"""Crown Landmark podium (round 6): foundation + plinth steps, three stepped terraces, sculpted slabs,
tulip-pier arcades with big round-topped arches, gold mullions, amber glazing, blue glass parapets, terrace detail.

Frame: metres, Z up, front = -Y, X = right, origin = tower centre at ground.
Per tier t (floor z0, slab top zt = z0 + 18):
  Podium_Slab_Tn      FULL R06 outline (145x106, 125x90, 105x76, rounded rectangle, front edges y=-53/-45/-38, tops 18/36/54).
                      Interior thickness 0.6 m (underside 17.4/35.4/53.4); a 1.6 m bullnose lip whose soffit sweeps up to the
                      interior thickness within W_SOFFIT of the edge (so only the overhang is thick)
  Podium_Piers_Tn     arcade skin: tulip piers flaring to the slab lip + lintel with big round arches; THIN HOLLOW SHELL
  Podium_Glazing_Tn   amber glazed wall behind the arcade (thin shell), Podium_Mullions_Tn gold mullions/transoms/tracery
  Podium_Parapet_Tn / Podium_Coping_Tn  blue glass parapet + ivory kerb/coping inside the slab edge
  Podium_Terrace_Tn / Podium_Water_Tn   channel kerbs, paving lines (stone) and shallow water channel along the slab edge
Foundation: Podium_Foundation (160 x 120, top 0, bottom -1.2) + Podium_Plinth (two edge steps, open at the entry).

Glazed wall line: 5 m inside the slab edge at the sides and rear; at the front it is set back (WALL_YF) so the rib-foot basins and
arch-blade feet stand in front of the arcade (the slab above overhangs them).
DOCUMENTED DEVIATIONS from the plain R06 slab outlines (everything else is the full outline):
  1. front centre bay |x| <= GAP_HALF is cut out of tier 1 (to y=-32.6, the lobby back wall) and tier 2 (to y=-39.6): the entrance
     module's lobby facade (glazed pointed arch to z~52) and lobby roof slab (z 35.2-36) pass through; no parapet there;
  2. small notches (rib box + RIB_PAD) where ribs R1-R6 cross a slab edge; the arcade bays that would touch a rib are cut.
"""
import math
import bisect
import bpy
import bmesh
from mathutils import Vector, geometry
import cl_common as C

COLLECTION = "Podium"

# ---------------------------------------------------------------- parameters --------------------------------------
GAP_HALF = 22.0           # front centre bay half width kept open (no wall, no piers)
TIER_H = 18.0             # floor to slab top
WALL_INSET = 5.0          # slab edge -> glazed wall line (plan offset): the slab overhangs the arcade by this much
SLAB_R = 16.0             # slab corner radius (wall-line radius = SLAB_R - WALL_INSET)
FOUND_R = 12.0
# front wall line (plan y) for |x| > GAP_HALF per tier (recessed behind the basins / arch-blade feet); notch depth of the lobby bay
WALL_YF = {1: -26.0, 2: -30.0, 3: -33.0}
NOTCH_Y = {1: -32.6, 2: -39.6, 3: None}
RIB_PAD = 1.2             # slab notch clearance around a rib footprint
POCKET_PAD = 1.6          # clearance along the wall between a rib footprint and the cut arcade end
# fascia / slab
D_EDGE = 2.2              # lip depth below the slab top at the edge
T_IN = 0.6                # slab thickness inside the wall line (underside 17.4 / 35.4 / 53.4)
W_SOFFIT, R_BULL = 4.8, 0.55
# arcade
PIER_W = 3.8              # nominal pier width at the floor (bay - open)
OPEN_MAX = 15.0
PIER_OUT0, PIER_OUT1, PIER_P = 2.0, WALL_INSET - 0.25, 2.2   # pier face offset: at floor, at top, flare exponent (tulip)
ARCH_EXP = 2.3            # superellipse exponent for the round arches
SKIN_T = 0.5              # hollow pier skin thickness
SPRING = {1: 8.8, 2: 8.6, 3: 8.4}
CROWN_ROUND = {1: 16.0, 2: 15.8, 3: 15.6}
CROWN_OGIVE = {1: 16.3, 2: 16.1, 3: 15.9}
# parapet / terrace
PARAPET_IN, PARAPET_T = 0.55, 0.14
KERB_W, KERB_H = 0.76, 0.28
GLASS_H = 1.30            # glass band above the kerb
COPING = (0.52, 0.18)
GLASS_OFF = (-0.35, -0.45)
CH_OUT, CH_IN = WALL_INSET - 1.5, 0.9  # channel edges as offset from the wall line (outward positive); slab edge = WALL_INSET
MAX_IN = {1: 6.2, 2: 5.2, 3: 4.6}


# ---------------------------------------------------------------- 2D helpers --------------------------------------
def _arc(cx, cy, r, a0, a1, n):
    return [(cx + r * math.cos(math.radians(a0 + (a1 - a0) * i / n)),
             cy + r * math.sin(math.radians(a0 + (a1 - a0) * i / n))) for i in range(n + 1)]


def _dedupe(pts, tol=1e-6):
    out = []
    for p in pts:
        if not out or abs(p[0] - out[-1][0]) > tol or abs(p[1] - out[-1][1]) > tol:
            out.append(p)
    if len(out) > 1 and abs(out[0][0] - out[-1][0]) < tol and abs(out[0][1] - out[-1][1]) < tol:
        out.pop()
    return out


def outline(w, d, r, notch=0.0, n=10):
    """Closed CCW rounded rectangle; optional notch (recess) in the front edge for |x| <= GAP_HALF."""
    W, D = w / 2, d / 2
    pts = _arc(-W + r, -D + r, r, 180, 270, n)
    if notch > 0:
        pts += [(-GAP_HALF, -D), (-GAP_HALF, -D + notch), (GAP_HALF, -D + notch), (GAP_HALF, -D)]
    pts += _arc(W - r, -D + r, r, -90, 0, n)
    pts += _arc(W - r, D - r, r, 0, 90, n)
    pts += _arc(-W + r, D - r, r, 90, 180, n)
    return _dedupe(pts)


