-
Notifications
You must be signed in to change notification settings - Fork 84
/
importer.py
1865 lines (1477 loc) · 74.5 KB
/
importer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2021 Victor Soupday
# This file is part of CC/iC Blender Tools <https://github.com/soupday/cc_blender_tools>
#
# CC/iC Blender Tools is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# CC/iC Blender Tools is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with CC/iC Blender Tools. If not, see <https://www.gnu.org/licenses/>.
import os
import shutil
import bpy
from enum import IntEnum, IntFlag
from . import (characters, hik, rigging, rigutils, bones, bake, imageutils, jsonutils, materials,
modifiers, wrinkle, drivers, meshutils, nodeutils, physics,
rigidbody, colorspace, scene, channel_mixer, shaders,
basic, properties, utils, vars)
debug_counter = 0
def delete_import(chr_cache):
props = vars.props()
chr_cache.invalidate()
chr_cache.delete()
chr_cache.clean_up()
utils.remove_from_collection(props.import_cache, chr_cache)
utils.clean_up_unused()
def process_material(chr_cache, obj_cache, obj, mat, obj_json, processed_images):
props = vars.props()
prefs = vars.prefs()
mat_cache = chr_cache.get_material_cache(mat)
mat_json = jsonutils.get_material_json(obj_json, mat)
if not mat_cache: return
# don't process user added materials
if mat_cache.user_added: return
if not mat.use_nodes:
mat.use_nodes = True
# store the material type and id
mat_cache.check_id()
if chr_cache.setup_mode == "ADVANCED":
if mat_cache.is_cornea() or mat_cache.is_eye():
shaders.connect_eye_shader(obj_cache, obj, mat, obj_json, mat_json, processed_images)
elif mat_cache.is_tearline():
shaders.connect_tearline_shader(obj_cache, obj, mat, mat_json, processed_images)
elif mat_cache.is_eye_occlusion():
shaders.connect_eye_occlusion_shader(obj_cache, obj, mat, mat_json, processed_images)
elif mat_cache.is_skin() or mat_cache.is_nails():
shaders.connect_skin_shader(chr_cache, obj_cache, obj, mat, mat_json, processed_images)
elif mat_cache.is_teeth():
shaders.connect_teeth_shader(obj_cache, obj, mat, mat_json, processed_images)
elif mat_cache.is_tongue():
shaders.connect_tongue_shader(obj_cache, obj, mat, mat_json, processed_images)
elif mat_cache.is_hair():
shaders.connect_hair_shader(obj_cache, obj, mat, mat_json, processed_images)
elif mat_cache.is_sss():
shaders.connect_sss_shader(obj_cache, obj, mat, mat_json, processed_images)
else:
shaders.connect_pbr_shader(obj_cache, obj, mat, mat_json, processed_images)
# optional pack channels
if prefs.build_limit_textures or prefs.build_pack_texture_channels:
bake.pack_shader_channels(chr_cache, mat_cache)
elif props.wrinkle_mode and mat_json and "Wrinkle" in mat_json.keys():
bake.pack_shader_channels(chr_cache, mat_cache)
else:
nodeutils.clear_cursor()
nodeutils.reset_cursor()
if mat_cache.is_eye_occlusion():
basic.connect_eye_occlusion_material(obj, mat, mat_json, processed_images)
elif mat_cache.is_tearline():
basic.connect_tearline_material(obj, mat, mat_json, processed_images)
elif mat_cache.is_cornea():
basic.connect_basic_eye_material(obj, mat, mat_json, processed_images)
else:
basic.connect_basic_material(obj, mat, mat_json, processed_images)
nodeutils.move_new_nodes(-600, 0)
# apply cached alpha settings
if mat_cache is not None:
if mat_cache.alpha_mode != "NONE":
materials.apply_alpha_override(obj, mat, mat_cache.alpha_mode)
if mat_cache.culling_sides > 0:
materials.apply_backface_culling(obj, mat, mat_cache.culling_sides)
# apply any channel mixers
if mat_cache is not None:
if mat_cache.mixer_settings:
mixer_settings = mat_cache.mixer_settings
if mixer_settings.rgb_image or mixer_settings.id_image:
channel_mixer.rebuild_mixers(chr_cache, mat, mixer_settings)
def process_object(chr_cache, obj, obj_cache, objects_processed, chr_json, processed_materials, processed_images):
props = vars.props()
prefs = vars.prefs()
if obj is None or obj in objects_processed:
return
objects_processed.append(obj)
obj_json = jsonutils.get_object_json(chr_json, obj_cache.source_name)
physics_json = None
utils.log_info("")
utils.log_info("Processing Object: " + obj.name + ", Type: " + obj.type)
utils.log_indent()
if obj.type == "MESH":
mesh : bpy.types.Mesh = obj.data
# Turn off auto smoothing
if not utils.B401():
mesh.use_auto_smooth = False
# Auto apply armature modifier settings
if prefs.build_armature_edit_modifier or prefs.build_armature_preserve_volume:
mod_arm = modifiers.get_object_modifier(obj, "ARMATURE")
if mod_arm:
if prefs.build_armature_edit_modifier:
mod_arm.show_in_editmode = True
mod_arm.show_on_cage = True
if prefs.build_armature_preserve_volume:
mod_arm.use_deform_preserve_volume = True
# Set to smooth shading (disabled as may not be needed anymore)
#meshutils.set_shading(obj, True)
# remove any modifiers for refractive eyes
modifiers.remove_eye_modifiers(obj)
# store the object type and id
# store the material type and id
if obj_cache:
obj_cache.check_id()
# process any materials found in the mesh object
for slot in obj.material_slots:
mat = slot.material
if mat and mat not in objects_processed:
utils.log_info("")
utils.log_info("Processing Material: " + mat.name)
utils.log_indent()
process_material(chr_cache, obj_cache, obj, mat, obj_json, processed_images)
if processed_materials is not None:
first = materials.find_duplicate_material(chr_cache, mat, processed_materials)
if first:
utils.log_info(f"Found duplicate material, re-using {first.name} instead.")
slot.material = first
else:
processed_materials.append(mat)
utils.log_recess()
objects_processed.append(mat)
# setup special modifiers for displacement, UV warp, etc...
if obj_cache and chr_cache.setup_mode == "ADVANCED":
if obj_cache.is_eye():
modifiers.add_eye_modifiers(obj)
elif obj_cache.is_eye_occlusion():
modifiers.add_eye_occlusion_modifiers(obj)
elif obj_cache.is_tearline():
modifiers.add_tearline_modifiers(obj)
elif obj.type == "ARMATURE":
# set the frame range of the scene to the active action on the armature
if props.physics_mode:
scene.fetch_anim_range(bpy.context, expand=True)
obj["rl_import_file"] = chr_cache.import_file
obj["rl_generation"] = chr_cache.generation
utils.log_recess()
def cache_object_materials(chr_cache, obj, chr_json, processed):
props = vars.props()
if obj is None or obj in processed:
return
obj_json = jsonutils.get_object_json(chr_json, obj)
obj_cache = chr_cache.add_object_cache(obj)
if obj.type == "MESH":
utils.log_info(f"Caching Object: {obj.name}")
utils.log_indent()
for mat in obj.data.materials:
if mat and mat.node_tree is not None:
object_type, material_type = materials.detect_materials(chr_cache, obj, mat, obj_json)
if obj_cache.object_type != "BODY":
obj_cache.set_object_type(object_type)
if mat not in processed:
mat_cache = chr_cache.add_material_cache(mat, material_type)
mat_cache.dir = imageutils.get_material_tex_dir(chr_cache, obj, mat)
utils.log_indent()
materials.detect_embedded_textures(chr_cache, obj, obj_cache, mat, mat_cache)
materials.detect_mixer_masks(chr_cache, obj, obj_cache, mat, mat_cache)
physics.detect_physics(chr_cache, obj, obj_cache, mat, mat_cache, chr_json)
utils.log_recess()
processed.append(mat)
utils.log_recess()
processed.append(obj)
def apply_edit_shapekeys(obj):
"""For objects with shapekeys, set the active visible and edit mode shapekey to the basis.
"""
# shapekeys data path:
# utils.get_active_object().data.shape_keys.key_blocks['Basis']
if obj.type == "MESH":
shape_keys = obj.data.shape_keys
if shape_keys is not None:
blocks = shape_keys.key_blocks
if blocks is not None:
# if the object has shape keys
if len(blocks) > 0:
try:
# set the active shapekey to the basis and apply shape keys in edit mode.
obj.active_shape_key_index = 0
obj.show_only_shape_key = False
obj.use_shape_key_edit_mode = True
except Exception as e:
utils.log_error("Unable to set shape key edit mode!", e)
def init_shape_key_range(obj):
#utils.get_active_object().data.shape_keys.key_blocks['Basis']
if obj.type == "MESH":
shape_keys: bpy.types.Key = obj.data.shape_keys
if shape_keys is not None:
blocks = shape_keys.key_blocks
if blocks is not None:
if len(blocks) > 0:
for block in blocks:
# expand the range of the shape key slider to include negative values...
if "Eye" in block.name and "_Look_" in block.name:
block.slider_min = -1.0
block.slider_max = 1.0
else:
block.slider_min = -1.5
block.slider_max = 1.5
# re-set a value in the shapekey action keyframes to force
# the shapekey action to update to the new ranges:
try:
action = utils.safe_get_action(shape_keys)
if action:
co = action.fcurves[0].keyframe_points[0].co
action.fcurves[0].keyframe_points[0].co = co
except:
pass
def detect_generation(chr_cache, json_data, character_id):
generation = "Unknown"
if json_data:
avatar_type = jsonutils.get_json(json_data, f"{character_id}/Avatar_Type")
json_generation = jsonutils.get_character_generation_json(json_data, chr_cache.get_character_id())
if json_generation and json_generation in vars.CHARACTER_GENERATION:
generation = vars.CHARACTER_GENERATION[json_generation]
elif avatar_type == "NonHuman":
generation = "Creature"
elif avatar_type == "NonStandard":
generation = "Humanoid"
elif json_generation is not None and json_generation == "":
generation = "Humanoid"
elif json_generation is None:
generation = "Prop"
arm = chr_cache.get_armature()
material_names = characters.get_character_material_names(arm)
object_names = characters.get_character_object_names(arm)
# some ActorScan characters are GameBase in disguise...
if characters.character_has_bones(arm, ["root", "pelvis", "spine_03", "CC_Base_FacialBone"]):
generation = "GameBase"
if generation in ["Unknown", "Humanoid", "Creature"]:
utils.log_info(f"Determining generation from armature...")
if len(material_names) == 1 and rigutils.is_ActorCore_armature(arm):
generation = "ActorScan"
utils.log_info(" - ActorScan found!")
elif characters.character_has_materials(arm, ["Ga_Skin_Body"]) and rigutils.is_ActorCore_armature(arm):
generation = "ActorBuild"
utils.log_info(" - ActorBuild found!")
elif characters.character_has_materials(arm, ["Ga_Skin_Body"]) and rigutils.is_GameBase_armature(arm):
generation = "GameBase"
utils.log_info(" - GameBase found!")
elif rigutils.is_rl_armature(arm):
generation = "AccuRig"
utils.log_info(" - AccuRig found!")
else:
utils.log_info(" - Not found...")
if generation == "Unknown" and arm:
if utils.find_pose_bone_in_armature(arm, "RootNode_0_", "RL_BoneRoot"):
generation = "ActorCore"
elif utils.find_pose_bone_in_armature(arm, "CC_Base_L_Pinky3", "L_Pinky3"):
generation = "G3"
elif utils.find_pose_bone_in_armature(arm, "pinky_03_l"):
generation = "GameBase"
elif utils.find_pose_bone_in_armature(arm, "CC_Base_L_Finger42", "L_Finger42"):
generation = "G1"
utils.log_info(f"Generation could be: {generation} detected from pose bones.")
if generation == "Unknown":
for obj_cache in chr_cache.object_cache:
obj = obj_cache.get_object()
if obj_cache.is_mesh():
name = obj.name.lower()
if "cc_game_body" in name or "cc_game_tongue" in name:
generation = "GameBase"
elif "cc_base_body" in name:
if utils.object_has_material(obj, "ga_skin_body"):
generation = "GameBase"
elif utils.object_has_material(obj, "std_skin_body"):
generation = "G3"
elif utils.object_has_material(obj, "skin_body"):
generation = "G1"
if generation != "Unknown":
utils.log_info(f"Generation could be: {generation} detected from materials.")
if generation == "Unknown" or generation == "G3":
for obj_cache in chr_cache.object_cache:
obj = obj_cache.get_object()
if obj_cache.is_mesh() and obj.name == "CC_Base_Body":
# try vertex count
if len(obj.data.vertices) == 14164:
utils.log_info("Generation: G3Plus detected by vertex count.")
generation = "G3Plus"
elif len(obj.data.vertices) == 13286:
utils.log_info("Generation: G3 detected by vertex count.")
generation = "G3"
#try UV map test
elif materials.test_for_material_uv_coords(obj, 0, [[0.5, 0.763], [0.7973, 0.6147], [0.1771, 0.0843], [0.912, 0.0691]]):
utils.log_info("Generation: G3Plus detected by UV test.")
generation = "G3Plus"
elif materials.test_for_material_uv_coords(obj, 0, [[0.5, 0.034365], [0.957562, 0.393431], [0.5, 0.931725], [0.275117, 0.961283]]):
utils.log_info("Generation: G3 detected by UV test.")
generation = "G3"
utils.log_info(f"Detected Character Generation: {generation}")
return generation
def is_iclone_temp_motion(name : str):
u_idx = name.find('_', 0)
if u_idx == -1:
return False
if not name[:u_idx].isdigit():
return False
search = "TempMotion"
if utils.partial_match(name, "TempMotion", u_idx + 1):
return True
else:
return False
def purge_imported_material(mat, imported_images: list):
if utils.material_exists(mat):
if mat.node_tree and mat.node_tree.nodes:
for node in mat.node_tree.nodes:
if node.type == "TEX_IMAGE":
if node.image:
if node.image in imported_images:
imported_images.remove(node.image)
bpy.data.images.remove(node.image)
bpy.data.materials.remove(mat)
def purge_imported_object(obj, imported_images):
if utils.object_exists(obj):
if obj.type == "MESH":
for mat in obj.data.materials:
purge_imported_material(mat, imported_images)
utils.delete_object_tree(obj)
def remap_action_names(arm, objects, actions, source_id, motion_prefix=""):
key_map = {}
num_keys = 0
rig_id = rigutils.get_rig_id(arm)
utils.log_info(f"Remap Action Names:")
utils.log_info(f"Armature: {source_id} => {rig_id}")
# don't change the armature id if it exists
rl_arm_id = utils.get_rl_object_id(arm)
if not rl_arm_id:
rl_arm_id = utils.generate_random_id(20)
utils.set_rl_object_id(arm, rl_arm_id)
# find all motions for this armature
armature_actions = []
shapekey_actions = []
motion_ids = set()
motion_sets = {}
for action in actions:
split = action.name.split("|")
action_arm_id = split[0]
motion_id = split[-1]
if action_arm_id == source_id:
utils.log_info(f"Motion ID: {motion_id}")
motion_ids.add(motion_id)
armature_actions.append(action)
motion_sets[motion_id] = rigutils.generate_motion_set(arm, motion_id,
motion_prefix)
# determine how each shape key id relates to each object in the import
for obj in objects:
if obj.type == "MESH":
obj_id = rigutils.get_action_obj_id(obj)
if obj.data.shape_keys:
obj_action = utils.safe_get_action(obj.data.shape_keys)
if obj_action:
actions.append(obj_action)
key_map[obj_id] = obj.data.shape_keys.name
utils.log_info(f"ShapeKey: {obj.data.shape_keys.name} belongs to: {obj_id}")
num_keys += 1
# rename all actions associated with this armature and it's motions
for action in actions:
split = action.name.split("|")
action_key_name = split[0]
motion_id = split[-1]
if motion_id in motion_ids:
set_id, set_generation = motion_sets[motion_id]
if action in armature_actions:
action_name = rigutils.make_armature_action_name(rig_id, motion_id, motion_prefix)
utils.log_info(f"Renaming action: {action.name} to {action_name}")
action.name = action_name
rigutils.add_motion_set_data(action, set_id, set_generation, rl_arm_id=rl_arm_id)
armature_actions.append(action)
else:
for obj_id, key_name in key_map.items():
if action_key_name == key_name:
action_name = rigutils.make_key_action_name(rig_id, motion_id, obj_id, motion_prefix)
utils.log_info(f"Renaming action: {action.name} to {action_name}")
action.name = action_name
rigutils.add_motion_set_data(action, set_id, set_generation, obj_id=obj_id)
shapekey_actions.append(action)
return armature_actions, shapekey_actions
def process_root_bones(arm, json_data, name):
root_bones = jsonutils.get_json(json_data, f"{name}/Root Bones")
if root_bones:
for root_def in root_bones:
name = root_def["Name"]
type = root_def["Type"]
sub_link_id = root_def["Link_ID"]
if name in arm.pose.bones:
pose_bone = arm.pose.bones[name]
pose_bone["root_id"] = sub_link_id
pose_bone["root_type"] = type
def process_rl_import(file_path, import_flags, armatures, rl_armatures, objects: list,
actions, json_data, report, link_id, only_objects=None, motion_prefix=""):
props = vars.props()
prefs = vars.prefs()
utils.log_info("")
utils.log_info("Processing Reallusion Import:")
utils.log_info("-----------------------------")
dir, file = os.path.split(file_path)
name, ext = os.path.splitext(file)
imported_characters = []
if armatures and (len(armatures) > 1 or len(rl_armatures) > 1):
report.append("Multiple armatures detected in Fbx is not fully supported!")
utils.log_warn("Multiple armatures detected in Fbx is not fully supported!")
utils.log_warn("Character exports from iClone to Blender do not fully support multiple characters.")
utils.log_warn("Characters should be exported individually for best results.")
if not objects:
report.append("No objects in import!")
utils.log_error("No objects in import!")
return None
try:
# try to override the import dir with the directory specified in the json:
# when exporting from Blender without copying textures, these custom fields
# tell us where the textures were originally and under what name
import_dir = json_data[name]["Import_Dir"]
import_name = json_data[name]["Import_Name"]
utils.log_info(f"Using original Import Dir: {import_dir}")
utils.log_info(f"Using original Import Name: {import_name}")
except:
import_name = name
import_dir = dir
processed = []
chr_json = jsonutils.get_character_json(json_data, name)
multi_import = (len(rl_armatures) + len(armatures) > 1)
if ImportFlags.FBX in import_flags:
for i, arm in enumerate(rl_armatures):
# actual name of character
# multiple character imports name the armatures after the character
# single character imports just name the armature 'armature' so use the file name
character_name = name
source_id = "Armature"
if len(rl_armatures) > 1:
source_id = arm.name
character_name = utils.safe_export_name(arm.name)
armature_objects = utils.get_child_objects(arm, include_parent=True)
utils.log_info(f"Generating Character Data: {character_name}")
utils.log_indent()
chr_cache = props.import_cache.add()
chr_cache.import_file = file_path
chr_cache.import_flags = import_flags
# display name of character
chr_cache.character_name = character_name
arm["rl_import_file"] = file_path
rigutils.fix_cc3_standard_rig(arm)
# link_id
json_link_id = jsonutils.get_json(json_data, f"{name}/Link_ID")
if not link_id and json_link_id:
link_id = json_link_id
if multi_import or not link_id:
link_id = utils.generate_random_id(20)
chr_cache.link_id = link_id
# root bones
process_root_bones(arm, json_data, name)
# determine the main texture dir
if os.path.exists(chr_cache.get_tex_dir()):
chr_cache.import_embedded = False
else:
chr_cache.import_embedded = True
arm.name = character_name
arm.data.name = character_name
# in case of duplicate names: character_name contains the name currently in Blender.
# get_character_id() is the original name.
chr_cache.character_name = arm.name
# add armature to object_cache
chr_cache.add_object_cache(arm)
# assign bone collections
bones.assign_rl_base_collections(arm)
# delete accessory colliders, currently they are useless as
# accessories don't export with any physics data or weightmaps.
physics.delete_accessory_colliders(arm, objects)
# add child objects to object_cache
for obj in objects:
if obj.type == "MESH" and obj.parent and obj.parent == arm:
if only_objects:
source_name = utils.strip_name(obj.name)
if source_name not in only_objects:
continue
chr_cache.add_object_cache(obj)
# remame actions
utils.log_info("Renaming actions:")
utils.log_indent()
remap_action_names(arm, armature_objects, actions, source_id,
motion_prefix=motion_prefix)
utils.log_recess()
# determine character generation
chr_cache.generation = detect_generation(chr_cache, json_data, chr_cache.get_character_id())
utils.log_info("Generation: " + chr_cache.character_name + " (" + chr_cache.generation + ")")
arm["rl_generation"] = chr_cache.generation
# cache materials
for obj_cache in chr_cache.object_cache:
if obj_cache.is_mesh():
obj = obj_cache.get_object()
cache_object_materials(chr_cache, obj, chr_json, processed)
shaders.init_character_property_defaults(chr_cache, chr_json)
basic.init_basic_default(chr_cache)
# set preserve volume on armature modifiers
for obj in objects:
if obj.type == "MESH":
arm_mod = modifiers.get_object_modifier(obj, "ARMATURE")
if arm_mod:
arm_mod.use_deform_preserve_volume = False
# material setup mode
chr_cache.setup_mode = props.setup_mode
# character render target
chr_cache.render_target = prefs.render_target
imported_characters.append(chr_cache.link_id)
utils.log_recess()
# any none character armatures should be scenes or props
for i, arm in enumerate(armatures):
character_name = name
source_id = "Armature"
if len(armatures) > 1:
source_id = arm.name
character_name = utils.safe_export_name(arm.name)
armature_objects = utils.get_child_objects(arm, include_parent=True)
utils.log_info(f"Generating Scene/Prop Data: {character_name}")
utils.log_indent()
chr_cache = props.import_cache.add()
chr_cache.import_file = file_path
chr_cache.import_flags = import_flags
# display name of character
chr_cache.character_name = character_name
chr_id = chr_cache.get_character_id()
# link_id
if multi_import:
link_id = utils.generate_random_id(20)
json_link_id = jsonutils.get_json(json_data, f"{name}/Link_ID")
if not multi_import and json_link_id:
chr_cache.link_id = json_link_id
else:
chr_cache.link_id = link_id
# root bones
process_root_bones(arm, json_data, name)
# determine the main texture dir
if os.path.exists(chr_cache.get_tex_dir()):
chr_cache.import_embedded = False
else:
chr_cache.import_embedded = True
arm.name = character_name
arm.data.name = character_name
# in case of duplicate names: character_name contains the name currently in Blender.
# import_name contains the original name.
chr_cache.character_name = arm.name
# add armature to object_cache
chr_cache.add_object_cache(arm)
# add child objects to object_cache
for obj in objects:
if obj.type == "MESH" and obj.parent and obj.parent == arm:
chr_cache.add_object_cache(obj)
# remame actions
utils.log_info("Renaming actions:")
utils.log_indent()
remap_action_names(arm, armature_objects, actions, source_id,
motion_prefix=motion_prefix)
utils.log_recess()
# determine character generation
chr_cache.generation = "Prop"
chr_cache.non_standard_type = "PROP"
# cache materials
for obj_cache in chr_cache.object_cache:
if obj_cache.is_mesh():
obj = obj_cache.get_object()
cache_object_materials(chr_cache, obj, chr_json, processed)
shaders.init_character_property_defaults(chr_cache, chr_json)
basic.init_basic_default(chr_cache)
# material setup mode
chr_cache.setup_mode = props.setup_mode
# character render target
chr_cache.render_target = prefs.render_target
json_avatar_type = jsonutils.get_json(json_data, f"{chr_id}/Avatar_Type")
if json_avatar_type and json_avatar_type == "Prop":
rigutils.custom_prop_rig(arm)
imported_characters.append(chr_cache.link_id)
utils.log_recess()
elif ImportFlags.OBJ in import_flags:
character_name = name
utils.log_info(f"Generating Character Data: {character_name}")
utils.log_indent()
chr_cache = props.import_cache.add()
chr_cache.import_file = file_path
chr_cache.import_flags = import_flags
# display name of character
chr_cache.character_name = character_name
# link_id (OBJ exports don't have json)
chr_cache.link_id = link_id
# determine the main texture dir
chr_cache.import_embedded = False
for obj in objects:
if utils.object_exists_is_mesh(obj):
chr_cache.add_object_cache(obj)
for obj_cache in chr_cache.object_cache:
# scale obj import by 1/100
obj = obj_cache.get_object()
if obj:
obj.scale = (0.01, 0.01, 0.01)
# objkey import is usually a single mesh with no materials
# but this is overridable in the pipeline plugin
if obj.data.materials and len(obj.data.materials) > 0:
cache_object_materials(chr_cache, obj, json_data, processed)
shaders.init_character_property_defaults(chr_cache, chr_json)
basic.init_basic_default(chr_cache)
# material setup mode
chr_cache.setup_mode = props.setup_mode
# character render target
chr_cache.render_target = prefs.render_target
imported_characters.append(chr_cache.link_id)
utils.log_info("")
return imported_characters
def obj_import(file_path, split_objects=False, split_groups=False, vgroups=False):
split_mode="ON" if (split_objects or split_groups) else "OFF"
if utils.B350():
bpy.ops.wm.obj_import(filepath=file_path,
use_split_objects=split_objects,
use_split_groups=split_groups,
import_vertex_groups=vgroups)
else:
bpy.ops.import_scene.obj(filepath=file_path,
split_mode=split_mode,
use_split_objects=split_objects,
use_split_groups=split_groups,
use_groups_as_vgroups=vgroups)
#
#
class ImportFlags(IntFlag):
NONE = 0
FBX = 1
OBJ = 2
GLB = 4
VRM = 8
USD = 16
RL = 1024
KEY = 2048
RL_FBX = RL | FBX
RL_OBJ = RL | OBJ
RL_FBX_KEY = RL_FBX | KEY
RL_OBJ_KEY = RL_OBJ | KEY
# Import operator
#
class CC3Import(bpy.types.Operator):
"""Import CC3 Character and build materials"""
bl_idname = "cc3.importer"
bl_label = "Import"
bl_options = {"REGISTER", "UNDO"}
filepath: bpy.props.StringProperty(
name="Filepath",
description="Filepath of the model to import.",
subtype="FILE_PATH"
)
directory: bpy.props.StringProperty(subtype='DIR_PATH')
files: bpy.props.CollectionProperty(
type=bpy.types.OperatorFileListElement,
options={'HIDDEN', 'SKIP_SAVE'}
)
link_id: bpy.props.StringProperty(
default="",
name="Link ID",
description="Link ID override",
options={"HIDDEN"},
)
process_only: bpy.props.StringProperty(
default="",
options={"HIDDEN"},
)
no_build: bpy.props.BoolProperty(
default=False,
name="No Build",
description="Don't build materials",
options={"HIDDEN"},
)
no_rigify: bpy.props.BoolProperty(
default=False,
name="Don't Rigify",
description="Don't Rigify Character",
options={"HIDDEN"},
)
filter_glob: bpy.props.StringProperty(
default="*.fbx;*.obj;*.glb;*.gltf;*.vrm;*.usd*",
options={"HIDDEN"},
)
param: bpy.props.StringProperty(
name = "param",
default = "",
options={"HIDDEN"}
)
motion_prefix: bpy.props.StringProperty(
name = "Motion Prefix",
default = ""
)
use_fake_user: bpy.props.BoolProperty(
name = "Use Fake User",
default = True
)
use_anim: bpy.props.BoolProperty(name = "Import Animation", description = "Import animation with character.\nWarning: long animations take a very long time to import in Blender 2.83", default = True)
zoom: bpy.props.BoolProperty(
default=False,
name="Zoom View",
description="Zoom view to imported character",
)
count = 0
running = False
imported = False
built = False
lighting = False
timer = None
clock = 0
invoked = False
imported_character_ids: list = None
imported_materials = []
imported_images = []
import_report = []
import_warn_level = 0
is_morph = False
def read_json_data(self, file_path, stage = 0):
# if not fbx, return no json without error
path, ext = os.path.splitext(file_path)
if not utils.is_file_ext(ext, "FBX"):
return None
errors = []
# importer operator should always read the original intended json data
json_data = jsonutils.read_json(file_path, errors, no_local=True)
msg = None
if "NO_JSON" in errors:
msg = "Character has no Json data, using default values."
elif "CORRUPT" in errors:
if stage == 0:
msg = "Corrupted Json data! \nThis character will not set up correctly!"
else:
msg = "Corrupted Json data! \nThis character will not have been set up correctly!"
elif "PATH_FAILED" in errors:
if stage == 0:
msg = "Unable to locate Json file path! \nThis character will not set up correctly!"
else:
msg = "Unable to locate Json file path! \nThis character will not have been set up correctly!"
if msg and msg not in self.import_report:
self.import_report.append(msg)
return json_data
def import_character(self, context):
props = vars.props()
prefs = vars.prefs()
utils.start_timer()
utils.log_info("")
utils.log_info("Importing Character Model:")
utils.log_info("--------------------------")
import_anim = self.use_anim
# multi selected files
file_paths = self.get_file_paths()
for filepath in file_paths:
# override link id only if not multi import
if len(file_paths) > 1:
self.link_id = ""
import_flags, param = self.detect_import_mode_from_files(filepath)
dir, file = os.path.split(filepath)
name, ext = os.path.splitext(file)
imported = None
actions = None
json_data = self.read_json_data(filepath, stage = 0)
json_generation = jsonutils.get_character_generation_json(json_data, name)
avatar_type = jsonutils.get_json(json_data, f"{name}/Avatar_Type")
only_objects = utils.names_to_list(self.process_only, "|")
if ImportFlags.FBX in import_flags:
# invoke the fbx importer
old_objects = utils.get_set(bpy.data.objects)
old_images = utils.get_set(bpy.data.images)
old_actions = utils.get_set(bpy.data.actions)
# in ACES color space, this will fail trying to set up the textures as it tries to use 'Non-Color' space.
# But the mesh is really all we need, so just keep going...
if colorspace.is_aces():
try:
bpy.ops.import_scene.fbx(filepath=filepath, directory=dir, use_anim=import_anim, use_image_search=False, use_custom_normals=True)
except:
utils.log_warn("FBX Import Error: This may be due to color space differences. Continuing...")
else:
try:
bpy.ops.import_scene.fbx(filepath=filepath, directory=dir, use_anim=import_anim, use_image_search=False, use_custom_normals=True)
except:
utils.log_error("FBX Import Error due to bad mesh?")
imported = utils.get_set_new(bpy.data.objects, old_objects)
actions = utils.get_set_new(bpy.data.actions, old_actions)