"""Eiffel Tower at about 1:33 (10 m to the antenna tip) as SL mesh parts, lattice modelled as real girders. "C:/Program Files/Blender Foundation/Blender 5.2/blender.exe" -b -P gen_eiffel.py -- [--out DIR] [--render] [--probe] [--autosim] [--desk HEIGHT_M] Parts (Z-up, x/y along the tower's faces, origin at ground centre, metres): base_quarter one leg + half of each neighbouring arch + a quarter of the first floor; rez 4x, turned 0/90/180/270 middle_quarter one leg from the first floor to the second + a quarter of the second floor; rez 4x the same way upper_a/_b the shaft from the second floor to the third, in two pieces (smaller pieces = cheaper LI per tri) top third floor, cabins, campanile, antenna Each part is written as NAME.glb (high LOD) plus NAME_LOD2.glb (medium), NAME_LOD1.glb (low), NAME_LOD0.glb (lowest) and NAME_PHYS.glb (physics): the suffixes SL's upload floater looks for next to the high-LOD file. Every LOD has the high LOD's exact bounding box (tiny anchor triangles where needed), since SL stretches LODs and physics to fit it. Every bar is a box (chords, 8 tris) or triangular (bracing, 6 tris) tube with shared, smooth-shaded vertices: fewer bytes per triangle, which is what SL's streaming cost counts. UVs are a planar function of position: no seams at all. Faces: 0 iron, 1 stone (piers) or glass (top cabins). auto/NAME.glb: the medium mesh alone, for an uploader that generates its own LODs (no LOD files next to it). --probe: counts and LI estimates only. --autosim: also render what the uploader's own auto LODs might look like (Blender decimate to 1/3 and 1/9, a rough stand-in for meshoptimizer). --desk H: the whole tower as one mesh scaled to H metres, bars thickened so they still read (use --out desk). Claude Opus 5.5 (subagent for Tessel), 2026-10-11. """ import math import os import sys import bpy import numpy as np from mathutils import Euler, Matrix, Vector argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] HERE = os.path.dirname(os.path.abspath(__file__)) OUT = argv[argv.index("--out") + 1] if "--out" in argv else HERE DESK = float(argv[argv.index("--desk") + 1]) if "--desk" in argv else None RENDER, PROBE, AUTOSIM = ("--render" in argv), ("--probe" in argv), ("--autosim" in argv) S = 10.0 / 330.0 # model metres per real metre Z1, Z2, Z3 = 57.6, 115.7, 276.1 # floor decks (real metres) THK = 2.2 if DESK else 1.0 # bar thickness multiplier LOD_NAMES = {0: "", 1: "_LOD2", 2: "_LOD1", 3: "_LOD0"} # my level -> SL file suffix (LOD2 = medium) LV_THK = 1.0 # set per level: fewer bars in lower LODs, drawn thicker to keep the lattice's mass # ------------------------------------------------------------------ profile (real metres) def pchip(xs, ys): xs, ys = np.asarray(xs, float), np.asarray(ys, float) h, d = np.diff(xs), np.diff(ys) / np.diff(xs) m = np.zeros_like(ys) m[0], m[-1] = d[0], d[-1] for k in range(1, len(xs) - 1): if d[k - 1] * d[k] > 0: w1, w2 = 2 * h[k] + h[k - 1], h[k] + 2 * h[k - 1] m[k] = (w1 + w2) / (w1 / d[k - 1] + w2 / d[k]) def f(x): k = int(np.clip(np.searchsorted(xs, x) - 1, 0, len(xs) - 2)) t = (x - xs[k]) / h[k] return ((2 * t ** 3 - 3 * t ** 2 + 1) * ys[k] + (t ** 3 - 2 * t ** 2 + t) * h[k] * m[k] + (-2 * t ** 3 + 3 * t ** 2) * ys[k + 1] + (t ** 3 - t ** 2) * h[k] * m[k + 1]) return f # outer half-width of the tower (outer corner of each leg), and the width of one leg/pillar W = pchip([0, 30, Z1, 85, Z2, 160, 210, 250, Z3, 300], [62.5, 45.5, 34.5, 25.5, 19.2, 13.6, 10.2, 8.4, 7.4, 6.6]) LEGW = pchip([0, Z1, Z2, 200, Z3], [25.5, 17.0, 11.5, 6.5, 3.6]) def I(z): # inner half-width: the leg's inner corner return W(z) - LEGW(z) def dI(z, e=0.5): return (I(z + e) - I(z - e)) / (2 * e) def P(x, y, z): # real metres -> model Vector return Vector((x * S, y * S, z * S)) # ------------------------------------------------------------------ mesh builder class Part: def __init__(self, name): self.name, self.V, self.F, self.M, self.smooth = name, [], [], [], [] def tube(self, pts, h, nhint, sides=4, mat=0, cap=False): """Swept tube through model-space points. h: half-size (float or per-point list); nhint: the direction a flat side faces (projected off the tube's axis).""" pts = [Vector(p) for p in pts] n = len(pts) hs = [v * THK * LV_THK for v in (h if isinstance(h, (list, tuple)) else [h] * n)] base = len(self.V) if sides == 4: ring = [(math.cos(a) * math.sqrt(2), math.sin(a) * math.sqrt(2)) for a in (math.pi / 4 + k * math.pi / 2 for k in range(4))] else: ring = [(math.cos(a) * 1.25, math.sin(a) * 1.25) for a in (math.pi / 3, math.pi, 5 * math.pi / 3)] for j, p in enumerate(pts): if j == 0: t = pts[1] - pts[0] elif j == n - 1: t = pts[-1] - pts[-2] else: t = (pts[j + 1] - pts[j]).normalized() + (pts[j] - pts[j - 1]).normalized() t.normalize() nh = Vector(nhint) a = nh - t * nh.dot(t) if a.length < 1e-6: a = Vector((1, 0, 0)) - t * t.x a.normalize() b = t.cross(a) for ca, cb in ring: self.V.append(p + a * (ca * hs[j]) + b * (cb * hs[j])) k = len(ring) for j in range(n - 1): for c in range(k): c2 = (c + 1) % k self._face((base + k * j + c, base + k * j + c2, base + k * (j + 1) + c2, base + k * (j + 1) + c), mat, True) if cap: self._face(tuple(base + k * (n - 1) + c for c in range(k)), mat, True) def bar(self, p0, p1, h, nhint, sides=3, mat=0): self.tube([p0, p1], h, nhint, sides, mat) def slab(self, corners, z0, z1, mat=0): """Prism from a CCW (seen from above) model-space xy polygon, flat shaded.""" n = len(corners) base = len(self.V) for z in (z0, z1): for x, y in corners: self.V.append(Vector((x, y, z))) self._face(tuple(base + n + c for c in range(n)), mat, False) self._face(tuple(base + c for c in reversed(range(n))), mat, False) for c in range(n): c2 = (c + 1) % n self._face((base + c, base + c2, base + n + c2, base + n + c), mat, False) def loft(self, rings, mat=0, flat=True): """Closed solid between stacked CCW rings of model-space points (frusta, physics hulls).""" n = len(rings[0]) base = len(self.V) for r in rings: self.V.extend(Vector(p) for p in r) self._face(tuple(base + c for c in reversed(range(n))), mat, False) top = base + n * (len(rings) - 1) self._face(tuple(top + c for c in range(n)), mat, False) for j in range(len(rings) - 1): for c in range(n): c2 = (c + 1) % n self._face((base + n * j + c, base + n * j + c2, base + n * (j + 1) + c2, base + n * (j + 1) + c), mat, not flat) def frustum(self, z0, z1, r0, r1, sides, mat=0, rot=0.0): ring = lambda z, r: [(r * math.cos(rot + 2 * math.pi * c / sides), r * math.sin(rot + 2 * math.pi * c / sides), z) for c in range(sides)] self.loft([ring(z0, r0), ring(z1, r1)], mat) def anchor(self, corner, inward, mat=0): """A 1 mm triangle sitting exactly in a bbox corner (keeps LOD bounding boxes equal).""" c = Vector(corner) e = 0.001 base = len(self.V) self.V += [c, c + Vector((inward[0] * e, 0, 0)), c + Vector((0, inward[1] * e, inward[2] * e))] self._face((base, base + 1, base + 2), mat, False) def merge(self, other, mat_map=None, xform=None): base = len(self.V) for v in other.V: self.V.append(xform @ v if xform else v.copy()) for f, m, s in zip(other.F, other.M, other.smooth): self._face(tuple(base + i for i in f), mat_map.get(m, m) if mat_map else m, s) def scale(self, k): self.V = [v * k for v in self.V] def _face(self, f, mat, smooth): self.F.append(f) self.M.append(mat) self.smooth.append(smooth) def tris(self): return sum(len(f) - 2 for f in self.F) def verts_exported(self): """Vertices after glTF export: shared across smooth faces, split per flat face.""" smooth = {i for f, sm in zip(self.F, self.smooth) if sm for i in f} return len(smooth) + sum(len(f) for f, sm in zip(self.F, self.smooth) if not sm) def bbox(self): a = np.array([tuple(v) for v in self.V]) return a.min(0), a.max(0) # ------------------------------------------------------------------ the parts (real metres in, model out) # LV: 0 high, 1 medium, 2 low, 3 lowest TH_CHORD = lambda z: (0.034 - 0.02 * min(z / Z3, 1.0)) # model half-size of leg/pillar corner chords TH_BRACE = lambda z: (0.0125 - 0.006 * min(z / Z3, 1.0)) FACES = [ # (normal, map(u, z, outward offset) -> point on that outer face); quarters cover +x +y ((0, 1, 0), lambda u, z, off=0.0: P(u, W(z) + off, z)), ((1, 0, 0), lambda u, z, off=0.0: P(W(z) + off, u, z)), ] def levels(z0, z1, n): return list(np.linspace(z0, z1, n + 1)) def leg_lattice(part, zs, faces, chords=("oo", "io", "oi", "ii"), csides=4): """One leg in the +x +y quadrant: corner chords and, per level, X bracing on the listed faces. faces: {face: horizontals?} with face in out_y, out_x, in_x, in_y.""" def c(kind, z): w, i = W(z), I(z) return {"oo": P(w, w, z), "io": P(i, w, z), "oi": P(w, i, z), "ii": P(i, i, z)}[kind] for kind in chords: part.tube([c(kind, z) for z in zs], [TH_CHORD(z) for z in zs], (1, 0, 0), csides) spec = {"out_y": ("io", "oo", (0, 1, 0)), "out_x": ("oi", "oo", (1, 0, 0)), "in_x": ("ii", "io", (-1, 0, 0)), "in_y": ("ii", "oi", (0, -1, 0))} for k in range(len(zs) - 1): z0, z1 = zs[k], zs[k + 1] hb = TH_BRACE(z0) for face, horiz in faces.items(): a, b, nrm = spec[face] part.bar(c(a, z0), c(b, z1), hb, nrm) part.bar(c(b, z0), c(a, z1), hb, nrm) if horiz and k > 0: part.bar(c(a, z0), c(b, z0), hb * 1.1, nrm) def arch_points(n): """Intrados of the first-level arch on the +y face, from the springing on the leg to the crown (x = 0): a Bezier leaving the leg's inner edge along its own curve and arriving level under the first floor.""" zs, zc = 13.0, 47.5 p0 = np.array([I(zs), zs]) t0 = np.array([dI(zs), 1.0]) t0 /= np.linalg.norm(t0) p3 = np.array([0.0, zc]) p1 = p0 + t0 * 18.0 p2 = p3 + np.array([16.0, 0.0]) return [(1 - u) ** 3 * p0 + 3 * (1 - u) ** 2 * u * p1 + 3 * (1 - u) * u ** 2 * p2 + u ** 3 * p3 for u in np.linspace(0, 1, n + 1)] def arch(part, fmap, nrm, n, web=True, outer_chord=True, sides=4): depth = 3.4 pin = arch_points(n) pout = [] for j, p in enumerate(pin): a, b = pin[max(j - 1, 0)], pin[min(j + 1, n)] t = (b - a) / np.linalg.norm(b - a) pout.append(p + np.array([t[1], -t[0]]) * depth) pout[-1][0] = 0.0 inner = [fmap(x, z) for x, z in pin] outer = [fmap(x, z) for x, z in pout] part.tube(inner, 0.021, nrm, sides) if outer_chord: part.tube(outer, 0.018, nrm, sides) if web: for j in range(n): # Warren web if j % 2 == 0: part.bar(inner[j], outer[j + 1], 0.009, nrm) else: part.bar(outer[j], inner[j + 1], 0.009, nrm) def band(part, fmap, nrm, u0, u1, z0, z1, npan, hc=0.016, hb=0.0085, posts=True, xs=True, bottom=True): """Girder band along a face from u0 to u1: two chords, X panels, posts.""" us = list(np.linspace(u0, u1, npan + 1)) part.tube([fmap(u, z1, 0.6) for u in us], hc, nrm, 4) if bottom: part.tube([fmap(u, z0, 0.6) for u in us], hc, nrm, 4) for k in range(npan): a, b = us[k], us[k + 1] if xs: part.bar(fmap(a, z0, 0.6), fmap(b, z1, 0.6), hb, nrm) part.bar(fmap(b, z0, 0.6), fmap(a, z1, 0.6), hb, nrm) if posts and k > 0: part.bar(fmap(a, z0, 0.6), fmap(a, z1, 0.6), hb, nrm) def rail(part, fmap, nrm, u0, u1, z, npost, h=1.4): us = list(np.linspace(u0, u1, npost + 1)) part.bar(fmap(u0, z + h, 0.9), fmap(u1, z + h, 0.9), 0.006, nrm, 4) for u in us[1:]: part.bar(fmap(u, z, 0.9), fmap(u, z + h, 0.9), 0.0045, nrm) def deck_quarter(part, z, outer, inner, thick=1.1, mat=0): """The +x +y quarter of a square ring deck (real metres): one L-shaped slab.""" o, i = outer * S, inner * S part.slab([(i, 0), (o, 0), (o, o), (0, o), (0, i), (i, i)], (z - thick) * S, z * S, mat) def leg_core(part, zs, h): """Lowest LOD: the leg as one thick triangular tube along its centre line (reads as the leg from afar).""" part.tube([P((W(z) + I(z)) / 2, (W(z) + I(z)) / 2, z) for z in zs], h, (1, 1, 0), 3) def piers(part, LV): h = 0.06 corners = ((1, 1), (0, 1), (1, 0), (0, 0)) if LV < 3 else ((1, 1), (0, 0)) for x, y in corners: # masonry piers under the corner chords cx = (I(0) + x * LEGW(0)) * S cy = (I(0) + y * LEGW(0)) * S part.slab([(cx - h, cy - h), (cx + h, cy - h), (cx + h, cy + h), (cx - h, cy + h)], 0.0, 2.0 * S + 0.01, 1) def build_base_quarter(LV): q = Part("base_quarter") if LV == 3: leg_core(q, [5.0, 25.0, Z1], [0.2, 0.15, 0.12]) return q z6 = levels(2.0, 51.0, 6) + [Z1] if LV == 0: # outer faces at double density, inner faces as in the medium LOD leg_lattice(q, levels(2.0, 51.0, 12) + [Z1], {"out_y": True, "out_x": True}) leg_lattice(q, z6, {"in_x": True, "in_y": True}, chords=()) elif LV == 1: leg_lattice(q, z6, {"out_y": True, "out_x": True, "in_x": True, "in_y": True}) else: leg_lattice(q, [2.0, 14.0, 26.0, 39.0, Z1], {"out_y": False, "out_x": False}, csides=3) if LV <= 1: piers(q, LV) for nrm, fmap in FACES: if LV <= 1: arch(q, fmap, nrm, 12 if LV == 0 else 8) band(q, fmap, nrm, 0.0, W(54.0) + 0.8, 51.0, Z1 - 0.6, 10 if LV == 0 else 7) else: arch(q, fmap, nrm, 3, web=False, outer_chord=False, sides=3) q.tube([fmap(0.0, Z1 - 0.6, 0.6), fmap(W(54.0) + 0.8, Z1 - 0.6, 0.6)], 0.016, nrm, 3) if LV == 0: rail(q, fmap, nrm, 0.0, W(Z1) + 0.8, Z1, 6) deck_quarter(q, Z1, W(Z1) + 1.2, I(Z1) - 1.0) return q def build_middle_quarter(LV): m = Part("middle_quarter") if LV == 3: leg_core(m, [Z1, Z2], [0.12, 0.08]) return m z5 = [Z1] + levels(Z1 + 7.0, 110.5, 4) + [Z2] if LV == 0: leg_lattice(m, [Z1] + levels(Z1 + 7.0, 110.5, 8) + [Z2], {"out_y": True, "out_x": True}) leg_lattice(m, z5, {"in_x": False, "in_y": False}, chords=()) elif LV == 1: leg_lattice(m, z5, {"out_y": True, "out_x": True, "in_x": False, "in_y": False}) else: leg_lattice(m, [Z1, 85.0, Z2], {"out_y": False, "out_x": False}, csides=3) for nrm, fmap in FACES: # a quarter of the second-floor band, rail and deck if LV <= 1: band(m, fmap, nrm, 0.0, W(113) + 0.6, 110.5, Z2 - 0.5, 5 if LV == 0 else 3, hc=0.012, hb=0.0065, posts=LV == 0) if LV == 0: rail(m, fmap, nrm, 0.0, W(Z2) + 0.8, Z2, 4) deck_quarter(m, Z2, W(Z2) + 1.0, 5.0) return m def shaft(part, z0, z1, nlev, LV): """Upper shaft: four corner pillars (corner chord + an inner chord on each face, zigzag between) with X bracing across the gap between pillars on each face and a belt at each level.""" zs = levels(z0, z1, nlev) if LV == 3: # the shaft as one tapered square tube part.tube([P(0, 0, z0), P(0, 0, z1)], [W(z0) * S * 0.5, W(z1) * S * 0.5], (1, 0, 0), 4) return for sx in (1, -1): for sy in (1, -1): ths = [TH_CHORD(z) for z in zs] part.tube([P(sx * W(z), sy * W(z), z) for z in zs], ths, (sx, 0, 0), 4 if LV < 2 else 3) if LV >= 2: continue part.tube([P(sx * I(z), sy * W(z), z) for z in zs], [t * 0.8 for t in ths], (0, sy, 0), 4) part.tube([P(sx * W(z), sy * I(z), z) for z in zs], [t * 0.8 for t in ths], (sx, 0, 0), 4) for k in range(nlev): za, zb = zs[k], zs[k + 1] hb = TH_BRACE(za) * 0.85 if k % 2: part.bar(P(sx * W(za), sy * W(za), za), P(sx * I(zb), sy * W(zb), zb), hb, (0, sy, 0)) part.bar(P(sx * W(za), sy * W(za), za), P(sx * W(zb), sy * I(zb), zb), hb, (sx, 0, 0)) else: part.bar(P(sx * I(za), sy * W(za), za), P(sx * W(zb), sy * W(zb), zb), hb, (0, sy, 0)) part.bar(P(sx * W(za), sy * I(za), za), P(sx * W(zb), sy * W(zb), zb), hb, (sx, 0, 0)) if LV == 3: return for sgn in (1, -1): for axis in (0, 1): def q(u, z, s=sgn, ax=axis): return P(u, s * W(z), z) if ax == 0 else P(s * W(z), u, z) nrm = (0, sgn, 0) if axis == 0 else (sgn, 0, 0) if LV == 2: # one X per level across the whole face for k in range(nlev): za, zb = zs[k], zs[k + 1] part.bar(q(-W(za), za), q(W(zb), zb), TH_BRACE(za), nrm) part.bar(q(W(za), za), q(-W(zb), zb), TH_BRACE(za), nrm) continue for k in range(nlev): za, zb = zs[k], zs[k + 1] hb = TH_BRACE(za) part.bar(q(-I(za), za), q(I(zb), zb), hb, nrm) part.bar(q(I(za), za), q(-I(zb), zb), hb, nrm) part.bar(q(-W(zb), zb), q(W(zb), zb), hb * 1.15, nrm) # belt at the top of the panel UPPER_SPLIT = 198.0 def build_upper(which, LV): u = Part("upper_" + which) z0, z1 = (Z2, UPPER_SPLIT) if which == "a" else (UPPER_SPLIT, Z3 - 1.2) shaft(u, z0, z1, {0: 10, 1: 5, 2: 2, 3: 1}[LV], LV) return u def build_top(LV): t = Part("top") zt = Z3 - 1.2 o = (W(Z3) + 1.4) * S if LV < 3: t.slab([(-o, -o), (o, -o), (o, o), (-o, o)], zt * S, (zt + 1.2) * S, 0) # third-floor deck c = (W(Z3) - 0.6) * S z0, z1 = Z3 * S, (Z3 + 6.0) * S if LV < 3: t.slab([(-c, -c), (c, -c), (c, c), (-c, c)], z0, z1, 1) # glazed cabin za, ztip = (Z3 + 22.0) * S + 0.10, 10.0 if LV == 3: t.tube([(0, 0, z0), (0, 0, (Z3 + 11.0) * S)], [c * 0.75, c * 0.45], (1, 0, 0), 4) t.bar((0, 0, (Z3 + 11.0) * S), (0, 0, ztip), 0.012, (1, 0, 0)) return t if LV >= 2: if LV == 2: c2 = c * 0.62 t.slab([(-c2, -c2), (c2, -c2), (c2, c2), (-c2, c2)], z1, (Z3 + 11.0) * S, 1) t.frustum((Z3 + 11.0) * S, za, c2 * 0.8, 0.012, 4, 0, rot=math.pi / 4) t.bar((0, 0, z1), (0, 0, ztip), 0.012, (1, 0, 0)) return t nm = 4 for s in (1, -1): # mullions for k in range(1, nm): u = -c + 2 * c * k / nm t.bar((u, s * (c + 0.004), z0), (u, s * (c + 0.004), z1), 0.004, (0, s, 0)) t.bar((s * (c + 0.004), u, z0), (s * (c + 0.004), u, z1), 0.004, (s, 0, 0)) r = c + 0.012 t.slab([(-r, -r), (r, -r), (r, r), (-r, r)], z1, z1 + 0.012, 0) # roof rim c2 = c * 0.62 # upper terrace cabin z2 = (Z3 + 11.0) * S t.slab([(-c2, -c2), (c2, -c2), (c2, c2), (-c2, c2)], z1 + 0.012, z2, 1) r2 = c2 + 0.01 t.slab([(-r2, -r2), (r2, -r2), (r2, r2), (-r2, r2)], z2, z2 + 0.01, 0) pc, zc0, zc1 = c2 * 0.7, z2 + 0.01, (Z3 + 22.0) * S # campanile + lantern for sx in (1, -1): for sy in (1, -1): t.tube([(sx * pc, sy * pc, zc0), (sx * pc * 0.8, sy * pc * 0.8, zc1)], 0.007, (sx, 0, 0), 4) t.frustum(zc1, zc1 + 0.025, pc * 1.15, pc * 1.15, 8, 0, rot=math.pi / 8) t.frustum(zc1 + 0.025, zc1 + 0.10, pc * 0.6, pc * 0.25, 8, 0, rot=math.pi / 8) zs = list(np.linspace(za, ztip, 6)) # antenna mast to 330 m t.tube([(0, 0, z) for z in zs], [0.016 - 0.012 * (z - za) / (ztip - za) for z in zs], (1, 0, 0), 4, cap=True) for zz, rr in ((za + 0.18, 0.03), (za + 0.45, 0.022)): t.frustum(zz, zz + 0.05, rr, rr, 6, 0) return t # ------------------------------------------------------------------ physics shapes (Prim type, simple solids) def phys_base_quarter(): p = Part("base_quarter_PHYS") sq = lambda z, a, b: [(a, a, z), (b, a, z), (b, b, z), (a, b, z)] p.loft([sq(0.0, I(0) * S, W(0) * S), sq(25 * S, I(25) * S, W(25) * S), sq(Z1 * S, I(Z1) * S, W(Z1) * S)]) deck_quarter(p, Z1, W(Z1) + 1.2, I(Z1) - 1.0) return p def phys_middle_quarter(): p = Part("middle_quarter_PHYS") sq = lambda z, a, b: [(a, a, z), (b, a, z), (b, b, z), (a, b, z)] p.loft([sq(Z1 * S, I(Z1) * S, W(Z1) * S), sq(Z2 * S, I(Z2) * S, W(Z2) * S)]) deck_quarter(p, Z2, W(Z2) + 1.0, 5.0) return p def phys_shaft(name, z0, z1): p = Part(name + "_PHYS") sq = lambda z: [(-W(z) * S, -W(z) * S, z * S), (W(z) * S, -W(z) * S, z * S), (W(z) * S, W(z) * S, z * S), (-W(z) * S, W(z) * S, z * S)] p.loft([sq(z0), sq(z1)]) return p def phys_top(): p = Part("top_PHYS") o = (W(Z3) + 1.4) * S p.slab([(-o, -o), (o, -o), (o, o), (-o, o)], (Z3 - 1.2) * S, (Z3 + 11) * S, 0) return p # ------------------------------------------------------------------ SL cost estimate def lod_weights(radius): """Area weights of high/medium/low/lowest from LLMeshCostData::getRadiusWeightedTris.""" dl, dlo, dm = min(radius / 0.03, 512), min(radius / 0.06, 512), min(radius / 0.24, 512) mx = 102944.0 high, mid, low = min(math.pi * dm * dm, mx), min(math.pi * dlo * dlo, mx), min(math.pi * dl * dl, mx) a = [max(v, 1.0) for v in (high, mid - high, low - mid, mx - low)] return [v / sum(a) for v in a] def est_tris(verts, tris): """SL's 'estimated triangles' for one LOD: (compressed bytes - 384) / 16, floor 1 (llmeshrepository.cpp). Bytes modelled as 0.67 x raw (16 B per vertex, 6 per triangle) + 250 B of per-LOD overhead: roughly what the teapot's two streaming quotes (3432 tris -> 3.99, 1472 -> 1.43) imply. Rough, maybe +-30%.""" b = 0.67 * (16 * verts + 6 * tris) + 250 return max(b - 384, 16) / 16 def li(lods, radius): """Streaming cost (LI) from [(verts, tris)] for high, medium, low, lowest.""" return sum(w * est_tris(v, t) for w, (v, t) in zip(lod_weights(radius), lods)) * 15000 / 250000 # ------------------------------------------------------------------ build everything def build_all(LV): global LV_THK LV_THK = {0: 1.0, 1: 1.15, 2: 1.7, 3: 1.0}[LV] return [build_base_quarter(LV), build_middle_quarter(LV), build_upper("a", LV), build_upper("b", LV), build_top(LV)] def physics_all(): return [phys_base_quarter(), phys_middle_quarter(), phys_shaft("upper_a", Z2, UPPER_SPLIT), phys_shaft("upper_b", UPPER_SPLIT, Z3 - 1.2), phys_top()] def whole(parts, name): """Everything as one mesh, quarters repeated four times round.""" w = Part(name) for p in parts: if p.name.startswith(("base_quarter", "middle_quarter")): for k in range(4): w.merge(p, xform=Matrix.Rotation(k * math.pi / 2, 3, "Z")) else: w.merge(p, mat_map={1: 2} if p.name.startswith("top") else None) # top's glass is face 2 here return w def match_bbox(p, lo, hi): """Add anchor triangles so p's bbox equals (lo, hi) exactly ((lo, hi) contains p).""" plo, phi = p.bbox() if np.any(plo > lo + 1e-5): p.anchor(lo, (1, 1, 1)) if np.any(phi < hi - 1e-5): p.anchor(hi, (-1, -1, -1)) if DESK: # a desk copy is seen from a metre or two: the 10 m model's medium and low specs make its high and medium # LODs (finer lattice would turn to noise); its low is the 10 m lowest; its lowest a bare spike (it's ~free # and a desk ornament can vanish beyond ~15 m) LEVELS = {} for LV in range(4): if LV < 3: d = whole(build_all(LV + 1), "desk" + LOD_NAMES[LV]) else: d = Part("desk" + LOD_NAMES[LV]) d.tube([P(0, 0, 0), P(0, 0, 300.0)], [W(0) * S * 0.25, 0.01], (1, 0, 0), 4) d.scale(DESK / 10.0) LEVELS[LV] = [d] ph = Part("desk_PHYS") sq = lambda z, h: [(-h, -h, z), (h, -h, z), (h, h, z), (-h, h, z)] ph.loft([sq(0.0, W(0) * S * 0.7), sq(Z1 * S, W(Z1) * S), sq(Z3 * S, W(Z3) * S), sq(10.0, 0.02)]) ph.scale(DESK / 10.0) PHYS = [ph] else: LEVELS = {LV: build_all(LV) for LV in range(4)} PHYS = physics_all() for LV in (1, 2, 3): for hp, lp in zip(LEVELS[0], LEVELS[LV]): lp.name = hp.name + LOD_NAMES[LV] for k in range(len(PHYS)): # every LOD and the physics shape get the same bbox (the union): SL fits them to the high's group = [LEVELS[LV][k] for LV in range(4)] + [PHYS[k]] lo = np.min([g.bbox()[0] for g in group], 0) hi = np.max([g.bbox()[1] for g in group], 0) grow = max((lo - LEVELS[0][k].bbox()[0]).__abs__().max(), (hi - LEVELS[0][k].bbox()[1]).max()) if grow > 1e-4: print(f"note: {LEVELS[0][k].name} bbox grown {grow * 1000:.1f} mm to contain its lower LODs") for g in group: match_bbox(g, lo, hi) CENTRE = {} tot_custom = tot_auto = 0.0 tot_tris = 0 print(f"{'part':15s} {'tris high/med/low/lowest':>26s} {'phys':>5s} {'size (m)':>20s} {'radius':>6s} " f"{'LI own LODs':>11s} {'LI auto/':>8s}") for k, hp in enumerate(LEVELS[0]): lo, hi = hp.bbox() size, ctr = hi - lo, (hi + lo) / 2 rad = float(np.linalg.norm(size)) / 2 tl = [LEVELS[LV][k].tris() for LV in range(4)] vl = [LEVELS[LV][k].verts_exported() for LV in range(4)] custom = li(list(zip(vl, tl)), rad) auto = li([(vl[1] / 3 ** j, tl[1] / 3 ** j) for j in range(4)], rad) # auto/ set: medium as the high n = 4 if hp.name.endswith("_quarter") else 1 tot_custom, tot_auto, tot_tris = tot_custom + n * custom, tot_auto + n * auto, tot_tris + n * tl[0] CENTRE[hp.name] = ctr print(f"{hp.name:15s} {'/'.join(str(t) for t in tl):>26s} {PHYS[k].tris():5d} " f"{' x '.join(f'{v:.2f}' for v in size):>20s} {rad:6.2f} {custom:11.2f} {auto:8.2f}" + (" (x4)" if n > 1 else "")) print(f"total high tris {tot_tris}; est LI {tot_custom:.1f} with these LOD files, {tot_auto:.1f} with the uploader's " f"auto LODs from the auto/ files (byte model is rough: trust the uploader's quote)") print("bbox centres (tower frame, origin at ground centre):") for k, c in CENTRE.items(): print(f" {k}: <{c[0]:.3f}, {c[1]:.3f}, {c[2]:.3f}>") if PROBE: sys.exit(0) # ------------------------------------------------------------------ blender objects, export def srgb_lin(c): return tuple(((v + 0.055) / 1.055) ** 2.4 if v > 0.04045 else v / 12.92 for v in c) def hexc(h): h = h.lstrip("#") return tuple(int(h[i:i + 2], 16) / 255 for i in (0, 2, 4)) def material(name, hexcol, rough=0.7, metal=0.0): m = bpy.data.materials.new(name) m.use_nodes = True b = m.node_tree.nodes["Principled BSDF"] b.inputs["Base Color"].default_value = (*srgb_lin(hexc(hexcol)), 1) b.inputs["Roughness"].default_value = rough b.inputs["Metallic"].default_value = metal return m for o in list(bpy.data.objects): bpy.data.objects.remove(o) IRON = material("iron", "#7a5a40", 0.62) STONE = material("stone", "#b8ab94", 0.9) GLASS = material("glass", "#3c4650", 0.25) def to_object(p, second): me = bpy.data.meshes.new(p.name) me.from_pydata([tuple(v) for v in p.V], [], p.F) me.update() me.polygons.foreach_set("material_index", p.M) me.polygons.foreach_set("use_smooth", p.smooth) uv = me.uv_layers.new(name="UVMap") co = np.array([tuple(v) for v in p.V]) li_ = np.zeros(len(me.loops), dtype=np.int32) me.loops.foreach_get("vertex_index", li_) uv.data.foreach_set("uv", np.stack([co[li_, 0] - co[li_, 1], co[li_, 2]], 1).astype(np.float32).ravel()) me.update() ob = bpy.data.objects.new(p.name, me) bpy.context.scene.collection.objects.link(ob) for m in [IRON] + (second or []): # the same material list in every LOD of a part me.materials.append(m) return ob def export(ob, path): for o in bpy.context.scene.objects: o.select_set(o == ob) bpy.context.view_layer.objects.active = ob bpy.ops.export_scene.gltf(filepath=path, export_format="GLB", use_selection=True, export_yup=False, export_apply=True) os.makedirs(OUT, exist_ok=True) OBS, LVOF = {}, {} for k, hp in enumerate(LEVELS[0]): second = {"base_quarter": [STONE], "top": [GLASS], "desk": [STONE, GLASS]}.get(hp.name, []) for LV in range(4): p = LEVELS[LV][k] OBS[p.name] = to_object(p, second) LVOF[p.name] = LV export(OBS[p.name], os.path.join(OUT, p.name + ".glb")) ob = OBS[LEVELS[1][k].name] # auto/: the medium mesh alone, for an uploader that makes its own LODs ob.name = hp.name + "_auto" os.makedirs(os.path.join(OUT, "auto"), exist_ok=True) export(ob, os.path.join(OUT, "auto", hp.name + ".glb")) ob.name = LEVELS[1][k].name OBS[PHYS[k].name] = to_object(PHYS[k], None) LVOF[PHYS[k].name] = -1 export(OBS[PHYS[k].name], os.path.join(OUT, PHYS[k].name + ".glb")) print("wrote", len(OBS), "glb files to", OUT) if not (RENDER or AUTOSIM): sys.exit(0) # ------------------------------------------------------------------ previews scene = bpy.context.scene scene.render.engine = "BLENDER_EEVEE" scene.eevee.taa_render_samples = 16 scene.view_settings.view_transform = "Standard" scene.world = bpy.data.worlds.new("w") scene.world.use_nodes = True scene.world.node_tree.nodes["Background"].inputs["Color"].default_value = (*srgb_lin(hexc("#a9bccf")), 1) scene.world.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.9 bpy.ops.mesh.primitive_plane_add(size=80, location=(0, 0, 0)) bpy.context.active_object.data.materials.append(material("ground", "#8c8a78", 0.95)) sun = bpy.data.objects.new("sun", bpy.data.lights.new("sun", "SUN")) sun.data.energy = 3.2 sun.data.angle = math.radians(3) sun.rotation_euler = Euler((math.radians(48), 0, math.radians(-30))) scene.collection.objects.link(sun) fill = bpy.data.objects.new("fill", bpy.data.lights.new("fill", "SUN")) fill.data.energy = 0.7 fill.rotation_euler = Euler((math.radians(70), 0, math.radians(160))) scene.collection.objects.link(fill) # copies of each quarter turned about z, as they'd be rezzed for name, ob in list(OBS.items()): if "_quarter" in name: for k in (1, 2, 3): d = bpy.data.objects.new(f"{name}_r{k}", ob.data) d.rotation_euler = (0, 0, k * math.pi / 2) scene.collection.objects.link(d) LVOF[d.name] = LVOF[name] def show_level(LV): """Render only one LOD level (-1: the physics shapes).""" for o in scene.objects: if o.name in LVOF: o.hide_render = LVOF[o.name] != LV def shot(fname, target, az, el, dist, lens=50, res=(640, 860), ortho=None, loc=None): scene.render.resolution_x, scene.render.resolution_y = res cam = bpy.data.objects.new("cam", bpy.data.cameras.new("cam")) scene.collection.objects.link(cam) cam.data.lens = lens cam.data.clip_start = 0.02 if ortho: cam.data.type = "ORTHO" cam.data.ortho_scale = ortho t = Vector(target) d = Vector((math.cos(math.radians(el)) * math.cos(math.radians(az)), math.cos(math.radians(el)) * math.sin(math.radians(az)), math.sin(math.radians(el)))) cam.location = Vector(loc) if loc else t + d * dist d = (cam.location - t).normalized() cam.rotation_euler = (-d).to_track_quat("-Z", "Y").to_euler() scene.camera = cam scene.render.filepath = os.path.join(OUT, fname) bpy.ops.render.render(write_still=True) bpy.data.objects.remove(cam) print("rendered", fname) H = DESK or 10.0 if RENDER and DESK: show_level(0) shot("preview_desk.png", (0, 0, H * 0.46), -55, 12, H * 1.9) elif RENDER: show_level(0) shot("preview.png", (0, 0, 4.6), -55, 6, 18.0) shot("preview_arches.png", (0.0, 0.9, 0.95), 75, 6, 4.6, lens=35, res=(900, 640)) shot("preview_side.png", (0, 0, 5.0), -90, 0, 30, res=(560, 860), ortho=10.6) shot("preview_visitor.png", (0, 0, 3.4), 0, 0, 0, lens=24, res=(640, 860), loc=(2.2, -6.5, 1.7)) strip = [] for LV in (1, 2, 3, -1): show_level(LV) shot("strip_tmp.png", (0, 0, 4.6), -55, 6, 18.0, res=(320, 430)) img = bpy.data.images.load(os.path.join(OUT, "strip_tmp.png")) strip.append(np.array(img.pixels[:]).reshape(430, 320, 4)) bpy.data.images.remove(img) os.remove(os.path.join(OUT, "strip_tmp.png")) out = bpy.data.images.new("strip", 320 * 4, 430) out.pixels = np.concatenate(strip, 1).ravel() out.filepath_raw = os.path.join(OUT, "preview_lods.png") out.file_format = "PNG" out.save() print("rendered preview_lods.png (medium, low, lowest, physics)") if AUTOSIM: # the auto/ set (medium mesh) after the uploader's own decimation, roughly show_level(1) for ratio, tag in ((1 / 3, "med"), (1 / 9, "low")): for o in scene.objects: if o.name in LVOF and not o.hide_render: mod = o.modifiers.get("dec") or o.modifiers.new("dec", "DECIMATE") mod.ratio = ratio shot(f"preview_autosim_{tag}.png", (0, 0, 4.6), -55, 6, 18.0, res=(320, 430))