Model loading#
How a model file becomes drawable geometry in the Vulkan engine: the one
loader, the async parse/upload split that keeps the frame loop responsive, and
the multi-mesh flow that turns one file into per-mesh draws. The chronological
change log is docs/source/cpp-renderer-improvements.md.
One loader for every format#
GltfLoader (scene/GltfLoader.{ixx,cpp}) loads .gltf, .glb and .obj
into one set of CPU-side arrays; the bridge picks OxidANT’s glTF or OBJ reader
by the file’s extension. It exposes:
parseCpu(path)— reads and decodes the file into flat arrays (vertices,indices, per-trianglematerialIndex,materials, plus a per-meshmeshRangestable, see below). Touches no Vulkan, so it can run on any thread.uploadParsed()— builds the Vulkan-sideModel(buffers, textures, meshes) from the lastparseCpuresult. Must run on the thread that owns the device.adoptParsed(other&&)— moves another loader’s parse results in, so a device-owning loader uploads what a device-free worker produced without copying the (tens-of-MB) arrays.
loadModel(path), the synchronous path, is parseCpu then uploadParsed
back-to-back on the calling (device-owning) thread.
The OBJ reader#
An .obj goes through the same bridge call to OxidANT’s OBJ reader
(kataglyphis_assets::obj::load_obj_flat), the one the WebGPU renderer opens
OBJ through too. It is tolerant like tinyobjloader, which it replaced on
2026-11-23: a malformed or unsupported line is skipped and logged, a number
that does not parse or is not finite reads 0, relative indices resolve, a face
over 2048 corners is skipped, and only a file without a drawable face fails.
Polygons split as tinyobjloader split them (a quad along its shorter diagonal,
larger ones through its ear clipper). Each usemtl run is one MeshRange: a
run ends where its o/g group or its material does (owner 2026-11-24), so
Sponza draws 385 meshes (ObjLoader drew 373, one per group). The .mtl
files and textures are confined to the OBJ’s folder like a glTF’s buffers and
images (owner 2026-11-24). Textures arrive decoded, as glTF’s do (below); a
file that cannot be read or lies outside the folder leaves its slot at -1. Tangents are
the glTF path’s, generated from UV0 per run. The material rules are the
owner’s (2026-11-19): d below 1 or Tr above 0 is BLEND, a map_Ke
without any Ke glows at factor 1 (an authored Ke 0 0 0 stays dark), no
Kd is white, no Pr and no Ns is roughness 1, map_d is its own linear
mask slot cut at 0.5.
ObjLoaderDiff compared tinyobjloader’s ObjLoader with the bridged reader
on every fixture and fetched OBJ scene before the switch
(cpp-renderer-improvements.md).
The glTF parser#
GltfLoader::parseCpu is OxidANT’s loader, the one the WebGPU renderer uses,
called over the cxx bridge (load_gltf_flat in crates/cxx_bridge/src/gltf.rs,
flattened by crates/assets/src/flat.rs). GltfLoaderRust.cpp keeps the
returned GltfModel alive through an untyped std::shared_ptr and views its
vertices, indices, material ids and texture chains in place (std::span over
data()/size(); GltfVertex and Vertex agree field by field): nothing is
copied before the staging buffer, which for Colosseum-gltf was about 0.5 GB
held twice at the parse’s peak. Copies of a loader share the parse. It bakes the default morph pose (the node’s
weights, else the mesh’s) and world space, reverses a mirrored node’s winding,
gives a primitive without NORMAL one vertex per corner with its face’s
normal, keeps only the vertices a primitive’s indices use, and hands textures
over decoded, deduped on (image sources, sampler settings, srgb).
EXT_ and KHR_meshopt_compression views are decoded before an accessor reads
them (crates/assets/src/meshopt.rs, plan N4): gltfpack’s -c, -cc and
-cz output loads, in both renderers. Each compressed bufferView’s stream is
decoded in safe Rust (meshopt_codec.rs: the attribute codec’s versions 0 and 1,
the triangle and index codecs, the octahedral, quaternion, exponential and colour
filters, as meshoptimizer’s scalar decoder does) in place into the parent view’s
range: of its fallback
buffer, which is never read, of a URI-less placeholder, or of a buffer with data.
A view that breaks the extension’s layout rules, a stream that ends early or runs
on, and a placeholder declaring more than its views decode (each rounded up to 16
bytes) fail the load. One file’s views decode to at most 1 GiB. A view is held
to the extension it names: EXT allows the attribute codec’s version 0 and no
colour filter, KHR attribute versions 0 and 1 and the index codecs’ version 1
only, and a view under both is refused.
Textures are decoded in Rust, on every core of the parse thread (plan B5).
Each slot is a mip chain, level 0 first and packed back to back (levels.rs’s
TextureChain, tagged with its ChainFormat), which Texture::createFromLevels
uploads without a blit. PNG, JPEG, BMP, TGA, GIF, PNM, Radiance HDR and WebP (lossy or
lossless) decode through the image crate (image_decode.rs, channels expanded and HDR gamma-encoded
as stb’s STBI_rgb_alpha does) to a full RGBA8 chain down to 1x1, box-filtered with
the WebGPU renderer’s filter (sRGB averaged in linear space). A KHR_texture_basisu
KTX2 is preferred over the core source, then an EXT_texture_webp image; one that
does not decode falls back to the next, the core source last. A KTX2 arrives as the
blocks the device samples (plan B5 step 3): VulkanDevice enables textureCompressionBC, ETC2 and
ASTC_LDR where offered and counts a family (BlockSupport, scene/TextureFit.hpp)
when every one of its formats, in both colour spaces, samples, filters linearly and
takes a copy with optimal tiling; the renderer hands that and maxImageDimension2D
to the scene before its first load, and the options carry them to the bridge. A Basis
payload is transcoded once to BC7, else ETC2, else ASTC 4x4, a BCn KTX2 kept as stored,
when the base is whole 4x4 blocks and a level of whole blocks fits the side; the chain
keeps the file’s levels, and a colour slot samples the sRGB format (BC5 has none).
Otherwise the payload’s own levels are transcoded straight to RGBA8 or decoded (a
Basis base of partial blocks included), and a chain shorter than full is completed by
halving its last level, as glTF asks of a texture a mipmapping sampler reads. A
decoded BC5 reads linear in a colour slot too, as its blocks do (levels::reads_srgb
labels the slot). The WebGPU renderer builds the same chain in the same colour space
for its adapter (a unit test compares the two for every KTX2 fixture). A stored ETC2 or ASTC KTX2 is still
refused; the core source is the fallback whenever the KTX2 fails. An animated WebP,
which EXT_texture_webp asks not to be, decodes to its first frame on a transparent
canvas, as a browser’s createImageBitmap takes it, and logs a warning. PSD and PIC arrive
as the file’s bytes, which parseCpu decodes with stb on its own thread into the same RGBA8
chain (decodeStbTextures, halveRgba8’s box filter), so uploadParsed decodes nothing; bytes
stb cannot read keep levelCount 0 and get the default texture. An image over 16384x16384
pixels (MAX_PIXELS, read from its header, PSD and PIC included) or in no format
either reader knows gets no slot, and the materials’ ids are renumbered. Decodes in
flight share a 1 GiB budget, and one image under two samplers is decoded once. A
level over maxImageDimension2D is skipped (a block chain starts at whole blocks);
a chain none of whose levels fits gets the default texture, as does a block format the
device does not sample. Colosseum-gltf’s 69 PNG and JPEG images make 760 MB of RGBA8
chains, held until uploadParsed has staged them; the decode runs after the scene walk
with the document’s buffers already dropped, so load_flat peaks at 1.28-1.30 GiB
resident there (745 MiB when it handed over the encoded files). The same images as
UASTC KTX2, AssetANT’s Colosseum-ktx2, make 190 MB of BC7 chains on a BC device
instead of 760 MB of RGBA8: load_flat peaks at 706-714 MiB instead of 1349-1375 MiB,
and the textures take 190 MiB of device memory instead of 760 MiB. The document, its buffers and
its images must be regular files, the buffers and images inside the document’s
directory.
What a load asks beyond the file is a GltfLoadOptions (mikktspaceTangents
and the device’s blocks), which parseCpu, loadModel, AsyncModelParse::start
and Scene hand to load_gltf_flat_with; each field’s zero is the loader’s default,
RGBA8 for every texture. The
loader reads no environment: App::run turns KATAGLYPHIS_MIKKTSPACE_TANGENTS
into the options once, through gltfLoadOptionsFromEnvironment (any non-empty
value; empty counts as unset, as in OxidANT’s viewer), and tests ask through the
options. The fixtures both renderers load are OxidANT’s
crates/assets/tests/assets; GltfFixtureRoundTrip.* checks each one’s
mapping into Vertex, MeshRange and ObjMaterial. What the parser decides
(slots, material defaults, the scene walk) is tested in OxidANT’s
crates/assets/tests/flat.rs; GltfParseUnit.* keeps what the C++ side decides.
An error, or a panic in any build, comes back as a failed parse, never an
exception or an abort: every bridged call runs inside OxidANT’s guarded(),
and the non-Debug builds link the bridge with OxidANT’s bridge cargo profile
(Src/CMakeLists.txt), release with panic = "unwind", since the release
profile’s abort let a loader panic end the engine. The path crosses as UTF-8
(Shared::utf8PathBytes): a Windows std::string is ANSI, which the bridge
rejects. The loader’s warnings come back as values too: right after the call,
on the thread that made it (the parse worker), logOxidantRecords drains
OxidANT’s take_log_records() into spdlog.
It walks a single scene, not every node in the document: the default scene if
the document names one, else the first of scenes (walk_nodes in
crates/assets/src/gltf_loader.rs). Only nodes reachable from that scene’s
roots are loaded. A document with no scenes array at all falls back to every
node, with a warning, since that is the only geometry available.
Until 2026-11-18 the engine had its own cgltf parser beside this one; a
field-by-field comparison of the two on every fixture and fetched scene found
three defects in each before the Rust loader became the only one (owner
decision, cpp-renderer-improvements.md).
BM_GltfLoaderParseCpu_* times the whole parse; on linux-profile-clang,
8-core aarch64 WSL, Colosseum-gltf (206 MB of buffers) took 394 ms against
cgltf’s 481 ms. That row skips unless KATAGLYPHIS_FETCH_ALL_ASSETS fetched
the scene.
The same walk reads each visited node’s KHR_lights_punctual light, mesh or no mesh, posed by the
node’s world transform (the Rust loader’s read_light). The lights ride
on the Model, so adoptParsed moves them with the geometry, and the renderer places them by the
model’s matrix when it packs the punctual-light buffer.
The first directional light is the Sun instead, both renderers’ rule (OxidANT’s CpuScene::take_sun):
it leaves the lights, rides on the Model as getSun(), and the load’s RendererFeedback::publishedSun
hands its direction and colour to the editor’s Sun in applyRendererFeedback. The radiance stays the
editor’s, since glTF gives lux. A direction its node scales to nothing is no Sun and no light either.
The async parse/upload split#
The parse is device-free and dominates load time (2802 ms of a 2818 ms load on
the bundled 27 MB dinosaurs.obj), so it runs off the render thread:
AsyncModelParse(scene/AsyncModelParse.ixx) runsparseCpuon a worker thread against a fresh device-freeGltfLoader{}.When the worker finishes,
Scene::pollModelLoad(scene/Scene.cpp) hands the worker’s loader to a device-owning uploader viaadoptParsedand callsuploadParsed, the only ~15 ms the frame loop pays.
Every texture is decoded by then, PSD and PIC included, so the device thread only copies.
uploadParsed records the model’s textures and every mesh’s vertex, index, material-id and
material buffers into one command buffer through an UploadBatch (scene/Texture.ixx): a
staging ring, one host-visible buffer of the upload’s size up to 64 MiB, filled front to back.
A model pays one submit per fill instead of one per texture and four per mesh (Colosseum-gltf’s
760 MB about 12 instead of 69 for the textures alone;
Integration.AModelsTexturesUploadThroughOneStagingRingSubmit,
Integration.AModelsMeshesUploadInTheSubmitItsTexturesTake, which counts every single-use submit
through CommandBufferManager::singleUseSubmitCount); a failed submit empties the textures it
held, each slot getting the default texture, and leaves the buffers unwritten.
No fill waits for the GPU. Every scene load uploads through the renderer’s UploadQueue
(vulkan_base/UploadQueue.ixx). It submits a fill without a fence and keeps its ring and command
buffers until a timeline semaphore reports its copies done. The next fill takes another ring. At
most two rings are in flight, so only a load past two fills waits, for the oldest one’s copies. If
that wait ends without them, as on a lost device, the fill takes a ring past the bound.
The fills copy on a transfer-only queue family where the device has one, else on a compute one
without graphics (pickUploadFamily, vulkan_base/UploadRoute.hpp). Each fill then releases its
images and buffers to the graphics family. A graphics-queue submit waits on the copies’ timeline and
acquires them, so every later graphics command reads the finished fill, the BLAS build included.
Each queue signals a timeline of its own. The acquire is recorded before the copies are submitted,
so a failed acquire submits nothing. Every call whose failure a fill reports takes vulkan.hpp’s
count-and-pointer overload, or endCommandBuffer (common/ResultReturningCalls.hpp), since the
enhanced overloads assert on a failure under VULKAN_HPP_NO_EXCEPTIONS. The startup log names the route and both queue families
(uploadRouteLine). On one family, llvmpipe’s, a fill runs on the graphics queue
and ends in one barrier that hands its copies to every later command. Model::cleanUp waits for a
fill that has not landed (UploadTicket). A loader given no queue, as the tests’ own, still waits
for each fill on the graphics queue.
Tests:
Integration.AModelUploadSubmitsWithoutTheCpuWaitingForTheGpu: no fence or GPU wait in an upload.Integration.AFillHandedOverInASubmitOfItsOwnDrawsAsAFenceWaitedFillDoes: the two-submit hand-over, split on llvmpipe’s one queue too, draws as a fence-waited fill.Integration.FillsPastTheRingReuseItsBytesOnlyOnceTheirCopiesEnd: reads back what reused rings wrote.Integration.AFillWhoseRingWaitEndsEarlyTakesANewRingInsteadOfWaitingAgainandIntegration.AFillWhoseVulkanCallFailsReportsItAndLeavesNothingPending: the failure paths above, each driven by a dispatcher entry that returns a failure.Integration.TheStartupLogNamesTheUploadRouteAndBothQueueFamilies: the route line.
A finished load drains nothing. The upload waits for nothing, and the device is not drained either:
pollModelLoad moves a replace’s old models to takeReplacedModels, and finishModelLoad hands
them, the old object-description and punctual-light buffers, the punctual shadow cubes a changed
shadowed-light count reallocated (PunctualShadowMaps::takeRetired) and the BLAS and TLAS the
rebuild replaced (ASManager::takeRetired) to the renderer’s FrameRetireQueue
(renderer/FrameRetireQueue.hpp). Each frame submit is numbered; a retired resource waits for the
last frame submitted before it, and is released once an in-flight fence covering that frame has
signaled (a fence signal covers every earlier submit on the queue). Every image’s descriptor sets
still name the replaced resources until its last frame is done, so the refresh only marks them
stale, and record_commands rewrites an image’s object-description, texture and ray-tracing
bindings before it records (Integration.AReplacedModelOutlivesTheFramesInFlightThatDrewIt, once
with the rig’s cubes kept and once with them reallocated).
So adoptParsed must move every field uploadParsed reads, meshRanges
included; miss one and the async path silently loads different geometry than
the synchronous one.
flowchart LR
subgraph worker["Worker thread (no device)"]
P["parseCpu(path)\nflat arrays + meshRanges"]
end
subgraph main["Render thread (owns device)"]
Poll["Scene::pollModelLoad\nwhen worker isFinished()"]
A["uploader.adoptParsed(move)\ntakes the arrays, no copy"]
U["uploader.uploadParsed()\nbuffers, textures, one Mesh per range"]
Add["Scene::add_model\none ObjectDescription per mesh"]
end
Start["AsyncModelParse.start(path)"] --> P
P -->|arrays moved| Poll --> A --> U --> Add
What the startup load reads, Rust’s chain: the command line’s [model] (App::run’s
AppOptions, from absl’s positional argument in Main.cpp), else KATAGLYPHIS_MODEL_OVERRIDE,
else the build’s default. A given file that is missing, not a file or no .gltf, .glb or .obj
is logged, and the chain goes on without it. The status bar shows the same notes in amber until a
load starts. That is Rust’s Notice::Hint, built by startupNotice. It names a missing model file.
An override that names no file is still tried, with no fallback. A missing default scene gets Rust’s fetch hint.
The status bar shows a load in flight, then a failed one. While a parse runs, the line reads
Loading <file stem> · parsing, muted, ahead of any notice (Scene::pendingModelLoadPath). A
load that fails leaves Could not load <file stem>: <reason> in red until the next load starts
(Scene::takeModelLoadFailure). The reason is OxidANT’s parse error, else it holds no triangles
or the upload failed. A dropped file that is no model fails the same way. A failed startup load keeps
the startup notes when it has them, since Rust never opens a model they call missing. Both texts are
OxidANT’s render_core::load_notice, through the bridge. C++ has no fetch or upload stage to show.
A dropped file replaces the scene through the same split. Window’s drop callback queues the
paths; the renderer takes the last model of a drop and Scene::beginModelReplaceAsync parses it on
the worker while the old scene draws. A drop while a parse runs, the startup load’s or an earlier
drop’s, waits for it to end (queuedModelReplace, the newest winning) instead of joining it on the
frame thread, and then supersedes it. pollModelLoad uploads the result first, then retires the
old models behind the frames in flight, so a drop that does not parse or upload keeps the scene. A command-line
or dropped file below Resources/Models goes by the path the library lists
(sceneConfig::libraryPathFor), so the library marks its row; any other keeps its absolute path.
The loaders take narrow paths, the ANSI code page on Windows, so a name that code page cannot hold
is skipped with a warning. The editor’s library pick loads the same way (since C7,
handleModelReloadRequest): a pick during a parse waits as a drop does, never joining it on the
frame thread (Integration.ALibraryPickDuringAParseWaitsWithoutBlockingTheFrame), the old scene
draws until the pick lands (Integration.ALibraryPickKeepsTheSceneDrawingUntilItsModelLands), and a
replace that does not load keeps it (SceneAsyncLoad.AFailedReplaceKeepsTheSceneItWouldReplace, and
the renderer keeps drawing it: Integration.ALibraryPickThatFailsToLoadKeepsTheSceneDrawing, which
lists a broken file through sceneConfig::addModelRowForTesting, since the scan is cached per
process); the synchronous reloadModel, which emptied the scene first, is gone. addModel stays
synchronous: a drain, the load, the refresh.
One file, many meshes#
A Model holds std::vector<Mesh> (scene/Model.ixx). One file becomes a
multi-mesh model through a per-mesh MeshRange, a slice of the flat arrays:
struct MeshRange {
vertexBase, vertexCount, indexStart, indexCount, triStart, triCount, doubleSided, alphaBlended
};
doubleSided carries glTF material.doubleSided per range, so uploadParsed
hands it to add_new_mesh and the raster pass can disable back-face culling
for that mesh alone. alphaBlended carries alphaMode BLEND the same way
(Mesh::isAlphaBlended): the opaque forward and deferred draws skip the mesh,
and collectBlendDraws (renderer/MeshDrawRecorder.cpp) draws it after them,
farthest first by the squared distance from the eye to its world-bounds centre,
through buildTransparentScenePipeline (src-alpha blending that accumulates
coverage, depth test on, depth writes off). Deferred shades it forward after
the lighting pass, against the geometry pass’s depth. An OBJ is never
double-sided; its d below 1 or Tr above 0 blends.
The type lives in its own module, kataglyphis.vulkan.mesh_range
(scene/MeshRange.ixx), export imported by GltfLoader. It exports
MeshRange and the two pieces the upload uses: meshRangeFits, which decides
whether a range gets its mesh or an empty one, and rebaseIndices.
parseCpu records one range per sub-object and keeps the flat arrays intact
(the ObjParseUnit/GltfParseUnit tests assert on the flat getters);
GltfLoader::uploadParsed hands add_new_mesh subspans of the bridge’s arrays
(addMeshesForRangesInPlace), and Mesh re-bases the indices while it writes
them into the staging memory. A sub-object is:
glTF — one primitive. Primitives already parse into disjoint contiguous vertex ranges, so the range is recorded directly.
OBJ — one
usemtlrun, ended by itso/ggroup or its material; the range gets only the vertices its triangles use, so a vertex two runs share is stored once per run.
A single-primitive glTF or single-run OBJ yields exactly one range spanning everything.
What downstream gets for free#
Object identity is per mesh, not per model, so splitting a file into meshes feeds the systems that were already mesh-aware:
Object descriptions —
Scene::add_modelflattens oneObjectDescriptionper mesh;objectIndexis the flat mesh index (sum of prior models’ mesh counts + local index), pushed per draw in the forward/deferred/shadow record loops.Culling — the record loops iterate meshes with per-mesh AABBs, so a multi-mesh model culls per mesh instead of all-or-nothing.
Acceleration structures — one BLAS per model with one geometry per mesh; RT/PT kernels fetch the per-mesh material with
instanceCustomIndex (= the model's first-mesh flat index) + gl_GeometryIndexEXT(GoldenRender.TracedSecondModelResolvesItsOwnMeshAndTextures). AnaddModelor a finished load builds only the new model’s BLAS: a BLAS stays while the scene holds the model object it was built from at its index (BlasReuse.hpp), so a reload rebuilds; every scene change builds the TLAS (GoldenRender.AddedModelBuildsOnlyItsOwnBlas). The TLAS is built witheAllowUpdate, so an editor move of model 0 rewrites its instances withvkCmdUpdateBufferand updates it in place in the next frame’s command buffer, as it does the punctual-light rows, without a device drain; the move restarts the path-traced mean itself, since no descriptor changes (GoldenRender.PathTracingRestartsWhenATransformUpdatesTheTlasInTheFrame). A move that changes the light count, reallocates the cubes or finds no TLAS takes the full refresh. It builds the TLAS again. It retires what it replaced, as a load does. It does not drain (GoldenRender.PathTracingRebuildsAMissingTlasOnAMove,GoldenRender.ALightCountChangeOnAMoveRetiresInsteadOfDrainingInForward).No build waits for the GPU — one command buffer records the new BLAS and the TLAS. A barrier after each BLAS build orders the TLAS build after it. The graphics queue runs it without a fence, so every later frame orders after it. A timeline semaphore tells when it is done. Then
ASManager::collect, once a frame, frees its scratch, staging and command buffer and the models it read. The same submit writes the compacted BLAS sizes into a query pool. A latercollectreads them without a wait. It copies each BLAS compacted and updates the TLAS in place to point at the copies, in one submit. The originals go once that submit is done. A reload that drops a BLAS drops its pending compaction too (Integration.ALoadOnARayTracingDeviceBuildsItsAccelerationStructuresWithoutACpuWait,Integration.ABlasBuildKeepsItsScratchUntilTheGpuIsDone).
Material fields and where they come from#
ObjMaterial (Src/shared/scene/ObjMaterial.hpp) is the single struct both
loaders fill and every shader reads. OxidANT’s load_material
(crates/assets/src/gltf_loader.rs), flattened by flat.rs and copied by
toObjMaterial (GltfLoaderRust.cpp), is the glTF mapping; OxidANT’s obj/flat.rs and obj/material.rs are the .mtl mapping, which writes roughness itself.
A — means that format has no source for the field, so the struct keeps its
default (documented on the member in ObjMaterial.hpp). “Read by” names the
shading paths at a glance; the exact per-path expression, or “not read” and
why, is in
shader-sharing.md’s “Which C++ shading path reads which ObjMaterial
field”.
Member |
glTF source |
|
Read by |
|---|---|---|---|
|
|
|
|
|
|
|
all four shading paths, via |
|
— (pinned to |
— (pinned to |
|
|
|
|
|
|
dedup’d slot into |
dedup’d slot into |
all five entry points, via |
|
|
— (OBJ has no sampler concept; every OBJ texture keeps the repeat/linear/linear default) |
|
|
|
|
|
|
|
|
|
|
|
— |
|
|
|
|
|
|
|
|
|
|
dedup’d slot into |
dedup’d slot (same |
all four shading paths, via |
|
dedup’d slot into |
dedup’d slot (same |
all four shading paths, via OxidANT’s |
|
|
the winning normal-directive’s own |
|
|
dedup’d slot into |
— |
|
|
|
— |
the normal sample in all four shading paths, via |
|
|
— |
the metallic-roughness sample in all four shading paths, via |
|
|
— |
the emissive sample in all four shading paths, via |
|
|
— ( |
all four shading paths return the base colour unshaded when set: |
|
— (glTF carries opacity in |
dedup’d slot (same |
|
|
bit per slot (0 base colour, 1 metallic-roughness, 2 normal, 3 emissive, 4 occlusion) whose |
— ( |
every texture sample, via |
|
|
|
|
|
dedup’d slot into |
— ( |
|
|
|
|
|
|
|
identity |
|
Textures, samplers and the 128-slot budget#
Every texture from every loaded model lands in one flat, fixed-size global
array bound at TEXTURES_BINDING/SAMPLER_BINDING, sized by
Resources/ShadersSlang/common/shared_constants.slang’s MAX_TEXTURE_COUNT, which
common/host_device_shared_vars.hpp includes: static const int MAX_TEXTURE_COUNT = 128;. The loader economises against that
budget:
glTF dedup by image, sampler settings and colour space — OxidANT’s
flat.rs(Slots) keys each slot on the triple(image, sampler settings, srgb), not the material or the texture slot (base-colour vs. emissive vs. normal). One decode+upload per triple, however many materials or texture slots reference it: a material whose base-colour and emissive views name the same PNG shares one slot (textureID == emissiveTextureID), and so do two equal sampler objects. Two textures that share an image but sample it differently, or need different colour spaces, still get distinct slots; collapsing them would make the second texture’s wrap/filter settings unobservable, or upload one of the two through the wrongVkFormat. A base-colour/normal pair sharing one image therefore gets two slots, one uploaded sRGB (Texture.cpp’suploadRgbapickseR8G8B8A8Srgb), the other UNORM (eR8G8B8A8Unorm): glTF normal maps are linear tangent-space data, not gamma-encoded colour.OBJ dedup by file and colour space — OxidANT’s
obj/flat.rs(Slots) keys on the resolved file’s canonical path and the sRGB flag, so two materials naming one file through different.mtlspellings (tex.pngvs./tex.png) share a slot, and a file used as colour and as a normal map gets two. A file that cannot be read gets no slot (-1).A corrupt image gets no slot — OxidANT drops a slot whose image does not decode and renumbers the materials’ later ids (
flat::renumber_slots;GltfParseUnit.ACorruptImageGetsNoSlotAndLaterIdsAreRenumbered).A failed upload still occupies its slot — when
Texture::createFromLevelsor its batch’s submit fails, or stb read no image,GltfLoader::uploadParsed’saddTextureOrDefaultcall substitutes the default texture instead of skipping the slot, so every latertextureIDkeeps its meaning.Sampler dedup by mip level and glTF sampler description —
Model::addSampler(scene/Model.cpp) keys on aSamplerKey{ mipLevel, GltfSamplerDesc }viafindSampler(vulkan_base/SamplerBuilder.cpp): N textures share onevk::Sampleronly when both their mip count and their wrap/filter settings match.Flattening into the global array —
assignTextureOffsets(scene/ObjectDescription.ixx) stamps each mesh’stexture_offsetwith its model’s running offset into the flattened array, advancing by that model’s texture count once its meshes are done;planFlattenedTextureSlots(same module) is the mirror image that builds the array, in model order, capped atMAX_TEXTURE_COUNTand padded with slot 0 past the cap. All five entry points (rasterizer,deferred,shadow_map,path_tracing,raytrace.rchit) compute and clamptextureIdthe same way,clamp(int(obj.texture_offset) + material.textureID, 0, MAX_TEXTURE_COUNT - 1), so a model that pushes the total past budget samples a wrong (but in-bounds) slot instead of reading out of the descriptor array.
Both readers fill Vertex::texture_coords1, the second UV set (vertex
attribute location 5): the glTF loader reads TEXCOORD_1 and copies
TEXCOORD_0 where a primitive has none;
the OBJ reader always copies. When a glTF primitive has no TANGENT,
the loader builds the frame from the UV set its normal texture samples.
Both readers also emit per-vertex colours (glTF COLOR_0; OBJ v x y z r g b)
and fill missing normals, differently: the glTF reader gives a primitive
without a NORMAL accessor one vertex per triangle corner with its face’s
normal; the OBJ reader never shares a corner without a vn between faces, so
each such corner takes its own face’s flat normal (a file with vn on only
some faces keeps those).
map_Kd texture path resolution#
OxidANT’s OBJ reader resolves every texture an .mtl names this way, for both
renderers:
Normalise \ to / in the map_Kd value; resolve the result relative to
the directory containing the .mtl (tinyobjloader’s rule, and the format’s);
if that file does not exist, retry under a textures/ subdirectory of the
same directory; if that misses too, or either path leaves the OBJ’s folder,
warn and draw the material untextured (slot -1).
The
\-to-/normalisation deliberately deviates from “as written in the.mtl”: a Windows-authored relative path (textures\wood.png) must still resolve on a platform where\is just another filename character.Relative to the
.mtlfirst is what the OBJ/MTL format specifies. Thetextures/retry exists because every textured OBJ inResources/Models(VikingRoom, and the AssetANT scenescrytek-sponza,PillumandSulo/WolfStahl) keeps its textures in atextures/sibling directory and names them by bare filename, not by the format’s convention.Every path, the
mtllibnames included, is confined like a glTF’s (files::confined_path, owner 2026-11-24): no drive or scheme, no root, no UNC name, no..out of the OBJ’s folder, regular files only.A path that resolves to neither candidate leaves the material untextured instead of failing the whole load, with a warning naming the file: the only signal a wrong or missing texture leaves.
Where: obj::texture_source (crates/assets/src/obj/paths.rs in OxidANT),
which the engine’s flat model, the in-memory GLB and obj2gltf’s
convert_file all call. convert_file emits the path relative to the OBJ’s
folder as the glTF uri and copies the texture to the same place beside the
glTF, never outside its folder.
Invariants worth preserving#
parseCpuleaves the flatgetVertices()/getIndices()/getMaterialIndices()/getMaterials()exactly as before the split: the CPU parse tests key on them, and both upload paths read from them.Every
MeshRangemust tile the flat arrays contiguously (no gap/overlap), and every index in a range must stay inside that range’s own vertex block, or the-vertexBasere-base (rebaseIndices) corrupts the mesh. TheObjParseUnit.EachUsemtlRunIsOneMeshRange/MultiPrimitive…RecordsPerPrimitiveMeshRangesparse tests assert this at parse level, andTest/commit/VulkanEngine/meshRangeSliceSuite.cppunit-testsrebaseIndicesandmeshRangeFitsdirectly.Each mesh currently shares the full
materialsarray (itsmaterialIndexholds the original indices). Trimming to a per-mesh material subset would be an optional optimisation, which no backlog entry tracks; it would go intoaddMeshesForRangesInPlaceinscene/ModelAssembly.ixx.