Exemple #1
0
    def draw(self, parent=None):

        # Initial hierarchy
        if parent is None:
            self.initialHierarchy()
            parent = self.model

        # Controlers
        for name, controler in self.controlers.items():
            if controler.xml.find("primitive").find("curve") != None:
                rC = controler.xml.find("primitive").find("curve").get("rColor")
                gC = controler.xml.find("primitive").find("curve").get("gColor")
                bC = controler.xml.find("primitive").find("curve").get("bColor")
                ctlColor = [rC, gC, bC]
            else:
                ctlColor = [.25,.35,.25]

            obj = controler.create(self.controlers_org, name, XSIMath.CreateTransform(), ctlColor )
            self.controlers_grp.AddMember(obj)

        # Components
        for name in self.componentsIndex:
            comp_guide = self.components[name]

            if comp_guide.parentComponent is None:
                parent = self.model
            else:
                parent = self.model.FindChild(comp_guide.parentComponent.getName(comp_guide.parentLocalName))
                if not parent:
                    gear.log("Unable to find parent (%s.%s) for guide %s"%(comp_guide.parentComponent .getFullName, comp_guide.parentLocalName, comp_guide.getFullName ))
                    parent = self.model

            comp_guide.drawFromXml(parent)
def gear_GuideToolsUI_import_OnClicked():

    if not os.path.exists(PPG.templateList.Value):
        return

    parent = xsi.Selection(0)
    if parent is not None and not parent.IsClassOf(c.siX3DObjectID):
        gear.log("Invalid Parent Selected", gear.sev_error)
        return

    if parent is not None:
        if parent.Type == "#model":
            target_model = parent
        else:
            target_model = parent.Model

        if not target_model.Properties("options"):
            gear.log("Invalid Parent Selected", gear.sev_error)
            return

    # import guide
    rg = RigGuide()
    model = rg.importFromXml(PPG.templateList.Value)

    if parent is not None:
        for child in model.children:
            if child.Name not in ["controlers_org"]:
                parent.AddChild(child)

        for group in model.Groups:
            if target_model.Groups(group.Name):
                target_model.Groups(group.Name).AddMember(group.Members)

        xsi.DeleteObj(model)
Exemple #3
0
def gear_ApplyZipperOp_Execute():

    if xsi.Selection.Count < 2:
        gear.log("Select 2 curve", gear.sev_error)
        return

    crv_A = xsi.Selection(0)
    crv_B = xsi.Selection(1)

    if crv_A.Type not in ["crvlist"] or crv_B.Type not in ["crvlist"]:
        gear.log("Select 2 curve", gear.sev_error)
        return


    # Apply Operator ----------------------
    op = XSIFactory.CreateObject("gear_ZipperOp")

    op.AddIOPort(crv_A.ActivePrimitive)
    op.AddIOPort(crv_B.ActivePrimitive)

    pStart_fcv = op.Parameters("Start_FCurve").Value
    fcv.drawFCurve(pStart_fcv, [[0,0],[1,1]], c.siLinearKeyInterpolation)

    pSpeed_fcv = op.Parameters("Speed_FCurve").Value
    fcv.drawFCurve(pStart_fcv, [[0,0],[1,1]], c.siLinearKeyInterpolation)

    op.Connect()

    xsi.InspectObj(op)

    return op
Exemple #4
0
def gear_ApplySpinePointAtOp_Execute():

    start_obj = uit.pickSession(c.siGenericObjectFilter, "Pick Start Reference", True)
    if not start_obj:
        return

    end_obj = uit.pickSession(c.siGenericObjectFilter, "Pick End Reference", True)
    if not end_obj:
        return

    count = xsi.Selection.Count+0.0
    operators = []
    for i, sel in enumerate(Application.Selection):

        path_cns = False
        for cns in sel.Kinematics.Constraints:
            if cns.Type in ["crvcns", "pathcns"]:
                path_cns = cns
                break

        if not path_cns:
            gear.log("There is no path or curve constraint on this object : %s"%sel.Name, gear.sev_warning)
            continue

        blend = i/count
        op = aop.spinePointAtOp(cns, start_obj, end_obj, blend)
        operators.append(op)
        
    xsi.InspectObj(operators)
        
    
Exemple #5
0
def gear_SymWeightMapPoints_Execute():

  if xsi.Selection.Count < 2:
      gear.log("Select some points and a weight map", gear.sev_error)
      return

  pntSubComp = xsi.Selection(0)
  wmap = xsi.Selection(1)

  # Check  if input doesn't match
  if pntSubComp.Type not in ["pntSubComponent"] or wmap.Type not in ["wtmap"]:
      gear.log("Invalid selection", gear.sev_error)
      return

  # Get Symmetry Map
  symMap = uti.getSymmetryMap(wmap.Parent3DObject)
  if not symMap:
      return

  # Get Arrays
  points = pntSubComp.SubComponent.ElementArray
  weights = [w for w in wmap.Elements.Array[0]]
  sym_array = symMap.Elements.Array

  # Process
  for i in points:
      weights[int(sym_array[0][i])] = weights[i]

  wmap.Elements.Array = weights
Exemple #6
0
    def draw(self, parent=None):

        # Initial hierarchy
        if parent is None:
            self.initialHierarchy()
            parent = self.model

        # Controlers
        for name, controler in self.controlers.items():
            obj = controler.create(self.controlers_org, name, XSIMath.CreateTransform(), [0.25, 0.35, 0.25])
            self.controlers_grp.AddMember(obj)

        # Components
        for name in self.componentsIndex:
            comp_guide = self.components[name]

            if comp_guide.parentComponent is None:
                parent = self.model
            else:
                parent = self.model.FindChild(comp_guide.parentComponent.getName(comp_guide.parentLocalName))
                if not parent:
                    gear.log(
                        "Unable to find parent (%s.%s) for guide %s"
                        % (comp_guide.parentComponent.getFullName, comp_guide.parentLocalName, comp_guide.getFullName)
                    )
                    parent = self.model

            comp_guide.drawFromXml(parent)
Exemple #7
0
def gear_DrawCnsCurve_Cubic_Execute():

    if xsi.Selection.Count < 2:
        gear.log("Select enough centers", gear.sev_error)
        return

    cur.addCnsCurve(xsi.ActiveSceneRoot, "crvCns", xsi.Selection, False, 3)
Exemple #8
0
def exportSkin(path, objects, compression=False):

    xml_doc = etree.Element("skin")
    xml_doc.set("user", getpass.getuser())
    xml_doc.set("date", str(datetime.datetime.now()))
    xml_doc.set("version", str(xsixmldom.VERSION))

    # -----------------------------------------------------
    for obj in objects:

        envelope_op = ope.getOperatorFromStack(obj, "envelopop")
        if not envelope_op:
            gear.log("%s has no envelope skipped"%obj.Name, gear.sev_warning)
            continue

        xsixmldom.setOptions(X3DObject_children=False,
                                    X3DObject_primitive=False,
                                    X3DObject_kinematics=False,
                                    X3DObject_properties=[],
                                    Geometry_operators=["envelopop"],
                                    Compression=compression)
        xObject = xsixmldom.getObject(obj)
        xml_doc.append(xObject.xml)

    # -----------------------------------------------------
    # Save to file
    xmldom.indent(xml_doc)

    tree = etree.ElementTree(xml_doc)
    tree.write(path)

    return True
