-- model/3mf tests: lib3mf's suite and SDK files, assimp and trimesh exports, against lib3mf, assimp and trimesh. -- Fixtures: tools/fixtures/3mf.py. local T = require("@tests/T") local ThreeMf = require("@rosetta/model/3mf") local Bytes = require("@rosetta/core/Bytes") local Err = require("@rosetta/core/Err") local Types = require("@rosetta/Types") local Zip = require("@rosetta/containers/Zip") local Cases = require("@tests/gen/3mf_cases") local Xcheck = require("@tests/gen/3mf_xcheck") local t = T.suite("3mf") local function decode(data: any, opts: any?): (any, any) local b = if type(data) == "string" then buffer.fromstring(data) else data return ThreeMf.decode(Bytes.reader(b), opts) end t:eq(ThreeMf.name, "3mf", "name") t:eq(ThreeMf.category, "model", "category") t:check(ThreeMf.caps.decode and ThreeMf.caps.encode and ThreeMf.extensions[1] == "3mf", "contract") local function near(a: number, b: number, eps: number): boolean return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) end local function metrics(scene: any): (number, number, { number }, { number }) local tris, area = 0, 0 local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } for _, pl in Types.Scene.flatten(scene) do local p = pl.primitive local m = pl.matrix local pos = p.attributes.POSITION local W = {} for i = 0, pos.count - 1 do local x, y, z = buffer.readf32(pos.data, i * 12), buffer.readf32(pos.data, i * 12 + 4), buffer.readf32(pos.data, i * 12 + 8) local w = { 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[i] = w end local ind = p.indices for k = 0, ind.count // 3 - 1 do local a, b, c = W[buffer.readu32(ind.data, k * 12)], W[buffer.readu32(ind.data, k * 12 + 4)], W[buffer.readu32(ind.data, k * 12 + 8)] for _, v in { a, b, c } do for q = 1, 3 do lo[q] = math.min(lo[q], v[q]) hi[q] = math.max(hi[q], v[q]) end end local e1 = { b[1] - a[1], b[2] - a[2], b[3] - a[3] } local e2 = { c[1] - a[1], c[2] - a[2], c[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] area += math.sqrt(x * x + y * y + z * z) / 2 tris += 1 end end return tris, area, lo, hi end local function boundsNear(lo: { number }, hi: { number }, rmin: { number }, rmax: { number }): boolean local ext = 0 for q = 1, 3 do ext = math.max(ext, rmax[q] - rmin[q]) end local eps = 1e-5 * math.max(ext, 1e-6) for q = 1, 3 do if math.abs(lo[q] - rmin[q]) > eps or math.abs(hi[q] - rmax[q]) > eps then return false end end return true end local UNIT_NAMES = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 } local refCount, rejectedOk, unsupported = 0, 0, 0 local byIndex = {} for i, c in Cases do local scene, err = decode(c.data) byIndex[i] = scene local ref = c.lib3mf if ref.failed then -- lib3mf rejects these (strict checks we do not make); it is enough not to throw rejectedOk += 1 continue end if not scene and err and err.code == Err.UNSUPPORTED and string.find(c.name, "SecureContent", 1, true) then unsupported += 1 -- encrypted / wrapped model parts (the secure content extension) continue end t:check(scene, c.name .. ": decode: " .. tostring(err)) if not scene then continue end t:eq(scene.meta.source.unit, ref.unit, c.name .. ": unit") t:eq(scene.meta.unit, UNIT_NAMES[ref.unit], c.name .. ": meta.unit") t:eq(scene.meta.up, "z", c.name .. ": up") local tris, area, lo, hi = metrics(scene) t:eq(tris, ref.triangles, c.name .. ": world triangles (lib3mf)") t:check(near(area, ref.area, 1e-5), string.format("%s: area %.7g, lib3mf %.7g", c.name, area, ref.area)) if ref.min then t:check(boundsNear(lo, hi, ref.min, ref.max), c.name .. ": bounds (lib3mf)") end t:check(#scene.textures <= ref.textures, c.name .. ": textures <= lib3mf's texture2d count") refCount += 1 -- trimesh reads build items and components the same way (it skips degenerate input) local tm = c.trimesh if tm and not tm.failed and tm.faces == tris and tm.faces > 0 then t:check(near(area, tm.area, 1e-5), c.name .. ": area (trimesh)") end end t:note("%d files: %d against lib3mf, %d rejected by lib3mf (decoded without throwing), %d secure content (UNSUPPORTED)", #Cases, refCount, rejectedOk, unsupported) local xchecked, withTextures = 0, 0 for _, x in Xcheck do local c = Cases[x.case] local ref = c.lib3mf if not byIndex[x.case] then continue end t:check(not x.lib3mf.failed, x.name .. " (" .. c.name .. "): lib3mf reads our file: " .. tostring(x.lib3mf.failed)) if not x.lib3mf.failed then t:eq(x.lib3mf.triangles, ref.triangles, c.name .. ": our file's triangles (lib3mf)") t:check(near(x.lib3mf.area, ref.area, 1e-5), string.format("%s: our file's area %.7g vs %.7g (lib3mf)", c.name, x.lib3mf.area, ref.area)) if ref.min then t:check(boundsNear(x.lib3mf.min, x.lib3mf.max, ref.min, ref.max), c.name .. ": our file's bounds (lib3mf)") end t:eq(x.lib3mf.unit, ref.unit, c.name .. ": our file's unit (lib3mf)") -- the material groups made it: textures, colour groups, base materials local scene = byIndex[x.case] local tex, col = 0, 0 for _, m in scene.meshes do for _, p in m.primitives do if p.attributes.TEXCOORD_0 and p.material and scene.materials[p.material].baseColorTexture then tex += 1 elseif p.attributes.COLOR_0 then col += 1 end end end t:check((tex == 0) == (x.lib3mf.texGroups == 0), c.name .. ": our texture groups (lib3mf)") t:check(tex == 0 or x.lib3mf.textures > 0, c.name .. ": our textures (lib3mf)") t:eq(x.lib3mf.colorGroups, col, c.name .. ": our colour groups (lib3mf)") t:eq(x.lib3mf.baseGroups, if #scene.materials > 0 then 1 else 0, c.name .. ": our base material group (lib3mf)") if tex > 0 then withTextures += 1 end end t:check(not x.assimp.failed or c.assimp.failed, c.name .. ": assimp reads our file") if not x.trimesh.failed and x.trimesh.faces > 0 and not c.trimesh.failed and c.trimesh.faces == x.trimesh.faces then t:check(near(x.trimesh.area, c.trimesh.area, 1e-5), c.name .. ": our file's area (trimesh)") end xchecked += 1 end t:note("%d of our files read back by lib3mf / assimp / trimesh like the originals (%d with textures)", xchecked, withTextures) local rts = 0 for i, c in Cases do local scene = byIndex[i] if scene and not c.lib3mf.failed then local out, err = ThreeMf.encode(scene) t:check(out, c.name .. ": encode: " .. tostring(err)) local back, berr = decode(out) t:check(back, c.name .. ": decode ours: " .. tostring(berr)) local a1, b1 = metrics(scene) local a2, b2 = metrics(back) t:eq(a2, a1, c.name .. ": round trip triangles") t:check(near(b2, b1, 1e-6), c.name .. ": round trip area") t:eq(back.meta.unit, scene.meta.unit, c.name .. ": round trip unit") local used = 0 for _, m in back.materials do if m.baseColorTexture then used += 1 t:check(back.textures[m.baseColorTexture.texture].data ~= nil, c.name .. ": texture bytes") end end rts += 1 end end t:note("%d round trips through our writer", rts) local function package(model: string, extra: { [string]: string }?): buffer local w = Zip.writer() w:add("[Content_Types].xml", '', { method = "store" }) w:add("_rels/.rels", '', { method = "store" }) w:add("3D/3dmodel.model", model, { method = "store" }) for k, v in extra or {} do w:add(k, v, { method = "store" }) end return (w:finish()) end local HEAD = '' local QUAD = '%s' local samples = {} local function f32s(acc: any): { number } local out = {} for i = 0, acc.count * acc.components - 1 do out[i + 1] = buffer.readf32(acc.data, i * 4) end return out end do -- per-corner colours: vertex 0 has two different colours -> split local xml = string.format(HEAD, "inch") .. 'quad & co' .. '' .. '' .. string.format(QUAD, '') .. '' .. '' local pkg = package(xml) table.insert(samples, pkg) local s, err = decode(pkg) t:check(s, "colours: " .. tostring(err)) t:eq(s.meta.unit, 0.0254, "colours: inch") t:eq(s.meta.metadata.Title, "quad & co", "colours: metadata") t:eq(#s.meshes, 1, "colours: one mesh") local prim = s.meshes[1].primitives[1] t:eq(#s.meshes[1].primitives, 1, "colours: one primitive") -- corners: (0,red) (1,green) (2,blue) | (0,blue) (2,blue) (3,blue) -> 5 vertices t:eq(prim.attributes.POSITION.count, 5, "colours: vertex 0 split by colour") local col = f32s(prim.attributes.COLOR_0) t:eq(col[1], 1, "colours: red r (linear)") t:eq(col[2], 0, "colours: red g") t:check(math.abs(col[8] - 128 / 255) < 1e-6, "colours: alpha kept linear") t:eq(s.nodes[1].matrix[13], 10, "colours: transform tx") t:eq(s.nodes[1].matrix[15], 30, "colours: transform tz") local back = decode((ThreeMf.encode(s))) local col2 = f32s(back.meshes[1].primitives[1].attributes.COLOR_0) local same = #col2 == #col for i = 1, #col do same = same and math.abs(col[i] - col2[i]) < 1e-6 end t:check(same, "colours: round trip exact (8-bit sRGB)") t:eq(back.meta.metadata.Title, "quad & co", "colours: metadata round trip") t:eq(back.meta.source.unit, "inch", "colours: unit round trip") end do -- base materials, object defaults, composite, multiproperties, textures local png = "\137PNG\r\n\26\nfake" local xml = string.format(HEAD, "millimeter") .. "" .. '' .. '' .. '' .. '' .. '' .. '' .. string.format(QUAD, '' -- object default: red .. '' -- texture .. '' -- composite .. '' -- multi -> its first layer (base 1 = "half") .. '') -- half .. "" local pkg = package(xml, { ["3D/Texture/a.png"] = png }) table.insert(samples, pkg) local s, err = decode(pkg) t:check(s, "materials: " .. tostring(err)) local prims = s.meshes[1].primitives t:eq(#prims, 4, "materials: red, texture, composite, half (multi shares half)") local red = s.materials[prims[1].material] t:eq(red.name, "red", "materials: object default pid / pindex") t:eq(red.baseColor[1], 1, "materials: red") t:eq(red.extras["3mf"].displaycolor, "#FF0000", "materials: display colour kept") local tex = s.materials[prims[2].material] t:check(tex.baseColorTexture and s.textures[tex.baseColorTexture.texture], "materials: texture material") local tx = s.textures[tex.baseColorTexture.texture] t:eq(buffer.tostring(tx.data), png, "materials: texture bytes from the package") t:eq(tx.mime, "image/png", "materials: texture mime") t:eq(tx.sampler.wrapS, "clamp", "materials: tilestyleu") t:eq(tx.sampler.wrapT, "mirror", "materials: tilestylev") t:eq(tx.sampler.filter, "nearest", "materials: filter") local uv = f32s(prims[2].attributes.TEXCOORD_0) t:eq(uv[4], 0.75, "materials: v flipped to the top-left origin") local comp = s.materials[prims[3].material] local half = (128 / 255 + 0.055) / 1.055 t:check(math.abs(comp.baseColor[1] - (((1 + 128 / 255) / 2 + 0.055) / 1.055) ^ 2.4) < 1e-6, "materials: composite blends in sRGB") t:eq(s.materials[prims[4].material].name, "half", "materials: multiproperties -> first layer") t:eq(prims[4].indices.count, 6, "materials: multi and base 'half' share a primitive") t:check(math.abs(s.materials[prims[4].material].baseColor[1] - half ^ 2.4) < 1e-6, "materials: sRGB -> linear") local out = assert(ThreeMf.encode(s)) local back = assert(decode(out)) local tm = nil for _, m in back.materials do if m.baseColorTexture then tm = m end end t:check(tm and buffer.tostring(back.textures[tm.baseColorTexture.texture].data) == png, "materials: texture round trip") t:eq(back.textures[1].sampler.wrapS, "clamp", "materials: sampler round trip") local _, a1 = metrics(s) local _, a2 = metrics(back) t:check(near(a1, a2, 1e-6), "materials: area round trip") local names = {} for _, m in back.materials do if m.name then names[m.name] = true end end t:check(names.red and names.half, "materials: base names round trip") end do -- components, another model part through p:path, nested transforms local part = string.format(HEAD, "millimeter") .. "" .. string.format(QUAD, '') .. "" local xml = string.format(HEAD, "centimeter") .. "" .. '' .. string.format(QUAD, '') .. "" .. '' .. '' .. '' local pkg = package(xml, { ["3D/other.model"] = part }) table.insert(samples, pkg) local s, err = decode(pkg) t:check(s, "components: " .. tostring(err)) t:eq(#s.roots, 2, "components: two build items") t:eq(#s.meshes, 2, "components: meshes shared between instances") t:eq(s.nodes[s.roots[1]].name, "group", "components: node names") t:eq(#s.nodes[s.roots[1]].children, 2, "components: children") local tris, area, lo, hi = metrics(s) t:eq(tris, 6, "components: world triangles") t:check(near(area, 2 * (2 + 1), 1e-9), "components: world area") t:check(lo[1] == 0 and hi[1] == 6 and hi[3] == 1, "components: nested transforms") t:eq(s.meta.unit, 0.01, "components: centimetre") -- the writer flattens the hierarchy into build items local back = assert(decode((ThreeMf.encode(s)))) local tris2, area2, lo2, hi2 = metrics(back) t:eq(tris2, 6, "components: flattened round trip triangles") t:check(near(area2, area, 1e-9) and lo2[1] == 0 and hi2[1] == 6 and hi2[3] == 1, "components: flattened round trip bounds") t:eq(back.meta.source.unit, "centimeter", "components: unit round trip") -- a unit 3MF lacks: scaled into millimetres s.meta.unit = 0.5 local scaled = assert(decode((ThreeMf.encode(s)))) local _, _, _, hi3 = metrics(scaled) t:eq(scaled.meta.source.unit, "millimeter", "units: millimetres when the scene's unit is not a 3MF unit") t:check(math.abs(hi3[1] - 3000) < 1e-3, "units: positions scaled through the build transforms") t:check(select(2, ThreeMf.encode(s, { unit = "parsec" :: any })).code == Err.ARG, "units: bad opts.unit") end do -- a Scene built by hand: strips, fans, polygons, vertex colours + texture coordinates, an unplaced mesh local s = Types.Scene.new() local pos = Types.Scene.accessor(nil, "f32", 3, 4) for i, v in { 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0 } do buffer.writef32(pos.data, (i - 1) * 4, v) end local faces = Types.Scene.accessor(nil, "u32", 1, 1) buffer.writeu32(faces.data, 0, 4) local col = Types.Scene.accessor(nil, "unorm8", 3, 4) buffer.fill(col.data, 0, 255) s.meshes = { { primitives = { { attributes = { POSITION = pos }, mode = "triangle_strip" }, { attributes = { POSITION = pos }, mode = "triangle_fan", material = 1 } } }, { primitives = { { attributes = { POSITION = pos, COLOR_0 = col }, mode = "polygons", faces = faces }, { attributes = { POSITION = pos }, mode = "points" } } }, } s.materials = { Types.Scene.material("m") } s.nodes = { { children = { 2 }, mesh = 1, translation = { 0, 0, 5 } }, { children = {}, mesh = 2, scale = { 2, 2, 2 } } } s.roots = { 1 } local out, err = ThreeMf.encode(s, { level = 0 }) t:check(out, "scene: encode " .. tostring(err)) table.insert(samples, out) local back = assert(decode(out)) local tris, area, _, hi = metrics(back) t:eq(tris, 6, "scene: strip + fan + polygon triangles (points skipped)") t:check(near(area, 2 + 4, 1e-9), "scene: area with node transforms") t:eq(hi[3], 5, "scene: parent translation applied to the child") t:eq(#back.roots, 2, "scene: one build item per placed mesh") local m2 = back.meshes[back.nodes[back.roots[2]].mesh] t:check(m2.primitives[1].attributes.COLOR_0 ~= nil, "scene: vertex colours as a colour group") t:check(select(2, ThreeMf.encode({} :: any)).code == Err.ARG, "encode: not a scene") end do local _, e1 = decode("not a zip at all") t:check(e1 and e1.code ~= nil, "errors: not a zip") local w = Zip.writer() w:add("hello.txt", "hi") local _, e2 = decode((w:finish())) t:eq(e2 and e2.code, Err.CORRUPT, "errors: no model part") local bad = string.format(HEAD, "millimeter") .. '' .. string.format(QUAD, '') .. "" local _, e3 = decode(package(bad)) t:eq(e3 and e3.code, Err.CORRUPT, "errors: vertex index out of range") local cyc = string.format(HEAD, "millimeter") .. '' local _, e4 = decode(package(cyc)) t:eq(e4 and e4.code, Err.CORRUPT, "errors: component cycle") local _, e5 = decode(package(string.format(HEAD, "millimeter") .. "")) t:eq(e5 and e5.code, Err.CORRUPT, "errors: build item without an object") local _, e6 = decode(package(string.format(HEAD, "millimeter") .. '' .. string.format(QUAD, "") .. ""), { maxVertices = 2 }) t:eq(e6 and e6.code, Err.LIMIT, "errors: maxVertices") table.insert(samples, package(bad)) table.insert(samples, package(cyc)) t:eq(ThreeMf.sniff(Bytes.reader(package(bad))), 0.95, "sniff: a 3MF package") t:eq(ThreeMf.sniff(Bytes.reader((w:finish()))), 0, "sniff: another zip") t:eq(ThreeMf.sniff(Bytes.reader(buffer.fromstring("solid x"))), 0, "sniff: not a zip") end do for _, c in Cases do if #c.data < 20000 then table.insert(samples, c.data) end end t:fuzz("decode", function(b: buffer) local s = ThreeMf.decode(Bytes.reader(b)) if s then ThreeMf.encode(s) end return s end, samples, { mutations = 12 }) end t:done()