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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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
# Project EmbodiedGen
#
# Copyright (c) 2025 Horizon Robotics. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
# Some code comes from: https://github.com/princeton-vl/infinigen/blob/main/infinigen/tools/export.py

import argparse
import logging
import math
import os
import shutil
import subprocess
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Optional, Tuple

import bpy
import coacd
import gin
import numpy as np
import trimesh
from infinigen.core.util import blender as butil

logger = logging.getLogger(__name__)

FORMAT_CHOICES = ["fbx", "obj", "usdc", "usda", "stl", "ply"]
BAKE_TYPES = {
    "DIFFUSE": "Base Color",
    "ROUGHNESS": "Roughness",
    "NORMAL": "Normal",
}  # "EMIT":"Emission Color" #  "GLOSSY": "Specular IOR Level", "TRANSMISSION":"Transmission Weight" don"t export
SPECIAL_BAKE = {"METAL": "Metallic", "TRANSMISSION": "Transmission Weight"}
ALL_BAKE = BAKE_TYPES | SPECIAL_BAKE


def apply_all_modifiers(obj):
    for mod in obj.modifiers:
        if mod is None:
            continue
        try:
            obj.select_set(True)
            bpy.context.view_layer.objects.active = obj
            bpy.ops.object.modifier_apply(modifier=mod.name)
            logger.info(f"Applied modifier {mod} on {obj}")
            obj.select_set(False)
        except RuntimeError:
            logger.info(f"Can't apply {mod} on {obj}")
            obj.select_set(False)
            return


def realizeInstances(obj):
    for mod in obj.modifiers:
        if mod is None or mod.type != "NODES":
            continue
        geo_group = mod.node_group
        outputNode = geo_group.nodes["Group Output"]

        logger.info(f"Realizing instances on {mod}")
        link = outputNode.inputs[0].links[0]
        from_socket = link.from_socket
        geo_group.links.remove(link)
        realizeNode = geo_group.nodes.new(type="GeometryNodeRealizeInstances")
        geo_group.links.new(realizeNode.inputs[0], from_socket)
        geo_group.links.new(outputNode.inputs[0], realizeNode.outputs[0])


def remove_shade_smooth(obj):
    for mod in obj.modifiers:
        if mod is None or mod.type != "NODES":
            continue
        geo_group = mod.node_group
        outputNode = geo_group.nodes["Group Output"]
        if geo_group.nodes.get("Set Shade Smooth"):
            logger.info("Removing shade smooth on " + obj.name)
            smooth_node = geo_group.nodes["Set Shade Smooth"]
        else:
            continue

        link = smooth_node.inputs[0].links[0]
        from_socket = link.from_socket
        geo_group.links.remove(link)
        geo_group.links.new(outputNode.inputs[0], from_socket)


def check_material_geonode(node_tree):
    if node_tree.nodes.get("Set Material"):
        logger.info("Found set material!")
        return True

    for node in node_tree.nodes:
        if node.type == "GROUP" and check_material_geonode(node.node_tree):
            return True

    return False


def handle_geo_modifiers(obj, export_usd):
    has_geo_nodes = False
    for mod in obj.modifiers:
        if mod is None or mod.type != "NODES":
            continue
        has_geo_nodes = True

    if has_geo_nodes and not obj.data.materials:
        mat = bpy.data.materials.new(name=f"{mod.name} shader")
        obj.data.materials.append(mat)
        mat.use_nodes = True
        mat.node_tree.nodes.remove(mat.node_tree.nodes["Principled BSDF"])

    if not export_usd:
        realizeInstances(obj)


def split_glass_mats():
    split_objs = []
    for obj in bpy.data.objects:
        if obj.hide_render or obj.hide_viewport:
            continue
        if any(
            exclude in obj.name
            for exclude in [
                "BowlFactory",
                "CupFactory",
                "OvenFactory",
                "BottleFactory",
            ]
        ):
            continue
        for slot in obj.material_slots:
            mat = slot.material
            if mat is None:
                continue
            if (
                "shader_glass" in mat.name or "shader_lamp_bulb" in mat.name
            ) and len(obj.material_slots) >= 2:
                logger.info(f"Splitting {obj}")
                obj.select_set(True)
                bpy.context.view_layer.objects.active = obj
                bpy.ops.object.mode_set(mode="EDIT")
                bpy.ops.mesh.separate(type="MATERIAL")
                bpy.ops.object.mode_set(mode="OBJECT")
                obj.select_set(False)
                split_objs.append(obj.name)
                break

    matches = [
        obj
        for split_obj in split_objs
        for obj in bpy.data.objects
        if split_obj in obj.name
    ]
    for match in matches:
        if len(match.material_slots) == 0 or match.material_slots[0] is None:
            continue
        mat = match.material_slots[0].material
        if mat is None:
            continue
        if "shader_glass" in mat.name or "shader_lamp_bulb" in mat.name:
            match.name = f"{match.name}_SPLIT_GLASS"


def clean_names(obj=None):
    if obj is not None:
        obj.name = (obj.name).replace(" ", "_")
        obj.name = (obj.name).replace(".", "_")

        if obj.type == "MESH":
            for uv_map in obj.data.uv_layers:
                uv_map.name = uv_map.name.replace(".", "_")

        for mat in bpy.data.materials:
            if mat is None:
                continue
            mat.name = (mat.name).replace(" ", "_")
            mat.name = (mat.name).replace(".", "_")

        for slot in obj.material_slots:
            mat = slot.material
            if mat is None:
                continue
            mat.name = (mat.name).replace(" ", "_")
            mat.name = (mat.name).replace(".", "_")
        return

    for obj in bpy.data.objects:
        obj.name = (obj.name).replace(" ", "_")
        obj.name = (obj.name).replace(".", "_")

        if obj.type == "MESH":
            for uv_map in obj.data.uv_layers:
                uv_map.name = uv_map.name.replace(
                    ".", "_"
                )  # if uv has "." in name the node will export wrong in USD

    for mat in bpy.data.materials:
        if mat is None:
            continue
        mat.name = (mat.name).replace(" ", "_")
        mat.name = (mat.name).replace(".", "_")


