-
-
Notifications
You must be signed in to change notification settings - Fork 219
Expand file tree
/
Copy pathentityModel.zig
More file actions
403 lines (342 loc) · 12.6 KB
/
entityModel.zig
File metadata and controls
403 lines (342 loc) · 12.6 KB
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
const std = @import("std");
const main = @import("main");
const chunk = main.chunk;
const game = main.game;
const graphics = main.graphics;
const c = graphics.c;
const ZonElement = main.ZonElement;
const renderer = main.renderer;
const settings = main.settings;
const utils = main.utils;
const vec = main.vec;
const Mat4f = vec.Mat4f;
const Vec3d = vec.Vec3d;
const Vec3f = vec.Vec3f;
const Vec4f = vec.Vec4f;
const NeverFailingAllocator = main.heap.NeverFailingAllocator;
const BinaryReader = main.utils.BinaryReader;
const gltf = @cImport({
@cInclude("cgltf.h");
});
pub const EntityModel = struct {
height: f32,
texturePath: []const u8,
modelId: ?[]const u8,
nodeReverse: std.StringHashMap(u16) = undefined,
nodes: NodeList = undefined,
nodeCount: u8,
vao: ?graphics.VertexArray = null,
indexCount: c_int,
defaultTexture: ?main.graphics.Texture,
coordinateSystem: CoordinateSystem,
pub const maxNodesCount = 20;
pub const NodeList = [maxNodesCount]Node;
pub const MatrixList = [maxNodesCount]Mat4f;
pub const Node = struct {
pos: Vec3f = @splat(0),
rot: Vec4f = Vec4f{0, 0, 0, 1},
scale: Vec3f = @splat(1),
originMat: Mat4f,
parent: ?u16 = null,
pub fn getHierarchyMatrix(self: Node, nodes: NodeList) Mat4f {
var mat = self.originMat.mul(Mat4f.translation(self.pos));
mat = mat.mul(Mat4f.rotationQuat(self.rot));
mat = mat.mul(Mat4f.scale(self.scale));
if (self.parent == null) {
return mat;
}
return nodes[self.parent.?].getHierarchyMatrix(nodes).mul(mat);
}
};
pub const CoordinateSystem = enum {
right_handed_z_up,
right_handed_y_up,
left_handed_z_up,
left_handed_y_up,
};
pub const Vertex = extern struct {
pos: [3]f32,
normal: [3]f32,
uv: [2]f32,
nodeID: c_uint,
pub const attributeDescriptions: []const c.VkVertexInputAttributeDescription = &.{
.{
.location = 0,
.format = c.VK_FORMAT_R32G32B32_SFLOAT,
.offset = @offsetOf(@This(), "pos"),
},
.{
.location = 1,
.format = c.VK_FORMAT_R32G32B32_SFLOAT,
.offset = @offsetOf(@This(), "normal"),
},
.{
.location = 2,
.format = c.VK_FORMAT_R32G32_SFLOAT,
.offset = @offsetOf(@This(), "uv"),
},
.{
.location = 3,
.format = c.VK_FORMAT_R32_UINT,
.offset = @offsetOf(@This(), "nodeID"),
},
};
};
pub fn init(assetFolder: []const u8, index: EntityModelIndex, zon: ZonElement) EntityModel {
var self: EntityModel = undefined;
if (zon.get(?[]const u8, "model", null)) |modelId| {
self.modelId = main.worldArena.dupe(u8, modelId);
} else {
self.modelId = null;
}
self.height = zon.getChild("height").as(f32, 1);
self.defaultTexture = null;
self.vao = null;
self.indexCount = 0;
self.coordinateSystem = zon.get(CoordinateSystem, "coordinateSystem", .right_handed_z_up);
self.nodeReverse = .init(main.worldArena.allocator);
self.nodes = std.mem.zeroes([20]Node);
self.nodeCount = 0;
if (zon.getChildOrNull("isPlayerModel")) |isPlayerModel| {
if (isPlayerModel.as(bool, false)) {
playerEntityModels.append(main.worldArena, index);
}
}
var isPlayerModel = false;
const tags = main.Tag.loadTagsFromZon(main.worldArena, zon.getChild("tags"));
for (tags) |tag| {
if (tag == .playerModel) {
isPlayerModel = true;
}
}
if (isPlayerModel) {
playerEntityModels.append(main.worldArena, index);
}
// get TexturePath
{
self.texturePath = &.{};
const fileEnding = ".png";
if (zon.get(?[]const u8, "defaultTexture", null)) |texture| {
var split = std.mem.splitScalar(u8, texture, ':');
const mod = split.first();
const textureName = split.next() orelse unreachable;
self.texturePath = std.fmt.allocPrint(main.worldArena.allocator, "{s}/{s}/entityModels/textures/{s}{s}", .{assetFolder, mod, textureName, fileEnding}) catch unreachable;
main.files.cubyzDir().dir.access(main.io, self.texturePath, .{}) catch {
main.worldArena.free(self.texturePath);
self.texturePath = std.fmt.allocPrint(main.worldArena.allocator, "assets/{s}/entityModels/textures/{s}{s}", .{mod, textureName, fileEnding}) catch unreachable;
};
}
}
return self;
}
pub fn deinit(self: *EntityModel) void {
if (self.defaultTexture) |defaultTexture| {
defaultTexture.deinit();
}
if (self.vao) |vao| {
vao.deinit();
}
}
fn cloneMetaData(self: *EntityModel) EntityModel {
return .{
.height = self.height,
.texturePath = main.worldArena.dupe(u8, self.texturePath),
.modelId = if (self.modelId) |modelId| main.worldArena.dupe(u8, modelId) else null,
.vao = null,
.indexCount = 0,
.defaultTexture = null,
.coordinateSystem = self.coordinateSystem,
.nodeReverse = self.nodeReverse.clone() catch unreachable,
.nodes = self.nodes,
.nodeCount = self.nodeCount,
};
}
fn loadModelAndTexture(self: *EntityModel) !void {
self.defaultTexture = main.graphics.Texture.initFromFile(self.texturePath);
if (self.modelId == null)
return error.NoModelSpecified;
const file = try main.assets.readAsset(main.stackAllocator, "entityModels/models", self.modelId.?, ".glb");
defer main.stackAllocator.free(file);
var options: gltf.cgltf_options = .{};
var data: *gltf.cgltf_data = undefined;
var result = gltf.cgltf_parse(&options, @ptrCast(file.ptr), @intCast(file.len), @ptrCast(&data));
if (result != gltf.cgltf_result_success) {
std.log.err("GLTF Parse error: {s}", .{@errorName(getGltfError(result))});
return getGltfError(result);
}
defer gltf.cgltf_free(@ptrCast(data));
result = gltf.cgltf_load_buffers(&options, @ptrCast(data), "data:application/octet-stream");
if (result != gltf.cgltf_result_success) {
std.log.err("GLTF Load buffers error: {s}", .{@errorName(getGltfError(result))});
return getGltfError(result);
}
result = gltf.cgltf_validate(@ptrCast(data));
if (result != gltf.cgltf_result_success) {
std.log.err("GLTF Validation error: {s}", .{@errorName(getGltfError(result))});
return getGltfError(result);
}
var vertices = main.List(Vertex).init(main.stackAllocator);
defer vertices.deinit();
var indices = main.List(u32).init(main.stackAllocator);
defer indices.deinit();
var baseVertex: u32 = 0;
var nodeIdx: u8 = 0;
for (data.nodes, 0..data.nodes_count) |node, _| {
if (node.children_count == 0) continue;
const nameC = std.mem.span(node.name);
const name = main.globalArena.alloc(u8, nameC.len);
@memcpy(name, nameC);
self.nodeReverse.put(name, @intCast(nodeIdx)) catch unreachable;
var originMat = Mat4f.translation(convertCoordinateSystemVec(node.translation, self.coordinateSystem));
originMat = originMat.mul(Mat4f.rotationQuat(convertCoordinateSystemQuat(node.rotation, self.coordinateSystem)));
originMat = originMat.mul(Mat4f.scale(convertCoordinateSystemScale(node.scale, self.coordinateSystem)));
self.nodes[nodeIdx] = Node{
.originMat = originMat,
};
nodeIdx += 1;
}
for (data.nodes, 0..data.nodes_count) |node, _| {
if (node.children_count == 0 or node.parent == null) continue;
const curNode = self.nodeReverse.get(std.mem.span(node.name)).?;
self.nodes[curNode].parent = self.nodeReverse.get(std.mem.span(node.parent.*.name)).?;
}
for (data.nodes[0..data.nodes_count]) |node| {
if (node.mesh == null) continue;
var finalMat = Mat4f.translation(convertCoordinateSystemVec(node.translation, self.coordinateSystem));
finalMat = finalMat.mul(Mat4f.rotationQuat(convertCoordinateSystemQuat(node.rotation, self.coordinateSystem)));
finalMat = finalMat.mul(Mat4f.scale(convertCoordinateSystemScale(node.scale, self.coordinateSystem)));
const parentNodeID = if (node.parent) |p| self.nodeReverse.get(std.mem.span(p.*.name)).? else 0;
const primitives = node.mesh.*.primitives;
for (primitives[0..node.mesh.*.primitives_count]) |primitive| {
if (primitive.type != gltf.cgltf_primitive_type_triangles) {
std.log.warn("Unsupported primitive type: {d}", .{primitive.type});
continue;
}
const indicesAccessor = primitive.indices.*;
const vertCount = primitive.attributes[0].data.*.count;
var indicesSlice = indices.addMany(indicesAccessor.count);
baseVertex = @intCast(vertices.items.len);
const vertSlice: []Vertex = vertices.addMany(vertCount);
for (0..indicesAccessor.count) |i| {
const idx = indicesAccessor.read_index(i);
indicesSlice[i] = @as(u32, @intCast(idx)) + baseVertex;
}
var positionAttr: gltf.cgltf_accessor = undefined;
var normalAttr: gltf.cgltf_accessor = undefined;
var uvAttr: gltf.cgltf_accessor = undefined;
for (primitive.attributes, 0..primitive.attributes_count) |attrib, _| {
const attribAccessor = attrib.data.*;
switch (attrib.type) {
gltf.cgltf_attribute_type_position => positionAttr = attribAccessor,
gltf.cgltf_attribute_type_normal => normalAttr = attribAccessor,
gltf.cgltf_attribute_type_texcoord => uvAttr = attribAccessor,
else => continue,
}
}
for (0..positionAttr.count) |v| {
var p: [3]f32 = undefined;
_ = positionAttr.read_float(v, @ptrCast(&p), 3);
const p2 = convertCoordinateSystemVec(p, self.coordinateSystem);
const pos: vec.Vec4f = finalMat.mulVec(.{p2[0], p2[1], p2[2], 1});
vertSlice[v].pos = vec.xyz(pos);
var normal: [3]f32 = undefined;
_ = normalAttr.read_float(v, @ptrCast(&normal), 3);
vertSlice[v].normal = convertCoordinateSystemVec(normal, self.coordinateSystem);
var uv: [2]f32 = undefined;
_ = uvAttr.read_float(v, @ptrCast(&uv), 2);
vertSlice[v].uv = .{uv[0], 1 - uv[1]};
vertSlice[v].nodeID = @intCast(parentNodeID);
}
}
}
self.vao = .init(Vertex, vertices.items, indices.items);
self.indexCount = @intCast(indices.items.len);
self.nodeCount = nodeIdx;
}
fn convertCoordinateSystemVec(v: Vec3f, sys: CoordinateSystem) Vec3f {
return switch (sys) {
.right_handed_z_up => Vec3f{v[0], v[1], v[2]},
.right_handed_y_up => Vec3f{v[0], v[2], -v[1]},
.left_handed_z_up => Vec3f{-v[0], v[1], v[2]},
.left_handed_y_up => Vec3f{-v[0], v[2], v[1]},
};
}
fn convertCoordinateSystemQuat(q: Vec4f, sys: CoordinateSystem) Vec4f {
return switch (sys) {
.right_handed_z_up => Vec4f{q[0], q[1], q[2], q[3]},
.right_handed_y_up => Vec4f{q[0], q[2], -q[1], q[3]},
.left_handed_z_up => Vec4f{-q[0], q[1], q[2], q[3]},
.left_handed_y_up => Vec4f{-q[0], q[2], q[1], q[3]},
};
}
fn convertCoordinateSystemScale(s: Vec3f, sys: CoordinateSystem) Vec3f {
return switch (sys) {
.right_handed_z_up, .left_handed_z_up => Vec3f{s[0], s[1], s[2]},
.right_handed_y_up, .left_handed_y_up => Vec3f{s[0], s[2], s[1]},
};
}
fn getGltfError(result: gltf.cgltf_result) anyerror {
return switch (result) {
gltf.cgltf_result_data_too_short => error.DataTooShort,
gltf.cgltf_result_unknown_format => error.UnknownFormat,
gltf.cgltf_result_invalid_json => error.InvalidJson,
gltf.cgltf_result_invalid_gltf => error.InvalidGltf,
gltf.cgltf_result_invalid_options => error.InvalidOptions,
gltf.cgltf_result_file_not_found => error.FileNotFound,
gltf.cgltf_result_io_error => error.IoError,
gltf.cgltf_result_out_of_memory => error.OutOfMemory,
gltf.cgltf_result_legacy_gltf => error.LegacyGltf,
else => unreachable,
};
}
pub fn bind(self: *EntityModel) void {
self.vao.?.bind();
self.defaultTexture.?.bindTo(0);
}
};
pub const EntityModelIndex = struct {
index: u32,
pub fn get(self: EntityModelIndex) *EntityModel {
std.debug.assert(entityModels.items.len > self.index);
return &entityModels.items[self.index];
}
};
pub var playerEntityModels: main.ListUnmanaged(EntityModelIndex) = .{};
pub var reverseIndices: std.StringHashMapUnmanaged(EntityModelIndex) = .{};
pub var entityModels: main.ListUnmanaged(EntityModel) = .{};
pub fn register(assetFolder: []const u8, entityModelId: []const u8, zon: ZonElement) EntityModelIndex {
const index = EntityModelIndex{.index = @intCast(entityModels.items.len)};
entityModels.append(main.worldArena, EntityModel.init(assetFolder, index, zon));
reverseIndices.put(main.worldArena.allocator, entityModelId, index) catch unreachable;
return index;
}
pub fn reset() void {
for (entityModels.items) |*model| {
model.deinit();
}
entityModels = .{};
reverseIndices = .{};
playerEntityModels = .{};
}
pub fn getById(id: []const u8) ?EntityModelIndex {
if (reverseIndices.get(id)) |result| {
return result;
}
return null;
}
pub fn default() EntityModelIndex {
if (reverseIndices.get("cubyz:missing")) |result| {
return result;
}
@panic("Not even cubyz:missing is available to fallback to!");
}
pub fn loadModelsAndTexture() void {
for (entityModels.items) |*value| {
value.loadModelAndTexture() catch {
value.deinit();
value.* = default().get().cloneMetaData();
value.loadModelAndTexture() catch unreachable;
continue;
};
}
}