Skip to content

Free Motion Capture for Everyone πŸ’€βœ¨

TypeScript

more or less basic FreeMoCap Blender addon, kinda!

jon matthis7a26747a3d7c
diff --git a/freemocap_blender_addon/freemocap_blender_addon/__init__.py b/freemocap_blender_addon/freemocap_blender_addon/__init__.py
index 8cde47fa..6f36379a 100644
--- a/freemocap_blender_addon/freemocap_blender_addon/__init__.py
+++ b/freemocap_blender_addon/freemocap_blender_addon/__init__.py
@@ -31,20 +31,11 @@ def register():
#define 'custom properties' - https://youtu.be/9fuFDHR-UkE
- bpy.types.Scene.fmc_session_config_path = bpy.props.StringProperty(
- name = 'FMC Session Config File Path',
+ bpy.types.Scene.fmc_session_path = bpy.props.StringProperty(
+ name = 'FMC Session Path',
subtype= 'FILE_PATH'
)
- bpy.types.Scene.omc_session_config_fname = bpy.props.StringProperty(
- name = 'FMC Session Config File',
- subtype= 'FILE_NAME'
- )
-
- bpy.types.Scene.fmc_session_id = bpy.props.StringProperty(
- name = 'FMC Session ID',
- )
-
auto_load.register()
print('registering FreeMoCap Addon')
diff --git a/freemocap_blender_addon/freemocap_blender_addon/build_armature_from_raw_mocap_data.py b/freemocap_blender_addon/freemocap_blender_addon/build_armature_from_raw_mocap_data.py
index 88588d5d..fd9871a6 100644
--- a/freemocap_blender_addon/freemocap_blender_addon/build_armature_from_raw_mocap_data.py
+++ b/freemocap_blender_addon/freemocap_blender_addon/build_armature_from_raw_mocap_data.py
@@ -3,8 +3,9 @@
import bpy
import numpy as np
-from ruamel.yaml import YAML
from pathlib import Path
+import math
+from mathutils import Vector
class FMC_OT_build_armature_from_raw_mocap_data(bpy.types.Operator): #setting the type as "FMC" for "FreeMoCap"
""" Load marker data via FMC yaml config and place empties in Blender scene """
@@ -12,176 +13,535 @@ class FMC_OT_build_armature_from_raw_mocap_data(bpy.types.Operator): #setting th
bl_label = "Build an armature from raw mocap data (in development)"
bl_options = {'REGISTER', 'UNDO'}
- bone_size: bpy.props.FloatProperty(
- name = 'Bone size',
- description = 'Size of the bones',
- default = .2,
- min = 0, soft_max =1,
- )
-
+
def execute(self, context):
- configPath = Path(context.scene.fmc_session_config_path)
- sessionPath = configPath.parent
-
- try:
- openpose_3d_data_path = sessionPath / 'DataArrays' / 'openPoseSkel_3d.npy'
- openpose_skel_fr_mar_xyz = np.load(str(openpose_3d_data_path))
- #convert to meters
- openpose_skel_fr_mar_xyz = openpose_skel_fr_mar_xyz/1000
- #names of markers
- openpose_skel_marker_names = ["Nose", "Neck", "RShoulder", "RElbow", "RWrist", "LShoulder",
- "LElbow", "LWrist", "MidHip", "RHip", "RKnee", "RAnkle", "LHip", "LKnee",
- "LAnkle", "REye", "LEye", "REar", "LEar", "LBigToe", "LSmallToe", "LHeel",
- "RBigToe", "RSmallToe", "RHeel"]
- openpose_bool = True
- except:
- openpose_bool = False
- print('No OpenPose Data Found')
-
- try:
- mediapipe_3d_data_path = sessionPath / 'DataArrays' / 'mediapipeSkel_3d.npy'
- mediapipe_skel_fr_mar_xyz = np.load(str(mediapipe_3d_data_path))
- #convert to meters
- mediapipe_skel_fr_mar_xyz = mediapipe_skel_fr_mar_xyz/1000
- #names of markers
- mediapipe_skel_marker_names = [ "nose",
-
- "left_eye_inner",
- "left_eye",
- "left_eye_outer",
-
- "right_eye_inner",
- "right_eye",
- "right_eye_outer",
-
- "left_ear",
- "right_ear",
-
- "mouth_left",
- "mouth_right",
-
- "left_shoulder",
- "right_shoulder",
-
- "left_elbow",
- "right_elbow",
-
- "left_wrist",
- "right_wrist",
-
- "left_pinky",
- "right_pinky",
-
- "left_index",
- "right_index",
-
- "left_thumb",
- "right_thumb",
-
- "left_hip",
- "right_hip",
-
- "left_knee",
- "right_knee",
-
- "left_ankle",
- "right_ankle",
-
- "left_heel",
- "right_heel",
-
- "left_foot_index",
- "right_foot_index",
- ]
- mediapipe_hand_marker_names = ["wrist",
- "thumb_cmc",
- "thumb_mcp",
- "thumb_ip",
- "thumb_tip",
-
- "index_finger_cmc",
- "index_finger_mcp",
- "index_finger_ip",
- "index_finger_tip",
-
- "middle_finger_cmc",
- "middle_finger_mcp",
- "middle_finger_ip",
- "middle_finger_tip",
-
- "ring_finger_cmc",
- "ring_finger_mcp",
- "ring_finger_ip",
- "ring_finger_tip",
-
- "pinky_cmc",
- "pinky_mcp",
- "pinky_ip",
- "pinky_tip",
-
-
- ]
- mediapipe_bool = True
- except:
- mediapipe_bool = False
- print('No mediapipe Data Found')
-
-
- startFr = 0
- numFrames = mediapipe_skel_fr_mar_xyz.shape[0]-1
+ session_path = Path(context.scene.fmc_session_path)
+
+ if not session_path.is_dir():
+ session_path = session_path.parent
- bpy.context.scene.frame_end = numFrames
+ input_npy = session_path / 'DataArrays' / 'mediaPipeSkel_3d.npy'
+ ##########
+ #### Begin Copy for fmc_blender
+ ##########
- #%% _______________________________________________________________________
- # Skreleton data!
- print('Loading raw motion capture data as bones!')
- face_iter = 0
+ #the path of the npy build data file
+ build_data = Path(__file__).parent.resolve() / "build_data.npy"
- # for marNum in range(len(mediapipe_skel_fr_mar_xyz[startFr,:,0])): #all dottos
- for marNum in range(len(mediapipe_skel_marker_names)): #only the body
-
- thisMarLoc = mediapipe_skel_fr_mar_xyz[startFr,marNum,:]
+ #3D array holding [[[x, y, z], [x, y, z]], [[x, y, z], [x, y, z]]]
+ arr = np.load(input_npy)
+
+ # Saved clean frame where all points are visible and not NANs
+ markers_list = np.load(build_data)
+
+ #a list containing empty objects
+ order_of_markers = []
+
+ #frame rate
+ bpy.context.scene.render.fps = 30
+
+ #dictionary corresponding to marker numbers and body parts
+ body_dict = {
+ 0:"head1",
+ 11:"shoulder_L",
+ 12:"shoulder_R",
+ 13:"elbow_L",
+ 14:"elbow_R",
+ 23:"hip_L",
+ 24:"hip_R",
+ 25:"knee_L",
+ 26:"knee_R",
+ 27:"ankle_L",
+ 28:"ankle_R",
+ 29:"heel_L",
+ 30:"heel_R",
+ 31:"toe_L",
+ 32:"toe_R" }
+
+ #-----------------------------------------------------------------------------------
+
+ # set project unit
+ bpy.context.scene.unit_settings.length_unit = 'METERS'
+ #iterate through arr and create an empty object at that location for each element
+ for index, col in enumerate(markers_list):
+ # parse string float value into floats, create Vector, set position to Vector
+
+ if math.isnan(col[0]):
+ col[0] = 0.0
+ if math.isnan(col[1]):
+ col[1] = 0.0
+ if math.isnan(col[2]):
+ col[2] = 0.0
+ coord = Vector(((float(col[0])*0.001), (float(col[2])*0.001), (float(col[1]))* -0.001))
+
+ #empties
+ bpy.ops.object.add(type='EMPTY', location=coord)
+ mt = bpy.context.active_object
+ mt.name = "mt_" + str(index)
+ if index in body_dict.keys():
+ mt.name += "_" + str(body_dict[index])
+ order_of_markers.append(mt)
+ #link empty to scene
+ bpy.context.scene.collection.objects.link( mt )
+ #set location
+ mt.location = coord
+ #set the display size of the empty
+ mt.empty_display_size = 0.02
- #these will define the size of teh body, hand, and face markers
- bms = self.bone_size
- hms = bms *.5
- fms = bms *.5
+ #--------------------------------------------------------------
+ #Virtual Markers!
+
+ # marker relationships:
+
+ # - "weight": the weighted average of multiple markers. the virtual_markers[x] contains the
+ #list of markers that affect this virtual one. the weights[x] contains their corresponding weights in order.
+
+ bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
+
+ #Create virtual marker where parameters are the name of the marker, the markers that affect its position, and each of their weights.
+ def create_marker_weight(name, markers, weighted):
+ center = Vector((0, 0, 0))
+ weight_iter = 0
+ for x in markers:
+ center += x.location*weighted[weight_iter]
+ weight_iter += 1
+ coord = Vector((float(center[0]), float(center[1]), float(center[2])))
+ bpy.ops.object.add(type='EMPTY', location=coord)
+ mt = bpy.context.active_object
+ mt.name = name
+ bpy.context.scene.collection.objects.link( mt )
+ mt.location = coord
+ mt.empty_display_size = 0.02
+ virtual_markers.append(mt)
+ #Keeping track of virtual marker info using arrays, where each marker is an index in each array
+ v_relationship = []
+ virtual_markers = []
+ surrounding_markers = []
+ weights = []
+
+ #updates data and creates virtual marker
+ def update_virtual_data(relationship, surrounding, vweights, vname):
+ v_relationship.append(relationship)
+ surrounding_markers.append(surrounding)
+ weights.append(vweights)
+ create_marker_weight(vname, surrounding, vweights)
+
+ #-----------------------------------------------------------------
+ #Define relationships and create virtual markers
+
+ #Neck Base: Halfway between order_of_markers[12] shoulder_L and order_of_markers[12] shoulder_R
+ l0 = [order_of_markers[12], order_of_markers[11]]
+ w0 = [0.5, 0.5]
+ update_virtual_data("weight", l0, w0, "m_neck")
+
+ #Waist Base: Halfway between order_of_markers[24] and order_of_markers[23]
+ l0 = [order_of_markers[24], order_of_markers[23]]
+ w0 = [0.5, 0.5]
+ update_virtual_data("weight", l0, w0, "m_neck")
+
+ #Update the location of virtual markers on each frame
+ def update_virtual_marker(index):
+ if(v_relationship[index] == "weight"):
+ center = Vector((0, 0, 0))
+ weight_iter = 0
+ for x in surrounding_markers[index]:
+ center += x.location*weights[index][weight_iter]
+ weight_iter += 1
+ coord = Vector((float(center[0]), float(center[1]), float(center[2])))
+ virtual_markers[index].location = coord
+ #-----------------------------------------------------------------------------------
+ # Bones!
+
+ #adds child bone given corresponding parent and empty
+ #bone tail will appear at the location of empty
+ def add_child_bone(bone_name, empty1, empty2):
+ #Set armature selected
+ armature_data.select_set(state=True)
+ #Set edit mode
+ bpy.ops.object.mode_set(mode='EDIT', toggle=False)
+ #Create a new bone
+ new_bone = armature_data.data.edit_bones.new(bone_name)
+ #Set bone's size
+ new_bone.head = (0,0,0)
+ new_bone.tail = (0,0.1,0)
+ #Set bone's location to wheel
+ new_bone.matrix = empty2.matrix_world
+ #set location of bone head
+ new_bone.head = empty1.location
+ #set location of bone tail
+ new_bone.tail = empty2.location
+ return new_bone
+
+ #Create armature object
+ armature = bpy.data.armatures.new('Armature')
+ armature_object = bpy.data.objects.new('Armature', armature)
+ #Link armature object to our scene
+ bpy.context.collection.objects.link(armature_object)
+ #Make armature variable
+ armature_data = bpy.data.objects[armature_object.name]
+ #Set armature active
+ bpy.context.view_layer.objects.active = armature_data
+ #Set armature selected
+ armature_data.select_set(state=True)
+ #Set edit mode
+ bpy.ops.object.mode_set(mode='EDIT', toggle=False)
+ #Set bones in front and show axis
+ armature_data.show_in_front = True
+ #True to show axis orientation of bones and false to hide it
+ armature_data.data.show_axes = False
- bpy.ops.object.armature_add(align='WORLD', location=thisMarLoc, scale=(bms, bms, bms))
- this_bone = context.active_object
+ #get armature object
+ def get_armature():
+ for ob in bpy.data.objects:
+ if ob.type == 'ARMATURE':
+ armature = ob
+ break
+ return armature
+ armature = get_armature()
+
+ #a list of tuples where each element represents the info for one bone, and
+ #the tuple contains the bone name, the marker of the head, and the marker of the tail
+ list_of_bones_order = [('upper_arm_L', order_of_markers[11], order_of_markers[13]),
+ ('upper_arm_R', order_of_markers[12], order_of_markers[14]),
+ ('lower_arm_L', order_of_markers[13], order_of_markers[15]),
+ ('lower_arm_R', order_of_markers[14], order_of_markers[16]),
+ ('upper_leg_L', order_of_markers[23], order_of_markers[25]),
+ ('upper_leg_R', order_of_markers[24], order_of_markers[26]),
+ ('lower_leg_L', order_of_markers[25], order_of_markers[27]),
+ ('lower_leg_R', order_of_markers[26], order_of_markers[28]),
+ ('heel_L', order_of_markers[27], order_of_markers[29]),
+ ('heel_R', order_of_markers[28], order_of_markers[30]),
+ ('foot_L', order_of_markers[29], order_of_markers[31]),
+ ('foot_R', order_of_markers[30], order_of_markers[32]),
+ ('neck', order_of_markers[0], virtual_markers[0]),
+ ('eye_L', order_of_markers[0], order_of_markers[2]),
+ ('ear_L', order_of_markers[2], order_of_markers[7]),
+ ('eye_R', order_of_markers[0], order_of_markers[5]),
+ ('ear_R', order_of_markers[5], order_of_markers[8]),
+ ('shoulder_L', virtual_markers[0], order_of_markers[11]),
+ ('shoulder_R', virtual_markers[0], order_of_markers[12]),
+ ('torso', virtual_markers[1], virtual_markers[0]),
+ ('hip_L', virtual_markers[1], order_of_markers[23]),
+ ('hip_R', virtual_markers[1], order_of_markers[24]),
+ ]
+
+ #based on marker # from order_of_markers array add bones for hands:
+ left_hand_offset = 54
+ left_hand = [('handL0', order_of_markers[0+left_hand_offset], order_of_markers[1+left_hand_offset]),
+ ('handL1', order_of_markers[1+left_hand_offset], order_of_markers[2+left_hand_offset]),
+ ('handL2', order_of_markers[2+left_hand_offset], order_of_markers[3+left_hand_offset]),
+ ('handL3', order_of_markers[3+left_hand_offset], order_of_markers[4+left_hand_offset]),
+ ('handL5', order_of_markers[1+left_hand_offset], order_of_markers[5+left_hand_offset]),
+ ('handL6', order_of_markers[5+left_hand_offset], order_of_markers[6+left_hand_offset]),
+ ('handL7', order_of_markers[6+left_hand_offset], order_of_markers[7+left_hand_offset]),
+ ('handL8', order_of_markers[7+left_hand_offset], order_of_markers[8+left_hand_offset]),
+ ('handL9', order_of_markers[5+left_hand_offset], order_of_markers[9+left_hand_offset]),
+ ('handL10', order_of_markers[9+left_hand_offset], order_of_markers[10+left_hand_offset]),
+ ('handL11', order_of_markers[10+left_hand_offset], order_of_markers[11+left_hand_offset]),
+ ('handL12', order_of_markers[11+left_hand_offset], order_of_markers[12+left_hand_offset]),
+ ('handL13', order_of_markers[9+left_hand_offset], order_of_markers[13+left_hand_offset]),
+ ('handL14', order_of_markers[13+left_hand_offset], order_of_markers[14+left_hand_offset]),
+ ('handL15', order_of_markers[14+left_hand_offset], order_of_markers[15+left_hand_offset]),
+ ('handL16', order_of_markers[15+left_hand_offset], order_of_markers[16+left_hand_offset]),
+ ('handL17', order_of_markers[13+left_hand_offset], order_of_markers[0+left_hand_offset]),
+ ('handL18', order_of_markers[0+left_hand_offset], order_of_markers[17+left_hand_offset]),
+ ('handL19', order_of_markers[17+left_hand_offset], order_of_markers[18+left_hand_offset]),
+ ('handL20', order_of_markers[18+left_hand_offset], order_of_markers[19+left_hand_offset]),
+ ('wristL', order_of_markers[15], order_of_markers[0+left_hand_offset]),
+ ('handL21', order_of_markers[19+left_hand_offset], order_of_markers[20+left_hand_offset]),]
- if marNum < len(mediapipe_skel_marker_names) : #body
- this_bone.name = mediapipe_skel_marker_names[marNum]
- this_bone.scale = (bms, bms, bms)
+ right_hand_offset = 33
+
+ right_hand = [('handR0', order_of_markers[18], order_of_markers[1+right_hand_offset]),
+ ('handR1', order_of_markers[1+right_hand_offset], order_of_markers[2+right_hand_offset]),
+ ('handR2', order_of_markers[2+right_hand_offset], order_of_markers[3+right_hand_offset]),
+ ('handR3', order_of_markers[3+right_hand_offset], order_of_markers[4+right_hand_offset]),
+ ('handR5', order_of_markers[1+right_hand_offset], order_of_markers[5+right_hand_offset]),
+ ('handR6', order_of_markers[5+right_hand_offset], order_of_markers[6+right_hand_offset]),
+ ('handR7', order_of_markers[6+right_hand_offset], order_of_markers[7+right_hand_offset]),
+ ('handR8', order_of_markers[7+right_hand_offset], order_of_markers[8+right_hand_offset]),
+ ('handR9', order_of_markers[5+right_hand_offset], order_of_markers[9+right_hand_offset]),
+ ('handR10', order_of_markers[9+right_hand_offset], order_of_markers[10+right_hand_offset]),
+ ('handR11', order_of_markers[10+right_hand_offset], order_of_markers[11+right_hand_offset]),
+ ('handR12', order_of_markers[11+right_hand_offset], order_of_markers[12+right_hand_offset]),
+ ('handR13', order_of_markers[9+right_hand_offset], order_of_markers[13+right_hand_offset]),
+ ('handR14', order_of_markers[13+right_hand_offset], order_of_markers[14+right_hand_offset]),
+ ('handR15', order_of_markers[14+right_hand_offset], order_of_markers[15+right_hand_offset]),
+ ('handR16', order_of_markers[15+right_hand_offset], order_of_markers[16+right_hand_offset]),
+ ('handR17', order_of_markers[18], order_of_markers[13+right_hand_offset]),
+ ('handR18', order_of_markers[18], order_of_markers[17+right_hand_offset]),
+ ('handR19', order_of_markers[17+right_hand_offset], order_of_markers[18+right_hand_offset]),
+ ('handR20', order_of_markers[18+right_hand_offset], order_of_markers[19+right_hand_offset]),
+ ('wristR', order_of_markers[16], order_of_markers[18]),
+ ('handR21', order_of_markers[19+right_hand_offset], order_of_markers[20+right_hand_offset]),]
+
+ #helper to create armature from list of tuples
+ def tuple_to_armature(bones):
+ for bone_name, bone_head, bone_tail in bones:
+ add_child_bone(bone_name, bone_head, bone_tail)
- elif marNum < len(mediapipe_skel_marker_names) + 2*len(mediapipe_hand_marker_names): #hands
+ #Set armature selected
+ armature_data.select_set(state=True)
+ #Set edit mode
+ bpy.ops.object.mode_set(mode='EDIT', toggle=False)
- if marNum < len(mediapipe_skel_marker_names) +len(mediapipe_hand_marker_names):
- this_hand_prefix = 'right_hand_'
- this_hand_prefix = 'right_hand_'
- marker_num_offset = len(mediapipe_skel_marker_names)
- else:
- this_hand_prefix = 'left_hand_'
- marker_num_offset = len(mediapipe_skel_marker_names) + len(mediapipe_hand_marker_names)
-
- this_bone.name = this_hand_prefix + mediapipe_hand_marker_names[marNum-marker_num_offset]
-
- this_bone.scale=(hms, hms, hms)
-
- else: #face
- this_bone.name = 'face_'+str(face_iter).zfill(4)
- face_iter += 1
- this_bone.scale=(fms, fms, fms)
-
- #loop through each frame (after the first [0th] frame) to set the keyframes for this marker
- for fr in range(1, numFrames):
- this_bone.location = mediapipe_skel_fr_mar_xyz[fr,marNum,:]
- this_bone.keyframe_insert(data_path="location", frame=fr)
- print('loaded marker: '+ this_bone.name)
+ #create all bones for skeleton body and hands
+ tuple_to_armature(list_of_bones_order)
+ tuple_to_armature(right_hand)
+ tuple_to_armature(left_hand)
+
+ #parent heads and tails to empties
+ #use bone constraints
+ def parent_to_empties(bone_name, head, tail):
+ #enter pose mode
+ bpy.ops.object.posemode_toggle()
+ marker = armature.data.bones[bone_name]
+ #Set marker selected
+ marker.select = True
+ #Set marker active
+ bpy.context.object.data.bones.active = marker
+ bone = bpy.context.object.pose.bones[bone_name]
+ #Copy Location Pose constraint: makes the bone's head follow the given empty
+ bpy.ops.pose.constraint_add(type='COPY_LOCATION')
+ bone.constraints["Copy Location"].target = head
+ #Stretch To Pose constraint: makes the bone's tail follow the given empty
+ #stretches the bones to reach the tail to that empty so head location is not affected
+ bpy.ops.pose.constraint_add(type='STRETCH_TO')
+ bone.constraints["Stretch To"].target = tail
+ #exit pose mode
+ bpy.ops.object.posemode_toggle()
- print('Done!')
+ #set parents of heads and tails for each bone
+ def tuple_to_parented(bones):
+ for bone_name, bone_head, bone_tail in bones:
+ parent_to_empties(bone_name, bone_head, bone_tail)
+
+ tuple_to_parented(list_of_bones_order)
+ tuple_to_parented(right_hand)
+ tuple_to_parented(left_hand)
+
+ #-----------------------------------------------------------------------------------
+ # Animate!
+ #find number of frames in animation
+ num_frames = len(arr)
+
+ #change start frame of animation
+ bpy.context.scene.frame_start = 1
+ #change end frame of animation
+ bpy.context.scene.frame_end = num_frames - 1
+
+ #create a new handler to change empty positions every frame
+ def my_handler(scene):
+ bpy.ops.object.mode_set(mode='OBJECT')
+ #keep track of current_marker
+ current_marker = 0
+ #find the current frame number
+ frame = scene.frame_current
+ #get the list of marker points from the current frame
+ markers_list = arr[frame]
+ #iterate through list of markers in this frame
+ for col in markers_list:
+ frame = scene.frame_current
+ if math.isnan(col[0]):
+ col[0] = 0.0
+ if math.isnan(col[1]):
+ col[1] = 0.0
+ if math.isnan(col[2]):
+ col[2] = 0.0
+ coord = Vector(((float(col[0])*0.001), (float(col[2])*0.001), (float(col[1]))* -0.001))
+ if len(order_of_markers) > 0:
+ empty = order_of_markers[current_marker]
+ empty.location = coord
+ current_marker += 1
+ for index in range(len(virtual_markers)):
+ update_virtual_marker(index)
+
+
+ #keyframe bones
+ #Goes through each bone
+ for editBone in get_armature().data.edit_bones:
+ boneName = editBone.name
+ poseBone = arm.pose.bones[boneName]
+ poseBone.keyframe_insert('rotation_euler', frame=scene.frame_current)
+ poseBone.keyframe_insert('location', frame=scene.frame_current)
+ poseBone.keyframe_insert('scale', frame=scene.frame_current)
+
+ #-----------------------------------------------------------------------------------
+ #script to create a mesh of the armature
+ def CreateMesh():
+ obj = get_armature()
+
+ if obj == None:
+ print( "No selection" )
+ elif obj.type != 'ARMATURE':
+ print( "Armature expected" )
+ else:
+ return processArmature( bpy.context, obj )
+
+ #Use armature to create base object
+ def armToMesh( arm ):
+ name = arm.name + "_mesh"
+ dataMesh = bpy.data.meshes.new( name + "Data" )
+ mesh = bpy.data.objects.new( name, dataMesh )
+ mesh.matrix_world = arm.matrix_world.copy()
+ return mesh
+
+ #Make vertices and faces
+ def boneGeometry( l1, l2, x, z, baseSize, l1Size, l2Size, base ):
+ x1 = x * baseSize * l1Size * 0.8
+ z1 = z * baseSize * l2Size * 0.8
+
+ x2 = Vector( (0, 0, 0) )
+ z2 = Vector( (0, 0, 0) )
+
+ verts = [
+ l1 - x1 + z1,
+ l1 + x1 + z1,
+ l1 - x1 - z1,
+ l1 + x1 - z1,
+ l2 - x2 + z2,
+ l2 + x2 + z2,
+ l2 - x2 - z2,
+ l2 + x2 - z2
+ ]
+
+ faces = [
+ (base+3, base+1, base+0, base+2),
+ (base+6, base+4, base+5, base+7),
+ (base+4, base+0, base+1, base+5),
+ (base+7, base+3, base+2, base+6),
+ (base+5, base+1, base+3, base+7),
+ (base+6, base+2, base+0, base+4)
+ ]
+
+ return verts, faces
+
+ #Process the armature, goes through its bones and creates the mesh
+ def processArmature(context, arm, genVertexGroups = True):
+ print("processing armature {0}".format(arm.name))
+
+ #Creates the mesh object
+ meshObj = armToMesh( arm )
+ context.collection.objects.link( meshObj )
+
+ verts = []
+ edges = []
+ faces = []
+ vertexGroups = {}
+
+ bpy.ops.object.mode_set(mode='EDIT')
+
+ try:
+ #Goes through each bone
+ for editBone in get_armature().data.edit_bones:
+ boneName = editBone.name
+ if boneName == "":
+ editBone.name = "bone"
+ boneName = "bone"
+ poseBone = arm.pose.bones[boneName]
+
+ #Gets edit bone informations
+ editBoneHead = editBone.head
+ editBoneTail = editBone.tail
+ editBoneVector = editBoneTail - editBoneHead
+ editBoneSize = editBoneVector.dot( editBoneVector )
+ editBoneRoll = editBone.roll
+ editBoneX = editBone.x_axis
+ editBoneZ = editBone.z_axis
+ editBoneHeadRadius = editBone.head_radius
+ editBoneTailRadius = editBone.tail_radius
+
+ #Creates the mesh data for the bone
+ baseIndex = len(verts)
+ baseSize = math.sqrt( editBoneSize )
+ newVerts, newFaces = boneGeometry( editBoneHead, editBoneTail, editBoneX, editBoneZ, baseSize, editBoneHeadRadius, editBoneTailRadius, baseIndex )
+ verts.extend( newVerts )
+ faces.extend( newFaces )
+
+ #Creates the weights for the vertex groups
+ vertexGroups[boneName] = [(x, 1.0) for x in range(baseIndex, len(verts))]
+ #Assigns the geometry to the mesh
+ meshObj.data.from_pydata(verts, edges, faces)
+
+ except:
+ bpy.ops.object.mode_set(mode='OBJECT')
+ else:
+ bpy.ops.object.mode_set(mode='OBJECT')
+ #Assigns the vertex groups
+ if genVertexGroups:
+ for name1, vertexGroup in vertexGroups.items():
+ groupObject = meshObj.vertex_groups.new(name = name1)
+ for (index, weight) in vertexGroup:
+ groupObject.add([index], weight, 'REPLACE')
+
+ #Creates the armature modifier
+ modifier = meshObj.modifiers.new('ArmatureMod', 'ARMATURE')
+ modifier.object = arm
+ modifier.use_bone_envelopes = False
+ modifier.use_vertex_groups = True
+
+ meshObj.data.update()
+
+ return meshObj
+
+ mesh_obob = CreateMesh()
+
+ #-----------------------------------------------------------------------------------
+ # Clean up the mesh by removing duplicate vertices, make sure all faces are quads, etc
+
+ checked = set()
+ for selected_object in bpy.data.objects:
+ if selected_object.type != 'MESH':
+ continue
+ meshdata = selected_object.data
+ if meshdata in checked:
+ continue
+ else:
+ checked.add(meshdata)
+ bpy.context.view_layer.objects.active = selected_object
+ bpy.ops.object.editmode_toggle()
+ bpy.ops.mesh.select_all(action='SELECT')
+ bpy.ops.mesh.remove_doubles()
+ bpy.ops.mesh.tris_convert_to_quads()
+ bpy.ops.mesh.normals_make_consistent()
+ bpy.ops.object.editmode_toggle()
+ #Set armature active
+ bpy.context.view_layer.objects.active = armature_data
+ #Set armature selected
+ armature_data.select_set(state=True)
+ #-----------------------------------------------------------------------------------
+ #function to register custom handler
+ bpy.app.handlers.frame_change_post.clear()
+ def register():
+ bpy.app.handlers.frame_change_post.append(my_handler)
+
+ def unregister():
+ bpy.app.handlers.frame_change_post.remove(my_handler)
+
+ register()
+
+ scene = bpy.context.scene
+
+ bpy.ops.object.mode_set(mode='OBJECT')
+
+ #set keyframes for whole animation
+ for frame in range(scene.frame_start, scene.frame_end):
+ scene.frame_set(frame)
+
+ #Select objects to export
+ col = bpy.data.collections.get("Collection")
+ if col:
+ for obj in col.objects:
+ if "Armature" == obj.name:
+ obj.select_set(True)
+
+
+ ##########
+ #### end Copy for fmc_blender ^^^
+ ##########
+
return{'FINISHED'}
diff --git a/freemocap_blender_addon/freemocap_blender_addon/build_data.npy b/freemocap_blender_addon/freemocap_blender_addon/build_data.npy
new file mode 100644
index 00000000..5b00b0b3
Binary files /dev/null and b/freemocap_blender_addon/freemocap_blender_addon/build_data.npy differ
diff --git a/freemocap_blender_addon/freemocap_blender_addon/import_freemocap_config.py b/freemocap_blender_addon/freemocap_blender_addon/import_freemocap_config.py
index 5fd5a5ec..99625309 100644
--- a/freemocap_blender_addon/freemocap_blender_addon/import_freemocap_config.py
+++ b/freemocap_blender_addon/freemocap_blender_addon/import_freemocap_config.py
@@ -1,56 +1,26 @@
-import pathlib
-import bpy
+# from pathlib import Path
+# import bpy
+
+# def get_session_path(scene) -> Path:
+# abspath = bpy.path.abspath(scene.fmc_session_path) #absolute path to this omc session's data
+# pathStringParts = abspath.split('\\') #split the absolute path at the \\'s
+# scene.fmc_session_id = pathStringParts[-2] #the 2nd to last element is the 'sessionID'
+# return Path(abspath)
+
+# class IMPORT_SCENE_OT_session_config_load(bpy.types.Operator):
+# bl_idname = 'fmc.load_session_config'
+# bl_label = 'Load Session Config.yaml'
+
+# def execute(self, context):
+# #find congif.yaml file for this session
+# import_path = get_session_path(context.scene)
+
+# iter = -1
+# for import_fpath in import_path.glob('*_config.yaml'):
+# iter +=1
+# assert iter < 1, 'Found Multiple *_config.yaml files, and thats not supposed to happen!'
+# bpy.types.Scene.fmc_session_path = import_fpath #path to the config gile
+# bpy.types.Scene.fmc_session_ID = import_fpath.name #name of the session
+# return{'FINISHED'}
-def mass_import_path(scene) -> pathlib.Path:
- abspath = bpy.path.abspath(scene.fmc_session_path) #absolute path to this omc session's data
- pathStringParts = abspath.split('\\') #split the absolute path at the \\'s
- scene.fmc_session_id = pathStringParts[-2] #the 2nd to last element is the 'sessionID'
- return pathlib.Path(abspath)
-
-class IMPORT_SCENE_OT_session_config_load(bpy.types.Operator):
- bl_idname = 'fmc.load_session_config'
- bl_label = 'Load Session Config.yaml'
-
- def execute(self, context):
- #find congif.yaml file for this session
- import_path = mass_import_path(context.scene)
-
- iter = -1
- for import_fpath in import_path.glob('*_config.yaml'):
- iter +=1
- assert iter < 1, 'Found Multiple *_config.yaml files, and thats not supposed to happen!'
- bpy.types.Scene.fmc_session_config_path = import_fpath #path to the config gile
- bpy.types.Scene.fmc_session_config_fname = import_fpath.name #name of the config file
- return{'FINISHED'}
-
-class IMPORT_SCENE_OT_obj_reload(bpy.types.Operator):
- bl_idname = 'fmc.obj_reload'
- bl_label = 'ReLoad Mass-imported OBJs'
-
- def execute(self, context):
- active_object = context.object
-
- #store wht we ant to remember
- fmc_session_config_fname = active_object.fmc_session_config_fname
- matrix_world = active_object.matrix_world.copy()
-
- #remove obj from scene
- for collection in list(active_object.users_collection):
- collection.objects.unlink(active_object)
-
- if active_object.users == 0:
- bpy.data.objects.remove(active_object)
- del active_object
-
- #load obj file
- import_path = mass_import_path(context.scene)
- import_fpath = import_path / omc_session_config_fname
- bpy.ops.import_scene.obj(filepath=str(import_fpath))
-
- #restore what we remembered
- for imported_ob in context.selected_objects:
- imported_ob.omc_session_config_fname = import_fpath.name
- imported_ob.matrix_world = matrix_world
-
- return('FINSHED')
diff --git a/freemocap_blender_addon/freemocap_blender_addon/load_marker_empties.py b/freemocap_blender_addon/freemocap_blender_addon/load_marker_empties.py
index 4f738e11..44f82d50 100644
--- a/freemocap_blender_addon/freemocap_blender_addon/load_marker_empties.py
+++ b/freemocap_blender_addon/freemocap_blender_addon/load_marker_empties.py
@@ -23,7 +23,7 @@ class FMC_OT_loadMarkerEmpties(bpy.types.Operator): #setting the type as "FMC" f
)
def execute(self, context):
- configPath = Path(context.scene.fmc_session_config_path)
+ configPath = Path(context.scene.fmc_session_path)
sessionPath = configPath.parent
try:
diff --git a/freemocap_blender_addon/freemocap_blender_addon/load_nsynched_videos.py b/freemocap_blender_addon/freemocap_blender_addon/load_nsynched_videos.py
index 4ef1bb19..37f0ae03 100644
--- a/freemocap_blender_addon/freemocap_blender_addon/load_nsynched_videos.py
+++ b/freemocap_blender_addon/freemocap_blender_addon/load_nsynched_videos.py
@@ -1,5 +1,6 @@
import bpy
-from ruamel.yaml import YAML
+import pickle
+
from pathlib import Path
class FMC_OT_loadVideos(bpy.types.Operator):
@@ -9,21 +10,45 @@ class FMC_OT_loadVideos(bpy.types.Operator):
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
- configPath = Path(context.scene.fmc_session_config_path)
- config_yaml = YAML().load(configPath)
- sessionPath = Path(config_yaml['Paths']['sessionPath'])
- vidFolderPath = sessionPath / 'SyncedVideos'
+ session_path = Path(context.scene.fmc_session_path)
+
+ if not session_path.is_dir():
+ session_path = session_path.parent
+
+
+ camera_calibration_pickle_path = session_path / (session_path.name + '_calibration.pickle')
+
+ vidFolderPath = session_path / 'SyncedVideos'
+
+
+
+ with open(camera_calibration_pickle_path, 'rb') as camera_calib_pickle:
+ camera_calibration_dict = pickle.load(camera_calib_pickle)
- # bpy.ops.import_image.to_plane(files=[{"name":"test6_01_21a_synced_Cam1.mp4"}], directory="C:\\Users\\jonma\\Dropbox\\GitKrakenRepos\\OpenMoCap\\Data\\test6_01_21a\\SyncedVideos\\", compositing_nodes=True, relative=False)
- iter = 0
- for thisVidPath in vidFolderPath.glob('*.mp4'):
- iter+=1
+ camera_translations = []
+ camera_rotations = []
+ for this_cam_calib_info in camera_calibration_dict:
+ camera_translations.append(this_cam_calib_info['translation'])
+ camera_rotations.append(this_cam_calib_info['rotation'])
+
+
+
+ for vid_number, thisVidPath, in enumerate(vidFolderPath.glob('*.mp4')):
+
+ this_camera_tx = camera_translations[vid_number][0]/1000 #convert to meters from millimeters
+ this_camera_ty = camera_translations[vid_number][1]/1000
+ this_camera_tz = camera_translations[vid_number][2]/1000
+
+ this_camera_rx = camera_rotations[vid_number][0]
+ this_camera_ry = camera_rotations[vid_number][1]
+ this_camera_rz = camera_rotations[vid_number][2]
+
#create camera object on Z-axis pointing down at origin
bpy.ops.object.camera_add(align='WORLD')
thisCam = context.active_object
- thisCam.location = (iter*2,0,3)
- thisCam.rotation_euler = (0,0,0)
- thisCam.scale = (5, 5, 5)
+ thisCam.location = (this_camera_tx,this_camera_ty,this_camera_tz)
+ thisCam.rotation_euler = (this_camera_rx, this_camera_ry, this_camera_rz)
+ # thisCam.scale = (5, 5, 5)
thisCam.name = 'Cam' + str(iter)
# use 'images as planes' add on to load in the video files as planes
@@ -34,5 +59,4 @@ class FMC_OT_loadVideos(bpy.types.Operator):
# context.active_object.location = (iter,iter,iter) #bump this image_plane over a bit so they don't over lap
- f=9
return {'FINISHED'}
\ No newline at end of file
diff --git a/freemocap_blender_addon/freemocap_blender_addon/load_raw_mocap_data_as_bones.py b/freemocap_blender_addon/freemocap_blender_addon/load_raw_mocap_data_as_bones.py
index ada6ea9b..56a7da15 100644
--- a/freemocap_blender_addon/freemocap_blender_addon/load_raw_mocap_data_as_bones.py
+++ b/freemocap_blender_addon/freemocap_blender_addon/load_raw_mocap_data_as_bones.py
@@ -1,6 +1,5 @@
import bpy
import numpy as np
-from ruamel.yaml import YAML
from pathlib import Path
class FMC_OT_load_raw_mocap_data_as_bones(bpy.types.Operator): #setting the type as "FMC" for "FreeMoCap"
@@ -17,7 +16,7 @@ class FMC_OT_load_raw_mocap_data_as_bones(bpy.types.Operator): #setting the type
)
def execute(self, context):
- configPath = Path(context.scene.fmc_session_config_path)
+ configPath = Path(context.scene.fmc_session_path)
sessionPath = configPath.parent
try:
diff --git a/freemocap_blender_addon/freemocap_blender_addon/ui_view3d_panel.py b/freemocap_blender_addon/freemocap_blender_addon/ui_view3d_panel.py
index b69c3cce..9ea6c19b 100644
--- a/freemocap_blender_addon/freemocap_blender_addon/ui_view3d_panel.py
+++ b/freemocap_blender_addon/freemocap_blender_addon/ui_view3d_panel.py
@@ -13,18 +13,21 @@ class VIEW3D_PT_freemocap(bpy.types.Panel):
#######################################################
# UI_COLUMN_0 - The part of the panel where you specify the Session Folder
- ui_column_0 = layout.column(align=True)
- ui_column_0.prop(context.scene, 'fmc_session_config_path' )
+ ui_set_session_path = layout.column(align=True)
+ ui_set_session_path.prop(context.scene, 'fmc_session_path' )
- if context.scene.fmc_session_config_path : #once you set the config path
- configPath = Path(context.scene.fmc_session_config_path)
- ui_column_0.label(text=f'Session Config File: {configPath.name}')
+ if context.scene.fmc_session_path : #once you set the config path
+ session_path = Path(context.scene.fmc_session_path)
+ if session_path.is_dir(): #JSM NOTE - This is kinda sloppy, but I don't know how to alter the actual session path variable. I want there to be a way to enforce that the 'session_path' value points to the whole session folder, NOT a file within that folder
+ ui_set_session_path.label(text=f'Session Path: {str(session_path)}')
+ else:
+ ui_set_session_path.label(text=f'Session Path: {str(session_path.parent)}')
else:
- ui_column_0.label(text='-No Session Config Loaded-')
- ui_column_0.label(text='_______')
+ ui_set_session_path.label(text='-No Session Config Loaded-')
+ ui_set_session_path.label(text='_______')
#######################################################
- # UI_COLUMN_1 # The part of the panel where you load in the marker data
+
ui_column_1 = self.layout.column(align=True)
ui_column_1.operator('fmc.load_marker_empties',
@@ -33,7 +36,7 @@ class VIEW3D_PT_freemocap(bpy.types.Panel):
#######################################################
- # UI_COLUMN_1 # The part of the panel where you load in the marker data
+
ui_as_bones_button = self.layout.column(align=True)
ui_as_bones_button.operator('fmc.load_raw_mocap_data_as_bones',
@@ -41,11 +44,21 @@ class VIEW3D_PT_freemocap(bpy.types.Panel):
icon = 'GROUP_BONE')
#######################################################
- # UI_COLUMN_2 # The part of the panel where you load in the videos
+
+ ui_build_armature= self.layout.column(align=True)
+
+ ui_build_armature.operator('fmc.build_armature_from_raw_mocap_data',
+ text='build armature from raw mocap data',
+ icon = 'ARMATURE_DATA')
+
+
+
+
+ #######################################################
ui_column_2= self.layout.column(align=True)
ui_column_2.operator('fmc.load_nsynced_videos',
- text='Load nSynced Videos!',
+ text='Load nSynced Videos!!',
icon = 'CAMERA_DATA')
# properties_0 = ui_column_2.operator('fmc.load_session_data',
diff --git a/freemocap_blender_addon/install_dependencies_to_blenders_python.py b/freemocap_blender_addon/install_dependencies_to_blenders_python.py
new file mode 100644
index 00000000..633b8aa6
--- /dev/null
+++ b/freemocap_blender_addon/install_dependencies_to_blenders_python.py
@@ -0,0 +1,14 @@
+import subprocess
+import sys
+import os
+
+# path to python.exe
+python_exe = os.path.join(sys.prefix, 'bin', 'python.exe')
+
+# upgrade pip
+subprocess.call([python_exe, "-m", "ensurepip"])
+subprocess.call([python_exe, "-m", "pip", "install", "--upgrade", "pip"])
+
+# install required packages
+subprocess.call([python_exe, "-m", "pip", "install", "rich"])
+subprocess.call([python_exe, "-m", "pip", "install", "toml"])
\ No newline at end of file