Exemple #9
0
def keyMulti(in_mousebutton, in_keymodifier, object_names, exclude=[]):

    # Right click - Do nothing
    if in_mousebutton == 2:
        return

    model = getModel()

    # Get objects
    for name in object_names:
        children = model.FindChildren(name)
        if children.Count:
            controlers.AddItems(children)

    # Remove objects
    # As we can yuse symbol such as '*' in the name list we might need to filter the result
    for name in exclude:
        if model.Name+"."+name in controlers.GetAsText().split(","):
            controlers.RemoveItems(model.Name+"."+name)

    if not controlers.Count:
        gear.log("Can't Find Controlers : "+",".join(object_names), gear.sev_siError)
        return

    ani.setKey(controlers)
Exemple #10
0
def gear_ImportEnvelope_Execute():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    # -----------------------------------------------------
    # Getting the file path
    path = uit.fileBrowser("Import Envelope", xsi.ActiveProject2.OriginPath, "", ["xml"], False)
    if not path:
        return

    # -----------------------------------------------------
    xml_objs = io.getObjectDefinitions(path, xsi.Selection, True)
    if not xml_objs:
        return

    # -----------------------------------------------------
    for sel in xsi.Selection:

        if sel.Type in ["pntSubComponent"]:
            obj = sel.SubComponent.Parent3DObject
            pnt_selection = sel.SubComponent.ElementArray
        else:
            obj = sel
            pnt_selection = None

        if obj.Name not in xml_objs.keys():
            continue

        io.importEnvelope(xml_objs[obj.Name], obj, pnt_selection)
Exemple #11
0
def mirrorShapeKey(shape):

    # Get Symmetry Map
    mesh = shape.Parent3DObject
    symmetry_map = uti.getSymmetryMap(mesh)
    if not symmetry_map:
        gear.log("There is no symmetry map available on this mesh", gear.sev_warning)
        return

    cls = shape.Parent
    shape_tuple = shape.Elements.Array
    symmetry_array = symmetry_map.Elements.Array

    shape_array = [0] * len(shape_tuple[0])*3

    # Process
    for iPntIndex in cls.Elements:

        iSymIndex = int(symmetry_array[0][iPntIndex])

        shape_array[iSymIndex*3+0] = - shape_tuple[0][iPntIndex]
        shape_array[iSymIndex*3+1] = shape_tuple[1][iPntIndex]
        shape_array[iSymIndex*3+2] = shape_tuple[2][iPntIndex]

    duplicate_shape = xsi.StoreShapeKey(cls, shape.Name+"_Mirror", c.siShapeObjectReferenceMode, 1, None, None, c.siShapeContentSecondaryShape, True)
    duplicate_shape.Elements.Array = shape_array
    xsi.ApplyShapeKey(duplicate_shape, None, None, 100, None, None, None, 2)
    xsi.FreezeObj(duplicate_shape)

    return duplicate_shape
Exemple #12
0
def gear_crvLenInfo_Execute():

    if not xsi.Selection.Count and xsi.Selection(0).Type == "crvlist":
        gear.log("No selection or first selected object not a crvlist",
        gear.sev_error)
        return

    crv = xsi.Selection(0)
    prop = xsi.gear_PSet_Apply(crv, "Length_Info", False, False )
    pLength = prop.AddParameter3( "Length", c.siDouble, 0, -1000000, 1000000 )
    pOriginalLength = prop.AddParameter3( "Original_Length", c.siDouble, 0, -1000000, 1000000, False, True )
    pLengthRatio = prop.AddParameter3( "Length Ratio", c.siDouble, 0, -1000000, 1000000 )

    layout = r"""layout.AddTab('Length_Info');\
        layout.AddGroup('Default Layout');\
        item = layout.AddItem('Length', 'Length', None);\
        item = layout.AddItem('Original_Length', 'Original_Length', None);\
        item = layout.AddItem('Length_Ratio', 'Length_Ratio', None);\
        layout.EndGroup()"""

    prop.Parameters("layout").Value = layout
    aop.sn_curvelength_op(pLength.FullName, crv)
    pOriginalLength.Value = pLength.Value
    pLengthRatio.AddExpression( pLength.FullName +  "/" + pOriginalLength.FullName)
    xsi.InspectObj(prop)
Exemple #13
0
def gear_SmoothWeightMapPoints_Execute():

    if xsi.Selection.Count < 2:
        gear.log("Select some points and a weight map", gear.sev_error)
        return

    pntSubComp = xsi.Selection(0)
    wmap = xsi.Selection(1)

    # Check  if input doesn't match
    if pntSubComp.Type not in ["pntSubComponent"] or wmap.Type not in ["wtmap"]:
        gear.log("Invalid selection", gear.sev_error)
        return

    # Get Arrays
    clsElements = wmap.Parent.Elements
    points = [clsElements.FindIndex(i) for i in pntSubComp.SubComponent.ElementArray if clsElements.FindIndex(i) != -1]

    obj = pntSubComp.SubComponent.Parent3DObject
    cls = obj.ActivePrimitive.Geometry.AddCluster(c.siVertexCluster, "gear_SmoothWeightMapPointsOp_Cls", points )

    # Apply Operator
    op = XSIFactory.CreateObject("gear_SmoothWeightMapPointsOp")

    op.AddIOPort(wmap)
    op.AddInputPort(wmap.Parent3DObject.ActivePrimitive)
    op.AddInputPort(cls)

    op.Connect(None, c.siConstructionModeModeling)

    xsi.InspectObj(op)
Exemple #14
0
def normalizeWeights(envelope_op, points):

    mesh = envelope_op.Parent3DObject
    deformer_count = envelope_op.Deformers.Count
    point_count = mesh.ActivePrimitive.Geometry.Points.Count
    weights_tuple = envelope_op.Weights.Array
    weights = [weights_tuple[j][i] for i in range(len(weights_tuple[0])) for j in range(len(weights_tuple))]

    for point_index in points:

        point_weights = weights[point_index*deformer_count:(point_index+1)*deformer_count]
        total_weight = sum(point_weights)

        if total_weight > 0:
            point_weights = normalizeArray(point_weights)
        else:
            point_weights = normalizeToClosestPoint(envelope_op, weights, point_index)

        if not point_weights:
            gear.log("Unable to normalize " + envelope_op.FullName, gear.sev_warning)
            return False

        # rebuilt weights array
        for deformer_index in range(deformer_count):
            weights[point_index*deformer_count + deformer_index] = point_weights[deformer_index]

    envelope_op.Weights.Array = weights

    return True
Exemple #15
0
def normalizeToClosestPoint(envelope_op, weights, point_index):

    mesh = envelope_op.Parent3DObject
    deformer_count = envelope_op.Deformers.Count
    point_count = mesh.ActivePrimitive.Geometry.Points.Count

    vertex = mesh.ActivePrimitive.Geometry.Points(point_index)

    point_weights = [0] * deformer_count

    distance = 1
    neighbor_count = vertex.NeighborVertices(1).Count

    while neighbor_count < point_count - 1:

        neighbor_vertices = vertex.NeighborVertices(distance)
        neighbor_count = neighbor_vertices.Count

        for neighbor_vertex in neighbor_vertices:
             neighbor_index = neighbor_vertex.Index
             for deformer_index in range(deformer_count):
                point_weights[deformer_index] += (weights[ neighbor_index*deformer_count + deformer_index ]) / neighbor_vertices.Count

        if sum(point_weights) != 0:
            point_weights = normalizeArray(point_weights)
            return point_weights

        distance += 1

    gear.log("Normalize to Closest Point aborded at distance "+ str(distance), c.siWarning)
    return False
