Beispiel #1
0
def create_scaled_ncloth_auto(**kwargs):
	transforms = selected(transforms=True)
	kwargs['shared_transforms'] = transforms
	result = [ScaledNCloth(s, **kwargs) for s in selected() \
		if not isinstance(s, PolyBase)]
	select(result)
	return result
Beispiel #2
0
def create_scaled_ncloth_auto(**kwargs):
    transforms = selected(transforms=True)
    kwargs['shared_transforms'] = transforms
    result = [ScaledNCloth(s, **kwargs) for s in selected() \
     if not isinstance(s, PolyBase)]
    select(result)
    return result
Beispiel #3
0
 def on_handlesToggleButton_clicked(self):
     undoInfo(openChunk=True)
     sel = selected()
     select(self.get_affected_joints())
     toggle(selectHandle=True)
     select(sel)
     undoInfo(closeChunk=True)
Beispiel #4
0
	def on_handlesToggleButton_clicked(self):
		undoInfo(openChunk=True)
		sel = selected()
		select(self.get_affected_joints())
		toggle(selectHandle=True)
		select(sel)
		undoInfo(closeChunk=True)
Beispiel #5
0
	def on_axesToggleButton_clicked(self):
		undoInfo(openChunk=True)
		sel = selected()
		select(self.get_affected_joints())
		toggle(localAxis=True)
		select(sel)
		undoInfo(closeChunk=True)
Beispiel #6
0
 def on_axesToggleButton_clicked(self):
     undoInfo(openChunk=True)
     sel = selected()
     select(self.get_affected_joints())
     toggle(localAxis=True)
     select(sel)
     undoInfo(closeChunk=True)
Beispiel #7
0
def transfer_UVs(sel=selected()):
    source, target = sel
    targets = isinstance(target, Transform) and target.getShapes() or [target]
    for t in targets:
        if t.attr('outMesh').exists() and t.attr('outMesh').listConnections():
            continue
        polyTransfer(t, uvSets=True, alternateObject=source)
    BakeNonDefHistory()
Beispiel #8
0
def transfer_UVs(sel=selected()):
	source, target = sel
	targets = isinstance(target, Transform) and target.getShapes() or [target]
	for t in targets:
		if t.attr('outMesh').exists() and t.attr('outMesh').listConnections():
			continue
		polyTransfer(t, uvSets=True, alternateObject=source)
	BakeNonDefHistory()
Beispiel #9
0
    def on_orientJointsButton_clicked(self):
        undoInfo(openChunk=True)
        sel = selected()

        kwargs = {}
        if self.zeroScaleOrientCB.isChecked():
            kwargs.update({'zeroScaleOrient': True})
        if self.aimAxisNoneRadio.isChecked():
            val = 'none'
        else:
            for i, radio in enumerate(
                (self.aimAxisXRadio, self.aimAxisYRadio, self.aimAxisZRadio)):
                if radio.isChecked():
                    xyz = 'xyz'
                    if self.upAxisNoneRadio.isChecked():
                        val = xyz[i:] + xyz[:i]
                    else:
                        val = str(radio.text()).lower()
                        for up_radio in (self.upAxisXRadio, self.upAxisYRadio,
                                         self.upAxisZRadio):
                            if up_radio.isChecked():
                                val += str(up_radio.text()).lower()
                                break
                        for c in xyz:
                            if c not in val:
                                val += c
                                break
                        sao = self.worldUpYRadio.isChecked() and 'y' \
                         or self.worldUpZRadio.isChecked() and 'z' \
                         or upAxis(query=True, axis=True)
                        sao += self.worldUpReverseCB.isChecked() \
                         and 'down' or 'up'
                        kwargs.update({'secondaryAxisOrient': sao})
                    break

        reverse_aim = self.aimAxisReverseCB.isChecked() \
         and Vector([val[1] == c for c in 'xyz']) * 180 or None
        reverse_up = self.upAxisReverseCB.isChecked() \
         and Vector([val[0] == c for c in 'xyz']) * 180 or None

        for j in self.get_affected_joints():
            if j.numChildren():
                j.orientJoint(val, **kwargs)
            else:
                p = j.getParent()
                if p:
                    delete(orientConstraint(p, j))
                else:
                    self.freeze(j, jointOrient=True)
                if self.zeroScaleOrientCB.isChecked():
                    j.zeroScaleOrient()
            if reverse_aim:
                self.tweak_joint_orientation(1, rotateAxis=reverse_aim)
            if reverse_up:
                self.tweak_joint_orientation(1, rotateAxis=reverse_up)

        select(sel)
        undoInfo(closeChunk=True)