def remove_obj_parents(obj=None):
    if obj is not None:
        old_location = obj.matrix_world.to_translation()
        obj.parent = None
        obj.matrix_world.translation = old_location
        return

    for obj in bpy.data.objects:
        old_location = obj.matrix_world.to_translation()
        obj.parent = None
        obj.matrix_world.translation = old_location


def delete_objects():
    logger.info("Deleting placeholders collection")
    collection_name = "placeholders"
    collection = bpy.data.collections.get(collection_name)

    if collection:
        for scene in bpy.data.scenes:
            if collection.name in scene.collection.children:
                scene.collection.children.unlink(collection)

        for obj in collection.objects:
            bpy.data.objects.remove(obj, do_unlink=True)

        def delete_child_collections(parent_collection):
            for child_collection in parent_collection.children:
                delete_child_collections(child_collection)
                bpy.data.collections.remove(child_collection)

        delete_child_collections(collection)
        bpy.data.collections.remove(collection)

    if bpy.data.objects.get("Grid"):
        bpy.data.objects.remove(bpy.data.objects["Grid"], do_unlink=True)

    if bpy.data.objects.get("atmosphere"):
        bpy.data.objects.remove(bpy.data.objects["atmosphere"], do_unlink=True)

    if bpy.data.objects.get("KoleClouds"):
        bpy.data.objects.remove(bpy.data.objects["KoleClouds"], do_unlink=True)


def rename_all_meshes(obj=None):
    if obj is not None:
        if obj.data and obj.data.users == 1:
            obj.data.name = obj.name
        return

    for obj in bpy.data.objects:
        if obj.data and obj.data.users == 1:
            obj.data.name = obj.name


def update_visibility():
    outliner_area = next(
        a for a in bpy.context.screen.areas if a.type == "OUTLINER"
    )
    space = outliner_area.spaces[0]
    space.show_restrict_column_viewport = (
        True  # Global visibility (Monitor icon)
    )
    collection_view = {}
    obj_view = {}
    for collection in bpy.data.collections:
        collection_view[collection] = collection.hide_render
        collection.hide_viewport = False  # reenables viewports for all
        collection.hide_render = False  # enables renders for all collections

    # disables viewports and renders for all objs
    for obj in bpy.data.objects:
        obj_view[obj] = obj.hide_render
        obj.hide_viewport = True
        obj.hide_render = True
        obj.hide_set(0)

    return collection_view, obj_view


def uv_unwrap(obj):
    obj.select_set(True)
    bpy.context.view_layer.objects.active = obj

    obj.data.uv_layers.new(name="ExportUV")
    bpy.context.object.data.uv_layers["ExportUV"].active = True

    logger.info("UV Unwrapping")
    bpy.ops.object.mode_set(mode="EDIT")
    bpy.ops.mesh.select_all(action="SELECT")
    try:
        bpy.ops.uv.smart_project(angle_limit=0.7)
    except RuntimeError:
        logger.info("UV Unwrap failed, skipping mesh")
        bpy.ops.object.mode_set(mode="OBJECT")
        obj.select_set(False)
        return False
    bpy.ops.object.mode_set(mode="OBJECT")
    obj.select_set(False)
    return True


def bakeVertexColors(obj):
    logger.info(f"Baking vertex color on {obj}")
    bpy.ops.object.select_all(action="DESELECT")
    obj.select_set(True)
    bpy.context.view_layer.objects.active = obj
    vertColor = bpy.context.object.data.color_attributes.new(
        name="VertColor", domain="CORNER", type="BYTE_COLOR"
    )
    bpy.context.object.data.attributes.active_color = vertColor
    bpy.ops.object.bake(
        type="DIFFUSE", pass_filter={"COLOR"}, target="VERTEX_COLORS"
    )
    obj.select_set(False)


def apply_baked_tex(obj, paramDict={}):
    bpy.context.view_layer.objects.active = obj
    bpy.context.object.data.uv_layers["ExportUV"].active_render = True
    for uv_layer in reversed(obj.data.uv_layers):
        if "ExportUV" not in uv_layer.name:
            logger.info(f"Removed extraneous UV Layer {uv_layer}")
            obj.data.uv_layers.remove(uv_layer)

    for slot in obj.material_slots:
        mat = slot.material
        if mat is None:
            continue
        mat.use_nodes = True
        nodes = mat.node_tree.nodes
        logger.info("Reapplying baked texs on " + mat.name)

        # delete all nodes except baked nodes and bsdf
        excludedNodes = [type + "_node" for type in ALL_BAKE]
        excludedNodes.extend(["Material Output", "Principled BSDF"])
        for n in nodes:
            if n.name not in excludedNodes:
                nodes.remove(
                    n
                )  # deletes an arbitrary principled BSDF in the case of a mix, which is handled below

        output = nodes["Material Output"]

        # stick baked texture in material
        if nodes.get("Principled BSDF") is None:  # no bsdf
            logger.info("No BSDF, creating new one")
            principled_bsdf_node = nodes.new("ShaderNodeBsdfPrincipled")
        elif (
            len(output.inputs[0].links) != 0
            and output.inputs[0].links[0].from_node.bl_idname
            == "ShaderNodeBsdfPrincipled"
        ):  # trivial bsdf graph
            logger.info("Trivial shader graph, using old BSDF")
            principled_bsdf_node = nodes["Principled BSDF"]
        else:
            logger.info("Non-trivial shader graph, creating new BSDF")
            nodes.remove(
                nodes["Principled BSDF"]
            )  # shader graph was a mix of bsdfs
            principled_bsdf_node = nodes.new("ShaderNodeBsdfPrincipled")

        links = mat.node_tree.links

        # create the new shader node links
        links.new(output.inputs[0], principled_bsdf_node.outputs[0])
        for type in ALL_BAKE:
            if not nodes.get(type + "_node"):
                continue
            tex_node = nodes[type + "_node"]
            if type == "NORMAL":
                normal_node = nodes.new("ShaderNodeNormalMap")
                links.new(normal_node.inputs["Color"], tex_node.outputs[0])
                links.new(
                    principled_bsdf_node.inputs[ALL_BAKE[type]],
                    normal_node.outputs[0],
                )
                continue
            links.new(
                principled_bsdf_node.inputs[ALL_BAKE[type]],
                tex_node.outputs[0],
            )

        # bring back cleared param values
        if mat.name in paramDict:
            principled_bsdf_node.inputs["Metallic"].default_value = paramDict[
                mat.name
            ]["Metallic"]
            principled_bsdf_node.inputs["Sheen Weight"].default_value = (
                paramDict[mat.name]["Sheen Weight"]
            )
            principled_bsdf_node.inputs["Coat Weight"].default_value = (
                paramDict[mat.name]["Coat Weight"]
            )


