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
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
# =============================================================================
# HOW TO RUN - Verified in Blender v5.0.1
# =============================================================================
# This script must be executed through Blender, not standard Python.
#
# Example:
# blender --background --python apply_decomposition_from_json.py -- \
#     --glb "path/to/scene.glb" \
#     --json "path/to/decomposition.json" \
#     --out_blend "path/to/output.blend"
#
# IMPORTANT:
# The "--" separator is required. Everything after it is passed to this script.
#
# Inputs:
#   --glb         Path to the source GLB/GLTF file
#   --json        Path to decomposition_mapping JSON file
#   --out_blend   Output .blend file with decomposition colors applied
#
# Optional:
#   --tolerance   (default: 1e-5) Matching tolerance for static meshes
#   --report_json Output path for match report JSON
# =============================================================================

import bpy
import json
import random
import argparse
from mathutils import Vector

import sys
import os

# Optional local package path for Blender Python environments.
if "APPDATA" in os.environ:
    pkg = os.path.join(os.environ["APPDATA"], "blender_packages")
    sys.path.insert(0, pkg)


# =============================================================================
# Public tool configuration
# =============================================================================

NORMALISE_CONTAINER_NAME = "NORMALISE_CONTAINER"
EMISSION_STRENGTH = 0.6
DEFAULT_TOLERANCE = 1e-5
DEFAULT_REPORT_PATH_SUFFIX = ".decomposition_report.json"


# =============================================================================
# Logging / scene setup
# =============================================================================

def log(msg):
    """Print a namespaced message so command-line output is easy to scan."""
    print(f"[apply_decomposition_from_json] {msg}")


def reset_scene():
    """

    Clear the current Blender scene before importing the target GLB/GLTF.



    This makes every run deterministic and prevents objects/materials from a

    previous file from contaminating the decomposition mapping process.

    """
    if bpy.ops.object.mode_set.poll():
        try:
            bpy.ops.object.mode_set(mode="OBJECT")
        except Exception:
            pass

    if bpy.ops.object.select_all.poll():
        bpy.ops.object.select_all(action="SELECT")
        bpy.ops.object.delete(use_global=False)

    for datablock_collection in (
        bpy.data.meshes,
        bpy.data.materials,
        bpy.data.images,
        bpy.data.textures,
        bpy.data.curves,
        bpy.data.armatures,
        bpy.data.cameras,
        bpy.data.lights,
        bpy.data.node_groups,
    ):
        for datablock in list(datablock_collection):
            if datablock.users == 0:
                try:
                    datablock_collection.remove(datablock)
                except Exception:
                    pass


# =============================================================================
# Import / hierarchy helpers
# =============================================================================

def import_glb(glb_path):
    """Import a GLB/GLTF file into the clean Blender scene."""
    bpy.ops.import_scene.gltf(filepath=glb_path)


def scene_bounds():
    """

    Return the full scene bounds in world space.



    Returns:

        min_co: world-space minimum corner

        max_co: world-space maximum corner

        centre: world-space center

        longest_side: longest scene dimension, clamped above zero

    """
    corners = []

    for obj in [o for o in bpy.context.scene.objects if o.type == "MESH"]:
        for corner in obj.bound_box:
            corners.append(obj.matrix_world @ Vector(corner))

    if not corners:
        zero = Vector((0.0, 0.0, 0.0))
        return zero, zero, zero, 1.0

    mn = Vector(map(min, zip(*corners)))
    mx = Vector(map(max, zip(*corners)))
    centre = (mn + mx) / 2.0
    longest = max((mx - mn).x, (mx - mn).y, (mx - mn).z)

    return mn, mx, centre, max(longest, 1e-6)


def normalise_scene():
    """

    Center and uniformly scale the whole imported scene using a parent container.



    Important:

        The transform is applied to the container only, not directly to meshes.

        This avoids breaking armatures, constraints, parent relationships, and

        animated/rigged objects.

    """
    _, _, centre, longest = scene_bounds()
    scale_factor = 1.0 / longest

    scene = bpy.context.scene
    root_objects = [o for o in scene.objects if o.parent is None]

    bpy.ops.object.empty_add(type="PLAIN_AXES", location=(0, 0, 0))
    container = bpy.context.active_object
    container.name = NORMALISE_CONTAINER_NAME

    for obj in root_objects:
        obj.parent = container

    container.location = -centre * scale_factor
    container.scale = (scale_factor, scale_factor, scale_factor)

    bpy.context.view_layer.update()
    return container


