-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathasset_adapter.gd
2738 lines (2521 loc) · 131 KB
/
asset_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 Resource
const object_adapter_class := preload("./object_adapter.gd")
const post_import_material_remap_script: GDScript = preload("./post_import_model.gd")
const convert_scene := preload("./convert_scene.gd")
const raw_parsed_asset := preload("./raw_parsed_asset.gd")
const bone_map_editor_plugin := preload("./bone_map_editor_plugin.gd")
const unidot_utils_class = preload("./unidot_utils.gd")
var unidot_utils = unidot_utils_class.new()
const ASSET_TYPE_YAML = 1
const ASSET_TYPE_MODEL = 2
const ASSET_TYPE_TEXTURE = 3
const ASSET_TYPE_ANIM = 4
const ASSET_TYPE_YAML_POST_MODEL = 5
const ASSET_TYPE_PREFAB = 6
const ASSET_TYPE_SCENE = 7
const ASSET_TYPE_UNKNOWN = 8
const SHOULD_CONVERT_TO_GLB: bool = false
const SILHOUETTE_FIX_THRESHOLD: float = 3.0 # 28.0
var STUB_PNG_FILE: PackedByteArray = Marshalls.base64_to_raw("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQot" + "tAAAAABJRU5ErkJggg==")
#const DEBUG_RAW_PARSED_ASSET_TYPES := ".anim.tres"
const DEBUG_RAW_PARSED_ASSET_TYPES := ".disabled"
func write_sentinel_png(sentinel_filename: String):
var f: FileAccess = FileAccess.open(sentinel_filename, FileAccess.WRITE)
f.store_buffer(STUB_PNG_FILE)
f.flush()
f.close()
f = null
class AssetHandler:
var unidot_utils = unidot_utils_class.new()
var editor_interface: EditorInterface = null
func _init():
var ep = EditorPlugin.new()
editor_interface = ep.get_editor_interface()
ep.queue_free()
class ConfigFileCompare:
extends ConfigFile
var modified: bool = false
var pkgasset: RefCounted = null
func _init(pkgasset: RefCounted):
self.pkgasset = pkgasset
func set_value_compare(section: String, key: String, value: Variant) -> bool:
var ret: bool = false
if not self.has_section_key(section, key):
pkgasset.log_debug("Added new section:" + section + " key:" + key + " : " + str(value))
ret = true
else:
var existing_val = self.get_value(section, key)
if typeof(existing_val) != typeof(value):
pkgasset.log_debug("Modified type section:" + section + " key:" + key + " : " + str(existing_val) + " => " + str(value))
ret = true
elif existing_val != value:
pkgasset.log_debug("Modified section:" + section + " key:" + key + " : " + str(existing_val) + " => " + str(value))
ret = true
modified = modified or ret
if ret:
self.set_value(section, key, value)
return ret
func was_modified() -> bool:
return modified
static func file_exists_hack(dres: DirAccess, fn: String):
if not dres.file_exists(fn):
return false
var fa = FileAccess.open(fn, FileAccess.READ)
if fa == null:
return false
return fa.get_length() != 0
func calc_existing_md5(fname: String) -> PackedByteArray:
var dres: DirAccess = DirAccess.open("res://")
if not dres.file_exists(fname):
return PackedByteArray()
var fres: FileAccess = FileAccess.open(fname, FileAccess.READ)
if fres == null:
return PackedByteArray()
var flen: int = fres.get_length()
var buf = fres.get_buffer(flen)
fres.close()
fres = null
if len(buf) != flen:
return PackedByteArray()
return calc_md5(buf)
func calc_md5(pba: PackedByteArray) -> PackedByteArray:
var md5 = HashingContext.new()
md5.start(HashingContext.HASH_MD5)
md5.update(pba)
return md5.finish()
func write_and_preprocess_asset(pkgasset: Object, tmpdir: String, thread_subdir: String) -> String:
var path: String = pkgasset.pathname
if len(path) == 0:
pkgasset.log_fail("pkgasset.pathname is empty")
var data_buf: PackedByteArray = pkgasset.asset_tar_header.get_data()
var output_path: String = self.preprocess_asset(pkgasset, tmpdir, thread_subdir, path, data_buf)
if len(output_path) == 0:
pkgasset.existing_data_md5 = calc_existing_md5(path)
pkgasset.data_md5 = calc_md5(data_buf)
if pkgasset.existing_data_md5 != pkgasset.data_md5:
var outfile: FileAccess = FileAccess.open(tmpdir + "/" + path, FileAccess.WRITE_READ)
if outfile == null:
pkgasset.log_fail("Unable to open file " + str(tmpdir + "/"+ path) + " for writing!")
else:
outfile.store_buffer(data_buf)
outfile.flush()
outfile.close()
outfile = null
output_path = pkgasset.pathname
if len(output_path) == 0:
pkgasset.log_fail("output_path became empty " + str(pkgasset.pathname))
pkgasset.log_debug("Updating file at " + output_path)
return output_path
func write_godot_import(pkgasset: Object, force_keep: bool) -> bool:
return false
func write_godot_asset(pkgasset: Object, temp_path: String) -> bool:
if pkgasset.existing_data_md5 != pkgasset.data_md5:
var dres = DirAccess.open("res://")
pkgasset.log_debug("Renaming " + temp_path + " to " + pkgasset.pathname)
dres.rename(temp_path, pkgasset.pathname)
return true
return false
func get_asset_type(pkgasset: Object) -> int:
return ASSET_TYPE_UNKNOWN
func uses_godot_importer(pkgasset: Object) -> bool:
return true
func preprocess_asset(pkgasset: Object, tmpdir: String, thread_subdir: String, path: String, data_buf: PackedByteArray, unique_texture_map: Dictionary = {}) -> String:
return ""
func about_to_import(pkgasset: Object):
pass
func finished_import(pkgasset: Object, res: Resource):
if res == null:
var dres = DirAccess.open("res://")
pkgasset.log_fail("Due to failed import, renaming " + pkgasset.pathname + " to " + pkgasset.pathname + ".failed_import")
dres.rename(pkgasset.pathname, pkgasset.pathname + ".failed_import")
else:
pkgasset.log_debug("Successfully imported " + str(pkgasset.pathname) + " as " + str(res.resource_name) + " " + str(res))
class DefaultHandler:
extends AssetHandler
pass
class ImageHandler:
extends AssetHandler
func preprocess_asset(pkgasset: Object, tmpdir: String, thread_subdir: String, path: String, data_buf: PackedByteArray, unique_texture_map: Dictionary = {}) -> String:
if len(data_buf) < 4:
pkgasset.log_fail("Empty data buf")
return ""
var user_path_base = OS.get_user_data_dir()
var is_psd: bool = (data_buf[0] == 0x38 and data_buf[1] == 0x42 and data_buf[2] == 0x50 and data_buf[3] == 0x53)
var is_tiff: bool = (data_buf[0] == 0x49 and data_buf[1] == 0x49 and data_buf[2] == 0x2A and data_buf[3] == 0x00) or (data_buf[0] == 0x4D and data_buf[1] == 0x4D and data_buf[2] == 0x00 and data_buf[3] == 0x2A)
var is_png: bool = (data_buf[0] == 0x89 and data_buf[1] == 0x50 and data_buf[2] == 0x4E and data_buf[3] == 0x47) or is_tiff
var full_output_path: String = pkgasset.pathname
if not is_png and path.get_extension().to_lower() == "png":
pkgasset.log_debug("I am a JPG pretending to be a " + str(path.get_extension()) + " " + str(path))
full_output_path = full_output_path.get_basename() + ".jpg"
elif (is_png or is_tiff or is_psd) and path.get_extension().to_lower() != "png":
pkgasset.log_debug("I am a PNG pretending to be a " + str(path.get_extension()) + " " + str(path))
full_output_path = full_output_path.get_basename() + ".png"
pkgasset.log_debug("PREPROCESS_IMAGE " + str(is_tiff or is_psd) + "/" + str(is_png) + " path " + str(path) + " to " + str(full_output_path))
var temp_output_path: String = tmpdir + "/" + full_output_path
if is_tiff or is_psd:
var ext: String = '.tif' if is_tiff else '.psd'
var outfile: FileAccess = FileAccess.open(temp_output_path.get_basename() + ext, FileAccess.WRITE_READ)
outfile.store_buffer(data_buf)
outfile.flush()
outfile.close()
outfile = null
var stdout: Array = [].duplicate()
var d = DirAccess.open("res://")
var addon_path: String = "convert" # ImageMagick installed system-wide.
if OS.get_name() == "Windows":
addon_path = post_import_material_remap_script.resource_path.get_base_dir().path_join("convert.exe")
if d.file_exists(addon_path):
addon_path = ProjectSettings.globalize_path(addon_path)
else:
pkgasset.log_warn("Not converting tiff to png because convert.exe is not present.")
addon_path = "convert.exe"
# [0] forces multi-layer files to only output the first layer. Otherwise filenames may be -0, -1, -2...
var convert_src: String = temp_output_path.get_basename() + ext + "[0]"
var convert_dst: String = temp_output_path
var convert_args: Array = [convert_src, convert_dst]
var ret = OS.execute(addon_path, convert_args, stdout)
for i in range(5):
OS.delay_msec(500)
OS.delay_msec(500)
# Hack, but I don't know what to do about this for now. The .close() is async or something.
if ret == 1 or "".join(stdout).strip_edges().find("@ error") != -1:
pkgasset.log_warn("Attempt to rerun FBX2glTF to mitigate windows file close race " + str(i) + ".")
ret = OS.execute(addon_path, convert_args, stdout)
pkgasset.log_debug("convert " + str(addon_path) + " " + str(convert_args) + " => result " + str(ret))
pkgasset.log_debug(str(stdout))
d.remove(temp_output_path.get_basename() + ext)
var res_file: FileAccess = FileAccess.open(temp_output_path, FileAccess.READ)
pkgasset.data_md5 = calc_md5(res_file.get_buffer(res_file.get_length()))
res_file.close()
res_file = null
pkgasset.existing_data_md5 = calc_existing_md5(full_output_path)
if pkgasset.existing_data_md5 == pkgasset.data_md5:
d.remove(temp_output_path)
else:
pkgasset.existing_data_md5 = calc_existing_md5(full_output_path)
pkgasset.data_md5 = calc_md5(data_buf)
if pkgasset.existing_data_md5 != pkgasset.data_md5:
var outfile: FileAccess = FileAccess.open(temp_output_path, FileAccess.WRITE_READ)
outfile.store_buffer(data_buf)
outfile.flush()
outfile.close()
outfile = null
return full_output_path
func get_asset_type(pkgasset: Object) -> int:
return ASSET_TYPE_TEXTURE
func write_godot_import(pkgasset: Object, force_keep: bool) -> bool:
var importer = pkgasset.parsed_meta.importer
var cfile = ConfigFileCompare.new(pkgasset)
if cfile.load("res://" + pkgasset.pathname + ".import") != OK:
pkgasset.log_debug("Failed to load .import config file for " + pkgasset.pathname)
cfile.set_value("remap", "path", "unidot_default_remap_path") # must be non-empty. hopefully ignored.
match importer.keys.get("textureShape", 0):
2:
cfile.set_value("remap", "type", "CompressedCubemap")
4:
cfile.set_value("remap", "type", "CompressedTexture2DArray")
8:
cfile.set_value("remap", "type", "CompressedTexture3D")
_: # 1 = standard 2D texture
cfile.set_value("remap", "type", "CompressedTexture2D")
if force_keep:
cfile.set_value("remap", "importer", "keep")
if cfile.has_section_key("remap", "type"):
cfile.erase_section_key("remap", "type")
if pkgasset.pathname.validate_filename().is_empty():
pkgasset.log_fail("pathname became empty: " + str(pkgasset.pathname))
return false
cfile.save("res://" + pkgasset.pathname + ".import")
return true
match importer.keys.get("textureShape", 0):
2:
var image_file := Image.load_from_file(pkgasset.pathname)
var wid: int = 0
var hei: int = 0
if image_file != null:
pkgasset.log_debug("Detecting Cubemap from image size " + str(image_file.get_size()))
wid = image_file.get_width()
hei = image_file.get_height()
cfile.set_value_compare("remap", "type", "CompressedCubemap")
cfile.set_value_compare("remap", "importer", "cubemap_texture")
# Godot "slices/arrangement", PROPERTY_HINT_ENUM, "1x6,2x3,3x2,6x1"
var gen_cube: int = importer.keys.get("generateCubemap", 0)
if image_file == null:
pkgasset.log_fail("Was unable to load the image file " + str(pkgasset.pathname) + " to determine cubemap format")
elif hei == wid or (gen_cube != 1 or gen_cube == 3 or gen_cube == 4):
pkgasset.log_fail("Spherical cubemap layout is not supported. Godot expects a 2x3 or 1x6 grid")
elif gen_cube == 2:
pkgasset.log_fail("Cylindrical cubemap layout is not supported. Godot expects a 2x3 or 1x6 grid")
elif float(wid) / hei > 5.5:
# Very wide, 1 tall
cfile.set_value_compare("params", "slices/arrangement", 3)
elif float(hei) / wid > 5.5:
# Very tall, 1 wide
cfile.set_value_compare("params", "slices/arrangement", 0)
elif float(hei) / wid > 1.3 and float(hei) / wid < 1.4:
pkgasset.log_fail("Cross cubemap layout is not supported. Godot expects 2x3 grid")
# More tall than wide
cfile.set_value_compare("params", "slices/arrangement", 1)
elif float(wid) / hei > 1.3 and float(wid) / hei < 1.4:
pkgasset.log_fail("Cross cubemap layout is not supported. Godot expects 3x2 grid")
# More wide than tall
cfile.set_value_compare("params", "slices/arrangement", 2)
elif float(hei) / wid > 1.4 and float(hei) / wid < 1.6:
# More tall than wide: godot compatible 2x3
cfile.set_value_compare("params", "slices/arrangement", 1)
elif float(wid) / hei > 1.4 and float(wid) / hei < 1.6:
# More wide than tall: godot compatible 3x2
cfile.set_value_compare("params", "slices/arrangement", 2)
elif float(wid) / hei > 1.9 and float(wid) / hei < 2.1:
pkgasset.log_fail("Cylinder cubemap layout is not supported. Godot expects a 2x3 or 1x6 grid")
# More wide than tall: godot compatible 3x2
cfile.set_value_compare("params", "slices/arrangement", 2)
else:
pkgasset.log_fail("Unknown cubemap layout! Godot expects a 2x3 or 1x6 grid")
4:
cfile.set_value_compare("remap", "type", "CompressedTexture2DArray")
cfile.set_value_compare("remap", "importer", "2d_array_texture")
if importer.keys.get("flipbookColumns", 0) > 0:
cfile.set_value_compare("params", "slices/horizontal", importer.keys.get("flipbookColumns", 0))
if importer.keys.get("flipbookRows", 0) > 0:
cfile.set_value_compare("params", "slices/vertical", importer.keys.get("flipbookRows", 0))
8:
cfile.set_value_compare("remap", "type", "CompressedTexture3D")
cfile.set_value_compare("remap", "importer", "3d_texture")
if importer.keys.get("flipbookColumns", 0) > 0:
cfile.set_value_compare("params", "slices/horizontal", importer.keys.get("flipbookColumns", 0))
if importer.keys.get("flipbookRows", 0) > 0:
cfile.set_value_compare("params", "slices/vertical", importer.keys.get("flipbookRows", 0))
_: # 1 = standard 2D texture
cfile.set_value_compare("remap", "type", "CompressedTexture2D")
cfile.set_value_compare("remap", "importer", "texture")
var chosen_platform = {}
for platform in importer.keys.get("platformSettings", []):
if platform.get("buildTarget", "") == "DefaultTexturePlatform":
chosen_platform = platform
for platform in importer.keys.get("platformSettings", []):
if platform.get("buildTarget", "") == "Standalone":
chosen_platform = platform
var use_tc = chosen_platform.get("textureCompression", importer.keys.get("textureCompression", 1))
var tc_level = chosen_platform.get("compressionQuality", importer.keys.get("compressionQuality", 50))
var max_texture_size = chosen_platform.get("maxTextureSize", importer.keys.get("maxTextureSize", 0))
if max_texture_size < 0:
max_texture_size = 0
#cfile.set_value("params", "import_script/path", post_import_material_remap_script.resource_path)
# TODO: If low quality (use_tc==2) then we may want to disable bptc on this file
cfile.set_value_compare("params", "compress/mode", 2 if use_tc > 0 else 0)
cfile.set_value_compare("params", "compress/bptc_ldr", 1 if use_tc == 2 else 0)
cfile.set_value_compare("params", "compress/lossy_quality", tc_level / 100.0)
var is_normal: int = importer.keys.get("bumpmap", {}).get("convertToNormalMap", 0)
if is_normal == 0:
# Detect/Enabled/Disabled
# Detect may crash Godot later on.
is_normal = 2
if importer.keys.get("textureType", 0) == 1:
is_normal = 1
cfile.set_value_compare("params", "compress/normal_map", is_normal)
cfile.set_value_compare("params", "detect_3d/compress_to", 0) # 0 = Disable (avoid crash)
# Roughness mode: Detect/Disable/Red/Green/etc.
# 1 = avoids crash later on.
# TODO: We may want an import setting to invert a channel for roughness use.
cfile.set_value_compare("params", "roughness/mode", 1)
# FIXME: No way yet to use premultiplied alpha in Godot 3D shaders
# importer.keys.get("alphaIsTransparency", 0) != 0)
cfile.set_value_compare("params", "process/premult_alpha", 0)
cfile.set_value_compare("params", "process/size_limit", max_texture_size)
cfile.set_value_compare("params", "mipmaps/generate", importer.keys.get("mipmaps", {}).get("enableMipMap", 0) != 0)
if pkgasset.pathname.validate_filename().is_empty():
pkgasset.log_fail("pathname became empty for image: " + str(pkgasset.pathname))
return false
cfile.save("res://" + pkgasset.pathname + ".import")
return cfile.was_modified()
class AudioHandler:
extends AssetHandler
var importer: String = "wav"
var resource_type: String = "AudioStreamSample"
func create_with_type(importer: String, resource_type: String):
var ret = self
ret.importer = importer
ret.resource_type = resource_type
return ret
func preprocess_asset(pkgasset: Object, tmpdir: String, thread_subdir: String, path: String, data_buf: PackedByteArray, unique_texture_map: Dictionary = {}) -> String:
return ""
func write_godot_import(pkgasset: Object, force_keep: bool) -> bool:
var importer = pkgasset.parsed_meta.importer
var cfile = ConfigFileCompare.new(pkgasset)
if cfile.load("res://" + pkgasset.pathname + ".import") != OK:
pkgasset.log_debug("Failed to load .import config file for " + pkgasset.pathname)
cfile.set_value("remap", "path", "unidot_default_remap_path") # must be non-empty. hopefully ignored.
if force_keep:
cfile.set_value("remap", "importer", "keep")
if cfile.has_section_key("remap", "type"):
cfile.erase_section_key("remap", "type")
if pkgasset.pathname.validate_filename().is_empty():
pkgasset.log_fail("pathname became empty audio: " + str(pkgasset.pathname))
return false
cfile.save("res://" + pkgasset.pathname + ".import")
return true
cfile.set_value_compare("remap", "type", self.resource_type)
cfile.set_value_compare("remap", "importer", self.importer)
# TODO "params":
# (MP3/OGG): loop=true, loop_offset=0
# (WAV): edit/loop_mode=0, edit/loop_begin=0, edit/loop_end=-1
# (WAV): compress/mode=0
# (WAV): force/8_bit, force/mono, force/max_rate, force/max_rate_hz
if pkgasset.pathname.validate_filename().is_empty():
pkgasset.log_fail("pathname became empty for audio: " + str(pkgasset.pathname))
return false
cfile.save("res://" + pkgasset.pathname + ".import")
return cfile.was_modified()
func get_asset_type(pkgasset: Object) -> int:
return ASSET_TYPE_TEXTURE
class YamlHandler:
extends AssetHandler
const tarfile := preload("./tarfile.gd")
func parse_yaml_or_binary(pkgasset: Object, temp_path: String) -> void:
var outfile: FileAccess = FileAccess.open(temp_path, FileAccess.WRITE_READ)
if outfile == null:
pkgasset.log_fail("Failed to open temporary path " + temp_path)
return
var buf: PackedByteArray = pkgasset.asset_tar_header.get_data()
outfile.store_buffer(buf)
outfile.flush()
outfile.close()
outfile = null
if len(buf) > 10 and buf[8] == 0 and buf[9] == 0:
pkgasset.parsed_asset = pkgasset.parsed_meta.parse_binary_asset(buf)
else:
var sf: Object = tarfile.StringFile.new()
sf.init(buf.get_string_from_utf8())
pkgasset.parsed_asset = pkgasset.parsed_meta.parse_asset(sf)
if pkgasset.parsed_asset == null:
pkgasset.log_fail("Parse asset failed " + pkgasset.pathname + "/" + pkgasset.guid)
func write_and_preprocess_asset(pkgasset: Object, tmpdir: String, thread_subdir: String) -> String:
# .anim assets contain nested structs for each keyframe
# If importing dozens of animations at once, godot may run out of memory.
var temp_path: String = tmpdir + "/" + pkgasset.pathname
if get_file_extension_without_early_parse(pkgasset) == "":
parse_yaml_or_binary(pkgasset, temp_path)
pkgasset.log_debug("Done with " + temp_path + "/" + pkgasset.guid)
return preprocess_asset(pkgasset, tmpdir, thread_subdir, pkgasset.pathname, PackedByteArray())
func preprocess_asset(pkgasset: Object, tmpdir: String, thread_subdir: String, path: String, data_buf: PackedByteArray, unique_texture_map: Dictionary = {}) -> String:
var early_file_ext: String = get_file_extension_without_early_parse(pkgasset)
if early_file_ext != "":
var new_pathname = pkgasset.pathname.get_basename() + early_file_ext
return new_pathname
if pkgasset.parsed_asset == null:
pkgasset.log_fail("Asset " + pkgasset.pathname + " guid " + pkgasset.parsed_meta.guid + " has was not parsed as YAML")
return ""
var main_asset: RefCounted = null
var godot_resource: Resource = null
if pkgasset.parsed_meta.main_object_id != -1 and pkgasset.parsed_meta.main_object_id != 0:
if pkgasset.parsed_asset.assets.has(pkgasset.parsed_meta.main_object_id):
main_asset = pkgasset.parsed_asset.assets[pkgasset.parsed_meta.main_object_id]
else:
pkgasset.log_fail("Asset " + pkgasset.pathname + " guid " + pkgasset.parsed_meta.guid + " missing main object id " + str(pkgasset.parsed_meta.main_object_id) + "!")
else:
pkgasset.log_fail("Asset " + pkgasset.pathname + " guid " + pkgasset.parsed_meta.guid + " has no main object id!")
var new_pathname: String = pkgasset.pathname
if main_asset != null:
new_pathname = pkgasset.pathname.get_basename() + pkgasset.parsed_meta.fixup_godot_extension(main_asset.get_godot_extension()) # ".mat.tres"
return new_pathname
func get_asset_type(pkgasset: Object) -> int:
var extn: String = pkgasset.orig_pathname.get_extension().to_lower()
if extn == "scene":
return ASSET_TYPE_SCENE
if extn == "prefab":
return ASSET_TYPE_PREFAB
if extn == "anim":
# FIXME: need to find PPtr dependencies and toposort.
return ASSET_TYPE_ANIM
if extn == "controller" or extn == "overridecontroller":
return ASSET_TYPE_YAML_POST_MODEL
if pkgasset.parsed_meta.type_to_fileids.has("TerrainData"):
# TerrainData depends on prefab assets.
return ASSET_TYPE_PREFAB
return ASSET_TYPE_YAML
func uses_godot_importer(pkgasset: Object) -> bool:
return false
func get_file_extension_without_early_parse(pkgasset: Object) -> String:
if get_asset_type(pkgasset) == ASSET_TYPE_ANIM:
# If we parse too many .anim files which are too big, we can use too much RAM
if pkgasset.asset_tar_header.get_size() > 50000:
# Returning a file extension here short-circuits the early parse.
# So we will parse the big animation files in the main thread one-by-one.
return pkgasset.parsed_meta.fixup_godot_extension(".anim.tres")
return ""
func write_godot_asset(pkgasset: Object, temp_path: String) -> bool:
if get_file_extension_without_early_parse(pkgasset) != "":
parse_yaml_or_binary(pkgasset, temp_path)
if pkgasset.parsed_asset == null:
pkgasset.log_fail("Asset " + pkgasset.pathname + " guid " + pkgasset.parsed_meta.guid + " has was not parsed as YAML")
return false
var main_asset: RefCounted = null
var godot_resource: Resource = null
if pkgasset.parsed_meta.main_object_id != 0 and pkgasset.parsed_asset.assets.has(pkgasset.parsed_meta.main_object_id):
main_asset = pkgasset.parsed_asset.assets[pkgasset.parsed_meta.main_object_id]
else:
pkgasset.log_fail("Asset " + pkgasset.pathname + " guid " + pkgasset.parsed_meta.guid + " has no main object id " + str(pkgasset.parsed_meta.main_object_id) + "!")
var extra_resources: Dictionary = {}
if main_asset != null:
extra_resources = main_asset.get_extra_resources()
for extra_asset_fileid in extra_resources:
var file_ext: String = pkgasset.parsed_meta.fixup_godot_extension(extra_resources.get(extra_asset_fileid))
var created_res: Resource = main_asset.get_extra_resource(extra_asset_fileid)
var basename: String = pkgasset.pathname.trim_suffix(".res").trim_suffix(".tres").get_basename()
pkgasset.log_debug("Creating " + str(extra_asset_fileid) + " is " + str(created_res) + " at " + str(basename + file_ext))
if created_res != null:
var new_pathname: String = "res://" + basename + file_ext # ".skin.tres"
created_res.resource_name = basename.get_file() + file_ext
unidot_utils.save_resource(created_res, new_pathname)
#created_res = load(new_pathname)
pkgasset.parsed_meta.insert_resource(extra_asset_fileid, created_res)
if main_asset != null:
godot_resource = main_asset.create_godot_resource()
if get_file_extension_without_early_parse(pkgasset) != "" or get_asset_type(pkgasset) == ASSET_TYPE_ANIM:
pkgasset.parsed_asset.assets.clear()
pkgasset.parsed_asset = null
pkgasset.parsed_meta.parsed = null
if godot_resource == pkgasset.parsed_meta:
return false
if godot_resource != null:
# Save main resource at end, so that it can reference extra resources.
unidot_utils.save_resource(godot_resource, pkgasset.pathname)
if godot_resource == null:
if pkgasset.pathname.ends_with(DEBUG_RAW_PARSED_ASSET_TYPES):
var rpa = raw_parsed_asset.new()
rpa.path = pkgasset.pathname
rpa.guid = pkgasset.guid
rpa.meta = pkgasset.parsed_meta.duplicate()
for key in pkgasset.parsed_asset.assets:
var parsed_obj: RefCounted = pkgasset.parsed_asset.assets[key]
rpa.objects[str(key) + ":" + str(parsed_obj.type)] = pkgasset.parsed_asset.assets[key].keys
rpa.resource_name + pkgasset.pathname.get_basename().get_file()
unidot_utils.save_resource(rpa, pkgasset.pathname + ".raw.tres")
return false
return true
class SceneHandler:
extends YamlHandler
func preprocess_asset(pkgasset: Object, tmpdir: String, thread_subdir: String, path: String, data_buf: PackedByteArray, unique_texture_map: Dictionary = {}) -> String:
var is_prefab = pkgasset.orig_pathname.get_extension().to_lower() != "scene"
var new_pathname: String = pkgasset.pathname.get_basename() + pkgasset.parsed_meta.fixup_godot_extension(".prefab.tscn" if is_prefab else ".tscn")
return new_pathname
func write_godot_asset(pkgasset, temp_path) -> bool:
var is_prefab = pkgasset.orig_pathname.get_extension().to_lower() != "scene"
var packed_scene: PackedScene = convert_scene.new().pack_scene(pkgasset, is_prefab)
if packed_scene != null:
unidot_utils.save_resource(packed_scene, "res://" + pkgasset.pathname)
unidot_utils.editor_interface.reload_scene_from_path("res://" + pkgasset.pathname)
return true
return false
class BaseModelHandler:
extends AssetHandler
func preprocess_asset(pkgasset: Object, tmpdir: String, thread_subdir: String, path: String, data_buf: PackedByteArray, unique_texture_map: Dictionary = {}) -> String:
var already_rewrote_file = false
if str(pkgasset.pathname).to_lower().ends_with(".dae"):
var buffer_as_ascii: String = data_buf.get_string_from_utf8() # may contain unicode
var pos: int = buffer_as_ascii.find("up_axis")
if pos != -1:
pos = buffer_as_ascii.find(">", pos)
if pos != -1:
var next_pos: int = buffer_as_ascii.find("<", pos)
var up_axis = buffer_as_ascii.substr(pos + 1, next_pos - pos - 1).strip_edges()
pkgasset.parsed_meta.internal_data["up_axis"] = up_axis
if up_axis != "Y_UP":
var outfile: FileAccess = FileAccess.open(tmpdir + "/" + pkgasset.pathname, FileAccess.WRITE_READ)
outfile.store_buffer(data_buf.slice(0, pos + 1))
outfile.store_string("Y_UP")
outfile.store_buffer(data_buf.slice(next_pos))
outfile.flush()
var fpos = outfile.get_position()
outfile.seek(0)
pkgasset.data_md5 = calc_md5(outfile.get_buffer(fpos))
outfile.close()
outfile = null
pkgasset.existing_data_md5 = calc_existing_md5(pkgasset.pathname)
already_rewrote_file = true
var extracted_assets_dir: String = post_import_material_remap_script.get_extracted_assets_dir(pkgasset.pathname)
if not DirAccess.dir_exists_absolute(extracted_assets_dir):
DirAccess.make_dir_absolute(extracted_assets_dir)
if already_rewrote_file:
return pkgasset.pathname
return ""
func get_asset_type(pkgasset: Object) -> int:
return ASSET_TYPE_MODEL
func write_godot_import(pkgasset: Object, force_keep: bool) -> bool:
var importer = pkgasset.parsed_meta.importer
var cfile = ConfigFileCompare.new(pkgasset)
if cfile.load("res://" + pkgasset.pathname + ".import") != OK:
pkgasset.log_debug("Failed to load .import config file for " + pkgasset.pathname)
cfile.set_value("remap", "path", "unidot_default_remap_path") # must be non-empty. hopefully ignored.
cfile.set_value("remap", "importer_version", 1)
if force_keep:
cfile.set_value("remap", "importer", "keep")
if cfile.has_section_key("remap", "type"):
cfile.erase_section_key("remap", "type")
cfile.set_value("params", "import_script/path", "")
if pkgasset.pathname.validate_filename().is_empty():
pkgasset.log_fail("pathname became empty in model: " + str(pkgasset.pathname))
return false
cfile.save("res://" + pkgasset.pathname + ".import")
return true
cfile.set_value_compare("remap", "importer", "scene")
cfile.set_value("params", "import_script/path", post_import_material_remap_script.resource_path)
# I think these are the default settings now?? The option no longer exists???
### cfile.set_value("params", "materials/location", 1) # Store on Mesh, not Node.
### cfile.set_value("params", "materials/storage", 0) # Store in file. post-import will export.
cfile.set_value_compare("params", "animation/fps", pkgasset.parsed_meta.internal_data.get("anim_bake_fps", 30))
# fps should match the bake30 option passed to FBX2glTF, it may ignore the original framerate...
# The importer seems to operate in terms of frames but no indication of time here....
cfile.set_value_compare("params", "animation/import", importer.animation_import)
# Humanoid animations in particular are sensititve to immutable tracks being shared across rigs.
cfile.set_value_compare("params", "animation/remove_immutable_tracks", (importer.keys.get("animationType", 2) == 3 or pkgasset.parsed_meta.is_force_humanoid()))
cfile.set_value_compare("params", "animation/import_rest_as_RESET", true)
# FIXME: Godot has a major bug if light baking is used:
# it leaves a file ".glb.unwrap_cache" open and causes future imports to fail.
cfile.set_value_compare("params", "meshes/light_baking", importer.meshes_light_baking)
# A bug exists in Godot 4.2 stable if meshes with blendshapes are imported without tangents. We should always generate them.
cfile.set_value_compare("params", "meshes/ensure_tangents", 1) # importer.ensure_tangents)
cfile.set_value_compare("params", "meshes/create_shadow_meshes", false) # Until visual artifacts with shadow meshes get fixed
cfile.set_value_compare("params", "nodes/root_scale", pkgasset.parsed_meta.internal_data.get("scale_correction_factor", 1.0))
cfile.set_value_compare("params", "nodes/apply_root_scale", true)
cfile.set_value_compare("params", "nodes/root_name", "")
# addCollider???? TODO
# ??? animation/optimizer setting seems to be missing?
var subresources: Dictionary = cfile.get_value("params", "_subresources", {})
var anim_clips: Array[Dictionary] = importer.get_animation_clips()
## animation/clips don't seem to work at least in 4.0.... why even bother?
## We should use an import script I guess.
#cfile.set_value("params", "animation/clips/amount", len(anim_clips))
#var idx: int = 0
subresources["animations"] = {}
var fps_ratio: float = pkgasset.parsed_meta.internal_data.get("anim_frames_fps_ratio", 1.0)
var used_animation_names: Dictionary = pkgasset.parsed_meta.internal_data.get("used_animation_names", {})
var orig_to_godot_sanitized_anim_takes: Dictionary = pkgasset.parsed_meta.internal_data.get("orig_to_godot_sanitized_anim_takes", {})
for anim_clip in anim_clips:
var take_name = orig_to_godot_sanitized_anim_takes.get(anim_clip["take_name"], anim_clip["take_name"])
if not used_animation_names.has(take_name):
for key in used_animation_names:
pkgasset.log_warn("Substituting requested takeName " + str(take_name) + " for first animation " + str(key))
take_name = key # Usually just one. Often "Take 001"
break
if not subresources["animations"].has(take_name):
subresources["animations"][take_name] = {}
var take: Dictionary = subresources["animations"][take_name]
var idx: int = take.get("slices/amount", 0) + 1 # 1-indexed
var prefix: String = "slice_" + str(idx)
# FIXME: If take_name == name, godot won't actually apply the slice data.
take[prefix + "/name"] = anim_clip.get("name")
take[prefix + "/start_frame"] = fps_ratio * anim_clip.get("start_frame")
take[prefix + "/end_frame"] = fps_ratio * anim_clip.get("end_frame")
take["settings/loop_mode"] = anim_clip.get("loop_mode")
take[prefix + "/loop_mode"] = anim_clip.get("loop_mode")
take[prefix + "/save_to_file/enabled"] = false # TODO
take[prefix + "/save_to_file/keep_custom_tracks"] = false # Buggy through 4.2
take[prefix + "/save_to_file/path"] = "" # TODO
take["slices/amount"] = idx # 1-indexed
# animation/import
if not subresources.has("nodes"):
subresources["nodes"] = {}
if not subresources["nodes"].has("PATH:AnimationPlayer"):
subresources["nodes"]["PATH:AnimationPlayer"] = {}
if importer.keys.get("animationType", 2) == 3 or pkgasset.parsed_meta.is_force_humanoid():
cfile.set_value_compare("params", "nodes/import_as_skeleton_bones", true)
if not subresources["nodes"].has("PATH:Skeleton3D"):
subresources["nodes"]["PATH:Skeleton3D"] = {}
var bone_map: BoneMap = importer.generate_bone_map_from_human()
# TODO: Allow generating BoneMap from Avatar object, too.
subresources["nodes"]["PATH:Skeleton3D"]["retarget/bone_map"] = bone_map
# FIXME: Disabled fix_silhouette because the pre-silhouette matrix is not being calculated yet
# This would break skins and unpacked prefabs.
if pkgasset.parsed_meta.is_using_builtin_ufbx():
var silhouette_anim: Animation = pkgasset.parsed_meta.internal_data.get("silhouette_anim", null)
if silhouette_anim != null and pkgasset.parsed_meta.internal_data.get("copy_avatar_src", []):
subresources["nodes"]["PATH:Skeleton3D"]["rest_pose/load_pose"] = 2
subresources["nodes"]["PATH:Skeleton3D"]["rest_pose/external_animation_library"] = silhouette_anim
subresources["nodes"]["PATH:Skeleton3D"]["retarget/rest_fixer/fix_silhouette/enable"] = false
subresources["nodes"]["PATH:Skeleton3D"]["retarget/rest_fixer/fix_silhouette/enable"] = true
subresources["nodes"]["PATH:Skeleton3D"]["retarget/rest_fixer/fix_silhouette/filter"] = [&"LeftFoot", &"RightFoot", &"LeftToes", &"RightToes"]
subresources["nodes"]["PATH:Skeleton3D"]["retarget/rest_fixer/fix_silhouette/threshold"] = SILHOUETTE_FIX_THRESHOLD
subresources["nodes"]["PATH:Skeleton3D"]["retarget/rest_fixer/reset_all_bone_poses_after_import"] = false
else:
subresources["nodes"]["PATH:Skeleton3D"]["retarget/rest_fixer/fix_silhouette/enable"] = false
var anim_player_settings: Dictionary = subresources["nodes"]["PATH:AnimationPlayer"]
var optim_setting: Dictionary = importer.animation_optimizer_settings()
anim_player_settings["optimizer/enabled"] = optim_setting.get("enabled", false)
anim_player_settings["optimizer/max_linear_error"] = optim_setting.get("max_linear_error", 0.0)
anim_player_settings["optimizer/max_angular_error"] = optim_setting.get("max_angular_error", 0.0)
cfile.set_value("params", "_subresources", subresources)
#cfile.set_value_compare("params", "animation/optimizer/enabled", optim_setting.get("enabled"))
#cfile.set_value_compare("params", "animation/optimizer/max_linear_error", optim_setting.get("max_linear_error"))
#cfile.set_value_compare("params", "animation/optimizer/max_angular_error", optim_setting.get("max_angular_error"))
if pkgasset.pathname.validate_filename().is_empty():
pkgasset.log_fail("pathname became empty for model: " + str(pkgasset.pathname))
return false
cfile.save("res://" + pkgasset.pathname + ".import")
return cfile.was_modified()
func about_to_import(pkgasset: Object):
var dres := DirAccess.open("res://")
for tex_name in pkgasset.parsed_meta.unique_texture_map:
var tex_uri = pkgasset.parsed_meta.unique_texture_map[tex_name]
var tex_pathname: String = "res://".path_join(pkgasset.pathname.get_base_dir().path_join(tex_name))
if not file_exists_hack(dres, tex_pathname):
var src_tex: Texture2D = ResourceLoader.load("res://".path_join(pkgasset.pathname.get_base_dir().path_join(tex_uri))) as Texture2D
if src_tex != null:
var tmp_tex: Texture2D = src_tex.duplicate()
tmp_tex.set_meta(&"src_tex", src_tex)
tmp_tex.resource_name = tex_name
if not tex_pathname.begins_with("res://"):
tex_pathname = "res://" + tex_pathname
pkgasset.log_debug("Would reference non-existent texture " + str(tex_pathname) + " from " + str(tex_name) + " rather than " + str(tex_uri))
tmp_tex.take_over_path(tex_pathname)
pkgasset.parsed_meta.taken_over_import_references[tex_name] = tmp_tex
else:
pkgasset.log_debug("Would reference existing texture " + str(tex_pathname) + " from " + str(tex_name) + " rather than " + str(tex_uri))
func finished_import(pkgasset: Object, res: Resource):
pkgasset.log_debug("taken_over_import_references: " + str(pkgasset.parsed_meta.taken_over_import_references))
pkgasset.parsed_meta.taken_over_import_references.clear()
super.finished_import(pkgasset, res)
if res != null:
pass
var cfile := ConfigFile.new()
if pkgasset.pathname.validate_filename().is_empty():
pkgasset.log_fail("pathname became empty in finished_import: " + str(pkgasset.pathname))
return
var import_file_path: String = "res://" + pkgasset.pathname + ".import"
if cfile.load(import_file_path) != OK:
pkgasset.log_fail("Unable to load " + str(import_file_path) + " to remove post-import script")
return
cfile.set_value("params", "import_script/path", "")
var subresources: Dictionary = cfile.get_value("params", "_subresources", {})
if not subresources.has("animations"):
subresources["animations"] = {}
var unused_anims: Dictionary = pkgasset.parsed_meta.imported_animation_paths.duplicate()
for take_name in subresources["animations"]:
var anim_properties = subresources["animations"][take_name]
var active_slices: Dictionary
var has_slices: bool = false
for keys in anim_properties:
var key: String = keys
if key.begins_with("slice_") and key.ends_with("/name") and anim_properties[key]:
# Slice has a name, so it is active
has_slices = true
if unused_anims.has(anim_properties[key]):
active_slices[key.split('/')[0]] = unused_anims[anim_properties[key]]
unused_anims.erase(anim_properties[key])
for slice_key in active_slices:
anim_properties[slice_key + "/save_to_file/enabled"] = true
anim_properties[slice_key + "/save_to_file/keep_custom_tracks"] = false # Buggy through 4.2
anim_properties[slice_key + "/save_to_file/path"] = active_slices[slice_key]
for take_name in unused_anims:
if not (subresources["animations"].has(take_name)):
subresources["animations"][take_name] = {}
subresources["animations"][take_name]["save_to_file/enabled"] = true
subresources["animations"][take_name]["save_to_file/keep_custom_tracks"] = true # Non-slices are not buggy
subresources["animations"][take_name]["save_to_file/path"] = unused_anims[take_name]
if not subresources.has("meshes"):
subresources["meshes"] = {}
for mesh_name in pkgasset.parsed_meta.imported_mesh_paths:
if not (subresources["meshes"].has(mesh_name)):
subresources["meshes"][mesh_name] = {}
subresources["meshes"][mesh_name]["save_to_file/enabled"] = true
subresources["meshes"][mesh_name]["save_to_file/make_streamable"] = ""
subresources["meshes"][mesh_name]["save_to_file/path"] = pkgasset.parsed_meta.imported_mesh_paths[mesh_name]
if not subresources.has("materials"):
subresources["materials"] = {}
for material_name in pkgasset.parsed_meta.imported_material_paths:
if not (subresources["materials"].has(material_name)):
subresources["materials"][material_name] = {}
subresources["materials"][material_name]["use_external/enabled"] = true
subresources["materials"][material_name]["use_external/path"] = pkgasset.parsed_meta.imported_material_paths[material_name]
if pkgasset.parsed_meta.imported_material_paths.has(""):
for i in range(pkgasset.parsed_meta.internal_data.get("unnamed_material_count", 0)):
var material_name: String = "@MATERIAL:" + str(i)
if not (subresources["materials"].has(material_name)):
subresources["materials"][material_name] = {}
subresources["materials"][material_name]["use_external/enabled"] = true
subresources["materials"][material_name]["use_external/path"] = pkgasset.parsed_meta.imported_material_paths[""]
cfile.set_value("params", "_subresources", subresources)
#cfile.set_value_compare("params", "animation/optimizer/enabled", optim_setting.get("enabled"))
#cfile.set_value_compare("params", "animation/optimizer/max_linear_error", optim_setting.get("max_linear_error"))
#cfile.set_value_compare("params", "animation/optimizer/max_angular_error", optim_setting.get("max_angular_error"))
cfile.save(import_file_path)
func write_godot_asset(pkgasset: Object, temp_path: String) -> bool:
var dres = DirAccess.open("res://")
# super.write_godot_asset(pkgasset, temp_path)
# Duplicate code since super causes a weird nonsensical error cannot call "importer()" function...
if pkgasset.existing_data_md5 != pkgasset.data_md5:
pkgasset.log_debug("Renaming " + temp_path + " to " + pkgasset.pathname)
dres.rename(temp_path, pkgasset.pathname)
if temp_path.ends_with(".gltf"):
dres.rename(temp_path.get_basename() + ".bin", pkgasset.pathname.get_basename() + ".bin")
return true
return false
class FbxHandler:
extends BaseModelHandler
# From core/string/ustring.cpp
func find_in_buffer(p_buf: PackedByteArray, p_str: PackedByteArray, p_from: int = 0, p_to: int = -1) -> int:
if p_from < 0:
return -1
var src_len: int = len(p_str)
var xlen: int = len(p_buf)
if p_to != -1 and xlen > p_to:
xlen = p_to
if src_len == 0 or xlen == 0:
return -1 # won't find anything!
var i: int = p_from
var ilen: int = xlen - src_len
while i < ilen:
var found: bool = true
var j: int = 0
while j < src_len:
var read_pos: int = i + j
if read_pos >= xlen:
push_error("FBX fail read_pos>=len")
return -1
if p_buf[read_pos] != p_str[j]:
found = false
break
j += 1
if found:
return i
i += 1
return -1
func _adjust_fbx_scale(pkgasset: Object, fbx_scale: float, useFileScale: bool, globalScale: float) -> float:
pkgasset.parsed_meta.internal_data["input_fbx_scale"] = fbx_scale
pkgasset.parsed_meta.internal_data["meta_scale_factor"] = globalScale
pkgasset.parsed_meta.internal_data["meta_convert_units"] = useFileScale
var desired_scale: float = 0
if useFileScale:
# Cases:
# (FBX All) fbx_scale=100; globalScale=1 -> 100
# (FBX All) fbx_scale=12.3; globalScale = 8.130081 -> 100
# (All Local) fbx_scale=1; globalScale=8.130081
# (All Local, No apply unit) fbx_scale=1; globalScale = 1 -> 1
desired_scale = fbx_scale * globalScale
else:
# Cases:
# (FBX All)fbx_scale=12.3; globalScale=1 -> 100
# (All Local) fbx_scale=1; globalScale=0.08130081 -> 8.130081
# (All Local, No apply unit) fbx_scale=1; globalScale = 0.01 -> 1
desired_scale = 100.0 * globalScale
var output_scale: float = desired_scale
# FBX2glTF does not implement scale correctly, so we must set it to 1.0 and correct it later
# Godot's new built-in FBX importer works correctly and does not need this correction.
if not pkgasset.parsed_meta.is_using_builtin_ufbx():
output_scale = 1.0
pkgasset.parsed_meta.internal_data["scale_correction_factor"] = desired_scale / output_scale
pkgasset.parsed_meta.internal_data["output_fbx_scale"] = output_scale
return output_scale
func convert_to_float(s: String) -> Variant:
return s.to_float()
func convert_to_int(s: String) -> int:
return s.to_int()
func _is_fbx_binary(fbx_file_binary: PackedByteArray) -> bool:
return find_in_buffer(fbx_file_binary, "Kaydara FBX Binary".to_ascii_buffer(), 0, 64) != -1
func _extract_fbx_textures_binary(pkgasset: Object, fbx_file_binary: PackedByteArray) -> PackedStringArray:
var spb: StreamPeerBuffer = StreamPeerBuffer.new()
spb.data_array = fbx_file_binary
spb.big_endian = false
var strlist: PackedStringArray = PackedStringArray()
var texname1_needle_buf: PackedByteArray = "...\u0010RelativeFilenameS".to_ascii_buffer()
texname1_needle_buf[0] = 0
texname1_needle_buf[1] = 0
texname1_needle_buf[2] = 0
var texname2_needle_buf: PackedByteArray = "S\u0007...XRefUrlS....S".to_ascii_buffer()
texname2_needle_buf[2] = 0
texname2_needle_buf[3] = 0
texname2_needle_buf[4] = 0
texname2_needle_buf[13] = 0
texname2_needle_buf[14] = 0
texname2_needle_buf[15] = 0
texname2_needle_buf[16] = 0
var texname1_pos: int = find_in_buffer(fbx_file_binary, texname1_needle_buf)
var texname2_pos: int = find_in_buffer(fbx_file_binary, texname2_needle_buf)
while texname1_pos != -1 or texname2_pos != -1:
var nextpos: int = -1
var ftype: int = 0
if texname1_pos != -1 and (texname2_pos == -1 or texname1_pos < texname2_pos):
nextpos = texname1_pos + len(texname1_needle_buf)
texname1_pos = find_in_buffer(fbx_file_binary, texname1_needle_buf, texname1_pos + 1)
ftype = 1
elif texname2_pos != -1:
nextpos = texname2_pos + len(texname2_needle_buf)
texname2_pos = find_in_buffer(fbx_file_binary, texname2_needle_buf, texname2_pos + 1)
ftype = 2
spb.seek(nextpos)
var strlen: int = spb.get_32()
spb.seek(nextpos + 4)
if strlen > 0 and strlen < 1024:
var fn_utf8: PackedByteArray = spb.get_data(strlen)[1] # NOTE: Do we need to detect charset? FBX should be unicode
strlist.append(fn_utf8.get_string_from_ascii())
return strlist
func _extract_fbx_textures_ascii(pkgasset: Object, buffer_as_ascii: String) -> PackedStringArray:
var strlist: PackedStringArray = PackedStringArray()
var texname1_needle = '"XRefUrl",'
var texname2_needle = "RelativeFilename:"
var texname1_pos: int = buffer_as_ascii.find(texname1_needle)
var texname2_pos: int = buffer_as_ascii.find(texname2_needle)
while texname1_pos != -1 or texname2_pos != -1:
var nextpos: int = -1
var newlinepos: int = -1
if texname1_pos != -1 and (texname2_pos == -1 or texname1_pos < texname2_pos):
nextpos = texname1_pos + len(texname1_needle)
newlinepos = buffer_as_ascii.find("\n", nextpos)
texname1_pos = buffer_as_ascii.find(texname1_needle, texname1_pos + 1)
nextpos = buffer_as_ascii.find('"', nextpos + 1)
nextpos = buffer_as_ascii.find('"', nextpos + 1)
nextpos = buffer_as_ascii.find('"', nextpos + 1)
elif texname2_pos != -1:
nextpos = texname2_pos + len(texname2_needle)
newlinepos = buffer_as_ascii.find("\n", nextpos)
texname2_pos = buffer_as_ascii.find(texname2_needle, texname2_pos + 1)
nextpos = buffer_as_ascii.find('"', nextpos + 1)
var lastquote: int = buffer_as_ascii.find('"', nextpos + 1)
if lastquote > newlinepos:
pkgasset.log_warn("Failed to parse texture from " + buffer_as_ascii.substr(nextpos, newlinepos - nextpos))
else:
strlist.append(buffer_as_ascii.substr(nextpos + 1, lastquote - nextpos - 1))
return strlist
func _extract_fbx_object_offsets_binary(obj_type: String, pkgasset: Object, fbx_file_binary: PackedByteArray) -> Dictionary:
var spb: StreamPeerBuffer = StreamPeerBuffer.new()
spb.data_array = fbx_file_binary
spb.big_endian = false
var str_offsets: Dictionary
# Binary FBX serializes ids such as Model::SomeNodeName as S__\x00\x00SomeNodeName\x00\x01Model
var modelname_needle_buf: PackedByteArray = (".\u0001" + obj_type).to_ascii_buffer()
modelname_needle_buf[0] = 0
var modelname_needle_pos: int = find_in_buffer(fbx_file_binary, modelname_needle_buf)
while modelname_needle_pos != -1:
var length_prefix_pos: int = modelname_needle_pos - 1
while fbx_file_binary[length_prefix_pos] != 0:
if length_prefix_pos < 4:
push_error("Failed to find beginning of Model name")
return str_offsets
length_prefix_pos -= 1
var nextpos: int = find_in_buffer(fbx_file_binary, modelname_needle_buf, modelname_needle_pos + 7)
spb.seek(length_prefix_pos - 3)
var strlen: int = spb.get_32()
#print(strlen + 1 + length_prefix_pos)
#print(modelname_needle_pos)
assert(strlen + 1 + length_prefix_pos == modelname_needle_pos + 2 + len(obj_type))
if strlen >= len(obj_type) + 2 and strlen < 1024: