Example #1
0
def sn_rollsplinekine_op(out, ctrl=[], u=.5):

    # Create Operator
    op = XSIFactory.CreateObject("sn_rollsplinekine_op")

    # Outputs
    op.AddOutputPort(out.Kinematics.Global)

    # Inputs
    for obj in ctrl:
        op.AddInputPort(obj.Parent.Kinematics.Global)
        op.AddInputPort(obj.Kinematics.Local)
    op.AddInputPort(ctrl[0].Parent.Kinematics.Global)

    # Set default values
    op.Parameters("count").Value = len(ctrl)
    op.Parameters("u").Value = u
    op.Parameters("resample").Value = True

    # Connect
    op.Connect()

    return op
Example #2
0
def gear_dualUpVDirCns(cns, ref, target, negate=False):

    # -----------------------------------------------------
    # JSCRIPT
    paramDefs = []
    paramDefs.append(
        XSIFactory.CreateParamDef("negate", c.siBool, 0,
                                  c.siPersistable | c.siAnimatable, "", "",
                                  negate))

    outputPorts = [(cns.Kinematics.Global, "out")]
    inputPorts = [(cns.Kinematics.Global, "kcns"),
                  (ref.Kinematics.Global, "kref"),
                  (target.Kinematics.Global, "ktar")]

    op = createJSOpFromFile("gear_dualUpVDirCns",
                            os.path.join(JSOPPATH, "gear_dualUpVDirCns_op.js"),
                            outputPorts, inputPorts, paramDefs)

    # Connect
    op.Connect()

    return op
Example #3
0
def sn_interLocalOri_op(out, refA, refB, blend=0):

    # Create Operator
    op = XSIFactory.CreateObject("sn_interLocalOri_op")

    # Outputs
    for s in ["rotx", "roty", "rotz", "nrotx", "nroty", "nrotz"]:
        op.AddOutputPort(out.Parameters(s), s)

    # Inputs
    op.AddInputPort(refA.Kinematics.Global)
    op.AddInputPort(refB.Kinematics.Global)
    op.AddInputPort(out.Parent.Kinematics.Global)
    op.AddInputPort(refA.Parameters("rotx"))
    op.AddInputPort(refB.Parameters("rotx"))

    # Set default values
    op.Parameters("blend").Value = blend

    # Connect
    op.Connect()

    return op
Example #4
0
def gear_CopyEnvWithGator_Execute():

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

    source_meshes = XSIFactory.CreateObject("XSI.Collection")
    while True:
        picked = uit.pickSession(c.siGeometryFilter, "Pick Source Mesh", False)
        if not picked:
            break

        if not ope.getOperatorFromStack(picked, "envelopop"):
            gear.log("No Envelope on " + picked.Name, c.siWarning)
            continue

        source_meshes.Add(picked)

    if not source_meshes:
        return

    for mesh in xsi.Selection:
        env.copyEnvelopeWithGator(mesh, source_meshes)
Example #5
0
def removeEnvDeformer(envelope_op, obj):

    mesh = envelope_op.Parent3DObject
    points = mesh.ActivePrimitive.Geometry.Points
    point_count = points.Count
    deformers = envelope_op.Deformers
    deformer_count = deformers.Count
    index = 0
    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))
    ]
    new_deformers = XSIFactory.CreateObject("XSI.Collection")

    # Process
    for deformer_index, deformer in enumerate(deformers):
        if obj.FullName == deformer.FullName:
            index = deformer_index
        else:
            new_deformers.add(deformer)

    newWeight = []
    for point_index in range(point_count):
        newWeight.extend(
            weights[point_index * deformer_count:point_index * deformer_count +
                    index])
        newWeight.extend(
            weights[point_index * deformer_count + index +
                    1:point_index * deformer_count + deformer_count])

    # Delete the old Envelope and add the new one with the new Deformers
    xsi.RemoveFlexEnv(mesh)
    envelope_op = mesh.ApplyEnvelope(new_deformers)
    envelope_op.Weights.Array = newWeight

    return envelope_op