def offset_poly(pts, o):
    """Mitre offset of a closed CCW polygon: o > 0 outward, o < 0 inward."""
    n = len(pts)
    out = []
    for i in range(n):
        p0, p1, p2 = pts[i - 1], pts[i], pts[(i + 1) % n]
        e1 = (p1[0] - p0[0], p1[1] - p0[1])
        e2 = (p2[0] - p1[0], p2[1] - p1[1])
        l1, l2 = math.hypot(*e1), math.hypot(*e2)
        n1 = (e1[1] / l1, -e1[0] / l1)
        n2 = (e2[1] / l2, -e2[0] / l2)
        dd = max(1.0 + n1[0] * n2[0] + n1[1] * n2[1], 1e-3)
        out.append((p1[0] + (n1[0] + n2[0]) / dd * o, p1[1] + (n1[1] + n2[1]) / dd * o))
    return out


def run_path(w, d, r, step=0.45, gap=GAP_HALF, y0=0.0):
    """Open dense path along the wall line from front x=+gap, CCW around, to front x=-gap."""
    W, D = w / 2, d / 2
    na = max(8, int(math.ceil(math.pi / 2 * r / step)))
    pts = []

    def seg(a, b):
        L = math.hypot(b[0] - a[0], b[1] - a[1])
        k = max(1, int(math.ceil(L / step)))
        return [(a[0] + (b[0] - a[0]) * i / k, a[1] + (b[1] - a[1]) * i / k) for i in range(k)]

    pts += seg((gap, -D), (W - r, -D))
    pts += _arc(W - r, -D + r, r, -90, 0, na)[:-1]
    pts += seg((W, -D + r), (W, D - r))
    pts += _arc(W - r, D - r, r, 0, 90, na)[:-1]
    pts += seg((W - r, D), (-W + r, D))
    pts += _arc(-W + r, D - r, r, 90, 180, na)[:-1]
    pts += seg((-W, D - r), (-W, -D + r))
    pts += _arc(-W + r, -D + r, r, 180, 270, na)[:-1]
    pts += seg((-W + r, -D), (-gap, -D))
    pts.append((-gap, -D))
    return _dedupe([(x, y + y0) for x, y in pts])


class Path:
    """Arc-length parametrised open polyline with outward (right-hand, CCW) normals."""

    def __init__(self, pts):
        self.p = pts
        self.s = [0.0]
        for a, b in zip(pts[:-1], pts[1:]):
            self.s.append(self.s[-1] + math.hypot(b[0] - a[0], b[1] - a[1]))
        self.L = self.s[-1]
        nv = []
        for i in range(len(pts)):
            a = pts[max(i - 1, 0)]
            b = pts[min(i + 1, len(pts) - 1)]
            tx, ty = b[0] - a[0], b[1] - a[1]
            l = math.hypot(tx, ty)
            nv.append((ty / l, -tx / l))
        self.n = nv

    def at(self, s):
        s = min(max(s, 0.0), self.L)
        i = min(max(bisect.bisect_right(self.s, s) - 1, 0), len(self.p) - 2)
        t = (s - self.s[i]) / max(self.s[i + 1] - self.s[i], 1e-9)
        p = (self.p[i][0] + (self.p[i + 1][0] - self.p[i][0]) * t, self.p[i][1] + (self.p[i + 1][1] - self.p[i][1]) * t)
        nx = self.n[i][0] + (self.n[i + 1][0] - self.n[i][0]) * t
        ny = self.n[i][1] + (self.n[i + 1][1] - self.n[i][1]) * t
        l = math.hypot(nx, ny)
        return p, (nx / l, ny / l)


# ---------------------------------------------------------------- mesh helpers ------------------------------------
def weld(verts, faces, tol=2e-3):
    key, remap, nv = {}, [], []
    for v in verts:
        k = (round(v[0] / tol), round(v[1] / tol), round(v[2] / tol))
        if k not in key:
            key[k] = len(nv)
            nv.append(v)
        remap.append(key[k])
    nf = []
    for f in faces:
        g = []
        for i in f:
            j = remap[i]
            if not g or g[-1] != j:
                g.append(j)
        if len(g) > 1 and g[0] == g[-1]:
            g.pop()
        if len(g) >= 3 and len(set(g)) == len(g):
            nf.append(tuple(g))
    return nv, nf


def cap_faces(ring_idx, verts, up=None):
    """Triangulate a ring; with up=True/False orient every triangle to face +Z/-Z (zero-area slivers kept so the rim stays closed)."""
    pts = [Vector(verts[i]) for i in ring_idx]
    tris = geometry.tessellate_polygon([pts])
    out = []
    for a, b, c in tris:
        t = (ring_idx[a], ring_idx[b], ring_idx[c])
        if up is not None:
            pa, pb, pc = pts[a], pts[b], pts[c]
            nz = (pb.x - pa.x) * (pc.y - pa.y) - (pb.y - pa.y) * (pc.x - pa.x)
            if abs(nz) > 1e-9 and (nz > 0) != up:
                t = (t[0], t[2], t[1])
        out.append(t)
    return out


def join(*vfs):
    V, F = [], []
    for v, f in vfs:
        b = len(V)
        V += list(v)
        F += [tuple(i + b for i in fc) for fc in f]
    return V, F


def slab_mesh(poly, zt, w_taper, t0, t1):
    """Plain thin slab (used for the foundation)."""
    prof = [(w_taper, 0.0), (0.0, 0.0), (0.0, -t0)]
    prof += [(w_taper * f, -(t0 + (t1 - t0) * C.smooth(f))) for f in (0.15, 0.3, 0.5, 0.75, 1.0)]
    verts, faces, rings = [], [], []
    for o, dz in prof:
        rp = offset_poly(poly, -o) if o > 0 else poly
        rings.append(list(range(len(verts), len(verts) + len(rp))))
        verts += [(x, y, zt + dz) for x, y in rp]
    n = len(poly)
    for k in range(len(rings) - 1):
        for i in range(n):
            j = (i + 1) % n
            faces.append((rings[k][i], rings[k][j], rings[k + 1][j], rings[k + 1][i]))
    faces += cap_faces(rings[0], verts)
    faces += cap_faces(rings[-1], verts)
    return verts, faces


