Repository navigation
Expand file tree
/
Copy pathSceneParser.cppm
More file actions
634 lines (560 loc) · 23 KB
/
Copy pathSceneParser.cppm
File metadata and controls
634 lines (560 loc) · 23 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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
module;
#include <charconv>
#include <cstdint>
#include <filesystem>
#include <fstream>
#include <locale>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
export module Kairo.Foundation.RayTracer.SceneParser;
import Kairo.Foundation.Math.Vector;
import Kairo.Foundation.Geometry.Triangle;
import Kairo.Foundation.RayTracer.Types;
import Kairo.Foundation.RayTracer.Color;
import Kairo.Foundation.RayTracer.Camera;
import Kairo.Foundation.RayTracer.Material;
import Kairo.Foundation.RayTracer.Light;
import Kairo.Foundation.RayTracer.Scene;
import Kairo.Foundation.RayTracer.Texture;
import Kairo.Foundation.RayTracer.Environment;
import Kairo.Foundation.RayTracer.Mesh;
import Kairo.Foundation.RayTracer.OBJLoader;
export namespace kairo::foundation::raytracer
{
using namespace kairo::foundation::math;
//=========================================================
// Scene Parser
//
// The .kairo format is deliberately line-oriented for V1. Every command is
// visible in plain text, parser errors can point to one line/column, and the
// renderer avoids a JSON dependency while the scene vocabulary is still tiny.
//=========================================================
class SceneParseException final : public std::runtime_error
{
public:
explicit SceneParseException(
SceneParseError error)
:
std::runtime_error(
"scene parse error at line " +
std::to_string(error.Line) +
", column " +
std::to_string(error.Column) +
": " +
error.Message),
m_Error(std::move(error))
{
}
[[nodiscard]]
const SceneParseError& Error() const noexcept
{
return m_Error;
}
private:
SceneParseError m_Error;
};
namespace parser_detail
{
struct Token final
{
std::string Text;
std::uint32_t Column = 1;
};
[[nodiscard]]
inline std::vector<Token> Tokenize(
const std::string& line)
{
// Tokenization is whitespace-based. `#` starts a comment anywhere on
// the line, which makes scene files double as readable render notes.
std::vector<Token> tokens;
std::size_t i = 0;
while (i < line.size())
{
if (line[i] == '#')
{
break;
}
if (line[i] == ' ' || line[i] == '\t' || line[i] == '\r')
{
++i;
continue;
}
const std::size_t begin = i;
while (i < line.size() &&
line[i] != ' ' &&
line[i] != '\t' &&
line[i] != '\r' &&
line[i] != '#')
{
++i;
}
tokens.push_back(
Token
{
line.substr(begin, i - begin),
static_cast<std::uint32_t>(begin + 1)
});
}
return tokens;
}
[[noreturn]]
inline void Fail(
std::uint32_t line,
std::uint32_t column,
std::string message)
{
throw SceneParseException(
SceneParseError
{
line,
column,
std::move(message)
});
}
inline void RequireCount(
const std::vector<Token>& tokens,
std::uint32_t line,
std::size_t expected,
std::string_view usage)
{
// Command arity is strict on purpose. A renderer should fail loudly
// when a scene says something ambiguous instead of guessing.
if (tokens.size() != expected)
{
const std::uint32_t column =
tokens.empty() ? 1u : tokens.back().Column;
Fail(
line,
column,
"expected " + std::to_string(expected) +
" tokens for `" + std::string(usage) +
"`, got " + std::to_string(tokens.size()) + ".");
}
}
[[nodiscard]]
inline float ParseFloat(
const Token& token,
std::uint32_t line)
{
// Floating-point std::from_chars in Homebrew libc++ is gated by
// the macOS deployment target. A classic-locale stream preserves
// deterministic decimal parsing while remaining available on the
// supported macOS versions. Requiring EOF rejects partial tokens.
std::istringstream stream(token.Text);
stream.imbue(std::locale::classic());
float value = 0.0f;
stream >> value;
if (!stream || stream.peek() != std::char_traits<char>::eof())
{
Fail(line, token.Column, "invalid float `" + token.Text + "`.");
}
return value;
}
[[nodiscard]]
inline std::uint32_t ParseUInt(
const Token& token,
std::uint32_t line)
{
std::uint32_t value = 0;
const char* begin = token.Text.data();
const char* end = begin + token.Text.size();
const auto [ptr, ec] = std::from_chars(begin, end, value);
if (ec != std::errc{} || ptr != end)
{
Fail(line, token.Column, "invalid unsigned integer `" + token.Text + "`.");
}
return value;
}
[[nodiscard]]
inline Color3f ParseColor(
const std::vector<Token>& tokens,
std::uint32_t line,
std::size_t offset)
{
return
{
ParseFloat(tokens.at(offset), line),
ParseFloat(tokens.at(offset + 1), line),
ParseFloat(tokens.at(offset + 2), line)
};
}
[[nodiscard]]
inline Vec3f ParseVec3(
const std::vector<Token>& tokens,
std::uint32_t line,
std::size_t offset)
{
return
{
ParseFloat(tokens.at(offset), line),
ParseFloat(tokens.at(offset + 1), line),
ParseFloat(tokens.at(offset + 2), line)
};
}
[[nodiscard]]
inline RenderMode ParseRenderMode(
const Token& token,
std::uint32_t line)
{
if (token.Text == "normal") return RenderMode::Normal;
if (token.Text == "depth") return RenderMode::Depth;
if (token.Text == "whitted") return RenderMode::Whitted;
if (token.Text == "shadow_mask") return RenderMode::ShadowMask;
if (token.Text == "bvh_heatmap") return RenderMode::BVHHeatmap;
if (token.Text == "albedo") return RenderMode::Albedo;
if (token.Text == "primitive_id") return RenderMode::PrimitiveID;
if (token.Text == "uv") return RenderMode::UV;
if (token.Text == "barycentric") return RenderMode::Barycentric;
if (token.Text == "accel_diff") return RenderMode::AccelerationDifference;
if (token.Text == "pbr") return RenderMode::PBR;
if (token.Text == "path") return RenderMode::Path;
Fail(line, token.Column, "unknown integrator `" + token.Text + "`.");
}
[[nodiscard]]
inline MaterialType ParseMaterialType(
const Token& token,
std::uint32_t line)
{
if (token.Text == "lambert") return MaterialType::Lambert;
if (token.Text == "mirror") return MaterialType::Mirror;
if (token.Text == "glass") return MaterialType::Glass;
if (token.Text == "pbr") return MaterialType::PBR;
if (token.Text == "emissive") return MaterialType::Emissive;
Fail(line, token.Column, "unknown material type `" + token.Text + "`.");
}
[[nodiscard]]
inline TextureFilter ParseTextureFilter(
const Token& token,
std::uint32_t line)
{
if (token.Text == "nearest") return TextureFilter::Nearest;
if (token.Text == "bilinear" || token.Text == "linear") return TextureFilter::Bilinear;
Fail(line, token.Column, "unknown texture filter `" + token.Text + "`.");
}
}
[[nodiscard]]
inline Scene ParseSceneText(
const std::string& text,
const std::filesystem::path& baseDirectory = std::filesystem::current_path())
{
// First pass and construction happen together because V1 references only
// earlier material names. This keeps the grammar simple: define material
// before using it.
Scene scene;
std::unordered_map<std::string, std::uint32_t> materialIndices;
std::unordered_map<std::string, std::uint32_t> textureIndices;
bool cameraFound = false;
Vec3f cameraPosition = Vec3f{ 0.0f, 1.0f, 6.0f };
Vec3f cameraTarget = Vec3f{ 0.0f, 1.0f, 0.0f };
Vec3f cameraUp = Vec3f::Up();
float cameraFOV = 45.0f;
std::istringstream stream(text);
std::string lineText;
std::uint32_t line = 0;
while (std::getline(stream, lineText))
{
++line;
const std::vector<parser_detail::Token> tokens =
parser_detail::Tokenize(lineText);
if (tokens.empty())
{
continue;
}
const std::string& command =
tokens[0].Text;
if (command == "resolution")
{
parser_detail::RequireCount(tokens, line, 3, "resolution width height");
scene.Settings.Width = parser_detail::ParseUInt(tokens[1], line);
scene.Settings.Height = parser_detail::ParseUInt(tokens[2], line);
if (scene.Settings.Width == 0 || scene.Settings.Height == 0)
{
parser_detail::Fail(line, tokens[1].Column, "resolution dimensions must be non-zero.");
}
}
else if (command == "samples")
{
parser_detail::RequireCount(tokens, line, 2, "samples count");
scene.Settings.SamplesPerPixel = parser_detail::ParseUInt(tokens[1], line);
if (scene.Settings.SamplesPerPixel == 0)
{
parser_detail::Fail(line, tokens[1].Column, "sample count must be non-zero.");
}
}
else if (command == "background")
{
parser_detail::RequireCount(tokens, line, 4, "background r g b");
scene.Settings.Background = parser_detail::ParseColor(tokens, line, 1);
}
else if (command == "environment")
{
if (tokens.size() < 2)
{
parser_detail::Fail(line, tokens[0].Column, "usage: environment constant r g b intensity or environment texture name intensity");
}
if (tokens[1].Text == "constant")
{
parser_detail::RequireCount(tokens, line, 6, "environment constant r g b intensity");
scene.Environment.Enabled = true;
scene.Environment.Color = parser_detail::ParseColor(tokens, line, 2);
scene.Environment.Intensity = parser_detail::ParseFloat(tokens[5], line);
}
else if (tokens[1].Text == "texture")
{
parser_detail::RequireCount(tokens, line, 4, "environment texture textureName intensity");
const auto textureIt =
textureIndices.find(tokens[2].Text);
if (textureIt == textureIndices.end())
{
parser_detail::Fail(line, tokens[2].Column, "unknown texture `" + tokens[2].Text + "`.");
}
scene.Environment.Enabled = true;
scene.Environment.TextureIndex = textureIt->second;
scene.Environment.Intensity = parser_detail::ParseFloat(tokens[3], line);
}
else
{
parser_detail::Fail(line, tokens[1].Column, "unknown environment type `" + tokens[1].Text + "`.");
}
}
else if (command == "integrator")
{
parser_detail::RequireCount(tokens, line, 2, "integrator mode");
scene.Settings.Mode = parser_detail::ParseRenderMode(tokens[1], line);
}
else if (command == "camera")
{
parser_detail::RequireCount(tokens, line, 11, "camera px py pz tx ty tz upx upy upz fov");
cameraPosition = parser_detail::ParseVec3(tokens, line, 1);
cameraTarget = parser_detail::ParseVec3(tokens, line, 4);
cameraUp = parser_detail::ParseVec3(tokens, line, 7);
cameraFOV = parser_detail::ParseFloat(tokens[10], line);
cameraFound = true;
}
else if (command == "material")
{
// Emissive materials may provide explicit emission. If omitted,
// albedo becomes the visible emission color so small demo scenes
// can be concise.
if (tokens.size() != 6 && tokens.size() != 7 && tokens.size() != 8 && tokens.size() != 9)
{
parser_detail::Fail(line, tokens[0].Column, "usage: material name type r g b [ior | roughness metallic | emitR emitG emitB].");
}
Material material;
material.Name = tokens[1].Text;
material.Type = parser_detail::ParseMaterialType(tokens[2], line);
material.Albedo = parser_detail::ParseColor(tokens, line, 3);
if (material.Type == MaterialType::Glass && tokens.size() == 7)
{
material.IOR = parser_detail::ParseFloat(tokens[6], line);
}
if (material.Type == MaterialType::PBR && tokens.size() == 8)
{
material.Roughness = parser_detail::ParseFloat(tokens[6], line);
material.Metallic = parser_detail::ParseFloat(tokens[7], line);
}
material.Emission = tokens.size() == 9
? parser_detail::ParseColor(tokens, line, 6)
: Color3f::Black();
if (material.Type == MaterialType::Emissive && !IsNonBlack(material.Emission))
{
material.Emission = material.Albedo;
}
if (materialIndices.contains(material.Name))
{
parser_detail::Fail(line, tokens[1].Column, "duplicate material `" + material.Name + "`.");
}
const std::string materialName =
material.Name;
materialIndices[materialName] =
scene.AddMaterial(std::move(material));
}
else if (command == "texture")
{
if (tokens.size() != 3 && tokens.size() != 4)
{
parser_detail::Fail(line, tokens[0].Column, "usage: texture name path [nearest|bilinear].");
}
if (textureIndices.contains(tokens[1].Text))
{
parser_detail::Fail(line, tokens[1].Column, "duplicate texture `" + tokens[1].Text + "`.");
}
std::filesystem::path texturePath =
tokens[2].Text;
if (texturePath.is_relative())
{
texturePath = baseDirectory / texturePath;
}
const TextureFilter filter =
tokens.size() == 4
? parser_detail::ParseTextureFilter(tokens[3], line)
: TextureFilter::Bilinear;
textureIndices[tokens[1].Text] =
scene.AddTexture(
LoadPPMTexture(
texturePath,
tokens[1].Text,
filter));
}
else if (command == "material_texture")
{
parser_detail::RequireCount(tokens, line, 3, "material_texture materialName textureName");
const auto materialIt =
materialIndices.find(tokens[1].Text);
if (materialIt == materialIndices.end())
{
parser_detail::Fail(line, tokens[1].Column, "unknown material `" + tokens[1].Text + "`.");
}
const auto textureIt =
textureIndices.find(tokens[2].Text);
if (textureIt == textureIndices.end())
{
parser_detail::Fail(line, tokens[2].Column, "unknown texture `" + tokens[2].Text + "`.");
}
scene.Materials.at(materialIt->second).AlbedoTextureIndex =
textureIt->second;
}
else if (command == "light")
{
if (tokens.size() < 2)
{
parser_detail::Fail(line, tokens[0].Column, "usage: light point ... or light area ...");
}
if (tokens[1].Text == "point")
{
parser_detail::RequireCount(tokens, line, 9, "light point x y z r g b intensity");
scene.Lights.push_back(
PointLight
{
parser_detail::ParseVec3(tokens, line, 2),
parser_detail::ParseColor(tokens, line, 5),
parser_detail::ParseFloat(tokens[8], line)
});
}
else if (tokens[1].Text == "area")
{
parser_detail::RequireCount(tokens, line, 16, "light area px py pz ux uy uz vx vy vz r g b intensity samples");
scene.AreaLights.push_back(
AreaLight
{
parser_detail::ParseVec3(tokens, line, 2),
parser_detail::ParseVec3(tokens, line, 5),
parser_detail::ParseVec3(tokens, line, 8),
parser_detail::ParseColor(tokens, line, 11),
parser_detail::ParseFloat(tokens[14], line),
parser_detail::ParseUInt(tokens[15], line)
});
}
else
{
parser_detail::Fail(line, tokens[1].Column, "unknown light type `" + tokens[1].Text + "`.");
}
}
else if (command == "sphere")
{
parser_detail::RequireCount(tokens, line, 6, "sphere x y z radius material");
const auto materialIt =
materialIndices.find(tokens[5].Text);
if (materialIt == materialIndices.end())
{
parser_detail::Fail(line, tokens[5].Column, "unknown material `" + tokens[5].Text + "`.");
}
scene.AddSphere(
parser_detail::ParseVec3(tokens, line, 1),
parser_detail::ParseFloat(tokens[4], line),
materialIt->second);
}
else if (command == "triangle")
{
parser_detail::RequireCount(tokens, line, 11, "triangle ax ay az bx by bz cx cy cz material");
const auto materialIt =
materialIndices.find(tokens[10].Text);
if (materialIt == materialIndices.end())
{
parser_detail::Fail(line, tokens[10].Column, "unknown material `" + tokens[10].Text + "`.");
}
scene.AddTriangle(
parser_detail::ParseVec3(tokens, line, 1),
parser_detail::ParseVec3(tokens, line, 4),
parser_detail::ParseVec3(tokens, line, 7),
materialIt->second);
}
else if (command == "obj")
{
parser_detail::RequireCount(tokens, line, 7, "obj path material scale tx ty tz");
const auto materialIt =
materialIndices.find(tokens[2].Text);
if (materialIt == materialIndices.end())
{
parser_detail::Fail(line, tokens[2].Column, "unknown material `" + tokens[2].Text + "`.");
}
std::filesystem::path meshPath =
tokens[1].Text;
if (meshPath.is_relative())
{
meshPath = baseDirectory / meshPath;
}
const TriangleMesh mesh =
LoadOBJMesh(
meshPath,
parser_detail::ParseFloat(tokens[3], line),
parser_detail::ParseVec3(tokens, line, 4));
for (const MeshTriangle& triangle : mesh.Triangles)
{
scene.AddTriangle(
triangle,
materialIt->second);
}
}
else
{
parser_detail::Fail(line, tokens[0].Column, "unknown command `" + command + "`.");
}
}
if (!cameraFound)
{
parser_detail::Fail(1, 1, "scene is missing a camera command.");
}
if (scene.Materials.empty())
{
parser_detail::Fail(1, 1, "scene must define at least one material.");
}
if (scene.Primitives.empty())
{
parser_detail::Fail(1, 1, "scene must define at least one primitive.");
}
scene.MainCamera =
Camera::LookAt(
cameraPosition,
cameraTarget,
cameraUp,
cameraFOV,
static_cast<float>(scene.Settings.Width) /
static_cast<float>(scene.Settings.Height));
// Build the BVH after all primitives are known. If parsing fails before
// this point, no half-built scene escapes to the renderer.
scene.BuildAcceleration();
return scene;
}
[[nodiscard]]
inline Scene LoadScene(
const std::filesystem::path& path)
{
std::ifstream in(path);
if (!in)
{
throw std::runtime_error("Failed to open scene file: " + path.string());
}
std::ostringstream buffer;
buffer << in.rdbuf();
return ParseSceneText(
buffer.str(),
path.has_parent_path()
? path.parent_path()
: std::filesystem::current_path());
}
}