예제 #1
0
    def convert_node(self, gltf, node_idx, materials=None):
        gltf_node = gltf.data.nodes[node_idx]
        c4d_object = None

        if gltf_node.mesh is not None:
            c4d_object = self.convert_mesh(gltf, gltf_node.mesh, c4d_object,
                                           materials)
        else:
            c4d_object = c4d.BaseObject(c4d.Onull)

        c4d_object.SetName(gltf_node.name if gltf_node.name else "GLTFObject")
        c4d_object.SetRotationOrder(5)  # Local XYZ
        c4d_mat = c4d.Matrix()

        if gltf_node.matrix:
            mat = gltf_node.matrix
            v1 = c4d.Vector(mat[0], mat[1], mat[2])
            v2 = c4d.Vector(mat[4], mat[5], mat[6])
            v3 = c4d.Vector(mat[8], mat[9], mat[10])
            off = c4d.Vector(mat[12], mat[13], mat[14])
            c4d_mat = c4d.Matrix(off, v1, v2, v3)
            c4d_object.SetMg(c4d_mat)

            pos = c4d_object.GetAbsPos()
            rot = c4d_object.GetAbsRot()

            pos[2] = -pos[2]

            rot[0] = -rot[0]
            rot[1] = -rot[1]

            c4d_object.SetAbsPos(pos)
            c4d_object.SetAbsRot(rot)

        else:
            if gltf_node.rotation:
                c4d_object.SetAbsRot(self.quat_to_eulerxyz(gltf_node.rotation))

            if gltf_node.scale:
                scale = gltf_node.scale
                c4d_object.SetAbsScale(c4d.Vector(scale[0], scale[1],
                                                  scale[2]))

            if gltf_node.translation:
                tr = gltf_node.translation
                c4d_object.SetAbsPos(c4d.Vector(tr[0], tr[1], tr[2]))

            pos = c4d_object.GetAbsPos()
            rot = c4d_object.GetAbsRot()

            pos[0] = pos[0]
            pos[2] = -pos[2]
            rot[2] = -rot[2]

            c4d_object.SetAbsPos(pos)
            c4d_object.SetAbsRot(rot)

        return c4d_object
예제 #2
0
def main():

    #~~~~OPEN CSV FILE FOR GH POSITION DATA~~~~~~~~~~~ CHECKED
    filepath = 'C:/Users/anam/Desktop/bch rotations/positions3.csv'

    GHPOS = []  #store position date from GH IN empty list

    data = open(filepath)
    csv_data = csv.reader(data)
    for row in csv_data:
        b = map(float, row)
        GHPOS.append(b)

    data.close()

    #~~~~~STORE X,Y,Z POS VECTORS FROM GH~~~~~~~~~~~~~~~~
    marrNew = []  # list of vectors for position
    for pos in GHPOS:
        x = pos[0]  #x items
        y = pos[1]  #y items
        z = pos[2]  #z items

        off = c4d.Vector(x, y, z)  #GH POSITION DATA
        newMatrix = c4d.Matrix(off)

        marrNew.append(newMatrix)

    #~~~~~~~SET GH MATRIX IN C4D~~~~~~~~~~~~~~~~~~~~~CHECKED
    setNewGHArr = md.SetArray(c4d.MODATA_MATRIX, marrNew, False)  #set GH PIXEL
    print marrNew
예제 #3
0
def main():
    spline = doc.GetActiveObject()

    doc.StartUndo()

    if not spline.CheckType(c4d.Ospline):
        print "this is NOT Oline"
        return

    count = spline.GetPointCount()
    matrix = spline.GetMg()
    spline.SetMg(c4d.Matrix())

    mospl = c4d.BaseObject(440000054) # MoSpline
    mospl[c4d.MGMOSPLINEOBJECT_MODE] = 1 # spline
    mospl[c4d.MGMOSPLINEOBJECT_SPLINE_MODE] = 2 # even
    mospl[c4d.MGMOSPLINEOBJECT_SOURCE_SPLINE] = spline
    mospl[c4d.MGMOSPLINEOBJECT_SPLINE_COUNT] = count
    mospl.SetName(spline.GetName())
    mospl.SetMg(matrix)

    doc.InsertObject(mospl)
    res = make_editable(mospl)
    res.InsertBefore(spline)
    doc.AddUndo(c4d.UNDOTYPE_NEW, mospl)

    c4d.EventAdd()

    doc.AddUndo(c4d.UNDOTYPE_DELETE, spline)
    spline.Remove()

    doc.SetActiveObject(mospl,1)

    doc.EndUndo()
예제 #4
0
def main():

    obs = doc.GetActiveObjects(0)

    if not obs:
        gui.MessageDialog('Please select some objects!')
        return

    if len(obs) == 1:
        nullm = obs[0].GetMg()
    else:
        nullm = c4d.Matrix()
        nullm.off = sum([ob.GetMg().off for ob in obs]) / len(obs)

    doc.StartUndo()
    null = c4d.BaseObject(c4d.Onull)
    null.InsertBefore(obs[0])
    doc.AddUndo(c4d.UNDOTYPE_NEW, null)
    null.SetBit(c4d.BIT_ACTIVE)
    null.SetMg(nullm)

    for ob in obs:
        m = ob.GetMg()
        doc.AddUndo(c4d.UNDOTYPE_HIERARCHY_PSR, ob)
        ob.InsertUnderLast(null)
        ob.DelBit(c4d.BIT_ACTIVE)
        ob.SetMg(m)

    doc.EndUndo()
    c4d.EventAdd()
예제 #5
0
    def test_serialize_matrix_as_dict(self):
        matrix = c4d.Matrix()

        result = serialize.serialize_matrix_as_dict(matrix)
        result_expected = {
            "instance_of": "c4d.Matrix",
            "off": {
                "instance_of": "c4d.Vector",
                "x": 0,
                "y": 0,
                "z": 0
            },
            "v1": {
                "instance_of": "c4d.Vector",
                "x": 1,
                "y": 0,
                "z": 0
            },
            "v2": {
                "instance_of": "c4d.Vector",
                "x": 0,
                "y": 1,
                "z": 0
            },
            "v3": {
                "instance_of": "c4d.Vector",
                "x": 0,
                "y": 0,
                "z": 1
            },
        }

        self.assertDictEqual(result, result_expected)
예제 #6
0
def quaternionToMatrix(x, y, z, w):
    xx = x * x
    xy = x * y
    xz = x * z
    xw = x * w
    yy = y * y
    yz = y * z
    yw = y * w
    zz = z * z
    zw = z * w
    vec1 = c4d.Vector()
    vec2 = c4d.Vector()
    vec3 = c4d.Vector()
    vecOff = c4d.Vector()
    vec1.x = 1 - 2 * (yy + zz)
    vec1.y = 2 * (xy - zw)
    vec1.z = 2 * (xz + yw)
    vec2.x = 2 * (xy + zw)
    vec2.y = 1 - 2 * (xx + zz)
    vec2.z = 2 * (yz - xw)
    vec3.x = 2 * (xz - yw)
    vec3.y = 2 * (yz + xw)
    vec3.z = 1 - 2 * (xx + yy)
    newMatrix = c4d.Matrix(vecOff, vec1, vec2, vec3)
    return newMatrix
def main():
    new_m = []
    for m in op.GetInstanceMatrices():
        angle = random() * math.pi * 2
        mrot = c4d.utils.MatrixRotY(angle)
        new_m.append(m * mrot)
    op.SetInstanceMatrices(new_m)
    c4d.EventAdd()
    return

    inst = c4d.BaseObject(c4d.Oinstance)
    inst[
        c4d.
        INSTANCEOBJECT_RENDERINSTANCE_MODE] = c4d.INSTANCEOBJECT_RENDERINSTANCE_MODE_MULTIINSTANCE
    inst[c4d.INSTANCEOBJECT_LINK] = op

    nb_clone = 100
    dist = 1000

    matrices = []
    for i in range(nb_clone):
        m = c4d.Matrix()
        pos = c4d.Vector(random() * dist, random() * dist, random() * dist)
        print(pos)
        m.off = pos
        matrices.append(m)
    inst.SetInstanceMatrices(matrices)
    doc.InsertObject(inst)
    c4d.EventAdd()
예제 #8
0
 def __init__(self, _frameTime, frameSuccess):
     self.frameTime = _frameTime
     self.headRotation = c4d.Matrix()
     self.headPosition = c4d.Vector()
     self.blendShapeValues = []
     self.eyeGazeValues = []
     self.markerPositions = []
     self.frameSuccess = frameSuccess
예제 #9
0
    def getSplines(self, origine):
        res = c4d.BaseObject(c4d.Onull)
        for bb in self.bboxes:
            sp = bb.GetSpline(origine)
            sp.InsertUnder(res)
            mg = c4d.Matrix()
            mg.off = bb.centre - origine

        return res
예제 #10
0
def RhinoMatrix_2_C4DMatrix (values):
    """
        Function that converts an array of 16 values coming from a Rhino.Geometry.Transform or a
        Rhino.Geometry.Matrix object (Rhinoceros/Grasshopper3d), to a c4d.Matrix (Cinema4D) object.
    """
    
    # The 4X4_Matrix values as they come from Rhino/Grasshopper, are in a 1D list of 16 elements,
    #structured like that:
    # | M00 | M01 | M02 | M03 | M10 | M11 | M12 | M13 |M20 | M21 | M22 | M23 | M30 | M31 | M32 | M33 |

    if len(values) is not 16:
        return
        
    # Those values correspond to a 4X4 matrix, that was originally structured like that:
    # | M00 | M01 | M02 | M03 |
    # | M10 | M11 | M12 | M13 |
    # | M20 | M21 | M22 | M23 |
    # | M30 | M31 | M32 | M33 |

    # and the meaning of it was :
    # | X_Direction.X | X_Direction.Y | X_Direction.Z | X_Pos |
    # | Y_Direction.X | Y_Direction.Y | Y_Direction.Z | Y_Pos |
    # | Z_Direction.X | Z_Direction.Y | Z_Direction.Z | Z_Pos |
    # |       0       |       0       |       0       |   1   |

    # where X_Direction is the direction of the X Axis (red) of the object,
    # Y_Direction is the direction of the Y Axis (green) of the objects,
    # Z_Direction is the direction of the Z Axis (blue) of the object,
    # and X_Pos,Y_Pos,Z_Pos are the coordinates of the object in World Space

    X = values[0:3]
    Y = values[4:7]
    Z = values[8:11]
    POS = [values[3], values[7], values[11]]

    #Now in Cinema4D, the 4x4 Matrix structures its vectors vertically, and it looks like this:
    # |   0   |       0       |       0       |       1       |
    # | X_Pos | X_Direction.X | Y_Direction.X | Z_Direction.X |
    # | Y_Pos | X_Direction.Y | Y_Direction.Y | Z_Direction.Y |
    # | Z_Pos | X_Direction.Z | Y_Direction.Z | Z_Direction.Z |

    # and in Cinema4D terminology:
    # |   0   |   0   |   0   |   1   |
    # | off.x |  v1.x |  v2.x |  v2.x |
    # | off.y |  v1.y |  v2.y |  v2.y |
    # | off.z |  v1.z |  v2.z |  v2.z |

    # Also in Cinema4D, the Y Axis is the Up Axis, so we need to swap Y and Z in every vector
    # Thus we need to do the following remapping:

    m = c4d.Matrix()
    m.v1  = c4d.Vector( X[0]  , Z[0]  , Y[0]    )
    m.v2  = c4d.Vector( X[1]  , Z[1]  , Y[1]    )
    m.v3  = c4d.Vector( X[2]  , Z[2]  , Y[2]    )
    m.off = c4d.Vector( POS[0], POS[2], POS[1]  )

    return m
예제 #11
0
파일: aabb.py 프로젝트: youdiaozi/c4dtools
    def __init__(self, translation=None):
        super(AABB, self).__init__()
        if translation is None:
            translation = c4d.Matrix()

        self.minv = None
        self.maxv = None
        self.init = False
        self.translation = translation