def create_glass_shader(node_tree, export_usd):
    nodes = node_tree.nodes
    if nodes.get("Glass BSDF"):
        color = nodes["Glass BSDF"].inputs[0].default_value
        roughness = nodes["Glass BSDF"].inputs[1].default_value
        ior = nodes["Glass BSDF"].inputs[2].default_value

    if nodes.get("Principled BSDF"):
        nodes.remove(nodes["Principled BSDF"])

    principled_bsdf_node = nodes.new("ShaderNodeBsdfPrincipled")

    if nodes.get("Glass BSDF"):
        principled_bsdf_node.inputs["Base Color"].default_value = color
        principled_bsdf_node.inputs["Roughness"].default_value = roughness
        principled_bsdf_node.inputs["IOR"].default_value = ior
    else:
        principled_bsdf_node.inputs["Roughness"].default_value = 0

    principled_bsdf_node.inputs["Transmission Weight"].default_value = 1
    if export_usd:
        principled_bsdf_node.inputs["Alpha"].default_value = 0.6
    node_tree.links.new(
        principled_bsdf_node.outputs[0], nodes["Material Output"].inputs[0]
    )


def process_glass_materials(obj, export_usd):
    for slot in obj.material_slots:
        mat = slot.material
        if mat is None or not mat.use_nodes:
            continue
        nodes = mat.node_tree.nodes
        outputNode = nodes["Material Output"]
        if nodes.get("Glass BSDF"):
            if (
                outputNode.inputs[0].links[0].from_node.bl_idname
                == "ShaderNodeBsdfGlass"
            ):
                logger.info(f"Creating glass material on {obj.name}")
            else:
                logger.info(
                    f"Non-trivial glass material on {obj.name}, material export will be inaccurate"
                )
            create_glass_shader(mat.node_tree, export_usd)
        elif "glass" in mat.name or "shader_lamp_bulb" in mat.name:
            logger.info(f"Creating glass material on {obj.name}")
            create_glass_shader(mat.node_tree, export_usd)


def bake_pass(
    obj, dest: Path, img_size, bake_type, export_usd, export_name=None
):
    if export_name is None:
        img = bpy.data.images.new(
            f"{obj.name}_{bake_type}", img_size, img_size
        )
        clean_name = (
            (obj.name).replace(" ", "_").replace(".", "_").replace("/", "_")
        )
        clean_name = (
            clean_name.replace("(", "_").replace(")", "").replace("-", "_")
        )
        file_path = dest / f"{clean_name}_{bake_type}.png"
    else:
        img = bpy.data.images.new(
            f"{export_name}_{bake_type}", img_size, img_size
        )
        file_path = dest / f"{export_name}_{bake_type}.png"
    dest = dest / "textures"

    bake_obj = False
    bake_exclude_mats = {}

    # materials are stored as stack so when removing traverse the reversed list
    for index, slot in reversed(list(enumerate(obj.material_slots))):
        mat = slot.material
        if mat is None:
            bpy.context.object.active_material_index = index
            bpy.ops.object.material_slot_remove()
            continue

        logger.info(mat.name)
        mat.use_nodes = True
        nodes = mat.node_tree.nodes

        output = nodes["Material Output"]

        img_node = nodes.new("ShaderNodeTexImage")
        img_node.name = f"{bake_type}_node"
        img_node.image = img
        img_node.select = True
        nodes.active = img_node
        img_node.select = True

        if len(output.inputs["Displacement"].links) != 0:
            bake_obj = True

        if len(output.inputs[0].links) == 0:
            logger.info(
                f"{mat.name} has no surface output, not using baked textures"
            )
            bake_exclude_mats[mat] = img_node
            continue

        # surface_node = output.inputs[0].links[0].from_node
        # if (
        #     bake_type in ALL_BAKE
        #     and surface_node.bl_idname == "ShaderNodeBsdfPrincipled"
        #     and len(surface_node.inputs[ALL_BAKE[bake_type]].links) == 0
        # ):  # trivial bsdf graph
        #     logger.info(
        #         f"{mat.name} has no procedural input for {bake_type}, not using baked textures"
        #     )
        #     bake_exclude_mats[mat] = img_node
        #     continue

        bake_obj = True

    if bake_type in SPECIAL_BAKE:
        internal_bake_type = "EMIT"
    else:
        internal_bake_type = bake_type

    if bake_obj:
        logger.info(f"Baking {bake_type} pass")
        bpy.ops.object.bake(
            type=internal_bake_type,
            pass_filter={"COLOR"},
            save_mode="EXTERNAL",
        )
        img.filepath_raw = str(file_path)
        img.save()
        logger.info(f"Saving to {file_path}")
    else:
        logger.info(
            f"No necessary materials to bake on {obj.name}, skipping bake"
        )

    for mat, img_node in bake_exclude_mats.items():
        mat.node_tree.nodes.remove(img_node)


