-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwavefront-obj.zig
More file actions
489 lines (423 loc) · 15.7 KB
/
wavefront-obj.zig
File metadata and controls
489 lines (423 loc) · 15.7 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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
const std = @import("std");
const zlm = @import("zlm");
const log = std.log.scoped(.wavefront_obj);
const vec2 = zlm.vec2;
const vec3 = zlm.vec3;
const vec4 = zlm.vec4;
const Vec2 = zlm.Vec2;
const Vec3 = zlm.Vec3;
const Vec4 = zlm.Vec4;
test "wavefront-obj" {
std.testing.refAllDecls(@This());
}
// this file parses OBJ wavefront according to
// http://paulbourke.net/dataformats/obj/
// with a lot of restrictions
pub const Vertex = struct {
position: usize,
normal: ?usize,
textureCoordinate: ?usize,
};
pub const Face = struct {
vertices: []Vertex,
};
pub const Line = struct {
vertices: [2]Vertex,
};
pub const Object = struct {
name: []const u8,
material: ?[]const u8,
start: usize,
count: usize,
};
pub const Model = struct {
const Self = @This();
allocator: std.mem.Allocator,
arena: std.heap.ArenaAllocator,
positions: []Vec4,
normals: []Vec3,
textureCoordinates: []Vec3,
faces: []Face,
lines: []Line,
objects: []Object,
pub fn deinit(self: *Self) void {
self.allocator.free(self.positions);
self.allocator.free(self.normals);
self.allocator.free(self.textureCoordinates);
self.allocator.free(self.faces);
self.allocator.free(self.lines);
self.allocator.free(self.objects);
self.arena.deinit();
self.* = undefined;
}
};
fn parseVertexSpec(spec: []const u8) !Vertex {
var vertex = Vertex{
.position = 0,
.normal = null,
.textureCoordinate = null,
};
var iter = std.mem.split(u8, spec, "/");
var state: u32 = 0;
while (iter.next()) |part| {
switch (state) {
0 => vertex.position = (try std.fmt.parseInt(usize, part, 10)) - 1,
1 => vertex.textureCoordinate = if (!std.mem.eql(u8, part, "")) (try std.fmt.parseInt(usize, part, 10)) - 1 else null,
2 => vertex.normal = if (!std.mem.eql(u8, part, "")) (try std.fmt.parseInt(usize, part, 10)) - 1 else null,
else => return error.InvalidFormat,
}
state += 1;
}
return vertex;
}
pub fn loadFile(allocator: std.mem.Allocator, path: []const u8) !Model {
var file = try std.fs.cwd().openFile(path, .{ .mode = .read_only });
defer file.close();
return load(allocator, file.reader());
}
pub fn load(
allocator: std.mem.Allocator,
stream: anytype,
) !Model {
var arena = std.heap.ArenaAllocator.init(allocator);
errdefer arena.deinit();
var positions = std.ArrayList(Vec4).init(allocator);
defer positions.deinit();
var normals = std.ArrayList(Vec3).init(allocator);
defer normals.deinit();
var textureCoordinates = std.ArrayList(Vec3).init(allocator);
defer textureCoordinates.deinit();
var faces = std.ArrayList(Face).init(allocator);
defer faces.deinit();
var lines = std.ArrayList(Line).init(allocator);
defer lines.deinit();
var objects = std.ArrayList(Object).init(allocator);
defer objects.deinit();
try positions.ensureTotalCapacity(10_000);
try normals.ensureTotalCapacity(10_000);
try textureCoordinates.ensureTotalCapacity(10_000);
try faces.ensureTotalCapacity(10_000);
try lines.ensureTotalCapacity(10_000);
try objects.ensureTotalCapacity(100);
// note:
// this may look like a dangling pointer as ArrayList changes it's pointers when resized.
// BUT: the pointer will be changed with the added element, so it will not dangle
var current_object: ?*Object = null;
var line_reader = lineIterator(allocator, stream);
defer line_reader.deinit();
while (try line_reader.next()) |line| {
errdefer {
log.err("error parsing line: '{s}'", .{line});
}
// parse vertex
if (std.mem.startsWith(u8, line, "v ")) {
var iter = std.mem.tokenize(u8, line[2..], " ");
var state: u32 = 0;
var vertex = vec4(0, 0, 0, 1);
while (iter.next()) |part| {
switch (state) {
0 => vertex.x = try std.fmt.parseFloat(f32, part),
1 => vertex.y = try std.fmt.parseFloat(f32, part),
2 => vertex.z = try std.fmt.parseFloat(f32, part),
3 => vertex.w = try std.fmt.parseFloat(f32, part),
else => return error.InvalidFormat,
}
state += 1;
}
if (state < 3) // v x y z w, with x,y,z are required, w is optional
return error.InvalidFormat;
try positions.append(vertex);
}
// parse uv coords
else if (std.mem.startsWith(u8, line, "vt ")) {
var iter = std.mem.tokenize(u8, line[3..], " ");
var state: u32 = 0;
var texcoord = vec3(0, 0, 0);
while (iter.next()) |part| {
switch (state) {
0 => texcoord.x = try std.fmt.parseFloat(f32, part),
1 => texcoord.y = try std.fmt.parseFloat(f32, part),
2 => texcoord.z = try std.fmt.parseFloat(f32, part),
else => return error.InvalidFormat,
}
state += 1;
}
if (state < 1) // vt u v w, with u is required, v and w are optional
return error.InvalidFormat;
try textureCoordinates.append(texcoord);
}
// parse normals
else if (std.mem.startsWith(u8, line, "vn ")) {
var iter = std.mem.tokenize(u8, line[3..], " ");
var state: u32 = 0;
var normal = vec3(0, 0, 0);
while (iter.next()) |part| {
switch (state) {
0 => normal.x = try std.fmt.parseFloat(f32, part),
1 => normal.y = try std.fmt.parseFloat(f32, part),
2 => normal.z = try std.fmt.parseFloat(f32, part),
else => return error.InvalidFormat,
}
state += 1;
}
if (state < 3) // vn i j k, with i,j,k are required, none are optional
return error.InvalidFormat;
try normals.append(normal);
}
// parse faces
else if (std.mem.startsWith(u8, line, "f ")) {
var iter = std.mem.tokenize(u8, line[2..], " ");
var state: u32 = 0;
var vertices = std.ArrayList(Vertex).init(arena.allocator());
defer vertices.deinit();
while (iter.next()) |part| {
const vert = try parseVertexSpec(part);
try vertices.append(vert);
state += 1;
}
if (vertices.items.len < 3) // less than 3 faces is an error (no line or point support)
return error.InvalidFormat;
try faces.append(Face{
.vertices = vertices.toOwnedSlice(),
});
}
// parse lines
else if (std.mem.startsWith(u8, line, "l ")) {
var iter = std.mem.tokenize(u8, line[2..], " ");
var state: u32 = 0;
var vertices = std.ArrayList(Vertex).init(arena.allocator());
defer vertices.deinit();
while (iter.next()) |part| {
const vert = try parseVertexSpec(part);
try vertices.append(vert);
state += 1;
}
if (vertices.items.len != 2) // Each line is always 2 vertices.
return error.InvalidFormat;
try lines.append(Line{
.vertices = vertices.items[0..2].*,
});
}
// parse objects
else if (std.mem.startsWith(u8, line, "o ")) {
if (current_object) |obj| {
// terminate object
obj.count = faces.items.len - obj.start;
}
var obj = try objects.addOne();
obj.start = faces.items.len;
obj.count = 0;
obj.name = arena.allocator().dupe(u8, line[2..]) catch |err| {
_ = objects.pop(); // remove last element, then error
return err;
};
current_object = obj;
}
// parse material libraries
else if (std.mem.startsWith(u8, line, "mtllib ")) {
// ignore material libraries for now...
// TODO: Implement material libraries
}
// parse material application
else if (std.mem.startsWith(u8, line, "usemtl ")) {
if (current_object) |*obj| {
if (obj.*.material != null) {
// duplicate object when two materials per object
const current_name = obj.*.name;
// terminate object
obj.*.count = faces.items.len - obj.*.start;
obj.* = try objects.addOne();
obj.*.start = faces.items.len;
obj.*.count = 0;
obj.*.name = arena.allocator().dupe(u8, current_name) catch |err| {
_ = objects.pop(); // remove last element, then error
return err;
};
}
obj.*.material = try arena.allocator().dupe(u8, line[7..]);
} else {
current_object = try objects.addOne();
current_object.?.start = faces.items.len;
current_object.?.count = 0;
current_object.?.name = arena.allocator().dupe(u8, "unnamed") catch |err| {
_ = objects.pop(); // remove last element, then error
return err;
};
current_object.?.material = try arena.allocator().dupe(u8, line[7..]);
}
}
// parse smoothing groups
else if (std.mem.startsWith(u8, line, "s ")) {
// and just ignore them :(
} else {
log.warn("unrecognized line: {s}", .{line});
}
}
// terminate object if any
if (current_object) |obj| {
obj.count = faces.items.len - obj.start;
}
return Model{
.allocator = allocator,
.arena = arena,
.positions = positions.toOwnedSlice(),
.normals = normals.toOwnedSlice(),
.textureCoordinates = textureCoordinates.toOwnedSlice(),
.faces = faces.toOwnedSlice(),
.lines = lines.toOwnedSlice(),
.objects = objects.toOwnedSlice(),
};
}
pub const Color = struct {
r: f32,
g: f32,
b: f32,
};
pub const Material = struct {
ambient_texture: ?[]const u8 = null,
diffuse_texture: ?[]const u8 = null,
specular_texture: ?[]const u8 = null,
ambient_color: ?Color = null,
diffuse_color: ?Color = null,
specular_color: ?Color = null,
};
pub const MaterialLibrary = struct {
const Self = @This();
arena: std.heap.ArenaAllocator,
materials: std.StringHashMap(Material),
pub fn deinit(self: *Self) void {
self.materials.deinit();
self.arena.deinit();
self.* = undefined;
}
};
pub fn loadMaterials(allocator: *std.mem.Allocator, stream: anytype) !MaterialLibrary {
var materials = std.StringHashMap(Material).init(allocator);
errdefer materials.deinit();
var arena = std.heap.ArenaAllocator.init(allocator);
errdefer arena.deinit();
var line_reader = lineIterator(allocator, stream);
defer line_reader.deinit();
var current_mtl: ?*Material = null;
while (try line_reader.next()) |line| {
errdefer {
log.err("error parsing line: '{s}'\n", .{
line,
});
}
if (std.mem.startsWith(u8, line, "newmtl ")) {
const mtl_name = try arena.allocator.dupe(u8, line[7..]);
const gop = try materials.getOrPut(mtl_name);
if (gop.found_existing) {
log.err("duplicate material name: '{s}'", .{mtl_name});
return error.DuplicateMaterial;
}
gop.entry.value = Material{};
current_mtl = &gop.entry.value;
} else if (std.mem.startsWith(u8, line, "Ka ")) {
if (current_mtl) |mtl| {
mtl.ambient_color = try parseColor(line[3..]);
} else {
log.err("missing newmtl!", .{});
return error.InvalidFormat;
}
} else if (std.mem.startsWith(u8, line, "Kd ")) {
if (current_mtl) |mtl| {
mtl.diffuse_color = try parseColor(line[3..]);
} else {
log.err("missing newmtl!", .{});
return error.InvalidFormat;
}
} else if (std.mem.startsWith(u8, line, "Ks ")) {
if (current_mtl) |mtl| {
mtl.specular_color = try parseColor(line[3..]);
} else {
log.err("missing newmtl!", .{});
return error.InvalidFormat;
}
} else if (std.mem.startsWith(u8, line, "map_Ka")) {
if (current_mtl) |mtl| {
mtl.ambient_texture = try arena.allocator.dupe(u8, std.mem.trim(u8, line[7..], " \t\r\n"));
} else {
log.err("missing newmtl!", .{});
return error.InvalidFormat;
}
} else if (std.mem.startsWith(u8, line, "map_Kd")) {
if (current_mtl) |mtl| {
mtl.diffuse_texture = try arena.allocator.dupe(u8, std.mem.trim(u8, line[7..], " \t\r\n"));
} else {
log.err("missing newmtl!", .{});
return error.InvalidFormat;
}
} else if (std.mem.startsWith(u8, line, "map_Ks")) {
if (current_mtl) |mtl| {
mtl.specular_texture = try arena.allocator.dupe(u8, std.mem.trim(u8, line[7..], " \t\r\n"));
} else {
log.err("missing newmtl!", .{});
return error.InvalidFormat;
}
} else {
log.warn("unrecognized line: '{s}'", .{line});
}
}
return MaterialLibrary{
.arena = arena,
.materials = materials,
};
}
fn parseColor(line: []const u8) !Color {
var iterator = std.mem.tokenize(line, " ");
var result = Color{
.r = undefined,
.g = undefined,
.b = undefined,
};
var index: usize = 0;
while (iterator.next()) |tok| : (index += 1) {
switch (index) {
0 => result.r = try std.fmt.parseFloat(f32, tok),
1 => result.g = try std.fmt.parseFloat(f32, tok),
2 => result.b = try std.fmt.parseFloat(f32, tok),
else => return error.InvalidFormat,
}
}
if (index < 3)
return error.InvalidFormat;
return result;
}
fn LineIterator(comptime Reader: type) type {
return struct {
const Self = @This();
reader: Reader,
buffer: std.ArrayList(u8),
pub fn deinit(self: *Self) void {
self.buffer.deinit();
self.* = undefined;
}
pub fn next(self: *Self) !?[]const u8 {
while (true) {
self.reader.readUntilDelimiterArrayList(&self.buffer, '\n', 4096) catch |err| switch (err) {
error.EndOfStream => return null,
else => return err,
};
var line: []const u8 = self.buffer.items;
// remove comments
if (std.mem.indexOf(u8, line, "#")) |idx| {
line = line[0..idx];
}
// strip trailing/leading whites
line = std.mem.trim(u8, line, " \r\n\t");
if (line.len == 0) {
continue;
}
return line;
}
}
};
}
fn lineIterator(allocator: std.mem.Allocator, reader: anytype) LineIterator(@TypeOf(reader)) {
return LineIterator(@TypeOf(reader)){
.reader = reader,
.buffer = std.ArrayList(u8).init(allocator),
};
}