def main(): # Retrieves a path to save the exported file filePath = c4d.storage.LoadDialog(title="Save File for OBJ Export", flags=c4d.FILESELECT_SAVE, force_suffix="obj") if not filePath: return # Retrieves Obj export plugin, defined in R17 as FORMAT_OBJ2EXPORT and below R17 as FORMAT_OBJEXPORT objExportId = c4d.FORMAT_OBJEXPORT if c4d.GetC4DVersion() < 17000 else c4d.FORMAT_OBJ2EXPORT plug = c4d.plugins.FindPlugin(objExportId, c4d.PLUGINTYPE_SCENESAVER) if plug is None: raise RuntimeError("Failed to retrieve the OBJ exporter.") data = dict() # Sends MSG_RETRIEVEPRIVATEDATA to OBJ export plugin if not plug.Message(c4d.MSG_RETRIEVEPRIVATEDATA, data): raise RuntimeError("Failed to retrieve private data.") # BaseList2D object stored in "imexporter" key hold the settings objExport = data.get("imexporter", None) if objExport is None: raise RuntimeError("Failed to retrieve BaseContainer private data.") # Defines OBJ export settings if c4d.GetC4DVersion() > 22600: objExport[c4d.OBJEXPORTOPTIONS_EXPORT_UVS] = c4d.OBJEXPORTOPTIONS_UV_ORIGINAL else: objExport[c4d.OBJEXPORTOPTIONS_TEXTURECOORDINATES] = True objExport[c4d.OBJEXPORTOPTIONS_MATERIAL] = c4d.OBJEXPORTOPTIONS_MATERIAL_MATERIAL objExport[c4d.OBJEXPORTOPTIONS_ANIMATION_TYPE] = c4d.OBJEXPORTOPTIONS_NO_ANIMATION # Finally export the document if not c4d.documents.SaveDocument(doc, filePath, c4d.SAVEDOCUMENTFLAGS_DONTADDTORECENTLIST, objExportId): raise RuntimeError("Failed to save the document.") print("Document successfully exported to:", filePath)
def main(): ctrl, shift, alt = get_modifiers() if ctrl: OpenWebsite('https://color.adobe.com/create/color-wheel/') return myColors = get_xml_colors() if not myColors: return # Strip Color-Index from Name name = myColors.keys()[0][:-2] colors = myColors.values()[0] #PRE R18 VERSION ( INSERT ONLY OBJECTS ) if c4d.GetC4DVersion() <= 18011: c4d.gui.MessageDialog( "I'm sorry, Color-Swatches haven't been introduced in your C4D-Version.\nYou need at least C4D R18! I'll just add some Cubes with Colors... Okay!?" ) InsertObjects(name, colors) return if c4d.GetC4DVersion() >= 20000: maxon_colors = convert_to_maxon(colors) #SHIFT-CLICK: ONLY ADD SWATCHES if shift: InsertSwatchesR21(doc, name, maxon_colors) return #DEFAULT-CLICK: REFERENCE CUBES + SWATCHES InsertSwatchesR21(doc, name, maxon_colors) InsertObjects(name, colors)
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)
def main(): # Retrieves a path to save the exported file filePath = c4d.storage.LoadDialog(title="Save File for Alembic Export", flags=c4d.FILESELECT_SAVE, force_suffix="abc") if not filePath: return # Retrieves Alembic exporter plugin, 1028082, defined in R20.046 as FORMAT_ABCEXPORT abcExportId = 1028082 if c4d.GetC4DVersion() < 20046 else c4d.FORMAT_ABCEXPORT plug = c4d.plugins.FindPlugin(abcExportId, c4d.PLUGINTYPE_SCENESAVER) if plug is None: raise RuntimeError("Failed to retrieve the alembic exporter.") data = dict() # Sends MSG_RETRIEVEPRIVATEDATA to Alembic export plugin if not plug.Message(c4d.MSG_RETRIEVEPRIVATEDATA, data): raise RuntimeError("Failed to retrieve private data.") # BaseList2D object stored in "imexporter" key hold the settings abcExport = data.get("imexporter", None) if abcExport is None: raise RuntimeError("Failed to retrieve BaseContainer private data.") # Defines Alembic export settings abcExport[c4d.ABCEXPORT_SELECTION_ONLY] = True abcExport[c4d.ABCEXPORT_PARTICLES] = False abcExport[c4d.ABCEXPORT_PARTICLE_GEOMETRY] = False # Finally export the document if not c4d.documents.SaveDocument(doc, filePath, c4d.SAVEDOCUMENTFLAGS_DONTADDTORECENTLIST, abcExportId): raise RuntimeError("Failed to save the document.") print("Document successfully exported to:", filePath)
def ReadMemoryFile(data): """Reads data from a memory file. Args: data: the byte sequence to read """ # Creates a MemoryFile, data will be read in mfs = c4d.storage.MemoryFileStruct() # Sets the memory file ready to be read from mfs.SetMemoryReadMode(data, len(data)) file = c4d.storage.HyperFile() # Opens the memory file and set it ready for reading if not file.Open(0, mfs, c4d.FILEOPEN_READ, c4d.FILEDIALOG_NONE): raise RuntimeError("Failed to open the HyperFile.") # Reads the string from the memory file value = file.ReadString() print("The string value is :", value) # Reads the int from the memory file value = file.ReadInt32() print("The int value is :", value) if c4d.GetC4DVersion() > 22600: # Reads the bytes from the memory file value = file.ReadMemory() print("The memory value is :", value) # Closes file file.Close()
def WriteMemoryFile(): """Writes data to a memory file. Returns: The byte sequence or None """ # Creates a MemoryFile, data will be written in mfs = c4d.storage.MemoryFileStruct() # Sets the memory file ready to be written to mfs.SetMemoryWriteMode() # Initializes a HyperFile file = c4d.storage.HyperFile() # Opens the HyperFile, with the MemoryFile used if not file.Open(0, mfs, c4d.FILEOPEN_WRITE, c4d.FILEDIALOG_NONE): raise RuntimeError("Failed to open the HyperFile.") # Writes a string to the memory file file.WriteString("MemoryFileStruct Example") # Writes an integer to the memory file file.WriteInt32(1214) if c4d.GetC4DVersion() > 22600: # Writes an byte array to the memory file file.WriteMemory(bytearray("Bytes Array data", "utf-8")) # Closes the file file.Close() # Returns the memory file data (the byte sequence) return mfs.GetData()[0]
def main(): # Retrieves a path to load the imported file selectedFile = c4d.storage.LoadDialog(title="Load File for OBJ Import", type=c4d.FILESELECTTYPE_ANYTHING, force_suffix="obj") if not selectedFile: return # Retrieves Obj import plugin, defined in R17 as FORMAT_OBJ2IMPORT and below R17 as FORMAT_OBJIMPORT objExportId = c4d.FORMAT_OBJIMPORT if c4d.GetC4DVersion() < 17000 else c4d.FORMAT_OBJ2IMPORT plug = c4d.plugins.FindPlugin(objExportId, c4d.PLUGINTYPE_SCENELOADER) if plug is None: raise RuntimeError("Failed to retrieve the obj importer.") data = dict() # Sends MSG_RETRIEVEPRIVATEDATA to OBJ import plugin if not plug.Message(c4d.MSG_RETRIEVEPRIVATEDATA, data): raise RuntimeError("Failed to retrieve private data.") # BaseList2D object stored in "imexporter" key hold the settings objImport = data.get("imexporter", None) if objImport is None: raise RuntimeError("Failed to retrieve BaseContainer private data.") # Defines the settings objImport[c4d.OBJIMPORTOPTIONS_PHONG_ANGLE_DEFAULT] = 22.5 objImport[c4d.OBJIMPORTOPTIONS_TEXTURECOORDINATES] = True objImport[c4d.OBJIMPORTOPTIONS_SPLITBY] = c4d.OBJIMPORTOPTIONS_SPLITBY_OBJECT objImport[c4d.OBJIMPORTOPTIONS_MATERIAL] = c4d.OBJIMPORTOPTIONS_MATERIAL_MTLFILE objImport[c4d.OBJIMPORTOPTIONS_POINTTRANSFORM_FLIPZ] = True # Finally imports without dialogs if not c4d.documents.MergeDocument(doc, selectedFile, c4d.SCENEFILTER_OBJECTS | c4d.SCENEFILTER_MATERIALS, None): raise RuntimeError("Failed to load the document.") # Pushes an update event to Cinema 4D c4d.EventAdd()
def host_info(self): """ :returns: A dictionary with information about the application hosting this engine. The returned dictionary is of the following form on success: { "name": "Cinema", "version": "R20", } The returned dictionary is of following form on an error preventing the version identification. { "name": "Cinema", "version: "unknown" } """ host_info = {"name": "Cinema", "version": "unknown"} try: cinema_ver = c4d.GetC4DVersion() host_info["version"] = cinema_ver except: # Fallback to 'Cinema' initialized above pass return host_info
def GetColors(string): #String for Testing purposes #string = "AE-C4D-CopyPasteColors;Ray - AEC4D-PRO;0.84313726425171,0.83137255907059,0.83137255907059,1;0.54901963472366,0.53725492954254,0.53725492954254,1;0.27058824896812,0.27058824896812,0.27058824896812,1;0.38431373238564,0.5137255191803,0.86274510622025,1;0.33333334326744,0.30588236451149,0.81960785388947,1;0.50196081399918,0,1,1;0.14509804546833,0.14117647707462,0.47843137383461,1;0.84705883264542,0.62745100259781,0.98039215803146,1;0.83137255907059,0.2392156869173,0.43137255311012,1;1,0.25,0.25,1;0.97647058963776,0.678431391716,1,1;" if not c4d.GetClipboardType( ) == c4d.CLIPBOARDTYPE_STRING and not string.startswith( 'AE-C4D-CopyPasteColors'): return color_table = string.split(';')[:-1] if not color_table: return #Remove Identifier > 'AE-C4D-CopyPasteColors' identifier = color_table.pop(0) #Pop Palette-Name from String myName = color_table.pop(0) myColors, my4DColors = [], [] for item in color_table: color_list = item.split(',') colors = [float(c) for c in color_list] v = c4d.Vector(colors[0], colors[1], colors[2]) myColors.append(v) if c4d.GetC4DVersion() >= 20000: v4D = v4.ColorA(colors[0], colors[1], colors[2], colors[3]) my4DColors.append(v4D) return myName, myColors, my4DColors
def main(): # Retrieves the object called obj1 from the active document. animatedBox = doc.SearchObject("obj1") if animatedBox is None: raise RuntimeError("Failed to retrieve obj1 in document.") # Retrieves the object called obj2 from the active document. fixedBox = doc.SearchObject("obj2") if fixedBox is None: raise RuntimeError("Failed to retrieve obj2 in document.") # Retrieves all the CTrack of obj1. CTracks contains all keyframes information of a parameter. tracks = animatedBox.GetCTracks() if not tracks: raise ValueError( "Failed to retrieve animated tracks information for obj1.") # Defines a list that will contains the ID of parameters we want to copy. # Such ID can be found by drag-and-drop a parameter into the python console. trackListToCopy = [ c4d.ID_BASEOBJECT_POSITION, c4d.ID_BASEOBJECT_ROTATION, c4d.ID_BASEOBJECT_SCALE ] # Start the Undo process. doc.StartUndo() # Iterates overs the CTracks of obj1. for track in tracks: # Retrieves the full parameter ID (DescID) describing a parameter. did = track.GetDescriptionID() # If the Parameter ID of the current CTracks is not on the trackListToCopy we go to the next one. if not did[0].id in trackListToCopy: continue # Find if our static object already got an animation track for this parameter ID. foundTrack = fixedBox.FindCTrack(did) if foundTrack: # Removes the track if found. doc.AddUndo(c4d.UNDOTYPE_DELETE, foundTrack) foundTrack.Remove() # Copies the initial CTrack in memory. All CCurve and CKey are kept in this CTrack. clone = track.GetClone() # Inserts the copied CTrack to the static object. fixedBox.InsertTrackSorted(clone) doc.AddUndo(c4d.UNDOTYPE_NEW, clone) # Ends the Undo Process. doc.EndUndo() # Updates fixedBox Geometry taking in account previously created keyframes animateFlag = c4d.ANIMATEFLAGS_NONE if c4d.GetC4DVersion( ) > 20000 else c4d.ANIMATEFLAGS_0 doc.AnimateObject(fixedBox, doc.GetTime(), animateFlag) # Pushes an update event to Cinema 4D c4d.EventAdd()
def main(): # Selects the c4d file to load filename = c4d.storage.LoadDialog(type=c4d.FILESELECTTYPE_SCENES, title="Choose File.", flags=c4d.FILESELECT_LOAD, force_suffix="c4d") if not filename: return # Checks selected file is a c4d scene file name, suffix = os.path.splitext(filename) if suffix != ".c4d": raise RuntimeError("Selected file is not a C4D file format.") # Loads the document flag = c4d.SCENEFILTER_NONE if c4d.GetC4DVersion() > 20000 else c4d.SCENEFILTER_0 loadedDoc = c4d.documents.LoadDocument(filename, flag) if loadedDoc is None: raise RuntimeError("Failed to load the document.") # Creates a new ColorSwatchData swatchData = c4d.modules.colorchooser.ColorSwatchData() if swatchData is None: raise MemoryError("Failed to create a ColorSwatchData.") # Loads swatches from document swatchData.Load(loadedDoc) # Stores swatches into the active document swatchData.Save(doc) # Pushes an update event to Cinema 4D c4d.EventAdd()
def join_objects(root, doc, merge_tags): # set_status("Joining %d objects ..." % len(children), 50) # Pre-R18 we need to pass the list of objects to join. if c4d.GetC4DVersion() < 18000: children = root.GetChildren() source = children else: source = [root] settings = c4d.BaseContainer() settings[c4d.MDATA_JOIN_MERGE_SELTAGS] = merge_tags # collapse objects result = c4d.utils.SendModelingCommand(c4d.MCOMMAND_JOIN, source, c4d.MODELINGCOMMANDMODE_ALL, settings, doc) obj = result[0] # delete selection tags if merge_tags == False: obj_tags = obj.GetTags() for tag in obj_tags: if tag.GetType() == c4d.Tpointselection: tag.Remove() elif tag.GetType() == c4d.Tedgeselection: tag.Remove() elif tag.GetType() == c4d.Tpolygonselection: tag.Remove() else: None if not obj: return None return obj
def main(): # Creates VolumeObject volumeObj = c4d.BaseObject(c4d.Ovolume) if volumeObj is None: raise MemoryError("Failed to create a volume object.") # Inserts the volume Object within the scene doc.InsertObject(volumeObj, None, None) # Creates volume volume = maxon.frameworks.volume.VolumeToolsInterface.CreateNewFloat32Volume( 0.0) if volume is None: raise MemoryError("Failed to create a float32 volume.") volume.SetGridClass(c4d.GRIDCLASS_FOG) volume.SetGridName("Example Grid") # Defines the initial matrix of the grid scaleMatrix = maxon.Matrix() volume.SetGridTransform(scaleMatrix) # Creates accessor access = maxon.frameworks.volume.GridAccessorInterface.Create( maxon.Float32) if access is None: raise RuntimeError("Failed to retrieve the grid accessor.") # Initializes the grid for write access, changed with R21 initMethod = access.Init if c4d.GetC4DVersion( ) < 21000 else access.InitWithWriteAccess initMethod(volume) # Sets values in the shape of a helix offset = 0.0 radius = 100.0 height = 500.0 step = 50.0 stepSize = height / step while offset < step: sin, cos = c4d.utils.SinCos(offset) pos = maxon.IntVector32() pos.x = maxon.Int32(sin * radius) pos.y = maxon.Int32(cos * radius) pos.z = maxon.Int32(offset * stepSize) # Sets value access.SetValue(pos, 10.0) offset = offset + 0.1 # Inserts volume in the VolumeObject volumeObj.SetVolume(volume) # Pushes an update event to Cinema 4D c4d.EventAdd()
def polygonToVolume(obj): # Checks if the input obj is a PolygonObject if not obj.IsInstanceOf(c4d.Opolygon): raise TypeError("obj is not a c4d.Opolygon.") # Retrieves the world matrices of the object matrix = obj.GetMg() # Creates a BaseArray (list) of all points position in world space vertices = maxon.BaseArray(maxon.Vector) vertices.Resize(obj.GetPointCount()) for i, pt in enumerate(obj.GetAllPoints()): vertices[i] = pt * matrix # Sets polygons polygons = maxon.BaseArray(maxon.frameworks.volume.VolumeConversionPolygon) polygons.Resize(obj.GetPolygonCount()) for i, poly in enumerate(obj.GetAllPolygons()): newPoly = maxon.frameworks.volume.VolumeConversionPolygon() newPoly.a = poly.a newPoly.b = poly.b newPoly.c = poly.c if poly.IsTriangle(): newPoly.SetTriangle() else: newPoly.d = poly.d polygons[i] = newPoly # Sets the matrice used for local grid translation and rotation polygonObjectMatrix = maxon.Matrix() polygonObjectMatrix.off = obj.GetMg().off polygonObjectMatrix.v1 = obj.GetMg().v1 polygonObjectMatrix.v2 = obj.GetMg().v2 polygonObjectMatrix.v3 = obj.GetMg().v3 gridSize = 1 bandWidthInterior = 1 bandWidthExterior = 1 # Before R21 if c4d.GetC4DVersion() < 21000: volumeRef = maxon.frameworks.volume.VolumeToolsInterface.MeshToVolume(vertices, polygons, polygonObjectMatrix, gridSize, bandWidthInterior, bandWidthExterior, maxon.ThreadRef(), None) else: volumeRef = maxon.frameworks.volume.VolumeToolsInterface.MeshToVolume(vertices, polygons, polygonObjectMatrix, gridSize, bandWidthInterior, bandWidthExterior, maxon.ThreadRef(), maxon.POLYGONCONVERSIONFLAGS.NONE, None) FogVolumeRef = maxon.frameworks.volume.VolumeToolsInterface.ConvertSDFToFog(volumeRef, 0.1) return FogVolumeRef
def sys_info(): sysname, nodename, release, version, machine, _processor = platform.uname() c4d_version = u"unk" try: import c4d c4d_version = unicode(c4d.GetC4DVersion()) except Exception, e: logging.error(e)
def get_c4d_ver(): C4D_ver = str(c4d.GetC4DVersion()) C4D_ver = C4D_ver[:2] + "." + C4D_ver[2:] version_to_log = "Cinema 4D R" + C4D_ver C4DR_ver = C4D_ver[:2] ver_list = [version_to_log, C4DR_ver] return ver_list
def getUClass(host,pref=None): """ Return the base class for UI design according the provide host. @type host: string @param host: name of the host application @type pref: string @param pref: UI interface prefernce for instance qt @rtype: Class @return: the specific ui class """ if host == 'blender24': #check version # from pyubic.blender.blenderUI import blenderUIDialog as adaptor from upy.blender.v249.blenderUI import blenderUIDialog as adaptor elif host == 'blender25': import bpy blender_version = bpy.app.version if blender_version < (2,60,0): from upy.blender.v257.blenderUI import blenderUIDialog as adaptor elif blender_version >= (2,60,0): #2.62 from upy.blender.v262.blenderUI import blenderUIDialog as adaptor else : print (blender_version,blender_version < (2,60,0)) elif host=='c4d': import c4d c4d_version = c4d.GetC4DVersion() if c4d_version > 12000 and c4d_version < 13000 : from upy.cinema4d.r12.c4dUI import c4dUIDialog as adaptor elif c4d_version > 13000: from upy.cinema4d.r13.c4dUI import c4dUIDialog as adaptor elif host=='maya': from upy.autodeskmaya.mayaUI import mayaUIDialog as adaptor elif host=='dejavu': from upy.dejavuTk.dejavuUI import dejavuUIDialog as adaptor # print ("ok",adaptor) elif host=='houdini': if pref is not None : if pref == "qt" : from upy.pythonUI.qtUI import qtUIDialog as adaptor else : from upy.houdini.houdiniUI import houdiniUIDialog as adaptor ## elif host == 'chimera': # from ePMV.Chimera.chimeraUI import chimeraAdaptor as uiadaptor # elif host == 'houdini': # from ePMV.houdini.houdiniUI import houdiniAdaptor as uiadaptor elif host =="qt" : from upy.pythonUI.qtUI import qtUIDialog as adaptor else : adaptor = None return adaptor
def hex_to_col(hex, normalize=True, precision=6): col = [] it = iter(str(hex)) if c4d.GetC4DVersion() <= 22123: for index, char in enumerate(it): col.append(int(char + next(it), 16)) else: for char in it: col.append(int(char + it.__next__(), 16)) if normalize: col = map(lambda x: x / 255, col) col = map(lambda x: round(x, precision), col) return list(c for c in col)
def main(): #Check Modifiers ctrl, shift, alt = GetModifiers() #Get String from Clipboard clipboard = c4d.GetStringFromClipboard() if not clipboard.startswith('AE-C4D-CopyPasteColors'): gui.MessageDialog( 'Please, use "copy-colors.jsx" for After Effects first...') return myName, myColors, my4DColors = GetColors(clipboard) #Import only Planes with Colors, without any questions... if alt: InsertColorPlanes(myName, myColors) return #Handle Pre R18 Releases if c4d.GetC4DVersion() <= 18011: gui.MessageDialog("Sorry, Swatches haven't been introduced yet!") question = gui.QuestionDialog( "Do you want to Create Planes with Colors?") if question: InsertColorPlanes(myName, myColors) return #Handle Post R18 Pre R20 Releases if c4d.GetC4DVersion() >= 18011 and c4d.GetC4DVersion() <= 20000: InsertSwatchesR18(doc, myName, myColors) #Handle Post R20 Releases if c4d.GetC4DVersion() >= 20000: InsertSwatchesR20(doc, myName, my4DColors) c4d.EventAdd()
def check_value(self, type, value): if type == "float": if isinstance(value, str): return 1 else: return value if type == "hex": if c4d.GetC4DVersion() <= 22123: if not isinstance(value, float): value = str(value) if isinstance(value, float): return "#FFFFFF" else: return value
def reset_bind_pose(self, c_meshes): for obj in c_meshes: tags = TagIterator(obj) for tag in tags: tag_type = tag.GetType() if tag_type == c4d.Tweights: if c4d.GetC4DVersion() <= 22123: tag[c4d.ID_CA_WEIGHT_TAG_SET] = 2005 c4d.CallButton(tag, c4d.ID_CA_WEIGHT_TAG_SET) c4d.EventAdd() break else: tag[c4d.ID_CA_WEIGHT_TAG_SET_BUTTON] = 2005 c4d.CallButton(tag, c4d.ID_CA_WEIGHT_TAG_SET_BUTTON) c4d.EventAdd() break
def sys_info(): sysname, nodename, release, version, machine, _processor = platform.uname() c4d_version = "unk" try: import c4d c4d_version = str(c4d.GetC4DVersion()) except Exception as e: logging.error(e) return { "c4d.version": c4d_version, "os.name": sysname, "node.name": nodename, "os.release": release, "os.version": version }
def report(): err = None try: yield except Exception: if gui.QuestionDialog( "There was an error running the script. Would you like to send a brief report?" ): # Generate Report webbrowser.open( "mailto:{email}?subject={subject}&body={body}".format( email=REPORT_ADDR, subject=urllib.quote(REPORT_SUBJ), body=urllib.quote("\n".join( (str(datetime.datetime.now()), platform.platform(), "C4D version %s" % c4d.GetC4DVersion(), __file__, traceback.format_exc()))))) raise
def join_objects(root, doc, merge_tags): # Pre-R18 we need to pass the list of objects to join. if c4d.GetC4DVersion() < 18000: children = root.GetChildren() source = children else: source = [root] settings = c4d.BaseContainer() settings[c4d.MDATA_JOIN_MERGE_SELTAGS] = False # collapse objects result = c4d.utils.SendModelingCommand(c4d.MCOMMAND_JOIN, source, c4d.MODELINGCOMMANDMODE_ALL, settings, doc=doc) obj = result[0] if not obj: return None return obj
def getHClass(host): """ Return the base class for modelling design according the provide host. @type host: string @param host: name of the host application @rtype: Class @return: the specific ui class """ if host == 'blender24': from upy.blender.v249.blenderHelper import blenderHelper as helper elif host == 'blender25': import bpy blender_version = bpy.app.version if blender_version < (2,60,0): from upy.blender.v257.blenderHelper import blenderHelper as helper elif blender_version >= (2,60,0): #2.62 from upy.blender.v262.blenderHelper import blenderHelper as helper else : print (blender_version,blender_version < (2,60,0)) elif host=='c4d': import c4d c4d_version = c4d.GetC4DVersion() if c4d_version > 12000 and c4d_version < 13000: from upy.cinema4d.r12.c4dHelper import c4dHelper as helper elif c4d_version > 13000: from upy.cinema4d.r13.c4dHelper import c4dHelper as helper elif host=='maya': from upy.autodeskmaya.mayaHelper import mayaHelper as helper elif host=='dejavu': from upy.dejavuTk.dejavuHelper import dejavuHelper as helper elif host == 'chimera': from upy.ucsfchimera.chimeraHelper import chimeraHelper as helper elif host == 'houdini': from upy.houdini.houdiniHelper import houdiniHelper as helper else : helper = None return helper
def getPClass(host): """ Return the base class for plugin type provided. @type host: string @param host: name of the host application @rtype: Class @return: the specific ui class """ if host == 'blender24': from upy.blender.v249 import blenderPlugin as plugClass elif host == 'blender25': import bpy blender_version = bpy.app.version if blender_version < (2,60,0): from upy.blender.v257 import blenderPlugin as plugClass elif blender_version >= (2,60,0): #2.62 from upy.blender.v262 import blenderPlugin as plugClass else : print (blender_version,blender_version < (2,60,0)) elif host=='c4d': import c4d c4d_version = c4d.GetC4DVersion() if c4d_version > 12000 and c4d_version < 13000: from upy.cinema4d.r12 import c4dPlugin as plugClass elif c4d_version > 13000: from upy.cinema4d.r13 import c4dPlugin as plugClass elif host=='maya': from upy.autodeskmaya import mayaPlugin as plugClass elif host=='dejavu': from upy.dejavuTk import dejavuPlugin as plugClass elif host == 'chimera': from upy.ucsfchimera import chimeraPlugin as plugClass elif host == 'houdini': from upy.houdini import houdiniPlugin as plugClass else : plugClass = None return plugClass
def main(): # Retrieves the selected object in the current document. flag = c4d.GETACTIVEOBJECTFLAGS_NONE if c4d.GetC4DVersion( ) > 20000 else c4d.GETACTIVEOBJECTFLAGS_0 objList = doc.GetActiveObjects(flag) if not objList: raise RuntimeError("Failed to retrieve selected objects.") matList = doc.GetActiveMaterials() if not matList: raise RuntimeError("Failed to retrieve selected materials.") # Checks if the document's mode is polygon so we will apply the mat to only the selected polygons onlyToSelection = doc.GetMode() == c4d.Mpolygons doc.StartUndo() for obj in objList: AssignMatToObject(obj, matList, onlyToSelection) doc.EndUndo() # Pushes an update event to Cinema 4D c4d.EventAdd()
import c4d # Prints Cinema 4D version number print(c4d.GetC4DVersion())
#Create IDs for the GUI elements in the settings dialog DLG_GROUP_1 = 1000 DLG_GROUP_2 = 1001 TEXTBOX = 1002 CANCELBUTTON = 1003 IMPORTBUTTON = 1004 HNCHECK = 1005 CONNECTCHECK = 1006 RAILCHECK = 1007 SWEEPCHECK = 1008 PROFILETEXT = 1009 PROFILESIDES = 1010 coordsystem="left" versionNumber=c4d.GetC4DVersion() def somaMake(somaLines, neuroFile, fileName): """Create splines to make the cell body.""" #reference global variables that set model parameters global DoHN, DoConnect, DoRail, DoSweep, NSides #create spline Spline = c4d.BaseObject(c4d.Ospline) #add name to spline Spline[c4d.ID_BASELIST_NAME] = "Soma" #set type to linear Spline[c4d.SPLINEOBJECT_TYPE] = 0
def Command(self, id, msg): if id == 1100: base = self.GetLink(1000) if base != None: objects = doc.GetActiveObjects(c4d.GETACTIVEOBJECTFLAGS_NONE) doc.StartUndo() for i, obj in enumerate(objects): # Create Instance instance = c4d.BaseObject(c4d.Oinstance) # Undo doc.AddUndo(c4d.UNDOTYPE_CHANGE, obj) doc.AddUndo(c4d.UNDOTYPE_NEW, instance) # Instance Data instance[c4d.INSTANCEOBJECT_LINK] = base instance[c4d.ID_BASEOBJECT_REL_POSITION] = obj[ c4d.ID_BASEOBJECT_REL_POSITION] instance[c4d.ID_BASEOBJECT_REL_SCALE] = obj[ c4d.ID_BASEOBJECT_REL_SCALE] instance[c4d.ID_BASEOBJECT_REL_ROTATION] = obj[ c4d.ID_BASEOBJECT_REL_ROTATION] instance[ c4d. INSTANCEOBJECT_RENDERINSTANCE_MODE] = self.GetInt32( 1004) instance[ c4d.INSTANCEOBJECT_MULTIPOSITIONINPUT] = self.GetLink( 1006) instance[c4d.INSTANCEOBJECT_DRAW_MODE] = self.GetInt32( 1008) # Layer layer = self.GetInt32(1010) if layer == 1: instance.SetLayerObject(obj.GetLayerObject(doc)) if layer == 2: instance.SetLayerObject(base.GetLayerObject(doc)) instance.SetName(obj.GetName() + "_" + base.GetName() + "_" + str(i)) instance.InsertBefore(obj) # Replace Children children = obj.GetChildren() for child in reversed(children): child.InsertUnder(instance) # Copy Animation tracks = obj.GetCTracks() trackListToCopy = [ c4d.ID_BASEOBJECT_POSITION, c4d.ID_BASEOBJECT_ROTATION, c4d.ID_BASEOBJECT_SCALE ] for track in tracks: did = track.GetDescriptionID() if not did[0].id in trackListToCopy: continue foundTrack = instance.FindCTrack(did) if foundTrack: foundTrack.Remove() clone = track.GetClone() instance.InsertTrackSorted(clone) animateflag = c4d.ANIMATEFLAGS_NONE if c4d.GetC4DVersion( ) > 20000 else c4d.ANIMATEFLAGS_0 doc.AnimateObject(instance, doc.GetTime(), animateflag) # Remove Obj obj.Remove() doc.EndUndo() c4d.EventAdd() if id == 1004: mode = self.GetInt32(1004) if mode == 0: self.HideElement(1005, True) self.HideElement(1006, True) self.HideElement(1007, True) self.HideElement(1008, True) self.LayoutChanged(1) elif mode == 1: self.HideElement(1005, True) self.HideElement(1006, True) self.HideElement(1007, True) self.HideElement(1008, True) self.LayoutChanged(1) else: self.HideElement(1005, False) self.HideElement(1006, False) self.HideElement(1007, False) self.HideElement(1008, False) self.LayoutChanged(1) return True