def bake_special_emit(
    obj, dest, img_size, export_usd, bake_type, export_name=None
):
    # If at least one material has both a BSDF and non-zero bake type value, then bake
    should_bake = False

    # (Root node, From Socket, To Socket)
    links_removed = []
    links_added = []

    for slot in obj.material_slots:
        mat = slot.material
        if mat is None:
            logger.warn("No material on mesh, skipping...")
            continue
        if not mat.use_nodes:
            logger.warn("Material has no nodes, skipping...")
            continue

        nodes = mat.node_tree.nodes
        principled_bsdf_node = None
        root_node = None
        logger.info(f"{mat.name} has {len(nodes)} nodes: {nodes}")
        for node in nodes:
            if node.type != "GROUP":
                continue

            for subnode in node.node_tree.nodes:
                logger.info(
                    f" [{subnode.type}] {subnode.name} {subnode.bl_idname}"
                )
                if subnode.type == "BSDF_PRINCIPLED":
                    logger.debug(f" BSDF_PRINCIPLED: {subnode.inputs}")
                    principled_bsdf_node = subnode
                    root_node = node

        if nodes.get("Principled BSDF"):
            principled_bsdf_node = nodes["Principled BSDF"]
            root_node = mat
        elif not principled_bsdf_node:
            logger.warn("No Principled BSDF, skipping...")
            continue
        elif ALL_BAKE[bake_type] not in principled_bsdf_node.inputs:
            logger.warn(f"No {bake_type} input, skipping...")
            continue

        # Here, we"ve found the proper BSDF and bake type input. Set up the scene graph
        # for baking.
        outputSoc = principled_bsdf_node.outputs[0].links[0].to_socket

        # Remove the BSDF link to Output first
        link = principled_bsdf_node.outputs[0].links[0]
        from_socket, to_socket = link.from_socket, link.to_socket
        logger.debug(f"Removing link: {from_socket.name} => {to_socket.name}")
        root_node.node_tree.links.remove(link)
        links_removed.append((root_node, from_socket, to_socket))

        # Get bake_type value
        bake_input = principled_bsdf_node.inputs[ALL_BAKE[bake_type]]
        bake_val = bake_input.default_value
        logger.info(f"{bake_type} value: {bake_val}")

        if bake_val > 0:
            should_bake = True

        # Make a color input matching the metallic value
        col = root_node.node_tree.nodes.new("ShaderNodeRGB")
        col.outputs[0].default_value = (bake_val, bake_val, bake_val, 1.0)

        # Link the color to output
        new_link = root_node.node_tree.links.new(col.outputs[0], outputSoc)
        links_added.append((root_node, col.outputs[0], outputSoc))
        logger.debug(
            f"Linking {col.outputs[0].name} to {outputSoc.name}({outputSoc.bl_idname}): {new_link}"
        )

    # After setting up all materials, bake if applicable
    if should_bake:
        bake_pass(obj, dest, img_size, bake_type, export_usd, export_name)

    # After baking, undo the temporary changes to the scene graph
    for n, from_soc, to_soc in links_added:
        logger.debug(
            f"Removing added link:\t{n.name}: {from_soc.name} => {to_soc.name}"
        )
        for l in n.node_tree.links:
            if l.from_socket == from_soc and l.to_socket == to_soc:
                n.node_tree.links.remove(l)
                logger.debug(
                    f"Removed link:\t{n.name}: {from_soc.name} => {to_soc.name}"
                )

    for n, from_soc, to_soc in links_removed:
        logger.debug(
            f"Adding back link:\t{n.name}: {from_soc.name} => {to_soc.name}"
        )
        n.node_tree.links.new(from_soc, to_soc)


def remove_params(mat, node_tree):
    nodes = node_tree.nodes
    paramDict = {}
    if nodes.get("Material Output"):
        output = nodes["Material Output"]
    elif nodes.get("Group Output"):
        output = nodes["Group Output"]
    else:
        raise ValueError("Could not find material output node")

    if (
        nodes.get("Principled BSDF")
        and output.inputs[0].links[0].from_node.bl_idname
        == "ShaderNodeBsdfPrincipled"
    ):
        principled_bsdf_node = nodes["Principled BSDF"]
        metal = principled_bsdf_node.inputs[
            "Metallic"
        ].default_value  # store metallic value and set to 0
        sheen = principled_bsdf_node.inputs["Sheen Weight"].default_value
        clearcoat = principled_bsdf_node.inputs["Coat Weight"].default_value
        paramDict[mat.name] = {
            "Metallic": metal,
            "Sheen Weight": sheen,
            "Coat Weight": clearcoat,
        }
        principled_bsdf_node.inputs["Metallic"].default_value = 0
        principled_bsdf_node.inputs["Sheen Weight"].default_value = 0
        principled_bsdf_node.inputs["Coat Weight"].default_value = 0
        return paramDict

    for node in nodes:
        if node.type == "GROUP":
            paramDict = remove_params(mat, node.node_tree)
            if len(paramDict) != 0:
                return paramDict

    return paramDict


def process_interfering_params(obj):
    for slot in obj.material_slots:
        mat = slot.material
        if mat is None or not mat.use_nodes:
            continue
        paramDict = remove_params(mat, mat.node_tree)
    return paramDict


def skipBake(obj):
    if not obj.data.materials:
        logger.info("No material on mesh, skipping...")
        return True

    if len(obj.data.vertices) == 0:
        logger.info("Mesh has no vertices, skipping ...")
        return True

    return False


def triangulate_mesh(obj: bpy.types.Object):
    logger.debug("Triangulating Mesh")
    if obj.type == "MESH":
        view_state = obj.hide_viewport
        obj.hide_viewport = False
        bpy.context.view_layer.objects.active = obj
        obj.select_set(True)
        bpy.ops.object.mode_set(mode="EDIT")
        bpy.ops.mesh.select_all(action="SELECT")
        logger.debug(f"Triangulating {obj}")
        bpy.ops.mesh.quads_convert_to_tris()
        bpy.ops.object.mode_set(mode="OBJECT")
        obj.select_set(False)
        obj.hide_viewport = view_state


