def process(self, instance):
import os
from maya import cmds
# Resources are optional
if "resources_SEL" not in instance:
return
resources = dict()
for resource in cmds.sets("resources_SEL", query=True):
if cmds.nodeType(resource) == "reference":
path = cmds.referenceQuery(resource,
filename=True,
unresolvedName=True)
elif cmds.nodeType(resource) == "AlembicNode":
path = cmds.getAttr(resource + ".abc_File")
else:
# Unsupported
path = None
resources[resource] = path
# All resources were resolved
assert all(resources.values()), (
"Unsupported resource(s): " +
", ".join("'%s': '%s'" % (resource, path)
for resource, path in resources.items()
if path is not None)
)
# No resource contains an absolute path
assert not any(os.path.isabs(fname) for fname in resources), (
"Some resources are absolute: " +
", ".join(resources)
)
python类referenceQuery()的实例源码
def process(self, instance):
import os
from maya import cmds
# Resources are optional
if "resources_SEL" not in instance:
return
resources = dict()
for resource in cmds.sets("resources_SEL", query=True):
if cmds.nodeType(resource) == "reference":
path = cmds.referenceQuery(resource,
filename=True,
unresolvedName=True)
elif cmds.nodeType(resource) == "AlembicNode":
path = cmds.getAttr(resource + ".abc_File")
else:
# Unsupported
path = None
resources[resource] = path
# All resources were resolved
assert all(resources.values()), (
"Unsupported resource(s): " +
", ".join("'%s': '%s'" % (resource, path)
for resource, path in resources.items()
if path is not None)
)
# No resource contains an absolute path
assert not any(os.path.isabs(fname) for fname in resources), (
"Some resources are absolute: " +
", ".join(resources)
)
def remove(container):
"""Remove an existing `container` from Maya scene
Deprecated; this functionality is replaced by `api.remove()`
Arguments:
container (avalon-core:container-1.0): Which container
to remove from scene.
"""
node = container["objectName"]
# Assume asset has been referenced
reference_node = next((node for node in cmds.sets(node, query=True)
if cmds.nodeType(node) == "reference"), None)
assert reference_node, ("Imported container not supported; "
"container must be referenced.")
log.info("Removing '%s' from Maya.." % container["name"])
namespace = cmds.referenceQuery(reference_node, namespace=True)
fname = cmds.referenceQuery(reference_node, filename=True)
cmds.file(fname, removeReference=True)
try:
cmds.delete(node)
except ValueError:
# Already implicitly deleted by Maya upon removing reference
pass
try:
# If container is not automatically cleaned up by May (issue #118)
cmds.namespace(removeNamespace=namespace, deleteNamespaceContent=True)
except RuntimeError:
pass
def meshesFromReference(control):
'''
Get meshes from the referenced file. This is faster and more accurate in most
cases than traversing history, but only works if the rig is referenced.
'''
if not mc.referenceQuery(control, isNodeReferenced=True):
return []
ref = mc.referenceQuery(control, referenceNode=True)
nodes = mc.referenceQuery(ref, nodes=True)
meshes = mc.ls(nodes, type='mesh')
return [x for x in meshes if isNodeVisible(x)]
def curves(self):
'''
The keySelections's animation curve list.
'''
# if self._curves is False or None, then it has been initialized and curves haven't been found.
if self._curves == []:
#find anim curves connected to channels or nodes
for each in (self._channels, self._nodes):
if not each:
continue
# this will only return time based keyframes, not driven keys
self._curves = mc.keyframe(each, time=(':',), query=True, name=True)
if self._curves:
self._curvesCulled = False
break
if not self._curves:
self._curves = False
# need to remove curves which are unkeyable
# supposedly referenced keys are keyable in 2013, I'll need to test that and update
if self._curves and not self._curvesCulled:
remove = list()
for c in self._curves:
if mc.referenceQuery(c, isNodeReferenced=True):
remove.append(c)
else:
plug = mc.listConnections('.'.join((c,'output')), source=False, plugs=True)
if plug:
if not mc.getAttr(plug, keyable=True) and not mc.getAttr(plug, settable=True):
remove.append(c)
if remove:
for r in remove:
self._curves.remove(r)
self._curvesCulled = True
return self._curves
def auto_connect_assets(src, dst):
"""Attempt to automatically two assets
Arguments:
src (str): Name of source reference node
dst (str): Name of destination reference node
Raises:
StopIteration on missing in_SET
"""
in_set = None
for node in cmds.referenceQuery(dst, nodes=True):
if node.endswith("in_SET"):
in_set = node
break
for input_transform in cmds.sets(in_set, query=True):
mbid = cmds.getAttr(input_transform + ".mbID")
input_shape = cmds.listRelatives(input_transform, shapes=True)[0]
for output_transform in lib.lsattr("mbID", value=mbid):
ref = cmds.referenceQuery(output_transform, referenceNode=True)
if ref != src:
continue
print("Connecting %s -> %s" % (output_transform, input_transform))
output_shape = cmds.listRelatives(output_transform, shapes=True)[0]
try:
auto_connect(output_transform, input_transform)
except RuntimeError:
# Already connected
pass
try:
auto_connect(output_shape, input_shape)
except RuntimeError:
# Already connected
pass
def process(self, name, namespace, context, data):
import os
import json
from maya import cmds
from polly.maya import lib
try:
existing_reference = cmds.file(self.fname,
query=True,
referenceNode=True)
except RuntimeError as e:
if e.message.rstrip() != "Cannot find the scene file.":
raise
self.log.info("Loading lookdev for the first time..")
nodes = cmds.file(
self.fname,
namespace=namespace,
reference=True,
returnNewNodes=True
)
else:
self.log.info("Reusing existing lookdev..")
nodes = cmds.referenceQuery(existing_reference, nodes=True)
namespace = nodes[0].split(":", 1)[0]
# Assign shaders
self.fname = self.fname.rsplit(".", 1)[0] + ".json"
# Expand $AVALON_PROJECT and friends, if used
self.fname = os.path.expandvars(self.fname)
if not os.path.isfile(self.fname):
self.log.warning("Look development asset "
"has no relationship data.\n"
"%s was not found" % self.fname)
return nodes
with open(self.fname) as f:
relationships = json.load(f)
lib.apply_shaders(relationships, namespace)
self[:] = nodes
def clean_up_file():
pass
# import references
"""
refs = cmds.ls(type='reference')
for i in refs:
rFile = cmds.referenceQuery(i, f=True)
cmds.file(rFile, importReference=True, mnr=True)
defaults = ['UI', 'shared']
# Used as a sort key, this will sort namespaces by how many children they have.
def num_children(ns):
return ns.count(':')
namespaces = [ns for ns in cmds.namespaceInfo(lon=True, r=True) if ns not in defaults]
# We want to reverse the list, so that namespaces with more children are at the front of the list.
namespaces.sort(key=num_children, reverse=True)
for ns in namespaces:
if namespaces.index(ns)+1 < len(namespaces):
parent_ns = namespaces[namespaces.index(ns)+1]
cmds.namespace(mv=[ns,parent_ns], f=True)
cmds.namespace(rm=ns)
else:
cmds.namespace(mv=[ns,":"], f=True)
cmds.namespace(rm=ns)
# remove ngSkinTools custom nodes
from ngSkinTools.layerUtils import LayerUtils
LayerUtils.deleteCustomNodes()
# remove RRM proxies
if cmds.objExists("RRM_MAIN"):
cmds.select("RRM_MAIN",hi=True)
proxies = cmds.ls(sl=True)
cmds.lockNode(proxies,lock=False)
cmds.delete(proxies)
if cmds.objExists("RRM_ProxiesLayer"):
cmds.delete("RRM_ProxiesLayer")"""
def load(asset, version=-1):
"""Load asset
Arguments:
asset ("pyblish-starter:asset-1.0"): Asset which to import
version (int, optional): Version number, defaults to latest
Returns:
Reference node
Raises:
IndexError on no version found
ValueError on no supported representation
"""
assert asset["schema"] == "pyblish-starter:asset-1.0"
assert isinstance(version, int), "Version must be integer"
try:
version = asset["versions"][version]
except IndexError:
raise IndexError("\"%s\" of \"%s\" not found." % (version, asset))
supported_formats = api.registered_formats()
# Pick any compatible representation.
# Hint: There's room to make the user choose one of many.
# Such as choosing between `.obj` and `.ma` and `.abc`,
# each compatible but different.
try:
representation = next(
rep for rep in version["representations"]
if rep["format"] in supported_formats and
rep["path"] != "{dirname}/source{format}"
)
except StopIteration:
formats = list(r["format"] for r in version["representations"])
raise ValueError(
"No supported representations for \"%s\"\n\n"
"Supported representations: %s"
% (asset["name"], "\n- ".join(formats)))
fname = representation["path"].format(
dirname=version["path"],
format=representation["format"]
)
nodes = cmds.file(fname,
namespace=asset["name"] + "_",
reference=True,
returnNewNodes=True)
self.log.info("Containerising \"%s\".." % fname)
containerise(asset["name"], nodes, version)
self.log.info("Container created, returning reference node.")
return cmds.referenceQuery(nodes[0], referenceNode=True)