|
tinypbrt 1.1.1
pbrt-v4 scene file parser for C11 with a header-only C++20 wrapper
|
Tiny but powerful pbrt-v4 scene file loader written in C11, with an optional header-only C++20 wrapper.
tinypbrt parses .pbrt scene descriptions (cameras, film, samplers, integrators, shapes, materials, textures, lights, participating media, object instancing, animated transforms, Include/Import) into plain C structures that you can feed into your own renderer. It does not render anything and it does not load external assets (PLY meshes, images, spectra files) - it gives you their file names.
The same in C++ (C++ wrapper) - the scene frees itself and tagged unions become std::variant:
Identity, Translate, Scale, Rotate, LookAt, Transform, ConcatTransform, CoordinateSystem, CoordSysTransform (including the built-in "camera" system), TransformTimes, ActiveTransform (motion blur: every transform has a start and an end matrix)Camera, Film, Sampler, Integrator, Accelerator, PixelFilter, ColorSpace, OptionAttributeBegin/AttributeEnd, Attribute defaults, ReverseOrientation, Shape, Material, MakeNamedMaterial/NamedMaterial, Texture, LightSource, AreaLightSource, MakeNamedMedium/MediumInterface, ObjectBegin/ObjectEnd/ObjectInstanceInclude and Import (paths relative to the directory of the main file)TransformBegin/TransformEnd are acceptedinteger, float, point2/3, vector2/3, normal, bool, string, rgb, spectrum, blackbody, texture) with pbrt-v4 defaults applied(wavelength, value) pairs, named built-ins ("metal-Cu-eta", "stdillum-D65", ...) or a file nameWorldBegin, so Film may come after Camera; uroughness/vroughness default to roughness; the explicit parameter wins over Attribute; string escapes (\n, \t, \\, escaped quotes, ...) are decodedAttributeBegin/ObjectBegin nesting, include cycles - every problem is reported as an error codetinypbrt::tinypbrt_cpp, header-only): RAII scene, zero-copy views, std::variant for every tagged union, ranges-compatible lists and tpbrt::result<T> instead of output parameters - with the same performance as the C API| Category | Supported types |
|---|---|
| Cameras | perspective, orthographic, realistic, spherical |
| Films | rgb, gbuffer, spectral |
| Samplers | zsobol, halton, sobol, paddedsobol, independent, stratified |
| Integrators | volpath, path, bdpt, mlt, sppm, lightpath, randomwalk, simplepath, simplevolpath, ambientocclusion |
| Filters | gaussian, box, mitchell, sinc, triangle |
| Accelerators | bvh, kdtree |
| Shapes | sphere, cylinder, disk, trianglemesh, bilinearmesh, curve, plymesh, loopsubdiv |
| Materials | diffuse, coateddiffuse, conductor, coatedconductor, dielectric, thindielectric, diffusetransmission, hair, measured, mix, subsurface, interface |
| Textures | constant, checkerboard, imagemap, bilerp, dots, fbm, wrinkled, windy, marble, mix, directionmix, scale, ptex |
| Lights | point, spot, distant, infinite, goniometric, projection, area diffuse |
| Media | homogeneous, uniformgrid, rgbgrid, cloud, nanovdb |
-Wpedantic (tested with GCC 13 and Clang 18; the Windows presets use Clang)libm is linked automatically where needed)The CMake target is **tinypbrt::tinypbrt** for C and **tinypbrt::tinypbrt_cpp** for the C++20 wrapper (it links the C library for you; disable it with TINYPBRT_BUILD_CPP_WRAPPER=OFF). Tests, benchmarks, documentation and examples are built only when tinypbrt is the top-level project, so adding it as a dependency builds just the library.
CPM.cmake downloads and caches the dependency for you.
gh:MAIPA01/tinypbrt@v1.1.1 fetches the git tag v1.1.1. To follow a branch or pin a commit, or to pass options, use the long form:
If your project does not use CPM yet, the smallest setup is to download CPM.cmake at configure time:
Set the CPM_SOURCE_CACHE environment variable (for example to ~/.cache/CPM) to share downloaded packages between projects.
tinypbrt is a static library by default. Set TINYPBRT_BUILD_SHARED=ON (or the global BUILD_SHARED_LIBS=ON) to build tinypbrt.dll / libtinypbrt.so / libtinypbrt.dylib instead. Nothing changes in your code: linking tinypbrt::tinypbrt adds the TINYPBRT_SHARED_LIBS definition for you, and the public functions are declared with TPBRT_API:
| building tinypbrt | using tinypbrt | |
|---|---|---|
| Windows (MSVC, clang-cl, Clang, MinGW) | __declspec(dllexport) | __declspec(dllimport) |
| Linux / macOS (GCC, Clang) | __attribute__((visibility("default"))) | same |
| static library | *(empty)* | *(empty)* |
Only the public API (tpbrt_scene_load_*, tpbrt_scene_free, tpbrt_get_*) is exported; everything else is hidden. On Windows the DLL has to be found at run time - for example copy it next to your executable:
If you build tinypbrt without CMake, define TINYPBRT_SHARED_LIBS everywhere and TINYPBRT_EXPORTS only while compiling the library.
Scenes can also be parsed from memory. The second argument is the directory used to resolve Include/Import paths:
Everything you get back lives in tpbrt_scene_t and is owned by it: call tpbrt_scene_free once you are done (and only after a successful load).
| Field | Contents |
|---|---|
camera, film, sampler, integrator, accelerator, filter, options | scene-wide settings with pbrt-v4 defaults filled in |
start_time, end_time | shutter interval from TransformTimes |
shapes | shapes outside of ObjectBegin blocks |
objects, instances | object definitions (their shapes are in objects.objects[i].children) and their instances |
materials, textures, medias | every material, texture and medium, named or not |
lights.lights_sources, lights.area_lights | light sources and area lights referenced by shapes |
transforms | shared pool of matrices referenced by transform handles |
Things worth knowing:
type field and an as union, e.g. shape->type == TPBRT_SHAPE_TYPE_SPHERE → shape->as.sphere.tpbrt_string_t is { data, size }; print it with printf("%.*s", (int)s.size, s.data).tpbrt_get_material_by_handle, tpbrt_get_area_light_by_handle, tpbrt_get_media_by_handle, tpbrt_get_texture_by_handle, tpbrt_get_object_by_handle and tpbrt_get_transform. Named objects can be looked up with the *_by_name variants. Lists are passed by pointer (tpbrt_get_material_by_name(&scene.materials, name, &material)); name lookups use a small hash index built while loading (O (1), about 5 bytes per named object, nothing at all for scenes with at most 8 names in a list).float m[16] mapping object space to world space (for the camera: camera to world). Shapes, instances and the camera have a start_transform and an end_transform for motion blur; both handles are equal when the transform is not animated. Lights, media and textures have a single transform, as in pbrt-v4.tpbrt_texture_handle_t) are either a reference to a texture (value_type == TPBRT_TEXTURE_HANDLE_VALUE_TYPE_TEXTURE_IDX) or an inline value (..._SPECTRUM); plain floats are stored as constant spectra (as.spectrum.as.constant).tpbrt_spectrum_t) are RGB (in the color space active at that point), blackbody temperature, wavelength/value pairs, a built-in name, a file name or a constant.All functions return tpbrt_error_t (TPBRT_ERROR_NONE on success). Loading stops at the first error and frees everything that was allocated, so a failed tpbrt_scene_load_* needs no cleanup. tpbrt_get_error_message turns a code into a readable message:
Parameters are matched by name and declared type, as in pbrt-v4: Shape "sphere" "string radius" "big" (or "integer radius" 2) fails with TPBRT_ERROR_PARAM_TYPE_MISMATCH - *"Parameter is declared with a different type
than expected"*. point/vector/normal are accepted as synonyms of point3/vector3/normal3. Numbers are parsed independently of the C locale, and a token must be a complete number (1.5abc or an integer written as 2.0 is an error). Redefining a named material, medium, object or a texture of the same type is an error (TPBRT_ERROR_DUPLICATE_*), like in pbrt-v4; float and spectrum textures have separate namespaces.
#include <tinypbrt/tinypbrt.hpp> and link tinypbrt::tinypbrt_cpp (C++20). The wrapper is header-only and adds no copies: every type is a small view over the C structure, so it is as fast as the C API (see Benchmarks).
| C | C++ |
|---|---|
tpbrt_scene_t + tpbrt_scene_free | tpbrt::scene (RAII, move-only) or tpbrt::scene_view over a scene you own |
tpbrt_error_t + output parameter | tpbrt::result<T> (if (r), *r, r->, get_error(), value_or(), visit()) |
tpbrt_string_t | tpbrt::string (std::string_view-like, comparable with strings) |
{ data, count } arrays and lists | tpbrt::array<...>: size(), [], at(), iterators, std::ranges algorithms/views |
type + as union | type(), is_xxx(), as_xxx() → std::optional, visit(), as<T>(), holds<T>() |
tpbrt_get_material_by_handle / _by_name | scene.materials().at(handle) / .at("name") (also textures, media, objects, ...) |
TPBRT_SHAPE_TYPE_SPHERE, ... | enum class (tpbrt::shape_type::SPHERE) and tpbrt::to_string(...) |
Things worth knowing:
tpbrt::scene) are non-owning, pointer-sized and cheap to copy - take them by value. They stay valid as long as the scene lives, also after the tpbrt::scene object was moved (the C data does not move). .native() returns the C structure, so both APIs can be mixed freely.std::visit always knows what it got: a blackbody temperature is tpbrt::blackbody, not a float like a constant spectrum, and fbm/wrinkled/windy textures have their own parameter types. visit returns std::optional with the visitor's result (empty for an unknown type), or nothing for a void visitor.tpbrt::result); operator[] and *result are unchecked like in the standard library, at() and get_value() check. Only get_value() on an error throws (std::bad_variant_access).== and <=> compare the contents, not the addresses).| Option | Default | Description |
|---|---|---|
TINYPBRT_BUILD_SHARED | BUILD_SHARED_LIBS | build tinypbrt as a shared library (details) |
TINYPBRT_BUILD_CPP_WRAPPER | ON | provide the C++20 wrapper tinypbrt::tinypbrt_cpp (details) |
BUILD_SHARED_LIBS | OFF | CMake's global default for all libraries (also GoogleTest in this repository) |
TINYPBRT_BUILD_TESTS | top-level only | build the GoogleTest suites (C library and C++ wrapper) and the C API test |
TINYPBRT_BUILD_BENCHMARK | top-level only | build benchmarks (C and C++) |
TINYPBRT_BUILD_EXAMPLES | top-level only | build examples |
TINYPBRT_BUILD_DOCUMENTATION | top-level only | Doxygen documentation: docs target (details) |
TINYPBRT_BUILD_COVERAGE | top-level only | LLVM coverage instrumentation and the coverage target (Clang) (details) |
TINYPBRT_ENABLE_CLANG_TIDY | top-level only | clang_tidy_* targets (details) |
TINYPBRT_WARNINGS_AS_ERRORS | top-level only | treat compiler warnings as errors when building tinypbrt |
TINYPBRT_ENABLE_PEDANTIC | ON | build tinypbrt with -Wpedantic (GCC/Clang): only ISO C11, no compiler extensions |
TINYPBRT_ENABLE_SANITIZERS | OFF | build the library and tests with sanitizers |
TINYPBRT_SANITIZERS | address;undefined | sanitizers to use (address, undefined, leak, memory, thread) |
TINYPBRT_INSTALL | top-level only | generate install rules |
TINYPBRT_SYNC_VERSION | top-level only | write the version into README.md and examples/cpm_project (details) |
Compiler warnings and optimization flags used to build tinypbrt are private to the library: they are not added to your targets. Link-time optimization and static linking are left to your project (e.g. CMAKE_INTERPROCEDURAL_OPTIMIZATION).
The version is set in one place only: project(tinypbrt VERSION x.y.z ...) in the main CMakeLists.txt. The library (VERSION/SOVERSION), the installed package version files and the Doxygen documentation read it from there, and configuring tinypbrt as the top-level project writes it into this README (@vx.y.z, GIT_TAG vx.y.z, find_package(tinypbrt x.y)) and into examples/cpm_project (cmake/version_sync.cmake). With TINYPBRT_SYNC_VERSION=OFF run cmake --build build --target tinypbrt-sync-version instead; the tinypbrt-version-check test fails when the files are out of date. Push the matching vx.y.z git tag when releasing, so the CPM and FetchContent snippets work.
[examples/](examples) contains small C11 programs built on the public API (-DTINYPBRT_BUILD_EXAMPLES=ON, on by default when tinypbrt is the top-level project), together with two scenes in examples/scenes:
| Example | Shows |
|---|---|
quickstart | the program from Quick start |
scene_info | camera, film, sampler, integrator, filter and accelerator settings; shapes, materials, textures and media |
load_from_memory | parsing from memory, Include relative to a working directory, error codes and messages |
materials | shape → material → texture handles, inline values vs. texture references, lookup by name |
lights | light sources in world space (from/to transformed by the light's CTM), area lights on shapes |
export_obj | converting meshes, spheres, cylinders, disks and object instances to a Wavefront OBJ file |
The C++20 versions in examples/cpp use the wrapper (built when TINYPBRT_BUILD_CPP_WRAPPER=ON):
| Example | Shows |
|---|---|
tinypbrt-cpp-example-quickstart | RAII scene, visit with overloaded lambdas, handle lookups returning tpbrt::result |
tinypbrt-cpp-example-scene_info | settings via tpbrt::to_string, a generic visitor with if constexpr, lights, textures |
tinypbrt-cpp-example-materials | std::views::filter / std::ranges::count_if on lists, lookup by name, texture handles |
examples/cpm_project is a standalone CMake project that pulls tinypbrt with CPM, exactly as described above. Pass -DCPM_tinypbrt_SOURCE=/path/to/tinypbrt to build it against a local checkout.
On Windows (Clang + Ninja) use the x64-debug-c11 preset, or x64-debug-c11-sanitizers for AddressSanitizer + UndefinedBehaviorSanitizer:
The shared-library build has its own presets: linux-debug-shared-sanitizers and x64-debug-c11-shared (the GoogleTest suite then links a static copy of the library, because it also tests internal functions; tinypbrt-c-api-tests runs against the DLL / .so).
Without presets:
The test suite (tinypbrt-tests, GoogleTest, C++17) covers the parser, parameter handling, every directive and object type, error paths and memory safety under the sanitizers; tinypbrt-c-api-tests checks that the public headers compile and work as strict C11. tinypbrt-cpp-tests (GoogleTest, C++20) tests the wrapper: every variant alternative, to_string of every enum value against the C parser, lookups, tpbrt::result, moves of tpbrt::scene, and that whole example scenes read through the wrapper give the same values as the C API. The tinypbrt_cpp_header_check target compiles every C++ header on its own.
tinypbrt-benchmark (Google Benchmark, -DTINYPBRT_BUILD_BENCHMARK=ON) loads generated scenes of growing size, each stressing a different part of the parser: many shapes with their own transforms, one large triangle mesh (number parsing), named materials and textures (name lookups), object instances, shared transforms (matrix deduplication), deeply nested attributes and a mixed scene. It also measures handle resolution and tpbrt_get_material_by_name on a loaded scene. Use a Release build:
bytes_per_second is the parser throughput, items_per_second the number of scene elements (shapes, vertices, instances...) per second. Compare two JSON runs with tools/compare.py from Google Benchmark.
tinypbrt-cpp-benchmark measures the cost of the C++ wrapper: every bm_cpp_* benchmark has a bm_c_* twin doing the same work with the C API (loading, iterating shapes with visit/as_xxx(), iterating a 1M-vertex mesh, lookup by name). Example results (GCC 13, Release):
| Benchmark | C | C++ |
|---|---|---|
| load 100k spheres | 98.9 ms | 97.0 ms |
| sum radii of 100k spheres | 390 µs | 402 µs (visit), 384 µs (as_sphere()) |
| max x of a 1M-vertex mesh | 1.45 ms | 1.47 ms |
| material by name (10k materials) | 49.7 ns | 48.3 ns |
With Clang (clang/clang++, also clang.exe on Windows) and TINYPBRT_BUILD_COVERAGE=ON the library, the tests and the examples are built with LLVM source-based coverage. The coverage target runs every test from ctest (each process writes its own .profraw), merges the data with llvm-profdata and writes an HTML report with line, region, branch and MC/DC coverage, plus a summary table in the console:
llvm-profdata/llvm-cov matching the Clang version are found next to the compiler. Tests, examples, benchmarks and third-party code are excluded from the report.
The report for the latest commit on main is published at https://maipa01.github.io/tinypbrt/coverage/ by the Docs & coverage workflow.
With TINYPBRT_ENABLE_CLANG_TIDY=ON every checked target gets two targets: clang_tidy_<target> checks only the files that changed (or still had warnings) since the last run, clang_tidy_<target>_full checks everything. Targets added with the same GROUP share one configuration and one run, clang_tidy_<group> / clang_tidy_<group>_full:
The first target of a group sets CONFIG, CXX_STANDARD and the header filters; later targets may omit them or must pass the same values (a different value is a configuration error). clang-tidy reads the compile flags from compile_commands.json, so it needs a Ninja or Makefile generator; EXCLUDE_HEADER_FILTER requires clang-tidy 19+ and is skipped for older versions.
cmake --build <build> --target docs runs Doxygen (TINYPBRT_BUILD_DOCUMENTATION=ON) with docs/Doxyfile.in and writes <build>/docs/html/index.html. This README is the main page; additional pages go to docs/pages (Markdown) and images to docs/images. Document the public headers with Doxygen comments; -DTINYPBRT_DOCUMENTATION_WARN_UNDOCUMENTED=ON lists what is still missing.
The documentation of main is published at https://maipa01.github.io/tinypbrt/ on every push (GitHub Actions -> GitHub Pages, together with the coverage report).
tinypbrt is released under the BSD 3-Clause License with an attribution requirement - see [LICENSE](LICENSE) for the full terms.