def triangulate_meshes():
    logger.debug("Triangulating Meshes")
    for obj in bpy.context.scene.objects:
        if obj.type == "MESH":
            view_state = obj.hide_viewport
            obj.hide_viewport = False
            bpy.context.view_layer.objects.active = obj
            obj.select_set(True)
            bpy.ops.object.mode_set(mode="EDIT")
            bpy.ops.mesh.select_all(action="SELECT")
            logger.debug(f"Triangulating {obj}")
            bpy.ops.mesh.quads_convert_to_tris()
            bpy.ops.object.mode_set(mode="OBJECT")
            obj.select_set(False)
            obj.hide_viewport = view_state


def adjust_wattages():
    logger.info("Adjusting light wattage")
    for obj in bpy.context.scene.objects:
        if obj.type == "LIGHT" and obj.data.type == "POINT":
            light = obj.data
            if hasattr(light, "energy") and hasattr(light, "shadow_soft_size"):
                X = light.energy
                r = light.shadow_soft_size
                # candelas * 1000 / (4 * math.pi * r**2). additionally units come out of blender at 1/100 scale
                new_wattage = (
                    (X * 20 / (4 * math.pi))
                    * 1000
                    / (4 * math.pi * r**2)
                    * 100
                )
                light.energy = new_wattage


def set_center_of_mass():
    logger.info("Resetting center of mass of objects")
    for obj in bpy.context.scene.objects:
        if not obj.hide_render:
            view_state = obj.hide_viewport
            obj.hide_viewport = False
            obj.select_set(True)
            bpy.context.view_layer.objects.active = obj
            bpy.ops.object.origin_set(type="ORIGIN_GEOMETRY", center="MEDIAN")
            obj.select_set(False)
            obj.hide_viewport = view_state


def duplicate_node_groups(node_tree, group_map=None):
    if group_map is None:
        group_map = {}

    for node in node_tree.nodes:
        if node.type == "GROUP":
            group = node.node_tree
            if group not in group_map:
                group_copy = group.copy()
                group_copy.name = f"{group.name}_copy"
                group_map[group] = group_copy

                duplicate_node_groups(group_copy, group_map)
            else:
                group_copy = group_map[group]

            node.node_tree = group_copy

    return group_map


def deep_copy_material(original_material, new_name_suffix="_deepcopy"):
    new_mat = original_material.copy()
    new_mat.name = original_material.name + new_name_suffix
    if new_mat.use_nodes and new_mat.node_tree:
        duplicate_node_groups(new_mat.node_tree)
    return new_mat


def bake_object(obj, dest, img_size, export_usd, export_name=None):
    if not uv_unwrap(obj):
        return

    bpy.ops.object.select_all(action="DESELECT")

    with butil.SelectObjects(obj):
        for slot in obj.material_slots:
            mat = slot.material
            if mat is not None:
                slot.material = deep_copy_material(
                    mat
                )  # we duplicate in the case of distinct meshes sharing materials

        process_glass_materials(obj, export_usd)

        for bake_type in SPECIAL_BAKE:
            bake_special_emit(
                obj, dest, img_size, export_usd, bake_type, export_name
            )

        # bake_normals(obj, dest, img_size, export_usd)
        paramDict = process_interfering_params(obj)
        for bake_type in BAKE_TYPES:
            bake_pass(obj, dest, img_size, bake_type, export_usd, export_name)

        apply_baked_tex(obj, paramDict)


def bake_scene(folderPath: Path, image_res, vertex_colors, export_usd):
    for obj in bpy.data.objects:
        logger.info("---------------------------")
        logger.info(obj.name)

        if obj.type != "MESH" or obj not in list(
            bpy.context.view_layer.objects
        ):
            logger.info("Not mesh, skipping ...")
            continue

        if skipBake(obj):
            continue

        if format == "stl":
            continue

        obj.hide_render = False
        obj.hide_viewport = False

        if vertex_colors:
            bakeVertexColors(obj)
        else:
            bake_object(obj, folderPath, image_res, export_usd)

        obj.hide_render = True
        obj.hide_viewport = True


def run_blender_export(
    exportPath: Path, format: str, vertex_colors: bool, individual_export: bool
):
    assert exportPath.parent.exists()
    exportPath = str(exportPath)

    if format == "obj":
        if vertex_colors:
            bpy.ops.wm.obj_export(
                filepath=exportPath,
                export_colors=True,
                export_eval_mode="DAG_EVAL_RENDER",
                export_selected_objects=individual_export,
            )
        else:
            bpy.ops.wm.obj_export(
                filepath=exportPath,
                path_mode="COPY",
                export_materials=True,
                export_pbr_extensions=False,
                export_eval_mode="DAG_EVAL_RENDER",
                export_selected_objects=individual_export,
                export_triangulated_mesh=True,
                export_normals=False,
            )

    if format == "fbx":
        if vertex_colors:
            bpy.ops.export_scene.fbx(
                filepath=exportPath,
                colors_type="SRGB",
                use_selection=individual_export,
            )
        else:
            bpy.ops.export_scene.fbx(
                filepath=exportPath,
                path_mode="COPY",
                embed_textures=True,
                use_selection=individual_export,
            )

    if format == "stl":
        bpy.ops.export_mesh.stl(
            filepath=exportPath, use_selection=individual_export
        )

    if format == "ply":
        bpy.ops.wm.ply_export(
            filepath=exportPath, export_selected_objects=individual_export
        )

    if format in ["usda", "usdc"]:
        bpy.ops.wm.usd_export(
            filepath=exportPath,
            export_textures=True,
            # use_instancing=True,
            overwrite_textures=True,
            selected_objects_only=individual_export,
            root_prim_path="/World",
        )


def export_scene(
    input_blend: Path,
    output_folder: Path,
    pipeline_folder=None,
    task_uniqname=None,
    **kwargs,
):
    folder = output_folder / f"export_{os.path.splitext(input_blend.name)[0]}"
    folder.mkdir(exist_ok=True, parents=True)
    export_curr_scene(folder, **kwargs)

    if pipeline_folder is not None and task_uniqname is not None:
        (pipeline_folder / "logs" / f"FINISH_{task_uniqname}").touch()

    return folder


