-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathobject_adapter.gd
7568 lines (6883 loc) · 327 KB
/
object_adapter.gd
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
# This file is part of Unidot Importer. See LICENSE.txt for full MIT license.
# Copyright (c) 2021-present Lyuma <xn.lyuma@gmail.com> and contributors
# SPDX-License-Identifier: MIT
@tool
extends RefCounted
const FORMAT_FLOAT32: int = 0
const FORMAT_FLOAT16: int = 1
const FORMAT_UNORM8: int = 2
const FORMAT_SNORM8: int = 3
const FORMAT_UNORM16: int = 4
const FORMAT_SNORM16: int = 5
const FORMAT_UINT8: int = 6
const FORMAT_SINT8: int = 7
const FORMAT_UINT16: int = 8
const FORMAT_SINT16: int = 9
const FORMAT_UINT32: int = 10
const FORMAT_SINT32: int = 11
const aligned_byte_buffer := preload("./aligned_byte_buffer.gd")
const monoscript := preload("./monoscript.gd")
const anim_tree_runtime := preload("./runtime/anim_tree.gd")
const human_trait = preload("./humanoid/human_trait.gd")
const humanoid_transform_util = preload("./humanoid/transform_util.gd")
const unidot_utils_class = preload("./unidot_utils.gd")
var unidot_utils = unidot_utils_class.new()
const STRING_KEYS: Dictionary = {
"value": 1,
"m_Name": 1,
"m_TagString": 1,
"name": 1,
"first": 1,
"propertyPath": 1,
"path": 1,
"attribute": 1,
"m_ShaderKeywords": 1,
"typelessdata": 1, # Mesh m_VertexData; Texture image data
"m_IndexBuffer": 1,
"Hash": 1,
}
func to_classname(utype: Variant) -> String:
if typeof(utype) == TYPE_NODE_PATH:
return str(utype)
var ret = utype_to_classname.get(utype, "")
if ret == "":
return "[UnknownType:" + str(utype) + "]"
return ret
func to_utype(classname: String) -> int:
return classname_to_utype.get(classname, 0)
func instantiate_unidot_object(meta: Object, fileID: int, utype: int, type: String) -> UnidotObject:
var ret: UnidotObject = null
var actual_type = type
if utype != 0 and utype_to_classname.has(utype):
actual_type = utype_to_classname[utype]
if actual_type != type and (type != "Behaviour" or actual_type != "FlareLayer") and (type != "Prefab" or actual_type != "PrefabInstance"):
meta.log_warn(fileID, "Mismatched type:" + type + " vs. utype:" + str(utype) + ":" + actual_type)
if _type_dictionary.has(actual_type):
# meta.log_debug(fileID, "Will instantiate object of type " + str(actual_type) + "/" + str(type) + "/" + str(utype) + "/" + str(classname_to_utype.get(actual_type, utype)))
ret = _type_dictionary[actual_type].new()
else:
meta.log_fail(fileID, "Failed to instantiate object of type " + str(actual_type) + "/" + str(type) + "/" + str(utype) + "/" + str(classname_to_utype.get(actual_type, utype)))
if type.ends_with("Importer"):
ret = UnidotAssetImporter.new()
else:
ret = UnidotObject.new()
ret.meta = meta
ret.adapter = self
ret.fileID = fileID
if utype != 0 and utype != classname_to_utype.get(actual_type, utype):
meta.log_warn(fileID, "Mismatched utype " + str(utype) + " for " + type)
ret.utype = classname_to_utype.get(actual_type, utype)
ret.type = actual_type
return ret
func instantiate_unidot_object_from_utype(meta: Object, fileID: int, utype: int) -> UnidotObject:
var ret: UnidotObject = null
if not utype_to_classname.has(utype):
meta.log_fail(fileID, "Unknown utype " + str(utype))
return
var actual_type: String = utype_to_classname[utype]
if _type_dictionary.has(actual_type):
ret = _type_dictionary[actual_type].new()
else:
meta.log_fail(fileID, "Failed to instantiate object of type " + str(actual_type) + "/" + str(utype) + "/" + str(classname_to_utype.get(actual_type, utype)))
ret = UnidotObject.new()
ret.meta = meta
ret.adapter = self
ret.fileID = fileID
ret.utype = classname_to_utype.get(actual_type, utype)
ret.type = actual_type
return ret
# Unidot types follow:
### ================ BASE OBJECT TYPE ================
class UnidotObject:
extends RefCounted
var meta: Resource = null # AssetMeta instance
var keys: Dictionary = {}
var fileID: int = 0 # Not set in .meta files
var type: String = ""
var utype: int = 0 # Not set in .meta files
var _cache_uniq_key: String = ""
var adapter: RefCounted = null # RefCounted to containing scope.
# Log messages related to this asset
func log_debug(msg: String):
meta.log_debug(self.fileID, msg)
# Anything that is unexpected but does not necessarily imply corruption.
# For example, successfully loaded a resource with default fileid
func log_warn(msg: String, field: String = "", remote_ref: Variant = [null, 0, "", null]):
if typeof(remote_ref) == TYPE_ARRAY:
meta.log_warn(self.fileID, msg, field, remote_ref)
elif typeof(remote_ref) == TYPE_OBJECT and remote_ref:
meta.log_warn(self.fileID, msg, field, [null, remote_ref.fileID, remote_ref.meta.guid, 0])
else:
meta.log_warn(self.fileID, msg, field)
# Anything that implies the asset will be corrupt / lost data.
# For example, some reference or field could not be assigned.
func log_fail(msg: String, field: String = "", remote_ref: Variant = [null, 0, "", null]):
if typeof(remote_ref) == TYPE_ARRAY:
meta.log_fail(self.fileID, msg, field, remote_ref)
elif typeof(remote_ref) == TYPE_OBJECT and remote_ref:
meta.log_fail(self.fileID, msg, field, [null, remote_ref.fileID, remote_ref.meta.guid, 0])
else:
meta.log_fail(self.fileID, msg, field)
# Some components or game objects within a prefab are "stripped" dummy objects.
# Setting the stripped flag is not required...
# and properties of prefabbed objects seem to have no effect anyway.
var is_stripped: bool = false
func is_stripped_or_prefab_instance() -> bool:
return is_stripped or is_non_stripped_prefab_reference
var uniq_key: String:
get:
if _cache_uniq_key.is_empty():
_cache_uniq_key = (str(utype) + ":" + str(keys.get("m_Name", "")) + ":" + str(meta.guid) + ":" + str(fileID))
return _cache_uniq_key
func _to_string() -> String:
#return "[" + str(type) + " @" + str(fileID) + ": " + str(len(keys)) + "]" # str(keys) + "]"
#return "[" + str(type) + " @" + str(fileID) + ": " + JSON.print(keys) + "]"
return "[" + str(type) + ":" + str(utype) + " " + str(get_debug_name()) + " @" + str(meta.guid) + ":" + str(fileID) + "]"
var name: String:
get:
return get_name()
func get_name() -> String:
if fileID == meta.main_object_id:
return meta.get_main_object_name()
if not keys.get("m_Name", "").is_empty():
return keys.get("m_Name", "")
return str(keys.get("m_Name", "NO_NAME_" + str(fileID)))
func get_debug_name() -> String:
return get_name()
var toplevel: bool:
get:
return is_toplevel()
func is_toplevel() -> bool:
return true
func is_collider() -> bool:
return false
var transform: Object:
get:
return get_transform()
func get_transform() -> Object:
return null
var gameObject: UnidotGameObject:
get:
return get_gameObject()
func get_gameObject() -> UnidotGameObject:
return null
# Belongs in UnidotComponent, but we haven't implemented all types yet.
func create_godot_node(state: RefCounted, new_parent: Node3D) -> Node:
var new_node: Node = Node.new()
new_node.name = type
assign_object_meta(new_node)
state.add_child(new_node, new_parent, self)
return new_node
func get_godot_type() -> String:
return "Object"
func get_extra_resources() -> Dictionary:
return {}
func get_extra_resource(fileID: int) -> Resource:
return null
func create_godot_resource() -> Resource:
return null
func get_godot_extension() -> String:
return ".res"
func assign_object_meta(ret: Object) -> void:
if ret != null:
if meta.get_database().enable_unidot_keys:
ret.set_meta("unidot_keys", self.keys)
func configure_skeleton_bone(skel: Skeleton3D, bone_name: String):
configure_skeleton_bone_props(skel, bone_name, self.keys)
func configure_skeleton_bone_props(skel: Node3D, bone_name: String, uprops: Dictionary):
if skel is BoneAttachment3D:
skel = skel.get_parent() # Should be the Skeleton3D
if not (skel is Skeleton3D):
log_fail("Unable to configure skeleton bone props on node " + str(skel) + " bone " + str(bone_name))
return
var props = self.convert_skeleton_properties(skel, bone_name, uprops)
var bone_idx: int = skel.find_bone(bone_name)
if props.has("quaternion"):
skel.set_bone_pose_rotation(bone_idx, props["quaternion"])
if props.has("position"):
skel.set_bone_pose_position(bone_idx, props["position"])
if props.has("scale"):
skel.set_bone_pose_scale(bone_idx, props["scale"])
var signs: Vector3 = (props["scale"].sign() + Vector3(0.5,0.5,0.5)).sign()
if not signs.is_equal_approx(Vector3.ONE) and not signs.is_equal_approx(-Vector3.ONE):
meta.transform_fileid_to_scale_signs[fileID] = signs
func convert_skeleton_properties(skel: Skeleton3D, bone_name: String, uprops: Dictionary):
var props: Dictionary = self.convert_properties(skel, uprops)
return props
func configure_node(node: Node):
if node == null:
return
var props: Dictionary = self.convert_properties(node, self.keys)
apply_component_props(node, props)
apply_node_props(node, props)
# Called once per component, not per-node. Only use for things that need a reference to the component
func apply_component_props(node: Node, props: Dictionary):
if props.has("scale"):
var signs: Vector3 = (props["scale"].sign() + Vector3(0.5,0.5,0.5)).sign()
if not signs.is_equal_approx(Vector3.ONE) and not signs.is_equal_approx(-Vector3.ONE):
meta.transform_fileid_to_scale_signs[fileID] = signs
# Called at least once per node. Most properties are set up in this way, since nodes are affected by multiple components
# Note that self.fileID may be pointing to a random component (or the GameObject itself) in this function.
func apply_node_props(node: Node, props: Dictionary):
if node is MeshInstance3D:
self.apply_mesh_renderer_props(meta, node, props)
log_debug(str(node.name) + ": " + str(props))
for propname in props:
if typeof(props.get(propname)) == TYPE_NIL:
continue
elif str(propname).ends_with(":x") or str(propname).ends_with(":y") or str(propname).ends_with(":z"):
log_warn("Unexpected per-axis value property in apply_node_props " + str(propname))
elif str(propname) == "name":
pass # We cannot do Name here because it will break existing NodePath of outer prefab to children.
else:
log_debug("SET " + str(node.name) + ":" + propname + " to " + str(props[propname]))
var dig: Variant = node
var dig_propnames: Array = propname.split(":") # example: dig_propnames = ["shape", "size"]
for prop in dig_propnames.slice(0, len(dig_propnames) - 1):
dig = dig.get(prop) # example: dig = CollisionShape3D
dig.set(dig_propnames[-1], props.get(propname))
func apply_mesh_renderer_props(meta: RefCounted, node: MeshInstance3D, props: Dictionary):
const material_prefix: String = ":UNIDOT_PROXY:"
log_debug("Apply mesh renderer props: " + str(props) + " / " + str(node.mesh))
var truncated_mat_prefix: String = meta.get_database().truncated_material_reference.resource_name
var null_mat_prefix: String = meta.get_database().null_material_reference.resource_name
var last_material: Object = null
var old_surface_count: int = 0
if node.mesh == null or node.mesh.get_surface_count() == 0:
last_material = node.get_material_override()
if last_material != null:
old_surface_count = 1
else:
old_surface_count = node.mesh.get_surface_count()
last_material = node.get_active_material(old_surface_count - 1)
while last_material != null and last_material.resource_name.begins_with(truncated_mat_prefix):
old_surface_count -= 1
if old_surface_count == 0:
last_material = null
break
last_material = node.get_active_material(old_surface_count - 1)
var last_extra_material: Resource = last_material
var current_materials_raw: Array = [].duplicate()
var prefix: String = material_prefix + str(old_surface_count - 1) + ":"
var new_prefix: String = prefix
var material_idx: int = 0
while material_idx < old_surface_count:
var mat: Resource = node.get_active_material(material_idx)
if mat != null and str(mat.resource_name).begins_with(prefix):
break
current_materials_raw.push_back(mat)
material_idx += 1
var mat_slots: PackedInt32Array = meta.fileid_to_material_order_rev.get(fileID, meta.prefab_fileid_to_material_order_rev.get(fileID, PackedInt32Array()))
var current_materials: Array
current_materials.resize(len(mat_slots))
for i in range(len(mat_slots)):
current_materials[i] = current_materials_raw[mat_slots[i]]
for i in range(len(mat_slots), len(current_materials_raw)):
current_materials.append(current_materials_raw[i])
log_debug("Current mat slots " + str(mat_slots) + " materials before: " + str(current_materials))
while last_extra_material != null and (str(last_extra_material.resource_name).begins_with(prefix) or str(last_extra_material.resource_name).begins_with(new_prefix)):
if str(last_extra_material.resource_name).begins_with(new_prefix):
prefix = new_prefix
var guid_fileid = str(last_extra_material.resource_name).substr(len(prefix)).split(":")
current_materials.push_back(meta.get_godot_resource([null, guid_fileid[1].to_int(), guid_fileid[0], null]))
material_idx += 1
new_prefix = material_prefix + str(material_idx) + ":"
#material_idx_to_extra_material[material_idx] = last_extra_material
last_extra_material = last_extra_material.next_pass
if material_idx == old_surface_count - 1:
assert(last_extra_material != null)
current_materials.push_back(last_extra_material)
material_idx += 1
var new_materials_size = props.get("_materials_size", material_idx)
if props.has("_mesh"):
var mesh_ref: Array = props["_mesh_ref"]
var mesh_meta: Resource = meta.lookup_meta(mesh_ref)
if mesh_meta != null:
meta.fileid_to_material_order_rev[fileID] = mesh_meta.fileid_to_material_order_rev.get(mesh_ref[1], PackedInt32Array())
log_debug("GET " + str(fileID) + ": " + str(mesh_ref[1]) + " from " + str(mesh_meta.fileid_to_material_order_rev.get(mesh_ref[1])))
node.mesh = props.get("_mesh")
node.material_override = null
if props.has("_lightmap_static"):
if props["_lightmap_static"]:
var has_uv2: bool = false
if node.mesh is ArrayMesh:
var array_mesh := node.mesh as ArrayMesh
has_uv2 = 0 != (array_mesh.surface_get_format(0) & Mesh.ARRAY_FORMAT_TEX_UV2)
if node.mesh is PrimitiveMesh:
var prim_mesh := node.mesh as PrimitiveMesh
prim_mesh.add_uv2 = true
has_uv2 = true
if has_uv2:
node.gi_mode = GeometryInstance3D.GI_MODE_STATIC
else:
node.gi_mode = GeometryInstance3D.GI_MODE_DYNAMIC
else:
# GI_MODE_DISABLED seems buggy and ignores light probes.
node.gi_mode = GeometryInstance3D.GI_MODE_DYNAMIC
mat_slots = meta.fileid_to_material_order_rev.get(fileID, meta.prefab_fileid_to_material_order_rev.get(fileID, PackedInt32Array()))
current_materials.resize(new_materials_size)
for i in range(new_materials_size):
var idx = mat_slots[i] if i < len(mat_slots) else i
if idx < new_materials_size:
current_materials[idx] = props.get("_materials/" + str(i), current_materials[i])
log_debug("After mat slots " + str(mat_slots) + " materials after: " + str(current_materials))
var new_surface_count: int = 0 if node.mesh == null else node.mesh.get_surface_count()
if new_surface_count != 0 and node.mesh != null:
if new_materials_size < new_surface_count:
for i in range(new_materials_size, new_surface_count):
node.set_surface_override_material(i, meta.get_database().truncated_material_reference)
for i in range(new_materials_size):
node.set_surface_override_material(i, current_materials[i])
# surface_get_material
#for i in range(new_surface_count)
# for i in range():
# node.material_override
#else:
# if new_materials_size < new_surface_count:
func convert_properties(node: Node, uprops: Dictionary) -> Dictionary:
return convert_properties_component(node, uprops)
func convert_properties_component(node: Node, uprops: Dictionary) -> Dictionary:
return {}
static func get_ref(uprops: Dictionary, key: String) -> Array:
var ref: Variant = uprops.get(key, null)
if typeof(ref) == TYPE_ARRAY:
return ref
return [null, 0, "", 0]
func get_vector(uprops: Dictionary, key: String, dfl := Vector3.ZERO) -> Variant:
if uprops.has(key):
return uprops.get(key)
# log_debug("key is " + str(key) + "; " + str(uprops))
if uprops.has(key + ".x") or uprops.has(key + ".y") or uprops.has(key + ".z"):
var xreturn: Vector3 = Vector3(uprops.get(key + ".x", dfl.x), uprops.get(key + ".y", dfl.y), uprops.get(key + ".z", dfl.z))
# log_debug("xreturn is " + str(xreturn))
return xreturn
return null
static func get_quat(uprops: Dictionary, key: String, dfl := Quaternion.IDENTITY) -> Variant:
if uprops.has(key):
return uprops.get(key)
if uprops.has(key + ".x") or uprops.has(key + ".y") or uprops.has(key + ".z") or uprops.has(key + ".w"):
return Quaternion(uprops.get(key + ".x", dfl.x), uprops.get(key + ".y", dfl.y), uprops.get(key + ".z", dfl.z), uprops.get(key + ".w", dfl.w)).normalized()
return null
# Prefab source properties: Component and GameObject sub-types only:
# version 2018+:
# m_CorrespondingSourceObject: {fileID: 100176, guid: ca6da198c98777940835205234d6323d, type: 3}
# m_PrefabInstance: {fileID: 2493014228082835901}
# m_PrefabAsset: {fileID: 0}
# (m_PrefabAsset is always(?) 0 no matter what. I guess we can ignore it?
# version 2017-:
# m_PrefabParentObject: {fileID: 4504365477183010, guid: 52b062a91263c0844b7557d84ca92dbd, type: 2}
# m_PrefabInternal: {fileID: 15226381}
var prefab_source_object: Array:
get:
# new: m_CorrespondingSourceObject; old: m_PrefabParentObject
return keys.get("m_CorrespondingSourceObject", keys.get("m_PrefabParentObject", [null, 0, "", 0]))
var prefab_instance: Array:
get:
# new: m_PrefabInstance; old: m_PrefabInternal
return keys.get("m_PrefabInstance", keys.get("m_PrefabInternal", [null, 0, "", 0]))
var is_non_stripped_prefab_reference: bool:
get:
# Might be some 5.6 content. See arktoon Shaders/ExampleScene
# non-stripped prefab references are allowed to override properties.
return not is_stripped and not (prefab_source_object[1] == 0 or prefab_instance[1] == 0)
var is_prefab_reference: bool:
get:
if not is_stripped:
#if not (prefab_source_object[1] == 0 or prefab_instance[1] == 0):
# log_debug(str(self) + " WITHIN " + str(self.meta.guid) + " / " + str(self.meta.path) + " keys:" + str(self.keys))
pass #assert (prefab_source_object[1] == 0 or prefab_instance[1] == 0)
else:
# Might have source object=0 if the object is a dummy / broken prefab?
pass # assert (prefab_source_object[1] != 0 and prefab_instance[1] != 0)
return prefab_source_object[1] != 0 and prefab_instance[1] != 0
func get_component_key() -> Variant:
if self.utype == 114:
return monoscript.convert_unidot_ref_to_npidentifier(self.keys["m_Script"])
return self.utype
var children_refs: Array:
get:
return keys.get("m_Children", [])
### ================ ASSET TYPES ================
# FIXME: All of these are native Godot types. I'm not sure if these types are needed or warranted.
class UnidotMesh:
extends UnidotObject
func get_primitive_format(submesh: Dictionary) -> int:
match submesh.get("topology", 0):
0:
return Mesh.PRIMITIVE_TRIANGLES
2:
return Mesh.PRIMITIVE_TRIANGLES # quad meshes handled specially later
3:
return Mesh.PRIMITIVE_LINES
4:
return Mesh.PRIMITIVE_LINE_STRIP
5:
return Mesh.PRIMITIVE_POINTS
_:
log_fail(str(self) + ": Unknown primitive format " + str(submesh.get("topology", 0)))
return Mesh.PRIMITIVE_TRIANGLES
func get_godot_type() -> String:
return "Mesh"
func get_extra_resources() -> Dictionary:
if binds.is_empty():
return {}
return {-self.fileID: ".skin.tres"}
func dict_to_matrix(b: Dictionary) -> Transform3D:
return (
Transform3D.FLIP_X.affine_inverse()
* Transform3D(
Vector3(b.get("e00"), b.get("e10"), b.get("e20")),
Vector3(b.get("e01"), b.get("e11"), b.get("e21")),
Vector3(b.get("e02"), b.get("e12"), b.get("e22")),
Vector3(b.get("e03"), b.get("e13"), b.get("e23")),
)
* Transform3D.FLIP_X
)
func get_extra_resource(fileID: int) -> Resource: #Skin:
var sk: Skin = Skin.new()
var idx: int = 0
for b in binds:
sk.add_bind(idx, dict_to_matrix(b))
idx += 1
return sk
func create_godot_resource() -> Resource: #ArrayMesh:
var vertex_buf: RefCounted = get_vertex_data()
var index_buf: RefCounted = get_index_data()
var vertex_layout: Dictionary = vertex_layout_info
var channel_info_array: Array = vertex_layout.get("m_Channels", [])
# https://docs.unity3d.com/2019.4/Documentation/ScriptReference/Rendering.VertexAttribute.html
var to_godot_mesh_channels: Array = [ArrayMesh.ARRAY_VERTEX, ArrayMesh.ARRAY_NORMAL, ArrayMesh.ARRAY_TANGENT, ArrayMesh.ARRAY_COLOR, ArrayMesh.ARRAY_TEX_UV, ArrayMesh.ARRAY_TEX_UV2, ArrayMesh.ARRAY_CUSTOM0, ArrayMesh.ARRAY_CUSTOM1, ArrayMesh.ARRAY_CUSTOM2, ArrayMesh.ARRAY_CUSTOM3, -1, -1, ArrayMesh.ARRAY_WEIGHTS, ArrayMesh.ARRAY_BONES]
# Old vertex layout is probably stable since Unidot 5.0
if vertex_layout.get("serializedVersion", 1) < 2:
# Old layout seems to have COLOR at the end.
to_godot_mesh_channels = [ArrayMesh.ARRAY_VERTEX, ArrayMesh.ARRAY_NORMAL, ArrayMesh.ARRAY_TANGENT, ArrayMesh.ARRAY_TEX_UV, ArrayMesh.ARRAY_TEX_UV2, ArrayMesh.ARRAY_CUSTOM0, ArrayMesh.ARRAY_CUSTOM1, ArrayMesh.ARRAY_COLOR]
var tmp: Array = self.pre2018_skin
var pre2018_weights_buf: PackedFloat32Array = tmp[0]
var pre2018_bones_buf: PackedInt32Array = tmp[1]
var surf_idx: int = 0
var total_vertex_count: int = vertex_layout.get("m_VertexCount", 0)
var idx_format: int = keys.get("m_IndexFormat", 0)
var arr_mesh = ArrayMesh.new()
var stream_strides: Array = [0, 0, 0, 0]
var stream_offsets: Array = [0, 0, 0, 0]
if len(to_godot_mesh_channels) != len(channel_info_array):
log_fail("Unidot has the wrong number of vertex channels: " + str(len(to_godot_mesh_channels)) + " vs " + str(len(channel_info_array)))
for array_idx in range(len(to_godot_mesh_channels)):
var channel_info: Dictionary = channel_info_array[array_idx]
stream_strides[channel_info.get("stream", 0)] += (((channel_info.get("dimension", 4) * aligned_byte_buffer.format_byte_width(channel_info.get("format", 0))) + 3) / 4 * 4)
for s in range(1, 4):
stream_offsets[s] = stream_offsets[s - 1] + (total_vertex_count * stream_strides[s - 1] + 15) / 16 * 16
for submesh in submeshes:
var surface_arrays: Array = []
surface_arrays.resize(ArrayMesh.ARRAY_MAX)
var surface_index_buf: PackedInt32Array
if idx_format == 0:
surface_index_buf = index_buf.uint16_subarray(submesh.get("firstByte", 0), submesh.get("indexCount", -1))
else:
surface_index_buf = index_buf.uint32_subarray(submesh.get("firstByte", 0), submesh.get("indexCount", -1))
if submesh.get("topology", 0) == 2:
# convert quad mesh to tris
var new_buf: PackedInt32Array = PackedInt32Array()
new_buf.resize(len(surface_index_buf) / 4 * 6)
var quad_idx = [0, 1, 2, 2, 1, 3]
var range_6: Array = [0, 1, 2, 3, 4, 5]
var i: int = 0
var ilen: int = len(surface_index_buf) / 4
while i < ilen:
for el in range_6:
new_buf[i * 6 + el] = surface_index_buf[i * 4 + quad_idx[el]]
i += 1
surface_index_buf = new_buf
log_debug("Index count " + str(len(surface_index_buf)) + " from byte " + str(submesh.get("firstByte", 0)) + " count " + str(submesh.get("indexCount", -1)))
var deltaVertex: int = submesh.get("firstVertex", 0)
var baseFirstVertex: int = submesh.get("baseVertex", 0) + deltaVertex
var vertexCount: int = submesh.get("vertexCount", 0)
log_debug("baseFirstVertex " + str(baseFirstVertex) + " baseVertex " + str(submesh.get("baseVertex", 0)) + " deltaVertex " + str(deltaVertex) + " index0 " + str(surface_index_buf[0]))
if deltaVertex != 0:
var i: int = 0
var ilen: int = len(surface_index_buf)
while i < ilen:
surface_index_buf[i] -= deltaVertex
i += 1
if not pre2018_weights_buf.is_empty():
surface_arrays[ArrayMesh.ARRAY_WEIGHTS] = pre2018_weights_buf.slice(baseFirstVertex * 4, (vertexCount + baseFirstVertex) * 4)
surface_arrays[ArrayMesh.ARRAY_BONES] = pre2018_bones_buf.slice(baseFirstVertex * 4, (vertexCount + baseFirstVertex) * 4)
var compress_flags: int = 0
for array_idx in range(len(to_godot_mesh_channels)):
var godot_array_type = to_godot_mesh_channels[array_idx]
if godot_array_type == -1:
continue
var channel_info: Dictionary = channel_info_array[array_idx]
var stream: int = channel_info.get("stream", 0)
var offset: int = channel_info.get("offset", 0) + stream_offsets[stream] + baseFirstVertex * stream_strides[stream]
var format: int = channel_info.get("format", 0)
var dimension: int = channel_info.get("dimension", 4)
if dimension <= 0:
continue
match godot_array_type:
ArrayMesh.ARRAY_BONES:
if dimension == 8:
compress_flags |= ArrayMesh.ARRAY_FLAG_USE_8_BONE_WEIGHTS
log_debug("Do bones int")
surface_arrays[godot_array_type] = vertex_buf.formatted_int_subarray(format, offset, dimension * vertexCount, stream_strides[stream], dimension)
ArrayMesh.ARRAY_WEIGHTS:
log_debug("Do weights int")
surface_arrays[godot_array_type] = vertex_buf.formatted_float_subarray(format, offset, dimension * vertexCount, stream_strides[stream], dimension)
ArrayMesh.ARRAY_VERTEX, ArrayMesh.ARRAY_NORMAL:
log_debug("Do vertex or normal vec3 " + str(godot_array_type) + " " + str(format))
surface_arrays[godot_array_type] = vertex_buf.formatted_vector3_subarray(Vector3(-1, 1, 1), format, offset, vertexCount, stream_strides[stream], dimension)
ArrayMesh.ARRAY_TANGENT:
log_debug("Do tangent float " + str(godot_array_type) + " " + str(format))
surface_arrays[godot_array_type] = vertex_buf.formatted_tangent_subarray(format, offset, vertexCount, stream_strides[stream], dimension)
ArrayMesh.ARRAY_COLOR:
log_debug("Do color " + str(godot_array_type) + " " + str(format))
surface_arrays[godot_array_type] = vertex_buf.formatted_color_subarray(format, offset, vertexCount, stream_strides[stream], dimension)
ArrayMesh.ARRAY_TEX_UV, ArrayMesh.ARRAY_TEX_UV2:
log_debug("Do uv " + str(godot_array_type) + " " + str(format))
log_debug("Offset " + str(offset) + " = " + str(channel_info.get("offset", 0)) + "," + str(stream_offsets[stream]) + "," + str(baseFirstVertex) + "," + str(stream_strides[stream]) + "," + str(dimension))
surface_arrays[godot_array_type] = vertex_buf.formatted_vector2_subarray(format, offset, vertexCount, stream_strides[stream], dimension, true)
log_debug("triangle 0: " + str(surface_arrays[godot_array_type][surface_index_buf[0]]) + ";" + str(surface_arrays[godot_array_type][surface_index_buf[1]]) + ";" + str(surface_arrays[godot_array_type][surface_index_buf[2]]))
ArrayMesh.ARRAY_CUSTOM0, ArrayMesh.ARRAY_CUSTOM1, ArrayMesh.ARRAY_CUSTOM2, ArrayMesh.ARRAY_CUSTOM3:
pass # Custom channels are currently broken in Godot master:
ArrayMesh.ARRAY_MAX: # ARRAY_MAX is a placeholder to disable this
log_debug("Do custom " + str(godot_array_type) + " " + str(format))
var custom_shift = ((ArrayMesh.ARRAY_FORMAT_CUSTOM1_SHIFT - ArrayMesh.ARRAY_FORMAT_CUSTOM0_SHIFT) * (godot_array_type - ArrayMesh.ARRAY_CUSTOM0)) + ArrayMesh.ARRAY_FORMAT_CUSTOM0_SHIFT
if format == FORMAT_UNORM8 or format == FORMAT_SNORM8:
# assert(dimension == 4) # Unidot docs says always word aligned, so I think this means it is guaranteed to be 4.
surface_arrays[godot_array_type] = vertex_buf.formatted_uint8_subarray(format, offset, 4 * vertexCount, stream_strides[stream], 4)
compress_flags |= ((ArrayMesh.ARRAY_CUSTOM_RGBA8_UNORM if format == FORMAT_UNORM8 else ArrayMesh.ARRAY_CUSTOM_RGBA8_SNORM) << custom_shift)
elif format == FORMAT_FLOAT16:
assert(dimension == 2 or dimension == 4) # Unidot docs says always word aligned, so I think this means it is guaranteed to be 2 or 4.
surface_arrays[godot_array_type] = vertex_buf.formatted_uint8_subarray(format, offset, dimension * vertexCount * 2, stream_strides[stream], dimension * 2)
compress_flags |= ((ArrayMesh.ARRAY_CUSTOM_RG_HALF if dimension == 2 else ArrayMesh.ARRAY_CUSTOM_RGBA_HALF) << custom_shift)
# We could try to convert SNORM16 and UNORM16 to float16 but that sounds confusing and complicated.
else:
assert(dimension <= 4)
surface_arrays[godot_array_type] = vertex_buf.formatted_float_subarray(format, offset, dimension * vertexCount, stream_strides[stream], dimension)
compress_flags |= (ArrayMesh.ARRAY_CUSTOM_R_FLOAT + (dimension - 1)) << custom_shift
#firstVertex: 1302
#vertexCount: 38371
surface_arrays[ArrayMesh.ARRAY_INDEX] = surface_index_buf
var primitive_format: int = get_primitive_format(submesh)
#var f= FileAccess.open("temp.temp", FileAccess.WRITE)
#f.store_string(str(surface_arrays))
#f.flush()
#f = null
for i in range(ArrayMesh.ARRAY_MAX):
log_debug("Array " + str(i) + ": length=" + (str(len(surface_arrays[i])) if typeof(surface_arrays[i]) != TYPE_NIL else "NULL"))
log_debug("here are some flags " + str(compress_flags))
arr_mesh.add_surface_from_arrays(primitive_format, surface_arrays, [], {}, compress_flags)
# arr_mesh.set_custom_aabb(local_aabb)
arr_mesh.resource_name = self.name
return arr_mesh
var local_aabb: AABB:
get:
log_debug(str(typeof(keys.get("m_LocalAABB", {}).get("m_Center"))) + "/" + str(keys.get("m_LocalAABB", {}).get("m_Center")))
return AABB(keys.get("m_LocalAABB", {}).get("m_Center") * Vector3(-1, 1, 1), keys.get("m_LocalAABB", {}).get("m_Extent"))
var pre2018_skin: Array:
get:
var skin_vertices = keys.get("m_Skin", [])
var ret = [PackedFloat32Array(), PackedInt32Array()]
# FIXME: Godot bug with F32Array. ret[0].resize(len(skin_vertices) * 4)
ret[1].resize(len(skin_vertices) * 4)
var i = 0
for vert in skin_vertices:
ret[0].push_back(vert.get("weight[0]"))
ret[0].push_back(vert.get("weight[1]"))
ret[0].push_back(vert.get("weight[2]"))
ret[0].push_back(vert.get("weight[3]"))
#ret[0][i] = vert.get("weight[0]")
#ret[0][i + 1] = vert.get("weight[1]")
#ret[0][i + 2] = vert.get("weight[2]")
#ret[0][i + 3] = vert.get("weight[3]")
ret[1][i] = vert.get("boneIndex[0]")
ret[1][i + 1] = vert.get("boneIndex[1]")
ret[1][i + 2] = vert.get("boneIndex[2]")
ret[1][i + 3] = vert.get("boneIndex[3]")
i += 4
return ret
var submeshes: Array:
get:
return keys.get("m_SubMeshes", [])
var binds: Array:
get:
return keys.get("m_BindPose", [])
var vertex_layout_info: Dictionary:
get:
return keys.get("m_VertexData", {})
func get_godot_extension() -> String:
return ".mesh"
func get_vertex_data() -> RefCounted:
return aligned_byte_buffer.new(keys.get("m_VertexData", ""))
func get_index_data() -> RefCounted:
return aligned_byte_buffer.new(keys.get("m_IndexBuffer", ""))
class UnidotMaterial:
extends UnidotObject
# Old:
# m_Colors:
# - _EmissionColor: {r: 0, g: 0, b: 0, a: 0}
# - _Color: {r: 1, g: 1, b: 1, a: 1}
# [{_EmissionColor:Color.TRANSPARENT,_Color:Color.WHITE}]
# New:
# m_Colors:
# data:
# first:
# name: _EmissionColor
# second: {r: 0, g: 0, b: 0, a: 0}
# data:
# first:
# name: _Color
# second: {r: 1, g: 1, b: 1, a: 1}
# ...
# [{first:{name:_EmissionColor},second:Color.TRANSPARENT},{first:{name:_Color},second:Color.WHITE}]
func get_float_properties() -> Dictionary:
var flts = keys.get("m_SavedProperties", {}).get("m_Floats", [])
var ret = {}.duplicate()
# log_debug("material floats: " + str(flts))
for dic in flts:
if len(dic) == 2 and dic.has("first") and dic.has("second"):
ret[dic["first"]["name"]] = dic["second"]
else:
for key in dic:
ret[key] = dic.get(key)
return ret
func get_color_properties() -> Dictionary:
var cols = keys.get("m_SavedProperties", {}).get("m_Colors", [])
var ret = {}.duplicate()
for dic in cols:
if len(dic) == 2 and dic.has("first") and dic.has("second"):
ret[dic["first"]["name"]] = dic["second"]
else:
for key in dic:
ret[key] = dic.get(key)
return ret
func get_tex_properties() -> Dictionary:
var texs = keys.get("m_SavedProperties", {}).get("m_TexEnvs", [])
var ret = {}.duplicate()
for dic in texs:
if len(dic) == 2 and dic.has("first") and dic.has("second"):
ret[dic["first"]["name"]] = dic["second"]
else:
for key in dic:
ret[key] = dic.get(key)
return ret
func get_texture_ref(texProperties: Dictionary, name: String) -> Array:
var env = texProperties.get(name, {})
return env.get("m_Texture", [null, 0, "", 0])
func get_texture(texProperties: Dictionary, name: String) -> Texture:
var texref: Array = get_texture_ref(texProperties, name)
if not texref.is_empty():
return meta.get_godot_resource(texref)
return null
func get_texture_scale(texProperties: Dictionary, name: String) -> Vector3:
var env = texProperties.get(name, {})
var scale: Vector2 = env.get("m_Scale", Vector2(1, 1))
return Vector3(scale.x, scale.y, 0.0)
func get_texture_offset(texProperties: Dictionary, name: String) -> Vector3:
var env = texProperties.get(name, {})
var offset: Vector2 = env.get("m_Offset", Vector2(0, 0))
return Vector3(offset.x, offset.y, 0.0)
func get_color(colorProperties: Dictionary, name: String, dfl: Color) -> Color:
var col: Color = colorProperties.get(name, dfl)
return col
func get_float(floatProperties: Dictionary, name: String, dfl: float) -> float:
var ret: float = floatProperties.get(name, dfl)
return ret
func get_vector_from_color(colorProperties: Dictionary, name: String, dfl: Color) -> Plane:
var col: Color = colorProperties.get(name, dfl)
return Plane(Vector3(col.r, col.g, col.b), col.a)
func get_keywords() -> Dictionary:
var ret: Dictionary = {}.duplicate()
var kwd = keys.get("m_ShaderKeywords", "")
if typeof(kwd) == TYPE_STRING:
for x in kwd.split(" "):
ret[x] = true
var validkws: Array = keys.get("m_ValidKeywords", [])
for x in validkws:
ret[str(x)] = true
var invalidkws: Array = keys.get("m_InvalidKeywords", [])
for x in invalidkws:
# Keywords from before the material was switched to another shader.
# Since we don't parse shaders, this will sometimes give the equivalent Standard shader keywords.
ret[str(x)] = true
return ret
func get_godot_type() -> String:
return "StandardMaterial3D"
func create_godot_resource() -> Resource: #Material:
#log_debug("keys: " + str(keys))
var kws = get_keywords()
var floatProperties = get_float_properties()
#log_debug(str(floatProperties))
var texProperties = get_tex_properties()
#log_debug(str(texProperties))
var colorProperties = get_color_properties()
#log_debug(str(colorProperties))
var ret = StandardMaterial3D.new()
ret.resource_name = self.name
# FIXME: Kinda hacky since transparent stuff doesn't always draw depth in Unidot
# But it seems to workaround a problem with some materials for now.
ret.depth_draw_mode = true ##### BaseMaterial3D.DEPTH_DRAW_ALWAYS
ret.albedo_color = get_color(colorProperties, "_Color", Color.WHITE)
var albedo_textures_to_try = ["_MainTex", "_Tex", "_Albedo", "_Diffuse", "_BaseColor", "_BaseColorMap"]
for name in texProperties:
if albedo_textures_to_try.has(name):
continue
if not name.ends_with("Map"):
albedo_textures_to_try.append(name)
# Pick a random non-null texture property as albedo. Prefer texture slots not ending with "Map"
for name in texProperties:
if name == "_BumpMap" or name == "_OcclusionMap" or name == "_MetallicGlossMap" or name == "_ParallaxMap":
continue
if name.ends_with("ColorMap") or name.ends_with("BaseMap"):
albedo_textures_to_try.append(name)
for name in albedo_textures_to_try:
var env = texProperties.get(name, {})
var texref: Array = env.get("m_Texture", [null, 0, "", 0])
if not texref.is_empty():
ret.albedo_texture = meta.get_godot_resource(texref)
if ret.albedo_texture != null:
log_debug("Trying to get albedo from " + str(name) + ": " + str(ret.albedo_texture))
ret.uv1_scale = get_texture_scale(texProperties, name)
ret.uv1_offset = get_texture_offset(texProperties, name)
break
if ret.albedo_texture == null:
ret.uv1_scale = get_texture_scale(texProperties, "_MainTex")
ret.uv1_offset = get_texture_offset(texProperties, "_MainTex")
# TODO: ORM not yet implemented.
if true: # kws.get("_NORMALMAP", false):
ret.normal_texture = get_texture(texProperties, "_BumpMap")
ret.normal_scale = get_float(floatProperties, "_BumpScale", 1.0)
if ret.normal_texture != null:
ret.normal_enabled = true
if kws.get("_EMISSION", false):
var emis_vec: Plane = get_vector_from_color(colorProperties, "_EmissionColor", Color.BLACK)
var emis_mag = max(emis_vec.x, max(emis_vec.y, emis_vec.z))
ret.emission = Color.BLACK
if emis_mag > 0.01:
ret.emission_enabled = true
ret.emission = Color(emis_vec.x / emis_mag, emis_vec.y / emis_mag, emis_vec.z / emis_mag).linear_to_srgb()
ret.emission_energy = emis_mag
ret.emission_texture = get_texture(texProperties, "_EmissionMap")
if ret.emission_texture != null:
ret.emission_operator = BaseMaterial3D.EMISSION_OP_MULTIPLY
if true: # kws.get("_PARALLAXMAP", false):
ret.heightmap_texture = get_texture(texProperties, "_ParallaxMap")
if ret.heightmap_texture != null:
ret.heightmap_enabled = true
# Godot generated standard shader code looks something like this:
# float depth = 1.0 - texture(texture_heightmap, base_uv).r;
# vec2 ofs = base_uv - view_dir.xy * depth * heightmap_scale * 0.01;
# ------
# Note in particular the * 0.01 multiplier.
# Unfortunately, Godot does not have a heightmap bias setting (such as 0.5)
# Therefore, it is not possible to represent a heightmap completely accurately
# And we must pick a direction: positive or negative. In this case I choose negative.
# Which causes the heightmap to "pop out" of the surface.
ret.heightmap_scale = -100.0 * get_float(floatProperties, "_Parallax", 1.0)
if kws.get("_SPECULARHIGHLIGHTS_OFF", false):
ret.specular_mode = BaseMaterial3D.SPECULAR_DISABLED
if kws.get("_GLOSSYREFLECTIONS_OFF", false):
pass
if kws.get("_DOUBLESIDED_ON", false): # HDRP-compatible materials should set this.
ret.cull_mode = BaseMaterial3D.CULL_DISABLED
var occlusion = get_texture(texProperties, "_OcclusionMap")
if occlusion != null:
ret.ao_enabled = true
ret.ao_texture = occlusion
ret.ao_light_affect = get_float(floatProperties, "_OcclusionStrength", 1.0) # why godot defaults to 0???
ret.ao_texture_channel = BaseMaterial3D.TEXTURE_CHANNEL_GREEN
var metallic_texture: Texture = null
var use_glossmap := false
if true: # kws.get("_METALLICGLOSSMAP"):
var metallic_gloss_texture_ref: Array = get_texture_ref(texProperties, "_MetallicGlossMap")
if metallic_gloss_texture_ref.is_empty() or metallic_gloss_texture_ref[1] == 0:
metallic_gloss_texture_ref = get_texture_ref(texProperties, "_MetallicSmoothness")
if not metallic_gloss_texture_ref.is_empty() and metallic_gloss_texture_ref[1] != 0:
metallic_gloss_texture_ref[1] = -metallic_gloss_texture_ref[1]
if not is_equal_approx(get_float(floatProperties, "_GlossMapScale", 1.0), 0.0):
metallic_texture = meta.get_godot_resource(metallic_gloss_texture_ref, false)
log_debug("Found metallic roughness texture " + str(metallic_gloss_texture_ref) + " => " + str(metallic_texture))
use_glossmap = true
if metallic_texture == null:
if use_glossmap:
log_debug("Load roughness " + str(load("res://Assets/ArchVizPRO Interior Vol.6/3D MATERIAL/Tiles_White/Tiles_White_metallic.roughness.png")))
log_warn("Unable to load metallic roughness texture. Trying metallic gloss.", "_MetallicGlossMap", metallic_gloss_texture_ref)
metallic_gloss_texture_ref[1] = -metallic_gloss_texture_ref[1]
metallic_texture = meta.get_godot_resource(metallic_gloss_texture_ref)
log_debug("Found metallic gloss texture " + str(metallic_gloss_texture_ref) + " => " + str(metallic_texture))
use_glossmap = false
ret.metallic_texture = metallic_texture
ret.metallic = get_float(floatProperties, "_Metallic", 0.0)
ret.metallic_texture_channel = BaseMaterial3D.TEXTURE_CHANNEL_RED
if use_glossmap:
ret.roughness_texture = metallic_texture
ret.roughness_texture_channel = BaseMaterial3D.TEXTURE_CHANNEL_ALPHA
ret.roughness = 1.0 # We scaled down the roughness in code.
# TODO: Glossiness: invert color channels??
if metallic_texture == null:
# UnidotStandardInput.cginc ignores _Glossiness if _METALLICGLOSSMAP.
ret.roughness = 1.0 - get_float(floatProperties, "_Glossiness", 0.0)
if kws.get("_ALPHATEST_ON"):
ret.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA_SCISSOR
var cutoff: float = get_float(floatProperties, "_Cutoff", 0.0)
if cutoff > 0.0:
ret.alpha_scissor_threshold = cutoff
elif kws.get("_ALPHABLEND_ON") or kws.get("_ALPHAPREMULTIPLY_ON"):
# FIXME: No premultiply
ret.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
# Godot's detail map is a bit lacking right now...
#if kws.get("_DETAIL_MULX2"):
# ret.detail_enabled = true
# ret.detail_blend_mode = BaseMaterial3D.BLEND_MODE_MUL
assign_object_meta(ret)
return ret
func bake_roughness_texture_if_needed(tmp_path: String, guid_to_pkgasset: Dictionary, stage2_dict_lock: Mutex, stage2_extra_asset_dict: Dictionary) -> String:
var kws = get_keywords()
var floatProperties = get_float_properties()
var texProperties = get_tex_properties()
# Note that this must be pre-baked into the texture to bring it towards 1.
# _GlossMapScale ????
var glossiness_value: float = get_float(floatProperties, "_GlossMapScale", 1.0)
if is_equal_approx(glossiness_value, 0.0):
log_debug("Material has 0 _GlossMapScale")
return "" # We can ignore the texture
var metallic_gloss_texture_ref: Array = get_texture_ref(texProperties, "_MetallicGlossMap")
if metallic_gloss_texture_ref.is_empty() or metallic_gloss_texture_ref[1] == 0:
metallic_gloss_texture_ref = get_texture_ref(texProperties, "_MetallicSmoothness")
# Not any more: Material has _METALLICGLOSSMAP enabled.
if metallic_gloss_texture_ref.is_empty() or metallic_gloss_texture_ref[1] == 0:
log_debug("Material has null _MetallicGlossMap")
# null gloss: no roughness to bake
return ""
log_debug("gloss map ref is " + str(metallic_gloss_texture_ref))
#var metallic_gloss_texture = get_texture(texProperties, "_MetallicGlossMap")
var target_meta: Object
if not metallic_gloss_texture_ref.is_empty() and guid_to_pkgasset.has(metallic_gloss_texture_ref[2]):
target_meta = guid_to_pkgasset[metallic_gloss_texture_ref[2]].parsed_meta
else:
target_meta = meta.lookup_meta(metallic_gloss_texture_ref)
if target_meta == null:
log_warn("Failed to lookup gloss texture ref", "_MetallicGlossMap", metallic_gloss_texture_ref)
return ""
target_meta.mutex.lock()
var pathname: String = target_meta.path
var roughness_filename = pathname.get_basename() + ".roughness.png"
# Sometimes multiple materials reference the same roughness texture. We to avoid generating the same texture multiple times.
stage2_dict_lock.lock()
if stage2_extra_asset_dict.has(roughness_filename):
stage2_dict_lock.unlock()
target_meta.mutex.unlock()
return ""
stage2_extra_asset_dict[roughness_filename] = true
stage2_dict_lock.unlock()
var ret: String = _bake_roughness_texture_locked(tmp_path, target_meta, roughness_filename, glossiness_value, guid_to_pkgasset)
target_meta.mutex.unlock()
return ret
func _bake_roughness_texture_locked(tmp_path: String, target_meta: Object, roughness_filename: String, glossiness_value: float, guid_to_pkgasset: Dictionary) -> String:
var pathname: String = target_meta.path
if FileAccess.file_exists(roughness_filename):
var fa := FileAccess.open(roughness_filename, FileAccess.READ)
if fa != null:
if fa.get_length() > 0:
if not target_meta.godot_resources.has(-target_meta.main_object_id):
target_meta.insert_resource_path(-target_meta.main_object_id, "res://" + roughness_filename)
log_debug("Roughness texture already exists. Modified " + str(target_meta.guid) + "/" + str(target_meta.path) + " godot_resources: " + str(target_meta.godot_resources))
return "" # Nothing new to import.
var image: Image
if FileAccess.file_exists(tmp_path + "/" + pathname):
image = Image.load_from_file(tmp_path + "/" + pathname)