def closed_tube(poly, zbase, section):
    verts, rings = [], []
    for off, dz in section:
        rp = offset_poly(poly, off)
        rings.append(list(range(len(verts), len(verts) + len(rp))))
        verts += [(x, y, zbase + dz) for x, y in rp]
    faces = []
    n = len(poly)
    m = len(section)
    for a in range(m):
        b = (a + 1) % m
        for i in range(n):
            j = (i + 1) % n
            faces.append((rings[a][i], rings[a][j], rings[b][j], rings[b][i]))
    return verts, faces


def open_tube(path, zbase, section, caps=True):
    verts, rings = [], []
    n = len(path.p)
    for i in range(n):
        nx, ny = path.n[i]
        px, py = path.p[i]
        rings.append(list(range(len(verts), len(verts) + len(section))))
        verts += [(px + nx * off, py + ny * off, zbase + dz) for off, dz in section]
    faces = []
    m = len(section)
    for i in range(n - 1):
        for a in range(m):
            b = (a + 1) % m
            faces.append((rings[i][a], rings[i][b], rings[i + 1][b], rings[i + 1][a]))
    if caps:
        faces.append(tuple(rings[0]))
        faces.append(tuple(reversed(rings[-1])))
    return verts, faces


def strip(path, zbase, off0, off1, h, i0=0, i1=None):
    """Rectangular band (offsets off0..off1 from the path, height h) along path[i0:i1+1]."""
    sub = Path(path.p[i0:(i1 + 1) if i1 is not None else None]) if (i0 or i1 is not None) else path
    return open_tube(sub, zbase, [(off0, 0.0), (off1, 0.0), (off1, h), (off0, h)])


def box_at(path, s, o0, o1, w, zbase, h):
    """Small box across the path at arc length s, spanning offsets o0..o1, width w along the path."""
    p, n = path.at(s)
    t = (-n[1], n[0])
    v = []
    for dz in (0.0, h):
        for (a, off) in ((-w / 2, o0), (-w / 2, o1), (w / 2, o1), (w / 2, o0)):
            v.append((p[0] + n[0] * off + t[0] * a, p[1] + n[1] * off + t[1] * a, zbase + dz))
    f = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]
    return v, f


def coarse(path, forced=(), ang=6.0):
    """Simplified copy of a dense path: keeps a vertex whenever the normal has turned `ang` degrees since the last
    kept one (straights collapse to their end points) plus `forced` indices. Returns (Path, {fine idx: coarse idx})."""
    keep = [0]
    last = path.n[0]
    cs = math.cos(math.radians(ang))
    fs = set(forced)
    for i in range(1, len(path.p) - 1):
        n = path.n[i]
        nxt = path.n[i + 1]
        turn = n[0] * last[0] + n[1] * last[1] < cs
        edge = (n[0] * nxt[0] + n[1] * nxt[1]) < 0.9999 and (n[0] * last[0] + n[1] * last[1]) > 0.9999
        if turn or i in fs or edge:
            keep.append(i)
            last = n
    keep.append(len(path.p) - 1)
    return Path([path.p[i] for i in keep]), {i: k for k, i in enumerate(keep)}


def orient_solids(verts, faces):
    """Flip every connected component whose signed volume is negative (so all closed solids face outward)."""
    par = list(range(len(verts)))

    def find(a):
        while par[a] != a:
            par[a] = par[par[a]]
            a = par[a]
        return a

    for f in faces:
        for i in f[1:]:
            ra, rb = find(f[0]), find(i)
            if ra != rb:
                par[ra] = rb
    vol = {}
    for f in faces:
        r = find(f[0])
        a = Vector(verts[f[0]])
        for k in range(1, len(f) - 1):
            vol[r] = vol.get(r, 0.0) + a.dot(Vector(verts[f[k]]).cross(Vector(verts[f[k + 1]]))) / 6.0
    return verts, [tuple(reversed(f)) if vol[find(f[0])] < 0 else tuple(f) for f in faces]


def shade(ob, angle=38.0):
    """Smooth faces, keep creases sharper than `angle` degrees."""
    me = ob.data
    bm = bmesh.new()
    bm.from_mesh(me)
    for f in bm.faces:
        f.smooth = f.calc_area() > 1e-4      # zero-area slivers stay flat so they cannot poison vertex normals
    lim = math.radians(angle)
    for e in bm.edges:
        if len(e.link_faces) == 2 and e.calc_face_angle(0.0) > lim:
            e.smooth = False
    bm.to_mesh(me)
    bm.free()


# ---------------------------------------------------------------- layout --------------------------------------------
def _weights(n, pos, tier):
    if n == 1:
        return [1.0]
    if pos == "first":      # nearest the entry first: larger bays by the centre, narrower toward the corner
        w = [1.08 - 0.16 * i / (n - 1) for i in range(n)]
    elif pos == "last":
        w = [0.92 + 0.16 * i / (n - 1) for i in range(n)]
    else:                   # long sides: larger central bays, narrower near the corners
        w = [0.92 + 0.24 * math.sin(math.pi * (i + 0.5) / n) ** 2 for i in range(n)]
    s = sum(w)
    return [x * n / s for x in w]


# measured rib plan footprints (z, x0, x1, y0, y1) at height z, left-hand ribs R1 (front), R3 (side), R5 (rear);
# right-hand ribs mirror x.  Source: round-3 assembly slices (+-2 m); re-measure if ribs.py changes.
_RIBF = {   # constant plan boxes over z 0..62 (ribs now rise vertically from the feet)
    "R1": [(0, -71.5, -44.5, -44.1, -35.9), (62, -71.5, -44.5, -44.1, -35.9)],
    "R3": [(0, -67.3, -50.5, -4.5, 16.5), (62, -67.3, -50.5, -4.5, 16.5)],
    "R5": [(0, -54.0, -28.0, 40.4, 47.6), (62, -54.0, -28.0, 40.4, 47.6)],
}


def rib_boxes(z):
    """Plan boxes (x0, x1, y0, y1) of the six ribs at height z (interpolated)."""
    out = []
    for key, rows in _RIBF.items():
        zz = min(max(z, rows[0][0]), rows[-1][0])
        i = 0
        while i < len(rows) - 2 and zz > rows[i + 1][0]:
            i += 1
        r0, r1 = rows[i], rows[i + 1]
        t = (zz - r0[0]) / (r1[0] - r0[0])
        x0, x1, y0, y1 = [r0[k] + (r1[k] - r0[k]) * t for k in (1, 2, 3, 4)]
        out.append((x0, x1, y0, y1))
        out.append((-x1, -x0, y0, y1))
    return out


def rib_hit(x, y, z, pad):
    for x0, x1, y0, y1 in rib_boxes(z):
        if x0 - pad <= x <= x1 + pad and y0 - pad <= y <= y1 + pad:
            return True
    return False


def wall_hits(path, z0, hs):
    """Per dense path index: does the arcade volume (glazing .. pier face) at this point touch a rib footprint?"""
    hit = []
    zs = [0.5 + k * (hs - 0.5) / 8 for k in range(9)]
    for i, (p, n) in enumerate(zip(path.p, path.n)):
        h = False
        for zl in zs:
            out = pier_out(zl, hs)
            for off in (-0.5, 0.0, out * 0.5, out):
                if rib_hit(p[0] + n[0] * off, p[1] + n[1] * off, z0 + zl, 0.5):
                    h = True
                    break
            if h:
                break
        hit.append(h)
    return hit


def wall_runs(path, z0, hs, min_len=9.0):
    """Index ranges [i0, i1] of the wall path that stay clear of the ribs (pockets padded by POCKET_PAD)."""
    hit = wall_hits(path, z0, hs)
    n = len(hit)
    pad = []
    for i in range(n):
        pad.append(any(hit[j] for j in range(n) if abs(path.s[j] - path.s[i]) <= POCKET_PAD))
    runs, i = [], 0
    while i < n:
        if pad[i]:
            i += 1
            continue
        j = i
        while j + 1 < n and not pad[j + 1]:
            j += 1
        if path.s[j] - path.s[i] >= min_len:
            runs.append((i, j))
        i = j + 1
    return runs


def layout(path, ww, wd, r, tier, y0=0.0, runs=None):
    """Bays along the wall path (list of dicts s0, w, kind, open, corner) for each clear run. Corner = one ogive bay."""
    W, D = ww / 2, wd / 2
    if runs is None:
        runs = [(0, len(path.p) - 1)]
    bays = []
    for ri, (a, b) in enumerate(runs):
        flags = [abs(path.p[i][0]) > W - r + 1e-6 and abs(path.p[i][1] - y0) > D - r + 1e-6 for i in range(a, b + 1)]
        groups = []
        for k, f in enumerate(flags):
            if not groups or groups[-1][0] != f:
                groups.append([f, a + k, a + k])
            groups[-1][2] = a + k
        ng = len(groups)
        for gi, (isc, i0, i1) in enumerate(groups):
            s0 = path.s[i0]
            s1 = path.s[groups[gi + 1][1]] if gi + 1 < ng else path.s[b]
            L = s1 - s0
            if L < 4.6 + 3.0:
                continue
            if isc:
                n, ws, kinds = 1, [1.0], ["round"]
                corner = True
            else:
                corner = False
                n = max(1, int(round(L / 17.0)))
                while n > 1 and L / n < 12.0:
                    n -= 1
                while L / n > 23.0:
                    n += 1
                first = ri == 0 and gi == 0 and a == 0
                last = ri == len(runs) - 1 and gi == ng - 1 and b == len(path.p) - 1
                pos = "first" if first else ("last" if last else "mid")
                ws = _weights(n, pos, tier)
                kinds = []
                wmax = max(ws)
                for k in range(n):
                    kinds.append("round")          # big round-topped openings, as in the references
            mean = L / n
            pos_s = s0
            for k in range(n):
                bw = mean * ws[k]
                op = min(OPEN_MAX, bw - PIER_W)
                bays.append(dict(s0=pos_s, w=bw, kind=kinds[k], open=op, corner=corner))
                pos_s += bw
    return bays


# ---------------------------------------------------------------- arches ---------------------------------------------
def pier_out(zl, hs):
    t = min(max(zl / hs, 0.0), 1.0)
    return PIER_OUT0 + (PIER_OUT1 - PIER_OUT0) * t ** PIER_P


def arch_curve(kind, a, sp, rise, n=18):
    """Left-to-right arch points (x, zl), 2n+1 of them, springing at (+-a, sp), apex (0, sp+rise)."""
    pts = []
    if kind == "ogive":
        half = C.pointed_arch(2 * a, rise, n)          # right half: (a,0) -> (0,rise)
        left = [(-x, sp + z) for x, z in half]
        right = [(x, sp + z) for x, z in reversed(half)][1:]
        pts = left + right
    else:
        N = 2 * n + 1
        e = ARCH_EXP
        for i in range(N):
            ph = math.pi * i / (N - 1)
            c, s_ = math.cos(ph), math.sin(ph)
            pts.append((-a * math.copysign(abs(c) ** (2 / e), c), sp + rise * abs(s_) ** (2 / e)))
    return pts


def arch_z(kind, a, sp, rise, x):
    """Height of the arch intrados at lateral position x."""
    x = abs(x)
    if x >= a:
        return sp
    if kind == "ogive":
        c = (rise ** 2 - a ** 2) / (2 * a)
        R = a + c
        return sp + math.sqrt(max(R * R - (x + c) ** 2, 0.0))
    return sp + rise * max(1 - (x / a) ** ARCH_EXP, 0.0) ** (1 / ARCH_EXP)