def CreateGuideFromPoints(obj):
    doc = c4d.documents.GetActiveDocument()  # Get active Cinema 4D document
    points = obj.GetPointS()  # Get object's points
    pointCount = obj.GetPointCount()  # Get point count of object
    positions = []  # Initialize a list for point positions
    for i in range(pointCount):  # Loop through points
        if (points.IsSelected(i)):  # If point is selected
            pointPosition = obj.GetPoint(i)  # Get point's position
            marr = c4d.Matrix()  # Initialize a matrix
            marr.off = pointPosition  # Set matrix position
            marr = op.GetMg() * marr  # Calculate global matrix
            positions.append(marr.off)  # Add point position to the list
    CreateGuide(positions)  # Create the guide
 def checkBind(self):
     matrices = []
     matrix = c4d.Matrix()
     for weightTag in self.allWeightTags:
         curMatrix = weightTag.GetGeomMg()
         if matrix != curMatrix:
             tester = 0
             for k in matrices:
                 if k == curMatrix:
                     tester += 1
             if tester == 0:
                 matrices.append(curMatrix)
     return matrices
예제 #14
0
    def __init__(self, elements=None):
        """

        :type elements: Union[list, c4d.Matrix]
        :param elements:
        """
        if elements is None:
            self.__matrix = c4d.Matrix()
        elif type(elements) is c4d.Matrix:
            self.__matrix = c4d.Matrix(elements)
        else:
            if len(elements) < 12:
                off = c4d.Vector()
            else:
                # Convert to CM
                off = c4d.Vector(elements[-3] * 100, elements[-2] * 100,
                                 elements[-1] * 100)
            v1 = c4d.Vector(elements[0], elements[1], elements[2])
            v2 = c4d.Vector(elements[3], elements[4], elements[5])
            v3 = c4d.Vector(elements[6], elements[7], elements[8])
            # Convert to LHS
            self.__matrix = _MATRIX_CV * c4d.Matrix(off, v1, v2,
                                                    v3) * _MATRIX_CV
예제 #15
0
def multiInstanceFromPoints(pts, obj_ref=None):
    inst = c4d.BaseObject(c4d.Oinstance)
    inst[
        c4d.
        INSTANCEOBJECT_RENDERINSTANCE_MODE] = c4d.INSTANCEOBJECT_RENDERINSTANCE_MODE_MULTIINSTANCE
    inst[c4d.INSTANCEOBJECT_LINK] = obj_ref

    matrices = []

    for pt in pts():
        m = c4d.Matrix()
        m.off = pt
        matrices.append(m)
    return inst
예제 #16
0
def main():
    renderer = 'arnold'
    c4dScale = 100
    
    filePath = c4d.storage.LoadDialog()
    
    f = open(filePath, 'r')
    
    data = json.load(f)  
    for lname in data:
        print lname
        light = data[lname]
        
        if(renderer == 'arnold'):
            c4dLight = c4d.BaseObject(1030424)
            c4dLight.SetName(lname)
            doc.InsertObject(c4dLight)
            
            objMatrix = c4d.Matrix()
            objMatrix.v1 = c4d.Vector(light['matrix'][0], light['matrix'][1], -light['matrix'][2])
            objMatrix.v2 = c4d.Vector(light['matrix'][4], light['matrix'][5], -light['matrix'][6])
            objMatrix.v3 = c4d.Vector(-light['matrix'][8], -light['matrix'][9], light['matrix'][10])
            objMatrix.off = c4d.Vector(light['matrix'][12], light['matrix'][13], -light['matrix'][14]) * c4dScale
            c4dLight.SetMg(objMatrix)
            
            c4dLight[2010942260] = c4d.Vector(light['color'][0], light['color'][1], light['color'][2])
            
            c4dLight[67722820] = light['intensity']
            c4dLight[1502846298] = light['normalize']
            
            c4dLight[1632353189] = light['soft_edge']
            c4dLight[1730825676] = light['spread']
            
            if light['type'] == 'point':
                c4dLight[c4d.C4DAI_LIGHT_TYPE] = 381492518
            elif light['type'] == 'spot':
                c4dLight[c4d.C4DAI_LIGHT_TYPE] = 876943490
            elif light['type'] == 'quad':
                c4dLight[c4d.C4DAI_LIGHT_TYPE] = 1218397465
                c4dLight[2034436501] = light['width'] * c4dScale
                c4dLight[2120286158] = light['height'] * c4dScale
                c4dLight[1641633270] = light['roundness']
            elif light['type'] == 'disk':
                c4dLight[c4d.C4DAI_LIGHT_TYPE] = 998592185           
            elif light['type'] == 'cylinder':
                c4dLight[c4d.C4DAI_LIGHT_TYPE] = 1944046294
        
    f.close()
    
    c4d.EventAdd()
