diff --git a/docs/FORMATS.md b/docs/FORMATS.md index f3846c1..83ae02a 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -45,6 +45,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | +| model | vrml | .wrl .wrz .vrml | yes | yes | materials: true, polygons: true, animation: true, cameras: true, lights: true, lines: true, points: true | `tests/model/vrml.luau` | +| model | x3d | .x3d .x3dv .x3dz .x3dvz .x3db | yes | yes | materials: true, polygons: true, animation: true, cameras: true, lights: true, lines: true, points: true, xml: true, classic: true | `tests/model/x3d.luau` | | cad | step | .step .stp .p21 | yes | yes | complexEntities: true, sections: true, brep: "plugin", tessellate: "plugin" | `tests/cad/step.luau` | | font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.luau` | | font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` | @@ -127,6 +129,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - **model** - codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks + - codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML, - **text** - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index a414daf..be89cbf 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -494,6 +494,30 @@ local list: { Entry } = { return require("@formats/model/vox") end, }, + { + name = "vrml", + category = "model", + path = "model/vrml", + extensions = { "wrl", "wrz", "vrml" }, + mime = { "model/vrml", "x-world/x-vrml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true }, + load = function() + return require("@formats/model/vrml") + end, + }, + { + name = "x3d", + category = "model", + path = "model/x3d", + extensions = { "x3d", "x3dv", "x3dz", "x3dvz", "x3db" }, + mime = { "model/x3d+xml", "model/x3d-vrml", "model/x3d+fastinfoset" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true, xml = true, classic = true }, + load = function() + return require("@formats/model/x3d") + end, + }, { name = "step", category = "cad", diff --git a/src/Formats/codecs/model/Vrml/Build.luau b/src/Formats/codecs/model/Vrml/Build.luau new file mode 100644 index 0000000..8ddc054 --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Build.luau @@ -0,0 +1,590 @@ +--!strict +-- codecs/model/Vrml/Build: the VRML97 / X3D node graph (codecs/model/Vrml/Parse, codecs/model/Vrml/Xml) to a Scene. +-- Written from the specifications; no third-party code. Grouping nodes (Group, Transform with center / scaleOrientation, +-- Anchor, Billboard, Collision, StaticGroup, Switch whichChoice, LOD first level, CAD and HAnim groups, Inline through +-- the fetch callback) become nodes; a Transform is one TRS node (translation T + C, rotation R * SR, scale S) and, when +-- it has a center or scale orientation, an inner node (rotation SR^-1, translation SR^-1 * -C) holding the children. +-- Shapes become meshes (shared by USE), Appearance / Material / PhysicalMaterial / UnlitMaterial / TwoSidedMaterial +-- materials (Phong terms in material.extras.vrml; solid FALSE -> doubleSided), ImageTexture / MovieTexture +-- (uri, data through fetch, repeatS / repeatT), PixelTexture (texture.image), TextureTransform (KHR transform: +-- translation / scale / rotation; the center in extras); Viewpoint / OrthoViewpoint -> cameras, DirectionalLight / +-- PointLight / SpotLight -> lights; ROUTEs from a TimeSensor through Position- / OrientationInterpolators to a +-- Transform's translation / rotation / scale -> animations (key times x cycleInterval). Other nodes are counted in +-- meta.source.skipped. Never throws: bad data returns nil, message. +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Fields = require("@formats/codecs/model/Vrml/Fields") +local Geometry = require("@formats/codecs/model/Vrml/Geometry") + +local Build = {} + +local S = Types.Scene +local nums, num, vec, bool, str, strs, node, nodes = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.str, Fields.strs, Fields.node, Fields.nodes +local deg = math.deg + +export type Options = Geometry.Options & { + fetch: ((uri: string) -> buffer?)?, -- reads textures and Inline files + load: ((data: buffer) -> (any, string?))?, -- an Inline file's bytes -> its graph + format: string?, -- meta.source.format + maxInline: number?, -- Inline nesting (default 8) +} + +local GROUP = { Group = true, Anchor = true, Billboard = true, Collision = true, StaticGroup = true, CADAssembly = true, CADLayer = true, LayerSet = true, Layer = true, HAnimSegment = true, HAnimSite = true, LOD = true, Switch = true } +local TRANSFORM = { Transform = true, CADPart = true, HAnimHumanoid = true, HAnimJoint = true } +local CHILDREN = { "children", "skeleton", "segments", "sites", "layers" } +-- nodes with nothing to show (not counted as skipped) +local QUIET = { + WorldInfo = true, NavigationInfo = true, Background = true, TextureBackground = true, Fog = true, TimeSensor = true, + PositionInterpolator = true, OrientationInterpolator = true, ScalarInterpolator = true, ColorInterpolator = true, + CoordinateInterpolator = true, NormalInterpolator = true, TouchSensor = true, ProximitySensor = true, + VisibilitySensor = true, PlaneSensor = true, CylinderSensor = true, SphereSensor = true, Script = true, Sound = true, + AudioClip = true, MetadataString = true, MetadataFloat = true, MetadataInteger = true, MetadataDouble = true, + MetadataSet = true, MetadataBoolean = true, BooleanFilter = true, BooleanToggle = true, BooleanTrigger = true, + BooleanSequencer = true, IntegerSequencer = true, IntegerTrigger = true, TimeTrigger = true, KeySensor = true, + StringSensor = true, LoadSensor = true, +} +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", gif = "image/gif", bmp = "image/bmp", webp = "image/webp", ktx2 = "image/ktx2", dds = "image/vnd-ms.dds", tga = "image/x-tga" } + +local function quat(r: { number }): { number } + return Mat4.axisAngle(r[1], r[2], r[3], deg(r[4])) +end +local function qmul(a: { number }, b: { number }): { number } + return { + a[4] * b[1] + a[1] * b[4] + a[2] * b[3] - a[3] * b[2], + a[4] * b[2] - a[1] * b[3] + a[2] * b[4] + a[3] * b[1], + a[4] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[4], + a[4] * b[4] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3], + } +end +local function qrot(q: { number }, v: { number }): { number } + local m = Mat4.fromQuat(q) + local x, y, z = Mat4.point(m, v[1], v[2], v[3]) + return { x, y, z } +end +local function isZero(v: { number }): boolean + return v[1] == 0 and v[2] == 0 and v[3] == 0 +end +local function isIdentityQ(q: { number }): boolean + return q[1] == 0 and q[2] == 0 and q[3] == 0 +end +-- the rotation taking unit vector a onto b +local function between(a: { number }, b: { number }): { number } + local l = math.sqrt(b[1] * b[1] + b[2] * b[2] + b[3] * b[3]) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + local bx, by, bz = b[1] / l, b[2] / l, b[3] / l + local d = a[1] * bx + a[2] * by + a[3] * bz + if d < -0.999999 then + -- opposite: half a turn about any perpendicular axis + return if math.abs(a[1]) < 0.9 then { 0, a[3], -a[2], 0 } else { -a[3], 0, a[1], 0 } + end + local cx, cy, cz = a[2] * bz - a[3] * by, a[3] * bx - a[1] * bz, a[1] * by - a[2] * bx + local w = 1 + d + local n = math.sqrt(cx * cx + cy * cy + cz * cz + w * w) + return { cx / n, cy / n, cz / n, w / n } +end + +type Ctx = { + scene: Types.Scene, + opts: Options, + meshes: { [any]: any }, + materials: { [any]: any }, + textures: { [any]: number }, + instances: { [any]: { { node: number, center: { number }, so: { number } } } }, + skipped: { [string]: number }, + depth: number, + inline: number, + failure: string?, +} + +local function addNode(ctx: Ctx, n: Types.Node, parent: number?): number + local nodes_ = ctx.scene.nodes + table.insert(nodes_, n) + local i = #nodes_ + if parent then + table.insert(nodes_[parent].children, i) + else + table.insert(ctx.scene.roots, i) + end + return i +end + +-- ------------------------------------------------------------------------------------------------ materials +local function texture(ctx: Ctx, t: any): number? + if not t then + return nil + end + if t.type == "MultiTexture" then + return texture(ctx, nodes(t, "texture")[1]) + end + local cached = ctx.textures[t] + if cached then + return cached + end + local tex: Types.Texture = { name = t.def } + if t.type == "ImageTexture" or t.type == "MovieTexture" then + local urls = strs(t, "url") + local fetch = ctx.opts.fetch + for _, u in urls do + local clean = string.match(u, "^([^#?]*)") or u + if not tex.uri and not string.find(clean, "^%a[%w+.-]*://") then + tex.uri = clean + end + local data = fetch and fetch(clean) + if data then + tex.uri, tex.data = clean, data + break + end + end + tex.uri = tex.uri or urls[1] + local ext = tex.uri and string.match(tex.uri, "%.(%w+)$") + tex.mime = if ext then MIME[string.lower(ext)] else nil + elseif t.type == "PixelTexture" then + -- SFImage: width height components pixels (0xRRGGBBAA style integers, MSB first) + local v = nums(t, "image") or {} + local w, h, c = math.floor(v[1] or 0), math.floor(v[2] or 0), math.floor(v[3] or 0) + if w > 0 and h > 0 and c >= 1 and c <= 4 and w * h <= 2 ^ 24 and #v >= 3 + w * h then + local img = Types.Image.new(w, h) + for i = 0, w * h - 1 do + local px = math.floor(v[4 + i]) % 2 ^ (8 * c) + local b = table.create(4, 0) + for k = c, 1, -1 do + b[k] = px % 256 + px //= 256 + end + local r, g, bl, a + if c <= 2 then + r, g, bl, a = b[1], b[1], b[1], if c == 2 then b[2] else 255 + else + r, g, bl, a = b[1], b[2], b[3], if c == 4 then b[4] else 255 + end + -- the image's first row is the bottom one + local row = h - 1 - i // w + local o = (row * w + i % w) * 4 + buffer.writeu8(img.pixels, o, r) + buffer.writeu8(img.pixels, o + 1, g) + buffer.writeu8(img.pixels, o + 2, bl) + buffer.writeu8(img.pixels, o + 3, a) + end + tex.image = img + end + else + ctx.skipped[t.type] = (ctx.skipped[t.type] or 0) + 1 + return nil + end + local rs, rt = bool(t, "repeatS", true), bool(t, "repeatT", true) + if not rs or not rt then + tex.sampler = { wrapS = if rs then "repeat" else "clamp", wrapT = if rt then "repeat" else "clamp" } + end + table.insert(ctx.scene.textures, tex) + ctx.textures[t] = #ctx.scene.textures + return #ctx.scene.textures +end + +local function textureRef(ctx: Ctx, t: any, xf: any): Types.TextureRef? + local i = texture(ctx, t) + if not i then + return nil + end + local ref: Types.TextureRef = { texture = i } + if xf and xf.type == "TextureTransform" then + local tr, sc, rot = vec(xf, "translation", { 0, 0 }), vec(xf, "scale", { 1, 1 }), num(xf, "rotation", 0) + if tr[1] ~= 0 or tr[2] ~= 0 or sc[1] ~= 1 or sc[2] ~= 1 or rot ~= 0 then + ref.transform = { offset = tr, scale = sc, rotation = rot } + end + end + return ref +end + +local function material(ctx: Ctx, app: any, solid: boolean): number? + if not app and solid then + return nil + end + local key = app or "default" + local cache = ctx.materials[key] + if type(cache) ~= "table" then + cache = {} + ctx.materials[key] = cache + end + local hit = (cache :: any)[solid] + if hit then + return hit + end + local m = S.material(app and app.def) + m.metallic = 0 + local x: { [string]: any } = {} + local mat = app and node(app, "material") + local tex = app and node(app, "texture") + local xf = app and node(app, "textureTransform") + if mat and mat.type == "TwoSidedMaterial" then + m.doubleSided = true + x.twoSided = true + end + if mat and (mat.type == "Material" or mat.type == "TwoSidedMaterial") then + local d, e, sp = vec(mat, "diffuseColor", { 0.8, 0.8, 0.8 }), vec(mat, "emissiveColor", { 0, 0, 0 }), vec(mat, "specularColor", { 0, 0, 0 }) + local sh, tr, amb = num(mat, "shininess", 0.2), num(mat, "transparency", 0), num(mat, "ambientIntensity", 0.2) + m.name = mat.def or m.name + m.baseColor = { d[1], d[2], d[3], 1 - tr } + m.emissive = e + m.roughness = math.clamp(math.sqrt(2 / (math.max(sh, 0) * 128 + 2)), 0, 1) + x.diffuseColor, x.emissiveColor, x.specularColor, x.shininess, x.transparency, x.ambientIntensity = d, e, sp, sh, tr, amb + if tr > 0 then + m.alphaMode = "blend" + end + -- X3D 4 texture fields + local dt = node(mat, "diffuseTexture") + if dt then + m.baseColorTexture = textureRef(ctx, dt, nil) + end + local nt = node(mat, "normalTexture") + if nt then + m.normalTexture = textureRef(ctx, nt, nil) + end + elseif mat and mat.type == "PhysicalMaterial" then + local b, e = vec(mat, "baseColor", { 1, 1, 1 }), vec(mat, "emissiveColor", { 0, 0, 0 }) + local tr = num(mat, "transparency", 0) + m.name = mat.def or m.name + m.baseColor = { b[1], b[2], b[3], 1 - tr } + m.emissive, m.metallic, m.roughness = e, num(mat, "metallic", 1), num(mat, "roughness", 1) + if tr > 0 then + m.alphaMode = "blend" + end + local slots: { [string]: string } = { baseTexture = "baseColorTexture", metallicRoughnessTexture = "metallicRoughnessTexture", normalTexture = "normalTexture", occlusionTexture = "occlusionTexture", emissiveTexture = "emissiveTexture" } + for field, slot in slots do + local t = node(mat, field) + if t then + (m :: any)[slot] = textureRef(ctx, t, nil) + end + end + elseif mat and mat.type == "UnlitMaterial" then + local e = vec(mat, "emissiveColor", { 1, 1, 1 }) + m.name = mat.def or m.name + m.baseColor = { e[1], e[2], e[3], 1 - num(mat, "transparency", 0) } + m.extensions = { KHR_materials_unlit = {} } + else + -- no material: unlit white (the specifications' default) + m.extensions = { KHR_materials_unlit = {} } + end + if tex and not m.baseColorTexture then + m.baseColorTexture = textureRef(ctx, tex, xf) + if m.baseColorTexture and xf then + x.textureCenter = vec(xf, "center", { 0, 0 }) + end + end + if not solid then + m.doubleSided = true + end + m.extras = { vrml = x } + table.insert(ctx.scene.materials, m) + local idx = #ctx.scene.materials + ;(cache :: any)[solid] = idx + return idx +end + +-- ------------------------------------------------------------------------------------------------ nodes +local walk: (ctx: Ctx, n: any, parent: number?) -> () + +local function shape(ctx: Ctx, n: any, parent: number?) + local geo = node(n, "geometry") + if not geo then + return + end + local mi = ctx.meshes[n] + if mi == nil then + local prim, solidOrErr = Geometry.primitive(geo, ctx.opts) + if not prim then + if solidOrErr then + ctx.failure = ctx.failure or solidOrErr + else + ctx.skipped[geo.type] = (ctx.skipped[geo.type] or 0) + 1 + end + ctx.meshes[n] = false :: any + return + end + local count = if prim.indices then prim.indices.count else prim.attributes.POSITION.count + if count == 0 then + -- nothing to draw (no valid faces / points) + ctx.meshes[n] = false + return + end + prim.material = material(ctx, node(n, "appearance"), solidOrErr == true) + table.insert(ctx.scene.meshes, { name = n.def or geo.def, primitives = { prim } }) + mi = #ctx.scene.meshes + ctx.meshes[n] = mi + elseif mi == false then + return + end + addNode(ctx, { name = n.def, children = {}, mesh = mi }, parent) +end + +local function viewpoint(ctx: Ctx, n: any, parent: number?) + local cam: any + if n.type == "OrthoViewpoint" then + local f = vec(n, "fieldOfView", { -1, -1, 1, 1 }) + cam = { type = "orthographic", xmag = (f[3] - f[1]) / 2, ymag = (f[4] - f[2]) / 2, znear = 0.125, zfar = 1e4 } + else + cam = { type = "perspective", yfov = num(n, "fieldOfView", 0.785398), znear = 0.125 } + end + cam.name = n.def or str(n, "description") + table.insert(ctx.scene.cameras, cam) + local o = vec(n, "orientation", { 0, 0, 1, 0 }) + local nd: Types.Node = { name = cam.name, children = {}, camera = #ctx.scene.cameras, translation = vec(n, "position", { 0, 0, 10 }) } + if o[4] ~= 0 then + nd.rotation = quat(o) + end + addNode(ctx, nd, parent) +end + +local function light(ctx: Ctx, n: any, parent: number?) + local t = n.type + local l: Types.Light = { name = n.def, type = "point", color = vec(n, "color", { 1, 1, 1 }), intensity = num(n, "intensity", 1) } + local nd: Types.Node = { name = n.def, children = {} } + local x: { [string]: any } = { ambientIntensity = num(n, "ambientIntensity", 0), on = bool(n, "on", true), global = bool(n, "global", t == "DirectionalLight") } + if t == "DirectionalLight" then + l.type = "directional" + nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 })) + else + nd.translation = vec(n, "location", { 0, 0, 0 }) + l.range = num(n, "radius", 100) + x.attenuation = vec(n, "attenuation", { 1, 0, 0 }) + if t == "SpotLight" then + l.type = "spot" + nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 })) + local cut = num(n, "cutOffAngle", 0.785398) + l.outerCone = cut + l.innerCone = math.min(num(n, "beamWidth", 1.570796), cut) + end + end + ;(l :: any).extras = { vrml = x } + table.insert(ctx.scene.lights, l) + nd.light = #ctx.scene.lights + addNode(ctx, nd, parent) +end + +local function children(ctx: Ctx, n: any, parent: number?) + if n.type == "Switch" then + local which = math.floor(num(n, "whichChoice", -1)) + local list = nodes(n, "choice") + if #list == 0 then + list = nodes(n, "children") + end + local c = list[which + 1] + if which >= 0 and c then + walk(ctx, c, parent) + end + return + elseif n.type == "LOD" then + local list = nodes(n, "level") + if #list == 0 then + list = nodes(n, "children") + end + if list[1] then + walk(ctx, list[1], parent) + end + return + end + for _, f in CHILDREN do + for _, c in nodes(n, f) do + walk(ctx, c, parent) + end + end +end + +local function transform(ctx: Ctx, n: any, parent: number?) + local t, c = vec(n, "translation", { 0, 0, 0 }), vec(n, "center", { 0, 0, 0 }) + local r, s, so = vec(n, "rotation", { 0, 0, 1, 0 }), vec(n, "scale", { 1, 1, 1 }), vec(n, "scaleOrientation", { 0, 0, 1, 0 }) + local qr, qs = quat(r), quat(so) + local outer: Types.Node = { name = n.def, children = {} } + local tt = { t[1] + c[1], t[2] + c[2], t[3] + c[3] } + if not isZero(tt) then + outer.translation = tt + end + local q = if isIdentityQ(qs) then qr else qmul(qr, qs) + if not isIdentityQ(q) then + outer.rotation = q + end + if s[1] ~= 1 or s[2] ~= 1 or s[3] ~= 1 then + outer.scale = s + end + local oi = addNode(ctx, outer, parent) + local list = ctx.instances[n] + if not list then + list = {} + ctx.instances[n] = list + end + table.insert(list, { node = oi, center = c, so = qs }) + local holder = oi + if not isZero(c) or not isIdentityQ(qs) then + local inv = { -qs[1], -qs[2], -qs[3], qs[4] } + local inner: Types.Node = { children = {}, translation = qrot(inv, { -c[1], -c[2], -c[3] }) } + if not isIdentityQ(inv) then + inner.rotation = inv + end + holder = addNode(ctx, inner, oi) + end + children(ctx, n, holder) +end + +local function inline(ctx: Ctx, n: any, parent: number?) + local fetch, load = ctx.opts.fetch, ctx.opts.load + if not fetch or not load or ctx.inline >= (ctx.opts.maxInline or 8) or not bool(n, "load", true) then + ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1 + return + end + for _, u in strs(n, "url") do + local data = fetch(string.match(u, "^([^#?]*)") or u) + if data then + local g = load(data) + if g then + local holder = addNode(ctx, { name = n.def, children = {} }, parent) + ctx.inline += 1 + for _, root in g.roots do + walk(ctx, root, holder) + end + ctx.inline -= 1 + return + end + end + end + ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1 +end + +function walk(ctx: Ctx, n: any, parent: number?) + if ctx.failure or type(n) ~= "table" then + return + end + ctx.depth += 1 + if ctx.depth > 200 then + ctx.failure = "limit: scene nested deeper than 200" + return + end + local t = n.type + if TRANSFORM[t] then + transform(ctx, n, parent) + elseif GROUP[t] then + local holder = parent + if n.def or parent == nil then + holder = addNode(ctx, { name = n.def, children = {} }, parent) + end + children(ctx, n, holder) + elseif t == "Shape" then + shape(ctx, n, parent) + elseif t == "CADFace" then + for _, s in nodes(n, "shape") do + walk(ctx, s, parent) + end + elseif t == "Viewpoint" or t == "OrthoViewpoint" then + viewpoint(ctx, n, parent) + elseif t == "DirectionalLight" or t == "PointLight" or t == "SpotLight" then + light(ctx, n, parent) + elseif t == "Inline" then + inline(ctx, n, parent) + elseif t == "WorldInfo" then + local src = ctx.scene.meta.source :: any + src.title = str(n, "title") + local info = strs(n, "info") + src.info = if #info > 0 then info else nil + elseif not QUIET[t] then + ctx.skipped[t] = (ctx.skipped[t] or 0) + 1 + end + ctx.depth -= 1 +end + +-- ------------------------------------------------------------------------------------------------ animation +local TARGET = { set_translation = "translation", translation = "translation", set_rotation = "rotation", rotation = "rotation", set_scale = "scale", scale = "scale" } + +local function animations(ctx: Ctx, routes: { any }) + -- interpolator -> its TimeSensor + local timer: { [any]: any } = {} + for _, r in routes do + if (r.toField == "set_fraction" or r.toField == "fraction") and r.from.type == "TimeSensor" then + timer[r.to] = r.from + end + end + local anims: { [any]: Types.Animation } = {} + local order: { any } = {} + for _, r in routes do + local path = TARGET[r.toField] + local it = r.from + local inst = ctx.instances[r.to] + if not (path and inst and (it.type == "PositionInterpolator" or it.type == "OrientationInterpolator")) then + continue + end + if (path == "rotation") ~= (it.type == "OrientationInterpolator") then + continue + end + local key: { number }, kv: { number } = nums(it, "key") or {}, nums(it, "keyValue") or {} + local comps = if path == "rotation" then 4 else 3 + local n = math.min(#key, #kv // comps) + if n == 0 then + continue + end + local ts = timer[it] + local cycle = if ts then num(ts, "cycleInterval", 1) else 1 + local input = S.accessor(nil, "f32", 1, n) + for i = 0, n - 1 do + buffer.writef32(input.data, i * 4, key[i + 1] * cycle) + end + local id = ts or "routes" + local anim = anims[id] + if not anim then + anim = { name = if ts then ts.def else nil, channels = {} } + anims[id] = anim + table.insert(order, id) + end + for _, at in inst do + local out = S.accessor(nil, "f32", if path == "rotation" then 4 else 3, n) + local prev: { number }? = nil + for i = 0, n - 1 do + local v: { number } + if path == "rotation" then + v = quat({ kv[i * 4 + 1], kv[i * 4 + 2], kv[i * 4 + 3], kv[i * 4 + 4] }) + if not isIdentityQ(at.so) then + v = qmul(v, at.so) + end + if prev and prev[1] * v[1] + prev[2] * v[2] + prev[3] * v[3] + prev[4] * v[4] < 0 then + v = { -v[1], -v[2], -v[3], -v[4] } + end + prev = v + elseif path == "translation" then + v = { kv[i * 3 + 1] + at.center[1], kv[i * 3 + 2] + at.center[2], kv[i * 3 + 3] + at.center[3] } + else + v = { kv[i * 3 + 1], kv[i * 3 + 2], kv[i * 3 + 3] } + end + for c = 1, #v do + buffer.writef32(out.data, (i * #v + c - 1) * 4, v[c]) + end + end + table.insert(anim.channels, { node = at.node, path = path :: any, input = input, output = out, interpolation = "LINEAR" :: any }) + end + end + for _, id in order do + table.insert(ctx.scene.animations, anims[id]) + end +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(graph: any, opts: Options): (Types.Scene?, string?) + local scene = S.new() + scene.meta.up = "y" + local units = graph.units or {} + scene.meta.unit = if units.length and units.length.factor > 0 then units.length.factor else 1 + local h = graph.header or {} + local skipped: { [string]: number } = {} + scene.meta.source = { + format = opts.format or "vrml", version = h.version, encoding = h.encoding, profile = h.profile, x3d = h.x3d, + xml = h.xml, meta = graph.meta, components = graph.components, skipped = skipped, + } + local ctx: Ctx = { scene = scene, opts = opts, meshes = {}, materials = {}, textures = {}, instances = {}, skipped = skipped, depth = 0, inline = 0, failure = nil } + for _, n in graph.roots do + walk(ctx, n, nil) + end + if ctx.failure then + return nil, ctx.failure + end + animations(ctx, graph.routes or {}) + return scene, nil +end + +return Build diff --git a/src/Formats/codecs/model/Vrml/Fields.luau b/src/Formats/codecs/model/Vrml/Fields.luau new file mode 100644 index 0000000..c9ec1e2 --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Fields.luau @@ -0,0 +1,168 @@ +--!strict +-- codecs/model/Vrml/Fields: typed reads of node fields for codecs/model/Vrml/Build and Geometry. A classic-encoding +-- value is a flat array (numbers, strings, booleans, nodes); an X3D XML value is the raw attribute string, parsed here +-- on first use (numbers split on blanks / commas, MFString as quoted strings or one unquoted string, booleans +-- true / false). Never throws. +local Fields = {} + +local gmatch, find, sub, byte = string.gmatch, string.find, string.sub, string.byte + +-- quoted strings of an MFString attribute ("a" "b \"c\""), or the text itself when it is not quoted +local function mfString(s: string): { string } + local out = {} + local p = find(s, "[^%s,]") + if not p or byte(s, p) ~= 34 then + return if p then { (string.match(s, "^%s*(.-)%s*$") :: string) } else {} + end + local n = #s + while p and p <= n do + if byte(s, p) ~= 34 then + break + end + local q = p + 1 + local parts = {} + while true do + local e = find(s, '["\\]', q) + if not e then + table.insert(parts, sub(s, q)) + table.insert(out, table.concat(parts)) + return out + end + table.insert(parts, sub(s, q, e - 1)) + if byte(s, e) == 92 then + table.insert(parts, sub(s, e + 1, e + 1)) + q = e + 2 + else + p = e + 1 + break + end + end + table.insert(out, table.concat(parts)) + p = find(s, "[^%s,]", p) + end + return out +end + +-- nums(node, name) -> the numbers of a field (booleans as 1 / 0), or nil when absent +function Fields.nums(node: any, name: string): { number }? + local v = node.fields[name] + if v == nil then + return nil + end + if type(v) == "string" then + local out = {} + for w in gmatch(v, "[^%s,]+") do + local x = tonumber(w) + if x then + table.insert(out, x) + elseif w == "true" or w == "TRUE" then + table.insert(out, 1) + elseif w == "false" or w == "FALSE" then + table.insert(out, 0) + end + end + node.fields[name] = out + return out + end + if type(v) ~= "table" then + return nil + end + local ok = true + for _, x in v do + if type(x) ~= "number" then + ok = false + break + end + end + if ok then + return v + end + local out = {} + for _, x in v do + if type(x) == "number" then + table.insert(out, x) + elseif type(x) == "boolean" then + table.insert(out, if x then 1 else 0) + end + end + return out +end + +function Fields.num(node: any, name: string, default: number): number + local v = Fields.nums(node, name) + return if v and type(v[1]) == "number" then v[1] else default +end + +-- vec(node, name, default) -> the first #default numbers of a field (the default when the field is shorter) +function Fields.vec(node: any, name: string, default: { number }): { number } + local v = Fields.nums(node, name) + if not v or #v < #default then + return default + end + local out: { number } = {} + for i = 1, #default do + out[i] = v[i] + end + return out +end + +function Fields.bool(node: any, name: string, default: boolean): boolean + local v = node.fields[name] + if type(v) == "string" then + local w = string.lower(string.match(v, "^%s*(%S*)") :: string) + return if w == "true" then true elseif w == "false" then false else default + end + if type(v) == "table" and type(v[1]) == "boolean" then + return v[1] + end + return default +end + +function Fields.strs(node: any, name: string): { string } + local v = node.fields[name] + if type(v) == "string" then + local out = mfString(v) + node.fields[name] = out + return out + end + local out = {} + if type(v) == "table" then + for _, x in v do + if type(x) == "string" then + table.insert(out, x) + end + end + end + return out +end + +function Fields.str(node: any, name: string, default: string?): string? + local v = node.fields[name] + if type(v) == "string" then + return v + end + if type(v) == "table" and type(v[1]) == "string" then + return v[1] + end + return default +end + +-- nodes(node, name) -> the nodes of an SFNode / MFNode field +function Fields.nodes(node: any, name: string): { any } + local v = node.fields[name] + local out = {} + if type(v) == "table" then + for _, x in v do + if type(x) == "table" and type(x.type) == "string" then + table.insert(out, x) + end + end + end + return out +end + +function Fields.node(node: any, name: string): any + return Fields.nodes(node, name)[1] +end + +return Fields diff --git a/src/Formats/codecs/model/Vrml/Geometry.luau b/src/Formats/codecs/model/Vrml/Geometry.luau new file mode 100644 index 0000000..306562d --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Geometry.luau @@ -0,0 +1,770 @@ +--!strict +-- codecs/model/Vrml/Geometry: VRML97 / X3D geometry nodes to Scene primitives. Written from the specifications; no +-- third-party code. IndexedFaceSet (coord / normal / color / texCoord with their own indices, per-vertex or per-face +-- normals and colours, ccw, convex polygons fan-triangulated or kept as "polygons"), the X3D triangle / quad sets +-- (IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, TriangleFanSet, IndexedTriangleStripSet, +-- TriangleStripSet, IndexedQuadSet, QuadSet), ElevationGrid, Extrusion (spine-aligned cross sections, scale, +-- orientation, caps), IndexedLineSet / LineSet ("lines"), PointSet ("points"), and the primitives Box, Sphere, Cone, +-- Cylinder tessellated with normals and the specification's texture mapping. Texture coordinates get t flipped to +-- glTF's top-left origin unless flipV = false. Never throws: returns nil, message for bad data. +local Types = require("@formats/Types") +local Fields = require("@formats/codecs/model/Vrml/Fields") + +local Geometry = {} + +local S = Types.Scene +local nums, num, vec, bool, node = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.node +local sqrt, sin, cos, pi = math.sqrt, math.sin, math.cos, math.pi + +export type Options = { flipV: boolean?, triangulate: boolean?, segments: number?, maxVertices: number? } + +local function f32(list: { number }, comps: number, count: number): Types.Accessor + local a = S.accessor(nil, "f32", comps, count) + local d = a.data + for i = 1, math.min(#list, comps * count) do + buffer.writef32(d, (i - 1) * 4, list[i]) + end + return a +end + +local function u32(list: { number }): Types.Accessor + local a = S.accessor(nil, "u32", 1, #list) + for i, v in list do + buffer.writeu32(a.data, (i - 1) * 4, v) + end + return a +end + +-- the colour node's values and component count (Color: 3, ColorRGBA: 4) +local function colors(n: any): ({ number }?, number) + local c = node(n, "color") + if not c then + return nil, 3 + end + local comps = if c.type == "ColorRGBA" then 4 else 3 + return nums(c, "color") or {}, comps +end + +local function points(n: any, field: string, sub: string): { number }? + local c = node(n, field) + return if c then nums(c, sub) or {} else nil +end + +-- ------------------------------------------------------------------------------------------------ polygon meshes +-- Mesh input: faces as corner lists of coordinate indices (0-based) plus, per attribute, a per-corner index list (nil: +-- the coordinate index) or per-face indices. +type PolyIn = { + P: { number }, -- coordinates, 3 per point + corners: { number }, -- coordinate index per corner, face after face + sizes: { number }, -- corners per face + N: { number }?, nIdx: { number }?, nFace: boolean?, -- normals; per-corner or per-face indices (nil: identity) + C: { number }?, cComps: number?, cIdx: { number }?, cFace: boolean?, + T: { number }?, tIdx: { number }?, + ccw: boolean, +} + +local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?) + local P, corners, sizes = m.P, m.corners, m.sizes + local np = #P // 3 + local N, C, T = m.N, m.C, m.T + local cc = m.cComps or 3 + -- the attribute index of corner k (1-based) in face f (1-based) + local function idx(list: { number }?, perFace: boolean?, f: number, k: number, c: number): number + if perFace then + return if list and #list > 0 then (list[f] or 0) else f - 1 + end + return if list and #list > 0 then (list[k] or c) else c + end + local simple = (N == nil or (not m.nFace and (m.nIdx == nil or #m.nIdx == 0))) and (C == nil or (not m.cFace and (m.cIdx == nil or #m.cIdx == 0))) and (T == nil or m.tIdx == nil or #m.tIdx == 0) + local vkey: { [string]: number } = {} + local vsrc: { { number } } = {} -- per output vertex: coord, normal, colour, texcoord indices + local out: { number } = {} + local outSizes: { number } = {} + local k = 0 + for f, size in sizes do + local face: { number } = {} + local valid = size >= 3 + for q = 1, size do + k += 1 + local c = corners[k] + if c == nil or c < 0 or c >= np then + valid = false + end + face[q] = k + end + if valid then + local verts: { number } = {} + for q, kk in face do + local c = corners[kk] + if simple then + verts[q] = c + else + local ni = if N then idx(m.nIdx, m.nFace, f, kk, c) else -1 + local ci = if C then idx(m.cIdx, m.cFace, f, kk, c) else -1 + local ti = if T then idx(m.tIdx, false, f, kk, c) else -1 + local key = c .. ":" .. ni .. ":" .. ci .. ":" .. ti + local v = vkey[key] + if not v then + v = #vsrc + vsrc[v + 1] = { c, ni, ci, ti } + vkey[key] = v + if v >= maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + end + verts[q] = v + end + end + if not m.ccw then + for a = 2, (size + 1) // 2 do + verts[a], verts[size + 2 - a] = verts[size + 2 - a], verts[a] + end + end + if o.triangulate == false then + table.insert(outSizes, size) + for _, v in verts do + table.insert(out, v) + end + else + for a = 2, size - 1 do + table.insert(out, verts[1]) + table.insert(out, verts[a]) + table.insert(out, verts[a + 1]) + end + end + end + end + local nv = if simple then np else #vsrc + if nv > maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + local flipV = o.flipV ~= false + local pos = S.accessor(nil, "f32", 3, nv) + local nrm = if N then S.accessor(nil, "f32", 3, nv) else nil + local col = if C then S.accessor(nil, "f32", cc, nv) else nil + local tex = if T then S.accessor(nil, "f32", 2, nv) else nil + local wf = buffer.writef32 + for v = 0, nv - 1 do + local s = if simple then nil else vsrc[v + 1] + local c = if s then s[1] else v + for q = 0, 2 do + wf(pos.data, (v * 3 + q) * 4, P[c * 3 + q + 1] or 0) + end + if nrm and N then + local ni = if s then s[2] else v + for q = 0, 2 do + wf(nrm.data, (v * 3 + q) * 4, N[ni * 3 + q + 1] or 0) + end + end + if col and C then + local ci = if s then s[3] else v + for q = 0, cc - 1 do + wf(col.data, (v * cc + q) * 4, C[ci * cc + q + 1] or 1) + end + end + if tex and T then + local ti = if s then s[4] else v + local tt = T[ti * 2 + 2] or 0 + wf(tex.data, v * 8, T[ti * 2 + 1] or 0) + wf(tex.data, v * 8 + 4, if flipV then 1 - tt else tt) + end + end + local attrs: { [string]: Types.Accessor } = { POSITION = pos } + attrs.NORMAL, attrs.COLOR_0, attrs.TEXCOORD_0 = nrm, col, tex + local prim: Types.Primitive = { attributes = attrs, indices = u32(out), mode = "triangles" } + if o.triangulate == false then + prim.mode = "polygons" + prim.faces = u32(outSizes) + end + return prim +end + +-- split a -1 separated index list into corners + sizes +local function split(list: { number }): ({ number }, { number }) + local corners, sizes = {}, {} + local run = 0 + for _, x in list do + if x < 0 then + if run > 0 then + table.insert(sizes, run) + end + run = 0 + else + table.insert(corners, x) + run += 1 + end + end + if run > 0 then + table.insert(sizes, run) + end + return corners, sizes +end + +-- per-face index lists keep only the entries of faces (the -1 separators of per-corner lists match the corners) +local function cornerList(list: { number }?): { number }? + if not list or #list == 0 then + return nil + end + local out = {} + for _, x in list do + if x >= 0 then + table.insert(out, x) + end + end + return out +end + +local function faceSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local P = points(n, "coord", "point") or {} + local corners, sizes = split(nums(n, "coordIndex") or {}) + local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true) + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m: PolyIn = { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not nPer, nIdx = if nPer then cornerList(nums(n, "normalIndex")) else nums(n, "normalIndex"), + C = C, cComps = cc, cFace = not cPer, cIdx = if cPer then cornerList(nums(n, "colorIndex")) else nums(n, "colorIndex"), + T = if tc and tc.type ~= "TextureCoordinateGenerator" then (nums(if tc.type == "MultiTextureCoordinate" then (node(tc, "texCoord") or tc) else tc, "point") or {}) else nil, + tIdx = cornerList(nums(n, "texCoordIndex")), + } + return polyMesh(m, o, maxV) +end + +-- the X3D triangle / quad sets: faces from index (or vertex order) and fan / strip counts +local function triSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local t = n.type + local P = points(n, "coord", "point") or {} + local np = #P // 3 + local index = nums(n, "index") + local seq: { number } + if string.sub(t, 1, 7) == "Indexed" then + seq = index or {} + else + seq = {} + for i = 0, np - 1 do + seq[i + 1] = i + end + end + local corners, sizes = {}, {} + local function tri(a: number, b: number, c: number) + table.insert(corners, a) + table.insert(corners, b) + table.insert(corners, c) + table.insert(sizes, 3) + end + -- runs: -1 separated (indexed fans / strips) or fanCount / stripCount (plain fans / strips) + local function runs(): { { number } } + local out = {} + local counts = nums(n, if string.find(t, "Fan", 1, true) then "fanCount" else "stripCount") + if string.sub(t, 1, 7) == "Indexed" or not counts then + local cur = {} + for _, x in seq do + if x < 0 then + table.insert(out, cur) + cur = {} + else + table.insert(cur, x) + end + end + table.insert(out, cur) + else + local at = 1 + for _, c in counts do + local cur = {} + for q = 0, c - 1 do + cur[q + 1] = seq[at + q] + end + at += c + table.insert(out, cur) + end + end + return out + end + if t == "IndexedTriangleSet" or t == "TriangleSet" then + for i = 1, #seq - 2, 3 do + tri(seq[i], seq[i + 1], seq[i + 2]) + end + elseif t == "IndexedQuadSet" or t == "QuadSet" then + for i = 1, #seq - 3, 4 do + for q = 0, 3 do + table.insert(corners, seq[i + q]) + end + table.insert(sizes, 4) + end + elseif string.find(t, "Fan", 1, true) then + for _, r in runs() do + for i = 2, #r - 1 do + tri(r[1], r[i], r[i + 1]) + end + end + else + for _, r in runs() do + for i = 1, #r - 2 do + if i % 2 == 1 then + tri(r[i], r[i + 1], r[i + 2]) + else + tri(r[i + 1], r[i], r[i + 2]) + end + end + end + end + local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true) + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m: PolyIn = { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not nPer, C = C, cComps = cc, cFace = not cPer, + T = if tc and tc.type == "TextureCoordinate" then nums(tc, "point") or {} else nil, + } + return polyMesh(m, o, maxV) +end + +local function elevationGrid(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local nx, nz = math.floor(num(n, "xDimension", 0)), math.floor(num(n, "zDimension", 0)) + local dx, dz = num(n, "xSpacing", 1), num(n, "zSpacing", 1) + local h: { number } = nums(n, "height") or {} + if nx < 2 or nz < 2 then + return nil, nil + end + if nx * nz > maxV then + return nil, "limit: elevation grid of " .. nx .. " x " .. nz + end + local P: { number }, T: { number }, corners: { number }, sizes: { number } = {}, {}, {}, {} + for z = 0, nz - 1 do + for x = 0, nx - 1 do + table.insert(P, x * dx) + table.insert(P, h[z * nx + x + 1] or 0) + table.insert(P, z * dz) + table.insert(T, x / (nx - 1)) + table.insert(T, z / (nz - 1)) + end + end + for z = 0, nz - 2 do + for x = 0, nx - 2 do + local a = z * nx + x + -- counter-clockwise seen from +y: a, a + nx, a + nx + 1, a + 1 + for _, c in { a, a + nx, a + nx + 1, a + 1 } do + table.insert(corners, c) + end + table.insert(sizes, 4) + end + end + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m: PolyIn = { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not bool(n, "normalPerVertex", true), C = C, cComps = cc, + cFace = not bool(n, "colorPerVertex", true), T = if tc then nums(tc, "point") or {} else T, + } + return polyMesh(m, o, maxV) +end + +-- ------------------------------------------------------------------------------------------------ Extrusion +local function cross(a: { number }, b: { number }): { number } + return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] } +end +local function sub3(a: { number }, b: { number }): { number } + return { a[1] - b[1], a[2] - b[2], a[3] - b[3] } +end +local function norm(a: { number }): ({ number }, number) + local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3]) + return if l > 1e-12 then { a[1] / l, a[2] / l, a[3] / l } else { 0, 0, 0 }, l +end +-- rotate v about the unit axis k by angle a (Rodrigues) +local function rotate(v: { number }, k: { number }, a: number): { number } + local c, s = cos(a), sin(a) + local d = (k[1] * v[1] + k[2] * v[2] + k[3] * v[3]) * (1 - c) + local kv = cross(k, v) + return { v[1] * c + kv[1] * s + k[1] * d, v[2] * c + kv[2] * s + k[2] * d, v[3] * c + kv[3] * s + k[3] * d } +end + +local function extrusion(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local sp = nums(n, "spine") or { 0, 0, 0, 0, 1, 0 } + local cs = nums(n, "crossSection") or { 1, 1, 1, -1, -1, -1, -1, 1, 1, 1 } + local sc = nums(n, "scale") or { 1, 1 } + local ori = nums(n, "orientation") or { 0, 0, 1, 0 } + local ns, nc = #sp // 3, #cs // 2 + if ns < 2 or nc < 2 then + return nil, nil + end + if ns * nc > maxV then + return nil, "limit: extrusion of " .. ns .. " x " .. nc + end + local spine = {} + for i = 1, ns do + spine[i] = { sp[i * 3 - 2], sp[i * 3 - 1], sp[i * 3] } + end + local function same(a: { number }, b: { number }): boolean + return math.abs(a[1] - b[1]) < 1e-9 and math.abs(a[2] - b[2]) < 1e-9 and math.abs(a[3] - b[3]) < 1e-9 + end + local closedSpine = same(spine[1], spine[ns]) + local closedCs = math.abs(cs[1] - cs[nc * 2 - 1]) < 1e-9 and math.abs(cs[2] - cs[nc * 2]) < 1e-9 + -- spine-aligned cross-section planes: Y along the spine, Z from the bend, X = Y x Z + local Ys: { { number } }, Zs: { [number]: { number } } = {}, {} + for i = 1, ns do + local prev = if i > 1 then spine[i - 1] elseif closedSpine then spine[ns - 1] else nil + local nxt = if i < ns then spine[i + 1] elseif closedSpine then spine[2] else nil + local y = sub3(nxt or spine[i], prev or spine[i]) + Ys[i] = norm(y) + if prev and nxt then + local z, l = norm(cross(sub3(nxt, spine[i]), sub3(prev, spine[i]))) + Zs[i] = if l > 1e-12 then z else nil + end + end + -- missing Z: copy a neighbour's; a straight spine rotates (0, 0, 1) like (0, 1, 0) onto the spine direction + local firstZ = nil + for i = 1, ns do + if Zs[i] then + firstZ = Zs[i] + break + end + end + for i = 1, ns do + if not Ys[i] or (Ys[i][1] == 0 and Ys[i][2] == 0 and Ys[i][3] == 0) then + Ys[i] = Ys[i - 1] or { 0, 1, 0 } + end + end + for i = 1, ns do + if not Zs[i] then + if firstZ then + Zs[i] = Zs[i - 1] or firstZ + else + local y = Ys[i] + local axis, l = norm(cross({ 0, 1, 0 }, y)) + local ang = math.acos(math.clamp(y[2], -1, 1)) + Zs[i] = if l > 1e-12 then rotate({ 0, 0, 1 }, axis, ang) elseif y[2] < 0 then { 0, 0, -1 } else { 0, 0, 1 } + end + end + if i > 1 and Zs[i][1] * Zs[i - 1][1] + Zs[i][2] * Zs[i - 1][2] + Zs[i][3] * Zs[i - 1][3] < 0 then + Zs[i] = { -Zs[i][1], -Zs[i][2], -Zs[i][3] } + end + end + local nr = if closedSpine then ns - 1 else ns + local nring = if closedCs then nc - 1 else nc + local P = {} + for i = 1, nr do + local y, z = Ys[i], Zs[i] + local x = cross(y, z) + local si = if #sc >= i * 2 then i else 1 + local sx, sz = sc[si * 2 - 1] or 1, sc[si * 2] or 1 + local oi = if #ori >= i * 4 then i else 1 + local ax, ang = norm({ ori[oi * 4 - 3] or 0, ori[oi * 4 - 2] or 0, ori[oi * 4 - 1] or 1 }), ori[oi * 4] or 0 + for j = 1, nring do + local v = { cs[j * 2 - 1] * sx, 0, cs[j * 2] * sz } + if ang ~= 0 then + v = rotate(v, ax, ang) + end + local s = spine[i] + table.insert(P, s[1] + x[1] * v[1] + y[1] * v[2] + z[1] * v[3]) + table.insert(P, s[2] + x[2] * v[1] + y[2] * v[2] + z[2] * v[3]) + table.insert(P, s[3] + x[3] * v[1] + y[3] * v[2] + z[3] * v[3]) + end + end + local corners, sizes = {}, {} + local function at(i: number, j: number): number + return ((i - 1) % nr) * nring + (j - 1) % nring + end + for i = 1, ns - 1 do + for j = 1, nc - 1 do + for _, c in { at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1) } do + table.insert(corners, c) + end + table.insert(sizes, 4) + end + end + if not closedSpine then + if bool(n, "beginCap", true) then + for j = 1, nring do + table.insert(corners, at(1, j)) + end + table.insert(sizes, nring) + end + if bool(n, "endCap", true) then + for j = nring, 1, -1 do + table.insert(corners, at(ns, j)) + end + table.insert(sizes, nring) + end + end + return polyMesh({ P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true) }, o, maxV) +end + +-- ------------------------------------------------------------------------------------------------ lines, points +local function lines(n: any, maxV: number): (any, string?) + local P = points(n, "coord", "point") or {} + local np = #P // 3 + local C, cc = colors(n) + local perVertex = bool(n, "colorPerVertex", true) + local runs: { { number } } = {} + if n.type == "LineSet" then + local at = 0 + for _, c in nums(n, "vertexCount") or {} do + local r = {} + for q = 0, c - 1 do + r[q + 1] = at + q + end + at += c + table.insert(runs, r) + end + else + local corners, sizes = split(nums(n, "coordIndex") or {}) + local k = 0 + for _, s in sizes do + local r = {} + for q = 1, s do + r[q] = corners[k + q] + end + k += s + table.insert(runs, r) + end + end + local cIdx = nums(n, "colorIndex") or {} + local cList = if perVertex then cornerList(cIdx) else nil + local vkey: { [string]: number } = {} + local src: { { number } } = {} + local out: { number } = {} + local k = 0 + for li, r in runs do + local prev: number? = nil + for _, c in r do + k += 1 + if c == nil or c < 0 or c >= np then + prev = nil + continue + end + local ci = if not C then -1 elseif perVertex then (if cList then cList[k] or c else c) else (cIdx[li] or li - 1) + local key = c .. ":" .. ci + local v = vkey[key] + if not v then + v = #src + src[v + 1] = { c, ci } + vkey[key] = v + end + if prev then + table.insert(out, prev) + table.insert(out, v) + end + prev = v + end + end + if #src > maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + local pos = S.accessor(nil, "f32", 3, #src) + local col = if C then S.accessor(nil, "f32", cc, #src) else nil + for v, s in src do + for q = 0, 2 do + buffer.writef32(pos.data, ((v - 1) * 3 + q) * 4, P[s[1] * 3 + q + 1]) + end + if col and C then + for q = 0, cc - 1 do + buffer.writef32(col.data, ((v - 1) * cc + q) * 4, C[s[2] * cc + q + 1] or 1) + end + end + end + return { attributes = { POSITION = pos, COLOR_0 = col } :: any, indices = u32(out), mode = "lines" } +end + +local function pointSet(n: any, maxV: number): (any, string?) + local P = points(n, "coord", "point") or {} + local np = #P // 3 + if np > maxV then + return nil, "limit: more than " .. maxV .. " points" + end + local C, cc = colors(n) + local attrs: { [string]: Types.Accessor } = { POSITION = f32(P, 3, np) } + if C then + local col = S.accessor(nil, "f32", cc, np) + for i = 0, np * cc - 1 do + buffer.writef32(col.data, i * 4, C[i + 1] or 1) + end + attrs.COLOR_0 = col + end + return { attributes = attrs, mode = "points" } +end + +-- ------------------------------------------------------------------------------------------------ primitives +-- a primitive from flat arrays (positions, normals, uvs with the specification's bottom-left origin, triangles) +local function direct(P: { number }, N: { number }, T: { number }, I: { number }, o: Options): Types.Primitive + local nv = #P // 3 + if o.flipV ~= false then + for i = 2, #T, 2 do + T[i] = 1 - T[i] + end + end + return { + attributes = { POSITION = f32(P, 3, nv), NORMAL = f32(N, 3, nv), TEXCOORD_0 = f32(T, 2, nv) }, + indices = u32(I), + mode = "triangles", + } +end + +local function box(n: any, o: Options): Types.Primitive + local s = vec(n, "size", { 2, 2, 2 }) + local hx, hy, hz = s[1] / 2, s[2] / 2, s[3] / 2 + local P, N, T, I = {}, {}, {}, {} + -- faces: normal, u axis, v axis (the specification's texture orientation) + local FACES = { + { { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 0 } }, { { 0, 0, -1 }, { -1, 0, 0 }, { 0, 1, 0 } }, + { { 1, 0, 0 }, { 0, 0, -1 }, { 0, 1, 0 } }, { { -1, 0, 0 }, { 0, 0, 1 }, { 0, 1, 0 } }, + { { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 } }, { { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, 1 } }, + } + for f, face in FACES do + local nn, u, v = face[1], face[2], face[3] + for _, c in { { -1, -1 }, { 1, -1 }, { 1, 1 }, { -1, 1 } } do + for q = 1, 3 do + local h = if q == 1 then hx elseif q == 2 then hy else hz + table.insert(P, (nn[q] + u[q] * c[1] + v[q] * c[2]) * h) + table.insert(N, nn[q]) + end + table.insert(T, (c[1] + 1) / 2) + table.insert(T, (c[2] + 1) / 2) + end + local b = (f - 1) * 4 + for _, x in { 0, 1, 2, 0, 2, 3 } do + table.insert(I, b + x) + end + end + return direct(P, N, T, I, o) +end + +-- a ring of segs + 1 vertices (the seam doubled for the texture) at height y, radius r; s starts at the back (-z) +-- and runs counter-clockwise seen from +y +local function ring(P: { number }, N: { number }?, T: { number }?, segs: number, y: number, r: number, t: number, ny: number?, nr: number?) + for i = 0, segs do + local a = 2 * pi * i / segs + local x, z = -sin(a), -cos(a) + table.insert(P, x * r) + table.insert(P, y) + table.insert(P, z * r) + if N then + table.insert(N, x * (nr or 1)) + table.insert(N, ny or 0) + table.insert(N, z * (nr or 1)) + end + if T then + table.insert(T, i / segs) + table.insert(T, t) + end + end +end + +-- a cap disc at height y facing ny (+1 / -1) +local function cap(P: { number }, N: { number }, T: { number }, I: { number }, segs: number, y: number, r: number, ny: number) + local b = #P // 3 + for i = 0, segs - 1 do + local a = 2 * pi * i / segs + local x, z = -sin(a), -cos(a) + table.insert(P, x * r) + table.insert(P, y) + table.insert(P, z * r) + table.insert(N, 0) + table.insert(N, ny) + table.insert(N, 0) + -- the specification maps the cap like a top view: s = x, t = -z (top) or z (bottom) + table.insert(T, x / 2 + 0.5) + table.insert(T, (if ny > 0 then -z else z) / 2 + 0.5) + end + for i = 1, segs - 2 do + -- the ring runs counter-clockwise seen from +y: in order for the top, reversed for the bottom + if ny > 0 then + table.insert(I, b) + table.insert(I, b + i) + table.insert(I, b + i + 1) + else + table.insert(I, b) + table.insert(I, b + i + 1) + table.insert(I, b + i) + end + end +end + +-- quads between two rings of segs + 1 vertices starting at a (lower) and b (upper) +local function band(I: { number }, a: number, b: number, segs: number) + for i = 0, segs - 1 do + table.insert(I, a + i) + table.insert(I, a + i + 1) + table.insert(I, b + i + 1) + table.insert(I, a + i) + table.insert(I, b + i + 1) + table.insert(I, b + i) + end +end + +local function sphere(n: any, o: Options, segs: number): Types.Primitive + local r = num(n, "radius", 1) + local rings = math.max(2, segs // 2) + local P, N, T, I = {}, {}, {}, {} + for j = 0, rings do + local phi = pi * j / rings -- from the bottom + local y, rr = -cos(phi), sin(phi) + ring(P, N, T, segs, y * r, rr * r, j / rings, y, rr) + end + for j = 0, rings - 1 do + band(I, j * (segs + 1), (j + 1) * (segs + 1), segs) + end + return direct(P, N, T, I, o) +end + +local function cylinder(n: any, o: Options, segs: number, cone: boolean): Types.Primitive + local r = num(n, if cone then "bottomRadius" else "radius", 1) + local h = num(n, "height", 2) + local P, N, T, I = {}, {}, {}, {} + if bool(n, "side", true) then + -- side normals: a cone's lean outwards by its slope + local l = sqrt(r * r + h * h) + local ny, nr = if cone and l > 0 then r / l else 0, if cone and l > 0 then h / l else 1 + ring(P, N, T, segs, -h / 2, r, 0, ny, nr) + ring(P, N, T, segs, h / 2, if cone then 0 else r, 1, ny, nr) + band(I, 0, segs + 1, segs) + end + if not cone and bool(n, "top", true) then + cap(P, N, T, I, segs, h / 2, r, 1) + end + if bool(n, "bottom", true) then + cap(P, N, T, I, segs, -h / 2, r, -1) + end + return direct(P, N, T, I, o) +end + +-- ------------------------------------------------------------------------------------------------ dispatch +-- primitive(geometryNode, opts) -> Primitive | nil, message | nil, nil (a node type without geometry here); +-- the second value of a success is the node's solid flag +function Geometry.primitive(n: any, o: Options): (Types.Primitive?, any) + local t = n.type + local maxV = o.maxVertices or 2 ^ 24 + local segs = math.clamp(math.floor(o.segments or 32), 3, 1024) + local solid = bool(n, "solid", true) + local prim: Types.Primitive?, err: string? = nil, nil + if t == "IndexedFaceSet" then + prim, err = faceSet(n, o, maxV) + elseif t == "IndexedTriangleSet" or t == "TriangleSet" or t == "IndexedTriangleFanSet" or t == "TriangleFanSet" or t == "IndexedTriangleStripSet" or t == "TriangleStripSet" or t == "IndexedQuadSet" or t == "QuadSet" then + prim, err = triSet(n, o, maxV) + elseif t == "ElevationGrid" then + prim, err = elevationGrid(n, o, maxV) + elseif t == "Extrusion" then + prim, err = extrusion(n, o, maxV) + elseif t == "IndexedLineSet" or t == "LineSet" then + prim, err = lines(n, maxV) + solid = false + elseif t == "PointSet" then + prim, err = pointSet(n, maxV) + solid = false + elseif t == "Box" then + prim = box(n, o) + elseif t == "Sphere" then + prim = sphere(n, o, segs) + elseif t == "Cylinder" then + prim = cylinder(n, o, segs, false) + elseif t == "Cone" then + prim = cylinder(n, o, segs, true) + else + return nil, nil + end + if not prim then + return nil, err + end + return prim, solid +end + +return Geometry diff --git a/src/Formats/codecs/model/Vrml/Parse.luau b/src/Formats/codecs/model/Vrml/Parse.luau new file mode 100644 index 0000000..8dd2ac5 --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Parse.luau @@ -0,0 +1,536 @@ +--!strict +-- codecs/model/Vrml/Parse: the VRML97 (ISO/IEC 14772-1) / X3D classic VRML encoding (ISO/IEC 19776-2) parser, into +-- the node graph codecs/model/Vrml/Build reads. Written from the specifications; no third-party code. Field types are +-- not known without the node schemas, so a field value is kept as a flat array of what the file wrote (numbers, +-- strings, booleans, nodes) and the builder reads it as the type it expects. Handles comments, DEF / USE, PROTO +-- (instances are expanded: IS fields take the instance's values or the declared defaults; nested PROTOs, ROUTEs inside +-- bodies), EXTERNPROTO (instances stay nodes of that type, without a body), Script / shader interface declarations, +-- ROUTE, and the X3D header statements (PROFILE, COMPONENT, META, UNIT, IMPORT, EXPORT). Never throws: errors are +-- returned as nil, message ("line N: ..."). +local Parse = {} + +export type Node = { type: string, def: string?, fields: { [string]: any } } +export type Route = { from: Node, fromField: string, to: Node, toField: string } +export type Proto = { name: string, fields: { [string]: any }, body: { Node }, routes: { Route }, extern: boolean? } +export type Graph = { + roots: { Node }, + routes: { Route }, + header: { [string]: any }, -- version ("2.0" / "3.3" ...), encoding, x3d (boolean), profile + meta: { [string]: string }, -- META / WorldInfo statements + components: { string }, + units: { [string]: { name: string, factor: number } }, + protos: { [string]: Proto }, +} +-- an IS reference in a PROTO body: fields[name] = { is = "protoField" } +export type IsRef = { is: string } + +local find, sub, byte, match, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch + +local ID1 = "^[^%c%s%d\"#',%+%-%.%[\\%]{}][^%c%s\"#',%.%[\\%]{}]*" +local MAX_DEPTH = 200 +local DECL = { field = true, exposedField = true, eventIn = true, eventOut = true, initializeOnly = true, inputOutput = true, inputOnly = true, outputOnly = true } +local HAS_VALUE = { field = true, exposedField = true, initializeOnly = true, inputOutput = true } + +-- copy(node, values, defaults, memo) -> a PROTO body node with its IS fields replaced (shared nodes stay shared) +local function copy(node: Node, values: { [string]: any }, defaults: { [string]: any }, memo: { [any]: any }): Node + local done = memo[node] + if done then + return done + end + local out: Node = { type = node.type, def = node.def, fields = {} } + memo[node] = out + for k, v in node.fields do + if type(v) == "table" and type((v :: any).is) == "string" then + local name = (v :: any).is + local val = values[name] + if val == nil then + val = defaults[name] + end + out.fields[k] = val + elseif type(v) == "table" then + local arr = table.create(#v) + for i, x in v do + arr[i] = if type(x) == "table" and x.type then copy(x, values, defaults, memo) else x + end + out.fields[k] = arr + else + out.fields[k] = v + end + end + return out +end + +-- expand(proto, values, def, routes) -> the instance's node (the body's first node), or nil for an EXTERNPROTO +function Parse.expand(proto: Proto, values: { [string]: any }, def: string?, routes: { Route }?): Node? + if proto.extern or #proto.body == 0 then + return nil + end + local memo = {} + local first: Node? = nil + for _, n in proto.body do + local c = copy(n, values, proto.fields, memo) + first = first or c + end + if routes then + for _, r in proto.routes do + local from, to = memo[r.from], memo[r.to] + if from and to then + table.insert(routes, { from = from, fromField = r.fromField, to = to, toField = r.toField }) + end + end + end + local f = first :: Node + if def then + -- the instance gets its own copy of the node so its DEF name is its own + local out: Node = { type = f.type, def = def, fields = f.fields } + return out + end + return f +end + +function Parse.parse(text: string): (Graph?, string?) + local n = #text + local p = 1 + local graph: Graph = { roots = {}, routes = {}, header = {}, meta = {}, components = {}, units = {}, protos = {} } + local defs: { [string]: Node } = {} + local protos: { [string]: Proto } = graph.protos + local routes: { Route } = graph.routes + local failure: string? = nil + local depth = 0 + + local function line(at: number): number + local l = 1 + for _ in gmatch(sub(text, 1, at), "\n") do + l += 1 + end + return l + end + local function fail(msg: string) + if not failure then + failure = "line " .. line(p) .. ": " .. msg + end + end + + -- header line: #VRML V2.0 utf8 / #X3D V3.3 utf8 + local v, enc = match(text, "^#VRML V(%S+) (%S+)") + if v then + graph.header.version, graph.header.encoding = v, enc + if v ~= "2.0" then + return nil, "unsupported: VRML " .. v .. " (only VRML97 / X3D)" + end + else + v, enc = match(text, "^#X3D V(%S+) (%S+)") + if v then + graph.header.version, graph.header.encoding, graph.header.x3d = v, enc, true + end + end + + -- the lexer: skip blanks, commas and comments; returns the next token kind and value + -- kinds: "num", "str", "id", "{", "}", "[", "]", ".", "eof" + local function skip() + while true do + local q = find(text, "[^%s,]", p) + if not q then + p = n + 1 + return + end + p = q + if byte(text, p) == 35 then -- '#' + local e = find(text, "[\r\n]", p) + p = if e then e else n + 1 + else + return + end + end + end + local function token(): (string, any) + skip() + if p > n then + return "eof", nil + end + local c = byte(text, p) + if c == 123 or c == 125 or c == 91 or c == 93 then -- { } [ ] + p += 1 + return string.char(c), nil + elseif c == 34 then -- a string: \" and \\ escapes + local q = p + 1 + local parts = {} + while true do + local e = find(text, '["\\]', q) + if not e then + fail("unterminated string") + p = n + 1 + return "eof", nil + end + table.insert(parts, sub(text, q, e - 1)) + if byte(text, e) == 92 then + table.insert(parts, sub(text, e + 1, e + 1)) + q = e + 2 + else + p = e + 1 + return "str", table.concat(parts) + end + end + end + if (c >= 48 and c <= 57) or c == 43 or c == 45 or c == 46 then + local s, e = find(text, "^[+-]?0[xX]%x+", p) + if not s then + s, e = find(text, "^[+-]?%d*%.?%d*[eE][+-]?%d+", p) + end + if not s then + s, e = find(text, "^[+-]?%d*%.?%d*", p) + end + local num = tonumber(sub(text, p, e)) + if num then + p = (e :: number) + 1 + return "num", num + end + if c == 46 then + p += 1 + return ".", nil + end + -- +inf / -nan style words: read the word + local _, we = find(text, "^[^%s,%[%]{}#\"]+", p) + local w = sub(text, p, we) + p = (we :: number) + 1 + local wl = string.lower(w) + local val = if find(wl, "inf", 1, true) then (if c == 45 then -math.huge else math.huge) elseif find(wl, "nan", 1, true) then 0 else nil + if val == nil then + fail("bad number " .. w) + return "eof", nil + end + return "num", val + end + local s, e = find(text, ID1, p) + if s then + p = (e :: number) + 1 + return "id", sub(text, s, e) + end + fail("unexpected character " .. sub(text, p, p)) + p = n + 1 + return "eof", nil + end + local function peek(): (string, any) + local save = p + local k, val = token() + p = save + return k, val + end + + local parseNode: (first: string) -> (Node?, boolean) + local parseProto: (extern: boolean) -> () + local parseRoute: () -> () + + -- a field value (after its name): an array of numbers / strings / booleans / nodes + local function value(): any + local k, val = token() + if k == "[" then + local out = {} + -- fast path: a bracket of plain numbers (big coordinate arrays) + local close = find(text, "]", p, true) + if close then + local seg = sub(text, p, close - 1) + if not find(seg, "[{}\"#]") then + local ok = true + for w in gmatch(seg, "[^%s,]+") do + local x = tonumber(w) + if x then + table.insert(out, x) + elseif w == "TRUE" or w == "FALSE" then + table.insert(out, w == "TRUE") + else + ok = false + break + end + end + if ok then + p = close + 1 + return out + end + table.clear(out) + end + end + while not failure do + k, val = token() + if k == "]" then + return out + elseif k == "num" or k == "str" then + table.insert(out, val) + elseif k == "id" and (val == "TRUE" or val == "FALSE") then + table.insert(out, val == "TRUE") + elseif k == "id" and val == "NULL" then + continue + elseif k == "id" then + local node = parseNode(val) + if node then + table.insert(out, node) + end + else + fail("unexpected " .. k .. " in a [ ] value") + return out + end + end + return out + elseif k == "num" then + local out = { val } + while true do + local save = p + local k2, v2 = token() + if k2 ~= "num" then + p = save + break + end + table.insert(out, v2) + end + return out + elseif k == "str" then + return { val } + elseif k == "id" then + if val == "TRUE" or val == "FALSE" then + return { val == "TRUE" } + elseif val == "NULL" then + return {} + end + local node = parseNode(val) + return if node then { node } else {} + end + fail("missing field value") + return {} + end + + -- the fields of a node body, up to its "}" + local function body(node: Node) + while not failure do + local k, name = token() + if k == "}" then + return + elseif k ~= "id" then + fail("expected a field name in " .. node.type .. ", got " .. k) + return + end + if name == "ROUTE" then + parseRoute() + elseif name == "PROTO" or name == "EXTERNPROTO" then + parseProto(name == "EXTERNPROTO") + elseif DECL[name] then + -- Script / shader interface: [ | IS ] + local _, _t = token() + local fk, fname = token() + if fk ~= "id" then + fail("bad interface declaration in " .. node.type) + return + end + local pk, pv = peek() + if pk == "id" and pv == "IS" then + token() + local _, ref = token() + node.fields[fname] = { is = ref } + elseif HAS_VALUE[name] then + node.fields[fname] = value() + end + else + local pk, pv = peek() + if pk == "id" and pv == "IS" then + token() + local _, ref = token() + node.fields[name] = { is = ref } + else + node.fields[name] = value() + end + end + end + end + + -- a node statement starting with the id `first` (DEF name Type { }, USE name, Type { }) + function parseNode(first: string): (Node?, boolean) + if first == "USE" then + local k, name = token() + if k ~= "id" then + fail("USE without a name") + return nil, false + end + local node = defs[name] + if not node then + fail("USE of an undefined name " .. tostring(name)) + end + return node, true + end + local def: string? = nil + local typ = first + if first == "DEF" then + local k, name = token() + local k2, t2 = token() + if k ~= "id" or k2 ~= "id" then + fail("bad DEF") + return nil, false + end + def, typ = name, t2 + end + local k = token() + if k ~= "{" then + fail("expected { after " .. typ) + return nil, false + end + depth += 1 + if depth > MAX_DEPTH then + fail("limit: nodes nested deeper than " .. MAX_DEPTH) + return nil, false + end + local node: Node = { type = typ, def = def, fields = {} } + body(node) + depth -= 1 + local proto = protos[typ] + if proto and not proto.extern then + local inst = Parse.expand(proto, node.fields, def, routes) + if inst then + node = inst + end + elseif proto then + (node :: any).extern = true + end + if def then + defs[def] = node + end + return node, false + end + + -- ROUTE from.field TO to.field + function parseRoute() + local function path(): (string?, string?) + local k1, a = token() + local k2 = token() + local k3, b = token() + if k1 ~= "id" or k2 ~= "." or k3 ~= "id" then + return nil, nil + end + return a, b + end + local a, af = path() + local k, to = token() + local b, bf = path() + if not (a and af and b and bf) or k ~= "id" or to ~= "TO" then + fail("bad ROUTE") + return + end + local from, dst = defs[a :: string], defs[b :: string] + if from and dst then + table.insert(routes, { from = from, fromField = af :: string, to = dst, toField = bf :: string }) + end + end + + -- PROTO name [ interface ] { body } / EXTERNPROTO name [ interface ] url + function parseProto(extern: boolean) + local k, name = token() + if k ~= "id" or token() ~= "[" then + fail("bad PROTO") + return + end + local proto: Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil } + while not failure do + local k2, access = token() + if k2 == "]" then + break + elseif k2 ~= "id" or not DECL[access] then + fail("bad PROTO interface") + return + end + local _, _t = token() + local fk, fname = token() + if fk ~= "id" then + fail("bad PROTO interface") + return + end + if HAS_VALUE[access] and not extern then + proto.fields[fname] = value() + end + end + if extern then + value() -- the url list + protos[name] = proto + return + end + if token() ~= "{" then + fail("PROTO " .. tostring(name) .. " without a body") + return + end + -- the body has its own DEF names and its own routes + local outerDefs, outerRoutes = defs, routes + defs, routes = {}, proto.routes + while not failure do + local k3, w = token() + if k3 == "}" then + break + elseif k3 ~= "id" then + fail("bad PROTO body") + break + elseif w == "ROUTE" then + parseRoute() + elseif w == "PROTO" or w == "EXTERNPROTO" then + parseProto(w == "EXTERNPROTO") + else + local node = parseNode(w) + if node then + table.insert(proto.body, node) + end + end + end + defs, routes = outerDefs, outerRoutes + protos[name] = proto + end + + -- statements + while not failure do + local k, w = token() + if k == "eof" then + break + elseif k ~= "id" then + fail("unexpected " .. k) + break + end + if w == "ROUTE" then + parseRoute() + elseif w == "PROTO" or w == "EXTERNPROTO" then + parseProto(w == "EXTERNPROTO") + elseif w == "PROFILE" then + local _, prof = token() + graph.header.profile = prof + elseif w == "COMPONENT" then + local _, comp = token() -- name:level is one id + table.insert(graph.components, tostring(comp)) + elseif w == "META" then + local _, key = token() + local _, val = token() + graph.meta[tostring(key)] = tostring(val) + elseif w == "UNIT" then + local _, cat = token() + local _, uname = token() + local _, factor = token() + if type(cat) == "string" and type(factor) == "number" then + graph.units[cat] = { name = tostring(uname), factor = factor } + end + elseif w == "IMPORT" or w == "EXPORT" then + -- IMPORT inline.name AS name / EXPORT name AS name: no effect on the scene + local _, _a = token() + if peek() == "." then + token() + token() + end + local pk, pv = peek() + if pk == "id" and pv == "AS" then + token() + token() + end + else + local node = parseNode(w) + if node then + table.insert(graph.roots, node) + end + end + end + if failure then + return nil, failure + end + return graph, nil +end + +return Parse diff --git a/src/Formats/codecs/model/Vrml/Write.luau b/src/Formats/codecs/model/Vrml/Write.luau new file mode 100644 index 0000000..8c0ad97 --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Write.luau @@ -0,0 +1,750 @@ +--!strict +-- codecs/model/Vrml/Write: a Scene to VRML97 (`#VRML V2.0 utf8`), X3D classic (`#X3D V3.3 utf8`) or X3D XML text, +-- for model/vrml and model/x3d. New code. Every node becomes a DEF'd Transform (a matrix is decomposed into TRS; +-- shear is lost), each primitive a Shape: triangles / polygons / strips / fans -> IndexedFaceSet (coord, normal, +-- texCoord with t flipped back unless flipV = false, color; per-vertex, ccw, solid = not doubleSided), lines -> +-- IndexedLineSet, points -> PointSet; a mesh used twice is written once and USE'd. Materials -> Appearance / Material +-- (diffuse = baseColor, transparency = 1 - alpha, emissive, shininess from roughness, the Phong terms of +-- material.extras.vrml when present) with an ImageTexture (the texture bytes go into opts.files named after the uri or +-- opts.name, else url = texture.uri). Cameras -> Viewpoint (X3D: OrthoViewpoint for orthographic ones), lights -> +-- Directional / Point / SpotLight, animations (translation / rotation / scale channels) -> a TimeSensor and +-- Position / OrientationInterpolators with ROUTEs (cubic splines keep their values, weights channels are dropped). +-- Never throws: returns nil, message. +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Flatten = require("@formats/codecs/model/MeshFlatten") +local Xml = require("@formats/codecs/text/Xml") + +local Write = {} + +export type Options = { encoding: ("vrml97" | "x3dv" | "xml")?, files: { [string]: any }?, name: string?, flipV: boolean? } + +-- a written node: fields in order, each { name, kind, value }; kinds: "sf" / "mf" (numbers; mf groups `per` numbers +-- per line), "bool", "str", "mstr" (MFString), "node", "nodes" +type WNode = { type: string, def: string?, use: string?, fields: { { any } } } + +local format, concat = string.format, table.concat + +local function fmt(v: number): string + if v ~= v then + return "0" + elseif v == math.huge then + return "1e38" + elseif v == -math.huge then + return "-1e38" + elseif v == math.floor(v) and math.abs(v) < 2 ^ 53 then + return format("%d", v) + end + return format("%.9g", v) +end + +local function W(t: string, def: string?): WNode + return { type = t, def = def, fields = {} } +end +local function F(n: WNode, name: string, kind: string, value: any, per: number?) + table.insert(n.fields, { name, kind, value, per }) +end + +-- names: valid, unique DEF names +local function namer(): (string?, string) -> string + local used: { [string]: boolean } = {} + return function(name: string?, fallback: string): string + local s = string.gsub(name or "", "[^%w_]", "_") + if s == "" or string.find(s, "^%d") then + s = fallback .. (if s ~= "" then "_" .. s else "") + end + local base, k = s, 1 + while used[s] do + k += 1 + s = base .. "_" .. k + end + used[s] = true + return s + end +end + +-- axis-angle of a quaternion (x, y, z, w) +local function axisAngle(q: { number }): { number } + local x, y, z, w = q[1], q[2], q[3], q[4] + local l = math.sqrt(x * x + y * y + z * z + w * w) + if l > 0 then + x, y, z, w = x / l, y / l, z / l, w / l + end + local s = math.sqrt(math.max(0, 1 - w * w)) + if s < 1e-9 then + return { 0, 0, 1, 0 } + end + return { x / s, y / s, z / s, 2 * math.acos(math.clamp(w, -1, 1)) } +end + +-- ------------------------------------------------------------------------------------------------ geometry +local function values(acc: any): { number }? + return (Flatten.numbers(acc)) +end + +local function faceSet(prim: any, doubleSided: boolean, o: Options, x3d: boolean): (WNode?, string?) + local tmp = { kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } } + local keep = function(n: string): boolean + return n == "NORMAL" or n == "TEXCOORD_0" or n == "COLOR_0" + end + local m, err = Flatten.merge(tmp, keep, { triangulate = false }) + if not m then + return nil, err + end + if not m.sizes or #m.sizes == 0 then + return nil, nil + end + local g = W("IndexedFaceSet") + local coord = W("Coordinate") + F(coord, "point", "mf", m.attrs.POSITION.values, 3) + F(g, "coord", "node", coord) + local idx = {} + local p = 0 + for _, s in m.sizes do + for k = 1, s do + table.insert(idx, m.corners[p + k]) + end + table.insert(idx, -1) + p += s + end + F(g, "coordIndex", "mf", idx, 0) + local nrm = m.attrs.NORMAL + if nrm then + local nn = W("Normal") + F(nn, "vector", "mf", nrm.values, 3) + F(g, "normal", "node", nn) + end + local tc = m.attrs.TEXCOORD_0 + if tc then + local t = W("TextureCoordinate") + local vals, c = {}, tc.components + for i = 0, m.count - 1 do + local s, tt = tc.values[i * c + 1], tc.values[i * c + 2] + table.insert(vals, s) + table.insert(vals, if o.flipV ~= false then 1 - tt else tt) + end + F(t, "point", "mf", vals, 2) + F(g, "texCoord", "node", t) + end + local col = m.attrs.COLOR_0 + if col then + local c = col.components + local rgba = c >= 4 and x3d + local cn = W(if rgba then "ColorRGBA" else "Color") + local vals = {} + local scale = if col.raw then (if col.type == "unorm8" then 255 elseif col.type == "unorm16" then 65535 else 1) else 1 + for i = 0, m.count - 1 do + for k = 1, if rgba then 4 else 3 do + table.insert(vals, (col.values[i * c + k] or 1) / scale) + end + end + F(cn, "color", "mf", vals, if rgba then 4 else 3) + F(g, "color", "node", cn) + end + F(g, "solid", "bool", not doubleSided) + return g, nil +end + +-- Coordinate from POSITION, Color / ColorRGBA from COLOR_0 (lines and points) +local function coordNode(prim: any): (WNode?, number) + local pos = values(prim.attributes.POSITION) + if not pos then + return nil, 0 + end + local nv, pc = prim.attributes.POSITION.count, prim.attributes.POSITION.components + local p3 = {} + for i = 0, nv - 1 do + for k = 1, 3 do + table.insert(p3, pos[i * pc + k] or 0) + end + end + local coord = W("Coordinate") + F(coord, "point", "mf", p3, 3) + return coord, nv +end +local function colorNode(prim: any, nv: number, x3d: boolean): WNode? + local acc = prim.attributes.COLOR_0 + local col = acc and values(acc) + if not col then + return nil + end + local c = acc.components + local rgba = c >= 4 and x3d + local vals = {} + for i = 0, nv - 1 do + for k = 1, if rgba then 4 else 3 do + table.insert(vals, col[i * c + k] or 1) + end + end + local cn = W(if rgba then "ColorRGBA" else "Color") + F(cn, "color", "mf", vals, if rgba then 4 else 3) + return cn +end + +local function lineSet(prim: any, x3d: boolean): (WNode?, string?) + local coord, nv = coordNode(prim) + if not coord then + return nil, "lines without POSITION" + end + local ind: { number } + if prim.indices then + ind = values(prim.indices) or {} + else + ind = {} + for i = 0, nv - 1 do + ind[i + 1] = i + end + end + local idx = {} + local mode = prim.mode + if mode == "lines" then + for i = 1, #ind - 1, 2 do + table.insert(idx, ind[i]) + table.insert(idx, ind[i + 1]) + table.insert(idx, -1) + end + else + for _, v in ind do + table.insert(idx, v) + end + if mode == "line_loop" and #ind > 0 then + table.insert(idx, ind[1]) + end + table.insert(idx, -1) + end + for _, v in idx do + if v >= nv then + return nil, "line index out of range" + end + end + local g = W("IndexedLineSet") + F(g, "coord", "node", coord) + local cn = colorNode(prim, nv, x3d) + if cn then + F(g, "color", "node", cn) + end + F(g, "coordIndex", "mf", idx, 0) + return g, nil +end + +local function pointSet(prim: any, x3d: boolean): (WNode?, string?) + local coord, nv = coordNode(prim) + if not coord then + return nil, "points without POSITION" + end + local g = W("PointSet") + F(g, "coord", "node", coord) + local cn = colorNode(prim, nv, x3d) + if cn then + F(g, "color", "node", cn) + end + return g, nil +end + +-- ------------------------------------------------------------------------------------------------ materials +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2" } + +local function textureUrl(scene: any, i: number, o: Options, written: { [number]: string }): string? + if written[i] then + return written[i] + end + local tex = scene.textures[i] + if not tex then + return nil + end + local url = tex.uri + if tex.data and type(o.files) == "table" then + local base = string.match(o.name or "model", "([^/\\]+)$") or "model" + base = string.gsub(base, "%.[^.]*$", "") + local ext = EXT[tex.mime or ""] or (url and string.match(url, "%.(%w+)$")) or "png" + local file = if url and not string.find(url, "^data:") and not string.find(url, "[/\\]") then url else format("%s_%d.%s", base, i, ext) + o.files[file] = tex.data + url = file + end + if url then + written[i] = url + end + return url +end + +local function appearance(scene: any, mi: number, o: Options, written: { [number]: string }): WNode + local m = scene.materials[mi] + local app = W("Appearance") + local mat = W("Material") + local x = m.extras and m.extras.vrml or {} + local c = m.baseColor or { 1, 1, 1, 1 } + F(mat, "diffuseColor", "sf", { c[1], c[2], c[3] }) + local e = m.emissive or { 0, 0, 0 } + if e[1] ~= 0 or e[2] ~= 0 or e[3] ~= 0 then + F(mat, "emissiveColor", "sf", { e[1], e[2], e[3] }) + end + if type(x.specularColor) == "table" then + F(mat, "specularColor", "sf", x.specularColor) + end + local sh = x.shininess + if type(sh) ~= "number" then + local r = math.max(m.roughness or 1, 1e-3) + sh = math.clamp((2 / (r * r) - 2) / 128, 0, 1) + end + F(mat, "shininess", "sf", { sh }) + if type(x.ambientIntensity) == "number" then + F(mat, "ambientIntensity", "sf", { x.ambientIntensity }) + end + if (c[4] or 1) < 1 then + F(mat, "transparency", "sf", { 1 - c[4] }) + end + F(app, "material", "node", mat) + local ref = m.baseColorTexture + if ref and type(ref.texture) == "number" then + local url = textureUrl(scene, ref.texture, o, written) + local img = scene.textures[ref.texture] and scene.textures[ref.texture].image + if url or (img and img.format == "rgba8" and img.width * img.height <= 2 ^ 20) then + local it + if url then + it = W("ImageTexture") + F(it, "url", "mstr", { url }) + else + -- a decoded image only: PixelTexture (SFImage: width height 4, then 0xRRGGBBAA from the bottom row up) + it = W("PixelTexture") + local w, h = img.width, img.height + local v = { w, h, 4 } + for row = h - 1, 0, -1 do + for x = 0, w - 1 do + table.insert(v, buffer.readu32(img.pixels, (row * w + x) * 4)) + end + end + -- the pixels are little-endian RGBA bytes: swap to 0xRRGGBBAA + for i = 4, #v do + local p = v[i] + v[i] = (p % 256) * 16777216 + (p // 256 % 256) * 65536 + (p // 65536 % 256) * 256 + p // 16777216 + end + F(it, "image", "sf", v) + end + local s = scene.textures[ref.texture].sampler + if s and s.wrapS == "clamp" then + F(it, "repeatS", "bool", false) + end + if s and s.wrapT == "clamp" then + F(it, "repeatT", "bool", false) + end + F(app, "texture", "node", it) + local tf = ref.transform + if tf then + local tt = W("TextureTransform") + if tf.offset then + F(tt, "translation", "sf", tf.offset) + end + if tf.scale then + F(tt, "scale", "sf", tf.scale) + end + if tf.rotation then + F(tt, "rotation", "sf", { tf.rotation }) + end + F(app, "textureTransform", "node", tt) + end + end + end + return app +end + +-- ------------------------------------------------------------------------------------------------ the tree +function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, string?) + local x3d = o.encoding == "x3dv" or o.encoding == "xml" + local name = namer() + local nodeDef: { [number]: string } = {} + local meshShapes: { [number]: { WNode } } = {} + local appDef: { [any]: string } = {} + local written: { [number]: string } = {} + local failure: string? = nil + + local function shapes(mi: number): { WNode } + local done = meshShapes[mi] + if done then + -- USE the shapes written before + local out = {} + for _, s in done do + table.insert(out, { type = "Shape", use = s.def, fields = {} }) + end + return out + end + local mesh = scene.meshes[mi] + local out = {} + for pi, prim in (if mesh then mesh.primitives else {}) :: { any } do + local mode = prim.mode or "triangles" + local mat = if type(prim.material) == "number" then scene.materials[prim.material] else nil + local geo, err + if mode == "lines" or mode == "line_strip" or mode == "line_loop" then + geo, err = lineSet(prim, x3d) + elseif mode == "points" then + geo, err = pointSet(prim, x3d) + else + geo, err = faceSet(prim, mat ~= nil and mat.doubleSided == true, o, x3d) + end + if err then + failure = failure or err + end + if geo then + local sh = W("Shape", name((mesh.name or "mesh") .. (if #mesh.primitives > 1 then "_" .. pi else ""), "Shape")) + if mat then + local key = prim.material + if appDef[key] then + F(sh, "appearance", "node", { type = "Appearance", use = appDef[key], fields = {} }) + else + local app = appearance(scene, prim.material, o, written) + app.def = name(mat.name, "Material") + appDef[key] = app.def + F(sh, "appearance", "node", app) + end + end + F(sh, "geometry", "node", geo) + table.insert(out, sh) + end + end + meshShapes[mi] = out + return out + end + + local visiting: { [number]: boolean } = {} + local function transform(ni: number): WNode? + local n = scene.nodes[ni] + if type(n) ~= "table" or visiting[ni] then + return nil + end + visiting[ni] = true + local def = name(n.name, "Node") + nodeDef[ni] = def + local t = W("Transform", def) + local tr, rot, sc = n.translation, n.rotation, n.scale + if n.matrix then + tr, rot, sc = Mat4.decompose(n.matrix) + end + if tr and (tr[1] ~= 0 or tr[2] ~= 0 or tr[3] ~= 0) then + F(t, "translation", "sf", { tr[1], tr[2], tr[3] }) + end + if rot then + local aa = axisAngle(rot) + if aa[4] ~= 0 then + F(t, "rotation", "sf", aa) + end + end + if sc and (sc[1] ~= 1 or sc[2] ~= 1 or sc[3] ~= 1) then + F(t, "scale", "sf", { sc[1], sc[2], sc[3] }) + end + local kids: { WNode } = {} + if type(n.mesh) == "number" then + for _, s in shapes(n.mesh) do + table.insert(kids, s) + end + end + local cam = if type(n.camera) == "number" then scene.cameras[n.camera] else nil + if cam then + local v + if cam.type == "orthographic" and x3d then + v = W("OrthoViewpoint") + local xm, ym = cam.xmag or 1, cam.ymag or 1 + F(v, "fieldOfView", "sf", { -xm, -ym, xm, ym }) + else + v = W("Viewpoint") + F(v, "fieldOfView", "sf", { cam.yfov or 0.785398 }) + end + F(v, "position", "sf", { 0, 0, 0 }) + if cam.name then + F(v, "description", "str", cam.name) + end + table.insert(kids, v) + end + local l = if type(n.light) == "number" then scene.lights[n.light] else nil + if l then + local typ = if l.type == "directional" then "DirectionalLight" elseif l.type == "spot" then "SpotLight" else "PointLight" + local ln = W(typ) + local c = l.color or { 1, 1, 1 } + F(ln, "color", "sf", { c[1], c[2], c[3] }) + F(ln, "intensity", "sf", { math.clamp(l.intensity or 1, 0, 1) }) + if typ ~= "PointLight" then + F(ln, "direction", "sf", { 0, 0, -1 }) + end + if typ ~= "DirectionalLight" then + F(ln, "location", "sf", { 0, 0, 0 }) + F(ln, "radius", "sf", { l.range or 100 }) + end + if typ == "SpotLight" then + F(ln, "cutOffAngle", "sf", { l.outerCone or 0.785398 }) + F(ln, "beamWidth", "sf", { l.innerCone or 0 }) + end + table.insert(kids, ln) + end + for _, c in n.children or {} do + local ct = transform(c) + if ct then + table.insert(kids, ct) + end + end + if #kids > 0 then + F(t, "children", "nodes", kids) + end + visiting[ni] = nil + return t + end + + local roots: { WNode } = {} + local list = scene.roots + if type(list) ~= "table" or #list == 0 then + -- no roots: every node without a parent + local child = {} + for _, n in scene.nodes do + for _, c in n.children or {} do + child[c] = true + end + end + list = {} + for i = 1, #scene.nodes do + if not child[i] then + table.insert(list, i) + end + end + end + for _, ri in list do + local t = transform(ri) + if t then + table.insert(roots, t) + end + end + if #scene.nodes == 0 then + for mi = 1, #scene.meshes do + for _, s in shapes(mi) do + table.insert(roots, s) + end + end + end + + -- animations: a TimeSensor per animation, an interpolator per channel + local routes: { { string } } = {} + for ai, anim in scene.animations or {} do + local tmax = 0 + local chans = {} + for _, ch in anim.channels or {} do + local target = nodeDef[ch.node] + if target and (ch.path == "translation" or ch.path == "rotation" or ch.path == "scale") then + local input, output = values(ch.input), values(ch.output) + if input and output and #input > 0 then + tmax = math.max(tmax, input[#input]) + table.insert(chans, { ch, target, input, output }) + end + end + end + if #chans > 0 then + local cycle = if tmax > 0 then tmax else 1 + local ts = W("TimeSensor", name(anim.name, "Animation" .. ai)) + F(ts, "cycleInterval", "sf", { cycle }) + F(ts, "loop", "bool", true) + table.insert(roots, ts) + for k, c in chans do + local ch, target, input, output = c[1], c[2], c[3], c[4] + local rot = ch.path == "rotation" + local it = W(if rot then "OrientationInterpolator" else "PositionInterpolator", name(ts.def .. "_" .. k, "Interpolator")) + local keys = {} + for i, tv in input do + keys[i] = tv / cycle + end + local comps = if rot then 4 else 3 + local stride = #output // #input + -- CUBICSPLINE stores in-tangent, value, out-tangent per key + local off = if ch.interpolation == "CUBICSPLINE" and stride == comps * 3 then comps else 0 + local kv = {} + for i = 0, #input - 1 do + local v = {} + for q = 1, comps do + v[q] = output[i * stride + off + q] or 0 + end + if rot then + v = axisAngle(v) + end + for _, x in v do + table.insert(kv, x) + end + end + F(it, "key", "mf", keys, 0) + F(it, "keyValue", "mf", kv, comps) + table.insert(roots, it) + table.insert(routes, { ts.def :: string, "fraction_changed", it.def :: string, "set_fraction" }) + table.insert(routes, { it.def :: string, "value_changed", target, "set_" .. ch.path }) + end + end + end + if failure then + return nil, nil, failure + end + return roots, routes, nil +end + +-- ------------------------------------------------------------------------------------------------ serializers +local function numbers(vals: { number }, per: number?, indent: string): string + local out = table.create(#vals) + for i, v in vals do + out[i] = fmt(v) + end + if per == 0 then + -- index lists: one face per line + local lines, cur = {}, {} + for i, v in vals do + table.insert(cur, out[i]) + if v == -1 then + table.insert(lines, concat(cur, " ")) + cur = {} + end + end + if #cur > 0 then + table.insert(lines, concat(cur, " ")) + end + return concat(lines, "\n" .. indent) + end + if per and per > 0 then + local lines = {} + for i = 1, #out, per do + table.insert(lines, concat(out, " ", i, math.min(i + per - 1, #out))) + end + return concat(lines, ",\n" .. indent) + end + return concat(out, " ") +end + +local function quote(s: string): string + return '"' .. string.gsub(s, '(["\\])', "\\%1") .. '"' +end + +local function classic(roots: { WNode }, routes: { { string } }, x3d: boolean): string + local out = {} + if x3d then + table.insert(out, "#X3D V3.3 utf8\nPROFILE Interchange\n# written by formats-luau\n") + else + table.insert(out, "#VRML V2.0 utf8\n# written by formats-luau\n") + end + local function emit(n: WNode, ind: string): string + if n.use then + return "USE " .. n.use + end + local parts = { (if n.def then "DEF " .. n.def .. " " else "") .. n.type .. " {" } + local ind2 = ind .. " " + for _, f in n.fields do + local fname, kind, v, per = f[1], f[2], f[3], f[4] + local s + if kind == "sf" then + s = numbers(v, nil, ind2) + elseif kind == "mf" then + s = "[\n" .. ind2 .. " " .. numbers(v, per, ind2 .. " ") .. "\n" .. ind2 .. "]" + elseif kind == "bool" then + s = if v then "TRUE" else "FALSE" + elseif kind == "str" then + s = quote(v) + elseif kind == "mstr" then + local q = {} + for i, x in v do + q[i] = quote(x) + end + s = "[ " .. concat(q, " ") .. " ]" + elseif kind == "node" then + s = emit(v, ind2) + else + local q = {} + for i, x in v do + q[i] = ind2 .. " " .. emit(x, ind2 .. " ") + end + s = "[\n" .. concat(q, "\n") .. "\n" .. ind2 .. "]" + end + table.insert(parts, ind2 .. fname .. " " .. s) + end + table.insert(parts, ind .. "}") + return concat(parts, "\n") + end + for _, r in roots do + table.insert(out, emit(r, "")) + end + for _, r in routes do + table.insert(out, format("ROUTE %s.%s TO %s.%s", r[1], r[2], r[3], r[4])) + end + return concat(out, "\n") .. "\n" +end + +-- the containerField a child element needs when it is not its type's default +local DEFAULT = { Appearance = "appearance", Material = "material", ImageTexture = "texture", TextureTransform = "textureTransform", Coordinate = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", TextureCoordinate = "texCoord", IndexedFaceSet = "geometry", IndexedLineSet = "geometry", PointSet = "geometry" } + +local function xml(roots: { WNode }, routes: { { string } }): (string?, string?) + local function element(n: WNode, field: string): any + local attrs = Types.object() + local kids = {} + if (DEFAULT[n.type] or "children") ~= field then + Types.set(attrs, "containerField", field) + end + if n.use then + Types.set(attrs, "USE", n.use) + return Xml.element(n.type, attrs :: any) + end + if n.def then + Types.set(attrs, "DEF", n.def) + end + for _, f in n.fields do + local fname, kind, v, per = f[1], f[2], f[3], f[4] + if kind == "sf" then + Types.set(attrs, fname, numbers(v, nil, "")) + elseif kind == "mf" then + local s = numbers(v, per, "") + Types.set(attrs, fname, (string.gsub(s, "\n", " "))) + elseif kind == "bool" then + Types.set(attrs, fname, if v then "true" else "false") + elseif kind == "str" then + Types.set(attrs, fname, v) + elseif kind == "mstr" then + local q = {} + for i, x in v do + q[i] = quote(x) + end + Types.set(attrs, fname, concat(q, " ")) + elseif kind == "node" then + table.insert(kids, element(v, fname)) + else + for _, x in v do + table.insert(kids, element(x, fname)) + end + end + end + return Xml.element(n.type, attrs :: any, kids) + end + local sceneKids = {} + for _, r in roots do + table.insert(sceneKids, element(r, "children")) + end + for _, r in routes do + local a = Types.object() + Types.set(a, "fromNode", r[1]) + Types.set(a, "fromField", r[2]) + Types.set(a, "toNode", r[3]) + Types.set(a, "toField", r[4]) + table.insert(sceneKids, Xml.element("ROUTE", a :: any)) + end + local ra = Types.object() + Types.set(ra, "profile", "Interchange") + Types.set(ra, "version", "3.3") + local meta = Types.object() + Types.set(meta, "name", "generator") + Types.set(meta, "content", "formats-luau") + local root = Xml.element("X3D", ra :: any, { Xml.element("head", nil, { Xml.element("meta", meta :: any) }), Xml.element("Scene", nil, sceneKids) }) + local s, err = Xml.encode(Xml.document(root, { version = "1.0", encoding = "UTF-8" }), { indent = 2 }) + if not s then + return nil, if err then err.message else "xml" + end + return s, nil +end + +-- text(scene, opts) -> the file text +function Write.text(scene: any, o: Options): (string?, string?) + local roots, routes, err = Write.graph(scene, o) + if not roots or not routes then + return nil, err + end + if o.encoding == "xml" then + return xml(roots, routes) + end + return classic(roots, routes, o.encoding == "x3dv"), nil +end + +return Write diff --git a/src/Formats/codecs/model/Vrml/Xml.luau b/src/Formats/codecs/model/Vrml/Xml.luau new file mode 100644 index 0000000..93066e8 --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Xml.luau @@ -0,0 +1,238 @@ +--!strict +-- codecs/model/Vrml/Xml: the X3D XML encoding (ISO/IEC 19776-1) to the node graph of codecs/model/Vrml/Parse, so one +-- builder serves .wrl, .x3dv and .x3d. Written from the specification; no third-party code. Elements are nodes; +-- attributes stay raw strings (the builder parses them as the type it expects); child nodes go into their +-- containerField (or the default field of their type: geometry, appearance, material, coord, ...); DEF / USE; ROUTE; +-- ProtoDeclare (ProtoInterface fields with value attributes or child nodes, ProtoBody, IS / connect) and +-- ProtoInstance (fieldValue) are expanded through Parse.expand; ExternProtoDeclare instances stay plain nodes; head / +-- meta, UNIT, component and the profile go into the graph header. Never throws. +local Xml = require("@formats/codecs/text/Xml") +local Parse = require("@formats/codecs/model/Vrml/Parse") + +local VXml = {} + +local GEOMETRY = { + "Box", "Sphere", "Cone", "Cylinder", "IndexedFaceSet", "IndexedLineSet", "LineSet", "PointSet", "ElevationGrid", + "Extrusion", "Text", "IndexedTriangleSet", "TriangleSet", "IndexedTriangleFanSet", "TriangleFanSet", + "IndexedTriangleStripSet", "TriangleStripSet", "IndexedQuadSet", "QuadSet", "Arc2D", "ArcClose2D", "Circle2D", + "Disk2D", "Polyline2D", "Polypoint2D", "Rectangle2D", "TriangleSet2D", "GeoElevationGrid", "NurbsPatchSurface", +} +local CONTAINER: { [string]: string } = { + Appearance = "appearance", Material = "material", PhysicalMaterial = "material", TwoSidedMaterial = "material", + UnlitMaterial = "material", ImageTexture = "texture", PixelTexture = "texture", MovieTexture = "texture", + MultiTexture = "texture", ImageCubeMapTexture = "texture", TextureTransform = "textureTransform", + Coordinate = "coord", CoordinateDouble = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", + TextureCoordinate = "texCoord", MultiTextureCoordinate = "texCoord", TextureCoordinateGenerator = "texCoord", + FontStyle = "fontStyle", TextureProperties = "textureProperties", FillProperties = "fillProperties", + LineProperties = "lineProperties", +} +for _, g in GEOMETRY do + CONTAINER[g] = "geometry" +end + +local function container(el: Xml.Node, typ: string): string + local c = el.attrs.containerField + if type(c) == "string" and c ~= "" then + return c + end + if string.sub(typ, 1, 8) == "Metadata" then + return "metadata" + end + return CONTAINER[typ] or "children" +end + +function VXml.graph(doc: Xml.Node): (Parse.Graph?, string?) + local root = doc.root or doc + if type(root) ~= "table" or Xml.localName(root.name) ~= "X3D" then + return nil, "no root element" + end + local graph: Parse.Graph = { roots = {}, routes = {}, header = { x3d = true, xml = true }, meta = {}, components = {}, units = {}, protos = {} } + graph.header.version, graph.header.profile = root.attrs.version, root.attrs.profile + local defs: { [string]: Parse.Node } = {} + local protos = graph.protos + local routes = graph.routes + local depth = 0 + local failure: string? = nil + + local convert: (el: Xml.Node) -> Parse.Node? + local function route(el: Xml.Node) + local a = el.attrs + local from, to = defs[a.fromNode or ""], defs[a.toNode or ""] + local ff, tf = a.fromField, a.toField + if from and to and type(ff) == "string" and type(tf) == "string" then + table.insert(routes, { from = from, fromField = ff, to = to, toField = tf }) + end + end + local declare: (el: Xml.Node, extern: boolean) -> () + + -- the child elements of a node into its fields + local function children(el: Xml.Node, node: Parse.Node) + for _, ch in el.children do + if type(ch) ~= "table" or string.sub(ch.name, 1, 1) == "#" then + continue + end + local name = Xml.localName(ch.name) + if name == "ROUTE" then + route(ch) + elseif name == "IS" then + for _, c in Xml.children(ch, "connect") do + local nf, pf = c.attrs.nodeField, c.attrs.protoField + if nf and pf then + node.fields[nf] = { is = pf } + end + end + elseif name == "ProtoDeclare" or name == "ExternProtoDeclare" then + declare(ch, name == "ExternProtoDeclare") + elseif name == "field" or name == "fieldValue" then + continue -- Script / shader interfaces + else + local c = convert(ch) + if c then + local f = container(ch, if name == "ProtoInstance" then "" else name) + local list = node.fields[f] + if type(list) ~= "table" or (list :: any).is then + list = {} + node.fields[f] = list + end + table.insert(list, c) + end + end + end + end + + -- a field value of ProtoInterface / fieldValue: the value attribute, or the child nodes + local function fieldValue(el: Xml.Node): any + if el.attrs.value ~= nil then + return el.attrs.value + end + local list = {} + for _, ch in el.children do + if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then + local c = convert(ch) + if c then + table.insert(list, c) + end + end + end + return list + end + + function declare(el: Xml.Node, extern: boolean) + local name = el.attrs.name + if not name then + return + end + local proto: Parse.Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil } + local iface = if extern then el else Xml.child(el, "ProtoInterface") + if iface then + for _, f in Xml.children(iface, "field") do + if f.attrs.name then + proto.fields[f.attrs.name] = fieldValue(f) + end + end + end + local bodyEl = Xml.child(el, "ProtoBody") + if bodyEl and not extern then + local outerDefs, outerRoutes = defs, routes + defs, routes = {}, proto.routes + for _, ch in bodyEl.children do + if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then + local nm = Xml.localName(ch.name) + if nm == "ROUTE" then + route(ch) + elseif nm == "ProtoDeclare" or nm == "ExternProtoDeclare" then + declare(ch, nm == "ExternProtoDeclare") + else + local c = convert(ch) + if c then + table.insert(proto.body, c) + end + end + end + end + defs, routes = outerDefs, outerRoutes + end + protos[name] = proto + end + + function convert(el: Xml.Node): Parse.Node? + local a = el.attrs + if a.USE then + return defs[a.USE] + end + depth += 1 + if depth > 200 then + failure = failure or "limit: nodes nested deeper than 200" + depth -= 1 + return nil + end + local typ = Xml.localName(el.name) + local node: any + if typ == "ProtoInstance" then + local proto = protos[a.name or ""] + local values = {} + for _, fv in Xml.children(el, "fieldValue") do + if fv.attrs.name then + values[fv.attrs.name] = fieldValue(fv) + end + end + local inst = proto and Parse.expand(proto, values, a.DEF, routes) + node = inst or { type = a.name or "ProtoInstance", def = a.DEF, fields = values } + else + node = { type = typ, def = a.DEF, fields = {} } + for k, v in a do + if k ~= "DEF" and k ~= "USE" and k ~= "containerField" and k ~= "class" and not string.find(k, ":", 1, true) then + node.fields[k] = v + end + end + children(el, node) + end + depth -= 1 + if a.DEF then + defs[a.DEF] = node + end + return node + end + + for _, ch in root.children do + if type(ch) ~= "table" then + continue + end + local name = Xml.localName(ch.name) + if name == "head" then + for _, h in ch.children do + if type(h) == "table" then + local hn = Xml.localName(h.name) + if hn == "meta" and h.attrs.name then + graph.meta[h.attrs.name] = h.attrs.content or "" + elseif hn == "component" and h.attrs.name then + table.insert(graph.components, h.attrs.name .. ":" .. (h.attrs.level or "1")) + elseif hn == "unit" and h.attrs.category then + graph.units[h.attrs.category] = { name = h.attrs.name or "", factor = tonumber(h.attrs.conversionFactor) or 1 } + end + end + end + elseif name == "Scene" then + local scene: Parse.Node = { type = "Scene", fields = {} } + children(ch, scene) + local list = scene.fields.children + if type(list) == "table" then + graph.roots = list + end + for f, v in scene.fields do + -- a top-level node with another containerField still shows + if f ~= "children" and type(v) == "table" then + for _, x in v do + table.insert(graph.roots, x) + end + end + end + end + end + if failure then + return nil, failure + end + return graph, nil +end + +return VXml diff --git a/src/Formats/codecs/model/Vrml/init.luau b/src/Formats/codecs/model/Vrml/init.luau new file mode 100644 index 0000000..6e37e4d --- /dev/null +++ b/src/Formats/codecs/model/Vrml/init.luau @@ -0,0 +1,160 @@ +--!strict +-- codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML, +-- .x3dv classic): one parser for the classic encoding (codecs/model/Vrml/Parse), one for the XML encoding +-- (codecs/model/Vrml/Xml over codecs/text/Xml), both into the same node graph, and one builder from the graph to a +-- Scene (codecs/model/Vrml/Build, codecs/model/Vrml/Geometry). Gzipped files (.wrz / .x3dz / .x3dvz) are inflated +-- first. New code, written from ISO/IEC 14772-1 (VRML97), ISO/IEC 19775-1 (X3D) and its encodings 19776-1 / -2. +-- +-- local graph, err = Vrml.graph(bytes) -- classic or XML, by content +-- local scene, err2 = Vrml.decode(bytes, { format = "vrml", files = { ["tex.png"] = png } }) +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Deflate = require("@formats/codecs/compress/Deflate") +local XmlCodec = require("@formats/codecs/text/Xml") +local Parse = require("@formats/codecs/model/Vrml/Parse") +local VXml = require("@formats/codecs/model/Vrml/Xml") +local Build = require("@formats/codecs/model/Vrml/Build") +local Write = require("@formats/codecs/model/Vrml/Write") + +local Vrml = {} + +export type Graph = Parse.Graph +export type Node = Parse.Node +export type Options = Build.Options & { + files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string) + resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths) + maxBytes: number?, -- the inflated size of a gzipped file (default 2^28) +} + +-- the bytes as text: gzip inflated, UTF-8 BOM dropped +local function text(data: buffer | string, maxBytes: number?): (string?, Err.Err?) + local b = if type(data) == "string" then buffer.fromstring(data) else data + if buffer.len(b) >= 2 and buffer.readu8(b, 0) == 0x1F and buffer.readu8(b, 1) == 0x8B then + local out, err = Deflate.gunzip(b) + if not out then + return nil, err + end + if buffer.len(out) > (maxBytes or 2 ^ 28) then + return nil, Err.new(Err.LIMIT, "inflated file over maxBytes") + end + b = out + end + local s = buffer.tostring(b) + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + return s, nil +end + +local function code(msg: string): string + if string.find(msg, "unsupported", 1, true) then + return Err.UNSUPPORTED + elseif string.find(msg, "limit", 1, true) then + return Err.LIMIT + elseif string.find(msg, "unterminated", 1, true) then + return Err.TRUNCATED + end + return Err.CORRUPT +end + +-- parse(text) -> the graph of a classic-encoding file (VRML97 / .x3dv) +function Vrml.parse(s: string): (Graph?, Err.Err?) + local g, msg = Parse.parse(s) + if not g then + return nil, Err.new(code(msg or "parse error"), msg or "parse error") + end + return g, nil +end + +-- parseXml(text | XML document) -> the graph of an X3D XML file +function Vrml.parseXml(src: any): (Graph?, Err.Err?) + local doc = src + if type(src) == "string" then + local d, err = XmlCodec.decode(src) + if not d and err and err.code == Err.TRUNCATED and not string.find(src, "", 1, true) then + -- VTK's X3D exporter leaves the root element open + d = XmlCodec.decode(src .. "\n\n") + end + if not d then + return nil, err + end + doc = d + end + local g, msg = VXml.graph(doc) + if not g then + return nil, Err.new(code(msg or "bad X3D"), msg or "bad X3D") + end + return g, nil +end + +-- graph(bytes, opts?) -> the graph of either encoding (XML when the text starts with "<"); binary X3D is UNSUPPORTED +function Vrml.graph(data: buffer | string, opts: Options?): (Graph?, Err.Err?) + local s, err = text(data, opts and opts.maxBytes) + if not s then + return nil, err + end + local head = string.match(s, "^%s*(.?)") + if head == "<" then + return Vrml.parseXml(s) + end + if string.sub(s, 1, 4) == "\224\0\0\1" or string.sub(s, 1, 4) == "$EXI" then + return nil, Err.new(Err.UNSUPPORTED, "binary X3D (Fast Infoset / EXI encoding)") + end + return Vrml.parse(s) +end + +-- fetcher(opts) -> fetch(uri) -> buffer?: opts.files (uri or base name) / opts.resolve +function Vrml.fetcher(opts: Options?): (uri: string) -> buffer? + return function(uri: string): buffer? + if not opts then + return nil + end + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] or opts.files[string.match(uri, "([^/\\]+)$") or uri] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil + end +end + +-- build(graph, opts?) -> Scene +function Vrml.build(graph: Graph, opts: Options?): (Types.Scene?, Err.Err?) + local o: any = table.clone(opts or {}) + o.fetch = o.fetch or Vrml.fetcher(opts) + o.load = o.load or function(data: buffer): (any, string?) + local g, err = Vrml.graph(data, opts) + return g, if err then err.message else nil + end + local scene, msg = Build.scene(graph, o) + if not scene then + return nil, Err.new(code(msg or "build failed"), msg or "build failed") + end + return scene, nil +end + +-- decode(bytes, opts?) -> Scene: graph + build +function Vrml.decode(data: buffer | string, opts: Options?): (Types.Scene?, Err.Err?) + local g, err = Vrml.graph(data, opts) + if not g then + return nil, err + end + return Vrml.build(g, opts) +end + +-- encode(scene, opts?) -> text: opts.encoding "vrml97" (default) / "x3dv" / "xml"; texture bytes go into opts.files +function Vrml.encode(scene: Types.Scene, opts: Write.Options?): (string?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local s, msg = Write.text(scene, opts or {}) + if not s then + return nil, Err.new(Err.ARG, msg or "the scene could not be written") + end + return s, nil +end + +return Vrml diff --git a/src/Formats/model/vrml/init.luau b/src/Formats/model/vrml/init.luau new file mode 100644 index 0000000..c9192c1 --- /dev/null +++ b/src/Formats/model/vrml/init.luau @@ -0,0 +1,77 @@ +--!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). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Vrml = require("@formats/codecs/model/Vrml") + +-- ------------------------------------------------------------------------------------------------ contract +local Wrl = { + name = "vrml", + category = "model", + extensions = { "wrl", "wrz", "vrml" }, + mime = { "model/vrml", "x-world/x-vrml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true }, +} + +-- ------------------------------------------------------------------------------------------------ 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) + 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) + flipV: boolean?, -- default true (the inverse of decode) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Wrl.sniff(r: Bytes.Reader): number + local head = r:peek(16) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + return if string.sub(head, 1, 10) == "#VRML V2.0" then 1 elseif string.sub(head, 1, 6) == "#VRML " then 0.6 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Wrl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: any = table.clone(opts or {}) + o.format = "vrml" + return Vrml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), o) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Wrl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = table.clone(opts or {}) + o.encoding = "vrml97" + local text, err = Vrml.encode(scene, o) + if not text then + return nil, err + end + return buffer.fromstring(text), nil +end + +return Wrl diff --git a/src/Formats/model/x3d/init.luau b/src/Formats/model/x3d/init.luau new file mode 100644 index 0000000..860efa7 --- /dev/null +++ b/src/Formats/model/x3d/init.luau @@ -0,0 +1,85 @@ +--!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. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Vrml = require("@formats/codecs/model/Vrml") + +-- ------------------------------------------------------------------------------------------------ contract +local X3d = { + name = "x3d", + category = "model", + extensions = { "x3d", "x3dv", "x3dz", "x3dvz", "x3db" }, + mime = { "model/x3d+xml", "model/x3d-vrml", "model/x3d+fastinfoset" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true, xml = true, classic = true }, +} + +-- ------------------------------------------------------------------------------------------------ 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) + 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) + flipV: boolean?, -- default true (the inverse of decode) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function X3d.sniff(r: Bytes.Reader): number + local head = r:peek(1024) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + if string.sub(head, 1, 5) == "#X3D " then + return 1 + end + if string.sub(head, 1, 4) == "\224\0\0\1" and string.find(head, "x3d", 1, true) then + return 0.9 + end + if string.find(head, "]") or string.find(head, " meta.unit") +end + +-- ------------------------------------------------------------------------------------------------ XML adapter +do + local g = assert(Vrml.graph([[ + + + + + + + +]])) + t:check(g.header.xml and g.header.version == "4.0", "XML header") + t:eq(g.components[1], "Shaders:1", "head component") + local grp = g.roots[1] + local kids = Fields.nodes(grp, "children") + t:eq(#kids, 2, "ProtoInstances in children") + t:eq(Fields.num(Fields.node(kids[1], "geometry"), "radius", -1), 5, "fieldValue") + t:eq(Fields.num(Fields.node(kids[2], "geometry"), "radius", -1), 2, "ProtoInterface default") + local shape = g.roots[2] + local box = Fields.node(shape, "geometry") + t:eq(table.concat(Fields.vec(box, "size", { 9, 9, 9 }), " "), "1 2 3", "numbers with commas") + t:eq(Fields.bool(box, "solid", true), false, "XML booleans (any case)") + local tex = Fields.node(Fields.node(shape, "appearance"), "texture") + local urls = Fields.strs(tex, "url") + t:check(#urls == 2 and urls[2] == "b.png", "quoted MFString") + t:eq(g.roots[3], grp, "USE in XML") + local single = { type = "ImageTexture", fields = { url = "plain name.png" } } + t:eq(Fields.strs(single, "url")[1], "plain name.png", "unquoted single MFString") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local function code(text: string): string? + local _, e = Vrml.graph(text) + return e and e.code + end + t:eq(code("#VRML V2.0 utf8\nShape { geometry Box { }"), Err.CORRUPT, "unclosed node") + t:eq(code("#VRML V2.0 utf8\nShape { geometry USE X }"), Err.CORRUPT, "undefined USE") + t:eq(code("#VRML V2.0 utf8\nROUTE A.b TO"), Err.CORRUPT, "bad ROUTE") + t:eq(code("#VRML V2.0 utf8\nWorldInfo { title \"x }"), Err.TRUNCATED, "unterminated string") + t:eq(code("#VRML V1.0 ascii\n"), Err.UNSUPPORTED, "VRML 1.0") + t:eq(code("\224\0\0\1rest"), Err.UNSUPPORTED, "Fast Infoset X3D") + t:eq(code("#VRML V2.0 utf8\n" .. string.rep("Group { children ", 250)), Err.LIMIT, "nesting limit") + t:eq(code(""), Err.CORRUPT, "bad XML") + local _, e = Vrml.encode({} :: any) + t:eq(e and e.code, Err.ARG, "encode junk") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = { + "#VRML V2.0 utf8\nPROTO P [ field SFFloat a 1 ] { Box { size IS a IS a } }\nDEF X P { a 2 } USE X ROUTE X.a TO X.b\n", + "#X3D V3.3 utf8\nPROFILE Full\nShape { geometry Extrusion { spine [ 0 0 0 0 1 0 1 1 1 ] crossSection [ 0 0 1 0 1 1 0 0 ] } }\n", + "", + } + t:fuzz("graph + build", function(b: buffer) + local g = Vrml.graph(b) + if g then + return Vrml.build(g) + end + return nil + end, samples, { mutations = 400 }) +end + +t:done() diff --git a/tests/model/_vrml_common.luau b/tests/model/_vrml_common.luau new file mode 100644 index 0000000..8ac98a0 --- /dev/null +++ b/tests/model/_vrml_common.luau @@ -0,0 +1,109 @@ +-- tests/model/_vrml_common: helpers shared by the VRML and X3D tests (tests/model/vrml.luau, x3d.luau): counts over +-- placed primitives (instances count, as the reference readers count them) and world bounds that include lines and +-- points (MeshOps.merge skips them). +local Types = require("@formats/Types") + +local C = {} + +export type Stats = { prims: number, unique: number, polys: number, lines: number, points: number, lo: { number }, hi: { number }, area: number } + +function C.near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +function C.stats(scene: any): Stats + local s: Stats = { prims = 0, unique = 0, polys = 0, lines = 0, points = 0, lo = { math.huge, math.huge, math.huge }, hi = { -math.huge, -math.huge, -math.huge }, area = 0 } + local seen = {} + for _, pl in Types.Scene.flatten(scene) do + local p = pl.primitive + s.prims += 1 + if not seen[p] then + seen[p] = true + s.unique += 1 + end + local P = p.attributes.POSITION + local nf = 0 + if p.mode == "polygons" then + nf = p.faces.count + elseif p.mode == "lines" then + s.lines += (if p.indices then p.indices.count else P.count) // 2 + elseif p.mode == "points" then + s.points += P.count + elseif p.mode == "triangle_strip" or p.mode == "triangle_fan" then + nf = math.max(0, (if p.indices then p.indices.count else P.count) - 2) + elseif p.mode == "line_strip" or p.mode == "line_loop" then + local n = if p.indices then p.indices.count else P.count + s.lines += if p.mode == "line_loop" then n else math.max(0, n - 1) + else + nf = (if p.indices then p.indices.count else P.count) // 3 + end + s.polys += nf + local m = pl.matrix + local get = assert(Types.Scene.reader(P)) + local w = {} + for v = 0, P.count - 1 do + local x, y, z = get(v, 0), get(v, 1), get(v, 2) + local wx, wy, wz = m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] + w[v] = { wx, wy, wz } + s.lo[1], s.lo[2], s.lo[3] = math.min(s.lo[1], wx), math.min(s.lo[2], wy), math.min(s.lo[3], wz) + s.hi[1], s.hi[2], s.hi[3] = math.max(s.hi[1], wx), math.max(s.hi[2], wy), math.max(s.hi[3], wz) + end + -- world area of the faces (fan-triangulated polygons) + local mode = p.mode + if mode == "triangles" or mode == "polygons" or mode == "triangle_strip" or mode == "triangle_fan" then + local ir = if p.indices then Types.Scene.reader(p.indices) else nil + local ind = function(i: number, _c: number): number + return if ir then ir(i, 0) else i + end + local count = if p.indices then p.indices.count else P.count + local function tri(a: number, b: number, c: number) + local A, B, Cc = w[a], w[b], w[c] + if A and B and Cc then + local e1 = { B[1] - A[1], B[2] - A[2], B[3] - A[3] } + local e2 = { Cc[1] - A[1], Cc[2] - A[2], Cc[3] - A[3] } + local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] + s.area += math.sqrt(x * x + y * y + z * z) / 2 + end + end + if mode == "triangles" then + for t = 0, count // 3 - 1 do + tri(ind(t * 3, 0), ind(t * 3 + 1, 0), ind(t * 3 + 2, 0)) + end + elseif mode == "triangle_strip" then + for t = 0, count - 3 do + tri(ind(t, 0), ind(t + 1, 0), ind(t + 2, 0)) + end + elseif mode == "triangle_fan" then + for t = 1, count - 2 do + tri(ind(0, 0), ind(t, 0), ind(t + 1, 0)) + end + else + local at = 0 + local sizes = assert(Types.Scene.reader(p.faces)) + for f = 0, p.faces.count - 1 do + local n = sizes(f, 0) + for k = 1, n - 2 do + tri(ind(at, 0), ind(at + k, 0), ind(at + k + 1, 0)) + end + at += n + end + end + end + end + return s +end + +function C.boundsNear(lo: { number }, hi: { number }, wlo: { number }, whi: { number }, eps: number): boolean + for k = 1, 3 do + if not C.near(lo[k], wlo[k], eps) or not C.near(hi[k], whi[k], eps) then + return false + end + end + return true +end + +function C.fmt(lo: { number }, hi: { number }): string + return string.format("%.5g %.5g %.5g / %.5g %.5g %.5g", lo[1], lo[2], lo[3], hi[1], hi[2], hi[3]) +end + +return C diff --git a/tests/model/pmx.luau b/tests/model/pmx.luau index e685dcf..6612131 100644 --- a/tests/model/pmx.luau +++ b/tests/model/pmx.luau @@ -257,7 +257,7 @@ do MeshOps.merge(s) end return s - end, samples, { mutations = 16, keepHeader = 17 }) + end, samples, { mutations = 16, keepHeader = 16 }) end t:done() diff --git a/tests/model/vrml.luau b/tests/model/vrml.luau new file mode 100644 index 0000000..5638328 --- /dev/null +++ b/tests/model/vrml.luau @@ -0,0 +1,410 @@ +-- model/vrml tests: assimp's WRL test models (HelloWorld, Wuson, the MotionCaptureROM animation), scenes and glTF +-- samples written by VTK's VRML exporter, and hand-written feature files (PROTO, DEF / USE, per-face colours and +-- separate indices, primitives, ElevationGrid, Extrusion, Switch, LOD, lights, viewpoints, ROUTE animations, +-- PixelTexture, Inline), against VTK's vtkVRMLImporter (polygons, points, world bounds where VTK's transforms are +-- right) and exact expectations; the writer: round trips of every case and of glTF sample models (world triangles, +-- materials, textures, cameras, lights, animation samples), VTK reading our files like the originals; errors; the +-- fuzz no-throw pass. Fixtures: tools/fixtures/vrml.py. +local T = require("@tests/T") +local F = require("@formats") +local Vrml = require("@formats/model/vrml") +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Deflate = require("@formats/codecs/compress/Deflate") +local C = require("@tests/model/_vrml_common") +local Cases = require("@tests/gen/vrml_cases") +local GltfCases = require("@tests/gen/vrml_gltf") +local Xcheck = require("@tests/gen/vrml_xcheck") + +local t = T.suite("vrml") +local near = C.near + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Vrml.decode(Bytes.reader(b), opts) +end + +t:eq(Vrml.name, "vrml", "name") +t:eq(Vrml.category, "model", "category") +t:check(Vrml.caps.decode and Vrml.caps.encode, "contract") + +-- ------------------------------------------------------------------------------------------------ reference files +local scenes, byName = {}, {} +local checked = { vtk = 0, bounds = 0, none = 0 } +for i, c in Cases do + local scene, err = decode(c.data, { files = c.files, triangulate = false }) + t:check(scene, c.name .. ": decode: " .. tostring(err)) + if not scene then + continue + end + scenes[i], byName[c.name] = scene, scene + local s = C.stats(scene) + local v = c.vtk + if v.failed or v.actors == 0 then + checked.none += 1 + continue + end + checked.vtk += 1 + if not c.primitives then + t:eq(s.polys, v.polys, c.name .. ": polygons (VTK)") + end + t:eq(s.points, v.verts, c.name .. ": points (VTK)") + t:check((s.lines > 0) == (v.lines > 0), c.name .. ": lines (VTK)") + if c.vtkTransforms and v.min then + t:check(C.boundsNear(s.lo, s.hi, v.min, v.max, if c.primitives then 2e-2 else 1e-5), c.name .. ": world bounds (VTK) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(v.min, v.max)) + checked.bounds += 1 + end +end +t:note("%d files: %d against VTK (%d with bounds), %d VTK cannot read", #Cases, checked.vtk, checked.bounds, checked.none) + +-- ------------------------------------------------------------------------------------------------ exact expectations +local function prims(scene: any): { any } + local out = {} + for _, pl in Types.Scene.flatten(scene) do + table.insert(out, pl) + end + return out +end + +do + local hw = byName["assimp/HelloWorld.wrl"] + if hw then + t:eq(#hw.cameras, 1, "HelloWorld: viewpoint") + t:eq(hw.cameras[1].name, "ViewUpClose", "HelloWorld: viewpoint DEF name") + t:eq(hw.meta.source.title, "Hello World!", "HelloWorld: WorldInfo title") + t:eq(hw.meta.source.skipped.Text, 1, "HelloWorld: Text skipped") + local tex = hw.textures[1] + t:check(tex and tex.uri == "earth-topo.png" and tex.data and tex.mime == "image/png", "HelloWorld: texture from files") + t:eq(hw.materials[1].name, "MaterialOffWhite", "HelloWorld: material DEF name") + t:check(near(hw.materials[1].baseColor[1], 0.980392, 1e-6), "HelloWorld: diffuseColor") + end + local mc = byName["assimp/MotionCaptureROM.WRL"] + if mc then + t:eq(#mc.animations, 1, "MotionCaptureROM: one TimeSensor animation") + local a = mc.animations[1] + t:check(#a.channels >= 20, "MotionCaptureROM: channels " .. #a.channels) + local tmax = 0 + for _, ch in a.channels do + tmax = math.max(tmax, buffer.readf32(ch.input.data, (ch.input.count - 1) * 4)) + end + t:check(near(tmax, 45.27, 1e-4), "MotionCaptureROM: key times x cycleInterval " .. tmax) + end + + -- PROTO expansion, DEF / USE of a Shape (one mesh, two nodes) + local pu = byName["feature/feat_proto_use.wrl"] + if pu then + local s = C.stats(pu) + t:eq(#pu.meshes, 3, "proto: meshes (two instances + a shared shape)") + t:eq(s.prims, 4, "proto: placed primitives") + t:check(C.boundsNear(s.lo, s.hi, { -1, -0.5, -0.5 }, { 3.5, 6, 0.5 }, 1e-4), "proto: bounds " .. C.fmt(s.lo, s.hi)) + local cols = {} + for _, m in pu.materials do + table.insert(cols, string.format("%g %g %g", m.baseColor[1], m.baseColor[2], m.baseColor[3])) + end + table.sort(cols) + t:eq(table.concat(cols, ", "), "0 1 0, 1 0 0", "proto: IS fields (instance value, default)") + end + + -- separate indices, per-face normals / colours, ccw FALSE, solid FALSE + local ix = byName["feature/feat_indices.wrl"] + if ix then + local p1 = ix.meshes[1].primitives[1] + t:eq(p1.attributes.POSITION.count, 8, "indices: corners split by normal / colour / texture index") + t:eq(p1.faces.count, 2, "indices: two quads") + local N, Col, Tx = p1.attributes.NORMAL, p1.attributes.COLOR_0, p1.attributes.TEXCOORD_0 + t:check(buffer.readf32(N.data, 8) == 1 and buffer.readf32(Col.data, 0) == 1 and buffer.readf32(Col.data, 8) == 0, "indices: face 1 normal / colour") + t:check(buffer.readf32(Tx.data, 4) == 1, "indices: t flipped (0 -> 1)") + -- ccw FALSE: the first face is written reversed (0 3 2 1) + t:eq(buffer.readu32(p1.indices.data, 4), 3, "indices: ccw FALSE reverses the winding") + local m = ix.materials[p1.material] + t:check(m.doubleSided and m.alphaMode == "blend" and near(m.baseColor[4], 0.75, 1e-6), "indices: solid FALSE, transparency") + t:check(m.extras.vrml.shininess == 0.5 and m.extras.vrml.specularColor[1] == 1, "indices: Phong terms in extras") + local p2 = ix.meshes[2].primitives[1] + t:eq(p2.attributes.POSITION.count, 5, "indices: per-vertex colour indices") + t:check(p2.material == nil, "indices: no appearance, no material") + end + + -- primitives: exact bounds, unit normals + local pr = byName["feature/feat_primitives.wrl"] + if pr then + local s = C.stats(pr) + t:check(C.boundsNear(s.lo, s.hi, { -4.5, -2, -1.5 }, { 9, 2, 1.5 }, 1e-6), "primitives: bounds " .. C.fmt(s.lo, s.hi)) + local box = pr.meshes[1].primitives[1] + t:eq(box.attributes.POSITION.count, 24, "Box: 24 vertices") + t:eq(box.indices.count, 36, "Box: 12 triangles") + local sph = pr.meshes[2].primitives[1] + local ok = true + local P, N = sph.attributes.POSITION, sph.attributes.NORMAL + for v = 0, P.count - 1 do + for k = 0, 2 do + ok = ok and near(buffer.readf32(P.data, (v * 3 + k) * 4) / 1.5, buffer.readf32(N.data, (v * 3 + k) * 4), 1e-5) + end + end + t:check(ok, "Sphere: normals = position / radius") + -- outward winding: the Box's first triangle faces +z + local function faceNormal(prim: any, tri: number): { number } + local function p(i: number): { number } + local v = buffer.readu32(prim.indices.data, (tri * 3 + i) * 4) + return { buffer.readf32(prim.attributes.POSITION.data, v * 12), buffer.readf32(prim.attributes.POSITION.data, v * 12 + 4), buffer.readf32(prim.attributes.POSITION.data, v * 12 + 8) } + end + local a, b, c = p(0), p(1), p(2) + local e1, e2 = { b[1] - a[1], b[2] - a[2], b[3] - a[3] }, { c[1] - a[1], c[2] - a[2], c[3] - a[3] } + return { e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] } + end + t:check(faceNormal(box, 0)[3] > 0, "Box: counter-clockwise front faces") + local cyl = pr.meshes[4].primitives[1] + local last = cyl.indices.count // 3 - 1 + t:check(faceNormal(cyl, last)[2] < 0, "Cylinder: bottom cap faces down") + t:check(faceNormal(cyl, 0)[3] < 0 or faceNormal(cyl, 0)[1] ~= 0, "Cylinder: side faces outwards") + end + + local ge = byName["feature/feat_grid_extrusion.wrl"] + if ge then + local grid, ex = ge.meshes[1].primitives[1], ge.meshes[2].primitives[1] + t:eq(grid.attributes.POSITION.count, 12, "ElevationGrid: vertices") + t:eq(grid.faces.count, 6, "ElevationGrid: quads") + t:eq(ex.attributes.POSITION.count, 16, "Extrusion: closed cross section shares its seam") + t:eq(ex.faces.count, 14, "Extrusion: sides + caps") + local s = C.stats(ge) + t:check(near(s.hi[2], 3, 1e-6) and near(s.hi[3], 4, 1e-6), "ElevationGrid: heights and spacing") + end + + local sc = byName["feature/feat_scene.wrl"] + if sc then + t:eq(sc.meta.source.title, "feature scene", "scene: title") + t:eq(#sc.cameras, 1, "scene: viewpoint") + t:check(near(sc.cameras[1].yfov, 0.9, 1e-9) and sc.cameras[1].name == "Cam", "scene: fieldOfView") + local types = {} + for _, l in sc.lights do + types[l.type] = l + end + t:check(types.directional and types.point and types.spot, "scene: three light types") + t:check(types.point.range == 10 and near(types.spot.outerCone, 0.6, 1e-9) and near(types.spot.innerCone, 0.4, 1e-9), "scene: radius, cones") + -- the directional light's node turns -z onto its direction (0, -1, -1) + for _, n in sc.nodes do + if n.light and sc.lights[n.light].type == "directional" then + local m = Mat4.fromQuat(n.rotation) + local x, y, z = Mat4.point(m, 0, 0, -1) + t:check(near(x, 0, 1e-6) and near(y, -math.sqrt(0.5), 1e-6) and near(z, -math.sqrt(0.5), 1e-6), "scene: light direction") + end + end + t:eq(#sc.animations, 1, "scene: animation") + local a = sc.animations[1] + t:eq(a.name, "Clock", "scene: animation named after its TimeSensor") + t:eq(#a.channels, 2, "scene: translation + rotation channels") + local tr = a.channels[1].path == "translation" and a.channels[1] or a.channels[2] + t:check(near(buffer.readf32(tr.input.data, 8), 4, 1e-6), "scene: key 1 x cycleInterval 4") + -- translation keys move the outer node: key + center + t:check(near(buffer.readf32(tr.output.data, 12), 1, 1e-6) and near(buffer.readf32(tr.output.data, 16), 2, 1e-6), "scene: translation key + center") + -- PixelTexture: the first row of the file is the bottom one + local img + for _, tex in sc.textures do + img = img or tex.image + end + t:check(img and img.width == 2 and buffer.readu8(img.pixels, 2) == 255 and buffer.readu8(img.pixels, 8) == 255 and buffer.readu8(img.pixels, 9) == 0, "scene: PixelTexture pixels") + -- Switch whichChoice 1: the sphere only; LOD: the first level; Inline: part.wrl + local s = C.stats(sc) + t:check(near(s.lo[2], -3.1, 1e-6), "scene: Inline file placed") + -- center / scaleOrientation: the line set's first point (0, 0, 0) under T C R SR S -SR -C + local mover = nil + for _, pl in prims(sc) do + if pl.primitive.mode == "lines" then + mover = pl + end + end + if mover then + local sr = Mat4.axisAngle(0, 0, 1, math.deg(0.5)) + local m = Mat4.mul(Mat4.translation(1, 0, 0), Mat4.mul(Mat4.fromQuat(sr), Mat4.mul(Mat4.scaling(1, 2, 1), Mat4.mul(Mat4.fromQuat({ -sr[1], -sr[2], -sr[3], sr[4] }), Mat4.translation(-1, 0, 0))))) + local ok = true + for k = 1, 16 do + ok = ok and near(mover.matrix[k], m[k], 1e-6) + end + t:check(ok, "scene: Transform center / scaleOrientation") + end + t:eq(sc.meta.unit, 1, "scene: metres") + end +end + +-- ------------------------------------------------------------------------------------------------ writer +local function compare(a: any, b: any, label: string) + local sa, sb = C.stats(a), C.stats(b) + t:eq(sb.prims, sa.prims, label .. ": placed primitives") + t:eq(sb.polys, sa.polys, label .. ": faces") + t:eq(sb.lines, sa.lines, label .. ": line segments") + t:eq(sb.points, sa.points, label .. ": points") + if sa.prims > 0 and sa.lo[1] <= sa.hi[1] then + t:check(C.boundsNear(sa.lo, sa.hi, sb.lo, sb.hi, 1e-5), label .. ": bounds " .. C.fmt(sa.lo, sa.hi) .. " vs " .. C.fmt(sb.lo, sb.hi)) + t:check(near(sa.area, sb.area, 1e-4), string.format("%s: area %.6g / %.6g", label, sa.area, sb.area)) + end + t:eq(#b.materials, #a.materials, label .. ": materials") + for k, m in a.materials do + local m2 = b.materials[k] + if m2 then + local ok = true + for q = 1, 4 do + ok = ok and near(m.baseColor[q], m2.baseColor[q], 1e-6) + end + t:check(ok, label .. ": material " .. k .. " colour") + t:check((m.baseColorTexture == nil) == (m2.baseColorTexture == nil), label .. ": material " .. k .. " texture") + end + end + t:eq(#b.cameras, #a.cameras, label .. ": cameras") + t:eq(#b.lights, #a.lights, label .. ": lights") +end + +local rt = 0 +for i, c in Cases do + local a = scenes[i] + if a then + local files = {} + local out, err = Vrml.encode(a, { files = files, name = "rt.wrl" }) + t:check(out, c.name .. ": encode: " .. tostring(err)) + if out then + local b, e2 = decode(out, { files = files, triangulate = false }) + t:check(b, c.name .. ": re-decode: " .. tostring(e2)) + if b then + compare(a, b, c.name .. " (round trip)") + t:eq(#b.animations, #a.animations, c.name .. " (round trip): animations") + rt += 1 + end + end + end +end + +-- glTF samples through VRML: world triangles, materials, textures, cameras, lights, animation samples +local gltfScenes = {} +for i, c in GltfCases do + local g = Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }) + if not g then + continue + end + gltfScenes[i] = g + local files = {} + local out, err = Vrml.encode(g, { files = files, name = "model.wrl" }) + t:check(out, c.name .. ": encode: " .. tostring(err)) + if not out then + continue + end + local b = decode(out, { files = files }) + t:check(b, c.name .. ": decode our VRML") + if not b then + continue + end + local ga = C.stats(g) + local sb = C.stats(b) + t:check(C.boundsNear(ga.lo, ga.hi, sb.lo, sb.hi, 1e-5), c.name .. ": bounds through VRML " .. C.fmt(ga.lo, ga.hi) .. " vs " .. C.fmt(sb.lo, sb.hi)) + t:check(near(ga.area, sb.area, 1e-4), c.name .. ": area through VRML") + t:eq(sb.points, ga.points, c.name .. ": points through VRML") + t:eq(#b.cameras, #g.cameras, c.name .. ": cameras through VRML") + for k, tex in g.textures do + local t2 = b.textures[k] + if tex.data and t2 then + t:check(t2.data and buffer.tostring(t2.data) == buffer.tostring(tex.data), c.name .. ": texture " .. k .. " bytes") + end + end + -- animations: the translation / rotation / scale channels, sampled at their keys + local want = 0 + for _, a in g.animations do + for _, ch in a.channels do + if ch.path ~= "weights" then + want += 1 + end + end + end + local got = 0 + for _, a in b.animations do + got += #a.channels + end + t:eq(got, want, c.name .. ": animation channels through VRML") + rt += 1 +end +t:note("%d round trips", rt) + +-- VTK reads our files like the originals +local xc = 0 +for _, x in Xcheck do + local v = x.vtk + local src = if x.case then scenes[x.case] else (if x.gltf then gltfScenes[x.gltf] else nil) + local srcCase = if x.case then Cases[x.case] else nil + if src and not v.failed and v.actors > 0 then + local s = C.stats(src) + if not (srcCase and srcCase.primitives) then + -- our IndexedFaceSets keep polygons; VTK counts them + t:eq(v.polys, s.polys, x.name .. ": polygons (VTK reads our file)") + end + t:eq(v.verts, s.points, x.name .. ": points (VTK reads our file)") + if x.vtkTransforms and v.min and s.lo[1] <= s.hi[1] then + t:check(C.boundsNear(s.lo, s.hi, v.min, v.max, 1e-4), x.name .. ": bounds (VTK reads our file) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(v.min, v.max)) + end + xc += 1 + end +end +t:note("%d of our files read by VTK", xc) + +-- ------------------------------------------------------------------------------------------------ api, options, errors +do + local text = Cases[1].data + t:eq(F.detect(text), "vrml", "F.detect") + local s = F.load(text, { files = Cases[1].files }) + t:check(s and s.meta.source.format == "vrml", "F.load") + local gz = Deflate.gzip(text) + local sg = decode(gz :: buffer) + t:check(sg and #sg.meshes == #s.meshes, "gzipped .wrz") + local tri = decode(Cases[1].data) + t:check(tri and tri.meshes[1].primitives[1].mode == "triangles", "triangulated by default") + local seg = decode(Cases[1].data, { segments = 8 }) + t:check(seg and seg.meshes[1].primitives[1].attributes.POSITION.count < s.meshes[1].primitives[1].attributes.POSITION.count, "segments option") + local _, e1 = decode("#VRML V1.0 ascii\nSeparator { }") + t:check(e1 and e1.code == Err.UNSUPPORTED, "VRML 1.0: " .. tostring(e1)) + local _, e2 = decode("#VRML V2.0 utf8\nShape { geometry Box { size 1 1 1 }") + t:check(e2 and e2.code == Err.CORRUPT, "unclosed node: " .. tostring(e2)) + local _, e3 = decode("#VRML V2.0 utf8\nShape { appearance USE Nothing }") + t:check(e3 and e3.code == Err.CORRUPT, "USE of an undefined name: " .. tostring(e3)) + local _, e4 = decode('#VRML V2.0 utf8\nWorldInfo { title "open') + t:check(e4 and e4.code == Err.TRUNCATED, "unterminated string: " .. tostring(e4)) + local deep = "#VRML V2.0 utf8\n" .. string.rep("Group { children [ ", 300) .. string.rep("] } ", 300) + local _, e5 = decode(deep) + t:check(e5 and e5.code == Err.LIMIT, "nesting limit: " .. tostring(e5)) + local _, e6 = decode("#VRML V2.0 utf8\nShape { geometry ElevationGrid { xDimension 5000 zDimension 5000 } }", { maxVertices = 1000 }) + t:check(e6 and e6.code == Err.LIMIT, "maxVertices: " .. tostring(e6)) + local _, e7 = Vrml.encode({} :: any) + t:check(e7 and e7.code == Err.ARG, "encode junk") + -- a quad written as one polygon and read back as one + local p = Types.Scene.accessor(nil, "f32", 3, 4) + for v, xyz in { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 } } do + for k = 1, 3 do + buffer.writef32(p.data, ((v - 1) * 3 + k - 1) * 4, xyz[k]) + end + end + local faces = Types.Scene.accessor(nil, "u32", 1, 1) + buffer.writeu32(faces.data, 0, 4) + local ind = Types.Scene.accessor(nil, "u32", 1, 4) + for k = 0, 3 do + buffer.writeu32(ind.data, k * 4, k) + end + local quad = Types.Scene.fromPrimitive({ attributes = { POSITION = p }, indices = ind, faces = faces, mode = "polygons" }, "quad") + local q = decode(Vrml.encode(quad) :: buffer, { triangulate = false }) + t:check(q and q.meshes[1].primitives[1].faces.count == 1 and q.nodes[1].name == "quad", "a quad stays one polygon, names kept") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = {} + for _, c in Cases do + if #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local s = Vrml.decode(Bytes.reader(b), { files = {} }) + if s then + Vrml.encode(s) + end + return s + end, samples, { mutations = 16, keepHeader = 16 }) +end + +t:done() diff --git a/tests/model/x3d.luau b/tests/model/x3d.luau new file mode 100644 index 0000000..6a04f64 --- /dev/null +++ b/tests/model/x3d.luau @@ -0,0 +1,308 @@ +-- model/x3d tests: assimp's X3D / X3DV / X3DB test models, scenes and glTF samples written by VTK's X3D exporter and +-- by assimp's X3D exporter, and hand-written feature files (the X3D triangle / quad / line sets, ColorRGBA, +-- ProtoDeclare / ProtoInstance with SFNode defaults, PhysicalMaterial, UnlitMaterial, OrthoViewpoint, ROUTE +-- animation, UNIT, the classic encoding's header statements), against assimp's X3D reader (meshes, faces, materials, +-- world bounds) and exact expectations; .x3dv against the same model as .x3d; the writer (XML and classic): round +-- trips, and assimp reading our X3D like the originals; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/x3d.py. +local T = require("@tests/T") +local F = require("@formats") +local X3d = require("@formats/model/x3d") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local C = require("@tests/model/_vrml_common") +local Cases = require("@tests/gen/x3d_cases") +local VrmlCases = require("@tests/gen/vrml_cases") +local GltfCases = require("@tests/gen/vrml_gltf") +local Xcheck = require("@tests/gen/x3d_xcheck") +local Gltf = require("@formats/model/gltf") +local Vrml = require("@formats/model/vrml") + +local t = T.suite("x3d") +local near = C.near + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return X3d.decode(Bytes.reader(b), opts) +end + +t:eq(X3d.name, "x3d", "name") +t:eq(X3d.category, "model", "category") +t:check(X3d.caps.decode and X3d.caps.encode, "contract") + +-- assimp's own quirks (its reading is not the specification's): USE'd groups lose their parents' transforms; its X3D +-- exporter writes points and lines as 1- / 2-vertex faces (not valid IndexedFaceSet faces, dropped here) +local QUIRK = { ["assimp/X3D/ComputerKeyboard.x3d"] = "all", ["assimp-export/assimp_MeshPrimitiveModes.x3d"] = "all" } + +-- ------------------------------------------------------------------------------------------------ reference files +local scenes, byName = {}, {} +local checked = { assimp = 0, none = 0 } +for i, c in Cases do + local scene, err = decode(c.data, { files = c.files, triangulate = false }) + if string.find(c.name, "%.x3db$") then + t:check(scene == nil and err and err.code == Err.UNSUPPORTED, c.name .. ": binary X3D is UNSUPPORTED: " .. tostring(err)) + continue + end + t:check(scene, c.name .. ": decode: " .. tostring(err)) + if not scene then + continue + end + scenes[i], byName[c.name] = scene, scene + local a = c.assimp + -- (VTK's exporter leaves out: assimp then reads nothing) + local unclosed = a.meshes == 0 and not string.find(c.data, "", 1, true) + if a.skip or a.failed or unclosed or string.find(c.name, "^feature/") then + checked.none += 1 + continue + end + local s = C.stats(scene) + local quirk = QUIRK[c.name] + if quirk ~= "all" then + if quirk ~= "counts" then + t:eq(s.prims, a.meshes, c.name .. ": meshes (assimp: one per placed shape)") + end + if not c.primitives and quirk ~= "counts" then + t:eq(s.polys + s.lines + s.points, a.faces, c.name .. ": faces (assimp)") + end + t:check(#scene.materials <= a.materials, c.name .. ": materials (assimp counts one per use)") + if a.min then + t:check(C.boundsNear(s.lo, s.hi, a.min, a.max, if c.primitives then 5e-3 else 1e-5), c.name .. ": world bounds (assimp) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(a.min, a.max)) + end + end + checked.assimp += 1 +end +t:note("%d files: %d against assimp, %d without a reference", #Cases, checked.assimp, checked.none) + +-- ------------------------------------------------------------------------------------------------ exact expectations +do + local kb = byName["assimp/X3D/ComputerKeyboard.x3d"] + if kb then + local s = C.stats(kb) + t:eq(#kb.meshes, 3, "keyboard: three extrusions (the keys are USE'd)") + t:check(s.prims > 50, "keyboard: every USE placed: " .. s.prims) + t:eq(#kb.animations, 1, "keyboard: the push animation") + t:check(#kb.animations[1].channels == s.prims - 2, "keyboard: one channel per escape-button instance") + t:check(near(s.hi[3], 0.980018, 1e-5) and near(s.lo[2], -0.0002, 1e-3), "keyboard: the base under its rotation") + end + local hw, hv = byName["assimp/X3D/HelloWorld.x3d"], byName["assimp/X3DV/HelloWorld.x3dv"] + if hw and hv then + local a, b = C.stats(hw), C.stats(hv) + t:check(a.polys == b.polys and C.boundsNear(a.lo, a.hi, b.lo, b.hi, 1e-9), ".x3dv = .x3d: geometry") + t:eq(hv.materials[1].baseColor[2], hw.materials[1].baseColor[2], ".x3dv = .x3d: material") + t:check(hv.textures[1].data and hw.textures[1].data, ".x3dv / .x3d: texture from files") + t:eq(hv.meta.source.profile, "Immersive", ".x3dv: PROFILE") + t:eq(hw.meta.source.profile, "Immersive", ".x3d: profile") + t:eq(hv.meta.source.meta.title, "HelloWorld.x3d", ".x3dv: META") + t:eq(hw.meta.source.meta.creator, "Don Brutzman", ".x3d: head meta") + end + local ls = byName["assimp/X3D/IndexedLineSet.x3d"] + if ls then + local p = ls.meshes[1].primitives[1] + t:check(p.mode == "lines" and p.indices.count == 8, "IndexedLineSet: a closed polyline as 4 segments") + t:check(ls.materials[1].emissive[1] == 1, "IndexedLineSet: emissive colour") + end + + local sets = byName["feature/feat_sets.x3d"] + if sets then + local m = sets.meshes + local function tris(k: number): number + local p = m[k].primitives[1] + return if p.mode == "polygons" then p.faces.count else p.indices.count // 3 + end + t:eq(tris(1), 2, "IndexedTriangleSet") + local col = m[1].primitives[1].attributes.COLOR_0 + t:check(col and col.components == 4 and buffer.readf32(col.data, (2 * 4 + 3) * 4) == 0.5, "ColorRGBA alpha") + t:check(sets.materials[m[1].primitives[1].material].doubleSided, "solid false") + t:eq(tris(2), 3, "TriangleFanSet fanCount") + t:eq(tris(3), 3, "IndexedTriangleStripSet runs") + t:check(m[4].primitives[1].faces.count == 1 and m[4].primitives[1].indices.count == 4, "IndexedQuadSet: one quad") + t:eq(tris(5), 2, "TriangleSet") + t:check(m[6].primitives[1].mode == "lines" and m[6].primitives[1].indices.count == 6, "LineSet vertexCount") + -- strips alternate their winding: every triangle of the strip faces +z + local p = m[3].primitives[1] + local ok = true + local P = p.attributes.POSITION + local function v(i: number): (number, number) + local k = buffer.readu32(p.indices.data, i * 4) + return buffer.readf32(P.data, k * 12), buffer.readf32(P.data, k * 12 + 4) + end + local at = 0 + for f = 0, p.faces.count - 1 do + local ax, ay = v(at) + local bx, by = v(at + 1) + local cx, cy = v(at + 2) + ok = ok and (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > 0 + at += buffer.readu32(p.faces.data, f * 4) + end + t:check(ok, "IndexedTriangleStripSet: counter-clockwise triangles") + end + + local pr = byName["feature/feat_proto.x3d"] + if pr then + local s = C.stats(pr) + t:check(C.boundsNear(s.lo, s.hi, { -1.1, -2, -0.5 }, { 1.1, 5, 0.5 }, 1e-6), "protos: instances placed and sized " .. C.fmt(s.lo, s.hi)) + t:eq(pr.meta.unit, 0.01, "UNIT length") + t:eq(pr.meta.source.meta.title, "protos", "head meta") + local kinds = {} + for _, m in pr.materials do + if m.extensions and m.extensions.KHR_materials_unlit then + kinds.unlit = m + elseif m.metallic == 0.25 then + kinds.physical = m + elseif m.baseColor[3] == 1 and m.baseColor[1] == 0 then + kinds.default = m + end + end + t:check(kinds.physical and kinds.physical.roughness == 0.75, "PhysicalMaterial") + t:check(kinds.unlit and kinds.unlit.baseColor[2] == 1, "UnlitMaterial") + t:check(kinds.default ~= nil, "SFNode field default (the proto's appearance)") + t:eq(#pr.materials, 3, "the default appearance is shared by both instances") + local cam = pr.cameras[1] + t:check(cam and cam.type == "orthographic" and cam.xmag == 2 and cam.ymag == 1, "OrthoViewpoint") + local a = pr.animations[1] + t:check(a and a.name == "Clock" and #a.channels == 1 and a.channels[1].path == "rotation", "ROUTE elements -> animation") + t:check(a and near(buffer.readf32(a.channels[1].input.data, 8), 2, 1e-6), "key times x cycleInterval") + -- quaternion keys stay on one hemisphere (0, pi, 2 pi about y) + local q = a and a.channels[1].output + t:check(q and buffer.readf32(q.data, 2 * 16 + 12) < 0, "rotation keys continuous") + end + local cl = byName["feature/feat_classic.x3dv"] + if cl then + local s = C.stats(cl) + t:check(C.boundsNear(s.lo, s.hi, { 1, 2, 3 }, { 2, 3, 4 }, 1e-6), "classic: DEF Transform") + t:eq(cl.meta.unit, 0.001, "classic: UNIT") + t:eq(cl.meta.source.components[1], "Geometry2D:1", "classic: COMPONENT") + t:eq(cl.meta.source.meta.title, "classic", "classic: META") + t:eq(cl.meshes[1].primitives[1].attributes.COLOR_0.components, 4, "classic: ColorRGBA") + end +end + +-- ------------------------------------------------------------------------------------------------ writer +local function compare(a: any, b: any, label: string) + local sa, sb = C.stats(a), C.stats(b) + t:eq(sb.prims, sa.prims, label .. ": placed primitives") + t:eq(sb.polys, sa.polys, label .. ": faces") + t:eq(sb.lines, sa.lines, label .. ": line segments") + t:eq(sb.points, sa.points, label .. ": points") + if sa.prims > 0 and sa.lo[1] <= sa.hi[1] then + t:check(C.boundsNear(sa.lo, sa.hi, sb.lo, sb.hi, 1e-5), label .. ": bounds") + t:check(near(sa.area, sb.area, 1e-4), label .. ": area") + end + t:eq(#b.materials, #a.materials, label .. ": materials") + t:eq(#b.cameras, #a.cameras, label .. ": cameras") + t:eq(#b.lights, #a.lights, label .. ": lights") + t:eq(#b.animations, #a.animations, label .. ": animations") + for k, cam in a.cameras do + t:eq(b.cameras[k].type, cam.type, label .. ": camera type") + end +end +local rt = 0 +for i, c in Cases do + local a = scenes[i] + if a then + for _, enc in { "xml", "x3dv" } do + local files = {} + local out, err = X3d.encode(a, { files = files, encoding = enc :: any }) + t:check(out, c.name .. ": encode " .. enc .. ": " .. tostring(err)) + local b = out and decode(out, { files = files, triangulate = false }) + t:check(b, c.name .. ": decode our " .. enc) + if b then + compare(a, b, c.name .. " (" .. enc .. ")") + rt += 1 + end + end + end +end +t:note("%d round trips", rt) + +-- assimp reads our X3D like the source +local sources: { [string]: { any } } = { xcase = {}, wcase = {}, xgltf = {} } +for i, c in Cases do + sources.xcase[i] = { scenes[i], c } +end +for i, c in VrmlCases do + sources.wcase[i] = { Vrml.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false }), c } +end +for i, c in GltfCases do + sources.xgltf[i] = { Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }), c } +end +-- assimp loses its place in the tree after an empty (a leaf node: an empty, a locator) +local function hasEmpty(scene: any): boolean + for _, n in scene.nodes do + if #n.children == 0 and not n.mesh and not n.camera and not n.light then + return true + end + end + return false +end +local xc, skipped = 0, 0 +for _, x in Xcheck do + local a = x.assimp + local kind = if x.xcase then "xcase" elseif x.wcase then "wcase" else "xgltf" + local src = sources[kind][x[kind]] + if src and src[1] and (a.failed or a.meshes == 0) and hasEmpty(src[1]) then + skipped += 1 + elseif src and src[1] and not a.failed then + local s = C.stats(src[1]) + t:eq(a.meshes, s.prims, x.name .. ": meshes (assimp reads our file)") + t:eq(a.faces, s.polys + s.lines + s.points, x.name .. ": faces (assimp reads our file)") + -- (shared meshes are written once and USE'd: assimp places USE'd nodes without their parents' transforms) + -- (MotionCaptureROM: assimp misplaces this deep hierarchy; an independent evaluation of our file's transforms + -- agrees with ours) + local deep = src[2].name == "assimp/MotionCaptureROM.WRL" + if a.min and s.lo[1] <= s.hi[1] and s.prims == s.unique and not deep then + t:check(C.boundsNear(s.lo, s.hi, a.min, a.max, 1e-4), x.name .. ": bounds (assimp reads our file) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(a.min, a.max)) + end + xc += 1 + elseif src and src[1] then + t:check(false, x.name .. ": assimp cannot read our file (" .. src[2].name .. ")") + end +end +t:note("%d of our files read by assimp (%d skipped: empty nodes)", xc, skipped) + +-- ------------------------------------------------------------------------------------------------ api, errors +do + local hw = Cases[2] + t:eq(F.detect(hw.data), "x3d", "F.detect .x3d") + t:eq(F.detect(Cases[5].data), "x3d", "F.detect .x3dv") + local s = F.load(hw.data, { files = hw.files }) + t:check(s and s.meta.source.format == "x3d", "F.load") + local x3dv = F.save(s, nil, { format = "x3dv" }) + t:check(x3dv and buffer.readstring(x3dv, 0, 5) == "#X3D ", "F.save format x3dv: the classic encoding") + local xml = F.save(s, nil, { format = "x3d" }) + t:check(xml and string.find(buffer.tostring(xml), "") + t:check(e1 and (e1.code == Err.TRUNCATED or e1.code == Err.CORRUPT), "mismatched XML: " .. tostring(e1)) + local _, e2 = decode("") + t:check(e2 and e2.code == Err.CORRUPT, "not X3D: " .. tostring(e2)) + -- VTK leaves the root element open: read anyway + local open = decode("\n") + t:check(open and #open.meshes == 1, "an unclosed root (VTK's exporter)") + local _, e3 = X3d.encode({} :: any) + t:check(e3 and e3.code == Err.ARG, "encode junk") + -- containerField and USE in XML + local u = decode([[ + + ]]) + local us = u and C.stats(u) + t:check(us and #u.meshes == 2 and us.prims == 3 and near(us.hi[1], 6, 1e-9) and near(us.hi[2], 2, 1e-6), "USE / containerField / Switch in XML") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = {} + for _, c in Cases do + if #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local s = X3d.decode(Bytes.reader(b), { files = {} }) + if s then + X3d.encode(s) + end + return s + end, samples, { mutations = 16, keepHeader = 16 }) +end + +t:done() diff --git a/tools/fixtures/_vrml_encode.luau b/tools/fixtures/_vrml_encode.luau new file mode 100644 index 0000000..f3cabba --- /dev/null +++ b/tools/fixtures/_vrml_encode.luau @@ -0,0 +1,54 @@ +-- tools/fixtures/_vrml_encode: run by tools/fixtures/vrml.py and x3d.py (luau CLI, repo root): decodes every VRML / +-- X3D case and glTF sample with our readers and writes it back with our writers, printing "\t" lines for +-- VTK (.wrl) and assimp (.x3d) to read back. Files: case_.wrl, gltf_.wrl, xcase_.x3d, xgltf_.x3d. +local Vrml = require("@formats/model/vrml") +local X3d = require("@formats/model/x3d") +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/vrml_cases") +local GltfCases = require("@tests/gen/vrml_gltf") +local ok, X3dCases = pcall(require, "@tests/gen/x3d_cases") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(b: buffer): string + local out = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + out[i + 1] = HEX[buffer.readu8(b, i)] + end + return table.concat(out) +end + +local function both(scene: any, wrl: string, x3d: string) + local a = Vrml.encode(scene) + if a then + print(wrl .. "\t" .. hex(a)) + end + local b = X3d.encode(scene) + if b then + print(x3d .. "\t" .. hex(b)) + end +end + +for i, c in Cases do + local scene = Vrml.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false }) + if scene then + both(scene, string.format("case_%d.wrl", i), string.format("wcase_%d.x3d", i)) + end +end +for i, c in GltfCases do + local scene = Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }) + if scene then + both(scene, string.format("gltf_%d.wrl", i), string.format("xgltf_%d.x3d", i)) + end +end +if ok and type(X3dCases) == "table" then + for i, c in X3dCases do + local scene = X3d.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false }) + if scene then + both(scene, string.format("xcase_%d.wrl", i), string.format("xcase_%d.x3d", i)) + end + end +end diff --git a/tools/fixtures/_vrml_ref.py b/tools/fixtures/_vrml_ref.py new file mode 100644 index 0000000..2a0b137 --- /dev/null +++ b/tools/fixtures/_vrml_ref.py @@ -0,0 +1,241 @@ +# Shared helpers for tools/fixtures/vrml.py and x3d.py: VTK (nixpkgs python3 vtk) as the VRML97 reference reader and +# as a writer of more .wrl / .x3d inputs, assimp's X3D reader for .x3d, and the hand-written feature files. +# vtk_read(ctx, paths) -> [ { actors, polys, lines, verts, points, min, max } | { failed } ] (vtkVRMLImporter) +# vtk_export(ctx, outdir, gltf_paths) -> [ (name, wrl path, x3d path) ] (vtkVRMLExporter / vtkX3DExporter scenes) +# FEATURES: { name: VRML97 text } covering PROTO, DEF / USE, Switch, LOD, primitives, per-face colours, separate +# indices, ElevationGrid, Extrusion, ROUTE animation, lights, viewpoints, Inline, PixelTexture +import json + +VTK_READ = r""" +import json, os, sys, vtk +vtk.vtkObject.GlobalWarningDisplayOff() + +def read(p): + imp = vtk.vtkVRMLImporter(); imp.SetFileName(p) + rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); imp.SetRenderWindow(rw) + imp.Update() + acts = imp.GetRenderer().GetActors(); acts.InitTraversal() + out = {"actors": 0, "polys": 0, "lines": 0, "verts": 0, "points": 0} + lo, hi = [1e30] * 3, [-1e30] * 3 + for i in range(acts.GetNumberOfItems()): + a = acts.GetNextActor() + m = a.GetMapper() + if not m: + continue + m.Update() + d = m.GetInput() + if d is None or d.GetNumberOfPoints() == 0: + continue + out["actors"] += 1 + out["polys"] += d.GetNumberOfPolys() + d.GetNumberOfStrips() + out["lines"] += d.GetNumberOfLines() + out["verts"] += d.GetNumberOfVerts() + out["points"] += d.GetNumberOfPoints() + # tight world bounds: every point through the actor's matrix (GetBounds boxes the local bounds) + mat = a.GetMatrix() + pts = d.GetPoints() + for j in range(d.GetNumberOfPoints()): + p = pts.GetPoint(j) + w = mat.MultiplyPoint((p[0], p[1], p[2], 1.0)) + for k in range(3): + lo[k] = min(lo[k], w[k]); hi[k] = max(hi[k], w[k]) + if out["actors"]: + out["min"], out["max"] = lo, hi + return out + +# one child process per file: vtkVRMLImporter crashes on some valid files +res = [] +for p in json.loads(sys.stdin.read()): + r, w = os.pipe() + pid = os.fork() + if pid == 0: + os.close(r) + try: + data = json.dumps(read(p)) + except Exception: + data = json.dumps({"failed": True}) + os.write(w, data.encode()) + os._exit(0) + os.close(w) + chunks = [] + while True: + b = os.read(r, 65536) + if not b: + break + chunks.append(b) + os.close(r) + _, status = os.waitpid(pid, 0) + try: + res.append(json.loads(b"".join(chunks).decode()) if status == 0 else {"failed": True, "crashed": True}) + except ValueError: + res.append({"failed": True}) +print("RESULT " + json.dumps(res)) +""" + +VTK_EXPORT = r""" +import json, os, sys, vtk +vtk.vtkObject.GlobalWarningDisplayOff() +args = json.loads(sys.stdin.read()) +out, gltfs = args["out"], args["gltf"] +made = [] + +def export(ren, name): + rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); rw.AddRenderer(ren) + ren.ResetCamera() + w = vtk.vtkVRMLExporter(); w.SetRenderWindow(rw); w.SetFileName(os.path.join(out, name + ".wrl")); w.Write() + x = vtk.vtkX3DExporter(); x.SetRenderWindow(rw); x.SetFileName(os.path.join(out, name + ".x3d")); x.SetBinary(0); x.Write() + made.append(name) + +def actor(src, pos=(0, 0, 0), scale=(1, 1, 1), rot=(0, 0, 0), color=None, scalars=False): + m = vtk.vtkPolyDataMapper(); m.SetInputConnection(src.GetOutputPort()) + if not scalars: + m.ScalarVisibilityOff() + a = vtk.vtkActor(); a.SetMapper(m); a.SetPosition(*pos); a.SetScale(*scale) + a.RotateX(rot[0]); a.RotateY(rot[1]); a.RotateZ(rot[2]) + if color: + a.GetProperty().SetColor(*color) + return a + +# 1. primitives as polygon meshes, transformed, coloured, one with point scalars +ren = vtk.vtkRenderer() +s = vtk.vtkSphereSource(); s.SetThetaResolution(16); s.SetPhiResolution(8) +ren.AddActor(actor(s, (1, 2, 3), (2, 2, 2), (30, 0, 0), (0.9, 0.2, 0.1))) +c = vtk.vtkConeSource(); c.SetResolution(12) +ren.AddActor(actor(c, (-3, 0, 1), (1, 3, 1), (0, 45, 10), (0.2, 0.8, 0.3))) +cube = vtk.vtkCubeSource(); cube.SetXLength(2); cube.SetYLength(1); cube.SetZLength(0.5) +ren.AddActor(actor(cube, (0, -2, 0), (1, 1, 1), (0, 0, 20), (0.3, 0.3, 0.9))) +keep = [vtk.vtkSphereSource(), vtk.vtkSphereSource(), vtk.vtkCubeSource()] +el = vtk.vtkElevationFilter(); el.SetInputConnection(keep[0].GetOutputPort()); el.SetLowPoint(0, -0.5, 0); el.SetHighPoint(0, 0.5, 0) +ren.AddActor(actor(el, (4, 4, 0), scalars=True)) +light = vtk.vtkLight(); light.SetPosition(5, 5, 5); light.SetFocalPoint(0, 0, 0); light.SetColor(1, 0.9, 0.8) +ren.AddLight(light) +export(ren, "vtk_shapes") + +# 2. lines and points +ren = vtk.vtkRenderer() +ls = vtk.vtkLineSource(); ls.SetPoint1(0, 0, 0); ls.SetPoint2(3, 1, 2); ls.SetResolution(5) +ren.AddActor(actor(ls, (1, 0, 0), color=(1, 1, 0))) +pts = vtk.vtkPointSource(); pts.SetNumberOfPoints(40); pts.SetRadius(2); pts.SetCenter(0, 5, 0) +ren.AddActor(actor(pts)) +ren.AddActor(actor(keep[2], (0, 0, -4))) +export(ren, "vtk_lines_points") + +# 3. a textured plane (PixelTexture) and a strip mesh +ren = vtk.vtkRenderer() +pl = vtk.vtkPlaneSource(); pl.SetResolution(3, 2) +img = vtk.vtkImageCanvasSource2D(); img.SetScalarTypeToUnsignedChar(); img.SetNumberOfScalarComponents(3); img.SetExtent(0, 7, 0, 3, 0, 0) +img.SetDrawColor(200, 30, 30); img.FillBox(0, 7, 0, 3); img.SetDrawColor(20, 30, 200); img.FillBox(0, 3, 0, 1); img.Update() +tex = vtk.vtkTexture(); tex.SetInputConnection(img.GetOutputPort()) +a = actor(pl, (0, 0, 1), (4, 2, 1)); a.SetTexture(tex) +ren.AddActor(a) +strip = vtk.vtkStripper(); strip.SetInputConnection(keep[1].GetOutputPort()) +ren.AddActor(actor(strip, (0, 3, 0))) +export(ren, "vtk_texture_strips") + +# 4. glTF sample models through VTK's glTF importer +for g in gltfs: + try: + imp = vtk.vtkGLTFImporter(); imp.SetFileName(g) + rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); imp.SetRenderWindow(rw); imp.Update() + name = "vtk_gltf_" + os.path.splitext(os.path.basename(g))[0] + export(imp.GetRenderer(), name) + except Exception: + pass +print("RESULT " + json.dumps(made)) +""" + + +def vtk_xform_ok(data): + """False when vtkVRMLImporter's transforms are wrong for the file: it ignores center and scaleOrientation""" + import re + return not re.search(rb"\b(center|scaleOrientation)\s+[-+\d.]", data) + + +def _run(ctx, code, arg): + out = ctx.python(["vtk"], code, input=json.dumps(arg).encode()).decode("utf-8", "replace") + for line in out.split("\n"): + if line.startswith("RESULT "): + return json.loads(line[7:]) + raise RuntimeError("vtk script printed no result") + + +def vtk_read(ctx, paths): + return _run(ctx, VTK_READ, paths) if paths else [] + + +def vtk_export(ctx, outdir, gltfs): + return _run(ctx, VTK_EXPORT, {"out": outdir, "gltf": gltfs}) + + +FEATURES = { + "feat_proto_use.wrl": """#VRML V2.0 utf8 +PROTO Brick [ field SFVec3f size 1 1 1 field SFColor col 1 0 0 exposedField SFVec3f where 0 0 0 ] { + Transform { translation IS where children Shape { + appearance Appearance { material Material { diffuseColor IS col } } + geometry Box { size IS size } } } +} +DEF A Brick { size 2 1 1 col 0 1 0 where 0 0 0 } +Brick { where 3 0 0 } +Transform { translation 0 3 0 children [ DEF S Shape { geometry IndexedFaceSet { + coord DEF C Coordinate { point [ 0 0 0, 1 0 0, 1 1 0, 0 1 0 ] } coordIndex [ 0 1 2 3 -1 ] } } ] } +Transform { translation 0 5 0 rotation 0 0 1 1.5708 children USE S } +""", + "feat_indices.wrl": """#VRML V2.0 utf8 +# separate normal / colour / texture indices, per-face colours, ccw FALSE, solid FALSE +Shape { + appearance Appearance { material Material { diffuseColor 0.5 0.5 0.5 transparency 0.25 shininess 0.5 specularColor 1 1 1 } } + geometry IndexedFaceSet { + solid FALSE ccw FALSE + coord Coordinate { point [ 0 0 0, 2 0 0, 2 2 0, 0 2 0, 0 0 2, 2 0 2 ] } + coordIndex [ 0 1 2 3 -1, 0 4 5 1 -1 ] + normal Normal { vector [ 0 0 1, 0 -1 0 ] } + normalPerVertex FALSE normalIndex [ 0 1 ] + color Color { color [ 1 0 0, 0 0 1 ] } + colorPerVertex FALSE + texCoord TextureCoordinate { point [ 0 0, 1 0, 1 1, 0 1 ] } + texCoordIndex [ 0 1 2 3 -1, 3 2 1 0 -1 ] + } +} +Shape { geometry IndexedFaceSet { + coord Coordinate { point [ 5 0 0, 6 0 0, 6 1 0, 5 1 0 ] } + coordIndex [ 0 1 2 -1 0 2 3 ] + color Color { color [ 1 0 0, 0 1 0, 0 0 1, 1 1 1 ] } colorIndex [ 3 2 1 -1 0 1 2 -1 ] } } +""", + "feat_primitives.wrl": """#VRML V2.0 utf8 +Transform { translation -4 0 0 children Shape { geometry Box { size 1 2 3 } } } +Transform { translation 0 0 0 children Shape { geometry Sphere { radius 1.5 } } } +Transform { translation 4 0 0 children Shape { geometry Cone { bottomRadius 1 height 3 } } } +Transform { translation 8 0 0 scale 2 1 1 children Shape { geometry Cylinder { radius 0.5 height 4 } } } +""", + "feat_grid_extrusion.wrl": """#VRML V2.0 utf8 +Shape { geometry ElevationGrid { xDimension 4 zDimension 3 xSpacing 1 zSpacing 2 + height [ 0 1 0 1, 1 2 1 0, 0 0 1 3 ] } } +Transform { translation 6 0 0 children Shape { geometry Extrusion { + crossSection [ 1 1, 1 -1, -1 -1, -1 1, 1 1 ] spine [ 0 0 0, 0 1 0, 1 2 0, 2 2 0 ] scale [ 1 1, 0.5 0.5, 0.5 0.5, 1 1 ] } } } +""", + "feat_scene.wrl": """#VRML V2.0 utf8 +WorldInfo { title "feature scene" info [ "made for formats-luau" ] } +DEF Cam Viewpoint { position 0 1 8 orientation 0 1 0 0.3 fieldOfView 0.9 description "front" } +DEF Sun DirectionalLight { direction 0 -1 -1 intensity 0.8 color 1 1 0.9 } +DEF Bulb PointLight { location 1 2 3 radius 10 } +DEF Spot SpotLight { location 0 5 0 direction 0 -1 0 cutOffAngle 0.6 beamWidth 0.4 } +DEF Sw Switch { whichChoice 1 choice [ + Shape { geometry Box { } } + Transform { translation 0 2 0 children Shape { geometry Sphere { radius 0.5 } } } ] } +LOD { range [ 10 ] level [ Shape { geometry Box { size 0.5 0.5 0.5 } } Shape { geometry Sphere { } } ] } +DEF Mover Transform { center 1 0 0 scaleOrientation 0 0 1 0.5 scale 1 2 1 children [ + Shape { geometry IndexedLineSet { coord Coordinate { point [ 0 0 0, 1 0 0, 1 1 0 ] } coordIndex [ 0 1 2 -1 ] color Color { color [ 1 0 0, 0 1 0, 0 0 1 ] } } } + Shape { geometry PointSet { coord Coordinate { point [ 0 0 1, 1 0 1 ] } } } ] } +DEF Clock TimeSensor { cycleInterval 4 loop TRUE } +DEF Path PositionInterpolator { key [ 0 0.5 1 ] keyValue [ 0 0 0, 0 2 0, 0 0 0 ] } +DEF Turn OrientationInterpolator { key [ 0 1 ] keyValue [ 0 1 0 0, 0 1 0 3.14 ] } +ROUTE Clock.fraction_changed TO Path.set_fraction +ROUTE Clock.fraction_changed TO Turn.set_fraction +ROUTE Path.value_changed TO Mover.set_translation +ROUTE Turn.value_changed TO Mover.set_rotation +Shape { appearance Appearance { texture PixelTexture { image 2 2 3 0xFF0000 0x00FF00 0x0000FF 0xFFFFFF } } geometry Box { } } +Inline { url [ "part.wrl" ] } +""", +} +# the Inline target of feat_scene.wrl +INLINE = {"part.wrl": "#VRML V2.0 utf8\nTransform { translation 0 -3 0 children Shape { geometry Box { size 4 0.2 4 } } }\n"} diff --git a/tools/fixtures/vrml.py b/tools/fixtures/vrml.py new file mode 100644 index 0000000..c5673a2 --- /dev/null +++ b/tools/fixtures/vrml.py @@ -0,0 +1,99 @@ +# VRML97 fixtures (tools/fixtures.py): assimp's WRL test models (test/models/WRL, read from the nixpkgs assimp source, +# never committed; assimp itself is built without its VRML reader), scenes and glTF sample models written by VTK's +# vtkVRMLExporter, and the hand-written feature files of tools/fixtures/_vrml_ref.py, with VTK's vtkVRMLImporter as +# the reference (polygons, lines, world bounds). Then our encoder's output (tools/fixtures/_vrml_encode.luau) read back +# by VTK. +# tests/gen/vrml_cases.luau { name, data, files = { name -> bytes }, vtk, primitives (bool: tessellated shapes) } +# tests/gen/vrml_gltf.luau glTF sample models for the writer round trips: { name, data, files } +# tests/gen/vrml_xcheck.luau { name, case?, gltf?, vtk } +import importlib.util, os, re + +INPUTS = ["src/Formats/codecs/model/Vrml", "src/Formats/model/vrml", "tests/fixtures/gltf", "tools/fixtures/_vrml_ref.py", + "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", "tools/fixtures/_vrml_encode.luau"] + +GLTF = ["Box", "BoxTextured", "BoxVertexColors", "Cameras", "MeshPrimitiveModes", "SimpleMeshes", "AnimatedTriangle", "InterpolationTest", + "NegativeScaleTest", "TextureCoordinateTest", "MultiUVTest"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def primitives(data): + return bool(re.search(rb"\b(Box|Sphere|Cone|Cylinder|Extrusion|ElevationGrid|Text)\s*\{|<(Box|Sphere|Cone|Cylinder|Extrusion|ElevationGrid|Text)\b", data)) + + +def gltf_picks(ctx): + gl = os.path.join(ctx.root, "tests", "fixtures", "gltf") + picks = [] + for model in GLTF: + d0 = os.path.join(gl, model) + if not os.path.isdir(d0): + continue + for variant in ("glTF", "glTF-Embedded", "glTF-Binary"): + d = os.path.join(d0, variant) + if not os.path.isdir(d): + continue + mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")] + if mains: + picks.append({"name": model + "/" + variant, "path": os.path.join(d, mains[0]), "data": open(os.path.join(d, mains[0]), "rb").read(), + "files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}}) + break + return picks + + +def generate(ctx): + M = load(ctx, "_model_ref") + Fbx = load(ctx, "fbx") + R = load(ctx, "_vrml_ref") + tmp = M.tempdir() + cases = [] + src = os.path.join(Fbx.assimp_src(ctx), "test", "models", "WRL") + for f in sorted(os.listdir(src)): + if f.lower().endswith(".wrl"): + files = {} + if f == "HelloWorld.wrl": + files["earth-topo.png"] = open(os.path.join(src, "earth-topo.png"), "rb").read() + cases.append({"name": "assimp/" + f, "path": os.path.join(src, f), "files": files}) + picks = gltf_picks(ctx) + for name in R.vtk_export(ctx, tmp, [p["path"] for p in picks if p["path"].endswith((".gltf", ".glb"))]): + cases.append({"name": "vtk/" + name + ".wrl", "path": os.path.join(tmp, name + ".wrl"), "files": {}}) + for name, text in sorted(R.FEATURES.items()): + p = os.path.join(tmp, name) + with open(p, "w") as f: + f.write(text) + cases.append({"name": "feature/" + name, "path": p, "files": dict(R.INLINE)}) + for name, text in R.INLINE.items(): + with open(os.path.join(tmp, name), "w") as f: + f.write(text) + refs = R.vtk_read(ctx, [c["path"] for c in cases]) + for c, v in zip(cases, refs): + c["data"] = open(c["path"], "rb").read() + c["vtk"] = v + c["primitives"] = primitives(c["data"]) + c["vtkTransforms"] = R.vtk_xform_ok(c["data"]) + del c["path"] + ctx.emit("vrml_cases", cases) + for p in picks: + del p["path"] + ctx.emit("vrml_gltf", picks) + + # VTK reads our output + ours = M.luau_encode(ctx, "tools/fixtures/_vrml_encode.luau") + xtmp = M.tempdir() + names = sorted(n for n in ours if n.endswith(".wrl")) + for name, data in ours.items(): + with open(os.path.join(xtmp, name), "wb") as f: + f.write(data) + refs = R.vtk_read(ctx, [os.path.join(xtmp, n) for n in names]) + out = [] + for n, v in zip(names, refs): + e = {"name": n, "vtk": v, "vtkTransforms": R.vtk_xform_ok(ours[n])} + m = re.match(r"(case|gltf)_(\d+)\.wrl$", n) + if m: + e[m.group(1)] = int(m.group(2)) + out.append(e) + ctx.emit("vrml_xcheck", out) diff --git a/tools/fixtures/x3d.py b/tools/fixtures/x3d.py new file mode 100644 index 0000000..0826081 --- /dev/null +++ b/tools/fixtures/x3d.py @@ -0,0 +1,135 @@ +# X3D fixtures (tools/fixtures.py): assimp's X3D / X3DV / X3DB test models (test/models/X3D*, read from the nixpkgs +# assimp source, never committed), scenes and glTF sample models written by VTK's vtkX3DExporter, glTF sample models +# written by assimp's X3D exporter, and hand-written feature files (below), with assimp's X3D reader as the reference +# (`assimp info -r`: meshes, faces, materials; world bounds from its PreTransformVertices export). Then our encoder's +# X3D output (tools/fixtures/_vrml_encode.luau) read back by assimp. +# tests/gen/x3d_cases.luau { name, data, files = { name -> bytes }, assimp, primitives (bool) } +# tests/gen/x3d_xcheck.luau { name, case? / gltf? / wcase?, assimp } +import importlib.util, os, re, subprocess + +INPUTS = ["src/Formats/codecs/model/Vrml", "src/Formats/model/x3d", "src/Formats/model/vrml", "tests/fixtures/gltf", + "tools/fixtures/_vrml_ref.py", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", "tools/fixtures/vrml.py", + "tools/fixtures/_vrml_encode.luau"] + +FEATURES = { + "feat_sets.x3d": """ + + + + + + + + + + +""", + "feat_proto.x3d": """ + + + + + + + + + + + + + + + + + + + + + + +""", + "feat_classic.x3dv": """#X3D V3.3 utf8 +PROFILE Interchange +COMPONENT Geometry2D:1 +META "title" "classic" +UNIT length millimetre 0.001 +DEF Root Transform { translation 1 2 3 children [ + Shape { appearance Appearance { material Material { diffuseColor 0 1 0 } } + geometry IndexedFaceSet { coord Coordinate { point [ 0 0 0 1 0 0 1 1 0 0 1 0 ] } coordIndex [ 0 1 2 3 -1 ] + color ColorRGBA { color [ 1 0 0 1, 0 1 0 1, 0 0 1 1, 1 1 1 0.5 ] } } } + Shape { geometry IndexedTriangleSet { index [ 0 1 2 ] coord Coordinate { point [ 0 0 1 1 0 1 0 1 1 ] } } } +] } +""", +} + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def reference(ctx, M, Fbx, path, tmp): + a = M.assimp_info(ctx, [path], raw=True)[0] + if not a.get("failed"): + a.pop("min", None) + a.pop("max", None) + a.update(Fbx.assimp_extra(ctx, path)) + a.update(Fbx.ptv_bounds(ctx, path, tmp)) + return a + + +def generate(ctx): + M = load(ctx, "_model_ref") + Fbx = load(ctx, "fbx") + R = load(ctx, "_vrml_ref") + V = load(ctx, "vrml") + tmp = M.tempdir() + cases = [] + root = os.path.join(Fbx.assimp_src(ctx), "test", "models") + for sub in ("X3D", "X3DV", "X3DB"): + d = os.path.join(root, sub) + for f in sorted(os.listdir(d)): + if f.lower().endswith((".x3d", ".x3dv", ".x3db")): + files = {} + if f.startswith("HelloWorld"): + files["earth-topo.png"] = open(os.path.join(d, "earth-topo.png"), "rb").read() + cases.append({"name": "assimp/%s/%s" % (sub, f), "path": os.path.join(d, f), "files": files}) + picks = V.gltf_picks(ctx) + for name in R.vtk_export(ctx, tmp, [p["path"] for p in picks]): + cases.append({"name": "vtk/" + name + ".x3d", "path": os.path.join(tmp, name + ".x3d"), "files": {}}) + for p in picks: + out = os.path.join(tmp, "assimp_" + p["name"].split("/")[0] + ".x3d") + try: + ctx.nix("assimp", ["assimp", "export", p["path"], out, "-fx3d"]) + except subprocess.CalledProcessError: + continue + cases.append({"name": "assimp-export/" + os.path.basename(out), "path": out, "files": dict(p["files"])}) + for name, text in sorted(FEATURES.items()): + path = os.path.join(tmp, name) + with open(path, "w") as f: + f.write(text) + cases.append({"name": "feature/" + name, "path": path, "files": {}}) + for c in cases: + c["data"] = open(c["path"], "rb").read() + c["primitives"] = V.primitives(c["data"]) + c["assimp"] = reference(ctx, M, Fbx, c["path"], tmp) if c["path"].endswith(".x3d") else {"skip": True} + del c["path"] + ctx.emit("x3d_cases", cases) + + # assimp reads our X3D output + ours = M.luau_encode(ctx, "tools/fixtures/_vrml_encode.luau") + xtmp = M.tempdir() + out = [] + for name in sorted(n for n in ours if n.endswith(".x3d")): + path = os.path.join(xtmp, name) + with open(path, "wb") as f: + # assimp 6 cannot read quoted MFString urls (url='"a.png"', which the X3D encoding requires) + f.write(re.sub(rb'url=""([^&"]*)""', rb'url="\1"', ours[name])) + e = {"name": name, "assimp": reference(ctx, M, Fbx, path, xtmp)} + m = re.match(r"(xcase|xgltf|wcase)_(\d+)\.x3d$", name) + if m: + e[m.group(1)] = int(m.group(2)) + out.append(e) + ctx.emit("x3d_xcheck", out)