ws-3d2/3mf: model/3mf read / write (core, materials extension: base / colour / texture2d groups, composite, multiproperties; components, production p:path parts, units, metadata); tests against lib3mf 2.5 (its test suite), assimp, trimesh, our output read back by all three; bench lines

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 09:33:43 -05:00
1 parent 75c677074a
commit e87102202e
10 files changed
+1805

No files matched your search

+12
View File
@@ -194,6 +194,18 @@ local list: { Entry } = {
return require("@formats/audio/wav")
end,
},
{
name = "3mf",
category = "model",
path = "model/3mf",
extensions = { "3mf" },
mime = { "model/3mf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "containers/Zip" },
caps = { decode = true, encode = true, materials = true, vertexColors = true, textures = true, units = true },
load = function()
return require("@formats/model/3mf")
end,
},
{
name = "gltf",
category = "model",
+598
View File
@@ -0,0 +1,598 @@
--!strict
-- model/3mf/Read: a 3MF package (an OPC zip) -> Scene. The root model part from _rels/.rels (fallback: the first
-- *.model under 3D/), other model parts referenced by the production extension's p:path (components and build items),
-- core resources (objects with mesh vertices / triangles, components with transforms), the materials extension
-- (basematerials, colorgroup, texture2d + texture2dgroup, compositematerials blended into one colour per entry,
-- multiproperties resolved through their first layer), build items with transforms -> root nodes, metadata, the unit.
-- Triangles are grouped into one primitive per property (a base material, a colour group, a texture group); colour and
-- texture groups give per-corner COLOR_0 / TEXCOORD_0, so vertices are split where corners of one vertex differ.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Xml = require("@formats/codecs/Xml")
local Zip = require("@formats/containers/Zip")
local Read = {}
local REL_MODEL = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"
local UNITS = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 }
Read.UNITS = UNITS
local WRAP = { wrap = "repeat", mirror = "mirror", clamp = "clamp", none = "clamp" }
local MAX_DEPTH = 64
local localName = Xml.localName
-- an attribute by local name (namespaced attributes such as p:path)
local function attr(node: any, name: string): string?
local a = node.attrs
local v = a[name]
if v ~= nil then
return v
end
for k, x in next, a do
if type(k) == "string" and localName(k) == name then
return x
end
end
return nil
end
local function int(s: string?): number?
local n = if s then tonumber(s) else nil
if n and n == math.floor(n) and n >= 0 then
return n
end
return nil
end
-- "#RRGGBB" / "#RRGGBBAA" -> { r, g, b, a } sRGB 0..1
local function hexColor(s: string?): { number }?
if type(s) ~= "string" then
return nil
end
local h = string.match(s, "^%s*#(%x+)%s*$")
if not h or (#h ~= 6 and #h ~= 8) then
return nil
end
local function c(i: number): number
return (tonumber(string.sub(h :: string, i, i + 1), 16) :: number) / 255
end
return { c(1), c(3), c(5), if #h == 8 then c(7) else 1 }
end
Read.hexColor = hexColor
function Read.toLinear(c: number): number
if c <= 0.04045 then
return c / 12.92
end
return ((c + 0.055) / 1.055) ^ 2.4
end
local toLinear = Read.toLinear
-- "m00 m01 m02 m10 ... m32" (3MF row-vector convention) -> a column-major glTF matrix, nil for identity / invalid
local function transform(s: string?): ({ number }?, boolean)
if not s then
return nil, true
end
local v = {}
for w in string.gmatch(s, "%S+") do
local n = tonumber(w)
if not n or n ~= n or n == math.huge or n == -math.huge then
return nil, false
end
table.insert(v, n)
end
if #v ~= 12 then
return nil, false
end
local m = { v[1], v[2], v[3], 0, v[4], v[5], v[6], 0, v[7], v[8], v[9], 0, v[10], v[11], v[12], 1 }
for i = 1, 16 do
if m[i] ~= Types.Scene.IDENTITY[i] then
return m, true
end
end
return nil, true
end
local function normPath(p: string): string
p = string.gsub(p, "\\", "/")
p = string.gsub(p, "^/+", "")
return p
end
-- one model part parsed into its resources and build
type Model = { path: string, unit: string?, metadata: { [string]: string }, res: { [number]: any }, items: { any }, required: string? }
local function parseModel(text: string, path: string, opts: any): (Model?, Err.Err?)
local doc, err = Xml.decode(text, { parents = false })
if not doc then
return nil, err
end
local root = (doc :: any).root
if not root or localName(root.name) ~= "model" then
return nil, Err.new(Err.CORRUPT, path .. ": the root element is not <model>")
end
local maxV = opts.maxVertices or 2 ^ 25
local model: Model = { path = path, unit = attr(root, "unit"), metadata = {}, res = {}, items = {}, required = attr(root, "requiredextensions") }
local resources: any = nil
local build: any = nil
for _, ch in Xml.children(root) do
local ln = localName(ch.name)
if ln == "metadata" then
local n = attr(ch, "name")
if n then
model.metadata[n] = Xml.text(ch)
end
elseif ln == "resources" then
resources = ch
elseif ln == "build" then
build = ch
end
end
local total = 0
if resources then
for _, r in Xml.children(resources) do
local ln = localName(r.name)
local id = int(attr(r, "id"))
if id == nil then
continue
end
if ln == "object" then
local o: any = { kind = "object", id = id, name = attr(r, "name"), type = attr(r, "type") or "model", pid = int(attr(r, "pid")), pindex = int(attr(r, "pindex")), partnumber = attr(r, "partnumber") }
local mesh = Xml.child(r, "mesh")
local comps = Xml.child(r, "components")
if mesh then
local verts = Xml.child(mesh, "vertices")
local tris = Xml.child(mesh, "triangles")
local vl = if verts then Xml.children(verts, "vertex") else {}
local tl = if tris then Xml.children(tris, "triangle") else {}
total += #vl + #tl * 3
if total > maxV then
return nil, Err.new(Err.LIMIT, "more than " .. maxV .. " vertices / corners")
end
local nv = #vl
local pos = table.create(nv * 3, 0)
for i, v in vl do
local a = v.attrs
local x, y, z = tonumber(a.x), tonumber(a.y), tonumber(a.z)
if not x or not y or not z then
return nil, Err.new(Err.CORRUPT, "object " .. id .. ": bad vertex " .. i)
end
pos[i * 3 - 2], pos[i * 3 - 1], pos[i * 3] = x, y, z
end
local nt = #tl
local tv = table.create(nt * 3, 0)
local tp = table.create(nt * 4, -1) -- pid, p1, p2, p3 (-1 = none)
for i, tri in tl do
local a = tri.attrs
local v1, v2, v3 = int(a.v1), int(a.v2), int(a.v3)
if not v1 or not v2 or not v3 or v1 >= nv or v2 >= nv or v3 >= nv then
return nil, Err.new(Err.CORRUPT, "object " .. id .. ": triangle " .. i .. " has a bad vertex index")
end
tv[i * 3 - 2], tv[i * 3 - 1], tv[i * 3] = v1, v2, v3
local b = i * 4 - 4
local pid, p1, p2, p3 = int(a.pid), int(a.p1), int(a.p2), int(a.p3)
tp[b + 1] = pid or -1
tp[b + 2] = p1 or -1
tp[b + 3] = p2 or p1 or -1
tp[b + 4] = p3 or p1 or -1
end
o.positions, o.tv, o.tp, o.nt = pos, tv, tp, nt
end
if comps then
o.components = {}
for _, c in Xml.children(comps, "component") do
local oid = int(attr(c, "objectid"))
local m, ok = transform(attr(c, "transform"))
if oid and ok then
table.insert(o.components, { objectid = oid, matrix = m, path = attr(c, "path") })
end
end
end
model.res[id] = o
elseif ln == "basematerials" then
local items = {}
for _, b in Xml.children(r, "base") do
table.insert(items, { name = attr(b, "name"), color = hexColor(attr(b, "displaycolor")) or { 1, 1, 1, 1 }, hex = attr(b, "displaycolor") })
end
model.res[id] = { kind = "base", id = id, items = items }
elseif ln == "colorgroup" then
local items = {}
for _, c in Xml.children(r, "color") do
table.insert(items, hexColor(attr(c, "color")) or { 1, 1, 1, 1 })
end
model.res[id] = { kind = "color", id = id, items = items }
elseif ln == "texture2d" then
model.res[id] = { kind = "texture", id = id, path = attr(r, "path"), contenttype = attr(r, "contenttype"), tileu = attr(r, "tilestyleu"), tilev = attr(r, "tilestylev"), filter = attr(r, "filter") }
elseif ln == "texture2dgroup" then
local uvs = {}
for _, c in Xml.children(r, "tex2coord") do
table.insert(uvs, tonumber(attr(c, "u")) or 0)
table.insert(uvs, tonumber(attr(c, "v")) or 0)
end
model.res[id] = { kind = "texgroup", id = id, texid = int(attr(r, "texid")), uvs = uvs, count = #uvs // 2 }
elseif ln == "compositematerials" then
local mats = {}
for w in string.gmatch(attr(r, "matindices") or "", "%S+") do
table.insert(mats, tonumber(w) or 0)
end
local items = {}
for _, c in Xml.children(r, "composite") do
local vals = {}
for w in string.gmatch(attr(c, "values") or "", "%S+") do
table.insert(vals, tonumber(w) or 0)
end
table.insert(items, vals)
end
model.res[id] = { kind = "composite", id = id, matid = int(attr(r, "matid")), matindices = mats, items = items }
elseif ln == "multiproperties" then
local pids = {}
for w in string.gmatch(attr(r, "pids") or "", "%S+") do
table.insert(pids, tonumber(w) or -1)
end
local items = {}
for _, c in Xml.children(r, "multi") do
local ix = {}
for w in string.gmatch(attr(c, "pindices") or "", "%S+") do
table.insert(ix, tonumber(w) or 0)
end
table.insert(items, ix)
end
model.res[id] = { kind = "multi", id = id, pids = pids, items = items }
end
end
end
if build then
for _, it in Xml.children(build, "item") do
local oid = int(attr(it, "objectid"))
local m, ok = transform(attr(it, "transform"))
if oid and ok then
table.insert(model.items, { objectid = oid, matrix = m, path = attr(it, "path"), partnumber = attr(it, "partnumber") })
end
end
end
return model, nil
end
-- the root model part's path
local function rootPath(zip: any): string?
local rels = zip:readString("_rels/.rels")
if rels then
local doc = Xml.decode(rels, { parents = false })
if doc then
for _, rel in Xml.descendants((doc :: any).root or doc, "Relationship") do
local t, target = attr(rel, "Type"), attr(rel, "Target")
if t and target and (t == REL_MODEL or string.find(t, "/3dmodel$")) then
return normPath(target)
end
end
end
end
for _, e in zip:list() do
if not e.isDir and string.find(string.lower(e.name), "%.model$") then
return e.name
end
end
return nil
end
function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?)
local rootP = rootPath(zip)
if not rootP then
return nil, Err.new(Err.CORRUPT, "no 3D model part in the package")
end
local models: { [string]: Model } = {}
local function getModel(path: string): (Model?, Err.Err?)
local p = normPath(path)
local m = models[p]
if m then
return m, nil
end
local text, err = zip:readString(p)
if not text then
return nil, err or Err.new(Err.CORRUPT, "missing model part " .. p)
end
if string.sub(text, 1, 5) == "%3McF" then
return nil, Err.new(Err.UNSUPPORTED, "secure content extension: " .. p .. " is encrypted / wrapped")
end
local mm, perr = parseModel(text, p, opts)
if not mm then
return nil, perr
end
models[p] = mm
return mm, nil
end
local root, rerr = getModel(rootP)
if not root then
return nil, rerr
end
local scene = Types.Scene.new()
local unitName = root.unit or "millimeter"
scene.meta.up = "z"
scene.meta.unit = UNITS[unitName] or 1e-3
scene.meta.metadata = root.metadata
scene.meta.source = { format = "3mf", unit = unitName, part = rootP, requiredExtensions = root.required }
-- textures and materials (shared across model parts by part path + resource id)
local texCache: { [string]: number } = {}
local function texture(model: Model, id: number): number?
local key = model.path .. "#" .. id
if texCache[key] then
return texCache[key]
end
local r = model.res[id]
if not r or r.kind ~= "texture" or type(r.path) ~= "string" then
return nil
end
local data = zip:read(normPath(r.path))
local tex: Types.Texture = {
name = r.path,
data = data,
mime = r.contenttype,
uri = r.path,
sampler = { wrapS = WRAP[r.tileu or "wrap"] or "repeat", wrapT = WRAP[r.tilev or "wrap"] or "repeat", filter = if r.filter == "nearest" or r.filter == "linear" then r.filter else nil },
extras = { ["3mf"] = { id = id, tilestyleu = r.tileu, tilestylev = r.tilev, filter = r.filter } },
}
table.insert(scene.textures, tex)
texCache[key] = #scene.textures
return #scene.textures
end
local matCache: { [string]: number } = {}
local function addMaterial(key: string, make: () -> Types.Material): number
local i = matCache[key]
if i then
return i
end
table.insert(scene.materials, make())
matCache[key] = #scene.materials
return #scene.materials
end
local function colorMaterial(name: string?, c: { number }, extras: any): Types.Material
local m = Types.Scene.material(name)
m.baseColor = { toLinear(c[1]), toLinear(c[2]), toLinear(c[3]), c[4] }
m.metallic = 0
m.roughness = 1
if c[4] < 1 then
m.alphaMode = "blend"
end
m.extras = { ["3mf"] = extras }
return m
end
-- property of one corner -> (group key, material index?, kind, resource, index)
local function resolve(model: Model, pid: number, p: number, depth: number?): (string, number?, string, any, number)
local r = model.res[pid]
if not r or p < 0 then
return "none", nil, "none", nil, 0
end
local k = r.kind
if k == "base" then
local item = r.items[p + 1]
if not item then
return "none", nil, "none", nil, 0
end
local key = "b" .. model.path .. "#" .. pid .. ":" .. p
return key, addMaterial(key, function()
return colorMaterial(item.name, item.color, { group = pid, index = p, displaycolor = item.hex })
end), "base", r, p
elseif k == "color" then
return "c" .. model.path .. "#" .. pid, nil, "color", r, p
elseif k == "texgroup" then
local ti = r.texid and texture(model, r.texid)
local mat: number? = nil
if ti then
local mk = "t" .. model.path .. "#" .. (r.texid :: number)
mat = addMaterial(mk, function()
local m = Types.Scene.material("texture " .. tostring(r.texid))
m.metallic = 0
m.roughness = 1
m.baseColorTexture = { texture = ti :: number }
m.extras = { ["3mf"] = { texture = r.texid } }
return m
end)
end
return "t" .. model.path .. "#" .. pid, mat, "tex", r, p
elseif k == "composite" then
local item = r.items[p + 1]
local base = r.matid and model.res[r.matid]
if not item or not base or base.kind ~= "base" then
return "none", nil, "none", nil, 0
end
local key = "x" .. model.path .. "#" .. pid .. ":" .. p
return key, addMaterial(key, function()
local c, sum = { 0, 0, 0, 0 }, 0
for j, w in item do
local b = base.items[(r.matindices[j] or 0) + 1]
if b then
for q = 1, 4 do
c[q] += b.color[q] * w
end
sum += w
end
end
if sum > 0 then
for q = 1, 4 do
c[q] /= sum
end
else
c = { 1, 1, 1, 1 }
end
return colorMaterial("composite " .. pid .. ":" .. p, c, { composite = pid, index = p })
end), "base", r, p
elseif k == "multi" and (depth or 0) < 1 then
local item = r.items[p + 1]
local first = r.pids[1]
if item and first then
return resolve(model, first, item[1] or 0, 1)
end
end
return "none", nil, "none", nil, 0
end
-- one Scene mesh per (part, object) with a mesh
local meshCache: { [string]: number } = {}
local function buildMesh(model: Model, o: any): number?
local key = model.path .. "#" .. o.id
local cached = meshCache[key]
if cached ~= nil then
return if cached > 0 then cached else nil
end
local groups: { [string]: any } = {}
local order: { any } = {}
local pos, tv, tp = o.positions, o.tv, o.tp
for t = 0, o.nt - 1 do
local pid = tp[t * 4 + 1]
local ps = { tp[t * 4 + 2], tp[t * 4 + 3], tp[t * 4 + 4] }
if pid < 0 then
pid = o.pid or -1
if ps[1] < 0 then
local d = o.pindex or (if pid >= 0 then 0 else -1)
ps = { d, d, d }
end
end
local gkey, mat, kind, res, _ = resolve(model, pid, ps[1])
local g = groups[gkey]
if not g then
g = { kind = kind, res = res, material = mat, vmap = {}, pos = {}, attr = {}, idx = {}, n = 0 }
groups[gkey] = g
table.insert(order, g)
end
for c = 1, 3 do
local v = tv[t * 3 + c]
local vk = v
local pc = 0
if kind == "color" or kind == "tex" then
pc = ps[c]
local cnt = if kind == "color" then #res.items else res.count
if pc < 0 or pc >= cnt then
pc = ps[1]
end
if pc < 0 or pc >= cnt then
pc = 0
end
vk = v * (cnt + 1) + pc
end
local ni = g.vmap[vk]
if not ni then
ni = g.n
g.n += 1
g.vmap[vk] = ni
table.insert(g.pos, pos[v * 3 + 1])
table.insert(g.pos, pos[v * 3 + 2])
table.insert(g.pos, pos[v * 3 + 3])
if kind == "color" then
local col = res.items[pc + 1] or { 1, 1, 1, 1 }
table.insert(g.attr, toLinear(col[1]))
table.insert(g.attr, toLinear(col[2]))
table.insert(g.attr, toLinear(col[3]))
table.insert(g.attr, col[4])
elseif kind == "tex" then
table.insert(g.attr, res.uvs[pc * 2 + 1] or 0)
table.insert(g.attr, 1 - (res.uvs[pc * 2 + 2] or 0))
end
end
table.insert(g.idx, ni)
end
end
local mesh: Types.Mesh = { name = o.name, primitives = {}, extras = { ["3mf"] = { id = o.id, part = model.path, type = o.type, partnumber = o.partnumber } } }
for _, g in order do
local n = g.n
local pa = Types.Scene.accessor(nil, "f32", 3, n)
for i, x in g.pos do
buffer.writef32(pa.data, (i - 1) * 4, x)
end
local ia = Types.Scene.accessor(nil, "u32", 1, #g.idx)
for i, x in g.idx do
buffer.writeu32(ia.data, (i - 1) * 4, x)
end
local prim: Types.Primitive = { attributes = { POSITION = pa }, indices = ia, mode = "triangles", material = g.material }
if g.kind == "color" then
local ca = Types.Scene.accessor(nil, "f32", 4, n)
for i, x in g.attr do
buffer.writef32(ca.data, (i - 1) * 4, x)
end
prim.attributes.COLOR_0 = ca
prim.extras = { ["3mf"] = { colorgroup = g.res.id } }
elseif g.kind == "tex" then
local ua = Types.Scene.accessor(nil, "f32", 2, n)
for i, x in g.attr do
buffer.writef32(ua.data, (i - 1) * 4, x)
end
prim.attributes.TEXCOORD_0 = ua
prim.extras = { ["3mf"] = { texture2dgroup = g.res.id } }
end
table.insert(mesh.primitives, prim)
end
if #mesh.primitives == 0 then
meshCache[key] = 0
return nil
end
table.insert(scene.meshes, mesh)
meshCache[key] = #scene.meshes
return #scene.meshes
end
-- nodes: one per object instance (build items and components)
local nodeCount = 0
local maxNodes = opts.maxNodes or 2 ^ 20
local instantiate: (model: Model, oid: number, matrix: { number }?, depth: number, extra: any) -> (number?, Err.Err?)
function instantiate(model: Model, oid: number, matrix: { number }?, depth: number, extra: any): (number?, Err.Err?)
if depth > MAX_DEPTH then
return nil, Err.new(Err.CORRUPT, "components nested deeper than " .. MAX_DEPTH .. " (a cycle?)")
end
nodeCount += 1
if nodeCount > maxNodes then
return nil, Err.new(Err.LIMIT, "more than " .. maxNodes .. " object instances")
end
local o = model.res[oid]
if not o or o.kind ~= "object" then
return nil, Err.new(Err.CORRUPT, "no object " .. oid .. " in " .. model.path)
end
local node: Types.Node = { name = o.name, children = {}, matrix = matrix, extras = { ["3mf"] = extra or { objectid = oid } } }
table.insert(scene.nodes, node)
local index = #scene.nodes
if o.positions then
node.mesh = buildMesh(model, o)
end
if o.components then
for _, c in o.components do
local m: Model? = model
if c.path then
local mm, err = getModel(c.path)
if not mm then
return nil, err
end
m = mm
end
local child, err = instantiate(m :: Model, c.objectid, c.matrix, depth + 1, { objectid = c.objectid, path = c.path })
if not child then
return nil, err
end
table.insert(node.children, child)
end
end
return index, nil
end
for _, it in root.items do
local m: Model? = root
if it.path then
local mm, err = getModel(it.path)
if not mm then
return nil, err
end
m = mm
end
local idx, err = instantiate(m :: Model, it.objectid, it.matrix, 0, { objectid = it.objectid, path = it.path, partnumber = it.partnumber, item = true })
if not idx then
return nil, err
end
table.insert(scene.roots, idx)
end
return scene, nil
end
function Read.open(r: any): (any, Err.Err?)
return Zip.open(r)
end
return Read
+417
View File
@@ -0,0 +1,417 @@
--!strict
-- model/3mf/Write: Scene -> a 3MF package. One mesh object per Scene mesh (every triangle primitive: triangles,
-- strips, fans, polygons fan-split; points and lines are skipped), one build item per node with a mesh, carrying the
-- node's world matrix (the hierarchy is flattened). Materials go into one basematerials group (sRGB display colours),
-- primitives with COLOR_0 into a colorgroup, primitives with TEXCOORD_0 and a material whose baseColorTexture has
-- PNG / JPEG bytes into a texture2d + texture2dgroup (the image stored in the package under 3D/Textures/).
-- Units: meta.unit picks the 3MF unit when it is one of them; otherwise millimetres and the build transforms scale.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Xml = require("@formats/codecs/Xml")
local Zip = require("@formats/containers/Zip")
local Write = {}
local NS_CORE = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02"
local NS_MAT = "http://schemas.microsoft.com/3dmanufacturing/material/2015/02"
local REL_MODEL = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"
local REL_TEXTURE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture"
local UNIT_ORDER = { "micron", "millimeter", "centimeter", "inch", "foot", "meter" }
local UNITS = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 }
local TEX_EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg" }
local fmt = string.format
local esc = Xml.escapeAttr
local function num(x: number): string
if x ~= x or x == math.huge or x == -math.huge then
return "0"
end
if x == math.floor(x) and math.abs(x) < 1e15 then
return fmt("%d", x)
end
return fmt("%.9g", x)
end
local function toSrgb(c: number): number
c = math.clamp(c, 0, 1)
if c <= 0.0031308 then
return c * 12.92
end
return 1.055 * c ^ (1 / 2.4) - 0.055
end
local function hex(r: number, g: number, b: number, a: number): string
local function q(x: number): number
return math.clamp(math.floor(x * 255 + 0.5), 0, 255)
end
return fmt("#%02X%02X%02X%02X", q(toSrgb(r)), q(toSrgb(g)), q(toSrgb(b)), q(math.clamp(a, 0, 1)))
end
-- the triangle corner list of a primitive (0-based vertex indices) or nil
local function triangles(prim: any): { number }?
local pos = prim.attributes and prim.attributes.POSITION
if type(pos) ~= "table" then
return nil
end
local n = pos.count
local ix: { number } = {}
if prim.indices then
local get = Types.Scene.reader(prim.indices)
if not get then
return nil
end
for i = 0, prim.indices.count - 1 do
ix[i + 1] = get(i, 0)
end
else
for i = 1, n do
ix[i] = i - 1
end
end
for _, v in ix do
if v ~= v or v < 0 or v >= n then
return nil
end
end
local mode = prim.mode or "triangles"
local out: { number } = {}
local function tri(a: number, b: number, c: number)
if a ~= b and b ~= c and a ~= c then
table.insert(out, a)
table.insert(out, b)
table.insert(out, c)
end
end
if mode == "triangles" then
for i = 1, #ix - 2, 3 do
tri(ix[i], ix[i + 1], ix[i + 2])
end
elseif mode == "triangle_strip" then
for i = 1, #ix - 2 do
if i % 2 == 1 then
tri(ix[i], ix[i + 1], ix[i + 2])
else
tri(ix[i + 1], ix[i], ix[i + 2])
end
end
elseif mode == "triangle_fan" then
for i = 2, #ix - 1 do
tri(ix[1], ix[i], ix[i + 1])
end
elseif mode == "polygons" and prim.faces then
local get = Types.Scene.reader(prim.faces)
if not get then
return nil
end
local at = 1
for f = 0, prim.faces.count - 1 do
local k = get(f, 0)
if at + k - 1 > #ix then
break
end
for j = 1, k - 2 do
tri(ix[at], ix[at + j], ix[at + j + 1])
end
at += k
end
else
return nil
end
return out
end
function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?)
local o = opts or {}
local nextId = 0
local function id(): number
nextId += 1
return nextId
end
local res: { string } = {} -- resource XML chunks, in definition order
local files: { { name: string, data: buffer, mime: string } } = {}
-- unit
local unitName: string, scale: number = "millimeter", 1
local mu: any = scene.meta and scene.meta.unit
if type(o.unit) == "string" and UNITS[o.unit] then
unitName = o.unit
if type(mu) == "number" and mu > 0 then
scale = mu / UNITS[o.unit]
end
elseif type(mu) == "number" and mu > 0 then
local found = false
for _, u in UNIT_ORDER do
if math.abs(UNITS[u] - mu) <= 1e-9 * mu then
unitName, found = u, true
break
end
end
if not found then
scale = mu / 1e-3
end
end
-- base materials: one group with every Scene material
local baseId: number? = nil
local nmat = #scene.materials
local defaultBase = nmat -- 0-based index of an extra white "default" base, added when needed
local needDefault = false
if nmat > 0 then
baseId = id()
end
-- textures used as base colour textures
local texRes: { [number]: number } = {}
local function textureId(ti: number): number?
if texRes[ti] ~= nil then
return if texRes[ti] > 0 then texRes[ti] else nil
end
local tex = scene.textures[ti]
local ext = tex and TEX_EXT[tex.mime or ""]
if not tex or type(tex.data) ~= "buffer" or not ext then
texRes[ti] = 0
return nil
end
local rid = id()
local name = fmt("3D/Textures/texture_%d.%s", ti, ext :: string)
table.insert(files, { name = name, data = tex.data :: buffer, mime = tex.mime :: string })
local s = tex.sampler
local function tile(w: string?): string
return if w == "clamp" then "clamp" elseif w == "mirror" then "mirror" else "wrap"
end
local filter = if s and (s.filter == "nearest" or s.filter == "linear") then s.filter else "auto"
table.insert(res, fmt('\t\t<m:texture2d id="%d" path="/%s" contenttype="%s" tilestyleu="%s" tilestylev="%s" filter="%s" />\n', rid, esc(name), tex.mime :: string, tile(s and s.wrapS), tile(s and s.wrapT), filter))
texRes[ti] = rid
return rid
end
-- objects
local objectOf: { [number]: number } = {}
local objChunks: { string } = {}
for mi, mesh in scene.meshes do
local verts: { string } = {}
local tris: { string } = {}
local base = 0
local objPid: number?, objP: number? = nil, nil
local anyNone = false
local triList: { { number } } = {} -- { v1, v2, v3, pid | -1, p1, p2, p3 }
for _, prim in mesh.primitives do
local corners = triangles(prim)
if not corners or #corners == 0 then
continue
end
local pos = prim.attributes.POSITION
local getP = Types.Scene.reader(pos)
if not getP then
continue
end
local n = pos.count
for v = 0, n - 1 do
table.insert(verts, fmt('\t\t\t\t\t<vertex x="%s" y="%s" z="%s" />\n', num(getP(v, 0)), num(if pos.components >= 2 then getP(v, 1) else 0), num(if pos.components >= 3 then getP(v, 2) else 0)))
end
-- properties: texture group, colour group, base material, none
local pid, kind = -1, "none"
local mat = prim.material and scene.materials[prim.material]
local uv = prim.attributes.TEXCOORD_0
local col = prim.attributes.COLOR_0
local tref = mat and mat.baseColorTexture
local tid = if tref and uv and (tref.texCoord or 0) == 0 then textureId(tref.texture) else nil
if tid and uv then
local get = Types.Scene.reader(uv)
if get then
pid, kind = id(), "tex"
local parts = { fmt('\t\t<m:texture2dgroup id="%d" texid="%d">\n', pid, tid) }
for v = 0, n - 1 do
table.insert(parts, fmt('\t\t\t<m:tex2coord u="%s" v="%s" />\n', num(get(v, 0)), num(1 - get(v, 1))))
end
table.insert(parts, "\t\t</m:texture2dgroup>\n")
table.insert(res, table.concat(parts))
end
end
if kind == "none" and col then
local get = Types.Scene.reader(col)
if get then
pid, kind = id(), "color"
local parts = { fmt('\t\t<m:colorgroup id="%d">\n', pid) }
local four = col.components >= 4
for v = 0, n - 1 do
table.insert(parts, fmt('\t\t\t<m:color color="%s" />\n', hex(get(v, 0), get(v, 1), get(v, 2), if four then get(v, 3) else 1)))
end
table.insert(parts, "\t\t</m:colorgroup>\n")
table.insert(res, table.concat(parts))
end
end
local pindex = -1
if kind == "none" and baseId and prim.material and scene.materials[prim.material] then
pid, kind, pindex = baseId :: number, "base", prim.material - 1
end
for i = 1, #corners, 3 do
local a, b, c = corners[i] + base, corners[i + 1] + base, corners[i + 2] + base
if kind == "tex" or kind == "color" then
table.insert(triList, { a, b, c, pid, corners[i], corners[i + 1], corners[i + 2] })
elseif kind == "base" then
table.insert(triList, { a, b, c, pid, pindex, pindex, pindex })
else
table.insert(triList, { a, b, c, -1, -1, -1, -1 })
anyNone = true
end
if objPid == nil and kind ~= "none" then
objPid, objP = pid, if kind == "base" then pindex else corners[i]
end
end
base += n
end
if #triList == 0 then
continue
end
if objPid and anyNone then
needDefault = true
if not baseId then
baseId = id()
end
end
for _, t in triList do
if t[4] < 0 and objPid then
t[4], t[5], t[6], t[7] = baseId :: number, defaultBase, defaultBase, defaultBase
end
if t[4] < 0 then
table.insert(tris, fmt('\t\t\t\t\t<triangle v1="%d" v2="%d" v3="%d" />\n', t[1], t[2], t[3]))
elseif t[5] == t[6] and t[6] == t[7] then
table.insert(tris, fmt('\t\t\t\t\t<triangle v1="%d" v2="%d" v3="%d" pid="%d" p1="%d" />\n', t[1], t[2], t[3], t[4], t[5]))
else
table.insert(tris, fmt('\t\t\t\t\t<triangle v1="%d" v2="%d" v3="%d" pid="%d" p1="%d" p2="%d" p3="%d" />\n', t[1], t[2], t[3], t[4], t[5], t[6], t[7]))
end
end
local oid = id()
objectOf[mi] = oid
local head = fmt('\t\t<object id="%d" type="model"', oid)
if mesh.name then
head ..= fmt(' name="%s"', esc(mesh.name))
end
if objPid then
head ..= fmt(' pid="%d" pindex="%d"', objPid, objP :: number)
end
table.insert(objChunks, table.concat({ head, ">\n\t\t\t<mesh>\n\t\t\t\t<vertices>\n", table.concat(verts), "\t\t\t\t</vertices>\n\t\t\t\t<triangles>\n", table.concat(tris), "\t\t\t\t</triangles>\n\t\t\t</mesh>\n\t\t</object>\n" }))
table.insert(res, objChunks[#objChunks])
end
-- the base material group goes first (its id was taken first)
if baseId then
local parts = { fmt('\t\t<basematerials id="%d">\n', baseId) }
for _, m in scene.materials do
local c = m.baseColor or { 1, 1, 1, 1 }
table.insert(parts, fmt('\t\t\t<base name="%s" displaycolor="%s" />\n', esc(m.name or "material"), hex(c[1] or 1, c[2] or 1, c[3] or 1, c[4] or 1)))
end
if needDefault then
table.insert(parts, '\t\t\t<base name="default" displaycolor="#FFFFFFFF" />\n')
end
table.insert(parts, "\t\t</basematerials>\n")
table.insert(res, 1, table.concat(parts))
end
-- build items: every node with a mesh, at its world matrix
local items: { string } = {}
local seen: { [number]: boolean } = {}
for _, pl in Types.Scene.flatten(scene) do
if seen[pl.node] then
continue
end
seen[pl.node] = true
local oid = objectOf[pl.mesh]
if not oid then
continue
end
local m = pl.matrix
local s = scale
local tr = { m[1] * s, m[2] * s, m[3] * s, m[5] * s, m[6] * s, m[7] * s, m[9] * s, m[10] * s, m[11] * s, m[13] * s, m[14] * s, m[15] * s }
local ident = s == 1
for i, v in { 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 } do
if tr[i] ~= v then
ident = false
end
end
if ident then
table.insert(items, fmt('\t\t<item objectid="%d" />\n', oid))
else
local ns = table.create(12, "")
for i = 1, 12 do
ns[i] = num(tr[i])
end
table.insert(items, fmt('\t\t<item objectid="%d" transform="%s" />\n', oid, table.concat(ns, " ")))
end
end
-- metadata
local meta: { string } = {}
local md = scene.meta and scene.meta.metadata
if type(md) == "table" then
local keys: { string } = {}
for k: any, v: any in md do
if type(k) == "string" and (type(v) == "string" or type(v) == "number") then
table.insert(keys, k)
end
end
table.sort(keys)
for _, k in keys do
table.insert(meta, fmt('\t<metadata name="%s">%s</metadata>\n', esc(k), Xml.escape(tostring(md[k]))))
end
end
local model = table.concat({
'<?xml version="1.0" encoding="UTF-8"?>\n',
'<model unit="' .. unitName .. '" xml:lang="en-US" xmlns="' .. NS_CORE .. '" xmlns:m="' .. NS_MAT .. '">\n',
table.concat(meta),
"\t<resources>\n",
table.concat(res),
"\t</resources>\n\t<build>\n",
table.concat(items),
"\t</build>\n</model>\n",
})
local types = { '<?xml version="1.0" encoding="UTF-8"?>\n<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\n',
'\t<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" />\n',
'\t<Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml" />\n' }
local exts: { [string]: boolean } = {}
for _, f in files do
local e = string.match(f.name, "%.(%w+)$") :: string
if not exts[e] then
exts[e] = true
table.insert(types, fmt('\t<Default Extension="%s" ContentType="%s" />\n', e, f.mime))
end
end
table.insert(types, "</Types>\n")
local rels = '<?xml version="1.0" encoding="UTF-8"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n'
.. fmt('\t<Relationship Target="/3D/3dmodel.model" Id="rel0" Type="%s" />\n', REL_MODEL)
.. "</Relationships>\n"
local w = Zip.writer()
local level = o.level or 6
local method = if level == 0 then "store" else "deflate"
local ok, err = w:add("[Content_Types].xml", table.concat(types), { level = level, method = method })
if ok then
ok, err = w:add("_rels/.rels", rels, { level = level, method = method })
end
if ok then
ok, err = w:add("3D/3dmodel.model", model, { level = level, method = method })
end
if ok and #files > 0 then
local mr = { '<?xml version="1.0" encoding="UTF-8"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n' }
for i, f in files do
table.insert(mr, fmt('\t<Relationship Target="/%s" Id="rel%d" Type="%s" />\n', esc(f.name), i, REL_TEXTURE))
end
table.insert(mr, "</Relationships>\n")
ok, err = w:add("3D/_rels/3dmodel.model.rels", table.concat(mr), { level = level, method = method })
for _, f in files do
if ok then
ok, err = w:add(f.name, f.data, { method = "store" })
end
end
end
if not ok then
return nil, err or Err.new(Err.ARG, "zip writer failed")
end
return w:finish()
end
return Write
+95
View File
@@ -0,0 +1,95 @@
--!strict
-- model/3mf: 3D Manufacturing Format (3MF Consortium core specification 1.3, materials and properties extension 1.2,
-- production extension 1.1 part references). New code. An OPC package (containers/Zip) holding XML model parts
-- (codecs/Xml).
-- Reads: the root model part (_rels/.rels), objects (mesh vertices / triangles; components with transforms, also from
-- other model parts through p:path), build items -> root nodes with their transforms (3MF's row-vector 4x3 matrices
-- become column-major node.matrix), object names / types / part numbers (node / mesh extras["3mf"]), metadata
-- (meta.metadata), the unit (meta.unit in metres; meta.up = "z"), basematerials (-> materials, sRGB display colours
-- made linear), colorgroup (-> COLOR_0, linear RGBA), texture2d + texture2dgroup (-> TEXCOORD_0 with v flipped to
-- glTF's top-left origin, a material with baseColorTexture, the texture kept encoded from its package part: decode it
-- with F.model.loadTextures), compositematerials (one blended colour per composite), multiproperties (their first
-- layer), per-triangle pid / p1 / p2 / p3 and per-object pid / pindex defaults. One primitive per property; vertices
-- are split where a vertex's corners carry different colours / texture coordinates.
-- Writes: one object per mesh (all triangle-like primitives; points / lines skipped), one build item per node with a
-- mesh at its world matrix (the hierarchy is flattened), materials as basematerials, COLOR_0 as colour groups,
-- PNG / JPEG base colour textures as texture2d + texture2dgroup, metadata, the unit (opts.unit or from meta.unit).
-- Not supported: beam lattice, slices, displacement, volumetric and secure content extensions (their elements are
-- ignored; meta.source.requiredExtensions lists what the file declared), thumbnails, normals (3MF has none).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Zip = require("@formats/containers/Zip")
local Read = require("@formats/model/3mf/Read")
local Write = require("@formats/model/3mf/Write")
-- ------------------------------------------------------------------------------------------------ contract
local ThreeMf = {
name = "3mf",
category = "model",
extensions = { "3mf" },
mime = { "model/3mf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "containers/Zip" },
caps = { decode = true, encode = true, materials = true, vertexColors = true, textures = true, units = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxVertices: number?, -- refuse more vertices + triangle corners in total (default 2^25)
maxNodes: number?, -- refuse more object instances (default 2^20)
}
export type EncodeOptions = {
unit: string?, -- "micron" | "millimeter" | "centimeter" | "inch" | "foot" | "meter" (default: from meta.unit, else
-- millimeter); positions are scaled through the build transforms when meta.unit differs
level: number?, -- deflate level for the XML parts (default 6; 0 stores them)
}
-- ------------------------------------------------------------------------------------------------ sniff
function ThreeMf.sniff(r: Bytes.Reader): number
if r:peek(4) ~= "PK\3\4" then
return 0
end
-- the central directory sits at the end: look for the model part's name there, then at the start
local n = r:size()
local tail = buffer.readstring(r.buf, r.base + math.max(0, n - 65536), math.min(n, 65536))
if string.find(tail, "3D/[^/]*%.model") or string.find(tail, "3dmodel.model", 1, true) then
return 0.95
end
local head = r:peek(256)
if string.find(head, "3D/", 1, true) then
return 0.7
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function ThreeMf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local zip, zerr = Zip.open(r)
if not zip then
return nil, zerr
end
local ok, scene, err = pcall(Read.scene, zip, opts or {})
if not ok then
return nil, Err.new(Err.CORRUPT, "bad package (" .. tostring(scene) .. ")")
end
return scene, err
end
-- ------------------------------------------------------------------------------------------------ encode
function ThreeMf.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.meshes) ~= "table" or type(scene.materials) ~= "table" or type(scene.textures) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Scene")
end
if opts and opts.unit ~= nil and not Read.UNITS[opts.unit] then
return nil, Err.new(Err.ARG, "unknown unit " .. tostring(opts.unit))
end
local ok, out, err = pcall(Write.build, scene, opts)
if not ok then
return nil, Err.new(Err.ARG, "bad scene (" .. tostring(out) .. ")")
end
return out, err
end
return ThreeMf