Exemple #16
0
def normalizeToDeformer(envelope_op, deformers, points=None, threshold=1E-6):

    mesh = envelope_op.Parent3DObject
    deformer_count = envelope_op.Deformers.Count
    point_count = mesh.ActivePrimitive.Geometry.Points.Count
    weights_tuple = envelope_op.Weights.Array
    weights = [weights_tuple[j][i] for i in range(len(weights_tuple[0])) for j in range(len(weights_tuple))]

    # Get Deformers Index
    deformers_index = [getDeformerIndex(envelope_op, obj) for obj in deformers if isDeformer(envelope_op, obj)]
    if not deformers_index:
        gear.log("No deformers to add weights", gear.sev_error)
        return False

    if points is None:
        points = range(point_count)

    for point_index in points:

        total_weights = 0
        for deformer_index, deformer in enumerate(envelope_op.Deformers):
            total_weights += weights[point_index*deformer_count + deformer_index]

        if total_weights < (100 - threshold):
            for deformer_index in deformers_index:
                weights[point_index*deformer_count + deformer_index] += (100 - total_weights) / len(deformers_index)

    # Apply new Weights
    envelope_op.Weights.Array = weights

    return True
Exemple #17
0
    def pickPositions(self):

        refs = []

        for name in self.pick_transform:

            if "#" in name:
                i = 0
                while not self.minmax[name].max > 0 or i < self.minmax[name].max:
                    localName = string.replaceSharpWithPadding(name, i)

                    position = uit.pickPosition("Pick %s position"%localName, False)
                    if not position:
                        break
                    self.tra[localName] = tra.getTransformFromPosition(position)
                    refs.append(self.drawRef(self.tra[localName]))

                    i += 1

                if i < self.minmax[name].min:
                    gear.log("Minimum of object requiered for "+name+" hasn't been reached", gear.sev_warning)
                    xsi.DeleteObj(refs)
                    return False
            else:
                position = uit.pickPosition("Pick %s position"%name, True)
                if not position:
                    xsi.DeleteObj(refs)
                    return False

                self.tra[name] = tra.getTransformFromPosition(position)
                refs.append(self.drawRef(self.tra[name]))

        xsi.DeleteObj(refs)

        return True
Exemple #18
0
def gear_MirrorPose_Execute():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    ani.mirror(xsi.Selection)
Exemple #19
0
def gear_DrawAxis_Execute():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    for sel in xsi.Selection:
        pri.drawAxis(sel, 1)
Exemple #20
0
    def getAsXml(self):

        if self.obj is None:
            gear.log("Can't export primitive to xml", gear.sev_error)
            return

        xsixmldom.setOptions(X3DObject_children=False, X3DObject_properties=[], X3DObject_kinematics=False, Geometry_stack=False)
        return xsixmldom.getObject(self.obj).xml
Exemple #21
0
def logMatrix3(m, msg="matrix3"):

    s = msg + " : \n"\
	+"| %s , %s , %s |\n"%(m.Value(0,0), m.Value(0,1), m.Value(0,2))\
	+"| %s , %s , %s |\n"%(m.Value(1,0), m.Value(1,1), m.Value(1,2))\
	+"| %s , %s , %s |"%(m.Value(2,0), m.Value(2,1), m.Value(2,2))

    gear.log(s)
Exemple #22
0
def gear_AddNullChild_Execute():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    for sel in xsi.Selection:
        pri.addNull(sel, sel.Name+"_child", sel.Kinematics.Global.Transform)
Exemple #23
0
    def isValidModel(self, model):

        self.model = model
        self.options = self.model.Properties("options")
        if not self.options:
            gear.log("Invalid parent selected", gear.sev_error)
            return False

        return True
Exemple #24
0
def gear_reloadModules(ctxt):

    errors = gear.reloadModule("gear", False)
    if errors:
        for error in errors:
            for msg in error:
                gear.log(msg, gear.sev_error)
    else:
        gear.log("GEAR MODULES RELOADED SUCCESSFULLY")
Exemple #25
0
def gear_MoveShapeKey_Execute():

    if not xsi.Selection.Count:
        gear.log("Select shape keys", gear.sev_error)
        return

    shapes = [shape for shape in xsi.Selection if shape.Type in ["clskey"]]
    if not shapes:
        return

    cls = shapes[0].Parent
    geo = cls.Parent
    clusters = geo.Clusters

    # UI
    prop = xsi.ActiveSceneRoot.AddProperty("Custom_parameter_list", False, "gear_MoveShapeKey")
    pDuplicate = prop.AddParameter3("duplicate", c.siBool, True, None, None, False, False)
    pClusters = prop.AddParameter3("clusters", c.siInt4, -1, 0, clusters.Count-1, False, False)

    clustersItems = ["New Cluster", -1]
    for i, cls in enumerate(clusters):
        clustersItems.append(cls.Name)
        clustersItems.append(i)

    layout = prop.PPGLayout
    layout.Clear()
    layout.AddTab("General")
    layout.AddGroup("Move Shape Key Option")
    item = layout.AddItem(pDuplicate.ScriptName, "Duplicate")
    item = layout.AddEnumControl(pClusters.ScriptName, clustersItems, "Move to", c.siControlCombo)
    layout.EndGroup()

    # Inspect
    rtn = xsi.InspectObj(prop, "", "Move Shape Key", c.siModal, False)

    # Return values
    duplicate = pDuplicate.Value
    cluster_index = pClusters.Value

    xsi.DeleteObj(prop)

    if rtn:
         return

    # Create or get target cluster
    if cluster_index == -1:
        target_cluster = geo.AddCluster(c.siVertexCluster, cls.Name+"_Copy", cls.Elements.Array)
    else:
        target_cluster = clusters(cluster_index)

    # Duplicate Shape key
    for shape in shapes:
        sha.duplicateShapeKey(shape, target_cluster)

    # Delete original
    if not duplicate:
        xsi.DeleteObj(shapes)
Exemple #26
0
    def connect(self):

        if self.settings["connector"] not in self.connections.keys():
            gear.log("Unable to connect object", gear.sev_error)
            return False

        self.connections[self.settings["connector"]]()

        return True
Exemple #27
0
def gear_AddNullParent_Execute():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    for sel in xsi.Selection:
        null = pri.addNull(sel.Parent3DObject, sel.Name+"_parent", sel.Kinematics.Global.Transform)
        null.AddChild(sel)
Exemple #28
0
def logMatrix4(m, msg="matrix4"):

    s = msg + " : \n"\
	+"| %s , %s , %s , %s |\n"%(m.Value(0,0), m.Value(0,1), m.Value(0,2), m.Value(0,3))\
	+"| %s , %s , %s , %s |\n"%(m.Value(1,0), m.Value(1,1), m.Value(1,2), m.Value(1,3))\
	+"| %s , %s , %s , %s |\n"%(m.Value(2,0), m.Value(2,1), m.Value(2,2), m.Value(2,3))\
	+"| %s , %s , %s , %s |"%(m.Value(3,0), m.Value(3,1), m.Value(3,2), m.Value(3,3))

    gear.log(s)
Exemple #29
0
    def __init__(self, root=None, name="chain"):

        if root.type != "root":
            gear.log( "chain Init : Invalid object specified", gear.sev_warning )
            return False

        self.root = root

        self.setDisplay()
        self.setName(name)
Exemple #30
0
def gear_GuideToolsUI_draw_OnClicked():

    if not PPG.componentList.Value:
        gear.log("There is no component selected in the list", gear.sev_error)
        return

    compType = PPG.componentList.Value

    rg = RigGuide()
    g = rg.drawNewComponent(xsi.Selection(0), compType)
