model formats (mca..x3d): comments are specs only
This commit is contained in:
1 parent
0bd7b87d2b
commit
b952c10222
49 files changed
+310
-936
No files matched your search
@@ -1,9 +1,7 @@
|
||||
--!strict
|
||||
-- model/mca/Chunk: the blocks of one Anvil chunk's NBT, from the Minecraft wiki "Chunk format" page, in the three
|
||||
-- layouts it has had: 1.18+ (root sections[] with block_states { palette, data }, non-spanning packing, at least
|
||||
-- 4 bits, yPos), 1.13 - 1.17 (Level.Sections[] with Palette + BlockStates, spanning before DataVersion 2529 =
|
||||
-- 20w17a), and before 1.13 (Level.Sections[] with Blocks / Add / Data nibble arrays, numeric ids through
|
||||
-- codecs/model/Minecraft legacyState). Each section is 16 x 16 x 16 cells in Minecraft's order (x, then z, then y).
|
||||
-- model/mca/Chunk: an Anvil chunk's blocks (Minecraft wiki "Chunk format"): 1.18+ sections[] block_states
|
||||
-- (non-spanning, >= 4 bits); 1.13 - 1.17 Level.Sections[] Palette + BlockStates (spanning before DataVersion 2529 =
|
||||
-- 20w17a); pre-1.13 Blocks / Add / Data nibble arrays. A section is 16 x 16 x 16 cells, x then z then y.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Nbt = require("@rosetta/codecs/text/Nbt")
|
||||
local Mc = require("@rosetta/codecs/model/Minecraft")
|
||||
@@ -12,14 +10,14 @@ local Chunk = {}
|
||||
|
||||
local Packed = Mc.Packed
|
||||
|
||||
export type Section = { y: number, states: { string }, cells: buffer } -- cells: u16 per cell, 4096, x-z-y order
|
||||
export type Section = { y: number, states: { string }, cells: buffer } -- u16 per cell, 4096, x-z-y order
|
||||
export type Blocks = {
|
||||
x: number, -- chunk coordinates (xPos / zPos)
|
||||
x: number, -- xPos / zPos
|
||||
z: number,
|
||||
dataVersion: number?,
|
||||
sections: { Section },
|
||||
blockEntities: { any }, -- the chunk's records as they are (absolute x, y, z)
|
||||
entities: { any }, -- entities stored in the chunk (before 1.17)
|
||||
blockEntities: { any }, -- absolute x, y, z
|
||||
entities: { any }, -- before 1.17
|
||||
}
|
||||
|
||||
local function int(v: any): number?
|
||||
@@ -31,7 +29,6 @@ local function list(v: any): { any }
|
||||
return if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then v else {}
|
||||
end
|
||||
|
||||
-- a palette section (1.13+): states from the palette compounds, cells from the packed array
|
||||
local function paletted(y: number, palette: { any }, data: any, minBits: number, spanning: boolean): (Section?, string?)
|
||||
local states = table.create(#palette) :: { string }
|
||||
for i, c in palette do
|
||||
@@ -58,7 +55,6 @@ local function paletted(y: number, palette: { any }, data: any, minBits: number,
|
||||
return { y = y, states = states, cells = cells }, nil
|
||||
end
|
||||
|
||||
-- blocks(root) -> Blocks | nil, message: the sections of a decoded chunk
|
||||
function Chunk.blocks(root: any): (Blocks?, string?)
|
||||
if type(root) ~= "table" or not Types.isObject(root) then
|
||||
return nil, "chunk NBT is not a compound"
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
--!strict
|
||||
-- model/mca/Lz4Block: the lz4-java LZ4BlockOutputStream framing Minecraft (24w04a+) uses for compression type 4
|
||||
-- chunks, from lz4-java's LZ4BlockOutputStream source: blocks of "LZ4Block", a token (method 0x10 raw / 0x20 LZ4 |
|
||||
-- level), compressed and decompressed lengths and an XXH32 checksum (little-endian i32s; not verified), then the
|
||||
-- block, each block independent; an empty block ends the stream. The blocks decode through codecs/compress/Lz4.
|
||||
-- model/mca/Lz4Block: lz4-java LZ4BlockOutputStream framing (Minecraft 24w04a+, compression type 4): "LZ4Block", token
|
||||
-- (0x10 raw / 0x20 LZ4 | level), compressed and decompressed lengths, XXH32 (LE i32s; not verified), then the block;
|
||||
-- blocks are independent and an empty block ends the stream.
|
||||
local Lz4 = require("@rosetta/codecs/compress/Lz4")
|
||||
|
||||
local Lz4Block = {}
|
||||
|
||||
local MAGIC = "LZ4Block"
|
||||
|
||||
-- decode(buf, offset, length, maxBytes) -> buffer | nil, message
|
||||
function Lz4Block.decode(b: buffer, offset: number, length: number, maxBytes: number): (buffer?, string?)
|
||||
local p, e = offset, offset + length
|
||||
local parts, total = {}, 0
|
||||
|
||||
@@ -1,17 +1,7 @@
|
||||
--!strict
|
||||
-- model/mca: Minecraft Anvil region files (r.<x>.<z>.mca: 32 x 32 chunks), read-only. New code, from the Minecraft
|
||||
-- wiki "Region file format" and "Chunk format" pages. Supports: the location / timestamp header, chunk payloads
|
||||
-- compressed with gzip, zlib (codecs/compress/Deflate), LZ4 (lz4-java block streams, 24w04a+: model/mca/Lz4Block over
|
||||
-- codecs/compress/Lz4) or stored, external .mcc chunks through opts.resolve, and every chunk layout: 1.18+ sections,
|
||||
-- 1.13 - 1.17 palettes (spanning and not) and pre-1.13 numeric ids (model/mca/Chunk).
|
||||
-- decode -> a Scene (meta.up = "y", one unit = one block) with one Types.Voxels covering the chosen chunks
|
||||
-- (opts.chunks, opts.area; by default every chunk, between the lowest and highest section holding blocks) with
|
||||
-- voxels.blocks (exact states, block entities relative to the grid), placed by its node at the world position of its
|
||||
-- minimum corner. meta.source.chunks lists every chunk read (local and world coordinates, timestamp, compression,
|
||||
-- DataVersion) with its whole NBT (chunk.nbt; opts.keepNbt = false drops it). Mca.list / Mca.chunk read the header
|
||||
-- and one chunk's NBT without building voxels.
|
||||
-- Not supported: writing; custom (127) chunk compression; LZ4 checksums are not verified; entities stored in the
|
||||
-- separate entities/ region files (1.17+) are another file (load it with Mca.chunk).
|
||||
-- model/mca: Minecraft Anvil region files (wiki "Region file format", "Chunk format"), read-only. Supports: gzip, zlib,
|
||||
-- LZ4 (lz4-java blocks, 24w04a+) and stored chunks, external .mcc chunks, every chunk layout back to pre-1.13.
|
||||
-- Not supported: writing; custom (127) compression; LZ4 checksums; the separate 1.17+ entities/ region files.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -35,19 +25,19 @@ local Mca = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
chunks: { { number } }?, -- only these chunks: { { x, z } } local coordinates 0 .. 31 (default all)
|
||||
area: { number }?, -- only blocks inside { minX, minY, minZ, maxX, maxY, maxZ } (world coordinates, inclusive)
|
||||
maxCells: number?, -- refuse grids with more cells (default 2^25: pick chunks or an area for big regions)
|
||||
maxBytes: number?, -- refuse a chunk that inflates past this (default 2^26)
|
||||
keepNbt: boolean?, -- keep each chunk's NBT in meta.source.chunks[i].nbt (default true)
|
||||
region: { number }?, -- the region's coordinates { x, z } (default: from opts.name "r.<x>.<z>.mca"), for .mcc files
|
||||
name: string?, -- the file name (the api fills it in)
|
||||
resolve: ((string) -> buffer?)?, -- reads a sibling file: external chunks c.<x>.<z>.mcc
|
||||
chunks: { { number } }?, -- local coordinates 0 .. 31 (default all)
|
||||
area: { number }?, -- world coordinates, inclusive
|
||||
maxCells: number?, -- default 2^25
|
||||
maxBytes: number?, -- default 2^26
|
||||
keepNbt: boolean?, -- default true
|
||||
region: { number }?, -- default: from opts.name "r.<x>.<z>.mca"
|
||||
name: string?,
|
||||
resolve: ((string) -> buffer?)?, -- external chunks c.<x>.<z>.mcc
|
||||
}
|
||||
export type Entry = {
|
||||
x: number, -- local chunk coordinates 0 .. 31
|
||||
x: number, -- 0 .. 31
|
||||
z: number,
|
||||
sector: number, -- 4 KiB sector of the chunk
|
||||
sector: number, -- 4 KiB sectors
|
||||
sectors: number,
|
||||
timestamp: number, -- seconds since 1970
|
||||
}
|
||||
@@ -87,7 +77,6 @@ function Mca.sniff(r: Bytes.Reader): number
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- list(r) -> { Entry } | nil, Err: the chunks present in the region (location and timestamp tables)
|
||||
function Mca.list(r: Bytes.Reader): ({ Entry }?, Err.Err?)
|
||||
local n = r.limit - r.base
|
||||
if n < 8192 then
|
||||
@@ -122,7 +111,6 @@ local function regionCoords(o: DecodeOptions): (number?, number?)
|
||||
return nil, nil
|
||||
end
|
||||
|
||||
-- payload(r, e, o) -> the chunk's uncompressed NBT bytes, compression name | nil, Err
|
||||
local function payload(r: Bytes.Reader, e: Entry, o: DecodeOptions): (buffer?, any)
|
||||
local p = r.base + e.sector * 4096
|
||||
if p + 5 > r.limit then
|
||||
@@ -175,7 +163,6 @@ local function payload(r: Bytes.Reader, e: Entry, o: DecodeOptions): (buffer?, a
|
||||
return out, comp
|
||||
end
|
||||
|
||||
-- chunk(r, x, z, opts?) -> the chunk's NBT root, compression | nil, Err (nil, nil when the chunk is absent)
|
||||
function Mca.chunk(r: Bytes.Reader, x: number, z: number, opts: DecodeOptions?): (any, any)
|
||||
local o: DecodeOptions = opts or {}
|
||||
if x < 0 or x > 31 or z < 0 or z > 31 or x % 1 ~= 0 or z % 1 ~= 0 then
|
||||
@@ -243,7 +230,6 @@ function Mca.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the bounds: chunks in x / z, sections holding anything but air in y, cut to the area
|
||||
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
|
||||
for _, c in chunks do
|
||||
lo[1], hi[1] = math.min(lo[1], c.x * 16), math.max(hi[1], c.x * 16 + 15)
|
||||
@@ -273,7 +259,7 @@ function Mca.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
end
|
||||
end
|
||||
if lo[2] == math.huge then
|
||||
lo[2], hi[2] = 0, -1 -- no blocks at all
|
||||
lo[2], hi[2] = 0, -1
|
||||
end
|
||||
if #chunks == 0 then
|
||||
lo, hi = { 0, 0, 0 }, { -1, -1, -1 }
|
||||
@@ -283,7 +269,6 @@ function Mca.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
if n > (o.maxCells or 2 ^ 25) then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d x %d x %d cells is over maxCells: choose opts.chunks or opts.area", sx, sy, sz))
|
||||
end
|
||||
-- one palette for the grid (air first), each section copied in through a remap table
|
||||
local states = { "minecraft:air" }
|
||||
local index: { [string]: number } = { ["minecraft:air"] = 0 }
|
||||
local grid = buffer.create(n * 2)
|
||||
|
||||
@@ -1,15 +1,7 @@
|
||||
--!strict
|
||||
-- model/md2: Quake II MD2 models ("IDP2" version 8), read into a Scene. Written from the MD2 format description in the
|
||||
-- Quake II source release (qfiles.h: dmdl_t) and the "MD2 file format" notes (David Henry); no code taken.
|
||||
-- Decode: one primitive: the triangles (welded on (vertex, texture coordinate) pairs; MD2 front faces are clockwise,
|
||||
-- the indices are reversed to counter-clockwise as glTF wants), POSITION of frame opts.frame (default 1),
|
||||
-- TEXCOORD_0 = s / skinwidth, t / skinheight (top-left origin), NORMAL computed from the geometry (the stored
|
||||
-- indexes into Quake's normal table are kept as meta.source.normalIndexes = false: that table is not
|
||||
-- redistributable here); every frame as a morph target (codecs/model/Rig: weight k = 1 shows frame k) and one
|
||||
-- animation per frame-name group ("run1".."run6" -> "run", 10 frames per second, LINEAR); the skins as texture
|
||||
-- URIs (the first is the material's base colour texture; mesh.extras.skins lists all). Units are Quake units, z up.
|
||||
-- meta.source = { format, frames, frameNames, skinWidth, skinHeight }.
|
||||
-- Not supported: the GL command list (the triangles carry the same geometry), writing.
|
||||
-- model/md2: Quake II MD2 ("IDP2" v8), from qfiles.h dmdl_t and David Henry's "MD2 file format"; no code taken.
|
||||
-- Supports: clockwise faces reversed, frames as morph targets, animations per frame-name group (10 fps), skin URIs.
|
||||
-- Not supported: the GL command list, writing; Quake's normal table (not redistributable: normals are computed).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -30,10 +22,10 @@ local Md2 = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
frame: number?, -- the frame used as the base POSITION (1-based, default 1)
|
||||
morph: boolean?, -- every frame as a morph target + the animations (default true)
|
||||
fps: number?, -- animation frame rate (default 10)
|
||||
maxVertices: number?, -- frames x vertices (default 2^24)
|
||||
frame: number?, -- 1-based, default 1
|
||||
morph: boolean?, -- default true
|
||||
fps: number?, -- default 10
|
||||
maxVertices: number?, -- default 2^24
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
@@ -49,7 +41,6 @@ function Md2.sniff(r: Bytes.Reader): number
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- group frame names by their name without trailing digits, in file order
|
||||
local function groups(names: { string }, fps: number): { Rig.Range }
|
||||
local out: { Rig.Range } = {}
|
||||
for i, n in names do
|
||||
@@ -99,13 +90,11 @@ function Md2.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
return nil, Err.new(Err.CORRUPT, "frame size too small", 16)
|
||||
end
|
||||
local b, base = r.buf, r.base
|
||||
-- skins
|
||||
local skins: { string } = {}
|
||||
for i = 0, nSkins - 1 do
|
||||
local s = buffer.readstring(b, base + oSkins + i * 64, 64)
|
||||
table.insert(skins, (string.match(s, "^[^%z]*")) :: string)
|
||||
end
|
||||
-- weld (xyz, st) pairs
|
||||
local key: { [number]: number } = {}
|
||||
local vx: { number }, vst: { number } = {}, {}
|
||||
local indices: { number } = {}
|
||||
@@ -140,7 +129,6 @@ function Md2.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
writef32(uv, (i - 1) * 8 + 4, readi16(b, o + 2) / math.max(sh, 1))
|
||||
end
|
||||
end
|
||||
-- frames
|
||||
local frames: { buffer } = {}
|
||||
local normals: { buffer } = {}
|
||||
local names: { string } = {}
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
--!strict
|
||||
-- model/md3: Quake III Arena MD3 models ("IDP3" version 15), read into a Scene. Written from the MD3 format
|
||||
-- description in the Quake III source release (qfiles.h: md3Header_t, md3Surface_t) and the "MD3 file format"
|
||||
-- notes (PhaethonH); no code taken.
|
||||
-- Decode: one mesh, one primitive per surface (indices reversed to counter-clockwise; POSITION of frame opts.frame
|
||||
-- (default 1) in units of 1/64; NORMAL from the stored latitude / longitude bytes; TEXCOORD_0 as stored, top-left
|
||||
-- origin); every frame as a morph target of each primitive (codecs/model/Rig) and one animation "frames" over all
|
||||
-- of them (opts.fps, default 15); the first shader of each surface as its material's texture URI; tags as child nodes
|
||||
-- (origin + axis of frame 1; their per-frame motion as translation / rotation channels of the same animation).
|
||||
-- Units are Quake units, z up. meta.source = { format, name, frames, frameNames, tags }.
|
||||
-- Not supported: writing.
|
||||
-- model/md3: Quake III MD3 ("IDP3" v15), from qfiles.h md3Header_t / md3Surface_t and PhaethonH's "MD3 file format";
|
||||
-- no code taken. Supports: surfaces as primitives, positions in 1/64 units, lat / long normals, frames as morph
|
||||
-- targets, tags as child nodes with channels. Not supported: writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -30,10 +23,10 @@ local Md3 = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
frame: number?, -- the frame used as the base POSITION / NORMAL (1-based, default 1)
|
||||
morph: boolean?, -- every frame as a morph target + the animation (default true)
|
||||
fps: number?, -- animation frame rate (default 15)
|
||||
maxVertices: number?, -- frames x vertices over all surfaces (default 2^24)
|
||||
frame: number?, -- 1-based, default 1
|
||||
morph: boolean?, -- default true
|
||||
fps: number?, -- default 15
|
||||
maxVertices: number?, -- default 2^24
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
@@ -175,7 +168,6 @@ function Md3.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
table.insert(mesh.primitives, prim)
|
||||
so += oEnd
|
||||
end
|
||||
-- frames and tags
|
||||
local frameNames: { string } = {}
|
||||
for f = 0, nFrames - 1 do
|
||||
frameNames[f + 1] = cstr(b, base + oFrames + f * 56 + 40, 16)
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
--!strict
|
||||
-- model/md5/Read: Doom 3 / Quake 4 MD5 text (MD5Version 10) to Scenes. md5mesh: joints (model-space bind pose:
|
||||
-- position + unit quaternion with w = -sqrt(1 - x² - y² - z²)) -> joint nodes and a Skin, each mesh -> a primitive
|
||||
-- (positions from the weights in the bind pose, normals computed, texture coordinates as stored, triangles reversed
|
||||
-- to counter-clockwise, JOINTS_0 / WEIGHTS_0 from the weights), its shader -> a material / texture URI. md5anim:
|
||||
-- hierarchy + baseframe (parent-relative) + frames of animated components -> translation / rotation channels at
|
||||
-- frameRate, applied to the joint nodes of the same names. Written from the format notes of the Doom 3 modding
|
||||
-- community (modwiki "MD5 (file format)", David Henry's "The MD5 Mesh and Animation Formats"); no code taken.
|
||||
-- model/md5/Read: MD5Version 10 text, from modwiki "MD5 (file format)" and David Henry's "The MD5 Mesh and Animation
|
||||
-- Formats"; no code taken. The bind pose is model space, the baseframe parent-relative.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Rig = require("@rosetta/codecs/model/Rig")
|
||||
|
||||
@@ -93,7 +88,7 @@ local function vec(L: Lexer, n: number): { number }
|
||||
return v
|
||||
end
|
||||
|
||||
-- the unit quaternion from its x, y, z (w <= 0, as id's tools store it)
|
||||
-- w = -sqrt(1 - x² - y² - z²) (w <= 0, as id's tools store it)
|
||||
local function quat(x: number, y: number, z: number): { number }
|
||||
local t = 1 - x * x - y * y - z * z
|
||||
return { x, y, z, if t < 0 then 0 else -math.sqrt(t) }
|
||||
@@ -109,7 +104,6 @@ end
|
||||
-- ------------------------------------------------------------------------------------------------ md5mesh
|
||||
type MeshJoint = { name: string, parent: number, pos: { number }, q: { number } }
|
||||
|
||||
-- mesh(text, opts) -> Scene, joint node indices by name | nil, message
|
||||
function Read.mesh(text: string, opts: Options?): (Types.Scene?, any)
|
||||
local L: Lexer = { text = text, pos = 1, err = nil }
|
||||
local joints: { MeshJoint } = {}
|
||||
@@ -277,7 +271,6 @@ export type Anim = {
|
||||
tracks: { Rig.Track }, -- per joint: translation / rotation keys, one per frame
|
||||
}
|
||||
|
||||
-- anim(text) -> Anim | nil, message
|
||||
function Read.anim(text: string): (Anim?, string?)
|
||||
local L: Lexer = { text = text, pos = 1, err = nil }
|
||||
local a: Anim = { frameRate = 24, frames = 0, joints = {}, base = {}, tracks = {} }
|
||||
@@ -396,7 +389,6 @@ function Read.anim(text: string): (Anim?, string?)
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- addAnim(scene, nodes by joint name, anim, name) -> channels added
|
||||
function Read.addAnim(scene: Types.Scene, byName: { [string]: number }, a: Anim, name: string): number
|
||||
local nodes: { number } = {}
|
||||
local tracks: { [number]: Rig.Track } = {}
|
||||
@@ -416,7 +408,6 @@ function Read.addAnim(scene: Types.Scene, byName: { [string]: number }, a: Anim,
|
||||
return #scene.animations[ai].channels
|
||||
end
|
||||
|
||||
-- animScene(a, name) -> a Scene of the animation's skeleton (baseframe pose) with the animation
|
||||
function Read.animScene(a: Anim, name: string): Types.Scene
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
--!strict
|
||||
-- model/md5: Doom 3 / Quake 4 MD5 models (MD5Version 10 text): .md5mesh (skeleton, skin, meshes) and .md5anim
|
||||
-- (skeletal animation), read into a Scene through model/md5/Read. A .md5mesh loads its animations from
|
||||
-- opts.anims = { "idle.md5anim", ... } (each found through opts.files[name] or opts.resolve(name); joints matched by
|
||||
-- name; the animation is named after the file without its extension); a missing one fails with UNSUPPORTED unless
|
||||
-- opts.skipMissing. A .md5anim alone loads as its skeleton (baseframe pose) with the animation. Units are Doom
|
||||
-- units, z up. Not supported: writing, .md5camera.
|
||||
-- model/md5: Doom 3 / Quake 4 MD5 (MD5Version 10 text): .md5mesh and .md5anim (model/md5/Read); a mesh loads
|
||||
-- opts.anims, joints matched by name. Not supported: writing, .md5camera.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -26,11 +22,11 @@ local Md5 = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
anims: { string }?, -- .md5anim files to load with a .md5mesh
|
||||
anims: { string }?,
|
||||
resolve: ((uri: string) -> (buffer | string)?)?,
|
||||
files: { [string]: buffer | string }?,
|
||||
skipMissing: boolean?, -- ignore animations that cannot be found (default false: UNSUPPORTED)
|
||||
name: string?, -- the file name (names a standalone animation)
|
||||
skipMissing: boolean?, -- default false: UNSUPPORTED
|
||||
name: string?,
|
||||
maxVertices: number?, -- default 2^24
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
--!strict
|
||||
-- model/mdl/HalfLife: Half-Life 1 (GoldSrc) studio models ("IDST" version 10) to a Scene. Written from the studio.h
|
||||
-- layout of the Half-Life SDK and the format notes of the HLMV / Crowbar communities; no code taken.
|
||||
-- Bones -> joint nodes and a Skin (bind pose from the bone defaults; Euler angles through Rig.angles), body parts ->
|
||||
-- one mesh per body part (its first model, or opts.bodies[part]), its meshes -> primitives (triangle strips and fans
|
||||
-- unrolled to counter-clockwise triangles; vertices transformed to model space by their bone's bind pose; JOINTS_0 =
|
||||
-- that bone, WEIGHTS_0 = 1), textures (8-bit + their own palette) -> texture.image, the first skin family ->
|
||||
-- materials, sequences of the main file -> animations (frames at the sequence's fps; the first blend only).
|
||||
-- Not supported: sequence groups in other files (those sequences are listed in meta, without channels), bone
|
||||
-- controllers, hitboxes / attachments / events (counted in meta), textures in a separate "<name>t.mdl" (pass it
|
||||
-- as opts.textures = that file's bytes).
|
||||
-- model/mdl/HalfLife: GoldSrc studio models ("IDST" v10), from the Half-Life SDK studio.h and HLMV / Crowbar notes; no
|
||||
-- code taken. Not supported: sequence groups in other files, bone controllers, hitboxes / attachments / events, blends
|
||||
-- past the first.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Mat4 = require("@rosetta/codecs/model/Mat4")
|
||||
local Pixels = require("@rosetta/codecs/image/Pixels")
|
||||
@@ -27,7 +20,6 @@ local function str(b: buffer, at: number, n: number): string
|
||||
return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string
|
||||
end
|
||||
|
||||
-- the textures of a studio header at base (this file or a separate texture file) -> { Image }, names | nil, message
|
||||
local function textures(b: buffer, base: number, size: number, maxPixels: number): ({ Types.Image }?, { string } | string)
|
||||
local n, at = readi32(b, base + 180), readi32(b, base + 184)
|
||||
if n < 0 or n > 4096 or at < 0 or at + n * 80 > size then
|
||||
@@ -52,7 +44,7 @@ local function textures(b: buffer, base: number, size: number, maxPixels: number
|
||||
return out, names
|
||||
end
|
||||
|
||||
-- one animation value: bone default + stored value * scale (frame f, 0-based)
|
||||
-- bone default + stored value * scale
|
||||
local function animValue(b: buffer, at: number, limit: number, f: number): number?
|
||||
local p = at
|
||||
local k = f
|
||||
@@ -77,7 +69,6 @@ local function animValue(b: buffer, at: number, limit: number, f: number): numbe
|
||||
return nil
|
||||
end
|
||||
|
||||
-- decode(b, base, size, opts) -> Scene | nil, message
|
||||
function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): (Types.Scene?, string?)
|
||||
if size < 244 then
|
||||
return nil, "truncated header"
|
||||
@@ -106,7 +97,6 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?):
|
||||
local maxPixels = opts and opts.maxPixels or 2 ^ 24
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
-- bones
|
||||
local bones: { Bone } = {}
|
||||
local joints: { Rig.Joint } = {}
|
||||
for i = 0, nBones - 1 do
|
||||
@@ -124,7 +114,6 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?):
|
||||
table.insert(scene.nodes, root)
|
||||
scene.roots[1] = 1
|
||||
local jointNodes, skinIndex, world = Rig.skeleton(scene, joints, "local", 1)
|
||||
-- textures and skins
|
||||
local texSrc, texBase, texSize = b, base, size
|
||||
if nTex == 0 and opts and opts.textures then
|
||||
texSrc, texBase, texSize = opts.textures, 0, buffer.len(opts.textures)
|
||||
@@ -151,7 +140,6 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?):
|
||||
skinMap[r + 1] = readi16(texSrc, texBase + oSkins + r * 2) + 1
|
||||
end
|
||||
end
|
||||
-- body parts
|
||||
local totalVerts = 0
|
||||
for part = 0, nParts - 1 do
|
||||
local po = base + oParts + part * 76
|
||||
@@ -173,7 +161,6 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?):
|
||||
local tex = skinMap[skinref + 1] or (skinref + 1)
|
||||
local img = images[tex]
|
||||
local tw, th = if img then img.width else 1, if img then img.height else 1
|
||||
-- triangle commands
|
||||
local weld: { [string]: number } = {}
|
||||
local corners: { { number } } = {}
|
||||
local indices: { number } = {}
|
||||
@@ -285,7 +272,6 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?):
|
||||
table.insert(root.children, #scene.nodes)
|
||||
end
|
||||
end
|
||||
-- sequences
|
||||
local seqs: { any } = {}
|
||||
for s = 0, nSeq - 1 do
|
||||
local so = base + oSeq + s * 176
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
--!strict
|
||||
-- model/mdl/Quake: Quake 1 MDL ("IDPO" version 6) to a Scene. Written from the Quake specs (Olivier Montanuy et
|
||||
-- al., "Quake Specs 3.4", section 5) and the modelgen.h layout of the Quake source release; no code taken.
|
||||
-- Skins (single and grouped: the first picture of a group) become texture.image through a 768-byte palette;
|
||||
-- texture coordinates on the seam of back-facing triangles move half a skin width (the vertices are welded per
|
||||
-- side); simple and grouped frames become morph targets with one animation per frame-name group.
|
||||
-- model/mdl/Quake: Quake 1 MDL ("IDPO" v6), from "Quake Specs 3.4" section 5 and modelgen.h; no code taken. Seam
|
||||
-- texture coordinates of back-facing triangles move half a skin width; a skin group shows its first picture.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Pixels = require("@rosetta/codecs/image/Pixels")
|
||||
local Rig = require("@rosetta/codecs/model/Rig")
|
||||
@@ -19,7 +16,6 @@ local function name16(b: buffer, at: number): string
|
||||
return (string.match(buffer.readstring(b, at, 16), "^[^%z]*")) :: string
|
||||
end
|
||||
|
||||
-- decode(b, base, size, palette, opts) -> Scene | nil, message (offsets relative to base)
|
||||
function Quake.decode(b: buffer, base: number, size: number, palette: buffer?, opts: Options?): (Types.Scene?, string?)
|
||||
if size < 84 then
|
||||
return nil, "truncated header"
|
||||
@@ -41,7 +37,6 @@ function Quake.decode(b: buffer, base: number, size: number, palette: buffer?, o
|
||||
local function need(n: number): boolean
|
||||
return n >= 0 and p + n <= size
|
||||
end
|
||||
-- skins
|
||||
local pal = if palette then Pixels.palette(palette, 0, 256) else nil
|
||||
local skins: { Types.Image } = {}
|
||||
local px = sw * sh
|
||||
@@ -79,7 +74,6 @@ function Quake.decode(b: buffer, base: number, size: number, palette: buffer?, o
|
||||
table.insert(skins, img)
|
||||
p += count * px
|
||||
end
|
||||
-- texture coordinates and triangles
|
||||
if not need(nVerts * 12 + nTris * 16) then
|
||||
return nil, "truncated vertices / triangles"
|
||||
end
|
||||
@@ -117,7 +111,7 @@ function Quake.decode(b: buffer, base: number, size: number, palette: buffer?, o
|
||||
table.insert(indices, c[1])
|
||||
end
|
||||
p += nTris * 16
|
||||
-- frames: simple (type 0) or groups of simple frames
|
||||
-- frames: simple (type 0) or groups
|
||||
local frameAt: { number } = {}
|
||||
local names: { string } = {}
|
||||
local fsize = 24 + nVerts * 4
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
--!strict
|
||||
-- model/mdl: Quake 1 ("IDPO" version 6: model/mdl/Quake) and Half-Life 1 / GoldSrc ("IDST" version 10:
|
||||
-- model/mdl/HalfLife) models, read into a Scene. See the two submodules for what each maps. Quake skins need the
|
||||
-- game's 768-byte palette (gfx/palette.lmp, not redistributable: never built in): opts.palette (a buffer / string),
|
||||
-- else opts.resolve("gfx/palette.lmp") / opts.files["gfx/palette.lmp"], else a grey ramp (meta.source.palette =
|
||||
-- false). Half-Life textures carry their own palettes. Source engine MDL ("IDST" version 44+, with .vvd / .vtx
|
||||
-- files) is UNSUPPORTED.
|
||||
-- model/mdl: Quake 1 ("IDPO" v6, model/mdl/Quake) and GoldSrc ("IDST" v10, model/mdl/HalfLife) models. Quake skins
|
||||
-- need gfx/palette.lmp (not redistributable, never built in; else a grey ramp). Not supported: Source MDL (v44+).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -26,14 +22,14 @@ local Mdl = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
palette: (buffer | string)?, -- Quake: the 768-byte palette (default: resolved gfx/palette.lmp, else grey)
|
||||
palette: (buffer | string)?, -- default: resolved gfx/palette.lmp, else grey
|
||||
resolve: ((uri: string) -> (buffer | string)?)?,
|
||||
files: { [string]: buffer | string }?,
|
||||
frame: number?, -- Quake: the frame used as the base POSITION (default 1)
|
||||
morph: boolean?, -- Quake: frames as morph targets + animations (default true)
|
||||
fps: number?, -- Quake: animation frame rate (default 10)
|
||||
bodies: { number }?, -- Half-Life: the model picked for each body part (1-based, default 1)
|
||||
textures: (buffer | string)?, -- Half-Life: the "<name>t.mdl" texture file of a model without textures
|
||||
frame: number?, -- Quake; default 1
|
||||
morph: boolean?, -- Quake; default true
|
||||
fps: number?, -- Quake; default 10
|
||||
bodies: { number }?, -- Half-Life; 1-based, default 1
|
||||
textures: (buffer | string)?,
|
||||
maxPixels: number?, -- default 2^24
|
||||
maxVertices: number?, -- default 2^24
|
||||
}
|
||||
|
||||
@@ -1,15 +1,7 @@
|
||||
--!strict
|
||||
-- model/ms3d/Read: MilkShape 3D 1.8 (.ms3d, version 3 / 4) -> Types.Scene. The layout from MilkShape's ms3dspec.h
|
||||
-- (chUmbaLum soft): vertices (position, a bone), triangles (three vertex indices, per-corner normals and uvs, a
|
||||
-- smoothing group, a group), groups (named triangle lists with a material), materials (Phong colours, shininess
|
||||
-- 0..128, transparency, texture and alpha map file names), the animation header (fps, current time, frames) and
|
||||
-- joints (name, parent name, local Euler XYZ rotation in radians and position, rotation / position keys in seconds
|
||||
-- relative to that rest pose); then the optional sub-versioned blocks: comments (groups, materials, joints, model),
|
||||
-- vertex extras (three more bones and weights in percent: subversion 1-3, with one or two extra u32s from 2 / 3),
|
||||
-- joint extras (colours) and model extras (joint size, transparency mode, alpha reference).
|
||||
-- Mapping: one node + mesh + primitive per group; joints -> nodes in their hierarchy, a skin (inverse bind matrices
|
||||
-- of the rest pose; JOINTS_0 / WEIGHTS_0 when a vertex has a bone) and one animation (rest * key rotations, rest +
|
||||
-- key positions). Never throws on bad data: returns nil, message, offset.
|
||||
-- model/ms3d/Read: the ms3dspec.h layout: vertices, triangles, groups, materials (shininess 0..128), the animation
|
||||
-- header, joints (local Euler XYZ radians, keys in seconds relative to the rest pose), then the sub-versioned comments,
|
||||
-- vertex extras (weights in percent, subversion 1-3), joint extras (colours) and model extras. Never throws.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Mat4 = require("@rosetta/codecs/model/Mat4")
|
||||
|
||||
@@ -62,7 +54,6 @@ type Joint = {
|
||||
rotKeys: { { number } }, posKeys: { { number } }, comment: string?, color: { number }?,
|
||||
}
|
||||
|
||||
-- scene(b, base, limit, opts) -> Scene | nil, message, offset
|
||||
function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Types.Scene?, string?, number?)
|
||||
local p = base
|
||||
local function need(n: number): boolean
|
||||
@@ -77,7 +68,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty
|
||||
end
|
||||
p += 14
|
||||
local maxV = opts and opts.maxVertices or 2 ^ 20
|
||||
-- vertices
|
||||
if not need(2) then
|
||||
return nil, "truncated vertex count", p
|
||||
end
|
||||
@@ -92,7 +82,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty
|
||||
verts[i] = { pos = { readf32(b, q + 1), readf32(b, q + 5), readf32(b, q + 9) }, bones = { readi8(b, q + 13), -1, -1, -1 }, weights = { 1, 0, 0, 0 } }
|
||||
end
|
||||
p += nv * 15
|
||||
-- triangles
|
||||
if not need(2) then
|
||||
return nil, "truncated triangle count", p
|
||||
end
|
||||
@@ -106,7 +95,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty
|
||||
end
|
||||
local triAt = p
|
||||
p += nt * 70
|
||||
-- groups
|
||||
if not need(2) then
|
||||
return nil, "truncated group count", p
|
||||
end
|
||||
@@ -135,7 +123,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty
|
||||
p += 1
|
||||
table.insert(groups, g)
|
||||
end
|
||||
-- materials
|
||||
if not need(2) then
|
||||
return nil, "truncated material count", p
|
||||
end
|
||||
@@ -154,7 +141,7 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty
|
||||
})
|
||||
end
|
||||
p += nm * 361
|
||||
-- animation header and joints (version 3 files may end here)
|
||||
-- version 3 files may end here
|
||||
local fps, current, frames = 24, 0, 0
|
||||
local joints: { Joint } = {}
|
||||
if need(12) then
|
||||
@@ -189,7 +176,6 @@ function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Ty
|
||||
table.insert(joints, j)
|
||||
end
|
||||
end
|
||||
-- sub-versioned blocks
|
||||
local source: { [string]: any } = { format = "ms3d", version = version, fps = fps, currentTime = current, frames = frames }
|
||||
local function comments(list: { any }): string?
|
||||
if not need(4) then
|
||||
@@ -283,7 +269,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any }
|
||||
local scene = S.new()
|
||||
scene.meta.up = "y"
|
||||
scene.meta.source = source :: any
|
||||
-- materials, textures
|
||||
for _, m in mats do
|
||||
local mat = S.material(m.name)
|
||||
local d = m.diffuse
|
||||
@@ -305,7 +290,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any }
|
||||
}
|
||||
table.insert(scene.materials, mat)
|
||||
end
|
||||
-- joints: nodes, rest pose, skin
|
||||
local nj = #joints
|
||||
local jointNode: { [number]: number } = {}
|
||||
local byName: { [string]: number } = {}
|
||||
@@ -355,7 +339,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any }
|
||||
end
|
||||
scene.skins[1] = { joints = list, inverseBindMatrices = ibm }
|
||||
end
|
||||
-- groups: one node + mesh each; vertices unwelded per (vertex, normal, uv) corner
|
||||
local nv = #verts
|
||||
for gi, g in groups do
|
||||
local remap: { [string]: number } = {}
|
||||
@@ -365,7 +348,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any }
|
||||
local count = 0
|
||||
for _, ti in g.tris do
|
||||
local q = triAt + ti * 70
|
||||
-- a triangle with an out-of-range vertex is dropped
|
||||
if readu16(b, q + 2) >= nv or readu16(b, q + 4) >= nv or readu16(b, q + 6) >= nv then
|
||||
continue
|
||||
end
|
||||
@@ -382,7 +364,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any }
|
||||
table.move(v.pos, 1, 3, o * 3 + 1, P)
|
||||
N[o * 3 + 1], N[o * 3 + 2], N[o * 3 + 3] = readf32(b, q + 8 + k * 12), readf32(b, q + 12 + k * 12), readf32(b, q + 16 + k * 12)
|
||||
U[o * 2 + 1], U[o * 2 + 2] = readf32(b, q + 44 + k * 4), readf32(b, q + 56 + k * 4)
|
||||
-- influences: the valid bones, weights normalized
|
||||
local sum = 0
|
||||
for c = 1, 4 do
|
||||
if v.bones[c] >= 0 then
|
||||
@@ -429,7 +410,6 @@ function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any }
|
||||
table.insert(scene.nodes, node)
|
||||
table.insert(scene.roots, #scene.nodes)
|
||||
end
|
||||
-- the animation: rest * key rotations, rest + key positions
|
||||
local channels: { Types.Channel } = {}
|
||||
for i, j in joints do
|
||||
if #j.rotKeys > 0 then
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
--!strict
|
||||
-- model/ms3d/Write: Types.Scene -> MilkShape 3D (version 4). One group per placed primitive (points / lines skipped,
|
||||
-- polygons triangulated); vertices in world space, or in the skin's bind space for primitives skinned by the first
|
||||
-- skin (JOINTS_0 / WEIGHTS_0 -> a bone and up to three more with weights in percent: vertex extras subversion 2);
|
||||
-- meshes under a joint of that skin are bound rigidly to it. Joints: the first skin's joints in tree order, each
|
||||
-- parented to its nearest joint ancestor, the rest pose from the inverse bind matrices; the first animation's
|
||||
-- rotation / translation keys on them become keys relative to that rest pose (scale is not MilkShape's). Materials:
|
||||
-- extras.ms3d when present, else from the PBR fields; texture file names from texture.uri (a texture with data and
|
||||
-- no uri is named after opts.name and put into opts.files). Comments (extras.ms3d.comment, meta.source.comment),
|
||||
-- joint colours and model extras are written in their sub-versioned blocks.
|
||||
-- model/ms3d/Write: Scene -> MilkShape 3D v4: a group per placed primitive, the first skin's joints (rest pose from
|
||||
-- the inverse bind matrices, keys relative to it), vertex extras subversion 2 (weights in percent).
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Mat4 = require("@rosetta/codecs/model/Mat4")
|
||||
@@ -57,14 +50,11 @@ end
|
||||
-- ------------------------------------------------------------------------------------------------ joints
|
||||
type Joint = { node: number, name: string, parent: string, pos: { number }, rot: { number }, quat: { number }, rotKeys: { { number } }, posKeys: { { number } } }
|
||||
|
||||
-- the rigid part (rotation and translation) of a matrix
|
||||
local function rigid(m: { number }): { number }
|
||||
local t, r = Mat4.decompose(m)
|
||||
return Mat4.compose(t, r, nil)
|
||||
end
|
||||
|
||||
-- the first skin's joints and every node the first animation moves (rigid meshes below them follow), in tree order;
|
||||
-- skin joint index -> joint, node -> joint (0-based); the bind transform of the skinned vertices
|
||||
local function joints(scene: Types.Scene, tr: Tree): ({ Joint }, { [number]: number }, { [number]: number }, { number })
|
||||
local skin = scene.skins[1]
|
||||
local anim = scene.animations[1]
|
||||
@@ -85,7 +75,6 @@ local function joints(scene: Types.Scene, tr: Tree): ({ Joint }, { [number]: num
|
||||
table.insert(chans[ch.node], ch)
|
||||
end
|
||||
end
|
||||
-- skinned vertices go to the space where the first joint's rest world undoes its inverse bind matrix
|
||||
local B = S.IDENTITY
|
||||
local IBM: any = if skin and skin.inverseBindMatrices then S.reader(skin.inverseBindMatrices) else nil
|
||||
if skin and IBM and tr.world[skin.joints[1]] then
|
||||
@@ -104,8 +93,7 @@ local function joints(scene: Types.Scene, tr: Tree): ({ Joint }, { [number]: num
|
||||
while p ~= 0 and byNode[p] == nil do
|
||||
p = tr.parent[p]
|
||||
end
|
||||
-- MilkShape joints are rigid: rest = (parent's rigid world)^-1 * rigid world; the static nodes between the
|
||||
-- joint and its joint parent (C) carry over to the keys
|
||||
-- MilkShape joints are rigid: rest = (parent's rigid world)^-1 * rigid world
|
||||
local invP = if p ~= 0 then Mat4.inverse(rigid(tr.world[p])) or Mat4.identity() else Mat4.identity()
|
||||
local gp = tr.parent[ni]
|
||||
local C = S.mul(invP, if gp ~= 0 then tr.world[gp] else S.IDENTITY)
|
||||
@@ -158,7 +146,6 @@ type Vertex = { x: number, y: number, z: number, bones: { number }, weights: { n
|
||||
type Tri = { v: { number }, n: { number }, uv: { number }, sg: number, group: number }
|
||||
type Group = { name: string, tris: { number }, material: number, flags: number, comment: string? }
|
||||
|
||||
-- every placed primitive as a group: vertices, triangles; or nil, message
|
||||
local function geometry(scene: Types.Scene, tr: Tree, bySkin: { [number]: number }, byNode: { [number]: number }, B: { number }): ({ Vertex }, { Tri }, { Group }, string?)
|
||||
local verts: { Vertex }, tris: { Tri }, groups: { Group } = {}, {}, {}
|
||||
for _, pl in S.flatten(scene) do
|
||||
@@ -175,7 +162,6 @@ local function geometry(scene: Types.Scene, tr: Tree, bySkin: { [number]: number
|
||||
continue
|
||||
end
|
||||
local skinned = node.skin == 1 and prim.attributes.JOINTS_0 ~= nil and prim.attributes.WEIGHTS_0 ~= nil
|
||||
-- a rigid mesh follows its nearest joint
|
||||
local rigid = -1
|
||||
if not skinned then
|
||||
local p = pl.node
|
||||
@@ -257,7 +243,6 @@ local function geometry(scene: Types.Scene, tr: Tree, bySkin: { [number]: number
|
||||
b, c = c, b
|
||||
end
|
||||
local t: Tri = { v = { base + a, base + b, base + c }, n = {}, uv = {}, sg = if saved then saved[f + 1] else 1, group = gi }
|
||||
-- the face normal for primitives without normals
|
||||
local va, vb, vc = verts[base + a + 1], verts[base + b + 1], verts[base + c + 1]
|
||||
local e1x, e1y, e1z = vb.x - va.x, vb.y - va.y, vb.z - va.z
|
||||
local e2x, e2y, e2z = vc.x - va.x, vc.y - va.y, vc.z - va.z
|
||||
@@ -343,7 +328,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?)
|
||||
end
|
||||
w:i8(g.material % 256)
|
||||
end
|
||||
-- materials
|
||||
w:u16le(#scene.materials)
|
||||
local base = string.match(o.name or "", "([^/\\]-)%.[^.]*$") or "texture"
|
||||
for i, m in scene.materials do
|
||||
@@ -375,7 +359,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?)
|
||||
fixedString(w, file, 128)
|
||||
fixedString(w, msg(x.alphamap), 128)
|
||||
end
|
||||
-- the animation header and joints
|
||||
local fps = o.fps or (if fromMs3d and type(src.fps) == "number" and src.fps > 0 then src.fps else 24)
|
||||
local last = 0
|
||||
for _, j in js do
|
||||
@@ -412,7 +395,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?)
|
||||
end
|
||||
end
|
||||
end
|
||||
-- comments
|
||||
w:u32le(1)
|
||||
local function comments(list: { any }, get: (any) -> string?)
|
||||
local found = {}
|
||||
@@ -465,7 +447,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?)
|
||||
end
|
||||
w:u32le(0)
|
||||
end
|
||||
-- joint colours, model extras
|
||||
w:u32le(1)
|
||||
for _, j in js do
|
||||
local x: any = scene.nodes[j.node].extras
|
||||
|
||||
@@ -1,18 +1,7 @@
|
||||
--!strict
|
||||
-- model/ms3d: MilkShape 3D (.ms3d, versions 3 and 4, with the comment / vertex / joint / model extra blocks of
|
||||
-- MilkShape 1.8). New code from MilkShape's ms3dspec.h; assimp's MS3D importer (BSD-3) is the reference it is tested
|
||||
-- against (no code ported).
|
||||
-- Reads (model/ms3d/Read): groups -> one node, mesh and primitive each (POSITION, the per-corner NORMAL and
|
||||
-- TEXCOORD_0: MilkShape's uv origin is already glTF's top left; vertices unwelded per corner; smoothing groups in
|
||||
-- extras.ms3d.smoothing), materials (diffuse -> baseColor with transparency as alpha, shininess -> roughness, emissive;
|
||||
-- ambient / specular / mode / alpha map in extras.ms3d; the texture file -> a Texture with `uri`, not loaded: use
|
||||
-- F.model.loadTextures), joints -> nodes (hierarchy by parent name, Euler XYZ rest rotations), one skin (inverse
|
||||
-- bind matrices of the rest pose, JOINTS_0 / WEIGHTS_0 from the vertex bone and the extra bones / weights), keyframes
|
||||
-- -> one animation (rotation and translation channels, times in seconds), comments and joint colours in extras.ms3d,
|
||||
-- the model comment / fps / frames / joint size in meta.source. meta.up = "y".
|
||||
-- Writes (model/ms3d/Write): version 4 with subversion 1 comments, subversion 2 vertex extras (four bones per vertex),
|
||||
-- joint colours and model extras. Limits of the format (Err.ARG): 65535 vertices / triangles, 255 groups, 127
|
||||
-- materials, 127 joints. Not supported: scale keys (MilkShape has none), more than one skin (the first one is written).
|
||||
-- model/ms3d: MilkShape 3D 1.8 (.ms3d v3 / v4), from ms3dspec.h, tested against assimp's MS3D importer (no code
|
||||
-- ported). Supports: groups, materials, joints, a skin, keyframes, comments and the extra blocks, read + write. Not
|
||||
-- supported: scale keys (MilkShape has none), a second skin; writes at most 65535 vertices, 255 groups, 127 joints.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -33,12 +22,12 @@ local Ms3d = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxVertices: number?, -- refuse more triangle corners (default 2^20)
|
||||
maxVertices: number?, -- default 2^20
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
fps: number?, -- the animation's frames per second (default: the source's, else 24)
|
||||
name: string?, -- the destination's file name (names textures that have no uri)
|
||||
files: { [string]: any }?, -- receives the bytes of textures that have data but no uri
|
||||
fps: number?, -- default: the source's, else 24
|
||||
name: string?,
|
||||
files: { [string]: any }?,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
@@ -53,7 +42,6 @@ end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Ms3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
||||
-- the scene builder is plain (not native) code: a bug there must not escape as an error
|
||||
local ok, scene, msg, at = pcall(Read.scene, r.buf, r.base, r.limit, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(scene))
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
--!strict
|
||||
-- model/obj/Mtl: Wavefront .mtl material libraries (Paul Bourke's MTL spec + the common PBR extension: Pr, Pm, Ps, Pc,
|
||||
-- Pcr, aniso, anisor, Ke, map_Pr, map_Pm, map_Ke, norm). parse(text) -> { name -> { statement -> values } } keeping
|
||||
-- every statement; toMaterial maps one onto the Scene Material (glTF PBR, Phong values in extras.obj); write is the
|
||||
-- reverse (from extras.obj when present, else from the PBR fields).
|
||||
-- model/obj/Mtl: Wavefront .mtl (Paul Bourke's MTL spec + the PBR extension: Pr, Pm, Ps, Pc, Pcr, aniso, anisor, Ke,
|
||||
-- map_Pr, map_Pm, map_Ke, norm); Phong values are kept in extras.obj.
|
||||
local Types = require("@rosetta/Types")
|
||||
|
||||
local Mtl = {}
|
||||
@@ -35,7 +33,6 @@ local function parseMap(args: { string }): Map
|
||||
end
|
||||
end
|
||||
else
|
||||
-- -o / -s / -t: up to three numbers
|
||||
while i <= #args and #vals < 3 and tonumber(args[i]) ~= nil and i < #args do
|
||||
table.insert(vals, args[i])
|
||||
i += 1
|
||||
@@ -48,7 +45,6 @@ local function parseMap(args: { string }): Map
|
||||
return { file = file, options = opts }
|
||||
end
|
||||
|
||||
-- parse(text) -> { Entry } in file order
|
||||
function Mtl.parse(text: string): { Entry }
|
||||
local out: { Entry } = {}
|
||||
local cur: Entry? = nil
|
||||
@@ -96,7 +92,6 @@ function Mtl.mime(file: string): string?
|
||||
return if ext then MIME[string.lower(ext)] else nil
|
||||
end
|
||||
|
||||
-- toMaterial(entry, texture) -> Material: texture(map) returns the scene texture index for a map
|
||||
function Mtl.toMaterial(e: Entry, texture: (Map) -> number): Types.Material
|
||||
local m = Types.Scene.material(e.name)
|
||||
local v = e.values
|
||||
@@ -144,7 +139,6 @@ function Mtl.toMaterial(e: Entry, texture: (Map) -> number): Types.Material
|
||||
if m.emissiveTexture and not ke then
|
||||
m.emissive = { 1, 1, 1 }
|
||||
end
|
||||
-- everything else as it was, for the writer and for Phong renderers
|
||||
local extra: { [string]: any } = {}
|
||||
for k, vals in v do
|
||||
extra[k] = vals
|
||||
@@ -171,7 +165,6 @@ local function num(v: number): string
|
||||
end
|
||||
Mtl.num = num
|
||||
|
||||
-- write(materials, name, textureFile) -> MTL text. textureFile(index) -> the file name a map refers to.
|
||||
function Mtl.write(materials: { Types.Material }, names: { string }, textureFile: (number) -> string?): string
|
||||
local out = { "# written by rosetta" }
|
||||
for i, m in materials do
|
||||
@@ -190,7 +183,6 @@ function Mtl.write(materials: { Types.Material }, names: { string }, textureFile
|
||||
end
|
||||
order = table.clone(saved.order or {})
|
||||
end
|
||||
-- the PBR fields win over the saved Phong values they map to
|
||||
local bc = m.baseColor or { 1, 1, 1, 1 }
|
||||
values.Kd = { bc[1], bc[2], bc[3] }
|
||||
if (bc[4] or 1) < 1 or values.d then
|
||||
@@ -235,7 +227,6 @@ function Mtl.write(materials: { Types.Material }, names: { string }, textureFile
|
||||
setMap("norm", m.normalTexture)
|
||||
end
|
||||
setMap("map_ORM", m.metallicRoughnessTexture)
|
||||
-- the saved order first, then the rest sorted
|
||||
local keys = {}
|
||||
local seen = {}
|
||||
for _, k in order do
|
||||
|
||||
@@ -1,17 +1,7 @@
|
||||
--!strict
|
||||
-- model/obj: Wavefront OBJ (+ MTL), from Paul Bourke's OBJ / MTL specifications and what Blender / Maya / assimp
|
||||
-- write. Supports: v (with the common "v x y z r g b" vertex colour extension), vt, vn, f with every index form
|
||||
-- (v, v/vt, v//vn, v/vt/vn, negative = relative), l, p, o / g (nodes), usemtl / mtllib (materials: Phong + the PBR
|
||||
-- extension, texture maps with -o / -s / -bm options; texture images stay encoded bytes or file names, see Types), line
|
||||
-- continuations, comments. n-gons are fan-triangulated by default (opts.triangulate = false keeps them as "polygons",
|
||||
-- MeshOps.triangulate ear-clips concave ones). TEXCOORD_0 is flipped to glTF's top-left origin (opts.flipV = false
|
||||
-- keeps OBJ's).
|
||||
-- Nodes: one per object (o); groups (g) inside an object become child nodes; files without o: one root node per group.
|
||||
-- Each node has a mesh with one primitive per material. Vertices are unwelded per (v, vt, vn) combination.
|
||||
-- Not supported: free-form geometry (curv, surf, ...: skipped and counted in meta.source.skipped), smoothing groups
|
||||
-- (s: kept per node in extras.obj.smoothing, not used to compute normals).
|
||||
-- encode: every mesh primitive of the scene baked into world space, one o per node; materials into a .mtl (written to
|
||||
-- opts.files[<name>.mtl] when opts.files is a table, see Types), embedded texture bytes into opts.files too.
|
||||
-- model/obj: Wavefront OBJ + MTL (Paul Bourke's specs, as Blender / Maya / assimp write them). Supports: v (with
|
||||
-- "v x y z r g b"), vt, vn, f in every index form, l, p, o / g, usemtl / mtllib, continuations; TEXCOORD_0 flipped to
|
||||
-- top-left. Not supported: free-form geometry (curv, surf: skipped), smoothing groups (kept in extras.obj.smoothing).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -31,21 +21,21 @@ local Obj = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps "polygons" primitives
|
||||
flipV: boolean?, -- TEXCOORD_0.v = 1 - v (default true: glTF's convention)
|
||||
mtl: (string | buffer)?, -- the material library text, when not found through resolve / files
|
||||
resolve: ((uri: string) -> any)?, -- reads mtllib / texture files (the api sets it for paths)
|
||||
files: { [string]: any }?, -- or: the other files by name
|
||||
triangulate: boolean?, -- default true
|
||||
flipV: boolean?, -- default true
|
||||
mtl: (string | buffer)?,
|
||||
resolve: ((uri: string) -> any)?,
|
||||
files: { [string]: any }?,
|
||||
maxVertices: number?, -- refuse more v / vt / vn / corners (default 2^25)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
name: string?, -- the destination file name: the .mtl is named after it (default "model.mtl")
|
||||
mtlName: string?, -- the .mtl file name (overrides name)
|
||||
files: { [string]: any }?, -- receives the .mtl and embedded textures
|
||||
name: string?, -- default "model.mtl"
|
||||
mtlName: string?,
|
||||
files: { [string]: any }?,
|
||||
flipV: boolean?, -- default true (the inverse of decode)
|
||||
normals: boolean?, -- write vn (default true when the primitives have NORMAL)
|
||||
texcoords: boolean?, -- write vt (default true when the primitives have TEXCOORD_0)
|
||||
colors: boolean?, -- write vertex colours after v (default true when COLOR_0 exists)
|
||||
normals: boolean?, -- default true when the primitives have NORMAL
|
||||
texcoords: boolean?, -- default true when the primitives have TEXCOORD_0
|
||||
colors: boolean?, -- default true when COLOR_0 exists
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
@@ -146,7 +136,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
end
|
||||
return p
|
||||
end
|
||||
-- one corner "v/vt/vn" -> indices (0-based, -1 for none) | nil
|
||||
local function corner(tok: string): (number?, number, number)
|
||||
local a, b, c = string.match(tok, "^([^/]*)/?([^/]*)/?([^/]*)$")
|
||||
local vi = tonumber(a)
|
||||
@@ -180,7 +169,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
local line = string.sub(text, pos, e - 1)
|
||||
pos = e + 1
|
||||
lineNo += 1
|
||||
-- continuation lines
|
||||
while string.sub(line, -1) == "\\" or string.sub(line, -2) == "\\\r" do
|
||||
line = string.gsub(line, "\\\r?$", " ")
|
||||
local e2 = string.find(text, "\n", pos, true) or (len + 1)
|
||||
@@ -192,7 +180,7 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
if key == nil or string.sub(key, 1, 1) == "#" then
|
||||
continue
|
||||
end
|
||||
local rest: string = rest :: string -- both captures match together
|
||||
local rest: string = rest :: string
|
||||
local hash = string.find(rest, "#", 1, true)
|
||||
if hash then
|
||||
rest = string.gsub(string.sub(rest, 1, hash - 1), "%s+$", "")
|
||||
@@ -266,7 +254,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
end
|
||||
end
|
||||
if mode == "triangles" and k > 3 then
|
||||
-- fan: rewrite the k corners as (k - 2) triangles
|
||||
local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {})
|
||||
local o = base
|
||||
for a = 2, k - 1 do
|
||||
@@ -276,7 +263,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
end
|
||||
end
|
||||
elseif mode == "lines" then
|
||||
-- a polyline -> segments
|
||||
local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {})
|
||||
local o = base
|
||||
for a = 1, k - 1 do
|
||||
@@ -309,7 +295,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
skipped += 1
|
||||
end
|
||||
end
|
||||
-- materials
|
||||
local scene = Types.Scene.new()
|
||||
local matIndex: { [string]: number } = {}
|
||||
local texIndex: { [string]: number } = {}
|
||||
@@ -354,7 +339,7 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
end
|
||||
end
|
||||
end
|
||||
-- materials named by usemtl but not defined anywhere: a default one with the name
|
||||
-- usemtl of an undefined material: a default one with that name
|
||||
for _, s in sections do
|
||||
for _, p in s.prims do
|
||||
if p.material and not matIndex[p.material] then
|
||||
@@ -364,7 +349,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
end
|
||||
end
|
||||
end
|
||||
-- vertices: one per distinct (v, vt, vn) in each primitive
|
||||
local f32 = buffer.writef32
|
||||
local KT, KN = nt + 1, nn + 1
|
||||
local numericKeys = np * KT * KN < 2 ^ 52
|
||||
@@ -434,7 +418,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
end
|
||||
return out
|
||||
end
|
||||
-- nodes: objects at the root, their groups as children; without objects every group is a root
|
||||
local objectNode: { [string]: number } = {}
|
||||
for _, s in sections do
|
||||
if #s.prims > 0 then
|
||||
@@ -463,7 +446,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
objectNode[s.object] = #scene.nodes
|
||||
table.insert(scene.roots, #scene.nodes)
|
||||
elseif hasObjects and s.object and objectNode[s.object] then
|
||||
-- the object's own faces after its groups: a child too
|
||||
table.insert(scene.nodes, node)
|
||||
table.insert(scene.nodes[objectNode[s.object]].children, #scene.nodes)
|
||||
else
|
||||
@@ -488,7 +470,6 @@ function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- the shortest decimal that reads back as the same f32
|
||||
local probe = buffer.create(4)
|
||||
local function f32str(v: number): string
|
||||
if v ~= v or v == math.huge or v == -math.huge then
|
||||
@@ -527,7 +508,6 @@ function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
|
||||
local placed = Types.Scene.flatten(scene)
|
||||
local out = { "# written by rosetta" }
|
||||
local mats = scene.materials or {}
|
||||
-- material names (unique), texture file names
|
||||
local names: { string } = {}
|
||||
local used: { [string]: boolean } = {}
|
||||
for i, m in mats do
|
||||
@@ -595,7 +575,6 @@ function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
|
||||
return nil, Err.new(Err.ARG, "an attribute is shorter than POSITION")
|
||||
end
|
||||
end
|
||||
-- the normal matrix (inverse transpose) for baked normals
|
||||
local nm: { number }? = nil
|
||||
if Nr and not ident then
|
||||
local a, b, c, d, e, f, g, h, i = m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11]
|
||||
@@ -647,7 +626,6 @@ function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
|
||||
end
|
||||
return s
|
||||
end
|
||||
-- the corner list
|
||||
local ind = prim.indices
|
||||
local I: ((number, number) -> number)? = if ind then Types.Scene.reader(ind) else nil
|
||||
local count = if ind then ind.count else n
|
||||
@@ -743,7 +721,6 @@ function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- encodeMtl(scene, opts?) -> the .mtl text for the scene's materials (what encode puts in opts.files)
|
||||
function Obj.encodeMtl(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
if type(scene) ~= "table" or type(scene.materials) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "needs a Scene")
|
||||
|
||||
@@ -1,21 +1,7 @@
|
||||
--!strict
|
||||
-- model/off: OFF (Geomview Object File Format), text, read + write. Written from the Geomview OFF description
|
||||
-- (geomview.org/docs/html/OFF.html).
|
||||
-- Decode: the header keyword [ST][C][N]OFF (texture coordinates, vertex colours, normals; the counts may follow on the
|
||||
-- same line), `nv nf [ne]`, vertex lines `x y z [nx ny nz] [r g b [a]] [s t]`, face lines `n i1 .. in [colour]`;
|
||||
-- `#` comments and blank lines anywhere. Vertices: POSITION f32 x3, NORMAL f32 x3, TEXCOORD_0 f32 x2, COLOR_0: unorm8
|
||||
-- x4 when the colours are integers (0..255) and some value is above 1, else f32 x4 (alpha full when only RGB is given).
|
||||
-- Faces: triangles as u32 indices; n-gons fan-triangulated (opts.triangulate, default true: right for convex faces;
|
||||
-- faces of fewer than 3 vertices are dropped, prim.extras.faceOfTriangle maps triangles to file faces when there are
|
||||
-- face colours) or kept as mode "polygons" (prim.faces). Face colours (3 or 4 values after the indices; integers or
|
||||
-- floats as for vertices; faces without one get opaque white): prim.extras.faceColors, one per file face. A single
|
||||
-- value after the indices (a colormap index) is ignored (meta.source.colormap = true). No faces: mode "points".
|
||||
-- meta.source = { format, keyword, vertices, faces, edges }.
|
||||
-- Encode: every primitive in world space (node transforms applied) into one vertex list, NOFF / COFF / STOFF prefixes
|
||||
-- for NORMAL / COLOR_0 / TEXCOORD_0 (unorm8 colours as integers 0..255, other colour types as floats 0..1), n-gons
|
||||
-- natively, face colours from prim.extras.faceColors (a single primitive), point clouds with 0 faces; lines are
|
||||
-- skipped. Floats print as %.9g (f32-exact). Not supported: 4OFF / nOFF (homogeneous / n-dimensional) and binary OFF
|
||||
-- (UNSUPPORTED).
|
||||
-- model/off: Geomview OFF text (geomview.org/docs/html/OFF.html), read + write. Supports: [ST][C][N]OFF, face colours
|
||||
-- (prim.extras.faceColors), n-gons (fan-triangulated or "polygons"), point clouds; floats as %.9g (f32-exact).
|
||||
-- Not supported: 4OFF / nOFF, binary OFF; colormap-index face colours are ignored.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -35,15 +21,15 @@ local Off = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps them as mode "polygons"
|
||||
triangulate: boolean?, -- default true
|
||||
maxVertices: number?, -- default 2^24
|
||||
maxFaces: number?, -- default 2^25
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
colors: boolean?, -- write COLOR_0 (COFF) and prim.extras.faceColors when present (default true)
|
||||
normals: boolean?, -- write NORMAL (NOFF) when present (default true)
|
||||
texcoords: boolean?, -- write TEXCOORD_0 (STOFF) when present (default true)
|
||||
comment: string?, -- a "# ..." line after the header keyword
|
||||
colors: boolean?, -- default true
|
||||
normals: boolean?, -- default true
|
||||
texcoords: boolean?, -- default true
|
||||
comment: string?,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
@@ -52,7 +38,7 @@ local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writ
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Off.sniff(r: Bytes.Reader): number
|
||||
local head = r:peek(512)
|
||||
for _ = 1, 16 do -- leading comment lines
|
||||
for _ = 1, 16 do
|
||||
local rest = string.match(head, "^%s*#[^\n]*\n(.*)$")
|
||||
if not rest then
|
||||
break
|
||||
@@ -67,14 +53,13 @@ function Off.sniff(r: Bytes.Reader): number
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- colours: a list of numbers + whether a token looked like a float; decide unorm8 or f32
|
||||
-- unorm8 when every value is an integer and some value is above 1, else f32
|
||||
type ColorSet = { values: { number }, float: boolean, max: number }
|
||||
|
||||
local function colorType(c: ColorSet): string
|
||||
return if not c.float and c.max > 1 then "unorm8" else "f32"
|
||||
end
|
||||
|
||||
-- the colour accessor for count entries of 4 values (nan = absent: opaque white)
|
||||
local function colorAccessor(c: ColorSet, count: number): (Types.Accessor?, string?)
|
||||
local t = colorType(c)
|
||||
local buf = buffer.create(count * (if t == "unorm8" then 4 else 16))
|
||||
@@ -109,7 +94,7 @@ local function addColor(c: ColorSet, toks: { string }, from: number, n: number)
|
||||
c.max = v
|
||||
end
|
||||
else
|
||||
table.insert(vals, 0 / 0) -- absent: full (opaque white)
|
||||
table.insert(vals, 0 / 0)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -122,7 +107,6 @@ function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
local maxVertices = opts and opts.maxVertices or 2 ^ 24
|
||||
local maxFaces = opts and opts.maxFaces or 2 ^ 25
|
||||
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
|
||||
-- the next non-empty line's tokens (comments stripped)
|
||||
local at = 1
|
||||
local lineNo = 0
|
||||
local function line(): { string }?
|
||||
@@ -188,7 +172,6 @@ function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
if nf > maxFaces then
|
||||
return nil, Err.new(Err.LIMIT, string.format("%d faces is over the %d face limit", nf, maxFaces))
|
||||
end
|
||||
-- every vertex / face line takes at least 6 / 2 bytes
|
||||
if nv * 6 + nf * 2 > #text - at + 2 then
|
||||
return nil, Err.new(Err.TRUNCATED, "fewer lines than the counts need")
|
||||
end
|
||||
@@ -273,7 +256,6 @@ function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
addColor(fcol, t, 1, 0)
|
||||
end
|
||||
end
|
||||
-- the primitive
|
||||
local attrs: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, nv) }
|
||||
if nrm then
|
||||
attrs.NORMAL = Types.Scene.accessor(nrm, "f32", 3, nv)
|
||||
@@ -367,7 +349,6 @@ local function fnum(v: number): string?
|
||||
return string.format("%.9g", v)
|
||||
end
|
||||
|
||||
-- a colour attribute's 4 components of entry i (0-based) as text
|
||||
local function colorText(a: Flatten.Attr, vals: { number }, comps: number, i: number): string
|
||||
local out = table.create(4)
|
||||
for c = 1, 4 do
|
||||
@@ -429,7 +410,6 @@ function Off.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
|
||||
end
|
||||
table.insert(out, s)
|
||||
end
|
||||
-- face colours of a single primitive (per file face, or through faceOfTriangle)
|
||||
local fc: Flatten.Attr? = nil
|
||||
local fcMap: { number }? = nil
|
||||
if wantC and #m.parts == 1 and nf > 0 then
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- model/ply/Binary: PLY element data loops. Value read / write by type code (1 i8, 2 u8, 3 i16, 4 u16, 5 i32, 6 u32,
|
||||
-- 7 f32, 8 f64) in either byte order, the column copy of fixed-size rows (scalar properties only) and the row walk of
|
||||
-- rows with lists (a scan for the list totals, then the fill). The caller (init) sizes every destination from the
|
||||
-- header counts and the scan, and checks the rows fit in the data first, so every index here is in range; a bad list
|
||||
-- count or an out-of-range vertex index returns false / -1 with a message. Nothing here throws.
|
||||
-- model/ply/Binary: PLY element data loops; type codes 1 i8, 2 u8, 3 i16, 4 u16, 5 i32, 6 u32, 7 f32, 8 f64, either
|
||||
-- byte order. Never throws: the caller bounds every row first.
|
||||
local readu8, readi8, readu16, readi16, readu32, readi32 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32
|
||||
local readf32, readf64 = buffer.readf32, buffer.readf64
|
||||
local writeu8, writei8, writeu16, writei16, writeu32, writei32 = buffer.writeu8, buffer.writei8, buffer.writeu16, buffer.writei16, buffer.writeu32, buffer.writei32
|
||||
@@ -22,7 +19,6 @@ local function swap16(v: number): number
|
||||
return rshift(v, 8) + band(v, 255) * 256
|
||||
end
|
||||
|
||||
-- rd(b, q, code, be) -> the value at q
|
||||
local function rd(b: buffer, q: number, code: number, be: boolean): number
|
||||
if not be then
|
||||
if code == 7 then
|
||||
@@ -63,7 +59,6 @@ local function rd(b: buffer, q: number, code: number, be: boolean): number
|
||||
end
|
||||
Binary.rd = rd
|
||||
|
||||
-- wr(d, o, code, v): v as code, little endian
|
||||
local function wr(d: buffer, o: number, code: number, v: number)
|
||||
if code == 7 then
|
||||
writef32(d, o, v)
|
||||
@@ -85,7 +80,6 @@ local function wr(d: buffer, o: number, code: number, v: number)
|
||||
end
|
||||
Binary.wr = wr
|
||||
|
||||
-- put(d, o, code, v, be): v as code in either byte order (the writer)
|
||||
function Binary.put(d: buffer, o: number, code: number, v: number, be: boolean)
|
||||
if not be or code <= 2 then
|
||||
wr(d, o, code, v)
|
||||
@@ -102,7 +96,6 @@ function Binary.put(d: buffer, o: number, code: number, v: number, be: boolean)
|
||||
end
|
||||
end
|
||||
|
||||
-- fixed(b, p, n, rowSize, np, srcOff, code, be, dst, dOff, dStride, dCode): column copies of n fixed-size rows at p
|
||||
function Binary.fixed(b: buffer, p: number, n: number, rowSize: number, np: number, srcOff: { number }, code: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number })
|
||||
for k = 1, np do
|
||||
local sc, dc, d = code[k], dCode[k], dst[k]
|
||||
@@ -135,8 +128,6 @@ function Binary.fixed(b: buffer, p: number, n: number, rowSize: number, np: numb
|
||||
end
|
||||
end
|
||||
|
||||
-- scan(b, p, limit, n, np, code, isList, countCode, be) -> the end offset and the item total of each list property,
|
||||
-- or -1, message (truncated rows, a negative / fractional count)
|
||||
function Binary.scan(b: buffer, p: number, limit: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean): (number, any)
|
||||
local totals = table.create(np, 0)
|
||||
local q = p
|
||||
@@ -168,10 +159,6 @@ function Binary.scan(b: buffer, p: number, limit: number, n: number, np: number,
|
||||
return q, totals
|
||||
end
|
||||
|
||||
-- rows(b, p, n, np, code, isList, countCode, be, dst, dOff, dStride, dCode, sizes, bound) -> true | false, message.
|
||||
-- Scalars go to dst[k] at dOff + row * dStride as dCode; lists write their count to sizes[k] (u32 per row) and their
|
||||
-- items one after the other into dst[k] as dCode; bound[k] >= 0 checks items are integers in 0 .. bound - 1. The rows
|
||||
-- must have passed scan() with the same arguments.
|
||||
function Binary.rows(b: buffer, p: number, n: number, np: number, code: { number }, isList: { boolean }, countCode: { number }, be: boolean, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }, sizes: { buffer }, bound: { number }): (boolean, string?)
|
||||
local at = table.create(np, 0)
|
||||
local q = p
|
||||
|
||||
@@ -1,24 +1,7 @@
|
||||
--!strict
|
||||
-- model/ply: PLY (Stanford polygon file format, Greg Turk 1994), ascii / binary_little_endian / binary_big_endian,
|
||||
-- read + write. Written from the format description (paulbourke.net/dataformats/ply, the rply / plyfile behaviour).
|
||||
-- Decode: the vertex element maps x y z -> POSITION f32 x3, nx ny nz -> NORMAL f32 x3, red green blue [alpha] ->
|
||||
-- COLOR_0 (uchar: unorm8 x4, ushort: unorm16 x4, float / double: f32 x4; alpha full when absent), u v / s t / texture_u
|
||||
-- texture_v / texture_s texture_t -> TEXCOORD_0 f32 x2, every other property -> "_" .. name in its own type (char ->
|
||||
-- i8, uchar -> u8, ..., double -> f64). Doubles in x / y / z / normals / texcoords become f32. The face element's
|
||||
-- vertex_indices / vertex_index list gives the faces: triangles stay triangles (u32 indices), n-gons are
|
||||
-- fan-triangulated (opts.triangulate, default true: right for convex faces; faces of fewer than 3 vertices are
|
||||
-- dropped) or kept as mode "polygons" (prim.faces = vertex count per face). No faces: a point cloud (mode "points",
|
||||
-- no indices). Other face properties: prim.extras.faceAttributes[name] (one value per file face, its own type), face
|
||||
-- lists: prim.extras.faceLists[name] = { countType, itemType, sizes (u32 accessor), items (accessor) }; after
|
||||
-- triangulating n-gons prim.extras.faceOfTriangle (u32, 0-based) maps triangles to file faces. Other elements (edge,
|
||||
-- material, ...) are kept raw in scene.meta.ply.elements (in their types) and written back, as are comments
|
||||
-- (meta.ply.comments), obj_info lines (meta.ply.objInfo), the element order and the vertex / face property order and
|
||||
-- types. meta.source = { format, encoding, vertices, faces }.
|
||||
-- Encode: every primitive in world space (node transforms applied) into one vertex list: POSITION, NORMAL, COLOR_0,
|
||||
-- TEXCOORD_0 and "_" attributes (under their name, in their type; several components: name_0, name_1, ...), faces
|
||||
-- (triangles and polygons natively as `property list uchar int vertex_indices`, a wider count / uint index type when
|
||||
-- needed), point clouds without a face element; lines are skipped. Floats print as %.9g (f32-exact), doubles %.17g.
|
||||
-- Not supported: list properties in the vertex element (UNSUPPORTED).
|
||||
-- model/ply: Stanford PLY (Greg Turk 1994; paulbourke.net/dataformats/ply, rply / plyfile behaviour), ascii and
|
||||
-- binary either endian, read + write. Supports: every property type, faces (fan-triangulated or "polygons"), point
|
||||
-- clouds; other elements, comments, obj_info and property order round-trip. Not supported: vertex list properties.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -39,13 +22,13 @@ local Ply = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps them as mode "polygons"
|
||||
triangulate: boolean?, -- default true
|
||||
maxVertices: number?, -- default 2^24
|
||||
maxFaces: number?, -- faces, and rows of any other element (default 2^25)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
format: ("binary_little_endian" | "binary_big_endian" | "ascii")?, -- default "binary_little_endian"
|
||||
comments: { string }?, -- extra comment lines (after those in scene.meta.ply.comments)
|
||||
comments: { string }?,
|
||||
}
|
||||
|
||||
type Prop = { name: string, ply: string, code: number, list: boolean, countPly: string?, countCode: number? }
|
||||
@@ -115,7 +98,6 @@ local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?)
|
||||
if first then
|
||||
first = false -- "ply"
|
||||
elseif kw == nil then
|
||||
-- blank line
|
||||
elseif kw == "end_header" then
|
||||
h.dataStart = base + at - 1
|
||||
break
|
||||
@@ -175,7 +157,6 @@ local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?)
|
||||
return h, nil
|
||||
end
|
||||
|
||||
-- the reading plan of one element: per property, where its values go
|
||||
type Plan = {
|
||||
code: { number },
|
||||
isList: { boolean },
|
||||
@@ -213,7 +194,6 @@ local function newPlan(e: Elem): Plan
|
||||
return pl
|
||||
end
|
||||
|
||||
-- unset scalar destinations get their own native buffer
|
||||
local function ownBuffers(e: Elem, pl: Plan)
|
||||
for k, p in e.props do
|
||||
if not p.list and pl.dst[k] == nil then
|
||||
@@ -222,7 +202,6 @@ local function ownBuffers(e: Elem, pl: Plan)
|
||||
end
|
||||
end
|
||||
|
||||
-- read one element's rows (binary) into the plan; returns the next offset or nil, Err
|
||||
local function readBinary(r: Bytes.Reader, p: number, e: Elem, pl: Plan, be: boolean): (number?, Err.Err?)
|
||||
local b, limit, n, np = r.buf, r.limit, e.count, #e.props
|
||||
local hasList, rowSize = false, 0
|
||||
@@ -267,7 +246,6 @@ local function readBinary(r: Bytes.Reader, p: number, e: Elem, pl: Plan, be: boo
|
||||
return q, nil
|
||||
end
|
||||
|
||||
-- a token as a value of type code, or nil
|
||||
local function value(tok: string?, code: number): number?
|
||||
if tok == nil then
|
||||
return nil
|
||||
@@ -283,7 +261,6 @@ local function value(tok: string?, code: number): number?
|
||||
return v
|
||||
end
|
||||
|
||||
-- read one element's rows (ascii) from the token stream
|
||||
local function readAscii(nextTok: () -> string?, e: Elem, pl: Plan): Err.Err?
|
||||
ownBuffers(e, pl)
|
||||
local n = e.count
|
||||
@@ -352,7 +329,6 @@ local function propIndex(e: Elem, name: string): number?
|
||||
return nil
|
||||
end
|
||||
|
||||
-- vertex element -> attributes: sets the plan's destinations, returns the attribute table
|
||||
local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Err.Err?)
|
||||
local nv = e.count
|
||||
local attrs: { [string]: Types.Accessor } = {}
|
||||
@@ -362,7 +338,6 @@ local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Er
|
||||
return nil, Err.new(Err.UNSUPPORTED, "list property " .. p.name .. " in the vertex element")
|
||||
end
|
||||
end
|
||||
-- group(attr, names, required, ok, comps, fill): the first `required` names must exist, the others are optional
|
||||
local function group(attr: string, names: { string }, required: number, ok: (codes: { number }) -> number?, comps: number, fillValue: number?)
|
||||
local ks: { [number]: number } = {}
|
||||
local codes = {}
|
||||
@@ -408,7 +383,6 @@ local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Er
|
||||
end
|
||||
group("POSITION", { "x", "y", "z" }, 3, anyNumber, 3, nil)
|
||||
group("NORMAL", { "nx", "ny", "nz" }, 3, floats, 3, nil)
|
||||
-- colours: one type class for all channels
|
||||
do
|
||||
local rk, gk, bk, ak = propIndex(e, "red"), propIndex(e, "green"), propIndex(e, "blue"), propIndex(e, "alpha")
|
||||
if rk and gk and bk then
|
||||
@@ -447,7 +421,6 @@ local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Er
|
||||
return attrs, nil
|
||||
end
|
||||
|
||||
-- the fan triangulation of faces with sizes / corners; returns indices (u32), triangle count, faceOfTriangle
|
||||
local function fan(sizes: buffer, corners: buffer, nf: number): (buffer, number, buffer)
|
||||
local nt = 0
|
||||
for f = 0, nf - 1 do
|
||||
@@ -513,7 +486,6 @@ function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
end
|
||||
if ascii then
|
||||
local body = buffer.readstring(r.buf, h.dataStart, r.limit - h.dataStart)
|
||||
-- each value takes at least 2 bytes (a digit and a separator): bound the counts before allocating
|
||||
local need = 0
|
||||
for _, e in h.elems do
|
||||
need += e.count * #e.props
|
||||
@@ -527,7 +499,6 @@ function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
local attrs: { [string]: Types.Accessor } = {}
|
||||
local p = h.dataStart
|
||||
if not ascii then
|
||||
-- every row takes at least its scalar sizes and list counts: bound the counts before allocating
|
||||
local need = 0
|
||||
for _, e in h.elems do
|
||||
local row = 0
|
||||
@@ -566,7 +537,6 @@ function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
p = q
|
||||
end
|
||||
end
|
||||
-- the primitive
|
||||
local prim: Types.Primitive = { attributes = attrs, mode = "points" }
|
||||
local nf = 0
|
||||
local extras: { [string]: any } = {}
|
||||
@@ -630,7 +600,6 @@ function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
if next(extras) then
|
||||
prim.extras = extras
|
||||
end
|
||||
-- raw elements, element order, property order
|
||||
local elements: { any } = {}
|
||||
local order: { string } = {}
|
||||
for i, e in h.elems do
|
||||
@@ -662,7 +631,6 @@ function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- a column to write: ply type code + spelling, the values (one per row, or per row * stride at offset)
|
||||
type Column = { name: string, ply: string, code: number, values: { number }, stride: number, offset: number }
|
||||
type ListColumn = { name: string, ply: string, code: number, countPly: string, countCode: number, sizes: { number }, items: { number } }
|
||||
|
||||
@@ -670,7 +638,6 @@ local function keep(name: string): boolean
|
||||
return name == "NORMAL" or name == "COLOR_0" or name == "TEXCOORD_0" or string.sub(name, 1, 1) == "_"
|
||||
end
|
||||
|
||||
-- the spelling `want` from the source file when it means the same type as code, else the classic name
|
||||
local function spell(want: string?, code: number): string
|
||||
if want and CODES[want] == code then
|
||||
return want
|
||||
@@ -689,7 +656,6 @@ local function toInt(v: number, code: number): number
|
||||
return v
|
||||
end
|
||||
|
||||
-- write rows of columns (+ list columns, in `order`) for n rows: ascii lines into out, binary into the writer
|
||||
type Row = { kind: "s", col: Column } | { kind: "l", col: ListColumn }
|
||||
|
||||
local function rowsAscii(out: { string }, n: number, cols: { Row })
|
||||
@@ -762,7 +728,6 @@ local function rowsBinary(w: Bytes.Writer, n: number, cols: { Row }, be: boolean
|
||||
w.pos = o
|
||||
end
|
||||
|
||||
-- numbers of a raw element column (buffer of a ply type)
|
||||
local function bufNumbers(b: any, code: number, count: number): { number }?
|
||||
if type(b) ~= "buffer" or buffer.len(b) < count * SIZE[code] then
|
||||
return nil
|
||||
@@ -774,7 +739,6 @@ local function bufNumbers(b: any, code: number, count: number): { number }?
|
||||
return out
|
||||
end
|
||||
|
||||
-- the list count type for a maximum count
|
||||
local function countCodeFor(maxCount: number): number
|
||||
return if maxCount <= 255 then 2 elseif maxCount <= 65535 then 4 else 6
|
||||
end
|
||||
@@ -791,7 +755,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
|
||||
end
|
||||
local meta: any = if type(scene) == "table" and type(scene.meta) == "table" and type(scene.meta.ply) == "table" then scene.meta.ply else {}
|
||||
local nv = m.count
|
||||
-- source property spellings / order
|
||||
local srcType: { [string]: string } = {}
|
||||
local srcOrder: { [string]: number } = {}
|
||||
if type(meta.vertexProperties) == "table" then
|
||||
@@ -822,7 +785,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
|
||||
if C then
|
||||
local code = if C.raw and C.type == "unorm8" then 2 elseif C.raw and C.type == "unorm16" then 4 else 7
|
||||
if C.raw and code == 7 then
|
||||
-- another normalized type: as floats
|
||||
local vals = table.create(#C.values)
|
||||
local scale = if C.type == "snorm8" then 127 else 32767
|
||||
for i, v in C.values do
|
||||
@@ -888,7 +850,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the source order first (stable for the rest)
|
||||
local rank: { [Column]: number } = {}
|
||||
for i, c in cols do
|
||||
rank[c] = (srcOrder[c.name] or (1000000 + i))
|
||||
@@ -896,7 +857,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
|
||||
table.sort(cols, function(a: Column, b: Column): boolean
|
||||
return rank[a] < rank[b]
|
||||
end)
|
||||
-- faces
|
||||
local faceRows: { Row }? = nil
|
||||
local nf = 0
|
||||
if m.sizes then
|
||||
@@ -929,7 +889,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
|
||||
local rows: { Row } = {
|
||||
{ kind = "l", col = { name = idxName, ply = spell(idxType, ic), code = ic, countPly = spell(idxCount, cc), countCode = cc, sizes = sizes, items = m.corners } },
|
||||
}
|
||||
-- per-face data of a single primitive
|
||||
if #m.parts == 1 then
|
||||
local ex = m.parts[1].prim.extras
|
||||
local fot: { number }? = nil
|
||||
@@ -984,7 +943,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the source order, then the rest by name
|
||||
local placed: { [string]: boolean } = { [idxName] = true }
|
||||
local ordered: { Row } = {}
|
||||
for _, fp in fprops do
|
||||
@@ -1014,7 +972,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
|
||||
end
|
||||
faceRows = rows
|
||||
end
|
||||
-- raw elements
|
||||
type Raw = { name: string, count: number, rows: { Row } }
|
||||
local raws: { [string]: Raw } = {}
|
||||
local rawOrder: { string } = {}
|
||||
@@ -1057,7 +1014,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
|
||||
end
|
||||
end
|
||||
end
|
||||
-- element order: the source's, then vertex, face, the rest
|
||||
local order: { string } = {}
|
||||
local seen: { [string]: boolean } = {}
|
||||
local function want(name: string)
|
||||
@@ -1081,7 +1037,6 @@ function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
|
||||
for _, name in rawOrder do
|
||||
want(name)
|
||||
end
|
||||
-- header
|
||||
local vrows: { Row } = {}
|
||||
for _, c in cols do
|
||||
table.insert(vrows, { kind = "s" :: "s", col = c })
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
--!strict
|
||||
-- model/pmx/Build: the parsed PMX / PMD model (model/pmx/Read, model/pmx/Pmd) to a Scene. MMD is left-handed (y up,
|
||||
-- x right, z forward), so positions / normals / bone positions get z negated and every triangle its winding reversed
|
||||
-- (glTF's right-handed, counter-clockwise front faces); UVs are already top-left. One primitive per material, with
|
||||
-- the material's vertices only (JOINTS_0 / WEIGHTS_0, the additional UVs as _UVA1.._UVA4 vec4, SDEF C / R0 / R1 as
|
||||
-- _SDEF_C / _SDEF_R0 / _SDEF_R1 and the deform type as _DEFORM when a vertex uses SDEF / QDEF, _EDGE_SCALE); vertex
|
||||
-- morphs become morph targets (POSITION deltas, names in mesh.extras.targetNames); bones become nodes (a parent-relative
|
||||
-- translation each) and one skin with translation-only inverse bind matrices.
|
||||
-- model/pmx/Build: the PMX / PMD model table to a Scene. MMD is left-handed (y up, x right, z forward): z is negated
|
||||
-- and every winding reversed; UVs are already top-left.
|
||||
local Types = require("@rosetta/Types")
|
||||
|
||||
local Build = {}
|
||||
@@ -17,7 +12,6 @@ local SPHERE = { [0] = "off", "multiply", "add", "subtexture" }
|
||||
local MORPH = { [0] = "group", "vertex", "bone", "uv", "uv1", "uv2", "uv3", "uv4", "material", "flip", "impulse" }
|
||||
local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", spa = "image/bmp", sph = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" }
|
||||
|
||||
-- fetch(uri) -> buffer?: opts.files (by the name as written, with "/" separators, or the base name) / opts.resolve
|
||||
local function fetcher(opts: any): (string) -> buffer?
|
||||
return function(uri: string): buffer?
|
||||
if not opts then
|
||||
@@ -40,7 +34,6 @@ local function lh(v: { number }?): { number }?
|
||||
return if v then { v[1], v[2], -v[3] } else nil
|
||||
end
|
||||
|
||||
-- the scene index of a file texture index (0-based, -1 = none)
|
||||
local function texIndex(m: any, i: number?): number?
|
||||
return if type(i) == "number" and i >= 0 and i < #m.textures then i + 1 else nil
|
||||
end
|
||||
@@ -73,7 +66,6 @@ local function material(m: any, mat: any): Types.Material
|
||||
return out
|
||||
end
|
||||
|
||||
-- bone parents that form a tree: an invalid index, the bone itself or a cycle makes a root
|
||||
local function parents(bones: { any }): { number }
|
||||
local nb = #bones
|
||||
local par = table.create(nb, 0)
|
||||
@@ -98,7 +90,6 @@ local function parents(bones: { any }): { number }
|
||||
return par
|
||||
end
|
||||
|
||||
-- the primitive of one material: indices [first, first + n) of the face list, its vertices renumbered
|
||||
local function primitive(m: any, first: number, n: number, morphs: { any }, sdef: boolean): Types.Primitive
|
||||
local map: { [number]: number } = {}
|
||||
local verts: { number } = {}
|
||||
@@ -150,7 +141,6 @@ local function primitive(m: any, first: number, n: number, morphs: { any }, sdef
|
||||
for a, acc in uvas do
|
||||
buffer.copy(acc.data, v * 16, m.uva[a], src * 16, 16)
|
||||
end
|
||||
-- weights: invalid bones get weight 0, the rest is normalized
|
||||
local sum = 0
|
||||
local js, ws = table.create(4, 0), table.create(4, 0)
|
||||
for c = 0, 3 do
|
||||
@@ -217,7 +207,6 @@ function Build.scene(m: any, opts: any): (any, ...any)
|
||||
scene.materials[i] = material(m, mat)
|
||||
end
|
||||
|
||||
-- vertex morphs -> targets (others stay in mesh.extras.pmx.morphs)
|
||||
local vmorphs, names, others = {}, {}, {}
|
||||
local wantMorphs = not (opts and opts.morphs == false)
|
||||
for _, mo in m.morphs do
|
||||
@@ -253,7 +242,6 @@ function Build.scene(m: any, opts: any): (any, ...any)
|
||||
first += n
|
||||
end
|
||||
if first < m.indexCount then
|
||||
-- faces no material covers
|
||||
table.insert(mesh.primitives, primitive(m, first, m.indexCount - first, vmorphs, sdef))
|
||||
end
|
||||
mesh.extras = { targetNames = if #names > 0 then names else nil, pmx = if #others > 0 then { morphs = others } else nil }
|
||||
@@ -262,7 +250,6 @@ function Build.scene(m: any, opts: any): (any, ...any)
|
||||
end
|
||||
scene.meshes[1] = mesh
|
||||
|
||||
-- nodes: 1 = the model, 2 = the mesh, then one per bone
|
||||
scene.nodes[1] = { name = m.name, children = { 2 } }
|
||||
scene.nodes[2] = { name = m.name .. "_mesh", children = {}, mesh = 1 }
|
||||
scene.roots[1] = 1
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
--!strict
|
||||
-- model/pmx/Pmd: the PMD 1.0 parser (MikuMikuDance's original model format), into the same model table as
|
||||
-- model/pmx/Read so model/pmx/Build makes the Scene. Written from the PMD layout as documented by the MMD community
|
||||
-- (MMDAgent / mmd_tools notes); no third-party code. Reads vertices (two bones, weight 0..100, edge flag), faces,
|
||||
-- materials ("texture*sphere" names, toon index), bones, IK chains, skins (the base skin + vertex morphs relative to
|
||||
-- it), display lists, the optional English names, toon texture names, rigid bodies and joints. Names are Shift-JIS in
|
||||
-- the file: ASCII names are kept, others use the English name when there is one, else the raw bytes (in
|
||||
-- extras / meta.source as `nameSjis`). Never throws: returns nil, message[, kind].
|
||||
-- model/pmx/Pmd: PMD 1.0, from the MMD community layout notes (MMDAgent / mmd_tools); no third-party code. Names are
|
||||
-- Shift-JIS: kept when ASCII, else the English name, else the raw bytes (`nameSjis`). Never throws.
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
|
||||
local Pmd = {}
|
||||
@@ -96,7 +91,7 @@ function Pmd.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...a
|
||||
r.pos += ni * 2
|
||||
m.indexCount, m.indices = ni, ind
|
||||
|
||||
-- materials: 70 bytes each; texture names collected into the texture list
|
||||
-- materials: 70 bytes each
|
||||
local nm = r:u32le()
|
||||
ok, e = counted(r, nm, 70, "materials")
|
||||
if r.err or not ok then
|
||||
@@ -159,7 +154,6 @@ function Pmd.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...a
|
||||
m.bones[i] = b
|
||||
end
|
||||
|
||||
-- IK chains
|
||||
local nik = r:u16le()
|
||||
for _ = 1, nik do
|
||||
local bone, target, len, loops, limit = r:u16le(), r:u16le(), r:u8(), r:u16le(), r:f32le()
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
--!strict
|
||||
-- model/pmx/Read: the PMX 2.0 / 2.1 parser (MikuMikuDance / PmxEditor model files), into the plain model table that
|
||||
-- model/pmx/Build turns into a Scene. Written from the PMX 2.0 / 2.1 specification notes that ship with PmxEditor.
|
||||
-- Reads every section: header globals (UTF-16LE / UTF-8 text, additional UV count, index sizes 1 / 2 / 4), vertices
|
||||
-- (BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF), faces, textures, materials, bones (tail, inherit, fixed / local axes,
|
||||
-- external parent, IK), morphs (group, vertex, bone, UV, UV1-4, material, flip, impulse), display frames, rigid bodies,
|
||||
-- joints; 2.1 soft bodies are counted, not parsed. Values stay as in the file (left-handed, 0-based indices).
|
||||
-- Never throws: returns nil, message[, kind].
|
||||
-- model/pmx/Read: PMX 2.0 / 2.1, from the specification notes that ship with PmxEditor; values as in the file
|
||||
-- (left-handed, 0-based indices); 2.1 soft bodies are counted, not parsed. Never throws.
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Text = require("@rosetta/codecs/text/Text")
|
||||
|
||||
@@ -33,7 +28,7 @@ local function vec(r: Bytes.Reader, n: number): { number }
|
||||
return v
|
||||
end
|
||||
|
||||
-- a count field: i32 >= 0 and at most remaining / minSize records
|
||||
-- a count field: i32 >= 0
|
||||
local function count(r: Bytes.Reader, minSize: number, what: string): (any, ...any)
|
||||
local n = r:i32le()
|
||||
if r.err then
|
||||
@@ -206,7 +201,6 @@ function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...
|
||||
r.pos = p + ni * vsize
|
||||
m.indexCount, m.indices = ni, ind
|
||||
|
||||
-- textures
|
||||
local nt
|
||||
nt, e, k = count(r, 4, "textures")
|
||||
if not nt then
|
||||
@@ -217,7 +211,6 @@ function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...
|
||||
m.textures[i] = text()
|
||||
end
|
||||
|
||||
-- materials
|
||||
local nm
|
||||
nm, e, k = count(r, 8 + 16 + 12 + 4 + 12 + 1 + 16 + 4 + 2 * tsize + 2 + 1 + 4 + 4, "materials")
|
||||
if not nm then
|
||||
@@ -242,7 +235,6 @@ function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...
|
||||
m.materials[i] = mat
|
||||
end
|
||||
|
||||
-- bones
|
||||
local nb
|
||||
nb, e, k = count(r, 8 + 12 + bsize + 4 + 2 + bsize, "bones")
|
||||
if not nb then
|
||||
@@ -290,7 +282,6 @@ function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...
|
||||
m.bones[i] = b
|
||||
end
|
||||
|
||||
-- morphs
|
||||
local nmo
|
||||
nmo, e, k = count(r, 8 + 2 + 4, "morphs")
|
||||
if not nmo then
|
||||
@@ -311,7 +302,7 @@ function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...
|
||||
return nil, e, k
|
||||
end
|
||||
if t == 1 then
|
||||
-- vertex morphs: packed (index list + deltas), they become morph targets
|
||||
-- vertex morphs: packed (index list + deltas)
|
||||
local vi, d = table.create(no), buffer.create(no * 12)
|
||||
for o = 1, no do
|
||||
local x = vidx()
|
||||
|
||||
@@ -1,17 +1,7 @@
|
||||
--!strict
|
||||
-- model/pmx: MikuMikuDance models, PMX 2.0 / 2.1 (PmxEditor's specification notes) and PMD 1.0 (the original MMD
|
||||
-- format, as documented by the MMD community). New code, no third-party code.
|
||||
-- Reads: UTF-16 / UTF-8 text (PMD: Shift-JIS names kept when ASCII, else the English names), vertices with BDEF1 /
|
||||
-- BDEF2 / BDEF4 / SDEF / QDEF weights -> JOINTS_0 / WEIGHTS_0 (normalized; SDEF C / R0 / R1 as _SDEF_C / _SDEF_R0 /
|
||||
-- _SDEF_R1, the deform type as _DEFORM, additional UVs as _UVA1.._UVA4 vec4, edge scale as _EDGE_SCALE), faces (one
|
||||
-- primitive per material), textures (uri, data through opts.files / opts.resolve), materials (diffuse -> baseColor,
|
||||
-- specular power -> roughness, no-cull -> doubleSided; diffuse / specular / ambient, edge, sphere map and mode, toon
|
||||
-- texture or shared toon index, memo in material.extras.pmx), bones (nodes with parent-relative translations, one skin;
|
||||
-- tail, inherit, axes, IK in node.extras.pmx), vertex morphs -> morph targets (POSITION deltas, mesh.extras.targetNames),
|
||||
-- the other morphs (group, bone, UV, material, flip, impulse), display frames, rigid bodies and joints as extras
|
||||
-- (mesh.extras.pmx.morphs, meta.source). MMD's left-handed coordinates become right-handed: z is negated and the
|
||||
-- winding reversed (extras keep the file's values and 0-based indices). meta.up = "y" (one unit is about 8 cm).
|
||||
-- Not supported: writing, PMX 2.1 soft bodies (counted in meta.source.softBodies), VMD motions / VPD poses.
|
||||
-- model/pmx: MikuMikuDance PMX 2.0 / 2.1 (PmxEditor's specification notes) and PMD 1.0 (MMD community notes); no
|
||||
-- third-party code. Supports: every deform type, materials, bones and IK, vertex morphs as morph targets, the other
|
||||
-- morphs, frames, rigid bodies and joints as extras. Not supported: writing, 2.1 soft bodies, VMD / VPD.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -33,11 +23,11 @@ local Pmx = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
files: { [string]: any }?, -- texture files by name (buffer or string; "/" or "\" separators, or the base name)
|
||||
resolve: ((uri: string) -> any)?, -- or: reads a texture file (the api sets it for paths)
|
||||
morphs: boolean?, -- vertex morphs as morph targets (default true)
|
||||
files: { [string]: any }?, -- "/" or "\" separators, or the base name
|
||||
resolve: ((uri: string) -> any)?,
|
||||
morphs: boolean?, -- default true
|
||||
maxVertices: number?, -- default 2^24
|
||||
maxBytes: number?, -- morph target bytes (default 2^28)
|
||||
maxBytes: number?, -- default 2^28
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
|
||||
@@ -1,15 +1,7 @@
|
||||
--!strict
|
||||
-- model/qb: Qubicle Binary (.qb, Qubicle 1.x "Qubicle Binary" exchange format), read and write. New code, from the
|
||||
-- format description in the Qubicle documentation (minddesk.com "Qubicle Binary"): version 1.1.0.0, RGBA or BGRA
|
||||
-- colours, left- or right-handed z axis, uncompressed or run-length compressed matrices (CODEFLAG 2 / NEXTSLICEFLAG 6
|
||||
-- per z slice), the visibility mask encoding in the alpha byte, named matrices with a position.
|
||||
-- decode -> a Scene (meta.up = "y"): one Types.Voxels per matrix with voxels.colors (each cell's exact colour as
|
||||
-- r, g, b, a bytes; a = the visibility mask when the file encodes one, 0 = empty) and data / palette as an indexed view
|
||||
-- (up to 255 colours exact, more mapped to the nearest of the 255 most used); a node per matrix with its name and
|
||||
-- position. Left-handed files are mirrored on z into the scene's right-handed axes (and back on write).
|
||||
-- encode <- a Scene with voxels or one Types.Voxels: voxels.colors when present (exact), else palette colours;
|
||||
-- options default to the source file's settings.
|
||||
-- Not supported: the Qubicle Exchange (.qbt / .qbcl) formats.
|
||||
-- model/qb: Qubicle Binary (.qb 1.1.0.0, minddesk.com "Qubicle Binary"), read + write. Supports: RGBA / BGRA, left- or
|
||||
-- right-handed z, plain or RLE matrices (CODEFLAG 2 / NEXTSLICEFLAG 6 per z slice), the alpha visibility mask, named
|
||||
-- matrices with a position. Not supported: Qubicle Exchange (.qbt / .qbcl).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -28,13 +20,13 @@ local Qb = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxCells: number?, -- refuse files whose matrices hold more cells in total (default 2^27)
|
||||
maxCells: number?, -- default 2^27
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
compressed: boolean?, -- run-length compress the matrices (default: the source's, else true)
|
||||
compressed: boolean?, -- default: the source's, else true
|
||||
colorFormat: ("rgba" | "bgra")?, -- default: the source's, else "rgba"
|
||||
rightHanded: boolean?, -- the z axis orientation (default: the source's, else true)
|
||||
visibilityMask: boolean?, -- encode the visible sides in the alpha byte (default: the source's, else false)
|
||||
rightHanded: boolean?, -- default: the source's, else true
|
||||
visibilityMask: boolean?, -- default: the source's, else false
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
@@ -56,7 +48,6 @@ function Qb.sniff(r: Bytes.Reader): number
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the indexed view of a true-colour grid: exact for up to 255 colours, else the 255 most used and the nearest of them
|
||||
local function indexed(v: Types.Voxels, colors: buffer, n: number)
|
||||
local count: { [number]: number } = {}
|
||||
for i = 0, n - 1 do
|
||||
@@ -337,7 +328,6 @@ function Qb.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
end
|
||||
return cellColor(v, x + sx * (y + sy * z)) >= 0x1000000
|
||||
end
|
||||
-- the value of file cell (x, y, z): colour bytes in the file's order, the alpha a mask when asked
|
||||
local function value(x: number, y: number, z: number): number
|
||||
local zz = if right then z else sz - 1 - z
|
||||
local c = cellColor(v, x + sx * (y + sy * zz))
|
||||
|
||||
@@ -1,15 +1,7 @@
|
||||
--!strict
|
||||
-- model/rbxm: the Roblox binary model / place format (.rbxm / .rbxl, "<roblox!"), read + write, to and from the instance
|
||||
-- tree of codecs/model/Rbx (an RbxTree, kind "rbxtree"; not a Scene: Roblox files hold instances, not meshes).
|
||||
-- Written from the rbx-dom format notes (docs/binary.md); checked against rojo 7.7 and lune 0.11 (rbx-dom) both ways.
|
||||
-- Decode: the header, META (tree.metadata), SSTR (shared strings), INST (classes, referents, service flags), PROP (every
|
||||
-- property type of codecs/model/Rbx/Binary), PRNT (the hierarchy), END; chunk bodies raw, LZ4 or Zstandard. Unknown
|
||||
-- chunks are kept raw in tree.extra and written back; properties of unknown types become "Raw" values that are
|
||||
-- written back verbatim while the class keeps its instances. tree.place is true when the file marks services (rbxl).
|
||||
-- Encode: every instance depth first (referents 0..n-1), classes sorted by name, properties sorted by name, chunks
|
||||
-- LZ4-compressed (opts.compression = "none" writes them raw), SharedStrings deduplicated (MD5 keys). An instance
|
||||
-- without a property its class's other instances have gets the type's default (the format stores one value per
|
||||
-- instance). "XmlRaw" values (unknown XML types) are skipped. Not supported: writing Zstandard chunks.
|
||||
-- model/rbxm: Roblox binary model / place (.rbxm / .rbxl, "<roblox!") to and from a codecs/model/Rbx RbxTree, from the
|
||||
-- rbx-dom notes (docs/binary.md), checked against rojo 7.7 and lune 0.11. Supports: META, SSTR, INST, PROP, PRNT, END;
|
||||
-- raw / LZ4 / Zstandard chunks; unknown chunks and types round-trip raw. Not supported: writing Zstandard chunks.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -32,13 +24,13 @@ local Rbxm = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- the largest decompressed chunk (default 2^28)
|
||||
maxBytes: number?, -- default 2^28
|
||||
maxInstances: number?, -- default 2^22
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
compression: ("lz4" | "none")?, -- chunk bodies (default "lz4"; END is always raw)
|
||||
place: boolean?, -- mark the roots as services (an .rbxl; default tree.place, or format = "rbxl")
|
||||
format: string?, -- "rbxl" writes a place
|
||||
compression: ("lz4" | "none")?, -- default "lz4"; END is always raw
|
||||
place: boolean?, -- default tree.place, or format = "rbxl"
|
||||
format: string?,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
@@ -50,7 +42,7 @@ function Rbxm.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(14) == MAGIC then 1 else 0
|
||||
end
|
||||
|
||||
-- variant(r) -> "rbxl" for a place (an INST chunk marks services), else "rbxm" (F.detect); reads only the INST chunks
|
||||
-- an INST chunk that marks services makes a place
|
||||
function Rbxm.variant(r: Bytes.Reader): string?
|
||||
local b, p, e = r.buf, r.base + 32, r.limit
|
||||
if r:peek(14) ~= MAGIC then
|
||||
@@ -83,7 +75,6 @@ end
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
type Class = { id: number, name: string, refs: { number }, service: boolean }
|
||||
|
||||
-- a length-prefixed string at p of b (limit e): string, next | nil
|
||||
local function str(b: buffer, p: number, e: number): (string?, number)
|
||||
if p + 4 > e then
|
||||
return nil, p
|
||||
@@ -292,7 +283,6 @@ function Rbxm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err
|
||||
return nil, Err.new(Err.CORRUPT, "an instance with two parents", at)
|
||||
end
|
||||
parented[child] = true
|
||||
-- refuse cycles: the parent may not be a descendant of the child
|
||||
local up: Rbx.Instance? = parent
|
||||
while up do
|
||||
if up == child then
|
||||
@@ -311,7 +301,6 @@ function Rbxm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err
|
||||
if not ended then
|
||||
return nil, Err.new(Err.TRUNCATED, "no END chunk", limit)
|
||||
end
|
||||
-- instances PRNT does not mention are roots
|
||||
for _, inst in order do
|
||||
if not parented[inst] then
|
||||
table.insert(tree.roots, inst)
|
||||
@@ -329,7 +318,6 @@ function Rbxm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- the binary type of a property over a class's instances: type id, type name | nil, message
|
||||
local function columnType(insts: { Rbx.Instance }, pname: string): (number?, string?)
|
||||
local id, tname = nil, nil
|
||||
for _, inst in insts do
|
||||
@@ -381,7 +369,6 @@ function Rbxm.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: any = opts or {}
|
||||
local compress = o.compression ~= "none"
|
||||
local place = if o.place ~= nil then o.place == true elseif o.format == "rbxl" then true else tree.place == true
|
||||
-- every instance depth first; referents in that order
|
||||
local insts: { Rbx.Instance } = {}
|
||||
local refOf: { [any]: number } = {}
|
||||
local parentOf: { [Rbx.Instance]: Rbx.Instance? } = {}
|
||||
@@ -409,7 +396,6 @@ function Rbxm.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
return nil, e
|
||||
end
|
||||
end
|
||||
-- classes by name
|
||||
local byClass: { [string]: { Rbx.Instance } } = {}
|
||||
local names = {}
|
||||
for _, inst in insts do
|
||||
@@ -422,7 +408,6 @@ function Rbxm.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
table.insert(list, inst)
|
||||
end
|
||||
table.sort(names)
|
||||
-- shared strings, in order of first use
|
||||
local sharedIdx: { [string]: number } = {}
|
||||
local sharedList: { string } = {}
|
||||
local ctx: Binary.Ctx = {
|
||||
@@ -497,7 +482,7 @@ function Rbxm.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
putStr(pw, pn)
|
||||
local tid = t :: number
|
||||
if tid == -1 then
|
||||
-- Raw: the column read from a file, written back only when this class still has exactly its instances
|
||||
-- Raw: written back only when this class still has exactly its instances
|
||||
local first = list[1].properties[pn]
|
||||
local raw = first and first.value
|
||||
local ok = type(raw) == "table" and raw.count == #list and type(raw.data) == "buffer"
|
||||
|
||||
@@ -1,18 +1,8 @@
|
||||
--!strict
|
||||
-- model/rbxmx: the Roblox XML model / place format (.rbxmx / .rbxlx, `<roblox version="4">`), read + write, to and from
|
||||
-- the instance tree of codecs/model/Rbx (an RbxTree, as model/rbxm: converting between the two is load + save).
|
||||
-- Written from the rbx-dom format notes (docs/xml.md); checked against rojo 7.7 and lune 0.11 (rbx-dom) both ways.
|
||||
-- Decode: <Meta>, <Item class referent> with <Properties> of every type codecs/model/Rbx lists (string, BinaryString
|
||||
-- (base64), ProtectedString, Content (url / uri / null), ContentId, bool, int, int64, float, double (INF / NAN),
|
||||
-- token, BrickColor (as rbx-dom: an <int>; read back as BrickColor for the BrickColor properties of a short
|
||||
-- built-in list), Color3 (components or packed ARGB), Color3uint8, Vector2 / 3 (int16), CoordinateFrame,
|
||||
-- OptionalCoordinateFrame, UDim / UDim2, Rect2D, Ray, Faces, Axes, NumberSequence, ColorSequence, NumberRange,
|
||||
-- PhysicalProperties, Ref, SharedString (+ <SharedStrings>), UniqueId, Font, SecurityCapabilities); unknown property
|
||||
-- tags are kept as "XmlRaw" values and written back as they are; unknown top-level elements go to tree.extra.
|
||||
-- tree.place is true when a root is a Workspace (rbxlx).
|
||||
-- Encode: rbx-dom's layout (version 4, referents "RBX" + 32 hex digits, properties sorted by name, two-space indent,
|
||||
-- floats as the shortest text that reads back to the same f32 / f64). A String holding bytes XML cannot carry (control
|
||||
-- characters, invalid UTF-8) is written as a BinaryString. "Raw" values (unknown binary types) are skipped.
|
||||
-- model/rbxmx: Roblox XML model / place (.rbxmx / .rbxlx, `<roblox version="4">`) to and from a codecs/model/Rbx
|
||||
-- RbxTree, from the rbx-dom notes (docs/xml.md), checked against rojo 7.7 and lune 0.11. Supports: every type
|
||||
-- codecs/model/Rbx lists; unknown tags round-trip as "XmlRaw". Encode follows rbx-dom's layout.
|
||||
-- Not supported: writing "Raw" values.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -34,17 +24,16 @@ local Rbxmx = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxDepth: number?, -- XML nesting limit (default 10000)
|
||||
maxDepth: number?, -- default 10000
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
indent: (number | string)?, -- default 2 spaces; 0 for none
|
||||
indent: (number | string)?, -- default 2; 0 for none
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local XmlNode = Xml.element
|
||||
local find, format, match, gmatch = string.find, string.format, string.match, string.gmatch
|
||||
|
||||
-- tag name -> type name for the simple (text) types
|
||||
local SCALAR_TAGS: { [string]: string } = {
|
||||
string = "String",
|
||||
ProtectedString = "ProtectedString",
|
||||
@@ -81,7 +70,7 @@ function Rbxmx.sniff(r: Bytes.Reader): number
|
||||
return 0
|
||||
end
|
||||
|
||||
-- variant(r) -> "rbxlx" for a place (a Workspace item), else "rbxmx" (F.detect)
|
||||
-- a Workspace item makes a place
|
||||
function Rbxmx.variant(r: Bytes.Reader): string?
|
||||
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
|
||||
return if find(text, '<Item class="Workspace"', 1, true) then "rbxlx" else "rbxmx"
|
||||
@@ -128,8 +117,6 @@ end
|
||||
local CF_NAMES = { "X", "Y", "Z", "R00", "R01", "R02", "R10", "R11", "R12", "R20", "R21", "R22" }
|
||||
local PHYS_NAMES = { "Density", "Friction", "Elasticity", "FrictionWeight", "ElasticityWeight" }
|
||||
|
||||
-- a property element -> type name, value | nil (unknown: XmlRaw). refs: referent -> instance (filled later: Refs
|
||||
-- come back as { pending = referent })
|
||||
local function readRaw(node: Xml.Node, shared: { [string]: string }, key: string): (string, any)
|
||||
local tag = node.name
|
||||
local scalar = SCALAR_TAGS[tag]
|
||||
@@ -298,7 +285,6 @@ function Rbxmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Er
|
||||
end
|
||||
local tree = Rbx.tree()
|
||||
tree.meta.source = { format = "rbxmx", version = root.attrs.version }
|
||||
-- shared strings first (properties name them by key)
|
||||
local shared: { [string]: string } = {}
|
||||
for _, ss in Xml.children(root, "SharedStrings") do
|
||||
for _, s in Xml.children(ss, "SharedString") do
|
||||
@@ -310,7 +296,7 @@ function Rbxmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Er
|
||||
end
|
||||
end
|
||||
local byRef: { [string]: Rbx.Instance } = {}
|
||||
local pending: { { any } } = {} -- { value table, field, referent }
|
||||
local pending: { { any } } = {}
|
||||
local function item(node: Xml.Node, parent: any): Err.Err?
|
||||
local cls = node.attrs.class
|
||||
if type(cls) ~= "string" then
|
||||
@@ -381,7 +367,6 @@ function Rbxmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Er
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- the shortest text that reads back as the same float (single: f32 values; else f64)
|
||||
local function fmt(v: any, single: boolean?): string
|
||||
if type(v) ~= "number" then
|
||||
v = 0
|
||||
@@ -435,7 +420,6 @@ local function xmlSafe(s: string): boolean
|
||||
return utf8.len(s) ~= nil
|
||||
end
|
||||
|
||||
-- a property -> its element, or nil to skip
|
||||
local function writeValue(name: string, v: any, refOf: (any) -> string, sharedKey: (string) -> string): Xml.Node?
|
||||
local t, x = v.type, v.value
|
||||
local a = { name = name }
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- model/robloxmesh/Parse: Roblox FileMesh bytes to a flat record (the file's arrays as packed buffers), for every version:
|
||||
-- 1.00 / 1.01 (ASCII), 2.00, 3.00 / 3.01 (LOD offsets), 4.00 / 4.01 (bones, skinning, subsets), 5.00 (+ FACS) and the
|
||||
-- chunked 6.00 / 7.00 (COREMESH v1, LODS, SKINNING, FACS, HSRAVIS; a Draco COREMESH v2 through the lim.core
|
||||
-- callback). Written from MaximumADHD's "Roblox Mesh Format" notes (devforum 326114). Little endian. Returns nil, message on bad data.
|
||||
-- model/robloxmesh/Parse: FileMesh bytes to a flat record, little endian, 1.00 - 7.00 (MaximumADHD's "Roblox Mesh
|
||||
-- Format", devforum 326114); a Draco COREMESH v2 goes through the lim.core callback. Never throws.
|
||||
local Parse = {}
|
||||
|
||||
local readu8, readu16, readu32, readf32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.readstring
|
||||
@@ -34,8 +32,6 @@ export type Record = {
|
||||
coreVersion: number?, -- 6.00+: 2 when the COREMESH was Draco-compressed
|
||||
}
|
||||
|
||||
-- core: decodes a Draco-compressed COREMESH (v2) body at (b, off, len) into the vertex / face fields of a Record
|
||||
-- (numVerts, pos, nrm, uv, tan?, col?, numFaces, faces); the format's init passes it (codecs/model/Draco)
|
||||
export type Core = { numVerts: number, pos: buffer, nrm: buffer, uv: buffer, tan: buffer?, col: buffer?, numFaces: number, faces: buffer }
|
||||
export type Limits = { maxVertices: number, maxFaces: number, core: ((b: buffer, off: number, len: number) -> (Core?, string?))? }
|
||||
|
||||
@@ -116,7 +112,7 @@ local function ascii(text: string, version: string, lim: Limits): (Record?, stri
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ binary parts
|
||||
-- vertices of size vs (36 / 40) at p
|
||||
-- vertices of 36 / 40 bytes
|
||||
local function vertices(b: buffer, p: number, n: number, vs: number, r: Record)
|
||||
local pos, nrm, uv, tan = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4)
|
||||
local col = if vs >= 40 then buffer.create(n * 4) else nil
|
||||
@@ -423,7 +419,6 @@ local function chunked(b: buffer, p: number, e: number, version: string, lim: Li
|
||||
return r, nil
|
||||
end
|
||||
|
||||
-- parse(b, p, e, lim) -> Record | nil, message
|
||||
function Parse.parse(b: buffer, p: number, e: number, lim: Limits): (Record?, string?)
|
||||
if e - p < 13 then
|
||||
return nil, "truncated: no version line"
|
||||
@@ -448,7 +443,7 @@ function Parse.parse(b: buffer, p: number, e: number, lim: Limits): (Record?, st
|
||||
return nil, "unsupported: version " .. version
|
||||
end
|
||||
|
||||
-- tangent(tan, i) -> x, y, z, w of vertex i's packed tangent (signed bytes / 127)
|
||||
-- packed tangent: signed bytes / 127
|
||||
local function snorm(v: number): number
|
||||
local x = if v >= 128 then v - 256 else v
|
||||
return math.clamp(x / 127, -1, 1)
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- model/robloxmesh/Write: a flat record (model/robloxmesh/Parse's shape) to a version 2.00 or 4.00 FileMesh. 2.00:
|
||||
-- header, 36- or 40-byte vertices (40 when col is set), faces. 4.00: the 24-byte header, 40-byte vertices, skinning
|
||||
-- (when there are bones), faces, LOD offsets, bones, the bone name table, subsets. Never throws.
|
||||
-- model/robloxmesh/Write: a flat record to FileMesh 2.00 (header, 36- or 40-byte vertices, faces) or 4.00 (24-byte
|
||||
-- header, 40-byte vertices, skinning, faces, LOD offsets, bones, bone names, subsets). Never throws.
|
||||
local Parse = require("@rosetta/model/robloxmesh/Parse")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
|
||||
@@ -30,7 +29,6 @@ local function vertex(w: Bytes.Writer, r: Parse.Record, i: number, colors: boole
|
||||
w.pos = p + (if colors then 40 else 36)
|
||||
end
|
||||
|
||||
-- write(r, version) -> buffer ("2.00" | "4.00")
|
||||
function Write.write(r: Parse.Record, version: string): buffer
|
||||
local nv, nf = r.numVerts, r.numFaces
|
||||
local w = Bytes.writer(64 + nv * 48 + nf * 12)
|
||||
|
||||
@@ -1,22 +1,7 @@
|
||||
--!strict
|
||||
-- model/robloxmesh: the Roblox FileMesh (.mesh), read + write, mapped to a Scene. Written from MaximumADHD's "Roblox Mesh
|
||||
-- Format" notes (devforum.roblox.com/t/roblox-mesh-format/326114); no port.
|
||||
-- Decode: 1.00 / 1.01 (ASCII; 1.00 positions halved, V flipped), 2.00, 3.00 / 3.01 (LOD offsets), 4.00 / 4.01 (bones,
|
||||
-- skinning, subsets), 5.00 (+ FACS), 6.00 / 7.00 chunked (COREMESH v1, LODS, SKINNING, FACS; HSRAVIS and unknown
|
||||
-- chunks kept raw in meta.source.chunks). A Draco-compressed COREMESH (v2: a u32 size, then the Draco stream) decodes
|
||||
-- through codecs/model/Draco: its POSITION / NORMAL / TEX_COORD / COLOR attributes and a 4-component TANGENT or GENERIC
|
||||
-- one as the tangents (meta.source.draco = true). One mesh, one triangle primitive (LOD 0): POSITION, NORMAL, TEXCOORD_0 (f32), TANGENT (f32 x4 from the signed
|
||||
-- bytes), COLOR_0 (unorm8 x4, when the vertices carry colours), u32 indices; the other LODs as primitives in
|
||||
-- mesh.extras.lods (same attributes, their own indices). Bones become joint nodes (local matrices from the files'
|
||||
-- world-space CFrames; extras.culling / lodParent) under one skin with inverse bind matrices; skinning becomes
|
||||
-- JOINTS_0 (u16, global joint indices through the subsets) and WEIGHTS_0 (unorm8). FACS data is kept raw
|
||||
-- (meta.source.facs). meta.up = "y"; units are studs.
|
||||
-- Encode: version 2.00 (default; 40-byte vertices when a COLOR_0 is not all white) or 4.00 (opts.version), from every
|
||||
-- primitive of the scene in world space (codecs/model/MeshFlatten; polygons / strips fan-triangulated). 4.00 writes
|
||||
-- the scene's first skin as bones + skinning (subsets of at most 26 bones, vertices duplicated across subsets, up to
|
||||
-- 4 influences, weights to bytes summing to 255) and LOD offsets (mesh.extras.lods of a single unskinned primitive).
|
||||
-- Missing normals are computed (area weighted), missing tangents written as (0, 0, -1, 1). Not supported: writing
|
||||
-- 3.00 / 5.00+ / FACS.
|
||||
-- model/robloxmesh: Roblox FileMesh (.mesh), from MaximumADHD's "Roblox Mesh Format" (devforum.roblox.com/t/326114); no
|
||||
-- port. Supports: reading 1.00 - 7.00 (Draco COREMESH v2 through codecs/model/Draco), writing 2.00 and 4.00. Not
|
||||
-- supported: writing 3.00 / 5.00+ / FACS; FACS and HSRAVIS are kept raw.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -69,7 +54,6 @@ local function indices(r: Parse.Record, from: number, to: number): Types.Accesso
|
||||
return accessor(d, "u32", 1, n * 3)
|
||||
end
|
||||
|
||||
-- a Draco-compressed COREMESH body -> the record's vertex / face fields
|
||||
local function dracoCore(b: buffer, off: number, len: number): (Parse.Core?, string?)
|
||||
-- the stream follows a u32 byte count (accepted without it too)
|
||||
if len >= 4 and buffer.readu32(b, off) <= len - 4 and buffer.readu32(b, off) >= 5 and buffer.readstring(b, off + 4, 5) == "DRACO" then
|
||||
@@ -95,7 +79,6 @@ local function dracoCore(b: buffer, off: number, len: number): (Parse.Core?, str
|
||||
if not pos or pos.components < 3 then
|
||||
return nil, "corrupt: Draco COREMESH without positions"
|
||||
end
|
||||
-- an attribute's values as numbers (normalized integers as -1..1 / 0..1)
|
||||
local function getter(a: Draco.Attribute): (number, number) -> number
|
||||
local t = if a.normalized then (({ u8 = "unorm8", i8 = "snorm8", u16 = "unorm16", i16 = "snorm16" }) :: any)[a.type] or a.type else a.type
|
||||
local rd = Types.Scene.reader({ data = a.data, type = t, components = a.components, count = n })
|
||||
@@ -163,7 +146,7 @@ local function dracoCore(b: buffer, off: number, len: number): (Parse.Core?, str
|
||||
}, nil
|
||||
end
|
||||
|
||||
-- Parse is native: nothing may throw through it, so the callback never does
|
||||
-- Parse is native: nothing may throw through it
|
||||
local function safeCore(b: buffer, off: number, len: number): (Parse.Core?, string?)
|
||||
local ok, c, err = pcall(dracoCore, b, off, len)
|
||||
if not ok then
|
||||
@@ -199,7 +182,6 @@ function RobloxMesh.decode(rd: Bytes.Reader, opts: DecodeOptions?): (Types.Scene
|
||||
if r.col then
|
||||
attrs.COLOR_0 = accessor(r.col, "unorm8", 4, nv)
|
||||
end
|
||||
-- LOD ranges (offsets clamped to the faces)
|
||||
local offs = {}
|
||||
for _, o in r.lods do
|
||||
table.insert(offs, math.clamp(o, 0, nf))
|
||||
@@ -220,7 +202,6 @@ function RobloxMesh.decode(rd: Bytes.Reader, opts: DecodeOptions?): (Types.Scene
|
||||
scene.meshes[1] = mesh
|
||||
scene.nodes[1] = { name = "Mesh", children = {}, mesh = 1 }
|
||||
scene.roots[1] = 1
|
||||
-- bones and skinning
|
||||
local nb = #r.bones
|
||||
if nb > 0 then
|
||||
local world: { { number } } = table.create(nb) :: any
|
||||
@@ -306,7 +287,6 @@ local function num(attr: any, i: number, c: number, default: number): number
|
||||
return attr.values[i * attr.components + c + 1]
|
||||
end
|
||||
|
||||
-- area-weighted vertex normals
|
||||
local function normals(pos: buffer, nv: number, corners: { number }): buffer
|
||||
local acc = table.create(nv * 3, 0)
|
||||
for f = 0, #corners // 3 - 1 do
|
||||
@@ -336,7 +316,6 @@ local function normals(pos: buffer, nv: number, corners: { number }): buffer
|
||||
return out
|
||||
end
|
||||
|
||||
-- world matrices of every node (parents through children lists)
|
||||
local function worlds(scene: any): { [number]: { number } }
|
||||
local out: { [number]: { number } } = {}
|
||||
local parent: { [number]: number } = {}
|
||||
@@ -363,7 +342,6 @@ local function worlds(scene: any): { [number]: { number } }
|
||||
return out
|
||||
end
|
||||
|
||||
-- the bones of a skin: Parse.Bone list, or nil, message
|
||||
local function skinBones(scene: any, skin: any): ({ Parse.Bone }?, string?)
|
||||
local joints = skin.joints
|
||||
if type(joints) ~= "table" or #joints == 0 then
|
||||
@@ -410,7 +388,6 @@ local function skinBones(scene: any, skin: any): ({ Parse.Bone }?, string?)
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- the vertex arrays of the record from merged attributes, for the vertices `order` (new index -> merged index)
|
||||
local function fill(r: Parse.Record, m: any, order: { number }, nrm: buffer?)
|
||||
local nv = #order
|
||||
local pos, nb, uv, tan = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 4)
|
||||
@@ -502,7 +479,6 @@ function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?,
|
||||
if src and type(src.lodType) == "number" then
|
||||
r.lodType, r.highQualityLods = src.lodType, if type(src.highQualityLods) == "number" then src.highQualityLods else 0
|
||||
end
|
||||
-- normals when the scene has none
|
||||
local nrm: buffer? = nil
|
||||
if not m.attrs.NORMAL then
|
||||
local pb = buffer.create(nv0 * 12)
|
||||
@@ -513,7 +489,6 @@ function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?,
|
||||
end
|
||||
nrm = normals(pb, nv0, corners)
|
||||
end
|
||||
-- the skin (4.00): the first node with a mesh and a skin
|
||||
local skin = nil
|
||||
if version == "4.00" and m.attrs.JOINTS_0 and m.attrs.WEIGHTS_0 then
|
||||
for _, n in scene.nodes or {} do
|
||||
@@ -533,7 +508,6 @@ function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?,
|
||||
local J, W = m.attrs.JOINTS_0, m.attrs.WEIGHTS_0
|
||||
local wscale = if W.raw then 1 / 255 else 1
|
||||
local nb = #bones
|
||||
-- per vertex: up to 4 (joint, weight) pairs with weight > 0
|
||||
local influences: { { { number } } } = table.create(nv0) :: any
|
||||
for v = 0, nv0 - 1 do
|
||||
local list = {}
|
||||
@@ -546,7 +520,7 @@ function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?,
|
||||
end
|
||||
influences[v + 1] = list
|
||||
end
|
||||
-- subsets: faces in order, a new subset when a face's joints do not fit in 26
|
||||
-- subsets: a new subset when a face's joints do not fit in 26
|
||||
local faceIdx = buffer.create(nf * 12)
|
||||
local order: { number } = {}
|
||||
local s: any = nil
|
||||
@@ -646,7 +620,6 @@ function RobloxMesh.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?,
|
||||
end
|
||||
r.faces = faces
|
||||
r.lods = { 0, nf }
|
||||
-- extra LODs of a single untransformed primitive
|
||||
local part = m.parts[1]
|
||||
local mesh = part and part.mesh
|
||||
local lods = if #m.parts == 1 and part.identity and mesh and type(mesh.extras) == "table" then mesh.extras.lods else nil
|
||||
|
||||
@@ -1,28 +1,25 @@
|
||||
--!strict
|
||||
-- model/schematic/Common: what the three schematic flavours share: the region record they read into and write from,
|
||||
-- NBT field access with type checks, and block entities in one shape ({ pos = { x, y, z }, id, data }: Sponge v3's,
|
||||
-- converted from / to MCEdit's and Litematica's flat { x, y, z, id, ... } and Sponge v2's { Pos, Id, ... }).
|
||||
-- model/schematic/Common: shared region record, NBT access and block entities as Sponge v3's { pos = { x, y, z }, id,
|
||||
-- data } (MCEdit / Litematica use flat { x, y, z, id, ... }, Sponge v2 { Pos, Id, ... }).
|
||||
local Types = require("@rosetta/Types")
|
||||
local Nbt = require("@rosetta/codecs/text/Nbt")
|
||||
local Mc = require("@rosetta/codecs/model/Minecraft")
|
||||
|
||||
local Common = {}
|
||||
|
||||
-- a block region: indices are u16 per cell in Types.Voxels order (x fastest, then y, then z) into states
|
||||
-- a block region: u16 indices per cell in Types.Voxels order (x fastest, then y, then z) into states
|
||||
export type Region = {
|
||||
name: string?,
|
||||
size: { number }, -- x, y, z cells
|
||||
position: { number }, -- the minimum corner relative to the schematic origin
|
||||
size: { number },
|
||||
position: { number }, -- relative to the schematic origin
|
||||
states: { string },
|
||||
indices: buffer,
|
||||
blockEntities: { any },
|
||||
entities: { any },
|
||||
}
|
||||
|
||||
-- int(v) -> the integer value of an NBT number (byte / short / int / long tag or plain number) | nil
|
||||
Common.int = Mc.int
|
||||
|
||||
-- dims(a, b, c, max) -> sx, sy, sz | nil, message: positive sizes whose product stays under max cells
|
||||
function Common.dims(a: any, b: any, c: any, max: number): (number?, any, number?)
|
||||
local x, y, z = Common.int(a), Common.int(b), Common.int(c)
|
||||
if not x or not y or not z then
|
||||
@@ -37,14 +34,11 @@ function Common.dims(a: any, b: any, c: any, max: number): (number?, any, number
|
||||
return x, y, z
|
||||
end
|
||||
|
||||
-- ints(v) -> the numbers of an intArray tag or a list of numbers | nil
|
||||
Common.ints = Mc.ints
|
||||
|
||||
-- blockEntity(c, style) / flatBlockEntity(be, style): codecs/model/Minecraft's (shared with model/mca)
|
||||
Common.blockEntity = Mc.blockEntity
|
||||
Common.flatBlockEntity = Mc.flatBlockEntity
|
||||
|
||||
-- list(v) -> v when it is an NBT list (array), else an empty list
|
||||
function Common.list(v: any): { any }
|
||||
if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then
|
||||
return v
|
||||
@@ -52,7 +46,6 @@ function Common.list(v: any): { any }
|
||||
return {}
|
||||
end
|
||||
|
||||
-- compound({ { key, value } }) -> a Types.object with these keys in this order (nil values skipped)
|
||||
function Common.compound(fields: { { any } }): { [string]: any }
|
||||
local o, keys = {}, {}
|
||||
for _, kv in fields do
|
||||
@@ -64,8 +57,6 @@ function Common.compound(fields: { { any } }): { [string]: any }
|
||||
return Types.object(o, keys)
|
||||
end
|
||||
|
||||
-- merge(base, fields, drop?) -> a compound of fields ({ { key, value } }, nil values left out) laid out in base's key
|
||||
-- order (a decoded source compound: its other keys are kept, except those in drop), new keys after
|
||||
function Common.merge(base: any, fields: { { any } }, drop: { [string]: boolean }?): { [string]: any }
|
||||
if type(base) ~= "table" or not Types.isObject(base) then
|
||||
return Common.compound(fields)
|
||||
@@ -98,7 +89,6 @@ function Common.merge(base: any, fields: { { any } }, drop: { [string]: boolean
|
||||
return Common.compound(out)
|
||||
end
|
||||
|
||||
-- dedupe(states, indices, n) -> states, indices with every state once (indices remapped when needed)
|
||||
function Common.dedupe(states: { string }, indices: buffer, n: number): ({ string }, buffer)
|
||||
local first: { [string]: number } = {}
|
||||
local remap: { number } = {}
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
--!strict
|
||||
-- model/schematic/Litematic: Litematica's .litematic, from the mod's sources (LitematicaSchematic,
|
||||
-- LitematicaBitArray) as documented by the litemapy project: Metadata (name, author, description, enclosing size,
|
||||
-- counts, times, preview), several named Regions with a Position and a Size that may be negative, a block-state
|
||||
-- palette (index 0 = air) and BlockStates packed spanning long boundaries (at least 2 bits), TileEntities (relative
|
||||
-- to the region's minimum corner), Entities and pending ticks (kept as they are).
|
||||
-- model/schematic/Litematic: .litematic, from LitematicaSchematic / LitematicaBitArray as documented by litemapy:
|
||||
-- Metadata, named Regions (Position, Size may be negative), palette (0 = air), BlockStates spanning longs (>= 2 bits),
|
||||
-- TileEntities relative to the region's minimum corner, Entities and pending ticks.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Nbt = require("@rosetta/codecs/text/Nbt")
|
||||
local Mc = require("@rosetta/codecs/model/Minecraft")
|
||||
@@ -28,7 +26,6 @@ local function vec(v: { number }): any
|
||||
return Common.compound({ { "x", v[1] }, { "y", v[2] }, { "z", v[3] } })
|
||||
end
|
||||
|
||||
-- read(root, maxCells) -> { Region }, extra | nil, message
|
||||
function Litematic.read(root: any, maxCells: number): ({ Common.Region }?, any)
|
||||
if not Types.isObject(root.Regions) then
|
||||
return nil, "no Regions"
|
||||
@@ -106,8 +103,6 @@ function Litematic.read(root: any, maxCells: number): ({ Common.Region }?, any)
|
||||
}
|
||||
end
|
||||
|
||||
-- write(regions, version, dataVersion, base?, name?) -> the root compound | nil, message. base: the decoded root
|
||||
-- (Metadata fields and each region's Position / Size signs and pending ticks are kept)
|
||||
function Litematic.write(regions: { Common.Region }, version: number, dataVersion: number, base: any, title: string?): (any, string?)
|
||||
local baseRegions = if type(base) == "table" and Types.isObject(base.Regions) then base.Regions else nil
|
||||
local regs, order = {}, {}
|
||||
@@ -163,7 +158,6 @@ function Litematic.write(regions: { Common.Region }, version: number, dataVersio
|
||||
local b = if baseRegions then baseRegions[name] else nil
|
||||
local bsize = if type(b) == "table" then xyz(b.Size) else nil
|
||||
if bsize and math.abs(bsize[1]) == sx and math.abs(bsize[2]) == sy and math.abs(bsize[3]) == sz then
|
||||
-- keep the source's corner and signs
|
||||
for k = 1, 3 do
|
||||
if bsize[k] < 0 then
|
||||
size[k] = bsize[k]
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
--!strict
|
||||
-- model/schematic/Mcedit: the MCEdit / WorldEdit .schematic layout (Minecraft before 1.13), from the Minecraft wiki
|
||||
-- "Schematic file format" page: Width / Height / Length, Blocks + Data (+ WorldEdit's AddBlocks high nibbles, high
|
||||
-- nibble first), Materials = "Alpha", TileEntities, Entities, WEOffset*, and the SchematicaMapping / BlockIDs name
|
||||
-- tables of Schematica and MCEdit-Unified. Block ids become state strings through codecs/model/Minecraft
|
||||
-- (legacyState: wool 14 -> minecraft:red_wool) and back (legacyId; blocks unknown before 1.13 become the legacy block
|
||||
-- nearest in colour).
|
||||
-- model/schematic/Mcedit: MCEdit / WorldEdit .schematic (pre-1.13; Minecraft wiki "Schematic file format"): Width /
|
||||
-- Height / Length, Blocks + Data (+ AddBlocks high nibbles, high nibble first), Materials = "Alpha", TileEntities,
|
||||
-- Entities, WEOffset*, and the SchematicaMapping / BlockIDs name tables of Schematica and MCEdit-Unified.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Nbt = require("@rosetta/codecs/text/Nbt")
|
||||
local Mc = require("@rosetta/codecs/model/Minecraft")
|
||||
@@ -14,7 +11,6 @@ local Mcedit = {}
|
||||
|
||||
local Packed = Mc.Packed
|
||||
|
||||
-- read(root, maxCells) -> { Region }, extra | nil, message
|
||||
function Mcedit.read(root: any, maxCells: number): ({ Common.Region }?, any)
|
||||
local blocks = root.Blocks
|
||||
if type(blocks) ~= "buffer" then
|
||||
@@ -152,15 +148,12 @@ local function nearest(state: string): (number, number)
|
||||
return bid, bd
|
||||
end
|
||||
|
||||
-- write(region, base?) -> the root compound (named "Schematic") | nil, message. base: a decoded root whose other
|
||||
-- fields are kept
|
||||
function Mcedit.write(r: Common.Region, base: any): (any, string?)
|
||||
local sx, sy, sz = r.size[1], r.size[2], r.size[3]
|
||||
if sx > 65535 or sy > 65535 or sz > 65535 then
|
||||
return nil, "a .schematic is at most 65535 cells on each axis"
|
||||
end
|
||||
local n = sx * sy * sz
|
||||
-- the source's name tables (Schematica / MCEdit-Unified) give the ids for the names they list
|
||||
local map: { [string]: number } = {}
|
||||
if type(base) == "table" then
|
||||
if Types.isObject(base.SchematicaMapping) then
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
--!strict
|
||||
-- model/schematic/Sponge: the Sponge schematic format (.schem: WorldEdit 7+, FAWE, Amulet), from the
|
||||
-- SpongePowered/Schematic-Specification documents for versions 1, 2 and 3: Width / Height / Length, Offset, the
|
||||
-- block-state Palette with varint BlockData (v1 / v2) or the Blocks container (v3), block entities (TileEntities /
|
||||
-- BlockEntities, v3 with Data), Entities, Metadata, DataVersion; biomes are kept as they are.
|
||||
-- model/schematic/Sponge: .schem (WorldEdit 7+, FAWE, Amulet), from SpongePowered/Schematic-Specification v1-3: Width /
|
||||
-- Height / Length, Offset, Palette with varint BlockData (v1 / v2) or the Blocks container (v3), block entities
|
||||
-- (TileEntities / BlockEntities, v3 with Data), Entities, Metadata, DataVersion; biomes are kept as they are.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Nbt = require("@rosetta/codecs/text/Nbt")
|
||||
local Mc = require("@rosetta/codecs/model/Minecraft")
|
||||
@@ -12,7 +11,6 @@ local Sponge = {}
|
||||
|
||||
local Packed = Mc.Packed
|
||||
|
||||
-- read(s, maxCells) -> { Region }, extra | nil, message. s: the Schematic compound (v3: the root's Schematic child)
|
||||
function Sponge.read(s: any, maxCells: number): ({ Common.Region }?, any)
|
||||
local version = Common.int(s.Version) or 1
|
||||
local function u16(v: any): any
|
||||
@@ -81,8 +79,6 @@ function Sponge.read(s: any, maxCells: number): ({ Common.Region }?, any)
|
||||
return regions, { version = version, dataVersion = Common.int(s.DataVersion), metadata = s.Metadata }
|
||||
end
|
||||
|
||||
-- write(region, version, dataVersion, base?) -> the Schematic compound (v3: the caller wraps it in the root) | nil,
|
||||
-- message. base: the decoded Schematic compound whose other fields (Metadata, Biomes, ...) are kept
|
||||
function Sponge.write(r: Common.Region, version: number, dataVersion: number, base: any): (any, string?)
|
||||
local sx, sy, sz = r.size[1], r.size[2], r.size[3]
|
||||
if sx > 65535 or sy > 65535 or sz > 65535 then
|
||||
|
||||
@@ -1,19 +1,7 @@
|
||||
--!strict
|
||||
-- model/schematic: Minecraft schematics: MCEdit / WorldEdit .schematic (before 1.13), Sponge .schem (versions 1, 2, 3:
|
||||
-- WorldEdit 7+) and Litematica .litematic, read and write. New code over codecs/text/Nbt (gzip NBT) and
|
||||
-- codecs/model/Minecraft (block states, colours, legacy ids, packed arrays); the layouts: model/schematic/Mcedit,
|
||||
-- Sponge, Litematic.
|
||||
-- decode -> a Scene (meta.up = "y", one unit = one block): scene.voxels holds one Types.Voxels per region (a .litematic
|
||||
-- has several), each with voxels.blocks (the exact block states, u16 per cell, plus block entities and entities as
|
||||
-- NBT) and data / palette coloured from the default block colour table; a node per region places it (translation =
|
||||
-- the region's minimum corner: Sponge Offset, WorldEdit WEOffset, Litematica Position). meta.source keeps the
|
||||
-- variant, version, DataVersion, Metadata and the whole root NBT (source.nbt).
|
||||
-- encode <- a Scene with voxels or one Types.Voxels: opts.variant (or the file name's extension, or the source's)
|
||||
-- "schem" (default, version 3) / "schematic" / "litematic". Grids without blocks (a .vox) get, per palette colour,
|
||||
-- the block nearest in colour. Several regions are merged into one grid for .schem / .schematic. Fields of the
|
||||
-- source that are not blocks (Metadata, biomes, pending ticks, ...) are written back when the variant is the same.
|
||||
-- Not supported: converting block properties to pre-1.13 data values (legacy writes keep the data a state came with
|
||||
-- or 0), Sponge biome conversion between versions, rotated nodes (only translations place a grid).
|
||||
-- model/schematic: Minecraft schematics, read + write: MCEdit / WorldEdit .schematic (pre-1.13), Sponge .schem v1-3
|
||||
-- (WorldEdit 7+) and Litematica .litematic. Not supported: block properties to pre-1.13 data values, Sponge biome
|
||||
-- conversion between versions, rotated nodes.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -38,18 +26,18 @@ local Schematic = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxCells: number?, -- refuse schematics with more cells in total (default 2^26)
|
||||
maxBytes: number?, -- refuse NBT that inflates past this (default 2^28)
|
||||
maxCells: number?, -- default 2^26
|
||||
maxBytes: number?, -- default 2^28
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
variant: ("schem" | "schematic" | "litematic")?, -- default: the extension of opts.name, the source's, else "schem"
|
||||
version: number?, -- Sponge 1 / 2 / 3 (default 3, or the source's), Litematica version (default 6, or the source's)
|
||||
dataVersion: number?, -- Minecraft's DataVersion (default the source's, else 3953 = 1.21)
|
||||
name: string?, -- the file name (its extension picks the variant); for .litematic also the default Metadata.Name
|
||||
title: string?, -- .litematic Metadata.Name
|
||||
version: number?, -- Sponge default 3, Litematica default 6 (or the source's)
|
||||
dataVersion: number?, -- default the source's, else 3953 = 1.21
|
||||
name: string?,
|
||||
title: string?,
|
||||
compression: ("gzip" | "zlib" | "none")?, -- default gzip, as every tool writes them
|
||||
level: number?, -- deflate level
|
||||
format: string?, -- set by the api: the format key the encoder was picked by ("schem", "litematic", ...)
|
||||
level: number?,
|
||||
format: string?,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
@@ -79,7 +67,6 @@ function Schematic.sniff(r: Bytes.Reader): number
|
||||
return if hinted(head, LITEMATIC_HINTS) or hinted(head, SPONGE_HINTS) then 1 else 0
|
||||
end
|
||||
|
||||
-- variant(r) -> "schem" | "litematic" | "schematic" | nil: the flavour, for F.detect (from the first inflated bytes)
|
||||
function Schematic.variant(r: Bytes.Reader): string?
|
||||
local p = Nbt.peek(r.buf, r.base, r.limit - r.base)
|
||||
if not p then
|
||||
@@ -98,7 +85,6 @@ function Schematic.variant(r: Bytes.Reader): string?
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- variantOf(root, name) -> "schem" | "schematic" | "litematic", the compound holding the Sponge fields | nil
|
||||
local function variantOf(root: any): (string?, any)
|
||||
if type(root) ~= "table" or not Types.isObject(root) then
|
||||
return nil, nil
|
||||
@@ -233,7 +219,6 @@ local function regionsOf(value: any): ({ Common.Region }?, string?)
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- merge(regions) -> one region covering them all (air where none is)
|
||||
local function merge(regions: { Common.Region }): Common.Region
|
||||
if #regions == 1 then
|
||||
return regions[1]
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
--!strict
|
||||
-- model/smd/Read: Valve SMD text (GoldSrc / Source studiomdl input: version 1) to a Scene. Sections "nodes" (id,
|
||||
-- "name", parent), "skeleton" ("time n" blocks of "bone px py pz rx ry rz", Euler radians, R = Rz Ry Rx; a bone
|
||||
-- missing from a later frame keeps its previous pose), "triangles" (a material line, then three vertex lines "bone px
|
||||
-- py pz nx ny nz u v [links (bone weight)...]": model-space positions, v up), "vertexanimation" (skipped, counted).
|
||||
-- Bones -> joint nodes and a Skin (bind pose = the first skeleton frame), triangles -> one primitive per material
|
||||
-- (welded vertices, counter-clockwise as stored, TEXCOORD_0 v flipped to top-left, JOINTS_0 / WEIGHTS_0: the links,
|
||||
-- the rest of the weight to the parent bone; GoldSrc lines without links: the parent bone), skeleton frames beyond
|
||||
-- the first -> one animation (opts.fps, default 30). An animation SMD (no triangles) is a skeleton + its animation.
|
||||
-- model/smd/Read: sections "nodes" (id, "name", parent), "skeleton" ("time n", "bone px py pz rx ry rz", Euler radians,
|
||||
-- R = Rz Ry Rx; a bone missing from a later frame keeps its pose), "triangles" (a material line, then "bone px py pz
|
||||
-- nx ny nz u v [links (bone weight)...]", model space, v up; the rest of the weight goes to the parent bone).
|
||||
local Types = require("@rosetta/Types")
|
||||
local Rig = require("@rosetta/codecs/model/Rig")
|
||||
|
||||
@@ -20,7 +15,6 @@ export type Options = { fps: number?, name: string?, maxVertices: number? }
|
||||
type Bone = { id: number, name: string, parent: number }
|
||||
local ZERO: { number } = { 0, 0, 0, 0, 0, 0 }
|
||||
|
||||
-- read(text, opts) -> Scene | nil, message
|
||||
function Read.read(text: string, opts: Options?): (Types.Scene?, string?)
|
||||
local lines: { string } = {}
|
||||
for line in string.gmatch(text, "[^\r\n]*") do
|
||||
@@ -177,7 +171,7 @@ function Read.read(text: string, opts: Options?): (Types.Scene?, string?)
|
||||
local root: Types.Node = { name = opts and opts.name or "smd", children = {} }
|
||||
table.insert(scene.nodes, root)
|
||||
scene.roots[1] = 1
|
||||
-- skeleton (bind pose: the first frame)
|
||||
-- bind pose: the first frame
|
||||
local joints: { Rig.Joint } = {}
|
||||
local bind: { [number]: { number } } = frames[1] or {}
|
||||
for k, bn in bones do
|
||||
@@ -186,7 +180,6 @@ function Read.read(text: string, opts: Options?): (Types.Scene?, string?)
|
||||
joints[k] = { name = bn.name, parent = parent, translation = { v[1], v[2], v[3] }, rotation = Rig.angles(v[4], v[5], v[6]) }
|
||||
end
|
||||
local jointNodes, skinIndex = Rig.skeleton(scene, joints, "local", 1)
|
||||
-- meshes
|
||||
if #batches > 0 then
|
||||
local mesh: Types.Mesh = { primitives = {} }
|
||||
for _, b in batches do
|
||||
@@ -244,7 +237,6 @@ function Read.read(text: string, opts: Options?): (Types.Scene?, string?)
|
||||
table.insert(scene.nodes, { name = "mesh", children = {}, mesh = #scene.meshes, skin = if #bones > 0 then skinIndex else nil })
|
||||
table.insert(root.children, #scene.nodes)
|
||||
end
|
||||
-- animation
|
||||
if #frames > 1 or (#frames == 1 and #batches == 0) then
|
||||
local fps = opts and opts.fps or 30
|
||||
local t: { number } = {}
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
--!strict
|
||||
-- model/smd/Write: a Scene to Valve SMD text (version 1). Bones: the joints of the first skin (parents from the node
|
||||
-- tree: the nearest ancestor that is also a joint), or one "root" bone for a static scene; "skeleton": the bind pose
|
||||
-- (each joint node's TRS: rotation as Euler radians, R = Rz Ry Rx), or, with opts.animation = i, that animation sampled
|
||||
-- at its key times (translation / scale linearly, rotation by normalised linear interpolation); "triangles": every
|
||||
-- triangle of the scene in world space (codecs/model/MeshFlatten), one material line per triangle (the material
|
||||
-- name, else "default"), vertex lines with the Source links (opts.links ~= false; GoldSrc style otherwise: the
|
||||
-- strongest joint as the parent bone only). Animation SMDs (opts.animation set) carry no triangles unless
|
||||
-- opts.triangles is true.
|
||||
-- model/smd/Write: Scene -> SMD version 1: the first skin's joints (or one "root" bone), the bind pose or a sampled
|
||||
-- animation, world-space triangles with Source links (GoldSrc style: the strongest joint as the parent bone only).
|
||||
local Types = require("@rosetta/Types")
|
||||
local Mat4 = require("@rosetta/codecs/model/Mat4")
|
||||
local Flatten = require("@rosetta/codecs/model/MeshFlatten")
|
||||
@@ -52,7 +46,6 @@ local function lerp(a: { number }, b: { number }, t: number): { number }
|
||||
return out
|
||||
end
|
||||
|
||||
-- the value of channel ch at time tm (nil when the channel has no keys)
|
||||
local function sample(ch: Types.Channel, tm: number): { number }?
|
||||
local input, output = ch.input, ch.output
|
||||
local n = input.count
|
||||
@@ -91,7 +84,6 @@ local function sample(ch: Types.Channel, tm: number): { number }?
|
||||
return key(n - 1)
|
||||
end
|
||||
|
||||
-- write(scene, opts) -> text | nil, message
|
||||
function Write.write(scene: Types.Scene, opts: Options?): (string?, string?)
|
||||
if type(scene) ~= "table" or scene.kind ~= "scene" then
|
||||
return nil, "expected a Scene"
|
||||
@@ -179,7 +171,6 @@ function Write.write(scene: Types.Scene, opts: Options?): (string?, string?)
|
||||
end
|
||||
end
|
||||
table.insert(out, "end")
|
||||
-- triangles
|
||||
if not anim or (opts and opts.triangles) then
|
||||
local m, err = Flatten.merge(scene, function(name: string): boolean
|
||||
return name == "NORMAL" or name == "TEXCOORD_0" or name == "JOINTS_0" or name == "WEIGHTS_0"
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
--!strict
|
||||
-- model/smd: Valve SMD (studiomdl data, GoldSrc and Source: "version 1" text), read and write. Written from the
|
||||
-- Valve Developer Community "SMD file format" page; no code taken. Read: model/smd/Read (bones -> joint nodes + a
|
||||
-- Skin, triangles -> a primitive per material with JOINTS_0 / WEIGHTS_0, skeleton frames -> an animation; animation
|
||||
-- SMDs too). Write: model/smd/Write (the first skin's joints or one root bone, the bind pose or opts.animation,
|
||||
-- world-space triangles with Source weight links). Units as stored (inches in Valve's games), z up.
|
||||
-- Not supported: vertex animation (flex) sections (skipped, counted in meta.source.vertexAnimations).
|
||||
-- model/smd: Valve SMD (studiomdl "version 1" text, GoldSrc and Source), from the Valve Developer Community "SMD file
|
||||
-- format" page; no code taken. Units as stored (inches in Valve's games), z up. Not supported: vertex animation (flex).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -26,8 +22,8 @@ local Smd = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
fps: number?, -- skeleton frames per second (default 30)
|
||||
name: string?, -- the root node / animation name (the api passes the file name)
|
||||
fps: number?, -- default 30
|
||||
name: string?,
|
||||
maxVertices: number?, -- default 2^24
|
||||
}
|
||||
export type EncodeOptions = Write.Options
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- model/stl/Decode: the binary STL facet loop (50 bytes per facet: normal, 3 vertices, u16 attribute) and the 5-5-5
|
||||
-- colour expansion of the VisCAM / SolidView and Materialise Magics conventions. The caller (init) has checked that
|
||||
-- the facets fit in the data and allocated the outputs, so every index here is in range; nothing here throws.
|
||||
-- model/stl/Decode: binary STL facets (50 bytes: normal, 3 vertices, u16 attribute) and the 5-5-5 colours of VisCAM /
|
||||
-- SolidView and Materialise Magics. Never throws: the caller bounds the facets first.
|
||||
local readu16, readu32, writeu8, writeu16, writeu32 = buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32
|
||||
local band, bor, rshift = bit32.band, bit32.bor, bit32.rshift
|
||||
|
||||
local Decode = {}
|
||||
|
||||
-- binary(b, p, n, pos, nrm, attr) -> the OR of every attribute word. Copies the vertices (f32 bits as they are) into
|
||||
-- pos (n * 36 bytes), the facet normal three times into nrm (n * 36 bytes) and the attributes into attr (n * 2 bytes).
|
||||
function Decode.binary(b: buffer, p: number, n: number, pos: buffer, nrm: buffer, attr: buffer): number
|
||||
local any = 0
|
||||
for i = 0, n - 1 do
|
||||
@@ -42,14 +39,12 @@ function Decode.binary(b: buffer, p: number, n: number, pos: buffer, nrm: buffer
|
||||
return any
|
||||
end
|
||||
|
||||
-- 5-bit -> 8-bit, rounded
|
||||
local function x8(v: number): number
|
||||
return (v * 255 + 15) // 31
|
||||
end
|
||||
|
||||
-- colors(attr, n, magics, r, g, b, a, out): unorm8 RGBA per vertex (n * 12 bytes). VisCAM: bit 15 set = valid,
|
||||
-- red in bits 10..14, blue in 0..4 (invalid facets get r, g, b, a). Magics: bit 15 clear = the facet's own colour,
|
||||
-- red in bits 0..4, blue in 10..14 (set: the object colour r, g, b, a).
|
||||
-- VisCAM: bit 15 set = valid, red in bits 10..14, blue in 0..4. Magics: bit 15 clear = the facet's own colour,
|
||||
-- red in bits 0..4, blue in 10..14.
|
||||
function Decode.colors(attr: buffer, n: number, magics: boolean, dr: number, dg: number, db: number, da: number, out: buffer)
|
||||
for i = 0, n - 1 do
|
||||
local w = readu16(attr, i * 2)
|
||||
|
||||
@@ -1,20 +1,7 @@
|
||||
--!strict
|
||||
-- model/stl: STL (3D Systems stereolithography), ASCII and binary, read + write. Written from the format description
|
||||
-- (Wikipedia "STL (file format)" and the 3D Systems SLC spec).
|
||||
-- Decode: a triangle soup, 3 vertices per facet, no indices: POSITION f32 x3, NORMAL f32 x3 (the facet normal from the
|
||||
-- file on each of its vertices), COLOR_0 unorm8 x4 when the binary file uses a colour convention (VisCAM / SolidView:
|
||||
-- attribute bit 15 = colour valid, RGB 5-5-5 with red high; Materialise Magics: "COLOR=" rgba in the header is the
|
||||
-- object colour, bit 15 clear = the facet's own colour, red low). Other non-zero attribute words are kept per facet in
|
||||
-- prim.extras.faceAttributes.attribute (u16). Binary files may start with "solid": a file whose size is exactly
|
||||
-- 84 + 50 * count is binary. ASCII: keywords in any case, any whitespace, several solids (one primitive per solid in
|
||||
-- one mesh, prim.extras.solid = its name), facets with more than 3 vertices are fan-triangulated, a missing final
|
||||
-- endsolid is tolerated. meta.up = "z"; meta.source = { format, binary, header, colors, defaultColor, material,
|
||||
-- solids, facets }.
|
||||
-- Encode: every primitive of the scene in world space (node transforms applied; polygons / strips / fans
|
||||
-- fan-triangulated, points and lines skipped), binary (default) or ASCII (one solid per primitive, named after
|
||||
-- prim.extras.solid / the mesh / the node, made distinct), facet normals computed from the triangle
|
||||
-- (right-hand rule) unless opts.normals = "attribute", colours from COLOR_0 (the facet's first vertex) in either
|
||||
-- convention. Not supported: binary-only extensions other than the two colour conventions.
|
||||
-- model/stl: STL (3D Systems; Wikipedia "STL (file format)", the SLC spec), ASCII and binary, read + write. Supports:
|
||||
-- the VisCAM / SolidView and Materialise Magics colour conventions, a binary file starting with "solid" (size exactly
|
||||
-- 84 + 50 * count), several ASCII solids. Not supported: other binary attribute extensions.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -35,18 +22,16 @@ local Stl = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxFaces: number?, -- refuse more facets (default 2^25)
|
||||
colors: ("auto" | "viscam" | "magics" | "none")?, -- binary colour convention (default "auto": "COLOR=" in the
|
||||
-- header = magics, else any attribute with bit 15 set = viscam, else none)
|
||||
maxFaces: number?, -- default 2^25
|
||||
colors: ("auto" | "viscam" | "magics" | "none")?, -- default "auto": "COLOR=" = magics, else bit 15 = viscam
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
ascii: boolean?, -- default false (binary)
|
||||
colors: ("viscam" | "magics")?, -- write COLOR_0 (the first vertex of each facet) in that convention (binary only)
|
||||
defaultColor: { number }?, -- magics: the object colour r, g, b, a 0..255 (default opaque white); facets of exactly
|
||||
-- that colour refer to it, the others carry their own (alpha 255)
|
||||
name: string?, -- the ASCII solid name (default: the mesh / node name, else "mesh")
|
||||
header: string?, -- the binary header text (at most 80 bytes; default "rosetta STL")
|
||||
normals: ("compute" | "attribute")?, -- facet normals from the triangle (default) or the first vertex's NORMAL
|
||||
colors: ("viscam" | "magics")?, -- binary only
|
||||
defaultColor: { number }?, -- magics object colour, 0..255 (default opaque white)
|
||||
name: string?, -- default: the mesh / node name, else "mesh"
|
||||
header: string?, -- at most 80 bytes; default "rosetta STL"
|
||||
normals: ("compute" | "attribute")?, -- default: from the triangle
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
@@ -290,7 +275,7 @@ function Stl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
|
||||
if size < 84 then
|
||||
return nil, Err.new(Err.TRUNCATED, "shorter than a binary STL header", r.base)
|
||||
end
|
||||
-- binary with extra bytes after the facets (tolerated) or too few (TRUNCATED)
|
||||
-- extra bytes after the facets are tolerated
|
||||
return decodeBinary(r, maxFaces, colors)
|
||||
end
|
||||
|
||||
@@ -301,7 +286,6 @@ local function f32(v: number): number
|
||||
return buffer.readf32(scratch, 0)
|
||||
end
|
||||
|
||||
-- a COLOR_0 component as 0..255
|
||||
local function byte(a: Flatten.Attr, v: number): number
|
||||
if a.raw then
|
||||
if a.type == "unorm16" then
|
||||
@@ -341,7 +325,6 @@ function Stl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
|
||||
local C = m.attrs.COLOR_0
|
||||
local corners = m.corners
|
||||
local nf = #corners // 3
|
||||
-- facet normal (computed in double from the f32 vertices) and colour of facet f (0-based)
|
||||
local function normal(f: number): (number, number, number)
|
||||
local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3]
|
||||
if N then
|
||||
@@ -403,7 +386,6 @@ function Stl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
|
||||
end
|
||||
return buffer.fromstring(table.concat(out)), nil
|
||||
end
|
||||
-- binary
|
||||
local buf = buffer.create(84 + 50 * nf)
|
||||
local header = o.header or "rosetta STL"
|
||||
if colors == "magics" then
|
||||
@@ -420,7 +402,6 @@ function Stl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err
|
||||
end
|
||||
buffer.writestring(buf, 0, header)
|
||||
writeu32(buf, 80, nf)
|
||||
-- the attribute words: colours, or the raw words of a single STL-decoded primitive
|
||||
local rawAttr: { number }? = nil
|
||||
if colors == nil and #m.parts == 1 then
|
||||
local ex = m.parts[1].prim.extras
|
||||
|
||||
@@ -1,22 +1,7 @@
|
||||
--!strict
|
||||
-- model/usda/Build: a parsed USDA layer (model/usda/Parse) -> Scene, following the UsdGeom / UsdShade / UsdLux
|
||||
-- schemas (openusd 26.x documentation). Prims: Xform / Scope / untyped def / over -> nodes (class prims are skipped;
|
||||
-- Material, Shader, NodeGraph, GeomSubset and scopes holding only those are not nodes); Mesh -> a node with a mesh
|
||||
-- (one primitive per GeomSubset of the "face" element type + one for the remaining faces), Camera, DistantLight /
|
||||
-- SphereLight / RectLight / DiskLight / CylinderLight. The selected variant of each variant set is merged into its prim.
|
||||
-- Transforms: xformOpOrder over translate / scale / rotateX|Y|Z / rotateXYZ (all six orders) / orient / transform, the
|
||||
-- !invert! prefix and !resetXformStack! (the node becomes a root). Time samples on xform ops -> one animation (the local
|
||||
-- matrix sampled at the union of the ops' time codes, decomposed into TRS channels; time = code / timeCodesPerSecond);
|
||||
-- other attributes use their earliest sample (as UsdTimeCode.EarliestTime()). Primvars: st (and every texCoord2f /
|
||||
-- float2 primvar) -> TEXCOORD_n (v flipped to glTF's top-left origin unless opts.flipV = false), normals, displayColor
|
||||
-- / displayOpacity -> COLOR_0 (a constant displayColor on an unbound mesh becomes a material instead), with every
|
||||
-- interpolation (constant / uniform / vertex / varying / faceVarying) and :indices. Faces are fan-triangulated
|
||||
-- (opts.triangulate = false keeps "polygons"), holeIndices skipped, orientation = "leftHanded" reversed.
|
||||
-- UsdPreviewSurface materials (inputs resolved through connections to Material / NodeGraph interface inputs) with
|
||||
-- UsdUVTexture textures (file, wrapS / wrapT, st through UsdPrimvarReader_float2, UsdTransform2d ->
|
||||
-- KHR_texture_transform), material:binding (inherited down the namespace, also on GeomSubsets).
|
||||
-- Not supported: composition arcs (references, payloads, inherits, specializes, subLayers: listed in
|
||||
-- meta.source.unsupported), UsdSkel, blend shapes, BasisCurves / Points / NURBS, instancing, MaterialX networks.
|
||||
-- model/usda/Build: a USDA layer to a Scene, following the UsdGeom / UsdShade / UsdLux schemas (OpenUSD 26.x). Other
|
||||
-- attributes than xform ops use their earliest sample (as UsdTimeCode.EarliestTime()). Not supported: composition arcs,
|
||||
-- UsdSkel, blend shapes, BasisCurves / Points / NURBS, instancing, MaterialX networks.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Mat4 = require("@rosetta/codecs/model/Mat4")
|
||||
local Parse = require("@rosetta/model/usda/Parse")
|
||||
@@ -53,7 +38,6 @@ local function str(v: any): string?
|
||||
end
|
||||
return nil
|
||||
end
|
||||
-- a tuple / scalar -> numbers (nil when not numeric)
|
||||
local function nums(v: any): { number }?
|
||||
if type(v) == "number" then
|
||||
return { v }
|
||||
@@ -90,7 +74,7 @@ local function num(v: any): number?
|
||||
return nil
|
||||
end
|
||||
|
||||
-- the value of a property: its default, else its earliest time sample
|
||||
-- a property's default, else its earliest time sample
|
||||
local function propValue(p: Prop?): any
|
||||
if not p then
|
||||
return nil
|
||||
@@ -117,7 +101,6 @@ local function joinPath(parent: string, name: string): string
|
||||
return if parent == "/" then "/" .. name else parent .. "/" .. name
|
||||
end
|
||||
|
||||
-- resolve a (possibly relative) Sdf path against the prim path that holds it
|
||||
local function resolvePath(base: string, p: string): string
|
||||
if string.sub(p, 1, 1) == "/" then
|
||||
return p
|
||||
@@ -138,7 +121,6 @@ local function resolvePath(base: string, p: string): string
|
||||
end
|
||||
return "/" .. table.concat(out, "/")
|
||||
end
|
||||
-- "/a/b.outputs:rgb" -> "/a/b", "outputs:rgb"
|
||||
local function splitProp(p: string): (string, string?)
|
||||
local prim, prop = string.match(p, "^(.-)%.([^/]+)$")
|
||||
if prim and prop then
|
||||
@@ -161,7 +143,6 @@ end
|
||||
-- ------------------------------------------------------------------------------------------------ xform ops
|
||||
type Op = { kind: string, axes: string?, prop: Prop, invert: boolean }
|
||||
|
||||
-- the op stack of a prim: ops in xformOpOrder, resetXformStack
|
||||
local function xformOps(p: Prim): ({ Op }, boolean)
|
||||
local order = p.props.xformOpOrder
|
||||
local list = order and propValue(order)
|
||||
@@ -193,7 +174,6 @@ local function xformOps(p: Prim): ({ Op }, boolean)
|
||||
end
|
||||
|
||||
local AXIS = { X = 1, Y = 2, Z = 3 }
|
||||
-- the matrix of one op for a value
|
||||
local function opMatrix(op: Op, v: any): { number }?
|
||||
local n = nums(v)
|
||||
if not n then
|
||||
@@ -217,7 +197,7 @@ local function opMatrix(op: Op, v: any): { number }?
|
||||
elseif k == "rotate" and op.axes then
|
||||
local axes = op.axes :: string
|
||||
local r: { number } = Types.Scene.IDENTITY :: any
|
||||
-- rotateXZY: X first, then Z, then Y: R = Ry * Rz * Rx (column vectors); the value is always (x, y, z) angles
|
||||
-- rotateXZY: R = Ry * Rz * Rx (column vectors); the value is always (x, y, z) angles
|
||||
for c = 1, #axes do
|
||||
local a = AXIS[string.sub(axes, c, c)]
|
||||
local angle = if #axes == 1 then n[1] or 0 else n[a] or 0
|
||||
@@ -240,7 +220,6 @@ local function lerpValue(a: any, b: any, f: number, quat: boolean): any
|
||||
end
|
||||
local out = table.create(#na)
|
||||
if quat and #na == 4 then
|
||||
-- (w, x, y, z): slerp through nlerp with the short path
|
||||
local dot = 0
|
||||
for k = 1, 4 do
|
||||
dot += na[k] * nb[k]
|
||||
@@ -257,7 +236,7 @@ local function lerpValue(a: any, b: any, f: number, quat: boolean): any
|
||||
return { t = "tuple", v = out }
|
||||
end
|
||||
|
||||
-- an op's value at time code t (samples interpolated linearly, held outside their range)
|
||||
-- samples interpolated linearly, held outside their range
|
||||
local function opValueAt(op: Op, t: number?): any
|
||||
local p = op.prop
|
||||
local s = p.samples
|
||||
@@ -309,7 +288,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
local unsupported: { [string]: boolean } = {}
|
||||
local meta = layer.meta
|
||||
|
||||
-- prim index (variants merged), paths
|
||||
local byPath: { [string]: Prim } = {}
|
||||
local parentOf: { [Prim]: string } = {}
|
||||
local pathOf: { [Prim]: string } = {}
|
||||
@@ -360,7 +338,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
parentOf[p] = parent
|
||||
local existing = byPath[path]
|
||||
if existing and existing ~= p then
|
||||
-- over / def of the same path in one layer: merge into the first spec
|
||||
-- over / def of the same path in one layer: merged into the first spec
|
||||
for _, pn in p.order do
|
||||
if not existing.props[pn] then
|
||||
existing.props[pn] = p.props[pn]
|
||||
@@ -375,7 +353,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
table.insert(existing.children, c)
|
||||
end
|
||||
table.clear(p.children)
|
||||
p.specifier = "class" -- skipped below
|
||||
p.specifier = "class"
|
||||
else
|
||||
byPath[path] = p
|
||||
end
|
||||
@@ -396,7 +374,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
unsupported.subLayers = true
|
||||
end
|
||||
|
||||
-- a property of a prim path ("/a/b.inputs:x")
|
||||
local function propAt(path: string): (Prim?, Prop?)
|
||||
local pp, pn = splitProp(path)
|
||||
local prim = byPath[pp]
|
||||
@@ -406,7 +383,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
return prim, prim.props[pn]
|
||||
end
|
||||
|
||||
-- --------------------------------------------------------------------------------------------- materials
|
||||
local texCoordIndex: { [string]: number } = {}
|
||||
local texCoordCount = 0
|
||||
local function texCoordFor(name: string): number
|
||||
@@ -418,7 +394,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
end
|
||||
return k
|
||||
end
|
||||
-- primvar names of every mesh, "st" first, so material readers and meshes agree on TEXCOORD_n
|
||||
-- "st" first, so materials and meshes agree on TEXCOORD_n
|
||||
do
|
||||
local names: { [string]: boolean } = {}
|
||||
for _, p in byPath do
|
||||
@@ -448,7 +424,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
end
|
||||
end
|
||||
|
||||
-- an input's resolved source: a value, or { shader = Prim, output = name }
|
||||
type Source = { value: any?, shader: Prim?, output: string? }
|
||||
local function input(prim: Prim, name: string, depth: number?): Source?
|
||||
local d = depth or 0
|
||||
@@ -469,7 +444,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
if outName and tprim.typeName == "Shader" then
|
||||
return { shader = tprim, output = outName }
|
||||
elseif outName then
|
||||
-- a NodeGraph output: follow its connection
|
||||
local op = tprim.props[tn]
|
||||
if op and op.connect and #op.connect > 0 then
|
||||
local t2 = resolvePath(tp, op.connect[1])
|
||||
@@ -499,7 +473,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
|
||||
local textureIndex: { [string]: number } = {}
|
||||
local WRAP: { [string]: string } = { ["repeat"] = "repeat", clamp = "clamp", mirror = "mirror", black = "clamp", useMetadata = "repeat" }
|
||||
-- UsdUVTexture shader -> TextureRef (texture index + texCoord + transform)
|
||||
local function textureRef(shader: Prim): Types.TextureRef?
|
||||
if shaderId(shader) ~= "UsdUVTexture" then
|
||||
return nil
|
||||
@@ -535,7 +508,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
textureIndex[key] = ti
|
||||
end
|
||||
local ref: Types.TextureRef = { texture = ti :: number }
|
||||
-- st: UsdPrimvarReader_float2 (maybe through UsdTransform2d)
|
||||
-- st: UsdPrimvarReader_float2, maybe through UsdTransform2d
|
||||
local st = input(shader, "st")
|
||||
local reader = st and st.shader
|
||||
if reader and shaderId(reader) == "UsdTransform2d" then
|
||||
@@ -587,7 +560,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
mat.metallic = 0
|
||||
mat.roughness = 0.5
|
||||
mat.extras = { usd = { path = path } }
|
||||
-- the surface shader
|
||||
local surf = mp.props["outputs:surface"] or mp.props["outputs:usd:surface"]
|
||||
local shader: Prim? = nil
|
||||
if surf and surf.connect and #surf.connect > 0 then
|
||||
@@ -695,7 +667,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
return #scene.materials
|
||||
end
|
||||
|
||||
-- the bound material of a prim (material:binding, inherited from ancestors)
|
||||
-- material:binding, inherited from ancestors
|
||||
local function binding(prim: Prim, path: string): number?
|
||||
local p: Prim? = prim
|
||||
local pp = path
|
||||
@@ -733,7 +705,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
return mi :: number
|
||||
end
|
||||
|
||||
-- --------------------------------------------------------------------------------------------- meshes
|
||||
type Primvar = { data: { number }, w: number, interp: string, idx: { number }? }
|
||||
local function primvar(p: Prop?, defaultInterp: string): Primvar?
|
||||
if not p then
|
||||
@@ -791,7 +762,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
end
|
||||
faceStart[nfaces + 1] = acc
|
||||
end
|
||||
-- primvars, validated
|
||||
local function sizeOk(pv: Primvar): boolean
|
||||
local n = (if pv.idx then #pv.idx else #pv.data // pv.w)
|
||||
local want = if pv.interp == "constant" then 1
|
||||
@@ -848,7 +818,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the value of a primvar for (point, face, corner) (0-based), component c
|
||||
local function get(pv: Primvar, point: number, face: number, corner: number, c: number): number
|
||||
local e = if pv.interp == "constant" then 0
|
||||
elseif pv.interp == "uniform" then face
|
||||
@@ -871,7 +840,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
end
|
||||
end
|
||||
local leftHanded = str(propValue(prim.props.orientation)) == "leftHanded"
|
||||
-- holes
|
||||
local hole: { [number]: boolean } = {}
|
||||
local hv = propValue(prim.props.holeIndices)
|
||||
if isArr(hv) then
|
||||
@@ -879,7 +847,7 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
hole[f] = true
|
||||
end
|
||||
end
|
||||
-- face sets: GeomSubsets ("face" elements), the rest
|
||||
-- face sets: GeomSubsets of "face" elements, then the rest
|
||||
local meshMaterial = binding(prim, path)
|
||||
local constantColor: { number }? = nil
|
||||
if color and color.interp == "constant" then
|
||||
@@ -921,9 +889,8 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
end
|
||||
local mesh: Types.Mesh = { name = prim.name, primitives = {} }
|
||||
for _, set in sets do
|
||||
-- vertices: one per point (vertex-rate data) or per corner
|
||||
local keyToVert: { [number]: number } = {}
|
||||
local vp, vf, vc = {}, {}, {} -- point, face, corner per new vertex (0-based)
|
||||
local vp, vf, vc = {}, {}, {}
|
||||
local nv = 0
|
||||
local out: { number } = {}
|
||||
local faceSizes: { number } = {}
|
||||
@@ -1001,7 +968,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
end
|
||||
local mi = set.material
|
||||
if color and not constantColor then
|
||||
-- varying colours -> COLOR_0 (rgb, or rgba with displayOpacity)
|
||||
if opacity then
|
||||
local a = Types.Scene.accessor(nil, "f32", 4, nv)
|
||||
for v = 1, nv do
|
||||
@@ -1048,7 +1014,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
return mesh, nil
|
||||
end
|
||||
|
||||
-- --------------------------------------------------------------------------------------------- cameras / lights
|
||||
local function camera(prim: Prim): Types.Camera
|
||||
local function f(name: string, d: number): number
|
||||
return num(propValue(prim.props[name])) or d
|
||||
@@ -1095,7 +1060,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
return l
|
||||
end
|
||||
|
||||
-- --------------------------------------------------------------------------------------------- nodes
|
||||
local tcps = num(meta.timeCodesPerSecond) or num(meta.framesPerSecond) or 24
|
||||
if tcps <= 0 then
|
||||
tcps = 24
|
||||
@@ -1147,7 +1111,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
table.insert(scene.nodes, n)
|
||||
local ni = #scene.nodes
|
||||
local ops, reset = xformOps(p)
|
||||
-- animated ops: the local matrix at the union of their time codes
|
||||
local times: { number } = {}
|
||||
do
|
||||
local seen: { [number]: boolean } = {}
|
||||
@@ -1192,7 +1155,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
local T, R, S = Mat4.decompose(localMatrix(ops, times[1]))
|
||||
n.translation, n.rotation, n.scale = T, R, S
|
||||
elseif #ops > 0 then
|
||||
-- static: TRS when the stack is translate / rotate / scale in that order, else the matrix
|
||||
local simple = true
|
||||
local stage = 0
|
||||
for _, op in ops do
|
||||
@@ -1288,7 +1250,6 @@ function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?)
|
||||
table.insert(scene.animations, animation)
|
||||
end
|
||||
|
||||
-- stage metadata
|
||||
local up = str(meta.upAxis)
|
||||
scene.meta.up = if up == "Z" then "z" else "y"
|
||||
local mpu = num(meta.metersPerUnit)
|
||||
|
||||
@@ -1,40 +1,33 @@
|
||||
--!strict
|
||||
-- model/usda/Parse: USD ASCII (Sdf text format, "#usda 1.0") -> a layer of prim specs. New code, from the Sdf text
|
||||
-- grammar as Pixar's USD writes and reads it: layer metadata, def / over / class prims with metadata, attributes
|
||||
-- (custom / uniform / varying / config, scalar and array types, defaults, .timeSamples, .connect, metadata), relationships,
|
||||
-- list ops (prepend / append / add / delete / reorder), variant sets, dictionaries, strings ("", '', triple quoted),
|
||||
-- asset paths (@...@, @@@...@@@), paths (<...>), comments (#, //, /* */). Numeric arrays (points, indices) take a fast
|
||||
-- path into flat number arrays. .spline blocks and unknown constructs are skipped by bracket matching.
|
||||
-- Errors raise a table { usda = message, at = byte offset } inside this module; Parse.layer catches them (pcall) and
|
||||
-- returns nil, message, offset - nothing escapes.
|
||||
-- model/usda/Parse: USD ASCII ("#usda 1.0") to prim specs, from the Sdf text grammar as Pixar's USD writes and reads
|
||||
-- it; new code. .spline blocks and unknown constructs are skipped by bracket matching. Never throws.
|
||||
local Parse = {}
|
||||
|
||||
-- values: numbers, booleans, strings, and these tagged tables
|
||||
export type Arr = { t: "arr", w: number, v: { number } } -- numeric array, w numbers per element (tuples flattened)
|
||||
export type Arr = { t: "arr", w: number, v: { number } } -- w numbers per element (tuples flattened)
|
||||
export type Value = any
|
||||
|
||||
export type Prop = {
|
||||
name: string,
|
||||
rel: boolean, -- a relationship
|
||||
typeName: string?, -- "point3f", "token", ... (attributes)
|
||||
rel: boolean,
|
||||
typeName: string?,
|
||||
array: boolean?,
|
||||
uniform: boolean?,
|
||||
custom: boolean?,
|
||||
value: Value?, -- the default value (attributes) or the targets (relationships: { path strings })
|
||||
value: Value?, -- relationships: { path strings }
|
||||
hasValue: boolean?,
|
||||
samples: { times: { number }, values: { Value } }?,
|
||||
connect: { string }?, -- connection target paths (attributes)
|
||||
connect: { string }?,
|
||||
meta: { [string]: Value }?,
|
||||
}
|
||||
export type Prim = {
|
||||
specifier: string, -- "def" | "over" | "class"
|
||||
specifier: string,
|
||||
typeName: string?,
|
||||
name: string,
|
||||
meta: { [string]: Value },
|
||||
props: { [string]: Prop },
|
||||
order: { string }, -- property names in file order
|
||||
order: { string },
|
||||
children: { Prim },
|
||||
variantSets: { [string]: { [string]: Prim } }?, -- set -> variant -> a prim body (props / children)
|
||||
variantSets: { [string]: { [string]: Prim } }?,
|
||||
}
|
||||
export type Layer = { meta: { [string]: Value }, prims: { Prim } }
|
||||
|
||||
@@ -51,12 +44,10 @@ local function fail(msg: string, at: number): never
|
||||
error({ usda = msg, at = at }, 0)
|
||||
end
|
||||
|
||||
-- the parser over one text; positions are 1-based string indices
|
||||
local function parser(s: string, maxBytes: number)
|
||||
local n = #s
|
||||
local depth = 0
|
||||
|
||||
-- whitespace and comments (newlines included)
|
||||
local function ws(i: number): number
|
||||
while true do
|
||||
local _, e = sfind(s, "^[ \t\r\n]+", i)
|
||||
@@ -64,13 +55,13 @@ local function parser(s: string, maxBytes: number)
|
||||
i = e + 1
|
||||
end
|
||||
local c = sbyte(s, i)
|
||||
if c == 35 then -- #
|
||||
if c == 35 then
|
||||
local nl = sfind(s, "\n", i, true)
|
||||
i = if nl then nl + 1 else n + 1
|
||||
elseif c == 47 and sbyte(s, i + 1) == 47 then -- //
|
||||
elseif c == 47 and sbyte(s, i + 1) == 47 then
|
||||
local nl = sfind(s, "\n", i, true)
|
||||
i = if nl then nl + 1 else n + 1
|
||||
elseif c == 47 and sbyte(s, i + 1) == 42 then -- /* */
|
||||
elseif c == 47 and sbyte(s, i + 1) == 42 then
|
||||
local _, ce = sfind(s, "*/", i + 2, true)
|
||||
if not ce then
|
||||
fail("unterminated comment", i)
|
||||
@@ -105,7 +96,7 @@ local function parser(s: string, maxBytes: number)
|
||||
end
|
||||
return (string.gsub(str, "\\(x?)(.)", function(x: string, c: string): string
|
||||
if x == "x" then
|
||||
return "\\x" .. c -- left alone (rare)
|
||||
return "\\x" .. c
|
||||
end
|
||||
return ESC[c] or c
|
||||
end))
|
||||
@@ -148,7 +139,6 @@ local function parser(s: string, maxBytes: number)
|
||||
return v, (e :: number) + 1
|
||||
end
|
||||
end
|
||||
-- inf / -inf / nan
|
||||
local w, e2 = sfind(s, "^[-+]?%a+", i)
|
||||
if w then
|
||||
local word = string.lower(ssub(s, w, e2))
|
||||
@@ -163,7 +153,6 @@ local function parser(s: string, maxBytes: number)
|
||||
return nil, i
|
||||
end
|
||||
|
||||
-- skip a balanced (), [], {} block starting at i (strings and comments respected)
|
||||
local function skipBalanced(i: number): number
|
||||
local open = sbyte(s, i)
|
||||
local level = 0
|
||||
@@ -202,7 +191,6 @@ local function parser(s: string, maxBytes: number)
|
||||
local value: (i: number) -> (Value, number)
|
||||
local metadata: (i: number) -> ({ [string]: Value }, number)
|
||||
|
||||
-- [ ... ]: the fast path for numeric arrays (flat numbers + tuple width), else a generic list
|
||||
local function list(i: number): (Value, number)
|
||||
local close = sfind(s, "]", i + 1, true)
|
||||
if close then
|
||||
@@ -216,7 +204,7 @@ local function parser(s: string, maxBytes: number)
|
||||
w += 1
|
||||
end
|
||||
elseif sfind(body, "[%(%)]") then
|
||||
w = -1 -- nested tuples: the generic path
|
||||
w = -1
|
||||
end
|
||||
if w > 0 then
|
||||
local out: { number } = {}
|
||||
@@ -240,7 +228,6 @@ local function parser(s: string, maxBytes: number)
|
||||
end
|
||||
end
|
||||
end
|
||||
-- generic
|
||||
local items = {}
|
||||
i += 1
|
||||
while true do
|
||||
@@ -256,7 +243,7 @@ local function parser(s: string, maxBytes: number)
|
||||
v, i = value(i)
|
||||
table.insert(items, v)
|
||||
i = ws(i)
|
||||
if ssub(s, i, i) == "(" then -- per-item metadata (subLayers offsets, ...)
|
||||
if ssub(s, i, i) == "(" then
|
||||
local _
|
||||
_, i = metadata(i)
|
||||
i = ws(i)
|
||||
@@ -268,7 +255,6 @@ local function parser(s: string, maxBytes: number)
|
||||
fail("expected ',' or ']' in a list", i)
|
||||
end
|
||||
end
|
||||
-- all numbers, or all equal-width numeric tuples -> arr
|
||||
local w: number? = nil
|
||||
local flat: { number } = {}
|
||||
for _, it in items do
|
||||
@@ -326,7 +312,6 @@ local function parser(s: string, maxBytes: number)
|
||||
return { t = "tuple", v = items }, i
|
||||
end
|
||||
|
||||
-- { type key = value ... } (metadata dictionaries)
|
||||
local function dict(i: number): (Value, number)
|
||||
local out: { [string]: Value } = {}
|
||||
i += 1
|
||||
@@ -403,7 +388,7 @@ local function parser(s: string, maxBytes: number)
|
||||
end
|
||||
local a: { [string]: any } = { t = "asset", v = path }
|
||||
local j = ws(i)
|
||||
if ssub(s, j, j) == "<" then -- references = @file@</prim>
|
||||
if ssub(s, j, j) == "<" then
|
||||
local e = sfind(s, ">", j + 1, true)
|
||||
if not e then
|
||||
fail("unterminated path", j)
|
||||
@@ -444,7 +429,6 @@ local function parser(s: string, maxBytes: number)
|
||||
return v, i
|
||||
end
|
||||
|
||||
-- ( key = value ; "doc" ; prepend key = value ... )
|
||||
function metadata(i: number): ({ [string]: Value }, number)
|
||||
local out: { [string]: Value } = {}
|
||||
i = expect(i, "(")
|
||||
@@ -481,9 +465,7 @@ local function parser(s: string, maxBytes: number)
|
||||
local v
|
||||
v, i = value(i + 1)
|
||||
if op == "delete" then
|
||||
-- deletions only matter for composition
|
||||
elseif op and op ~= "reorder" then
|
||||
-- prepend / append / add: merge into one list
|
||||
local prev = out[key :: string]
|
||||
if type(prev) == "table" and prev.t == "list" and type(v) == "table" and v.t == "list" then
|
||||
for _, x in v.v do
|
||||
@@ -499,7 +481,6 @@ local function parser(s: string, maxBytes: number)
|
||||
end
|
||||
end
|
||||
|
||||
-- time samples: { time: value, ... }
|
||||
local function samples(i: number): ({ times: { number }, values: { Value } }, number)
|
||||
local times: { number }, values: { Value } = {}, {}
|
||||
i = expect(i, "{")
|
||||
@@ -523,7 +504,7 @@ local function parser(s: string, maxBytes: number)
|
||||
i = expect(i, ":")
|
||||
local v
|
||||
v, i = value(i)
|
||||
table.insert(times, t :: number) -- fail() threw on nil
|
||||
table.insert(times, t :: number)
|
||||
table.insert(values, v)
|
||||
end
|
||||
return { times = times, values = values }, i
|
||||
@@ -562,7 +543,6 @@ local function parser(s: string, maxBytes: number)
|
||||
fail("expected a prim type or name", i)
|
||||
end
|
||||
i = ws(i)
|
||||
-- dotted schema names (rare)
|
||||
while ssub(s, i, i) == "." do
|
||||
local more
|
||||
more, i = ident(i + 1)
|
||||
@@ -618,7 +598,7 @@ local function parser(s: string, maxBytes: number)
|
||||
end
|
||||
end
|
||||
|
||||
-- one property: [listop] [custom] [uniform|varying|config] (rel name | type[] name)[.connect|.timeSamples|...]
|
||||
-- [listop] [custom] [uniform|varying|config] (rel name | type[] name)[.connect|.timeSamples|...]
|
||||
local function property(i: number, first: string, p: Prim): number
|
||||
local word: string? = first
|
||||
local op: string? = nil
|
||||
@@ -685,7 +665,6 @@ local function parser(s: string, maxBytes: number)
|
||||
local v
|
||||
v, i = value(i)
|
||||
if op == "delete" then
|
||||
-- composition only
|
||||
elseif suffix == "connect" then
|
||||
pr.connect = targets(v)
|
||||
elseif isRel then
|
||||
@@ -755,7 +734,6 @@ local function parser(s: string, maxBytes: number)
|
||||
end
|
||||
end
|
||||
|
||||
-- the whole layer
|
||||
local function layer(): Layer
|
||||
local i = 1
|
||||
if ssub(s, 1, 3) == "\239\187\191" then
|
||||
@@ -799,7 +777,6 @@ local function parser(s: string, maxBytes: number)
|
||||
return layer
|
||||
end
|
||||
|
||||
-- layer(text, opts?) -> Layer | nil, message, offset (0-based)
|
||||
function Parse.layer(text: string, maxBytes: number?): (Layer?, string?, number?)
|
||||
local run = parser(text, maxBytes or 2 ^ 30)
|
||||
local ok, res = pcall(run)
|
||||
@@ -812,7 +789,6 @@ function Parse.layer(text: string, maxBytes: number?): (Layer?, string?, number?
|
||||
return nil, "parse error: " .. tostring(res), nil
|
||||
end
|
||||
|
||||
-- version(text) -> the "#usda <version>" string
|
||||
function Parse.version(text: string): string?
|
||||
return smatch(text, "^\239?\187?\191?#usda%s+([%d%.]+)")
|
||||
end
|
||||
|
||||
@@ -1,15 +1,6 @@
|
||||
--!strict
|
||||
-- model/usda/Write: Scene -> USD ASCII text (UsdGeom / UsdShade / UsdLux). New code.
|
||||
-- Layout: one root prim (the scene's single root node, else an Xform "root" holding every root) as the defaultPrim,
|
||||
-- a "Looks" scope under it with the materials (UsdPreviewSurface + UsdUVTexture + UsdPrimvarReader_float2, texture
|
||||
-- transforms as UsdTransform2d), and one prim per node: a node with a mesh is a Mesh prim (its primitives merged, a
|
||||
-- GeomSubset per primitive when there are several), a node with only a camera / light is that Camera / light prim,
|
||||
-- other nodes are Xforms (meshes / cameras / lights that cannot share the node's prim become children). Transforms are
|
||||
-- translate / orient / scale ops (or a transform op for matrices); animation channels (translation / rotation / scale)
|
||||
-- become time samples on those ops (timeCodesPerSecond 24). TEXCOORD_n -> primvars:st, st1, ... (v flipped back),
|
||||
-- COLOR_0 -> displayColor (+ displayOpacity), NORMAL -> normals, all "vertex" interpolated. Textures: their uri, or the
|
||||
-- embedded bytes written into opts.files as <name>_<n>.<ext>. Not written: skins, morph targets, weights animation,
|
||||
-- lines / points primitives (counted in the returned notes).
|
||||
-- model/usda/Write: Scene -> USD ASCII (UsdGeom / UsdShade / UsdLux); new code. timeCodesPerSecond 24. Not written:
|
||||
-- skins, morph targets, weights animation, lines / points primitives.
|
||||
local Types = require("@rosetta/Types")
|
||||
|
||||
local Write = {}
|
||||
@@ -48,7 +39,6 @@ local function asset(s: string): string
|
||||
end
|
||||
return "@" .. s .. "@"
|
||||
end
|
||||
-- a valid, sibling-unique prim name
|
||||
local function namer(): (string?, string) -> string
|
||||
local used: { [string]: boolean } = {}
|
||||
return function(name: string?, fallback: string): string
|
||||
@@ -69,7 +59,6 @@ local function namer(): (string?, string) -> string
|
||||
end
|
||||
end
|
||||
|
||||
-- an accessor's elements as numbers (normalized types to floats)
|
||||
local function values(acc: Types.Accessor?): ({ number }?, number)
|
||||
if not acc then
|
||||
return nil, 0
|
||||
@@ -88,7 +77,6 @@ local function values(acc: Types.Accessor?): ({ number }?, number)
|
||||
return out, c
|
||||
end
|
||||
|
||||
-- array literal of tuples ("[(x, y, z), ...]") or scalars
|
||||
local function arrayText(vals: { number }, width: number, stride: number?, count: number?, map: ((i: number, k: number, v: number) -> number)?): string
|
||||
local st = stride or width
|
||||
local n = count or (#vals // st)
|
||||
@@ -114,12 +102,11 @@ type Merged = {
|
||||
indices: { number },
|
||||
normals: { number }?,
|
||||
uvs: { [number]: { number } },
|
||||
colors: { number }?, -- rgba
|
||||
colors: { number }?,
|
||||
hasAlpha: boolean,
|
||||
subsets: { { faces: { number }, material: number? } },
|
||||
}
|
||||
|
||||
-- the triangles / polygons of a primitive as (counts, corner indices into its vertices); nil for lines / points
|
||||
local function faces(p: Types.Primitive, nverts: number): ({ number }?, { number }?)
|
||||
local idx: { number }
|
||||
if p.indices then
|
||||
@@ -176,7 +163,6 @@ local function faces(p: Types.Primitive, nverts: number): ({ number }?, { number
|
||||
return counts, out
|
||||
end
|
||||
|
||||
-- the primitives of a mesh merged into one USD mesh (GeomSubsets per primitive); nil when nothing is writable
|
||||
local function merge(mesh: Types.Mesh, notes: { [string]: number }): Merged?
|
||||
local prims: { Types.Primitive } = {}
|
||||
for _, p in mesh.primitives do
|
||||
@@ -192,7 +178,6 @@ local function merge(mesh: Types.Mesh, notes: { [string]: number }): Merged?
|
||||
if #prims == 0 then
|
||||
return nil
|
||||
end
|
||||
-- attributes every primitive has
|
||||
local all = { NORMAL = true }
|
||||
local uvSets: { number } = {}
|
||||
for k = 0, 7 do
|
||||
@@ -317,7 +302,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu
|
||||
local rootNames = namer()
|
||||
local rootName = if wrap then "root" else rootNames(nodes[roots[1]].name, "root")
|
||||
|
||||
-- texture files
|
||||
local base: string = o.name and string.gsub(string.match(o.name, "([^/\\]+)$") or o.name, "%.[^.]*$", "") or "model"
|
||||
local texFile: { [number]: string } = {}
|
||||
for i, tex in scene.textures or {} do
|
||||
@@ -338,7 +322,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu
|
||||
texFile[i] = uri :: string
|
||||
end
|
||||
|
||||
-- animation: per node, per path -> { times, values (components) }
|
||||
type Track = { times: { number }, vals: { number }, comps: number }
|
||||
local tracks: { [number]: { [string]: Track? } } = {}
|
||||
local tcps = 24
|
||||
@@ -353,7 +336,7 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu
|
||||
if vals and #times > 0 then
|
||||
local stride = comps
|
||||
local per = #vals // (comps * #times)
|
||||
-- CUBICSPLINE: in-tangent, value, out-tangent per key: keep the value
|
||||
-- CUBICSPLINE: in-tangent, value, out-tangent per key
|
||||
local off = if ch.interpolation == "CUBICSPLINE" and per == 3 then comps else 0
|
||||
local mult = if ch.interpolation == "CUBICSPLINE" and per == 3 then 3 else 1
|
||||
local tv = {}
|
||||
@@ -373,7 +356,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu
|
||||
end
|
||||
end
|
||||
|
||||
-- header
|
||||
table.insert(out, "#usda 1.0")
|
||||
table.insert(out, "(")
|
||||
line(1, "defaultPrim = " .. quote(rootName))
|
||||
@@ -397,7 +379,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu
|
||||
matPath[i] = looksPath .. "/" .. matNames(mat.name, "material_" .. i)
|
||||
end
|
||||
|
||||
-- xform ops of a node (+ its animation)
|
||||
local function xform(depth: number, ni: number, n: Types.Node)
|
||||
local tr: { [string]: Track? }? = tracks[ni]
|
||||
local order: { string } = {}
|
||||
@@ -418,7 +399,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu
|
||||
local t, r, s = n.translation, n.rotation, n.scale
|
||||
if n.matrix and #n.matrix == 16 then
|
||||
if tr then
|
||||
-- animated: start from the matrix's TRS
|
||||
local m = n.matrix
|
||||
local sx = math.sqrt(m[1] ^ 2 + m[2] ^ 2 + m[3] ^ 2)
|
||||
local sy = math.sqrt(m[5] ^ 2 + m[6] ^ 2 + m[7] ^ 2)
|
||||
@@ -476,7 +456,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu
|
||||
if doubleSided then
|
||||
line(depth, "uniform bool doubleSided = 1")
|
||||
end
|
||||
-- extent
|
||||
local mn, mx = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
|
||||
for i = 0, #m.points // 3 - 1 do
|
||||
for c = 1, 3 do
|
||||
@@ -634,7 +613,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu
|
||||
lightBody(depth + 1, lig :: Types.Light)
|
||||
end
|
||||
local childNames = namer()
|
||||
-- a camera / light that did not take the node's prim
|
||||
if cam and kind ~= "Camera" then
|
||||
table.insert(out, "")
|
||||
line(depth + 1, "def Camera " .. quote(childNames(cam.name, "camera")))
|
||||
@@ -678,7 +656,6 @@ function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: nu
|
||||
return table.concat(out, "\n"), notes
|
||||
end
|
||||
|
||||
-- the Looks scope: materials as UsdPreviewSurface networks
|
||||
function Write._looks(out: { string }, depth: number, scene: Types.Scene, matPath: { [number]: string }, texFile: { [number]: string }, line: (number, string) -> ())
|
||||
local mats = scene.materials or {}
|
||||
if #mats == 0 then
|
||||
@@ -695,7 +672,6 @@ function Write._looks(out: { string }, depth: number, scene: Types.Scene, matPat
|
||||
line(depth + 1, "{")
|
||||
local d = depth + 2
|
||||
line(d, "token outputs:surface.connect = <" .. path .. "/PreviewSurface.outputs:surface>")
|
||||
-- texture nodes (one per distinct ref)
|
||||
type TexNode = { name: string, ref: Types.TextureRef, color: boolean }
|
||||
local texNodes: { TexNode } = {}
|
||||
local function texNode(ref: Types.TextureRef?, color: boolean): string?
|
||||
@@ -768,7 +744,6 @@ function Write._looks(out: { string }, depth: number, scene: Types.Scene, matPat
|
||||
end
|
||||
line(e, "token outputs:surface")
|
||||
line(d, "}")
|
||||
-- primvar readers per texCoord set, transforms, textures
|
||||
local readers: { [number]: boolean } = {}
|
||||
for _, tn in texNodes do
|
||||
local tc = (tn.ref.transform and tn.ref.transform.texCoord) or tn.ref.texCoord or 0
|
||||
|
||||
@@ -1,20 +1,8 @@
|
||||
--!strict
|
||||
-- model/usda: USD ASCII layers (.usda, .usd in text form) and USDZ packages holding them. New code, from the Sdf text
|
||||
-- format and the UsdGeom / UsdShade / UsdLux schema documentation (OpenUSD 26.x); checked against OpenUSD's own
|
||||
-- reader / writer (pxr) and Blender's USD exporter.
|
||||
-- Reads: stage metadata (upAxis -> meta.up, metersPerUnit -> meta.unit, defaultPrim, timeCodesPerSecond, start /
|
||||
-- endTimeCode), the prim tree (def / over; class skipped; selected variants merged), xform op stacks (translate, scale,
|
||||
-- rotateX/Y/Z, rotateXYZ ... rotateZYX, orient, transform, !invert!, !resetXformStack!) with time samples -> one
|
||||
-- animation of TRS channels, Mesh (faceVertexCounts / Indices, holes, leftHanded orientation, normals, every
|
||||
-- texCoord2f primvar -> TEXCOORD_n with st first, displayColor / displayOpacity, all interpolations, :indices,
|
||||
-- GeomSubsets -> one primitive each), UsdPreviewSurface materials with UsdUVTexture / UsdPrimvarReader_float2 /
|
||||
-- UsdTransform2d, material:binding (inherited, per subset), Camera, DistantLight / SphereLight (+ ShapingAPI cone ->
|
||||
-- spot) / RectLight / DiskLight (-> spot lights over a hemisphere). Textures stay encoded: bytes from opts.files /
|
||||
-- opts.resolve (or the USDZ package) + mime, else just the uri (F.model.loadTextures decodes them).
|
||||
-- Writes .usda (see model/usda/Write): Xform / Mesh / GeomSubset / Material / Shader / Camera / lights, time samples.
|
||||
-- Not supported: USDC binary crate files (.usdc, and .usd / USDZ holding one: UNSUPPORTED), composition arcs
|
||||
-- (references, payloads, inherits, specializes, subLayers: ignored and listed in meta.source.unsupported), UsdSkel
|
||||
-- skinning, blend shapes, curves / points / NURBS prims, point instancers, MaterialX shading networks, writing USDZ.
|
||||
-- model/usda: USD ASCII layers (.usda, text .usd) and USDZ packages of them, from the Sdf text format and the UsdGeom /
|
||||
-- UsdShade / UsdLux docs (OpenUSD 26.x), checked against pxr and Blender's exporter. Not supported: USDC crate files,
|
||||
-- composition arcs (listed in meta.source.unsupported), UsdSkel, blend shapes, curves / points / NURBS, instancers,
|
||||
-- MaterialX, writing USDZ.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -37,18 +25,18 @@ local Usda = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
triangulate: boolean?, -- fan-triangulate faces (default true); false keeps "polygons" primitives
|
||||
flipV: boolean?, -- TEXCOORD_n.v = 1 - v (default true: glTF's top-left origin)
|
||||
resolve: ((uri: string) -> any)?, -- texture files next to the layer (the api sets it for paths)
|
||||
files: { [string]: any }?, -- or: the files by asset path
|
||||
maxVertices: number?, -- refuse meshes with more points / face corners (default 2^25)
|
||||
maxBytes: number?, -- refuse numeric arrays over this many bytes (default 2^30)
|
||||
triangulate: boolean?, -- default true
|
||||
flipV: boolean?, -- default true
|
||||
resolve: ((uri: string) -> any)?,
|
||||
files: { [string]: any }?,
|
||||
maxVertices: number?, -- default 2^25
|
||||
maxBytes: number?, -- default 2^30
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
files: { [string]: any }?, -- receives embedded texture bytes as <name>_<n>.<ext>
|
||||
name: string?, -- the destination's file name (names the texture files)
|
||||
format: string?, -- "usdz" -> UNSUPPORTED (set by the api from the destination's extension)
|
||||
upAxis: string?, -- "Y" / "Z" (default: from scene.meta.up)
|
||||
files: { [string]: any }?, -- as <name>_<n>.<ext>
|
||||
name: string?,
|
||||
format: string?, -- "usdz" -> UNSUPPORTED
|
||||
upAxis: string?, -- default: from scene.meta.up
|
||||
metersPerUnit: number?, -- default scene.meta.unit or 1
|
||||
}
|
||||
|
||||
@@ -57,7 +45,6 @@ local function isUsdz(r: Bytes.Reader): boolean
|
||||
if r:peek(4) ~= "PK\3\4" then
|
||||
return false
|
||||
end
|
||||
-- the first entry is the root layer
|
||||
local lo, hi = r:peekU8(26), r:peekU8(27)
|
||||
if lo < 0 or hi < 0 then
|
||||
return false
|
||||
@@ -74,7 +61,7 @@ function Usda.sniff(r: Bytes.Reader): number
|
||||
return 1
|
||||
end
|
||||
if head == "PXR-USDC" then
|
||||
return 0.9 -- recognised so the error says USDC is not supported
|
||||
return 0.9 -- USDC magic, so the error says it is unsupported
|
||||
end
|
||||
if isUsdz(r) then
|
||||
return 0.95
|
||||
@@ -209,7 +196,6 @@ function Usda.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Er
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- parse(text) -> the raw layer (prim specs, properties, metadata) | nil, Err: for prims the Scene does not cover
|
||||
function Usda.parse(text: string): (Parse.Layer?, Err.Err?)
|
||||
local layer, msg, at = Parse.layer(text)
|
||||
if not layer then
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- model/vox/Grid: the voxel loops of the VOX format: XYZI records into a dense grid, and a dense grid back into XYZI
|
||||
-- records. Callers check every range first; nothing here throws.
|
||||
-- model/vox/Grid: XYZI records to and from a dense grid (cell x + sx * (y + sy * z); index 0 = empty). Never throws.
|
||||
local Grid = {}
|
||||
|
||||
local readu8, writeu8 = buffer.readu8, buffer.writeu8
|
||||
|
||||
-- fill(dst, sx, sy, sz, src, off, n) -> skipped: writes n XYZI records (x, y, z, index bytes at src[off ..]) into the
|
||||
-- dense grid dst (cell x + sx * (y + sy * z)); records outside the grid or with index 0 are skipped and counted.
|
||||
-- The caller guarantees off + 4 * n <= buffer.len(src) and buffer.len(dst) >= sx * sy * sz.
|
||||
function Grid.fill(dst: buffer, sx: number, sy: number, sz: number, src: buffer, off: number, n: number): number
|
||||
local skipped = 0
|
||||
local sxy = sx * sy
|
||||
@@ -24,7 +20,6 @@ function Grid.fill(dst: buffer, sx: number, sy: number, sz: number, src: buffer,
|
||||
return skipped
|
||||
end
|
||||
|
||||
-- count(data, cells) -> the number of non-empty cells in data[0, cells)
|
||||
function Grid.count(data: buffer, cells: number): number
|
||||
local n = 0
|
||||
for k = 0, cells - 1 do
|
||||
@@ -35,8 +30,7 @@ function Grid.count(data: buffer, cells: number): number
|
||||
return n
|
||||
end
|
||||
|
||||
-- write(dst, at, data, sx, sy, sz) -> the offset after the last record: one XYZI record per non-empty cell (x fastest).
|
||||
-- The caller sizes dst with count() (sx, sy, sz <= 256).
|
||||
-- one XYZI record per non-empty cell (x fastest; sx, sy, sz <= 256)
|
||||
function Grid.write(dst: buffer, at: number, data: buffer, sx: number, sy: number, sz: number): number
|
||||
local p = at
|
||||
local k = 0
|
||||
|
||||
@@ -1,17 +1,7 @@
|
||||
--!strict
|
||||
-- model/vox: MagicaVoxel .vox, from ephtracy's spec (voxel-model/MagicaVoxel-file-format-vox.txt and -vox-extension.txt)
|
||||
-- and the files MagicaVoxel 0.99.x saves (version 150 and 200).
|
||||
-- Reads every chunk: SIZE + XYZI models, RGBA palette (the default palette when absent), the scene graph (nTRN / nGRP /
|
||||
-- nSHP, with names, hidden flags, layers, 90-degree rotations, translations and animation frames), MATL materials,
|
||||
-- LAYR layers, rOBJ render settings, rCAM cameras, NOTE palette notes, IMAP, META; PACK and MATT (old) and unknown
|
||||
-- chunks are kept raw and written back.
|
||||
-- decode -> a Scene (meta.up = "z", units = voxels): scene.voxels holds the grids (Types.Voxels: size, one byte per
|
||||
-- cell, palette, materials), each scene node from an nTRN, its nGRP children as node.children, its nSHP model as
|
||||
-- node.voxels. Vox.decodeVoxels gives the grids alone. Meshes: ops/MeshOps.meshVoxels(scene) (greedy meshing; a shape is
|
||||
-- centred on its node like MagicaVoxel does: cell (x, y, z) spans x - floor(sx / 2) .. + 1). A format never meshes.
|
||||
-- encode <- a Scene with voxels (or one Types.Voxels): models, the node tree back as nTRN / nGRP / nSHP (rotations must
|
||||
-- be multiples of 90 degrees; translations are rounded to whole voxels), palette, materials and every meta chunk.
|
||||
-- Not supported: models over 256 cells per axis on write (MagicaVoxel's limit); node scale other than mirroring.
|
||||
-- model/vox: MagicaVoxel .vox (ephtracy's MagicaVoxel-file-format-vox.txt / -vox-extension.txt, versions 150 and 200).
|
||||
-- Supports: every chunk (unknown, PACK, MATT kept raw); shapes centred on their node like MagicaVoxel. Not supported:
|
||||
-- writing models over 256 cells per axis (MagicaVoxel's limit); node scale other than mirroring.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -31,10 +21,10 @@ local Vox = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
maxCells: number?, -- refuse files whose grids hold more cells in total (default 2^27)
|
||||
maxCells: number?, -- default 2^27
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
version: number?, -- the file version (default 200, what MagicaVoxel 0.99.7 writes; 150 is the older one)
|
||||
version: number?, -- default 200 (MagicaVoxel 0.99.7); 150 is the older one
|
||||
}
|
||||
type Dict = { [string]: string }
|
||||
type GraphNode = {
|
||||
@@ -123,7 +113,7 @@ local function ints(s: string?): { number }
|
||||
return out
|
||||
end
|
||||
|
||||
-- _r byte -> the row-major 3 x 3 rotation (rows of { column, sign }) | nil when the byte is not a permutation
|
||||
-- _r byte -> the row-major 3 x 3 rotation (rows of { column, sign }); nil when not a permutation
|
||||
local function rotation(b: number): { { number } }?
|
||||
local i0, i1 = bit32.band(b, 3), bit32.band(bit32.rshift(b, 2), 3)
|
||||
if i0 > 2 or i1 > 2 or i0 == i1 then
|
||||
@@ -136,7 +126,6 @@ local function rotation(b: number): { { number } }?
|
||||
return { { i0, sign(4) }, { i1, sign(5) }, { i2, sign(6) } }
|
||||
end
|
||||
|
||||
-- the node transform of a frame dictionary (_r, _t)
|
||||
local function applyFrame(node: Types.Node, f: Dict)
|
||||
local t = ints(f._t)
|
||||
local tx, ty, tz = t[1] or 0, t[2] or 0, t[3] or 0
|
||||
@@ -185,7 +174,7 @@ local function applyFrame(node: Types.Node, f: Dict)
|
||||
end
|
||||
end
|
||||
|
||||
-- MATL dictionary -> VoxelMaterial: _type -> type (without "_"), the other keys without their "_", numbers as numbers
|
||||
-- MATL: _type -> type, the other keys without their "_", numbers as numbers
|
||||
local function material(d: Dict): Types.VoxelMaterial
|
||||
local m: Types.VoxelMaterial = { type = "diffuse" }
|
||||
for k, v in d do
|
||||
@@ -413,7 +402,6 @@ local function parse(r: Bytes.Reader, opts: DecodeOptions?): (Parsed?, Err.Err?)
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- the Scene node tree from the nTRN at id (nil for a missing / looping / non-transform node)
|
||||
local function build(scene: Types.Scene, graph: { [number]: GraphNode }, id: number, depth: number, visiting: { [number]: boolean }, nmodels: number): number?
|
||||
local t = graph[id]
|
||||
if not t or t.kind ~= "nTRN" or depth > MAX_DEPTH or visiting[id] then
|
||||
@@ -453,7 +441,6 @@ local function build(scene: Types.Scene, graph: { [number]: GraphNode }, id: num
|
||||
return index
|
||||
end
|
||||
|
||||
-- decodeVoxels(r, opts?) -> { Voxels } (every model, in file order) | nil, Err
|
||||
function Vox.decodeVoxels(r: Bytes.Reader, opts: DecodeOptions?): ({ Types.Voxels }?, Err.Err?)
|
||||
local p, err = parse(r, opts)
|
||||
if not p then
|
||||
@@ -546,7 +533,6 @@ local function wdict(w: Bytes.Writer, d: { [string]: any }?)
|
||||
end
|
||||
end
|
||||
|
||||
-- a node's transform as a frame dictionary (_r, _t) | nil, message
|
||||
local function frameOf(node: Types.Node, base: Dict?): (Dict?, string?)
|
||||
local f: Dict = {}
|
||||
if base then
|
||||
@@ -646,7 +632,6 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
wdict(w, meta.info)
|
||||
end)
|
||||
end
|
||||
-- models
|
||||
for _, v in models do
|
||||
local sx, sy, sz = v.size[1], v.size[2], v.size[3]
|
||||
chunk("SIZE", function()
|
||||
@@ -662,7 +647,6 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
w.pos = at + count * 4
|
||||
end)
|
||||
end
|
||||
-- the scene graph
|
||||
local records: { Record } = {}
|
||||
local nextId = 0
|
||||
local function alloc(): number
|
||||
@@ -796,7 +780,6 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
end
|
||||
end)
|
||||
end
|
||||
-- layers
|
||||
if type(meta.layers) == "table" then
|
||||
for _, l in meta.layers do
|
||||
chunk("LAYR", function()
|
||||
@@ -814,7 +797,6 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
end)
|
||||
end
|
||||
end
|
||||
-- palette
|
||||
local pal = models[1].palette or DEFAULT_PALETTE
|
||||
chunk("RGBA", function()
|
||||
for i = 1, 256 do
|
||||
@@ -836,7 +818,6 @@ function Vox.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
end
|
||||
end)
|
||||
end
|
||||
-- materials
|
||||
local mats = models[1].materials
|
||||
if type(mats) == "table" then
|
||||
local ids = {}
|
||||
|
||||
@@ -1,20 +1,7 @@
|
||||
--!strict
|
||||
-- model/vrml: VRML97 (ISO/IEC 14772-1, `#VRML V2.0 utf8`) .wrl files, plain or gzipped (.wrz), a thin format over
|
||||
-- codecs/model/Vrml (the scene-graph engine model/x3d shares). New code.
|
||||
-- Reads: the scene graph (Transform with center / scaleOrientation, Group, Anchor, Billboard, Collision, Switch, LOD,
|
||||
-- Inline through opts.files / opts.resolve), DEF / USE (shared meshes and materials), PROTO instances (expanded) and
|
||||
-- EXTERNPROTO, Shape / Appearance / Material / ImageTexture / PixelTexture / TextureTransform, IndexedFaceSet (coord,
|
||||
-- normal, color, texCoord with their own indices, per-vertex / per-face normals and colours, ccw, solid -> doubleSided),
|
||||
-- IndexedLineSet, PointSet, ElevationGrid, Extrusion, the primitives Box / Sphere / Cone / Cylinder tessellated
|
||||
-- (opts.segments), Viewpoint -> cameras, DirectionalLight / PointLight / SpotLight -> lights, TimeSensor ->
|
||||
-- Position- / OrientationInterpolator -> Transform ROUTEs -> animations, WorldInfo -> meta.source.title / info. Polygons
|
||||
-- are fan-triangulated unless opts.triangulate = false; texture t is flipped to glTF's top-left origin unless
|
||||
-- opts.flipV = false. meta.up = "y", meta.unit = 1 (metres).
|
||||
-- Writes: VRML97 text (see codecs/model/Vrml/Write: Transforms from the node tree, Shapes with IndexedFaceSet /
|
||||
-- IndexedLineSet / PointSet, Appearance / Material / ImageTexture (texture files into opts.files), Viewpoints, lights,
|
||||
-- TimeSensor + interpolator animations; DEF / USE for shared meshes and materials).
|
||||
-- Not supported: VRML 1.0, Text / FontStyle (no glyphs), Script behaviour, sensors, sound, NURBS, morph targets and
|
||||
-- skins on write (the rest pose is written).
|
||||
-- model/vrml: VRML97 (ISO/IEC 14772-1, `#VRML V2.0 utf8`) .wrl / .wrz over codecs/model/Vrml; new code. Supports:
|
||||
-- the scene graph, DEF / USE, PROTO / EXTERNPROTO, the geometry nodes, Viewpoints, lights, interpolator ROUTEs as
|
||||
-- animations. Not supported: VRML 1.0, Text, Script, sensors, sound, NURBS; morph targets and skins on write.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -34,16 +21,16 @@ local Wrl = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
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)
|
||||
triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives
|
||||
flipV: boolean?, -- texture t -> 1 - t (default true: glTF's convention)
|
||||
segments: number?, -- Sphere / Cone / Cylinder segments around (default 32)
|
||||
files: { [string]: any }?, -- by uri or base name
|
||||
resolve: ((uri: string) -> any)?,
|
||||
triangulate: boolean?, -- default true
|
||||
flipV: boolean?, -- default true
|
||||
segments: number?, -- default 32
|
||||
maxVertices: number?, -- per geometry (default 2^24)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
files: { [string]: any }?, -- receives the texture images (else url = texture.uri)
|
||||
name: string?, -- the destination's file name (names the image files)
|
||||
files: { [string]: any }?, -- else url = texture.uri
|
||||
name: string?,
|
||||
flipV: boolean?, -- default true (the inverse of decode)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
--!strict
|
||||
-- model/x/Build: the .x object tree (model/x/Parse) -> Types.Scene, from the DirectX templates' layouts. Direct3D is
|
||||
-- left-handed (y up, row vectors): z is negated (positions, normals, matrices as S * M * S, keys) and the winding
|
||||
-- reversed, so the scene is glTF's right-handed y-up with counter-clockwise front faces (assimp does the same).
|
||||
-- A FrameTransformMatrix (row-vector order) is already column-major for column vectors. Texture coordinates keep
|
||||
-- Direct3D's top-left origin (glTF's). Plain code (the caller wraps it in pcall).
|
||||
-- model/x/Build: the .x object tree to a Scene, from the DirectX template layouts. Direct3D is left-handed (y up, row
|
||||
-- vectors): z is negated (matrices as S * M * S) and windings reversed, as assimp does; UVs stay top-left.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Mat4 = require("@rosetta/codecs/model/Mat4")
|
||||
local Rig = require("@rosetta/codecs/model/Rig")
|
||||
@@ -16,7 +13,6 @@ local writef32, writeu32 = buffer.writef32, buffer.writeu32
|
||||
|
||||
type Node = Parse.Node
|
||||
|
||||
-- a cursor over an object's flattened values
|
||||
type Vals = { v: { any }, i: number }
|
||||
local function num(c: Vals): number
|
||||
local x = c.v[c.i]
|
||||
@@ -34,7 +30,6 @@ local function str(c: Vals): string
|
||||
end
|
||||
return x
|
||||
end
|
||||
-- a non-negative integer (an index)
|
||||
local function index(c: Vals, limit: number): number
|
||||
local n = num(c)
|
||||
if n < 0 or n ~= math.floor(n) or n > limit then
|
||||
@@ -43,8 +38,6 @@ local function index(c: Vals, limit: number): number
|
||||
return n
|
||||
end
|
||||
|
||||
-- a count of items that follow (each takes at least one value: a count past the data is refused before anything
|
||||
-- is allocated for it)
|
||||
local function count(c: Vals, limit: number): number
|
||||
local n = num(c)
|
||||
if n < 0 or n ~= math.floor(n) or n > limit then
|
||||
@@ -56,7 +49,7 @@ local function count(c: Vals, limit: number): number
|
||||
return n
|
||||
end
|
||||
|
||||
-- z mirror of a column-major matrix: S * M * S, S = diag(1, 1, -1)
|
||||
-- S * M * S, S = diag(1, 1, -1)
|
||||
local function mirror(m: { number }): { number }
|
||||
local o = table.clone(m)
|
||||
for _, k in { 3, 7, 9, 10, 12, 15 } do
|
||||
@@ -140,7 +133,6 @@ local function accessorF32(values: { number }, comps: number): Types.Accessor
|
||||
return Scene.accessor(b, "f32", comps, n // comps)
|
||||
end
|
||||
|
||||
-- mesh(ctx, meshNode) -> mesh index, the skin's bones (nil: not skinned) | nil (no faces)
|
||||
local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?)
|
||||
local scene = ctx.scene
|
||||
local c: Vals = { v = m.vals, i = 1 }
|
||||
@@ -168,7 +160,6 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?)
|
||||
end
|
||||
faces[f] = face
|
||||
end
|
||||
-- the optional data objects
|
||||
local normals: { number }? = nil
|
||||
local nfaces: { { number } }? = nil
|
||||
local uvSets: { { number } } = {}
|
||||
@@ -243,12 +234,11 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?)
|
||||
table.insert(bones, { name = name, verts = verts, weights = weights, matrix = matrix(kc) })
|
||||
end
|
||||
end
|
||||
-- material per face (a single index applies to every face)
|
||||
-- a single index applies to every face
|
||||
local function matOf(f: number): number
|
||||
local mi = if #faceMat == 1 then faceMat[1] else faceMat[f]
|
||||
return if mi then mi + 1 else 1
|
||||
end
|
||||
-- unique vertices per (position, normal index)
|
||||
local key: { [number]: number } = {}
|
||||
local srcPos: { number } = {}
|
||||
local srcNrm: { number } = {}
|
||||
@@ -264,7 +254,7 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?)
|
||||
local nface = nfaces and nfaces[f]
|
||||
local vs = table.create(n) :: { number }
|
||||
for k = 1, n do
|
||||
local src = if k == 1 then 1 else n - k + 2 -- winding reversed, first corner kept
|
||||
local src = if k == 1 then 1 else n - k + 2
|
||||
local p = face[src]
|
||||
local q = if nface and nface[src] and nface[src] < nNormals then nface[src] else -1
|
||||
local kk = p * (nNormals + 1) + q + 1
|
||||
@@ -301,7 +291,6 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?)
|
||||
return nil, nil
|
||||
end
|
||||
table.sort(order)
|
||||
-- shared vertex attributes (one vertex buffer for every primitive of the mesh)
|
||||
local nout = #srcPos
|
||||
local P = table.create(nout * 3) :: { number }
|
||||
for v = 1, nout do
|
||||
@@ -415,7 +404,6 @@ local function frame(ctx: Ctx, f: Node, parent: number?, triangulate: boolean, d
|
||||
node.matrix = m
|
||||
end
|
||||
elseif k.type == "Mesh" then
|
||||
-- the first mesh on the frame's node, more as child nodes
|
||||
local mi, bones = mesh(ctx, k, triangulate)
|
||||
if mi then
|
||||
local holder = ni
|
||||
@@ -536,7 +524,6 @@ function Build.scene(root: Node, opts: { triangulate: boolean?, maxVertices: num
|
||||
end
|
||||
end
|
||||
end
|
||||
-- skins: bone names -> frames
|
||||
for _, ps in ctx.pendingSkins do
|
||||
local joints: { number } = {}
|
||||
local ibm = buffer.create(#ps.bones * 64)
|
||||
|
||||
@@ -1,21 +1,13 @@
|
||||
--!strict
|
||||
-- model/x/Parse: DirectX .x data -> a generic object tree, for the text ("txt ") and binary ("bin ") encodings (the
|
||||
-- caller inflates "tzip" / "bzip" first). From Microsoft's "DirectX File Format Specification" (text grammar and
|
||||
-- binary tokens), checked against what assimp's XFileParser accepts (no code taken).
|
||||
-- Every data object becomes { type, name?, vals, kids }: vals holds its members flattened in order (numbers and
|
||||
-- strings; separators, array brackets and member structure are not kept: model/x/Build knows each template's layout),
|
||||
-- kids its nested data objects and references ({ name } -> { type = "@ref", name }). Templates are skipped.
|
||||
-- Text: ; and , separators, // and # comments, quoted strings, <guid>s, Blender's "1.#IND00" / "1.#QNAN0" (read as 0).
|
||||
-- Binary: NAME, STRING, INTEGER, GUID, INTEGER_LIST, FLOAT_LIST (32- or 64-bit floats) and the punctuation and
|
||||
-- keyword tokens. Plain code (the caller wraps it in pcall); bad data returns nil, message.
|
||||
-- model/x/Parse: .x text and binary tokens to { type, name?, vals, kids } objects, from Microsoft's "DirectX File
|
||||
-- Format Specification", checked against assimp's XFileParser (no code taken). Templates are skipped; Blender's
|
||||
-- "1.#IND00" / "1.#QNAN0" read as 0. Never throws: bad data returns nil, message.
|
||||
local Parse = {}
|
||||
|
||||
export type Node = { type: string, name: string?, vals: { any }, kids: { Node } }
|
||||
|
||||
local readu16, readu32, readf32, readf64, readstring = buffer.readu16, buffer.readu32, buffer.readf32, buffer.readf64, buffer.readstring
|
||||
|
||||
-- a token source: next() -> kind, value. kinds: "{", "}", "id", "num", "str", "guid", "list" (value: { number }),
|
||||
-- "punct", "eof"; err holds a message after a bad token
|
||||
type Lexer = { next: () -> (string, any), err: string? }
|
||||
|
||||
local KEYWORDS: { [number]: string } = {
|
||||
@@ -50,7 +42,7 @@ local function textLexer(s: string): Lexer
|
||||
return "eof", nil
|
||||
end
|
||||
local c = string.byte(s, p)
|
||||
if c == 47 and string.byte(s, p + 1) == 47 or c == 35 then -- // or #
|
||||
if c == 47 and string.byte(s, p + 1) == 47 or c == 35 then
|
||||
local nl = string.find(s, "[\r\n]", p)
|
||||
p = if nl then nl + 1 else n + 1
|
||||
else
|
||||
@@ -199,7 +191,6 @@ local function tree(lex: Lexer, maxValues: number): (Node?, string?)
|
||||
return if q then q[1] else "eof"
|
||||
end
|
||||
local budget = maxValues
|
||||
-- skips a template / unknown block whose "{" was just read
|
||||
local function skipBlock(): string?
|
||||
local depth = 1
|
||||
while depth > 0 do
|
||||
@@ -215,7 +206,6 @@ local function tree(lex: Lexer, maxValues: number): (Node?, string?)
|
||||
return nil
|
||||
end
|
||||
local body: (Node, number) -> string?
|
||||
-- an object whose type token was read: [name] { ... }
|
||||
local function object(parent: Node, typ: string, depth: number): string?
|
||||
local name: string? = nil
|
||||
local kind, v = take()
|
||||
@@ -297,7 +287,6 @@ local function tree(lex: Lexer, maxValues: number): (Node?, string?)
|
||||
return root, nil
|
||||
end
|
||||
|
||||
-- parse(b, from, limit, binary, floatSize, maxValues) -> root Node | nil, message
|
||||
function Parse.tree(b: buffer, from: number, limit: number, binary: boolean, floatSize: number, maxValues: number): (Node?, string?)
|
||||
local lex = if binary then binaryLexer(b, from, limit, floatSize) else textLexer(readstring(b, from, limit - from))
|
||||
return tree(lex, maxValues)
|
||||
|
||||
@@ -1,20 +1,7 @@
|
||||
--!strict
|
||||
-- model/x: DirectX .x files, read only: text ("txt "), binary ("bin ") and MSZIP-compressed ("tzip" / "bzip",
|
||||
-- through codecs/compress/Deflate), 32- and 64-bit floats. New code from Microsoft's DirectX file format
|
||||
-- specification and the standard templates, checked against assimp's X importer and test models.
|
||||
-- Reads the Frame hierarchy (FrameTransformMatrix -> TRS, or a matrix when it has shear), meshes (one primitive per
|
||||
-- material of MeshMaterialList; MeshNormals with their own face indices (vertices split per position / normal
|
||||
-- pair), MeshTextureCoords -> TEXCOORD_n, MeshVertexColors -> COLOR_n), materials (inline or referenced global
|
||||
-- Material objects: face colour -> baseColor, power -> roughness, emissive; TextureFilename -> baseColorTexture,
|
||||
-- NormalmapFilename -> normalTexture, as uris: F.model.loadTextures reads them; the Phong values in extras.x),
|
||||
-- SkinWeights (-> a skin per mesh: joints = the named frames, offset matrices as inverse bind matrices, the four
|
||||
-- strongest influences as JOINTS_0 / WEIGHTS_0) and AnimationSet / Animation / AnimationKey (rotation, scale,
|
||||
-- position and matrix keys -> channels, AnimTicksPerSecond (default 4800) -> seconds). Templates are skipped.
|
||||
-- Direct3D's left-handed space becomes glTF's right-handed y up (z negated, winding reversed), as assimp does.
|
||||
-- Polygons are fan-triangulated unless opts.triangulate = false. Faces of fewer than 3 corners are skipped (counted in
|
||||
-- meta.source.skippedFaces).
|
||||
-- Not supported: DeclData / FVFData vertex streams, progressive meshes, patch meshes, 3- and 2-corner key
|
||||
-- interpolation options (keys are linear).
|
||||
-- model/x: DirectX .x, read only: text ("txt "), binary ("bin "), MSZIP ("tzip" / "bzip"), 32- and 64-bit floats; from
|
||||
-- Microsoft's DirectX file format spec and templates, checked against assimp. AnimTicksPerSecond defaults to 4800. Not
|
||||
-- supported: DeclData / FVFData, progressive and patch meshes, non-linear key interpolation.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -36,10 +23,10 @@ local X = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives
|
||||
maxVertices: number?, -- refuse more vertices / face corners per mesh (default 2^25)
|
||||
maxValues: number?, -- refuse files with more numbers than this (default 2^27)
|
||||
maxBytes: number?, -- refuse compressed files inflating to more (default 2^30)
|
||||
triangulate: boolean?, -- default true
|
||||
maxVertices: number?, -- default 2^25
|
||||
maxValues: number?, -- default 2^27
|
||||
maxBytes: number?, -- default 2^30
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
@@ -55,8 +42,7 @@ end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- MSZIP: a u32 total size (with the 16-byte file header), then blocks (u16 uncompressed size, u16 compressed size,
|
||||
-- "CK" + deflate data). The blocks are walked here; codecs/compress/Deflate.mszip inflates the chain (each block may
|
||||
-- refer back into the previous block's output).
|
||||
-- "CK" + deflate data); each block may refer back into the previous block's output.
|
||||
local function mszip(b: buffer, p: number, limit: number, maxBytes: number): (buffer?, Err.Err?)
|
||||
if p + 4 > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "no MSZIP header", p)
|
||||
|
||||
@@ -1,16 +1,7 @@
|
||||
--!strict
|
||||
-- model/x3d: X3D (ISO/IEC 19775-1) in its XML encoding (.x3d, ISO/IEC 19776-1) and its classic VRML encoding (.x3dv,
|
||||
-- 19776-2), plain or gzipped (.x3dz / .x3dvz), a thin format over codecs/model/Vrml (the engine model/vrml shares).
|
||||
-- New code.
|
||||
-- Reads: everything model/vrml reads, plus the X3D nodes: IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet,
|
||||
-- TriangleFanSet, IndexedTriangleStripSet, TriangleStripSet, IndexedQuadSet, QuadSet, LineSet, ColorRGBA,
|
||||
-- CoordinateDouble, MultiTexture / MultiTextureCoordinate (the first), PhysicalMaterial / UnlitMaterial /
|
||||
-- TwoSidedMaterial, OrthoViewpoint, CAD groups; XML ProtoDeclare / ProtoInstance, ROUTE elements, containerField;
|
||||
-- head meta, components and UNIT length (-> meta.unit).
|
||||
-- Writes: X3D 3.3 XML (default) or the classic encoding (opts.encoding = "x3dv"; the api passes the extension), the
|
||||
-- same scene graph as model/vrml writes (ColorRGBA for colours with alpha, OrthoViewpoint for orthographic cameras).
|
||||
-- Not supported: the binary encodings (.x3db Fast Infoset / EXI: UNSUPPORTED), X3D JSON, Text, NURBS, shaders,
|
||||
-- H-Anim skinning, scripts.
|
||||
-- model/x3d: X3D (ISO/IEC 19775-1) XML (.x3d, 19776-1) and classic VRML (.x3dv, 19776-2) encodings, plain or gzipped,
|
||||
-- over codecs/model/Vrml; new code. Supports: the model/vrml set plus the X3D geometry and material nodes.
|
||||
-- Not supported: binary encodings (.x3db Fast Infoset / EXI), X3D JSON, Text, NURBS, shaders, H-Anim skinning, scripts.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
@@ -30,18 +21,18 @@ local X3d = {
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
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)
|
||||
triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives
|
||||
flipV: boolean?, -- texture t -> 1 - t (default true: glTF's convention)
|
||||
segments: number?, -- Sphere / Cone / Cylinder segments around (default 32)
|
||||
files: { [string]: any }?, -- by uri or base name
|
||||
resolve: ((uri: string) -> any)?,
|
||||
triangulate: boolean?, -- default true
|
||||
flipV: boolean?, -- default true
|
||||
segments: number?, -- default 32
|
||||
maxVertices: number?, -- per geometry (default 2^24)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
encoding: ("xml" | "x3dv")?, -- default "xml"
|
||||
format: string?, -- the api passes the extension: "x3dv" / "x3dvz" select the classic encoding
|
||||
files: { [string]: any }?, -- receives the texture images (else url = texture.uri)
|
||||
name: string?, -- the destination's file name (names the image files)
|
||||
format: string?, -- "x3dv" / "x3dvz" select the classic encoding
|
||||
files: { [string]: any }?, -- else url = texture.uri
|
||||
name: string?,
|
||||
flipV: boolean?, -- default true (the inverse of decode)
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user