* Optimize Shader LineDictionary with Variable-Length 3-Streams
This commit completely reorganizes the string dictionary compression
pipeline used by compiled Material Text Chunks and improves matinfo
dictionary output.
1. Multi-Base Variable-Length Scaling:
We replaced the static 16-bit indices overhead with a
bounded payload. Now, indices scale dynamically:
- 0 to 239 evaluate in 1 byte.
- 240 to 3584 leverage 0xF0-0xFD escapes evaluating in 2 bytes.
- 3584+ are locked behind a 0xFF marker to 3 bytes.
This natively eradicated the massive monolithic lengths and zero-padding
issues previously dominating shader packages.
2. Variable-Length 3-Stream Decoding:
To solve the Zstandard/Zlib entropy fragmentation that conventionally
plagues interleaved variable byte lengths (which previously inflated
our `filament.aar` boundary constraint by +2KB), we segregated the encoded
payloads.
By grouping high-entropy string boundaries into a `Base Stream`
and isolating offset digits inside an `Extension Stream`,
predictive LZ77 ZIP sliding-windows perfectly map
over both arrays independently without disruption.
3. Optimize Numeric Stream using LEB128
Prior to this change, numerical suffixes split from shader
variables (e.g., `param_1024` -> `param_` + `1024`) were fed back
into the localized String Dictionary. Because high-frequency numbers were
assigned disjointed localized IDs per shader variant, LZ77
failed to cross-reference their repetitive structures across
shipped `.aar` archives, fracturing compression sequences.
This patch implements a unified 3-Stream topology. It
extracts numerical primitives (< 32768) away from the baseline
String Dictionary, writing them into an isolated, contiguous
LEB128 array.
By using a dedicated `[254]` Escape Token within the primary stream, numerical
variables maintain exact 1-byte (`< 128`) or 2-byte (`>= 128`)
geometric layouts across all permutations.
The resulting deterministic alignment guarantees that Zlib sliding windows
can deduplicate highly repetitive variables across the
entire application binary block.
4. We use the ShaderStage information to create distinct index ranges, which
further help use 1-byte indices.
Verification Metrics:
`filament-android.aar`: -7,938 B
`gltfio-android.aar`: -290,939 B
`libfilament.a`: -18,464 B
* Optimize shader dictionary by decoding '_' for numeric literals
Most numbers extracted from the shader text are preceded by an
underscore (e.g., from `_`, `hp_copy_`), which previously caused
standalone `_` strings to heavily pollute the LineDictionary.
This change removes the standalone `_` from the dictionary index:
- `MaterialChunk` rehydrates the `_` prefix when decoding these numeric
literals.
This frees up dictionary indices, yielding massive byte savings across
uncompressed binaries (e.g., -28.4 KB for volume_masked.filamat).
* Optimize ShaderMinifier to strip explicit spacing
Spirv-cross outputs GLSL with explicit spacing around generic
operators (e.g., ` = `, `, `, ` ) * `). This padding consumes a
significant amount of uncompressed bytes across large ubershaders.
By applying targeted string replacements at the end of the `ShaderMinifier`
pass, we strip this extraneous padding down to its raw tokens
(e.g., `a=b`, `a,b`, `a*b`).
This optimization preserves isolating spaces where valuable, ensuring
line-dictionary tokens (such as raw `=` or `,`) remain deduplicated
instead of fusing into unpredictable variables.
Impact:
This saves roughly ~9.1 KB in `libfilament.a` and ~3.2 KB in
`volume_masked.filamat` uncompressed, with proportional gains across
the downstream LZ4 compressed archives.
* Fix out-of-bounds string read by verifying null-terminator existence
during extraction.
* Fix heap buffer overflow by validating dictionary string lengths
against target shader buffers before copying.
* Fix out-of-bounds array reads by validating chunk-provided lookup
indices against parsed dictionary sizes.
* Fix integer wrapping exploits by replacing pointer addition with
offset subtraction during chunk size verifications.
Add unit tests for these vulerabilities.
- Introduce `shiftRadius` to allow positional tolerances by searching
a local neighborhood, absorbing sub-pixel shifts and MSAA quirks.
- Introduce `blurRadius` to apply local area averaging, ignoring
high-frequency noise like hardware dithering.
- Enhance `ImageDiffResult` to include an `averageError` array and
a 10-bin `errorHistogram` for actionable failure debugging.
- Update Android JNI bindings (`ImageDiff.java` and `ImageDiff.cpp`)
to propagate the new error distribution statistics to Java callers.
- Update C++ unit tests to cover the new heuristic options.
- Document the new parameters and JSON result format in README.md.
- Add synthetic image generation tests in `tools/diffimg/tests/` to
validate the CLI tool's handling of spatial shifts and dithering.
libfilament (including libutils and libmath) are 100% std::string
free.
std::string is pulled in the .so (on android) through libc++ for
exception handling, even if we're not using them. There is not much
we can do here, but at least, it's not because of us!
utils::ostream still references it but only as an inline function,
so if the inline is not called, std::string won't be pulled in.
It's also referenced from Path.cpp, but that's not included in
libfilament.
This made it nearly impossible to find the actual error. Now, we
output only the error from the compiler + the material name, variant
and shader stage all in one line.
On certain linux, macOS environment, there is already a system
getopt. This often creates conflict when compiling filament.
Here we alias utils::getopt to either the system getopt (if
present) or third_party/getopt.
Fixes#7551
This commit addresses a critical security vulnerability (OOB write) and
several stability issues in the Radiance HDR parser.
Primary Fix:
* Fixed a heap buffer overflow in the RLE decoding loop (Issue #9748).
The decoder previously failed to verify if a run-length chunk exceeded
the remaining space in the scanline buffer. Added strict bounds checking
(`num_bytes + run_length > width`) before executing `memset` or
`mStream.read` to prevent arbitrary memory corruption.
Additional Security & Stability Improvements:
* Prevented an infinite loop (DoS) in header parsing. Replaced the
`do { ... } while(true);` loop with proper stream state checking
(`while (mStream.getline(...))`) to handle unexpected EOFs gracefully.
* Mitigated integer overflow and Out-Of-Memory (OOM) vulnerabilities by
enforcing maximum sane dimensions (`MAX_IMAGE_DIMENSION` and
`MAX_IMAGE_PIXELS`). This prevents catastrophic memory allocations
triggered by maliciously crafted width/height values.
* Initialized local variables and buffers (`buf`, `gamma`, `exposure`) to
prevent undefined behavior and parsing of stack garbage upon stream read
failures.
Fixes#9748
* utils: add LRU cache to RefCountedMap
This change introduces a new data structure LruCache and uses it in
RefCountedMap to keep a fixed number of cache entries alive after their
reference count has dropped to zero in the main map.
* utils: address LRU cache comments
- refactoring/clecanup to make some changes easier
- VSM mipmap generation was mistakenly disable when blur radius was 0
- analytic variance was disabled because the math only worked for VSM. Fixed the math.
- better handling of large blurs when using fp32
- implement EVSM equivalent of receiver plane normal bias
- use correct EVSM clearing color
- mipmapping with point lights works much better (no seams)
- min variance is computed automatically
- custom high precision mipmaping shader for VSM
The VSM variant bit was overloaded, it meant two different things
depending on the DEP bit (depth).
For standard variants (DEP = 0), it decides the type of the shadow
sampler used (PCF or 2D).
For depth variants (DEP = 1), it decides what is written during the
shadow pass (nothing, i.e. depth only, or EVSM depth moments).
We now clearly separate the two bits throughout the code.
This change should be purely source-cosmetic, there shouldn't be any
behavior changes.
Co-authored-by: Powei Feng <powei@google.com>
The previous code used the max of the texel's width or height footprint
in world space to compute the offset; this could both overestimate or
underestimate the bias causing some peter panning or acne.
The new code replaces a sqrt with a dot, but is otherwise similar.
* fixbug:"debug error, reason: The material 'Material_MR' has not been compiled to include the required GLSL or SPIR-V chunks for the vertex shader (variant=5, filtered=5)",Because the member variable mVariantFilter is not initialized, random values will appear on Windows 10 or others platform, which eventually causes some variants to be filtered out by this mVariantFilter.
* fix:Fix morph target loading for accessors without buffer_view
Morph targets were not working because ResourceLoader skipped all
accessors without buffer_view. For morph targets, the data can be
accessed directly via cgltf_accessor_unpack_floats().
This fix properly unpacks and uploads morph target vertex data to the
GPU, enabling blendshapes and facial deformation to work correctly.
Steps to Reproduce
1、In Unity (2022.3.11): Create a Prefab with Blend Shapes (Morph Targets) and an Animator to control them (e.g., an animation clip that makes the eyes squint).
2、Export: Use the UnityGLTF tool to export the model as a .glb file (including the Animator and Morph Target tracks).
3、In Filament: Load and play the animation.
4、Result: The skeletal animation (bone-based) may play, but the Morph Target effect (squinting) is missing or static.
- This is an initial implementation, not yet complete
- Goal of this sample is to run a series of offscreen single
frame captures, and capmre the result against a set of golden
images
- Uses existing scene description in libs/viewer and
test/renderdiff
- Uses existing image difference description/implementation in
libs/imagediff
- Add imagediff API to filament-utils-android
Enables the multiview implementation as the default for stereoscopic
rendering. Now all STE variants use the multiview path.
This change removes all CMake configurations, build scripts, and C++
preprocessors previously used for selecting stereoscopic rendering
modes. And, all shaders are now compiled for multiview.
The instanced rendering implementation is going to be removed. Note that
this commit only handles switching the default. The actual removal of
instanced rendering code will be submitted as a separate follow-up
commit.
BUGS=[470198472]
A preliminary commit to add a websocket server to the DebugServer.
This will enable us to transfer large data (like images) across
to the frontend.
This is part of the work to enable viewing intermediate
render buffers in fgviewer.
Instead of computing the fog "inline", in the forward pass, we can
instead compute it as post-process pass that is applied with a
simple fullscreen quad blending. On tilers, the operation entirely
stays in the tile, on desktop GPU it is a blending operation.
This works only for opaque materials.
The benefit is that fog will become immune to overdraw, and the forward
pass shader will be simplified, hopefully leading to less register
pressure. Overall performance should be improved.
Another benefit is that it will allow us to free the "fog" texture
slot from all opaque materials.
Transparent materials are unchanged.
This feature is currently DISABLED, and still work in progress; but it
should be mostly functional.
To test it:
```
env material.enable_fog_as_postprocess=true ./out/samples/gltf_viewer
```
This change refactor the fog code, but shouldn't have any impact on the
current behavior.
- Add new library to do tiff import/export. This library is
different from imageio in that it doesn't pull in additional
3p libraries. This reduces binary size and reduces
complexity in maintaining the android build (which depends
on libs/viewer).
- The encode() code has been moved from libs/viewer to
libs/imageio-lite
- encode/decode only handles the simplest case of uncompressed
rgba.
* engine: add program cache
This is another chunky change.
The core of this change is to cache programs in MaterialCache according to a
"specialization" (ProgramSpecialization) which is defined as the program cache
ID (the same key used for the OpenGL binary blob cache), the variant, and the
set of spec constants.
As part of this change, a lot of the implementation details of shader
compilation were refactored from Material to MaterialDefinition. The resulting
flow is a lot cleaner and easier to reason about, since shader compilation is
now a pure function of the MaterialDefinition + ProgramSpecialization.
Since the global cache program lookups might take a bit of time to compute
hashes, etc, I left the set of cached programs in Material as well, which kind
of acts like an L1 cache. The effect is that prepareProgram() and getProgram()
should be no slower than HEAD, even with the more complex caching requirements.
I'm planning on writing a document about this (and all changes up until this
point), but I'm being asked to work on higher priority things and I wanted to
have this PR out for review in the meantime so it doesn't bitrot.
* engine: fix unit tests
* engine: fix spec constants intern pool memory leak
* engine: address program cache comments
* engine: address more program cache comments
* engine: matdbg support for program cache
* engine: reinstate descriptorLayout calls
* engine: address bitrot
* engine: add feature flag to disable program cache
* engine: use material CRC32 for program cache
The "cache ID" of a material is supposed to uniquely identify a shader program
and all its variants. This is true to a certain extent, but does not account for
the code generation that happens at runtime. Two materials may have "identical"
shader programs, but due to each material's differing unique metadata, the final
compiled programs may end up very different. Unfortunately, this means we cannot
rely on the "cache ID" alone to determine a shader program's reusability.
Ideally, we should hash this "cache ID" with the exact set of changes to each
shader program so that we could reuse programs across materials. Instead, as a
stopgap solution, use the material's CRC32 instead.
* engine: fix double-free in program cache
* engine: address comments
* engine: assert_invariant empty material cache
- Extended Settings to include properties for Camera, Animation, Lights,
and Render options.
- Moved camera options from Viewer options to Camera options
- Implemented generic JSON parsing for these new settings in Settings.cpp.
- Updated AutomationEngine to apply these settings, including dynamic
creation of lights.
- Fixed a JSON parsing bug in AutomationSpec that failed on nested objects.
- Updated gltf_viewer to use the new settings and correctly initialize
AutomationEngine context.
- Add test for new json changes
- Add README to libs/viewer
- Link libs/viewer/README.md to official doc
- Remove unused libs/viewer/schemas
- Updated remote web assets (because the viewer/settings json needs to
match)
PerformanceHint manager needs a java thread during initialization,
so we need to attach a jvm to the thread that's going to be used.
That thread is the filament backend thread, not necessarily the thread
the platform is created on.
So we make sure to do that from the backend thread.
FIXES=[427945768]
- Add plumbing to add more information about rendertargets
(including discard flags and pass id) to the fgviewer pass
struct.
- Add UI to display information about a selected pass
- Highlight a selected resource or pass
The new tone mapper, dubbed "GT7" in the code, is based on
the Gran Turismo 7 tone mapper, as described in the SIGGRAPH
2025 presentation called "Driving Toward Reality: Physically
Based Tone Mapping and Perceptual Fidelity in Gran Turismo 7".
This tone mapper exhibits fewer hue skews than the other tone
mappers, at the exception of PBR Neutral. The GT7 tone mapper
is however better at preserving the perception of high
dynamic range.
The tone mapper, as implemented, targets an SDR paper white
of 250 nits, using 100 cd/m^2 as the reference luminance (for
values of 1.0 in the linear HDR framebuffer). This can result
in an overall darker image compared to the other tone mappers
but this can be controlled through camera settings, post-
processing exposure, or lighting intensity.
The GT7 tone mapper also allows to target HDR output, and
could be made customizable via APIs if desired. The current
implementation offers a fixed aesthetic solution.
- Add documentation for specgen along with proper math rendering
- Adjust the heading size, capitalization of various READMEs.
- Add backend test README to the doc
- Rename the CI related tests to have prefix "CI:"
- Pick a default view when database is filled.
- Fix d3, d3-graphviz depdency.
- reduce the size into a smaller table (to avoid scrolling)
- slant the pass items to allow smaller cells for the table.
- make subresource rendering the same as regular resource
rendering with a color hint.
- Use color-only to indicate resource/pass interaction (read,
write, read-write, no-access)
- add tooltip to indicate resource action
* feat(engine): Add automatic frame skipping to manage CPU/GPU latency
Introduces a new feature, disabled by default, that allows the engine to automatically skip frames when the CPU gets too far ahead of the display's refresh rate. This helps to reduce overall latency by preventing a backlog of frames from building up in the driver queue.
The feature can be enabled with the "engine.skip_frame_when_cpu_ahead_of_display" property.
To implement this, the compositor timing mechanism has been refactored. Instead of reporting an absolute `expectedPresentTime`, the backend now provides an `expectedPresentLatency` relative to vsync. This is more robust against synchronization issues with platform callbacks (like Android's Choreographer), as the latency is generally a constant value.
BUGS=[474599530]