Beispiel #10
0
	def on_orientJointsButton_clicked(self):
		undoInfo(openChunk=True)
		sel = selected()
		
		kwargs = {}
		if self.zeroScaleOrientCB.isChecked():
			kwargs.update({'zeroScaleOrient': True})
		if self.aimAxisNoneRadio.isChecked():
			val = 'none'
		else:
			for i, radio in enumerate((self.aimAxisXRadio,
				self.aimAxisYRadio, self.aimAxisZRadio)):
				if radio.isChecked():
					xyz = 'xyz'
					if self.upAxisNoneRadio.isChecked():
						val = xyz[i:] + xyz[:i]
					else:
						val = str(radio.text()).lower()
						for up_radio in (self.upAxisXRadio,
							self.upAxisYRadio, self.upAxisZRadio):
							if up_radio.isChecked():
								val += str(up_radio.text()).lower()
								break
						for c in xyz:
							if c not in val:
								val += c
								break
						sao = self.worldUpYRadio.isChecked() and 'y' \
							or self.worldUpZRadio.isChecked() and 'z' \
							or upAxis(query=True, axis=True)
						sao += self.worldUpReverseCB.isChecked() \
							and 'down' or 'up'
						kwargs.update({'secondaryAxisOrient': sao})
					break
		
		reverse_aim = self.aimAxisReverseCB.isChecked() \
			and Vector([val[1] == c for c in 'xyz']) * 180 or None
		reverse_up = self.upAxisReverseCB.isChecked() \
			and Vector([val[0] == c for c in 'xyz']) * 180 or None
		
		for j in self.get_affected_joints():
			if j.numChildren():
				j.orientJoint(val, **kwargs)
			else:
				p = j.getParent()
				if p:
					delete(orientConstraint(p, j))
				else:
					self.freeze(j, jointOrient=True)
				if self.zeroScaleOrientCB.isChecked():
					j.zeroScaleOrient()
			if reverse_aim:
				self.tweak_joint_orientation(1, rotateAxis=reverse_aim)
			if reverse_up:
				self.tweak_joint_orientation(1, rotateAxis=reverse_up)
		
		select(sel)
		undoInfo(closeChunk=True)
Beispiel #11
0
    def on_createSplineIKSystemButton_clicked(self):
        self.bottomWidget.show()
        self.topWidget.setEnabled(False)

        dj_chains, output_curves = (), ()
        for root in selected():
            dj_chain = (root, )
            while dj_chain[-1].numChildren():
                dj_chain += (dj_chain[-1].getChildren()[0], )
            dj_chains += (dj_chain, )

            # Assign a hair system to the driver joint chain.
            output_curves += ( \
             curve(p=[dj.getTranslation(space='world').get() \
             for dj in dj_chain]),)

        select(output_curves)
        mel.eval('assignNewHairSystem')
        follicle_curves = selected()

        hs = follicle_curves[0].getParent().getShape().attr('outHair') \
         .outputs()[0]

        [hs.attr(x).set(0) for x in \
         ('drag', 'friction', 'mass', 'gravity', 'dynamicsWeight')]

        hs.attr('startCurveAttract').set(0.25)

        for i, dj_chain in enumerate(dj_chains):
            oc = output_curves[i]
            select(dj_chain + (oc, ))
            SmoothBindSkin()
            bjs = [dj.attr('rotate').outputs()[0].attr('constraintRotateZ') \
             .outputs()[0] for dj in (dj_chain[0], dj_chain[-1])]
            ikHandle(startJoint=bjs[0],
                     endEffector=bjs[1],
                     curve=oc,
                     solver='ikSplineSolver',
                     parentCurve=False,
                     createCurve=False)

        self.topWidget.setEnabled(True)
        self.bottomWidget.hide()
Beispiel #12
0
 def __new__(cls, transform, **kwargs):
     if not isinstance(transform, Transform):
         transform = transform.getParent()
     select(transform, replace=True)
     nClothCreate()
     shape = selected()[0]
     nc_xform = shape.getParent()
     rename(nc_xform, transform.namespace() + 'snCloth' + \
      _util.capitalize(transform.name().split(':')[-1]))
     shape.__class__ = cls
     return shape
Beispiel #13
0
	def __new__(cls, transform, **kwargs):
		if not isinstance(transform, Transform):
			transform = transform.getParent()
		select(transform, replace=True)
		nClothCreate()
		shape = selected()[0]
		nc_xform = shape.getParent()
		rename(nc_xform, transform.namespace() + 'snCloth' + \
			_util.capitalize(transform.name().split(':')[-1]))
		shape.__class__ = cls
		return shape
