forked from z64tools/io_export_objex_2.5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interface.py
2132 lines (1823 loc) · 93 KB
/
interface.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2020-2021 Dragorn421, Rankaisija
#
# This objex2 addon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This objex2 addon is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this objex2 addon. If not, see <https://www.gnu.org/licenses/>.
from . import blender_version_compatibility
import os
import bpy
import bpy.utils.previews
import mathutils
import re
from math import pi
from . import const_data as CST
from . import data_updater
from . import node_setup_helpers
from .logging_util import getLogger
from . import util
from . import rigging_helpers
from pathlib import Path
"""
useful reference for UI
Vanilla Blender Material UI https://github.com/uzairakbar/blender/blob/master/blender/2.79/scripts/startup/bl_ui/properties_material.py
About Panel Ordering (2016): no API https://blender.stackexchange.com/questions/24041/how-i-can-define-the-order-of-the-panels
Thorough UI script example https://blender.stackexchange.com/questions/57306/how-to-create-a-custom-ui
More examples https://b3d.interplanety.org/en/creating-panels-for-placing-blender-add-ons-user-interface-ui/
bl_idname and class name guidelines (Blender 2.80) https://wiki.blender.org/wiki/Reference/Release_Notes/2.80/Python_API/Addons
General information https://docs.blender.org/api/2.79/info_overview.html#integration-through-classes
Menu examples https://docs.blender.org/api/2.79/bpy.types.Menu.html
Panel examples https://docs.blender.org/api/2.79/bpy.types.Panel.html
Preferences example https://docs.blender.org/api/2.79/bpy.types.AddonPreferences.html
Using properties, and a list of properties https://docs.blender.org/api/2.79/bpy.props.html
"Color property" (2014) https://blender.stackexchange.com/questions/6154/custom-color-property-in-panel-draw-layout
UILayout https://docs.blender.org/api/2.79/bpy.types.UILayout.html
Looks like a nice tutorial, demonstrates operator.draw but not other UI stuff https://michelanders.blogspot.com/p/creating-blender-26-python-add-on.html
custom properties https://docs.blender.org/api/2.79/bpy.types.bpy_struct.html
very nice bare-bones example with custom node and ui https://gist.github.com/OEP/5978445
other useful reference
GPL https://www.gnu.org/licenses/gpl-3.0.en.html
API changes https://docs.blender.org/api/current/change_log.html
More up-to-date-ish but somewhat vague and summarized version changes https://wiki.blender.org/wiki/Reference/Release_Notes
Addon Tutorial (not part of the addon doc) https://docs.blender.org/manual/en/latest/advanced/scripting/addon_tutorial.html
Operator examples https://docs.blender.org/api/2.79/bpy.types.Operator.html
bl_idname requirements https://github.com/blender/blender/blob/f149d5e4b21f372f779fdb28b39984355c9682a6/source/blender/windowmanager/intern/wm_operators.c#L167
add input socket to a specific node instance #bpy.data.materials["Material"].node_tree.nodes["Material"].inputs.new("NodeSocketColor", "envcolor2")
"""
def foldable_icon(attr):
if attr:
return "DOWNARROW_HLT"
else:
return "RIGHTARROW"
def foldable_menu(element:bpy.types.UILayout, data, attr:str):
element.prop(data, attr, icon=foldable_icon(getattr(data, attr)), emboss=False)
if getattr(data, attr) == True:
return True
return False
def propOffset(layout, data, key, propName):
offsetStr = getattr(data, key)
bad_offset = None
# also allows an empty string
if not re.match(r"^(?:(?:0x)?[0-9a-fA-F]|)+$", offsetStr):
bad_offset = "not_hex"
if re.match(r"^[0-9]+$", offsetStr):
bad_offset = "warn_decimal"
layout.prop(data, key, icon=("ERROR" if bad_offset else "NONE"))
if bad_offset == "not_hex":
layout.label(text="%s must be hexadecimal" % propName)
elif bad_offset == "warn_decimal":
layout.label(text="%s looks like base 10" % propName)
layout.label(text="It will be read in base 16")
layout.label(text="Use 0x prefix to be explicit")
# mesh
def menu_draw_mesh(layout:bpy.types.UILayout, context:bpy.types.Context):
objex_scene = context.scene.objex_bonus
object = context.object
data = object.data.objex_bonus # ObjexMeshProperties
box = layout.box()
box.row().prop(data, "type", expand=True)
box = layout.box()
row = box.row()
row.alignment = "CENTER"
row.label(text="Mesh")
row = box.row()
# row.use_property_split = True
row.use_property_decorate = False # Do not display keyframe setting
row.label(text="Origin")
row.prop(data, "write_origin", expand=True)
row = box.row()
# row.use_property_split = True
row.use_property_decorate = False # Do not display keyframe setting
row.label(text="Billboard")
row.prop(data, "attrib_billboard", expand=True)
box.prop(data, "priority")
sub_box = box.box()
row = sub_box.row()
row.prop(data, "attrib_POSMTX")
row.prop(data, "attrib_PROXY")
row.label(text="") # Only for aligning with the next row items
armature = object.find_armature()
if armature:
row = sub_box.row()
row.prop(data, "attrib_NOSPLIT")
invert = False
col = row.column()
if data.attrib_NOSPLIT:
col.enabled = False
# Make it look like the disabled button is enabled
if data.attrib_NOSKEL == False:
invert=True
col.prop(data, "attrib_NOSKEL", invert_checkbox=invert)
row.prop(data, "attrib_LIMBMTX")
row = box.row()
row.operator("objex.mesh_find_multiassigned_vertices", text="Find multiassigned vertices")
row.operator("objex.mesh_find_unassigned_vertices", text="Find unassigned vertices")
box.operator("objex.mesh_list_vertex_groups", text="List groups of selected vertex")
return
def get_active_object(context:bpy.types.Context):
object = context.object
return object != None and object.type == "MESH"
class OBJEX_PT_mesh_object_prop(bpy.types.Panel):
bl_label = "Objex"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "data"
@classmethod
def poll(self, context):
return get_active_object(context)
def draw(self, context):
menu_draw_mesh(self.layout, context)
class OBJEX_OT_MassInit(bpy.types.Operator):
bl_idname = "objex.massinit"
bl_label = 'Mass Initialize'
bl_description = "Initializes Objex material on all materials in the scene"
bl_options = {"INTERNAL", "UNDO"}
def execute(self, context):
if not bpy.context.object:
bpy.ops.mesh.primitive_cube_add(size=1)
temp_obj = bpy.context.object
temp_obj.name = "TempMaterialObject"
else:
temp_obj = bpy.context.object
original_materials = list(temp_obj.data.materials)
for mat in bpy.data.materials:
if not mat.users:
continue
temp_obj.data.materials.clear()
temp_obj.data.materials.append(mat)
with bpy.context.temp_override(object=temp_obj, material=mat):
bpy.ops.objex.material_build_nodes(
init=True,
reset=False,
create=True,
update_groups_of_existing=True,
set_looks=True,
set_basic_links=True
)
temp_obj.data.materials.clear()
for mat in original_materials:
temp_obj.data.materials.append(mat)
if temp_obj.name == "TempMaterialObject":
bpy.data.objects.remove(temp_obj)
return {'FINISHED'}
# armature
# do not use the self argument, as the function is used by at least 2 properties
def armature_export_actions_change(self, context):
armature = context.armature
data = armature.objex_bonus
actions = data.export_actions
# remove all items without an action set
# this purposefully skips actions[-1]
i = len(actions) - 1
while i > 0:
i -= 1
item = actions[i]
if not item.action:
actions.remove(i)
# make sure last item is empty, to allow adding actions
if not actions or actions[-1].action:
actions.add()
class OBJEX_UL_actions(bpy.types.UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname):
if blender_version_compatibility.no_ID_PointerProperty:
layout.prop_search(item, "action", bpy.data, "actions", text="")
else:
layout.prop(item, "action", text="")
def get_active_armature(object:bpy.types.Object):
if object is not None:
if object.type == "ARMATURE":
return object
return object.find_armature()
return None
from .export_objex_anim import order_bones
class OBJEX_OT_add_joint_sphere(bpy.types.Operator):
bl_idname = "objex.add_joint_sphere"
bl_label = "Add Joint Sphere"
bl_options = {"INTERNAL", "UNDO"}
@classmethod
def poll(cls, context):
return get_active_armature(context.active_object) != None and context.active_bone != None and context.active_bone.use_deform == True
def execute(self, context):
armature = context.active_object
armature_data = armature.data
assert isinstance(armature_data, bpy.types.Armature)
if "Joint Collection" not in bpy.data.collections:
collection = bpy.data.collections.new(name="Joint Collection")
bpy.context.scene.collection.children.link(collection)
else:
collection = bpy.data.collections["Joint Collection"]
collection.color_tag = "COLOR_01"
for bone in context.selected_bones:
if bone.select == False:
continue
bone = armature_data.bones[context.active_bone.name]
sphere_name = armature.name + "_JointSphere_" + bone.name
armature.data.objex_bonus.uses_joint_spheres = True
sphere = bpy.data.objects.new(sphere_name, None)
collection.objects.link(sphere)
sphere.empty_display_type = "SPHERE"
sphere.parent = armature
sphere.parent_type = "BONE"
sphere.parent_bone = bone.name
sphere.show_in_front = True
# Place the empty so that it covers the bone: centered on the middle of the bone and of radius half the bone length
sphere.location = (0, -bone.length/2, 0)
sphere.scale = [bone.length / 2] * 3
return {"FINISHED"}
class OBJEX_OT_export_joint_sphere_header(bpy.types.Operator):
bl_idname = "objex.export_joint_sphere_header"
bl_label = "Export Header"
bl_options = { "INTERNAL", "UNDO" }
@classmethod
def poll(self, context:bpy.types.Context):
return get_active_armature(context.object) != None
def execute(self, context:bpy.types.Context):
armature = get_active_armature(context.object)
if armature == None:
return {"CANCELLED"}
armature_data = armature.data
assert isinstance(armature_data, bpy.types.Armature)
data = armature.data.objex_bonus
filename = Path(bpy.path.abspath(data.joint_sphere_header_filepath))
basename = filename.stem
joint_sphere_scale = armature.data.objex_bonus.joint_sphere_scale
# blender to z64
transform_zup_to_yup = mathutils.Matrix([[1,0,0,0],[0,0,1,0],[0,-1,0,0],[0,0,0,1],])
with filename.open("w", newline="\n") as f:
fw = f.write
fw("#ifndef " + basename.upper() + "_H\n")
fw("#define " + basename.upper() + "_H\n\n")
fw("#include <global.h>\n\n")
fw("static ColliderJntSphElementInit s" + basename + "Elems[] = {\n")
root_bone, bones_ordered = order_bones(armature)
for child in armature.children:
child:bpy.types.Object
if child.parent_type != "BONE":
continue
bone = armature_data.bones[child.parent_bone]
bone_index = 1 + bones_ordered.index(bone)
sphere = child
# notes on Blender bones:
# 1) their own space is origin=head (thick end), with +y towards the tail (thin end)
# 2) bone.matrix_local is a transform from their own space to armature space
pos_blender = (
(
# from bone space (relative to bone head) to armature space (relative to armature)
# This mimics (1/2) export_objex_anim.write_skeleton which writes the skeleton in armature(/world?) space
# Note: idk how this behaves in the end if the armature has a non-0 location/rotation/scale
bone.matrix_local @ (
# bone parenting is relative to the bone tail, make the position relative to the bone head
sphere.location + mathutils.Vector((0, bone.length, 0))
)
)
# Make position relative to bone head (in armature space)
- bone.head_local
)
pos = transform_zup_to_yup @ pos_blender
pos *= joint_sphere_scale
assert (sum((s - sum(sphere.scale)/3)**2 for s in sphere.scale[:])/(sum(sphere.scale)/3)) < 1e-5, sphere.scale
radius_blender = sphere.scale[0] * sphere.empty_display_size
radius = radius_blender
fw(
" /* " + bone.name + " */ {\n"
" .info.bumperFlags = BUMP_ON,\n"
" \n"
" .dim.limb = " + str(bone_index) + ",\n"
" .dim.modelSphere ={\n"
" { " + str(int(pos.x)) + ", " + str(int(pos.y)) + ", " + str(int(pos.z)) + " },\n"
" " + str(int(radius * joint_sphere_scale)) +",\n"
" },\n"
# note joint_sphere_scale must be <= 100 for the dim.scale (integer) to stay > 0
" .dim.scale = " + str(int(100 * 1 / joint_sphere_scale)) + ",\n"
" },\n"
)
fw("};\n\n")
fw(
"static ColliderJntSphInit s" + basename + "Init = {\n"
" .base.shape = COLSHAPE_JNTSPH,\n"
" .base.colType = COLTYPE_NONE,\n"
" .base.acFlags = AC_ON,\n"
" \n"
" .count = ARRAY_COUNT(s" + basename + "Elems),\n"
" .elements = s" + basename + "Elems,\n"
"};\n\n#endif\n"
)
print("Collider OK")
return {"FINISHED"}
def menu_draw_armature(layout:bpy.types.UILayout, armature:bpy.types.Armature):
data = armature.objex_bonus
box = layout
box.use_property_split = False
box.row().prop(data, "type", expand=True)
box_row = box.row()
box_row.prop(data, "start_frame_clamp")
col = box_row.column()
col.enabled = data.start_frame_clamp
col.prop(data, "start_frame_clamp_value")
box_row = box.row()
box_row.prop(data, "end_frame_minus")
col = box_row.column()
col.enabled = data.end_frame_minus
col.prop(data, "end_frame_minus_value")
box.prop(data, "export_all_actions")
if not data.export_all_actions:
box.label(text="Actions to export:")
box.template_list("OBJEX_UL_actions", "", data, "export_actions", data, "export_actions_active")
sub_box = box.box()
if data.pbody:
sub_box.prop(data, "pbody")
def prop_pbody_parent_object(layout, icon="NONE"):
if blender_version_compatibility.no_ID_PointerProperty:
layout.prop_search(data, "pbody_parent_object", bpy.data, "objects", icon=icon)
else:
layout.prop(data, "pbody_parent_object", icon=icon)
if data.pbody_parent_object:
if blender_version_compatibility.no_ID_PointerProperty:
pbody_parent_object = bpy.data.objects[data.pbody_parent_object]
else:
pbody_parent_object = data.pbody_parent_object
if hasattr(pbody_parent_object, "type") and pbody_parent_object.type == "ARMATURE":
prop_pbody_parent_object(sub_box)
valid_bone = data.pbody_parent_bone in pbody_parent_object.data.bones
sub_box.prop_search(data, "pbody_parent_bone", pbody_parent_object.data, "bones", icon=("NONE" if valid_bone else "ERROR"))
if not valid_bone:
sub_box.label(text="A bone must be picked")
else:
prop_pbody_parent_object(sub_box, icon="ERROR")
sub_box.label(text="If set, parent must be an armature")
else:
prop_pbody_parent_object(sub_box)
else:
sub_box.prop(data, "pbody")
# segment
sub_box.prop(data, "segment_local")
propOffset(sub_box, data, "segment", "Segment")
if data.type == "z64player":
box = box.box()
row = box.row()
if data.anim_filepath == "":
row.enabled = False
row.operator("objex.export_link_anim_bin")
box.prop(data, "anim_filepath", text="Output")
row = box.row()
if data.src_bin_anim_filepath == "":
row.enabled = False
row.operator("objex.import_link_anim_bin")
box.prop(data, "src_bin_anim_filepath", text="Input")
class OBJEX_PT_armature_prop(bpy.types.Panel):
bl_label = "Objex"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_context = "data"
@classmethod
def poll(self, context):
armature = context.armature
return armature is not None
def draw(self, context):
menu_draw_armature(self.layout, context.armature)
def menu_draw_jointsphere(layout:bpy.types.UILayout, context:bpy.types.Context):
sphere = context.active_object
armature:bpy.types.Armature = sphere.parent.data
box = layout.box()
box.label(text='Joint Sphere')
if armature.bones[sphere.parent_bone].use_deform == False:
box.label(text="Warning! Parent bone is non-deform!")
box.prop_search(sphere, "parent_bone", armature, "bones", text="Parent")
box.prop(sphere, "location")
class OBJECT_PT_panel3d(bpy.types.Panel):
bl_category = "Objex"
bl_label = "Objex"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
def draw(self, context):
armature = get_active_armature(context.object)
if context.active_object != None and context.active_object.type == "EMPTY" and context.active_object.parent_type == "BONE":
menu_draw_jointsphere(self.layout, context)
self.layout.operator('objex.massinit')
box = self.layout.box()
if foldable_menu(box, context.scene.objex_bonus, "menu_mesh"):
if get_active_object(context):
menu_draw_mesh(box, context)
box = self.layout.box()
if foldable_menu(box, context.scene.objex_bonus, "menu_bone"):
if armature and context.mode != "OBJECT":
pose_bone = bpy.context.active_bone
if pose_bone != None:
box.label(text="Selected Bone")
box.prop(pose_bone, "name")
row = box.row()
row.prop(pose_bone, "use_deform")
row.operator("objex.add_joint_sphere", text="Add Joint Sphere")
box = self.layout.box()
if foldable_menu(box, context.scene.objex_bonus, "menu_skelanime"):
if armature:
menu_draw_armature(box, armature.data)
box = box.box()
if foldable_menu(box, context.scene.objex_bonus, "menu_joint"):
if armature and armature.data.objex_bonus.uses_joint_spheres:
box.prop(armature.data.objex_bonus, "joint_sphere_header_filepath")
box.prop(armature.data.objex_bonus, "joint_sphere_scale")
box.operator("objex.export_joint_sphere_header")
box = self.layout.box()
if foldable_menu(box, context.scene.objex_bonus, "menu_global"):
box.prop(context.scene.objex_bonus, 'blend_scale')
# material
def stripPrefix(s, prefix):
return s[len(prefix):] if s.startswith(prefix) else s
# NodeSocketInterface
class OBJEX_NodeSocketInterface_CombinerIO():
def draw(self, context, layout):
pass
def draw_color(self, context):
return CST.COLOR_OK
class OBJEX_NodeSocketInterface_CombinerInput(bpy.types.NodeSocketInterface, OBJEX_NodeSocketInterface_CombinerIO):
bl_socket_idname = "OBJEX_NodeSocket_CombinerInput"
# registering NodeSocketInterface classes without registering their NodeSocket classes
# led to many EXCEPTION_ACCESS_VIOLATION crashs, so don"t do that
OBJEX_NodeSocketInterface_CombinerOutput = None
OBJEX_NodeSocketInterface_RGBA_Color = None
class OBJEX_NodeSocketInterface_Dummy():
def draw(self, context, layout):
pass
def draw_color(self, context):
return CST.COLOR_NONE
# NodeSocket
class OBJEX_NodeSocket_CombinerInput(bpy.types.NodeSocket):
default_value = bpy.props.FloatVectorProperty(name="default_value", default=(0,1,0), min=0, max=1, subtype="COLOR")
def linkToFlag(self):
"""
returns a (flag, error) tuple
flag standing for what is linked to this socket
and error being an error message string
success: flag is a string and error is None
failure: flag is None and error is a string
Note that flag may be an empty string "" to
indicate lack of support for the cycle
This does not check if the input can be used for
this socket"s variable (A,B,C,D)
"""
cycle = self.node.get("cycle")
if cycle not in (CST.CYCLE_COLOR, CST.CYCLE_ALPHA):
return None, "Unknown cycle %s" % cycle
# default to 0 (allowed everywhere)
if not self.links:
return CST.COMBINER_FLAGS_0[cycle], None
otherSocket = self.links[0].from_socket
if OBJEX_NodeSocket_CombinerOutput is not None: # < 2.80
if otherSocket.bl_idname != combinerOutputClassName:
return None, "Bad link to %s" % otherSocket.bl_idname
if cycle == CST.CYCLE_COLOR:
return otherSocket.flagColorCycle, None
else: # CST.CYCLE_ALPHA
return otherSocket.flagAlphaCycle, None
else: # 2.80+
key = "%s %s" % (
"flagColorCycle" if cycle == CST.CYCLE_COLOR else "flagAlphaCycle",
otherSocket.identifier)
if otherSocket.bl_idname != combinerOutputClassName or key not in otherSocket.node:
return None, "Bad link to %s" % otherSocket.bl_idname
return otherSocket.node[key], None
def draw(self, context, layout, node, text):
# don"t do anything fancy in node group "inside" view
if node.bl_idname == "NodeGroupInput":
layout.label(text=text)
return
cycle = self.node.get("cycle")
name = self.name # A,B,C,D
if node.name == "OBJEX_AlphaCycle0" or node.name == "OBJEX_ColorCycle0":
cycle_id = 0
else:
cycle_id = 1
flag, warnMsg = self.linkToFlag()
if flag is None:
value = "?"
elif flag == "":
value = "XXX"
warnMsg = "Not for cycle %s" % cycle
else:
value = stripPrefix(flag, CST.COMBINER_FLAGS_PREFIX[cycle])
if flag not in CST.COMBINER_FLAGS_SUPPORT[cycle][name]:
warnMsg = "Only for %s, not %s" % (",".join(var for var,flags in CST.COMBINER_FLAGS_SUPPORT[cycle].items() if flag in flags), name)
input_flags_prop_name = "input_flags_%s_%s_%d" % (cycle, name, cycle_id)
col = layout.column()
if warnMsg:
col = layout.column()
col.label(text=warnMsg, icon="ERROR")
col.label(text="%s = %s" % (name, value))
col.prop(self, input_flags_prop_name, text="")
def draw_color(self, context, node):
if node.bl_idname == "NodeGroupInput":
return CST.COLOR_OK
flag, warnMsg = self.linkToFlag()
cycle = self.node.get("cycle")
name = self.name # A,B,C,D
return CST.COLOR_OK if (
flag and not warnMsg
and flag in CST.COMBINER_FLAGS_SUPPORT[cycle][name]
) else CST.COLOR_BAD
def input_flag_list_choose_get(cycle, variable, cycle_id):
def input_flag_list_choose(self, context):
log = getLogger("interface")
input_flags_prop_name = "input_flags_%s_%s_%d" % (cycle, variable, cycle_id)
flag = getattr(self, input_flags_prop_name)
if flag == "_":
return
tree = self.id_data
matching_socket = None
for n in tree.nodes:
for s in n.outputs:
if s.bl_idname == combinerOutputClassName:
if OBJEX_NodeSocket_CombinerOutput is not None: # < 2.80
socket_flag = s.flagColorCycle if cycle == CST.CYCLE_COLOR else s.flagAlphaCycle
else: # 2.80+
key = "%s %s" % (
"flagColorCycle" if cycle == CST.CYCLE_COLOR else "flagAlphaCycle",
s.identifier)
socket_flag = n[key] if key in n else None
if flag == socket_flag:
if matching_socket:
log.error("Found several sockets for flag {}: {!r} {!r}", flag, matching_socket, s)
matching_socket = s
if not matching_socket:
log.error("Did not find any socket for flag {}", flag)
return
while self.links:
tree.links.remove(self.links[0])
tree.links.new(matching_socket, self)
return input_flag_list_choose
for cycle in (CST.CYCLE_COLOR, CST.CYCLE_ALPHA):
for cycle_id in (0, 1):
for variable in ("A","B","C","D"):
setattr(
OBJEX_NodeSocket_CombinerInput,
"input_flags_%s_%s_%d" % (cycle, variable, cycle_id),
bpy.props.EnumProperty(
items=sorted(
(flag, stripPrefix(flag, CST.COMBINER_FLAGS_PREFIX[cycle]), flag)
for flag in CST.COMBINER_FLAGS_SUPPORT[cycle][variable]
if cycle_id != 0 or flag not in ("G_CCMUX_COMBINED","G_CCMUX_COMBINED_ALPHA","G_ACMUX_COMBINED")
) + [("_","...","")],
name="%s" % variable,
default="_",
update=input_flag_list_choose_get(cycle, variable, cycle_id)
)
)
del input_flag_list_choose_get
combinerInputClassName = "OBJEX_NodeSocket_CombinerInput"
# 421FIXME_UPDATE this could use refactoring?
# I have no idea how to do custom color sockets in 2.80+...
OBJEX_NodeSocket_CombinerOutput = None
OBJEX_NodeSocket_RGBA_Color = None
combinerOutputClassName = "NodeSocketColor"
rgbaColorClassName = "NodeSocketColor"
class OBJEX_NodeSocket_IntProperty():
def update_prop(self, context):
self.node.inputs[self.target_socket_name].default_value = self.default_value
default_value = bpy.props.IntProperty(update=update_prop)
def draw(self, context, layout, node, text):
layout.prop(self, "default_value", text=text)
def draw_color(self, context, node):
return CST.COLOR_NONE
class OBJEX_NodeSocket_BoolProperty():
def update_prop(self, context):
self.node.inputs[self.target_socket_name].default_value = 1 if self.default_value else 0
default_value = bpy.props.BoolProperty(update=update_prop)
def draw(self, context, layout, node, text):
layout.prop(self, "default_value", text=text)
def draw_color(self, context, node):
return CST.COLOR_NONE
# node groups creation
def create_node_group_cycle(group_name):
tree = bpy.data.node_groups.new(group_name, "ShaderNodeTree")
def addMixRGBnode(operation):
n = tree.nodes.new("ShaderNodeMixRGB")
n.blend_type = operation
n.inputs[0].default_value = 1 # "Fac"
return n
inputs_node = tree.nodes.new("NodeGroupInput")
inputs_node.location = (-450,0)
tree.inputs.new(combinerInputClassName, "A")
tree.inputs.new(combinerInputClassName, "B")
tree.inputs.new(combinerInputClassName, "C")
tree.inputs.new(combinerInputClassName, "D")
A_minus_B = addMixRGBnode("SUBTRACT")
A_minus_B.location = (-250,150)
tree.links.new(inputs_node.outputs["A"], A_minus_B.inputs[1])
tree.links.new(inputs_node.outputs["B"], A_minus_B.inputs[2])
times_C = addMixRGBnode("MULTIPLY")
times_C.location = (-50,100)
tree.links.new(A_minus_B.outputs[0], times_C.inputs[1])
tree.links.new(inputs_node.outputs["C"], times_C.inputs[2])
plus_D = addMixRGBnode("ADD")
plus_D.location = (150,50)
tree.links.new(times_C.outputs[0], plus_D.inputs[1])
tree.links.new(inputs_node.outputs["D"], plus_D.inputs[2])
outputs_node = tree.nodes.new("NodeGroupOutput")
outputs_node.location = (350,0)
tree.outputs.new(combinerOutputClassName, "Result")
tree.links.new(plus_D.outputs[0], outputs_node.inputs["Result"])
tree.outputs["Result"].name = "(A-B)*C+D" # rename from "Result" to formula
return tree
def create_node_group_color_static(group_name, colorValue, colorValueName):
tree = bpy.data.node_groups.new(group_name, "ShaderNodeTree")
rgb = tree.nodes.new("ShaderNodeRGB")
rgb.outputs[0].default_value = colorValue
rgb.location = (0,100)
outputs_node = tree.nodes.new("NodeGroupOutput")
outputs_node.location = (150,50)
tree.outputs.new(combinerOutputClassName, colorValueName)
tree.links.new(rgb.outputs[0], outputs_node.inputs[colorValueName])
return tree
def addMathNodeTree(tree, operation, location, in0=None, in1=None):
n = tree.nodes.new("ShaderNodeMath")
n.operation = operation
n.location = location
for i in (0,1):
input = (in0,in1)[i]
if input is not None:
if isinstance(input, (int,float)):
n.inputs[i].default_value = input
else:
tree.links.new(input, n.inputs[i])
return n.outputs[0]
def create_node_group_uv_pipe_main(group_name):
tree = bpy.data.node_groups.new(group_name, "ShaderNodeTree")
inputs_node = tree.nodes.new("NodeGroupInput")
inputs_node.location = (-1000,150)
tree.inputs.new("NodeSocketVector", "UV")
tree.inputs.new("NodeSocketVector", "Normal")
tree.inputs.new("OBJEX_NodeSocket_UVpipe_main_Texgen", "Texgen")
tree.inputs.new("OBJEX_NodeSocket_UVpipe_main_TexgenLinear", "Texgen Linear")
for uv in ("U","V"):
scale = tree.inputs.new("NodeSocketFloat", "%s Scale" % uv)
scale.default_value = 1
scale.min_value = 0
scale.max_value = 1
tree.inputs.new("NodeSocketFloat", "Texgen (0/1)")
tree.inputs.new("NodeSocketFloat", "Texgen Linear (0/1)")
# texgen math based on GLideN64/src/gSP.cpp (see G_TEXTURE_GEN in gSPProcessVertex)
separateUV = tree.nodes.new("ShaderNodeSeparateXYZ")
separateUV.location = (-800,300)
tree.links.new(inputs_node.outputs["UV"], separateUV.inputs[0])
transformNormal = tree.nodes.new("ShaderNodeVectorTransform")
transformNormal.location = (-800,-100)
tree.links.new(inputs_node.outputs["Normal"], transformNormal.inputs[0])
transformNormal.vector_type = "VECTOR"
transformNormal.convert_from = "OBJECT"
transformNormal.convert_to = "CAMERA"
normalize = tree.nodes.new("ShaderNodeVectorMath")
normalize.location = (-600,-100)
tree.links.new(transformNormal.outputs[0], normalize.inputs[0])
normalize.operation = "NORMALIZE"
separateUVtexgen = tree.nodes.new("ShaderNodeSeparateXYZ")
separateUVtexgen.location = (-400,-100)
tree.links.new(normalize.outputs[0], separateUVtexgen.inputs[0])
def addMathNode(operation, location, in0=None, in1=None):
return addMathNodeTree(tree, operation, location, in0, in1)
texgenOn = inputs_node.outputs["Texgen (0/1)"]
texgenOff = addMathNode("SUBTRACT", (-600,500), 1, texgenOn)
texgenLinear = inputs_node.outputs["Texgen Linear (0/1)"]
texgenLinearNot = addMathNode("SUBTRACT", (-600,-300), 1, texgenLinear)
frameLinear = tree.nodes.new("NodeFrame")
frameLinear.label = "_LINEAR"
final = {}
for uv, i, y in (("U",0,100),("V",1,-200)):
d = -200 if uv == "V" else 200
texgenNotLinear = separateUVtexgen.outputs[i]
texgenNotLinearPart = addMathNode("MULTIPLY", (-200,d+y), texgenLinearNot, texgenNotLinear)
multMin1 = addMathNode("MULTIPLY", (-200,y), texgenNotLinear, -1)
acos = addMathNode("ARCCOSINE", (0,y), multMin1)
divPi = addMathNode("DIVIDE", (200,y), acos, pi)
mult2 = addMathNode("MULTIPLY", (400,y), divPi, 2)
sub1 = addMathNode("SUBTRACT", (600,y), mult2, 1)
for s in (multMin1, acos, divPi, mult2, sub1):
s.node.parent = frameLinear
texgenLinearPart = addMathNode("MULTIPLY", (800,d+y), texgenLinear, sub1)
finalIfTexgen = addMathNode("ADD", (1000,y), texgenNotLinearPart, texgenLinearPart)
trulyFinalIfTexgen = addMathNode("MULTIPLY", (1200,y), finalIfTexgen, 50)
texgenPart = addMathNode("MULTIPLY", (1400,d+y), texgenOn, trulyFinalIfTexgen)
noTexgenPart = addMathNode("MULTIPLY", (1100,d+y), texgenOff, separateUV.outputs[i])
onlyScaleLeft = addMathNode("ADD", (1600,y), texgenPart, noTexgenPart)
final[uv] = addMathNode("MULTIPLY", (1800,y), onlyScaleLeft, inputs_node.outputs["%s Scale" % uv])
combineXYZ = tree.nodes.new("ShaderNodeCombineXYZ")
combineXYZ.location = (2000,100)
tree.links.new(final["U"], combineXYZ.inputs[0])
tree.links.new(final["V"], combineXYZ.inputs[1])
outputs_node = tree.nodes.new("NodeGroupOutput")
outputs_node.location = (2200,100)
tree.outputs.new("NodeSocketVector", "UV")
tree.links.new(combineXYZ.outputs[0], outputs_node.inputs["UV"])
return tree
def create_node_group_uv_pipe(group_name):
tree = bpy.data.node_groups.new(group_name, "ShaderNodeTree")
inputs_node = tree.nodes.new("NodeGroupInput")
inputs_node.location = (-600,150)
tree.inputs.new("NodeSocketVector", "UV")
# 421todo if Uniform UV Scale is checked, only display Scale Exponent and use for both U and V scales (is this possible?)
#tree.inputs.new("NodeSocketBool", "Uniform UV Scale").default_value = True
#tree.inputs.new("NodeSocketInt", "Scale Exponent")
# blender 2.79 fails to transfer data somewhere when linking int socket to float socket of math node, same for booleans
# those sockets wrap the float ones that are actually used for calculations
# this trick also seems to work fine in 2.82 though I"m not sure if it is required then
tree.inputs.new("OBJEX_NodeSocket_UVpipe_ScaleU", "U Scale Exponent")
tree.inputs.new("OBJEX_NodeSocket_UVpipe_ScaleV", "V Scale Exponent")
tree.inputs.new("OBJEX_NodeSocket_UVpipe_WrapU", "Wrap U")
tree.inputs.new("OBJEX_NodeSocket_UVpipe_WrapV", "Wrap V")
tree.inputs.new("OBJEX_NodeSocket_UVpipe_MirrorU", "Mirror U")
tree.inputs.new("OBJEX_NodeSocket_UVpipe_MirrorV", "Mirror V")
# internal hidden sockets
tree.inputs.new("NodeSocketFloat", "U Scale Exponent Float")
tree.inputs.new("NodeSocketFloat", "V Scale Exponent Float")
tree.inputs.new("NodeSocketFloat", "Wrap U (0/1)")
tree.inputs.new("NodeSocketFloat", "Wrap V (0/1)")
tree.inputs.new("NodeSocketFloat", "Mirror U (0/1)")
tree.inputs.new("NodeSocketFloat", "Mirror V (0/1)")
# pixels along U/V used for better clamping, to clamp the last pixel in the tile
# before the clamp part instead of clamping at the limit, where color is
# merged with the wrapping UV
# (this is only what I am guessing is happening)
# 421todo this is basically texture width/height right? could be set automatically
pixelsU = tree.inputs.new("NodeSocketFloat", "Pixels along U")
pixelsU.min_value = 1
inf = float("inf")
pixelsU.default_value = +inf
pixelsV = tree.inputs.new("NodeSocketFloat", "Pixels along V")
pixelsV.min_value = 1
pixelsV.default_value = +inf
separateXYZ = tree.nodes.new("ShaderNodeSeparateXYZ")
separateXYZ.location = (-800,100)
tree.links.new(inputs_node.outputs["UV"], separateXYZ.inputs[0])
def addMathNode(operation, location, in0=None, in1=None):
return addMathNodeTree(tree, operation, location, in0, in1)
final = {}
for uv, i, y in (("U",0,400),("V",1,-600)):
# looking at the nodes in blender is probably better than trying to understand the code here
# 421FIXME_UPDATE detect the -1;1 / 0;1 uv range in a cleaner way? not sure the break was exactly at 2.80
blenderNodesUvRangeIsMinusOneToOne = bpy.app.version < (2, 80, 0)
if blenderNodesUvRangeIsMinusOneToOne: # < 2.80
# (-1 ; 1) -> (0 ; 1)
ranged02 = addMathNode("ADD", (-600,200+y), separateXYZ.outputs[i], 1)
ranged01 = addMathNode("DIVIDE", (-400,200+y), ranged02, 2)
else: # 2.80+
ranged01 = separateXYZ.outputs[i]
# blender uses bottom left as (u,v)=(0,0) but oot uses top left as (0,0),
# so we mirror v around 1/2
if uv == "V":
uv64space = addMathNode("SUBTRACT", (-200,200+y), 1, ranged01)
else:
uv64space = ranged01
# scale from exponent
roundedExp = addMathNode("ROUND", (-400,400+y), inputs_node.outputs["%s Scale Exponent Float" % uv])
scalePow = addMathNode("POWER", (-200,400+y), 2, roundedExp)
scale = addMathNode("MULTIPLY", (0,400+y), uv64space, scalePow)
# mirror
notMirroredBool = addMathNode("SUBTRACT", (200,600+y), 1, inputs_node.outputs["Mirror %s (0/1)" % uv])
identity = addMathNode("MULTIPLY", (400,400+y), scale, notMirroredBool)
reversed = addMathNode("MULTIPLY", (200,200+y), scale, -1)
mod2_1 = addMathNode("MODULO", (400,0+y), scale, 2)
add2 = addMathNode("ADD", (600,0+y), mod2_1, 2)
mod2_2 = addMathNode("MODULO", (800,0+y), add2, 2)
notMirroredPartBool = addMathNode("LESS_THAN", (1000,0+y), mod2_2, 1)
mirroredPartNo = addMathNode("MULTIPLY", (1200,400+y), scale, notMirroredPartBool)
mirroredPartBool = addMathNode("SUBTRACT", (1200,0+y), 1, notMirroredPartBool)
mirroredPartYes = addMathNode("MULTIPLY", (1400,200+y), reversed, mirroredPartBool)
withMirror = addMathNode("ADD", (1600,300+y), mirroredPartYes, mirroredPartNo)
mirrored = addMathNode("MULTIPLY", (1800,400+y), withMirror, inputs_node.outputs["Mirror %s (0/1)" % uv])
mirroredFinal = addMathNode("ADD", (2000,300+y), identity, mirrored)
# wrapped (identity)
wrapped = addMathNode("MULTIPLY", (2200,400+y), mirroredFinal, inputs_node.outputs["Wrap %s (0/1)" % uv])
# clamped (in [0;1])
pixelSizeUVspace = addMathNode("DIVIDE", (1800,100+y), 1, inputs_node.outputs["Pixels along %s" % uv])
upperBound = addMathNode("SUBTRACT", (2000,0+y), 1, pixelSizeUVspace)
lowerBound = addMathNode("ADD", (2000,-300+y), 0, pixelSizeUVspace)
upperClamped = addMathNode("MINIMUM", (2300,200+y), mirroredFinal, upperBound)
upperLowerClamped = addMathNode("MAXIMUM", (2500,200+y), upperClamped, lowerBound)
notWrap = addMathNode("SUBTRACT", (2400,0+y), 1, inputs_node.outputs["Wrap %s (0/1)" % uv])
clamped = addMathNode("MULTIPLY", (2700,200+y), upperLowerClamped, notWrap)
#
final64space = addMathNode("ADD", (2900,300+y), wrapped, clamped)
# mirror v back around 1/2
if uv == "V":
final01range = addMathNode("SUBTRACT", (3000,500+y), 1, final64space)
else:
final01range = final64space
if blenderNodesUvRangeIsMinusOneToOne: # < 2.80
# (0 ; 1) -> (-1 ; 1)
final02range = addMathNode("MULTIPLY", (3100,300+y), final01range, 2)
final[uv] = addMathNode("SUBTRACT", (3300,300+y), final02range, 1)
else: # 2.80+
final[uv] = final01range
finalU = final["U"]
finalV = final["V"]
# out
combineXYZ = tree.nodes.new("ShaderNodeCombineXYZ")
combineXYZ.location = (3500,100)
tree.links.new(finalU, combineXYZ.inputs[0])
tree.links.new(finalV, combineXYZ.inputs[1])
outputs_node = tree.nodes.new("NodeGroupOutput")
outputs_node.location = (3700,100)
tree.outputs.new("NodeSocketVector", "UV")
tree.links.new(combineXYZ.outputs[0], outputs_node.inputs["UV"])
return tree
def create_node_group_rgba_pipe(group_name):
"""
"Casts" input for use as cycle inputs
Inputs: {rgbaColorClassName} "Color", NodeSocketFloat "Alpha"
Outputs: {combinerOutputClassName} "Color", {combinerOutputClassName} "Alpha"
"""