comments: ops MeshOps

This commit is contained in:
4DBug committed 2026-11-01 01:57:14 -05:00
1 parent fcf8aedb99
commit fd606b8225
1 file changed
+7 -60
+7 -60
View File
@@ -1,16 +1,7 @@
--!strict
-- ops/MeshOps: editing meshes in the standard Scene type (Types.luau): triangulate (strips, fans, n-gons by fan or ear
-- clipping), transform (positions, normals, tangents; winding kept for mirrors), computeNormals (area weighted, or flat),
-- computeTangents (per-triangle UV derivatives, Lengyel 2001, Gram-Schmidt + handedness in w), weld (exact or within an
-- epsilon), bounds, merge (a whole scene baked into world space, one primitive or one per material), unit and up-axis
-- changes, and greedy meshing of voxel grids (VOX: voxelsToPrimitive, meshVoxels).
-- Every function takes / returns Primitives and Scenes as decoded by the model formats; inputs may use any accessor type
-- (f32, unorm8, snorm16, ...): outputs are f32 attributes and u32 indices. Bad arguments return nil, Err (never throw).
--
-- local MeshOps = require("@rosetta/ops/MeshOps") -- F.ops.mesh in the api (when it lists ops)
-- local prim = MeshOps.merge(scene) -- one triangle primitive in world space
-- MeshOps.computeNormals(prim)
-- MeshOps.meshVoxels(voxScene) -- greedy meshes for every voxel shape
-- ops/MeshOps: editing meshes in the standard Scene type: triangulate, transform, normals (area weighted or flat),
-- tangents (Lengyel 2001), weld, bounds, merge into world space, unit / up-axis changes, greedy voxel meshing. Inputs
-- may use any accessor type; outputs are f32 attributes and u32 indices. Never throws.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Greedy = require("@rosetta/ops/MeshOps/Greedy")
@@ -25,8 +16,6 @@ local Scene = Types.Scene
local readf32, writef32 = buffer.readf32, buffer.writef32
local readu32, writeu32 = buffer.readu32, buffer.writeu32
-- ------------------------------------------------------------------------------------------------ accessors
-- f32(acc) -> the accessor as f32 (the same accessor when it already is), nil for a broken one
function MeshOps.f32(acc: Accessor): Accessor?
if acc.type == "f32" then
return acc
@@ -47,7 +36,6 @@ function MeshOps.f32(acc: Accessor): Accessor?
return a
end
-- the index list of a primitive (u32 buffer, count): its indices, or 0 .. n - 1
local function indexBuffer(prim: Primitive): (buffer, number)
local ind = prim.indices
if ind then
@@ -114,7 +102,6 @@ local function checkPrim(prim: any): Err.Err?
end
MeshOps.check = checkPrim
-- ------------------------------------------------------------------------------------------------ triangulate
-- ear clipping of one polygon (corner indices into px / py / pz) -> triangles appended to out; fan when it gets stuck
local function earclip(poly: { number }, P: (number, number) -> number, out: { number })
local k = #poly
@@ -206,9 +193,7 @@ local function u32(list: { number }): Accessor
return Scene.accessor(b, "u32", 1, n)
end
-- triangulate(prim, opts?) -> a new triangle Primitive (the same attributes) | nil, Err. opts.method: "earclip"
-- (default; handles concave n-gons) or "fan". Strips and fans are unrolled (strip winding alternates as glTF says).
-- Lines and points come back unchanged.
-- strips and fans unroll with glTF's alternating strip winding
function MeshOps.triangulate(prim: Primitive, opts: { method: string? }?): (Primitive?, Err.Err?)
local err = checkPrim(prim)
if err then
@@ -294,7 +279,6 @@ function MeshOps.triangulate(prim: Primitive, opts: { method: string? }?): (Prim
}, nil
end
-- ------------------------------------------------------------------------------------------------ transform
local function det3(m: { number }): number
return m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3])
end
@@ -317,8 +301,7 @@ local function normalMatrix(m: { number }): { number }
}
end
-- transform(prim, matrix) -> prim (changed in place: POSITION, NORMAL, TANGENT become f32; morph target deltas too).
-- A mirroring matrix (negative determinant) also reverses the triangle winding so faces stay front-facing.
-- a mirroring matrix (negative determinant) reverses the winding so faces stay front-facing
function MeshOps.transform(prim: Primitive, m: { number }): (Primitive?, Err.Err?)
local err = checkPrim(prim)
if err then
@@ -423,10 +406,6 @@ function MeshOps.transform(prim: Primitive, m: { number }): (Primitive?, Err.Err
return prim, nil
end
-- ------------------------------------------------------------------------------------------------ normals / tangents
-- computeNormals(prim, opts?) -> prim with NORMAL (f32, area-weighted average of the triangle normals of each vertex) |
-- nil, Err. opts.flat = true: split every triangle's corners first (unwelded, one face normal per corner). Non-triangle
-- modes are triangulated first (the returned primitive is then a new one).
function MeshOps.computeNormals(prim: Primitive, opts: { flat: boolean? }?): (Primitive?, Err.Err?)
local p = prim
if (prim.mode or "triangles") ~= "triangles" then
@@ -482,8 +461,7 @@ function MeshOps.computeNormals(prim: Primitive, opts: { flat: boolean? }?): (Pr
return p, nil
end
-- computeTangents(prim, opts?) -> prim with TANGENT (f32 vec4: xyz orthogonal to the normal, w = +-1 handedness) |
-- nil, Err. Needs triangles, NORMAL (computed when missing) and TEXCOORD_<opts.texCoord or 0>.
-- TANGENT: f32 vec4, xyz orthogonal to the normal, w = +-1 handedness
function MeshOps.computeTangents(prim: Primitive, opts: { texCoord: number? }?): (Primitive?, Err.Err?)
local p = prim
if not p.attributes.NORMAL or (p.mode or "triangles") ~= "triangles" then
@@ -565,7 +543,6 @@ function MeshOps.computeTangents(prim: Primitive, opts: { texCoord: number? }?):
return p, nil
end
-- ------------------------------------------------------------------------------------------------ weld / unweld
local function gather(acc: Accessor, ib: buffer, n: number): Accessor
local size = (Types.COMPONENT_SIZE[acc.type] or 4) * acc.components
local out = buffer.create(n * size)
@@ -577,7 +554,6 @@ local function gather(acc: Accessor, ib: buffer, n: number): Accessor
return a
end
-- unweld(prim) -> a new primitive with one vertex per index (no indices; triangle soups, flat normals)
function MeshOps.unweld(prim: Primitive): Primitive
local ib, n = indexBuffer(prim)
local attrs = {}
@@ -598,10 +574,6 @@ function MeshOps.unweld(prim: Primitive): Primitive
return { attributes = attrs, indices = nil, mode = prim.mode, faces = prim.faces, material = prim.material, targets = targets, extras = prim.extras }
end
-- weld(prim, opts?) -> a new indexed primitive where vertices with identical attributes are one | nil, Err.
-- opts.epsilon > 0: positions within epsilon (on a grid of that size) merge too, keeping the first vertex's other
-- attributes only when they are equal (opts.positionsOnly = true merges by position alone, keeping the first vertex).
-- Morph targets are kept per merged vertex (the first one's).
function MeshOps.weld(prim: Primitive, opts: { epsilon: number?, positionsOnly: boolean? }?): (Primitive?, Err.Err?)
local err = checkPrim(prim)
if err then
@@ -680,9 +652,6 @@ function MeshOps.weld(prim: Primitive, opts: { epsilon: number?, positionsOnly:
}, nil
end
-- ------------------------------------------------------------------------------------------------ bounds
-- bounds(primitive | scene) -> min { x, y, z }, max { x, y, z } (a scene: in world space, every mesh primitive and
-- voxel shape cell corners excluded) | nil, nil when there are no positions
function MeshOps.bounds(x: any): ({ number }?, { number }?)
local lo = { math.huge, math.huge, math.huge }
local hi = { -math.huge, -math.huge, -math.huge }
@@ -736,7 +705,6 @@ function MeshOps.bounds(x: any): ({ number }?, { number }?)
return lo, hi
end
-- ------------------------------------------------------------------------------------------------ merge
-- the value of an attribute nobody had (COLOR_n white, WEIGHTS_0 { 1, 0, 0, 0 }, the rest zero)
local function defaultFor(name: string, k: number): number
if string.sub(name, 1, 6) == "COLOR_" then
@@ -748,11 +716,6 @@ local function defaultFor(name: string, k: number): number
return 0
end
-- merge(scene | { Primitive }, opts?) -> one triangle Primitive with every mesh primitive baked into world space |
-- { Primitive } with opts.byMaterial (one per material, in material order) | nil, Err. Attributes present in any input
-- appear in the output (f32; missing ones filled with defaults: white colours, zeros); custom "_x" attributes too.
-- Lines and points are skipped (opts.keepPoints = true keeps a point-only input as points). Skins and morph targets
-- are not applied (the rest pose).
function MeshOps.merge(input: any, opts: { byMaterial: boolean?, method: string? }?): (any, Err.Err?)
local placed: { Types.Placed } = {}
if type(input) ~= "table" then
@@ -765,7 +728,6 @@ function MeshOps.merge(input: any, opts: { byMaterial: boolean?, method: string?
placed[i] = { primitive = p, matrix = Scene.IDENTITY, node = 0, mesh = 0 }
end
end
-- triangulate + bake each
local groups: { [number]: { Primitive } } = {}
local order: { number } = {}
local allPoints = #placed > 0
@@ -861,7 +823,6 @@ function MeshOps.merge(input: any, opts: { byMaterial: boolean?, method: string?
return concat(all, first and first.material), nil
end
-- ------------------------------------------------------------------------------------------------ units / up axis
local function scaleAccessor(acc: Accessor?, f: number): Accessor?
if not acc then
return nil
@@ -877,9 +838,6 @@ local function scaleAccessor(acc: Accessor?, f: number): Accessor?
return a
end
-- scale(scene, factor) -> scene, scaled in place: mesh positions and morph target deltas, node translations (TRS and
-- matrices), translation animations, inverse bind matrices, camera clip planes, light ranges; meta.unit is divided by
-- factor (the same physical size in smaller units).
function MeshOps.scale(scene: Scene, f: number): (Scene?, Err.Err?)
if type(scene) ~= "table" or scene.kind ~= "scene" or type(f) ~= "number" or f ~= f or f == 0 then
return nil, Err.new(Err.ARG, "scale: expected a Scene and a non-zero factor")
@@ -956,7 +914,6 @@ function MeshOps.scale(scene: Scene, f: number): (Scene?, Err.Err?)
return scene, nil
end
-- setUnit(scene, metresPerUnit) -> scene scaled so that one unit is metresPerUnit (from meta.unit, default 1 m)
function MeshOps.setUnit(scene: Scene, metresPerUnit: number): (Scene?, Err.Err?)
if type(scene) ~= "table" or type(metresPerUnit) ~= "number" or metresPerUnit <= 0 then
return nil, Err.new(Err.ARG, "setUnit: expected a Scene and a positive unit")
@@ -965,8 +922,6 @@ function MeshOps.setUnit(scene: Scene, metresPerUnit: number): (Scene?, Err.Err?
return MeshOps.scale(scene, from / metresPerUnit)
end
-- setUp(scene, "y" | "z") -> scene with a new root node rotating the old roots from meta.up (default "y") to up.
-- Nothing is baked: the vertex data stays as it is (MeshOps.merge bakes it).
function MeshOps.setUp(scene: Scene, up: string): (Scene?, Err.Err?)
if type(scene) ~= "table" or scene.kind ~= "scene" or (up ~= "y" and up ~= "z") then
return nil, Err.new(Err.ARG, "setUp: expected a Scene and \"y\" or \"z\"")
@@ -984,17 +939,12 @@ function MeshOps.setUp(scene: Scene, up: string): (Scene?, Err.Err?)
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ voxels
local function linear(c: number): number
local s = c / 255
return if s <= 0.04045 then s / 12.92 else ((s + 0.055) / 1.055) ^ 2.4
end
-- voxelsToPrimitive(voxels, opts?) -> a triangle Primitive of the grid's visible faces, greedily merged (POSITION,
-- NORMAL f32; COLOR_0 from the palette; u32 indices) | nil, Err.
-- opts.pivot: "center" (default: MagicaVoxel's placement, cell x spans x - floor(sx / 2) ..) or "corner" (0 .. sx);
-- opts.scale: units per voxel (default 1); opts.colors: "linear" (default: f32 linear RGBA, glTF's COLOR_0 meaning) or
-- "srgb" (unorm8, the palette bytes as they are); opts.indexAttribute = true adds "_PALETTE_INDEX" (u8 per vertex).
-- pivot "center": MagicaVoxel's placement (cell x spans x - floor(sx / 2) ..)
function MeshOps.voxelsToPrimitive(v: Types.Voxels, opts: { pivot: string?, scale: number?, colors: string?, indexAttribute: boolean? }?): (Primitive?, Err.Err?)
if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then
return nil, Err.new(Err.ARG, "expected a Voxels grid")
@@ -1051,9 +1001,6 @@ function MeshOps.voxelsToPrimitive(v: Types.Voxels, opts: { pivot: string?, scal
return { attributes = attrs, indices = Scene.accessor(trim(g.indices, g.quads * 24), "u32", 1, g.quads * 6), mode = "triangles" }, nil
end
-- meshVoxels(scene, opts?) -> scene with a mesh for every voxel grid (scene.voxels) and node.mesh set on every node
-- that shows one (node.voxels); one shared material (white, rough, not metallic: the colours are per vertex). Options as
-- voxelsToPrimitive. Each call adds new meshes (call it once per scene, after editing the grids).
function MeshOps.meshVoxels(scene: Scene, opts: { pivot: string?, scale: number?, colors: string?, indexAttribute: boolean? }?): (Scene?, Err.Err?)
if type(scene) ~= "table" or scene.kind ~= "scene" then
return nil, Err.new(Err.ARG, "expected a Scene")