def bay_params(b, tier):
    if b["kind"] == "ogive":
        sp, crown = SPRING[tier] - 1.6, CROWN_OGIVE[tier]
    else:
        sp, crown = SPRING[tier], CROWN_ROUND[tier]
    return b["open"] / 2, sp, crown - sp


# ---------------------------------------------------------------- arcade shell ---------------------------------------
def arcade_skin(path, z0, bays, tier, hc, hs):
    """Perforated fascia skin (tulip piers + lintel) as bays along `path`: front skin + reveals only (open back)."""
    verts, faces = [], []
    N1, K = 7, 3
    n_half = 12
    N2 = 2 * n_half + 1
    for b in bays:
        a, sp, rise = bay_params(b, tier)
        w = b["w"]
        sc = b["s0"] + w / 2
        arch = arch_curve(b["kind"], a, sp, rise, n_half)
        inner, outer = [], []
        for i in range(N1):
            inner.append((-a, sp * i / N1))
            outer.append((-w / 2, hc * i / N1))
        for i in range(N2):
            inner.append(arch[i])
            outer.append((-w / 2 + w * i / (N2 - 1), hc))
        for i in range(N1):
            inner.append((a, sp * (N1 - 1 - i) / N1))
            outer.append((w / 2, hc * (N1 - 1 - i) / N1))
        M = len(inner)

        def P(u, zl, off):
            p, n = path.at(sc + u)
            return (p[0] + n[0] * off, p[1] + n[1] * off, z0 + zl)

        fid = []
        for k in range(K + 1):
            t = k / K
            row = []
            for j in range(M):
                u = inner[j][0] + (outer[j][0] - inner[j][0]) * t
                zl = inner[j][1] + (outer[j][1] - inner[j][1]) * t
                row.append(len(verts))
                verts.append(P(u, zl, pier_out(zl, hs)))
            fid.append(row)
        bid = []
        row = []
        for j in range(M):
            row.append(len(verts))
            verts.append(P(inner[j][0], inner[j][1], 0.0))
        bid = row
        for k in range(K):
            for j in range(M - 1):
                faces.append((fid[k][j], fid[k][j + 1], fid[k + 1][j + 1], fid[k + 1][j]))
        for j in range(M - 1):
            faces.append((fid[0][j + 1], fid[0][j], bid[j], bid[j + 1]))      # reveal
    return verts, faces


def hollow_shell(verts, faces, t):
    """Give an open outward-oriented skin a thickness t inward; rim faces close the open edges."""
    vn = [Vector((0, 0, 0)) for _ in verts]
    for f in faces:
        pts = [Vector(verts[i]) for i in f]
        nrm = Vector((0, 0, 0))
        for i in range(len(pts)):
            a, b = pts[i], pts[(i + 1) % len(pts)]
            nrm += Vector(((a.y - b.y) * (a.z + b.z), (a.z - b.z) * (a.x + b.x), (a.x - b.x) * (a.y + b.y)))
        for i in f:
            vn[i] += nrm
    n0 = len(verts)
    nv = list(verts)
    for i, v in enumerate(verts):
        nrm = vn[i]
        if nrm.length > 1e-9:
            nrm = nrm.normalized()
        nv.append(tuple(Vector(v) - nrm * t))
    nf = [tuple(f) for f in faces]
    nf += [tuple(i + n0 for i in reversed(f)) for f in faces]
    edges = {}
    for f in faces:
        for i in range(len(f)):
            a, b = f[i], f[(i + 1) % len(f)]
            edges[(a, b)] = True
    for (a, b) in list(edges):
        if (b, a) not in edges:
            nf.append((b, a, a + n0, b + n0))
    return nv, nf


# ---------------------------------------------------------------- fascia slab ----------------------------------------
# ---------------------------------------------------------------- slab outline + solid -------------------------------
def _pip(pt, poly):
    x, y = pt
    c = False
    n = len(poly)
    for i in range(n):
        x1, y1 = poly[i]
        x2, y2 = poly[(i + 1) % n]
        if (y1 > y) != (y2 > y) and x < (x2 - x1) * (y - y1) / (y2 - y1) + x1:
            c = not c
    return c


def _box_cross(a, b, box):
    x0, x1, y0, y1 = box
    ts = []
    dx, dy = b[0] - a[0], b[1] - a[1]
    for xe in (x0, x1):
        if abs(dx) > 1e-12:
            t = (xe - a[0]) / dx
            if 1e-9 < t < 1 - 1e-9 and y0 - 1e-9 <= a[1] + t * dy <= y1 + 1e-9:
                ts.append(t)
    for ye in (y0, y1):
        if abs(dy) > 1e-12:
            t = (ye - a[1]) / dy
            if 1e-9 < t < 1 - 1e-9 and x0 - 1e-9 <= a[0] + t * dx <= x1 + 1e-9:
                ts.append(t)
    return sorted(set(round(t, 9) for t in ts))


def _perim(pt, box):
    x0, x1, y0, y1 = box
    W, H = x1 - x0, y1 - y0
    x, y = pt
    if abs(y - y0) < 1e-6:
        return x - x0
    if abs(x - x1) < 1e-6:
        return W + (y - y0)
    if abs(y - y1) < 1e-6:
        return W + H + (x1 - x)
    return 2 * W + H + (y1 - y)


