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
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
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:
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.")
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
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.
raycast_texture.c4d : The scene file.
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()
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
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
Hi,
as @Cairyn said the problem is unreachable code. I also just saw now that you did assign the same ID to all your buttons in your CreateLayout()
. Ressource and dialog element IDs should be unique. I would generally recommend to define your dialogs using a resource, but here is an example on how to do it in code.
BUTTON_BASE_ID = 1000
BUTTON_NAMES = ["Button1", "Button2", "Button3", "Button4", "Button5"]
BUTTON_DATA = {BUTTON_BASE_ID + i: name for i, name in enumerate(BUTTON_NAMES)}
class MyDialog(gui.GeDialog):
def CreateLayout(self):
"""
"""
self.GroupBegin(id=1013, flags=c4d.BFH_SCALEFIT, cols=5, rows=4)
for element_id, element_name in BUTTON_DATA.items():
self.AddButton(element_id, c4d.BFV_MASK, initw=100,
name=element_name)
self.GroupEnd()
return True
def Command(self, id, msg):
"""
"""
if id == BUTTON_BASE_ID:
print "First button has been clicked"
elif id == BUTTON_BASE_ID + 1:
print "Second button has been clicked"
# ...
if id in BUTTON_DATA.keys(): # or just if id in BUTTON_DATA
self.Close()
return True
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:
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.c4d
package remains the home for all formerly Classic and now Cinema API entities.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 pressCTRL
and click on the reload icon of your browser anywhere ondevelopers.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.
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
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
Hi,
you have to invoke AddUserArea
and then attach an instance of your implemented type to it. Something like this:
my_user_area = MyUserAreaType()
self.AddUserArea(1000,*other_arguments)
self.AttachUserArea(my_user_area, 1000)
I have attached an example which does some things you are trying to do (rows of things, highlighting stuff, etc.). The gadget is meant to display a list of boolean values and the code is over five years old. I had a rather funny idea of what good Python should look like then and my attempts of documentation were also rather questionable. I just wrapped the gadget into a quick example dialog you could run as a script. I did not maintain the code, so there might be newer and better ways to do things now.
Also a warning: GUI stuff is usually a lot of work and very little reward IMHO.
Cheers
zipit
import c4d
import math
import random
from c4d import gui
# Pattern Gadget
IDC_SELECTLOOP_CELLSIZE = [32, 32]
IDC_SELECTLOOP_GADGET_MINW = 400
IDC_SELECTLOOP_GADGET_MINH = 32
class ExampleDialog(gui.GeDialog):
"""
"""
def CreateLayout(self):
"""
"""
self.Pattern = c4d.BaseContainer()
for i in range(10):
self.Pattern[i] = random.choice([True, False])
self.PatternSize = len(self.Pattern)
self.gadget = Patterngadget(host=self)
self.AddUserArea(1000, c4d.BFH_FIT, 400, 32)
self.AttachUserArea(self.gadget, 1000)
return True
class Patterngadget(gui.GeUserArea):
"""
A gui gadget to modify and display boolean patterns.
"""
def __init__(self, host):
"""
:param host: The hosting BaseToolData instance
"""
self.Host = host
self.BorderWidth = None
self.CellPerColumn = None
self.CellWidht = IDC_SELECTLOOP_CELLSIZE[0]
self.CellHeight = IDC_SELECTLOOP_CELLSIZE[1]
self.Columns = None
self.Height = None
self.Width = None
self.MinHeight = IDC_SELECTLOOP_GADGET_MINH
self.MinWidht = IDC_SELECTLOOP_GADGET_MINW
self.MouseX = None
self.MouseY = None
"""------------------------------------------------------------------------
Overridden methods
--------------------------------------------------------------------"""
def Init(self):
"""
Init the gadget.
:return : Bool
"""
self._get_colors()
return True
def GetMinSize(self):
"""
Resize the gadget
:return : int, int
"""
return int(self.MinWidht), int(self.MinHeight)
def Sized(self, w, h):
"""
Get the gadgets height and width
"""
self.Height, self.Width = int(h), int(w)
self._fit_gadget()
def Message(self, msg, result):
"""
Fetch and store mouse over events
:return : bool
"""
if msg.GetId() == c4d.BFM_GETCURSORINFO:
base = self.Local2Screen()
if base:
self.MouseX = msg.GetLong(c4d.BFM_DRAG_SCREENX) - base['x']
self.MouseY = msg.GetLong(c4d.BFM_DRAG_SCREENY) - base['y']
self.Redraw()
self.SetTimer(1000)
return gui.GeUserArea.Message(self, msg, result)
def InputEvent(self, msg):
"""
Fetch and store mouse clicks
:return : bool
"""
if not isinstance(msg, c4d.BaseContainer):
return True
if msg.GetLong(c4d.BFM_INPUT_DEVICE) == c4d.BFM_INPUT_MOUSE:
if msg.GetLong(c4d.BFM_INPUT_CHANNEL) == c4d.BFM_INPUT_MOUSELEFT:
base = self.Local2Global()
if base:
x = msg.GetLong(c4d.BFM_INPUT_X) - base['x']
y = msg.GetLong(c4d.BFM_INPUT_Y) - base['y']
pid = self._get_id(x, y)
if pid <= self.Host.PatternSize:
self.Host.Pattern[pid] = not self.Host.Pattern[pid]
self.Redraw()
return True
def Timer(self, msg):
"""
Timer loop to catch OnMouseExit
"""
base = self.Local2Global()
bc = c4d.BaseContainer()
res = gui.GetInputState(c4d.BFM_INPUT_MOUSE,
c4d.BFM_INPUT_MOUSELEFT, bc)
mx = bc.GetLong(c4d.BFM_INPUT_X) - base['x']
my = bc.GetLong(c4d.BFM_INPUT_Y) - base['y']
if res:
if not (mx >= 0 and mx <= self.Width and
my >= 0 and my <= self.Height):
self.SetTimer(0)
self.Redraw()
def DrawMsg(self, x1, y1, x2, y2, msg):
"""
Draws the gadget
"""
# double buffering
self.OffScreenOn(x1, y1, x2, y2)
# background & border
self.DrawSetPen(self.ColBackground)
self.DrawRectangle(x1, y1, x2, y2)
if self.BorderWidth:
self.DrawBorder(c4d.BORDER_THIN_IN, x1, y1,
self.BorderWidth + 2, y2 - 1)
# draw pattern
for pid, state in self.Host.Pattern:
x, y = self._get_rect(pid)
self._draw_cell(x, y, state, self._is_focus(x, y))
"""------------------------------------------------------------------------
Public methods
--------------------------------------------------------------------"""
def Update(self, cid=None):
"""
Update the gadget.
:param cid: A pattern id to toggle.
"""
if cid and cid < self.Host.PatternSize:
self.Host.Pattern[cid] = not self.Host.Pattern[cid]
self._fit_gadget()
self.Redraw()
"""------------------------------------------------------------------------
Private methods
--------------------------------------------------------------------"""
def _get_colors(self, force=False):
"""
Set the drawing colors.
:return : Bool
"""
self.ColScale = 1.0 / 255.0
if self.IsEnabled() or force:
self.ColBackground = self._get_color_vector(c4d.COLOR_BG)
self.ColCellActive = c4d.GetViewColor(
c4d.VIEWCOLOR_ACTIVEPOINT) * 0.9
self.ColCellFocus = self._get_color_vector(c4d.COLOR_BGFOCUS)
self.ColCellInactive = self._get_color_vector(c4d.COLOR_BGEDIT)
self.ColEdgeDark = self._get_color_vector(c4d.COLOR_EDGEDK)
self.ColEdgeLight = self._get_color_vector(c4d.COLOR_EDGELT)
else:
self.ColBackground = self._get_color_vector(c4d.COLOR_BG)
self.ColCellActive = self._get_color_vector(c4d.COLOR_BG)
self.ColCellFocus = self._get_color_vector(c4d.COLOR_BG)
self.ColCellInactive = self._get_color_vector(c4d.COLOR_BG)
self.ColEdgeDark = self._get_color_vector(c4d.COLOR_EDGEDK)
self.ColEdgeLight = self._get_color_vector(c4d.COLOR_EDGELT)
return True
def _get_cell_pen(self, state, _is_focus):
"""
Get the color for cell depending on its state.
:param state : The state
:param _is_focus : If the cell is hoovered.
:return : c4d.Vector()
"""
if state:
pen = self.ColCellActive
else:
pen = self.ColCellInactive
if self.IsEnabled() and _is_focus:
return (pen + c4d.Vector(2)) * 1/3
else:
return pen
def _draw_cell(self, x, y, state, _is_focus):
"""
Draws a gadget cell.
:param x: local x
:param y: local y
:param state: On/Off
:param _is_focus: MouseOver state
"""
# left and top bright border
self.DrawSetPen(self.ColEdgeLight)
self.DrawLine(x, y, x + self.CellWidht, y)
self.DrawLine(x, y, x, y + self.CellHeight)
# bottom and right dark border
self.DrawSetPen(self.ColEdgeDark)
self.DrawLine(x, y + self.CellHeight - 1, x +
self.CellWidht - 1, y + self.CellHeight - 1)
self.DrawLine(x + self.CellWidht - 1, y, x +
self.CellWidht - 1, y + self.CellHeight - 1)
# cell content
self.DrawSetPen(self._get_cell_pen(state, _is_focus))
self.DrawRectangle(x + 1, y + 1, x + self.CellWidht -
2, y + self.CellHeight - 2)
def _get_rect(self, pid, offset=1):
"""
Get the drawing rect for an array id.
:param pid : the pattern id
:param offset : the pixel border offset
:return : int, int
"""
pid = int(pid)
col = pid / self.CellPerColumn
head = pid % self.CellPerColumn
return self.CellWidht * head + offset, self.CellHeight * col + offset
def _get_id(self, x, y):
"""
Get the array id for a coord within the gadget.
:param x : local x
:param y : local y
:return : int
"""
col = (y - 1) / self.CellHeight
head = (x - 1) / self.CellWidht
return col * self.CellPerColumn + head
def _is_focus(self, x, y):
"""
Test if the cell coords are under the cursor.
:param x : local x
:param y : local y
:return : bool
"""
if (self.MouseX >= x and self.MouseX <= x + self.CellWidht and
self.MouseY >= y and self.MouseY <= y + self.CellHeight):
self.MouseX = c4d.NOTOK
self.MouseY = c4d.NOTOK
return True
else:
return False
def _fit_gadget(self):
"""
Fit the gadget size to the the array
"""
oldHeight = self.MinHeight
self.CellPerColumn = int((self.Width - 2) / self.CellWidht)
self.Columns = math.ceil(
self.Host.PatternSize / self.CellPerColumn) + 1
self.MinHeight = int(IDC_SELECTLOOP_GADGET_MINH * self.Columns) + 3
self.MinWidht = int(IDC_SELECTLOOP_GADGET_MINW)
self.BorderWidth = self.CellWidht * self.CellPerColumn
if oldHeight != self.MinHeight:
self.LayoutChanged()
def _get_color_vector(self, cid):
"""
Get a color vector from a color ID.
:param cid : The color ID
:return : c4d.Vector()
"""
dic = self.GetColorRGB(cid)
if dic:
return c4d.Vector(float(dic['r']) * self.ColScale,
float(dic['g']) * self.ColScale,
float(dic['b']) * self.ColScale)
else:
return c4d.Vector()
if __name__ == "__main__":
dlg = ExampleDialog()
dlg.Open(c4d.DLG_TYPE_ASYNC, defaultw=400, defaulth=400)
Hey @ECHekman,
I assume you are looking here for some kind of approval from my side? That looks fine, but it is hard to give a concrete assessment with mock code. But as lined out above, there is little which can go wrong here. Splitting up your data into sub-containers could help with access times when you plan to add lots of 'attributes' and 'pins'. So, it is good that you do that. And shifting your application IDs into lower ranges for Cinema 4D is probably not technically necessary but will lead to more 'natural' IDs. I cannot really see much going wrong here.
The only thing which is not so nice, is the unsafe C-style cast in BaseContainer *data = ((BaseShader*)node)->GetDataInstance();
. We recommend using static_cast
for safe casts and reinterpret_cast
for casts which are explicitly meant to be unsafe.
Cheers,
Ferdinand
Hey @ECHekman,
Thank you for reaching out to us. As you know, you should avoid topics with multiple questions, as they have a tendency to get out of hand.
However im running into two issues. Some of these symbols clash with existing symbols in c4d.
Yes, many symbols in Cinema 4D collide, dialog message symbols (BFM_SOMETHING
) collide for example with atom message (MSG_SOMETHING
) which again collide with core and event messages (EVMSG_SOMETHING
). The symbols for values inside the data containers of scene elements also collide with each other. This is for once because the address space of Int32 might not be big enough to address everything Cinema 4D has to address, and the curation of that would be very cumbersome or even impossible in the case of third parties.
The larger problem than value collision (both ID_FOO
and ID_BAR
resolve to 1000
) is actual symbol collision (you have the plugins A and B which both define an ID_FOO
which then resolves to different numeric values). In C++ this is offset by the fact that you can selectively include header files. In Python you cannot do this and all symbol labels must fit here collision free into the c4d
package namespace. One should therefore always prefix node symbols with the node they are for. E.g., for an ObjectData
plugin omyobject.res
, the symbols should look like this: ID_MYOBJECT_FOO
, ID_MYOBJECT_BAR
and not ID_FOO
or ID_BAR
.
I have read that the first 1000 are reserved. And that I shouldn't go above 1 million?
That is true, the parameter slots 0
to 1000
are reserved for the Basic tab each node has (with different content based on the node type) and some internal things. The name of a node is for example stored under ID_BASELIST_NAME
which is an alias for 900
.
I know that there is this information floating around that one should not use high numbers like a million. For stuff like plugin IDs (which you should not invent in the first place) it is true that we use the end of the Int32 address space for special purposes, so you REALLY should not invent a plugin ID that is 2^32 - 5
. But that would not be millions but billions. It could be that we in the past did occupy slots at the end of the Int32 space for scene elements. But I am currently not aware of any cases.
But for readability and conformance reasons I would recommend to stick to the Cinema 4D pattern of staying in the low hundreds of thousands. Due to how BaseContainer
works, there could also be a performance argument for small key values, but I am (a) not 100% sure and (b) it can probably be ignored on modern hardware.
What should not be ignored is that BaseContainer
is neither a hash map not a fixed size array but a list of key value pairs at its core. Storing 100, 1000, or 10 000 values is fine, and you can also store 100 000 values if you really have to. But you should be aware that access times are not constant (at the advantage that for the common case of small container sizes of ~1000 items, this will outperform hashing).
My other related issue is that I would like to reuse symbols in the same NodeData plugin.
You can reuse symbols between nodes as much as you want. What I would personally consider formally not so nice, is when you would just define a symbol in the resource of a node A and then also use it to store things in the data container of node B. But it is technically totally fine, I would just consider it poor code hygiene.
omyobject.h
must appear in omyobject.res
and omyobject.str
. When you want to define a 'global' symbol, you should do that in your c4d_symbols.h
.INCLUDE Obase;
is the line which includes the file obase.res
and its symbols into your object plugin and makes sure that it has the common UI elements and parameters all object nodes have. You can define your own base descriptions and include them. I would invite you to have a look at {C4D_FOLDER}/resource.zip/modules/c4d_base/description
to check out how Cinema 4D composes complex descriptions. All node types have a base, e.g., Obase
, Tbase
, Xbase
, etc., which are all based on the atomic description Obaselist
. But there is more modularization, things like spline interpolations, field handling, and more are all encapsulated in reusable description elements.You can also build dynamically descriptions or allocate data. In a node, we then usually define a base symbol ID_MYOBJECT_ITEMS_BASE = 50000
at a safe offset tp the rest of the data (so that we have room for adding other static parameters in the future), a stride ID_MYOBJECT_ITEMS_STRIDE = 100
(it does not matter that we define here the stride as 100 as we are not going to write with it into the data container at that value) and optionally a few named offsets (ID_MYOBJECT_ITEM_NAME = 0, _COLOR = 2, _LAYER = 3, ..
) and then write with these values at runtime into the data container of the node; e.g.,
const Int32 i = ID_MYOBJECT_ITEMS_BASE + ID_MYOBJECT_ITEMS_STRIDE * layer;
bc.SetString(i + ID_MYOBJECT_ITEM_NAME, "MyName"_s);
bc.SetVector(i + ID_MYOBJECT_ITEM_COLOR, myColor);
...
My solution idea was to use sub-containers to avoid both of these symbol clashes. However I cannot find in the sdk if the same symbol restrictions apply for subcontainers.
You can do whatever you want to in sub-containers. But I would avoid overly large containers (holding millions of items) for performance reasons. Only the data container of a scene element (BaseList2D::GetDataInstance
) comes with the restriction that you should not write into the 0
to 1000
range, as there it is where scene elements store their atomic data. A BaseContainer
itself is free of restrictions.
Additionally, do links work the same as with normal BaseContainers?
Are you talking about BaseLink
fields of a container? And what is here the implicitly referred counter part of 'normal' containers? A sub container? Links are stored document agnostic, i.e., you have to pass a document within which you want to resolve the link. It does not matter if you store that link in the top level of a nodes data container, in a sub-container of that data container, a bare BaseContainer
instance in memory, or a hyper file on disk. They all will be able to resolve their link when passed the correct document which contains a node with the matching marker stored in the link.
Cheers,
Ferdinand
Dear development community,
On December the 4th, 2024, Maxon Computer released Cinema 4D 2025.1.0. For an overview of the new features of Cinema 4D 2025.1, 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.1.0. The major changes are:
The PluginCafe GitHub organization has been deprecated in favour of a new Maxon-Computer GitHub organization. The legacy repositories have been moved, renamed, and brought into a consistent metadata form. Local clones of the legacy repositories will continue to work as they are.
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.
The graph description code examples on GitHub have not been uploaded yet, I will do this by the end of the week (6/12/2024)
Happy Christmas 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.
Well, my answer answers that, check out the posting I linked to. You must insert a MENURESOURCE_SUBTITLE
:
menu.InsData(c4d.MENURESOURCE_SUBTITLE, "My Heading")
Hey @Gemini,
Thank you for reaching out to us. I am struggling a bit with understanding all details of your question(s). Please also note that we do not allow for multi question topics, see Support Procedures: How to ask Questions for details.
Is there a way to add not pickable items like a title written with capital letter to custom menus created by python.
I assume you are talking about sub-titles in menus here, @i_mazlov has shown here how to do that.
How a toggle line be added and how can be get its sate?
I assume you mean here a menu entry with a checkbox/checkmark next to it? Menus allow you to mark entries as checked or disabled with the label suffixes 'c' and 'd'. E.g.: "I am a checked label&c&"
and "I am a disabled label&d&"
. See ShowPopupDialog() for an example. But one usually does this on a popup menu or dialog menu level.
The code you show us as "yours", is code I have written in the context of the main menu of Cinema 4D. So, the question is: Do you want to inject things into the main menu of Cinema 4D, or are you just populating a dialog or popup menu.
I am not sure if you are allowed to place checkmarks there and manually disable menu entries, as Cinema 4D itself owns its main menu. It might ignore such markup there, you would have to try yourself.
Cheers,
Ferdinand
addendum, I briefly spoke with the dev:
In SetDParameter, there is code that sets the correct group automatically if force_type or force_type_mode is specified, and the other way around. One thing to keep in mind is that, when you set the parameter force_type_group, the mode is set to default value for that group, i.e., ball and socket for spherical, hinge for angular, slider for linear. This is what you see ig you play in with the dropdown menus in the UI as well. So, if one first sets force_type_mode and then force_type_group, the latter resets the mode to a possibly different value. But in the code snippet attached it looks though like the order is correct (assuming is the actual code used in the plugin).
In a way, I understand that if you are setting mode and group manually from you plugin and you know what you are doing, you are setting a combination that makes sense. But in general, to be extra safe, I decided to go with this solution, so if you change the group the mode is automatically set to something that makes sense. And, btw, also when you set the mode there is a check on the group, and if the values don't match it gets overwritten with the correct group.
so, valid options are:
- simply set force_type (as before)
- set force_type_group and force_type_mode (in this order)
- only set force_type_mode (group set automatically)
If any of these don't give the expected combination it is a bug
I think he too struggled a bit with understanding what you did concretely, so I would recommend creating a bug report as lined out above.
Cheers,
Ferdinand
Hello @yaya,
Thank you for reaching out to us. Although your problem might be related to your old problem for you (as introduced by the connector object changes in 2024.4), I would say this is an entirely new issue. Please open a new thread for a new issue, as lined out in our Support Procedures.
Your problem description is also rather hard to follow, at least for me. I would recommend that you follow the pattern shown in Support Procedures: Examples - Reporting Bugs & Crashes very closely.
Cheers,
Ferdinand
Hello @ECHekman,
Thank you for reaching out to us. When you run into compiler errors, you should always include them, because how should we otherwise help you? Sure, I could throw your code into our code base, guess some things, and then try to compile it, but the guessing and compiling is unnecessary and makes our answers more imprecise.
But this should work:
iferr_scope;
maxon::String myString = "Hello/World"_s;
maxon::BaseArray<maxon::String> parts; // could also be const
myString.Split("/"_s, true, parts) iferr_return;
if (MAXON_UNLIKELY(parts.GetCount() < 1))
return maxon::IllegalStateError(MAXON_SOURCE_LOCATION, "Splitting path failed."_s);
FYI: There is also UrlInterface::GetComponents.
Cheers,
Ferdinand
Hey @peter_horvath,
So, you do call InstanceObject.GetInstanceMatrices()
etc. and construct the clones yourself. That was what confused me in your fist posting, as you talked about 'clones' in 'We'd need this index to be able to export MoGraph attributes to each clone/instance.'
What you effectively want to do, is associate the matrices/colors in an multi InstanceObject
with the MoGraph particle IDs they have been created for, right? That is not possible, at least for all cloners which have more than one particle geometry. I briefly talked with the current developer of MoGraph, and he does not see an option either.
I also tried to have a look at the Redshift code base, and as far as I can see, they simply seem to unravel things from the MoData side and mostly ignore the true cache and then end up with the ability to match a clone with its particle index even in Multi Instance mode (that is at least what it looks like to me, I have reached out to one of their devs). In the end I do not see anything particularly bad with this approach, because when syncing scene graphs, you have to reallocate geometry anyway. The problem with this is that MODATA_MATRIX
does not reflect the deformed matrix, i.e., it does not respect BaseObject::GetDeformMatrix
and with that simulations like for example RBD. I have absolultely no idea how Redshift handles that, I might be misinterpreting their code.
So, long story short, what you want to do, does not seem possible at the moment for externals. But the MoGraph Developer mentioned that we could try to store the InstanceObject::GetInstanceUniqueIP
in the MODATA_ALT_INDEX . But we would have to check first that this does not break anything. When you really want this, I would suggest filing a feature request (your Nodes API menu sorting thing is still cooking btw.)
Cheers,
Ferdinand
Hey @peter_horvath,
Thank you for reaching out to us. I am a little bit confused as I do not truly understand your question. You are an experienced developer, so it seems a bit unlikely that you overlooked what I am explaining next.
In the video below I have unfolded the cache of a MoGraph cloner and switch through the modes, which are admittedly named quite confusingly, but the docs mostly clear up their purpose: