deformer_nodes.py 37 KB

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