def carve(poly, box):
    """Cut the axis-aligned box out of a closed CCW polygon where the box crosses its boundary (no holes are made)."""
    x0, x1, y0, y1 = box
    pts = []
    n = len(poly)
    for i in range(n):
        a, b = poly[i], poly[(i + 1) % n]
        pts.append(a)
        for t in _box_cross(a, b, box):
            pts.append((a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t))
    m = len(pts)

    def inside_edge(i):
        a, b = pts[i], pts[(i + 1) % m]
        mx, my = (a[0] + b[0]) / 2, (a[1] + b[1]) / 2
        return x0 < mx < x1 and y0 < my < y1

    ins = [inside_edge(i) for i in range(m)]
    if not any(ins):
        return poly
    if all(ins):
        return poly
    st = next(i for i in range(m) if ins[i] and not ins[i - 1])      # first inside edge of a run
    order = [(st + k) % m for k in range(m)]
    out = []
    k = 0
    corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
    P0 = 2 * (x1 - x0) + 2 * (y1 - y0)
    while k < m:
        i = order[k]
        if not ins[i]:
            out.append(pts[i])
            k += 1
            continue
        j = k
        while j < m and ins[order[j]]:
            j += 1
        pa = pts[order[k]]                    # start of the removed run
        pb = pts[(order[j - 1] + 1) % m]      # end of the removed run
        sa, sb = _perim(pa, box), _perim(pb, box)
        # candidate routes along the box perimeter: increasing and decreasing
        routes = []
        for direction in (1, -1):
            d = ((sb - sa) % P0) if direction == 1 else ((sa - sb) % P0)
            via = []
            for c in (corners if direction == 1 else corners[::-1]):
                sc = _perim(c, box)
                dd = ((sc - sa) % P0) if direction == 1 else ((sa - sc) % P0)
                if 1e-9 < dd < d - 1e-9:
                    via.append((dd, c))
            via.sort()
            path = [c for _, c in via]
            samples = path + [((pa[0] + (path[0] if path else pb)[0]) / 2, (pa[1] + (path[0] if path else pb)[1]) / 2)]
            ok = all(_pip(q, poly) for q in samples)
            routes.append((ok, d, path))
        good = [r for r in routes if r[0]]
        pick = min(good or routes, key=lambda r: r[1])
        out.append(pa)
        out += pick[2]
        out.append(pb)
        k = j
    return _dedupe(out)


def densify(poly, step):
    out = []
    n = len(poly)
    for i in range(n):
        a, b = poly[i], poly[(i + 1) % n]
        L = math.hypot(b[0] - a[0], b[1] - a[1])
        k = max(1, int(math.ceil(L / step)))
        for t in range(k):
            out.append((a[0] + (b[0] - a[0]) * t / k, a[1] + (b[1] - a[1]) * t / k))
    return out


def slab_outline(ti, w, d):
    """Full R06 rounded rectangle, minus the lobby bay (tiers 1, 2) and rib notches where a rib crosses the edge."""
    poly = outline(w, d, SLAB_R, 0.0, n=10)
    if NOTCH_Y[ti] is not None:
        poly = carve(poly, (-GAP_HALF - 0.3, GAP_HALF + 0.3, -d / 2 - 1.0, NOTCH_Y[ti]))
    zmid = TIER_H * ti - 1.0
    for x0, x1, y0, y1 in rib_boxes(zmid):
        poly = carve(poly, (x0 - RIB_PAD, x1 + RIB_PAD, y0 - RIB_PAD, y1 + RIB_PAD))
    return poly


def slab_solid(poly, zt):
    """Slab with bullnose lip: top at zt, interior underside at zt - T_IN, edge lip D_EDGE deep, soffit swept up over W_SOFFIT."""
    prof = [(0.0, 0.0), (0.0, -0.18), (0.0, -(D_EDGE - R_BULL))]
    for ph in (30.0, 60.0, 90.0):
        c, s_ = math.cos(math.radians(ph)), math.sin(math.radians(ph))
        prof.append((R_BULL * (1 - c), -(D_EDGE - R_BULL) - R_BULL * s_))
    for f in (0.18, 0.4, 0.68, 1.0):
        prof.append((R_BULL + (W_SOFFIT - R_BULL) * f, -(T_IN + (D_EDGE - T_IN) * (1 - f) ** 2.2)))
    verts, rings = [], []
    cache = {}
    n = len(poly)
    for o, dz in prof:
        key = round(o, 6)
        if key not in cache:
            cache[key] = offset_poly(poly, -o) if o > 1e-9 else poly
        rp = cache[key]
        rings.append(list(range(len(verts), len(verts) + n)))
        verts += [(x, y, zt + dz) for x, y in rp]
    faces = []
    for k in range(len(rings) - 1):
        for i in range(n):
            j = (i + 1) % n
            faces.append((rings[k][i], rings[k + 1][i], rings[k + 1][j], rings[k][j]))
    faces.append(tuple(rings[0]))
    faces.append(tuple(reversed(rings[-1])))
    return verts, faces


# ---------------------------------------------------------------- mullions -------------------------------------------
def bar(path, z0, sc, pts_uz, w, off_in, off_out):
    """Rectangular bar following the polyline pts_uz = [(u, zl)] on the wall (plan follows the path)."""
    rings = []
    n = len(pts_uz)
    for i, (u, zl) in enumerate(pts_uz):
        a = pts_uz[max(i - 1, 0)]
        b = pts_uz[min(i + 1, n - 1)]
        du, dz = b[0] - a[0], b[1] - a[1]
        l = math.hypot(du, dz) or 1.0
        nu, nz = -dz / l, du / l
        ring = []
        for (su, so) in ((1, off_out), (-1, off_out), (-1, off_in), (1, off_in)):
            uu = u + nu * w / 2 * su
            zz = zl + nz * w / 2 * su
            p, nn = path.at(sc + uu)
            ring.append((p[0] + nn[0] * so, p[1] + nn[1] * so, z0 + zz))
        rings.append(ring)
    return C.loft(rings, True, True)