예제 #17
0
def moveboids(c):
   
    bvel[c] += rule1(c) + rule2(c) + rule3(c) + rule4(c)
    bvel[c] = limitspeed(bvel[c], boid_maxspeed)

    tp.SetVelocity(c, bvel[c])

    vel=bvel[c].GetNormalized()

    side = c4d.Vector(c4d.Vector(0,1,0).Cross(vel)).GetNormalized()
    up = vel.Cross(side)
    m = c4d.Matrix(c4d.Vector(0), side, up, vel)

    tp.SetAlignment(c, m)
    tp.SetPosition(c, bpos[c] + bvel[c])
예제 #18
0
def randomize_cuts(dest, iterations, seed):
    # Create a random generator with the specified seed.
    r = random.Random(seed)

    # Read the matrix, mid-point and size from the target
    # object.
    mat = dest.GetMg()
    mid = dest.GetMp()
    rad = dest.GetRad()

    # We need to offset the cutting plane so that it is surely
    # not inside of the target object.
    offset_distance = rad.GetLength() * 4

    # Helper function to get a random value in range -1..1
    rand11 = lambda: r.random() * 2 - 1

    # Helper function to get a Vector with all three components
    # in the range of -1..1.
    randv = lambda: c4d.Vector(rand11(), rand11(), rand11())
    for __ in xrange(iterations):
        # Step 1) Choose a random point inside the bounding box
        # of the destination object. We do this by multiplying
        # each component of the `rad` vector with a random value
        # between -1 and 1.
        off = mid + rad ^ randv()

        # Step 2) Choose a random cutting plane spanned by two
        # vectors.  We use the cross-product to ensure they are
        # perpendicular.
        v1 = randv()
        v2 = v1.Cross(randv())

        # Step 3): Move the cutting plane offset away from the
        # object into the right direction (so the plane is still
        # cutting through the object).
        direction = (v1 + v2) * 0.5
        off -= direction * offset_distance

        # Step 4) Multiply with the target object's global matrix
        # to adjust to its offset and rotation. The direction
        # vectors should not be offset, so we use the no-offset
        # matrix.
        rot = c4d.Matrix(off, v1, v2, v2.Cross(v1))
        rot = rot.GetNormalized() * mat

        # Cut the object.
        cut(dest, rot.off, rot.off, rot.v1, rot.v2)
예제 #19
0
def CenterAxis(obj): # Center object's axis
    doc = c4d.documents.GetActiveDocument() # Get active Cinema 4D document
    points = [] # Initialize empty list
    pointCount = obj.GetPointCount() # Get object's point count
    for i in range(0, pointCount): # Loop through points
        points.append(obj.GetPoint(i)) # Add point to points list
    matrix = obj.GetMg() # Get object's global matrix
    axis = obj.GetAbsPos() # Get object's absolute position
    center = obj.GetMp() # Get Object's bounding box center in local space
    difference = axis - (axis + center) # Calculate difference
    if difference != c4d.Vector(0): # If there is a difference
        for i in xrange(pointCount): # Loop through object's points
            obj.SetPoint(i, points[i] + difference) # Set new point position
        obj.Message(c4d.MSG_UPDATE) # Send update message
        obj.SetMg(c4d.Matrix((matrix * center),
            matrix.v1, matrix.v2, matrix.v3)) # Set new matrix for the object