# side effects: will remove parents of inputted obj and clean its name, hides viewport of all objects
def export_single_obj(
    obj: bpy.types.Object,
    output_folder: Path,
    format="usdc",
    image_res=1024,
    vertex_colors=False,
):
    export_usd = format in ["usda", "usdc"]

    export_folder = output_folder
    export_folder.mkdir(parents=True, exist_ok=True)
    export_file = export_folder / output_folder.with_suffix(f".{format}").name

    logger.info(f"Exporting to directory {export_folder=}")

    remove_obj_parents(obj)
    rename_all_meshes(obj)

    collection_views, obj_views = update_visibility()

    bpy.context.scene.render.engine = "CYCLES"
    bpy.context.scene.cycles.device = "GPU"
    bpy.context.scene.cycles.samples = 1  # choose render sample
    # Set the tile size
    bpy.context.scene.cycles.tile_x = image_res
    bpy.context.scene.cycles.tile_y = image_res

    if obj.type != "MESH" or obj not in list(bpy.context.view_layer.objects):
        raise ValueError("Object not mesh")

    if export_usd:
        apply_all_modifiers(obj)
    else:
        realizeInstances(obj)
        apply_all_modifiers(obj)

    if not skipBake(obj) and format != "stl":
        if vertex_colors:
            bakeVertexColors(obj)
        else:
            obj.hide_render = False
            obj.hide_viewport = False
            bake_object(obj, export_folder / "textures", image_res, export_usd)
            obj.hide_render = True
            obj.hide_viewport = True

    for collection, status in collection_views.items():
        collection.hide_render = status

    for obj, status in obj_views.items():
        obj.hide_render = status

    clean_names(obj)

    old_loc = obj.location.copy()
    obj.location = (0, 0, 0)

    if (
        obj.type != "MESH"
        or obj.hide_render
        or len(obj.data.vertices) == 0
        or obj not in list(bpy.context.view_layer.objects)
    ):
        raise ValueError("Object is not mesh or hidden from render")

    export_subfolder = export_folder / obj.name
    export_subfolder.mkdir(exist_ok=True)
    export_file = export_subfolder / f"{obj.name}.{format}"

    logger.info(f"Exporting file to {export_file=}")
    obj.hide_viewport = False
    obj.select_set(True)
    run_blender_export(
        export_file, format, vertex_colors, individual_export=True
    )
    obj.select_set(False)
    obj.location = old_loc

    return export_file


def export_sim_ready(
    obj: bpy.types.Object,
    output_folder: Path,
    image_res: int = 1024,
    translation: Tuple = (0, 0, 0),
    name: Optional[str] = None,
    visual_only: bool = False,
    collision_only: bool = False,
    separate_asset_dirs: bool = True,
) -> Dict[str, List[Path]]:
    """Exports both the visual and collision assets for a geometry."""
    if not visual_only:
        assert (
            coacd is not None
        ), "coacd is required to export simulation assets."

    asset_exports = defaultdict(list)
    export_name = name if name is not None else obj.name

    if separate_asset_dirs:
        visual_export_folder = output_folder / "visual"
        collision_export_folder = output_folder / "collision"
    else:
        visual_export_folder = output_folder
        collision_export_folder = output_folder

    texture_export_folder = output_folder / "textures"

    visual_export_folder.mkdir(parents=True, exist_ok=True)
    collision_export_folder.mkdir(parents=True, exist_ok=True)

    logger.info(f"Exporting to directory {output_folder=}")

    collection_views, obj_views = update_visibility()

    bpy.context.scene.render.engine = "CYCLES"
    bpy.context.scene.cycles.device = "GPU"
    bpy.context.scene.cycles.samples = 1  # choose render sample
    # Set the tile size
    bpy.context.scene.cycles.tile_x = image_res
    bpy.context.scene.cycles.tile_y = image_res

    if obj.type != "MESH" or obj not in list(bpy.context.view_layer.objects):
        raise ValueError("Object not mesh")

    # export the textures
    if not skipBake(obj):
        texture_export_folder.mkdir(parents=True, exist_ok=True)
        obj.hide_render = False
        obj.hide_viewport = False
        bake_object(obj, texture_export_folder, image_res, False, export_name)
        obj.hide_render = True
        obj.hide_viewport = True

    for collection, status in collection_views.items():
        collection.hide_render = status

    for obj_tmp, status in obj_views.items():
        obj_tmp.hide_render = status

    # translating object
    old_loc = obj.location.copy()
    obj.location = (
        old_loc[0] + translation[0],
        old_loc[1] + translation[1],
        old_loc[2] + translation[2],
    )

    if (
        obj.type != "MESH"
        or obj.hide_render
        or len(obj.data.vertices) == 0
        or obj not in list(bpy.context.view_layer.objects)
    ):
        raise ValueError("Object is not mesh or hidden from render")

    # export the mesh assets
    visual_export_file = visual_export_folder / f"{export_name}.obj"

    logger.info(f"Exporting file to {visual_export_file=}")
    obj.hide_viewport = False
    obj.select_set(True)

    # export visual asset
    with butil.SelectObjects(obj, active=1):
        bpy.ops.wm.obj_export(
            filepath=str(visual_export_file),
            up_axis="Z",
            forward_axis="Y",
            export_selected_objects=True,
            export_triangulated_mesh=True,  # required for coacd to run properly
        )
    if not collision_only:
        asset_exports["visual"].append(visual_export_file)

    if visual_only:
        obj.select_set(False)
        obj.location = old_loc
        return asset_exports

    clone = butil.deep_clone_obj(obj)
    parts = butil.split_object(clone)

    part_export_obj_file = visual_export_folder / f"{export_name}_part.obj"
    part_export_mtl_file = visual_export_folder / f"{export_name}_part.mtl"

    collision_count = 0
    for part in parts:
        with butil.SelectObjects(part, active=1):
            bpy.ops.wm.obj_export(
                filepath=str(part_export_obj_file),
                up_axis="Z",
                forward_axis="Y",
                export_selected_objects=True,
                export_triangulated_mesh=True,  # required for coacd to run properly
            )

        # export the collision meshes
        mesh_tri = trimesh.load(
            str(part_export_obj_file),
            merge_norm=True,
            merge_tex=True,
            force="mesh",
        )
        trimesh.repair.fix_inversion(mesh_tri)
        preprocess_mode = "off"
        if not mesh_tri.is_volume:
            print(
                mesh_tri.is_watertight,
                mesh_tri.is_winding_consistent,
                np.isfinite(mesh_tri.center_mass).all(),
                mesh_tri.volume > 0.0,
            )
            preprocess_mode = "on"

            if len(mesh_tri.vertices) < 4:
                logger.warning(
                    f"Mesh is not a volume. Only has {len(mesh_tri.vertices)} vertices."
                )
                # raise ValueError(f"Mesh is not a volume. Only has {len(mesh_tri.vertices)} vertices.")
        mesh = coacd.Mesh(mesh_tri.vertices, mesh_tri.faces)

        subparts = coacd.run_coacd(
            mesh=mesh,
            threshold=0.05,
            max_convex_hull=-1,
            preprocess_mode=preprocess_mode,
            mcts_max_depth=3,
        )
        export_name = export_name.replace("vis", "col")
        for vs, fs in subparts:
            collision_export_file = (
                collision_export_folder
                / f"{export_name}_col{collision_count}.obj"
            )
            subpart_mesh = trimesh.Trimesh(vs, fs)

            # if subpart_mesh.is_empty:
            #     raise ValueError(
            #         "Warning: Collision mesh is completely outside the bounds of the original mesh."
            #     )
            subpart_mesh.export(str(collision_export_file))
            asset_exports["collision"].append(collision_export_file)
            collision_count += 1

    # delete temporary part files
    part_export_obj_file.unlink(missing_ok=True)
    part_export_mtl_file.unlink(missing_ok=True)

    obj.select_set(False)
    obj.location = old_loc
    butil.delete(clone)

    return asset_exports