Example #6
0
def gear_RemoveUnusedEnvCls_Execute():

    # This method is named based and doesn't provide a perfect result but should work in most of the case.

    # Return All the Pnt Cluster from the active scene
    point_clusters = xsi.FindObjects(None,
                                     "{E4DD8E40-1E1C-11D0-AA2E-00A0243E34C4}")

    # Search for unused EnvelopWeightCls
    delete_objs = XSIFactory.CreateObject("XSI.Collection")
    for cls in point_clusters:

        if cls.Name.startswith("EnvelopWeightCls"):
            delete = True
            for prop in cls.Properties:
                if prop.Type == "envweights":
                    delete = False

            if delete:
                delete_objs.Add(cls)

    # Delete
    if delete_objs.Count:
        xsi.DeleteObj(delete_objs)
Example #7
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)
Example #8
0
def getKeyableParameters(in_controlers):

    # We make sure input is a collection (next method doesn't work with selection)
    controlers = XSIFactory.CreateObject("XSI.Collection")
    controlers.AddItems(in_controlers)
    return controlers.FindObjectsByMarkingAndCapabilities(None, 2048)
Example #9
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
Example #10
0
    def __init__(self, rig, guide):

        # --------------------------------------------------
        # Main Objects
        self.rig = rig
        self.guide = guide

        self.options = self.rig.options
        self.model = self.rig.model
        self.settings = self.guide.values

        self.name = self.settings["comp_name"]
        self.side = self.settings["comp_side"]
        self.index = self.settings["comp_index"]

        # --------------------------------------------------
        # Shortcut to useful settings
        self.size = self.guide.size

        self.color_fk = self.options[self.side + "_color_fk"]
        self.color_ik = self.options[self.side + "_color_ik"]

        self.negate = self.side == "R"
        if self.negate:
            self.n_sign = "-"
            self.n_factor = -1
        else:
            self.n_sign = ""
            self.n_factor = 1

        # --------------------------------------------------
        # Builder init
        self.groups = {}  ## Dictionary of groups
        self.controlers = []  ## List of all the controlers of the component
        self.inv_params = XSIFactory.CreateObject("XSI.Collection")

        if not self.settings["set_ctl_grp"] or (self.settings["set_ctl_grp"]
                                                and self.settings["ctl_grp"]
                                                == ""):
            self.settings["ctl_grp"] = "01"

        # --------------------------------------------------
        # Property init
        self.anim_layout = ppg.PPGLayout()
        self.anim_logic = ppg.PPGLogic()
        self.setup_layout = ppg.PPGLayout()
        self.setup_logic = ppg.PPGLogic()

        self.ui = None

        # --------------------------------------------------
        # Connector init
        self.connections = {}
        self.connections["standard"] = self.connect_standard

        self.relatives = {}

        # --------------------------------------------------
        # Step
        self.stepMethods = [
            eval("self.step_0%s" % i) for i in range(len(self.steps))
        ]
