"""Same-body gap audit: parts of one rigid body must form one connected cluster (touching within a tolerance).
Complements check.py, which only tests different bodies against each other.
  blender -b 06_walk.blend -P gapcheck.py -- meta.json out.json [tol m]
"""
import bpy, sys, json
import numpy as np
from mathutils import Vector
from mathutils.bvhtree import BVHTree

A = sys.argv[sys.argv.index('--') + 1:]
META = json.load(open(A[0]))
TOL = float(A[2]) if len(A) > 2 else 0.02
SC = bpy.context.scene
SC.frame_set(0)
dg = bpy.context.evaluated_depsgraph_get()
parts = [p for p in META['parts'] if p['kind'] != 'decal']
byb = {}
for p in parts:
    byb.setdefault(p['body'], []).append(p['name'])
DIRS = [Vector((0.123, 0.456, 0.880)).normalized(), Vector((-0.71, 0.33, -0.62)).normalized(), Vector((0.2, -0.9, 0.38)).normalized()]


def inside(tree, p):
    for d in DIRS:
        o = Vector(p)
        n = 0
        for _ in range(48):
            loc, nrm, idx, dist = tree.ray_cast(o, d)
            if loc is None:
                break
            n += 1
            o = loc + d * 1e-5
        if n % 2 == 0:
            return False
    return True


res = {}
bad = []
for b, names in byb.items():
    trees, verts = {}, {}
    for n in names:
        ev = bpy.data.objects[n].evaluated_get(dg)
        me = ev.to_mesh()
        M = bpy.data.objects[n].matrix_world
        v = [M @ x.co for x in me.vertices]
        me.calc_loop_triangles()
        t = [tuple(l.vertices) for l in me.loop_triangles]
        trees[n] = BVHTree.FromPolygons([tuple(x) for x in v], t, all_triangles=True)
        verts[n] = v
        ev.to_mesh_clear()
    par = {n: n for n in names}

    def find(x):
        while par[x] != x:
            par[x] = par[par[x]]
            x = par[x]
        return x
    for i, a in enumerate(names):
        for c in names[i + 1:]:
            if find(a) == find(c):
                continue
            hit = bool(trees[a].overlap(trees[c]))
            if not hit:
                for (x, y, ty) in ((a, c, trees[c]), (c, a, trees[a])):
                    for p in verts[x][:: max(1, len(verts[x]) // 12)]:
                        if inside(ty, p):
                            hit = True
                            break
                    if hit:
                        break
            if not hit:
                va, vc = verts[a], verts[c]
                x, y, ty = (a, c, trees[c]) if len(va) < len(vc) else (c, a, trees[a])
                for p in verts[x][:: max(1, len(verts[x]) // 200)]:
                    loc, nrm, idx, d = ty.find_nearest(p, TOL)
                    if loc is not None:
                        hit = True
                        break
            if hit:
                par[find(a)] = find(c)
    comps = {}
    for n in names:
        comps.setdefault(find(n), []).append(n)
    res[b] = len(comps)
    if len(comps) > 1:
        small = sorted(comps.values(), key=len)[:-1]
        bad.append((b, [x[:4] for x in small]))
print('GAP bodies', len(res), 'single-cluster', sum(1 for v in res.values() if v == 1))
for b, s in bad:
    print('GAP', b, s)
json.dump({'tol_m': TOL, 'components_per_body': res, 'floating': bad}, open(A[1], 'w'), indent=1)
