def addValueAtFrame(xtrack, ytrack, ztrack, XYFrameNum, ZFrameNum, fps,
                    valueVec):

    # linear interpolation
    animation_interpolation_val = 465001092

    # Add a key to each CubeSat linear position tracks
    xtrack = xtrack.GetCurve()
    xkey = xtrack.AddKey(c4d.BaseTime(XYFrameNum, fps))['key']
    xkey.SetValue(xtrack, valueVec[0])

    # set the track position variation to linear
    c4d.CallCommand(animation_interpolation_val)

    ytrack = ytrack.GetCurve()
    ykey = ytrack.AddKey(c4d.BaseTime(XYFrameNum, fps))['key']
    ykey.SetValue(ytrack, valueVec[1])

    # set the track position variation to linear
    c4d.CallCommand(animation_interpolation_val)

    ztrack = ztrack.GetCurve()
    zkey = ztrack.AddKey(c4d.BaseTime(ZFrameNum, fps))['key']
    zkey.SetValue(ztrack, valueVec[2])

    # set the track position variation to linear
    c4d.CallCommand(animation_interpolation_val)
def main():
    c4d.StopAllThreads()
    doc = c4d.documents.GetActiveDocument()
    fps = doc.GetFps()
    fromTime = doc.GetMinTime().GetFrame(fps)
    toTime = doc.GetMaxTime().GetFrame(fps)
    animLength = toTime - fromTime + 1
    filePath = c4d.storage.SaveDialog()
    filePath, objName = os.path.split(filePath)
    objName = objName + "_"
    filePath = filePath + "\\"

    for f in range(0, animLength):
        doc.SetTime(c4d.BaseTime(fromTime, fps) + c4d.BaseTime(f, fps))
        c4d.EventAdd(c4d.EVENT_FORCEREDRAW)
        c4d.DrawViews(c4d.DRAWFLAGS_FORCEFULLREDRAW)

        c4d.StatusSetText("Exporting " + str(f) + " of " + str(animLength))
        c4d.StatusSetBar(100.0 * f / animLength)

        c4d.CallCommand(16768, 16768)
        c4d.CallCommand(100004794, 100004794)
        c4d.CallCommand(100004787)

        fileName = filePath + objName + str(f) + ".obj"
        savingresult = c4d.documents.SaveDocument(doc, fileName,
                                                  c4d.SAVEDOCUMENTFLAGS_0,
                                                  c4d.FORMAT_OBJ2EXPORT)

        c4d.CallCommand(12105, 12105)
        c4d.CallCommand(12105, 12105)
        c4d.CallCommand(12105, 12105)

    c4d.StatusClear()
    gui.MessageDialog('Exporting to' + filePath + ' done')
示例#3
0
def main():
    random.seed(24)
    PS = doc.GetParticleSystem()
    cframe = doc.GetTime().GetFrame(doc.GetFps())  #10->300,1->30
    N = PS.NumParticles()
    if cframe == 0:
        ids = range(N)
        life = [c4d.BaseTime(10.0)] * N
        map(PS.SetLife, ids, life)
    else:
        #set default ages for everyone
        ids = range(N)
        dval = 0.
        ages = [c4d.BaseTime(dval)] * N
        map(PS.SetAge, ids, ages)
        #randomly change life on a pacth, always same patch?
        ids = range(int(N / 3), int(N / 2))
        nN = int(len(ids))
        val = cframe / 30.0  #random.random()*10.0
        ages = [c4d.BaseTime(val)] * nN
        map(PS.SetAge, ids, ages)

        ids = range(int(N / 2), int(N))
        nN = int(len(ids))
        val = cframe / 60.0  #random.random()*10.0
        ages = [c4d.BaseTime(val)] * nN
        map(PS.SetAge, ids, ages)
def SequenceTracks(keyMod):
    tracks = GetTracks()  # Get selected tracks
    prevTrack = tracks[0]  # Get the first selected track
    prevOut = prevTrack.GetCurve().GetEndTime()  # Get out time

    if keyMod == "None":
        gap = c4d.BaseTime(1.0 / doc.GetFps())
    elif keyMod == "Shift":
        inp = gui.InputDialog('Gap')  # Store user given value
        gap = c4d.BaseTime(1.0 / doc.GetFps() * float(inp))  # Gap
    elif keyMod == "Ctrl":
        tracks.reverse()
        gap = c4d.BaseTime(1.0 / doc.GetFps())
    elif keyMod == "Ctrl+Shift":
        tracks.reverse()
        inp = gui.InputDialog('Gap')  # Store user given value
        gap = c4d.BaseTime(1.0 / doc.GetFps() * float(inp))  # Gap

    for i in range(1, len(tracks)):  # Iterate through tracks
        curve = tracks[i].GetCurve()  # Get current curve
        startTime = curve.GetStartTime()
        endTime = curve.GetEndTime()
        sub = prevOut - (startTime - gap)  # Get time subtraction
        if sub.Get() < 0:  # If subtraction is negative
            sub = (startTime - gap) - prevOut  # New subtraction
            for i in range(0, sub.GetFrame(doc.GetFps())):
                MoveKeys(curve, -1)  # Move keys one frame to the left
        else:  # Otherwise
            for i in range(0, sub.GetFrame(doc.GetFps())):
                MoveKeys(curve, 1)  # Move keys one frame to the right
        prevOut = curve.GetEndTime()  # Get new out time