def all_descendants(root):
    """Return every descendant object below a root object."""
    stack = list(root.children)
    result = []

    while stack:
        obj = stack.pop()
        result.append(obj)
        stack.extend(list(obj.children))

    return result


def collect_meshes_under_container(root):
    """Return all mesh objects below NORMALISE_CONTAINER."""
    return [obj for obj in all_descendants(root) if obj.type == "MESH"]


# =============================================================================
# Animated / rigged mesh protection
# =============================================================================

def split_static_and_animated_meshes(root, anim_rig_names=None):
    """

    Split visible meshes under NORMALISE_CONTAINER into static and animated lists.



    Animated/rigged object names come exclusively from the JSON's ``anim_rig``

    key (via ``anim_rig_names``).  If that set is empty, all meshes are static.



    Args:

        root:            The NORMALISE_CONTAINER object.

        anim_rig_names:  frozenset of object names from

                         ``decomposition_mapping["anim_rig"]``.

    """
    anim_rig_names = anim_rig_names or frozenset()
    visible = [
        o for o in collect_meshes_under_container(root)
        if not o.hide_viewport and not o.hide_render and o.visible_get()
    ]
    anim_meshes   = [o for o in visible if o.name in anim_rig_names]
    static_meshes = [o for o in visible if o.name not in anim_rig_names]
    return static_meshes, anim_meshes


# =============================================================================
# Loose separation
# =============================================================================

def separate_loose_parts_under_normalise_container(protected_meshes=None, blockers=None, anim_rig_names=None):
    """

    Separate static meshes into loose parts under NORMALISE_CONTAINER.



    Animated/rigged meshes (identified by name via ``anim_rig_names``) and any

    explicitly protected or blocker meshes are skipped.



    Args:

        protected_meshes:

            Meshes that must not be loose-separated. Usually animated/rigged meshes.

        blockers:

            Optional meshes to skip, such as large planes or environment spheres.

        anim_rig_names:

            frozenset of object names from ``decomposition_mapping["anim_rig"]``.



    Returns:

        List of newly created mesh objects generated by Blender's loose separation.

    """
    protected_meshes = protected_meshes or []
    blockers = blockers or []
    anim_rig_names = anim_rig_names or frozenset()

    root = bpy.data.objects.get(NORMALISE_CONTAINER_NAME)
    if root is None:
        log("NORMALISE_CONTAINER not found.")
        return []

    exclude_ptrs = {obj.as_pointer() for obj in protected_meshes + blockers if obj is not None}

    target_meshes = [
        obj for obj in root.children_recursive
        if obj.type == "MESH"
        and obj.as_pointer() not in exclude_ptrs
        and obj.name not in anim_rig_names
    ]

    if not target_meshes:
        log("No static target meshes found for LOOSE separation.")
        return []

    view_layer = bpy.context.view_layer
    created_objects = []

    active_obj = view_layer.objects.active
    if active_obj is not None and bpy.ops.object.mode_set.poll():
        try:
            bpy.ops.object.mode_set(mode="OBJECT")
        except Exception:
            pass

    if bpy.ops.object.select_all.poll():
        bpy.ops.object.select_all(action="DESELECT")

    log(f"Perform LOOSE only on static meshes. target_mesh_count={len(target_meshes)}")

    for idx, obj in enumerate(target_meshes, start=1):
        if obj.name not in bpy.data.objects:
            continue

        prev_hide_viewport = obj.hide_viewport
        prev_hide_render = obj.hide_render
        prev_hide_select = obj.hide_select

        try:
            obj.hide_viewport = False
            obj.hide_select = False

            if bpy.ops.object.select_all.poll():
                bpy.ops.object.select_all(action="DESELECT")

            obj.select_set(True)
            view_layer.objects.active = obj

            before_ptrs = {
                o.as_pointer()
                for o in bpy.data.objects
                if o.type == "MESH"
            }

            if bpy.ops.object.mode_set.poll():
                bpy.ops.object.mode_set(mode="EDIT")
            else:
                log(f"Failed on {obj.name}: cannot enter EDIT mode")
                continue

            bpy.ops.mesh.select_all(action="SELECT")
            bpy.ops.mesh.separate(type="LOOSE")

            if bpy.ops.object.mode_set.poll():
                bpy.ops.object.mode_set(mode="OBJECT")

            new_objs = [
                o for o in bpy.data.objects
                if o.type == "MESH" and o.as_pointer() not in before_ptrs
            ]
            created_objects.extend(new_objs)

            if idx % 25 == 0 or idx == len(target_meshes):
                log(f"LOOSE progress: {idx}/{len(target_meshes)}")

        except Exception as exc:
            log(f"Failed on {obj.name}: {exc}")
            try:
                if bpy.ops.object.mode_set.poll():
                    bpy.ops.object.mode_set(mode="OBJECT")
            except Exception:
                pass

        finally:
            if obj.name in bpy.data.objects:
                obj.hide_viewport = prev_hide_viewport
                obj.hide_render = prev_hide_render
                obj.hide_select = prev_hide_select

    return created_objects


# =============================================================================
# Geometry metadata helpers
# =============================================================================

def world_bbox_min_max(obj):
    """Return world-space bounding box min/max corners for one object."""
    corners = [obj.matrix_world @ Vector(corner) for corner in obj.bound_box]
    mn = Vector((min(v.x for v in corners), min(v.y for v in corners), min(v.z for v in corners)))
    mx = Vector((max(v.x for v in corners), max(v.y for v in corners), max(v.z for v in corners)))
    return mn, mx


def bbox_size(obj):
    """Return world-space bounding box size for one object."""
    mn, mx = world_bbox_min_max(obj)
    return mx - mn


def object_center_world(obj, precision=6):
    """Return rounded world-space bounding box center."""
    mn, mx = world_bbox_min_max(obj)
    center = (mn + mx) * 0.5
    return [round(float(center.x), precision), round(float(center.y), precision), round(float(center.z), precision)]


def object_bbox_size_world(obj, precision=6):
    """Return rounded world-space bounding box size."""
    size = bbox_size(obj)
    return [round(float(size.x), precision), round(float(size.y), precision), round(float(size.z), precision)]


def object_poly_count(obj):
    """Return polygon count for a mesh object."""
    if obj is None or obj.type != "MESH" or obj.data is None:
        return 0
    return int(len(obj.data.polygons))


def object_vertex_count(obj):
    """Return vertex count for a mesh object."""
    if obj is None or obj.type != "MESH" or obj.data is None:
        return 0
    return int(len(obj.data.vertices))


def object_bbox_diag_world(obj):
    """Return rounded world-space bounding box diagonal length."""
    size = bbox_size(obj)
    return round(float(size.length), 6)


def object_bbox_size_world_sorted(obj, precision=6):
    """Return sorted bbox dimensions, useful when axes are not semantically important."""
    size = object_bbox_size_world(obj, precision=precision)
    return sorted(size)


def mapping_entry_with_metadata(value, anim_rig_names=None):
    """

    Convert a Blender object or object name into a JSON-style decomposition entry.



    This mirrors the metadata used in Objaverse Data Intelligence decomposition

    mapping. The key "is_rigged_or_animated" helps users understand why some

    meshes are name-matched instead of geometry-approximated.



    Args:

        value:           A Blender object or an object name string.

        anim_rig_names:  frozenset of object names from

                         ``decomposition_mapping["anim_rig"]``.

    """
    anim_rig_names = anim_rig_names or frozenset()
    obj = value if hasattr(value, "name") else bpy.data.objects.get(str(value))
    name = obj.name if obj is not None else str(value)

    if obj is None or obj.type != "MESH":
        return {
            "name": name,
            "center": None,
            "bbox_size": None,
            "poly_count": 0,
            "vertex_count": 0,
            "bbox_diag": 0.0,
            "bbox_size_sorted": None,
            "is_rigged_or_animated": False,
        }

    return {
        "name": name,
        "center": object_center_world(obj),
        "bbox_size": object_bbox_size_world(obj),
        "poly_count": object_poly_count(obj),
        "vertex_count": object_vertex_count(obj),
        "bbox_diag": object_bbox_diag_world(obj),
        "bbox_size_sorted": object_bbox_size_world_sorted(obj),
        "is_rigged_or_animated": name in anim_rig_names,
    }