@gin.configurable
def export_curr_scene(
    output_folder: Path,
    format="usdc",
    image_res=1024,
    vertex_colors=False,
    individual_export=False,
    omniverse_export=False,
    pipeline_folder=None,
    task_uniqname=None,
    deconvex=False,
    center_scene=False,
    align_quat=(0.7071, 0, 0, 0.7071),  # xyzw
) -> Path:
    export_usd = format in ["usda", "usdc"]
    export_folder = output_folder
    export_folder.mkdir(exist_ok=True)
    export_file = export_folder / output_folder.with_suffix(f".{format}").name
    logger.info(f"Exporting to directory {export_folder=}")

    remove_obj_parents()
    delete_objects()
    triangulate_meshes()
    if omniverse_export and format not in ["usda", "usdc"]:
        split_glass_mats()
    rename_all_meshes()

    # remove 0 polygon meshes
    for obj in bpy.data.objects:
        if obj.type == "MESH" and len(obj.data.polygons) == 0:
            logger.info(f"{obj.name} has no faces, removing...")
            bpy.data.objects.remove(obj, do_unlink=True)

    if center_scene:
        from mathutils import Vector

        positions = []
        view_objs = set(bpy.context.view_layer.objects)
        for obj in bpy.data.objects:
            if (
                obj.type == "MESH"
                and obj.data
                and obj.data.vertices
                and obj.data.polygons
                and not obj.hide_render
                and obj in view_objs
            ):
                pos = np.array(obj.matrix_world.translation)
                if not np.allclose(pos, 0):
                    positions.append(pos)

        if len(positions) > 0:
            positions = np.stack(positions)
            center = (positions.min(axis=0) + positions.max(axis=0)) * 0.5
            center[2] = positions[:, 2].min()  # Set floor to 0 among z-axis.
            for obj in bpy.data.objects:
                pos = np.array(obj.matrix_world.translation)
                if not np.allclose(pos, 0):
                    obj.location -= Vector(center)

    scatter_cols = []
    if export_usd:
        if bpy.data.collections.get("scatter"):
            scatter_cols.append(bpy.data.collections["scatter"])
        if bpy.data.collections.get("scatters"):
            scatter_cols.append(bpy.data.collections["scatters"])
        for col in scatter_cols:
            for obj in col.all_objects:
                remove_shade_smooth(obj)

    collection_views, obj_views = update_visibility()
    for obj in bpy.data.objects:
        if obj.type != "MESH" or obj not in list(
            bpy.context.view_layer.objects
        ):
            continue
        if export_usd:
            apply_all_modifiers(obj)
        else:
            realizeInstances(obj)
            apply_all_modifiers(obj)

    bpy.context.scene.render.engine = "CYCLES"
    bpy.context.scene.cycles.device = "GPU"
    bpy.context.scene.cycles.samples = 1  # choose render sample
    # Set the tile size
    bpy.context.scene.cycles.tile_x = image_res
    bpy.context.scene.cycles.tile_y = image_res

    # iterate through all objects and bake them
    bake_scene(
        folderPath=export_folder / "textures",
        image_res=image_res,
        vertex_colors=vertex_colors,
        export_usd=export_usd,
    )

    for collection, status in collection_views.items():
        collection.hide_render = status

    for obj, status in obj_views.items():
        obj.hide_render = status

    clean_names()

    for obj in bpy.data.objects:
        obj.hide_viewport = obj.hide_render

    if omniverse_export:
        adjust_wattages()
        set_center_of_mass()

    if individual_export:
        import math
        import xml.etree.ElementTree as ET
        from xml.dom import minidom

        import trimesh
        from scipy.spatial.transform import Rotation
        from embodied_gen.data.convex_decomposer import decompose_convex_mesh

        urdf_root = ET.Element("robot", name="multi_object_scene")
        ET.SubElement(urdf_root, "link", name="base")
        object_info = []
        bpy.ops.object.select_all(action="DESELECT")
        objects = list(bpy.data.objects)
        for obj in objects:
            if (
                obj.type != "MESH"
                or obj.data is None
                or len(obj.data.vertices) == 0
                or len(obj.data.polygons) == 0
                or obj.hide_render
                or obj not in list(bpy.context.view_layer.objects)
            ):
                continue

            obj_name = obj.name.replace("/", "_").replace("-", "_")
            obj_name = obj_name.replace("(", "_").replace(")", "")
            obj.name = obj_name
            export_subfolder = export_folder / obj_name
            export_subfolder.mkdir(exist_ok=True, parents=True)
            export_file = export_subfolder / f"{obj_name}.{format}"

            if "skirtingboard" in obj_name.lower():
                logger.info(f"Skipping skirting board {obj_name}")
                continue

            logger.info(f"Exporting file to {export_file=}")
            obj.hide_viewport = False

            position = obj.matrix_world.to_translation()
            rotation = Rotation.from_quat(align_quat)
            rotation = rotation.as_euler("xyz", degrees=False)

            obj.select_set(True)
            bpy.context.view_layer.objects.active = obj
            bpy.ops.object.location_clear()

            face_count = len(obj.data.polygons)
            if face_count > 1000:
                if face_count > 1000000:
                    ratio = 0.005
                elif face_count > 100000:
                    ratio = 0.02
                elif face_count > 10000:
                    ratio = 0.1
                else:
                    ratio = 0.2
                angle_threshold = math.radians(5)
                bpy.ops.object.mode_set(mode="OBJECT")
                dec_mod = obj.modifiers.new(name="Decimate", type="DECIMATE")
                dec_mod.decimate_type = "DISSOLVE"
                dec_mod.angle_limit = angle_threshold
                dec_mod.use_collapse_triangulate = False
                dec_mod.ratio = ratio
                bpy.ops.object.modifier_apply(modifier=dec_mod.name)

            run_blender_export(
                export_file, format, vertex_colors, individual_export
            )
            obj.select_set(False)

            mesh = trimesh.load(export_file)
            if isinstance(mesh, trimesh.Scene) and len(mesh.geometry) == 0:
                shutil.rmtree(export_file.parent)
                continue

            object_info.append(
                {
                    "name": obj_name,
                    "mesh_path": f"{obj_name}/{obj_name}.{format}",
                    "mesh_abs_path": str(export_file),
                    "xyz": tuple(position),
                    "rpy": tuple(rotation),
                }
            )

        for obj in object_info:
            link = ET.SubElement(urdf_root, "link", name=obj["name"])
            visual = ET.SubElement(link, "visual")
            geom = ET.SubElement(visual, "geometry")
            ET.SubElement(
                geom, "mesh", filename=obj["mesh_path"], scale="1 1 1"
            )
            if deconvex:
                print("Deconvexing mesh for collision, waiting...")
                d_params = dict(
                    threshold=0.05, max_convex_hull=128, verbose=False
                )
                mesh_path = obj["mesh_abs_path"]
                output_path = mesh_path.replace(".obj", "_collision.obj")
                decompose_convex_mesh(mesh_path, output_path, **d_params)
                collision_mesh = obj["mesh_path"].replace(
                    ".obj", "_collision.obj"
                )
                collision = ET.SubElement(link, "collision")
                geom2 = ET.SubElement(collision, "geometry")
                ET.SubElement(
                    geom2, "mesh", filename=collision_mesh, scale="1 1 1"
                )

            joint = ET.SubElement(
                urdf_root, "joint", name=f"joint_{obj['name']}", type="fixed"
            )
            ET.SubElement(joint, "parent", link="base")
            ET.SubElement(joint, "child", link=obj["name"])
            ET.SubElement(
                joint,
                "origin",
                xyz="%.4f %.4f %.4f" % obj["xyz"],
                rpy="%.4f %.4f %.4f" % obj["rpy"],
            )

        urdf_str = minidom.parseString(ET.tostring(urdf_root)).toprettyxml(
            indent="  "
        )
        urdf_path = export_folder / "scene.urdf"
        with open(urdf_path, "w") as f:
            f.write(urdf_str)
        logger.info(f"URDF exported to {urdf_path}")

        return urdf_path
    else:
        logger.info(f"Exporting file to {export_file=}")
        run_blender_export(
            export_file, format, vertex_colors, individual_export
        )

        return export_file


