code
stringlengths
1
1.72M
language
stringclasses
1 value
# Abstract classes. class Event(object): def __init__(self, start_mark=None, end_mark=None): self.start_mark = start_mark self.end_mark = end_mark def __repr__(self): attributes = [key for key in ['anchor', 'tag', 'implicit', 'value'] if hasattr(self, key)] arguments = ', '.join(['%s=%r' % (key, getattr(self, key)) for key in attributes]) return '%s(%s)' % (self.__class__.__name__, arguments) class NodeEvent(Event): def __init__(self, anchor, start_mark=None, end_mark=None): self.anchor = anchor self.start_mark = start_mark self.end_mark = end_mark class CollectionStartEvent(NodeEvent): def __init__(self, anchor, tag, implicit, start_mark=None, end_mark=None, flow_style=None): self.anchor = anchor self.tag = tag self.implicit = implicit self.start_mark = start_mark self.end_mark = end_mark self.flow_style = flow_style class CollectionEndEvent(Event): pass # Implementations. class StreamStartEvent(Event): def __init__(self, start_mark=None, end_mark=None, encoding=None): self.start_mark = start_mark self.end_mark = end_mark self.encoding = encoding class StreamEndEvent(Event): pass class DocumentStartEvent(Event): def __init__(self, start_mark=None, end_mark=None, explicit=None, version=None, tags=None): self.start_mark = start_mark self.end_mark = end_mark self.explicit = explicit self.version = version self.tags = tags class DocumentEndEvent(Event): def __init__(self, start_mark=None, end_mark=None, explicit=None): self.start_mark = start_mark self.end_mark = end_mark self.explicit = explicit class AliasEvent(NodeEvent): pass class ScalarEvent(NodeEvent): def __init__(self, anchor, tag, implicit, value, start_mark=None, end_mark=None, style=None): self.anchor = anchor self.tag = tag self.implicit = implicit self.value = value self.start_mark = start_mark self.end_mark = end_mark self.style = style class SequenceStartEvent(CollectionStartEvent): pass class SequenceEndEvent(CollectionEndEvent): pass class MappingStartEvent(CollectionStartEvent): pass class MappingEndEvent(CollectionEndEvent): pass
Python
__all__ = ['BaseConstructor', 'SafeConstructor', 'Constructor', 'ConstructorError'] from error import * from nodes import * import datetime try: set except NameError: from sets import Set as set import binascii, re, sys, types class ConstructorError(MarkedYAMLError): pass class BaseConstructor(object): yaml_constructors = {} yaml_multi_constructors = {} def __init__(self): self.constructed_objects = {} self.recursive_objects = {} self.state_generators = [] self.deep_construct = False def check_data(self): # If there are more documents available? return self.check_node() def get_data(self): # Construct and return the next document. if self.check_node(): return self.construct_document(self.get_node()) def get_single_data(self): # Ensure that the stream contains a single document and construct it. node = self.get_single_node() if node is not None: return self.construct_document(node) return None def construct_document(self, node): data = self.construct_object(node) while self.state_generators: state_generators = self.state_generators self.state_generators = [] for generator in state_generators: for dummy in generator: pass self.constructed_objects = {} self.recursive_objects = {} self.deep_construct = False return data def construct_object(self, node, deep=False): if deep: old_deep = self.deep_construct self.deep_construct = True if node in self.constructed_objects: return self.constructed_objects[node] if node in self.recursive_objects: raise ConstructorError(None, None, "found unconstructable recursive node", node.start_mark) self.recursive_objects[node] = None constructor = None state_constructor = None tag_suffix = None if node.tag in self.yaml_constructors: constructor = self.yaml_constructors[node.tag] else: for tag_prefix in self.yaml_multi_constructors: if node.tag.startswith(tag_prefix): tag_suffix = node.tag[len(tag_prefix):] constructor = self.yaml_multi_constructors[tag_prefix] break else: if None in self.yaml_multi_constructors: tag_suffix = node.tag constructor = self.yaml_multi_constructors[None] elif None in self.yaml_constructors: constructor = self.yaml_constructors[None] elif isinstance(node, ScalarNode): constructor = self.__class__.construct_scalar elif isinstance(node, SequenceNode): constructor = self.__class__.construct_sequence elif isinstance(node, MappingNode): constructor = self.__class__.construct_mapping if tag_suffix is None: data = constructor(self, node) else: data = constructor(self, tag_suffix, node) if isinstance(data, types.GeneratorType): generator = data data = generator.next() if self.deep_construct: for dummy in generator: pass else: self.state_generators.append(generator) self.constructed_objects[node] = data del self.recursive_objects[node] if deep: self.deep_construct = old_deep return data def construct_scalar(self, node): if not isinstance(node, ScalarNode): raise ConstructorError(None, None, "expected a scalar node, but found %s" % node.id, node.start_mark) return node.value def construct_sequence(self, node, deep=False): if not isinstance(node, SequenceNode): raise ConstructorError(None, None, "expected a sequence node, but found %s" % node.id, node.start_mark) return [self.construct_object(child, deep=deep) for child in node.value] def construct_mapping(self, node, deep=False): if not isinstance(node, MappingNode): raise ConstructorError(None, None, "expected a mapping node, but found %s" % node.id, node.start_mark) mapping = {} for key_node, value_node in node.value: key = self.construct_object(key_node, deep=deep) try: hash(key) except TypeError, exc: raise ConstructorError("while constructing a mapping", node.start_mark, "found unacceptable key (%s)" % exc, key_node.start_mark) value = self.construct_object(value_node, deep=deep) mapping[key] = value return mapping def construct_pairs(self, node, deep=False): if not isinstance(node, MappingNode): raise ConstructorError(None, None, "expected a mapping node, but found %s" % node.id, node.start_mark) pairs = [] for key_node, value_node in node.value: key = self.construct_object(key_node, deep=deep) value = self.construct_object(value_node, deep=deep) pairs.append((key, value)) return pairs def add_constructor(cls, tag, constructor): if not 'yaml_constructors' in cls.__dict__: cls.yaml_constructors = cls.yaml_constructors.copy() cls.yaml_constructors[tag] = constructor add_constructor = classmethod(add_constructor) def add_multi_constructor(cls, tag_prefix, multi_constructor): if not 'yaml_multi_constructors' in cls.__dict__: cls.yaml_multi_constructors = cls.yaml_multi_constructors.copy() cls.yaml_multi_constructors[tag_prefix] = multi_constructor add_multi_constructor = classmethod(add_multi_constructor) class SafeConstructor(BaseConstructor): def construct_scalar(self, node): if isinstance(node, MappingNode): for key_node, value_node in node.value: if key_node.tag == u'tag:yaml.org,2002:value': return self.construct_scalar(value_node) return BaseConstructor.construct_scalar(self, node) def flatten_mapping(self, node): merge = [] index = 0 while index < len(node.value): key_node, value_node = node.value[index] if key_node.tag == u'tag:yaml.org,2002:merge': del node.value[index] if isinstance(value_node, MappingNode): self.flatten_mapping(value_node) merge.extend(value_node.value) elif isinstance(value_node, SequenceNode): submerge = [] for subnode in value_node.value: if not isinstance(subnode, MappingNode): raise ConstructorError("while constructing a mapping", node.start_mark, "expected a mapping for merging, but found %s" % subnode.id, subnode.start_mark) self.flatten_mapping(subnode) submerge.append(subnode.value) submerge.reverse() for value in submerge: merge.extend(value) else: raise ConstructorError("while constructing a mapping", node.start_mark, "expected a mapping or list of mappings for merging, but found %s" % value_node.id, value_node.start_mark) elif key_node.tag == u'tag:yaml.org,2002:value': key_node.tag = u'tag:yaml.org,2002:str' index += 1 else: index += 1 if merge: node.value = merge + node.value def construct_mapping(self, node, deep=False): if isinstance(node, MappingNode): self.flatten_mapping(node) return BaseConstructor.construct_mapping(self, node, deep=deep) def construct_yaml_null(self, node): self.construct_scalar(node) return None bool_values = { u'yes': True, u'no': False, u'true': True, u'false': False, u'on': True, u'off': False, } def construct_yaml_bool(self, node): value = self.construct_scalar(node) return self.bool_values[value.lower()] def construct_yaml_int(self, node): value = str(self.construct_scalar(node)) value = value.replace('_', '') sign = +1 if value[0] == '-': sign = -1 if value[0] in '+-': value = value[1:] if value == '0': return 0 elif value.startswith('0b'): return sign*int(value[2:], 2) elif value.startswith('0x'): return sign*int(value[2:], 16) elif value[0] == '0': return sign*int(value, 8) elif ':' in value: digits = [int(part) for part in value.split(':')] digits.reverse() base = 1 value = 0 for digit in digits: value += digit*base base *= 60 return sign*value else: return sign*int(value) inf_value = 1e300 while inf_value != inf_value*inf_value: inf_value *= inf_value nan_value = -inf_value/inf_value # Trying to make a quiet NaN (like C99). def construct_yaml_float(self, node): value = str(self.construct_scalar(node)) value = value.replace('_', '').lower() sign = +1 if value[0] == '-': sign = -1 if value[0] in '+-': value = value[1:] if value == '.inf': return sign*self.inf_value elif value == '.nan': return self.nan_value elif ':' in value: digits = [float(part) for part in value.split(':')] digits.reverse() base = 1 value = 0.0 for digit in digits: value += digit*base base *= 60 return sign*value else: return sign*float(value) def construct_yaml_binary(self, node): value = self.construct_scalar(node) try: return str(value).decode('base64') except (binascii.Error, UnicodeEncodeError), exc: raise ConstructorError(None, None, "failed to decode base64 data: %s" % exc, node.start_mark) timestamp_regexp = re.compile( ur'''^(?P<year>[0-9][0-9][0-9][0-9]) -(?P<month>[0-9][0-9]?) -(?P<day>[0-9][0-9]?) (?:(?:[Tt]|[ \t]+) (?P<hour>[0-9][0-9]?) :(?P<minute>[0-9][0-9]) :(?P<second>[0-9][0-9]) (?:\.(?P<fraction>[0-9]*))? (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?) (?::(?P<tz_minute>[0-9][0-9]))?))?)?$''', re.X) def construct_yaml_timestamp(self, node): value = self.construct_scalar(node) match = self.timestamp_regexp.match(node.value) values = match.groupdict() year = int(values['year']) month = int(values['month']) day = int(values['day']) if not values['hour']: return datetime.date(year, month, day) hour = int(values['hour']) minute = int(values['minute']) second = int(values['second']) fraction = 0 if values['fraction']: fraction = values['fraction'][:6] while len(fraction) < 6: fraction += '0' fraction = int(fraction) delta = None if values['tz_sign']: tz_hour = int(values['tz_hour']) tz_minute = int(values['tz_minute'] or 0) delta = datetime.timedelta(hours=tz_hour, minutes=tz_minute) if values['tz_sign'] == '-': delta = -delta data = datetime.datetime(year, month, day, hour, minute, second, fraction) if delta: data -= delta return data def construct_yaml_omap(self, node): # Note: we do not check for duplicate keys, because it's too # CPU-expensive. omap = [] yield omap if not isinstance(node, SequenceNode): raise ConstructorError("while constructing an ordered map", node.start_mark, "expected a sequence, but found %s" % node.id, node.start_mark) for subnode in node.value: if not isinstance(subnode, MappingNode): raise ConstructorError("while constructing an ordered map", node.start_mark, "expected a mapping of length 1, but found %s" % subnode.id, subnode.start_mark) if len(subnode.value) != 1: raise ConstructorError("while constructing an ordered map", node.start_mark, "expected a single mapping item, but found %d items" % len(subnode.value), subnode.start_mark) key_node, value_node = subnode.value[0] key = self.construct_object(key_node) value = self.construct_object(value_node) omap.append((key, value)) def construct_yaml_pairs(self, node): # Note: the same code as `construct_yaml_omap`. pairs = [] yield pairs if not isinstance(node, SequenceNode): raise ConstructorError("while constructing pairs", node.start_mark, "expected a sequence, but found %s" % node.id, node.start_mark) for subnode in node.value: if not isinstance(subnode, MappingNode): raise ConstructorError("while constructing pairs", node.start_mark, "expected a mapping of length 1, but found %s" % subnode.id, subnode.start_mark) if len(subnode.value) != 1: raise ConstructorError("while constructing pairs", node.start_mark, "expected a single mapping item, but found %d items" % len(subnode.value), subnode.start_mark) key_node, value_node = subnode.value[0] key = self.construct_object(key_node) value = self.construct_object(value_node) pairs.append((key, value)) def construct_yaml_set(self, node): data = set() yield data value = self.construct_mapping(node) data.update(value) def construct_yaml_str(self, node): value = self.construct_scalar(node) try: return value.encode('ascii') except UnicodeEncodeError: return value def construct_yaml_seq(self, node): data = [] yield data data.extend(self.construct_sequence(node)) def construct_yaml_map(self, node): data = {} yield data value = self.construct_mapping(node) data.update(value) def construct_yaml_object(self, node, cls): data = cls.__new__(cls) yield data if hasattr(data, '__setstate__'): state = self.construct_mapping(node, deep=True) data.__setstate__(state) else: state = self.construct_mapping(node) data.__dict__.update(state) def construct_undefined(self, node): raise ConstructorError(None, None, "could not determine a constructor for the tag %r" % node.tag.encode('utf-8'), node.start_mark) SafeConstructor.add_constructor( u'tag:yaml.org,2002:null', SafeConstructor.construct_yaml_null) SafeConstructor.add_constructor( u'tag:yaml.org,2002:bool', SafeConstructor.construct_yaml_bool) SafeConstructor.add_constructor( u'tag:yaml.org,2002:int', SafeConstructor.construct_yaml_int) SafeConstructor.add_constructor( u'tag:yaml.org,2002:float', SafeConstructor.construct_yaml_float) SafeConstructor.add_constructor( u'tag:yaml.org,2002:binary', SafeConstructor.construct_yaml_binary) SafeConstructor.add_constructor( u'tag:yaml.org,2002:timestamp', SafeConstructor.construct_yaml_timestamp) SafeConstructor.add_constructor( u'tag:yaml.org,2002:omap', SafeConstructor.construct_yaml_omap) SafeConstructor.add_constructor( u'tag:yaml.org,2002:pairs', SafeConstructor.construct_yaml_pairs) SafeConstructor.add_constructor( u'tag:yaml.org,2002:set', SafeConstructor.construct_yaml_set) SafeConstructor.add_constructor( u'tag:yaml.org,2002:str', SafeConstructor.construct_yaml_str) SafeConstructor.add_constructor( u'tag:yaml.org,2002:seq', SafeConstructor.construct_yaml_seq) SafeConstructor.add_constructor( u'tag:yaml.org,2002:map', SafeConstructor.construct_yaml_map) SafeConstructor.add_constructor(None, SafeConstructor.construct_undefined) class Constructor(SafeConstructor): def construct_python_str(self, node): return self.construct_scalar(node).encode('utf-8') def construct_python_unicode(self, node): return self.construct_scalar(node) def construct_python_long(self, node): return long(self.construct_yaml_int(node)) def construct_python_complex(self, node): return complex(self.construct_scalar(node)) def construct_python_tuple(self, node): return tuple(self.construct_sequence(node)) def find_python_module(self, name, mark): if not name: raise ConstructorError("while constructing a Python module", mark, "expected non-empty name appended to the tag", mark) try: __import__(name) except ImportError, exc: raise ConstructorError("while constructing a Python module", mark, "cannot find module %r (%s)" % (name.encode('utf-8'), exc), mark) return sys.modules[name] def find_python_name(self, name, mark): if not name: raise ConstructorError("while constructing a Python object", mark, "expected non-empty name appended to the tag", mark) if u'.' in name: # Python 2.4 only #module_name, object_name = name.rsplit('.', 1) items = name.split('.') object_name = items.pop() module_name = '.'.join(items) else: module_name = '__builtin__' object_name = name try: __import__(module_name) except ImportError, exc: raise ConstructorError("while constructing a Python object", mark, "cannot find module %r (%s)" % (module_name.encode('utf-8'), exc), mark) module = sys.modules[module_name] if not hasattr(module, object_name): raise ConstructorError("while constructing a Python object", mark, "cannot find %r in the module %r" % (object_name.encode('utf-8'), module.__name__), mark) return getattr(module, object_name) def construct_python_name(self, suffix, node): value = self.construct_scalar(node) if value: raise ConstructorError("while constructing a Python name", node.start_mark, "expected the empty value, but found %r" % value.encode('utf-8'), node.start_mark) return self.find_python_name(suffix, node.start_mark) def construct_python_module(self, suffix, node): value = self.construct_scalar(node) if value: raise ConstructorError("while constructing a Python module", node.start_mark, "expected the empty value, but found %r" % value.encode('utf-8'), node.start_mark) return self.find_python_module(suffix, node.start_mark) class classobj: pass def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False): if not args: args = [] if not kwds: kwds = {} cls = self.find_python_name(suffix, node.start_mark) if newobj and isinstance(cls, type(self.classobj)) \ and not args and not kwds: instance = self.classobj() instance.__class__ = cls return instance elif newobj and isinstance(cls, type): return cls.__new__(cls, *args, **kwds) else: return cls(*args, **kwds) def set_python_instance_state(self, instance, state): if hasattr(instance, '__setstate__'): instance.__setstate__(state) else: slotstate = {} if isinstance(state, tuple) and len(state) == 2: state, slotstate = state if hasattr(instance, '__dict__'): instance.__dict__.update(state) elif state: slotstate.update(state) for key, value in slotstate.items(): setattr(object, key, value) def construct_python_object(self, suffix, node): # Format: # !!python/object:module.name { ... state ... } instance = self.make_python_instance(suffix, node, newobj=True) yield instance deep = hasattr(instance, '__setstate__') state = self.construct_mapping(node, deep=deep) self.set_python_instance_state(instance, state) def construct_python_object_apply(self, suffix, node, newobj=False): # Format: # !!python/object/apply # (or !!python/object/new) # args: [ ... arguments ... ] # kwds: { ... keywords ... } # state: ... state ... # listitems: [ ... listitems ... ] # dictitems: { ... dictitems ... } # or short format: # !!python/object/apply [ ... arguments ... ] # The difference between !!python/object/apply and !!python/object/new # is how an object is created, check make_python_instance for details. if isinstance(node, SequenceNode): args = self.construct_sequence(node, deep=True) kwds = {} state = {} listitems = [] dictitems = {} else: value = self.construct_mapping(node, deep=True) args = value.get('args', []) kwds = value.get('kwds', {}) state = value.get('state', {}) listitems = value.get('listitems', []) dictitems = value.get('dictitems', {}) instance = self.make_python_instance(suffix, node, args, kwds, newobj) if state: self.set_python_instance_state(instance, state) if listitems: instance.extend(listitems) if dictitems: for key in dictitems: instance[key] = dictitems[key] return instance def construct_python_object_new(self, suffix, node): return self.construct_python_object_apply(suffix, node, newobj=True) Constructor.add_constructor( u'tag:yaml.org,2002:python/none', Constructor.construct_yaml_null) Constructor.add_constructor( u'tag:yaml.org,2002:python/bool', Constructor.construct_yaml_bool) Constructor.add_constructor( u'tag:yaml.org,2002:python/str', Constructor.construct_python_str) Constructor.add_constructor( u'tag:yaml.org,2002:python/unicode', Constructor.construct_python_unicode) Constructor.add_constructor( u'tag:yaml.org,2002:python/int', Constructor.construct_yaml_int) Constructor.add_constructor( u'tag:yaml.org,2002:python/long', Constructor.construct_python_long) Constructor.add_constructor( u'tag:yaml.org,2002:python/float', Constructor.construct_yaml_float) Constructor.add_constructor( u'tag:yaml.org,2002:python/complex', Constructor.construct_python_complex) Constructor.add_constructor( u'tag:yaml.org,2002:python/list', Constructor.construct_yaml_seq) Constructor.add_constructor( u'tag:yaml.org,2002:python/tuple', Constructor.construct_python_tuple) Constructor.add_constructor( u'tag:yaml.org,2002:python/dict', Constructor.construct_yaml_map) Constructor.add_multi_constructor( u'tag:yaml.org,2002:python/name:', Constructor.construct_python_name) Constructor.add_multi_constructor( u'tag:yaml.org,2002:python/module:', Constructor.construct_python_module) Constructor.add_multi_constructor( u'tag:yaml.org,2002:python/object:', Constructor.construct_python_object) Constructor.add_multi_constructor( u'tag:yaml.org,2002:python/object/apply:', Constructor.construct_python_object_apply) Constructor.add_multi_constructor( u'tag:yaml.org,2002:python/object/new:', Constructor.construct_python_object_new)
Python
#!/usr/bin/env python # # Open-source benchmarking suite. Similar to SPEC CPU. # (c) 2008 Thomas Stromberg <thomas%stromberg.org> # # $Id: benchmark.py 771 2008-11-26 03:32:22Z thomas $ import urllib import os import random import re import shutil import time import os.path import subprocess import datetime from optparse import OptionParser # local import builder import util import yaml import sysinfo import version class FreeBench(object): def __init__(self): self.current_thread = 0 self.run_tests = [] self.run_suites = [] self.num_attempts = None self.compile_only = False self.sysinfo = sysinfo.SysInfo() self.num_threads = self.sysinfo.ProcessorCount() self.base_dir = os.getcwd() self.data_dir = os.getcwd() + '/data' self.testbase_dir = os.getcwd() + '/test' self.LoadConfiguration() def LoadConfiguration(self): """Loads configuration data. Side Effects: Populates self.tests, self.test_suites, self.recipes """ self.tests = yaml.load(open('tests.yml').read()) self.test_suites = yaml.load(open('testsuites.yml').read()) def Run(self): """Generic Run wrapper.""" queue = set() if not self.num_attempts: util.msg("NOTE: Running in quick mode. Use freebench -a3 for official results.") self.num_attempts = 1 if self.run_tests: name = 'custom' queue.update(self.run_tests) if self.run_suites: name = '+'.join(self.run_suites) for suite in self.run_suites: queue.update(self.test_suites[suite]) if not self.compile_only: build = builder.Builder(base_dir=self.base_dir) build.FetchPrecompiledBinaries() util.msg("Running '%s' test suite with %s tests" % (name, len(queue))) results = [] for test_name in queue: if test_name not in self.tests: util.msg('Could not find a test named %s, skipping' % test_name) break best_score = 0 adjusted_score = 0 test = self.tests[test_name] test_results = self.RunTest(test_name) scores = [ x[0] for x in test_results if x ] if scores: if 'score_parse' in test: best_score = max(scores) else: best_score = min(scores) else: best_score = None adjusted_score = None if best_score and 'base_score' in test: if 'score_parse' in test: adjusted_score = (float(best_score / test['base_score'])) * 100 else: adjusted_score = (float(test['base_score']) / best_score) * 100 else: adjusted_score = 0 results.append((test_name, adjusted_score, best_score, test_results)) self.DisplayConfiguration() self.DisplayResults(name, results) return results def DisplayConfiguration(self): si = self.sysinfo distro = si.DistroName() build = builder.Builder() kern = si.KernelName() print if distro == kern: print "%% FreeBench %s - %s %s %s %s" % (version.VERSION, si.DistroName(), si.DistroVersion(), si.Architecture(), build.CompilerBanner()) else: print "%% FreeBench %s - %s %s (%s %s %s)" % (version.VERSION, si.DistroName(), si.DistroVersion(), kern, si.Architecture(), si.KernelVersion()) print "%% %s" % build.CompilerBanner() print "%% %s x %sMHz (%s), %sM RAM, %s" % (si.ProcessorCount(), si.ProcessorSpeedInMhz(), si.ProcessorType(), si.RamInMegabytes(), si.FilesystemType()) print "%% %s %s" % (build.compiler, build.cflags) def DisplayResults(self, suite_name, results): total_score = 0 total_best_duration = datetime.timedelta() total_adjusted_score = 0 failures = 0 attempts = 0 adjusted_scores = [] test_variations = [] print '\n%-18.18s| %6.6s | %-9.9s| %-12.12s | %-6.6s| %s' % (suite_name, 'score (adjusted)', 'best raw', 'best durat.', 'vari.', 'raw scores') print '-' * 80 for (test, adjusted_score, best_score, test_data) in results: scores = [ x[0] for x in test_data if x and x[0] ] durations = [ x[1] for x in test_data if x and x[1] ] threads = [ x[2] for x in test_data if x and x[2] ] attempts = len(test_data) printed_score = 'N/A' if best_score: total_score += best_score else: best_score = 0.0 if adjusted_score: adjusted_scores.append(adjusted_score) printed_score = '%5.2f' % adjusted_score if scores: variation = ((max(scores) / min(scores)) * 100) - 100 else: variation = 0 test_variations.append(variation) if durations: best_duration = min(durations) else: best_duration = datetime.timedelta(seconds=0) total_best_duration = total_best_duration + best_duration print_scores = [ '%2.2f' % x for x in scores ] print '%-18.18s| %-6.6s | %-9.3f| %-12.12s |%5.2f%% | %s' % (test, printed_score, best_score, best_duration, variation, ', '.join(print_scores)) if total_score: if adjusted_scores: total_adjusted_score = util.avg(adjusted_scores) print '-' * 80 avg_variation = util.avg(test_variations) print '%-18.18s| %-6.2f | %-9.9s| %-12.12s |%5.2f%% |' % ('TOTAL', total_adjusted_score, total_score, total_best_duration, avg_variation) print '-' * 80 if total_adjusted_score: ref = "MacBook Pro (Intel Core 2 Duo 2.33GHz)" util.msg("This host is %2.2fX as fast as a %s" % ((total_adjusted_score / 100), ref)) print if attempts == 1: util.msg("NOTE: Depending on your machine, there may be ~5% variance between test runs.") util.msg(" For better results, use -n3 to the best score of 3 runs") def _ExpandMacros(self, string): for macro in ('DATA_DIR', 'TEST_DIR', 'NUM_THREADS', 'CURRENT_THREAD', 'RANDOM_PORT', 'INPUT_FILE', 'INSTALL_DIR'): if macro in string: string = string.replace(macro, str(getattr(self, macro.lower()))) return string def BackgroundExec(self, raw_command): """Execute a command in the background, expanding any macros.""" command = self._ExpandMacros(raw_command) proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) util.debug(" > %s: '%s'" % (proc.pid, command)) return proc def RunTest(self, test_name): """Wrapper to build and find binaries, reserve ports, handle multiple runs.""" results = [] test = self.tests[test_name] recipe_name = test_name.split('.')[0] build = builder.Builder(base_dir=self.base_dir) try: (install_dir, bin_path) = build.BuildRecipe(recipe_name) except ValueError, e: util.msg("[FAIL] %s" % e) return ((None, None, None)) self.install_dir = install_dir util.set_library_path(self.install_dir + '/lib') self.test_dir = self.testbase_dir + '/' + test_name util.mkdir_p(self.test_dir) dir = self._ExpandMacros(test.get('chdir', self.test_dir)) util.debug("Changing to test directory: %s" % dir) util.chdir(dir) for attempt in range(self.num_attempts): self.random_port = int(random.uniform(16000,32000)) daemon = None try: daemon = self._PrepareTest(test_name) except ValueError, e: util.msg('Could not prepare %s: %s (pwd=%s)' % (test_name, e, os.getcwd())) results.append(None) break util.debug("Changing to test directory (just in case): %s" % dir) util.chdir(dir) (score, delta, threads) = self.ExecuteTest(test_name, bin_path, attempt_num=attempt+1) # sleep for sanity. if score: time.sleep(3) if daemon: exited = os.waitpid(daemon.pid, os.WNOHANG) if exited[0]: util.msg('daemon appears to not be running: out=%s err=%s' % (daemon.stderr.readlines(), daemon.stdout.readlines())) results.append((None, delta, threads)) break else: os.kill(daemon.pid, 15) time.sleep(1) try: os.kill(daemon.pid, 9) except OSError: pass daemon.wait() util.debug('daemon stdout: %s' % daemon.stdout.readlines()) util.debug('daemon stderr: %s' % daemon.stderr.readlines()) results.append((score, delta, threads)) return results def _PrepareTest(self, test_name): """Creates input files and runs any pre-commands or daemons for a test.""" test = self.tests[test_name] # For a more accurate workload, copy our input file once per thread. if 'input_file' in test: input_file = self._ExpandMacros(test['input_file']) num_threads = test.get('threads', self.num_threads) for thread in range(num_threads): output_file = '%s/%s.%s' % (self.test_dir, os.path.basename(input_file), thread) shutil.copyfile(input_file, output_file) if 'pre-command' in test: code = self.BackgroundExec(test['pre-command']) if code: raise ValueError("'%s' exited with code %s" % (test['pre-command'], code)) if 'daemon' in test: return self.BackgroundExec(test['daemon']) def ExecuteTest(self, test_name, bin_path, attempt_num=None): """Executes a test against a particular binary file. Handles multi-core runs.""" test = self.tests[test_name] procs = [] failed = False num_threads = test.get('threads', self.num_threads) command = re.sub('^\w+', bin_path, test['command']) util.msg(" Starting '%s' with %s threads (run %s of %s)" % (test_name, num_threads, attempt_num, self.num_attempts)) input_base = self.test_dir + '/' + os.path.basename(test.get('input_file', 'NULL')) + '.' start_ts = datetime.datetime.now() for thread in range(num_threads): self.current_thread = thread self.input_file = input_base + str(thread) procs.append(self.BackgroundExec(command)) for proc in procs: exitcode = proc.wait() if exitcode and exitcode != test.get('exitcode', 0): failed = True util.msg("'%s' exited with %s" % (command, exitcode)) util.msg('stdout: %s' % proc.stdout.readlines()) util.msg('stderr: %s' % proc.stderr.readlines()) end_ts = datetime.datetime.now() delta = end_ts - start_ts # We return here because we want to reap our children first. if failed: return (None, delta, num_threads) elif 'score_parse' in test: score = 0 for proc in procs: output = proc.stdout.readlines() match = re.search(test['score_parse'], ''.join(output), re.MULTILINE) if match: util.debug("Found score match: %s" % match.groups()) score = score + float(match.groups()[0]) else: util.msg('Failed to match %s in output: %s' % (test['score_parse'], output)) return None else: score = util.delta_seconds(delta) / num_threads return (score, delta, num_threads) if __name__ == "__main__": print "* Freebench %s - $Rev: 43 $" % version.VERSION parser = OptionParser() parser.add_option("-s", "--suite", dest="suite", help="test suite to run") parser.add_option("-c", "--compile", dest="compile_only", action="store_true", help="compile all dependencies (do not use packages)") parser.add_option("-a", "--number_of_attempts", dest="num_attempts", help="# of attempts to run (default 3)") parser.add_option("-v", "--verbose", dest="verbose", action="store_true", help="Turn on verbose mode") parser.add_option("-n", "--num_threads", dest="num_threads", help="number of threads (autodetect)") parser.add_option("-t", "--test", dest="test", help="test package to run") (options, args) = parser.parse_args() fb = FreeBench() if options.num_attempts: fb.num_attempts = int(options.num_attempts) if options.compile_only: fb.compile_only = True if options.num_threads: fb.num_threads = int(options.num_threads) if options.verbose: VERBOSE = True if options.suite: fb.run_suites = [options.suite] elif options.test: fb.run_tests = [options.test] else: fb.run_suites=['standard'] fb.Run()
Python
# FreeBench tool building library # (c) 2008 Thomas Stromberg <thomas%stromberg.org> import sys import datetime import os # This needs to be made tunable again. VERBOSE = os.getenv('VERBOSE', False) def debug(string): if VERBOSE: print ': %s' % string def msg(string): print "- %s" % string sys.stdout.flush() def avg(sequence): return float(sum(sequence)) / float(len(sequence)) def chdir(dir): debug("-> %s" % dir) os.chdir(dir) def mkdir_p(dir): try: debug('mkdir %s' % dir) os.makedirs(dir) except OSError: pass def delta_seconds(delta): if isinstance(delta, datetime.timedelta): return float(delta.days * 86400) + float(delta.seconds) + (float(delta.microseconds) / 1000000) else: return None def set_library_path(path): ostype = os.uname()[0] if ostype == 'AIX': var = 'LIBPATH' elif ostype == 'HP-UX': var = 'SHLIB_PATH' elif ostype == 'Darwin': var = 'DYLD_LIBRARY_PATH' else: var = 'LD_LIBRARY_PATH' debug('Set %s=%s' % (var, path)) os.putenv(var, path)
Python
#!/usr/bin/env python # sysinfo, return hardware/OS information for the current machine. # # TODO(thomas): Use platform library for as muchh as possible here. import os import platform import re import sys def execute(command): return os.popen(command).read().strip() class SysInfo(object): def __init__(self): self.os = self.KernelName() self.os_ver = self.KernelVersion() self.distro = self.DistroName() self.mount_dev = self.MountDevice() def Architecture(self): return platform.machine() def KernelName(self): return platform.system() def KernelVersion(self): return platform.uname()[2] def KernelMajorVersion(self): if self.os in ('Linux', 'SunOS'): return '.'.join(self.os_ver.split('.')[:2]) else: return self.os_ver.split('.')[0] def KernelBuild(self): return execute("uname -v | sed s/'\@[a-z0-9\.]*'/@/g") def Bits(self): return platform.architecture()[0] def SystemModel(self): if self.distro == 'Solaris': return execute('/usr/sbin/prtdiag | grep "^System Configuration" | cut -d" " -f3-10') elif self.distro == 'Mac OS X': return execute("/usr/sbin/system_profiler SPHardwareDataType | grep 'Model Name' | cut -c19-80") elif self.os == 'HP-UX': return execute('model') elif self.os == 'AIX': return execute('uname -M') else: return 'Unknown' def Platform(self): tags = [self.os, self.KernelMajorVersion(), self.Architecture(), self.Bits()] if platform.libc_ver()[0]: tags.extend(platform.libc_ver()) return '-'.join(tags) def L2CacheInKb(self): if self.distro == 'Mac OS X': return int(execute('/usr/sbin/system_profiler SPHardwareDataType | grep "L2 Cache" | cut -d" " -f9')) * 1024 elif self.os == 'Linux': return int(execute("grep 'cache size' /proc/cpuinfo | awk '{ print $4 }' | head -1")) else: return 'Unknown' def DistroName(self): if os.path.exists('/usr/sbin/sw_vers') or os.path.exists('/usr/sbin/system_profiler'): return 'Mac OS X' elif self.os == 'SunOS': minor = self.os_ver.split('.')[1] if minor > 5: return 'Solaris' elif os.path.exists('/usr/bin/lsb_release'): return execute('lsb_release -i -s') elif os.path.exists('/etc/release'): return execute('cat /etc/release') else: (distname, version, id) = platform.dist() if distname: return distname else: return self.os def DistroVersion(self): if self.distro == 'Mac OS X': return platform.mac_ver()[0] elif os.path.exists('/usr/bin/lsb_release'): return execute('lsb_release -r -s') elif self.os in ('IRIX', 'IRIX64'): return execute("uname -R | cut -d' ' -f2`") elif self.os == 'AIX': return execute('oslevel') else: (distname, version, id) = platform.dist() if version: return version else: return self.os_ver def RamInMegabytes(self): if self.os == 'Darwin': return int(execute('/usr/sbin/sysctl -n hw.memsize')) / 1024 / 1024 elif self.distro == 'Solaris': return execute('/usr/sbin/prtconf | grep "Memory size" | cut -d" " -f3') elif self.os == 'HP-UX': # this is horrible. return int(execute('grep Physical /var/adm/syslog/syslog.log | tail -1 | cut -d: -f5 | cut -d" " -f2')) / 1024 elif self.os in ('FreeBSD', 'OpenBSD', 'DragonFly'): return int(execute('/sbin/sysctl -n hw.physmem')) / 1024 / 1024 elif self.os == 'NetBSD': return int(execute('grep "^total memory" /var/run/dmesg.boot| head -1 | cut -d" " -f4')) elif self.os == 'Linux': return int(execute("grep '^MemTotal' /proc/meminfo | awk '{ print $2 }'")) / 1024 elif self.os in ('IRIX', 'IRIX64'): return int(execute('hinv -c memory | grep "^Main memory" | cut -d" " -f4')) else: return 0 def ProcessorSpeedInMhz(self): if self.distro == 'Solaris': return execute('/usr/sbin/psrinfo -v | grep "operates at" | head -1 | cut -d" " -f8') elif self.os == 'Darwin': return int(execute('/usr/sbin/sysctl -n hw.cpufrequency')) / 1000 / 1000 elif self.os == 'FreeBSD': return int(execute('/sbin/sysctl -n hw.clockrate')) elif self.os in ('DragonFly', 'OpenBSD', 'NetBSD'): return int(execute('/sbin/sysctl -n kern.ccpu')) elif self.os in ('IRIX', 'IRIX64'): return int(execute('hinv -c processor | grep MHZ | cut -d" " -f2')) elif self.os == 'AIX': return int(execute('lsattr -E -l proc0 | grep "^frequency" | cut -d" " -f2')) / 1024 elif self.os == 'Linux': return int(float(execute("grep 'cpu MHz' /proc/cpuinfo | awk '{ print $4 }' | head -1"))) else: return 0 def ProcessorCount(self): if self.os == 'Darwin': return int(execute('/usr/sbin/sysctl -n hw.ncpu')) if self.os in ('FreeBSD', 'OpenBSD', 'DragonFly', 'NetBSD'): return int(execute('/sbin/sysctl -n hw.ncpu')) elif self.distro == 'Solaris': return int(execute("/usr/sbin/psrinfo | wc -l | awk '{ print $1}'`")) elif self.os == 'Linux': return int(execute('grep "^processor" /proc/cpuinfo | wc -l')) elif self.os in ('IRIX', 'IRIX64'): return int(execute('hinv -c processor | grep MHZ | cut -d" " -f1')) elif self.os == 'AIX': return int(execute('lscfg -l proc\* | grep -c Processor')) elif self.os == 'HP-UX': # cry. topfile = '/tmp/top.%s' % os.getpid() os.system('top -s1 -n1 -u -f %s' % topfile) nprocs = int(execute('egrep "[0-9] .*%%" %s | grep -vc avg' % topfile)) os.unlink(topfile) return nprocs else: return 0 def ProcessorType(self): proc = 'Unknown' if self.os == 'Darwin': proc = execute('/usr/sbin/sysctl -n machdep.cpu.brand_string') elif self.os in ('FreeBSD', 'OpenBSD', 'DragonFly', 'NetBSD'): proc = execute('/sbin/sysctl -n hw.model') elif self.os in ('IRIX', 'IRIX64'): return execute('hinv -c processor | grep "^CPU" | cut -d" " -f2-3') elif self.os == 'Linux': proc = execute('egrep "^family|^model name" /proc/cpuinfo | head -1 | cut -c14-90') # TODO(tstromberg): munge proc here proc = proc.replace('(R)', '') proc = proc.replace('(TM)', '') proc = proc.replace(' CPU', '') return re.sub(' +', ' ', proc) def BusSpeedInMHz(self): if self.distro == 'Mac OS X': return int(float(execute('/usr/sbin/system_profiler SPHardwareDataType | grep "Bus Speed" | cut -d" " -f9')) * 1000) else: return 'Unknown' def MountDevice(self): return execute("df . | grep '/dev' | awk '{ print $1 }'") def DiskId(self): match = re.match('.*\/([a-z]+\d+)', self.mount_dev) if match: return match.groups()[0] else: return 'Unknown' def VolumeType(self): disk_id = self.DiskId() if os.path.exists('/var/run/dmesg.boot'): return execute("grep '^%s:' /var/run/dmesg.boot | cut -d' ' -f2-50" % disk_id) elif self.distro == 'Mac OS X': is_raid = execute('diskutil listRAID | grep %s' % disk_id) if is_raid: # not necessarily mapped to thisk disk! raid_type = execute("diskutil listRAID | grep '^Type:' | awk '{ print $2 }'") disk_count = execute("diskutil listRAID | grep 'disk.*Online' | wc -l | awk '{ print $1 }'") return '%s-disk %s RAID' % (disk_count, raid_type) elif self.os == 'Linux' and 'VolGroup' in disk_id: return 'LVM' else: return 'Unknown' def FilesystemType(self): disk = self.mount_dev mount = execute('mount | grep "%s"' % disk) if 'type' in mount: match = re.search(' type (.*)', mount) if match: options = match.groups()[0] return re.sub(',errors=[\w-]+', '', options) bsd = execute('mount | grep "%s" | cut -d\( -f2 | cut -d\) -f1' % disk) if bsd: return bsd if __name__ == "__main__": si = SysInfo() if len(sys.argv) > 1: bound_method = getattr(si, sys.argv[1]) print bound_method() else: for method in dir(si): if '_' not in method: try: bound_method = getattr(si, method) print '%-20.20s: %s' % (method, bound_method()) except: print '%-20.20s: FAILED' % method
Python
VERSION='0.5'
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import unittest import util class AnimMeshTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] self.__abcStitcherExe = os.environ['AbcStitcher'] + ' ' def tearDown(self): for f in self.__files : os.remove(f) def testAnimPolyReadWrite(self): numFaces = 6 numVertices = 8 numFaceConnects = 24 vtx_1 = OpenMaya.MFloatPoint(-0.5, -0.5, -0.5) vtx_2 = OpenMaya.MFloatPoint( 0.5, -0.5, -0.5) vtx_3 = OpenMaya.MFloatPoint( 0.5, -0.5, 0.5) vtx_4 = OpenMaya.MFloatPoint(-0.5, -0.5, 0.5) vtx_5 = OpenMaya.MFloatPoint(-0.5, 0.5, -0.5) vtx_6 = OpenMaya.MFloatPoint(-0.5, 0.5, 0.5) vtx_7 = OpenMaya.MFloatPoint( 0.5, 0.5, 0.5) vtx_8 = OpenMaya.MFloatPoint( 0.5, 0.5, -0.5) points = OpenMaya.MFloatPointArray() points.setLength(8) points.set(vtx_1, 0) points.set(vtx_2, 1) points.set(vtx_3, 2) points.set(vtx_4, 3) points.set(vtx_5, 4) points.set(vtx_6, 5) points.set(vtx_7, 6) points.set(vtx_8, 7) faceConnects = OpenMaya.MIntArray() faceConnects.setLength(numFaceConnects) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) faceConnects.set(4, 4) faceConnects.set(5, 5) faceConnects.set(6, 6) faceConnects.set(7, 7) faceConnects.set(3, 8) faceConnects.set(2, 9) faceConnects.set(6, 10) faceConnects.set(5, 11) faceConnects.set(0, 12) faceConnects.set(3, 13) faceConnects.set(5, 14) faceConnects.set(4, 15) faceConnects.set(0, 16) faceConnects.set(4, 17) faceConnects.set(7, 18) faceConnects.set(1, 19) faceConnects.set(1, 20) faceConnects.set(7, 21) faceConnects.set(6, 22) faceConnects.set(2, 23) faceCounts = OpenMaya.MIntArray() faceCounts.setLength(6) faceCounts.set(4, 0) faceCounts.set(4, 1) faceCounts.set(4, 2) faceCounts.set(4, 3) faceCounts.set(4, 4) faceCounts.set(4, 5) transFn = OpenMaya.MFnTransform() parent = transFn.create() transFn.setName('poly') meshFn = OpenMaya.MFnMesh() meshFn.create(numVertices, numFaces, points, faceCounts, faceConnects, parent) meshFn.setName("polyShape"); MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe('polyShape.vtx[0:7]') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe('polyShape.vtx[0:7]') MayaCmds.currentTime(12, update=True) vtx_11 = OpenMaya.MFloatPoint(-1, -1, -1) vtx_22 = OpenMaya.MFloatPoint( 1, -1, -1) vtx_33 = OpenMaya.MFloatPoint( 1, -1, 1) vtx_44 = OpenMaya.MFloatPoint(-1, -1, 1) vtx_55 = OpenMaya.MFloatPoint(-1, 1, -1) vtx_66 = OpenMaya.MFloatPoint(-1, 1, 1) vtx_77 = OpenMaya.MFloatPoint( 1, 1, 1) vtx_88 = OpenMaya.MFloatPoint( 1, 1, -1) points.set(vtx_11, 0) points.set(vtx_22, 1) points.set(vtx_33, 2) points.set(vtx_44, 3) points.set(vtx_55, 4) points.set(vtx_66, 5) points.set(vtx_77, 6) points.set(vtx_88, 7) meshFn.setPoints(points) MayaCmds.setKeyframe('polyShape.vtx[0:7]') self.__files.append(util.expandFileName('animPoly.abc')) self.__files.append(util.expandFileName('animPoly01_14.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root poly -file ' + self.__files[-1]) self.__files.append(util.expandFileName('animPoly15_24.abc')) MayaCmds.AbcExport(j='-fr 15 24 -root poly -file ' + self.__files[-1]) # use AbcStitcher to combine two files into one os.system(self.__abcStitcherExe + ' '.join(self.__files[-3:])) # reading test MayaCmds.AbcImport(self.__files[-3], mode='open') MayaCmds.currentTime(1, update=True) sList = OpenMaya.MSelectionList(); sList.add('polyShape'); meshObj = OpenMaya.MObject(); sList.getDependNode(0, meshObj); meshFn = OpenMaya.MFnMesh(meshObj) # check the point list meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_1, meshPoints[0]) self.failUnlessEqual(vtx_2, meshPoints[1]) self.failUnlessEqual(vtx_3, meshPoints[2]) self.failUnlessEqual(vtx_4, meshPoints[3]) self.failUnlessEqual(vtx_5, meshPoints[4]) self.failUnlessEqual(vtx_6, meshPoints[5]) self.failUnlessEqual(vtx_7, meshPoints[6]) self.failUnlessEqual(vtx_8, meshPoints[7]) # check the polygonvertices list vertexList = OpenMaya.MIntArray() faceConnects = OpenMaya.MIntArray() faceConnects.setLength(4) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) meshFn.getPolygonVertices(0, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(4, 0) faceConnects.set(5, 1) faceConnects.set(6, 2) faceConnects.set(7, 3) meshFn.getPolygonVertices(1, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(3, 0) faceConnects.set(2, 1) faceConnects.set(6, 2) faceConnects.set(5, 3) meshFn.getPolygonVertices(2, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(3, 1) faceConnects.set(5, 2) faceConnects.set(4, 3) meshFn.getPolygonVertices(3, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(4, 1) faceConnects.set(7, 2) faceConnects.set(1, 3) meshFn.getPolygonVertices(4, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(1, 0) faceConnects.set(7, 1) faceConnects.set(6, 2) faceConnects.set(2, 3) meshFn.getPolygonVertices(5, vertexList) self.failUnlessEqual(faceConnects, vertexList) MayaCmds.currentTime(12, update=True) meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_11, meshPoints[0]) self.failUnlessEqual(vtx_22, meshPoints[1]) self.failUnlessEqual(vtx_33, meshPoints[2]) self.failUnlessEqual(vtx_44, meshPoints[3]) self.failUnlessEqual(vtx_55, meshPoints[4]) self.failUnlessEqual(vtx_66, meshPoints[5]) self.failUnlessEqual(vtx_77, meshPoints[6]) self.failUnlessEqual(vtx_88, meshPoints[7]) MayaCmds.currentTime(24, update=True) meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_1, meshPoints[0]) self.failUnlessEqual(vtx_2, meshPoints[1]) self.failUnlessEqual(vtx_3, meshPoints[2]) self.failUnlessEqual(vtx_4, meshPoints[3]) self.failUnlessEqual(vtx_5, meshPoints[4]) self.failUnlessEqual(vtx_6, meshPoints[5]) self.failUnlessEqual(vtx_7, meshPoints[6]) self.failUnlessEqual(vtx_8, meshPoints[7]) def testAnimSubDReadWrite(self): numFaces = 6 numVertices = 8 numFaceConnects = 24 vtx_1 = OpenMaya.MFloatPoint(-0.5, -0.5, -0.5) vtx_2 = OpenMaya.MFloatPoint( 0.5, -0.5, -0.5) vtx_3 = OpenMaya.MFloatPoint( 0.5, -0.5, 0.5) vtx_4 = OpenMaya.MFloatPoint(-0.5, -0.5, 0.5) vtx_5 = OpenMaya.MFloatPoint(-0.5, 0.5, -0.5) vtx_6 = OpenMaya.MFloatPoint(-0.5, 0.5, 0.5) vtx_7 = OpenMaya.MFloatPoint( 0.5, 0.5, 0.5) vtx_8 = OpenMaya.MFloatPoint( 0.5, 0.5, -0.5) points = OpenMaya.MFloatPointArray() points.setLength(8) points.set(vtx_1, 0) points.set(vtx_2, 1) points.set(vtx_3, 2) points.set(vtx_4, 3) points.set(vtx_5, 4) points.set(vtx_6, 5) points.set(vtx_7, 6) points.set(vtx_8, 7) faceConnects = OpenMaya.MIntArray() faceConnects.setLength(numFaceConnects) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) faceConnects.set(4, 4) faceConnects.set(5, 5) faceConnects.set(6, 6) faceConnects.set(7, 7) faceConnects.set(3, 8) faceConnects.set(2, 9) faceConnects.set(6, 10) faceConnects.set(5, 11) faceConnects.set(0, 12) faceConnects.set(3, 13) faceConnects.set(5, 14) faceConnects.set(4, 15) faceConnects.set(0, 16) faceConnects.set(4, 17) faceConnects.set(7, 18) faceConnects.set(1, 19) faceConnects.set(1, 20) faceConnects.set(7, 21) faceConnects.set(6, 22) faceConnects.set(2, 23) faceCounts = OpenMaya.MIntArray() faceCounts.setLength(6) faceCounts.set(4, 0) faceCounts.set(4, 1) faceCounts.set(4, 2) faceCounts.set(4, 3) faceCounts.set(4, 4) faceCounts.set(4, 5) transFn = OpenMaya.MFnTransform() parent = transFn.create() transFn.setName('subD') meshFn = OpenMaya.MFnMesh() meshFn.create(numVertices, numFaces, points, faceCounts, faceConnects, parent) meshFn.setName("subDShape"); MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe('subDShape.vtx[0:7]') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe('subDShape.vtx[0:7]') MayaCmds.currentTime(12, update=True) vtx_11 = OpenMaya.MFloatPoint(-1, -1, -1) vtx_22 = OpenMaya.MFloatPoint( 1, -1, -1) vtx_33 = OpenMaya.MFloatPoint( 1, -1, 1) vtx_44 = OpenMaya.MFloatPoint(-1, -1, 1) vtx_55 = OpenMaya.MFloatPoint(-1, 1, -1) vtx_66 = OpenMaya.MFloatPoint(-1, 1, 1) vtx_77 = OpenMaya.MFloatPoint( 1, 1, 1) vtx_88 = OpenMaya.MFloatPoint( 1, 1, -1) points.set(vtx_11, 0) points.set(vtx_22, 1) points.set(vtx_33, 2) points.set(vtx_44, 3) points.set(vtx_55, 4) points.set(vtx_66, 5) points.set(vtx_77, 6) points.set(vtx_88, 7) meshFn.setPoints(points) MayaCmds.setKeyframe('subDShape.vtx[0:7]') # mark the mesh as a subD MayaCmds.select('subDShape') MayaCmds.addAttr(attributeType='bool', defaultValue=1, keyable=True, longName='SubDivisionMesh') self.__files.append(util.expandFileName('animSubD.abc')) self.__files.append(util.expandFileName('animSubD01_14.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root subD -file ' + self.__files[-1]) self.__files.append(util.expandFileName('animSubD15_24.abc')) MayaCmds.AbcExport(j='-fr 15 24 -root subD -file ' + self.__files[-1]) # use AbcStitcher to combine two files into one os.system(self.__abcStitcherExe + ' '.join(self.__files[-3:])) # reading test MayaCmds.AbcImport(self.__files[-3], mode='open') MayaCmds.currentTime(1, update=True) sList = OpenMaya.MSelectionList() sList.add('subDShape') meshObj = OpenMaya.MObject() sList.getDependNode(0, meshObj) meshFn = OpenMaya.MFnMesh(meshObj) # check the point list meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_1, meshPoints[0]) self.failUnlessEqual(vtx_2, meshPoints[1]) self.failUnlessEqual(vtx_3, meshPoints[2]) self.failUnlessEqual(vtx_4, meshPoints[3]) self.failUnlessEqual(vtx_5, meshPoints[4]) self.failUnlessEqual(vtx_6, meshPoints[5]) self.failUnlessEqual(vtx_7, meshPoints[6]) self.failUnlessEqual(vtx_8, meshPoints[7]) # check the polygonvertices list vertexList = OpenMaya.MIntArray() faceConnects = OpenMaya.MIntArray() faceConnects.setLength(4) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) meshFn.getPolygonVertices(0, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(4, 0) faceConnects.set(5, 1) faceConnects.set(6, 2) faceConnects.set(7, 3) meshFn.getPolygonVertices(1, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(3, 0) faceConnects.set(2, 1) faceConnects.set(6, 2) faceConnects.set(5, 3) meshFn.getPolygonVertices(2, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(3, 1) faceConnects.set(5, 2) faceConnects.set(4, 3) meshFn.getPolygonVertices(3, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(4, 1) faceConnects.set(7, 2) faceConnects.set(1, 3) meshFn.getPolygonVertices(4, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(1, 0) faceConnects.set(7, 1) faceConnects.set(6, 2) faceConnects.set(2, 3) meshFn.getPolygonVertices(5, vertexList) self.failUnlessEqual(faceConnects, vertexList) MayaCmds.currentTime(12, update=True) meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_11, meshPoints[0]) self.failUnlessEqual(vtx_22, meshPoints[1]) self.failUnlessEqual(vtx_33, meshPoints[2]) self.failUnlessEqual(vtx_44, meshPoints[3]) self.failUnlessEqual(vtx_55, meshPoints[4]) self.failUnlessEqual(vtx_66, meshPoints[5]) self.failUnlessEqual(vtx_77, meshPoints[6]) self.failUnlessEqual(vtx_88, meshPoints[7]) MayaCmds.currentTime(24, update=True) meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_1, meshPoints[0]) self.failUnlessEqual(vtx_2, meshPoints[1]) self.failUnlessEqual(vtx_3, meshPoints[2]) self.failUnlessEqual(vtx_4, meshPoints[3]) self.failUnlessEqual(vtx_5, meshPoints[4]) self.failUnlessEqual(vtx_6, meshPoints[5]) self.failUnlessEqual(vtx_7, meshPoints[6]) self.failUnlessEqual(vtx_8, meshPoints[7])
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import unittest import util def getObjFromName( nodeName ): selectionList = OpenMaya.MSelectionList() selectionList.add( nodeName ) obj = OpenMaya.MObject() selectionList.getDependNode(0, obj) return obj class MeshUVsTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) # we only support writing out the most basic uv sets (and static only) def testPolyUVs(self): MayaCmds.polyCube(name = 'cube') cubeObj = getObjFromName('cubeShape') fnMesh = OpenMaya.MFnMesh(cubeObj) # get the name of the current UV set uvSetName = fnMesh.currentUVSetName() uArray = OpenMaya.MFloatArray() vArray = OpenMaya.MFloatArray() fnMesh.getUVs(uArray, vArray, uvSetName) newUArray = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 2, -1, -1] newVArray = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 0, 1 , 0, 1] for i in range(0, 14): uArray[i] = newUArray[i] vArray[i] = newVArray[i] fnMesh.setUVs(uArray, vArray, uvSetName) self.__files.append(util.expandFileName('polyUvsTest.abc')) MayaCmds.AbcExport(j='-uv -root cube -file ' + self.__files[-1]) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.select('cube.map[0:13]', replace=True) uvs = MayaCmds.polyEditUV(query=True) for i in range(0, 14): self.failUnlessAlmostEqual(newUArray[i], uvs[2*i], 4, 'map[%d].u is not the same' % i) self.failUnlessAlmostEqual(newVArray[i], uvs[2*i+1], 4, 'map[%d].v is not the same' % i)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import unittest import util import os class interpolationTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testSubD(self): trans = MayaCmds.polyPlane(n='plane', sx=1, sy=1, ch=False)[0] shape = MayaCmds.pickWalk(d='down')[0] MayaCmds.addAttr(attributeType='bool', defaultValue=1, keyable=True, longName='SubDivisionMesh') MayaCmds.select(trans+'.vtx[0:3]', r=True) MayaCmds.move(0, 1, 0, r=True) MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe() MayaCmds.currentTime(2, update=True) MayaCmds.move(0, 5, 0, r=True) MayaCmds.setKeyframe() self.__files.append(util.expandFileName('testSubDInterpolation.abc')) MayaCmds.AbcExport(j='-fr 1 2 -root %s -file %s' % (trans, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.currentTime(1.004, update=True) ty = MayaCmds.getAttr(shape+'.vt[0]')[0][1] self.failUnlessAlmostEqual(1.02, ty) setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) ty = MayaCmds.getAttr(shape+'.vt[0]')[0][1] self.failUnlessAlmostEqual(ty, (1-alpha)*1.0+alpha*6.0, 3) def testPoly(self): trans = MayaCmds.polyPlane(n='plane', sx=1, sy=1, ch=False)[0] shape = MayaCmds.pickWalk(d='down')[0] MayaCmds.select(trans+'.vtx[0:3]', r=True) MayaCmds.move(0, 1, 0, r=True) MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe() MayaCmds.currentTime(2, update=True) MayaCmds.move(0, 5, 0, r=True) MayaCmds.setKeyframe() self.__files.append(util.expandFileName('testPolyInterpolation.abc')) MayaCmds.AbcExport(j='-fr 1 2 -root %s -file %s' % (trans, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.currentTime(1.004, update=True) ty = MayaCmds.getAttr(shape+'.vt[0]')[0][1] self.failUnlessAlmostEqual(1.02, ty) setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) ty = MayaCmds.getAttr(shape+'.vt[0]')[0][1] self.failUnlessAlmostEqual(ty, (1-alpha)*1.0+alpha*6.0, 3) def testTransOp(self): nodeName = MayaCmds.createNode('transform', n='test') # shear MayaCmds.setKeyframe(nodeName, value=0, attribute='shearXY', t=1) MayaCmds.setKeyframe(nodeName, value=0, attribute='shearYZ', t=1) MayaCmds.setKeyframe(nodeName, value=0, attribute='shearXZ', t=1) MayaCmds.setKeyframe(nodeName, value=1.5, attribute='shearXY', t=2) MayaCmds.setKeyframe(nodeName, value=5, attribute='shearYZ', t=2) MayaCmds.setKeyframe(nodeName, value=2.5, attribute='shearXZ', t=2) # translate MayaCmds.setKeyframe('test', value=0, attribute='translateX', t=1) MayaCmds.setKeyframe('test', value=0, attribute='translateY', t=1) MayaCmds.setKeyframe('test', value=0, attribute='translateZ', t=1) MayaCmds.setKeyframe('test', value=1.5, attribute='translateX', t=2) MayaCmds.setKeyframe('test', value=5, attribute='translateY', t=2) MayaCmds.setKeyframe('test', value=2.5, attribute='translateZ', t=2) # rotate MayaCmds.setKeyframe('test', value=0, attribute='rotateX', t=1) MayaCmds.setKeyframe('test', value=0, attribute='rotateY', t=1) MayaCmds.setKeyframe('test', value=0, attribute='rotateZ', t=1) MayaCmds.setKeyframe('test', value=24, attribute='rotateX', t=2) MayaCmds.setKeyframe('test', value=53, attribute='rotateY', t=2) MayaCmds.setKeyframe('test', value=90, attribute='rotateZ', t=2) # scale MayaCmds.setKeyframe('test', value=1, attribute='scaleX', t=1) MayaCmds.setKeyframe('test', value=1, attribute='scaleY', t=1) MayaCmds.setKeyframe('test', value=1, attribute='scaleZ', t=1) MayaCmds.setKeyframe('test', value=1.2, attribute='scaleX', t=2) MayaCmds.setKeyframe('test', value=1.5, attribute='scaleY', t=2) MayaCmds.setKeyframe('test', value=1.5, attribute='scaleZ', t=2) # rotate pivot MayaCmds.setKeyframe('test', value=0.5, attribute='rotatePivotX', t=1) MayaCmds.setKeyframe('test', value=-0.1, attribute='rotatePivotY', t=1) MayaCmds.setKeyframe('test', value=1, attribute='rotatePivotZ', t=1) MayaCmds.setKeyframe('test', value=0.8, attribute='rotatePivotX', t=2) MayaCmds.setKeyframe('test', value=1.5, attribute='rotatePivotY', t=2) MayaCmds.setKeyframe('test', value=-1, attribute='rotatePivotZ', t=2) # scale pivot MayaCmds.setKeyframe('test', value=1.2, attribute='scalePivotX', t=1) MayaCmds.setKeyframe('test', value=1.0, attribute='scalePivotY', t=1) MayaCmds.setKeyframe('test', value=1.2, attribute='scalePivotZ', t=1) MayaCmds.setKeyframe('test', value=1.4, attribute='scalePivotX', t=2) MayaCmds.setKeyframe('test', value=1.5, attribute='scalePivotY', t=2) MayaCmds.setKeyframe('test', value=1.5, attribute='scalePivotZ', t=2) self.__files.append(util.expandFileName('testTransOpInterpolation.abc')) MayaCmds.AbcExport(j='-fr 1 2 -root %s -f %s' % (nodeName, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.currentTime(1.004, update=True) # should read the content of frame #1 self.failUnlessAlmostEqual(0.006, MayaCmds.getAttr('test.shearXY')) self.failUnlessAlmostEqual(0.02, MayaCmds.getAttr('test.shearYZ')) self.failUnlessAlmostEqual(0.01, MayaCmds.getAttr('test.shearXZ')) self.failUnlessAlmostEqual(0.006, MayaCmds.getAttr('test.translateX')) self.failUnlessAlmostEqual(0.02, MayaCmds.getAttr('test.translateY')) self.failUnlessAlmostEqual(0.01, MayaCmds.getAttr('test.translateZ')) self.failUnlessAlmostEqual(0.096, MayaCmds.getAttr('test.rotateX')) self.failUnlessAlmostEqual(0.212, MayaCmds.getAttr('test.rotateY')) self.failUnlessAlmostEqual(0.36, MayaCmds.getAttr('test.rotateZ')) self.failUnlessAlmostEqual(1.0008, MayaCmds.getAttr('test.scaleX')) self.failUnlessAlmostEqual(1.002, MayaCmds.getAttr('test.scaleY')) self.failUnlessAlmostEqual(1.002, MayaCmds.getAttr('test.scaleZ')) self.failUnlessAlmostEqual(0.5012, MayaCmds.getAttr('test.rotatePivotX')) self.failUnlessAlmostEqual(-0.0936, MayaCmds.getAttr('test.rotatePivotY')) self.failUnlessAlmostEqual(0.992, MayaCmds.getAttr('test.rotatePivotZ')) self.failUnlessAlmostEqual(1.2008, MayaCmds.getAttr('test.scalePivotX')) self.failUnlessAlmostEqual(1.002, MayaCmds.getAttr('test.scalePivotY')) self.failUnlessAlmostEqual(1.2012, MayaCmds.getAttr('test.scalePivotZ')) setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) # should interpolate the content of frame #3 and frame #4 self.failUnlessAlmostEqual(MayaCmds.getAttr('test.shearXY'), (1-alpha)*0+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.shearYZ'), (1-alpha)*0+alpha*5.0) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.shearXZ'), (1-alpha)*0+alpha*2.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.translateX'), (1-alpha)*0+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.translateY'), (1-alpha)*0+alpha*5.0) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.translateZ'), (1-alpha)*0+alpha*2.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotateX'), (1-alpha)*0+alpha*24) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotateY'), (1-alpha)*0+alpha*53) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotateZ'), (1-alpha)*0+alpha*90) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scaleX'), (1-alpha)*1+alpha*1.2) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scaleY'), (1-alpha)*1+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scaleZ'), (1-alpha)*1+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotatePivotX'), (1-alpha)*0.5+alpha*0.8) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotatePivotY'), (1-alpha)*(-0.1)+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotatePivotZ'), (1-alpha)*1.0+alpha*(-1.0)) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scalePivotX'), (1-alpha)*1.2+alpha*1.4) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scalePivotY'), (1-alpha)*1.0+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scalePivotZ'), (1-alpha)*1.2+alpha*1.5) def testCamera(self): # create an animated camera and write out name = MayaCmds.camera() MayaCmds.setAttr(name[1]+'.horizontalFilmAperture', 0.962) MayaCmds.setAttr(name[1]+'.verticalFilmAperture', 0.731) MayaCmds.setAttr(name[1]+'.focalLength', 50) MayaCmds.setAttr(name[1]+'.focusDistance', 5) MayaCmds.setAttr(name[1]+'.shutterAngle', 144) # animate the camera MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(name[1], attribute='horizontalFilmAperture') MayaCmds.setKeyframe(name[1], attribute='focalLength') MayaCmds.setKeyframe(name[1], attribute='focusDistance') MayaCmds.setKeyframe(name[1], attribute='shutterAngle') MayaCmds.currentTime(6, update=True) MayaCmds.setKeyframe(name[1], attribute='horizontalFilmAperture', value=0.95) MayaCmds.setKeyframe(name[1], attribute='focalLength', value=40) MayaCmds.setKeyframe(name[1], attribute='focusDistance', value=5.4) MayaCmds.setKeyframe(name[1], attribute='shutterAngle', value=174.94) self.__files.append(util.expandFileName('testCameraInterpolation.abc')) MayaCmds.AbcExport(j='-fr 1 6 -root %s -f %s' % (name[0], self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='import') camList = MayaCmds.ls(type='camera') t = 1.004 MayaCmds.currentTime(t, update=True) self.failUnlessAlmostEqual(MayaCmds.getAttr(camList[0]+'.horizontalFilmAperture'), 0.962, 3) setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) if not util.compareCamera(camList[0], camList[1]): self.fail('%s and %s are not the same at frame %d' % (camList[0], camList[1], t)) def testProp(self): trans = MayaCmds.createNode("transform") # create animated props MayaCmds.select(trans) MayaCmds.addAttr(longName='SPT_int8', dv=0, attributeType='byte', keyable=True) MayaCmds.addAttr(longName='SPT_int16', dv=0, attributeType='short', keyable=True) MayaCmds.addAttr(longName='SPT_int32', dv=0, attributeType='long', keyable=True) MayaCmds.addAttr(longName='SPT_float', dv=0, attributeType='float', keyable=True) MayaCmds.addAttr(longName='SPT_double', dv=0, attributeType='double', keyable=True) MayaCmds.setKeyframe(trans, value=0, attribute='SPT_int8', t=1) MayaCmds.setKeyframe(trans, value=100, attribute='SPT_int16', t=1) MayaCmds.setKeyframe(trans, value=1000, attribute='SPT_int32', t=1) MayaCmds.setKeyframe(trans, value=0.57777777, attribute='SPT_float', t=1) MayaCmds.setKeyframe(trans, value=5.045643545457, attribute='SPT_double', t=1) MayaCmds.setKeyframe(trans, value=8, attribute='SPT_int8', t=2) MayaCmds.setKeyframe(trans, value=16, attribute='SPT_int16', t=2) MayaCmds.setKeyframe(trans, value=32, attribute='SPT_int32', t=2) MayaCmds.setKeyframe(trans, value=3.141592654, attribute='SPT_float', t=2) MayaCmds.setKeyframe(trans, value=3.141592654, attribute='SPT_double', t=2) self.__files.append(util.expandFileName('testPropInterpolation.abc')) MayaCmds.AbcExport(j='-fr 1 2 -atp SPT_ -root %s -f %s' % (trans, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') t = 1.004 MayaCmds.currentTime(t, update=True) self.failUnlessEqual(MayaCmds.getAttr(trans+'.SPT_int8'), 0) self.failUnlessEqual(MayaCmds.getAttr(trans+'.SPT_int16'), 99) self.failUnlessEqual(MayaCmds.getAttr(trans+'.SPT_int32'), 996) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_float'), 0.5880330295359999, 7) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_double'), 5.038027341891171, 7) setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_int8'), (1-alpha)*0+alpha*8, -1) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_int16'), (1-alpha)*100+alpha*16, -1) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_int32'), (1-alpha)*1000+alpha*32, -1) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_float'), (1-alpha)*0.57777777+alpha*3.141592654, 6) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_double'), (1-alpha)* 5.045643545457+alpha*3.141592654, 6)
Python
#!/usr/bin/env mayapy ##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** # run this via mayapy # runs the test suite import glob import os import sys import time import unittest import maya.standalone maya.standalone.initialize(name='python') from maya import cmds as MayaCmds from maya.mel import eval as MelEval usage = """ Usage: mayapy RunTests.py AbcExport AbcImport AbcStitcher [tests.py] Where: AbcExport is the location of the AbcExport Maya plugin to load. AbcImport is the location of the AbcImport Maya plugin to load. AbcStitcher is the location of the AbcStitcher command to use. If no specific python tests are specified, all python files named *_test.py in the same directory as this file are used. """ if len(sys.argv) < 4: raise RuntimeError(usage) MayaCmds.loadPlugin(sys.argv[1]) print 'LOADED', sys.argv[1] MayaCmds.loadPlugin(sys.argv[2]) print 'LOADED', sys.argv[2] if not os.path.exists(sys.argv[3]): raise RuntimeError (sys.argv[3] + ' does not exist') else: os.environ['AbcStitcher'] = sys.argv[3] suite = unittest.TestSuite() main_dir = os.path.dirname(os.path.abspath(__file__)) os.chdir( main_dir ) MelEval('chdir "%s"' % main_dir ) # For now, hack the path (so the import below works) sys.path.append("..") # Load all the tests specified by the command line or *_test.py testFiles = sys.argv[4:] if not testFiles: testFiles = glob.glob('*_test.py') for file in testFiles: name = os.path.splitext(file)[0] __import__(name) test = unittest.defaultTestLoader.loadTestsFromName(name) suite.addTest(test) # Run the tests runner = unittest.TextTestRunner(verbosity=2) runner.run(suite)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class TransformTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticTransformReadWrite(self): nodeName = MayaCmds.polyCube(n='cube') MayaCmds.setAttr('cube.translate', 2.456, -3.95443, 0, type="double3") MayaCmds.setAttr('cube.rotate', 45, 15, -90, type="double3") MayaCmds.setAttr('cube.rotateOrder', 4) MayaCmds.setAttr('cube.scale', 1.5, 5, 1, type="double3") MayaCmds.setAttr('cube.shearXY',1) MayaCmds.setAttr('cube.rotatePivot', 13.52, 0.0, 20.25, type="double3") MayaCmds.setAttr('cube.rotatePivotTranslate', 0.5, 0.0, 0.25, type="double3") MayaCmds.setAttr('cube.scalePivot', 10.7, 2.612, 0.2, type="double3") MayaCmds.setAttr('cube.scalePivotTranslate', 0.0, 0.0, 0.25, type="double3") MayaCmds.setAttr('cube.inheritsTransform', 0) self.__files.append(util.expandFileName('testStaticTransformReadWrite.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (nodeName[0], self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') self.failUnlessAlmostEqual(2.456, MayaCmds.getAttr('cube.translateX'), 4) self.failUnlessAlmostEqual(-3.95443, MayaCmds.getAttr('cube.translateY'), 4) self.failUnlessAlmostEqual(0.0, MayaCmds.getAttr('cube.translateZ'), 4) self.failUnlessAlmostEqual(45, MayaCmds.getAttr('cube.rotateX'), 4) self.failUnlessAlmostEqual(15, MayaCmds.getAttr('cube.rotateY'), 4) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr('cube.rotateZ'), 4) self.failUnlessEqual(4, MayaCmds.getAttr('cube.rotateOrder')) self.failUnlessAlmostEqual(1.5, MayaCmds.getAttr('cube.scaleX'), 4) self.failUnlessAlmostEqual(5, MayaCmds.getAttr('cube.scaleY'), 4) self.failUnlessAlmostEqual(1, MayaCmds.getAttr('cube.scaleZ'), 4) self.failUnlessAlmostEqual(1, MayaCmds.getAttr('cube.shearXY'), 4) self.failUnlessAlmostEqual(13.52, MayaCmds.getAttr('cube.rotatePivotX'), 4) self.failUnlessAlmostEqual(0.0, MayaCmds.getAttr('cube.rotatePivotY'), 4) self.failUnlessAlmostEqual(20.25, MayaCmds.getAttr('cube.rotatePivotZ'), 4) self.failUnlessAlmostEqual(0.5, MayaCmds.getAttr('cube.rotatePivotTranslateX'), 4) self.failUnlessAlmostEqual(0.0, MayaCmds.getAttr('cube.rotatePivotTranslateY'), 4) self.failUnlessAlmostEqual(0.25, MayaCmds.getAttr('cube.rotatePivotTranslateZ'), 4) self.failUnlessAlmostEqual(10.7, MayaCmds.getAttr('cube.scalePivotX'), 4) self.failUnlessAlmostEqual(2.612, MayaCmds.getAttr('cube.scalePivotY'), 4) self.failUnlessAlmostEqual(0.2, MayaCmds.getAttr('cube.scalePivotZ'), 4) self.failUnlessAlmostEqual(0.0, MayaCmds.getAttr('cube.scalePivotTranslateX'), 4) self.failUnlessAlmostEqual(0.0, MayaCmds.getAttr('cube.scalePivotTranslateY'), 4) self.failUnlessAlmostEqual(0.25, MayaCmds.getAttr('cube.scalePivotTranslateZ'), 4) self.failUnlessEqual(0, MayaCmds.getAttr('cube.inheritsTransform')) def testStaticTransformRotateOrder(self): nodeName = MayaCmds.polyCube(n='cube') MayaCmds.setAttr('cube.rotate', 45, 1, -90, type="double3") MayaCmds.setAttr('cube.rotateOrder', 5) self.__files.append(util.expandFileName('testStaticTransformRotateOrder.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (nodeName[0], self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') self.failUnlessEqual(5, MayaCmds.getAttr('cube.rotateOrder')) self.failUnlessAlmostEqual(45, MayaCmds.getAttr('cube.rotateX'), 4) self.failUnlessAlmostEqual(1, MayaCmds.getAttr('cube.rotateY'), 4) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr('cube.rotateZ'), 4) def testStaticTransformRotateOrder2(self): nodeName = MayaCmds.polyCube(n='cube') MayaCmds.setAttr('cube.rotate', 45, 0, -90, type="double3") MayaCmds.setAttr('cube.rotateOrder', 5) self.__files.append(util.expandFileName('testStaticTransformRotateOrder2.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (nodeName[0], self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') self.failUnlessEqual(5, MayaCmds.getAttr('cube.rotateOrder')) self.failUnlessAlmostEqual(45, MayaCmds.getAttr('cube.rotateX'), 4) self.failUnlessAlmostEqual(0, MayaCmds.getAttr('cube.rotateY'), 4) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr('cube.rotateZ'), 4)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import subprocess import unittest import util class AnimNurbsCurveTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__abcStitcher = [os.environ['AbcStitcher']] self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) # a test for animated non-curve group Nurbs Curve def testAnimSimpleNurbsCurveRW(self): # create the Nurbs Curve name = MayaCmds.curve( d=3, p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9), (12, 10, 2)], k=[0,0,0,1,2,2,2] ) MayaCmds.select(name+'.cv[0:4]') # frame 1 MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe() # frame 24 MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe() # frame 12 MayaCmds.currentTime(12, update=True) MayaCmds.move(3, 0, 0, r=True) MayaCmds.setKeyframe() self.__files.append(util.expandFileName('testAnimNurbsSingleCurve.abc')) self.__files.append(util.expandFileName('testAnimNurbsSingleCurve01_14.abc')) self.__files.append(util.expandFileName('testAnimNurbsSingleCurve15_24.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % (name, self.__files[-2])) MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % (name, self.__files[-1])) # use AbcStitcher to combine two files into one subprocess.call(self.__abcStitcher + self.__files[-3:]) MayaCmds.AbcImport(self.__files[-3], mode='import') shapeNames = MayaCmds.ls(exactType='nurbsCurve') MayaCmds.currentTime(1, update=True) self.failUnless(util.compareNurbsCurve(shapeNames[0], shapeNames[1])) MayaCmds.currentTime(12, update=True) self.failUnless(util.compareNurbsCurve(shapeNames[0], shapeNames[1])) MayaCmds.currentTime(24, update=True) self.failUnless(util.compareNurbsCurve(shapeNames[0], shapeNames[1])) def testAnimNurbsCurveGrpRW(self): # create Nurbs Curve group knotVec = [0,0,0,1,2,2,2] curve1CV = [(0, 0, 0), (3, 5, 0), (5, 6, 0), (9, 9, 0), (12, 10, 0)] curve2CV = [(0, 0, 3), (3, 5, 3), (5, 6, 3), (9, 9, 3), (12, 10, 3)] curve3CV = [(0, 0, 6), (3, 5, 6), (5, 6, 6), (9, 9, 6), (12, 10, 6)] MayaCmds.curve(d=3, p=curve1CV, k=knotVec, name='curve1') MayaCmds.curve(d=3, p=curve2CV, k=knotVec, name='curve2') MayaCmds.curve(d=3, p=curve3CV, k=knotVec, name='curve3') MayaCmds.group('curve1', 'curve2', 'curve3', name='group') MayaCmds.addAttr('group', longName='riCurves', at='bool', dv=True) # frame 1 MayaCmds.currentTime(1, update=True) MayaCmds.select('curve1.cv[0:4]', 'curve2.cv[0:4]', 'curve3.cv[0:4]', replace=True) MayaCmds.setKeyframe() # frame 24 MayaCmds.currentTime(24, update=True) MayaCmds.select('curve1.cv[0:4]') MayaCmds.rotate(0.0, '90deg', 0.0, relative=True ) MayaCmds.select('curve2.cv[0:4]') MayaCmds.move(0.0, 0.5, 0.0, relative=True ) MayaCmds.select('curve3.cv[0:4]') MayaCmds.scale(1.0, 0.5, 1.0, relative=True ) MayaCmds.select('curve1.cv[0:4]', 'curve2.cv[0:4]', 'curve3.cv[0:4]', replace=True) MayaCmds.setKeyframe() self.__files.append(util.expandFileName('testAnimNCGrp.abc')) self.__files.append(util.expandFileName('testAnimNCGrp01_14.abc')) self.__files.append(util.expandFileName('testAnimNCGrp15_24.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % ('group', self.__files[-2])) MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % ('group', self.__files[-1])) # use AbcStitcher to combine two files into one subprocess.call(self.__abcStitcher + self.__files[-3:]) # reading test MayaCmds.AbcImport(self.__files[-3], mode='import') shapeNames = MayaCmds.ls(exactType='nurbsCurve') MayaCmds.currentTime(1, update=True) for i in range(0, 3): self.failUnless( util.compareNurbsCurve(shapeNames[i], shapeNames[i+3])) MayaCmds.currentTime(12, update=True) for i in range(0, 3): self.failUnless( util.compareNurbsCurve(shapeNames[i], shapeNames[i+3])) MayaCmds.currentTime(24, update=True) for i in range(0, 3): self.failUnless( util.compareNurbsCurve(shapeNames[i], shapeNames[i+3]))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds from maya.mel import eval as MelEval import os import maya.OpenMaya as OpenMaya import unittest import util class StaticMeshTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticMeshReadWrite(self): numFaces = 6 numVertices = 8 numFaceConnects = 24 vtx_1 = OpenMaya.MFloatPoint(-0.5, -0.5, -0.5) vtx_2 = OpenMaya.MFloatPoint( 0.5, -0.5, -0.5) vtx_3 = OpenMaya.MFloatPoint( 0.5, -0.5, 0.5) vtx_4 = OpenMaya.MFloatPoint(-0.5, -0.5, 0.5) vtx_5 = OpenMaya.MFloatPoint(-0.5, 0.5, -0.5) vtx_6 = OpenMaya.MFloatPoint(-0.5, 0.5, 0.5) vtx_7 = OpenMaya.MFloatPoint( 0.5, 0.5, 0.5) vtx_8 = OpenMaya.MFloatPoint( 0.5, 0.5, -0.5) points = OpenMaya.MFloatPointArray() points.setLength(8) points.set(vtx_1, 0) points.set(vtx_2, 1) points.set(vtx_3, 2) points.set(vtx_4, 3) points.set(vtx_5, 4) points.set(vtx_6, 5) points.set(vtx_7, 6) points.set(vtx_8, 7) faceConnects = OpenMaya.MIntArray() faceConnects.setLength(numFaceConnects) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) faceConnects.set(4, 4) faceConnects.set(5, 5) faceConnects.set(6, 6) faceConnects.set(7, 7) faceConnects.set(3, 8) faceConnects.set(2, 9) faceConnects.set(6, 10) faceConnects.set(5, 11) faceConnects.set(0, 12) faceConnects.set(3, 13) faceConnects.set(5, 14) faceConnects.set(4, 15) faceConnects.set(0, 16) faceConnects.set(4, 17) faceConnects.set(7, 18) faceConnects.set(1, 19) faceConnects.set(1, 20) faceConnects.set(7, 21) faceConnects.set(6, 22) faceConnects.set(2, 23) faceCounts = OpenMaya.MIntArray() faceCounts.setLength(6) faceCounts.set(4, 0) faceCounts.set(4, 1) faceCounts.set(4, 2) faceCounts.set(4, 3) faceCounts.set(4, 4) faceCounts.set(4, 5) transFn = OpenMaya.MFnTransform() parent = transFn.create() transFn.setName('mesh') meshFn = OpenMaya.MFnMesh() meshFn.create(numVertices, numFaces, points, faceCounts, faceConnects, parent) meshFn.setName("meshShape"); self.__files.append(util.expandFileName('testStaticMeshReadWrite.abc')) MayaCmds.AbcExport(j='-root mesh -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') sList = OpenMaya.MSelectionList() sList.add('meshShape') meshObj = OpenMaya.MObject() sList.getDependNode(0, meshObj) meshFn = OpenMaya.MFnMesh(meshObj) # check the point list meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints); self.failUnlessEqual(vtx_1, meshPoints[0]) self.failUnlessEqual(vtx_2, meshPoints[1]) self.failUnlessEqual(vtx_3, meshPoints[2]) self.failUnlessEqual(vtx_4, meshPoints[3]) self.failUnlessEqual(vtx_5, meshPoints[4]) self.failUnlessEqual(vtx_6, meshPoints[5]) self.failUnlessEqual(vtx_7, meshPoints[6]) self.failUnlessEqual(vtx_8, meshPoints[7]) # check the polygonvertices list vertexList = OpenMaya.MIntArray() faceConnects = OpenMaya.MIntArray() faceConnects.setLength(4) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) meshFn.getPolygonVertices(0, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(4, 0) faceConnects.set(5, 1) faceConnects.set(6, 2) faceConnects.set(7, 3) meshFn.getPolygonVertices(1, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(3, 0) faceConnects.set(2, 1) faceConnects.set(6, 2) faceConnects.set(5, 3) meshFn.getPolygonVertices(2, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(3, 1) faceConnects.set(5, 2) faceConnects.set(4, 3) meshFn.getPolygonVertices(3, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(4, 1) faceConnects.set(7, 2) faceConnects.set(1, 3) meshFn.getPolygonVertices(4, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(1, 0) faceConnects.set(7, 1) faceConnects.set(6, 2) faceConnects.set(2, 3) meshFn.getPolygonVertices(5, vertexList) self.failUnlessEqual(faceConnects, vertexList)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class VisibilityTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticVisibility(self): poly1 = MayaCmds.polyPlane(sx=2, sy=2, w=1, h=1, ch=0)[0] group1 = MayaCmds.group() group2 = MayaCmds.createNode("transform") MayaCmds.select(group1, group2) group3 = MayaCmds.group() group4 = (MayaCmds.duplicate(group1, rr=1))[0] group5 = MayaCmds.group() MayaCmds.select(group3, group5) root = MayaCmds.group(name='root') MayaCmds.setAttr(group1 + '.visibility', 0) MayaCmds.setAttr(group2 + '.visibility', 0) MayaCmds.setAttr(group5 + '.visibility', 0) self.__files.append(util.expandFileName('staticVisibilityTest.abc')) MayaCmds.AbcExport(j='-wv -root %s -file %s' % (root, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], m='open') self.failIf(MayaCmds.getAttr(group1+'.visibility')) self.failIf(MayaCmds.getAttr(group2+'.visibility')) self.failIf(MayaCmds.getAttr(group5+'.visibility')) self.failUnless(MayaCmds.getAttr(group1+'|'+poly1+'.visibility')) self.failUnless(MayaCmds.getAttr(group4+'|'+poly1+'.visibility')) self.failUnless(MayaCmds.getAttr(group3+'.visibility')) self.failUnless(MayaCmds.getAttr(group4+'.visibility')) self.failUnless(MayaCmds.getAttr(root+'.visibility')) def testAnimVisibility(self): poly1 = MayaCmds.polyPlane( sx=2, sy=2, w=1, h=1, ch=0)[0] group1 = MayaCmds.group() group2 = MayaCmds.createNode("transform") MayaCmds.select(group1, group2) group3 = MayaCmds.group() group4 = (MayaCmds.duplicate(group1, rr=1))[0] group5 = MayaCmds.group() MayaCmds.select(group3, group5) root = MayaCmds.group(name='root') MayaCmds.setKeyframe(group1 + '.visibility', v=0, t=[1, 4]) MayaCmds.setKeyframe(group2 + '.visibility', v=0, t=[1, 4]) MayaCmds.setKeyframe(group5 + '.visibility', v=0, t=[1, 4]) MayaCmds.setKeyframe(group1 + '.visibility', v=1, t=2) MayaCmds.setKeyframe(group2 + '.visibility', v=1, t=2) MayaCmds.setKeyframe(group5 + '.visibility', v=1, t=2) self.__files.append(util.expandFileName('animVisibilityTest.abc')) MayaCmds.AbcExport(j='-wv -fr 1 4 -root %s -file %s' % (root, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.currentTime(1, update = True) self.failIf(MayaCmds.getAttr(group1 + '.visibility')) self.failIf(MayaCmds.getAttr(group2 + '.visibility')) self.failIf(MayaCmds.getAttr(group5 + '.visibility')) self.failUnless(MayaCmds.getAttr(group1 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group3 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '.visibility')) self.failUnless(MayaCmds.getAttr(root+'.visibility')) MayaCmds.currentTime(2, update = True) self.failUnless(MayaCmds.getAttr(group1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group2 + '.visibility')) self.failUnless(MayaCmds.getAttr(group5 + '.visibility')) self.failUnless(MayaCmds.getAttr(group1 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group3 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '.visibility')) self.failUnless(MayaCmds.getAttr(root + '.visibility')) MayaCmds.currentTime(4, update = True ) self.failIf(MayaCmds.getAttr(group1 + '.visibility')) self.failIf(MayaCmds.getAttr(group2 + '.visibility')) self.failIf(MayaCmds.getAttr(group5 + '.visibility')) self.failUnless(MayaCmds.getAttr(group1 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group3 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '.visibility')) self.failUnless(MayaCmds.getAttr(root+'.visibility'))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util def testNurbsCurveRW( self, isGroup, abcFileName, inText): MayaCmds.file(new=True, force=True) name = MayaCmds.textCurves( font='Courier', text=inText ) if isGroup == True : MayaCmds.addAttr(name[0], longName='riCurves', at='bool', dv=True) shapeNames = MayaCmds.ls(type='nurbsCurve') miscinfo=[] cv=[] knot=[] curveInfoNode = MayaCmds.createNode('curveInfo') for i in range(0, len(shapeNames)) : shapeName = shapeNames[i] MayaCmds.connectAttr(shapeName+'.worldSpace', curveInfoNode+'.inputCurve', force=True) controlPoints = MayaCmds.getAttr(curveInfoNode + '.controlPoints[*]') cv.append(controlPoints) numCV = len(controlPoints) spans = MayaCmds.getAttr(shapeName+'.spans') degree = MayaCmds.getAttr(shapeName+'.degree') form = MayaCmds.getAttr(shapeName+'.form') minVal = MayaCmds.getAttr(shapeName+'.minValue') maxVal = MayaCmds.getAttr(shapeName+'.maxValue') misc = [numCV, spans, degree, form, minVal, maxVal] miscinfo.append(misc) knots = MayaCmds.getAttr(curveInfoNode + '.knots[*]') knot.append(knots) MayaCmds.AbcExport(j='-root %s -f %s' % (name[0], abcFileName)) # reading test MayaCmds.AbcImport(abcFileName, mode='open') if isGroup == True: shapeNames = MayaCmds.ls(exactType='nurbsCurve') self.failUnless(MayaCmds.getAttr(name[0]+'.riCurves')) miscinfo2 = [] cv2 = [] knot2 = [] curveInfoNode = MayaCmds.createNode('curveInfo') for i in range(0, len(shapeNames)): name = shapeNames[i] MayaCmds.connectAttr(name+'.worldSpace', curveInfoNode+'.inputCurve', force=True) controlPoints = MayaCmds.getAttr(curveInfoNode + '.controlPoints[*]') cv2.append(controlPoints) numCV = len(controlPoints) spans = MayaCmds.getAttr(name+'.spans') degree = MayaCmds.getAttr(name+'.degree') form = MayaCmds.getAttr(name+'.form') minVal = MayaCmds.getAttr(name+'.minValue') maxVal = MayaCmds.getAttr(name+'.maxValue') misc = [numCV, spans, degree, form, minVal, maxVal] miscinfo2.append(misc) knots = MayaCmds.getAttr(curveInfoNode + '.knots[*]') knot2.append(knots) for i in range(0, len(shapeNames)) : name = shapeNames[i] self.failUnlessEqual(len(cv[i]), len(cv2[i])) for j in range(0, len(cv[i])) : cp1 = cv[i][j] cp2 = cv2[i][j] self.failUnlessAlmostEqual(cp1[0], cp2[0], 3, 'curve[%d].cp[%d].x not equal' % (i,j)) self.failUnlessAlmostEqual(cp1[1], cp2[1], 3, 'curve[%d].cp[%d].y not equal' % (i,j)) self.failUnlessAlmostEqual(cp1[2], cp2[2], 3, 'curve[%d].cp[%d].z not equal' % (i,j)) class StaticNurbsCurveTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testNurbsSingleCurveReadWrite(self): name = MayaCmds.curve(d=3, p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9), (12, 10, 2)], k=[0,0,0,1,2,2,2]) self.__files.append(util.expandFileName('testStaticNurbsSingleCurve.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (name, self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='import') shapeNames = MayaCmds.ls(exactType='nurbsCurve') self.failUnless(util.compareNurbsCurve(shapeNames[0], shapeNames[1])) def testNurbsCurveGrpReadWrite(self): # test w/r of simple Nurbs Curve self.__files.append(util.expandFileName('testStaticNurbsCurves.abc')) testNurbsCurveRW(self, False, self.__files[-1], 'haka') self.__files.append(util.expandFileName('testStaticNurbsCurveGrp.abc')) testNurbsCurveRW(self, True, self.__files[-1], 'haka') # test if some curves have different degree or close states information MayaCmds.file(new=True, force=True) name = MayaCmds.textCurves(font='Courier', text='Maya') MayaCmds.addAttr(name[0], longName='riCurves', at='bool', dv=True) self.__files.append(util.expandFileName('testStaticNurbsCurveGrp2.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (name[0], self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') if 'riCurves' in MayaCmds.listAttr(name[0]): self.fail(name[0]+".riCurves shouldn't exist") def testNurbsSingleCurveWidthReadWrite(self): MayaCmds.file(new=True, force=True) # single curve with no width information MayaCmds.curve(d=3, p=[(0, 0, 0), (3, 5, 0), (5, 6, 0), (9, 9, 0), (12, 10, 0)], k=[0,0,0,1,2,2,2], name='curve1') # single curve with constant width information MayaCmds.curve(d=3, p=[(0, 0, 3), (3, 5, 3), (5, 6, 3), (9, 9, 3), (12, 10, 3)], k=[0,0,0,1,2,2,2], name='curve2') MayaCmds.select('curveShape2') MayaCmds.addAttr(longName='width', attributeType='double', dv=0.75) # single open curve with width information MayaCmds.curve(d=3, p=[(0, 0, 6), (3, 5, 6), (5, 6, 6), (9, 9, 6), (12, 10, 6)], k=[0,0,0,1,2,2,2], name='curve3') MayaCmds.select('curveShape3') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curveShape3.width', [0.2, 0.4, 0.6, 0.8, 1.0], type='doubleArray') # single open curve with wrong width information MayaCmds.curve(d=3, p=[(0, 0, 9), (3, 5, 9), (5, 6, 9), (9, 9, 9), (12, 10, 9)], k=[0,0,0,1,2,2,2], name='curve4') MayaCmds.select('curveShape4') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curveShape4.width', [0.12, 1.4, 0.37], type='doubleArray') # single curve circle with width information MayaCmds.circle(ch=False, name='curve5') MayaCmds.select('curve5Shape') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curve5Shape.width', [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1], type='doubleArray') # single curve circle with wrong width information MayaCmds.circle(ch=False, name='curve6') MayaCmds.select('curve6Shape') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curve6Shape.width', [0.12, 1.4, 0.37], type='doubleArray') self.__files.append(util.expandFileName('testStaticNurbsCurveWidthTest.abc')) MayaCmds.AbcExport(j='-root curve1 -root curve2 -root curve3 -root curve4 -root curve5 -root curve6 -f ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') # check the width # curve 1 self.failUnless('width' in MayaCmds.listAttr('curveShape1')) self.failUnlessAlmostEqual( MayaCmds.getAttr('curveShape1.width'), 0.1, 4) # curve 2 self.failUnless('width' in MayaCmds.listAttr('curveShape2')) self.failUnlessAlmostEqual( MayaCmds.getAttr('curveShape2.width'), 0.75, 4) # curve 3 width = MayaCmds.getAttr('curveShape3.width') for i in range(5): self.failUnlessAlmostEqual(width[i], 0.2*i+0.2, 4) # curve 4 (bad width defaults to 0.1) self.failUnless('width' in MayaCmds.listAttr('curveShape4')) width = MayaCmds.getAttr('curveShape4.width') self.failUnlessAlmostEqual( MayaCmds.getAttr('curveShape4.width'), 0.1, 4) # curve 5 self.failUnlessEqual('width' in MayaCmds.listAttr('curve5Shape'), True) width = MayaCmds.getAttr('curve5Shape.width') for i in range(11): self.failUnlessAlmostEqual(width[i], 0.1*i+0.1, 4) # curve 6 (bad width defaults to 0.1) self.failUnless('width' in MayaCmds.listAttr('curve6Shape')) self.failUnlessAlmostEqual( MayaCmds.getAttr('curve6Shape.width'), 0.1, 4) def testNurbsCurveGrpWidthRW1(self): widthVecs = [[0.11, 0.12, 0.13, 0.14, 0.15], [0.1, 0.3, 0.5, 0.7, 0.9], [0.2, 0.3, 0.4, 0.5, 0.6]] MayaCmds.curve(d=3, p=[(0, 0, 0), (3, 5, 0), (5, 6, 0), (9, 9, 0), (12, 10, 0)], k=[0,0,0,1,2,2,2], name='curve1') MayaCmds.select('curveShape1') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curveShape1.width', widthVecs[0], type='doubleArray') MayaCmds.curve(d=3, p=[(0, 0, 3), (3, 5, 3), (5, 6, 3), (9, 9, 3), (12, 10, 3)], k=[0,0,0,1,2,2,2], name='curve2') MayaCmds.select('curveShape2') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curveShape2.width', widthVecs[1], type='doubleArray') MayaCmds.curve(d=3, p=[(0, 0, 6), (3, 5, 6), (5, 6, 6), (9, 9, 6), (12, 10, 6)], k=[0,0,0,1,2,2,2], name='curve3') MayaCmds.select('curveShape3') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curveShape3.width', widthVecs[2], type='doubleArray') MayaCmds.group('curve1', 'curve2', 'curve3', name='group') MayaCmds.addAttr('group', longName='riCurves', at='bool', dv=True) self.__files.append(util.expandFileName('testStaticNurbsCurveGrpWidthTest1.abc')) MayaCmds.AbcExport(j='-root group -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') # width check for i in range(0,3): shapeName = '|group|group' if i > 0: shapeName = shapeName + str(i) self.failUnless('width' in MayaCmds.listAttr(shapeName)) width = MayaCmds.getAttr(shapeName + '.width') for j in range(len(widthVecs[i])): self.failUnlessAlmostEqual(width[j], widthVecs[i][j], 4) def testNurbsCurveGrpWidthRW2(self): MayaCmds.curve(d=3, p=[(0, 0, 0), (3, 5, 0), (5, 6, 0), (9, 9, 0), (12, 10, 0)], k=[0,0,0,1,2,2,2], name='curve1') MayaCmds.select('curveShape1') MayaCmds.curve(d=3, p=[(0, 0, 3), (3, 5, 3), (5, 6, 3), (9, 9, 3), (12, 10, 3)], k=[0,0,0,1,2,2,2], name='curve2') MayaCmds.curve(d=3, p=[(0, 0, 6), (3, 5, 6), (5, 6, 6), (9, 9, 6), (12, 10, 6)], k=[0,0,0,1,2,2,2], name='curve3') MayaCmds.select('curveShape3') MayaCmds.group('curve1', 'curve2', 'curve3', name='group') MayaCmds.addAttr('group', longName='riCurves', at='bool', dv=True) MayaCmds.addAttr('group', longName='width', attributeType='double', dv=0.75) self.__files.append(util.expandFileName('testStaticNurbsCurveGrpWidthTest2.abc')) MayaCmds.AbcExport(j='-root group -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') # constant width check self.failUnless('width' in MayaCmds.listAttr('|group')) self.failUnlessAlmostEqual(MayaCmds.getAttr('|group.width'), 0.75, 4)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util def makeRobot(): MayaCmds.polyCube(name="head") MayaCmds.move(0, 4, 0, r=1) MayaCmds.polyCube(name="chest") MayaCmds.scale(2, 2.5, 1) MayaCmds.move(0, 2, 0, r=1) MayaCmds.polyCube(name="leftArm") MayaCmds.move(0, 3, 0, r=1) MayaCmds.scale(2, 0.5, 1, r=1) MayaCmds.duplicate(name="rightArm") MayaCmds.select("leftArm") MayaCmds.move(1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, 32, r=1, os=1) MayaCmds.select("rightArm") MayaCmds.move(-1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, -32, r=1, os=1) MayaCmds.select("rightArm", "leftArm", "chest", r=1) MayaCmds.group(name="body") MayaCmds.polyCube(name="bottom") MayaCmds.scale(2, 0.5, 1) MayaCmds.move(0, 0.5, 0, r=1) MayaCmds.polyCube(name="leftLeg") MayaCmds.scale(0.65, 2.8, 1, r=1) MayaCmds.move(-0.5, -1, 0, r=1) MayaCmds.duplicate(name="rightLeg") MayaCmds.move(1, 0, 0, r=1) MayaCmds.select("rightLeg", "leftLeg", "bottom", r=1) MayaCmds.group(name="lower") MayaCmds.select("head", "body", "lower", r=1) MayaCmds.group(name="robot") class selectionTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testSelectionNamespace(self): nodes = MayaCmds.polyCube() MayaCmds.namespace(add="potato") MayaCmds.rename(nodes[0], "potato:" + nodes[0]) MayaCmds.select(MayaCmds.ls(type="mesh")) self.__files.append(util.expandFileName('selectionTest_namespace.abc')) MayaCmds.AbcExport(j='-sl -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') self.failUnless(MayaCmds.ls(type="mesh") != 1) def testSelectionFlag(self): makeRobot() MayaCmds.select('bottom', 'leftArm', 'head') self.__files.append(util.expandFileName('selectionTest_partial.abc')) MayaCmds.AbcExport(j='-sl -root head -root body -root lower -file ' + self.__files[-1]) self.__files.append(util.expandFileName('selectionTest.abc')) MayaCmds.AbcExport(j='-sl -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') self.failUnless(MayaCmds.objExists("robot|head")) self.failUnless(MayaCmds.objExists("robot|body|leftArm")) self.failUnless(MayaCmds.objExists("robot|lower|bottom")) self.failIf(MayaCmds.objExists("robot|body|rightArm")) self.failIf(MayaCmds.objExists("robot|body|chest")) self.failIf(MayaCmds.objExists("robot|lower|rightLeg")) self.failIf(MayaCmds.objExists("robot|lower|leftLeg")) MayaCmds.AbcImport(self.__files[-2], m='open') self.failUnless(MayaCmds.objExists("head")) self.failUnless(MayaCmds.objExists("body|leftArm")) self.failUnless(MayaCmds.objExists("lower|bottom")) # we didnt actually select any meshes so there shouldnt # be any in the scene self.failIf(MayaCmds.ls(type='mesh'))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import subprocess import unittest import util def createJoints(): name = MayaCmds.joint(position=(0, 0, 0)) MayaCmds.rotate(33.694356, 4.000428, 61.426019, r=True, ws=True) MayaCmds.joint(position=(0, 4, 0), orientation=(0.0, 45.0, 90.0)) MayaCmds.rotate(62.153171, 0.0, 0.0, r=True, os=True) MayaCmds.joint(position=(0, 8, -1), orientation=(90.0, 0.0, 0.0)) MayaCmds.rotate(70.245162, -33.242019, 41.673097, r=True, os=True) MayaCmds.joint(position=(0, 12, 3)) MayaCmds.rotate(0.0, 0.0, -58.973851, r=True, os=True) return name class JointTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] self.__abcStitcher = [os.environ['AbcStitcher']] def tearDown(self): for f in self.__files: os.remove(f) def testStaticJointRW(self): name = createJoints() # write to file self.__files.append(util.expandFileName('testStaticJoints.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (name, self.__files[-1])) MayaCmds.select(name) MayaCmds.group(name='original') # read from file MayaCmds.AbcImport(self.__files[-1], mode='import') # make sure the translate and rotation are the same nodes1 = ["|original|joint1", "|original|joint1|joint2", "|original|joint1|joint2|joint3", "|original|joint1|joint2|joint3|joint4"] nodes2 = ["|joint1", "|joint1|joint2", "|joint1|joint2|joint3", "|joint1|joint2|joint3|joint4"] for i in range(0, 4): self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tx'), MayaCmds.getAttr(nodes2[i]+'.tx'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.ty'), MayaCmds.getAttr(nodes2[i]+'.ty'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tz'), MayaCmds.getAttr(nodes2[i]+'.tz'), 4) def testStaticIKRW(self): name = createJoints() MayaCmds.ikHandle(sj=name, ee='joint4') MayaCmds.move(-1.040057, -7.278225, 6.498725, r=True) # write to file self.__files.append(util.expandFileName('testStaticIK.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (name, self.__files[-1])) MayaCmds.select(name) MayaCmds.group(name='original') # read from file MayaCmds.AbcImport(self.__files[-1], mode='import') # make sure the translate and rotation are the same nodes1 = ["|original|joint1", "|original|joint1|joint2", "|original|joint1|joint2|joint3", "|original|joint1|joint2|joint3|joint4"] nodes2 = ["|joint1", "|joint1|joint2", "|joint1|joint2|joint3", "|joint1|joint2|joint3|joint4"] for i in range(0, 4): self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tx'), MayaCmds.getAttr(nodes2[i]+'.tx'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.ty'), MayaCmds.getAttr(nodes2[i]+'.ty'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tz'), MayaCmds.getAttr(nodes2[i]+'.tz'), 4) def testAnimIKRW(self): name = createJoints() handleName = MayaCmds.ikHandle(sj=name, ee='joint4')[0] MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(handleName, breakdown=0, hierarchy='none', controlPoints=False, shape=False) MayaCmds.currentTime(16, update=True) MayaCmds.move(-1.040057, -7.278225, 6.498725, r=True) MayaCmds.setKeyframe(handleName, breakdown=0, hierarchy='none', controlPoints=False, shape=False) self.__files.append(util.expandFileName('testAnimIKRW.abc')) self.__files.append(util.expandFileName('testAnimIKRW01_08.abc')) self.__files.append(util.expandFileName('testAnimIKRW09-16.abc')) # write to files MayaCmds.AbcExport(j='-fr 1 8 -root %s -f %s' % (name, self.__files[-2])) MayaCmds.AbcExport(j='-fr 9 16 -root %s -f %s' % (name, self.__files[-1])) MayaCmds.select(name) MayaCmds.group(name='original') subprocess.call(self.__abcStitcher + self.__files[-3:]) # read from file MayaCmds.AbcImport(self.__files[-3], mode='import') # make sure the translate and rotation are the same nodes1 = ["|original|joint1", "|original|joint1|joint2", "|original|joint1|joint2|joint3", "|original|joint1|joint2|joint3|joint4"] nodes2 = ["|joint1", "|joint1|joint2", "|joint1|joint2|joint3", "|joint1|joint2|joint3|joint4"] for t in range(1, 25): MayaCmds.currentTime(t, update=True) for i in range(0, 4): self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tx'), MayaCmds.getAttr(nodes2[i]+'.tx'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.ty'), MayaCmds.getAttr(nodes2[i]+'.ty'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tz'), MayaCmds.getAttr(nodes2[i]+'.tz'), 4)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds from maya import mel as Mel import os import unittest import util def makeRobot(): MayaCmds.polyCube(name="head") MayaCmds.move(0, 4, 0, r=1) MayaCmds.polyCube(name="chest") MayaCmds.scale(2, 2.5, 1) MayaCmds.move(0, 2, 0, r=1) MayaCmds.polyCube(name="leftArm") MayaCmds.move(0, 3, 0, r=1) MayaCmds.scale(2, 0.5, 1, r=1) MayaCmds.duplicate(name="rightArm") MayaCmds.select("leftArm") MayaCmds.move(1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, 32, r=1, os=1) MayaCmds.select("rightArm") MayaCmds.move(-1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, -32, r=1, os=1) MayaCmds.select("rightArm", "leftArm", "chest", r=1) MayaCmds.group(name="body") MayaCmds.polyCube(name="bottom") MayaCmds.scale(2, 0.5, 1) MayaCmds.move(0, 0.5, 0, r=1) MayaCmds.polyCube(name="leftLeg") MayaCmds.scale(0.65, 2.8, 1, r=1) MayaCmds.move(-0.5, -1, 0, r=1) MayaCmds.duplicate(name="rightLeg") MayaCmds.move(1, 0, 0, r=1) MayaCmds.select("rightLeg", "leftLeg", "bottom", r=1) MayaCmds.group(name="lower") MayaCmds.select("head", "body", "lower", r=1) MayaCmds.group(name="robot") def makeRobotAnimated(): makeRobot() #change pivot point of arms and legs MayaCmds.move(0.65, -0.40, 0, 'rightArm.scalePivot', 'rightArm.rotatePivot', relative=True) MayaCmds.move(-0.65, -0.40, 0, 'leftArm.scalePivot', 'leftArm.rotatePivot', relative=True) MayaCmds.move(0, 1.12, 0, 'rightLeg.scalePivot', 'rightLeg.rotatePivot', relative=True) MayaCmds.move(0, 1.12, 0, 'leftLeg.scalePivot', 'leftLeg.rotatePivot', relative=True) MayaCmds.setKeyframe('leftLeg', at='rotateX', value=25, t=[1, 12]) MayaCmds.setKeyframe('leftLeg', at='rotateX', value=-40, t=[6]) MayaCmds.setKeyframe('rightLeg', at='scaleY', value=2.8, t=[1, 12]) MayaCmds.setKeyframe('rightLeg', at='scaleY', value=5.0, t=[6]) MayaCmds.setKeyframe('leftArm', at='rotateZ', value=55, t=[1, 12]) MayaCmds.setKeyframe('leftArm', at='rotateZ', value=-50, t=[6]) MayaCmds.setKeyframe('rightArm', at='scaleX', value=0.5, t=[1, 12]) MayaCmds.setKeyframe('rightArm', at='scaleX', value=3.6, t=[6]) def drawBBox(llx, lly, llz, urx, ury, urz): # delete the old bounding box if MayaCmds.objExists('bbox'): MayaCmds.delete('bbox') p0 = (llx, lly, urz) p1 = (urx, lly, urz) p2 = (urx, lly, llz) p3 = (llx, lly, llz) p4 = (llx, ury, urz) p5 = (urx, ury, urz) p6 = (urx, ury, llz) p7 = (llx, ury, llz) MayaCmds.curve(d=1, p=[p0, p1]) MayaCmds.curve(d=1, p=[p1, p2]) MayaCmds.curve(d=1, p=[p2, p3]) MayaCmds.curve(d=1, p=[p3, p0]) MayaCmds.curve(d=1, p=[p4, p5]) MayaCmds.curve(d=1, p=[p5, p6]) MayaCmds.curve(d=1, p=[p6, p7]) MayaCmds.curve(d=1, p=[p7, p4]) MayaCmds.curve(d=1, p=[p0, p4]) MayaCmds.curve(d=1, p=[p1, p5]) MayaCmds.curve(d=1, p=[p2, p6]) MayaCmds.curve(d=1, p=[p3, p7]) MayaCmds.select(MayaCmds.ls("curve?")) MayaCmds.select(MayaCmds.ls("curve??"), add=True) MayaCmds.group(name="bbox") class callbackTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testMelPerFrameCallbackFlag(self): makeRobotAnimated() # make a non-zero transform on top of it MayaCmds.select('robot') MayaCmds.group(n='parent') MayaCmds.setAttr('parent.tx', 5) MayaCmds.setAttr('parent.ty', 3.15) MayaCmds.setAttr('parent.tz', 0.8) MayaCmds.setAttr('parent.rx', 2) MayaCmds.setAttr('parent.ry', 90) MayaCmds.setAttr('parent.rz', 1) MayaCmds.setAttr('parent.sx', 0.9) MayaCmds.setAttr('parent.sy', 1.1) MayaCmds.setAttr('parent.sz', 0.5) # create a camera looking at the robot camNames = MayaCmds.camera() MayaCmds.move(50.107, 20.968, 5.802, r=True) MayaCmds.rotate(-22.635, 83.6, 0, r=True) MayaCmds.camera(camNames[1], e=True, centerOfInterest=55.336, focalLength=50, horizontalFilmAperture=0.962, verticalFilmAperture=0.731) MayaCmds.rename(camNames[0], "cam_master") MayaCmds.setKeyframe('cam_master', t=[1, 12]) __builtins__['bboxDict'] = {} self.__files.append(util.expandFileName('pyPerFrameTest.abc')) MayaCmds.AbcExport(j='-fr 1 12 -pfc bboxDict[#FRAME#]=#BOUNDSARRAY# -root robot -file ' + self.__files[-1]) # push the numbers into a flat list array = [] for i in range(1, 13): array.append(bboxDict[i][0]) array.append(bboxDict[i][1]) array.append(bboxDict[i][2]) array.append(bboxDict[i][3]) array.append(bboxDict[i][4]) array.append(bboxDict[i][5]) bboxList_worldSpaceOff = [ -1.10907, -2.4, -1.51815, 1.8204, 4.5, 0.571487, -1.64677, -2.85936, -0.926652, 2.24711, 4.5, 0.540761, -2.25864, -3.38208, -0.531301, 2.37391, 4.5, 0.813599, -2.83342, -3.87312, -0.570038, 2.3177, 4.5, 1.45821, -3.25988, -4.23744, -0.569848, 2.06639, 4.5, 1.86489, -3.42675, -4.38, -0.563003, 1.92087, 4.5, 2.00285, -3.30872, -4.27917, -0.568236, 2.02633, 4.5, 1.9066, -2.99755, -4.01333, -0.572918, 2.24279, 4.5, 1.62326, -2.55762, -3.6375, -0.556938, 2.3781, 4.5, 1.16026, -2.05331, -3.20667, -0.507072, 2.37727, 4.5, 0.564985, -1.549, -2.77583, -1.04022, 2.18975, 4.5, 0.549216, -1.10907, -2.4, -1.51815, 1.8204, 4.5, 0.571487] self.failUnlessEqual(len(array), len(bboxList_worldSpaceOff)) for i in range(0, len(array)): self.failUnlessAlmostEqual(array[i], bboxList_worldSpaceOff[i], 4, '%d element in bbox array does not match.' % i) # test the bounding box calculation when worldSpace flag is on __builtins__['bboxDict'] = {} self.__files.append(util.expandFileName('pyPerFrameWorldspaceTest.abc')) MayaCmds.AbcExport(j='-fr 1 12 -ws -pfc bboxDict[#FRAME#]=#BOUNDSARRAY# -root robot -file ' + self.__files[-1]) # push the numbers into a flat list array = [] for i in range(1, 13): array.append(bboxDict[i][0]) array.append(bboxDict[i][1]) array.append(bboxDict[i][2]) array.append(bboxDict[i][3]) array.append(bboxDict[i][4]) array.append(bboxDict[i][5]) bboxList_worldSpaceOn = [ 4.77569, 0.397085, -0.991594, 5.90849, 7.99465, 1.64493, 5.06518, -0.108135, -1.37563, 5.90849, 7.99465, 2.12886, 5.25725, -0.683039, -1.48975, 5.9344, 7.99465, 2.67954, 5.24782, -1.223100, -1.43916, 6.26283, 7.99465, 3.19685, 5.24083, -1.62379, -1.21298, 6.47282, 7.99465, 3.58066, 5.23809, -1.78058, -1.08202, 6.54482, 7.99465, 3.73084, 5.24003, -1.66968, -1.17693, 6.49454, 7.99465, 3.62461, 5.24513, -1.37731, -1.37175, 6.34772, 7.99465, 3.34456, 5.25234, -0.963958, -1.49352, 6.11048, 7.99465, 2.94862, 5.26062, -0.490114, -1.49277, 5.90849, 7.99465, 2.49475, 5.00931, -0.0162691, -1.32401, 5.90849, 7.99465, 2.04087, 4.77569, 0.397085, -0.991594, 5.90849, 7.99465, 1.64493] self.failUnlessEqual(len(array), len(bboxList_worldSpaceOn)) for i in range(0, len(array)): self.failUnlessAlmostEqual(array[i], bboxList_worldSpaceOn[i], 4, '%d element in bbox array does not match.' % i) # test the bounding box calculation for camera __builtins__['bboxDict'] = {} self.__files.append(util.expandFileName('camPyPerFrameTest.abc')) MayaCmds.AbcExport(j='-fr 1 12 -pfc bboxDict[#FRAME#]=#BOUNDSARRAY# -root cam_master -file ' + self.__files[-1]) # push the numbers into a flat list ( since each frame is the same ) array = [] array.append(bboxDict[1][0]) array.append(bboxDict[1][1]) array.append(bboxDict[1][2]) array.append(bboxDict[1][3]) array.append(bboxDict[1][4]) array.append(bboxDict[1][5]) # cameras aren't included in the bounds bboxList_CAM = [0, 0, 0, 0, 0, 0] for i in range(0, len(array)): self.failUnlessAlmostEqual(array[i], bboxList_CAM[i], 4, '%d element in camera bbox array does not match.' % i)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import subprocess import unittest import util class AnimNurbsSurfaceTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__abcStitcher = [os.environ['AbcStitcher']] self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testAnimNurbsPlaneWrite(self): ret = MayaCmds.nurbsPlane(p=(0, 0, 0), ax=(0, 1, 0), w=1, lr=1, d=3, u=5, v=5, ch=0) name = ret[0] MayaCmds.lattice(name, dv=(4, 5, 4), oc=True) MayaCmds.select('ffd1Lattice.pt[1:2][0:4][1:2]', r=True) MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe() MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe() MayaCmds.currentTime(12, update=True) MayaCmds.move( 0, 0.18, 0, r=True) MayaCmds.scale( 2.5, 1.0, 2.5, r=True) MayaCmds.setKeyframe() MayaCmds.curveOnSurface(name, uv=((0.597523,0), (0.600359,0.271782), (0.538598,0.564218), (0.496932,0.779936), (0.672153,1)), k=(0,0,0,0.263463,0.530094,0.530094,0.530094)) curvename = MayaCmds.curveOnSurface(name, uv=((0.170718,0.565967), (0.0685088,0.393034), (0.141997,0.206296), (0.95,0.230359), (0.36264,0.441381), (0.251243,0.569889)), k=(0,0,0,0.200545,0.404853,0.598957,0.598957,0.598957)) MayaCmds.closeCurve(curvename, ch=1, ps=1, rpo=1, bb=0.5, bki=0, p=0.1, cos=1) MayaCmds.trim(name, lu=0.23, lv=0.39) degreeU = MayaCmds.getAttr(name+'.degreeU') degreeV = MayaCmds.getAttr(name+'.degreeV') spansU = MayaCmds.getAttr(name+'.spansU') spansV = MayaCmds.getAttr(name+'.spansV') formU = MayaCmds.getAttr(name+'.formU') formV = MayaCmds.getAttr(name+'.formV') minU = MayaCmds.getAttr(name+'.minValueU') maxU = MayaCmds.getAttr(name+'.maxValueU') minV = MayaCmds.getAttr(name+'.minValueV') maxV = MayaCmds.getAttr(name+'.maxValueV') MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', 'surfaceInfo1.inputSurface', force=True) MayaCmds.currentTime(1, update=True) controlPoints = MayaCmds.getAttr('surfaceInfo1.controlPoints[*]') knotsU = MayaCmds.getAttr('surfaceInfo1.knotsU[*]') knotsV = MayaCmds.getAttr('surfaceInfo1.knotsV[*]') MayaCmds.currentTime(12, update=True) controlPoints2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[*]') knotsU2 = MayaCmds.getAttr('surfaceInfo1.knotsU[*]') knotsV2 = MayaCmds.getAttr('surfaceInfo1.knotsV[*]') self.__files.append(util.expandFileName('testAnimNurbsPlane.abc')) self.__files.append(util.expandFileName('testAnimNurbsPlane01_14.abc')) self.__files.append(util.expandFileName('testAnimNurbsPlane15_24.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % (name, self.__files[-2])) MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % (name, self.__files[-1])) # use AbcStitcher to combine two files into one subprocess.call(self.__abcStitcher + self.__files[-3:]) # reading test MayaCmds.AbcImport(self.__files[-3], mode='open') self.failUnlessEqual(degreeU, MayaCmds.getAttr(name+'.degreeU')) self.failUnlessEqual(degreeV, MayaCmds.getAttr(name+'.degreeV')) self.failUnlessEqual(spansU, MayaCmds.getAttr(name+'.spansU')) self.failUnlessEqual(spansV, MayaCmds.getAttr(name+'.spansV')) self.failUnlessEqual(formU, MayaCmds.getAttr(name+'.formU')) self.failUnlessEqual(formV, MayaCmds.getAttr(name+'.formV')) self.failUnlessEqual(minU, MayaCmds.getAttr(name+'.minValueU')) self.failUnlessEqual(maxU, MayaCmds.getAttr(name+'.maxValueU')) self.failUnlessEqual(minV, MayaCmds.getAttr(name+'.minValueV')) self.failUnlessEqual(maxV, MayaCmds.getAttr(name+'.maxValueV')) MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', 'surfaceInfo1.inputSurface', force=True) MayaCmds.currentTime(1, update=True) errmsg = "At frame #1, Nurbs Plane's control point #%d.%s not equal" for i in range(0, len(controlPoints)): cp1 = controlPoints[i] cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % (i)) self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, 'x')) self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, 'y')) self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, 'z')) errmsg = "At frame #1, Nurbs Plane's control knotsU #%d not equal" for i in range(0, len(knotsU)): ku1 = knotsU[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % (i)) self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i)) errmsg = "At frame #1, Nurbs Plane's control knotsV #%d not equal" for i in range(0, len(knotsV)): kv1 = knotsV[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % (i)) self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i)) MayaCmds.currentTime(12, update=True) errmsg = "At frame #12, Nurbs Plane's control point #%d.%s not equal" for i in range(0, len(controlPoints2)): cp1 = controlPoints2[i] cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % (i)) self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, 'x')) self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, 'y')) self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, 'z')) errmsg = "At frame #12, Nurbs Plane's control knotsU #%d not equal" for i in range(0, len(knotsU2)): ku1 = knotsU2[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % (i)) self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i)) errmsg = "At frame #12, Nurbs Plane's control knotsV #%d not equal" for i in range(0, len(knotsV2)): kv1 = knotsV2[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % (i)) self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i)) MayaCmds.currentTime(24, update=True) errmsg = "At frame #24, Nurbs Plane's control point #%d.%s not equal" for i in range(0, len(controlPoints)): cp1 = controlPoints[i] cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % (i)) self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, 'x')) self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, 'y')) self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, 'z')) errmsg = "At frame #24, Nurbs Plane's control knotsU #%d not equal" for i in range(0, len(knotsU)): ku1 = knotsU[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % (i)) self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i)) errmsg = "At frame #24, Nurbs Plane's control knotsV #%d not equal" for i in range(0, len(knotsV)): kv1 = knotsV[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % (i)) self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import subprocess import unittest import util def createLocator(): shape = MayaCmds.createNode("locator") name = MayaCmds.pickWalk(shape, d="up") MayaCmds.setAttr(shape+'.localPositionX', 0.962) MayaCmds.setAttr(shape+'.localPositionY', 0.731) MayaCmds.setAttr(shape+'.localPositionZ', 5.114) MayaCmds.setAttr(shape+'.localScaleX', 5) MayaCmds.setAttr(shape+'.localScaleY', 1.44) MayaCmds.setAttr(shape+'.localScaleZ', 1.38) return name[0], shape class locatorTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] self.__abcStitcher = [os.environ['AbcStitcher']] def tearDown(self): for f in self.__files: os.remove(f) def testStaticLocatorRW(self): name = createLocator() # write to file self.__files.append(util.expandFileName('testStaticLocatorRW.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (name[0], self.__files[-1])) # read from file MayaCmds.AbcImport(self.__files[-1], mode='import') locatorList = MayaCmds.ls(type='locator') self.failUnless(util.compareLocator(locatorList[0], locatorList[1])) def testAnimLocatorRW(self): name = createLocator() MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(name[1], attribute='localPositionX') MayaCmds.setKeyframe(name[1], attribute='localPositionY') MayaCmds.setKeyframe(name[1], attribute='localPositionZ') MayaCmds.setKeyframe(name[1], attribute='localScaleX') MayaCmds.setKeyframe(name[1], attribute='localScaleY') MayaCmds.setKeyframe(name[1], attribute='localScaleZ') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe(name[1], attribute='localPositionX', value=0.0) MayaCmds.setKeyframe(name[1], attribute='localPositionY', value=0.0) MayaCmds.setKeyframe(name[1], attribute='localPositionZ', value=0.0) MayaCmds.setKeyframe(name[1], attribute='localScaleX', value=1.0) MayaCmds.setKeyframe(name[1], attribute='localScaleY', value=1.0) MayaCmds.setKeyframe(name[1], attribute='localScaleZ', value=1.0) self.__files.append(util.expandFileName('testAnimLocatorRW.abc')) self.__files.append(util.expandFileName('testAnimLocatorRW01_14.abc')) self.__files.append(util.expandFileName('testAnimLocatorRW15-24.abc')) # write to files MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % (name[0], self.__files[-2])) MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % (name[0], self.__files[-1])) subprocess.call(self.__abcStitcher + self.__files[-3:]) # read from file MayaCmds.AbcImport(self.__files[-3], mode='import') locatorList = MayaCmds.ls(type='locator') for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareLocator(locatorList[0], locatorList[1]): self.fail('%s and %s are not the same at frame %d' % (locatorList[0], locatorList[1], t))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class emptyMeshTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testEmptyMeshFlag(self): MayaCmds.createNode('mesh', name='mesh') MayaCmds.rename('|polySurface1', 'trans') self.__files.append(util.expandFileName('emptyMeshTest.abc')) MayaCmds.AbcExport(j='-root trans -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') self.failUnless(MayaCmds.objExists("trans")) self.failIf(MayaCmds.objExists("head"))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class TransformTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticTransformReadWrite(self): nodeName1 = MayaCmds.polyCube() nodeName2 = MayaCmds.duplicate() nodeName3 = MayaCmds.duplicate() self.__files.append(util.expandFileName('reparentflag.abc')) MayaCmds.AbcExport(j='-root %s -root %s -root %s -file %s' % (nodeName1[0], nodeName2[0], nodeName3[0], self.__files[-1])) # reading test MayaCmds.file(new=True, force=True) MayaCmds.createNode('transform', n='root') MayaCmds.AbcImport(self.__files[-1], mode='import', reparent='root') self.failUnlessEqual(MayaCmds.objExists('root|'+nodeName1[0]), 1) self.failUnlessEqual(MayaCmds.objExists('root|'+nodeName2[0]), 1) self.failUnlessEqual(MayaCmds.objExists('root|'+nodeName3[0]), 1)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class AnimPointPrimitiveTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testAnimPointPrimitiveReadWrite(self): # Creates a point emitter. MayaCmds.emitter(dx=1, dy=0, dz=0, sp=0.33, pos=(1, 1, 1), n='myEmitter') MayaCmds.particle(n='emittedParticles') MayaCmds.setAttr('emittedParticles.lfm', 2) MayaCmds.setAttr('emittedParticles.lifespan', 50) MayaCmds.setAttr('emittedParticles.lifespanRandom', 2) MayaCmds.connectDynamic('emittedParticles', em='myEmitter') self.__files.append(util.expandFileName('testAnimParticleReadWrite.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root emittedParticles -file ' + self.__files[-1]) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') # reading animated point clouds into Maya aren't fully supported # yet which is why we don't have any checks on the data here
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest class AbcExport_dupRootsTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) def testStaticTransformReadWrite(self): MayaCmds.polyCube(n='cube') MayaCmds.group(n='group1') MayaCmds.duplicate() self.failUnlessRaises(RuntimeError, MayaCmds.AbcExport, j='-root group1|cube -root group2|cube -f dupRoots.abc') # the abc file shouldn't exist self.failUnless(not os.path.isfile('dupRoots.abc'))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import subprocess import unittest import util class AnimMeshTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__abcStitcher = [os.environ['AbcStitcher']] self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testAnimSPT_HwColor_ReadWrite(self): numFaces = 6 numVertices = 8 numFaceConnects = 24 vtx_1 = OpenMaya.MFloatPoint(-0.5, -0.5, -0.5) vtx_2 = OpenMaya.MFloatPoint( 0.5, -0.5, -0.5) vtx_3 = OpenMaya.MFloatPoint( 0.5, -0.5, 0.5) vtx_4 = OpenMaya.MFloatPoint(-0.5, -0.5, 0.5) vtx_5 = OpenMaya.MFloatPoint(-0.5, 0.5, -0.5) vtx_6 = OpenMaya.MFloatPoint(-0.5, 0.5, 0.5) vtx_7 = OpenMaya.MFloatPoint( 0.5, 0.5, 0.5) vtx_8 = OpenMaya.MFloatPoint( 0.5, 0.5, -0.5) points = OpenMaya.MFloatPointArray() points.setLength(8) points.set(vtx_1, 0) points.set(vtx_2, 1) points.set(vtx_3, 2) points.set(vtx_4, 3) points.set(vtx_5, 4) points.set(vtx_6, 5) points.set(vtx_7, 6) points.set(vtx_8, 7) faceConnects = OpenMaya.MIntArray() faceConnects.setLength(numFaceConnects) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) faceConnects.set(4, 4) faceConnects.set(5, 5) faceConnects.set(6, 6) faceConnects.set(7, 7) faceConnects.set(3, 8) faceConnects.set(2, 9) faceConnects.set(6, 10) faceConnects.set(5, 11) faceConnects.set(0, 12) faceConnects.set(3, 13) faceConnects.set(5, 14) faceConnects.set(4, 15) faceConnects.set(0, 16) faceConnects.set(4, 17) faceConnects.set(7, 18) faceConnects.set(1, 19) faceConnects.set(1, 20) faceConnects.set(7, 21) faceConnects.set(6, 22) faceConnects.set(2, 23) faceCounts = OpenMaya.MIntArray() faceCounts.setLength(6) faceCounts.set(4, 0) faceCounts.set(4, 1) faceCounts.set(4, 2) faceCounts.set(4, 3) faceCounts.set(4, 4) faceCounts.set(4, 5) transFn = OpenMaya.MFnTransform() parent = transFn.create() transFn.setName('poly') meshFn = OpenMaya.MFnMesh() meshFn.create(numVertices, numFaces, points, faceCounts, faceConnects, parent) shapeName = 'polyShape' meshFn.setName(shapeName) # add SPT_HwColor attributes MayaCmds.select( shapeName ) MayaCmds.addAttr(longName='SPT_HwColor', usedAsColor=True, attributeType='float3') MayaCmds.addAttr(longName='SPT_HwColorR', attributeType='float', parent='SPT_HwColor') MayaCmds.addAttr(longName='SPT_HwColorG', attributeType='float', parent='SPT_HwColor') MayaCmds.addAttr(longName='SPT_HwColorB', attributeType='float', parent='SPT_HwColor') # set colors MayaCmds.setAttr(shapeName+'.SPT_HwColor', 0.50, 0.15, 0.75, type='float3') MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe('polyShape.vtx[0:7]') # colors MayaCmds.setKeyframe( shapeName+'.SPT_HwColor') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe('polyShape.vtx[0:7]') # colors MayaCmds.setKeyframe( shapeName+'.SPT_HwColor') MayaCmds.currentTime(12, update=True) vtx_11 = OpenMaya.MFloatPoint(-1.0, -1.0, -1.0) vtx_22 = OpenMaya.MFloatPoint( 1.0, -1.0, -1.0) vtx_33 = OpenMaya.MFloatPoint( 1.0, -1.0, 1.0) vtx_44 = OpenMaya.MFloatPoint(-1.0, -1.0, 1.0) vtx_55 = OpenMaya.MFloatPoint(-1.0, 1.0, -1.0) vtx_66 = OpenMaya.MFloatPoint(-1.0, 1.0, 1.0) vtx_77 = OpenMaya.MFloatPoint( 1.0, 1.0, 1.0) vtx_88 = OpenMaya.MFloatPoint( 1.0, 1.0, -1.0) points.set(vtx_11, 0) points.set(vtx_22, 1) points.set(vtx_33, 2) points.set(vtx_44, 3) points.set(vtx_55, 4) points.set(vtx_66, 5) points.set(vtx_77, 6) points.set(vtx_88, 7) meshFn.setPoints(points) MayaCmds.setAttr( shapeName+'.SPT_HwColor', 0.15, 0.5, 0.15, type='float3') MayaCmds.setKeyframe('polyShape.vtx[0:7]') # colors MayaCmds.setKeyframe( shapeName+'.SPT_HwColor') self.__files.append(util.expandFileName('animSPT_HwColor.abc')) self.__files.append(util.expandFileName('animSPT_HwColor_01_14.abc')) self.__files.append(util.expandFileName('animSPT_HwColor_15_24.abc')) MayaCmds.AbcExport(j='-atp SPT_ -fr 1 14 -root poly -file ' + self.__files[-2]) MayaCmds.AbcExport(j='-atp SPT_ -fr 15 24 -root poly -file ' + self.__files[-1]) subprocess.call(self.__abcStitcher + self.__files[-3:]) # reading test MayaCmds.AbcImport(self.__files[-3], mode='open') places = 7 # check colors MayaCmds.currentTime(1, update=True) colorVec_1 = MayaCmds.getAttr(shapeName+'.SPT_HwColor')[0] self.failUnlessAlmostEqual(colorVec_1[0], 0.50, places) self.failUnlessAlmostEqual(colorVec_1[1], 0.15, places) self.failUnlessAlmostEqual(colorVec_1[2], 0.75, places) MayaCmds.currentTime(2, update=True) # only needed for interpolation test on frame 1.422 colorVec_2 = MayaCmds.getAttr(shapeName+'.SPT_HwColor')[0] setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) colorVec = MayaCmds.getAttr(shapeName+'.SPT_HwColor')[0] self.failUnlessAlmostEqual(colorVec[0], (1-alpha)*colorVec_1[0]+alpha*colorVec_2[0], places) self.failUnlessAlmostEqual(colorVec[1], (1-alpha)*colorVec_1[1]+alpha*colorVec_2[1], places) self.failUnlessAlmostEqual(colorVec[2], (1-alpha)*colorVec_1[2]+alpha*colorVec_2[2], places) MayaCmds.currentTime(12, update=True) colorVec = MayaCmds.getAttr( shapeName+'.SPT_HwColor' )[0] self.failUnlessAlmostEqual( colorVec[0], 0.15, places) self.failUnlessAlmostEqual( colorVec[1], 0.50, places) self.failUnlessAlmostEqual( colorVec[2], 0.15, places) MayaCmds.currentTime(24, update=True) colorVec = MayaCmds.getAttr(shapeName+'.SPT_HwColor')[0] self.failUnlessAlmostEqual(colorVec[0], 0.50, places) self.failUnlessAlmostEqual(colorVec[1], 0.15, places) self.failUnlessAlmostEqual(colorVec[2], 0.75, places)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class StaticPointPrimitiveTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testPointPrimitiveReadWrite(self): # Creates a particle object with four particles name = MayaCmds.particle( p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9)]) posVec = [0, 0, 0, 3, 5, 6, 5, 6, 7, 9, 9, 9] self.__files.append(util.expandFileName('testPointPrimitiveReadWrite.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (name[0], self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') pos = MayaCmds.getAttr(name[1] + '.position') ids = MayaCmds.getAttr(name[1] + '.particleId') self.failUnlessEqual(len(ids), 4) for i in range(0, 4): index = 3*i self.failUnlessAlmostEqual(pos[i][0], posVec[index], 4) self.failUnlessAlmostEqual(pos[i][1], posVec[index+1], 4) self.failUnlessAlmostEqual(pos[i][2], posVec[index+2], 4)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class LoadWorldSpaceTranslateJobTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticLoadWorldSpaceTranslateJobReadWrite(self): nodeName = MayaCmds.polyCube(n='cube') root = nodeName[0] MayaCmds.setAttr(root+'.rotateX', 45) MayaCmds.setAttr(root+'.scaleX', 1.5) MayaCmds.setAttr(root+'.translateY', -1.95443) nodeName = MayaCmds.group() MayaCmds.setAttr(nodeName+'.rotateY', 15) MayaCmds.setAttr(nodeName+'.translateY', -3.95443) nodeName = MayaCmds.group() MayaCmds.setAttr(nodeName+'.rotateZ',-90) MayaCmds.setAttr(nodeName+'.shearXZ',2.555) self.__files.append(util.expandFileName('testStaticLoadWorldSpaceTranslateJob.abc')) MayaCmds.AbcExport(j='-ws -root %s -file %s' % (root, self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateX'), 3) self.failUnlessAlmostEqual(-5.909, MayaCmds.getAttr(root+'.translateY'), 3) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateZ'), 3) self.failUnlessAlmostEqual(68.211, MayaCmds.getAttr(root+'.rotateX'), 3) self.failUnlessAlmostEqual(40.351, MayaCmds.getAttr(root+'.rotateY'), 3) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr(root+'.rotateZ'), 3) self.failUnlessAlmostEqual(0.600, MayaCmds.getAttr(root+'.scaleX'), 3) self.failUnlessAlmostEqual(1.905, MayaCmds.getAttr(root+'.scaleY'), 3) self.failUnlessAlmostEqual(1.313, MayaCmds.getAttr(root+'.scaleZ'), 3) self.failUnlessAlmostEqual(0.539, MayaCmds.getAttr(root+'.shearXY'), 3) self.failUnlessAlmostEqual(0.782, MayaCmds.getAttr(root+'.shearXZ'), 3) self.failUnlessAlmostEqual(1.051, MayaCmds.getAttr(root+'.shearYZ'), 3) def testAnimLoadWorldSpaceTranslateJobReadWrite(self): nodeName = MayaCmds.polyCube(n='cube') root = nodeName[0] MayaCmds.setAttr(root+'.rotateX', 45) MayaCmds.setAttr(root+'.scaleX', 1.5) MayaCmds.setAttr(root+'.translateY', -1.95443) MayaCmds.setKeyframe(root, value=0, attribute='translateX', t=[1, 24]) MayaCmds.setKeyframe(root, value=1, attribute='translateX', t=12) nodeName = MayaCmds.group() MayaCmds.setAttr(nodeName+'.rotateY', 15) MayaCmds.setAttr(nodeName+'.translateY', -3.95443) nodeName = MayaCmds.group() MayaCmds.setAttr(nodeName+'.rotateZ',-90) MayaCmds.setAttr(nodeName+'.shearXZ',2.555) self.__files.append(util.expandFileName('testAnimLoadWorldSpaceTranslateJob.abc')) MayaCmds.AbcExport(j='-fr 1 24 -ws -root %s -file %s' % (root, self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') # frame 1 MayaCmds.currentTime(1, update=True) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateX'), 3) self.failUnlessAlmostEqual(-5.909, MayaCmds.getAttr(root+'.translateY'), 3) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateZ'), 3) self.failUnlessAlmostEqual(68.211, MayaCmds.getAttr(root+'.rotateX'), 3) self.failUnlessAlmostEqual(40.351, MayaCmds.getAttr(root+'.rotateY'), 3) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr(root+'.rotateZ'), 3) self.failUnlessAlmostEqual(0.600, MayaCmds.getAttr(root+'.scaleX'), 3) self.failUnlessAlmostEqual(1.905, MayaCmds.getAttr(root+'.scaleY'), 3) self.failUnlessAlmostEqual(1.313, MayaCmds.getAttr(root+'.scaleZ'), 3) self.failUnlessAlmostEqual(0.539, MayaCmds.getAttr(root+'.shearXY'), 3) self.failUnlessAlmostEqual(0.782, MayaCmds.getAttr(root+'.shearXZ'), 3) self.failUnlessAlmostEqual(1.051, MayaCmds.getAttr(root+'.shearYZ'), 3) # frame 12 MayaCmds.currentTime(12, update=True) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateX'), 3) self.failUnlessAlmostEqual(-6.2135, MayaCmds.getAttr(root+'.translateY'), 3) self.failUnlessAlmostEqual(-0.258819, MayaCmds.getAttr(root+'.translateZ'), 3) self.failUnlessAlmostEqual(68.211, MayaCmds.getAttr(root+'.rotateX'), 3) self.failUnlessAlmostEqual(40.351, MayaCmds.getAttr(root+'.rotateY'), 3) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr(root+'.rotateZ'), 3) self.failUnlessAlmostEqual(0.600, MayaCmds.getAttr(root+'.scaleX'), 3) self.failUnlessAlmostEqual(1.905, MayaCmds.getAttr(root+'.scaleY'), 3) self.failUnlessAlmostEqual(1.313, MayaCmds.getAttr(root+'.scaleZ'), 3) self.failUnlessAlmostEqual(0.539, MayaCmds.getAttr(root+'.shearXY'), 3) self.failUnlessAlmostEqual(0.782, MayaCmds.getAttr(root+'.shearXZ'), 3) self.failUnlessAlmostEqual(1.051, MayaCmds.getAttr(root+'.shearYZ'), 3) # frame 24 MayaCmds.currentTime(24, update=True) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateX'), 3) self.failUnlessAlmostEqual(-5.909, MayaCmds.getAttr(root+'.translateY'), 3) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateZ'), 3) self.failUnlessAlmostEqual(68.211, MayaCmds.getAttr(root+'.rotateX'), 3) self.failUnlessAlmostEqual(40.351, MayaCmds.getAttr(root+'.rotateY'), 3) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr(root+'.rotateZ'), 3) self.failUnlessAlmostEqual(0.600, MayaCmds.getAttr(root+'.scaleX'), 3) self.failUnlessAlmostEqual(1.905, MayaCmds.getAttr(root+'.scaleY'), 3) self.failUnlessAlmostEqual(1.313, MayaCmds.getAttr(root+'.scaleZ'), 3) self.failUnlessAlmostEqual(0.539, MayaCmds.getAttr(root+'.shearXY'), 3) self.failUnlessAlmostEqual(0.782, MayaCmds.getAttr(root+'.shearXZ'), 3) self.failUnlessAlmostEqual(1.051, MayaCmds.getAttr(root+'.shearYZ'), 3)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util def checkEqualRotate(test, nodeName1, nodeName2, precision): test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1 + '.rotateX'), MayaCmds.getAttr(nodeName2 + '.rotateX'), precision) test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1 + '.rotateY'), MayaCmds.getAttr(nodeName2 + '.rotateY'), precision) test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1 + '.rotateZ'), MayaCmds.getAttr(nodeName2 + '.rotateZ'), precision) def checkEqualTranslate(test, nodeName1, nodeName2, precision): test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1 + '.translateX'), MayaCmds.getAttr(nodeName2 + '.translateX'), precision) test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1 + '.translateY'), MayaCmds.getAttr(nodeName2 + '.translateY'), precision) test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1+'.translateZ'), MayaCmds.getAttr(nodeName2 + '.translateZ'), precision) def createStaticSolarSystem(): MayaCmds.file(new=True, force=True) moon = MayaCmds.polySphere( radius=0.5, name="moon" )[0] MayaCmds.move( -5, 0.0, 0.0, r=1 ) earth = MayaCmds.polySphere( radius=2, name="earth" )[0] MayaCmds.select( moon, earth ) MayaCmds.group(name='group1') MayaCmds.polySphere( radius=5, name="sun" )[0] MayaCmds.move( 25, 0.0, 0.0, r=1 ) MayaCmds.group(name='group2') def createAnimatedSolarSystem(): MayaCmds.file(new=True, force=True) moon = MayaCmds.polySphere(radius=0.5, name="moon")[0] MayaCmds.move(-5, 0.0, 0.0, r=1) earth = MayaCmds.polySphere(radius=2, name="earth")[0] MayaCmds.select(moon, earth) MayaCmds.group(name='group1') MayaCmds.polySphere(radius=5, name="sun")[0] MayaCmds.move(25, 0.0, 0.0, r=1) MayaCmds.group(name='group2') # the sun's simplified self-rotation MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe('sun', at='rotateY', v=0) MayaCmds.currentTime(240, update=True) MayaCmds.setKeyframe('sun', at='rotateY', v=360) # the earth rotate around the sun MayaCmds.expression( s='$angle = (frame-91)/180*3.1415;\n\ earth.translateX = 25+25*sin($angle)') MayaCmds.expression( s='$angle = (frame-91)/180*3.1415;\n\ earth.translateZ = 25*cos($angle)') # the moon rotate around the earth MayaCmds.expression( s='$angle = (frame-91)/180*3.1415+frame;\n\ moon.translateX = earth.translateX+5*sin($angle)') MayaCmds.expression( s='$angle = (frame-91)/180*3.1415+frame;\n\ moon.translateZ = earth.translateZ+5*cos($angle)') class AbcImportSwapTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] # write out an animated Alembic file createAnimatedSolarSystem() self.__files.append(util.expandFileName('testAnimatedSolarSystem.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root group1 -root group2 -file ' + self.__files[-1]) # write out a static Alembic file that's different than the static scene # created by createStaticSolarSystem() MayaCmds.currentTime(12, update=True) self.__files.append(util.expandFileName('testStaticSolarSystem.abc')) MayaCmds.AbcExport(j='-fr 12 12 -root group1 -root group2 -file ' + self.__files[-1]) # write out an animated mesh with animated parent transform node MayaCmds.polyPlane(sx=2, sy=2, w=1, h=1, ch=0, n='polyMesh') MayaCmds.createNode('transform', n='group') MayaCmds.parent('polyMesh', 'group') # key the transform node MayaCmds.setKeyframe('group', attribute='translate', t=[1, 4]) MayaCmds.move(0.36, 0.72, 0.36) MayaCmds.setKeyframe('group', attribute='translate', t=2) #key the mesh node MayaCmds.select('polyMesh.vtx[0:8]') MayaCmds.setKeyframe(t=[1, 4]) MayaCmds.scale(0.1, 0.1, 0.1, r=True) MayaCmds.setKeyframe(t=2) self.__files.append(util.expandFileName('testAnimatedMesh.abc')) MayaCmds.AbcExport(j='-fr 1 4 -root group -file ' + self.__files[-1]) MayaCmds.file(new=True, force=True) def tearDown(self): for f in self.__files : os.remove(f) def testStaticSceneSwapInStaticAlembicTransform(self): createStaticSolarSystem() MayaCmds.AbcImport(self.__files[1], connect='/', debug=False ) # check the swapped scene is the same as frame #12 # tranform node moon self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateX'), -4.1942, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateZ'), 2.9429, 4) # transform node earth self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateX'), 0.4595, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateZ'), 4.7712, 4) # transform node sun self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateX'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateY'), 16.569, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateZ'), 0.0000, 4) def testStaticSceneSwapInAnimatedAbcTransform(self): createStaticSolarSystem() # swap in the animated hierarchy MayaCmds.AbcImport(self.__files[0], connect='/', debug=False) # this is loaded in for value comparison purpose only MayaCmds.AbcImport(self.__files[0], mode='import') # check the swapped scene at every frame for frame in range(1, 25): MayaCmds.currentTime(frame, update=True) # tranform node moon checkEqualTranslate(self, 'group1|moon', 'group3|moon', 4) # transform node earth checkEqualTranslate(self, 'group1|earth', 'group3|earth', 4) # transform node sun checkEqualRotate(self, 'group2|sun', 'group4|sun', 4) def testAnimatedSceneSwapInStaticAbcTransform(self): createAnimatedSolarSystem() MayaCmds.AbcImport(self.__files[1], connect='/') # check the swapped scene is the same as frame #12 # tranform node moon self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateX'), -4.1942, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateZ'), 2.9429, 4) # transform node earth self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateX'), 0.4595, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateZ'), 4.7712, 4) # transform node sun self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateX'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateY'), 16.569, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateZ'), 0.0000, 4) def testRemoveIfNoUpdate(self): createStaticSolarSystem() # add a few nodes that don't exist in the Alembic file MayaCmds.createNode('transform', name='saturn') MayaCmds.parent('saturn', 'group1') MayaCmds.createNode('transform', name='venus') MayaCmds.parent('venus', 'group2') MayaCmds.AbcImport(self.__files[1], connect='/', removeIfNoUpdate=True) # check if venus and saturn is deleted self.failUnlessEqual(MayaCmds.objExists('venus'), False) self.failUnlessEqual(MayaCmds.objExists('saturn'), False) # check the swapped scene is the same as frame #12 # tranform node moon self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateX'), -4.1942, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateZ'), 2.9429, 4) # transform node earth self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateX'), 0.4595, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateZ'), 4.7712, 4) # transform node sun self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateX'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateY'), 16.569, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateZ'), 0.0000, 4) def testCreateIfNotFound(self): createStaticSolarSystem() # delete some nodes MayaCmds.delete( 'sunShape' ) MayaCmds.delete( 'moon' ) MayaCmds.AbcImport(self.__files[1], connect='/', createIfNotFound=True) # check the swapped scene is the same as frame #12 # tranform node moon self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateX'), -4.1942, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateZ'), 2.9429, 4) # transform node earth self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateX'), 0.4595, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateZ'), 4.7712, 4) # transform node sun self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateX'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateY'), 16.569, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateZ'), 0.0000, 4) def testPartialSwap(self): createStaticSolarSystem() MayaCmds.AbcImport(self.__files[1], connect='group1', createIfNotFound=True) # check the swapped scene is the same as frame #12 # tranform node moon self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateX'), -4.1942, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateZ'), 2.9429, 4) # transform node earth self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateX'), 0.4595, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateZ'), 4.7712, 4) # transform node sun self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateX'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateZ'), 0.0000, 4) def testAnimatedMeshSwap(self): MayaCmds.polyPlane( sx=2, sy=2, w=1, h=1, ch=0, n='polyMesh') MayaCmds.createNode('transform', n='group') MayaCmds.parent('polyMesh', 'group') MayaCmds.AbcImport(self.__files[2], connect='group') # this is loaded in for value comparison purpose only MayaCmds.AbcImport(self.__files[2], mode='import') # check the swapped scene at every frame for frame in range(1, 4): MayaCmds.currentTime(frame, update=True) # tranform node group checkEqualTranslate(self, 'group', 'group1', 4) # tranform node group checkEqualTranslate(self, 'group|polyMesh', 'group1|polyMesh', 4) # mesh node polyMesh for index in range(0, 9): string1 = 'group|polyMesh.vt[%d]' % index string2 = 'group1|polyMesh.vt[%d]' % index self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][0], MayaCmds.getAttr(string2)[0][0], 4, '%s.x != %s.x' % (string1, string2)) self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][1], MayaCmds.getAttr(string2)[0][1], 4, '%s.y != %s.y' % (string1, string2)) self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][2], MayaCmds.getAttr(string2)[0][2], 4, '%s.z != %s.z' % (string1, string2)) def testMeshTopoChange(self): MayaCmds.polySphere( sx=10, sy=15, r=0, n='polyMesh') MayaCmds.createNode('transform', n='group') MayaCmds.parent('polyMesh', 'group') MayaCmds.AbcImport(self.__files[2], connect='group') # this is loaded in for value comparison purpose only MayaCmds.AbcImport(self.__files[2], mode='import') # check the swapped scene at every frame for frame in range(1, 4): MayaCmds.currentTime(frame, update=True) # tranform node group checkEqualTranslate(self, 'group', 'group1', 4) # tranform node group checkEqualTranslate(self, 'group|polyMesh', 'group1|polyMesh', 4) # mesh node polyMesh for index in range(0, 9): string1 = 'group|polyMesh.vt[%d]' % index string2 = 'group1|polyMesh.vt[%d]' % index self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][0], MayaCmds.getAttr(string2)[0][0], 4, '%s.x != %s.x' % (string1, string2)) self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][1], MayaCmds.getAttr(string2)[0][1], 4, '%s.y != %s.y' % (string1, string2)) self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][2], MayaCmds.getAttr(string2)[0][2], 4, '%s.z != %s.z' % (string1, string2))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import math # adds the current working directory so tools don't get confused about where we # are storing files def expandFileName(name): return os.getcwd() + os.path.sep + name # compare the two floating point values def floatDiff(val1, val2, tolerance): diff = math.fabs(val1 - val2) if diff < math.pow(10, -tolerance): return True return False # function that returns a node object given a name def getObjFromName(nodeName): selectionList = OpenMaya.MSelectionList() selectionList.add( nodeName ) obj = OpenMaya.MObject() selectionList.getDependNode(0, obj) return obj # function that finds a plug given a node object and plug name def getPlugFromName(attrName, nodeObj): fnDepNode = OpenMaya.MFnDependencyNode(nodeObj) attrObj = fnDepNode.attribute(attrName) plug = OpenMaya.MPlug(nodeObj, attrObj) return plug # meaning of return value: # 0 if array1 = array2 # 1 if array1 and array2 are of the same length, array1[i] == array2[i] for 0<=i<m<len, and array1[m] < array2[m] # -1 if array1 and array2 are of the same length, array1[i] == array2[i] for 0<=i<m<len, and array1[m] > array2[m] # 2 if array1.length() < array2.length() # -2 if array1.length() > array2.length() def compareArray(array1, array2): len1 = array1.length() len2 = array2.length() if len1 > len2 : return -2 if len1 < len2 : return 2 for i in range(0, len1): if array1[i] < array2[i] : return 1 if array1[i] > array2[i] : return -1 return 0 # return True if the two point arrays are exactly the same def comparePointArray(array1, array2): len1 = array1.length() len2 = array2.length() if len1 != len2 : return False for i in range(0, len1): if not array1[i].isEquivalent(array2[i], 1e-6): return False return True # return True if the two meshes are identical def compareMesh( nodeName1, nodeName2 ): # basic error checking obj1 = getObjFromName(nodeName1) if not obj1.hasFn(OpenMaya.MFn.kMesh): return False obj2 = getObjFromName(nodeName2) if not obj2.hasFn(OpenMaya.MFn.kMesh): return False polyIt1 = OpenMaya.MItMeshPolygon( obj1 ) polyIt2 = OpenMaya.MItMeshPolygon( obj2 ) if polyIt1.count() != polyIt2.count(): return False if polyIt1.polygonVertexCount() != polyIt2.polygonVertexCount(): return False vertices1 = OpenMaya.MIntArray() vertices2 = OpenMaya.MIntArray() pointArray1 = OpenMaya.MPointArray() pointArray2 = OpenMaya.MPointArray() while polyIt1.isDone()==False and polyIt2.isDone()==False : # compare vertex indices polyIt1.getVertices(vertices1) polyIt2.getVertices(vertices2) if compareArray(vertices1, vertices2) != 0: return False # compare vertex positions polyIt1.getPoints(pointArray1) polyIt2.getPoints(pointArray2) if not comparePointArray( pointArray1, pointArray2 ): return False polyIt1.next() polyIt2.next() if polyIt1.isDone() and polyIt2.isDone() : return True return False # return True if the two Nurbs Surfaces are identical def compareNurbsSurface(nodeName1, nodeName2): # basic error checking obj1 = getObjFromName(nodeName1) if not obj1.hasFn(OpenMaya.MFn.kNurbsSurface): return False obj2 = getObjFromName(nodeName2) if not obj2.hasFn(OpenMaya.MFn.kNurbsSurface): return False fn1 = OpenMaya.MFnNurbsSurface(obj1) fn2 = OpenMaya.MFnNurbsSurface(obj2) # degree if fn1.degreeU() != fn2.degreeU(): return False if fn1.degreeV() != fn2.degreeV(): return False # span if fn1.numSpansInU() != fn2.numSpansInU(): return False if fn1.numSpansInV() != fn2.numSpansInV(): return False # form if fn1.formInU() != fn2.formInU(): return False if fn1.formInV() != fn2.formInV(): return False # control points if fn1.numCVsInU() != fn2.numCVsInU(): return False if fn1.numCVsInV() != fn2.numCVsInV(): return False cv1 = OpenMaya.MPointArray() fn1.getCVs(cv1) cv2 = OpenMaya.MPointArray() fn2.getCVs(cv2) if not comparePointArray(cv1, cv2): return False # knots if fn1.numKnotsInU() != fn2.numKnotsInU(): return False if fn1.numKnotsInV() != fn2.numKnotsInV(): return False knotsU1 = OpenMaya.MDoubleArray() fn1.getKnotsInU(knotsU1) knotsV1 = OpenMaya.MDoubleArray() fn1.getKnotsInV(knotsV1) knotsU2 = OpenMaya.MDoubleArray() fn2.getKnotsInU(knotsU2) knotsV2 = OpenMaya.MDoubleArray() fn2.getKnotsInV(knotsV2) if compareArray( knotsU1, knotsU2 ) != 0: return False if compareArray( knotsV1, knotsV2 ) != 0: return False # trim curves if fn1.isTrimmedSurface() != fn2.isTrimmedSurface(): return False # may need to add more trim checks return True # return True if the two locators are idential def compareLocator(nodeName1, nodeName2): # basic error checking obj1 = getObjFromName(nodeName1) if not obj1.hasFn(OpenMaya.MFn.kLocator): return False obj2 = getObjFromName(nodeName2) if not obj2.hasFn(OpenMaya.MFn.kLocator): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localPositionX'), MayaCmds.getAttr(nodeName2+'.localPositionX'), 4): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localPositionY'), MayaCmds.getAttr(nodeName2+'.localPositionY'), 4): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localPositionZ'), MayaCmds.getAttr(nodeName2+'.localPositionZ'), 4): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localScaleX'), MayaCmds.getAttr(nodeName2+'.localScaleX'), 4): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localScaleY'), MayaCmds.getAttr(nodeName2+'.localScaleY'), 4): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localScaleZ'), MayaCmds.getAttr(nodeName2+'.localScaleZ'), 4): return False return True # return True if the two cameras are identical def compareCamera( nodeName1, nodeName2 ): # basic error checking obj1 = getObjFromName(nodeName1) if not obj1.hasFn(OpenMaya.MFn.kCamera): return False obj2 = getObjFromName(nodeName2) if not obj2.hasFn(OpenMaya.MFn.kCamera): return False fn1 = OpenMaya.MFnCamera( obj1 ) fn2 = OpenMaya.MFnCamera( obj2 ) if fn1.filmFit() != fn2.filmFit(): print "differ in filmFit" return False if not floatDiff(fn1.filmFitOffset(), fn2.filmFitOffset(), 4): print "differ in filmFitOffset" return False if fn1.isOrtho() != fn2.isOrtho(): print "differ in isOrtho" return False if not floatDiff(fn1.orthoWidth(), fn2.orthoWidth(), 4): print "differ in orthoWidth" return False if not floatDiff(fn1.focalLength(), fn2.focalLength(), 4): print "differ in focalLength" return False if not floatDiff(fn1.lensSqueezeRatio(), fn2.lensSqueezeRatio(), 4): print "differ in lensSqueezeRatio" return False if not floatDiff(fn1.cameraScale(), fn2.cameraScale(), 4): print "differ in cameraScale" return False if not floatDiff(fn1.horizontalFilmAperture(), fn2.horizontalFilmAperture(), 4): print "differ in horizontalFilmAperture" return False if not floatDiff(fn1.verticalFilmAperture(), fn2.verticalFilmAperture(), 4): print "differ in verticalFilmAperture" return False if not floatDiff(fn1.horizontalFilmOffset(), fn2.horizontalFilmOffset(), 4): print "differ in horizontalFilmOffset" return False if not floatDiff(fn1.verticalFilmOffset(), fn2.verticalFilmOffset(), 4): print "differ in verticalFilmOffset" return False if not floatDiff(fn1.overscan(), fn2.overscan(), 4): print "differ in overscan" return False if not floatDiff(fn1.nearClippingPlane(), fn2.nearClippingPlane(), 4): print "differ in nearClippingPlane" return False if not floatDiff(fn1.farClippingPlane(), fn2.farClippingPlane(), 4): print "differ in farClippingPlane" return False if not floatDiff(fn1.preScale(), fn2.preScale(), 4): print "differ in preScale" return False if not floatDiff(fn1.postScale(), fn2.postScale(), 4): print "differ in postScale" return False if not floatDiff(fn1.filmTranslateH(), fn2.filmTranslateH(), 4): print "differ in filmTranslateH" return False if not floatDiff(fn1.filmTranslateV(), fn2.filmTranslateV(), 4): print "differ in filmTranslateV" return False if not floatDiff(fn1.horizontalRollPivot(), fn2.horizontalRollPivot(), 4): print "differ in horizontalRollPivot" return False if not floatDiff(fn1.verticalRollPivot(), fn2.verticalRollPivot(), 4): print "differ in verticalRollPivot" return False if fn1.filmRollOrder() != fn2.filmRollOrder(): print "differ in filmRollOrder" return False if not floatDiff(fn1.filmRollValue(), fn2.filmRollValue(), 4): print "differ in filmRollValue" return False if not floatDiff(fn1.fStop(), fn2.fStop(), 4): print "differ in fStop" return False if not floatDiff(fn1.focusDistance(), fn2.focusDistance(), 4,): print "differ in focusDistance" return False if not floatDiff(fn1.shutterAngle(), fn2.shutterAngle(), 4): print "differ in shutterAngle" return False if fn1.usePivotAsLocalSpace() != fn2.usePivotAsLocalSpace(): print "differ in usePivotAsLocalSpace" return False if fn1.tumblePivot() != fn2.tumblePivot(): print "differ in tumblePivot" return False return True # return True if the two Nurbs curves are identical def compareNurbsCurve(nodeName1, nodeName2): # basic error checking obj1 = getObjFromName(nodeName1) if not obj1.hasFn(OpenMaya.MFn.kNurbsCurve): print nodeName1, "not a curve." return False obj2 = getObjFromName(nodeName2) if not obj2.hasFn(OpenMaya.MFn.kNurbsCurve): print nodeName2, "not a curve." return False fn1 = OpenMaya.MFnNurbsCurve(obj1) fn2 = OpenMaya.MFnNurbsCurve(obj2) if fn1.degree() != fn2.degree(): print nodeName1, nodeName2, "degrees differ." return False if fn1.numCVs() != fn2.numCVs(): print nodeName1, nodeName2, "numCVs differ." return False if fn1.numSpans() != fn2.numSpans(): print nodeName1, nodeName2, "spans differ." return False if fn1.numKnots() != fn2.numKnots(): print nodeName1, nodeName2, "numKnots differ." return False if fn1.form() != fn2.form(): print nodeName1, nodeName2, "form differ." return False cv1 = OpenMaya.MPointArray() fn1.getCVs(cv1) cv2 = OpenMaya.MPointArray() fn2.getCVs(cv2) if not comparePointArray(cv1, cv2): print nodeName1, nodeName2, "points differ." return False # we do not need to compare knots, since they aren't stored in Alembic # and are currently recreated as uniformly distributed between 0 and 1 return True
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import subprocess import unittest import util class subframesTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testRangeFlag(self): MayaCmds.createNode('transform', name='node') MayaCmds.setKeyframe('node.translateX', time=1.0, v=1.0) MayaCmds.setKeyframe('node.translateX', time=11.0, v=11.0) self.__files.append(util.expandFileName('rangeTest.abc')) MayaCmds.AbcExport(j='-fr 1 11 -step 0.25 -root node -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') abcNodeName = MayaCmds.ls(exactType='AlembicNode') MayaCmds.currentTime(0, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.translateX'), 1) MayaCmds.currentTime(1, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.translateX'), 1) MayaCmds.currentTime(1.0003, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.translateX'), 1) MayaCmds.currentTime(1.333333, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessAlmostEqual(MayaCmds.getAttr('node.translateX'), 1.333333333, 2) MayaCmds.currentTime(9.66667, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessAlmostEqual(MayaCmds.getAttr('node.translateX'), 9.6666666666, 2) MayaCmds.currentTime(11, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.translateX'), 11) MayaCmds.currentTime(12, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.translateX'), 11) def testPreRollStartFrameFlag(self): MayaCmds.createNode('transform', name='node') MayaCmds.setAttr('node.tx', 0.0) MayaCmds.expression( string="if(time==0)\n\tnode.tx=0;\n\nif (time*24 > 6 && node.tx > 0.8)\n\tnode.tx = 10;\n\nnode.tx = node.tx + time;\n", name="startAtExp", ae=1, uc=all) self.__files.append(util.expandFileName('startAtTest.abc')) MayaCmds.AbcExport(j='-fr 1 10 -root node -file ' + self.__files[-1], prs=0, duf=True) MayaCmds.AbcImport(self.__files[-1], m='open') abcNodeName = MayaCmds.ls(exactType='AlembicNode') # if the evaluation doesn't start at frame 0, node.tx < 10 MayaCmds.currentTime(10, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnless(MayaCmds.getAttr('node.translateX')-10 > 0) def testSkipFrames(self): MayaCmds.createNode('transform', name='node') MayaCmds.setKeyframe('node.translateX', time=1.0, v=1.0) MayaCmds.setKeyframe('node.translateX', time=10.0, v=10.0) MayaCmds.duplicate(name='dupNode') MayaCmds.setAttr('dupNode.tx', 0.0) MayaCmds.expression( string="if(time==11)\n\tdupNode.tx=-50;\n\ndupNode.tx = dupNode.tx + time;\n", name="startAtExp", ae=1, uc=all) self.__files.append(util.expandFileName('skipFrameTest1.abc')) self.__files.append(util.expandFileName('skipFrameTest2.abc')) MayaCmds.AbcExport(j=['-fr 1 10 -root node -file ' + self.__files[-2], '-fr 20 25 -root dupNode -file ' + self.__files[-1]]) MayaCmds.AbcImport(self.__files[-2], m='open') abcNodeName = MayaCmds.ls(exactType='AlembicNode') # make sure all the frames needed are written out and correctly for val in range(1, 11): MayaCmds.currentTime(val, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessAlmostEqual(MayaCmds.getAttr('node.tx'), val, 3) # also make sure nothing extra gets written out MayaCmds.currentTime(11, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.tx'), 10.0) MayaCmds.AbcImport(self.__files[-1], m='open') abcNodeName = MayaCmds.ls(exactType='AlembicNode') # if dontSkipFrames flag is not set maya would evaluate frame 11 and # set dupNode.tx to a big negative number MayaCmds.currentTime(20, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnless(MayaCmds.getAttr('dupNode.tx') > 0) def testWholeFrameGeoFlag(self): MayaCmds.polyCube(name='node') MayaCmds.setKeyframe('node.translateX', time=1.0, v=1.0) MayaCmds.setKeyframe('node.translateX', time=2.0, v=-3.0) MayaCmds.setKeyframe('node.translateX', time=5.0, v=9.0) MayaCmds.select('node.vtx[0:8]') MayaCmds.setKeyframe(time=1.0) MayaCmds.scale(1.5, 1.5, 1.8) MayaCmds.setKeyframe(time=5.0) self.__files.append(util.expandFileName('noSampleGeoTest.abc')) MayaCmds.AbcExport(j='-fr 1 5 -wfg -frs 0 -frs 0.9 -root node -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') abcNodeName = MayaCmds.ls(exactType='AlembicNode') setTime = MayaCmds.currentTime(1, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) val_1 = MayaCmds.getAttr('node.vt[0]')[0][0] MayaCmds.currentTime(2.0, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) MayaCmds.getAttr('node.vt[0]') val_2 = MayaCmds.getAttr('node.vt[0]')[0][0] self.failUnlessAlmostEqual(val_2, -0.5625, 3) setTime = MayaCmds.currentTime(1.9, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessAlmostEqual(MayaCmds.getAttr('node.tx'), -3.086, 3) # the vertex will get linearly interpolated alpha = (setTime - 1) / (2 - 1) self.failUnlessAlmostEqual(MayaCmds.getAttr('node.vt[0]')[0][0], (1-alpha)*val_1+alpha*val_2, 3) # convenience functions for the tests following def noFrameRangeExists(self, fileName): retVal = subprocess.call(['h5dump', '--attribute=1.time', fileName]) self.failUnless(retVal != 0) def isFrameRangeExists(self, fileName): retVal = subprocess.call(['h5dump', '--attribute=2.time', fileName]) self.failUnless(retVal != 0) retVal = subprocess.call(['h5dump', '--attribute=1.time', fileName]) self.failUnless(retVal == 0) def isFrameRangeTransAndFrameRangeShapeExists(self, fileName): retVal = subprocess.call(['h5dump', '--attribute=2.time', fileName]) self.failUnless(retVal == 0) retVal = subprocess.call(['h5dump', '--attribute=1.time', fileName]) self.failUnless(retVal == 0) def test_agat(self): # animated geometry, animated transform node nodename = 'agat_node' MayaCmds.polyCube(name=nodename) MayaCmds.setKeyframe(nodename+'.translateX', time=1.0, v=1.0) MayaCmds.setKeyframe(nodename+'.translateX', time=5.0, v=10.0) MayaCmds.select(nodename+'.vtx[0:8]') MayaCmds.setKeyframe(time=1.0) MayaCmds.scale(1.5, 1.5, 1.8) MayaCmds.setKeyframe(time=5.0) self.__files.append(util.expandFileName('agat_motionblur_noSampleGeo_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -wfg -step 0.5 -root %s -file %s' % ( nodename, self.__files[-1])) # frameRangeShape: 1, 2, 3, 4, 5, 6 # frameRangeTrans: 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6 self.isFrameRangeTransAndFrameRangeShapeExists(self.__files[-1]) self.__files.append(util.expandFileName('agat_motionblur_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -root %s -file %s' % ( nodename, self.__files[-1])) # frameRange: 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6 self.isFrameRangeExists(self.__files[-1]) self.__files.append(util.expandFileName('agat_norange_Test.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (nodename,self.__files[-1])) # no frameRange self.noFrameRangeExists(self.__files[-1]) def test_agst(self): # animated geometry, static transform node nodename = 'agst_node' MayaCmds.polyCube(name=nodename) MayaCmds.select(nodename+'.vtx[0:8]') MayaCmds.setKeyframe(time=1.0) MayaCmds.scale(1.5, 1.5, 1.8) MayaCmds.setKeyframe(time=5.0) self.__files.append(util.expandFileName('agst_motionblur_noSampleGeo_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -wfg -root %s -file %s' % ( nodename, self.__files[-1])) # frameRange: 1, 2, 3, 4, 5, 6 self.isFrameRangeTransAndFrameRangeShapeExists(self.__files[-1]) self.__files.append(util.expandFileName('agst_motionblur_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -root %s -f %s' % ( nodename, self.__files[-1])) # frameRange: 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6 self.isFrameRangeExists(self.__files[-1]) self.__files.append(util.expandFileName('agst_noSampleGeo_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -wfg -root %s -f %s' % (nodename, self.__files[-1])) # frameRange: 1, 2, 3, 4, 5 self.isFrameRangeExists(self.__files[-1]) def test_sgat(self): # static geometry, animated transform node nodename = 'sgat_node' MayaCmds.polyCube(name=nodename) MayaCmds.setKeyframe(nodename+'.translateX', time=1.0, v=1.0) MayaCmds.setKeyframe(nodename+'.translateX', time=5.0, v=10.0) self.__files.append(util.expandFileName('sgat_motionblur_noSampleGeo_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -wfg -root %s -f %s' % ( nodename, self.__files[-1])) # frameRange: 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6 self.isFrameRangeTransAndFrameRangeShapeExists(self.__files[-1]) self.__files.append(util.expandFileName('sgat_motionblur_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -root %s -f %s ' % ( nodename, self.__files[-1])) # frameRange: 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6 self.isFrameRangeExists(self.__files[-1]) def test_sgst(self): # static geometry, static transform node nodename = 'sgst_node' MayaCmds.polyCube(name=nodename) self.__files.append(util.expandFileName('sgst_motionblur_noSampleGeo_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -wfg -root %s -file %s ' % ( nodename, self.__files[-1])) self.failIf(MayaCmds.AbcImport(self.__files[-1]) != "") self.__files.append(util.expandFileName('sgst_moblur_noSampleGeo_norange_Test.abc')) MayaCmds.AbcExport(j='-step 0.5 -wfg -root %s -file %s' % ( nodename, self.__files[-1])) # frameRange: NA self.noFrameRangeExists(self.__files[-1])
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import unittest import util class ColorSetsTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticMeshStaticColor(self): red_array = OpenMaya.MColorArray() red_array.append(1.0, 0.0, 0.0) blue_array = OpenMaya.MColorArray() blue_array.append(0.0, 0.0, 1.0) single_indices = OpenMaya.MIntArray(4, 0) mixed_colors = [[1.0, 1.0, 0.0, 1.0], [0.0, 1.0, 1.0, 0.75], [1.0, 0.0, 1.0, 0.5], [1.0, 1.0, 1.0, 0.25]] mixed_array = OpenMaya.MColorArray() for x in mixed_colors: mixed_array.append(x[0], x[1], x[2], x[3]) mixed_indices = OpenMaya.MIntArray() for i in range(4): mixed_indices.append(i) MayaCmds.polyPlane(sx=1, sy=1, name='poly') MayaCmds.select('polyShape') sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) fn.createColorSetWithName('reds') fn.createColorSetWithName('mixed') fn.setColors(red_array, 'reds', OpenMaya.MFnMesh.kRGB) fn.assignColors(single_indices, 'reds') fn.setColors(mixed_array, 'mixed', OpenMaya.MFnMesh.kRGBA) fn.assignColors(mixed_indices, 'mixed') fn.setCurrentColorSetName('mixed') MayaCmds.polyPlane(sx=1, sy=1, name='subd') MayaCmds.select('subdShape') sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) fn.createColorSetWithName('blues') fn.createColorSetWithName('mixed') fn.setColors(blue_array, 'blues', OpenMaya.MFnMesh.kRGB) fn.assignColors(single_indices, 'blues') fn.setColors(mixed_array, 'mixed', OpenMaya.MFnMesh.kRGBA) fn.assignColors(mixed_indices, 'mixed') fn.setCurrentColorSetName('blues') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) self.__files.append(util.expandFileName('staticColorSets.abc')) MayaCmds.AbcExport(j='-root poly -root subd -wcs -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.select('polyShape') sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) self.failUnless(fn.currentColorSetName() == 'mixed') setNames = [] fn.getColorSetNames(setNames) self.failUnless(len(setNames) == 2) self.failUnless(setNames.count('mixed') == 1) self.failUnless(setNames.count('reds') == 1) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray, 'reds') self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnless(colArray[x].r == 1) self.failUnless(colArray[x].g == 0) self.failUnless(colArray[x].b == 0) fn.getFaceVertexColors(colArray, 'mixed') self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnless(colArray[x].r == mixed_colors[x][0]) self.failUnless(colArray[x].g == mixed_colors[x][1]) self.failUnless(colArray[x].b == mixed_colors[x][2]) self.failUnless(colArray[x].a == mixed_colors[x][3]) MayaCmds.select('subdShape') self.failUnless(MayaCmds.getAttr('subdShape.SubDivisionMesh') == 1) sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) self.failUnless(fn.currentColorSetName() == 'blues') setNames = [] fn.getColorSetNames(setNames) self.failUnless(len(setNames) == 2) self.failUnless(setNames.count('mixed') == 1) self.failUnless(setNames.count('blues') == 1) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray, 'blues') self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnless(colArray[x].r == 0) self.failUnless(colArray[x].g == 0) self.failUnless(colArray[x].b == 1) fn.getFaceVertexColors(colArray, 'mixed') self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnless(colArray[x].r == mixed_colors[x][0]) self.failUnless(colArray[x].g == mixed_colors[x][1]) self.failUnless(colArray[x].b == mixed_colors[x][2]) self.failUnless(colArray[x].a == mixed_colors[x][3]) def testStaticMeshAnimColor(self): MayaCmds.currentTime(1) MayaCmds.polyPlane(sx=1, sy=1, name='poly') MayaCmds.polyColorPerVertex(r=0.0,g=1.0,b=0.0, cdo=True) MayaCmds.setKeyframe(["polyColorPerVertex1"]) MayaCmds.currentTime(10) MayaCmds.polyColorPerVertex(r=0.0,g=0.0,b=1.0, cdo=True) MayaCmds.setKeyframe(["polyColorPerVertex1"]) MayaCmds.currentTime(1) MayaCmds.polyPlane(sx=1, sy=1, name='subd') MayaCmds.select('subdShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) MayaCmds.polyColorPerVertex(r=1.0,g=1.0,b=0.0, cdo=True) MayaCmds.setKeyframe(["polyColorPerVertex2"]) MayaCmds.currentTime(10) MayaCmds.polyColorPerVertex(r=1.0,g=0.0,b=0.0, cdo=True) MayaCmds.setKeyframe(["polyColorPerVertex2"]) self.__files.append(util.expandFileName('animColorSets.abc')) MayaCmds.AbcExport(j='-fr 1 10 -root poly -root subd -wcs -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.select('polyShape') sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) MayaCmds.currentTime(1) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 0) self.failUnlessAlmostEqual(colArray[x].g, 1) self.failUnlessAlmostEqual(colArray[x].b, 0) MayaCmds.currentTime(5) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnless(colArray[x].r == 0) self.failUnlessAlmostEqual(colArray[x].g, 0.555555582047) self.failUnlessAlmostEqual(colArray[x].b, 0.444444447756) MayaCmds.currentTime(10) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 0) self.failUnlessAlmostEqual(colArray[x].g, 0) self.failUnlessAlmostEqual(colArray[x].b, 1) self.failUnless(MayaCmds.getAttr('subdShape.SubDivisionMesh') == 1) MayaCmds.select('subdShape') sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) MayaCmds.currentTime(1) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 1) self.failUnlessAlmostEqual(colArray[x].g, 1) self.failUnlessAlmostEqual(colArray[x].b, 0) MayaCmds.currentTime(5) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 1) self.failUnlessAlmostEqual(colArray[x].g, 0.555555582047) self.failUnlessAlmostEqual(colArray[x].b, 0) MayaCmds.currentTime(10) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 1) self.failUnlessAlmostEqual(colArray[x].g, 0) self.failUnlessAlmostEqual(colArray[x].b, 0)
Python
# # Copyright (c) 2010 Sony Pictures Imageworks Inc. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the # distribution. Neither the name of Sony Pictures Imageworks nor the # names of its contributors may be used to endorse or promote # products derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED # OF THE POSSIBILITY OF SUCH DAMAGE. from maya import cmds as MayaCmds from maya import mel as Mel import os import unittest import util def makeRobot(): MayaCmds.polyCube(name="head") MayaCmds.move(0, 4, 0, r=1) MayaCmds.polyCube(name="chest") MayaCmds.scale(2, 2.5, 1) MayaCmds.move(0, 2, 0, r=1) MayaCmds.polyCube(name="leftArm") MayaCmds.move(0, 3, 0, r=1) MayaCmds.scale(2, 0.5, 1, r=1) MayaCmds.duplicate(name="rightArm") MayaCmds.select("leftArm") MayaCmds.move(1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, 32, r=1, os=1) MayaCmds.select("rightArm") MayaCmds.move(-1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, -32, r=1, os=1) MayaCmds.select("rightArm", "leftArm", "chest", r=1) MayaCmds.group(name="body") MayaCmds.polyCube(name="bottom") MayaCmds.scale(2, 0.5, 1) MayaCmds.move(0, 0.5, 0, r=1) MayaCmds.polyCube(name="leftLeg") MayaCmds.scale(0.65, 2.8, 1, r=1) MayaCmds.move(-0.5, -1, 0, r=1) MayaCmds.duplicate(name="rightLeg") MayaCmds.move(1, 0, 0, r=1) MayaCmds.select("rightLeg", "leftLeg", "bottom", r=1) MayaCmds.group(name="lower") MayaCmds.select("head", "body", "lower", r=1) MayaCmds.group(name="robot") def makeRobotAnimated(): makeRobot() #change pivot point of arms and legs MayaCmds.move(0.65, -0.40, 0, 'rightArm.scalePivot', 'rightArm.rotatePivot', relative=True) MayaCmds.move(-0.65, -0.40, 0, 'leftArm.scalePivot', 'leftArm.rotatePivot', relative=True) MayaCmds.move(0, 1.12, 0, 'rightLeg.scalePivot', 'rightLeg.rotatePivot', relative=True) MayaCmds.move(0, 1.12, 0, 'leftLeg.scalePivot', 'leftLeg.rotatePivot', relative=True) MayaCmds.setKeyframe('leftLeg', at='rotateX', value=25, t=[1, 12]) MayaCmds.setKeyframe('leftLeg', at='rotateX', value=-40, t=[6]) MayaCmds.setKeyframe('rightLeg', at='scaleY', value=2.8, t=[1, 12]) MayaCmds.setKeyframe('rightLeg', at='scaleY', value=5.0, t=[6]) MayaCmds.setKeyframe('leftArm', at='rotateZ', value=55, t=[1, 12]) MayaCmds.setKeyframe('leftArm', at='rotateZ', value=-50, t=[6]) MayaCmds.setKeyframe('rightArm', at='scaleX', value=0.5, t=[1, 12]) MayaCmds.setKeyframe('rightArm', at='scaleX', value=3.6, t=[6]) class AbcNodeNameTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testReturnAbcNodeName(self): makeRobotAnimated() self.__files.append(util.expandFileName('returnAlembicNodeNameTest.abc')) MayaCmds.AbcExport(j='-fr 1 12 -root robot -file ' + self.__files[-1]) ret = MayaCmds.AbcImport(self.__files[-1], mode='open') ret1 = MayaCmds.AbcImport(self.__files[-1], mode='import') self.failUnless(MayaCmds.objExists(ret)) self.failUnless(MayaCmds.objExists(ret1)) self.failIf(ret == ret1)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class staticPropTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def setProps(self, nodeName): MayaCmds.select(nodeName) MayaCmds.addAttr(longName='SPT_int8', defaultValue=8, attributeType='byte', keyable=True) MayaCmds.addAttr(longName='SPT_int16', defaultValue=16, attributeType='short', keyable=True) MayaCmds.addAttr(longName='SPT_int32', defaultValue=32, attributeType='long', keyable=True) MayaCmds.addAttr(longName='SPT_float', defaultValue=3.2654, attributeType='float', keyable=True) MayaCmds.addAttr(longName='SPT_double', defaultValue=0.15724757, attributeType='double', keyable=True) MayaCmds.addAttr(longName='SPT_double_AbcGeomScope', dataType="string") MayaCmds.setAttr(nodeName+'.SPT_double_AbcGeomScope', "vtx", type="string") MayaCmds.addAttr(longName='SPT_string', dataType="string") MayaCmds.setAttr(nodeName+'.SPT_string', "empty", type="string") MayaCmds.addAttr(longName='SPT_string_AbcGeomScope', dataType="string") MayaCmds.setAttr(nodeName+'.SPT_string_AbcGeomScope', "potato", type="string") MayaCmds.addAttr(longName='SPT_int32_array', dataType='Int32Array') MayaCmds.setAttr(nodeName+'.SPT_int32_array', [6, 7, 8, 9, 10], type='Int32Array') MayaCmds.addAttr(longName='SPT_vector_array', dataType='vectorArray') MayaCmds.setAttr(nodeName+'.SPT_vector_array', 3, (1,1,1), (2,2,2), (3,3,3), type='vectorArray') MayaCmds.addAttr(longName='SPT_vector_array_AbcType', dataType="string") MayaCmds.setAttr(nodeName+'.SPT_vector_array_AbcType', "normal2", type="string") MayaCmds.addAttr(longName='SPT_point_array', dataType='pointArray') MayaCmds.setAttr(nodeName+'.SPT_point_array', 2, (2,4,6,8), (20,40,60,80), type='pointArray') MayaCmds.addAttr(longName='SPT_double_array', dataType='doubleArray') MayaCmds.addAttr(longName='SPT_double_array_AbcGeomScope', dataType="string") MayaCmds.setAttr(nodeName+'.SPT_double_array', [1.1, 2.2, 3.3, 4.4, 5.5], type='doubleArray') MayaCmds.setAttr(nodeName+'.SPT_double_array_AbcGeomScope', "vtx", type="string") MayaCmds.addAttr(longName='SPT_string_array', dataType='stringArray') MayaCmds.setAttr(nodeName+'.SPT_string_array', 3, "string1", "string2", "string3", type='stringArray') def verifyProps(self, nodeName, fileName): MayaCmds.AbcImport(fileName, mode='open') self.failUnlessEqual(8, MayaCmds.getAttr(nodeName+'.SPT_int8')) self.failUnlessEqual(16, MayaCmds.getAttr(nodeName+'.SPT_int16')) self.failUnlessEqual(32, MayaCmds.getAttr(nodeName+'.SPT_int32')) self.failUnlessAlmostEqual(3.2654, MayaCmds.getAttr(nodeName+'.SPT_float'), 4) self.failUnlessAlmostEqual(0.15724757, MayaCmds.getAttr(nodeName+'.SPT_double'), 7) self.failUnlessEqual('vtx', MayaCmds.getAttr(nodeName+'.SPT_double_AbcGeomScope')) self.failUnlessEqual('empty', MayaCmds.getAttr(nodeName+'.SPT_string')) self.failUnlessEqual(0, MayaCmds.attributeQuery( 'SPT_string_AbcGeomScope', node=nodeName, exists=True)) self.failUnlessEqual([6, 7, 8, 9, 10], MayaCmds.getAttr(nodeName+'.SPT_int32_array')) self.failUnlessEqual(["string1", "string2", "string3"], MayaCmds.getAttr(nodeName+'.SPT_string_array')) self.failUnlessEqual([1.1, 2.2, 3.3, 4.4, 5.5], MayaCmds.getAttr(nodeName+'.SPT_double_array')) self.failUnlessEqual([(1.0, 1.0, 0.0), (2.0, 2.0, 0.0), (3.0, 3.0, 0.0)], MayaCmds.getAttr(nodeName+'.SPT_vector_array')) self.failUnlessEqual('normal2', MayaCmds.getAttr(nodeName+'.SPT_vector_array_AbcType')) self.failUnlessEqual([(2.0, 4.0, 6.0, 1.0), (20.0, 40.0, 60.0, 1.0)], MayaCmds.getAttr(nodeName+'.SPT_point_array')) def testStaticTransformPropReadWrite(self): nodeName = MayaCmds.createNode('transform') self.setProps(nodeName) self.__files.append(util.expandFileName('staticPropTransform.abc')) MayaCmds.AbcExport(j='-atp SPT_ -root %s -file %s' % (nodeName, self.__files[-1])) self.verifyProps(nodeName, self.__files[-1]) def testStaticCameraPropReadWrite(self): root = MayaCmds.camera() nodeName = root[0] shapeName = root[1] self.setProps(shapeName) self.__files.append(util.expandFileName('staticPropCamera.abc')) MayaCmds.AbcExport(j='-atp SPT_ -root %s -f %s' % (nodeName, self.__files[-1])) self.verifyProps(shapeName, self.__files[-1]) def testStaticParticlePropReadWrite(self): root = MayaCmds.particle(p=[(0, 0, 0), (1, 1, 1)]) nodeName = root[0] shapeName = root[1] self.setProps(shapeName) self.__files.append(util.expandFileName('staticPropParticles.abc')) MayaCmds.AbcExport(j='-atp -root %s -f %s' % (nodeName, self.__files[-1])) self.verifyProps(shapeName, self.__files[-1]) def testStaticMeshPropReadWrite(self): nodeName = 'polyCube' shapeName = 'polyCubeShape' MayaCmds.polyCube(name=nodeName) self.setProps(shapeName) self.__files.append(util.expandFileName('staticPropMesh.abc')) MayaCmds.AbcExport(j='-atp SPT_ -root %s -f %s' % (nodeName, self.__files[-1])) self.verifyProps(shapeName, self.__files[-1]) def testStaticNurbsCurvePropReadWrite(self): nodeName = 'nCurve' shapeName = 'curveShape1' MayaCmds.curve(p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9)], name=nodeName) self.setProps(shapeName) self.__files.append(util.expandFileName('staticPropCurve.abc')) MayaCmds.AbcExport(j='-atp SPT_ -root %s -f %s' % (nodeName, self.__files[-1])) self.verifyProps(shapeName, self.__files[-1]) def testStaticNurbsSurfacePropReadWrite(self): nodeName = 'nSphere' shapeName = 'nSphereShape' MayaCmds.sphere(name=nodeName) self.setProps(shapeName) self.__files.append(util.expandFileName('staticPropNurbs.abc')) MayaCmds.AbcExport(j='-atp SPT_ -root %s -file %s' % (nodeName, self.__files[-1])) self.verifyProps(shapeName, self.__files[-1])
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util def testStaticNurbsWithoutTrim(self, surfacetype, abcFileName): if (surfacetype == 0): ret = MayaCmds.nurbsPlane(p=(0, 0, 0), ax=(0, 1, 0), w=1, lr=1, d=3, u=5, v=5, ch=0) errmsg = 'Nurbs Plane' elif (surfacetype == 1): ret = MayaCmds.sphere(p=(0, 0, 0), ax=(0, 1, 0), ssw=0, esw=360, r=1, d=3, ut=0, tol=0.01, s=8, nsp=4, ch=0) errmsg = 'Nurbs Sphere' elif (surfacetype == 2): ret = MayaCmds.torus(p=(0, 0, 0), ax=(0, 1, 0), ssw=0, esw=360, msw=360, r=1, hr=0.5, ch=0) errmsg = 'Nurbs Torus' name = ret[0] degreeU = MayaCmds.getAttr(name+'.degreeU') degreeV = MayaCmds.getAttr(name+'.degreeV') spansU = MayaCmds.getAttr(name+'.spansU') spansV = MayaCmds.getAttr(name+'.spansV') minU = MayaCmds.getAttr(name+'.minValueU') maxU = MayaCmds.getAttr(name+'.maxValueU') minV = MayaCmds.getAttr(name+'.minValueV') maxV = MayaCmds.getAttr(name+'.maxValueV') surfaceInfoNode = MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', surfaceInfoNode+'.inputSurface', force=True) controlPoints = MayaCmds.getAttr(surfaceInfoNode+'.controlPoints[*]') knotsU = MayaCmds.getAttr(surfaceInfoNode+'.knotsU[*]') knotsV = MayaCmds.getAttr(surfaceInfoNode+'.knotsV[*]') MayaCmds.AbcExport(j='-root %s -f %s' % (name, abcFileName)) # reading test MayaCmds.AbcImport(abcFileName, mode='open') self.failUnlessEqual(degreeU, MayaCmds.getAttr(name+'.degreeU')) self.failUnlessEqual(degreeV, MayaCmds.getAttr(name+'.degreeV')) self.failUnlessEqual(spansU, MayaCmds.getAttr(name+'.spansU')) self.failUnlessEqual(spansV, MayaCmds.getAttr(name+'.spansV')) self.failUnlessEqual(minU, MayaCmds.getAttr(name+'.minValueU')) self.failUnlessEqual(maxU, MayaCmds.getAttr(name+'.maxValueU')) self.failUnlessEqual(minV, MayaCmds.getAttr(name+'.minValueV')) self.failUnlessEqual(maxV, MayaCmds.getAttr(name+'.maxValueV')) if (surfacetype == 0): self.failUnlessEqual(0, MayaCmds.getAttr(name+'.formU')) self.failUnlessEqual(0, MayaCmds.getAttr(name+'.formV')) elif (surfacetype == 1): self.failUnlessEqual(0, MayaCmds.getAttr(name+'.formU')) self.failUnlessEqual(2, MayaCmds.getAttr(name+'.formV')) elif (surfacetype == 2): self.failUnlessEqual(2, MayaCmds.getAttr(name+'.formU')) self.failUnlessEqual(2, MayaCmds.getAttr(name+'.formV')) surfaceInfoNode = MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', surfaceInfoNode+'.inputSurface', force=True) controlPoints2 = MayaCmds.getAttr(surfaceInfoNode + '.controlPoints[*]') self.failUnlessEqual(len(controlPoints), len(controlPoints2)) for i in range(0, len(controlPoints)): cp1 = controlPoints[i] cp2 = controlPoints2[i] self.failUnlessAlmostEqual(cp1[0], cp2[0], 3, 'cp[%d].x not equal' % i) self.failUnlessAlmostEqual(cp1[1], cp2[1], 3, 'cp[%d].y not equal' % i) self.failUnlessAlmostEqual(cp1[2], cp2[2], 3, 'cp[%d].z not equal' % i) for i in range(0, len(knotsU)): ku1 = knotsU[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % i) self.failUnlessAlmostEqual(ku1, ku2, 3, 'control knotsU # %d not equal' % i) for i in range(0, len(knotsV)): kv1 = knotsV[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % i) self.failUnlessAlmostEqual(kv1, kv2, 3, 'control knotsV # %d not equal' % i) def testStaticNurbsWithOneCloseCurveTrim(self, surfacetype, abcFileName, trimtype): if (surfacetype == 0): ret = MayaCmds.nurbsPlane(p=(0, 0, 0), ax=(0, 1, 0), w=1, lr=1, d=3, u=5, v=5, ch=0) elif (surfacetype == 1): ret = MayaCmds.sphere(p=(0, 0, 0), ax=(0, 1, 0), ssw=0, esw=360, r=1, d=3, ut=0, tol=0.01, s=8, nsp=4, ch=0) elif (surfacetype == 2): ret = MayaCmds.torus(p=(0, 0, 0), ax=(0, 1, 0), ssw=0, esw=360, msw=360, r=1, hr=0.5, ch=0) name = ret[0] MayaCmds.curveOnSurface(name, uv=((0.170718,0.565967), (0.0685088,0.393034), (0.141997,0.206296), (0.95,0.230359), (0.36264,0.441381), (0.251243,0.569889)), k=(0,0,0,0.200545,0.404853,0.598957,0.598957,0.598957)) MayaCmds.closeCurve(name+'->curve1', ch=1, ps=1, rpo=1, bb=0.5, bki=0, p=0.1, cos=1) if trimtype == 0 : MayaCmds.trim(name, lu=0.68, lv=0.39) elif 1 : MayaCmds.trim(name, lu=0.267062, lv=0.39475) degreeU = MayaCmds.getAttr(name+'.degreeU') degreeV = MayaCmds.getAttr(name+'.degreeV') spansU = MayaCmds.getAttr(name+'.spansU') spansV = MayaCmds.getAttr(name+'.spansV') formU = MayaCmds.getAttr(name+'.formU') formV = MayaCmds.getAttr(name+'.formV') minU = MayaCmds.getAttr(name+'.minValueU') maxU = MayaCmds.getAttr(name+'.maxValueU') minV = MayaCmds.getAttr(name+'.minValueV') maxV = MayaCmds.getAttr(name+'.maxValueV') surfaceInfoNode = MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', surfaceInfoNode+'.inputSurface', force=True) controlPoints = MayaCmds.getAttr(surfaceInfoNode+'.controlPoints[*]') knotsU = MayaCmds.getAttr(surfaceInfoNode+'.knotsU[*]') knotsV = MayaCmds.getAttr(surfaceInfoNode+'.knotsV[*]') MayaCmds.AbcExport(j='-root %s -f %s' % (name, abcFileName)) MayaCmds.AbcImport(abcFileName, mode='open') self.failUnlessEqual(degreeU, MayaCmds.getAttr(name+'.degreeU')) self.failUnlessEqual(degreeV, MayaCmds.getAttr(name+'.degreeV')) self.failUnlessEqual(spansU, MayaCmds.getAttr(name+'.spansU')) self.failUnlessEqual(spansV, MayaCmds.getAttr(name+'.spansV')) self.failUnlessEqual(minU, MayaCmds.getAttr(name+'.minValueU')) self.failUnlessEqual(maxU, MayaCmds.getAttr(name+'.maxValueU')) self.failUnlessEqual(minV, MayaCmds.getAttr(name+'.minValueV')) self.failUnlessEqual(maxV, MayaCmds.getAttr(name+'.maxValueV')) surfaceInfoNode = MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', surfaceInfoNode+'.inputSurface', force=True) controlPoints2 = MayaCmds.getAttr( surfaceInfoNode + '.controlPoints[*]') self.failUnlessEqual(len(controlPoints), len(controlPoints2)) for i in range(0, len(controlPoints)): cp1 = controlPoints[i] cp2 = controlPoints2[i] self.failUnlessAlmostEqual(cp1[0], cp2[0], 3, 'cp[%d].x not equal' % i) self.failUnlessAlmostEqual(cp1[1], cp2[1], 3, 'cp[%d].y not equal' % i) self.failUnlessAlmostEqual(cp1[2], cp2[2], 3, 'cp[%d].z not equal' % i) for i in range(0, len(knotsU)): ku1 = knotsU[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % i) self.failUnlessAlmostEqual(ku1, ku2, 3, 'control knotsU # %d not equal' % i) for i in range(0, len(knotsV)): kv1 = knotsV[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % i) self.failUnlessAlmostEqual(kv1, kv2, 3, 'control knotsV # %d not equal' % i) class StaticNurbsSurfaceTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticNurbsSurfaceWithoutTrimReadWrite(self): # open - open surface self.__files.append(util.expandFileName('testStaticNurbsPlaneWithoutTrim.abc')) testStaticNurbsWithoutTrim(self, 0, self.__files[-1]) # open - periodic surface self.__files.append(util.expandFileName('testStaticNurbsSphereWithoutTrim.abc')) testStaticNurbsWithoutTrim(self, 1, self.__files[-1]) # periodic - periodic surface self.__files.append(util.expandFileName('testStaticNurbsTorusWithoutTrim.abc')) testStaticNurbsWithoutTrim(self, 2 , self.__files[-1]) def testStaticNurbsSurfaceWithOneCloseCurveTrimInsideReadWrite(self): # open - open surface self.__files.append(util.expandFileName('testStaticNurbsPlaneWithOneCloseCurveTrimInside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 0 , self.__files[-1], 0) # open - periodic surface self.__files.append(util.expandFileName('testStaticNurbsSphereWithOneCloseCurveTrimInside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 1, self.__files[-1], 0) # periodic - periodic surface self.__files.append(util.expandFileName('testStaticNurbsTorusWithOneCloseCurveTrimInside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 2, self.__files[-1], 0) def testStaticNurbsSurfaceWithOneCloseCurveTrimOutsideReadWrite(self): # open - open surface self.__files.append(util.expandFileName('testStaticNurbsPlaneWithOneCloseCurveTrimOutside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 0, self.__files[-1], 1) # open - periodic surface self.__files.append(util.expandFileName('testStaticNurbsSphereWithOneCloseCurveTrimOutside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 1, self.__files[-1], 1) # periodic - periodic surface self.__files.append(util.expandFileName('testStaticNurbsTorusWithOneCloseCurveTrimOutside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 2, self.__files[-1], 1) def testStaticNurbsPlaneWithOneSegmentTrimReadWrite(self): ret = MayaCmds.nurbsPlane(p=(0, 0, 0), ax=(0, 1, 0), w=1, lr=1, d=3, u=5, v=5, ch=0) name = ret[0] MayaCmds.curveOnSurface(name, uv=((0.597523,0), (0.600359,0.271782), (0.538598,0.564218), (0.496932,0.779936), (0.672153,1)), k=(0,0,0,0.263463,0.530094,0.530094,0.530094)) MayaCmds.trim(name, lu=0.68, lv=0.39) degreeU = MayaCmds.getAttr(name+'.degreeU') degreeV = MayaCmds.getAttr(name+'.degreeV') spansU = MayaCmds.getAttr(name+'.spansU') spansV = MayaCmds.getAttr(name+'.spansV') minU = MayaCmds.getAttr(name+'.minValueU') maxU = MayaCmds.getAttr(name+'.maxValueU') minV = MayaCmds.getAttr(name+'.minValueV') maxV = MayaCmds.getAttr(name+'.maxValueV') MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', 'surfaceInfo1.inputSurface', force=True) controlPoints = MayaCmds.getAttr('surfaceInfo1.controlPoints[*]') knotsU = MayaCmds.getAttr('surfaceInfo1.knotsU[*]') knotsV = MayaCmds.getAttr('surfaceInfo1.knotsV[*]') self.__files.append(util.expandFileName('testStaticNurbsPlaneWithOneSegmentTrim.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (name, self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') self.failUnlessEqual(degreeU, MayaCmds.getAttr(name+'.degreeU')) self.failUnlessEqual(degreeV, MayaCmds.getAttr(name+'.degreeV')) self.failUnlessEqual(spansU, MayaCmds.getAttr(name+'.spansU')) self.failUnlessEqual(spansV, MayaCmds.getAttr(name+'.spansV')) self.failUnlessEqual(0, MayaCmds.getAttr(name+'.formU')) self.failUnlessEqual(0, MayaCmds.getAttr(name+'.formV')) self.failUnlessEqual(minU, MayaCmds.getAttr(name+'.minValueU')) self.failUnlessEqual(maxU, MayaCmds.getAttr(name+'.maxValueU')) self.failUnlessEqual(minV, MayaCmds.getAttr(name+'.minValueV')) self.failUnlessEqual(maxV, MayaCmds.getAttr(name+'.maxValueV')) MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', 'surfaceInfo1.inputSurface', force=True) for i in range(0, len(controlPoints)): cp1 = controlPoints[i] cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % i) self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, 'control point [%d].x not equal' % i) self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, 'control point [%d].y not equal' % i) self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, 'control point [%d].z not equal' % i) for i in range(0, len(knotsU)): ku1 = knotsU[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % i) self.failUnlessAlmostEqual(ku1, ku2, 3, 'control knotsU # %d not equal' % i) for i in range(0, len(knotsV)): kv1 = knotsV[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % i) self.failUnlessAlmostEqual(kv1, kv2, 3, 'control knotsV # %d not equal' % i)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import unittest import util class MayaReloadTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) # this test makes sure that not just the vertex positions but the # connection info is all correct def testAnimMeshReload(self): MayaCmds.polyCube( name = 'mesh') MayaCmds.setKeyframe('meshShape.vtx[0:7]', time=[1, 24]) MayaCmds.setKeyframe('meshShape.vtx[0:7]') MayaCmds.currentTime(12, update=True) MayaCmds.select('meshShape.vtx[0:7]') MayaCmds.scale(5, 5, 5, r=True) MayaCmds.setKeyframe('meshShape.vtx[0:7]', time=[12]) self.__files.append(util.expandFileName('testAnimMeshReadWrite.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root mesh -f ' + self.__files[-1]) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') # save as a maya file self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # reload as a maya file MayaCmds.file(self.__files[-1], open=True) MayaCmds.AbcImport(self.__files[-2], mode='import') retVal = True mesh1 = '|mesh|meshShape' mesh2 = '|mesh1|meshShape' for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareMesh( mesh1, mesh2 ): self.fail('%s and %s were not equal at frame %d' % (mesh1, mesh2, t)) #------------------------------------------------------------------------------- # The following tests each creates four animated nodes of the same data # type, writes out to Abc file, loads back the file and deletes one node. # Then the scene is saved as a Maya file, and load back to check if the # reload works as expected #------------------------------------------------------------------------------- def testAnimPolyDeleteReload(self): # create a poly cube and animate shapeName = 'pCube' MayaCmds.polyCube( name=shapeName ) MayaCmds.move(5, 0, 0, r=True) MayaCmds.setKeyframe( shapeName+'.vtx[2:5]', time=[1, 24] ) MayaCmds.currentTime( 12 ) MayaCmds.select( shapeName+'.vtx[2:5]',replace=True ) MayaCmds.move(0, 4, 0, r=True) MayaCmds.setKeyframe( shapeName+'.vtx[2:5]', time=[12] ) # create a poly sphere and animate shapeName = 'pSphere' MayaCmds.polySphere( name=shapeName ) MayaCmds.move(-5, 0, 0, r=True) MayaCmds.setKeyframe( shapeName+'.vtx[200:379]', shapeName+'.vtx[381]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select( shapeName+'.vtx[200:379]', shapeName+'.vtx[381]',replace=True) MayaCmds.scale(0.5, 0.5, 0.5, relative=True) MayaCmds.setKeyframe( shapeName+'.vtx[200:379]', shapeName+'.vtx[381]', time=[12]) MayaCmds.currentTime(1) # create a poly torus and animate shapeName = 'pTorus' MayaCmds.polyTorus(name=shapeName) MayaCmds.setKeyframe(shapeName+'.vtx[200:219]',time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[200:219]',replace=True) MayaCmds.scale(2, 1, 2, relative=True) MayaCmds.setKeyframe(shapeName+'.vtx[200:219]', time=[12]) # create a poly cone and animate shapeName = 'pCone' MayaCmds.polyCone(name=shapeName) MayaCmds.move(0, 0, -5, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[20]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[20]',replace=True) MayaCmds.move(0, 4, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[20]', time=[12]) # write it out to Abc file and load back in self.__files.append(util.expandFileName('testPolyReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root pCube -root pSphere -root pTorus -root pCone -file %s' % self.__files[-1]) # load back the Abc file, delete the sphere and save to a maya file MayaCmds.AbcImport( self.__files[-1], mode='open') MayaCmds.delete('pSphere') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('pCube', 'pTorus', 'pCone', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') shapeList = MayaCmds.ls(type='mesh') self.failUnlessEqual(len(shapeList), 7) meshes = [('|pCube|pCubeShape', '|ReloadGrp|pCube|pCubeShape'), ('|pTorus|pTorusShape', '|ReloadGrp|pTorus|pTorusShape'), ('|pCone|pConeShape', '|ReloadGrp|pCone|pConeShape')] for m in meshes: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareMesh(m[0], m[1]): self.fail('%s and %s are not the same at frame %d' % (m[0], m[1], t)) def testAnimSubDDeleteReload(self): # create a subD cube and animate shapeName = 'cube' MayaCmds.polyCube( name=shapeName ) MayaCmds.select('cubeShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) MayaCmds.move(5, 0, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[2:5]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[2:5]',replace=True) MayaCmds.move(0, 4, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[2:5]', time=[12]) # create a subD sphere and animate shapeName = 'sphere' MayaCmds.polySphere(name=shapeName) MayaCmds.select('sphereShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) MayaCmds.move(-5, 0, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[200:379]', shapeName+'.vtx[381]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[200:379]', shapeName+'.vtx[381]', replace=True) MayaCmds.scale(0.5, 0.5, 0.5, relative=True) MayaCmds.setKeyframe(shapeName+'.vtx[200:379]', shapeName+'.vtx[381]', time=[12]) MayaCmds.currentTime(1) # create a subD torus and animate shapeName = 'torus' MayaCmds.polyTorus(name=shapeName) MayaCmds.select('torusShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) MayaCmds.setKeyframe(shapeName+'.vtx[200:219]',time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[200:219]',replace=True) MayaCmds.scale(2, 1, 2, relative=True) MayaCmds.setKeyframe(shapeName+'.vtx[200:219]', time=[12]) # create a subD cone and animate shapeName = 'cone' MayaCmds.polyCone( name=shapeName ) MayaCmds.select('coneShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) MayaCmds.move(0, 0, -5, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[20]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[20]',replace=True) MayaCmds.move(0, 4, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[20]', time=[12]) self.__files.append(util.expandFileName('testSubDReload.abc')) # write it out to Abc file and load back in MayaCmds.AbcExport(j='-fr 1 24 -root cube -root sphere -root torus -root cone -file ' + self.__files[-1]) # load back the Abc file, delete the sphere and save to a maya file MayaCmds.AbcImport( self.__files[-1], mode='open' ) MayaCmds.delete('sphere') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('cube', 'torus', 'cone', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') shapeList = MayaCmds.ls(type='mesh') self.failUnlessEqual(len(shapeList), 7) # test the equality of cubes meshes = [('|cube|cubeShape', '|ReloadGrp|cube|cubeShape'), ('|torus|torusShape', '|ReloadGrp|torus|torusShape'), ('|cone|coneShape', '|ReloadGrp|cone|coneShape')] for m in meshes: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareMesh(m[0], m[1]): self.fail('%s and %s are not the same at frame %d' % (m[0], m[1], t)) def testAnimNSurfaceDeleteReload(self): # create an animated Nurbs sphere MayaCmds.sphere(ch=False, name='nSphere') MayaCmds.move(5, 0, 0, relative=True) MayaCmds.select('nSphere.cv[0:1][0:7]', 'nSphere.cv[5:6][0:7]', replace=True) MayaCmds.setKeyframe(time=[1, 24]) MayaCmds.currentTime(12, update=True) MayaCmds.scale(1.5, 1, 1, relative=True) MayaCmds.setKeyframe(time=12) # create an animated Nurbs torus MayaCmds.torus(ch=False, name='nTorus') MayaCmds.move(-5, 0, 0, relative=True) MayaCmds.select('nTorus.cv[0][0:7]', 'nTorus.cv[2][0:7]', replace=True) MayaCmds.setKeyframe(time=[1, 24]) MayaCmds.currentTime(12, update=True) MayaCmds.scale(1, 2, 2, relative=True) MayaCmds.setKeyframe(time=12) # create an animated Nurbs plane # should add the trim curve test on this surface, will be easier # than the rest MayaCmds.nurbsPlane(ch=False, name='nPlane') MayaCmds.move(-5, 5, 0, relative=True) MayaCmds.select('nPlane.cv[0:3][0:3]', replace=True) MayaCmds.setKeyframe(time=1) MayaCmds.currentTime(12, update=True) MayaCmds.rotate(0, 0, 90, relative=True) MayaCmds.setKeyframe(time=12) MayaCmds.currentTime(24, update=True) MayaCmds.rotate(0, 0, 90, relative=True) MayaCmds.setKeyframe(time=24) # create an animated Nurbs cylinder MayaCmds.cylinder(ch=False, name='nCylinder') MayaCmds.select('nCylinder.cv[0][0:7]', replace=True) MayaCmds.setKeyframe(time=[1, 24]) MayaCmds.currentTime(12, update=True) MayaCmds.move(-3, 0, 0, relative=True) MayaCmds.setKeyframe(time=12) # write it out to Abc file and load back in self.__files.append(util.expandFileName('testNSurfaceReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root nSphere -root nTorus -root nPlane -root nCylinder -file ' + self.__files[-1]) # load back the Abc file, delete the torus and save to a maya file MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.delete('nTorus') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('nSphere', 'nPlane', 'nCylinder', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') surfaceList = MayaCmds.ls(type='nurbsSurface') self.failUnlessEqual(len(surfaceList), 7) surfaces = [('|nSphere|nSphereShape', '|ReloadGrp|nSphere|nSphereShape'), ('|nPlane|nPlaneShape', '|ReloadGrp|nPlane|nPlaneShape'), ('|nCylinder|nCylinderShape', '|ReloadGrp|nCylinder|nCylinderShape')] for s in surfaces: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareNurbsSurface(s[0], s[1]): self.fail('%s and %s are not the same at frame %d' % (s[0], s[1], t)) def testAnimNSurfaceAndPolyDeleteReload(self): # create a poly cube and animate shapeName = 'pCube' MayaCmds.polyCube(name=shapeName) MayaCmds.move(5, 0, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[2:5]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[2:5]',replace=True) MayaCmds.move(0, 4, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[2:5]', time=[12]) # create an animated Nurbs plane MayaCmds.nurbsPlane(ch=False, name='nPlane') MayaCmds.move(-5, 5, 0, relative=True) MayaCmds.select('nPlane.cv[0:3][0:3]', replace=True) MayaCmds.setKeyframe(time=1) MayaCmds.currentTime(12, update=True) MayaCmds.rotate(0, 0, 90, relative=True) MayaCmds.setKeyframe(time=12) MayaCmds.currentTime(24, update=True) MayaCmds.rotate(0, 0, 90, relative=True) MayaCmds.setKeyframe(time=24) # write it out to Abc file and load back in self.__files.append(util.expandFileName('testNSurfaceAndPolyReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root pCube -root nPlane -file ' + self.__files[-1]) # load back the Abc file, delete the cube and save to a maya file MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.delete('pCube') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('nPlane', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') shapeList = MayaCmds.ls(type='mesh') self.failUnlessEqual(len(shapeList), 1) surfaceList = MayaCmds.ls(type='nurbsSurface') self.failUnlessEqual(len(surfaceList), 2) # test the equality of plane surface1 = '|nPlane|nPlaneShape' surface2 = '|ReloadGrp|nPlane|nPlaneShape' for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareNurbsSurface( surface1, surface2 ): self.fail('%s and %s are not the same at frame %d' % (surface1, surface2, t)) def testAnimCameraDeleteReload(self): # cam1 MayaCmds.camera(name='cam1') MayaCmds.setAttr('cam1Shape1.horizontalFilmAperture', 0.962) MayaCmds.setAttr('cam1Shape1.verticalFilmAperture', 0.731) MayaCmds.setAttr('cam1Shape1.focalLength', 50) MayaCmds.setAttr('cam1Shape1.focusDistance', 5) MayaCmds.setAttr('cam1Shape1.shutterAngle', 144) MayaCmds.setAttr('cam1Shape1.centerOfInterest', 1384.825) # cam2 MayaCmds.duplicate('cam1', returnRootsOnly=True) # cam3 MayaCmds.duplicate('cam1', returnRootsOnly=True) # cam4 MayaCmds.duplicate('cam1', returnRootsOnly=True) # animate each camera slightly different MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe('cam1Shape1', attribute='horizontalFilmAperture') MayaCmds.setKeyframe('cam2Shape', attribute='focalLength') MayaCmds.setKeyframe('cam3Shape', attribute='focusDistance') MayaCmds.setKeyframe('cam4Shape', attribute='shutterAngle') MayaCmds.setKeyframe('cam4Shape', attribute='centerOfInterest') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe('cam1Shape1', attribute='horizontalFilmAperture', value=0.95) MayaCmds.setKeyframe('cam2Shape', attribute='focalLength', value=40) MayaCmds.setKeyframe('cam3Shape', attribute='focusDistance', value=5.4) MayaCmds.setKeyframe('cam4Shape', attribute='shutterAngle', value=174.94) MayaCmds.setKeyframe('cam4Shape', attribute='centerOfInterest', value=67.418) # write them out to an Abc file and load back in self.__files.append(util.expandFileName('testCamReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root cam1 -root cam2 -root cam3 -root cam4 -file ' + self.__files[-1]) # load back the Abc file, delete the 2nd camera and save to a maya file MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.delete('cam2') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('cam1', 'cam3', 'cam4', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') camList = MayaCmds.ls(type='camera') # should be 7, but this query will return the four standard cameras in # the scene too self.failUnlessEqual(len(camList), 11) # test the equality of cameras cameras = [('|cam1|cam1Shape1', '|ReloadGrp|cam1|cam1Shape1'), ('|cam3|cam3Shape', '|ReloadGrp|cam3|cam3Shape'), ('|cam4|cam4Shape', '|ReloadGrp|cam4|cam4Shape')] for c in cameras: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareCamera(c[0], c[1]): self.fail('%s and %s are not the same at frame %d' % (c[0], c[1], t)) def testAnimNCurvesDeleteReload(self): # create some animated curves MayaCmds.textCurves(ch=False, t='Maya', name='Curves', font='Courier') MayaCmds.currentTime(1, update=True) MayaCmds.select('curve1.cv[0:27]', 'curve2.cv[0:45]', 'curve3.cv[0:15]', 'curve4.cv[0:19]', 'curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.setKeyframe() MayaCmds.currentTime(24, update=True) MayaCmds.select('curve1.cv[0:27]', replace=True) MayaCmds.move(-3, 3, 0, relative=True) MayaCmds.select('curve2.cv[0:45]', 'curve3.cv[0:15]', replace=True) MayaCmds.scale(1.5, 1.5, 1.5, relative=True) MayaCmds.select('curve4.cv[0:19]', replace=True) MayaCmds.move(1.5, 0, 0, relative=True) MayaCmds.rotate(0, 90, 0, relative=True) MayaCmds.select('curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.move(3, 0, 0, relative=True) MayaCmds.select('curve1.cv[0:27]', 'curve2.cv[0:45]', 'curve3.cv[0:15]', 'curve4.cv[0:19]', 'curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.setKeyframe() # write them out to an Abc file and load back in self.__files.append(util.expandFileName('testNCurvesReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root CurvesShape -file ' + self.__files[-1]) # load back the Abc file, delete the 2nd letter and save to a maya file MayaCmds.AbcImport(self.__files[-1], mode='open') # delete letter "a" which has two curves MayaCmds.delete('Char_a_1') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('CurvesShape', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') curveList = MayaCmds.ls(type='nurbsCurve') self.failUnlessEqual(len(curveList), 10) # test the equality of curves curves = [('|CurvesShape|Char_M_1|curve1|curveShape1', '|ReloadGrp|CurvesShape|Char_M_1|curve1|curveShape1'), ('|CurvesShape|Char_y_1|curve4|curveShape4', '|ReloadGrp|CurvesShape|Char_y_1|curve4|curveShape4'), ('|CurvesShape|Char_a_2|curve5|curveShape5', '|ReloadGrp|CurvesShape|Char_a_2|curve5|curveShape5'), ('|CurvesShape|Char_a_2|curve6|curveShape6', '|ReloadGrp|CurvesShape|Char_a_2|curve6|curveShape6')] for c in curves: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareNurbsCurve(c[0], c[1]): self.fail('%s and %s are not the same at frame %d' % (c[0], c[1], t)) #------------------------------------------------------------------------- def testAnimNCurveGrpDeleteReload(self): # create an animated curves group MayaCmds.textCurves(ch=False, t='haka', name='Curves', font='Courier') MayaCmds.addAttr(longName='riCurves', at='bool', dv=True) MayaCmds.currentTime(1, update=True) MayaCmds.select('curve1.cv[0:27]', 'curve2.cv[0:45]', 'curve3.cv[0:15]', 'curve4.cv[0:19]', 'curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.setKeyframe() MayaCmds.currentTime(24, update=True) MayaCmds.select('curve1.cv[0:27]', replace=True) MayaCmds.move(-3, 3, 0, relative=True) MayaCmds.select('curve2.cv[0:45]', 'curve3.cv[0:15]', replace=True) MayaCmds.scale(1.5, 1.5, 1.5, relative=True) MayaCmds.select('curve4.cv[0:19]', replace=True) MayaCmds.move(1.5, 0, 0, relative=True) MayaCmds.rotate(0, 90, 0, relative=True) MayaCmds.select('curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.move(3, 0, 0, relative=True) MayaCmds.select('curve1.cv[0:27]', 'curve2.cv[0:45]', 'curve3.cv[0:15]', 'curve4.cv[0:19]', 'curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.setKeyframe() # write them out to an Abc file and load back in self.__files.append(util.expandFileName('testNCurveGrpReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root CurvesShape -file ' + self.__files[-1]) # load back the Abc file, delete the 2nd letter and save to a maya file MayaCmds.AbcImport(self.__files[-1], mode='open') # delete letter "a" which has two curves, but as a curve group. # the curve shapes are renamed under the group node MayaCmds.delete('CurvesShape1') MayaCmds.delete('CurvesShape2') self.__files.append(util.expandFileName('testCurves.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('|CurvesShape', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') curveList = MayaCmds.ls(type='nurbsCurve') self.failUnlessEqual(len(curveList), 10) curves = [('|CurvesShape|CurvesShape', '|ReloadGrp|CurvesShape|CurvesShape'), ('|CurvesShape|CurvesShape8', '|ReloadGrp|CurvesShape|CurvesShape3'), ('|CurvesShape|CurvesShape9', '|ReloadGrp|CurvesShape|CurvesShape4'), ('|CurvesShape|CurvesShape10', '|ReloadGrp|CurvesShape|CurvesShape5')] for c in curves: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareNurbsCurve(c[0], c[1]): self.fail('%s and %s are not the same at frame %d' % (c[0], c[1], t)) def testAnimPropDeleteReload(self): # create some animated properties on a transform node ( could be any type ) nodeName = MayaCmds.polyPrism(ch=False, name = 'prism') MayaCmds.addAttr(longName='SPT_int8', defaultValue=0, attributeType='byte', keyable=True) MayaCmds.addAttr(longName='SPT_int16', defaultValue=100, attributeType='short', keyable=True) MayaCmds.addAttr(longName='SPT_int32', defaultValue=1000, attributeType='long', keyable=True) MayaCmds.addAttr(longName='SPT_float', defaultValue=0.57777777, attributeType='float', keyable=True) MayaCmds.addAttr(longName='SPT_double', defaultValue=5.0456435, attributeType='double', keyable=True) MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(nodeName, attribute='SPT_int8') MayaCmds.setKeyframe(nodeName, attribute='SPT_int16') MayaCmds.setKeyframe(nodeName, attribute='SPT_int32') MayaCmds.setKeyframe(nodeName, attribute='SPT_float') MayaCmds.setKeyframe(nodeName, attribute='SPT_double') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe(nodeName, attribute='SPT_int8', value=8) MayaCmds.setKeyframe(nodeName, attribute='SPT_int16', value=16) MayaCmds.setKeyframe(nodeName, attribute='SPT_int32', value=32) MayaCmds.setKeyframe(nodeName, attribute='SPT_float', value=5.24847) MayaCmds.setKeyframe(nodeName, attribute='SPT_double', value=3.14154) # create SPT_HWColor on the shape node MayaCmds.select('prismShape') MayaCmds.addAttr(longName='SPT_HwColorR', defaultValue=1.0, minValue=0.0, maxValue=1.0) MayaCmds.addAttr(longName='SPT_HwColorG', defaultValue=1.0, minValue=0.0, maxValue=1.0) MayaCmds.addAttr(longName='SPT_HwColorB', defaultValue=1.0, minValue=0.0, maxValue=1.0) MayaCmds.addAttr( longName='SPT_HwColor', usedAsColor=True, attributeType='float3') MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(at='SPT_HwColorR') MayaCmds.setKeyframe(at='SPT_HwColorG') MayaCmds.setKeyframe(at='SPT_HwColorB') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe(at='SPT_HwColorR', value=0.5) MayaCmds.setKeyframe(at='SPT_HwColorG', value=0.15) MayaCmds.setKeyframe(at='SPT_HwColorB', value=0.75) # write them out to an Abc file and load back in self.__files.append(util.expandFileName('testPropReload.abc')) MayaCmds.AbcExport(j='-atp SPT_ -fr 1 24 -root prism -file ' + self.__files[-1]) # load back the Abc file, delete the 2nd letter and save to a maya file abcNode = MayaCmds.AbcImport( self.__files[-1], mode='open' ) # delete connections to animated props prop = MayaCmds.listConnections('|prism.SPT_float', p=True)[0] MayaCmds.disconnectAttr(prop, '|prism.SPT_float') attr = '|prism|prismShape.SPT_HwColorG' prop = MayaCmds.listConnections(attr, p=True)[0] MayaCmds.disconnectAttr(prop, attr) self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('prism', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') # test the equality of props for t in range(1, 25): MayaCmds.currentTime(t, update=True) self.failUnlessEqual(MayaCmds.getAttr('|prism.SPT_int8'), MayaCmds.getAttr('|ReloadGrp|prism.SPT_int8'), 'prism.SPT_int8 not equal' ) self.failUnlessEqual(MayaCmds.getAttr('|prism.SPT_int16'), MayaCmds.getAttr('|ReloadGrp|prism.SPT_int16'), 'prism.SPT_int16 not equal') self.failUnlessEqual(MayaCmds.getAttr('|prism.SPT_int32'), MayaCmds.getAttr('|ReloadGrp|prism.SPT_int32'), 'prism.SPT_int32 not equal') self.failUnlessAlmostEqual(MayaCmds.getAttr('|prism.SPT_double'), MayaCmds.getAttr('|ReloadGrp|prism.SPT_double'), 4, 'prism.SPT_double not equal') self.failUnlessAlmostEqual( MayaCmds.getAttr('|prism|prismShape.SPT_HwColorR'), MayaCmds.getAttr('|ReloadGrp|prism|prismShape.SPT_HwColorR'), 4, 'prismShape.SPT_HwColorR not equal') self.failUnlessAlmostEqual( MayaCmds.getAttr('|prism|prismShape.SPT_HwColorB'), MayaCmds.getAttr('|ReloadGrp|prism|prismShape.SPT_HwColorB'), 4, 'prismShape.SPT_HwColorB not equal')
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class renderableOnlyTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testRenderableOnly(self): MayaCmds.polyPlane(name='potato') MayaCmds.polyPlane(name='hidden') MayaCmds.setAttr("hidden.visibility", 0) self.__files.append(util.expandFileName('renderableOnlyTest.abc')) MayaCmds.AbcExport(j='-renderableOnly -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') self.failUnless(MayaCmds.objExists('potato')) self.failIf(MayaCmds.objExists('hidden'))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** import maya.cmds as MayaCmds import os import subprocess import unittest import util class animPropTest(unittest.TestCase): #------------------------------------------------------------------------- def setUp(self): MayaCmds.file(new=True, force=True) self.__abcStitcher = [os.environ['AbcStitcher']] self.__files = [util.expandFileName('animProp.abc'), util.expandFileName('animProp01_14.abc'), util.expandFileName('animProp15_24.abc')] #------------------------------------------------------------------------- def tearDown(self): for f in self.__files : os.remove(f) #------------------------------------------------------------------------- def setAndKeyProps( self, nodeName ): MayaCmds.select(nodeName) MayaCmds.addAttr(longName='SPT_int8', defaultValue=0, attributeType='byte', keyable=True) MayaCmds.addAttr(longName='SPT_int16', defaultValue=0, attributeType='short', keyable=True) MayaCmds.addAttr(longName='SPT_int32', defaultValue=0, attributeType='long', keyable=True) MayaCmds.addAttr(longName='SPT_float', defaultValue=0, attributeType='float', keyable=True) MayaCmds.addAttr(longName='SPT_double', defaultValue=0, attributeType='double', keyable=True) MayaCmds.setKeyframe(nodeName, value=0, attribute='SPT_int8', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=100, attribute='SPT_int16', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=1000, attribute='SPT_int32', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=0.57777777, attribute='SPT_float', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=5.045643545457, attribute='SPT_double', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=8, attribute='SPT_int8', t=12) MayaCmds.setKeyframe(nodeName, value=16, attribute='SPT_int16', t=12) MayaCmds.setKeyframe(nodeName, value=32, attribute='SPT_int32', t=12) MayaCmds.setKeyframe(nodeName, value=3.141592654, attribute='SPT_float', t=12) MayaCmds.setKeyframe(nodeName, value=3.141592654, attribute='SPT_double', t=12) def verifyProps( self, root, nodeName ): # write to files MayaCmds.AbcExport(j='-atp SPT_ -fr 1 14 -root %s -file %s' % (root, self.__files[1])) MayaCmds.AbcExport(j='-atp SPT_ -fr 15 24 -root %s -file %s' % (root, self.__files[2])) subprocess.call(self.__abcStitcher + self.__files) # read file and verify data MayaCmds.AbcImport(self.__files[0], mode='open') t = 1 # frame 1 MayaCmds.currentTime(t, update=True) self.failUnlessEqual(0, MayaCmds.getAttr(nodeName+'.SPT_int8'), '%s.SPT_int8 != 0 at frame %d' %( nodeName, t)) self.failUnlessEqual(100, MayaCmds.getAttr(nodeName+'.SPT_int16'), '%s.SPT_int16 != 100 at frame %d' %( nodeName, t)) self.failUnlessEqual(1000, MayaCmds.getAttr(nodeName+'.SPT_int32'), '%s.SPT_int32 != 1000 at frame %d' %( nodeName, t)) self.failUnlessAlmostEqual(0.57777777, MayaCmds.getAttr(nodeName+'.SPT_float'), 4, '%s.SPT_float != 0.57777777 at frame %d' %( nodeName, t)) self.failUnlessAlmostEqual(5.045643545457, MayaCmds.getAttr(nodeName+'.SPT_double'), 7, '%s.SPT_double != 5.045643545457 at frame %d' %( nodeName, t)) t = 12 # frame 12 MayaCmds.currentTime(t, update=True) self.failUnlessEqual(8, MayaCmds.getAttr(nodeName+'.SPT_int8'), '%s.SPT_int8 != 8 at frame %d' %( nodeName, t)) self.failUnlessEqual(16, MayaCmds.getAttr(nodeName+'.SPT_int16'), '%s.SPT_int16 != 16 at frame %d' %( nodeName, t)) self.failUnlessEqual(32, MayaCmds.getAttr(nodeName+'.SPT_int32'), '%s.SPT_int32 != 32 at frame %d' %( nodeName, t)) self.failUnlessAlmostEqual(3.141592654, MayaCmds.getAttr(nodeName+'.SPT_float'), 4, '%s.SPT_float != 3.141592654 at frame %d' %( nodeName, t)) self.failUnlessAlmostEqual(3.1415926547, MayaCmds.getAttr(nodeName+'.SPT_double'), 7, '%s.SPT_double != 3.141592654 at frame %d' %( nodeName, t)) t = 24 # frame 24 MayaCmds.currentTime(t, update=True) self.failUnlessEqual(0,MayaCmds.getAttr(nodeName+'.SPT_int8'), '%s.SPT_int8 != 0 at frame %d' % (nodeName, t)) self.failUnlessEqual(100, MayaCmds.getAttr(nodeName+'.SPT_int16'), '%s.SPT_int16 != 100 at frame %d' % (nodeName, t)) self.failUnlessEqual(1000, MayaCmds.getAttr(nodeName+'.SPT_int32'), '%s.SPT_int32 != 1000 at frame %d' % (nodeName, t)) self.failUnlessAlmostEqual(0.57777777, MayaCmds.getAttr(nodeName+'.SPT_float'), 4, '%s.SPT_float != 0.57777777 at frame %d' % (nodeName, t)) self.failUnlessAlmostEqual(5.045643545457, MayaCmds.getAttr(nodeName+'.SPT_double'), 7, '%s.SPT_double != 5.045643545457 at frame %d' % (nodeName, t)) def testAnimTransformProp(self): nodeName = MayaCmds.createNode('transform') self.setAndKeyProps(nodeName) self.verifyProps(nodeName, nodeName) def testAnimCameraProp(self): root = MayaCmds.camera() nodeName = root[0] shapeName = root[1] self.setAndKeyProps(shapeName) self.verifyProps(nodeName, shapeName) def testAnimMeshProp(self): nodeName = 'polyCube' shapeName = 'polyCubeShape' MayaCmds.polyCube(name=nodeName, ch=False) self.setAndKeyProps(shapeName) self.verifyProps(nodeName, shapeName) def testAnimNurbsCurvePropReadWrite(self): nodeName = 'nCurve' shapeName = 'curveShape1' MayaCmds.curve(p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9)], name=nodeName) self.setAndKeyProps(shapeName) self.verifyProps(nodeName, shapeName) def testAnimNurbsSurfaceProp(self): nodeName = MayaCmds.sphere(ch=False)[0] nodeNameList = MayaCmds.pickWalk(d='down') shapeName = nodeNameList[0] self.setAndKeyProps(shapeName) self.verifyProps(nodeName, shapeName)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util def makeRobot(): MayaCmds.polyCube(name="head") MayaCmds.move(0, 4, 0, r=1) MayaCmds.polyCube(name="chest") MayaCmds.scale(2, 2.5, 1) MayaCmds.move(0, 2, 0, r=1) MayaCmds.polyCube(name="leftArm") MayaCmds.move(0, 3, 0, r=1) MayaCmds.scale(2, 0.5, 1, r=1) MayaCmds.duplicate(name="rightArm") MayaCmds.select("leftArm") MayaCmds.move(1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, 32, r=1, os=1) MayaCmds.select("rightArm") MayaCmds.move(-1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, -32, r=1, os=1) MayaCmds.select("rightArm", "leftArm", "chest", r=1) MayaCmds.group(name="body") MayaCmds.polyCube(name="bottom") MayaCmds.scale(2, 0.5, 1) MayaCmds.move(0, 0.5, 0, r=1) MayaCmds.polyCube(name="leftLeg") MayaCmds.scale(0.65, 2.8, 1, r=1) MayaCmds.move(-0.5, -1, 0, r=1) MayaCmds.duplicate(name="rightLeg") MayaCmds.move(1, 0, 0, r=1) MayaCmds.select("rightLeg", "leftLeg", "bottom", r=1) MayaCmds.group(name="lower") MayaCmds.select("head", "body", "lower", r=1) MayaCmds.group(name="robot") class selectionTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testWriteMultipleRoots(self): makeRobot() MayaCmds.duplicate("robot", name="dupRobot") self.__files.append(util.expandFileName('writeMultipleRootsTest.abc')) MayaCmds.AbcExport(j='-root dupRobot -root head -root lower -root chest -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') self.failUnless(MayaCmds.objExists("dupRobot")) self.failUnless(MayaCmds.objExists("head")) self.failUnless(MayaCmds.objExists("lower")) self.failUnless(MayaCmds.objExists("chest")) self.failIf(MayaCmds.objExists("robot")) self.failIf(MayaCmds.objExists("robot|body"))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import unittest import util def getObjFromName(nodeName): selectionList = OpenMaya.MSelectionList() selectionList.add(nodeName) obj = OpenMaya.MObject() selectionList.getDependNode(0, obj) return obj class PolyNormalsTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testSet_noNormals_Attr(self): MayaCmds.polyCube(name='polyCube') # add the necessary props MayaCmds.select('polyCubeShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='interpolateBoundary', attributeType='bool', defaultValue=True) MayaCmds.addAttr(longName='noNormals', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='flipNormals', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='faceVaryingInterpolateBoundary', attributeType='bool', defaultValue=False) MayaCmds.polySphere(name='polySphere') # add the necessary props MayaCmds.select('polySphereShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='interpolateBoundary', attributeType='bool', defaultValue=True) MayaCmds.addAttr(longName='noNormals', attributeType='bool', defaultValue=True) MayaCmds.addAttr(longName='flipNormals', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='faceVaryingInterpolateBoundary', attributeType='bool', defaultValue=False) #ignore facevaryingType, subdPaintLev MayaCmds.group('polyCube', 'polySphere', name='polygons') self.__files.append(util.expandFileName('staticPoly_noNormals_AttrTest.abc')) MayaCmds.AbcExport(j='-root polygons -f ' + self.__files[-1]) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open', debug=False) # make sure the noNormal attribute is set correctly when the file is loaded self.failIf(MayaCmds.listAttr('polyCubeShape').count('noNormals') != 0) self.failUnless(MayaCmds.getAttr('polySphereShape.noNormals')) def testStaticMeshPolyNormals(self): # create a polygon cube polyName = 'polyCube' polyShapeName = 'polyCubeShape' MayaCmds.polyCube( sx=1, sy=1, sz=1, name=polyName, constructionHistory=False) # add the necessary props MayaCmds.select(polyShapeName) MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='noNormals', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='flipNormals', attributeType='bool', defaultValue=False) # tweek some normals MayaCmds.select(polyName+'.vtxFace[2][1]', replace=True) MayaCmds.polyNormalPerVertex(xyz=(0.707107, 0.707107, 0)) MayaCmds.select(polyName+'.vtxFace[7][4]', replace=True) MayaCmds.polyNormalPerVertex(xyz=(-0.707107, 0.707107, 0)) # write to file self.__files.append(util.expandFileName('staticPolyNormalsTest.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (polyName, self.__files[-1])) # read back from file MayaCmds.AbcImport(self.__files[-1], mode='import') self.failIf(MayaCmds.listAttr('polyCube1|polyCubeShape').count('noNormals') != 0) # make sure the normals are the same shapeObj = getObjFromName('polyCube1|polyCubeShape') fnMesh = OpenMaya.MFnMesh(shapeObj) numFaces = fnMesh.numPolygons() for faceIndex in range(0, numFaces): vertexList = OpenMaya.MIntArray() fnMesh.getPolygonVertices(faceIndex, vertexList) numVertices = vertexList.length() for v in range(0, numVertices): vertexIndex = vertexList[v] normal = OpenMaya.MVector() fnMesh.getFaceVertexNormal(faceIndex, vertexIndex, normal) vtxFaceAttrName = '.vtxFace[%d][%d]' % (vertexIndex, faceIndex) MayaCmds.select(polyName+vtxFaceAttrName, replace=True) oNormal = MayaCmds.polyNormalPerVertex( query=True, xyz=True) self.failUnlessAlmostEqual(normal[0], oNormal[0], 4) self.failUnlessAlmostEqual(normal[1], oNormal[1], 4) self.failUnlessAlmostEqual(normal[2], oNormal[2], 4) def testAnimatedMeshPolyNormals(self): # create a polygon cube polyName = 'polyCube' polyShapeName = 'polyCubeShape' MayaCmds.polyCube(sx=1, sy=1, sz=1, name=polyName, constructionHistory=False) # add the necessary props MayaCmds.select(polyShapeName) MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='noNormals', attributeType='bool', defaultValue=False) MayaCmds.addAttr(longName='flipNormals', attributeType='bool', defaultValue=False) # tweek some normals MayaCmds.select(polyName+'.vtxFace[2][1]', replace=True) MayaCmds.polyNormalPerVertex(xyz=(0.707107, 0.707107, 0)) MayaCmds.select(polyName+'.vtxFace[7][4]', replace=True) MayaCmds.polyNormalPerVertex(xyz=(-0.707107, 0.707107, 0)) # set keyframes to make sure normals are written out as animated MayaCmds.setKeyframe(polyShapeName+'.vtx[0:7]', time=[1, 4]) MayaCmds.currentTime(2, update=True) MayaCmds.select(polyShapeName+'.vtx[0:3]') MayaCmds.move(0, 0.5, 1, relative=True) MayaCmds.setKeyframe(polyShapeName+'.vtx[0:7]', time=[2]) # write to file self.__files.append(util.expandFileName('animPolyNormalsTest.abc')) MayaCmds.AbcExport(j='-fr 1 4 -root %s -f %s' % (polyName, self.__files[-1])) # read back from file MayaCmds.AbcImport(self.__files[-1], mode='import') # make sure the noNormal attribute is set correctly when the file is # loaded self.failIf(MayaCmds.listAttr('polyCube1|polyCubeShape').count('noNormals') != 0) # make sure the normals are the same for time in range(1, 5): MayaCmds.currentTime(time, update=True) shapeObj = getObjFromName('polyCube1|polyCubeShape') fnMesh = OpenMaya.MFnMesh(shapeObj) numFaces = fnMesh.numPolygons() for faceIndex in range(0, numFaces): vertexList = OpenMaya.MIntArray() fnMesh.getPolygonVertices(faceIndex, vertexList) numVertices = vertexList.length() for v in range(0, numVertices): vertexIndex = vertexList[v] normal = OpenMaya.MVector() fnMesh.getFaceVertexNormal(faceIndex, vertexIndex, normal) vtxFaceAttrName = '.vtxFace[%d][%d]' % (vertexIndex, faceIndex) MayaCmds.select(polyName+vtxFaceAttrName, replace=True) oNormal = MayaCmds.polyNormalPerVertex(query=True, xyz=True) self.failUnlessAlmostEqual(normal[0], oNormal[0], 4) self.failUnlessAlmostEqual(normal[1], oNormal[1], 4) self.failUnlessAlmostEqual(normal[2], oNormal[2], 4)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import subprocess import unittest import util def createCamera(): name = MayaCmds.camera() MayaCmds.setAttr(name[1]+'.horizontalFilmAperture', 0.962) MayaCmds.setAttr(name[1]+'.verticalFilmAperture', 0.731) MayaCmds.setAttr(name[1]+'.focalLength', 50) MayaCmds.setAttr(name[1]+'.focusDistance', 5) MayaCmds.setAttr(name[1]+'.shutterAngle', 144) return name class cameraTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] self.__abcStitcher = [os.environ['AbcStitcher']] def tearDown(self): for f in self.__files: os.remove(f) def testStaticCameraReadWrite(self): name = createCamera() # write to file self.__files.append(util.expandFileName('testStaticCameraReadWrite.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (name[0], self.__files[-1])) # read from file MayaCmds.AbcImport(self.__files[-1], mode='import') camList = MayaCmds.ls(type='camera') self.failUnless(util.compareCamera(camList[0], camList[1])) def testAnimCameraReadWrite(self): name = createCamera() MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(name[1], attribute='horizontalFilmAperture') MayaCmds.setKeyframe(name[1], attribute='focalLength') MayaCmds.setKeyframe(name[1], attribute='focusDistance') MayaCmds.setKeyframe(name[1], attribute='shutterAngle') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe(name[1], attribute='horizontalFilmAperture', value=0.95) MayaCmds.setKeyframe(name[1], attribute='focalLength', value=40) MayaCmds.setKeyframe(name[1], attribute='focusDistance', value=5.4) MayaCmds.setKeyframe(name[1], attribute='shutterAngle', value=174.94) self.__files.append(util.expandFileName('testAnimCameraReadWrite.abc')) self.__files.append(util.expandFileName('testAnimCameraReadWrite01_14.abc')) self.__files.append(util.expandFileName('testAnimCameraReadWrite15-24.abc')) # write to files MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % (name[0], self.__files[-2])) MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % (name[0], self.__files[-1])) subprocess.call(self.__abcStitcher + self.__files[-3:]) # read from file MayaCmds.AbcImport(self.__files[-3], mode='import') camList = MayaCmds.ls(type='camera') for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareCamera(camList[0], camList[1]): self.fail('%s and %s are not the same at frame %d' % (camList[0], camList[1], t))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** import maya.cmds as MayaCmds import os import subprocess import unittest import util class AnimTransformTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__abcStitcher = [os.environ['AbcStitcher']] self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testAnimTransformReadWrite(self): nodeName = MayaCmds.createNode('transform', n='test') # shear MayaCmds.setKeyframe(nodeName, value=0, attribute='shearXY', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=0, attribute='shearYZ', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=0, attribute='shearXZ', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=1.5, attribute='shearXY', t=12) MayaCmds.setKeyframe(nodeName, value=5, attribute='shearYZ', t=12) MayaCmds.setKeyframe(nodeName, value=2.5, attribute='shearXZ', t=12) # translate MayaCmds.setKeyframe('test', value=0, attribute='translateX', t=[1, 24]) MayaCmds.setKeyframe('test', value=0, attribute='translateY', t=[1, 24]) MayaCmds.setKeyframe('test', value=0, attribute='translateZ', t=[1, 24]) MayaCmds.setKeyframe('test', value=1.5, attribute='translateX', t=12) MayaCmds.setKeyframe('test', value=5, attribute='translateY', t=12) MayaCmds.setKeyframe('test', value=2.5, attribute='translateZ', t=12) # rotate MayaCmds.setKeyframe('test', value=0, attribute='rotateX', t=[1, 24]) MayaCmds.setKeyframe('test', value=0, attribute='rotateY', t=[1, 24]) MayaCmds.setKeyframe('test', value=0, attribute='rotateZ', t=[1, 24]) MayaCmds.setKeyframe('test', value=24, attribute='rotateX', t=12) MayaCmds.setKeyframe('test', value=53, attribute='rotateY', t=12) MayaCmds.setKeyframe('test', value=90, attribute='rotateZ', t=12) # scale MayaCmds.setKeyframe('test', value=1, attribute='scaleX', t=[1, 24]) MayaCmds.setKeyframe('test', value=1, attribute='scaleY', t=[1, 24]) MayaCmds.setKeyframe('test', value=1, attribute='scaleZ', t=[1, 24]) MayaCmds.setKeyframe('test', value=1.2, attribute='scaleX', t=12) MayaCmds.setKeyframe('test', value=1.5, attribute='scaleY', t=12) MayaCmds.setKeyframe('test', value=1.5, attribute='scaleZ', t=12) # rotate pivot MayaCmds.setKeyframe('test', value=0.5, attribute='rotatePivotX', t=[1, 24]) MayaCmds.setKeyframe('test', value=-0.1, attribute='rotatePivotY', t=[1, 24]) MayaCmds.setKeyframe('test', value=1, attribute='rotatePivotZ', t=[1, 24]) MayaCmds.setKeyframe('test', value=0.8, attribute='rotatePivotX', t=12) MayaCmds.setKeyframe('test', value=1.5, attribute='rotatePivotY', t=12) MayaCmds.setKeyframe('test', value=-1, attribute='rotatePivotZ', t=12) # scale pivot MayaCmds.setKeyframe('test', value=1.2, attribute='scalePivotX', t=[1, 24]) MayaCmds.setKeyframe('test', value=1.0, attribute='scalePivotY', t=[1, 24]) MayaCmds.setKeyframe('test', value=1.2, attribute='scalePivotZ', t=[1, 24]) MayaCmds.setKeyframe('test', value=1.4, attribute='scalePivotX', t=12) MayaCmds.setKeyframe('test', value=1.5, attribute='scalePivotY', t=12) MayaCmds.setKeyframe('test', value=1.5, attribute='scalePivotZ', t=12) self.__files.append(util.expandFileName('testAnimTransformReadWrite.abc')) self.__files.append(util.expandFileName('testAnimTransformReadWrite01_14.abc')) self.__files.append(util.expandFileName('testAnimTransformReadWrite15_24.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root test -file ' + self.__files[-2]) MayaCmds.AbcExport(j='-fr 15 24 -root test -file ' + self.__files[-1]) subprocess.call(self.__abcStitcher + self.__files[-3:]) MayaCmds.AbcImport(self.__files[-3], mode='open') # frame 1 MayaCmds.currentTime(1, update=True) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearXY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearYZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearXZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateX')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateX')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateZ')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleX')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleY')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleZ')) self.failUnlessEqual(0.5, MayaCmds.getAttr('test.rotatePivotX')) self.failUnlessEqual(-0.1, MayaCmds.getAttr('test.rotatePivotY')) self.failUnlessEqual(1, MayaCmds.getAttr('test.rotatePivotZ')) self.failUnlessEqual(1.2, MayaCmds.getAttr('test.scalePivotX')) self.failUnlessEqual(1.0, MayaCmds.getAttr('test.scalePivotY')) self.failUnlessEqual(1.2, MayaCmds.getAttr('test.scalePivotZ')) # frame 12 MayaCmds.currentTime(12, update=True); abcNodeName = MayaCmds.ls(exactType='AlembicNode') MayaCmds.dgeval(abcNodeName, verbose=True) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.shearXY')) self.failUnlessEqual(5, MayaCmds.getAttr('test.shearYZ')) self.failUnlessEqual(2.5, MayaCmds.getAttr('test.shearXZ')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.translateX')) self.failUnlessEqual(5, MayaCmds.getAttr('test.translateY')) self.failUnlessEqual(2.5, MayaCmds.getAttr('test.translateZ')) self.failUnlessAlmostEqual(24.0, MayaCmds.getAttr('test.rotateX'), 4) self.failUnlessAlmostEqual(53.0, MayaCmds.getAttr('test.rotateY'), 4) self.failUnlessAlmostEqual(90.0, MayaCmds.getAttr('test.rotateZ'), 4) self.failUnlessEqual(1.2, MayaCmds.getAttr('test.scaleX')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.scaleY')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.scaleZ')) self.failUnlessEqual(0.8, MayaCmds.getAttr('test.rotatePivotX')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.rotatePivotY')) self.failUnlessEqual(-1, MayaCmds.getAttr('test.rotatePivotZ')) self.failUnlessEqual(1.4, MayaCmds.getAttr('test.scalePivotX')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.scalePivotY')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.scalePivotZ')) # frame 24 MayaCmds.currentTime(24, update=True); abcNodeName = MayaCmds.ls(exactType='AlembicNode') MayaCmds.dgeval(abcNodeName, verbose=True) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearXY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearYZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearXZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateX')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateX')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateZ')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleX')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleY')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleZ')) self.failUnlessEqual(0.5, MayaCmds.getAttr('test.rotatePivotX')) self.failUnlessEqual(-0.1, MayaCmds.getAttr('test.rotatePivotY')) self.failUnlessEqual(1, MayaCmds.getAttr('test.rotatePivotZ')) self.failUnlessEqual(1.2, MayaCmds.getAttr('test.scalePivotX')) self.failUnlessEqual(1.0, MayaCmds.getAttr('test.scalePivotY')) self.failUnlessEqual(1.2, MayaCmds.getAttr('test.scalePivotZ')) def testSampledConnectionDetectionRW(self): # connect to plugs at parent level and see if when loaded back # the sampled channels are recognized correctly driver = MayaCmds.createNode('transform', n='driverTrans') # shear MayaCmds.setKeyframe(driver, value=0, attribute='shearXY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='shearYZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='shearXZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.5, attribute='shearXY', t=12) MayaCmds.setKeyframe(driver, value=5, attribute='shearYZ', t=12) MayaCmds.setKeyframe(driver, value=2.5, attribute='shearXZ', t=12) # translate MayaCmds.setKeyframe(driver, value=0, attribute='translateX', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='translateY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='translateZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.5, attribute='translateX', t=12) MayaCmds.setKeyframe(driver, value=5, attribute='translateY', t=12) MayaCmds.setKeyframe(driver, value=2.5, attribute='translateZ', t=12) # rotate MayaCmds.setKeyframe(driver, value=0, attribute='rotateX', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='rotateY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='rotateZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=24, attribute='rotateX', t=12) MayaCmds.setKeyframe(driver, value=53, attribute='rotateY', t=12) MayaCmds.setKeyframe(driver, value=90, attribute='rotateZ', t=12) # scale MayaCmds.setKeyframe(driver, value=1, attribute='scaleX', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1, attribute='scaleY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1, attribute='scaleZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.2, attribute='scaleX', t=12) MayaCmds.setKeyframe(driver, value=1.5, attribute='scaleY', t=12) MayaCmds.setKeyframe(driver, value=1.5, attribute='scaleZ', t=12) # rotate pivot MayaCmds.setKeyframe(driver, value=0.5, attribute='rotatePivotX', t=[1, 24]) MayaCmds.setKeyframe(driver, value=-0.1, attribute='rotatePivotY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1, attribute='rotatePivotZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0.8, attribute='rotatePivotX', t=12) MayaCmds.setKeyframe(driver, value=1.5, attribute='rotatePivotY', t=12) MayaCmds.setKeyframe(driver, value=-1, attribute='rotatePivotZ', t=12) # scale pivot MayaCmds.setKeyframe(driver, value=1.2, attribute='scalePivotX', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.0, attribute='scalePivotY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.2, attribute='scalePivotZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.4, attribute='scalePivotX', t=12) MayaCmds.setKeyframe(driver, value=1.5, attribute='scalePivotY', t=12) MayaCmds.setKeyframe(driver, value=1.5, attribute='scalePivotZ', t=12) # create the transform node that's been driven by the connections driven = MayaCmds.createNode('transform', n = 'drivenTrans') MayaCmds.connectAttr(driver+'.translate', driven+'.translate') MayaCmds.connectAttr(driver+'.scale', driven+'.scale') MayaCmds.connectAttr(driver+'.rotate', driven+'.rotate') MayaCmds.connectAttr(driver+'.shear', driven+'.shear') MayaCmds.connectAttr(driver+'.rotatePivot', driven+'.rotatePivot') MayaCmds.connectAttr(driver+'.scalePivot', driven+'.scalePivot') self.__files.append(util.expandFileName('testSampledTransformDetection.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root drivenTrans -file ' + self.__files[-1]) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') # frame 1 MayaCmds.currentTime(1, update=True) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearXY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearYZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearXZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateX')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateX')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateZ')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleX')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleY')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleZ')) self.failUnlessEqual(0.5, MayaCmds.getAttr(driven+'.rotatePivotX')) self.failUnlessEqual(-0.1, MayaCmds.getAttr(driven+'.rotatePivotY')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.rotatePivotZ')) self.failUnlessEqual(1.2, MayaCmds.getAttr(driven+'.scalePivotX')) self.failUnlessEqual(1.0, MayaCmds.getAttr(driven+'.scalePivotY')) self.failUnlessEqual(1.2, MayaCmds.getAttr(driven+'.scalePivotZ')) # frame 12 MayaCmds.currentTime(12, update=True); abcNodeName = MayaCmds.ls(exactType='AlembicNode') MayaCmds.dgeval(abcNodeName, verbose=True) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.shearXY')) self.failUnlessEqual(5, MayaCmds.getAttr(driven+'.shearYZ')) self.failUnlessEqual(2.5, MayaCmds.getAttr(driven+'.shearXZ')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.translateX')) self.failUnlessEqual(5, MayaCmds.getAttr(driven+'.translateY')) self.failUnlessEqual(2.5, MayaCmds.getAttr(driven+'.translateZ')) self.failUnlessAlmostEqual(24.0, MayaCmds.getAttr(driven+'.rotateX'), 4) self.failUnlessAlmostEqual(53.0, MayaCmds.getAttr(driven+'.rotateY'), 4) self.failUnlessAlmostEqual(90.0, MayaCmds.getAttr(driven+'.rotateZ'), 4) self.failUnlessEqual(1.2, MayaCmds.getAttr(driven+'.scaleX')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.scaleY')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.scaleZ')) self.failUnlessEqual(0.8, MayaCmds.getAttr(driven+'.rotatePivotX')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.rotatePivotY')) self.failUnlessEqual(-1, MayaCmds.getAttr(driven+'.rotatePivotZ')) self.failUnlessEqual(1.4, MayaCmds.getAttr(driven+'.scalePivotX')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.scalePivotY')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.scalePivotZ')) # frame 24 MayaCmds.currentTime(24, update=True); abcNodeName = MayaCmds.ls(exactType='AlembicNode') MayaCmds.dgeval(abcNodeName, verbose=True) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearXY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearYZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearXZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateX')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateX')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateZ')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleX')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleY')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleZ')) self.failUnlessEqual(0.5, MayaCmds.getAttr(driven+'.rotatePivotX')) self.failUnlessEqual(-0.1, MayaCmds.getAttr(driven+'.rotatePivotY')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.rotatePivotZ')) self.failUnlessEqual(1.2, MayaCmds.getAttr(driven+'.scalePivotX')) self.failUnlessEqual(1.0, MayaCmds.getAttr(driven+'.scalePivotY')) self.failUnlessEqual(1.2, MayaCmds.getAttr(driven+'.scalePivotZ'))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic, nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** #!/usr/bin/env python sprops = \ """ IBoolProperty IUcharProperty ICharProperty IUInt16Property IInt16Property IUInt32Property IInt32Property IUInt64Property IInt64Property IHalfProperty IFloatProperty IDoubleProperty IStringProperty IWstringProperty IV2sProperty IV2iProperty IV2fProperty IV2dProperty IV3sProperty IV3iProperty IV3fProperty IV3dProperty IBox2sProperty IBox2iProperty IBox2fProperty IBox2dProperty IBox3sProperty IBox3iProperty IBox3fProperty IBox3dProperty IM33fProperty IM33dProperty IM44fProperty IM44dProperty IQuatfProperty IQuatdProperty IC3hProperty IC3fProperty IC3cProperty IC4hProperty IC4fProperty IC4cProperty IN3fProperty IN3dProperty """ def printdefs( p ): s = " //%s\n //\n" #s += 'bool\n( Abc::%s::*matchesMetaData )( const AbcA::MetaData&,\nAbc::SchemaInterpMatching ) = \\\n' #s += '&Abc::%s::matches;\n\n' #s += 'bool\n( Abc::%s::*matchesHeader )( const AbcA::PropertyHeader&,\nAbc::SchemaInterpMatching ) = \\\n' #s += '&Abc::%s::matches;\n\n' s += 'class_<Abc::%s>( "%s",\ninit<Abc::ICompoundProperty,\nconst std::string&>() )\n' s += '.def( init<>() )\n' s += '.def( "getName", &Abc::%s::getName,\nreturn_value_policy<copy_const_reference>() )\n' s += '.def( "getHeader", &Abc::%s::getHeader,\nreturn_internal_reference<1>() )\n' s += '.def( "isScalar", &Abc::%s::isScalar )\n' s += '.def( "isArray", &Abc::%s::isArray )\n' s += '.def( "isCompound", &Abc::%s::isCompound )\n' s += '.def( "isSimple", &Abc::%s::isSimple )\n' s += '.def( "getMetaData", &Abc::%s::getMetaData,\nreturn_internal_reference<1>() )\n' s += '.def( "getDataType", &Abc::%s::getDataType,\nreturn_internal_reference<1>() )\n' s += '.def( "getTimeSamplingType", &Abc::%s::getTimeSamplingType )\n' s += '.def( "getInterpretation", &Abc::%s::getInterpretation,\nreturn_value_policy<copy_const_reference>() )\n' #s += '.def( "matches", matchesMetaData )\n' #s += '.def( "matches", matchesHeader )\n' s += '.def( "getNumSamples", &Abc::%s::getNumSamples )\n' #s += '.def( "getValue", &Abc::%s::getValue, %s_overloads() )\n' s += '.def( "getObject", &Abc::%s::getObject,\nwith_custodian_and_ward_postcall<0,1>() )\n' s += '.def( "reset", &Abc::%s::reset )\n' s += '.def( "valid", &Abc::%s::valid )\n' s += '.def( "__str__", &Abc::%s::getName,\nreturn_value_policy<copy_const_reference>() )\n' s += '.def( "__nonzero__", &Abc::%s::valid )\n' s += ';' print s % eval( "%s" % ( 'p,' * s.count( r'%s' ) ) ) print return for i in sprops.split(): if i == "": pass else: printdefs( i )
Python
#!/usr/bin/env python2.5 #-*- mode: python -*- ##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Industrial Light & Magic nor the names of ## its contributors may be used to endorse or promote products derived ## from this software without specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** import os, sys class Path( object ): """The Path class simplifies filesystem path manipulation. If you wish to use a Path object as an argument to standard Python path functions such as os.path.*, open(), etc., you must first cast it to a string like "str( myPathObject )".""" def __init__( self, path=None ): if path != None: path = str( path ) self._isabs = os.path.isabs( path ) self._orig = path self._path = os.path.normpath( os.path.expanduser( path ) ) else: self._isabs = False self._path = '' self._orig = '' if self._isabs: self._root = os.sep else: if self._orig == '': self._root = None else: self._root = os.curdir self._plist = filter( lambda x: x and x != os.curdir, self._path.split( os.sep )) self._len = len( self._plist ) self._isempty = self._root == None and self._len == 0 self._maxindex = self._len - 1 self._maxsliceindex = self._len def __reinit__( self, new ): self._len = len( new._plist ) self._plist = new._plist[:] self._isempty = 0 == new._len self._maxindex = new._len - 1 self._maxsliceindex = new._len self._path = new._path self._orig = new._orig self._isabs = new._isabs self._root = new._root def __repr__( self ): return self._path def __str__( self ): return self.__repr__() def __contains__( self, other ): return other in self._plist def __len__( self ): return self._len def __add__( self, other ): return Path( os.path.join( str( self ), str( other ) ) ) def __radd__( self, other ): return Path( other ) + self def __iter__( self ): self._iterindex = 0 return self def __eq__( self, other ): return str( self ) == str( other ) def __ne__( self, other ): return str( self ) != str( other ) def __cmp__( self, other ): _, p1, p2 = self.common( other ) return len( p1 ) - len( p2 ) def __nonzero__( self ): if not self.isabs() and len( self ) == 0: return False else: return True def __hash__( self ): return hash( str( self )) def __getitem__( self, n ): if isinstance( n, slice ): path = None plist = self._plist[n.start:n.stop:n.step] returnabs = self._isabs and n.start < 1 if len( plist ) > 0: path = os.sep.join( plist ) else: path = os.curdir path = Path( path ) if returnabs: path = self.root() + path else: pass return path else: return self._plist[n] def __setitem__( self, key, value ): try: key = int( key ) except ValueError: raise ValueError, "You must use an integer to refer to a path element." if key > abs( self._maxindex ): raise IndexError, "Maximum index is +/- %s." % self._maxindex self._plist[key] = value self._path = str( self[:] ) def __delitem__( self, n ): try: n = int( n ) except ValueError: raise ValueError, "You must use an integer to refer to a path element." try: del( self._plist[n] ) t = Path( self[:] ) self.__reinit__( t ) except IndexError: raise IndexError, "Maximum index is +/- %s" & self._maxindex def rindex( self, val ): if val in self: return len( self._plist ) - \ list( reversed( self._plist ) ).index( val ) - 1 else: raise ValueError, "%s is not in path." % val def index( self, val ): if val in self: return self._plist.index( val ) else: raise ValueError, "%s is not in path." % val def common( self, other, cmn=None ): cmn = Path( cmn ) other = Path( str( other ) ) if self.isempty() or other.isempty(): return cmn, self, other elif (self[0] != other[0]) or (self.root() != other.root()): return cmn, self, other else: return self[1:].common( other[1:], self.root() + cmn + self[0] ) def relative( self, other ): cmn, p1, p2 = self.common( other ) relhead = Path() if len( p1 ) > 0: relhead = Path( (os.pardir + os.sep) * len( p1 )) return relhead + p2 def join( self, *others ): t = self[:] for o in others: t = t + o return t def split( self ): head = self[:-1] tail = None if not head.isempty(): tail = Path( self[-1] ) else: tail = self if not head.isabs() and head.isempty(): head = Path( None ) if head.isabs() and len( tail ) == 1: tail = tail[-1] return ( head, tail ) def splitext( self ): head, tail = os.path.splitext( self._path ) return Path( head ), tail def next( self ): if self._iterindex > self._maxindex: raise StopIteration else: i = self._iterindex self._iterindex += 1 return self[i] def subpaths( self ): sliceind = 0 while sliceind < self._maxsliceindex: sliceind += 1 yield self[:sliceind] def append( self, *others ): t = self[:] for o in others: t = t + o self.__reinit__( t ) def root( self ): return Path( self._root ) def elems( self ): return self._plist def path( self ): return self._path def exists( self ): return os.path.exists( self._path ) def isempty( self ): return self._isempty def isabs( self ): return self._isabs def islink( self ): return os.path.islink( self._path ) def isdir( self ): return os.path.isdir( self._path ) def isfile( self ): return os.path.isfile( self._path ) def readlink( self ): if self.islink(): return Path( os.readlink( self._orig ) ) else: return self def dirname( self ): return self[:-1] def basename( self ): return self.dirname() def startswith( self, other ): return self._path.startswith( other ) def makeabs( self ): t = self[:] t._root = os.sep t._isabs = True t._path = os.path.join( os.sep, self._path ) self.__reinit__( t ) def makerel( self ): t = self[:] t._root = os.curdir t._isabs = False t._path = os.sep.join( t._plist ) self.__reinit__( t ) def toabs( self ): return Path( os.path.abspath( self._path ) ) def torel( self ): t = self[:] t.makerel() return t ##-***************************************************************************** def mapFSTree( root, path, dirs=set(), links={} ): """Create a sparse map of the filesystem graph from the root node to the path node.""" root = Path( root ) path = Path( path ) for sp in path.subpaths(): if sp.isabs(): full = sp else: full = sp.toabs() head = full.dirname() if full.islink(): target = full.readlink() if target.isabs(): newpath = target else: newpath = head + target # make sure there are no cycles if full in links: continue links[full] = newpath _dirs, _links = mapFSTree( full, newpath, dirs, links ) dirs.update( _dirs ) links.update( _links ) elif full.isdir(): if full in dirs: continue else: dirs.add( full ) elif full.isfile(): break #pass else: print "QOI??? %s" % full return dirs, links ##-***************************************************************************** def main(): try: arg = Path( sys.argv[1] ) except IndexError: print "Please supply a directory to analyze." return 1 dirs, links = mapFSTree( Path( os.getcwd() ), arg ) print print "Directories traversed to get to %s\n" % arg for d in sorted( list( dirs ) ): print d print print "Symlinks in traversed directories for %s\n" % arg for k in links: print "%s: %s" % ( k, links[k] ) print return 0 ##-***************************************************************************** if __name__ == "__main__": sys.exit( main() )
Python
#!/usr/bin/env python2.6 #-*- mode: python -*- ##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Industrial Light & Magic nor the names of ## its contributors may be used to endorse or promote products derived ## from this software without specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from __future__ import with_statement import os, sys, re from Path import Path ##-***************************************************************************** COMMENT = re.compile( r"//|#" ) WS = re.compile( r"\s" ) ##-***************************************************************************** class CacheEntry( object ): def __init__( self, _line ): line = WS.sub( "", str( _line ) ) if not line: return None elif COMMENT.match( line ): return None else: # get rid of comments at the end of the line line = COMMENT.split( line, 1 )[0].strip() try: name_type, value = line.split( '=' ) self._value = value.strip() if self._value == '': self._value = None name, typ = name_type.split( ':' ) self._name = name.strip() self._type = typ.strip() except ValueError: sys.stderr.write( "Could not parse line '%s'\n" % _line ) self._value = None self._name = None self._type = None def __str__( self ): val = "" typ = "" if self._value != None: val = self._value if self._type != None: typ = self._type if self._name == None: return "" else: s = "%s:%s=%s" % ( self._name, typ, val ) return s.strip() def __eq__( self, other ): return str( self ) == str( other ) def __nonzero__( self ): try: return self._name != None and self._value != None except AttributeError: return False def name( self ): return self._name def value( self, newval = None ): if newval != None: self._value = newval else: return self._value def hint( self ): """Return the CMakeCache TYPE of the entry; used as a hint to CMake GUIs.""" return self._type ##-***************************************************************************** class CMakeCache( object ): """This class is used to read in and get programmatic access to the variables in a CMakeCache.txt file, manipulate them, and then write the cache back out.""" def __init__( self, path=None ): self._cachefile = Path( path ) _cachefile = str( self._cachefile ) self._entries = {} if self._cachefile.exists(): with open( _cachefile ) as c: entries = filter( None, map( lambda x: CacheEntry( x ), c.readlines() ) ) entries = filter( lambda x: x.value() != None, entries ) for i in entries: self._entries[i.name()] = i def __contains__( self, thingy ): try: return thingy in self.names() except TypeError: return thingy in self._entries.values() def __iter__( self ): return self._entries def __nonzero__( self ): return len( self._entries ) > 0 def __str__( self ): return os.linesep.join( map( lambda x: str( x ), self.entries() ) ) def add( self, entry ): e = CacheEntry( entry ) if e: if not e in self: self._entries[e.name()] = e else: sys.stderr.write( "Entry for '%s' is already in the cache.\n" % \ e.name() ) else: sys.stderr.write( "Could not create cache entry for '%s'\n" % e ) def update( self, entry ): e = CacheEntry( entry ) if e: self._entries[e.name()] = e else: sys.stderr.write( "Could not create cache entry for '%s'\n" % e ) def names( self ): return self._entries.keys() def entries( self ): return self._entries.values() def get( self, name ): return self._entries[name] def cachefile( self ): return self._cachefile def refresh( self ): self.__init__( self._cachefile ) def write( self, newfile = None ): if newfile == None: newfile = self._cachefile with open( newfile, 'w' ) as f: for e in self.entries(): f.write( str( e ) + os.linesep )
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic, nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from Path import Path from CMakeCache import CMakeCache, CacheEntry
Python
#! /usr/bin/env python # Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # This code is courtesy of Thomas Heller, who # has kindly donated it to this project. RT_ICON = 3 RT_GROUP_ICON = 14 LOAD_LIBRARY_AS_DATAFILE = 2 import struct import types try: StringTypes = types.StringTypes except AttributeError: StringTypes = [ type("") ] class Structure: def __init__ (self): size = self._sizeInBytes = struct.calcsize (self._format_) self._fields_ = list (struct.unpack (self._format_, '\000' * size)) indexes = self._indexes_ = {} for i in range (len (self._names_)): indexes[self._names_[i]] = i def dump (self): print "I: DUMP of", self for name in self._names_: if name[0] != '_': print "I: %20s = %s" % (name, getattr (self, name)) print def __getattr__ (self, name): if name in self._names_: index = self._indexes_[name] return self._fields_[index] try: return self.__dict__[name] except KeyError: raise AttributeError, name def __setattr__ (self, name, value): if name in self._names_: index = self._indexes_[name] self._fields_[index] = value else: self.__dict__[name] = value def tostring (self): return apply (struct.pack, [self._format_,] + self._fields_) def fromfile (self, file): data = file.read (self._sizeInBytes) self._fields_ = list (struct.unpack (self._format_, data)) class ICONDIRHEADER (Structure): _names_ = "idReserved", "idType", "idCount" _format_ = "hhh" class ICONDIRENTRY (Structure): _names_ = "bWidth", "bHeight", "bColorCount", "bReserved", "wPlanes", "wBitCount", "dwBytesInRes", "dwImageOffset" _format_ = "bbbbhhii" class GRPICONDIR (Structure): _names_ = "idReserved", "idType", "idCount" _format_ = "hhh" class GRPICONDIRENTRY (Structure): _names_ = "bWidth", "bHeight", "bColorCount", "bReserved", "wPlanes", "wBitCount", "dwBytesInRes", "nID" _format_ = "bbbbhhih" class IconFile: def __init__ (self, path): self.path = path file = open (path, "rb") self.entries = [] self.images = [] header = self.header = ICONDIRHEADER() header.fromfile (file) for i in range (header.idCount): entry = ICONDIRENTRY() entry.fromfile (file) self.entries.append (entry) for e in self.entries: file.seek (e.dwImageOffset, 0) self.images.append (file.read (e.dwBytesInRes)) def grp_icon_dir (self): return self.header.tostring() def grp_icondir_entries (self, id=1): data = "" for entry in self.entries: e = GRPICONDIRENTRY() for n in e._names_[:-1]: setattr(e, n, getattr (entry, n)) e.nID = id id = id + 1 data = data + e.tostring() return data def CopyIcons_FromIco (dstpath, srcpath, id=1): import win32api #, win32con icons = map(IconFile, srcpath) print "I: Updating icons from", srcpath, "to", dstpath hdst = win32api.BeginUpdateResource (dstpath, 0) iconid = 1 for i in range(len(icons)): f = icons[i] data = f.grp_icon_dir() data = data + f.grp_icondir_entries(iconid) win32api.UpdateResource (hdst, RT_GROUP_ICON, i, data) print "I: Writing RT_GROUP_ICON %d resource with %d bytes" % (i, len(data)) for data in f.images: win32api.UpdateResource (hdst, RT_ICON, iconid, data) print "I: Writing RT_ICON %d resource with %d bytes" % (iconid, len (data)) iconid = iconid + 1 win32api.EndUpdateResource (hdst, 0) def CopyIcons (dstpath, srcpath): import os.path, string if type(srcpath) in StringTypes: srcpath = [ srcpath ] def splitter(s): try: srcpath, index = map(string.strip, string.split(s, ',')) return srcpath, int(index) except ValueError: return s, None srcpath = map(splitter, srcpath) print "I: SRCPATH", srcpath if len(srcpath) > 1: # At the moment, we support multiple icons only from .ico files srcs = [] for s in srcpath: e = os.path.splitext(s[0])[1] if string.lower(e) != '.ico': raise ValueError, "multiple icons supported only from .ico files" if s[1] is not None: raise ValueError, "index not allowed for .ico files" srcs.append(s[0]) return CopyIcons_FromIco(dstpath, srcs) srcpath,index = srcpath[0] srcext = os.path.splitext(srcpath)[1] if string.lower (srcext) == '.ico': return CopyIcons_FromIco (dstpath, [srcpath]) if index is not None: print "I: Updating icons from", srcpath, ", %d to" % index, dstpath else: print "I: Updating icons from", srcpath, "to", dstpath import win32api #, win32con hdst = win32api.BeginUpdateResource (dstpath, 0) hsrc = win32api.LoadLibraryEx (srcpath, 0, LOAD_LIBRARY_AS_DATAFILE) if index is None: grpname = win32api.EnumResourceNames (hsrc, RT_GROUP_ICON)[0] elif index >= 0: grpname = win32api.EnumResourceNames (hsrc, RT_GROUP_ICON)[index] else: grpname = -index data = win32api.LoadResource (hsrc, RT_GROUP_ICON, grpname) win32api.UpdateResource (hdst, RT_GROUP_ICON, grpname, data) for iconname in win32api.EnumResourceNames (hsrc, RT_ICON): data = win32api.LoadResource (hsrc, RT_ICON, iconname) win32api.UpdateResource (hdst, RT_ICON, iconname, data) win32api.FreeLibrary (hsrc) win32api.EndUpdateResource (hdst, 0) if __name__ == "__main__": import sys dstpath = sys.argv[1] srcpath = sys.argv[2:] CopyIcons(dstpath, srcpath)
Python
#! /usr/bin/env python # encoding: utf-8 import platform import Utils import Options # the following two variables are used by the target "waf dist" VERSION='' APPNAME='' # these variables are mandatory ('/' are converted automatically) top = '.' out = 'build' # TODO extensive testing with different configuration (should work with Python >= 2.3) def set_options(opt): myplatform = Utils.detect_platform() if myplatform.startswith('linux'): opt.add_option('--no-lsb', action = 'store_true', help = 'Prevent building LSB (Linux Standard Base) bootloader.', default = False, dest = 'nolsb') opt.add_option('--lsbcc-path', action = 'store', help = 'Path to lsbcc. By default PATH is searched for lsbcc otherwise is tried file /opt/lsb/bin/lsbcc. [Default: lsbcc]', default = 'lsbcc', dest = 'lsbcc_path') opt.add_option('--lsb-target-version', action = 'store', help = 'Specify LSB target version [Default: 4.0]', default = '4.0', dest = 'lsb_version') opt.tool_options('compiler_cc') opt.tool_options('python') def configure(conf): conf.env.NAME = 'default' opt = Options.options myplatform = Utils.detect_platform() architecture = platform.architecture()[0] # 32bit or 64bit Utils.pprint('CYAN', '%s-%s detected' % (platform.system(), architecture)) if myplatform.startswith('linux') and not opt.nolsb: Utils.pprint('CYAN', 'Building LSB bootloader.') if myplatform.startswith('darwin'): conf.env.MACOSX_DEPLOYMENT_TARGET = '10.4' ### C compiler if myplatform.startswith('win'): try: # mingw (gcc for Windows) conf.check_tool('gcc') except: try: # Newest detected MSVC version is used by default. # msvc 7.1 (Visual Studio 2003) # msvc 8.0 (Visual Studio 2005) # msvc 9.0 (Visual Studio 2008) #conf.env['MSVC_VERSIONS'] = ['msvc 7.1', 'msvc 8.0', 'msvc 9.0'] if architecture == '32bit': conf.env['MSVC_TARGETS'] = ['x86', 'ia32'] elif architecture == '64bit': conf.env['MSVC_TARGETS'] = ['x64', 'x86_amd64', 'intel64', 'em64t'] conf.check_tool('msvc') conf.print_all_msvc_detected() except: Utils.pprint('RED', 'GCC (MinGW) or MSVC compiler not found.') exit(1) else: # When using GCC, deactivate declarations after statements # (not supported by Visual Studio) conf.env.append_value('CCFLAGS', '-Wdeclaration-after-statement') conf.env.append_value('CCFLAGS', '-Werror') else: conf.check_tool('compiler_cc') conf.check_tool('python') conf.check_python_headers() # Do not link with libpython and libpthread. for lib in conf.env.LIB_PYEMBED: if lib.startswith('python') or lib.startswith('pthread'): conf.env.LIB_PYEMBED.remove(lib) ### build LSB (Linux Standard Base) boot loader if myplatform.startswith('linux') and not opt.nolsb: try: # custom lsbcc path if opt.lsbcc_path != 'lsbcc': conf.env.LSBCC = conf.find_program(opt.lsbcc_path, mandatory=True) # default values else: conf.env.LSBCC = conf.find_program(opt.lsbcc_path) if not conf.env.LSBCC: conf.env.LSBCC = conf.find_program('/opt/lsb/bin/lsbcc', mandatory=True) except: Utils.pprint('RED', 'LSB (Linux Standard Base) tools >= 4.0 are required.') Utils.pprint('RED', 'Try --no-lsb option if not interested in building LSB binary.') exit(2) # lsbcc as CC compiler conf.env.append_value('CCFLAGS', '--lsb-cc=%s' % conf.env.CC[0]) conf.env.append_value('LINKFLAGS', '--lsb-cc=%s' % conf.env.CC[0]) conf.env.CC = conf.env.LSBCC conf.env.LINK_CC = conf.env.LSBCC ## check LSBCC flags # --lsb-besteffort - binary will work on platforms without LSB stuff # --lsb-besteffort - available in LSB build tools >= 4.0 conf.check_cc(ccflags='--lsb-besteffort', msg='Checking for LSB build tools >= 4.0', errmsg='LSB >= 4.0 is required', mandatory=True) conf.env.append_value('CCFLAGS', '--lsb-besteffort') conf.env.append_value('LINKFLAGS', '--lsb-besteffort') # binary compatibility with a specific LSB version # LSB 4.0 can generate binaries compatible with 3.0, 3.1, 3.2, 4.0 # however because of using function 'mkdtemp', loader requires # using target version 4.0 lsb_target_flag = '--lsb-target-version=%s' % opt.lsb_version conf.env.append_value('CCFLAGS', lsb_target_flag) conf.env.append_value('LINKFLAGS', lsb_target_flag) ### Defines, Includes if myplatform.startswith('lin'): # make sure we don't use declarations after statement (break Visual Studio) conf.env.append_value('CCFLAGS', '-Wdeclaration-after-statement') conf.env.append_value('CCFLAGS', '-Werror') if myplatform.startswith('win'): conf.env.append_value('CCDEFINES', 'WIN32') conf.env.append_value('CPPPATH', '../zlib') conf.env.append_value('CPPPATH', '../common') ### Libraries if myplatform.startswith('win'): conf.check_cc(lib='user32', mandatory=True) conf.check_cc(lib='comctl32', mandatory=True) conf.check_cc(lib='kernel32', mandatory=True) conf.check_cc(lib='ws2_32', mandatory=True) else: conf.check_cc(lib='z', mandatory=True) if conf.check_cc(function_name='readlink', header_name='unistd.h'): conf.env.append_value('CCFLAGS', '-DHAVE_READLINK') ### ccflags if myplatform.startswith('win') and conf.env.CC_NAME == 'gcc': # Disables console - MinGW option conf.check_cc(ccflags='-mwindows', mandatory=True, msg='Checking for flags -mwindows') # Use Visual C++ compatible alignment conf.check_cc(ccflags='-mms-bitfields', mandatory=True, msg='Checking for flags -mms-bitfields') conf.env.append_value('CCFLAGS', '-mms-bitfields') elif myplatform.startswith('win') and conf.env.CC_NAME == 'msvc': if architecture == '32bit': conf.env.append_value('LINKFLAGS', '/MACHINE:X86') elif architecture == '64bit': conf.env.append_value('LINKFLAGS', '/MACHINE:X64') # enable 64bit porting warnings conf.env.append_value('CCFLAGS', '/Wp64') # We use SEH exceptions in winmain.c; make sure they are activated. conf.env.append_value('CCFLAGS', '/EHa') # link only with needed libraries # XXX: -Wl,--as-needed detected during configure but fails during mac build if conf.check_cc(ccflags='-Wl,--as-needed', msg='Checking for flags -Wl,--as-needed') \ and not myplatform.startswith('darwin'): conf.env.append_value('LINKFLAGS', '-Wl,--as-needed') ### Other stuff if myplatform.startswith('win'): # RC file - icon conf.check_tool('winres') ### DEBUG and RELEASE environments rel = conf.env.copy() dbg = conf.env.copy() rel.set_variant('release') # separate subfolder for building dbg.set_variant('debug') # separate subfolder for building rel.detach() # detach environment from default dbg.detach() ## setup DEBUG environment dbg.set_variant('debug') # separate subfolder for building conf.set_env_name('debug', dbg) conf.setenv('debug') conf.env.append_value('CCDEFINES', '_DEBUG LAUNCH_DEBUG'.split()) conf.env.append_value('CCFLAGS', conf.env.CCFLAGS_DEBUG) dbgw = conf.env.copy() # WINDOWED DEBUG environment dbgw.set_variant('debugw') # separate subfolder for building dbgw.detach() ## setup windowed DEBUG environment conf.set_env_name('debugw', dbgw) conf.setenv('debugw') if myplatform.startswith('darwin') or myplatform.startswith('win'): conf.env.append_value('CCDEFINES', 'WINDOWED') # disables console - mingw option if myplatform.startswith('win') and conf.env.CC_NAME == 'gcc': conf.env.append_value('LINKFLAGS', '-mwindows') elif myplatform.startswith('darwin'): conf.env.append_value('CCFLAGS', '-I/Developer/Headers/FlatCarbon') conf.env.append_value('LINKFLAGS', '-framework') conf.env.append_value('LINKFLAGS', 'Carbon') ## setup RELEASE environment conf.set_env_name('release', rel) conf.setenv('release') conf.env.append_value('CCDEFINES', 'NDEBUG') conf.env.append_value('CCFLAGS', conf.env.CCFLAGS_RELEASE) relw = conf.env.copy() # WINDOWED RELEASE environment relw.set_variant('releasew') # separate subfolder for building relw.detach() ## setup windowed RELEASE environment conf.set_env_name('releasew', relw) conf.setenv('releasew') if myplatform.startswith('darwin') or myplatform.startswith('win'): conf.env.append_value('CCDEFINES', 'WINDOWED') # disables console if myplatform.startswith('win') and conf.env.CC_NAME == 'gcc': conf.env.append_value('LINKFLAGS', '-mwindows') elif myplatform.startswith('darwin'): conf.env.append_value('CCFLAGS', '-I/Developer/Headers/FlatCarbon') conf.env.append_value('LINKFLAGS', '-framework') conf.env.append_value('LINKFLAGS', 'Carbon') def build(bld): # Force to run with 1 job (no parallel building). # There are reported build failures on multicore CPUs # with some msvc versions. Options.options.jobs = 1 myplatform = Utils.detect_platform() install_path = '../../support/loader/' + platform.system() + "-" + platform.architecture()[0] targets = dict(release='run', debug='run_d', releasew='runw', debugw='runw_d') if myplatform.startswith('win'): # static lib zlib for key in targets.keys(): bld( features = 'cc cstaticlib', source = bld.path.ant_glob('zlib/*.c'), target = 'staticlib_zlib', env = bld.env_of_name(key), ) # console for key in ('release', 'debug'): bld( features = 'cc cprogram pyembed', source = bld.path.ant_glob('windows/winmain.c windows/run.rc common/*.c'), target = targets[key], install_path = install_path, uselib_local = 'staticlib_zlib', uselib = 'USER32 COMCTL32 KERNEL32 WS2_32', env = bld.env_of_name(key).copy(), ) # windowed for key in ('releasew', 'debugw'): bld( features = 'cc cprogram pyembed', source = bld.path.ant_glob('windows/winmain.c windows/runw.rc common/*.c'), # uses different RC file (icon) target = targets[key], install_path = install_path, uselib_local = 'staticlib_zlib', uselib = 'USER32 COMCTL32 KERNEL32 WS2_32', env = bld.env_of_name(key).copy(), ) ## inprocsrvr console if bld.env.CC_NAME == 'msvc': linkflags_c = bld.env.CPPFLAGS_CONSOLE linkflags_w = bld.env.CPPFLAGS_WINDOWS else: linkflags_c = '' linkflags_w = '' for key, value in dict(release='inprocsrvr', debug='inprocsrvr_d').items(): bld( features = 'cc cshlib', source = bld.path.ant_glob('common/launch.c windows/dllmain.c'), target = value, install_path = install_path, uselib_local = 'staticlib_zlib', uselib = 'USER32 COMCTL32 KERNEL32 WS2_32', env = bld.env_of_name(key).copy(), linkflags = linkflags_c ) ## inprocsrvr windowed for key, value in dict(releasew='inprocsrvrw', debugw='inprocsrvrw_d').items(): bld( features = 'cc cshlib', source = bld.path.ant_glob('common/launch.c windows/dllmain.c'), target = value, install_path = install_path, uselib_local = 'staticlib_zlib', uselib = 'USER32 COMCTL32 KERNEL32 WS2_32', env = bld.env_of_name(key).copy(), linkflags = linkflags_w ) else: # linux, darwin (MacOSX) for key, value in targets.items(): bld( features = 'cc cprogram pyembed', source = bld.path.ant_glob('linux/*.c common/*.c'), target = value, install_path = install_path, uselib = 'Z', # zlib env = bld.env_of_name(key).copy(), )
Python
#!/usr/bin/env python from distutils.core import setup from distutils.extension import Extension setup( name = 'AES', ext_modules=[ Extension("AES", ["AES.c"]), ], )
Python
#! /usr/bin/env python # Viewer for archives packaged by archive.py # Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import archive import carchive import sys, string, tempfile, os try: import zlib except ImportError: zlib = archive.DummyZlib() import pprint stack = [] cleanup = [] def main(): global stack name = sys.argv[1] arch = getArchive(name) stack.append((name, arch)) show(name, arch) while 1: try: toks = string.split(raw_input('? '), None, 1) except EOFError: # Ctrl-D print # clear line break if not toks: usage() continue if len(toks) == 1: cmd = toks[0] arg = '' else: cmd, arg = toks cmd = string.upper(cmd) if cmd == 'U': if len(stack) > 1: arch = stack[-1][1] arch.lib.close() del stack[-1] nm, arch = stack[-1] show(nm, arch) elif cmd == 'O': if not arg: arg = raw_input('open name? ') arg = string.strip(arg) arch = getArchive(arg) if arch is None: print arg, "not found" continue stack.append((arg, arch)) show(arg, arch) elif cmd == 'X': if not arg: arg = raw_input('extract name? ') arg = string.strip(arg) data = getData(arg, arch) if data is None: print "Not found" continue fnm = raw_input('to filename? ') if not fnm: print `data` else: open(fnm, 'wb').write(data) elif cmd == 'Q': break else: usage() for (nm, arch) in stack: arch.lib.close() stack = [] for fnm in cleanup: try: os.remove(fnm) except Exception, e: print "couldn't delete", fnm, e.args def usage(): print "U: go Up one level" print "O <nm>: open embedded archive nm" print "X <nm>: extract nm" print "Q: quit" def getArchive(nm): if not stack: if string.lower(nm[-4:]) == '.pyz': return ZlibArchive(nm) return carchive.CArchive(nm) parent = stack[-1][1] try: return parent.openEmbedded(nm) except KeyError, e: return None except (ValueError, RuntimeError): ndx = parent.toc.find(nm) dpos, dlen, ulen, flag, typcd, nm = parent.toc[ndx] x, data = parent.extract(ndx) tfnm = tempfile.mktemp() cleanup.append(tfnm) open(tfnm, 'wb').write(data) if typcd == 'z': return ZlibArchive(tfnm) else: return carchive.CArchive(tfnm) def getData(nm, arch): if type(arch.toc) is type({}): (ispkg, pos, lngth) = arch.toc.get(nm, (0, None, 0)) if pos is None: return None arch.lib.seek(arch.start + pos) return zlib.decompress(arch.lib.read(lngth)) ndx = arch.toc.find(nm) dpos, dlen, ulen, flag, typcd, nm = arch.toc[ndx] x, data = arch.extract(ndx) return data def show(nm, arch): if type(arch.toc) == type({}): print " Name: (ispkg, pos, len)" toc = arch.toc else: print " pos, length, uncompressed, iscompressed, type, name" toc = arch.toc.data pprint.pprint(toc) class ZlibArchive(archive.ZlibArchive): def checkmagic(self): """ Overridable. Check to see if the file object self.lib actually has a file we understand. """ self.lib.seek(self.start) #default - magic is at start of file if self.lib.read(len(self.MAGIC)) != self.MAGIC: raise RuntimeError, "%s is not a valid %s archive file" \ % (self.path, self.__class__.__name__) if self.lib.read(len(self.pymagic)) != self.pymagic: print "Warning: pyz is from a different Python version" self.lib.read(4) if __name__ == '__main__': main()
Python
import sys,os targetdir = os.environ.get("_MEIPASS2", os.path.abspath(os.path.dirname(sys.argv[0]))) os.environ["MATPLOTLIBDATA"] = os.path.join(targetdir, "mpl-data")
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # In addition to the permissions in the GNU General Public License, the # authors give you unlimited permission to link or embed the compiled # version of this file into combinations with other programs, and to # distribute those combinations without any restriction coming from the # use of this file. (The General Public License restrictions do apply in # other respects; for example, they cover modification of the file, and # distribution when not linked into a combine executable.) # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import os, sys, iu, imp class Win32ImportDirector(iu.ImportDirector): def __init__(self): self.path = sys.path[0] # since I run as a hook, sys.path probably hasn't been mucked with if hasattr(sys, 'version_info'): self.suffix = '%d%d'%(sys.version_info[0],sys.version_info[1]) else: self.suffix = '%s%s' % (sys.version[0], sys.version[2]) def getmod(self, nm): fnm = os.path.join(self.path, nm+self.suffix+'.dll') try: fp = open(fnm, 'rb') except: return None else: mod = imp.load_module(nm, fp, fnm, ('.dll', 'rb', imp.C_EXTENSION)) mod.__file__ = fnm return mod sys.importManager.metapath.insert(1, Win32ImportDirector())
Python
# Copyright (C) 2009, Lorenzo Berni # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import os import sys if "_MEIPASS2" in os.environ: d = os.environ["_MEIPASS2"] else: d = os.path.dirname(sys.argv[0]) import django.core.management import django.utils.autoreload def _setup_environ(settings_mod, original_settings_path=None): project_name = settings_mod.__name__.split(".")[0] settings_name = "settings" if original_settings_path: os.environ['DJANGO_SETTINGS_MODULE'] = original_settings_path else: os.environ['DJANGO_SETTINGS_MODULE'] = '%s.%s' % (project_name, settings_name) project_module = __import__(project_name, {}, {}, ['']) return d def _find_commands(_): return """cleanup compilemessages createcachetable dbshell shell runfcgi runserver startproject""".split() old_restart_with_reloader = django.utils.autoreload.restart_with_reloader def _restart_with_reloader(*args): import sys a0 = sys.argv.pop(0) try: return old_restart_with_reloader(*args) finally: sys.argv.insert(0, a0) django.core.management.setup_environ = _setup_environ django.core.management.find_commands = _find_commands django.utils.autoreload.restart_with_reloader = _restart_with_reloader
Python
# Copyright (C) 2005, Giovanni Bajo # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # In addition to the permissions in the GNU General Public License, the # authors give you unlimited permission to link or embed the compiled # version of this file into combinations with other programs, and to # distribute those combinations without any restriction coming from the # use of this file. (The General Public License restrictions do apply in # other respects; for example, they cover modification of the file, and # distribution when not linked into a combine executable.) # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # PyOpenGL (specifically, OpenGL.__init__) reads a "version" text file # containing the version number to export it as OpenGL.__version__. When # packaging with PyInstaller, the 'version' file does not exist, and importing # PyOpenGL results in an IOError. # The (convoluted) solution is to override Python's builtin "open" with our # own function which detects when "version" is opened and returns some fake # content stream (through cStringIO). __realopen__ = open def myopen(fn, *args): if isinstance(fn, basestring): if fn.endswith("version") and ".pyz" in fn: # Restore original open, since we're almost done __builtins__.__dict__["open"] = __realopen__ # Report a fake revision number. Anything would do since it's not # used by the library, but it needs to be made of four numbers # separated by dots. import cStringIO return cStringIO.StringIO("0.0.0.0") return __realopen__(fn, *args) __builtins__.__dict__["open"] = myopen
Python
# Qt4 plugins are bundled as data files (see hooks/hook-PyQt4*), # within a "qt4_plugins" directory. # We add a runtime hook to tell Qt4 where to find them. import os d = "qt4_plugins" if "_MEIPASS2" in os.environ: d = os.path.join(os.environ["_MEIPASS2"], d) else: d = os.path.join(os.path.dirname(sys.argv[0]), d) # We cannot use QT_PLUGIN_PATH here, because it would not work when # PyQt4 is compiled with a different CRT from Python (eg: it happens # with Riverbank's GPL package). from PyQt4.QtCore import QCoreApplication QCoreApplication.addLibraryPath(os.path.abspath(d))
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # In addition to the permissions in the GNU General Public License, the # authors give you unlimited permission to link or embed the compiled # version of this file into combinations with other programs, and to # distribute those combinations without any restriction coming from the # use of this file. (The General Public License restrictions do apply in # other respects; for example, they cover modification of the file, and # distribution when not linked into a combine executable.) # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import os, sys supportdir = os.path.join(sys.path[0], 'support') genpydir = os.path.join(supportdir, 'gen_py') initmod = os.path.join(genpydir, '__init__.py') if not os.path.exists(genpydir): os.makedirs(genpydir) if not os.path.exists(initmod): open(initmod, 'w') import win32com win32com.__gen_path__ = genpydir win32com.__path__.insert(0, supportdir) # for older Pythons import copy_reg
Python
import sys,os d = "localedata" if "_MEIPASS2" in os.environ: d = os.path.join(os.environ["_MEIPASS2"], d) else: d = os.path.join(os.path.dirname(sys.argv[0]), d) import babel.localedata babel.localedata._dirname = os.path.abspath(d)
Python
#!/usr/bin/env python # # Make .eggs and zipfiles available at runtime # # Copyright (C) 2010 Giovanni Bajo <rasky@develer.com> # # This file is part of PyInstaller <http://www.pyinstaller.org> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # In addition to the permissions in the GNU General Public License, the # authors give you unlimited permission to link or embed the compiled # version of this file into combinations with other programs, and to # distribute those combinations without any restriction coming from the # use of this file. (The General Public License restrictions do apply in # other respects; for example, they cover modification of the file, and # distribution when not linked into a combine executable.) # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import os d = "eggs" if "_MEIPASS2" in os.environ: d = os.path.join(os.environ["_MEIPASS2"], d) else: d = os.path.join(os.path.dirname(sys.argv[0]), d) for fn in os.listdir(d): sys.path.append(os.path.join(d, fn))
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # In addition to the permissions in the GNU General Public License, the # authors give you unlimited permission to link or embed the compiled # version of this file into combinations with other programs, and to # distribute those combinations without any restriction coming from the # use of this file. (The General Public License restrictions do apply in # other respects; for example, they cover modification of the file, and # distribution when not linked into a combine executable.) # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import sys, os def empty(dir): try: fnms = os.listdir(dir) except OSError: return for fnm in fnms: path = os.path.join(dir, fnm) if os.path.isdir(path): empty(path) try: os.rmdir(path) except: pass else: try: os.remove(path) except: pass tcldir = os.environ['TCL_LIBRARY'] prvtdir = os.path.dirname(tcldir) if os.path.basename(prvtdir) == '_MEI': empty(prvtdir) os.rmdir(prvtdir)
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # In addition to the permissions in the GNU General Public License, the # authors give you unlimited permission to link or embed the compiled # version of this file into combinations with other programs, and to # distribute those combinations without any restriction coming from the # use of this file. (The General Public License restrictions do apply in # other respects; for example, they cover modification of the file, and # distribution when not linked into a combine executable.) # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import archive, iu, sys iu._globalownertypes.insert(0, archive.PYZOwner) sys.importManager = iu.ImportManager() sys.importManager.install() if not hasattr(sys, 'frozen'): sys.frozen = 1 # Implement workaround for prints in non-console mode. In non-console mode # (with "pythonw"), print randomically fails with "[errno 9] Bad file descriptor" # when the printed text is flushed (eg: buffer full); this is because the # sys.stdout object is bound to an invalid file descriptor. # Python 3000 has a fix for it (http://bugs.python.org/issue1415), but we # feel that a workaround in PyInstaller is a good thing since most people # found this problem for the first time with PyInstaller as they don't # usually run their code with "pythonw" (and it's hard to debug anyway). class NullWriter: def write(*args): pass def flush(*args): pass if sys.stdout.fileno() < 0: sys.stdout = NullWriter() if sys.stderr.fileno() < 0: sys.stderr = NullWriter()
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # In addition to the permissions in the GNU General Public License, the # authors give you unlimited permission to link or embed the compiled # version of this file into combinations with other programs, and to # distribute those combinations without any restriction coming from the # use of this file. (The General Public License restrictions do apply in # other respects; for example, they cover modification of the file, and # distribution when not linked into a combine executable.) # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import carchive import sys import os this = carchive.CArchive(sys.executable) tk = this.openEmbedded('tk.pkg') targetdir = os.environ['_MEIPASS2'] for fnm in tk.contents(): stuff = tk.extract(fnm)[1] outnm = os.path.join(targetdir, fnm) dirnm = os.path.dirname(outnm) if not os.path.exists(dirnm): os.makedirs(dirnm) open(outnm, 'wb').write(stuff) tk = None
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import win32api import struct import pywintypes import string import pprint TEST=0 LOAD_LIBRARY_AS_DATAFILE = 2 RT_VERSION = 16 def getRaw0(o): return o.raw def getRaw1(o): return str(buffer(o)) import sys if hasattr(sys, "version_info"): pyvers = sys.version_info[0]*10 + sys.version_info[1] else: toks = string.split(sys.version, '.', 2) pyvers = int(toks[0])*10 + int(toks[1]) if pyvers < 20: getRaw = getRaw0 else: getRaw = getRaw1 ##VS_VERSION_INFO { ## WORD wLength; // Specifies the length of the VS_VERSION_INFO structure ## WORD wValueLength; // Specifies the length of the Value member ## WORD wType; // 1 means text, 0 means binary ## WCHAR szKey[]; // Contains the Unicode string "VS_VERSION_INFO". ## WORD Padding1[]; ## VS_FIXEDFILEINFO Value; ## WORD Padding2[]; ## WORD Children[]; // Specifies a list of zero or more StringFileInfo or VarFileInfo structures (or both) that are children of the current version structure. ##}; def decode(pathnm): h = win32api.LoadLibraryEx(pathnm, 0, LOAD_LIBRARY_AS_DATAFILE) nm = win32api.EnumResourceNames(h, RT_VERSION)[0] data = win32api.LoadResource(h, RT_VERSION, nm) vs = VSVersionInfo() j = vs.fromRaw(data) if TEST: print vs if data[:j] != vs.toRaw(): print "AAAAAGGHHHH" txt = repr(vs) glbls = {} glbls['VSVersionInfo'] = VSVersionInfo glbls['FixedFileInfo'] = FixedFileInfo glbls['StringFileInfo'] = StringFileInfo glbls['StringTable'] = StringTable glbls['StringStruct'] = StringStruct glbls['VarFileInfo'] = VarFileInfo glbls['VarStruct'] = VarStruct vs2 = eval(txt+'\n', glbls) if vs.toRaw() != vs2.toRaw(): print print 'reconstruction not the same!' print vs2 win32api.FreeLibrary(h) return vs class VSVersionInfo: def __init__(self, ffi=None, kids=None): self.ffi = ffi self.kids = kids if kids is None: self.kids = [] def fromRaw(self, data): i, (sublen, vallen, wType, nm) = parseCommon(data) #vallen is length of the ffi, typ is 0, nm is 'VS_VERSION_INFO' i = ((i + 3) / 4) * 4 # now a VS_FIXEDFILEINFO self.ffi = FixedFileInfo() j = self.ffi.fromRaw(data, i) #print ffi if TEST: if data[i:j] != self.ffi.toRaw(): print "raw:", `data[i:j]` print "ffi:", `self.ffi.toRaw()` i = j while i < sublen: j = i i, (csublen, cvallen, ctyp, nm) = parseCommon(data, i) if string.strip(str(nm)) == "StringFileInfo": sfi = StringFileInfo() k = sfi.fromRaw(csublen, cvallen, nm, data, i, j+csublen) if TEST: if data[j:k] != sfi.toRaw(): rd = data[j:k] sd = sfi.toRaw() for x in range(0, len(rd), 16): rds = rd[x:x+16] sds = sd[x:x+16] if rds != sds: print "rd[%s:%s+16]: %s" % (x, x, `rds`) print "sd[%s:%s+16]: %s" % (x, x, `sds`) print print "raw: len %d, wLength %d" % (len(rd), struct.unpack('h', rd[:2])[0]) print "sfi: len %d, wLength %d" % (len(sd), struct.unpack('h', sd[:2])[0]) self.kids.append(sfi) i = k else: vfi = VarFileInfo() k = vfi.fromRaw(csublen, cvallen, nm, data, i, j+csublen) self.kids.append(vfi) if TEST: if data[j:k] != vfi.toRaw(): print "raw:", `data[j:k]` print "vfi:", `vfi.toRaw()` i = k i = j + csublen i = ((i + 3) / 4) * 4 return i def toRaw(self): nm = pywintypes.Unicode('VS_VERSION_INFO') rawffi = self.ffi.toRaw() vallen = len(rawffi) typ = 0 sublen = 6 + 2*len(nm) + 2 pad = '' if sublen % 4: pad = '\000\000' sublen = sublen + len(pad) + vallen pad2 = '' if sublen % 4: pad2 = '\000\000' tmp = [] for kid in self.kids: tmp.append(kid.toRaw()) tmp = string.join(tmp, '') sublen = sublen + len(pad2) + len(tmp) return struct.pack('hhh', sublen, vallen, typ) + getRaw(nm) + '\000\000' + pad + rawffi + pad2 + tmp def __repr__(self, indent=''): tmp = [] newindent = indent + ' ' for kid in self.kids: tmp.append(kid.__repr__(newindent+' ')) tmp = string.join(tmp, ', \n') return "VSVersionInfo(\n%sffi=%s,\n%skids=[\n%s\n%s]\n)" % (newindent, self.ffi.__repr__(newindent), newindent, tmp, newindent) def parseCommon(data, start=0): i = start + 6 (wLength, wValueLength, wType) = struct.unpack('3h', data[start:i]) #print "wLength, wValueLength, wType, i:", wLength, wValueLength, wType, i i, szKey = parseUString(data, i, i+wLength) #i = ((i + 3) / 4) * 4 #print `data[start+6:start+wLength]` return i, (wLength, wValueLength, wType, szKey) def parseUString(data, start, limit): i = start while i < limit: if data[i:i+2] == '\000\000': break i = i + 2 szKey = pywintypes.UnicodeFromRaw(data[start:i]) i = i + 2 #print "szKey:", '"'+str(szKey)+'"', "(consumed", i-start, "bytes - to", i, ")" return i, szKey ##VS_FIXEDFILEINFO { // vsffi ## DWORD dwSignature; //Contains the value 0xFEEFO4BD ## DWORD dwStrucVersion; //Specifies the binary version number of this structure. The high-order word of this member contains the major version number, and the low-order word contains the minor version number. ## DWORD dwFileVersionMS; // Specifies the most significant 32 bits of the file's binary version number ## DWORD dwFileVersionLS; // ## DWORD dwProductVersionMS; // Specifies the most significant 32 bits of the binary version number of the product with which this file was distributed ## DWORD dwProductVersionLS; // ## DWORD dwFileFlagsMask; // Contains a bitmask that specifies the valid bits in dwFileFlags. A bit is valid only if it was defined when the file was created. ## DWORD dwFileFlags; // VS_FF_DEBUG, VS_FF_PATCHED etc. ## DWORD dwFileOS; // VOS_NT, VOS_WINDOWS32 etc. ## DWORD dwFileType; // VFT_APP etc. ## DWORD dwFileSubtype; // 0 unless VFT_DRV or VFT_FONT or VFT_VXD ## DWORD dwFileDateMS; ## DWORD dwFileDateLS; ##}; class FixedFileInfo: def __init__(self, filevers=(0, 0, 0, 0), prodvers=(0, 0, 0, 0), mask=0x3f, flags=0x0, OS=0x40004, fileType=0x1, subtype=0x0, date=(0, 0)): self.sig = 0xfeef04bdL self.strucVersion = 0x10000 self.fileVersionMS = (filevers[0] << 16) | (filevers[1] & 0xffff) self.fileVersionLS = (filevers[2] << 16) | (filevers[3] & 0xffff) self.productVersionMS = (prodvers[0] << 16) | (prodvers[1] & 0xffff) self.productVersionLS = (prodvers[2] << 16) | (prodvers[3] & 0xffff) self.fileFlagsMask = mask self.fileFlags = flags self.fileOS = OS self.fileType = fileType self.fileSubtype = subtype self.fileDateMS = date[0] self.fileDateLS = date[1] def fromRaw(self, data, i): (self.sig, self.strucVersion, self.fileVersionMS, self.fileVersionLS, self.productVersionMS, self.productVersionLS, self.fileFlagsMask, self.fileFlags, self.fileOS, self.fileType, self.fileSubtype, self.fileDateMS, self.fileDateLS) = struct.unpack('13l', data[i:i+52]) return i+52 def toRaw(self): return struct.pack('L12l', self.sig, self.strucVersion, self.fileVersionMS, self.fileVersionLS, self.productVersionMS, self.productVersionLS, self.fileFlagsMask, self.fileFlags, self.fileOS, self.fileType, self.fileSubtype, self.fileDateMS, self.fileDateLS) def __repr__(self, indent=''): fv = (self.fileVersionMS >> 16, self.fileVersionMS & 0xffff, self.fileVersionLS >> 16, self.fileVersionLS & 0xFFFF) pv = (self.productVersionMS >> 16, self.productVersionMS & 0xffff, self.productVersionLS >> 16, self.productVersionLS & 0xFFFF) fd = (self.fileDateMS, self.fileDateLS) tmp = ["FixedFileInfo(", "filevers=%s," % (fv,), "prodvers=%s," % (pv,), "mask=%s," % hex(self.fileFlagsMask), "flags=%s," % hex(self.fileFlags), "OS=%s," % hex(self.fileOS), "fileType=%s," % hex(self.fileType), "subtype=%s," % hex(self.fileSubtype), "date=%s" % (fd,), ")" ] return string.join(tmp, '\n'+indent+' ') ##StringFileInfo { ## WORD wLength; // Specifies the length of the version resource ## WORD wValueLength; // Specifies the length of the Value member in the current VS_VERSION_INFO structure ## WORD wType; // 1 means text, 0 means binary ## WCHAR szKey[]; // Contains the Unicode string "StringFileInfo". ## WORD Padding[]; ## StringTable Children[]; // Specifies a list of zero or more String structures ##}; class StringFileInfo: def __init__(self, kids=None): self.name = "StringFileInfo" if kids is None: self.kids = [] else: self.kids = kids def fromRaw(self, sublen, vallen, name, data, i, limit): self.name = name while i < limit: st = StringTable() j = st.fromRaw(data, i, limit) if TEST: if data[i:j] != st.toRaw(): rd = data[i:j] sd = st.toRaw() for x in range(0, len(rd), 16): rds = rd[x:x+16] sds = sd[x:x+16] if rds != sds: print "rd[%s:%s+16]: %s" % (x, x, `rds`) print "sd[%s:%s+16]: %s" % (x, x, `sds`) print print "raw: len %d, wLength %d" % (len(rd), struct.unpack('h', rd[:2])[0]) print " st: len %d, wLength %d" % (len(sd), struct.unpack('h', sd[:2])[0]) self.kids.append(st) i = j return i def toRaw(self): if type(self.name) is STRINGTYPE: self.name = pywintypes.Unicode(self.name) vallen = 0 typ = 1 sublen = 6 + 2*len(self.name) + 2 pad = '' if sublen % 4: pad = '\000\000' tmp = [] for kid in self.kids: tmp.append(kid.toRaw()) tmp = string.join(tmp, '') sublen = sublen + len(pad) + len(tmp) if tmp[-2:] == '\000\000': sublen = sublen - 2 return struct.pack('hhh', sublen, vallen, typ) + getRaw(self.name) + '\000\000' + pad + tmp def __repr__(self, indent=''): tmp = [] newindent = indent + ' ' for kid in self.kids: tmp.append(kid.__repr__(newindent)) tmp = string.join(tmp, ', \n') return "%sStringFileInfo(\n%s[\n%s\n%s])" % (indent, newindent, tmp, newindent) ##StringTable { ## WORD wLength; ## WORD wValueLength; ## WORD wType; ## WCHAR szKey[]; ## String Children[]; // Specifies a list of zero or more String structures. ##}; class StringTable: def __init__(self, name=None, kids=None): self.name = name self.kids = kids if name is None: self.name = '' if kids is None: self.kids = [] def fromRaw(self, data, i, limit): #print "Parsing StringTable" i, (cpsublen, cpwValueLength, cpwType, self.name) = parseCodePage(data, i, limit) # should be code page junk #i = ((i + 3) / 4) * 4 while i < limit: ss = StringStruct() j = ss.fromRaw(data, i, limit) if TEST: if data[i:j] != ss.toRaw(): print "raw:", `data[i:j]` print " ss:", `ss.toRaw()` i = j self.kids.append(ss) i = ((i + 3) / 4) * 4 return i def toRaw(self): if type(self.name) is STRINGTYPE: self.name = pywintypes.Unicode(self.name) vallen = 0 typ = 1 sublen = 6 + 2*len(self.name) + 2 tmp = [] for kid in self.kids: raw = kid.toRaw() if len(raw) % 4: raw = raw + '\000\000' tmp.append(raw) tmp = string.join(tmp, '') sublen = sublen + len(tmp) if tmp[-2:] == '\000\000': sublen = sublen - 2 return struct.pack('hhh', sublen, vallen, typ) + getRaw(self.name) + '\000\000' + tmp def __repr__(self, indent=''): tmp = [] newindent = indent + ' ' for kid in self.kids: tmp.append(repr(kid)) tmp = string.join(tmp, ',\n%s' % newindent) return "%sStringTable(\n%s'%s', \n%s[%s])" % (indent, newindent, str(self.name), newindent, tmp) ##String { ## WORD wLength; ## WORD wValueLength; ## WORD wType; ## WCHAR szKey[]; ## WORD Padding[]; ## String Value[]; ##}; class StringStruct: def __init__(self, name=None, val=None): self.name = name self.val = val if name is None: self.name = '' if val is None: self.val = '' def fromRaw(self, data, i, limit): i, (sublen, vallen, typ, self.name) = parseCommon(data, i) limit = i + sublen i = ((i + 3) / 4) * 4 i, self.val = parseUString(data, i, limit) return i def toRaw(self): if type(self.name) is STRINGTYPE: self.name = pywintypes.Unicode(self.name) if type(self.val) is STRINGTYPE: self.val = pywintypes.Unicode(self.val) vallen = len(self.val) + 1 typ = 1 sublen = 6 + 2*len(self.name) + 2 pad = '' if sublen % 4: pad = '\000\000' sublen = sublen + len(pad) + 2*vallen return struct.pack('hhh', sublen, vallen, typ) + getRaw(self.name) + '\000\000' + pad + getRaw(self.val) + '\000\000' def __repr__(self, indent=''): if pyvers < 20: return "StringStruct('%s', '%s')" % (str(self.name), str(self.val)) else: return "StringStruct('%s', '%s')" % (self.name, self.val) def parseCodePage(data, i, limit): #print "Parsing CodePage" i, (sublen, wValueLength, wType, nm) = parseCommon(data, i) #i = ((i + 3) / 4) * 4 return i, (sublen, wValueLength, wType, nm) ##VarFileInfo { ## WORD wLength; // Specifies the length of the version resource ## WORD wValueLength; // Specifies the length of the Value member in the current VS_VERSION_INFO structure ## WORD wType; // 1 means text, 0 means binary ## WCHAR szKey[]; // Contains the Unicode string "VarFileInfo". ## WORD Padding[]; ## Var Children[]; // Specifies a list of zero or more Var structures ##}; class VarFileInfo: def __init__(self, kids=None): if kids is None: self.kids = [] else: self.kids = kids def fromRaw(self, sublen, vallen, name, data, i, limit): self.sublen = sublen self.vallen = vallen self.name = name i = ((i + 3) / 4) * 4 while i < limit: vs = VarStruct() j = vs.fromRaw(data, i, limit) self.kids.append(vs) if TEST: if data[i:j] != vs.toRaw(): print "raw:", `data[i:j]` print "cmp:", `vs.toRaw()` i = j return i def toRaw(self): self.vallen = 0 self.wType = 1 self.name = pywintypes.Unicode('VarFileInfo') sublen = 6 + 2*len(self.name) + 2 pad = '' if sublen % 4: pad = '\000\000' tmp = [] for kid in self.kids: tmp.append(kid.toRaw()) tmp = string.join(tmp, '') self.sublen = sublen + len(pad) + len(tmp) return struct.pack('hhh', self.sublen, self.vallen, self.wType) + getRaw(self.name) + '\000\000' + pad + tmp def __repr__(self, indent=''): tmp = map(repr, self.kids) return "%sVarFileInfo([%s])" % (indent, string.join(tmp, ', ')) ##Var { ## WORD wLength; // Specifies the length of the version resource ## WORD wValueLength; // Specifies the length of the Value member in the current VS_VERSION_INFO structure ## WORD wType; // 1 means text, 0 means binary ## WCHAR szKey[]; // Contains the Unicode string "Translation" or a user-defined key string value ## WORD Padding[]; // ## WORD Value[]; // Specifies a list of one or more values that are language and code-page identifiers ##}; STRINGTYPE = type('') class VarStruct: def __init__(self, name=None, kids=None): self.name = name self.kids = kids if name is None: self.name = '' if kids is None: self.kids = [] def fromRaw(self, data, i, limit): i, (self.sublen, self.wValueLength, self.wType, self.name) = parseCommon(data, i) i = ((i + 3) / 4) * 4 for j in range(self.wValueLength/2): kid = struct.unpack('h', data[i:i+2])[0] self.kids.append(kid) i = i + 2 return i def toRaw(self): self.wValueLength = len(self.kids) * 2 self.wType = 0 if type(self.name) is STRINGTYPE: self.name = pywintypes.Unicode(self.name) sublen = 6 + 2*len(self.name) + 2 pad = '' if sublen % 4: pad = '\000\000' self.sublen = sublen + len(pad) + self.wValueLength tmp = [] for kid in self.kids: tmp.append(struct.pack('h', kid)) tmp = string.join(tmp, '') return struct.pack('hhh', self.sublen, self.wValueLength, self.wType) + getRaw(self.name) + '\000\000' + pad + tmp def __repr__(self, indent=''): return "VarStruct('%s', %s)" % (str(self.name), repr(self.kids)) def SetVersion(exenm, versionfile): txt = open(versionfile, 'r').read() vs = eval(txt+'\n', globals()) hdst = win32api.BeginUpdateResource(exenm, 0) win32api.UpdateResource(hdst, RT_VERSION, 1, vs.toRaw()) win32api.EndUpdateResource (hdst, 0) if __name__ == '__main__': import sys TEST = 1 if len(sys.argv) < 2: decode('c:/Program Files/Netscape/Communicator/Program/netscape.exe') else: print "Examining", sys.argv[1] decode(sys.argv[1])
Python
# Subclass of Archive that can be understood by a C program (see launch.c). # Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 1999, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import archive import struct try: import zlib except ImportError: zlib = archive.DummyZlib() import sys if sys.version[0] == '1': import strop find = strop.find split = strop.split else: def find(s, sub): return s.find(sub) def split(s, delim, count): return s.split(delim, count) class CTOC: """A class encapsulating the table of contents of a CArchive. When written to disk, it is easily read from C.""" ENTRYSTRUCT = '!iiiibc' #(structlen, dpos, dlen, ulen, flag, typcd) followed by name def __init__(self): self.data = [] def frombinary(self, s): """Decode the binary string into an in memory list. S is a binary string.""" entrylen = struct.calcsize(self.ENTRYSTRUCT) p = 0 while p<len(s): (slen, dpos, dlen, ulen, flag, typcd) = struct.unpack(self.ENTRYSTRUCT, s[p:p+entrylen]) nmlen = slen - entrylen p = p + entrylen (nm,) = struct.unpack(`nmlen`+'s', s[p:p+nmlen]) p = p + nmlen # version 4 # self.data.append((dpos, dlen, ulen, flag, typcd, nm[:-1])) # version 5 # nm may have up to 15 bytes of padding pos = find(nm, '\0') if pos < 0: self.data.append((dpos, dlen, ulen, flag, typcd, nm)) else: self.data.append((dpos, dlen, ulen, flag, typcd, nm[:pos])) #end version 5 def tobinary(self): """Return self as a binary string.""" import string entrylen = struct.calcsize(self.ENTRYSTRUCT) rslt = [] for (dpos, dlen, ulen, flag, typcd, nm) in self.data: nmlen = len(nm) + 1 # add 1 for a '\0' # version 4 # rslt.append(struct.pack(self.ENTRYSTRUCT+`nmlen`+'s', # nmlen+entrylen, dpos, dlen, ulen, flag, typcd, nm+'\0')) # version 5 # align to 16 byte boundary so xplatform C can read toclen = nmlen + entrylen if toclen % 16 == 0: pad = '\0' else: padlen = 16 - (toclen % 16) pad = '\0'*padlen nmlen = nmlen + padlen rslt.append(struct.pack(self.ENTRYSTRUCT+`nmlen`+'s', nmlen+entrylen, dpos, dlen, ulen, flag, typcd, nm+pad)) # end version 5 return string.join(rslt, '') def add(self, dpos, dlen, ulen, flag, typcd, nm): """Add an entry to the table of contents. DPOS is data position. DLEN is data length. ULEN is the uncompressed data len. FLAG says if the data is compressed. TYPCD is the "type" of the entry (used by the C code) NM is the entry's name.""" self.data.append((dpos, dlen, ulen, flag, typcd, nm)) def get(self, ndx): """return the toc entry (tuple) at index NDX""" return self.data[ndx] def __getitem__(self, ndx): return self.data[ndx] def find(self, name): """Return the index of the toc entry with name NAME. Return -1 for failure.""" for i in range(len(self.data)): if self.data[i][-1] == name: return i return -1 class CArchive(archive.Archive): """An Archive subclass that an hold arbitrary data. Easily handled from C or from Python.""" MAGIC = 'MEI\014\013\012\013\016' HDRLEN = 0 TOCTMPLT = CTOC TRLSTRUCT = '!8siiii' TRLLEN = 24 LEVEL = 9 def __init__(self, path=None, start=0, len=0): """Constructor. PATH is path name of file (create an empty CArchive if path is None). START is the seekposition within PATH. LEN is the length of the CArchive (if 0, then read till EOF). """ self.len = len archive.Archive.__init__(self, path, start) def checkmagic(self): """Verify that self is a valid CArchive. Magic signature is at end of the archive.""" #magic is at EOF; if we're embedded, we need to figure where that is if self.len: self.lib.seek(self.start+self.len, 0) else: self.lib.seek(0, 2) filelen = self.lib.tell() if self.len: self.lib.seek(self.start+self.len-self.TRLLEN, 0) else: self.lib.seek(-self.TRLLEN, 2) (magic, totallen, tocpos, toclen, pyvers) = struct.unpack(self.TRLSTRUCT, self.lib.read(self.TRLLEN)) if magic != self.MAGIC: raise RuntimeError, "%s is not a valid %s archive file" \ % (self.path, self.__class__.__name__) self.pkgstart = filelen - totallen if self.len: if totallen != self.len or self.pkgstart != self.start: raise RuntimeError, "Problem with embedded archive in %s" % self.path self.tocpos, self.toclen = tocpos, toclen def loadtoc(self): """Load the table of contents into memory.""" self.toc = self.TOCTMPLT() self.lib.seek(self.pkgstart+self.tocpos) tocstr = self.lib.read(self.toclen) self.toc.frombinary(tocstr) def extract(self, name): """Get the contents of an entry. NAME is an entry name. Return the tuple (ispkg, contents). For non-Python resoures, ispkg is meaningless (and 0). Used by the import mechanism.""" if type(name) == type(''): ndx = self.toc.find(name) if ndx == -1: return None else: ndx = name (dpos, dlen, ulen, flag, typcd, nm) = self.toc.get(ndx) self.lib.seek(self.pkgstart+dpos) rslt = self.lib.read(dlen) if flag == 2: global AES import AES key = rslt[:32] # Note: keep this in sync with bootloader's code rslt = AES.new(key, AES.MODE_CFB, "\0"*AES.block_size).decrypt(rslt[32:]) if flag == 1 or flag == 2: rslt = zlib.decompress(rslt) if typcd == 'M': return (1, rslt) return (0, rslt) def contents(self): """Return the names of the entries""" rslt = [] for (dpos, dlen, ulen, flag, typcd, nm) in self.toc: rslt.append(nm) return rslt def add(self, entry): """Add an ENTRY to the CArchive. ENTRY must have: entry[0] is name (under which it will be saved). entry[1] is fullpathname of the file. entry[2] is a flag for it's storage format (0==uncompressed, 1==compressed) entry[3] is the entry's type code. Version 5: If the type code is 'o': entry[0] is the runtime option eg: v (meaning verbose imports) u (menaing unbuffered) W arg (warning option arg) s (meaning do site.py processing.""" (nm, pathnm, flag, typcd) = entry[:4] # version 5 - allow type 'o' = runtime option try: if typcd == 'o': s = '' flag = 0 elif typcd == 's': # If it's a source code file, add \0 terminator as it will be # executed as-is by the bootloader. s = open(pathnm, 'r').read() s = s.replace("\r\n", "\n") s = s + '\n\0' else: s = open(pathnm, 'rb').read() except IOError: print "Cannot find ('%s', '%s', %s, '%s')" % (nm, pathnm, flag, typcd) raise ulen = len(s) assert flag in range(3) if flag == 1 or flag == 2: s = zlib.compress(s, self.LEVEL) if flag == 2: global AES import AES, Crypt key = Crypt.gen_random_key(32) # Note: keep this in sync with bootloader's code s = key + AES.new(key, AES.MODE_CFB, "\0"*AES.block_size).encrypt(s) dlen = len(s) where = self.lib.tell() if typcd == 'm': if find(pathnm, '.__init__.py') > -1: typcd = 'M' self.toc.add(where, dlen, ulen, flag, typcd, nm) self.lib.write(s) def save_toc(self, tocpos): """Save the table of contents to disk.""" self.tocpos = tocpos tocstr = self.toc.tobinary() self.toclen = len(tocstr) self.lib.write(tocstr) def save_trailer(self, tocpos): """Save the trailer to disk. CArchives can be opened from the end - the trailer points back to the start. """ totallen = tocpos + self.toclen + self.TRLLEN if hasattr(sys, "version_info"): pyvers = sys.version_info[0]*10 + sys.version_info[1] else: toks = split(sys.version, '.', 2) pyvers = int(toks[0])*10 + int(toks[1]) trl = struct.pack(self.TRLSTRUCT, self.MAGIC, totallen, tocpos, self.toclen, pyvers) self.lib.write(trl) def openEmbedded(self, name): """Open a CArchive of name NAME embedded within this CArchive.""" ndx = self.toc.find(name) if ndx == -1: raise KeyError, "Member '%s' not found in %s" % (name, self.path) (dpos, dlen, ulen, flag, typcd, nm) = self.toc.get(ndx) if flag: raise ValueError, "Cannot open compressed archive %s in place" return CArchive(self.path, self.pkgstart+dpos, dlen)
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA print "test5 - W ignore" try: import regex except ImportError: import re print "test5 - done"
Python
#!/usr/bin/env python import time print time.strptime(time.ctime())
Python
# -*- mode: python -*- __testname__ = 'test1' a = Analysis(['../support/_mountzlib.py', 'test1.py'], pathex=[], hookspath=['hooks1']) pyz = PYZ(a.pure) exe = EXE(pyz, a.scripts, exclude_binaries=1, name=os.path.join('build', 'pyi.' + config['target_platform'], __testname__ + '.exe'), debug=0, console=1) coll = COLLECT( exe, a.binaries, name=os.path.join('dist', __testname__),)
Python
# -*- mode: python -*- __testname__ = 'test13' a = Analysis(['../support/_mountzlib.py', '../support/useUnicode.py', 'test13.py'], pathex=[]) pyz = PYZ(a.pure) exe = EXE(pyz, a.scripts, exclude_binaries=1, name=os.path.join('build', 'pyi.' + config['target_platform'], __testname__ + '.exe'), debug=False, strip=False, upx=False, console=1 ) coll = COLLECT( exe, a.binaries, strip=False, upx=False, name=os.path.join('dist', __testname__),)
Python
# -*- mode: python -*- __testname__ = 'test-relative-import2' a = Analysis([os.path.join(HOMEPATH,'support/_mountzlib.py'), __testname__ + '.py'], ) pyz = PYZ(a.pure) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, name = os.path.join('dist', __testname__, __testname__ +'.exe'), debug=False, strip=False, upx=False, console=1 )
Python
#!/usr/bin/env python # Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # This program will execute any file with name test*<digit>.py. If your test # need an aditional dependency name it test*<digit><letter>.py to be ignored # by this program but be recognizable by any one as a dependency of that # particual test. import os, sys, glob, string import pprint import shutil HOME = '..' MIN_VERSION = { 'test-relative-import': (2,5), 'test-relative-import2': (2,6), 'test-relative-import3': (2,5), 'test-celementtree': (2,5), 'test9': (2,3), } DEPENDENCIES = { 'test-ctypes-cdll-c': ["ctypes"], 'test-ctypes-cdll-c2': ["ctypes"], 'test-numpy': ["numpy"], 'test-pycrypto': ["Crypto"], 'test-zipimport1': ["pkg_resources"], 'test-zipimport2': ["pkg_resources", "setuptools"], 'test15': ["ctypes"], 'test-wx': ["wx"], } try: here=os.path.dirname(os.path.abspath(__file__)) except NameError: here=os.path.dirname(os.path.abspath(sys.argv[0])) os.chdir(here) PYTHON = sys.executable # On Mac OS X we support only 32bit # python interpreter can be run as 32bit or 64bit # run as 32bit if sys.platform.startswith('darwin'): PYTHON = 'arch -i386 ' + PYTHON if sys.platform[:3] == 'win': if string.find(PYTHON, ' ') > -1: PYTHON='"%s"' % PYTHON if __debug__: PYOPTS = "" else: PYOPTS = "-O" # files/globs to clean up CLEANUP = """python_exe.build logdict*.log disttest* buildtest* warn*.txt *.py[co] */*.py[co] */*/*.py[co] build/ dist/ """.split() def clean(): for clean in CLEANUP: clean = glob.glob(clean) for path in clean: try: if os.path.isdir(path): shutil.rmtree(path) else: os.remove(path) except OSError, e: print e def _msg(*args, **kw): short = kw.get('short', 0) sep = kw.get('sep', '#') if not short: print print sep*20, for a in args: print a, print sep*20 if not short: print def runtests(alltests, filters=None, configfile=None, run_executable=1): info = "Executing PyInstaller tests in: %s" % os.getcwd() print "*" * min(80, len(info)) print info print "*" * min(80, len(info)) OPTS = '' if configfile: # todo: quote correctly OTPS = ' -c "%s"' % configfile build_python = open("python_exe.build", "w") build_python.write(sys.executable+"\n") build_python.write("debug=%s" % __debug__+"\n") build_python.close() if not filters: tests = alltests else: tests = [] for part in filters: tests += [t for t in alltests if part in t and t not in tests] tests = [(len(x), x) for x in tests] tests.sort() path = os.environ["PATH"] counter = { "passed": [], "failed": [], "skipped": [] } for _,test in tests: test = os.path.splitext(os.path.basename(test))[0] if test in MIN_VERSION and MIN_VERSION[test] > sys.version_info: counter["skipped"].append(test) continue if test in DEPENDENCIES: failed = False for mod in DEPENDENCIES[test]: res = os.system(PYTHON + ' -c "import %s"' % mod) if res != 0: failed = True break if failed: print "Skipping test because module %s is missing" % mod counter["skipped"].append(test) continue _msg("BUILDING TEST", test) prog = string.join([PYTHON, PYOPTS, os.path.join(HOME, 'Build.py'), OPTS, test+".spec"], ' ') print "BUILDING:", prog res = os.system(prog) if res == 0 and run_executable: _msg("EXECUTING TEST", test) # Run the test in a clean environment to make sure they're # really self-contained del os.environ["PATH"] of_prog = os.path.join('dist', test) # one-file deploy filename od_prog = os.path.join('dist', test, test) # one-dir deploy filename prog = None if os.path.isfile(of_prog): prog = of_prog elif os.path.isfile(of_prog + ".exe"): prog = of_prog + ".exe" elif os.path.isdir(of_prog): if os.path.isfile(od_prog): prog = od_prog elif os.path.isfile(od_prog + ".exe"): prog = od_prog + ".exe" if prog is None: res = 1 print "ERROR: no file generated by PyInstaller found!" else: print "RUNNING:", prog res = os.system(prog) os.environ["PATH"] = path if res == 0: _msg("FINISHING TEST", test, short=1) counter["passed"].append(test) else: _msg("TEST", test, "FAILED", short=1, sep="!!") counter["failed"].append(test) pprint.pprint(counter) if __name__ == '__main__': normal_tests = glob.glob('test*.spec') interactive_tests = glob.glob('test*i.spec') try: from optparse import OptionParser except ImportError: sys.path.append("..") from pyi_optparse import OptionParser if sys.version_info < (2,5): parser = OptionParser(usage="%prog [options] [TEST-NAME ...]") else: parser = OptionParser(usage="%prog [options] [TEST-NAME ...]", epilog="TEST-NAME can be the name of the .py-file, the .spec-file or only the basename.") parser.add_option('-c', '--clean', action='store_true', help='Clean up generated files') parser.add_option('-i', '--interactive-tests', action='store_true', help='Run interactive tests (default: run normal tests)') parser.add_option('-n', '--no-run', action='store_true', help='Do not run the built executables. ' 'Useful for cross builds.') parser.add_option('-C', '--configfile', default=os.path.join(HOME, 'config.dat'), help='Name of generated configfile (default: %default)') opts, args = parser.parse_args() if opts.clean: clean() raise SystemExit() if args: if opts.interactive_tests: parser.error('Must not specify -i/--interactive-tests when passing test names.') tests = args elif opts.interactive_tests: print "Running interactive tests" tests = interactive_tests else: tests = [t for t in normal_tests if t not in interactive_tests] print "Running normal tests (-i for interactive tests)" clean() runtests(tests, configfile=opts.configfile, run_executable=not opts.no_run)
Python
from relimp3a.aa import a1 if __name__ == '__main__': print a1.getString()
Python
name = 'relimp.relimp.relimp3'
Python
from __future__ import absolute_import name = 'relimp.relimp.relimp2' from . import relimp3 assert relimp3.name == 'relimp.relimp.relimp3' from .. import relimp assert relimp.name == 'relimp.relimp' import relimp assert relimp.name == 'relimp' import relimp.relimp2 assert relimp.relimp2.name == 'relimp.relimp2' # While this seams to work when running Python, it is wrong: # .relimp should be a sibling of this package #from .relimp import relimp2 #assert relimp2.name == 'relimp.relimp2'
Python
name = 'relimp.relimp'
Python
from __future__ import absolute_import name = 'relimp.relimp1' from . import relimp2 as upper from . relimp import relimp2 as lower assert upper.name == 'relimp.relimp2' assert lower.name == 'relimp.relimp.relimp2' if upper.__name__ == lower.__name__: raise SystemExit("Imported the same module") if upper.__file__ == lower.__file__: raise SystemExit("Imported the same file")
Python
name = 'relimp.E'
Python
name = 'relimp.relimp2'
Python
name = 'relimp.F.G'
Python
name = 'relimp.F' class H: name = 'relimp.F.H'
Python
name = 'relimp'
Python
name = 'relimp.B.D' class X: name = 'relimp.B.D.X'
Python
name = 'relimp.B'
Python
name = 'relimp.B.C' from . import D # Imports relimp.B.D from .D import X # Imports relimp.B.D.X from .. import E # Imports relimp.E from ..F import G # Imports relimp.F.G from ..F import H # Imports relimp.F.H assert D.name == 'relimp.B.D' assert E.name == 'relimp.E' assert G.name == 'relimp.F.G' assert H.name == 'relimp.F.H'
Python
import sys if sys.version_info >= (2,5): from email import utils from email.header import Header from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.nonmultipart import MIMENonMultipart else: print "test-email skipped"
Python
# -*- mode: python -*- __testname__ = 'test10' a = Analysis([os.path.join(HOMEPATH,'support', '_mountzlib.py'), os.path.join(HOMEPATH,'support', 'useUnicode.py'), 'test10.py'], pathex=['.']) pyz = PYZ(a.pure) exe = EXE(pyz, a.scripts, exclude_binaries=1, name=os.path.join('build', 'pyi.' + config['target_platform'], __testname__ + '.exe'), debug=False, strip=False, upx=False, console=True ) coll = COLLECT( exe, a.binaries, strip=False, upx=False, name=os.path.join('dist', __testname__),)
Python
# -*- mode: python -*- a = Analysis([os.path.join(HOMEPATH,'support/_mountzlib.py'), os.path.join(HOMEPATH,'support/useUnicode.py'), 'test-celementtree.py'], pathex=[]) pyz = PYZ(a.pure) exe = EXE(pyz, a.scripts, exclude_binaries=1, name=os.path.join('build/pyi.linux2/test-celementtree', 'test-celementtree.exe'), debug=True, strip=False, upx=False, console=1 ) coll = COLLECT( exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=False, name=os.path.join('dist', 'test-celementtree'))
Python
# -*- mode: python -*- __testname__ = 'test-zipimport1' a = Analysis([os.path.join(HOMEPATH,'support/_mountzlib.py'), os.path.join(HOMEPATH,'support/useUnicode.py'), __testname__ + '.py'], ) pyz = PYZ(a.pure) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, name = os.path.join('dist', __testname__, __testname__ +'.exe'), debug=False, strip=False, upx=False, console=1 )
Python
import ctypes, ctypes.util # Make sure we are able to load the MSVCRXX.DLL we are currently bound # to through ctypes. lib = ctypes.CDLL(ctypes.util.find_library('c')) print lib
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy from matplotlib import mlab from matplotlib import pyplot def main(): # Part of the example at # http://matplotlib.sourceforge.net/plot_directive/mpl_examples/pylab_examples/contour_demo.py delta = 0.025 x = numpy.arange(-3.0, 3.0, delta) y = numpy.arange(-2.0, 2.0, delta) X, Y = numpy.meshgrid(x, y) Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = 10.0 * (Z2 - Z1) pyplot.figure() CS = pyplot.contour(X, Y, Z) pyplot.show() if __name__ == "__main__": main()
Python
#!/usr/bin/env python # Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import sys try: import codecs except ImportError: print "This test works only with Python versions that support Unicode" sys.exit(0) a = "foo bar" au = codecs.getdecoder("utf-8")(a)[0] b = codecs.getencoder("utf-8")(au)[0] print "codecs working:", a == b assert a == b sys.exit(0)
Python
# -*- mode: python -*- __testname__ = 'test-pycrypto' a = Analysis([os.path.join(HOMEPATH,'support', '_mountzlib.py'), os.path.join(HOMEPATH,'support', 'useUnicode.py'), __testname__ + '.py']) pyz = PYZ(a.pure) exe = EXE(pyz, a.scripts, exclude_binaries=1, name=os.path.join('build', 'pyi.' + config['target_platform'], __testname__, __testname__ + '.exe'), debug=False, strip=False, upx=False, console=True ) coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=False, name=os.path.join('dist', __testname__))
Python
import os import sys if __name__ == "__main__": if sys.version_info >= (2,5): import subprocess subprocess.check_call([os.path.dirname(sys.executable) + "/../test-nestedlaunch0/test-nestedlaunch0.exe"]) else: fn = os.path.join(os.path.dirname(sys.executable), "..", "test-nestedlaunch0", "test-nestedlaunch0.exe") if os.system(fn) != 0: raise RuntimeError("os.system failed: %s" % fn)
Python
assert "foo".decode("ascii") == u"foo"
Python
#!/usr/bin/env python # -*- mode: python -*- # # Copyright (C) 2008 Hartmut Goebel <h.goebel@goebel-consult.de> # Licence: GNU General Public License version 3 (GPL v3) # # This file is part of PyInstaller <http://www.pyinstaller.org> # # pyinstaller is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # pyinstaller is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ test for zipimport - minimalistic, just import pgk_resource """ import os import sys print __name__, 'is running' print 'sys.path:', sys.path print 'dir contents .exe:', os.listdir(os.path.dirname(sys.executable)) print '-----------' print 'dir contents _MEIPASS2:', os.listdir(os.environ['_MEIPASS2']) print '-----------' print 'now importing pkg_resources' import pkg_resources print "dir(pkg_resources)", dir(pkg_resources)
Python
# Copyright (C) 2007, Matteo Bertini # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA print "test13 - Used to fail if _xmlplus is installed" import sys if sys.version_info[:2] >= (2, 5): import _elementtree print "test13 DONE" else: print "Python 2.5 test13 skipped"
Python
# -*- mode: python -*- a = Analysis([os.path.join(HOMEPATH,'support/_mountzlib.py'), os.path.join(HOMEPATH,'support/useUnicode.py'), 'test-nestedlaunch0.py'], pathex=['']) pyz = PYZ(a.pure) exe = EXE( pyz, a.scripts, a.binaries, a.zipfiles, name=os.path.join('dist', 'test-nestedlaunch0', 'test-nestedlaunch0.exe'), debug=False, strip=False, upx=False, console=1 )
Python
# -*- mode: python -*- __testname__ = 'test2' config['useZLIB'] = 0 a = Analysis(['../support/_mountzlib.py', 'test2.py'], pathex=[], hookspath=['hooks1']) pyz = PYZ(a.pure, level=0) exe = EXE(pyz, a.scripts, exclude_binaries=1, name=os.path.join('build', 'pyi.' + config['target_platform'], __testname__ + '.exe'), icon='test2.ico', version='test2-version.txt', debug=0, console=1) coll = COLLECT( exe, a.binaries - [('zlib','','EXTENSION')], name=os.path.join('dist', __testname__),)
Python
# -*- mode: python -*- __testname__ = 'test9' a = Analysis([os.path.join(HOMEPATH,'support', '_mountzlib.py'), os.path.join(HOMEPATH,'support', 'useUnicode.py'), 'test9.py'], pathex=['.']) pyz = PYZ(a.pure) exe = EXE(pyz, a.scripts, exclude_binaries=1, name=os.path.join('build', 'pyi.' + config['target_platform'], __testname__ + '.exe'), debug=False, strip=False, upx=False, console=True ) coll = COLLECT( exe, a.binaries, strip=False, upx=False, name=os.path.join('dist', __testname__),)
Python
attrs = [('notamodule','')] def hook(mod): import os, sys, marshal other = os.path.join(mod.__path__[0], '../pkg2/__init__.pyc') if os.path.exists(other): co = marshal.loads(open(other,'rb').read()[8:]) else: co = compile(open(other[:-1],'r').read()+'\n', other, 'exec') mod.__init__(mod.__name__, other, co) mod.__path__.append(os.path.join(mod.__path__[0], 'extra')) return mod
Python
# Copyright (C) 2007, Matteo Bertini # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA print "test14 - Used to fail if _xmlplus is installed" import sys if sys.version_info[:2] >= (2, 5): import subprocess import xml.etree.ElementTree as ET print "#"*50 print "xml.etree.ElementTree", dir(ET) print "#"*50 import xml.etree.cElementTree as cET pyexe = open("python_exe.build").readline().strip() out = subprocess.Popen(pyexe + ' -c "import xml.etree.cElementTree as cET; print dir(cET)"', stdout=subprocess.PIPE, shell=True).stdout.read().strip() assert str(dir(cET)) == out, (str(dir(cET)), out) print "test14 DONE" else: print "Python 2.5 test14 skipped"
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- from numpy.core.numeric import dot def main(): print "dot(3, 4):", dot(3, 4) if __name__ == "__main__": main()
Python
#!/usr/bin/env python import sys from ctypes import * def dummy(arg): if sys.platform == "linux2": tct = CDLL("ctypes/testctypes.so") elif sys.platform[:6] == "darwin": tct = CDLL("ctypes/testctypes.dylib") elif sys.platform == "win32": tct = CDLL("ctypes\\testctypes.dll") else: raise NotImplementedError return tct.dummy(arg)
Python