Files
rosetta/src/Rosetta/model/godot/Surface.luau
T
2026-11-01 19:25:15 -06:00

484 lines
15 KiB
Luau

--!strict
-- model/godot/Surface: ArrayMesh surfaces <-> Scene primitives. Godot 4.2+ surfaces (format version 2: vertex_data =
-- positions then octahedral normal / tangent pairs, attribute_data = colour / UV / UV2 / custom per vertex,
-- skin_data = bones + weights, index_data u16 / u32; RenderingServer mesh_create_surface_data_from_arrays), and the
-- "arrays" surfaces of format-2 .escn files (Godot 3 ArrayType order). Godot's front faces are clockwise: triangle
-- winding is reversed both ways. Not supported: compressed attributes, format version 1 (Godot 4.0 / 4.1), Godot 3
-- binary array_data, blend shapes (counted in extras).
local Types = require("@rosetta/Types")
local GodotVariant = require("@rosetta/codecs/text/GodotVariant")
local Primitives = require("@rosetta/model/godot/Primitives")
local Surface = {}
local S = Types.Scene
local function arr(n: number): { number }
return table.create(n) :: any
end
local function bit(f: number, i: number): boolean
return math.floor(f / 2 ^ i) % 2 == 1
end
-- Vector3::octahedron_decode
local function octDecode(x: number, y: number): (number, number, number)
local fx, fy = x * 2 - 1, y * 2 - 1
local nz = 1 - math.abs(fx) - math.abs(fy)
local t = math.clamp(-nz, 0, 1)
fx += if fx >= 0 then -t else t
fy += if fy >= 0 then -t else t
local l = math.sqrt(fx * fx + fy * fy + nz * nz)
if l == 0 then
return 0, 0, 1
end
return fx / l, fy / l, nz / l
end
-- Vector3::octahedron_encode
local function octEncode(x: number, y: number, z: number): (number, number)
local s = math.abs(x) + math.abs(y) + math.abs(z)
if s == 0 then
return 0.5, 0.5
end
x, y, z = x / s, y / s, z / s
local ox, oy
if z >= 0 then
ox, oy = x, y
else
ox = (1 - math.abs(y)) * (if x >= 0 then 1 else -1)
oy = (1 - math.abs(x)) * (if y >= 0 then 1 else -1)
end
return ox * 0.5 + 0.5, oy * 0.5 + 0.5
end
local function u16(v: number): number
return math.clamp(math.floor(v * 65535), 0, 65535)
end
local CUSTOM_SIZE = { [0] = 4, 4, 4, 8, 4, 8, 12, 16 }
export type Lists = {
points: { number },
normals: { number }?,
tangents: { number }?,
colors: buffer?,
uvs: { number }?,
uv2s: { number }?,
joints: { number }?,
weights: { number }?,
jointsPer: number,
indices: { number }?,
mode: string,
}
-- a Godot 4 surface dictionary (format version 2) into lists
local function binary(d: any, maxVertices: number): (Lists?, string?)
local f = tonumber(d.format) or 0
local vc = tonumber(d.vertex_count) or 0
if vc < 0 or vc > maxVertices or vc % 1 ~= 0 then
return nil, "limit: vertex count " .. tostring(d.vertex_count)
end
if bit(f, 29) then
return nil, "unsupported: compressed surface attributes"
end
if not bit(f, 35) then
return nil, "unsupported: surface format version 1 (Godot 4.0 / 4.1)"
end
local vd = GodotVariant.bytes(d.vertex_data)
if not vd then
return nil, "surface without vertex_data"
end
local is2D = bit(f, 25)
local pstride = if is2D then 8 else 12
local hasN, hasT = bit(f, 1), bit(f, 2)
local ntStride = (if hasN then 4 else 0) + (if hasT then 4 else 0)
if buffer.len(vd) < vc * (pstride + ntStride) then
return nil, "truncated vertex_data"
end
local L: Lists = { points = arr(vc * 3), jointsPer = 4, mode = "triangles" }
local P = L.points
for i = 0, vc - 1 do
local o = i * pstride
P[i * 3 + 1] = buffer.readf32(vd, o)
P[i * 3 + 2] = buffer.readf32(vd, o + 4)
P[i * 3 + 3] = if is2D then 0 else buffer.readf32(vd, o + 8)
end
if ntStride > 0 then
local base = vc * pstride
local N, T = if hasN then arr(vc * 3) else nil, if hasT then arr(vc * 4) else nil
for i = 0, vc - 1 do
local o = base + i * ntStride
if N then
local x, y, z = octDecode(buffer.readu16(vd, o) / 65535, buffer.readu16(vd, o + 2) / 65535)
N[i * 3 + 1], N[i * 3 + 2], N[i * 3 + 3] = x, y, z
o += 4
end
if T then
local tx = buffer.readu16(vd, o) / 65535
local ty = buffer.readu16(vd, o + 2) / 65535 * 2 - 1
local sign = if ty >= 0 then 1 else -1
local x, y, z = octDecode(tx, math.abs(ty))
T[i * 4 + 1], T[i * 4 + 2], T[i * 4 + 3], T[i * 4 + 4] = x, y, z, sign
end
end
L.normals, L.tangents = N, T
end
-- attribute stream
local hasC, hasUV, hasUV2 = bit(f, 3), bit(f, 4), bit(f, 5)
local astride = (if hasC then 4 else 0) + (if hasUV then 8 else 0) + (if hasUV2 then 8 else 0)
for k = 0, 3 do
if bit(f, 6 + k) then
astride += CUSTOM_SIZE[math.floor(f / 2 ^ (13 + 3 * k)) % 8]
end
end
if astride > 0 then
local ad = GodotVariant.bytes(d.attribute_data)
if not ad or buffer.len(ad) < vc * astride then
return nil, "truncated attribute_data"
end
local C = if hasC then buffer.create(vc * 4) else nil
local UV, UV2 = if hasUV then arr(vc * 2) else nil, if hasUV2 then arr(vc * 2) else nil
for i = 0, vc - 1 do
local o = i * astride
if C then
buffer.writeu32(C, i * 4, buffer.readu32(ad, o))
o += 4
end
if UV then
UV[i * 2 + 1], UV[i * 2 + 2] = buffer.readf32(ad, o), buffer.readf32(ad, o + 4)
o += 8
end
if UV2 then
UV2[i * 2 + 1], UV2[i * 2 + 2] = buffer.readf32(ad, o), buffer.readf32(ad, o + 4)
end
end
L.colors, L.uvs, L.uv2s = C, UV, UV2
end
-- skin stream: bones then weights per vertex
local hasB, hasW = bit(f, 10), bit(f, 11)
if hasB and hasW then
local per = if bit(f, 27) then 8 else 4
local sd = GodotVariant.bytes(d.skin_data)
if sd and buffer.len(sd) >= vc * per * 4 then
local J, W = arr(vc * per), arr(vc * per)
for i = 0, vc - 1 do
local o = i * per * 4
for c = 0, per - 1 do
J[i * per + c + 1] = buffer.readu16(sd, o + c * 2)
W[i * per + c + 1] = buffer.readu16(sd, o + per * 2 + c * 2) / 65535
end
end
L.joints, L.weights, L.jointsPer = J, W, per
end
end
local ic = tonumber(d.index_count) or 0
if bit(f, 12) and ic > 0 then
local id = GodotVariant.bytes(d.index_data)
local size = if vc <= 65536 then 2 else 4
if not id or buffer.len(id) < ic * size then
return nil, "truncated index_data"
end
local I = arr(ic)
for i = 0, ic - 1 do
local v = if size == 2 then buffer.readu16(id, i * 2) else buffer.readu32(id, i * 4)
if v >= vc then
return nil, "index out of range"
end
I[i + 1] = v
end
L.indices = I
end
local prim = tonumber(d.primitive) or 3
L.mode = if prim == 0 then "points" elseif prim == 1 then "lines" elseif prim == 2 then "line_strip" elseif prim == 4 then "triangle_strip" else "triangles"
return L, nil
end
local function nums(v: any): { number }?
return GodotVariant.numbers(v)
end
-- a format-2 "arrays" surface (Godot 3 Mesh::ArrayType: vertex, normal, tangent, color, uv, uv2, bones, weights, index)
local function arrays(d: any, maxVertices: number): (Lists?, string?)
local a = d.arrays
local P = nums(a[1])
if not P or #P % 3 ~= 0 then
return nil, "surface without a vertex array"
end
local vc = #P // 3
if vc > maxVertices then
return nil, "limit: vertex count " .. vc
end
local L: Lists = { points = P, jointsPer = 4, mode = "triangles" }
local N, T = nums(a[2]), nums(a[3])
L.normals = if N and #N == vc * 3 then N else nil
L.tangents = if T and #T == vc * 4 then T else nil
local C = nums(a[4])
if C and #C == vc * 4 then
local cb = buffer.create(vc * 4)
for i = 1, #C do
buffer.writeu8(cb, i - 1, math.clamp(math.floor(C[i] * 255 + 0.5), 0, 255))
end
L.colors = cb
end
local UV, UV2 = nums(a[5]), nums(a[6])
L.uvs = if UV and #UV == vc * 2 then UV else nil
L.uv2s = if UV2 and #UV2 == vc * 2 then UV2 else nil
local B, W = nums(a[7]), nums(a[8])
if B and W and #B == vc * 4 and #W == vc * 4 then
L.joints, L.weights = B, W
end
local I = nums(a[9])
if I and #I > 0 then
for _, v in I do
if v < 0 or v >= vc then
return nil, "index out of range"
end
end
L.indices = I
end
local prim = tonumber(d.primitive) or 4
L.mode = if prim == 0 then "points" elseif prim == 1 then "lines" elseif prim == 2 then "line_strip" elseif prim == 3 then "line_loop" elseif prim == 5 then "triangle_strip" elseif prim == 6 then "triangle_fan" else "triangles"
return L, nil
end
function Surface.lists(d: any, maxVertices: number): (Lists?, string?)
if type(d) ~= "table" then
return nil, "bad surface"
end
if type(d.arrays) == "table" then
return arrays(d, maxVertices)
end
if d.array_data ~= nil then
return nil, "unsupported: Godot 3 binary surface (array_data)"
end
return binary(d, maxVertices)
end
function Surface.fromPrimitiveArrays(a: Primitives.Arrays): Lists
return { points = a.points, normals = a.normals, tangents = a.tangents, uvs = a.uvs, indices = a.indices, jointsPer = 4, mode = "triangles" }
end
local function acc(list: { number }, comps: number, t: string?): Types.Accessor
local count = #list // comps
local typ = t or "f32"
local a = S.accessor(nil, typ :: any, comps, count)
local d = a.data
for i, v in list do
if typ == "f32" then
buffer.writef32(d, (i - 1) * 4, v)
elseif typ == "u16" then
buffer.writeu16(d, (i - 1) * 2, v)
end
end
return a
end
-- lists into a Primitive; triangles (and strips / fans, made into triangles) get counter-clockwise winding
function Surface.primitive(L: Lists): Types.Primitive
local n = #L.points // 3
local attrs: { [string]: Types.Accessor } = { POSITION = acc(L.points, 3) }
if L.normals then
attrs.NORMAL = acc(L.normals :: { number }, 3)
end
if L.tangents then
attrs.TANGENT = acc(L.tangents :: { number }, 4)
end
if L.colors then
attrs.COLOR_0 = S.accessor(L.colors, "unorm8", 4, n)
end
if L.uvs then
attrs.TEXCOORD_0 = acc(L.uvs :: { number }, 2)
end
if L.uv2s then
attrs.TEXCOORD_1 = acc(L.uv2s :: { number }, 2)
end
if L.joints and L.weights then
local per = L.jointsPer
for set = 0, per // 4 - 1 do
local J, W = arr(n * 4), arr(n * 4)
for i = 0, n - 1 do
for c = 0, 3 do
J[i * 4 + c + 1] = (L.joints :: { number })[i * per + set * 4 + c + 1] or 0
W[i * 4 + c + 1] = (L.weights :: { number })[i * per + set * 4 + c + 1] or 0
end
end
attrs["JOINTS_" .. set] = acc(J, 4, "u16")
attrs["WEIGHTS_" .. set] = acc(W, 4)
end
end
local mode = L.mode
local idx = L.indices
if mode == "triangles" or mode == "triangle_strip" or mode == "triangle_fan" then
local src: { number }
if idx then
src = idx
else
src = arr(n)
for i = 1, n do
src[i] = i - 1
end
end
local out: { number } = {}
if mode == "triangles" then
for k = 1, #src - 2, 3 do
table.insert(out, src[k])
table.insert(out, src[k + 2])
table.insert(out, src[k + 1])
end
elseif mode == "triangle_strip" then
for k = 1, #src - 2 do
local a, b, c = src[k], src[k + 1], src[k + 2]
if k % 2 == 0 then
a, b = b, a
end
table.insert(out, a)
table.insert(out, c)
table.insert(out, b)
end
else
for k = 2, #src - 1 do
table.insert(out, src[1])
table.insert(out, src[k + 1])
table.insert(out, src[k])
end
end
idx = out
mode = "triangles"
end
local prim: Types.Primitive = { attributes = attrs, mode = mode :: any }
if idx then
prim.indices = acc(idx :: { number }, 1, "u32")
local d = (prim.indices :: Types.Accessor).data
for i, v in idx :: { number } do
buffer.writeu32(d, (i - 1) * 4, v)
end
end
return prim
end
-- ------------------------------------------------------------------------------------------------ write
local function perpendicular(x: number, y: number, z: number): (number, number, number)
local ax, ay, az = if math.abs(y) < 0.9 then 0 else 1, if math.abs(y) < 0.9 then 1 else 0, 0
local tx, ty, tz = ay * z - az * y, az * x - ax * z, ax * y - ay * x
local l = math.sqrt(tx * tx + ty * ty + tz * tz)
if l == 0 then
return 1, 0, 0
end
return tx / l, ty / l, tz / l
end
-- a triangle Primitive as a Godot 4 surface dictionary (format version 2, uncompressed); nil for other modes
function Surface.encode(prim: Types.Primitive, triangles: { number }): any
local a = prim.attributes
local pos = a.POSITION
local rp = S.reader(pos)
if not rp then
return nil
end
local vc = pos.count
local an: any, at: any, ac: any, a0: any, a1: any = a.NORMAL, a.TANGENT, a.COLOR_0, a.TEXCOORD_0, a.TEXCOORD_1
local rn = if an then S.reader(an) else nil
local rt = if at then S.reader(at) else nil
local rc = if ac then S.reader(ac) else nil
local cc = if ac then ac.components else 0
local ru = if a0 then S.reader(a0) else nil
local ru2 = if a1 then S.reader(a1) else nil
local flags = 1 + 2 ^ 35
if rn then
flags += 2 + 4
end
local ntStride = if rn then 8 else 0
local vd = buffer.create(vc * (12 + ntStride))
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
for i = 0, vc - 1 do
for c = 0, 2 do
local v = rp(i, c)
buffer.writef32(vd, i * 12 + c * 4, v)
lo[c + 1], hi[c + 1] = math.min(lo[c + 1], v), math.max(hi[c + 1], v)
end
if rn then
local nx, ny, nz = rn(i, 0), rn(i, 1), rn(i, 2)
local o = vc * 12 + i * 8
local ox, oy = octEncode(nx, ny, nz)
buffer.writeu16(vd, o, u16(ox))
buffer.writeu16(vd, o + 2, u16(oy))
local tx, ty, tz, sign
if rt then
tx, ty, tz, sign = rt(i, 0), rt(i, 1), rt(i, 2), if at.components >= 4 then rt(i, 3) else 1
else
tx, ty, tz = perpendicular(nx, ny, nz)
sign = 1
end
-- Vector3::octahedron_tangent_encode
local qx, qy = octEncode(tx, ty, tz)
qy = math.max(qy, 1 / 32767) * 0.5 + 0.5
qy = if sign >= 0 then qy else 1 - qy
buffer.writeu16(vd, o + 4, u16(qx))
buffer.writeu16(vd, o + 6, u16(qy))
end
end
local astride = (if rc then 4 else 0) + (if ru then 8 else 0) + (if ru2 then 8 else 0)
local ad: buffer? = nil
if astride > 0 then
flags += (if rc then 8 else 0) + (if ru then 16 else 0) + (if ru2 then 32 else 0)
local b = buffer.create(vc * astride)
for i = 0, vc - 1 do
local o = i * astride
if rc then
for c = 0, 3 do
local v = if c < cc then rc(i, c) else 1
buffer.writeu8(b, o + c, math.clamp(math.floor(v * 255 + 0.5), 0, 255))
end
o += 4
end
if ru then
buffer.writef32(b, o, ru(i, 0))
buffer.writef32(b, o + 4, ru(i, 1))
o += 8
end
if ru2 then
buffer.writef32(b, o, ru2(i, 0))
buffer.writef32(b, o + 4, ru2(i, 1))
end
end
ad = b
end
local isize = if vc <= 65536 then 2 else 4
local id = buffer.create(#triangles * isize)
-- counter-clockwise -> Godot's clockwise
for k = 0, #triangles // 3 - 1 do
local t = { triangles[k * 3 + 1], triangles[k * 3 + 3], triangles[k * 3 + 2] }
for c = 0, 2 do
if isize == 2 then
buffer.writeu16(id, (k * 3 + c) * 2, t[c + 1])
else
buffer.writeu32(id, (k * 3 + c) * 4, t[c + 1])
end
end
end
flags += 4096
if vc == 0 then
lo, hi = { 0, 0, 0 }, { 0, 0, 0 }
end
local keys = { "aabb" }
local out: { [string]: any } = { aabb = GodotVariant.ctor("AABB", { lo[1], lo[2], lo[3], hi[1] - lo[1], hi[2] - lo[2], hi[3] - lo[3] }) }
if ad then
out.attribute_data = ad
table.insert(keys, "attribute_data")
end
out.format = flags
out.index_count = #triangles
out.index_data = id
out.primitive = 3
out.uv_scale = GodotVariant.ctor("Vector4", { 0, 0, 0, 0 })
out.vertex_count = vc
out.vertex_data = vd
for _, k in { "format", "index_count", "index_data", "material", "primitive", "uv_scale", "vertex_count", "vertex_data" } do
table.insert(keys, k)
end
return Types.object(out, keys)
end
return Surface