def Subdivide(op, amount): bc = c4d.BaseContainer() # Initialize Base Container bc[c4d.MDATA_SUBDIVIDE_SPLINESUB] = int(amount) # Subdivision rate mcommand = c4d.MCOMMAND_SUBDIVIDE # Mcommand 'Make Editable' op = c4d.utils.SendModelingCommand(mcommand, [op], 0, bc, doc, c4d.MODELINGCOMMANDFLAGS_CREATEUNDO) # Subdivide
def main(): # Checks if selected object is valid if op is None: raise ValueError("op is none, please select one object.") # Enables UV Polygon Mode if not already in any UV mode (needed for GetActiveUVSet to works) if doc.GetMode() not in [c4d.Muvpoints, c4d.Muvpolygons]: doc.SetMode(c4d.Muvpolygons) # Retrieves active UVSet, The UV windows need to be opened at least one time handle = c4d.modules.bodypaint.GetActiveUVSet(doc, c4d.GETACTIVEUVSET_ALL) if handle is None: # If fail it may be because the Texture view is not open # Open A texture View c4d.CallCommand(170103) # In S22 you need to update the UV Mesh if c4d.API_VERSION >= 22000: c4d.modules.bodypaint.UpdateMeshUV(False) # Retrieves active UVSet, The UV windows need to be opened at least one time handle = c4d.modules.bodypaint.GetActiveUVSet(doc, c4d.GETACTIVEUVSET_ALL) if handle is None: raise RuntimeError("There is no Active UVSet") # Prints UVSet information print("UV Handle Data:") print("Handle: {0}".format(handle)) print("Handle Mode: {0}".format(handle.GetMode())) print("Handle Points: {0}".format(handle.GetPoints())) print("Handle Polygons: {0}".format(handle.GetPolys())) print("Handle Polygon Selection: {0}".format(handle.GetPolySel())) print("Handle Hidden Polygons: {0}".format(handle.GetPolyHid())) print("Handle Point Selection: {0}".format(handle.GetUVPointSel())) print("Handle Point Count: {0}".format(handle.GetPointCount())) print("Handle Polygon Count: {0}".format(handle.GetPolyCount())) print("Handle Object: {0}".format(handle.GetBaseObject())) print("Handle Editable: {0}".format(handle.IsEditable())) print("Handle UVW: {0}".format(handle.GetUVW())) # Builds UVCOMMAND_TRANSFORM container for the command settings settings = c4d.BaseContainer() settings[c4d.UVCOMMAND_TRANSFORM_MOVE_X] = 0 settings[c4d.UVCOMMAND_TRANSFORM_MOVE_Y] = 0 settings[c4d.UVCOMMAND_TRANSFORM_SCALE_X] = 1 settings[c4d.UVCOMMAND_TRANSFORM_SCALE_Y] = 1 settings[c4d.UVCOMMAND_TRANSFORM_ANGLE] = c4d.utils.DegToRad(90) # Retrieves UVW list uvw = handle.GetUVW() if uvw is None: raise RuntimeError( "Failed to retrieve the uvw from the the texture view.") # Calls UVCOMMAND_TRANSFORM to change UVW list ret = c4d.modules.bodypaint.CallUVCommand(handle.GetPoints(), handle.GetPointCount(), handle.GetPolys(), handle.GetPolyCount(), uvw, handle.GetPolySel(), handle.GetUVPointSel(), op, handle.GetMode(), c4d.UVCOMMAND_TRANSFORM, settings) if not ret: raise RuntimeError("CallUVCommand failed.") # Sets the transformedUVW from Texture View if not handle.SetUVWFromTextureView(uvw, True, True, True): raise RuntimeError("UVW from Texture View failed to be set.") print("UVW from Texture View successfully set") # Releases active UVSet c4d.modules.bodypaint.FreeActiveUVSet(handle)
def ctrl_hold(): state = c4d.BaseContainer() gui.GetInputEvent(c4d.BFM_INPUT_KEYBOARD, state) res = state.GetData(c4d.BFM_INPUT_QUALIFIER) == c4d.QCTRL return res
def do_one_file(inputfile): helper = helperClass() inputStructure = inputfile.split('-')[0] inputStage = inputfile.split('-')[1] print('inputStructure ' + inputStructure) print('inputStage ' + inputStage) outputDirectory = os.path.join(outputBasePath, outputStructures[inputStructure], outputStages[inputStage]) print(outputDirectory) inputfile = inputfile + '.obj' c4d.documents.LoadFile( os.path.join(current_dir, 'base-visual-cell-maker-file.c4d')) doc = helper.getCurrentScene() filename = inputfile file_to_load = os.path.join(loadpath, filename) # Import without dialogs c4d.documents.MergeDocument(doc, file_to_load, c4d.SCENEFILTER_OBJECTS, None) c4d.EventAdd() # get the main object target_obj = helper.getObject(filename) print(target_obj.GetName()) tp = target_obj.GetDown() while tp is not None: print("tp name = ", tp.GetName()) i = int(tp.GetName()[-1]) doc.SetSelection(tp) # getting rid of tags that came from chimera tp.KillTag(c4d.Tnormal) tp.KillTag(c4d.Ttexture) tp.KillTag(c4d.Tphong) tp.MakeTag(c4d.Tphong) c4d.CallCommand(14039, 14039) # Optimize c4d.CallCommand(14039, 14039) # Optimize # doc.InsertObject(smoothing_deformer) # reducer = c4d.BaseObject(1001253) # Polgyon reduction # reducer[c4d.POLYREDUCTIONOBJECT_STRENGTH] = settings[i]['polygonReduction'] # helper.setName(reducer, "Polygon_Reduction_"+tp.GetName()) # helper.AddObject(reducer, parent=tp) # displacer = helper.getObject("displacer_" + str(i)) # helper.reParent(displacer, tp) if i == 1: CellMembraneHolster = helper.getObject("Holster_1") while CellMembraneHolster.GetDown() is not None: # tp is not None: helper.reParent(CellMembraneHolster.GetDown(), tp) if i == 2: DNAHolster = helper.getObject("Holster_2") while DNAHolster.GetDown() is not None: # tp is not None: helper.reParent(DNAHolster.GetDown(), tp) if i == 3: StructureHolster = helper.getObject("Holster_3") while StructureHolster.GetDown() is not None: # tp is not None: helper.reParent(StructureHolster.GetDown(), tp) # smoothing_deformer = c4d.BaseObject(1024529) # smoothing deformer # smoothing_deformer[c4d.ID_CA_SMOOTHING_DEFORMER_OBJECT_STRENGTH] = settings[i]['smoothStrength'] # helper.setName(smoothing_deformer, "Smoothing_"+tp.GetName()) # helper.AddObject(smoothing_deformer, parent=tp) tp = tp.GetNext() res = utils.SendModelingCommand( command=c4d.MCOMMAND_CURRENTSTATETOOBJECT, list=[target_obj], doc=doc, # flags = c4d.MODELINGCOMMANDFLAGS_CREATEUNDO ) res = res[0] helper.setName(res, helper.getName(res) + '_reduced') print("created reduced object") helper.AddObject(res) doc.SetSelection(target_obj) target_obj[c4d.ID_BASEOBJECT_VISIBILITY_RENDER] = 1 c4d.EventAdd() # return # c4d.documents.SaveDocument(doc, os.path.join(current_dir, 'gj.c4d'), c4d.SAVEDOCUMENTFLAGS_0, c4d.FORMAT_C4DEXPORT) c4d.documents.SaveDocument( doc, os.path.join(outputDirectory, inputStructure + '_prebake' + '.c4d'), c4d.SAVEDOCUMENTFLAGS_0, c4d.FORMAT_C4DEXPORT) print("deleting original target object") target_obj.Remove() c4d.EventAdd() material = doc.GetFirstMaterial() tp = res.GetDown() # enter polygon edit mode c4d.CallCommand(12187) # Polygons while tp is not None: print("make texture tag") texture = tp.MakeTag(c4d.Ttexture) texture[ c4d.TEXTURETAG_PROJECTION] = c4d.TEXTURETAG_PROJECTION_SPHERICAL texture[c4d.TEXTURETAG_MATERIAL] = material doc.SetSelection(texture) # makes a uvw tag on the object c4d.CallCommand(12235, 12235) # Generate UVW Coordinates print("generate uvw coords") doc.SetSelection(tp.GetTag(c4d.Tuvw)) uvsettings = c4d.BaseContainer() uvsettings.SetBool(c4d.OPTIMALMAPPING_PRESERVEORIENTATION, False) uvsettings.SetBool(c4d.OPTIMALMAPPING_STRETCHTOFIT, True) uvsettings.SetFloat(c4d.OPTIMALMAPPING_DISTORTION, 0.01) uvsettings.SetInt32(c4d.OPTIMALMAPPING_RELAXCOUNT, 0) uvsettings.SetFloat(c4d.OPTIMALMAPPING_SPACING, 0.01) print("get active uv set") uvset = c4d.modules.bodypaint.GetActiveUVSet(doc, c4d.GETACTIVEUVSET_ALL) uvw = uvset.GetUVW() # if tp.GetName()[-2:] == '_2': #switch these ifs for expensive structures during debugging if 1 == 1: uv_ok = c4d.modules.bodypaint.CallUVCommand( uvset.GetPoints(), uvset.GetPointCount(), uvset.GetPolys(), uvset.GetPolyCount(), uvw, uvset.GetPolySel(), uvset.GetUVPointSel(), tp, c4d.Mpolygons, c4d.UVCOMMAND_OPTIMALMAPPING, uvsettings) print("call uv command:", uv_ok) uvset.SetUVWFromTextureView(uvw, True, True, True) c4d.modules.bodypaint.FreeActiveUVSet(uvset) tp = tp.GetNext() subdiv = helper.getObject("Subdivision Surface") tp = res.GetDown() i = 0 membraneobj = None while i < 3: if tp.GetName()[-2:] == '_1': membraneobj = tp break tp = tp.GetNext() i = i + 1 children = [] tp = res.GetDown() while tp is not None: # tp is not None: children.append(tp) tp = tp.GetNext() for tp in children: # tp is not None: if tp.GetName() == membraneobj.GetName(): # switch object on membraneobj[c4d.ID_BASEOBJECT_VISIBILITY_RENDER] = 2 else: # switch object off membraneobj[c4d.ID_BASEOBJECT_VISIBILITY_RENDER] = 1 if tp.GetName( )[-2:] != '_2': # do not subdivide the nucleus before baking print("reparent to subdiv for baking") helper.reParent(tp, subdiv) bake = c4d.BaseContainer() bake.SetBool(c4d.BAKE_TEX_AMBIENT_OCCLUSION, True) bake.SetInt32(c4d.BAKE_TEX_WIDTH, 1024) bake.SetInt32(c4d.BAKE_TEX_HEIGHT, 1024) bake.SetInt32(c4d.BAKE_TEX_PIXELBORDER, 3) bake.SetInt32(c4d.BAKE_TEX_SUPERSAMPLING, 0) (bakedoc, result) = c4d.utils.InitBakeTexture(doc, tp.GetTag(c4d.Ttexture), tp.GetTag(c4d.Tuvw), None, bake) if result != c4d.BAKE_TEX_ERR_NONE: print("InitBakeTexture error") else: output_bmp = c4d.bitmaps.MultipassBitmap(1024, 1024, c4d.COLORMODE_ARGB) bakeobj = BakeOneObj( output_bmp, os.path.join(outputDirectory, fileNames[int(tp.GetName()[-1:])] + '_ao.jpg')) print("BakeTexture " + fileNames[int(tp.GetName()[-1:])]) c4d.utils.BakeTexture(bakedoc, bake, output_bmp, None, bakeobj.onbakeprogress) bakeobj.wait() print("done baking, reparenting to done") helper.reParent(tp, helper.getObject('done')) c4d.EventAdd() # print(fileNames[int(tp.GetName()[-1:])] + '_ao') # print("reparent to done") # helper.reParent(tp, res) # done with "res" since everything is reparented to "done" doc.SetSelection(res) res[c4d.ID_BASEOBJECT_VISIBILITY_RENDER] = 1 c4d.EventAdd() res.Remove() c4d.EventAdd() tp = helper.getObject('done').GetDown() # while tp is not None: # tp is not None: for tp in children: # rotate by 90 degrees tp.SetAbsRot(c4d.Vector(0, c4d.utils.DegToRad(-90), 0)) newdoc = c4d.documents.IsolateObjects(doc, [tp]) c4d.documents.SaveDocument( newdoc, os.path.join(outputDirectory, fileNames[int(tp.GetName()[-1:])] + '.obj'), c4d.SAVEDOCUMENTFLAGS_0, c4d.FORMAT_OBJ2EXPORT) print(fileNames[int(tp.GetName()[-1:])] + '.obj') c4d.EventAdd() c4d.documents.KillDocument(newdoc) c4d.EventAdd() doc.SetDocumentName('tmp') c4d.documents.SaveDocument(doc, os.path.join(current_dir, 'tmp.c4d'), c4d.SAVEDOCUMENTFLAGS_0, c4d.FORMAT_C4DEXPORT) c4d.EventAdd() c4d.documents.KillDocument(doc) c4d.documents.CloseAllDocuments()
def __init__(self): super(Dialog, self).__init__() self.res = c4d.BaseContainer()
def get_subcontainer(bc, sub_id): if not has_subcontainer(bc, sub_id): bc.SetContainer(sub_id, c4d.BaseContainer()) assert has_subcontainer(bc, sub_id) return bc.GetContainerInstance(sub_id)
def insertObject(pX, pY, pZ, pWidth, pHeight, pDepth, pIndex): #INSERT A CUBE obj = c4d.BaseObject(c4d.Ocube) obj[c4d.PRIM_CUBE_SUBX] = 2 obj[c4d.PRIM_CUBE_SUBY] = 2 obj[c4d.PRIM_CUBE_SUBZ] = 2 obj[c4d.PRIM_CUBE_LEN] = c4d.Vector(pWidth, pHeight, pDepth) res = utils.SendModelingCommand(command=c4d.MCOMMAND_CURRENTSTATETOOBJECT, list=[obj], mode=c4d.MODELINGCOMMANDMODE_ALL, bc=c4d.BaseContainer(), doc=doc)[0] res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_X] = pX res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_Y] = pY res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_Z] = pZ res[c4d.ID_BASELIST_NAME] = "cuby_" + str(pIndex) doc.InsertObject(res) doc.SetActiveObject(res, c4d.SELECTION_NEW) c4d.EventAdd() #EXTRUDE THE SURFACES TO RANDOM LENGTHS sel = res.GetPolygonS() c4d.CallCommand(12187) # Polygons #PASS 1 - CREATE A BASE SHAPE for growthCounter in range(0, 100): for f in range(0, 23): c4d.CallCommand(13324) # Deselect All sel.Select(f) c4d.CallCommand(1011183) # Extrude getTool()[c4d.MDATA_EXTRUDE_OFFSET] = randrange(10, 40) * 1.0 fireAction(obj) #PASS 2 - ADD EXTRUSIONS TO RANDOM FACES sel = res.GetPolygonS() c4d.CallCommand(12187) # Polygons for f in range(0, 500): c4d.CallCommand(13324) # Deselect All sel.Select(f) #INNER EXTRUDE c4d.CallCommand(450000004) # Extrude Inner getTool()[c4d.MDATA_EXTRUDEINNER_OFFSET] = randrange(2, 30) * 1.0 fireAction(obj) #OUTER c4d.CallCommand(1011183) # Extrude getTool()[c4d.MDATA_EXTRUDE_OFFSET] = randrange(9, 30) * -1.0 fireAction(obj) #kick out a render doc[c4d.RDATA_PATH] = "" c4d.CallCommand(12098) # Save c4d.CallCommand(12099) # Render to Picture Viewer return obj
def main(): doc = c4d.documents.GetActiveDocument() # Get active Cinema 4D document doc.StartUndo() # Start recording undos folder = s.LoadDialog(c4d.FILESELECTTYPE_ANYTHING, 'Select image folder', c4d.FILESELECT_DIRECTORY, '') if not folder: return # If no folder, quit the script bc = c4d.BaseContainer() # Initialize a base container keyMod = "None" # Initialize a keyboard modifier status # Button is pressed if c4d.gui.GetInputState(c4d.BFM_INPUT_KEYBOARD, c4d.BFM_INPUT_CHANNEL, bc): if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QSHIFT: if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QCTRL: # Ctrl + Shift if bc[c4d. BFM_INPUT_QUALIFIER] & c4d.QALT: # Alt + Ctrl + Shift keyMod = 'Alt+Ctrl+Shift' else: # Shift + Ctrl keyMod = 'Ctrl+Shift' elif bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QALT: # Alt + Shift keyMod = 'Alt+Shift' else: # Shift keyMod = 'Shift' elif bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QCTRL: if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QALT: # Alt + Ctrl keyMod = 'Alt+Ctrl' else: # Ctrl keyMod = 'Ctrl' elif bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QALT: # Alt keyMod = 'Alt' else: # No keyboard modifiers used keyMod = 'None' try: # Try to execute following script files = os.listdir(folder) for f in files: # Loop through files extension = f.rpartition(".")[-1].lower() formats = [ "tif", "tiff", "psd", "jpg", "jpeg", "png", "exr", "tga" ] # Supported file formats if extension in formats: # If file is supported mat = c4d.BaseMaterial(c4d.Mmaterial) path = os.path.join(folder, f) #path = folder+"\\"+f mat[c4d. MATERIAL_USE_REFLECTION] = 0 # Disable reflection channel # Color channel color = c4d.BaseShader(c4d.Xbitmap) color[c4d.BITMAPSHADER_FILENAME] = path mat[c4d.MATERIAL_COLOR_SHADER] = color # Get bitmap size irs = c4d.modules.render.InitRenderStruct( ) # Needed to get shader's bitmap info if color.InitRender(irs) == c4d.INITRENDERRESULT_OK: bitmap = color.GetBitmap() # Get bitmap color.FreeRender( ) # Frees all resources used by this shader if bitmap is not None: # If there is bitmap width = bitmap.GetSize()[ 0] # Get bitmap width in pixels height = bitmap.GetSize()[ 1] # Get bitmap height in pixels # Luminance channel luminance = c4d.BaseShader(c4d.Xbitmap) luminance[c4d.BITMAPSHADER_FILENAME] = path mat[c4d.MATERIAL_LUMINANCE_SHADER] = luminance # Alpha channel alpha = c4d.BaseShader(c4d.Xbitmap) alpha[c4d.BITMAPSHADER_FILENAME] = path mat[c4d.MATERIAL_ALPHA_SHADER] = alpha # Assign shaders to material mat.InsertShader(color) # Insert shader to color channel mat.InsertShader( luminance) # Insert shader to luminance channel mat.InsertShader(alpha) # Insert shader to alpha channel # Other stuff mat.Message(c4d.MSG_UPDATE) mat.Update(True, True) # Update material matname = f.rpartition(".")[ 0] # Get material name from file path mat.SetName(matname) # Set material name doc.InsertMaterial(mat) # Insert new material to document doc.AddUndo(c4d.UNDOTYPE_NEW, mat) # Add undo command for inserting new material if keyMod == "Shift": # If Shift key pressed - Generate planes and assign materials to them # Create plane plane = c4d.BaseObject( c4d.Oplane) # Initialize plane object plane.SetName( matname) # Set plane's name same as the material name plane[c4d.PRIM_AXIS] = 5 # Set plane's orientation to -z plane[ c4d.PRIM_PLANE_SUBW] = 1 # Set plane's width segments plane[ c4d.PRIM_PLANE_SUBH] = 1 # Set plane's height segments plane[c4d.PRIM_PLANE_WIDTH] = width # Set plane's width plane[c4d.PRIM_PLANE_HEIGHT] = height # Set planes height doc.InsertObject(plane) # Insert plane to document doc.AddUndo( c4d.UNDOTYPE_NEW, plane ) # Add undo command for inserting plane to document # Texture tag t = c4d.BaseTag(5616) # Initialize texture tag plane.InsertTag(t) # Insert texture tag to object tag = plane.GetFirstTag() # Get object's first tag tag[c4d. TEXTURETAG_MATERIAL] = mat # Set material to texture tag tag[c4d. TEXTURETAG_PROJECTION] = 6 # Set texture projection to uvw mapping doc.AddUndo( c4d.UNDOTYPE_NEW, tag ) # Add undo command for inserting texture tag to object except: # If something went wrong pass # Do nothing doc.EndUndo() # Stop recording undos c4d.EventAdd() # Refresh Cinema 4D
def CreateLayout(self): """ This method is called automatically when Cinema 4D Create the Layout (display) of the Dialog. """ # Defines the title of the Dialog self.SetTitle("A Custom Dialog with a Top Menu") # Flushes all the already existing menu to create our one. The content will be on the left. self.MenuFlushAll() # Creates a Sub menu begin to insert new menu entry self.MenuSubBegin("Left Menu") # Adds a string with a given ID, so it will trigger a call to Command once clicked self.MenuAddString(self.ID_LEFT_MENU_FIRST_ITEM, "Close") # Finalizes the Sub Menu self.MenuSubEnd() # Finalizes the menu self.MenuFinished() # Creates a Group in the Menu. The content will be on the right if self.GroupBeginInMenuLine(): # Creates a BitmapButtonCustomGui with the find icon settings = c4d.BaseContainer() settings[c4d.BITMAPBUTTON_BUTTON] = True settings[c4d.BITMAPBUTTON_BORDER] = False settings[c4d.BITMAPBUTTON_TOGGLE] = True settings[ c4d. BITMAPBUTTON_ICONID1] = c4d.RESOURCEIMAGE_SCENEBROWSER_FIND2 settings[ c4d. BITMAPBUTTON_ICONID2] = c4d.RESOURCEIMAGE_SCENEBROWSER_FIND1 self.displayContentButtonDlg = self.AddCustomGui( self.ID_RIGHT_MENU_SHOW_CONTENT, c4d.CUSTOMGUI_BITMAPBUTTON, "", c4d.BFH_CENTER | c4d.BFV_CENTER, 0, 0, settings) self.GroupEnd() # Creates a group that will contain the content that will be hidden when the BitmapButton is pressed. It's # important to have a parent group to the group that needs to be hidden since you need to redraw this parent # group after the visibility definition. if self.GroupBegin(self.ID_MAIN_GROUP, c4d.BFH_LEFT | c4d.BFV_CENTER): # The group that will be hidden if self.GroupBegin(self.ID_HIDDEN_GROUP, c4d.BFH_LEFT | c4d.BFV_CENTER): # Adds the content you want to toggle self.AddStaticText(0, c4d.BFH_LEFT | c4d.BFV_CENTER, name="test") self.GroupEnd() self.GroupEnd() # Adds two buttons, Ok and Cancel self.AddDlgGroup(c4d.DLG_OK | c4d.DLG_CANCEL) return True
def StopProgress(self): self.set_status('IMPORT MODEL') progressMsg = c4d.BaseContainer(c4d.BFM_SETSTATUSBAR) progressMsg.SetBool(c4d.BFM_STATUSBAR_PROGRESSON, False) self.SendMessage(UI_PROGRESSBAR, progressMsg)
def Timer(self, msg): progressMsg = c4d.BaseContainer(c4d.BFM_SETSTATUSBAR) progressMsg[c4d.BFM_STATUSBAR_PROGRESSON] = True progressMsg[c4d.BFM_STATUSBAR_PROGRESS] = self.progress self.SendMessage(UI_PROGRESSBAR, progressMsg) self.refresh_window()
def EnableStatusBar(self): progressMsg = c4d.BaseContainer(c4d.BFM_SETSTATUSBAR) progressMsg[c4d.BFM_STATUSBAR_PROGRESSON] = True progressMsg[c4d.BFM_STATUSBAR_PROGRESS] = 0.2
def main(): # General doc = c4d.documents.GetActiveDocument() obj = doc.GetActiveObject() bc = c4d.BaseContainer() prefix = ("OR_") a = ("== ") b = (" ==") separator = (a + b + "&d&") # Icons ico_none = "&i1&" ico_RenderAllMats = "&i12253&" ico_DelUnusedMat = "&i12168&" ico_mix = "&i1033895&" ico_tags = "&i5616&" ico_node = "&i1033872&" ico_texman = "&i1035275&" ico_convert = "&i1029770&" # -- Build Menu -- entries = c4d.BaseContainer() # Node Editor Block entries.SetString(20, ico_none + a + "Node Editor" + b + "&d&") entries.SetString(21, ico_node + prefix + "Node Editor") # MixMat Block entries.SetString(000, ico_none + a + "Mix Mat" + b + "&d&") entries.SetString(11, ico_mix + prefix + "Duplicate Mix") entries.SetString(13, ico_mix + prefix + "Mix Mat") entries.SetString(14, ico_mix + prefix + "Rename Mix2") entries.SetString(15, ico_mix + prefix + "Select Father Mix") entries.SetString(16, ico_mix + prefix + "Select Mix Group") entries.SetString(17, ico_mix + prefix + "Select Top Mix") entries.SetString(18, ico_mix + prefix + "Switch Mix") # MatTool Block entries.SetString(200, ico_none + a + "Mat Tool" + b + "&d&") entries.SetString(201, ico_texman + prefix + "Tex Manager") entries.SetString(202, ico_convert + prefix + "Convert Mats") # MatHelp Block entries.SetString(100, ico_none + a + "MatHelp" + b + "&d&") entries.SetString(101, ico_tags + prefix + "Del Disabled MatTag") entries.SetString(102, ico_DelUnusedMat + prefix + "Del Unused Mat") entries.SetString(103, ico_RenderAllMats + prefix + " Render All Mats") # -- Build Objects -- def DuplicateMix(): mixlist = [] matgroup = [] matgroup2 = [] templist = [] matgroupnew = [] matgroupnewmix = [] i = 0 j = 0 matlist = doc.GetMaterials() SelMat = doc.GetActiveMaterial() for mat in matlist: if mat.GetType() == 1029622: # MixMaterial type int mixlist.append(mat) # get all mixmaterials in doc while i < len(mixlist): for mat in mixlist: if SelMat == mat[c4d.MIXMATERIAL_TEXTURE1] or SelMat == mat[ c4d.MIXMATERIAL_TEXTURE2]: SelMat = mat i = i + 1 if SelMat == None: gui.MessageDialog('Not Mixed!') # determine if selected material in any mix group c4d.CallCommand(300001026, 300001026) # Deselect all mat while SelMat.GetType() == 1029622: SelMat.SetBit(c4d.BIT_ACTIVE) while SelMat[c4d.MIXMATERIAL_TEXTURE1].GetType() == 1029622: SelMat = SelMat[c4d.MIXMATERIAL_TEXTURE1] SelMat.SetBit(c4d.BIT_ACTIVE) while SelMat[c4d.MIXMATERIAL_TEXTURE2].GetType() == 1029622: SelMat = SelMat[c4d.MIXMATERIAL_TEXTURE2] SelMat.SetBit(c4d.BIT_ACTIVE) SelMat = SelMat[c4d.MIXMATERIAL_TEXTURE1] mixlist2 = doc.GetActiveMaterials() # get all mixmaterials in selected mix group for mat in mixlist2: mat[c4d.MIXMATERIAL_TEXTURE1].SetBit(c4d.BIT_ACTIVE) mat[c4d.MIXMATERIAL_TEXTURE2].SetBit(c4d.BIT_ACTIVE) matgroup = doc.GetActiveMaterials() matgroup.reverse() # get all materials in seleceted mix group for mat in matgroup: matb = mat.GetClone() doc.InsertMaterial(matb) matgroupnew.append(matb) for mat in matgroupnew: if mat.GetType() == 1029622: matgroupnewmix.append(mat) matgroupnewmix.reverse() # dupilcate new materials c4d.CallCommand(300001026, 300001026) # Deselect all mat while j < len(mixlist2): ind1 = matgroup.index(mixlist2[j][c4d.MIXMATERIAL_TEXTURE1]) matgroupnewmix[j][c4d.MIXMATERIAL_TEXTURE1] = matgroupnew[ind1] ind2 = matgroup.index(mixlist2[j][c4d.MIXMATERIAL_TEXTURE2]) matgroupnewmix[j][c4d.MIXMATERIAL_TEXTURE2] = matgroupnew[ind2] j = j + 1 # insert sub materials for each mixmaterial c4d.EventAdd() def MixMat(): doc.StartUndo() matlist = doc.GetActiveMaterials() if len(matlist) > 1: mixmat = c4d.BaseMaterial(1029622) doc.InsertMaterial(mixmat) doc.AddUndo(c4d.UNDOTYPE_NEW, mixmat) doc.AddUndo(c4d.UNDOTYPE_CHANGE, mixmat) mixmat[c4d.MIXMATERIAL_TEXTURE1] = matlist[0] mixmat[c4d.MIXMATERIAL_TEXTURE2] = matlist[1] doc.AddUndo(c4d.UNDOTYPE_CHANGE, mixmat) mixmat[c4d.ID_BASELIST_NAME] = matlist[0][ c4d.ID_BASELIST_NAME] + '|' + matlist[1][c4d.ID_BASELIST_NAME] else: return c4d.EventAdd() doc.EndUndo() def RenameMix2(): def CtrlKey(): bc = c4d.BaseContainer() if c4d.gui.GetInputState(c4d.BFM_INPUT_KEYBOARD, c4d.BFM_INPUT_CHANNEL, bc): if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QCTRL: return True else: return False def RenameMixN(): mixlist = [] i = 0 j = 2 matlist = doc.GetMaterials() SelMat = doc.GetActiveMaterial() for mat in matlist: if mat.GetType() == 1029622: # MixMaterial type int mixlist.append(mat) # print mixlist while i < len(mixlist): for mat in mixlist: if SelMat == mat[ c4d.MIXMATERIAL_TEXTURE1] or SelMat == mat[ c4d.MIXMATERIAL_TEXTURE2]: SelMat = mat i = i + 1 name = SelMat.GetName().split("|")[0] SelMat.SetName(name + "|●") while SelMat[ c4d.MIXMATERIAL_TEXTURE1].GetType() == 1029622 or SelMat[ c4d.MIXMATERIAL_TEXTURE2].GetType() == 1029622: if SelMat[c4d.MIXMATERIAL_TEXTURE1].GetType() == 1029622: SelMat = SelMat[c4d.MIXMATERIAL_TEXTURE1] else: SelMat = SelMat[c4d.MIXMATERIAL_TEXTURE2] SelMat.SetName(name + "|" + j * "●") j = j + 1 c4d.EventAdd() def RenameMixP(): mixlist = [] mixlist2 = [] i = 0 j = 1 matlist = doc.GetMaterials() SelMat = doc.GetActiveMaterial() for mat in matlist: if mat.GetType() == 1029622: # MixMaterial type int mixlist.append(mat) # print mixlist while i < len(mixlist): for mat in mixlist: if SelMat == mat[ c4d.MIXMATERIAL_TEXTURE1] or SelMat == mat[ c4d.MIXMATERIAL_TEXTURE2]: SelMat = mat i = i + 1 name = SelMat.GetName().split("|")[0] top = SelMat SelMat2 = SelMat while SelMat2[ c4d.MIXMATERIAL_TEXTURE1].GetType() == 1029622 or SelMat2[ c4d.MIXMATERIAL_TEXTURE2].GetType() == 1029622: if SelMat2[c4d.MIXMATERIAL_TEXTURE1].GetType() == 1029622: SelMat2 = SelMat2[c4d.MIXMATERIAL_TEXTURE1] j = j + 1 else: SelMat2 = SelMat2[c4d.MIXMATERIAL_TEXTURE2] j = j + 1 top.SetName(name + "|" + j * "●") while SelMat[ c4d.MIXMATERIAL_TEXTURE1].GetType() == 1029622 or SelMat[ c4d.MIXMATERIAL_TEXTURE2].GetType() == 1029622: j = j - 1 if SelMat[c4d.MIXMATERIAL_TEXTURE1].GetType() == 1029622: SelMat = SelMat[c4d.MIXMATERIAL_TEXTURE1] else: SelMat = SelMat[c4d.MIXMATERIAL_TEXTURE2] SelMat.SetName(name + "|" + j * "●") c4d.EventAdd() if __name__ == '__main__': if CtrlKey(): RenameMixN() else: RenameMixP() def SelectFatherMix(): mixlist = [] i = 0 matlist = doc.GetMaterials() SelMat = doc.GetActiveMaterial() for mat in matlist: if mat.GetType() == 1029622: # MixMaterial type int mixlist.append(mat) # print mixlist for mat in mixlist: if SelMat == mat[c4d.MIXMATERIAL_TEXTURE1] or SelMat == mat[ c4d.MIXMATERIAL_TEXTURE2]: SelMat = mat if SelMat == None: gui.MessageDialog('Not Mixed!') # print len(mixlist) c4d.CallCommand(300001026, 300001026) # Deselect all mat SelMat.SetBit(c4d.BIT_ACTIVE) c4d.EventAdd() def SelectMixGroup(): mixlist = [] i = 0 matlist = doc.GetMaterials() SelMat = doc.GetActiveMaterial() for mat in matlist: if mat.GetType() == 1029622: # MixMaterial type int mixlist.append(mat) # print mixlist while i < len(mixlist): for mat in mixlist: if SelMat == mat[c4d.MIXMATERIAL_TEXTURE1] or SelMat == mat[ c4d.MIXMATERIAL_TEXTURE2]: SelMat = mat i = i + 1 if SelMat == None: gui.MessageDialog('Not Mixed!') # print len(mixlist) c4d.CallCommand(300001026, 300001026) # Deselect all mat # SelMat.SetBit(c4d.BIT_ACTIVE) while SelMat.GetType() == 1029622: SelMat.SetBit(c4d.BIT_ACTIVE) while SelMat[c4d.MIXMATERIAL_TEXTURE1].GetType() == 1029622: SelMat = SelMat[c4d.MIXMATERIAL_TEXTURE1] SelMat.SetBit(c4d.BIT_ACTIVE) while SelMat[c4d.MIXMATERIAL_TEXTURE2].GetType() == 1029622: SelMat = SelMat[c4d.MIXMATERIAL_TEXTURE2] SelMat.SetBit(c4d.BIT_ACTIVE) SelMat = SelMat[c4d.MIXMATERIAL_TEXTURE1] mixlist2 = doc.GetActiveMaterials() for mat in mixlist2: mat[c4d.MIXMATERIAL_TEXTURE1].SetBit(c4d.BIT_ACTIVE) mat[c4d.MIXMATERIAL_TEXTURE2].SetBit(c4d.BIT_ACTIVE) matgroup = doc.GetActiveMaterials() def SelectTopMix(): mixlist = [] i = 0 matlist = doc.GetMaterials() SelMat = doc.GetActiveMaterial() for mat in matlist: if mat.GetType() == 1029622: # MixMaterial type int mixlist.append(mat) # print mixlist while i < len(mixlist): for mat in mixlist: if SelMat == mat[c4d.MIXMATERIAL_TEXTURE1] or SelMat == mat[ c4d.MIXMATERIAL_TEXTURE2]: SelMat = mat i = i + 1 if SelMat == None: gui.MessageDialog('Not Mixed!') # print len(mixlist) c4d.CallCommand(300001026, 300001026) # Deselect all mat SelMat.SetBit(c4d.BIT_ACTIVE) c4d.EventAdd() def SwitchMix(): mat = doc.GetActiveMaterial() mata = mat[c4d.MIXMATERIAL_TEXTURE1] matb = mat[c4d.MIXMATERIAL_TEXTURE2] mat[c4d.MIXMATERIAL_TEXTURE1] = matb mat[c4d.MIXMATERIAL_TEXTURE2] = mata c4d.EventAdd() def Tex(): c4d.CallCommand(1035275) c4d.EventAdd() def Convert(): active_mat = doc.GetActiveMaterial() if active_mat == None: gui.MessageDialog("Please select at least one Material") c4d.CallCommand(1029770, 1029770) c4d.EventAdd() def DelDisableTag(): def nextObj(obj): if not obj: return elif obj.GetDown(): return obj.GetDown() while obj.GetUp() and not obj.GetNext(): obj = obj.GetUp() return obj.GetNext() def main(): obj = doc.GetFirstObject() if not obj: return doc.StartUndo() while obj: for tag in obj.GetTags(): if tag.GetType() == 5616: if tag[c4d.TEXTURETAG_MATERIAL] == None: doc.AddUndo(c4d.UNDOTYPE_CHANGE, tag) tag.Remove() obj = nextObj(obj) doc.EndUndo() c4d.EventAdd() if __name__ == '__main__': main() def RenderAllMats(): c4d.CallCommand(12253, 12253) # Render All Material c4d.EventAdd() def Node(): c4d.CallCommand(1033872) c4d.EventAdd() def DelUnusedMat(): c4d.CallCommand(12168, 12168) # Remove Unused Materials c4d.EventAdd() ########### -- User Input -- ########### result = gui.ShowPopupDialog(cd=None, bc=entries, x=c4d.MOUSEPOS, y=c4d.MOUSEPOS, flags=c4d.POPUP_RIGHT) if result == 11: DuplicateMix() elif result == 12: FolderMix() elif result == 13: MixMat() elif result == 14: RenameMix2() elif result == 15: SelectFatherMix() elif result == 16: SelectMixGroup() elif result == 17: SelectTopMix() elif result == 18: SwitchMix() elif result == 201: Tex() elif result == 202: Convert() elif result == 101: DelDisableTag() elif result == 102: DelUnusedMat() elif result == 103: RenderAllMats() else: return
def GetMesh(code): # goto 0 doc.SetTime(c4d.BaseTime(0, fps)) c4d.DrawViews(c4d.DA_ONLY_ACTIVE_VIEW | c4d.DA_NO_THREAD | c4d.DA_NO_REDUCTION | c4d.DA_STATICBREAK) c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED) doc.SetTime(doc.GetTime()) c4d.EventAdd(c4d.EVENT_ANIMATE) SendModelingCommand(command=c4d.MCOMMAND_REVERSENORMALS, list=[op], mode=c4d.MODIFY_ALL, bc=c4d.BaseContainer(), doc=doc) verts = op.GetAllPoints() for v in verts: code += '\tv( %.6f, %.6f, %.6f );\n' % (v.x, -v.y, v.z) code += '\n' ncount = 0 uvcount = 0 faces = op.GetAllPolygons() normals = op.CreatePhongNormals() ndirection = 1 hasUV = False for tag in op.GetTags(): if tag.GetName() == "UVW": uvw = tag hasUV = True for f in faces: if (f.d == f.c): if (normals): code += '\tf3( %d, %d, %d, %.6f, %.6f, %.6f );\n' % ( f.a, f.b, f.c, normals[ncount].x * ndirection, normals[ncount].y * ndirection, normals[ncount].z * ndirection) else: code += '\tf3( %d, %d, %d );\n' % (f.a, f.b, f.c) else: if (normals): code += '\tf4( %d, %d, %d, %d, %.6f, %.6f, %.6f );\n' % ( f.a, f.b, f.c, f.d, normals[ncount].x * ndirection, normals[ncount].y * ndirection, normals[ncount].z * ndirection) else: code += '\tf4( %d, %d, %d, %d );\n' % (f.a, f.b, f.c, f.d) if hasUV: uv = uvw.GetSlow(uvcount) # uvs += '[Vector('+str(uv[0].x)+','+str(1.0-uv[0].y)+'),Vector('+str(uv[1].x)+','+str(1.0-uv[1].y)+'),Vector('+str(uv[2].x)+','+str(1.0-uv[2].y)+')],' if len(uv) == 4: # {'a': Vector(1, 1, 0), 'c': Vector(0, 0, 0), 'b': Vector(1, 0, 0), 'd': Vector(0, 1, 0)} code += '\tuv( %.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f);\n' % ( uv['a'].x, uv['a'].y, uv['b'].x, uv['b'].y, uv['b'].x, uv['b'].y, uv['c'].x, uv['c'].y) else: code += '\tuv( %.6f, %.6f, %.6f, %.6f, %.6f, %.6f);\n' % ( uv['a'].x, uv['a'].y, uv['b'].x, uv['b'].y, uv['c'].x, uv['c'].y) ncount += 1 uvcount += 1 code += '\n\tthis.computeCentroids();\n\tthis.computeNormals(true);\n' #selection color code += '\n\tscope.colors = {};\n' code += '\tscope.selections = {};\n' selName = '' for tag in op.GetTags(): if (tag.GetType() == 5616): #texture tag material = tag.GetMaterial() color = material[c4d.MATERIAL_COLOR_COLOR] tag.SetBit(c4d.BIT_ACTIVE) selName = clean(tag[c4d.TEXTURETAG_RESTRICTION]) if len(selName) == 0: print "*** WARNING! *** Missing selection name for material: " + material.GetName( ) code += '\tscope.colors["' + selName + '"] = ' + str( RGBToHTMLColor( (color.x * 255, color.y * 255, color.z * 255))) + ';\n' if tag.GetType() == 5673: #selection tag print 'selection: ' + tag.GetName() print 'selection object: ' + tag sel = tag.GetSelection() selName = clean(tag.GetName()) ids = sel.GetAll(op.GetPointCount()) indices = [i for i, e in enumerate(ids) if e != 0] code += '\tscope.selections["' + selName + '"] = ' + str( indices) + ';\n' code += '\n\tscope.autoColor = function(){\n' code += '\t\tfor(var s in this.selections){\n' code += '\t\t\tfor(var i = 0 ; i < this.selections[s].length; i++) this.faces[this.selections[s][i]].material = [new THREE.MeshBasicMaterial({color:this.colors[s]})];\n' code += '\t\t}\n\t}\n' # model position, rotation, scale rotation x,y,z = H,P,B => three.js x,y,z is P,H,B => y,x,z p = op.GetPos() r = op.GetRot() s = op.GetScale() code += '\n\tscope.getPosition = function(){\treturn new THREE.Vector3' + str( (p.x, p.y, p.z)) + ';\t}\n' code += '\n\tscope.getRotation = function(){\treturn new THREE.Vector3' + str( (r.y, r.x, r.z)) + ';\t}\n' code += '\n\tscope.getScale = function(){\treturn new THREE.Vector3' + str( (s.x, s.y, s.z)) + ';\t}\n' code += '\n' code += '\tfunction v( x, y, z ) {\n\n' code += '\t\tscope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );\n\n' code += '\t}\n\n' code += '\tfunction f3( a, b, c, nx, ny, nz ) {\n\n' code += '\t\tscope.faces.push( new THREE.Face3( a, b, c, nx && ny && nz ? new THREE.Vector3( nx, ny, nz ) : null ) );\n\n' code += '\t}\n\n' code += '\tfunction f4( a, b, c, d, nx, ny, nz ) {\n\n' code += '\t\tscope.faces.push( new THREE.Face4( a, b, c, d, nx && ny && nz ? new THREE.Vector3( nx, ny, nz ) : null ) );\n\n' code += '\t}\n\n' code += '\tfunction uv( u1, v1, u2, v2, u3, v3, u4, v4 ) {\n\n' code += '\t\tvar uv = [];\n' code += '\t\tuv.push( new THREE.UV( u1, v1 ) );\n' code += '\t\tuv.push( new THREE.UV( u2, v2 ) );\n' code += '\t\tuv.push( new THREE.UV( u3, v3 ) );\n' code += '\t\tif ( u4 && v4 ) uv.push( new THREE.UV( u4, v4 ) );\n' code += '\t\tscope.uvs.push( uv );\n' code += '\t}\n\n' code += '}\n\n' code += '%s.prototype = new THREE.Geometry();\n' % classname code += '%s.prototype.constructor = %s;' % (classname, classname) SendModelingCommand(command=MCOMMAND_REVERSENORMALS, list=[op], mode=MODIFY_ALL, bc=c4d.BaseContainer(), doc=doc) return code
def main(): #General doc = c4d.documents.GetActiveDocument() obj = doc.GetActiveObject() null = c4d.BaseObject(5140) light = c4d.BaseObject(5102) target = c4d.BaseTag(5676) protect = c4d.BaseTag(5629) octane_cam_tag = c4d.BaseTag(1029524) octane_light_tag = c4d.BaseTag(1029526) octane_daylight_tag = c4d.BaseTag(1029754) bc = c4d.BaseContainer() prefix = ("OR_") a = ("== ") b = (" ==") separator = (a + b + "&d&") #Icons ico_none = "&i1&" ico_arealight = "&i1033864&" ico_daylight = "&i1033863&" ico_tglight = "&i1033868&" ico_cam = "&i1033865&" ico_diffuse = "&i1033871&" ico_glossy = "&i1033893&" ico_specular = "&i1033894&" ico_mix = "&i1033895&" ico_convert = "&i1029770&" ico_blend = "&i1040118&" ico_metallic = "&i1040116&" ico_universal = "&i1041569&" ico_toon = "&i1040117&" ico_hdrienv = "&i1033867&" ico_texenv = "&i1033866&" ico_scatter = "&i1035961&" ico_volfog = "&i1036589&" ico_volvdb = "&i1037329&" ico_node = "&i1033872&" ico_livedb = "&i1033870&" ico_texman = "&i1035275&" ico_setting = "&i1031195&" ico_viewer = "&i1029499&" # -- Build Menu -- entries = c4d.BaseContainer() # Useful Block entries.SetString(000, ico_none + a + "Basic" + b + "&d&") entries.SetString(10, ico_viewer + prefix + "Live Viewer") entries.SetString(11, ico_node + prefix + "Node Editor") entries.SetString(12, ico_setting + prefix + "Setting") #Camera Block entries.SetString(100, ico_none + a + "Camera" + b + "&d&") #entries.SetString(101, ico_cam + prefix + "Linear AI Cam") entries.SetString(102, ico_cam + prefix + "Octane Cam") #Lights Block entries.SetString(200, ico_none + a + "Lights" + b + "&d&") entries.SetString(201, ico_arealight + prefix + "Area Light") entries.SetString(203, ico_tglight + prefix + "Target Light") #entries.SetString(202, ico_daylight + prefix + "Day Light") #Environments Block entries.SetString(300, ico_none + a + "Env" + b + "&d&") entries.SetString(301, ico_hdrienv + prefix + "HDRI Env") entries.SetString(302, ico_texenv + prefix + "Texture Env") #Materials Block entries.SetString(400, ico_none + a + "Materials" + b + "&d&") entries.SetString(401, ico_diffuse + prefix + "Diffuse") entries.SetString(402, ico_glossy + prefix + "Glossy") entries.SetString(403, ico_specular + prefix + "Specular") entries.SetString(407, ico_metallic + prefix + "Metallic") entries.SetString(404, ico_mix + prefix + "Mix") entries.SetString(408, ico_blend + prefix + "Blend") entries.SetString(406, ico_universal + prefix + "Universal") entries.SetString(409, ico_toon + prefix + "Toon") entries.SetString(405, ico_convert + prefix + "Convert Mats") #Generators Block entries.SetString(500, ico_none + a + "Generators" + b + "&d&") entries.SetString(501, ico_scatter + prefix + "Scatter") entries.SetString(502, ico_volfog + prefix + "Fog Volume") entries.SetString(503, ico_volvdb + prefix + "VDB Volume") #Helpers Block entries.SetString(600, ico_none + a + "Helpers" + b + "&d&") entries.SetString(601, ico_texman + prefix + "Tex Manager") entries.SetString(603, ico_livedb + prefix + "Live DB") # Tools #entries.SetString(700, ico_none + a + "Tools" + b + "&d&") #entries.SetString(701, "Tool_01 On The Way") #entries.SetString(702, "Tool_02 On The Way") # -- Build Objects -- ## --- Cameras --- ## #Octane Camera def AIOctaneCam(): if c4d.gui.GetInputState(c4d.BFM_INPUT_KEYBOARD, c4d.BFM_INPUT_CHANNEL, bc): if bc[c4d.BFM_INPUT_QUALIFIER] == 0: c4d.CallCommand(5103) obj = doc.GetActiveObject() obj.SetName(prefix + "Linear AICam") c4d.EventAdd() elif bc[c4d.BFM_INPUT_QUALIFIER] == 2 and targ_obj == None: c4d.CallCommand(12519, 12519) obj = doc.GetActiveObject() obj.SetName(prefix + "TG Cam") obj[c4d.LIGHT_TYPE] = 8 c4d.EventAdd() else: c4d.CallCommand(5103) obj = doc.GetActiveObject() obj.SetName(prefix + "TG Cam") obj.InsertTag(target) targ_tag = obj.GetFirstTag() targ_tag[c4d.TARGETEXPRESSIONTAG_LINK] = targ_obj c4d.EventAdd() obj = doc.GetActiveObject() obj.InsertTag(octane_cam_tag) doc.SetActiveTag(octane_cam_tag) octane_cam_tag[c4d.OCTANECAMERA_ENABLE_IMAGER] = True octane_cam_tag[c4d.OCTANECAMERA_GAMMA] = 2.2 octane_cam_tag[c4d.OCTANECAMERA_RESPONSE] = 5400 octane_cam_tag[c4d.OCTANECAMERA_VIGNETTING] = 0 octane_cam_tag[c4d.OCT_CAMIMAGER_EN_DENOISER] = True c4d.EventAdd() """Gamma=2.2 Cam Type = Linear Click = Cam Ctrl+Click = Target Cam AI Denoise is ON""" def OctaneCam(): c4d.CallCommand(1033865) # Octane Camera """Normal Cam""" ## --- Lights --- ## #Octane Area light def OctaneAreaLight(): c4d.CallCommand(1033864) # Octane Arealight obj = doc.GetActiveObject() obj.SetName(prefix + "Area Light") c4d.EventAdd() #Octane Targeted Aera light def OctaneTargetAeraLight(): c4d.CallCommand(1033868) obj = doc.GetActiveObject() obj.SetName(prefix + "Target Light") c4d.EventAdd() ## --- Materials --- ## #Octane Diffuse def MatDiffuse(): c4d.CallCommand(1033871, 1033871) obj = doc.GetActiveMaterial() obj.SetName("Diffuse") c4d.EventAdd() #Octane Glossy def MatGlossy(): c4d.CallCommand(1033893, 1033893) obj = doc.GetActiveMaterial() obj.SetName("Glossy") c4d.EventAdd() #Octane Specular def MatSpecular(): c4d.CallCommand(1033894, 1033894) obj = doc.GetActiveMaterial() obj.SetName("Specular") c4d.EventAdd() #Octane Mix def MatMix(): c4d.CallCommand(1033895, 1033895) obj = doc.GetActiveMaterial() obj.SetName("Mix") c4d.EventAdd() #Convert Materials def ConvertMats(): active_mat = doc.GetActiveMaterial() if active_mat == None: gui.MessageDialog("Please select at least one Material") c4d.CallCommand(1029770, 1029770) c4d.EventAdd() # Octane Blend def MatBlend(): c4d.CallCommand(1040118) obj = doc.GetActiveMaterial() obj.SetName("Blend") c4d.EventAdd() # Octane Universal def MatUniversal(): c4d.CallCommand(1041569) obj = doc.GetActiveMaterial() obj.SetName("Universal") c4d.EventAdd() # Octane Metallic def MatMetallic(): c4d.CallCommand(1040116) obj = doc.GetActiveMaterial() obj.SetName("Metallic") c4d.EventAdd() # Octane Toon def MatToon(): c4d.CallCommand(1040117) obj = doc.GetActiveMaterial() obj.SetName("Toon") c4d.EventAdd() ## --- Environments --- ## #HDRI Environment def HDRIEnv(): c4d.CallCommand(1033867) obj = doc.GetActiveObject() obj.SetName(prefix + "HDRI Environment") c4d.EventAdd() #Texture Environment def TextureEnv(): c4d.CallCommand(1033866) obj = doc.GetActiveObject() obj.SetName(prefix + "Texture Environment") c4d.EventAdd() ## --- Generators --- ## #Octane Scatter def OctaneScatter(): c4d.CallCommand(1035961) c4d.EventAdd() #Octane Fog def OctaneFog(): c4d.CallCommand(1036589, 1036589) obj = doc.GetActiveObject() obj.SetName(prefix + "Fog") c4d.EventAdd() #Octane VDB def OctaneVDB(): c4d.CallCommand(1037329, 1037329) obj = doc.GetActiveObject() obj.SetName(prefix + "VDB") c4d.EventAdd() ## --- Helpers --- ## #Octane Tex Manager def OctTexManager(): c4d.CallCommand(1035275) c4d.EventAdd() #Octane Node Editor def OctNodeEditor(): c4d.CallCommand(1033872) c4d.EventAdd() #Octane LiveDB def OctLiveDB(): c4d.CallCommand(1033870) c4d.EventAdd() #Octane Live Viewer def LiveViewer(): c4d.CallCommand(1029499) # Live Viewer Window #Octane Setiing def Setting(): if c4d.gui.GetInputState(c4d.BFM_INPUT_KEYBOARD, c4d.BFM_INPUT_CHANNEL, bc): if bc[c4d.BFM_INPUT_QUALIFIER] == 0: c4d.CallCommand(1031195) # Octane Settings c4d.EventAdd() elif bc[c4d.BFM_INPUT_QUALIFIER] == 2: c4d.CallCommand(1031195) # Octane Settings rdata = doc.GetActiveRenderData() rdata[c4d.RDATA_RENDERENGINE] = 1029525 OctaneRender = 1029525 videopost = rdata.GetFirstVideoPost() """Click = Setting Ctrl+Click = Setting & Set Renderer to Octane""" #Set Render Engine def OctaneRenderer(): rdata = doc.GetActiveRenderData() rdata[c4d.RDATA_RENDERENGINE] = 1029525 OctaneRender = 1029525 videopost = rdata.GetFirstVideoPost() """Set Render Engine as Octane Renderer Open Octane Setting""" ########### -- User Input -- ########### result = gui.ShowPopupDialog(cd=None, bc=entries, x=c4d.MOUSEPOS, y=c4d.MOUSEPOS, flags=c4d.POPUP_RIGHT) if result == 10: LiveViewer() elif result == 11: OctNodeEditor() elif result == 12: Setting() elif result == 101: AIOctaneCam() elif result == 102: OctaneCam() elif result == 201: OctaneAreaLight() elif result == 202: OctaneDayLight() elif result == 203: OctaneTargetAeraLight() elif result == 301: HDRIEnv() elif result == 302: TextureEnv() elif result == 401: MatDiffuse() elif result == 402: MatGlossy() elif result == 403: MatSpecular() elif result == 404: MatMix() elif result == 405: ConvertMats() elif result == 406: MatUniversal() elif result == 407: MatMetallic() elif result == 408: MatBlend() elif result == 409: MatToon() elif result == 501: OctaneScatter() elif result == 502: OctaneFog() elif result == 503: OctaneVDB() elif result == 601: OctTexManager() elif result == 603: OctLiveDB() else: return
def main(): # Get file data document = documents.GetActiveDocument() path = document.GetDocumentPath() name = document.GetDocumentName() settings = c4d.BaseContainer() obj = document.SearchObject("Connect") userDataObject = document.SearchObject("Mordifier") objList = document.GetObjects() outPutFilename = userDataObject[c4d.ID_USERDATA, 15] outPutPath = userDataObject[c4d.ID_USERDATA, 16] # C-Model return_value = utils.SendModelingCommand( command=c4d.MCOMMAND_CURRENTSTATETOOBJECT, list=[obj], mode=c4d.MODELINGCOMMANDMODE_ALL, bc=settings, doc=document) if return_value: document.InsertObject( return_value[0]) #return_value is a list in this case c4d.EventAdd() # del others for i in objList: i.Remove() # change name of the model newModel = document.GetFirstObject() newModel.SetName(outPutFilename) # delete all material mat = document.GetMaterials() for i in mat: i.Remove() # save file # path = "C:\\newStart\\Assets\\Models\\CutOutModels\\" name = outPutFilename + "_forUnity.c4d" path = os.path.join(outPutPath, name) # 导出模型到原文件路径 if documents.SaveDocument(doc, path, c4d.SAVEDOCUMENTFLAGS_DONTADDTORECENTLIST, c4d.FORMAT_C4DEXPORT): print "export document to: " + path else: print "export failed" # open new model # try: # newDoc = documents.LoadDocument(path, c4d. # SCENEFILTER_0) # except IOError: # print "Can't open the new model" c4d.EventAdd()
def SendCommand(self, param_id, bc=None): if bc is None: bc = c4d.BaseContainer() bc.SetId(c4d.BFM_ACTION) bc.SetInt32(c4d.BFM_ACTION_ID, param_id) return self.Message(bc, c4d.BaseContainer())
def main(): radius = 50 # enter radius here if not op: return if not op.IsInstanceOf(c4d.Opolygon): return doc.StartUndo() # step 1 # we convert the selected points to edges # from the edges we create a spline settings = c4d.BaseContainer() settings[c4d.MDATA_CONVERTSELECTION_LEFT] = 0 settings[c4d.MDATA_CONVERTSELECTION_RIGHT] = 1 res = c4d.utils.SendModelingCommand(command=c4d.MCOMMAND_CONVERTSELECTION, list=[op], mode=c4d.MODIFY_POINTSELECTION, bc=settings, doc=doc, flags=c4d.MODELINGCOMMANDFLAGS_0) if res is False: print "P2C: Failed convert points to edges." return res = c4d.utils.SendModelingCommand( command=c4d.MCOMMAND_EDGE_TO_SPLINE, list=[op], mode=c4d.MODIFY_EDGESELECTION, bc=settings, doc=doc, flags=c4d.MODELINGCOMMANDFLAGS_CREATEUNDO) if res is False: print "P2C: Failed edge to spline." return # step 2 # we get the spline to process it spline = op.GetDown() if not spline: print "P2C: Failed to get the spline." return if spline.IsInstanceOf(c4d.Opolygon): return pointCnt = op.GetPointCount() pointSel = op.GetPointS() pointSelCnt = pointSel.GetCount() spPointCnt = spline.GetPointCount() spPointSel = spline.GetPointS() spPointSelCnt = spPointSel.GetCount() if spPointCnt != pointSelCnt: return # step 3 # map the points of the spline to the original points # of the object, in order to be able to move the appropriate ones later pointMap = [] sel = pointSel.GetAll(pointCnt) for pIndex, selected in enumerate(sel): if not selected: continue # find the matching point in the spline for spIndex in xrange(spPointCnt): if op.GetPoint(pIndex) == spline.GetPoint(spIndex): data = (pIndex, spIndex) pointMap.append(data) break # display the result (debug) #for m in pointMap: # print m[0], m[1] # step 4 # make the spline into a circle # apply the spline coordinates to the appropriate source points doc.AddUndo(c4d.UNDOTYPE_CHANGE, op) vectorSum = c4d.Vector(0) for i in xrange(spPointCnt): p = spline.GetPoint(i) vectorSum += spline.GetPoint(i) spMg = spline.GetMg() vectorAv = vectorSum / spPointCnt vectorAv_g = spMg.Mul(vectorAv) refPointA = spline.GetPoint(0) refPointB = spline.GetPoint(1) refPointAg = spMg.Mul(refPointA) refPointBg = spMg.Mul(refPointB) m = c4d.Matrix() m.off = vectorAv_g m.v1 = (refPointAg - vectorAv_g).GetNormalized() mV1 = m.v1 m.v3 = mV1.Cross((refPointBg - vectorAv_g).GetNormalized()) mV3 = m.v3 m.v2 = mV3.Cross(mV1).GetNormalized() angle = 6.283 / spPointCnt opMg = op.GetMg() mInv = ~m opMgInv = ~opMg for pm in pointMap: pointA = spline.GetPoint(pm[1]) pointAg = spMg.Mul(pointA) pointAl = mInv.Mul(pointAg) sn, cs = c4d.utils.SinCos(angle * (pm[1])) posAl_x = cs * radius posAl_y = sn * radius pointAlMod = c4d.Vector(posAl_x, posAl_y, pointAl.z) pointAg2 = m.Mul(pointAlMod) pointAl2 = opMgInv.Mul(pointAg2) op.SetPoint(pm[0], pointAl2) spline.Remove() op.Message(c4d.MSG_UPDATE) #c4d.CallCommand(200000089) # Scale doc.EndUndo() c4d.EventAdd() return
def main(): # Checks if selected object is valid if op is None: raise ValueError("op is none, please select one object.") # Check if it's a polygon object if not op.IsInstanceOf(c4d.Opolygon): raise TypeError("Selected object is not a polygon Object.") # Defines settings for PolygonReduction.PreProcess() settings = c4d.BaseContainer() settings[c4d.POLYREDUXOBJECT_PRESERVE_3D_BOUNDARY] = True settings[c4d.POLYREDUXOBJECT_PRESERVE_UV_BOUNDARY] = True # Defines data for PolygonReduction.PreProcess() data = dict() data['_op'] = op data['_doc'] = doc data['_settings'] = settings data['_thread'] = None # Creates PolygonReduction object polyReduction = c4d.utils.PolygonReduction() if polyReduction is None: raise RuntimeError("Failed to create the PolygonReduction.") # Pre-process the data if not polyReduction.PreProcess(data): raise RuntimeError( "Failed to Pre-Process the PolygonReduction with data.") # Asks for number of triangle level while True: # Opens a Dialog where user can enter a text userInput = c4d.gui.InputDialog("Enter number of triangle level:") # Checks if operation was cancelled if userInput == "": return # Tries to convert to integer try: triangleLevel = int(userInput) break except ValueError: c4d.gui.MessageDialog("Please enter a number.") # Checks entered number of triangle level is valid if not polyReduction.GetMinTriangleLevel( ) < triangleLevel < polyReduction.GetMaxTriangleLevel(): raise RuntimeError("Entered value is not valid.") # Sets the triangle level polyReduction.SetTriangleLevel(triangleLevel) # Gets triangle level count after reduction realTriangleResult = polyReduction.GetTriangleLevel() print("Triangle Result: ".format(realTriangleResult)) # Updates original PolygonObject op.Message(c4d.MSG_UPDATE) # Pushes an update event to Cinema 4D c4d.EventAdd()
def main(): #get polygon object polyObject = doc.GetActiveObject() if polyObject is None: return if not polyObject.IsInstanceOf(c4d.Opolygon): return # settings for PolygonReduction.PreProcess() settings = c4d.BaseContainer() settings[c4d.POLYREDUXOBJECT_PRESERVE_3D_BOUNDARY] = True settings[c4d.POLYREDUXOBJECT_PRESERVE_UV_BOUNDARY] = True # data for PolygonReduction.PreProcess() data = {} data['_op'] = polyObject data['_doc'] = doc data['_settings'] = settings data['_thread'] = None # synchronous pre-processing and reduction # create PolygonReduction object polyReduction = utils.PolygonReduction() if polyReduction is None: return # pre process if not polyReduction.PreProcess(data): return # ask for number of vertex level while True: input = gui.InputDialog("Enter number of vertex level:") if input == "": # operation was cancelled polyObject.Message(c4d.MSG_UPDATE) c4d.EventAdd() return # try to convert to integer try: vertexLevel = int(input) break except ValueError: gui.MessageDialog("Please enter a number.") # check entered number of vertex level is valid if vertexLevel < polyReduction.GetMinVertexLevel(): return if vertexLevel > polyReduction.GetMaxVertexLevel(): return # set vertex level polyReduction.SetVertexLevel(vertexLevel) # get number of vertex level after reduction realVertexResult = polyReduction.GetVertexLevel() print "Vertex Result: " + str(realVertexResult) # update original PolygonObject polyObject.Message(c4d.MSG_UPDATE) c4d.EventAdd()
import c4d import random # setting of "convert selection" command setting = c4d.BaseContainer() setting[c4d.MDATA_CONVERTSELECTION_LEFT] = 2 # polygon setting[c4d.MDATA_CONVERTSELECTION_RIGHT] = 1 # edge # get object obj = doc.GetActiveObject() poly_cnt = obj.GetPolygonCount() # initialize polygon selection sel = obj.GetPolygonS() sel.DeselectAll() for index in xrange(poly_cnt): # select polygon sel.DeselectAll() sel.Select(index) # convert selection (polygon -> edge) c4d.utils.SendModelingCommand(c4d.MCOMMAND_CONVERTSELECTION, [obj], c4d.MODELINGCOMMANDMODE_POLYGONSELECTION, setting, doc) # edge to spline c4d.utils.SendModelingCommand(c4d.MCOMMAND_EDGE_TO_SPLINE, [obj]) c4d.EventAdd()
def main(): doc.StartUndo() # Start recording undos selection = doc.GetSelection() #Get selection bc = c4d.BaseContainer() # Get base container forward = True # Initialize direction variable # Input qualifier check if c4d.gui.GetInputState(c4d.BFM_INPUT_KEYBOARD, c4d.BFM_INPUT_CHANNEL, bc): if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QSHIFT: # If shift is pressed forward = False # Set direction to backwards commonTags = [ c4d.BaseTag, c4d.TextureTag, c4d.NormalTag, c4d.UVWTag, c4d.SelectionTag, c4d.modules.character.CAPoseMorphTag, c4d.modules.character.CAWeightTag, c4d.VariableTag, c4d.modules.graphview.XPressoTag, c4d.VertexColorTag, c4d.modules.hair.HairVertexMapTag, c4d.modules.hair.HairSelectionTag ] # List of tags hiddenTags = [c4d.PointTag, c4d.PolygonTag] # Hidden tags objList = [] prevGUID = None selection = doc.GetSelection() #Get selection # Collect objects for s in selection: # Iterate trough selection if type(s) in commonTags: # If selected item is a tag obj = s.GetObject() # Get the object objGUID = obj.GetGUID() # Get object's GUID if objGUID != prevGUID: # If everytime different object objList.append(obj) # Add object to the object list prevGUID = objGUID # Store previous object's GUID # Do the thing for obj in objList: # Iterate through collected objects tags = obj.GetTags() # Get tags tagList = [] # Initialize list for tags index = 0 # Initialize index variable # Collect active tags for tag in tags: # Loop through tags if tag not in hiddenTags: # If tag is not a hidden tag if tag.GetBit(c4d.BIT_ACTIVE): # Check if tag is selected tagList.append([tag, index]) # Add selected tag to the list else: tagList.append([tag, None]) # Add not selected tag to the list index = index + 1 # Increase index by one # Remove tags for tag in tags: # Loop again trough tags doc.AddUndo(c4d.UNDOTYPE_DELETE, tag) # Add undo command for deleting tag tag.Remove() # Remove tag # Move tags if forward: # If direction is forward for i, data in reversed(list( enumerate(tagList))): # Loop once again trough tags if data[1] != None: tagList.insert(data[1] + 1, tagList.pop(i)) # Move tag forwards #tagList.insert(spot + 1, tagList.pop(spot)) # Move tag forwards else: # Otherwise for i, data in enumerate(tagList): # Loop once again trough tags if data[1] != None: if data[1] != 0: # If tag is not the first tag tagList.insert(data[1] - 1, tagList.pop(i)) # Move tag backwards tagList.reverse() # Reverse list items order # Add tags back for data in tagList: # Loop trough tagList obj.InsertTag(data[0]) # Insert tag back to object doc.AddUndo(c4d.UNDOTYPE_NEW, data[0]) # Add undo command for inserting tag doc.EndUndo() # Stop recording undos c4d.EventAdd() # Refresh Cinema 4D
def arbresLignes(sp, mnt, fn_arbres_srce): minY, maxY = getMinMaxY(mnt) doc_temp = c4d.documents.BaseDocument() # altitude des points de la copie de la spline au minimum du mnt (-delta) sp = sp.GetClone() sp[c4d.SPLINEOBJECT_CLOSED] = False setAltPointObj(sp, minY) # extrusion extr = c4d.BaseObject(c4d.Oextrude) extr[c4d.EXTRUDEOBJECT_DIRECTION] = c4d.EXTRUDEOBJECT_DIRECTION_Y extr[c4d.EXTRUDEOBJECT_EXTRUSIONOFFSET] = maxY - minY sp.InsertUnder(extr) # boolean boolObj = c4d.BaseObject(c4d.Oboole) boolObj[c4d.BOOLEOBJECT_TYPE] = c4d.BOOLEOBJECT_TYPE_WITHOUT boolObj[c4d.BOOLEOBJECT_HIGHQUALITY] = True boolObj[c4d.BOOLEOBJECT_SEL_CUT_EDGES] = True mnt.GetClone().InsertUnder(boolObj) extr.InsertUnder(boolObj) doc_temp.InsertObject(boolObj) doc_temp = doc_temp.Polygonize() decoupe = doc_temp.GetFirstObject().GetDown() if not decoupe: c4d.gui.MessageDialog(TXT_ALERT) return settings = c4d.BaseContainer() # Settings res = c4d.utils.SendModelingCommand( command=c4d.MCOMMAND_EDGE_TO_SPLINE, list=[decoupe], mode=c4d.MODELINGCOMMANDMODE_EDGESELECTION, bc=settings, doc=doc_temp) if not decoupe.GetDown(): c4d.gui.MessageDialog(TXT_ALERT2) return sp_decoupe = decoupe.GetDown().GetClone() # sp_decoupe.SetMg(mnt.GetMg()) sp_decoupe[ c4d. SPLINEOBJECT_INTERPOLATION] = c4d.SPLINEOBJECT_INTERPOLATION_UNIFORM sp_decoupe[c4d.SPLINEOBJECT_SUB] = 0 # cloneur cloner = c4d.BaseObject(1018544) cloner[ c4d.ID_MG_MOTIONGENERATOR_MODE] = c4d.ID_MG_MOTIONGENERATOR_MODE_OBJECT cloner[c4d.MGCLONER_MODE] = c4d.MGCLONER_MODE_RANDOM cloner[ c4d. MGCLONER_VOLUMEINSTANCES_MODE] = c4d.MGCLONER_VOLUMEINSTANCES_MODE_RENDERMULTIINSTANCE cloner[c4d.MG_OBJECT_LINK] = sp_decoupe cloner[c4d.MG_POLY_MODE_] = c4d.MG_POLY_MODE_SURFACE cloner[c4d.MG_OBJECT_ALIGN] = False cloner[c4d.MG_SPLINE_MODE] = c4d.MG_SPLINE_MODE_STEP cloner[c4d.MG_SPLINE_STEP] = DISTANCE_CLONE objs_to_clone = getArbresSourcesFromFile(fn_arbres_srce) if objs_to_clone: for o in objs_to_clone: o.InsertUnderLast(cloner) else: nobj = c4d.BaseObject(c4d.Onull) sphere = c4d.BaseObject(c4d.Osphere) sphere[c4d.PRIM_SPHERE_RAD] = RAYON_SPHERE_DEFAULT sphere.InsertUnder(nobj) sphere.SetRelPos(c4d.Vector(0, RAYON_SPHERE_DEFAULT, 0)) nobj.InsertUnder(cloner) # random effector rdm_effector = c4d.BaseObject(1018643) in_ex_data = cloner[c4d.ID_MG_MOTIONGENERATOR_EFFECTORLIST] in_ex_data.InsertObject(rdm_effector, 1) cloner[c4d.ID_MG_MOTIONGENERATOR_EFFECTORLIST] = in_ex_data rdm_effector[c4d.ID_MG_BASEEFFECTOR_POSITION_ACTIVE] = False rdm_effector[c4d.ID_MG_BASEEFFECTOR_ROTATE_ACTIVE] = True rdm_effector[c4d.ID_MG_BASEEFFECTOR_ROTATION, c4d.VECTOR_X] = math.pi * 2 rdm_effector.InsertUnder(sp_decoupe) cloner.InsertUnder(sp_decoupe) return sp_decoupe
def escPressed(): bc = c4d.BaseContainer() rs = gui.GetInputState( c4d.BFM_INPUT_KEYBOARD, c4d.KEY_ESC, bc ) if rs and bc[ c4d.BFM_INPUT_VALUE ]: return True return False
def QueryNetwork(material): msg = c4d.BaseContainer() msg.SetInt32(C4DTOA_MSG_TYPE, C4DTOA_MSG_QUERY_SHADER_NETWORK) material.Message(c4d.MSG_BASECONTAINER, msg) return msg
def main(): doc = c4d.documents.GetActiveDocument() # Get active Cinema 4D document doc.StartUndo() # Start recording undos keyMod = GetKeyMod() # Get keymodifier editorMode = doc.GetMode() # Get editor's active mode selection = doc.GetActiveObjects( c4d.GETACTIVEOBJECTFLAGS_SELECTIONORDER) # Get active objects cnt = len(selection) # Count of selected objects # Edge selection if editorMode == c4d.Medges: edgeToSpline = c4d.MCOMMAND_EDGE_TO_SPLINE # Mcommand 'Edge To Spline' modeEdgeSel = c4d.MODELINGCOMMANDMODE_EDGESELECTION # Modeling command mode 'Edge Selection' createUndo = c4d.MODELINGCOMMANDFLAGS_CREATEUNDO # Modeling command flag 'Create undo' bc = c4d.BaseContainer() # Initialize base container u.SendModelingCommand( edgeToSpline, selection, modeEdgeSel, bc, doc, createUndo) # Send modeling command 'Edge To Spline' obj = selection[0] spline = obj.GetDown() spline.InsertBefore(obj) spline.SetMg(obj.GetMg()) CenterAxis(spline) doc.AddUndo(c4d.UNDOTYPE_BITS, selection[0]) # Add undo command for changing bits selection[0].DelBit(c4d.BIT_ACTIVE) # Deselect object doc.AddUndo(c4d.UNDOTYPE_BITS, spline) spline.SetBit(c4d.BIT_ACTIVE) doc.SetMode(c4d.Mmodel) # Object selection else: # No active objects if cnt == 0: if keyMod == "None": spline = CreateSpline(2, [ c4d.Vector(0, 0, 0), c4d.Vector(0, 0, 100), ]) InsertObject(spline) if keyMod == "Shift": spline = CreateSpline(2, [ c4d.Vector(0, 0, 0), c4d.Vector(0, 100, 0), ]) InsertObject(spline) if keyMod == "Ctrl": spline = CreateSpline(2, [ c4d.Vector(0, 0, 0), c4d.Vector(100, 0, 0), ]) InsertObject(spline) # Only one selected object elif cnt == 1: if selection[0].GetType() == 5101: # If spline object subd = gui.InputDialog('Subdivide', "0") if keyMod == "None": controllers = CreateControls(selection[0], "Ends") elif keyMod == "Shift": controllers = CreateControls(selection[0], "All") CreateDynamics(selection[0], controllers, int(subd)) doc.AddUndo(c4d.UNDOTYPE_BITS, selection[0]) # Add undo command for changing bits selection[0].DelBit(c4d.BIT_ACTIVE) # Deselect object # Multiple selected objects else: # If spline object if selection[0].GetType() == 5101: subd = gui.InputDialog('Subdivide', "0") for s in selection: if keyMod == "None": controllers = CreateControls(s, "Ends") elif keyMod == "Shift": controllers = CreateControls(s, "All") CreateDynamics(s, controllers, int(subd)) doc.AddUndo(c4d.UNDOTYPE_BITS, s) # Add undo command for changing bits # No spline object else: if keyMod == "Alt+Shift" or keyMod == "Alt+Ctrl": TracerFromObjects(selection, keyMod) else: SplineFromObjects(selection, keyMod) # Deselect old selection for s in selection: # Iterate through selection doc.AddUndo(c4d.UNDOTYPE_BITS, s) # Add undo command for changing bits s.DelBit(c4d.BIT_ACTIVE) # Deselect object doc.EndUndo() # Stop recording undos c4d.EventAdd() # Refresh Cinema 4D
def export_to_renderfarm(): #Collect start save = c4d.CallCommand(12098) # Save #function variables container = rdata.GetData() #Render setting collect name rdata[c4d.ID_BASELIST_NAME] = "_" + docfolder + "_To Render Farm" #Output Formats #Beauty if rdata[c4d.RDATA_RENDERENGINE] == ARNOLD_RENDERER: BeautyFormat = ARNOLD_DUMMYFORMAT #ArnoldDummy Format if not rdata[c4d.RDATA_RENDERENGINE] == ARNOLD_RENDERER: BeautyFormat = c4d.FILTER_JPG #Beauty reference in JPG format #MultiPass MPFormat = c4d.FILTER_EXR container[c4d.RDATA_FORMAT] = BeautyFormat container[c4d.RDATA_ALPHACHANNEL] = False container[c4d.RDATA_MULTIPASS_SAVEFORMAT] = MPFormat saveOptions = container.GetContainerInstance( c4d.RDATA_MULTIPASS_SAVEOPTIONS) # OpenEXR Compression options bc = c4d.BaseContainer() bc[0] = 3 # ZIP bc[1] = True # clamp to half float # save OpenEXR options & continer data saveOptions.SetContainer(0, bc) rdata.SetData(container) #set render paths rdata[ c4d. RDATA_PATH] = "./$prj/$prj_Beauty" #Beauty export is not necessary with some 3rd party renders just like C4DtoA rdata[c4d.RDATA_MULTIPASS_FILENAME] = "./$prj/$prj_MP" #MP = Multipass #Arnold Render Settings Safety check if rdata[c4d.RDATA_RENDERENGINE] == ARNOLD_RENDERER: Arnold_Safety_Checks() if not rdata[c4d.RDATA_RENDERENGINE] == ARNOLD_RENDERER: None #Update te scene c4d.EventAdd() #Collect New File c4d.CallCommand(12255, 12255) # Save Project with Assets... #Write codument with frames and path settings #New documents IDs n_docpath = doc.GetDocumentPath() n_docname = doc.GetDocumentName() n_docfolder = n_docname[:-4] write_txt(n_docpath, n_docname, n_docfolder) print "Collected file: " + n_docname #Close the collected file c4d.CallCommand(12664, 12664) # Close collected project c4d.CallCommand(52000, 2) # Recent Files #Collect finish dialog gui.MessageDialog( "Successfully Exported!\nSee the console for more details.")
def export_to_renderfarm(): #Collect start save = c4d.CallCommand(12098) # Save #function variables container = renderdata.GetData() render_engine = active_render_engine_string() print render_engine + " detected" render_engine = rdata[c4d.RDATA_RENDERENGINE] #Render setting collect name renderdata[c4d.ID_BASELIST_NAME] = "_" + docfolder + "_To Render Farm" #Output Render File Formats #Beauty if render_engine == ARNOLD_RENDERER: BeautyFormat = ARNOLD_DUMMYFORMAT #ArnoldDummy Format if not render_engine == ARNOLD_RENDERER: BeautyFormat = c4d.FILTER_JPG #Beauty reference in JPG format #MultiPass MPFormat = c4d.FILTER_EXR container[c4d.RDATA_FORMAT] = BeautyFormat container[c4d.RDATA_ALPHACHANNEL] = False container[c4d.RDATA_MULTIPASS_SAVEFORMAT] = MPFormat saveOptions = container.GetContainerInstance( c4d.RDATA_MULTIPASS_SAVEOPTIONS) # OpenEXR Compression options bc = c4d.BaseContainer() bc[0] = 3 # ZIP bc[1] = True # clamp to half float # save OpenEXR options & continer data saveOptions.SetContainer(0, bc) renderdata.SetData(container) #set render paths renderdata[ c4d. RDATA_PATH] = "./$prj/$prj_Beauty" #Beauty export is not necessary with some 3rd party renders just like C4DtoA renderdata[ c4d.RDATA_MULTIPASS_FILENAME] = "./$prj/$prj_MP" #MP = Multipass #Safety checks settings in render engine if render_engine == ARNOLD_RENDERER: Arnold_Safety_Checks() elif render_engine == REDSHIFT_RENDERER: Redshift_Safety_Checks() elif render_engine == OCTANE_RENDERER: Octane_Safety_Checks() elif render_engine == PHYSICAL_RENDERER: Physical_Safety_Checks() else: Standard_Safety_Checks() #Update the scene c4d.EventAdd() #Collect New File c4d.CallCommand(12255, 12255) # Save Project with Assets... #Write codument with log information #New documents IDs n_docpath = doc.GetDocumentPath() n_docname = doc.GetDocumentName() n_docfolder = n_docname[:-4] #output data format and resolution to log output_data_format = get_output_data_format() #render log from render engine if render_engine == ARNOLD_RENDERER: render_log = Arnold_Log_Data() elif render_engine == REDSHIFT_RENDERER: render_log = Redshift_Log_Data() elif render_engine == OCTANE_RENDERER: render_log = Octane_Log_Data() elif render_engine == PHYSICAL_RENDERER: render_log = Physical_Log_Data() else: render_log = Standard_Log_Data() write_txt(n_docpath, n_docname, n_docfolder, render_log, output_data_format) print "Collected file: " + n_docname #Close the collected file c4d.CallCommand(12664, 12664) # Close collected project c4d.CallCommand(52000, 2) # Recent Files #Collect finish dialog print "Successfully Exported! Happy Rendering ;)" gui.MessageDialog( "Successfully Exported!\nSee the console and log for more details.")
def thumbnail_button_settings(): settings = c4d.BaseContainer() settings[c4d.BITMAPBUTTON_BUTTON] = False settings[c4d.BITMAPBUTTON_BORDER] = False settings[c4d.BITMAPBUTTON_TOGGLE] = False return settings
def main(): class polys: def __init__(self, ind, polygon): self.Id = ind self.polyst = polygon self.triangle = self.polyst.IsTriangle() obj = doc.GetActiveObject() all_polys = obj.GetAllPolygons() select = obj.GetPolygonS().GetAll(obj.GetPolygonCount()) select_list = [] for i in range(obj.GetPolygonCount()): ### make select polys list a = polys(i, all_polys[i]) if select[i] == 1: select_list.append(a) for i in range(len(select_list)): ### print select polys print select_list[i].Id, " ", select_list[i].polyst new_list = [] for i in range(len(select_list)): polycount = obj.GetPolygonCount() pointcount = obj.GetPointCount() if select_list[i].triangle == 0: n = [] n.append(obj.GetPoint(select_list[i].polyst.a)) n.append(obj.GetPoint(select_list[i].polyst.b)) n.append(obj.GetPoint(select_list[i].polyst.c)) n.append(obj.GetPoint(select_list[i].polyst.d)) obj.ResizeObject(pointcount + 4, polycount + 1) index = [] for k in range(len(n)): obj.SetPoint(pointcount + k, n[k]) index.append(pointcount + k) poly = c4d.CPolygon(index[0], index[1], index[2], index[3]) obj.SetPolygon(polycount, poly) obj.Message(c4d.MSG_UPDATE) else: n = [] n.append(obj.GetPoint(select_list[i].polyst.a)) n.append(obj.GetPoint(select_list[i].polyst.b)) n.append(obj.GetPoint(select_list[i].polyst.c)) obj.ResizeObject(pointcount + 3, polycount + 1) index = [] for k in range(len(n)): obj.SetPoint(pointcount + k, n[k]) index.append(pointcount + k) poly = c4d.CPolygon(index[0], index[1], index[2]) obj.SetPolygon(polycount, poly) obj.Message(c4d.MSG_UPDATE) new_list.append(polycount) print new_list select = obj.GetPolygonS() select.DeselectAll() for i in range(len(new_list)): select.Select(new_list[i]) settings = c4d.BaseContainer() settings[c4d.MDATA_OPTIMIZE_TOLERANCE] = 0.01 settings[c4d.MDATA_OPTIMIZE_POINTS] = True settings[c4d.MDATA_OPTIMIZE_POLYGONS] = True settings[c4d.MDATA_OPTIMIZE_UNUSEDPOINTS] = True utils.SendModelingCommand(command=c4d.MCOMMAND_OPTIMIZE, list=[op], mode=c4d.MODELINGCOMMANDMODE_POLYGONSELECTION, bc=settings, doc=doc)