def GuideSpline(cam, length):
    positions = []
    pos1 = cam.GetMg().off

    m = c4d.Matrix()
    m.off = c4d.Vector(0, 0, length)
    mpos2 = cam.GetMg() * m

    pos2 = mpos2.off
    positions.append(pos1)
    positions.append(pos2)

    splineObject = c4d.SplineObject(2, c4d.SPLINETYPE_LINEAR)
    splineObject.SetAllPoints(positions)

    return splineObject
예제 #21
0
def main():
    active_objects = doc.GetActiveObjects(
        c4d.GETACTIVEOBJECTFLAGS_SELECTIONORDER)
    if not active_objects:
        return

    # Retrieve the target's global position
    target = active_objects.pop()
    target_mg = target.GetMg()
    target_pos = target_mg.off

    doc.StartUndo()
    for obj in active_objects:
        if not obj:
            continue

        # Store object's starting global matrix and position for calculations
        obj_mg = obj.GetMg()
        obj_pos = obj_mg.off

        # Calculate direction to target
        obj_to_target = (target_pos - obj_pos).GetNormalized()
        up_vector = c4d.Vector(0.0, 1.0, 0.0)  # Try to point the Y-Axis up

        # Build a global matrix to orient towards the object
        aim_mg = c4d.Matrix()
        aim_mg.v3 = obj_to_target  # Point Z-Axis at target
        aim_mg.v2 = up_vector  # Force Y-Axis to point up at world Y
        aim_mg.v1 = up_vector.Cross(obj_to_target).GetNormalized(
        )  # X-Axis is perpindicular to plane formed by Z and Y
        aim_mg.v2 = obj_to_target.Cross(aim_mg.v1).GetNormalized(
        )  # Recalculate Y-Axis to be actually perpindicular to X and Z.

        # Move and Scale matrix to match how object started
        aim_mg.off = obj_mg.off
        aim_mg.v1 *= obj_mg.v1.GetLength()
        aim_mg.v2 *= obj_mg.v2.GetLength()
        aim_mg.v3 *= obj_mg.v3.GetLength()

        # Rotate object to point at target
        doc.AddUndo(c4d.UNDOTYPE_CHANGE, obj)
        obj.SetMg(aim_mg)

    doc.EndUndo()
    c4d.EventAdd()
예제 #22
0
def main():
    poly = doc.GetFirstObject()
    plan = poly.GetNext()

    mg = poly.GetMg()
    p1, p2, p3 = [p * mg for p in poly.GetAllPoints()]

    dir1 = (p2 - p1).GetNormalized()
    dir2 = (p3 - p1).GetNormalized()

    v2 = dir1.Cross(dir2)
    v3 = dir1
    v1 = v3.Cross(v2)
    off = p1

    mg = c4d.Matrix(off, v1, v2, v3)
    plan.SetMg(mg)
    c4d.EventAdd()
예제 #23
0
파일: utils.py 프로젝트: youdiaozi/c4dtools
def move_object_axis(obj, new_matrix=c4d.Matrix()):
    r"""
    *New in 1.3.0*: Normalize the axis of an object by adjusting the local
    matrix of the child objects and, if *obj* is a polygon object, it's
    points. Simulates the 'Axis Move' mode in Cinema.

    :param obj: :class:`c4d.BaseObject`
    :param new_matrix: :class:`c4d.Matrix`
    """

    mat = ~new_matrix * obj.GetMl()
    if obj.CheckType(c4d.Opoint):
        points = [p * mat for p in obj.GetAllPoints()]
        obj.SetAllPoints(points)
        obj.Message(c4d.MSG_UPDATE)

    for child in obj.GetChildren():
        child.SetMl(mat * child.GetMl())
    obj.SetMl(new_matrix)