Example #11
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
Example #12
0
def sn_ikfk2bone_op(out=[],
                    root=None,
                    eff=None,
                    upv=None,
                    fk0=None,
                    fk1=None,
                    fk2=None,
                    lengthA=5,
                    lengthB=3,
                    negate=False,
                    blend=0,
                    lang=CPP):

    # -----------------------------------------------------
    if lang == CPP:
        # Create Operator
        op = XSIFactory.CreateObject("sn_ikfk2bone_op")

        # Outputs
        for i, s in enumerate(["OutBoneA", "OutBoneB", "OutCenterN",
                               "OutEff"]):
            if len(out) > i and out[i] is not None:
                op.AddOutputPort(out[i].Kinematics.Global, s)

        # Inputs
        op.AddInputPort(root.Kinematics.Global)
        op.AddInputPort(eff.Kinematics.Global)
        op.AddInputPort(upv.Kinematics.Global)
        op.AddInputPort(fk0.Kinematics.Global)
        op.AddInputPort(fk1.Kinematics.Global)
        op.AddInputPort(fk2.Kinematics.Global)

    # -----------------------------------------------------
    elif lang == JSCRIPT:

        paramDefs = []
        paramDefs.append(
            XSIFactory.CreateParamDef("lengthA", c.siDouble, 0,
                                      c.siPersistable | c.siAnimatable, "", "",
                                      3, 0, None, 0, 10))
        paramDefs.append(
            XSIFactory.CreateParamDef("lengthB", c.siDouble, 0,
                                      c.siPersistable | c.siAnimatable, "", "",
                                      5, 0, None, 0, 10))
        paramDefs.append(
            XSIFactory.CreateParamDef("negate", c.siBool, 0,
                                      c.siPersistable | c.siAnimatable, "", "",
                                      False))
        paramDefs.append(
            XSIFactory.CreateParamDef("blend", c.siDouble, 0,
                                      c.siPersistable | c.siAnimatable, "", "",
                                      0, 0, 1, 0, 1))
        paramDefs.append(
            XSIFactory.CreateParamDef("roll", c.siDouble, 0,
                                      c.siPersistable | c.siAnimatable, "", "",
                                      0, -360, 360, -360, 360))
        paramDefs.append(
            XSIFactory.CreateParamDef("scaleA", c.siDouble, 0,
                                      c.siPersistable | c.siAnimatable, "", "",
                                      1, 0, None, 0, 2))
        paramDefs.append(
            XSIFactory.CreateParamDef("scaleB", c.siDouble, 0,
                                      c.siPersistable | c.siAnimatable, "", "",
                                      1, 0, None, 0, 2))
        paramDefs.append(
            XSIFactory.CreateParamDef("maxstretch", c.siDouble, 0,
                                      c.siPersistable | c.siAnimatable, "", "",
                                      1, 1, None, 1, 2))
        paramDefs.append(
            XSIFactory.CreateParamDef("softness", c.siDouble, 0,
                                      c.siPersistable | c.siAnimatable, "", "",
                                      0, 0, None, 0, 1))
        paramDefs.append(
            XSIFactory.CreateParamDef("slide", c.siDouble, 0,
                                      c.siPersistable | c.siAnimatable, "", "",
                                      0.5, 0, 1, 0, 1))
        paramDefs.append(
            XSIFactory.CreateParamDef("reverse", c.siDouble, 0,
                                      c.siPersistable | c.siAnimatable, "", "",
                                      0, 0, 1, 0, 1))

        outputPorts = [(out[i].Kinematics.Global, name)
                       for i, name in enumerate(
                           ["OutBoneA", "OutBoneB", "OutCenterN", "OutEff"])
                       if (len(out) > i and out[i] is not None)]
        inputPorts = [(obj.Kinematics.Global, "input_%s" % i)
                      for i, obj in enumerate([root, eff, upv, fk0, fk1, fk2])]

        op = createJSOpFromFile("sn_ikfk2bone_op",
                                os.path.join(JSOPPATH, "sn_ikfk2bone_op.js"),
                                outputPorts, inputPorts, paramDefs)

    # -----------------------------------------------------
    # Set default values
    op.Parameters("negate").Value = negate
    op.Parameters("lengthA").Value = lengthA
    op.Parameters("lengthB").Value = lengthB
    op.Parameters("blend").Value = blend

    # Connect
    op.Connect()

    return op
Example #13
0
def sn_curveslide2_op(outcrv,
                      incrv,
                      position=0,
                      maxstretch=1,
                      maxsquash=1,
                      softness=0,
                      lang=CPP):

    inlength = incrv.ActivePrimitive.Geometry.Length

    # CPP -----------------------------------------------
    if lang == CPP:
        # Create Operator
        op = XSIFactory.CreateObject("sn_curveslide2_op")

        # IO
        op.AddIOPort(outcrv.ActivePrimitive)
        op.AddInputPort(incrv.ActivePrimitive)

        # Set default values
        op.Parameters("mstlength").Value = inlength
        op.Parameters("slvlength").Value = inlength
        op.Parameters("position").Value = position
        op.Parameters("maxstretch").Value = maxstretch
        op.Parameters("maxsquash").Value = maxsquash
        op.Parameters("softness").Value = softness

        # Connect
        op.Connect()

    # JSCRIPT -------------------------------------------
    elif lang == JSCRIPT:

        paramDefs = []
        paramDefs.append(
            XSIFactory.CreateParamDef("mstlength", c.siDouble, 0,
                                      c.siPersistable | c.siAnimatable, "", "",
                                      inlength, 0, None, inlength * .5,
                                      inlength * 2))
        paramDefs.append(
            XSIFactory.CreateParamDef("slvlength", c.siDouble, 0,
                                      c.siPersistable | c.siAnimatable, "", "",
                                      inlength, 0, None, inlength * .5,
                                      inlength * 2))
        paramDefs.append(
            XSIFactory.CreateParamDef("position", c.siDouble, 0,
                                      c.siPersistable | c.siAnimatable, "", "",
                                      position, 0, 1, 0, 1))
        paramDefs.append(
            XSIFactory.CreateParamDef("maxstretch", c.siDouble, 0,
                                      c.siPersistable | c.siAnimatable, "", "",
                                      maxstretch, 0, None, 0, 3))
        paramDefs.append(
            XSIFactory.CreateParamDef("maxsquash", c.siDouble, 0,
                                      c.siPersistable | c.siAnimatable, "", "",
                                      maxsquash, 0, 1, 0, 1))
        paramDefs.append(
            XSIFactory.CreateParamDef("softness", c.siDouble, 0,
                                      c.siPersistable | c.siAnimatable, "", "",
                                      softness, 0, 1, 0, 1))

        outputPorts = [(outcrv.ActivePrimitive, "out")]
        inputPorts = [(outcrv.ActivePrimitive, "in_crv"),
                      (incrv.ActivePrimitive, "ref_crv")]

        op = createJSOpFromFile(
            "gear_curveslide2", os.path.join(JSOPPATH,
                                             "gear_curveslide2_op.js"),
            outputPorts, inputPorts, paramDefs)

        op.Connect()

        layout = op.PPGLayout
        layout.Clear()

        layout.AddGroup("Default")
        layout.AddItem("slvlength", "Slave Length")
        layout.AddItem("mstlength", "Master Length")
        layout.EndGroup()
        layout.AddGroup("Animate")
        layout.AddItem("position", "Position")
        layout.AddItem("maxstretch", "Max Stretch")
        layout.AddItem("maxsquash", "Max Squash")
        layout.AddItem("softness", "Softness")
        layout.EndGroup()

    return op