Exemple #31
0
def gear_Select5BranchesStars_Execute():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    objects = [obj for obj in xsi.Selection if obj.Type in ["polymsh"]]

    if not objects:
        gear.log("Invalid Selection", gear.sev_error)
        return

    xsi.DeselectAll()

    for obj in objects:

        stars = geo.getStars(obj, 5, False)

        if stars:
            gear.log("There is " + str(len(stars)) +
                     " stars with 5 branches on " + obj.FullName)
            xsi.AddToSelection(obj.FullName + ".pnt" + str(stars), "", True)
        else:
            gear.log("There is no stars with 5 branches on " + obj.FullName)
Exemple #32
0
def gear_SelectWeightMapPoints_Execute():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    wmap = xsi.Selection(0)
    if wmap.Type not in ["wtmap"]:
        gear.log("Select a Weight Map", gear.sev_error)
        return

    obj = wmap.Parent3DObject
    points = wei.getWeightMapPoints(wmap)

    if points:
        xsi.SelectGeometryComponents(obj.FullName + ".pnt" + str(points))
    else:
        gear.log("There is no points in the Weght map", gear.sev_warning)
Exemple #33
0
def gear_RebuildEnvelope_Execute():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    for mesh in xsi.Selection:

        if mesh.Type not in ["polymsh", "surfmsh", "crvlist"]:
            gear.log("Invalid selection", gear.sev_error)
            continue

        # Get Envelope from object
        envelope_op = ope.getOperatorFromStack(mesh, "envelopop")
        if not envelope_op:
            gear.log("There is no envelope on selected mesh", c.siWarning)
            continue

        env.rebuiltEnvelope(envelope_op)
Exemple #34
0
def gear_MatchGeometry_Execute():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    target = xsi.Selection(0)
    if target.Type not in ["pntSubComponent", "polymsh", "surfmsh", "crvlist"]:
        gear.log("Invalid Selection, select a geometry or a point selection", gear.sev_error)
        return

    # Get reference
    source = uit.pickSession(c.siGenericObjectFilter, "Pick Source Geometry")
    if not source:
        return

    # Get cluster
    if target.Type == "pntSubComponent":
        obj = target.SubComponent.Parent3DObject
        cls = obj.ActivePrimitive.Geometry.AddCluster(c.siVertexCluster, "gear_MatchGeometryOp_cls", target.SubComponent.ElementArray)
    else:
        obj = target
        cls = obj.ActivePrimitive.Geometry.AddCluster(c.siVertexCluster, "gear_MatchGeometryOp_cls")

    if source.Type != obj.Type:
        gear.log("Invalid Selection", gear.sev_error)
        xsi.DeleteObj(cls)
        return

    # Apply Operator
    op = XSIFactory.CreateObject("gear_MatchGeometryOp")

    op.AddIOPort(obj.ActivePrimitive)
    op.AddInputPort(source.ActivePrimitive)
    op.AddInputPort(cls)
    op.AddInputPort(obj.Kinematics.Global)
    op.AddInputPort(source.Kinematics.Global)

    op.Connect()

    xsi.InspectObj(op)

    return op
Exemple #35
0
def gear_CreateSymmetryMappingTemplate_Execute():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    mesh = xsi.Selection(0)

    # Check input
    if mesh.Type not in ["polymsh", "crvlist", "surfmsh"]:
        gear.log("Invalid selection", gear.sev_error)
        return

    # Get Envelope
    envelope_op = ope.getOperatorFromStack(mesh, "envelopop")
    if not envelope_op:
        gear.log("There's no envelope on " + mesh.Fullname, gear.sev_error)
        return

    env.createSymmetryMappingTemplate(envelope_op.Deformers)
Exemple #36
0
def gear_CurveResampler_Execute():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    for curve in xsi.Selection:

        if curve.Type not in ["crvlist"]:
            gear.log("Invalid selection", gear.sev_warning)
            continue

        if curve.ActivePrimitive.Geometry.Curves.Count > 1:
            gear.log("Curve Resampler works only with single curve", gear.sev_warning)
            continue

        # Apply Operator
        op = cur.applyCurveResamplerOp(curve)

    xsi.InspectObj(op)
Exemple #37
0
def gear_SelectShapePoints_Execute():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    shape = xsi.Selection(0)

    # Check input
    if shape.Type not in ["clskey"]:
        gear.log("Invalid selection", gear.sev_error)
        return

    points = sha.getShapePoints(shape)

    if not points:
        gear.log("There is no point deformed by this shape", gear.sev_warning)
        return

    mesh = shape.Parent3DObject
    xsi.SelectGeometryComponents(mesh.FullName + ".pnt" + str(points))
Exemple #38
0
def gear_MatchShapeKey_Execute():

    if not xsi.Selection.Count:
        gear.log("Select shape key", gear.sev_error)
        return

    target_shape = xsi.Selection(0)
    if target_shape.Type not in ["clskey"]:
        gear.log("Invalid selection", gear.sev_error)
        return

    source_shape = uit.pickSession(c.siPropertyFilter, "Pick Source Shape",
                                   True)
    if not source_shape:
        return

    if source_shape.Type not in ["clskey"]:
        gear.log("Invalid selection", gear.sev_error)
        return

    sha.matchShapeKey(target_shape, source_shape)
Exemple #39
0
def gear_AverageMirrorWeights_Execute():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    sel = xsi.Selection(0)

    # Check input
    if sel.Type not in ["pntSubComponent"]:
        gear.log("Invalid selection", gear.sev_error)
        return

    mesh = sel.SubComponent.Parent3DObject
    envelope_op = ope.getOperatorFromStack(mesh, "envelopop")
    if not envelope_op:
        gear.log("There is no envelope on selected mesh", gear.sev_error)
        return

    points = sel.SubComponent.ElementArray

    # Process
    env.averageMirrorWeights(envelope_op, points)
Exemple #40
0
def gear_MoveShapeKey_Execute():

    if not xsi.Selection.Count:
        gear.log("Select shape keys", gear.sev_error)
        return

    shapes = [shape for shape in xsi.Selection if shape.Type in ["clskey"]]
    if not shapes:
        return

    cls = shapes[0].Parent
    geo = cls.Parent
    clusters = geo.Clusters

    # UI
    prop = xsi.ActiveSceneRoot.AddProperty("Custom_parameter_list", False,
                                           "gear_MoveShapeKey")
    pDuplicate = prop.AddParameter3("duplicate", c.siBool, True, None, None,
                                    False, False)
    pClusters = prop.AddParameter3("clusters", c.siInt4, -1, 0,
                                   clusters.Count - 1, False, False)

    clustersItems = ["New Cluster", -1]
    for i, cls in enumerate(clusters):
        clustersItems.append(cls.Name)
        clustersItems.append(i)

    layout = prop.PPGLayout
    layout.Clear()
    layout.AddTab("General")
    layout.AddGroup("Move Shape Key Option")
    item = layout.AddItem(pDuplicate.ScriptName, "Duplicate")
    item = layout.AddEnumControl(pClusters.ScriptName, clustersItems,
                                 "Move to", c.siControlCombo)
    layout.EndGroup()

    # Inspect
    rtn = xsi.InspectObj(prop, "", "Move Shape Key", c.siModal, False)

    # Return values
    duplicate = pDuplicate.Value
    cluster_index = pClusters.Value

    xsi.DeleteObj(prop)

    if rtn:
        return

    # Create or get target cluster
    if cluster_index == -1:
        target_cluster = geo.AddCluster(c.siVertexCluster, cls.Name + "_Copy",
                                        cls.Elements.Array)
    else:
        target_cluster = clusters(cluster_index)

    # Duplicate Shape key
    for shape in shapes:
        sha.duplicateShapeKey(shape, target_cluster)

    # Delete original
    if not duplicate:
        xsi.DeleteObj(shapes)
