506 lines
16 KiB
Luau
506 lines
16 KiB
Luau
--!strict
|
|
-- model/blend/Prim: model/blend/Mesh polygons to Scene primitives (one per material slot): corner normals from smooth
|
|
-- fans (angle-weighted face normals; sharp faces, sharp edges, auto smooth before 4.1 and non-manifold or flipped edges
|
|
-- split fans, as Blender does), custom normals, vertices shared by corners with equal attributes, n-gons by ear
|
|
-- clipping, deform weights (top 4) and shape keys as morph targets.
|
|
local Types = require("@rosetta/Types")
|
|
local Polygon = require("@rosetta/codecs/model/Polygon")
|
|
local Rig = require("@rosetta/codecs/model/Rig")
|
|
local Normals = require("@rosetta/model/blend/Normals")
|
|
local MeshT = require("@rosetta/model/blend/Mesh")
|
|
|
|
local Prim = {}
|
|
|
|
local Scene = Types.Scene
|
|
local readu32, readf32, writef32, writeu32 = buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32
|
|
local sqrt, acos = math.sqrt, math.acos
|
|
|
|
export type Options = {
|
|
triangulate: boolean?, -- default true
|
|
flipV: boolean?, -- default true (glTF's top-left UV origin)
|
|
normals: boolean?, -- default true
|
|
}
|
|
export type Skinning = { joints: { [number]: number } } -- def_nr (0-based) -> joint index (0-based) in the skin
|
|
|
|
local function face(poly: MeshT.Poly, fi: number): (number, number)
|
|
return readu32(poly.faceStart, fi * 4), readu32(poly.faceStart, fi * 4 + 4)
|
|
end
|
|
|
|
local function vec(pos: buffer, v: number): (number, number, number)
|
|
return readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8)
|
|
end
|
|
|
|
-- face normals (Newell) and corner angles
|
|
function Prim.geometry(poly: MeshT.Poly): (buffer, buffer)
|
|
local fn = buffer.create(poly.nf * 12)
|
|
local ang = buffer.create(poly.nc * 4)
|
|
local cv, pos = poly.cornerVert, poly.pos
|
|
for fi = 0, poly.nf - 1 do
|
|
local s0, s1 = face(poly, fi)
|
|
local nx, ny, nz = 0, 0, 0
|
|
local n = s1 - s0
|
|
for c = s0, s1 - 1 do
|
|
local d = if c + 1 < s1 then c + 1 else s0
|
|
local x1, y1, z1 = vec(pos, readu32(cv, c * 4))
|
|
local x2, y2, z2 = vec(pos, readu32(cv, d * 4))
|
|
nx += (y1 - y2) * (z1 + z2)
|
|
ny += (z1 - z2) * (x1 + x2)
|
|
nz += (x1 - x2) * (y1 + y2)
|
|
end
|
|
local l = sqrt(nx * nx + ny * ny + nz * nz)
|
|
if l > 0 then
|
|
nx, ny, nz = nx / l, ny / l, nz / l
|
|
end
|
|
writef32(fn, fi * 12, nx)
|
|
writef32(fn, fi * 12 + 4, ny)
|
|
writef32(fn, fi * 12 + 8, nz)
|
|
if n >= 3 then
|
|
for c = s0, s1 - 1 do
|
|
local pc = if c > s0 then c - 1 else s1 - 1
|
|
local nc = if c + 1 < s1 then c + 1 else s0
|
|
local x, y, z = vec(pos, readu32(cv, c * 4))
|
|
local ax, ay, az = vec(pos, readu32(cv, pc * 4))
|
|
local bx, by, bz = vec(pos, readu32(cv, nc * 4))
|
|
ax, ay, az = ax - x, ay - y, az - z
|
|
bx, by, bz = bx - x, by - y, bz - z
|
|
local la, lb = sqrt(ax * ax + ay * ay + az * az), sqrt(bx * bx + by * by + bz * bz)
|
|
local a = 0
|
|
if la > 0 and lb > 0 then
|
|
a = acos(math.clamp((ax * bx + ay * by + az * bz) / (la * lb), -1, 1))
|
|
end
|
|
writef32(ang, c * 4, a)
|
|
end
|
|
end
|
|
end
|
|
return fn, ang
|
|
end
|
|
|
|
-- smooth fans: for each corner the corner after it in its face, and the fan links across smooth edges
|
|
export type Fans = {
|
|
next: buffer, -- u32 per corner: the next corner of its face
|
|
prev: buffer, -- u32 per corner
|
|
face: buffer, -- u32 per corner: its face
|
|
-- per corner: the corner of the neighbouring face across the edge from this corner to the next one (the corner
|
|
-- at this corner's next vertex), or -1 where the edge splits fans
|
|
across: { [number]: number },
|
|
}
|
|
|
|
function Prim.fans(poly: MeshT.Poly, fn: buffer): Fans
|
|
local nc, nv = poly.nc, poly.nv
|
|
local cv = poly.cornerVert
|
|
local nxt, prv, fc = buffer.create(nc * 4), buffer.create(nc * 4), buffer.create(nc * 4)
|
|
for fi = 0, poly.nf - 1 do
|
|
local s0, s1 = face(poly, fi)
|
|
for c = s0, s1 - 1 do
|
|
writeu32(nxt, c * 4, if c + 1 < s1 then c + 1 else s0)
|
|
writeu32(prv, c * 4, if c > s0 then c - 1 else s1 - 1)
|
|
writeu32(fc, c * 4, fi)
|
|
end
|
|
end
|
|
local first: { [number]: number } = {}
|
|
local second: { [number]: number } = {}
|
|
local uses: { [number]: number } = {}
|
|
for c = 0, nc - 1 do
|
|
local a, b = readu32(cv, c * 4), readu32(cv, readu32(nxt, c * 4) * 4)
|
|
local key = math.min(a, b) * nv + math.max(a, b)
|
|
local u = (uses[key] or 0) + 1
|
|
uses[key] = u
|
|
if u == 1 then
|
|
first[key] = c
|
|
elseif u == 2 then
|
|
second[key] = c
|
|
end
|
|
end
|
|
local across: { [number]: number } = {}
|
|
local smooth = poly.faceSmooth
|
|
local cosLimit = if poly.autoSmooth then math.cos(poly.autoSmooth) else nil
|
|
for key, u in uses do
|
|
if u == 2 then
|
|
local c1, c2 = first[key], second[key]
|
|
local f1, f2 = readu32(fc, c1 * 4), readu32(fc, c2 * 4)
|
|
local a1 = readu32(cv, c1 * 4)
|
|
local a2 = readu32(cv, c2 * 4)
|
|
local ok = a1 ~= a2 and f1 ~= f2 and buffer.readu8(smooth, f1) ~= 0 and buffer.readu8(smooth, f2) ~= 0
|
|
and not poly.sharp[key]
|
|
if ok and cosLimit then
|
|
local d = readf32(fn, f1 * 12) * readf32(fn, f2 * 12) + readf32(fn, f1 * 12 + 4) * readf32(fn, f2 * 12 + 4)
|
|
+ readf32(fn, f1 * 12 + 8) * readf32(fn, f2 * 12 + 8)
|
|
ok = d >= cosLimit
|
|
end
|
|
if ok then
|
|
-- c1 runs a -> b, c2 runs b -> a: the corner at b in face 2 is c2, at a it is next(c2)
|
|
across[c1] = c2
|
|
across[c2] = c1
|
|
end
|
|
end
|
|
end
|
|
return { next = nxt, prev = prv, face = fc, across = across }
|
|
end
|
|
|
|
-- corner normals: angle-weighted face normals summed over each smooth fan; with fan ids (u32 per corner)
|
|
function Prim.cornerNormals(poly: MeshT.Poly, fn: buffer, ang: buffer, fans: Fans): (buffer, buffer)
|
|
local nc = poly.nc
|
|
local parent = buffer.create(nc * 4)
|
|
for c = 0, nc - 1 do
|
|
writeu32(parent, c * 4, c)
|
|
end
|
|
local function root(c: number): number
|
|
local r = c
|
|
while readu32(parent, r * 4) ~= r do
|
|
r = readu32(parent, r * 4)
|
|
end
|
|
while readu32(parent, c * 4) ~= r do
|
|
local nx = readu32(parent, c * 4)
|
|
writeu32(parent, c * 4, r)
|
|
c = nx
|
|
end
|
|
return r
|
|
end
|
|
local function union(a: number, b: number)
|
|
local ra, rb = root(a), root(b)
|
|
if ra ~= rb then
|
|
writeu32(parent, math.max(ra, rb) * 4, math.min(ra, rb))
|
|
end
|
|
end
|
|
for c1, c2 in fans.across do
|
|
if c1 < c2 then
|
|
-- edge c1 (a -> b) shared with c2 (b -> a): corners at b are next(c1) and c2, at a c1 and next(c2)
|
|
union(readu32(fans.next, c1 * 4), c2)
|
|
union(c1, readu32(fans.next, c2 * 4))
|
|
end
|
|
end
|
|
local acc = buffer.create(nc * 12)
|
|
local fanId = buffer.create(nc * 4)
|
|
for c = 0, nc - 1 do
|
|
local r = root(c)
|
|
writeu32(fanId, c * 4, r)
|
|
local fi = readu32(fans.face, c * 4)
|
|
local w = readf32(ang, c * 4)
|
|
for k = 0, 2 do
|
|
writef32(acc, (r * 3 + k) * 4, readf32(acc, (r * 3 + k) * 4) + readf32(fn, (fi * 3 + k) * 4) * w)
|
|
end
|
|
end
|
|
local out = buffer.create(nc * 12)
|
|
for c = 0, nc - 1 do
|
|
local r = readu32(fanId, c * 4)
|
|
local x, y, z = readf32(acc, r * 12), readf32(acc, r * 12 + 4), readf32(acc, r * 12 + 8)
|
|
local l = sqrt(x * x + y * y + z * z)
|
|
local fi = readu32(fans.face, c * 4)
|
|
writef32(out, c * 12, if l > 1e-20 then x / l else readf32(fn, fi * 12))
|
|
writef32(out, c * 12 + 4, if l > 1e-20 then y / l else readf32(fn, fi * 12 + 4))
|
|
writef32(out, c * 12 + 8, if l > 1e-20 then z / l else readf32(fn, fi * 12 + 8))
|
|
end
|
|
return out, fanId
|
|
end
|
|
|
|
function Prim.normals(poly: MeshT.Poly): buffer
|
|
local fn, ang = Prim.geometry(poly)
|
|
local fans = Prim.fans(poly, fn)
|
|
local nrm, fanId = Prim.cornerNormals(poly, fn, ang, fans)
|
|
if poly.customNormals then
|
|
return poly.customNormals :: buffer
|
|
end
|
|
if poly.encodedNormals then
|
|
return Normals.decode(poly, nrm, fanId, fans, ang)
|
|
end
|
|
return nrm
|
|
end
|
|
|
|
-- triangles of face fi as corner indices (appended to out)
|
|
local function triangulate(poly: MeshT.Poly, fi: number, fnx: number, fny: number, fnz: number, out: { number })
|
|
local s0, s1 = face(poly, fi)
|
|
local n = s1 - s0
|
|
if n < 3 then
|
|
return
|
|
end
|
|
if n == 3 then
|
|
table.insert(out, s0)
|
|
table.insert(out, s0 + 1)
|
|
table.insert(out, s0 + 2)
|
|
return
|
|
end
|
|
local ax, ay, az = math.abs(fnx), math.abs(fny), math.abs(fnz)
|
|
local cu, cv, sign = 0, 1, fnz
|
|
if ax >= ay and ax >= az then
|
|
cu, cv, sign = 1, 2, fnx
|
|
elseif ay >= az then
|
|
cu, cv, sign = 2, 0, fny
|
|
end
|
|
local ring = table.create(n * 2) :: { number }
|
|
for c = s0, s1 - 1 do
|
|
local v = readu32(poly.cornerVert, c * 4)
|
|
local u, w = readf32(poly.pos, (v * 3 + cu) * 4), readf32(poly.pos, (v * 3 + cv) * 4)
|
|
table.insert(ring, if sign < 0 then -u else u)
|
|
table.insert(ring, w)
|
|
end
|
|
local tris = Polygon.triangulate({ ring })
|
|
if #tris == (n - 2) * 6 then
|
|
for k = 2, #tris, 2 do
|
|
table.insert(out, s0 + tris[k] - 1)
|
|
end
|
|
return
|
|
end
|
|
for k = 1, n - 2 do -- degenerate: a fan
|
|
table.insert(out, s0)
|
|
table.insert(out, s0 + k)
|
|
table.insert(out, s0 + k + 1)
|
|
end
|
|
end
|
|
|
|
local function accessor(t: { number }, comps: number): Types.Accessor
|
|
local n = #t // comps
|
|
local b = buffer.create(#t * 4)
|
|
for i = 1, #t do
|
|
writef32(b, (i - 1) * 4, t[i])
|
|
end
|
|
return Scene.accessor(b, "f32", comps, n)
|
|
end
|
|
|
|
export type Built = { mesh: Types.Mesh, slots: { number }, vertexSource: { { number } } }
|
|
|
|
-- morph targets of the output vertices (vsrc: their mesh vertices): each key minus its relative key, times the weight
|
|
-- of the key's vertex group, as Blender evaluates relative keys
|
|
local function targetDeltas(poly: MeshT.Poly, vsrc: { number }, shapes: { MeshT.Shape }, ref: number, groups: { string }?): { { [string]: Types.Accessor } }
|
|
local n = #vsrc
|
|
local targets: { { [string]: Types.Accessor } } = {}
|
|
for k, s in shapes do
|
|
if k ~= ref then
|
|
local rel = shapes[s.relative + 1] or shapes[ref]
|
|
local base = rel.data
|
|
local def: number? = nil
|
|
if s.vgroup and groups then
|
|
for gi, g in groups do
|
|
if g == s.vgroup then
|
|
def = gi - 1
|
|
end
|
|
end
|
|
end
|
|
local t = table.create(n * 3) :: { number }
|
|
for i = 1, n do
|
|
local v = vsrc[i]
|
|
local w: number = 1
|
|
if def then
|
|
w = 0
|
|
local list = poly.weights and poly.weights[v + 1] or {}
|
|
for q = 1, #list - 1, 2 do
|
|
if list[q] == def then
|
|
w = list[q + 1]
|
|
end
|
|
end
|
|
end
|
|
for c = 0, 2 do
|
|
t[(i - 1) * 3 + c + 1] = (readf32(s.data, (v * 3 + c) * 4) - readf32(base, (v * 3 + c) * 4)) * w
|
|
end
|
|
end
|
|
table.insert(targets, { POSITION = accessor(t, 3) } :: { [string]: Types.Accessor })
|
|
end
|
|
end
|
|
return targets
|
|
end
|
|
|
|
-- a "lines" primitive of the given edges (u32 vertex pairs), with the morph targets the face primitives have
|
|
function Prim.lines(poly: MeshT.Poly, edges: buffer, shapes: { MeshT.Shape }?, ref: number?, groups: { string }?): Types.Primitive?
|
|
local ne = buffer.len(edges) // 8
|
|
if ne == 0 then
|
|
return nil
|
|
end
|
|
local out: { [number]: number } = {}
|
|
local vsrc: { number } = {}
|
|
local I = buffer.create(ne * 8)
|
|
for k = 0, ne * 2 - 1 do
|
|
local v = readu32(edges, k * 4)
|
|
local o = out[v]
|
|
if not o then
|
|
o = #vsrc
|
|
out[v] = o
|
|
table.insert(vsrc, v)
|
|
end
|
|
writeu32(I, k * 4, o)
|
|
end
|
|
local n = #vsrc
|
|
local P = buffer.create(n * 12)
|
|
for i = 1, n do
|
|
buffer.copy(P, (i - 1) * 12, poly.pos, vsrc[i] * 12, 12)
|
|
end
|
|
local prim: Types.Primitive = { attributes = { POSITION = Scene.accessor(P, "f32", 3, n) }, indices = Scene.accessor(I, "u32", 1, ne * 2), mode = "lines" }
|
|
if shapes and ref and #shapes > 1 then
|
|
prim.targets = targetDeltas(poly, vsrc, shapes, ref, groups)
|
|
end
|
|
return prim
|
|
end
|
|
|
|
-- slots[k] = the scene material of slot k - 1 (or 0 for none); skin maps deform groups to joints; vgroups names the
|
|
-- vertex groups (def_nr + 1) for shape keys limited to one
|
|
function Prim.build(poly: MeshT.Poly, slots: { number }, opts: Options?, skin: Skinning?, shapes: { MeshT.Shape }?, ref: number?, vgroups: { string }?): Built
|
|
local triangulateOn = not (opts and opts.triangulate == false)
|
|
local flipV = not (opts and opts.flipV == false)
|
|
local withNormals = not (opts and opts.normals == false)
|
|
local nrm = if withNormals and poly.nf > 0 then Prim.normals(poly) else nil
|
|
local fn = if poly.nf > 0 then (Prim.geometry(poly)) else buffer.create(0)
|
|
local nslots = math.max(#slots, 1)
|
|
local groups: { [number]: { number } } = {}
|
|
local order: { number } = {}
|
|
for fi = 0, poly.nf - 1 do
|
|
local m = math.clamp(buffer.readi32(poly.faceMat, fi * 4), 0, nslots - 1)
|
|
local g = groups[m]
|
|
if not g then
|
|
g = {}
|
|
groups[m] = g
|
|
table.insert(order, m)
|
|
end
|
|
table.insert(g, fi)
|
|
end
|
|
table.sort(order)
|
|
local cornerColors: { MeshT.Color }, pointColors: { MeshT.Color } = {}, {}
|
|
for _, c in poly.colors do
|
|
table.insert(if c.domain == "corner" then cornerColors else pointColors, c)
|
|
end
|
|
local keyBytes = 4 + (if nrm then 12 else 0) + #poly.uvs * 8 + #cornerColors * 16
|
|
local scratch = buffer.create(keyBytes)
|
|
local mesh: Types.Mesh = { name = poly.name, primitives = {} }
|
|
local sources: { { number } } = {}
|
|
local cv = poly.cornerVert
|
|
for _, m in order do
|
|
local faces = groups[m]
|
|
local map: { [string]: number } = {}
|
|
local vsrc: { number } = {}
|
|
local corners: { number } = {} -- the first corner of each output vertex
|
|
local cornerOut = {} -- corner -> output vertex
|
|
for _, fi in faces do
|
|
local s0, s1 = face(poly, fi)
|
|
for c = s0, s1 - 1 do
|
|
local v = readu32(cv, c * 4)
|
|
buffer.writeu32(scratch, 0, v)
|
|
local o = 4
|
|
if nrm then
|
|
buffer.copy(scratch, o, nrm, c * 12, 12)
|
|
o += 12
|
|
end
|
|
for _, uv in poly.uvs do
|
|
buffer.copy(scratch, o, uv.data, c * 8, 8)
|
|
o += 8
|
|
end
|
|
for _, col in cornerColors do
|
|
buffer.copy(scratch, o, col.data, c * 16, 16)
|
|
o += 16
|
|
end
|
|
local key = buffer.readstring(scratch, 0, keyBytes)
|
|
local idx = map[key]
|
|
if not idx then
|
|
idx = #vsrc
|
|
map[key] = idx
|
|
table.insert(vsrc, v)
|
|
table.insert(corners, c)
|
|
end
|
|
cornerOut[c] = idx
|
|
end
|
|
end
|
|
local n = #vsrc
|
|
local attrs: { [string]: Types.Accessor } = {}
|
|
local P = buffer.create(n * 12)
|
|
for i = 1, n do
|
|
buffer.copy(P, (i - 1) * 12, poly.pos, vsrc[i] * 12, 12)
|
|
end
|
|
attrs.POSITION = Scene.accessor(P, "f32", 3, n)
|
|
if nrm then
|
|
local N = buffer.create(n * 12)
|
|
for i = 1, n do
|
|
buffer.copy(N, (i - 1) * 12, nrm, corners[i] * 12, 12)
|
|
end
|
|
attrs.NORMAL = Scene.accessor(N, "f32", 3, n)
|
|
end
|
|
for k, uv in poly.uvs do
|
|
local T = buffer.create(n * 8)
|
|
for i = 1, n do
|
|
local c = corners[i]
|
|
writef32(T, (i - 1) * 8, readf32(uv.data, c * 8))
|
|
local v = readf32(uv.data, c * 8 + 4)
|
|
writef32(T, (i - 1) * 8 + 4, if flipV then 1 - v else v)
|
|
end
|
|
local acc = Scene.accessor(T, "f32", 2, n)
|
|
acc.name = uv.name
|
|
attrs["TEXCOORD_" .. (k - 1)] = acc
|
|
end
|
|
local ci = 0
|
|
for _, col in poly.colors do
|
|
local C = buffer.create(n * 16)
|
|
for i = 1, n do
|
|
local e = if col.domain == "corner" then corners[i] else vsrc[i]
|
|
buffer.copy(C, (i - 1) * 16, col.data, e * 16, 16)
|
|
end
|
|
local acc = Scene.accessor(C, "f32", 4, n)
|
|
acc.name = col.name
|
|
attrs["COLOR_" .. ci] = acc
|
|
ci += 1
|
|
end
|
|
if skin and poly.weights then
|
|
local lists = table.create(n) :: { { number } }
|
|
for i = 1, n do
|
|
local src = poly.weights[vsrc[i] + 1] or {}
|
|
local l = {}
|
|
for k = 1, #src - 1, 2 do
|
|
local j = skin.joints[src[k]]
|
|
if j then
|
|
table.insert(l, j)
|
|
table.insert(l, src[k + 1])
|
|
end
|
|
end
|
|
lists[i] = l
|
|
end
|
|
attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists)
|
|
end
|
|
local prim: Types.Primitive = { attributes = attrs, mode = "triangles" }
|
|
local idx: { number } = {}
|
|
if triangulateOn then
|
|
for _, fi in faces do
|
|
local tri: { number } = {}
|
|
triangulate(poly, fi, readf32(fn, fi * 12), readf32(fn, fi * 12 + 4), readf32(fn, fi * 12 + 8), tri)
|
|
for _, c in tri do
|
|
table.insert(idx, cornerOut[c])
|
|
end
|
|
end
|
|
else
|
|
local sizes = buffer.create(#faces * 4)
|
|
for k, fi in faces do
|
|
local s0, s1 = face(poly, fi)
|
|
writeu32(sizes, (k - 1) * 4, s1 - s0)
|
|
for c = s0, s1 - 1 do
|
|
table.insert(idx, cornerOut[c])
|
|
end
|
|
end
|
|
prim.mode = "polygons"
|
|
prim.faces = Scene.accessor(sizes, "u32", 1, #faces)
|
|
end
|
|
local I = buffer.create(#idx * 4)
|
|
for k, v in idx do
|
|
writeu32(I, (k - 1) * 4, v)
|
|
end
|
|
prim.indices = Scene.accessor(I, "u32", 1, #idx)
|
|
local mat = slots[m + 1]
|
|
if mat and mat > 0 then
|
|
prim.material = mat
|
|
end
|
|
if shapes and ref and #shapes > 1 then
|
|
prim.targets = targetDeltas(poly, vsrc, shapes, ref, vgroups)
|
|
end
|
|
table.insert(mesh.primitives, prim)
|
|
table.insert(sources, vsrc)
|
|
end
|
|
if shapes and ref and #shapes > 1 then
|
|
local w = {}
|
|
for k, s in shapes do
|
|
if k ~= ref then
|
|
table.insert(w, if s.mute then 0 else s.value) -- Blender skips muted keys
|
|
end
|
|
end
|
|
mesh.weights = w
|
|
end
|
|
local usedSlots = {}
|
|
for _, m in order do
|
|
table.insert(usedSlots, m)
|
|
end
|
|
return { mesh = mesh, slots = usedSlots, vertexSource = sources }
|
|
end
|
|
|
|
return Prim
|