codecs/model: comments to specs only
This commit is contained in:
1 parent
0bd7b87d2b
commit
9b6a205844
26 files changed
+134
-571
No files matched your search
+7
-7
@@ -246,14 +246,14 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
|
||||
- codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or
|
||||
- **model**
|
||||
- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7).
|
||||
- codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16
|
||||
- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks
|
||||
- codecs/model/Mat4: 4x4 matrix (column-major, glTF / Types.Scene layout) and quaternion { x, y, z, w } helpers.
|
||||
- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF).
|
||||
- codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code.
|
||||
- codecs/model/Polygon: 2D polygons with holes to triangles, for formats that store regions as outlines (Doom map
|
||||
- codecs/model/Rbx: the Roblox instance tree every Roblox file format maps to (model/rbxm binary rbxm / rbxl,
|
||||
- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each
|
||||
- codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for
|
||||
- codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML,
|
||||
- codecs/model/Polygon: 2D polygons with holes to triangles by hole bridging and ear clipping. New code.
|
||||
- codecs/model/Rbx: the Roblox instance tree and property values shared by model/rbxm and model/rbxmx.
|
||||
- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...). New code.
|
||||
- codecs/model/Sampler: Scene animation sampling, STEP / LINEAR (slerp) / CUBICSPLINE as in glTF 2.0 3.11. New code.
|
||||
- codecs/model/Vrml: VRML97 / X3D scene-graph engine (classic and XML encodings) for model/vrml and model/x3d.
|
||||
- **text**
|
||||
- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
|
||||
- codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt,
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco/Attributes: Draco attribute decoding. The attributes decoders (one per connectivity: linear
|
||||
-- sequencer for sequential meshes and point clouds, traversal sequencers for Edgebreaker), their attribute
|
||||
-- descriptors, and the sequential attribute decoders: generic (raw values), integer, quantization (dequantized to
|
||||
-- f32 exactly like the C++) and octahedral normals; prediction through codecs/model/Draco/Predict. Bitstream
|
||||
-- versions 1.0 - 2.2. Ported from Google's Draco 1.5.7 (compression/attributes/*, compression/point_cloud/
|
||||
-- point_cloud_decoder.cc, attributes/attribute_quantization_transform.cc, attribute_octahedron_transform.cc;
|
||||
-- Apache-2.0, licenses/draco-LICENSE.txt).
|
||||
-- codecs/model/Draco/Attributes: Draco attribute decoders and sequential attribute decoding (bitstreams 1.0 - 2.2).
|
||||
-- Port of Draco 1.5.7 compression/attributes/*, point_cloud_decoder.cc, attribute_quantization_transform.cc and
|
||||
-- attribute_octahedron_transform.cc (Apache-2.0, licenses/draco-LICENSE.txt).
|
||||
local Reader = require("@rosetta/codecs/model/Draco/Reader")
|
||||
local Connectivity = require("@rosetta/codecs/model/Draco/Connectivity")
|
||||
local Predict = require("@rosetta/codecs/model/Draco/Predict")
|
||||
@@ -20,18 +16,18 @@ local DT_LENGTH = { [1] = 1, [2] = 1, [3] = 2, [4] = 2, [5] = 4, [6] = 4, [7] =
|
||||
Attributes.DT_LENGTH = DT_LENGTH
|
||||
|
||||
export type Attr = {
|
||||
id: number, -- 0-based attribute id
|
||||
id: number,
|
||||
type: number, -- GeometryAttribute::Type (0 POSITION, 1 NORMAL, 2 COLOR, 3 TEX_COORD, 4 GENERIC, 5.. transcoder types)
|
||||
dataType: number,
|
||||
comps: number,
|
||||
normalized: boolean,
|
||||
uniqueId: number,
|
||||
seqType: number, -- 0 generic, 1 integer, 2 quantization, 3 normals
|
||||
map: { number }?, -- point -> value (0-based values at [point + 1]); nil = identity
|
||||
map: { number }?,
|
||||
numValues: number,
|
||||
portable: { number }?, -- the integer (portable) values
|
||||
values: { number }?, -- the final values (numbers), flat
|
||||
raw: buffer?, -- generic attributes: the raw values
|
||||
portable: { number }?,
|
||||
values: { number }?,
|
||||
raw: buffer?,
|
||||
quant: { min: { number }, range: number, bits: number }?,
|
||||
octBits: number?,
|
||||
scheme: Predict.Scheme?,
|
||||
@@ -44,7 +40,6 @@ type Decoder = {
|
||||
points: { number }?,
|
||||
}
|
||||
|
||||
-- the geometry the attributes decode against
|
||||
export type Geom = { numPoints: number, mesh: Connectivity.Mesh?, edgebreaker: boolean, kdTree: boolean }
|
||||
|
||||
local function zigzag(v: number): number
|
||||
@@ -54,8 +49,7 @@ local function zigzag(v: number): number
|
||||
return v // 2
|
||||
end
|
||||
|
||||
-- the parent (position) getter for a scheme: portable integers from 2.0 on, the final values before (truncated to
|
||||
-- integers unless the scheme works in floats)
|
||||
-- parent getter: portable integers from 2.0 on, the final values before (truncated unless the scheme uses floats)
|
||||
local function parentGetter(ver: number, pos: Attr, floats: boolean): Predict.Parent?
|
||||
local old = ver < 0x0200
|
||||
local vals = if old then pos.values else pos.portable
|
||||
@@ -228,7 +222,6 @@ local function storeValues(a: Attr): (boolean, string?)
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- decodes every attribute; returns them in attribute id order
|
||||
function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?)
|
||||
local ver = d.ver
|
||||
local numDecoders = Reader.u8(d)
|
||||
@@ -283,13 +276,11 @@ function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?)
|
||||
enc = cad.enc
|
||||
dec.traversal = { ct = cad.ct :: Connectivity.CT, enc = enc, method = 0 }
|
||||
end
|
||||
-- prediction data: the attribute's own corner table when its seams are in use
|
||||
local pct = if ad and ad.used then ad.ct :: Connectivity.CT else ct
|
||||
dec.md = { ct = pct, e2c = enc.e2c, v2e = enc.v2e }
|
||||
end
|
||||
decoders[i + 1] = dec
|
||||
end
|
||||
-- the attribute descriptors
|
||||
local all: { Attr } = {}
|
||||
for _, dec in decoders do
|
||||
local n = Reader.count(d, 0x0200)
|
||||
@@ -350,7 +341,6 @@ function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
-- decode
|
||||
for _, dec in decoders do
|
||||
if g.kdTree then
|
||||
local ok, err = KdTree.decode(d, dec.attrs, g.numPoints)
|
||||
@@ -383,7 +373,6 @@ function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?)
|
||||
end
|
||||
end
|
||||
dec.points = points
|
||||
-- portable values
|
||||
for _, a in dec.attrs do
|
||||
if a.seqType == 0 then
|
||||
local stride = DT_LENGTH[a.dataType] * a.comps
|
||||
@@ -449,7 +438,6 @@ function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?)
|
||||
end
|
||||
end
|
||||
end
|
||||
-- data needed by the transforms
|
||||
if ver >= 0x0200 then
|
||||
for _, a in dec.attrs do
|
||||
if a.seqType == 2 then
|
||||
|
||||
@@ -1,27 +1,21 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco/Connectivity: Draco mesh connectivity. The sequential decoder (raw or rANS delta-coded indices)
|
||||
-- and the Edgebreaker decoder (standard, predictive and valence traversals, topology splits, start faces, attribute
|
||||
-- seams), the corner tables they build (the mesh's and one per attribute seam set), and the traversal sequencers
|
||||
-- (depth first and max prediction degree) that order attribute values. Ported from Google's Draco 1.5.7
|
||||
-- (compression/mesh/mesh_sequential_decoder.cc, mesh_edgebreaker_decoder_impl.cc, mesh_edgebreaker_traversal_*,
|
||||
-- mesh/corner_table, mesh/mesh_attribute_corner_table, compression/mesh/traverser/*; Apache-2.0,
|
||||
-- licenses/draco-LICENSE.txt). Corners, vertices and faces are 0-based values stored at [i + 1]; -1 is invalid.
|
||||
-- codecs/model/Draco/Connectivity: Draco mesh connectivity (sequential and Edgebreaker) and traversal sequencers.
|
||||
-- Port of Draco 1.5.7 mesh_sequential_decoder.cc, mesh_edgebreaker_decoder_impl.cc, mesh_edgebreaker_traversal_*,
|
||||
-- corner_table, mesh_attribute_corner_table, traverser/* (Apache-2.0, licenses/draco-LICENSE.txt).
|
||||
local Reader = require("@rosetta/codecs/model/Draco/Reader")
|
||||
|
||||
local Connectivity = {}
|
||||
|
||||
type D = Reader.D
|
||||
|
||||
-- a corner table: corner -> vertex, corner -> opposite corner, vertex -> left-most corner
|
||||
export type CT = { c2v: { number }, opp: { number }, lmc: { number }, nv: number, nf: number }
|
||||
-- encoding data of one attribute connectivity: vertex -> value index, value index -> corner
|
||||
export type Enc = { v2e: { number }, e2c: { number }, numValues: number }
|
||||
export type AttrData = { decoderId: number, used: boolean, seams: { number }, ct: CT?, enc: Enc }
|
||||
export type Mesh = {
|
||||
faces: { number }, -- corner -> point
|
||||
faces: { number },
|
||||
numFaces: number,
|
||||
numPoints: number,
|
||||
ct: CT?, -- Edgebreaker only
|
||||
ct: CT?,
|
||||
attrData: { AttrData },
|
||||
posEnc: Enc?,
|
||||
posDecoderId: number,
|
||||
@@ -49,7 +43,6 @@ local function newEnc(nv: number): Enc
|
||||
return { v2e = table.create(nv, 0), e2c = {}, numValues = 0 }
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sequential
|
||||
function Connectivity.sequential(d: D): (Mesh?, string?)
|
||||
local numFaces, numPoints
|
||||
if d.ver < 0x0202 then
|
||||
@@ -124,8 +117,6 @@ function Connectivity.sequential(d: D): (Mesh?, string?)
|
||||
return { faces = faces, numFaces = numFaces, numPoints = numPoints, ct = nil, attrData = {}, posEnc = nil, posDecoderId = -1 }, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ edgebreaker
|
||||
-- the traversal decoders: symbols, start face configurations, attribute seam bits
|
||||
type Trav = {
|
||||
decodeSymbol: () -> number,
|
||||
newActiveCorner: (corner: number) -> (),
|
||||
@@ -134,8 +125,7 @@ type Trav = {
|
||||
seam: (i: number) -> boolean,
|
||||
}
|
||||
|
||||
-- MeshEdgebreakerTraversalDecoder::Start (the standard parts): symbols (bits), start faces, seam decoders.
|
||||
-- Returns the decoder state and the buffer after them.
|
||||
-- MeshEdgebreakerTraversalDecoder::Start
|
||||
local function standardStart(buf: D, numAttributeData: number, withSymbols: boolean): (any?, D)
|
||||
local st: any = {}
|
||||
if withSymbols then
|
||||
@@ -195,7 +185,7 @@ local function standardSymbol(sym: D): number
|
||||
return s + Reader.bits(sym, 2) * 2
|
||||
end
|
||||
|
||||
-- builds the traversal decoder for `kind` (0 standard, 1 predictive, 2 valence); returns it and the buffer after its data
|
||||
-- traversal decoder kind: 0 standard, 1 predictive, 2 valence
|
||||
local function makeTraversal(kind: number, buf: D, numAttributeData: number, numVertices: number, numFaces: number, ct: CT): (Trav?, D)
|
||||
local ver = buf.ver
|
||||
local st, out = standardStart(buf, numAttributeData, kind ~= 2 or ver < 0x0202)
|
||||
@@ -372,7 +362,6 @@ local function makeTraversal(kind: number, buf: D, numAttributeData: number, num
|
||||
}, out
|
||||
end
|
||||
|
||||
-- hole and topology split events; returns the split stack (source / split symbol ids, edges) or nil
|
||||
local function splitEvents(eb: D, numFaces: number): { any }?
|
||||
local ver = eb.ver
|
||||
local n = Reader.count(eb, 0x0200)
|
||||
@@ -559,7 +548,6 @@ function Connectivity.edgebreaker(d: D, traversalKind: number): (Mesh?, string?)
|
||||
end
|
||||
local maxVertices = numEncodedVertices + numSplitSymbols
|
||||
|
||||
-- the corner table (filled lazily: nil = invalid)
|
||||
local c2v: { number } = {}
|
||||
local opp: { number } = {}
|
||||
local lmc: { number } = {}
|
||||
@@ -630,7 +618,6 @@ function Connectivity.edgebreaker(d: D, traversalKind: number): (Mesh?, string?)
|
||||
return prevC(O(prevC(c)))
|
||||
end
|
||||
|
||||
-- the symbols
|
||||
local stack: { number } = {}
|
||||
local sp = 0
|
||||
local splitActive: { [number]: number } = {}
|
||||
@@ -869,7 +856,6 @@ function Connectivity.edgebreaker(d: D, traversalKind: number): (Mesh?, string?)
|
||||
d.pos += splitBytes
|
||||
end
|
||||
|
||||
-- attribute seams
|
||||
local attrData: { AttrData } = {}
|
||||
for i = 1, numAttributeData do
|
||||
attrData[i] = { decoderId = -1, used = true, seams = {}, ct = nil, enc = newEnc(0) }
|
||||
@@ -990,9 +976,7 @@ function Connectivity.edgebreaker(d: D, traversalKind: number): (Mesh?, string?)
|
||||
}, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ traversal
|
||||
-- MeshTraversalSequencer::GenerateSequence: the point ids in value order; fills enc (v2e, e2c, numValues).
|
||||
-- method 0 = depth first, 1 = max prediction degree.
|
||||
-- MeshTraversalSequencer::GenerateSequence: method 0 depth first, 1 max prediction degree
|
||||
function Connectivity.traverse(ct: CT, faces: { number }, enc: Enc, method: number): { number }?
|
||||
local c2v, opp, lmc = ct.c2v, ct.opp, ct.lmc
|
||||
local nf, nvt = ct.nf, ct.nv
|
||||
@@ -1093,7 +1077,6 @@ function Connectivity.traverse(ct: CT, faces: { number }, enc: Enc, method: numb
|
||||
end
|
||||
return points
|
||||
end
|
||||
-- max prediction degree
|
||||
if nvt == 0 then
|
||||
return points
|
||||
end
|
||||
@@ -1182,7 +1165,7 @@ function Connectivity.traverse(ct: CT, faces: { number }, enc: Enc, method: numb
|
||||
return points
|
||||
end
|
||||
|
||||
-- MeshTraversalSequencer::UpdatePointToAttributeIndexMapping: point -> value index (1-based table of 0-based values)
|
||||
-- MeshTraversalSequencer::UpdatePointToAttributeIndexMapping
|
||||
function Connectivity.mapping(ct: CT, faces: { number }, enc: Enc, numPoints: number): { number }?
|
||||
local map = table.create(numPoints, 0)
|
||||
local c2v, v2e = ct.c2v, enc.v2e
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco/Int64: the 64-bit integer arithmetic Draco's portable tex coord predictor relies on (int64 /
|
||||
-- uint64 with wrap-around, truncating division, IntSqrt), on (hi, lo) pairs of 32-bit halves held in numbers (both
|
||||
-- runtimes: no native 64-bit integers). Two's complement: hi >= 2^31 is negative when read as signed.
|
||||
-- codecs/model/Draco/Int64: wrap-around int64 / uint64 for Draco's portable tex coord predictor.
|
||||
-- Values are (hi, lo) 32-bit halves, two's complement (hi >= 2^31 is negative).
|
||||
local Int64 = {}
|
||||
|
||||
local P32 = 4294967296
|
||||
@@ -37,7 +36,6 @@ function Int64.sub(ah: number, al: number, bh: number, bl: number): (number, num
|
||||
return Int64.add(ah, al, nh, nl)
|
||||
end
|
||||
|
||||
-- the product mod 2^64 (the same bits for signed and unsigned operands)
|
||||
function Int64.mul(ah: number, al: number, bh: number, bl: number): (number, number)
|
||||
local a0, a1, a2, a3 = al % 65536, al // 65536, ah % 65536, ah // 65536
|
||||
local b0, b1, b2, b3 = bl % 65536, bl // 65536, bh % 65536, bh // 65536
|
||||
@@ -56,7 +54,6 @@ function Int64.isNeg(h: number): boolean
|
||||
return h >= P31
|
||||
end
|
||||
|
||||
-- the signed value as a number (exact below 2^53 in magnitude)
|
||||
function Int64.signed(h: number, l: number): number
|
||||
if h >= P31 then
|
||||
return (h - P32) * P32 + l
|
||||
@@ -64,12 +61,10 @@ function Int64.signed(h: number, l: number): number
|
||||
return h * P32 + l
|
||||
end
|
||||
|
||||
-- the unsigned value as a number (rounded past 2^53)
|
||||
function Int64.unsigned(h: number, l: number): number
|
||||
return h * P32 + l
|
||||
end
|
||||
|
||||
-- unsigned compare: -1, 0, 1
|
||||
function Int64.ucmp(ah: number, al: number, bh: number, bl: number): number
|
||||
if ah ~= bh then
|
||||
return if ah < bh then -1 else 1
|
||||
@@ -80,7 +75,6 @@ function Int64.ucmp(ah: number, al: number, bh: number, bl: number): number
|
||||
return 0
|
||||
end
|
||||
|
||||
-- signed compare: -1, 0, 1
|
||||
function Int64.cmp(ah: number, al: number, bh: number, bl: number): number
|
||||
local sa = if ah >= P31 then ah - P32 else ah
|
||||
local sb = if bh >= P31 then bh - P32 else bh
|
||||
@@ -90,14 +84,12 @@ function Int64.cmp(ah: number, al: number, bh: number, bl: number): number
|
||||
return Int64.ucmp(0, al, 0, bl)
|
||||
end
|
||||
|
||||
-- unsigned division (b ~= 0): quotient, remainder
|
||||
function Int64.udivmod(ah: number, al: number, bh: number, bl: number): (number, number, number, number)
|
||||
if ah == 0 and bh == 0 then
|
||||
return 0, al // bl, 0, al % bl
|
||||
end
|
||||
local qh, ql, rh, rl = 0, 0, 0, 0
|
||||
for i = 63, 0, -1 do
|
||||
-- r = r * 2 + bit i of a
|
||||
local bit = if i >= 32 then (ah // 2 ^ (i - 32)) % 2 else (al // 2 ^ i) % 2
|
||||
local over = rh >= P31
|
||||
rh = (rh * 2 + rl // P31) % P32
|
||||
@@ -114,7 +106,6 @@ function Int64.udivmod(ah: number, al: number, bh: number, bl: number): (number,
|
||||
return qh, ql, rh, rl
|
||||
end
|
||||
|
||||
-- signed division truncating toward zero (b ~= 0)
|
||||
function Int64.div(ah: number, al: number, bh: number, bl: number): (number, number)
|
||||
local na, nb = ah >= P31, bh >= P31
|
||||
if na then
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco/KdTree: kd-tree coded point cloud attributes (bitstream 2.3): DynamicIntegerPointsKdTreeDecoder
|
||||
-- at compression levels 0 - 6 (direct bits, rANS bits, folded 32-bit rANS numbers, selected axes) over all the
|
||||
-- attributes of a decoder at once, then the signed offsets and the dequantization of f32 attributes. Ported from
|
||||
-- Google's Draco 1.5.7 (compression/attributes/kd_tree_attributes_decoder.cc, compression/point_cloud/algorithms/
|
||||
-- dynamic_integer_points_kd_tree_decoder.h, compression/bit_coders/{direct,folded_integer}_bit_decoder; Apache-2.0,
|
||||
-- licenses/draco-LICENSE.txt). The pre-2.3 kd-tree layouts are not supported.
|
||||
-- codecs/model/Draco/KdTree: kd-tree coded point cloud attributes (bitstream 2.3, compression levels 0 - 6).
|
||||
-- Port of Draco 1.5.7 kd_tree_attributes_decoder.cc, dynamic_integer_points_kd_tree_decoder.h and the direct /
|
||||
-- folded_integer bit decoders (Apache-2.0, licenses/draco-LICENSE.txt). Pre-2.3 kd-tree layouts are not supported.
|
||||
local Reader = require("@rosetta/codecs/model/Draco/Reader")
|
||||
local Predict = require("@rosetta/codecs/model/Draco/Predict")
|
||||
|
||||
@@ -12,7 +9,7 @@ local KdTree = {}
|
||||
|
||||
type D = Reader.D
|
||||
|
||||
-- a bit source: next() -> 0 / 1, bits(n) -> value (MSB first); bits returns nil when a direct decoder runs out
|
||||
-- bits(n) reads MSB first
|
||||
type Src = { next: () -> number, bits: (n: number) -> number? }
|
||||
|
||||
local function direct(d: D): Src?
|
||||
@@ -122,7 +119,7 @@ local function msb(n: number): number
|
||||
return k
|
||||
end
|
||||
|
||||
-- DynamicIntegerPointsKdTreeDecoder::DecodePoints -> points (each a table of `dim` u32 values), or nil
|
||||
-- DynamicIntegerPointsKdTreeDecoder::DecodePoints
|
||||
local function decodePoints(d: D, level: number, dim: number, expected: number): ({ { number } }?, string?)
|
||||
local bitLength = Reader.u32(d)
|
||||
local numPoints = Reader.u32(d)
|
||||
@@ -250,7 +247,6 @@ end
|
||||
|
||||
local SIGNED = { [1] = 8, [3] = 16, [5] = 32 }
|
||||
|
||||
-- decodes the attributes of one kd-tree decoder (Attributes.Attr records: dataType, comps; sets values / numValues)
|
||||
function KdTree.decode(d: D, attrs: { any }, numPoints: number): (boolean, string?)
|
||||
if d.ver < 0x0203 then
|
||||
return false, "unsupported: kd-tree point clouds before bitstream 2.3"
|
||||
@@ -293,7 +289,6 @@ function KdTree.decode(d: D, attrs: { any }, numPoints: number): (boolean, strin
|
||||
a.map = nil
|
||||
off += comps
|
||||
end
|
||||
-- the data needed by the transforms: f32 quantization, then the signed minima
|
||||
for _, a in attrs do
|
||||
if a.dataType == 9 then
|
||||
local mins = table.create(a.comps, 0)
|
||||
@@ -321,7 +316,6 @@ function KdTree.decode(d: D, attrs: { any }, numPoints: number): (boolean, strin
|
||||
a.signedMin = mins
|
||||
end
|
||||
end
|
||||
-- back to the original values
|
||||
local fround = Predict.fround
|
||||
for _, a in attrs do
|
||||
local vals = a.portable :: { number }
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco/Predict: Draco attribute prediction schemes and their decoding transforms. Schemes: difference
|
||||
-- (delta), parallelogram, multi-parallelogram, constrained multi-parallelogram, tex coords (deprecated, float) and
|
||||
-- portable tex coords, geometric normal; transforms: wrap, normal octahedron and canonicalized normal octahedron.
|
||||
-- Integer semantics follow the C++ (int32 wrap, truncating division, exact 64-bit products where they can pass 2^53;
|
||||
-- float math rounded to f32 at every step). Ported from Google's Draco 1.5.7
|
||||
-- (compression/attributes/prediction_schemes/*, compression/attributes/normal_compression_utils.h; Apache-2.0,
|
||||
-- licenses/draco-LICENSE.txt).
|
||||
-- codecs/model/Draco/Predict: Draco attribute prediction schemes and their decoding transforms.
|
||||
-- C++ integer semantics (int32 wrap, truncating division, exact 64-bit products) and f32 rounding at every step.
|
||||
-- Port of Draco 1.5.7 prediction_schemes/*, normal_compression_utils.h (Apache-2.0, licenses/draco-LICENSE.txt).
|
||||
local Reader = require("@rosetta/codecs/model/Draco/Reader")
|
||||
local Connectivity = require("@rosetta/codecs/model/Draco/Connectivity")
|
||||
local Int64 = require("@rosetta/codecs/model/Draco/Int64")
|
||||
@@ -87,7 +83,7 @@ local function isqrtProd(a: number, b: number): number
|
||||
end
|
||||
local s = math.floor(math.sqrt(a) * math.sqrt(b))
|
||||
local ph, pl = twoProd(a, b)
|
||||
local function le(x: number): boolean -- x * x <= a * b
|
||||
local function le(x: number): boolean
|
||||
local xh, xl = twoProd(x, x)
|
||||
if xh ~= ph then
|
||||
return xh < ph
|
||||
@@ -103,7 +99,6 @@ local function isqrtProd(a: number, b: number): number
|
||||
return s
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ octahedron toolbox
|
||||
export type Oct = { bits: number, maxQ: number, maxV: number, center: number, scale: number }
|
||||
|
||||
function Predict.octahedron(bits: number): Oct?
|
||||
@@ -207,8 +202,6 @@ function Predict.octToVector(o: Oct, s: number, t: number): (number, number, num
|
||||
return fround(x * dd), fround(y * dd), fround(z * dd)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ transforms
|
||||
-- tr.apply(pred, data, off): data[off + 1 ..] holds the corrections and receives the original values
|
||||
export type Transform = {
|
||||
kind: number, -- 1 wrap, 2 octahedron, 3 octahedron canonicalized
|
||||
positive: boolean, -- corrections are stored without the zig-zag sign mapping
|
||||
@@ -254,7 +247,6 @@ function Predict.decodeTransform(tr: Transform, d: D): boolean
|
||||
return true
|
||||
end
|
||||
|
||||
-- the original values from a prediction (pred[1 .. comps]) and the corrections at data[off + 1 ..]
|
||||
local function apply(tr: Transform, pred: { number }, data: { number }, off: number, comps: number)
|
||||
if tr.kind == 1 then
|
||||
local mn, mx, dif = tr.min, tr.max, tr.maxDif
|
||||
@@ -324,10 +316,7 @@ local function apply(tr: Transform, pred: { number }, data: { number }, off: num
|
||||
end
|
||||
Predict.apply = apply
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ schemes
|
||||
-- the mesh data of a scheme: corner table, value -> corner, vertex -> value
|
||||
export type MeshData = { ct: CT, e2c: { number }, v2e: { number } }
|
||||
-- the parent position attribute: pos(point) -> x, y, z (portable integers, or floats before 2.0)
|
||||
export type Parent = (point: number) -> (number, number, number)
|
||||
|
||||
export type Scheme = {
|
||||
@@ -335,7 +324,6 @@ export type Scheme = {
|
||||
tr: Transform,
|
||||
md: MeshData?,
|
||||
parent: Parent?,
|
||||
-- per-scheme decoded data
|
||||
crease: { { boolean } }?,
|
||||
orient: { boolean }?,
|
||||
flips: Reader.Bits?,
|
||||
@@ -346,7 +334,6 @@ export type Scheme = {
|
||||
local DELTA, PARALLELOGRAM, MULTI, TEXDEP, CONSTRAINED, TEXPORT, GEONORMAL = 0, 1, 2, 3, 4, 5, 6
|
||||
Predict.GEOMETRIC_NORMAL = GEONORMAL
|
||||
|
||||
-- whether the scheme needs the position attribute
|
||||
function Predict.needsParent(s: Scheme): boolean
|
||||
return s.md ~= nil and (s.method == TEXDEP or s.method == TEXPORT or s.method == GEONORMAL)
|
||||
end
|
||||
@@ -489,9 +476,7 @@ local function swingLeft(ct: CT, c: number): number
|
||||
return nextC(o)
|
||||
end
|
||||
|
||||
-- the portable tex coord prediction when both neighbours are decoded (MeshPredictionSchemeTexCoordsPortablePredictor
|
||||
-- ::ComputePredictedValue), in int64 / uint64 arithmetic like the C++. Returns "ok", u, v; "fallback" (degenerate
|
||||
-- edge: predict from a neighbour); or "fail", message.
|
||||
-- MeshPredictionSchemeTexCoordsPortablePredictor::ComputePredictedValue in int64 / uint64 like the C++
|
||||
local function texPortable(nu: number, nv: number, pu: number, pv: number, tx: number, ty: number, tz: number, nx: number, ny: number, nz: number, qx: number, qy: number, qz: number, pop: () -> boolean?): (string, any, any)
|
||||
local pnx, pny, pnz = qx - nx, qy - ny, qz - nz
|
||||
local cnx, cny, cnz = tx - nx, ty - ny, tz - nz
|
||||
@@ -524,7 +509,6 @@ local function texPortable(nu: number, nv: number, pu: number, pv: number, tx: n
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the general case: int64
|
||||
local from, add, sub, mul, div = Int64.from, Int64.add, Int64.sub, Int64.mul, Int64.div
|
||||
local function dot3(ax: number, ay: number, az: number, bx: number, by: number, bz: number): (number, number)
|
||||
local xh, xl = from(ax)
|
||||
@@ -636,7 +620,7 @@ local function texPortable(nu: number, nv: number, pu: number, pv: number, tx: n
|
||||
return "ok", i32(ul), i32(vl)
|
||||
end
|
||||
|
||||
-- ComputeOriginalValues over data (corrections in, values out, in place); points = the entry -> point map
|
||||
-- ComputeOriginalValues (in place); points = the entry -> point map
|
||||
function Predict.compute(s: Scheme, data: { number }, numEntries: number, comps: number, points: { number }): (boolean, string?)
|
||||
local tr = s.tr
|
||||
local m = s.method
|
||||
@@ -912,7 +896,6 @@ function Predict.compute(s: Scheme, data: { number }, numEntries: number, comps:
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
-- geometric normal
|
||||
local o = tr.oct
|
||||
local flips = s.flips
|
||||
if not o or not flips or comps ~= 2 then
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco/Reader: the Draco decoder buffer (little-endian fields, LEB128 varints, LSB-first bit runs) and
|
||||
-- its entropy decoders: rANS symbol coding (tagged and raw schemes, DecodeSymbols) and the binary rANS / rABS bit
|
||||
-- decoder. Ported from Google's Draco 1.5.7 (core/decoder_buffer, core/varint_decoding, compression/entropy/ans.h,
|
||||
-- rans_symbol_decoder.h, symbol_decoding.cc, compression/bit_coders/rans_bit_decoder.cc; Apache-2.0,
|
||||
-- licenses/draco-LICENSE.txt). Bitstream versions 1.0 - 2.2 (fixed-width counts before 2.0 / 2.2).
|
||||
-- A failed read sets the sticky d.bad message and returns 0; callers check d.bad at their boundaries.
|
||||
-- codecs/model/Draco/Reader: Draco's decoder buffer (LE fields, LEB128, LSB-first bit runs) and rANS / rABS decoders.
|
||||
-- Port of Draco 1.5.7 core/decoder_buffer, core/varint_decoding, entropy/ans.h, rans_symbol_decoder.h, symbol_decoding.cc
|
||||
-- and rans_bit_decoder.cc (Apache-2.0, licenses/draco-LICENSE.txt).
|
||||
local Reader = {}
|
||||
|
||||
local readu8, readu16, readu32, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readf32
|
||||
@@ -12,13 +9,13 @@ local band, rshift = bit32.band, bit32.rshift
|
||||
|
||||
export type D = {
|
||||
b: buffer,
|
||||
pos: number, -- absolute offset in b
|
||||
limit: number, -- absolute end
|
||||
pos: number,
|
||||
limit: number,
|
||||
ver: number, -- major * 256 + minor
|
||||
bad: string?,
|
||||
bitMode: boolean,
|
||||
bitStart: number, -- absolute byte where the bit run starts
|
||||
bitOff: number, -- bits consumed
|
||||
bitStart: number,
|
||||
bitOff: number,
|
||||
}
|
||||
|
||||
function Reader.new(b: buffer, pos: number, limit: number, ver: number): D
|
||||
@@ -82,7 +79,6 @@ function Reader.i32(d: D): number
|
||||
return readi32(d.b, p)
|
||||
end
|
||||
|
||||
-- u64 as a number (exact below 2^53; sizes beyond that fail the bounds checks anyway)
|
||||
function Reader.u64(d: D): number
|
||||
local p = d.pos
|
||||
if p + 8 > d.limit then
|
||||
@@ -132,7 +128,6 @@ function Reader.count(d: D, fixedBefore: number): number
|
||||
return Reader.varint(d)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ bit runs
|
||||
-- StartBitDecoding(decodeSize): an optional size (u64 before 2.2, varint64 after), then LSB-first bits up to the end
|
||||
-- of the buffer; EndBitDecoding moves pos past the whole bytes consumed.
|
||||
function Reader.startBits(d: D, decodeSize: boolean): number
|
||||
@@ -179,7 +174,6 @@ function Reader.endBits(d: D)
|
||||
d.pos = d.bitStart + (d.bitOff + 7) // 8
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ rANS symbols
|
||||
-- the precision for a symbol alphabet of `bitLength`-bit symbols: (3 * bits) / 2 clamped to 12..20
|
||||
local function precisionBits(bitLength: number): number
|
||||
local p = (3 * bitLength) // 2
|
||||
@@ -188,12 +182,12 @@ end
|
||||
|
||||
export type Rans = {
|
||||
b: buffer,
|
||||
base: number, -- absolute start of the coded bytes
|
||||
off: number, -- bytes left (read backwards from base + off)
|
||||
base: number,
|
||||
off: number,
|
||||
state: number,
|
||||
lBase: number,
|
||||
precBits: number,
|
||||
lut: { number }, -- rem + 1 -> symbol + 1
|
||||
lut: { number },
|
||||
prob: { number },
|
||||
cum: { number },
|
||||
numSymbols: number,
|
||||
@@ -337,7 +331,6 @@ local function ransStart(d: D, r: Rans): boolean
|
||||
return true
|
||||
end
|
||||
|
||||
-- decodes n symbols into out[first .. first + n - 1] (0-based symbol values)
|
||||
local function ransRead(r: Rans, n: number, out: { number }, first: number)
|
||||
local b, base, off, state = r.b, r.base, r.off, r.state
|
||||
local lBase, bits = r.lBase, r.precBits
|
||||
@@ -412,7 +405,7 @@ local function decodeRaw(d: D, n: number, out: { number }): boolean
|
||||
return true
|
||||
end
|
||||
|
||||
-- DecodeSymbols(n, components) -> { u32 } (1-based) | nil (d.bad set)
|
||||
-- DecodeSymbols
|
||||
function Reader.symbols(d: D, n: number, comps: number): { number }?
|
||||
local out = table.create(n, 0)
|
||||
if n == 0 then
|
||||
@@ -434,7 +427,6 @@ function Reader.symbols(d: D, n: number, comps: number): { number }?
|
||||
return if ok then out else nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ binary rANS
|
||||
export type Bits = { b: buffer, base: number, off: number, state: number, p0: number, p: number }
|
||||
|
||||
-- RAnsBitDecoder::StartDecoding: prob_zero, the size (u32 before 2.2), the bytes
|
||||
|
||||
@@ -1,25 +1,7 @@
|
||||
--!strict
|
||||
-- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7).
|
||||
-- A codec, not a format: model/gltf (and any format carrying Draco data) calls it on a byte range.
|
||||
-- Ported from Google's Draco 1.5.7 (Apache-2.0, licenses/draco-LICENSE.txt): the decoder only, bitstream versions
|
||||
-- 1.0 - 2.2 for meshes (sequential and Edgebreaker connectivity: standard, predictive and valence traversals; topology
|
||||
-- splits, attribute seams), sequential point clouds and kd-tree point clouds (2.3); attribute decoders generic /
|
||||
-- integer / quantization / octahedral normals; prediction schemes difference, parallelogram, multi-parallelogram,
|
||||
-- constrained multi-parallelogram, tex coords (deprecated and portable), geometric normal, with the wrap and normal
|
||||
-- octahedron transforms; metadata. Values match draco_decoder bit for bit (f32 rounding at every step of the
|
||||
-- dequantization).
|
||||
-- Not supported: the pre-2.3 kd-tree point cloud layouts (Err.UNSUPPORTED).
|
||||
--
|
||||
-- local Draco = require("@rosetta/codecs/model/Draco")
|
||||
-- local g, err = Draco.decode(buf, off?, len?, opts?) -- buffer | string
|
||||
-- g.kind ("mesh" | "points"), g.numPoints, g.numFaces, g.indices (u32 x 3 per face, or nil for points)
|
||||
-- g.attributes[i] = { name = "POSITION" | "NORMAL" | "COLOR" | "TEX_COORD" | "GENERIC" | ..., uniqueId,
|
||||
-- components, type = "f32" | "u8" | "i16" | ..., normalized, data (per point, packed) }
|
||||
-- Draco.attribute(g, uniqueId) -> the attribute with that unique id (glTF's attribute map)
|
||||
-- g.metadata = { entries = { [name] = buffer }, children = { [name] = Metadata }, attributes = { [uniqueId] = Metadata } }
|
||||
--
|
||||
-- Options: maxPoints (default 2^24), maxFaces (default 2^24): larger geometry returns Err.LIMIT.
|
||||
-- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT).
|
||||
-- Port of Draco 1.5.7's decoder (Apache-2.0, licenses/draco-LICENSE.txt): bitstreams 1.0 - 2.2 meshes, 2.3 kd-tree
|
||||
-- point clouds; values match draco_decoder bit for bit (f32 rounding at every dequantization step).
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Reader = require("@rosetta/codecs/model/Draco/Reader")
|
||||
@@ -55,7 +37,6 @@ export type Geometry = {
|
||||
}
|
||||
export type Header = { major: number, minor: number, kind: "mesh" | "points", method: number, flags: number }
|
||||
|
||||
-- sniff(buf, off?) -> whether the bytes start with "DRACO"
|
||||
function Draco.sniff(buf: buffer, off: number?): boolean
|
||||
local o = off or 0
|
||||
return buffer.len(buf) >= o + 5 and buffer.readstring(buf, o, 5) == "DRACO"
|
||||
@@ -77,7 +58,6 @@ local function header(d: Reader.D): (Header?, string?)
|
||||
return { major = major, minor = minor, kind = if kind == 0 then "points" else "mesh", method = method, flags = flags }, nil
|
||||
end
|
||||
|
||||
-- info(buf, off?, len?) -> the header
|
||||
function Draco.info(src: buffer | string, off: number?, len: number?): (Header?, Err.Err?)
|
||||
local buf, o, l, aerr = Bytes.span("draco", src, off, len)
|
||||
if not buf then
|
||||
@@ -169,7 +149,6 @@ local WRITE: { [number]: (buffer, number, number) -> () } = {
|
||||
[11] = buffer.writeu8,
|
||||
}
|
||||
|
||||
-- per point output buffer of an attribute
|
||||
local function expand(a: Attributes.Attr, numPoints: number): (buffer?, string?)
|
||||
local size = Attributes.DT_LENGTH[a.dataType]
|
||||
local comps = a.comps
|
||||
@@ -324,7 +303,6 @@ local function decode(buf: buffer, o: number, l: number, opts: any): (Geometry?,
|
||||
return g, nil, nil
|
||||
end
|
||||
|
||||
-- decode(src, off?, len?, opts?) -> Geometry | nil, Err
|
||||
function Draco.decode(src: buffer | string, off: number?, len: number?, opts: any?): (Geometry?, Err.Err?)
|
||||
local buf, o, l, aerr = Bytes.span("draco", src, off, len)
|
||||
if not buf then
|
||||
@@ -340,7 +318,6 @@ function Draco.decode(src: buffer | string, off: number?, len: number?, opts: an
|
||||
return g, nil
|
||||
end
|
||||
|
||||
-- attribute(g, uniqueId) -> the attribute with that unique id
|
||||
function Draco.attribute(g: Geometry, uniqueId: number): Attribute?
|
||||
for _, a in g.attributes do
|
||||
if a.uniqueId == uniqueId then
|
||||
|
||||
@@ -1,14 +1,5 @@
|
||||
--!strict
|
||||
-- codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16
|
||||
-- (glTF / FBX / Types.Scene layout: translation at 13..15), quaternions { x, y, z, w }, angles in degrees where a
|
||||
-- format stores degrees. Shared by FBX, Collada, USD and MeshOps instead of a copy in each. New in rosetta (the
|
||||
-- functions come from the former model/fbx/Xform, model/dae/Math and model/usda/Build helpers).
|
||||
--
|
||||
-- local m = Mat4.compose({ 1, 2, 3 }, quat, { 2, 2, 2 }) -- T * R * S
|
||||
-- local t, r, s = Mat4.decompose(m) -- (decomposeStrict: nil for shear / projective / singular)
|
||||
-- local w = Mat4.mul(parent, m) -- = Types.Scene.mul
|
||||
-- local inv = Mat4.inverse(m) -- affine inverse | nil
|
||||
-- local x, y, z = Mat4.point(m, px, py, pz)
|
||||
-- codecs/model/Mat4: 4x4 matrix (column-major, glTF / Types.Scene layout) and quaternion { x, y, z, w } helpers.
|
||||
local Types = require("@rosetta/Types")
|
||||
|
||||
local Mat4 = {}
|
||||
@@ -21,7 +12,6 @@ function Mat4.identity(): M4
|
||||
return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
|
||||
-- mul(a, b) -> a * b
|
||||
Mat4.mul = Types.Scene.mul
|
||||
|
||||
function Mat4.translation(x: number, y: number, z: number): M4
|
||||
@@ -32,7 +22,6 @@ function Mat4.scaling(x: number, y: number, z: number): M4
|
||||
return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 }
|
||||
end
|
||||
|
||||
-- rotation(axis, degrees) -> the rotation about axis 1 (X), 2 (Y) or 3 (Z)
|
||||
function Mat4.rotation(axis: number, degrees: number): M4
|
||||
local a = rad(degrees)
|
||||
local c, s = cos(a), sin(a)
|
||||
@@ -45,7 +34,6 @@ function Mat4.rotation(axis: number, degrees: number): M4
|
||||
end
|
||||
|
||||
local AXIS = { x = 1, y = 2, z = 3 }
|
||||
-- euler(x, y, z, order?) -> the rotation applying the axes in order (default "xyz": R = Rz * Ry * Rx), degrees
|
||||
function Mat4.euler(x: number, y: number, z: number, order: string?): M4
|
||||
local o = order or "xyz"
|
||||
local deg = { x = x, y = y, z = z }
|
||||
@@ -57,7 +45,6 @@ function Mat4.euler(x: number, y: number, z: number, order: string?): M4
|
||||
return m
|
||||
end
|
||||
|
||||
-- axisAngle(x, y, z, degrees) -> quaternion
|
||||
function Mat4.axisAngle(x: number, y: number, z: number, degrees: number): { number }
|
||||
local l = sqrt(x * x + y * y + z * z)
|
||||
if l < 1e-12 then
|
||||
@@ -68,7 +55,6 @@ function Mat4.axisAngle(x: number, y: number, z: number, degrees: number): { num
|
||||
return { x * s, y * s, z * s, cos(h) }
|
||||
end
|
||||
|
||||
-- fromQuat(q) -> the rotation matrix of a quaternion
|
||||
function Mat4.fromQuat(q: { number }): M4
|
||||
local x, y, z, w = q[1], q[2], q[3], q[4]
|
||||
local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z
|
||||
@@ -80,7 +66,6 @@ function Mat4.fromQuat(q: { number }): M4
|
||||
}
|
||||
end
|
||||
|
||||
-- quat(m) -> the unit quaternion of the rotation in m's upper 3x3 (columns assumed orthonormal)
|
||||
function Mat4.quat(m: M4): { number }
|
||||
local m00, m01, m02 = m[1], m[5], m[9]
|
||||
local m10, m11, m12 = m[2], m[6], m[10]
|
||||
@@ -107,7 +92,6 @@ function Mat4.quat(m: M4): { number }
|
||||
return { x / n, y / n, z / n, w / n }
|
||||
end
|
||||
|
||||
-- eulerXYZ(q) -> Euler XYZ degrees (R = Rz * Ry * Rx) of a quaternion
|
||||
function Mat4.eulerXYZ(q: { number }): { number }
|
||||
local m = Mat4.fromQuat(q)
|
||||
local sy = math.clamp(-m[3], -1, 1) -- m[3] = r20 = -sin(y)
|
||||
@@ -123,7 +107,7 @@ function Mat4.eulerXYZ(q: { number }): { number }
|
||||
return { math.deg(x), math.deg(y), math.deg(z) }
|
||||
end
|
||||
|
||||
-- compose(t?, r?, s?) -> T * R * S (glTF node semantics)
|
||||
-- T * R * S (glTF 2.0 node transform)
|
||||
function Mat4.compose(t: { number }?, r: { number }?, s: { number }?): M4
|
||||
local m = if r then Mat4.fromQuat(r) else Mat4.identity()
|
||||
if s then
|
||||
@@ -171,19 +155,16 @@ local function split(m: M4, strict: boolean): ({ number }?, { number }?, { numbe
|
||||
return { m[13], m[14], m[15] }, Mat4.quat(r), { sx, sy, sz }
|
||||
end
|
||||
|
||||
-- decompose(m) -> translation, rotation (quaternion), scale (a negative determinant flips the x scale; shear is lost)
|
||||
-- a negative determinant flips the x scale; shear is lost
|
||||
function Mat4.decompose(m: M4): ({ number }, { number }, { number })
|
||||
local t, r, s = split(m, false)
|
||||
return t :: { number }, r :: { number }, s :: { number }
|
||||
end
|
||||
|
||||
-- decomposeStrict(m) -> translation, rotation, scale | nil for matrices TRS cannot express (a projective row, shear,
|
||||
-- a zero scale)
|
||||
function Mat4.decomposeStrict(m: M4): ({ number }?, { number }?, { number }?)
|
||||
return split(m, true)
|
||||
end
|
||||
|
||||
-- inverse(m) -> the inverse of an affine matrix (general upper 3x3) | nil when singular
|
||||
function Mat4.inverse(m: M4): M4?
|
||||
local a, b, c = m[1], m[5], m[9]
|
||||
local d, e, f = m[2], m[6], m[10]
|
||||
@@ -207,7 +188,6 @@ function Mat4.inverse(m: M4): M4?
|
||||
return r
|
||||
end
|
||||
|
||||
-- inverseFull(m) -> the inverse of any invertible 4x4 (projective rows too) | nil when singular
|
||||
function Mat4.inverseFull(m: M4): M4?
|
||||
local a = m
|
||||
local inv = table.create(16, 0)
|
||||
@@ -237,12 +217,10 @@ function Mat4.inverseFull(m: M4): M4?
|
||||
return inv
|
||||
end
|
||||
|
||||
-- transpose3(m) -> m with its upper 3x3 transposed and no translation (the inverse of a pure rotation)
|
||||
function Mat4.transpose3(m: M4): M4
|
||||
return { m[1], m[5], m[9], 0, m[2], m[6], m[10], 0, m[3], m[7], m[11], 0, 0, 0, 0, 1 }
|
||||
end
|
||||
|
||||
-- fromRows(v, at?) -> column-major from 16 row-major values at v[at] (default 1; missing values: identity)
|
||||
function Mat4.fromRows(v: { number }, at: number?): M4
|
||||
local o = (at or 1) - 1
|
||||
local m = table.create(16, 0)
|
||||
@@ -254,7 +232,6 @@ function Mat4.fromRows(v: { number }, at: number?): M4
|
||||
return m
|
||||
end
|
||||
|
||||
-- toRows(m) -> the 16 values row-major
|
||||
function Mat4.toRows(m: M4): { number }
|
||||
local v = table.create(16, 0)
|
||||
for r = 0, 3 do
|
||||
@@ -265,12 +242,10 @@ function Mat4.toRows(m: M4): { number }
|
||||
return v
|
||||
end
|
||||
|
||||
-- point(m, x, y, z) -> m * (x, y, z, 1)
|
||||
function Mat4.point(m: M4, x: number, y: number, z: number): (number, number, number)
|
||||
return m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15]
|
||||
end
|
||||
|
||||
-- normalMatrix(m) -> the inverse transpose of the upper 3x3 (for normals) as a 4x4 (identity when singular)
|
||||
function Mat4.normalMatrix(m: M4): M4
|
||||
local inv = Mat4.inverse({ m[1], m[2], m[3], 0, m[5], m[6], m[7], 0, m[9], m[10], m[11], 0, 0, 0, 0, 1 })
|
||||
if not inv then
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
--!strict
|
||||
-- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks
|
||||
-- scene.roots recursively (TRS or column-major `matrix` per node; a scene without nodes uses its meshes as they are),
|
||||
-- applies the transforms to POSITION (and the inverse transpose to NORMAL), reverses the winding under mirroring
|
||||
-- transforms, reads every accessor type to numbers and concatenates all primitives (triangles with or without indices,
|
||||
-- polygons, strips, fans, points; lines are skipped). Shared here because a format cannot require another one
|
||||
-- (ops/MeshOps.merge is the editing-side equivalent).
|
||||
-- Never throws: bad input returns nil, message.
|
||||
-- codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF).
|
||||
local Types = require("@rosetta/Types")
|
||||
|
||||
local Flatten = {}
|
||||
@@ -19,31 +13,29 @@ local SIZE = Types.COMPONENT_SIZE
|
||||
local NORM: { [string]: number } = { unorm8 = 255, unorm16 = 65535, snorm8 = 127, snorm16 = 32767 }
|
||||
|
||||
export type Attr = {
|
||||
type: string, -- the accessor type shared by every part ("f32" when the parts disagree)
|
||||
type: string,
|
||||
components: number,
|
||||
raw: boolean, -- values are raw integers of a normalized type (unorm8: 0..255), else plain numbers
|
||||
values: { number }, -- count * components
|
||||
raw: boolean,
|
||||
values: { number },
|
||||
}
|
||||
export type PartInfo = {
|
||||
prim: Types.Primitive,
|
||||
mesh: Types.Mesh?,
|
||||
node: Types.Node?,
|
||||
firstVertex: number, -- 0-based offset of the part's vertices in the merged mesh
|
||||
firstVertex: number,
|
||||
vertexCount: number,
|
||||
firstFace: number, -- 0-based offset of the part's faces
|
||||
firstFace: number,
|
||||
faceCount: number,
|
||||
identity: boolean, -- no transform was applied
|
||||
identity: boolean,
|
||||
}
|
||||
export type Merged = {
|
||||
count: number, -- vertices
|
||||
attrs: { [string]: Attr }, -- POSITION and NORMAL in world space (f32 values), the others as read
|
||||
sizes: { number }?, -- vertices per face (nil: no part has faces, a point cloud)
|
||||
corners: { number }, -- 0-based vertex indices, face after face
|
||||
count: number,
|
||||
attrs: { [string]: Attr },
|
||||
sizes: { number }?,
|
||||
corners: { number },
|
||||
parts: { PartInfo },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ accessors
|
||||
-- numbers(acc, raw) -> the accessor's count * components values (normalized types divided out unless raw), or nil, msg
|
||||
function Flatten.numbers(acc: any, raw: boolean?): ({ number }?, string?)
|
||||
if type(acc) ~= "table" or type(acc.data) ~= "buffer" then
|
||||
return nil, "accessor without a data buffer"
|
||||
@@ -106,10 +98,9 @@ function Flatten.numbers(acc: any, raw: boolean?): ({ number }?, string?)
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ transforms
|
||||
local IDENTITY = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
|
||||
|
||||
local mul = Types.Scene.mul -- column-major 4x4 product a * b
|
||||
local mul = Types.Scene.mul
|
||||
|
||||
local function numList(v: any, n: number): boolean
|
||||
if type(v) ~= "table" then
|
||||
@@ -123,7 +114,6 @@ local function numList(v: any, n: number): boolean
|
||||
return true
|
||||
end
|
||||
|
||||
-- a node's local matrix (nil: none), or nil, message
|
||||
local function localMatrix(node: any): ({ number }?, string?)
|
||||
if node.matrix ~= nil then
|
||||
if not numList(node.matrix, 16) then
|
||||
@@ -186,7 +176,6 @@ end
|
||||
|
||||
type Instance = { prim: Types.Primitive, mesh: Types.Mesh?, node: Types.Node?, matrix: { number }? }
|
||||
|
||||
-- the primitive instances of a scene in traversal order, or nil, message
|
||||
local function instances(scene: any): ({ Instance }?, string?)
|
||||
local out: { Instance } = {}
|
||||
local nodes, meshes = scene.nodes, scene.meshes
|
||||
@@ -274,8 +263,6 @@ local function instances(scene: any): ({ Instance }?, string?)
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ faces
|
||||
-- the faces of a primitive: sizes (nil = all triangles), corners (0-based), or "points" / "skip", or nil, message
|
||||
local function faces(prim: any, nv: number): (any, any, string?)
|
||||
local mode = prim.mode or "triangles"
|
||||
if mode == "points" then
|
||||
@@ -352,7 +339,6 @@ local function faces(prim: any, nv: number): (any, any, string?)
|
||||
return nil, nil, "unknown primitive mode " .. tostring(mode)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ merge
|
||||
-- the fill value of a missing attribute component: colours default to opaque white, everything else to 0
|
||||
local function fill(name: string, t: string, raw: boolean): number
|
||||
if string.sub(name, 1, 6) ~= "COLOR_" then
|
||||
@@ -367,8 +353,6 @@ local function f32(v: number): number
|
||||
return buffer.readf32(b, 0)
|
||||
end
|
||||
|
||||
-- merge(scene, keep, opts) -> Merged | nil, message. keep(name) says which attributes to carry (POSITION always).
|
||||
-- opts.triangulate fan-triangulates polygons (faces of fewer than 3 vertices are dropped then).
|
||||
function Flatten.merge(scene: any, keep: (string) -> boolean, opts: { triangulate: boolean? }?): (Merged?, string?)
|
||||
if type(scene) ~= "table" then
|
||||
return nil, "not a scene"
|
||||
@@ -378,7 +362,6 @@ function Flatten.merge(scene: any, keep: (string) -> boolean, opts: { triangulat
|
||||
return nil, lerr
|
||||
end
|
||||
local triangulate = opts and opts.triangulate or false
|
||||
-- the attribute set: union over parts, a type every part agrees on (else f32), the widest component count
|
||||
local types: { [string]: string } = {}
|
||||
local comps: { [string]: number } = {}
|
||||
local used: { Instance } = {}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
--!strict
|
||||
-- codecs/model/Minecraft/Colors: the built-in default colour of Minecraft blocks, for showing block grids as coloured
|
||||
-- voxels. Hand-made for this library (approximate average colours picked by eye; no game assets or wiki tables were
|
||||
-- copied): exact block names, then families by dye colour and wood type; codecs/model/Minecraft resolves stairs /
|
||||
-- slabs / walls / ... to their base block and falls back to keywords. Format: name=rrggbb or name=rrggbbaa.
|
||||
-- codecs/model/Minecraft/Colors: default Minecraft block colours as name=rrggbb or name=rrggbbaa.
|
||||
-- Hand-picked approximations; no game assets or wiki tables copied.
|
||||
local Colors = {}
|
||||
|
||||
Colors.BLOCKS = [[
|
||||
@@ -66,13 +64,11 @@ muddy_mangrove_roots=46413a ochre_froglight=f6e8a6 verdant_froglight=dcf0d6 pear
|
||||
creaking_heart=5a4a3c resin_block=d9661c resin_bricks=ce5a1a
|
||||
]]
|
||||
|
||||
-- wool-like colour of each dye, then concrete and terracotta (same order as Colors.DYES)
|
||||
Colors.DYES = { "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black" }
|
||||
Colors.WOOL = "e9ecec f07613 bd44b3 3aafd9 f8c527 70b919 ed8dac 3e4447 8e8e86 158991 792aac 35399d 724728 546d1b a12722 141519"
|
||||
Colors.CONCRETE = "cfd5d6 e06100 a9309f 2389c6 f0af15 5ea818 d5658e 36393d 7d7d73 157788 64209c 2c2e8f 603b1f 495b24 8e2020 080a0f"
|
||||
Colors.TERRACOTTA = "d1b2a1 a15325 95576c 716c89 ba8523 677534 a14e4e 392a23 876a61 575b5b 764656 4a3b5b 4d3323 4c532a 8f3d2e 251610"
|
||||
|
||||
-- wood types: planks, bark (log / wood), leaves
|
||||
Colors.WOODS = { "oak", "spruce", "birch", "jungle", "acacia", "dark_oak", "mangrove", "cherry", "pale_oak", "bamboo", "crimson", "warped" }
|
||||
Colors.PLANKS = "a2834f 735531 c0af79 a07351 a85a32 432b14 763631 e3b3ad e4d9d3 c1ad50 653147 2b6963"
|
||||
Colors.BARK = "6d5533 3a2510 d8d7d2 55441a 676157 3e2f17 543a26 371b22 524a46 7f9030 5c1919 3a3a4d"
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
--!strict
|
||||
-- codecs/model/Minecraft/Legacy: numeric block ids of Minecraft before 1.13 (the .schematic format, Anvil chunks with
|
||||
-- Blocks / Data arrays), from the Minecraft wiki "Java Edition data values/Pre-flattening" page (facts, not code):
|
||||
-- the 1.12 name of every id, and how the data value picks a variant for the blocks whose colour or wood depends on it
|
||||
-- (the modern name of that variant: wool 14 -> red_wool, planks 2 -> birch_planks).
|
||||
-- codecs/model/Minecraft/Legacy: pre-1.13 numeric block ids and their data-value variants.
|
||||
-- From the Minecraft wiki "Java Edition data values/Pre-flattening" (facts, not code).
|
||||
local Legacy = {}
|
||||
|
||||
local function words(s: string): { string }
|
||||
@@ -46,8 +44,7 @@ gray_glazed_terracotta silver_glazed_terracotta cyan_glazed_terracotta purple_gl
|
||||
blue_glazed_terracotta brown_glazed_terracotta green_glazed_terracotta red_glazed_terracotta black_glazed_terracotta
|
||||
concrete concrete_powder - - structure_block]])
|
||||
|
||||
-- legacy names whose modern name differs (data value not involved; only one-to-one renames, so the way back is exact:
|
||||
-- lit_furnace, powered_repeater, ... keep their legacy names)
|
||||
-- one-to-one renames only, so the way back is exact (lit_furnace, powered_repeater, ... keep their legacy names)
|
||||
Legacy.RENAMED = {
|
||||
grass = "grass_block", brick_block = "bricks", stonebrick = "stone_bricks", hardened_clay = "terracotta",
|
||||
melon_block = "melon", lit_pumpkin = "jack_o_lantern", slime = "slime_block", magma = "magma_block",
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/model/Minecraft/Packed: Minecraft's packed index arrays. New code, from the Minecraft wiki "Chunk format" and
|
||||
-- the Sponge / Litematica schematic specs: long arrays (little-endian int64s as codecs/text/Nbt keeps them) holding
|
||||
-- bits-wide indices either spanning long boundaries (Litematica, chunks before 1.16) or not (chunks since 1.16:
|
||||
-- floor(64 / bits) per long, the rest padding), and the varint byte arrays of Sponge schematics. Indices are written
|
||||
-- to / read from u16 little-endian buffers. Every access is bounds-checked first; never throws.
|
||||
-- codecs/model/Minecraft/Packed: Minecraft's packed index arrays. New code.
|
||||
-- Minecraft wiki "Chunk format", Sponge / Litematica schematic specs: little-endian int64 longs of bits-wide indices,
|
||||
-- spanning long boundaries (Litematica, chunks before 1.16) or floor(64 / bits) per long plus padding (since 1.16).
|
||||
local Packed = {}
|
||||
|
||||
local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
|
||||
local writeu8, writeu16 = buffer.writeu8, buffer.writeu16
|
||||
local extract, band, rshift, lshift, bor = bit32.extract, bit32.band, bit32.rshift, bit32.lshift, bit32.bor
|
||||
|
||||
-- longsNeeded(count, bits, spanning) -> the number of longs a packed array of count indices takes
|
||||
function Packed.longsNeeded(count: number, bits: number, spanning: boolean): number
|
||||
if spanning then
|
||||
return (count * bits + 63) // 64
|
||||
@@ -21,8 +18,6 @@ function Packed.longsNeeded(count: number, bits: number, spanning: boolean): num
|
||||
return (count + per - 1) // per
|
||||
end
|
||||
|
||||
-- unpack(longs, bits, count, spanning, out, max) -> true | false, message: count indices into out (u16 LE, from byte
|
||||
-- 0); an index >= max is an error. bits 1 .. 16.
|
||||
function Packed.unpack(longs: buffer, bits: number, count: number, spanning: boolean, out: buffer, max: number): (boolean, string?)
|
||||
if bits < 1 or bits > 16 then
|
||||
return false, "unsupported: " .. bits .. "-bit packed indices"
|
||||
@@ -34,7 +29,6 @@ function Packed.unpack(longs: buffer, bits: number, count: number, spanning: boo
|
||||
if buffer.len(out) < count * 2 then
|
||||
return false, "output too small"
|
||||
end
|
||||
-- a copy with 4 bytes of padding, so every 32-bit read stays in range
|
||||
local n = need * 8
|
||||
local src = buffer.create(n + 4)
|
||||
buffer.copy(src, 0, longs, 0, n)
|
||||
@@ -72,7 +66,6 @@ function Packed.unpack(longs: buffer, bits: number, count: number, spanning: boo
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- pack(indices, count, bits, spanning) -> longs buffer (little-endian int64s): the inverse of unpack
|
||||
function Packed.pack(indices: buffer, count: number, bits: number, spanning: boolean): buffer
|
||||
local need = Packed.longsNeeded(count, bits, spanning)
|
||||
local out = buffer.create(need * 8 + 4)
|
||||
@@ -82,7 +75,6 @@ function Packed.pack(indices: buffer, count: number, bits: number, spanning: boo
|
||||
local p = if spanning then i * bits else (i // per) * 64 + (i % per) * bits
|
||||
local at = rshift(p, 3)
|
||||
local sh = band(p, 7)
|
||||
-- OR the value in byte by byte (up to 3 bytes for 16 bits at a shift of 7)
|
||||
local x = lshift(v, sh)
|
||||
for k = 0, 2 do
|
||||
local bits8 = band(rshift(x, k * 8), 0xff)
|
||||
@@ -96,7 +88,6 @@ function Packed.pack(indices: buffer, count: number, bits: number, spanning: boo
|
||||
return res
|
||||
end
|
||||
|
||||
-- bitsFor(n, min) -> bits for indices 0 .. n - 1 (at least min)
|
||||
function Packed.bitsFor(n: number, min: number): number
|
||||
local b = min
|
||||
while lshift(1, b) < n and b < 31 do
|
||||
@@ -105,8 +96,7 @@ function Packed.bitsFor(n: number, min: number): number
|
||||
return b
|
||||
end
|
||||
|
||||
-- varints(src, offset, length, count, out, max) -> true | false, message: count unsigned LEB128 varints (Sponge
|
||||
-- BlockData) into out (u16 LE)
|
||||
-- Sponge BlockData: unsigned LEB128 varints
|
||||
function Packed.varints(src: buffer, offset: number, length: number, count: number, out: buffer, max: number): (boolean, string?)
|
||||
if buffer.len(out) < count * 2 or offset + length > buffer.len(src) then
|
||||
return false, "bad varint array arguments"
|
||||
@@ -137,7 +127,6 @@ function Packed.varints(src: buffer, offset: number, length: number, count: numb
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- toVarints(indices, count) -> buffer: count u16 indices as unsigned LEB128 varints
|
||||
function Packed.toVarints(indices: buffer, count: number): buffer
|
||||
local out = buffer.create(count * 3)
|
||||
local p = 0
|
||||
@@ -156,8 +145,7 @@ function Packed.toVarints(indices: buffer, count: number): buffer
|
||||
return res
|
||||
end
|
||||
|
||||
-- nibble(src, offset, i, highFirst) -> the 4-bit value i of a nibble array (Minecraft: low nibble first; WorldEdit's
|
||||
-- AddBlocks: high nibble first)
|
||||
-- nibble arrays: Minecraft low nibble first; WorldEdit AddBlocks high nibble first
|
||||
function Packed.nibble(src: buffer, offset: number, i: number, highFirst: boolean): number
|
||||
local b = readu8(src, offset + rshift(i, 1))
|
||||
local odd = band(i, 1) == 1
|
||||
@@ -167,7 +155,6 @@ function Packed.nibble(src: buffer, offset: number, i: number, highFirst: boolea
|
||||
return rshift(b, 4)
|
||||
end
|
||||
|
||||
-- setNibble(dst, offset, i, v, highFirst)
|
||||
function Packed.setNibble(dst: buffer, offset: number, i: number, v: number, highFirst: boolean)
|
||||
local at = offset + rshift(i, 1)
|
||||
local b = readu8(dst, at)
|
||||
@@ -179,9 +166,7 @@ function Packed.setNibble(dst: buffer, offset: number, i: number, v: number, hig
|
||||
end
|
||||
end
|
||||
|
||||
-- fromYzx(src, sx, sy, sz, dst?, ox?, oy?, oz?, dsx?, dsy?) -> dst: u16 cells in Minecraft's order (x fastest, then
|
||||
-- z, then y: schematics, chunk sections) to Types.Voxels order (x, then y, then z), into dst (default a new
|
||||
-- sx * sy * sz grid) at cell offset (ox, oy, oz) of a dsx * dsy * ... grid. The caller checks the ranges.
|
||||
-- Minecraft order: x fastest, then z, then y (schematics, chunk sections)
|
||||
function Packed.fromYzx(src: buffer, sx: number, sy: number, sz: number, dst: buffer?, ox: number?, oy: number?, oz: number?, dsx: number?, dsy: number?): buffer
|
||||
local out = dst or buffer.create(sx * sy * sz * 2)
|
||||
local bx, by, bz = ox or 0, oy or 0, oz or 0
|
||||
@@ -200,7 +185,6 @@ function Packed.fromYzx(src: buffer, sx: number, sy: number, sz: number, dst: bu
|
||||
return out
|
||||
end
|
||||
|
||||
-- toYzx(src, sx, sy, sz) -> buffer: Types.Voxels order to Minecraft's (the inverse of fromYzx)
|
||||
function Packed.toYzx(src: buffer, sx: number, sy: number, sz: number): buffer
|
||||
local out = buffer.create(sx * sy * sz * 2)
|
||||
local i = 0
|
||||
|
||||
@@ -1,16 +1,5 @@
|
||||
--!strict
|
||||
-- codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code.
|
||||
-- Block states ("minecraft:oak_stairs[facing=east,half=bottom]": parse / format / NBT compound form), the default
|
||||
-- block colour table (codecs/model/Minecraft/Colors, hand-made) with fallbacks by family, the pre-1.13 numeric ids
|
||||
-- (codecs/model/Minecraft/Legacy), packed index arrays (codecs/model/Minecraft/Packed), and the bridge between block
|
||||
-- grids and Types.Voxels: voxels.blocks holds the exact states (u16 indices into a state palette), voxels.data /
|
||||
-- palette their colours; writing a grid without blocks picks the block nearest in colour for each palette colour.
|
||||
--
|
||||
-- local Mc = require("@rosetta/codecs/model/Minecraft")
|
||||
-- local name, props = Mc.parseState("minecraft:oak_log[axis=y]") -- "minecraft:oak_log", { { "axis", "y" } }
|
||||
-- local rgba = Mc.color("minecraft:red_wool") -- { r, g, b, a } | nil for air
|
||||
-- local v = Mc.voxels(sx, sy, sz, states, indices) -- a Types.Voxels with .blocks
|
||||
-- local states, indices = Mc.blocksOf(v) -- back (or chosen by colour)
|
||||
local Types = require("@rosetta/Types")
|
||||
local Nbt = require("@rosetta/codecs/text/Nbt")
|
||||
local Colors = require("@rosetta/codecs/model/Minecraft/Colors")
|
||||
@@ -22,8 +11,6 @@ local Minecraft = {}
|
||||
Minecraft.Packed = Packed
|
||||
Minecraft.Legacy = Legacy
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ block states
|
||||
-- parseState(s) -> name (namespace added when missing), props { { key, value } } in their order
|
||||
function Minecraft.parseState(s: string): (string, { { string } })
|
||||
local name, rest = string.match(s, "^%s*([^%[%s]*)%s*(.*)$")
|
||||
local n = name or ""
|
||||
@@ -43,7 +30,6 @@ function Minecraft.parseState(s: string): (string, { { string } })
|
||||
return n, props
|
||||
end
|
||||
|
||||
-- stateString(name, props?) -> "name[k=v,...]" (props { { k, v } } in order, or a map: keys sorted)
|
||||
function Minecraft.stateString(name: string, props: { any }?): string
|
||||
if not props or next(props) == nil then
|
||||
return name
|
||||
@@ -61,7 +47,6 @@ function Minecraft.stateString(name: string, props: { any }?): string
|
||||
return name .. "[" .. table.concat(parts, ",") .. "]"
|
||||
end
|
||||
|
||||
-- stateFromNbt(compound) -> the state string of a palette entry { Name, Properties? } (litematic, chunk sections)
|
||||
function Minecraft.stateFromNbt(c: any): string?
|
||||
if type(c) ~= "table" or type(c.Name) ~= "string" then
|
||||
return nil
|
||||
@@ -76,7 +61,6 @@ function Minecraft.stateFromNbt(c: any): string?
|
||||
return Minecraft.stateString(c.Name, props)
|
||||
end
|
||||
|
||||
-- stateToNbt(state) -> { Name, Properties? } (a Types.object; Properties in the state's order)
|
||||
function Minecraft.stateToNbt(s: string): { [string]: any }
|
||||
local name, props = Minecraft.parseState(s)
|
||||
local c = Types.object({ Name = name }, { "Name" })
|
||||
@@ -91,19 +75,16 @@ function Minecraft.stateToNbt(s: string): { [string]: any }
|
||||
return c
|
||||
end
|
||||
|
||||
-- baseName(state) -> the name without namespace and properties ("minecraft:oak_log[axis=y]" -> "oak_log")
|
||||
function Minecraft.baseName(s: string): string
|
||||
local name = string.match(s, "^%s*([^%[%s]*)") or ""
|
||||
return string.match(name, ":(.*)$") or name
|
||||
end
|
||||
|
||||
local AIR = { air = true, cave_air = true, void_air = true, structure_void = true, light = true, barrier = true, moving_piston = true }
|
||||
-- isAir(state) -> true for blocks that are not drawn (air, cave_air, void_air, structure_void, light, barrier)
|
||||
function Minecraft.isAir(s: string): boolean
|
||||
return AIR[Minecraft.baseName(s)] == true
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ colours
|
||||
local function hex(h: string): { number }
|
||||
local c = { tonumber(string.sub(h, 1, 2), 16) or 0, tonumber(string.sub(h, 3, 4), 16) or 0, tonumber(string.sub(h, 5, 6), 16) or 0, 255 }
|
||||
if #h >= 8 then
|
||||
@@ -259,7 +240,6 @@ resolve = function(n: string, depth: number): { number }?
|
||||
end
|
||||
|
||||
local cache: { [string]: { number } | false } = {}
|
||||
-- color(state) -> { r, g, b, a } (0..255) | nil for air-like blocks: the default colour table, families, keywords
|
||||
function Minecraft.color(s: string): { number }?
|
||||
local hit = cache[s]
|
||||
if hit ~= nil then
|
||||
@@ -269,7 +249,6 @@ function Minecraft.color(s: string): { number }?
|
||||
local n = string.match(name, ":(.*)$") or name
|
||||
local res: { number }? = nil
|
||||
if not AIR[n] then
|
||||
-- pre-1.13 names whose data value picks the variant
|
||||
local variants = Legacy.VARIANTS[n] or (if n == "double_wooden_slab" then Legacy.VARIANTS.planks else nil)
|
||||
if variants then
|
||||
local data = 0
|
||||
@@ -287,7 +266,6 @@ function Minecraft.color(s: string): { number }?
|
||||
return res
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ legacy ids
|
||||
local REVERSE: { [string]: { number } }? = nil
|
||||
local function reverse(): { [string]: { number } }
|
||||
if REVERSE then
|
||||
@@ -319,8 +297,7 @@ local function reverse(): { [string]: { number } }
|
||||
return r
|
||||
end
|
||||
|
||||
-- legacyState(id, data) -> the state string for a pre-1.13 block (variant names where the data value picks one, the
|
||||
-- rest of the data value kept as [data=N] so legacyId gives it back exactly)
|
||||
-- the rest of the data value stays as [data=N], so legacyId gives it back exactly
|
||||
function Minecraft.legacyState(id: number, data: number): string
|
||||
local n = Legacy.NAMES[id + 1]
|
||||
if n == nil or n == "-" then
|
||||
@@ -337,8 +314,6 @@ function Minecraft.legacyState(id: number, data: number): string
|
||||
return "minecraft:" .. (Legacy.RENAMED[n] or n) .. (if data ~= 0 then "[data=" .. data .. "]" else "")
|
||||
end
|
||||
|
||||
-- legacyId(state) -> id, data | nil: the inverse of legacyState (modern names that exist before 1.13 too; their
|
||||
-- properties are not converted to data values)
|
||||
function Minecraft.legacyId(s: string): (number?, number?)
|
||||
local name, props = Minecraft.parseState(s)
|
||||
local n = string.match(name, ":(.*)$") or name
|
||||
@@ -363,10 +338,6 @@ function Minecraft.legacyId(s: string): (number?, number?)
|
||||
return id, data
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ voxels
|
||||
-- voxels(sx, sy, sz, states, indices, opts?) -> Types.Voxels: indices (u16 LE per cell in Voxels order: x fastest,
|
||||
-- then y, then z) into states; data / palette from the block colours (air -> 0; up to 255 colours, more merge into
|
||||
-- the nearest one)
|
||||
function Minecraft.voxels(sx: number, sy: number, sz: number, states: { string }, indices: buffer): Types.Voxels
|
||||
local v = Types.Voxels.new(sx, sy, sz)
|
||||
local lut = buffer.create(#states)
|
||||
@@ -409,7 +380,6 @@ function Minecraft.voxels(sx: number, sy: number, sz: number, states: { string }
|
||||
return v
|
||||
end
|
||||
|
||||
-- the blocks a colour grid is written with: full blocks of distinct colours (and stained glass for translucent ones)
|
||||
local CANDIDATES: { { any } }? = nil
|
||||
local function candidates(): { { any } }
|
||||
if CANDIDATES then
|
||||
@@ -434,7 +404,6 @@ local function candidates(): { { any } }
|
||||
return out
|
||||
end
|
||||
|
||||
-- nearestBlock(rgba) -> the block state whose default colour is nearest (translucent colours -> stained glass)
|
||||
function Minecraft.nearestBlock(c: { number }): string
|
||||
local a = c[4] or 255
|
||||
if a < 200 then
|
||||
@@ -459,8 +428,6 @@ function Minecraft.nearestBlock(c: { number }): string
|
||||
return best
|
||||
end
|
||||
|
||||
-- blocksOf(voxels) -> states, indices (u16 LE per cell): voxels.blocks when present (checked), else a block per
|
||||
-- palette colour (nearestBlock; cell 0 -> "minecraft:air" at index 0) | nil, message
|
||||
function Minecraft.blocksOf(v: Types.Voxels): ({ string }?, any)
|
||||
local n = v.size[1] * v.size[2] * v.size[3]
|
||||
local b = v.blocks
|
||||
@@ -497,9 +464,8 @@ function Minecraft.blocksOf(v: Types.Voxels): ({ string }?, any)
|
||||
return states, out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ block entities
|
||||
-- Block entity records in one shape, { pos = { x, y, z }, id, data } (Sponge v3's), from / to the flat
|
||||
-- { x, y, z, id, ... } of MCEdit, Litematica and chunks, and Sponge v1 / v2's { Pos, Id, ... }.
|
||||
-- block entities: Sponge v3 { pos = { x, y, z }, id, data } <-> flat { x, y, z, id, ... } (MCEdit, Litematica,
|
||||
-- chunks) / Sponge v1 / v2 { Pos, Id, ... }
|
||||
local function int(v: any): number?
|
||||
local n = Nbt.number(v)
|
||||
if n == nil or n ~= n or n % 1 ~= 0 then
|
||||
@@ -519,8 +485,8 @@ local function ints(v: any): { number }?
|
||||
end
|
||||
return nil
|
||||
end
|
||||
Minecraft.int = int -- the integer value of an NBT number | nil
|
||||
Minecraft.ints = ints -- the numbers of an intArray or a list | nil
|
||||
Minecraft.int = int
|
||||
Minecraft.ints = ints
|
||||
|
||||
local function rest(c: any, skip: { [string]: boolean }): { [string]: any }
|
||||
local out, keys = {}, {}
|
||||
@@ -536,8 +502,6 @@ end
|
||||
local FLAT_SKIP = { x = true, y = true, z = true, id = true }
|
||||
local POS_SKIP = { Pos = true, Id = true }
|
||||
|
||||
-- blockEntity(c, style) -> the common shape of one record: style "flat" (MCEdit, Litematica), "pos" (Sponge v1 / v2),
|
||||
-- "data" (Sponge v3)
|
||||
function Minecraft.blockEntity(c: any, style: string): any
|
||||
if type(c) ~= "table" or Nbt.isTag(c) then
|
||||
return nil
|
||||
@@ -550,7 +514,6 @@ function Minecraft.blockEntity(c: any, style: string): any
|
||||
return { pos = { p[1] or 0, p[2] or 0, p[3] or 0 }, id = if type(c.Id) == "string" then c.Id else nil, data = data }
|
||||
end
|
||||
|
||||
-- flatBlockEntity(be, style) -> the record in a flavour's shape (the inverse of blockEntity)
|
||||
function Minecraft.flatBlockEntity(be: any, style: string): any
|
||||
local o = Types.object()
|
||||
local data = if type(be.data) == "table" then be.data else Types.object()
|
||||
|
||||
@@ -1,16 +1,6 @@
|
||||
--!strict
|
||||
-- codecs/model/Polygon: 2D polygons with holes to triangles, for formats that store regions as outlines (Doom map
|
||||
-- sectors, ...). Loops are classified by nesting (a loop inside an odd number of other loops is a hole of the
|
||||
-- smallest loop around it), oriented, each hole bridged to its outer loop at a mutually visible vertex, then the
|
||||
-- result is ear-clipped (reflex-vertex test; a polygon that never yields a clean ear clips its least bad corner so
|
||||
-- every input terminates). New in rosetta, after the classic "ear clipping with hole bridging" method
|
||||
-- (D. Eberly, Triangulation by Ear Clipping); no code taken.
|
||||
--
|
||||
-- local tris = Polygon.triangulate({ { 0, 0, 10, 0, 10, 10, 0, 10 }, { 2, 2, 4, 2, 4, 4, 2, 4 } })
|
||||
-- -- tris = { loop, index, loop, index, loop, index, ... }: three corners per triangle, each a (loop, vertex) pair
|
||||
-- -- (1-based), counter-clockwise
|
||||
--
|
||||
-- Never throws; degenerate loops (fewer than 3 points, zero area) are ignored.
|
||||
-- codecs/model/Polygon: 2D polygons with holes to triangles by hole bridging and ear clipping. New code.
|
||||
-- After D. Eberly, "Triangulation by Ear Clipping" (no code taken).
|
||||
local Polygon = {}
|
||||
|
||||
type Pt = { x: number, y: number, loop: number, index: number }
|
||||
@@ -43,7 +33,6 @@ local function cross(o: Pt, a: Pt, b: Pt): number
|
||||
return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x)
|
||||
end
|
||||
|
||||
-- segments p1-p2 and q1-q2 cross properly (touching at an endpoint does not count)
|
||||
local function crosses(p1: Pt, p2: Pt, q1: Pt, q2: Pt): boolean
|
||||
if (p1.x == q1.x and p1.y == q1.y) or (p1.x == q2.x and p1.y == q2.y) or (p2.x == q1.x and p2.y == q1.y) or (p2.x == q2.x and p2.y == q2.y) then
|
||||
return false
|
||||
@@ -65,8 +54,6 @@ local function visible(m: Pt, v: Pt, rings: { { Pt } }): boolean
|
||||
return true
|
||||
end
|
||||
|
||||
-- splice hole h into ring outer (both oriented: outer counter-clockwise, hole clockwise) at mutually visible
|
||||
-- vertices; others = every ring the bridge must not cross
|
||||
local function bridge(outer: { Pt }, h: { Pt }, others: { { Pt } }): { Pt }
|
||||
local mi = 1
|
||||
for i, p in h do
|
||||
@@ -110,7 +97,6 @@ local function inTri(a: Pt, b: Pt, c: Pt, p: Pt): boolean
|
||||
return cross(a, b, p) >= 0 and cross(b, c, p) >= 0 and cross(c, a, p) >= 0
|
||||
end
|
||||
|
||||
-- ear clipping of one counter-clockwise ring
|
||||
local function clip(ring: { Pt }, out: { number })
|
||||
local pts = table.clone(ring)
|
||||
local guard = #pts * #pts + 16
|
||||
@@ -159,7 +145,6 @@ local function clip(ring: { Pt }, out: { number })
|
||||
end
|
||||
end
|
||||
|
||||
-- triangulate(loops) -> { loop, index, ... }: loops[i] = { x1, y1, x2, y2, ... } (closed implicitly)
|
||||
function Polygon.triangulate(loops: { { number } }): { number }
|
||||
local rings: { { Pt } } = {}
|
||||
local areas: { number } = {}
|
||||
@@ -184,7 +169,6 @@ function Polygon.triangulate(loops: { { number } }): { number }
|
||||
end
|
||||
end
|
||||
end
|
||||
-- nesting: the parent of a ring is the smallest ring containing its first point
|
||||
local n = #rings
|
||||
local depth, parent = table.create(n, 0), table.create(n, 0)
|
||||
for i = 1, n do
|
||||
|
||||
@@ -1,19 +1,8 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/model/Rbx/Binary: the property columns of the Roblox binary format (rbx-dom docs/binary.md): one PROP chunk
|
||||
-- holds a property's values for every instance of a class, by type id, with the format's array transforms: byte
|
||||
-- interleaving (all first bytes, then all second bytes, ...), big-endian integers, zigzag signed integers, "rotated"
|
||||
-- floats (sign bit moved to bit 0), delta-coded referents, and CFrame rotation ids (codecs/model/Rbx). Never throws.
|
||||
--
|
||||
-- local values, pEnd = Binary.decode(typeId, buf, p, limit, n, ctx) -- n plain values (codecs/model/Rbx forms)
|
||||
-- local err = Binary.encode(typeId, values, n, writer, ctx) -- nil, or a message
|
||||
-- Binary.readRefs(buf, p, limit, n) / Binary.writeRefs(writer, refs) -- referent arrays (INST, PRNT)
|
||||
--
|
||||
-- ctx: { ref = function(referent) -> Instance? (decode), refOf = function(Instance?) -> referent (-1 = none),
|
||||
-- shared = { string } (SSTR entries, 1-based, decode), sharedIndex = function(string) -> 0-based index (encode) }.
|
||||
-- decode returns nil, message on bad data ("truncated", "corrupt: ...", "unknown" for a type id it does not know /
|
||||
-- a layout it cannot read, which the format keeps raw).
|
||||
-- codecs/model/Rbx/Binary: the property column codecs of the Roblox binary format (rbx-dom docs/binary.md).
|
||||
-- PROP columns: byte-interleaved big-endian values, zigzag signed integers, rotated floats, delta-coded referents.
|
||||
local Rbx = require("@rosetta/codecs/model/Rbx")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
|
||||
@@ -28,7 +17,6 @@ local floor = math.floor
|
||||
local scratch = buffer.create(8)
|
||||
local TWO32 = 4294967296
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ transforms
|
||||
-- the rotated float encoding: bits rotated left by one (sign in bit 0)
|
||||
local function unrotate(x: number): number
|
||||
writeu32(scratch, 0, x // 2 + (x % 2) * 2147483648)
|
||||
@@ -47,7 +35,6 @@ local function zigzag32(v: number): number
|
||||
return (if v >= 0 then v * 2 else -v * 2 - 1) % TWO32
|
||||
end
|
||||
|
||||
-- n big-endian u32 values interleaved at p (4n bytes)
|
||||
local function u32s(b: buffer, p: number, n: number): { number }
|
||||
local out = table.create(n, 0)
|
||||
local n2, n3 = n * 2, n * 3
|
||||
@@ -70,7 +57,6 @@ local function f32s(b: buffer, p: number, n: number): { number }
|
||||
end
|
||||
return out
|
||||
end
|
||||
-- n zigzag i64 values (8n interleaved bytes), as doubles
|
||||
local function i64s(b: buffer, p: number, n: number): { number }
|
||||
local out = table.create(n, 0)
|
||||
for i = 0, n - 1 do
|
||||
@@ -82,7 +68,6 @@ local function i64s(b: buffer, p: number, n: number): { number }
|
||||
return out
|
||||
end
|
||||
|
||||
-- writers: n values interleaved as big-endian u32 / zigzag i32 / rotated f32 / zigzag i64
|
||||
local function putU32s(w: Bytes.Writer, vals: { number })
|
||||
local n = #vals
|
||||
local p = w:reserve(4 * n)
|
||||
@@ -153,7 +138,6 @@ function Binary.writeRefs(w: Bytes.Writer, refs: { number })
|
||||
putI32s(w, d)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
export type Ctx = {
|
||||
ref: ((number) -> any)?,
|
||||
refOf: ((any) -> number)?,
|
||||
@@ -161,7 +145,6 @@ export type Ctx = {
|
||||
sharedIndex: ((string) -> number)?,
|
||||
}
|
||||
|
||||
-- a length-prefixed string at p: string, next p (nil when it runs past limit)
|
||||
local function str(b: buffer, p: number, limit: number): (string?, number)
|
||||
if p + 4 > limit then
|
||||
return nil, p
|
||||
@@ -211,7 +194,7 @@ local function cframes(b: buffer, p: number, limit: number, n: number): ({ any }
|
||||
return out, p + 12 * n
|
||||
end
|
||||
|
||||
local FIXED: { [number]: number } = { -- bytes per value of the fixed-size types
|
||||
local FIXED: { [number]: number } = {
|
||||
[0x02] = 1,
|
||||
[0x03] = 4,
|
||||
[0x04] = 4,
|
||||
@@ -238,7 +221,6 @@ local FIXED: { [number]: number } = { -- bytes per value of the fixed-size types
|
||||
[0x21] = 8,
|
||||
}
|
||||
|
||||
-- decode(typeId, b, p, limit, n, ctx) -> n values, the end offset | nil, message
|
||||
function Binary.decode(t: number, b: buffer, p: number, limit: number, n: number, ctx: Ctx): ({ any }?, any)
|
||||
if limit > buffer.len(b) or p < 0 or n < 0 then
|
||||
return nil, "corrupt: bad ranges"
|
||||
@@ -531,11 +513,9 @@ function Binary.decode(t: number, b: buffer, p: number, limit: number, n: number
|
||||
return nil, "unknown"
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function num(v: any): number
|
||||
return if type(v) == "number" and v == v then v else 0
|
||||
end
|
||||
-- column c of n array values (missing components 0)
|
||||
local function column(vals: { any }, n: number, c: number): { number }
|
||||
local out = table.create(n, 0)
|
||||
for i = 1, n do
|
||||
@@ -571,8 +551,6 @@ local function hexByte(s: string, i: number): number
|
||||
return tonumber(string.sub(s, 2 * i - 1, 2 * i), 16) or 0
|
||||
end
|
||||
|
||||
-- encode(typeId, values, n, w, ctx) -> nil | message: values[1 .. n] in the codecs/model/Rbx forms (nil entries are
|
||||
-- the type's none / default)
|
||||
function Binary.encode(t: number, vals: { any }, n: number, w: Bytes.Writer, ctx: Ctx): string?
|
||||
if t == 0x01 or t == 0x1D then
|
||||
for i = 1, n do
|
||||
|
||||
@@ -1,40 +1,9 @@
|
||||
--!strict
|
||||
-- codecs/model/Rbx: the Roblox instance tree every Roblox file format maps to (model/rbxm binary rbxm / rbxl,
|
||||
-- model/rbxmx XML rbxmx / rbxlx), the typed property values, the CFrame rotation IDs, and (codecs/model/Rbx/Binary) the
|
||||
-- binary format's property column codecs. Shared here because a format cannot require another one. Written from the
|
||||
-- rbx-dom format notes (docs/binary.md, docs/xml.md) and checked against rbx-dom through rojo / lune. A file library,
|
||||
-- not a Roblox runtime: nothing here creates Instances; a Roblox game reads the tree itself.
|
||||
--
|
||||
-- local tree = Rbx.tree() -- { kind = "rbxtree", roots = {}, place = false, ... }
|
||||
-- local part = Rbx.instance("Part", "Floor") -- { className, name, properties = {}, children = {} }
|
||||
-- Rbx.set(part, "Size", "Vector3", { 64, 1, 64 }) -- properties.Size = { type = "Vector3", value = {...} }
|
||||
-- Rbx.add(tree, part) -- a root; Rbx.add(parentInstance, child) nests
|
||||
-- for inst, depth in Rbx.descendants(tree) do ... end
|
||||
--
|
||||
-- Property values are { type = <name>, value = <v> } with these value forms (arrays follow the Roblox constructor
|
||||
-- argument order, so Vector3.new(table.unpack(v.value)) / CFrame.new(table.unpack(v.value)) rebuild them in Roblox):
|
||||
-- String, BinaryString, ProtectedString, ContentId, Bytecode string (bytes)
|
||||
-- SharedString string (the content; writers deduplicate)
|
||||
-- Bool boolean
|
||||
-- Int32, Int64, Float32, Float64 number (Int64 exact to 2^53)
|
||||
-- Enum, BrickColor, SecurityCapabilities number
|
||||
-- Faces number: bits Right 1, Top 2, Back 4, Left 8, Bottom 16, Front 32
|
||||
-- Axes number: bits X 1, Y 2, Z 4
|
||||
-- UDim { scale, offset } UDim2 { xScale, xOffset, yScale, yOffset } NumberRange { min, max }
|
||||
-- Vector2 / Vector2int16 { x, y } Vector3 / Vector3int16 { x, y, z } Color3 { r, g, b } (0..1)
|
||||
-- Color3uint8 { r, g, b } (0..255) Rect { minX, minY, maxX, maxY } Ray { ox, oy, oz, dx, dy, dz }
|
||||
-- CFrame { x, y, z, r00, r01, r02, r10, r11, r12, r20, r21, r22 } OptionalCFrame: the same, or nil (none)
|
||||
-- NumberSequence { { time, value, envelope } ... } ColorSequence { { time, r, g, b, envelope } ... }
|
||||
-- PhysicalProperties nil (default) | { density, friction, elasticity, frictionWeight, elasticityWeight,
|
||||
-- acousticAbsorption } (decoders fill acousticAbsorption = 1 when the file leaves it out)
|
||||
-- Ref an Instance of the tree, or nil
|
||||
-- UniqueId 32 hex digits: random (16), time (8), index (8)
|
||||
-- Font { family, weight (100..900), style ("Normal" | "Italic"), cachedFaceId? }
|
||||
-- Content nil (none) | string (a URI) | an Instance (object)
|
||||
-- Raw a binary property of a type this library does not know: { typeId, data (the class's whole column),
|
||||
-- index, count }; written back verbatim while the class keeps the same instances in the same order
|
||||
-- XmlRaw an XML property of an unknown type: value = the element (codecs/text/Xml node), written back as it is
|
||||
-- Name is not a property here: it is inst.name. Never throws.
|
||||
-- codecs/model/Rbx: the Roblox instance tree and property values shared by model/rbxm and model/rbxmx.
|
||||
-- Written from the rbx-dom format notes (docs/binary.md, docs/xml.md); checked against rbx-dom through rojo / lune.
|
||||
-- Faces: bits Right 1, Top 2, Back 4, Left 8, Bottom 16, Front 32
|
||||
-- Axes: bits X 1, Y 2, Z 4
|
||||
-- UniqueId: 32 hex digits: random (16), time (8), index (8)
|
||||
|
||||
local Rbx = {}
|
||||
|
||||
@@ -44,20 +13,19 @@ export type Instance = {
|
||||
name: string,
|
||||
properties: { [string]: Value },
|
||||
children: { Instance },
|
||||
parent: Instance?, -- nil for roots
|
||||
referent: string?, -- the file's referent (XML "RBX..." id, binary index) when read; writers make their own
|
||||
parent: Instance?,
|
||||
referent: string?,
|
||||
service: boolean?, -- a service (binary INST object format 1; rbxl roots)
|
||||
}
|
||||
export type Tree = {
|
||||
kind: "rbxtree",
|
||||
roots: { Instance },
|
||||
place: boolean, -- a place (rbxl / rbxlx: the roots are services under the DataModel) or a model
|
||||
place: boolean,
|
||||
metadata: { [string]: string }, -- binary META / XML <Meta> entries (ExplicitAutoJoints, ...)
|
||||
extra: { any }, -- unknown binary chunks { name, data } / unknown top-level XML elements, written back
|
||||
extra: { any },
|
||||
meta: { source: { format: string, [string]: any }?, [string]: any },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ tree
|
||||
function Rbx.tree(place: boolean?): Tree
|
||||
return { kind = "rbxtree", roots = {}, place = place == true, metadata = {}, extra = {}, meta = {} }
|
||||
end
|
||||
@@ -66,7 +34,6 @@ function Rbx.instance(className: string, name: string?): Instance
|
||||
return { className = className, name = name or className, properties = {}, children = {} }
|
||||
end
|
||||
|
||||
-- add(parent, child) -> child: parent is a Tree (child becomes a root) or an Instance
|
||||
function Rbx.add(parent: any, child: Instance): Instance
|
||||
if parent.kind == "rbxtree" then
|
||||
child.parent = nil
|
||||
@@ -78,19 +45,15 @@ function Rbx.add(parent: any, child: Instance): Instance
|
||||
return child
|
||||
end
|
||||
|
||||
-- set(inst, name, type, value): a property (value nil = the type's nil form: Ref none, OptionalCFrame none, ...)
|
||||
function Rbx.set(inst: Instance, name: string, typ: string, value: any)
|
||||
inst.properties[name] = { type = typ, value = value }
|
||||
end
|
||||
|
||||
-- get(inst, name) -> the property's value (not the Value table), nil when absent
|
||||
function Rbx.get(inst: Instance, name: string): any
|
||||
local v = inst.properties[name]
|
||||
return if v then v.value else nil
|
||||
end
|
||||
|
||||
-- descendants(treeOrInstance) -> iterator over (instance, depth) in depth-first order (roots / the instance's children
|
||||
-- at depth 1)
|
||||
function Rbx.descendants(root: any): () -> (Instance?, number?)
|
||||
local stack: { any } = {}
|
||||
local list = if root.kind == "rbxtree" then root.roots else root.children
|
||||
@@ -110,7 +73,6 @@ function Rbx.descendants(root: any): () -> (Instance?, number?)
|
||||
end
|
||||
end
|
||||
|
||||
-- list(tree) -> every instance, depth first
|
||||
function Rbx.list(tree: any): { Instance }
|
||||
local out = {}
|
||||
for inst in Rbx.descendants(tree) do
|
||||
@@ -119,7 +81,6 @@ function Rbx.list(tree: any): { Instance }
|
||||
return out
|
||||
end
|
||||
|
||||
-- find(treeOrInstance, path) -> the instance at a "/"-separated path of names ("Workspace/Baseplate"), or nil
|
||||
function Rbx.find(root: any, path: string): Instance?
|
||||
local cur: any = root
|
||||
for part in string.gmatch(path, "[^/]+") do
|
||||
@@ -139,7 +100,6 @@ function Rbx.find(root: any, path: string): Instance?
|
||||
return if cur.kind == "rbxtree" then nil else cur
|
||||
end
|
||||
|
||||
-- fullName(inst) -> "Workspace.Model.Part" (names joined up to the root)
|
||||
function Rbx.fullName(inst: Instance): string
|
||||
local parts = {}
|
||||
local cur: Instance? = inst
|
||||
@@ -150,12 +110,10 @@ function Rbx.fullName(inst: Instance): string
|
||||
return table.concat(parts, ".")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ CFrame rotation ids
|
||||
-- The binary format stores axis-aligned rotations as one byte: id = 6 * n(RightVector) + n(UpVector) + 1, where n is
|
||||
-- the NormalId of a unit axis (+X 0, +Y 1, +Z 2, -X 3, -Y 4, -Z 5) and the third column is their cross product.
|
||||
local AXES = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }, { -1, 0, 0 }, { 0, -1, 0 }, { 0, 0, -1 } }
|
||||
|
||||
-- the rotation of an id as { r00 .. r22 } (row major), or nil for an id that is not a rotation
|
||||
local ROTATIONS: { [number]: { number } } = {}
|
||||
for a = 0, 5 do
|
||||
for b = 0, 5 do
|
||||
@@ -178,7 +136,6 @@ local function axisIndex(x: number, y: number, z: number): number?
|
||||
return nil
|
||||
end
|
||||
|
||||
-- rotationId(cf) -> the id of the CFrame's rotation (cf = { x, y, z, r00 .. r22 }), or 0 when it is not axis aligned
|
||||
function Rbx.rotationId(cf: { number }): number
|
||||
local a = axisIndex(cf[4], cf[7], cf[10])
|
||||
local b = axisIndex(cf[5], cf[8], cf[11])
|
||||
@@ -193,7 +150,6 @@ function Rbx.rotationId(cf: { number }): number
|
||||
return id
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ values
|
||||
-- binary type ids (rbx-dom docs/binary.md) by type name, and back
|
||||
Rbx.TYPE_IDS = table.freeze({
|
||||
String = 0x01,
|
||||
@@ -241,8 +197,7 @@ for name, id in Rbx.TYPE_IDS do
|
||||
end
|
||||
Rbx.TYPE_NAMES = table.freeze(NAMES)
|
||||
|
||||
-- the value a binary writer uses for an instance without the property (zero / empty / identity; BrickColor 194, the
|
||||
-- Medium stone grey Roblox defaults to; sequences of two keypoints at times 0 and 1)
|
||||
-- BrickColor 194 (Medium stone grey) is Roblox's default
|
||||
local IDENTITY_CF = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 }
|
||||
function Rbx.default(typ: string): any
|
||||
if typ == "String" or typ == "BinaryString" or typ == "ProtectedString" or typ == "ContentId" or typ == "Bytecode" or typ == "SharedString" then
|
||||
@@ -275,7 +230,6 @@ function Rbx.default(typ: string): any
|
||||
return 0
|
||||
end
|
||||
|
||||
-- STRINGS: the string-valued types (one binary type, several XML tags)
|
||||
Rbx.STRINGS = table.freeze({ String = true, BinaryString = true, ProtectedString = true, ContentId = true, Bytecode = true } :: { [string]: boolean })
|
||||
|
||||
return Rbx
|
||||
@@ -1,16 +1,5 @@
|
||||
--!strict
|
||||
-- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each
|
||||
-- format only parses its file: vertex-animation frames as morph targets plus "weights" animations, joint hierarchies
|
||||
-- as Scene nodes plus a Skin (inverse bind matrices), per-vertex joint influences as JOINTS_0 / WEIGHTS_0, and
|
||||
-- keyframed joint TRS tracks as animation channels. New in rosetta.
|
||||
--
|
||||
-- Rig.morph(prim, frames) -- frames[k] = f32 x3 positions: targets[k] = frame k - base
|
||||
-- Rig.morphAnimation(scene, node, #frames, { { name = "run", first = 41, last = 46, fps = 10 } }, "LINEAR")
|
||||
-- local nodes, skin = Rig.skeleton(scene, joints, "world") -- joints = { { name, parent (0 = root), t, r, s? } }
|
||||
-- prim.attributes.JOINTS_0, prim.attributes.WEIGHTS_0 = Rig.influences(lists) -- lists[v] = { j1, w1, j2, w2, ... }
|
||||
-- Rig.animation(scene, "idle", nodes, times, tracks) -- tracks[j] = { translation = {...}, rotation = {...} }
|
||||
--
|
||||
-- Frames, joints and tracks come from parsed files: the helpers check every count they rely on and never throw.
|
||||
-- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...). New code.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Mat4 = require("@rosetta/codecs/model/Mat4")
|
||||
|
||||
@@ -21,18 +10,14 @@ local readf32, writef32, writeu16 = buffer.readf32, buffer.writef32, buffer.writ
|
||||
|
||||
export type Joint = {
|
||||
name: string?,
|
||||
parent: number, -- 1-based index into the joint list, 0 for a root (parents come before their children)
|
||||
parent: number,
|
||||
translation: { number },
|
||||
rotation: { number }, -- quaternion x, y, z, w
|
||||
scale: { number }?,
|
||||
}
|
||||
export type Range = { name: string?, first: number, last: number, fps: number? } -- frames first..last (1-based)
|
||||
export type Track = { translation: { number }?, rotation: { number }?, scale: { number }? } -- flat, one key per time
|
||||
export type Range = { name: string?, first: number, last: number, fps: number? }
|
||||
export type Track = { translation: { number }?, rotation: { number }?, scale: { number }? }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ morph targets
|
||||
-- morph(prim, frames, normals?, base?) -> (): prim.targets[k] = { POSITION = frames[k] - base positions } (and NORMAL
|
||||
-- deltas when normals[k] is given), base = prim.attributes.POSITION (and NORMAL). Every frame buffer must hold as
|
||||
-- many f32 x3 as the base; shorter ones are skipped (false is returned).
|
||||
function Rig.morph(prim: Types.Primitive, frames: { buffer }, normals: { buffer }?): boolean
|
||||
local pos = prim.attributes.POSITION
|
||||
if not pos or pos.type ~= "f32" or pos.components ~= 3 then
|
||||
@@ -70,9 +55,6 @@ function Rig.morph(prim: Types.Primitive, frames: { buffer }, normals: { buffer
|
||||
return ok
|
||||
end
|
||||
|
||||
-- morphAnimation(scene, node, targets, ranges, interpolation?) -> (): one animation per range, a "weights" channel on
|
||||
-- scene.nodes[node] whose key k (at (k - first) / fps seconds) sets target k to 1 and the others to 0 (LINEAR
|
||||
-- blends neighbouring frames, as the games do; default "LINEAR"). Ranges out of 1..targets are clamped / skipped.
|
||||
function Rig.morphAnimation(scene: Types.Scene, node: number, targets: number, ranges: { Range }, interpolation: string?)
|
||||
for _, rg in ranges do
|
||||
local first, last = math.max(1, math.floor(rg.first)), math.min(targets, math.floor(rg.last))
|
||||
@@ -101,9 +83,7 @@ function Rig.morphAnimation(scene: Types.Scene, node: number, targets: number, r
|
||||
end
|
||||
end
|
||||
|
||||
-- normals(pos, count, indices) -> f32 x3 buffer: smooth vertex normals (area-weighted face normals, normalised) of a
|
||||
-- triangle list (indices: 0-based, three per triangle; out-of-range triangles are skipped). For formats whose stored
|
||||
-- normals cannot be used (Quake's precomputed normal table is not redistributable here).
|
||||
-- Quake's precomputed normal table is not redistributable here
|
||||
function Rig.normals(pos: buffer, count: number, indices: { number }): buffer
|
||||
local out = buffer.create(count * 12)
|
||||
local acc = table.create(count * 3, 0)
|
||||
@@ -134,13 +114,11 @@ function Rig.normals(pos: buffer, count: number, indices: { number }): buffer
|
||||
return out
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ skeletons
|
||||
local function trs(j: Joint): { number }
|
||||
return Mat4.compose(j.translation, j.rotation, j.scale)
|
||||
end
|
||||
|
||||
-- angles(x, y, z) -> quaternion { x, y, z, w } of the Euler angles in radians applied x first, then y, then z
|
||||
-- (R = Rz * Ry * Rx: the Quake / Half-Life "AngleQuaternion" convention of MDL bones and SMD skeletons)
|
||||
-- R = Rz * Ry * Rx: the Quake / Half-Life AngleQuaternion convention of MDL bones and SMD skeletons
|
||||
function Rig.angles(x: number, y: number, z: number): { number }
|
||||
local sy, cy = math.sin(z / 2), math.cos(z / 2)
|
||||
local sp, cp = math.sin(y / 2), math.cos(y / 2)
|
||||
@@ -148,10 +126,6 @@ function Rig.angles(x: number, y: number, z: number): { number }
|
||||
return { sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy }
|
||||
end
|
||||
|
||||
-- skeleton(scene, joints, space, root?) -> (joint node indices, skin index, world matrices): one node per joint (TRS relative to its
|
||||
-- parent), parented as listed, roots added to scene.roots (or as children of node `root`); a Skin with the inverse
|
||||
-- bind matrices. space "local": joint TRS are relative to the parent (SMD, MDL); "world": in model space (MD5's
|
||||
-- bind pose), converted to local here. A parent index that does not come earlier makes the joint a root.
|
||||
function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "world", root: number?): ({ number }, number, { { number } })
|
||||
local n = #joints
|
||||
local world: { { number } } = {}
|
||||
@@ -197,9 +171,6 @@ function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "w
|
||||
return nodes, #scene.skins, world
|
||||
end
|
||||
|
||||
-- influences(lists) -> JOINTS_0 (u16 x4), WEIGHTS_0 (f32 x4): lists[v] = { joint, weight, joint, weight, ... } with
|
||||
-- 0-based joint indices (into the skin's joints; a joint listed twice adds up); the four largest weights are kept
|
||||
-- and normalised to sum 1.
|
||||
function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor)
|
||||
local n = #lists
|
||||
local jb, wb = buffer.create(n * 8), buffer.create(n * 16)
|
||||
@@ -210,7 +181,7 @@ function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor)
|
||||
if l[k + 1] > 0 then
|
||||
local same = at[l[k]]
|
||||
if same then
|
||||
same[2] += l[k + 1] -- the same joint twice: one influence
|
||||
same[2] += l[k + 1]
|
||||
else
|
||||
local e = { l[k], l[k + 1] }
|
||||
at[l[k]] = e
|
||||
@@ -233,7 +204,6 @@ function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor)
|
||||
return Scene.accessor(jb, "u16", 4, n), Scene.accessor(wb, "f32", 4, n)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ animations
|
||||
local function floats(t: { number }, count: number, comps: number): Types.Accessor?
|
||||
if #t < count * comps then
|
||||
return nil
|
||||
@@ -245,9 +215,6 @@ local function floats(t: { number }, count: number, comps: number): Types.Access
|
||||
return Scene.accessor(b, "f32", comps, count)
|
||||
end
|
||||
|
||||
-- animation(scene, name, nodes, times, tracks, interpolation?) -> the animation index: tracks[j] (j = index into
|
||||
-- nodes) holds flat translation (x3) / rotation (quaternion x4) / scale (x3) keys, one per time (seconds); tracks
|
||||
-- with too few keys are skipped. Default interpolation "LINEAR".
|
||||
function Rig.animation(scene: Types.Scene, name: string?, nodes: { number }, times: { number }, tracks: { [number]: Track }, interpolation: string?): number
|
||||
local count = #times
|
||||
local input = floats(times, count, 1)
|
||||
|
||||
@@ -1,15 +1,5 @@
|
||||
--!strict
|
||||
-- codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for
|
||||
-- rotations, CUBICSPLINE Hermite splines as glTF 2.0 defines them; times before the first / after the last key hold
|
||||
-- the end values), and the node poses of an animation at a time, for writers of formats that store sampled frames
|
||||
-- (IQM, MD5, BVH, ...). New in rosetta.
|
||||
--
|
||||
-- local sample = Sampler.channel(ch) -- nil for an unreadable channel
|
||||
-- local v = sample(0.5) -- { x, y, z } / { x, y, z, w } / the morph weights
|
||||
-- local times = Sampler.times(anim) -- every key time of the animation, sorted, unique
|
||||
-- local pose = Sampler.pose(scene, anim, 0.5) -- pose[node] = { translation?, rotation?, scale?, weights? }
|
||||
--
|
||||
-- Never throws on bad data: unreadable channels are skipped.
|
||||
-- codecs/model/Sampler: Scene animation sampling, STEP / LINEAR (slerp) / CUBICSPLINE as in glTF 2.0 3.11. New code.
|
||||
local Types = require("@rosetta/Types")
|
||||
|
||||
local Sampler = {}
|
||||
@@ -42,7 +32,6 @@ local function slerp(a: { number }, b: { number }, s: number): { number }
|
||||
return normalize({ a[1] * wa + bx * wb, a[2] * wa + by * wb, a[3] * wa + bz * wb, a[4] * wa + bw * wb })
|
||||
end
|
||||
|
||||
-- channel(ch) -> sample(t) | nil
|
||||
function Sampler.channel(ch: Types.Channel): Sample?
|
||||
local inp, out = ch.input, ch.output
|
||||
if type(inp) ~= "table" or type(out) ~= "table" then
|
||||
@@ -69,7 +58,6 @@ function Sampler.channel(ch: Types.Channel): Sample?
|
||||
times[k] = IN(k - 1, 0)
|
||||
end
|
||||
local oc = out.components
|
||||
-- element e (0-based, of comps values) of the flat output
|
||||
local function get(e: number): { number }
|
||||
local v = table.create(comps) :: { number }
|
||||
for c = 0, comps - 1 do
|
||||
@@ -78,7 +66,7 @@ function Sampler.channel(ch: Types.Channel): Sample?
|
||||
end
|
||||
return v
|
||||
end
|
||||
local function value(k: number): { number } -- key k (1-based)
|
||||
local function value(k: number): { number }
|
||||
return get(if cubic then (k - 1) * 3 + 1 else k - 1)
|
||||
end
|
||||
local rot = ch.path == "rotation"
|
||||
@@ -127,7 +115,6 @@ function Sampler.channel(ch: Types.Channel): Sample?
|
||||
end
|
||||
end
|
||||
|
||||
-- times(anim) -> every key time, sorted and unique
|
||||
function Sampler.times(anim: Types.Animation): { number }
|
||||
local seen: { [number]: boolean } = {}
|
||||
local out: { number } = {}
|
||||
@@ -148,8 +135,6 @@ function Sampler.times(anim: Types.Animation): { number }
|
||||
return out
|
||||
end
|
||||
|
||||
-- pose(scene, anim, t, samplers?) -> pose[node] = { [path] = values } for the animated nodes. samplers: a cache table
|
||||
-- (reuse it across calls for the same animation)
|
||||
function Sampler.pose(_scene: Types.Scene, anim: Types.Animation, t: number, samplers: { [any]: any }?): Pose
|
||||
local cache: { [any]: any } = samplers or {}
|
||||
local pose: Pose = {}
|
||||
|
||||
@@ -1,16 +1,7 @@
|
||||
--!strict
|
||||
-- codecs/model/Vrml/Build: the VRML97 / X3D node graph (codecs/model/Vrml/Parse, codecs/model/Vrml/Xml) to a Scene.
|
||||
-- Written from the specifications; no third-party code. Grouping nodes (Group, Transform with center / scaleOrientation,
|
||||
-- Anchor, Billboard, Collision, StaticGroup, Switch whichChoice, LOD first level, CAD and HAnim groups, Inline through
|
||||
-- the fetch callback) become nodes; a Transform is one TRS node (translation T + C, rotation R * SR, scale S) and, when
|
||||
-- it has a center or scale orientation, an inner node (rotation SR^-1, translation SR^-1 * -C) holding the children.
|
||||
-- Shapes become meshes (shared by USE), Appearance / Material / PhysicalMaterial / UnlitMaterial / TwoSidedMaterial
|
||||
-- materials (Phong terms in material.extras.vrml; solid FALSE -> doubleSided), ImageTexture / MovieTexture
|
||||
-- (uri, data through fetch, repeatS / repeatT), PixelTexture (texture.image), TextureTransform (KHR transform:
|
||||
-- translation / scale / rotation; the center in extras); Viewpoint / OrthoViewpoint -> cameras, DirectionalLight /
|
||||
-- PointLight / SpotLight -> lights; ROUTEs from a TimeSensor through Position- / OrientationInterpolators to a
|
||||
-- Transform's translation / rotation / scale -> animations (key times x cycleInterval). Other nodes are counted in
|
||||
-- meta.source.skipped. Never throws: bad data returns nil, message.
|
||||
-- codecs/model/Vrml/Build: the VRML97 / X3D node graph to a Scene. Written from the specifications; no third-party code.
|
||||
-- A Transform is one TRS node (translation T + C, rotation R * SR, scale S) plus, when it has a center or scale
|
||||
-- orientation, an inner node (rotation SR^-1, translation SR^-1 * -C) holding the children.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Mat4 = require("@rosetta/codecs/model/Mat4")
|
||||
local Fields = require("@rosetta/codecs/model/Vrml/Fields")
|
||||
@@ -23,16 +14,15 @@ local nums, num, vec, bool, str, strs, node, nodes = Fields.nums, Fields.num, Fi
|
||||
local deg = math.deg
|
||||
|
||||
export type Options = Geometry.Options & {
|
||||
fetch: ((uri: string) -> buffer?)?, -- reads textures and Inline files
|
||||
load: ((data: buffer) -> (any, string?))?, -- an Inline file's bytes -> its graph
|
||||
format: string?, -- meta.source.format
|
||||
maxInline: number?, -- Inline nesting (default 8)
|
||||
fetch: ((uri: string) -> buffer?)?,
|
||||
load: ((data: buffer) -> (any, string?))?,
|
||||
format: string?,
|
||||
maxInline: number?,
|
||||
}
|
||||
|
||||
local GROUP = { Group = true, Anchor = true, Billboard = true, Collision = true, StaticGroup = true, CADAssembly = true, CADLayer = true, LayerSet = true, Layer = true, HAnimSegment = true, HAnimSite = true, LOD = true, Switch = true }
|
||||
local TRANSFORM = { Transform = true, CADPart = true, HAnimHumanoid = true, HAnimJoint = true }
|
||||
local CHILDREN = { "children", "skeleton", "segments", "sites", "layers" }
|
||||
-- nodes with nothing to show (not counted as skipped)
|
||||
local QUIET = {
|
||||
WorldInfo = true, NavigationInfo = true, Background = true, TextureBackground = true, Fog = true, TimeSensor = true,
|
||||
PositionInterpolator = true, OrientationInterpolator = true, ScalarInterpolator = true, ColorInterpolator = true,
|
||||
@@ -67,7 +57,6 @@ end
|
||||
local function isIdentityQ(q: { number }): boolean
|
||||
return q[1] == 0 and q[2] == 0 and q[3] == 0
|
||||
end
|
||||
-- the rotation taking unit vector a onto b
|
||||
local function between(a: { number }, b: { number }): { number }
|
||||
local l = math.sqrt(b[1] * b[1] + b[2] * b[2] + b[3] * b[3])
|
||||
if l < 1e-12 then
|
||||
@@ -76,7 +65,6 @@ local function between(a: { number }, b: { number }): { number }
|
||||
local bx, by, bz = b[1] / l, b[2] / l, b[3] / l
|
||||
local d = a[1] * bx + a[2] * by + a[3] * bz
|
||||
if d < -0.999999 then
|
||||
-- opposite: half a turn about any perpendicular axis
|
||||
return if math.abs(a[1]) < 0.9 then { 0, a[3], -a[2], 0 } else { -a[3], 0, a[1], 0 }
|
||||
end
|
||||
local cx, cy, cz = a[2] * bz - a[3] * by, a[3] * bx - a[1] * bz, a[1] * by - a[2] * bx
|
||||
@@ -110,7 +98,6 @@ local function addNode(ctx: Ctx, n: Types.Node, parent: number?): number
|
||||
return i
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ materials
|
||||
local function texture(ctx: Ctx, t: any): number?
|
||||
if not t then
|
||||
return nil
|
||||
@@ -282,7 +269,6 @@ local function material(ctx: Ctx, app: any, solid: boolean): number?
|
||||
return idx
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ nodes
|
||||
local walk: (ctx: Ctx, n: any, parent: number?) -> ()
|
||||
|
||||
local function shape(ctx: Ctx, n: any, parent: number?)
|
||||
@@ -304,7 +290,6 @@ local function shape(ctx: Ctx, n: any, parent: number?)
|
||||
end
|
||||
local count = if prim.indices then prim.indices.count else prim.attributes.POSITION.count
|
||||
if count == 0 then
|
||||
-- nothing to draw (no valid faces / points)
|
||||
ctx.meshes[n] = false
|
||||
return
|
||||
end
|
||||
@@ -491,11 +476,9 @@ function walk(ctx: Ctx, n: any, parent: number?)
|
||||
ctx.depth -= 1
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ animation
|
||||
local TARGET = { set_translation = "translation", translation = "translation", set_rotation = "rotation", rotation = "rotation", set_scale = "scale", scale = "scale" }
|
||||
|
||||
local function animations(ctx: Ctx, routes: { any })
|
||||
-- interpolator -> its TimeSensor
|
||||
local timer: { [any]: any } = {}
|
||||
for _, r in routes do
|
||||
if (r.toField == "set_fraction" or r.toField == "fraction") and r.from.type == "TimeSensor" then
|
||||
@@ -564,7 +547,6 @@ local function animations(ctx: Ctx, routes: { any })
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ scene
|
||||
function Build.scene(graph: any, opts: Options): (Types.Scene?, string?)
|
||||
local scene = S.new()
|
||||
scene.meta.up = "y"
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
--!strict
|
||||
-- codecs/model/Vrml/Fields: typed reads of node fields for codecs/model/Vrml/Build and Geometry. A classic-encoding
|
||||
-- value is a flat array (numbers, strings, booleans, nodes); an X3D XML value is the raw attribute string, parsed here
|
||||
-- on first use (numbers split on blanks / commas, MFString as quoted strings or one unquoted string, booleans
|
||||
-- true / false). Never throws.
|
||||
-- codecs/model/Vrml/Fields: typed reads of VRML / X3D node fields (classic arrays or X3D XML attribute strings).
|
||||
local Fields = {}
|
||||
|
||||
local gmatch, find, sub, byte = string.gmatch, string.find, string.sub, string.byte
|
||||
|
||||
-- quoted strings of an MFString attribute ("a" "b \"c\""), or the text itself when it is not quoted
|
||||
local function mfString(s: string): { string }
|
||||
local out = {}
|
||||
local p = find(s, "[^%s,]")
|
||||
@@ -43,7 +39,6 @@ local function mfString(s: string): { string }
|
||||
return out
|
||||
end
|
||||
|
||||
-- nums(node, name) -> the numbers of a field (booleans as 1 / 0), or nil when absent
|
||||
function Fields.nums(node: any, name: string): { number }?
|
||||
local v = node.fields[name]
|
||||
if v == nil then
|
||||
@@ -93,7 +88,6 @@ function Fields.num(node: any, name: string, default: number): number
|
||||
return if v and type(v[1]) == "number" then v[1] else default
|
||||
end
|
||||
|
||||
-- vec(node, name, default) -> the first #default numbers of a field (the default when the field is shorter)
|
||||
function Fields.vec(node: any, name: string, default: { number }): { number }
|
||||
local v = Fields.nums(node, name)
|
||||
if not v or #v < #default then
|
||||
@@ -147,7 +141,6 @@ function Fields.str(node: any, name: string, default: string?): string?
|
||||
return default
|
||||
end
|
||||
|
||||
-- nodes(node, name) -> the nodes of an SFNode / MFNode field
|
||||
function Fields.nodes(node: any, name: string): { any }
|
||||
local v = node.fields[name]
|
||||
local out = {}
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
--!strict
|
||||
-- codecs/model/Vrml/Geometry: VRML97 / X3D geometry nodes to Scene primitives. Written from the specifications; no
|
||||
-- third-party code. IndexedFaceSet (coord / normal / color / texCoord with their own indices, per-vertex or per-face
|
||||
-- normals and colours, ccw, convex polygons fan-triangulated or kept as "polygons"), the X3D triangle / quad sets
|
||||
-- (IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, TriangleFanSet, IndexedTriangleStripSet,
|
||||
-- TriangleStripSet, IndexedQuadSet, QuadSet), ElevationGrid, Extrusion (spine-aligned cross sections, scale,
|
||||
-- orientation, caps), IndexedLineSet / LineSet ("lines"), PointSet ("points"), and the primitives Box, Sphere, Cone,
|
||||
-- Cylinder tessellated with normals and the specification's texture mapping. Texture coordinates get t flipped to
|
||||
-- glTF's top-left origin unless flipV = false. Never throws: returns nil, message for bad data.
|
||||
-- codecs/model/Vrml/Geometry: VRML97 / X3D geometry nodes to Scene primitives. New code, from the specifications.
|
||||
-- Texture t is flipped to glTF's top-left origin unless flipV = false.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Fields = require("@rosetta/codecs/model/Vrml/Fields")
|
||||
|
||||
@@ -35,7 +29,6 @@ local function u32(list: { number }): Types.Accessor
|
||||
return a
|
||||
end
|
||||
|
||||
-- the colour node's values and component count (Color: 3, ColorRGBA: 4)
|
||||
local function colors(n: any): ({ number }?, number)
|
||||
local c = node(n, "color")
|
||||
if not c then
|
||||
@@ -50,14 +43,11 @@ local function points(n: any, field: string, sub: string): { number }?
|
||||
return if c then nums(c, sub) or {} else nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ polygon meshes
|
||||
-- Mesh input: faces as corner lists of coordinate indices (0-based) plus, per attribute, a per-corner index list (nil:
|
||||
-- the coordinate index) or per-face indices.
|
||||
type PolyIn = {
|
||||
P: { number }, -- coordinates, 3 per point
|
||||
corners: { number }, -- coordinate index per corner, face after face
|
||||
sizes: { number }, -- corners per face
|
||||
N: { number }?, nIdx: { number }?, nFace: boolean?, -- normals; per-corner or per-face indices (nil: identity)
|
||||
P: { number },
|
||||
corners: { number },
|
||||
sizes: { number },
|
||||
N: { number }?, nIdx: { number }?, nFace: boolean?,
|
||||
C: { number }?, cComps: number?, cIdx: { number }?, cFace: boolean?,
|
||||
T: { number }?, tIdx: { number }?,
|
||||
ccw: boolean,
|
||||
@@ -68,7 +58,6 @@ local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?)
|
||||
local np = #P // 3
|
||||
local N, C, T = m.N, m.C, m.T
|
||||
local cc = m.cComps or 3
|
||||
-- the attribute index of corner k (1-based) in face f (1-based)
|
||||
local function idx(list: { number }?, perFace: boolean?, f: number, k: number, c: number): number
|
||||
if perFace then
|
||||
return if list and #list > 0 then (list[f] or 0) else f - 1
|
||||
@@ -77,7 +66,7 @@ local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?)
|
||||
end
|
||||
local simple = (N == nil or (not m.nFace and (m.nIdx == nil or #m.nIdx == 0))) and (C == nil or (not m.cFace and (m.cIdx == nil or #m.cIdx == 0))) and (T == nil or m.tIdx == nil or #m.tIdx == 0)
|
||||
local vkey: { [string]: number } = {}
|
||||
local vsrc: { { number } } = {} -- per output vertex: coord, normal, colour, texcoord indices
|
||||
local vsrc: { { number } } = {}
|
||||
local out: { number } = {}
|
||||
local outSizes: { number } = {}
|
||||
local k = 0
|
||||
@@ -179,7 +168,6 @@ local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?)
|
||||
return prim
|
||||
end
|
||||
|
||||
-- split a -1 separated index list into corners + sizes
|
||||
local function split(list: { number }): ({ number }, { number })
|
||||
local corners, sizes = {}, {}
|
||||
local run = 0
|
||||
@@ -230,7 +218,6 @@ local function faceSet(n: any, o: Options, maxV: number): (Types.Primitive?, str
|
||||
return polyMesh(m, o, maxV)
|
||||
end
|
||||
|
||||
-- the X3D triangle / quad sets: faces from index (or vertex order) and fan / strip counts
|
||||
local function triSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?)
|
||||
local t = n.type
|
||||
local P = points(n, "coord", "point") or {}
|
||||
@@ -359,7 +346,6 @@ local function elevationGrid(n: any, o: Options, maxV: number): (Types.Primitive
|
||||
return polyMesh(m, o, maxV)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ Extrusion
|
||||
local function cross(a: { number }, b: { number }): { number }
|
||||
return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] }
|
||||
end
|
||||
@@ -489,7 +475,6 @@ local function extrusion(n: any, o: Options, maxV: number): (Types.Primitive?, s
|
||||
return polyMesh({ P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true) }, o, maxV)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ lines, points
|
||||
local function lines(n: any, maxV: number): (any, string?)
|
||||
local P = points(n, "coord", "point") or {}
|
||||
local np = #P // 3
|
||||
@@ -583,8 +568,6 @@ local function pointSet(n: any, maxV: number): (any, string?)
|
||||
return { attributes = attrs, mode = "points" }
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ primitives
|
||||
-- a primitive from flat arrays (positions, normals, uvs with the specification's bottom-left origin, triangles)
|
||||
local function direct(P: { number }, N: { number }, T: { number }, I: { number }, o: Options): Types.Primitive
|
||||
local nv = #P // 3
|
||||
if o.flipV ~= false then
|
||||
@@ -628,8 +611,7 @@ local function box(n: any, o: Options): Types.Primitive
|
||||
return direct(P, N, T, I, o)
|
||||
end
|
||||
|
||||
-- a ring of segs + 1 vertices (the seam doubled for the texture) at height y, radius r; s starts at the back (-z)
|
||||
-- and runs counter-clockwise seen from +y
|
||||
-- a ring of segs + 1 vertices (seam doubled); s starts at the back (-z) and runs counter-clockwise seen from +y
|
||||
local function ring(P: { number }, N: { number }?, T: { number }?, segs: number, y: number, r: number, t: number, ny: number?, nr: number?)
|
||||
for i = 0, segs do
|
||||
local a = 2 * pi * i / segs
|
||||
@@ -649,7 +631,6 @@ local function ring(P: { number }, N: { number }?, T: { number }?, segs: number,
|
||||
end
|
||||
end
|
||||
|
||||
-- a cap disc at height y facing ny (+1 / -1)
|
||||
local function cap(P: { number }, N: { number }, T: { number }, I: { number }, segs: number, y: number, r: number, ny: number)
|
||||
local b = #P // 3
|
||||
for i = 0, segs - 1 do
|
||||
@@ -679,7 +660,6 @@ local function cap(P: { number }, N: { number }, T: { number }, I: { number }, s
|
||||
end
|
||||
end
|
||||
|
||||
-- quads between two rings of segs + 1 vertices starting at a (lower) and b (upper)
|
||||
local function band(I: { number }, a: number, b: number, segs: number)
|
||||
for i = 0, segs - 1 do
|
||||
table.insert(I, a + i)
|
||||
@@ -727,9 +707,6 @@ local function cylinder(n: any, o: Options, segs: number, cone: boolean): Types.
|
||||
return direct(P, N, T, I, o)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ dispatch
|
||||
-- primitive(geometryNode, opts) -> Primitive | nil, message | nil, nil (a node type without geometry here);
|
||||
-- the second value of a success is the node's solid flag
|
||||
function Geometry.primitive(n: any, o: Options): (Types.Primitive?, any)
|
||||
local t = n.type
|
||||
local maxV = o.maxVertices or 2 ^ 24
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
--!strict
|
||||
-- codecs/model/Vrml/Parse: the VRML97 (ISO/IEC 14772-1) / X3D classic VRML encoding (ISO/IEC 19776-2) parser, into
|
||||
-- the node graph codecs/model/Vrml/Build reads. Written from the specifications; no third-party code. Field types are
|
||||
-- not known without the node schemas, so a field value is kept as a flat array of what the file wrote (numbers,
|
||||
-- strings, booleans, nodes) and the builder reads it as the type it expects. Handles comments, DEF / USE, PROTO
|
||||
-- (instances are expanded: IS fields take the instance's values or the declared defaults; nested PROTOs, ROUTEs inside
|
||||
-- bodies), EXTERNPROTO (instances stay nodes of that type, without a body), Script / shader interface declarations,
|
||||
-- ROUTE, and the X3D header statements (PROFILE, COMPONENT, META, UNIT, IMPORT, EXPORT). Never throws: errors are
|
||||
-- returned as nil, message ("line N: ...").
|
||||
-- codecs/model/Vrml/Parse: the VRML97 (ISO/IEC 14772-1) / X3D classic (ISO/IEC 19776-2) encoding parser.
|
||||
-- Written from the specifications; no third-party code.
|
||||
local Parse = {}
|
||||
|
||||
export type Node = { type: string, def: string?, fields: { [string]: any } }
|
||||
@@ -15,13 +9,12 @@ export type Proto = { name: string, fields: { [string]: any }, body: { Node }, r
|
||||
export type Graph = {
|
||||
roots: { Node },
|
||||
routes: { Route },
|
||||
header: { [string]: any }, -- version ("2.0" / "3.3" ...), encoding, x3d (boolean), profile
|
||||
meta: { [string]: string }, -- META / WorldInfo statements
|
||||
header: { [string]: any },
|
||||
meta: { [string]: string },
|
||||
components: { string },
|
||||
units: { [string]: { name: string, factor: number } },
|
||||
protos: { [string]: Proto },
|
||||
}
|
||||
-- an IS reference in a PROTO body: fields[name] = { is = "protoField" }
|
||||
export type IsRef = { is: string }
|
||||
|
||||
local find, sub, byte, match, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch
|
||||
@@ -31,7 +24,6 @@ local MAX_DEPTH = 200
|
||||
local DECL = { field = true, exposedField = true, eventIn = true, eventOut = true, initializeOnly = true, inputOutput = true, inputOnly = true, outputOnly = true }
|
||||
local HAS_VALUE = { field = true, exposedField = true, initializeOnly = true, inputOutput = true }
|
||||
|
||||
-- copy(node, values, defaults, memo) -> a PROTO body node with its IS fields replaced (shared nodes stay shared)
|
||||
local function copy(node: Node, values: { [string]: any }, defaults: { [string]: any }, memo: { [any]: any }): Node
|
||||
local done = memo[node]
|
||||
if done then
|
||||
@@ -60,7 +52,6 @@ local function copy(node: Node, values: { [string]: any }, defaults: { [string]:
|
||||
return out
|
||||
end
|
||||
|
||||
-- expand(proto, values, def, routes) -> the instance's node (the body's first node), or nil for an EXTERNPROTO
|
||||
function Parse.expand(proto: Proto, values: { [string]: any }, def: string?, routes: { Route }?): Node?
|
||||
if proto.extern or #proto.body == 0 then
|
||||
return nil
|
||||
@@ -125,8 +116,6 @@ function Parse.parse(text: string): (Graph?, string?)
|
||||
end
|
||||
end
|
||||
|
||||
-- the lexer: skip blanks, commas and comments; returns the next token kind and value
|
||||
-- kinds: "num", "str", "id", "{", "}", "[", "]", ".", "eof"
|
||||
local function skip()
|
||||
while true do
|
||||
local q = find(text, "[^%s,]", p)
|
||||
@@ -189,7 +178,6 @@ function Parse.parse(text: string): (Graph?, string?)
|
||||
p += 1
|
||||
return ".", nil
|
||||
end
|
||||
-- +inf / -nan style words: read the word
|
||||
local _, we = find(text, "^[^%s,%[%]{}#\"]+", p)
|
||||
local w = sub(text, p, we)
|
||||
p = (we :: number) + 1
|
||||
@@ -221,12 +209,10 @@ function Parse.parse(text: string): (Graph?, string?)
|
||||
local parseProto: (extern: boolean) -> ()
|
||||
local parseRoute: () -> ()
|
||||
|
||||
-- a field value (after its name): an array of numbers / strings / booleans / nodes
|
||||
local function value(): any
|
||||
local k, val = token()
|
||||
if k == "[" then
|
||||
local out = {}
|
||||
-- fast path: a bracket of plain numbers (big coordinate arrays)
|
||||
local close = find(text, "]", p, true)
|
||||
if close then
|
||||
local seg = sub(text, p, close - 1)
|
||||
@@ -298,7 +284,6 @@ function Parse.parse(text: string): (Graph?, string?)
|
||||
return {}
|
||||
end
|
||||
|
||||
-- the fields of a node body, up to its "}"
|
||||
local function body(node: Node)
|
||||
while not failure do
|
||||
local k, name = token()
|
||||
@@ -445,7 +430,7 @@ function Parse.parse(text: string): (Graph?, string?)
|
||||
end
|
||||
end
|
||||
if extern then
|
||||
value() -- the url list
|
||||
value()
|
||||
protos[name] = proto
|
||||
return
|
||||
end
|
||||
@@ -478,7 +463,6 @@ function Parse.parse(text: string): (Graph?, string?)
|
||||
protos[name] = proto
|
||||
end
|
||||
|
||||
-- statements
|
||||
while not failure do
|
||||
local k, w = token()
|
||||
if k == "eof" then
|
||||
|
||||
@@ -1,15 +1,5 @@
|
||||
--!strict
|
||||
-- codecs/model/Vrml/Write: a Scene to VRML97 (`#VRML V2.0 utf8`), X3D classic (`#X3D V3.3 utf8`) or X3D XML text,
|
||||
-- for model/vrml and model/x3d. New code. Every node becomes a DEF'd Transform (a matrix is decomposed into TRS;
|
||||
-- shear is lost), each primitive a Shape: triangles / polygons / strips / fans -> IndexedFaceSet (coord, normal,
|
||||
-- texCoord with t flipped back unless flipV = false, color; per-vertex, ccw, solid = not doubleSided), lines ->
|
||||
-- IndexedLineSet, points -> PointSet; a mesh used twice is written once and USE'd. Materials -> Appearance / Material
|
||||
-- (diffuse = baseColor, transparency = 1 - alpha, emissive, shininess from roughness, the Phong terms of
|
||||
-- material.extras.vrml when present) with an ImageTexture (the texture bytes go into opts.files named after the uri or
|
||||
-- opts.name, else url = texture.uri). Cameras -> Viewpoint (X3D: OrthoViewpoint for orthographic ones), lights ->
|
||||
-- Directional / Point / SpotLight, animations (translation / rotation / scale channels) -> a TimeSensor and
|
||||
-- Position / OrientationInterpolators with ROUTEs (cubic splines keep their values, weights channels are dropped).
|
||||
-- Never throws: returns nil, message.
|
||||
-- codecs/model/Vrml/Write: a Scene to VRML97 (`#VRML V2.0 utf8`), X3D classic (`#X3D V3.3 utf8`) or X3D XML. New code.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Mat4 = require("@rosetta/codecs/model/Mat4")
|
||||
local Flatten = require("@rosetta/codecs/model/MeshFlatten")
|
||||
@@ -19,8 +9,6 @@ local Write = {}
|
||||
|
||||
export type Options = { encoding: ("vrml97" | "x3dv" | "xml")?, files: { [string]: any }?, name: string?, flipV: boolean? }
|
||||
|
||||
-- a written node: fields in order, each { name, kind, value }; kinds: "sf" / "mf" (numbers; mf groups `per` numbers
|
||||
-- per line), "bool", "str", "mstr" (MFString), "node", "nodes"
|
||||
type WNode = { type: string, def: string?, use: string?, fields: { { any } } }
|
||||
|
||||
local format, concat = string.format, table.concat
|
||||
@@ -45,7 +33,6 @@ local function F(n: WNode, name: string, kind: string, value: any, per: number?)
|
||||
table.insert(n.fields, { name, kind, value, per })
|
||||
end
|
||||
|
||||
-- names: valid, unique DEF names
|
||||
local function namer(): (string?, string) -> string
|
||||
local used: { [string]: boolean } = {}
|
||||
return function(name: string?, fallback: string): string
|
||||
@@ -63,7 +50,6 @@ local function namer(): (string?, string) -> string
|
||||
end
|
||||
end
|
||||
|
||||
-- axis-angle of a quaternion (x, y, z, w)
|
||||
local function axisAngle(q: { number }): { number }
|
||||
local x, y, z, w = q[1], q[2], q[3], q[4]
|
||||
local l = math.sqrt(x * x + y * y + z * z + w * w)
|
||||
@@ -77,7 +63,6 @@ local function axisAngle(q: { number }): { number }
|
||||
return { x / s, y / s, z / s, 2 * math.acos(math.clamp(w, -1, 1)) }
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ geometry
|
||||
local function values(acc: any): { number }?
|
||||
return (Flatten.numbers(acc))
|
||||
end
|
||||
@@ -145,7 +130,6 @@ local function faceSet(prim: any, doubleSided: boolean, o: Options, x3d: boolean
|
||||
return g, nil
|
||||
end
|
||||
|
||||
-- Coordinate from POSITION, Color / ColorRGBA from COLOR_0 (lines and points)
|
||||
local function coordNode(prim: any): (WNode?, number)
|
||||
local pos = values(prim.attributes.POSITION)
|
||||
if not pos then
|
||||
@@ -241,7 +225,6 @@ local function pointSet(prim: any, x3d: boolean): (WNode?, string?)
|
||||
return g, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ materials
|
||||
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2" }
|
||||
|
||||
local function textureUrl(scene: any, i: number, o: Options, written: { [number]: string }): string?
|
||||
@@ -347,7 +330,6 @@ local function appearance(scene: any, mi: number, o: Options, written: { [number
|
||||
return app
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ the tree
|
||||
function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, string?)
|
||||
local x3d = o.encoding == "x3dv" or o.encoding == "xml"
|
||||
local name = namer()
|
||||
@@ -360,7 +342,6 @@ function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, stri
|
||||
local function shapes(mi: number): { WNode }
|
||||
local done = meshShapes[mi]
|
||||
if done then
|
||||
-- USE the shapes written before
|
||||
local out = {}
|
||||
for _, s in done do
|
||||
table.insert(out, { type = "Shape", use = s.def, fields = {} })
|
||||
@@ -489,7 +470,6 @@ function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, stri
|
||||
local roots: { WNode } = {}
|
||||
local list = scene.roots
|
||||
if type(list) ~= "table" or #list == 0 then
|
||||
-- no roots: every node without a parent
|
||||
local child = {}
|
||||
for _, n in scene.nodes do
|
||||
for _, c in n.children or {} do
|
||||
@@ -517,7 +497,6 @@ function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, stri
|
||||
end
|
||||
end
|
||||
|
||||
-- animations: a TimeSensor per animation, an interpolator per channel
|
||||
local routes: { { string } } = {}
|
||||
for ai, anim in scene.animations or {} do
|
||||
local tmax = 0
|
||||
@@ -577,14 +556,12 @@ function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, stri
|
||||
return roots, routes, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ serializers
|
||||
local function numbers(vals: { number }, per: number?, indent: string): string
|
||||
local out = table.create(#vals)
|
||||
for i, v in vals do
|
||||
out[i] = fmt(v)
|
||||
end
|
||||
if per == 0 then
|
||||
-- index lists: one face per line
|
||||
local lines, cur = {}, {}
|
||||
for i, v in vals do
|
||||
table.insert(cur, out[i])
|
||||
@@ -665,7 +642,6 @@ local function classic(roots: { WNode }, routes: { { string } }, x3d: boolean):
|
||||
return concat(out, "\n") .. "\n"
|
||||
end
|
||||
|
||||
-- the containerField a child element needs when it is not its type's default
|
||||
local DEFAULT = { Appearance = "appearance", Material = "material", ImageTexture = "texture", TextureTransform = "textureTransform", Coordinate = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", TextureCoordinate = "texCoord", IndexedFaceSet = "geometry", IndexedLineSet = "geometry", PointSet = "geometry" }
|
||||
|
||||
local function xml(roots: { WNode }, routes: { { string } }): (string?, string?)
|
||||
@@ -735,7 +711,6 @@ local function xml(roots: { WNode }, routes: { { string } }): (string?, string?)
|
||||
return s, nil
|
||||
end
|
||||
|
||||
-- text(scene, opts) -> the file text
|
||||
function Write.text(scene: any, o: Options): (string?, string?)
|
||||
local roots, routes, err = Write.graph(scene, o)
|
||||
if not roots or not routes then
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
--!strict
|
||||
-- codecs/model/Vrml/Xml: the X3D XML encoding (ISO/IEC 19776-1) to the node graph of codecs/model/Vrml/Parse, so one
|
||||
-- builder serves .wrl, .x3dv and .x3d. Written from the specification; no third-party code. Elements are nodes;
|
||||
-- attributes stay raw strings (the builder parses them as the type it expects); child nodes go into their
|
||||
-- containerField (or the default field of their type: geometry, appearance, material, coord, ...); DEF / USE; ROUTE;
|
||||
-- ProtoDeclare (ProtoInterface fields with value attributes or child nodes, ProtoBody, IS / connect) and
|
||||
-- ProtoInstance (fieldValue) are expanded through Parse.expand; ExternProtoDeclare instances stay plain nodes; head /
|
||||
-- meta, UNIT, component and the profile go into the graph header. Never throws.
|
||||
-- codecs/model/Vrml/Xml: the X3D XML encoding (ISO/IEC 19776-1) to the Vrml/Parse node graph. New code.
|
||||
local Xml = require("@rosetta/codecs/text/Xml")
|
||||
local Parse = require("@rosetta/codecs/model/Vrml/Parse")
|
||||
|
||||
@@ -65,7 +59,6 @@ function VXml.graph(doc: Xml.Node): (Parse.Graph?, string?)
|
||||
end
|
||||
local declare: (el: Xml.Node, extern: boolean) -> ()
|
||||
|
||||
-- the child elements of a node into its fields
|
||||
local function children(el: Xml.Node, node: Parse.Node)
|
||||
for _, ch in el.children do
|
||||
if type(ch) ~= "table" or string.sub(ch.name, 1, 1) == "#" then
|
||||
@@ -100,7 +93,6 @@ function VXml.graph(doc: Xml.Node): (Parse.Graph?, string?)
|
||||
end
|
||||
end
|
||||
|
||||
-- a field value of ProtoInterface / fieldValue: the value attribute, or the child nodes
|
||||
local function fieldValue(el: Xml.Node): any
|
||||
if el.attrs.value ~= nil then
|
||||
return el.attrs.value
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
--!strict
|
||||
-- codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML,
|
||||
-- .x3dv classic): one parser for the classic encoding (codecs/model/Vrml/Parse), one for the XML encoding
|
||||
-- (codecs/model/Vrml/Xml over codecs/text/Xml), both into the same node graph, and one builder from the graph to a
|
||||
-- Scene (codecs/model/Vrml/Build, codecs/model/Vrml/Geometry). Gzipped files (.wrz / .x3dz / .x3dvz) are inflated
|
||||
-- first. New code, written from ISO/IEC 14772-1 (VRML97), ISO/IEC 19775-1 (X3D) and its encodings 19776-1 / -2.
|
||||
--
|
||||
-- local graph, err = Vrml.graph(bytes) -- classic or XML, by content
|
||||
-- local scene, err2 = Vrml.decode(bytes, { format = "vrml", files = { ["tex.png"] = png } })
|
||||
-- codecs/model/Vrml: VRML97 / X3D scene-graph engine (classic and XML encodings) for model/vrml and model/x3d.
|
||||
-- VRML97 ISO/IEC 14772-1, X3D ISO/IEC 19775-1, encodings ISO/IEC 19776-1 (XML) / -2 (classic). New code.
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Deflate = require("@rosetta/codecs/compress/Deflate")
|
||||
@@ -21,12 +15,11 @@ local Vrml = {}
|
||||
export type Graph = Parse.Graph
|
||||
export type Node = Parse.Node
|
||||
export type Options = Build.Options & {
|
||||
files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string)
|
||||
resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths)
|
||||
maxBytes: number?, -- the inflated size of a gzipped file (default 2^28)
|
||||
files: { [string]: any }?,
|
||||
resolve: ((uri: string) -> any)?,
|
||||
maxBytes: number?,
|
||||
}
|
||||
|
||||
-- the bytes as text: gzip inflated, UTF-8 BOM dropped
|
||||
local function text(data: buffer | string, maxBytes: number?): (string?, Err.Err?)
|
||||
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
if buffer.len(b) >= 2 and buffer.readu8(b, 0) == 0x1F and buffer.readu8(b, 1) == 0x8B then
|
||||
@@ -57,7 +50,6 @@ local function code(msg: string): string
|
||||
return Err.CORRUPT
|
||||
end
|
||||
|
||||
-- parse(text) -> the graph of a classic-encoding file (VRML97 / .x3dv)
|
||||
function Vrml.parse(s: string): (Graph?, Err.Err?)
|
||||
local g, msg = Parse.parse(s)
|
||||
if not g then
|
||||
@@ -66,7 +58,6 @@ function Vrml.parse(s: string): (Graph?, Err.Err?)
|
||||
return g, nil
|
||||
end
|
||||
|
||||
-- parseXml(text | XML document) -> the graph of an X3D XML file
|
||||
function Vrml.parseXml(src: any): (Graph?, Err.Err?)
|
||||
local doc = src
|
||||
if type(src) == "string" then
|
||||
@@ -87,7 +78,6 @@ function Vrml.parseXml(src: any): (Graph?, Err.Err?)
|
||||
return g, nil
|
||||
end
|
||||
|
||||
-- graph(bytes, opts?) -> the graph of either encoding (XML when the text starts with "<"); binary X3D is UNSUPPORTED
|
||||
function Vrml.graph(data: buffer | string, opts: Options?): (Graph?, Err.Err?)
|
||||
local s, err = text(data, opts and opts.maxBytes)
|
||||
if not s then
|
||||
@@ -103,7 +93,6 @@ function Vrml.graph(data: buffer | string, opts: Options?): (Graph?, Err.Err?)
|
||||
return Vrml.parse(s)
|
||||
end
|
||||
|
||||
-- fetcher(opts) -> fetch(uri) -> buffer?: opts.files (uri or base name) / opts.resolve
|
||||
function Vrml.fetcher(opts: Options?): (uri: string) -> buffer?
|
||||
return function(uri: string): buffer?
|
||||
if not opts then
|
||||
@@ -121,7 +110,6 @@ function Vrml.fetcher(opts: Options?): (uri: string) -> buffer?
|
||||
end
|
||||
end
|
||||
|
||||
-- build(graph, opts?) -> Scene
|
||||
function Vrml.build(graph: Graph, opts: Options?): (Types.Scene?, Err.Err?)
|
||||
local o: any = table.clone(opts or {})
|
||||
o.fetch = o.fetch or Vrml.fetcher(opts)
|
||||
@@ -136,7 +124,6 @@ function Vrml.build(graph: Graph, opts: Options?): (Types.Scene?, Err.Err?)
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
-- decode(bytes, opts?) -> Scene: graph + build
|
||||
function Vrml.decode(data: buffer | string, opts: Options?): (Types.Scene?, Err.Err?)
|
||||
local g, err = Vrml.graph(data, opts)
|
||||
if not g then
|
||||
@@ -145,7 +132,6 @@ function Vrml.decode(data: buffer | string, opts: Options?): (Types.Scene?, Err.
|
||||
return Vrml.build(g, opts)
|
||||
end
|
||||
|
||||
-- encode(scene, opts?) -> text: opts.encoding "vrml97" (default) / "x3dv" / "xml"; texture bytes go into opts.files
|
||||
function Vrml.encode(scene: Types.Scene, opts: Write.Options?): (string?, Err.Err?)
|
||||
if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "needs a Scene")
|
||||
|
||||
Reference in new issue
Block a user