deformer_nodes.py 36 KB

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