# =============================================================================
# Matching helpers
# =============================================================================

def _vec_diff_sq(a, b):
    """Squared difference between two numeric vectors."""
    return sum((float(x) - float(y)) ** 2 for x, y in zip(a, b))


def _maybe_vec_diff_sq(a, b, missing_penalty=1e12):
    """Squared vector difference with a large penalty for missing metadata."""
    if a is None or b is None:
        return missing_penalty
    return _vec_diff_sq(a, b)


def _maybe_abs_diff(a, b, missing_penalty=1e12):
    """Absolute scalar difference with a large penalty for missing metadata."""
    if a is None or b is None:
        return missing_penalty
    return abs(float(a) - float(b))


def metadata_score(candidate_meta, target_meta):
    """

    Approximate similarity score between candidate metadata and target metadata.



    Lower is better.



    Important:

        This approximation is used only for static meshes. Animated/rigged

        meshes are intentionally excluded from this path.

    """
    score = 0.0

    if target_meta.get("poly_count") is not None:
        score += abs(int(candidate_meta.get("poly_count", 0)) - int(target_meta["poly_count"])) * 1000000.0

    if target_meta.get("vertex_count") is not None:
        score += abs(int(candidate_meta.get("vertex_count", 0)) - int(target_meta["vertex_count"])) * 10000.0

    score += _maybe_abs_diff(candidate_meta.get("bbox_diag"), target_meta.get("bbox_diag")) * 100.0
    score += _maybe_vec_diff_sq(candidate_meta.get("center"), target_meta.get("center"))
    score += _maybe_vec_diff_sq(candidate_meta.get("bbox_size"), target_meta.get("bbox_size"))
    score += _maybe_vec_diff_sq(candidate_meta.get("bbox_size_sorted"), target_meta.get("bbox_size_sorted"))

    return score


def metadata_exact_match(candidate_meta, target_meta, tolerance=DEFAULT_TOLERANCE):
    """

    Return True when candidate metadata exactly matches target metadata.



    Integer fields must match exactly. Floating-point geometry fields may differ

    within tolerance.

    """
    required_exact_int_fields = ("poly_count", "vertex_count")

    for field in required_exact_int_fields:
        target_val = target_meta.get(field)
        if target_val is not None and candidate_meta.get(field) != target_val:
            return False

    vec_fields = ("center", "bbox_size", "bbox_size_sorted")

    for field in vec_fields:
        target_vec = target_meta.get(field)
        cand_vec = candidate_meta.get(field)

        if target_vec is None:
            continue

        if cand_vec is None:
            return False

        for a, b in zip(cand_vec, target_vec):
            if abs(float(a) - float(b)) > tolerance:
                return False

    target_diag = target_meta.get("bbox_diag")
    cand_diag = candidate_meta.get("bbox_diag")

    if target_diag is not None:
        if cand_diag is None or abs(float(cand_diag) - float(target_diag)) > tolerance:
            return False

    return True


def build_candidate_pool(meshes):
    """

    Build a one-use candidate pool.



    Each decomposition mapping entry consumes one candidate object. This avoids

    accidentally applying the same object to multiple decomposition components.

    """
    pool = []

    for obj in meshes:
        meta = mapping_entry_with_metadata(obj)
        pool.append({
            "object": obj,
            "meta": meta,
            "used": False,
        })

    return pool


def _entry_has_any_geometry_metadata(entry):
    """Return True if a mapping entry contains usable geometry metadata."""
    if not isinstance(entry, dict):
        return False

    return any(
        entry.get(k) is not None
        for k in ("center", "bbox_size", "poly_count", "vertex_count", "bbox_diag", "bbox_size_sorted")
    )


def _entry_requests_animated_mesh(entry):
    """

    Return True when the JSON entry explicitly says this is animated/rigged.

    """
    return isinstance(entry, dict) and bool(entry.get("is_rigged_or_animated", False))