Exemple #41
0
def gear_PSet_OnInit():

    prop = PPG.Inspected(0)
    layout = PPG.PPGLayout

    # Define the Logic -----------------------------------------------
    path = plu.getPluginFullPath("gear_PSet")
    f = open(path)

    layout.Logic = f.read()
    layout.Logic += PPG.Logic.Value

    # Define Layout --------------------------------------------------
    layout.Clear()

    baseParameters = ["layout", "logic", "debug"]

    # If there is no parameters and debug mode is False
    if not PPG.debug.Value and prop.Parameters.Count == len(baseParameters):
        layout.AddStaticText("No Parameter to display")

    # If Debug Mode is True or no layout has been define
    elif PPG.debug.Value or PPG.layout.Value == "":

        layout.AddTab("DEBUG LAYOUT")

        layout.AddGroup()
        layout.AddRow()
        layout.AddButton("refresh", "Refresh")
        layout.AddSpacer()
        layout.AddButton("hide", "Hide Me")
        layout.AddButton("generateLayout", "Generate Layout")
        layout.EndRow()
        layout.EndGroup()

        layout.AddGroup("Layout")
        item = layout.AddString("layout", "", True, 300)
        item.SetAttribute(c.siUINoLabel, True)
        layout.EndGroup()

        layout.AddTab("DEBUG LOGIC")

        layout.AddGroup()
        layout.AddRow()
        layout.AddButton("refresh", "Refresh")
        layout.AddSpacer()
        layout.AddButton("hide", "Hide Me")
        layout.AddButton("generateLayout", "Generate Layout")
        layout.EndRow()
        layout.EndGroup()

        layout.AddGroup("Logic")
        item = layout.AddString("logic", "", True, 300)
        item.SetAttribute(c.siUINoLabel, True)
        layout.EndGroup()

        # If there is no layout define we still display the parameter with a default layout
        if PPG.layout.Value == "":
            drawDefaultLayout(prop, baseParameters)

    # Add custom Layout -----------------------------------------
    layoutcode = PPG.layout.Value.replace("\r\n", "\r\n    ")
    code = "def readLayout(layout, PPG):\r\n    " + layoutcode + "\r\n    return\r\n"

    try:
        xsi.ExecuteScriptCode(code, "Python", "readLayout", [layout, PPG])
    except Exception, e:

        gear.log("INVALID LAYOUT DETECTED ========================",
                 gear.sev_error)
        for arg in e.args:
            gear.log(arg, gear.sev_error)

        gear.log("LAYOUT CODE ====================================",
                 gear.sev_error)
        gear.log("\r\n" + code, gear.sev_error)
        gear.log("END OF LAYOUT CODE =============================",
                 gear.sev_error)

        drawDefaultLayout(prop, baseParameters)
Exemple #42
0
def pruneWeights(envelope_op,
                 points=None,
                 threshold=.1,
                 remove=False,
                 showPBar=False):

    # Get weights array
    mesh = envelope_op.Parent3DObject
    point_count = mesh.ActivePrimitive.Geometry.Points.Count
    weights_tuple = envelope_op.Weights.Array
    weights = [
        weights_tuple[j][i] for i in range(len(weights_tuple[0]))
        for j in range(len(weights_tuple))
    ]

    deformer_count = envelope_op.Deformers.Count
    used_deformers = XSIFactory.CreateObject("XSI.Collection")
    used_deformers.Unique = True

    if points is None:
        points = range(point_count)

    if showPBar:
        pbar = uit.progressBar(
            len(points), 1,
            str(len(points)) + " points to prune on : " + mesh.Name, "0",
            False)

    # Prune Weights
    pointsToNormalize = []
    for point_index in points:

        if showPBar:
            pbar.StatusText = point_index

        for deformer_index, deformer in enumerate(envelope_op.Deformers):

            if weights[point_index * deformer_count +
                       deformer_index] <= threshold:
                weights[point_index * deformer_count + deformer_index] = 0
                if not point_index in pointsToNormalize:
                    pointsToNormalize.append(point_index)
            else:
                used_deformers.Add(deformer)

        if showPBar:
            pbar.Increment()

    if showPBar:
        pbar.Visible = False

    # Normalize points
    envelope_op.Weights.Array = weights
    normalizeWeights(envelope_op, pointsToNormalize)
    freezeEnvelope(envelope_op)

    # Rebuilt Envelope ------------------------------------------------
    # If True, we rebuilt the envelope a first time without the unused deformers
    if remove:

        gear.log("There is " +
                 str(envelope_op.Deformers.Count - used_deformers.Count) +
                 " deformers that will be removed")

        path = XSIUtils.ResolvePath("Temp")
        preset_name = mesh.Name + "_Weights"

        env_prop = envelope_op.PortAt(4, 0, 0).Target2
        xsi.SavePreset(env_prop, preset_name, path, None, 1, None, None)
        xsi.RemoveFlexEnv(mesh)

        envelope_op = mesh.ApplyEnvelope(used_deformers)
        env_prop = envelope_op.PortAt(4, 0, 0).Target2

        xsi.LoadPreset(path + "/" + preset_name, env_prop)

    # Rebuilt the envelope to get the correct colors and normalisation warning
    envelope_op = rebuiltEnvelope(envelope_op)

    return envelope_op
Exemple #43
0
    def getBiNormalFromPos(self, pos):
        if len(pos) < 3:
            gear.log("%s : Not enough references to define binormal"%self.fullName, gear.sev_error)

        return vec.getPlaneBiNormal(pos[0], pos[1], pos[2])
Exemple #44
0
def gear_SelectUnnormalizedPoints_Execute():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    mesh = xsi.Selection(0)

    # Check input
    if mesh.Type not in ["polymsh", "crvlist", "surfmsh"]:
        gear.log("Invalid selection", gear.sev_error)
        return

    # Get Envelope
    envelope_op = ope.getOperatorFromStack(mesh, "envelopop")
    if not envelope_op:
        gear.log("There's no envelope on " + mesh.Fullname, gear.sev_error)
        return

    unNormPntId = env.getUnnormalizedPoints(envelope_op)

    # Select Pnt
    if unNormPntId:
        gear.log("There is " + str(len(unNormPntId)) +
                 " unnormalized point(s)")
        gear.log(mesh.FullName + ".pnt" + str(unNormPntId))
        xsi.SelectGeometryComponents(mesh.FullName + ".pnt" + str(unNormPntId))
    else:
        gear.log("There is no unnormalized point", gear.sev_warning)
Exemple #45
0
def mirror(controlers=xsi.Selection,
           animation=False,
           frame_offset=0,
           considerTime=False,
           frame_in=0,
           frame_out=0):

    if not animation:
        source_type = 1
        considerTime = False
        frame_offset = 0
    else:
        source_type = 6

    params = getKeyableParameters(controlers)

    # Avoid having the parameter and its proxy in the collection
    # Curiosly, XSI can store the fcurves of the parameter and its proxy separatly
    # We get weird result when applying the action
    key_params = XSIFactory.CreateObject("XSI.Collection")
    key_params.Unique = True
    for param in params:
        if param.Type == "ProxyParameter":
            key_params.Add(param.MasterParameter)
        else:
            key_params.Add(param)

    if not key_params.Count:
        gear.log("No Keyable Parameter on Selection", gear.sev_error)
        return

    # Get all keys if considerTime is False
    if not considerTime and animation:
        frame_in, frame_out = fcu.getFirstAndLastKey(controlers)

    # Get Connexion Map --------------------
    model = controlers(0).Model
    cnx_prop = model.Properties(MIRROR_PROP_NAME)
    if not cnx_prop:
        gear.log("There is no Mirror Cnx Template on this model",
                 gear.sev_error)
        return

    cnx_grid = cnx_prop.Parameters("CnxGridHidden").Value
    connections = par.getDictFromGridData(cnx_grid)

    # Actions ------------------------------
    # Store the Action
    if model.Sources("Temp_MirrorAction"):
        xsi.DeleteObj(model.Sources("Temp_MirrorAction"))

    action = xsi.StoreAction(model, key_params, source_type,
                             "Temp_MirrorAction", False, frame_in, frame_out,
                             considerTime, False, False, False)

    # Edit the stored Action
    for item in action.SourceItems:

        # skip sourceItems if not listed in the CnxMap
        if item.Target not in connections:
            continue

        # Change the target to mirror action
        target = connections[item.Target]
        item.Target = target[0]

        # Inverse the value of fcurve if necessary
        # The string version is to keep compatibility with previous version of XSI
        # When the gridata was only returning string
        if target[1] in [True, "True"]:
            invertSource(item.Source)

    xsi.ApplyAction(action, model, True, frame_in + frame_offset,
                    frame_out + frame_offset, False)
    xsi.DeleteObj(action)

    return