Beispiel #14
0
	def on_createSplineIKSystemButton_clicked(self):
		self.bottomWidget.show()
		self.topWidget.setEnabled(False)
		
		dj_chains, output_curves = (), ()
		for root in selected():
			dj_chain = (root,)
			while dj_chain[-1].numChildren():
				dj_chain += (dj_chain[-1].getChildren()[0],)
			dj_chains += (dj_chain,)
			
			# Assign a hair system to the driver joint chain.
			output_curves += ( \
				curve(p=[dj.getTranslation(space='world').get() \
				for dj in dj_chain]),)
		
		select(output_curves)
		mel.eval('assignNewHairSystem')
		follicle_curves = selected()
		
		hs = follicle_curves[0].getParent().getShape().attr('outHair') \
			.outputs()[0]
		
		[hs.attr(x).set(0) for x in \
			('drag', 'friction', 'mass', 'gravity', 'dynamicsWeight')]
		
		hs.attr('startCurveAttract').set(0.25)
		
		for i, dj_chain in enumerate(dj_chains):
			oc = output_curves[i]
			select(dj_chain + (oc,))
			SmoothBindSkin()
			bjs = [dj.attr('rotate').outputs()[0].attr('constraintRotateZ') \
				.outputs()[0] for dj in (dj_chain[0], dj_chain[-1])]
			ikHandle(startJoint=bjs[0], endEffector=bjs[1],
				curve=oc, solver='ikSplineSolver',
				parentCurve=False, createCurve=False)
		
		self.topWidget.setEnabled(True)
		self.bottomWidget.hide()
Beispiel #15
0
	def on_loadWeightsButton_clicked(self):
		for mesh in selected():
			sc = mel.findRelatedSkinCluster(mesh)
			if not sc: continue
			sc = ls(sc)[0]
			
			doc = ElementTree(file=path + mesh.nodeName().replace('|', '').replace(':', '.') + '.xml')
			
			influences = [inf.attrib['name'] for inf in doc.findall('//Influence')]
			for i, vtx in enumerate(doc.findall('//Vertex')):
				weights = [(influences[int(w.attrib['influence'])],
					float(w.attrib['value'])) for w in vtx.findall('Weight')]
				skinPercent(sc, '%s.vtx[%d]' % (mesh, i),
					transformValue=weights)
Beispiel #16
0
 def get_affected_nodes(self, dagObjects=True, **kwargs):
     """
     Reads the UI's "Affecting: Hierarchy, Selected, All" radios and
     returns the appropriate selection of nodes.
     """
     if self.affectingAllRadio.isChecked():
         nodes = ls(dagObjects=dagObjects, **kwargs)
     else:
         nodes = selected(dagObjects=dagObjects, **kwargs)
         if nodes and self.affectingHierarchyRadio.isChecked():
             nodes += [n for n in \
                 listRelatives(allDescendents=True, **kwargs) \
                 if n not in nodes]
     return nodes
Beispiel #17
0
	def freeze(self, node, **kwargs):
		
		sel = selected()
		
		kwargs['rotate'] = kwargs.pop('r', kwargs.pop('rotate', True))
		kwargs['scale'] = kwargs.pop('s', kwargs.pop('scale', True))
		skip_locked = kwargs.pop('skip_locked', True)
		
		# Unparent all the joint's children to prevent any locked
		# attribute errors.
		children = dict([(c, c.listRelatives(allParents=True)) \
			for c in node.getChildren(type=['transform', 'joint'])])
		[c.setParent(world=True) for c in children.keys()]
		
		# Unlock any locked rotate or scale attributes, save their
		# values for later and set them to zero for now, so they
		# aren't affected by the freeze.
		atts = {}
		for rs in ('rotate', 'scale'):
			if not kwargs[rs]: continue
			for axis in 'xyz':
				a = node.attr(rs[0] + axis)
				if a.isLocked():
					atts[a] = a.get()
					a.unlock()
					if skip_locked: a.set(0)
		
		# Perform the freeze.
		select(node)
		makeIdentity(apply=True, **kwargs)
		
		# Restore and lock any rotate or scale attributes that
		# were locked before.
		for a, v in atts.items():
			if skip_locked: a.set(v)
			a.lock()
		
		# Restore children to their original parents and delete any
		# automatically-generated parent buffers.
		for c, parents in children.items():
			p = c.getParent()
			c.setParent(parents)
			if p: delete(p)
		
		select(sel)