예제 #24
0
    def __init__(self):
        self.rotationVector = c4d.Vector()
        self.positionVector = c4d.Vector()
        self.frameSuccess = 0
        self.frameTime = 0
        self.calcObj = c4d.BaseObject(c4d.Onull)
        self.headMatrix = c4d.Matrix()
        self.headTarget = [0, 1, 2, 3, 4, 5, 6]
        self.blendShapes = []
        self.eyeGazeValues = []
        self.registeredBlendShapeNames = []
        self.connected = 0

        shapeCnt = 0
        while shapeCnt < 48:
            shapeCnt += 1
            self.blendShapes.append(0.0)
            self.registeredBlendShapeNames.append("")
        self.eyesTarget = [0, 1, 2, 3]
        self.markers = []
예제 #25
0
def main():
    md = mo.GeGetMoData(op)
    if md is None: return False

    cnt = md.GetCount()
    marr = md.GetArray(c4d.MODATA_MATRIX)

    fall = md.GetFalloffs()

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP
    sock.bind((UDP_IP, UDP_PORT))
    data, addr = sock.recvfrom(1024)  # buffer size is 1024 bytes
    #print "received message:", data
    sock.close()

    fingerdictC4D = eval(data)  # convert to dictionary again from string
    fingers = ['Thumb', 'Index', 'Middle', 'Ring',
               'Pinky']  # list to sort the dictionary
    #get position y of each unicorn
    marrNew = []  # new vectors matrix
    for im, m in enumerate(marr):

        positions = m.off  #obtain position data
        xpos = positions[0]
        ypos = positions[1]
        ypos = fingerdictC4D[fingers[im]]
        zpos = positions[2]

        off = c4d.Vector(xpos, ypos, zpos)
        newMatrix = c4d.Matrix(off)
        marrNew.append(newMatrix)

        #set new position vector with new leap yposiiton
        #create new matrix
        #append matrix to empty list
    #set new y position for each clone

    setNewArr = md.SetArray(c4d.MODATA_MATRIX, marrNew,
                            False)  # set new cloner matrix
예제 #26
0
#!usr/bin/python
# -*- coding: utf-8 -*-

import c4d

context_doc = c4d.documents.GetActiveDocument()
context_obj = context_doc.GetActiveObject()

ID_DIRS = [c4d.VECTOR_X, c4d.VECTOR_Y, c4d.VECTOR_Z]
ID_TYPES = [
    c4d.ID_BASEOBJECT_REL_POSITION, c4d.ID_BASEOBJECT_REL_ROTATION,
    c4d.ID_BASEOBJECT_REL_SCALE
]

_MATRIX_CV = c4d.Matrix(v2=c4d.Vector(0, 0, 1), v3=c4d.Vector(0, 1, 0))


class Matrix(object):
    def __init__(self, elements=None):
        """

        :type elements: Union[list, c4d.Matrix]
        :param elements:
        """
        if elements is None:
            self.__matrix = c4d.Matrix()
        elif type(elements) is c4d.Matrix:
            self.__matrix = c4d.Matrix(elements)
        else:
            if len(elements) < 12:
                off = c4d.Vector()
예제 #27
0
def main():
    colors_objects_mgs = {}

    doc.StartUndo()

    c4d.StatusSetText("[1/2]: Collating by color.")
    c4d.StatusSetSpin()

    # Store objects by color
    obj = doc.GetFirstObject()
    while obj:
        color = obj[c4d.ID_BASEOBJECT_COLOR]
        color_string = repr(color)
        mg = obj.GetMg()

        obj_mg = (obj, mg)

        if color_string in colors_objects_mgs.keys():
            colors_objects_mgs[color_string].append(obj_mg)
        else:
            colors_objects_mgs[color_string] = [obj_mg]

        obj = GetNextObject(obj)

    c4d.StatusSetText("[2/2]: Grouping Objects.")
    # Build groups of objects by color
    pred_null = None
    for color_string, obj_mg_list in colors_objects_mgs.iteritems():
        # Find the center position of the objects
        average_pos = c4d.Vector(0.0)

        for obj, mg in obj_mg_list:
            average_pos += mg.off

        average_pos /= float(len(obj_mg_list))

        # Create a null centered between the objects
        null_obj = c4d.BaseObject(c4d.Onull)

        # Make it the same color as the objects
        null_obj[c4d.ID_BASEOBJECT_USECOLOR] = 1  # Automatic Mode
        null_obj[c4d.ID_BASEOBJECT_COLOR] = eval("c4d." + color_string)
        null_obj[c4d.NULLOBJECT_ICONCOL] = True

        # Center the null
        center_mg = c4d.Matrix()
        mg.off = average_pos

        # Ensure nulls are inserted roughly in the same order colors first occurred in the scene.
        doc.InsertObject(null_obj, pred=pred_null)
        pred_null = null_obj

        # Center the null
        null_obj.SetMg(center_mg)
        doc.AddUndo(c4d.UNDOTYPE_NEW, null_obj)

        # Move objects of the came color under the new null
        pred = None
        for obj, mg in obj_mg_list:
            doc.AddUndo(c4d.UNDOTYPE_CHANGE, obj)
            obj.Remove()
            doc.InsertObject(obj, parent=null_obj, pred=pred)
            obj.SetMg(mg)
            pred = obj

    doc.EndUndo()
    c4d.EventAdd()
    c4d.StatusClear()