Exemple #46
0
    def setFromHierarchy(self, root):

        self.root = root
        self.model = self.root.Model

        # ---------------------------------------------------
        # First check and set the settings
        self.settings = self.root.Properties("settings")
        if not self.settings:
            gear.log(
                "Can't find the 'setting' property. %s is not a proper guide."
                % self.root.Name, gear.sev_error)
            self.valid = False
            return

        self.setParamDefValuesFromProperty(self.settings)

        # ---------------------------------------------------
        # Then get the objects
        for name in self.save_transform:
            if "#" in name:
                i = 0
                while not self.minmax[name].max > 0 or i < self.minmax[
                        name].max:
                    localName = string.replaceSharpWithPadding(name, i)

                    obj = self.model.FindChild(self.getName(localName))
                    if not obj:
                        break

                    self.tra[localName] = obj.Kinematics.Global.Transform
                    self.atra.append(obj.Kinematics.Global.Transform)
                    self.pos[
                        localName] = obj.Kinematics.Global.Transform.Translation
                    self.apos.append(
                        obj.Kinematics.Global.Transform.Translation)

                    i += 1

                if i < self.minmax[name].min:
                    gear.log(
                        "Minimum of object requiered for " + name +
                        " hasn't been reached", gear.sev_warning)
                    self.valid = False
                    continue

            else:
                obj = self.model.FindChild(self.getName(name))
                if not obj:
                    gear.log("Object missing : %s" % name, gear.sev_warning)
                    self.valid = False
                    continue

                self.tra[name] = obj.Kinematics.Global.Transform
                self.atra.append(obj.Kinematics.Global.Transform)
                self.pos[name] = obj.Kinematics.Global.Transform.Translation
                self.apos.append(obj.Kinematics.Global.Transform.Translation)

        for name in self.save_primitive:
            obj = self.model.FindChild(self.getName(name))
            if not obj:
                gear.log("Object missing : %s" % name, gear.sev_warning)
                self.valid = False
                continue

            self.prim[name] = pri.getPrimitive(obj)

        for name in self.save_blade:
            obj = self.model.FindChild(self.getName(name))
            if not obj:
                gear.log("Object missing : %s" % name, gear.sev_warning)
                self.valid = False
                continue

            self.blades[name] = vec.Blade(obj.Kinematics.Global.Transform)

        self.size = self.getSize()
        self.root_size = self.root.size.Value
Exemple #47
0
def logVector(v, msg="v"):

    gear.log(msg + "[ x : " + str(v.X) + " | y : " + str(v.Y) + " | z : " +
             str(v.Z) + " ] - Length : " + str(v.Length()))
Exemple #48
0
def logQuaternion(q, msg="quaternion"):

    gear.log(msg + "[ w : " + str(q.W) + " | x : " + str(q.X) + " | y : " +
             str(q.Y) + " | z : " + str(q.Z) + " ]")
Exemple #49
0
    def setFromXml(self, xml_comp):

        # ---------------------------------------------------
        # Settings
        xml_settings = xml_comp.find("settings")
        self.setParamDefValuesFromXml(xml_settings)

        # ---------------------------------------------------
        # First get all the object available in the xml (it's faster that way)
        xml_objects = xml_comp.find("objects")
        for xml_obj in xml_objects.findall("x3dobject"):
            localName = xml_obj.get("localName")
            xObj = xsixmldom.xmlToObject(xml_obj)

            xml_kine = xml_obj.find("kinematics")
            if xml_kine and len(xml_kine):
                t = xObj.getGlobalTransform()
                self.tra[localName] = t
                self.pos[localName] = t.Translation

            xml_prim = xml_obj.find("primitive")
            if xml_prim and len(xml_prim):
                self.prim[localName] = pri.getPrimitive(xml_obj)

            if localName in self.save_blade:
                self.blades[localName] = vec.Blade(self.tra[localName])

        # ---------------------------------------------------
        # Then check what is missing
        for name in self.save_transform:
            if "#" in name:
                i = 0
                while not self.minmax[name].max > 0 or i < self.minmax[
                        name].max:
                    localName = string.replaceSharpWithPadding(name, i)

                    if localName not in self.tra.keys():
                        break

                    self.atra.append(self.tra[localName])
                    self.apos.append(self.pos[localName])

                    i += 1

                if i < self.minmax[name].min:
                    gear.log(
                        "Minimum of object requiered for " + name +
                        " hasn't been reached", gear.sev_warning)
                    self.valid = False
                    continue
            else:
                if name not in self.tra.keys():
                    gear.log("Object missing : %s" % name, gear.sev_warning)
                    self.valid = False
                    continue

                self.atra.append(self.tra[name])
                self.apos.append(self.pos[name])

        for name in self.save_primitive:
            if name not in self.prim.keys():
                gear.log("Object missing : %s" % name, gear.sev_warning)
                self.valid = False
                continue

        for name in self.save_blade:
            if name not in self.blades.keys():
                gear.log("Object missing : %s" % name, gear.sev_warning)
                self.valid = False
                continue

        self.size = self.getSize()
        self.root_size = float(xml_comp.get("root_size"))
Exemple #50
0
    def getAsXml(self):

        xml_comp = etree.Element("component")
        xml_comp.set("name", self.fullName)
        xml_comp.set("type", self.type)
        if self.parentComponent is None:
            xml_comp.set("parent", "None")
        else:
            xml_comp.set(
                "parent",
                self.parentComponent.fullName + "." + self.parentLocalName)
        xml_comp.set("root_size", str(self.root.size.Value))

        # Settings and parameters
        xml_settings = self.getParametersAsXml("settings")
        xml_comp.append(xml_settings)

        # Objects
        xml_objects = etree.SubElement(xml_comp, "objects")
        for name in self.objectNames:
            if "#" in name:
                i = 0
                while not self.minmax[name].max > 0 or i < self.minmax[
                        name].max:
                    localName = string.replaceSharpWithPadding(name, i)

                    xsixmldom.setOptions(
                        X3DObject_children=False,
                        X3DObject_primitive=(name in self.save_primitive),
                        X3DObject_kinematics=(name in self.save_transform
                                              or name in self.save_blade),
                        X3DObject_properties=[],
                        Kinematics_local=False,
                        Kinematics_constraints=False,
                        Kinematics_removeScaling=True,
                        Geometry_addScaling=True,
                        Geometry_stack=False)

                    obj = self.model.FindChild(self.getName(localName))
                    if not obj:
                        break
                    xml_def = xsixmldom.getObject(obj).xml
                    xml_def.set("localName", localName)
                    xml_objects.append(xml_def)

                    i += 1

                if i < self.minmax[name].min:
                    gear.log(
                        "Minimum of object requiered for " + name +
                        " hasn't been reached", gear.sev_warning)
                    self.valid = False
                    continue

            else:
                xsixmldom.setOptions(
                    X3DObject_children=False,
                    X3DObject_primitive=(name in self.save_primitive),
                    X3DObject_kinematics=(name in self.save_transform
                                          or name in self.save_blade),
                    X3DObject_properties=[],
                    Kinematics_local=False,
                    Kinematics_constraints=False,
                    Kinematics_removeScaling=True,
                    Geometry_addScaling=True,
                    Geometry_stack=False)

                obj = self.model.FindChild(self.getName(name))
                if not obj:
                    gear.log("Object missing : %s" % name, gear.sev_warning)
                    continue
                xml_def = xsixmldom.getObject(obj).xml
                xml_def.set("localName", name)
                xml_objects.append(xml_def)

        return xml_comp