Example #14
0
def gear_zipper_op(crv0, crv1):

    # -----------------------------------------------------
    # JSCRIPT
    paramDefs = []
    paramDefs.append(
        XSIFactory.CreateParamDef("zip", c.siDouble, 0,
                                  c.siPersistable | c.siAnimatable, "", "", 0,
                                  0, 1, 0, 1))
    paramDefs.append(
        XSIFactory.CreateParamDef("bias", c.siDouble, 0,
                                  c.siPersistable | c.siAnimatable, "", "", .5,
                                  0, 1, 0, 1))
    paramDefs.append(XSIFactory.CreateFCurveParamDef("start_fcv"))
    paramDefs.append(XSIFactory.CreateFCurveParamDef("speed_fcv"))

    outputPorts = [(crv0.ActivePrimitive, "out_0"),
                   (crv1.ActivePrimitive, "out_1")]
    inputPorts = [(crv0.ActivePrimitive, "crv0"),
                  (crv1.ActivePrimitive, "crv1")]

    op = createJSOpFromFile("gear_zipper",
                            os.path.join(JSOPPATH, "gear_zipper_op.js"),
                            outputPorts, inputPorts, paramDefs)

    op.Connect()

    # FCurve profile
    fcv.drawFCurve(
        op.Parameters("start_fcv").Value, [[0, 0], [1, 1]],
        c.siLinearKeyInterpolation)
    fcv.drawFCurve(
        op.Parameters("speed_fcv").Value, [[0, 0], [1, 1]],
        c.siLinearKeyInterpolation)

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

    layout.AddGroup("Zipper")
    layout.AddItem("Mute", "Mute")
    layout.AddItem("zip", "Zip")
    layout.AddItem("bias", "Bias")
    layout.EndGroup()

    layout.AddGroup("Profile")
    item = layout.AddFCurve("start_fcv")
    item.SetAttribute(c.siUIFCurveLabelX, "Points")
    item.SetAttribute(c.siUIFCurveLabelY, "Start")
    item.SetAttribute(c.siUIFCurveViewMinX, -.1)
    item.SetAttribute(c.siUIFCurveViewMaxX, 1.1)
    item.SetAttribute(c.siUIFCurveViewMinY, -.1)
    item.SetAttribute(c.siUIFCurveViewMaxY, 1.1)
    item.SetAttribute(c.siUIFCurveGridSpaceX, .1)
    item.SetAttribute(c.siUIFCurveGridSpaceY, .1)
    layout.EndGroup()

    layout.AddGroup("Speed")
    item = layout.AddFCurve("speed_fcv")
    item.SetAttribute(c.siUIFCurveLabelX, "Points")
    item.SetAttribute(c.siUIFCurveLabelY, "Speed")
    item.SetAttribute(c.siUIFCurveViewMinX, -.1)
    item.SetAttribute(c.siUIFCurveViewMaxX, 2.1)
    item.SetAttribute(c.siUIFCurveViewMinY, -.1)
    item.SetAttribute(c.siUIFCurveViewMaxY, 1.1)
    item.SetAttribute(c.siUIFCurveGridSpaceX, .1)
    item.SetAttribute(c.siUIFCurveGridSpaceY, .1)
    layout.EndGroup()

    return op