Beispiel #18
0
    def freeze(self, node, **kwargs):

        sel = selected()

        kwargs['rotate'] = kwargs.pop('r', kwargs.pop('rotate', True))
        kwargs['scale'] = kwargs.pop('s', kwargs.pop('scale', True))
        skip_locked = kwargs.pop('skip_locked', True)

        # Unparent all the joint's children to prevent any locked
        # attribute errors.
        children = dict([(c, c.listRelatives(allParents=True)) \
         for c in node.getChildren(type=['transform', 'joint'])])
        [c.setParent(world=True) for c in children.keys()]

        # Unlock any locked rotate or scale attributes, save their
        # values for later and set them to zero for now, so they
        # aren't affected by the freeze.
        atts = {}
        for rs in ('rotate', 'scale'):
            if not kwargs[rs]: continue
            for axis in 'xyz':
                a = node.attr(rs[0] + axis)
                if a.isLocked():
                    atts[a] = a.get()
                    a.unlock()
                    if skip_locked: a.set(0)

        # Perform the freeze.
        select(node)
        makeIdentity(apply=True, **kwargs)

        # Restore and lock any rotate or scale attributes that
        # were locked before.
        for a, v in atts.items():
            if skip_locked: a.set(v)
            a.lock()

        # Restore children to their original parents and delete any
        # automatically-generated parent buffers.
        for c, parents in children.items():
            p = c.getParent()
            c.setParent(parents)
            if p: delete(p)

        select(sel)
Beispiel #19
0
    def on_loadWeightsButton_clicked(self):
        for mesh in selected():
            sc = mel.findRelatedSkinCluster(mesh)
            if not sc: continue
            sc = ls(sc)[0]

            doc = ElementTree(
                file=path +
                mesh.nodeName().replace('|', '').replace(':', '.') + '.xml')

            influences = [
                inf.attrib['name'] for inf in doc.findall('//Influence')
            ]
            for i, vtx in enumerate(doc.findall('//Vertex')):
                weights = [(influences[int(w.attrib['influence'])],
                            float(w.attrib['value']))
                           for w in vtx.findall('Weight')]
                skinPercent(sc,
                            '%s.vtx[%d]' % (mesh, i),
                            transformValue=weights)
Beispiel #20
0
def snap(*args, **kwargs):
	"""
	Snaps one or more source transforms to a target node's world
	position, rotation and (optionally) the scale as well.
	"""
	
	if not args: args = selected()
	target, sources = args[0], args[1:]
	
	kwargs['space'] = kwargs.pop('space', 'world')
	translate = kwargs.pop('t', kwargs.pop('translate', True))
	rotate = kwargs.pop('r', kwargs.pop('rotate', True))
	scale = kwargs.pop('s', kwargs.pop('scale', False))
	if translate:
		t = target.getTranslation(**kwargs)
		[s.setTranslation(t, **kwargs) for s in sources]
	if rotate:
		r = target.getRotation(**kwargs)
		[s.setRotation(r, **kwargs) for s in sources]
	if scale:
		s = target.getScale(**kwargs)
		[s.setScale(s, **kwargs) for s in sources]
Beispiel #21
0
def snap(*args, **kwargs):
    """
	Snaps one or more source transforms to a target node's world
	position, rotation and (optionally) the scale as well.
	"""

    if not args: args = selected()
    target, sources = args[0], args[1:]

    kwargs['space'] = kwargs.pop('space', 'world')
    translate = kwargs.pop('t', kwargs.pop('translate', True))
    rotate = kwargs.pop('r', kwargs.pop('rotate', True))
    scale = kwargs.pop('s', kwargs.pop('scale', False))
    if translate:
        t = target.getTranslation(**kwargs)
        [s.setTranslation(t, **kwargs) for s in sources]
    if rotate:
        r = target.getRotation(**kwargs)
        [s.setRotation(r, **kwargs) for s in sources]
    if scale:
        s = target.getScale(**kwargs)
        [s.setScale(s, **kwargs) for s in sources]