def main():
    # Creates the object in memory
    obj = c4d.BaseObject(c4d.Ocube)

    # Creates the track in memory. Defined by it's DescID
    trackY = c4d.CTrack(obj, c4d.DescID(c4d.DescLevel(c4d.ID_BASEOBJECT_POSITION, c4d.DTYPE_VECTOR, 0),
                                        c4d.DescLevel(c4d.VECTOR_Y, c4d.DTYPE_REAL, 0)))

    # Gets curves for the track
    curveY = trackY.GetCurve()

    # Creates a key in the Y curve with value 0 at 0 frame with a spline interpolation
    keyA, keyAIndex = CreateKey(curveY, c4d.BaseTime(0), value=0, interpolation=c4d.CINTERPOLATION_SPLINE)

    # Retrieves time at frame 10
    keyBTime = c4d.BaseTime(10, doc.GetFps())

    # Creates another key in the Y curve with value 100 at 10 frame with a spline interpolation
    keyB, keyBIndex = CreateKey(curveY, keyBTime, value=100, interpolation=c4d.CINTERPOLATION_SPLINE)

    # Inserts the track containing the Y curve to the object
    obj.InsertTrackSorted(trackY)

    # Inserts the object in document
    doc.InsertObject(obj)

    # Pushes an update event to Cinema 4D
    c4d.EventAdd()
示例#6
0
def push_key(curve, key, key_data):
    key.SetTime(curve, c4d.BaseTime(key_data[0]))
    key.SetValue(curve, key_data[1])
    key.SetInterpolation(curve, INTERPOLATION[key_data[6]])
    key.SetTimeLeft(curve, c4d.BaseTime(key_data[2]))
    key.SetTimeRight(curve, c4d.BaseTime(key_data[4]))
    key.SetValueLeft(curve, key_data[3])
    key.SetValueRight(curve, key_data[5])
    return key
示例#7
0
def new_rig(obj, cachetype):
    #create a Python tag and attach it to the selected tag's object
    pythontag = c4d.BaseTag(c4d.Tpython)

    #set the Python code inside the tag
    pythontag[
        c4d.TPYTHON_CODE] = copyright + pythontagcode + pythontagcode_dict[
            cachetype]

    #add userdata to the Python tag
    userdata = c4d.GetCustomDataTypeDefault(c4d.DTYPE_REAL)
    userdata[c4d.DESC_NAME] = "Frame"
    pythontag.AddUserData(userdata)
    pythontag[c4d.ID_USERDATA, 1] = 0.0

    #add an animation track to the userdata we just created
    track = c4d.CTrack(
        pythontag,
        c4d.DescID(c4d.DescLevel(c4d.ID_USERDATA, c4d.DTYPE_SUBCONTAINER, 0),
                   c4d.DescLevel(1, c4d.DTYPE_REAL, 0)))
    pythontag.InsertTrackSorted(track)
    #get the curve of our new track (we'll attach keyframes to this curve)
    curve = track.GetCurve()
    #make some keyframes, setting their time, value and curve
    key1 = c4d.CKey()
    key1.SetTime(curve, doc.GetMinTime())
    key1.SetValue(curve, doc.GetMinTime().Get() * doc.GetFps())
    key1.SetTimeRight(curve, c4d.BaseTime(0.5))

    key2 = c4d.CKey()
    key2.SetTime(curve, doc.GetMaxTime())
    key2.SetValue(curve, doc.GetMaxTime().Get() * doc.GetFps())
    key2.SetTimeLeft(curve, c4d.BaseTime(-0.5))

    #add the keyframes to the curve
    curve.InsertKey(key1)
    curve.InsertKey(key2)

    #set the Python tag's priority
    priority = c4d.PriorityData()
    priority.SetPriorityValue(c4d.PRIORITYVALUE_MODE, c4d.CYCLE_GENERATORS)
    priority.SetPriorityValue(c4d.PRIORITYVALUE_PRIORITY, -1)
    pythontag[c4d.EXPRESSION_PRIORITY] = priority

    #add the Python tag to the selected object, and add an undo
    doc.StartUndo()
    obj.InsertTag(pythontag)
    doc.AddUndo(c4d.UNDOTYPE_NEW, pythontag)
    doc.EndUndo()

    c4d.EventAdd(c4d.EVENT_FORCEREDRAW)

    print "Cache retimer successfully added to " + obj.GetName() + "!"