def find_name_match_for_animated_entry(entry, animated_pool):
    """

    Match an animated/rigged mesh by object name only.



    Animated/rigged meshes should not be loose-separated and should not use

    geometry-nearest approximation because animation, armature, constraints,

    or shape-key state can make location/bbox metadata less reliable.

    """
    target_name = entry.get("name") if isinstance(entry, dict) else str(entry)

    if not target_name:
        return None, "animated_name_missing", 0, None

    matches = [
        item for item in animated_pool
        if (not item["used"]) and item["object"].name == target_name
    ]

    if len(matches) == 1:
        matches[0]["used"] = True
        return matches[0]["object"], "animated_name", len(matches), matches[0]["meta"]

    if len(matches) > 1:
        matches.sort(key=lambda item: item["object"].name)
        matches[0]["used"] = True
        return matches[0]["object"], "animated_name_collision", len(matches), matches[0]["meta"]

    return None, "animated_name_not_found", 0, None


def find_static_match_for_entry(entry, static_pool, tolerance=DEFAULT_TOLERANCE):
    """

    Match a static mesh using metadata first, then name fallback.



    Matching order:

        1. Exact metadata match

        2. Metadata tie-break by object name

        3. Metadata tie-break by score

        4. Metadata-nearest approximation

        5. Name fallback if no metadata exists



    This function must only receive static meshes.

    """
    has_metadata = _entry_has_any_geometry_metadata(entry)

    if has_metadata:
        exact = []

        for item in static_pool:
            if item["used"]:
                continue

            if metadata_exact_match(item["meta"], entry, tolerance=tolerance):
                exact.append(item)

        if len(exact) == 1:
            exact[0]["used"] = True
            return exact[0]["object"], "metadata_exact_unique", len(exact), exact[0]["meta"]

        if len(exact) > 1:
            preferred_name = entry.get("name") if isinstance(entry, dict) else str(entry)
            same_name = [item for item in exact if item["object"].name == preferred_name]

            if len(same_name) == 1:
                same_name[0]["used"] = True
                return same_name[0]["object"], "metadata_exact_tiebreak_name", len(exact), same_name[0]["meta"]

            ranked = sorted(exact, key=lambda item: (metadata_score(item["meta"], entry), item["object"].name))
            ranked[0]["used"] = True
            return ranked[0]["object"], "metadata_exact_tiebreak_score", len(exact), ranked[0]["meta"]

        ranked_all = []

        for item in static_pool:
            if item["used"]:
                continue
            ranked_all.append((metadata_score(item["meta"], entry), item))

        if ranked_all:
            ranked_all.sort(key=lambda x: (x[0], x[1]["object"].name))
            best_score, best = ranked_all[0]
            near_mode = "metadata_nearest" if best_score < 1e12 else "metadata_missing_fallback"
            best["used"] = True
            return best["object"], near_mode, 0, best["meta"]

    target_name = entry.get("name") if isinstance(entry, dict) else str(entry)

    by_name = [
        item for item in static_pool
        if (not item["used"]) and item["object"].name == target_name
    ]

    if by_name:
        by_name[0]["used"] = True
        return by_name[0]["object"], "name", len(by_name), by_name[0]["meta"]

    return None, "not_found", 0, None


def find_match_for_entry(entry, static_pool, animated_pool, tolerance=DEFAULT_TOLERANCE):
    """

    Main object-recovery function.



    Public behavior:

        - Animated/rigged objects are recovered by object name.

        - Static objects are recovered by geometry metadata.

        - Metadata-nearest approximation is never applied to animated/rigged meshes.

    """
    if _entry_requests_animated_mesh(entry):
        return find_name_match_for_animated_entry(entry, animated_pool)

    anim_obj, anim_mode, anim_count, anim_meta = find_name_match_for_animated_entry(entry, animated_pool)

    if anim_obj is not None:
        return anim_obj, anim_mode, anim_count, anim_meta

    return find_static_match_for_entry(entry, static_pool, tolerance=tolerance)


# =============================================================================
# Coloring helpers
# =============================================================================

