--!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 ") 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