示例#8
0
def SetKeys(keyData, keyMod):
    tracks = GetKeys(keyMod)  # Get selected keys
    for track in tracks:
        keys = track[1]
        for i, k in enumerate(keys):  # Iterate through tracks
            diff = 1.0
            if i < len(keyData) - 1:  # Not the last key
                valueDiffRef = float(keyData[i]['value']) - float(
                    keyData[i + 1]['value'])
                valueDiffOrig = k.GetValue() - k.GetNext().GetValue()
                if valueDiffRef != 0:
                    if valueDiffOrig != 0:
                        diff = valueDiffOrig / valueDiffRef  # Fixed
            if i == len(keyData) - 1:  # The last key
                valueDiffRef = float(keyData[i - 1]['value']) - float(
                    keyData[i]['value'])
                valueDiffOrig = k.GetPred().GetValue() - k.GetValue()
                if valueDiffRef != 0:
                    if valueDiffOrig != 0:
                        diff = valueDiffOrig / valueDiffRef  # Fixed
                        print "end diff " + str(diff)

            leftValue = float(keyData[i]['leftvalue']) * diff
            rightValue = float(keyData[i]['rightvalue']) * diff
            leftTime = c4d.BaseTime(float(keyData[i]['lefttime']))
            rightTime = c4d.BaseTime(float(keyData[i]['righttime']))

            doc.AddUndo(c4d.UNDOTYPE_CHANGE, k)  # Record undo
            curve = k.GetCurve()
            k.SetInterpolation(curve, c4d.CINTERPOLATION_SPLINE)
            k.ChangeNBit(c4d.NBIT_CKEY_AUTO,
                         CheckBit(keyData[i]['autotan']))  # Auto Tangents
            k.SetAutomaticTangentMode(curve, int(keyData[i]['slope']))  # Slope
            k.ChangeNBit(c4d.NBIT_CKEY_CLAMP,
                         CheckBit(keyData[i]['clamp']))  # Clamp
            k.ChangeNBit(c4d.NBIT_CKEY_REMOVEOVERSHOOT,
                         CheckBit(
                             keyData[i]['overshoot']))  # Remove Overshooting
            k.ChangeNBit(c4d.NBIT_CKEY_WEIGHTEDTANGENT,
                         CheckBit(keyData[i]['weighted']))  # Weighted Tangent
            k.ChangeNBit(
                c4d.NBIT_CKEY_LOCK_O,
                CheckBit(keyData[i]['locktanangles']))  # Lock Tangent Angles
            k.ChangeNBit(
                c4d.NBIT_CKEY_LOCK_L,
                CheckBit(keyData[i]['locktanlengths']))  # Lock Tangent Lengths
            k.ChangeNBit(c4d.NBIT_CKEY_KEEPVISUALANGLE,
                         CheckBit(
                             keyData[i]['keepvisangle']))  # Keep Visual Angle
            k.SetValueLeft(curve, leftValue)
            k.SetValueRight(curve, rightValue)
            k.SetTimeLeft(curve, leftTime)
            k.SetTimeRight(curve, rightTime)
示例#9
0
def main():
    # Retrieves the FPS of the document
    fps = doc.GetFps()

    # Creates a first marker
    firstMarker = c4d.documents.AddMarker(doc, None, c4d.BaseTime(30, fps), "First Marker")

    # Creates a second marker with a duration of 5 frame
    secondMarker = c4d.documents.AddMarker(doc, None, c4d.BaseTime(27, fps), "Second Marker")
    secondMarker[c4d.TLMARKER_LENGTH] = c4d.BaseTime(5, fps)

    # Pushes an update event to Cinema 4D
    c4d.EventAdd()
示例#10
0
    def Execute(self, tag, doc, op, bt, priority, flags):
        dname = doc.GetDocumentName()
        if hasattr(c4d, 'mv'):
            if c4d.mv.has_key(dname):
                self.epmv = c4d.mv[dname]
                self.mv = self.epmv.mv
            else:
                self.epmv = None
                self.mv = None
            #print "rexectute", self.mv
        else:
            self.epmv = None
            self.mv = None
        sel = doc.GetSelection()
        if hasattr(self.mv, 'art'):
            vp = doc.GetActiveBaseDraw()
            self.epmv.helper.updateImage(self.mv, viewport=vp)
        if self.epmv.synchro_timeline:
            traj = self.epmv.gui.current_traj
            t = c4d.BaseTime()
            fps = doc.GetFps()
            #getCurrent time
            frame = doc.GetTime().GetFrame(fps)
            st, ft = self.epmv.synchro_ratio
            if (frame % ft) == 0:
                step = frame * st
                self.epmv.helper.updateData(self.epmv, traj, step)


#                self.epmv.gui.updateViewer()
        else:
            self.epmv.helper.updateCoordFromObj(self.mv, sel, debug=True)
        #this update should recognise the displayed object and update consequently
        #like update bond geometry,loft ss, constraint the move ? calcul_energy?
        return c4d.EXECUTIONRESULT_OK
