--!strict -- model/ply: PLY (Stanford polygon file format, Greg Turk 1994), ascii / binary_little_endian / binary_big_endian, -- read + write. Written from the format description (paulbourke.net/dataformats/ply, the rply / plyfile behaviour). -- Decode: the vertex element maps x y z -> POSITION f32 x3, nx ny nz -> NORMAL f32 x3, red green blue [alpha] -> -- COLOR_0 (uchar: unorm8 x4, ushort: unorm16 x4, float / double: f32 x4; alpha full when absent), u v / s t / texture_u -- texture_v / texture_s texture_t -> TEXCOORD_0 f32 x2, every other property -> "_" .. name in its own type (char -> -- i8, uchar -> u8, ..., double -> f64). Doubles in x / y / z / normals / texcoords become f32. The face element's -- vertex_indices / vertex_index list gives the faces: triangles stay triangles (u32 indices), n-gons are -- fan-triangulated (opts.triangulate, default true: right for convex faces; faces of fewer than 3 vertices are -- dropped) or kept as mode "polygons" (prim.faces = vertex count per face). No faces: a point cloud (mode "points", -- no indices). Other face properties: prim.extras.faceAttributes[name] (one value per file face, its own type), face -- lists: prim.extras.faceLists[name] = { countType, itemType, sizes (u32 accessor), items (accessor) }; after -- triangulating n-gons prim.extras.faceOfTriangle (u32, 0-based) maps triangles to file faces. Other elements (edge, -- material, ...) are kept raw in scene.meta.ply.elements (in their types) and written back, as are comments -- (meta.ply.comments), obj_info lines (meta.ply.objInfo), the element order and the vertex / face property order and -- types. meta.source = { format, encoding, vertices, faces }. -- Encode: every primitive in world space (node transforms applied) into one vertex list: POSITION, NORMAL, COLOR_0, -- TEXCOORD_0 and "_" attributes (under their name, in their type; several components: name_0, name_1, ...), faces -- (triangles and polygons natively as `property list uchar int vertex_indices`, a wider count / uint index type when -- needed), point clouds without a face element; lines are skipped. Floats print as %.9g (f32-exact), doubles %.17g. -- Not supported: list properties in the vertex element (UNSUPPORTED). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Binary = require("@formats/model/ply/Binary") local Flatten = require("@formats/codecs/MeshFlatten") -- ------------------------------------------------------------------------------------------------ contract local Ply = { name = "ply", category = "model", extensions = { "ply" }, mime = { "model/ply", "application/ply" }, deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" }, caps = { decode = true, encode = true, ascii = true, binary = true, polygons = true, points = true, colors = true }, } -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps them as mode "polygons" maxVertices: number?, -- default 2^24 maxFaces: number?, -- faces, and rows of any other element (default 2^25) } export type EncodeOptions = { format: ("binary_little_endian" | "binary_big_endian" | "ascii")?, -- default "binary_little_endian" comments: { string }?, -- extra comment lines (after those in scene.meta.ply.comments) } type Prop = { name: string, ply: string, code: number, list: boolean, countPly: string?, countCode: number? } type Elem = { name: string, count: number, props: { Prop } } -- ------------------------------------------------------------------------------------------------ constants local CODES: { [string]: number } = { char = 1, int8 = 1, uchar = 2, uint8 = 2, short = 3, int16 = 3, ushort = 4, uint16 = 4, int = 5, int32 = 5, uint = 6, uint32 = 6, float = 7, float32 = 7, double = 8, float64 = 8, } local ACC_TYPE = { "i8", "u8", "i16", "u16", "i32", "u32", "f32", "f64" } local PLY_NAME = { "char", "uchar", "short", "ushort", "int", "uint", "float", "double" } local CODE_OF_ACC: { [string]: number } = { i8 = 1, u8 = 2, i16 = 3, u16 = 4, i32 = 5, u32 = 6, f32 = 7, f64 = 8, unorm8 = 2, unorm16 = 4, snorm8 = 1, snorm16 = 3 } local RANGE = { { -128, 127 }, { 0, 255 }, { -32768, 32767 }, { 0, 65535 }, { -2147483648, 2147483647 }, { 0, 4294967295 } } local SIZE = Binary.SIZE local ENCODINGS = { ascii = true, binary_little_endian = true, binary_big_endian = true } local MAX_HEADER = 1048576 local TEXCOORD_PAIRS = { { "u", "v" }, { "s", "t" }, { "texture_u", "texture_v" }, { "texture_s", "texture_t" } } -- ------------------------------------------------------------------------------------------------ sniff function Ply.sniff(r: Bytes.Reader): number local h = r:peek(4) return if h == "ply\n" or h == "ply\r" then 1 else 0 end -- ------------------------------------------------------------------------------------------------ decode type Header = { encoding: string, elems: { Elem }, comments: { string }, objInfo: { string }, dataStart: number } local function parseHeader(r: Bytes.Reader): (Header?, Err.Err?) local b, base, size = r.buf, r.base, r.limit - r.base local text = buffer.readstring(b, base, math.min(size, MAX_HEADER)) if string.sub(text, 1, 3) ~= "ply" or not string.match(string.sub(text, 4, 5), "^\r?\n") then return nil, Err.new(Err.CORRUPT, "bad signature", base) end local h: Header = { encoding = "", elems = {}, comments = {}, objInfo = {}, dataStart = -1 } local at = 1 local first = true while true do local e = string.find(text, "\n", at, true) if not e then if size > MAX_HEADER then return nil, Err.new(Err.LIMIT, "header longer than 1 MB") end return nil, Err.new(Err.TRUNCATED, "no end_header", base + at - 1) end local line = string.sub(text, at, e - 1) if string.sub(line, -1) == "\r" then line = string.sub(line, 1, -2) end local lineAt = base + at - 1 at = e + 1 local kw = string.match(line, "^%s*(%S+)") if first then first = false -- "ply" elseif kw == nil then -- blank line elseif kw == "end_header" then h.dataStart = base + at - 1 break elseif kw == "comment" or kw == "obj_info" then local rest = string.match(line, "^%s*%S+ ?(.*)$") or "" table.insert(if kw == "comment" then h.comments else h.objInfo, rest) elseif kw == "format" then local enc, ver = string.match(line, "^%s*format%s+(%S+)%s+(%S+)") if not enc or not ENCODINGS[enc] then return nil, Err.new(Err.UNSUPPORTED, "unknown format " .. tostring(enc), lineAt) end if string.sub(ver, 1, 1) ~= "1" then return nil, Err.new(Err.UNSUPPORTED, "version " .. ver, lineAt) end h.encoding = enc elseif kw == "element" then local name, count = string.match(line, "^%s*element%s+(%S+)%s+(%d+)%s*$") local n = tonumber(count) if not name or not n then return nil, Err.new(Err.CORRUPT, "bad element line", lineAt) end table.insert(h.elems, { name = name, count = n, props = {} }) elseif kw == "property" then local el = h.elems[#h.elems] if not el then return nil, Err.new(Err.CORRUPT, "property before any element", lineAt) end local words = {} for w in string.gmatch(line, "%S+") do table.insert(words, w) end local p: Prop if words[2] == "list" and #words == 5 then local cc, ic = CODES[words[3]], CODES[words[4]] if not cc or not ic then return nil, Err.new(Err.CORRUPT, "unknown property type in " .. line, lineAt) end p = { name = words[5], ply = words[4], code = ic, list = true, countPly = words[3], countCode = cc } elseif #words == 3 and CODES[words[2]] then p = { name = words[3], ply = words[2], code = CODES[words[2]], list = false } else return nil, Err.new(Err.CORRUPT, "bad property line: " .. string.sub(line, 1, 60), lineAt) end for _, q in el.props do if q.name == p.name then return nil, Err.new(Err.CORRUPT, "duplicate property " .. p.name, lineAt) end end table.insert(el.props, p) else return nil, Err.new(Err.CORRUPT, "unknown header line: " .. string.sub(line, 1, 60), lineAt) end end if h.encoding == "" then return nil, Err.new(Err.CORRUPT, "no format line", base) end return h, nil end -- the reading plan of one element: per property, where its values go type Plan = { code: { number }, isList: { boolean }, countCode: { number }, dst: { buffer }, dOff: { number }, dStride: { number }, dCode: { number }, sizes: { buffer }, bound: { number }, totals: { number }, } local function newPlan(e: Elem): Plan local np = #e.props local pl: Plan = { code = table.create(np, 0), isList = table.create(np, false), countCode = table.create(np, 2), dst = table.create(np), dOff = table.create(np, 0), dStride = table.create(np, 0), dCode = table.create(np, 0), sizes = table.create(np), bound = table.create(np, -1), totals = table.create(np, 0), } for k, p in e.props do pl.code[k] = p.code pl.isList[k] = p.list pl.countCode[k] = p.countCode or 2 pl.dCode[k] = p.code pl.dStride[k] = SIZE[p.code] end return pl end -- unset scalar destinations get their own native buffer local function ownBuffers(e: Elem, pl: Plan) for k, p in e.props do if not p.list and pl.dst[k] == nil then pl.dst[k] = buffer.create(e.count * SIZE[p.code]) end end end -- read one element's rows (binary) into the plan; returns the next offset or nil, Err local function readBinary(r: Bytes.Reader, p: number, e: Elem, pl: Plan, be: boolean): (number?, Err.Err?) local b, limit, n, np = r.buf, r.limit, e.count, #e.props local hasList, rowSize = false, 0 for k, pr in e.props do if pr.list then hasList = true rowSize += SIZE[pr.countCode :: number] else rowSize += SIZE[pr.code] end end if n * rowSize > limit - p then return nil, Err.new(Err.TRUNCATED, string.format("element %s: %d rows need at least %d bytes", e.name, n, n * rowSize), p) end if not hasList then ownBuffers(e, pl) local srcOff = table.create(np, 0) local o = 0 for k, pr in e.props do srcOff[k] = o o += SIZE[pr.code] end Binary.fixed(b, p, n, rowSize, np, srcOff, pl.code, be, pl.dst, pl.dOff, pl.dStride, pl.dCode) return p + n * rowSize, nil end local q, totals = Binary.scan(b, p, limit, n, np, pl.code, pl.isList, pl.countCode, be) if q < 0 then return nil, Err.new(if totals == "bad list count" then Err.CORRUPT else Err.TRUNCATED, "element " .. e.name .. ": " .. tostring(totals), p) end ownBuffers(e, pl) for k, pr in e.props do if pr.list then pl.totals[k] = totals[k] pl.sizes[k] = buffer.create(n * 4) pl.dst[k] = buffer.create(totals[k] * SIZE[pl.dCode[k]]) end end local ok, msg = Binary.rows(b, p, n, np, pl.code, pl.isList, pl.countCode, be, pl.dst, pl.dOff, pl.dStride, pl.dCode, pl.sizes, pl.bound) if not ok then return nil, Err.new(Err.CORRUPT, "element " .. e.name .. ": " .. tostring(msg), p) end return q, nil end -- a token as a value of type code, or nil local function value(tok: string?, code: number): number? if tok == nil then return nil end local v = tonumber(tok) if v == nil then return nil end local rg = RANGE[code] if rg and (v ~= v // 1 or v < rg[1] or v > rg[2]) then return nil end return v end -- read one element's rows (ascii) from the token stream local function readAscii(nextTok: () -> string?, e: Elem, pl: Plan): Err.Err? ownBuffers(e, pl) local n = e.count local listSizes: { [number]: { number } } = {} local listItems: { [number]: { number } } = {} for k, p in e.props do if p.list then listSizes[k] = table.create(n) listItems[k] = {} end end local wr = Binary.wr for i = 0, n - 1 do for k, p in e.props do if p.list then local t = nextTok() local c = value(t, p.countCode :: number) if c == nil or c < 0 or c % 1 ~= 0 then return Err.new(if t == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad list count", e.name, i)) end listSizes[k][i + 1] = c local items, bd, code = listItems[k], pl.bound[k], p.code for _ = 1, c do local t2 = nextTok() local v = value(t2, code) if v == nil then return Err.new(if t2 == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad value", e.name, i)) end if bd >= 0 and (v < 0 or v >= bd or v ~= v // 1) then return Err.new(Err.CORRUPT, string.format("element %s row %d: vertex index out of range", e.name, i)) end table.insert(items, v) end else local t = nextTok() local v = value(t, p.code) if v == nil then return Err.new(if t == nil then Err.TRUNCATED else Err.CORRUPT, string.format("element %s row %d: bad %s value", e.name, i, p.name)) end wr(pl.dst[k], pl.dOff[k] + i * pl.dStride[k], pl.dCode[k], v) end end end for k in listSizes do local sz, items = listSizes[k], listItems[k] local s = buffer.create(n * 4) for i = 1, n do buffer.writeu32(s, (i - 1) * 4, sz[i]) end local dc = pl.dCode[k] local d = buffer.create(#items * SIZE[dc]) for j = 1, #items do wr(d, (j - 1) * SIZE[dc], dc, items[j]) end pl.sizes[k], pl.dst[k], pl.totals[k] = s, d, #items end return nil end local function propIndex(e: Elem, name: string): number? for k, p in e.props do if p.name == name then return k end end return nil end -- vertex element -> attributes: sets the plan's destinations, returns the attribute table local function planVertex(e: Elem, pl: Plan): ({ [string]: Types.Accessor }?, Err.Err?) local nv = e.count local attrs: { [string]: Types.Accessor } = {} local taken: { [number]: boolean } = {} for _, p in e.props do if p.list then return nil, Err.new(Err.UNSUPPORTED, "list property " .. p.name .. " in the vertex element") end end -- group(attr, names, required, ok, comps, fill): the first `required` names must exist, the others are optional local function group(attr: string, names: { string }, required: number, ok: (codes: { number }) -> number?, comps: number, fillValue: number?) local ks: { [number]: number } = {} local codes = {} for i, nm in names do local k = propIndex(e, nm) if k == nil then if i <= required then return end else ks[i] = k table.insert(codes, e.props[k].code) end end local dc = ok(codes) if dc == nil then return end local sz = SIZE[dc] local buf = buffer.create(nv * comps * sz) if fillValue then for i = 0, nv - 1 do Binary.wr(buf, (i * comps + comps - 1) * sz, dc, fillValue) end end for i, k in ks do pl.dst[k], pl.dOff[k], pl.dStride[k], pl.dCode[k] = buf, (i - 1) * sz, comps * sz, dc taken[k] = true end local accType = if attr == "COLOR_0" and dc == 2 then "unorm8" elseif attr == "COLOR_0" and dc == 4 then "unorm16" else ACC_TYPE[dc] attrs[attr] = Types.Scene.accessor(buf, accType, comps, nv) end local function floats(codes: { number }): number? for _, c in codes do if c ~= 7 and c ~= 8 then return nil end end return 7 end local function anyNumber(_codes: { number }): number? return 7 end group("POSITION", { "x", "y", "z" }, 3, anyNumber, 3, nil) group("NORMAL", { "nx", "ny", "nz" }, 3, floats, 3, nil) -- colours: one type class for all channels do local rk, gk, bk, ak = propIndex(e, "red"), propIndex(e, "green"), propIndex(e, "blue"), propIndex(e, "alpha") if rk and gk and bk then local codes = { e.props[rk].code, e.props[gk].code, e.props[bk].code } if ak then table.insert(codes, e.props[ak].code) end local cls: number? = codes[1] for _, c in codes do local a = if c == 8 then 7 else c local b0 = if cls == 8 then 7 else cls if a ~= b0 then cls = nil end end local dc = if cls == 2 then 2 elseif cls == 4 then 4 elseif cls == 7 or cls == 8 then 7 else nil if dc then group("COLOR_0", { "red", "green", "blue", "alpha" }, 3, function() return dc end, 4, if dc == 2 then 255 elseif dc == 4 then 65535 else 1) end end end for _, pair in TEXCOORD_PAIRS do if attrs.TEXCOORD_0 == nil then group("TEXCOORD_0", pair, 2, floats, 2, nil) end end for k, p in e.props do if not taken[k] then local buf = buffer.create(nv * SIZE[p.code]) pl.dst[k] = buf attrs["_" .. p.name] = Types.Scene.accessor(buf, ACC_TYPE[p.code], 1, nv) end end return attrs, nil end -- the fan triangulation of faces with sizes / corners; returns indices (u32), triangle count, faceOfTriangle local function fan(sizes: buffer, corners: buffer, nf: number): (buffer, number, buffer) local nt = 0 for f = 0, nf - 1 do local s = buffer.readu32(sizes, f * 4) if s >= 3 then nt += s - 2 end end local idx, fot = buffer.create(nt * 12), buffer.create(nt * 4) local p, t = 0, 0 local readu32, writeu32 = buffer.readu32, buffer.writeu32 for f = 0, nf - 1 do local s = readu32(sizes, f * 4) local a = readu32(corners, p * 4) for k = 1, s - 2 do writeu32(idx, t * 12, a) writeu32(idx, t * 12 + 4, readu32(corners, (p + k) * 4)) writeu32(idx, t * 12 + 8, readu32(corners, (p + k + 1) * 4)) writeu32(fot, t * 4, f) t += 1 end p += s end return idx, nt, fot end function Ply.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) local triangulate = true if opts and opts.triangulate == false then triangulate = false end local maxVertices = opts and opts.maxVertices or 2 ^ 24 local maxFaces = opts and opts.maxFaces or 2 ^ 25 local h, herr = parseHeader(r) if not h then return nil, herr end local vi, fi, idxK for i, e in h.elems do if e.name == "vertex" and vi == nil then vi = i if e.count > maxVertices then return nil, Err.new(Err.LIMIT, string.format("%d vertices is over the %d vertex limit", e.count, maxVertices)) end elseif e.name == "face" and fi == nil then local k = propIndex(e, "vertex_indices") or propIndex(e, "vertex_index") if k and e.props[k].list then fi, idxK = i, k end end if e.count > maxFaces then return nil, Err.new(Err.LIMIT, string.format("element %s: %d rows is over the %d limit", e.name, e.count, maxFaces)) end end if vi == nil then return nil, Err.new(Err.CORRUPT, "no vertex element") end local nv = h.elems[vi].count local be = h.encoding == "binary_big_endian" local ascii = h.encoding == "ascii" local nextTok: () -> string? = function() return nil end if ascii then local body = buffer.readstring(r.buf, h.dataStart, r.limit - h.dataStart) -- each value takes at least 2 bytes (a digit and a separator): bound the counts before allocating local need = 0 for _, e in h.elems do need += e.count * #e.props end if need > (#body + 1) // 2 then return nil, Err.new(Err.TRUNCATED, "fewer values than the element counts need", h.dataStart) end nextTok = string.gmatch(body, "%S+") :: any end local plans: { Plan } = {} local attrs: { [string]: Types.Accessor } = {} local p = h.dataStart if not ascii then -- every row takes at least its scalar sizes and list counts: bound the counts before allocating local need = 0 for _, e in h.elems do local row = 0 for _, pr in e.props do row += SIZE[if pr.list then pr.countCode :: number else pr.code] end need += e.count * row end if need > r.limit - h.dataStart then return nil, Err.new(Err.TRUNCATED, string.format("the elements need at least %d bytes, %d left", need, r.limit - h.dataStart), h.dataStart) end end for i, e in h.elems do local pl = newPlan(e) plans[i] = pl if i == vi then local a, aerr = planVertex(e, pl) if not a then return nil, aerr end attrs = a elseif i == fi then pl.dCode[idxK] = 6 pl.bound[idxK] = nv end if ascii then local err = readAscii(nextTok, e, pl) if err then return nil, err end else local q, err = readBinary(r, p, e, pl, be) if not q then return nil, err end p = q end end -- the primitive local prim: Types.Primitive = { attributes = attrs, mode = "points" } local nf = 0 local extras: { [string]: any } = {} local faceProps: { any } = {} if fi then local e, pl = h.elems[fi], plans[fi] nf = e.count local sizes, corners, total = pl.sizes[idxK], pl.dst[idxK], pl.totals[idxK] local faceAttributes: { [string]: Types.Accessor } = {} local faceLists: { [string]: any } = {} local anyExtra = false for k, pr in e.props do table.insert(faceProps, { name = pr.name, type = pr.ply, countType = pr.countPly }) if k ~= idxK then anyExtra = true if pr.list then faceLists[pr.name] = { countType = pr.countPly, itemType = pr.ply, sizes = Types.Scene.accessor(pl.sizes[k], "u32", 1, nf), items = Types.Scene.accessor(pl.dst[k], ACC_TYPE[pr.code], 1, pl.totals[k]), } else faceAttributes[pr.name] = Types.Scene.accessor(pl.dst[k], ACC_TYPE[pr.code], 1, nf) end end end if next(faceAttributes) then extras.faceAttributes = faceAttributes end if next(faceLists) then extras.faceLists = faceLists end if nf > 0 then local allTri = total == nf * 3 if allTri then for f = 0, nf - 1 do if buffer.readu32(sizes, f * 4) ~= 3 then allTri = false break end end end if allTri then prim.mode = "triangles" prim.indices = Types.Scene.accessor(corners, "u32", 1, total) elseif triangulate then local idx, nt, fot = fan(sizes, corners, nf) prim.mode = "triangles" prim.indices = Types.Scene.accessor(idx, "u32", 1, nt * 3) if anyExtra then extras.faceOfTriangle = Types.Scene.accessor(fot, "u32", 1, nt) end else prim.mode = "polygons" prim.indices = Types.Scene.accessor(corners, "u32", 1, total) prim.faces = Types.Scene.accessor(sizes, "u32", 1, nf) end end end if next(extras) then prim.extras = extras end -- raw elements, element order, property order local elements: { any } = {} local order: { string } = {} for i, e in h.elems do table.insert(order, e.name) if i ~= vi and i ~= fi then local pl = plans[i] local props = {} for k, pr in e.props do props[k] = { name = pr.name, type = pr.ply, countType = pr.countPly, values = pl.dst[k], sizes = pl.sizes[k], total = if pr.list then pl.totals[k] else nil } end table.insert(elements, { name = e.name, count = e.count, properties = props }) end end local vprops = {} for _, pr in h.elems[vi].props do table.insert(vprops, { name = pr.name, type = pr.ply }) end local scene = Types.Scene.fromPrimitive(prim, nil) scene.meta.source = { format = "ply", encoding = h.encoding, vertices = nv, faces = nf } scene.meta.ply = { comments = h.comments, objInfo = h.objInfo, elements = elements, order = order, vertexProperties = vprops, faceProperties = if fi then faceProps else nil, } return scene, nil end -- ------------------------------------------------------------------------------------------------ encode -- a column to write: ply type code + spelling, the values (one per row, or per row * stride at offset) type Column = { name: string, ply: string, code: number, values: { number }, stride: number, offset: number } type ListColumn = { name: string, ply: string, code: number, countPly: string, countCode: number, sizes: { number }, items: { number } } local function keep(name: string): boolean return name == "NORMAL" or name == "COLOR_0" or name == "TEXCOORD_0" or string.sub(name, 1, 1) == "_" end -- the spelling `want` from the source file when it means the same type as code, else the classic name local function spell(want: string?, code: number): string if want and CODES[want] == code then return want end return PLY_NAME[code] end local function toInt(v: number, code: number): number local rg = RANGE[code] if rg then if v ~= v then return 0 end return math.clamp(math.floor(v + 0.5), rg[1], rg[2]) end return v end -- write rows of columns (+ list columns, in `order`) for n rows: ascii lines into out, binary into the writer type Row = { kind: "s", col: Column } | { kind: "l", col: ListColumn } local function rowsAscii(out: { string }, n: number, cols: { Row }) local fmt = string.format local function num(code: number, v: number): string if code == 7 then return fmt("%.9g", v) elseif code == 8 then return fmt("%.17g", v) end return fmt("%d", toInt(v, code)) end local at: { [number]: number } = {} for i = 0, n - 1 do local parts = {} for k, c in cols do if c.kind == "s" then local col = c.col :: Column table.insert(parts, num(col.code, col.values[i * col.stride + col.offset + 1])) else local col = c.col :: ListColumn local s = col.sizes[i + 1] table.insert(parts, fmt("%d", s)) local a = at[k] or 0 for j = 1, s do table.insert(parts, num(col.code, col.items[a + j])) end at[k] = a + s end end table.insert(out, table.concat(parts, " ")) end end local function rowsBinary(w: Bytes.Writer, n: number, cols: { Row }, be: boolean) local size = 0 for _, c in cols do if c.kind == "s" then size += n * SIZE[(c.col :: Column).code] else local col = c.col :: ListColumn size += n * SIZE[col.countCode] + #col.items * SIZE[col.code] end end local o = w:reserve(size) local d = w.buf local put = Binary.put local at: { [number]: number } = {} for i = 0, n - 1 do for k, c in cols do if c.kind == "s" then local col = c.col :: Column local code = col.code put(d, o, code, toInt(col.values[i * col.stride + col.offset + 1], code), be) o += SIZE[code] else local col = c.col :: ListColumn local s = col.sizes[i + 1] put(d, o, col.countCode, s, be) o += SIZE[col.countCode] local a, code = at[k] or 0, col.code for j = 1, s do put(d, o, code, toInt(col.items[a + j], code), be) o += SIZE[code] end at[k] = a + s end end end w.pos = o end -- numbers of a raw element column (buffer of a ply type) local function bufNumbers(b: any, code: number, count: number): { number }? if type(b) ~= "buffer" or buffer.len(b) < count * SIZE[code] then return nil end local out = table.create(count) for i = 0, count - 1 do out[i + 1] = Binary.rd(b, i * SIZE[code], code, false) end return out end -- the list count type for a maximum count local function countCodeFor(maxCount: number): number return if maxCount <= 255 then 2 elseif maxCount <= 65535 then 4 else 6 end function Ply.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) local o: EncodeOptions = opts or {} local enc = o.format or "binary_little_endian" if not ENCODINGS[enc] then return nil, Err.new(Err.ARG, "format must be ascii, binary_little_endian or binary_big_endian") end local m, merr = Flatten.merge(scene, keep, { triangulate = false }) if not m then return nil, Err.new(Err.ARG, tostring(merr)) end local meta: any = if type(scene) == "table" and type(scene.meta) == "table" and type(scene.meta.ply) == "table" then scene.meta.ply else {} local nv = m.count -- source property spellings / order local srcType: { [string]: string } = {} local srcOrder: { [string]: number } = {} if type(meta.vertexProperties) == "table" then for i, vp in meta.vertexProperties do if type(vp) == "table" and type(vp.name) == "string" then srcType[vp.name] = vp.type srcOrder[vp.name] = i end end end local cols: { Column } = {} local function add(name: string, code: number, a: Flatten.Attr, comp: number) table.insert(cols, { name = name, ply = spell(srcType[name], code), code = code, values = a.values, stride = a.components, offset = comp }) end local function floatCode(name: string): number return if CODES[srcType[name] or ""] == 8 then 8 else 7 end local A = m.attrs for i, nm in { "x", "y", "z" } do add(nm, floatCode(nm), A.POSITION, i - 1) end if A.NORMAL then for i, nm in { "nx", "ny", "nz" } do add(nm, floatCode(nm), A.NORMAL, i - 1) end end local C = A.COLOR_0 if C then local code = if C.raw and C.type == "unorm8" then 2 elseif C.raw and C.type == "unorm16" then 4 else 7 if C.raw and code == 7 then -- another normalized type: as floats local vals = table.create(#C.values) local scale = if C.type == "snorm8" then 127 else 32767 for i, v in C.values do vals[i] = math.max(v / scale, -1) end C = { type = "f32", components = C.components, raw = false, values = vals } end local cc = C :: Flatten.Attr for i, nm in { "red", "green", "blue" } do if i <= cc.components then add(nm, code, cc, i - 1) end end if cc.components >= 4 then local full = if code == 2 then 255 elseif code == 4 then 65535 else 1 local need = srcOrder.alpha ~= nil if not need then for i = 0, nv - 1 do if cc.values[i * cc.components + 4] ~= full then need = true break end end end if need then add("alpha", code, cc, 3) end end end if A.TEXCOORD_0 then local names = { "s", "t" } for _, pair in TEXCOORD_PAIRS do if srcOrder[pair[1]] and srcOrder[pair[2]] then names = pair break end end local tc = A.TEXCOORD_0 if tc.raw then return nil, Err.new(Err.ARG, "TEXCOORD_0 of a normalized integer type") end add(names[1], floatCode(names[1]), tc, 0) if tc.components >= 2 then add(names[2], floatCode(names[2]), tc, 1) end end local customs = {} for name in A do if string.sub(name, 1, 1) == "_" then table.insert(customs, name) end end table.sort(customs) for _, name in customs do local a = A[name] local code = CODE_OF_ACC[a.type] or 7 local base = string.sub(name, 2) if a.components == 1 then add(base, code, a, 0) else for c = 0, a.components - 1 do add(base .. "_" .. c, code, a, c) end end end -- the source order first (stable for the rest) local rank: { [Column]: number } = {} for i, c in cols do rank[c] = (srcOrder[c.name] or (1000000 + i)) end table.sort(cols, function(a: Column, b: Column): boolean return rank[a] < rank[b] end) -- faces local faceRows: { Row }? = nil local nf = 0 if m.sizes then local sizes = m.sizes :: { number } nf = #sizes local maxS, maxI = 0, 0 for _, s in sizes do maxS = math.max(maxS, s) end for _, c in m.corners do maxI = math.max(maxI, c) end local fprops: { any } = if type(meta.faceProperties) == "table" then meta.faceProperties else {} local idxName, idxType, idxCount = "vertex_indices", nil, nil for _, fp in fprops do if type(fp) == "table" and (fp.name == "vertex_indices" or fp.name == "vertex_index") then idxName, idxType, idxCount = fp.name, fp.type, fp.countType end end local cc = countCodeFor(maxS) local srcCC = CODES[idxCount or ""] if srcCC and srcCC <= 6 and SIZE[srcCC] >= SIZE[cc] then cc = srcCC end local ic = if maxI < 2147483648 then 5 else 6 local srcIC = CODES[idxType or ""] if srcIC == 6 or (srcIC and srcIC <= 6 and maxI <= RANGE[srcIC][2]) then ic = srcIC end local rows: { Row } = { { kind = "l", col = { name = idxName, ply = spell(idxType, ic), code = ic, countPly = spell(idxCount, cc), countCode = cc, sizes = sizes, items = m.corners } }, } -- per-face data of a single primitive if #m.parts == 1 then local ex = m.parts[1].prim.extras local fot: { number }? = nil if type(ex) == "table" and ex.faceOfTriangle then fot = Flatten.numbers(ex.faceOfTriangle, true) end local function perFace(vals: { number }, count: number): { number }? if count == nf then return vals elseif fot and #fot == nf then local out = table.create(nf) for i = 1, nf do local v = vals[fot[i] + 1] if v == nil then return nil end out[i] = v end return out end return nil end local extraRows: { [string]: Row } = {} if type(ex) == "table" and type(ex.faceAttributes) == "table" then for name, acc in ex.faceAttributes do local vals = Flatten.numbers(acc, true) local code = CODE_OF_ACC[acc.type] if vals and code and acc.components == 1 then local pv = perFace(vals, acc.count) if pv then extraRows[name] = { kind = "s", col = { name = name, ply = PLY_NAME[code], code = code, values = pv, stride = 1, offset = 0 } } end end end end if type(ex) == "table" and type(ex.faceLists) == "table" then for name, fl in ex.faceLists do local sz = type(fl) == "table" and Flatten.numbers(fl.sizes, true) local items = type(fl) == "table" and Flatten.numbers(fl.items, true) local code = type(fl) == "table" and (CODES[fl.itemType or ""] or CODE_OF_ACC[fl.items and fl.items.type or ""]) if sz and items and code and #sz == nf and fot == nil then local mx = 0 for _, s in sz do mx = math.max(mx, s) end local lcc = countCodeFor(mx) local scc = CODES[fl.countType or ""] if scc and scc <= 6 and SIZE[scc] >= SIZE[lcc] then lcc = scc end extraRows[name] = { kind = "l", col = { name = name, ply = spell(fl.itemType, code), code = code, countPly = spell(fl.countType, lcc), countCode = lcc, sizes = sz, items = items } } end end end -- the source order, then the rest by name local placed: { [string]: boolean } = { [idxName] = true } local ordered: { Row } = {} for _, fp in fprops do if type(fp) == "table" then if fp.name == idxName then table.insert(ordered, rows[1]) elseif extraRows[fp.name] then table.insert(ordered, extraRows[fp.name]) placed[fp.name] = true end end end if not table.find(ordered, rows[1]) then table.insert(ordered, 1, rows[1]) end local rest = {} for name in extraRows do if not placed[name] then table.insert(rest, name) end end table.sort(rest) for _, name in rest do table.insert(ordered, extraRows[name]) end rows = ordered end faceRows = rows end -- raw elements type Raw = { name: string, count: number, rows: { Row } } local raws: { [string]: Raw } = {} local rawOrder: { string } = {} if type(meta.elements) == "table" then for _, el in meta.elements do if type(el) == "table" and type(el.name) == "string" and type(el.count) == "number" and type(el.properties) == "table" and el.name ~= "vertex" and not raws[el.name] then if el.name == "face" and faceRows then continue end local rows: { Row } = {} for _, pr in el.properties do local code = CODES[pr.type or ""] if not code then return nil, Err.new(Err.ARG, "element " .. el.name .. ": unknown property type") end if pr.countType then local cc = CODES[pr.countType] local sz = cc and bufNumbers(pr.sizes, 6, el.count) local total = 0 if sz then for _, s in sz do total += s end end local items = sz and bufNumbers(pr.values, code, total) if not (cc and sz and items) then return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad list property " .. tostring(pr.name)) end table.insert(rows, { kind = "l", col = { name = pr.name, ply = pr.type, code = code, countPly = pr.countType, countCode = cc, sizes = sz, items = items } }) else local vals = bufNumbers(pr.values, code, el.count) if not vals then return nil, Err.new(Err.ARG, "element " .. el.name .. ": bad property " .. tostring(pr.name)) end table.insert(rows, { kind = "s", col = { name = pr.name, ply = pr.type, code = code, values = vals, stride = 1, offset = 0 } }) end end raws[el.name] = { name = el.name, count = el.count, rows = rows } table.insert(rawOrder, el.name) end end end -- element order: the source's, then vertex, face, the rest local order: { string } = {} local seen: { [string]: boolean } = {} local function want(name: string) if seen[name] then return end if name == "vertex" or (name == "face" and faceRows) or raws[name] then seen[name] = true table.insert(order, name) end end if type(meta.order) == "table" then for _, name in meta.order do if type(name) == "string" then want(name) end end end want("vertex") want("face") for _, name in rawOrder do want(name) end -- header local vrows: { Row } = {} for _, c in cols do table.insert(vrows, { kind = "s", col = c }) end local lines = { "ply", "format " .. enc .. " 1.0" } local function noNewline(s: any): string return (string.gsub(tostring(s), "[\r\n]", " ")) end for _, c in (if type(meta.comments) == "table" then meta.comments else {}) :: { any } do table.insert(lines, "comment " .. noNewline(c)) end for _, c in o.comments or {} do table.insert(lines, "comment " .. noNewline(c)) end for _, c in (if type(meta.objInfo) == "table" then meta.objInfo else {}) :: { any } do table.insert(lines, "obj_info " .. noNewline(c)) end local function elementRows(name: string): (number, { Row }) if name == "vertex" then return nv, vrows elseif name == "face" and faceRows then return nf, faceRows end local raw = raws[name] return raw.count, raw.rows end for _, name in order do local n, rows = elementRows(name) table.insert(lines, "element " .. noNewline(name) .. " " .. string.format("%d", n)) for _, rw in rows do if rw.kind == "s" then local c = rw.col :: Column table.insert(lines, "property " .. c.ply .. " " .. noNewline(c.name)) else local c = rw.col :: ListColumn table.insert(lines, "property list " .. c.countPly .. " " .. c.ply .. " " .. noNewline(c.name)) end end end table.insert(lines, "end_header") local header = table.concat(lines, "\n") .. "\n" if enc == "ascii" then local out = { header } local body: { string } = {} for _, name in order do local n, rows = elementRows(name) rowsAscii(body, n, rows) end if #body > 0 then table.insert(out, table.concat(body, "\n")) table.insert(out, "\n") end return buffer.fromstring(table.concat(out)), nil end local w = Bytes.writer(#header + nv * 32 + nf * 16) w:string(header) for _, name in order do local n, rows = elementRows(name) rowsBinary(w, n, rows, enc == "binary_big_endian") end return w:finish(), nil end return Ply