def mullions(path, z0, bays, tier):
    out = []
    for b in bays:
        a, sp, rise = bay_params(b, tier)
        sc = b["s0"] + b["w"] / 2
        kind = b["kind"]
        arch = arch_curve(kind, a, sp, rise, 12)
        sub = arch[::2] + ([arch[-1]] if len(arch) % 2 == 0 else [])
        # frame: sill-to-springing jambs, arch head bar
        out.append(bar(path, z0, sc, [(-a + 0.12, 0.2), (-a + 0.12, sp)], 0.26, -0.40, -0.04))
        out.append(bar(path, z0, sc, [(a - 0.12, 0.2), (a - 0.12, sp)], 0.26, -0.40, -0.04))
        head = [(x * 0.985, z - 0.16) for x, z in sub]
        out.append(bar(path, z0, sc, head, 0.24, -0.40, -0.04))
        # transoms
        nt = 9 if b["corner"] else 2
        for zt_ in (sp, sp * 0.52):
            line = [(-a + 0.12 + (2 * a - 0.24) * i / (nt - 1), zt_) for i in range(nt)]
            out.append(bar(path, z0, sc, line, 0.2, -0.38, -0.05))
        # verticals
        nv = max(1, int(round(2 * a / 2.7)) - 1)
        for k in range(1, nv + 1):
            x = -a + 2 * a * k / (nv + 1)
            zt_ = arch_z(kind, a, sp, rise, x) - 0.2
            out.append(bar(path, z0, sc, [(x, 0.2), (x, zt_)], 0.16, -0.38, -0.05))
        # inner tracery arc (smaller concentric arch)
        a2, r2 = a * 0.6, rise * 0.62
        arc2 = arch_curve(kind, a2, sp * 1.0, r2, 8)
        out.append(bar(path, z0, sc, arc2[::2] + ([arc2[-1]] if len(arc2) % 2 == 0 else []), 0.14, -0.36, -0.07))
    return join(*out)


# ---------------------------------------------------------------- build -------------------------------------------
def _clean(me):
    """Mesh hygiene: merge doubles, remove degenerate faces/edges and loose verts, consistent outward normals."""
    bm = bmesh.new()
    bm.from_mesh(me)
    bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=2e-4)
    bmesh.ops.dissolve_degenerate(bm, edges=bm.edges, dist=2e-4)
    bad = [f for f in bm.faces if f.calc_area() < 1e-7]
    if bad:
        bmesh.ops.delete(bm, geom=bad, context="FACES")
    loose = [v for v in bm.verts if not v.link_edges]
    if loose:
        bmesh.ops.delete(bm, geom=loose, context="VERTS")
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    bm.to_mesh(me)
    bm.free()
    me.update()


def _add(name, vf, material, coll, weld_it=True, smooth=False, extra_mats=(), clean=True):
    v, f = vf
    if weld_it:
        v, f = weld(v, f)
    ob = C.make_object(name, v, f, material, coll, smooth_shade=False, recalc=not clean)
    if clean:
        _clean(ob.data)
    for m in extra_mats:
        ob.data.materials.append(m)
    if smooth:
        shade(ob)
    return ob


def _pieces(pts, keep):
    """Split a dense point list into runs of kept points (cyclic when the list is closed). Returns (pieces, all_kept)."""
    flags = [keep(p) for p in pts]
    if all(flags):
        return [pts], True
    k0 = flags.index(False)
    order = pts[k0:] + pts[:k0]
    fl = flags[k0:] + flags[:k0]
    pieces, cur = [], []
    for p, f in zip(order, fl):
        if f:
            cur.append(p)
        elif cur:
            pieces.append(cur)
            cur = []
    if cur:
        pieces.append(cur)
    return [pc for pc in pieces if len(pc) >= 3], False