Beispiel #22
0
    def export_skin_weights(self):

        format, ext = str(self.format.text()), str(self.formatExt.text())
        format = self.name_pat.sub( \
         lambda m: '%(name)' + m.group(1)[1:], format)
        path = Path(self.path.text())

        # Validate selection.
        sel = selected()
        if not sel:
            error('Selection is empty.')

        # Find the skin cluster.
        sc = mel.findRelatedSkinCluster(sel[0])
        skin_cluster = None
        for s in sel:
            sc = mel.findRelatedSkinCluster(s)
            if sc:
                skin_cluster = ls(sc)[0]
                break
        if not skin_cluster:
            error('No skin cluster found.')

        for mesh in sel:

            mesh_element = Element('Mesh', name=mesh)
            xml_tree = ElementTree(mesh_element)

            sc = mel.findRelatedSkinCluster(mesh)
            if not sc: continue
            sc = ls(sc)[0]

            influences = sc.influenceObjects()
            inf_tag = SubElement(mesh_element, 'Influences')
            for i, inf in enumerate(influences):
                SubElement(inf_tag, 'Influence', index=str(i), name=inf)
            #joints = ls(ios, type='joint')
            #if len(joints) < len(ios):
            #	error('Remove non-joint influences before exporting to Massive.')

            # TODO: progress bar

            name = format % dict(name=mesh.name().replace('|', '') \
             .replace(':', '.')) + ext
            with open(path / name, 'w') as f:

                #f.write(os.linesep + '# influences')
                #for i, inf in enumerate(ios):
                #	if inf in influences:
                #		inf_index = influences.index(j)
                #	else:
                #		influences += (inf,)
                #		inf_index = len(influences)
                #f.write('%sdeformer %d %s' % (os.linesep, i, inf))

                #f.write(os.linesep)

                vertices = SubElement(mesh_element, 'Vertices')

                #f.write(os.linesep + '# weights')
                for i, vtx in enumerate(mesh.vtx):
                    vertex = SubElement(vertices,
                                        'Vertex',
                                        pos=str(vtx.getPosition()))
                    #f.write('%s%d: ' % (os.linesep, vi))
                    for ii, inf in enumerate(influences):
                        weight_val = skinPercent(sc,
                                                 '%s.vtx[%d]' % (mesh, i),
                                                 transform=inf,
                                                 query=True)
                        if weight_val:
                            SubElement(vertex,
                                       'Weight',
                                       influence=str(ii),
                                       value=str(weight_val))
                            #f.write(' %d %f' % (ii, weight_val))

                #f.write(os.linesep + ':')
                rough_string = tostring(xml_tree.getroot(), 'utf-8')
                reparsed = minidom.parseString(rough_string)
                f.write(reparsed.toprettyxml(indent='\t'))
Beispiel #23
0
	def export_skin_weights(self):
		
		format, ext = str(self.format.text()), str(self.formatExt.text())
		format = self.name_pat.sub( \
			lambda m: '%(name)' + m.group(1)[1:], format)
		path = Path(self.path.text())
		
		# Validate selection.
		sel = selected()
		if not sel:
			error('Selection is empty.')
		
		# Find the skin cluster.
		sc = mel.findRelatedSkinCluster(sel[0])
		skin_cluster = None
		for s in sel:
			sc = mel.findRelatedSkinCluster(s)
			if sc:
				skin_cluster = ls(sc)[0]
				break
		if not skin_cluster:
			error('No skin cluster found.')
		
		for mesh in sel:
			
			mesh_element = Element('Mesh', name=mesh)
			xml_tree = ElementTree(mesh_element)
			
			sc = mel.findRelatedSkinCluster(mesh)
			if not sc: continue
			sc = ls(sc)[0]
			
			influences = sc.influenceObjects()
			inf_tag = SubElement(mesh_element, 'Influences')
			for i, inf in enumerate(influences):
				SubElement(inf_tag, 'Influence', index=str(i), name=inf)
			#joints = ls(ios, type='joint')
			#if len(joints) < len(ios):
			#	error('Remove non-joint influences before exporting to Massive.')
			
			# TODO: progress bar
			
			name = format % dict(name=mesh.name().replace('|', '') \
				.replace(':', '.')) + ext
			with open(path / name, 'w') as f:
				
				#f.write(os.linesep + '# influences')
				#for i, inf in enumerate(ios):
				#	if inf in influences:
				#		inf_index = influences.index(j)
				#	else:
				#		influences += (inf,)
				#		inf_index = len(influences)
					#f.write('%sdeformer %d %s' % (os.linesep, i, inf))
				
				#f.write(os.linesep)
				
				vertices = SubElement(mesh_element, 'Vertices')
				
				#f.write(os.linesep + '# weights')
				for i, vtx in enumerate(mesh.vtx):
					vertex = SubElement(vertices, 'Vertex', pos=str(vtx.getPosition()))
					#f.write('%s%d: ' % (os.linesep, vi))
					for ii, inf in enumerate(influences):
						weight_val = skinPercent(sc, '%s.vtx[%d]' % (mesh, i),
							transform=inf, query=True)
						if weight_val:
							SubElement(vertex, 'Weight', influence=str(ii),
								value=str(weight_val))
							#f.write(' %d %f' % (ii, weight_val))
				
				
				
				#f.write(os.linesep + ':')
				rough_string = tostring(xml_tree.getroot(), 'utf-8')
				reparsed = minidom.parseString(rough_string)
				f.write(reparsed.toprettyxml(indent='\t'))