def random_component_color(component_id):
    """

    Create a deterministic soft pastel color for a decomposition component.

    Lower saturation/value keeps the verification view less blown out.

    """
    rng = random.Random(str(component_id))

    return (
        rng.uniform(0.25, 0.65),
        rng.uniform(0.25, 0.65),
        rng.uniform(0.25, 0.65),
        1.0,
    )


def ensure_emission_material(component_id, color, strength=EMISSION_STRENGTH):
    """

    Create or reuse a simple emission material for decomposition preview.

    """
    mat_name = f"VERIFY_DECOMP_{component_id}"
    mat = bpy.data.materials.get(mat_name)

    if mat is None:
        mat = bpy.data.materials.new(name=mat_name)

    mat.use_nodes = True
    nt = mat.node_tree
    nodes = nt.nodes
    links = nt.links
    nodes.clear()

    emission = nodes.new(type="ShaderNodeEmission")
    output = nodes.new(type="ShaderNodeOutputMaterial")
    emission.inputs["Color"].default_value = color
    emission.inputs["Strength"].default_value = strength
    links.new(emission.outputs["Emission"], output.inputs["Surface"])

    return mat


def apply_material_to_object(obj, mat):
    """Replace the object's visible material slots with the verification material."""
    if obj.data is None:
        return

    if len(obj.data.materials) == 0:
        obj.data.materials.append(mat)
    else:
        for i in range(len(obj.data.materials)):
            obj.data.materials[i] = mat


# =============================================================================
# JSON loading
# =============================================================================

def load_decomposition_mapping_from_json(json_path):
    """

    Load decomposition_mapping from supported JSON formats.



    Supported:

        1. Direct scene JSON:

           {"decomposition_mapping": {...}}



        2. UID-wrapped JSON:

           {"<uid>": {"decomposition_mapping": {...}}}

    """
    with open(json_path, "r", encoding="utf-8") as f:
        data = json.load(f)

    if isinstance(data, dict) and "decomposition_mapping" in data:
        return data["decomposition_mapping"], data

    if isinstance(data, dict) and len(data) == 1:
        first_val = next(iter(data.values()))

        if isinstance(first_val, dict) and "decomposition_mapping" in first_val:
            return first_val["decomposition_mapping"], first_val

    raise ValueError("Could not find decomposition_mapping in JSON.")


# =============================================================================
# Main public function
# =============================================================================