예제 #28
0
    def connect_objects(self, objects):
        '''
    Joins all PolygonObjects and SplineObjects the list *objects*
    into a single object using the Cinema 4D "Connect Objects"
    command.

    This method will move *all* objects to the internal document
    temporarily before joining them into one object.

    :param objects: A list of :class:`c4d.BaseObject`.
    :return: The new connected object.
    :requires:
      - The *Kernel* must be initialized with a document.
    :raise RuntimeError: If the *Kernel* was not initialized
      with a document.
    :raise TypeError:
        - If *objects* is not iterable
        - If an element of *objects* is not a BaseObject
    :raise Error: When an unexpected error occurs.


    .. important:: The returned object axis is located at the world
      center. If you want to mimic the real "Connect Objects" command
      in that it positions the axis at the location of the first
      object in the list, use the :func:`nr.c4d.utils.move_axis`
      function.
    '''

        self._assert_doc('connect_objects')
        if not isinstance(objects, collections.Iterable):
            raise TypeError("<objects> must be iterable", type(objects))

        doc = self._doc
        root = c4d.BaseObject(c4d.Onull)

        with UndoHandler() as undo:
            undo.location(root)
            doc.InsertObject(root)

            # Move all objects under the new root object temporarily.
            for obj in objects:
                if not isinstance(obj, c4d.BaseObject):
                    message = "element of <objects> must be BaseObject"
                    raise TypeError(message, type(obj))

                undo.location(obj)
                undo.matrix(obj)

                mg = obj.GetMg()
                obj.Remove()
                obj.InsertUnder(root)
                obj.SetMl(mg)

            result = c4d.utils.SendModelingCommand(c4d.MCOMMAND_JOIN,
                                                   root.GetChildren(),
                                                   doc=doc)

        if not result:
            raise Error("Connect Objects failed")

        result[0].SetMl(c4d.Matrix())
        return result[0]
    uvSeams.CopyTo(edgeSelect)

    # Resets the previous document mode
    doc.SetMode(docMode)

    # Pushes an update event to Cinema 4D
    c4d.EventAdd()


if __name__ == "__main__":
    main()

import c4d

initialMatrices = []
initialMatrices.append(c4d.Matrix(c4d.Vector(0)))
initialMatrices.append(c4d.Matrix(c4d.Vector(1)))
initialMatrices.append(c4d.Matrix(c4d.Vector(2)))

print("Initial Data")
for mat in initialMatrices:
    print(mat)

print("Transform them to str")


def vecToDict(vector):
    return {"x": vector.x, "y": vector.y, "z": vector.z}


def matToDict(matricesList):
예제 #30
0
def set_world_pos(obj, xyz):
    mg = obj.GetMg()
    v1, v2, v3 = mg.v1, mg.v2, mg.v3
    off_new = c4d.Vector(xyz[0], xyz[1], xyz[2])
    c4d_mat_mg = c4d.Matrix(off_new, v1, v2, v3)
    obj.SetMg(c4d_mat_mg)