def main():
    
    path = s.LoadDialog(c4d.FILESELECTTYPE_ANYTHING, "Sound file", c4d.FILESELECT_LOAD)
    folderPath, fileName = os.path.split(path)

    doc = c4d.documents.GetActiveDocument() # Get active Cinema 4D document    
    time = c4d.BaseTime(doc.GetTime().Get()) # Get current time
    
    null = c4d.BaseObject(c4d.Onull) # Initialize a null
    null.SetName("Sound: "+fileName) # Set name
    null[c4d.NULLOBJECT_DISPLAY] = 14 # Set 'Display' to 'None'
    null[c4d.ID_BASELIST_ICON_FILE] = "440000255" # Set icon
    null[c4d.ID_BASELIST_ICON_COLORIZE_MODE] = 2 # Set 'Icon Color' to 'Display Color'
    null[c4d.ID_BASEOBJECT_USECOLOR] = 2 # Set 'Display Color' to 'On'
    null[c4d.ID_BASEOBJECT_COLOR] = c4d.Vector(140.0/255.0, 203.0/255.0, 1.0)
    null[c4d.ID_BASELIST_ICON_COLOR] = c4d.Vector(140.0/255.0, 203.0/255.0, 1.0)
    doc.InsertObject(null) # Insert null to the document   

    desc = c4d.DescID(c4d.DescLevel(c4d.CTsound, c4d.CTsound, 0))
    SoundTrack = c4d.CTrack(null, desc) # Initialize a sound Track
    null.InsertTrackSorted(SoundTrack) # Insert the sound track to the object
    SoundTrack[c4d.CID_SOUND_NAME] = path # Set sou
    SoundTrack[c4d.CID_SOUND_START] = time

    c4d.EventAdd()
def main():

    global tp
    global doc
    global frame
    global bpos
    global bvel
    
    frame = doc.GetTime().GetFrame(doc.GetFps())
    if frame==0:
        tp.FreeAllParticles()
        tp.AllocParticles(boids_number)    
    
    lt = c4d.BaseTime(1000)

    bpos = []
    bvel = []

    for i in tp.GetParticles():
        tp.SetLife(i, lt)

        bpos.append(tp.Position(i))
        bvel.append(tp.Velocity(i))

        moveboids(i)
    
    set_target()    
    movetarget()   
示例#13
0
def resetAllObjectsAtBeginning(objList=None):
    for curObj in objList:
        #if curObj.GetTag(c4d.Tweights):#	
            #c4d.documents.GetActiveDocument().SetActiveObject(curObj)
            #c4d.CallCommand(1019937)
            #c4d.DrawViews( c4d.DA_ONLY_ACTIVE_VIEW|c4d.DA_NO_THREAD|c4d.DA_NO_REDUCTION|c4d.DA_STATICBREAK )
            #c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)
            #c4d.documents.GetActiveDocument().SetTime(c4d.documents.GetActiveDocument().GetTime())
            #c4d.EventAdd(c4d.EVENT_ANIMATE)
        if curObj.GetTag(c4d.Tposemorph):#	reset morphtags
            all_tags=curObj.GetTags()#get all tags applied to object
            for morphtag in all_tags:#do for each tag:
                if morphtag.GetType()==c4d.Tposemorph:#do if the tag is a morphtag
                    if morphtag.GetMode()==1:#do if the tag is in animation-mode:
                        exportData.doc.SetTime(c4d.BaseTime(0, exportData.doc.GetFps()))
                        c4d.DrawViews( c4d.DA_ONLY_ACTIVE_VIEW|c4d.DA_NO_THREAD|c4d.DA_NO_REDUCTION|c4d.DA_STATICBREAK )
                        c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)
                        exportData.doc.SetTime(exportData.doc.GetTime())
                        c4d.EventAdd(c4d.EVENT_ANIMATE)
                        for track in morphtag.GetCTracks():
                            curve = track.GetCurve()
                            if curve.GetKeyCount()==0:
                               pass#print "skipped morphpose"
                            if curve.GetKeyCount()>0:
                               curve.GetKey(0).SetValue(curve,0.0)
        resetAllObjectsAtBeginning(curObj.GetChildren())