def build():
    coll = C.collection(COLLECTION)
    ivory, stone, amber, parapet = C.mat("ivory"), C.mat("stone"), C.mat("amber"), C.mat("parapet")
    gold, water = C.mat("gold"), C.mat("water")

    # ---- foundation plate (top z=0, bottom -1.2) and plinth steps (open across the entry)
    fpoly = outline(C.FOUNDATION[0], C.FOUNDATION[1], FOUND_R, 0.0, n=12)
    _add("Podium_Foundation", slab_mesh(fpoly, 0.0, 1.0, 1.2, 1.2), stone, coll)
    fp, _ = coarse(Path(run_path(C.FOUNDATION[0] - 5.6, C.FOUNDATION[1] - 5.6, FOUND_R - 2.8, gap=26.0)))
    steps = join(open_tube(fp, 0.0, [(2.8, 0.0), (1.3, 0.0), (1.3, 0.15), (2.8, 0.15)]),
                 open_tube(fp, 0.0, [(1.3, 0.0), (-0.3, 0.0), (-0.3, 0.32), (1.3, 0.32)]))
    _add("Podium_Plinth", steps, stone, coll, weld_it=False, clean=False)

    for ti, (zt, w, d) in enumerate(C.DECKS, start=1):
        z0 = zt - TIER_H
        hc = TIER_H - 0.55       # arcade skin top: reaches the slab underside (17.45 > 17.4)
        hs = hc

        # ---- slab: full R06 outline (lobby bay / rib notches excepted), thin interior, bullnose lip
        poly = slab_outline(ti, w, d)
        sv, sf = slab_solid(poly, zt)
        slab = _add(f"Podium_Slab_T{ti}", (sv, sf), ivory, coll, weld_it=False, extra_mats=(stone,))
        for pg in slab.data.polygons:
            if pg.normal.z > 0.9 and abs(pg.center.z - zt) < 1e-4:
                pg.material_index = 1
        shade(slab)

        # ---- wall line (glazed wall + arcade): 5 m inside the slab edge, front set back behind the basins / blade feet
        yf, yr = WALL_YF[ti], d / 2 - WALL_INSET
        ww, wd = w - 2 * WALL_INSET, yr - yf
        y0 = (yr + yf) / 2
        wr = SLAB_R - WALL_INSET
        path = Path(run_path(ww, wd, wr, y0=y0))
        runs = wall_runs(path, z0, hs)
        bays = layout(path, ww, wd, wr, ti, y0, runs)

        # ---- hollow arcade skin
        av, af = arcade_skin(path, z0, bays, ti, hc, hs)
        av, af = weld(av, af)
        tot = 0.0
        for f in af:
            pts = [Vector(av[i]) for i in f]
            nrm = Vector((0, 0, 0))
            for i in range(len(pts)):
                a_, b_ = pts[i], pts[(i + 1) % len(pts)]
                nrm += Vector(((a_.y - b_.y) * (a_.z + b_.z), (a_.z - b_.z) * (a_.x + b_.x), (a_.x - b_.x) * (a_.y + b_.y)))
            cen = sum(pts, Vector((0, 0, 0))) / len(pts)
            out_dir = Vector((cen.x, cen.y - y0, 0)).normalized()
            if abs(nrm.z) < 0.5 * nrm.length:
                tot += nrm.dot(out_dir)
        if tot < 0:
            af = [tuple(reversed(f)) for f in af]
        sv2, sf2 = hollow_shell(av, af, SKIN_T)
        _add(f"Podium_Piers_T{ti}", (sv2, sf2), ivory, coll, weld_it=False, smooth=True)

        # ---- amber glazing (thin shell behind the arcade), continuous also across the rib pockets
        gsec = [(GLASS_OFF[0], -0.1), (GLASS_OFF[1], -0.1), (GLASS_OFF[1], TIER_H - 0.55), (GLASS_OFF[0], TIER_H - 0.55)]
        sp_ = Path(path.p[::3] + ([path.p[-1]] if (len(path.p) - 1) % 3 else []))
        _add(f"Podium_Glazing_T{ti}", open_tube(sp_, z0, gsec), amber, coll, weld_it=False)

        # ---- gold mullions (+ grid across the curtain wall where the arcade is cut for a rib)
        mv, mf = mullions(path, z0, bays, ti)
        edges, last_s = [], 0.0
        for (a_, b_) in runs:
            if path.s[a_] - last_s > 2.0:
                edges.append((last_s, path.s[a_]))
            last_s = path.s[b_]
        if path.L - last_s > 2.0:
            edges.append((last_s, path.L))
        gb = []
        for sa, sb in edges:
            sc_, hh = (sa + sb) / 2, (sb - sa) / 2
            for zt_ in (4.4, 8.8, 13.2):
                gb.append(bar(path, z0, sc_, [(-hh + k * 2 * hh / 12, zt_) for k in range(13)], 0.2, -0.38, -0.05))
            nvv = max(1, int(round(2 * hh / 2.7)) - 1)
            for k in range(1, nvv + 1):
                gb.append(bar(path, z0, sc_, [(-hh + 2 * hh * k / (nvv + 1), 0.2), (-hh + 2 * hh * k / (nvv + 1), 16.6)], 0.16, -0.38, -0.05))
        if gb:
            mv, mf = join((mv, mf), *gb)
        _add(f"Podium_Mullions_T{ti}", (mv, mf), gold, coll, weld_it=False)

        # ---- parapet band (glass on an ivory kerb) + coping, along the slab outline inset PARAPET_IN (none in the lobby bay)
        h = PARAPET_T / 2
        kw = KERB_W / 2
        cw, ch = COPING[0] / 2, COPING[1]
        ppts = densify(offset_poly(poly, -PARAPET_IN), 1.2)
        yl = NOTCH_Y[ti]

        def in_lobby(p, yl=yl):
            return yl is not None and abs(p[0]) <= GAP_HALF + 1.3 and p[1] <= yl + 1.0

        pcs, closed = _pieces(ppts, lambda p: not in_lobby(p))
        pv, cv = [], []
        for pc in pcs:
            if closed:
                pc = pc + [pc[0]]
            cpp, _m = coarse(Path(pc))
            pv.append(open_tube(cpp, zt + KERB_H, [(-h, 0.0), (h, 0.0), (h, GLASS_H), (-h, GLASS_H)]))
            cv.append(open_tube(cpp, zt, [(-kw, 0.0), (kw, 0.0), (kw, KERB_H), (-kw, KERB_H)]))
            cv.append(open_tube(cpp, zt + KERB_H + GLASS_H, [(-cw, 0.0), (cw, 0.0), (cw, ch), (-cw, ch)]))
        _add(f"Podium_Parapet_T{ti}", join(*pv), parapet, coll, weld_it=False)
        _add(f"Podium_Coping_T{ti}", join(*cv), ivory, coll, weld_it=False)

        # ---- terrace detail along the slab edge (full outline inset WALL_INSET): channel kerbs, paving lines, water
        tpath = Path(run_path(w - 2 * WALL_INSET, d - 2 * WALL_INSET, wr))
        tpts = list(tpath.p)
        tn = {id(p): n for p, n in zip(tpts, tpath.n)}

        def clear(p, tn=tn, zt=zt):
            n = tn[id(p)]
            for off in (0.0, CH_OUT):
                if rib_hit(p[0] + n[0] * off, p[1] + n[1] * off, zt, 1.0):
                    return False
            return True

        tp_pieces, _c = _pieces(tpts, clear)
        parts, wparts = [], []
        for pc in tp_pieces:
            cp, _m = coarse(Path(pc))
            o_out, o_in = CH_OUT, CH_IN
            parts.append(open_tube(cp, zt, [(o_out, 0.0), (o_out - 0.34, 0.0), (o_out - 0.34, 0.30), (o_out, 0.30)]))
            parts.append(open_tube(cp, zt, [(o_in + 0.34, 0.0), (o_in, 0.0), (o_in, 0.30), (o_in + 0.34, 0.30)]))
            off = 0.9
            while off >= -MAX_IN[ti]:
                parts.append(open_tube(cp, zt, [(off + 0.07, 0.0), (off - 0.07, 0.0), (off - 0.07, 0.05), (off + 0.07, 0.05)]))
                off -= 2.1
            wparts.append(open_tube(cp, zt, [(o_out - 0.34, 0.05), (o_in + 0.34, 0.05), (o_in + 0.34, 0.20), (o_out - 0.34, 0.20)]))
        _add(f"Podium_Terrace_T{ti}", join(*parts), stone, coll, weld_it=False)
        _add(f"Podium_Water_T{ti}", join(*wparts), water, coll, weld_it=False)
    return coll
