The c4dtools module is a thin Python library created by Niklas Rosenstein. It provides functions and classes for the everyday work with Python in Cinema 4D. The most significant feature is the cached parsing of dialog symbols, see c4dtools.prepare().
Call this function from a Cinema 4D python plugin-file (*.pyp) to set up convenient data that can be used from the plugin.
import c4d
import c4dtools
res, imp = c4dtools.prepare(__file__, __res__)
# ...
Parameters : |
|
---|---|
Returns: | A tuple of two elements.
|
New in 1.2.6.
This class implements a subset of the dictionary interface but without the requirement of the __hash__() method to be implemented. It is using comparing objects directly with the == operator instead.
This class keeps track of a file on the local filesystem and tell you if the specific file has changed since the last time the FileChangedChecker was asked this question.
It can run in two modes: pushing or pulling. With pulling, we mean to request the information whether the file has changed or not. With pushing, we mean to get notified when the file has changed. Pushing comes in connection with threading. Only one thread can be run from on FileChangedChecker instance.
Example for pulling:
f = FileChangedChecker(my_filename)
# ...
if f.has_changed():
print ("File %s has changed since `f` has been created." %
f.filename)
Example for pushing:
f = FileChangedChecker(my_filename)
def worker(f):
print ("File %s has changed since `f` has been created." %
f.filename)
f.run_in_background(worker)
This is the worker class instantiated by the FileChangedChecker to run in the background.
This method returns True when file pointed to by the stored filename has changed since the last time the FileChangedChecker was asked for.
Start a new thread invoking the callable callback passing the FileChangedChecker instance when the file it points to has changed. period defines the time in seconds that passes until the next time the thread checks for the change.
Stops the background operation started with run_in_background(). When join evaluates to True, this method will wait until the thread has stopped working before terminating.
Raises: RuntimeError when no thread has been started yet.
Not public. This method is called by a FileChangedChecker.Worker instance to dispose the worker from the list of not yet disposed workers.
A wrapper class for the os.path module.
Use this class to enable importing modules from specific directories independent from sys.path.
When this value is True, the paths defined in the importer are prepended to the original paths in sys.path. If False, they will be appended. Does only have an effect when use_sys_path is True.
When this value is True, the original paths from sys.path are used additionally to the paths defined in the imported.
Add the passed strings to the search-path for importing modules. Raises TypeError if non-string object was passed. Passed paths are automatically expanded.
New in 1.2.5.
This class stores the points and polygons of a polygon-object and additionally computes it’s normals and polygon-midpoints.
Utility class for measuring execution-time of code-blocks implementing the with-interface.
>>> with Watch() as w:
... time_intensive_code()
...
>>> w.delta
4.32521002
Returns the difference between the time Watch.start() has been and Watch.stop() has been called. If Watch.stop() has not yet been invoked, the current time is used.
Reset the information and return the Watch into a state where time measuring has not been started yet.
Stop the time measuring.
Raises : | RuntimeError when Watch.start() was not called before. |
---|
New in 1.2.5.
This function is similar to the built-in isinstance() function in Python. It accepts an instance of a class as first argument, namely x, and checks if it is an instance of one of the passed types. The types must not be encapsulated in a tuple (which is in contrast to the isinstance() method).
This function raises a TypeError exception with a proper error message when x is not an instance of the passed *types.
Changed in 1.2.8: Renamed from assert_type to ensure_type. Added **kwargs parameter. Pass name as keyword-argument for adding the parameter name that was wrong in the message.
New in 1.2.8. Yields the passed object and all following objects in the hierarchy (retrieved via GetNext()). When the safe parameter is True, the next object will be retrieved before yielding to allow the yielded object to be moved in the hierarchy and iteration continues as if the object was not moved in hierarchy.
Searches for value in obj and returns a list of all keys where the callback returns True, being passed value as first argument, the value to compare it with as the second argument and the name of the attribute as the third.
Returns: list of str
Replaces the suffix of the passed filename with new_suffix.
Return the name of the class of the passed object. This is a shortcut for obj.__class__.__name__.
Makes the passed c4d.BaseObject instance an editable object by applieng a modeling command on it. The returned object’s hierarchy will consist of Null-Objects and editable objects only.
container is an argument assigned a new c4d.BaseContainer to optimize speed and memory usage, but you can pass your own c4d.BaseContainer in case you want to pass any additional information to the c4d.utils.SendModelingCommand function.
Example code for the Script Manager:
import c4dtools
def main():
obj = c4dtools.utils.current_state_to_object(op)
doc.InsertObject(obj)
c4d.EventAdd()
main()
Raises: TypeError if op is not a c4d.BaseObject instance. Returns: c4d.BaseObject
New in 1.2.5.
This function is similar to the built-in isinstance() function in Python. It accepts an instance of a class as first argument, namely x, and checks if it is an instance of one of the passed types. The types must not be encapsulated in a tuple (which is in contrast to the isinstance() method).
This function raises a TypeError exception with a proper error message when x is not an instance of the passed *types.
Changed in 1.2.8: Renamed from assert_type to ensure_type. Added **kwargs parameter. Pass name as keyword-argument for adding the parameter name that was wrong in the message.
New in 1.2.8.
This function checks if the value x is in *values. If this does not result in True, ValueError is raised.
Pass name as keyword-argument to specify the parameter name that was given wrong in the message.
Returns True when the filename pointed by original was modified before the last time copy was modified, False otherwise.
New in 1.2.6.
This decorator must be called, passing attributes to be stored in the decorated function.
New in 1.2.6.
This function goes through the complete object hierarchy of the passed c4d.BaseDocument and all materials with the objects that carry a texture-tag with that material. The returnvalue is an AtomDict instance. The keys of the dictionary-like object are the materials in the document, their associated values are lists of c4d.BaseObject. Note that an object can occure twice in the same list when the object has two tags with the same material on it.
Parameters: | doc – c4d.BaseDocument |
---|---|
Returns: | AtomDict |
New in 1.2.6.
Returns the root-file or folder of a module filename. The return-value is a tuple of (root_path, is_file).
A bitmap can be retrieved from a c4d.BaseShader instance of type Xbitmap using its GetBitmap() method. This method must however be wrapped in calls to InitRender() and FreeRender().
This function initializes rendering of the passed shader, retrieves the bitmap and frees it.
Return : | c4d.BaseBitmap or None. |
---|
Iterate over the passed container being a c4d.BaseContainer instance recursively. The callback will be called for each key-value pair. The default callback will print out the values in the container.
The callback is passed the containers key, value and stack-level.
Returns : | None |
---|---|
Raises : | TypeError when callback is not callable. |
New in 1.2.8. This function creates one polygon object from the passed list objects containing c4d.PolygonObject instances. Any other type of object is ignored.
The returned polygon-object is located at the global world center.
# TODO: Add description for parameters.
New in 1.2.7.
Returns serial-information of the user. Returns (sinfo, is_multi). is_multi indicates whether the sinfo is a multilicense information or not.
A shortcut for
c4d.DrawViews(
c4d.DRAWFLAGS_ONLY_ACTIVE_VIEW | c4d.DRAWFLAGS_NO_THREAD |
c4d.DRAWFLAGS_NO_REDUCTION | c4d.DRAWFLAGS_STATICBREAK)
Can be used to update the editor, useful for going through the frames of a document and doing backing or similar stuff.
Returns : | The return-value of c4d.DrawViews(). |
---|
Returns the mid-point of the bounding box spanned by the list of vectors. This is different to the arithmetic middle of the points.
Returns: c4d.Vector
This module defines content that has a rather generic purpose, unlike the contents of the c4dtools.utils module.
This class is wrapping the CommandData class to make the registration of plugins of this kind easier. Subclasses are automatically registered on c4dtools.plugins.main() unless autoregister evaluates to False.
An instance of a subclass of this class must provide the following attributes to be successfully registered:
This module implements functionality for making it possible for plugins to interface with each other, i.e. one plugin may depend on the functionality of another plugin (even developed from different developers).
A Python plugin may create a Library class that will be (automatically) registered to the c4dtools.library mmodule. This library can then be loaded from another plugin to establish a Python-level communication between these plugins. As the plugin initialization order can not be controlled from Python, and there may also exist a circular reference to libraries of two or more plugins, references to libraries are always lazy and loaded on-request.
Example library:
import c4dtools
class MyLibrary(c4dtools.library.Library):
class Meta:
# Here comes meta information.
pass
def on_create(self):
print "MyLibrary has been created."
def on_install(self, name):
print "MyLibrary has been installed under the name %s." % name
def get_stuff(self):
return "This is from MyLibrary!"
Nothing more needs to be done. The library is automatically registered with the name 'MyLibrary'. The name the library is registered with can be changed by defining name=’libname’ in the Meta section. When registration should be prevented, one needs to define abstract=True in the Meta section.
This library can now be loaded from another Python unit.
import c4dtools
MyLibrary = c4dtools.load_library('MyLibrary')
print MyLibrary.get_stuff()
This class is representing a lazy reference to a library. The actual library will be loaded on the first request.
This is the base class for library objects. It’s metaclass LibraryMeta will automatically turn methods into classmethods and will disallow the instantiaton of the class.
This is the meta-class of the Library class. It implements automatically registering the Library when the class is created, except it is marked as abstract.
One can mark a Library as abstract when defining a meta-object on class-level that contains an attribute abstract that evaluates to True. A library must be marked abstract explicitly. An abstract library will not be registered.
Example:
class MyLibrary(Library):
class Meta:
abstract = True
# ...
This exception is thrown when a requested library was not found.
Load a library. Returns a Library instance unless lazy does not evaluate to True. If lazy is True, a LazyLibrary instance will be returned.
An instance of this class is used to store the symbols of a C4D symbols file and several other information to work with the resource of a plugin, such as easily grabbing files from that folder, etc.
The directory name of the resource-folder. Not garuanteed to exist!
The c4d.plugins.GeResource object passed on construction. This is usually the __res__ variable passed through from a Python plugin.
A StringLoader instance associated with the resource object. Used to load resource strings.
# Load a resource-string with the IDC_MYSTRING symbol-name
# without formatting arguments.
res.string.IDC_MYSTRING()
# Or call the str() function on the returned ResourceString
# instance.
str(res.string.IDC_MYSTRING)
# Format the resource string by replacing the hashes in
# the string with the passed arguments.
res.string.IDC_FILENOTFOUND(filename)
# Unpack the tuple returned by the `both` property.
# Shortcut for:
# container.SetString(
# res.IDC_CONTEXTMENU_1,
# res.string.IDC_CONTEXTMENU_1())
container.SetString(*res.string.IDC_CONTEXTMENU_1.both)
This attribute is set by the load() function and is only True when the resource was cached and has changed, therefore the cache was rebuilt. When symbol-caching is deactivated, this attribute will always be False.
Add the dictionary symbols to the resources symbols.
This class represents a resource-string loaded from plugin resource.
This class is used for conveniently loading strings from the c4d_strings.str file. It is basically a wrapper for the c4d.plugin.GeLoadString function. Accessing an attribute on an instance of this class will return a callable object accepting the same parameters as the previously mentioned API call, but with the symbol-id already passed.
Load the symbols of a Cinema 4D resource file. The symbols will be loaded directly from the symbols file when use_cache is False. In the other case, the symbols are loaded from the cached symbols if the symbols haven’t changed since the cache has been generated. If the cache is not available, it will be generated when use_cache is True.
The advantage of caching the symbols in a seperate file is the improved speed of reading in the symbols.
Returns : | (symbols_dict, changed) |
---|---|
Raises : | OSError if filename does not exist or does not point to a file. |
Miscellaneous packages.
Utility for computing the bounding-box spanned by a couple of vectors or by c4d.BaseObject instances.
This class makes it easy to compute the bounding-box of a set of points or even objects. AABB is short for “axis-aligned bounding-box”.
Example for Script Manager:
from c4dtools.misc.boundingbox import AABB
box = AABB()
box.expand(op, recursive=True)
print box.midpoint
print box.size
The bounding box is always calculated from global coordinates and is translated with the matrix in the translation_matrix slot. The translation can not be performed after expansion of the bounding- box, the translation_matrix must therefore be set before expand() or expand_point() is called.
from c4dtools.misc.boundingbox import AABB
box = AABB(translation_matrix=~op.GetMg())
box.expand(mg, recursive=True)
print box.midpoint
print box.size
Expand the bounding-box by the passed c4d.BaseObject instance. The method can optionally continue recursively.
Thin wrapper for interacting with XPresso Node UI.
This class is a thin wrapper for the c4d.modules.graphview.GvNode class providing an easy interface for accessing and modifieng the visual appeareance of an XPresso node in the XPresso editor.
Currently, only accessing the position and size is supported.
This method returns the container containing the graphdata for the node in the XPresso grap based on the GvNode s container.
Returns the visual size of the node as c4d.Vector. The container IDs differ for extended and standart view mode. The size is read/set according the to view mode the node is currently assigned to.
Returns the type of view of the node. Either VIEW_MINIMIZED, VIEW_STANDART, VIEW_EXTENDED or VIEW_FULLSCREEN.
Module for interacting with Cinema 4D’s UserData interface.
This class manages userdata-value retrieval and storing. It accepts a dictionary associating the attribute-name and the userdata’s sub-id on initialization and the c4d.BaseList2D object to use for retrival and storing.
The values can optionally be cached to improve value retrieval.
from c4dtools.misc.userdata import UserDataSetAndGet as UDSG
data = UDSG({
'count': 1,
'link': 2,
}, op)
print data.count
print data.link
# Equal to
print op[c4d.ID_USERDATA, 1]
print op[c4d.ID_USERDATA, 2]
New in 1.2.5.
This module implements a function for checking the alignment of the normals of a polygon-object.
Align the passed polygon-object’s normals to point to the outside of the object. The same algorithmic restrictions as for test_object_normals() apply. The parameters do also equal.
Tests the polygon-object op‘s normals if they’re pointing to the in or outside of the object. Returns a list of boolean variables where each index defines wether the associated polygon’s normal is pointing into the right direction or not.
The algorithm works best on completely closed shapes with one segment only. The polygon-object should also be valid, therefore not more than two polygons per edge, etc. The results might be incorrect with an invalid mesh structure.
Parameters: |
|
---|---|
Returns: | list of bool and the PolygonObjectInfo instance. |