示例#14
0
def Bake(source, target):
    """ Bake function  """

    doc = c4d.documents.GetActiveDocument() # Get active Cinema 4D document
    fps = doc.GetFps() # Get Frame Rate
    startFrame = doc.GetLoopMinTime().GetFrame(fps) # Get first frame of Preview Range
    endFrame = doc.GetLoopMaxTime().GetFrame(fps) # Get last frame of Preview Range

    desc = c4d.DescID(c4d.DescLevel(c4d.CTpla, c4d.CTpla, 0))
    PLAtrack = c4d.CTrack(target, desc) # Initialize a PLA track
    target.InsertTrackSorted(PLAtrack) # Insert PLA track to the object

    curve = PLAtrack.GetCurve() # Get Curve of the CTrack

    for i in range(startFrame, endFrame+1): # Iterate through Preview Range
        SetCurrentFrame(i, doc) # Set current frame
        frame = doc.GetTime().GetFrame(fps) # Get current frame

        points = source.GetAllPoints()
        
        #key.SetValue(curve, value)
        #key.SetGeData(curve, value) # Keyframe value needs to be set with SetGeData

        currentTime = c4d.BaseTime(frame, fps) # Get current time
        #points = source.GetAllPoints()
        key = curve.AddKey(currentTime)["key"]

        target.SetAllPoints(points)
        target.Message(c4d.MSG_UPDATE)
        PLAtrack.FillKey(doc, target, key)
 def _goToFrame(self, frame):
     time = c4d.BaseTime(frame, self.fps)
     self.doc.SetTime(time)
     self.doc.ExecutePasses(
         None, True, True, True,
         c4d.BUILDFLAGS_0)  #try BUILDFLAGS_INTERNALRENDERER
     c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)  #update timeline
def SetCurrentFrame(frame, doc):
    """ Changes editor's current frame to  """

    doc.SetTime(c4d.BaseTime(float(frame)/doc.GetFps())) # Set current time to given frame
    doc.ExecutePasses(None, True, True, True, 0) # Animate the current frame of the document
    c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED) # Send a synchronous event message that time has changed
    return
示例#17
0
def main():
    fps = doc.GetFps()  #get fps number
    frame = 0  #set the start frame
    maxFrame = doc.GetLoopMaxTime().GetFrame(fps)  #get all frame

    #For each frame
    while frame != maxFrame + 1:
        doc.SetTime(c4d.BaseTime(frame, fps))  #change time
        c4d.EventAdd()  #Update scene
        c4d.DrawViews(c4d.DRAWFLAGS_FORCEFULLREDRAW)  #ask to redraw the view
        c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED
                          )  #send message to c4d we have change the time

        camera = doc.SearchObject("Camera.1")

        xform = camera.GetMg()

        pos = xform.Mul(c4d.Vector(0, 0, 0))
        target = xform.Mul(c4d.Vector(0, 0, 1))

        # pos = camera.GetAbsPos()
        # rotationmatrix = c4d.utils.HPBToMatrix(camera.GetAbsRot())
        # target = pos + rotationmatrix.MulV(c4d.Vector(0,0,1))
        print(str(pos))
        print(str(target))

        # rotate (0,0,1) by GetAbsRot to get a target point that the camera is pointing at.

        frame += 1  #define the next frame

    c4d.EventAdd()  #Update scene
示例#18
0
    def set_matrix(self, matrix, frame):
        """

        :type frame: int
        :param frame:
        :type: Matrix
        :param matrix:
        :return:
        """
        transform = [
            matrix.get().off,
            c4d.utils.MatrixToHPB(matrix.get(),
                                  self.__object.GetRotationOrder()),
            matrix.get().GetScale()
        ]
        for i_type in range(3):
            for i_dir in range(3):
                desc_id = c4d.DescID(
                    c4d.DescLevel(ID_TYPES[i_type], c4d.DTYPE_VECTOR, 0),
                    c4d.DescLevel(ID_DIRS[i_dir], c4d.DTYPE_REAL, 0))
                track = self.__object.FindCTrack(desc_id)
                if track is None:
                    track = c4d.CTrack(self.__object, desc_id)
                    self.__object.InsertTrackSorted(track)
                curve = track.GetCurve()
                key = curve.AddKey(c4d.BaseTime(frame, get_fps()))['key']
                if key is None:
                    print('Error: Failed to add keys!')
                    continue
                track.FillKey(context_doc, self.__object, key)
                key.SetValue(curve, transform[i_type][i_dir])
示例#19
0
def main():
    # Saves current time
    ctime = doc.GetTime()

    # Retrieves BaseTime of frame 5, 20
    start = 5
    end = 20

    # Loops through the frames
    for frame in range(start, end + 1):

        # Sets the Status Bar
        c4d.StatusSetBar(100.0 * float(frame - start) / float(end - start))

        # Changes the time of the document
        doc.SetTime(c4d.BaseTime(frame, doc.GetFps()))

        # Updates timeline
        c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)

        # Redraws the viewport and regenerate the cache object
        c4d.DrawViews(c4d.DRAWFLAGS_ONLY_ACTIVE_VIEW | c4d.DRAWFLAGS_NO_THREAD
                      | c4d.DRAWFLAGS_STATICBREAK)

        # Do the stuff for each frame here you may be interested in BaseDocument.Polygonize()
        print("Frame {0}".format(frame))

    # Sets the time back to the original time.
    doc.SetTime(ctime)

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

    # Clears the Status Bar
    c4d.StatusClear()
def MoveKeys(curve, shift=1):
    shift = c4d.BaseTime(
        (1.0 / doc.GetFps()) * shift)  # Get one frame in BaseTime
    keyCount = curve.GetKeyCount()  # Get count of keyframes
    for i in range(0, keyCount):  # Iterate through keyframe indicies
        oldTime = curve.GetKey(i).GetTime()  # Get keyframe's current time
        newTime = oldTime + shift
        curve.MoveKey(newTime, i, None, True, False)  # Move keyframe
 def timeadvance(Advance): # Define a function called "timeadvance", which will act as a container for the script to be implemented in other scripts.
     CurrentTime = doc.GetTime() # Define CurrentTime to look at the current time in the document
     CurrentFrame = CurrentTime.GetFrame(doc.GetFps()) # Define CurrentFrame to calculate the current frame number based on the frame rate of the document
     FPS = doc[c4d.DOCUMENT_FPS] # Define FPS to look at the current document's fps setting
     NewFrame = CurrentFrame + Advance # Define NewFrame to add the current frame with the number of frames to advance forward
     Time = c4d.BaseTime(NewFrame,FPS) # Define Time to find the new frame location based on the combination of the current frame, the number of frames to advance, and the fps setting of the document
     doc.SetTime(Time) # Move the playhead to the newly referenced location in the timeline
     c4d.EventAdd() # Refresh the scene to update the change
    def set_frame_range(self, in_frame=None, out_frame=None, **kwargs):
        """
        set_frame_range will set the frame range using `in_frame` and `out_frame`
        :param int in_frame: in_frame for the current context
            (e.g. the current shot, current asset etc)
        :param int out_frame: out_frame for the current context
            (e.g. the current shot, current asset etc)
        """

        doc = c4d.documents.GetActiveDocument()
        fps = doc[c4d.DOCUMENT_FPS]
        head_in_frame = kwargs.get('head_in_frame')
        tail_out_frame = kwargs.get('tail_out_frame')

        if head_in_frame:
            # Set Handles if exists
            doc[c4d.DOCUMENT_MINTIME] = c4d.BaseTime(head_in_frame, fps)
        else:
            doc[c4d.DOCUMENT_MINTIME] = c4d.BaseTime(in_frame, fps)

        if tail_out_frame:
            # Set Handles if exists
            doc[c4d.DOCUMENT_MAXTIME] = c4d.BaseTime(tail_out_frame, fps)
        else:
            doc[c4d.DOCUMENT_MAXTIME] = c4d.BaseTime(out_frame, fps)

        # Set Project Preview MIN/MAX Time
        doc[c4d.DOCUMENT_LOOPMINTIME] = c4d.BaseTime(in_frame, fps)
        doc[c4d.DOCUMENT_LOOPMAXTIME] = c4d.BaseTime(out_frame, fps)

        doc[c4d.DOCUMENT_LOOPMINTIME] = c4d.BaseTime(in_frame, fps)
        return True
示例#23
0
def main():
    c4d.StopAllThreads()
    doc = c4d.documents.GetActiveDocument()
    fps = doc.GetFps()
    fromTime = doc.GetMinTime().GetFrame(fps)
    toTime = doc.GetMaxTime().GetFrame(fps)
    animLength = toTime - fromTime + 1
    filePath = c4d.storage.SaveDialog()
    filePath, objName = os.path.split(filePath)
    objName = objName + "_"
    filePath = filePath + "\\"


    for f in range(0,animLength):
        
        c4d.EventAdd(c4d.EVENT_FORCEREDRAW)
        c4d.DrawViews(c4d.DRAWFLAGS_FORCEFULLREDRAW)
        c4d.StatusSetText("Exporting " + str(f) + " of " + str(animLength))
        c4d.StatusSetBar(100.0*f/animLength)
         
        objs = doc.GetActiveObjects(c4d.GETACTIVEOBJECTFLAGS_CHILDREN)
 
        # Get a fresh, temporary document with only the selected objects
        docTemp = c4d.documents.IsolateObjects(doc, objs)
        docTemp.SetTime(c4d.BaseTime(fromTime,fps) + c4d.BaseTime(f,fps))
        if docTemp == None:
            return
    
        # Set project scale
        unitScale = c4d.UnitScaleData()
        unitScale.SetUnitScale(1.0, c4d.DOCUMENT_UNIT_M)
    
        bc = c4d.BaseContainer()
        bc[c4d.DOCUMENT_DOCUNIT] = unitScale
        docTemp.SetDocumentData(c4d. DOCUMENTSETTINGS_DOCUMENT, bc)
        

        fileName = filePath+objName+str(f)+".obj"
        savingresult = c4d.documents.SaveDocument(docTemp,fileName,c4d.SAVEDOCUMENTFLAGS_0,c4d.FORMAT_OBJ2EXPORT)
        c4d.documents.KillDocument(docTemp)

    c4d.StatusClear()
    gui.MessageDialog( 'Exporting to'+filePath+' done' )
