1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
|
//! Basic opaque glTF drawing. Geometry uploads once; each frame submits transforms.
//! shortcut: base colors only; add texture/alpha handling when the assets need it.
const std = @import("std");
const sk = @import("sketch");
const gltf = @import("gltf");
const shaders = @import("shaders");
const types = @import("types");
pub const math = @import("math.zig");
pub const Camera = math.Camera;
pub const Vertex = types.Vertex;
pub const supported = true;
const gpu = sk.abi.gpu;
/// Camera projection plus the sampled node transform; no Blender constraint solver.
pub fn sceneCamera(scene: *const gltf.Scene, node_index: usize) !Camera {
if (node_index >= scene.nodes.len) return error.InvalidCameraNode;
const node = scene.nodes[node_index];
const index = node.camera orelse return error.NodeHasNoCamera;
const m = node.world;
var camera: Camera = .{
.eye = .{ m[12], m[13], m[14] },
.target = .{ m[12] - m[8], m[13] - m[9], m[14] - m[10] },
.up = .{ m[4], m[5], m[6] },
};
switch (scene.cameras[index]) {
.perspective => |p| {
camera.fov = p.yfov;
camera.near = p.znear;
camera.far = p.zfar orelse std.math.inf(f32);
camera.aspect_ratio = p.aspect_ratio;
},
.orthographic => |o| {
camera.orthographic = .{ .xmag = o.xmag, .ymag = o.ymag };
camera.near = o.znear;
camera.far = o.zfar;
},
}
return camera;
}
pub const Geometry = struct {
vertices: []const Vertex,
buffer: sk.abi.Buffer = .none,
pub fn upload(g: *Geometry, host: sk.Host) !void {
if (g.buffer != .none) return;
const bytes = std.mem.sliceAsBytes(g.vertices);
if (bytes.len == 0 or bytes.len > std.math.maxInt(u32)) return error.InvalidGeometrySize;
g.buffer = host.newBuffer(@intCast(bytes.len));
if (g.buffer == .none) return error.GpuBufferCreationFailed;
errdefer g.release(host);
try host.writeBuffer(g.buffer, 0, bytes);
}
pub fn release(g: *Geometry, host: sk.Host) void {
if (g.buffer != .none) host.freeBuffer(g.buffer);
g.buffer = .none;
}
};
pub const Model = struct {
scene: gltf.Scene,
geometry: []Geometry,
/// Read the generated asset filename, validate its binding hash, and upload once.
pub fn load(setup: *sk.Init, comptime asset: type) !Model {
const bytes = setup.host.readFile(asset.source_path);
var hash: [32]u8 = undefined;
std.crypto.hash.sha2.Sha256.hash(bytes, &hash, .{});
if (!std.mem.eql(u8, &hash, &asset.source_sha256)) return error.SceneChangedRebuildBindings;
var model = try Model.init(setup.session, bytes);
errdefer model.release(setup.host);
for (model.geometry) |*g| try g.upload(setup.host);
return model;
}
/// Allocate in the sketch's Session arena; GPU handles share its host lifetime.
pub fn init(arena: std.mem.Allocator, bytes: []const u8) !Model {
const doc = try gltf.Document.parse(bytes);
defer doc.deinit();
try doc.loadBuffers(null);
var scene = try gltf.Scene.init(arena, doc);
errdefer scene.deinit();
const geometry = try arena.alloc(Geometry, scene.meshes.len);
for (scene.meshes, geometry) |mesh, *g| {
var count: usize = 0;
for (mesh.primitives) |primitive| count = try std.math.add(usize, count, primitive.indices.len);
const vertices = try arena.alloc(Vertex, count);
var offset: usize = 0;
// Opaque materials share one pipeline: carry color per vertex to batch a mesh.
for (mesh.primitives) |primitive| {
for (primitive.indices) |index| {
const source = primitive.vertices[index];
vertices[offset] = .{ .position = source.position, .normal = source.normal, .color = primitive.color };
offset += 1;
}
}
g.* = .{ .vertices = vertices };
}
return .{ .scene = scene, .geometry = geometry };
}
pub fn release(m: *Model, host: sk.Host) void {
for (m.geometry) |*g| g.release(host);
}
};
/// Imperative frame builder: add a whole scene, individual meshes, or geometry.
pub const View = struct {
frame: *sk.Frame,
image: sk.Image,
width: u32,
height: u32,
vp: math.Mat4,
draws: std.ArrayList(gpu.Draw) = .empty,
background: [4]f32 = .{ 0.54, 0.72, 0.83, 1 },
pub fn init(f: *sk.Frame, image: sk.Image, width: u32, height: u32, camera: Camera) View {
return .{ .frame = f, .image = image, .width = width, .height = height, .vp = camera.matrix(@as(f32, @floatFromInt(width)) / @as(f32, @floatFromInt(height))) };
}
pub fn scene(v: *View, model: *Model) !void {
for (model.scene.nodes) |node| if (node.visible) {
if (node.mesh) |index| try v.mesh(model, index, node.world);
};
}
pub fn mesh(v: *View, model: *Model, index: usize, transform: math.Mat4) !void {
if (index >= model.geometry.len) return error.InvalidMesh;
try v.triangles(&model.geometry[index], transform, .{ 1, 1, 1, 1 });
}
pub fn triangles(v: *View, geometry: *Geometry, transform: math.Mat4, color: [4]f32) !void {
if (geometry.buffer == .none) return error.GeometryNotUploaded;
try v.draws.append(v.frame.scratch, .{
.pipeline = 0,
.vertex_count = @intCast(geometry.vertices.len),
.vertex_storage = v.frame.keep(sk.abi.Buffer, &.{geometry.buffer}),
.vertex_uniforms = gpu.uniform(v.frame.scratch, types.Transform{
.model = @bitCast(transform),
.view_projection = @bitCast(v.vp),
.color = color,
}),
});
}
pub fn end(v: *View) void {
v.frame.gpu(.{
.label = "gltf scene",
.image = v.image,
.width = v.width,
.height = v.height,
.depth = true,
.clear = v.background,
.pipelines = &.{pipeline},
.draws = v.draws.items,
});
}
};
const pipeline: gpu.Pipeline = .{
.vertex = .{ .code = shaders.basic_vert, .uniform_buffers = 1, .storage_buffers = 1 },
.fragment = .{ .code = shaders.basic_frag },
.stride = 0,
.attributes = &.{},
.blend = .none,
.depth_test = .less,
.depth_write = true,
};
comptime {
// std430 scalar storage is ten contiguous floats, with no vec3 padding.
if (@sizeOf(Vertex) != 40 or @offsetOf(Vertex, "normal") != 12 or @offsetOf(Vertex, "color") != 24) @compileError("unexpected glTF vertex layout");
gpu.assertStd140(types.Transform);
}
|