def main(args):
    args.output_folder.mkdir(exist_ok=True)
    targets = sorted(list(args.input_folder.iterdir()))
    for blendfile in targets:
        if not blendfile.suffix == ".blend":
            print(f"Skipping non-blend file {blendfile}")
            continue

        bpy.ops.wm.open_mainfile(filepath=str(blendfile))

        folder = export_scene(
            blendfile,
            args.output_folder,
            format=args.format,
            image_res=args.resolution,
            vertex_colors=args.vertex_colors,
            individual_export=args.individual,
            omniverse_export=args.omniverse,
            deconvex=args.deconvex,
            center_scene=args.center_scene,
        )

    bpy.ops.wm.quit_blender()


def make_args():
    parser = argparse.ArgumentParser()

    parser.add_argument("--input_folder", type=Path)
    parser.add_argument("--output_folder", type=Path)

    parser.add_argument("-f", "--format", type=str, choices=FORMAT_CHOICES)

    parser.add_argument("-v", "--vertex_colors", action="store_true")
    parser.add_argument("-r", "--resolution", default=1024, type=int)
    parser.add_argument("-i", "--individual", action="store_true")
    parser.add_argument("-o", "--omniverse", action="store_true")
    parser.add_argument("--deconvex", action="store_true")
    parser.add_argument("--center_scene", action="store_true")

    args = parser.parse_args()

    if args.format not in FORMAT_CHOICES:
        raise ValueError("Unsupported or invalid file format.")

    if args.vertex_colors and args.format not in ["ply", "fbx", "obj"]:
        raise ValueError("File format does not support vertex colors.")

    if args.format == "ply" and not args.vertex_colors:
        raise ValueError(".ply export must use vertex colors.")

    return args


if __name__ == "__main__":
    args = make_args()
    main(args)