示例#24
0
def Bake(source, target):
    """ Bake function  """

    doc = c4d.documents.GetActiveDocument()  # Get active Cinema 4D document
    fps = doc.GetFps()  # Get Frame Rate
    startFrame = doc.GetLoopMinTime().GetFrame(
        fps)  # Get first frame of Preview Range
    endFrame = doc.GetLoopMaxTime().GetFrame(
        fps)  # Get last frame of Preview Range

    for i in range(startFrame, endFrame + 1):  # Iterate through Preview Range
        SetCurrentFrame(i, doc)  # Set current frame
        frame = doc.GetTime().GetFrame(fps)  # Get current frame

        dataVault = [
            [903, c4d.DTYPE_REAL, 1000, c4d.DTYPE_VECTOR],
            [903, c4d.DTYPE_REAL, 1001, c4d.DTYPE_VECTOR],
            [903, c4d.DTYPE_REAL, 1002, c4d.DTYPE_VECTOR],  # Position
            [904, c4d.DTYPE_REAL, 1000, c4d.DTYPE_VECTOR],
            [904, c4d.DTYPE_REAL, 1001, c4d.DTYPE_VECTOR],
            [904, c4d.DTYPE_REAL, 1002, c4d.DTYPE_VECTOR],  # Rotation
            [905, c4d.DTYPE_REAL, 1000, c4d.DTYPE_VECTOR],
            [905, c4d.DTYPE_REAL, 1001, c4d.DTYPE_VECTOR],
            [905, c4d.DTYPE_REAL, 1002, c4d.DTYPE_VECTOR],  # Scale
        ]

        for data in dataVault:  # Iterate through data vault
            if len(data) == 2:  # Float
                desc = c4d.DescID(c4d.DescLevel(data[0], data[1], 0))
                value = source[data[0]]

            if len(data) == 4:  # Vector
                desc = c4d.DescID(c4d.DescLevel(data[0], data[3], 0),
                                  c4d.DescLevel(data[2], data[1], 0))
                value = source[data[0], data[2]]

            track = target.FindCTrack(desc)  # Try to find CTrack
            if not track:  # If CTrack does not exists
                track = c4d.CTrack(target, desc)  # Initialize CTrack
                target.InsertTrackSorted(track)  # Insert CTrack to the object

            curve = track.GetCurve()  # Get Curve of the CTrack
            currentTime = c4d.BaseTime(frame, fps)  # Get current time
            key = curve.AddKey(currentTime)["key"]
            track.FillKey(doc, target, key)

            if data[1] == c4d.DTYPE_REAL:  # Float
                key.SetValue(curve, value)
            else:  # If boolean or integer
                key.SetValue(curve, value)
                key.SetGeData(
                    curve,
                    value)  # Keyframe value needs to be set with SetGeData
示例#25
0
def set_key(curve, key_data):
    key = curve.FindKey(c4d.BaseTime(
        key_data[0]))  # Check for an existing keyframe
    if key:
        key = push_key(curve, key["key"], key_data)
        new = False
    else:
        key = push_key(curve, c4d.CKey(), key_data)
        new = True
    if new:
        curve.InsertKey(key)
    c4d.EventAdd()
示例#26
0
 def gotoframe(
     GoToFrame
 ):  # Define a function called "gotoframe", which will act as a container for the script to be implemented in other scripts.
     FPS = doc[
         c4d.
         DOCUMENT_FPS]  # Define FPS to look at the current document's fps setting
     Time = c4d.BaseTime(
         GoToFrame, FPS
     )  # Define Time to find the new frame location based on the combination of the current frame, the number of frames to advance, and the fps setting of the document
     doc.SetTime(
         Time
     )  # Move the playhead to the newly referenced location in the timeline
     c4d.EventAdd()  # Refresh the scene to update the change
示例#27
0
    def execute(self,
                operation,
                head_in_frame=None,
                in_frame=None,
                out_frame=None,
                tail_out_frame=None,
                **kwargs):
        """
        Main hook entry point

        :operation: String
                    Frame operation to perform

        :in_frame: int
                    in_frame for the current context (e.g. the current shot, 
                                                      current asset etc)

        :out_frame: int
                    out_frame for the current context (e.g. the current shot, 
                                                      current asset etc)

        :returns:   Depends on operation:
                    'set_frame_range' - Returns if the operation was succesfull
                    'get_frame_range' - Returns the frame range in the form
                                        (in_frame, out_frame)
        """

        doc = c4d.documents.GetActiveDocument()
        fps = doc[c4d.DOCUMENT_FPS]

        if operation == "get_frame_range":
            current_in, current_out = doc[c4d.DOCUMENT_MINTIME].GetFrame(
                fps), doc[c4d.DOCUMENT_MAXTIME].GetFrame(fps)
            return (current_in, current_out)
        elif operation == "set_frame_range":
            # Set Project MIN/MAX Time
            if head_in_frame:
                # Set Handles if exists
                doc[c4d.DOCUMENT_MINTIME] = c4d.BaseTime(head_in_frame, fps)
            else:
                doc[c4d.DOCUMENT_MINTIME] = c4d.BaseTime(in_frame, fps)

            if tail_out_frame:
                # Set Handles if exists
                doc[c4d.DOCUMENT_MAXTIME] = c4d.BaseTime(tail_out_frame, fps)
            else:
                doc[c4d.DOCUMENT_MAXTIME] = c4d.BaseTime(out_frame, fps)

            # Set Project Preview MIN/MAX Time
            doc[c4d.DOCUMENT_LOOPMINTIME] = c4d.BaseTime(in_frame, fps)
            doc[c4d.DOCUMENT_LOOPMAXTIME] = c4d.BaseTime(out_frame, fps)

            doc[c4d.DOCUMENT_LOOPMINTIME] = c4d.BaseTime(in_frame, fps)
            return True
示例#28
0
def main():
    # Saves current time
    ctime = doc.GetTime()

    # Retrieves BaseTime of frame 5, 20
    start = 5
    end = 20

    # Marks the state of the document as the initial step of our undo process
    doc.StartUndo()

    # Loops through the frames
    for frame in xrange(start, end + 1):
        # Changes the time of the document
        doc.SetTime(c4d.BaseTime(frame, doc.GetFps()))

        # Executes the document, so animation, dynamics, expression are calculated and cached are build accordingly
        buildflag = c4d.BUILDFLAGS_NONE if c4d.GetC4DVersion(
        ) > 20000 else c4d.BUILDFLAGS_0
        doc.ExecutePasses(None, True, True, True, buildflag)

        # For each cache objects of our current selected object
        for obj in DeformedPolygonCacheIterator(op):

            # Calculates the position of the point 88 in world space
            pos = obj.GetPoint(88) * obj.GetMg()

            # Creates a null for each frame and each cache
            null = c4d.BaseObject(c4d.Onull)
            null.SetName(str(frame))

            # Inserts the objects into the documents
            doc.AddUndo(c4d.UNDOTYPE_NEW, null)
            doc.InsertObject(null)

            # Defines the position of the null with the position of the point from the deformed mesh
            null.SetAbsPos(pos)

    # Sets the time back to the original time.
    doc.SetTime(ctime)

    # Executes the document, so animation, dynamics, expression are calculated and cached are build accordingly
    buildflag = c4d.BUILDFLAGS_NONE if c4d.GetC4DVersion(
    ) > 20000 else c4d.BUILDFLAGS_0
    doc.ExecutePasses(None, True, True, True, buildflag)

    # Marks the state of the document as the final step of our undo process
    doc.EndUndo()

    # Pushes an update event to Cinema 4D
    c4d.EventAdd(c4d.EVENT_ANIMATE)
示例#29
0
def DistributeKeys(keyMod, step):
    tracks = GetKeys() # Get selected keys
    for track in tracks:
        keys = track[1]
        for i, k in enumerate(keys): # Iterate through tracks
            curve = k.GetCurve() # Get the curve
            firstKeyTime = keys[0].GetTime().Get()
            lastKeyTime = keys[-1].GetTime().Get()
            if i != 0: # If not first run
                if keyMod == "None":
                    time = firstKeyTime + (lastKeyTime - firstKeyTime) / (len(keys)-1) * (i) # Distribution algorithm
                elif keyMod == "Shift":
                    time = firstKeyTime + float(step)/doc.GetFps() * (i) # Distribution algorithm
                index = curve.FindKey(k.GetTime())["idx"] # Get correct index
                curve.MoveKey(c4d.BaseTime(time), index, None, True, False) # Move keyframe        
示例#30
0
def main():
    # Which frame to sample. Grab this from the userattr of the tag!
    obj = op.GetObject()
    pytag = obj.GetFirstTag()

    # Gotcha - when rendering tags get reordered and coffee tag might not come first,
    # so walk the f*****g linked list until we arrive at the tag
    # while(pytag):
    #     if(instanceof(pytag, c4d.PythonTag)):
    #         break
    #     pytag = pytag.GetNext()

    # Float attr ID_USERDATA:1
    at = 5  #pytag[c4d.ID_USERDATA, 1]

    # Sample FPS once
    fps = doc.GetFps()

    # We need to pass a BaseTime object to the track sampler
    # and we create it with the SECONDS
    seconds = at / fps
    atTime = c4d.BaseTime(seconds)

    # Positions
    myT = obj.GetFirstCTrack()
    posX = myT.GetValue(doc, atTime, fps)

    myT = myT.GetNext()
    posY = myT.GetValue(doc, atTime, fps)

    myT = myT.GetNext()
    posZ = myT.GetValue(doc, atTime, fps)

    # Then rotations
    myT = myT.GetNext()
    rotH = myT.GetValue(doc, atTime, fps)

    myT = myT.GetNext()
    rotP = myT.GetValue(doc, atTime, fps)

    myT = myT.GetNext()
    rotB = myT.GetValue(doc, atTime, fps)

    posVec = c4d.Vector(posX, posY, posZ)
    rotVec = c4d.Vector(rotH, rotP, rotB)

    obj.SetRelPos(posVec)
    obj.SetRelRot(rotVec)