deformer_nodes.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. from .utilities.node_common import *
  2. from .xForm_nodes import xFormGeometryObject, xFormObjectInstance
  3. from .misc_nodes import InputExistingGeometryObject
  4. from .base_definitions import MantisNode
  5. from .mantis_dataclasses import MantisSocketTemplate
  6. from .utilities.utilities import (prRed, prGreen, prPurple, prWhite, prOrange,
  7. wrapRed, wrapGreen, wrapPurple, wrapWhite,
  8. wrapOrange,)
  9. from .deformer_socket_templates import *
  10. from bpy.types import NodeTree
  11. def TellClasses():
  12. return [
  13. DeformerArmature,
  14. DeformerHook,
  15. DeformerMorphTarget,
  16. DeformerMorphTargetDeform,
  17. DeformerSurfaceDeform,
  18. DeformerMeshDeform,
  19. DeformerLatticeDeform,
  20. DeformerSmoothCorrectiveDeform,
  21. ]
  22. # object instance probably can't use the deformer but it doesn't hurt to try.
  23. deformable_types= (xFormGeometryObject, InputExistingGeometryObject, xFormObjectInstance)
  24. # This is used by Armature Deformer for finding xForm to copy skin weights from
  25. def trace_xForm_back(mantis_node, socket):
  26. if (trace := trace_single_line(mantis_node, socket)[0] ) :
  27. for i in range(len(trace)): # have to look in reverse, actually
  28. if ( isinstance(trace[ i ], deformable_types ) ):
  29. return trace[ i ].bGetObject()
  30. raise GraphError(wrapRed(f"No other object found for {mantis_node}."))
  31. class MantisDeformerNode(MantisNode):
  32. node_type = 'LINK'
  33. __slots__ = ()
  34. passes=frozenset({'bRelationship', 'bFinalize',})
  35. def __init__(self, signature : tuple,
  36. base_tree : NodeTree,
  37. socket_templates : list[MantisSocketTemplate]=[]):
  38. super().__init__(signature, base_tree, socket_templates,
  39. additional_parameters= {"Name":None})
  40. self.prepared = True
  41. self.bObject=[]
  42. # almost all of the deformer nodes need this
  43. if 'Deformer' in self.inputs.keys() and 'Deformer' in self.outputs.keys():
  44. self.set_traverse( [('Deformer', 'Deformer')])
  45. # we need evaluate_input to have the same behaviour as links.
  46. def evaluate_input(self, input_name, index=0):
  47. if (input_name in ['Target', 'Object', 'Hook Target']):
  48. socket = self.inputs.get(input_name)
  49. if socket.is_linked:
  50. return socket.links[0].from_node
  51. return None
  52. else:
  53. return super().evaluate_input(input_name, index)
  54. def GetxForm(mantis_node, output_name="Deformer"):
  55. break_condition= lambda node : node.__class__ in deformable_types
  56. xforms = trace_line_up_branching(mantis_node, output_name, break_condition)
  57. return_me=[]
  58. for xf in xforms:
  59. if xf.node_type != 'XFORM':
  60. continue
  61. if xf in return_me:
  62. continue
  63. return_me.append(xf)
  64. return return_me
  65. def reset_execution(self):
  66. super().reset_execution()
  67. self.bObject=[]; self.prepared=True
  68. def fill_parameters(self, ui_node=None):
  69. super().fill_parameters(ui_node)
  70. self.parameters["Name"] = ui_node.label if ui_node.label else ui_node.name
  71. def standard_modifier_bind(self, bContext=None, operator=None):
  72. for d in self.bObject:
  73. # we'll only bind it if it is un-muted.
  74. if self.evaluate_input("Enable in Viewport") == False:
  75. continue
  76. from .utilities.utilities import bind_modifier_operator
  77. bind_modifier_operator(d, operator)
  78. class DeformerArmature(MantisDeformerNode):
  79. '''A node representing an armature deformer'''
  80. __slots__ = ()
  81. socket_templates = DeformArmatureSockets
  82. def GetxForm(self, socket="Deformer"):
  83. if socket == "Deformer":
  84. return super().GetxForm()
  85. else:
  86. trace_xForm_back(self, socket)
  87. # DUPLICATED FROM xForm_nodes::xFormBone
  88. # DEDUP HACK HACK HACK HACK HACK
  89. def bGetParentArmature(self):
  90. from .xForm_nodes import xFormArmature
  91. from .misc_nodes import InputExistingGeometryObject
  92. from bpy.types import Object
  93. if (trace := trace_single_line(self, "Armature Object")[0] ) :
  94. for i in range(len(trace)):
  95. # have to look in reverse, actually
  96. if ( isinstance(trace[ i ], xFormArmature ) ):
  97. return trace[ i ].bGetObject()
  98. elif ( isinstance(trace[i], InputExistingGeometryObject)):
  99. if (ob := trace[i].bGetObject()).type == "ARMATURE":
  100. return ob
  101. raise RuntimeError(f"Cannot find armature for node {self}")
  102. return None
  103. #should do the trick...
  104. def bRelationshipPass(self, bContext = None,):
  105. self.executed = True
  106. def initialize_vgroups(self, xf):
  107. ob = xf.bGetObject()
  108. armOb = self.bGetParentArmature()
  109. for b in armOb.data.bones:
  110. if b.use_deform == False:
  111. continue
  112. vg = ob.vertex_groups.get(b.name)
  113. if not vg:
  114. vg = ob.vertex_groups.new(name=b.name)
  115. if ob.type == 'MESH':
  116. num_verts = len(ob.data.vertices)
  117. elif ob.type == 'LATTICE':
  118. num_verts = len(ob.data.points)
  119. vg.add(range(num_verts), 0, 'REPLACE')
  120. def copy_weights(self, xf):
  121. # we'll use modifiers for this, maybe use GN for it in the future tho
  122. import bpy
  123. ob = xf.bGetObject()
  124. try:
  125. copy_from = self.GetxForm(socket="Copy Skin Weights From")
  126. except GraphError:
  127. copy_from = None
  128. prRed(f"No object found for copying weights in {self}, continuing anyway.")
  129. m = ob.modifiers.new(type="DATA_TRANSFER", name="Mantis_temp_data_transfer")
  130. m.object = None; m.use_vert_data = True
  131. m.data_types_verts = {'VGROUP_WEIGHTS'}
  132. m.vert_mapping = 'POLYINTERP_NEAREST'
  133. m.layers_vgroup_select_src = 'ALL'
  134. m.layers_vgroup_select_dst = 'NAME'
  135. m.object = copy_from
  136. # m.use_object_transform = False # testing reveals that this is undesirable - since the objects may not have their transforms applied.
  137. ob.modifiers.move(len(ob.modifiers)-1, 0)
  138. # ob.data = ob.data.copy()
  139. if False: #MAYBE the mouse needs to be in the 3D viewport, no idea how to set this in an override
  140. # TODO: figure out how to apply this, context is incorrect because armature is still in pose mode
  141. original_active = bpy.context.active_object
  142. original_mode = original_active.mode
  143. bpy.ops.object.mode_set(mode='OBJECT')
  144. with bpy.context.temp_override(**{'active_object':ob, 'selected_objects':[ob, copy_from]}):
  145. # bpy.ops.object.datalayout_transfer(modifier=m.name) # note: this operator is used by the modifier or stand-alone in the UI
  146. # the poll for this operator is defined in blender/source/blender/editors/object/object_data_transfer.cc
  147. # and blender/source/blender/editors/object/object_modifier.cc
  148. # bpy.ops.object.modifier_apply(modifier=m.name, single_user=True)
  149. bpy.ops.object.datalayout_transfer(data_type='VGROUP_WEIGHTS')
  150. bpy.ops.object.data_transfer(data_type='VGROUP_WEIGHTS')
  151. bpy.ops.object.mode_set(mode=original_mode)
  152. def do_automatic_skinning_mesh(self, ob, xf, bContext):
  153. # This is bad and leads to somewhat unpredictable
  154. # behaviour, e.g. what object will be selected? What mode?
  155. # also bpy.ops is ugly and prone to error when used in
  156. # scripts. I don't intend to use bpy.ops when I can avoid it.
  157. import bpy
  158. self.initialize_vgroups(xf)
  159. armOb = self.bGetParentArmature()
  160. armOb.data.pose_position = 'REST'
  161. bContext.view_layer.depsgraph.update()
  162. deform_bones = []
  163. for pb in armOb.pose.bones:
  164. if pb.bone.use_deform == True:
  165. deform_bones.append(pb)
  166. if not deform_bones:
  167. prPurple("Warning: No deform bones in armature. Cancelling.")
  168. return
  169. context_override = {
  170. 'active_object':ob,
  171. 'selected_objects':[ob, armOb],
  172. 'active_pose_bone':deform_bones[0],
  173. 'selected_pose_bones':deform_bones,}
  174. from .utilities.utilities import set_bone_selection
  175. for pb in armOb.pose.bones:
  176. set_bone_selection(pose_bone=pb, selection_state=True)
  177. with bContext.temp_override(**context_override):
  178. bpy.ops.paint.weight_paint_toggle()
  179. bpy.ops.paint.weight_from_bones(type='AUTOMATIC')
  180. bpy.ops.paint.weight_paint_toggle()
  181. for pb in armOb.pose.bones:
  182. set_bone_selection(pose_bone=pb, selection_state=False)
  183. armOb.data.pose_position = 'POSE'
  184. # TODO: modify Blender to make this available as a Python API function.
  185. def do_automatic_skinning_lattice(self, ob, xf, bContext):
  186. # Temporarily, I am making a very simple and ugly automatic skinning algo for lattice points
  187. import bpy
  188. from mathutils.geometry import intersect_point_line
  189. self.initialize_vgroups(xf)
  190. armOb = self.bGetParentArmature()
  191. armOb.data.pose_position = 'REST'
  192. bContext.view_layer.depsgraph.update()
  193. deform_bones = []
  194. for pb in armOb.pose.bones:
  195. if pb.bone.use_deform == True: deform_bones.append(pb)
  196. # How this works:
  197. # - Calculates the weights based on proximity and angle
  198. # - we'll make a vector of the point and the nearest point on the bone
  199. # - dot (point_displacement, bone_y_axis) to get the angle
  200. # - weight the bone's value by this dot product and distance
  201. # - distance should prevail when both bones are within the angle
  202. mat = ob.matrix_world; mat_arm = armOb.matrix_world
  203. for p_index, p in enumerate(ob.data.points):
  204. loc = mat @ p.co_deform # co_deform is the position in edit mode
  205. pt_distance, pt_dot = {}, {}
  206. for b in deform_bones:
  207. bone_vec = ((mat_arm @ b.tail) - (mat_arm @ b.head)).normalized()
  208. nearest_point_on_bone, factor = intersect_point_line(
  209. loc, mat_arm @ b.head, mat_arm @ b.tail) # 0 is point, 1 is factor
  210. if factor > 1.0: nearest_point_on_bone = mat_arm @ b.tail
  211. if factor < 0.0: nearest_point_on_bone = mat_arm @ b.head
  212. point_vec = nearest_point_on_bone - loc
  213. distance = point_vec.length_squared # no need to sqrt, this is faster and
  214. # the quadratic falloff is better than linear falloff.
  215. dot = 1-abs(point_vec.normalized().dot(bone_vec))
  216. # we want to weight zero at 1.0 so that it favors points in its "envelope"
  217. pt_distance[b.name]=distance; pt_dot[b.name] = dot
  218. # now we can assign weights
  219. distance_pairs = [(k,v) for k,v in pt_distance.items()]
  220. distance_pairs.sort(key = lambda a : a[1])
  221. i=0; max_distance = 0.0; near_enough_bones = []
  222. while (i < 4): # TODO: limit-total should be exposed to the user.
  223. if i+1 > len(distance_pairs): break # in case there are fewer than 4 deform bones
  224. near_enough_bones.append(distance_pairs[i][0])
  225. if distance_pairs[i][1] > max_distance: max_distance = distance_pairs[i][1]
  226. i+=1
  227. max_pre_normalized_weight = 0.0
  228. weights = {}
  229. if max_distance == 0.0: max_distance = 1.0
  230. for b_name in near_enough_bones:
  231. w = 1.0
  232. if pt_distance[b_name] > 0:
  233. w*= 1/(pt_distance[b_name]/max_distance) # weight by inverse-distance
  234. w*= pt_dot[b_name]**4 # NOTE: **4 is arbitrary but feels good to me.
  235. if w > max_pre_normalized_weight: max_pre_normalized_weight = w
  236. weights[b_name] = w
  237. if max_pre_normalized_weight == 0.0: max_pre_normalized_weight = 1.0
  238. for b_name in near_enough_bones:
  239. vg = ob.vertex_groups.get(b_name)
  240. vg.add([p_index], weights[b_name]/max_pre_normalized_weight, 'REPLACE')
  241. armOb.data.pose_position = 'POSE'
  242. def bFinalize(self, bContext=None):
  243. prGreen("Executing Armature Deform Node")
  244. mod_name = self.evaluate_input("Name")
  245. for xf in self.GetxForm():
  246. ob = xf.bGetObject()
  247. d = ob.modifiers.new(mod_name, type='ARMATURE')
  248. if d is None:
  249. raise RuntimeError(f"Modifier was not created in node {self} -- the object is invalid.")
  250. self.bObject.append(d)
  251. d.object = self.bGetParentArmature()
  252. props_sockets = self.property_socket_map
  253. evaluate_sockets(self, {"DEFAULT":d}, props_sockets)
  254. #
  255. if (skin_method := self.evaluate_input("Skinning Method")) == "AUTOMATIC_HEAT":
  256. match ob.type:
  257. case "MESH":
  258. self.do_automatic_skinning_mesh(ob, xf, bContext)
  259. case "LATTICE":
  260. self.do_automatic_skinning_lattice(ob, xf, bContext)
  261. elif skin_method == "COPY_FROM_OBJECT":
  262. self.initialize_vgroups(xf)
  263. self.copy_weights(xf)
  264. # elif skin_method == "EXISTING_GROUPS":
  265. # pass
  266. class DeformerHook(MantisDeformerNode):
  267. '''A node representing a hook deformer'''
  268. __slots__ = ()
  269. socket_templates = HookSockets
  270. def driver_for_radius(self, object, hook, index, influence, bezier=True):
  271. """ Creates a driver to control the radius of a curve point with the hook."""
  272. from bpy.types import Bone, PoseBone
  273. var_template = {"owner":hook,
  274. "name":"a",
  275. "type":"TRANSFORMS",
  276. "space":'WORLD_SPACE',
  277. "channel":'SCALE_X',}
  278. var1_template = {"owner":hook.id_data,
  279. "name":"b",
  280. "type":"TRANSFORMS",
  281. "space":'WORLD_SPACE',
  282. "channel":'SCALE_X',}
  283. keys_template = [{"co":(0,0),
  284. "interpolation": "LINEAR",
  285. "type":"KEYFRAME",},
  286. {"co":(1,influence),
  287. "interpolation": "LINEAR",
  288. "type":"KEYFRAME",},]
  289. if bezier:
  290. owner=object.data.splines[0].bezier_points
  291. else:
  292. owner=object.data.splines[0].points
  293. driver = {
  294. "owner":owner[index],
  295. "prop":"radius",
  296. "ind":-1,
  297. "extrapolation":"LINEAR",
  298. "type":"AVERAGE",
  299. "vars":[],
  300. "keys":keys_template,
  301. }
  302. if isinstance(hook, (Bone, PoseBone)):
  303. driver['type']='SCRIPTED'
  304. driver['expression']="(((1/b)*a)+((1/b_001)*a_001)+((1/b_002)*a_002))/3"
  305. from .utilities.drivers import CreateDrivers
  306. axes='XYZ'
  307. for i in range(3):
  308. suffix = "" if i == 0 else f"_{i:03d}" # explicit names -- 5.2 no longer uniquifies duplicates
  309. var = var_template.copy()
  310. var["name"]="a"+suffix
  311. var["channel"]="SCALE_"+axes[i]
  312. driver["vars"].append(var)
  313. if isinstance(hook, (Bone, PoseBone)):
  314. var1=var1_template.copy()
  315. var1['name']="b"+suffix
  316. var1['channel']="SCALE_"+axes[i]
  317. driver['vars'].append(var1)
  318. CreateDrivers([driver])
  319. def bRelationshipPass(self, bContext = None,):
  320. self.executed = True
  321. def bFinalize(self, bContext=None):
  322. from bpy.types import Bone, PoseBone, Object
  323. prGreen(f"Executing Hook Deform Node: {self}")
  324. mod_name = self.evaluate_input("Name")
  325. affect_radius = self.evaluate_input("Affect Curve Radius")
  326. auto_bezier = self.evaluate_input("Auto-Bezier")
  327. target_node = self.evaluate_input('Hook Target')
  328. target = target_node.bGetObject(); subtarget = ""
  329. props_sockets = self.property_socket_map
  330. if isinstance(target, Bone) or isinstance(target, PoseBone):
  331. subtarget = target.name; target = target.id_data
  332. for xf in self.GetxForm():
  333. ob=xf.bGetObject()
  334. if ob.type == 'CURVE':
  335. spline_index = self.evaluate_input("Spline Index")
  336. from .utilities.utilities import get_extracted_spline_object
  337. ob = get_extracted_spline_object(ob, spline_index, self.mContext)
  338. reuse = False
  339. for m in ob.modifiers:
  340. if m.type == 'HOOK' and m.object == target and m.subtarget == subtarget:
  341. if self.evaluate_input("Influence") != m.strength:
  342. continue # make a new modifier so they can have different strengths
  343. if ob.animation_data: # this can be None
  344. drivers = ob.animation_data.drivers
  345. for k in props_sockets.keys():
  346. if driver := drivers.find(k):
  347. # TODO: I should check to see if the drivers are the same...
  348. break # continue searching for an equivalent modifier
  349. else: # There was no driver - use this one.
  350. d = m; reuse = True; break
  351. else: # use this one, there can't be drivers without animation_data.
  352. d = m; reuse = True; break
  353. else:
  354. d = ob.modifiers.new(mod_name, type='HOOK')
  355. if d is None:
  356. raise RuntimeError(f"Modifier was not created in node {self} -- the object is invalid.")
  357. self.bObject.append(d)
  358. self.get_target_and_subtarget(d, input_name="Hook Target")
  359. vertices_used=[]
  360. if reuse: # Get the verts in the list... filter out all the unneeded 0's
  361. vertices_used = list(d.vertex_indices)
  362. include_0 = 0 in vertices_used
  363. vertices_used = list(filter(lambda a : a != 0, vertices_used))
  364. if include_0: vertices_used.append(0)
  365. # now we add the selected vertex to the list, too
  366. vertex = self.evaluate_input("Point Index")
  367. if ob.type == 'CURVE' and ob.data.splines[0].type == 'BEZIER' and auto_bezier:
  368. if affect_radius:
  369. self.driver_for_radius(ob, target_node.bGetObject(), vertex, d.strength)
  370. vertex*=3
  371. vertices_used.extend([vertex, vertex+1, vertex+2])
  372. else:
  373. vertices_used.append(vertex)
  374. # if we have a curve and it is NOT using auto-bezier for the verts..
  375. if ob.type == 'CURVE' and ob.data.splines[0].type == 'BEZIER' and affect_radius and not auto_bezier:
  376. print (f"WARN: {self}: \"Affect Radius\" may not behave as expected"
  377. " when used on Bezier curves without Auto-Bezier")
  378. #bezier point starts at 1, and then every third vert, so 4, 7, 10...
  379. if vertex%3==1:
  380. self.driver_for_radius(ob, target_node.bGetObject(), vertex, d.strength)
  381. if ob.type == 'CURVE' and ob.data.splines[0].type != 'BEZIER' and \
  382. affect_radius:
  383. self.driver_for_radius(ob, target_node.bGetObject(), vertex, d.strength, bezier=False)
  384. d.vertex_indices_set(vertices_used)
  385. evaluate_sockets(self, {"DEFAULT":d}, props_sockets)
  386. finish_drivers(self)
  387. # todo: this node should be able to take many indices in the future.
  388. # Also: I have a Geometry Nodes implementation of this I can use... maybe...
  389. class DeformerMorphTarget(MantisDeformerNode):
  390. '''A node representing an armature deformer'''
  391. __slots__ = ()
  392. socket_templates = MorphTargetSockets
  393. passes=frozenset({'bRelationship',})
  394. def GetxForm(self, trace_input="Object"):
  395. trace = trace_single_line(self, trace_input)
  396. for node in trace[0]:
  397. if (isinstance(node, deformable_types)):
  398. return node
  399. raise GraphError("%s is not connected to an upstream xForm" % self)
  400. def bRelationshipPass(self, bContext = None,):
  401. prGreen("Executing Morph Target Node")
  402. ob = None; relative = None
  403. # do NOT check if the object exists here. Just let the next node deal with that.
  404. try:
  405. ob = self.GetxForm().bGetObject().name
  406. except Exception as e: # this will and should throw an error if it fails
  407. ob = self.GetxForm().evaluate_input("Name")
  408. if self.inputs["Relative to"].is_linked:
  409. try:
  410. relative = self.GetxForm("Relative to").bGetObject().name
  411. except Exception as e: # same here
  412. prRed(f"Execution failed at {self}: no relative object found for morph target, despite link existing.")
  413. raise e
  414. vg = self.evaluate_input("Vertex Group") if self.evaluate_input("Vertex Group") else "" # just make sure it is a string
  415. mt={"object":ob, "vertex_group":vg, "relative_shape":relative}
  416. self.parameters["Morph Target"] = mt
  417. self.parameters["Name"] = ob # this is redundant but it's OK since accessing the mt is tedious
  418. self.executed = True
  419. class DeformerMorphTargetDeform(MantisDeformerNode):
  420. '''A node representing an armature deformer'''
  421. __slots__ = ()
  422. socket_templates = MorphTargetDeformSockets
  423. passes=frozenset({'bFinalize',})
  424. def __init__(self, signature, base_tree):
  425. super().__init__(signature, base_tree, self.socket_templates)
  426. self.executed = True
  427. setup_custom_property_inputs_outputs(self)
  428. def reset_execution(self):
  429. return super().reset_execution()
  430. self.executed=True
  431. def gen_morph_target_modifier(self, xf, context):
  432. # first let's see if this is a no-op
  433. targets = []
  434. for k,v in self.inputs.items():
  435. if "Target" in k:
  436. targets.append(v)
  437. if not targets:
  438. return # nothing to do here.
  439. # at this point we make the node tree
  440. from .utilities.geometry_node_graphgen import gen_morph_target_nodes
  441. d, props_sockets, b_obs = gen_morph_target_nodes(
  442. self.evaluate_input("Name"),
  443. xf.bGetObject(),
  444. targets,
  445. context,
  446. use_offset=self.evaluate_input("Use Offset"))
  447. b_obs['DEFAULT']=d
  448. self.bObject.append(d)
  449. evaluate_sockets(self, b_obs, props_sockets)
  450. finish_drivers(self)
  451. def gen_shape_key_lattice(self, xf, context):
  452. # first check if we need to do anything
  453. targets = []
  454. for k,v in self.inputs.items():
  455. if "Target" in k:
  456. targets.append(v)
  457. if not targets:
  458. return # nothing to do here
  459. # TODO: deduplicate the code above here
  460. from time import time
  461. start_time = time()
  462. from bpy import data
  463. ob = xf.bGetObject()
  464. dg = context.view_layer.depsgraph
  465. dg.update()
  466. if xf.has_shape_keys == False:
  467. lat = ob.data.copy()
  468. ob.data = lat
  469. ob.add_rest_position_attribute = True
  470. ob.shape_key_clear()
  471. ob.shape_key_add(name='Basis', from_mix=False)
  472. else:
  473. lat = ob.data
  474. xf.has_shape_keys = True
  475. # first make a basis shape key
  476. keys = {}
  477. for i, t in enumerate(targets):
  478. mt_node = t.links[0].from_node; sk_ob = mt_node.GetxForm().bGetObject()
  479. if sk_ob is None:
  480. sk_ob = data.objects.new(mt_node.evaluate_input("Name"), data.meshes.new_from_object(ob))
  481. context.collection.objects.link(sk_ob)
  482. prOrange(f"WARN: no object found for f{mt_node}; creating duplicate of current object ")
  483. sk_ob = dg.id_eval_get(sk_ob)
  484. mt_name = sk_ob.name
  485. vg = mt_node.parameters["Morph Target"]["vertex_group"]
  486. if vg: mt_name = mt_name+"."+vg
  487. sk = ob.shape_key_add(name=mt_name, from_mix=False)
  488. # the shapekey data is absolute point data for each vertex, in order, very simple
  489. # SERIOUSLY IMPORTANT:
  490. # use the current position of the vertex AFTER SHAPE KEYS AND DEFORMERS
  491. # easiest way to do it is to eval the depsgraph
  492. # TODO: try and get it without depsgraph update, since that may be (very) slow
  493. sk_m = sk_ob.data#data.meshes.new_from_object(sk_ob, preserve_all_data_layers=True, depsgraph=dg)
  494. for j in range(len(m.vertices)):
  495. sk.data[j].co = sk_m.vertices[j].co # assume they match
  496. # data.meshes.remove(sk_m)
  497. sk.vertex_group = vg
  498. sk.slider_min = -10
  499. sk.slider_max = 10
  500. keys[mt_name]=sk
  501. from .mantis_dataclasses import MantisSocketFiller
  502. filler = MantisSocketFiller(
  503. property_name=mt_name,
  504. socket_name = "Value."+str(i).zfill(3),
  505. default_value= 1.0,
  506. )
  507. evaluate_sockets( self, {"DEFAULT":sk}, {mt_name:filler})
  508. for i, t in enumerate(targets):
  509. mt_node = t.links[0].from_node; sk_ob = mt_node.GetxForm().bGetObject()
  510. if sk_ob is None: continue
  511. if rel := mt_node.parameters["Morph Target"]["relative_shape"]:
  512. sk = keys.get(mt_name)
  513. sk.relative_key = keys.get(rel)
  514. self.bObject.append(sk.id_data)
  515. finish_drivers(self)
  516. prWhite(f"Initializing morph target took {time() -start_time} seconds")
  517. def gen_shape_key(self, xf, context):
  518. # TODO: make this a feature of the node definition that appears only when there are no prior deformers - and shows a warning!
  519. # TODO: the below works well, but it is quite slow. It does not seem to have better performence. Its only advantage is export to FBX.
  520. # there are a number of things I need to fix here
  521. # - reuse shape keys if possible
  522. # - figure out how to make this a lot faster
  523. # - edit the xForm stuff to delete drivers from shape key ID's, since they belong to the Key, not the Object.
  524. # first check if we need to do anythign
  525. targets = []
  526. for k,v in self.inputs.items():
  527. if "Target" in k:
  528. targets.append(v)
  529. if not targets:
  530. return # nothing to do here
  531. from time import time
  532. start_time = time()
  533. from bpy import data
  534. ob = xf.bGetObject()
  535. dg = context.view_layer.depsgraph
  536. dg.update()
  537. if xf.has_shape_keys == False:
  538. match ob.type:
  539. case 'MESH':
  540. ob_data = data.meshes.new_from_object(ob, preserve_all_data_layers=True, depsgraph=dg)
  541. case 'LATTICE':
  542. ob_data = ob.data.copy()
  543. ob.data = ob_data
  544. ob.add_rest_position_attribute = True
  545. ob.shape_key_clear()
  546. ob.shape_key_add(name='Basis', from_mix=False)
  547. else:
  548. ob_data = ob.data
  549. xf.has_shape_keys = True
  550. # using the built-in shapekey feature is actually a lot harder in terms of programming because I need...
  551. # min/max, as it is just not a feature of the GN version
  552. # to carry info from the morph target node regarding relative shapes and vertex groups and all that
  553. # the drivers may be more difficult to apply, too.
  554. # hafta make new geometry for the object and add shape keys and all that
  555. # the benefit to all this being exporting to game engines via .fbx
  556. # first make a basis shape key
  557. keys={}
  558. for i, t in enumerate(targets):
  559. mt_node = t.links[0].from_node; sk_ob = mt_node.GetxForm().bGetObject()
  560. if sk_ob is None:
  561. sk_ob = data.objects.new(mt_node.evaluate_input("Name"), data.meshes.new_from_object(ob))
  562. context.collection.objects.link(sk_ob)
  563. prOrange(f"WARN: no object found for f{mt_node}; creating duplicate of current object ")
  564. sk_ob = dg.id_eval_get(sk_ob)
  565. mt_name = sk_ob.name
  566. vg = mt_node.parameters["Morph Target"]["vertex_group"]
  567. if vg: mt_name = mt_name+"."+vg
  568. sk = ob.shape_key_add(name=mt_name, from_mix=False)
  569. # the shapekey data is absolute point data for each vertex, in order, very simple
  570. # SERIOUSLY IMPORTANT:
  571. # use the current position of the vertex AFTER SHAPE KEYS AND DEFORMERS
  572. # easiest way to do it is to eval the depsgraph
  573. # TODO: try and get it without depsgraph update, since that may be (very) slow
  574. sk_m = sk_ob.data#data.meshes.new_from_object(sk_ob, preserve_all_data_layers=True, depsgraph=dg)
  575. match ob.type:
  576. case 'MESH':
  577. for j in range(len(ob_data.vertices)):
  578. sk.data[j].co = sk_m.vertices[j].co # assume they match
  579. case 'LATTICE':
  580. for j in range(len(ob.data.points)):
  581. sk.data[j].co = sk_m.points[j].co_deform
  582. # data.meshes.remove(sk_m)
  583. sk.vertex_group = vg
  584. sk.slider_min = -10
  585. sk.slider_max = 10
  586. keys[mt_name]=sk
  587. from .mantis_dataclasses import MantisSocketFiller
  588. filler = MantisSocketFiller(
  589. property_group=mt_name,
  590. property_name=mt_name,
  591. socket_name = "Value."+str(i).zfill(3),
  592. default_value= 1.0,
  593. )
  594. evaluate_sockets( self, {"DEFAULT":sk}, {mt_name:filler})
  595. for i, t in enumerate(targets):
  596. mt_node = t.links[0].from_node; sk_ob = mt_node.GetxForm().bGetObject()
  597. if sk_ob is None: continue
  598. if rel := mt_node.parameters["Morph Target"]["relative_shape"]:
  599. sk = keys.get(mt_name)
  600. sk.relative_key = keys.get(rel)
  601. self.bObject.append(sk.id_data)
  602. finish_drivers(self)
  603. prWhite(f"Initializing morph target took {time() -start_time} seconds")
  604. def bFinalize(self, bContext=None):
  605. prGreen(f"Executing Morph Deform node {self}")
  606. use_shape_keys = self.evaluate_input("Use Shape Key")
  607. # if there is a not a prior deformer then there should be an option to use plain 'ol shape keys
  608. # GN is always desirable as an option though because it can be baked & many other reasons
  609. if use_shape_keys: # check and see if we can.
  610. if self.inputs.get("Deformer"): # I guess this isn't available in some node group contexts... bad. FIXME
  611. if (links := self.inputs["Deformer"].links):
  612. if not links[0].from_node.parameters.get("Use Shape Key"):
  613. use_shape_keys = False
  614. elif links[0].from_node.parameters.get("Use Shape Key") == False:
  615. use_shape_keys = False
  616. self.parameters["Use Shape Key"] = use_shape_keys
  617. for xf in self.GetxForm():
  618. # Lattice objects do not support geometry nodes at this time.
  619. ob = xf.bGetObject()
  620. if ob and ob.type == 'LATTICE':
  621. if not use_shape_keys:
  622. raise NotImplementedError("Blender does not support Geometry Nodes for Lattices. "
  623. "Enable 'Shape Key' and execute again.")
  624. self.gen_shape_key(xf, bContext)
  625. elif use_shape_keys:
  626. self.gen_shape_key(xf, bContext)
  627. else:
  628. self.gen_morph_target_modifier(xf, bContext)
  629. class DeformerSurfaceDeform(MantisDeformerNode):
  630. '''A node representing an surface deform modifier'''
  631. __slots__ = ()
  632. socket_templates = SurfaceDeformSockets
  633. passes=frozenset({'bRelationship', 'bFinalize', 'bModifierApply'})
  634. def bRelationshipPass(self, bContext = None,):
  635. self.executed = True
  636. def bFinalize(self, bContext=None):
  637. prGreen("Executing Surface Deform Node")
  638. mod_name = self.evaluate_input("Name")
  639. for xf in self.GetxForm():
  640. ob = xf.bGetObject()
  641. d = ob.modifiers.new(mod_name, type='SURFACE_DEFORM')
  642. if d is None:
  643. raise RuntimeError(f"Modifier was not created in node {self} -- the object is invalid.")
  644. self.bObject.append(d)
  645. self.get_target_and_subtarget(d, input_name="Target")
  646. props_sockets = self.property_socket_map
  647. evaluate_sockets(self, {"DEFAULT":d}, props_sockets)
  648. def bModifierApply(self, bContext=None):
  649. from bpy import ops
  650. standard_modifier_bind(self, bContext, ops.object.surfacedeform_bind)
  651. class DeformerMeshDeform(MantisDeformerNode):
  652. '''A node representing a mesh deform modifier'''
  653. __slots__ = ()
  654. socket_templates = MeshDeformSockets
  655. passes=frozenset({'bRelationship', 'bFinalize', 'bModifierApply'})
  656. def bRelationshipPass(self, bContext = None,):
  657. self.executed = True
  658. def bFinalize(self, bContext=None):
  659. prGreen("Executing Mesh Deform Node")
  660. mod_name = self.evaluate_input("Name")
  661. for xf in self.GetxForm():
  662. ob = xf.bGetObject()
  663. d = ob.modifiers.new(mod_name, type='MESH_DEFORM')
  664. if d is None:
  665. raise RuntimeError(f"Modifier was not created in node {self} -- the object is invalid.")
  666. self.bObject.append(d)
  667. self.get_target_and_subtarget(d, input_name="Object")
  668. props_sockets = self.property_socket_map
  669. evaluate_sockets(self, {"DEFAULT":d}, props_sockets)
  670. def bModifierApply(self, bContext=None):
  671. from bpy import ops
  672. standard_modifier_bind(self, bContext, ops.object.meshdeform_bind)
  673. class DeformerLatticeDeform(MantisDeformerNode):
  674. '''A node representing a lattice deform modifier'''
  675. __slots__ = ()
  676. socket_templates = LatticeDeformSockets
  677. def bRelationshipPass(self, bContext = None,):
  678. self.executed = True
  679. def bFinalize(self, bContext=None):
  680. prGreen("Executing Lattice Deform Node")
  681. mod_name = self.evaluate_input("Name")
  682. for xf in self.GetxForm():
  683. ob = xf.bGetObject()
  684. d = ob.modifiers.new(mod_name, type='LATTICE')
  685. if d is None:
  686. raise RuntimeError(f"Modifier was not created in node {self} -- the object is invalid.")
  687. self.bObject.append(d)
  688. self.get_target_and_subtarget(d, input_name="Object")
  689. props_sockets = self.property_socket_map
  690. evaluate_sockets(self, {"DEFAULT":d}, props_sockets)
  691. class DeformerSmoothCorrectiveDeform(MantisDeformerNode):
  692. '''A node representing a corrective smooth deform modifier'''
  693. __slots__ = ()
  694. socket_templates = SmoothDeformSockets
  695. def bRelationshipPass(self, bContext = None,):
  696. self.executed = True
  697. def bFinalize(self, bContext=None):
  698. prGreen("Executing Smooth Deform Node")
  699. mod_name = self.evaluate_input("Name")
  700. for xf in self.GetxForm():
  701. ob = xf.bGetObject()
  702. d = ob.modifiers.new(mod_name, type='CORRECTIVE_SMOOTH')
  703. if d is None:
  704. raise RuntimeError(f"Modifier was not created in node {self} -- the object is invalid.")
  705. self.bObject.append(d)
  706. # self.get_target_and_subtarget(d, input_name="Object")
  707. props_sockets = self.property_socket_map
  708. evaluate_sockets(self, {"DEFAULT":d}, props_sockets)