Exemple #51
0
 def addMinMax(self, name, minimum=1, maximum=-1):
     if "#" not in name:
         gear.log(
             "Invalid definition for min/max. You should have a '#' in the name",
             gear.sev_error)
     self.minmax[name] = MinMax(minimum, maximum)
Exemple #52
0
def gear_CopyEnvWithGator_Execute():

    # Check Selection
    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    meshes = []
    for item in xsi.Selection:
        if item.Type == "#Group":
            for member in item.Members:
                if member.Type == "polymsh":
                    meshes.append(member)
                else:
                    gear.log("Invalid Selection : %s" % member.FullName,
                             gear.sev_warning)
        elif item.Type == "polymsh":
            meshes.append(item)
        else:
            gear.log("Invalid Selection : %s" % item.FullName,
                     gear.sev_warning)

    if not meshes:
        gear.log("Invalid Selection", gear.sev_error)
        return

    # Pick Session for the sources
    source_meshes = XSIFactory.CreateObject("XSI.Collection")
    while True:
        picked = uit.pickSession(c.siGenericObjectFilter, "Pick Source Mesh",
                                 False)
        if not picked:
            break

        if picked.Type in ["#Group"]:
            for member in picked.Members:
                if ope.getOperatorFromStack(member, "envelopop"):
                    source_meshes.AddItems(member)
                else:
                    gear.log("No Envelope on " + member.Name, gear.sev_warning)
        else:
            if ope.getOperatorFromStack(picked, "envelopop"):
                source_meshes.Add(picked)
            else:
                gear.log("No Envelope on " + picked.Name, gear.sev_warning)

    if not source_meshes:
        gear.log("Invalid Picking", gear.sev_error)
        return

    # Process
    for mesh in meshes:
        env.copyEnvelopeWithGator(mesh, source_meshes)
Exemple #53
0
    def setFromHierarchy(self, root, branch=True):

        if not root.IsClassOf(c.siX3DObjectID):
            root = root.Parent3DObject

        # Start
        self.plog.start("Checking guide")

        if root.Type == "#model":
            self.model = root
        else:
            self.model = root.Model
            while True:
                if root.Properties("settings") or root.IsEqualTo(self.model):
                    break
                root = root.Parent3DObject

        # ---------------------------------------------------
        # First check and set the options
        self.plog.log(None, "Get options")
        self.options = self.model.Properties("options")
        if not self.options:
            gear.log(
                "Can't find the 'options' property. %s is not a proper rig guide."
                % self.model.Name, gear.sev_error)
            self.valid = False
            return

        self.setParamDefValuesFromProperty(self.options)

        # ---------------------------------------------------
        # Get the controlers
        self.plog.log(None, "Get controlers")
        self.controlers_org = self.model.FindChild("controlers_org")
        if self.controlers_org:
            for child in self.controlers_org.Children:
                if child.Type in ["null", "crvlist"]:
                    self.controlers[child.Name] = pri.getPrimitive(child)
                else:
                    gear.log(
                        "Invalid controler type : " + child.Name + " - " +
                        child.Type, gear.sev_warning)

        # ---------------------------------------------------
        # Components
        self.plog.log(None, "Get components")
        self.findComponentRecursive(root, branch)

        # Parenting
        self.plog.log(None, "Get parenting")
        for name in self.componentsIndex:
            compChild = self.components[name]
            for name in self.componentsIndex:
                compParent = self.components[name]
                for name, element in compParent.getObjects(self.model).items():
                    if element is not None and element.IsEqualTo(
                            compChild.root.Parent):
                        compChild.parentComponent = compParent
                        compChild.parentLocalName = name
                        break

        # More option values
        self.addOptionsValues()

        # End
        if not self.valid:
            gear.log(
                "The guide doesn't seem to be up to date. Check logged messages and update the guide.",
                gear.sev_warning)

        gear.log("Guide loaded from hierarchy in [ " + self.plog.getTime() +
                 " ]")
        self.plog.hideBar()
Exemple #54
0
def XSIUnloadPlugin(in_reg):
    strPluginName = in_reg.Name
    gear.log(str(strPluginName) + str(" has been unloaded."), c.siVerbose)
    return True
Exemple #55
0
def gear_ReplaceDeformer_Execute():

    if not xsi.Selection.Count:
        gear.log("No selection", gear.sev_error)
        return

    sel = xsi.Selection(0)

    if sel.Type == "polymsh":
        mesh = sel
        points = range(mesh.ActivePrimitive.Geometry.Points.Count)
    elif sel.Type == "pntSubComponent":
        mesh = sel.SubComponent.Parent3DObject
        points = sel.SubComponent.ElementArray
    else:
        gear.log("Invalid selection", gear.sev_error)
        return

    # Get Envelope from object
    envelope_op = ope.getOperatorFromStack(mesh, "envelopop")
    if not envelope_op:
        gear.log("There is no envelope on selected mesh", gear.sev_error)
        return False

    # Source deformers
    source_deformers = XSIFactory.CreateObject("XSI.Collection")
    while True:
        picked = uit.pickSession(c.siGenericObjectFilter,
                                 "Pick Source Deformers", False)
        if not picked:
            break

        if picked.Type == "#Group":
            source_deformers.AddItems(picked.Members)
        else:
            source_deformers.Add(picked)

    if not source_deformers.Count:
        return False

    # Target deformers
    target_deformers = XSIFactory.CreateObject("XSI.Collection")
    while True:
        picked = uit.pickSession(c.siGenericObjectFilter,
                                 "Pick Target Deformers", False)
        if not picked:
            break

        if picked.Type == "#Group":
            target_deformers.AddItems(picked.Members)
        else:
            target_deformers.Add(picked)

    if not target_deformers.Count:
        return False

    # Some log to be sure of what we have selected
    gear.log("Geometry: " + mesh.FullName + "  \nSource(s): " +
             str(source_deformers) + "  \nTarget(s): " + str(target_deformers))

    env.replaceDeformerInEnvelope(envelope_op, source_deformers,
                                  target_deformers, points)
