mari
Mari docs package.
- class mari.Action
Bases:
objectAn action that can be assigned to a menu and/or shortcut.
Built-in actions will generally be of this type when retrieved from the
ActionManager. Custom user actions, which run Python scripts, will beScriptActionobjects.Example Code
>>> # This example creates an action to print "Hello World" to the log and executes the action >>> import mari >>> action = mari.actions.create("MyCustomActions/Print Hello","mari.app.log('Hello World')") >>> action.trigger()
>>> import mari >>> # This example finds the action and executes it >>> action = mari.actions.find("Mari/Scripts/MyCustomActions/Print Hello") >>> action.trigger()
- addToSet(SetName)
Adds the action to an action set.
Adding an action to a set that is disabled will disable the action.
- Parameters:
SetName (str) – The name of the set to add the action to. If the set does not exist, it will be created
- Raises:
ValueError – Raised if the set name was invalid.
See also
removeFromSet()
- autoRepeat()
Returns whether this action is auto repeatable when the key is pressed.
- Returns:
bool– Whether this action is auto repeatable when the key is pressed.
- iconPath()
Returns the path to the icon used for the action.
- Raises:
TypeError – Raised if the action is of a built-in type that does not support icon path retrieval.
- Returns:
str– The path to the icon. If no icon is used, this will be blank.
See also
setIconPath()
- isCheckable()
Indicates whether the given action has a check box that can be turned on and off.
- Returns:
bool– True if the action has a check box, or false if not.
See also
setCheckable()
- isChecked()
Returns true if the action is checked, false otherwise.
- Returns:
bool– Whether the action is checked or not
See also
setChecked()
- isEnabled()
Indicates whether the action is enabled.
- Returns:
bool– True if the action is enabled, or false otherwise.
See also
setEnabled()
- name()
Returns the name of the action.
This is the same as
text().- Returns:
str– The name of the action
See also
setText(), text()
- path()
Returns the path that this action is registered in.
If an internal action is registered in multiple paths, this will return the first one.
- Returns:
str– The path that this action is registered in, such as “Mari/Scripts/Custom Action”. For a description of action paths, see ActionManager::create()
- removeFromSet(SetName)
Removes the action from an action set.
- Parameters:
SetName (str) – The set to remove the action from
- Raises:
ValueError – Raised if the set name was invalid.
See also
addToSet()
- removeShortcut(Group)
Removes any current shortcut in the given shortcut group for the action.
If the action specified does not have a shortcut, this function will complete successfully without raising an exception.
- Parameters:
Group (ActionManager.ShortcutGroup) – The shortcut group
See also
setShortcut(), shortcut()
- setAutoRepeat(AutoRepeat)
Sets whether this action is auto repeatable when the key is pressed.
- Parameters:
AutoRepeat (bool) – Whether this action is auto repeatable when the key is pressed.
- setCheckable(Checkable)
Sets the action as being checkable i.e. one that has an on/off state.
- Parameters:
Checkable (bool) – Whether the action is checkable or not
See also
isCheckable()
- setChecked(Checked)
Sets the action as being checked.
- Parameters:
Checked (bool) – Whether the action is checked or not
See also
isChecked()
- setEnabled(Enabled)
Enables or disables this action.
- Parameters:
Enabled (bool) – True to enable the action, or false to disable it.
See also
isEnabled()
- setIconPath(IconPath)
Sets the icon to display on menus for the action.
- Parameters:
IconPath (str) – The path to an icon to load
- Raises:
IOError – Raised if the icon failed to load.
TypeError – Raised if the action is of a built-in type that does not support icon path retrieval.
See also
iconPath()
- setShortcut(rString, Group)
Sets the shortcut key for the action in the given shortcut group.
Shortcuts can be single keys (“F1”), keys with modifiers (“Ctrl+A”), or empty to specify no shortcut.
- Parameters:
rString (str) – The new shortcut string for the given action. Pass in an empty string to clear the shortcut
Group (ActionManager.ShortcutGroup) – The shortcut group
- Raises:
ValueError – Raised if the shortcut string was invalid.
See also
removeShortcut(), shortcut()
- setStatusTip(StatusTip)
Sets the status tip displayed on all status bars by the action’s top-level parent widget.
- Parameters:
StatusTip (str) – The status tip for the action
See also
statusTip()
- setText(NewText)
Sets the text to display for the action.
- Parameters:
NewText (str) – The new text for the action
See also
name(), text()
- setToolTip(ToolTip)
Sets the tool tip for the action.
- Parameters:
ToolTip (str) – The tool tip for the action
See also
toolTip()
- setWhatsThis(WhatsThis)
Sets the “What’s This?” text used to provide a brief description of the action.
- Parameters:
WhatsThis (str) – The “What’s This?” text for the action
See also
whatsThis()
- shortcut(Group)
Returns the string representation of the shortcut for the action in the given shortcut group.
- Parameters:
Group (ActionManager.ShortcutGroup) – The shortcut group
- Returns:
str– A string returning the shortcut for the given action, or an empty string if there is no shortcut.
Note
This may not match the value originally set if something else has overridden the shortcut key since then.
See also
removeShortcut(), setShortcut()
- statusTip()
Returns the status tip for the action displayed on status bars.
- Returns:
str– The status tip for the action
See also
setStatusTip()
- text()
Returns the text to display for the action when required.
- Returns:
str– The text to display for the action when required
See also
name(), setText()
- toolTip()
Returns the tool tip for the action.
- Returns:
str– The tool tip for the action
See also
setToolTip()
- trigger()
Executes the script action.
See also
triggered()
- triggered()
This is emitted when the action is triggered by Python or GUI interaction.
See also
trigger()
- whatsThis()
Returns the “What’s This?” text used to provide a brief description of the action.
- Returns:
str– The “What’s This?” text for the action
See also
setWhatsThis()
- class mari.ActionManager
Bases:
objectManages creation and manipulation of actions.
This class creates and manipulates
Mariactions, which are used as menu commands, and can have shortcut keys bound to them. By default, any action created through scripting will be in the “/Mari/Scripts” path, but this can be customized if there is any need to avoid clashes.Maristores all of the available actions in a tree, and actions are identified by their path within this tree. For example, “/Mari/Tools/TestTool” refers to an action called TestTool in a subsection called Tools.Example Code
>>> # This example creates an action through mari.actions(ActionManager singleton instance) to print "Hello World" to the log and executes the action >>> import mari >>> action = mari.actions.create("MyCustomActions/Print Hello","mari.app.log('Hello World')") >>> action.trigger()
>>> # This example finds the action and executes it >>> import mari >>> action = mari.actions.find("Mari/Scripts/MyCustomActions/Print Hello") >>> action.trigger()
Alias
actions
- APPLICATION = 0
Application.
- Type:
int
- NODE_GRAPH = 1
Node Graph.
- Type:
int
- class ShortcutGroup
Bases:
objectThese values identify the shortcut groups numerically.
- APPLICATION = 0
Application.
- Type:
int
- NODE_GRAPH = 1
Node Graph.
- Type:
int
- actionFromShortcut(Shortcut, Group='APPLICATION')
Returns the path of the action that is using the given shortcut in the given shortcut group.
- Parameters:
Shortcut (str) – A text version of the shortcut you’re interested in
Group (ShortcutGroup, optional) – The shortcut group. Defaults to APPLICATION.
- Returns:
str– The path to the action that uses the given shortcut in the given shortcut group, or an empty string if the shortcut is invalid or not in use
- addToSet(SetName, pAction)
Adds an action to an action set.
This will not modify the enabled state of the action.
- Parameters:
SetName (str) – The name of the set to add the action to. If the set does not exist, it will be created
pAction (Action) – The action to add to the set
- Raises:
ValueError – Raised if the set name or action were invalid.
See also
disableSet(), enableSet(), removeFromSet(), sets()
- create(rIdentifier, rCommand)
Creates a new action with the given name and scripting command.
The identifier supplied for an action is composed of an optional path and a name. The path, if supplied, gives the path in the action hierarchy where the action will be stored. These paths help conceptually group actions and avoid name clashes. If no path is provided to this function, it will use “/Mari/Scripts” by default. If a path is provided, it is assumed to be absolute if it starts with a slash (e.g. “/Mari/SomethingElse/” is used as is), or otherwise it is taken as relative (e.g. “My/Path/” becomes “/Mari/Scripts/My/Path/”). The remainder of the identifier is used as the display text for the action.
Both the path and the display text can contain spaces.
Note that you will need to assign the action to a menu or a shortcut before you will be able to do anything useful with it.
- Parameters:
rIdentifier (str) – The identifier that provides the action’s path and display text. See the main description.
rCommand (str) – The scripting command to run when the action is activated.
- Returns:
ScriptAction– A new action object.
- disableSet(SetName)
Disables all actions in the given set.
- Parameters:
SetName (str) – The name of the action set to disable
See also
addToSet(), enableSet(), removeFromSet(), sets()
- enableSet(SetName)
Enables all actions in the given set.
- Parameters:
SetName (str) – The name of the action set to enable
See also
addToSet(), disableSet(), removeFromSet(), sets()
- find(rPath)
Returns the Mari action that corresponds to the path provided.
Using this function, users can find an individual action. Calling
Action::trigger()on the action returned will execute it.See
create()for a description of action paths.- Parameters:
rPath (str) – The path to the action to find
- Returns:
Action– The requested action if found, or NULL otherwise
See also
get()
- get(rPath)
Returns the Mari action that corresponds to the path provided.
Using this function, users can find an individual action. Calling
Action::trigger()on the action returned will execute it.See
create()for a description of action paths.- Parameters:
rPath (str) – The path to the action to find
- Raises:
ValueError – Raised if the requested action was not found.
- Returns:
Action– The requested action
See also
find()
- list(rPath='')
Returns a list of the available actions.
Without a parameter this action will return a list of all actions, including the full path The user may optionally pass in a path to a subtree. Given a subtree, only actions in that subtree will be returned.
- Parameters:
rPath (str, optional) – An optional path to a subtree. If provided, only actions in that subtree will be returned. Defaults to “”.
- Returns:
list of str– A list of actions, including their path
- loadUserShortcuts()
Loads user shortcuts from the configuration file.
This is provided mainly for internal use, so user-specific shortcuts can be loaded after any shortcuts have been set up by the Python stage of the initialization process.
- removeFromSet(SetName, pAction)
Removes an action from an action set.
This will not modify the enabled state of the action.
- Parameters:
SetName (str) – The set to remove the action from
pAction (Action) – The action to remove
- Raises:
ValueError – Raised if the set name or action were invalid.
See also
addToSet(), disableSet(), enableSet(), sets()
- removeShortcut(Path, Shortcut='', Group='APPLICATION')
Removes the given shortcut for the given action in the given shortcut group.
If the given shortcut is empty the first shortcut will be removed. If the action specified does not have any shortcuts, this function will complete successfully without raising an exception.
- Parameters:
Path (str) – The path to the action
Shortcut (str, optional) – The shortcut to remove. Defaults to “”.
Group (ShortcutGroup, optional) – The shortcut group. Defaults to APPLICATION.
- Raises:
ValueError – Raised if no action with the given path was found.
- removeShortcuts(Path, Group='APPLICATION')
Removes all shortcuts for the given action in the given shortcut group.
If the action specified does not have any shortcuts, this function will complete successfully without raising an exception.
- Parameters:
Path (str) – The path to the action
Group (ShortcutGroup, optional) – The shortcut group. Defaults to APPLICATION.
- Raises:
ValueError – Raised if no action with the given path was found.
- setShortcut(Path, Shortcut, Group='APPLICATION')
Sets the shortcut for the given action in the given shortcut group.
Shortcuts can be single keys (“F1”), keys with modifiers (“Ctrl+A”), or empty to specify no shortcut.
- Parameters:
Path (str) – The path to the action
Shortcut (str) – The new shortcut string for the given action. Pass in an empty string to clear the shortcut
Group (ShortcutGroup, optional) – The shortcut group. Defaults to APPLICATION.
- Raises:
ValueError – Raised if no action with the given path was found, or if the shortcut string was invalid.
- sets()
Returns the list of defined action set names.
Actionsets are groups of actions that can be enabled and disabled as a group. This can be used to easily configureMaridepending on the context. If, for example, you have actions that only work on floating point channels, they can be added to an action set, and then enabled or disabled depending on the currently selected channel.Actions can be added to multiple sets. However, please note that the sets themselves do not have an enabled state; only the actions do. This means that, for example, if an action has been added to two sets, and
enableSet()is called on one and thendisableSet()is called on the other, the action will be disabled - but, if the calls are the other way around, it will be enabled. In other words, there is no way of saying “disable (or enable) this action if either of its two sets are disabled (or enabled)”. If this behavior is not suitable, please define a new set and enable and disable that one separately.- Returns:
list of str– The list of defined action set names
See also
addToSet(), removeFromSet(), enableSet(), disableSet()
- shortcut(Path, Group='APPLICATION')
Returns the first shortcut for the given action in the given shortcut group.
- Parameters:
Path (str) – The path to the action
Group (ShortcutGroup, optional) – The shortcut group. Defaults to APPLICATION.
- Returns:
str– A string returning the first shortcut for the given action in the given shortcut group, or an empty string if there is no shortcut.
- shortcutIsInUse(Shortcut, Group='APPLICATION')
Indicates whether the given shortcut is in use in the given shortcut group.
- Parameters:
Shortcut (str) – The string version of the shortcut to check (e.g. “Ctrl+S”)
Group (ShortcutGroup, optional) – The shortcut group. Defaults to APPLICATION.
- Returns:
bool– True if the shortcut has been set (with or without an existing action), or False otherwise.
- shortcuts(Path, Group='APPLICATION')
Returns all shortcuts for the given action in the given shortcut group.
- Parameters:
Path (str) – The path to the action
Group (ShortcutGroup, optional) – The shortcut group. Defaults to APPLICATION.
- Returns:
list of str– A list of all shortcuts for the given action in the given shortcut group, or an empty list if there is no shortcuts.
- class mari.AdjustableLayer
Bases:
LayerAdjustable layers can be set to apply an adjustment stack to their image data.
Adjustment stacks can be used to apply a set of adjustment operations to only the image data in the individual layer, without affecting those below it.
This is an abstract class; every layer that is an
AdjustableLayerwill also be of a further-derived type, such asPaintableLayer.Example Code
>>> #This example finds adjustmentable layers in the current channel. >>> import mari >>> adjustable_layers = [] >>> channel = mari.geo.current().currentChannel() >>> for layer in channel.layerList(): ... if layer.isAdjustableLayer(): ... adjustable_layers.append(layer)
- adjustmentStack()
Returns the adjustment layer stack that is applied to this layers paint image set.
- Raises:
RuntimeError – Raised if the layer has no paint adjustment stack.
- Returns:
LayerStack– Returns a layer stack
- hasAdjustmentStack()
Indicates whether this layer has an adjustment stack.
- Returns:
bool– True is this layer has an adjustment stack
- isAdjustmentStackEnabled()
Indicates if the adjustment stack is disabled.
- Returns:
bool– False is an adjustment stack is present and disabled.
- makeAdjustmentStack()
Creates an adjustment stack on the layer.
- Raises:
RuntimeError – Raised if the layer adjustment stack cannot be create or already exists or the layer is not modifiable.
- Returns:
LayerStack– Returns the created layer stack
- removeAdjustmentStack()
Removes the adjustment stack from the layer.
- Raises:
RuntimeError – Raised if the layer adjustment stack cannot be removed or does not exist or the layer is not modifiable.
- setAdjustmentStackEnabled(Enabled)
Set the enabled state of the adjustment stack.
- Parameters:
Enabled (bool) – The enabled state to set the adjustment stack to
- class mari.AdjustmentLayer
Bases:
LayerAdjustment layers modify the data from the layers below them in the layer stack.
You can access all types of layers from their containing
Channelobjects - for example:channel.layerList()You can check for
AdjustmentLayerobjects by callingLayer::isAdjustmentLayer():Example Code
>>> #This example finds adjustment layers in the current channel >>> import mari >>> adjustment_layers = [] >>> channel = mari.geo.current().currentChannel() >>> for layer in channel.layerList(): ... if layer.isAdjustmentLayer(): ... adjustment_layers.append(layer)
>>> #This example creates an "Brightness" adjustment layers in the current channel >>> import mari >>> channel = mari.geo.current().currentChannel() >>> layer = channel.createAdjustmentLayer("Brightness","Filter/Brightness") >>> layer.isAdjustmentLayer() True
- getPrimaryAdjustmentParameter(ParameterName)
Retrieves the current value of a parameter from this primary adjustment layer.
- Parameters:
ParameterName (str) – The name of the parameter to inspect
- Raises:
ValueError – Raised if name of the parameter does not match any existing items.
- Returns:
variant– The current value of the parameter
See also
setPrimaryAdjustmentParameter()
- getPrimaryAdjustmentParameterAsImage(ParameterName)
Retrieves the current value of a parameter from this primary adjustment layer and, if possible, return the Image it relates to.
- Parameters:
ParameterName (str) – The name of the parameter to inspect.
- Raises:
ValueError – Raised if name of the parameter does not match any existing items.
- Returns:
Image– Image of the parameter. None if not image is assigned.
See also
getPrimaryAdjustmentParameter()
- getSecondaryAdjustmentParameter(ParameterName)
Retrieves the current value of a parameter from this secondary adjustment layer.
- Parameters:
ParameterName (str) – The name of the parameter to inspect.
- Raises:
ValueError – Raised if name of the parameter does not match any existing items.
RuntimeError – Raised if the layer has no secondary adjustment.
- Returns:
variant– QVariant The current value of the parameter.
See also
setSecondaryAdjustmentParameter()
- getSecondaryAdjustmentParameterAsImage(ParameterName)
Retrieves the current value of a parameter from this primary secondary layer and, if possible, return the Image it relates to.
- Parameters:
ParameterName (str) – The name of the parameter to inspect.
- Raises:
ValueError – Raised if name of the parameter does not match any existing items.
- Returns:
Image– Image of the parameter. None if not image is assigned.
See also
getSecondaryAdjustmentParameter()
- hasSecondaryAdjustment()
Indicates whether this adjustment layer has a secondary adjustment.
- Returns:
bool– True is this layer has a secondary adjustment
- makeSecondaryAdjustment(AdjustmentKey)
Makes a secondary adjustment on this adjustment layer.
- Parameters:
AdjustmentKey (str) – the path key of the type of the adjustment to create
- Raises:
ValueError – Raised if adjustment key parameter does not match any valid value
RuntimeError – Raised if the secondary adjustment cannot be create or already exists. Or the layer is not modifiable.
- primaryAdjustmentParameters()
Returns the list of parameters on this primary adjustment layer.
- Returns:
list of str– A list of the parameter names for this primary adjustment layer
- primaryAdjustmentType()
Returns the name of the primary adjustment type.
- Returns:
str– The name of the type of primary adjustment, which will be of the form ‘Filter/Brightness’
- removeSecondaryAdjustment()
Removes a secondary adjustment on this adjustment layer.
- Raises:
RuntimeError – Raised if the secondary adjustment cannot be removed or does not exist. Or the layer is not modifiable.
- secondaryAdjustmentParameters()
Returns the list of parameters on this secondary adjustment layer.
- Raises:
RuntimeError – Raised if the layer has no secondary adjustment.
- Returns:
list of str– A list of the parameter names for this secondary adjustment layer.
- secondaryAdjustmentType()
Returns the name of the secondary adjustment type.
- Raises:
RuntimeError – Raised if the layer has no secondary adjustment.
- Returns:
str– The name of the type of secondary adjustment, which will be of the form ‘Filter/Brightness’
- setPrimaryAdjustmentParameter(ParameterName, NewValue)
Sets the value of a parameter on the primary adjustment.
- Parameters:
ParameterName (str) – The name of the parameter to modify
NewValue (variant) – The new value for the parameter. This can be of a variety of types.
- Raises:
ValueError – Raised if the parameter could not be found, or was invalid.
See also
getPrimaryAdjustmentParameter()
- setSecondaryAdjustmentParameter(ParameterName, NewValue)
Sets the value of a parameter on the secondary adjustment.
- Parameters:
ParameterName (str) – The name of the parameter to modify.
NewValue (variant) – The new value for the parameter. This can be of a variety of types.
- Raises:
ValueError – Raised if the parameter could not be found, or was invalid.
RuntimeError – Raised if the layer has no secondary adjustment.
See also
getSecondaryAdjustmentParameter()
- class mari.AppVersion
Bases:
objectThis class contains detailed version information for Mari.
Example Code
>>> # This example stores mari information in a string and prints it out to the application log >>> import mari >>> version = mari.app.version() >>> mari_info_dict = {} >>> mari_info_dict["major"] = version.major() >>> mari_info_dict["minor"] = version.minor() >>> mari_info_dict["revision"] = version.revision() >>> mari_info_dict["stage"] = version.stage() >>> mari_info_string = "Mari {major}.{minor}.{revision}{stage}".format(**mari_info_dict) >>> mari.app.log(mari_info_string)
- ALPHA = 1
An early testing version.
- Type:
int
- BETA = 2
An advanced testing version.
- Type:
int
- DEV = 0
An internal development version.
- Type:
int
- RELEASE = 3
An official released version.
- Type:
int
- class Stage
Bases:
objectThese values identify the build stages numerically.
- ALPHA = 1
An early testing version.
- Type:
int
- BETA = 2
An advanced testing version.
- Type:
int
- DEV = 0
An internal development version.
- Type:
int
- RELEASE = 3
An official released version.
- Type:
int
- date()
Returns the date that this version was built.
- Returns:
str– The build date as a string, in YYYY-MM-DD format.
- feature()
Returns the name of the feature of the build.
- info()
Returns an information string describing the build.
- isLinux()
Indicates whether Mari is running on Linux.
- Returns:
bool– True if on Linux, or false on other operating systems
- isMac()
Indicates whether Mari is running on Mac OS X.
- Returns:
bool– True if on Mac OS X, or false on other operation systems
- isWindows()
Indicates whether Mari is running on Windows.
- Returns:
bool– True if on Windows, or false on other operating systems
- iteration()
Returns the iteration number, as used in alpha and beta builds.
For example, the iteration number of 1.2v3.000004b is 4.
- major()
Returns the major version number of the build.
For example, the major version number of 1.2v3 is 1.
- minor()
Returns the minor version number of the build.
For example, the minor version number of 1.2v3 is 2.
- number()
Returns the full build version as an integer for comparison.
These build version integers can be compared to easily test whether one build comes before or after another.
The number consists of the major, minor, revision, stage, and iteration components of the version. For example, 1.5v6.000007b would be 105062000007 (with the 2 referring to the beta stage), and 1.5v6 would be 105063000000 (with the 3 for the release stage).
- qt()
Returns the Qt version as a string.
- Returns:
str– The version of Qt that Mari was built with, in x.x.x format.
- revision()
Returns the ‘v’ revision number of the build.
For example, the revision number of 1.2v3 is 3.
- stage()
Returns the build stage - development, alpha, beta, or release.
- string()
Returns the full build version as a string for display.
- time()
Returns the time that this version was built.
- Returns:
str– The build time as a string, in 24 hour HH-MM format.
- class mari.Application
Bases:
objectThis object handles basic operations to be performed on the entire application.
Example Code
>>> # This example prints out "Hello World" to the application log >>> import mari >>> mari.app.log("Hello World")
Alias
app
- BOTTOM_TOOLBAR_AREA = 8
.
- Type:
int
- CANVAS = 0
.
- Type:
int
- class DropTargetArea
Bases:
objectIndicates an UI area for custom drop target.
- CANVAS = 0
.
- Type:
int
- IMAGE_MANAGER = 2
.
- Type:
int
- LAYER_STACK = 3
.
- Type:
int
- NODE_GRAPH = 4
.
- Type:
int
- SHELF = 1
.
- Type:
int
- IMAGE_MANAGER = 2
.
- Type:
int
- LAYER_STACK = 3
.
- Type:
int
- LEFT_TOOLBAR_AREA = 1
.
- Type:
int
- NODE_GRAPH = 4
.
- Type:
int
- RIGHT_TOOLBAR_AREA = 2
.
- Type:
int
- SHELF = 1
.
- Type:
int
- TOP_TOOLBAR_AREA = 4
.
- Type:
int
- class ToolBarArea
Bases:
objectIndicates an area of the main window to create a tool bar in.
- BOTTOM_TOOLBAR_AREA = 8
.
- Type:
int
- LEFT_TOOLBAR_AREA = 1
.
- Type:
int
- RIGHT_TOOLBAR_AREA = 2
.
- Type:
int
- TOP_TOOLBAR_AREA = 4
.
- Type:
int
- activateMainWindow()
Sets the desktop focus to the Mari window.
The standard focus rules for the OS apply. For example, on Windows the application must have permission to set the foreground window; otherwise, it flashes the taskbar icon instead.
See also
MSDN: SetForegroundWindow() (for Windows)
- addTab(Name, Widget)
Adds a custom tab to the main window.
Users can add custom tabs to the tab bar on the main window. The user is responsible for enabling and disabling these tabs when required.
- Parameters:
Name (str) – The name of the new tab. This will appear in the tab bar
Widget (QWidget) – The widget for the new tab
- Raises:
ValueError – Raised if the name or widget were invalid.
See also
removeTab()
- autosaveReset()
This is emitted when the application autosave is reset.
- autosaveTriggered(ScheduledTime)
This is emitted when the application autosave is triggered.
We call the autosave manager several times at various places throughout the application. The autosave manager is responsible to maintain the current time and when the autosave should next happen and update the timer accordingly. This means that we could call the autosave manager a hundred times and only one call will get through at the scheduled time. This makes the autosaving efficient. To that end, if the autosave call is not completed (because it’s not yet time), we return the scheduled time as a string. Otherwise, if the call does go through and an autosave is performed, we return an empty string here.
- Parameters:
ScheduledTime (str) – This is the time when the autosave is scheduled next.
- backgroundJobCaption(JobID)
Returns the caption for the background job ID.
- Parameters:
JobID (int) – The ID of the job to query the caption.
- Returns:
str– The caption for the background job ID.
- backgroundJobIDs()
Returns the list of job IDs for background jobs.
- Returns:
list of
int– The list of job IDs for background jobs.
- backgroundJobsRunning(AreJobsRunning)
This is emitted when Mari begins and end background processing of jobs.
Marican run multiple jobs in the background while the user is working. These can be tasks like exporting or importing images or performing long running processing. This signal informs the user whenMaristarts or end processing background tasks. This is only emitted as True whenMarigoes from a state where no background jobs are running to running background jobs. IfMariis currently running background jobs and new jobs are added this signal is not emitted.#Print out a message when background jobs start or stop def printRunning(a): print('Background Job Running ', a) mari.utils.connect(mari.app.backgroundJobsRunning, printRunning)
- Parameters:
AreJobsRunning (bool) – True if background jobs are now scheduled, or False if there are no more background jobs
- canceledProcessing()
This is emitted when the user cancels a long-running job.
Note that this is the signal version. The matching function call is
wasProcessingCanceled().Avoid immediately showing GUI elements in response to this signal. The application will not be processing user input at this stage, and may become unresponsive if a blocking element (such as a message box) is displayed.
See also
endingProcessing, startingProcessing, wasProcessingCanceled()
- canvasHeight()
Get the current height of the canvas area.
- canvasWidth()
Get the current width of the canvas area.
- captureDesktop()
Captures a pixmap of the desktop and returns it.
- Returns:
QPixmap– A QPixmap containing the desktop image
- clearScriptOutput()
Clears the script console output.
- commandPortEnabled()
Indicates whether the command port is currently enabled.
- Returns:
bool– True if the command port is ready to accept connections, or false if not
- commandPortNumber()
Returns the port number that the command port will accept connections on.
See also
enableCommandPort()
- createCustomDisplayWidget(Name, OffscreenBufferWidth, OffscreenBufferHeight, Widget)
Creates a custom display widget into which Display Render Plugin can render.
- Parameters:
Name (str) – The name of the custom display widget to create
OffscreenBufferWidth (int) – The width of the offscreen buffer inside the custom display widget.
OffscreenBufferHeight (int) – The height of the offscreen buffer inside the custom display widget.
Widget (QWidget) – The PySide QWidget object into which the custom display widget is created.
- createToolBar(Name, Area='TOP_TOOLBAR_AREA', IsVisible=True)
Creates a custom toolbar and adds it to the main window.
Users can add custom toolbars to the main window. The user is responsible for enabling and disabling these toolbars when required.
- Parameters:
Name (str) – The name of the new toolbar
Area (ToolBarArea, optional) – The area of the main window to place the toolbar in. Defaults to TOP_TOOLBAR_AREA.
IsVisible (bool, optional) – Whether the toolbar is initially visible. Defaults to True.
- Raises:
ValueError – Raised if the name was invalid, or a toolbar with the given name already exists.
- Returns:
ToolBar– The newly-created toolbar.
See also
deleteToolBar()
- currentMeshPathInGeoLoader()
Returns the mesh path currently displayed in the GeoEntity creation dialog.
- Returns:
str– the mesh path currently displayed in the GeoEntity creation dialog
- decryptString(Passphrase, CypherText)
Decrypt a string. param Passphrase the decryption key param CyperText the text to decrypt.
- Parameters:
Passphrase (str)
CypherText (str)
- Returns:
str– The decrypted string
- deleteToolBar(Name)
Removes a custom tab from the main window.
- Parameters:
Name (str) – The name of the tab to remove
- Raises:
ValueError – Raised if no tab with the given name was found
- enableCommandPort(Enabled)
Enables or disables the command port.
After enabling,
Mariwill accept connections on the specific command port.- Parameters:
Enabled (bool)
See also
commandPortNumber()
- encryptString(Passphrase, CypherText)
Encrypt a string. param Passphrase the encryption key param CyperText the text to encrypt.
- Parameters:
Passphrase (str)
CypherText (str)
- Returns:
str– The encrypted string
- endingProcessing()
This is emitted when all long-running jobs have finished.
Note that startingProcessing is emitted for each job that begins, but endingProcessing is only emitted once, when all active jobs have completed.
See also
canceledProcessing, startingProcessing
- executeDialog(Dialog)
Execute a dialog widget.
Due to issues with modal dialogs on OSX,
Marihandles dialog opening in a special way. This allows dialogs created from the Python API to be executed safely across all platforms.- Parameters:
Dialog (QDialog) – The dialog to execute
- Returns:
int– The result code of the dialog’s execution.
- exit(ResultCode=0, ConfirmIfProjectModified=True)
Exits Mari.
This is the same as
quit(), but allows the caller to specify a result code.- Parameters:
ResultCode (int, optional) – The result code to return to the application’s caller. Defaults to 0.
ConfirmIfProjectModified (bool, optional) – When set to true (the default), a confirmation dialog will be shown if a project is open and needs saving. When set to false, this exits without confirmation. Defaults to True.
Note
When running in terminal mode, the project will always be closed without confirmation.
- exiting()
This is emitted just before Mari exits.
The signal will only be emitted if the user accepts any confirmation dialogs (such as the save project before closing dialog). If so, the project will be closed, and then the signal will be emitted before any further shut down processing is performed.
For example, it is safe to perform project maintenance operations in response to this signal if desired.
- findToolBar(Name)
Returns the tool bar with the given name, or NULL if not found.
- Parameters:
Name (str)
- Returns:
ToolBar– The tool bar with the given name, or NULL if not found.
- fullScreenChanging(FullScreen)
This is emitted when the full screen state of the main window is about to change.
- Parameters:
FullScreen (bool) – True if the main window is becoming full screen, or false if it is becoming windowed.
- geometry()
Returns the geometry of the main window.
- Returns:
QRect– The geometry of the main window.
- getGeoPluginAttribute(Key)
Gets a geo plugin attribute. The attributes get passed to the CAPI. param Key The key of the attribute.
- Parameters:
Key (str)
- hasPendingPortCommands()
Returns whether any commands have been received by the command port but not yet executed.
- Returns:
bool– True if any commands are pending, or false if not
- inRestrictedVersion()
Indicates whether the app is running in a restricted version (i.e, Minion or non commercial mode)
This indicates whether the application is run in a restricted mode (Indie or non commercial mode).
- Returns:
bool– True if the app has restrictions.
- inTerminalMode()
Indicates whether the app is running in terminal mode.
This includes interactive terminal mode (“mari -t”) and execute mode (“mari -x”).
- Returns:
bool– True if the app is in terminal mode, or false if not.
- isBackgroundJobFinished(JobID)
Returns whether the job of the given job ID has finished running in the background.
- Parameters:
JobID (int) – The ID of the job to check the status.
- Returns:
bool– Whether the job of the given job ID has finished running in the background.
- isFullScreen()
Returns whether the main window is set to full screen.
- Returns:
bool– True if the main window is covering the full screen, or false if not.
- isMaximized()
Returns whether the main window is maximized.
- Returns:
bool– True if the main window is maximized, or false if not.
- isMinimized()
Returns whether the main window is minimized.
- Returns:
bool– True if the main window is minimized, or false if not.
- isProcessing()
Returns whether or not a long processing operation is active.
This will perform a poll of the processing state. It is advisable to use the
startingProcessing()andendingProcessing()signals to track processing operations in a non-blocking way.- Returns:
bool– True if a long processing operation is active or false otherwise.
See also
progress(), progressDescription(), startingProcessing(), endingProcessing()
- isRunning()
Returns whether the application is currently running.
This is currently only for internal use.
- Returns:
bool– True when Mari is running (currently in all practical cases for users), or false in some special internal cases such as documentation generation.
- isSafeFeature_BypassUserEnvironmentResourceKeys_Enabled()
Indicates whether the app is running in safe mode at a level where we want to bypass any user environment resource key values settings.
- Returns:
bool– True if the app is in safe mode, or false if not.
- lastDropData()
Returns the data from latest drop.
Use mari.utils.ui.registerDropDataCallback for registering of custom drop event callbacks
- Returns:
variant– the dict of drop data MimeType : The mime type of drop dataData : A QMimeData object
DropTarget : The target UI component of the drop
ContextualInfo : The contexual data of the drop in a dict
- launchArgs()
Returns the entire argument list that was passed into the application when launched.
- Returns:
list of str– List of arguments the application was launched with.
- launchDir()
Returns the original directory in which the application was launched from.
- Returns:
str– Path to the directory the application was launched from.
- layoutLoaded(Filename)
This is emitted when a layout is loaded.
- Parameters:
Filename (str) – The path to the file that was loaded
- layoutSaved(Filename)
This is emitted when a layout is saved.
- Parameters:
Filename (str) – The path to the file the layout was saved to
- loadLayout(Filename)
Loads layout settings from the specified file.
- Parameters:
Filename (str) – The file to load the layout from
- Raises:
ValueError – Raised if Filename is invalid.
IOError – Raised if unable to read from Filename.
- log(Message, MessageType='QtInfoMsg', FileName='str', Line=-1)
Writes the given message to the log file for the application.
In verbose mode, the message will also appear in the terminal, in the same way as many application debug messages.
- Parameters:
Message (str) – The message to write
MessageType (QtMsgType, optional) – The type of message to write. QtDebugMsg will only be written if
Mariis started with -logall flag. QtInfoMsg or greater will be displayed in the log. Defaults to QtInfoMsg.FileName (str, optional) – If non-empty, this will show as the originating file name in the log rather than the real file name. Defaults to empty. Defaults to str.
Line (int, optional) – If 0 or greater, this will show as the originating line in the log rather than the real line number. Defaults to -1. Defaults to -1.
- logFileName()
Returns the log file that Mari will be writing to.
- Returns:
str– The log full file name.
- maximize()
Maximizes the main window.
- minimize()
Minimizes the main window.
- numProcessingSteps()
Returns he number of steps to be performed in the current long running processing operation.
This is only valid if a processing operation is active.
- Raises:
RuntimeError – Raised if there is no processing operation active.
- Returns:
int– The number of steps to be performed in the processing.
See also
progress(), progressDescription(), startingProcessing(), endingProcessing()
- onProgress(Progress)
This is emitted to update the progress of a long-running job.
- Parameters:
Progress (int) – The progress of the currently running job, as an integer between 0 and NumSteps, inclusive.
- popupsAllowed()
Returns whether popups such as dialogs and message boxes are allowed.
When running in a non-interactive mode, such as terminal mode, or performing a long non-blocking batch of processing, it’s important that popups are not displayed.
- Returns:
bool– True when popups can be shown to the user, or false because Mari is being run in a non-interactive mode or is currently running a series of processes which shouldn’t be blocked for user input.
- processEvents(IncludeInputEvents=True)
Processes events such as redrawing the screen and updating the GUI.
This is for use during long running operations.
This function is called automatically by many of the processing functions, such as
setProgress(). If you perform other long-running operations, or do not callsetProgress()very often, consider calling this function manually to improve the interactivity of the application.- Parameters:
IncludeInputEvents (bool, optional) – Determine whether to process input events, if False then only internal events will be processed and any pending user input will remain in the event queue. Defaults to True. Defaults to True.
See also
canceledProcessing(), setProgress(), setProgressDescription(), startProcessing(), stepProgress(), stopProcessing(), wasProcessingCanceled()
- progress()
Returns the progress of the current long running processing operation.
This is only valid if a processing operation is active.
- Raises:
RuntimeError – Raised if there is no processing operation active.
- Returns:
int– The number of steps completed in this processing operation.
See also
processEvents(), canceledProcessing(), setProgressDescription(), startProcessing(), stepProgress(), stopProcessing(), wasProcessingCanceled()
- progressDescription()
Returns the process description of the current long running processing operation.
This is only valid if a processing operation is active.
- Raises:
RuntimeError – Raised if there is no processing operation active.
- Returns:
str– The user-readable description of the process.
See also
processEvents(), canceledProcessing(), startProcessing(), stepProgress(), stopProcessing(), wasProcessingCanceled()
- progressDescriptionChanged(NewDescription)
This is emitted to update the description of a long-running job.
- Parameters:
NewDescription (str) – A description of the job for display.
- quit(ConfirmIfProjectModified=True)
Quits Mari.
This is the same as
exit().- Parameters:
ConfirmIfProjectModified (bool, optional) – When set to true (the default), a confirmation dialog will be shown if a project is open and needs saving. When set to false, this exits without confirmation. Defaults to True.
Note
When running in terminal mode, the project will always be closed without confirmation.
- registerCustomDropMimeType(MimeType, Target)
Registers the custom MIME type for accepting a drag & drop at the given Target.
Use mari.utils.ui.registerDropDataCallback for registering of custom drop event callbacks
- Parameters:
MimeType (str) – the MIME type to support custom drag & drop
Target (DropTargetArea) – the target UI component at which the custom drag & drop is accepted
- registerGeoPluginWidget(FileExtensions, Widget)
Registers the custom Geometry Plugin widget to display in the GeoEntity creation tab.
- Parameters:
FileExtensions (list of str) – The list of file extensions to display the given widget for
Widget (QWidget) – The custom widget to register
- removeTab(Name)
Removes a custom tab from the main window.
- Parameters:
Name (str) – The name of the tab to remove
- Raises:
ValueError – Raised if no tab with the given name was found
See also
addTab(), tabNames()
- restore()
Restores the main window to the size it was before minimize, maximize or full screen.
- restoreCursor()
Restores cursor.
Restores the cursor after calling setBusyCursor.
See also
setBusyCursor()
- resumeProcessing()
Resumes a temporarily suspended long processing operation.
Call this function as soon as the user interaction that the processing was suspended for has been performed.
See also
suspendProcessing()
- saveLayout(Filename)
Saves the current layout settings to the specified file.
- Parameters:
Filename (str) – The file to save the layout to
- Raises:
ValueError – Raised if Filename is invalid.
IOError – Raised if unable to write to Filename.
- setActiveTab(Name)
Sets the currently active, visible tab.
- Parameters:
Name (str) – The name of the tab to make active
- Raises:
ValueError – Raised if no tab with the given name was found
See also
tabNames()
- setCommandPortNumber(Number)
Sets the port number that the command port should accept connections on.
This will close any existing connections and restart the command port on a new socket.
- Parameters:
Number (int)
- setFixedCanvasSize(Width, Height)
Set the current canvas area to a fixed size.
This fixes the canvas area to a certain size, preventing the user from modifying it in any way, until unfixed. Passing in an invalid size will unfix the canvas area and enable the user to modify the size again.
- Parameters:
Width (int) – The width to fix the canvas area too, or zero or less to unfix.
Height (int) – The height to fix the canvas area too, or zero or less to unfix.
- setFullScreen(FullScreen)
Sets the full screen state of the main window.
- Parameters:
FullScreen (bool) – True will set
Marito full screen mode; false will set it to normal windowed behavior.
- setGeoPluginAttribute(Key, Value)
Sets a geo plugin attribute. The attributes get passed to the CAPI. param Key The key of the attribute param Value The value of the attribute.
- Parameters:
Key (str)
Value (variant)
- setGeometry(Geom)
Sets the geometry of the main window.
- Parameters:
Geom (QRect) – The new geometry of the main window.
- setNukeConnectionActive(Active, ConnectionInfo='str')
Sets the status of the Nuke connection indicator.
- Parameters:
Active (bool) – True to show the indicator, or false to hide it
ConnectionInfo (str, optional) – Text info describing the connection. This will be displayed in the status bar as “Connected to Nuke” followed by the given text. Defaults to str.
- setProgress(Progress)
Provides an indication of the progress of a long running processing operation.
This will update the status bar on the main window.
This function will automatically call
processEvents()once to ensure that the change to the status bar is displayed to the user.- Parameters:
Progress (int) – The number of steps completed in this processing operation. This should be at least zero and at most the value passed as NumSteps to
startProcessing().
See also
processEvents(), canceledProcessing(), setProgressDescription(), startProcessing(), stepProgress(), stopProcessing(), wasProcessingCanceled()
- setProgressDescription(Description)
Sets the process description displayed in the status bar.
This will update the status bar on the main window replacing the description provided to
startProcessing().This function will automatically call
processEvents()once to ensure that the change to the status bar is displayed to the user.- Parameters:
Description (str) – A user-readable description of the process - e.g. “Processing Data”. This will be displayed in the status bar.
See also
processEvents(), canceledProcessing(), startProcessing(), stepProgress(), stopProcessing(), wasProcessingCanceled()
- setSuppressPopups(Suppress)
Set whether popups should be temporarily suppressed or resumed.
Allows long running operations to disable popups, similar to how non-interactive and terminal modes work, so that they never get blocked waiting for user input. This also stops popups from suddenly appearing over other applications that the user is currently interacting with and interrupting them.
- Parameters:
Suppress (bool) – True when popups need to be temporarily suppressed and can’t be shown to the user, or false when they are to be resumed.
- setWaitCursor()
Switches cursor to Qt::WaitCursor.
Switches cursor to Qt::WaitCursor. Restore by calling restoreCursor.
See also
restoreCursor()
- startProcessing(Description, NumSteps=100, CanCancel=False)
Registers the start of a long processing operation.
Marigives the user feedback on the status of long running processes. This method indicates the start of one of these processes. It is a good idea to always start this when processing data.Mariwill display a busy icon, and calls tosetProgress()will update a status bar in the bottom right corner of the application GUI.Calls to
startProcessing()must always be followed by astopProcessing()call. It may also be useful to callprocessEvents()during your processing loop to give the application time to update the GUI.This function will automatically call
processEvents()once to ensure that the new status bar is displayed to the user.- Parameters:
Description (str) – A user-readable description of the process - e.g. “Processing Data”. This will be displayed in the status bar.
NumSteps (int, optional) – The number of steps to be performed in the processing. Calls to setProgress should indicate the number of steps completed. Defaults to 100.
CanCancel (bool, optional) – Set this to true if the action being executed can be safely canceled. Defaults to False.
Attention
If run in the script editor, this function will cause Mari to become non-interactive until stopProcessing() is called, so make sure you call it as part of your script or you will not be able to enter any further commands.
See also
canceledProcessing(), processEvents(), setProgress(), setProgressDescription(), stepProgress(), stopProcessing(), suspendProcessing(), wasProcessingCanceled(), numProcessingSteps()
- startingProcessing(Operation, NumSteps)
This is emitted when a long-running job starts.
- Parameters:
Operation (str) – A description of the job for display.
NumSteps (int) – The number of steps involved in this job
See also
canceledProcessing, endingProcessing
- stepProgress()
Moves forward the progress indicator of a long running processing operation by one step.
This will update the status bar on the main window.
This function will automatically call
processEvents()once to ensure that the change to the status bar is displayed to the user.- Raises:
RuntimeError – Raised if the current progress is already at 100%.
See also
processEvents(), canceledProcessing(), setProgress(), setProgressDescription(), startProcessing(), stopProcessing(), wasProcessingCanceled()
- stopProcessing()
Registers the end of a long processing operation.
This should always be called after
startProcessing().See also
processEvents(), canceledProcessing(), setProgress(), setProgressDescription(), startProcessing(), stepProgress(), wasProcessingCanceled()
- suppressPopups()
Returns whether popups have been temporarily suppressed.
Some long running operations will disable popups, similar to how non-interactive and terminal modes work, so that they never get blocked waiting for user input.
- Returns:
bool– True when popups have been temporarily suppressed and can’t be shown to the user.
- suspendProcessing()
Temporarily suspends a long processing operation.
Normally, long-running processing operations ignore mouse and keyboard input from the user while running. Use this function to suspend the processing temporarily, and allow mouse and keyboard input again, if input is required from the user - such as in the case of a message box querying the user for action.
Make sure you call
resumeProcessing()again as soon as possible, or the status bar will not be updated, and users may be able to interfere with processing operations by making changes through the GUI at the same time.See also
resumeProcessing()
- tabNames()
Lists the available tabs in the main window.
See also
addTab(), removeTab(), setActiveTab()
- toggleFullScreen()
Toggle the main window between full screen and windowed states.
- toolBar(Name)
Returns the tool bar with the given name.
- Parameters:
Name (str)
- Raises:
ValueError – Raised if no tool bar with the given name exists.
- Returns:
ToolBar– The tool bar with the given name
- toolBarsCreated()
This is emitted when the window tool bars are created.
- version()
Returns an object that contains version information for Mari.
- wasProcessingCanceled()
Checks to see if the user has chosen to cancel a long-running process.
Users can cancel many long-running processes by clicking the ‘X’ button on the progress bar when one is present, or by pressing the “Escape” key.
Note that this is the function version. There is a matching signal called
canceledProcessing().- Returns:
bool– True if the current processing should be canceled, or false otherwise
Note
This function should be called sporadically, because calling this method may also call processEvents() and slow down processing if called continuously.
See also
processEvents(), canceledProcessing, setProgress(), setProgressDescription(), startProcessing(), stepProgress(), stopProcessing()
- class mari.BackdropNode
Bases:
NodeRepresents a special backdrop that can visually group nodes.
Example Code
This example obtains a
BackdropNodefrom the node graph of the current geo entity and>>> for node in nodeGraph.nodeList(): ... if node.isBackdropNode(): ... mari.app.log("Found BackdropNode '%s'")
- childNodes()
Returns the nodes that belong in this backdrop.
- Raises:
RuntimeError – Raised if the node has no presence in a node graph.
- Returns:
list of
Node– List of Node
- isBackdropNode()
Returns whether this node is a BackdropNode.
- Returns:
bool– Whether this node is a BackdropNode
- portListMode()
No description
- selectChildNodes()
Selects the nodes that belong in this backdrop.
- Raises:
RuntimeError – Raised if the node has no presence in a node graph.
- setNodeGraphSize(Size)
Sets the size of this node in its NodeGraph.
Resizing will stretch/shrink the node from the top left corner of the node bounding box.
- Parameters:
Size (QSizeF) – The size to resize the node to.
- Raises:
RuntimeError – Raised if the node cannot have its size set.
- setPortListMode(Mode)
No description
- Parameters:
Mode (PortListMode)
- class mari.BakeItem
Bases:
MetadataRepresents a Bake Item to submit to the baker. Fill the parameters by the Metadata interface.
>>> import mari >>> recipe = mari.bakery.allRecipes()[0] >>> bakeItem = recipe.createBakeItem() >>> bakeItem.setMetadata("Samples", 1000)
- EDGE_BLEED_OFF = 0
No edge bleed applied to output textures.
- Type:
int
- EDGE_BLEED_ON_FAST = 1
Faster and lower quality edge bleed algorithm used.
- Type:
int
- class EdgeBleedMode
Bases:
objectHow to Bleed the pixels around the bake.
- EDGE_BLEED_OFF = 0
No edge bleed applied to output textures.
- Type:
int
- EDGE_BLEED_ON_FAST = 1
Faster and lower quality edge bleed algorithm used.
- Type:
int
- class HighPolySearchMode
Bases:
objectModes for finding the high poly mesh.
- SEARCH_CLOSEST = 0
Fire a ray forwards and a ray backwards from the low resolution mesh to the high resolution mesh. Use the closest hit.
- Type:
int
- SEARCH_NORMAL_CAGE = 1
Fire a ray back towards the high resolution mesh from a point projected out from the low resolution mesh.
- Type:
int
- SEARCH_CLOSEST = 0
Fire a ray forwards and a ray backwards from the low resolution mesh to the high resolution mesh. Use the closest hit.
- Type:
int
- SEARCH_NORMAL_CAGE = 1
Fire a ray back towards the high resolution mesh from a point projected out from the low resolution mesh.
- Type:
int
- cageDistance()
Return the cage distance.
- Returns:
float– float
- cageDistanceChanged()
No description
- edgeBleedMode()
Return thes edge bleed mode.
- Returns:
EdgeBleedMode– EdgeBleedMode
- edgeBleedModeChanged()
No description
- edgeBleedModeList()
Returns the list of supported edge bleed modes.
- Returns:
list of
EdgeBleedMode– List of BakeItem.EdgeBleedMode
- edgeBleedModeString(EdgeBleedMode)
Returns the input edge bleed mode as string.
- Parameters:
EdgeBleedMode (EdgeBleedMode) – The EdgeBleedMode.
- Returns:
str– String
- edgeBleedModeStringChanged()
No description
- edgeBleedModeStringList()
List of string to allow the UI to display and select from.
- Returns:
list of str– List of strings
- edgeBleedModeStringTooltip()
Returns a tooltip string.
- Returns:
str– String
- highPolySearchMode()
Return the high poly search mode.
- Returns:
HighPolySearchMode– HighPolySearchMode
- highPolySearchModeChanged()
No description
- imageFormat()
Returns the image format to process.
- Returns:
Image.Depth– mari.Image.Depth
- imageFormatChanged()
No description
- imageFormatList()
Returns the list of supported image formats.
- Returns:
list– List of Image::Depth
- imageFormatString(Format)
Returns the specified image format as a string.
- Parameters:
Format (Image.Depth) – The format.
- Returns:
str– String
- imageFormatStringChanged()
No description
- imageFormatStringList()
List of string to allow the UI to display and select from.
- Returns:
list of str– StringList
- imageFormatStringTooltip()
Returns a tooltip string.
- Returns:
str– String
- imageSize()
Returns the image size to process.
- Returns:
QSize– QSize
- imageSizeChanged()
No description
- imageSizeString(Size)
Returns the specified Size as a string.
- Parameters:
Size (QSize) – The size.
- Returns:
str– String
- imageSizeStringChanged()
No description
- imageSizeStringList()
Returns all images sizes as a list of strings.
- Returns:
list of str– StringList
- imageSizeStringTooltip()
Returns a tooltip string.
- Returns:
str– String
- name()
Returns the name of the BakeItem.
- Returns:
str– QString
- nameChanged()
No description
- nameTooltip()
Returns a tooltip string.
- Returns:
str– String
- recipe()
Returns the original recipe this Bake Item was created from.
- Returns:
BakeRecipe– The original recipe this Bake Item was created from
- setCageDistance(CageDistance)
Sets the cage distance.
- Parameters:
CageDistance (float)
- setEdgeBleedMode(EdgeBleedMode)
Sets the edge bleed mode.
- Parameters:
EdgeBleedMode (EdgeBleedMode) – The mode.
- setEdgeBleedModeString(EdgeBleedModeString)
Sets the edge bleed mode.
- Parameters:
EdgeBleedModeString (str)
- setHighPolySearchMode(NewMode)
Sets the high poly search mode.
- Parameters:
NewMode (HighPolySearchMode)
- setImageFormat(Format)
Sets the image format to process.
- Parameters:
Format (Image.Depth) – the depth format.
- setImageFormatString(ImageFormatString)
Sets the image format to process.
- Parameters:
ImageFormatString (str) – The image format string.
- setImageSize(Size)
Sets the image size to process.
- Parameters:
Size (QSize) – The image size.
- setImageSizeString(Size)
Sets the image size to process.
- Parameters:
Size (str) – The size.
- setName(Name)
Sets the name of the BakeItem.
- Parameters:
Name (str) – The name to set.
- class mari.BakePointLayer
Bases:
LayerBakePoint layers contain an image for each patch that can be painted directly.
You can access all types of layers from their containing
Channelobjects - for example:channel.layerList()You can check for
BakePointLayerobjects by callingLayer::isBakePointLayer():This examples shows how to create a Bake Point layer and checks if it’s a BakePoint layer
>>> import mari >>> channel = mari.geo.current().currentChannel() >>> bakePointLayer = channel.createBakePointLayer("Test") >>> bakePointLayer.isBakePointLayer() True
- bake()
Bakes the result at this layer into the image set.
The result of baking can be obtained by
bakedResult().
- bakedResult()
Returns the image set of baked result.
- Raises:
RuntimeError – Raised if the image set cannot be found.
- Returns:
ImageSet– The image set this layer holds as baked result.
- deleteBakedResult()
Deletes the baked result.
- hasBakedResult()
Returns whether there is baked result.
- isBakedResultUpToDate()
Returns whether the baked result is up to date.
If there is no baked result yet, this will return False.
- setUseBaked(UseBaked)
Sets whether this layer should use the baked result if available.
- Parameters:
UseBaked (bool)
Deprecated
This function will be removed in a future version. This is currently the same as running setEnabled(), please use that instead.
- useBaked()
Returns whether this layer should use the baked result or not.
Deprecated
This function will be removed in a future version. This is currently the same as running isEnabled(), please use that instead.
- class mari.BakePointNode
Bases:
PaintNodeRepresents node speciailizing in baking result of intermediate point in the NodeGraph.
Example Code
This example shows how to create a
BakePointNode>>> import mari >>> nodeGraph = mari.geo.current().nodeGraph() >>> paintNode = nodeGraph.createBakePointNode( 1024, 1024, 8, mari.Color(1.0,1.0,0.0,1.0) )
This example obtains a
BakePointNodefrom the node graph of the current geo entity and>>> for node in nodeGraph.nodeList(): ... if node.isBakePointNode(): ... mari.app.log( "Found BakePointNode : "+node.nodeName() )
The following example demonstrates the usage of connecting and using bake point signals
>>> ng = mari.geo.current().nodeGraph() >>> >>> cs = mari.current.channel().colorspaceConfig() >>> cs.setColorspace(cs.COLORSPACE_STAGE_NATIVE, "Gamma2.2") >>> >>> b = ng.createBakePointNode(512, 512, 16, None, mari.Image.FileSpace.FILESPACE_VECTOR, cs) >>> >>> def test_exportPathChanged(a): >>> print("export path changed : ", a) >>> mari.utils.connect(b.exportPathChanged, test_exportPathChanged) >>> >>> def test_bakedStateChanged(a): >>> print("baked state changed", a) >>> mari.utils.connect(b.bakedStateChanged, test_bakedStateChanged)
The following example demonstrates exporting baked textures to disk
>>> b.setExportPath("/tmp/test.tiff") >>> print(b.exportPath()) >>> >>> bakeOutOfDate = False >>> options = mari.Image.SaveOptions.DEFAULT_OPTIONS >>> uVIndexList = [] >>> fileOptions = {} >>> b.exportBakedResult(bakeOutOfDate, options, uVIndexList, fileOptions)
- BAKEPOINTSTATE_DIRTY = 1
The node has detected some changes.
- Type:
int
- BAKEPOINTSTATE_NOT_AVAILABLE = 0
This corresponds to an unbaked node.
- Type:
int
- BAKEPOINTSTATE_UP_TO_DATE = 2
The node is up to date.
- Type:
int
- class BakePointNodeState
Bases:
objectThis describes the state of the bake point.
- BAKEPOINTSTATE_DIRTY = 1
The node has detected some changes.
- Type:
int
- BAKEPOINTSTATE_NOT_AVAILABLE = 0
This corresponds to an unbaked node.
- Type:
int
- BAKEPOINTSTATE_UP_TO_DATE = 2
The node is up to date.
- Type:
int
- applyFilterCollection()
Applies the filters to the baked result.
- Raises:
RuntimeError – Raised if the node has no bake result.
- bake()
Bakes the result at this node into the image set.
The result of baking can be obtained by
bakedResult().
- bakedResult()
Returns the image set of baked result.
- Raises:
RuntimeError – Raised if the image set cannot be found.
- Returns:
ImageSet– The image set this node holds as baked result.
- bakedStateChanged(State)
This is emitted when the bake state of the node changes.
- Parameters:
State (BakePointNode.BakePointNodeState)
- deleteBakedResult()
Deletes the baked result.
- depth()
Returns the depth of this BakePoint node.
- Returns:
Image.Depth– The depth of this BakePoint node
- exportBakedResult(BakeOutOfDate, UVIndexList, Options='Image.DEFAULT_OPTIONS', FileOptions='variant')
Exports the baked result of this node to a file location, specified by the node property “Export Path”.
- Parameters:
BakeOutOfDate (bool) – Flag to specify whether to bake and then export, in case the node result is out of date.
Options (Image.SaveOptionsFlags, optional) – Pass in a value other than the default to turn on an option, such as disabling “small uniforms”. See
Image::SaveOptions. Defaults to Image.DEFAULT_OPTIONS.UVIndexList (list of
int) – Pass in a list of zero-based UV indices if desired to specify the patches to export images for. If not specified or empty, images will be exported for all indices. The UDIM for a patch is the zero-based UV index plus 1001.FileOptions (variant, optional) – This is a key/value map of optional parameters passed to the file writer plugin. Defaults to variant.
- Raises:
RuntimeError – Raised if the node has no bake result, or no valid export operation found or the export cannot continue due to bake being out of date.
ValueError – Raised if the path and template parameter was empty, or if an invalid UV index was specified.
IOError – Raised if an error occurred with the export process.
- exportOnBake()
Returns whether exporting on bake is on.
- Returns:
bool– Whether exporting on bake is on
- exportPath()
Returns the export path, where the baked textures will be exported to.
- Returns:
str– The export path, where the baked textures will be exported to
- exportPathChanged(Path)
This is emitted when export path changes.
- Parameters:
Path (str)
- filterCollection()
Returns the current filters applied to the baked result.
- Returns:
PostFilterCollection– The filters applied to the bake result
- filterCollectionEnabled()
Returns whether the filter collection is enabled.
- Returns:
bool– Whether the filter collection is enabled.
- geoChannel()
Returns the GeoChannel this BakePointNode is linked to.
- Returns:
GeoChannel– The GeoChannel this BakePointNode is linked to.
- geoChannelName()
Returns the GeoChannel name of this BakePointNode is linked to.
- Returns:
str– The GeoChannel name of this BakePointNode is linked to
- hasBakedResult()
Returns whether there is baked result.
- isBakePointNode()
Returns whether this node is a BakePointNode.
- Returns:
bool– Whether this node is a BakePointNode
- isBakedResultUpToDate()
Returns whether the baked result is up to date.
If there is no baked result yet, this will return False.
- isPaintNode()
Returns whether this node is a PaintNode.
- Returns:
bool– Whether this node is a PaintNode
- limitBake()
Returns whether the limited patch baking is on.
- Returns:
bool– Whether the limited patch baking is on
- limitBakeRange()
Returns the current baking patch range.
- Returns:
UvIndexRangeList– The baking patch range
- setExportOnBake(ExportOnBake)
Sets whether exporting on bake is on.
- Parameters:
ExportOnBake (bool) – Whether exporting on bake is on
- setExportPath(Path)
Sets the export path, where the baked textures will be exported to.
- Parameters:
Path (str) – The export path, where the baked textures will be exported to
- setFilterCollectionEnabled(FilterCollectionEnabled)
Sets whether the filter collection is enabled.
- Parameters:
FilterCollectionEnabled (bool) – whether the filter collection is enabled.
- setGeoChannelName(Alias)
Sets the target of this BakePoint node to the GeoChannel of the given alias.
- Parameters:
Alias (str) – The
GeoChannelalias to set to
- setLimitBake(LimitBake)
Sets whether the limited patch baking is on.
- Parameters:
LimitBake (bool) – Whether the limited patch baking is on
- setLimitBakeRange(LimitBakeRange)
Sets the baking patch range to the given range.
- Parameters:
LimitBakeRange (UvIndexRangeList) – The range to set
- setSyncToGeoChannel(Sync)
Sets whether synchronizing to GeoChannel is on.
- Parameters:
Sync (bool) – Whether synchronizing to
GeoChannelis on
- syncGeoChannel()
Immediately synchronize the bake point to the Geo Channel.
- syncToGeoChannel()
Returns whether synchronizing to GeoChannel is on.
- Returns:
bool– Whether synchronizing to GeoChannel is on
- class mari.BakeRecipe
Bases:
objectRepresents a Baker Recipe for obtaining information about the recipe and allows to create a bake item for the recipe.
>>> import mari >>> recipe = mari.bakery.allRecipes()[0] >>> bakeItem = recipe.createBakeItem() >>> print(recipe.name())
- createBakeItem()
Creates and returns a BakeItem for this recipe.
- Returns:
BakeItem– The BakeItem object for this recipe.
- name()
Returns the name of the recipe.
- Returns:
str– The name of the recipe
- prettyName()
Returns the pretty name of the recipe.
- Returns:
str– The pretty name of the recipe
- class mari.BakeSettings
Bases:
objectObject to hold the list of bakeItems and settings to pass into the bakery.
>>> import mari >>> settings = mari.bakery.newSettings() >>> recipe = mari.bakery.allRecipes()[0] >>> bakeItem = recipe.createBakeItem() >>> settings.addBakeItems([bakeItem], mari.geo.current().versionList(), mari.geo.current().versionList()) >>> settings.setAnimationMode(mari.BakeSettings.AnimationMode.ANIMATION_OFF) >>> settings.setPreviewQuality(mari.BakeSettings.PreviewQuality.PREVIEW_LOW) >>> settings.setOutputPaintNode(True)
- ANIMATION_ALL = 1
Use all animated geometry frames.
- Type:
int
- ANIMATION_OFF = 0
No frame/animated data used.
- Type:
int
- class AnimationMode
Bases:
objectModes for baking animated frames.
- ANIMATION_ALL = 1
Use all animated geometry frames.
- Type:
int
- ANIMATION_OFF = 0
No frame/animated data used.
- Type:
int
- OUTPUT_CHANNEL = 4
Create a new Channel with a paint node containing the baked data.
- Type:
int
- OUTPUT_GEO_CHANNEL = 2
Create a new Geo-Channel containing the baked data.
- Type:
int
- OUTPUT_PAINT_NODE = 1
Create a Paint node containing the baked data.
- Type:
int
- class OutputMode
Bases:
objectAll the possible outputs of the bake results.
- OUTPUT_CHANNEL = 4
Create a new Channel with a paint node containing the baked data.
- Type:
int
- OUTPUT_GEO_CHANNEL = 2
Create a new Geo-Channel containing the baked data.
- Type:
int
- OUTPUT_PAINT_NODE = 1
Create a Paint node containing the baked data.
- Type:
int
- PREVIEW_HIGH = 1024
.
- Type:
int
- PREVIEW_LOW = 256
.
- Type:
int
- PREVIEW_MEDIUM = 512
.
- Type:
int
- class PreviewQuality
Bases:
objectModes for setting resolution quality of preview.
- PREVIEW_HIGH = 1024
.
- Type:
int
- PREVIEW_LOW = 256
.
- Type:
int
- PREVIEW_MEDIUM = 512
.
- Type:
int
- addBakeItems(BakeItems, BakeToVersions, BakeFromVersions)
Sets the bakeItems to bake.
>>> import mari >>> settings = mari.bakery.newSettings() >>> recipe = mari.bakery.allRecipes()[0] >>> bakeItem = recipe.createBakeItem() >>> settings.addBakeItems([bakeItem], mari.geo.current().versionList(), mari.geo.current().versionList())
- Parameters:
BakeItems (list of
BakeItem) – List of bakeItems to bake.BakeToVersions (list of
GeoEntityVersion) – List Of mari.GeoEntityVersion target meshes (cannot be empty)BakeFromVersions (list of
GeoEntityVersion) – List Of mari.GeoEntityVersion source meshes (cannot be empty)
- animationMode()
Return the edge bleed mode.
- Returns:
AnimationMode– AnimationMode
- animationModeChanged(Mode)
Emitted when the animation mode has changed.
- Parameters:
Mode (BakeSettings.AnimationMode) – New animation mode.
- devices()
Returns the names of the raytracing devices to use.
- Returns:
list of
str– List of strings
- devicesChanged(Devices)
Emitted when the specified devices to use change.
- Parameters:
Devices (list of
str) – New list of devices.
- outputChannel()
Returns whether the output channel flag is set.
- Returns:
bool– Boolean
- outputGeoChannel()
Returns whether the output Geo-Channel flag is set.
- Returns:
bool– Boolean
- outputModes()
Return the output mode flags.
- Returns:
OutputModes– OutputModes
- outputPaintNode()
Returns whether the output paint node flag is set.
- Returns:
bool– Boolean
- previewQuality()
Return the preview quality mode.
- Returns:
PreviewQuality– preview quality
- setAnimationMode(NewMode)
Sets the animation mode.
- Parameters:
NewMode (AnimationMode)
- setDevices(Devices)
Sets the raytracing devices to use.
If possible, this function should only receive items returned by bakery.allDevices() .. code-block:
>>> import mari >>> settings = mari.bakery.newSettings() >>> deviceList = mari.bakery.allDevices() >>> settings.setDevices(deviceList[:1]) >>> print(settings.devices())
- Parameters:
Devices (list of
str) – List of strings with the names of the devices to set- Raises:
ValueError – raised if the name of one device can’t be found
- setOutputChannel(Enabled)
Set the output channel flag.
- Parameters:
Enabled (bool) – Specify the state of the output channel flag
- setOutputGeoChannel(Enabled)
Set the output Geo-Channel flag.
- Parameters:
Enabled (bool) – Specify the state of the output Geo-Channel flag
- setOutputModes(Outputs)
Sets the output mode flags.
- Parameters:
Outputs (OutputModes) – Sets which flags should be set for output modes
- setOutputPaintNode(Enabled)
Set the output paint node flag.
- Parameters:
Enabled (bool) – Specify the state of the output paint node flag
- setPreviewQuality(NewMode)
Sets the preview quality.
- Parameters:
NewMode (PreviewQuality)
- class mari.BakeryManager
Bases:
objectUsed to access mesh map baker functionality.
# This example creates a new BakeSettings object, sets it up with the # desired values and sends it to the baker to perform a bake operation >>> import mari >>> settings = mari.bakery.newSettings() >>> settings.setDevices(mari.bakery.allDevices()[:1]) >>> recipes = mari.bakery.allRecipes() >>> bakeItem = recipes[0].createBakeItem() >>> settings.addBakeItems([bakeItem], mari.geo.current().versionList(), mari.geo.current().versionList()) >>> settings.setOutputPaintNode(True) >>> mari.bakery.onBake(settings)
- allDevices()
Returns all the raytracing devices that can be used.
In case of having multiple GPUs of the same model in a single machine, the environment variable MARI_MULTI_GPU_SUPPORT should be set to “True”. This will append the device ID to the device name in order to uniquely identify devices of the same model
- Returns:
list of
str– list of strings with device names
- allRecipes()
Returns all the recipes currently available.
- Returns:
list of
BakeRecipe– list of BakeRecipe instances currently available
- isProcessing()
Returns whether any bakery processing is happening.
The client code should check this before issuing any further processing such as initialization, baking or previewing.
- Returns:
bool– Whether any bakery processing is happeningThe client code should check this before issuing any further processing such as initialization, baking or previewing.
- loadPresets(Path)
Load Bake Items from preset file.
- Parameters:
Path (str)
- Raises:
RuntimeError – if preset file could not be loaded.
- Returns:
list of
BakeItem– List of Bake Items.
- newSettings()
Creates a new object to hold the bake settings.
- Returns:
BakeSettings– Pointer to the BakeSettings object
- onBake(Settings)
Execute a bake operation.
- Parameters:
Settings (BakeSettings)
- onBakeQuit()
Stop bake operation.
- progressError(Error)
Emitted when there is an error during baking.
- Parameters:
Error (str)
- progressIncrement()
Emitted every time progress is made on the bake.
- progressStart(Name, Maximum)
Emitted when baking starts.
- Parameters:
Name (str) – of the Geometry being baked
Maximum (int) – Total number of processes that will be run
- progressStop()
Emitted when baking stops.
- recipe(Name)
Returns the recipe with the given name.
- Parameters:
Name (str) – of the recipe to find
- Returns:
BakeRecipe– BakeRecipe instance if found or None if not
- class mari.BakeryPreview
Bases:
WidgetBase- clear()
Clears the preview and start displaying the default checkerboard pattern.
- paused()
Returns if the preview is paused.
- setBakeSettings(Settings)
Sets the BakeSettings object.
- Parameters:
Settings (BakeSettings)
- setPaused(Paused)
Sets the paused state of this preview.
- Parameters:
Paused (bool) – the paused state of this preview.
- setup()
Sets up the preview by preparing the device and resources.
- update()
Updates the preview by rendering the preview.
- class mari.BroadcastTeleportNode
Bases:
TeleportNodeRepresents a broadcast teleport node.
- connectedReceiverNodeList()
Returns any Receiver Teleport Nodes which are listening on the channel this node is broadcasting on.
- Returns:
list of
ReceiverTeleportNode– A list of ReceiverTeleportNodes.
- setChannelName(ChannelName)
Sets the channel this node uses.
- Parameters:
ChannelName (str) – The channel this node uses.
- Raises:
ValueError – Raised if the given channel is invalid.
- class mari.Camera
Bases:
MetadataProvides 3D camera settings.
Example Code
>>> # This example obtains the camera of the current canvas view >>> import mari >>> camera = mari.canvases.current().camera() >>> mari.app.log("Position = "+str(camera.translation().asTuple()))
- ORTHOGRAPHIC = 1
2D Orthographic of 3D geometry
- Type:
int
- PERSPECTIVE = 0
3D Perspective of 3D geometry
- Type:
int
- class Type
Bases:
objectThese are the viewing modes.
- ORTHOGRAPHIC = 1
2D Orthographic of 3D geometry
- Type:
int
- PERSPECTIVE = 0
3D Perspective of 3D geometry
- Type:
int
- UV = 2
2D Orthographic of UV space
- Type:
int
- UV = 2
2D Orthographic of UV space
- Type:
int
- adjustClipPlanes()
Adjusts the Near and Far clip planes so they contain the current geometry.
- attributeChanged()
This is emitted when the camera has had an internal attribute changed.
For example, this can be triggered by changes to the field of view, near or far clip plane, type, or name.
- farClip(Frame=0)
Returns the far clip plane.
- Parameters:
Frame (int, optional)
- fieldOfView(Frame=0)
Returns the field of view.
- Parameters:
Frame (int, optional)
- Raises:
RuntimeError – Raised if the camera is not a perspective camera.
- Returns:
float– The field of view in degrees
- fieldOfViewX(Frame=0)
Returns the horizontal field of view.
- Parameters:
Frame (int, optional)
- Raises:
RuntimeError – Raised if the camera is not a perspective camera.
- Returns:
float– The field of view in degrees
- fieldOfViewY(Frame=0)
Returns the vertical field of view.
- Parameters:
Frame (int, optional)
- Raises:
RuntimeError – Raised if the camera is not a perspective camera.
- Returns:
float– The field of view in degrees
- isAnimated()
Returns whether the camera is animated.
- Returns:
bool– True if the camera can be accessed for animation data, or false otherwise.
- lookAt(Frame=0)
Returns the present look-at point.
- Parameters:
Frame (int, optional)
- Returns:
VectorN– The 3D position the camera is looking at
- moved()
This is emitted after the camera has been moved: translated, scaled or rotated.
- name()
Returns the name of the camera.
- Returns:
str– The name of the camera.
- nearClip(Frame=0)
Returns the near clip plane.
- Parameters:
Frame (int, optional)
- perspectiveAspectRatio()
Returns the camera perspective aspect ratio.
- Raises:
RuntimeError – Raised if the camera is not a perspective camera.
- projectionMatrix(AspectRatio=0.0, Frame=-1)
Returns the entire 4x4 projection matrix of the camera.
- The result will be a tuple of four tuples of floats representing the rows of the matrix - for example:
((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), (0.0, 0.0, 0.0, 1.0))
The matrix will use the right-handed coordinate system.
- Parameters:
AspectRatio (float, optional) – The ratio of width to height of the viewport. If not supplied (or zero), it defaults to the camera’s
viewportAspectRatio(). Defaults to 0.0.Frame (int, optional) – The frame number to return the matrix for, or -1 (the default) to return the value for the current frame. Defaults to -1.
- Returns:
variant– The camera’s view matrix, as described above
- scale()
Returns the camera scale.
- Returns:
float– The camera view scale
- setAnimated(Animated)
Sets if the camera is animated.
- Parameters:
Animated (bool)
- setFarClip(FarClip)
Sets the distance to the far clip plane.
- Parameters:
FarClip (float)
- setFieldOfView(FieldOfView)
Sets both the horizontal and vertical fields of view.
This also removes existing animation key frames.
- Parameters:
FieldOfView (float)
- Raises:
RuntimeError – Raised if the camera is not a perspective camera.
- setFieldOfViewX(FieldOfView)
Sets the horizontal field of view.
This also removes existing animation key frames.
- Parameters:
FieldOfView (float)
- Raises:
RuntimeError – Raised if the camera is not a perspective camera.
- setFieldOfViewY(FieldOfView)
Sets the vertical field of view.
This also removes existing animation key frames.
- Parameters:
FieldOfView (float)
- Raises:
RuntimeError – Raised if the camera is not a perspective camera.
- setLookAt(pLookAt)
Rotates the camera to look at the provided position.
- Parameters:
pLookAt (VectorN)
- setName(Name)
Sets the camera name.
- Parameters:
Name (str)
- setNearClip(NearClip)
Sets the distance to the near clip plane.
- Parameters:
NearClip (float)
- setScale(Scale)
Sets the camera scale.
- Parameters:
Scale (float)
- setTranslation(pLookAt)
Sets the translation (or position) of the camera.
- Parameters:
pLookAt (VectorN)
- setUp(pLookAt)
Rotates the camera so that the specified vector is straight “up”.
- Parameters:
pLookAt (VectorN)
- translation(Frame=0)
Returns the camera location.
- Parameters:
Frame (int, optional)
- Returns:
VectorN– The 3D position of the camera
- up(Frame=0)
Returns the present up vector.
- Parameters:
Frame (int, optional)
- Returns:
VectorN– The 3D direction pointing “up” from the top of the camera
- viewMatrix(Frame=-1)
Returns the entire 4x4 view matrix of the camera.
- The result will be a tuple of four tuples of floats representing the rows of the matrix - for example:
((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0), (0.0, 0.0, 0.0, 1.0))
The matrix will use the right-handed coordinate system.
- Parameters:
Frame (int, optional) – The frame number to return the matrix for, or -1 (the default) to return the value for the current frame. Defaults to -1.
- Returns:
variant– The camera’s view matrix, as described above
- viewport()
Returns a rectangle describing the camera viewport.
- Returns:
QRect– The rectangle of the viewport.
- viewportAspectRatio()
Returns the viewport aspect ratio.
- Returns:
float– The aspect ratio of the viewport
- class mari.Canvas
Bases:
objectA canvas is a Mari viewport.
Canvases are the geometry viewport containers in the
Mariwindow.You can access canvas objects through the
CanvasManager- for example:mari.canvases.current()Example Code:
>>> # This example shows how to access the current canvas object and to print canvas size to the application log >>> import mari >>> canvas = mari.canvases.current() >>> mari.app.log(str(canvas.size()))
- PICKSPACE_PAINTING = 0
Pick colors pre lighting and color management (colors will be in the ‘Working’ color-space)
- Type:
int
- PICKSPACE_SCREEN = 1
Pick colors post lighting and color management (colors will be in the ‘Monitor’ color-space)
- Type:
int
- class PickSpace
Bases:
objectThese are used to define the space in which to pick pixels in.
- PICKSPACE_PAINTING = 0
Pick colors pre lighting and color management (colors will be in the ‘Working’ color-space)
- Type:
int
- PICKSPACE_SCREEN = 1
Pick colors post lighting and color management (colors will be in the ‘Monitor’ color-space)
- Type:
int
- averageColor(X, Y, Width, Height, Space='PICKSPACE_SCREEN')
Calculate the average color for an area in the canvas.
This allows a script to calculate the average pixel color values from the canvas. The x and y position must be in the range returned by
size()The color returned may be an HDR value with r, g, b values above 1.0 This method is relatively slow to execute and should not be used to the query lots of pixels#Pick a pixel in the middle of the screen Size = mari.canvases.current().size(); c = mari.canvases.current().pickColor(Size.width()/2, Size.height()/2) print(c.toString())
- Parameters:
X (int) – The x coordinate of the sample area. These coordinates are relative to the top left corner of the canvas
Y (int) – The y coordinate of the sample area. These coordinates are relative to the top left corner of the canvas
Width (int) – The width of the sample area. These coordinates are relative to the top left corner of the canvas
Height (int) – The height of the sample area. These coordinates are relative to the top left corner of the canvas
Space (PickSpace, optional) – The space in which to pick pixels in. Defaults to PICKSPACE_SCREEN.
- Raises:
ValueError – Emitted if the sample area is outside of the range (0, 0) - size()
- Returns:
Color– The average color of the pixels at the canvas location (x, y, x + width, y + height)
- camera()
Returns the interface to the camera on the canvas, or NULL if none exists.
- Returns:
Camera– The camera on the canvas, or NULL if none exists
- capture(Width=0, Height=0)
Captures an image of the canvas and returns it.
This is used for preview images of projects, for example. When optional arguments of Width and Height are provided, the image is captured at the provided resolution.
- Parameters:
Width (int, optional) – If non-zero, the image is captured at the specified width. Defaults to 0.
Height (int, optional) – If non-zero, the image is captured at the specified height. Defaults to 0.
- Returns:
QImage– A QImage containing the frame buffer image
- displayPropertyList()
Returns display property names that can be used as keys to manipulate any of the properties individually.
mari.canvases.current().displayPropertyList()- Returns:
list of str– a list of property keys
- getDisplayProperty(PropertyKey)
Determines the state of a display property.
Get whether HUD is visible
mari.canvases.current().getDisplayProperty("HUD/RenderHud")Get the background image of the canvas
mari.canvases.current().getDisplayProperty("Background/BackgroundTexture")Get the grid size
mari.canvases.current().getDisplayProperty("Grid/UvGridSize")- Parameters:
PropertyKey (str) – A display property key to query, in the form “group name/sub property name”. e.g : HUD/RenderHud
- Returns:
variant– A display property value
- pickColor(X, Y, Space='PICKSPACE_SCREEN')
Pick a color from the canvas.
This allows a script to pick pixel color values from the canvas. The x and y position must be in the range returned by
size()The color returned may be an HDR value with r, g, b values above 1.0 This method is relatively slow to execute and should not be used to the query lots of pixels#Pick a pixel in the middle of the screen Size = mari.canvases.current().size(); c = mari.canvases.current().pickColor(Size.width() / 2, Size.height() / 2) print(c.toString())
- Parameters:
X (int) – The x coordinate of the pixel. These coordinates are relative to the top left corner of the canvas
Y (int) – The y coordinate of the pixel. These coordinates are relative to the top left corner of the canvas
Space (PickSpace, optional) – The space in which to pick pixels in. Defaults to PICKSPACE_SCREEN.
- Raises:
ValueError – Emitted if X or Y are outside of the range (0, 0) - size()
- Returns:
Color– The color of the pixel at the canvas location (x, y)
- repaint()
Forces the canvas to repaint itself immediately.
- requestRepaint()
Requests the canvas to be repainted during the next events’ processing.
- sceneCamera()
Returns the interface to the scene camera associated with canvas’s camera, or NULL, if none exists.
- Returns:
Camera– The scene camera associated with canvas’s camera, or NULL, if none exists.
- setDisplayProperty(PropertyKey, NewValue)
Sets the state of a display property.
Enable HUD
mari.canvases.current().setDisplayProperty("HUD/RenderHud", True)Set the background image of the canvas
mari.canvases.current().setDisplayProperty("Background/BackgroundTexture", "/tmp/bluesky.jpg")Set the grid size
mari.canvases.current().setDisplayProperty("Grid/UvGridSize", 5)- Parameters:
PropertyKey (str) – A display property key to set, in the form “group name/sub property name”. e.g : HUDRenderHud
NewValue (variant) – The new value to set
- size()
Return the size of the Canvas in pixels.
print(mari.canvases.current().size())- Returns:
QSize– The Size of the canvas in pixels
- class mari.CanvasManager
Bases:
PropertySourceThis object handles the list of canvases, or viewports, available in the project.
Example Code:
>>> # This example shows how to access the current canvas object and to print canvas size to the application log >>> import mari >>> canvas = mari.canvases.current() >>> mari.app.log(str(canvas.size()))
>>> # This example show hot obtain the list of canvases >>> import mari >>> canvases = mari.canvases.list()
Alias
canvases
- RENDER_BUSY = 1
The busy render chain was used to render the scene, usually due to shaders requiring compiling.
- Type:
int
- RENDER_DISABLED = 3
Rendering was skipped due to things like the canvas not being visible etc.
- Type:
int
- RENDER_ERROR = 2
Rendering failed for some reason such as a shader failed to compile etc.
- Type:
int
- RENDER_NORMAL = 0
The normal render chain completed successfully and the standard scene was displayed.
- Type:
int
- class RenderState
Bases:
objectDifferent states in which the canvas may have finished rendering.
- RENDER_BUSY = 1
The busy render chain was used to render the scene, usually due to shaders requiring compiling.
- Type:
int
- RENDER_DISABLED = 3
Rendering was skipped due to things like the canvas not being visible etc.
- Type:
int
- RENDER_ERROR = 2
Rendering failed for some reason such as a shader failed to compile etc.
- Type:
int
- RENDER_NORMAL = 0
The normal render chain completed successfully and the standard scene was displayed.
- Type:
int
- aboutToRenderCanvas(CanvasToDraw)
This is emitted when a canvas is about to be drawn.
- Parameters:
CanvasToDraw (Canvas) – The canvas about to be drawn
- current()
Returns the interface to the current canvas.
- Returns:
Canvas– The currently active canvas, or NULL if no canvas is active.
- fps()
Returns the current frame rate.
- Returns:
float– The rate at which the canvas is being updated, in frames per second
- list()
Returns a list of the available canvases as Canvas objects.
- Returns:
list of
Canvas– A list of objects describing the available canvases
- normalRenderFinished(CanvasDrawn, SvtStable)
This is emitted after a canvas has just been drawn with the Render_Normal state.
This is equivalent to renderCanvas2(
Canvas, State=Render_Normal).- Parameters:
CanvasDrawn (Canvas) – The canvas drawn
SvtStable (bool) – The state of the SVT used for this render. If true the render has no pixelation.
- paintBuffer()
Returns the current paint buffer.
The paint buffer is the transparent, screen-aligned plane that users paint into.
- Returns:
PaintBuffer– The current paint buffer
- pauseShaderCompiles()
Returns whether shader compilation is paused on the canvas.
The canvas rendering uses a shader and it gets compiled on occasions.
Shadercompilation can be expensive, so it is useful to pause shader compilation during long operation such as baking nodes, flattening layers or converting procedural to paintable.- Returns:
bool– True if shader compilation is paused.
- renderError(ErrorCanvas, ErrorMessages)
This is emitted whenever a rendering error occurs in one of the canvases.
- Parameters:
ErrorCanvas (Canvas) – The canvas where the errors have occurred
ErrorMessages (list of str) – The descriptions of the errors that have occurred
- renderedCanvas(CanvasDrawn)
This is emitted when a canvas has just been drawn.
- Parameters:
CanvasDrawn (Canvas) – The canvas drawn
- renderedCanvas2(CanvasDrawn, State)
This is emitted when a canvas has just been drawn.
This is emitted when the renderCanvas signal is emitted; this signal is used differs only in signature. It is named renderCanvas2 to allow for easy connection in Python and to maintain backward compatibility with Python code that already uses the renderCanvas signal.
- Parameters:
CanvasDrawn (Canvas) – The canvas drawn
State (CanvasManager.RenderState) – The state in which the canvas has finished rendering.
- setPauseShaderCompiles(Pause)
Toggles shader compilation on the canvas.
The canvas rendering uses a shader and it gets compiled on occasions.
Shadercompilation can be expensive, so it is useful to pause shader compilation during long operation such as baking nodes, flattening layers or converting procedural to paintable. This function provides the ability to pause and unpause shader compilation on the canvas.- Parameters:
Pause (bool) – Flag to pause shader compilation.
- size()
Returns the dimensions of every canvas, in pixels.
All canvases have the same dimensions, so the function
Canvas::size()will return the same value.- Returns:
list of
int– The dimensions of every canvas, in pixels, in the format: (width, height)
- class mari.Channel
Bases:
LayerStackChannels are collections of layers that combine sets of image data to display using Shader objects.
You can access channels through their parent
GeoEntityobjects - for example:mari.geo.current().currentChannel()Example Code
>>> # This example shows how to obtain the current channel of the current GeoEntity object >>> import mari >>> channel = mari.geo.current().currentChannel()
- CONVERT_ALL = 1
Convert all layers including locked and shared layers.
- Type:
int
- CONVERT_CHANNEL_ONLY = 0
Convert only the layers in this channel only that are neither locked or shared.
- Type:
int
- class ConvertOption
Bases:
objectSpecifies options for what layers are converted when converting the depth.
- CONVERT_ALL = 1
Convert all layers including locked and shared layers.
- Type:
int
- CONVERT_CHANNEL_ONLY = 0
Convert only the layers in this channel only that are neither locked or shared.
- Type:
int
- RESIZE_BY_PATCH_MAXIMUM = 2
Resize patches to a given maximum size and their world-space size relative to each other.
- Type:
int
- RESIZE_BY_TEXELS_PER_UNIT = 1
Resize patches such that a single world-space unit contains a given number of pixels.
- Type:
int
- RESIZE_BY_TEXEL_SIZE = 0
Resize patches such that a single pixel is of a given world-space size.
- Type:
int
- class ResizeMetric
Bases:
objectSpecifies options on how to calculate patch sizes from a texel system of measurement.
- RESIZE_BY_PATCH_MAXIMUM = 2
Resize patches to a given maximum size and their world-space size relative to each other.
- Type:
int
- RESIZE_BY_TEXELS_PER_UNIT = 1
Resize patches such that a single world-space unit contains a given number of pixels.
- Type:
int
- RESIZE_BY_TEXEL_SIZE = 0
Resize patches such that a single pixel is of a given world-space size.
- Type:
int
- bakeTo(TargetLayer, SelectedOnly=True)
Bakes the current channel into an existing layer.
- Parameters:
TargetLayer (Layer) – The layer to bake the channel into.
SelectedOnly (bool, optional) – Whether or not to bake the result into all patches or only the selected patches. Defaults to True.
- Raises:
ValueError – The target layer provided was invalid, or not paintable.
- Returns:
bool– True if successful.
- bleed()
Returns True if the textures in this channel will bleed when baked.
TODO: Texture bleeding or necessary for most of
Marioperations . However, shared paintable layers and individual patches may not respect this file space depending on how it been adjusted elsewhere.- Returns:
bool– The texture bleed setting for this channel.
- channelNode()
Returns the node graph node that corresponds to this Channel.
- Returns:
ChannelNode– the node graph node that corresponds to this Channel
- colorspaceConfig()
Returns the colorspace configuration for color data of the channel.
New paintable layers created in this channel will use this colorspace configuration. However, shared paintable layers and individual patches may not respect this colorspace depending on how it’s been adjusted elsewhere.
- Returns:
ColorspaceConfig– The colorspace configuration for color data.
- colorspaceConfigChanged(Config)
This is emitted after the colorspace config for color data is modified for the channel.
- Parameters:
Config (ColorspaceConfig)
- convertColorSpaceTo(NewColorSpace, Option='CONVERT_CHANNEL_ONLY')
Converts this channel’s data to a new colorspace.
- Parameters:
NewColorSpace (str) – The colorspace to convert this channel to
Option (ConvertOption, optional) – The option on which layers/nodes to convert. Defaults to CONVERT_CHANNEL_ONLY.
Deprecated
Please use convertColorspaceTo() instead.
- convertColorspaceTo(OutputColorspace, InputColorspace='str', Config='str', Option='CONVERT_CHANNEL_ONLY')
Converts this channel’s data to a new colorspace.
This only applies the colorspace transform and does not update the colorspace config of the channel.
- Parameters:
OutputColorspace (str) – Name of the colorspace or role in the OCIO config to convert this channel to.
InputColorspace (str, optional) – Optional name of the colorspace or role in the OCIO config to convert this channel from. If not specified then the native colorspace of the channel is used. Defaults to str.
Config (str, optional) – Optional name of a standard OCIO config file or the path to a custom one. If not specified then the OCIO config of the project is used. Defaults to str.
Option (ConvertOption, optional) – The option on which layers/nodes to convert. Defaults to CONVERT_CHANNEL_ONLY.
- Raises:
ValueError – Raised if an invalid colorspace or OCIO config is given.
- createSnapshot(Name, ID='str')
Creates a new snapshot of the object.
- Parameters:
Name (str) – A descriptive name for this snapshot. There is no restriction on naming convention, so it is recommended to make this clear, such as “new test version”.
ID (str, optional) – An optional identifier for this snapshot. This value can be used to group together sets of snapshots, as described in
Snapshot::setID(). Defaults to str.
- Raises:
NotImplementedError – Raised if the function is called on a Ptex channel.
- Returns:
Snapshot– The newly created snapshot.
- currentLayer()
Returns the currently active layer on the channel.
- deleteSnapshot(ShotToDelete)
Deletes the given snapshot.
- Parameters:
ShotToDelete (Snapshot) – The snapshot to delete
- Raises:
ValueError – The snapshot provided was invalid, or not owned by this object.
NotImplementedError – Raised if the function is called on a Ptex channel.
Warning
This method cannot be undone, so please use caution.
- depth()
Returns the preferred depth of paintable layers.
New paintable layers created in this channel will use this depth. Resizing the channel will also use this depth to calculate relative resizing sizes. However, shared paintable layers and individual patches may not respect this depth depending on how it has been adjusted elsewhere.
- Returns:
Image.Depth– The preferred height of paintable layers.
- exportToGeoChannel(GeoChannelName)
Exports (bakes) the current channel into the Geo-Channel with the given alias. A new Geo-Channel will be created if required.
- Parameters:
GeoChannelName (str) – An alias of the Geo-Channel to bake into.
- Returns:
bool– True if successful.
- fileSpace()
Returns the preferred file space of paintable layers in this channel.
New paintable layers created in this channel will use this file space. However, shared paintable layers and individual patches may not respect this file space depending on how it been adjusted elsewhere.
- Returns:
Image.FileSpace– The preferred file space of paintable layers.
- findSnapshotWithID(ID)
Returns the snapshot with the given identifier, if found.
If more than one snapshot with the given identifier exists, the first one will be returned.
- Parameters:
ID (str) – The shot identifier to search for
- Raises:
NotImplementedError – Raised if the function is called on a Ptex channel.
- Returns:
Snapshot– The first snapshot with the given identifier, or NULL
- flatten()
Merges all the layers in the channel into a single paintable layer and returns the layer.
- Returns:
Layer– The resulting paintable layer into which all the layers are flattened into.
- geoEntity()
Returns the GeoEntity that this channel belongs to.
- Returns:
GeoEntity– The GeoEntity that this channel belongs to.
- height(UVIndex=-1)
Returns either the maximum height of all patches in this channel, or a single patch.
New paintable layers created in this channel will use this height. Resizing the channel will also use this height to calculate relative resizing sizes. However, shared paintable layers and individual patches may not respect this height depending on how they have been resized elsewhere.
- Parameters:
UVIndex (int, optional) – The UV index of the patch to return the height of, or -1 to return the maximum height of all patches. Defaults to -1.
- Raises:
ValueError – Raised if an invalid UV index was specified.
NotImplementedError – Raised if the function is called on a Ptex channel.
- Returns:
int– The maximum height of all patches, or the height of a single patch.
- isLocked()
Indicates whether this channel is locked, and if so, unmodifiable.
- Returns:
bool– True if this image is locked, or false if unlocked
See also
lock(), setLocked(), unlock()
- isPtex()
Returns true if this channel is Ptex based.
- isShaderStack()
Returns true if this is a ShaderStack.
- layerMadeCurrent(CurrentLayer)
This is emitted when a layer from the channel is made current.
- Parameters:
CurrentLayer (Layer) – The current layer
- lock()
Locks the channel to prevent modifications.
See also
isLocked(), setLocked(), unlock()
- lockedChanged(Locked)
This is emitted after the channel is locked or unlocked.
- Parameters:
Locked (bool) – True if the channel is now locked, or false otherwise
- makeCurrent()
Sets this channel as the currently active channel on its GeoEntity.
- metricResize(Metric, Value, UVIndexList)
Resize a set of patches in the channel using a geometry based metric.
- Parameters:
Metric (ResizeMetric) – The geometry metric to use when resizing each patch.
Value (float) – The value of the geometry metric to use.
UVIndexList (list of
int) – Pass in a list of zero-based UV indices if desired to specify which patches to resize the images of. If not specified or empty, all patches will be resized. The UDIM for a patch is the zero-based UV index plus 1001.
- Raises:
ValueError – Raised if the size provided was invalid, or if an invalid UV index was specified.
NotImplementedError – Raised if the function is called on a Ptex channel.
- name()
Returns the name of the channel.
- Returns:
str– The name of this channel.
- nameChanged(NewName)
This is emitted after the channel has had its name changed.
- Parameters:
NewName (str) – The new name.
- resize(NewSize, UVIndexList)
Resize a set of patches in the channel.
- Parameters:
NewSize (ImageSet.Size) – The desired size for the patch.
UVIndexList (list of
int) – Pass in a list of zero-based UV indices if desired to specify which patches to resize the images of. If not specified or empty, all patches will be resized. The UDIM for a patch is the zero-based UV index plus 1001.
- Raises:
ValueError – Raised if the size provided was invalid, or if an invalid UV index was specified.
NotImplementedError – Raised if the function is called on a Ptex channel.
- revertToSnapshot(OldSnapshot)
Reverts the state of the object to that in the given snapshot.
- Parameters:
OldSnapshot (Snapshot) – A valid snapshot of this object
- Raises:
ValueError – The snapshot provided was invalid, or not owned by this object.
NotImplementedError – Raised if the function is called on a Ptex channel.
- scalarColorspaceConfig()
Returns the colorspace configuration for scalar data of the channel.
New masks created in this channel will use this colorspace configuration. However, shared masks and individual patches may not respect this colorspace depending on how it’s been adjusted elsewhere.
- Returns:
ColorspaceConfig– The colorspace configuration for scalar data.
- scalarColorspaceConfigChanged(Config)
This is emitted after the colorspace config for scalar data is modified for the channel.
- Parameters:
Config (ColorspaceConfig)
- setBleed(Bleed)
Sets the Texture Bleed setting for this channel.
TODO: The file space set here will be propagated down to all non-shared paintable layers and their patches contained in this channel. The file space for Images (patches) may be altered by calling the appropriate functions on these objects.
- Parameters:
Bleed (bool) – The texture bleed setting for this channel.
- setColorspaceConfig(Config)
Sets the colorspace configuration for color data of the channel.
The colorspace configuration set here will be propagated down to all non-shared paintable layers and their patches contained in the channel. The colorspace configuration for Images (patches) may be altered by calling the appropriate functions on these objects.
- Parameters:
Config (ColorspaceConfig) – The colorspace configuration for color data.
- Raises:
ValueError – Raised if the colorspace configuration is invalid.
- setCurrentLayer(NewCurrentLayer)
Sets the given layer as the currently active layer on the channel and selects it.
- Parameters:
NewCurrentLayer (Layer) – The layer that is to be made current.
- Raises:
ValueError – Raised if the layer is not in this channel.
- setDepth(Depth, Option)
Sets the depth of this channel and converts internal layers’ bit depths.
- Parameters:
Depth (Image.Depth) – The bit depth to convert this channel to
Option (ConvertOption) – The option on which layers to convert bit depth of
- setFileSpace(FileSpace)
Sets the file space of non-shared paintable layers in this channel.
The file space set here will be propagated down to all non-shared paintable layers and their patches contained in this channel. The file space for Images (patches) may be altered by calling the appropriate functions on these objects.
- Parameters:
FileSpace (Image.FileSpace) – The file space to set non-shared layers to.
- setLocked(Locked)
Locks or unlocks the channel, to optionally prevent modifications.
- Parameters:
Locked (bool)
See also
isLocked(), lock(), unlock()
- setName(NewName)
Sets the name of the channel.
- Parameters:
NewName (str) – The new name for the channel.
- setScalarColorspaceConfig(Config)
Sets the colorspace configuration for scalar data of the channel.
The colorspace configuration set here will be propagated down to all non-shared masks and their patches contained in the channel. The colorspace configuration for Images (patches) may be altered by calling the appropriate functions on these objects.
- Parameters:
Config (ColorspaceConfig) – The colorspace configuration for scalar data.
- Raises:
ValueError – Raised if the colorspace configuration is invalid.
- snapshotAdded(NewSnapshot)
This is emitted after a snapshot is created for this object.
- Parameters:
NewSnapshot (Snapshot)
- snapshotList()
Returns a list of the snapshots available on the object.
- Raises:
NotImplementedError – Raised if the function is called on a Ptex channel.
- Returns:
list of
Snapshot– A list of the available snapshots
- snapshotRemoved(OldSnapshot)
This is emitted after a snapshot is deleted for this object.
- Parameters:
OldSnapshot (Snapshot)
- unlock()
Unlocks the channel and allows modifications.
See also
isLocked(), lock(), setLocked()
- updateUvImageSizes()
Add missing and remove unneeded patch size information on the channel node.
This corrects channels that have been imported from
Mariversion < 3.2.68. For channels imported with earlier versions, if they came from models with a different set of patches to the target model, some patch size information was not initialized properly leading to errors when interacting with the channel.
- width(UVIndex=-1)
Returns either the maximum width of all patches in this channel, or a single patch.
New paintable layers created in this channel will use this width. Resizing the channel will also use this width to calculate relative resizing sizes. However, shared paintable layers and individual patches may not respect this width depending on how they have been resized elsewhere.
- Parameters:
UVIndex (int, optional) – The UV index of the patch to return the width of, or -1 to return the maximum width of all patches. Defaults to -1.
- Raises:
ValueError – Raised if an invalid UV index was specified.
NotImplementedError – Raised if the function is called on a Ptex channel.
- Returns:
int– The maximum width of all patches, or the width of a single patch.
- class mari.ChannelInfo(rName, Width=4096, Height=4096, BitDepth='Image.DEPTH_BYTE', pFillColor='nullptr', FileSpace='Image.FILESPACE_NORMAL', ColorspaceSettings='nullptr', ScalarColorspaceSettings='nullptr')
Bases:
objectProvides information about a channel to create or import.
- __init__(rName, Width=4096, Height=4096, BitDepth='Image.DEPTH_BYTE', pFillColor='nullptr', FileSpace='Image.FILESPACE_NORMAL', ColorspaceSettings='nullptr', ScalarColorspaceSettings='nullptr')
Constructor for ChannelInfo.
This class contains the information for creating a new channel. Note that this API is not complete, as not all options are fully supported yet.
- Parameters:
rName (str) – Name of the channel. A value exception is raised if this is empty.
Width (int, optional) – The width of the channel’s textures in pixels. The default is 4K (4096). Defaults to 4096.
Height (int, optional) – The height of the channel’s textures in pixels. The default is 4K (4096). Defaults to 4096.
BitDepth (Image.Depth, optional) – The bit depth of the channel’s textures: mari.Image.Depth.DEPTH_BYTE (8, the default), mari.Image.Depth.DEPTH_HALF (16) or mari.Image.Depth.DEPTH_FLOAT (32). Defaults to Image.DEPTH_BYTE.
pFillColor (Color, optional) – Specifies a color to fill the channel’s texture with on creation. If invalid, it uses a default gray. Defaults to nullptr.
FileSpace (Image.FileSpace, optional) – The file space the channel will import and export data as: mari.Image.FileSpace.FILESPACE_NORMAL, mari.Image.FileSpace.FILESPACE_VECTOR or mari.Image.FileSpace.FILESPACE_VECTOR_Y_FLIP. Defaults to Image.FILESPACE_NORMAL.
ColorspaceSettings (ColorspaceConfig, optional) – The colorspace settings for color data of the channel. Defaults to nullptr.
ScalarColorspaceSettings (ColorspaceConfig, optional) – The colorspace settings for scalar data of the channel. Defaults to nullptr.
- Raises:
ValueError – Raised if the channel name was empty, or the requested dimensions are not supported.
ValueError – Raised if invalid colorspace configurations were supplied.
See also
mari.Image.Depth
See also
mari.Image.FileSpace
- colorspaceConfig()
Returns the colorspace configuration for color data of the channel.
- Returns:
ColorspaceConfig– The colorspace configuration.
- depth()
Returns the bit depth of the channel.
- fileSpace()
Returns the name of the file space the channel will import and export data as.
- fileTemplate()
Returns the template used to generate the file name.
- Returns:
str– The template for the file name. See setFileTemplate() for details of the supported replaceable tokens.
See also
setFileTemplate()
- fillColor()
Returns the color that the channel will be filled with on creation.
- height()
Returns the height of the channel’s textures.
Textures in channels must always be square, so this will be the same as the width.
See also
setHeight(), setSize(), setWidth(), size(), width()
- name()
Returns the name of the channel.
- path()
Returns the base path for the channel’s textures.
- scalarColorspaceConfig()
Returns the colorspace configuration for scalar data of the channel.
New masks created in this channel will use this colorspace configuration. However, shared masks and individual patches may not respect this colorspace depending on how it’s been adjusted elsewhere.
- Returns:
ColorspaceConfig– The colorspace configuration for scalar data.
- setColorspaceConfig(Config)
Sets the colorspace configuration for color data of the channel.
- Parameters:
Config (ColorspaceConfig) – The colorspace configuration.
- Raises:
ValueError – Raised if the colorspace configuration is invalid.
- setDepth(NewDepth)
Sets the bit depth of the channel.
- Parameters:
NewDepth (Image.Depth)
- setFileSpace(FileSpace)
Set the name of the file space the channel will import and export data as.
- Parameters:
FileSpace (Image.FileSpace)
- setFileTemplate(rTemplate)
Sets the template used to generate the file name.
- File templates are used to create the file names for each individual patch to load for the channel. The file names are copied from the template, with the following supported tokens replaced with their appropriate values:
$PATH - The base path for the textures, as returned by the
path()function$ENTITY - The name of the geometry object (or entity) that the images are being imported into
$CHANNEL - The name of the channel in the geometry object (or entity)
$LAYER - The name of the individual layer in the channel
$IMAGESET - The UUID of the channel in the layer
$UDIM - A special number indicating the index of the patch in the channel
$NUMBER - The number of the patch within the batch, starting from zero
$INDEX - Same as $NUMBER
$COUNT - The number of patches in the channel
$EXPORTROOT - The Export Root Path set in the Export Manager.
See
GeoPatch::udim()for a description of UDIM values.- Parameters:
rTemplate (str) – The template string to use for the patch file names
See also
mari.examples.create_blacksmith_project.createBlacksmithProject()
See also
fileTemplate()
- setFillColor(pCol)
Sets the color that the channel will be filled with on creation.
- Parameters:
pCol (Color)
- setHeight(Height)
Sets the height (and width) of the channel’s textures.
- Parameters:
Height (int)
- Raises:
ValueError – Raised if the new dimensions of the channel (after setting both the width and height) are invalid.
Note
Textures in channels must always be square, so this will set the width as well as the height.
See also
height(), setSize(), setWidth(), size(), width()
- setName(rName)
Sets the name of the channel.
- Parameters:
rName (str)
- setPath(rPath)
Sets the base path for the channel’s textures.
- Parameters:
rPath (str)
- setScalarColorspaceConfig(Config)
Sets the colorspace configuration for scalar data of the channel.
The colorspace configuration set here will be propagated down to all non-shared masks and their patches contained in the channel. The colorspace configuration for Images (patches) may be altered by calling the appropriate functions on these objects.
- Parameters:
Config (ColorspaceConfig) – The colorspace configuration for scalar data.
- Raises:
ValueError – Raised if the colorspace configuration is invalid.
- setShader(rShader)
Sets the shader category of the channel.
- Parameters:
rShader (str) – The shader that this channel should be plugged into.
- setSize(WidthAndHeight)
Sets the width and height of the channel, which must be the same.
- Parameters:
WidthAndHeight (int) – The width and height of the channel, which must be the same
- Raises:
ValueError – Raised if the new dimensions of the channel are invalid.
See also
height(), setHeight(), setWidth(), size(), width()
- setWidth(Width)
Sets the width (and height) of the channel’s textures.
- Parameters:
Width (int)
- Raises:
ValueError – Raised if the new dimensions of the channel (after setting both the width and height) are invalid.
Note
Textures in channels must always be square, so this will set the height as well as the width.
See also
height(), setHeight(), setSize(), size(), width()
- shader()
Returns the shader category of the channel.
- size()
Returns the width and height of the channel, which must be the same.
- Returns:
int– The width and height of the channel, which must be the same
See also
height(), setHeight(), setSize(), setWidth(), width()
- width()
Returns the width of the channel’s textures.
Textures in channels must always be square, so this will be the same as the height.
See also
height(), setHeight(), setSize(), setWidth(), size()
- class mari.ChannelLayer
Bases:
AdjustableLayerChannel layers add the image output of a Channel into another stack as a layer.
You can access all types of layers from their containing
Channelobjects - for example:channel.layerList()You can check for
ChannelLayerobjects by callingLayer::isChannelLayer():Example Code
>>> #This example finds channel layers in the current channel >>> import mari >>> channel_layers = [] >>> channel = mari.geo.current().currentChannel() >>> for layer in channel.layerList(): ... if layer.isChannelLayer(): ... channel_layers.append(layer)
- class mari.ChannelNode
Bases:
BakePointNodeRepresents a channel node.
A
ChannelNodeis a node represents a channel.
- class mari.ChannelSnapshot
Bases:
SnapshotA copy of the state of a channel at a particular time.
By creating snapshots, users can easily preserve the state of an object and return to that state at some later time.
For example, this could be used to preserve the history of a design, or to try new ideas without risking the current textures. The user could snapshot the current state, paint some modifications, ask for approval, and if the changes are not accepted, quickly and easily revert to the previous state.
Example Code
>>> # This example shows how to obtain the current channel of the current GeoEntity object >>> import mari >>> channel = mari.geo.current().currentChannel() >>> channel_snapshot = channel.createSnapshot("Test Snapshot")
- class mari.Clock
Bases:
objectControls for Mari’s internal animation clock.
Using this class the user can control playback of animation in
Mari. Various things can be animated inMari, including geometry, cameras, and textures. The frame range may be set to any required values, and animated scene elements will clamp their animation to the frames they have available. The clock can be run forwards or backwards at different frame rates. The behavior for when the end of the frame range is reached can also be customized, so playback can stop, loop, or bounce.Example Code
>>> # This example obtains the current animation frame >>> import mari >>> current_frame = mari.clock.frame()
Alias
clock
- BACKWARDS = -1
.
- Type:
int
- BOUNCE = 1
Play in reverse back to the start of the frame range, and then resume forward playback.
- Type:
int
- FORWARDS = 1
.
- Type:
int
- LOOP = 0
Return to the start of the frame range and continue playing.
- Type:
int
- class PlayDirection
Bases:
objectDirections of animation playback.
- BACKWARDS = -1
.
- Type:
int
- FORWARDS = 1
.
- Type:
int
- class RepeatType
Bases:
objectThese are the types of behavior available for when the end of the frame range is reached.
- BOUNCE = 1
Play in reverse back to the start of the frame range, and then resume forward playback.
- Type:
int
- LOOP = 0
Return to the start of the frame range and continue playing.
- Type:
int
- STOP = 2
Stop playback.
- Type:
int
- STOP = 2
Stop playback.
- Type:
int
- frame()
Returns the current frame number.
- Returns:
int– The current frame number
- frameChanged(Frame)
This is emitted when the frame number changes.
- Parameters:
Frame (int) – The new frame number
- frameCount()
Returns the number of frames in the current frame range.
- Returns:
int– The number of frames in the current frame range
- frameRate()
Returns the animation playback frame rate, in FPS.
- Returns:
int– The current frame rate, in frames per second.
- frameRateChanged(NewFps)
This is emitted when the frame rate changes.
- Parameters:
NewFps (int) – The new frame rate, in frames per second.
- loopCount()
Returns the number of animation loops that have been completed.
When in bounce playback mode, playing all frames forwards and then all in reverse counts as one loop.
- Returns:
int– The number of animation loops that have been completed.
See also
BOUNCE
- play(Direction='FORWARDS')
Starts animation playback.
- Parameters:
Direction (PlayDirection, optional) – Indicates whether to play forwards (the default) or backwards. Defaults to FORWARDS.
- playing()
Indicates whether animation playback is active.
- Returns:
bool– True if the clock is currently playing
- playingChanged(IsPlaying)
This is emitted when animation starts or stops.
- Parameters:
IsPlaying (bool) – True when playing, or false when stopped
- rangeChanged(Start, End)
This is emitted when the frame range changes.
- Parameters:
Start (int) – The start frame of the new range
End (int) – The end frame of the new range
- repeatType()
Indicates how the clock handles reaching the end of the frame range during playback.
- Returns:
RepeatType– The current repeating behavior
- reset()
Resets all the internal clock values to sensible defaults.
- rewind()
Rewinds to the first frame.
- setFrame(Frame)
Sets the current frame.
- Parameters:
Frame (int) – The new frame number
- setFrameRange(Start, End)
Sets the animation frame range.
Animation will run between the start and end of the range.
- Parameters:
Start (int) – The start frame of the new range
End (int) – The end frame of the new range
- setFrameRate(fps)
Sets the animation playback frame rate, in FPS.
- Parameters:
fps (int) – The new frame rate, in frames per second.
- setRepeatType(Type)
Sets how the clock should handle reaching the end of the frame range during playback.
- Parameters:
Type (RepeatType) – The new repeating behavior
- setSourceFrameRate(Fps)
Sets the frame rate of the source material, in FPS.
- Parameters:
Fps (int) – The frame rate, in frames per second, that the material in the current project should be played at. For film this is generally 24 FPS.
- sourceFrameRate()
Returns the frame rate of the source material, in FPS.
- Returns:
int– The frame rate, in frames per second, that material in the current project is played at
- startFrame()
Returns the start frame.
- Returns:
int– The starting frame of the current frame range
- stepBack()
Steps back to the frame before the current one.
- stepForward()
Steps forward to the frame after the current one.
- stop()
Stops animation playback.
- stopFrame()
Returns the end frame.
- Returns:
int– The end frame of the current frame range
- time()
Returns the animation playback time in HH:MM:SS:MS format.
- Returns:
str– A string representation of the current animation playback time. When at the first frame, this will be “00:00:00:00”.
- class mari.Color(Red=0.0, Green=0.0, Blue=0.0, Alpha=1.0)
Bases:
objectObjects of this class hold information about an individual color value.
All channels are specified in the range [0, 1] - so passing in a value of 1 will set the channel to 100% intensity.
RGB and HSV/L values are updated automatically. For example, if you set the color from RGB values, you can immediately retrieve the HSV equivalents of those if desired.
Example Code
>>> # This example constructs a Color object and sets the foreground color with it >>> import mari >>> foreground_color = mari.Color(1,1,0,1) >>> mari.colors.setForeground(foreground_color)
>>> # This example obtains the current foreground color >>> import mari >>> foreground_color = mari.colors.foreground() >>> print(foreground_color.toString()) (1,1,0,1)
- __init__(Red=0.0, Green=0.0, Blue=0.0, Alpha=1.0)
Sets to the color specified by the given components.
All color components are optional. This provides the convenience of being able to specify only R, G, and B components to default to opaque (100% alpha), or not provide any parameters to create a default color of opaque black.
- Parameters:
Red (float, optional)
Green (float, optional)
Blue (float, optional)
Alpha (float, optional)
- a()
Returns the alpha component.
- b()
Returns the blue component.
- exposure()
Returns the exposure value of the color.
- g()
Returns the green component.
- h()
Returns the hue component.
- hsl()
Returns the color as a list of hue, saturation, and lightness components.
- hsla()
Returns the color as a list of hue, saturation, lightness, and alpha components.
- hsv()
Returns the color as a list of hue, saturation, and value components.
- hsva()
Returns the color as a list of hue, saturation, value, and alpha components.
- l()
Returns the lightness component.
- lum()
Returns the luminance value of the color.
- r()
Returns the red component.
- rgb()
Returns the color as a list of red, green, and blue components.
- rgba()
Returns the color as a list of red, green, blue, and alpha components.
- s()
Returns the saturation component.
- setA(Alpha)
Sets the alpha component.
- Parameters:
Alpha (float)
- setB(Blue)
Sets the blue component.
- Parameters:
Blue (float)
- setG(Green)
Sets the green component.
- Parameters:
Green (float)
- setH(Hue)
Sets the hue component.
- Parameters:
Hue (float)
- setHSL(Hue, Saturation, Lightness)
Sets the color using hue, saturation, and lightness components.
- Parameters:
Hue (float)
Saturation (float)
Lightness (float)
- setHSLA(Hue, Saturation, Lightness, Alpha)
Sets the color using hue, saturation, lightness, and alpha components.
- Parameters:
Hue (float)
Saturation (float)
Lightness (float)
Alpha (float)
- setHSV(Hue, Saturation, Value)
Sets the color using hue, saturation, and value components.
- Parameters:
Hue (float)
Saturation (float)
Value (float)
- setHSVA(Hue, Saturation, Value, Alpha)
Sets the color using hue, saturation, value, and alpha components.
- Parameters:
Hue (float)
Saturation (float)
Value (float)
Alpha (float)
- setL(Lightness)
Sets the lightness component.
- Parameters:
Lightness (float)
- setR(Red)
Sets the red component.
- Parameters:
Red (float)
- setRGB(Red, Green, Blue)
Sets the color using red, green, and blue components.
- Parameters:
Red (float)
Green (float)
Blue (float)
- setRGBA(Red, Green, Blue, Alpha)
Sets the color using red, green, blue, and alpha components.
- Parameters:
Red (float)
Green (float)
Blue (float)
Alpha (float)
- setS(Saturation)
Sets the saturation component.
- Parameters:
Saturation (float)
- setV(Value)
Sets the value component.
- Parameters:
Value (float)
- toString()
Returns a string representation of the color.
For example, opaque black will be displayed as “(0,0,0,1)”.
- userReadable()
Returns a user-readable description of the color.
This will be a three line string showing the RGB, HSV, and alpha components.
- v()
Returns the value component.
- class mari.Colors
Bases:
objectProvides access to various color-related functionality.
This includes setting and retrieving the foreground and background colors.
Example Code
>>> # This example constructs a Color object and sets the foreground color with it >>> import mari >>> foreground_color = mari.Color(1,1,0,1) >>> mari.colors.setForeground(foreground_color)
>>> # This example obtains the current foreground color >>> import mari >>> foreground_color = mari.colors.foreground() >>> print(foreground_color.toString()) (1,1,0,1)
- background()
Returns the current background color.
- Returns:
Color– The currently selected background color
- backgroundChanged()
This is emitted when the background color is changed.
- foreground()
Returns the current foreground color.
- Returns:
Color– The currently selected foreground color
- foregroundChanged()
This is emitted when the foreground color is changed.
- pick(InitialColor, ScalarPickingMode=False)
Displays the Mari color picking widget, and returns the color picked.
- Parameters:
InitialColor (Color) – The initial color to display in the picker widget
ScalarPickingMode (bool, optional) – Whether to display the color picking widget in scalar picking mode. Defaults to False.
- Raises:
RuntimeError – Raised if the user cancelled the color selection.
- class mari.ColorspaceConfig(Colorspaces, AutomaticTypes, Raw=False, Scalar=False)
Bases:
objectUsed to specify the colorspace OpenColorIO(OCIO) configuration file and associated colorspaces to use at various points in the pipeline.
- COLORSPACE_STAGE_COUNT = 3
Total number of colorspace stages.
- Type:
int
- COLORSPACE_STAGE_NATIVE = 0
Colorspace of the raw data.
- Type:
int
- COLORSPACE_STAGE_OUTPUT = 1
Colorspace to export the data out in.
- Type:
int
- COLORSPACE_STAGE_WORKING = 2
Colorspace used when working with the data.
- Type:
int
- COLORSPACE_TYPE_COUNT = 3
Total number of colorspace data types.
- Type:
int
- COLORSPACE_TYPE_FLOAT = 2
Floating-point (including half float and double).
- Type:
int
- COLORSPACE_TYPE_INT16 = 1
Integer more than 8 bits (not half float).
- Type:
int
- COLORSPACE_TYPE_INT8 = 0
8 bit integer.
- Type:
int
- class ColorspaceStage
Bases:
objectThese are used to define a particular point in the pipeline when a colorspace can be defined.
- COLORSPACE_STAGE_COUNT = 3
Total number of colorspace stages.
- Type:
int
- COLORSPACE_STAGE_NATIVE = 0
Colorspace of the raw data.
- Type:
int
- COLORSPACE_STAGE_OUTPUT = 1
Colorspace to export the data out in.
- Type:
int
- COLORSPACE_STAGE_WORKING = 2
Colorspace used when working with the data.
- Type:
int
- class ColorspaceType
Bases:
objectThese are used to define the data types used by colorspaces.
- COLORSPACE_TYPE_COUNT = 3
Total number of colorspace data types.
- Type:
int
- COLORSPACE_TYPE_FLOAT = 2
Floating-point (including half float and double).
- Type:
int
- COLORSPACE_TYPE_INT16 = 1
Integer more than 8 bits (not half float).
- Type:
int
- COLORSPACE_TYPE_INT8 = 0
8 bit integer.
- Type:
int
- __init__(Colorspaces, AutomaticTypes, Raw=False, Scalar=False)
Creates a new colorspace config.
- Parameters:
Colorspaces (list of str)
AutomaticTypes (list<ColorspaceConfig.ColorspaceType>)
Raw (bool, optional)
Scalar (bool, optional)
- Raises:
ValueError – Raised if an invalid number of colorspaces or automatic types is given.
- automaticColorspace(Stage)
Returns the automatic colorspace or role for a particular stage.
- Parameters:
Stage (ColorspaceStage) – The stage in the pipeline where a colorspace or role can be defined.
- Raises:
IndexError – Raised if the stage index is out of range.
- Returns:
str– The automatic colorspace or role of the pipeline stage.
- automaticType(Stage)
Returns the automatic data type for either the native and output stages.
- Parameters:
Stage (ColorspaceStage) – The stage in which a data type can be defined.
- Raises:
IndexError – Raised if the stage index is neither the native or output stage.
- Returns:
ColorspaceType– The automatic data type of the pipeline stage.
- availableColorspaces(Stage='COLORSPACE_STAGE_COUNT', PrettyNames=False)
Returns a list of all the available colorspaces and roles present in the OCIO config file for a particular stage.
If COLORSPACE_STAGE_COUNT is passed in for Stage then only the colorspaces and roles defined in the OCIO config file will be checked and none of the extras for the stages such as ‘Automatic’.
- Parameters:
Stage (ColorspaceStage, optional) – The stage in the pipeline where a colorspace or role can be defined. Defaults to COLORSPACE_STAGE_COUNT.
PrettyNames (bool, optional) – Flag used to indicate whether user interface friendly colorspace names are to be returned. Defaults to False.
- Raises:
IndexError – Raised if the stage index is out of range.
- Returns:
list of str– The list of colorspaces and roles within the OCIO config file for a particular stage.
- colorspace(Stage)
Returns the colorspace or role for a particular stage.
This may not actually be a colorspace or role within the OCIO config file. Please use ‘resolveColorSpace’ to get the actual colorspace name.
- Parameters:
Stage (ColorspaceStage) – The stage in the pipeline where a colorspace or role can be defined.
- Raises:
IndexError – Raised if the stage index is out of range.
- Returns:
str– The colorspace or role of the pipeline stage.
- defaultColorspace(Stage)
Returns the default colorspace or role for a particular stage.
- Parameters:
Stage (ColorspaceStage) – The stage in the pipeline where a colorspace or role can be defined.
- Raises:
IndexError – Raised if the stage index is out of range.
- Returns:
str– The default colorspace or role of the pipeline stage.
- fileName()
Returns the name or path of the OCIO config file.
- fromString(Str)
Sets the colorspace settings from a string representation.
- Parameters:
Str (str) – The string representation of the colorspace data.
- isColorspaceValid(Colorspace, Stage='COLORSPACE_STAGE_COUNT', Strict=False)
Returns true if the given colorspace or role is present in the OCIO config file and is valid for a particular stage.
If COLORSPACE_STAGE_COUNT is passed in for Stage then only the colorspaces and roles defined in the OCIO config file will be checked and none of the extras for the stages such as ‘Automatic’.
- Parameters:
Colorspace (str) – The colorspace or role to look for.
Stage (ColorspaceStage, optional) – The stage in the pipeline where a colorspace or role can be defined. Defaults to COLORSPACE_STAGE_COUNT.
Strict (bool, optional) – When set the automatic colorspaces are parsed to determine whether they can be resolved to an actual colorspace within the OCIO config file. Defaults to False.
- Raises:
IndexError – Raised if the stage index is out of range.
- Returns:
bool– True if the colorspace or role is present in the OCIO config file and is valid for the stage, false otherwise.
- isFileCustom()
Returns true if the OCIO config file is not one of the standard ones packaged with Mari.
- isFileValid()
Returns true if the OCIO config file is valid.
- isValid()
Returns true if the OCIO config file and corresponding colorspace stages are valid.
- raw()
Returns whether the configuration is enabled and to be used to convert data between colorspaces.
- Returns:
bool– True if the configuration is enabled.
- reset()
Sets both the OCIO config file and each of the colorspace stages to their default.
- resolveColorspace(Stage)
Returns the colorspace found within the OCIO config file for a particular stage.
- Parameters:
Stage (ColorspaceStage) – The stage in the pipeline where a colorspace or role can be defined.
- Raises:
IndexError – Raised if the stage index is out of range.
- Returns:
str– The colorspace of the pipeline stage.
- resolveRaw()
Returns whether the configuration should be used to convert between color-spaces.
This takes into consideration, not only the internal flag, the global default raw option and whether the
OpenColorIOis valid.
- scalar()
Returns whether the configuration is targeting masks, heights, normals, depths, and other non-color images.
- Returns:
bool– True if the configuration is targeting non-color data.
- setAutomaticColorspace(Stage, Colorspace)
Sets the automatic colorspace or role for a particular stage.
- Parameters:
Stage (ColorspaceStage) – The stage in the pipeline where a colorspace or role can be defined.
Colorspace (str) – The automatic colorspace or role of the pipeline stage.
- Raises:
IndexError – Raised if the stage index is out of range.
ValueError – Raised if an invalid colorspaces, for the OCIO config file, is given.
- setAutomaticType(Stage, Type)
Sets the automatic data type for either the native and output stages.
- Parameters:
Stage (ColorspaceStage) – The stage in which a data type can be defined.
Type (ColorspaceType) – The automatic data type of the pipeline stage.
- Raises:
IndexError – Raised if the stage index is neither the native or output stage.
- setColorspace(Stage, Colorspace)
Sets the colorspace or role for a particular stage.
- Parameters:
Stage (ColorspaceStage) – The stage in the pipeline where a colorspace or role can be defined.
Colorspace (str) – The new colorspace or role of the stage in the pipeline.
- Raises:
IndexError – Raised if the stage index is out of range.
ValueError – Raised if an invalid colorspaces, for the OCIO config file, is given.
- setRaw(Enable)
Sets whether the configuration is enabled and to be used to convert data between colorspaces.
- Parameters:
Enable (bool) – Whether the configuration is enabled.
- setScalar(Enable)
Sets whether the configuration is targeting masks, heights, normals, depths, and other non-color images.
- Parameters:
Enable (bool) – Whether the configuration is targeting non-color data.
- toString()
Returns a string representation of the colorspace.
- Returns:
str– Colorspace data.
- class mari.ColorspaceDefaults(ColorSpaces, FileName='str', ColorManagementEnabled=True)
Bases:
objectUsed to specify the default OpenColorIO(OCIO) configuration file and associated colorspaces for a project.
- COLORSPACE_TARGET_BLENDING = 7
Default for applying blending operations such as, comp of the paint buffer and the current paint target, blending between layers, and combining inputs in a merge node. You will typically want to select the “Default” colorspace to get the same results as painting prior to Mari 3.0, and to get less banding artifacts when painting 8-bit channels and images.
- Type:
int
- COLORSPACE_TARGET_COLOR_PICKER = 6
Default for color pickers and swatches. You will typically want to select the same colorspace as the current channel.
- Type:
int
- COLORSPACE_TARGET_COUNT = 9
Total number of colorspace targets.
- Type:
int
- COLORSPACE_TARGET_FLOAT = 3
Default for channels and, reading and writing image files containing floating-point data.
- Type:
int
- COLORSPACE_TARGET_INT16 = 1
Default for reading image files containing integer data more than 8 bits (not half float).
- Type:
int
- COLORSPACE_TARGET_INT8 = 0
Default for channels and, reading and writing image files containing 8 bit integer data.
- Type:
int
- COLORSPACE_TARGET_INT_SCALAR = 2
Default for masks, heights, normals, depths, and other non-color images containing integer data.
- Type:
int
- COLORSPACE_TARGET_MONITOR = 5
Default for thumbnails of color images. You will typically want to select the same colorspace as the viewer when viewing color data.
- Type:
int
- COLORSPACE_TARGET_SCALAR_MONITOR = 8
Default for thumbnails of scalar images. You will typically want to select the same colorspace as the viewer when viewing scalar data.
- Type:
int
- COLORSPACE_TARGET_WORKING = 4
Default for painting, lighting, applying filters, and other such operations. You will typically want to select the “Linear” colorspace to get accurate results.
- Type:
int
- class ColorspaceTarget
Bases:
objectThese are used to define the default colorspace of a data type or device.
- COLORSPACE_TARGET_BLENDING = 7
Default for applying blending operations such as, comp of the paint buffer and the current paint target, blending between layers, and combining inputs in a merge node. You will typically want to select the “Default” colorspace to get the same results as painting prior to Mari 3.0, and to get less banding artifacts when painting 8-bit channels and images.
- Type:
int
- COLORSPACE_TARGET_COLOR_PICKER = 6
Default for color pickers and swatches. You will typically want to select the same colorspace as the current channel.
- Type:
int
- COLORSPACE_TARGET_COUNT = 9
Total number of colorspace targets.
- Type:
int
- COLORSPACE_TARGET_FLOAT = 3
Default for channels and, reading and writing image files containing floating-point data.
- Type:
int
- COLORSPACE_TARGET_INT16 = 1
Default for reading image files containing integer data more than 8 bits (not half float).
- Type:
int
- COLORSPACE_TARGET_INT8 = 0
Default for channels and, reading and writing image files containing 8 bit integer data.
- Type:
int
- COLORSPACE_TARGET_INT_SCALAR = 2
Default for masks, heights, normals, depths, and other non-color images containing integer data.
- Type:
int
- COLORSPACE_TARGET_MONITOR = 5
Default for thumbnails of color images. You will typically want to select the same colorspace as the viewer when viewing color data.
- Type:
int
- COLORSPACE_TARGET_SCALAR_MONITOR = 8
Default for thumbnails of scalar images. You will typically want to select the same colorspace as the viewer when viewing scalar data.
- Type:
int
- COLORSPACE_TARGET_WORKING = 4
Default for painting, lighting, applying filters, and other such operations. You will typically want to select the “Linear” colorspace to get accurate results.
- Type:
int
- __init__(ColorSpaces, FileName='str', ColorManagementEnabled=True)
Creates a new colorspace config.
- Parameters:
FileName (str, optional)
ColorSpaces (list of str)
ColorManagementEnabled (bool, optional)
- Raises:
ValueError – Raised if an invalid number of colorspaces is given.
- availableColorspaces(Target='COLORSPACE_TARGET_COUNT', PrettyNames=False)
Returns a list of all the available colorspaces present in the OCIO config file for a particular target.
If COLORSPACE_TARGET_COUNT is passed in for Target then only the colorspaces and roles defined in the OCIO config file will be checked and none of the extras for the targets such as ‘Automatic’.
- Parameters:
Target (ColorspaceTarget, optional) – The target data type or device for which a colorspace can be defined. Defaults to COLORSPACE_TARGET_COUNT.
PrettyNames (bool, optional) – Flag used to indicate whether user interface friendly colorspace names are to be returned. Defaults to False.
- Raises:
IndexError – Raised if the stage index is out of range.
- Returns:
list of str– The list of colorspaces within the OCIO config file for a particular target.
- colorManagementEnabled()
Returns true if color management is enabled on the project.
- colorspace(Target)
Returns the colorspace or role for a particular target.
- Parameters:
Target (ColorspaceTarget) – The target in the pipeline where a colorspace or role can be defined.
- Raises:
IndexError – Raised if the target index is out of range.
- Returns:
str– The colorspace or role of the target data type or device.
- defaultColorspace(Target)
Returns the default colorspace or role for a particular target.
- Parameters:
Target (ColorspaceTarget) – The target data type or device for which a colorspace can be defined.
- Raises:
IndexError – Raised if the target index is out of range.
- Returns:
str– The default colorspace or role of the target data type or device.
- fileName()
Returns the name or path of the OCIO config file.
- hasColorspace(Colorspace)
Returns true if the given colorspace is present in the OCIO config file.
- Parameters:
Colorspace (str) – The colorspace or role to look for.
- Returns:
bool– True if the colorspace is present in the configuration file, false otherwise.
- isFileCustom()
Returns true if the OCIO config file is not one of the standard ones packaged with Mari.
- isFileValid()
Returns true if the OCIO config file is valid.
- isValid()
Returns true if the OCIO config file and corresponding colorspace targets are valid.
- reset()
Sets both the OCIO config file and each of the colorspace targets to their default.
- resolveColorspace(Target)
Returns the colorspace found within the OCIO config file for a particular target.
- Parameters:
Target (ColorspaceTarget) – The target in the pipeline where a colorspace or role can be defined.
- Raises:
IndexError – Raised if the target index is out of range.
- Returns:
str– The colorspace of the pipeline stage.
- setColorManagementEnabled(Enable)
Sets whether color management is enabled on the project.
- Parameters:
Enable (bool) – Whether color management is enabled.
- setColorspace(Target, Colorspace)
Sets the colorspace for a particular target.
- Parameters:
Target (ColorspaceTarget) – The target data type or device for which a colorspace can be defined.
Colorspace (str) – The new colorspace of the target data type or device.
- Raises:
IndexError – Raised if the target index is out of range.
ValueError – Raised if an invalid colorspaces, for the OCIO config file, is given.
- setFileName(FileName)
Sets the OCIO config file.
This causes the targets to be validated and updated to sensible defaults if they aren’t within the new OCIO config file.
- Parameters:
FileName (str) – Either the name of a standard OCIO config file packaged with
Marior a path to a custom one.- Raises:
ValueError – Raised if an invalid OCIO config file is given.
- class mari.ComboBox(Parent=None)
Bases:
WidgetBaseA Mari specific combo box widget.
Provides a custom combo box widget that supports sub-menus, separators, and disabled items.
Example Code
>>> # This example creates a new ComboBox object, add it to a QWidget and show it >>> import mari >>> from PySide6 import QtWidgets >>> >>> combo_box = mari.ComboBox() >>> >>> container = QtWidgets.QWidget() >>> container.setLayout(QtWidgets.QHBoxLayout()) >>> combo_box.addToLayout(container.layout()) >>> container.show()
- __init__(Parent=None)
Sets to the combo box specified by the given components.
- Parameters:
Parent (QWidget, optional)
- clear()
Removes all items from the combo box.
- currentIndex()
Returns the index of the current item in the combo box; otherwise returns -1 if the combo box is empty.
- currentIndexChanged(Index)
This is emitted when the current index of the combo box changes.
- Parameters:
Index (int) – The index of the combo box options that was made current.
- currentText()
Returns the current text.
If the combo box is editable, the current text is the value displayed by the line edit. Otherwise, it is the value of the current item or an empty string if the combo box is empty or no current item is set.
- Returns:
str– The current text of the combo box.
- currentTextChanged(Value)
This is emitted when the current text of the combo box changes.
- Parameters:
Value (str) – The text the combo box has changed to.
- findText(Text)
Returns the index of the item containing the given text; otherwise returns -1.
- Parameters:
Text (str) – The text to find in the combo box.
- setContents(Values)
Adds each of the strings in the given texts to the combo box.
The existing items are cleared and then each new item is appended in turn.
- Parameters:
Values (list of str) – The strings to add to the combo box.
- setCurrentIndex(Index)
Sets the index of the current item in the combo box.
- Parameters:
Index (int) – The index of the item to set.
- setCurrentText(Value)
Sets the currently selected value of the combo box.
- Parameters:
Value (str) – The value to select in the combo box.
- class mari.CustomLUTFilter
Bases:
PostFilterA post processing filter that applies a LUT from custom provided color values.
CustomLUTFilterobjects can be created by callingPostFilterCollection::createCustomLUT().Example Code
>>> # This examples creates a new CustomLUTFilter object through GLRender and PostFilterCollection >>> import mari >>> filter_collection = mari.gl_render.createPostFilterCollection("New Filter Collection") >>> file_lut = filter_collection.createCustomLUT("New Custom LUT") >>> mari.gl_render.deletePostFilterCollection(filter_collection)
- class mari.CustomProceduralLayer
Bases:
AdjustableLayerCustom Procedural Layers contain a child NodeGraph that generates procedural data for Layer payload.
You can access all types of layers from their containing
Channelobjects - for example:channel.layerList()You can check for
CustomProceduralLayerobjects by callingLayer::isCustomProceduralLayer():Example Code
>>> #This example finds custom procedural layers in the current channel >>> import mari >>> custom_procedural_layers = [] >>> channel = mari.geo.current().currentChannel() >>> for layer in channel.layerList(): ... if layer.isCustomProceduralLayer(): ... procedural_layers.append(layer)
- convertToPaintable(SelectedOnly=False)
Converts the Layer into a Paintable Layer.
As this operation changes the
Layertype, it is suggested that you reobtain a reference to thisLayer.- Parameters:
SelectedOnly (bool, optional) – Whether or not to bake the result into all patches or only the selected patches. Defaults to False.
- customProceduralType()
Return the type of procedural for this layer.
- Returns:
CustomProceduralNode.CustomProceduralType– The type of procedural.
- geoChannels()
Return a list of Geo Channel aliases that are in use within this Custom Procedural layer.
- Returns:
list of str– A list of aliases, or empty if none is found.
- missingGeoChannels()
Return a list of Geo Channel aliases that are missing within this Custom Procedural layer.
- Returns:
list of str– A list of aliases, or empty if none is found.
- nodeGraph()
Returns the NodeGraph object contained in this layer.
- Raises:
SystemError – Raised if the layer’s node graph cannot be found.
- Returns:
NodeGraph– Return the NodeGraph object contained in this layer.
- setCustomProceduralType(Type)
Sets the type of procedural layer for this layer.
- Parameters:
Type (CustomProceduralNode.CustomProceduralType) – (CustomProceduralType) Type to set.
- class mari.CustomProceduralNode
Bases:
GroupNodeThis class represents a Custom Procedural node.
- CUSTOMPROCEDURAL_TYPE_COLOR = 0
Color type.
- Type:
int
- CUSTOMPROCEDURAL_TYPE_MASK = 2
Mask type.
- Type:
int
- CUSTOMPROCEDURAL_TYPE_SCALAR = 1
Scalar type.
- Type:
int
- class CustomProceduralType
Bases:
objectThis describes the type of the Custom Procedural node.
- CUSTOMPROCEDURAL_TYPE_COLOR = 0
Color type.
- Type:
int
- CUSTOMPROCEDURAL_TYPE_MASK = 2
Mask type.
- Type:
int
- CUSTOMPROCEDURAL_TYPE_SCALAR = 1
Scalar type.
- Type:
int
- addCustomProceduralTag(Tag)
Adds the specified Custom Procedural tag to the Custom Procedural node.
- Parameters:
Tag (str) – The tag to add
- Raises:
ValueError – Raised if the tag is invalid.
- addCustomProceduralTags(Tags)
Adds the specified Custom Procedural tags to the Custom Procedural node.
- Parameters:
Tags (list of str) – The tags to add
- Raises:
ValueError – Raised if a tag is invalid.
- customProceduralTags()
Return a list of Custom Procedural tags applied to this Custom Procedural node.
- Returns:
list of str– A list of tags.
- customProceduralType()
Return the type of procedural node this is.
- Returns:
CustomProceduralType– The type of procedural.
- exportCustomProcedural(FileName, ThumbnailFileName='str')
Exports the Custom Procedural node to the given file name.
- Parameters:
FileName (str) – (str) The absolute path, file name, and extension to save the Custom Procedural to.
ThumbnailFileName (str, optional) – (str) Optional path to a thumbnail image to save with the Custom Procedural. Defaults to str.
- Raises:
IOError – Raised if there is a problem saving the file or invalid thumbnail image given.
ValueError – Raised if the Custom Procedural contains paint nodes, or has an output node mismatch to the ShaderModel it was created against.
- geoChannels()
Return a list of Geo Channel aliases that are in use within this Custom Procedural node.
- Returns:
list of str– A list of aliases, or empty if none is found.
- missingGeoChannels()
Return a list of Geo Channel aliases that are missing within this Custom Procedural node.
- Returns:
list of str– A list of aliases, or empty if none is found.
- static readMetadataFromCustomProceduralFile(CustomProceduralFilePath)
Reads the metadata in the Custom Procedural file pointed by the CustomProceduralFilePath and returns it as QJsonDocument.
- Parameters:
CustomProceduralFilePath (str) – The Custom Procedural file path to read from
- Raises:
IOError – Raised if the file is not a valid custom procedural.
- Returns:
QJsonDocument– The metadata as QJsonDocument
- static readSystemMetadataFromCustomProceduralFile(CustomProceduralFilePath)
Reads the system metadata in the Custom Procedural file pointed by the CustomProceduralFilePath and returns it as QJsonDocument.
- Parameters:
CustomProceduralFilePath (str) – The Custom Procedural file path to read from
- Raises:
IOError – Raised if the file is not a valid custom procedural.
- Returns:
QJsonDocument– The metadata as QJsonDocument
- static readTagsFromCustomProceduralFile(CustomProceduralFilePath)
Reads the tags in the Custom Procedural file pointed by the CustomProceduralFilePath.
- Parameters:
CustomProceduralFilePath (str) – The Custom Procedural file path to read from
- Raises:
IOError – Raised if the file is not a valid custom procedural.
- Returns:
list of str– The tags as a list of strings
- static readThumbnailFromCustomProceduralFile(CustomProceduralFilePath)
Reads the thumbnail in the Custom Procedural file pointed by the CustomProceduralFilePath.
- Parameters:
CustomProceduralFilePath (str) – The Custom Procedural file path to read from
- Raises:
IOError – Raised if the file is not a valid custom procedural.
- Returns:
QImage– The thumbnail as QImage
- removeCustomProceduralTag(Tag)
Removes the specified Custom Procedural tag from the Custom Procedural node.
- Parameters:
Tag (str) – The tag to remove
- removeCustomProceduralTags(Tags)
Removes the specified Custom Procedural tags from the Custom Procedural node.
- Parameters:
Tags (list of str) – The tags to remove
- setCustomProceduralTags(CustomProceduralTags)
Sets the list of Custom Procedural tags on the Custom Procedural node.
- Parameters:
CustomProceduralTags (list of str) – The list of tags to assign to the node
- Raises:
ValueError – Raised if the list of tags contains invalid tags.
- setCustomProceduralType(Type)
Sets the type of procedural node this is.
- Parameters:
Type (CustomProceduralType) – (CustomProceduralType) Type to set.
- static writeMetadataToCustomProceduralFile(MetadataMap, CustomProceduralFilePath)
Writes the given metadata in the given QJsonDocument to the CustomProceduralFilePath.
Note that this overwrites the existing metadata, so existing metadata needs to be united beforehand.
- Parameters:
MetadataMap (QJsonDocument) – The metadata in QJsonDocument
CustomProceduralFilePath (str) – The Custom Procedural file path to write to
- Raises:
IOError – Raised if the file is not a valid custom procedural.
- Returns:
bool– Whether the write was successful
- static writeTagsToCustomProceduralFile(Tags, CustomProceduralFilePath)
Writes the given tags to the CustomProceduralFilePath.
Note that this overwrites the existing tags, so existing tags needs to be united beforehand.
- Parameters:
Tags (list of str) – The tags in a list of strings
CustomProceduralFilePath (str) – The Custom Procedural file path to write to
- Raises:
IOError – Raised if the file is not a valid custom procedural.
- Returns:
bool– Whether the write was successful
- static writeThumbnailToCustomProceduralFile(Thumbnail, CustomProceduralFilePath)
Writes the given thumbnail to the CustomProceduralFilePath and replaces existing thumbnail.
- Parameters:
Thumbnail (QImage) – The thumbnail in QImage
CustomProceduralFilePath (str) – The Custom Procedural file path to write to
- Raises:
IOError – Raised if the file is not a valid custom procedural.
- class mari.DDI
Bases:
objectThis class gives access to some of the functionality of Mari’s Dynamic Data Interface.
The Dynamic Data Interface, or
DDI, is the low level data handling system inMari. This system manages the caches on disk and in memory.The functionality provided can be used to test
Mari‘s performance on different systems.A good test of raw performance is to set the cache size to 1 GB (but remember to change this back!) and then run a profile test for 4 or 5 GB. This ensures that all of the memory created during the test is saved and loaded. You should use a new, empty project for this sort of testing.
Example Code
>>> import mari >>> mari.ddi.garbageCollect()
This example shows how to add a trace to a data block to help track down a leak.
>>> leaked_hash = "99509829-142878836-1476483496-3107337093-1453028546-3157207537-1483745010-4081687562-826787922-3359455053-540328779-2788957582-2637324277-1847316313-2355536554-2879429988" ... mari.ddi.setTraceEnabled(leaked_hash) ... project = mari.projects.open("ProjectWithLeak") ... project.close() ... for trace in mari.ddi.traces(leaked_hash): ... print("DDI Leak: %s" % trace)
Warning
Please note that misuse of these methods can severely impact Mari’s performance. Dramatically increasing or decreasing cache sizes can (and probably will) have a negative effect.
Alias
ddi
- clearMemory()
Clear cacheable memory.
Write all blocks to disk that are marked cacheable (cacheable in this context refers to the ability to be written to disk. Cacheable blocks can be written to disk. Non-cacheable blocks that were loaded as temporary blocks are not cacheable). Then try to free blocks in the RLU (which only contains cacheable blocks) until there is only 512 MB
DDIusage. Non-cacheable (temprorary) blocks are not released.
- clearMemoryCache()
Releases RAM by uncaching currently cached data blocks.
After calling this method, the number of data blocks reported by liveBlocks should be significantly reduced. This method releases blocks in memory including those not marked as cacheable; in other words, this method will cause data loaded as temporary to be lost. For example, some brush bitmaps are loaded as temporary. It is advised to use this method for testing only, as releasing temporary data may lead to a crash.
- clearTraces(Hash)
Clears all callstack information presently held on a block.
- Parameters:
Hash (str) – The hash identifier of the block to clear
- dataBlocks()
Returns the total number of data blocks managed by Mari.
Marimanages data as individual blocks. This method returns the number of blocks thatMaricurrently knows about in the current project. Each block may be of any size, and may be reused multiple times.- Returns:
int– The number of individual blocks that Mari knows about in the current project
- garbageCollect(UnusedPatches=False)
Performs a full garbage collection on the cache directory.
Marirecords all of your brush strokes to theDDIas you are painting. When you exit the application, or remove those undo records, the data on disk is no longer needed. These garbage files are removed byMariautomatically.If you want to optimize your cache (just before archiving, for example) you can use this method. It should be used in conjunction with the
History::clear()method. This will ensure that only valid data remains in the cache.- Parameters:
UnusedPatches (bool, optional) – Delete patche images from the project cache that are no longer being referenced because a geo version has been removed. Defaults to False.
Note
This may take a while to execute, depending on the size of the cache.
- garbageCollectionEnabled()
Returns whether or not the DDI garbage collector is running.
This doesn’t necessarily mean that the garbage collector is currently performing a cleanup, but rather that the corresponding threads are started and that it’s free to operate.
- Returns:
bool– True if garbage collection is active.
- isLive(Hash)
Returns whether or not a block is loaded into system RAM.
- Parameters:
Hash (str) – The hash identifier of the block to check
- Returns:
bool– True if the block is loaded into system RAM, or False otherwise.
- liveBlocks()
Returns the number of blocks that are loaded into system RAM.
This can be smaller than the total number of blocks.
- Returns:
int– The number of blocks that are live - i.e. loaded into system RAM
- liveBytes()
Returns the number of bytes currently loaded into system RAM.
The number of bytes currently loaded into system RAM
- memoryCacheSize()
Returns the size of the memory cache.
- Returns:
int– The size in bytes of the memory cache
See also
setMemoryCacheSize
- profile(NumberOfBlocks=30000, BlockSize=30000, RandomSize=False)
Runs performance tests on the DDI.
This can help to track down problems on systems showing poor performance. This method will create a number of blocks of a given size. These blocks will be filled with random data to ensure they are unique, registered with the
DDI, and then freed. The time taken for this in milliseconds will be returned. If the operation detects any problems they will be reported into theMariLog.- Parameters:
NumberOfBlocks (int, optional) – The number of blocks to register while profiling. Defaults to 30000.
BlockSize (unsignedint, optional) – The maximum size of block to create while profiling, in bytes. Defaults to 30000.
RandomSize (bool, optional) – If set to true, each block will be of a random size between 1 and BlockSize bytes; otherwise all blocks will be exactly BlockSize bytes. Defaults to False.
- Returns:
int– The time in milliseconds that the test took to run
- setGarbageCollectionEnabled(Enabled)
Enables or disables the DDI garbage collector.
The garbage collector is automatically started when a project is loaded and remains active until it is either manually disabled or automatically when the project is closed.
- Parameters:
Enabled (bool)
- Raises:
RuntimeError – Raised if no project was open.
See also
mari.projects.open and mari.projects.create
- setMemoryCacheSize(Size)
Sets the amount of system memory used by the DDI for caching.
Marimaintains an area of system memory that it uses to cache data blocks. Blocks are loaded from disk into this cache, and then removed in a least-recently-used scheme. i.e. if blocks are used, they are kept around, but if a block is not used for a while and some memory needs to be freed, it will be cleared to make room for a new block.This method controls the size of this cache. It does not need to be too big, as
Mariis very efficient at managing this data. It is a good idea to limit this so other programs on your system have memory to work with.- Parameters:
Size (int) – The number of bytes
Marishould use for memory caching
Warning
If set to a large value, Mari will use all of the RAM on your system, and you will see degraded performance.
- setTraceEnabled(Hash, Enabled=True)
Enables or disables callstack tracing on a block.
When enabled callstack information will be recorded when references are added to a block. This information will then be output when a potential memory leak is detected and can be subsequently used to find it’s origin.
- Parameters:
Hash (str) – The hash identifier of the block to trace
Enabled (bool, optional) – Whether to enable or desable debug tracing. Defaults to True.
- traces(Hash)
Returns all callstacks for any references currently held to a block.
- Parameters:
Hash (str) – The hash identifier of the block to trace
- Returns:
list of str– A list of callstacks for the current references
- class mari.Environment
Bases:
objectAllows dynamic modification of the environment in the running application. Python’s ‘os.environ’ only allows the manipulation of the environment the Python interpreter is running in which doesn’t include the native application. This API guaranttees the ability to affect all apsects of the running application.
- changed(Name, Value)
This is emitted whenever a new environment variable is added or an existing environment variable is updated.
- Parameters:
Name (str) – The name of the environment variable that was added or updated.
Value (str) – The string value the environment variable was set to.
- exists(Name)
Returns whether or not an environment variable is present in the running environment.
- Parameters:
Name (str) – The name of the environment variable to check.
- Returns:
bool– True if the environment variable is present.
- get(Name)
Returns the value of an existing environment variable in the running environment.
- Parameters:
Name (str) – The name of the environment variable to check.
- Raises:
ValueError – Raised if ‘Name’ is not an existing environment variable.
- Returns:
str– The string value of an environment variable.
- names()
Returns the names of all environment variables in the running environment.
- Returns:
list of str– A list of all environment variables.
- removed(Name, Value)
This is emitted whenever an environment variable is removed.
- Parameters:
Name (str) – The name of the environment variable that was removed.
Value (str) – The string value the environment variable was set to.
- set(Name, NewValue)
Adds an environemt variable to the running environment if it doesn’t exist. If it already exists then it’s value is updated to ‘NewValue’.
- Parameters:
Name (str) – The name of the environment variable to add or update.
NewValue (str) – The string value to set the environment variable to.
- Raises:
NotImplementedError – Raised if the function is called on a platform other than Linux.
- Returns:
bool– True is returned if it succeeds and the environment is changed. This wont be the case if the environment variable is already set to ‘NewValue’.
- unset(Name)
Removes an environment variable from the running environment.
- Parameters:
Name (str) – The name of the environment variable to remove.
- Raises:
ValueError – Raised if ‘Name’ is not an existing environment variable.
NotImplementedError – Raised if the function is called on a platform other than Linux.
- Returns:
bool– True is returned if it succeeds and the environment is changed.
- class mari.EnvironmentLight
Bases:
LightAn object for creating lighting effects on a 3D mesh.
You can access lights through the
LightManager- for example:mari.lights.list()- AXIS_UP_X = 0
.
- Type:
int
- AXIS_UP_Y = 1
.
- Type:
int
- AXIS_UP_Z = 2
.
- Type:
int
- class CubeImageType
Bases:
object- TYPE_2D_CROSS = 3
3 or 3:4 ratio image with 6 square images in an cross shape
- Type:
int
- Type:
4
- TYPE_2D_LATLONG = 2
Rectangluar image with spherical distortion, similar to a world Atlas image.
- Type:
int
- TYPE_3D_CUBEMAP = 1
Accutal cubemap from DDS or EXR filetype.
- Type:
int
- TYPE_GUESS = 4
Allows the best guess for the supplied image to be used.
- Type:
int
- TYPE_NONE = 0
No type set.
- Type:
int
- class ImageUpAxis
Bases:
object- AXIS_UP_X = 0
.
- Type:
int
- AXIS_UP_Y = 1
.
- Type:
int
- AXIS_UP_Z = 2
.
- Type:
int
- MODE_ROTATE = 1
Animated Rotation.
- Type:
int
- MODE_STATIC = 0
Static Rotation.
- Type:
int
- class RotationMode
Bases:
object- MODE_ROTATE = 1
Animated Rotation.
- Type:
int
- MODE_STATIC = 0
Static Rotation.
- Type:
int
- TYPE_2D_CROSS = 3
3 or 3:4 ratio image with 6 square images in an cross shape
- Type:
int
- Type:
4
- TYPE_2D_LATLONG = 2
Rectangluar image with spherical distortion, similar to a world Atlas image.
- Type:
int
- TYPE_3D_CUBEMAP = 1
Accutal cubemap from DDS or EXR filetype.
- Type:
int
- TYPE_GUESS = 4
Allows the best guess for the supplied image to be used.
- Type:
int
- TYPE_NONE = 0
No type set.
- Type:
int
- canvasBlur()
Return the blur for this environment light canvas display.
- Returns:
float– The blur value
- canvasBlurChanged(Blur)
Emitted when canvasBlur changes.
- Parameters:
Blur (float) – The new value
- canvasDisplay()
Return the enabled state for this environment light canvas display.
- Returns:
bool– The enabled state value
- canvasDisplayChanged(Display)
Emitted when canvasDisplay changes.
- Parameters:
Display (bool) – The new value
- clearCubeImageCache()
Clear out the internally cached cubeImage data.
- clearLightCache()
Clear out the internally cached environment data.
- cubeImage()
Returns the image manager image used to produce the environment light.
Some image types cannot be stored in the image manager (i.e. DDS cubemaps). These types of files will return None as there is no image manager entry for them. In these cases use
cubeImageFilename()instead- Returns:
Image– The image manager image
See also
cubeImageFilename()
- cubeImageFilename()
Returns the filename of the image used as to produce the environment light.
- Returns:
str– The filename of the image
- cubeImageFilenameChanged(Filename)
Emitted when cubeImageFilename changes.
- Parameters:
Filename (str) – The new value
- cubeImageResolution()
Returns the cube image resolution. This resolution is used for all X, Y and Z sides of the cubemap.
- Returns:
int– The image up resolution
- cubeImageResolutionChanged(Resolution)
Emitted when cubeImageResolution changes.
- Parameters:
Resolution (int) – The new value
- cubeImageType()
Returns the present method used to convert the image into a cubemap.
- Returns:
CubeImageType– The cube image conversion type
- cubeImageTypeChanged(Type)
Emitted when cubeImageType changes.
- Parameters:
Type (int) – The new value
- cubeImageUpAxis()
Returns the image axis that is treated as ‘up’.
- Returns:
ImageUpAxis– The image up axis
- cubeImageUpAxisChanged(Axis)
Emitted when cubeImageUpAxis changes.
- Parameters:
Axis (int) – The new value
- fixedTo()
Returns the type of object that the light is fixed to.
Lights can be fixed to either the world or the camera. This allows lights to follow the view, ensuring models are illuminated at all times.
- Returns:
FixedTo– Light::SCENE if the light is fixed to the scene, or Light::CAMERA if fixed to the camera.
- fixedToChanged(Type)
Emitted when fixedTo changes.
- Parameters:
Type (int) – The new value
- intensity()
Return the intensity value for this environment light.
- Returns:
float– The intensity value
- intensityChanged(Intensity)
Emitted when intensity changes.
- Parameters:
Intensity (float) – The new value
- printLightCacheKeys()
Print out the internal environment light cache keys return Cache keys.
- rotationUp()
Return the rotation angle for this environment light.
- Returns:
float– The rotation angle
- rotationUpChanged(Rotation)
Emitted when rotationUp changes.
- Parameters:
Rotation (float) – The new value
- rotationUpMode()
Return the rotation mode for this environment light.
- Returns:
RotationMode– The rotation mode
- rotationUpModeChanged(Mode)
Emitted when rotationUpMode changes.
- Parameters:
Mode (int) – The new value
- rotationUpSpeed()
Return the rotation speed for this environment light.
- Returns:
float– The rotation speed, in rotations per second
- rotationUpSpeedChanged(Speed)
Emitted when rotationUpSpeed changes.
- Parameters:
Speed (float) – The new value
- setCanvasBlur(Blur)
Set the blur for the environment light canvas dislay.
- Parameters:
Blur (float) – The new blur for the environment light canvas display
- setCanvasDisplay(Display)
Set the enable for the environment light canvas dislay.
- Parameters:
Display (bool) – The enable state for the environment light canvas display
- setCubeImage(rImage, Type)
Sets the image and how to convert it to a cubemap.
- Parameters:
rImage (variant) – Value to set image as. Can be a
Imageor a string file pathType (CubeImageType) – How to convert the image into the cubemap image. Use TYPE_GUESS to allow auto detection to be used
- Raises:
ValueError – Raised if the rImage is empty, of an unsupported type or contains an invalid entry.
- setCubeImageResolution(Resolution)
Sets the cube image resolution.
- Parameters:
Resolution (int) – The cube image size used for all X, Y and Z sides of the cubemap.
- Raises:
ValueError – Raise if resolution is invalid
- setCubeImageType(Type)
Sets the image conversion type.
- Parameters:
Type (CubeImageType) – How to convert the image into the cubemap image. This method cannot accept the TYPE_GUESS value, use
setCubeImage()- Raises:
ValueError – Raised if the TYPE_GUESS value is used.
See also
setCubeImage()
- setCubeImageUpAxis(Axis)
Sets the image axis that is treated as ‘up’.
- Parameters:
Axis (ImageUpAxis) – The image axis to treat up
- Raises:
ValueError – Raise if the axis is invalid
- setFixedTo(TargetType)
Sets the type of object that the light should be fixed to.
- Parameters:
TargetType (FixedTo) –
Light::SCENEif the light is to be fixed to the scene, orLight::CAMERAif fixed to the camera.
See also
fixedTo()
- setIntensity(Intensity)
Set the intensity for the environment light.
- Parameters:
Intensity (float) – The new Intensity for the environment light
- setRotationUp(Angle)
Set the rotation about the up direction for the environment light.
- Parameters:
Angle (float) – The new angle for the environment light rotation, in degrees
- setRotationUpMode(Mode)
Set the rotation mode for the environment light.
- Parameters:
Mode (RotationMode) – The new rotation mode for the environment light
- setRotationUpSpeed(Speed)
Set the rotation speed about the up direction for the environment light.
- Parameters:
Speed (float) – The new speed for the environment light rotation, in rotations per second
- class mari.Event
Bases:
objectProvides a method for sending events to the system.
Example Code
>>> #This example sends "B" key to the canvas, which bakes the paint by default >>> import mari >>> from PySide6 import QtCore >>> mari.event.sendKeyEvent(mari.event.EventType.KEY_PRESS, QtCore.Qt.Key_B, 0, False)
- ALT_MODIFIER = 134217728
An Alt key on the keyboard is pressed.
- Type:
int
- APPLICATION_SPACE = 1
Origin is at the top-left pixel of the main window.
- Type:
int
- CANVAS_SPACE = 0
Origin is at the top-left pixel of the currently active canvas.
- Type:
int
- CONTROL_MODIFIER = 67108864
A Ctrl key on the keyboard is pressed.
- Type:
int
- DESKTOP_SPACE = 2
Origin is at the top-left pixel of the desktop.
- Type:
int
- class EventCoordinateSpace
Bases:
objectThis enum defines which coordinate space the position of an event is in.
- APPLICATION_SPACE = 1
Origin is at the top-left pixel of the main window.
- Type:
int
- CANVAS_SPACE = 0
Origin is at the top-left pixel of the currently active canvas.
- Type:
int
- DESKTOP_SPACE = 2
Origin is at the top-left pixel of the desktop.
- Type:
int
- class EventType
Bases:
objectThis enum type defines the valid event types.
- KEY_PRESS = 6
.
- Type:
int
- KEY_RELEASE = 7
.
- Type:
int
- MOUSE_DOUBLE_CLICK = 4
.
- Type:
int
- MOUSE_MOVE = 5
.
- Type:
int
- MOUSE_PRESS = 2
.
- Type:
int
- MOUSE_RELEASE = 3
.
- Type:
int
- TABLET_ENTER_PROXIMITY = 171
.
- Type:
int
- TABLET_LEAVE_PROXIMITY = 172
.
- Type:
int
- TABLET_MOVE = 87
.
- Type:
int
- TABLET_PRESS = 92
.
- Type:
int
- TABLET_RELEASE = 93
.
- Type:
int
- GROUP_SWITCH_MODIFIER = 1073741824
X11 only. A Mode_switch key on the keyboard is pressed.
- Type:
int
- KEYPAD_MODIFIER = 536870912
A keypad button is pressed.
- Type:
int
- KEY_PRESS = 6
.
- Type:
int
- KEY_RELEASE = 7
.
- Type:
int
- class KeyboardModifier
Bases:
objectThis enum describes the modifier keys.
- ALT_MODIFIER = 134217728
An Alt key on the keyboard is pressed.
- Type:
int
- CONTROL_MODIFIER = 67108864
A Ctrl key on the keyboard is pressed.
- Type:
int
- GROUP_SWITCH_MODIFIER = 1073741824
X11 only. A Mode_switch key on the keyboard is pressed.
- Type:
int
- KEYPAD_MODIFIER = 536870912
A keypad button is pressed.
- Type:
int
- META_MODIFIER = 268435456
A Meta key on the keyboard is pressed.
- Type:
int
- NO_MODIFIER = 0
No modifier key is pressed.
- Type:
int
- SHIFT_MODIFIER = 33554432
A Shift key on the keyboard is pressed.
- Type:
int
- LEFT_BUTTON = 1
The left button is pressed, or an event refers to the left button. (The left button may be the right button on left-handed mice.)
- Type:
int
- META_MODIFIER = 268435456
A Meta key on the keyboard is pressed.
- Type:
int
- MIDDLE_BUTTON = 4
The middle button.
- Type:
int
- MOUSE_DOUBLE_CLICK = 4
.
- Type:
int
- MOUSE_MOVE = 5
.
- Type:
int
- MOUSE_PRESS = 2
.
- Type:
int
- MOUSE_RELEASE = 3
.
- Type:
int
- class MouseButton
Bases:
objectThis enum type describes the different mouse buttons.
- LEFT_BUTTON = 1
The left button is pressed, or an event refers to the left button. (The left button may be the right button on left-handed mice.)
- Type:
int
- MIDDLE_BUTTON = 4
The middle button.
- Type:
int
- NO_BUTTON = 0
The button state does not refer to any button.
- Type:
int
- RIGHT_BUTTON = 2
The right button.
- Type:
int
- X_BUTTON_1 = 8
The first X button.
- Type:
int
- X_BUTTON_2 = 16
The second X button.
- Type:
int
- NO_BUTTON = 0
The button state does not refer to any button.
- Type:
int
- NO_MODIFIER = 0
No modifier key is pressed.
- Type:
int
- RIGHT_BUTTON = 2
The right button.
- Type:
int
- SHIFT_MODIFIER = 33554432
A Shift key on the keyboard is pressed.
- Type:
int
- TABLET_ENTER_PROXIMITY = 171
.
- Type:
int
- TABLET_LEAVE_PROXIMITY = 172
.
- Type:
int
- TABLET_MOVE = 87
.
- Type:
int
- TABLET_PRESS = 92
.
- Type:
int
- TABLET_RELEASE = 93
.
- Type:
int
- X_BUTTON_1 = 8
The first X button.
- Type:
int
- X_BUTTON_2 = 16
The second X button.
- Type:
int
- isPlaying()
Returns whether or not any events are currently queued for playback.
- Returns:
bool– True one or more events are in the event queue.
- playbackComplete()
This is emitted after the event queue has finished playing any events it had queued.
- recordPlay()
Playback all the events currently recorded.
- recordStart(Space='CANVAS_SPACE', Normalized=False)
Called to begin recording of the events sent to the receiver.
- Parameters:
Space (EventCoordinateSpace, optional) – The coordinate space to use for any mouse and/or tablet events. Defaults to CANVAS_SPACE.
Normalized (bool, optional) – Whether recorded positions should be specified in normalised device coordinates(0.0 - 1.0) or pixels. Defaults to False.
- recordStop()
Called to end recording triggered by a previous call to ‘recordStart’.
- recordString()
Returns the commands required to playback the events currently recorded.
- Returns:
str– The playback commands.
- sendKeyEvent(Type, Key, Modifiers, AutoRepeat, Msecs=0)
Triggers a key event directly in the receiver.
- Parameters:
Type (EventType) – The type of key event to trigger.
Key (int) – The key code that triggers the event.
Modifiers (int) – The keyboard modifier flags that existed immediately before the event occurred.
AutoRepeat (bool) – True if this event comes from an auto-repeating key; false if it comes from an initial key press.
Msecs (int, optional) – How many milliseconds to wait before sending the event. Defaults to 0.
- sendMouseEvent(Type, Pos, Button, Buttons, Modifiers, Space='CANVAS_SPACE', Normalized=False, Msecs=0, MoveCursor=True)
Triggers a mouse event directly in the receiver.
- Parameters:
Type (EventType) – The type of mouse event to trigger.
Pos (QPointF) – The mouse cursor’s position relative to the receiver.
Button (MouseButton) – The button that triggers the event.
Buttons (int) – Returns the button state when the event was generated. The button state is a combination of ‘MouseButton’ values.
Modifiers (int) – The keyboard modifier flags that existed immediately before the event occurred.
Space (EventCoordinateSpace, optional) – The coordinate space of the given position ‘Pos’. Defaults to CANVAS_SPACE.
Normalized (bool, optional) – Whether the given position ‘Pos’ is specified in normalized device coordinates(0.0 - 1.0) or pixels. Defaults to False.
Msecs (int, optional) – How many milliseconds to wait before sending the event. Defaults to 0.
MoveCursor (bool, optional) – Whether the cursor should move to the position specified by the event. This creates an additional mouse move event coming from the window system, which can have adverse affects for certain circumstances (e.g. moving in the canvas or node graph) however some UI elements use the cursor position rather than the event position in order to place them near the mouse (e.g. create node dialog and spawning palettes). Defaults to True.
- sendTabletEvent(Type, Pos, Pressure, Modifiers, Space='CANVAS_SPACE', Normalized=False, Msecs=0)
Triggers a tablet event directly in the receiver.
- Parameters:
Type (EventType) – The type of tablet event to trigger.
Pos (QPointF) – The mouse cursor’s position relative to the receiver.
Pressure (qreal) – The pressure for the device. 0.0 indicates that the stylus is not on the tablet, 1.0 indicates the maximum amount of pressure for the stylus.
Modifiers (int) – The keyboard modifier flags that existed immediately before the event occurred.
Space (EventCoordinateSpace, optional) – The coordinate space of the given position ‘Pos’. Defaults to CANVAS_SPACE.
Normalized (bool, optional) – Whether the given position ‘Pos’ is specified in normalised device coordinates(0.0 - 1.0) or pixels. Defaults to False.
Msecs (int, optional) – How many milliseconds to wait before sending the event. Defaults to 0.
- class mari.EventWorker
Bases:
object
- class mari.ExportItem
Bases:
MetadataRepresents the data model of export item.
Example Code
>>> # Get Current GeoEntity >>> geo = mari.geo.current() >>> # Get a Channel from the GeoEntity >>> channel = geo.channelList()[0] >>> # Create an ExportItem for the Channel and configure its source and target >>> eItem = mari.ExportItem() >>> eItem.setSourceNode(channel.channelNode()) >>> eItem.setFileTemplate("$CHANNEL.$UDIM.tif") >>> # Add ExportItem to ExportManager >>> mari.exports.addExportItem(eItem, mari.current.geo()) >>> # Export the ExportItem with a resolution override >>> mari.exports.exportTextures([eItem], "/tmp", Overrides = {"RESOLUTION": "512 x 512"})
- colorspace()
Returns the colorspace to which exported textures are converted.
- Returns:
str– The colorspace to convert the textures to
- colorspaceChanged(Colorspace)
Emitted when the colorspace to which exported textures are converted is modified.
- Parameters:
Colorspace (str) – The colorspace to convert the textures to
- depth()
Returns the depth in which textures are exported.
- Returns:
str– The texture depth for export
- depthChanged(Depth)
Emitted when the depth in which textures are exported is modified.
- Parameters:
Depth (str) – The texture depth for export
- deserializeFromString(XMLString)
Populate this ExportItem from the XMLString representing an ExportItem.
- Parameters:
XMLString (str) – The XMLString representing an
ExportItem
- errorStringList()
Returns the error string of ExportItem.
If this
ExportItemhas errors such as depth and file format mismatch. This function returns the string describing the error.- Returns:
list of str– The error string of ExportItem
- errorStringListChanged(ErrorStringList)
Emitted when the error string of ExportItem is modified.
- Parameters:
ErrorStringList (list of str) – The error string of
ExportItem
- exportEnabled()
Returns whether this ExportItem is enabled for export.
- Returns:
bool– Whether this ExportItem is enabled for export
- exportEnabledChanged(ExportEnabled)
Emitted when the Export Item is enabled or disabled for export.
- Parameters:
ExportEnabled (bool)
- Returns:
obj:`` : Whether this ExportItem is enabled for export
- exportedImagesUniform()
No description
- exportedImagesUniformColor()
No description
- fileOptions()
Returns the image file options of textures to be exported.
- Returns:
variant– The image file options of textures to be exported
- fileOptionsChanged(FileOptions)
Emitted when the image file options of textures to be exported is modified.
- Parameters:
FileOptions (variant) – The image file options of textures to be exported
- fileOptionsString()
Returns the string representation of image file options.
- Returns:
str– The string representation of image file options.
- fileTemplate()
Returns the file template of textures to be exported.
- Returns:
str– The file template of textures to be exported
- fileTemplateChanged(FileTemplate)
Emitted when the file template of textures to be exported is modified.
- Parameters:
FileTemplate (str) – The file template of textures to be exported
- geoEntity()
Returns the GeoEntity this ExportItem is associated with.
- imageExported(Path, Udim)
Emitted when an image is exported from this Export Item. Note that post-processing commands may not have finished running.
- Parameters:
Path (str) – The file path to the exported image.
Udim (int) – The Udim tile of the exported image.
- itemExported()
Emitted when this Export Item is exported, after any post-processing commands have run.
- postProcessCommand()
Returns the post process command to run after the export.
- Returns:
str– The post process command to run after the export
- postProcessCommandChanged(PostProcessCommand)
Emitted when the post process command to run after the export is modified.
- Parameters:
PostProcessCommand (str) – The post process command to run after the export
- postProcessedFileTemplate()
Returns the post processed file template of textures to be exported.
- Returns:
str– The post processed file template of textures to be exported
- preferredFileExtension()
Returns the preferred file extension for this item.
- resolution()
Returns the resolution at which textures are exported.
- Returns:
str– The texture resolution for export
- resolutionChanged(Resolution)
Emitted when the resolution at which textures are exported is modified.
- Parameters:
Resolution (str) – The texture resolution for export
- resolveColorspace()
Returns the resolved colorspace to which exported textures are converted.
This function does not take into account an overrides map
- Returns:
str– The resolved colorspace to convert the textures to
- resolveDepth()
Returns the depth of the images that the Export Manager is expected to use.
This function does not take into account an overrides map
- Returns:
Image.Depth– The depth in number of bits
- resolveDepthAsInternalFormat()
Returns the depth of the images that the Export Manager is expected to use in internal format.
This function does not take into account an overrides map
- Returns:
int– The depth in OpenGL unsigned integer format
- resolveExportFilePaths(RootPath='str')
Processes the fileTemplate() and returns the list of file paths with tokens replaced.
- Parameters:
RootPath (str, optional) – Optional root path to prepend to the file template. Defaults to str.
- Returns:
list of str– The list of file paths the fileTemplate() is resolved to
- resolveFileTemplate(Overrides='variant')
Replaces $ tokens in the fileTemplate and returns the resulting file path.
- Parameters:
Overrides (variant, optional) – An optional map of overrides (string key and values), that will be used to resolve the file template. The list of valid keys are “RESOLUTION”, “DEPTH”, “COLORSPACE”, and “”POST_PROCESS”. An example would be {“COLORSPACE” : “sRGB”}. Defaults to variant.
- Returns:
str– The file path after replacing $ tokens in the fileTemplate
- resolvePostProcessedFileTemplate(Overrides='variant')
Replaces $ tokens in the postProcessedFileTemplate and returns the resulting file path.
- Parameters:
Overrides (variant, optional)
- Returns:
str– The file path after replacing $ tokens in the postProcessedFileTemplate
- resolveResolutionSizes()
Returns a set of resolutions of the images in uvIndexList that the Export Manager is expected to use.
This function does not take into account an overrides map
- Returns:
list of
QSize– The resolutions as a QList<QSize>
- resolvedColorspace()
Returns the resolved colorspace to which exported textures are converted.
This function does not take into account an overrides map
- Returns:
str– The resolved colorspace to convert the textures to
Deprecated
Please use resolveColorspace() instead.
- serializeToString()
Serializes this ExportItem as an XMLString.
- Returns:
str– The XMLString representing this ExportItem
- setColorspace(Colorspace)
Sets the colorspace to which exported textures are converted.
- Parameters:
Colorspace (str) – The colorspace to convert the textures to
- setDepth(Depth)
Sets the depth in which textures are exported.
- Parameters:
Depth (str) – The texture depth for export
- setErrorStringList(ErrorStringList)
Sets the error string of ExportItem.
If this
ExportItemhas errors such as depth and file format mismatch. Set the error string via this function.- Parameters:
ErrorStringList (list of str) – The error string of
ExportItem
- setExportEnabled(ExportEnabled)
Sets whether this ExportItem is enabled for export.
- Parameters:
ExportEnabled (bool) – boolean to specify whether this
ExportItemis enabled for export.
- setFileOptions(FileOptions)
Sets the image file options of textures to be exported.
- Parameters:
FileOptions (variant) – The image file options of textures to be exported
- setFileTemplate(FileTemplate)
Sets the file template of textures to be exported.
- Parameters:
FileTemplate (str) – The file template of textures to be exported
- setGeoEntity(Entity)
Sets the GeoEntity this ExportItem is associated with.
- Parameters:
Entity (GeoEntity) – the
GeoEntityobjrect thisExportItemis associated with
- setPostProcessCommand(PostProcessCommand)
Sets the post process command to run after the export.
- Parameters:
PostProcessCommand (str) – The post process command to run after the export
- setPostProcessedFileTemplate(PostProcessedFileTemplate)
Sets the post processed file template of textures to be exported.
- Parameters:
PostProcessedFileTemplate (str) – The post processed file template of textures to be exported
- setResolution(Resolution)
Sets the resolution at which textures are exported.
- Parameters:
Resolution (str) – The texture resolution for export
- setSourceNode(SourceNode)
Sets the source node at which textures are flattened and exported from.
- Parameters:
SourceNode (Node) – the source node at which textures are flattened and exported from
- setUvIndexList(UVIndexList)
Set UV Index list to export.
- Parameters:
UVIndexList (list of
int) – UV Index list to export
- setWarningStringList(WarningStringList)
Sets the warning string of ExportItem.
If this
ExportItemhas warnings such as files to be overwritten. Set the warning string via this function.- Parameters:
WarningStringList (list of str) – The warning string of
ExportItem
- sourceColorspace()
Returns the colorspace of the source node.
- Returns:
str– The colorspace of the source node
- sourceDepth()
Returns the depth of the images that the Export Manager is expected to use.
This function does not take into account an overrides map
- Returns:
Image.Depth– The depth in number of bits
Deprecated
Please use resolveDepth() instead.
- sourceDepthAsInternalFormat()
Returns the depth of the images that the Export Manager is expected to use in internal format.
This function does not take into account an overrides map
- Returns:
int– The depth in OpenGL unsigned integer format
Deprecated
Please use resolveDepthAsInternalFormat() instead.
- sourceNode()
Returns the source node at which textures are flattened and exported from.
- Returns:
Node– The source node at which textures are flattened and exported from
- sourceNodeChanged(Node)
Emitted when the node is changed for the Export Item.
- Parameters:
Node (Node)
- sourceNodeDepth()
Returns the depth of the source node.
- Returns:
str– The depth of the source node
- sourceNodeName()
Returns the name of source node at which textures are flattened and exported from.
- Returns:
str– The name of source node at which textures are flattened and exported from
- sourceResolution()
Returns the resolution of the source node.
- Returns:
str– The resolution of the source node
- uvIndexList()
Return UV Index list to export.
- Returns:
list of
int– UV Index list to export
- warningStringList()
Returns the warning string of ExportItem.
If this
ExportItemhas warnings such as files to be overwritten. this function returns the string describing the warning.- Returns:
list of str– The warning string of ExportItem
- warningStringListChanged(WarningStringList)
Emitted when the warning string of ExportItem is modified.
- Parameters:
WarningStringList (list of str) – The warning string of
ExportItem
- class mari.ExportManager
Bases:
objectManages export functionality of Mari.
Example Code
>>> # Get Current GeoEntity >>> geo = mari.geo.current() >>> # Get a Channel from the GeoEntity >>> channel = geo.channelList()[0] >>> # Create an ExportItem for the Channel and configure its source and target >>> eItem = mari.ExportItem() >>> eItem.setSourceNode(channel.channelNode()) >>> eItem.setFileTemplate("$CHANNEL.$UDIM.tif") >>> # Add ExportItem to ExportManager >>> mari.exports.addExportItem(eItem, mari.current.geo()) >>> # Export the ExportItem with a resolution override >>> mari.exports.exportTextures([eItem], "/tmp", Overrides = {"RESOLUTION": "512 x 512"})
- addExportItem(Item, Entity)
Adds ExportItem associated with the given GeoEntity.
- Parameters:
Item (ExportItem) – The
ExportItemto add to the EntityEntity (GeoEntity) – The parent
GeoEntityto add theExportItemto
- Raises:
ValueError – Raised if an invalid export item or object was provided.
- allItemsExported(Items)
Emitted upon completion of exporting textures for a batch of ExportItems.
- Parameters:
Items (list of
variant)
- checkExportItemIsValid(Item, Entity)
Checks if an export item has a valid source node.
- Parameters:
Item (ExportItem) – The
ExportItemto check forEntity (GeoEntity) – The
GeoEntityto check for source node comparison
- Raises:
ValueError – Raised if an invalid export item or object was provided.
- Returns:
bool– Whether the export item has a valid source node
- colorspaceList()
Returns the list of supported texture colorspace for export.
Use this function to obtain the list of supported texture colorspace. “Original” indicates the original colorspace specified in the original channel or node.
- Returns:
list of str– The list of supported texture colorspace for export
- depthList()
Returns the list of supported texture depth for export.
Use this function to obtain the list of supported texture depth. “Original” indicates the original depth specified in the original channel or node.
- Returns:
list of str– The list of supported texture depth for export
- exportItemList(Entity)
Returns the list of ExportItem for the given GeoEntity.
- Parameters:
Entity (GeoEntity) – The
GeoEntitythe list ofExportItemis returned for- Raises:
ValueError – Raised if an invalid object was provided.
- Returns:
list of
ExportItem– the list of ExportItem for the given GeoEntity
- exportTextures(ExportItems, ExportRootPath, Overrides='variant', ShowProgressDialog=False)
Export textures with the settings from given ExportItem applied.
Example Code
>>> #This example globally overrides the patch list to export using an integer list in UV_INDICES overrides >>> eItems = [] >>> for geo in mari.geo.list(): ... eItem = mari.ExportItem() ... for node in geo.nodeGraph().nodeList(): ... if node.nodeName()=="diffuse": ... eItem.setSourceNode(node) ... eItem.setFileTemplate("$ENTITY/$CHANNEL.$UDIM.tif") ... mari.exports.addExportItem(eItem, geo) ... eItems.append(eItem) >>> >>> mari.exports.exportTextures( ... eItems, ... "/tmp", ... Overrides={"UV_INDICES": [0, 1, 2, 5]} # Export UDIMs 1001-1003 & 1006 of all GeoEntities ... )
>>> geo1, geo2 = mari.geo.list() # Assigns two GeoEntity instances to variables >>> eItems = [] >>> for geo in (geo1,geo2): ... eItem = mari.ExportItem() ... for node in geo.nodeGraph().nodeList(): ... if node.nodeName()=="diffuse": ... eItem.setSourceNode(node) ... eItem.setFileTemplate("$ENTITY/$CHANNEL.$UDIM.tif") ... mari.exports.addExportItem(eItem, geo) ... eItems.append(eItem) >>> >>> mari.exports.exportTextures( ... eItems, ... "/tmp", ... Overrides={"UV_INDICES": {geo1.uuid():[0], geo2.uuid():[5]}} # Export UDIM 1001 from Geo1 and 1006 from Geo2 ... )
- Parameters:
ExportItems (list of
ExportItem) – Specifies the various settings for export operationExportRootPath (str) – Specifies the root path to which textures are exported
Overrides (variant, optional) –
Specifies the map of various options to override the settings in each
ExportItem:BACKGROUND_EXPORT: boolean flag to force or not force background export. If not present, the user preferences in
Preferencesdialog is used.RESOLUTION: Resolution of exported textures. “Original” to override to the original resolution of patches. Otherwise, “WIDTH x HEIGHT” format e.g. “2048 x 2048”
DEPTH: Depth of exported textures. “Original” to override to the original depth of
ChannelorBakePointNode. Otherwise, “DEPTH bit” format e.g. “8bit (Byte)”, “16bit (Half)” or “32bit (Float)”COLORSPACE: Colorspace of exported textures. “Original” to override to the original Colorspace. Otherwise, specify the name of the colorspace e.g. “sRGB”Z
POST_PROCESS: Post process command to run after export. e.g. “ls $EXPORTED”
DISABLE_SMALL_UNIFORMS: boolean flag to disable small uniform export.
Mariexports 8x8 images if it detects an image to export is of uniform color.ENABLE_FULL_PATCH_BLEED: boolean flag to enable full patch texture bleed
REMOVE_ALPHA: boolean flag to force removal of alpha channel
BACKGROUND_EXPORT: boolean flag to force or not force background export. If not present, the user preferences in
Preferencesdialog is used.UV_INDICES: (variant) Pass in a list of zero-based UV indices if desired to specify the patches to export images for. If not specified or empty, images will be exported for all indices. The UDIM for a patch is the zero-based UV index plus 1001. Alternatively to specify a different patch list per
GeoEntityyou can pass in a variant map where the key is aGeoEntity‘s UUID, and the value is a UV index list. See examples of both above. Defaults to variant.
ShowProgressDialog (bool, optional) – Specifies whether to show the progress dialog. Defaults to False.
- Raises:
ValueError – Raised if an invalid export item was provided.
- Returns:
str– Returns the error message encountered during export
- imageExported(Item, Path, Udim)
Emitted upon completion of exporting image of an ExportItem.
- Parameters:
Item (ExportItem) –
ExportItemobject that has been exportedPath (str) – Path to image that was exported
Udim (int) – Udim of the image that was exported
- imageFileExtensionList()
Returns the list of supported image file extensions for export.
Use this function to obtain the list of supported image file extensions. “Original” indicates the original file format specified in the original channel or node.
- Returns:
list of str– The list of supported image file extensions for export
- imageFileOptions(Extension)
Returns the dictionary of image file options for the given file extension.
Use this function to obtain the result of
- Parameters:
Extension (str) – File extension to query the image file options for
- Returns:
variant– the dictionary for the file type specific options
- imageFileOptionsWidget(Extension)
Returns the widget to select the file type specific options.
- Parameters:
Extension (str) – File extension to show the image file options for
- Returns:
QWidget– the widget for selecting the file type specific options
- itemAdded(Entity, Item)
Emmited when an ExportItem is added to a GeoEntity.
- Parameters:
Entity (GeoEntity) – The
GeoEntitytheExportItemhas been added toItem (ExportItem) –
ExportItemobject that has been added
- itemExported(Item)
Emitted upon completion of exporting textures for the ExportItem.
- Parameters:
Item (ExportItem) –
ExportItemobject that has been exported
- itemRemoved(Entity, Item)
Emmited when an ExportItem is removed from a GeoEntity.
- Parameters:
Entity (GeoEntity) – The
GeoEntitytheExportItemhas been removed fromItem (ExportItem) –
ExportItemobject that has been removed
- postProcessCommandList()
Returns the list of post process commands for export.
Use this function to obtain the list of post process commands.
- Returns:
list of str– The list of post process commands
- preferredFileExtension(BitDepth)
Returns the preferred file extension for an exportItem of a given BitDepth.
- Parameters:
BitDepth (Image.Depth) – bit depth of the export item
- Returns:
str– the file extension or an empty string if the bitdepth is invalid
- registerPostProcessCommand(Command)
Registers a post process command to be listed by postProcessCommandList()
The post process command is run per image after exporting an image. $EXPORTED token within the command will be replaced by the file path of the exported image.
- Parameters:
Command (str) – The post process command to be run after exporting an image. $EXPORTED token will be replaced by the file path for each exported image.
- removeExportItem(Item)
Removes the given ExportItem.
- Parameters:
Item (ExportItem) – The
ExportItemto remove- Raises:
ValueError – Raised if an invalid export item was provided.
- resolutionList()
Returns the list of supported texture resolutions for export.
Use this function to obtain the list of supported texture resolutions. “Original” indicates the original resolution specified in the original channel or node.
- Returns:
list of str– The list of supported texture resolutions for export
- setImageFileOptions(Extension, Options)
Sets the dictionary of image file options for the given file extension.
Use this function to set file type specific options from a dictionary.
- Parameters:
Extension (str) – File extension to set the image file options for
Options (variant) – Dictionary of image file options to apply
- setPreferredFileExtension(BitDepth, Extension)
Set the preferred file extension for an exportItem of a given BitDepth.
- Parameters:
BitDepth (Image.Depth) – bit depth of the export item
Extension (str) – the file extension (“exr”, “tif”, …)
- class mari.FaceSelectionGroup
Bases:
SelectionGroupA specialised selection group that consists of faces.
- geoEntityList()
Returns a list of Geo Entities, that are parent to this face group.
A face selection group store various geometry meshes and a list of selected faces for this selection group. A GeoVersion has a list of meshes, that it uses to store low level geometry information, for various purposes, such as rendering, subdivision, and etc. Each GeoVersion has a parent
GeoEntity, that has a corresponding entry in the Objects palette. Therefore, given a selection group, it is possible to get a list of the parent geoversions and geoentities that are the parent of the selection group.- Raises:
RuntimeError – Raised if no project is opened.
- geoVersionList()
Returns a list of Geo Versions, that are direct parent to this face group.
A face selection group store various geometry meshes and a list of selected faces for this selection group. A GeoVersion has a list of meshes, that it uses to store low level geometry information, for various purposes, such as rendering, subdivision, and etc. Each GeoVersion has a parent
GeoEntity, that has a corresponding entry in the Objects palette. Therefore, given a selection group, it is possible to get a list of the parent geoversions and geoentities that are the parent of the selection group.- Raises:
RuntimeError – Raised if no project is opened.
- meshLocationToFaceSelectionIndexRangeListMap()
Returns the map of source mesh location path and the IndexRangeList of the selected faces for the mesh.
- Raises:
RuntimeError – Raised if no project is opened.
- Returns:
dict– the map of source mesh location path and the IndexRangeList of the selected faces for the mesh
- class mari.FileLUTFilter
Bases:
PostFilterA post processing filter that reads a 1D LUT from a file.
FileLUTFilterobjects can be created by callingPostFilterCollection::createFileLUT().Example Code
>>> # This examples creates a new FileLUTFilter object through GLRender and PostFilterCollection >>> import mari >>> filter_collection = mari.gl_render.createPostFilterCollection("New Filter Collection") >>> file_lut = filter_collection.createFileLUT("New File LUT") >>> mari.gl_render.deletePostFilterCollection(filter_collection)
- filePath()
Returns the file path of the LUT.
- Returns:
str– The current file path to read the LUT from.
- setFilePath(FilePath)
Sets the file path of the LUT.
- Parameters:
FilePath (str) – The new file path to read the LUT from.
- class mari.FileList(Value)
Bases:
objectStores a list of files and directories that can be used for custom attributes.
Example Code
>>> # This example creates a FileList object with a sample file path >>> import mari >>> file_list = mari.FileList(mari.FileList.Type.TYPE_SINGLE_FILE) >>> file_list.append("/tmp/Hello.txt")
- TYPE_CHOOSE_FILE = 4
Choose from the list of given files.
- Type:
int
- TYPE_DIRECTORY = 1
Supports directory paths.
- Type:
int
- TYPE_FILE = 0
Supports file paths.
- Type:
int
- TYPE_FILE_AND_DIRECTORY = 6
Supports files and directories.
- Type:
int
- TYPE_SAVE_FILE = 3
Supports a file for saving.
- Type:
int
- TYPE_SINGLE_DIRECTORY = 5
Supports a single directory.
- Type:
int
- TYPE_SINGLE_FILE = 2
Just support a single file.
- Type:
int
- class Type
Bases:
objectThis defines the type of contents the file list supports.
- TYPE_CHOOSE_FILE = 4
Choose from the list of given files.
- Type:
int
- TYPE_DIRECTORY = 1
Supports directory paths.
- Type:
int
- TYPE_FILE = 0
Supports file paths.
- Type:
int
- TYPE_FILE_AND_DIRECTORY = 6
Supports files and directories.
- Type:
int
- TYPE_SAVE_FILE = 3
Supports a file for saving.
- Type:
int
- TYPE_SINGLE_DIRECTORY = 5
Supports a single directory.
- Type:
int
- TYPE_SINGLE_FILE = 2
Just support a single file.
- Type:
int
- __init__(Value)
Creates a new file list.
- Parameters:
Value (variant) – This can either be a
FileList::Typeor anotherFileList.
- acceptNonExisting()
Returns true if the file list accepts non-existent files.
- Returns:
bool– Whether the file list accepts non-existent files
- append(File)
Inserts a file at the end of the list.
- Parameters:
File (str) – The file to append
- at(Index)
Returns the file at the given index in the list.
- Parameters:
Index (int) – The index of the file to return
- Returns:
str– The file at the given index
- clear()
Removes all files from the list.
- contains(File)
Returns true if the list contains an occurrence of the file, otherwise returns false.
- Parameters:
File (str) – The file to search for
- Returns:
bool– Whether the list contains an occurrence of the given file
- count()
Returns the number of files in the list.
- Returns:
int– The number of files in the list
- defaultDirectory()
Returns the default directory.
- Returns:
str– The default directory
- filter()
Returns the filter used in selecting files.
- Returns:
str– The file filter
- insert(Index, File)
Inserts the file at the given index in the list. If index is 0, the value is prepended to the list. If index is the size of the list, the file is appended to the list.
- Parameters:
Index (int) – The position to insert the file at
File (str) – The file to insert
- isEmpty()
Returns true if the list contains no files, otherwise returns false.
- Returns:
bool– Whether the list contains no files
- pathKey()
Returns the path key used by the widgets and dialogs for default path saving.
- Returns:
str– The path key used for default path saving
- pickedFile()
Returns the currently picked file.
- Returns:
str– The currently picked file
- removeAt(Index)
Removes the file at the given index.
- Parameters:
Index (int) – The index of the file to remove
- setAcceptNonExisting(AcceptNonExisting)
Sets whether the file list should accept non-existent files.
- Parameters:
AcceptNonExisting (bool) – Whether the file list accepts non-existent files
- setDefaultDirectory(DefaultDirectory)
Sets the default directory to open to (only if this is of type directory).
- Parameters:
DefaultDirectory (str) – The default directory to open to
- setFilter(Filter)
Sets the filter used in selecting files.
- Parameters:
Filter (str) – The file filter
- setPathKey(PathKey)
Sets the path key used by widgets and dialogs for default path saving.
- Parameters:
PathKey (str) – The path key used for default path saving
- setPickedFile(PickedFile)
Sets the currently chosen file.
- Parameters:
PickedFile (str) – The currently picked file
- class mari.FloatSlider(Parent=None)
Bases:
SliderBaseA floating-point slider widget.
Provides a custom single-precision floating-point slider widget.
Example Code
>>> # This example creates a new FloatSlider object, add it to a QWidget and show it >>> import mari >>> from PySide6 import QtWidgets >>> >>> float_slider = mari.FloatSlider() >>> container = QtWidgets.QWidget() >>> container.setLayout(QtWidgets.QHBoxLayout()) >>> float_slider.addToLayout(container.layout()) >>> container.show()
- __init__(Parent=None)
Sets to the float slider specified by the given components.
- Parameters:
Parent (QWidget, optional)
- setValue(Value)
Sets the value of the slider.
- Parameters:
Value (float) – The value to set the slider to.
- value()
Returns the value of the slider.
- Returns:
float– The value of the slider.
- valueChanged(Value)
This is emitted when the value of the slider changes.
- Parameters:
Value (float) – The value the slider has changed to.
- class mari.GLRender
Bases:
objectManages Mari’s OpenGL Renderer and associated objects.
Mariuses OpenGL to render in 3D. This object gives access to this renderer, allowing configuration of available shaders and other settings.Shadermodules can be applied using the appropriate methods onGeoEntityobjects.Example Code
>>> # This example checks if color manager is applied >>> import mari >>> is_color_manager_ppplied = mari.gl_render.isPostProcessingEnabled()
See also
Alias
gl_render
- SHADER_COMPILE_FAILED = 1
The shader failed to compile. This is most likely due to syntax errors in the GLSL code.
- Type:
int
- SHADER_LINK_FAILED = 2
The shader failed to link. This can be for many reasons such as references to declared functions that are not defined.
- Type:
int
- SHADER_LINK_SUCCESS = 3
The shader compiled and linked successfully and can be used.
- Type:
int
- SHADER_RELOAD_MACROS_FAILED = 0
An error occurred during dynamic macro replacement.
- Type:
int
- class ShaderCompileResult
Bases:
objectThese are used to define the various states a shader can be.
- SHADER_COMPILE_FAILED = 1
The shader failed to compile. This is most likely due to syntax errors in the GLSL code.
- Type:
int
- SHADER_LINK_FAILED = 2
The shader failed to link. This can be for many reasons such as references to declared functions that are not defined.
- Type:
int
- SHADER_LINK_SUCCESS = 3
The shader compiled and linked successfully and can be used.
- Type:
int
- SHADER_RELOAD_MACROS_FAILED = 0
An error occurred during dynamic macro replacement.
- Type:
int
- applyFilter(Filter)
Applies a filter to current layer.
- Parameters:
Filter (PostFilter) – The filter to apply
- Returns:
bool– true if filter successfully applied
- clearError()
Makes a single call to OpenGL’s ‘glGetError()’ and outputs the result to the log if an error is detected.
- createPostFilterCollection(Name)
Creates a new post process filter collection.
The creates a new post process filter stack with given name, and sets it as current.
- Parameters:
Name (str) – The name for the new post process filter collection.
- Raises:
ValueError – Raised if a collection with the given name already exists.
See also
currentPostFilterCollection(), deletePostFilterCollection(), findPostFilterCollection(), setPostFilterCollection()
- createQuickApplyGLSL(Name, DefinitionsSnippet='', BodySnippet='', IconPath='', DisplayMetadata=True)
Creates a new GLSL post processing filter that can be applied to the viewport.
Marisupports post-render processing effects. These can be used to color-correct, blur, filter or warp the viewport display to achieve different effects.- Filters are implemented as two snippets of GLSL shader code:
The DefinitionsSnippet defines uniforms and functions required for the filter
The BodySnippet contains the implementation of the filter itself
As multiple instances of a filter can be created, we need to give each instance a unique ID. To do this, all uniforms and function names in the shader should have a $ID appended to their names.
Maritakes this token internally and adds a unique ID. This preventing name collisions in shaders. For example, a definitions snippet that looks like:uniform float ScaleX_$ID_; uniform float ScaleY_$ID_;
will be translated internally into:
uniform float ScaleX1; uniform float ScaleY2;
Body snippets should be protected with braces, and can expect the color value of the pixel being processed to be available in a vec4 called “Out”.
If you wanted to simply multiply the viewport display pixels by a floating point value, for example, you could write something like:
definition_snippet = "uniform float ScaleValue_$ID_;" body_snippet = "{ Out.rgb *= ScaleValue_$ID_; }"
The values passed into the shader can be controlled by modifying a metadata value on the
PostFilterobject. The metadata value should have the same name and type as the uniform, but should not include the $ID. In the scaling example above, we could add some metadata to the filter called ScaleValue, and this would then be passed into the shader automatically.- Parameters:
Name (str) – The name for the new filter
DefinitionsSnippet (str, optional) – A snippet of GLSL code that defines the uniforms and functions used by this post process filter. Defaults to “”.
BodySnippet (str, optional) – A snippet of GLSL code that defines the body of the post process filter. Defaults to “”.
IconPath (str, optional) – Path of the icon used to represent the filter with. Defaults to “”.
DisplayMetadata (bool, optional) – If set to true the dialog will expose the metadata set on the filter allowing users to manipulate it. Defaults to True.
- Raises:
ValueError – Raised if a filter of the given name already exists.
- Returns:
GLSLFilter– A new post process filter object
- currentPostFilterCollection()
Returns the currently active post process filter collection.
These post process filters are executed in order.
See also
createPostFilterCollection(), deletePostFilterCollection(), findPostFilterCollection(), setPostFilterCollection()
- currentPostFilterCollectionModified()
This is emitted whenever the settings of any filter in the current post filter collection is changed.
- deletePostFilterCollection(Collection)
Deletes a post process filter collection.
- Parameters:
Collection (PostFilterCollection) – The post filter collection to delete.
See also
createPostFilterCollection(), currentPostFilterCollection(), findPostFilterCollection(), setPostFilterCollection()
- static deregisterCustomCubemapFile(UUID)
Deregisters a registered custom cubemap generation file.
Deregisters a new custom cubemap generation file
- Parameters:
UUID (str) – Unique ID of the file
- Raises:
ValueError – Raised if the given UUID is not valid
- static deregisterCustomImagemapFile(UUID)
Deregisters a registered custom imagemap generation file.
Deregisters a new custom imagemap generation file
- Parameters:
UUID (str) – Unique ID of the file
- Raises:
ValueError – Raised if the given UUID is not valid
- findFilter(Name)
Finds a filter.
- Parameters:
Name (str) – The name of filter required
- Returns:
PostFilter– NULL if filter not found
- findPostFilterCollection(Name)
Returns the post process filter collection of given name.
These post process filters are executed in order.
- Parameters:
Name (str) – The name for the post process filter collection to find.
- Returns:
PostFilterCollection– The post process filter collection with the given name, or NULL if no matching collection exists
See also
createPostFilterCollection(), currentPostFilterCollection(), deletePostFilterCollection(), setPostFilterCollection()
- findQuickApplyFilter(Name)
Returns the first occurrence of a filter with the given name.
- Parameters:
Name (str) – The name of filter to find
- Returns:
PostFilter– A filter with the given name, or NULL if not found
- isCurrentGLShaderProgramValid()
Returns whether the current GL shader program is compiled and linked fine.
Returns whether the current GL shader program is compiled and linked fine. If the current shader is built in the background, it will wait for the completion.
- isPostProcessingEnabled()
Indicates whether post processing color management is applied to the viewport.
- Returns:
bool– True if post processing is enabled, or false if not
- platformInformation()
Returns key/value pairs of OpenGL information obtained from the main OpenGL context.
- Raises:
RuntimeError – Raised if OpenGL has not been setup. This can be due to system issues or running in terminal mode.
- postFilterCollectionAdded(Collection)
This is emitted when a new post processing filter collection is added.
- Parameters:
Collection (PostFilterCollection) – The newly added post filter collection
- postFilterCollectionNames()
Returns the names of all the post filter collections.
- Returns:
list of str– The names of all the post filter collections
- postFilterCollectionRemoved(Name)
This is emitted when a post processing filter collection is removed.
- Parameters:
Name (str) – The name of the post filter collection that was removed
- postFilterCollections()
Returns all the post filter collections.
- Returns:
list of
PostFilterCollection– All the post filter collections
- postProcessingEnabled(Enabled)
This is emitted when post processing is enabled or disabled.
- Parameters:
Enabled (bool) – Whether of not post processing is enabled
- static registerCustomAdjustmentLayerFromXMLFile(Name, FilePath)
Registers a new adjustment layer type from the given XML file path.
- Parameters:
Name (str) – The name of the layer. Paths separated by / in the name will appear as nested menu groups.
FilePath (str) – The XML file path that defines the adjustment
- Raises:
ValueError – Raised if the given XML file does not contain a valid XML string
RuntimeError – Raised if the given Name exists
IOError – Raised if the given XML file does not exist
- static registerCustomBlendMode(DisplayName, FunctionName, BlendModeCode)
Registers a new custom blend mode.
- Registers a new custom blend mode written in GLSL. The code must contain a function :
that returns the result of blending in vec4
that takes in three arguments where the first argument is the base value in vec4, the second argument is the blended value in vec4, and the third argument is the blend amount
that has the function name matching the FunctionName parameter
Example Code
>>> # This example registers a custom blend mode >>> mari.gl_render.registerCustomBlendMode("My Mix", "Comp_MyMix",''' ... vec4 Comp_MyMix(vec4 base, vec4 over, float blend_amount) ... { ... //Blends using standard OpenGL mix for RGB with the blend_amount while the alpha is the max of base or over ... return vec4( mix(base.rgb, over.rgb, blend_amount), max(base.a,over.a) ); ... } ... ''')
- Parameters:
DisplayName (str) – The name of the blend mode to display in the GUI.
FunctionName (str) – The name of the GLSL function to call.
BlendModeCode (str) – The blend mode logic written in GLSL.
- static registerCustomCodeFile(UUID, FilePath)
Registers a new custom code file written in GLSL.
Registers a new custom code file written in GLSL. The text contents of the given file will be included in the compilation of
Mari‘s GLSL shader. In combination with the header file registered withregisterCustomHeaderFile(), the functions defined in the registered file will be available to custom layers and shaders. This behaves like .c file of C language. The UUID uniquely identifies the file. Another path registered with the same UUID is regarded as a new version for the file and replace the old one. The UUID and path pair is also used to track missing files.- Parameters:
UUID (str) – Unique ID of the file
FilePath (str) – The file path containing the GLSL
- Raises:
IOError – Raised if the given file does not exist
- static registerCustomCubemapFile(UUID, FilePath, MinMipSize=16)
Registers a new custom cubemap generation file written in GLSL.
Registers a new custom cubemap generation file written in GLSL. The text contents of the given file will be used to generate a cubemap with the given UUID. The UUID uniquely identifies the file. Another path registered with the same UUID is regarded as a new version for the file and replace the old one. The UUID and path pair is also used to track missing files.
- Parameters:
UUID (str) – Unique ID of the file
FilePath (str) – The file path containing the GLSL
MinMipSize (int, optional) – The smallest size of mipmap that should be generated for this environment map. Defaults to 16.
- Raises:
IOError – Raised if the given file does not exist
ValueError – Raised if the given UUID is not valid
- static registerCustomDiffuseShaderFromXMLFile(Name, FilePath)
Registers a new diffuse shader type from the given XML file path.
- Parameters:
Name (str) – The name of the layer.
FilePath (str) – The XML file path that defines the diffuse shader
- Raises:
ValueError – Raised if the given XML file does not contain a valid XML string
RuntimeError – Raised if the given Name exists
IOError – Raised if the given XML file does not exist
- static registerCustomHeaderFile(UUID, FilePath)
Registers a new custom header file written in GLSL.
Registers a new custom header file written in GLSL. The text contents of the given file will be included in relevant parts of the shader system.
Shaderand layer GLSL code can access function declarations and variables declared in the header file. This behaves like .h file of C language. The UUID uniquely identifies the file. Another path registered with the same UUID is regarded as a new version for the file and replace the old one. The UUID and path pair is also used to track missing files.- Parameters:
UUID (str) – Unique ID of the file
FilePath (str) – The file path containing the GLSL
- Raises:
IOError – Raised if the given file does not exist
- static registerCustomImagemapFile(UUID, FilePath)
Registers a new custom imagemap generation file written in GLSL.
Registers a new custom imagemap generation file written in GLSL. The text contents of the given file will be used to generate an imagemap with the given UUID. The UUID uniquely identifies the file. Another path registered with the same UUID is regarded as a new version for the file and replace the old one. The UUID and path pair is also used to track missing files.
- Parameters:
UUID (str) – Unique ID of the file
FilePath (str) – The file path containing the GLSL
- Raises:
IOError – Raised if the given file does not exist
ValueError – Raised if the given UUID is not valid
- static registerCustomLayeredShaderFromXMLFile(Name, FilePath)
Registers a new layered shader type from the given XML file path.
- Parameters:
Name (str) – The name of the layered shader.
FilePath (str) – The XML file path that defines the layered shader
- Raises:
ValueError – Raised if the given XML file does not contain a valid XML string
RuntimeError – Raised if the given Name exists
IOError – Raised if the given XML file does not exist
- static registerCustomNodeFromXMLFile(Name, FilePath, Hidden=False, IconPath='str')
Registers a new node type from the given XML file path.
- Parameters:
Name (str) – The name of the node. Paths separated by / in the name will appear as nested menu groups.
FilePath (str) – The XML file path that defines the adjustment
Hidden (bool, optional) – If true, the node remains registered and creatable via the API (and still appears in the list of available node types), but it will not appear in the node graph’s Tab Menu (Quick Create) or in the “Add Node” menus. Defaults to False.
IconPath (str, optional) – Fully-qualified path to an icon to display for this node in the “Add Node” menus. Ignored if empty. Defaults to str.
- Raises:
ValueError – Raised if the given XML file does not contain a valid XML string
RuntimeError – Raised if the given Name exists
IOError – Raised if the given XML file does not exist
- static registerCustomNodeUpgrade(OldVersionUUID, NewVersionUUID, AttributeRemapping, InputRemapping, OutputRemapping)
Registers a node upgrade from an old to new type.
This is used during the node upgrade process to re-target unversioned nodes of type OldVersionUUID be converted into the NewVersionUUID type.
- Parameters:
OldVersionUUID (str) – The version id of the old node type to upgrade.
NewVersionUUID (str) – The version id of the new node type that it should be converted into.
AttributeRemapping (dict<str,str>) – Old attribute to new attribute name mapping used to ensure old attributes are correctly copied across to their corresponding new attribute.
InputRemapping (dict<str,str>) – Old input to new input name mapping used to ensure old input connections are correctly maintained in the existing node graph.
OutputRemapping (dict<str,str>) – Old output to new output name mapping used to ensure old output connections are correctly maintained in the existing node graph.
- Raises:
RuntimeError – Raised if the given OldVersionUUID has already a registered upgrade.
RuntimeError – Raised if the given OldVersionUUID is a registered node type.
RuntimeError – Raised if the given NewVersionUUID is not a registered node type.
- static registerCustomProceduralLayerFromXMLFile(Name, FilePath)
Registers a new procedural layer type from the given XML file path.
- Parameters:
Name (str) – The name of the layer. Paths separated by / in the name will appear as nested menu groups.
FilePath (str) – The XML file path that defines the procedural
- Raises:
ValueError – Raised if the given XML file does not contain a valid XML string
RuntimeError – Raised if the given Name exists
IOError – Raised if the given XML file does not exist
- static registerCustomSpecularShaderFromXMLFile(Name, FilePath)
Registers a new specular shader type from the given XML file path.
- Parameters:
Name (str) – The name of the layer.
FilePath (str) – The XML file path that defines the specular shader
- Raises:
ValueError – Raised if the given XML file does not contain a valid XML string
RuntimeError – Raised if the given Name exists
IOError – Raised if the given XML file does not exist
- static registerCustomStandaloneShaderFromXMLFile(Name, FilePath)
Registers a new standalone shader type from the given XML file path.
- Parameters:
Name (str) – The name of the layer.
FilePath (str) – The XML file path that defines the standlone shader
- Raises:
ValueError – Raised if the given XML file does not contain a valid XML string
RuntimeError – Raised if the given Name exists
IOError – Raised if the given XML file does not exist
- reloadXMLDefinitions()
Reloads layer and shader definition files.
A custom shader and layer developer can reload and test the shader and layer definition files without relaunching
Mariby executing this function.
- removeQuickApplyFilter(Filter)
Deletes (removes) a filter.
- Parameters:
Filter (PostFilter) – The filter to delete
- Raises:
ValueError – Raised if the filter is not a quick apply filter.
- runGLSLCode(GLSLCode, Destination, Source=None, Mask=None, BlendMode='str', BlendAmount=1.0)
Runs the given GLSL code and writes the result into the given ImageSet.
Runs the given GLSL code and writes the result into the Destination
ImageSet.The GLSL code must write the result into the “Output” variable as vec4.
When Source is provided, the GLSL code can use the values from the texture values in Source by using the token, “#Input”. The result will be blended onto the Source
ImageSetwith Mask applied using the BlendMode and BlendAmountExamples :
This fills selected area in red and leave the rest black.
mari.gl_render.runGLSLCode("Output = vec4(_State.Selected,0,0,1);",DestImageSet)This fills the selected area in red and blends it with Source image set and writes the result into Dest
mari.gl_render.runGLSLCode("Output = vec4(1,0,0,_State.Selected);",DestImageSet,SourceImageSet)This amplifies the red component of non-masked area of the Source imageset and writes the result into Dest
mari.gl_render.runGLSLCode("Output = vec4(#Input.r*2.0,#Input.gba",DestImageSet,SourceImageSet,MaskImageSet)This fills the selected area in transparency. Note that, in order to modify alpha component, you must use Comp_Copy blend mode
mari.gl_render.runGLSLCode("Output = mix(#Input, vec4(0,0,0,0), float(_State.Selected));",DestImageSet,SourceImageSet,None,"Comp_Copy")- Parameters:
GLSLCode (str) – The GLSL code to run
Destination (ImageSet) – The Destination
ImageSetto write the result intoSource (ImageSet, optional) – The Source
ImageSetto look up input textures from. Defaults to None.Mask (ImageSet, optional) – The Mask
ImageSetto use as a mask for blending. Defaults to None.BlendMode (str, optional) – The name of the blend mode to use for blending. Defaults to str.
BlendAmount (float, optional) – The blend amount for blending. Defaults to 1.0.
- setCurrentPostFilterCollection()
This is emitted just after the current post filter collection is changed.
- setPostFilterCollection(Collection)
Sets a post process filter collection as the current.
Changes the current post process filter collection to another.
- Parameters:
Collection (PostFilterCollection) – The post filter collection to set.
See also
createPostFilterCollection(), currentPostFilterCollection(), deletePostFilterCollection(), findPostFilterCollection()
- setPostProcessingEnabled(Enabled)
Enables or disables post processing color management in the viewport.
- Parameters:
Enabled (bool) – True to enable post processing, or false to disable it
- shaderCompileComplete(Result, ErrorMessage)
This is emitted whenever the current GL shader program is compiled and linked.
# Print out result when current GL shader program compiles. def printShaderCompileResult(result, error_message): print('Shader Compile SUCCEEDED' if result == mari.gl_render.ShaderCompileResult.SHADER_LINK_SUCCESS else 'Shader Compile FAILED') if error_message: print('Error Message:\n', error_message) mari.utils.connect(mari.gl_render.shaderCompileComplete, printShaderCompileResult)
- Parameters:
Result (GLRender.ShaderCompileResult) – Whether the current GL shader program is compiled and linked successfully.
ErrorMessage (str) – The associated error message if compilation or linking failed.
- upgradeExistingShadersAndLayers()
Upgrades existing shaders and layers based on up-to-date XML definitions.
Upgrades existing shaders and layers based on up-to-date XML definitions. A custom shader and layer developer can call this function after
reloadXMLDefinitions()to update existing shaders and layers with the new updated definitions.
- class mari.GLSLFilter
Bases:
PostFilterA post processing filter that runs custom GLSL code.
GLSLFilterobjects can be created by callingPostFilterCollection::createGLSL().Example Code
>>> # This examples creates a new GLSLFilter object through GLRender and PostFilterCollection >>> import mari >>> filter_collection = mari.gl_render.createPostFilterCollection("New Filter Collection") >>> glsl_filter = filter_collection.createGLSL("New GLSL Filter") >>> mari.gl_render.deletePostFilterCollection(filter_collection)
- CLAMP_REPEAT = 1
Loop around in texture space, so -0.2 becomes 0.8, 1.2 becomes 0.2, and so on.
- Type:
int
- CLAMP_TO_EDGE = 0
Repeat the edge pixel for out of range values.
- Type:
int
- class Clamp
Bases:
objectThe strategy for handling out-of-range errors.
- CLAMP_REPEAT = 1
Loop around in texture space, so -0.2 becomes 0.8, 1.2 becomes 0.2, and so on.
- Type:
int
- CLAMP_TO_EDGE = 0
Repeat the edge pixel for out of range values.
- Type:
int
- FILTER_LINEAR = 0
Filter the texture using a bilinear filter.
- Type:
int
- FILTER_MIPMAP_LINEAR = 2
Perform a mipmapped linear lookup on the texture.
- Type:
int
- FILTER_NEAREST = 1
Filter the texture by sampling the value of the nearest pixel.
- Type:
int
- FORMAT_L = 1
Legacy. The texture has 1 component per pixel. Please use FORMAT_R instead.
- Type:
int
- FORMAT_R = 1
The texture has 1 component per pixel.
- Type:
int
- FORMAT_RGB = 3
The texture has 3 components per pixel.
- Type:
int
- FORMAT_RGBA = 4
The texture has 4 components per pixel.
- Type:
int
- class Filter
Bases:
objectFiltering modes that can be selected when performing texture look-ups.
- FILTER_LINEAR = 0
Filter the texture using a bilinear filter.
- Type:
int
- FILTER_MIPMAP_LINEAR = 2
Perform a mipmapped linear lookup on the texture.
- Type:
int
- FILTER_NEAREST = 1
Filter the texture by sampling the value of the nearest pixel.
- Type:
int
- class Format
Bases:
objectThis defines the format of the incoming data.
- FORMAT_L = 1
Legacy. The texture has 1 component per pixel. Please use FORMAT_R instead.
- Type:
int
- FORMAT_R = 1
The texture has 1 component per pixel.
- Type:
int
- FORMAT_RGB = 3
The texture has 3 components per pixel.
- Type:
int
- FORMAT_RGBA = 4
The texture has 4 components per pixel.
- Type:
int
- bodySnippet()
Returns the body GLSL snippet for the filter.
- Returns:
str– Body GLSL snippet.
- definitionsSnippet()
Returns the definition GLSL snippet for the filter.
- Returns:
str– The GLSL shader snippet that defines the functions and uniforms for this post process filter.
- deleteTexture(SamplerName)
Deletes the texture associated with the given sampler.
This deletes and frees the texture associated with the given sampler. You should do this when replacing the texture with a new one.
- Parameters:
SamplerName (str) – The name of the sampler associated with the texture to delete
- enabledChanged(Enabled)
This is emitted when the filter is enabled or disabled.
DEPRICATED (3.0v2): This function will be removed in a future version. Please use
flagsChanged()instead.- Parameters:
Enabled (bool)
- setBodySnippet(BodySnippet)
Sets the body GLSL snippet for the filter.
- Parameters:
BodySnippet (str) – Body GLSL snippet.
- setDefinitionsSnippet(DefinitionsSnippet)
Sets the definition GLSL snippet for the filter.
- Parameters:
DefinitionsSnippet (str) – The GLSL shader snippet that defines the functions and uniforms for this post process filter.
- setTexture1D(SamplerName, Width, DataFormat, Data, MinFilter='FILTER_LINEAR', MagFilter='FILTER_LINEAR', ClampS='CLAMP_TO_EDGE', ClampT='CLAMP_TO_EDGE')
Adds a 1D texture for this filter to use.
Post processing filters, such as look up tables (LUTs), need input data to work with. This method makes it possible to provide texture data for use in the filter.
This is not really intended for large images, as upload performance will not be great.
All texture data is assumed to be floating point, and is uploaded unclamped.
- Parameters:
SamplerName (str) – The name of the sampler to bind this texture to
Width (int) – The width of the texture in pixels.
DataFormat (Format) – The format of the incoming texture data.
Data (list of
float) – A list of floating point values that constitutes the data for the texture. This should contain (Width * components per pixel) entriesMinFilter (Filter, optional) – The filter to use when minifying the texture. Defaults to FILTER_LINEAR.
MagFilter (Filter, optional) – The filter to use when magnifying the texture. Defaults to FILTER_LINEAR.
ClampS (Clamp, optional) – The method for clamping the texture in the S Direction. Defaults to CLAMP_TO_EDGE.
ClampT (Clamp, optional) – The method for clamping the texture in the T direction. Defaults to CLAMP_TO_EDGE.
- setTexture2D(SamplerName, Width, Height, DataFormat, Data, MinFilter='FILTER_LINEAR', MagFilter='FILTER_LINEAR', ClampS='CLAMP_TO_EDGE', ClampT='CLAMP_TO_EDGE')
Adds a 2D texture for this filter to use.
Post processing filters, such as look up tables (LUTs), need input data to work with. This method makes it possible to provide texture data for use in the filter.
This is not really intended for large images, as upload performance will not be great.
All texture data is assumed to be floating point, and is uploaded unclamped.
- Parameters:
SamplerName (str) – The name of the sampler to bind this texture to
Width (int) – The width of the texture in pixels
Height (int) – The height of the texture in pixels
DataFormat (Format) – The format of the incoming texture data
Data (list of
float) – A list of floating point values that constitutes the data for the texture. This should contain (Width * Height * components per pixel) entriesMinFilter (Filter, optional) – The filter to use when minifying the texture. Defaults to FILTER_LINEAR.
MagFilter (Filter, optional) – The filter to use when magnifying the texture. Defaults to FILTER_LINEAR.
ClampS (Clamp, optional) – The method for clamping the texture in the S Direction. Defaults to CLAMP_TO_EDGE.
ClampT (Clamp, optional) – The method for clamping the texture in the T direction. Defaults to CLAMP_TO_EDGE.
- setTexture3D(SamplerName, Width, Height, Depth, DataFormat, Data, MinFilter='FILTER_LINEAR', MagFilter='FILTER_LINEAR', ClampS='CLAMP_TO_EDGE', ClampT='CLAMP_TO_EDGE', ClampR='CLAMP_TO_EDGE')
Adds a 3D texture for this filter to use.
Post processing filters, such as look up tables (LUTs), need input data to work with. This method makes it possible to provide texture data for use in the filter.
This is not really intended for large images, as upload performance will not be great.
All texture data is assumed to be floating point, and is uploaded unclamped.
- Parameters:
SamplerName (str) – The name of the sampler to bind this texture to
Width (int) – The width of the texture in pixels
Height (int) – The height of the texture in pixels
Depth (int) – The height of the texture in pixels
DataFormat (Format) – The format of the incoming texture data.
Data (list of
float) – A list of floating point values that constitutes the data for the texture. This should contain (Width * Height * Depth * components per pixel) entriesMinFilter (Filter, optional) – The filter to use when minifying the texture. Defaults to FILTER_LINEAR.
MagFilter (Filter, optional) – The filter to use when magnifying the texture. Defaults to FILTER_LINEAR.
ClampS (Clamp, optional) – The method for clamping the texture in the S Direction. Defaults to CLAMP_TO_EDGE.
ClampT (Clamp, optional) – The method for clamping the texture in the T direction. Defaults to CLAMP_TO_EDGE.
ClampR (Clamp, optional) – The method for clamping the texture in the R direction. Defaults to CLAMP_TO_EDGE.
- updateTexture1D(SamplerName, Data)
Updates an existing 1D texture.
This is similar to a glTexSubImage1D call.
- Parameters:
SamplerName (str) – The name of the sampler to bind this texture to. This must already have a texture bound using setTexture2D
Data (list of
float) – A list of floating point values that constitutes the data for the texture. This should contain (width * components per pixel) entries
- Raises:
ValueError – Raised if Data does not contain the correct number of entries, or another parameter is incorrect.
Note
The width and format of the texture update must be the same as the texture set with setTexture1D. If Data does not contain the correct number of samples, this function will raise an exception.
- updateTexture2D(SamplerName, Data)
Updates an existing 2D texture.
This is similar to a glTexSubImage2D call.
- Parameters:
SamplerName (str) – The name of the sampler to bind this texture to. This must already have a texture bound using setTexture2D
Data (list of
float) – A list of floating point values that constitutes the data for the texture. This should contain (width * height * components per pixel) entries
- Raises:
ValueError – Raised if Data does not contain the correct number of entries, or another parameter is incorrect.
Note
The width, height, and format of the texture update must be the same as the texture set with setTexture2D. If Data does not contain the correct number of samples, this function will raise an exception.
- updateTexture3D(SamplerName, Data)
Updates an existing 3D texture.
This is similar to a glTexSubImage3D call.
- Parameters:
SamplerName (str) – The name of the sampler to bind this texture to. This must already have a texture bound using setTexture3D
Data (list of
float) – A list of floating point values that constitutes the data for the texture. This should contain (width * height * depth * components per pixel) entries
- Raises:
ValueError – Raised if Data does not contain the correct number of entries, or another parameter is incorrect.
Note
The width, height, depth, and format of the texture update must be the same as the texture set with setTexture3D. If Data does not contain the correct number of samples, this function will raise an exception.
- class mari.GLSLFilterFactory(Name='str')
Bases:
objectClass to create filters.
Testing
- __init__(Name='str')
Initialize the class using the given name.
The name must be unique to the filter type.
- Parameters:
Name (str, optional) – The name to use. Defaults to str.
- deregisterFilter()
No description
- registerFilter(CreateMenuEntries=True, IconPath='str', DisplayProperties=True)
Registers this filter into the filter system.
- Parameters:
CreateMenuEntries (bool, optional) – If false, does not create entries in the main ‘Filters’ menu and the filter selection lists. Defaults to True.
IconPath (str, optional) – Path to an icon to use for the registered filter in the main ‘Filters’ menu. Defaults to str.
DisplayProperties (bool, optional) – If false, hides the properties of the filter from the filter UI. Defaults to True.
- setupFilter(Filter)
Override this function in derived classes to add properties, connect signals, etc to each instance of the filter created.
- Parameters:
Filter (GLSLFilter) – An instance of mari.GLSLFilter that requires initialising.
- class mari.GeoChannel
Bases:
MetadataRepresents a Geo-Channel, part of a GeoEntity.
Geo-channel(s) are image sets that are stored at the
GeoEntitylevel; this is different from paint nodes, which store their image sets as part of the nodegraph. Geo-Channel(s) also have aliases, comma-delimited, that serve as links to the imagesets. This means we can easily access the contents of the geo-channel imagesets via aliases and call Imageset operations on the former, such as importing textures, exporting textures, propagating them down a nodegraph and etc.Example Code
This example creates and returns a
GeoChannelon the current Geo Entity>>> newGeoChannel = mari.geo.current().createGeoChannel()This example sets some aliases on the newly added geo-channel
>>> newGeoChannel.setAliases("ao,roughness")This example accesses the imageset of the geo-channel
>>> imageSet = newGeoChannel.imageSet()The following example removes the newly added geo-channel
>>> mari.geo.current().removeGeoChannel(newGeoChannel)- aliases()
Returns the aliases of the geo-channel.
- Returns:
list of str– List of aliases, comma-delimited from the name.
- geoChannelLayers()
Returns a list of Procedural layers that are set to one of the GeoChannel’s aliases.
- Returns:
list of
Layer– List of layers.
- geoChannelNodes()
Returns a list of GeoChannel nodes that are set to one of the GeoChannel’s aliases.
- Returns:
list of
GeoChannelNode– List of GeoChannel nodes.
- imageSetChanged(pImageSet)
This is emitted when the image set of the geo channel is changed.
- Parameters:
pImageSet (ImageSet) – The updated imageset.
- name()
Returns the name of the geo-channel.
- Returns:
str– The name.
- nameChanged(Name)
This is emitted when the name (aliases) of the geo channel changed.
- Parameters:
Name (str) – The changed name (aliases).
- static sanitizedName(Name)
Returns a santized name that is suitable for use as a GeoChannel alias.
All characters that are not alphanumeric, an underscore or a dash are replaced with an underscore.
- Parameters:
Name (str) – The name to be sanitized.
- Returns:
str– Sanitized name.
- setAliases(Aliases)
Sets the aliases of the geo-channel.
- Parameters:
Aliases (list of str) – The list of aliases to set.
- Raises:
ValueError – Raised if the aliases are invalid.
- setImageSet(ImageSetObject)
Sets an image set for the geo-channel.
- Parameters:
ImageSetObject (ImageSet) – The image set object.
- Raises:
ValueError – Raised if the image set is invalid.
- setName(Name)
Sets the name of the geo-channel.
- Parameters:
Name (str) – The name of the channel.
- Raises:
ValueError – Raised if name is invalid.
- class mari.GeoChannelNode
Bases:
NodeRepresents a node that can output geometry data from a Geo-Channel of GeoEntity.
Example Code
This example obtains a
GeoChannelNodefrom the node graph of the current geo entity and>>> for node in nodeGraph.nodeList(): ... if node.isGeoChannelNode(): ... mari.app.log("Found GeoChannelNode '%s' with geo-channel name '%s'" % (node.nodeName(), node.geoChannelName()))
The following example demonstrates the usage of creating a new geo-channel and setting GeoChannelName of a geo-channel node
>>> geoChannelName = "MyCurvature" >>> geoChannel = mari.geo.current().createGeoChannel() >>> geoChannel.setName(GeoChannelName) >>> for node in nodeGraph.nodeList(): ... if node.isGeoChannelNode(): ... node.setGeoChannelName(geoChannelName)
- geoChannelName()
Returns the geo-channel name from which the gei channel data is fed from.
- geoChannelNameChanged(Name)
This is emitted when the Geo-Channel Name property changes.
- Parameters:
Name (str) – The name of the geo-channel.
- isGeoChannelNode()
Returns whether this node is a GeoChannelNode.
- Returns:
bool– Whether this node is a GeoChannelNode
- setGeoChannelName(Name)
Set the geo-channel name from which the gei channel data is fed from.
- Parameters:
Name (str) – The name of the geo-channel.
- Raises:
ValueError – Raised if the given Name is invalid.
- class mari.GeoEntity
Bases:
LockableThese are the geometric meshes referred to as “Objects” in the GUI.
Example Code
# This examples obtains the current geometry object >>> import mari >>> current_object = mari.geo.current()
- class ChannelDestroyStrategy
Bases:
objectStrategy adopted when destroying a channel that’s shared.
- DESTROY_ALL = 1
Destroy the channel and its layers regardless.
- Type:
int
- DESTROY_NONE = 0
Don’t destroy the layers.
- Type:
int
- DESTROY_UNSHARED = 2
Don’t destroy the channel.
- Type:
int
- DESTROY_ALL = 1
Destroy the channel and its layers regardless.
- Type:
int
- DESTROY_NONE = 0
Don’t destroy the layers.
- Type:
int
- DESTROY_UNSHARED = 2
Don’t destroy the channel.
- Type:
int
- SYSTEM_SHADER_CURRENT_CHANNEL = 0
Current Channel.
- Type:
int
- SYSTEM_SHADER_CURRENT_LAYER = 2
Current Layer.
- Type:
int
- SYSTEM_SHADER_CURRENT_LAYER_AND_BELOW = 1
Current Layer & Below.
- Type:
int
- SYSTEM_SHADER_CURRENT_PAINT_TARGET = 3
Current Paint Target.
- Type:
int
- class SystemShaderType
Bases:
objectTye type of system shaders such as “Current Channel” and “Current Layer” shaders.
- SYSTEM_SHADER_CURRENT_CHANNEL = 0
Current Channel.
- Type:
int
- SYSTEM_SHADER_CURRENT_LAYER = 2
Current Layer.
- Type:
int
- SYSTEM_SHADER_CURRENT_LAYER_AND_BELOW = 1
Current Layer & Below.
- Type:
int
- SYSTEM_SHADER_CURRENT_PAINT_TARGET = 3
Current Paint Target.
- Type:
int
- addLocator()
Add a locator to this object.
- Returns:
LocatorEntity– The newly-created locator.
- addVersion(Paths, Name, Options='variant')
Adds a new version of the object from one or more files.
It is often useful to have multiple versions of a geometry available to test.
When adding versions, it is assumed that only the world space positions and normals of the objects have changed.
When dealing with geometry with updated UVs, no conversion occurs, and rendering artifacts may be seen.
As in
GeoManager::load(), the settings for the geometry load can be controlled by the function parameter Options, and the format of the parameter is the same.- Parameters:
Paths (variant) – The path(s) to the file(s) containing the new version geometry. This must be either a single pathname, or a list of pathnames.
Name (str) – The name for the new version. This must be unique for this item.
Options (variant, optional) – An optional dictionary (or list, for backwards compatibility) of settings to control the geometry load, as in
GeoManager::load(). Defaults to variant.
- Raises:
ValueError – Raised if no paths were provided, any of the file paths were empty, the version name already exists, or the options string list was invalid.
IOError – Raised if any of the files to load the version from was not found.
TypeError – Raised if the paths parameter is not a string or list of strings.
RuntimeError – Raised if the mesh types are invalid for adding version.
Note
The Options initially default to the settings from the current version of the Object. Any options provided are treated as overrides to the defaults.
See also
versionList(), versionNames(), removeVersion(), renameVersion()
- boundingBoxLowerBounds()
Returns the lower bounds of the object bounding box.
- Returns:
VectorN– Vector of the lower bounds.
- boundingBoxUpperBounds()
Returns the upper bounds of the object bounding box.
- Returns:
VectorN– Vector of the upper bounds.
- boundingSphereCenter()
Return the centrum of the bounding sphere of the object.
- Returns:
VectorN– The position of the sphere center.
- boundingSphereRadius()
Return the radius of the bounding sphere of the object.
- Returns:
float– The sphere radius.
- channel(ChannelName)
Returns the channel with the given name.
- Parameters:
ChannelName (str) – The name of the channel to retrieve
- Raises:
ValueError – Raised if the given channel name was not found on the object.
- Returns:
Channel– The requested channel.
- channelAdded(NewChannel)
This is emitted when a new channel is added, by creation and loading.
- Parameters:
NewChannel (Channel) – The newly-added channel
- channelCreated(NewChannel)
This is emitted when a new channel is created on the entity.
- Parameters:
NewChannel (Channel) – The newly-created channel
- channelList()
Returns a list of channels present on the object.
- Returns:
list of
Channel– A list of the channels associated with this object
- channelMadeCurrent(NewCurrentChannel)
This is emitted when a different channel is made current.
- Parameters:
NewCurrentChannel (Channel) – The channel that is now current.
- channelRemoved(OldChannel)
This is emitted when a channel is removed.
- Parameters:
OldChannel (Channel) – The removed channel
- completePatchList()
Returns a list of all the different UV patches that make up this object.
This function behaves the same as
patchList()except that invalid patches are appeneded to the end of the returned list.- Returns:
list of
GeoPatch– A list of the UV patch objects associated with this geometry
See also
patchList()
- createChannel(Name, Width, Height, Depth, IsShaderStack=False)
Creates a new channel from the settings provided.
This function can be used to create either UV or
Ptexchannels, depending on whether or not the entity is usingPtex. ForPtexchannels, the Width and Height parameters are ignored, so using the functioncreatePtexChannel()is more convenient.- Parameters:
Name (str) – The name to call the new channel
Width (int) – The default width of the channel (ignored for
Ptex)Height (int) – The default height of the channel (ignored for
Ptex)Depth (int) – The default bit depth of the channel
IsShaderStack (bool, optional) – If true create the channel as a ShaderStack. If none is passed a nonShaderStack is created. Defaults to False.
- Raises:
ValueError – Raised if the channel name is already in use, depth is not supported or width and height are not supported
RuntimeError – Raised if the channel could not be created
- Returns:
Channel– The newly-created channel
See also
createPtexChannel(), createDuplicateChannel()
- createDuplicateChannel(ChannelToDuplicate, NewChannelName='str')
Creates a new channel as a duplicate of the passed channel.
- Parameters:
- Raises:
RuntimeError – Raised if the channel could not be created, or if ChannelToDuplicate is not part of this GeoEntity.
- Returns:
Channel– The newly created channel.
See also
createChannel(), createPtexChannel()
- createDuplicateShader(ShaderToDuplicate, NewShaderName='str')
Creates a new shader as a duplicate of the passed shader.
- Parameters:
- Raises:
RuntimeError – Raised if the shader could not be created, or if ShaderToDuplicate is not part of this GeoEntity.
- Returns:
Shader– The newly created shader.
- createGeoChannel()
Add a new geo channel.
- Returns:
GeoChannel– The new geo channel added
- createLayeredShader(Name, LayeredType)
Creates a new layered shader.
- Parameters:
Name (str) – The name of the shader to create.
LayeredType (str) – The layered type of the shader to create.
- Raises:
RuntimeError – Raised if the shader could not be created.
- Returns:
Shader– The new shader.
- createPtexChannel(Name, Depth)
Creates a new Ptex channel from the settings provided.
For entities using
Ptex, this is the same as callingcreateChannel(), but does not require the width and height parameters, which are not applicable.For entities not using
Ptex, this function will raise an exception.- Parameters:
Name (str) – The name to call the new channel
Depth (int) – The default bit depth of the channel
- Raises:
ValueError – Raised if the channel name is already in use, depth is not supported or width and height are not supported
RuntimeError – Raised if the channel could not be created, or if the entity is not using Ptex
- Returns:
Channel– The newly-created channel
See also
createChannel(), createDuplicateChannel()
- createStandaloneShader(Name, StandaloneType)
Creates a new standalone shader.
- Parameters:
Name (str) – The name of the shader to create.
StandaloneType (str) – The standalone type of the shader to create.
- Raises:
RuntimeError – Raised if the shader could not be created.
- Returns:
Shader– The new shader.
- currentChannel()
Returns the channel currently selected on the entity.
- Returns:
Channel– The currently selected channel, or NULL if none.
- currentImageSet()
Returns the image set currently selected for painting into on the entity.
- Returns:
ImageSet– The currently-selected image set, or NULL if none.
- currentShader()
Returns the currently active shader.
- Returns:
Shader– The active shader for this object
See also
setCurrentShader()
- currentVersion()
Returns the currently active version of the object.
- Returns:
GeoEntityVersion– The currently active version.
See also
currentVersionName()
- currentVersionName()
Returns the name of the currently active version of the object.
- Returns:
str– The name of the currently active version
See also
currentVersion()
- exportAsArchive(DirPath)
Export this GeoEntity as a light weight geometry archive.
- Parameters:
DirPath (str) – The directory path to save the
GeoEntityarchive to.
- findChannel(ChannelName)
Returns the channel with the given name.
- Parameters:
ChannelName (str)
- Returns:
Channel– The requested channel. Return NULL is not found.
- findGeoChannel(Alias)
Returns the GeoChannel with the matching alias or None.
- Parameters:
Alias (str) – Alias to find.
- Returns:
GeoChannel– A Geo channel
- findImageSet(rName)
Returns the image set with the given name if found, or NULL.
The string matching is case insensitive.
- Parameters:
rName (str)
- Returns:
ImageSet– The given image set if found, or NULL otherwise
- findShader(Name)
Finds and returns any shader with the given name.
- Parameters:
Name (str) – The name of the shader to look for.
- Returns:
Shader– The matching shader if found, or NULL otherwise.
See also
shader()
- generateSubdivision(Options)
Generates subdivision surfaces.
- This calls OpenSubdiv library to generate subdivision surfaces. Options can be specified to set the following:
Level (int) : Subdivision Level
Force (bool) : True to force subdivision of geometry pieces marked as “Don’t subdivide”
Use Source (bool) : True, to automatically use subdivision settings (scheme and rules) from the source geometry file, or False, to use user-supplied settings.
Scheme (
Mari::GeoManager::OpenSubdivisionSchemeType) : Subdivision schemeBoundary Interpolation (
Mari::GeoManager::OpenSubdivisionBoundaryInterpolation) : Boundary interpolation ruleFace Varying Interpolation (
Mari::GeoManager::OpenSubdivisionFaceVaryingInterpolation) : Face-varying data interpolation ruleCreasing (
Mari::GeoManager::OpenSubdivisionCreasingMethod) : Creasing methodTriangle Subdivision (
Mari::GeoManager::OpenSubdivisionTriangleSubdivision) : Triangle subdivision ruleLimitEnabled (bool) : Toggle to snap subvided to limit surface (Default value is False)
Examples:
>>> import mari >>> # Subdivide using default settings from source file >>> options = {} >>> mari.geo.current().generateSubdivision(options) >>> >>> # Subdivide using overriden settings, Catmull clark subdivision at level 2 >>> options = {} >>> options["Level"] = 2 >>> options["Scheme"] = mari.geo.OpenSubdivisionSchemeType.SCHEME_CATMARK >>> mari.geo.current().generateSubdivision(options) >>> >>> # Subdivide using overriden settings, Loop clark subdivision at level 3, boundary interpolation set to edge only, uv face varying interpolation set to boundaries >>> options = {} >>> options["Level"] = 3 >>> options["Scheme"] = mari.geo.OpenSubdivisionSchemeType.SCHEME_LOOP >>> options["Boundary Interpolation"] = mari.geo.OpenSubdivisionBoundaryInterpolation.VTX_BOUNDARY_EDGE_ONLY >>> options["Face Varying Interpolation"] = mari.geo.OpenSubdivisionFaceVaryingInterpolation.FVAR_LINEAR_BOUNDARIES >>> mari.geo.current().generateSubdivision(options) >>> >>> # Subdivide using overriden settings, Catmull clark subdivision at level 1, creasing set to chaikin and triangle subdivision set to smooth and snap vertices to limit surface >>> options = {} >>> options["Level"] = 1 >>> options["Scheme"] = mari.geo.OpenSubdivisionSchemeType.SCHEME_CATMARK >>> options["Creasing"] = mari.geo.OpenSubdivisionCreasingMethod.CREASE_CHAIKIN >>> options["Triangle Subdivision"] = mari.geo.OpenSubdivisionTriangleSubdivision.TRI_SUB_SMOOTH >>> options["LimitEnabled"] = True >>> mari.geo.current().generateSubdivision(options)
- Parameters:
Options (dict<str,variant>) – Options for generating subdivision surfaces up to.
- Raises:
ValueError – Raised if the operation fails, with warnings.
- Returns:
bool– Returns whether subdivision succeeded.
- geoChannelAdded(NewGeoChannel)
This is emitted when a geo channel is added.
- Parameters:
NewGeoChannel (GeoChannel) – The newly added geo channel.
- geoChannelRemoved(RemovedGeoChannel)
This is emitted when a geo channel is removed.
- Parameters:
RemovedGeoChannel (GeoChannel) – The removed geo channel.
- geoChannels()
Returns the geo channels of this object.
- Returns:
list of
GeoChannel– Geo channel objects
- geometryVersionAdded(Name)
This is emitted when a new geometry version is added.
- Parameters:
Name (str) – The name of the new version
- geometryVersionMadeCurrent(Name)
This is emitted when a new geometry version becomes current.
- Parameters:
Name (str) – The name of the newly current version
- geometryVersionRemoved(Name)
This is emitted when a geometry version is removed.
- Parameters:
Name (str) – The name of the version removed
- hideLocator()
Hide the locator UI object.
- imageSet(rImageSetName)
Returns the image set with the given name.
The string matching is case insensitive.
- Parameters:
rImageSetName (str)
- Raises:
ValueError – Raised if the given image set name was not found on the object.
- Returns:
ImageSet– The requested image set.
- imageSetAdded(NewImageSet)
This is emitted when a image set is added to the object.
- Parameters:
NewImageSet (ImageSet) – The newly-created image set
- imageSetList()
Returns a list of the image sets that are present on the entity.
- Returns:
list of
ImageSet– A list of the image sets associated with this object
- imageSetMadeCurrent(CurrentImageSet)
This is emitted when an image set becomes current.
- Parameters:
CurrentImageSet (ImageSet) – The new current image set
- imageSetNames()
Returns a string list of the names of all of the image sets that are present on the object.
- Returns:
list of str– A list of the names of the image sets associated with this object
- imageSetRemoved(OldImageSet)
This is emitted when a image set is removed from the object.
- Parameters:
OldImageSet (ImageSet) – The removed image set
- importFromArchive(DirPath)
Import this GeoEntity from a light weight geometry archive.
- Parameters:
DirPath (str) – The directory path to load the
GeoEntityarchive from.
- is2DPaintObject()
Returns whether this object is a 2D paint object.
- Returns:
bool– Whether this object is a 2D paint object.
- isPtex()
Returns true if the object is Ptex based.
- isSelected()
Indicates whether the object is currently selected.
- Returns:
bool– True if the object is selected, or false if not
- maximumSubdivisionLevel()
Returns the maximum subdivision level calculated already for this GeoEntity.
- missingGeoChannels()
Return a list of Geo Channel aliases that are missing within any node in the GeoEntity.
- Returns:
list of str– A list of aliases, or empty if none is found.
- name()
Returns the name of the object.
- Returns:
str– The name of this object
- nameChanged(NewName)
This is emitted after the entity has been renamed.
- Parameters:
NewName (str) – The new name of the entity
- nodeGraph()
Returns the root shader node graph this GeoEntity holds.
- Returns:
NodeGraph– The shader node graph
- patch(UvIndex)
Returns the patch that corresponds to the given UV index.
- Parameters:
UvIndex (int) – The index of the patch to return
- Raises:
ValueError – If index is out of range
- Returns:
GeoPatch– The requested patch
- patchImage(Patch, pImageSet)
Convenience method to lookup the image for the specified patch. on the specified channel.
- Parameters:
- Raises:
ValueError – Raised if Patch isn’t a valid GeoPatch object, or if Chan isn’t a valid ImageSet object.
- Returns:
Image– Image object associated with the patch.
- patchList()
Returns a list of the different valid UV patches that make up this object.
Geometry may be broken into multiple UV patches. Each UV patch occupies a single integer square in UV space. Each patch may have a name, associated metadata, and locked or hidden or valid status.
As of version 1.4v3, these patches are returned in UV index order - the same order as
ImageSet::imageList(). Note however that these indices do not necessarily map directly to UDIMs, as some UDIMs may be unused, and there will not be any corresponding spaces left empty in the array. To be sure of the UDIM of a patch, call theGeoPatch::udim()method.- Returns:
list of
GeoPatch– A list of the UV patch objects associated with this geometry
Note
In versions older than 1.4v3, this function does not necessarily return the images in any particular order, or in the same order as ImageSet::imageList().
Note
Only valid patches are returned. To retreive all patches use completePatchList().
Note
This method returns the combined list of all patches from the GeoEntityVersion objects belonging to this GeoEntity. See GeoEntityVersion.patchList()
See also
completePatchList()
- remapSubdivisionSettings(Options)
Remap source subdivision settings.
We currently load subdivision meshes from Alembic and then uses OpenSubdiv to subdivide them in
Mari. Some of the options from Alembic or your DCC might not be what you would want to pass on to OpenSubdiv, since they will be exported using the DCC’s in built exporter. To fix that, you can use this function, that will remap your source DCC subdivision settings, beforeMarisubdivides using OpenSubdiv.Currently, we only support remapping “Boundary Interpolation” and “Face Varying Interpolation”. The function accepts, as input, a map of QStrings and a list of tuples, of the format:
{ParameterName1 : [(source value, destination value), (source value, destination value), ], ParameterName2 : [(source value, destination value), ]}
The parameter names are either “Boundary Interpolation” or “Face Varying Interpolation”. The source and destination values are enums or ints, that you want to remap.
Examples:
>>> import mari >>> # Remap corners only to corners plus 1, for the face varying interpolation, on the current geoentity >>> options = {} >>> options["Face Varying Interpolation"] = [(mari.geo.OpenSubdivisionFaceVaryingInterpolation.FVAR_LINEAR_CORNERS_ONLY, mari.geo.OpenSubdivisionFaceVaryingInterpolation.FVAR_LINEAR_CORNERS_PLUS1), ] >>> mari.geo.current().remapSubdivisionSettings(options) >>> >>> # Remap corners only to corners plus 1 and linear boundaries to all, for the face varying interpolation, on the current geoentity >>> options = {} >>> options["Face Varying Interpolation"] = [(mari.geo.OpenSubdivisionFaceVaryingInterpolation.FVAR_LINEAR_CORNERS_ONLY, mari.geo.OpenSubdivisionFaceVaryingInterpolation.FVAR_LINEAR_CORNERS_PLUS1), (mari.geo.OpenSubdivisionFaceVaryingInterpolation.FVAR_LINEAR_BOUNDARIES, mari.geo.OpenSubdivisionFaceVaryingInterpolation.FVAR_LINEAR_ALL), ] >>> mari.geo.current().remapSubdivisionSettings(options)
- Parameters:
Options (dict<str,variant>) – Options for remapping settings.
- removeChannel(ChannelToRemove, Strategy='DESTROY_NONE')
Removes the given channel.
This is added as an undo record, and so can be undone if required.
- Parameters:
ChannelToRemove (Channel) – The channel to remove. This must be a channel owned by the
GeoEntity.Strategy (ChannelDestroyStrategy, optional) – The logic used to remove shared items with the channel. Defaults to DESTROY_NONE.
- Raises:
ValueError – Raised if the channel provided is invalid, locked or does not belong to the object.
- removeGeoChannel(GeoChannelObject)
Removes a geo channel from this geo entity.
- Parameters:
GeoChannelObject (GeoChannel) – The geo channel object to remove
- Raises:
ValueError – If the geo data object is invalid
- removeShader(ShaderToRemove, RetractionMode='Shader.REMOVE_DISCONNECT')
Removes the given shader.
This is added as an undo record, and so can be undone if required.
- Parameters:
ShaderToRemove (Shader) – The shader to remove. This must be a shader owned by the
GeoEntity.RetractionMode (Shader.ChannelSetMode, optional) – The Retraction mode to use if removing the
Shaderresults in retracting MultiChannelLayers from Channels. Defaults to Shader.REMOVE_DISCONNECT.
- Raises:
ValueError – Raised if the shader provided is invalid, locked or does not belong to the object.
- removeVersion(VersionName)
Removes the named version of this object.
An object must have at least one version. Attempting to remove the last version of an object will fail.
- Parameters:
VersionName (str) – The name of the version to remove
- Raises:
ValueError – Raised if the given version name was not found.
RuntimeError – Raised if the given version could not be removed because it was the last one on the object.
See also
addVersion(), renameVersion()
- renameVersion(OldName, NewName)
Renames a geometry version.
The new name must be unique for this object.
- Parameters:
OldName (str) – The name of the version you wish to change
NewName (str) – The new name for the version. This must be unique for the object.
- Raises:
ValueError – Raised if the provided old name did not match any available version to change, or the new name was a duplicate of an existing version name.
See also
versionList(), versionNames(), addVersion(), removeVersion()
- resetHandleTransform(Frame=0)
Resets the internal cache of transform information set by the 3D handle in the viewport.
- Parameters:
Frame (int, optional) – Frame. Defaults to 0.
- save(FileName, Format='')
Saves the geometry into a file. The current version at the current subdivision level is saved.
- Parameters:
FileName (str) – The file name to save as
Format (str, optional) – The geometry format. If not provided, the format is guessed from the extension. Defaults to “”.
- Raises:
RuntimeError – Raised if the geometry cannot be saved .
- selectedPatches()
Returns a list of the different selected UV patches that make up this object.
- Returns:
list of
GeoPatch– A list of the currently selected UV patch objects associated with this geometry
- setCurrentChannel(NewCurrentChannel)
Makes the given channel current on this object.
- Parameters:
NewCurrentChannel (Channel) – The channel to make current
- Raises:
ValueError – Raised if the channel provided is invalid, locked or does not belong to the object.
See also
currentChannel()
- setCurrentImageSet(NewCurrentImageSet)
Sets the image set to be ‘current’, or active for painting into.
- Parameters:
NewCurrentImageSet (variant) – The image set to make current. This must be either an
ImageSetobject owned by theGeoEntity, or the name of one.- Raises:
ValueError – Raised if the image set is invalid, or not owned by the object.
TypeError – Raised if the image set parameter is not a string or ImageSet object.
- setCurrentShader(NewCurrentShader)
Makes the given shader current on this object.
- Parameters:
NewCurrentShader (Shader) – The shader to make current.
- Raises:
ValueError – Raised if the shader provided is invalid, locked or does not belong to the object.
See also
currentShader()
- setCurrentVersion(VersionName)
Sets the current active version of the object.
- Parameters:
VersionName (str) – The name of the version to set as current.
See also
versionList(), versionNames()
- setName(NewName)
Changes the name of the object.
- Parameters:
NewName (str) – The new name of the object
- setSelected(Selected)
Changes the selection state of the object.
- Parameters:
Selected (bool) – True to select the object, or false to deselect it
Note
Exactly one object can be selected at a time. If only one object is available, it cannot be deselected.
- setSubdivisionLevel(Level)
Sets the subdivision level to render this GeoEntity at.
- Parameters:
Level (int) – Sudivision level to render this
GeoEntityat.- Raises:
ValueError – Throws a value error if the given Level is below 0 or exceeds the maximum subdivision level calculated for the current version.
- setTransform(pTransform, Frame=0)
Sets the transform of the geo entity for a frame.
- Parameters:
pTransform (Matrix) – Translation vector
Frame (int, optional) – Frame. Defaults to 0.
- Raises:
ValueError – Throws a value error if the input if not a valid matrix
- shader(Name)
Returns the shader with the given name.
- Parameters:
Name (str) – The name of the shader to look for.
- Raises:
ValueError – Raised if the given shader name was not found on the object.
- Returns:
Shader– The matching shader.
See also
findShader()
- shaderCreated(NewShader)
This is emitted when a new shader is created.
- Parameters:
NewShader (Shader) – The newly-created shader.
- shaderList()
Returns a list of shaders present on the object.
- Returns:
list of
Shader– A list of the shaders associated with this object
- shaderMadeCurrent(CurrentShader)
This is emitted when a different shader is made current.
- Parameters:
CurrentShader (Shader) – The shader that became current.
- shaderRemoved(OldShader)
This is emitted when a shader is removed.
- Parameters:
OldShader (Shader) – The removed shader.
- showLocator()
Show the locator UI object.
- subdivisionBoundaryInterpolateMethod()
Returns the collated subdivision boundary interpolation rule for this GeoEntity.
- subdivisionCreasing()
Returns the collated subdivision creasing for this GeoEntity.
- subdivisionFaceVaryingBoundaryInterpolateMethod()
Returns the collated subdivision face varying interpolation rule for this GeoEntity.
- subdivisionScheme()
Returns the collated subdivision scheme for this GeoEntity.
- subdivisionSkippedMeshList()
Returns the list of skipped meshes during subdivision.
- subdivisionTriangleSubdivisionRule()
Returns the collated subdivision triangle rule for this GeoEntity.
- systemShader(Type)
Returns the system shader of the specified type.
- Parameters:
Type (SystemShaderType) – The type of the desired system shader
- Raises:
RuntimeError – Raised if the system shader could not be found.
ValueError – Raised if invalid type is specified by Type.
- Returns:
Shader– The system shader of the specified type
- static transferChannels(UVRemap, SourceChannels, SourceGeoVersion, DestinationGeoVersion, SourceUVIndices, DestinationUVIndices, DestinationSize='ImageSet.SIZE_None', BleedEdges=True, FillColor='nullptr')
Copies channels from one object to another.
The channels in the source list must belong to the same object. .. code-block:
>>> src_geo_entity = mari.geo.get('Head1') >>> src_geo_version = src_geo_entity.version("v4") >>> src_channel = src_geo_entity.channel('diffuse') >>> dst_geo_entity = mari.geo.get('Head2') >>> dst_geo_version = dst_geo_entity.version("v1") >>> mari.GeoEntity.transferChannels("UVRemap_Head1v4_to_Head2v1_$UDIM.exr", [src_channel], src_geo_version, ... dst_geo_version)
- Parameters:
UVRemap (variant) – Either an existing image set or a filename template to a set of uv remapping textures.
SourceChannels (list of
Channel) – A list of source channels to read from.SourceGeoVersion (GeoEntityVersion) – The source geometry version to read from.
DestinationGeoVersion (GeoEntityVersion) – The destination geometry version to write into.
DestinationSize (ImageSet.Size, optional) – Used to specified the image size for all uv indices in the destination channel. If a size is not given then the size will match the source. Defaults to ImageSet.SIZE_None.
BleedEdges (bool, optional) – Turns on or off “full texture bleed” (full patch texture bleed is generated). Defaults to True.
FillColor (Color, optional) – The color used to fill the newly created destination image sets with. Defaults to nullptr.
SourceUVIndices (list of
int) – Which patches in the source to read from. Passing in an empty list will cause all source patches to be read from.DestinationUVIndices (list of
int) – Which patches in the destination to write to. Passing in an empty list will cause all destination patches to be written to.
- Raises:
ValueError – Raised if no channels were supplied; if any of the channels are invalid; if the channels belong to different objects; if any of the patch indices was invalid; if no source or destination geo version was supplied.
- Returns:
list of
Channel– A list of destination nodes if the transfer completed successfully, or an empty list otherwise.
- transform(Frame)
Returns the transform matrix at a given frame.
- Parameters:
Frame (int) – Frame
- Returns:
Matrix– Matrix of the transform.
- translation(Frame=0)
Returns the translation vector at a given frame.
- Parameters:
Frame (int, optional) – Frame. Defaults to 0.
- Returns:
VectorN– Vector of the translation.
- version(VersionName)
Returns a geometry version object.
- Parameters:
VersionName (str) – The name of the version to return. This should be one of the names returned by
versionNames().- Raises:
ValueError – Raised if the version name was not found.
- Returns:
GeoEntityVersion– The requested version object.
See also
versionNames()
- versionList()
Returns a list of the available versions of this geometry.
- Returns:
list of
GeoEntityVersion– A list of the available geometry versions
See also
addVersion(), removeVersion(), versionNames()
- versionNames()
Returns a list of names of the available versions of this geometry.
- Returns:
list of str– A list of the names of the geometry versions
See also
versionList()
- class mari.GeoEntityVersion
Bases:
MetadataProvides access to an individual version of a geometry entity.
Mariallows objects to have multiple versions. These versions should be uniquely named.You can access a geometry entity version through a
GeoEntity- for example:mari.geo.current().versionList()Example Code
# This examples obtains the current version of current geometry object import mari currentObjectVersion = mari.geo.current().currentVersion()
- aboutToLoad()
This is emitted just before the data for the version is loaded.
- created()
Returns the date and time that the source file for the version was created.
- Returns:
QDateTime– The date and time that the source file for this version was created
- createdChanged(NewCreated)
This is emitted when the created date details change for the version.
- Parameters:
NewCreated (QDateTime) – The new date for the created field
- creator()
Returns information about the creator of the version.
This can be the creator’s name, or any other desired information.
- Returns:
str– Information about the creator of the version
- creatorChanged(NewCreator)
This is emitted when the creator details change for the version.
- Parameters:
NewCreator (str) – The new creator details
- geoEntity()
Returns the parent geoentity of this version.
- Raises:
RuntimeError – Raised if no project was open.
- Returns:
GeoEntity– Geoentity parent object.
- geometryCount()
Returns the count of geometries that are contained within a version.
When geometries are merged together, they could either exist as a single geometry (if the merge type is set to be SINGLE_MESH) or still as several ones (in the case of JUST_MERGE_NODES). In any case, this is managed internally by
Mariand the user doens’t have access to that information; this funciton returns the count of geometries that were merged together.- Returns:
int– Count of geometries contained in a version
- load()
Loads the version from file.
The file path should be set using
setPath()before calling this method. Any settings required for loading should also be provided beforehand usingsetSettingsString().If the version is already loaded, this will clear it and reload from the file.
- Returns:
bool– True if the version was loaded correctly, or false otherwise.
- loaded()
This is emitted after the data for the version has been loaded.
- meshLocationToFaceCountMap()
Returns the map of source mesh location path and the face count for the mesh.
- Returns:
dict– the map of source mesh location path and the face count for the mesh
- meshPaths()
Returns the paths used to create the version, when there are multiple mesh source files.
- Returns:
list of str– The file paths that the version was loaded from
- modified()
Returns the last modified date and time of the source file for the version.
- Returns:
QDateTime– The date and time that the source file for this version was last modified
- modifiedChanged(NewModified)
This is emitted when the modified date changes for the version.
- Parameters:
NewModified (QDateTime)
- name()
Returns the name of the version.
- Returns:
str– The name of the version
- nameChanged(NewName)
This is emitted when the name of the version is changed.
- Parameters:
NewName (str) – The new name of the version
- patchList()
Returns a list of the different valid UV patches that make up this GeoEntityVesion.
Geometry may be broken into GeoVersions with multiple UV patches. Each UV patch occupies a single integer square in UV space. Each patch may have a name, associated metadata, and locked or hidden or valid status.
Note however that these indices do not necessarily map directly to UDIMs, as some UDIMs may be unused, and there will not be any corresponding spaces left empty in the array. To be sure of the UDIM of a patch, call the
GeoPatch::udim()method.- Returns:
list of
GeoPatch– A list of the UV patch objects associated with this geometry version
Note
This method returns the list of patches from this GeoEntityVersion. See GeoEntity.patchList()
- path()
Returns the path used to create the version.
- Returns:
str– The file path that the version was loaded from
- pathChanged(NewPath)
This is emitted when the path changes for the version.
- Parameters:
NewPath (str) – The new path for the version
- setCreated(CreatedDate)
Sets the file creation date and time for this version.
- Parameters:
CreatedDate (QDateTime) – The date and time that the source file for the version was created
- setCreator(Creator)
Sets the name of the creator of the version.
This can be the creator’s name, or any other desired information.
- Parameters:
Creator (str) – Information about the creator of the version
- setMeshPaths(Paths)
Sets the file paths for this version, when there are multiple mesh source files.
- Parameters:
Paths (list of str) – The paths that this version should be loaded from
- setModified(ModifiedDate)
Sets the last modified date and time for the source file for the version.
- Parameters:
ModifiedDate (QDateTime) – The date and time that the source file for this version was last modified
- setName(NewName)
Sets the name for the version.
- Parameters:
NewName (str) – The new name for the version
- Raises:
ValueError – Raised if the version name is not unique (i.e. if the parent GeoEntity already has a version with the specified name)
- setPath(Path)
Sets the file path for this version.
- Parameters:
Path (str) – The path that this version should be loaded from
- setSettings(NewSettings)
Sets the settings used to load the version.
These are passed into the geometry loader.
- Parameters:
NewSettings (variant) – A dictionary that maps string setting names to string setting values
- setSettingsString(SettingsString)
Sets the settings used to load the version.
These are passed into the geometry loader.
The string should be a list of name-value pairs collapsed into a single string. The pairs should be of the form “name=value”, with each pair separated by “|” - for example: “setting1=5|setting2=8”
This format can be produced from a Python dictionary using code such as the following:
"|".join([str(key) + "=" + str(value) for (key, value) in settings_dict.iteritems()])- Parameters:
SettingsString (str) – A list of name-value pairs collapsed into a single string.
See also
settings()
- settings()
Returns the settings used to create the version.
These settings can control things like SUB-D level, proxy creation, etc. The values accepted by geometry loaders are different for each loader.
- Returns:
variant– A map of name-value pairs that are passed into the geometry loader when loading the version.
- settingsString()
Returns the settings used to create the version as a string.
- Returns:
str– The settings for this version as a string. This is a list of name-value pairs collapsed into a single string, as described in setSettingsString().
See also
settings()
- sourceMeshLocationList()
Returns the list of mesh locations in this GeoEntityVersion.
The mesh locations are the mesh location paths within the source file, where the source file represents a scene rather than a single mesh.
- Returns:
list of str– The list of mehs locations in this GeoEntityVersion
- class mari.GeoManager
Bases:
objectManages geometry objects in the project.
Marican handle many 3D objects at once. Each 3D object or entity can have multiple geometric representations.This interface allows the user to query the internal object lists, add objects, remove objects, and generally build up a scene.
Example Code
# This examples obtains the current geometry object >>> import mari >>> current_object = mari.geo.current()
Alias
geo
- CAMERA = 5
.
- Type:
int
- CREASE_CHAIKIN = 1
Chaikin rule.
- Type:
int
- CREASE_UNIFORM = 0
Catmark rule.
- Type:
int
- class CreateSelectionSetOptions
Bases:
objectOptions to create selection sets.
- SELECTION_GROUPS_CREATE_FROM_FACE_GROUPS = 1
Create selection sets from face groups.
- Type:
int
- SELECTION_GROUPS_DONT_CREATE = 0
Don’t create selection groups.
- Type:
int
- FACESET = 3
.
- Type:
int
- FVAR_LINEAR_ALL = 0
bilinear interpolation (“bilinear”)
- Type:
int
- FVAR_LINEAR_BOUNDARIES = 3
sharpen all boundaries (“always sharp”)
- Type:
int
- FVAR_LINEAR_CORNERS_ONLY = 5
sharpen corners only
- Type:
int
- FVAR_LINEAR_CORNERS_PLUS1 = 1
(“edge corner”)
- Type:
int
- FVAR_LINEAR_CORNERS_PLUS2 = 4
(“edge and corner + propagate corner”)
- Type:
int
- FVAR_LINEAR_NONE = 2
smooth everywhere (“edge only”)
- Type:
int
- GEOMETRY_IMPORT_DONT_MERGE_CHILDREN = 2
Do not merge children of the object.
- Type:
int
- GEOMETRY_IMPORT_DONT_SELECT_CHILDREN = 1
Do not select children of the object.
- Type:
int
- GROUP = 1
.
- Type:
int
- class GeometryImportFlags
Bases:
objectThese are various options of how an imported hierarchy of objects is to be selected and merged.
- GEOMETRY_IMPORT_DONT_MERGE_CHILDREN = 2
Do not merge children of the object.
- Type:
int
- GEOMETRY_IMPORT_DONT_SELECT_CHILDREN = 1
Do not select children of the object.
- Type:
int
- MERGESELECTIONGROUP_DO_NOT_MERGE = 0
Do not merge selection groups that have the same name (default)
- Type:
int
- MERGESELECTIONGROUP_MERGE_SELECTIONGROUP_HAVING_SAME_NAME = 1
Merge selection groups that have the same name.
- Type:
int
- MERGETYPE_JUST_MERGE_NODES = 1
Semi merge type, where we preserve all the individual geometries within the geo entity.
- Type:
int
- MERGETYPE_SINGLE_MESH = 2
Full merge type, where everything is collapsed into one single geometry within the geo entity.
- Type:
int
- class MergeSelectionGroupWithSameNameType
Bases:
objectGeometry selection group with same name merge type.
- MERGESELECTIONGROUP_DO_NOT_MERGE = 0
Do not merge selection groups that have the same name (default)
- Type:
int
- MERGESELECTIONGROUP_MERGE_SELECTIONGROUP_HAVING_SAME_NAME = 1
Merge selection groups that have the same name.
- Type:
int
- class MergeType
Bases:
objectGeometry merge type image data formats.
- MERGETYPE_JUST_MERGE_NODES = 1
Semi merge type, where we preserve all the individual geometries within the geo entity.
- Type:
int
- MERGETYPE_SINGLE_MESH = 2
Full merge type, where everything is collapsed into one single geometry within the geo entity.
- Type:
int
- class NodeType
Bases:
objectThese are various types of objects that we can load from a geometry file.
- CAMERA = 5
.
- Type:
int
- FACESET = 3
.
- Type:
int
- GROUP = 1
.
- Type:
int
- POLYMESH = 2
.
- Type:
int
- ROOT = 0
.
- Type:
int
- SUBDIV = 4
.
- Type:
int
- class OpenSubdivisionBoundaryInterpolation
Bases:
objectEnumerated type for vertex boundary interpolation rules.
- VTX_BOUNDARY_EDGE_AND_CORNER = 1
sharpen edges and corners
- Type:
int
- VTX_BOUNDARY_EDGE_ONLY = 2
sharpen edges
- Type:
int
- VTX_BOUNDARY_NONE = 0
do not interpolate boundaries
- Type:
int
- class OpenSubdivisionCreasingMethod
Bases:
objectEnumerated type for edge crease methods.
- CREASE_CHAIKIN = 1
Chaikin rule.
- Type:
int
- CREASE_UNIFORM = 0
Catmark rule.
- Type:
int
- class OpenSubdivisionFaceVaryingInterpolation
Bases:
objectEnumerated type for face-varying interpolation rules.
- FVAR_LINEAR_ALL = 0
bilinear interpolation (“bilinear”)
- Type:
int
- FVAR_LINEAR_BOUNDARIES = 3
sharpen all boundaries (“always sharp”)
- Type:
int
- FVAR_LINEAR_CORNERS_ONLY = 5
sharpen corners only
- Type:
int
- FVAR_LINEAR_CORNERS_PLUS1 = 1
(“edge corner”)
- Type:
int
- FVAR_LINEAR_CORNERS_PLUS2 = 4
(“edge and corner + propagate corner”)
- Type:
int
- FVAR_LINEAR_NONE = 2
smooth everywhere (“edge only”)
- Type:
int
- class OpenSubdivisionSchemeType
Bases:
objectEnumerated type for all subdivisions schemes supported by OpenSubdiv.
- SCHEME_BILINEAR = 2
Bilinear.
- Type:
int
- SCHEME_CATMARK = 0
Catmark clark.
- Type:
int
- SCHEME_LOOP = 1
Loop.
- Type:
int
- class OpenSubdivisionTriangleSubdivision
Bases:
objectEnumerated type for the triangle subdivsion weights rule.
- TRI_SUB_CATMARK = 0
Catmark weights (Catmark scheme only)
- Type:
int
- TRI_SUB_SMOOTH = 1
“smooth triangle” weights (Catmark scheme only)
- Type:
int
- POLYMESH = 2
.
- Type:
int
- ROOT = 0
.
- Type:
int
- SCHEME_BILINEAR = 2
Bilinear.
- Type:
int
- SCHEME_CATMARK = 0
Catmark clark.
- Type:
int
- SCHEME_LOOP = 1
Loop.
- Type:
int
- SELECTION_GROUPS_CREATE_FROM_FACE_GROUPS = 1
Create selection sets from face groups.
- Type:
int
- SELECTION_GROUPS_DONT_CREATE = 0
Don’t create selection groups.
- Type:
int
- SUBDIV = 4
.
- Type:
int
- TRI_SUB_CATMARK = 0
Catmark weights (Catmark scheme only)
- Type:
int
- TRI_SUB_SMOOTH = 1
“smooth triangle” weights (Catmark scheme only)
- Type:
int
- VTX_BOUNDARY_EDGE_AND_CORNER = 1
sharpen edges and corners
- Type:
int
- VTX_BOUNDARY_EDGE_ONLY = 2
sharpen edges
- Type:
int
- VTX_BOUNDARY_NONE = 0
do not interpolate boundaries
- Type:
int
- addLocator(AddAsChildToSelectedObject=False)
Add a locator to the project.
# Add root level locator >>> import mari >>> mari.geo.addLocator() # Add another locator, parented to the locator created previously >>> mari.geo.addLocator(True)
- Parameters:
AddAsChildToSelectedObject (bool, optional) – Flag to speficy whether the locator is to be created at the root level or parented to the currently selected object in the objects palette. Defaults to False.
- Returns:
LocatorEntity– The newly-created locator.
- current()
Returns the currently selected geoentity object.
- Returns:
GeoEntity– The currently selected geoentity object.
- currentLocator()
Returns the currently selected locator object.
- Returns:
LocatorEntity– The currently selected locator object.
- duplicateCurrentGeoEntity(DuplicateShaderNetwork=True)
Duplicates the current selected GeoEntity in the project.
- Parameters:
DuplicateShaderNetwork (bool, optional) – Toggles whether to duplicate the shader network of the selected object as well. Defaults to True.
- Raises:
RuntimeError – Raised if no project is opened.
- duplicateGeoEntity(Object, DuplicateShaderNetwork=True)
Duplicates an input GeoEntity in the project.
- Parameters:
Object (GeoEntity) – The object to duplicate.
DuplicateShaderNetwork (bool, optional) – Toggles whether to duplicate the shader network of the selected object as well. Defaults to True.
- Raises:
RuntimeError – Raised if no project is opened.
- entityAdded(pNewEntity)
This is emitted after a new geometry object has been added to the project.
This only includes manual addition (by menu or by script), however. It will not be emitted when a project is loaded.
- Parameters:
pNewEntity (GeoEntity) – The newly-added geometry object
- entityMadeCurrent(pNewCurrent)
This is emitted after a new geometry object becomes current.
- Parameters:
pNewCurrent (GeoEntity) – The new current geometry object
- entityRemoved(pOldEntity)
This is emitted after a new geometry object has been removed from the project.
This only includes manual removal (by menu or by script), however. It will not be emitted when a project is closed.
- Parameters:
pOldEntity (GeoEntity) – The geometry object that was just removed
- find(Name)
Finds a geometry object from the scene, given the name of the entity.
- Parameters:
Name (str) – The name of the entity to look for
- Returns:
GeoEntity– The requested geometry object if found, or NULL otherwise
See also
get()
- geometryOperationList()
Get a list of the geometry operations, registered by entity image manager.
- Returns:
list of
GeometryOperation– A list of geometry operations.
- get(Name)
Gets a geometry object from the scene, given the name of the entity.
- Parameters:
Name (str) – The name of the entity to look for
- Raises:
ValueError – Raised if no entity with the given name was found.
- Returns:
GeoEntity– The requested geometry object
See also
find()
- getAnimationTakes(Path)
Returns the names of animation takes from a file.
- Parameters:
Path (str) – The file path to query
- Raises:
RuntimeError – Raised if the file cannot be loaded by Mari or we cannot have any take information
- Returns:
list of str– a list of takes
- getDefaultAnimationTake(Path)
Returns the name of the default take.
- Parameters:
Path (str) – The file path to query
- Raises:
RuntimeError – Raised if the file cannot be loaded by Mari or we cannot have any take information
- Returns:
str– name of default take
- getFileContents(Path)
Returns a list of objects, name and type, that can be loaded from a file.
- Parameters:
Path (str) – The file path to query
- Raises:
RuntimeError – Raised if file cannot be loaded by Mari or we cannot get the contents of the file
- Returns:
variant– A list of objects that can be loaded, their names and types
- getFileFrameRange(Path, Take='')
Returns the start and end frames of a file.
- Parameters:
Path (str) – The file path to query
Take (str, optional) – Optional take used to query specific animation range if the file supports the concept of takes. Defaults to “”.
- Raises:
RuntimeError – Raised if the file cannot be loaded by Mari or the take is invalid or we cannot get a frame range from the file
- Returns:
list of
int– a list of two items, which are the start and end frames
- importFromArchive(DirPath)
Import the GeoEntity from the geometry archive given in DirPath.
- Parameters:
DirPath (str) – The directory path from which the
GeoEntityis loaded.
- list()
Returns a list of all objects in the project.
- Returns:
list of
GeoEntity– All objects in the project.
- listLocators()
Returns a list of all locators in the project.
- Returns:
list of
LocatorEntity– All locators in the project.
- load(Paths, Options='variant', ObjectsToLoad='variant', LoadAsChild=False)
Loads the given file as new geometry.
Requests for object loading are routed to the correct plugin based on file extension.
- The settings for the geometry load can be controlled by the function parameter Options. This parameter should be a dictionary, with strings for keys, and values. The geometry loader plug-in that interprets the mesh to be loaded will receive the options passed in here that it recognises, and the others will be ignored. A list of the commonly used settings is as follows:
“MappingScheme” - geometry mapping scheme (type MeshOptions).
“MultipleGeometries” - how to handle multiple geometries in a single object (type MultipleGeometryOptions).
“PtexFaceSizeScheme” -
Ptexspecific: scheme to use for face texture size calculations (type PtexFaceSizeScheme).“PtexFaceSize” -
Ptexspecific: size to use with the scheme above (type int).“PtexImageFormat” -
Ptexspecific: image data format (type PtexFormat).“PtexFaceColor” -
Ptexspecific: color to clear faces to (typeColor).“PtexImportFilename” -
Ptexspecific: import an existingPtexfile onto the .obj geometry (type string).“PtexShowCreationDialog” -
Ptexspecific: show thePtexcreation dialog after mesh loading (type Bool; default is False from Python).“EachMeshCreatesObject” - each mesh can either create an Object or each be a geometry within a single Object. This is currently
Ptexspecific. (type Bool; default is True).“MergeType” - merging of geometries can be either single-mesh or just-merge-nodes (type mari.GeoManager.MergeType).
“MergeSelectionGroupWithSameNameType” - merging of face selection groups that have the same name (type mari.GeoManager.MergeSelectionGroupWithSameNameType) - default is mari.geo.MergeSelectionGroupWithSameNameType.MERGESELECTIONGROUP_MERGE_SELECTIONGROUP_HAVING_SAME_NAME
“CreateSelectionSets” - specify whether to create selection sets from face groups (type CreateSelectionSetOptions) - default value is mari.GeoManager.CREATE_FROM_FACE_GROUPS
“FrameOffset” - specify the start frame in
Mari‘s timeline to import the geometry (default value is zero).“GeoChannels” - specify whether to create Geo-Channel(s) on a single
GeoEntityadded as part of theload()function. This is a dictionary of {key = names of geo-channels to create, value = image path template to import a sequence of images onto the geo-channel}. Note that the geo-channels will only be added if there is a singleGeoEntitycreated, either through all the geo meshes merged together or a single geo mesh being specified. In the case of multiple GeoEntities, please use theGeoEntity::createGeoChannelAPI once the objects have been added.
There are two special options (‘CreateChannels’ and ‘ImportChannels’, with a list of
ChannelInfoas values) that can optionally be passed in to allow the user to create/import channels when loading geometry; not passing these options results in default channels (diffuse) being created. Example usage of these would be as follows:>>> import mari >>> # Example code on loading geometry and creating a channel >>> mari.geo.load('/tmp/test.abc', {'name':'test', 'CreateChannels':[mari.ChannelInfo('exampleChan', 2048, 2048, 16),]}) >>> >>> # Example code to load a geometry and import a channel >>> importChannel = mari.ChannelInfo('test1', 2048, 2048, 16) >>> importChannel.setPath('/tmp') >>> importChannel.setFileTemplate('/$PATH/test.tif') >>> mari.geo.load('/tmp/test.abc', {'name':'test', 'ImportChannels':[importChannel,]})
When used in combination with the C API, this allows users to pass in parameters with specified names to a custom geometry loader. See the C API documentation for further details.
>>> # Assuming the geometry loader for the 'abc' format understands the parameters 'size' and 'name' >>> import mari >>> try: ... mari.geo.load('/tmp/test.abc', {'size': 5, 'name': 'test'}) ... except: ... pass
Here is an example of adding 2 geo-channels, Copper and Rust:
>>> import mari >>> options = {"GeoChannels": {"Copper" : "/tmp/Copper.$UDIM.tif", "Rust" : "/tmp/Rust.$UDIM.tif", }, } >>> mari.geo.load("/tmp/tent.abc", options)
- Parameters:
Paths (variant) – A single path or list of paths to be loaded.
Options (variant, optional) – This is an optional parameter which can be used to pass options to the file loader. Options should ideally be provided in dictionary format, as described above. Defaults to variant.
ObjectsToLoad (variant, optional) – This is a list of objects to load from the file. Each item of the list is a dictionary that contains the name of the objects to load and various geometry import flags to specify whether the children of the current object are to be selected and whether they are to be merged as well. children underneath the current node onto 1 entity. Defaults to variant.
LoadAsChild (bool, optional) – A flag to indicate whether the newly added geometry will be parented to the currently selected object in the project or not. Defaults to False.
- Raises:
RuntimeError – Raised if no project is currently open, or if there was a general error with loading such as missing importers or channel creation failure.
ValueError – Raised if the input file path is invalid.
ValueError – Raised if there was a problem interpreting the options.
- Returns:
list of
GeoEntity– A list of the entities loaded from the given file. This list may be empty if the load failed.
- names()
Returns a list of the names of the geometry objects in the current project.
- Returns:
list of str– A list of the names of the geometry objects in the current project
- recalculatePatchBounds()
Forces each geometry version to recalculate it’s world-space patch bounds.
The bounds are used in things like navigation and can cause the geometry to appear to be lost if they become invalid for any reason. As such this provides a way of resetting them to regain control.
- remove(Name)
Removes a given entity from the project.
The given entity and all child entities will be removed and placed onto the undo stack.
You cannot remove the last entity from a project.
- Parameters:
Name (str) – The name of the entity to be removed
- Raises:
RuntimeError – Raised if no project was open, or if only one object remains in the project.
ValueError – Raised if no object with the given name was found.
- setCurrent(Object)
Sets the currently selected object.
- Parameters:
Object (GeoEntity) – The object to make current
- Raises:
ValueError – Raised if an invalid object was provided.
RuntimeError – Raised if no project was open.
- supportedReadFormats()
Returns a string list of all object formats supported for reading.
The list returned will be all unique lower case strings in ascending alphabetic order.
- Returns:
list of str– A string list of all object formats supported for reading - e.g. [‘obj, ‘abc’]
- class mari.GeoPatch
Bases:
LockableA geometry patch is section of a GeoEntity that occupies a single UV square.
Geometry can be broken into multiple patches. Each patch may have multiple textures associated with it.
An
ImageSetcontains one texture for eachGeoPatchin aGeoEntity.Patches may be named, and can have associated metadata. They may also be locked or hidden.
You can access geometry patches through a
GeoEntity- for example:mari.geo.current().patchList()Example Code>>> # This examples obtains the patch with UDIM 1001 of current geometry object >>> import mari >>> patch_1001 = mari.geo.current().patch(0)
- isLocked()
Returns the locked status of the patch.
- Returns:
bool– True if the patch is locked, or false (the default) otherwise
See also
setLocked()
- isSelected()
Indicates whether the patch is currently selected.
- Returns:
bool– True if the patch is selected, or false if not
- isValid()
Indicates whether the patch is valid.
For a patch to be valid, its U and V location must be greater than zero.
Maridoes not support negative UVs which lead to invalid patches. If a patch is invalid,uvIndex()may not return a useful index andudim()will return a value less than 1001. Invalid patches may not have images associated with them.- Returns:
bool– True if the patch is valid, or false if not.
See also
uvIndex(), udim()
- isVisible()
Returns the visible status of the patch.
- Returns:
bool– True if the patch is visible; false if hidden
- name()
Returns the name of the patch.
- Returns:
str– The name of this patch
See also
setName()
- setLocked(Locked)
Changes the locked state of the patch.
Patches may be locked to prevent painting on or applying filters to them. They may still be exported when locked.
- Parameters:
Locked (bool) – The new locked status of the Patch. If true, the patch will be locked and cannot be edited
- setName(Name)
Sets the name of the patch.
The name is used in the UV view and the patch view.
The default name for a patch is its UDIM.
- Parameters:
Name (str) – The new name for the patch
- setSelected(Selected)
Changes the selection state of the patch.
- Parameters:
Selected (bool) – True to select the patch, or false to deselect it
- setVisibility(Visible)
Shows or hides the patch.
- Parameters:
Visible (bool) – True to show the patch, or false to hide it
- u()
Returns the U location of the patch.
- Returns:
int– The integer U coordinate of the lower left corner of the patch in UV space
- udim()
Returns the UDIM of the patch.
UDIM values identify the integer position of a patch in a channel. Each patch represents a square of dimensions 1x1 in U-V space with integer boundaries. There may be up to ten patches across, and any number of patches upwards - so the U index of a patch must be in the range [0, 9], and the V index can be zero or any positive integer.
The UDIM value for a patch can be calculated using the following formula:
udim = 1001 + u + (10 * v)}For example, the UDIM of the bottom left patch, which represents the U-V space region (0, 0) to (1, 1), will be 1001. The next patch to the right of that will have UDIM 1002, and the patch directly above the bottom left will be 1011. If there are ten patches across, the one on the bottom row at the far right, representing the region (9, 0) to (10, 1), will have UDIM 1010.
The U index limit of ten is currently hard-wired.
- Returns:
int– The UDIM of the patch, as specified above
- uv()
Returns the UV location of the patch.
- Returns:
QPoint– The integer U and V coordinates of the lower left corner of the patch in UV space
- uvIndex()
Returns the UV index of the patch.
This provides a 0-based index of the patch, which can be used with
ImageSet::image()to find the image in a channel that will be applied to the patch.The UDIM of the patch will be this value plus 1001.
- Returns:
int– The integer UV index of the patch.
- v()
Returns the V location of the patch.
- Returns:
int– The integer V coordinate of the lower left corner of the patch in UV space
- class mari.GeometryOperation
Bases:
MetadataThis encapsulates a geometry operation that can be performed on a Geo Entity.
You can access the registered geometry operations through the EntityManager - for example:
mari.geo.geometryOperationList()- execute(Operation, GeometryEntity, GeoVersion, QuerySubdivisionMesh, SubdivisionLevel, ExtraParams='variant')
Executes the geometry operation for the current frame.
- Parameters:
Operation (str) – The sub-operation to execute.
GeometryEntity (GeoEntity) – The
GeoEntitythat we want to query info for.GeoVersion (GeoEntityVersion) – The Version,within the Geo Entity, that we want to query.
QuerySubdivisionMesh (bool) – Flag to toggle querying subdivision meshes or original meshes.
SubdivisionLevel (int) – Subdivision level to query for subdivision meshes.
ExtraParams (variant, optional) – Extra parameters for the image operation. Defaults to variant.
- Returns:
bool– The result of the operation.
- name()
Returns the name of the operation.
- Returns:
str– The name of the operation.
- operationDescription(Name)
Returns the description of one of the operations.
- Parameters:
Name (str) – The sub-operation whose description we require.
- Returns:
str– The description corresponding to the operation.
- supportedOperations()
Returns the supported operations by this object.
- Returns:
list of str– The supported operations.
- class mari.GraphLayer
Bases:
AdjustableLayerGraph layers contain an image for each patch that can be painted directly.
You can access all types of layers from their containing
Channelobjects - for example:channel.layerList()You can check for
GraphLayerobjects by callingLayer::isGraphLayer():This examples shows how to create a graph layer and checks if it’s a graph layer
>>> import mari >>> channel = mari.geo.current().currentChannel() >>> graphLayer = channel.createGraphLayer("Test") >>> graphLayer.isGraphLayer() True
This examples shows how to create a Perlin node in the graph layer
>>> childNodeGraph = graphLayer.nodeGraph() >>> perlin = childNodeGraph.createNode("Procedural/Noise/Perlin")
- convertToPaintable(SelectedOnly=False)
Converts the Layer into a Paintable Layer.
As this operation changes the
Layertype, it is suggested that you reobtain a reference to thisLayer.- Parameters:
SelectedOnly (bool, optional) – Whether or not to bake the result into all patches or only the selected patches. Defaults to False.
- class mari.GroupLayer
Bases:
AdjustableLayerGroup layers contain a stack of other layers to be processed as a separate unit.
You can access all types of layers from their containing
Channelobjects - for example:channel.layerList()You can check for
GroupLayerobjects by callingLayer::isGroupLayer():Example Code
>>> #This example finds group layers in the current channel. >>> import mari >>> group_layers = [] >>> channel = mari.geo.current().currentChannel() >>> for layer in channel.layerList(): ... if layer.isGroupLayer(): ... group_layers.append(layer)
- flattenLayerGroup()
Flattens the layer group to a single layer.
- Returns:
bool– Returns whether the operation was successful.
- layerStack()
Returns the layer stack that is grouped within this layer.
- Returns:
LayerStack– Returns a layer stack
- class mari.GroupNode
Bases:
NodeRepresents an group node.
A
GroupNodeis a node that contains its own subNodeGraph. It can be used to organize nodes.It is possible to promote parameters of the member nodes as parameters of
GroupNodeitself. The promoted parameters are called knobs.Example Code
This example shows how to obtain a group node from the node graph of the current geo entity and print the names of the member nodes.
>>> import mari >>> nodeGraph = mari.geo.current().nodeGraph() >>> for node in nodeGraph.nodeList(): ... if isinstance(node, mari.GroupNode) and not node.hasTag('_shader'): ... childNodeGraph = node.childNodeGraph() ... for memberNode in childNodeGraph.nodeList(): ... nodeName = memberNode.nodeName()
This example shows how to create a group node and create a new node inside the group node.
>>> group = nodeGraph.createNode("Misc/Group") >>> subNodeGraph = group.childNodeGraph() >>> merge = subNodeGraph.createNode("Layer/Merge")
This example shows how to create a group node by passing in what nodes to group.
>>> mergeA = nodeGraph.createNode("Layer/Merge") >>> mergeB = nodeGraph.createNode("Layer/Merge") >>> group = nodeGraph.groupNodes([mergeA,mergeB]);
This example shows how create a knob in the group node
>>> group.createKnob("BAmount",mergeB,"Amount","B Amount")This example shows how to create a gizmo and register it for reusing in a node graph.
>>> # Get the node graph of the current object >>> ng = mari.geo.current().nodeGraph() >>> >>> # Create UV node that outputs UV coordinates >>> uv = ng.createNode("Geometry/UV") >>> >>> # Create a cloud fractal noise node >>> cloud = ng.createNode("Procedural/Fractal/Cloud") >>> >>> # Connect UV to the position of cloud so that the cloud pattern is generated over UV space >>> cloud.setInputNode("Position",uv) >>> >>> # Group UV and cloud into a group node >>> group = ng.groupNodes([uv,cloud]) >>> >>> # Create gizmo knobs, Size and Roughness >>> group.createKnob("CloudSize",cloud,"Size","Cloud Size") >>> group.createKnob("CloudRoughness",cloud,"Roughness","Cloud Roughness") >>> >>> # Save the group node out as an .mng file >>> ng.save("/tmp/UvCloud.mng",[group])
The saved group node can be automatically registered to appear in
Mariby placing the file under Mari/Gizmos directory:~/Mari/Gizmos/Procedural/UVCloud.mng (On Mac and Linux) C:/Users/UserNname/My Documents/Mari/Gizmos/Procedural/UVCloud.mng (On Windows)
- childNodeGraph()
Returns the node graph this group node contains.
- Raises:
RuntimeError – Raised if the child node graph cannot be found.
- Returns:
NodeGraph– The GroupNode object this node contains.
- convertToCustomProcedural()
Converts this group to a Custom Procedural node and returns the new Custom Procedural node.
- createKnob(KnobName, TargetNode, TargetAttributeName, PrettyKnobName='str')
Creates a knob linked to a node attribute.
- Parameters:
KnobName (str) – name of the knob to create. It must contain only alphabets, numbers and underscores.
TargetAttributeName (str) – The attribute name of the TargetNode to link the new knob to
PrettyKnobName (str, optional) – The pretty name of the knob to be created. Defaults to str.
- Raises:
RuntimeError – Raised if the knob cannot be created.
- Returns:
bool– The status of the operation, as a boolean flag.
- deleteKnob(KnobName, TargetNode, TargetAttributeName)
Deletes a knob linked to the node attribute.
- groupInputNode(InputName)
Returns the node inside the group network that corresponds to the given input name.
- groupOutputNode(OutputName)
Returns the node inside the group network that corresponds to the given output name.
- isGroupNode()
Returns whether this node is an GroupNode.
- Returns:
bool– Whether this node is an GroupNode
- knobList()
Returns the list of tuples representing the knobs of this GroupNode.
A tuple in the list consists of four items:
Name(str): The name of the knob
GroupName(str): The name of the attribute group the knob belongs to
NodeObject(mari.Node): The node the knob links to
NodeAttributeName(str): The node attribute name the knob links to
Example Code
This example shows how to print knobs for all the group nodes.
>>> for node in mari.geo.current().nodeGraph().nodeList(): ... if node.isGroupNode(): ... print("Knobs for the node - ",node.name()) ... for knob in node.knobList(): ... print(" Knob Name:%s, Group:%s, Node:%s, Target Attribute:%s" % (knob[0],knob[1],knob[2].name(),knob[3])) Knobs for the node - MyGroup Knob Name:Offset, Group:Ambient Occlusion, Node:Ambient Occlusion, Target Attribute:Offset Knob Name:Gamma, Group:Ambient Occlusion, Node:Ambient Occlusion, Target Attribute:Gamma Knob Name:InputA, Group:Edge Pattern, Node:Edge Pattern, Target Attribute:InputA
- Returns:
list of variant– the list of tuples representing the knobs of this GroupNode
- linkKnobs(KnobName, TargetKnobNames, PrettyKnobName='str')
Creates a linked knob linked to the existing specified group node knobs.
Example Code
>>> # Create an Empty Group node >>> nodeGraph = mari.current.geo().nodeGraph() >>> groupNode = nodeGraph.createNode("Misc/Group") >>> >>> # Get the output node from the node list as an empty group only contains a single node : output node >>> groupNodeGraph = groupNode.childNodeGraph() >>> outputA = groupNodeGraph.nodeList()[0] >>> >>> # Create two Tiled procedural nodes and a second output >>> tiledA = groupNodeGraph.createNode("Procedural/Pattern/Tiled") >>> tiledB = groupNodeGraph.createNode("Procedural/Pattern/Tiled") >>> outputB = groupNodeGraph.createNode("Misc/Output") >>> >>> # Connect the outputs to the tiled procedurals >>> outputA.setInputNode("Input", tiledA) >>> outputB.setInputNode("Input", tiledB) >>> >>> # Expose the U / V Repeat attributes as group knobs >>> knobNames = [] >>> for attributeName in ("URepeat", "VRepeat"): ... for index, tiledNode in enumerate((tiledA, tiledB)): ... knobName = "Tiled%d%s" % (index, attributeName) ... groupNode.createKnob(knobName, tiledNode, attributeName) ... knobNames.append(knobName) ... ... # Link the 4 exposed knobs as a single linked knob ... groupNode.linkKnobs("tileRepeat", knobNames)
- Parameters:
KnobName (str) – Name of the knob to create.It must contain only alphabets, numbers and underscores.
TargetKnobNames (list of str) – The knob names of the Groups node’s existing knobs to link together.
PrettyKnobName (str, optional) – The pretty name of the knob to be created. Defaults to str.
- Raises:
RuntimeError – Raised, if the knob cannot be created.
- renameKnob(OldName, NewName)
Renames a knob.
- Parameters:
OldName (str) – the name of the knob to change
NewName (str) – the new name of the knob
- class mari.History
Bases:
objectProvides access to the Mari editing history, or undo stack.
The history is only available for the currently open project, and will be lost when the project is closed. Operations cannot be performed when there is no project open.
Example Code
>>> # This example calls undo() to undo the last change in the undo history >>> import mari >>> mari.history.undo() True
Alias
history
- cancelMacro()
Cancels the current macro grouping.
This cancels the group of history items begun by
startMacro(). You need to callstopMacro()after all anyway. All actions performed sincestartMacro()call tillstopMacro()call are undone and the macro itself is removed from the undo stack.- Raises:
RuntimeError – Raised, if there is no project open or if no macro is currently active.
See also
startMacro()
See also
stopMacro()
See also
isMacroActive()
- clear(ShowDialog=True)
Clears the undo history, without undoing any operations.
This permanently clears the undo history, without undoing any of the operations. Effectively there will be no change to the current state of the project other than that none of the previous operations can be undone (or redone) afterwards.
However, clearing the undo history will remove references to previous data that are no longer needed, and hence free space in memory and on disk when garbage collection is performed.
As undo data will be destroyed, this method optionally displays a confirmation dialog.
This function raises an exception if it is called when the current project requires saving. This is because clearing history on an unsaved project would invalidate any old data from the saved state that has since been changed. If the user then closed the project without saving, some of the data from that saved state might no longer be valid. This could appear as project corruption, so the exception avoids that risk.
- Parameters:
ShowDialog (bool, optional) – If set to true,
Mariwill display a confirmation dialog. Defaults to True.- Raises:
RuntimeError – Raised if there is no project open, or if the current project requires saving.
Warning
Older versions of Mari did not raise an exception when the function was called on a project that required saving. Please ensure that any relevant scripts are up to date.
- isMacroActive()
Indicates whether history items are currently being grouped into a macro.
This method will return true if
startMacro()has been called without a correspondingstopMacro().Many internal functions also start and stop macros, and this function will also return true if called while one of those macros is active. This can happen when running custom code in response to a signal, for example.
- Raises:
ValueError – Raised if there is no project open.
- Returns:
bool– True if history items are being grouped into a macro, or false otherwise
- redo()
Redoes the most recently undone action in the history.
- Raises:
RuntimeError – Raised if there is no project open.
- Returns:
bool– True if the redo was performed, or false when there are no more items to redo
See also
undo()
- startMacro(MacroName)
Starts grouping history items into a new macro.
Mariallows grouping of history items into macros. A macro is a block of actions that appears as one item in the history and can be done or redone as a single unit.startMacro()must be followed bystopMacro(); if not, the behavior is undefined.- Parameters:
MacroName (str) – The name of the new macro block. This name will appear in the history view.
- Raises:
RuntimeError – Raised if there is no project open.
ValueError – Raised if the macro name is empty.
See also
isMacroActive()
- stopMacro()
Stops the current macro grouping.
This ends the group of history items begun by
startMacro().- Raises:
RuntimeError – Raised if there is no project open, or if no macro is currently active.
See also
isMacroActive()
- undo()
Undoes the last action in the history.
- Raises:
RuntimeError – Raised if there is no project open.
- Returns:
bool– True if the undo was performed, or false when there are no more items to undo
See also
redo()
- class mari.Image
Bases:
MetadataThese objects contain individual 2D images.
You can access images either from an
ImageSetor through theImageManager- for example:mari.images.list()Example Code
>>> # This example obtains the image of UDIM 1001 from the current layer of the current channel >>> import mari >>> layer = mari.geo.current().currentChannel().currentLayer() >>> if layer.isPaintableLayer(): ... image_set = layer.imageSet() ... image = image_set.image(0)
>>> # This examples opens an image through ImageManager and obtains the Image object >>> import mari >>> import os >>> imagePath = os.path.join(mari.resources.path(mari.resources.IMAGES),"NoThumb.png") >>> image = mari.images.load(imagePath)
- BACKGROUND_EXPORT = 8
When set saveAs will return immediately and exporting will occur as a background job. Background jobs may not report errors or raise exceptions.
- Type:
int
- DEFAULT_OPTIONS = 0
None of the other options are set.
- Type:
int
- DEPTH_BYTE = 8
Standard eight bit depth.
- Type:
int
- DEPTH_FLOAT = 32
Full float depth.
- Type:
int
- DEPTH_HALF = 16
Half-float depth.
- Type:
int
- DISABLE_SMALL_UNIFORMS = 1
Turns off “small uniforms” (exporting blank textures as 8x8)
- Type:
int
- class Depth
Bases:
objectThese are the bit depths supported by images and image sets.
- DEPTH_BYTE = 8
Standard eight bit depth.
- Type:
int
- DEPTH_FLOAT = 32
Full float depth.
- Type:
int
- DEPTH_HALF = 16
Half-float depth.
- Type:
int
- ENABLE_FULL_PATCH_BLEED = 2
Turns on “full texture bleed” (full patch texture bleed is generated). This takes effect only for exporting textures.
- Type:
int
- EXPORT_UV_MASK_IN_ALPHA = 16
The UV mask will be exported in the alpha channel. 1 represents inside, 0, out. This option is ignored if REMOVE_ALPHA is enabled.
- Type:
int
- FILESPACE_NORMAL = 0
Copy Values.
- Type:
int
- FILESPACE_NORMAL_Y_FLIP = 3
Same as NORMAL but Y vector is flipped, i.e. [0,1] is mapped to [1,0] for Y.
- Type:
int
- FILESPACE_VECTOR = 1
Values [0,1] get mapped to [-1,+1] for float and half formats. No conversion for bytes.
- Type:
int
- FILESPACE_VECTOR_Y_FLIP = 2
Same as VECTOR but Y component of vector is flipped, i.e. [-1,+1] is mapped to [+1,-1] for Y.
- Type:
int
- FORMAT_R = 1
Each pixel is a single red component.
- Type:
int
- FORMAT_RG = 2
Each pixel is a red/green double.
- Type:
int
- FORMAT_RGB = 3
Each pixel is an RGB triple.
- Type:
int
- FORMAT_RGBA = 4
Each pixel contains all four components.
- Type:
int
- class FileSpace
Bases:
objectThese are the file spaces supported by by images and image sets.
- FILESPACE_NORMAL = 0
Copy Values.
- Type:
int
- FILESPACE_NORMAL_Y_FLIP = 3
Same as NORMAL but Y vector is flipped, i.e. [0,1] is mapped to [1,0] for Y.
- Type:
int
- FILESPACE_VECTOR = 1
Values [0,1] get mapped to [-1,+1] for float and half formats. No conversion for bytes.
- Type:
int
- FILESPACE_VECTOR_Y_FLIP = 2
Same as VECTOR but Y component of vector is flipped, i.e. [-1,+1] is mapped to [+1,-1] for Y.
- Type:
int
- class Format
Bases:
objectThese are the pixel formats supported by images and image sets and relate to how many components.
- FORMAT_R = 1
Each pixel is a single red component.
- Type:
int
- FORMAT_RG = 2
Each pixel is a red/green double.
- Type:
int
- FORMAT_RGB = 3
Each pixel is an RGB triple.
- Type:
int
- FORMAT_RGBA = 4
Each pixel contains all four components.
- Type:
int
- REMOVE_ALPHA = 4
Remove the alpha channel (convert RGBA to RGB)
- Type:
int
- class SaveOptions
Bases:
objectSpecifies optional behavior for image saving.
- BACKGROUND_EXPORT = 8
When set saveAs will return immediately and exporting will occur as a background job. Background jobs may not report errors or raise exceptions.
- Type:
int
- DEFAULT_OPTIONS = 0
None of the other options are set.
- Type:
int
- DISABLE_SMALL_UNIFORMS = 1
Turns off “small uniforms” (exporting blank textures as 8x8)
- Type:
int
- ENABLE_FULL_PATCH_BLEED = 2
Turns on “full texture bleed” (full patch texture bleed is generated). This takes effect only for exporting textures.
- Type:
int
- EXPORT_UV_MASK_IN_ALPHA = 16
The UV mask will be exported in the alpha channel. 1 represents inside, 0, out. This option is ignored if REMOVE_ALPHA is enabled.
- Type:
int
- REMOVE_ALPHA = 4
Remove the alpha channel (convert RGBA to RGB)
- Type:
int
- aboutToClose()
This is emitted just before the image is closed.
- aboutToExport(Path)
This is emitted when the user is about to export the image.
- Parameters:
Path (str) – The path the image will be exported to
- aboutToImport(Path)
This is emitted when the user is about to import into the image.
- Parameters:
Path (str) – The path the image will be imported from
- category()
Returns the name of the tab, in the image manager palette, that the image is in.
- Returns:
str– The image manager tab the image is located in.
Deprecated
This function will be removed in a future version. This function currently behaves like imageGroup().
See also
setCategory()
- close()
Closes the image, removing it from the image manager.
If the image is open in the image manager, it will be closed and removed. Not all images can be closed in this way. If the image is a member of an image set, the image set “owns” the image and will not allow it to be closed. To remove such an image, remove the image set that owns it.
This method can be called on all images, but images that are not in the image manager will not be closed, and an exception will be raised.
- Raises:
RuntimeError – Raised if the image is not owned by the image manager and cannot be closed.
Note
If this function successfully closes the image, the image object will become invalid.
- colorspaceConfig()
Returns the colorspace configuration of the image.
- Returns:
ColorspaceConfig– The colorspace configuration.
- colorspaceConfigChanged(Config)
This is emitted after the colorspace config is modified for this object.
- Parameters:
Config (ColorspaceConfig)
- convertColorspaceTo(OutputColorspace, InputColorspace='str', Config='str')
Converts this image’s data to a new colorspace.
This only applies the colorspace transform and does not update the colorspace config of the image.
- Parameters:
OutputColorspace (str) – Name of the colorspace or role in the OCIO config to convert this image to.
InputColorspace (str, optional) – Optional name of the colorspace or role in the OCIO config to convert this image from. If not specified then the native colorspace of the image is used. Defaults to str.
Config (str, optional) – Optional name of a standard OCIO config file or the path to a custom one. If not specified then the OCIO config of the project is used. Defaults to str.
- Raises:
ValueError – Raised if an invalid colorspace or OCIO config is given.
- convertDepth(Depth)
Converts the depth of the image.
- Parameters:
Depth (Image.Depth) – The new bit depth for the image.
- copyFrom(SourceImage)
Copies the contents of another image into this one.
Mariallows very quick copying and duplication of image data. This method allows the contents of another image to be copied into this one. The image must have the same dimensions (width and height) and format as the source image, otherwise an exception will be raised. As the API does not yet allow you to alter the format of an image directly, this method is useful only when the images already have the same format (e.g. images from the sameImageSet). This operation is effectively free in terms of memory usage and the user should not worry about copying large amounts of data using this method.- Parameters:
SourceImage (Image) – The image to copy from
- Raises:
ValueError – Raised if the source or destination image is invalid, or if they are both the same image object, or if the destination image does not have the same dimensions and format as the source image.
- depth()
Returns the bit depth of the image.
- static depthAsInternalFormat(Depth)
Returns the OpenGL integer representation of Internal Format of the given Depth.
- Parameters:
Depth (Image.Depth) – The Depth that corresponds to the returned Internal Format.
- Returns:
int– The Internal Format as the OpenGL integer
- exported(Path)
This is emitted after the image is exported.
- Parameters:
Path (str) – The path the image was exported to
- filePath()
Returns the path to the file that the image was loaded from.
This path will be valid for images loaded from disk into the image manager. Images that are contained in channels will have a blank file path.
- Returns:
str– The path that the image was loaded from, or a blank string if not available
See also
lastImportPath(), lastExportPath()
- fileSpace()
Returns the file space the image will import and export data as.
- fill(FillColor)
Fills the image entirely with a given color.
This function is the same as
setUniformColor().- Parameters:
FillColor (Color) – The color to fill the patch with. RGB images will ignore the alpha component.
- Raises:
ValueError – Raised if the color provided was invalid.
See also
isUniform(), setUniformColor(), uniformColor()
- hash()
Returns a unique identifier for this image.
Marimaintains hashes of images for internal book-keeping. These hashes are assumed to be universally unique (256bit skein hash). These hashes can be used to determine if an image has changed since some given checkpoint. A different hash means a different image.The hash of an image is calculated from its resolution (which determines the number of tiles it uses), bit depth, and tile data. Any metadata for the image is not included. Multiple images that store the same data will have the same hash and reference the same underlying data block, which means that the
DDIcan save memory and disk space by storing the same block of data only once.- Returns:
str– A hash string that uniquely identifies this version of this image, or an empty string on failure.
- height(MipMapLevel=0)
Returns the height of a mip-map level in the image.
- Parameters:
MipMapLevel (int, optional) – Mip-map level, in the range [0 to Count - 1], where 0 is the original size. Defaults to 0.
- Raises:
ValueError – Raised if the mip-map level was out of range.
- Returns:
int– The height of the mip-map level in pixels
- imageGroup()
Returns the name of the image group this image belongs to.
- Returns:
str– The image group for this image.
See also
setImageGroup()
- imported(Path)
This is emitted after the image is imported.
Path The path the image was imported from
- Parameters:
Path (str)
- isUniform()
Returns whether the given image is all a single color.
Marimakes storing large uniform color images very efficent internally. It is often useful to know if an image is all a single color on export.This method indicates whether the image is uniform - i.e. all a single color. This can help to decide whether an image should be exported.
- Returns:
bool– True if this image is a uniform color, or false if it contains any pixels that are different colors.
See also
fill(), setUniformColor(), uniformColor()
- lastExportPath()
Returns the last path the image was saved to.
- Returns:
str– The path that the image was last saved to. This will be an empty string if the image has not been saved yet
See also
lastImportPath(), lastExportTime(), filePath()
- lastExportTime()
Returns the date and time at which the image was last exported.
- Returns:
QDateTime– The date and time of the last export, or an empty DateTime object if never exported
See also
lastExportPath()
- lastImportPath()
Returns the path to the last file that was imported into the image.
- Returns:
str– The path of the last file imported into the image. This will be an empty string if nothing has been imported into the image
See also
lastExportPath(), lastImportTime(), filePath()
- lastImportTime()
Returns the date and time at which the image was last imported.
- Returns:
QDateTime– The date and time of the last import, or an empty DateTime object if never imported
See also
lastImportPath()
- makeThumbnail()
Makes a thumbnail image from the current image contents for use by the GUI.
- mipMapCount()
Returns the number of mip-maps in the image.
- Returns:
int– The number mip-maps in the image
- mostRelevantPath()
Returns a best guess as to which file on disk represents this texture.
Marikeeps track of when files are imported and exported. It uses a basic heuristic to guess which file on disk represents a givenMariImage.The time and date of each import and export is recorded. If an image was imported more recently than
Mariexported, the import image is presumed to be most relevant. IfMariexported more recently than importing, the exported version is presumed to be more relevant.- A couple of quick examples:
Mariimport from a.pngUser paints some more detail
Mariexports to b.png
- In this case, b.png is presumed to be most relevant and will be returned by this method.
Mariexports to a.pngUser paints some more detail
User decides they don’t like the changes
Mariimports from a-version2.png
In this case, a-version2.png will be returned.
- Returns:
str– The most relevant path or and empty string if neither importing or exporting has occured
- name()
Returns the name of the image. This defaults to the filename of the imported image.
- Returns:
str– The name of the image.
- resize(NewSize)
Resizes the image.
- Parameters:
NewSize (QSize) – the desired size for the image.
- Raises:
ValueError – Raised if the size provided was invalid.
- saveAs(FileName, Options='variant', SaveOpts='Image.DEFAULT_OPTIONS')
Saves the image to the given file name.
The options parameter can be used to pass options to the file writer, in dictionary format. For example:
img.saveAs('/tmp/test.jpg', {'IntegerSetting': 1, 'StringSetting': 'Hello'})These options are currently only used by custom image writers. Please refer to the C API documentation - specifically, the MriImageReaderPlugin type and the attribute system - for details of how to develop a plug-in and read the values passed into it from this function.
Saving may occur in the background. If this is enabled (via the BACKGROUND_EXPORT enum from SaveOptions) then saveAs will return instantly and the image will be exported on a background thread.By default background exporting is disabled and saveAs will only return when the image has been exported. When exporting in the background, errors and exceptions may not be raised on failure to save. An example of using background export would be:
img.saveAs('/tmp/test.jpg', {}, mari.Image.SaveOptions.BACKGROUND_EXPORT)When background exporting the source image is copied internally and can be closed or modified without disrupting the background job.
- Parameters:
FileName (str) – The absolute path, file name, and extension to save the image to.
Options (variant, optional) – This is an optional parameter which can be used to pass options to the file writer. See above for details. Defaults to variant.
SaveOpts (int, optional) – Pass in a value other than the default to turn on an option, such as disabling “small uniforms”. See SaveOptions. Defaults to Image.DEFAULT_OPTIONS.
- Raises:
IOError – Raised if there is a problem saving the file.
TypeError – Raised if the options parameter is not a dict.
- selected()
Returns true if the image is selected in the image manager palette, false otherwise.
- Returns:
bool– Whether the image is selected or not.
See also
setSelected()
- setCategory(Name)
Moves the image to another tab in the image manager palette.
If the tab doesn’t exist then a new one will be created.
- Parameters:
Name (str) – The name of the tab to move the image into.
Deprecated
This function will be removed in a future version. This function currently behaves like setImageGroup().
See also
category()
- setColorspaceConfig(Config)
Sets the colorspace configuration of the image.
- Parameters:
Config (ColorspaceConfig) – The colorspace configuration.
- Raises:
ValueError – Raised if the colorspace configuration is invalid.
- setFileSpace(FileSpace)
Set the file space the image will import and export data as.
- Parameters:
FileSpace (Image.FileSpace)
- setImageGroup(GroupName)
Moves the image to the given image group.
If the image group does not exist, one will be created.
- Parameters:
GroupName (str) – The name of the image group to assign the image to.
See also
imageGroup()
- setName(Name)
Sets the name of the image.
- Parameters:
Name (str) – The name of the image.
- Raises:
ValueError – Raised if the given name is not valid.
- setSelected(Select)
Either select or deslect the image in the image manager palette.
- Parameters:
Select (bool) – Whether the image should be selected or deselected.
See also
selected()
- setUniformColor(pUniformColor)
Fills the image entirely with the given color.
This function is the same as
fill().- Parameters:
pUniformColor (Color) – The color to fill this patch with. RGB images will ignore the alpha component.
- Raises:
ValueError – Raised if the color provided was invalid.
See also
fill(), isUniform(), uniformColor()
- size(MipMapLevel=0)
Returns the size of a mip-map level in the image.
- Parameters:
MipMapLevel (int, optional) – Mip-map level, in the range [0 to Count - 1], where 0 is the original size. Defaults to 0.
- Raises:
ValueError – Raised if the mip-map level was out of range.
- Returns:
list of
int– The size of the image in pixels, in the format: (width, height)
- thumbnail()
Get thumbnail.
- transform(Collection)
Transform the image entirely with a given filter.
This function allows an image to be quickly tranformed with the given
PostFilterCollectionobject.- Parameters:
Collection (PostFilterCollection) – A filter collection object.
- Raises:
ValueError – Raised if the input filter is invalid.
- Returns:
bool– True on success
- uniformColor()
Returns the single color that fills the entire image, if applicable.
Storing large images that are uniform - i.e., consist entirely of a single color - is very efficient. This function returns that single color, for an image that is uniform.
- Raises:
RuntimeError – Raised if the image was not all of a single color.
- Returns:
Color– The uniform color of the image
See also
fill(), isUniform(), setUniformColor()
- width(MipMapLevel=0)
Returns the width of a mip-map level in the image.
- Parameters:
MipMapLevel (int, optional) – Mip-map level, in the range [0 to Count - 1], where 0 is the original size. Defaults to 0.
- Raises:
ValueError – Raised if the mip-map level was out of range.
- Returns:
int– The width of the mip-map level in pixels
- class mari.ImageManager
Bases:
MetadataHandles the images available in the application.
Example Code
>>> # This examples opens an image through ImageManager and obtains the Image object >>> import mari >>> import os >>> image_path = os.path.join(mari.resources.path(mari.resources.IMAGES),"NoThumb.png") >>> image = mari.images.open(image_path)
Alias
images
- IMAGE_COLOR_CONVERSION_LINEAR_TO_SRGB = 1
Convert from linear to srgb.
- Type:
int
- IMAGE_COLOR_CONVERSION_NONE = 0
No conversion required.
- Type:
int
- IMAGE_NO_PRE_MULTIPLY_ALPHA = 1
Leave pixels as they are.
- Type:
int
- IMAGE_PRE_MULTIPLY_ALPHA = 0
Convert pixels into premultiplied alpha format, if required.
- Type:
int
- class ImageAlphaProcessing
Bases:
object- IMAGE_NO_PRE_MULTIPLY_ALPHA = 1
Leave pixels as they are.
- Type:
int
- IMAGE_PRE_MULTIPLY_ALPHA = 0
Convert pixels into premultiplied alpha format, if required.
- Type:
int
- class ImageColorSpaceConversionType
Bases:
objectThese are various options for colour conversion, when loading an image.
- IMAGE_COLOR_CONVERSION_LINEAR_TO_SRGB = 1
Convert from linear to srgb.
- Type:
int
- IMAGE_COLOR_CONVERSION_NONE = 0
No conversion required.
- Type:
int
- add(ImageToAdd, Name='str')
Adds the given image to the image manager view.
Marimaintains a set of reference images that the user can access. This method adds the given image to the set of reference images- Parameters:
ImageToAdd (Image) – The image object to add
Name (str, optional) – The name of the image to be set to. Defaults to str.
- addCategory(CategoryName)
Add a new images’ category to Image Manager palette. Categories are shown as tabs.
- Parameters:
CategoryName (str) – Name of an added category.
Deprecated
This function will be removed in a future version. Please use addImageGroup() instead. This now adds a new image group, which replaces the category tab feature.
- addImage(ImageToAdd, Name='str')
Adds the given QImage to the image manager view.
Marimaintains a set of reference images that the user can access. This method adds the given QImage to the set of reference images- Parameters:
ImageToAdd (QImage) – The QImage object to add
Name (str, optional) – The name of the image to be set to. Defaults to str.
- Returns:
Image– The new reference image stored in the image manager.
- addImageGroup(GroupName)
Add a new image group.
If an image group already exists with the given name, no new group will be created.
- Parameters:
GroupName (str) – Name of an image group.
- Raises:
ValueError – Raised if the given image group does not already exist and could not be created.
- addToImageGroup(Images, GroupName)
Add the given images to the given image group.
- Parameters:
Images (list of
Image) – Images to add to the group.GroupName (str) – Name of the image group the images should be added to. A new group will be created if one does not already exist.
- Raises:
ValueError – Raised if the given image group isn’t found and could not be created.
- backgroundOpen(Path, Config=None, AlphaProcessing='IMAGE_PRE_MULTIPLY_ALPHA', Name='str', Category='str')
Loads images from an image file into the image manager view in the background.
Marimaintains a set of reference images that the user can access. This method opens an image into this set of reference images.- Parameters:
Path (str) – The path to the image file to open.
Config (ColorspaceConfig, optional) – The colorspace configuration to use. If none is given then a default configuration will be used. Defaults to None.
AlphaProcessing (ImageAlphaProcessing, optional) – This specifies if the pixels are converted into a premultiplied alpha format; conversion is the default. Defaults to IMAGE_PRE_MULTIPLY_ALPHA.
Name (str, optional) – By default the name of the loaded image will be derived from the Path. This optional parameter specifies a different name for the loaded image. Defaults to str.
Category (str, optional) – The category in
ImageManager palette to load the image into. Defaults to str.
- Raises:
ValueError – Raised if the specified path was empty, the colorspace configuration file is invalid, or the colorspaces are invalid.
IOError – Raised if there was an error loading the image.
- beginImageLoading()
This is emitted before image loading.
This signal can be used to detect when
Mariis about to load one or more images.
- categories()
Get a list of all categories currently existing in Image Manager palette.
- Returns:
list of str– List of all categories in Image Manager palette.
Deprecated
This function will be removed in a future version. Currently returns the same as imageGroupList().
- clearTraces(PathOrHash)
Clears all callstack information presently held on a path or hash.
- Parameters:
PathOrHash (str) – The file path or hash of the image to trace
- collapseImageGroup(GroupName)
Collapse the image group of the given GroupName.
- Parameters:
GroupName (str) – Name of the image group to collapse.
- Raises:
ValueError – Raised if the given image group isn’t found.
- compressionList(Extension)
Query the supported list of export compression methods, for a given image extension. Example Code
>>> # This examples queries the compression methods for exporting an exr image >>> mari.images.compressionList("exr")
- Parameters:
Extension (str) – The file extension, whose plugin to query for compression methods.
- Returns:
list of str– List of compression methods for the image export plugin.
- currentCategory()
Get the current images’ category in Image Manager palette. Categories are shown as tabs.
- Returns:
str– Name of the current images’ category.
Deprecated
This function will be removed in a future version. This function takes no effect and returns an empty string.
- defaultCompressionMethod(Extension)
Query the default export compression method, for a given image extension. Example Code
>>> # This examples queries the default compression method for exporting an exr image >>> mari.images.defaultCompressionMethod("exr")
- Parameters:
Extension (str) – The file extension, whose plugin to query for the compression method.
- Returns:
str– The default compression method for the image export plugin.
- defaultImageFormat(BitDepth)
Gets the default file format for given texture bit depth.
- Parameters:
BitDepth (Image.Depth) – The bit depth of an image.
- Raises:
RuntimeError – Raised if the bit depth is invalid.
- Returns:
str– A file format.
- endImageLoading()
This is emitted after image loading.
This signal can be used to detect when
Marihas completed loading one or more images.
- expandImageGroup(GroupName)
Expand the image group of the given GroupName.
- Parameters:
GroupName (str) – Name of the image group to expand.
- Raises:
ValueError – Raised if the given image group isn’t found.
- expandedImageGroupList()
Get the names of all expanded image groups.
- Returns:
list of str– List of names of all expanded image groups.
- generateCrossMask(Width, Height, CrossWidthPercentage, CrossHeightPercentage)
Generates a cross shaped mask image.
- Parameters:
Width (int) – The width of the created mask image
Height (int) – The height of the created mask image
CrossWidthPercentage (float) – The width of the vertical cross line in the unit of [0:1] ratio based on the final Width
CrossHeightPercentage (float) – The width of the horizontal cross line in the unit of [0:1] ratio based on the final Height
- getImage(Hash)
Finds an image in the image manager view.
Marimaintains a set of reference images that the user can access. This method opens an image from this set of reference images.- Parameters:
Hash (str) – The hash of the image to retrieve.
- Raises:
ValueError – Raised if the specified hash was empty.
- Returns:
Image– The image object if found. If not found, it returns None.
- handleProtocol(url)
This is emitted when attempting to open image with unknown protocol.
- Parameters:
url (str)
- imageGroupList()
Get a list of all image groups currently existing in Image Manager palette.
- Returns:
list of str– List of all image groups in Image Manager palette.
- imageLoaded(Img)
This is emitted when images are loaded.
- Parameters:
Img (Image) – Newly loaded image.
- imageOperationList()
Get a list of the image operations, registered by the image manager.
- Returns:
list of
ImageOperation– A list of image operations.
- list(GroupName='str')
Returns all of the currently open reference images.
When an image group is specified then only the images in that image group are returned. Otherwise all images are returned regardless of group.
- Parameters:
GroupName (str, optional) – Optional group name to return the images of. Defaults to str.
- Returns:
list of
Image– A list of all the currently open reference images
- open(Path, Config=None, AlphaProcessing='IMAGE_PRE_MULTIPLY_ALPHA', Name='str')
Loads images from an image file into the image manager view.
Marimaintains a set of reference images that the user can access. This method opens an image into this set of reference images.- Parameters:
Path (str) – The path to the image file to open.
Config (ColorspaceConfig, optional) – The colorspace configuration to use. If none is given then a default configuration will be used. Defaults to None.
AlphaProcessing (ImageAlphaProcessing, optional) – This specifies if the pixels are converted into a premultiplied alpha format; conversion is the default. Defaults to IMAGE_PRE_MULTIPLY_ALPHA.
Name (str, optional) – By default the name of the loaded image will be derived from the Path. This optional parameter specifies a different name for the loaded image. Defaults to str.
- Raises:
ValueError – Raised if the specified path was empty, the colorspace configuration file is invalid, or the colorspaces are invalid.
IOError – Raised if there was an error loading the image.
- Returns:
list of
Image– A list of all the images from the file. There will be more than one image for layered image files.
- protocolSupported(Protocol)
Checks if there is a ImageProtocolHandler object with associated protocol.
- Parameters:
Protocol (str) – the protocol name for the handler to handle
- Returns:
bool– boolean indicating if there is a handler for given protocol
Note
ImageProtocolHandler
- registerContextAction(MenuAction, Category='str', IconPath='str')
Register an action, that is to be added as a menu item to the image manager context sentive menu. Example Code
>>> from PySide6.QtWidgets import QAction >>> >>> # Register an action, to be added to the root level of the image manager's context sensitive menu >>> # On triggered, this menu will print "Hello world" to the python console >>> def printMessage(): >>> print("Hello world") >>> >>> PrintAction1 = QAction("Print hello", mari.app) >>> PrintAction1.triggered.connect(printMessage) >>> >>> mari.images.registerContextAction(PrintAction1) >>> >>> >>> # Register 2 actions, to be added to a sub menu "UserSubMenu" of the image manager's context sensitive menu. >>> SubMenuIconPath = mari.resources.path(mari.resources.iconPathKey()) + "/" + "Up.png" >>> >>> def printMessage2(): >>> print("Hello") >>> PrintAction2 = QAction("Hello from sub menu ", mari.app) >>> PrintAction2.triggered.connect(printMessage2) >>> mari.images.registerContextAction(PrintAction2, "UserSubMenu", SubMenuIconPath) >>> >>> def printMessage3(): >>> print("Bye") >>> PrintAction3 = QAction("Bye from sub menu ", mari.app) >>> PrintAction3.triggered.connect(printMessage3) >>> mari.images.registerContextAction(PrintAction3, "UserSubMenu", SubMenuIconPath) >>>
- Parameters:
MenuAction (QAction) – An action that will be added to the menu list
Category (str, optional) – An optional sub-category, to group the actions. This is an empty string, by default. An empty category creates menu items on the main menu itself. Defaults to str.
IconPath (str, optional) – An optional icon path, to add to the sub menu. Defaults to str.
- registerProtocolHandler(Protocol, Handler)
Registers the given ImageProtocolHandler object with associated protocol.
- Parameters:
Protocol (str) – the protocol name for the handler to handle
Handler (ImageProtocolHandler) – the
ImageProtocolHandlerobject to handle the protocol
- Returns:
bool– boolean indicating whether it was successful to register the handler
Note
ImageProtocolHandler
- remove(ImageToRemove)
Removes the given image from the image manager view.
Marimaintains a set of reference images that the user can access. This method removes the given image from the set of reference images- Parameters:
ImageToRemove (Image) – The image object to remove
- Raises:
ValueError – Raised if the given image isn’t in the image manager.
- removeCategory(CategoryName)
Remove images of a chosen category and the category itself from Image Manager palette. Categories are shown as tabs.
- Parameters:
CategoryName (str) – Name of the removed category.
- Returns:
bool– True, if the chosen category was successfully removed. False otherwise.
Deprecated
This function will be removed in a future version. This function takes no effect.
- removeContextAction(MenuAction, Category='str')
Deregister an action from the image manager context sentive menu. Example Code
>>> from PySide6.QtWidgets import QAction >>> >>> # Register an action to the image manager menu >>> MyAction = QAction("Print hello", mari.app) >>> mari.images.registerContextAction(MyAction, "SubMenu") >>> >>> # Unregister the action >>> print(mari.images.removeContextAction(MyAction, "SubMenu")) >>>
- Parameters:
MenuAction (QAction) – An action to be removed.
Category (str, optional) – An optional sub-category, in which the action was originally registered. An empty category refers to the main root menu of the image manager. Defaults to str.
- Raises:
ValueError – Raised if the category is invalid.
- Returns:
bool– A boolean to indicate whether the operation suceeded.
- removeFromImageGroup(Images)
Remove the given images from their respective image groups.
- Parameters:
Images (list of
Image) – Images to remove from their group.
- removeImageGroup(GroupName, RemoveImages=False)
Remove the given image group.
- Parameters:
GroupName (str) – Name of the image group to remove.
RemoveImages (bool, optional) – If true, the images in the group will also be removed. Defaults to false. Defaults to False.
- Raises:
ValueError – Raised if the given image group does not exist or cannot be removed.
- saveImages(Images, Path)
Saves a list of images to a file.
Marisupports saving images to a variety of formats. Some formats support saving multiple images as layers. Others only support single images. This function will save a list of images to a specified path.If a non-layered format is chosen, the list must contain just one image.
If a layered format is chosen, the names of the layers are of the form ‘
LayerN’ where N is the zero-based index of the image in the provided list. There may be other restrictions on each image forming a layer, depending on the file format.- Parameters:
Images (list of
Image) – A list containing the image(s) to save.Path (str) – The path to save the image file(s) to.
- Raises:
ValueError – Raised if the specified path was empty, or no Images were provided.
IOError – Raised if there was an error saving the image.
- Returns:
bool– Always true. On failure, it raises an exception.
- selectCategory(CategoryName)
Select a current images’ category in Image Manager palette. Categories are shown as tabs.
- Parameters:
CategoryName (str) – Name of a selected category.
- Returns:
bool– True, if the chosen category exists and became selected. False otherwise.
Deprecated
This function will be removed in a future version. Please use expandImageGroup instead.
- selected(GroupName='str')
Returns all of the currently open and selected reference images.
When an image group is specified then only the selected images in that image group are returned. Otherwise all selected images are returned regardless of group.
- Parameters:
GroupName (str, optional) – Optional category name to return the selected images of. Defaults to str.
- Returns:
list of
Image– A list of all the currently open and selected reference images
- setDefaultImageFormat(Format, BitDepth)
Set the default file format for given texture bit depth.
- Parameters:
Format (str) – The file format to set to.
BitDepth (Image.Depth) – The bit depth of an image.
- Raises:
RuntimeError – Raised if the bit depth is invalid.
- setMetadata(Name, Value)
Adds or modifies an item of metadata on the object.
If a metadata item with the given name exists already, its value will be updated. If not, a new one will be created.
- Parameters:
Name (str) – The name of the item
Value (variant) – The value of the item
- Raises:
ValueError – Raised if the type of the value is not supported by the metadata system.
- setTraceEnabled(PathOrHash, Enabled=True)
Enables or disables callstack tracing on a path or hash.
When enabled callstack information will be recorded when an image for a path or hash is registered or deregistered. This information can then be subsequently used to find issues.
- Parameters:
PathOrHash (str) – The file path or hash of the image to trace
Enabled (bool, optional) – Whether to enable or disable debug tracing. Defaults to True.
- supportedReadFormats()
Returns a string list of all image formats supported for reading.
The list returned will be all unique lower case strings in ascending alphabetic order.
- Returns:
list of str– A string list of all image formats supported for reading - e.g. [‘jpg, ‘tif’]
- supportedTextureSizeList()
Returns a list of the supported texture sizes.
Marisupports power of two sized textures, with the exact list provided by this function. Textures within channels may be created at any of these sizes.Note that only square textures are supported.
- Returns:
list of
variant– The supported texture sizes in pixels, in the format: ((width1, height1), (width2, height2)…)
- supportedWriteFormats(InternalFormat=0)
Returns a string list of image formats supported for writing.
Supply an internal format value to retrieve only the write formats that can deal with that given internal format, or leave it as zero to return all of them.
The list returned will be all unique lower case strings in ascending alphabetic order.
- Parameters:
InternalFormat (int, optional)
- Returns:
list of str– A string list of all image formats supported for writing - e.g. [‘jpg, ‘tif’]
- swapQuadrants(SourceImage, SwapBack)
Creates a new image where, the top-left/bottom-right quadrants and top-right/bottom-left quadrants are swapped.
If the source image has odd numbers for its width and/or height, one side is longer than the other by one pixel. Use SwapBack, which will flip the longer sides, for swapping back the quadrants.
- traces(PathOrHash)
Returns all callstacks for any register or deregister calls for a path or hash.
- Parameters:
PathOrHash (str) – The file path or hash of the image to trace
- Returns:
list of str– A list of callstacks for the path
- unregisterProtocolHandler(Protocol)
Unregisters the ImageProtocolHandler object associated with given protocol.
- Parameters:
Protocol (str) – the protocol name for the handler to handle
Note
ImageProtocolHandler
- class mari.ImageMimeDataInfo
Bases:
objectObjects of this class holds information for Image.
Information for an
ImageMimeData can be obtained from an instance of this Class.- colorspaceConfigString()
Returns the string representation of the colorspace config of the image.
- Returns:
str– the string representation of the colorspace config of the image
- static fromMimeDataString(MimeDataString)
Returns the list of ImageMimeDataInfo objects represented by the given MimeData.
- Parameters:
MimeDataString (str) – the string representation of the MimeData representing Mari/MriImage MimeType.
- Returns:
list of
ImageMimeDataInfo– the list of ImageMimeDataInfo objects represented by the given MimeData
- path()
Returns the path of the image.
- Returns:
str– the path of the image
- class mari.ImageOperation
Bases:
MetadataThese objects are image operations that can be performed on a layer list.
You can access the registered image operations through the
ImageManager- for example:mari.images.imageOperationList()- execute(Operation, Source, ExtraParams='variant')
Executes the operation.
- Parameters:
Operation (str) – The sub-operation to execute.
Source (Image) – The image on which to execute the operation.
ExtraParams (variant, optional) – Extra parameters for the image operation. Defaults to variant.
- Returns:
bool– The result of the image operation.
- name()
Returns the name of the operation.
- Returns:
str– The name of the operation.
- operationDescription(Name)
Returns the description of one of the operations.
- Parameters:
Name (str) – The sub-operation whose description we require.
- Returns:
str– The description corresponding to the operation.
- supportedOperations()
Returns the supported operations by this object.
- Returns:
list of str– The supported operations.
- class mari.ImageProtocolHandler
Bases:
MetadataAbstract class for implementing a custom ImageProtocolHandler.
An
ImageProtocolHandlersubclass allows translating an URL with custom protocol into actual image path. Once a subclass ofImageProtocolHandleris registered with its associated protocol,ImageManagerwill start redirecting incoming URL to the protocol handler for the protocol. Then the handler translates URL into an actual image path so thatImageManagercan open the image. A typical use case is to integrate a in-house image library into MARI for straight drag&drop of imageExample Code
>>> # This examples implements a new sample ImageProtocolHandler that removes the protocol scheme and adds .jpg as extension >>> from PySide6 import QtCore >>> >>> class MyImageProtocolHandler(mari.ImageProtocolHandler): >>> def load(self, location): >>> return QtCore.QUrl(location).toString(QtCore.QUrl.RemoveScheme) + ".jpg" >>> >>> my_protocol_handler = MyImageProtocolHandler() >>> mari.images.registerProtocolHandler("myjpgprotocol", my_protocol_handler)
- load(Location)
The actual logic to handle translation of the given URL location to actual file path.
- Parameters:
Location (str) – the URL location passed for translation
- Returns:
str– the string representing the actual file path after translating the URL
- class mari.ImageSet
Bases:
SnapshotableA collection of one or more images or Ptex face textures to be manipulated as a group.
There are two types of image set: traditional UV image sets and
Pteximage sets.In the case of UV image sets, each UV patch on a model will have one associated image per image set. A 4 patch model will have 4 images in each image set.
In the case of
Pteximage sets, the image set serves as container for thePtexpixel data. ForPteximage sets, the concept of UV patches does not apply. Calling any patch-related methods on aPteximage set will result in exceptions being raised. Also note that anySnapshotablemethods aren’t currently supported onPteximage sets, although this may change in future.Imagesets can be manipulated as a whole, allowing the same operations to be performed on multiple images at once.One image set at a time is nominated as the “current” image set. This is the image set that the user will interact with when painting.
You can access image sets from a
Layer- for example:layer.imageSet()(forPaintableLayerobjects)Example Code
>>> # This example obtains the image of UDIM 1001 from the current layer of the current channel >>> import mari >>> layer = mari.geo.current().currentChannel().currentLayer() >>> if layer.isPaintableLayer(): ... image_set = layer.imageSet() ... image = image_set.image(0)
- SCALE_THE_IMAGE = 1
Scale the image to the size of the patch.
- Type:
int
- SCALE_THE_PATCH = 0
Scale the patch to the size of the image.
- Type:
int
- SIZE_1024 = 1024
.
- Type:
int
- SIZE_16384 = 16384
.
- Type:
int
- SIZE_2048 = 2048
.
- Type:
int
- SIZE_256 = 256
.
- Type:
int
- SIZE_32768 = 32768
.
- Type:
int
- SIZE_4096 = 4096
.
- Type:
int
- SIZE_512 = 512
.
- Type:
int
- SIZE_8192 = 8192
.
- Type:
int
- SIZE_DOUBLE = -2
.
- Type:
int
- SIZE_HALF = -1
.
- Type:
int
- SIZE_NULL = 0
.
- Type:
int
- class ScaleChoice
Bases:
objectSpecifies options for which item to scale when importing images.
- SCALE_THE_IMAGE = 1
Scale the image to the size of the patch.
- Type:
int
- SCALE_THE_PATCH = 0
Scale the patch to the size of the image.
- Type:
int
- class Size
Bases:
objectThese are the size options for image resizing.
- SIZE_1024 = 1024
.
- Type:
int
- SIZE_16384 = 16384
.
- Type:
int
- SIZE_2048 = 2048
.
- Type:
int
- SIZE_256 = 256
.
- Type:
int
- SIZE_32768 = 32768
.
- Type:
int
- SIZE_4096 = 4096
.
- Type:
int
- SIZE_512 = 512
.
- Type:
int
- SIZE_8192 = 8192
.
- Type:
int
- SIZE_DOUBLE = -2
.
- Type:
int
- SIZE_HALF = -1
.
- Type:
int
- SIZE_NULL = 0
.
- Type:
int
- addKeyFrame(FrameNumber)
Adds a key frame.
- Parameters:
FrameNumber (int) – The frame number of the new key frame
- Returns:
bool– True if the new key frame was successfully created or already exists, or false otherwise.
- static calculateNewSize(CurrentSize, NewSize)
Calculate the new size of an image.
- Parameters:
CurrentSize (QSize) – The current size of the image.
NewSize (Size) – The desired size for the image.
- Raises:
ValueError – Raised if the size provided was invalid.
- Returns:
QSize– The new size of the image.
- colorspaceConfig()
Returns the colorspace configuration of the image.
- Returns:
ColorspaceConfig– The colorspace configuration.
- convertColorspaceTo(OutputColorspace, InputColorspace='str', Config='str')
Converts this image set’s data to a new colorspace.
This only applies the colorspace transform and does not update the colorspace config of the image set.
- Parameters:
OutputColorspace (str) – Name of the colorspace or role in the OCIO config to convert this image set to.
InputColorspace (str, optional) – Optional name of the colorspace or role in the OCIO config to convert this image set from. If not specified then the native colorspace of the image set is used. Defaults to str.
Config (str, optional) – Optional name of a standard OCIO config file or the path to a custom one. If not specified then the OCIO config of the project is used. Defaults to str.
- Raises:
ValueError – Raised if an invalid colorspace or OCIO config is given.
- createSnapshot(Name, ID='str')
Creates a new snapshot of the object.
- Parameters:
Name (str) – A descriptive name for this snapshot. There is no restriction on naming convention, so it is recommended to make this clear, such as “new test version”.
ID (str, optional) – An optional identifier for this snapshot. This value can be used to group together sets of snapshots, as described in
Snapshot::setID(). Defaults to str.
- Raises:
NotImplementedError – Raised if the function is called on a Ptex image set.
- Returns:
Snapshot– The newly created snapshot.
- defaultKeyFrame()
Returns the default frames of animation for this image set.
- Returns:
int– The default animation frame
- deleteSnapshot(ShotToDelete)
Deletes the given snapshot.
- Parameters:
ShotToDelete (Snapshot) – The snapshot to delete
- Raises:
ValueError – The snapshot provided was invalid, or not owned by this object.
NotImplementedError – Raised if the function is called on a Ptex image set.
Warning
This method cannot be undone, so please use caution.
- exportImages(PathAndTemplate, Options='Image.DEFAULT_OPTIONS', FileOptions='variant')
Export the images of the image set to disk.
This internally calls the saveAs method of
Mari::Image, with the same arguments.>>> import mari >>> currentImageSet = mari.geo.current().currentChannel().currentLayer().imageSet() >>> currentImageSet.exportImages('/tmp/test.$UDIM.tif')
- Parameters:
PathAndTemplate (str) – The target path for the export and the template to export the files to. string.
Options (Image.SaveOptionsFlags, optional) – Pass in a value other than the default to turn on an option, such as disabling “small uniforms”. See
Image::SaveOptions. Defaults to Image.DEFAULT_OPTIONS.FileOptions (variant, optional) – This is a key/value map of optional parameters passed to the file writer plugin. Defaults to variant.
- Raises:
IOError – Raised if there is a problem saving the file.
TypeError – Raised if the options parameter is not a dict.
NotImplementedError – Raised if the function is called on a Ptex image set.
- findSnapshotWithID(ID)
Returns the snapshot with the given identifier, if found.
If more than one snapshot with the given identifier exists, the first one will be returned.
- Parameters:
ID (str) – The shot identifier to search for
- Raises:
NotImplementedError – Raised if the function is called on a Ptex image set.
- Returns:
Snapshot– The first snapshot with the given identifier, or NULL
- frameCount()
Returns the number of frames of animations for this image set.
Imagesets may be animated. Each image can have multiple frames associated with it.- Returns:
int– The number of frames of animation
- frames()
Returns the list of frames of animations for this image set.
Imagesets may be animated. Each image can have multiple frames associated with it.- Returns:
list of
int– The list of frames of animation
- getImportTemplate(Title='str', ImportAllText='str', ImportSelectedText='str', HideScaleOptions=False, HideAlphaOptions=False)
Return an existing set of file names or template as selected by the user.
- Parameters:
Title (str, optional) – Optional title of the dialog presented to the user. Defaults to str.
ImportAllText (str, optional) – Optional text for the “Import All Patches” button. Defaults to str.
ImportSelectedText (str, optional) – Optional text for the “Import Selected Patches” button. Defaults to str.
HideScaleOptions (bool, optional) – Whether the scaling options should be presented to the user. Defaults to False.
HideAlphaOptions (bool, optional) – Whether the alpha options should be presented to the user. Defaults to False.
- Returns:
variant– A dictionary containing the following user selected settings: “Path”: Directory location where the files are to be found. “Template”: String filename template containing “$UDIM”. “Images”: Dictionary of target Image objects to image file paths. “Scale”: The mari.ImageSet.ScaleChoice as to how the user wants the images to be scaled. “RemoveAlpha”: Boolean value as to whether the user has choosen to remove the alpha channel from the image files. “SelectedPatchesOnly”: Boolean value as to whether the user has choosen to import only to the selected patches.
- static getImportTemplateForEntity(TargetEntity, Title='str', ImportAllText='str', HideScaleOptions=False, HideAlphaOptions=False)
Return a template to an existing set of files as selected by the user.
- Parameters:
TargetEntity (GeoEntity) – Geo entity that the files or template are targeting to import into. This used to determine information such as UDIMs etc.
Title (str, optional) – Optional title of the dialog presented to the user. Defaults to str.
ImportAllText (str, optional) – Optional text for the “Import All Patches” button. Defaults to str.
HideScaleOptions (bool, optional) – Whether the scaling options should be presented to the user. Defaults to False.
HideAlphaOptions (bool, optional) – Whether the alpha options should be presented to the user. Defaults to False.
- Raises:
ValueError – Raised if the target geo entity provided was invalid.
- Returns:
variant– A dictionary containing the following user selected settings: “Path”: Directory location where the files are to be found. “Template”: String filename template containing “$UDIM”. “Scale”: The mari.ImageSet.ScaleChoice as to how the user wants the images to be scaled. “RemoveAlpha”: Boolean value as to whether the user has choosen to remove the alpha channel from the image files.
- image(UVIndex, Frame=-1)
Returns the image that corresponds to the given UV index.
- Parameters:
UVIndex (int) – The UV index of the image to return. You can get a list of the UV indices in use (for all image sets and patches) by calling
uvIndices().Frame (int, optional) – The frame to retrieve the image for. If left as the default, -1, it uses the default keyframe. Defaults to -1.
- Raises:
NotImplementedError – Raised if the function is called on a Ptex image set.
See also
frameCount(), uvIndices()
- imageCount()
Returns the number of images in this image set.
- Raises:
NotImplementedError – Raised if the function is called on a Ptex image set.
- Returns:
int– The number of images that make up this image set
- imageList(Frame=-1)
Returns the list of images for this image set.
As of version 1.4v3, these images are returned in UV index order - the same order as GeoEntity::patches(). Note however that these indices do not necessarily map directly to UDIMs, as some UDIMs may be unused, and there will not be any corresponding spaces left empty in the array. To be sure of the UDIM of a patch, you should instead either call the
GeoPatch::udim()function on the patch in the corresponding position in the results of GeoEntity::patches(), or iterate through the UV indices of the image set, where you can reliably add the constant 1001 to each of them to calculate the UDIM. For example:>>> import mari >>> layer = mari.geo.current().currentChannel().currentLayer() >>> result = True >>> if layer.isPaintableLayer(): ... image_set = layer.imageSet() ... for index in image_set.uvIndices(): ... result = result and image_set.image(index).saveAs("/tmp/"+str(index + 1001) + '.tif')
Alternatively, you can retrieve a list of all images in an array where the indices match the UV indices (and so can be easily converted to UDIMs) using the function
uvImageList().- Parameters:
Frame (int, optional) – The frame number to return. If left as the default, -1, the current frame is used. Defaults to -1.
- Raises:
NotImplementedError – Raised if the function is called on a Ptex image set.
- Returns:
list of
Image– A list of the images in this image set
Note
In versions older than 1.4v3, this function does not necessarily return the images in any particular order, or in the same order as GeoEntity::patches().
See also
uvImageList()
- importImages(ImagePaths, ScaleOption, UVIndexList, RemoveAlpha=False, SourceColorConfig='nullptr')
Imports a set of texture files into the images in the image set.
The file names to import and the images to import them into can be specified in two ways.
To specify a template for the file paths to import from:
>>> import mari >>> layer = mari.geo.current().currentChannel().currentLayer() >>> if layer.isPaintableLayer(): ... image_set = layer.imageSet() ... # To export all images: ... image_set.importImages('/tmp/filename.$UDIM.tif', image_set.SCALE_THE_IMAGE) ... # To export images for UV indices 2 and 3: (UDIMs 1003 and 1004) ... image_set.importImages('/tmp/filename.$UDIM.tif', image_set.SCALE_THE_IMAGE, [2, 3])
To specify the items as a sequence of sequences that each contain an
Imageobject and a source path: (both lists and tuples will work)>>> image_set.importImages([[image_set.image(0), '/tmp/img0.tif'], [image_set.image(1), '/tmp/img1.tif']], ... image_set.SCALE_THE_IMAGE)
- Parameters:
ImagePaths (variant) – Specifies the images and file names to import. This parameter can be either a string template containing “$UDIM”, or a list of two-element sequences containing an
Imageobject and a path. See above for examples.ScaleOption (ScaleChoice) – When the existing patch and the image in the file to import are of different sizes, this indicates which of the two to rescale to match the other
UVIndexList (list of
int) – This parameter can only be used when passing in a string template for the ImagePaths argument. Pass in a list of zero-based UV indices if desired to specify the patches to export images for. If not specified or empty, images will be exported for all indices. The UDIM for a patch is the zero-based UV index plus 1001.RemoveAlpha (bool, optional) – Remove the alpha channel (convert RGBA to RGB). Defaults to False.
SourceColorConfig (ColorspaceConfig, optional) – The colorspace configuration of the images being imported. Defaults to nullptr.
- Raises:
NotImplementedError – Raised if the function is called on a Ptex image set.
ValueError – Raised if no image paths were supplied; if the scale option was invalid; if an invalid UV index was specified; if a non-empty UV index list parameter was supplied, but the image paths parameter was not a string; or if the colorspace configuration is not valid.
- importImagesFromDict(ImagePaths, ScaleOption, RemoveAlpha=False, SourceColorConfig='nullptr')
Imports a map of texture files into the images in the image set.
The file names to import are specified as a dictionary of target
Imageobjects to image file paths.>>> image_set.importImages({image_set.image(0): '/tmp/img0.tif', image_set.image(1): '/tmp/img1.tif'}, ... image_set.SCALE_THE_IMAGE)
- Parameters:
ImagePaths (dict<Image,str>) – Specifies the
Imageobjects and file names to import in a dictionary. See the example above.ScaleOption (ScaleChoice) – When the existing patch and the image in the file to import are of different sizes, this indicates which of the two to rescale to match the other
RemoveAlpha (bool, optional) – Remove the alpha channel (convert RGBA to RGB). Defaults to False.
SourceColorConfig (ColorspaceConfig, optional) – The colorspace configuration of the images being imported. Defaults to nullptr.
- Raises:
NotImplementedError – Raised if the function is called on a Ptex image set.
ValueError – Raised if no image paths were supplied; if the scale option was invalid; if an invalid UV index was specified; if a non-empty UV index list parameter was supplied, but the image paths parameter was not a string; or if the colorspace configuration is not valid.
- isAnimated()
Indicates whether the image set has an animation.
- Returns:
bool– True if this image set has animation - i.e. more than one frame of image data
- isPtex()
Indicates whether this image set is a Ptex image set.
- Returns:
bool– True if this image set uses per-face Ptex mapping, or false otherwise
- name()
Returns the name of the image set.
See also
setName()
- nameChanged(NewName)
This is emitted after the image set has been renamed.
- Parameters:
NewName (str) – The new name of the image set
- removeKeyFrame(FrameNumber)
Removes a key frame.
- Parameters:
FrameNumber (int)
- Returns:
bool– True if the new key frame was successfully removed or false otherwise.
- resize(NewSize, UVIndexList)
Resize a set of images in the image set.
- Parameters:
NewSize (ImageSet.Size) – The desired size for the image.
UVIndexList (list of
int) – Pass in a list of zero-based UV indices if desired to specify which patches to resize the images of. If not specified or empty, all patches will be resized. The UDIM for a patch is the zero-based UV index plus 1001.
- Raises:
ValueError – Raised if the size provided was invalid, or if an invalid UV index was specified.
NotImplementedError – Raised if the function is called on a Ptex image set.
- revertToSnapshot(OldSnapshot)
Reverts the state of the object to that in the given snapshot.
- Parameters:
OldSnapshot (Snapshot) – A valid snapshot of this object
- Raises:
ValueError – The snapshot provided was invalid, or not owned by this object.
NotImplementedError – Raised if the function is called on a Ptex image set.
- setColorspaceConfig(Config)
Sets the colorspace configuration of the image.
- Parameters:
Config (ColorspaceConfig) – The colorspace configuration.
- Raises:
ValueError – Raised if the colorspace configuration is invalid.
- setName(NewName)
Sets a new name for the image set.
- Parameters:
NewName (str) – The new name for the image set
- Raises:
ValueError – Raised if an image set with the given name already exists on the object.
See also
name()
- static sizeFromQSize(Size)
Converts a QSize to its corresponding Size type.
- Parameters:
Size (QSize) – The size to convert.
- Raises:
ValueError – Raised if the size provided was invalid.
- Returns:
Size– The converted size, of type Size.
- snapshotList()
Returns a list of the snapshots available on the object.
- Raises:
NotImplementedError – Raised if the function is called on a Ptex image set.
- Returns:
list of
Snapshot– A list of the available snapshots
- supportedWriteFormats()
Returns a string list of all image formats that the image set can be written as.
This function returns a list of unique lower case strings in ascending alphabetic order.
See also
Mari::ImageManager::supportedWriteFormats()
- uvImageList(Frame=-1)
Returns a list of the images for this image set, in UV coordinate order.
This will include some entries with the value NULL if any UDIM is not used by the model. The advantage of this over the
imageList()function is that the index of each image in the return value can be converted to a UDIM by simply adding the constant 1001.For example:
>>> import mari >>> layer = mari.geo.current().currentChannel().currentLayer() >>> result = True >>> if layer.isPaintableLayer(): ... image_set = layer.imageSet() ... for index, image in enumerate(image_set.uvImageList()): ... result = result and image.saveAs('/tmp/{0}.tif'.format(index + 1001))
- Parameters:
Frame (int, optional)
- Raises:
NotImplementedError – Raised if the function is called on a Ptex image set.
- Returns:
list of
Image– A list of the images for the image set, with one entry per UV patch position (or UDIM)
See also
imageList()
- uvIndex(UvImage)
Return the UV Index for the given image if it belongs to this image set.
- Parameters:
UvImage (Image) – The image to find the UV index for
- Returns:
int– The UV index of the given image if it belongs to this image set, -1 otherwise
- uvIndices()
Returns a list of all of the UV indices used by the image set.
The UV indices are integers, but not necessarily consecutive.
- Raises:
NotImplementedError – Raised if the function is called on a Ptex image set.
- class mari.IndexRangeList(RangeString='str')
Bases:
objectClass to contain a list of general index ranges.
It can contain a list of index ranges or single indices separated by a space. Example:
"1-5 13 10-7"- __init__(RangeString='str')
Initialize the class using the range from the given string.
The string can contain a list of UDIM ranges or single UDIMs separated by a space. Example:
"1001-1005 1013 1010-1007"- Parameters:
RangeString (str, optional) – The range as a string. Defaults to str.
- fromString(RangeString)
Sets the range from a given string.
The string can contain a list of index ranges or single indices separated by a space. Example:
"1-5 13 10-7"- Parameters:
RangeString (str) – The range as a string
- Returns:
bool– Whether the range was set correctly.
- indexList()
Returns the list of indices as a list of integers.
- Returns:
list of
int– the list of indices as a list of integers
- toString()
Returns a string representation of the range.
- Returns:
str– The range as a string.
- class mari.IndexRangeListWidget(Parent=None)
Bases:
WidgetBaseA index range list widget.
Provides a custom index range list edit widget, which accepts
IndexRangeListobjects. Example Code>>> # This example creates a new IndexRangeList object, add it to a QWidget and show it >>> import mari >>> from PySide6 import QtWidgets >>> >>> widget = mari.IndexRangeListWidget() >>> container = QtWidgets.QWidget() >>> container.setLayout(QtWidgets.QHBoxLayout()) >>> widget.addToLayout(container.layout()) >>> container.show()
- __init__(Parent=None)
Sets to the int slider specified by the given components.
- Parameters:
Parent (QWidget, optional)
- lostFocus()
This is emitted when the line edit loses focus.
- movedMouse(YPosition)
This is emitted when the mouse is dragged from the line edit.
- Parameters:
YPosition (int) – The relative y position of the cursor.
- setExtraControlsDisplayed(Display)
Sets whether to display the extra controls (Reset button and the Range editing menus)
- Parameters:
Display (bool) – whether to display the extra controls (Reset button and the Range editing menus)
- setGeoEntity(GeoEntityObject)
Sets the connection to the given GeoEntity for restricting the range list.
- Parameters:
GeoEntityObject (GeoEntity) – The
GeoEntityobject to connect thisIndexRangeListWidgetto.
- setUdimMode(UdimMode)
Sets this IndexRangeListWidget to display the IndexRangeList in the UDIM mode.
- Parameters:
UdimMode (bool) – Whether this
IndexRangeListWidgetdisplays theIndexRangeListin the UDIM mode.
- setValue(Value)
Sets the value of the IndexRangeListWidget.
- Parameters:
Value (IndexRangeList) – The
IndexRangeListobject to set to.
- udimMode()
Returns whether this IndexRangeListWidget displays the IndexRangeList in the UDIM mode.
- Returns:
bool– Whether the widget displays the IndexRangeList in the UDIM mode.
- value()
Returns the value of the IndexRangeListWidget.
- Returns:
IndexRangeList– The IndexRangeListWidget object the IndexRangeListWidget contains.
- class mari.IntSlider(Parent=None)
Bases:
SliderBaseAn integer slider widget.
Provides a custom integer slider widget.
Example Code
>>> # This example creates a new FloatSlider object, add it to a QWidget and show it >>> import mari >>> from PySide6 import QtWidgets >>> >>> int_slider = mari.IntSlider() >>> container = QtWidgets.QWidget() >>> container.setLayout(QtWidgets.QHBoxLayout()) >>> int_slider.addToLayout(container.layout()) >>> container.show()
- __init__(Parent=None)
Sets to the int slider specified by the given components.
- Parameters:
Parent (QWidget, optional)
- setValue(Value)
Sets the value of the slider.
- Parameters:
Value (int) – The value to set the slider to.
- value()
Returns the value of the slider.
- Returns:
int– The value of the slider.
- valueChanged(Value)
This is emitted when the value of the slider changes.
- Parameters:
Value (int) – The value the slider has changed to.
- class mari.Layer
Bases:
MetadataA layer in a Channel is an image data operation that can be stacked on top of another layer.
Layers may contain their own image data, such as
PaintableLayer, which can be blended with other layers in a layer stack. Other layer types, such asAdjustmentLayer, can specify operations to be performed on the image data from the layers below them in the stack, or in the case ofProceduralLayer, can contain operations that generate new image data from a set of parameters.Each layer can also contain a mask, either as an image set or a separate layer stack. Most can also contain an adjustment stack, which specifies adjustment operations to be performed only on that layer; see
AdjustableLayerfor details.You can access all types of layers from their containing
Channelobjects - for example:channel.layerList()Example Code
>>> # This example finds all layers in the current channel >>> import mari >>> layers = mari.geo.current().currentChannel().layerList()
- ADD = 2
.
- Type:
int
- ADD_NORMAL_MAPS = 33
.
- Type:
int
- ADVANCED_BLEND = 1
Enable Advanced blending.
- Type:
int
- class AdvancedBlendComponent
Bases:
objectWhen using the ADVANCED blending type Mari can use different color components (R,G,B,Greyscale) etc in conjunction with the lookup tables to pull masks from the input layers.
- BLUE_BLEND = 3
Use B as the input to the lookup table.
- Type:
int
- GREEN_BLEND = 2
Use G as the input to the lookup table.
- Type:
int
- GREYSCALE_BLEND = 0
Use SUM(R/3, G/3, B/3) as the input to the lookup table, this is the default.
- Type:
int
- LUMINANCE_BLEND = 4
Use SUM(0.2126*R, 0.7152*G ,0.0722*B) as the input to the lookup table.
- Type:
int
- RED_BLEND = 1
Use R as the input to the lookup table.
- Type:
int
- BASIC_BLEND = 0
Basic blending using only the opacity value.
- Type:
int
- BLUE_BLEND = 3
Use B as the input to the lookup table.
- Type:
int
- BURN_HIGHLIGHTS = 3
.
- Type:
int
- BURN_MIDRANGE = 4
.
- Type:
int
- BURN_SHADOWS = 5
.
- Type:
int
- class BlendMode
Bases:
object- ADD = 2
.
- Type:
int
- ADD_NORMAL_MAPS = 33
.
- Type:
int
- BURN_HIGHLIGHTS = 3
.
- Type:
int
- BURN_MIDRANGE = 4
.
- Type:
int
- BURN_SHADOWS = 5
.
- Type:
int
- CLEAR = 6
.
- Type:
int
- COLOR = 9
.
- Type:
int
- COLOR_BURN = 7
.
- Type:
int
- COLOR_DODGE = 8
.
- Type:
int
- CONTRAST = 36
.
- Type:
int
- COPY = 31
.
- Type:
int
- COPY_RGB = 35
.
- Type:
int
- CUSTOM = 100
.
- Type:
int
- DARKEN = 10
.
- Type:
int
- DECONTRAST = 37
.
- Type:
int
- DIFFERENCE = 11
.
- Type:
int
- DIVIDE = 44
.
- Type:
int
- DODGE_HIGHLIGHTS = 12
.
- Type:
int
- DODGE_MIDRANGE = 13
.
- Type:
int
- DODGE_SHADOWS = 14
.
- Type:
int
- EXCLUSION = 15
.
- Type:
int
- HARD_LIGHT = 16
.
- Type:
int
- HARD_MIX = 17
.
- Type:
int
- HUE = 18
.
- Type:
int
- INVERSE_DIFFERENCE = 19
.
- Type:
int
- INVERT = 20
.
- Type:
int
- LIGHTEN = 21
.
- Type:
int
- LUMINANCE = 22
.
- Type:
int
- MIX = 1
.
- Type:
int
- MIX_NORMAL_MAPS = 32
.
- Type:
int
- MULTIPLY = 23
.
- Type:
int
- NUDGE_FLOW_VECTORS = 39
.
- Type:
int
- NUDGE_NORMAL_VECTORS = 41
.
- Type:
int
- OVERLAY = 24
.
- Type:
int
- PAINT_FLOW_VECTORS = 38
.
- Type:
int
- PAINT_NORMAL_VECTORS = 40
.
- Type:
int
- PIN_LIGHT = 25
.
- Type:
int
- REORIENTED_NORMAL_MAPPING = 34
.
- Type:
int
- SATURATION = 26
.
- Type:
int
- SCALE_VECTORS = 42
.
- Type:
int
- SCREEN = 27
.
- Type:
int
- SOFT_LIGHT = 28
.
- Type:
int
- SPONGE_DESATURATE = 29
.
- Type:
int
- SUBTRACT = 43
.
- Type:
int
- VIVID_LIGHT = 30
.
- Type:
int
- class BlendType
Bases:
object- ADVANCED_BLEND = 1
Enable Advanced blending.
- Type:
int
- BASIC_BLEND = 0
Basic blending using only the opacity value.
- Type:
int
- CLEAR = 6
.
- Type:
int
- COLOR = 9
.
- Type:
int
- COLOR_BURN = 7
.
- Type:
int
- COLOR_DODGE = 8
.
- Type:
int
- CONTRAST = 36
.
- Type:
int
- COPY = 31
.
- Type:
int
- COPY_RGB = 35
.
- Type:
int
- CUSTOM = 100
.
- Type:
int
- DARKEN = 10
.
- Type:
int
- DECONTRAST = 37
.
- Type:
int
- DIFFERENCE = 11
.
- Type:
int
- DIVIDE = 44
.
- Type:
int
- DODGE_HIGHLIGHTS = 12
.
- Type:
int
- DODGE_MIDRANGE = 13
.
- Type:
int
- DODGE_SHADOWS = 14
.
- Type:
int
- EXCLUSION = 15
.
- Type:
int
- FROM_ALPHA = 2
A mask, created from the alpha channel.
- Type:
int
- FROM_SELECTION_GROUP = 3
A mask created from a selection group.
- Type:
int
- GREEN_BLEND = 2
Use G as the input to the lookup table.
- Type:
int
- GREYSCALE_BLEND = 0
Use SUM(R/3, G/3, B/3) as the input to the lookup table, this is the default.
- Type:
int
- HARD_LIGHT = 16
.
- Type:
int
- HARD_MIX = 17
.
- Type:
int
- HIDE_ALL = 1
A mask to hide all.
- Type:
int
- HUE = 18
.
- Type:
int
- INVERSE_DIFFERENCE = 19
.
- Type:
int
- INVERT = 20
.
- Type:
int
- LIGHTEN = 21
.
- Type:
int
- LUMINANCE = 22
.
- Type:
int
- LUMINANCE_BLEND = 4
Use SUM(0.2126*R, 0.7152*G ,0.0722*B) as the input to the lookup table.
- Type:
int
- MIX = 1
.
- Type:
int
- MIX_NORMAL_MAPS = 32
.
- Type:
int
- MULTIPLY = 23
.
- Type:
int
- class MaskType
Bases:
objectSpecify the type of mask we can add on a layer.
- FROM_ALPHA = 2
A mask, created from the alpha channel.
- Type:
int
- FROM_SELECTION_GROUP = 3
A mask created from a selection group.
- Type:
int
- HIDE_ALL = 1
A mask to hide all.
- Type:
int
- REVEAL_ALL = 0
A mask to reveal all, this is the default.
- Type:
int
- NUDGE_FLOW_VECTORS = 39
.
- Type:
int
- NUDGE_NORMAL_VECTORS = 41
.
- Type:
int
- OVERLAY = 24
.
- Type:
int
- PAINT_FLOW_VECTORS = 38
.
- Type:
int
- PAINT_NORMAL_VECTORS = 40
.
- Type:
int
- PIN_LIGHT = 25
.
- Type:
int
- RED_BLEND = 1
Use R as the input to the lookup table.
- Type:
int
- REORIENTED_NORMAL_MAPPING = 34
.
- Type:
int
- REVEAL_ALL = 0
A mask to reveal all, this is the default.
- Type:
int
- SATURATION = 26
.
- Type:
int
- SCALE_VECTORS = 42
.
- Type:
int
- SCREEN = 27
.
- Type:
int
- SOFT_LIGHT = 28
.
- Type:
int
- SPONGE_DESATURATE = 29
.
- Type:
int
- SUBTRACT = 43
.
- Type:
int
- SWIZZLE_DST_ALPHA = 3
.
- Type:
int
- SWIZZLE_DST_BLUE = 2
.
- Type:
int
- SWIZZLE_DST_GREEN = 1
.
- Type:
int
- SWIZZLE_DST_RED = 0
.
- Type:
int
- SWIZZLE_SRC_ALPHA = 3
.
- Type:
int
- SWIZZLE_SRC_BLUE = 2
.
- Type:
int
- SWIZZLE_SRC_GREEN = 1
.
- Type:
int
- SWIZZLE_SRC_ONE = 4
.
- Type:
int
- SWIZZLE_SRC_RED = 0
.
- Type:
int
- SWIZZLE_SRC_ZERO = 5
.
- Type:
int
- class SwizzleDestination
Bases:
objectSpecify the layer’s color component to swizzle.
- SWIZZLE_DST_ALPHA = 3
.
- Type:
int
- SWIZZLE_DST_BLUE = 2
.
- Type:
int
- SWIZZLE_DST_GREEN = 1
.
- Type:
int
- SWIZZLE_DST_RED = 0
.
- Type:
int
- class SwizzleSource
Bases:
objectSpecify the color compenet swizzle source.
- SWIZZLE_SRC_ALPHA = 3
.
- Type:
int
- SWIZZLE_SRC_BLUE = 2
.
- Type:
int
- SWIZZLE_SRC_GREEN = 1
.
- Type:
int
- SWIZZLE_SRC_ONE = 4
.
- Type:
int
- SWIZZLE_SRC_RED = 0
.
- Type:
int
- SWIZZLE_SRC_ZERO = 5
.
- Type:
int
- VIVID_LIGHT = 30
.
- Type:
int
- activeCacheUpToHereParents()
Returns the top most layer on each of the cache stacks being used that this layer is part of.
- Returns:
list of
Layer– The top most layer on each of the cache stacks being used that this layer is part of.
- static advancedBlendComponentName(Value)
Return the display name for a given advanced blend component value.
print(mari.current.layer().advancedBlendComponentName(mari.Layer.AdvancedBlendComponent.RED_BLEND))- Parameters:
Value (AdvancedBlendComponent) – The AdvancedBlendComponent value to query
- Returns:
str– A human readable version of the given advanced blend component value
- advancedBlendComponentStr()
Return the advanced blend component for this layer as a string.
print(mari.current.layer().advancedBlendComponentStr())- Returns:
str– The display value for the advanced blend component value for this layer
- blendAmount()
Get blend amount of the layer.
- Returns:
float– The blend amount of the layer
- blendAmountChanged(Amount)
Emitted when the blend amount of the layer changes.
- Parameters:
Amount (float) – The new value for the blend amount.
- blendAmountEnabled()
Get enabled state of the blend amount of the layer.
- Returns:
bool– The enabled state of the blend amount of the layer
- blendComponentChanged(Type)
Emitted when the advanvced blend component of the layer is changed.
def blendComponentChanged(a): print("new component is ",a) mari.utils.connect( mari.current.layer().blendComponentChanged, blendComponentChanged)
- Parameters:
Type (str) – The new blend component for this layer
- blendMode()
Returns the blend mode of the layer. Returns CUSTOM if the blend mode is a custom one.
- Returns:
BlendMode– The blend mode
- blendModeChanged(Mode)
Emitted when the blend mode of the layer changes.
def blendModeChanged(a): print("new mode is ",a) mari.utils.connect( mari.current.layer().blendModeChanged, blendModeChanged)
- Parameters:
Mode (str) – The pretty string name of the blend mode.
- static blendModeName(BlendModeValue)
Convert blend mode to a pretty string name.
- Parameters:
BlendModeValue (BlendMode) – The blend node value to find a string for
- Returns:
str– The pretty string name of the blend mode
- blendModePath()
Returns the path of the blend mode of the layer.
- Raises:
ValueError – Raised if the blend mode on the layer is not supported.
- Returns:
str– The hierarchical path of the blend mode
- blendModeStr()
Returns the pretty string name of the blend mode of the layer.
- Raises:
ValueError – Raised if the blend mode on the layer is not supported.
- Returns:
str– The pretty string name of the blend mode
- blendType()
Return the blend type for this layer.
print(mari.current.layer().blendType())- Returns:
BlendType– The BlendType enabled for this layer
- blendTypeChanged(Type)
Emitted when the blend type (Basic, Advanced) of the layer is changed.
def blendTypeChanged(a): print("new type is ",a) mari.utils.connect( mari.current.layer().blendTypeChanged, blendTypeChanged)
- Parameters:
Type (str) – The new blend type for this layer
- static blendTypeName(BlendTypeValue)
Convert blend type to a pretty string name.
print(mari.current.layer().blendTypeName(mari.Layer.BlendType.ADVANCED_BLEND))- Parameters:
BlendTypeValue (BlendType) – The blend node type to find a string for
- Returns:
str– The pretty string name of the blend type
- blendTypeStr()
Returns the pretty string name of the blend type of the layer.
print(mari.current.layer().blendTypeStr())- Raises:
ValueError – Raised if the blend type on the layer is not supported.
- Returns:
str– The pretty string name of the blend type
- cacheLayer()
Cache this layer.
- Raises:
RuntimeError – Raised if this layer cannot be cached.
- cacheStateChanged()
This is emitted if the cache status changes.
- cacheUpToHere()
Caches the layer stack up to this layer.
- Raises:
RuntimeError – Raised if the layer stack up to here cannot be cached.
- cacheUpToHereParents()
Returns the top most layer on each of the cache stacks, even if it is not in use, that this layer is part of.
- Returns:
list of
Layer– The top most layer on each of the cache stacks, even if it is not in use, that this layer is part of.
- close()
Removes and deletes the layer from its layer stack.
- colorTag()
Return the current color tag of this layer.
- Returns:
str– This returns the name of the color assigned to this layer. The name will be one of the valid names returned by colorTagNames() or “none” if no tag is assigned
- colorTagChanged(ColorName)
This is emitted when the color tag changes.
- Parameters:
ColorName (str) – The name of the new color tag.
- static colorTagNames()
Return the list of valid color tags.
Users may assign color tags to layers to help catagorize them. This method returns the list of valid color tags that can be assigned to layers. No other tag values will be accepted
- convertedToPaint(Success, ThisLayer)
This is emitted when the layer is converted to paintable.
- Parameters:
Success (bool) – The result of the signal.
ThisLayer (Layer) – This layer, for easy connection to other slots for updates.
- getAdvancedBlendComponent()
Get the advance blend type component. This defines how the mask is created using the input layer and the LUT.
print(mari.current.layer().getAdvancedBlendComponent( ))- Returns:
AdvancedBlendComponent– The current advanced blend component set on this layer
- getLayerBelowBlendLut()
Return the ‘Layer Below’ lookup table used when advanced blending is enabled.
LUT = mari.current.layer().getLayerBelowBlendLut()- Returns:
variant– A handle to the lookuptable
- getThisLayerBlendLut()
Return the ‘This layer’ lookup table used when advanced blending is enabled.
LUT = mari.current.layer().getThisLayerBlendLut()- Returns:
variant– A handle to the lookuptable
- groupStack()
Returns the group layer stack this group layer contains.
- Raises:
RuntimeError – Raised if the layer is not a group layer
- Returns:
LayerStack– Returns a layer stack
- hasCacheUpToHere()
Indicates whether the stack up to this layer has cache data, even if it is not in use.
- Returns:
bool– True if the stack up to this layer has cache data.
- hasLayerCache()
Indicates whether this layer has cache data, even if it is not in use.
- Returns:
bool– True if this layer has cache data.
- hasMask()
Indicates whether this layer has a paintable mask image set, custom procedural mask or mask stack.
- Returns:
bool– True is this layer has a paintable mask image set or mask stack
- hasMaskCustomProcedural()
Indicates whether this layer has a mask custom procedural.
- Returns:
bool– True if this layer has a mask custom procedural
- hasMaskStack()
Indicates whether this layer has a mask stack.
- Returns:
bool– True if this layer has a mask stack
- hash(UVIndex=-1)
Returns a unique identifier for this layer.
This hash is assumed to be universally unique (256bit skein hash). This can be used to determine if a layer or its children have changed since some given checkpoint. A different hash means a different layer or children. This hash is based on image data, blend mode, parameters and anything that might effect the pixel output. Use this to detect any changes to the layers.
- Parameters:
UVIndex (int, optional) – The UV index of the patch to return the hash of, or -1 to return the hash of all the patches. Defaults to -1.
- Returns:
str– A hash string that uniquely identifies this version of this layer and its children, or an empty string on failure.
See also
imageHash()
- imageHash(UVIndex=-1)
Returns a unique identifier for this layer’s image data.
This hash is assumed to be universally unique (256bit skein hash). This can be used to determine if a layer or its children have changed their image data since some given checkpoint. A different hash means a different layer or children. This hash is only based on image data and can be used to detect changes in the images.
- Parameters:
UVIndex (int, optional) – The UV index of the patch to return the hash of, or -1 to return the hash of all the patches. Defaults to -1.
- Returns:
str– A hash string that uniquely identifies this version of this layer and its children image data, or an empty string on failure.
See also
hash()
- isAdjustableLayer()
Indicates whether this is a channel layer.
- Returns:
bool– True if this layer is a channel layer or False if not.
- isAdjustmentLayer()
Indicates whether this is a adjustment layer.
- Returns:
bool– True if this layer is a adjustment layer or False if not.
- isBakePointLayer()
Indicates whether this is a bake point layer.
- Raises:
RuntimeError – Raised if the experimental bake point layer feature is not enabled.
- Returns:
bool– True if this layer is a bake point layer or False if not.
- isCachedUpToHere()
Indicates whether the stack up to this layer is cached and the cache is being used.
- Returns:
bool– True if the stack up to this layer is cached and is being used.
- isChannelLayer()
Indicates whether this is a channel layer.
- Returns:
bool– True if this layer is a channel layer or False if not.
- isChildOfActiveCacheUpToHere()
Indicates whether the layer is part of a cache stack that is being used.
- Returns:
bool– True if the layer is part of a cache stack that is being used.
- isChildOfCacheUpToHere()
Indicates whether the layer is part of a cache stack, even if it is not in use.
- Returns:
bool– True if the layer is part of a cache stack.
- isCustomProceduralLayer()
Indicates whether this is a custom procedural layer.
- Returns:
bool– True if this layer is a custom procedural layer or False if not.
- isGraphLayer()
Indicates whether this is a node graph layer.
- Returns:
bool– True if this layer is a node graph layer or False if not.
- isGroupLayer()
Indicates whether this is a group layer.
- Returns:
bool– True if this layer is a channel layer or False if not.
- isLayerCached()
Indicates whether this layer is cached and the cache is being used.
- Returns:
bool– True if this layer is cached and is being used.
- isLocked()
Indicates whether this layer is locked and, if so, unmodifiable.
- Returns:
bool– True if this layer is locked, or false if unlocked.
- isMaskEnabled()
Indicates if the mask is disabled.
- Returns:
bool– False is a mask is present and disabled.
- isModifiable()
Indicates whether this layer is allowed to be modified.
This is not the same as
isLocked(), if a parent layerisLocked()then this layer will not modifiable even though it is not locked.- Returns:
bool– True if the layer can be modified.
- isMultiChannelGroupLayer()
Indicates whether this is a multi-channel group layer.
- Returns:
bool– True if this layer is a multi-channel group layer or False if not.
- isMultiChannelMaterialLayer()
Indicates whether this is a multi-channel material layer.
- Returns:
bool– True if this layer is a multi-channel material layer or False if not.
- isPaintableLayer()
Indicates whether this is a paintable layer.
- Returns:
bool– True if this layer is a paintable layer or False if not.
- isProceduralLayer()
Indicates whether this is a procedural layer.
- Returns:
bool– True if this layer is a procedural layer or False if not.
- isSelected()
Indicates whether this layer is selected.
- Returns:
bool– True if the layer is selected, or false if not.
- isShaderLayer()
Indicates whether this is a shader layer.
- Returns:
bool– True if this layer is a shader layer or False if not.
Indicates whether this layer is shared.
- Returns:
bool– True if the layer is shared, or false if not.
- isVisible()
Indicates whether this layer is visible.
- Returns:
bool– True if the layer is visible, or false if not.
- layerNode()
Returns the node graph node that corresponds to this Layer.
Mari‘s layers are all build on top of node graph. A layer consists of a Merge node, its business node which provide the content of layer and, if existing, a mask. The primary node represending a layer is its Merge node which provides the blending logic. This function returns the Merge node.- Returns:
Node– the node graph Merge node that corresponds to this Layer
- lockedChanged(Locked)
This is emitted when the locked state changes.
- Parameters:
Locked (bool) – The new locked state.
- makeCurrent()
Sets this layer as the currently active layer on the currently active channel if it belongs to it and make this the current layer of the geo entity.
- makeMask(Mask='REVEAL_ALL', Group=None)
Creates a mask image set on the layer.
- Parameters:
Mask (MaskType, optional) – The mask type (Reveal all, hide all, from alpha and from selection group) to create a mask of. Defaults to REVEAL_ALL.
Group (SelectionGroup, optional) – In the case of creation a mask of type FROM_SELECTION_GROUP, we need the source selection group. Defaults to None.
- Raises:
RuntimeError – Raised if the layer mask image set cannot be create or already exists. Or the layer is not modifiable or the selection group is invalid.
- Returns:
ImageSet– Return an image set
- makeMaskCustomProcedural(FileName)
Creates a mask custom procedural from the given custom procedural path.
- Parameters:
FileName (str) – The absolute path, file name, and extension to create the custom procedural mask from.
- Raises:
RuntimeError – Raised if the layer mask custom procedural cannot be created, already exists, the layer is not modifiable or the selection group is invalid.
- makeMaskStack()
Creates a mask stack on the layer.
- Raises:
RuntimeError – Raised if the layer mask stack cannot be create or already exists or the layer is not modifiable.
- maskCreated(Mask)
This is emitted when a mask is created on a layer.
- Parameters:
Mask (Layer.MaskType) – The type of mask added (its type being MaskType).
- maskCustomProceduralNode()
Returns the mask custom procedural node that is applied to the mask of this layer.
- Raises:
RuntimeError – Raised if the layer has no mask or mask custom procedural.
- Returns:
CustomProceduralNode– Returns a CustomProceduralNode
- maskImageSet()
Returns the image set used by this layers mask.
- Raises:
RuntimeError – Raised if the layer mask image set cannot be found.
- Returns:
ImageSet– Return an image set
- maskRemoved()
This is emitted when a mask is removed on a layer.
- maskStack()
Returns the mask stack that is applied to the mask of this layer.
- Raises:
RuntimeError – Raised if the layer has no mask or mask stack.
- Returns:
LayerStack– Returns a layer stack
- maskStackCreated()
This is emitted when a mask stack is created.
- name()
Returns the name of the layer.
- Returns:
str– The name of this layer.
- nameChanged(NewName)
This is emitted after the channel has had its name changed.
- Parameters:
NewName (str) – The new name.
- parents()
Returns a list of all the layers and channels that use this layer.
- Returns:
list of
variant– A list of layers and channels that use this layer
- removeMask()
Remove the mask stack from the layer.
- Raises:
RuntimeError – Raised if the layer mask stack cannot be removed or does not exist or the layer is not modifiable.
- selectedChanged(Selected, ThisLayer)
This is emitted when the selection state changes.
- Parameters:
Selected (bool) – The new selected state.
ThisLayer (Layer) – The layer that changed for easy connection to other slots for updates.
- setAdvancedBlendComponent(Component)
Set the advance blend type component. This defines how the mask is created using the input layer and the LUT.
mari.current.layer().setAdvancedBlendComponent( mari.Layer.AdvancedBlendComponent.RED_BLEND )- Parameters:
Component (AdvancedBlendComponent) – The new component value
- Returns:
obj:`` : The current advanced blend component set on this layer
- setBlendAmount(BlendAmount)
Sets the blend amount of the layer.
- Parameters:
BlendAmount (float) – The new value for the blend amount. This must be in the range of 0.0 to 1.0.
- Raises:
ValueError – Raised if the blend amount was invalid.
- setBlendAmountEnabled(Enabled)
Enables or Disables the blend amount of the layer.
- Parameters:
Enabled (bool) – The new enabled state to set the blend amount to.
- setBlendMode(BlendModeValue)
Sets the blend mode of the layer.
- Parameters:
BlendModeValue (variant) – The new value for the blend mode. Must be of type mari.Layer.BlendMode
- Raises:
ValueError – Raised if the blend mode was invalid.
- setBlendType(Type)
Set the blend type for this layer.
mari.current.layer().setBlendType(mari.Layer.BlendType.ADVANCED_BLEND)- Parameters:
Type (BlendType) – The type of blending to enable for this layer
- setCachedUpToHere(Cache)
Sets the cached state up to this layer.
- Parameters:
Cache (bool) – Whether to cache up to this layer. True has the same effect as
cacheUpToHere()while False has the same effect asuncacheUpToHere().
- setColorTag(ColorTag)
Set the tag color for this layer.
This is a GUI only tag that allows users to catagorize layers by assigning a color tag.
- Parameters:
ColorTag (str) – The name of the color tag to assign. This should be one of the valid tags returned by
colorTagNames(). Pass “none” to clear any existing tag.- Raises:
ValueError – Raised, if Color is not a valid color tag name.
- setLayerBelowBlendLut(NewLut)
Set the “Layer Below” LUT to use when advanced blending.
LUT = mari.current.layer().getLayerBelowBlendLut() LUT.setLinear(0,1) mari.current.layer().setLayerBelowBlendLut(LUT)
- Parameters:
NewLut (LookUpTable) – A Handle to the new LUT to apply when advanced blending
- Raises:
ValueError – If NewLut is not a valid LUT
- setLayerCached(Cache)
Sets the layer cached state of this layer.
- Parameters:
Cache (bool) – Whether to cache this layer. True has the same effect as
cacheLayer()while False has the same effect asuncacheLayer().
- setLocked(Locked)
Locks or unlocks the layer, to optionally prevent modifications.
- Parameters:
Locked (bool) – True to lock the layer, or false to unlock it.
- setMaskEnabled(Enabled)
Set the enabled state of the layers mask.
- Parameters:
Enabled (bool) – The enabled state to set the mask to
- setMaskImageSet(Mask)
Sets a Image set as the layer’s mask.
- Parameters:
Mask (ImageSet)
- Raises:
RuntimeError – Raised if the layer already has a mask image or mask stack. Or the mask is not modifiable.
- setMaskStack(MaskStack)
Sets a LayerStack as the layer’s mask stack.
- Parameters:
MaskStack (LayerStack)
- Raises:
RuntimeError – Raised if the layer already has a mask image or mask stack. Or the layer is not modifiable.
- setName(NewName)
Sets the name of the layer.
- Parameters:
NewName (str) – The new name for the layer.
- setSelected(Selected)
Sets the selected status of the layer.
- Parameters:
Selected (bool) – True to select layer, or false to unselect it.
- setSwizzle(Dst, Src)
Set one of the layer’s color component sources.
- Parameters:
Dst (SwizzleDestination) – The component to change.
Src (SwizzleSource) – The source to takde the component from.
- setThisLayerBlendLut(NewLut)
Set the “This Layer” LUT to use when advanced blending.
LUT = mari.current.layer().getThisLayerBlendLut() LUT.setLinear(0,1) mari.current.layer().setThisLayerBlendLut(LUT)
- Parameters:
NewLut (LookUpTable) – A Handle to the new LUT to apply when advanced blending
- Raises:
ValueError – If NewLut is not a valid LUT
- setVisibility(Visible)
Shows or hides the layer.
- Parameters:
Visible (bool) – True to show the layer, or false to hide it.
Returns the list of layers that share the resources with this layer.
- Returns:
list of
Layer– The list of layers that share the resources with this layer
- swizzle(Dst)
Get the specified layer’s color components source.
- Parameters:
Dst (SwizzleDestination)
- uncacheLayer()
Deletes the cache of this layer.
- Raises:
RuntimeError – Raised if the cache for this layer cannot be deleted.
- uncacheUpToHere()
Deletes the cache of the layer stack up to this layer.
- Raises:
RuntimeError – Raised if the cache for layer stack up to here cannot be deleted
- class mari.LayerStack
Bases:
MetadataThis is the interface for creating, traversing and destroying layers on any part of the layer system that has layer stacks.
Obtain these using methods on the relevant interfaces that return
LayerStack. For example:layer.makeMaskStack()Example Code>>> # This example creates a mask stack and returns the mask stack >>> import mari >>> current_layer = mari.geo.current().currentChannel().currentLayer() >>> mask_stack = current_layer.makeMaskStack()
- CLEAR_ADJUSTMENT_STACKS = 2
Recursively unselects the sub-layers of any child adjustment stacks.
- Type:
int
- CLEAR_CURRENT_LAYER_SELECTION = 2
Deselect all layers presently selected in this stack.
- Type:
int
- CLEAR_GROUPS = 1
Recursively unselects the sub-layers of any child group layers.
- Type:
int
- CLEAR_MASK_STACKS = 4
Recursively unselects the sub-layers of any child mask stacks.
- Type:
int
- CREATE_NEW_LAYERS = 2
Always create new layers and do not update any existing ones.
- Type:
int
- class ClearSelectionFlag
Bases:
object- CLEAR_ADJUSTMENT_STACKS = 2
Recursively unselects the sub-layers of any child adjustment stacks.
- Type:
int
- CLEAR_GROUPS = 1
Recursively unselects the sub-layers of any child group layers.
- Type:
int
- CLEAR_MASK_STACKS = 4
Recursively unselects the sub-layers of any child mask stacks.
- Type:
int
- DEFAULT_CLEAR_SELECTION_FLAGS = 0
All other options are turned off.
- Type:
int
- DEFAULT_CLEAR_SELECTION_FLAGS = 0
All other options are turned off.
- Type:
int
- DEFAULT_LAYER_CREATE_FLAGS = 1
All other options are turned off.
- Type:
int
- INSERT_NEW_LAYER_ABOVE_SELECTION = 16
Inserts the newly created layer above the top-most selected layer in the stack.
- Type:
int
- INSERT_NEW_LAYER_BELOW_REF_LAYER = 32
Inserts the newly created layer below the given RefLayer in the stack.
- Type:
int
- class LayerCreateFlag
Bases:
object- CLEAR_CURRENT_LAYER_SELECTION = 2
Deselect all layers presently selected in this stack.
- Type:
int
- DEFAULT_LAYER_CREATE_FLAGS = 1
All other options are turned off.
- Type:
int
- INSERT_NEW_LAYER_ABOVE_SELECTION = 16
Inserts the newly created layer above the top-most selected layer in the stack.
- Type:
int
- INSERT_NEW_LAYER_BELOW_REF_LAYER = 32
Inserts the newly created layer below the given RefLayer in the stack.
- Type:
int
- MAKE_NEW_LAYER_CURRENT = 8
Set the newly created layer as the current layer.
- Type:
int
- SELECT_NEW_LAYERS = 4
Select the newly created layers.
- Type:
int
- class LayerImportOption
Bases:
objectThese options determine how to handle importing layers with names that match existing ones.
- CREATE_NEW_LAYERS = 2
Always create new layers and do not update any existing ones.
- Type:
int
- OPTION_NOT_SPECIFIED = 0
Use a default option.
- Type:
int
- SKIP_LAYERS = 3
Ignore any layers being imported that match existing layers.
- Type:
int
- UPDATE_LAYERS = 1
Update (overwrite) existing layers with new data from the imported files.
- Type:
int
- MAKE_NEW_LAYER_CURRENT = 8
Set the newly created layer as the current layer.
- Type:
int
- OPTION_NOT_SPECIFIED = 0
Use a default option.
- Type:
int
- SELECT_NEW_LAYERS = 4
Select the newly created layers.
- Type:
int
- SKIP_LAYERS = 3
Ignore any layers being imported that match existing layers.
- Type:
int
- UPDATE_LAYERS = 1
Update (overwrite) existing layers with new data from the imported files.
- Type:
int
- clearSelection(Flags='LayerStack.DEFAULT_CLEAR_SELECTION_FLAGS')
Deselects all currently selected layers in the hierarchy of the stack.
- Parameters:
Flags (int, optional) – Values of ClearSelectionFlag or’ed together. Defaults to LayerStack.DEFAULT_CLEAR_SELECTION_FLAGS.
- createAdjustmentLayer(LayerName, PrimaryAdjustmentKey, RefLayer='nullptr', Flags='LayerStack.DEFAULT_LAYER_CREATE_FLAGS')
Returns a new adjustment layer that has been created on layer stack.
- Parameters:
LayerName (str) – the name of the layer to create.
PrimaryAdjustmentKey (str) – The path key of the type of the primary adjustment to create.
RefLayer (Layer, optional) – The layer to create the new layer above. If None then the new layer is created at the top of the layer stack. Defaults to nullptr.
Flags (int, optional) – Optional layer creation flags. Values of LayerCreateFlag or’ed together. Defaults to LayerStack.DEFAULT_LAYER_CREATE_FLAGS.
- Raises:
ValueError – Raised if adjustment key parameter does not match any valid value. Or if the reference layer is not in this stack.
- Returns:
Layer– The newly created adjustment layer.
- createBakePointLayer(LayerName, RefLayer='nullptr', Flags='LayerStack.DEFAULT_LAYER_CREATE_FLAGS')
Returns a new bake point layer that has been created on layer stack.
- Parameters:
LayerName (str) – The name of the layer to create.
RefLayer (Layer, optional) – The layer to create the new layer above. If None then the new layer is created at the top of the layer stack. Defaults to nullptr.
Flags (int, optional) – Optional layer creation flags. Values of LayerCreateFlag or’ed together. Defaults to LayerStack.DEFAULT_LAYER_CREATE_FLAGS.
- Raises:
ValueError – Raised if the reference layer is not in this stack.
RuntimeError – Raised if the experimental bake point layer feature is not enabled.
- Returns:
Layer– The newly created bake point layer.
- createChannelLayer(LayerName, TargetChannel, RefLayer='nullptr', Flags='LayerStack.DEFAULT_LAYER_CREATE_FLAGS')
Returns a new channel layer that has been created on layer stack.
- Parameters:
LayerName (str) – the name of the layer to create.
TargetChannel (Channel) – The channel to use.
RefLayer (Layer, optional) – The layer to create the new layer above. If None then the new layer is created at the top of the layer stack. Defaults to nullptr.
Flags (int, optional) – Optional layer creation flags. Values of LayerCreateFlag or’ed together. Defaults to LayerStack.DEFAULT_LAYER_CREATE_FLAGS.
- Raises:
ValueError – Raised if channel parameter is not valid, or if the reference layer is not in this stack.
- Returns:
Layer– The newly-created channel layer.
- createCustomProceduralLayer(LayerName, FilePath, RefLayer='nullptr', Flags='LayerStack.DEFAULT_LAYER_CREATE_FLAGS')
Creates and returns a new custom procedural layer.
- Parameters:
LayerName (str) – The name of the layer to create.
FilePath (str) – The path to the custom procedural file to create a custom procedural layer from.
RefLayer (Layer, optional) – The layer to create the new layer above. If None then the new layer is created at the top of the layer stack. Defaults to nullptr.
Flags (int, optional) – Optional layer creation flags. Values of LayerCreateFlag or’ed together. Defaults to LayerStack.DEFAULT_LAYER_CREATE_FLAGS.
- Raises:
ValueError – Raised if the reference layer is not in this stack or if the layer cannot be created.
- Returns:
Layer– The newly created custom procedural layer.
- createGraphLayer(LayerName, RefLayer='nullptr', Flags='LayerStack.DEFAULT_LAYER_CREATE_FLAGS')
Returns a new graph layer that has been created on layer stack.
- Parameters:
LayerName (str) – The name of the layer to create.
RefLayer (Layer, optional) – The layer to create the new layer above. If None then the new layer is created at the top of the layer stack. Defaults to nullptr.
Flags (int, optional) – Optional layer creation flags. Values of LayerCreateFlag or’ed together. Defaults to LayerStack.DEFAULT_LAYER_CREATE_FLAGS.
- Raises:
ValueError – Raised if the reference layer is not in this stack.
- Returns:
Layer– The newly created graph layer.
- createGroupLayer(LayerName, RefLayer='nullptr', Flags='LayerStack.DEFAULT_LAYER_CREATE_FLAGS')
Returns a new group layer that has been created on layer stack.
- Parameters:
LayerName (str) – The name of the layer to create.
RefLayer (Layer, optional) – The layer to create the new layer above. If None then the new layer is created at the top of the layer stack. Defaults to nullptr.
Flags (int, optional) – Optional layer creation flags. Values of LayerCreateFlag or’ed together. Defaults to LayerStack.DEFAULT_LAYER_CREATE_FLAGS.
- Raises:
ValueError – Raised if the reference layer is not in this stack.
- Returns:
Layer– The newly created group layer.
- createMaterialLayer(LayerName, FilePath, RefLayer='nullptr', Flags='LayerStack.DEFAULT_LAYER_CREATE_FLAGS')
Creates and returns a new material layer.
- Parameters:
LayerName (str) – The name of the layer to create.
FilePath (str) – The path to the material file to create a material layer from.
RefLayer (Layer, optional) – The layer to create the new layer above. If None then the new layer is created at the top of the layer stack. Defaults to nullptr.
Flags (int, optional) – Optional layer creation flags. Values of LayerCreateFlag or’ed together. Defaults to LayerStack.DEFAULT_LAYER_CREATE_FLAGS.
- Raises:
ValueError – Raised if the reference layer is not in this stack or if the layer cannot be created.
- Returns:
Layer– The newly created material layer.
- createMultiChannelGroupLayer(LayerName, RefLayer='nullptr', Flags='LayerStack.DEFAULT_LAYER_CREATE_FLAGS')
Creates and returns a new multi-channel group layer.
- Parameters:
LayerName (str) – The name of the layer to create.
RefLayer (Layer, optional) – The layer to create the new layer above. If None then the new layer is created at the top of the layer stack. Defaults to nullptr.
Flags (int, optional) – Optional layer creation flags. Values of LayerCreateFlag or’ed together. Defaults to LayerStack.DEFAULT_LAYER_CREATE_FLAGS.
- Raises:
ValueError – Raised if the reference layer is not in this stack or if the layer cannot be created.
- Returns:
Layer– The newly created group layer.
- createPaintableLayer(LayerName, RefLayer='nullptr', FillColor='nullptr', Flags='LayerStack.DEFAULT_LAYER_CREATE_FLAGS')
Returns a new paintable layer that has been created on layer stack.
- Parameters:
LayerName (str) – The name of the layer to create.
RefLayer (Layer, optional) – The layer to create the new layer above. If None then the new layer is created at the top of the layer stack. Defaults to nullptr.
FillColor (Color, optional) – The color the layer is initially set to. Defaults to nullptr.
Flags (int, optional) – Optional layer creation flags. Values of LayerCreateFlag or’ed together. Defaults to LayerStack.DEFAULT_LAYER_CREATE_FLAGS.
- Raises:
ValueError – Raised if the reference layer is not in this stack.
- Returns:
Layer– The newly created paintable layer.
- createProceduralLayer(LayerName, ProceduralKey, RefLayer='nullptr', Flags='LayerStack.DEFAULT_LAYER_CREATE_FLAGS')
Returns a new procedural layer that has been created on layer stack.
To get a list of the available types of procedural layers to create, call
Channel.proceduralLayerTypeList().For example:
>>> import mari >>> channel = mari.geo.current().currentChannel() >>> procedural_layer_type_list = channel.proceduralLayerTypeList()
- Parameters:
LayerName (str) – The name of the layer to create.
ProceduralKey (str) – The path key of the type of the procedural to create
RefLayer (Layer, optional) – The layer to create the new layer above. If None then the new layer is created at the top of the layer stack. Defaults to nullptr.
Flags (int, optional) – Optional layer creation flags. Values of LayerCreateFlag or’ed together. Defaults to LayerStack.DEFAULT_LAYER_CREATE_FLAGS.
- Raises:
ValueError – Raised if procedural key parameter does not match any valid value. Or if the reference layer is not in this stack.
- Returns:
Layer– The newly created procedural layer.
- createShaderLayer(LayerName, TargetShader, RefLayer='nullptr', Flags='LayerStack.DEFAULT_LAYER_CREATE_FLAGS')
Returns a new shader layer that has been created on layer stack.
- Parameters:
LayerName (str) – the name of the layer to create.
TargetShader (Shader) – The shader to use.
RefLayer (Layer, optional) – The layer to create the new layer above. If None then the new layer is created at the top of the layer stack. Defaults to nullptr.
Flags (int, optional) – Optional layer creation flags. Values of LayerCreateFlag or’ed together. Defaults to LayerStack.DEFAULT_LAYER_CREATE_FLAGS.
- Raises:
ValueError – Raised if channel parameter is not valid, or if the reference layer is not in this stack.
- Returns:
Layer– The newly-created channel layer.
See also
mari.examples.shaderstacks.createShaderStacks(), GeoEntity::createShader(), GeoEntity::createStandaloneShader(), GeoEntity::createLayeredShader(), GeoEntity::createDiffuseSpecularShader()
- duplicateLayers(LayersToDuplicate, RefLayer='nullptr', Flags='LayerStack.DEFAULT_LAYER_CREATE_FLAGS')
Creates copies of the given layers within the layer stack.
- Parameters:
LayersToDuplicate (list of
Layer) – The list of layers to create copies of. If empty all currently selected layers will be used.RefLayer (Layer, optional) – The reference layer, above which the new layer is created. If None then the layers are added to the top of this stack. Defaults to nullptr.
Flags (int, optional) – Optional layer creation flags. Values of LayerCreateFlag or’ed together. Defaults to LayerStack.DEFAULT_LAYER_CREATE_FLAGS.
- Raises:
ValueError – Raised if the layers to duplicate or the reference layer are not in this stack.
- Returns:
list of
Layer– The newly created layer copies.
- exportImages(PathAndTemplate, UVIndexList, Options='Image.DEFAULT_OPTIONS', FileOptions='variant', OutputColorConfig='nullptr')
Exports a set of images from the layer stack.
This is the same as selecting “Export All Layers” from the GUI within the given layer stack. To export an individual layer, call
PaintableLayer::exportImages()orProceduralLayer::exportImages().Pass in the path and template to export the files to - for example:
>>> import mari >>> channel = mari.geo.current().currentChannel() >>> channel.exportImages('/tmp/$CHANNEL.$LAYER.$UDIM.tif')
Pass in the path and template to export the files to and two options - for example:
>>> import mari >>> channel = mari.geo.current().currentChannel() >>> channel.exportImages('/tmp/$CHANNEL.$LAYER.$UDIM.tif', 0, [], {'A' : 'B', 'C' : 'D'})
- Parameters:
PathAndTemplate (str) – The target path for the export and the template to export the files to, in a single string.
Options (Image.SaveOptionsFlags, optional) – Pass in a value other than the default to turn on an option, such as disabling “small uniforms”. See
Image::SaveOptions. Defaults to Image.DEFAULT_OPTIONS.UVIndexList (list of
int) – Pass in a list of zero-based UV indices if desired to specify the patches to export images for. If not specified or empty, images will be exported for all indices. The UDIM for a patch is the zero-based UV index plus 1001.FileOptions (variant, optional) – This is a key/value map of optional parameters passed to the file writer plugin. Defaults to variant.
OutputColorConfig (ColorspaceConfig, optional) – The output colorspace configuration, used during export. Defaults to nullptr.
- Raises:
ValueError – Raised if the path and template parameter was empty, or if an invalid UV index was specified, or if the colorspace configuration is not valid.
RuntimeError – Raised if the stack contains multiple layers, but the export was not to a layered format and the template did not contain $LAYER. This would otherwise write the same file multiple times.
IOError – Raised if an error occurred with the export process.
See also
importImages(), exportImagesFlattened(), PaintableLayer::exportImages(), ProceduralLayer::exportImages()
- exportImagesFlattened(PathAndTemplate, UVIndexList, Options='Image.DEFAULT_OPTIONS', FileOptions='variant', OutputColorConfig='nullptr')
Exports a set of images from the flattened contents of the layer stack.
This is the same as selecting “Export All Layers Flattened” from the GUI within the given layer stack. It bakes the contents of the layer stack into a single temporary image for each patch, and then exports those.
Pass in the path and template to export the files to - for example:
>>> import mari >>> channel = mari.geo.current().currentChannel() >>> channel.exportImagesFlattened('/tmp/$CHANNEL.$UDIM.tif')
Some file specific options can be passed via FileOptions - for example :
>>> import mari >>> channel = mari.geo.current().currentChannel() >>> channel.exportImagesFlattened('/tmp/$CHANNEL.$UDIM.exr',mari.Image.SaveOptions.DEFAULT_OPTIONS,[],{"compression":"zip"})
- For OpenEXR files, FileOptions uses the “compression” method as an option for selecting which compression type is used. The following values are accepted as OpenEXR “compression” options.
‘none’ : ‘none’
‘Zip (1 scanline)’ : ‘zips’
‘Zip (16 scanlines)’ : ‘zip’
‘PIZ Wavelet (32 scanlines)’ :’piz’
‘RLE’ : ‘rle’
‘B44’: ‘b44’
‘B44A’: ‘b44a’
‘DWAA’: ‘dwaa’
‘DWAB’: ‘dwab’
- For OpenEXR files, FileOptions uses “exr_type” key to specify the type of EXR file to export. The following values are accepted as OpenEXR “exr_type” options.
‘tiled’ : Default value.
Mariwill export EXR files in the tiled format. For UDIM textures, the tile size will be 256x256.‘renderman’ :
Mariwill export RenderMan compliant EXR files with tile size of 32x32 and mipmaps‘scanline’ :
Mariwill export EXR files in the scanline format.
Note that both the long and short names for the compression method are accepted. Either of the following lines will set the compression type to Zip (16 scanlines).
>>> channel.exportImagesFlattened('/tmp/$CHANNEL.$UDIM.exr',mari.Image.SaveOptions.DEFAULT_OPTIONS,[],{"compression":"zip"})>>> channel.exportImagesFlattened('/tmp/$CHANNEL.$UDIM.exr',mari.Image.SaveOptions.DEFAULT_OPTIONS,[],{"compression":"Zip (16 scanlines)"})This example shows how to export flattened a channel with an output colorspace
>>> import mari >>> nodeGraph = mari.geo.current().nodeGraph() >>> >>> OutputCS = mari.current.channel().colorspaceConfig() >>> OutputCS.setColorspace(OutputCS.COLORSPACE_STAGE_OUTPUT, "AlexaV3LogC") >>> >>> mari.geo.current().currentChannel().exportImagesFlattened('/tmp/$CHANNEL.$COLORSPACE.$UDIM.tif', mari.Image.SaveOptions.DEFAULT_OPTIONS, [], None, OutputCS)
- Parameters:
PathAndTemplate (str) – The target path for the export and the template to export the files to, in a single string.
Options (Image.SaveOptionsFlags, optional) – Pass in a value other than the default to turn on an option, such as disabling “small uniforms”. See
Image::SaveOptions. Defaults to Image.DEFAULT_OPTIONS.UVIndexList (list of
int) – Pass in a list of zero-based UV indices if desired to specify the patches to export images for. If not specified or empty, images will be exported for all indices. The UDIM for a patch is the zero-based UV index plus 1001.FileOptions (variant, optional) – This is a key/value map of optional parameters passed to the file writer plugin. Defaults to variant.
OutputColorConfig (ColorspaceConfig, optional) – The output colorspace configuration, used during export. Defaults to nullptr.
- Raises:
ValueError – Raised if the path and template parameter was empty, or if an invalid UV index was specified, or if the colorspace configuration is not valid.
IOError – Raised if an error occurred with the export process.
See also
importImages(), exportImages(), exportSelectedPatches(), exportSelectedPatchesFlattened()
- exportSelectedPatches(PathAndTemplate, Options='Image.DEFAULT_OPTIONS', FileOptions='variant', OutputColorConfig='nullptr')
Exports images from the selected patches.
This is the same as selecting “Export All Layers” from the GUI within the given layer stack. To export an individual layer, call
PaintableLayer::exportImages()orProceduralLayer::exportImages(). Images will only be exported for patches that are currently selected.Pass in the path and template to export the files to - for example:
>>> channel.exportSelectedPatches('/tmp/$CHANNEL.$LAYER.$UDIM.tif')- Parameters:
PathAndTemplate (str) – The target path for the export and the template to export the files to, in a single string.
Options (Image.SaveOptionsFlags, optional) – Pass in a value other than the default to turn on an option, such as disabling “small uniforms”. See
Image::SaveOptions. Defaults to Image.DEFAULT_OPTIONS.FileOptions (variant, optional) – This is a key/value map of optional parameters passed to the file writer plugin. Defaults to variant.
OutputColorConfig (ColorspaceConfig, optional) – The output colorspace configuration, used during export. Defaults to nullptr.
- Raises:
ValueError – Raised if the path and template parameter was empty, or if an invalid UV index was specified, or if the colorspace configuration is not valid.
RuntimeError – Raised if the stack contains multiple layers, but the export was not to a layered format and the template did not contain $LAYER. This would otherwise write the same file multiple times.
IOError – Raised if an error occurred with the export process.
See also
importImages(), exportImagesFlattened(), exportSelectedPatchesFlattened(), exportPaintableLayer::exportImages(), ProceduralLayer::exportImages()
- exportSelectedPatchesFlattened(PathAndTemplate, Options='Image.DEFAULT_OPTIONS', FileOptions='variant', OutputColorConfig='nullptr')
Exports the selected patches with the layer stack flattened.
This is the same as selecting “Export All Layers Flattened” from the GUI within the given layer stack. It bakes the contents of the layer stack into a single temporary image for each selected patch, and then exports those.
Pass in the path and template to export the files to - for example:
>>> channel.exportSelectedPatchesFlattened('/tmp/$CHANNEL.$UDIM.tif')- Parameters:
PathAndTemplate (str) – The target path for the export and the template to export the files to, in a single string.
Options (Image.SaveOptionsFlags, optional) – Pass in a value other than the default to turn on an option, such as disabling “small uniforms”. See
Image::SaveOptions. Defaults to Image.DEFAULT_OPTIONS.FileOptions (variant, optional) – This is a key/value map of optional parameters passed to the file writer plugin. Defaults to variant.
OutputColorConfig (ColorspaceConfig, optional) – The output colorspace configuration, used during export. Defaults to nullptr.
- Raises:
ValueError – Raised if the path and template parameter was empty, or if an invalid UV index was specified, or if the colorspace configuration is not valid.
IOError – Raised if an error occurred with the export process.
See also
importImages(), exportImages(),exportSelectedPatches()
- findLayer(LayerName)
Returns the layer with the given name.
- Parameters:
LayerName (str)
- Returns:
Layer– The requested layer. Return None is not found.
- groupLayers(LayersToGroup, RefLayer='nullptr', LayerName='str', Flags='LayerStack.DEFAULT_LAYER_CREATE_FLAGS')
Creates a new group layer on the layer stack and adds the given layers to it.
If an empty layer list is given then a new group layer won’t be created.
- Parameters:
LayersToGroup (list of
Layer) – The list of layers to add to the new group. If empty all currently selected layers will be used.RefLayer (Layer, optional) – The reference layer, above which the new layer is created. If None then the layer is added to the top of this stack. Defaults to nullptr.
LayerName (str, optional) – The name of the layer to create. If empty a unique name will be auto-generated for the layer. Defaults to str.
Flags (int, optional) – Optional layer creation flags. Values of LayerCreateFlag or’ed together. Defaults to LayerStack.DEFAULT_LAYER_CREATE_FLAGS.
- Raises:
ValueError – Raised if the layers to group or the reference layer are not in this stack.
- Returns:
Layer– The newly created group layer.
- hash(UVIndex=-1)
Returns a unique identifier for this layer stack.
This hash is assumed to be universally unique (256bit skein hash). This can be used to determine if a layer stack or its children have changedsince some given checkpoint. A different hash means a different layer or children. This hash is based on image data, blend mode, parameters and anything that might effect the pixel output. Use this to detect any changes to the layers.
- Parameters:
UVIndex (int, optional) – The UV index of the patch to return the hash of, or -1 to return the hash of all the patches. Defaults to -1.
- Returns:
str– A hash string that uniquely identifies this version of this layer stack and its childrens, or an empty string on failure.
See also
imageHash()
- imageHash(UVIndex=-1)
Returns a unique identifier for this layer stack’s image data.
This hash is assumed to be universally unique (256bit skein hash). This can be used to determine if a layer stack or its children have changed their image data since some given checkpoint. A different hash means a different layer or children. This hash is only based on image data and can be used to detect changes in the images.
- Parameters:
UVIndex (int, optional) – The UV index of the patch to return the hash of, or -1 to return the hash of all the patches. Defaults to -1.
- Returns:
str– A hash string that uniquely identifies this version of this layer stack and its childrens image data, or an empty string on failure.
See also
hash()
- importImages(PathAndTemplate, UVIndexList, ScaleOption='ImageSet.SCALE_THE_IMAGE', MatchingLayersOption='OPTION_NOT_SPECIFIED', MismatchingLayersOption='OPTION_NOT_SPECIFIED', RemoveAlpha=False, SourceColorConfig='nullptr')
Imports a set of images into the layer stack.
This is the same as selecting “Import into Layer Stack” from the GUI. To import into an individual layer, call
PaintableLayer::importImages().Pass in the path to the files and the template to import them from - for example:
>>> channel.importImages('/tmp/$CHANNEL.$UDIM.psd')- Parameters:
PathAndTemplate (str) – The path to the files and the template to import them from, in a single string.
ScaleOption (ImageSet.ScaleChoice, optional) – When the existing patch and the image in the file to import are of different sizes, this indicates which of the two to rescale to match the other. Defaults to ImageSet.SCALE_THE_IMAGE.
MatchingLayersOption (LayerImportOption, optional) – Determines what to do when the current layer stack and the layers being imported contain matching layer names, where the types of both layers match. This is the most common case. The default is to update the existing layers. Defaults to OPTION_NOT_SPECIFIED.
MismatchingLayersOption (LayerImportOption, optional) – Determines what to do when the current layer stack and the layers being imported contain matching layer names, where the types of the existing layers and those being imported do not match. This can happen when an exported file contains procedural layers baked as paintable, for example. The default is to skip the mismatching layers. Defaults to OPTION_NOT_SPECIFIED.
UVIndexList (list of
int) – Pass in a list of zero-based UV indices if desired to specify the patches to export images for. If not specified or empty, images will be exported for all indices. The UDIM for a patch is the zero-based UV index plus 1001.RemoveAlpha (bool, optional) – Remove the alpha channel (convert RGBA to RGB). Defaults to False.
SourceColorConfig (ColorspaceConfig, optional) – The colorspace configuration of the images being imported. Defaults to nullptr.
- Raises:
ValueError – Raised if the path and template parameter was empty, or if one or both of the matching and mismatching layers options was invalid, or if the colorspace configuration is not valid.
IOError – Raised if an error occurred with the import process.
See also
exportImages(), PaintableLayer::importImages()
- layer(LayerName)
Returns the layer with the given name.
- Parameters:
LayerName (str) – The name of the layer to retrieve
- Raises:
ValueError – Raised if the given layer name was not found on the object.
- Returns:
Layer– The requested layer.
- layerList()
Returns the list of layers that make up this objects layer stack.
- Returns:
list of
Layer– The list of layers for this object’s layer stack
- mergeLayers(LayersToMerge, RefLayer='nullptr', Flags='LayerStack.DEFAULT_LAYER_CREATE_FLAGS')
Merges the given layers within the layer stack into a single paintable layer.
- Parameters:
LayersToMerge (list of
Layer) – The list of layers to merge. If empty all currently selected layers will be used.RefLayer (Layer, optional) – The reference layer, above which the merge result is added. If None then the new layer is added to the top of this stack. Defaults to nullptr.
Flags (int, optional) – Optional layer creation flags. Values of LayerCreateFlag or’ed together. Defaults to LayerStack.DEFAULT_LAYER_CREATE_FLAGS.
- Raises:
ValueError – Raised if the layers to merge or the reference layer are not in this stack.
- Returns:
Layer– The newly created merged layer
- moveLayer(LayerToMove, RefLayer='nullptr')
Moves the layer from its current layer stack position to this stack and position.
- Parameters:
- Raises:
ValueError – Raised if the reference layer is not in this stack or the operation failed.
- moveLayerBelow(LayerToMove, RefLayer='nullptr')
Moves the layer from its current layer stack position to this stack and position.
- Parameters:
- Raises:
ValueError – Raised if the reference layer is not in this stack or the operation failed.
- name()
Returns the name of the object.
- Returns:
str– The name of this object
- removeLayers(LayersToRemove)
Removes the given layers within the layer stack.
- Parameters:
LayersToRemove (list of
Layer) – The list of layers to remove. If empty all currently selected layers will be used.- Raises:
ValueError – Raised if the layers to remove are not in this stack.
Shares the layer from its current layer stack position to this stack and position.
- Parameters:
LayerToShare (Layer) – The layer that is to be shared.
RefLayer (Layer, optional) – The reference layer to move the layer above. If None then the layer is moved to the top of this stack. Defaults to nullptr.
Flags (int, optional) – Optional layer creation flags. Values of LayerCreateFlag or’ed together. Defaults to LayerStack.DEFAULT_LAYER_CREATE_FLAGS.
- Raises:
ValueError – Raised if the layer to share is not valid or is of type multi-channel or if reference layer is not in this stack.
- Returns:
Layer– The newly-shared layer.
- static transferLayers(UVRemap, SourceLayers, SourceGeoVersion, DestinationLayerStack, DestinationGeoVersion, SourceUVIndices, DestinationUVIndices, DestinationSize='ImageSet.SIZE_None', BleedEdges=True, FillColor='nullptr')
Copies layers from one object to another.
The layers in the source list must belong to the same object. .. code-block:
>>> src_geo_entity = mari.geo.get('Head1') >>> src_geo_version = src_geo_entity.version("v4") >>> src_channel = src_geo_entity.channel('diffuse') >>> src_layer = src_channel.layer('color') >>> dst_geo_entity = mari.geo.get('Head2') >>> dst_geo_version = dst_geo_entity.version("v1") >>> dst_channel = dst_geo_entity.channel('diffuse') >>> mari.LayerStack.transferLayers("UVRemap_Head1v4_to_Head2v1_$UDIM.exr", [src_layer], src_geo_version, ... dst_channel, dst_geo_version)
- Parameters:
UVRemap (variant) – Either an existing image set or a filename template to a set of uv remapping textures.
SourceLayers (list of
Layer) – A list of source layers to read from.SourceGeoVersion (GeoEntityVersion) – The source geometry version to read from.
DestinationLayerStack (LayerStack) – The destination layer stack to write into.
DestinationGeoVersion (GeoEntityVersion) – The destination geometry version to write into.
DestinationSize (ImageSet.Size, optional) – Used to specified the image size for all uv indices in the destination channel. If a size is not given then the size will match the source. Defaults to ImageSet.SIZE_None.
BleedEdges (bool, optional) – Turns on or off “full texture bleed” (full patch texture bleed is generated). Defaults to True.
FillColor (Color, optional) – The color used to fill the newly created destination image sets with. Defaults to nullptr.
SourceUVIndices (list of
int) – Which patches in the source to read from. Passing in an empty list will cause all source patches to be read from.DestinationUVIndices (list of
int) – Which patches in the destination to write to. Passing in an empty list will cause all destination patches to be written to.
- Raises:
ValueError – Raised if no layers were supplied; if any of the layers are invalid; if the layers belong to different objects; if any of the patch indices was invalid; if no destination layer stack was supplied; if no source or destination geo version was supplied.
- Returns:
list of
Layer– A list of destination nodes if the transfer completed successfully, or an empty list otherwise.
- ungroupLayers(GroupLayersToUngroup)
Removes the group layers specified and inserts the deleted group’s layer stack in its place in the layer stack.
- Parameters:
GroupLayersToUngroup (list of
Layer) – The list of group layers to ungroup. If empty all currently selected layers will be used.- Raises:
ValueError – Raised if the layers to ungroup are not in this stack.
- class mari.Light
Bases:
MetadataAn object for creating lighting effects on a 3D mesh.
You can access lights through the
LightManager- for example:mari.lights.list()Example Code
>>> # This example shows hot to obtain all lights >>> import mari >>> lights = mari.lights.list()
- CAMERA = 1
Fixes the light to the camera.
- Type:
int
- class FixedTo
Bases:
objectThese values define what type of object the light should be fixed to.
- CAMERA = 1
Fixes the light to the camera.
- Type:
int
- SCENE = 0
Fixes the light to the scene, so it does not move with the camera.
- Type:
int
- SCENE = 0
Fixes the light to the scene, so it does not move with the camera.
- Type:
int
- isEnvironmentLight()
Indicates whether this is a environment light.
- Returns:
bool– True if this light is an environment light or False if not.
- isOn()
Indicates whether the light is on or off.
- Returns:
bool– True if the light is turned on, or false otherwise
- isPointLight()
Indicates whether this is a point light.
- Returns:
bool– True if this light is an point light or False if not.
- name()
Returns the name of the light.
- Returns:
str– The name of the light.
- onChanged(On)
Emitted when on changes.
- Parameters:
On (bool) – The new value
- setOn(OnOrOff)
Turns the light on or off.
- Parameters:
OnOrOff (bool) – Set to true to turn the light on, or false to turn it off
- class mari.LightManager
Bases:
objectManages the lights in the scene.
Example Code
>>> # This example shows how to obtain all lights >>> import mari >>> lights = mari.lights.list()
Alias
lights
- class mari.LineEdit(Parent=None, Value=0, Range=0)
Bases:
WidgetBaseA numeric slider widget.
Provides a custom line edit widget, which accepts integers (the default) or floating point values. Example Code
>>> # This example creates a new FloatSlider object, add it to a QWidget and show it >>> import mari >>> from PySide6 import QtWidgets >>> >>> line_edit = mari.LineEdit() >>> container = QtWidgets.QWidget() >>> container.setLayout(QtWidgets.QHBoxLayout()) >>> line_edit.addToLayout(container.layout()) >>> container.show()
- __init__(Parent=None, Value=0, Range=0)
Sets to the int slider specified by the given components.
- Parameters:
Parent (QWidget, optional)
Value (int, optional)
Range (int, optional)
- addFloatValidator(Minimum, Maximum, Precision)
Adds a validator to provided range checking of floating-point numbers.
- Parameters:
Minimum (float) – The minimum value accepted.
Maximum (float) – The maximum value accepted.
Precision (int) – The number of decimal places accepted.
- home(Mark)
Moves the text cursor to the beginning of the line unless it is already there.
- Parameters:
Mark (bool) – If true, text is selected towards the first position; otherwise, any selected text is unselected if the cursor is moved.
- isReadOnly()
Returns whether the line edit is read only.
- lostFocus()
This is emitted when the line edit loses focus.
- movedMouse(YPosition)
This is emitted when the mouse is dragged from the line edit.
- Parameters:
YPosition (int) – The relative y position of the cursor.
- setRange(Range)
Sets the range of the line edit.
- Parameters:
Range (int) – The range to set on the line edit.
- setReadOnly(ReadOnly)
Sets whether the line edit is read only.
- Parameters:
ReadOnly (bool)
- setText(Text)
Sets the text entered in the line edit.
- Parameters:
Text (str)
- setValue(Value)
Sets the value of the slider.
- Parameters:
Value (int) – The value to set the slider to.
- text()
Returns the entered text.
- class mari.LocatorEntity
Bases:
LockableThese are the locator object in the “Objects” Gui.
- addLocator()
Add a locator to this object.
- Returns:
LocatorEntity– The newly-created locator.
- hideLocator()
Hide the locator UI object.
- isSelected()
Indicates whether the object is currently selected.
- Returns:
bool– True if the object is selected, or false if not
- name()
Returns the name of the object.
- Returns:
str– The name of this object
- nameChanged(NewName)
This is emitted after the entity has been renamed.
- Parameters:
NewName (str) – The new name of the entity
- resetLocatorHandleTransform(Frame=0)
Resets the internal cache of locator’s transform information set by the 3D handle in the viewport.
- Parameters:
Frame (int, optional) – Frame. Defaults to 0.
- setName(NewName)
Changes the name of the object.
- Parameters:
NewName (str) – The new name of the object
- setSelected(Selected)
Changes the selection state of the object.
- Parameters:
Selected (bool) – True to select the object, or false to deselect it
Note
Exactly one object can be selected at a time. If only one object is available, it cannot be deselected.
- setTransform(pTransform, Frame=0)
Sets the transform of the geo entity for a frame.
- Parameters:
pTransform (Matrix) – Translation vector
Frame (int, optional) – Frame. Defaults to 0.
- Raises:
ValueError – Throws a value error if the input if not a valid matrix
- showLocator()
Show the locator UI object.
- class mari.LocatorList
Bases:
objectAn object for creating a locatorlist.
- LOCATOR_LIST_TYPE_MATRIX = 7
Matrix.
- Type:
int
- LOCATOR_LIST_TYPE_PROJECTOR = 8
Projection Matrix.
- Type:
int
- LOCATOR_LIST_TYPE_ROTATION = 2
Rotation.
- Type:
int
- LOCATOR_LIST_TYPE_SCALE = 1
Scale.
- Type:
int
- LOCATOR_LIST_TYPE_TRANSLATION = 4
Translation.
- Type:
int
- class LocatorListType
Bases:
objectThese are various types of locatorlist.
- LOCATOR_LIST_TYPE_MATRIX = 7
Matrix.
- Type:
int
- LOCATOR_LIST_TYPE_PROJECTOR = 8
Projection Matrix.
- Type:
int
- LOCATOR_LIST_TYPE_ROTATION = 2
Rotation.
- Type:
int
- LOCATOR_LIST_TYPE_SCALE = 1
Scale.
- Type:
int
- LOCATOR_LIST_TYPE_TRANSLATION = 4
Translation.
- Type:
int
- currentLocator()
Returns the locator object.
- Returns:
LocatorEntity– The locator object.
- locatorType()
Returns the type of the locator list.
- Returns:
LocatorListType– The type of the locator list
- setCurrentLocator(Locator)
Sets the locator object for the locator list.
- Parameters:
Locator (LocatorEntity) – The locator object.
- Raises:
ValueError – Raised if the LocatorType is PROJECTOR.
- setCurrentProjector(ProjectorEntity)
Sets the projector object for the locator list.
- Parameters:
ProjectorEntity (Projector) – The projector object.
- Raises:
ValueError – Raised if the LocatorType is not PROJECTOR.
- setLocatorType(Type)
Sets the type of the locator list.
- Parameters:
Type (LocatorListType) – The type to set the locator list to
- setRotationVector(Vector)
Sets the rotation angles.
- Parameters:
Vector (VectorN) – The rotation euler angles.
- setShowUI(Value)
Sets whether to show UI for the locator list.
- Parameters:
Value (bool) – Whether to show UI.
- setTranslationVector(Vector)
Sets the translation vector.
- Parameters:
Vector (VectorN) – The translation vector.
- setWorldSpace(Value)
Sets whether to generate world space transforms, rather than local space.
- Parameters:
Value (bool) – Whether to generatate world space transform.
- showUI()
Returns whether to show ui for the locator list.
- Returns:
bool– The show ui flag.
- worldSpace()
Returns whether to generate world space transforms, rather than local space.
- Returns:
bool– The whether to generatate world space transform toggle.
- class mari.Lockable
Bases:
MetadataProvides an interface to objects within Mari that are lockable and hidable.
This includes methods for settings and getting the visible and locked status and signals to indicate when these states are changed.
Example Code
>>> # This examples obtains the patch with UDIM 1001 of current geometry object, and locks it >>> import mari >>> patch_1001 = mari.geo.current().patch(0) >>> patch_1001.lock()
- hide()
Hides the object from view.
See also
isVisible(), setVisibility(), show()
- isLocked()
Indicates whether this object is locked, and if so, unmodifiable.
- Returns:
bool– True if this image is locked, or false if unlocked
See also
lock(), setLocked(), unlock()
- isVisible()
Indicates whether this object is visible.
- Returns:
bool– True if the object is visible, or false if not.
See also
hide(), setVisibility(), show()
- lock()
Locks the object to prevent modifications.
See also
isLocked(), setLocked(), unlock()
- lockedChanged(Locked)
This is emitted after the object is locked or unlocked.
- Parameters:
Locked (bool) – True if the object is now locked, or false otherwise
- setLocked(Locked)
Locks or unlocks the object, to optionally prevent modifications.
- Parameters:
Locked (bool)
See also
isLocked(), lock(), unlock()
- setVisibility(Visible)
Shows or hides the object.
- Parameters:
Visible (bool) – True to show the object, or false to hide it.
See also
hide(), isVisible(), show()
- show()
Shows the object again after a previous hide() operation.
See also
hide(), isVisible(), setVisibility()
- unlock()
Unlocks the object and allows modifications.
See also
isLocked(), lock(), setLocked()
- visibilityChanged(Visible)
This is emitted after the object is shown or hidden.
- Parameters:
Visible (bool) – True if this object is now visible, or false otherwise
- class mari.LookUpTable
Bases:
objectObjects of this class holds 1-dimensional look up table curve.
Curve is defined from a set of control points.
Objects of this class often appears as parameters of shaders and layers
Example Code
>>> # This example creates a "Brightness Lookup" layer and obtains its "Map" parameter, which is of LookUpTable type >>> import mari >>> layer = mari.geo.current().currentChannel().createAdjustmentLayer("Test", "Filter/Brightness Lookup") >>> lut = layer.getPrimaryAdjustmentParameter("Map")
- __init__()
Sets to the settings specified by the given components.
- controlPoints()
Returns the list of control points as a list of VectorN.
- Returns:
list of
VectorN– The list of control points as a list of VectorN
- controlPointsAsString()
Returns the string representation of the control points of the look up table.
- Returns:
str– The string representation of the contol points of the look up table
- invert()
Inverts the look up curve.
- isClamped()
Returns whether values outside of [0,1] are clamped.
- Returns:
bool– Whether values outside of [0,1] are clamped
- setClamped(Clamped)
Sets whether values outside of [0,1] are clamped.
- Parameters:
Clamped (bool) – If true, values outside of [0,1] are clamped
- setControlPoints(ControlPoints)
Sets the control points from a given list of VectorN.
- setControlPointsFromString(ControlPointsString)
Sets the control points from given string representation of look up table.
- Parameters:
ControlPointsString (str) – The string reprentation of control points to set
- setLinear(ValueAtZero, ValueAtOne)
Sets the look up table curve to a linear curve.
- Parameters:
ValueAtZero (float) – The value to map zero to
ValueAtOne (float) – The value to map one to
- class mari.MaterialNode
Bases:
GroupNodeRepresents a material node.
A Material
Nodeis a node that contains its own subNodeGraph. It can be used as an input to a multi-channel merge node. The node can be exported to a file (extension .mma) by callingexportMaterial().Example Code
>>> # This example creates a material node, connects a procedural to its outputs, and exports it to a file >>> nodeGraph = mari.current.geo().nodeGraph() >>> material = nodeGraph.createMaterialTemplate(mari.current.shader().shaderModel()) >>> materialNodeGraph = material.childNodeGraph() >>> outputNodes = materialNodeGraph.nodeList() # Get all the output nodes while the material is empty >>> cloud = materialNodeGraph.createNode("Procedural/Fractal/Cloud") >>> for outputNode in outputNodes : >>> outputNode.setInputNode("Input", cloud) # Connect the cloud procedural to every output node >>> material.exportMaterial("~/clouds.mma") # Export the material
- addMaterialTag(Tag)
Adds the specified Material tag to the Material node.
- Parameters:
Tag (str) – The tag to add
- Raises:
ValueError – Raised if the tag is invalid.
- addMaterialTags(Tags)
Adds the specified Material tags to the Material node.
- Parameters:
Tags (list of str) – The tags to add
- Raises:
ValueError – Raised if a tag is invalid.
- exportMaterial(FileName, ThumbnailFileName='str')
Exports the Material node to the given file name.
- Parameters:
FileName (str) – (str) The absolute path, file name, and extension to save the Material to.
ThumbnailFileName (str, optional) – (str) Optional path to a thumbnail image to save with the material. Defaults to str.
- Raises:
IOError – Raised if there is a problem saving the file or invalid thumbnail image given.
ValueError – Raised if the Material contains paint nodes, or has an output node mismatch to the ShaderModel it was created against.
- geoChannels()
Return a list of Geo Channel aliases that are in use within this material node.
- Returns:
list of str– A list of aliases, or empty if none is found.
- materialTags()
Return a list of Material tags applied to this Material node.
- Returns:
list of str– A list of tags.
- missingGeoChannels()
Return a list of Geo Channel aliases that are missing within this material node.
- Returns:
list of str– A list of aliases, or empty if none is found.
- static readMetadataFromMaterialFile(MaterialFilePath)
Reads the metadata in the material file pointed by the MaterialFilePath and returns it as QJsonDocument.
- Parameters:
MaterialFilePath (str) – The material file path to read from
- Raises:
IOError – Raised if the file is not a valid material.
- Returns:
QJsonDocument– The metadata as QJsonDocument
- static readSystemMetadataFromMaterialFile(MaterialFilePath)
Reads the system metadata in the material file pointed by the MaterialFilePath and returns it as QJsonDocument.
- Parameters:
MaterialFilePath (str) – The material file path to read from
- Raises:
IOError – Raised if the file is not a valid material.
- Returns:
QJsonDocument– The metadata as QJsonDocument
- static readTagsFromMaterialFile(MaterialFilePath)
Reads the tags in the material file pointed by the MaterialFilePath.
- Parameters:
MaterialFilePath (str) – The material file path to read from
- Raises:
IOError – Raised if the file is not a valid material.
- Returns:
list of str– The tags as a list of strings
- static readThumbnailFromMaterialFile(MaterialFilePath)
Reads the thumbnail in the material file pointed by the MaterialFilePath.
- Parameters:
MaterialFilePath (str) – The material file path to read from
- Raises:
IOError – Raised if the file is not a valid material.
- Returns:
QImage– The thumbnail as QImage
- removeMaterialTag(Tag)
Removes the specified Material tag from the Material node.
- Parameters:
Tag (str) – The tag to remove
- removeMaterialTags(Tags)
Removes the specified Material tags from the Material node.
- Parameters:
Tags (list of str) – The tags to remove
- setMaterialTags(MaterialTags)
Sets the list of Material tags on the Material node.
- Parameters:
MaterialTags (list of str) – The list of tags to assign to the node
- Raises:
ValueError – Raised if the list of tags contains invalid tags.
- shaderModel()
Returns the shader model for this material node.
- Returns:
ShaderModel– Shader model.
- static writeMetadataToMaterialFile(MetadataMap, MaterialFilePath)
Writes the given metadata in the given QJsonDocument to the MaterialFilePath.
Note that this overwrites the existing metadata, so existing metadata needs to be united beforehand.
- Parameters:
MetadataMap (QJsonDocument) – The metadata in QJsonDocument
MaterialFilePath (str) – The material file path to write to
- Raises:
IOError – Raised if the file is not a valid material.
- Returns:
bool– Whether the write was successful
- static writeTagsToMaterialFile(Tags, MaterialFilePath)
Writes the given tags to the MaterialFilePath.
Note that this overwrites the existing tags, so existing tags needs to be united beforehand.
- Parameters:
Tags (list of str) – The tags in a list of strings
MaterialFilePath (str) – The material file path to write to
- Raises:
IOError – Raised if the file is not a valid material.
- Returns:
bool– Whether the write was successful
- static writeThumbnailToMaterialFile(Thumbnail, MaterialFilePath)
Writes the given thumbnail to the MaterialFilePath and replaces existing thumbnail.
- Parameters:
Thumbnail (QImage) – The thumbnail in QImage
MaterialFilePath (str) – The material file path to write to
- Raises:
IOError – Raised if the file is not a valid material.
- class mari.Matrix
Bases:
objectObjects of this class hold a matrix 4x4.
Example Code
- asList()
Returns the elements of the matrix as a list of 16 values.
- Returns:
tuple of
float– The elements of the matrix
- length()
Returns the length of the vector.
This is the same as size().
- Returns:
int– The length of the vector
- class mari.MenuManager
Bases:
objectManages creation and manipulation of menu entries.
The menu manager creates and manipulates entries on the menus.
Menu paths are all split into three components: the “set” (e.g. “MainWindow” for the main window menu), the “root” (e.g. “File”, potentially with an “&” in it for the shortcut key), and the “submenu” (an optional menu under that, such as “Open”, also possibly containing “&” characters). This split will be made automatically by the various menu functions, but it is necessary to supply at least a set and a root to add an action.
Path elements should be separated by slashes, and any leading slash is ignored - so using either “MainWindow/File” or “/MainWindow/File” is equivalent.
Example Code
>>> # This example finds the "Print Hello" action from registered actions and add it to the menus >>> import mari >>> action = mari.actions.find("Mari/Scripts/MyCustomActions/Print Hello") >>> #mari.menus.addAction(action,"MainWindow/P&ython/&Examples")
>>> # This example removes the "Print Hello" action from the menus >>> import mari >>> #mari.menus.removeAction("MainWindow/P&ython/&Examples/Print Hello")
Alias
menus
- actions(rSet, rRoot, rSubMenu='str')
Returns the actions available for the given set, root and optional sub menu.
mari.menus.actions("MainWindow","&File") mari.menus.actions("MainWindow","P&ython", "&Examples") mari.menus.actions("MainWindow","P&ython", "&Examples/&Channels")
- Parameters:
rSet (str) – The set containing the root menu to look in.
rRoot (str) – The root menu to look up items in.
rSubMenu (str, optional) – The submenu to look up items in. Defaults to str.
- Returns:
list of
Action– The list of items associated with a given set/root menu/submenu
- addAction(pAction, rPath, rAddBefore='str')
Adds an action to the menu in the given path.
# Create an example item in the main file menu, before the save option mari.menus.addAction(mari.actions.create('Create Project And Import', 'mari.examples.create_project.createAndImport()'), "MainWindow/&File/", "/MainWindow/&File/&Save")
- Parameters:
pAction (Action) – The existing action to add to the menu.
rPath (str) – The menu path to add
rAddBefore (str, optional) – The text of an item in the given menu. The new action will be added immediately before the given item. If left blank, the item will be appended to the end of the menu. To add before a separator, pass in any string beginning with ‘-’. This should be just the name of the item not the full path. To find the list of items in a menu use
itemNames(). Defaults to str.
- Raises:
ValueError – Raised if the action or path were invalid, or if an item to add before was specified but did not match a valid item in the given menu.
- addSeparator(Path, rAddBefore='str')
Adds a separator to the menu in the given path.
- Parameters:
Path (str) – The menu path to add
rAddBefore (str, optional) – The text of an item in the given menu. The new action will be added immediately before the given item. If left blank, the item will be appended to the end of the menu. To add before another separator, pass in any string beginning with ‘-’. Defaults to str.
- Raises:
ValueError – Raised if the action or path were invalid, or if an item to add before was specified but did not match a valid item in the given menu.
- itemNames(rSet, rRoot, rSubMenu='str')
Returns the names of the items available for the given set, root and optional sub menu.
mari.menus.itemNames("MainWindow","&File") mari.menus.itemNames("MainWindow","P&ython", "&Examples") mari.menus.itemNames("MainWindow","P&ython", "&Examples/&Channels")
- Parameters:
rSet (str) – The set containing the root menu to look in.
rRoot (str) – The root menu to look up items in.
rSubMenu (str, optional) – The submenu to look up items in. Defaults to str.
- Returns:
list of str– The list of items associated with a given set/root menu/submenu
- removeAction(rFullPath)
Removes an action specified by a path from the menu.
- Parameters:
rFullPath (str) – The path to the action, including its name.
- Raises:
ValueError – Raised if the action was not found.
- roots(rSet)
Returns a list of the root menus available for the given set.
Marihas a hierarchical menu system. Menus may contain other menus. Each set of menus has one or more root menus. These are the items that appear in the menu bar and are presented as context menus.- Parameters:
rSet (str) – The set to look up root menus for.
- Returns:
list of str– A list of the root menu names.
- sets()
Returns a list of the available menu sets.
Marimaintains multiple sets of menus. These menus appear in different contexts such as the main window or the context (right click) menus of various palettes. This method returns the list of set names.- Returns:
list of str– The list of available menu sets.
Returns a list of the submenus available for the given set and root menu.
mari.menus.submenus("MainWindow","&File") mari.menus.submenus("MainWindow","P&ython", "&Examples") mari.menus.submenus("MainWindow","P&ython", "&Examples/&Channels")
- Parameters:
rSet (str) – The set containing the root menu to look in.
rRoot (str) – The root menu to look up submenus in.
rSubMenu (str, optional) – The submenu to look up items in. Defaults to str.
- Returns:
list of str– The list of sub menus associated with a given root menu
- class mari.MessageBox
Bases:
objectWrapper on Qt QMessageBox that shows up only if popups are allowed.
- class mari.Metadata
Bases:
objectAn interface for dealing with metadata associated with Mari objects.
Users can add arbitrary amounts of metadata to objects. This metadata can be used for asset management tracking, or any situation where extra information is required for an object.
Items of metadata are stored in the form of string and variant pairs, allowing the use of different types of data. Certain types of metadata have GUI editor components; these are exposed in the “User Attributes” section of the property editor.
Example Code
>>> # This adds a new metadata (i.e. attribute) called "MyVersion" to the current channel >>> import mari >>> channel = mari.geo.current().currentChannel() >>> channel.setMetadata("MyVersion", "2.1")
- METADATA_EDITABLE = 2
The item’s value can be modified.
- Type:
int
- METADATA_GROUP_HINT_DISPLAY = 4
The item is displaye in some collection palette.
- Type:
int
- METADATA_GROUP_HINT_SORTABLE = 8
The item can be used for sorting.
- Type:
int
- METADATA_REMOVABLE = 4
The item can be removed by users.
- Type:
int
- METADATA_REMOVEABLE = 4
Due to spelling mistake. Please use METADATA_REMOVABLE instead.
- Type:
int
- Type:
DEPRICATED
- METADATA_SAVED = 16
The item is saved with the project and will persist between sessions.
- Type:
int
- METADATA_TYPE_FLAG_COLOR_SCALAR = 1
Color should be treated as scalar.
- Type:
int
- METADATA_TYPE_FLAG_FLOAT_LOGARITHMIC = 1
Float should be treated as logarithmic.
- Type:
int
- METADATA_TYPE_FLAG_STRING_MULTILINE = 1
String should be treated as multi-line.
- Type:
int
- METADATA_UNDOABLE = 8
Modifications to the item’s value are added to the undo history, and can be undone and redone.
- Type:
int
- METADATA_VISIBLE = 1
The item is visible and can be seen in the corresponding GUI.
- Type:
int
- class MetadataFlag
Bases:
objectSpecifies the options that can be set on metadata items.
- METADATA_EDITABLE = 2
The item’s value can be modified.
- Type:
int
- METADATA_REMOVABLE = 4
The item can be removed by users.
- Type:
int
- METADATA_REMOVEABLE = 4
Due to spelling mistake. Please use METADATA_REMOVABLE instead.
- Type:
int
- Type:
DEPRICATED
- METADATA_SAVED = 16
The item is saved with the project and will persist between sessions.
- Type:
int
- METADATA_UNDOABLE = 8
Modifications to the item’s value are added to the undo history, and can be undone and redone.
- Type:
int
- METADATA_VISIBLE = 1
The item is visible and can be seen in the corresponding GUI.
- Type:
int
- class MetadataGroupHint
Bases:
objectSpecifies the group the metadata belongs to.
- METADATA_GROUP_HINT_DISPLAY = 4
The item is displaye in some collection palette.
- Type:
int
- METADATA_GROUP_HINT_SORTABLE = 8
The item can be used for sorting.
- Type:
int
- class MetadataTypeFlag
Bases:
objectSpecifies the flags for metadata types.
- METADATA_TYPE_FLAG_COLOR_SCALAR = 1
Color should be treated as scalar.
- Type:
int
- METADATA_TYPE_FLAG_FLOAT_LOGARITHMIC = 1
Float should be treated as logarithmic.
- Type:
int
- METADATA_TYPE_FLAG_STRING_MULTILINE = 1
String should be treated as multi-line.
- Type:
int
- hasMetadata(Name)
Indicates whether an item of metadata with the given name exists on the object.
- Parameters:
Name (str) – The name of the metadata item to query
- Returns:
bool– True if a metadata item with the given name is associated with this object, or false otherwise
- static isSupportedMetadataType(Value)
Returns whether the data type of the argument can be stored as metadata.
Most plain-old data types (e.g., integers, floats and strings) are supported. If the data type you would like to add as metadata is not supported, you should consider serializing it to a unicode string and saving that as metadata instead.
- Parameters:
Value (variant) – An object instance of the type you would like to check.
- Returns:
bool– True if the type is supported, and False if not.
- metadata(Name)
Returns the value of an item of metadata.
- Parameters:
Name (str) – The name of the item to query
- Raises:
ValueError – Raised if no metadata item with the given name was found, and no default value was provided.
- Returns:
variant– The value of the item.
- metadataAsImage(Name)
Retrieves the current value of a parameter and, if possible, return the Image it relates to.
- Parameters:
Name (str) – The name of the parameter to inspect.
- Raises:
ValueError – Raised if name of the parameter does not match any existing items.
- Returns:
Image– Image of the parameter. None if not image is assigned.
See also
metadata()
- metadataCreated(Name, Value)
This is emitted when a metadata item is added.
- Parameters:
Name (str) – The name of the metadata that has been added.
Value (variant) – The value of the new metadata item.
- metadataDefault(Name)
Returns the default value of an item of metadata on the object.
- Parameters:
Name (str) – The name of the item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- Returns:
variant– The default value of the item
- metadataDescription(Name)
Returns the description of an item of metadata on the object.
- Parameters:
Name (str) – The name of the item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- Returns:
str– The description of the item
- metadataDisplayName(Name)
Returns the display name of an item of metadata on the object.
- Parameters:
Name (str) – The name of the item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- Returns:
str– The display name of the item
- metadataEnabledChanged(Name, Enabled)
This is emitted when a metadata item’s enable state is changed.
- Parameters:
Name (str) – The name of the metadata that has been enabled or disabled.
Enabled (bool) – Whether the metadata is enabled.
- metadataFlags(Name)
Returns the flags of an item of metadata on the object.
- Parameters:
Name (str) – The name of the item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- Returns:
MetadataFlags– The flags of the item
- metadataIsEnabled(Name)
Return true if the given item of metadata is enabled.
- Parameters:
Name (str) – The name of the metadata
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- Returns:
bool– True if the given metadata item is enabled, false otherwise
- metadataItemList(Name)
Returns the list of strings that the user can select from to choose the value of the metadata item.
- Parameters:
Name (str) – The name of the item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- Returns:
list of str– The list of potential value strings. If no list of strings has been set using setMetadataItemList(), the list will be empty.
- metadataMax(Name)
Returns the range of an item of metadata on the object.
- Parameters:
Name (str) – The name of the item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- Returns:
variant– The maximum value of the item
- metadataMin(Name)
Returns the range of an item of metadata on the object.
- Parameters:
Name (str) – The name of the item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- Returns:
variant– The minimum value of the item
- metadataNames()
Returns a list of the metadata items associated with this object.
- Returns:
list of str– A list of the metadata names
- metadataRemoved(Name)
This is emitted when a item of metadata is removed from this object.
- Parameters:
Name (str) – The name of the metadata item that was removed.
- metadataStep(Name)
Returns the step size of an item of metadata on the object.
- Parameters:
Name (str) – The name of the item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- Returns:
variant– The step size of the item
- metadataTypeFlags(Name)
Returns the type flags of an item of metadata on the object.
- Parameters:
Name (str) – The name of the item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- Returns:
MetadataTypeFlags– The type flags of the item
- metadataValueChanged(Name, Value)
This is emitted when a metadata item’s value is changed.
- Parameters:
Name (str) – The name of the metadata that has been changed.
Value (variant) – The new value of the metadata item.
- removeMetadata(Name)
Removes an item of metadata.
- Parameters:
Name (str) – The name of the medata item to remove
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- setMetadata(Name, Value)
Adds or modifies an item of metadata on the object.
If a metadata item with the given name exists already, its value will be updated. If not, a new one will be created.
- Parameters:
Name (str) – The name of the item
Value (variant) – The value of the item
- Raises:
ValueError – Raised if the type of the value is not supported by the metadata system.
- setMetadataDefault(Name, Default)
Modifies the default value of an item of metadata on the object.
If a metadata item with the given name exists already, its default value will be updated.
- Parameters:
Name (str) – The name of the item
Default (variant) – The default value of the item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- setMetadataDescription(Name, Description)
Modifies the description of an item of metadata on the object.
If a metadata item with the given name exists already, its description will be updated.
- Parameters:
Name (str) – The name of the item
Description (str) – The description of the item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- setMetadataDisplayName(Name, DisplayName)
Modifies the display name of an item of metadata on the object.
If a metadata item with the given name exists already, its display name will be updated.
- Parameters:
Name (str) – The name of the item
DisplayName (str) – The display name of the item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- setMetadataEnabled(Name, Enabled)
Set the enabled flag for the given item of metadata.
- Parameters:
Name (str) – The name of the metadata
Enabled (bool) – The new enabled state of the metadata item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- setMetadataFlags(Name, Flags)
Modifies the flags of an item of metadata on the object.
If a metadata item with the given name exists already, its flags will be updated.
- Parameters:
Name (str) – The name of the item
Flags (MetadataFlags) – The flags of the item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- setMetadataGroupHints(Name, Hints)
Modifies the group hint of an item of metadata on the object.
If a metadata item with the given name exists already, its flags will be updated.
- Parameters:
Name (str) – The name of the item
Hints (MetadataGroupHints) – The hint of the item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- setMetadataItemList(Name, ItemList)
Sets a list of strings that the user can select from to choose the value of the metadata item.
If a metadata item with the given name exists already, its item list will be updated.
- Parameters:
Name (str) – The name of the item
ItemList (list of str) – The item list of the item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- setMetadataRange(Name, Min, Max)
Modifies the range of an item of metadata on the object.
If a metadata item with the given name exists already, its range will be updated.
- Parameters:
Name (str) – The name of the item
Min (variant) – The minimum value of the item
Max (variant) – The maximum value of the item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- setMetadataStep(Name, Step)
Modifies the step size of an item of metadata on the object.
If a metadata item with the given name exists already, its step size will be updated.
- Parameters:
Name (str) – The name of the item
Step (variant) – The step size of the item
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- setMetadataTypeFlags(Name, Flags)
Modifies the type flags of an item of metadata on the object.
If a metadata item with the given name exists already, its type flags will be updated.
- Parameters:
Name (str) – The name of the item
Flags (MetadataTypeFlags) – The flags to set for the type
- Raises:
ValueError – Raised if no metadata item with the given name was found.
- uuid()
Return a UUID that uniquely identifies this object.
Marimaintains a unique ID for each object, this will return that UUIDprint(mari.current.channel().uuid())- Returns:
str– A String containing the UUID for the object
- class mari.Miscellaneous
Bases:
objectProvides access to the various interactive user utility functions.
Alias
hidden
- createIconFromPath(Path)
This is a convenience static function that creates a icon with different images for different states from a single image.
- Parameters:
Path (str) –
Imagepath to create the icon from.- Returns:
QIcon– The resulting icon for the given image.
- getExistingDirectory(Parent=None, Caption='str', Dir='str')
This is a convenience static function that returns an existing directory selected by the user. If the user presses Cancel, it returns a null string.
- Parameters:
Parent (QWidget, optional) – Parent widget to center dialog over. Defaults to None.
Caption (str, optional) – Title of the dialog box. Defaults to str.
Dir (str, optional) – Initial working directory of the dialog. Defaults to str.
- Returns:
str– Name of the directory selected by the user, or null if user pressed Cancel.
- getMkdirCommand()
The is a convenience static function to return the custom system command for creating directories.
- Returns:
str– Name of the script or program.
- getOpenFileName(Parent=None, Caption='str', Dir='str', Filter='str', SelectedFilter='str', Options=0)
This is a convenience static function that returns an existing file selected by the user. If the user presses Cancel, it returns a null string.
- Parameters:
Parent (QWidget, optional) – Parent widget to center dialog over. Defaults to None.
Caption (str, optional) – Title of the dialog box. Defaults to str.
Dir (str, optional) – Initial working directory of the dialog. If it includes a file the file will be selected. Defaults to str.
Filter (str, optional) – Only files that match the given filter are shown. Defaults to str.
SelectedFilter (str, optional) – Initial selected filter. Defaults to str.
Options (int, optional) – Options about how to run the dialog. Defaults to 0.
- Returns:
str– Name of the file selected by the user, or null if user pressed Cancel.
- getSaveFileName(Parent=None, Caption='str', Dir='str', Filter='str', SelectedFilter='str', Options=0, SaveFileName='str')
This is a convenience static function that returns a filename to save selected by the user. If the user presses Cancel, it returns a null string.
- Parameters:
Parent (QWidget, optional) – Parent widget to center dialog over. Defaults to None.
Caption (str, optional) – Title of the dialog box. Defaults to str.
Dir (str, optional) – Initial working directory of the dialog. If it includes a file the file will be selected. Defaults to str.
Filter (str, optional) – Only files that match the given filter are shown. Defaults to str.
SelectedFilter (str, optional) – Initial selected filter. Defaults to str.
Options (int, optional) – Options about how to run the dialog. Defaults to 0.
SaveFileName (str, optional) – Default filename to save to. Defaults to str.
- Returns:
str– Name of the file selected by the user, or null if user pressed Cancel.
- registerRegExpChannelNameExtractor(RegExp)
This is a convenience static function to override the logic used in the Channel Presets dialog.
When using the
ChannelPresets dialog, or when creating a new project, a scan button is provided to allow channel information to be extracted from textures that already exist on disk. This routine allows a regular expression to be used for determining the channel names from these filenames.- Parameters:
RegExp (str) – A string containing a regular expression that will return a channel name given a texture filename.
- setMkdirCommand(Command)
This is a convenience static function to allow the use of a custom program for creating directories on Linux.
- Parameters:
Command (str) – Full path to the command to exectute.
- class mari.MultiChannelBakePointNode
Bases:
GroupNodeRepresents a multi-channel bake point node.
A
MultiChannelBakePointNodeis a node that groups multiple BakePointNodes for an associatedShaderModel.Example Code
>>> # This example creates a MultiChannelBakePointNode >>> nodeGraph = mari.current.geo().nodeGraph() >>> mcBakePoint = nodeGraph.createMultiChannelBakePointNode(mari.current.shader().shaderModel(), 512, 512, 16)
- bakeActive()
Bakes the active streams of BakePointNodes.
A stream is considered active if it’s connected to a
ChannelNodein its downstream.
- bakePointNode(ShaderModelInputForBakePoint)
Returns the BakePointNode object corresponding to the given ShaderModelInput object.
- Parameters:
ShaderModelInputForBakePoint (ShaderModelInput) – The
ShaderModelInputobject corresponding to the desiredBakePointNodeobject.- Raises:
ValueError – Raised if the given ShaderModelInput does not belong to the shader model of this MultiChannelBakePointNode.
RuntimeError – Raised if the BakePointNode cannot be obtained.
- Returns:
BakePointNode– the BakePointNode object corresponding to the given ShaderModelInput object.
- bakeStreams(Streams)
Bakes the given streams of BakePointNodes.
- Parameters:
Streams (list of
ShaderModelInput) – The list of Streams represented byShaderModelInputobjects to bake at.- Raises:
ValueError – Raised if the given sStreams do not belong to the shader model of this MultiChannelBakePointNode.
- deleteBake()
Deletes the baked result of all the child BakePointNodes.
- setLimitBake(LimitBake)
Sets whether the limited patch baking is on.
Setting this will enable or disable limited patch baking of all the child BakePointNodes.
- Parameters:
LimitBake (bool) – Whether the limited patch baking is on
- setLimitBakeRange(LimitBakeRange)
Sets the baking patch range to the given range.
Setting this will set the baking patch range of all the child BakePointNodes.
- Parameters:
LimitBakeRange (UvIndexRangeList) – The range to set
- shaderModel()
Returns the shader model for this multi-channel bake point node.
- Returns:
ShaderModel– Shader model.
- streamBakePointNodes()
Returns the map of ShaderModelInput short name to the corresponding BakePointNode object.
- Returns:
variant– the map of ShaderModelInput short name to the corresponding BakePointNode object
- class mari.MultiChannelContainer
Bases:
MetadataThis class represents a multi-channel layer entity which is essentially a set of sibling stream layers connected to different channels.
Every multi-channel layer is tighly coupled with a specific shader model. Multi-channel layer is built on multi-output blend node, which can be treated as a set of normal blend nodes for every shader model’s input. They all share the same mask or mask stack. All blend node’s streams derive names from shader model inputs’ short names.
See also
mari.MultiChannelLayer
- isVisible()
Checks, if the underlying multi-channel blend node is visible.
- Returns:
bool– True, if the blend node is visible, or false otherwise.
- setVisibility(Visible)
Shows or hides the underlying multi-channel blend node.
Changing the visibility state for a multi-channel layer means disabling or enabling a multi-channel blend node as a whole, so disabling or enabling all stream layers at once.
- Parameters:
Visible (bool) – Should be True to show the multi-channel layer, or False to hide it.
- shaderModel()
Returns the shader model, which is coupled with this multi-channel layer.
- Returns:
ShaderModel– A related shader model.
See also
mari.ShaderModel
- streamList()
Returns a list of multi-channel stream layers, that are currently connected to any channel.
- Returns:
list of
MultiChannelLayer– A list of active multi-channel stream layers.
See also
mari.MultiChannelLayer
- class mari.MultiChannelGroup
Bases:
MultiChannelContainerThis class represents a multi-channel group layer entity.
See also
mari.MultiChannelContainer
See also
mari.MultiChannelGroupLayer
- flattenLayerGroup()
Flatten the group layer stacks of this multi-channel layer.
- Returns:
list of
Layer– Returns a list with the new paintable layers which contain results of flattening this multi-channel group layer for all active streams. For every active stream a new paintable layer will be added, in place of the multi-channel group, with its contents flattened into it and the original layer removed from the channel.
- class mari.MultiChannelGroupLayer
Bases:
MultiChannelLayerThis class represents a multi-channel group stream layer i.e. it is a part (one stream) of a multi-channel layer that is able to group other layers. Specifically it can group a set of multi-channel material layers. For more explanations on multi-channel layers please take a look at MultiChannelLayer’s description.
See also
mari.MultiChannelLayer
See also
mari.MultiChannelGroup
- container()
Returns a multi-channel group layer entity object, which contains this particular stream layer.
- Returns:
MultiChannelGroup– A container of this multi-channel group stream layer.
See also
mari.MultiChannelGroup
- layerStack()
Returns a layer stack containing all child layers of this multi-channel stream layer.
- Returns:
LayerStack– A layer stack with all child layer’s of this multi-channel stream layer.
See also
mari.LayerStack
- class mari.MultiChannelLayer
Bases:
LayerMultiChannelLayer represents one stream in a bigger entity called a multi-channel layer.
Multi-channel layers span across multiple channels and are mostly used for blending materials into them. Every multi-channel layer is tightly coupled with a specific shader model. Output names of a multi-channel layer are derived from names of a related shader model (i.e. use their short names). It looks similarly for Base and Over inputs, but we add ‘Base ‘ or ‘Over ‘ prefix to a short name of shader model input to form an input name. All stream layers of a multi-channel layer share the same mask, so if you change something in a mask stack for one stream layer, it affects other sibling stream layers as well. Every stream layer in the
MariPython API can be treated as a normal layer with a standard set of methods.Example Code
>>> # This example finds all multi-channel stream layers in the current channel. >>> import mari >>> mc_layers = [] >>> channel = mari.geo.current().currentChannel() >>> for layer in channel.layerList(): ... if layer.isMultiChannelGroupLayer() or layer.isMultiChannelMaterialLayer(): ... mc_layers.append(layer)
See also
mari.Layer
See also
mari.MultiChannelContainer
See also
mari.MultiChannelGroupLayer
See also
mari.MultiChannelMaterialLayer
- streamName()
Returns the stream name of this multi-channel stream layer.
The stream name is the same as an output name of a multi-channel blend node. It is also the same as a short name of a corresponding shader model’s input.
- Returns:
str– The stream name of this multi-channel stream layer.
- class mari.MultiChannelMaterial
Bases:
MultiChannelContainerThis class represents a multi-channel material layer entity.
See also
mari.MultiChannelContainer
See also
mari.MultiChannelMaterialLayer
- convertToPaintable(SelectedOnly=False)
Converts this material layer entity into paintable layers across streams.
As this operation changes the layer type, this material will no longer be valid.
- Parameters:
SelectedOnly (bool, optional) – Whether or not to bake the result into all patches or only the selected patches. Defaults to False.
- materialNode()
Returns the material node object, which belongs to this multi-channel material layer.
Material node is a special group node connected to all Over inputs of the multi-channel layer’s blend node. It holds a material definition for all inputs of the related shader model.
- Returns:
MaterialNode– The material node object hold by this layer.
See also
mari.MaterialNode
- class mari.MultiChannelMaterialLayer
Bases:
MultiChannelLayerThis class represents a multi-channel material stream layer. It is one stream of a multi-channel layer that holds a node with a material definition. For more explanations on multi-channel layers please take a look at MultiChannelLayer’s description.
See also
mari.MultiChannelLayer
See also
mari.MultiChannelMaterial
- container()
Returns a multi-channel material layer entity object, which contains this particular stream layer.
- Returns:
MultiChannelMaterial– A container of this multi-channel material stream layer.
See also
mari.MultiChannelMaterial
- class mari.MultiChannelPaintNode
Bases:
GroupNodeRepresents a multi-channel paint node.
A
MultiChannelPaintNodeis a node that groups multiple PaintNodes for an associatedShaderModel.Example Code
>>> # This example creates a MultiChannelPaintNode >>> nodeGraph = mari.current.geo().nodeGraph() >>> mcPaint = nodeGraph.createMultiChannelPaintNode(mari.current.shader().shaderModel(), 512, 512, 16)
- paintNode(ShaderModelInputForPaint)
Returns the PaintNode object corresponding to the given ShaderModelInput object.
- Parameters:
ShaderModelInputForPaint (ShaderModelInput) – The
ShaderModelInputobject corresponding to the desiredPaintNodeobject.- Raises:
ValueError – Raised if the given ShaderModelInput does not belong to the shader model of this MultiChannelPaintNode.
RuntimeError – Raised if the PaintNode cannot be obtained.
- Returns:
PaintNode– the PaintNode object corresponding to the given ShaderModelInput object.
- setAsCurrentMultiChannelPaintNode()
Sets this MultiChannelPaintNode as the current MultiChannelPaintNode.
- shaderModel()
Returns the shader model for this multi-channel paint node.
- Returns:
ShaderModel– Shader model.
- streamPaintNodes()
Returns the map of ShaderModelInput short name to the corresponding PaintNode object.
- Returns:
variant– the map of ShaderModelInput short name to the corresponding PaintNode object
- class mari.MultiPaintManager
Bases:
objectManages Multi-Paint streams and palette configuration.
Alias
multi_paint
- activeStreams()
Returns a list of active stream names.
- Returns:
list of str– List of active stream names
- multiPaintEnabled()
Returns true if multi-paint is enabled, false otherwise.
- primaryStream()
Returns the name of the primary stream.
- Returns:
str– The name of the primary stream
- setMultiPaintEnabled(Enabled)
Enables or disables multi-paint mode.
- Parameters:
Enabled (bool) – True to enable multi-paint, false to disable
- setPrimaryStream(StreamName)
Sets the primary stream.
- Parameters:
StreamName (str) – The name of the stream to set as primary
- Raises:
ValueError – Raised if the stream doesn’t exist or is not active
- setStreamActive(StreamName, Active)
Sets the active state of a stream.
- Parameters:
StreamName (str) – The name of the stream to modify
Active (bool) – True to activate the stream, false to deactivate
- Raises:
ValueError – Raised if trying to deactivate the last active stream or activate more than maximum streams
- setStreamBackgroundColor(StreamName, NewColor)
Sets the background color of a stream.
- Parameters:
StreamName (str) – The name of the stream
NewColor (Color) – The color to set
- Raises:
ValueError – Raised if the stream doesn’t exist
TypeError – Raised if NewColor is not a Color object
- setStreamBlendMode(StreamName, BlendMode)
Sets the blend mode of a stream.
- Parameters:
StreamName (str) – The name of the stream
BlendMode (str) – The blend mode to set, specified by its path (e.g. “/Darken/Multiply”) or name only (e.g. “Multiply”)
- Raises:
ValueError – Raised if the stream doesn’t exist or blend mode is invalid
- setStreamForegroundColor(StreamName, NewColor)
Sets the foreground color of a stream.
- Parameters:
StreamName (str) – The name of the stream
NewColor (Color) – The color to set
- Raises:
ValueError – Raised if the stream doesn’t exist
TypeError – Raised if NewColor is not a Color object
- setStreamImage(StreamName, NewImage)
Sets the image for a stream.
- Parameters:
StreamName (str) – The name of the stream
NewImage (Image) – The image to set, or nullptr to clear the image
- Raises:
ValueError – Raised if the stream doesn’t exist
TypeError – Raised if NewImage is not an Image object
- streamActive(StreamName)
Returns true if the specified stream is active.
- Parameters:
StreamName (str) – The name of the stream to check
- Returns:
bool– True if the stream is active, false otherwise
- streamBackgroundColor(StreamName)
Gets the background color of a stream.
- Parameters:
StreamName (str) – The name of the stream
- Raises:
ValueError – Raised if the stream doesn’t exist
- Returns:
Color– The background color as a Color object
- streamBlendMode(StreamName)
Gets the blend mode of a stream.
- Parameters:
StreamName (str) – The name of the stream
- Raises:
ValueError – Raised if the stream doesn’t exist
- Returns:
str– The blend mode path as a string
- streamForegroundColor(StreamName)
Gets the foreground color of a stream.
- Parameters:
StreamName (str) – The name of the stream
- Raises:
ValueError – Raised if the stream doesn’t exist
- Returns:
Color– The foreground color as a Color object
- streamImage(StreamName)
Gets the image associated with a stream.
- Parameters:
StreamName (str) – The name of the stream
- Raises:
ValueError – Raised if the stream doesn’t exist
- Returns:
Image– The image as an Image object, or nullptr if no image is set
- streamNames()
Returns a list of all stream names.
- Returns:
list of str– List of stream names
- class mari.Node
Bases:
MetadataProvides shader node graph functionality.
Example Code
>>> # This example obtains a node from the node graph of the current geo entity >>> import mari >>> nodeGraph = mari.geo.current().nodeGraph() >>> node = nodeGraph.nodeList()[0]
- PORT_LIST_COLLAPSED = 5
.
- Type:
int
- PORT_LIST_EXPANDED = 1
.
- Type:
int
- PORT_LIST_GROUPED = 3
.
- Type:
int
- PORT_LIST_ONLY_CONNECTED = 4
.
- Type:
int
- PORT_LIST_T2B = 2
.
- Type:
int
- class PortListMode
Bases:
objectSpecifies the options for the port list mode of nodes.
- PORT_LIST_COLLAPSED = 5
.
- Type:
int
- PORT_LIST_EXPANDED = 1
.
- Type:
int
- PORT_LIST_GROUPED = 3
.
- Type:
int
- PORT_LIST_ONLY_CONNECTED = 4
.
- Type:
int
- PORT_LIST_T2B = 2
.
- Type:
int
- addNodeContext(Name, Context)
Adds the given Context to this node with the given Name.
- Parameters:
Name (str) – The name of the Context is added under.
Context (NodeContext) – The
NodeContextobject to add.
- Raises:
RuntimeError – Raised if the NodeContext cannot be added.
- addTag(Tag, ForceAdd=False)
Adds the given tag to this node.
All system tags are prefixed by underscores(_).Tags with underscores cannot be added unless ForceAdd is True.
- Parameters:
Tag (str) – The tag to add.
ForceAdd (bool, optional) – Force adding the tag even if the given tag is considered a system tag. Defaults to False.
- Raises:
RuntimeError – Raised if the given tag cannot be added.
- attachViewer(InputNumber=1)
Connects the viewer to this node for glsl rendering on the canvas.
- Parameters:
InputNumber (int, optional) – A number of the viewer’s input that the node should be connected to. It should be in a range from 1 to 9. Defaults to 1.
- bake(Width, Height, Depth, FileSpace='Image.FILESPACE_NORMAL', ColorConfig='nullptr', OutputPortName='')
Bakes the result at the current node into an ImageSet and returns the PaintNode owning the ImageSet.
- Parameters:
Width (int) – The default width of the
ImageSet(ignored forPtex)Height (int) – The default height of the (ignored for
Ptex)Depth (int) – The default bit depth of the
ImageSetFileSpace (Image.FileSpace, optional) – The file space of the imageset, with the default value being “Normal”. Defaults to Image.FILESPACE_NORMAL.
ColorConfig (ColorspaceConfig, optional) – The colorspace configuration of the imageset. Defaults to nullptr.
OutputPortName (str, optional) – The output port at which the result should be baked. Defaults to “”.
- Raises:
RuntimeError – Raised if the PainNode could not be created
- bypassInput(OutputPoint='')
Returns the index of input passed to the output bypassing this node.
Bypassing a node effectively disables this node and pass an input straight to the output. This method allows to set which input is passed to the output.
- Parameters:
OutputPoint (str, optional) – the output point to which the input is bypassed. Defaults to “”.
- Returns:
int– -1 if this node is processed in the normal manner. If this node is bypassed, then the index of input passed to the output bypassing this node is returned
- exportToGeoChannel(DestGeoChannel, OutputPortName='')
Bakes the result at the current node into the given Geo-Channel.
- Parameters:
DestGeoChannel (GeoChannel) – The Geo-Channel to bake to
OutputPortName (str, optional) – The output port at which the result should be baked. Defaults to “”.
- Returns:
bool– Success of the bake
- focusInNodeGraph()
Centres the nodegraph view on this node.
If the nodegraph this node belongs to does not have a tab open in the
NodeGraph palette, a tab will be opened for it.
- hasChanged()
This signal is emitted when the node has been modified.
- hasTag(Tag)
Returns whether this node has the given tag.
- Parameters:
Tag (str)
- Returns:
bool– Whether this node has the given tag.
- hash(UVIndex=-1, IgnoreChildren=False)
Returns a unique identifier for this node and its children.
This hash is assumed to be universally unique (256bit skein hash). This can be used to determine if this node or any of its connected child has changed since some given checkpoint. This hash is based on image data, parameters and anything that might effect the pixel output. Use this to detect any changes to a node, in the node graph.
- Parameters:
UVIndex (int, optional) – The UV index of the patch to return the hash of, or -1 (default) to return the hash of all the patches. Defaults to -1.
IgnoreChildren (bool, optional) – A flag to specify whether we only want the hash of this node itself or whether we want an accumulative hash of this node and its connected children (default value). Defaults to False.
- Returns:
str– A hash string that uniquely identifies a node and its childrens, or an empty string on failure.
- inputConnection(PortName)
Returns a list consisting of a node and output port, which is connected to the given input port name.
If no connection is present, a list containing None and an empty string is returned.
>>> selected_node = mari.current.geo().nodeGraph().selectedNodeList()[0] >>> for input_name in selected_node.inputPortNames(): ... input_node, output_port = selected_node.inputConnection(input_name) ... if input_node: ... print("%s's input port %s is connected to %s's output port %s" % (selected_node.name(), input_name, input_node.name(), output_port)) ... else: ... print("%s's input port %s is not connected" % (selected_node.name(), input_name))
- Parameters:
PortName (str) – The name of the port to which the returned connection is connected.
- Returns:
list of variant– A list containing the input node and the output port name of the input node, in that order.
- inputNode(PortName)
Returns the node connected to the given input port name .
If no node is connected, None is returned.
- Parameters:
PortName (str) – The name of the port to which the returned node is connected.
- Returns:
Node– The node connected to the given port name. If no node is connected, None is returned.
- inputNodeChanged(Name)
This signal is emitted when a input node is changed on this node.
- Parameters:
Name (str) – Name of the input that was modified.
- inputPortCount()
Returns the number of input point count.
- Returns:
int– The number of input port count.
- inputPortName(Index)
Returns the input port name at the given index.
- Parameters:
Index (int)
- Returns:
str– The input port name at the given index.
- inputPortNames()
Returns a list of all the names of the input points of this node.
- Returns:
list of str– The list of input port names.
- isBackdropNode()
Returns whether this node is a BackdropNode.
- Returns:
bool– Whether this node is a BackdropNode
- isBakePointNode()
Returns whether this node is a BakePointNode.
- Returns:
bool– Whether this node is a BakePointNode
- isEnabled()
Returns whether the node is enabled.
- Returns:
bool– Whether the node is enabled.
- isGeoChannelNode()
Returns whether this node is a GeoChannelNode.
- Returns:
bool– Whether this node is a GeoChannelNode
- isGroupNode()
Returns whether this node is an GroupNode.
- Returns:
bool– Whether this node is an GroupNode
- isPaintNode()
Returns whether this node is a PaintNode.
- Returns:
bool– Whether this node is a PaintNode
- isSelected()
Returns whether this node is selected.
- Returns:
bool– Whether this node is selected.
- name()
Returns the name of the node.
- Returns:
str– The name of this node.
- nameChanged(NewName)
This is emitted after the node has had its name changed.
- Parameters:
NewName (str) – The new name.
- nodeContext(Name)
Returns the NodeContext of the given name.
- Parameters:
Name (str) – The name of the
NodeContext- Returns:
NodeContext– The NodeContext of the given name
- nodeContextNames()
Returns the names of NodeContext this Node holds.
- Returns:
list of str– The list of names of NodeContext this Node holds
- nodeGraphPosition()
Returns the position of this node in its NodeGraph.
The position refers to the top left corner of the node bounding box.
- Raises:
RuntimeError – Raised if the node has no presence in a node graph.
- Returns:
QPointF– Position of the node
- nodeGraphSize()
Returns the size of this node in its NodeGraph.
The size refers to the size of the nodes bounding box.
- Raises:
RuntimeError – Raised if the node has no presence in a node graph.
- Returns:
QSizeF– Size of the node
- nodeInformation()
Gets vital information about the node such as its inputs, attributes and outputs.
- Returns:
str– Vital node information.
- nodePath()
Returns the path of this node, which can be used by mari.NodeGraph.createNode() to create more.
- outputNodes(PortName='')
Returns a list of list pairs, each containing the immediate nodes connected and the input port name, to the given output port name.
If no nodes are connected, an empty list is returned.
>>> # Get a selected node that connects to multiple nodes, like a shared layer >>> sharedLayerSource = mari.current.geo().nodeGraph().selectedNodeList()[0] >>> print(sharedLayerSource.name()) Cloud >>> outputPortName = "Output" >>> for targetNode, targetPortName in sharedLayerSource.outputNodes(outputPortName): # Returns a list of node, port name list pairs ... print("%s's output port %s is connected to %s's input port %s" % (sharedLayerSource.name(), outputPortName, targetNode.name(), targetPortName)) Cloud's output port Output is connected to Cloud (Merge)'s input port Over Cloud's output port Output is connected to Shared Cloud (Merge)'s input port Over
- Parameters:
PortName (str, optional) – The name of the port from which the returned nodes are connected. Defaults to “”.
- Raises:
RuntimeError – Raised if the input portname is invalid.
- Returns:
list of variant– List of pairs, containing the connected node from the given port name and its corresponding input port name. If no nodes are connected, an empty list is returned.
- outputPortCount()
Returns the number of output point count.
- Returns:
int– The number of output port count.
- outputPortName(Index)
Returns the output port name at the given index.
- Parameters:
Index (int)
- Returns:
str– The output port name at the given index.
- outputPortNames()
Returns a list of all the names of the output points of this node.
- Returns:
list of str– The list of output port names.
- parentNodeGraph()
Returns the NodeGraph this Node belongs to.
- Returns:
NodeGraph– NodeGraph object this Node belongs to.
- pathKey()
Returns the path key of this node.
The path key of this node.
- portListMode()
Returns the port list mode of this node.
- Raises:
RuntimeError – Raised if the node has no presence in a node graph.
- printVersionHashSource()
Prints the node’s source that is hashed and compared at upgrade time.
- removeNodeContext(Name)
Removes the Context from this node with the given Name.
- Parameters:
Name (str) – The name of the Context to be removed.
- Raises:
RuntimeError – Raised if the NodeContext cannot be removed.
- removeTag(Tag, ForceRemove=False)
Removes the given tag to this node.
All system tags are prefixed by underscores(_).Tags with underscores cannot be removed unless ForceRemove is True.
- Parameters:
Tag (str) – The tag to remove.
ForceRemove (bool, optional) – Force removing the tag even if the given tag is considered a system tag. Defaults to False.
- Raises:
RuntimeError – Raised if the given tag cannot be removed.
- setBypassInput(BypassInput)
Set which input value is passed to output bypassing this node.
Bypassing a node effectively disables this node and pass an input straight to the output. This method allows to set which input is passed to the output.
- Parameters:
BypassInput (int) – The index of the input to pass to output instead of processing this node. If -1 is given, no input is passed to the output and the result of processing node is passed to the output.
- setEnabled(Enabled)
Sets the enabled status of the node.
- Parameters:
Enabled (bool) – The enabled status of this node.
- setInputNode(PortName, NodeToConnect, OutputPortName='')
Connects the given node to the given input port name.
- Parameters:
PortName (str) – The name of the port to which the given node is connected.
NodeToConnect (Node) – The node to connect to the input port name. If None, the input port gets disconnected.
OutputPortName (str, optional) – The output port name of NodeToConnect to connect to. If empty or not provided, the first output port will be selected. Defaults to “”.
- Raises:
RuntimeError – Raised if this node and NodeToConnect belong to different node graphs. Also raised if the connection would break DAG.
- setMetadata(Name, Value)
Adds or modifies an item of metadata on the object.
If a metadata item with the given name exists already, its value will be updated. If not, a new one will be created. This overrides
Metadata.setMetadata()- Parameters:
Name (str) – The name of the item
Value (variant) – The value of the item
- Raises:
ValueError – Raised if the type of the value is not supported by the metadata system.
- setName(NewName)
Sets the name of the node.
- Parameters:
NewName (str) – The new name for the node.
- Raises:
ValueError – Raised if the name is invalid.
- setNodeGraphPosition(Position)
Sets the position of this node in its NodeGraph.
The position refers to the top left corner of the node bounding box.
- Parameters:
Position (QPointF) – The position to move the node to.
- Raises:
RuntimeError – Raised if the node cannot have its position set.
- setPortListMode(Mode)
Sets the port list mode of this node.
- Parameters:
Mode (PortListMode) – The mode to set the node to.
- Raises:
ValueError – Raised if given value of Mode is invalid.
RuntimeError – Raised if the node cannot have its port list mode set.
- setSelected(Selected)
Sets whether this node is selected.
- Parameters:
Selected (bool) – If True, this node will be selected. If false, this node wil be deselected.
- setTypeID(TypeID)
Sets the type of this node.
This overwrites the node’s type information. The type information is used for the node upgrade mechanism. Once the node’s typeID is changed, the node will not be upgraded when the original node’s XML file has changed.
- Parameters:
TypeID (str) – The type of node to set this node to.
- tagList()
Returns the list of tags this node holds.
- Returns:
list of str– The list of tags this node holds.
- typeID()
Returns the type of this node.
- Returns:
str– The type of this node.
- class mari.NodeActionCallback
Bases:
objectClass which registers a response to buttons being clicked in the Node properties.
NodeActionCallbackobjects can be inherited and then registered against a name by callingNodeActionCallback.registerCallback(name).>>> class select_node_callback(mari.NodeActionCallback): >>> def execute(self, node): >>> if not node: >>> return >>> >>> node.setSelected(True) >>> >>> callback_instance = select_node_callback() >>> callback_instance.registerCallback("SelectNodeCallback")
Nodes would then be able to reference this callback via an attribute in their XML definition;
<Attribute Name="SelectAction" PrettyName="Select Node" Type="action">SelectNodeCallback</Attribute>This creates a button labelled “Select Node” in the node properties which would select the node when clicked.- __init__()
Initialize the class.
- deregisterCallback()
Deregisters this callback.
- Raises:
RuntimeError – Raised if this callback cannot be deregistered.
- execute(TargetNode)
Override this function in derived classes to respond to the callback being triggered.
- iconPath(TargetNode)
Override this function to return a path to an icon to use on buttons.
- label(TargetNode)
Override this function to return the text to display on buttons.
Leaving undefined or returning an empty QString will use the PrettyName or Name defined in the
NodeXML.
- registerCallback(Name)
Registers this callback into the system.
The Name may only contain alphanumeric, underscore and dash characters.
- Parameters:
Name (str) – The name of this callback, to be referenced by a
Nodein its XML definition (case sensitive).- Raises:
ValueError – Raised if this callback is invalid.
ValueError – Raised if Name is invalid.
RuntimeError – Raised if Name is already taken.
- class mari.NodeContext
Bases:
MetadataProvides shader node graph context functionality.
NodeContextis a patricular context attached to a node. For example, the GLSL context of a node is how the node is represented in GLSL so that the GLSL code is used when rendered in the view port.NodeContextmechanism is used to add some custom contextual information to a node. A common usage would be to attach information about offline renderer so that the node graph can be processed and translated into the language of the offline renderer.Each
NodeContextattached to aNodeis stored inMari.- __init__()
Sets to the settings specified by the given components.
- metadataSupported(MetadataName)
Return whether the given metadata is supported by this context.
A metadata supported by any context will be enabled for editing in the node property UI.
- Parameters:
MetadataName (str) – The name of the metadata to query
- setMetadataSupported(MetadataName, Supported)
Sets whether the metadata of the parent node is supported by this context.
A metadata supported by any context will be enabled for editing in the node property UI.
- Parameters:
MetadataName (str) – The name of the metadata to set the support
Supported (bool) – Whether the specified metadata is supported
- class mari.NodeGraph
Bases:
MetadataProvides shader node graph functionality.
Example Code
This example creates a Perlin node and Merge node, connect them and sets a property
>>> # obtain the root level node graph of the current geo entity >>> import mari >>> nodeGraph = mari.geo.current().nodeGraph() >>> >>> # Obtain the list of node types >>> nodeTypeList = nodeGraph.typeList() >>> >>> # Create perlin noise node >>> perlin = nodeGraph.createNode("Procedural/Noise/Perlin") >>> >>> # Create a merge node >>> merge = nodeGraph.createNode("Layer/Merge") >>> >>> # Connect the perlin node to the Base input of the merge node >>> merge.setInputNode("Base",perlin) >>> >>> # Obtain parameters of the merge node >>> parameterNames = merge.metadataNames() >>> >>> # Set the BlendAmount of merge node to 0.5 >>> merge.setMetadata("Amount",0.5)
This example shows how to create a
PaintNode>>> paintNode = nodeGraph.createPaintNode( 1024, 1024, 8, mari.Color(1.0,1.0,0.0,1.0) )- addNode(NodeToAdd)
Adds the given node to this node graph.
- autoLayoutNodes(Roots)
Automatically lays out nodes.
Automatically lays out the nodes upstream of the given nodes in Roots. If Roots is empty, all root nodes are considered roots.
- Parameters:
Roots (list of
Node) – The root nodes to start auto layout from.
- bakeEmptyAndUpdateOutOfDateBakePoints()
Bake all empty bake point nodes and update any out of date bake point nodes in the graph.
- bakeSelectedBakePoints()
Bake all the selected bake point nodes in the graph, where we bake any of the selected nodes.
- createBakePointNode(Width, Height, Depth, FillColor='nullptr', FileSpace='Image.FILESPACE_NORMAL', ColorConfig='nullptr')
Creates a BakePointNode with given settings.
- Parameters:
Width (int) – The default width of the
ImageSet(ignored forPtex) to bake intoHeight (int) – The default height of the (ignored for
Ptex) to bake intoDepth (int) – The default bit depth of the
ImageSetto bake intoFillColor (Color, optional) – The color to fill the initial
ImageSetto bake into. Defaults to nullptr.FileSpace (Image.FileSpace, optional) – The file space of node, with the default value being “Normal”. Defaults to Image.FILESPACE_NORMAL.
ColorConfig (ColorspaceConfig, optional) – The colorspace configuration. Defaults to nullptr.
- Raises:
RuntimeError – Raised if the PaintNode could not be created
- createChannelNode(Width, Height, Depth, FileSpace='Image.FILESPACE_NORMAL', ColorConfig='nullptr', Name='str')
Creates a new channel node from the settings provided.
This function can be used to create either UV or
Ptexchannel nodes, depending on whether or not the node graph is usingPtex. ForPtexchannels, the Width and Height parameters are ignored.This example shows how to create a channel node:
>>> import mari >>> nodeGraph = mari.geo.current().nodeGraph() >>> >>> cs = mari.current.channel().colorspaceConfig() >>> cs.setColorspace(cs.COLORSPACE_STAGE_NATIVE, "Gamma2.2") >>> >>> n = nodeGraph.createChannelNode(512, 512, 16, mari.Image.FileSpace.FILESPACE_VECTOR, cs)
- Parameters:
Width (int) – The default width of the channel (ignored for
Ptex).Height (int) – The default height of the channel (ignored for
Ptex).Depth (int) – The default bit depth of the channel.
FileSpace (Image.FileSpace, optional) – The file space of the imageset. Defaults to Image.FILESPACE_NORMAL.
ColorConfig (ColorspaceConfig, optional) – The colorspace configuration for color data. Defaults to nullptr.
Name (str, optional) – The name to call the new channel node. This is optional. Defaults to str.
- Raises:
ValueError – Raised, if the depth is not supported, width and height are not supported or the colorspace config is not valid.
RuntimeError – Raised, if the channel could not be created.
- Returns:
Node– The newly created channel node.
- createMaterialTemplate(Model, CreateWithDefaultColors=False)
Creates an empty material node based on the given shader model.
A newly created material template node will have set of outputs to support the given shader model. For example, if the shader model has two inputs, Albedo and Roughness, the material template node will have Albedo and Roughness outputs.
- Parameters:
Model (ShaderModel) – the
ShaderModelto create the material template node for.CreateWithDefaultColors (bool, optional) – Whether to create create default
Colornodes for each output in the MaterialNode. Defaults to False.
- createMultiChannelBakePointNode(Model, Width, Height, Depth, StreamSettingsMap='variant')
Creates a multi channel bake point node based on the given shader model.
A newly created multi channel bake point node will have a set of outputs to support the given shader model. For example, if the shader model has two inputs, Albedo and Roughness, the multi channel bake point node will have Albedo and Roughness outputs.
MultiChannelBakePointNodecan be made with default resolution and depth across all the streams, but optional settings for each stream can be passed in to StreamSettingsMap>>> # obtain the root level node graph of the current geo entity >>> import mari >>> nodeGraph = mari.geo.current().nodeGraph() >>> >>> # Create MultiChannelBakePointNode >>> shaderModel = mari.shader_models.shaderModel("Principled BRDF") >>> colorspaceConfig = mari.ColorspaceConfig() >>> colorspaceConfig.setRaw(True) >>> streamSettings = { ... "BaseColor":{ "Width":512, "Height":512, "Depth":32, "FillColor":mari.Color(1,0,0,1), "FileSpace":mari.Image.FileSpace.FILESPACE_NORMAL, "ColorConfig":colorspaceConfig } ... } >>> mcbp = nodeGraph.createMultiChannelBakePointNode(shaderModel, 4096, 4096, 16, streamSettings )
- Parameters:
Model (ShaderModel) – The
ShaderModelto create the multi channel bake point node for.Width (int) – The width of the bake point
ImageSetHeight (int) – The height of the bake point
ImageSetDepth (int) – The bit depth of the bake point
ImageSetStreamSettingsMap (variant, optional) – The optional map of per stream BakePoint settings. This is a dict of dict, where the key is the
ShaderModelInputname and the value is another map of settings for each BakePoint. See createBakePointNode for the options. Width (int), Height (int), FillColor (mari.Color), FileSpace (mari.Image.FileSpace), ColorConfig (mari.ColorspaceConfig) can be provided as the options. Defaults to variant.
- Raises:
ValueError – Raised, if the depth is not supported, width and height are not supported
- Returns:
GroupNode– The created MultiChannelBakePointNode object
- createMultiChannelBottomTransparencyNode(Model)
Creates a multi-channel bottom transparency node based on the given shader model.
A newly created multi-channel bottom transparency node will have set of outputs to support the given shader model. For example, if the shader model has two inputs, Albedo and Roughness, the multi-channel bottom transparency node will have Albedo and Roughness outputs.
- Parameters:
Model (ShaderModel) – The
ShaderModelto create the multi-channel bottom transparency node for.
- createMultiChannelMergeNode(Model)
Creates a multi channel merge node based on the given shader model.
A newly created multi channel merge node will have set of inputs and output to support the given shader model. For example, if the shader model has two inputs, Albedo and Roughness, the multi channel merge node will have Albedo Base, Roughness Base, Albedo Base, Albedo Over and Mask inputs and Albedo and Roughness outputs.
- Parameters:
Model (ShaderModel) – the
ShaderModelto create the multi channel merge node for.
- createMultiChannelPaintNode(Model, Width, Height, Depth, StreamSettingsMap='variant')
Creates a multi channel paint node based on the given shader model.
A newly created multi channel paint node will have a set of outputs to support the given shader model. For example, if the shader model has two inputs, Albedo and Roughness, the multi channel paint node will have Albedo and Roughness outputs.
MultiChannelPaintNodecan be made with default resolution and depth across all the streams, but optional settings for each stream can be passed in to StreamSettingsMap>>> # obtain the root level node graph of the current geo entity >>> import mari >>> nodeGraph = mari.geo.current().nodeGraph() >>> >>> # Create MultiChannelPaintNode >>> shaderModel = mari.shader_models.shaderModel("Principled BRDF") >>> colorspaceConfig = mari.ColorspaceConfig() >>> colorspaceConfig.setRaw(True) >>> streamSettings = { ... "BaseColor":{ "Width":512, "Height":512, "Depth":32, "FillColor":mari.Color(1,0,0,1), "FileSpace":mari.Image.FileSpace.FILESPACE_NORMAL, "ColorConfig":colorspaceConfig } ... } >>> mcp = nodeGraph.createMultiChannelPaintNode(shaderModel, 4096, 4096, 16, streamSettings )
- Parameters:
Model (ShaderModel) – The
ShaderModelto create the multi channel paint node for.Width (int) – The width of the paint
ImageSetHeight (int) – The height of the paint
ImageSetDepth (int) – The bit depth of the paint
ImageSetStreamSettingsMap (variant, optional) – The optional map of per stream Paint
Nodesettings. This is a dict of dict, where the key is theShaderModelInputname and the value is another map of settings for each Paint. See createPaintNode for the options. Width (int), Height (int), FillColor (mari.Color), FileSpace (mari.Image.FileSpace), ColorConfig (mari.ColorspaceConfig) can be provided as the options. Defaults to variant.
- Raises:
ValueError – Raised, if the depth is not supported, width and height are not supported
- Returns:
GroupNode– The created MultiChannelPaintNode object
- createNode(Type)
Creates a node of the given type. Example Code
This example creates a tri planar node.
>>> # obtain the root level node graph of the current geo entity >>> import mari >>> nodeGraph = mari.geo.current().nodeGraph() >>> >>> # Create a tri planar node "Projection/Tri Planar Projection" >>> nodeGraph.createNode("Projection/Tri Planar Projection") >>> >>> # Create a tri planar node using the deprecated key "Environment/Tri Planar Projection" >>> # This should give you a deprecation warning on your console >>> nodeGraph.createNode("Environment/Tri Planar Projection")
- Parameters:
Type (str) – The type of the node to be created.
- Raises:
RuntimeError – Raised if the given type is not valid.
- createPaintNode(Width, Height, Depth, FillColor='nullptr', FileSpace='Image.FILESPACE_NORMAL', ColorConfig='nullptr')
Creates a paintable node with given settings.
- Parameters:
Width (int) – The default width of the
ImageSet(ignored forPtex)Height (int) – The default height of the (ignored for
Ptex)Depth (int) – The default bit depth of the
ImageSetFillColor (Color, optional) – The color to fill the initial
ImageSetin. Defaults to nullptr.FileSpace (Image.FileSpace, optional) – The file space of node, with the default value being “Normal”. Defaults to Image.FILESPACE_NORMAL.
ColorConfig (ColorspaceConfig, optional) – The colorspace configuration. Defaults to nullptr.
- Raises:
RuntimeError – Raised if the PaintNode could not be created
- deleteNode(NodeToDelete)
Deletes the given node.
- exportNodesAsArchive(DirPath, Nodes, UVIndexList, NoDataBlockCopy=False)
Saves the archive of the given nodes to the given location.
This saves the given nodes in an XML format and saves all dependencies into the given directory If the given location does not exist, it is created. If there are any exising files and directories, they will be deleted.
The nodes saved in the XML file as part of the archive are assigned with new unique UUIDs for sanity. The map returned by this function contains the mapping of the original node UUIDs to the unique UUIDs of the nodes in the XML file. A partial list of the new unique UUIDs can be given as an optional argument to
importNodesFromArchive()to load a partial set of nodes from the archive.- Parameters:
DirPath (str) – The directory path to save the nodes archive to.
Nodes (list of
Node) – The list of nodes to save as archive.NoDataBlockCopy (bool, optional) – Whether to skip copying data blocks. If True, the images are copied only as template, but without texture data. This is False by default. Defaults to False.
UVIndexList (list of
int) – Pass in a list of zero-based UV indices if desired to specify the patches to export images for. If not specified or empty, images will be exported for all indices. The UDIM for a patch is the zero-based UV index plus 1001.
- Returns:
dict– Returns the map of original node UUIDs to the new unique UUIDs stored in the node XML file of the archive.
- static getAllUpstreamNodes(DestNode)
Returns all upstream nodes recursively starting at the given node.
- static getUpstreamNodes(DestNode)
Returns the list of nodes upstream of the given node, only from the root network.
- groupNodes(Nodes)
Groups the given nodes and returns the resulting GroupNode.
- importCustomProcedural(FileName)
Loads the Custom Procedural Node from the specified file path.
- Parameters:
FileName (str) – The absolute path, file name, and extension to import the Custom Procedural from.
- Raises:
IOError – Raised if the input path is invalid, the archive could not be read or extracted or there was an issue in reading the archive.
- Returns:
Node– The imported Custom Procedural node
- importMaterial(FileName)
Loads the Material node from the specified file path.
- Parameters:
FileName (str) – The absolute path, file name, and extension to import the Material from.
- Raises:
IOError – Raised if the input path is invalid, the archive could not be read or extracted or there was an issue in reading the archive.
- Returns:
Node– The imported Material node
- importNodesFromArchive(DirPath, UuidsToLoad, UvIndexMap)
Loads nodes from the archive directory exported by exportNodesAsArchive.
- Parameters:
DirPath (str) – The directory path to the node archive
UuidsToLoad (list of str) – The list of UUID of nodes to partially load from the archive. If empty, all the nodes in the archive are loaded.
UvIndexMap (dict<int,list of
int>) – Map to specify remapping of patches based on UvIndex. E.g. provide {0:[1,2],3:[]} to copy UV patch 0 to 1 and 2, then remove UV patch 3. If this argument is non-empty. It should be all inclusive. Patches not included in this map will be discarded.
- Returns:
list of
Node– Returns the list of nodes imported from the archive
- load(FilePath)
Loades the nodes in the file into this NodeGraph and returns the loaded nodes.
- Parameters:
FilePath (str) – The file path from which the nodes areloaded.
- Returns:
list of
Node– The loaded nodes.
- nodeList(IncludeSystemNodes=True)
Returns a list of the nodes in this node graph.
This example returns a list of nodes in the root nodegraph of the currently-selected geoentity.
>>> # obtain the root level node graph of the current geo entity >>> import mari >>> nodeGraph = mari.geo.current().nodeGraph() >>> >>> # Obtain the list of node types >>> nodeList = nodeGraph.nodeList() >>> >>> # Print the count of nodes >>> print("+ %d nodes found" % (len(nodeList)))
- nodeSelectionChanged()
Signal emitted when a node is selected in the Node Graph.
- nodesFromString(String)
Loads and returns the nodes in the string into this NodeGraph.
This takes in the string returnd by
nodesToString()and loads the nodes into thisNodeGraph.- Parameters:
String (str) – The string in which nodes are contained.
- Returns:
list of
Node– Returns the nodes loaded.
- nodesToString(Nodes)
Returns the string representation of the given nodes.
The returned string can be useful for copy&paste purpose.
save()will save this string into the resulting file.- Parameters:
Nodes (list of
Node) – The nodes to represent in the string.- Raises:
RuntimeError – Raised if any of the Nodes does not belong to this NodeGraph.
- Returns:
str– The string represending the Nodes.
- nodesWithTag(Tag)
Returns the list of nodes having the given Tag.
- Parameters:
Tag (str) – The tag of the nodes to be returned.
- Returns:
list of
Node– The list of nodes having the given Tag.
- parentGeoEntity()
Return the GeoEntity this NodeGraph belongs to if this NodeGraph is not the root level network (i.e. does not belong to a GroupNode).
- Returns:
GeoEntity– The GeoEntity this NodeGraph belongs to.
- parentGroupNode()
Returns the parent GroupNode if this NodeGraph is the child node graph of the GroupNode.
- Returns:
GroupNode– The parent GroupNode
- removeNode(NodeToRemove)
Removes the given node from this node graph.
- save(FilePath, Nodes)
Saves the given node to the specified file.
- Parameters:
FilePath (str) – The file path to save the given nodes to.
Nodes (list of
Node) – The nodes to save to the given file path.
- Raises:
RuntimeError – Raised if any of the Nodes does not belong to this NodeGraph.
- selectedNodeList(IncludeSystemNodes=True)
Returns a list of selected nodes in this node graph.
This example returns the list of selected nodes in the root nodegraph of the currently-selected geoentity.
>>> # obtain the root level node graph of the current geo entity >>> import mari >>> nodeGraph = mari.geo.current().nodeGraph() >>> >>> # Get the selected nodes >>> selectedNodeList = nodeGraph.selectedNodeList() >>> >>> # Print the count of nodes >>> print("+ %d selected nodes found" % (len(selectedNodeList))
- setActiveViewerInput(InputNumber)
Changes the active Viewer node’s input.
- Parameters:
InputNumber (int) – Number of the new active Viewer node’s input. It should be in a range from 0 to 9.
- static swapNodes(NodeA, NodeB)
Swaps the position and connections between two nodes.
The input and output connections are moved based on order, and not by name, as the names may not match. The intention is that only similar node types are swapped.
- Parameters:
- Raises:
RuntimeError – Raised if the two nodes do not belong to the same node graph, have no presence in a node graph, or cannot have their position set.
- teleportBroadcastChannelNameList()
Returns a list of all channels that are being broadcast on.
- Returns:
list of str– The list of channels being broadcast on by Teleport Broadcast nodes.
- teleportNodeBroadcastingOnChannel(ChannelName)
Returns the Teleport Broadcast node broadcasting on the given channel.
- Parameters:
ChannelName (str) – The channel to find the broadcaster of.
- Returns:
BroadcastTeleportNode– The Teleport Broadcast node broadcasting on this channel, if there is one.
- teleportNodesListeningToChannel(ChannelName)
Returns a list of all nodes listening to the channel.
- Parameters:
ChannelName (str) – The channel to find the listeners of.
- Returns:
list of
ReceiverTeleportNode– The Teleport Receiver nodes listening to this channel, if there are any.
- static topologicalSortTo(DestNode, ReverseOrder=False)
Returns the topologically sorted list of nodes towards the DestNode.
- static transferNodes(UVRemap, SourceNodes, SourceGeoVersion, DestinationGeoVersion, SourceUVIndices, DestinationUVIndices, DestinationSize='ImageSet.SIZE_None', BleedEdges=True, FillColor='nullptr')
Copies nodes from one object to another.
The nodes in the source list must belong to the same object. .. code-block:
>>> src_geo_entity = mari.geo.get("Head1") >>> src_geo_version = src_geo_entity.version("v4") >>> src_node_graph = src_geo_entity.nodeGraph() >>> dst_geo_entity = mari.geo.get('Head2') >>> dst_geo_version = dst_geo_entity.version("v1") >>> mari.NodeGraph.transferNodes("UVRemap_Head1v4_to_Head2v1_$UDIM.exr", src_node_graph.selectedNodeList(), ... src_geo_version, dst_geo_version)
- Parameters:
UVRemap (variant) – Either an existing image set or a filename template to a set of uv remapping textures.
SourceNodes (list of
Node) – A list of source nodes to read from.SourceGeoVersion (GeoEntityVersion) – The source geometry version to read from.
DestinationGeoVersion (GeoEntityVersion) – The destination geometry version to write into.
DestinationSize (ImageSet.Size, optional) – Used to specified the image size for all uv indices in the destination channel. If a size is not given then the size will match the source. Defaults to ImageSet.SIZE_None.
BleedEdges (bool, optional) – Turns on or off “full texture bleed” (full patch texture bleed is generated). Defaults to True.
FillColor (Color, optional) – The color used to fill the newly created destination image sets with. Defaults to nullptr.
SourceUVIndices (list of
int) – Which patches in the source to read from. Passing in an empty list will cause all source patches to be read from.DestinationUVIndices (list of
int) – Which patches in the destination to write to. Passing in an empty list will cause all destination patches to be written to.
- Raises:
ValueError – Raised if no nodes were supplied; if any of the nodes are invalid; if the nodes belong to different objects; if any of the patch indices was invalid; if no source or destination geo version was supplied.
- Returns:
list of
Node– A list of destination nodes if the transfer completed successfully, or an empty list otherwise.
- typeList()
Returns a list of the types of nodes that can be created.
- Returns:
list of str– A list of the types of nodes that can be created.
- updateSelectedBakePoints()
Update all the selected bake point nodes in the graph, where we re-bake any of the out of date bake point nodes.
- viewerNode()
Returns the viewer node of the node graph.
Mari‘s viewport shows the result of all the node graph processing up to the viewer node. The viewer node is a node to specify which node to view the node graph processing.- Returns:
Node– The viewer node of the node graph.
- static willConnectionBreakDAG(SourceNode, SourceNodeOutputPort, DestNode, DestNodeInputPort)
Returns whether the given connection would break directed acyclic graph (DAG).
This function tests whether making the connection between SourceNode and DesNode would break directed acyclic graph.
- Parameters:
SourceNode (Node) – The source node of potential connection to test the DAG breakage.
SourceNodeOutputPort (str) – The output port of source node of potential connection to test the DAG breakage.
DestNode (Node) – The destination node of potential connection to test the DAG breakage.
DestNodeInputPort (str) – The input port of destination node of potential connection to test the DAG breakage.
- Raises:
RuntimeError – Raised if the two inputs do not belong to the same node graph.
- Returns:
bool– Whether the connection would break DAG.
- class mari.NodeGraphPalette(rName, pBodyWidget=None)
Bases:
PaletteThe palette class for the Node Graph.
NodeGraphPaletteis aPalettesubclass specific to theNodeGraphPaletteYou can obtain theNodeGraphPaletteobject through thePaletteManagerExample Code
>>> # This example shows how to obtain the NodeGraphPalette object >>> import mari >>> node_graph_palette = mari.palettes.find("Node Graph")
- closeTab(Index)
Closes the Node Graph tab specified by the tab Index.
- Parameters:
Index (int) – the index of the
NodeGraph tab to close
- currentTabIndex()
Returns the index of the current Node Graph tab.
- Returns:
int– The index of the current Node Graph tab
- indexForNodeGraph(NodeGraphObject)
Returns the index of the NodeGraphView for the given NodeGraph object.
Note that this function returns the tab index of the given
NodeGraphobject. If such tab already exists, then the index is just returned. If there is no open tab for the givenNodeGraphobject, this function will create a tab.
- nodeGraphView(TabIndex)
Returns the NodeGraphView object at the tab specified by the index.
- Parameters:
TabIndex (int) – The index of the tab to return the
NodeGraphViewobject for.- Returns:
NodeGraphView– The NodeGraphView object at the tab specified by the index.
- nodeGraphViewList()
Returns the list of NodeGraphView objects.
NodeGraphViewobjects represent the views to eachNodeGraphin the tabs of theNodeGraph palette.- Returns:
list of
NodeGraphView– The list of NodeGraphView objects.
- class mari.NodeGraphView
Bases:
objectThe view class for a NodeGraph object.
The
NodeGraphPaletteobject contains tabs forNodeGraphobjects This class represents a view forNodeGraphobjects inside each tab.Example Code
>>> # This example shows how to shift the center of view by 100 units >>> import mari >>> node_graph_palette = mari.palettes.find("Node Graph") >>> current_view = node_graph_palette.nodeGraphView(node_graph_palette.currentTabIndex()) >>> center = current_view.center() >>> center.setX(center.x()+100) >>> current_view.setCenter(center)
- center()
Returns the center position of this NodeGraphView.
- Returns:
QPointF– The center position of this NodeGraphView.
- nodeGraph()
Returns the NodeGraph object this NodeGraphView represents.
- Returns:
NodeGraph– The NodeGraph object this NodeGraphView represents.
- posFromGlobalPos(GlobalPos)
Returns the position in this NodeGraphView mapped from the global position.
- Parameters:
GlobalPos (QPoint) – The global position in the screen coordinates to map from.
- Returns:
QPointF– The position in this NodeGraphView mapped from the global position.
- setCenter(Center)
Sets the center position of this NodeGraphView.
- Parameters:
Center (QPointF) – The center position to set to.
- setZoomLevel(ZoomLevel)
Sets the zoom level of this NodeGraphView.
- Parameters:
ZoomLevel (float) – The zoom level to set to.
- zoomLevel()
Returns the zoom level of this NodeGraphView.
- Returns:
float– The zoom level of this NodeGraphView.
- class mari.NodeManager
Bases:
object- customProceduralNodeExported(pCustomProceduralNode, ExportPath)
This is emitted after a CustomProceduralNode has been exported.
- Parameters:
pCustomProceduralNode (CustomProceduralNode) – The
CustomProceduralNodeexportedExportPath (str) – The path to which the
CustomProceduralNodehas been exported
- customProceduralNodeImported(pCustomProceduralNode, ImportPath)
This is emitted after a CustomProceduralNode has been imported.
- Parameters:
pCustomProceduralNode (CustomProceduralNode) – The
CustomProceduralNodeimportedImportPath (str) – The path from which the
CustomProceduralNodehas been imported
- materialNodeExported(pMaterialNode, ExportPath)
This is emitted after a MaterialNode has been exported.
- Parameters:
pMaterialNode (MaterialNode) – The
MaterialNodeexportedExportPath (str) – The path to which the
MaterialNodehas been exported
- materialNodeImported(pMaterialNode, ImportPath)
This is emitted after a MaterialNode has been imported.
- Parameters:
pMaterialNode (MaterialNode) – The
MaterialNodeimportedImportPath (str) – The path from which the
MaterialNodehas been imported
- nodeCreated(pNewNode)
This is emitted after a new node has been created.
- Parameters:
pNewNode (Node) – The newly-added node
- nodeNameChanged(pNode, OldName, NewName)
This is emitted after a node has had it’s name modified.
- Parameters:
pNode (Node) – The node that’s been renamed
OldName (str) – The old name of the node.
NewName (str) – The new name of the node.
- typeList()
Returns a list of the types of nodes that can be created.
- Returns:
list of str– A list of the types of nodes that can be created.
- class mari.ObjectSelectionGroup
Bases:
SelectionGroupA specialised selection group that consists of objects.
- class mari.OcioNamedTransformFilter
Bases:
PostFilterA post processing filter that uses OCIO NamedTransforms for color management.
OcioNamedTransformFilterobjects can be created by callingPostFilterCollection::createOcioNamedTransform(). This filter handles OCIO processor creation, GPU shader generation, and texture management internally, providing a simplified interface for OCIO-based color transformations.Example Code
>>> # This example creates a new OcioNamedTransformFilter object >>> import mari >>> filter_collection = mari.gl_render.createPostFilterCollection("New Filter Collection") >>> ocio_filter = filter_collection.createOcioNamedTransform("OCIO Filter") >>> success = ocio_filter.buildFromOcioConfig(config_string, "my_named_transform") >>> mari.gl_render.deletePostFilterCollection(filter_collection)
- buildFromAnalyticalGlsl(Declaration, Fragment)
Build the filter from pre-written analytical GLSL, bypassing the OCIO LUT path.
This clears any existing LUT textures and installs the provided GLSL directly. Use this to avoid the domain-clamping banding that occurs when using finite 3D LUTs for HDR-capable view transforms such as ACES RRT+ODT Rec.709.
- Parameters:
Declaration (str) – GLSL function definition(s) to prepend to the shader
Fragment (str) – GLSL fragment body (receives vec4 Out, must end with })
- Returns:
bool– True if the filter was built successfully
- buildFromOcioConfig(ConfigStr, NamedTransformName, SearchPaths, WorkingDir, LutSize, Extrapolate=False, ForceShaderBuild=False, Swizzle='str')
No description
- Parameters:
ConfigStr (str)
NamedTransformName (str)
SearchPaths (list of str)
WorkingDir (str)
LutSize (int)
Extrapolate (bool, optional)
ForceShaderBuild (bool, optional)
Swizzle (str, optional)
- clear()
Clear the filter completely, removing all shader templates and textures.
This method clears the shader declaration and fragment templates, deletes all GL textures, and resets the filter to an empty state.
- clearCache()
Clear all cached data and force a rebuild on next buildFromOcioConfig call.
- ocioDebug(Message)
Emitted when debug information is available.
- Parameters:
Message (str) – Debug message
- ocioError(Message)
Emitted when an OCIO error occurs during processing.
- Parameters:
Message (str) – Error message describing what went wrong
- ocioWarning(Message)
Emitted when an OCIO warning occurs during processing.
- Parameters:
Message (str) – Warning message
- class mari.OpenColorIO
Bases:
objectHandles the OpenColorIO colorspace transforms in the application.
- COLOR_PICKER_COLOR_MANAGER = 1
The color values are converted using the current color profile set on the color manager.
- Type:
int
- COLOR_PICKER_OCIO = 2
The color values are converted to the current default monitor colorspace set on the current project using OCIO.
- Type:
int
- COLOR_PICKER_RAW = 0
No colorspace conversion is applied. The raw values are displayed on the monitor.
- Type:
int
- class ColorPickerMode
Bases:
objectThese are used to define the various modes that the color swatches and pickers can be displayed in.
- COLOR_PICKER_COLOR_MANAGER = 1
The color values are converted using the current color profile set on the color manager.
- Type:
int
- COLOR_PICKER_OCIO = 2
The color values are converted to the current default monitor colorspace set on the current project using OCIO.
- Type:
int
- COLOR_PICKER_RAW = 0
No colorspace conversion is applied. The raw values are displayed on the monitor.
- Type:
int
- static analyticalViewEntries(config)
Return all registered analytical view entries applicable to the given OCIO config.
Returns a list of (label, display, view, glsl_declaration, func_name) tuples for each registered entry whose config_matcher matches config. ‘label’ is the combobox string, e.g. ‘sRGB (ACES) - Analytical’.
- Parameters:
config – A PyOpenColorIO.Config object for the currently active OCIO config.
- Returns:
List of (label, display, view, glsl_declaration, func_name) tuples. Empty if no registered entries match the given config.
- colorPickerMode()
Returns the method in which we are to display color swatches and pickers.
- Returns:
ColorPickerMode– The mode of the color swatches and pickers.
- colorPickerModeChanged(Mode)
This is emitted after the method in which we are to display color swatches and pickers is modified.
- Parameters:
Mode (OpenColorIO.ColorPickerMode)
- colorspace(Config, Index)
Returns the colorspace at a position within an OCIO config file.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
Index (int) – The index of the colorspace to return.
- Raises:
ValueError – Raised if the OCIO config file is invalid or the index is out of range.
- Returns:
str– The colorspace at a particular position in the OCIO config file.
- colorspaceCount(Config)
Returns the number of colorspaces within an OCIO config file.
This doesn’t include the extra options for the stages such as ‘Automatic’.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
- Raises:
ValueError – Raised if the OCIO config file is invalid.
- Returns:
int– The number of colorspaces in the OCIO config file.
- colorspacePrettyNames(Config)
Returns a list of all colorspaces and roles within an OCIO config file for use in user interfaces and the like.
Each entry in the list is a path which is based on the colorspace family or whether colorspace is a role. Roles in the list will also contain their corresponding colorspace in brackets.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
- Raises:
ValueError – Raised if the OCIO config file is invalid.
- Returns:
list of str– The colorspace list for the OCIO config file.
- configDescription(Config)
Returns the internal description of an OCIO config file.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
- Raises:
ValueError – Raised if the OCIO config file is invalid.
- Returns:
str– The internal description of the OCIO config file.
- currentColorspaceConfig()
Returns the current colorspace configuration.
This will be the configuration of the current active image set. If no image set is active then the configuration of the current channel is returned. If no current configuration is active then None is returned.
- Returns:
ColorspaceConfig– The current colorspace defaults.
- currentColorspaceDefaults()
Returns the current colorspace defaults.
When a project is opened then this will be the colorspace defaults of the project. And if a project is not opened this will the global defaults for
Mari.- Returns:
ColorspaceDefaults– The current colorspace defaults.
- defaultConfig()
Returns the name of the standard OCIO config file used by default.
- Returns:
str– The name of the default OCIO config file.
- get3DLutValuesFromColorSpaceTransform(Config, Input, Output, LutSize)
Utility function to obtain the 3D LUT values from an OpenColorIO colorspace transform.
The PyOpenColorIO.GpuShaderDesc.Texture3D.getValues() function depends on numpy at run-time. This function provides the ability to query the 3D LUT values directly from the internal
OpenColorIOlibrary, where numpy module is not present- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
Input (str) – The input colorspace
Output (str) – The output colorspace
LutSize (int) – The length of 3D lut along one dimension
- Returns:
tuple of
float– The 3D lut values
Deprecated
This function will be removed in a future version. Please use PyOpenColorIO.GpuShaderDesc.Texture3D.getValues() instead.
- get3DLutValuesFromDisplayViewTransform(Config, Src, View, Display, LutSize)
Utility function to obtain the 3D LUT values from an OpenColorIO display-view transform.
The PyOpenColorIO.GpuShaderDesc.Texture3D.getValues() function depends on numpy at run-time. This function provides the ability to query the 3D LUT values directly from the internal
OpenColorIOlibrary, where numpy module is not present- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
Src (str) – The source colorspace
View (str) – The view transorm
Display (str) – The display
LutSize (int) – The length of 3D lut along one dimension
- Returns:
tuple of
float– The 3D lut values
Deprecated
This function will be removed in a future version. Please use PyOpenColorIO.GpuShaderDesc.Texture3D.getValues() instead.
- get3DLutValuesFromFileTransform(Config, LutFile, LutSize)
Utility function to obtain the 3D LUT values from an OpenColorIO file transform.
The PyOpenColorIO.GpuShaderDesc.Texture3D.getValues() function depends on numpy at run-time. This function provides the ability to query the 3D LUT values directly from the internal
OpenColorIOlibrary, where numpy module is not present- Parameters:
Config (str) – The path to the config file
LutFile (str) – The path to the lut file
LutSize (int) – The length of 3D lut along one dimension
- Returns:
tuple of
float– The 3D lut values
Deprecated
This function will be removed in a future version. Please use PyOpenColorIO.GpuShaderDesc.Texture3D.getValues() instead.
- hasColorspace(Config, Name)
Indicates whether a colorspace or role is present within an OCIO config file.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
Name (str) – The name of the colorspace or role to look for.
- Returns:
bool– True if the colorspace is present, false otherwise.
- hasRole(Config, Name)
Indicates whether a role is present within an OCIO config file.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
Name (str) – The name of the role to look for.
- Raises:
ValueError – Raised if the OCIO config file is invalid.
- Returns:
bool– True if the role is present, false otherwise.
- isConfigValid(Config)
Indicates whether an OCIO config file is valid.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
- Returns:
bool– True if the OCIO config file is valid, false otherwise.
- isShaderTransformAccurate(Config, InputColorspace, OutputColorspace, LutSize)
Returns true if the given transform is accurate when run in shaders on the GPU.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
InputColorspace (str) – The colorspace of the input image
OutputColorspace (str) – The colorspace of the output image
LutSize (int) – Ignored.
- Raises:
ValueError – Raised if the OCIO config file or either the input and output colorspaces are invalid.
- Returns:
bool– Always returns true.
Deprecated
This method always returns true. The Transform Accuracy feature has been removed.
- isStandardConfig(Name)
Returns true if a name is one of the standard OCIO config files packaged with Mari.
- Parameters:
Name (str) – The name to check.
- Returns:
bool– True if the name is a standard OCIO config.
- isTargetScalar()
Returns whether or not the current active image set is used for scalar or color data.
- Returns:
bool– True if scalar or false if color.
- isTransformValid(Config, InputColorspace, OutputColorspace)
Returns true if a colorspace transform is valid.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
InputColorspace (str) – The colorspace of the input color
OutputColorspace (str) – The colorspace of the output color
- Raises:
ValueError – Raised if the OCIO config file or either the input and output colorspaces are invalid.
- Returns:
bool– True if the transform is valid; false otherwise.
- isViewerScalar()
Returns whether or not the canvas is currently displaying scalar or color data.
- Returns:
bool– True if scalar or false if color.
- static onAnalyticalViewTransformRegistered(callback)
Subscribe to be notified when a new analytical view transform is registered.
Subscribers are called with no arguments immediately after each call to registerAnalyticalViewTransform. Use this to refresh UI that needs to reflect newly added entries.
If entries are already in the registry when this is called, the callback is fired once immediately so that a subscriber that registers after some entries exist does not miss them.
- Parameters:
callback – A callable that takes no arguments.
- parseColorspaceFromString(Config, Str)
Returns the longest, right-most, colorspace substring from the given string.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
Str (str) – The string to parse for colorspace.
- Raises:
ValueError – Raised if the OCIO config file or either the input and output colorspaces are invalid.
- Returns:
str– The longest, right-most, colorspace substring.
- static registerAnalyticalViewTransform(config_matcher, display, view, glsl_declaration, func_name, label_suffix='Analytical')
Register a custom analytical GLSL function as an opt-in View Transform combobox entry.
When the active OCIO config matches config_matcher, an extra entry is added to the View Transform dropdown: ‘{view} ({display}) - {label_suffix}’. Selecting it calls func_name (defined in glsl_declaration) on the GPU instead of the normal OCIO LUT path.
Subscribers registered via onAnalyticalViewTransformRegistered are notified immediately after the new entry is appended, allowing live UI to refresh without manual intervention.
Note: entries are config-specific. An entry only appears in the UI when the currently active OCIO config satisfies config_matcher. If no project is open yet, or the open project uses a different config, the entry remains hidden until a matching config is loaded. onAnalyticalViewTransformRegistered handles the timing gap between toolbar initialization and later module imports; it does not bypass config matching.
- Parameters:
config_matcher – A callable(config) -> bool, or a str that is matched as a substring of config.getWorkingDir(). Use a callable for complex logic.
display – OCIO display name, e.g. ‘ACES’.
view – OCIO view name, e.g. ‘sRGB’.
glsl_declaration – GLSL function definition string. The function must have the signature: vec4 func_name(vec4 inVal) { … }
func_name – The GLSL function name to call, e.g. ‘aces_srgb_analytical’.
label_suffix – Text appended after ‘ - ‘ in the combobox label (default: ‘Analytical’).
- registerConfigUiAllowlist(ConfigFilePath, Allowlist)
Registers the allowlist of colorspace names for the Given ConfigFilePath.
Some color configs list many colorspaces. Sometimes only a small subset of colorspaces need listing for common usage. This function can be used to allowlist the colorspaces to display for colorspace combo-boxes.
- Parameters:
ConfigFilePath (str) – The path of the config.ocio file to register the allowlist for
Allowlist (list of str) – The list of colorspaces to display in colorspace combo-boxes
- role(Config, Index)
Returns the role at a position within an OCIO config file.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
Index (int) – The index of the role to return.
- Raises:
ValueError – Raised if the OCIO config file is invalid or the index is out of range.
- Returns:
str– The role at a particular position in the OCIO config file.
- roleCount(Config)
Returns the number of roles within an OCIO config file.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
- Raises:
ValueError – Raised if the OCIO config file is invalid.
- Returns:
int– The number of roles in the OCIO config file.
- setColorPickerMode(Mode)
Sets the method in which we are to display color swatches and pickers.
- Parameters:
Mode (ColorPickerMode) – The mode of the color swatches and pickers.
- Raises:
ValueError – Raised if the mode is invalid.
- setShaderTransformAccuracy(Config, InputColorspace, OutputColorspace, MinimumLutSize)
Sets the minimum size the 3D LUT needs to be for the transform to be considered accurate when run in shaders on the GPU.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
InputColorspace (str) – The colorspace of the input image
OutputColorspace (str) – The colorspace of the output image
MinimumLutSize (int) – Ignored.
Deprecated
This method is a no-op. The Transform Accuracy feature has been removed.
- setShaderTransformCode(Config, InputColorspace, OutputColorspace, Code)
Sets the associated GLSL source code to use, for the given transform, when run on the GPU.
This overrides the code returned by the
OpenColorIOlibrary and can be used to give a more optimal transform.>>> # This example overrides the 'sRGB' to 'linear' transform to avoid the use of the standard 3D LUT texture and give better accuracy >>> mari.ocio.setShaderTransformCode( >>> 'nuke-default', >>> 'sRGB', >>> 'linear', >>> ''' >>> vec3 v1 = #Input.rgb; >>> vec3 mask = vec3(greaterThan(v1, vec3(0.04045))); >>> vec3 v2 = v1 / vec3(12.92); >>> v1 = pow((v1 + vec3(0.055)) / vec3(1.055), vec3(2.4)); >>> #Output = vec4(mix(v2, v1, mask), #Input.a); >>> ''')
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
InputColorspace (str) – The colorspace of the input image
OutputColorspace (str) – The colorspace of the output image
Code (str) – The GLSL source code to use for the transform on the GPU.
- Raises:
ValueError – Raised if the OCIO config file or either the input and output colorspaces are invalid. Also if the shader input or shader output are missing from the given GLSL source code.
- shaderTransformUsesLut(Config, InputColorspace, OutputColorspace)
Returns true if the given transform requires a 3D LUT when run in shaders on the GPU.
This can be useful in determining how accurate the transform will be when run on the GPU as a 3D LUT is only an approximation so can introduce more error.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
InputColorspace (str) – The colorspace of the input image
OutputColorspace (str) – The colorspace of the output image
- Raises:
ValueError – Raised if the OCIO config file or either the input and output colorspaces are invalid.
- Returns:
bool– Whether the corresponding colorspace transform requires the use a 3D LUT texture on the GPU.
- standardConfigPath(Config)
Returns the absolute path of a standard OCIO config file packaged with Mari.
- Parameters:
Config (str) – The name of a standard OCIO config file packaged with
Mari.- Raises:
ValueError – Raised if ‘Config’ is not the name of a standard OCIO config file packaged with Mari.
- Returns:
str– The absolute path to the OCIO config file.
- standardConfigs()
Returns the names of the standard OCIO config files packaged with Mari.
- Returns:
list of str– A list of all standard OCIO config files packaged with Mari.
- targetScalarChanged(Scalar)
This is emitted whenever the current target changes from being color to scalar or vice versa.
- Parameters:
Scalar (bool) – The new target is scalar image data or false if color image data.
- toColorspace(Config, Role)
Returns the corresponding colorspace for a role.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
Role (str) – The role to return the corresponding colorspace for.
- Raises:
ValueError – Raised if the OCIO config file is invalid.
- Returns:
str– The colorspace that corresponds to the role.
- toPrettyName(Config, Name)
Returns the corresponding pretty name for the given colorspace or role.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
Name (str) – The name of the colorspace or role to look for.
- Raises:
ValueError – Raised if either the OCIO config file or the colorspace is invalid.
- Returns:
str– The pretty name that corresponds to the colorspace or role.
- transformColor(Config, InputColorspace, OutputColorspace, InputColor)
Applies a colorspace transform on a color value.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
InputColorspace (str) – The colorspace of the input color
OutputColorspace (str) – The colorspace of the output color
InputColor (Color) – The color value to transform.
- Raises:
ValueError – Raised if the OCIO config file or either the input and output colorspaces are invalid.
- Returns:
Color– The resulting transformed output color value
- transformImage(Config, InputColorspace, OutputColorspace, InputImage)
Applies a colorspace transform from the given input colorspace to the given output colorspace on the given MriImage.
- Parameters:
Config (str) – The name of a standard OCIO config file or the path to a custom one.
InputColorspace (str) – The colorspace of the input image
OutputColorspace (str) – The colorspace of the output image
InputImage (Image) – The image to transform.
- Raises:
ValueError – Raised if the OCIO config file or either the input and output colorspaces are invalid.
- Returns:
Image– The resulting transformed output image
- viewerScalarChanged(Scalar)
This is emitted whenever the viewer/canvas changes from displaying color to scalar or vice versa.
- Parameters:
Scalar (bool) – The viewer is displaying scalar image data or false if color image data.
- class mari.PaintBuffer
Bases:
PropertySourceThe paint buffer is the screen aligned plane that users paint onto.
It can be accessed from the
CanvasManager- for example:mari.canvases.paintBuffer()Example Code
>>> # This example shows how to set or get the paint buffer depth >>> import mari >>> paint_buffer = mari.canvases.paintBuffer() >>> original_depth = paint_buffer.depth() >>> paint_buffer.setDepth(8) >>> paint_buffer.depth() 8 >>> paint_buffer.setDepth(original_depth)
- class BufferDepth
Bases:
objectBit depth options for the paint buffer.
- DEPTH_BYTE = 8
Standard eight bit depth.
- Type:
int
- DEPTH_FLOAT = 32
Full float depth.
- Type:
int
- DEPTH_HALF = 16
Half-float depth.
- Type:
int
- DEPTH_BYTE = 8
Standard eight bit depth.
- Type:
int
- DEPTH_FLOAT = 32
Full float depth.
- Type:
int
- DEPTH_HALF = 16
Half-float depth.
- Type:
int
- MIRROR_NONE = 0
Default. No mirrored strokes are created.
- Type:
int
- MIRROR_X = 1
Paint strokes are mirrored across the middle of the buffer on the x-axis i.e. left to right and right to left.
- Type:
int
- MIRROR_XY = 3
Paint strokes are mirrored both on the x and y axis.
- Type:
int
- MIRROR_Y = 2
Paint strokes are mirrored across the middle of the buffer on the y-axis i.e. top to bottom and bottom to top.
- Type:
int
- class Mirroring
Bases:
objectThis enum controls mirroring in the paint buffer.
- MIRROR_NONE = 0
Default. No mirrored strokes are created.
- Type:
int
- MIRROR_X = 1
Paint strokes are mirrored across the middle of the buffer on the x-axis i.e. left to right and right to left.
- Type:
int
- MIRROR_XY = 3
Paint strokes are mirrored both on the x and y axis.
- Type:
int
- MIRROR_Y = 2
Paint strokes are mirrored across the middle of the buffer on the y-axis i.e. top to bottom and bottom to top.
- Type:
int
- aboutToBake()
This is emitted just before baking occurs.
- aboutToClear()
This is emitted just before the paint buffer is cleared.
- bake()
Bakes the paint from the buffer down onto the currently selected channel.
This bakes paint from all streams.
- Returns:
bool– True if any projection occurred. If the buffer is empty, this will return false
- bakeAndClear()
Bakes the paint from the buffer down onto the currently selected channel and then forces it to be cleared.
This bakes and clears paint from all streams.
- Returns:
bool– True if any projection occurred. If the buffer is empty, this will return false
- baked()
This is emitted just after baking occurs.
- clampColors()
Returns the color clamping behavior of the projector.
This is a global setting that applies to all streams.
- Returns:
bool– True if the colors are clamped to the 0..1 range on output
- clear()
Clears all paint from the buffer.
This clears paint from all streams.
- cleared()
This is emitted just after the paint buffer has been cleared.
- compImage(CompImage, Undoable=True, BlendMode='Normal')
No description
- Parameters:
CompImage (QImage)
Undoable (bool, optional)
BlendMode (str, optional)
- depth()
Returns the current bit depth of the buffer.
- Returns:
BufferDepth– The current bit depth
- depthChanged(NewDepth)
This is emitted when the depth of the buffer is changed.
- Parameters:
NewDepth (PaintBuffer.BufferDepth) – The new depth of the paint buffer
- getPaint()
Returns a QImage containing the current paint buffer.
This captures the paint in the paint buffer and returns it as an 8 bit RGBA QImage. When Multi-Paint is enabled, this returns the paint from the primary stream.
QImage does not support higher bit depths, so any float or half data will be reduced to 8 bits.
- Returns:
QImage– A QImage which is the same size as the paint buffer resolution, and contains 8 bit RGBA data
- isDirty()
Indicates whether the buffer has paint in it.
- Returns:
bool– True if the paint buffer has some paint in it, or false if not
- loadPaint(Paint)
Loads an Image into the paint buffer.
When Multi-Paint is enabled, this loads the image into the primary stream.
- mirroring()
Return the mirroring mode for the paint buffer.
- Returns:
Mirroring– The current mirroring state of the paint buffer
- pickColor(x, y)
Pick a color from the paintbuffer.
This allows a script to pick pixel color values from the paintbuffer. The x and y position must be in the range returned by
resolution()The color returned may be a HDR value with r,g,b values above 1.0 This method is relatively slow to execute and should not be used to the query lots of pixels When Multi-Paint is enabled, this picks the color from the primary stream.#Pick a pixel in the middle of the screen Size = mari.canvases.paintBuffer().resolution() c = mari.canvases.paintBuffer().pickColor(Size.width()/2, Size.height()/2) print(c.toString())
- Parameters:
x (int) – The x coordinate of the pixel.These coordinates are relative to the top left corner of the canvas
y (int) – The y coordinate of the pixel.These coordinates are relative to the top left corner of the canvas
- Raises:
ValueError – Emitted if x or y are outside of the range (0,0)-resolution()
- Returns:
Color– The color of the pixel at the paintbuffer location (x,y)
- resolution()
Returns the current resolution of the buffer.
This returns the resolution that is consistent across all streams.
- Returns:
QSize– The current resolution of the paint buffer. This will be one of the values reported by supportedResolutions()
- resolutionChanged(Resolution)
This is emitted when the paint buffer is resized.
- Parameters:
Resolution (QSize) – The new size of the buffer in pixels
- restoreContent()
Restores the content of the paint buffer from the special internal clipboard.
When Multi-Paint is enabled, this restores the paint to the primary stream.
- Raises:
RuntimeError – Raised if there is no saved content in the special internal clipboard
- rotation()
Returns the rotation of the buffer in degrees.
- Returns:
float– The angle of rotation of the paint buffer in degrees
- rotationChanged(Angle)
This is emitted when the rotation of the paint buffer changes.
- Parameters:
Angle (float) – The new angle of rotation of the paint buffer in degrees
- saveContent()
Saves the content of the paint buffer to the special internal clipboard.
When Multi-Paint is enabled, this saves the paint from the primary stream.
- savePaint()
Saves the content of the paint buffer to an Image in the ImageManager.
When Multi-Paint is enabled, this saves the paint from the primary stream.
- Returns:
Image– the Image object of the saved paint buffer content
- scale()
Returns the scaling factor of the buffer.
This is independent of the resolution.
- Returns:
QSizeF– The scaling factor of the paint buffer in world space
- scaleChanged(Scale)
This is emitted when the scale of the paint buffer changes.
- Parameters:
Scale (QSizeF) – The new scaling factor of the paint buffer
- setClampColors(ClampColors)
Sets the color clamping behavior of the projector.
This is a global setting that applies to all streams.
- Parameters:
ClampColors (bool) – True to clamp the colors to the 0..1 range
- setDepth(Depth)
Sets the bit depth of the buffer.
This must be one of the options defined in BufferDepth. This sets the depth for all streams.
- Parameters:
Depth (BufferDepth) – The new bit depth of the buffer
- setMirroring(Mirror)
Set the mirroring scheme for the paint buffer.
- Parameters:
Mirror (Mirroring) – The new mirroring mode
See also
Mirroring
- setPaint(PaintImage)
Sets the contents of the paint buffer with a QImage.
This takes an RGBA QImage and copies it into the paint buffer. The QImage must be RGBA and the same resolution as the paint buffer (see
resolution()). When Multi-Paint is enabled, this sets the paint in the primary stream.8 bit images will be converted to 16 or 32 bit where appropriate.
- Parameters:
PaintImage (QImage) – The image to load into the paint buffer
- Raises:
ValueError – Raised if the image was invalid, or not of the correct resolution.
- Returns:
bool– True if the paint was updated from the given image, or false otherwise
Attention
Any existing paint will be replaced without warning, so please be careful.
- setResolution(Size)
Sets the resolution of the buffer.
This must be one of the resolutions returned by
supportedResolutions(). This sets the resolution for all streams.- Parameters:
Size (QSize)
- Raises:
ValueError – Raised if the requested resolution is not supported.
- Returns:
bool– True if the resolution was set, or if the buffer was already the requested size; false if the resolution could not be set for any reason other than not being in the supported list
- setRotation(Angle)
Sets the angle of rotation of the buffer in degrees.
Angles outside the range [0, 360] will be replaced with values wrapped into that range. For example, after calling setRotation(-10),
rotation()will return 350.- Parameters:
Angle (float) – The rotation angle.
- setScale(Size)
Sets the scaling factor of the buffer.
- This does not change the resolution.
mari.canvases.paintBuffer().setScale(PySide6.QtCore.QSizeF(1,1))
- Parameters:
Size (QSizeF) – The new scaling factor of the paint buffer.
- setTranslation(Translation)
Sets the translation, or offset from the origin, of the buffer.
mari.canvases.paintBuffer().setTranslation(PySide6.QtCore.QPointF(0.1,0.1))- Parameters:
Translation (QPointF) – The new translation of the paint buffer
- supportedResolutions()
Returns the list of resolutions that the paint buffer supports.
- Returns:
list of
QSize– A list of valid resolutions (in pixels) for the paint buffer
- translation()
Returns the translation, or offset from the origin, of the buffer.
- Returns:
QPointF– The translation of the paint buffer in screen coordinates
- translationChanged(Translation)
This is emitted when the translation of the buffer changes.
- Parameters:
Translation (QPointF) – The new translation of the paint buffer
- class mari.PaintNode
Bases:
NodeRepresents an image set node.
Example Code
This example shows how to create a
PaintNode>>> import mari >>> nodeGraph = mari.geo.current().nodeGraph() >>> paintNode = nodeGraph.createPaintNode( 1024, 1024, 8, mari.Color(1.0,1.0,0.0,1.0) )
This example obtains a paint node from the node graph of the current geo entity and
>>> for node in nodeGraph.nodeList(): ... if node.isPaintNode(): ... mari.app.log( "Found PaintNode : "+node.nodeName() )
- MANAGED_BY_CHANNEL = 0
Properties of the paint node is managed automatically by its channel.
- Type:
int
- MANAGED_BY_SELF = 1
Properties of the paint node is managed by itself, independent of a channel.
- Type:
int
- class ManagementType
Bases:
objectThis determines how the properties of the node are managed.
- MANAGED_BY_CHANNEL = 0
Properties of the paint node is managed automatically by its channel.
- Type:
int
- MANAGED_BY_SELF = 1
Properties of the paint node is managed by itself, independent of a channel.
- Type:
int
- bleed()
Returns whether the imageset of this node bleeds.
- Returns:
bool– Bleed toggle.
- bleedChanged(Bleed)
This is emitted when the bleed property of this node changes.
- Parameters:
Bleed (bool)
- colorspaceConfig()
Returns the colorspace configuration of this node.
- Returns:
ColorspaceConfig– The colorspace configuration.
- colorspaceConfigChanged(Config)
This is emitted after the colorspace config is modified for this object.
- Parameters:
Config (ColorspaceConfig)
- depth()
Returns the bit depth of the paint of this node.
- depthChanged(BitDepth)
This is emitted when the bit depth of this node changes.
- Parameters:
BitDepth (Image.Depth)
- fileSpace()
Returns the file space of this node, as an enum Image::FileSpace.
- Returns:
Image.FileSpace– The preferred file space of the node.
- fileSpaceChanged(FileSpace)
This is emitted when the file space of this node changes.
- Parameters:
FileSpace (Image.FileSpace)
- fillColor()
Returns the fill color, set to the imageset at creation time.
- Returns:
Color– The fill color.
- imageSet()
Returns the image set this node holds.
- Raises:
RuntimeError – Raised if the image set cannot be found.
- Returns:
ImageSet– The image set this node holds.
- isPaintNode()
Returns whether this node is a paint node.
- Returns:
bool– Whether this node is a paint node
- management()
Returns the way this node is managed by, as ManagementType.
- Returns:
ManagementType– Method by which this node is managed by.
- managementChanged(Management)
This is emitted when the management property of this node changes.
- Parameters:
Management (PaintNode.ManagementType)
- setBleed(Bleed)
Sets whether the imageset paint of this node should bleed.
- Parameters:
Bleed (bool) – The way this node properties are managed by, set by the enum ManagedByChannel.
- setColorspaceConfig(Config)
Sets the colorspace configuration of this node.
- Parameters:
Config (ColorspaceConfig) – The colorspace configuration.
- Raises:
ValueError – Raised if the colorspace configuration is invalid or the node is managed by a channel.
- setDepth(NewDepth)
Sets the bit depth of this node.
- Parameters:
NewDepth (Image.Depth) – The new bit depth.
- Raises:
RuntimeError – Raised if the input depth is invalid or the node is managed by a channel.
- setFileSpace(FileSpace)
Sets the file space of this node.
- Parameters:
FileSpace (Image.FileSpace) – The file space of this node, set by the enum
Image::FileSpace.- Raises:
RuntimeError – Raised if the input FileSpace is invalid or the node is managed by a channel.
- setManagement(ManagedBy)
Sets the way this node is managd by.
This node can either managed itself (SELF) or be managed by a parent channel (CHANNEL). When the the node is self-managed, any operation on the parent channel, such as resize or convert depth, would not propagate to the paint node. This makes the paint node independent. Being managed by a channel is the total opposite of that and the paint data is entirely the responsibility of the channel.
- Parameters:
ManagedBy (ManagementType) – The way this node properties are managed by, set by the enum ManagementType.
- Raises:
RuntimeError – Raised if the input ManagedBy is invalid or the node is managed by a channel.
- setSize(NewSize)
Sets the size of the paint in this node, as the enum ImageSet::Size.
- Parameters:
NewSize (ImageSet.Size) – The desired size for the data of this node.
- Raises:
RuntimeError – Raised if the input size is invalid or the node is managed by a channel.
- size()
Returns the size of the paint in this node, as the enum ImageSet::Size. Returns The size of the data in this node.
- sizeChanged(ImageSize)
This is emitted when the paint size of this node changes.
- Parameters:
ImageSize (ImageSet.Size)
- class mari.PaintableLayer
Bases:
AdjustableLayerPaintable layers contain an image for each patch that can be painted directly.
You can access all types of layers from their containing
Channelobjects - for example:channel.layerList()You can check for
PaintableLayerobjects by callingLayer::isPaintableLayer():>>> # This examples creates a paintable layer and checks if it's a paintable layer >>> import mari >>> channel = mari.geo.current().currentChannel() >>> layer = channel.createPaintableLayer("Test") >>> layer.isPaintableLayer() True
- bleed()
Returns True if the layer has Texture Bleed enabled.
- Returns:
bool– Return a Boolean
- exportImages(PathAndTemplate, UVIndexList, Options='Image.DEFAULT_OPTIONS', FileOptions='variant', OutputColorConfig='nullptr')
Exports a set of images from the layer.
This is the same as selecting “Export Selected Layers” from the GUI with only the given layer selected. To export the entire layer stack, call
LayerStack::exportImages().Pass in the path and template to export the files to - for example:
>>> import mari >>> layer = mari.geo.current().currentChannel().currentLayer() >>> layer.exportImages('/tmp/$CHANNEL.$LAYER.$UDIM.tif')
Only paintable and procedural layers can be exported individually in this way.
- Parameters:
PathAndTemplate (str) – The target path for the export and the template to export the files to, in a single string.
Options (Image.SaveOptionsFlags, optional) – Pass in a value other than the default to turn on an option, such as disabling “small uniforms”. See
Image::SaveOptions. Defaults to Image.DEFAULT_OPTIONS.UVIndexList (list of
int) – Pass in a list of zero-based UV indices if desired to specify the patches to export images for. If not specified or empty, images will be exported for all indices. The UDIM for a patch is the zero-based UV index plus 1001.FileOptions (variant, optional) – This is a key/value map of optional parameters passed to the file writer plugin. Defaults to variant.
OutputColorConfig (ColorspaceConfig, optional) – The output colorspace configuration, used during export. Defaults to nullptr.
- Raises:
ValueError – Raised if the path and template parameter was empty, or if an invalid UV index was specified, or if the colorspace configuration is not valid.
IOError – Raised if an error occurred with the export process.
See also
importImages(), LayerStack::exportImages(), ProceduralLayer::exportImages()
- exportSelectedPatches(PathAndTemplate, Options='Image.DEFAULT_OPTIONS', FileOptions='variant', OutputColorConfig='nullptr')
Exports images for the selected patches from this layer.
Pass in the path and template to export the files to - for example:
>>> layer.exportSelectedPatches('/tmp/$CHANNEL.$LAYER.$UDIM.tif')Only paintable and procedural layers can be exported individually in this way.
- Parameters:
PathAndTemplate (str) – The target path for the export and the template to export the files to, in a single string.
Options (Image.SaveOptionsFlags, optional) – Pass in a value other than the default to turn on an option, such as disabling “small uniforms”. See
Image::SaveOptions. Defaults to Image.DEFAULT_OPTIONS.FileOptions (variant, optional) – This is a key/value map of optional parameters passed to the file writer plugin. Defaults to variant.
OutputColorConfig (ColorspaceConfig, optional) – The output colorspace configuration, used during export. Defaults to nullptr.
- Raises:
ValueError – Raised if the path and template parameter was empty, or if an invalid UV index was specified, or if the colorspace configuration is not valid.
IOError – Raised if an error occurred with the export process.
See also
importImages(), LayerStack::exportImages(), ProceduralLayer::exportImages()
- imageSet()
Returns the image set used by this layer.
- Raises:
SystemError – Raised if the layers paint image set cannot be found.
- Returns:
ImageSet– Return an image set.
- importImages(PathAndTemplate, UVIndexList, ScaleOption='ImageSet.SCALE_THE_IMAGE', RemoveAlpha=False, SourceColorConfig='nullptr')
Imports a set of images into the layer.
This is the same as selecting “Import into Layer” from the GUI. To import into a layer stack, call
LayerStack::importImages().Pass in the path to the files and the template to import them from - for example:
>>> layer.importImages('/tmp/$CHANNEL.$LAYER.$UDIM.tif')- Parameters:
PathAndTemplate (str) – The path to the files and the template to import them from, in a single string
ScaleOption (ImageSet.ScaleChoice, optional) – When the existing patch and the image in the file to import are of different sizes, this indicates which of the two to rescale to match the other. Defaults to ImageSet.SCALE_THE_IMAGE.
UVIndexList (list of
int) – Pass in a list of zero-based UV indices if desired to specify the patches to export images for. If not specified or empty, images will be exported for all indices. The UDIM for a patch is the zero-based UV index plus 1001.RemoveAlpha (bool, optional) – Remove the alpha channel (convert RGBA to RGB). Defaults to False.
SourceColorConfig (ColorspaceConfig, optional) – The colorspace configuration of the images being imported. Defaults to nullptr.
- Raises:
ValueError – Raised if the path and template parameter was empty, or if an invalid UV index was specified, or if the colorspace configuration is not valid.
IOError – Raised if an error occurred with the import process.
See also
exportImages(), ProceduralLayer::exportImages(), LayerStack::importImages()
- setBleed(bleed)
Sets the Texture Bleed for this layer.
- Parameters:
bleed (bool) – The new bleed value
- class mari.Palette(rName, pBodyWidget=None)
Bases:
WidgetBaseA dockable widget class.
Palettes are dockable widgets that can be moved around and configured by the user.
You can access palettes through the
PaletteManager- for example:mari.palettes.list()Example Code
>>> # This example shows how to create a palette with a label >>> import mari >>> from PySide6 import QtWidgets >>> label = QtWidgets.QLabel("Hello World") >>> new_palette = mari.palettes.create("Hello World Palette", label) >>> mari.palettes.remove(new_palette.name())
- __init__(rName, pBodyWidget=None)
Creates a new palette with the given name.
- Parameters:
rName (str) – The name of the new palette to create. This must be non-empty and unique, or the function will raise an exception. The name will be initially used as both the full and short name for the palette.
pBodyWidget (QWidget, optional) – The widget to set as the palette’s body - i.e. the one that holds everything to display for the palette. Defaults to None.
- Raises:
ValueError – Throws a value error if the name is empty, of if a palette with the given name already exists.
- bringToFront()
Brings the palette to the front of the other windows.
This can be used to bring the palette to the front of the group of palettes it is docked with, or to raise a floating palette above anything else it might currently be behind.
See also
showInFront()
- fullName()
Returns the full name displayed on the palette title.
This is the same as
name().- Returns:
str– The full name displayed on the palette title.
- helpURL()
Returns the URL for the context sensitive help page of this palette.
- Returns:
str– The URL for the context sensitive help page of this palette
- name()
Returns the full name displayed on the palette title.
This is the same as
fullName().- Returns:
str– The full name displayed on the palette title.
- setBodyWidget(pBody)
Sets the body widget of the palette.
This is the widget that holds everything to display for the palette.
- Parameters:
pBody (QWidget) – The widget that holds everything to display for the palette
- setCSHKey(Key)
Sets the context sensitive key, that is appended to the online documentation when the CSH button on this palette is triggered.
- Parameters:
Key (str) – The context sensitive key.
- setFocus()
Sets the focus to this palette.
Note that calling this from the Python Console does not take effect because running a script in the Console immediately sets the focus back to the Console’s editor.
- setFullName(rName)
Sets the full name to be displayed on the palette title.
- Parameters:
rName (str) – The full name to be displayed on the palette title.
- setShortName(rName)
Sets the short name to be displayed on the palettes tab.
- Parameters:
rName (str) – The short name to be displayed on the palettes tab.
- shortName()
Returns the short name displayed on the palettes tab.
- Returns:
str– The short name displayed on the palettes tab.
- showInFront()
Shows the palette and brings it to the front of other windows.
This is the equivalent of calling
show()and thenbringToFront().
- class mari.PaletteManager
Bases:
objectManages creation and manipulation of palettes (dockable widgets).
Palettes are dockable widgets that can be moved around and configured by the user.
Example Code
>>> # This example shows how to create a palette with a label >>> import mari >>> from PySide6 import QtWidgets >>> >>> label = QtWidgets.QLabel("Hello World") >>> new_palette = mari.palettes.create("Hello Palette", label) >>> mari.palettes.remove(new_palette.name());
Alias
palettes
- create(rName, pBodyWidget)
Creates a new palette with the given name.
- Parameters:
rName (str) – The name of the new palette to create. This must be non-empty and unique, or the function will raise an exception. The name will be initially used as both the full and short name for the palette.
pBodyWidget (QWidget) – The widget to set as the palette’s body - i.e. the one that holds everything to display for the palette. This can be any PySide widget. There used to be a method a second parameter as a string path, this is accepted but will be depricated. Use
createWithIcon()instead.
- Raises:
ValueError – Raised if the name is empty, or if a palette with the given name already exists. A non-valid widget in pBodyWidget will also Raise this exception.
- createWithIcon(rName, rIconPath, pBodyWidget=None)
Creates a new palette with the given name.
- Parameters:
rName (str) – The name of the new palette to create. This must be non-empty and unique, or the function will raise an exception. The name will be initially used as both the full and short name for the palette.
rIconPath (str) – The filename of the icon to use for the palette.
pBodyWidget (QWidget, optional) – The widget to set as the palette’s body - i.e. the one that holds everything to display for the palette. Defaults to None.
- Raises:
ValueError – Raised if the name is empty, or if a palette with the given name already exists.
- find(rName)
Returns the palette with the given full name.
Note that this returns the palette with the given full name - i.e. the one displayed on the top of the palette - rather than the one on the palette tab.
- Parameters:
rName (str)
- Returns:
Palette– The palette object if found, or NULL if not.
See also
get()
- get(rName)
Returns the palette with the given full name.
Note that this returns the palette with the given full name - i.e. the one displayed on the top of the palette - rather than the one on the palette tab.
- Parameters:
rName (str)
- Raises:
ValueError – Raised if no palette with the given full name was found.
- Returns:
Palette– The palette object.
See also
find()
- list()
Returns a list of all registered palettes.
- remove(rName)
Removes, or deletes, the palette with the given name.
- Parameters:
rName (str) – The name of the palette to remove
- Raises:
ValueError – Raised if the name is empty, or if no palette with the given name exists.
- class mari.Particle
Bases:
objectProvides Particle scripting.
- EXPORT_ALPHA = 512
Include alpha channel of all image set attributes.
- Type:
int
- EXPORT_AMBIENT_OCCLUSION = 1024
Include ambient occlusion attribute at the particle position (name = ambientOcclusion, type = float)
- Type:
int
- EXPORT_BITANGENT = 256
Include attribute for the object’s world-space bitangent at the particle position (name = bitangent, type = vector)
- Type:
int
- EXPORT_CENTER_POSITIONS = 1
Subtracts the object’s center position from each of the particle positions.
- Type:
int
- EXPORT_GEOMETRY_ID = 2
Include attribute to identify which object the particle belongs to (name = geometryId, type = indexed string)
- Type:
int
- EXPORT_IGNORE_HIDDEN = 8192
The operation ignores hidden parts of the geometry.
- Type:
int
- EXPORT_IGNORE_MEMORY_REQUIREMENT = 2048
The operation will still continue even if the system doesn’t have enough memory available.
- Type:
int
- EXPORT_IGNORE_UNSELECTED = 16384
The operation ignores unselected parts of the geometry.
- Type:
int
- EXPORT_MATCH_IMPORT = 32768
This is a special option only used in the transfer functions that makes the export options match the given import options.
- Type:
int
- EXPORT_NORMAL = 64
Include attribute for the object’s world-space normal at the particle position (name = normal, type = vector)
- Type:
int
- EXPORT_PARTICLE_ID = 8
Include attribute to uniquely identify the particle (name = id, type = int)
- Type:
int
- EXPORT_PATCH_ID = 4
Include attribute to identify which patch the particle belongs to (name = patchId, type = int)
- Type:
int
- EXPORT_PIXEL_COORDINATE = 16
Include attribute to identify the pixel within the patch that the particle belongs to (name = pixelCoordinate, type = int[2])
- Type:
int
- EXPORT_RADIUS = 4096
Include attribute for the radius that encompasses the particle’s immediate neighbours (name = radius, type = float)
- Type:
int
- EXPORT_TANGENT = 128
Include attribute for the object’s world-space tangent at the particle position (name = tangent, type = vector)
- Type:
int
- EXPORT_UV = 32
Include attribute for the object’s texture coordinates at the particle position (name = uv, type = float[2])
- Type:
int
- class ExportFlags
Bases:
objectSpecifies options for use in exporting.
- EXPORT_ALPHA = 512
Include alpha channel of all image set attributes.
- Type:
int
- EXPORT_AMBIENT_OCCLUSION = 1024
Include ambient occlusion attribute at the particle position (name = ambientOcclusion, type = float)
- Type:
int
- EXPORT_BITANGENT = 256
Include attribute for the object’s world-space bitangent at the particle position (name = bitangent, type = vector)
- Type:
int
- EXPORT_CENTER_POSITIONS = 1
Subtracts the object’s center position from each of the particle positions.
- Type:
int
- EXPORT_GEOMETRY_ID = 2
Include attribute to identify which object the particle belongs to (name = geometryId, type = indexed string)
- Type:
int
- EXPORT_IGNORE_HIDDEN = 8192
The operation ignores hidden parts of the geometry.
- Type:
int
- EXPORT_IGNORE_MEMORY_REQUIREMENT = 2048
The operation will still continue even if the system doesn’t have enough memory available.
- Type:
int
- EXPORT_IGNORE_UNSELECTED = 16384
The operation ignores unselected parts of the geometry.
- Type:
int
- EXPORT_MATCH_IMPORT = 32768
This is a special option only used in the transfer functions that makes the export options match the given import options.
- Type:
int
- EXPORT_NORMAL = 64
Include attribute for the object’s world-space normal at the particle position (name = normal, type = vector)
- Type:
int
- EXPORT_PARTICLE_ID = 8
Include attribute to uniquely identify the particle (name = id, type = int)
- Type:
int
- EXPORT_PATCH_ID = 4
Include attribute to identify which patch the particle belongs to (name = patchId, type = int)
- Type:
int
- EXPORT_PIXEL_COORDINATE = 16
Include attribute to identify the pixel within the patch that the particle belongs to (name = pixelCoordinate, type = int[2])
- Type:
int
- EXPORT_RADIUS = 4096
Include attribute for the radius that encompasses the particle’s immediate neighbours (name = radius, type = float)
- Type:
int
- EXPORT_TANGENT = 128
Include attribute for the object’s world-space tangent at the particle position (name = tangent, type = vector)
- Type:
int
- EXPORT_UV = 32
Include attribute for the object’s texture coordinates at the particle position (name = uv, type = float[2])
- Type:
int
- IMPORT_BLEED_EDGES = 2
Turns on “full texture bleed” (full patch texture bleed is generated)
- Type:
int
- IMPORT_CENTER_POSITIONS = 1
Subtracts the object’s center position from each of the particle positions.
- Type:
int
- IMPORT_FLATTEN = 4
The source layers/channel is flattened into a single image set prior to transfer (Layer & channel transfer ONLY)
- Type:
int
- IMPORT_IGNORE_HIDDEN = 8
The operation ignores hidden parts of the geometry.
- Type:
int
- IMPORT_IGNORE_UNSELECTED = 16
The operation ignores unselected parts of the geometry.
- Type:
int
- INTERPOLATION_INVERSE_DISTANCE_WEIGHTED = 1
The final value is the weighted average of the closest particles.
- Type:
int
- INTERPOLATION_INVERSE_DISTANCE_WEIGHTED_SHARPER = 3
The final value is the weighted average, with a sharper falloff, of the closest particles. This produces a more sharp result.
- Type:
int
- INTERPOLATION_INVERSE_DISTANCE_WEIGHTED_SMOOTHER = 2
The final value is the weighted average, with a smoother falloff, of the closest particles. This produces a more blurry result.
- Type:
int
- INTERPOLATION_NEAREST_NEIGHBOR = 0
The value of the closest particle.
- Type:
int
- class ImportFlags
Bases:
objectSpecifies options for use in importing.
- IMPORT_BLEED_EDGES = 2
Turns on “full texture bleed” (full patch texture bleed is generated)
- Type:
int
- IMPORT_CENTER_POSITIONS = 1
Subtracts the object’s center position from each of the particle positions.
- Type:
int
- IMPORT_FLATTEN = 4
The source layers/channel is flattened into a single image set prior to transfer (Layer & channel transfer ONLY)
- Type:
int
- IMPORT_IGNORE_HIDDEN = 8
The operation ignores hidden parts of the geometry.
- Type:
int
- IMPORT_IGNORE_UNSELECTED = 16
The operation ignores unselected parts of the geometry.
- Type:
int
- class InterpolationMethod
Bases:
objectThe method of interpolation to use when calculating the final value from the closest particles on import.
- INTERPOLATION_INVERSE_DISTANCE_WEIGHTED = 1
The final value is the weighted average of the closest particles.
- Type:
int
- INTERPOLATION_INVERSE_DISTANCE_WEIGHTED_SHARPER = 3
The final value is the weighted average, with a sharper falloff, of the closest particles. This produces a more sharp result.
- Type:
int
- INTERPOLATION_INVERSE_DISTANCE_WEIGHTED_SMOOTHER = 2
The final value is the weighted average, with a smoother falloff, of the closest particles. This produces a more blurry result.
- Type:
int
- INTERPOLATION_NEAREST_NEIGHBOR = 0
The value of the closest particle.
- Type:
int
- RANGE_GEO_SIZE_PERCENTAGE = 2
Units are a percentage of the world-space size of the geo being imported into.
- Type:
int
- RANGE_INFINITE = 0
Ignore search range restrictions.
- Type:
int
- RANGE_WORLD_SPACE_UNITS = 1
Units are in world-space coordinates.
- Type:
int
- class RangeUnits
Bases:
objectThe units of measure for a given search range.
- RANGE_GEO_SIZE_PERCENTAGE = 2
Units are a percentage of the world-space size of the geo being imported into.
- Type:
int
- RANGE_INFINITE = 0
Ignore search range restrictions.
- Type:
int
- RANGE_WORLD_SPACE_UNITS = 1
Units are in world-space coordinates.
- Type:
int
- SEARCH_BACKWARD = 3
Search in the opposite direction of the surface normal.
- Type:
int
- SEARCH_BIDIRECTIONAL = 1
Search in the direction and opposite direction of the surface normal.
- Type:
int
- SEARCH_FORWARD = 2
Search in the direction of the surface normal.
- Type:
int
- SEARCH_RADIAL = 0
Search equally in all directions.
- Type:
int
- class SearchMethod
Bases:
objectThe method used to search the particle cloud with from each of destination points.
- SEARCH_BACKWARD = 3
Search in the opposite direction of the surface normal.
- Type:
int
- SEARCH_BIDIRECTIONAL = 1
Search in the direction and opposite direction of the surface normal.
- Type:
int
- SEARCH_FORWARD = 2
Search in the direction of the surface normal.
- Type:
int
- SEARCH_RADIAL = 0
Search equally in all directions.
- Type:
int
- availableOps()
Returns a list all the available operations chains.
- exportGeo(FileName, Object, UVImageSizes, Flags, Frame, GeoVersion=None)
Exports a predefined set of attributes to a particle file on disk.
>>> geo_entity = mari.geo.current() >>> mari.particle.exportGeo('/tmp/filename.bgeo', geo_entity, {0: 256, 10: 512 }, ... mari.particle.EXPORT_NORMAL, 0)
- Parameters:
FileName (str) – The name of the file to export to. Any existing file will be overwritten.
Object (GeoEntity) – The object to export attributes for.
UVImageSizes (variant) – A dictionary that maps integer patch indices to sizes to export at. Only patch indices specified in the dictionary will be exported.
Flags (int) – The options to export with. See ExportFlags.
Frame (int) – The animated frame number to export for.
GeoVersion (GeoEntityVersion, optional) – The geometry version to export for. If None then the current geometry version is used. Defaults to None.
- Raises:
TypeError – Raised if the patch sizes dictionary was in the wrong format.
ValueError – Raised if no object was given, no patch sizes are given, the patch indices are invalid, the patch sizes are invalid.
- Returns:
bool– True if the export completed successfully, or false otherwise.
- exportImageSets(FileName, ImageSets, Flags, Frame, UVIndices, GeoVersion=None)
Exports a set of image sets to a particle file on disk.
The image sets must belong to the same object and have the same width and height. .. code-block:
>>> geo_entity = mari.geo.current() >>> image_set = geo_entity.currentImageSet() >>> mari.particle.exportImageSets('/tmp/filename.bgeo', {'color' : image_set}, mari.particle.EXPORT_ALPHA, ... 0, [0, 1])
- Parameters:
FileName (str) – The name of the file to export to. Any existing file will be overwritten.
ImageSets (variant) – A dictionary that maps string particle attribute names, to export to, to image sets, to export from.
Flags (int) – The options to export with. See ExportFlags.
Frame (int) – The animated frame number to export for.
UVIndices (list of
int) – Which patches to export for. Passing in an empty list will cause all patches to be exported.GeoVersion (GeoEntityVersion, optional) – The geometry version to export for. If None then the current geometry version is used. Defaults to None.
- Raises:
ValueError – Raised if no image sets are given, the image sets are invalid, the patch indices are invalid, the patch sizes don’t match or they don’t belong to the same object.
- Returns:
bool– True if the export completed successfully, or false otherwise.
- findOp(Name)
Returns the operations chain of the given name.
- Parameters:
Name (str) – The name of the operations chain to find.
- Returns:
ParticleOp– The operations chain, or None if no operations chain exists for the given name.
- importImageSets(FileName, ImageSets, Interpolation, Flags, Frame, UVIndices, GeoVersion=None, SearchRange=1.0, SearchUnits='RANGE_INFINITE', Search='SEARCH_RADIAL', SampleCount=16)
Imports into a set of image sets from a particle file on disk.
The image sets must belong to the same object and have the same width and height. .. code-block:
>>> geo_entity = mari.geo.current() >>> image_set = geo_entity.currentImageSet() >>> mari.particle.importImageSets('/tmp/filename.bgeo', {'color' : image_set}, ... mari.particle.INTERPOLATION_INVERSE_DISTANCE_WEIGHTED, ... mari.particle.IMPORT_BLEED_EDGES, 0, [0, 1])
- Parameters:
FileName (str) – The name of the file to import to.
ImageSets (variant) – A dictionary that maps string particle attribute names, to import from, to image sets, to import into.
Interpolation (InterpolationMethod) – Which method of interpolation to use when calculating the final color value from the closest particles.
Flags (int) – The options to import with. See ImportFlags.
Frame (int) – The animated frame number to import to.
UVIndices (list of
int) – Which patches to import into. Passing in an empty list will cause all patches to be imported.GeoVersion (GeoEntityVersion, optional) – The geometry version to import to. If None then the current geometry version is used. Defaults to None.
SearchRange (float, optional) – The maximum distance allowed to be searched. Defaults to 1.0.
SearchUnits (RangeUnits, optional) – The units of measure for the search range. Defaults to RANGE_INFINITE.
Search (SearchMethod, optional) – The method used to search the particle cloud with from each of destination points. Defaults to SEARCH_RADIAL.
SampleCount (int, optional) – The number of samples to search for and interpolate together to produce the final color. Defaults to 16.
- Raises:
IOError – Raised if the file was invalid; if the file was missing data; if any of the file data was in the wrong format.
TypeError – Raised if the image set dictionary was in the wrong format.
ValueError – Raised if no image sets were supplied; if any of the image sets was invalid; if the image sets belong to different objects; if any of the patch indices was invalid; if any of the patch sizes didn’t match between image sets.
- Returns:
bool– True if the import completed successfully, or false otherwise.
- interpolationMethods()
Returns a dictionary of user-friendly names to their associated enum value, for all the supported interpolation methods.
- rangeUnits()
Returns a dictionary of user-friendly names to their associated enum value, for all the supported search range units.
- searchMethods()
Returns a dictionary of user-friendly names to their associated enum value, for all the supported search methods.
- supportedFileFormats()
Returns a list of all the supported particle file formats.
- transferChannel(SourceChannel, SourceFrame, SourceUVIndices, DestinationObject, DestinationFrame, DestinationUVIndices, Interpolation, DestinationFlags, SourceGeoVersion=None, DestinationGeoVersion=None, SearchRange=1.0, SearchUnits='RANGE_INFINITE', FillColor=None, Search='SEARCH_RADIAL', SampleCount=16, SourceFlags='Particle.EXPORT_MATCH_IMPORT', DestinationSize='ImageSet.SIZE_None')
Copies a single channel from one object to another.
>>> src_geo_entity = mari.geo.get('Head1') >>> src_channel = src_geo_entity.channel('diffuse') >>> dst_geo_entity = mari.geo.get('Head2') >>> mari.particle.transferChannel(src_channel, 0, [], dst_geo_entity, 0, [], ... mari.particle.InterpolationMethod.INTERPOLATION_INVERSE_DISTANCE_WEIGHTED, ... mari.particle.ImportFlags.IMPORT_BLEED_EDGES | mari.particle.ImportFlags.IMPORT_FLATTEN)
- Parameters:
SourceChannel (Channel) – The source channel to read from.
SourceFrame (int) – The animated frame number to read from.
SourceUVIndices (list of
int) – Which patches in the source to read from. Passing in an empty list will cause all source patches to be read from.DestinationObject (GeoEntity) – The destination object to write into.
DestinationFrame (int) – The animated frame number to write to.
DestinationUVIndices (list of
int) – Which patches in the destination to write to. Passing in an empty list will cause all destination patches to be written to.Interpolation (InterpolationMethod) – Which method of interpolation to use when calculating the final color value from the closest particles.
DestinationFlags (int) – The options used in writing. See ImportFlags.
SourceGeoVersion (GeoEntityVersion, optional) – The source geometry version to read from. If None then the current geometry version is used. Defaults to None.
DestinationGeoVersion (GeoEntityVersion, optional) – The destination geometry version to write into. If None then the current geometry version is used. Defaults to None.
SearchRange (float, optional) – The maximum distance allowed to be searched. Defaults to 1.0.
SearchUnits (RangeUnits, optional) – The units of measure for the search range. Defaults to RANGE_INFINITE.
FillColor (Color, optional) – The color used to fill the newly created destination image sets with. Defaults to None.
Search (SearchMethod, optional) – The method used to search the particle cloud with from each of destination points. Defaults to SEARCH_RADIAL.
SampleCount (int, optional) – The number of samples to search for and interpolate together to produce the final color. Defaults to 16.
SourceFlags (int, optional) – The options used in reading. See ExportFlags. Defaults to Particle.EXPORT_MATCH_IMPORT.
DestinationSize (ImageSet.Size, optional) – Used to specified the image size for all uv indices in the destination channel. If a size is not given then the size will match the source. Defaults to ImageSet.SIZE_None.
- Raises:
ValueError – Raised if no channel was supplied; if any of the patch indices was invalid; if no destination object was supplied.
- Returns:
Channel– A destination channel if the transfer completed successfully, or None otherwise.
Deprecated
This function will be removed in a future version. Please use mari.GeoEntity.transferChannels instead.
- transferImageSets(SourceImageSets, SourceFrame, SourceUVIndices, DestinationImageSets, DestinationFrame, DestinationUVIndices, Interpolation, DestinationFlags, SourceGeoVersion=None, DestinationGeoVersion=None, SearchRange=1.0, SearchUnits='RANGE_INFINITE', Search='SEARCH_RADIAL', SampleCount=16, SourceFlags='Particle.EXPORT_MATCH_IMPORT')
Copies image data from one image set to another.
The image sets in the source list must belong to the same object and have the same width and height. This also applies to the destination list. .. code-block:
>>> src_geo_entity = mari.geo.get('Head1') >>> src_image_set = src_geo_entity.currentImageSet() >>> dst_geo_entity = mari.geo.get('Head2') >>> dst_image_set = dst_geo_entity.currentImageSet() >>> mari.particle.transferImageSets([src_image_set], 0, [0, 1], [dst_image_set], 0, [0, 1], ... mari.particle.INTERPOLATION_INVERSE_DISTANCE_WEIGHTED, ... mari.particle.IMPORT_BLEED_EDGES)
- Parameters:
SourceImageSets (list of
ImageSet) – A list of source image sets to read from.SourceFrame (int) – The animated frame number to read from.
SourceUVIndices (list of
int) – Which patches in the source to read from. Passing in an empty list will cause all source patches to be read from.DestinationImageSets (list of
ImageSet) – A list of destination image sets to write into.DestinationFrame (int) – The animated frame number to write to.
DestinationUVIndices (list of
int) – Which patches in the destination to write to. Passing in an empty list will cause all destination patches to be written to.Interpolation (InterpolationMethod) – Which method of interpolation to use when calculating the final color value from the closest particles.
DestinationFlags (int) – The options used in writing. See ImportFlags.
SourceGeoVersion (GeoEntityVersion, optional) – The source geometry version to read from. If None then the current geometry version is used. Defaults to None.
DestinationGeoVersion (GeoEntityVersion, optional) – The destination geometry version to write into. If None then the current geometry version is used. Defaults to None.
SearchRange (float, optional) – The maximum distance allowed to be searched. Defaults to 1.0.
SearchUnits (RangeUnits, optional) – The units of measure for the search range. Defaults to RANGE_INFINITE.
Search (SearchMethod, optional) – The method used to search the particle cloud with from each of destination points. Defaults to SEARCH_RADIAL.
SampleCount (int, optional) – The number of samples to search for and interpolate together to produce the final color. Defaults to 16.
SourceFlags (int, optional) – The options used in reading. See ExportFlags. Defaults to Particle.EXPORT_MATCH_IMPORT.
- Raises:
ValueError – Raised if no image sets were supplied; the number of source image sets doesn’t match the number of destination image sets; if any of the image sets was invalid; if the image sets belong to different objects; if any of the patch indices was invalid; if any of the patch sizes didn’t match between image sets.
- Returns:
bool– True if the transfer completed successfully, or false otherwise.
- transferLayers(SourceLayers, SourceFrame, SourceUVIndices, DestinationStack, DestinationFrame, DestinationUVIndices, Interpolation, DestinationFlags, SourceGeoVersion=None, DestinationGeoVersion=None, SearchRange=1.0, SearchUnits='RANGE_INFINITE', FillColor=None, Search='SEARCH_RADIAL', SampleCount=16, SourceFlags='Particle.EXPORT_MATCH_IMPORT')
Copies layers from one object to another.
The layers in the source list must belong to the same object. .. code-block:
>>> src_geo_entity = mari.geo.get('Head1') >>> src_channel = src_geo_entity.channel('diffuse') >>> src_layer = src_channel.layer('color') >>> dst_geo_entity = mari.geo.get('Head2') >>> dst_channel = dst_geo_entity.channel('diffuse') >>> mari.particle.transferLayers([src_layer], 0, [], dst_channel, 0, [], ... mari.particle.INTERPOLATION_INVERSE_DISTANCE_WEIGHTED, ... mari.particle.IMPORT_BLEED_EDGES | mari.particle.IMPORT_FLATTEN)
- Parameters:
SourceLayers (list of
Layer) – A list of source layers to read from.SourceFrame (int) – The animated frame number to read from.
SourceUVIndices (list of
int) – Which patches in the source to read from. Passing in an empty list will cause all source patches to be read from.DestinationStack (LayerStack) – The destination layer stack to write into.
DestinationFrame (int) – The animated frame number to write to.
DestinationUVIndices (list of
int) – Which patches in the destination to write to. Passing in an empty list will cause all destination patches to be written to.Interpolation (InterpolationMethod) – Which method of interpolation to use when calculating the final color value from the closest particles.
DestinationFlags (int) – The options used in writing. See ImportFlags.
SourceGeoVersion (GeoEntityVersion, optional) – The source geometry version to read from. If None then the current geometry version is used. Defaults to None.
DestinationGeoVersion (GeoEntityVersion, optional) – The destination geometry version to write into. If None then the current geometry version is used. Defaults to None.
SearchRange (float, optional) – The maximum distance allowed to be searched. Defaults to 1.0.
SearchUnits (RangeUnits, optional) – The units of measure for the search range. Defaults to RANGE_INFINITE.
FillColor (Color, optional) – The color used to fill the newly created destination image sets with. Defaults to None.
Search (SearchMethod, optional) – The method used to search the particle cloud with from each of destination points. Defaults to SEARCH_RADIAL.
SampleCount (int, optional) – The number of samples to search for and interpolate together to produce the final color. Defaults to 16.
SourceFlags (int, optional) – The options used in reading. See ExportFlags. Defaults to Particle.EXPORT_MATCH_IMPORT.
- Raises:
ValueError – Raised if no layers were supplied; if any of the layers was invalid; if the layers belong to different objects; if any of the patch indices was invalid; if no destination layer stack was supplied.
- Returns:
list of
Layer– A list of destination layers if the transfer completed successfully, or an empty list otherwise.
Deprecated
This function will be removed in a future version. Please use mari.LayerStack.transferLayers instead.
- transferNodes(SourceNodes, SourceFrame, SourceUVIndices, DestinationNodeGraph, DestinationFrame, DestinationUVIndices, Interpolation, DestinationFlags, SourceGeoVersion=None, DestinationGeoVersion=None, SearchRange=1.0, SearchUnits='RANGE_INFINITE', FillColor=None, Search='SEARCH_RADIAL', SampleCount=16, SourceFlags='Particle.EXPORT_MATCH_IMPORT', DestinationSize='ImageSet.SIZE_None')
Copies nodes from one object to another.
The nodes in the source list must belong to the same object. .. code-block:
>>> src_geo_entity = mari.geo.get('Head1') >>> src_node_graph = src_geo_entity.nodeGraph() >>> dst_geo_entity = mari.geo.get('Head2') >>> dst_node_graph = dst_geo_entity.nodeGraph() >>> mari.particle.transferNodes(src_node_graph.selectedNodeList(), 0, [], dst_node_graph, 0, ... [], mari.particle.INTERPOLATION_INVERSE_DISTANCE_WEIGHTED, ... mari.particle.IMPORT_BLEED_EDGES)
- Parameters:
SourceNodes (list of
Node) – A list of source nodes to read from.SourceFrame (int) – The animated frame number to read from.
SourceUVIndices (list of
int) – Which patches in the source to read from. Passing in an empty list will cause all source patches to be read from.DestinationNodeGraph (NodeGraph) – The destination node graph to write into.
DestinationFrame (int) – The animated frame number to write to.
DestinationUVIndices (list of
int) – Which patches in the destination to write to. Passing in an empty list will cause all destination patches to be written to.Interpolation (InterpolationMethod) – Which method of interpolation to use when calculating the final color value from the closest particles.
DestinationFlags (int) – The options used in writing. See ImportFlags.
SourceGeoVersion (GeoEntityVersion, optional) – The source geometry version to read from. If None then the current geometry version is used. Defaults to None.
DestinationGeoVersion (GeoEntityVersion, optional) – The destination geometry version to write into. If None then the current geometry version is used. Defaults to None.
SearchRange (float, optional) – The maximum distance allowed to be searched. Defaults to 1.0.
SearchUnits (RangeUnits, optional) – The units of measure for the search range. Defaults to RANGE_INFINITE.
FillColor (Color, optional) – The color used to fill the newly created destination image sets with. Defaults to None.
Search (SearchMethod, optional) – The method used to search the particle cloud with from each of destination points. Defaults to SEARCH_RADIAL.
SampleCount (int, optional) – The number of samples to search for and interpolate together to produce the final color. Defaults to 16.
SourceFlags (int, optional) – The options used in reading. See ExportFlags. Defaults to Particle.EXPORT_MATCH_IMPORT.
DestinationSize (ImageSet.Size, optional) – Used to specified the image size for all uv indices in the destination channel. If a size is not given then the size will match the source. Defaults to ImageSet.SIZE_None.
- Raises:
ValueError – Raised if no nodes were supplied; if any of the nodes are invalid; if the nodes belong to different objects; if any of the patch indices was invalid; if no destination node graph was supplied.
- Returns:
list of
Node– A list of destination layers if the transfer completed successfully, or an empty list otherwise.
Deprecated
This function will be removed in a future version. Please use mari.NodeGraph.transferNodes instead.
- class mari.ParticleOp
Bases:
PropertySourceProvides Particle operations chain scripting.
- description()
Returns a brief description of the operations chain.
- Returns:
str– A string containing the description.
- execute()
Executes the operations chain.
- Returns:
bool– True if all operations completed successfully, false otherwise.
- name()
Returns the name of the operations chain.
- Returns:
str– A string containing the name.
- propertyWidget()
Returns the properties widget for the operations chain.
- Returns:
QWidget– A widget with all operations properties exposed as a number of sub-widgets.
- class mari.PatchLinksManager
Bases:
objectHandles patch image linking.
Using this manager, you can create and managed named groups of linked images. Linked patches share their underlying image contents, so if you paint on one linked patch, all other linked patches are updated.
Currently, the API restricts linkage to
Imageobjects on the sameImageSet. At some point in the future, which restriction will be removed. Some methods require an seemingly redundantImageSetparameter to make provision for such a change.Example Code
>>> # This example creates a patch link between 1001 and 1011 >>> import mari >>> geo = mari.geo.current() >>> patch_1001 = geo.patch(0) >>> patch_1011 = geo.patch(10) >>> layer = geo.currentChannel().createPaintableLayer("Test") >>> mari.patch_links.linkPatches([patch_1001,patch_1011],"Test Link",layer.imageSet()) >>> print(mari.patch_links.groupNamesForImageSet(layer.imageSet())[0]) Test Link
Alias
patch_links
- canLinkImageInternals(Images)
Checks whether the input images can be linked based on their internal structure.
- Images can be linked if
- Parameters:
Images (list of
Image) – Container of Images objects.- Raises:
RuntimeError – Raised if any of the input images are not valid.
- Returns:
bool– True if the images internals can be linked, or False if not.
- canLinkImages(Images, GroupName)
Checks whether the input images can be linked into an existing/new group with the specified group name.
This will check whether the input images, and any existing images linked in the group indexed by the specified groupname, can have their internals linked. It also checks whether any of the images are already part of other link groups, in which case they can not be linked, and this method will return False.
- Parameters:
- Raises:
RuntimeError – Raised if any of the input images are not valid.
ValueError – Raised if GroupName is an empty string.
- Returns:
bool– True if the images can be linked in a group with the specified group name, and False if not.
See also
canLinkImageInternals()
- canLinkPatchInternals(Patches, pImageSet)
Checks whether the input patches for the specified image set can be linked based on their underlying image’s internal structure.
This is a convenience function which will look up the underlying images for the patches (similar to what can be done by using method mari.GeoEntity.patchImage), and then checks whether the image internals can be linked.
- Parameters:
- Raises:
RuntimeError – Raised if any of the input patches are not valid.
ValueError – Raised if pImageSet isn’t a valid ImageSet.
- Returns:
bool– True if the patches internals can be linked, or False if not.
See also
canLinkImageInternals()
See also
mari.GeoEntity.patchImage()
- canLinkPatches(Patches, GroupName, pImageSet)
Checks whether the underlying images for the given patches on the specified image set can be linked into a new/existing group with the specified group name.
This is a convenience function which will look up the underlying images for the given patch-image set combination, and then calls
canLinkImages().- Parameters:
- Raises:
RuntimeError – Raised if any of the input patches are not valid.
ValueError – Raised if GroupName is an empty string or if pImageSet isn’t a valid ImageSet.
- Returns:
bool– True if the underlying images for the patches can be linked in a group with the specified group name, or False if not.
See also
canLinkImages()
See also
mari.GeoEntity.patchImage()
- generateUniqueGroupName()
Generates a unique name which hasn’t yet been used to index a group of linked patches, which you can use to create a uniquely named group of linked patches.
- Returns:
str– String containing the unique name.
- groupAdded(GroupName)
Emitted when a new link group has been added.
- Parameters:
GroupName (str) – String name of the group that was added.
- groupNames()
Gets the names of all existing link groups.
- Returns:
list of str– Container of strings for the names.
- groupNamesForImageSet(pImageSet)
Gets the names of all link groups (if any) which link patch images on the specified image set.
- groupRemoved(GroupName)
Emitted when a link group has been removed.
- Parameters:
GroupName (str) – String name of the group that was renamed.
- groupRenamed(OldName, NewName)
Emitted when a link group has been renamed.
- Parameters:
OldName (str) – The previous name.
NewName (str) – The new name.
- imageGroup(Img)
Gets the name of the link group, if any, containing the specified image.
- imageUnlinked(Img)
Emitted when an Image object has been unlinked.
- images(GroupName)
Gets the images which are part of the specified link group.
- Parameters:
GroupName (str) – String name indexing the group which images will be returned.
- Raises:
ValueError – Raised if GroupName is an empty string.
- Returns:
list of
Image– Container of Image objects which are part of the specified group. If no no such group exists, an empty container is returned.
- imagesLinked(Images)
Emitted when a set of Images object have been linked.
- isImageLinked(Img)
Checks if the image is part of any link groups.
- isPatchLinked(Patch, pImageSet)
Check if the image for the patch on the given image set has been linked.
- Parameters:
- Raises:
ValueError – Raised if Patch isn’t a valid GeoPatch or if pImageSet isn’t a valid ImageSet.
- Returns:
bool– True if the patch image is linked, and False if not.
See also
isImageLinked()
See also
mari.GeoEntity.patchImage()
- linkImages(Images, GroupName)
Link the input images into a new/existing group with the specified group name.
This method will check the images are linkable by using
canLinkImages(), and if so, it will link them. If the images are linked into an existing group, their contents will immediately be updated to match that of other images in the link group.- Parameters:
- Raises:
RuntimeError – Raised if the images could not be linked.
ValueError – Raised if Images is not a list of valid image objects, or if GroupName is an empty string.
See also
generateUniqueGroupName()
See also
canLinkImages()
- linkPatches(Patches, GroupName, pImageSet)
Convenience function to link the images for the patches on the specified image set.
This essentially looks up the images for the patches, and then calls
linkImages().- Parameters:
- Raises:
RuntimeError – Raised if the patch images could not be linked.
ValueError – Raised if Patches is not a container of valid patch objects, or if pImageSet isn’t a valid ImageSet, or if GroupName is an empty string.
See also
linkImages()
See also
mari.GeoEntity.patchImage()
- linkSelectedPatches(GroupName, pImageSet)
Convenience method to link the currently selected patches on the specified image set.
- Parameters:
- Raises:
RuntimeError – Raised if the selected patches could not be linked.
ValueError – Raised if GroupName is an empty string, or if pImageSet isn’t a valid ImageSet object.
See also
linkPatches()
See also
linkImages()
- linkedImages(Img)
Gets the group of linked images of which the input image is part.
- linkedPatches(Patch, pImageSet=None)
Gets the group of linked patches of which the input patch is part.
- Parameters:
- Returns:
list of
GeoPatch– Container of Image objects. The container will be empty if no images are linked against Img.
- patchGroup(Patch, pImageSet)
Gets the name of the link group, if any, containing the specified patch image on the specified image set.
- Parameters:
- Raises:
ValueError – Raised if Patch isn’t a valid GeoPatch object, or if pImageSet isn’t a valid ImageSet object.
- Returns:
str– String name for the group. If Patch is not part of any link groups, and empty string is returned.
- patches(GroupName, pImageSet=None)
Gets the patches which are part of the specified link group on the specified or current image set.
- Parameters:
- Raises:
ValueError – Raised if GroupName is an empty string.
- Returns:
list of
GeoPatch– Container or GeoPatch objects.
See also
images()
- removeGroup(GroupName)
Removes a group of linked patch images.
- Parameters:
GroupName (str) – String name indexing the group which must be removed.
- Raises:
RuntimeError – Raised if removing the named group failed.
ValueError – Raised if GroupName is an empty string.
- renameGroup(OldName, NewName)
Renames a group of linked patch images.
- Parameters:
OldName (str) – String specifying the name of the group.
NewName (str) – String specifying the new name for the group.
- Raises:
RuntimeError – Raised if the group does not exist, or if it could not be renamed.
ValueError – Raised if OldName or NewName are invalid strings.
- unlinkImage(Img)
Unlinks the specified image from all other images.
- unlinkPatch(Patch, pImageSet)
Unlinks the image for the patch on the specified image set from all other images.
- Parameters:
- Raises:
RuntimeError – Raised if the Patch could not be unlinked in pImageSet.
ValueError – Raised if Patch isn’t a valid GeoPatch object, or if pImageSet isn’t a valid ImageSet object.
See also
unlinkImage()
See also
mari.GeoEntity.patchImage()
- unlinkSelectedPatches(pImageSet)
Unlinks the patch images for the selected patches on the specified image set.
- class mari.PatchSelectionGroup
Bases:
SelectionGroupA specialised selection group that consists of patches.
- class mari.PointLight
Bases:
LightAn object for creating lighting effects on a 3D mesh.
You can access lights through the
LightManager- for example:mari.lights.list()- constantAttenuation()
Return the constant attenuation value for this light.
- Returns:
float– The constant attenuation value
- fixedTo()
Returns the type of object that the light is fixed to.
Lights can be fixed to either the world or the camera. This allows lights to follow the view, ensuring models are illuminated at all times.
- Returns:
FixedTo– Light::SCENE if the light is fixed to the scene, or Light::CAMERA if fixed to the camera.
- intensity()
Return the intensity value for this point light.
- Returns:
float– The intensity value
- linearAttenuation()
Return the linear attenuation value for this light.
- Returns:
float– The linear attenuation value
- position(Frame=0)
Returns the position of the light in the scene.
- Parameters:
Frame (int, optional) – The frame to retrieve the position for. Use 0 (the default) when there is no animation. Defaults to 0.
- Returns:
VectorN– The position of the light in the scene
See also
setPosition()
- quadraticAttenuation()
Return the quadratic attenuation value for this light.
- Returns:
float– The quadratic attenuation value
- renderShadows()
Return whether to render shadows.
- Returns:
bool– Whether to render shadows
- setAmbient(NewColor)
Sets the specular Color of the light.
- Parameters:
NewColor (Color) – The new specular color for the light
- setConstantAttenuation(Atten)
Set the constant attenuation for the light.
- Parameters:
Atten (float) – The new constant attenuation for the light
- setDiffuse(NewColor)
Set the diffuse color of the light.
- Parameters:
NewColor (Color) – The new diffuse color for the light
- setFixedTo(TargetType)
Sets the type of object that the light should be fixed to.
- Parameters:
TargetType (FixedTo) –
Light::SCENEif the light is to be fixed to the scene, orLight::CAMERAif fixed to the camera.
See also
fixedTo()
- setIntensity(Intensity)
Set the intensity for the point light.
- Parameters:
Intensity (float) – The new Intensity for the point light
- setLinearAttenuation(Atten)
Set the linear attenuation for the light.
- Parameters:
Atten (float) – The new linear attenuation for the light
- setPosition(pTranslation)
Sets the position of the light in the scene.
Positions can only be set on the default frame (0) at present.
- Parameters:
pTranslation (VectorN) – The new position of the light
See also
position()
- setQuadraticAttenuation(Atten)
Set the quadratic attenuation for the light.
- Parameters:
Atten (float) – The new quadratic attenuation for the light
- setRenderShadows(Render)
Set whether to render shadows.
- Parameters:
Render (bool) – Whether to render shadows
- setSpecular(NewColor)
Sets the specular Color of the light.
- Parameters:
NewColor (Color) – The new specular color for the light
- setSpotCutoff(Cutoff)
Set the Spot cutoff component of the light.
- Parameters:
Cutoff (float) – The new spot cutoff of the light
- setSpotDirection(Direction)
Set the spot direction for this light.
- Parameters:
Direction (VectorN) – The new spot direction for this light
- setSpotExponent(Exponent)
Set the Spot exponent component of the light.
- Parameters:
Exponent (float) – The new spot exponent of the light
- spotCutoff()
Return the spot cutoff for the light.
- Returns:
float– The spot cutoff value
- spotDirection()
Return the spot direction for this light.
- Returns:
VectorN– The spot direction value for this light
- spotExponent()
Return the spot exponent of this light.
- Returns:
float– The spot exponent of the light
- class mari.PostFilter
Bases:
PropertySourceA post processing, image space color management filter.
Post processing filters can be applied to the canvas display after rendering. These filters can be used for color correction, bloom, or other fancy effects. Filters are written as GLSL shader fragments, and can have uniform values and texture data as well.
PostFilterinstances can be created by calling the various “create” functions on aPostFilterCollection.Example Code
>>> # This examples creates a new FileLUTFilter object through GLRender and PostFilterCollection >>> import mari >>> filter_collection = mari.gl_render.createPostFilterCollection("New Filter Collection") >>> file_lut = filter_collection.createFileLUT("New File LUT") >>> mari.gl_render.deletePostFilterCollection(filter_collection)
- POSTFILTER_ENABLED = 1
Whether the filter is enabled.
- Type:
int
- POSTFILTER_REMOVABLE = 2
The filter can be removed by users.
- Type:
int
- class PostFilterFlags
Bases:
objectSpecifies the options that can be set on filters.
- POSTFILTER_ENABLED = 1
Whether the filter is enabled.
- Type:
int
- POSTFILTER_REMOVABLE = 2
The filter can be removed by users.
- Type:
int
- enabled()
Returns whether the filter is enabled.
- Returns:
bool– True if the filter is enabled
Deprecated
This function will be removed in a future version. Please use ‘enabled = (filter.flags() & filter.POSTFILTER_ENABLED) is filter.POSTFILTER_ENABLED’.
- flags()
Returns the flags of the filter.
- Returns:
int– The flags of the filter. See PostFilterFlags.
- flagsChanged(Flags)
Emitted when the flags changes.
- Parameters:
Flags (int) – The new flags.
- name()
Returns the name of the filter.
- Returns:
str– The unique name of the filter
- setEnabled(Enabled)
Used to enables or disable the filter.
- Parameters:
Enabled (bool) – Whether the filter is to be enabled or disabled
Deprecated
This function will be removed in a future version. Please use ‘filter.setFlags(filter.flags() | filter.POSTFILTER_ENABLED)’.
- setFlags(Flags)
Modifies the flags of the filter.
- Parameters:
Flags (int) – The flags of the filter. See PostFilterFlags.
- class mari.PostFilterCollection
Bases:
MetadataA collection of post processing, image space filters.
These filters are applied to the canvas display after rendering. These filters can be used for color correction, bloom or other fancy effects. Filters are written as GLSL shader fragments, and can have uniform values and texture data as well.
PostFilterCollectioninstances can be created by callingGLRender::createPostFilterCollection().Example Code
>>> # This examples creates a new FileLUTFilter object through GLRender and PostFilterCollection >>> import mari >>> filter_collection = mari.gl_render.createPostFilterCollection("New Filter Collection") >>> file_lut = filter_collection.createFileLUT("New File LUT") >>> mari.gl_render.deletePostFilterCollection(filter_collection)
- POSTFILTERCOLLECTION_EDITABLE = 1
The collection can have filters added and removed by users.
- Type:
int
- POSTFILTERCOLLECTION_REMOVABLE = 2
The collection can be removed by users.
- Type:
int
- POSTFILTERCOLLECTION_RENAMABLE = 4
The collection can be renamed by users.
- Type:
int
- class PostFilterCollectionFlags
Bases:
objectSpecifies the options that can be set on collections.
- POSTFILTERCOLLECTION_EDITABLE = 1
The collection can have filters added and removed by users.
- Type:
int
- POSTFILTERCOLLECTION_REMOVABLE = 2
The collection can be removed by users.
- Type:
int
- POSTFILTERCOLLECTION_RENAMABLE = 4
The collection can be renamed by users.
- Type:
int
- addFilter(Name, Index=-1)
Add a filter to the collection.
- Parameters:
Name (str) – The name for the default filter add
Index (int, optional) – The index to insert the filter at. If -1 is given, the filter will be appended to the end of the collection. Defaults to -1.
- clear()
Removes all of the filters held by the collection.
- createCustomLUT(Name, Index=-1)
Creates a new custom LUT post processing filter that can be applied to the viewport.
- Parameters:
Name (str) – The name for the new filter
Index (int, optional) – The index to insert the new filter at. If -1 is given, the new filter will be appended to the end of the collection. Defaults to -1.
- Returns:
CustomLUTFilter– A new post process custom LUT filter object
- createFileLUT(Name, Index=-1)
Creates a new file LUT post processing filter that can be applied to the viewport.
- Parameters:
Name (str) – The name for the new filter
Index (int, optional) – The index to insert new filter at. If -1 is given, the new filter will be appended to the end of the collection. Defaults to -1.
- Returns:
FileLUTFilter– A new post process file LUT filter object
- createGLSL(Name, DefinitionsSnippet='', BodySnippet='', Index=-1)
Creates a new GLSL post processing filter that can be applied to the viewport.
Marisupports post-render processing effects. These can be used to color-correct, blur, filter or warp the viewport display to achieve different effects.- Filters are implemented as two snippets of GLSL shader code:
The DefinitionsSnippet defines uniforms and functions required for the filter
The BodySnippet contains the implementation of the filter itself
As multiple instances of a filter can be created, we need to give each instance a unique ID. To do this, all uniforms and function names in the shader should have a $ID appended to their names.
Maritakes this token internally and adds a unique ID. This preventing name collisions in shaders. For example, a definitions snippet that looks like:uniform float ScaleX_$ID_; uniform float ScaleY_$ID_;
will be translated internally into:
uniform float ScaleX1; uniform float ScaleY2;
Body snippets should be protected with braces, and can expect the color value of the pixel being processed to be available in a vec4 called “Out”.
If you wanted to simply multiply the viewport display pixels by a floating point value, for example, you could write something like:
definition_snippet = "uniform float ScaleValue_$ID_;" body_snippet = "{ Out.rgb *= ScaleValue_$ID_; }"
The values passed into the shader can be controlled by modifying a metadata value on the
PostFilterobject. The metadata value should have the same name and type as the uniform, but should not include the $ID. In the scaling example above, we could add some metadata to the filter called ScaleValue, and this would then be passed into the shader automatically.- Parameters:
Name (str) – The name for the new filter
DefinitionsSnippet (str, optional) – A snippet of GLSL code that defines the uniforms and functions used by this post process filter. Defaults to “”.
BodySnippet (str, optional) – A snippet of GLSL code that defines the body of the post process filter. Defaults to “”.
Index (int, optional) – The index to insert the new filter at. If -1 is given, the new filter is appended to the end of the collection. Defaults to -1.
- Returns:
GLSLFilter– A new post process filter object
- createOcioNamedTransform(Name, Index=-1)
Creates a new OCIO NamedTransform post processing filter that can be applied to the viewport.
This filter provides specialized OCIO color management functionality using NamedTransforms. Unlike generic GLSL filters, this filter handles OCIO processor creation, GPU shader generation, and texture management internally, providing a simplified interface for OCIO-based transformations.
The filter can be configured by calling buildFromOcioConfig() with a serialized OCIO configuration and the name of a NamedTransform to use for processing.
Example Usage .. code-block:
>>> import mari >>> collection = mari.gl_render.createPostFilterCollection("OCIO Collection") >>> ocio_filter = collection.createOcioNamedTransform("Gain Filter") >>> success = ocio_filter.buildFromOcioConfig(config_string, "gain_transform")
- Parameters:
Name (str) – The name for the new OCIO filter
Index (int, optional) – The index to insert the new filter at. If -1 is given, the new filter is appended to the end of the collection. Defaults to -1.
- Raises:
ValueError – Raised if a filter of the given name already exists or Index is out of range.
- Returns:
OcioNamedTransformFilter– A new OCIO NamedTransform post process filter object
- filters()
Returns the post process filters in the collection.
These post process filters are executed in order.
- Returns:
list of
PostFilter– A list of all post process filters within the collection
- find(Name)
Returns the first occurrence of a filter with the given name.
- Parameters:
Name (str) – The name of filter to find
- Returns:
PostFilter– A filter with the given name, or NULL if not found
- flags()
Returns the flags of the collection.
- Returns:
int– The flags of the collection. See PostFilterCollectionFlags.
- indexOf(Filter, StartAt=0)
Returns the index of a filter.
- Parameters:
Filter (PostFilter) – The filter to return the index of
StartAt (int, optional) – Index to start searching from. Defaults to 0.
- Returns:
int– The index position of the first occurrence of a filter in the collection, searching forward from index position StartAt. Returns -1 if no matching item was found
- isReadOnly()
Returns whether the collection is read only.
Deprecated
This function will be removed in a future version. Please use ‘read_only = collection.flags() is (collection.POSTFILTERCOLLECTION_EDITABLE | collection.POSTFILTERCOLLECTION_REMOVABLE)’.
- move(Filter, Index)
Moves a single filter within the collection.
- Parameters:
Filter (PostFilter) – The filter to move
Index (int) – The index to move the filter to
- name()
Returns the name of the collection.
- Returns:
str– The unique name of the collection.
- remove(Filter)
Deletes (removes) a filter from the collection.
- Parameters:
Filter (PostFilter) – The filter to delete
- Raises:
ValueError – Raised if the filter is not a member of this collection.
- setFlags(Flags)
Modifies the flags of the collection.
- Parameters:
Flags (int) – The flags of the collection. See PostFilterCollectionFlags.
- setReadOnly(ReadOnly)
Sets whether the collection is read only.
- Parameters:
ReadOnly (bool)
Deprecated
This function will be removed in a future version. Please use ‘collection.setFlags(collection.POSTFILTERCOLLECTION_EDITABLE | collection.POSTFILTERCOLLECTION_REMOVABLE)’.
- size()
Returns the number of filters in the collection.
- class mari.Preferences
Bases:
objectManages retrieval and modification of user preferences.
Mariseparates preferences in groups and subgroups. In the preference dialog, a group is represented by a tab, and a subgroup by a group box.Preference groups and individual preferences are accessed in a similar way to a folder and file structure. For example, calling
list()might return('Data/', 'Scripts/'), and their subgroups could be displayed by callinglist('Data').All preferences have a group and subgroup, so values will always be accessed in the form:
Example Code
>>> import mari >>> original_autosave_interval = mari.prefs.get('Data/Autosave/autosaveInterval') >>> mari.prefs.set('Data/Autosave/autosaveInterval',15) >>> mari.prefs.get('Data/Autosave/autosaveInterval') 15 >>> mari.prefs.set('Data/Autosave/autosaveInterval',original_autosave_interval)
Attention
Dynamically created preferences don’t persist between sessions. In order to achieve this you can save and load data using the Settings interface.
Alias
prefs
- get(Path)
Returns the value of the preference with the given path.
The path matching is case insensitive.
- Parameters:
Path (str) – The path to the preference
- Returns:
variant– The current value of the preference
- list(Path='str')
Returns a list of the available preferences or preference groups in the given path.
The path matching is case insensitive.
- Parameters:
Path (str, optional) – The path to list groups, subgroups, or preferences for. Defaults to str.
- prettyPropertyName(PropertyName)
Method used to filter and catch changes to dynamic properties.
- Parameters:
PropertyName (str)
- remove(Path)
Deregisters the preference of the given path.
The path matching is case insensitive.
- Parameters:
Path (str) – The path to the preference
- Raises:
ValueError – Raised if no preference with the given path was found.
- set(Path, Value)
Modifies the value of the preference with the given path.
The path matching is case insensitive.
- Parameters:
Path (str) – The path to the preference
Value (variant) – The new value to store
- Raises:
ValueError – Raised if the preference could not be set to the value.
- setChangedScript(Path, ChangedScript)
Sets the script to execute if the preference of the given path is changed.
The path matching is case insensitive.
- Parameters:
Path (str) – The path to the preference
ChangedScript (str) – The script to execute if the preference is changed
- Raises:
ValueError – Raised if no preference with the given path was found.
- setDefault(Path, Default)
Sets the value to reset the preference of the given path to.
The path matching is case insensitive.
- Parameters:
Path (str) – The path to the preference
Default (variant) – The value to be reset to. A value of ‘None’ disables reset
- Raises:
ValueError – Raised if no preference with the given path was found.
- setDisplayName(Path, DisplayName)
Sets the used when presenting the preference of the given path to the user.
The path matching is case insensitive.
- Parameters:
Path (str) – The path to the preference
DisplayName (str) – The name used when presenting the preference to the user
- Raises:
ValueError – Raised if no preference with the given path was found.
- setItemList(Path, ItemList)
Sets the list of available options the preference of the given path is allowed to be set to.
The path matching is case insensitive.
- Parameters:
Path (str) – The path to the preference
ItemList (list of str) – The list of available options the value is allowed to be set to
- Raises:
ValueError – Raised if no preference with the given path was found or it’s not supported on the type.
- setRange(Path, Min, Max)
Sets the allowed range of the preference of the given path.
The path matching is case insensitive.
- Parameters:
Path (str) – The path to the preference
Min (variant) – The minimum value possible
Max (variant) – The maximum value possible
- Raises:
ValueError – Raised if no preference with the given path was found or it’s not supported on the type.
- setStep(Path, Step)
Sets the step size used when incrementing the preference of the given path.
The path matching is case insensitive.
- Parameters:
Path (str) – The path to the preference
Step (variant) – The step size used when incrementing the value
- Raises:
ValueError – Raised if no preference with the given path was found or it’s not supported on the type.
- class mari.ProceduralLayer
Bases:
AdjustableLayerProcedural layers use GPU processing operations to generate image data.
These layers will normally take up no disk space, but consume GPU processing time to calculate their image data whenever it is visible. As an alternative, they can be cached, which will consume disk space for the cached image data, but decrease GPU processing time.
You can access all types of layers from their containing
Channelobjects - for example:channel.layerList()You can check for
ProceduralLayerobjects by callingLayer::isProceduralLayer():Example Code
>>> #This example finds procedural layers in the current channel >>> import mari >>> procedural_layers = [] >>> channel = mari.geo.current().currentChannel() >>> for layer in channel.layerList(): ... if layer.isProceduralLayer(): ... procedural_layers.append(layer)
>>> #This example creates an "Brightness" procedural layers in the current channel >>> import mari >>> channel = mari.geo.current().currentChannel() >>> layer = channel.createProceduralLayer("Constant","Basic/Constant") >>> layer.isProceduralLayer() True
- convertToPaintable(SelectedOnly=False)
Converts the layer into a paintable layer.
As this operation changes the layer type, it is suggested that you reobtain a reference to this layer.
- Parameters:
SelectedOnly (bool, optional) – Whether or not to bake the result into all patches or only the selected patches. Defaults to False.
- exportImages(PathAndTemplate, UVIndexList, Options='Image.DEFAULT_OPTIONS', FileOptions='variant', OutputColorConfig='nullptr')
Exports a set of images from the layer.
This is the same as selecting “Export Selected Layers” from the GUI with only the given layer selected. To export the entire layer stack, call
LayerStack::exportImages().Pass in the path and template to export the files to - for example:
>>> import mari >>> layer = mari.geo.current().currentChannel().currentLayer() >>> layer.exportImages('/tmp/$CHANNEL.$LAYER.$UDIM.tif')
Only paintable and procedural layers can be exported individually in this way.
- Parameters:
PathAndTemplate (str) – The target path for the export and the template to export the files to, in a single string.
Options (Image.SaveOptionsFlags, optional) – Pass in a value other than the default to turn on an option, such as disabling “small uniforms”. See
Image::SaveOptions. Defaults to Image.DEFAULT_OPTIONS.UVIndexList (list of
int) – Pass in a list of zero-based UV indices if desired to specify the patches to export images for. If not specified or empty, images will be exported for all indices. The UDIM for a patch is the zero-based UV index plus 1001.FileOptions (variant, optional) – This is a key/value map of optional parameters passed to the file writer plugin. Defaults to variant.
OutputColorConfig (ColorspaceConfig, optional) – The output colorspace configuration, used during export. Defaults to nullptr.
- Raises:
ValueError – Raised if the path and template parameter was empty, or if an invalid UV index was specified, or if the colorspace configuration is not valid.
IOError – Raised if an error occurred with the export process.
See also
LayerStack::exportImages(), PaintableLayer::exportImages(), PaintableLayer::importImages()
- exportSelectedPatches(PathAndTemplate, Options='Image.DEFAULT_OPTIONS', FileOptions='variant', OutputColorConfig='nullptr')
Exports images for the selected patches from this layer.
Pass in the path and template to export the files to - for example:
>>> layer.exportSelectedPatches('/tmp/$CHANNEL.$LAYER.$UDIM.tif')Only paintable and procedural layers can be exported individually in this way.
- Parameters:
PathAndTemplate (str) – The target path for the export and the template to export the files to, in a single string.
Options (Image.SaveOptionsFlags, optional) – Pass in a value other than the default to turn on an option, such as disabling “small uniforms”. See
Image::SaveOptions. Defaults to Image.DEFAULT_OPTIONS.FileOptions (variant, optional) – This is a key/value map of optional parameters passed to the file writer plugin. Defaults to variant.
OutputColorConfig (ColorspaceConfig, optional) – The output colorspace configuration, used during export. Defaults to nullptr.
- Raises:
ValueError – Raised if the path and template parameter was empty, or if an invalid UV index was specified, or if the colorspace configuration is not valid.
IOError – Raised if an error occurred with the export process.
See also
importImages(), LayerStack::exportImages(), ProceduralLayer::exportImages()
- getProceduralParameter(ParameterName)
Retrieves the current value of a parameter from this procedural layer.
- Parameters:
ParameterName (str) – The name of the parameter to inspect.
- Raises:
ValueError – Raised if name of the parameter does not match any existing items. Or there is an issue with the image value.
TypeError – Raised if the parameter does not relate to an image.
- Returns:
variant– QVariant The current value of the parameter.
See also
setProceduralParameter()
- getProceduralParameterAsImage(ParameterName)
Retrieves the current value of a parameter from this procedural layer and, if possible, return the Image it relates to.
- Parameters:
ParameterName (str) – The name of the parameter to inspect.
- Raises:
ValueError – Raised if name of the parameter does not match any existing items.
- Returns:
Image– Image of the parameter. None if not image is assigned.
See also
getProceduralParameter()
- proceduralParameters()
Returns the list of parameters on this procedural layer.
- Returns:
list of str– A list of the parameter names for this procedural layer.
- proceduralType()
Get the name of the procedural type.
- Returns:
str– The name of the type of procedural, which will be of the form ‘Procedural/Fractal/Cloud’
- setProceduralParameter(ParameterName, NewValue)
Sets the value of a parameter on the procedural layer.
- Parameters:
ParameterName (str) – The name of the parameter to modify.
NewValue (variant) – The new value for the parameter. This can be of a variety of types.
- Raises:
ValueError – Raised if the parameter could not be found, or was invalid.
See also
getProceduralParameter()
- class mari.Project
Bases:
PropertySourceProvides access to a currently open project.
A project stores information about a currently open user session. It contains the geometry textures, reference images, and all associated user settings. This object provides basic access to the project.
Data for the project is stored in
Mari‘s internal caching system. To export the project fully the user may archive it.Projects can be accessed through the
ProjectManager- for example:mari.projects.current()Note that it is not possible to obtain a
Projectobject for a project that is not currently open. To obtain information about an available unopened project, get aProjectInfoobject using a function call like the following:mari.projects.find('blacksmith')Example Code
>>> # This example shows how to obtain the Project object representing the current project >>> import mari >>> project = mari.projects.current() >>> print(project.className()) Project
- LIGHTING_BASIC = 1
Basic lighting from above, front.
- Type:
int
- LIGHTING_FLAT = 0
A flat, uniform, directionless light.
- Type:
int
- LIGHTING_FULL = 2
User-controllable lighting.
- Type:
int
- class LightingMode
Bases:
objectOptions for lighting the main model.
- LIGHTING_BASIC = 1
Basic lighting from above, front.
- Type:
int
- LIGHTING_FLAT = 0
A flat, uniform, directionless light.
- Type:
int
- LIGHTING_FULL = 2
User-controllable lighting.
- Type:
int
- backupPath()
Returns the directory path where incrememtal backups of the project will be saved.
- Returns:
str– The path of the backup directory, as a string.
- backupPathChanged(Path)
This is emitted when the backup path is modified.
- Parameters:
Path (str)
- close(ConfirmIfModified=True)
Closes the project.
- Parameters:
ConfirmIfModified (bool, optional) – Set to false to suppress the confirmation dialog that normally appears if the project has been modified. Defaults to True.
- closing()
This is emitted when the project is about to close.
- colorspaceDefaults()
Returns the colorspace defaults for the project.
- Returns:
ColorspaceDefaults– The colorspace defaults.
- colorspaceDefaultsChanged(Defaults)
This is emitted after the colorspace defaults are modified for this object.
- Parameters:
Defaults (ColorspaceDefaults)
- description()
Returns the description of the project.
- Returns:
str– The description of the project.
- info()
Returns information about the current project.
- Returns:
ProjectInfo– An object describing the current project
- isDirty()
Returns the dirty (modified) status of the project.
Marimaintains a dirty state for projects when they are open. If a project is dirty it has been modified since it was loaded. Only dirty projects are saved. If a project is dirty when it is closed the user will be presented with a dialog asking them if they wish to save. Saving a project clears the dirty state.This is the same as
isModified().- Returns:
bool– True if the project is dirty, and has been modified since it was opened, or false otherwise
- isModified()
Returns the modified status of the project.
This is the same as
isDirty().- Returns:
bool– True if the project has been modified since it was opened, or false otherwise
- isSaved()
Returns the saved status of the project.
- Returns:
bool– True if the project has been saved on disk since it’s creation
- lightingMode()
Returns the current lighting mode set on the main model.
- Returns:
LightingMode– The lighting mode set.
- name()
Returns the name of the project.
- Returns:
str– The name of the project.
- remapConfigColorspaces(ColorspaceRemappings, Stages, FileName='str')
Switches a given set of colorspaces for another in all configurations in the project.
- Parameters:
ColorspaceRemappings (dict<str,variant>) – Table used to define what a particular colorspace should map to, where the key is the old colorspace we want to swap, and the value is the new colorspace we want to swap it to.
FileName (str, optional) – Only remap if the
OpenColorIOconfiguration file matches this. If empty string is given then the remapping is done regardless of theOpenColorIOconfiguration file. Defaults to str.Stages (list of
int) – The colorspace stages to consider for remapping. Used to selectively ignore colorspaces at certain stages such as the output stage. If an empty list is given then all stages are considered.
- Raises:
ValueError – Raised if the colorspace remapping table is empty. If any of the stages are invalid. Or if an invalid OCIO config file is given.
- removeInvalidImageTags()
Check all the images in this project and removes any invalid tags on them.
- Returns:
bool– Whether any invalid tag was removed.
- save(ForceSave=False, BackupOptions='variant')
Saves the project.
- For the built-in geometry types, the meta keys currently supported are:
“DiskUsage” - Gather and log disk usage statistics for both the source project sub-cache and destination backup directories. This significantly increases the time to make a backup and can be switched off if speed is an issue (type bool; default is True).
“PostProcesss” - Spawn a number of detached processes and run a specific command in each once the backup completes. This is to allow other operations dependant on a backup to be run at the right point. (type list(str); default is [] or do nothing).
“PreCull” - Calculate which hash files already exist in the destination using the “DataHashes*.txt”, rather than checking for their existance on the file system which can be expensive (type bool; default is False).
“Suffix” - Guarantee the suffix used to name the files of a backup so that an external process can more easily work with the system. When given, “Tags” are ignored. See mari.projects.generateRestoreSuffix (type str; default is None).
“Tags” - An list of strings used to tag the backup with so it can be more easily identified in the future (type list(str); default is []).
- Parameters:
ForceSave (bool, optional) – Set to true to force the save to be performed even if the project has not been modified. Defaults to False.
BackupOptions (variant, optional) – An optional dictionary of settings used when the backup that is make. Defaults to variant.
- Raises:
ValueError – Raised if backup options are provided but the project has no assigned backup location.
ValueError – Raised if any supplied backup option “Tags” contain unsuitable file name characters.
- saved()
This is emitted after the project is saved.
- setBackupPath(Path)
Sets the directory path where incrememtal backups of the project will be saved.
- Parameters:
Path (str) – The path of the backup directory, as a string.
- setColorspaceDefaults(Defaults)
Sets the colorspace defaults for the project.
- Parameters:
Defaults (ColorspaceDefaults) – The colorspace defaults.
- Raises:
ValueError – Raised if the colorspace defaults are invalid.
- setDescription(Description)
Sets the description of the project.
- Parameters:
Description (str) – The descrption of the project.
- setLightingMode(Mode)
Sets the lighting mode on the main model.
- Parameters:
Mode (LightingMode) – The lighting mode to set.
- updatePatchResolutionInfo()
Updates the GUI overlay resolution information for all of the patches in the project.
This can be useful to update patch resolution information that is out of date after patches have been resized.
- uuid()
Returns the UUID of the project.
- Returns:
str– The UUID of the project, as a string.
- class mari.ProjectInfo
Bases:
MetadataHolds preview information about an available project.
These objects provide summary information about the projects that are available in the user’s cache directory.
You can set metadata on
ProjectInfoobjects to be accessed at any time, including when the project is closed. This data will persist automatically, without the need for an explicit save. You can also add metadata items to the tool tip text displayed when the user hovers their mouse over the project icon.You can access project information through the
ProjectManager- for example:mari.projects.list()Example Code
>>> # This example shows how to print the list of names of existing projects to the application log >>> import mari >>> for project_info in mari.projects.list(): ... mari.app.log(project_info.name())
- addArchiveRecord(ArchivePath, CreatedAt='QDateTime.currentDateTime')
Records a new archive that has been created from this project.
- Parameters:
ArchivePath (str) – The path of the archive file on disk.
CreatedAt (QDateTime, optional) – The date/time at which the archive was created. Defaults to the current local date/time when omitted. Defaults to QDateTime.currentDateTime.
- addMetadataToToolTip(Name)
Adds the metadata item to the tool tip display for the project.
Hovering the mouse pointer over a project icon will display a short summary of information about the project. Call this function to add the metadata item with the specified name to that display.
If the metadata item is already in the tool tip display, this function will do nothing.
The list of metadata items to display is itself stored in the metadata item ‘ToolTipItems’. You can also manipulate this directly as a list of strings if desired.
- Parameters:
Name (str) – The name of the metadata item to display
- Raises:
ValueError – Raised if no metadata item with the given name exists.
See also
removeMetadataFromToolTip()
- archiveHistory()
Returns the history of archives that have been created from this project.
- Returns:
list of variant– A list of dicts, ordered from oldest to newest, each with a ‘Path’ entry (the path to the archive file on disk) and a ‘Created’ entry (the date/time at which it was created). Returns an empty list if no archives have been recorded.
- autosavePath()
Returns the autosave path.
- backupPath()
Returns the directory path where incrememtal backups of the project will be saved.
- cacheDiskUsage()
Return the disk cache usage of this project in bytes. If this returns 0 the cache usage may not have been calculated on this project. Older projects may be in this state.
- Raises:
RuntimeError – If the size has not been calculated for this project yet. Old projects may not have this value calculated. Loading and re-saving the project will solve this problem.
- close(ConfirmIfModified=True)
Closes the project.
- Parameters:
ConfirmIfModified (bool, optional) – If true (the default), a confirmation dialog is displayed if the project has been modified. Defaults to True.
- Raises:
RuntimeError – Raised if the project is already closed.
- createdTime()
Returns the time and date that the project was created.
- description()
Returns the description of the project.
- isEnabled()
Returns if the porjected is enabled, i.e. can be opened, or not.
If the project is enabled it is available to open in the GUI. If disabled, the project is greyed out and unavailable to open through the GUI. The project may still be opened using
open().- Returns:
bool– True is enabled, false if disabled.
- isMinionProject()
Return true if this project was created using Mari Minion.
- Returns:
bool– True if Mari Minion was used to create this project, false otherwise
- isNull()
Returns true if this is a null record, and the project is invalid.
- isOpen()
Returns true if the project is open, or false otherwise.
- lastArchiveIsUpToDate()
Determines if the most recently created archive of this project is up to date.
- Returns:
bool– True if the last recorded archive was created at or after the project was last modified, false if the project has since been modified, or if no archives have been recorded.
- lastModifiedTime()
Returns the time and date of the last modification to the project.
- modelPath()
Returns the path to the model file used in the project.
For projects that contain multiple models, this will return the currently selected one.
For models with multiple versions, the currently selected version will be used.
See also
modelPathList()
- modelPathList()
Returns the paths to all model files used in the project.
For models with multiple versions, the currently selected version will be used.
See also
modelPath()
- name()
Returns the name of the project.
- open()
Opens the project.
- Raises:
IOError – Raised if the project was found, but there was an error opening it.
RuntimeError – Raised if there was already a project open, since only one can be open at a time.
- Returns:
Project– The newly opened project.
- projectDirectories()
Returns the directory for the project.
- projectPath()
Returns the project path.
- recentIndex()
Returns the index of the project in the list of recently opened projects.
- Returns:
int– The index of the project in the recent projects list, starting from 0 for the first. If the project is not in the list, the result will be -1.
Deprecated
Please use lastModifiedTime() instead.
- removeMetadataFromToolTip(Name)
Removes the metadata item from the tool tip display for the project.
If the metadata item is not currently in the tool tip display, this function will do nothing.
If the metadata item is removed, it will also be automatically removed from the tool tip display, so there is no need to call this function in that case.
The list of metadata items to display is itself stored in the metadata item ‘ToolTipItems’. You can also manipulate this directly as a list of strings if desired.
- Parameters:
Name (str) – The name of the metadata item to remove
- Raises:
ValueError – Raised if no metadata item with the given name exists.
See also
addMetadataToToolTip()
- setEnabled(Enabled)
Sets the project to enabled or disabled.
- Parameters:
Enabled (bool) – If true, the project will be available to open in the GUI. If false, the project will not be available to be open in the GUI. The project may still be opened using
open().
- setTags(Tags)
Sets the current tags on the project.
- Parameters:
Tags (list of str)
- subcachePath()
Returns the subcache path for the project.
Deprecated
Please use uuid() instead.
- tagHistory()
Returns all the tags that have been applied throughout the project’s lifetime.
- tags()
Returns the tags currently applied to the project.
- uuid()
Returns the UUID of the project.
- version()
Returns the version of Mari that the project was saved in.
This will include only major and minor version numbers, so for example both 1.3v1 and 1.3v2 will be shown as 1.3.
In some cases, such as for older projects without version information, this may be a string such as “Unknown”.
- Returns:
str– The version of Mari that the project was saved in
- versionHistory()
Returns the history of Mari versions the project has been saved in.
- Returns:
str– A list of the Mari version numbers that the project has been saved in, starting with the one in which it was saved. Some data may be missing from projects created or saved in Mari versions that do not support this functionality.
- class mari.ProjectManager
Bases:
objectHandles opening, closing, and general manipulation of projects.
Information about the available projects can be obtained using the
list()method. This returnsProjectInfoobjects to describe the projects can be opened. These projects will only be available asProjectobjects after opening.Example Code
>>> # This example shows how to obtain the Project object representing the current project >>> import mari >>> project = mari.projects.current()
Alias
projects
- ANY = 2
Projects from any version of Mari can be loaded (be careful with this)
- Type:
int
- ASK = 3
Ask the user with message boxes whether they want to load other project versions.
- Type:
int
- class AllowedVersions
Bases:
objectDetermines the versions of project that can be loaded.
- ANY = 2
Projects from any version of Mari can be loaded (be careful with this)
- Type:
int
- ASK = 3
Ask the user with message boxes whether they want to load other project versions.
- Type:
int
- EXACT = 0
Only projects from exactly this version of Mari can be loaded.
- Type:
int
- OLDER_OR_EXACT = 1
Projects from older versions or the current version can be loaded.
- Type:
int
- EXACT = 0
Only projects from exactly this version of Mari can be loaded.
- Type:
int
- FORCE_EMPTY = 3
Use zero values for UVs.
- Type:
int
- FORCE_PTEX = 1
Force Ptex mode.
- Type:
int
- KEEP_SEPARATE = 1
Keep multiple surfaces as separate Mari geometries in a single object (Ptex only).
- Type:
int
- MERGE_GEOMETRIES = 0
Merge multiple surfaces in the obj file into one Mari geometry in a single object; this is the default value.
- Type:
int
- class MeshOptions
Bases:
objectMesh options for choosing the texturing method in projects.
- FORCE_EMPTY = 3
Use zero values for UVs.
- Type:
int
- FORCE_PTEX = 1
Force Ptex mode.
- Type:
int
- UV_OR_EMPTY = 2
Use UVs if they exist, or zero values if there are none.
- Type:
int
- UV_OR_PTEX = 0
Use UVs if they exist, or Ptex if there are none; this is the default value.
- Type:
int
- class MultipleGeometryOptions
Bases:
objectMultiple geometry options for importing obj files.
- KEEP_SEPARATE = 1
Keep multiple surfaces as separate Mari geometries in a single object (Ptex only).
- Type:
int
- MERGE_GEOMETRIES = 0
Merge multiple surfaces in the obj file into one Mari geometry in a single object; this is the default value.
- Type:
int
- class OCIOOptions
Bases:
objectDetermines the course of action to take when opening a project that uses an OCIO config that doesn’t match the OCIO environment variable.
- OCIO_ASK = 3
Ask the user with a message box what to do when the project’s OCIO config doesn’t match the OCIO environment variable.
- Type:
int
- OCIO_EXACT = 0
Only projects with OCIO configs that match the OCIO environment variable can be loaded.
- Type:
int
- OCIO_REMAP = 2
Projects with OCIO configs that don’t match the OCIO environment variable will be switched to match and any colorspaces and/or roles with matching names will be maintained.
- Type:
int
- OCIO_RESET = 1
Projects with OCIO configs that don’t match the OCIO environment variable will be switched to match and have their colorspaces reset to defaults.
- Type:
int
- OCIO_ASK = 3
Ask the user with a message box what to do when the project’s OCIO config doesn’t match the OCIO environment variable.
- Type:
int
- OCIO_EXACT = 0
Only projects with OCIO configs that match the OCIO environment variable can be loaded.
- Type:
int
- OCIO_REMAP = 2
Projects with OCIO configs that don’t match the OCIO environment variable will be switched to match and any colorspaces and/or roles with matching names will be maintained.
- Type:
int
- OCIO_RESET = 1
Projects with OCIO configs that don’t match the OCIO environment variable will be switched to match and have their colorspaces reset to defaults.
- Type:
int
- OLDER_OR_EXACT = 1
Projects from older versions or the current version can be loaded.
- Type:
int
- PTEXFORMAT_BYTE = 0
Unsigned byte image data.
- Type:
int
- PTEXFORMAT_FLOAT = 2
Float image data.
- Type:
int
- PTEXFORMAT_HALF = 1
Half float image data.
- Type:
int
- PTEX_UNIFORM_SIZE = 0
All faces all have a uniform texture size. The size is specified in the value of the PtexFaceSize meta option.
- Type:
int
- PTEX_WORLD_SPACE_DENSITY_SIZE = 1
Faces have texture sizes proportional to their model sizes. The texel density is specified in the value of the PtexFaceSize meta option.
- Type:
int
- class PtexFaceSizeScheme
Bases:
objectPtex schemes for setting face sizes.
- PTEX_UNIFORM_SIZE = 0
All faces all have a uniform texture size. The size is specified in the value of the PtexFaceSize meta option.
- Type:
int
- PTEX_WORLD_SPACE_DENSITY_SIZE = 1
Faces have texture sizes proportional to their model sizes. The texel density is specified in the value of the PtexFaceSize meta option.
- Type:
int
- class PtexFormat
Bases:
objectPtex image data formats.
- PTEXFORMAT_BYTE = 0
Unsigned byte image data.
- Type:
int
- PTEXFORMAT_FLOAT = 2
Float image data.
- Type:
int
- PTEXFORMAT_HALF = 1
Half float image data.
- Type:
int
- UV_OR_EMPTY = 2
Use UVs if they exist, or zero values if there are none.
- Type:
int
- UV_OR_PTEX = 0
Use UVs if they exist, or Ptex if there are none; this is the default value.
- Type:
int
- aboutToArchive(UUID, FileName)
This is emitted just before a project is archived.
- Parameters:
UUID (str) – The unique identifier of the project
FileName (str) – The filename of the archive
See also
archived()
- aboutToClose(CurrentProject)
This is emitted just before a project is closed.
- Parameters:
CurrentProject (Project) – The project
Mariis about to close
See also
closed()
- aboutToExport()
This is emitted just before an export operation.
This signal is emitted before an export operation, and allows message hooks to be attached to Images, for example.
- aboutToExtractArchive(UUID, FileName)
This is emitted just before a new project is going to be created from an archive.
- Parameters:
UUID (str) – The unique identifier of the new project.
FileName (str) – The filename of the archive.
- aboutToOpen(UUID)
This is emitted just before a new project is opened.
- Parameters:
UUID (str) – The unique identifier of the project
Mariis about to open
See also
opened()
- aboutToSave(ProjectToSave)
This is emitted just before a project is saved.
- Parameters:
ProjectToSave (Project) – The project about to be saved
See also
saved()
- aboutToSaveNew(NewProject)
This is emitted when a new project has been created, and is about to be saved.
This can be used to apply modifications to a project before its initial save, for example.
- Parameters:
NewProject (Project) – The newly-created project
See also
created()
- archive(rUUIDOrName, rTargetFileName, ArchiveAll=True, KeepOnError=False)
Archives the project with the given UUID or name into a .mra file.
- Parameters:
rUUIDOrName (str) – The UUID or name of the project to archive. This is checked in the same way as in
open().rTargetFileName (str) – The file name of the archive to create.
ArchiveAll (bool, optional) – Whether or not all files within the project sub-cache directory should be included in the archive, and not just those specific to the project. When false, this can reduce the number of files in the archive along with it’s final size, as files from autosave and backups will be excluded. Defaults to True.
KeepOnError (bool, optional) – Whether or not the archive should be kept when an error occurs with one or more of the files being archived. Sometimes files may be corrupted but it’s still useful to create an archive in order to backup the data before recover is attempted. Defaults to False.
- Raises:
RuntimeError – Raised if the user cancelled the operation.
ValueError – Raised if no project with the given UUID or name could be found.
RuntimeError – Raised if the project could not be archived because it was open.
IOError – Raised if an I/O error occurred during the archiving process.
Note
Additional custom user data can be included in the archive by storing it within the project sub-cache directory under a “UserData” directory.
- archiveBackup(UUIDOrName, rTargetFileName, rSuffix='str', ArchiveAll=False, KeepOnError=False)
Create a .mra archive from an existing project backup.
A background process is spawned to generate the archive.
- Parameters:
UUIDOrName (str) – The UUID or name of the project to archive a backup of. This is checked in the same way as in
open().rTargetFileName (str) – The file name of the archive to create.
rSuffix (str, optional) – The suffix of the backup point to archive. If none is given then the latest will be archived. Defaults to str.
ArchiveAll (bool, optional) – Whether or not all files within the project sub-cache directory should be included in the archive, and not just those specific to the project. When true, this can reduce the number of files in the archive along with it’s final size, as files from autosave and backups will be excluded. Defaults to False.
KeepOnError (bool, optional) – Whether or not the archive should be kept when an error occurs with one or more of the files being archived. Sometimes files may be corrupted but it’s still useful to create an archive in order to backup the data before recover is attempted. Defaults to False.
- Raises:
ValueError – Raised if no project with the given UUID or name could be found.
ValueError – Raised if the project could not be archived because of invalid setup.
- archived(UUID, FileName)
This is emitted after a project is successfully archived.
- Parameters:
UUID (str) – The unique identifier of the project
FileName (str) – The filename of the archive
See also
aboutToArchive()
- backupRestored(UUID, NewlyCreated)
This is emitted when a project backup is restored.
- Parameters:
UUID (str) – The unique identifier of the restored project.
NewlyCreated (bool) – False if an existing project restored, or true if a new project was created from the backup.
See also
restoreBackup()
- cachePath()
Returns the path to the Mari cache directory, where the projects are stored.
- Returns:
str– The absolute path to the cache
- close(ConfirmIfModified=True)
Closes the project.
- Parameters:
ConfirmIfModified (bool, optional) – Set to false to suppress the confirmation dialog that normally appears if the project has been modified. Defaults to True.
- closed()
This is emitted after a project is closed.
See also
aboutToClose()
- copy(rUUIDOrName)
Makes a duplicate of the project with the given UUID or name.
This is the same as
duplicate().- Parameters:
rUUIDOrName (str) – The UUID or name of the project to archive. This is checked in the same way as in
open().- Raises:
RuntimeError – Raised if the user cancelled the operation.
ValueError – Raised if no project with the given UUID or name could be found.
RuntimeError – Raised if the project could not be archived because it was open or in use.
IOError – Raised if an I/O error occurred during the duplication process.
- Returns:
ProjectInfo– An object with information about the newly copied project
See also
duplicate
- create(Name, MeshPaths, ChannelsToCreate, ChannelsToImport, ProjectMetaOptions='variant', ObjectsToLoad='variant', ColorspaceSettings='nullptr', UUID='str', GarbageCollectionEnabled=True)
Creates and opens a new project with the parameters supplied.
Many parameters of the channels that are imported are ignored, such as the size and bit depth, which are read from the file.
At least one channel must be created or imported. If not, an exception will be raised.
Projects currently cannot be created while another project is open.
Options controlling the geometry load can be passed to the function in the dictionary parameter ProjectMetaOptions. The dictionary keys must be strings, and the values can be any simple type (i.e., no lists or other containers). The geometry loader plug-in that interprets the mesh to be loaded will receive the options passed in here that it recognises, and the others will be ignored.
When used in combination with the C API, this allows users to pass in parameters with specified names to a custom geometry loader. See the C API documentation for further details.
- For the built-in geometry types, the meta keys currently supported are:
“MappingScheme” - geometry mapping scheme (type MeshOptions).
“MultipleGeometries” - how to handle multiple geometries in a single object (type MultipleGeometryOptions).
“PtexFaceSizeScheme” -
Ptexspecific: scheme to use for face texture size calculations (type PtexFaceSizeScheme).“PtexFaceSize” -
Ptexspecific: size to use with the scheme above (type int).“PtexImageFormat” -
Ptexspecific: image data format (type PtexFormat).“PtexFaceColor” -
Ptexspecific: color to clear faces to (typeColor).“PtexImportFilename” -
Ptexspecific: import an existingPtexfile onto the .obj geometry (type string).“PtexShowCreationDialog” -
Ptexspecific: show thePtexcreation dialog after mesh loading (type Bool; default is False from Python).“EachMeshCreatesObject” - each mesh can either create an Object or each be a geometry within a single Object. This is currently
Ptexspecific. (type Bool; default is True).“MergeType” - merging of geometries can be either single-mesh or just-merge-nodes (
Mari::GeoManager::MergeType).“MergeSelectionGroupWithSameNameType” - merging of face selection groups that have the same name (
Mari::GeoManager::MergeSelectionGroupWithSameNameType) - default isMari::GeoManager::MERGESELECTIONGROUP_MERGE_SELECTIONGROUP_HAVING_SAME_NAME“CreateSelectionSets” - specify whether to create selection sets from face groups (
Mari::GeoManager::CreateSelectionSetOptions) - default value isMari::GeoManager::SELECTION_GROUPS_CREATE_FROM_FACE_GROUPS“FrameOffset” - specify the start frame in
Mari‘s timeline to import the geometry (default value is zero).“GeoChannels” - specify whether to create Geo-Channel(s) on a single
GeoEntityadded as part of thecreate()function. This is a dictionary of {key = names of geo-channels to create, value = image path template to import a sequence of images onto the geo-channel}. Note that the geo-channels will only be added if there is a singleGeoEntitycreated, either through all the geo meshes merged together or a single geo mesh being specified. In the case of multiple GeoEntities, please use theGeoEntity::createGeoChannelAPI once the objects have been added.
- For USD geometries, the following meta keys are supported.
“Load” - specify which meshes are loaded (type string). “All Models” will load all meshes in the file; this is the default when the option is omitted. “First Found” will load the first mesh found. “Specified Models in Model Names” will only load the meshes specified in the “Model Names” meta key.
“Model Names” - the comma separated list of model names to load from the USD file (type string). Only used when the “Load” option is set to “Specified Models in Model Names”. Note that each model name needs to be the full path of the item in the USD file.
“Merge Type” - USD specific: how multiple loaded models are combined (type string). “Merge Models” will merge all loaded models into a single
Marigeometry; this is the default. “Keep Models Separate” will keep each loaded model as a separate child geometry.“Mapping Scheme” - USD specific: geometry mapping scheme (type string). “UV if available, Ptex otherwise” is the default. Other values are “Force Ptex”, “UV if available, empty otherwise”, and “Force empty”.
“UV Set” - USD specific: the name of the UV set to use for texturing (type string), chosen from the UV sets found in the file. Has no effect if the file contains no UV sets.
“Frame Numbers” - USD specific: the frame numbers to load from an animated USD file (type string). Accepts a comma separated list of frame numbers and/or ranges (e.g. “1,3,5-10”); default is “1”.
“Gprim Names” - USD specific: the comma separated list of gprim names to import (type string). Each name can be either the gprim’s simple name or its full path in the USD file. If left empty (the default), all gprims found under the loaded models are imported.
“Variants” - USD specific: a space separated list of variant selections to apply before loading (type string), each specified as a prim variant selection path, e.g. “/path{variantSetName=variantName}”. Default is empty, meaning no variant selections are changed.
“Conform to Mari Y as up” - USD specific: whether the geometry is re-oriented so that Y is up in
Mari(type Bool); default is True.“Keep Centered” - USD specific: whether model transforms are discarded so the geometry is centered at the origin (type Bool); default is False.
“Include Invisible” - USD specific: whether gprims with computed invisible visibility are included (type Bool); default is False.
“Create Face Selection Group per mesh” - USD specific: whether a face selection group is created for each imported mesh (type Bool); default is False.
Here is an example of creating a
Ptexproject that does not show thePtexcreation dialog after mesh loading:>>> import mari, os >>> EmptyChannels = [] >>> project_meta_options = dict() >>> project_meta_options["MappingScheme"] = mari.projects.MeshOptions.FORCE_PTEX >>> project_meta_options["MultipleGeometries"] = mari.projects.MultipleGeometryOptions.MERGE_GEOMETRIES >>> project_meta_options["PtexFaceSizeScheme"] = mari.projects.PtexFaceSizeScheme.PTEX_WORLD_SPACE_DENSITY_SIZE >>> project_meta_options["PtexFaceSize"] = 16 >>> project_meta_options["PtexImageFormat"] = mari.projects.PtexFormat.PTEXFORMAT_HALF >>> project_meta_options["PtexFaceColor"] = mari.Color(1, 0.25, 1, 1) >>> project_meta_options["MergeType"] = mari.geo.MergeType.MERGETYPE_SINGLE_MESH >>> project_meta_options["CreateSelectionSets"] = mari.geo.CreateSelectionSetOptions.SELECTION_GROUPS_CREATE_FROM_FACE_GROUPS >>> obj_file = os.path.join(mari.resources.path(mari.resources.EXAMPLES),"Objects","cube.obj") >>> try: ... mari.projects.create("ptex_example", obj_file, EmptyChannels, EmptyChannels, project_meta_options) ... except: ... pass
Here is an example of creating a
Ptexproject from a number of .ptx files, treating each as a geometry within a single Object:>>> import mari >>> ptxFiles = [ "body.ptx", "head.ptx", "larm.ptx", "rarm.ptx" ] >>> EmptyChannels = [] >>> project_meta_options = dict() >>> project_meta_options["EachMeshCreatesObject"] = False >>> try: ... mari.projects.create("ptexoneobjmanygeos", ptxFiles, EmptyChannels, EmptyChannels, project_meta_options) ... except: ... pass
Here is an example of creating a project with frames 1 to 10 of an animated geometry, starting at frame 1001 on the timeline:
>>> import mari >>> EmptyChannels = [] >>> project_meta_options = dict() >>> project_meta_options["StartFrame"] = 1 >>> project_meta_options["EndFrame"] = 10 >>> project_meta_options["FrameOffset"] = 1000 >>> try: ... mari.projects.create("test", "/tmp/animatedGeo.abc", EmptyChannels, EmptyChannels, project_meta_options) ... except: ... pass
Creating an alembic project is slightly different, in the sense that you can additionally pass in a list of items/nodes/objects to load from the file. The latter is a list of dictionary items, each dictionary having the name of the object to load as key and flags to specify whether children of the object should be selected as well and whether the children objects should be merged or not (using the enum type GeometryImportFlags); the latter has all of its children and merged by default.
Here is an example of creating a project from an alembic file, with everything merged (by default)
>>> import mari >>> EmptyChannels = [] >>> project_meta_options = dict() >>> mari.projects.create("test", "/tmp/animatedGeo.abc", EmptyChannels, EmptyChannels, project_meta_options)
Here is an example of creating a project from an alembic file, with root object(and its children) un-merged
>>> import mari >>> EmptyChannels = [] >>> project_meta_options = dict() >>> mari.projects.create("test", "/tmp/animatedGeo.abc", EmptyChannels, EmptyChannels, project_meta_options, [{"/":mari.geo.GeometryImportFlags.GEOMETRY_IMPORT_DONT_MERGE_CHILDREN}, ])
Here is an example of creating a project from an alembic file, with a child object (and its children) selected and merged. Please note that passing None as value to the dictionary of the object to load will set its value to defaults, which is select and merge of of its children objects.
>>> import mari >>> project_meta_options = dict() >>> mari.projects.create("test", "/tmp/village.abc", [], [], project_meta_options, [{"/Person/Head":None}, ])
Merging of objects can be of two types, namely SINGLE_MESH or JUST_MERGE_NODES. While both of the latters combine multiple geometries into one GeoEnity, the former (the default one as well) goes an extra step further to combine the various geometries into one single geometry inside that
GeoEntity; this can lead to more efficient patch layout in the case of PTex. The merge type can be passed in as part of the project_meta_options, as follows:>>> import mari >>> project_meta_options = dict() >>> project_meta_options["MergeType"] = mari.geo.MergeType.MERGETYPE_JUST_MERGE_NODES >>> mari.projects.create("test", "/tmp/animatedGeo.abc", [], [], project_meta_options)
Here is an example of adding 2 geo-channels, Copper and Rust.
>>> import mari >>> project_meta_options = {"GeoChannels": {"Copper" : "/tmp/Copper.$UDIM.tif", "Rust" : "/tmp/Rust.$UDIM.tif", }, } >>> mari.projects.create("test", "/tmp/test.abc", [], [], project_meta_options)
- Parameters:
Name (str) – The name of the project to create.
MeshPaths (variant) – A single path or list of paths to the object file(s) that the project should load.
ChannelsToCreate (list of
ChannelInfo) – A list ofChannelInfoobjects that contain information about the channels to create - such as their size, color depth, and other properties. Generally the channels in this list will not also be imported.ChannelsToImport (list of
ChannelInfo) – A list ofChannelInfoobjects that specify information on the channels that should be imported. These should include valid paths and file template so the textures can be loaded correctly. Imported channels do not need to be included in the rChannelsToCreate list.ProjectMetaOptions (variant, optional) – A dictionary of project creation meta options (see above). Defaults to variant.
ObjectsToLoad (variant, optional) – This is a list of objects to load from the file. Each item of the list is a dictionary that contains the name of the objects to load and various geometry import flags to specify whether the children of the current object are to be selected and whether they are to be merged as well. Defaults to variant.
ColorspaceSettings (ColorspaceDefaults, optional) – The global colorspace settings of the project. Defaults to nullptr.
UUID (str, optional) – A UUID created ahead of time used to assign and identify the newly created project. Defaults to str.
GarbageCollectionEnabled (bool, optional) – Used to either allow or block the
DDIgarbage collector from being automatically started once the project is opened. Switching it off allows remote machines and/or processes to carefully operate on the project without data loss. Defaults to True.
- Raises:
ValueError – Raised if no mesh paths were supplied.
ValueError – Raised if invalid colorspace settings were supplied.
ValueError – Raised if an invalid UUID is supplied.
TypeError – Raised if the mesh paths parameter was not a string or list of strings.
RuntimeError – Raised if another project is already open.
RuntimeError – Raised if the mesh types are invalid for project creation.
- created(NewProject)
This is emitted when a new project has been created, after it has been saved.
This can be used to perform responses to the successful save of a new project.
- Parameters:
NewProject (Project) – The newly-created project
See also
aboutToSaveNew()
- current()
Returns the interface to the current project, or NULL if nothing is loaded.
- Returns:
Project– The currently open project, or NULL if no project is open
- duplicate(rUUIDOrName)
Makes a duplicate of the project with the given UUID or name.
This is the same as
copy().- Parameters:
rUUIDOrName (str) – The UUID or name of the project to archive. This is checked in the same way as in
open().- Raises:
RuntimeError – Raised if the user cancelled the operation.
ValueError – Raised if no project with the given UUID or name could be found.
RuntimeError – Raised if the project could not be archived because it was open or in use.
IOError – Raised if an I/O error occurred during the duplication process.
- Returns:
ProjectInfo– An object with information about the newly duplicated project
See also
copy
- exported()
This is emitted just after an export operation.
This signal is emitted after an export operation, and allows for post-processing or cleanup after export.
- exportedSummary(Summary)
This is emitted just after an export operation.
This signal is emitted just after an export operation, and includes a summary of what has been exported.
- Parameters:
Summary (str) – A string containing a summary of what has been exported.
- extract(rFileName)
Extracts a .mra project archive into a usable project.
- Parameters:
rFileName (str) – The file name of the archive to extract
- Raises:
RuntimeError – Raised if the user cancelled the operation.
ValueError – Raised if no project with the given UUID or name could be found, or if the supplied file name is invalid.
IOError – Raised if an I/O error occurred during the extraction process.
- Returns:
ProjectInfo– An object with information about the newly extracted project
- extractedArchive(UUID, FileName)
This is emitted when a new project has been created from an archive.
- Parameters:
UUID (str) – The unique identifier of the new project.
FileName (str) – The filename of the archive.
- find(rUUIDOrName)
Returns information about the project with the given UUID or name, if one exists.
This function first tries to find and open a project with the given string as a UUID, and if that fails, it tries again looking for the string as a project name.
- Parameters:
rUUIDOrName (str) – The UUID or name of the project to look for.
- Returns:
ProjectInfo– An object describing the project with the given UUID or name if found, or NULL if not.
See also
get()
- generateRestoreSuffix(rTags)
Generates a new unique restore suffix to use in a project backup.
This suffix is used by the backup system to uniquely name the files so that they can reside in the same directory as other backups of a project as well as used to indentify a particular backup.
rTags Optional tags to be included in the final suffix.
- Parameters:
rTags (list of str)
- Raises:
ValueError – Raised if any supplied tags contain unsuitable file name characters.
- Returns:
str– A new suffix suitable for a project backup.
- static generateUUID()
Creates a new UUID which can used to generate a valid project sub-cache ahead of time.
This can then be passed into create to make sure the newly created project is created in that directory.
- Returns:
str– A new UUID suitable for a new project.
- get(rUUIDOrName)
Returns information about the project with the given UUID or name.
This function first tries to find and open a project with the given string as a UUID, and if that fails, it tries again looking for the string as a project name.
- Parameters:
rUUIDOrName (str) – The UUID or name of the project to look for.
- Raises:
ValueError – Raised if no project matching the given UUID or name was found.
- Returns:
ProjectInfo– An object describing the project with the given UUID or name.
See also
find()
- lastRestorePoint(rPath)
Returns the file name suffix of the latest backup for the given project backup directory.
- Parameters:
rPath (str) – The path to the directory where the various backups can be found.
- Raises:
ValueError – Raised if the supplied directory is invalid.
- Returns:
str– The file name suffix of the last backup made.
- list()
Returns a list of ProjectInfo objects, which contain information about the available projects.
- Returns:
list of
ProjectInfo– A list of objects describing the available projects
- names()
Returns the names of the available projects.
- Returns:
list of str– The names of the available projects
- open(rUUIDOrName, Allowed='OLDER_OR_EXACT', OCIO='variant', GarbageCollectionEnabled=True)
Opens the project with the given UUID or name.
This function first tries to find and open a project with the given string as a UUID, and if that fails, it tries again looking for the string as a project name.
If both attempts fail, it raises an exception.
- Parameters:
rUUIDOrName (str) – The UUID or name of the project to open.
Allowed (AllowedVersions, optional) – Determines the project versions of
Marithat can be loaded. The default is to only allow loading projects that were saved in older versions ofMarior the current one. Defaults to OLDER_OR_EXACT.OCIO (variant, optional) – Determines the course of action to take when the project’s OCIO config doesn’t match the one specified by the OCIO environment variable. Either a mari.projects.OCIOOptions or a boolean value can be used. In the case of a boolean value True will be equivalent to mari.projects.OCIOOptions.OCIO_RESET and False will be equivalent to mari.projects.OCIOOptions.OCIO_EXACT. When no option is given mari.projects.OCIOOptions.OCIO_EXACT will be used. Defaults to variant.
GarbageCollectionEnabled (bool, optional) – Used to either allow or block the
DDIgarbage collector from being automatically started once the project is opened. Switching it off allows remote machines and/or processes to carefully operate on the project without data loss. Defaults to True.
- Raises:
ValueError – Raised if no project with the given UUID or name could be found.
IOError – Raised if the project was found, but there was an error opening it - including if the project was from a different version of Mari to those specified as allowed.
RuntimeError – Raised if there was already a project open, since only one can be open at a time.
- Returns:
Project– The newly opened project.
- opened(NewProject, NewlyCreated)
This is emitted just after a project is opened.
- Parameters:
NewProject (Project) – The newly-opened project
NewlyCreated (bool) – True if the project has just been created, or false otherwise
See also
aboutToOpen()
- projectDuplicated(UUID)
This is emitted when a project is duplicated.
- Parameters:
UUID (str) – The unique identifier of the newly duplicated project.
- remove(rUUIDOrName)
Removes, or deletes, the project with the given UUID or name.
- Parameters:
rUUIDOrName (str) – The UUID or name of the project to remove. This is checked in the same way as in
open().- Raises:
ValueError – Raised if no project with the given UUID or name could be found.
RuntimeError – Raised if the project could not be removed because it was open or in use, or if the user cancelled the operation.
- rename(OldName, NewName)
Changes the name of a project.
- Parameters:
OldName (str) – The UUID or name of the project to modify
NewName (str) – The new name for the project. This must not be an empty string.
- Raises:
ValueError – Raised if no project with the given name exists, or if the new name was empty.
- repair(UUIDOrName, rSourcePath='str', rSourceSuffix='str')
Repairs an existing project using a backup or another project directory.
A background process is spawned to scan the project for missing files and copy them back.
- Parameters:
UUIDOrName (str) – The UUID or name of the project to repair. This is checked in the same way as in
open().rSourcePath (str, optional) – The existing backup or project path to locate the missing files from. If no path is given then the project’s backup location is used. Defaults to str.
rSourceSuffix (str, optional) – The suffix of the backup point to archive. If none is given then the latest will be used. Defaults to str.
- Raises:
ValueError – Raised if no project with the given UUID or name could be found.
ValueError – Raised if the project could not be archived because of invalid setup.
- restoreBackup(rPath, UUIDOrName='str', Suffix='str')
Restore a .mri project from a backup.
- Parameters:
rPath (str) – Either the path to the directory where the various backups can be found, or the path to a .mri project file.
UUIDOrName (str, optional) – The UUID or name of the project to overwrite and restore. If empty then a new project will be created from the backup This is checked in the same way as in
open(). Defaults to str.Suffix (str, optional) – The suffix to restore from. This argument is ignored when ‘rPath’ is to an .mri project file. Defaults to str.
- Raises:
RuntimeError – Raised if the user cancelled the operation.
ValueError – Raised if the given path is invalid or no project with the given UUID or name could be found.
IOError – Raised if an I/O error occurred during the restore process.
- Returns:
ProjectInfo– An object with information about the newly restored project
See also
restorePoints
- restorePoints(rPath, rTags)
Returns the file name suffixes of all backups available for the given project backup directory.
- Parameters:
rPath (str) – The path to the directory where the various backups can be found.
rTags (list of str) – Optional tags used to filter by. Wildcard patterns can be used such as “2023-05*”.
- Raises:
ValueError – Raised if the supplied directory is invalid.
- Returns:
list of str– A list of file name suffixes of all the available backups for the directory
- restoreTags(rPath)
Returns the tags of all available backups for the given project backup directory.
- Parameters:
rPath (str) – The path to the directory where the various backups can be found.
- Raises:
ValueError – Raised if the supplied directory is invalid.
- Returns:
list of str– A list of unique tags of all the available backups for the directory
- saved(SavedProject)
This is emitted just after a project is saved.
- Parameters:
SavedProject (Project) – The project that was saved
See also
aboutToSave()
- selected()
Returns a list of ProjectInfo objects, which contain information about the selected projects.
- Returns:
list of
ProjectInfo– A list of objects describing the currently selected projects
- setRestoreSystemTags(rTags)
Registers one or more tags as non-user generated.
Some tags maybe automaticaly generated by pipeline tasks rather than users and should be restricted in the UI to stop it from becoming to cluttered. As such, any backups containing one or more of these tags will only shown under project’s ‘System’ context menu.
- Parameters:
rTags (list of str) – Tags to be treated as system tags and thus restricted in the UI. Passing in an empty list can be used to clear out any existing registered tags.
- Raises:
ValueError – Raised if any of the tags are invalid due to illegal characters.
- showCreateDialog()
Displays the project creation dialog box.
- triggerBackup(rCommands, rPaths, Force=False, Threads=0)
Spawn a detached project backup process in the background.
- Parameters:
rCommands (list of str) –
One or more of the following operations to run on the project backup directory: - “push” - Process any queued backup requests and copy and move the relevant files to the backup location.
”validate” - Check that all the files in the specified folders have a checksum result matching what’s specified in the corresponding “Checksum*.txt”.
”checksums” - Generate any missing “Checksum*.txt” files in the specified backup folders.
”clean” - Remove any data hash files not being referenced by any backup “DataHashes*.txt” file. Warning: Running on a folder that is a parent of a backup directory or the projects directory will delete all backup data blocks throughout that entire tree. Always pass the specific backup directory to clean, not a shared parent folder.
”repair” - Copy any missing data hash files being referenced by the “DataHashes.txt” file.
rPaths (list of str) – One or more directory paths the backup process should operate on. If no paths are given then the process will be run on all the project sub-cache directories.
Force (bool, optional) – By default the backup process will not run if either the ‘MARI__DONT_AUTO_TRIGGER_PROJECT_BACKUP’ environment or the ‘DontAutoTriggerProjectBackup’ config setting are set. This enables these to be ignored and the process to be run regardless. Defaults to False.
Threads (int, optional) – How many threads the process is allowed to use. Specifying a value of zero or less will result in the default being used. Defaults to 0.
- Raises:
ValueError – Raised if any of the supplied commands are invalid.
ValueError – Raised if the supplied directory is invalid.
- updateAvailableProjects()
Reprocesses the project cache for available projects.
Used when projects are modified externally to
Mari.
- class mari.ProjectionManager
Bases:
PropertySourceHandles settings used to project the paint buffer into a scene.
Alias
projection
- X = 0
.
- Type:
int
- Y = 1
.
- Type:
int
- Z = 2
.
- Type:
int
- debugOcclusionResult()
No description
- mirrorAxis()
No description
- mirrorProjectionEnabled()
No description
- paintingMode()
Returns the current paint compositing mode.
- Returns:
Layer.BlendMode– The current painting mode as a string, such as Darken.
- paintingModeList()
Returns the list of possible painting modes.
- Returns:
list– The list of possible painting mode enums, such as Darken, Screen and etc.
- paintingModePath()
Returns the current paint compositing mode path.
- Returns:
str– The current painting mode path, such as /Darken/Darken.
- paintingModePathList()
Returns the list of possible painting mode paths.
- Returns:
list of str– The list of possible painting mode paths, such as /Darken/Darken, /Lighten/Screen and etc.
- paintingModeStr()
Returns the current paint compositing mode.
- Returns:
str– The current painting mode as a string, such as Darken.
- paintingModeStrList()
Returns the list of possible painting modes.
- Returns:
list of str– The list of possible painting modes, such as Darken, Screen and etc.
- setMirrorAxis(Axis)
No description
- Parameters:
Axis (variant)
- setPaintingMode(PaintingMode)
Sets the paint compositing mode of projection.
- Parameters:
PaintingMode (variant) – The new painting mode. Must be of type mari.Layer.BlendMode .
- Raises:
ValueError – Raised if the specified mode is unknown.
- setProperty(PropertyName, NewValue)
Set the value of a given property.
mari.tools.currentTool().setProperty( mari.tools.currentTool().propertiesList()[0],2.0)mari.tools.currentTool().setProperty( mari.tools.currentTool().propertiesList()[0],2.0)- Parameters:
PropertyName (str) – The name of the property to set, this should be found in the list returned by
propertiesList()NewValue (variant) – The new value for the property
- Raises:
ValueError – Raised if the given property is not found on this object or the value passed is incompatible
ValueError – Raised if the property is read only
InternalError – Raised if some other problem was encountered when setting the property
- toggleDebugDrawOcclusion()
No description
- class mari.Projector
Bases:
MetadataProjectors store the specific camera details of a particular view.
This includes the rotation, zoom, and orientation of the view, plus the current paintable area, painting mode, and mask settings. This is much like a bookmark or snapshot of a view.
Use the
camera()attached to the projector to access its camera-like properties, such as its current position and orientation.You can access projectors through the
ProjectorManager- for example:mari.projectors.list()Example Code
>>> # This examples shows how to create a new projector >>> import mari >>> projector = mari.projectors.create("Test Projector") >>> print(projector.name()) Test Projector >>> mari.projectors.remove(projector.name())
- BASIC = 1
Simple lighting.
- Type:
int
- class BitDepth
Bases:
objectThese are the bit depths supported by projectors.
- DEPTH_BYTE = 8
Standard eight bit depth.
- Type:
int
- DEPTH_FLOAT = 32
Full float depth.
- Type:
int
- DEPTH_HALF = 16
Half-float depth.
- Type:
int
- DEPTH_BYTE = 8
Standard eight bit depth.
- Type:
int
- DEPTH_FLOAT = 32
Full float depth.
- Type:
int
- DEPTH_HALF = 16
Half-float depth.
- Type:
int
- class DepthProjectionMode
Bases:
objectSpecifies ways to project via depth - front only, or through all faces.
- FRONT = 0
Project on front faces only.
- Type:
int
- THROUGH = 1
Project on all faces.
- Type:
int
- FLAT = 0
Flat shading.
- Type:
int
- FRONT = 0
Project on front faces only.
- Type:
int
- FULL = 2
Full detail lighting.
- Type:
int
- class LightingMode
Bases:
objectSpecifies available lighting detail levels.
- BASIC = 1
Simple lighting.
- Type:
int
- FLAT = 0
Flat shading.
- Type:
int
- FULL = 2
Full detail lighting.
- Type:
int
- THROUGH = 1
Project on all faces.
- Type:
int
- aboutToSaveImage(SaveImage)
This is emitted just before a unproject image is saved.
- Parameters:
SaveImage (Image) – The image that is going to be saved
- bitDepth()
Returns the current bit depth of the projector.
- Returns:
BitDepth– The current bit depth of the projector
See also
setBitDepth()
- camera()
Returns the camera attached to the projector.
Use this to access the projector’s camera-like properties, such as its current position and orientation.
- clampColors()
Returns the color clamping behavior of the projector.
- Returns:
bool– True if the colors are clamped to the 0..1 range on output, or false otherwise
See also
setClampColors()
- colorspaceConfig()
Returns the colorspace configuration for import and export of the projector.
- Returns:
ColorspaceConfig– The colorspace configuration for import and export.
- colorspaceConfigChanged(Config)
This is emitted after the colorspace configuration for import and export is modified for the projector.
- Parameters:
Config (ColorspaceConfig)
- depthProjectionMode()
Returns the type of depth-dependent projection onto object faces.
- Returns:
DepthProjectionMode– The current type of projection
- exportColorspaceConfig()
Returns the colorspace configuration for export of the projector.
- Returns:
ColorspaceConfig– The colorspace configuration for export.
Deprecated
Both the import and export colorspace configurations have been consolidated together. This function will be removed in a future version. Please use colorspaceConfig() instead.
- exportColorspaceConfigChanged(Config)
This is emitted after the colorspace configuration for export is modified for the projector.
- Parameters:
Config (ColorspaceConfig)
Deprecated
Both the import and export colorspace configurations have been consolidated together. This signal will be removed in a future version. Please use colorspaceConfigChanged() instead.
- exportOptions()
Returns the options passed to the file writer.
- Returns:
variant– The options that are used in exporting images.
- exportPath()
Returns the file path to export the projection to.
- Returns:
str– The file path that projection images are exported to
See also
setExportPath()
- format()
Returns the pixel format of the projection as a string.
- Raises:
RuntimeError – Raised if the current format is not supported.
- frameOffset()
Returns the frame offset of the projection.
- Returns:
int– The frame offset of the projection
- frameOffsetChanged(Offset)
This is emitted when the frame offset is changed.
- Parameters:
Offset (int) – The new frame offset
- height()
Returns the pixel height of the projection.
- Returns:
int– The height in pixels of the projection
- importColorspaceConfig()
Returns the colorspace configuration for import of the projector.
- Returns:
ColorspaceConfig– The colorspace configuration for import.
Deprecated
Both the import and export colorspace configurations have been consolidated together. This function will be removed in a future version. Please use colorspaceConfig() instead.
- importColorspaceConfigChanged(Config)
This is emitted after the colorspace configuration for import is modified for the projector.
- Parameters:
Config (ColorspaceConfig)
Deprecated
Both the import and export colorspace configurations have been consolidated together. This signal will be removed in a future version. Please use colorspaceConfigChanged() instead.
- importFromFile(Path='str')
Sets the camera to the projector’s view and imports the given image into the paint buffer.
If no path is provided, the current import path is used. Otherwise, this function sets the current import path to the one provided.
This function is similar to
projectFromFile(), but does not bake the loaded paint buffer.- Parameters:
Path (str, optional) – The file path to import the projection image from. If the path is empty, the current value of
importPath()is used. Defaults to str.- Raises:
IOError – Raised if the file from the updated image import path does not exist.
See also
projectFromFile()
- importPath()
Returns the file path to import the projection from.
- Returns:
str– The file path to import projection images from
See also
setImportPath()
- lightingMode()
Returns the detail level of the lighting calculations.
- Returns:
LightingMode– The current lighting mode
- makeCurrent()
Changes the camera’s settings to those of the projector.
See also
ProjectorManager::setCurrent()
- name()
Returns the name of the projector.
- Returns:
str– The name of the projector.
- nameChanged(NewName)
This is emitted after the shader has been renamed.
- Parameters:
NewName (str) – The new name of the shader
- paintingMode()
Returns the current paint compositing mode.
- Returns:
Layer.BlendMode– The current painting mode as a mari.Layer.BlendMode enum.
- paintingModePath()
Returns the current paint compositing mode, as a mari.Layer.BlendMode enum.
- Returns:
str– The current painting mode enum, such as mari.Layer.BlendMode.MIX or mari.Layer.BlendMode.MULTIPLY
- paintingModeStr()
Returns the current paint compositing mode.
- Returns:
str– The current painting mode as a string, such as ‘Multiply’ or ‘Lighten’.
- project()
Imports an image and projects onto the geometry in the projector’s view.
This reads an image from the current image import path into the paint buffer and bakes it.
- Raises:
IOError – Raised if the file from the current image import path does not exist.
See also
importPath(), projectFromFile()
- projectFromFile(Path='str')
Projects the given image file onto the geometry in the projector’s view.
If no path is provided, the current import path is used. Otherwise, this is the equivalent of calling
setImportPath()and thenproject().This function is similar to
importFromFile(), but also bakes the loaded paint buffer.- Parameters:
Path (str, optional) – The file path to import the projection image from, or an empty string to use the current value of
importPath(). Defaults to str.- Raises:
IOError – Raised if the file from the updated image import path does not exist.
See also
project(), importFromFile()
- projectionMaskNameList()
Return a list of the projection mask names for this projector.
- Returns:
list of str– The names of the projection masks for this projector.
- projectionMaskProperty(MaskName, PropertyName)
Returns the value of a given property of the given projection mask.
For example, to get the enabled state of the ambient occlusion mask:
ao_projection_mask_enabled = projector.projectionMaskProperty('Ambient Occlusion Mask', 'enabled')- Parameters:
MaskName (str)
PropertyName (str)
- Raises:
ValueError – Raised if a projection mask is not found with the given name.
ValueError – Raised if the projection mask does not have a property called the given name.
- Returns:
variant– The value of the given property.
- projectionMaskPropertyList(MaskName)
Set the given property of the given projection mask to the given value.
For example, to retrieve the list of property names for the ambient occlusion mask:
ao_property_name_list = projector.projectionMaskPropertyList('Ambient Occlusion Mask')- Parameters:
MaskName (str)
- Raises:
ValueError – Raised if a projection mask is not found with the given name.
- Returns:
list of str– A list of property names for the given projection mask.
- rotation()
Returns the rotation of the projector’s projection.
- save(FileName)
Save the projector data to a file.
- Parameters:
FileName (str) – The absolute path, file name, and extension to save the projector data to.
- scale()
Returns the scale of the projection.
- setBitDepth(Depth)
Sets the bit depth of the projector.
When unprojecting, the projector can render at varying bit depths. This method give control over the bit depth used.
- Parameters:
Depth (BitDepth) – The bit depth of the unprojection image. This should be suitable for the output image format - e.g. unprojecting to a PNG file with floating point bit depth will fail.
- Raises:
ValueError – Raised if the bit depth provided was invalid.
See also
bitDepth()
- setClampColors(ClampColors)
Sets the color clamping behavior of the projector.
- Parameters:
ClampColors (bool) – True to clamp the colors to the 0..1 range, or false to not clamp
See also
clampColors()
- setColorspaceConfig(Config)
Sets the colorspace configuration for import and export of the projector.
The scalar flag will be ignored as it is automatically updated based on ‘
useShader()‘.- Parameters:
Config (ColorspaceConfig) – The colorspace configuration for import and export.
- Raises:
ValueError – Raised if the colorspace configuration is invalid.
- setDepthProjectionMode(ProjectionMode)
Sets the type of depth-dependent projection onto object faces.
- Parameters:
ProjectionMode (DepthProjectionMode) – The new type of projection
- setExportColorspaceConfig(Config)
Sets the colorspace configuration for export of the channel.
- Parameters:
Config (ColorspaceConfig) – The colorspace configuration for export.
- Raises:
ValueError – Raised if the colorspace configuration is invalid.
Deprecated
Both the import and export colorspace configurations have been consolidated together. This function will be removed in a future version. Please use setColorspaceConfig() instead.
- setExportOptions(Options)
Sets the options passed to the file writer.
These can be used to pass options to the file writer, in dictionary format. For example:
projector.setExportOptions({'Quality': 78.0, 'Scanline': True})- Parameters:
Options (variant) – The options that are used in exporting images.
- setExportPath(Path)
Sets the path that the projector will export images to.
- Parameters:
Path (str) – The file path to export projection images to
See also
exportPath()
- setFormat(Format)
Sets the pixel format of the projection from a string.
- Parameters:
Format (str)
- Raises:
ValueError – Raised if the requested format is not supported.
- setFrameOffset(Offset)
Sets the frame offset, when using the imported path with the timeline.
- Parameters:
Offset (int) – The frame offset from 0 to 9999
- Raises:
ValueError – Raised if the offset is out of range.
- setImportColorspaceConfig(Config)
Sets the colorspace configuration for import of the projector.
- Parameters:
Config (ColorspaceConfig) – The colorspace configuration for import.
- Raises:
ValueError – Raised if the colorspace configuration is invalid.
Deprecated
Both the import and export colorspace configurations have been consolidated together. This function will be removed in a future version. Please use setColorspaceConfig() instead.
- setImportPath(Path)
Sets the file path that the projector will import images from.
- Parameters:
Path (str) – The file path to import projection images from
See also
importPath()
- setLightingMode(NewMode)
Sets the detail level of the lighting calculations.
- Parameters:
NewMode (LightingMode) – The new lighting mode
- setName(Name)
Sets the projector’s name.
- Parameters:
Name (str)
- Raises:
ValueError – Raised if the name is empty, or if a projector with the given name already exists.
RuntimeError – Raised if no projector is open.
- setPaintingMode(PaintingMode)
Sets the paint compositing mode of the projector.
- Parameters:
PaintingMode (variant) – The new painting mode as a mari.Layer.BlendMode enum. See the
Layerclass for a full list of available painting modes.- Raises:
ValueError – Raised if the specified mode is unknown.
- setProjectionMaskProperty(MaskName, PropertyName, Value)
Set the given property of the given projection mask to the given value.
For example, to enable the ambient occlusion mask:
projector.setProjectionMaskProperty('Ambient Occlusion Mask', 'enabled', True)- Parameters:
MaskName (str)
PropertyName (str)
Value (variant)
- Raises:
ValueError – Raised if a projection mask is not found with the given name.
ValueError – Raised if the projection mask does not have a property called the given name.
ValueError – Raised if it was not possible to set the given property to the given value.
- setRotation(Rotation)
Sets the rotation of the projector’s projection.
- Parameters:
Rotation (float)
- Raises:
ValueError – Throws a value error if the vector is not a 2D vector
- setSize(Width, Height)
Sets the projection size in pixels.
- Parameters:
Width (int)
Height (int)
- Raises:
ValueError – Raised if the requested size is not supported.
- setTranslation(pTranslation)
Sets the translation of the projector’s projection.
- Parameters:
pTranslation (VectorN)
- Raises:
ValueError – Throws a value error if the vector is not a 2D vector
- setUseShader(UseShader)
Sets the shader to use for unprojection.
- Parameters:
UseShader (str) – The name of the shader to use for unprojection.
- Raises:
ValueError – Raised if the specified shader is unknown.
- translation()
Returns the translation of the projector’s projection.
- unproject(SaveOptions='Image.DEFAULT_OPTIONS')
Exports an image from the projector’s view to the current export path.
- Parameters:
SaveOptions (Image.SaveOptionsFlags, optional) – Pass in a value other than the default to turn on an option, currently only supporting “DISABLE_SMALL_UNIFORMS” See
Image::SaveOptions. Defaults to Image.DEFAULT_OPTIONS.
See also
exportPath(), unprojectToFile()
- unprojectToFile(Path='str', Options='variant', SaveOptions='Image.DEFAULT_OPTIONS')
Exports an image from the projector’s view to the given file.
If no path is provided, the current export path is used. Otherwise, this is the equivalent of calling
setExportPath()and thenunproject().The options parameter can be used to pass options to the file writer, in dictionary format. For example:
projector.unprojectToFile('/tmp/test.jpg', {'IntegerSetting': 1, 'StringSetting': 'Hello'})- Parameters:
Path (str, optional) – The file path to export the projection image to, or an empty string to use the current value of
exportPath(). Defaults to str.Options (variant, optional) – This is an optional parameter which can be used to pass options to the file writer. See above for details. Defaults to variant.
SaveOptions (Image.SaveOptionsFlags, optional) – Pass in a value other than the default to turn on an option, currently only supporting “DISABLE_SMALL_UNIFORMS” See
Image::SaveOptions. Defaults to Image.DEFAULT_OPTIONS.
See also
unproject()
- useShader()
Returns the name of the shader used for unprojection.
- Returns:
str– The name of the shader used for unprojection.
- useShaderList()
Returns a list of shader names that can be used for unprojection.
- Returns:
list of str– A list of shader names that can be used for unprojection.
- width()
Returns the pixel width of the projection.
- Returns:
int– The width in pixels of the projection
- class mari.ProjectorManager
Bases:
objectThis object manages projectors in the project, including creation and listing.
Example Code
>>> # This examples shows how to create a new projector >>> import mari >>> projector = mari.projectors.create("Test Projector") >>> print(projector.name()) Test Projector >>> mari.projectors.remove(projector.name())
Alias
projectors
- create(Name)
Creates a new projector with the given name.
- Parameters:
Name (str) – The name of the new projector to create. This must be non-empty and unique.
- Raises:
ValueError – Raised if the name is empty, or if a projector with the given name already exists.
RuntimeError – Raised if no project is currently open.
- current()
Returns the currently selected projector.
- Raises:
RuntimeError – Raised if no project is currently open.
- Returns:
Projector– The currently selected projector
- find(Name)
Returns the projector with the given name, if found.
- Parameters:
Name (str) – The name of the projector to look for
- Returns:
Projector– The projector if found, or NULL if not
- frameRange(Path, Take='str')
Returns the start and end frames of a projector from the given file path.
- Parameters:
Path (str) – The path to the file to be loaded. A file may contain multiple projectors.
Take (str, optional) – Optional take used to query specific animation range if the file supports the concept of takes. Defaults to str.
- Raises:
ValueError – Raised if the file path isn’t a valid projector format.
- Returns:
list of
int– The start and end frames of the projector as a list [start, end]. An empty list is returned on failure.
- get(Name)
Returns the projector with the given name.
- Parameters:
Name (str) – The name of the projector to look for
- Raises:
ValueError – Raised if no projector with the given name exists
- Returns:
Projector– The projector with the given name
- list()
Returns a list of all projectors in the project.
- Raises:
RuntimeError – Raised if no project is currently open.
- Returns:
list of
Projector– A list of all projectors in the project
- load(Path, Options, CameraNames='variant')
Loads a projector from the given file path.
Requests for projector loading are routed to the correct plugin based on file extension.
The following is an example of loading a camera from an alembic file with some additional camera options:
>>> import mari >>> filePath = "/tmp/test.abc" >>> options = ["FrameOffset = 1", "StartFrame = 2", "EndFrame=4"] >>> camerasToLoad = ["/CameraTopPersp/CameraTopPersp"] >>> mari.projectors.load(filePath, options, camerasToLoad)
- Parameters:
Path (str) – The path to the file to be loaded. A file may contain multiple projectors.
Options (list of str) – This is an optional parameter which can be used to pass options to the file loader. Options should be in name=value format. Some examples are StartFrame, EndFrame and FrameOffset.
CameraNames (variant, optional) – This is an optional list of cameras to load from the file. Each item of the list is a string, corresponding to the name of the camera in the source file. Defaults to variant.
- Raises:
RuntimeError – Raised if no project is currently open.
ValueError – Raised if the options list contains invalid items.
- Returns:
list of
Projector– A list of the projectors loaded from the given file, empty list on failure
- names()
Returns a list of the names of all projectors in the project.
- Raises:
RuntimeError – Raised if no projet is currently open.
- Returns:
list of str– The names of all projectors in the project
- projectorAdded(NewProjector)
This is emitted after a new projector has been added to the project.
This only includes manual addition (by menu or by script), however. It will not be emitted when a project is loaded.
- Parameters:
NewProjector (Projector) – The newly-added projector
- projectorMadeCurrent(NewCurrent)
This is emitted after a projector becomes current.
- Parameters:
NewCurrent (Projector) – The new current projector
- projectorRemoved(OldProjector)
This is emitted after a projector has been removed from the project.
This only includes manual removal (by menu or by script), however. It will not be emitted when a project is closed.
- Parameters:
OldProjector (Projector) – The projector that was just removed
- quick()
Returns the quick projection settings.
- Raises:
RuntimeError – Raised if no project is currently open.
- Returns:
QuickProjector– The quick projection settings.
- remove(Name)
Removes, or deletes, the projector with the given name.
- Parameters:
Name (str) – The name of the projector to remove
- class mari.PropertySource
Bases:
MetadataThis API provides functionality for objects that expose a number of built in properties.
Objects within
Marican have two forms of properties, built in values or metadata. Built in properties are hard coded onto objects and cannot be removed or their characteristics modified. This API provides generic functionality for objects that expose these built in properties for scripting.def PrintPropertyInfo(Obj): for Property in Obj.propertiesList(): print(Property, "=", Obj.getProperty(Property)) print(" Display Name :", Obj.propertyDisplayName(Property)) print(" Can reset :", Obj.canResetProperty(Property)) print(" Is Enum :", Obj.propertyIsEnum(Property)) if Obj.propertyIsEnum(Property) == True: for value in Obj.propertyEnumValues(Property): print(" :" , value) print(" Has MinMax :", Obj.propertyHasMinMax(Property)) print(" Is Read Only :", Obj.propertyIsReadOnly(Property)) print(" Tooltip :", Obj.propertyTooltip(Property)) if Obj.propertyHasMinMax(Property) == True: print(" MinMax Values:", Obj.propertyMinMax(Property))
Properties on an object are refered to by a path normally of the form subobject/group/property Subobjects are separate sub-components of an object that expose properties through the main object . Proprties can be get/set/reset, and you can query various attributes of the property such as min and max values and the tooltip if one is provided.
Warning
The Property API should be considered to be a “low level” API and only used when the objects implementing it don’t expose the required functionality in another way. An example of this might be an object that has a property “size” and the methods getSize() and setSize(). In this instance the API methods should be used rather than the getProperty or setProperty methods. Properties exposed by this API may move, be renamed or removed entirely in future Mari releases. We will endevor to keep properties backwards compatible but they may change without warning or deprecation. Users of this API should also be aware that modifying properties via this interface can lead to unexpected side effects and may cause Mari to enter a unwanted state. All properties exposed by an object are accessible via this interface and that may include properties that are normally reserved for internal use only. You have been warned. :)
- canResetProperty(PropertyName)
Query if a given property can be automatically reset to a default value.
print(mari.tools.currentTool().canResetProperty( mari.tools.currentTool().propertiesList()[0]))- Parameters:
PropertyName (str) – The name of the property to query, this should be found in the list returned by
propertiesList()- Raises:
ValueError – Raised if the given property is not found on this object
- Returns:
bool– True if the given property can be reset to a default value
- getProperty(PropertyName)
Return the value of a given property.
print(mari.tools.currentTool().getProperty( mari.tools.currentTool().propertiesList()[0]))- Parameters:
PropertyName (str) – The name of the property to query, this should be found in the list returned by
propertiesList()- Raises:
ValueError – Raised if the given property is not found on this object
- Returns:
variant– The current value of the given property
- propertiesList()
Return the list of properties that can be set on this object.
print(mari.tools.currentTools().propertiesList( ))- Returns:
list of str– a list of strings. Each entry is the full name of a property that can be set on this object
- propertyDisplayName(PropertyName)
Return the display name of a given property, this is the name that should be presented to the user.
print(mari.tools.currentTool().propertyDisplayName( mari.tools.currentTool().propertiesList()[0]))- Parameters:
PropertyName (str) – The name of the property to query, this should be found in the list returned by
propertiesList()- Raises:
ValueError – Raised if the given property is not found on this object
- Returns:
str– The display name of the given property
- propertyEnumValues(PropertyName)
Return the valid values for an enum type property.
print(mari.tools.currentTool().propertyEnumValues( mari.tools.currentTool().propertiesList()[0]))- Parameters:
PropertyName (str) – The name of the property to query, this should be found in the list returned by
propertiesList()- Raises:
ValueError – Raised if the given property is not found on this object
ValueError – Raised if the given property is not an enum type property
- Returns:
list of str– A list containing the valid values for the given property
- propertyHasMinMax(PropertyName)
Query if a given property has defined min and max values.
print(mari.tools.currentTool().propertyHasMinxMax( mari.tools.currentTool().propertiesList()[0]))- Parameters:
PropertyName (str) – The name of the property to query, this should be found in the list returned by
propertiesList()- Raises:
ValueError – Raised if the given property is not found on this object
- Returns:
bool– True if the given property has defined min and max values
- propertyIsEnum(PropertyName)
Query if a given property is an enumerated type.
print(mari.tools.currentTool().propertyIsEnum( mari.tools.currentTool().propertiesList()[0]))- Parameters:
PropertyName (str) – The name of the property to query, this should be found in the list returned by
propertiesList()- Raises:
ValueError – Raised if the given property is not found on this object
- Returns:
bool– True if the given property is an enumerated type
- propertyIsReadOnly(PropertyName)
Query if a given property is read only.
print(mari.tools.currentTool().propertyIsReadOnly( mari.tools.currentTool().propertiesList()[0]))- Parameters:
PropertyName (str) – The name of the property to query, this should be found in the list returned by
propertiesList()- Raises:
ValueError – Raised if the given property is not found on this object
- Returns:
bool– True if the given property is read only if False the property can be changed using setProperty
- propertyMinMax(PropertyName)
Query the min and max values for a given property.
print(mari.tools.currentTool().propertyMinMax( mari.tools.currentTool().propertiesList()[0]))- Parameters:
PropertyName (str) – The name of the property to query, this should be found in the list returned by
propertiesList()- Raises:
ValueError – Raised if the given property is not found on this object
ValueError – Raised if the given property does not proviude min max values
- Returns:
list of
variant– A tuple containing the min [0] and max [1] values for the given property
- propertyTooltip(PropertyName)
Query the tooltip for a given property, if non is found an empty string will be returned.
print(mari.tools.currentTool().propertyTooltip( mari.tools.currentTool().propertiesList()[0]))- Parameters:
PropertyName (str) – The name of the property to query, this should be found in the list returned by
propertiesList()- Raises:
ValueError – Raised if the given property is not found on this object
- Returns:
str– The tooltip (if any) for the given property
- resetProperty(PropertyName)
Reset the given property to the default value, if the given property cannot be reset this method will simply return without error.
mari.tools.currentTool().resetProperty( mari.tools.currentTool().propertiesList()[0])- Parameters:
PropertyName (str) – The name of the property to query, this should be found in the list returned by
propertiesList()- Raises:
ValueError – Raised if the given property is not found on this object
- setProperty(PropertyName, NewValue)
Set the value of a given property.
mari.tools.currentTool().setProperty( mari.tools.currentTool().propertiesList()[0],2.0)- Parameters:
PropertyName (str) – The name of the property to set, this should be found in the list returned by
propertiesList()NewValue (variant) – The new value for the property
- Raises:
ValueError – Raised if the given property is not found on this object or the value passed is incompatible
ValueError – Raised if the property is read only
InternalError – Raised if some other problem was encountered when setting the property
- class mari.PropertyWidget
Bases:
WidgetBase- static generatePropertyWidget(Object, MetadataToExclude={}, PropertyGrouping={}, RootHeader='')
Static function to generate PropertyWidget for a given object.
- Parameters:
Object (Metadata) – The
Metadataclass instance to generating aPropertyWidgetfor.MetadataToExclude (list of
str, optional) – The list of metadata names to exclude creating controlets for. Defaults to {}.PropertyGrouping (dict<str,str>, optional) – The dictionary of str to str map to create UI grouping. E.g. {“Size”:”Parent Group”} would put the Size contolet under the Parent Group. Defaults to {}.
RootHeader (str, optional) – The root header group text. If empty, no root header is created. Defaults to “”.
- class mari.Ptex(pPtexImageSet)
Bases:
MetadataProvides Ptex image set scripting.
See also
- LARGEST_AREA_PER_FACE_SIZE = 2
.
- Type:
int
- MATCH_CHANNEL_TO_PTEX = 1
.
- Type:
int
- MATCH_PTEX_TO_CHANNEL = 0
.
- Type:
int
- class ResizeMethod
Bases:
objectDifferent resize methods for importing ptex files.
- LARGEST_AREA_PER_FACE_SIZE = 2
.
- Type:
int
- MATCH_CHANNEL_TO_PTEX = 1
.
- Type:
int
- MATCH_PTEX_TO_CHANNEL = 0
.
- Type:
int
- __init__(pPtexImageSet)
Constructs a new Ptex wrapper.
This is a helper class for dealing with
Pteximage sets. It should be constructed by passing in a pointer to an existingPteximage set.
- doubleFaceSize(FaceId)
Doubles the size of the texture of the Ptex face.
- Parameters:
FaceId (int) – The ID of the face to double the size of.
- Raises:
RuntimeError – Raised if an error was detected during face resizing.
- exportToPtexFile(PtexPathName, IncludeGeo, IncludeAdjacency, GenerateMipMaps, IncludeUserAttributes, RemapQuads)
Exports an image set as a Ptex file.
- Parameters:
PtexPathName (str) –
Ptexpath name to export to.IncludeGeo (bool) – Include geometry as meta data.
IncludeAdjacency (bool) – Include adjacency information.
GenerateMipMaps (bool) – Generate mipmaps using the
Ptexlibrary.IncludeUserAttributes (bool) – Include user attributes from the image set.
RemapQuads (bool) – Remap all quad face texture data from triangle layout to quad layout.
- Raises:
RuntimeError – Raised if an error was detected while exporting to the .ptx file.
- faceSize(FaceId)
Returns the size in pixels of the given face.
- Parameters:
FaceId (int) – The ID of the face to query.
- Returns:
QSize– The size in pixels of the face.
- floodFillFace(FaceId, FillColor)
Floodfills a face within the Ptex texture to a given color.
- Parameters:
FaceId (int) – The ID of the face to fill.
FillColor (Color) – The color that the face will be filled with.
- Raises:
RuntimeError – Raised if an error was detected while flooding filling faces.
- floodFillFaces(FaceIds, FillColor)
Floodfills faces within the Ptex texture to a given color.
- Parameters:
FaceIds (list of
int) – A list of face IDs to fill.FillColor (Color) – The color that the faces will be filled with.
- Raises:
RuntimeError – Raised if an error was detected while flooding filling faces.
- geoFaceCount()
Returns the number of faces in this Ptex texture.
- Returns:
int– The total face count of the various geometries contained in a GeoVersion.
- halveFaceSize(FaceId)
Halves the size of the texture of the Ptex face.
- Parameters:
FaceId (int) – The ID of the face to halve the size of.
- Raises:
RuntimeError – Raised if an error was detected during face resizing.
- hash()
Returns a unique identifier for this Ptex image set.
Marimaintains hashes of ptex data for internal book-keeping. These hashes are assumed to be universally unique (256bit skein hash). These hashes can be used to determine if anPteximage set has changed since some given checkpoint. A different hash means different ptex data.- Returns:
str– A hash string that uniquely identifies this version of this Ptex image set, or an empty string on failure.
- importFromPtexFile(PtexPathName, RemapQuads, Method)
Import a compatible Ptex file onto an existing image set.
- Parameters:
PtexPathName (str) –
Ptexpathname to import from.RemapQuads (bool) – Remap all quad face texture data from quad layout to triangle layout.
Method (int) – The ResizeMethod to use when importing.
- Raises:
RuntimeError – Raised if an error was detected while importing from the .ptx file.
- resizeFace(FaceId, NewSize)
Resizes a face within the Ptex texture.
- Parameters:
FaceId (int) – The ID of the face to resize.
NewSize (QSize) – The new size of the face. This must be a size returned by
validFaceSizes().
- Raises:
RuntimeError – Raised if an error was detected during face resizing.
- resizeFaceToTexelDensity(FaceId, Density)
Resizes a face within the Ptex texture to a world space texel density.
- Parameters:
FaceId (int) – The ID of the face to resize.
Density (float) – The texel density to use in the resize calculations.
- Raises:
RuntimeError – Raised if an error was detected during face resizing.
- validFaceSizes()
Returns the list of valid face sizes for Ptex faces.
- Returns:
list of
int– A list of valid face sizes.
- class mari.QuickProjector
Bases:
MetadataProjectors store the specific camera details of a particular view.
This includes the rotation, zoom, and orientation of the view, plus the current paintable area, painting mode, and mask settings. This is much like a bookmark or snapshot of a view.
You can access projectors through the
ProjectorManager- for example:mari.projectors.list()Example Code
>>> # This example shows how to the path of the quick projector >>> import mari >>> mari.projectors.quick().setPath("/tmp/quick_unprojection.png")
- class BitDepth
Bases:
objectThese are the bit depths supported by projectors.
- DEPTH_BYTE = 8
Standard eight bit depth.
- Type:
int
- DEPTH_FLOAT = 32
Full float depth.
- Type:
int
- DEPTH_HALF = 16
Half-float depth.
- Type:
int
- DEPTH_BYTE = 8
Standard eight bit depth.
- Type:
int
- DEPTH_FLOAT = 32
Full float depth.
- Type:
int
- DEPTH_HALF = 16
Half-float depth.
- Type:
int
- bitDepth()
Returns the current bit depth of the projector.
- Returns:
BitDepth– The current bit depth of the projector
See also
setBitDepth()
- clampColors()
Returns the color clamping behavior of the projector.
- Returns:
bool– True if the colors are clamped to the 0..1 range on output, or false otherwise
See also
setClampColors()
- height()
Returns the pixel height of the projection.
- Returns:
int– The height in pixels of the projection
- path()
Returns the file path to export the projection to.
- Returns:
str– The file path that projection images are exported to
See also
setExportPath()
- setBitDepth(Depth)
Sets the bit depth of the projector.
When unprojecting, the projector can render at varying bit depths. This method give control over the bit depth used.
- Parameters:
Depth (BitDepth) – The bit depth of the unprojection image. This should be suitable for the output image format - e.g. unprojecting to a PNG file with floating point bit depth will fail.
- Raises:
ValueError – Raised if the bit depth provided was invalid.
See also
bitDepth()
- setClampColors(ClampColors)
Sets the color clamping behavior of the projector.
- Parameters:
ClampColors (bool) – True to clamp the colors to the 0..1 range, or false to not clamp
See also
clampColors()
- setPath(Path)
Sets the path that the projector will export images to.
- Parameters:
Path (str) – The file path to export projection images to
See also
exportPath()
- setSize(Width, Height)
Sets the projection size in pixels.
- Parameters:
Width (int)
Height (int)
- Raises:
ValueError – Raised if the requested size is not supported.
- width()
Returns the pixel width of the projection.
- Returns:
int– The width in pixels of the projection
- class mari.ReceiverTeleportNode
Bases:
TeleportNodeRepresents a receiver teleport node.
- connectedBroadcastNode()
Returns the Broadcast Teleport Nodes which is broadcasting on the channel this node is listening to, if there is one.
- Returns:
BroadcastTeleportNode– A BroadcastTeleportNode or None.
- setChannelName(ChannelName)
Sets the channel this node uses.
- Parameters:
ChannelName (str) – The channel this node uses.
- Raises:
ValueError – Raised if the given channel is invalid.
- class mari.ResourceInfo
Bases:
objectThis provides access to Mari’s resource paths and some related system functions.
The paths supplied should be accessed using a string identifier returned from one of the appropriate functions. Note that new paths cannot currently be registered through scripting.
The current value of a path can be accessed with code like the following:
mari.resources.path(mari.resources.USER_SCRIPTS)Many paths can be overridden by environment variables that match their string identifiers. For example,
mari.resources.USER_SCRIPTSis set to the string “MARI_SCRIPT_PATH”, and if an environment variable with that name is found whenMarilaunches, the user scripts path will be set to its contents.The paths that can be modified by users will generally have string identifiers that begin with “MARI”, which also makes the environment variables clearer. Alternatively, an individual path can be checked for modifiability by calling
mari.scripts.setPath()on it; the function will raise an exception if the path is not user-modifiable.Example Code
>>> # This example shows how to obtain the path to example directory >>> import mari >>> example_dir_path = mari.resources.path(mari.resources.EXAMPLES)
See also
examples.resource_info
Alias
resources
- createIcon(IconFileName)
Constructs a QIcon for the given file name from Mari’s stock icon library.
- Parameters:
IconFileName (str) – The file name of the icon in
Mari‘s stock icon library- Returns:
QIcon– QIcon object for the given icon file name
- customPluginPaths()
Returns the list of plugin paths specified by environment variable MARI_CUSTOM_PLUGINS_PATH.
- disableEnviromentKeyValues()
Refreshes all environment paths to mari default values, instead of reading from the environment.
- exportSequenceTemplate()
Returns the default template used for exporting image sequences.
- Returns:
str– The default template used for exporting image sequences
- flattenedSequenceTemplate()
Returns the default template used for flattened image sequences.
- Returns:
str– The default template used for flattened image sequences
- importSequenceTemplate()
Returns the default template used for importing image sequences.
- Returns:
str– The default template used for importing image sequences
- logPath()
Returns the filename of the log file for the application.
- path(Key)
Retrieves the value of a registered path as a single string.
The available registered paths are listed in the System Paths and User Paths sections above.
- Parameters:
Key (str) – The string identifier of the path.
- Raises:
AttributeError – Raised if the supplied key does not match a path entry.
- Returns:
str– The value of the path.
See also
pathList()
- pathList(Key)
Retrieves the value of a registered path as a list of strings.
The available registered paths are listed in the System Paths and User Paths sections above.
The strings are combined into a single one by joining with instances of the standard path specifier - ‘:’ on Linux/OS X, and ‘;’ on Windows.
- Parameters:
Key (str) – The string identifier of the path.
- Raises:
AttributeError – Raised if the supplied key does not match a path entry.
- Returns:
list of str– A list of the values in the path.
See also
path()
- ptexFlattenedSequenceTemplate()
Returns the default template used for flattened Ptex image sequences.
- Returns:
str– The default template used for flattened Ptex image sequences
- ptexSequenceTemplate()
Returns the default template used for Ptex image sequences.
- Returns:
str– The default template used for Ptex image sequences
- refreshAllPaths()
Refreshes all paths from environment variables to account for any changes.
This calls
refreshPath()for all available paths.This is used to take into account any path modifications applied by environment variable changes on start up. The standard start up process calls this function when setting up the ‘mari’ module so that users can set up their environment variables for paths using Python’s sitecustomize.py if desired.
- refreshPath(Key)
Refreshes the given path from its environment variable, in case of any changes.
If the specified path is read from an environment variable (see
ResourceInfofor details), this will look for the variable, and if found and non-empty, it will set the path to the corresponding value.For paths that are not read from environment variables, or not modifiable by the user, this operation will do nothing.
- Parameters:
Key (str)
- Raises:
AttributeError – Raised if the supplied key does not match a path entry.
- sequenceTemplate()
Returns the default template used for both importing and exporting image sequences.
- Returns:
str– The default template used for both importing and exporting image sequences
- sequenceToken()
Returns the token that should be used to identity sequences of images.
- Returns:
str– The token to identify image sequences
See also
setSequenceToken()
- setExportSequenceTemplate(Name)
Sets the default template used for exporting image sequences.
- Parameters:
Name (str) – The new default template to use for exporting image sequences
- setFlattenedSequenceTemplate(Name)
Sets the default template used for flattened image sequences.
- Parameters:
Name (str) – The new default template to use for flattened image sequences
- setImportSequenceTemplate(Name)
Sets the default template used for importing image sequences.
- Parameters:
Name (str) – The new default template to use for image sequences
- setPath(Key, NewPath)
Sets the value of a registered path to a single string.
The available registered paths are listed in the System Paths and User Paths sections above.
Note that no new paths can be registered through scripting at this stage.
- Parameters:
Key (str) – The string identifier of the path.
NewPath (str) – The new value for the path. This must not be empty.
- Raises:
AttributeError – Raised if the supplied key does not match a path entry.
ValueError – Raised if the new path is empty.
RuntimeError – Raised if the path is not user-modifiable.
See also
setPathList()
- setPathList(Key, NewPathList)
Sets the value of a registered path to a list of strings.
The strings are combined into a single one by joining with instances of the standard path specifier - ‘:’ on Linux/OS X, and ‘;’ on Windows.
The available registered paths are listed in the System Paths and User Paths sections above.
Note that no new paths can be registered through scripting at this stage.
- Parameters:
Key (str) – The string identifier of the path.
NewPathList (list of str) – The new value for the path. If this is empty, the path is not changed.
- Raises:
AttributeError – Raised if the supplied key does not match a path entry.
ValueError – Raised if NewPathList is empty.
RuntimeError – Raised if the path is not user-modifiable.
See also
setPath()
- setPtexFlattenedSequenceTemplate(Name)
Sets the default template used for flattened Ptex image sequences.
- Parameters:
Name (str) – The new default template to use for flattened
Pteximage sequences
- setPtexSequenceTemplate(Name)
Sets the default template used for Ptex image sequences.
- Parameters:
Name (str) – The new default template to use for
Pteximage sequences
- setSequenceTemplate(Name)
Sets the default template used for both importing and exporting image sequences.
- Parameters:
Name (str) – The new default template to use for both importing and exporting image sequences
- setSequenceToken(Token)
Sets the sequence token to be used to replace the number in a sequence of images.
By default, this is “$INDEX”. Other examples are: $UDIM (WETA), @, ####
- Parameters:
Token (str) – The new sequence token to use.
- settingsFilePath(Name)
Returns the path to the given settings file.
This allows a settings file to be overridden in a local settings folder.
- Parameters:
Name (str) – The file name of the settings file to retrieve the path for
- Returns:
str– The resolved file path. This is not guaranteed to exist.
- showPDF(Path)
Displays a PDF file in the system’s default viewer.
- Parameters:
Path (str) – The file path of the PDF to view
- showURL(Url)
Displays a URL in the system’s default web browser.
- Parameters:
Url (str) – The URL of the web site to display.
- Raises:
ValueError – Raised if the URL is invalid.
RuntimeError – Raised if the external browser could not be successfully launched.
- class mari.ScriptAction
Bases:
ActionAn action to run a Python script, which can be assigned to a menu and/or shortcut.
Example Code
>>> # This example creates an action to print "Hello World" to the log and executes the action >>> import mari >>> action = mari.actions.create("MyCustomActions/Print Hello","mari.app.log('Hello World')") >>> action.trigger()
- script()
Returns the script currently set for the action.
See also
setScript()
- setScript(rScript)
Modifies the script to run for the action.
- Parameters:
rScript (str)
See also
script()
- class mari.ScriptManager
Bases:
objectThe Script Manager is the interface to the
Mariscripting system. It provides access to the scripting environment, including the ability to retrieve script errors.- errorOccurred(errorMessage)
No description
Emitted when an error occurs during script execution.
- Parameters:
errorMessage (str) – The error message produced by the script engine.
- class mari.SelectionGroup
Bases:
LockableA selection group object.
- entityName()
Returns the name of the selection group.
- Returns:
str– The name of the selection group.
- name()
Returns the name of the object.
- Returns:
str– The name of this object
- nameChanged(name)
Emitted when the selection group is renamed.
- Parameters:
name (str) – The new name.
- selectionMode()
Return the selection mode of the group.
- Returns:
SelectionGroupManager.SelectionMode– The selection mode of the group.
- setEntityName(name)
Sets the name of the selection group.
- Parameters:
name (str) – The name to set for the selection group
- class mari.SelectionGroupManager
Bases:
objectManages the selection groups in the scene.
- SELECTION_MODE_FACES = 2
Selection mode of type face.
- Type:
int
- SELECTION_MODE_OBJECTS = 1
Selection mode of type object.
- Type:
int
- SELECTION_MODE_PATCHES = 0
Selection mode of type patch.
- Type:
int
- class SelectionMode
Bases:
objectModes of selections.
- SELECTION_MODE_FACES = 2
Selection mode of type face.
- Type:
int
- SELECTION_MODE_OBJECTS = 1
Selection mode of type object.
- Type:
int
- SELECTION_MODE_PATCHES = 0
Selection mode of type patch.
- Type:
int
- createIDMapsFromSelectionGroups(IDMapSpecifications, SingleMap=False)
Creates colored maps from selection groups.
Each entry in IDMapSpecifications is a dict that specifies the desired settings for each ID map created.
- The keys in the dictionary are:
“Group” - The
SelectionGroupto bake an ID map for.“Size” - A mari.ImageSet.Size to specify the size of the ID map. Defaults to 2048x2048.
“Depth” - A mari.Image.Depth to specify the bit depth of the ID map. Defaults to 16bit half float.
“Color” - A mari.Color with which to fill the selection group with. If missing, the last used color will be used (or a random color will be generated if there was no last used color).
“PaintNodeName” - A string to name the
PaintNodecreated. If empty or missing, noPaintNodeis created.“GeoChannelName” - A string to name the
GeoChannelcreated. If aGeoChannelexists with this name, it will be overwritten. If empty, noGeoChannelis created or overwritten.
For example, to create selection_group_1 as a 2k 16bit paint node with a random color, selection_group_2 as a 4k 8bit geo-channel in red and selection_group_3 as a 1k 32bit paint node and geo-channel in blue:
>>> import mari >>> id_map_specifications = [] >>> id_map_specification_1 = dict() >>> id_map_specification_1["Group"] = selection_group_1 >>> id_map_specification_1["Size"] = mari.ImageSet.Size.SIZE_2048 >>> id_map_specification_1["Depth"] = mari.Image.Depth.DEPTH_HALF >>> id_map_specification_1["PaintNodeName"] = "Selection Group 1 Mask" >>> id_map_specification_2 = dict() >>> id_map_specification_2["Group"] = selection_group_2 >>> id_map_specification_2["Size"] = mari.ImageSet.Size.SIZE_4096 >>> id_map_specification_2["Depth"] = mari.Image.Depth.DEPTH_BYTE >>> id_map_specification_2["Color"] = mari.Color(1.0, 0.0, 0.0, 1.0) >>> id_map_specification_2["GeoChannelName"] = "Selection Group 2 Mask" >>> id_map_specification_3 = dict() >>> id_map_specification_3["Group"] = selection_group_3 >>> id_map_specification_3["Size"] = mari.ImageSet.Size.SIZE_1024 >>> id_map_specification_3["Depth"] = mari.Image.Depth.DEPTH_FLOAT >>> id_map_specification_3["Color"] = mari.Color(0.0, 0.0, 1.0, 1.0) >>> id_map_specification_3["PaintNodeName"] = "Selection Group 3 Mask" >>> id_map_specification_3["GeoChannelName"] = "Selection Group 3 Mask" id_map_specifications.append(id_map_specification_1) id_map_specifications.append(id_map_specification_2) id_map_specifications.append(id_map_specification_3) mari.selection.createIDMapsFromSelectionGroups(id_map_specifications)
- Parameters:
IDMapSpecifications (list of variant) – A list of dictionaries with desired parameters for ID map creation.
SingleMap (bool, optional) – If True, the masks will be filled into a single map. The size, depth and name(s) will be taken from the first entry in IDMapSpecifications. Defaults to False. Defaults to False.
- Raises:
ValueError – Raised if invalid values are given in IDMapSpecifications.
- Returns:
list of variant– A list of tuples, one for each entry in IDMapSpecifications, with the PaintNode and GeoChannel created for it.
- createMasksFromSelectionGroups(MaskSpecifications)
Creates black and white masks from selection groups.
Each entry in MaskSpecifications is a dict that specifies the desired settings for each mask created.
- The keys in the dictionary are:
“Group” - The
SelectionGroupto bake a mask of. If unspecified, will use the current selection instead.“Size” - A mari.ImageSet.Size to specify the size of the mask.
“Depth” - A mari.Image.Depth to specify the bit depth of the mask.
“PaintNodeName” - A string to name the
PaintNodecreated. If empty or missing, noPaintNodeis created.“GeoChannelName” - A string to name the
GeoChannelcreated. If aGeoChannelexists with this name, it will be overwritten. If empty, noGeoChannelis created or overwritten.
For example, to create selection_group_1 as a 2k 16bit paint node, selection_group_2 as a 4k 8bit geo-channel and selection_group_3 as a 1k 32bit paint node and geo-channel:
>>> import mari >>> mask_specifications = [] >>> mask_specification_1 = dict() >>> mask_specification_1["Group"] = selection_group_1 >>> mask_specification_1["Size"] = mari.ImageSet.Size.SIZE_2048 >>> mask_specification_1["Depth"] = mari.Image.Depth.DEPTH_HALF >>> mask_specification_1["PaintNodeName"] = "Selection Group 1 Mask" >>> mask_specification_2 = dict() >>> mask_specification_2["Group"] = selection_group_2 >>> mask_specification_2["Size"] = mari.ImageSet.Size.SIZE_4096 >>> mask_specification_2["Depth"] = mari.Image.Depth.DEPTH_BYTE >>> mask_specification_2["GeoChannelName"] = "Selection Group 2 Mask" >>> mask_specification_3 = dict() >>> mask_specification_3["Group"] = selection_group_3 >>> mask_specification_3["Size"] = mari.ImageSet.Size.SIZE_1024 >>> mask_specification_3["Depth"] = mari.Image.Depth.DEPTH_FLOAT >>> mask_specification_3["PaintNodeName"] = "Selection Group 3 Mask" >>> mask_specification_3["GeoChannelName"] = "Selection Group 3 Mask" mask_specifications.append(mask_specification_1) mask_specifications.append(mask_specification_2) mask_specifications.append(mask_specification_3) mari.selection.createMasksFromSelectionGroups(mask_specifications)
- Parameters:
MaskSpecifications (list of variant) – A list of dictionaries with desired parameters for mask creation.
- Raises:
ValueError – Raised if invalid values are given in MaskSpecifications.
- Returns:
list of variant– A list of dicts containing created “PaintNodes” and “GeoChannels”, if any. One for each entry in MaskSpecifications.
- createSelectionGroupFromSelection(name)
Create new group from current selection in project.
- Parameters:
name (str) – The name to set for the selection group.
- Raises:
RuntimeError – Raised if no project was open.
- current()
Returns the currently selected selection group.
- Raises:
ValueError – Raised if no project was open.
- Returns:
SelectionGroup– The currently selected selection group.
Emitted when the hidden state of a selection group in the scene is changed.
- Parameters:
group (SelectionGroup) – The affected selection group.
hidden (bool) – The locked state.
- list()
Returns a list of all selection groups in the project.
- Raises:
ValueError – Raised if no project was open.
- Returns:
list of
SelectionGroup– List of selection groups in the project.
- lockedChanged(group, locked)
Emitted when the locked state of a selection group in the scene is changed.
- Parameters:
group (SelectionGroup) – The affected selection group.
locked (bool) – The locked state.
- modeChanged(group, mode)
Emitted when the mode of a selection group in the scene is changed.
- Parameters:
group (SelectionGroup) – The affected selection group.
mode (SelectionGroupManager.SelectionMode) – The selection mode.
- removeSelectionGroup(group)
Remove a selection group from the project.
- Parameters:
group (SelectionGroup) – The selection group to remove.
- Raises:
RuntimeError – Raised if no project was open.
- sceneSelectionMode()
Returns the current mode of the selection in the project.
- Returns:
SelectionMode– The current mode of selection.
- select(group)
Selects a selection group from the project.
- Parameters:
group (SelectionGroup) – The selection group to select.
- Raises:
RuntimeError – Raised if no project was open.
- selectModeChanged(mode)
Emitted when the selection mode in the scene changes.
- Parameters:
mode (SelectionGroupManager.SelectionMode) – The new selection mode.
- selectedChanged(group, selected)
Emitted when the selected state of a selection group in the scene is changed.
- Parameters:
group (SelectionGroup) – The affected selection group.
selected (bool) – The selected state.
- selection()
Returns a list of all selected selection groups in the project.
- Raises:
ValueError – Raised if no project was open.
- Returns:
list of
SelectionGroup– List of selected selection groups in the project.
- selectionGroupAdded(group)
Emitted when a selection group is added.
- Parameters:
group (SelectionGroup) – The new selection group.
- selectionGroupRemoved(group)
Emitted when a selection group is removed.
- Parameters:
group (SelectionGroup) – The selection group.
- setSelectionMode(mode)
Sets the mode of selection in the scene.
- Parameters:
mode (SelectionMode) – The selection mode to set
- visibleChanged(group, visible)
Emitted when the visibility state of a selection group in the scene is changed.
- Parameters:
group (SelectionGroup) – The affected selection group.
visible (bool) – The visibility state.
- class mari.Settings
Bases:
objectA group of settings.
Users can load and save their own custom settings within
Mari.Example Code
>>> # This examples shows how to store a user settings >>> import mari >>> settings = mari.Settings() >>> settings.setValue("Test Setting","Hello World") >>> print(settings.value("Test Setting")) Hello World
- __init__()
Sets to the settings specified by the given components.
- allKeys()
Returns all of the available keys for settings.
Keys nested within groups will be prefixed by the group name, separated with a forward slash. If currently in a group, using ‘
beginGroup()‘, only child keys are returned and their prefixed group names are relative to the current group.
- beginGroup(Prefix)
Appends prefix to the current group.
Starts a named nested set of values. All values set after this call and before the next
endGroup()will be accessable only via the groups namespace.- Parameters:
Prefix (str) – Value to append
See also
value
- endGroup()
Resets the group to what it was before the corresponding ‘beginGroup()’ call.
Ends a named nested set of values. All values set before this call and after the previous
beginGroup()will be accessable only via the groups namespace.See also
value
- groupPrefixes()
Returns the list of groups prefixes that can be accessed by beginGroup().
If currently in a group, using ‘
beginGroup()‘, only the sub groups of the current group are returned.
- remove(Key)
Removes the given key and all subkeys.
If an empty key is given, all keys and subkeys of the current group are removed. If currently in a group, using ‘
beginGroup()‘, only child keys are removed.- Parameters:
Key (str)
- setValue(Key, Value)
Sets the value of setting key to value. If the key already exists, the previous value is overwritten.
- Parameters:
Key (str) – Setting key
Value (variant) – New value of the setting
- value(Key, DefaultValue='variant')
Returns the value for setting key. If the setting doesn’t exist, returns defaultValue.
If no default value is specified, ‘None’ is returned.
If the key was set within a
beginGroup()andendGroup()the group’s path must be appended to the Key pathsettings = mari.Settings() settings.beginGroup('foo') settings.setValue('bar', True) settings.endGroup() print(settings.value('foo/bar'))
- Parameters:
Key (str) – Setting key
DefaultValue (variant, optional) – Value returned if the setting doesn’t exist. Defaults to variant.
- Returns:
variant– The value of the setting, or the default if the setting doesn’t exist.
- valueKeys()
Returns the list of available keys for settings.
If currently in a group, using ‘
beginGroup()‘, only the keys in the current group are returned.
- class mari.Shader
Bases:
MetadataProvides access to Mari’s real-time layer based display shaders.
Shaders are modules that combine the layer system’s
Channelobjects to produce a rendered output.You can access shaders from a
GeoEntity- for example:mari.geo.current().shaderList()Example Code
>>> # This example shows how to obtain the current shader >>> import mari >>> current_shader = mari.geo.current().currentShader() >>> print(current_shader.className()) Shader
- class ChannelSetMode
Bases:
objectDescribes the layer stream auto-extension or retraction behavior when setting the input channel.
- EXTEND_INVISIBLE = 2
The extended layer will be invisible on creation.
- Type:
int
- EXTEND_VISIBLE = 1
The extended layer will be visible on creation.
- Type:
int
- NONE = 0
Placeholder for default values.
- Type:
int
- REMOVE_CONVERT = 4
Removed layer streams will be converted into standard groups and paintable layers, any masks will be copied and baked.
- Type:
int
- REMOVE_DISCONNECT = 3
Removed layer streams will be simply disconnected from the material layer.
- Type:
int
- EXTEND_INVISIBLE = 2
The extended layer will be invisible on creation.
- Type:
int
- EXTEND_VISIBLE = 1
The extended layer will be visible on creation.
- Type:
int
- NONE = 0
Placeholder for default values.
- Type:
int
- REMOVE_CONVERT = 4
Removed layer streams will be converted into standard groups and paintable layers, any masks will be copied and baked.
- Type:
int
- REMOVE_DISCONNECT = 3
Removed layer streams will be simply disconnected from the material layer.
- Type:
int
- channelList()
Returns a list of the Channel objects in use by the shader.
- Returns:
list of
Channel– The list of Channel objects.
- diffuseType()
Returns the path of the diffuse component of the shader.
- Returns:
str– The path of the diffuse component of the shader, which will be of the form “Lighting/Diffuse/Lambertian” or an empty string if this is a standalone shader.
See also
specularType(), standaloneType(), layeredType()
- getParameter(ParameterName)
Retrieves the current value of a parameter from this shader.
- Parameters:
ParameterName (str) – The name of the parameter to inspect.
- Raises:
ValueError – Raised if name of the parameter does not match any existing items.
SystemError – Raised if there is problem obtaining the parameter value.
- Returns:
variant– QVariant The current value of the parameter.
See also
setParameter()
- inputList()
Returns a list of the shader’s input names and channel pairs.
- Returns:
list of variant– The list of name and Channel tuple.
- inputNameList()
Returns a list of the names of shader inputs.
- Returns:
list of str– The list of names of the shader inputs.
- isInputForShaderStacks(InputName)
Returns true if the input will only accept channels that are ShaderStacks.
- Parameters:
InputName (str)
- isLayeredShader()
Returns true if the shader can contain ShaderStack channels.
- isLocked()
Indicates whether this shader is locked and, if so, unmodifiable.
- Returns:
bool– True if this shader is locked, or false if unlocked.
- isStackShader()
Returns true if the shader is used in a ShaderStack channel.
- isSystemShader()
Returns true if the shader is one of the special system shaders.
See also
GeoEntity::systemShader()
- layeredType()
Returns the path of the shader, if it is of a layered type.
- Returns:
str– The path of the shader, which will be of the form “Lighting/Layered/Layered” or an empty string if this is not a layered shader.
See also
diffuseType(), specularType(), standaloneType()
- makeCurrent()
Sets this shader as the currently active shader on its GeoEntity.
- name()
Returns the name of the shader.
- Returns:
str– The name of this shader.
- nameChanged(NewName)
This is emitted after the shader has had its name changed.
- Parameters:
NewName (str) – The new name.
- parameterNameList()
Returns the list of parameter names for this shader.
- Returns:
list of str– A list of the parameter names for this shader.
- parameterValueChanged(Name, Value)
This is emitted when a parameter value is changed.
- Parameters:
Name (str) – The name of the parameter that has been changed.
Value (variant) – The new value of the parameter.
- setInput(InputName, Input, SetMode='NONE')
Sets the channel to use on the named input.
- Parameters:
InputName (str) – The name of the input to change.
Input (Channel) – The channel to set the named input to. This value can be NULL to clear an input.
SetMode (ChannelSetMode, optional) – The layer stream auto-extension or retraction behavior to apply when setting the input channel. Defaults to NONE.
- Raises:
ValueError – Raised if the parameter could not be found, or was invalid.
ValueError – Raised if SetMode does not match the action performed. i.e. setting or un-setting the input.
- setName(Name)
Sets the name of the shader.
- Parameters:
Name (str) – The new name for the shader.
- setParameter(ParameterName, NewValue)
Sets the value of a parameter on the shader.
- Parameters:
ParameterName (str) – The name of the parameter to modify.
NewValue (variant) – The new value for the parameter. This can be of a variety of types.
- Raises:
ValueError – Raised if the parameter could not be found, or was invalid.
See also
getParameter()
- shaderModel()
Returns the shader model of this shader.
- Returns:
ShaderModel– the model of this shader.
- shaderNode()
Returns the node graph node that corresponds to this Shader.
- Returns:
Node– the node graph node that corresponds to this Shader
- specularType()
Returns the path of the specular component of the shader.
- Returns:
str– The path of the specular component of the shader, which will be of the form “Lighting/Specular/Blinn” or an empty string if this is a standalone shader.
See also
diffuseType(), standaloneType(), layeredType()
- standaloneType()
Returns the path of the shader, if it is of a standalone type.
- Returns:
str– The path of the shader, which will be of the form “Lighting/Standalone/Standard Lighting” or an empty string if this is not a standalone shader.
See also
diffuseType(), specularType(), layeredType()
- class mari.ShaderLayer
Bases:
AdjustableLayerShader layers contain a shader objects in a layer stack.
Shaderlayers use an internal shader to produce the result.You can check for
ShaderLayerobjects by callingLayer::isShaderLayer():>>> layer = channel.layer('Layer 2') >>> if layer.isShaderLayer(): ... print("Found a shader layer")
- class mari.ShaderModel
Bases:
MetadataA shader is linked with a model, which has a minimal definition of its inputs.
- id()
Returns the id of the model.
- Returns:
str– The id.
- input(InputName)
Returns a ShaderModelInput for a given input name.
- Parameters:
InputName (str) – The input name to query the shader model for.
- Raises:
ValueError – Raised if the input name is invalid and is not part of the model input list.
- Returns:
ShaderModelInput– The shader model input, corresponding to the input name.
- inputNames()
Returns a list of the names of shader model inputs.
- Returns:
list of str– The list of names of the inputs.
- inputs()
Returns a dictionary of input name : ShaderModelInput for this shader model.
- Returns:
variant– The shader model input, corresponding to the input name.
- class mari.ShaderModelInput
Bases:
MetadataA shader model input is linked with a shader model and provides access to the properties of an input of the shader model.
- name()
Returns the name of the input.
- Returns:
str– The name.
- prettyName()
Returns the pretty name of the input.
- Returns:
str– The pretty name.
- scalar()
Returns whether the input is scalar.
- Returns:
bool– The scalar value.
- setDefaultColor(DefaultColor)
Set the default color for this input.
- Parameters:
DefaultColor (Color) – The default color.
- shortName()
Returns the short name of the input.
- Returns:
str– The short name.
- class mari.ShaderModelManager
Bases:
objectManages the shader models in the application.
Example Code
>>> # This example shows how to get a list of shader models in the application. >>> import mari >>> shadermodels = mari.shader_models.list()
- list()
Returns a list of all shader models in the application.
- Returns:
list of
ShaderModel– Shader model list.
- loadMaterialIngestPresetFile(PresetFilePath)
Load the preset defined in the given file.
- Parameters:
PresetFilePath (str) – The path of the preset file to load.
- Raises:
ValueError – Raised if the file fails to be loaded.
- Returns:
str– The name of the loaded preset.
- materialIngestPreset(PresetName)
Returns the preset information for the given preset name.
The information is laid out as a series of nested dictionaries with specific keys
The main preset dictionary follows the layout; .. code-block:
{ "name" : preset name (type str), "filenameTemplate" : the pattern of the filename to match against when ingesting images (type str), "proceduralType" : the type of procedural node to assign ingested images to in the generated material node (type int), "caseSensitive" : whether pattern matching should be done in a case sensitive manner (type bool), "thumbnailTemplate" : the optional filename of the project file to use for generating thumbnails (type str), "loadedFromFilepath" : the path of the file this template was loaded from (type str), "Shaders" : the shader model mapping for this preset (type dict) }
The shader model mapping lists shader model IDs against the stream mapping for that shader model; .. code-block:
{ shader model ID (type str) : a stream mapping for this shader model (type dict) }
The stream mapping lists stream names against the values for that stream; .. code-block:
{ stream name (type str) : the values for this stream (type dict) }
The stream values dict follows the format; .. code-block:
{ "color" : the default color for this stream (type mari.Color) "enabled" : whether this stream should have images assigned when ingesting images (type bool) "patterns" : the patterns to match in image names for assigning images to this stream (type list of str) }
e.g. .. code-block:
preset_values = mari.shaders.materialIngestPreset("Preset Name") principled_diffuse_patterns = preset_values["Shaders"]["Principled BRDF"]["baseColor"]["patterns"]
- Parameters:
PresetName (str) – The name of the preset to return.
- Raises:
ValueError – Raised if the given preset is not found.
- Returns:
variantMap– A map of values for the given preset.
- materialIngestPresetChanged(PresetName)
Emitted when a loaded template changes.
- Parameters:
PresetName (str)
- materialIngestPresetList()
Returns a list of names of the loaded material ingest presets.
- Returns:
list of str– List of preset names.
- materialIngestPresetLoaded(PresetName)
Emitted when a new template is loaded.
- Parameters:
PresetName (str)
- materialIngestPresetRemoved(PresetName)
Emitted when a loaded template is removed.
- Parameters:
PresetName (str)
- modelNames()
Returns a list of all the shader model names.
- Returns:
list of str– Shader model names.
- nodePathKey(Model)
Returns the node path key associated with the input shader model.
- Parameters:
Model (ShaderModel) – The shader model.
- Raises:
ValueError – Raised if the shader model object is invalid.
- Returns:
str– Shader path key corresponding to shader model.
- saveMaterialIngestPresetFile(FilePath, Name, Data, LoadAfterSave=False)
Save the given preset to the given file with the given name.
- Parameters:
FilePath (str) – The path of the preset file to save.
Name (str) – The name to give the preset.
Data (variantMap) – The data to save to the preset, matching the format returned by
materialIngestPreset(). Note that the “loadedFromFilepath”LoadAfterSave (bool, optional) – When true, the preset is loaded immediately after a successful save. Defaults to False.
- Raises:
IOError – Raised if the given file path cannot be written to.
ValueError – Raised if the given name is invalid.
ValueError – Raised if the given data is invalid.
- Returns:
bool– The success state of the save.
- shaderModel(Name)
Returns the shader model for the given shader model name.
- Parameters:
Name (str) – Name of the shader model.
- Returns:
ShaderModel– Shader model.
- shaderNodePathKeys()
Returns a list of the shader node path keys, for which shader models have been created.
- Returns:
list of str– Shader path keys of the shader nodes, corresponding to registered shader models.
- class mari.Shelf
Bases:
MetadataA shelf is a place where the user can bookmark objects such as brushes, images, and colors.
Example Code
>>> # This example shows how to obtain the "Personal" shelf >>> import mari >>> personal_shelf = mari.shelves.find("Personal") >>> print(personal_shelf.className()) Shelf
- createItem(Type, Item, ForceImmediateLoad=False)
Creates a shelf item from the given data on this shelf.
This function is provided only for backward compatibility purpose. Please use
createShelfItem()instead. Calling this function will have exactly the same effect as callingcreateShelfItem(). SeecreateShelfItem()documentation for more details.- Parameters:
Type (ShelfManager.ShelfItemType) – The type of the item to create a shelf item for.
Item (variant) – The item to create a shelf item from.
ForceImmediateLoad (bool, optional) – Force loading custom procedural and material items in a foreground process. Defaults to False.
- Raises:
ValueError – Raised if we could not create a shelf item from the given item.
- Returns:
ShelfItem– The newly created item, if the operation worked, or a None if we could not determine the type of the Item.
Deprecated
This function will be removed in a future version. Please use createShelfItem.
- createShelfItem(Type, Item, ForceImmediateLoad=True)
Creates a shelf item from the given data on this shelf.
- Valid items are as follows:
Imageobject : this is a mari.Image object. Please note that the created shelf item is a simply link to the filepath of the image object. Therefore, it is essential that the image object is saved locally to disk.Filepath of image : please ensure that the filename has a valid extension that can be imported in
Mari.Colorobject : this is a mari.Color object.Material file : this is a material filepath, of extension .mma
Custom Procedural file : this is a Custom Procedural filepath, of extension .mpc
Brush XML : this is a serialised mari brush xml string. This string will and should have the root element ‘MariBrushSettings’
Script : this is a python script string. The thumbnail for a python script item can be specified by a python comment line “#thumbnail:/path/to/thumbnail_file”
The following are some code examples of how to create the various item types:
>>> import mari >>> >>> # Get the first shelf, where we will add the new shelf item, assuming we have one such shelf >>> FirstShelf = mari.shelves.list()[0] >>> >>> # Get a selected image from the image manager, assuming that we have one in the image manager >>> SelectedImage = mari.images.selected()[0] >>> # Create a shelf item from the selected image >>> FirstShelf.createShelfItem(mari.shelves.ShelfItemType.SHELF_ITEM_IMAGE, SelectedImage) >>> >>> >>> # Create a shelf item from an image filepath >>> FirstShelf.createShelfItem(mari.shelves.ShelfItemType.SHELF_ITEM_IMAGE, "/tmp/TestImage.jpg") >>> >>> >>> # Create a mari.Color object by picking a color >>> SelectedColor = mari.Color() >>> SelectedColor = mari.colors.pick(SelectedColor) >>> # Create a shelf item from our color object >>> FirstShelf.createShelfItem(mari.shelves.ShelfItemType.SHELF_ITEM_COLOR, SelectedColor) >>> >>> >>> # Create a shelf item from a material filepath >>> FirstShelf.createShelfItem(mari.shelves.ShelfItemType.SHELF_ITEM_MATERIAL, "/tmp/MarbleMaterial.mma") >>> >>> >>> # Create a shelf item from a custom procedural filepath >>> # Note: Creating a custom procedural item normally loads its data in a background process for performance. >>> # This means that querying its type() immediately after its creation might return an SHELF_ITEM_UNKNOWN value. >>> # Please pass ForceImmediateLoad argument as True to force load the item in the foreground and be aware that >>> # this can potentially impact performance. >>> Item = FirstShelf.createShelfItem(mari.shelves.ShelfItemType.SHELF_ITEM_COLOR_PROCEDURAL, "/tmp/Procedural.mpc") >>> >>> >>> # Find our 'Basic Brushes' system shelf >>> BasicBrushes = mari.shelves.find('Basic Brushes') >>> # Get the first brush from that shelf >>> BrushItem1 = BasicBrushes.list()[0] >>> # Get the serialised xml data of the brush item >>> BrushXML = BrushItem1.data() >>> # Create a shelf item from the brush xml >>> FirstShelf.createShelfItem(mari.shelves.ShelfItemType.SHELF_ITEM_BRUSH, BrushXML) >>> >>> >>> # Create a shelf item from a python script >>> Script = ''' #thumbnail:/home/user/script_thumbnail.png >>> print("Hello World"); >>> ''' >>> FirstShelf.createShelfItem(mari.shelves.ShelfItemType.SHELF_ITEM_SCRIPT, Script)
- Parameters:
Type (ShelfManager.ShelfItemType) – The type of the item to create a shelf item for.
Item (variant) – The item to create a shelf item from.
ForceImmediateLoad (bool, optional) – Force loading custom procedural and material items in a foreground process. When false, use the shelf signals to receive notification when each element in the item finishes loading. Modifying the item before that may result in loss of data. Defaults to True.
- Raises:
ValueError – Raised if we could not create a shelf item from the given item.
- Returns:
ShelfItem– The newly created item, if the operation worked, or a None if we could not determine the type of the Item.
- exportTo(DirectoryPath, GenerateCatalog)
Exports the shelf to the folder specified as a set of XML and image files.
All resources will be localized into the location.
- Parameters:
DirectoryPath (str) – The path to the directory the shelf should be exported to
GenerateCatalog (bool) – Indicates whether to generate a catalog for the shelf
- Raises:
IOError – Raised if the export failed.
- find(Name)
Returns the shelf action, of this shelf, filtered by a name.
- Parameters:
Name (str)
- Returns:
ShelfItem– The shelf itemsof the shelf with the input name.
- importShelf(FileName)
Imports shelf items from the given file onto this shelf.
This operation appends imported shelf items to this shelf.
- Parameters:
FileName (str) – The file name from which to import items. Must be of extension .msh
- Raises:
ValueError – Raised if the filename is empty or is not valid or does not end with the extension .msh or if this shelf is locked or if the file could not be loaded.
- isGrouped()
Returns whether the shelf is grouped in a hierarchy.
- Returns:
bool– Whether the shelf is grouped in a hierarchy
- isSystemShelf()
Returns whether this is a system shelf.
System shelves are managed by the application and cannot be modified by the user.
- Returns:
bool– Whether this is a system shelf
- list()
Returns the shelf actions of this shelf.
- Returns:
list of
ShelfItem– The shelf items of the shelf.
- loadItem(FileName)
Loads a shelf item from the given file onto this shelf.
- Parameters:
FileName (str) – The file name from which to import item. Must be of extension .msi
- Raises:
ValueError – Raised if the filename is empty or is not valid or does not end with the extension .msi or if this shelf is locked or if the file could not be loaded.
- loadShelf(FileName)
Loads shelf items from the given file onto this shelf.
This operation replaces all the current items of this shelf with those from the file.
- Parameters:
FileName (str) – The file name from which to import items. Must be of extension .msh
- Raises:
ValueError – Raised if the filename is empty or is not valid or does not end with the extension .msh or if this shelf is locked or if the file could not be loaded.
- locked()
Returns whether this shelf is locked.
- Returns:
bool– Locked value
- name()
Returns the name of the shelf.
- Returns:
str– The name of the shelf
- path()
Returns the hierarchical path of the Shelf.
- Returns:
str– The hierarchical path of the Shelf
- removeItem(Item)
Removes the given item from the shelf.
- Parameters:
Item (ShelfItem) – The shelf item to remove.
- Raises:
ValueError – Raised if the shelf item provided is not valid, not part of this shelf or child of a locked shelf.
- Returns:
bool– Whether the operation was successful.
- saveAs(rFileName)
Saves the shelf to the given file name.
- Parameters:
rFileName (str) – The file name to save the shelf to
- Raises:
RuntimeError – Raised if the save failed.
- setLocked(Locked)
Set the lock state of this shelf.
The lock state affects manipulating of shelf items as well as renaming of this shelf.
- Parameters:
Locked (bool) – value to set.
- setName(NewName)
Sets the name of the shelf.
- Parameters:
NewName (str) – The new name for the shelf
- Raises:
ValueError – Raised if the shelf is locked.
- shelfItemAdded(Item)
This is emitted when a shelf item in added to this shelf.
- Parameters:
Item (ShelfItem) – The new shelf item.
- shelfItemBadgeChanged(Item)
This is emitted when a shelf item’s badge changed.
- Parameters:
Item (ShelfItem) – The updated shelf item.
- shelfItemDataChanged(Item)
This is emitted when a shelf item’s data changed.
- Parameters:
Item (ShelfItem) – The updated shelf item.
- shelfItemIconChanged(Item)
This is emitted when a shelf item’s icon changed.
- Parameters:
Item (ShelfItem) – The updated shelf item.
- shelfItemLabelChanged(Item)
This is emitted when a shelf item’s label changed.
- Parameters:
Item (ShelfItem) – The updated shelf item.
- shelfItemRefreshed(Item)
This is emitted when a shelf item is refreshed.
A shelf item create goes through a background load and refresh. It is therefore not guaranteed to have its information up-to-date until this signal is emitted.
- Parameters:
Item (ShelfItem) – The refreshed shelf item.
- shelfItemRemoved()
This is emitted when a shelf item in removed from this shelf.
- shelfItemTagsChanged(Item)
This is emitted when a shelf item’s tags changed.
- Parameters:
Item (ShelfItem) – The updated shelf item.
- shelfItemThumbnailChanged(Item)
This is emitted when a shelf item’s thumbnail changed.
- Parameters:
Item (ShelfItem) – The updated shelf item.
- shelfItemTooltipChanged(Item)
This is emitted when a shelf item’s tooltip changed.
- Parameters:
Item (ShelfItem) – The updated shelf item.
- shelfNameChanged(Name)
This is emitted when the shelf name changes.
- Parameters:
Name (str) – The new name of this shelf.
- class mari.ShelfItem
Bases:
ActionRepresents the data model of a shelf item.
- data()
Returns the data of the shelf item.
- We return different data, depending on the type of the item, as follows:
SHELF_ITEM_IMAGE (image url): the filepath of the corresponding image
SHELF_ITEM_COLOR (color object): the corresponding mari.Color object
SHELF_ITEM_MATERIAL (material url): the filepath of the corresponding material file.
SHELF_ITEM_BRUSH (brush object): the serialised xml string of the corresponding brush.
SHELF_ITEM_COLOR_PROCEDURAL (procedural url): the filepath of the corresponding color procedural file.
SHELF_ITEM_SCALAR_PROCEDURAL (procedural url): the filepath of the corresponding scalar procedural file.
SHELF_ITEM_PROCEDURAL_MASK (procedural url): the filepath of the corresponding procedural mask file.
SHELF_ITEM_SCRIPT (python script): the python script.
- Raises:
ValueError – Raised if the shelf item has no valid parent shelf.
- Returns:
variant– Data of item
- name()
Returns the name of the item.
- Raises:
ValueError – Raised if the shelf item has no valid parent shelf.
- Returns:
str– The name of the item
- saveAs(rFileName)
Saves the shelf item to the given file name.
- Parameters:
rFileName (str) – The file name to save the item to. This extension of shelf items is .msi
- Raises:
ValueError – Raised if the filename is empty or does not end with the extension .msi or if the shelf item has no valid parent shelf.
IOError – Raised if the save failed.
- setData(Data)
Sets the data of the shelf item.
The data type must match for this method to succeed. For the details of content of Data, please refer to
Shelf.createItem()documentation- Parameters:
Data (variant) – the data content of the shelf item to set to
- setName(NewName)
Sets the name of the shelf item.
- Parameters:
NewName (str) – The new name for the item
- Raises:
ValueError – Raised if the shelf item has no valid parent shelf or if the parent shelf is locked.
- setTags(Tags)
Sets the tags of the ShelfItem to the given Tags.
This writes the data to the file pointed to by the
ShelfItem- Parameters:
Tags (list of str)
- Raises:
ValueError – Raised if the ShelfItem is of type that does not support tags or error occured while trying to set tags on the shelf item.
- setThumbnail(Thumbnail)
Sets the thumbnail of the ShelfItem to the given Thumbnail.
This writes the data to the file pointed to by the
ShelfItem- Parameters:
Thumbnail (QImage)
- Raises:
ValueError – Raised if an error occured while trying to set a thumbnail on the shelf item.
- tags()
Gets the tags of the ShelfItem.
- Raises:
ValueError – Raised if the ShelfItem is of type that does not support tags.
- Returns:
list of str– Tags of the ShelfItem
- thumbnail()
Gets the thumbnail of the ShelfItem.
- Raises:
ValueError – Raised if an error occured while trying to resolve the thumbnail for the shelf item.
- Returns:
QImage– Thumbnail of the ShelfItem
- type()
Returns the type of the item.
The valid types that can be manipulated via the python api are image, color, brush, and material.
- Raises:
ValueError – Raised if the shelf item has no valid parent shelf.
- Returns:
ShelfManager.ShelfItemType– Type of item
- class mari.ShelfManager
Bases:
objectThis manages the available shelves, or sets of item bookmarks.
Example Code
>>> # This example shows how to obtain the "Personal" shelf >>> import mari >>> personal_shelf = mari.shelves.find("Personal") >>> print(personal_shelf.className()) Shelf
Alias
shelves
- SHELF_ITEM_BRUSH = 0
Brush type (String)
- Type:
int
- SHELF_ITEM_COLOR = 1
Color type (mari.Color)
- Type:
int
- SHELF_ITEM_COLOR_PROCEDURAL = 5
Color Procedural url (String)
- Type:
int
- SHELF_ITEM_IMAGE = 2
Image type (String)
- Type:
int
- SHELF_ITEM_MATERIAL = 4
Material url (String)
- Type:
int
- SHELF_ITEM_NODE_GRAPH = 3
Node graph url (String)
- Type:
int
- SHELF_ITEM_PROCEDURAL_MASK = 7
Procedural Mask url (String)
- Type:
int
- SHELF_ITEM_SCALAR_PROCEDURAL = 6
Scalar Procedural url (String)
- Type:
int
- SHELF_ITEM_SCRIPT = 8
Python script (String)
- Type:
int
- SHELF_ITEM_UNKNOWN = 9
Unknown/Internal type (String)
- Type:
int
- class ShelfItemType
Bases:
objectShelfItemType type of the shelf item.
- SHELF_ITEM_BRUSH = 0
Brush type (String)
- Type:
int
- SHELF_ITEM_COLOR = 1
Color type (mari.Color)
- Type:
int
- SHELF_ITEM_COLOR_PROCEDURAL = 5
Color Procedural url (String)
- Type:
int
- SHELF_ITEM_IMAGE = 2
Image type (String)
- Type:
int
- SHELF_ITEM_MATERIAL = 4
Material url (String)
- Type:
int
- SHELF_ITEM_NODE_GRAPH = 3
Node graph url (String)
- Type:
int
- SHELF_ITEM_PROCEDURAL_MASK = 7
Procedural Mask url (String)
- Type:
int
- SHELF_ITEM_SCALAR_PROCEDURAL = 6
Scalar Procedural url (String)
- Type:
int
- SHELF_ITEM_SCRIPT = 8
Python script (String)
- Type:
int
- SHELF_ITEM_UNKNOWN = 9
Unknown/Internal type (String)
- Type:
int
- createShelf(ShelfName)
Creates a new shelf with the given name.
- Parameters:
ShelfName (str) – The shelf name.
- Raises:
ValueError – Raised if the name is not valid or a shelf of that name already exists.
- Returns:
Shelf– The newly created shelf, if the operation was successfull, or None if this function failed
- find(Name)
Returns the shelf with the given name.
- Parameters:
Name (str) – The name of the shelf to look for
- Returns:
Shelf– The shelf with the given name if found, or NULL otherwise
- groupShelf(ShelfToGroup, GroupPath)
Puts the given Shelf under the specified GroupPath.
- list()
Returns a list of all the available shelves.
- Returns:
list of
Shelf– A list of all of the available shelves
- loadShelvesFromDirectory(Path)
Loads all “.msh” shelf files within a directory and any sub-directories..
- Parameters:
Path (str) – Path to the directory where to search for “.msh” shelf files to load.
- Raises:
ValueError – Raised if the directory provided is not valid.
- Returns:
list of
Shelf– The list of newly created shelves.
- names()
Returns a string list of the names of all of the available shelves.
- Returns:
list of str– A string list of the names of all of the available shelves
- removeShelf(ShelfToRemove)
Removes the given shelf.
- Parameters:
ShelfToRemove (Shelf) – The shelf to remove.
- Raises:
ValueError – Raised if the shelf provided if not valid, locked or the shelf is a system one.
- Returns:
bool– Flag for whether the operation was successfull.
- search(SearchKeyword, Shelves)
Searches and returns the ShelfItems matching the keyword from the given Shelves.
- class mari.SliderBase
Bases:
WidgetBaseBase class for a slider widget.
Provides the base functionality for a custom slider widget in
Mari.Example Code
>>> # This example creates a new FloatSlider object, add it to a QWidget and show it >>> import mari >>> from PySide6 import QtWidgets >>> >>> float_slider = mari.FloatSlider() >>> container = QtWidgets.QWidget() >>> container.setLayout(QtWidgets.QHBoxLayout()) >>> float_slider.addToLayout(container.layout()) >>> container.show()
- hideSlider()
Hides the value slider next to the edit text box.
- hideValueEdit()
Hides the value edit text box next to the slider.
- logarithmic()
Returns whether or not the slider is logarithmic.
- Returns:
bool– Whether or not the slider is logarithmic.
- precision()
Returns the number of decimal places for the slider.
- Returns:
int– The number of decimal places of the slider.
- range(Min, Max)
Returns the upper and lower limits for the slider.
- Parameters:
Min (float) – The lower limit of the slider.
Max (float) – The upper limit of the slider.
- rangeMax()
Returns the upper limit for the slider.
- Returns:
float– The upper limit of the slider.
- rangeMin()
Returns the lower limit for the slider.
- Returns:
float– The lower limit of the slider.
- setLogarithmic(IsLogarithmic)
Sets whether or not the slider is logarithmic.
- Parameters:
IsLogarithmic (bool) – Whether or not the slider is logarithmic.
- setPrecision(NumDecimalPlaces)
Sets the number of decimal places for the slider.
- Parameters:
NumDecimalPlaces (int) – The number of decimal places of the slider.
- setRange(Min, Max)
Sets the upper and lower ranges for the slider.
- Parameters:
Min (float) – The lower limit of the slider.
Max (float) – The upper limit of the slider.
- setStepSize(StepSize)
Sets the size of each slider click.
- Parameters:
StepSize (float) – The step size of the slider.
- showSlider()
Shows the value slider next to the edit text box.
- showValueEdit()
Shows the value edit text box next to the slider.
- stepSize()
Returns the size of each slider click.
- Returns:
float– The step size of the slider.
- class mari.Snapshot
Bases:
MetadataA copy of the state of an object at a particular time.
By creating snapshots, users can easily preserve the state of an object and return to that state at some later time.
For example, this could be used to preserve the history of a design, or to try new ideas without risking the current textures. The user could snapshot the current state, paint some modifications, ask for approval, and if the changes are not accepted, quickly and easily revert to the previous state.
Example Code
>>> # This example shows how to obtain the current channel of the current GeoEntity object >>> import mari >>> channel = mari.geo.current().currentChannel() >>> channel_snapshot = channel.createSnapshot("Test Snapshot")
- creationDate()
Returns the date and time that the snapshot was created.
- Returns:
QDateTime– The date and time of creation of the snapshot
- creationDateChanged(DateTime)
This is emitted when the date or time of creation changes for the snapshot.
- Parameters:
DateTime (QDateTime) – The new date and time
- creator()
Returns the name of the user who created the snapshot.
- Returns:
str– The user name of the creator of the snapshot
- creatorChanged(Creator)
This is emitted when the creator of the snapshot changes.
- Parameters:
Creator (str) – The new creator of the snapshot
- hasPreview()
Indicates whether the snapshot has a valid preview image set.
- Returns:
bool– True if a valid preview has been set, or false otherwise
See also
preview(), setPreview()
- id()
Returns the identifier of the snapshot.
- Returns:
str– The identifier of the snapshot. This UUID may not be human readable, and may take the form of a long number string.
See also
setID()
- idChanged(NewID)
This is emitted when the ID of the snapshot changes.
- Parameters:
NewID (str) – The new identifier of the snapshot
- name()
Returns the descriptive name of the snapshot.
- Returns:
str– The name of the snapshot
See also
setName()
- nameChanged(Name)
This is emitted when the name of the snapshot changes.
- Parameters:
Name (str) – The new name for this snapshot
- preview()
Returns a preview image of the snapshot.
- Returns:
QPixmap– The current preview image
Note
Preview images are not created for snapshots automatically. Canvas::captureImage() can provide useful data for this purpose.
See also
setPreview(), hasPreview()
- previewChanged(pSnapshot)
This is emitted after the preview image for the snapshot changes.
- Parameters:
pSnapshot (Snapshot)
- setCreationDate(DateTime)
Sets the date of the creation of the snapshot.
- Parameters:
DateTime (QDateTime) – The date and time the snapshot was created
- setCreator(Creator)
Sets the name of the creator of the snapshot.
The creator is set automatically from the system on creation of a snapshot.
This method can be used to override the default value if required.
- Parameters:
Creator (str) – The name of the person who created the snapshot
- setID(NewID)
Sets the identifier of the snapshot.
The identifier is any (generally numeric) reproducible string to identify the snapshot or group of snapshots. If no custom ID is supplied, one is generated internally.
The ID can be used to group snapshots together across objects. For example, if you want to create a snapshot of five different objects at the same time, you can generate an ID and assign it to all of the snapshots. This makes an association between them, and then they can then be used as a group.
An example of this is the “snapshot all channels” option. In that case, all of the snapshots maintain the same ID, and can be reverted as a set.
- Parameters:
NewID (str) – The new identifier to use. This does not need to be unique between snapshots.
See also
id()
- setName(NewName)
Changes the descriptive name of the snapshot that is displayed to users.
There is no required naming standard for snapshots, so this can be written as clearly as desired - e.g. “new test version”.
- Parameters:
NewName (str) – A descriptive name for the snapshot for users
- Raises:
ValueError – Raised if the supplied name string was empty.
See also
name()
- setPreview(NewImage)
Sets the preview image of the snapshot.
- Parameters:
NewImage (QPixmap) – The new preview image to store
See also
preview(), hasPreview()
- class mari.Snapshotable
Bases:
LockableAn object that can have copies of its state taken at particular times.
A
Snapshotis a copy of the state of an object at a particular time. Objects of this type can have snapshots of their state taken.- createSnapshot(Name, ID='str')
Creates a new snapshot of the object.
- Parameters:
Name (str) – A descriptive name for this snapshot. There is no restriction on naming convention, so it is recommended to make this clear, such as “new test version”.
ID (str, optional) – An optional identifier for this snapshot. This value can be used to group together sets of snapshots, as described in
Snapshot::setID(). Defaults to str.
- Returns:
Snapshot– The newly created snapshot.
- deleteSnapshot(ShotToDelete)
Deletes the given snapshot.
- Parameters:
ShotToDelete (Snapshot) – The snapshot to delete
- Raises:
ValueError – The snapshot provided was invalid, or not owned by this object.
Warning
This method cannot be undone, so please use caution.
- findSnapshotWithID(ID)
Returns the snapshot with the given identifier, if found.
If more than one snapshot with the given identifier exists, the first one will be returned.
- Parameters:
ID (str) – The shot identifier to search for
- Returns:
Snapshot– The first snapshot with the given identifier, or NULL
- revertToSnapshot(OldSnapshot)
Reverts the state of the object to that in the given snapshot.
- Parameters:
OldSnapshot (Snapshot) – A valid snapshot of this object
- Raises:
ValueError – The snapshot provided was invalid, or not owned by this object.
- snapshotAdded(NewSnapshot)
This is emitted after a snapshot is created for this object.
- Parameters:
NewSnapshot (Snapshot)
- class mari.StringList(Value)
Bases:
objectStores a list of strings and can specify an entry as the current value.
Example Code
>>> # This example creates a StringList object with a current entry >>> import mari >>> string_list = mari.StringList() >>> string_list.append("First") >>> string_list.append("Second") >>> string_list.append("Third") >>> string_list.setCurrent("Second") >>> string_list.current() // returns "Second"
- __init__(Value)
Creates a new string list.
- Parameters:
Value (variant) – This can either be a StringList::Type or another
StringList.
- append(String)
Inserts a string at the end of the list.
- Parameters:
String (str) – The string to append
- at(Index)
Returns the string at the given index in the list.
- Parameters:
Index (int) – The index of the string to return
- Raises:
IndexError – Raised if the index is out of range.
- Returns:
str– The string at the given index
- clear()
Removes all strings from the list.
- contains(String)
Returns true if the list contains an occurrence of the string, otherwise returns false.
- Parameters:
String (str) – The string to search for
- Returns:
bool– Whether the list contains an occurrence of the given string
- count()
Returns the number of strings in the list.
- Returns:
int– The number of strings in the list
- current()
Return the current string.
- Returns:
str– Returns the current string.
- currentIndex()
Return the index of the current string in the list.
- Returns:
int– The index of the current string. May return -1 if no current index is set.
- insert(Index, String)
Inserts the string at the given index in the list. If index is 0, the value is prepended to the list. If index is the size of the list, the string is appended to the list.
- Parameters:
Index (int) – The position to insert the string at
String (str) – The string to insert
- Raises:
IndexError – Raised if the index is out of range.
- isEmpty()
Returns true if the list contains no strings, otherwise returns false.
- Returns:
bool– Whether the list contains no strings
- removeAt(Index)
Removes the string at the given index.
- Parameters:
Index (int) – The index of the string to remove
- Raises:
IndexError – Raised if the index is out of range.
- setCurrent(String)
Set the given string as the current string.
- Parameters:
String (str) – The string to make the current string
- Raises:
ValueError – Raised if the given string is not in the list.
- setCurrentIndex(Index)
Set the string at the given index as the current string.
- Parameters:
Index (int) – The index of the string to make current. A value of -1 may be used to unset the current string.
- Raises:
IndexError – Raised if the index is out of range.
- class mari.SwitchNode
Bases:
NodeRepresents a switch node.
- activeInput()
Returns the name of the currently active input.
- Returns:
str– The name of the active input. This may be an empty string if there is no currently active input.
- addInput(PrettyName)
Add an input to this node.
- Parameters:
PrettyName (str) – The pretty name of the input to add.
- Raises:
ValueError – Raised if the pretty name is invalid.
SystemError – Raised if the given input could not be added.
- Returns:
str– The name of the new input.
- inputNameFromPrettyName(PrettyName)
Return the name of the input that has the given pretty name assigned to it.
- Parameters:
PrettyName (str) – The pretty name to find the input for.
- Raises:
ValueError – Raised if no input has the given pretty name assigned.
- Returns:
str– The name of the input with the given pretty name assigned.
- inputPrettyName(InputName)
Return the pretty name assigned to a given input.
- Parameters:
InputName (str) – The name of the input to get the pretty name of.
- Raises:
ValueError – Raised if the given input could not be found.
- Returns:
str– The pretty name assigned to the input. This may be an empty string if the input has no pretty name assigned.
- moveInput(InputName, Index)
Move the given input on this node to the index specified.
- Parameters:
InputName (str) – The name of the input to move.
Index (int) – The index to move it to. Valid indices are of the range [0,:obj:inputPortCount() -1].
- Raises:
ValueError – Raised if the given input could not be found.
IndexError – Raised if the given index was invalid.
SystemError – Raised if the given input could not be moved.
- removeInput(InputName)
Remove the given input from this node.
- Parameters:
InputName (str) – The name of the input to remove.
- Raises:
ValueError – Raised if the given input could not be found.
RuntimeError – Raised if trying to remove the last input. Switch Nodes must have at least one input.
SystemError – Raised if the given input could not be removed.
- setActiveInput(InputName)
Sets the active input for this node.
- Parameters:
InputName (str) – The name of the active input to use.
- Raises:
ValueError – Raised if the given input could not be found.
- setInputPrettyName(InputName, PrettyName)
Set the pretty name of the given input.
- Parameters:
InputName (str) – The name of the input to assign a pretty name to.
PrettyName (str) – The pretty name to assign to the given input.
- Raises:
ValueError – Raised if the given input could not be found.
ValueError – Raised if another input is already assigned the given pretty name.
ValueError – Raised if the given pretty name is invalid.
SystemError – Raised if the given input could not be renamed.
- Returns:
str– The pretty name assigned to the given input.
- class mari.TeleportNode
Bases:
NodeRepresents a teleport node.
- channelName()
Returns the channel this node uses.
- Returns:
str– The channel this node uses.
- channelNameChanged(ChannelName)
This is emitted when the channel this node uses changes.
- Parameters:
ChannelName (str)
- setChannelName(ChannelName)
Sets the channel this node uses.
- Parameters:
ChannelName (str) – The channel this node uses.
- class mari.Tool
Bases:
PropertySourceThis is the base API for Mari’s viewport tools.
You can access canvas objects through the
CanvasManager- for example:mari.canvases.current()- cursor()
Returns cursor used for this tool.
mari.tools.currentTool().cursor()- Returns:
QCursor– A QCursor containing the cursor for this tool
- description()
Returns a brief description of the tool.
print(mari.tools.currentTool().description()- Returns:
str– A string containing the description
- help()
Returns the help string for this tool.
print(mari.tools.currentTool().help())- Returns:
str– A string containing help information for this tool.
- icon()
Return the main icon for the tool.
mari.tools.currentTool().icon()- Returns:
QIcon– A QIcon representing the main icon for the tool
- iconActive()
Return the icon to be displayed when the tool is active.
mari.tools.currentTool().iconActive()- Returns:
QIcon– A QIcon representing the active icon for the tool
- information()
Return information about the current state of the tool.
print(mari.tools.currentTool().information())- Returns:
str– A string containing information about the state of the tool. Brush Radius etc.
- name()
Return the name of the tool.
print(mari.tools.currentTool().name())- Returns:
str– A string containing the name of the tool
- class mari.ToolBar
Bases:
WidgetBaseA tool bar widget.
Users can create their own custom tool bars, and add any pre-defined or custom actions as they wish.
Example Code
>>> # This example shows how to create a toolbar and add a label to it >>> import mari >>> from PySide6 import QtWidgets >>> label = QtWidgets.QLabel("Hello World") >>> toolbar = mari.app.createToolBar("Hello World Toolbar") >>> toolbar.addWidget(label) >>> mari.app.deleteToolBar("Hello World Toolbar")
- actionsList()
Returns the paths of the actions in this toolbar.
- addAction(Path, Pos, Removable=True)
(Deprecated) Adds an action based on the action repository path.
- Parameters:
Path (str) – The path to the new action to add
Pos (list of
int) – The point at which the new action should be added, as a list of integers - e.g. [1, 2]Removable (bool, optional) – Defines whether the action can be removed from the toolbar. Defaults to True.
Deprecated
This function will be removed in a future version. Please use addActionBefore() instead.
- addActionBefore(Path, InsertBefore=None, Removable=True)
Adds an action based on the action repository path.
- Parameters:
Path (str) – The path to the new action to add
InsertBefore (QAction, optional) – The action before which the new aciton is added. If None, the new action is added to the end. Defaults to None.
Removable (bool, optional) – Defines whether the action can be removed from the toolbar. Defaults to True.
- addActionList(Actions, Removable)
Adds a list of actions based on the action repository path.
- Parameters:
Actions (list of str) – List of actions
Removable (bool) – Boolean showing whether the action should be removable from the toolbar
- addActionObject(Object)
Adds the given action to the toolbar as the toolbar’s last item.
- Parameters:
Object (QAction) – The action to add
- addSeparator()
Adds a separator to the end of the toolbar.
- addWidget(Widget)
No description
- Parameters:
Widget (WidgetBase)
- insertAction(PathBefore, PathAction, Removable=True)
Inserts the action specified by PathAction to the position before the action specified by PathBefore.
- Parameters:
PathBefore (str) – The path to the action to insert the action before
PathAction (str) – The path to the new action to insert
Removable (bool, optional) – Defines whether the action can be removed from the toolbar. Defaults to True.
- Returns:
bool– True if the action is successfully inserted.
- insertSeparator(Path)
Inserts a separator into the toolbar in front of the toolbar item associated with the given action.
- Parameters:
Path (str) – The path to the action to insert a separator before
- Raises:
ValueError – Raised if the requested action was not found.
- insertWidget(Path, Widget)
No description
- Parameters:
Path (str)
Widget (WidgetBase)
- isLocked()
Indicates whether this toolbar is locked, and if so, unmodifiable.
Toolbars can only have new actions dragged onto them when unlocked.
- Returns:
bool– True if this image is locked, or false if unlocked
See also
lock(), setLocked(), unlock()
- lock()
Locks the toolbar to prevent modifications.
Toolbars can only have new actions dragged onto them when unlocked.
See also
isLocked(), setLocked(), unlock()
- setLocked(Locked)
Locks or unlocks the toolbar, to optionally prevent modifications.
Toolbars can only have new actions dragged onto them when unlocked.
- Parameters:
Locked (bool)
See also
isLocked(), lock(), unlock()
- setSpacing(Spacing)
Sets the spacing between widgets inside the toolbar.
- Parameters:
Spacing (int)
- setVisibile(Visible)
Shows or hides the toolbar.
- Parameters:
Visible (bool) – True to show the toolbar, or false to hide it.
See also
hide(), isVisible(), show()
- spacing()
Returns the spacing between widgets inside the toolbar.
- unlock()
Unlocks the toolbar and allows modifications.
Toolbars can only have new actions dragged onto them when unlocked.
See also
isLocked(), lock(), setLocked()
- class mari.ToolManager
Bases:
objectProvides access to the various interactive user tools.
Example Code
>>> # This example shows how to print the name of the current tool >>> import mari >>> print(mari.tools.current()) Paint (P)
Alias
tools
- current()
Returns the name of the current tool.
print(mari.tools.current())- Returns:
str– The name of the active tool
See also
setCurrent(), currentHelpString()
- currentHelpString()
Returns the help string for the current tool.
print(mari.tools.currentHelpString())- Returns:
str– The help string for the active tool
See also
current()
- currentTool()
Returns a handle to the current tool.
T = mari.tools.currentTool() print(T.name())
- Returns:
Tool– A Handle to the current tool
- getTool(Name)
Return a handle to the given tool.
T = mari.tools.getTool('Paint') print(T.name())
- Parameters:
Name (str) – The name of the tool requested
- Raises:
ValueError – Raised if the given tool is not found
- Returns:
Tool– A handle to the requested tool
- loadBrushes(Path)
Loads a brushes file into the brush library.
- Parameters:
Path (str) – The path to the brush file to open.
- Raises:
ValueError – Raise if the file could not be openned or used as a brush
- names()
Returns the names of the available tools.
print(mari.tools.names())- Returns:
list of str– The list of available tools
- setCurrent(Name)
Sets the current tool by name.
mari.tools.setCurrent('Paint')- Parameters:
Name (str) – The name of a tool, as returned by
names()- Raises:
ValueError – if the given tool is not found
See also
current(), names()
- class mari.UvIndexRangeList(RangeString='str')
Bases:
IndexRangeListClass to contain a list UDIM ranges.
It can contain a list of UDIM ranges or single UDIMs separated by a space. Example:
"1001-1005 1013 1010-1007"- __init__(RangeString='str')
Initialize the class using the range from the given string.
The string can contain a list of UDIM ranges or single UDIMs separated by a space. Example:
"1001-1005 1013 1010-1007"- Parameters:
RangeString (str, optional) – The range as a string. Defaults to str.
- fromString(RangeString)
Sets the range from a given string.
The string can contain a list of UDIM ranges or single UDIMs separated by a space. Example:
"1001-1005 1013 1010-1007"- Parameters:
RangeString (str) – The range as a string
- Returns:
bool– Whether the range was set correctly.
- toString()
Returns a string representation of the range.
- Returns:
str– The range as a string.
- udimList()
Returns the list of UDIM as a list of integers.
- Returns:
list of
int– the list of UDIM as a list of integers
- uvIndexList()
Returns the list of UV indices as a list of integers.
- Returns:
list of
int– the list of UV indices as a list of integers
- class mari.VectorN(X='variant', Y='variant', Z='variant', W='variant')
Bases:
objectObjects of this class hold multi-dimensional coordinates.
Coordinates that represent UV, 3D, or 4D values should all be stored in objects of this type.
Example Code
>>> # This example shows how to obtain the position of the 1st light >>> import mari >>> lights = mari.lights.list() >>> light_position = lights[0].position() >>> print(light_position.className()) VectorN
- __init__(X='variant', Y='variant', Z='variant', W='variant')
Constructs a new vector.
A vector can be constructed from up to four components. The specified parameters should be either all float values for these components, or one single parameter which is a list containing float values.
For example:
mari.VectorN(1, 2) // 2D vector mari.VectorN([1, 2]) // 2D vector mari.VectorN(1, 2, 3) // 3D vector mari.VectorN([1, 2, 3]) // 3D vector mari.VectorN(1, 2, 3, 4) // 4D vector mari.VectorN([1, 2, 3, 4])// 4D vector
- Parameters:
X (variant, optional) – Optional first element (float, or list of floats). Defaults to variant.
Y (variant, optional) – Optional second element (float). Defaults to variant.
Z (variant, optional) – Optional third element (float). Defaults to variant.
W (variant, optional) – Optional fourth element (float). Defaults to variant.
- asTuple()
Returns the elements of the vector as a tuple.
- Returns:
tuple of
float– The elements of the vector in a tuple - e.g., (1.0, 2.0, 3.0)
- length()
Returns the length of the vector.
This is the same as
size().- Returns:
int– The length of the vector
- size()
Returns the size of the vector.
This is the same as
length().- Returns:
int– The size of the vector
- w()
Returns the 3rd component.
- x()
Returns the 0th component.
- y()
Returns the 1st component.
- z()
Returns the 2nd component.
- class mari.WidgetBase
Bases:
objectBase class for a widget.
Provides the base functionality for a custom widget in
Mari.- addToLayout(Layout)
Adds the widget to the given layout.
- Parameters:
Layout (QLayout) – The layout to add the widget to.
- Raises:
ValueError – Raised if the given layout is null.
- blockSignals(Block)
Disables or re-enables the emission of signals from the object.
If Block is true, this will block the emission of signals from this object - i.e., emitting a signal will not invoke anything connected to it. If Block is false, any previous blocking will be deactivated.
Signals are always enabled by default.
When using this function, you should store the return value, which is the previous setting for whether signals were blocked. When your processing has finished, you should call this function again with the previous value. This will ensure that signals will not be re-enabled earlier than intended.
- Parameters:
Block (bool) – True to block signals, or false to unblock them - but see above for why this should generally be called with a stored value instead of an explicit false
- Returns:
bool– The previous value of whether signals were blocked.
- disable()
Disables interaction with the widget.
See also
enable(), isEnabled(), setEnabled()
- enable()
Enables interaction with the widget.
See also
disable(), isEnabled(), setEnabled()
- hide()
Hides the widget from view.
See also
isVisible(), setVisibility(), show()
- isEnabled()
Indicates whether the widget is enabled, and if so, modifiable.
- Returns:
bool– True if this widget is enabled, or false if disabled
See also
setEnabled()
- isVisible()
Indicates whether the widget is visible.
- Returns:
bool– True if the widget is visible, or false if not.
See also
hide(), setVisibility(), show()
- maximumHeight()
Returns the maximum height of the widget in pixels.
See also
setMaximumHeight()
- maximumWidth()
Returns the maximum width of the widget in pixels.
See also
setMaximumWidth()
- minimumHeight()
Returns the minimum height of the widget in pixels.
See also
setMinimumHeight()
- minimumWidth()
Returns the minimum width of the widget in pixels.
See also
setMinimumWidth()
- setEnabled(Enable)
Enables or disables the widget, to optionally prevent modifications.
- Parameters:
Enable (bool) – True to enable the toolbar, or false to disable it.
See also
isEnabled()
- setMaximumHeight(Height)
Sets the maximum height of the widget in pixels.
- Parameters:
Height (int)
See also
maximumHeight()
- setMaximumWidth(Width)
Sets the maximum width of the widget in pixels.
- Parameters:
Width (int)
See also
maximumWidth()
- setMinimumHeight(Height)
Sets the minimum height of the widget in pixels.
- Parameters:
Height (int)
See also
minimumHeight()
- setMinimumWidth(Width)
Sets the minimum width of the widget in pixels.
- Parameters:
Width (int)
See also
minimumWidth()
- setStatusTip(StatusTip)
Sets the status tip for the widget.
- Parameters:
StatusTip (str)
See also
statusTip()
- setToolTip(ToolTip)
Sets the tooltip for the widget.
- Parameters:
ToolTip (str)
See also
toolTip()
- setVisible(Visible)
Shows or hides the widget.
- Parameters:
Visible (bool) – True to show the widget, or false to hide it.
See also
hide(), isVisible(), show()
- show()
Shows the widget again after a previous hide() operation.
See also
hide(), isVisible(), setVisibility()
- statusTip()
Returns the status tip for the widget.
See also
setStatusTip()
- toolTip()
Returns the tooltip for the widget.
See also
setToolTip()
- class mari.WrappedEvent
Bases:
object
- mari.signal(f)