--!strict -- model/iqm/Read: an Inter-Quake Model (version 2) -> Types.Scene. From the IQM format description (iqm.txt and -- iqm.h of the IQM SDK by Lee Salzman, public domain), checked against assimp's IQM importer (no code taken). -- Every header range is checked against the data before it is read. Plain code (the caller wraps it in pcall). local Types = require("@formats/Types") local Rig = require("@formats/codecs/model/Rig") local Read = {} local Scene = Types.Scene local readu8, readi8, readu16, readi16, readu32, readi32, readf32, readf64 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64 local writef32, writeu32, writeu8, writeu16 = buffer.writef32, buffer.writeu32, buffer.writeu8, buffer.writeu16 Read.HEADER = { "version", "filesize", "flags", "num_text", "ofs_text", "num_meshes", "ofs_meshes", "num_vertexarrays", "num_vertexes", "ofs_vertexarrays", "num_triangles", "ofs_triangles", "ofs_adjacency", "num_joints", "ofs_joints", "num_poses", "ofs_poses", "num_anims", "ofs_anims", "num_frames", "num_framechannels", "ofs_frames", "ofs_bounds", "num_comment", "ofs_comment", "num_extensions", "ofs_extensions", } Read.SIZES = { [0] = 1, 1, 2, 2, 4, 4, 2, 4, 8 } -- byte, ubyte, short, ushort, int, uint, half, float, double Read.ARRAYS = { [0] = "position", "texcoord", "normal", "tangent", "blendindexes", "blendweights", "color" } local function half(h: number): number local s = if bit32.band(h, 0x8000) ~= 0 then -1 else 1 local e = bit32.band(bit32.rshift(h, 10), 0x1F) local m = bit32.band(h, 0x3FF) if e == 0 then return s * m * 2 ^ -24 elseif e == 31 then return if m == 0 then s * math.huge else 0 end return s * (1 + m / 1024) * 2 ^ (e - 15) end -- the values of one vertex array element range as numbers (normalized = integer formats scaled to 0..1 / -1..1) local function values(b: buffer, at: number, format: number, n: number, normalized: boolean): { number } local out = table.create(n) :: { number } local size = Read.SIZES[format] for i = 0, n - 1 do local p = at + i * size local v: number if format == 0 then v = readi8(b, p) v = if normalized then math.max(v / 127, -1) else v elseif format == 1 then v = readu8(b, p) v = if normalized then v / 255 else v elseif format == 2 then v = readi16(b, p) v = if normalized then math.max(v / 32767, -1) else v elseif format == 3 then v = readu16(b, p) v = if normalized then v / 65535 else v elseif format == 4 then v = readi32(b, p) elseif format == 5 then v = readu32(b, p) elseif format == 6 then v = half(readu16(b, p)) elseif format == 7 then v = readf32(b, p) else v = readf64(b, p) end out[i + 1] = v end return out end local function f32acc(vals: { number }, comps: number): Types.Accessor local d = buffer.create(#vals * 4) for i, v in vals do writef32(d, (i - 1) * 4, v) end return Scene.accessor(d, "f32", comps, #vals // comps) end local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", dds = "image/vnd-ms.dds" } -- scene(b, base, limit, opts) -> Scene | nil, message function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: number? }?): (Types.Scene?, string?) local size = limit - base local H: { [string]: number } = {} for i, name in Read.HEADER do H[name] = readu32(b, base + 12 + i * 4) end if H.version ~= 2 then return nil, "unsupported: IQM version " .. H.version .. " (only 2)" end if H.filesize > size then return nil, "truncated: the header says " .. H.filesize .. " bytes, " .. size .. " present" end local maxV = opts and opts.maxVertices or 2 ^ 25 if H.num_vertexes > maxV or H.num_triangles > maxV then return nil, "limit: more than " .. maxV .. " vertices / triangles" end local function range(ofs: number, count: number, each: number, what: string): string? if count > 0 and (ofs < 124 or count * each > H.filesize or ofs + count * each > H.filesize) then return "the " .. what .. " lie outside the file" end return nil end local err = range(H.ofs_text, H.num_text, 1, "text") or range(H.ofs_meshes, H.num_meshes, 24, "meshes") or range(H.ofs_vertexarrays, H.num_vertexarrays, 20, "vertex arrays") or range(H.ofs_triangles, H.num_triangles, 12, "triangles") or range(H.ofs_joints, H.num_joints, 48, "joints") or range(H.ofs_poses, H.num_poses, 88, "poses") or range(H.ofs_anims, H.num_anims, 20, "anims") or range(H.ofs_frames, H.num_frames * H.num_framechannels, 2, "frames") or range(H.ofs_bounds, if H.ofs_bounds > 0 then H.num_frames else 0, 32, "bounds") or range(H.ofs_comment, H.num_comment, 1, "comment") if err then return nil, err end local text = if H.num_text > 0 then buffer.readstring(b, base + H.ofs_text, H.num_text) else "" local function str(ofs: number): string if ofs >= #text then return "" end local z = string.find(text, "\0", ofs + 1, true) return string.sub(text, ofs + 1, (z or #text + 1) - 1) end local scene = Scene.new() scene.meta.up = "z" local source: { [string]: any } = { format = "iqm", version = 2, flags = H.flags } scene.meta.source = source if H.num_comment > 0 then source.comment = string.match(buffer.readstring(b, base + H.ofs_comment, H.num_comment), "^[^%z]*") end -- vertex arrays (the whole model's vertices; meshes are ranges of them) local nv = H.num_vertexes type Array = { kind: string, name: string, format: number, comps: number, offset: number } local arrays: { Array } = {} for i = 0, H.num_vertexarrays - 1 do local p = base + H.ofs_vertexarrays + i * 20 local typ, format, comps, offset = readu32(b, p), readu32(b, p + 8), readu32(b, p + 12), readu32(b, p + 16) local esize = Read.SIZES[format] if not esize or comps < 1 or comps > 16 then return nil, "vertex array " .. i .. " has format " .. format .. " / " .. comps .. " components" end local e = range(offset, nv, comps * esize, "vertex array " .. i) if e then return nil, e end local kind = Read.ARRAYS[typ] local name = if kind then kind else "_" .. (if typ >= 0x10 then str(typ - 0x10) else tostring(typ)) table.insert(arrays, { kind = kind or "custom", name = name, format = format, comps = comps, offset = base + offset }) end -- joints -> nodes + a skin local jointNodes: { number } = {} local skin: number? = nil if H.num_joints > 0 then local joints: { Rig.Joint } = {} for j = 0, H.num_joints - 1 do local p = base + H.ofs_joints + j * 48 local parent = readi32(b, p + 4) local f = table.create(10) :: { number } for k = 0, 9 do f[k + 1] = readf32(b, p + 8 + k * 4) end local q = { f[4], f[5], f[6], f[7] } local ql = math.sqrt(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2) q = if ql > 0 then { q[1] / ql, q[2] / ql, q[3] / ql, q[4] / ql } else { 0, 0, 0, 1 } joints[j + 1] = { name = str(readu32(b, p)), parent = parent + 1, translation = { f[1], f[2], f[3] }, rotation = q, scale = { f[8], f[9], f[10] } } end jointNodes, skin = Rig.skeleton(scene, joints, "local") end -- materials: one per distinct material string (IQM names its texture there) local matOf: { [string]: number } = {} local function material(name: string): number? if name == "" then return nil end local hit = matOf[name] if hit then return hit end local mat = Scene.material(name) mat.metallic = 0 local ext = string.lower(string.match(name, "%.(%w+)$") or "") table.insert(scene.textures, { name = name, uri = name, mime = MIME[ext] }) mat.baseColorTexture = { texture = #scene.textures } table.insert(scene.materials, mat) matOf[name] = #scene.materials return #scene.materials end -- meshes for m = 0, H.num_meshes - 1 do local p = base + H.ofs_meshes + m * 24 local name, mname = str(readu32(b, p)), str(readu32(b, p + 4)) local fv, cv, ft, ct = readu32(b, p + 8), readu32(b, p + 12), readu32(b, p + 16), readu32(b, p + 20) if fv + cv > nv or ft + ct > H.num_triangles then return nil, "mesh " .. m .. " points outside the vertex / triangle arrays" end local attributes: { [string]: Types.Accessor } = {} for _, a in arrays do local esize = Read.SIZES[a.format] local at = a.offset + fv * a.comps * esize if a.kind == "blendindexes" then local vals = values(b, at, a.format, cv * a.comps, false) local big = a.format ~= 1 local d = buffer.create(cv * 4 * (if big then 2 else 1)) for v = 0, cv - 1 do for c = 0, 3 do local x = if c < a.comps then vals[v * a.comps + c + 1] else 0 x = math.clamp(math.floor(x), 0, if big then 65535 else 255) if big then writeu16(d, (v * 4 + c) * 2, x) else writeu8(d, v * 4 + c, x) end end end attributes.JOINTS_0 = Scene.accessor(d, if big then "u16" else "u8", 4, cv) elseif a.kind == "blendweights" or (a.kind == "color" and a.format == 1) then local vals = values(b, at, a.format, cv * a.comps, true) local d = buffer.create(cv * 4) for v = 0, cv - 1 do for c = 0, 3 do local x = if c < a.comps then vals[v * a.comps + c + 1] elseif a.kind == "color" and c == 3 then 1 else 0 writeu8(d, v * 4 + c, math.clamp(math.floor(x * 255 + 0.5), 0, 255)) end end attributes[if a.kind == "color" then "COLOR_0" else "WEIGHTS_0"] = Scene.accessor(d, "unorm8", 4, cv) else local vals = values(b, at, a.format, cv * a.comps, true) local name0 = if a.kind == "position" then "POSITION" elseif a.kind == "texcoord" then "TEXCOORD_0" elseif a.kind == "normal" then "NORMAL" elseif a.kind == "tangent" then "TANGENT" elseif a.kind == "color" then "COLOR_0" else a.name local want = if a.kind == "position" or a.kind == "normal" then 3 elseif a.kind == "texcoord" then 2 elseif a.kind == "tangent" or a.kind == "color" then 4 else a.comps if want ~= a.comps then local fixed = table.create(cv * want, 0) :: { number } for v = 0, cv - 1 do for c = 0, want - 1 do fixed[v * want + c + 1] = if c < a.comps then vals[v * a.comps + c + 1] elseif c == 3 then 1 else 0 end end vals = fixed end attributes[name0] = f32acc(vals, want) end end if not attributes.POSITION then return nil, "no position array" end -- triangles: IQM's front faces are clockwise; corners 2 and 3 swap for glTF's counter-clockwise local ib = buffer.create(ct * 12) for k = 0, ct - 1 do local q = base + H.ofs_triangles + (ft + k) * 12 local a, c2, c3 = readu32(b, q), readu32(b, q + 4), readu32(b, q + 8) if a < fv or c2 < fv or c3 < fv or a >= fv + cv or c2 >= fv + cv or c3 >= fv + cv then return nil, "triangle " .. (ft + k) .. " uses a vertex outside mesh " .. m end writeu32(ib, k * 12, a - fv) writeu32(ib, k * 12 + 4, c3 - fv) writeu32(ib, k * 12 + 8, c2 - fv) end local prim: Types.Primitive = { attributes = attributes, indices = Scene.accessor(ib, "u32", 1, ct * 3), mode = "triangles", material = material(mname) } table.insert(scene.meshes, { name = name, primitives = { prim } }) local node: Types.Node = { name = name, children = {}, mesh = #scene.meshes } if skin and attributes.JOINTS_0 then node.skin = skin end table.insert(scene.nodes, node) table.insert(scene.roots, #scene.nodes) end -- animations: frames hold the masked pose channels (offset + value * scale), in pose order if H.num_anims > 0 and H.num_frames > 0 and H.num_poses > 0 then local np = H.num_poses local poses: { { mask: number, offset: { number }, scale: { number } } } = {} local channels = 0 for i = 0, np - 1 do local p = base + H.ofs_poses + i * 88 local mask = readu32(b, p + 4) local off, sc = table.create(10) :: { number }, table.create(10) :: { number } for c = 0, 9 do off[c + 1] = readf32(b, p + 8 + c * 4) sc[c + 1] = readf32(b, p + 48 + c * 4) if bit32.band(mask, bit32.lshift(1, c)) ~= 0 then channels += 1 end end poses[i + 1] = { mask = mask, offset = off, scale = sc } end if channels ~= H.num_framechannels then return nil, "the poses use " .. channels .. " frame channels, the header says " .. H.num_framechannels end -- frame f, pose i -> 10 values local frameBytes: number = H.num_framechannels * 2 local framesAt: number = base + H.ofs_frames local function frame(f: number): { { number } } local out = table.create(np) :: { { number } } local q = framesAt + f * frameBytes for i = 1, np do local ps = poses[i] local v = table.create(10) :: { number } for c = 0, 9 do local x = ps.offset[c + 1] if bit32.band(ps.mask, bit32.lshift(1, c)) ~= 0 then local k: number = ps.scale[c + 1] x += readu16(b, q) * k q += 2 end v[c + 1] = x end out[i] = v end return out end local anims: { any } = {} for a = 0, H.num_anims - 1 do local p = base + H.ofs_anims + a * 20 local name, first, count, rate, flags = str(readu32(b, p)), readu32(b, p + 4), readu32(b, p + 8), readf32(b, p + 12), readu32(b, p + 16) if first + count > H.num_frames then return nil, "animation " .. a .. " uses frames past the end" end local fps = if rate > 0 and rate == rate then rate else 30 local times = table.create(count) :: { number } local tracks: { [number]: Rig.Track } = {} for j = 1, math.min(np, #jointNodes) do tracks[j] = { translation = {}, rotation = {}, scale = {} } end for k = 0, count - 1 do times[k + 1] = k / fps local fr = frame(first + k) for j, tr in tracks do local v = fr[j] local t, r, s = tr.translation :: { number }, tr.rotation :: { number }, tr.scale :: { number } table.move(v, 1, 3, #t + 1, t) local ql = math.sqrt(v[4] ^ 2 + v[5] ^ 2 + v[6] ^ 2 + v[7] ^ 2) ql = if ql > 0 then ql else 1 table.move({ v[4] / ql, v[5] / ql, v[6] / ql, v[7] / ql }, 1, 4, #r + 1, r) table.move(v, 8, 10, #s + 1, s) end end if count > 0 then Rig.animation(scene, name, jointNodes, times, tracks) end table.insert(anims, { name = name, first = first, frames = count, framerate = rate, loop = bit32.band(flags, 1) ~= 0 }) end source.animations = anims end -- bounds: one box per frame if H.ofs_bounds > 0 and H.num_frames > 0 then local boxes = {} for f = 0, H.num_frames - 1 do local p = base + H.ofs_bounds + f * 32 boxes[f + 1] = { min = { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) }, max = { readf32(b, p + 12), readf32(b, p + 16), readf32(b, p + 20) }, xyradius = readf32(b, p + 24), radius = readf32(b, p + 28), } end source.bounds = boxes end return scene, nil end return Read