Exemple #56
0
def gear_SplitShapeKey_Execute():

    if not xsi.Selection.Count:
        gear.log("Select shape keys", gear.sev_error)
        return

    shapes = [shape for shape in xsi.Selection if shape.Type in ["clskey"]]
    if not shapes:
        return

    cls = shapes[0].Parent
    mesh = cls.Parent3DObject
    geo = mesh.ActivePrimitive.Geometry
    clusters = geo.Clusters

    # UI
    prop = xsi.ActiveSceneRoot.AddProperty("Custom_parameter_list", False,
                                           "gear_SplitShapeKey")

    pLPrefix = prop.AddParameter3("LPrefix", c.siString, "L_", None, None,
                                  False, False)
    pRPrefix = prop.AddParameter3("RPrefix", c.siString, "R_", None, None,
                                  False, False)
    pRCluster = prop.AddParameter3("RCluster", c.siInt4, -1, -1,
                                   clusters.Count - 1, False, False)
    pLCluster = prop.AddParameter3("LCluster", c.siInt4, -1, -1,
                                   clusters.Count - 1, False, False)
    pCCluster = prop.AddParameter3("CCluster", c.siInt4, -1, -1,
                                   clusters.Count - 1, False, False)

    clusters_items = ["Auto Detect Points", -1]
    for i, cls in enumerate(clusters):
        clusters_items.append(cls.Name)
        clusters_items.append(i)

    # Layout
    layout = prop.PPGLayout
    layout.Clear()

    layout.AddTab("General")
    layout.AddGroup("Prefix")
    layout.AddRow()
    layout.AddItem(pRPrefix.ScriptName, "Right")
    layout.AddItem(pLPrefix.ScriptName, "Left")
    layout.EndRow()
    layout.EndGroup()

    layout.AddGroup("Clusters")
    layout.AddEnumControl(pRCluster.ScriptName, clusters_items, "Right Points",
                          c.siControlCombo)
    layout.AddEnumControl(pLCluster.ScriptName, clusters_items, "Left Points",
                          c.siControlCombo)
    layout.AddEnumControl(pCCluster.ScriptName, clusters_items,
                          "Center Points", c.siControlCombo)
    layout.EndGroup()

    # Inspect
    rtn = xsi.InspectObj(prop, "", "Split Shape Key", c.siModal, False)

    # Return Values
    if pRCluster.Value == -1:
        r_points = sha.getPoints(geo, "R")
    else:
        r_points = clusters(pRCluster.value - 1).Elements.Array

    if pLCluster.Value == -1:
        l_points = sha.getPoints(geo, "L")
    else:
        l_points = clusters(pLCluster.value - 1).Elements.Array

    if pCCluster.Value == -1:
        c_points = sha.getPoints(geo, "C")
    else:
        c_points = clusters(pCCluster.value - 1).Elements.Array

    r_prefix = pRPrefix.Value
    l_prefix = pLPrefix.Value

    xsi.DeleteObj(prop)

    if rtn:
        return

    # Process
    for shape in shapes:
        sha.createHalfShape(shape, c_points, l_prefix, r_points)
        sha.createHalfShape(shape, c_points, r_prefix, l_points)
Exemple #57
0
def replaceDeformerInEnvelope(envelope_op,
                              source_deformers,
                              target_deformers,
                              points=None):

    # Check source deformers
    source_index = []
    for obj in source_deformers:
        deformer_index = getDeformerIndex(envelope_op, obj)
        if deformer_index != -1:
            source_index.append(deformer_index)

    if not source_index:
        gear.log("None of the source deformers belongs to the envelope",
                 gear.sev_warning)
        return False

    # Add Target Deformer to envelope if missing
    mesh = envelope_op.Parent3DObject
    for obj in target_deformers:
        if not isDeformer(envelope_op, obj):
            envelope_op = mesh.ApplyEnvelope(obj)

    # Get the target deformers index
    target_index = []
    for obj in target_deformers:
        deformer_index = getDeformerIndex(envelope_op, obj)
        target_index.append(deformer_index)

    # Get Weights
    mesh = envelope_op.Parent3DObject
    point_count = mesh.ActivePrimitive.Geometry.Points.Count
    deformer_count = envelope_op.Deformers.Count
    weights_tuple = envelope_op.Weights.Array
    weights = [
        weights_tuple[j][i] for i in range(len(weights_tuple[0]))
        for j in range(len(weights_tuple))
    ]

    # Process
    if points is None:
        points = range(point_count)

    for point_index in points:

        point_weight = 0
        for deformer_index in source_index:
            point_weight += weights_tuple[deformer_index][point_index]
            weights[point_index * deformer_count + deformer_index] = 0

        if point_weight == 0:
            continue

        for deformer_index in target_index:
            weights[point_index * deformer_count +
                    deformer_index] += point_weight / len(target_index)

    envelope_op.Weights.Array = weights

    freezeEnvelope(envelope_op)

    # Remove old deformers from the envelope
    for source_deformer in source_deformers:
        delete = True

        for target_deformer in target_deformers:
            if source_deformer.FullName == target_deformer.FullName:
                delete = False

        gear.log(mesh.FullName + "     " + source_deformer.FullName + "    " +
                 str(delete))

        if delete:
            rtn = removeEnvDeformer(envelope_op, source_deformer)
            if not rtn:
                gear.log(
                    "Deformer " + source_deformer.FullName +
                    " could not be removed !", gear.sev_warning)

    return True
Exemple #58
0
def select(in_mousebutton, in_keymodifier, name=None):

    model = getModel()

    if name is None:
        ctl = model
    else:
        ctl = model.FindChild(name)

    # Check if the object exists
    if not ctl:
        gear.log("Can't Find object : " + name, gear.sev_warning)
        return

    # Create Collection for different selection mode
    controlers = XSIFactory.CreateObject("XSI.Collection")

    # Mouse button ======================================
    # Left Clic - Simple select
    if in_mousebutton == 0:
        controlers.Add(ctl)

    # Middle Clic - Select in 'branch'
    elif in_mousebutton == 1:
        controlers.Add(ctl)

        # Get all controlers of the model
        controlers_filtered = []
        for group in getControlersGroups():
            controlers_filtered.extend(group.Members.GetAsText().split(","))

        # First Method, Try to find controlers of the same 'kind'
        # Find controler index
        has_index = False
        sIndex = re.search("[0-9]+_ctl$", ctl.Name)
        if sIndex:
            index = int(sIndex.group(0)[:-4])
            has_index = True

        # Try to find child of the same 'type'
        if has_index and controlers_filtered:
            while True:
                index += 1
                next_name = re.sub("[0-9]+_ctl$",
                                   str(index) + "_ctl", ctl.Name)

                if model.Name + "." + next_name not in controlers_filtered:
                    break

                controlers.Add(model.FindChild(next_name))

        # Second Method if no child found
        # we get all controlers children of selected one
        if controlers.Count == 1 and controlers_filtered:
            for child in ctl.FindChildren():
                if child.FullName in controlers_filtered:
                    controlers.Add(child)

    # Right Clic - Do nothing
    elif in_mousebutton == 2:
        return

    # Key pressed =======================================
    if in_keymodifier == 0:  # No Key or No Valid Key
        xsi.SelectObj(controlers)
    elif in_keymodifier == 1:  # Shift    check the object isn't already selected
        try:
            xsi.AddToSelection(controlers)
        except:
            return
    elif in_keymodifier == 2:  # Ctrl
        xsi.ToggleSelection(controlers)
    elif in_keymodifier == 3:  # Shift+Ctrl
        xsi.RemoveFromSelection(controlers)
    elif in_keymodifier == 4:  # Alt
        xsi.SelectObj(controlers, "BRANCH", True)
    elif in_keymodifier == 5:  # Alt+Shift check the object isn't already selected
        try:
            xsi.AddToSelection(controlers, "BRANCH", True)
        except:
            return
    elif in_keymodifier == 6:  # Alt+Ctrl
        xsi.ToggleSelection(controlers, "BRANCH", True)
    elif in_keymodifier == 7:  # Alt+Shift+Ctrl
        xsi.RemoveFromSelection(controlers)
Exemple #59
0
    def getRelation(self, name):
        if name not in self.relatives.keys():
            gear.log("Can't find reference for object : " + self.fullName + "." + name, gear.sev_error)
            return False

        return self.relatives[name]