Maxon Developers Maxon Developers
    • Documentation
      • Cinema 4D Python API
      • Cinema 4D C++ API
      • Cineware API
      • ZBrush Python API
      • ZBrush GoZ API
      • Code Examples on Github
    • Forum
    • Downloads
    • Support
      • Support Procedures
      • Registered Developer Program
      • Plugin IDs
      • Contact Us
    • Categories
      • Overview
      • News & Information
      • Cinema 4D SDK Support
      • Cineware SDK Support
      • ZBrush 4D SDK Support
      • Bugs
      • General Talk
    • Unread
    • Recent
    • Tags
    • Users
    • Login
    1. Maxon Developers Forum
    2. ferdinand
    Offline
    • Profile
    • Following 0
    • Followers 15
    • Topics 54
    • Posts 3,114
    • Groups 2

    ferdinand

    @ferdinand

    931
    Reputation
    773
    Profile views
    3.1k
    Posts
    15
    Followers
    0
    Following
    Joined
    Last Online

    ferdinand Unfollow Follow
    Global Moderator administrators

    Best posts made by ferdinand

    • How to implement an image control that can receive and generate image data drag events

      Dear community,

      We recently got a non-public support request about handling drag and drop events for a custom image control in a dialog. And while we have shown this, drag event handling, multiple times before, I thought it does not hurt to answer this publicly, as this very case - an image control - is quite common, and it does not hurt having a bit more verbose public example for it.

      edit: I have updated this topic with new code and a new video, to also handle outgoing asset drag events, and talk a bit about the pros and cons of different approaches, and what you could do when not implementing a code example as I did here, and therefore have a bit more leverage room when it comes to complexity.

      In general, doing all this is possible. It is just that not everything is a ready-made solution for you, where you just call a function. At some point you have to "swim" here yourself, as we cannot write your code for you, but I hope the example helps shedding some light on the probably uncessarily complicated drag handling in Cinema 4D.

      Cheers,
      Ferdinand

      Result

      Code

      """Provides an example for implementing a custom control that can generate and receive drag events.
      
      The example implements a dialog which holds multiple "cards" (BitmapCard) that display an image
      and can receive drag events. The user can drag images from the file system into these cards (file
      paths) or drag texture assets from the Asset Browser into these cards. The cards can also generate
      drag events themselves, e.g., when the user drags from a card, it will generate a drag event. 
      Showcased (selectable via the combo box in the menu of the dialog) are three drag types:
      
      1. File paths: Dragging a card will generate an image file path drag event, which for example could 
         be dragged into a file path field of a shader, onto an object in the viewport, or onto other 
         BitmapCard controls. The advantage of this approach is that we do not have to create
         materials or assets, but can just use the file path directly.
      
      2. Materials: Dragging a card will generate an atom drag event, here populated with a Redshift
         material that has the texture of the card as an input. This material can then be dragged onto
         anything that accepts materials, like objects in the viewport. The disadvantage of this
         approach is that we have to create a material, and that we have to exactly define how the 
         material is constructed.
      
      3. Assets: Dragging a card will generate an asset drag event, here populated with a texture asset
         that has the texture of the card as an input. This asset can then be dragged onto anything that
         texture accepts assets, such as an object in the viewport. The disadvantage of this
         approach is that we have to create an asset.
      
         - The example also showcases a variation oof this approach, where we exploit a bit how the
           texture asset drag handling works, to avoid having to create an asset.
      
      
      Overview:
      
      - BitmapCard: A user area control that can receive drag events and generate drag events itself. Here
                    you will find almost all the relevant code for drag and drop handling
      - BitmapStackDialog: A dialog that holds multiple BitmapCard controls and allows the user to select
                      the drag type via a combo box. This dialog is the main entry point of the example
                      but does not contain much relevant code itself.
      """
      __author__ = "Ferdinand Hoppe"
      __copyright__ = "Copyright 2025 Maxon Computer GmbH"
      
      import os
      import re
      
      import c4d
      import maxon
      import mxutils
      
      # The file types that are supported to be dragged into a BitmapCard control.
      DRAG_IN_FILE_TYPES: list[str] = [".png", ".jpg", ".jpeg", ".tif"]
      
      # A regex to check of a string (which is meant to be a path/url) already as a scheme (like file:///
      # or http:///). The protocol we are mostly checking for is "asset:///", but we keep this regex generic
      # to allow for other schemes as well.
      RE_URL_HAS_SCHEME = re.compile("^[a-zA-Z][a-zA-Z\d+\-.]*:\/\/\/")
      
      # A non-public core message which need when we want to properly generate asset drag events.
      COREMSG_SETCOMMANDEDITMODE: int = 300001000
      
      
      class BitmapCard(c4d.gui.GeUserArea):
          """Implements a control that can receive bitmap path drag events and generates drag events itself.
          """
      
          def __init__(self, host: "BitmapStackDialog") -> None:
              """Constructs a new BitmapCard object.
              """
              # The host dialog that holds this card. This is used to access the drag type selected in the
              # combo box of the dialog.
              self._host: BitmapStackDialog = host
      
              # The image file path and the bitmap that is displayed in this card.
              self._path: str | None = ""
              self._bitmap: c4d.bitmaps.BaseBitmap | None = None
      
          def GetMinSize(self) -> tuple[int, int]:
              """Called by Cinema 4d to evaluate the minimum size of the user area.
              """
              return 250, 100
      
          def DrawMsg(self, x1, y1, x2, y2, msg_ref):
              """Called by Cinema 4D to let the user area draw itself.
              """
              self.OffScreenOn()
              self.SetClippingRegion(x1, y1, x2, y2)
      
              # Draw the background and then the bitmap if it exists. In the real world, we would have to
              # either adapt #GetMinSize to the size of the bitmap, or draw the bitmap in a way that it
              # fits into the user area, e.g., by scaling it down. Here we just draw it at a fixed size.
              self.DrawSetPen(c4d.gui.GetGuiWorldColor(c4d.COLOR_BGGADGET))
              self.DrawRectangle(x1, y1, x2, y2)
              if self._bitmap:
                  w, h = self._bitmap.GetSize()
                  self.DrawBitmap(self._bitmap, 5, 5, 240, 90, 0,
                                  0, w, h, c4d.BMP_NORMALSCALED)
      
          def Message(self, msg: c4d.BaseContainer, result: c4d.BaseContainer) -> int:
              """Called by Cinema 4D to handle messages sent to the user area.
      
              Here we implement receiving drag events when the user drags something onto this user area.
              """
              # A drag event is coming in.
              if msg.GetId() == c4d.BFM_DRAGRECEIVE:
                  # Get out when the drag event has been discarded.
                  if msg.GetInt32(c4d.BFM_DRAG_LOST) or msg.GetInt32(c4d.BFM_DRAG_ESC):
                      return self.SetDragDestination(c4d.MOUSE_FORBIDDEN)
      
                  # Get out when this is not a drag type we support (we just support images). Note that we
                  # cannot make up drag types ourselves, so when we want to send/receive complex data, we
                  # must use the DRAGTYPE_ATOMARRAY type and pack our data into a BaseContainer attached
                  # to the nodes we drag/send.
                  data: dict = self.GetDragObject(msg)
                  dragType: int = data.get("type", 0)
                  if dragType not in [c4d.DRAGTYPE_FILENAME_IMAGE, maxon.DRAGTYPE_ASSET]:
                      return self.SetDragDestination(c4d.MOUSE_FORBIDDEN)
      
                  # Here we could optionally check the drag event hitting some target area.
                  # yPos: float = self.GetDragPosition(msg).get('y', 0.0)
                  # if not 0 < yPos < 50 or not self.CheckDropArea(msg, True, True):
                  #     return self.SetDragDestination(c4d.MOUSE_FORBIDDEN)
      
                  # After this point, we are dealing with a valid drag event.
      
                  # The drag is still going on, we just set the mouse cursor to indicate that we are
                  # ready to receive the drag event.
                  if msg.GetInt32(c4d.BFM_DRAG_FINISHED) == 0:
                      return self.SetDragDestination(c4d.MOUSE_MOVE)
                  # The drag event is finished, we can now process the data.
                  else:
                      # Unpack a file being dragged directly.
                      path: str | None = None
                      if dragType == c4d.DRAGTYPE_FILENAME_IMAGE:
                          path = data.get("object", None)
                      # Unpack an asset being dragged.
                      elif dragType == maxon.DRAGTYPE_ASSET:
                          array: maxon.DragAndDropDataAssetArray = data.get(
                              "object", None)
                          descriptions: tuple[tuple[maxon.AssetDescription, maxon.Url, maxon.String]] = (
                              array.GetAssetDescriptions())
                          if not descriptions:
                              # Invalid asset but we are not in an error state.
                              return True
      
                          # Check that we are dealing with an image asset.
                          asset: maxon.AssetDescription = descriptions[0][0]
                          metadata: maxon.BaseContainer = asset.GetMetaData()
                          subType: maxon.Id = metadata.Get(
                              maxon.ASSETMETADATA.SubType, maxon.Id())
                          if (subType != maxon.ASSETMETADATA.SubType_ENUM_MediaImage):
                              # Invalid asset but we are not in an error state.
                              return True
      
                          path = str(maxon.AssetInterface.GetAssetUrl(asset, True))
      
                      if not isinstance(path, str):
                          return False  # Critical failure.
      
                      if (dragType == c4d.DRAGTYPE_FILENAME_IMAGE and
                          (not os.path.exists(path) or
                           os.path.splitext(path)[1].lower() not in DRAG_IN_FILE_TYPES)):
                          # Invalid file type but we are not in an error state.
                          return True
      
                      self._path = path
                      self._bitmap = c4d.bitmaps.BaseBitmap()
                      if self._bitmap.InitWith(path)[0] != c4d.IMAGERESULT_OK:
                          return False  # Critical failure.
      
                      self.Redraw()  # Redraw the user area to show the new bitmap.
      
                      return True
      
              # Process other messages, doing this is very important, as we otherwise break the
              # message chain.
              return c4d.gui.GeUserArea.Message(self, msg, result)
      
          def InputEvent(self, msg: c4d.BaseContainer) -> bool:
              """Called by Cinema 4D when the user area receives input events.
      
              Here we implement creating drag events when the user drags from this user area. The type of
              drag event which is initiated is determined by the drag type selected in the combo box
              of the dialog.
              """
              # When this is not a left mouse button event on this user area, we just get out without
              # consuming the event (by returning False).
              if (msg.GetInt32(c4d.BFM_INPUT_DEVICE) != c4d.BFM_INPUT_MOUSE or
                      msg.GetInt32(c4d.BFM_INPUT_CHANNEL) != c4d.BFM_INPUT_MOUSELEFT):
                  return False
      
              # Get the type of drag event that should be generated, and handle it.
              dragType: int = self._host.GetInt32(self._host.ID_DRAG_TYPE)
              return self.HandleDragEvent(msg, dragType)
          
          # --- Custom drag handling methods -------------------------------------------------------------
      
          # I have split up thing into three methods for readability, this all could also be done directly
          # in the InputEvent method.
      
          def HandleDragEvent(self, event: c4d.BaseContainer, dragType: int) -> bool:
              """Handles starting a drag event by generating the drag data and sending it to the system.
      
              This is called when the user starts dragging from this user area.
              """
              # This requires us to modify the document, so we must be on the main thread (technically
              # not true when the type is DRAGTYPE_FILENAME_IMAGE, but that would be for you to optimize).
              if not c4d.threading.GeIsMainThread():
                  raise False
      
              # Generate our drag data, either a file path, a material, or an asset.
              doc: c4d.documents.BaseDocument = c4d.documents.GetActiveDocument()
              data: object = self.GenerateDragData(doc, dragType)
      
              # Now we set off the drag event. When we are dragging assets, we have to sandwich the event
              # in these core message calls, as otherwise the palette edit mode toggling will not work
              # correctly.
              if dragType == maxon.DRAGTYPE_ASSET:
                  bc: c4d.BaseContainer = c4d.BaseContainer(
                      COREMSG_SETCOMMANDEDITMODE)
                  bc.SetInt32(1, True)
                  c4d.SendCoreMessage(c4d.COREMSG_CINEMA, bc, 0)
      
              # When #HandleMouseDrag returns #False, this means that the user has cancelled the drag
              # event, one case could be that the user actually did not intend to drag, but just
              # clicked on the user area.
              #
              # In this case we remove the drag data we generated, as it is not needed anymore. Note that
              # this will NOT catch the case that the drag event is cancelled by the recipient, e.g., the
              # user drags a material onto something that does not accept materials.
              if not self.HandleMouseDrag(event, dragType, data, 0):
                  self.RemoveDragData(doc, data)
                  return True
      
              # Other half of the sandwich, we toggle the palette edit mode back to normal.
              if dragType == maxon.DRAGTYPE_ASSET:
                  bc: c4d.BaseContainer = c4d.BaseContainer(
                      COREMSG_SETCOMMANDEDITMODE)
                  bc.SetInt32(1, False)
                  c4d.SendCoreMessage(c4d.COREMSG_CINEMA, bc, 0)
      
              return True
      
          def GenerateDragData(self, doc: c4d.documents.BaseDocument, dragType
                               ) -> str | c4d.BaseMaterial | maxon.DragAndDropDataAssetArray:
              """Generates the drag data for the given drag type.
      
              Each tile just encapsulates a file path, but we realize dragging them as file paths,
              materials, or assets. So, when the type is material or asset, the drag data must be
              generated from the file path. Which is why we have this method here.
              """
              if not c4d.threading.GeIsMainThread():
                  raise RuntimeError(
                      "GenerateDragData must be called from the main thread.")
      
              # The user has selected "File" as the drag type, we just return the file path.
              if dragType == c4d.DRAGTYPE_FILENAME_IMAGE:
                  return self._path
              # The user has selected "Material" as the drag type, we create a Redshift material with the
              # texture as input and return that material.
              elif dragType == c4d.DRAGTYPE_ATOMARRAY:
                  material: c4d.BaseMaterial = mxutils.CheckType(
                      c4d.BaseMaterial(c4d.Mmaterial))
      
                  # Create a simple graph using that texture, and insert the material into the
                  # active document.
                  maxon.GraphDescription.ApplyDescription(
                      maxon.GraphDescription.GetGraph(
                          material, maxon.NodeSpaceIdentifiers.RedshiftMaterial),
                      {
                          "$type": "Output",
                          "Surface": {
                              "$type": "Standard Material",
                              "Base/Color": {
                                  "$type": "Texture",
                                  # Set the texture. When our source is a file we will just have a plain
                                  # path, e.g. "C:/path/to/file.png" and we have to prefix with a scheme
                                  # (file) to make it a valid URL. When we are dealing with an asset, the
                                  # texture path will already be a valid URL in the "asset:///" scheme.
                                  "Image/Filename/Path": (maxon.Url(f"{self._path}")
                                                          if RE_URL_HAS_SCHEME.match(self._path) else
                                                          maxon.Url(f"file:///{self._path}"))
                              }
                          }
                      })
                  doc.InsertMaterial(material)
                  return [material]
              # The user has selected "Asset" as the drag type, we create a texture asset and return that.
              elif dragType == maxon.DRAGTYPE_ASSET:
                  # So we have to cases here, either that we want truly want to generate an asset drag
                  # event or that we just want to piggy-back onto the texture asset drag and drop
                  # mechanism of Cinema 4D, which is what we do here.
      
                  # Code for truly generating an asset drag event, where we would store the asset in the
                  # scene repository.
                  generateAssets: bool = False
                  if generateAssets:
                      # Get the scene repository and create an asset storage structure for the asset.
                      repo: maxon.AssetRepository = doc.GetSceneRepository(True)
                      store: maxon.StoreAssetStruct = maxon.StoreAssetStruct(
                          maxon.Id(), repo, repo)
      
                      # Now save the texture asset to the repository.
                      url: maxon.Url = maxon.Url(self._path)
                      name: str = url.GetName()
                      asset, _ = maxon.AssetCreationInterface.SaveTextureAsset(
                          url, name, store, (), True)
      
                      # Create a drag array for that asset. It is important that we use the URL of the
                      # asset (maxon.AssetInterface.GetAssetUrl) and not #url or asset.GetUrl(), as both
                      # are physical file paths, and will then cause the drag and drop handling to use
                      # these physical files, including the popup asking for wether the file should be
                      # copied. We will exploit exactly this behavior in the second case.
                      dragArray: maxon.DragAndDropDataAssetArray = maxon.DragAndDropDataAssetArray()
                      dragArray.SetLookupRepository(repo)
                      dragArray.SetAssetDescriptions((
                          (asset, maxon.AssetInterface.GetAssetUrl(asset, True), maxon.String(name)),
                      ))
      
                      return dragArray
                  # With this case we can piggy-back onto the existing drag and drop texture asset
                  # handling of Cinema 4D, without actually having to create an asset. THIS IS A
                  # WORKAROUND, we could decide at any moment to change how the drag and drop
                  # handling of assets works, possibly rendering this approach obsolete.
                  else:
                      # The slight disadvantage of this approach (besides it being a hack and us possibly
                      # removing it at some point) is that we have to pay the download cost of
                      # #self._host._dummyAssetId once. I.e., the user has to download that texture once
                      # either by using it in the Asset Browser or by running this code. Once the asset has
                      # been cached, this will not happen again.
                      #
                      # But since we search below in a 'whoever comes first' manner, what is the first
                      # texture asset could change, and this could then be an asset which has not been
                      # downloaded yet. So, in a more robust world we would pick a fixed asset below. But
                      # this comes then with the burden of maintenance, as we could remove one of the
                      # builtin texture assets at any time. So, the super advanced solution would be to
                      # ship the plugin with its own asset database, and mount and use that. Here we could
                      # use a hard-coded asset ID, and would have to have never pay download costs, as
                      # the repository would be local.
      
                      # Find the asset by its Id, which we have stored in the dialog.
                      repo: maxon.AssetRepositoryInterface = maxon.AssetInterface.GetUserPrefsRepository()
                      dummy: maxon.AssetDescription = repo.FindLatestAsset(
                          maxon.AssetTypes.File().GetId(), self._host._dummyAssetId, maxon.Id(),
                          maxon.ASSET_FIND_MODE.LATEST)
      
                      # Setup the drag array with the asset. Note that #asset must be a valid texture
                      # asset, so just passing maxon.AssetDescription() will not work. But the backend
                      # for drag and drop handling will actually ignore the asset except for type checking
                      # it, and use the URL we provided instead.
                      dragArray: maxon.DragAndDropDataAssetArray = maxon.DragAndDropDataAssetArray()
                      dragArray.SetLookupRepository(repo)
                      dragArray.SetAssetDescriptions((
                          (dummy, maxon.Url(self._path), maxon.String(os.path.basename(self._path))),
                      ))
                  return dragArray
              else:
                  raise ValueError(f"Unsupported drag type: {dragType}")
      
          def RemoveDragData(self, doc: c4d.documents.BaseDocument,
                             data: str | list[c4d.BaseMaterial] | maxon.DragAndDropDataAssetArray) -> bool:
              """Removes generated content when the user cancels a drag event.
      
              Sometimes the user starts a drag event, but then cancels it, e.g., by pressing the
              escape key. In this case, we have to remove the generated content, e.g., the material or
              asset that we created for the drag event.
              """
              if not c4d.threading.GeIsMainThread():
                  return False
      
              if isinstance(data, list):
                  # Remove the dragged materials from the document. Since we are always generating a new
                  # material, we can just remove them. That is in general probably not the best design,
                  # and a real world application should avoid duplicating materials.
                  for item in data:
                      if isinstance(item, c4d.BaseList2D):
                          item.Remove()
              elif isinstance(data, str):
                  # Here we could technically remove a file.
                  pass
              elif isinstance(data, maxon.DragAndDropDataAssetArray):
                  # We could remove the asset, but other than for the material, there is no guarantee
                  # that we are the only user of it, as the Asset API has a duplicate preventing
                  # mechanism. So, the #SaveTextureAsset call above could have returned an already
                  # existing asset. Since we could operate with a document bound repository, we could
                  # search the whole document for asset references and only when we find none, remove
                  # the asset.
                  #
                  # We use here the little hack that we actually do not create an asset, to just to piggy-
                  # back onto the material drag and drop mechanism of assets, so we can just ignore
                  # this case.
                  pass
      
              return True
      
      
      class BitmapStackDialog(c4d.gui.GeDialog):
          """Implements a a simple dialog that stacks multiple BitmapCard controls.
          """
          ID_DRAG_TYPE: int = 1002
      
          def __init__(self):
              """Constructs a new ExampleDialog object.
              """
              # The user area controls that will generate and receive drag events.
              self._cards: list[BitmapCard] = [
                  BitmapCard(host=self) for _ in range(4)]
      
              # The id for the dummy asset that used to generate 'fake' texture asset drag events. We
              # search for it here once, so that we do not have to do it in the __init__ of each
              # BitmapCard, or even worse, in the HandleDragEvent of each BitmapCard.
      
              # We could technically also store here the AssetDescription instead of the Id, but that
              # reference can go stale, so we just store the Id and then grab with it the asset when we
              # need it. Which is much faster than searching asset broadly as we do here. In the end, we
              # could probably also do all this in the drag handling of the BitmapCard, but a little bit
              # of optimization does not hurt.
              self._dummyAssetId: maxon.Id | None = None
              if not maxon.AssetDataBasesInterface.WaitForDatabaseLoading():
                  raise RuntimeError("Could not initialize the asset databases.")
      
              def findTexture(asset: maxon.AssetDescription) -> bool:
                  """Finds the first texture asset in the user preferences repository.
                  """
                  # When this is not a texture asset, we just continue searching.
                  meta: maxon.AssetMetaData = asset.GetMetaData()
                  if (meta.Get(maxon.ASSETMETADATA.SubType, maxon.Id()) !=
                          maxon.ASSETMETADATA.SubType_ENUM_MediaImage):
                      return True
      
                  # When it is a texture asset, we store it as the dummy asset and stop searching.
                  self._dummyAssetId = asset.GetId()
                  return False
      
              # Search for our dummy asset in the user preferences repository.
              repo: maxon.AssetRepositoryInterface = maxon.AssetInterface.GetUserPrefsRepository()
              repo.FindAssets(maxon.AssetTypes.File().GetId(), maxon.Id(), maxon.Id(),
                              maxon.ASSET_FIND_MODE.LATEST, findTexture)
      
          def CreateLayout(self):
              """Called by Cinema 4D to populate the dialog with controls.
              """
              self.SetTitle("Drag and Drop Example")
              self.GroupSpace(5, 5)
              self.GroupBorderSpace(5, 5, 5, 5)
      
              # Build the combo box in the menu bar of the dialog.
              self.GroupBeginInMenuLine()
              self.GroupBegin(1000, c4d.BFH_LEFT | c4d.BFV_TOP, cols=2)
              self.GroupBorderSpace(5, 5, 5, 5)
              self.GroupSpace(5, 5)
              self.AddStaticText(1001, c4d.BFH_LEFT |
                                 c4d.BFV_CENTER, name="Drag Events as:")
              self.AddComboBox(1002, c4d.BFH_RIGHT | c4d.BFV_TOP)
              self.GroupEnd()
              self.GroupEnd()
      
              # Add the BitmapCard controls to the dialog.
              for i, card in enumerate(self._cards):
                  self.AddUserArea(2000 + i, c4d.BFH_LEFT | c4d.BFV_TOP)
                  self.AttachUserArea(card, 2000 + i)
      
              # Add items to the combo box to select the drag type.
              self.AddChild(self.ID_DRAG_TYPE, c4d.DRAGTYPE_FILENAME_IMAGE, "Files")
              self.AddChild(self.ID_DRAG_TYPE, c4d.DRAGTYPE_ATOMARRAY, "Materials")
              self.AddChild(self.ID_DRAG_TYPE, maxon.DRAGTYPE_ASSET, "Assets")
              self.SetInt32(self.ID_DRAG_TYPE, c4d.DRAGTYPE_FILENAME_IMAGE)
      
              return True
      
      
      # Define a global variable of the dialog to keep it alive in a Script Manager script. ASYNC dialogs
      # should not be opened in production code from a Script Manager script, as this results in a
      # dangling dialog. Implement a command plugin when you need async dialogs in production.
      dlg: BitmapStackDialog = BitmapStackDialog()
      if __name__ == "__main__":
          dlg.Open(dlgtype=c4d.DLG_TYPE_ASYNC, defaultw=150, defaulth=250)
      
      
      posted in Cinema 4D SDK 2025 python
      ferdinandF
      ferdinand
    • RE: Welcome Mr. Hoppe

      Hi,

      thanks for the kind words both from Maxon and the community. I am looking forward to my upcoming adventures with the SDK Team and Cinema community.

      Cheers,
      Ferdinand

      posted in News & Information
      ferdinandF
      ferdinand
    • RE: API for new behavior of opnening Windows in Layout

      Hello @holgerbiebrach,

      please excuse the wait. So, this is possible in Python and quite easy to do. This new behavior is just the old dialog folding which has been reworked a little bit. I have provided a simple example at the end of the posting. There is one problem regarding title bars which is sort of an obstacle for plugin developers which want to distribute their plugins, it is explained in the example below.

      I hope this helps and cheers,
      Ferdinand

      The result:
      3453535.gif
      The code:

      """Example for a command plugin with a foldable dialog as provided with the
      Asset Browser or Coordinate Manger in Cinema 4D R25.
      
      The core of this is just the old GeDialog folding mechanic which has been
      changed slightly with R25 as it will now also hide the title bar of a folded
      dialog, i.e., the dialog will be hidden completely.
      
      The structure shown here mimics relatively closely what the Coordinate Manger
      does. There is however one caveat: Even our internal implementations do not
      hide the title bar of a dialog when unfolded. Instead, this is done via 
      layouts, i.e., by clicking onto the ≡ icon of the dialog and unchecking the
      "Show Window Title" option and then saving such layout. If you would want
      to provide a plugin which exactly mimics one of the folding managers, you
      would have to either ask your users to take these steps or provide a layout.
      
      Which is not ideal, but I currently do not see a sane way to hide the title
      bar of a dialog. What you could do, is open the dialog as an async popup which 
      would hide the title bar. But that would also remove the ability to dock the 
      dialog. You could then invoke `GeDialog.AddGadegt(c4d.DIALOG_PIN, SOME_ID)`to 
      manually add a pin back to your dialog, so that you can dock it. But that is 
      not how it is done internally by us, as we simply rely on layouts for that.
      """
      
      import c4d
      
      
      class ExampleDialog (c4d.gui.GeDialog):
          """Example dialog that does nothing.
      
          The dialog itself has nothing to do with the implementation of the
          folding.
          """
          ID_GADGETS_START = 1000
          ID_GADGET_GROUP = 0
          ID_GADGET_LABEL = 1
          ID_GADGET_TEXT = 2
      
          GADGET_STRIDE = 10
          GADEGT_COUNT = 5
      
          def CreateLayout(self) -> bool:
              """Creates dummy gadgets.
              """
              self.SetTitle("ExampleDialog")
              flags = c4d.BFH_SCALEFIT
      
              for i in range(self.GADEGT_COUNT):
                  gid = self.ID_GADGETS_START + i * self.GADGET_STRIDE
                  name = f"Item {i}"
      
                  self.GroupBegin(gid + self.ID_GADGET_GROUP, flags, cols=2)
                  self.GroupBorderSpace(5, 5, 5, 5)
                  self.GroupSpace(2, 2)
                  self.AddStaticText(gid + self.ID_GADGET_LABEL, flags, name=name)
                  self.AddEditText(gid + self.ID_GADGET_TEXT, flags)
                  self.GroupEnd()
              return True
      
      
      class FoldingManagerCommand (c4d.plugins.CommandData):
          """Provides the implementation for a command with a foldable dialog.
          """
          ID_PLUGIN = 1058525
          REF_DIALOG = None
      
          @property
          def Dialog(self) -> ExampleDialog:
              """Returns a class bound ExampleDialog instance.
              """
              if FoldingManagerCommand.REF_DIALOG is None:
                  FoldingManagerCommand.REF_DIALOG = ExampleDialog()
      
              return FoldingManagerCommand.REF_DIALOG
      
          def Execute(self, doc: c4d.documents.BaseDocument) -> bool:
              """Folds or unfolds the dialog.
      
              The core of the folding logic as employed by the Asset Browser
              or the Coordinate manager in R25.
              """
              # Get the class bound dialog reference.
              dlg = self.Dialog
              # Fold the dialog, i.e., hide it if it is open and unfolded. In C++
              # you would also want to test for the dialog being visible with
              # GeDialog::IsVisible, but we cannot do that in Python.
              if dlg.IsOpen() and not dlg.GetFolding():
                  dlg.SetFolding(True)
              # Open or unfold the dialog. The trick here is that calling
              # GeDialog::Open will also unfold the dialog.
              else:
                  dlg.Open(c4d.DLG_TYPE_ASYNC, FoldingManagerCommand.ID_PLUGIN)
      
              return True
      
          def RestoreLayout(self, secret: any) -> bool:
              """Restores the dialog on layout changes.
              """
              return self.Dialog.Restore(FoldingManagerCommand.ID_PLUGIN, secret)
      
          def GetState(self, doc: c4d.documents.BaseDocument) -> int:
              """Sets the command icon state of the plugin.
      
              This is not required, but makes it a bit nicer, as it will indicate
              in the command icon when the dialog is folded and when not.
              """
              dlg = self.Dialog
              result = c4d.CMD_ENABLED
              if dlg.IsOpen() and not dlg.GetFolding():
                  result |= c4d.CMD_VALUE
      
              return result
      
      
      def RegisterFoldingManagerCommand() -> bool:
          """Registers the example.
          """
          return c4d.plugins.RegisterCommandPlugin(
              id=FoldingManagerCommand.ID_PLUGIN,
              str="FoldingManagerCommand",
              info=c4d.PLUGINFLAG_SMALLNODE,
              icon=None,
              help="FoldingManagerCommand",
              dat=FoldingManagerCommand())
      
      
      if __name__ == '__main__':
          if not RegisterFoldingManagerCommand():
              raise RuntimeError(
                  f"Failed to register {FoldingManagerCommand} plugin.")
      
      posted in Cinema 4D SDK
      ferdinandF
      ferdinand
    • Projecting Points from Object/World Space into Texture Space

      Dear Community,

      this question reached us via email-support in the context of C++, but I thought the answer might be interesting for other users too.

      The underlying question in this case was how to project points from object or world space into the texture space of an object with UV data. I am showing here deliberately an approach that can be followed both in C++ and Python, so that all users can benefit from this. In C++ one has also the option of using VolumeData and its methods VolumeData::GetUvw or VolumeData::ProjectPoint but must then either implement a volume shader (as otherwise the volume data attached to the ChannelData passed to ShaderData::Output will be nullptr), or use VolumeData:: AttachVolumeDataFake to access ::ProjectPoint. There is however no inherent necessity to take this shader bound route as shown by the example.

      Cheers,
      Ferdinand

      Result

      The script has created a texture with red pixels for the intersection points of the rays cast from each vertex of the spline towards the origin of the polygon object. The script also created the null object rays to visualize the rays which have been cast.
      820ac56e-be8c-4e02-adde-62301f1dfd79-image.png

      raycast_texture.c4d : The scene file.

      Code

      ⚠ You must save the script to disk before running it, as the script infers from the script location the place to save the generated texture to.

      """Demonstrates how to project points from world or object space to UV space.
      
      This script assumes that the user has selected a polygon object and a spline object in the order
      mentioned. The script projects the points of the spline object onto the polygon object and creates
      a texture from the UV coordinates of the projected points. The texture is then applied to the
      polygon object.
      
      The script uses the `GeRayCollider` class to find the intersection of rays cast from the points of
      the spline object to the polygon object. The UV coordinates of the intersection points are then
      calculated using the `HairLibrary` class. In the C++ API, one should use maxon::
      GeometryUtilsInterface::CalculatePolygonPointST() instead.
      
      Finally, using GeRayCollider is only an example for projecting points onto the mesh. In practice,
      any other method can be used as long as it provides points that lie in the plane(s) of a polygon.
      
      The meat of the example is in the `main()` function. The other functions are just fluff.
      """
      
      import os
      import c4d
      import mxutils
      import uuid
      
      from mxutils import CheckType
      
      doc: c4d.documents.BaseDocument  # The currently active document.
      op: c4d.BaseObject | None  # The primary selected object in `doc`. Can be `None`.
      
      def CreateTexture(points: list[c4d.Vector], path: str, resolution: int = 1000) -> None:
          """Creates a texture from the given `points` and saves it to the given `path`.
      
          Parameters:
              path (str): The path to save the texture to.
              points (list[c4d.Vector]): The points to create the texture from.
          """
          # Check the input values for validity.
          if os.path.exists(path):
              raise FileExistsError(f"File already exists at path: {path}")
          if not path.endswith(".png"):
              raise ValueError("The path must end with '.png'.")
      
          # Create a drawing canvas to draw the points on.
          canvas: c4d.bitmaps.GeClipMap = CheckType(c4d.bitmaps.GeClipMap())
          if not canvas.Init(resolution, resolution, 24):
              raise MemoryError("Failed to initialize GeClipMap.")
      
          # Fill the canvas with white.
          canvas.BeginDraw()
          canvas.SetColor(255, 255, 255)
          canvas.FillRect(0, 0, resolution, resolution)
      
          # Draw the points on the canvas.
          canvas.SetColor(255, 0, 0)
          for p in points:
              x: int = int(p.x * resolution)
              y: int = int(p.y * resolution)
              x0: int = max(0, x - 1)
              y0: int = max(0, y - 1)
              x1: int = min(resolution, x + 1)
              y1: int = min(resolution, y + 1)
              canvas.FillRect(x0, y0, x1, y1)
      
          canvas.EndDraw()
      
          # Save the canvas to the given path.
          bitmap: c4d.bitmaps.BaseBitmap = CheckType(canvas.GetBitmap())
          bitmap.Save(path, c4d.FILTER_PNG)
      
          c4d.bitmaps.ShowBitmap(bitmap)
      
      def ApplyTexture(obj: c4d.BaseObject, path: str) -> None:
          """Applies the texture at the given `path` to the given `obj`.
          """
          CheckType(obj, c4d.BaseObject)
      
          # Check the input values for validity.
          if not os.path.exists(path):
              raise FileNotFoundError(f"File does not exist at path: {path}")
      
          # Create a material and apply the texture to it.
          material: c4d.BaseMaterial = CheckType(c4d.BaseMaterial(c4d.Mmaterial), c4d.BaseMaterial)
          obj.GetDocument().InsertMaterial(material)
      
          shader: c4d.BaseShader = CheckType(c4d.BaseShader(c4d.Xbitmap), c4d.BaseShader)
          shader[c4d.BITMAPSHADER_FILENAME] = path
          material.InsertShader(shader)
          material[c4d.MATERIAL_COLOR_SHADER] = shader
          material[c4d.MATERIAL_PREVIEWSIZE] = c4d.MATERIAL_PREVIEWSIZE_1024
      
          # Apply the material to the object.
          tag: c4d.TextureTag = CheckType(obj.MakeTag(c4d.Ttexture))
          tag[c4d.TEXTURETAG_PROJECTION] = c4d.TEXTURETAG_PROJECTION_UVW
          tag[c4d.TEXTURETAG_MATERIAL] = material
      
      def CreateDebugRays(spline: c4d.SplineObject, p: c4d.Vector) -> None:
          """Adds spline objects to the document to visualize the rays from the given `p` to the points of
          the given `spline`.
          """
          doc: c4d.documents.BaseDocument = CheckType(spline.GetDocument(), c4d.documents.BaseDocument)
          rays: c4d.BaseObject = c4d.BaseObject(c4d.Onull)
          rays.SetName("Rays")
          doc.InsertObject(rays)
      
          for q in spline.GetAllPoints():
              ray: c4d.SplineObject = c4d.SplineObject(2, c4d.SPLINETYPE_LINEAR)
              ray.SetPoint(0, p)
              ray.SetPoint(1, q * spline.GetMg())
              ray.Message(c4d.MSG_UPDATE)
              ray.InsertUnder(rays)
      
      def main() -> None:
          """Carries out the main logic of the script.
          """
          # Check the object selection for being meaningful input.
          selected: list[c4d.BaseObject] = doc.GetActiveObjects(c4d.GETACTIVEOBJECTFLAGS_SELECTIONORDER)
          if (len(selected) != 2 or not selected[0].CheckType(c4d.Opolygon) or
              not selected[1].CheckType(c4d.Ospline)):
              raise ValueError("Please select a polygon object and a spline object.")
      
          polygonObject, splineObject = selected
      
          # Get the uvw tag, the points, and the polygons of the polygon object.
          uvwTag: c4d.UvwTag = mxutils.CheckType(polygonObject.GetTag(c4d.Tuvw))
          points: list[c4d.Vector] = [polygonObject.GetMg() * p for p in polygonObject.GetAllPoints()]
          polys: list[c4d.CPolygon] = polygonObject.GetAllPolygons()
      
          # We are casting here in a dumb manner towards the center of the polygon object. In practice,
          # one should cast rays towards the plane of the polygon object. Or even better, use another
          # method to project the points onto the polygon object, as GeRayCollider is not the most 
          # efficient thing in the world.
          rayTarget: c4d.Vector = polygonObject.GetMg().off
          CreateDebugRays(splineObject, rayTarget)
      
          # Initialize the GeRayCollider to find the intersection of rays cast from the points of the
          # spline object to the polygon object.
          collider: c4d.utils.GeRayCollider = c4d.utils.GeRayCollider()
          if not collider.Init(polygonObject):
              raise MemoryError("Failed to initialize GeRayCollider.")
      
      
          # Init our output list and iterate over the points of the spline object.
          uvPoints: list[c4d.Vector] = []
          for p in splineObject.GetAllPoints():
      
              # Transform the point from object to world space (q) and then to the polygon object's space
              # (ro). Our ray direction always points towards the center of the polygon object.
              q: c4d.Vector = splineObject.GetMg() * p
              ro: c4d.Vector = ~polygonObject.GetMg() * q
              rd: c4d.Vector = rayTarget - ro
      
              # Cast the ray and check if it intersects with the polygon object.
              if not collider.Intersect(ro, rd, 1E6) or collider.GetIntersectionCount() < 1:
                  continue
              
              # Get the hit position and the polygon ID of the intersection.
              hit: dict = collider.GetNearestIntersection()
              pos: c4d.Vector = mxutils.CheckType(hit.get("hitpos", None), c4d.Vector)
              pid: int = mxutils.CheckType(hit.get("face_id", None), int)
      
              # One mistake would be now to use the barycentric coordinates that are in the intersection
              # data, as Cinema uses an optimized algorithm to interpolate in a quad and not the standard
              # cartesian-barycentric conversion. In Python these polygon weights are only exposed in a 
              # bit weird place, the hair library. In C++ these barycentric coordinates make sense because
              # there exist methods to convert them to weights. In Python the barycentric coordinates are
              # pretty much useless as we do not have such a conversion function here.
      
              # Compute the weights s, t for the intersection point in the polygon.
              s, t = c4d.modules.hair.HairLibrary().GetPolyPointST(
                  pos, points[polys[pid].a], points[polys[pid].b],
                       points[polys[pid].c], points[polys[pid].d], True)
      
              # Get the uv polygon and bilinearly interpolate the coordinates using the weights. It would
              # be better to use the more low-level variable tag data access functions in VariableTag 
              # than UvwTag.GetSlow() in a real-world scenario.
              uvw: list[c4d.Vector] = list(uvwTag.GetSlow(pid).values())
              t0: c4d.Vector = c4d.utils.MixVec(uvw[0], uvw[1], s)
              t1: c4d.Vector = c4d.utils.MixVec(uvw[3], uvw[2], s)
              uv: c4d.Vector = c4d.utils.MixVec(t0, t1, t)
      
              # Append the UV coordinates to the output list.
              uvPoints.append(uv)
      
          # Write the UV coordinates to a texture and apply it to the polygon object.
          path: str = os.path.join(os.path.dirname(__file__), f"image-{uuid.uuid4()}.png")
          CreateTexture(uvPoints, path, resolution=1024)
          ApplyTexture(polygonObject, path)
      
          c4d.EventAdd()
      
      
      if __name__ == '__main__':
          main()
      
      posted in Cinema 4D SDK 2024 python
      ferdinandF
      ferdinand
    • RE: Reading proper decimal values on lower numbers?

      Hi,

      that your script is not working has not anything to do with pseudo decimals, but the fact that you are treating numbers as strings (which is generally a bad idea) in a not very careful manner. When you truncate the string representation of a number which is represented in scientific notation (with an exponent), then you also truncate that exponent and therefor change the value of the number.

      To truncate a float you can either take the floor of my_float * 10 ** digits and then divide by 10 ** digits again or use the keyword round.

      data = [0.03659665587738824,
              0.00018878623163019122,
              1.1076812650509394e-03,
              1.3882258325566638e-06]
      
      for n in data:
          rounded = round(n, 4)
          floored = int(n * 10000) / 10000
          print(n, rounded, floored)
      
      0.03659665587738824 0.0366 0.0365
      0.00018878623163019122 0.0002 0.0001
      0.0011076812650509394 0.0011 0.0011
      1.3882258325566637e-06 0.0 0.0
      [Finished in 0.1s]
      

      Cheers
      zipit

      posted in General Talk
      ferdinandF
      ferdinand
    • Forum and Documentation Maintenance on the 18th and 22nd

      Dear community,

      We will have to touch multiple parts of developers.maxon.net on the 18.01.2024 and 19.01.2024 22.01.2024. This will result in outages of our documentation and the forum these days. I will try to keep the outage times to a minimum and it will certainly not span the whole two days. But especially one task I will do on Friday might take hours to complete and I can only do that on a forum which is in maintenance mode.

      Please make sure to download a recent offline documentation in case you plan to do extended development work the next two days. As a result, forum support might also be delayed on these days.

      Cheers,
      Ferdinand

      posted in News & Information forum news
      ferdinandF
      ferdinand
    • RE: GetAllTextures from materials only

      Hi,

      sorry for all the confusion. You have to pass actual instances of objects. The following code does what you want (and this time I actually tried it myself ;)).

      import c4d
      
      def main():
          """
          """
          bc = doc.GetAllTextures(ar=doc.GetMaterials())
          for cid, value in bc:
              print cid, value
      
      if __name__=='__main__':
         main()
      

      Cheers,
      zipit

      posted in Cinema 4D SDK
      ferdinandF
      ferdinand
    • 2025.0.0 SDK Release

      Dear development community,

      On September the 10th, 2024, Maxon Computer released Cinema 4D 2025.0.0. For an overview of the new features of Cinema 4D 2025.0, please refer to the release announcement. Alongside this release, a new Cinema 4D SDK and SDK documentation have been released, reflecting the API changes for 2025.0.0. The major changes are:

      C++ API

      • What was formerly has been know as the Classic API has been deprecated in favour of the Cinema API. Alongside this a new cinema namespace has been introduced which contains all the entities which were formerly in the anonymous global namespace known as the Classic API. Plugin authors must adopt their code to this new API, although the changes are not nearly as extensive as for 2024. See the 2025 migration guide for details. Code examples and documentation have been updated to now refer to a Cinema API.
      • 2025 uses OCIO as the default color management mode, brings an improved color picker, and made general improvements to the consistency of the OCIO implementation. This had some effects on the underlying OCIO API which are reflected in two new code examples in the OCIO Manual and a new plugin in the SDK.

      Python API

      • Python also received the update from Classic to Cinema API. But here the change was more of a cosmetic nature confined to the documentation. The c4d package remains the home for all formerly Classic and now Cinema API entities.
      • The mxutils package received updates around standardized scene traversal, random number generation, and more.
      • Graph descriptions now support variadic ports of arbitrary complexity and explicit port references.

      Head to our download section for the newest SDK downloads, or the C++ and Python API change notes for an in detail overview of the changes.

      ⚠ We discovered late in the cycle bugs in the Asset API code examples and OCIO code in the Python SDK. Which is why the publication of the Python SDK and GitHub code examples has been postponed until these bugs are fixed. They should be ready latest by Friday the 13th of September. But the Python online documentation is accessible and error free (to our knowledge).

      ⚠ We had to make some last minute changes to the C++ SDK regarding OCIO code examples. Only the extended C++ SDK contains these changes. The application provided sdk.zip will catch up with the next release of Cinema 4D.

      Happy rendering and coding,
      the Maxon SDK Team

      ℹ Cloudflare unfortunately still does interfere with our server cache. And you might have to refresh your cache manually.

      When you are not automatically redirected to the new versions, and also do not see 2024.5 in the version selector, please press CTRL + F5 or press CTRL and click on the reload icon of your browser anywhere on developers.maxon.net/docs/ to refresh your cache. You only have to do this once and it will apply to all documentations at once. Otherwise your cache will automatically update latest by 19/07/2024 00:00.

      posted in News & Information cinema 4d news c++ python sdk
      ferdinandF
      ferdinand
    • RE: Object materials won't show up in final render

      Hi,

      you use GetActiveDocument() in a NodeData environment. You cannot do this, since nodes are also executed when their document is not the active document (while rendering for example - documents get cloned for rendering).

      Cheers
      zipit

      posted in Cinema 4D SDK
      ferdinandF
      ferdinand
    • 2025.3.0 SDK Release

      Dear development community,

      On June the 18th, 2025, Maxon Computer released Cinema 4D 2025.3.0. For an overview of the new features of Cinema 4D 2025.3.0, please refer to the 2025.3.0 release notes. Alongside this release, a new Cinema 4D SDK and SDK documentation have been released, reflecting the API changes for 2025.3.0. The major changes are:

      C++ API

      • After the introduction of the CMake build system generator in Cinema 4D 2025.2.0, the C++ SDK now only supports CMake as its build system generator. The Legacy Build System is no longer supported. When you have not yet switched to CMake, please refer to our Build Systems manual for more information on how to switch to CMake.
      • Updated the required Windows SDK version to Windows 10 SDK 10.0.20348.0. You might have to update Visual Studio and install the SDK via the Visual Studio installer app.

      Python API

      ⚠ In 2025.3.0, there is a critical issue with c4dpy that will cause it to halt indefinitely when run for the first time. See the c4dpy manual for an explanation and workaround. This issue will be fixed with a hotfix for 2025.3.0.

      • Added features to c4d.documents.BatchRender class, to have more control over render settings, cameras, and takes for a given job.
      • Added a suite of new code examples around the subject of dialogs, including both simple beginner examples, as well as more complex examples covering subjects such as dynamic GUIs, value and layout persistence, and using resources to define dialogs and string translations. The new examples all begin with the prefix py-cmd_gui_, see our plugin examples overview for details.

      Head to our download section to grab the newest SDK downloads, or read the C++ or Python API change notes for an in detail overview of the changes.

      Happy rendering and coding,
      the Maxon SDK Team

      ℹ Cloudflare unfortunately still does interfere with our server cache. You might have to refresh your cache manually to see new data when you read this posting within 24 hours of its release.

      posted in News & Information news cinema 4d c++ python sdk information
      ferdinandF
      ferdinand

    Latest posts made by ferdinand

    • RE: The value of 'porgress' during the use of RenderDocument() is greater than 1.0

      I have moved this into bugs.

      posted in Bugs
      ferdinandF
      ferdinand
    • RE: The value of 'porgress' during the use of RenderDocument() is greater than 1.0

      Hey @chuanzhen,

      So, first of all, please excuse the delay. And thank you for the exemplary problem description, I almost booked this under "cannot reproduce" but you really hit the nail on the head with the conditions.

      There is currently a bug in how the viewport renderer handles sending data to the progress hook. But this only happens when rendering a document from another frame than its starting frame. I am not yet 100% certain, but I am pretty sure this is a bug in the progress hook itself and not the viewport renderer. So, the bug could also appear in other contexts where a specific function of the progress hook is used. But so far the viewport renderer is the only renderer with which I could reproduce this.

      There is not really anything you can do as a user, because there is a concrete bug. But the viewport renderer calls the progress hook twice each frame: Once with the correct progress, and once with a progress that is shifted by renderFrameRange/documentFrameRange percent. With some internal code knowledge we can simply say by the call index if the given progress is correct or not. But please understand that this is very much a hack.

      I will probably fix this, but I cannot fix this retroactively in 2025. This workaround could be useful for you but it is also a bit risky.

      I have moved this into bugs.

      Cheers,
      Ferdinand

      """Provides a workaround to get correct progress values when rendering a document with the viewport 
      renderer.
      
      This workaround is specific to the case of this thread (viewport renderer + start frame other than
      the first frame). I know what causes the bug, but I am not yet sure if it is the viewport renderer
      which feeds the thing with wrong data, or of the thing itself is buggy.
      
      THIS IS A HACK USE AT YOUR OWN RISK! DO NOT REMOVE THIS WARNING.
      
      See: https://developers.maxon.net/forum/topic/16341
      """
      import c4d
      import mxutils
      
      doc: c4d.documents.BaseDocument
      
      # What basically happens for the preview renderer, is that it calls the progress hook twice for each
      # frame. The second call happens just two lines after the first call. Each first call provides 
      # "correct" data, while the second does not. However, the first call is only made when RDATA_FASTAFX
      # is set to false in the render data (is the case by default). The workaround is then simply to build
      # history data so that we can know if the current call is an even (correct) or odd (incorrect) call.
      PROGRESS_STACK: list[float] = []
      
      def PythonCallBack(progress, progress_type):
          """
          """
          # Just some stuff I used for debugging which only works in 2026 and above.
          # symbol: str = mxutils.g_c4d_symbol_translation_cache.Get(progress_type, "RENDERPROGRESSTYPE_")[0]
          # with open("/Users/f_hoppe/Documents/temp/render_progress.txt", "a") as f:
          #     f.write(f"{symbol}: {progress:.2f}%\n")
      
          PROGRESS_STACK.append(progress)
          if len(PROGRESS_STACK) % 2 == 0:
              # Even call: correct data
              print(f"Render Progress: {progress:.2f}%")
          else:
              # Odd call: incorrect data, ignore, this is the same context as the previous one.
              pass
      
      def main() -> None:
          """
          """
          # c4d.ClearPythonConsole()
      
          rd = doc.GetActiveRenderData()
          rd[c4d.RDATA_FASTAFX] = False # REALLY make sure that RDATA_FASTAFX is disabled
      
          bmp = c4d.bitmaps.MultipassBitmap(int(rd[c4d.RDATA_XRES]), int(rd[c4d.RDATA_YRES]), c4d.COLORMODE_RGB)
          if bmp is None:
              raise RuntimeError("Failed to create the bitmap.")
      
          bmp.AddChannel(True, True)
          if c4d.documents.RenderDocument(doc, rd.GetDataInstance(), bmp, c4d.RENDERFLAGS_EXTERNAL, prog=PythonCallBack,
                                      ) != c4d.RENDERRESULT_OK:
              raise RuntimeError("Failed to render the temporary document.")
      
      if __name__ == "__main__":
          main()
      
      posted in Bugs
      ferdinandF
      ferdinand
    • RE: Python tag or Python node in Xpresso crash Cinema 4D

      Hey @SmetK,

      so I am back, and I have good and bad news 🙂

      The bad news is that I could not reproduce the crash with your scene on my Win machine with 2026_0_0_db12fb68d6ba_2004155263. I today also asked the users in our beta forum, and multiple users could not reproduce it either.

      The "good" news is that without me noticing, in the last days a similar crash report (it terminates into the exact same lines as yours) has been attached to the issue I created for your crash. This crash came from a Korean user on macOS and with this users scene I could reproduce your crash (I just got the same exact stack trace). The Korean user does not have any Python in his/her scene, just some Boolean setup not unsimilar to yours.

      I have grouped everything and added some comments in your ticket, and will in moment briefly talk with the Boolean developer. Python might be here a component in your case (which so far no one go to crash), but there seems to be a base case which happens independently of Python. Which makes sense given how harmless your code is.

      When you want to follow this case, I would recommend reaching out to end user support, feel free to mention the ticket ITEM#623378 [Python] Booleans crash when building output. When there is a fundamental development which impacts API users, I will post it here for all developers to see, but we should not let end user issues bleed into developer issues.

      So, I do not have a super satisfying answer, but we can at least reproduce this, which increases the chances of this being fixed.

      Cheers,
      Ferdinand

      posted in Cinema 4D SDK
      ferdinandF
      ferdinand
    • RE: The value of 'porgress' during the use of RenderDocument() is greater than 1.0

      FYI: I have not forgotten you. Will get to your topic tomorrow, hopefully 🙂

      posted in Bugs
      ferdinandF
      ferdinand
    • RE: Several Asset Browser Issues

      Hey Ben,

      Thank your for your reply. It always pains me a bit to be that upfront when a user has clearly put effort into a problem description. But it is very hard to follow your description and videos when looking at it from a developers standpoint, what to pinpoint and/or fix a bug.

      Please follow our support procedures regarding reporting bugs and crashes. When need a written step by step instruction, scene files (or in your case a zip database), and what you consider wrong. I would recommend to:

      • Prune all stuff that is not directly relevant to the crash or bug. When you create a zip database from one of our built-in assets, you can just share the zip and say "this is toony-123" as zip database to demonstrate my problem.
      • Then either provide reproduction steps (in which case this would be an end user issue) or the code which triggers the issue and describe in text what leads up to your problem and equally important, what you consider wrong about the outcome.

      But I watched your two videos, and read your posting and got a sense of what you are doing. A few points:

      • The toon rig uses some dark magic Python code (event notifications, something you better keep away from), where I would not be too surprised if they break. And just for clarity: The Toon rig is not part of the SDK or owned by the SDK. That does not mean we won't help you, but I cannot fix the toon rig for you, that would have to be done by the animation team.
      • On some level this does also seem to involve exchange topics, i.e., File IO when you import things.
      • The toon rig might need an extra nudge in your script to attach its event handlers or something like that. But I can only evaluate this once I have a file/database to work on and a script to run.

      Cheers,
      Ferdinand

      posted in Cinema 4D SDK
      ferdinandF
      ferdinand
    • RE: Usage of SplineHelp.InitSplineWith() regarding flags -> returned data

      Hey @mogh,

      Yes, a new topic would be better if we move on to debugging your plugin. But I'll briefly answer here.

      1. That the comb curve flips between 'above' and 'below' is normal and exactly what I talked about before with mathematical vs 'what artists want' tangents. I once spend here some time on explaining this.
      2. The problem with your screens is a bit that you do not explain what you would consider incorrect. I assume that you understand why the flipping happens and are okay with it and are concerned about the jaggedness of your combs? Without debugging your code this is very hard to evaluate.

      C4D can not get more precise than a 0° degree line object ?

      Splines are what is often called smooth geometry, i.e., a parametric curve that is mathematically defined and has infinite precision (you can think of it as infinite points). This is opposed by discrete geometry such as a LineObject which has a finite set of data points. The interpolation settings of a spline are the parameters with which the smooth form ('the spline') is brought into a discrete representation ('the line object') for display and other purposes. So, asking if Cinema 4D could discretize with 0° (or less) does not make too much sense, since discretization with 0° means infinite precision, i.e., the smooth form. For practical purposes, 0.1° should be more than enough. And that is probably already more than order of precision more than you actually need, as humans cannot see that level of detail.

      When you do not want to only control the discretization over the angle of change (a.k.a. curvature), but also over the distance of points, you can also set a maximum length for the segments. For that you must change the spline interpolation from 'Adaptive' to 'Subdivided'. This way, you can ensure that even in straight areas, the segments do not become too long.

      But the general problem is probably that you do not normalize your data. It makes a difference if the last point is 10 units away from the second last or 1000 units. To approximate the mean curvature between two vertices in some discrete geometry, the formula shown below exists; which is a hack compared to more fancy approaches such as this one. It will approximate the mean curvature between two vertices p and q with the normals np and nq:

              (nq - np) * (q - p)
        c_i = -------------------
                   |q - p|
      

      For a mesh vertex you do this with all neighboring vertices and average the result. My guess would be that you are missing this exact normalization step (/|q - p|, i.e., the value divided by the Euclidean distance between the two points) in your comb calculation. Because curvature is inherently a smooth property, the 'neighbor' of a point in a smooth curve/geometry is always exactly 1/infinity units away. So, you need to ensure that the influence of a neighbor vertex in the discrete world is weighted by its distance to the current vertex.

      For splines you would probably have to do this for the left and right tangent of each vertex and then take the mean value. But curvature discretization is like all computational geometry subjects not super trivial, and there might be extra/expert steps required for splines I am not aware of right now.

      Hope this helps,
      Ferdinand

      Here is a script I wrote a long time ago where I used that 'formula' to approximate the mean curvature for a mesh. This is non-public code, so it has no comments except for me pointing out the formula.

      """Computes the mean curvature of the selected mesh and stores it in a vertex map.
      """
      
      import c4d
      
      
      def GetNormal(pid, points, polygons, neighbor):
          """
          """
          connected = neighbor.GetPointPolys(pid)
          vertexNormals = []
      
          for cpoly in [polygons[pid] for pid in connected]:
              if pid == cpoly.a:
                  o, p, q = points[cpoly.d], points[cpoly.a], points[cpoly.b]
              elif pid == cpoly.b:
                  o, p, q = points[cpoly.a], points[cpoly.b], points[cpoly.c]
              elif pid == cpoly.c and cpoly.IsTriangle():
                  o, p, q = points[cpoly.b], points[cpoly.c], points[cpoly.a]
              elif pid == cpoly.c and not cpoly.IsTriangle():
                  o, p, q = points[cpoly.b], points[cpoly.c], points[cpoly.d]
              elif pid == cpoly.d:
                  o, p, q = points[cpoly.c], points[cpoly.d], points[cpoly.a]
              vNormal = ~((o-p) % (q-p))
              vertexNormals.append(vNormal)
          factor = 1./len(vertexNormals)
          return ~(sum(vertexNormals) * factor)
      
      
      def GetCurvature(node):
          """
          """
          neighbor = c4d.utils.Neighbor()
          neighbor.Init(node)
          points = node.GetAllPoints()
          polygons = node.GetAllPolygons()
      
          def getNeighborVertices(pid):
      
              ids = [pid]
              for i in neighbor.GetPointPolys(pid):
                  cpoly = polygons[i]
                  pnts = [cpoly.a, cpoly.b, cpoly.c]
                  if not cpoly.IsTriangle():
                      pnts.append(cpoly.d)
      
                  fi = cpoly.Find(pid)
                  cnt = len(pnts) - 1
      
                  prev = pnts[fi - 1] if fi > 0 else pnts[-1]
                  nxt = pnts[fi + 1] if fi < cnt else pnts[0]
                  if prev not in ids:
                      ids.append(prev)
                  if nxt not in ids:
                      ids.append(nxt)
              for i in ids[1:]:
                  yield i, points[i]
      
          data = []
          for ip, p in enumerate(points):
              np = GetNormal(ip, points, polygons, neighbor)
              temp = []
              for iq, q in getNeighborVertices(ip):
                  nq = GetNormal(iq, points, polygons, neighbor)
                  # This is just a very cheap
                  #
                  #        (nq - np) * (q - p)
                  #  c_i = -------------------
                  #             |q - p|
                  #             
                  temp.append((nq - np) * (q - p) / (q - p).GetLength())
              c = sum(temp) * (1. / len(temp)) * .5 + .5
              data.append(c)
      
          neighbor.Flush()
          return data
      
      def CreateVertexMap(node, data):
          """
          """
          tag = c4d.VariableTag(c4d.Tvertexmap, len(data))
          tag.SetAllHighlevelData(data)
          tag.SetBit(c4d.BIT_ACTIVE)
          node.InsertTag(tag)
          c4d.EventAdd()
      
      def main():
          """
          """
          data = GetCurvature(op)
          CreateVertexMap(op, data)
      
      if __name__ == '__main__':
          main()
      
      posted in Cinema 4D SDK
      ferdinandF
      ferdinand
    • RE: Usage of SplineHelp.InitSplineWith() regarding flags -> returned data

      Hey @mogh,

      Thank you for reaching out to us. I agree that it is a bit unclear, but the TLDR is that this is just a minor niche feature. I first thought it would be a way to treat a spline as a close splined, with the description a bit weirdly put, but that is not the case. There is only once place where this flag is used, and it is here:

      cf94c215-834c-406e-b398-eda5e49e79ea-image.png

      I.e., it seems to try to continue the curvature of the last segment. How this works in detail and how sensible this is, I cannot really tell you either. From the code we can see here, it seems to try to parallel transport the last tangent. But there is also something else going on, as it not only takes the last point but the point before that into account (i - 2). It then uses the tangent of m2 * (~m1 * m2), which is also super hand-wavy for me. It basically takes the orientation of the last tangent twice but for A * B, makes B relative to the second last tangent (m1). Or a bit incorrect but more readable: 'It takes the orientation of the last point twice, but also undoes the orientation of the second last point.'

      How this is relevant I have absolutely no idea, probably some MoGraph related 'custom logic'. My advice: Leave it as its default and otherwise ignore it.

      As a warning: All the spline helpers implement parallel transport, which can make their output for curvature tasks undesirable (as it messes with what is the mathematical tangent of a spline in favour of what humans would expect. When you are at a loss about what I am talking about, search the forum for parallel transport and my username, the topic has come up multiple times in the past). It might be better to get the LineObject of a spline, i.e., its current discrete form, and do all the math based on its vertices.

      Cheers,
      Ferdinand

      posted in Cinema 4D SDK
      ferdinandF
      ferdinand
    • RE: Python tag or Python node in Xpresso crash Cinema 4D

      Hey @SmetK,

      Thank you for the added information; that is really helpful! I unfortunately did not find the time to try this again on Windows, but I'll try next week if I can reproduce your crash. But I am a bit doubtful that jumping from my late-late beta version to the customer RC will make any difference. I will post here an update when I found anything out.

      There exists already a ticket for the crash report I uploaded for you, I will add your explanations there. But I have two questions:

      • May I upload your example file into the ticket?
      • May I share your file in our beta community, to see if anyone else can reproduce the crash?

      Cheers,
      Ferdinand

      posted in Cinema 4D SDK
      ferdinandF
      ferdinand
    • RE: Ctr+drag copy vs internal copy in CopyTo function in C++

      Hey @aghiad322,

      Thank you for your code. It is still very unclear to me what you are doing on a higher more abstract level, and on a concrete level, where exactly you want to detect something. Find below your commented code and at the end a few shots into the dark from me regarding what you are trying to do.

      I also just saw now that you posted in the wrong forum. I moved your topic and marked it as C++ and 2025 since you said you are not using the 2026 SDK.

      I hope this help and cheers,
      Ferdinand

      // I wrote this blind without compiling it. So ,there might be some syntax issues in the code I wrote,
      // but it should still illustrate the concepts well enough.
      
      #include "maxon/weakrawptr.h"
      
      using namespace cinema;
      using namespace maxon;
      
      struct NexusMember
      {
          // While we could consider a pointer somewhat conceptually a weak reference, it is factually 
          // not one, as the pointed object being deleted does not invalidate the pointer. This can lead 
          // to dangling pointers and access violation crashes.
          BaseObject* object = nullptr; // weak ref, don’t own it
          Bool isChild = false;         // "include children" flag
      
          // This is better.
          WeakRawPtr<BaseTag> _tagWeakPtr;
      
          // Gets the tag pointed to by this member, or nullptr if it has been deleted.
          BaseTag* GetTag() const
          {
              return _tagWeakPtr.Get();
          }
      
          // Sets the tag for this member.
          void Set(const BaseTag* tag)
          {
              _tagWeakPtr = _tagWeakPtr.Set(tag);
          }
      };
      
      struct NexusGroup
      {
          Vector color;
      
          // No, do not use the std library. Cinema 4D modules are by default compiled without exception 
          // handling for performance reasons, and the standard library uses exceptions for error handling,
          // making its behavior undefined in such builds. std::vector::push_back() can throw 
          // std::bad_alloc, for example.
      
          std::vector<String> links;
          std::vector<NexusMember> members;
          Int32 dirtyLevel = 0;
      
          // MUST be:
          BaseArray<String> links;
          BaseArray<NexusMember> members;
      };
      
      class NexusRegistry : public SceneHookData
      {
      public:
          static NexusRegistry* Get(BaseDocument* doc);
          static NodeData* Alloc();
          virtual Bool Message(GeListNode* node, Int32 type, void* data);
          virtual EXECUTIONRESULT Execute(BaseSceneHook* node, BaseDocument* doc,
                                          BaseThread* bt, Int32 priority, EXECUTIONFLAGS flags);
         
          // The same applies here, the Maxon API alternatives to unordered_map are:
          //
          //   * HashSet (just a hash set of fixed type values without keys)
          //   * HashMap(a hash map of fixed key and value type),
          //   * DataDictionary (a hash map of arbitrary key and value types).
      
          std::unordered_map<Int32, NexusGroup> groups;
          maxon::BaseArray<BaseTag*> pendingRegistration;
      
          void ProcessPendingTags(BaseDocument* doc);
          void RebuildRegistry(BaseDocument* doc);
          void UpdateGroupFromTag(BaseDocument* doc, BaseTag* tag);
          void RemoveObjectFromGroups(BaseObject* obj);
          void RemoveTagFromGroup(BaseTag* tag);
          const NexusGroup* GetGroup(Int32 hash) const;
      };
      
      // -------------------------------------------------------------------------------------------------
      
      void NexusRegistry::UpdateGroupFromTag(BaseDocument* doc, BaseTag* tag)
      {
          if (!tag) return;
          BaseObject* obj = tag->GetObject();
          if (!obj) return;
          BaseContainer* tagContainer = tag->GetDataInstance();
      
          String id = tagContainer->GetString(ID);
      
          // I do not know of which nature this HashID is, but our API has multiple hash functions. 
          Int32 hashedID = HashID(id);
          
          // There is for once StringTemplate::GetHashCode(). I.e., you could do this:
          const HashInt = id.GetHashCode();
      
          // But all scene elements already have a marker on them which uniquely identifies them (if that
          // is what you are after).
      
          // Uniquely identifies over its time of creation and the machine it was created on. I.e., this
          // value is persistent across sessions and unique across machines.
          const GeMarker uuid = tag->GetMarker();
      
          Bool includeChildren = tagContainer->GetBool(CHILDREN);
      
          Int32 oldIdHash = tagContainer->GetInt32(NEXUS_TAG_PREV_ID, NOTOK);
          if (oldIdHash != NOTOK && oldIdHash != hashedID)
          {
              auto it = groups.find(oldIdHash);
              if (it != groups.end())
              {
                  auto& members = it->second.members;
                  // std::vector::erase is not noexcept, this can crash Cinema 4D, unless you compile your
                  // module with exception handling enabled (which we do not recommend for performance
                  // reasons). I am not going to repeat this comment in similar places below.
                  members.erase(std::remove_if(members.begin(), members.end(),
                      [obj](const NexusMember& m) { return m.object == obj; }),
                      members.end());
      
                  it->second.dirtyLevel++;
                  if ((Int32)members.size() == 0)
                      groups.erase(it);
              }
          }
      
          // Update new group
          NexusGroup& group = groups[hashedID];
      
          // Remove duplicates of this object first
          group.members.erase(std::remove_if(group.members.begin(), group.members.end(),
              [obj](const NexusMember& m) { return m.object == obj; }),
              group.members.end());
      
          group.members.push_back({ obj, includeChildren });
      
          ((Nexus*)tag)->UpdateInfo(doc, tag);
      
          // Store current ID for next update
          tagContainer->SetInt32(NEXUS_TAG_PREV_ID, hashedID);
      }
      
      // -------------------------------------------------------------------------------------------------
      
      
      void NexusRegistry::ProcessPendingTags(BaseDocument* doc)
      {
          if (pendingRegistration.IsEmpty())
              return;
      
          Int32 i = 0;
          while (i < pendingRegistration.GetCount())
          {
              BaseTag* tag = pendingRegistration[i];
              BaseObject* op = tag->GetObject();
      
              if (op)
              {
                  UpdateGroupFromTag(doc, tag);
      
                  // This is not how our error system works. Functions of type Result<T> are our exception
                  // handling equivalent. You need iferr statements to catch and/or propagate errors. See
                  // code below.
                  maxon::ResultRef eraseresult = pendingRegistration.Erase(i, 1);
              }
              else
              {
                  i++;
              }
          }
      }
      
      // -------------------------------------------------------------------------------------------------
      
      // See https://developers.maxon.net/docs/cpp/2026_0_0/page_maxonapi_error_overview.html for a more in detail
      // explanation of our error handling system.
      
      // So we have some class with a field whose type has a function of return type Result<T>, e.g., your
      // NexusRegistry. We have now three ways to handle errors when calling such functions:
      
      // Ignoring errors (not recommended):
      void NexusRegistry::AddItem(const String name)
      {
          links.Append(name) iferr_ignore("I do not care about errors here."); // Append is of type Result<void>
      }
      
      // Handling errors locally, i.e., within a function that itself is not of type Result<T>.
      Bool NexusRegistry::RemoveItem(const String name)
      {
          // The scope handler for this function so that we can terminate errors when the are thrown.
          iferr_scope_handler
          {
              // Optional, print some debug output to the console, #err is the error object.
              DiagnosticOutput("Error in @: @", MAXON_FUNCTIONNAME, err);
      
              // We just return false to indicate failure. If we would have to do cleanup/unwinding, we
              // would do it here.
              return false;
          };
      
          const Int32 i = links.FindIndex(name);
      
          // We call our Result<T> function and propagate any error to the scope handler if an error 
          // occurs. The iferr_return keyword basically unpacks a Result<T> into its T value, or jumps 
          // to the error handler in the current or higher scope and propagates the error.
          const String item = links.Erase(i) iferr_return;
          
          return true;
      }
      
      // And the same thing in green but we propagate errors further up the call chain, i.e., our function
      // is itself of type Result<T>. It now also does not make too much sense to return a Bool, so our 
      // return type is now Result<void>.
      Result<void> NexusRegistry::RemoveItem(const String name)
      {
          // Here we just use the default handler which will just return the #err object to the caller.
          iferr_scope;
      
          const Int32 i = links.FindIndex(name);
          const String item = links.Erase(i) iferr_return;
      
          return OK; // Result<void> functions return OK on success.
      }
      
      // -------------------------------------------------------------------------------------------------
      
      
      EXECUTIONRESULT NexusRegistry::Execute(BaseSceneHook* node, BaseDocument* doc,
                                             BaseThread* bt, Int32 priority, EXECUTIONFLAGS flags)
      {
          ProcessPendingTags(doc);
          return EXECUTIONRESULT::OK;
      }
      
      
      // -------------------------------------------------------------------------------------------------
      
      // So, all in all, this does not shed too much light on what you are doing for me :) The main questions 
      // is if you implement your tags yourself, i.e., the items stored in your NexusGroup::members.
      
      // When you implement a node yourself, you can override its ::Read, ::Write, and ::CopyTo functions
      // to handle the node serialization and copying yourself. See https://tinyurl.com/2v4ajn58 for a
      // modern example for that. So for your, let's call it NexusTag, you would do something like this:
      class NexusTag : public TagData
      {
          Bool CopyTo(NodeData* dest, const GeListNode* snode, GeListNode* dnode, COPYFLAGS flags, 
                      AliasTrans* trn) const
          {
              // This is a copy and paste event. There is no dedicated event for CTRL + DRAG you seem
              // to after.
              if (flags & PRIVATE_CLIPBOARD_COPY)
              {
                  // Do something special with the destination node #dnode or call home to you registry.
              }
              else
              {
                  // Do something different.
              }
      
              // We should always call the base class implementation, unless we want interrupt the copy.
              return SUPER::CopyTo(dest, snode, dnode, flags, trn);
          }
      };
      
      // ---
      
      // Another way could using a MessageData hook and monitoring the EVMSG_CHANGE events, i.e., when
      // something in a scene changed. This is usually how render engines synchronize scene graphs. I am
      // not going to exemplify this here, as this is a lot of work.But you can have a look at this thread
      // which is the most simple example we have for this (in Python, but is more or less the same in C++):
      // https://developers.maxon.net/forum/topic/14124/how-to-detect-a-new-light-and-pram-change
      
      // Here you do not have to own the tag implementation. But you could not detect how something has
      // been inserted, only that it has been inserted.
      
      // ---
      
      // Yet another thing which could help are event notifications. I.e., you hook yourself into the copy
      // event of any node (you do not have to own the node implementation for this) and get notified when
      // a copy occurs. But event notifications are private for a reason, as you can easily crash Cinema
      // with them. You will find some material on the forum, but they are intentionally not documented.
      
      // https://tinyurl.com/2jj8xa6s
      
      // ---
      
      // Finally, with NodeData::Init you can also react in your node to it being cloned.
      Bool NexusTag::Init(GeListNode* node, Bool isCloneInit)
      {
          if (isCloneInit)
          {
              // Do something special when this is a clone operation.
          }
      
          return true;
      }
      
      posted in Cinema 4D SDK
      ferdinandF
      ferdinand
    • RE: The value of 'porgress' during the use of RenderDocument() is greater than 1.0

      Hey @chuanzhen,

      Thank you for reaching out to us. I will have a look at this problem, at the latest by the end of next week (31/10). We are aware that RendeDocument keeps regressing, because there are a lot of render technology changes happening behind the scenes in the Cinema in the last releases.

      Hopefully, this is just a smaller bug, or a user error. But this could also be a more complicated thing. I will let you know at the latest by the end of next week.

      Cheers,
      Ferdinand

      posted in Bugs
      ferdinandF
      ferdinand