def apply_decomposition_from_json(glb_path, json_path, out_blend_path, tolerance=DEFAULT_TOLERANCE, report_path=None):
    """

    Apply/recover Objaverse Data Intelligence decomposition mapping on a GLB/GLTF.



    Inputs:

        glb_path:

            Source GLB/GLTF file.



        json_path:

            JSON file containing decomposition_mapping.



        out_blend_path:

            Output .blend path. The saved blend contains colored decomposition

            components.



        tolerance:

            Floating-point tolerance for exact metadata matching.



        report_path:

            Optional output report JSON path.



    Output:

        - A colored .blend file for visual inspection.

        - A JSON report showing match modes, collisions, matched entries, and

          unmatched entries.

    """
    reset_scene()
    import_glb(glb_path)
    container = normalise_scene()

    decomposition_mapping, raw_json = load_decomposition_mapping_from_json(json_path)
    requires_mesh_separation = bool(raw_json.get("summary", {}).get("requires_mesh_separation", True))

    # Build the authoritative set of anim/rig object names from the JSON.
    # The analysis pipeline that produced the JSON already inspected every
    # Blender property; we use its conclusion directly instead of re-running
    # property checks at apply time.
    anim_rig_names = frozenset(decomposition_mapping.get("anim_rig", []))
    if anim_rig_names:
        log(f"JSON anim_rig objects ({len(anim_rig_names)}): {sorted(anim_rig_names)}")
    else:
        log("No anim_rig entries in decomposition_mapping; falling back to Blender property inspection.")

    static_before_loose, animated_before_loose = split_static_and_animated_meshes(
        container, anim_rig_names=anim_rig_names
    )
    log(f"Initial mesh split: static={len(static_before_loose)}, animated_or_rigged={len(animated_before_loose)}")

    if requires_mesh_separation:
        separate_loose_parts_under_normalise_container(
            protected_meshes=animated_before_loose,
            blockers=[],
            anim_rig_names=anim_rig_names,
        )
    else:
        log("JSON summary says requires_mesh_separation=False. Skipping LOOSE separation.")

    static_meshes, animated_meshes = split_static_and_animated_meshes(
        container, anim_rig_names=anim_rig_names
    )
    static_pool = build_candidate_pool(static_meshes)
    animated_pool = build_candidate_pool(animated_meshes)

    log(f"Candidate pools after LOOSE: static={len(static_pool)}, animated_or_rigged={len(animated_pool)}")

    report = {
        "total_components": len(decomposition_mapping),
        "total_entries": 0,
        "matched_entries": 0,
        "unmatched_entries": 0,
        "match_modes": {},
        "collision_entries": 0,
        "static_candidate_count": len(static_pool),
        "animated_candidate_count": len(animated_pool),
        "requires_mesh_separation": requires_mesh_separation,
        "component_reports": {},
    }

    for component_id, entries in decomposition_mapping.items():
        color = random_component_color(component_id)
        mat = ensure_emission_material(component_id, color)
        component_report = []

        if not isinstance(entries, list):
            entries = [entries]

        for entry in entries:
            report["total_entries"] += 1

            match_obj, mode, candidate_count, matched_meta = find_match_for_entry(
                entry,
                static_pool=static_pool,
                animated_pool=animated_pool,
                tolerance=tolerance,
            )

            report["match_modes"][mode] = report["match_modes"].get(mode, 0) + 1

            item_name = entry.get("name") if isinstance(entry, dict) else str(entry)

            row = {
                "requested": item_name,
                "mode": mode,
                "candidate_count": candidate_count,
                "matched_object": match_obj.name if match_obj else None,
                "requested_meta": entry if isinstance(entry, dict) else {"name": str(entry)},
                "matched_meta": matched_meta,
            }

            if candidate_count > 1:
                report["collision_entries"] += 1

            if match_obj is not None:
                apply_material_to_object(match_obj, mat)
                report["matched_entries"] += 1
            else:
                report["unmatched_entries"] += 1

            component_report.append(row)

        report["component_reports"][component_id] = component_report

    bpy.ops.wm.save_as_mainfile(filepath=out_blend_path)

    if report_path is None:
        report_path = out_blend_path + DEFAULT_REPORT_PATH_SUFFIX

    with open(report_path, "w", encoding="utf-8") as f:
        json.dump(report, f, indent=2, ensure_ascii=False)

    log(f"Saved blend file: {out_blend_path}")
    log(f"Saved report: {report_path}")
    log(f"Matched {report['matched_entries']} / {report['total_entries']} mapping entries")
    log(f"Collision entries: {report['collision_entries']}")
    log(f"Match modes: {report['match_modes']}")

    return report


# =============================================================================
# CLI
# =============================================================================

def parse_args(argv=None):
    parser = argparse.ArgumentParser(
        description=(
            "Apply Objaverse Data Intelligence decomposition_mapping JSON to a "
            "GLB/GLTF scene and save a colored Blender verification file."
        )
    )

    parser.add_argument("--glb", required=True, help="Source GLB/GLTF path")
    parser.add_argument("--json", required=True, help="JSON file containing decomposition_mapping")
    parser.add_argument("--out_blend", required=True, help="Output .blend path")
    parser.add_argument(
        "--tolerance",
        type=float,
        default=DEFAULT_TOLERANCE,
        help="Metadata comparison tolerance for static meshes",
    )
    parser.add_argument(
        "--report_json",
        default=None,
        help="Optional output JSON report path. Default: <out_blend>.decomposition_report.json",
    )

    return parser.parse_args(argv)


def main():
    argv = []

    if "--" in sys.argv:
        argv = sys.argv[sys.argv.index("--") + 1:]

    args = parse_args(argv)

    apply_decomposition_from_json(
        glb_path=args.glb,
        json_path=args.json,
        out_blend_path=args.out_blend,
        tolerance=args.tolerance,
        report_path=args.report_json,
    )


if __name__ == "__main__":
    main()