Example #15
0
    def finalize(self):

        # Properties --------------------------------------
        self.plog.log("Filling layout and logic")
        self.ui.fillLayoutAndLogic()

        # Groups ------------------------------------------
        self.plog.log("Creating groups")
        # Retrieve group content from components
        for name in self.componentsIndex:
            component = self.components[name]
            for name, objects in component.groups.items():
                self.addToGroup(objects, name)

        # Creating all groups
        for name, objects in self.groups.items():
            collection = XSIFactory.CreateObject("XSI.Collection")
            collection.AddItems(objects)
            self.groups[name] = self.model.AddGroup(collection, name + "_grp")

        # Hidden
        if self.options["setHidden"]:
            self.groups["hidden"].Parameters("viewvis").Value = 0
            self.groups["hidden"].Parameters("rendvis").Value = 0

        # Unselectable
        if self.options["setUnselectable"]:
            self.groups["unselectable"].Parameters("selectability").Value = 0

        # Deformers
        if self.options["setDeformers"]:
            self.groups["deformers"].Parameters("viewvis").Value = 0
            self.groups["deformers"].Parameters("rendvis").Value = 0

        # Geometries
        if self.options["setGeometries"]:
            self.groups["geometries"].Parameters("selectability").Value = 0
            prop = self.groups["geometries"].AddProperty("GeomApprox")
            par.addExpression(prop.Parameters("gapproxmosl"), self.pOGLLevel)

        # Skin --------------------------------------------
        if self.options["addGeometry"]:
            self.plog.log("Applying skin")

            # Import geometry
            if self.options["geo_path"] and os.path.exists(
                    self.options["geo_path"]):
                geo_model = xsi.ImportModel(self.options["geo_path"],
                                            xsi.ActiveSceneRoot, False,
                                            None)(1)

                geo_objects = geo_model.FindChildren()

                self.model.AddChild(geo_model.children)
                for group in geo_model.Groups:
                    target_group = pri.createOrReturnGroup(
                        self.model, group.Name)
                    target_group.AddMember(group.Members)
                xsi.DeleteObj(geo_model)

                # Apply skin
                if self.options["skin_path"] and os.path.exists(
                        self.options["skin_path"]):
                    xml_objs = io.getObjectDefinitions(
                        self.options["skin_path"], geo_objects, False)

                    for obj in geo_objects:

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

                        io.importSkin(xml_objs[obj.Name], obj)

        # Symmetry Mapping Template -----------------------
        if self.options["mode"] == 1:

            env.createSymmetryMappingTemplate(self.groups["deformers"].Members)

            for geo in self.groups["geometries"].Members:
                if geo.Type == "polymsh":
                    xsi.CreateSymmetryMap("SymmetryMap", geo, "Symmetry Map")

        # Mirror Animation Template -----------------------
        if self.options["mode"] == 0:
            cnx_prop = ani.createMirrorCnxTemplate(self.model)
            for count, compName in enumerate(self.componentsIndex):
                component = self.components[compName]
                inversed_params = component.inv_params.GetAsText().split(",")
                for ctl in component.controlers:
                    ani.addMirroringRule(ctl, cnx_prop, inversed_params, True)

        # Reset Pose --------------------------------------
        self.plog.log("Creating rest pose")
        controlers = XSIFactory.CreateObject("XSI.Collection")
        for group in self.model.Groups:
            if group.Name.startswith("controlers"):
                controlers.AddItems(group.Members)

        keyableParams = controlers.FindObjectsByMarkingAndCapabilities(
            None, c.siKeyable)
        xsi.StoreAction(self.model, keyableParams, 1, "reset", False)

        # Isolate and popup -------------------------------
        if self.options["isolateResult"]:
            xsi.SelectObj(self.model, "BRANCH")
            xsi.IsolateSelected(False, -1)
            xsi.DeselectAll()

        if self.options["popUpControls"]:
            xsi.InspectObj(self.ui.anim_prop)
Example #16
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)