//! CPU mesh data and sampled node transforms. No renderer or GPU ownership. const std = @import("std"); const gltf = @import("gltf.zig"); const c = gltf.c; pub const Vertex = extern struct { position: [3]f32, normal: [3]f32 }; pub const Primitive = struct { vertices: []Vertex, indices: []u32, color: [4]f32 = .{ 1, 1, 1, 1 }, double_sided: bool = false, }; pub const Mesh = struct { primitives: []Primitive }; pub const Camera = union(enum) { perspective: struct { yfov: f32, znear: f32, zfar: ?f32, aspect_ratio: ?f32 }, orthographic: struct { xmag: f32, ymag: f32, znear: f32, zfar: f32 }, }; pub const Node = struct { mesh: ?usize, camera: ?usize = null, parent: ?usize, world: [16]f32 = undefined, visible: bool, }; const Track = struct { node: usize, path: c.cgltf_animation_path_type, interpolation: c.cgltf_interpolation_type, times: []f32, values: [][4]f32, }; const Animation = struct { tracks: []Track, duration: f32 }; pub const Scene = struct { arena: std.heap.ArenaAllocator, meshes: []Mesh, cameras: []Camera, nodes: []Node, animations: []Animation, base: []c.cgltf_node, pose: []c.cgltf_node, /// Copies geometry and tracks from a document whose buffers are loaded. /// The document can be released after this returns. Indices match glTF. pub fn init(allocator: std.mem.Allocator, document: gltf.Document) !Scene { var arena = std.heap.ArenaAllocator.init(allocator); errdefer arena.deinit(); const a = arena.allocator(); const data = document.data; const meshes = try a.alloc(Mesh, data.meshes_count); for (meshes, 0..) |*mesh, i| { const source = data.meshes[i]; mesh.primitives = try a.alloc(Primitive, source.primitives_count); for (mesh.primitives, 0..) |*primitive, j| primitive.* = try readPrimitive(a, @ptrCast(&source.primitives[j])); } const cameras = try a.alloc(Camera, data.cameras_count); for (cameras, 0..) |*camera, i| { const source = data.cameras[i]; camera.* = switch (source.type) { c.cgltf_camera_type_perspective => blk: { const p = source.data.perspective; try finite(&.{ p.yfov, p.znear }); if (p.yfov <= 0 or p.yfov >= std.math.pi or p.znear <= 0) return error.InvalidCamera; if (p.has_zfar != 0 and (!std.math.isFinite(p.zfar) or p.zfar <= p.znear)) return error.InvalidCamera; if (p.has_aspect_ratio != 0 and (!std.math.isFinite(p.aspect_ratio) or p.aspect_ratio <= 0)) return error.InvalidCamera; break :blk .{ .perspective = .{ .yfov = p.yfov, .znear = p.znear, .zfar = if (p.has_zfar != 0) p.zfar else null, .aspect_ratio = if (p.has_aspect_ratio != 0) p.aspect_ratio else null, } }; }, c.cgltf_camera_type_orthographic => blk: { const o = source.data.orthographic; try finite(&.{ o.xmag, o.ymag, o.znear, o.zfar }); if (o.xmag == 0 or o.ymag == 0 or o.znear < 0 or o.zfar <= o.znear) return error.InvalidCamera; break :blk .{ .orthographic = .{ .xmag = o.xmag, .ymag = o.ymag, .znear = o.znear, .zfar = o.zfar } }; }, else => return error.UnsupportedCamera, }; } const nodes = try a.alloc(Node, data.nodes_count); const base = try a.dupe(c.cgltf_node, document.nodes()); for (nodes, base) |*node, source| { if (source.skin != null) return error.UnsupportedSkin; if (source.has_mesh_gpu_instancing != 0) return error.UnsupportedInstancing; node.* = .{ .mesh = if (source.mesh != null) c.cgltf_mesh_index(data, source.mesh) else null, .camera = if (source.camera != null) c.cgltf_camera_index(data, source.camera) else null, .parent = if (source.parent != null) c.cgltf_node_index(data, source.parent) else null, .visible = data.scene == null, }; } // A glTF scene selects roots; other scene nodes stay addressable but hidden. if (data.scene != null) for (nodes, 0..) |*node, i| { var root = i; var depth: usize = 0; while (nodes[root].parent) |parent| { root = parent; depth += 1; if (depth > nodes.len) return error.InvalidHierarchy; } const selected = data.scene.*; for (0..selected.nodes_count) |j| { if (root == c.cgltf_node_index(data, selected.nodes[j])) node.visible = true; } }; const animations = try a.alloc(Animation, data.animations_count); for (animations, 0..) |*animation, i| { const source = data.animations[i]; animation.* = .{ .tracks = try a.alloc(Track, source.channels_count), .duration = 0 }; for (animation.tracks, 0..) |*track, j| { const channel = source.channels[j]; if (channel.target_node == null) return error.UnsupportedAnimationTarget; const node = c.cgltf_node_index(data, channel.target_node); if (base[node].has_matrix != 0) return error.AnimatedMatrix; const components: usize = switch (channel.target_path) { c.cgltf_animation_path_type_translation, c.cgltf_animation_path_type_scale => 3, c.cgltf_animation_path_type_rotation => 4, else => return error.UnsupportedAnimationTarget, }; const sampler = channel.sampler.*; const multiplier: usize = switch (sampler.interpolation) { c.cgltf_interpolation_type_linear, c.cgltf_interpolation_type_step => 1, c.cgltf_interpolation_type_cubic_spline => 3, else => return error.UnsupportedInterpolation, }; if (sampler.input.*.count == 0 or sampler.output.*.count != try std.math.mul(usize, sampler.input.*.count, multiplier)) return error.InvalidAnimation; track.* = .{ .node = node, .path = channel.target_path, .interpolation = sampler.interpolation, .times = try a.alloc(f32, sampler.input.*.count), .values = try a.alloc([4]f32, sampler.output.*.count) }; for (track.times, 0..) |*time, k| { try gltf.readFloats(sampler.input, k, @as(*[1]f32, @ptrCast(time))); if (!std.math.isFinite(time.*) or time.* < 0 or (k > 0 and time.* <= track.times[k - 1])) return error.InvalidAnimation; } for (track.values, 0..) |*value, k| { value.* = .{ 0, 0, 0, 0 }; try gltf.readFloats(sampler.output, k, value[0..components]); try finite(value); } animation.duration = @max(animation.duration, track.times[track.times.len - 1]); } } var scene: Scene = .{ .arena = arena, .meshes = meshes, .cameras = cameras, .nodes = nodes, .animations = animations, .base = base, .pose = try a.dupe(c.cgltf_node, base) }; try scene.updateWorld(); return scene; } pub fn deinit(self: *Scene) void { self.arena.deinit(); self.* = undefined; } pub fn duration(self: *const Scene, animation: usize) !f32 { if (animation >= self.animations.len) return error.InvalidAnimationIndex; return self.animations[animation].duration; } /// Samples seconds, clamped to each track's range. Looping belongs to callers. pub fn sample(self: *Scene, animation: usize, seconds: f32) !void { if (animation >= self.animations.len) return error.InvalidAnimationIndex; if (!std.math.isFinite(seconds)) return error.InvalidAnimationTime; @memcpy(self.pose, self.base); for (self.animations[animation].tracks) |track| { const value = try sampleTrack(track, seconds); const node = &self.pose[track.node]; switch (track.path) { c.cgltf_animation_path_type_translation => node.translation = value[0..3].*, c.cgltf_animation_path_type_rotation => node.rotation = value, c.cgltf_animation_path_type_scale => node.scale = value[0..3].*, else => unreachable, } } try self.updateWorld(); } pub fn reset(self: *Scene) !void { @memcpy(self.pose, self.base); try self.updateWorld(); } fn updateWorld(self: *Scene) !void { for (self.nodes, self.pose) |*node, *pose| { c.cgltf_node_transform_local(pose, &node.world); var ancestor = node.parent; var depth: usize = 0; while (ancestor) |index| { var parent: [16]f32 = undefined; c.cgltf_node_transform_local(&self.pose[index], &parent); node.world = multiply(parent, node.world); ancestor = self.nodes[index].parent; depth += 1; if (depth > self.nodes.len) return error.InvalidHierarchy; } try finite(&node.world); } } }; fn readPrimitive(a: std.mem.Allocator, primitive: *const c.cgltf_primitive) !Primitive { if (primitive.type != c.cgltf_primitive_type_triangles) return error.UnsupportedPrimitive; if (primitive.targets_count != 0) return error.UnsupportedMorphTargets; if (primitive.has_draco_mesh_compression != 0) return error.UnsupportedCompression; var positions: [*c]c.cgltf_accessor = null; var normals: [*c]c.cgltf_accessor = null; for (0..primitive.attributes_count) |i| { const attr = primitive.attributes[i]; if (attr.type == c.cgltf_attribute_type_position) positions = attr.data; if (attr.type == c.cgltf_attribute_type_normal) normals = attr.data; } if (positions == null or positions.*.count == 0 or positions.*.count > std.math.maxInt(u32)) return error.InvalidPositions; if (normals != null and normals.*.count != positions.*.count) return error.InvalidNormals; var out: Primitive = .{ .vertices = try a.alloc(Vertex, positions.*.count), .indices = try a.alloc(u32, if (primitive.indices != null) primitive.indices.*.count else positions.*.count) }; if (out.indices.len % 3 != 0) return error.InvalidTriangles; for (out.vertices, 0..) |*vertex, i| { try gltf.readFloats(positions, i, &vertex.position); try finite(&vertex.position); vertex.normal = .{ 0, 0, 0 }; if (normals != null) { try gltf.readFloats(normals, i, &vertex.normal); try finite(&vertex.normal); } } if (primitive.indices != null) { const accessor = primitive.indices; if (accessor.*.type != c.cgltf_type_scalar or (accessor.*.component_type != c.cgltf_component_type_r_8u and accessor.*.component_type != c.cgltf_component_type_r_16u and accessor.*.component_type != c.cgltf_component_type_r_32u)) return error.InvalidIndices; // cgltf's uint reader handles sparse indices without lossy f32 conversion. if (accessor.*.is_sparse != 0 and (c.cgltf_buffer_view_data(accessor.*.sparse.indices_buffer_view) == null or c.cgltf_buffer_view_data(accessor.*.sparse.values_buffer_view) == null)) return error.MissingBuffer; for (out.indices, 0..) |*index, i| { if (c.cgltf_accessor_read_uint(accessor, i, @ptrCast(index), 1) == 0) return error.MissingBuffer; if (index.* >= out.vertices.len) return error.InvalidIndices; } } else { for (out.indices, 0..) |*index, i| index.* = @intCast(i); } // With no authored normals, split triangles to preserve flat faces. if (normals == null) { const expanded = try a.alloc(Vertex, out.indices.len); var i: usize = 0; while (i < out.indices.len) : (i += 3) { const p = out.vertices[out.indices[i]].position; const q = out.vertices[out.indices[i + 1]].position; const r = out.vertices[out.indices[i + 2]].position; const u = [3]f32{ q[0] - p[0], q[1] - p[1], q[2] - p[2] }; const v = [3]f32{ r[0] - p[0], r[1] - p[1], r[2] - p[2] }; var normal = [3]f32{ u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0] }; const length = @sqrt(normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2]); if (length > 0) for (&normal) |*n| { n.* /= length; }; for (0..3) |j| { expanded[i + j] = .{ .position = out.vertices[out.indices[i + j]].position, .normal = normal }; out.indices[i + j] = @intCast(i + j); } } out.vertices = expanded; } if (primitive.material != null) { out.color = primitive.material.*.pbr_metallic_roughness.base_color_factor; out.double_sided = primitive.material.*.double_sided != 0; try finite(&out.color); } return out; } fn finite(values: []const f32) !void { for (values) |v| if (!std.math.isFinite(v)) return error.NonFiniteValue; } /// Column-major multiplication, compatible with glTF and shader mat4 values. pub fn multiply(a: [16]f32, b: [16]f32) [16]f32 { var out: [16]f32 = undefined; for (0..4) |col| for (0..4) |row| { var value: f32 = 0; for (0..4) |k| value += a[k * 4 + row] * b[col * 4 + k]; out[col * 4 + row] = value; }; return out; } fn sampleTrack(track: Track, seconds: f32) ![4]f32 { const cubic = track.interpolation == c.cgltf_interpolation_type_cubic_spline; const stride: usize = if (cubic) 3 else 1; const offset: usize = if (cubic) 1 else 0; var lo: usize = 0; var hi = track.times.len; while (lo < hi) { const mid = lo + (hi - lo) / 2; if (track.times[mid] <= seconds) lo = mid + 1 else hi = mid; } const first = lo -| 1; const last = @min(first + 1, track.times.len - 1); var result = track.values[first * stride + offset]; const rotation = track.path == c.cgltf_animation_path_type_rotation; if (seconds > track.times[first] and first != last and track.interpolation != c.cgltf_interpolation_type_step) { const dt = track.times[last] - track.times[first]; const t = (seconds - track.times[first]) / dt; var next = track.values[last * stride + offset]; if (cubic) { const t2 = t * t; const t3 = t2 * t; const a = track.values[first * stride + 2]; const b = track.values[last * stride]; for (&result, 0..) |*v, i| v.* = (2 * t3 - 3 * t2 + 1) * v.* + (t3 - 2 * t2 + t) * dt * a[i] + (-2 * t3 + 3 * t2) * next[i] + (t3 - t2) * dt * b[i]; } else if (rotation) { result = try normalizeQuaternion(result); next = try normalizeQuaternion(next); var dot: f32 = 0; for (result, next) |a, b| dot += a * b; if (dot < 0) { dot = -dot; for (&next) |*v| v.* = -v.*; } dot = std.math.clamp(dot, 0, 1); const angle = std.math.acos(dot); const denominator = @sin(angle); const a = if (dot > 0.9995) 1 - t else @sin((1 - t) * angle) / denominator; const b = if (dot > 0.9995) t else @sin(t * angle) / denominator; for (&result, next) |*v, n| v.* = a * v.* + b * n; } else { for (&result, next) |*v, n| v.* += (n - v.*) * t; } } try finite(&result); return if (rotation) normalizeQuaternion(result) else result; } fn normalizeQuaternion(q: [4]f32) ![4]f32 { var length: f32 = 0; for (q) |v| length += v * v; if (!std.math.isFinite(length) or length < 1e-12) return error.InvalidQuaternion; var out = q; for (&out) |*v| v.* /= @sqrt(length); return out; } test "animation interpolation clamps, steps, slerps shortest path, and scales cubic tangents by time" { var times = [_]f32{ 0, 2 }; var values = [_][4]f32{ .{ 0, 0, 0, 0 }, .{ 2, 4, 6, 0 } }; var track: Track = .{ .node = 0, .path = c.cgltf_animation_path_type_translation, .interpolation = c.cgltf_interpolation_type_linear, .times = ×, .values = &values }; try std.testing.expectEqualSlices(f32, &.{ 1, 2, 3, 0 }, &(try sampleTrack(track, 1))); try std.testing.expectEqualSlices(f32, &values[0], &(try sampleTrack(track, -1))); try std.testing.expectEqualSlices(f32, &values[1], &(try sampleTrack(track, 9))); track.interpolation = c.cgltf_interpolation_type_step; try std.testing.expectEqualSlices(f32, &values[0], &(try sampleTrack(track, 1))); track.path = c.cgltf_animation_path_type_rotation; track.interpolation = c.cgltf_interpolation_type_linear; values = .{ .{ 0, 0, 0, 1 }, .{ 0, 0, -0.70710678, -0.70710678 } }; const q = try sampleTrack(track, 1); try std.testing.expectApproxEqAbs(@as(f32, 0.38268343), q[2], 0.00001); try std.testing.expectApproxEqAbs(@as(f32, 0.92387953), q[3], 0.00001); var cubic = [_][4]f32{ .{ 0, 0, 0, 0 }, .{ 0, 0, 0, 0 }, .{ 2, 0, 0, 0 }, .{ 0, 0, 0, 0 }, .{ 0, 0, 0, 0 }, .{ 0, 0, 0, 0 } }; track.path = c.cgltf_animation_path_type_translation; track.interpolation = c.cgltf_interpolation_type_cubic_spline; track.values = &cubic; try std.testing.expectApproxEqAbs(@as(f32, 0.5), (try sampleTrack(track, 1))[0], 0.00001); } test "scene copies hierarchy and restricts visibility to selected scene" { const doc = try gltf.Document.parse( \\{"asset":{"version":"2.0"},"scene":0,"scenes":[{"nodes":[1]}],"nodes":[{"translation":[0,2,0]},{"translation":[3,0,0],"children":[2]},{"translation":[0,4,0]}]} ); defer doc.deinit(); var scene = try Scene.init(std.testing.allocator, doc); defer scene.deinit(); try std.testing.expect(!scene.nodes[0].visible); try std.testing.expect(scene.nodes[2].visible); try std.testing.expectEqual(@as(f32, 3), scene.nodes[2].world[12]); try std.testing.expectEqual(@as(f32, 4), scene.nodes[2].world[13]); try std.testing.expectError(error.InvalidAnimationIndex, scene.sample(0, 0)); } test "indexed mesh flat normals, material and decoded animation survive document release" { const doc = try gltf.Document.parse( \\{"asset":{"version":"2.0"},"buffers":[{"byteLength":72,"uri":"data:application/octet-stream;base64,AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAAAgABAAAAAAAAAABAAAAAAAAAAAAAAAAAAACAQAAAAAAAAAAA"}],"bufferViews":[{"buffer":0,"byteOffset":0,"byteLength":36},{"buffer":0,"byteOffset":36,"byteLength":3},{"buffer":0,"byteOffset":40,"byteLength":8},{"buffer":0,"byteOffset":48,"byteLength":24}],"accessors":[{"bufferView":0,"componentType":5126,"count":3,"type":"VEC3","min":[0,0,0],"max":[1,1,0]},{"bufferView":1,"componentType":5121,"count":3,"type":"SCALAR"},{"bufferView":2,"componentType":5126,"count":2,"type":"SCALAR","min":[0],"max":[2]},{"bufferView":3,"componentType":5126,"count":2,"type":"VEC3"}],"materials":[{"pbrMetallicRoughness":{"baseColorFactor":[0.2,0.4,0.6,1]},"doubleSided":true}],"meshes":[{"primitives":[{"attributes":{"POSITION":0},"indices":1,"material":0}]}],"nodes":[{"translation":[0,3,0],"children":[1]},{"mesh":0}],"animations":[{"samplers":[{"input":2,"output":3}],"channels":[{"sampler":0,"target":{"node":1,"path":"translation"}}]}]} ); var scene = blk: { defer doc.deinit(); try doc.loadBuffers(null); break :blk try Scene.init(std.testing.allocator, doc); }; defer scene.deinit(); const primitive = scene.meshes[0].primitives[0]; try std.testing.expectEqualSlices(f32, &.{ 0, 1, 0 }, &primitive.vertices[0].position); try std.testing.expectEqualSlices(f32, &.{ 0, 0, 1 }, &primitive.vertices[0].normal); try std.testing.expectEqualSlices(u32, &.{ 0, 1, 2 }, primitive.indices); try std.testing.expectApproxEqAbs(@as(f32, 0.4), primitive.color[1], 0.00001); try std.testing.expect(primitive.double_sided); try std.testing.expectEqual(@as(f32, 2), try scene.duration(0)); try scene.sample(0, 1); try std.testing.expectEqual(@as(f32, 2), scene.nodes[1].world[12]); try std.testing.expectEqual(@as(f32, 3), scene.nodes[1].world[13]); try scene.sample(0, 0); try std.testing.expectEqual(@as(f32, 0), scene.nodes[1].world[12]); try std.testing.expectError(error.InvalidAnimationTime, scene.sample(0, std.math.nan(f32))); } test "perspective and orthographic cameras survive document release" { const doc = try gltf.Document.parse( \\{"asset":{"version":"2.0"},"cameras":[{"type":"perspective","perspective":{"yfov":0.8,"znear":0.1}},{"type":"perspective","perspective":{"yfov":1,"znear":1,"zfar":100,"aspectRatio":1.5}},{"type":"orthographic","orthographic":{"xmag":8,"ymag":6,"znear":0,"zfar":50}}],"nodes":[{"camera":0},{"camera":1},{"camera":2}]} ); var scene = blk: { defer doc.deinit(); break :blk try Scene.init(std.testing.allocator, doc); }; defer scene.deinit(); const infinite = scene.cameras[scene.nodes[0].camera.?].perspective; try std.testing.expectEqual(@as(f32, 0.8), infinite.yfov); try std.testing.expect(infinite.zfar == null and infinite.aspect_ratio == null); const perspective = scene.cameras[scene.nodes[1].camera.?].perspective; try std.testing.expectEqual(@as(f32, 100), perspective.zfar.?); try std.testing.expectEqual(@as(f32, 1.5), perspective.aspect_ratio.?); const orthographic = scene.cameras[scene.nodes[2].camera.?].orthographic; try std.testing.expectEqual(@as(f32, 8), orthographic.xmag); try std.testing.expectEqual(@as(f32, 6), orthographic.ymag); try std.testing.expectEqual(@as(f32, 0), orthographic.znear); try std.testing.expectEqual(@as(f32, 50), orthographic.zfar); }