### Create Modal Dialog for User Input in Cinema 4D Python Source: https://context7.com/maxon-computer/cinema-4d-python-api-examples/llms.txt Demonstrates how to create a modal dialog using Cinema 4D's GeDialog class to get user input. This dialog blocks the main application until it is closed, ensuring the user provides input before proceeding. It includes input fields for text and a checkbox for an option. ```python import c4d class InputDialog(c4d.gui.GeDialog): """Modal dialog for getting user input.""" ID_EDIT = 1000 ID_CHECKBOX = 1001 def __init__(self): super().__init__() self.user_text = "" self.user_checked = False self.confirmed = False def CreateLayout(self): self.SetTitle("Enter Value") self.GroupBegin(0, c4d.BFH_SCALEFIT, cols=2) self.AddStaticText(0, c4d.BFH_LEFT, name="Text:") self.AddEditText(self.ID_EDIT, c4d.BFH_SCALEFIT) self.AddStaticText(0, c4d.BFH_LEFT, name="Option:") self.AddCheckbox(self.ID_CHECKBOX, c4d.BFH_LEFT, 0, 0, name="Enable feature") self.GroupEnd() self.AddDlgGroup(c4d.DLG_OK | c4d.DLG_CANCEL) return True def InitValues(self): self.SetString(self.ID_EDIT, "Default text") self.SetBool(self.ID_CHECKBOX, False) return True def Command(self, mid, bc): if mid == c4d.DLG_OK: self.user_text = self.GetString(self.ID_EDIT) self.user_checked = self.GetBool(self.ID_CHECKBOX) self.confirmed = True self.Close() elif mid == c4d.DLG_CANCEL: self.confirmed = False self.Close() return True def main(): dlg = InputDialog() # Open as modal - blocks until closed dlg.Open(c4d.DLG_TYPE_MODAL, defaultw=300, defaulth=100) if dlg.confirmed: print(f"User entered: {dlg.user_text}") print(f"Option enabled: {dlg.user_checked}") else: print("User cancelled") if __name__ == '__main__': main() ``` -------------------------------- ### Register Object Plugin (Generator) Source: https://context7.com/maxon-computer/cinema-4d-python-api-examples/llms.txt Registers a custom object generator plugin. This example creates a 'Py-RoundedTube' object. It requires an icon file and references a description string. ```python import c4d import os PLUGIN_ID = 1028283 class RoundedTube(c4d.plugins.ObjectData): def Init(self, node): # Initialize node parameters return True def GetVirtualObjects(self, op, hh, bd, flags): # Generate the object geometry return None if __name__ == "__main__": directory, _ = os.path.split(__file__) bmp = c4d.bitmaps.BaseBitmap() bmp.InitWith(os.path.join(directory, "res", "icon.tif")) c4d.plugins.RegisterObjectPlugin( id=PLUGIN_ID, str="Py-RoundedTube", g=RoundedTube, description="roundedtube", # References .res file icon=bmp, info=c4d.OBJECT_GENERATOR ) ``` -------------------------------- ### Take System Overview Source: https://github.com/maxon-computer/cinema-4d-python-api-examples/blob/master/scripts/04_3d_concepts/scene_elements/take_system/readme.md Provides an overview of the core classes within the Take System module. ```APIDOC ## Take System Classes ### Description This section details the primary classes used in the Cinema 4D Take System for managing scene variations. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response (200) - **c4d.modules.takesystem.TakeData** (object) - Stores the Take data of a given BaseDocument and settings of the Take Manager. - **c4d.modules.takesystem.BaseTake** (object) - Represents a Take and stores the overrides. - **c4d.modules.takesystem.BaseOverride** (object) - Stores the settings of a certain object in a certain Take. - **c4d.modules.takesystem.BaseOverrideGroup** (object) - Acts like a virtual null object and can assign different tags to the objects organized in that group. #### Response Example N/A ``` -------------------------------- ### takesystem_renderdata Source: https://github.com/maxon-computer/cinema-4d-python-api-examples/blob/master/scripts/04_3d_concepts/scene_elements/take_system/readme.md Creates a Take for each Render Setting by iterating through available Render Setting objects. ```APIDOC ## takesystem_renderdata ### Description Gets the first Render Setting and loops through all Render Setting objects. Creates a Take for each Render Setting. ### Method N/A (Example Script) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Response Example N/A ``` -------------------------------- ### takesystem_new_take Source: https://github.com/maxon-computer/cinema-4d-python-api-examples/blob/master/scripts/04_3d_concepts/scene_elements/take_system/readme.md Creates a new Take and sets it as the current Take. ```APIDOC ## takesystem_new_take ### Description Creates a new Take and makes it the current one. ### Method N/A (Example Script) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Response Example N/A ``` -------------------------------- ### takesystem_autotake Source: https://github.com/maxon-computer/cinema-4d-python-api-examples/blob/master/scripts/04_3d_concepts/scene_elements/take_system/readme.md Demonstrates storing edits of a sphere object within a Take. ```APIDOC ## takesystem_autotake ### Description Stores edits of the given sphere object in a Take. ### Method N/A (Example Script) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Response Example N/A ``` -------------------------------- ### takesystem_cameras Source: https://github.com/maxon-computer/cinema-4d-python-api-examples/blob/master/scripts/04_3d_concepts/scene_elements/take_system/readme.md Creates a new Take for each currently selected camera object. ```APIDOC ## takesystem_cameras ### Description Creates a new Take for each currently selected camera object. ### Method N/A (Example Script) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Response Example N/A ``` -------------------------------- ### Animation: Create Keyframes and Tracks in Python Source: https://context7.com/maxon-computer/cinema-4d-python-api-examples/llms.txt Demonstrates how to programmatically create animation tracks and keyframes for object parameters like position. It utilizes the `c4d.CTrack` and `c4d.BaseBitmap` classes to define keyframe values and interpolation types. This script requires a Cinema 4D document context. ```python import c4d def create_key(curve, time, value, interpolation): """Create a keyframe on a curve with specified value and interpolation.""" keyDict = curve.AddKey(time) if keyDict is None: raise MemoryError("Failed to create key.") key = keyDict["key"] keyIndex = keyDict["nidx"] key.SetValue(curve, value) curve.SetKeyDefault(doc, keyIndex) # Apply default settings key.SetInterpolation(curve, interpolation) return key, keyIndex def main(): # Create object to animate cube = c4d.BaseObject(c4d.Ocube) cube.SetName("Animated Cube") # Create position Y track using DescID # DescID identifies the exact parameter: Position > Y component trackY = c4d.CTrack(cube, c4d.DescID( c4d.DescLevel(c4d.ID_BASEOBJECT_REL_POSITION, c4d.DTYPE_VECTOR, 0), c4d.DescLevel(c4d.VECTOR_Y, c4d.DTYPE_REAL, 0) )) # Get curve from track curveY = trackY.GetCurve() # Create keyframes fps = doc.GetFps() # Key at frame 0: Y = 0 create_key(curveY, c4d.BaseTime(0, fps), 0, c4d.CINTERPOLATION_SPLINE) # Key at frame 30: Y = 200 create_key(curveY, c4d.BaseTime(30, fps), 200, c4d.CINTERPOLATION_SPLINE) # Key at frame 60: Y = 0 (back to start) create_key(curveY, c4d.BaseTime(60, fps), 0, c4d.CINTERPOLATION_SPLINE) # Insert track into object cube.InsertTrackSorted(trackY) # Insert object into document doc.InsertObject(cube) c4d.EventAdd() if __name__ == '__main__': main() ``` -------------------------------- ### Create Material and Assign to Object with Cinema 4D Python API Source: https://context7.com/maxon-computer/cinema-4d-python-api-examples/llms.txt Shows how to create a standard Cinema 4D material, configure its properties, and assign it to a selected object using a texture tag. Requires the 'c4d' module and a selected object. ```python import c4d def main(): # Ensure an object is selected if op is None: raise ValueError("Please select an object.") # Create a standard Cinema 4D material mat = c4d.BaseMaterial(c4d.Mmaterial) if mat is None: raise RuntimeError("Failed to create material.") # Configure material properties mat.SetName("Python Material") mat[c4d.MATERIAL_COLOR_COLOR] = c4d.Vector(1, 0.5, 0) # Orange mat[c4d.MATERIAL_USE_REFLECTION] = True # Insert material into document doc.InsertMaterial(mat) # Get or create texture tag on object textureTag = op.GetTag(c4d.Ttexture) if not textureTag: textureTag = op.MakeTag(c4d.Ttexture) if textureTag is None: raise RuntimeError("Failed to create texture tag.") # Link material to tag textureTag[c4d.TEXTURETAG_MATERIAL] = mat # Configure projection textureTag[c4d.TEXTURETAG_PROJECTION] = c4d.TEXTURETAG_PROJECTION_CUBIC c4d.EventAdd() if __name__ == '__main__': main() ``` -------------------------------- ### takesystem_loop_takes Source: https://github.com/maxon-computer/cinema-4d-python-api-examples/blob/master/scripts/04_3d_concepts/scene_elements/take_system/readme.md Iterates through all direct child Takes of the main Take. ```APIDOC ## takesystem_loop_takes ### Description Loops through all Takes that are direct child Takes of the main Take. ### Method N/A (Example Script) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Response Example N/A ``` -------------------------------- ### takesystem_material_override Source: https://github.com/maxon-computer/cinema-4d-python-api-examples/blob/master/scripts/04_3d_concepts/scene_elements/take_system/readme.md Creates 10 Takes with varying overrides for a material's color. ```APIDOC ## takesystem_material_override ### Description Creates 10 Takes with different overrides of the material color. ### Method N/A (Example Script) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Response Example N/A ``` -------------------------------- ### Rendering: Render Current Frame to Bitmap in Python Source: https://context7.com/maxon-computer/cinema-4d-python-api-examples/llms.txt This script demonstrates how to render the current frame of a Cinema 4D document to a bitmap object. It configures render settings for a single frame, initializes a `c4d.bitmaps.BaseBitmap`, performs the render using `c4d.documents.RenderDocument`, and displays the resulting bitmap. Optionally, the bitmap can be saved to a file. ```python import c4d def main(): # Get active render settings rd = doc.GetActiveRenderData().GetDataInstance() if rd is None: raise RuntimeError("Failed to get render settings.") # Configure for single frame render rd[c4d.RDATA_FRAMESEQUENCE] = 1 # Current frame only rd[c4d.RDATA_SAVEIMAGE] = False # Don't save to disk # Get output resolution xRes = int(rd[c4d.RDATA_XRES]) yRes = int(rd[c4d.RDATA_YRES]) # Create bitmap to receive render bmp = c4d.bitmaps.BaseBitmap() if bmp.Init(x=xRes, y=yRes) != c4d.IMAGERESULT_OK: raise RuntimeError("Failed to initialize bitmap.") # Render document result = c4d.documents.RenderDocument( doc, rd, bmp, c4d.RENDERFLAGS_EXTERNAL # External render mode ) if result != c4d.RENDERRESULT_OK: raise RuntimeError(f"Render failed with code: {result}") # Display in Picture Viewer c4d.bitmaps.ShowBitmap(bmp) # Optionally save to file # bmp.Save("/path/to/render.png", c4d.FILTER_PNG) if __name__ == '__main__': main() ``` -------------------------------- ### Export Document to OBJ Format in Cinema 4D Python Source: https://context7.com/maxon-computer/cinema-4d-python-api-examples/llms.txt Shows how to access and utilize Cinema 4D's export plugins, specifically for the OBJ format. It covers displaying a save dialog, finding the OBJ exporter, configuring export settings like UVs and animation, and finally saving the document. ```python import c4d def main(): # Show save dialog filePath = c4d.storage.LoadDialog( title="Export OBJ", flags=c4d.FILESELECT_SAVE, force_suffix="obj" ) if not filePath: return # Get OBJ exporter plugin objExportId = c4d.FORMAT_OBJ2EXPORT # R17+ plug = c4d.plugins.FindPlugin(objExportId, c4d.PLUGINTYPE_SCENESAVER) if plug is None: raise RuntimeError("OBJ exporter not found.") # Get exporter settings data = {} if not plug.Message(c4d.MSG_RETRIEVEPRIVATEDATA, data): raise RuntimeError("Failed to get exporter settings.") objExport = data.get("imexporter") if objExport is None: raise RuntimeError("Failed to access exporter.") # Configure export options objExport[c4d.OBJEXPORTOPTIONS_EXPORT_UVS] = c4d.OBJEXPORTOPTIONS_UV_ORIGINAL objExport[c4d.OBJEXPORTOPTIONS_ANIMATION_TYPE] = c4d.OBJEXPORTOPTIONS_NO_ANIMATION # Export document success = c4d.documents.SaveDocument( doc, filePath, c4d.SAVEDOCUMENTFLAGS_DONTADDTORECENTLIST, objExportId ) if success: print(f"Exported to: {filePath}") else: raise RuntimeError("Export failed.") if __name__ == '__main__': main() ``` -------------------------------- ### Create Cinema 4D Command Plugin with GUI (Python) Source: https://context7.com/maxon-computer/cinema-4d-python-api-examples/llms.txt This Python code defines a command plugin for Cinema 4D that opens a custom dialog window. The dialog allows users to input two numbers, select an operation (add or multiply), and see the result. It utilizes Cinema 4D's c4d.plugins.CommandData and c4d.gui.GeDialog classes. ```python import c4d import typing class SimpleGuiDialog(c4d.gui.GeDialog): """Dialog with number inputs, combo box, and calculation logic.""" # Gadget IDs must be unique within the dialog ID_NUM_A: int = 2002 ID_NUM_B: int = 2004 ID_CMB_OPERATION: int = 2006 ID_BTN_CALCULATE: int = 2007 ID_MLE_RESULT: int = 2008 # Combo box item IDs ID_OP_ADD: int = 0 ID_OP_MULTIPLY: int = 1 def CreateLayout(self) -> bool: """Build the dialog GUI - called once when dialog opens.""" self.SetTitle("Calculator") # Main group with vertical stacking self.GroupBegin(1000, c4d.BFH_SCALEFIT | c4d.BFV_SCALEFIT, cols=1, rows=0) self.GroupBorderSpace(5, 5, 5, 5) # Number inputs in a horizontal row self.GroupBegin(1001, c4d.BFH_SCALEFIT, cols=4, rows=0) self.AddStaticText(2001, c4d.BFH_LEFT, name="A:") self.AddEditNumberArrows(self.ID_NUM_A, c4d.BFH_SCALEFIT) self.AddStaticText(2003, c4d.BFH_LEFT, name="B:") self.AddEditNumberArrows(self.ID_NUM_B, c4d.BFH_SCALEFIT) self.GroupEnd() # Operation combo box self.GroupBegin(1002, c4d.BFH_SCALEFIT, cols=2, rows=0) self.AddStaticText(2005, c4d.BFH_LEFT, name="Operation:") self.AddComboBox(self.ID_CMB_OPERATION, c4d.BFH_SCALEFIT) self.AddChild(self.ID_CMB_OPERATION, self.ID_OP_ADD, "Add") self.AddChild(self.ID_CMB_OPERATION, self.ID_OP_MULTIPLY, "Multiply") self.GroupEnd() self.AddButton(self.ID_BTN_CALCULATE, c4d.BFH_SCALEFIT, name="Calculate") self.AddSeparatorH(1) self.AddMultiLineEditText(self.ID_MLE_RESULT, c4d.BFH_SCALEFIT | c4d.BFV_SCALEFIT, style=c4d.DR_MULTILINE_READONLY) self.GroupEnd() return True def InitValues(self) -> bool: """Set initial values after layout creation.""" self.SetFloat(self.ID_NUM_A, 42.0) self.SetFloat(self.ID_NUM_B, 3.14) self.SetInt32(self.ID_CMB_OPERATION, self.ID_OP_MULTIPLY) return True def Command(self, mid: int, data: c4d.BaseContainer) -> bool: """Handle gadget clicks and value changes.""" if mid == self.ID_BTN_CALCULATE: a = self.GetFloat(self.ID_NUM_A) b = self.GetFloat(self.ID_NUM_B) op = self.GetInt32(self.ID_CMB_OPERATION) if op == self.ID_OP_ADD: result = a + b expr = f"{a} + {b}" else: result = a * b expr = f"{a} * {b}" self.SetString(self.ID_MLE_RESULT, f"{expr} = {result:.2f}") return True class SimpleGuiCommand(c4d.plugins.CommandData): """Command plugin that manages the dialog lifecycle.""" REF_DIALOG: SimpleGuiDialog | None = None ID_PLUGIN: int = 1065652 # Unique ID from plugincafe.com def Execute(self, doc: c4d.documents.BaseDocument) -> bool: """Called when user clicks the command button.""" if self.REF_DIALOG is None: self.REF_DIALOG = SimpleGuiDialog() if self.REF_DIALOG.IsOpen(): self.REF_DIALOG.SetFolding(True) # Minimize if open else: self.REF_DIALOG.Open(c4d.DLG_TYPE_ASYNC, self.ID_PLUGIN, defaultw=300, defaulth=300) return True def RestoreLayout(self, secret: any) -> bool: """Required for dialog persistence across layout changes.""" if self.REF_DIALOG is None: self.REF_DIALOG = SimpleGuiDialog() return self.REF_DIALOG.Restore(self.ID_PLUGIN, secret) def GetState(self, doc: c4d.documents.BaseDocument) -> int: """Control command icon state (enabled/highlighted).""" result = c4d.CMD_ENABLED if self.REF_DIALOG and self.REF_DIALOG.IsOpen(): result |= c4d.CMD_VALUE # Blue highlight when open return result if __name__ == '__main__': bitmap = c4d.bitmaps.InitResourceBitmap(465001193) # Built-in icon c4d.plugins.RegisterCommandPlugin( id=SimpleGuiCommand.ID_PLUGIN, str="Py - Calculator", info=0, icon=bitmap, help="Opens a simple calculator dialog", dat=SimpleGuiCommand() ) ``` -------------------------------- ### Create Cube Polygon Object with Cinema 4D Python API Source: https://context7.com/maxon-computer/cinema-4d-python-api-examples/llms.txt Demonstrates constructing a cube polygon object from scratch using points and polygons. It includes proper update messaging and undo support. Requires the 'c4d' module. ```python import c4d import typing doc: c4d.documents.BaseDocument op: typing.Optional[c4d.BaseObject] def create_cube(size: float = 100.0) -> c4d.PolygonObject: """Create a cube polygon object programmatically.""" # Allocate object with 8 points and 6 polygons cube = c4d.PolygonObject(pcnt=8, vcnt=6) if not isinstance(cube, c4d.PolygonObject): raise MemoryError("Could not allocate polygon object.") # Define cube vertices # 3 ------- 2 # /| /| # / | / | # 0 ------- 1 | # | 7 -----|- 6 # | / | / # |/ |/ # 4 ------- 5 points = [ c4d.Vector(0, size, 0), # 0: top-front-left c4d.Vector(size, size, 0), # 1: top-front-right c4d.Vector(size, size, size),# 2: top-back-right c4d.Vector(0, size, size), # 3: top-back-left c4d.Vector(0, 0, 0), # 4: bottom-front-left c4d.Vector(size, 0, 0), # 5: bottom-front-right c4d.Vector(size, 0, size), # 6: bottom-back-right c4d.Vector(0, 0, size), # 7: bottom-back-left ] # Define polygons - vertex order determines normal direction (counter-clockwise = outward) polygons = [ c4d.CPolygon(3, 2, 1, 0), # Top c4d.CPolygon(4, 5, 6, 7), # Bottom c4d.CPolygon(0, 4, 7, 3), # Left c4d.CPolygon(1, 2, 6, 5), # Right c4d.CPolygon(0, 1, 5, 4), # Front c4d.CPolygon(3, 7, 6, 2), # Back ] # Set all points at once cube.SetAllPoints(points) # Set polygons one by one (Python API requirement) for i, cpoly in enumerate(polygons): cube.SetPolygon(i, cpoly) # Notify object of structure change cube.Message(c4d.MSG_UPDATE) return cube def main(): """Insert cube into document with undo support.""" cube = create_cube(100.0) cube.SetName("Python Cube") # Proper undo handling doc.StartUndo() doc.InsertObject(cube) doc.AddUndo(c4d.UNDOTYPE_NEWOBJ, cube) doc.EndUndo() doc.SetActiveObject(cube, c4d.SELECTION_NEW) c4d.EventAdd() if __name__ == '__main__': main() ``` -------------------------------- ### takesystem_take_to_document Source: https://github.com/maxon-computer/cinema-4d-python-api-examples/blob/master/scripts/04_3d_concepts/scene_elements/take_system/readme.md Saves the state of each child Take to a separate document. ```APIDOC ## takesystem_take_to_document ### Description Loops through the child Takes of the main Take. Saves the state of each child Take to a document. ### Method N/A (Example Script) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Response Example N/A ``` -------------------------------- ### Register Tag Plugin (Look at Camera) Source: https://context7.com/maxon-computer/cinema-4d-python-api-examples/llms.txt Registers a custom tag plugin that makes the host object always face the camera. It requires initialization of tag parameters and sets the tag to be camera-dependent for correct execution order. ```python import c4d import os PLUGIN_ID = 1028284 class LookAtCamera(c4d.plugins.TagData): """Tag that makes host object always face the camera.""" def Init(self, node, isCloneInit=False): """Initialize tag parameters.""" self.InitAttr(node, bool, c4d.PYLOOKATCAMERA_PITCH) node[c4d.PYLOOKATCAMERA_PITCH] = True # Set tag to be camera-dependent for proper execution order pd = c4d.PriorityData() pd.SetPriorityValue(c4d.PRIORITYVALUE_CAMERADEPENDENT, True) node[c4d.EXPRESSION_PRIORITY] = pd return True def Execute(self, tag, doc, op, bt, priority, flags): """Called during scene execution to update object orientation.""" # Get current render view bd = doc.GetRenderBaseDraw() if bd is None: return c4d.EXECUTIONRESULT_OK # Get active camera camera = bd.GetSceneCamera(doc) if camera is None: camera = bd.GetEditorCamera() if camera is None: return c4d.EXECUTIONRESULT_OK # Calculate direction to camera in local space local = camera.GetMg().off * (~(op.GetUpMg() * op.GetFrozenMln())) - op.GetRelPos() # Convert to rotation hpb = c4d.utils.VectorToHPB(local) # Optionally preserve pitch if not tag[c4d.PYLOOKATCAMERA_PITCH]: hpb.y = op.GetRelRot().y hpb.z = op.GetRelRot().z op.SetRelRot(hpb) return c4d.EXECUTIONRESULT_OK if __name__ == "__main__": directory, _ = os.path.split(__file__) bmp = c4d.bitmaps.BaseBitmap() bmp.InitWith(os.path.join(directory, "res", "tpylookatcamera.tif")) c4d.plugins.RegisterTagPlugin( id=PLUGIN_ID, str="Py - LookAtCamera", info=c4d.TAG_EXPRESSION | c4d.TAG_VISIBLE, g=LookAtCamera, description="Tpylookatcamera", icon=bmp ) ``` -------------------------------- ### takesystem_override_group_materials Source: https://github.com/maxon-computer/cinema-4d-python-api-examples/blob/master/scripts/04_3d_concepts/scene_elements/take_system/readme.md Creates a Take with an override group for each selected material, assigning an object to the group. ```APIDOC ## takesystem_override_group_materials ### Description Creates a Take with an override group for each selected material. Adds the object "object" to the newly created group. ### Method N/A (Example Script) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Response Example N/A ``` -------------------------------- ### takesystem_userdata Source: https://github.com/maxon-computer/cinema-4d-python-api-examples/blob/master/scripts/04_3d_concepts/scene_elements/take_system/readme.md Adds a new boolean userdata parameter to a given BaseTake. ```APIDOC ## takesystem_userdata ### Description Adds a new boolean userdata parameter to the given BaseTake. ### Method N/A (Example Script) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Response Example N/A ``` -------------------------------- ### takesystem_main_take_current Source: https://github.com/maxon-computer/cinema-4d-python-api-examples/blob/master/scripts/04_3d_concepts/scene_elements/take_system/readme.md Checks if the current Take is the main Take; if not, it sets the main Take as current. ```APIDOC ## takesystem_main_take_current ### Description Checks if the current Take is the main Take. If not, the main Take becomes the current Take. ### Method N/A (Example Script) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Response Example N/A ``` -------------------------------- ### takesystem_override_group_add Source: https://github.com/maxon-computer/cinema-4d-python-api-examples/blob/master/scripts/04_3d_concepts/scene_elements/take_system/readme.md Adds currently selected objects to a specified BaseOverrideGroup. ```APIDOC ## takesystem_override_group_add ### Description Adds the currently selected objects to the BaseOverrideGroup "group". ### Method N/A (Example Script) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Response Example N/A ``` -------------------------------- ### takesystem_override_group Source: https://github.com/maxon-computer/cinema-4d-python-api-examples/blob/master/scripts/04_3d_concepts/scene_elements/take_system/readme.md Adds a new Take and an override group for selected objects, optionally adding a material texture tag. ```APIDOC ## takesystem_override_group ### Description Adds a new Take and creates a new override group for all selected objects. If a material with the name "Green" exists, a texture tag referencing that material is added to the override group. ### Method N/A (Example Script) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Response Example N/A ``` -------------------------------- ### takesystem_counter_part Source: https://github.com/maxon-computer/cinema-4d-python-api-examples/blob/master/scripts/04_3d_concepts/scene_elements/take_system/readme.md Searches for a material's color parameter override and transfers state between Takes. ```APIDOC ## takesystem_counter_part ### Description Searches for the BaseOverride of the given material and its color parameter. If found, the color value is applied to the backup value and transfers the state of this Take to the backup Take. ### Method N/A (Example Script) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Response Example N/A ``` -------------------------------- ### MoGraph Field Sampling in Python Source: https://context7.com/maxon-computer/cinema-4d-python-api-examples/llms.txt This script demonstrates how to sample values from a MoGraph field at specified 3D positions using the Cinema 4D Fields API. It requires a Random Field object to be selected in the scene. The script creates sample positions, sets up the `FieldInput` and `FieldInfo` contexts, samples the field, and then prints the resulting values for each position. ```python import c4d def main(): # Ensure a Random Field is selected if op is None or not op.CheckType(c4d.Frandom): raise ValueError("Please select a Random Field object.") # Create sample positions sampleCount = 10 positions = [c4d.Vector(i * 10.0, 0, 0) for i in range(sampleCount)] # Create FieldInput with positions fieldInput = c4d.modules.mograph.FieldInput(positions, sampleCount) # Create FieldInfo context flags = c4d.FIELDSAMPLE_FLAG_VALUE # We want value output thread = c4d.threading.GeGetCurrentThread() fieldInfo = c4d.modules.mograph.FieldInfo.Create( flags, thread, doc, 0, # Thread index 1, # Thread count fieldInput ) # Create output buffer fieldOutput = c4d.modules.mograph.FieldOutput() fieldOutput.Resize(sampleCount, c4d.FIELDSAMPLE_FLAG_VALUE) # Sample the field op.InitSampling(fieldInfo) op.Sample( fieldInput, fieldOutput.GetBlock(), fieldInfo, c4d.FIELDOBJECTSAMPLE_FLAG_DISABLEDIRECTIONFALLOFF ) op.FreeSampling(fieldInfo) # Access results for i in range(sampleCount): value = fieldOutput.GetValue(i) print(f"Position {positions[i]}: Value = {value}") if __name__ == '__main__': main() ```