Create an Atoms Skeleton from scratch

Create an Atoms Skeleton from scratch

This is an example script to create an Atoms Skeleton from a Maya skeleton.

""" maya_to_atoms_skeleton.py Builds an AtomsCore.Skeleton from a selected Maya root joint. Usage (Maya Script Editor): 1. Select the root joint of your skeleton in Maya. 2. Run this script. 3. Optionally save the skeleton to disk via Atoms.exportSkeleton(). """ import maya.cmds as cmds import maya.api.OpenMaya as om import AtomsCore import Atoms import AtomsMath # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def get_dag_path(node_name): """Return an MDagPath for the given node name.""" sel = om.MSelectionList() sel.add(node_name) return sel.getDagPath(0) def get_world_matrix(joint_name): """ Return the world-space matrix of a joint as an AtomsCore.Matrix44d. """ dag = get_dag_path(joint_name) inclusive_matrix = dag.inclusiveMatrix() # MMatrix (world) m = list(inclusive_matrix) # flat list of 16 doubles, row-major # AtomsCore.Matrix44d constructor accepts a flat 16-element list (row-major) return AtomsMath.Matrix(m) def get_local_matrix(joint_name): """ Return the local (parent-relative) matrix as an AtomsCore.Matrix44d. The local transform = world * inverse(parent_world). For root joints the local == world matrix. """ dag = get_dag_path(joint_name) local_matrix = dag.exclusiveMatrix() # parent-space matrix via exclusiveMatrix inverse trick # Safer: read xformMatrix attribute directly (local space) local_m = cmds.xform(joint_name, q=True, m=True, os=True) # 16 floats, object space return AtomsMath.Matrix(local_m) def recursive_collect_joints(joint, parent_idx, joint_names, parent_indices): if not cmds.objectType(joint, isType='joint'): return current_idx = len(joint_names) joint_names.append(joint) parent_indices.append(parent_idx) children = cmds.listRelatives(joint, children=True, type='joint', fullPath=False) or [] for child in children: recursive_collect_joints(child, current_idx, joint_names, parent_indices) def collect_joint_hierarchy(root_joint): """ BFS traversal of the joint hierarchy starting from root_joint. Returns: joint_names : list[str] - ordered joint names (root first) parent_index : list[int] - parent index for each joint (-1 for root) """ joint_names = [] parent_indices = [] recursive_collect_joints(root_joint, -1, joint_names, parent_indices) return joint_names, parent_indices def get_atoms_tag(joint_name): tag_map = { 'atoms_pelvisHeight': 'pelvis', 'atoms_footRoot': 'footroot', 'atoms_footIK': 'footik', 'atoms_footOnGround': 'foottip', 'atoms_skipIk': 'skipik', } for tag_attr in tag_map: if cmds.attributeQuery(tag_attr, node=joint_name, exists=True): return tag_map[tag_attr] return '' def sanitize_joint_name(name): """ Mirror the Atoms 'Sanitize Joint Names' option: - Replace '.' with '_' - If ':' present, take only the part after the last ':' """ if ':' in name: name = name.rsplit(':', 1)[-1] name = name.replace('.', '_') return name def find_leg_joint(joint, leg_joint_ids=[]): for i in range(joint.numChildren()): child = joint.child(i) if child.id() in leg_joint_ids: return child.id() child_id = find_leg_joint(child, leg_joint_ids) if child_id != -1: return child_id return -1 # --------------------------------------------------------------------------- # Core builder # --------------------------------------------------------------------------- def build_atoms_skeleton_from_maya(root_joint=None, sanitize_names=True): """ Build and return an AtomsCore.Skeleton from a Maya joint hierarchy. Args: root_joint : str - Maya joint name. If None, uses the current selection. sanitize_names: bool - Apply Atoms name sanitization rules. Returns: AtomsCore.Skeleton """ # Resolve root joint if root_joint is None: sel = cmds.ls(selection=True, type='joint') if not sel: raise RuntimeError( 'No root joint provided and nothing joint-type selected. ' 'Select the root joint in Maya and re-run.' ) root_joint = sel[0] root_translation = get_world_matrix(root_joint).translation() print('[AtomsSkeletonBuilder] Root joint: {}'.format(root_joint)) # Collect hierarchy joint_names, parent_indices = collect_joint_hierarchy(root_joint) num_joints = len(joint_names) print('[AtomsSkeletonBuilder] Found {} joints.'.format(len(joint_names))) print(joint_names, parent_indices) # Create skeleton skeleton = AtomsCore.Skeleton(num_joints) foot_root = [] foot_ik = [] foot_tip = [] skipIks = [] pelvis = [] for idx, joint_name in enumerate(joint_names): parent_idx = parent_indices[idx] # Sanitize name for Atoms atoms_name = sanitize_joint_name(joint_name) if sanitize_names else joint_name # Build AtomsCore.Joint joint = skeleton[idx] joint.setName(atoms_name) # Local (parent-relative) rest pose matrix local_mat = get_local_matrix(joint_name) if idx == 0: # get the root in world space and mute its translation local_mat = get_world_matrix(joint_name) local_mat[3][0] = 0.0 local_mat[3][1] = 0.0 local_mat[3][2] = 0.0 joint.setMatrix(local_mat) # Atoms tagging (pelvis, foot root, etc.) tag = get_atoms_tag(joint_name) if tag: if tag == 'pelvis': pelvis.append(idx) elif tag == 'footroot': foot_root.append(idx) elif tag == 'footik': foot_ik.append(idx) elif tag == 'foottip': foot_tip.append(idx) elif tag == 'skipik': skipIks.append(idx) print('[AtomsSkeletonBuilder] Tagged "{}" as {}'.format(atoms_name, tag)) # Parent index (-1 = root) if parent_idx != -1: parent_joint = skeleton[parent_idx] joint.setParent(parent_joint) parent_joint.addChild(joint) # Add to skeleton print('[AtomsSkeletonBuilder] Added joint [{}] "{}" (parent={})'.format( idx, atoms_name, parent_idx)) print('[AtomsSkeletonBuilder] Skeleton built with {} joints.'.format( skeleton.numJoints())) skeleton.buildJointNameMap() skel.clearPelvises() for idx in pelvis: skeleton.addPelvis(idx) for idx in foot_root: #find the matching ik and tip joint = skeleton[idx] ik = find_leg_joint(joint, foot_ik) tip = find_leg_joint(joint, foot_tip) if ik == -1 or tip == -1: continue skeleton.addFoot(ik, idx, tip) print('[AtomsSkeletonBuilder] Leg {} {} {}'.format(joint.id(), ik, tip)) for skip in skipIks: skeleton.addJointMetadata(skip, 'skipIk', AtomsCore.BoolMetadata(True)) for idx in foot_root: leg_root_name = skeleton[idx].name() if cmds.attributeQuery('atoms_poleVector', node=leg_root_name, exists=True): pole_vec = cmds.getAttr(leg_root_name + '.atoms_poleVector')[0] print(pole_vec) poleVector = AtomsMath.Vector3(pole_vec[0], pole_vec[1], pole_vec[2]) poleVector = poleVector - root_translation poleVectorMeta = AtomsCore.Vector3Metadata(poleVector) skeleton.addJointMetadata(idx, "poleVector", poleVectorMeta) skeleton.buildIkData() skeleton.buildDetachedJointsList() return skeleton # --------------------------------------------------------------------------- # Optional: save skeleton to disk # --------------------------------------------------------------------------- def export_atoms_skeleton(skeleton, output_path): """ Export the AtomsCore.Skeleton to a file using the Atoms exporter. Supports .atoms, .fbx, .usd output paths. Args: skeleton : AtomsCore.Skeleton output_path : str e.g. '/path/to/output/my_skeleton.atoms' """ Atoms.exportSkeleton(skeleton, output_path) print('[AtomsSkeletonBuilder] Skeleton exported to: {}'.format(output_path)) # --------------------------------------------------------------------------- # Entry point # --------------------------------------------------------------------------- if __name__ == '__main__': # --- Build --- # Either pass the root joint name explicitly: # skel = build_atoms_skeleton_from_maya(root_joint='Root') # Or select the root joint in Maya and run: skel = build_atoms_skeleton_from_maya() # Exoirt the skeleton to a .atomsskel or .usd or .fbx file export_atoms_skeleton(skel, 'G:/my_character.atomsskel') print('[AtomsSkeletonBuilder] Done. Skeleton object:', skel)

Copyright © 2017, Toolchefs LTD.