Compare commits

..
Author SHA1 Message Date
Doris Wu bd073119d2 Revert "buffer update opt: Add a flag to guard the feature (#9322)"
This reverts commit 49c4a5d62c.
2025-10-15 23:41:03 +08:00
Doris Wu 06c4ed4e6b fix: material sandbox scene crashes during shutdown (#9325) 2025-10-15 15:34:50 +00:00
Doris Wu 49c4a5d62c buffer update opt: Add a flag to guard the feature (#9322) 2025-10-15 23:14:53 +08:00
Doris Wu c757cc3629 buffer update opt: Introduce BufferAllocator and its tests (#9304)
* Introduce AllocationStrategy and its tests

* feedback

* feedback

* Add stress test

* Fix the build

* Minor fix

* Rename the class

* Rename

* Make const
2025-10-15 06:25:42 +00:00
rafadevai dbdf8f672b GL: Check if GL_EXT_texture_filter_anisotropic in supported in GLES (#9317)
In GLES the anisotropic filtering featuring is always
disabled even in the cases where is supported by the hardware
because the check for the extension is missing.
2025-10-14 23:03:25 -07:00
Filament Bot 54bd888374 [automated] Updating /docs due to commit b7dea28
Full commit hash is b7dea28cc5

DOCS_ALLOW_DIRECT_EDITS
2025-10-14 21:28:53 +00:00
Benjamin Doherty b7dea28cc5 Release Filament 1.66.0 2025-10-14 14:25:20 -07:00
Benjamin Doherty 9aa8e7780b Fix NEW_RELEASE_NOTES 2025-10-14 14:24:52 -07:00
Ben Doherty 271e639abe Revert "Make check-headers test use c++20" (#9316) 2025-10-14 14:12:34 -07:00
Ben Doherty 082a79eebc Fix, revert to C++17 string_view constructor (#9315) 2025-10-13 15:01:40 -07:00
Ben Doherty 7a10c09954 Fix, Abseil compilation error with StaticString (#9314) 2025-10-13 15:01:39 -07:00
Filament Bot 3139a37cc7 [automated] Updating /docs due to commit f8e8c27
Full commit hash is f8e8c27c04

DOCS_ALLOW_DIRECT_EDITS
2025-10-13 19:56:08 +00:00
Mathias AgopianandPowei Feng f8e8c27c04 Add a Renderer API to force skipping frames (#9313)
* Add a Renderer API to force skipping frames

Renderer::skipNextFrames(size_t) can be used to force filament to
pretend the next N frames must be skipped. This is mostly useful for
debugging.

* Add DebugOptions to Settings

We still need to move the "Debug" features of gltf_viewer to this,
but this give us a framework to do it. 
Currently there is one debug option that allows to set a number of
frames to skip.

ViewerGui propose a button to skip 10 frames using this framework

* Update libs/viewer/src/Settings.cpp

Co-authored-by: Powei Feng <powei@google.com>

* Update libs/viewer/src/Settings.cpp

Co-authored-by: Powei Feng <powei@google.com>

---------

Co-authored-by: Powei Feng <powei@google.com>
2025-10-13 12:52:17 -07:00
Mathias Agopian c79d695ffb fix wasm build. (#9312)
The new AsyncJobQueue can't work with wasm, which doesn't support 
threads.
2025-10-13 12:18:28 -07:00
David Neto ad6f6cf149 filamat: remove call to Glslang's SPIR-V remapper (#9310)
The Glslang SPIR-V remapper was removed, and replaced by the CanonicalizeIds
pass in spirv-opt.  See https://github.com/KhronosGroup/SPIRV-Tools/pull/6174

Filament's GLSL post-optimization algorithm already runs CanonicalizeIds.

Bug: b:450891564
2025-10-13 09:46:07 -07:00
Mathias Agopian 8506e94f10 Improvements to FrameInfo (#9293)
* fix a possible deadlock in AsyncJobQueue

drainAndExit() could get stuck because it waited for the job
queue to be empty, but that was not signaled.
in fact, drainAndExit() didn't need to do that.

* Improvements to FrameInfo 

- return the GPU Complete timestamp
- return the app VSYNC timestamp
- works TimerQueries are not supported

The VSYNC time is just a convenience as it is the same value
provided by the application during Renderer::beginFrame() or via
Renderer::setVsyncTime().
2025-10-10 21:40:28 +00:00
Mathias Agopian 5db8e0b9ab fix a regression in FMaterial::setConstant() (#9308)
it used to return false when setting the same value for the constant,
which other code used to invalidate the material or not. but it
was recently changed to always return true on success.

this reestablish the previous behavior.
2025-10-10 12:43:32 -07:00
Powei Feng da55574b32 webgpu: refactor blitter to use struct as keys (#9300)
Using struct as keys simplifies the parameter definitions of the
relevant pipeline, pipelinelayout, shader module methods. This
enables adding or removing fields without adding major changes
to method definitions.

Using utils::hash::MurmurHashFn also aligns with the style of
the rest of filament.
2025-10-10 17:31:47 +00:00
yein 736fed00b3 handle StatusCode::UNSUPPORTED in << operator (#9307) 2025-10-10 00:06:57 +00:00
Evan Mezeske 9b200fc33a Some trivial changes to compile under most recent MSVC as a CMake sub-project (#9275)
* Add a workaround for Filament's breaking change to add_subdirectory for Abseil, see: https://github.com/google/filament/issues/8611

* Fix #pragma warning syntax for MSVC

* Only search for an external Abseil dependency if a new option FILAMENT_USE_EXTERNAL_ABSL is set
2025-10-09 23:06:18 +00:00
yein fa436f1d12 Make JsonishParser use utils::Status (#9302)
* Make JsonishParser use utils::Status

- add unsupported error in utils::Status
- add invalid case in the test

* return a pair of Status and string in resolveEscapes;
use initializer list for JsonishString and move that to the header.
2025-10-09 15:44:03 -07:00
Powei Feng 837b2715a0 Update MATERIAL_VERSION to 66 2025-10-09 11:29:16 -07:00
Jordan Rupprecht 1a04312986 Add missing #include <ios> (#9305)
This is needed to instantiate `std::streampos`. It currently relies on transitive header inclusion to get that, which is going away for libc++ in https://github.com/llvm/llvm-project/commit/ebcf1bf2ecba6b25ece3c2bbddb4485e76189387.
2025-10-09 10:24:00 -07:00
Filament Bot a89711b006 [automated] Updating /docs due to commit 6d061b5
Full commit hash is 6d061b5d01

DOCS_ALLOW_DIRECT_EDITS
2025-10-08 20:04:04 +00:00
Powei Feng 6d061b5d01 renderdiff: add two params to local_test.sh (#9301)
- --no_rebuild will skip building the gltf_viewer again
 - --num_threads will limit the number of threads used in running
   the rendering test.

Both of these options are meant for debugging locally.
2025-10-08 13:01:09 -07:00
Powei Feng 53ddb3dd1c renderdiff: [viewer] enable frontend to be used with runID (#9277) 2025-10-08 18:36:30 +00:00
Powei Feng c7b0a7f441 webgpu: fix queue submission and fence (#9299)
- Add WebGPUQeuueManager to manage queue submissions
 - The manager will keep a "last status" field that will track
   the status of the last submission.
 - Any created HwFence will be associated with a status object.
 - The object updates in a callback that indicates that the
   submitted workfload has been completed.
2025-10-08 17:30:19 +00:00
Filament Bot d7b44a2585 [automated] Updating /docs due to commit caf886d
Full commit hash is caf886df6b

DOCS_ALLOW_DIRECT_EDITS
2025-10-07 22:58:22 +00:00
Powei Feng caf886df6b Release Filament 1.65.4 2025-10-07 15:54:13 -07:00
Sungun Park 287984dd7f gl: Enable shared contexts for Windows (#9298)
This change addresses a platform-specific issue on Windows where shared
OpenGL contexts must be created on the same thread as the primary
context.

To resolve this, we now pre-create a pool of shared contexts when the
driver is initialized. These contexts are then distributed to other
threads as needed, ensuring shared context creation requirement on
Windows. This allows us to be able to use THREAD_POOL mode for shader
compiler service on Windows. So Windows build uses THREAD_POOL mode
instead of ASYNCHRONOUS mode as of this change.

This change also refactors the shader compiler service to catch and
report errors in the same thread where the program compilation and
linking actually performed as it's the correct way to use shared
contexts. Otherwise it may crashes.
2025-10-07 19:30:42 +00:00
Powei Feng 3294bb64a5 Revert "Make matc workarounds default to NONE again" (#9295)
This reverts commit d11a6b4467.

Breakage detailed in following bug

BUGS=449740720
2025-10-07 18:50:34 +00:00
yeinandPowei Feng f52476a323 Use utils::Status in MaterialParser (#9285)
* Use utils::Status in MaterialParser

* Use utils::sstream instead of std::stringstream

* Remove remaining std::cerr and dep; update MaterialParser::reflectParameters

* make error message in utils::Status more generic

---------

Co-authored-by: Powei Feng <powei@google.com>
2025-10-07 11:27:11 -07:00
Powei Feng c839915a00 Add missing optional include for MaterialParser (#9296) 2025-10-06 22:50:02 -07:00
Mathias Agopian 2deafc6b81 fix matc -E (preprocessor) option (#9292)
this option was ignored and treated as -O0.
2025-10-03 20:15:05 -07:00
Powei Feng fdec0f79a2 renderdiff: [viewer] fix magnifier (#9290)
- Fix the magnifier positioning for both compare and standalone
   mode. Simplified a lot of the logic and streamlined passing
   of states between components.
- Slight css adjustments
2025-10-03 21:44:53 +00:00
Mathias Agopian 31d66002a9 optional per-channel depth clear (#9287)
- increase the number of channels from 4 to 8
- new api on View to enable per-channel depth clear
FIXES=[447648764]
2025-10-03 14:25:02 -07:00
Mathias Agopian f2ed382cf1 New ImmutableCString string class (#9291)
ImmutableCString is a string class similar to CString except it's
immutable. ImmutableCString occupies 16 bytes instead of 8 for CString.

However, ImmutableCString is able to avoid memory allocation when
constructed from a string literal, and in that way it us similar
to StaticString.

ImmutableCString can be auto converted from StaticString.

The backend tag tracking is updated to use ImmutableCString and
the FrameGraph resource manager us updated to use StaticString.

Together these changes significantly cut down heap allocations due to
internal tagging.


We also add optional tracking to {Immutable}CString.
2025-10-03 14:23:36 -07:00
yein a4746eab0c Minor changes in utils::Status (#9288)
* Minor changes in utils::Status

- << operator doesn't have to be friend
- simplify getErrorMessage to not use strlen internally

* Replace std::ostream to utils::io::ostream
2025-10-03 12:53:46 -07:00
Filament Bot 0b011fae7d [automated] Updating /docs due to commit a6c9922
Full commit hash is a6c9922d33

DOCS_ALLOW_DIRECT_EDITS
2025-10-03 18:40:22 +00:00
Eliza a6c9922d33 internal: fix some editor indentation rules (#9289)
* internal: fix some editor indentation rules

* internal: update CODE_STYLE.md
2025-10-03 11:38:01 -07:00
Eliza 7fe1ee3fd5 utils: RefCountedInternPool/RefCountedMap (#9284)
* utils: RefCountedInternPool/RefCountedMap

First, introduce RefCountedInternPool, a reference counted intern pool of
Slice<const T>. Just acquire() a slice that you want and you're guaranteed to
get exactly one canonical value-equal Slice<const T> back.

Additionally, introduce the concept of NullValue to RefCountedMap. A NullValue
defines what should be considered an uninitialized value; by default, it's the
default value of that type (0 for ints, nullptr for pointers, etc). This allows
us to lazily-initialize values in the map. A client can acquire() a bunch of
different resources which will be initialized only when get(factory) is called.
If a client attempts to get() a value without specifying a factory, and the
value is not initialized (i.e. equal to NullValue{}()), RefCountedMap will
panic.

* utils: add unit tests for ref-counted collections

* utils: remove C++20 features, fix memory issue

* utils: remove RefCounted from InternPool
2025-10-03 11:21:02 -07:00
Eliza 075726db8b engine: change spec constants to simple list (#9283)
* engine: change spec constants to simple list

For a shader program cache to be keyed on the set of spec constants that a
program has set, we need to know full exact list of constants, including their
default values. If we're going to always hold a list of all constants all the
time, then we may as well store them as a simple list where each index is the ID
number of the spec constant.

As part of this change, we now write the default values of spec constants into
the material file metadata.

* fix indent

* engine: fix sRGB swapchain emulation
2025-10-02 23:48:11 +00:00
Mathias Agopian b22ff3bebb fix exceptions (#9281) 2025-10-02 16:22:01 -07:00
Sungun Park bc794bbf7b Fix public headers check on github (#9286) 2025-10-01 23:36:26 -07:00
Sungun Park 9c29c3d192 Fix memory leaks for xlib (#9282)
This change frees memory returned by `glXGetFBConfigs` and
`glXChooseFBConfig` using `XFree`.
2025-10-01 23:09:55 +00:00
Eliza 8e5dabfa8e utils: split Slice into mutable and constant types (#9276)
* slice: fix memory semantics

* slice: prefer passing slice by value

This lets us do nice things like coercing Slice<T> to Slice<const T>, etc.

* slice: fix unit tests

* slice: fix copy/assignment, hash function

Don't attempt to define a copy constructor/assignment operator which would
convert a constant type to a mutable type.

Additionally, fix the hash function such that we're hashing U instead of const
U.
2025-10-01 22:40:50 +00:00
Mathias Agopian e974989a95 new utility AsyncJobQueue (#9278)
* new utility AsyncJobQueue

this is a very simple job queue, it spawns a thread and runs the jobs
pushed to the queue in sequence.

* use AsyncJobQueue in OpenGLTimerQuery
2025-10-01 14:54:34 -07:00
yein 057ce2ea4b Introduce utils::Status (#9279)
* Introduce utils::Status

* Replace std::string with utils::CString in utils::Status

* Update unit tests
2025-10-01 14:53:51 -07:00
Martin Valgur 2e920f2780 Fix an invalid USE_EXTERNAL_GLES3 define (#9280)
Should be FILAMENT_USE_EXTERNAL_GLES3 to match its usage in code.
2025-10-01 10:59:55 -07:00
Mathias Agopian b41e6dfd5c fix several issues CircularQueue (#9271)
- pop_back() didn't call the object's dtor
- added a dtor so objects can't be leaked
- made it moveable but not copiable
- added unit tests
2025-09-30 16:06:58 -07:00
Filament Bot 8413c84284 [automated] Updating /docs due to commit 10e63bf
Full commit hash is 10e63bf2cf

DOCS_ALLOW_DIRECT_EDITS
2025-09-30 21:44:09 +00:00
Powei Feng 10e63bf2cf renderdiff: [viewer] add Run ID as a way to pull artifacts (#9272)
The viewer supports pulling artifacts based on PR number, and now
we support providing Run ID as an alternative to identify the
renderdiff run on Github CI.
2025-09-30 21:32:36 +00:00
Filament Bot 73ba8fc753 [automated] Updating /docs due to commit f07a44e
Full commit hash is f07a44eb15

DOCS_ALLOW_DIRECT_EDITS
2025-09-30 18:53:20 +00:00
Sungun Park f07a44eb15 Release Filament 1.65.3 2025-09-30 18:50:39 +00:00
Sungun Park 3dc3c78901 Support C++17 for RefCountedMap (#9274)
Some of our users are sticking to C++17 for a while.
2025-09-30 11:45:51 -07:00
Sungun Park db099033e8 Fix compile issues (#9273) 2025-09-30 10:48:35 -07:00
lyriccoder 14a460961c Signal handler calls non-async-safe function (std::cout) (#9227)
In the current implementation, the function std::cout is used inside a                                                                                                                                                                signal handler. This is problematic because std::cout is not
async-signal-safe. According to POSIX standards, only a small set of
functions are guaranteed to be safe when called from signal handlers,
and std::cout is not one of them. Using non-async-signal-safe functions
inside signal handlers leads to undefined behavior and can cause
crashes, deadlocks, or other unpredictable issues.

By making these changes, we avoid undefined behavior and ensure the
program can handle signals safely.
2025-09-30 00:23:09 -07:00
Mathias AgopianandPowei Feng b467690ac7 new fenceWait() API in the backend (#9267)
* new fenceWait() API in the backend

* correct implementation of fenceWait() for GL and WebGPU

- fenceWait() now works correctly if called before the fence is
  created on the backend side

- the STL's condition wait_for() is actually a wait_until, which
  means we have to make sure now() + timeout doesn't overflow.

- also we make sure to keep a reference to the fence internal state
  while we wait so that we're safe if it's destroyed during that time.

* Implement fenceWait() properly on vulkan


On Vulkan, unfortunately, the implementation is complicated, as we
need three levels of "wait".

First we need to wait using a mutex/condition that the shared fence
is created (this is because on vulkan, all HwFence share the same
"state" associated to the same command buffer).

Once we have that, we need to wait for the VkFence to be submitted,
this is done using a read/write lock and condition variable. The
read/write lock is not needed at this stage, but in the next.

Once the fence is submitted, we can now wait using vkWaitForFences,
however, external host synchronization is needed. Multiple 
vkWaitForFences can be issued together (and use the read lock), but
must be mutually exclusive with vkResetFences and vkQueueSubmit.
By construction, we know that this can't happen during vkQueueSubmit
due to the "2nd level" of wait, however we need to prevent
simultaneous calls to  vkResetFences, this is done using a write lock.

By construction, we're guaranteed that when vkResetFences is called,
the fence has signaled, we just need to wait for all vkWaitForFences to
return.

A side effect of this change is that fenceGetStatus() has a better
implementation, since it's just a wait with timeout of 0.

* Update filament/backend/src/vulkan/VulkanDriver.cpp

Co-authored-by: Powei Feng <powei@google.com>

---------

Co-authored-by: Powei Feng <powei@google.com>
2025-09-29 13:09:43 -07:00
Mathias Agopian b02bb0eaf6 assert sampler function only when it's not NONE.
FIXES=[437172017]
2025-09-29 13:08:54 -07:00
Sungun Park 436dffcbb3 Fix a crash for MaterialCache
The parser object was accessed to generate a key after being passed to
the lambda using std::move(). This led to a crash on certain platforms
(at least on Windows).

This change fixes it by creating key first before moving the parser
object into the lambda.
2025-09-27 00:03:32 -07:00
Mathias Agopian 95935b38bc enable timer queries on Mali drivers known to be good
FIXES=[273759031]
2025-09-27 00:02:09 -07:00
Powei Feng 0fa3de5ac7 renderdiff: add magnification glass of rendering (#9265)
- Show magnifying glass when diffing between two images
- Add checkbox to enable or disable feature
2025-09-27 00:19:26 +00:00
Powei Feng d8e8aafad7 vk: fix VulkanPlatform CString usage (#9266) (#9260)
Since #9259, CString in VulkanPlatform fall into the literal
constructor path. But we really want the null-terminated
(char const*) path.  So we cast the strings to (char const*)
to enforce null-teriminated behavior.

RDIFF_BRANCH=pf/renderdiff-add-tolerance
2025-09-26 23:42:56 +00:00
Powei Feng 33a4ab3d88 vk: fix VulkanPlatform CString usage (#9266)
Since #9259, CString in VulkanPlatform fall into the literal
constructor path. But we really want the null-terminated
(char const*) path.  So we cast the strings to (char const*)
to enforce null-teriminated behavior.
2025-09-26 15:37:33 -07:00
rafadevai bcaf5e9da5 VK: Allow memcpy of vertex/index static buffers in UMA (#9258)
* VK: Allow memcpy of vertex/index buffers in UMA

- Renamed VulkanBufferUsage to VulkanBufferBinding
to avoid confusion with the BufferUsage enum.
- In UMA all buffers are persistently memory mapped.
- In the case of static buffers that are memory mapped
use memcpy directly to update their contents.

* PR Comments
2025-09-26 14:07:00 -07:00
Mathias Agopian 98f8c93950 in-place CString replace when possible 2025-09-26 08:07:55 -07:00
Mathias Agopian d11a6b4467 Make matc workarounds default to NONE again 2025-09-25 16:37:50 -07:00
Mathias Agopian 91d4e0e688 Workaround a rendering corruption on Mali
The corruption seems to be triggered with a combination of using:
- spirv-opt
- RGBA16F (as opposed to e.g. RGBA8)
- framebuffer_fetch

In this CL we disable framebuffer_fetch for drivers we know have the
issue.

FIXES=[445721121]
Fix #7794
2025-09-25 16:37:50 -07:00
Mathias Agopian 8af1cb3489 fix build warning (#9263) 2025-09-25 16:37:24 -07:00
Filament Bot 456ae4cabe [automated] Updating /docs due to commit f233b20
Full commit hash is f233b20427

DOCS_ALLOW_DIRECT_EDITS
2025-09-25 21:20:43 +00:00
Powei Feng f233b20427 renderdiff: add a filter option for local testing (#9257)
This option will allow for rendering and comparing a single
image or files that match a wildcard-style string.

README.md has been updated
2025-09-25 21:18:35 +00:00
Mathias Agopian a1b825b5b4 performance improvements to CString (#9259)
- make sure CString("foo") calls the literal constructor
- avoid memory allocations when comparing to a literal
2025-09-25 13:57:53 -07:00
Powei Feng f9beffe3dc vk: add pool for VkSemaphore for re-use and lifetime tracking (#9254)
- Add a VulkanSemaphore ref-counted class to track the references
   of a semamphore - i.e. in a command buffer or in a present.
 - Add a VulkanSemaphoreManager class to keep a pool of
   VkSempahores for better re-use.

This fixes a validation error where we were re-using a semaphore
that is associated with a command buffer while its being used
in a present (as a wait signal).
Error ris VUID-vkQueueSubmit-pSignalSemaphores-00067
2025-09-25 13:39:25 -07:00
Mathias Agopian db96b262a2 fix another matdbg build breakage (#9255) 2025-09-24 23:13:10 -07:00
Eliza c0ab447ef7 material cache: address comments (#9253)
* material cache: address comments

* material cache: simplify CRC32 comparison

* material cache: == if same address

* material cache: use plain type for cached crc32
2025-09-24 17:00:14 -07:00
rafadevai 855a8f0b49 Refactor backend getShaderLanguage functions. (#9204)
Allow returning a list of supported shader languages
instead of only one.

Notify the backend which is the preferred language.
In the case of metal, the preferred language will be
the first element in the list.

This change will allow a backend to support multiple
languages as needed, in the case of the noop driver,
it will support a material with any shader languages.
2025-09-24 16:23:42 -07:00
Mathias Agopian 9c455e856d Fix matdbg build 2025-09-24 14:36:55 -07:00
Filament Bot 009de921e2 [automated] Updating /docs due to commit 7663ca8
Full commit hash is 7663ca8dfe

DOCS_ALLOW_DIRECT_EDITS
2025-09-24 18:55:45 +00:00
281 changed files with 7612 additions and 2785 deletions
+3 -1
View File
@@ -65,4 +65,6 @@ SpacesInParentheses: false
SpacesInSquareBrackets: false
TabWidth: 4
UseTab: Never
PackConstructorInitializers: Never
PackConstructorInitializers: Never
ConstructorInitializerIndentWidth: 8
IndentWrappedFunctionNames: true
+1 -1
View File
@@ -391,7 +391,7 @@ Alternatively, if you have node installed you can use the
[live-server](https://www.npmjs.com/package/live-server) package, which automatically refreshes the
web page when it detects a change.
Each sample app has its own handwritten html file. Additionally the server folder contains assets
Each sample app has its own handwritten html file. Additionally, the server folder contains assets
such as meshes, textures, and materials.
## Running the native samples
+1 -1
View File
@@ -351,7 +351,7 @@ else()
endif()
if (FILAMENT_USE_EXTERNAL_GLES3)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DUSE_EXTERNAL_GLES3")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DFILAMENT_USE_EXTERNAL_GLES3")
endif()
if (FILAMENT_SUPPORTS_EGL_ON_LINUX)
+18 -6
View File
@@ -20,7 +20,7 @@ The guiding principles of the filament code style and code formatting can be res
- class access modifiers are not indented
- last line of `.cpp` or `.h` file must be an empty line
```
```c++
for (int i = 0; i < max; i++) {
}
@@ -73,12 +73,24 @@ src/data.inc
- `public` class attributes *are not* prefixed
- class attributes and methods are lower camelcase
```
```c++
extern int gGlobalWarming;
class FooBar {
public:
void methodName();
FooBar(int attributeName, int sizeInBytes)
: mAttributeName(attributeName),
sizeInBytes(sizeInBytes) {}
void reallyLongMethodNameWithLotsOfArguments(bool argument1,
int someSecondArgument, int bestArgument) {
std::pair<bool, int> pair = {
argument1,
argument2,
};
// etc
}
int sizeInBytes;
private:
int mAttributeName;
@@ -97,7 +109,7 @@ private:
- always include the copyright notice at the top of every file
- make sure the date is correct
```
```c++
/*
* Copyright (C) 2018 The Android Open Source Project
*
@@ -139,7 +151,7 @@ conversely containers and algorithms are not allowed. There are exceptions such
*Sorting the headers is important to help catching missing `#include` directives.*
```
```c++
/*
* Copyright (C) 2018 The Android Open Source Project
*
@@ -183,7 +195,7 @@ conversely containers and algorithms are not allowed. There are exceptions such
### Misc
- Use `auto` only when the type appears on the same line or with iterators and lambdas.
```
```c++
auto foo = new Foo();
for (auto& i : collection) { }
```
-1
View File
@@ -1,7 +1,6 @@
# Filament Release Notes log
**If you are merging a PR into main**: please add the release note below, under the *Release notes
We are chaning the way Vulkan buffers are handled. We need to switch over to a managed (or view-based) model where the data stored inside the object is a proxy to a Vulkan object that can dynamically be swapped around.
**If you are cherry-picking a commit into an rc/ branch**: add the release note under the
appropriate header in [RELEASE_NOTES.md](./RELEASE_NOTES.md).
+2 -2
View File
@@ -31,7 +31,7 @@ repositories {
}
dependencies {
implementation 'com.google.android.filament:filament-android:1.65.3'
implementation 'com.google.android.filament:filament-android:1.66.0'
}
```
@@ -51,7 +51,7 @@ Here are all the libraries available in the group `com.google.android.filament`:
iOS projects can use CocoaPods to install the latest release:
```shell
pod 'Filament', '~> 1.65.3'
pod 'Filament', '~> 1.66.0'
```
## Documentation
+13
View File
@@ -7,6 +7,19 @@ A new header is inserted each time a *tag* is created.
Instead, if you are authoring a PR for the main branch, add your release note to
[NEW_RELEASE_NOTES.md](./NEW_RELEASE_NOTES.md).
## v1.66.1
- filamat: Removed a dependency on Glslang's deprecated SPIR-V remapper.
The functionality is already implemented by calling the CanonicalizeIds pass
in the SPIRV-Tools, and should be a non-functional change.
## v1.66.0
- materials: include default values of spec constants in material metadata [⚠️ **Recompile Materials**]
## v1.65.4
## v1.65.3
@@ -208,3 +208,19 @@ Java_com_google_android_filament_Renderer_nSetVsyncTime(JNIEnv *, jclass,
Renderer *renderer = (Renderer *) nativeRenderer;
renderer->setVsyncTime(steadyClockTimeNano);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_Renderer_nSkipNextFrames(JNIEnv *, jclass ,
jlong nativeRenderer, jint frameCount) {
Renderer *renderer = (Renderer *) nativeRenderer;
renderer->skipNextFrames(frameCount);
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_google_android_filament_Renderer_nGetFrameToSkipCount(JNIEnv *, jclass ,
jlong nativeRenderer) {
Renderer *renderer = (Renderer *) nativeRenderer;
return renderer->getFrameToSkipCount();
}
@@ -356,6 +356,7 @@ Java_com_google_android_filament_View_nSetFogOptions(JNIEnv *, jclass , jlong na
view->setFogOptions(options);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetBlendMode(JNIEnv *, jclass , jlong nativeView, jint blendMode) {
View* view = (View*) nativeView;
@@ -554,3 +555,20 @@ Java_com_google_android_filament_View_nClearFrameHistory(JNIEnv *env, jclass cla
Engine *engine = (Engine *) nativeEngine;
view->clearFrameHistory(*engine);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetChannelDepthClearEnabled(JNIEnv *, jclass ,
jlong nativeView, jint channel, jboolean enabled) {
View* view = (View*) nativeView;
view->setChannelDepthClearEnabled((uint8_t) channel, (bool) enabled);
}
extern "C"
JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_View_nIsChannelDepthClearEnabled(JNIEnv *env, jclass clazz,
jlong nativeView, jint channel) {
// TODO: implement nIsChannelDepthClearEnabled()
View* view = (View*) nativeView;
return (jboolean)view->isChannelDepthClearEnabled((uint8_t) channel);
}
@@ -332,7 +332,7 @@ public class RenderableManager {
}
/**
* Set the channel this renderable is associated to. There can be 4 channels.
* Set the channel this renderable is associated to. There can be 8 channels.
*
* <p>All renderables in a given channel are rendered together, regardless of anything else.
* They are sorted as usual within a channel.</p>
@@ -342,7 +342,7 @@ public class RenderableManager {
* <p>Channels 0 and 1 may not have render primitives using a material with `refractionType`
* set to `screenspace`.</p>
*
* @param channel clamped to the range [0..3], defaults to 2.
* @param channel clamped to the range [0..7], defaults to 2.
*
* @return Builder reference for chaining calls.
*
@@ -351,7 +351,7 @@ public class RenderableManager {
* @see RenderableManager::setBlendOrderAt()
*/
@NonNull
public Builder channel(@IntRange(from = 0, to = 3) int channel) {
public Builder channel(@IntRange(from = 0, to = 7) int channel) {
nBuilderChannel(mNativeBuilder, channel);
return this;
}
@@ -730,7 +730,7 @@ public class RenderableManager {
*
* @see Builder#channel
*/
public void setChannel(@EntityInstance int i, @IntRange(from = 0, to = 3) int channel) {
public void setChannel(@EntityInstance int i, @IntRange(from = 0, to = 7) int channel) {
nSetChannel(mNativeObject, i, channel);
}
@@ -732,6 +732,22 @@ public class Renderer {
nResetUserTime(getNativeObject());
}
/**
* Requests the next frameCount frames to be skipped. For Debugging.
* @param frameCount number of frames to skip.
*/
public void skipNextFrames(int frameCount) {
nSkipNextFrames(getNativeObject(), frameCount);
}
/**
* Remainder count of frame to be skipped
* @return remaining frames to be skipped
*/
public int getFrameToSkipCount() {
return nGetFrameToSkipCount(getNativeObject());
}
public long getNativeObject() {
if (mNativeObject == 0) {
throw new IllegalStateException("Calling method on destroyed Renderer");
@@ -773,4 +789,7 @@ public class Renderer {
float interval, float headRoomRatio, float scaleRate, int history);
private static native void nSetClearOptions(long nativeRenderer,
float r, float g, float b, float a, boolean clear, boolean discard);
private static native void nSkipNextFrames(long nativeObject, int frameCount);
private static native int nGetFrameToSkipCount(long nativeObject);
}
@@ -291,6 +291,25 @@ public class View {
return mViewport;
}
/**
* Sets whether a channel must clear the depth buffer before all primitives are rendered.
* Channel depth clear is off by default for all channels.
* This is orthogonal to Renderer::setClearOptions().
* @param channel between 0 and 7
* @param enabled true to enable clear, false to disable
*/
void setChannelDepthClearEnabled(@IntRange(from = 0, to = 7) int channel, boolean enabled) {
nSetChannelDepthClearEnabled(getNativeObject(), channel, enabled);
}
/**
* @param channel between 0 and 7
* @return true if this channel has depth clear enabled.
*/
boolean isChannelDepthClearEnabled(@IntRange(from = 0, to = 7) int channel) {
return nIsChannelDepthClearEnabled(getNativeObject(), channel);
}
/**
* Sets the blending mode used to draw the view into the SwapChain.
*
@@ -1318,6 +1337,8 @@ public class View {
boolean lensFlare, boolean starburst, float chromaticAberration, int ghostCount, float ghostSpacing, float ghostThreshold, float haloThickness, float haloRadius, float haloThreshold);
private static native void nSetFogOptions(long nativeView, float distance, float maximumOpacity, float height, float heightFalloff, float cutOffDistance, float v, float v1, float v2, float density, float inScatteringStart, float inScatteringSize, boolean fogColorFromIbl, long skyColorNativeObject, boolean enabled);
private static native void nSetStereoscopicOptions(long nativeView, boolean enabled);
private static native void nSetChannelDepthClearEnabled(long nativeView, int channel, boolean enabled);
private static native boolean nIsChannelDepthClearEnabled(long nativeView, int channel);
private static native void nSetBlendMode(long nativeView, int blendMode);
private static native void nSetDepthOfFieldOptions(long nativeView, float cocScale, float maxApertureDiameter, boolean enabled, int filter,
boolean nativeResolution, int foregroundRingCount, int backgroundRingCount, int fastGatherRingCount, int maxForegroundCOC, int maxBackgroundCOC);
@@ -1615,7 +1636,7 @@ public class View {
*
* This value is used as a tint instead, when fogColorFromIbl is enabled.
*
* @see fogColorFromIbl
* @see #fogColorFromIbl
*/
@NonNull @Size(min = 3)
public float[] color = {1.0f, 1.0f, 1.0f};
@@ -1656,7 +1677,7 @@ public class View {
*
* `fogColorFromIbl` is ignored when skyTexture is specified.
*
* @see skyColor
* @see #skyColor
*/
public boolean fogColorFromIbl = false;
/**
@@ -1674,7 +1695,7 @@ public class View {
* In `linearFog` mode mipmap level 0 is always used.
*
* @see Texture
* @see fogColorFromIbl
* @see #fogColorFromIbl
*/
@Nullable
public Texture skyColor = null;
@@ -1796,7 +1817,8 @@ public class View {
/**
* Structure used to set the precision of the color buffer and related quality settings.
*
* @see setRenderQuality, getRenderQuality
* @see #setRenderQuality
* @see #getRenderQuality
*/
public static class RenderQuality {
/**
@@ -1814,7 +1836,7 @@ public class View {
/**
* Options for screen space Ambient Occlusion (SSAO) and Screen Space Cone Tracing (SSCT)
* @see setAmbientOcclusionOptions()
* @see #setAmbientOcclusionOptions
*/
public static class AmbientOcclusionOptions {
public enum AmbientOcclusionType {
@@ -1966,7 +1988,7 @@ public class View {
/**
* Options for Multi-Sample Anti-aliasing (MSAA)
* @see setMultiSampleAntiAliasingOptions()
* @see #setMultiSampleAntiAliasingOptions
*/
public static class MultiSampleAntiAliasingOptions {
/**
@@ -1996,7 +2018,7 @@ public class View {
* `feedback` of 0.1 effectively accumulates a maximum of 19 samples in steady state.
* see "A Survey of Temporal Antialiasing Techniques" by Lei Yang and all for more information.
*
* @see setTemporalAntiAliasingOptions()
* @see #setTemporalAntiAliasingOptions
*/
public static class TemporalAntiAliasingOptions {
public enum BoxType {
@@ -2098,7 +2120,7 @@ public class View {
/**
* Options for Screen-space Reflections.
* @see setScreenSpaceReflectionsOptions()
* @see #setScreenSpaceReflectionsOptions
*/
public static class ScreenSpaceReflectionsOptions {
/**
@@ -2132,7 +2154,9 @@ public class View {
/**
* List of available post-processing anti-aliasing techniques.
* @see setAntiAliasing, getAntiAliasing, setSampleCount
* @see #setAntiAliasing
* @see #getAntiAliasing
* @see #setSampleCount
*/
public enum AntiAliasing {
/**
@@ -2161,7 +2185,7 @@ public class View {
/**
* List of available shadow mapping techniques.
* @see setShadowType
* @see #setShadowType
*/
public enum ShadowType {
/**
@@ -2185,7 +2209,7 @@ public class View {
/**
* View-level options for VSM Shadowing.
* @see setVsmShadowOptions()
* @see #setVsmShadowOptions
* @warning This API is still experimental and subject to change.
*/
public static class VsmShadowOptions {
@@ -2226,7 +2250,7 @@ public class View {
/**
* View-level options for DPCF and PCSS Shadowing.
* @see setSoftShadowOptions()
* @see #setSoftShadowOptions
* @warning This API is still experimental and subject to change.
*/
public static class SoftShadowOptions {
+1 -1
View File
@@ -1,5 +1,5 @@
GROUP=com.google.android.filament
VERSION_NAME=1.65.3
VERSION_NAME=1.66.0
POM_DESCRIPTION=Real-time physically based rendering engine for Android.
+1 -1
View File
@@ -434,7 +434,7 @@ to create a quick localhost server:</p>
<p>Alternatively, if you have node installed you can use the
<a href="https://www.npmjs.com/package/live-server">live-server</a> package, which automatically refreshes the
web page when it detects a change.</p>
<p>Each sample app has its own handwritten html file. Additionally the server folder contains assets
<p>Each sample app has its own handwritten html file. Additionally, the server folder contains assets
such as meshes, textures, and materials.</p>
<h2 id="running-the-native-samples"><a class="header" href="#running-the-native-samples">Running the native samples</a></h2>
<p>The <code>samples/</code> directory contains several examples of how to use Filament with SDL2.</p>
+18 -6
View File
@@ -179,7 +179,7 @@ Google code style and is derived from the Java code style, but not quite.</p>
<li>class access modifiers are not indented</li>
<li>last line of <code>.cpp</code> or <code>.h</code> file must be an empty line</li>
</ul>
<pre><code>for (int i = 0; i &lt; max; i++) {
<pre><code class="language-c++">for (int i = 0; i &lt; max; i++) {
}
class Foo {
@@ -227,11 +227,23 @@ src/data.inc
<li><code>public</code> class attributes <em>are not</em> prefixed</li>
<li>class attributes and methods are lower camelcase</li>
</ul>
<pre><code>extern int gGlobalWarming;
<pre><code class="language-c++">extern int gGlobalWarming;
class FooBar {
public:
void methodName();
FooBar(int attributeName, int sizeInBytes)
: mAttributeName(attributeName),
sizeInBytes(sizeInBytes) {}
void reallyLongMethodNameWithLotsOfArguments(bool argument1,
int someSecondArgument, int bestArgument) {
std::pair&lt;bool, int&gt; pair = {
argument1,
argument2,
};
// etc
}
int sizeInBytes;
private:
int mAttributeName;
@@ -248,7 +260,7 @@ private:
<li>always include the copyright notice at the top of every file</li>
<li>make sure the date is correct</li>
</ul>
<pre><code>/*
<pre><code class="language-c++">/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -293,7 +305,7 @@ conversely containers and algorithms are not allowed. There are exceptions such
</li>
</ul>
<p><em>Sorting the headers is important to help catching missing <code>#include</code> directives.</em></p>
<pre><code>/*
<pre><code class="language-c++">/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -336,7 +348,7 @@ from other string types.</li>
<ul>
<li>Use <code>auto</code> only when the type appears on the same line or with iterators and lambdas.</li>
</ul>
<pre><code>auto foo = new Foo();
<pre><code class="language-c++">auto foo = new Foo();
for (auto&amp; i : collection) { }
</code></pre>
+2 -2
View File
@@ -181,7 +181,7 @@ important for <code>matc</code> (material compiler).</p>
}
dependencies {
implementation 'com.google.android.filament:filament-android:1.65.1'
implementation 'com.google.android.filament:filament-android:1.66.0'
}
</code></pre>
<p>Here are all the libraries available in the group <code>com.google.android.filament</code>:</p>
@@ -196,7 +196,7 @@ dependencies {
</div>
<h3 id="ios"><a class="header" href="#ios">iOS</a></h3>
<p>iOS projects can use CocoaPods to install the latest release:</p>
<pre><code class="language-shell">pod 'Filament', '~&gt; 1.65.1'
<pre><code class="language-shell">pod 'Filament', '~&gt; 1.66.0'
</code></pre>
<h2 id="documentation"><a class="header" href="#documentation">Documentation</a></h2>
<ul>
+57 -50
View File
@@ -161,97 +161,96 @@
<h1 id="rendering-difference-test"><a class="header" href="#rendering-difference-test">Rendering Difference Test</a></h1>
<p>We created a few scripts to run <code>gltf_viewer</code> and produce headless renderings.</p>
<p>This is mainly useful for continuous integration where GPUs are generally not available on cloud
machines. To perform software rasterization, these scripts are centered around <a href="https://docs.mesa3d.org">Mesa</a>'s software
rasterizers, but nothing bars us from using another rasterizer like <a href="https://github.com/google/swiftshader">SwiftShader</a>. Additionally,
we should be able to use GPUs where available (though this is more of a future work).</p>
machines. To perform software rasterization, these scripts are centered around <a href="https://docs.mesa3d.org">Mesa</a>'s
software rasterizers, but nothing bars us from using another rasterizer like <a href="https://github.com/google/swiftshader">SwiftShader</a>.
Additionally, we should be able to use GPUs where available (though this is more of a future
work).</p>
<p>The script <code>render.py</code> contains the core logic for taking input parameters (such as the test
description file) and then running gltf_viewer to produce the renderings.</p>
<p>In the <code>test</code> directory is a list of test descriptions that are specified in json. Please see
<p>In the <code>test</code> directory is a list of test descriptions that are specified in json. Please see
<code>sample.json</code> to parse the structure.</p>
<h2 id="setting-up-python"><a class="header" href="#setting-up-python">Setting up python</a></h2>
<p>The <code>renderdiff</code> project uses <code>python</code> extensively. To install the dependencies for producing
renderings, do the following step</p>
<ul>
<li>Set up a virtual environment (from the root directory)
<pre><code> python3 -m venv venv
. ./venv/bin/activate
<pre><code>python3 -m venv venv
. ./venv/bin/activate
</code></pre>
</li>
<li>Install the rendering dependencies
<pre><code> pip install -r test/renderdiff/src/rendering_requirements.txt
<pre><code>pip install -r test/renderdiff/src/rendering_requirements.txt
</code></pre>
</li>
<li>Install the viewer depdencies
<pre><code> pip install -r test/renderdiff/src/viewer_requirements.txt
<pre><code>pip install -r test/renderdiff/src/viewer_requirements.txt
</code></pre>
</li>
<li>For the commands in the following section, do not exit the virtual environment. Once you've
completed all your work, you can exit with
<pre><code> deactivate
<pre><code>deactivate
</code></pre>
</li>
</ul>
<h2 id="running-the-test-locally"><a class="header" href="#running-the-test-locally">Running the test locally</a></h2>
<ul>
<li>
<p>To run the same presbumit as <a href="presubmit-renderdiff"><code>test-renderdiff</code></a>, you can do</p>
<li>To run the same presbumit as <a href="presubmit-renderdiff"><code>test-renderdiff</code></a>, you can do
<pre><code>bash test/renderdiff/local_test.sh
</code></pre>
</li>
<li>
<p>This script will generate the renderings based on the current state of your repo.
<li>This script will generate the renderings based on the current state of your repo.
Additionally, it will also compare the generated images with corresponding images in the
golden repo.</p>
</li>
<li>
<p>To just render without running the test, you could use the following script</p>
golden repo.</li>
<li>To just render without running the test, you could use the following script
<pre><code>bash test/renderdiff/generate.sh
</code></pre>
</li>
</ul>
<h2 id="command-line-options"><a class="header" href="#command-line-options">Command-line Options</a></h2>
<p>You can control the behavior of the test scripts with the following flags passed to <code>local_test.sh</code>:</p>
<ul>
<li><code>--test_filter=&lt;filter&gt;</code>: Run a subset of tests. The filter supports wildcards (<code>*</code>) to match test names.</li>
<li><code>--no_rebuild</code>: Skip rebuilding the <code>gltf_viewer</code> executable.</li>
<li><code>--num_threads=&lt;number&gt;</code>: Set the number of threads for rendering. If not set, the system's default is used.</li>
</ul>
<p>For example, to run all <code>MSAA</code> tests without rebuilding and using 8 threads:</p>
<pre><code>bash test/renderdiff/local_test.sh --test_filter='MSAA.*.*' --no_rebuild --num_threads=8
</code></pre>
<h2 id="update-the-golden-images"><a class="header" href="#update-the-golden-images">Update the golden images</a></h2>
<p>The golden images are stored in a github repository: https://github.com/google/filament-assets.
Filament team members should have access to write to the repository. A typical flow for updating
the goldens is to upload your changed images into <strong>branch</strong> of <code>filament-assets</code>. This branch is
paired with a PR or commit on the <code>filament</code> repo.</p>
<p>As an example, imagine I am working on a PR, and I've uploaded my change, which is in a branch
called <code>my-pr-branch</code>, to <code>filament</code>. This PR requires updating the golden. We would do it
in the following fashion</p>
<p>The golden images are stored in a github repository:
https://github.com/google/filament-assets. Filament team members should have access to write
to the repository. A typical flow for updating the goldens is to upload your changed images
into <strong>branch</strong> of <code>filament-assets</code>. This branch is paired with a PR or commit on the
<code>filament</code> repo.</p>
<p>As an example, imagine I am working on a PR, and I've uploaded my change, which is in a
branch called <code>my-pr-branch</code>, to <code>filament</code>. This PR requires updating the golden. We would do
it in the following fashion</p>
<h3 id="using-a-script-to-update-the-golden-repo"><a class="header" href="#using-a-script-to-update-the-golden-repo">Using a script to update the golden repo</a></h3>
<ul>
<li>
<p>Run interactive mode in the <code>update_golden.py</code> script.</p>
<li>Run interactive mode in the <code>update_golden.py</code> script.
<pre><code>python3 test/renderdiff/src/update_golden.py
</code></pre>
</li>
<li>
<p>This will guide you through a series of steps to push the changes to a remote branch
on <code>filament-assets</code>.</p>
</li>
<li>This will guide you through a series of steps to push the changes to a remote branch on
<code>filament-assets</code>.</li>
</ul>
<h3 id="manually-updating-the-golden-repo"><a class="header" href="#manually-updating-the-golden-repo">Manually updating the golden repo</a></h3>
<ul>
<li>
<p>Check out the golden repo</p>
<li>Check out the golden repo
<pre><code>git clone git@github.com:google/filament-assets.git
</code></pre>
</li>
<li>
<p>Create a branch on the golden repo</p>
<li>Create a branch on the golden repo
<pre><code>cd filament-assets
git switch -c my-pr-branch-golden
</code></pre>
</li>
<li>
<p>Copy the new images to their appropriate place in <code>filament-assets</code></p>
</li>
<li>
<p>Push the <code>filament-assets</code> working branch to remote</p>
<li>Copy the new images to their appropriate place in <code>filament-assets</code></li>
<li>Push the <code>filament-assets</code> working branch to remote
<pre><code>git push origin my-pr-branch-golden
</code></pre>
</li>
<li>
<p>In the commit message of your working branch on <code>filament</code>, add the following line</p>
<li>In the commit message of your working branch on <code>filament</code>, add the following line
<pre><code>RDIFF_BBRANCH=my-pr-branch-golden
</code></pre>
</li>
@@ -260,16 +259,17 @@ git switch -c my-pr-branch-golden
<ul>
<li>The presubmit test <a href="https://github.com/google/filament/blob/e85dfe75c86106a05019e13ccdbef67e030af675/.github/workflows/presubmit.yml#L118"><code>test-renderdiff</code></a> will test against the provided
branch of the golden repo (i.e. <code>my-pr-branch-golden</code>).</li>
<li>If the PR is merged, then there is another workflow that will merge <code>my-pr-branch-golden</code> to
the <code>main</code> branch of the golden repo.</li>
<li>If the PR is merged, then there is another workflow that will merge <code>my-pr-branch-golden</code>
to the <code>main</code> branch of the golden repo.</li>
</ul>
<h2 id="viewing-test-results"><a class="header" href="#viewing-test-results">Viewing test results</a></h2>
<p>We provide a viewer for looking at the result of a test run. The viewer is a webapp that can be used by
pointing your browser to a localhost port. If you input the viewer with a PR or a directory, it will
parse the test result and show the results and the rendered and/or golden images.</p>
<p>We provide a viewer for looking at the result of a test run. The viewer is a webapp that can
be used by pointing your browser to a localhost port. If you input the viewer with a PR or a
directory, it will parse the test result and show the results and the rendered and/or golden
images.</p>
<p><img src="../images/renderdiff_example.png" alt="Viewer" /></p>
<p>To run the viewer of a test output directory that has been generated locally, you would run the
following</p>
<p>To run the viewer of a test output directory that has been generated locally, you would run
the following</p>
<pre><code>python3 test/renderdiff/src/viewer.py --diff=[test output]
</code></pre>
<p>where <code>[test output]</code> is a directory containing the <code>compare_results.json</code> of the test run.
@@ -278,8 +278,15 @@ For example, it could be <code>out/renderdiff/diffs/presubmit</code> for the sta
<p>To see the results of a Pull Request initiated test run, you would do the following</p>
<pre><code>python3 test/renderdiff/src/viewer.py --pr_number=[PR #] --github_token=[github token]
</code></pre>
<p>where <code>[PR #]</code> is the numeric ID of your pull request, and the <code>[github token]</code> is an acess token
that you (as a github user) needs to generate (<a href="https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens">reference</a>).</p>
<p>where <code>[PR #]</code> is the numeric ID of your pull request, and the <code>[github token]</code> is an acess
token that you (as a github user) needs to generate (<a href="https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens">reference</a>).</p>
<p>To see the results of a specific run, you would do the following</p>
<pre><code>python3 test/renderdiff/src/viewer.py --run_number=[RUN #] --github_token=[github token]
</code></pre>
<p>where <code>[RUN #]</code> is the numeric ID of the run. You can find the run number in the URL of the
GitHub Actions page. For example, in the URL
<code>https://github.com/google/filament/actions/runs/18023632663/job/51286323708?pr=9264</code>,
the run number is <code>18023632663</code>.</p>
</main>
+1 -1
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+4 -1
View File
@@ -117,6 +117,7 @@ set(SRCS
src/components/LightManager.cpp
src/components/RenderableManager.cpp
src/components/TransformManager.cpp
src/details/BufferAllocator.cpp
src/details/BufferObject.cpp
src/details/Camera.cpp
src/details/ColorGrading.cpp
@@ -196,6 +197,7 @@ set(PRIVATE_HDRS
src/components/LightManager.h
src/components/RenderableManager.h
src/components/TransformManager.h
src/details/BufferAllocator.h
src/details/BufferObject.h
src/details/Camera.h
src/details/ColorGrading.h
@@ -249,9 +251,10 @@ set(PRIVATE_HDRS
set(MATERIAL_SRCS
src/materials/antiAliasing/fxaa/fxaa.mat
src/materials/antiAliasing/taa/taa.mat
src/materials/blitArray.mat
src/materials/blitDepth.mat
src/materials/blitLow.mat
src/materials/blitArray.mat
src/materials/clearDepth.mat
src/materials/bloom/bloomDownsample.mat
src/materials/bloom/bloomDownsample2x.mat
src/materials/bloom/bloomDownsample9.mat
+7
View File
@@ -179,6 +179,7 @@ endif()
if (FILAMENT_SUPPORTS_VULKAN)
list(APPEND SRCS
include/backend/platforms/VulkanPlatform.h
src/vulkan/VulkanAsyncHandles.cpp
src/vulkan/VulkanAsyncHandles.h
src/vulkan/VulkanBlitter.cpp
src/vulkan/VulkanBlitter.h
@@ -217,6 +218,10 @@ if (FILAMENT_SUPPORTS_VULKAN)
src/vulkan/VulkanReadPixels.h
src/vulkan/VulkanSamplerCache.cpp
src/vulkan/VulkanSamplerCache.h
src/vulkan/VulkanSemaphore.cpp
src/vulkan/VulkanSemaphore.h
src/vulkan/VulkanSemaphoreManager.cpp
src/vulkan/VulkanSemaphoreManager.h
src/vulkan/VulkanStagePool.cpp
src/vulkan/VulkanStagePool.h
src/vulkan/VulkanSwapChain.cpp
@@ -289,6 +294,8 @@ if (FILAMENT_SUPPORTS_WEBGPU)
src/webgpu/WebGPUPipelineLayoutCache.h
src/webgpu/WebGPUProgram.cpp
src/webgpu/WebGPUProgram.h
src/webgpu/WebGPUQueueManager.cpp
src/webgpu/WebGPUQueueManager.h
src/webgpu/WebGPURenderPassMipmapGenerator.cpp
src/webgpu/WebGPURenderPassMipmapGenerator.h
src/webgpu/WebGPURenderPrimitive.h
@@ -197,6 +197,7 @@ constexpr std::string_view to_string(Backend const backend) noexcept {
* - The Metal backend can prefer precompiled Metal libraries, while falling back to MSL.
*/
enum class ShaderLanguage {
UNSPECIFIED = -1,
ESSL1 = 0,
ESSL3 = 1,
SPIRV = 2,
@@ -219,6 +220,8 @@ constexpr const char* shaderLanguageToString(ShaderLanguage shaderLanguage) noex
return "Metal precompiled library";
case ShaderLanguage::WGSL:
return "WGSL";
case ShaderLanguage::UNSPECIFIED:
return "Unspecified";
}
return "UNKNOWN";
}
@@ -710,6 +713,12 @@ enum class Precision : uint8_t {
DEFAULT
};
union ConstantValue {
int32_t i;
float f;
bool b;
};
/**
* Shader compiler priority queue
*
@@ -1694,6 +1703,8 @@ enum class Workaround : uint16_t {
// prevents these stutters by not precaching depth variants of the default material for those
// particular browsers.
DISABLE_DEPTH_PRECACHE_FOR_DEFAULT_MATERIAL,
// Emulate an sRGB swapchain in shader code.
EMULATE_SRGB_SWAPCHAIN,
};
using StereoscopicType = backend::Platform::StereoscopicType;
+1 -1
View File
@@ -236,7 +236,7 @@ public:
* @return nullptr on failure, or a pointer to the newly created driver.
*/
virtual Driver* UTILS_NULLABLE createDriver(void* UTILS_NULLABLE sharedContext,
const DriverConfig& driverConfig) noexcept = 0;
const DriverConfig& driverConfig) = 0;
/**
* Processes the platform's event queue when called from its primary event-handling thread.
+2 -6
View File
@@ -50,11 +50,7 @@ public:
descriptor_binding_t binding;
};
struct SpecializationConstant {
using Type = std::variant<int32_t, float, bool>;
uint32_t id; // id set in glsl
Type value; // value and type
};
using SpecializationConstant = std::variant<int32_t, float, bool>;
struct Uniform { // For ES2 support
utils::CString name; // full qualified name of the uniform field
@@ -118,7 +114,7 @@ public:
Program& multiview(bool multiview) noexcept;
// For ES2 support only...
Program& uniforms(uint32_t index, utils::CString name, UniformInfo uniforms) noexcept;
Program& uniforms(uint32_t index, utils::CString name, UniformInfo uniforms);
Program& attributes(AttributesInfo attributes) noexcept;
//
@@ -112,7 +112,7 @@ public:
*
*/
virtual SwapChain* UTILS_NULLABLE createSwapChain(
void* UTILS_NULLABLE nativeWindow, uint64_t flags) noexcept = 0;
void* UTILS_NULLABLE nativeWindow, uint64_t flags) = 0;
/**
* Called by the driver create a headless SwapChain.
@@ -126,7 +126,7 @@ public:
* A void* might be enough.
*/
virtual SwapChain* UTILS_NULLABLE createSwapChain(
uint32_t width, uint32_t height, uint64_t flags) noexcept = 0;
uint32_t width, uint32_t height, uint64_t flags) = 0;
/**
* Called by the driver to destroys the SwapChain
@@ -40,7 +40,7 @@ protected:
// Platform Interface
Driver* createDriver(void* sharedContext,
const DriverConfig& driverConfig) noexcept override;
const DriverConfig& driverConfig) override;
// Currently returns 0
int getOSVersion() const noexcept override;
@@ -38,7 +38,7 @@ public:
// Platform Interface
Driver* createDriver(void* sharedGLContext,
const DriverConfig& driverConfig) noexcept override;
const DriverConfig& driverConfig) override;
int getOSVersion() const noexcept final { return 0; }
@@ -80,7 +80,7 @@ protected:
* Initializes EGL, creates the OpenGL context and returns a concrete Driver implementation
* that supports OpenGL/OpenGL ES.
*/
Driver* createDriver(void* sharedContext, const DriverConfig& driverConfig) noexcept override;
Driver* createDriver(void* sharedContext, const DriverConfig& driverConfig) override;
/**
* This returns zero. This method can be overridden to return something more useful.
@@ -101,8 +101,8 @@ protected:
bool isSRGBSwapChainSupported() const noexcept override;
bool isMSAASwapChainSupported(uint32_t samples) const noexcept override;
SwapChain* createSwapChain(void* nativewindow, uint64_t flags) noexcept override;
SwapChain* createSwapChain(uint32_t width, uint32_t height, uint64_t flags) noexcept override;
SwapChain* createSwapChain(void* nativewindow, uint64_t flags) override;
SwapChain* createSwapChain(uint32_t width, uint32_t height, uint64_t flags) override;
void destroySwapChain(SwapChain* swapChain) noexcept override;
bool isSwapChainProtected(SwapChain* swapChain) noexcept override;
@@ -80,7 +80,7 @@ protected:
int getOSVersion() const noexcept override;
Driver* createDriver(void* sharedContext,
const Platform::DriverConfig& driverConfig) noexcept override;
const Platform::DriverConfig& driverConfig) override;
// --------------------------------------------------------------------------------------------
// OpenGLPlatform Interface
@@ -29,7 +29,7 @@ public:
PlatformEGLHeadless() noexcept;
Driver* createDriver(void* sharedContext,
const Platform::DriverConfig& driverConfig) noexcept override;
const Platform::DriverConfig& driverConfig) override;
protected:
bool isOpenGL() const noexcept override;
@@ -39,7 +39,7 @@ protected:
// Platform Interface
Driver* createDriver(void* sharedGLContext,
const DriverConfig& driverConfig) noexcept override;
const DriverConfig& driverConfig) override;
int getOSVersion() const noexcept final override { return 0; }
@@ -55,9 +55,9 @@ protected:
void commit(SwapChain* swapChain) noexcept override;
private:
Display *mGLXDisplay;
GLXContext mGLXContext;
GLXFBConfig* mGLXConfig;
Display* mGLXDisplay;
GLXContext mGLXContext{};
GLXFBConfig mGLXConfig{};
GLXPbuffer mDummySurface;
std::vector<GLXPbuffer> mPBuffers;
};
@@ -36,7 +36,7 @@ public:
PlatformMetal();
~PlatformMetal() noexcept override;
Driver* createDriver(void* sharedContext, const Platform::DriverConfig& driverConfig) noexcept override;
Driver* createDriver(void* sharedContext, const Platform::DriverConfig& driverConfig) override;
int getOSVersion() const noexcept override { return 0; }
/**
@@ -43,7 +43,7 @@ protected:
// --------------------------------------------------------------------------------------------
// Platform Interface
Driver* createDriver(void* sharedGLContext, const DriverConfig& driverConfig) noexcept override;
Driver* createDriver(void* sharedGLContext, const DriverConfig& driverConfig) override;
int getOSVersion() const noexcept final override { return 0; }
@@ -38,7 +38,7 @@ protected:
// Platform Interface
Driver* createDriver(void* sharedGLContext,
const Platform::DriverConfig& driverConfig) noexcept override;
const Platform::DriverConfig& driverConfig) override;
int getOSVersion() const noexcept final override { return 0; }
@@ -61,8 +61,12 @@ protected:
HWND mHWnd = NULL;
HDC mWhdc = NULL;
PIXELFORMATDESCRIPTOR mPfd = {};
std::vector<HGLRC> mAdditionalContexts;
std::vector<int> mAttribs;
// For shared contexts
static constexpr int SHARED_CONTEXT_NUM = 1;
std::vector<HGLRC> mAdditionalContexts;
std::atomic<int> mNextFreeSharedContextIndex{0};
};
} // namespace filament::backend
@@ -34,7 +34,7 @@ protected:
// Platform Interface
Driver* createDriver(void* sharedGLContext,
const Platform::DriverConfig& driverConfig) noexcept override;
const Platform::DriverConfig& driverConfig) override;
int getOSVersion() const noexcept override;
@@ -119,7 +119,7 @@ public:
~VulkanPlatform() override;
Driver* createDriver(void* sharedContext,
Platform::DriverConfig const& driverConfig) noexcept override;
Platform::DriverConfig const& driverConfig) override;
int getOSVersion() const noexcept override {
return 0;
@@ -72,7 +72,7 @@ public:
protected:
[[nodiscard]] Driver* createDriver(void* sharedContext,
const Platform::DriverConfig& driverConfig) noexcept override;
const Platform::DriverConfig& driverConfig) override;
private:
// returns adapter request option variations applicable for the particular
@@ -61,7 +61,7 @@ class CommandBase {
protected:
using Execute = Dispatcher::Execute;
constexpr explicit CommandBase(Execute execute) noexcept : mExecute(execute) {}
constexpr explicit CommandBase(Execute const execute) noexcept : mExecute(execute) {}
public:
// alignment of all Commands in the CommandStream
@@ -70,7 +70,7 @@ public:
}
// executes this command and returns the next one
inline CommandBase* execute(Driver& driver) {
CommandBase* execute(Driver& driver) {
// returning the next command by output parameter allows the compiler to perform the
// tail-call optimization in the function called by mExecute, however that comes at
// a cost here (writing and reading the stack at each iteration), in the end it's
@@ -80,7 +80,7 @@ public:
return reinterpret_cast<CommandBase*>(reinterpret_cast<intptr_t>(this) + next);
}
inline ~CommandBase() noexcept = default;
~CommandBase() noexcept = default;
private:
Execute mExecute;
@@ -135,7 +135,7 @@ struct CommandType<void (Driver::*)(ARGS...)> {
public:
template<typename M, typename D>
static inline void execute(M&& method, D&& driver, CommandBase* base, intptr_t* next) {
static void execute(M&& method, D&& driver, CommandBase* base, intptr_t* next) {
Command* self = static_cast<Command*>(base);
*next = align(sizeof(Command));
#if DEBUG_COMMAND_STREAM
@@ -147,15 +147,15 @@ struct CommandType<void (Driver::*)(ARGS...)> {
}
// A command can be moved
inline Command(Command&& rhs) noexcept = default;
Command(Command&& rhs) noexcept = default;
template<typename... A>
inline explicit constexpr Command(Execute execute, A&& ... args)
explicit constexpr Command(Execute const execute, A&& ... args) noexcept
: CommandBase(execute), mArgs(std::forward<A>(args)...) {
}
// placement new declared as "throw" to avoid the compiler's null-check
inline void* operator new(std::size_t, void* ptr) {
void* operator new(std::size_t, void* ptr) noexcept {
assert_invariant(ptr);
return ptr;
}
@@ -171,8 +171,9 @@ class CustomCommand : public CommandBase {
std::function<void()> mCommand;
static void execute(Driver&, CommandBase* base, intptr_t* next);
public:
inline CustomCommand(CustomCommand&& rhs) = default;
inline explicit CustomCommand(std::function<void()> cmd)
CustomCommand(CustomCommand&& rhs) = default;
explicit CustomCommand(std::function<void()> cmd)
: CommandBase(execute), mCommand(std::move(cmd)) { }
};
@@ -184,7 +185,7 @@ class NoopCommand : public CommandBase {
*next = static_cast<NoopCommand*>(self)->mNext;
}
public:
inline constexpr explicit NoopCommand(void* next) noexcept
constexpr explicit NoopCommand(void* next) noexcept
: CommandBase(execute), mNext(intptr_t((char *)next - (char *)this)) { }
};
@@ -207,8 +208,8 @@ class CommandStream {
template<typename T>
struct AutoExecute {
T closure;
inline explicit AutoExecute(T&& closure) : closure(std::forward<T>(closure)) {}
inline ~AutoExecute() { closure(); }
explicit AutoExecute(T&& closure) : closure(std::forward<T>(closure)) {}
~AutoExecute() { closure(); }
};
public:
@@ -221,7 +222,7 @@ public:
public:
#define DECL_DRIVER_API(methodName, paramsDecl, params) \
inline void methodName(paramsDecl) { \
inline void methodName(paramsDecl) noexcept { \
DEBUG_COMMAND_BEGIN(methodName, false, params); \
using Cmd = COMMAND_TYPE(methodName); \
void* const p = allocateCommand(CommandBase::align(sizeof(Cmd))); \
@@ -230,7 +231,7 @@ public:
}
#define DECL_DRIVER_API_SYNCHRONOUS(RetType, methodName, paramsDecl, params) \
inline RetType methodName(paramsDecl) { \
inline RetType methodName(paramsDecl) noexcept { \
DEBUG_COMMAND_BEGIN(methodName, true, params); \
AutoExecute callOnExit([=, this](){ \
DEBUG_COMMAND_END(methodName, true); \
@@ -239,7 +240,7 @@ public:
}
#define DECL_DRIVER_API_RETURN(RetType, methodName, paramsDecl, params) \
inline RetType methodName(paramsDecl) { \
inline RetType methodName(paramsDecl) noexcept { \
DEBUG_COMMAND_BEGIN(methodName, false, params); \
RetType result = mDriver.methodName##S(); \
using Cmd = COMMAND_TYPE(methodName##R); \
@@ -255,7 +256,7 @@ public:
// This is for debugging only. Currently, CircularBuffer can only be written from a
// single thread. In debug builds we assert this condition.
// Call this first in the render loop.
inline void debugThreading() noexcept {
void debugThreading() noexcept {
#ifndef NDEBUG
mThreadId = utils::ThreadUtils::getThreadId();
#endif
@@ -281,11 +282,11 @@ public:
*/
template<typename PodType,
typename = typename std::enable_if<std::is_trivially_destructible<PodType>::value>::type>
inline PodType* allocatePod(
PodType* allocatePod(
size_t count = 1, size_t alignment = alignof(PodType)) noexcept;
private:
inline void* allocateCommand(size_t size) {
void* allocateCommand(size_t const size) noexcept {
assert_invariant(utils::ThreadUtils::isThisThread(mThreadId));
return mCurrentBuffer.allocate(size);
}
@@ -27,6 +27,8 @@
#include <backend/AcquiredImage.h>
#include <utils/CString.h>
#include <utils/ImmutableCString.h>
#include <utils/FixedCapacityVector.h>
#include <utils/compiler.h>
#include <functional>
@@ -71,7 +73,11 @@ public:
virtual ShaderModel getShaderModel() const noexcept = 0;
// The shader language used for shaders for this driver, used to inform matdbg.
// The shader languages used for shaders for this driver in order of preference, used to inform
// matdbg.
//
// The `preferredLanguage` is only a hint. If the backend supports it, it will appear first in
// the list.
//
// For OpenGL, this distinguishes whether the driver's shaders are powered by ESSL1 or ESSL3.
// This information is used by matdbg to display the correct shader code to the web UI and patch
@@ -79,7 +85,8 @@ public:
//
// Metal shaders can either be MSL or Metal libraries, but at time of writing, matdbg can only
// interface with MSL.
virtual ShaderLanguage getShaderLanguage() const noexcept = 0;
virtual utils::FixedCapacityVector<ShaderLanguage> getShaderLanguages(
ShaderLanguage preferredLanguage) const noexcept = 0;
// Returns the dispatcher. This is only called once during initialization of the CommandStream,
// so it doesn't matter that it's virtual.
@@ -108,15 +108,15 @@
DECL_DRIVER_API_RETURN(R, N, PAIR_ARGS_N(ARG, ##__VA_ARGS__), PAIR_ARGS_N(PARAM, ##__VA_ARGS__))
#define DECL_DRIVER_API_TAGGED_R_N(R, N, ...) \
DECL_DRIVER_API_RETURN(R, N, PAIR_ARGS_N(ARG, ##__VA_ARGS__, utils::CString&&, tag = {}), \
PAIR_ARGS_N(PARAM, ##__VA_ARGS__, utils::CString&&, tag))
DECL_DRIVER_API_RETURN(R, N, PAIR_ARGS_N(ARG, ##__VA_ARGS__, utils::ImmutableCString&&, tag = {}), \
PAIR_ARGS_N(PARAM, ##__VA_ARGS__, utils::ImmutableCString&&, tag))
#define DECL_DRIVER_API_SYNCHRONOUS_N(R, N, ...) \
DECL_DRIVER_API_SYNCHRONOUS(R, N, PAIR_ARGS_N(ARG, ##__VA_ARGS__), PAIR_ARGS_N(PARAM, ##__VA_ARGS__))
#define DECL_DRIVER_API_SYNCHRONOUS_TAGGED_N(R, N, ...) \
DECL_DRIVER_API_SYNCHRONOUS(R, N, PAIR_ARGS_N(ARG, ##__VA_ARGS__, utils::CString, tag = {}), \
PAIR_ARGS_N(PARAM, ##__VA_ARGS__, utils::CString, tag))
DECL_DRIVER_API_SYNCHRONOUS(R, N, PAIR_ARGS_N(ARG, ##__VA_ARGS__, utils::ImmutableCString, tag = {}), \
PAIR_ARGS_N(PARAM, ##__VA_ARGS__, utils::ImmutableCString, tag))
// on some compilers the ##__VA_ARGS__ hack is not supported, so we can't handle 0-parameter APIs
// with DECL_DRIVER_API_SYNCHRONOUS_N
@@ -336,6 +336,7 @@ DECL_DRIVER_API_SYNCHRONOUS_N(void, setStreamDimensions, backend::StreamHandle,
DECL_DRIVER_API_SYNCHRONOUS_N(int64_t, getStreamTimestamp, backend::StreamHandle, stream)
DECL_DRIVER_API_SYNCHRONOUS_N(void, updateStreams, backend::DriverApi*, driver)
DECL_DRIVER_API_SYNCHRONOUS_N(backend::FenceStatus, getFenceStatus, backend::FenceHandle, fh)
DECL_DRIVER_API_SYNCHRONOUS_N(backend::FenceStatus, fenceWait, backend::FenceHandle, fh, uint64_t, timeout)
DECL_DRIVER_API_SYNCHRONOUS_N(void, getPlatformSync, backend::SyncHandle, sh,
backend::CallbackHandler*, handler, backend::Platform::SyncCallback, cb, void*, userData)
DECL_DRIVER_API_SYNCHRONOUS_N(bool, isTextureFormatSupported, backend::TextureFormat, format)
@@ -416,14 +417,6 @@ DECL_DRIVER_API_N(setExternalStream,
backend::TextureHandle, th,
backend::StreamHandle, sh)
DECL_DRIVER_API_N(beginRenderPass,
backend::RenderTargetHandle, rth,
const backend::RenderPassParams&, params)
DECL_DRIVER_API_0(endRenderPass)
DECL_DRIVER_API_0(nextSubpass)
DECL_DRIVER_API_N(beginTimerQuery,
backend::TimerQueryHandle, tqh)
@@ -456,6 +449,36 @@ DECL_DRIVER_API_N(copyToMemoryMappedBuffer,
size_t, offset,
backend::BufferDescriptor&&, data)
DECL_DRIVER_API_N(setPushConstant,
backend::ShaderStage, stage,
uint8_t, index,
backend::PushConstantVariant, value)
/*
* Setting rendering state
* -----------------------
*/
DECL_DRIVER_API_N(beginRenderPass,
backend::RenderTargetHandle, rth,
const backend::RenderPassParams&, params)
DECL_DRIVER_API_0(endRenderPass)
DECL_DRIVER_API_0(nextSubpass)
DECL_DRIVER_API_N(bindPipeline,
backend::PipelineState const&, state)
DECL_DRIVER_API_N(bindRenderPrimitive,
backend::RenderPrimitiveHandle, rph)
DECL_DRIVER_API_N(bindDescriptorSet,
backend::DescriptorSetHandle, dsh,
backend::descriptor_set_t, set,
backend::DescriptorSetOffsetArray&&, offsets
)
/*
* Swap chain
*/
@@ -473,11 +496,6 @@ DECL_DRIVER_API_N(commit,
* -----------------------
*/
DECL_DRIVER_API_N(setPushConstant,
backend::ShaderStage, stage,
uint8_t, index,
backend::PushConstantVariant, value)
DECL_DRIVER_API_N(insertEventMarker,
const char*, string)
@@ -538,18 +556,6 @@ DECL_DRIVER_API_N(blit,
math::uint2, srcOrigin,
math::uint2, size)
DECL_DRIVER_API_N(bindPipeline,
backend::PipelineState const&, state)
DECL_DRIVER_API_N(bindRenderPrimitive,
backend::RenderPrimitiveHandle, rph)
DECL_DRIVER_API_N(bindDescriptorSet,
backend::DescriptorSetHandle, dsh,
backend::descriptor_set_t, set,
backend::DescriptorSetOffsetArray&&, offsets
)
DECL_DRIVER_API_N(draw2,
uint32_t, indexOffset,
uint32_t, indexCount,
@@ -21,6 +21,7 @@
#include <utils/Allocator.h>
#include <utils/CString.h>
#include <utils/ImmutableCString.h>
#include <utils/Log.h>
#include <utils/Panic.h>
#include <utils/compiler.h>
@@ -52,16 +53,16 @@ namespace filament::backend {
class DebugTag {
public:
DebugTag();
void writePoolHandleTag(HandleBase::HandleId key, utils::CString&& tag) noexcept;
void writeHeapHandleTag(HandleBase::HandleId key, utils::CString&& tag) noexcept;
utils::CString findHandleTag(HandleBase::HandleId key) const noexcept;
void writePoolHandleTag(HandleBase::HandleId key, utils::ImmutableCString&& tag) noexcept;
void writeHeapHandleTag(HandleBase::HandleId key, utils::ImmutableCString&& tag) noexcept;
utils::ImmutableCString findHandleTag(HandleBase::HandleId key) const noexcept;
private:
// This is used to associate a tag to a handle. mDebugTags is only written the in the main
// driver thread, but it can be accessed from any thread, because it's called from handle_cast<>
// which is used by synchronous calls.
mutable utils::Mutex mDebugTagLock;
tsl::robin_map<HandleBase::HandleId, utils::CString> mDebugTags;
tsl::robin_map<HandleBase::HandleId, utils::ImmutableCString> mDebugTags;
};
/*
@@ -70,12 +71,12 @@ private:
template<size_t P0, size_t P1, size_t P2>
class HandleAllocator : public DebugTag {
public:
HandleAllocator(const char* name, size_t size) noexcept;
HandleAllocator(const char* name, size_t size);
HandleAllocator(const char* name, size_t size,
bool disableUseAfterFreeCheck, bool disableHeapHandleTags) noexcept;
bool disableUseAfterFreeCheck, bool disableHeapHandleTags);
HandleAllocator(HandleAllocator const& rhs) = delete;
HandleAllocator& operator=(HandleAllocator const& rhs) = delete;
~HandleAllocator();
~HandleAllocator() noexcept;
/*
* Constructs a D object and returns a Handle<D>
@@ -106,7 +107,7 @@ public:
*
*/
template<typename D>
Handle<D> allocate() noexcept {
Handle<D> allocate() {
Handle<D> h{ allocateHandle<D>() };
return h;
}
@@ -222,7 +223,7 @@ public:
return static_cast<Dp>(p);
}
utils::CString getHandleTag(HandleBase::HandleId key) const noexcept;
utils::ImmutableCString getHandleTag(HandleBase::HandleId key) const noexcept;
template<typename B>
bool is_valid(Handle<B>& handle) {
@@ -248,7 +249,7 @@ public:
return handle_cast<Dp>(const_cast<Handle<B>&>(handle));
}
void associateTagToHandle(HandleBase::HandleId id, utils::CString&& tag) noexcept {
void associateTagToHandle(HandleBase::HandleId id, utils::ImmutableCString&& tag) noexcept {
if (tag.empty()) {
return;
}
@@ -342,7 +343,7 @@ private:
// allocation size this is always inlined, because all these do is to call
// allocateHandleInPool()/deallocateHandleFromPool() with the right pool size.
template<typename D>
HandleBase::HandleId allocateHandle() noexcept {
HandleBase::HandleId allocateHandle() {
constexpr size_t BUCKET_SIZE = getBucketSize<D>();
return allocateHandleInPool<BUCKET_SIZE>();
}
@@ -358,7 +359,7 @@ private:
// the code generated is not trivial (even if it's not insane either).
template<size_t SIZE>
UTILS_NOINLINE
HandleBase::HandleId allocateHandleInPool() noexcept {
HandleBase::HandleId allocateHandleInPool() {
uint8_t age;
void* p = mHandleArena.alloc(SIZE, alignof(std::max_align_t), 0, &age);
if (UTILS_LIKELY(p)) {
+1 -1
View File
@@ -20,7 +20,7 @@
namespace filament::backend {
CallbackManager::CallbackManager(DriverBase& driver) noexcept
CallbackManager::CallbackManager(DriverBase& driver)
: mDriver(driver), mCallbacks(1) {
}
+2 -2
View File
@@ -51,7 +51,7 @@ class CallbackManager {
public:
using Handle = Container::const_iterator;
explicit CallbackManager(DriverBase& driver) noexcept;
explicit CallbackManager(DriverBase& driver);
~CallbackManager() noexcept;
@@ -78,7 +78,7 @@ private:
return --mCallbacks.end();
}
Container::iterator allocateNewSlot() noexcept {
Container::iterator allocateNewSlot() {
std::lock_guard const lock(mLock);
auto curr = --mCallbacks.end();
mCallbacks.emplace_back();
+6 -3
View File
@@ -57,12 +57,15 @@ static void printParameterPack(io::ostream& out, const FIRST& first, const REMAI
printParameterPack(out, rest...);
}
static UTILS_NOINLINE UTILS_UNUSED std::string_view extractMethodName(std::string_view command) noexcept {
constexpr const char startPattern[] = "::Command<&filament::backend::Driver::";
static UTILS_NOINLINE UTILS_UNUSED std::string_view extractMethodName(std::string_view command) noexcept { // NOLINT(*-exception-escape)
constexpr char startPattern[] = "::Command<&filament::backend::Driver::";
auto pos = command.rfind(startPattern);
auto end = command.rfind('(');
pos += sizeof(startPattern) - 1;
return command.substr(pos, end-pos);
if (pos > command.size()) {
return { command.data(), command.size() };
}
return command.substr(pos, end-pos); // this can't throw by construction
}
// ------------------------------------------------------------------------------------------------
+8 -1
View File
@@ -18,7 +18,14 @@
#include <private/utils/Tracing.h>
#include <utils/compiler.h>
#include <utils/debug.h>
#include <algorithm>
#include <iterator>
#include <memory>
#include <mutex>
#include <utility>
namespace filament::backend {
@@ -36,7 +43,7 @@ CompilerThreadPool::~CompilerThreadPool() noexcept {
}
void CompilerThreadPool::init(uint32_t threadCount,
ThreadSetup&& threadSetup, ThreadCleanup&& threadCleanup) noexcept {
ThreadSetup&& threadSetup, ThreadCleanup&& threadCleanup) {
auto setup = std::make_shared<ThreadSetup>(std::move(threadSetup));
auto cleanup = std::make_shared<ThreadCleanup>(std::move(threadCleanup));
+1 -2
View File
@@ -47,8 +47,7 @@ public:
using Job = utils::Invocable<void()>;
using ThreadSetup = utils::Invocable<void()>;
using ThreadCleanup = utils::Invocable<void()>;
void init(uint32_t threadCount,
ThreadSetup&& threadSetup, ThreadCleanup&& threadCleanup) noexcept;
void init(uint32_t threadCount, ThreadSetup&& threadSetup, ThreadCleanup&& threadCleanup);
void terminate() noexcept;
void queue(CompilerPriorityQueue priorityQueue, program_token_t const& token, Job&& job);
Job dequeue(program_token_t const& token);
+2 -2
View File
@@ -131,7 +131,7 @@ void DriverBase::purge() noexcept {
// ------------------------------------------------------------------------------------------------
void DriverBase::scheduleDestroySlow(BufferDescriptor&& buffer) noexcept {
void DriverBase::scheduleDestroySlow(BufferDescriptor&& buffer) {
auto const handler = buffer.getHandler();
scheduleCallback(handler, [buffer = std::move(buffer)]() {
// user callback is called when BufferDescriptor gets destroyed
@@ -140,7 +140,7 @@ void DriverBase::scheduleDestroySlow(BufferDescriptor&& buffer) noexcept {
// This is called from an async driver method so it's in the GL thread, but purge is called
// on the user thread. This is typically called 0 or 1 times per frame.
void DriverBase::scheduleRelease(AcquiredImage const& image) noexcept {
void DriverBase::scheduleRelease(AcquiredImage const& image) {
scheduleCallback(image.handler, [callback = image.callback, image = image.image, userData = image.userData]() {
callback(image, userData);
});
+3 -3
View File
@@ -214,15 +214,15 @@ public:
protected:
class CallbackDataDetails;
void scheduleDestroy(BufferDescriptor&& buffer) noexcept {
void scheduleDestroy(BufferDescriptor&& buffer) {
if (buffer.hasCallback()) {
scheduleDestroySlow(std::move(buffer));
}
}
void scheduleDestroySlow(BufferDescriptor&& buffer) noexcept;
void scheduleDestroySlow(BufferDescriptor&& buffer);
void scheduleRelease(AcquiredImage const& image) noexcept;
void scheduleRelease(AcquiredImage const& image);
void debugCommandBegin(CommandStream* cmds, bool synchronous, const char* methodName) noexcept override;
void debugCommandEnd(CommandStream* cmds, bool synchronous, const char* methodName) noexcept override;
+7 -7
View File
@@ -81,19 +81,19 @@ HandleAllocator<P0, P1, P2>::Allocator::Allocator(AreaPolicy::HeapArea const& ar
template <size_t P0, size_t P1, size_t P2>
HandleAllocator<P0, P1, P2>::HandleAllocator(const char* name, size_t size,
bool disableUseAfterFreeCheck,
bool disableHeapHandleTags) noexcept
bool disableHeapHandleTags)
: mHandleArena(name, size, disableUseAfterFreeCheck),
mUseAfterFreeCheckDisabled(disableUseAfterFreeCheck),
mHeapHandleTagsDisabled(disableHeapHandleTags) {
}
template <size_t P0, size_t P1, size_t P2>
HandleAllocator<P0, P1, P2>::HandleAllocator(const char* name, size_t size) noexcept
HandleAllocator<P0, P1, P2>::HandleAllocator(const char* name, size_t size)
: HandleAllocator(name, size, false, false) {
}
template <size_t P0, size_t P1, size_t P2>
HandleAllocator<P0, P1, P2>::~HandleAllocator() {
HandleAllocator<P0, P1, P2>::~HandleAllocator() noexcept {
auto& overflowMap = mOverflowMap;
if (!overflowMap.empty()) {
PANIC_LOG("Not all handles have been freed. Probably leaking memory.");
@@ -156,7 +156,7 @@ void HandleAllocator<P0, P1, P2>::deallocateHandleSlow(HandleBase::HandleId id,
template<size_t P0, size_t P1, size_t P2>
UTILS_NOINLINE
CString HandleAllocator<P0, P1, P2>::getHandleTag(HandleBase::HandleId id) const noexcept {
ImmutableCString HandleAllocator<P0, P1, P2>::getHandleTag(HandleBase::HandleId id) const noexcept {
uint32_t key = id;
if (UTILS_LIKELY(isPoolHandle(id))) {
// Truncate the age to get the debug tag
@@ -172,7 +172,7 @@ DebugTag::DebugTag() {
}
UTILS_NOINLINE
CString DebugTag::findHandleTag(HandleBase::HandleId key) const noexcept {
ImmutableCString DebugTag::findHandleTag(HandleBase::HandleId key) const noexcept {
std::unique_lock const lock(mDebugTagLock);
if (auto pos = mDebugTags.find(key); pos != mDebugTags.end()) {
return pos->second;
@@ -181,7 +181,7 @@ CString DebugTag::findHandleTag(HandleBase::HandleId key) const noexcept {
}
UTILS_NOINLINE
void DebugTag::writePoolHandleTag(HandleBase::HandleId key, CString&& tag) noexcept {
void DebugTag::writePoolHandleTag(HandleBase::HandleId key, ImmutableCString&& tag) noexcept {
// This line is the costly part. In the future, we could potentially use a custom
// allocator.
std::unique_lock const lock(mDebugTagLock);
@@ -190,7 +190,7 @@ void DebugTag::writePoolHandleTag(HandleBase::HandleId key, CString&& tag) noexc
}
UTILS_NOINLINE
void DebugTag::writeHeapHandleTag(HandleBase::HandleId key, CString&& tag) noexcept {
void DebugTag::writeHeapHandleTag(HandleBase::HandleId key, ImmutableCString&& tag) noexcept {
// This line is the costly part. In the future, we could potentially use a custom
// allocator.
std::unique_lock const lock(mDebugTagLock);
+9 -9
View File
@@ -41,37 +41,37 @@ Program& Program::operator=(Program&& rhs) noexcept = default;
Program::~Program() noexcept = default;
Program& Program::priorityQueue(CompilerPriorityQueue priorityQueue) noexcept {
Program& Program::priorityQueue(CompilerPriorityQueue const priorityQueue) noexcept {
mPriorityQueue = priorityQueue;
return *this;
}
Program& Program::diagnostics(CString const& name,
Invocable<io::ostream&(utils::CString const& name, io::ostream&)>&& logger) {
Invocable<io::ostream&(CString const& name, io::ostream&)>&& logger) {
mName = name;
mLogger = std::move(logger);
return *this;
}
Program& Program::shader(ShaderStage shader, void const* data, size_t size) {
Program& Program::shader(ShaderStage shader, void const* data, size_t const size) {
ShaderBlob blob(size);
std::copy_n((const uint8_t *)data, size, blob.data());
mShadersSource[size_t(shader)] = std::move(blob);
return *this;
}
Program& Program::shaderLanguage(ShaderLanguage shaderLanguage) {
Program& Program::shaderLanguage(ShaderLanguage const shaderLanguage) {
mShaderLanguage = shaderLanguage;
return *this;
}
Program& Program::descriptorBindings(backend::descriptor_set_t set,
Program& Program::descriptorBindings(descriptor_set_t const set,
DescriptorBindingsInfo descriptorBindings) noexcept {
mDescriptorBindings[set] = std::move(descriptorBindings);
return *this;
}
Program& Program::uniforms(uint32_t index, utils::CString name, UniformInfo uniforms) noexcept {
Program& Program::uniforms(uint32_t index, CString name, UniformInfo uniforms) {
mBindingUniformsInfo.reserve(mBindingUniformsInfo.capacity() + 1);
mBindingUniformsInfo.emplace_back(index, std::move(name), std::move(uniforms));
return *this;
@@ -88,17 +88,17 @@ Program& Program::specializationConstants(SpecializationConstantsInfo specConsta
}
Program& Program::pushConstants(ShaderStage stage,
utils::FixedCapacityVector<PushConstant> constants) noexcept {
FixedCapacityVector<PushConstant> constants) noexcept {
mPushConstants[static_cast<uint8_t>(stage)] = std::move(constants);
return *this;
}
Program& Program::cacheId(uint64_t cacheId) noexcept {
Program& Program::cacheId(uint64_t const cacheId) noexcept {
mCacheId = cacheId;
return *this;
}
Program& Program::multiview(bool multiview) noexcept {
Program& Program::multiview(bool const multiview) noexcept {
mMultiview = multiview;
return *this;
}
+1 -1
View File
@@ -192,7 +192,7 @@ public:
void* getCpuBuffer() const noexcept { return mCpuBuffer; }
void setLabel(const utils::CString& label) {
void setLabel(const utils::ImmutableCString& label) {
#if FILAMENT_METAL_DEBUG_LABELS
if (label.empty()) {
return;
+4 -2
View File
@@ -25,8 +25,9 @@
#include <backend/SamplerDescriptor.h>
#include <utils/compiler.h>
#include <utils/FixedCapacityVector.h>
#include <utils/Log.h>
#include <utils/compiler.h>
#include <utils/debug.h>
#include <functional>
@@ -69,7 +70,8 @@ private:
MetalContext* mContext;
ShaderModel getShaderModel() const noexcept final;
ShaderLanguage getShaderLanguage() const noexcept final;
utils::FixedCapacityVector<ShaderLanguage> getShaderLanguages(
ShaderLanguage preferredLanguage) const noexcept final;
// Overrides the default implementation by wrapping the call to fn in an @autoreleasepool block.
void execute(std::function<void(void)> const& fn) noexcept final;
+38 -29
View File
@@ -42,6 +42,7 @@
#include <utils/Logger.h>
#include <utils/Panic.h>
#include <utils/sstream.h>
#include <utils/ImmutableCString.h>
#include <algorithm>
@@ -418,14 +419,14 @@ void MetalDriver::finish(int) {
}
void MetalDriver::createVertexBufferInfoR(Handle<HwVertexBufferInfo> vbih, uint8_t bufferCount,
uint8_t attributeCount, AttributeArray attributes, utils::CString&& tag) {
uint8_t attributeCount, AttributeArray attributes, utils::ImmutableCString&& tag) {
construct_handle<MetalVertexBufferInfo>(vbih, *mContext,
bufferCount, attributeCount, attributes);
mHandleAllocator.associateTagToHandle(vbih.getId(), std::move(tag));
}
void MetalDriver::createVertexBufferR(Handle<HwVertexBuffer> vbh,
uint32_t vertexCount, Handle<HwVertexBufferInfo> vbih, utils::CString&& tag) {
uint32_t vertexCount, Handle<HwVertexBufferInfo> vbih, utils::ImmutableCString&& tag) {
MetalVertexBufferInfo const* const vbi = handle_cast<const MetalVertexBufferInfo>(vbih);
construct_handle<MetalVertexBuffer>(vbh, *mContext, vertexCount, vbi->bufferCount, vbih);
mHandleAllocator.associateTagToHandle(vbh.getId(), std::move(tag));
@@ -433,7 +434,7 @@ void MetalDriver::createVertexBufferR(Handle<HwVertexBuffer> vbh,
}
void MetalDriver::createIndexBufferR(Handle<HwIndexBuffer> ibh, ElementType elementType,
uint32_t indexCount, BufferUsage usage, utils::CString&& tag) {
uint32_t indexCount, BufferUsage usage, utils::ImmutableCString&& tag) {
auto elementSize = (uint8_t)getElementTypeSize(elementType);
auto* indexBuffer =
construct_handle<MetalIndexBuffer>(ibh, *mContext, usage, elementSize, indexCount);
@@ -446,7 +447,7 @@ void MetalDriver::createIndexBufferR(Handle<HwIndexBuffer> ibh, ElementType elem
}
void MetalDriver::createBufferObjectR(Handle<HwBufferObject> boh, uint32_t byteCount,
BufferObjectBinding bindingType, BufferUsage usage, utils::CString&& tag) {
BufferObjectBinding bindingType, BufferUsage usage, utils::ImmutableCString&& tag) {
auto* bufferObject =
construct_handle<MetalBufferObject>(boh, *mContext, bindingType, usage, byteCount);
FILAMENT_CHECK_POSTCONDITION(bufferObject->getBuffer()->wasAllocationSuccessful())
@@ -488,7 +489,7 @@ inline const char* stringify(SamplerType samplerType) {
void MetalDriver::createTextureR(Handle<HwTexture> th, SamplerType target, uint8_t levels,
TextureFormat format, uint8_t samples, uint32_t width, uint32_t height,
uint32_t depth, TextureUsage usage, utils::CString&& tag) {
uint32_t depth, TextureUsage usage, utils::ImmutableCString&& tag) {
// Clamp sample count to what the device supports.
auto& sc = mContext->sampleCountLookup;
samples = sc[std::min(MAX_SAMPLE_COUNT, samples)];
@@ -508,7 +509,7 @@ void MetalDriver::createTextureR(Handle<HwTexture> th, SamplerType target, uint8
}
void MetalDriver::createTextureViewR(Handle<HwTexture> th, Handle<HwTexture> srch,
uint8_t baseLevel, uint8_t levelCount, utils::CString&& tag) {
uint8_t baseLevel, uint8_t levelCount, utils::ImmutableCString&& tag) {
MetalTexture const* src = handle_cast<MetalTexture>(srch);
MetalTexture* texture =
construct_handle<MetalTexture>(th, *mContext, src, baseLevel, levelCount);
@@ -519,7 +520,7 @@ void MetalDriver::createTextureViewR(Handle<HwTexture> th, Handle<HwTexture> src
void MetalDriver::createTextureViewSwizzleR(Handle<HwTexture> th, Handle<HwTexture> srch,
backend::TextureSwizzle r, backend::TextureSwizzle g, backend::TextureSwizzle b,
backend::TextureSwizzle a, utils::CString&& tag) {
backend::TextureSwizzle a, utils::ImmutableCString&& tag) {
MetalTexture const* src = handle_cast<MetalTexture>(srch);
MetalTexture* texture = construct_handle<MetalTexture>(th, *mContext, src, r, g, b, a);
mContext->textures.insert(texture);
@@ -531,13 +532,13 @@ void MetalDriver::createTextureExternalImage2R(Handle<HwTexture> th,
backend::SamplerType target,
backend::TextureFormat format,
uint32_t width, uint32_t height, backend::TextureUsage usage,
Platform::ExternalImageHandleRef image, utils::CString&& tag) {
Platform::ExternalImageHandleRef image, utils::ImmutableCString&& tag) {
// FIXME: implement createTextureExternalImage2R
}
void MetalDriver::createTextureExternalImageR(Handle<HwTexture> th, backend::SamplerType target,
backend::TextureFormat format, uint32_t width, uint32_t height, backend::TextureUsage usage,
void* image, utils::CString&& tag) {
void* image, utils::ImmutableCString&& tag) {
MetalTexture* texture = construct_handle<MetalTexture>(th, *mContext, format, width, height,
usage, (CVPixelBufferRef) image);
mContext->textures.insert(texture);
@@ -550,7 +551,7 @@ void MetalDriver::createTextureExternalImageR(Handle<HwTexture> th, backend::Sam
void MetalDriver::createTextureExternalImagePlaneR(Handle<HwTexture> th,
backend::TextureFormat format, uint32_t width, uint32_t height, backend::TextureUsage usage,
void* image, uint32_t plane, utils::CString&& tag) {
void* image, uint32_t plane, utils::ImmutableCString&& tag) {
MetalTexture* texture = construct_handle<MetalTexture>(th, *mContext, format, width, height,
usage, (CVPixelBufferRef) image, plane);
mContext->textures.insert(texture);
@@ -564,7 +565,7 @@ void MetalDriver::createTextureExternalImagePlaneR(Handle<HwTexture> th,
void MetalDriver::importTextureR(Handle<HwTexture> th, intptr_t i,
SamplerType target, uint8_t levels,
TextureFormat format, uint8_t samples, uint32_t width, uint32_t height,
uint32_t depth, TextureUsage usage, utils::CString&& tag) {
uint32_t depth, TextureUsage usage, utils::ImmutableCString&& tag) {
id<MTLTexture> metalTexture = (id<MTLTexture>) CFBridgingRelease((void*) i);
FILAMENT_CHECK_PRECONDITION(metalTexture.width == width)
<< "Imported id<MTLTexture> width (" << metalTexture.width
@@ -588,13 +589,13 @@ void MetalDriver::importTextureR(Handle<HwTexture> th, intptr_t i,
void MetalDriver::createRenderPrimitiveR(Handle<HwRenderPrimitive> rph,
Handle<HwVertexBuffer> vbh, Handle<HwIndexBuffer> ibh,
PrimitiveType pt, utils::CString&& tag) {
PrimitiveType pt, utils::ImmutableCString&& tag) {
construct_handle<MetalRenderPrimitive>(rph);
MetalDriver::setRenderPrimitiveBuffer(rph, pt, vbh, ibh);
mHandleAllocator.associateTagToHandle(rph.getId(), std::move(tag));
}
void MetalDriver::createProgramR(Handle<HwProgram> rph, Program&& program, utils::CString&& tag) {
void MetalDriver::createProgramR(Handle<HwProgram> rph, Program&& program, utils::ImmutableCString&& tag) {
#if FILAMENT_METAL_DEBUG_LOG
auto handleId = rph.getId();
DEBUG_LOG("createProgramR(rph = %d, program = ", handleId);
@@ -604,7 +605,7 @@ void MetalDriver::createProgramR(Handle<HwProgram> rph, Program&& program, utils
mHandleAllocator.associateTagToHandle(rph.getId(), std::move(tag));
}
void MetalDriver::createDefaultRenderTargetR(Handle<HwRenderTarget> rth, utils::CString&& tag) {
void MetalDriver::createDefaultRenderTargetR(Handle<HwRenderTarget> rth, utils::ImmutableCString&& tag) {
construct_handle<MetalRenderTarget>(rth, mContext);
mHandleAllocator.associateTagToHandle(rth.getId(), std::move(tag));
}
@@ -612,7 +613,7 @@ void MetalDriver::createDefaultRenderTargetR(Handle<HwRenderTarget> rth, utils::
void MetalDriver::createRenderTargetR(Handle<HwRenderTarget> rth,
TargetBufferFlags targetBufferFlags, uint32_t width, uint32_t height,
uint8_t samples, uint8_t layerCount, MRT color,
TargetBufferInfo depth, TargetBufferInfo stencil, utils::CString&& tag) {
TargetBufferInfo depth, TargetBufferInfo stencil, utils::ImmutableCString&& tag) {
FILAMENT_CHECK_PRECONDITION(!isInRenderPass(mContext))
<< "createRenderTarget must be called outside of a render pass.";
// Clamp sample count to what the device supports.
@@ -659,14 +660,14 @@ void MetalDriver::createRenderTargetR(Handle<HwRenderTarget> rth,
mHandleAllocator.associateTagToHandle(rth.getId(), std::move(tag));
}
void MetalDriver::createFenceR(Handle<HwFence> fh, utils::CString&& tag) {
void MetalDriver::createFenceR(Handle<HwFence> fh, utils::ImmutableCString&& tag) {
auto* fence = handle_cast<MetalFence>(fh);
fence->encode();
mHandleAllocator.associateTagToHandle(fh.getId(), std::move(tag));
}
void MetalDriver::createSwapChainR(Handle<HwSwapChain> sch, void* nativeWindow, uint64_t flags,
utils::CString&& tag) {
utils::ImmutableCString&& tag) {
// TODO: support MSAA swapchain
if (UTILS_UNLIKELY(flags & SWAP_CHAIN_CONFIG_APPLE_CVPIXELBUFFER)) {
@@ -683,18 +684,18 @@ void MetalDriver::createSwapChainR(Handle<HwSwapChain> sch, void* nativeWindow,
}
void MetalDriver::createSwapChainHeadlessR(Handle<HwSwapChain> sch,
uint32_t width, uint32_t height, uint64_t flags, utils::CString&& tag) {
uint32_t width, uint32_t height, uint64_t flags, utils::ImmutableCString&& tag) {
construct_handle<MetalSwapChain>(sch, *mContext, mPlatform, width, height, flags);
mHandleAllocator.associateTagToHandle(sch.getId(), std::move(tag));
}
void MetalDriver::createSyncR(Handle<HwSync> sh, utils::CString&& tag) {
void MetalDriver::createSyncR(Handle<HwSync> sh, utils::ImmutableCString&& tag) {
// TODO: Ensure sync is active, and then invoke and clear all pending
// callbacks.
mHandleAllocator.associateTagToHandle(sh.getId(), std::move(tag));
}
void MetalDriver::createTimerQueryR(Handle<HwTimerQuery> tqh, utils::CString&& tag) {
void MetalDriver::createTimerQueryR(Handle<HwTimerQuery> tqh, utils::ImmutableCString&& tag) {
// nothing to do, timer query was constructed in createTimerQueryS
mHandleAllocator.associateTagToHandle(tqh.getId(), std::move(tag));
}
@@ -733,12 +734,12 @@ const char* toString(DescriptorFlags flags) {
}
void MetalDriver::createDescriptorSetLayoutR(
Handle<HwDescriptorSetLayout> dslh, DescriptorSetLayout&& info, utils::CString&& tag) {
Handle<HwDescriptorSetLayout> dslh, DescriptorSetLayout&& info, utils::ImmutableCString&& tag) {
#if FILAMENT_METAL_DEBUG_LOG == 1
const char* labelStr = "";
std::visit([&labelStr](auto&& arg) {
using T = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<T, utils::CString> || std::is_same_v<T, utils::StaticString>) {
if constexpr (std::is_same_v<T, utils::ImmutableCString> || std::is_same_v<T, utils::StaticString>) {
labelStr = arg.c_str();
}
}, info.label);
@@ -758,7 +759,7 @@ void MetalDriver::createDescriptorSetLayoutR(
}
void MetalDriver::createDescriptorSetR(
Handle<HwDescriptorSet> dsh, Handle<HwDescriptorSetLayout> dslh, utils::CString&& tag) {
Handle<HwDescriptorSet> dsh, Handle<HwDescriptorSetLayout> dslh, utils::ImmutableCString&& tag) {
DEBUG_LOG("createDescriptorSetR(dsh = %d, dslh = %d)\n", dsh.getId(), dslh.getId());
MetalDescriptorSetLayout* layout = handle_cast<MetalDescriptorSetLayout>(dslh);
MetalDescriptorSet* ds = construct_handle<MetalDescriptorSet>(dsh, layout);
@@ -1002,15 +1003,19 @@ ShaderModel MetalDriver::getShaderModel() const noexcept {
#endif
}
ShaderLanguage MetalDriver::getShaderLanguage() const noexcept {
return ShaderLanguage::MSL;
utils::FixedCapacityVector<ShaderLanguage> MetalDriver::getShaderLanguages(
ShaderLanguage preferredLanguage) const noexcept {
if (preferredLanguage == backend::ShaderLanguage::MSL) {
return { backend::ShaderLanguage::MSL, backend::ShaderLanguage::METAL_LIBRARY };
}
return { backend::ShaderLanguage::METAL_LIBRARY, backend::ShaderLanguage::MSL };
}
Handle<HwStream> MetalDriver::createStreamNative(void* stream, utils::CString tag) {
Handle<HwStream> MetalDriver::createStreamNative(void* stream, utils::ImmutableCString tag) {
return {};
}
Handle<HwStream> MetalDriver::createStreamAcquired(utils::CString tag) {
Handle<HwStream> MetalDriver::createStreamAcquired(utils::ImmutableCString tag) {
return {};
}
@@ -1038,11 +1043,15 @@ void MetalDriver::destroyFence(Handle<HwFence> fh) {
}
FenceStatus MetalDriver::getFenceStatus(Handle<HwFence> fh) {
return fenceWait(fh, 0);
}
FenceStatus MetalDriver::fenceWait(FenceHandle fh, uint64_t const timeout) {
auto* fence = handle_cast<MetalFence>(fh);
if (!fence) {
return FenceStatus::ERROR;
}
return fence->wait(0);
return fence->wait(timeout);
}
void MetalDriver::destroySync(Handle<HwSync> sh) {
@@ -2223,7 +2232,7 @@ MemoryMappedBufferHandle MetalDriver::mapBufferS() noexcept {
void MetalDriver::mapBufferR(MemoryMappedBufferHandle mmbh,
BufferObjectHandle boh, size_t offset,
size_t size, MapBufferAccessFlags access, utils::CString&& tag) {
size_t size, MapBufferAccessFlags access, utils::ImmutableCString&& tag) {
construct_handle<MetalMemoryMappedBuffer>(mmbh, boh, offset, size, access);
mHandleAllocator.associateTagToHandle(mmbh.getId(), std::move(tag));
}
+3 -3
View File
@@ -267,7 +267,7 @@ public:
static MTLPixelFormat decidePixelFormat(MetalContext* context, TextureFormat format);
void setLabel(const utils::CString& label) {
void setLabel(const utils::ImmutableCString& label) {
#if FILAMENT_METAL_DEBUG_LABELS
if (label.empty()) {
return;
@@ -494,7 +494,7 @@ struct MetalDescriptorSet : public HwDescriptorSet {
void finalize(MetalDriver* driver);
void setLabel(const utils::CString& l) {
void setLabel(const utils::ImmutableCString& l) {
#if FILAMENT_METAL_DEBUG_LABELS
if (l.empty()) {
return;
@@ -527,7 +527,7 @@ struct MetalDescriptorSet : public HwDescriptorSet {
std::array<TrackedMetalBuffer, Program::SHADER_TYPE_COUNT> cachedBuffer = { nil };
#if FILAMENT_METAL_DEBUG_LABELS
utils::CString label;
utils::ImmutableCString label;
#endif
};
@@ -134,6 +134,7 @@ bool MetalShaderCompiler::isParallelShaderCompileSupported() const noexcept {
case ShaderLanguage::ESSL3:
case ShaderLanguage::SPIRV:
case ShaderLanguage::WGSL:
case ShaderLanguage::UNSPECIFIED:
break;
}
@@ -152,14 +153,15 @@ bool MetalShaderCompiler::isParallelShaderCompileSupported() const noexcept {
MTLFunctionConstantValues* constants = [MTLFunctionConstantValues new];
auto const& specializationConstants = program.getSpecializationConstants();
for (auto const& sc : specializationConstants) {
for (size_t i = 0; i < specializationConstants.size(); i++) {
auto const& sc = specializationConstants[i];
const std::array<MTLDataType, 3> types{
MTLDataTypeInt, MTLDataTypeFloat, MTLDataTypeBool };
std::visit([&sc, constants, type = types[sc.value.index()]](auto&& arg) {
std::visit([i, constants, type = types[sc.index()]](auto&& arg) {
[constants setConstantValue:&arg
type:type
atIndex:sc.id];
}, sc.value);
atIndex:i];
}, sc);
}
id<MTLFunction> function = [library newFunctionWithName:@"main0"
+5 -3
View File
@@ -155,9 +155,11 @@ id<MTLSamplerState> SamplerStateCreator::operator()(id<MTLDevice> device,
// Older Apple devices (and the simulator) don't support setting a comparison function in
// MTLSamplerDescriptor.
// In practice, this means shadows are not supported when running in the simulator.
if (![device supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily3_v1]) {
LOG(WARNING) << "Warning: sample comparison not supported by this GPU";
samplerDescriptor.compareFunction = MTLCompareFunctionNever;
if (samplerDescriptor.compareFunction != MTLCompareFunctionNever) {
if (![device supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily3_v1]) {
LOG(WARNING) << "Warning: sample comparison not supported by this GPU";
samplerDescriptor.compareFunction = MTLCompareFunctionNever;
}
}
#endif
+1 -1
View File
@@ -52,7 +52,7 @@ PlatformMetal::~PlatformMetal() noexcept {
delete pImpl;
}
Driver* PlatformMetal::createDriver(void* /*sharedContext*/, const Platform::DriverConfig& driverConfig) noexcept {
Driver* PlatformMetal::createDriver(void* /*sharedContext*/, const Platform::DriverConfig& driverConfig) {
pImpl->mDrawableFailureBehavior = driverConfig.metalDisablePanicOnDrawableFailure
? DrawableFailureBehavior::ABORT_FRAME
: DrawableFailureBehavior::PANIC;
+18 -4
View File
@@ -21,6 +21,8 @@
#include "noop/NoopDriver.h"
#include "CommandStreamDispatcher.h"
#include <utils/ImmutableCString.h>
#include <stdint.h>
namespace filament::backend {
@@ -45,8 +47,16 @@ ShaderModel NoopDriver::getShaderModel() const noexcept {
#endif
}
ShaderLanguage NoopDriver::getShaderLanguage() const noexcept {
return ShaderLanguage::ESSL3;
utils::FixedCapacityVector<ShaderLanguage> NoopDriver::getShaderLanguages(
ShaderLanguage /*preferredLanguage*/) const noexcept {
return {
ShaderLanguage::ESSL3,
ShaderLanguage::ESSL1,
ShaderLanguage::SPIRV,
ShaderLanguage::MSL,
ShaderLanguage::METAL_LIBRARY,
ShaderLanguage::WGSL,
};
}
// explicit instantiation of the Dispatcher
@@ -127,11 +137,11 @@ void NoopDriver::destroyDescriptorSetLayout(Handle<HwDescriptorSetLayout> tqh) {
void NoopDriver::destroyDescriptorSet(Handle<HwDescriptorSet> tqh) {
}
Handle<HwStream> NoopDriver::createStreamNative(void* nativeStream, utils::CString tag) {
Handle<HwStream> NoopDriver::createStreamNative(void* nativeStream, utils::ImmutableCString tag) {
return {};
}
Handle<HwStream> NoopDriver::createStreamAcquired(utils::CString tag) {
Handle<HwStream> NoopDriver::createStreamAcquired(utils::ImmutableCString tag) {
return {};
}
@@ -160,6 +170,10 @@ FenceStatus NoopDriver::getFenceStatus(Handle<HwFence> fh) {
return FenceStatus::CONDITION_SATISFIED;
}
FenceStatus NoopDriver::fenceWait(Handle<HwFence> fh, uint64_t timeout) {
return FenceStatus::ERROR;
}
// We create all textures using VK_IMAGE_TILING_OPTIMAL, so our definition of "supported" is that
// the GPU supports the given texture format with non-zero optimal tiling features.
bool NoopDriver::isTextureFormatSupported(TextureFormat format) {
+3 -1
View File
@@ -20,6 +20,7 @@
#include "private/backend/Driver.h"
#include "DriverBase.h"
#include <utils/FixedCapacityVector.h>
#include <utils/compiler.h>
namespace filament::backend {
@@ -34,7 +35,8 @@ public:
private:
ShaderModel getShaderModel() const noexcept final;
ShaderLanguage getShaderLanguage() const noexcept final;
utils::FixedCapacityVector<ShaderLanguage> getShaderLanguages(
ShaderLanguage preferredLanguage) const noexcept final;
uint64_t nextFakeHandle = 1;
+1 -1
View File
@@ -20,7 +20,7 @@
namespace filament::backend {
Driver* PlatformNoop::createDriver(void* sharedGLContext, const Platform::DriverConfig& driverConfig) noexcept {
Driver* PlatformNoop::createDriver(void* sharedGLContext, const Platform::DriverConfig& driverConfig) {
return NoopDriver::create();
}
+1 -1
View File
@@ -31,7 +31,7 @@ public:
protected:
Driver* createDriver(void* sharedContext, const Platform::DriverConfig& driverConfig) noexcept override;
Driver* createDriver(void* sharedContext, const Platform::DriverConfig& driverConfig) override;
};
} // namespace filament
@@ -33,6 +33,7 @@
#include <utils/BitmaskEnum.h>
#include <utils/Log.h>
#include <utils/Logger.h>
#include <utils/Panic.h>
#include <utils/bitset.h>
#include <utils/compiler.h>
@@ -49,7 +50,7 @@
namespace filament::backend {
GLDescriptorSet::GLDescriptorSet(OpenGLContext& gl, DescriptorSetLayoutHandle dslh,
GLDescriptorSetLayout const* layout) noexcept
GLDescriptorSetLayout const* layout)
: descriptors(layout->maxDescriptorBinding + 1),
dslh(std::move(dslh)) {
@@ -156,8 +157,9 @@ void GLDescriptorSet::update(OpenGLContext&,
arg.bo = bo;
arg.offset = uint32_t(offset);
} else {
// API usage error. User asked to update the wrong type of descriptor.
PANIC_PRECONDITION("descriptor %d is not a buffer", +binding);
// User asked to update the wrong type of descriptor. This should never happen
// because we're checking that on the filament side
LOG(ERROR) << "descriptor " << +binding << " is not a buffer";
}
}, descriptors[binding].desc);
}
@@ -214,8 +216,9 @@ void GLDescriptorSet::update(OpenGLContext& gl, HandleAllocatorGL& handleAllocat
arg.params = params;
}
} else {
// API usage error. User asked to update the wrong type of descriptor.
PANIC_PRECONDITION("descriptor %d is not a texture", +binding);
// User asked to update the wrong type of descriptor. This should never happen
// because we're checking that on the filament side
LOG(ERROR) << "descriptor " << +binding << " is not a texture";
}
}, descriptors[binding].desc);
}
@@ -52,7 +52,7 @@ struct GLDescriptorSet : public HwDescriptorSet {
using HwDescriptorSet::HwDescriptorSet;
GLDescriptorSet(OpenGLContext& gl, DescriptorSetLayoutHandle dslh,
GLDescriptorSetLayout const* layout) noexcept;
GLDescriptorSetLayout const* layout);
// update a buffer descriptor in the set
void update(OpenGLContext& gl,
+35 -12
View File
@@ -277,7 +277,7 @@ void OpenGLContext::terminate() noexcept {
}
void OpenGLContext::destroyWithContext(
size_t index, std::function<void(OpenGLContext&)> const& closure) noexcept {
size_t index, std::function<void(OpenGLContext&)> const& closure) {
if (index == 0) {
// Note: we only need to delay the destruction of objects on the unprotected context
// (index 0) because the protected context is always immediately destroyed and all its
@@ -296,7 +296,7 @@ void OpenGLContext::unbindEverything() noexcept {
// worry about.
}
void OpenGLContext::synchronizeStateAndCache(size_t index) noexcept {
void OpenGLContext::synchronizeStateAndCache(size_t index) {
// if we're just switching back to context 0, run all the pending destructors
if (index == 0) {
@@ -507,20 +507,40 @@ void OpenGLContext::initBugs(Bugs* bugs, Extensions const& exts,
} else if (strstr(renderer, "Mali")) {
// ARM GPU
bugs->vao_doesnt_store_element_array_buffer_binding = true;
// We have run into several problems with timer queries on Mali-Gxx:
// - timer queries seem to cause memory corruptions in some cases on some devices
// (see b/233754398)
// - appeared at least in: "OpenGL ES 3.2 v1.r26p0-01eac0"
// - wasn't present in: "OpenGL ES 3.2 v1.r32p1-00pxl1"
// - timer queries sometime crash with an NPE (see b/273759031)
// (see b/273759031)
// - possibly not present in: "OpenGL ES 3.2 v1.r46p0"
bugs->dont_use_timer_query = true;
// at least some version of Mali have problems with framebuffer_fetch
// (see b/445721121, https://github.com/google/filament/issues/7794)
bugs->disable_framebuffer_fetch_extension = true;
if (strstr(renderer, "Mali-T")) {
bugs->disable_glFlush = true;
bugs->disable_shared_context_draws = true;
// We have not verified that timer queries work on Mali-T, so we disable to be safe.
bugs->dont_use_timer_query = true;
}
if (strstr(renderer, "Mali-G")) {
// We have run into several problems with timer queries on Mali-Gxx:
// - timer queries seem to cause memory corruptions in some cases on some devices
// (see b/233754398)
// - appeared at least in: "OpenGL ES 3.2 v1.r26p0-01eac0"
// - wasn't present in: "OpenGL ES 3.2 v1.r32p1-00pxl1"
// - timer queries sometime crash with an NPE (see b/273759031)
bugs->dont_use_timer_query = true;
int maj, min, driverVersion, driverRelease;
int const c = sscanf(version, "OpenGL ES %d.%d v%d.r%d",
&maj, &min, &driverVersion, &driverRelease);
if (UTILS_LIKELY(c == 4)) {
// we were able to parse the version string
if (driverVersion > 1 || (driverVersion == 1 && driverRelease >= 46)) {
// this driver version is known to be good
bugs->dont_use_timer_query = false;
}
if (driverVersion > 1 || (driverVersion == 1 && driverRelease >= 53)) {
// this driver version is known to be good
bugs->disable_framebuffer_fetch_extension = false;
}
}
}
// Mali seems to have no problem with this (which is good for us)
bugs->allow_read_only_ancillary_feedback_loop = true;
@@ -740,6 +760,7 @@ void OpenGLContext::initExtensionsGLES(Extensions* ext, GLint major, GLint minor
ext->EXT_texture_compression_rgtc = exts.has("GL_EXT_texture_compression_rgtc"sv);
ext->EXT_texture_compression_bptc = exts.has("GL_EXT_texture_compression_bptc"sv);
ext->EXT_texture_cube_map_array = exts.has("GL_EXT_texture_cube_map_array"sv) || exts.has("GL_OES_texture_cube_map_array"sv);
ext->EXT_texture_filter_anisotropic = exts.has("GL_EXT_texture_filter_anisotropic"sv);
ext->GOOGLE_cpp_style_line_directive = exts.has("GL_GOOGLE_cpp_style_line_directive"sv);
ext->KHR_debug = exts.has("GL_KHR_debug"sv);
ext->KHR_parallel_shader_compile = exts.has("GL_KHR_parallel_shader_compile"sv);
@@ -845,10 +866,12 @@ GLuint OpenGLContext::bindFramebuffer(GLenum target, GLuint buffer) noexcept {
if (UTILS_UNLIKELY(buffer == 0)) {
// we're binding the default frame buffer, resolve its actual name
auto& defaultFboForThisContext = mDefaultFbo[contextIndex];
if (UTILS_UNLIKELY(!defaultFboForThisContext.has_value())) {
defaultFboForThisContext = GLuint(mPlatform.getDefaultFramebufferObject());
}
buffer = defaultFboForThisContext.value();
// by construction, defaultFboForThisContext has a value. value_or() avoids a throwing call.
buffer = defaultFboForThisContext.value_or(0);
}
bindFramebufferResolved(target, buffer);
return buffer;
+3 -2
View File
@@ -193,7 +193,7 @@ public:
void deleteBuffer(GLuint buffer, GLenum target) noexcept;
void deleteVertexArray(GLuint vao) noexcept;
void destroyWithContext(size_t index, std::function<void(OpenGLContext&)> const& closure) noexcept;
void destroyWithContext(size_t index, std::function<void(OpenGLContext&)> const& closure);
// glGet*() values
struct Gets {
@@ -338,6 +338,7 @@ public:
// 'OpenGL error 0x502 (GL_INVALID_OPERATION) in "draw2" at line 4389'
// This coincides with the use of framebuffer fetch (ColorGradingAsSubpass). We disable
// framebuffer fetch in the case of llvmpipe.
// Some Mali drivers also have problems with this (b/445721121)
bool disable_framebuffer_fetch_extension;
} bugs = {};
@@ -497,7 +498,7 @@ public:
} procs{};
void unbindEverything() noexcept;
void synchronizeStateAndCache(size_t index) noexcept;
void synchronizeStateAndCache(size_t index);
#ifndef FILAMENT_SILENCE_NOT_SUPPORTED_BY_ES2
GLuint getSamplerSlow(SamplerParams sp) const noexcept;
+120 -96
View File
@@ -50,6 +50,7 @@
#include <type_traits>
#include <utils/BitmaskEnum.h>
#include <utils/CString.h>
#include <utils/ImmutableCString.h>
#include <utils/FixedCapacityVector.h>
#include <utils/Invocable.h>
#include <utils/Logger.h>
@@ -368,8 +369,9 @@ ShaderModel OpenGLDriver::getShaderModel() const noexcept {
return mContext.getShaderModel();
}
ShaderLanguage OpenGLDriver::getShaderLanguage() const noexcept {
return mContext.isES2() ? ShaderLanguage::ESSL1 : ShaderLanguage::ESSL3;
utils::FixedCapacityVector<ShaderLanguage> OpenGLDriver::getShaderLanguages(
ShaderLanguage /*preferredLanguage*/) const noexcept {
return { mContext.isES2() ? ShaderLanguage::ESSL1 : ShaderLanguage::ESSL3 };
}
// ------------------------------------------------------------------------------------------------
@@ -393,7 +395,7 @@ void OpenGLDriver::setPushConstant(ShaderStage const stage, uint8_t const index,
}
#endif
Slice<std::pair<GLint, ConstantType>> constants;
Slice<const std::pair<GLint, ConstantType>> constants;
if (stage == ShaderStage::VERTEX) {
constants = mCurrentPushConstants->vertexConstants;
} else if (stage == ShaderStage::FRAGMENT) {
@@ -660,7 +662,7 @@ void OpenGLDriver::createVertexBufferInfoR(
uint8_t bufferCount,
uint8_t attributeCount,
AttributeArray attributes,
CString&& tag) {
ImmutableCString&& tag) {
DEBUG_MARKER()
construct<GLVertexBufferInfo>(vbih, bufferCount, attributeCount, attributes);
mHandleAllocator.associateTagToHandle(vbih.getId(), std::move(tag));
@@ -670,7 +672,7 @@ void OpenGLDriver::createVertexBufferR(
Handle<HwVertexBuffer> vbh,
uint32_t vertexCount,
Handle<HwVertexBufferInfo> vbih,
CString&& tag) {
ImmutableCString&& tag) {
DEBUG_MARKER()
construct<GLVertexBuffer>(vbh, vertexCount, vbih);
mHandleAllocator.associateTagToHandle(vbh.getId(), std::move(tag));
@@ -681,7 +683,7 @@ void OpenGLDriver::createIndexBufferR(
ElementType const elementType,
uint32_t indexCount,
BufferUsage const usage,
CString&& tag) {
ImmutableCString&& tag) {
DEBUG_MARKER()
auto& gl = mContext;
@@ -697,7 +699,7 @@ void OpenGLDriver::createIndexBufferR(
}
void OpenGLDriver::createBufferObjectR(Handle<HwBufferObject> boh, uint32_t byteCount,
BufferObjectBinding bindingType, BufferUsage usage, CString&& tag) {
BufferObjectBinding bindingType, BufferUsage usage, ImmutableCString&& tag) {
DEBUG_MARKER()
assert_invariant(byteCount > 0);
@@ -724,7 +726,7 @@ void OpenGLDriver::createBufferObjectR(Handle<HwBufferObject> boh, uint32_t byte
void OpenGLDriver::createRenderPrimitiveR(Handle<HwRenderPrimitive> rph,
Handle<HwVertexBuffer> vbh, Handle<HwIndexBuffer> ibh,
PrimitiveType const pt, CString&& tag) {
PrimitiveType const pt, ImmutableCString&& tag) {
DEBUG_MARKER()
auto& gl = mContext;
@@ -760,32 +762,9 @@ void OpenGLDriver::createRenderPrimitiveR(Handle<HwRenderPrimitive> rph,
mHandleAllocator.associateTagToHandle(rph.getId(), std::move(tag));
}
void OpenGLDriver::createProgramR(Handle<HwProgram> ph, Program&& program, CString&& tag) {
void OpenGLDriver::createProgramR(Handle<HwProgram> ph, Program&& program, ImmutableCString&& tag) {
DEBUG_MARKER()
if (UTILS_UNLIKELY(mContext.isES2())) {
// Here we patch the specialization constants to enable or not the rec709 output
// color space emulation in this program. Obviously, the backend shouldn't know about
// specific spec-constants, so we need to handle failures gracefully. This cannot be
// done at Material creation time because only the backend has access to
// Platform.isSRGBSwapChainSupported().
if (!mPlatform.isSRGBSwapChainSupported()) {
auto& specializationConstants = program.getSpecializationConstants();
auto const pos = std::find_if(specializationConstants.begin(), specializationConstants.end(),
[](auto&& sc) {
// This constant must match
// ReservedSpecializationConstants::CONFIG_SRGB_SWAPCHAIN_EMULATION
// which we can't use here because it's defined in EngineEnums.h.
// (we're breaking layering here, but it's for the good cause).
return sc.id == 3;
});
if (pos != specializationConstants.end()) {
pos->value = true;
}
}
}
construct<OpenGLProgram>(ph, *this, std::move(program));
CHECK_GL_ERROR()
mHandleAllocator.associateTagToHandle(ph.getId(), std::move(tag));
@@ -893,7 +872,7 @@ void OpenGLDriver::textureStorage(GLTexture* t,
void OpenGLDriver::createTextureR(Handle<HwTexture> th, SamplerType target, uint8_t levels,
TextureFormat format, uint8_t samples, uint32_t width, uint32_t height, uint32_t depth,
TextureUsage usage, CString&& tag) {
TextureUsage usage, ImmutableCString&& tag) {
DEBUG_MARKER()
GLenum internalFormat = getInternalFormat(format);
@@ -986,7 +965,7 @@ void OpenGLDriver::createTextureR(Handle<HwTexture> th, SamplerType target, uint
}
void OpenGLDriver::createTextureViewR(Handle<HwTexture> th,
Handle<HwTexture> srch, uint8_t const baseLevel, uint8_t const levelCount, CString&& tag) {
Handle<HwTexture> srch, uint8_t const baseLevel, uint8_t const levelCount, ImmutableCString&& tag) {
DEBUG_MARKER()
GLTexture const* const src = handle_cast<GLTexture const*>(srch);
@@ -1034,7 +1013,7 @@ void OpenGLDriver::createTextureViewR(Handle<HwTexture> th,
void OpenGLDriver::createTextureViewSwizzleR(Handle<HwTexture> th, Handle<HwTexture> srch,
TextureSwizzle const r, TextureSwizzle const g, TextureSwizzle const b, TextureSwizzle const a,
CString&& tag) {
ImmutableCString&& tag) {
DEBUG_MARKER()
GLTexture const* const src = handle_cast<GLTexture const*>(srch);
@@ -1100,7 +1079,7 @@ void OpenGLDriver::createTextureViewSwizzleR(Handle<HwTexture> th, Handle<HwText
void OpenGLDriver::createTextureExternalImage2R(Handle<HwTexture> th, SamplerType target,
TextureFormat format, uint32_t width, uint32_t height, TextureUsage usage,
Platform::ExternalImageHandleRef image, CString&& tag) {
Platform::ExternalImageHandleRef image, ImmutableCString&& tag) {
DEBUG_MARKER()
usage |= TextureUsage::SAMPLEABLE;
@@ -1152,7 +1131,7 @@ void OpenGLDriver::createTextureExternalImage2R(Handle<HwTexture> th, SamplerTyp
void OpenGLDriver::createTextureExternalImageR(Handle<HwTexture> th, SamplerType target,
TextureFormat format, uint32_t width, uint32_t height, TextureUsage usage, void* image,
CString&& tag) {
ImmutableCString&& tag) {
DEBUG_MARKER()
usage |= TextureUsage::SAMPLEABLE;
@@ -1203,13 +1182,13 @@ void OpenGLDriver::createTextureExternalImageR(Handle<HwTexture> th, SamplerType
void OpenGLDriver::createTextureExternalImagePlaneR(Handle<HwTexture> th,
TextureFormat format, uint32_t width, uint32_t height, TextureUsage usage,
void* image, uint32_t plane, CString&&) {
void* image, uint32_t plane, ImmutableCString&&) {
// not relevant for the OpenGL backend
}
void OpenGLDriver::importTextureR(Handle<HwTexture> th, intptr_t const id,
SamplerType target, uint8_t levels, TextureFormat format, uint8_t samples,
uint32_t width, uint32_t height, uint32_t depth, TextureUsage usage, CString&& tag) {
uint32_t width, uint32_t height, uint32_t depth, TextureUsage usage, ImmutableCString&& tag) {
DEBUG_MARKER()
auto const& gl = mContext;
@@ -1664,7 +1643,7 @@ void OpenGLDriver::renderBufferStorage(GLuint const rbo, GLenum internalformat,
}
void OpenGLDriver::createDefaultRenderTargetR(
Handle<HwRenderTarget> rth, CString&& tag) {
Handle<HwRenderTarget> rth, ImmutableCString&& tag) {
DEBUG_MARKER()
construct<GLRenderTarget>(rth, 0, 0); // FIXME: we don't know the width/height
@@ -1687,7 +1666,7 @@ void OpenGLDriver::createRenderTargetR(Handle<HwRenderTarget> rth,
MRT color,
TargetBufferInfo depth,
TargetBufferInfo stencil,
CString&& tag) {
ImmutableCString&& tag) {
DEBUG_MARKER()
GLRenderTarget* rt = construct<GLRenderTarget>(rth, width, height);
@@ -1803,31 +1782,41 @@ void OpenGLDriver::createRenderTargetR(Handle<HwRenderTarget> rth,
mHandleAllocator.associateTagToHandle(rth.getId(), std::move(tag));
}
void OpenGLDriver::createFenceR(Handle<HwFence> fh, CString&& tag) {
void OpenGLDriver::createFenceR(Handle<HwFence> fh, ImmutableCString&& tag) {
DEBUG_MARKER()
GLFence* f = handle_cast<GLFence*>(fh);
if (mPlatform.canCreateFence() || mContext.isES2()) {
assert_invariant(mPlatform.canCreateFence());
f->fence = mPlatform.createFence();
}
#ifndef FILAMENT_SILENCE_NOT_SUPPORTED_BY_ES2
else {
std::weak_ptr const weak = f->state;
whenGpuCommandsComplete([weak](){
if (auto const state = weak.lock()) {
std::lock_guard const lock(state->lock);
state->status = FenceStatus::CONDITION_SATISFIED;
state->cond.notify_all();
}
});
}
#endif
mHandleAllocator.associateTagToHandle(fh.getId(), std::move(tag));
GLFence* f = handle_cast<GLFence*>(fh);
assert_invariant(f->state);
bool const platformCanCreateFence = mPlatform.canCreateFence();
if (mContext.isES2() || platformCanCreateFence) {
std::lock_guard const lock(f->state->lock);
if (platformCanCreateFence) {
f->fence = mPlatform.createFence();
f->state->cond.notify_all();
} else {
f->state->status = FenceStatus::ERROR;
}
return;
}
// This is the case where we need to use OpenGL fences
#ifndef FILAMENT_SILENCE_NOT_SUPPORTED_BY_ES2
std::weak_ptr<GLFence::State> const weak = f->state;
whenGpuCommandsComplete([weak] {
if (auto const state = weak.lock()) {
std::lock_guard const lock(state->lock);
state->status = FenceStatus::CONDITION_SATISFIED;
state->cond.notify_all();
}
});
#endif
}
void OpenGLDriver::createSyncR(Handle<HwSync> sh, CString&& tag) {
void OpenGLDriver::createSyncR(Handle<HwSync> sh, ImmutableCString&& tag) {
DEBUG_MARKER()
GLSyncFence* s = handle_cast<GLSyncFence*>(sh);
@@ -1846,7 +1835,7 @@ void OpenGLDriver::createSyncR(Handle<HwSync> sh, CString&& tag) {
}
void OpenGLDriver::createSwapChainR(Handle<HwSwapChain> sch, void* nativeWindow, uint64_t const flags,
CString&& tag) {
ImmutableCString&& tag) {
DEBUG_MARKER()
GLSwapChain* sc = handle_cast<GLSwapChain*>(sch);
@@ -1868,7 +1857,7 @@ void OpenGLDriver::createSwapChainR(Handle<HwSwapChain> sch, void* nativeWindow,
}
void OpenGLDriver::createSwapChainHeadlessR(Handle<HwSwapChain> sch,
uint32_t const width, uint32_t const height, uint64_t const flags, CString&& tag) {
uint32_t const width, uint32_t const height, uint64_t const flags, ImmutableCString&& tag) {
DEBUG_MARKER()
GLSwapChain* sc = handle_cast<GLSwapChain*>(sch);
@@ -1890,7 +1879,7 @@ void OpenGLDriver::createSwapChainHeadlessR(Handle<HwSwapChain> sch,
mHandleAllocator.associateTagToHandle(sch.getId(), std::move(tag));
}
void OpenGLDriver::createTimerQueryR(Handle<HwTimerQuery> tqh, CString&& tag) {
void OpenGLDriver::createTimerQueryR(Handle<HwTimerQuery> tqh, ImmutableCString&& tag) {
DEBUG_MARKER()
GLTimerQuery* tq = handle_cast<GLTimerQuery*>(tqh);
mContext.createTimerQuery(tq);
@@ -1898,14 +1887,14 @@ void OpenGLDriver::createTimerQueryR(Handle<HwTimerQuery> tqh, CString&& tag) {
}
void OpenGLDriver::createDescriptorSetLayoutR(Handle<HwDescriptorSetLayout> dslh,
DescriptorSetLayout&& info, CString&& tag) {
DescriptorSetLayout&& info, ImmutableCString&& tag) {
DEBUG_MARKER()
construct<GLDescriptorSetLayout>(dslh, std::move(info));
mHandleAllocator.associateTagToHandle(dslh.getId(), std::move(tag));
}
void OpenGLDriver::createDescriptorSetR(Handle<HwDescriptorSet> dsh,
Handle<HwDescriptorSetLayout> dslh, CString&& tag) {
Handle<HwDescriptorSetLayout> dslh, ImmutableCString&& tag) {
DEBUG_MARKER()
GLDescriptorSetLayout const* dsl = handle_cast<GLDescriptorSetLayout*>(dslh);
construct<GLDescriptorSet>(dsh, mContext, dslh, dsl);
@@ -1914,7 +1903,7 @@ void OpenGLDriver::createDescriptorSetR(Handle<HwDescriptorSet> dsh,
void OpenGLDriver::mapBufferR(MemoryMappedBufferHandle mmbh,
BufferObjectHandle boh, size_t offset,
size_t size, MapBufferAccessFlags access, CString&& tag) {
size_t size, MapBufferAccessFlags access, ImmutableCString&& tag) {
DEBUG_MARKER()
construct<GLMemoryMappedBuffer>(mmbh, mContext, mHandleAllocator, boh, offset, size, access);
mHandleAllocator.associateTagToHandle(mmbh.getId(), std::move(tag));
@@ -2184,14 +2173,14 @@ void OpenGLDriver::unmapBuffer(MemoryMappedBufferHandle mmbh) {
// These are called on the application's thread
// ------------------------------------------------------------------------------------------------
Handle<HwStream> OpenGLDriver::createStreamNative(void* nativeStream, CString tag) {
Handle<HwStream> OpenGLDriver::createStreamNative(void* nativeStream, ImmutableCString tag) {
Platform::Stream* stream = mPlatform.createStream(nativeStream);
auto handle = initHandle<GLStream>(stream);
mHandleAllocator.associateTagToHandle(handle.getId(), std::move(tag));
return handle;
}
Handle<HwStream> OpenGLDriver::createStreamAcquired(CString tag) {
Handle<HwStream> OpenGLDriver::createStreamAcquired(ImmutableCString tag) {
auto handle = initHandle<GLStream>();
mHandleAllocator.associateTagToHandle(handle.getId(), std::move(tag));
return handle;
@@ -2307,29 +2296,62 @@ void OpenGLDriver::destroyFence(Handle<HwFence> fh) {
}
FenceStatus OpenGLDriver::getFenceStatus(Handle<HwFence> fh) {
return fenceWait(fh, 0);
}
FenceStatus OpenGLDriver::fenceWait(FenceHandle fh, uint64_t const timeout) {
if (fh) {
GLFence* f = handle_cast<GLFence*>(fh);
if (mPlatform.canCreateFence() || mContext.isES2()) {
if (f->fence == nullptr) {
// we can end-up here if:
// - the platform doesn't support h/w fences
if (UTILS_UNLIKELY(!mPlatform.canCreateFence())) {
return FenceStatus::ERROR;
// we have to take into account that the STL's wait_for() actually works with
// time_points relative to steady_clock::now() internally.
using namespace std::chrono;
auto const now = steady_clock::now();
steady_clock::time_point until = steady_clock::time_point::max();
if (now <= steady_clock::time_point::max() - nanoseconds(timeout)) {
until = now + nanoseconds(timeout);
}
GLFence const* f = handle_cast<GLFence*>(fh);
assert_invariant(f->state);
bool const platformCanCreateFence = mPlatform.canCreateFence();
// immediately acquire a reference on our state, so that things don't go south if
// the HwFence gets destroyed (on the main thread) while we wait.
std::shared_ptr const state{ f->state };
if (mContext.isES2() || platformCanCreateFence) {
if (platformCanCreateFence) {
std::unique_lock lock(state->lock);
if (f->fence == nullptr) {
// we've been called before the fence was created asynchronously,
// so we need to wait for that, before using the real fence.
// By construction, "f" can't be destroyed while we wait, because its
// construction call is in the queue and a destroy call will have to come later.
state->cond.wait_until(lock, until, [f] {
return f->fence != nullptr;
});
if (f->fence == nullptr) {
// the only possible choice here is that we timed out
assert_invariant(state->status == FenceStatus::TIMEOUT_EXPIRED);
return FenceStatus::TIMEOUT_EXPIRED;
}
}
// - wait() was called before the fence was asynchronously created.
return FenceStatus::TIMEOUT_EXPIRED;
lock.unlock();
// here we know that we have the platform fence
assert_invariant(f->fence);
return mPlatform.waitFence(f->fence, timeout);
}
return mPlatform.waitFence(f->fence, 0);
// platform doesn't support fences -- nothing we can do.
return FenceStatus::ERROR;
}
// This is the case where we need to use OpenGL fences
#ifndef FILAMENT_SILENCE_NOT_SUPPORTED_BY_ES2
else {
assert_invariant(f->state);
std::unique_lock lock(f->state->lock);
f->state->cond.wait_for(lock, std::chrono::nanoseconds(0), [&state = f->state]() {
return state->status != FenceStatus::TIMEOUT_EXPIRED;
});
return f->state->status;
}
std::unique_lock lock(state->lock);
state->cond.wait_until(lock, until, [&state] {
return state->status != FenceStatus::TIMEOUT_EXPIRED;
});
return state->status;
#endif
}
return FenceStatus::ERROR;
@@ -2596,6 +2618,8 @@ bool OpenGLDriver::isWorkaroundNeeded(Workaround const workaround) {
return mContext.bugs.powervr_shader_workarounds;
case Workaround::DISABLE_DEPTH_PRECACHE_FOR_DEFAULT_MATERIAL:
return mContext.bugs.disable_depth_precache_for_default_material;
case Workaround::EMULATE_SRGB_SWAPCHAIN:
return mContext.isES2() && !mPlatform.isSRGBSwapChainSupported();
default:
return false;
}
@@ -3169,7 +3193,7 @@ void OpenGLDriver::setExternalStream(Handle<HwTexture> th, Handle<HwStream> sh)
}
UTILS_NOINLINE
void OpenGLDriver::attachStream(GLTexture* t, GLStream* hwStream) noexcept {
void OpenGLDriver::attachStream(GLTexture* t, GLStream* hwStream) {
mTexturesWithStreamsAttached.push_back(t);
switch (hwStream->streamType) {
@@ -3755,16 +3779,16 @@ void OpenGLDriver::readBufferSubData(BufferObjectHandle boh,
}
void OpenGLDriver::runEveryNowAndThen(std::function<bool()> fn) noexcept {
void OpenGLDriver::runEveryNowAndThen(std::function<bool()> fn) {
mEveryNowAndThenOps.push_back(std::move(fn));
}
void OpenGLDriver::executeEveryNowAndThenOps() noexcept {
void OpenGLDriver::executeEveryNowAndThenOps() noexcept { // NOLINT(*-exception-escape)
auto& v = mEveryNowAndThenOps;
auto it = v.begin();
while (it != v.end()) {
if ((*it)()) {
it = v.erase(it);
it = v.erase(it); // cannot throw by construction
} else {
++it;
}
@@ -3772,17 +3796,17 @@ void OpenGLDriver::executeEveryNowAndThenOps() noexcept {
}
#ifndef FILAMENT_SILENCE_NOT_SUPPORTED_BY_ES2
void OpenGLDriver::whenFrameComplete(const std::function<void()>& fn) noexcept {
void OpenGLDriver::whenFrameComplete(const std::function<void()>& fn) {
mFrameCompleteOps.push_back(fn);
}
void OpenGLDriver::whenGpuCommandsComplete(const std::function<void()>& fn) noexcept {
void OpenGLDriver::whenGpuCommandsComplete(const std::function<void()>& fn) {
GLsync sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
mGpuCommandCompleteOps.emplace_back(sync, fn);
CHECK_GL_ERROR()
}
void OpenGLDriver::executeGpuCommandsCompleteOps() noexcept {
void OpenGLDriver::executeGpuCommandsCompleteOps() noexcept { // NOLINT(*-exception-escape)
auto& v = mGpuCommandCompleteOps;
auto it = v.begin();
while (it != v.end()) {
@@ -3798,13 +3822,13 @@ void OpenGLDriver::executeGpuCommandsCompleteOps() noexcept {
// ready
it->second();
glDeleteSync(sync);
it = v.erase(it);
it = v.erase(it); // cannot throw by construction
break;
default:
// This should never happen, but is very problematic if it does, as we might leak
// some data depending on what the callback does. However, we clean up our own state.
glDeleteSync(sync);
it = v.erase(it);
it = v.erase(it); // cannot throw by construction
break;
}
}
+9 -7
View File
@@ -45,6 +45,7 @@
#include <utils/FixedCapacityVector.h>
#include <utils/compiler.h>
#include <utils/CString.h>
#include <utils/ImmutableCString.h>
#include <utils/debug.h>
#include <math/vec4.h>
@@ -194,8 +195,8 @@ public:
struct GLFence : public HwFence {
using HwFence::HwFence;
struct State {
std::mutex lock;
std::condition_variable cond;
utils::Mutex lock; // NOLINT(*-include-cleaner)
utils::Condition cond; // NOLINT(*-include-cleaner)
FenceStatus status{ FenceStatus::TIMEOUT_EXPIRED };
};
std::shared_ptr<State> state{ std::make_shared<State>() };
@@ -233,7 +234,8 @@ private:
}
ShaderModel getShaderModel() const noexcept override;
ShaderLanguage getShaderLanguage() const noexcept override;
utils::FixedCapacityVector<ShaderLanguage> getShaderLanguages(
ShaderLanguage preferredLanguage) const noexcept override;
/*
* OpenGLDriver interface
@@ -394,23 +396,23 @@ private:
std::unordered_map<GLuint, BufferObjectStreamDescriptor> mStreamUniformDescriptors;
void attachStream(GLTexture* t, GLStream* stream) noexcept;
void attachStream(GLTexture* t, GLStream* stream);
void detachStream(GLTexture* t) noexcept;
void replaceStream(GLTexture* t, GLStream* stream) noexcept;
math::mat3f getStreamTransformMatrix(Handle<HwStream> sh);
#ifndef FILAMENT_SILENCE_NOT_SUPPORTED_BY_ES2
// tasks executed on the main thread after the fence signaled
void whenGpuCommandsComplete(const std::function<void()>& fn) noexcept;
void whenGpuCommandsComplete(const std::function<void()>& fn);
void executeGpuCommandsCompleteOps() noexcept;
std::vector<std::pair<GLsync, std::function<void()>>> mGpuCommandCompleteOps;
void whenFrameComplete(const std::function<void()>& fn) noexcept;
void whenFrameComplete(const std::function<void()>& fn);
std::vector<std::function<void()>> mFrameCompleteOps;
#endif
// tasks regularly executed on the main thread at until they return true
void runEveryNowAndThen(std::function<bool()> fn) noexcept;
void runEveryNowAndThen(std::function<bool()> fn);
void executeEveryNowAndThenOps() noexcept;
std::vector<std::function<bool()>> mEveryNowAndThenOps;
@@ -121,7 +121,7 @@ void OpenGLProgram::initialize(OpenGLDriver& gld) {
* checkProgramStatus() has been successfully called.
*/
void OpenGLProgram::initializeProgramState(OpenGLContext& context, GLuint program,
LazyInitializationData& lazyInitializationData) noexcept {
LazyInitializationData& lazyInitializationData) {
FILAMENT_TRACING_CALL(FILAMENT_TRACING_CATEGORY_FILAMENT);
// from the pipeline layout we compute a mapping from {set, binding} to {binding}
+5 -5
View File
@@ -43,8 +43,8 @@ namespace filament::backend {
class OpenGLDriver;
struct PushConstantBundle {
utils::Slice<std::pair<GLint, ConstantType>> vertexConstants;
utils::Slice<std::pair<GLint, ConstantType>> fragmentConstants;
utils::Slice<const std::pair<GLint, ConstantType>> vertexConstants;
utils::Slice<const std::pair<GLint, ConstantType>> fragmentConstants;
};
class OpenGLProgram : public HwProgram {
@@ -94,8 +94,8 @@ public:
PushConstantBundle getPushConstants() {
auto fragBegin = mPushConstants.begin() + mPushConstantFragmentStageOffset;
return {
.vertexConstants = utils::Slice(mPushConstants.begin(), fragBegin),
.fragmentConstants = utils::Slice(fragBegin, mPushConstants.end()),
.vertexConstants = { mPushConstants.begin(), fragBegin },
.fragmentConstants = { fragBegin, mPushConstants.end() },
};
}
@@ -106,7 +106,7 @@ private:
void initialize(OpenGLDriver& gld);
void initializeProgramState(OpenGLContext& context, GLuint program,
LazyInitializationData& lazyInitializationData) noexcept;
LazyInitializationData& lazyInitializationData);
BindingMap mBindingMap; // 8 bytes + out-of-line 256 bytes
@@ -51,7 +51,7 @@ class OpenGLDriver;
bool TimerQueryFactory::mGpuTimeSupported = false;
TimerQueryFactoryInterface* TimerQueryFactory::init(
OpenGLPlatform& platform, OpenGLContext& context) noexcept {
OpenGLPlatform& platform, OpenGLContext& context) {
(void)context;
TimerQueryFactoryInterface* impl = nullptr;
@@ -172,46 +172,12 @@ void TimerQueryNativeFactory::endTimeElapsedQuery(OpenGLDriver& driver, GLTimerQ
// ------------------------------------------------------------------------------------------------
TimerQueryFenceFactory::TimerQueryFenceFactory(OpenGLPlatform& platform)
: mPlatform(platform) {
mQueue.reserve(2);
mThread = std::thread([this]() {
utils::JobSystem::setThreadName("OpenGLTimerQueryFence");
utils::JobSystem::setThreadPriority(utils::JobSystem::Priority::URGENT_DISPLAY);
auto& queue = mQueue;
bool exitRequested;
do {
std::unique_lock<utils::Mutex> lock(mLock);
mCondition.wait(lock, [this, &queue]() -> bool {
return mExitRequested || !queue.empty();
});
exitRequested = mExitRequested;
if (!queue.empty()) {
Job const job(queue.front());
queue.erase(queue.begin());
lock.unlock();
job();
}
} while (!exitRequested);
});
: mPlatform(platform),
mJobQueue("OpenGLTimerQueryFence", utils::AsyncJobQueue::Priority::URGENT_DISPLAY) {
}
TimerQueryFenceFactory::~TimerQueryFenceFactory() {
assert_invariant(mQueue.empty());
if (mThread.joinable()) {
std::unique_lock<utils::Mutex> lock(mLock);
mExitRequested = true;
mCondition.notify_one();
lock.unlock();
if (mThread.joinable()) {
mThread.join();
}
}
}
void TimerQueryFenceFactory::push(TimerQueryFenceFactory::Job&& job) {
std::unique_lock<utils::Mutex> const lock(mLock);
mQueue.push_back(std::move(job));
mCondition.notify_one();
mJobQueue.drainAndExit();
}
void TimerQueryFenceFactory::createTimerQuery(GLTimerQuery* tq) {
@@ -236,7 +202,7 @@ void TimerQueryFenceFactory::beginTimeElapsedQuery(GLTimerQuery* tq) {
// on a dummy target for instance, or somehow latch the begin time at the next renderpass
// start.
push([&platform = mPlatform, fence = mPlatform.createFence(), weak]() {
mJobQueue.push([&platform = mPlatform, fence = mPlatform.createFence(), weak]() {
auto state = weak.lock();
if (state) {
platform.waitFence(fence, FENCE_WAIT_FOR_EVER);
@@ -252,7 +218,7 @@ void TimerQueryFenceFactory::endTimeElapsedQuery(OpenGLDriver&, GLTimerQuery* tq
assert_invariant(tq->state);
std::weak_ptr<GLTimerQuery::State> const weak = tq->state;
push([&platform = mPlatform, fence = mPlatform.createFence(), weak]() {
mJobQueue.push([&platform = mPlatform, fence = mPlatform.createFence(), weak]() {
auto state = weak.lock();
if (state) {
platform.waitFence(fence, FENCE_WAIT_FOR_EVER);
+3 -13
View File
@@ -21,8 +21,7 @@
#include "DriverBase.h"
#include <utils/Condition.h>
#include <utils/Mutex.h>
#include <utils/AsyncJobQueue.h>
#include "gl_headers.h"
@@ -65,7 +64,7 @@ class TimerQueryFactory {
static bool mGpuTimeSupported;
public:
static TimerQueryFactoryInterface* init(
OpenGLPlatform& platform, OpenGLContext& context) noexcept;
OpenGLPlatform& platform, OpenGLContext& context);
static bool isGpuTimeSupported() noexcept {
return mGpuTimeSupported;
@@ -108,22 +107,13 @@ public:
explicit TimerQueryFenceFactory(OpenGLPlatform& platform);
~TimerQueryFenceFactory() override;
private:
using Job = std::function<void()>;
using Container = std::vector<Job>;
void createTimerQuery(GLTimerQuery* query) override;
void destroyTimerQuery(GLTimerQuery* query) override;
void beginTimeElapsedQuery(GLTimerQuery* tq) override;
void endTimeElapsedQuery(OpenGLDriver& driver, GLTimerQuery* tq) override;
void push(Job&& job);
OpenGLPlatform& mPlatform;
std::thread mThread;
mutable utils::Mutex mLock;
mutable utils::Condition mCondition;
Container mQueue;
bool mExitRequested = false;
utils::AsyncJobQueue mJobQueue;
};
class TimerQueryFallbackFactory final : public TimerQueryFactoryInterface {
@@ -71,7 +71,7 @@ static CString to_string(int const i) { return utils::to_string(i); }
static CString to_string(float const f) { return "float(" + utils::to_string(f) + ")"; }
static void logCompilationError(ShaderStage shaderType, const char* name, GLuint shaderId,
Program::ShaderBlob const& sourceCode) noexcept;
Program::ShaderBlob const& sourceCode);
static void logProgramLinkError(char const* name, GLuint program) noexcept;
static void process_GOOGLE_cpp_style_line_directive(OpenGLContext const& context, char* source,
@@ -79,7 +79,7 @@ static void process_GOOGLE_cpp_style_line_directive(OpenGLContext const& context
static void process_OVR_multiview2(OpenGLContext const& context, int32_t eyeCount, char* source,
size_t len) noexcept;
static std::string_view process_ARB_shading_language_packing(OpenGLContext& context) noexcept;
static std::array<std::string_view, 3> splitShaderSource(std::string_view source) noexcept;
static std::array<std::string_view, 3> splitShaderSource(std::string_view source);
// ------------------------------------------------------------------------------------------------
@@ -312,7 +312,7 @@ ShaderCompilerService::program_token_t ShaderCompilerService::createProgram(
}
void ShaderCompilerService::compileProgram(
program_token_t const& token, Program&& program) noexcept {
program_token_t const& token, Program&& program) {
auto& gl = mDriver.getContext();
CompilerPriorityQueue const priorityQueue = program.getPriorityQueue();
switch (mMode) {
@@ -343,6 +343,12 @@ void ShaderCompilerService::compileProgram(
program.getSpecializationConstants(), program.isMultiview(),
token);
linkProgram(gl, token);
// Check status of program linking. If it failed, errors will be logged.
bool const linked = checkLinkStatusAndCleanupShaders(token);
// We panic if it failed to create the program.
FILAMENT_CHECK_POSTCONDITION(linked)
<< "OpenGL program " << token->name.c_str_safe()
<< " failed to link or compile";
}
// Now `token->gl.program` must be populated, so we signal the completion
// of the linking. We don't need to check the result of the program here
@@ -475,16 +481,14 @@ GLuint ShaderCompilerService::initialize(program_token_t& token) {
ensureTokenIsReady(token);
assert_invariant(token->gl.program);
// Check status of program linking. If it failed, errors will be logged.
bool const linked = checkLinkStatusAndCleanupShaders(token);
// We panic if it failed to create the program.
FILAMENT_CHECK_POSTCONDITION(linked)
<< "OpenGL program " << token->name.c_str_safe() << " failed to link or compile";
GLuint const program = token->gl.program;
if (mMode != Mode::THREAD_POOL) {
// Check status of program linking. If it failed, errors will be logged.
bool const linked = checkLinkStatusAndCleanupShaders(token);
// We panic if it failed to create the program.
FILAMENT_CHECK_POSTCONDITION(linked)
<< "OpenGL program " << token->name.c_str_safe() << " failed to link or compile";
// The program has been successfully created. Try caching the program blob for
// non-THREAD_POOL modes. In the THREAD_POOL mode, caching is performed in the pool.
tryCachingProgram(mBlobCache, mDriver.mPlatform, token);
@@ -586,7 +590,7 @@ void ShaderCompilerService::handleCanceledTokensForThreadPool() {
// ------------------------------------------------------------------------------------------------
void ShaderCompilerService::runAtNextTick(CompilerPriorityQueue priority,
program_token_t const& token, Job job) noexcept {
program_token_t const& token, Job job) {
// insert items in order of priority and at the end of the range
auto& ops = mRunAtNextTickOps;
auto const pos = std::lower_bound(ops.begin(), ops.end(), priority,
@@ -614,7 +618,7 @@ bool ShaderCompilerService::cancelTickOp(program_token_t const& token) noexcept
return false;
}
void ShaderCompilerService::executeTickOps() noexcept {
void ShaderCompilerService::executeTickOps() {
auto& ops = mRunAtNextTickOps;
auto it = ops.begin();
while (it != ops.end()) {
@@ -636,7 +640,7 @@ bool ShaderCompilerService::shouldCompileSynchronousProgramThisTick() const noex
mNumTicksUntilNextSynchronousProgram == 0);
}
void ShaderCompilerService::compilePendingSynchronousPrograms() noexcept {
void ShaderCompilerService::compilePendingSynchronousPrograms() {
if (mDriver.getDriverConfig().disableAmortizedShaderCompile) {
return;
}
@@ -655,7 +659,7 @@ void ShaderCompilerService::compilePendingSynchronousPrograms() noexcept {
}
void ShaderCompilerService::compilePendingSynchronousProgramNow(
program_token_t const& token) noexcept {
program_token_t const& token) {
if (mDriver.getDriverConfig().disableAmortizedShaderCompile) {
return;
}
@@ -692,27 +696,28 @@ void ShaderCompilerService::cancelPendingSynchronousProgram(program_token_t cons
/* static */ void ShaderCompilerService::compileShaders(OpenGLContext& context,
Program::ShaderSource shadersSource,
FixedCapacityVector<Program::SpecializationConstant> const& specializationConstants,
bool multiview, program_token_t const& token) noexcept {
bool multiview, program_token_t const& token) {
FILAMENT_TRACING_CALL(FILAMENT_TRACING_CATEGORY_FILAMENT);
auto const appendSpecConstantString = +[](CString& s, Program::SpecializationConstant const& sc) {
s += "#define SPIRV_CROSS_CONSTANT_ID_" + utils::to_string(sc.id) + ' ';
s += std::visit([](auto&& arg) { return to_string(arg); }, sc.value);
s += '\n';
return s;
};
auto const appendSpecConstantString =
+[](CString& s, size_t id, Program::SpecializationConstant const& sc) {
s += "#define SPIRV_CROSS_CONSTANT_ID_" + utils::to_string(id) + ' ';
s += std::visit([](auto&& arg) { return to_string(arg); }, sc);
s += '\n';
return s;
};
CString specializationConstantString;
int32_t numViews = 2;
for (auto const& sc: specializationConstants) {
appendSpecConstantString(specializationConstantString, sc);
if (sc.id == 8) {
// This constant must match
// ReservedSpecializationConstants::CONFIG_STEREO_EYE_COUNT
// which we can't use here because it's defined in EngineEnums.h.
// (we're breaking layering here, but it's for the good cause).
numViews = std::get<int32_t>(sc.value);
}
// This constant must match
// ReservedSpecializationConstants::CONFIG_STEREO_EYE_COUNT
// which we can't use here because it's defined in EngineEnums.h.
// (we're breaking layering here, but it's for the good cause).
constexpr size_t CONFIG_STEREO_EYE_COUNT = 8;
int32_t numViews = specializationConstants.size() >= CONFIG_STEREO_EYE_COUNT
? std::get<int32_t>(specializationConstants[CONFIG_STEREO_EYE_COUNT])
: 2;
for (size_t id = 0; id < specializationConstants.size(); id++) {
appendSpecConstantString(specializationConstantString, id, specializationConstants[id]);
}
if (!specializationConstantString.empty()) {
specializationConstantString += '\n';
@@ -817,7 +822,7 @@ void ShaderCompilerService::cancelPendingSynchronousProgram(program_token_t cons
return true;
}
/* static */ void ShaderCompilerService::checkCompileStatus(program_token_t const& token) noexcept {
/* static */ void ShaderCompilerService::checkCompileStatus(program_token_t const& token) {
FILAMENT_TRACING_CALL(FILAMENT_TRACING_CATEGORY_FILAMENT);
UTILS_NOUNROLL
@@ -839,7 +844,7 @@ void ShaderCompilerService::cancelPendingSynchronousProgram(program_token_t cons
}
/* static */ void ShaderCompilerService::linkProgram(OpenGLContext const& context,
program_token_t const& token) noexcept {
program_token_t const& token) {
FILAMENT_TRACING_CALL(FILAMENT_TRACING_CATEGORY_FILAMENT);
// Shader compilation should be completed by now. Check the status and log errors on failure.
@@ -933,7 +938,7 @@ void ShaderCompilerService::cancelPendingSynchronousProgram(program_token_t cons
UTILS_NOINLINE
/* static */ void logCompilationError(ShaderStage shaderType, const char* name,
GLuint const shaderId,
UTILS_UNUSED_IN_RELEASE Program::ShaderBlob const& sourceCode) noexcept {
UTILS_UNUSED_IN_RELEASE Program::ShaderBlob const& sourceCode) {
// Collects the current GL error for additional context. While often redundant,
// errors like `GL_CONTEXT_LOST` can occur asynchronously after `glCompileShader`.
@@ -1179,7 +1184,7 @@ mediump vec4 unpackSnorm4x8(highp uint v) {
// - the version line
// - extensions
// - everything else
/* static */ std::array<std::string_view, 3> splitShaderSource(std::string_view source) noexcept {
/* static */ std::array<std::string_view, 3> splitShaderSource(std::string_view source) {
auto const version_start = source.find("#version");
assert_invariant(version_start != std::string_view::npos);
@@ -148,16 +148,16 @@ private:
// Methods for SYNCHRONOUS and ASYNCHRONOUS modes.
void runAtNextTick(CompilerPriorityQueue priority, program_token_t const& token,
Job job) noexcept;
void executeTickOps() noexcept;
Job job);
void executeTickOps();
bool cancelTickOp(program_token_t const& token) noexcept;
bool shouldCompileSynchronousProgramThisTick() const noexcept;
void compilePendingSynchronousPrograms() noexcept;
void compilePendingSynchronousProgramNow(program_token_t const& token) noexcept;
void compilePendingSynchronousPrograms();
void compilePendingSynchronousProgramNow(program_token_t const& token);
void cancelPendingSynchronousProgram(program_token_t const& token) noexcept;
void compileProgram(program_token_t const& token, Program&& program) noexcept;
void compileProgram(program_token_t const& token, Program&& program);
// Compile shaders with the given `shaderSource`. `gl.shaders` is always populated with valid
// shader IDs after this method. But this doesn't necessarily mean the shaders are successfully
@@ -165,20 +165,20 @@ private:
static void compileShaders(OpenGLContext& context, Program::ShaderSource shadersSource,
utils::FixedCapacityVector<Program::SpecializationConstant> const&
specializationConstants,
bool multiview, program_token_t const& token) noexcept;
bool multiview, program_token_t const& token);
// Check if the shader compilation is completed. You may want to call this when the extension
// `KHR_parallel_shader_compile` is enabled.
static bool isCompileCompleted(program_token_t const& token) noexcept;
// Check compilation status of the shaders and log errors on failure.
static void checkCompileStatus(program_token_t const& token) noexcept;
static void checkCompileStatus(program_token_t const& token);
// Create a program by linking the compiled shaders. `gl.program` is always populated with a
// valid program ID after this method. But this doesn't necessarily mean the program is
// successfully linked. Errors can be checked by calling `checkLinkStatusAndCleanupShaders`
// later.
static void linkProgram(OpenGLContext const& context, program_token_t const& token) noexcept;
static void linkProgram(OpenGLContext const& context, program_token_t const& token);
// Check if the program link is completed. You may want to call this when the extension
// `KHR_parallel_shader_compile` is enabled.
@@ -148,7 +148,7 @@ PlatformCocoaGL::~PlatformCocoaGL() noexcept {
delete pImpl;
}
Driver* PlatformCocoaGL::createDriver(void* sharedContext, const Platform::DriverConfig& driverConfig) noexcept {
Driver* PlatformCocoaGL::createDriver(void* sharedContext, const Platform::DriverConfig& driverConfig) {
// NSOpenGLPFAColorSize: when unspecified, a format that matches the screen is preferred
NSOpenGLPixelFormatAttribute pixelFormatAttributes[] = {
NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core,
@@ -64,7 +64,7 @@ PlatformCocoaTouchGL::~PlatformCocoaTouchGL() noexcept {
delete pImpl;
}
Driver* PlatformCocoaTouchGL::createDriver(void* sharedGLContext, const Platform::DriverConfig& driverConfig) noexcept {
Driver* PlatformCocoaTouchGL::createDriver(void* sharedGLContext, const Platform::DriverConfig& driverConfig) {
EAGLSharegroup* sharegroup = (__bridge EAGLSharegroup*) sharedGLContext;
EAGLContext *context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3 sharegroup:sharegroup];
@@ -119,7 +119,7 @@ bool PlatformEGL::isOpenGL() const noexcept {
PlatformEGL::ExternalImageEGL::~ExternalImageEGL() = default;
Driver* PlatformEGL::createDriver(void* sharedContext, const DriverConfig& driverConfig) noexcept {
Driver* PlatformEGL::createDriver(void* sharedContext, const DriverConfig& driverConfig) {
mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
assert_invariant(mEGLDisplay != EGL_NO_DISPLAY);
@@ -500,7 +500,7 @@ bool PlatformEGL::isMSAASwapChainSupported(uint32_t samples) const noexcept {
}
Platform::SwapChain* PlatformEGL::createSwapChain(
void* nativeWindow, uint64_t flags) noexcept {
void* nativeWindow, uint64_t flags) {
Config attribs;
@@ -561,7 +561,7 @@ Platform::SwapChain* PlatformEGL::createSwapChain(
}
Platform::SwapChain* PlatformEGL::createSwapChain(
uint32_t width, uint32_t height, uint64_t flags) noexcept {
uint32_t width, uint32_t height, uint64_t flags) {
Config attribs = {
{ EGL_WIDTH, EGLint(width) },
@@ -198,7 +198,7 @@ void backend::PlatformEGLAndroid::preCommit() noexcept {
}
Driver* PlatformEGLAndroid::createDriver(void* sharedContext,
const Platform::DriverConfig& driverConfig) noexcept {
const Platform::DriverConfig& driverConfig) {
// the refresh rate default value doesn't matter, we change it later
int32_t const tid = gettid();
@@ -39,7 +39,7 @@ bool PlatformEGLHeadless::isOpenGL() const noexcept {
}
backend::Driver* PlatformEGLHeadless::createDriver(void* sharedContext,
const Platform::DriverConfig& driverConfig) noexcept {
const Platform::DriverConfig& driverConfig) {
EGLBoolean bindAPI = eglBindAPI(EGL_OPENGL_API);
if (UTILS_UNLIKELY(!bindAPI)) {
LOG(ERROR) << "eglBindAPI EGL_OPENGL_API failed";
@@ -31,6 +31,7 @@
// Function pointer types for X11 functions
typedef Display* (* X11_OPEN_DISPLAY)(const char*);
typedef Display* (* X11_CLOSE_DISPLAY)(Display*);
typedef int (* X11_FREE)(void*);
// Function pointer types for GLX functions
typedef void (* GLX_DESTROY_CONTEXT)(Display*, GLXContext);
@@ -43,7 +44,7 @@ struct GLXFunctions {
PFNGLXDESTROYPBUFFERPROC destroyPbuffer;
PFNGLXMAKECONTEXTCURRENTPROC setCurrentContext;
/*
/*
When creating a shared GL context, we query the used
GLX_FBCONFIG_ID to make sure our display framebuffer
attributes match; otherwise making our context current
@@ -52,7 +53,7 @@ struct GLXFunctions {
*/
PFNGLXQUERYCONTEXTPROC queryContext;
/*
/*
When creating a shared GL context, we select the matching
GLXFBConfig that is used by the shared GL context. `getFBConfigs`
will return all the available GLXFBConfigs.
@@ -76,6 +77,7 @@ struct GLXFunctions {
struct X11Functions {
X11_OPEN_DISPLAY openDisplay;
X11_CLOSE_DISPLAY closeDisplay;
X11_FREE free;
void* library;
} g_x11;
@@ -121,6 +123,7 @@ static bool loadLibraries() {
g_x11.openDisplay = (X11_OPEN_DISPLAY)dlsym(g_x11.library, "XOpenDisplay");
g_x11.closeDisplay = (X11_CLOSE_DISPLAY)dlsym(g_x11.library, "XCloseDisplay");
g_x11.free = (X11_FREE)dlsym(g_x11.library, "XFree");
return true;
}
@@ -129,7 +132,7 @@ namespace filament::backend {
using namespace backend;
Driver* PlatformGLX::createDriver(void* sharedGLContext,
const DriverConfig& driverConfig) noexcept {
const DriverConfig& driverConfig) {
loadLibraries();
// Get the display device
mGLXDisplay = g_x11.openDisplay(NULL);
@@ -151,16 +154,13 @@ Driver* PlatformGLX::createDriver(void* sharedGLContext,
int numConfigs = 0;
GLXFBConfig* fbConfigs = g_glx.getFbConfigs(mGLXDisplay, 0, &numConfigs);
if (fbConfigs == nullptr) {
LOG(ERROR) << "Failed to get the available GLXFBConfigs.";
return nullptr;
}
int fbId = 0;
int fbIndex = -1;
for (int i = 0; i < numConfigs; ++i) {
int fbId = 0;
r = g_glx.getFbConfigAttrib(mGLXDisplay, fbConfigs[i], GLX_FBCONFIG_ID, &fbId);
if (r != 0) {
LOG(ERROR) << "Failed to get GLX_FBCONFIG_ID for entry " << i << ".";
@@ -168,17 +168,17 @@ Driver* PlatformGLX::createDriver(void* sharedGLContext,
}
if (fbId == usedFbId) {
fbIndex = i;
mGLXConfig = fbConfigs[i];
break;
}
}
if (fbIndex < 0) {
g_x11.free(fbConfigs);
if (!mGLXConfig) {
LOG(ERROR) << "Failed to find an `GLXFBConfig` with the requested ID.";
return nullptr;
}
mGLXConfig = fbConfigs + fbIndex;
} else {
// Create a context
static int attribs[] = {
@@ -188,17 +188,17 @@ Driver* PlatformGLX::createDriver(void* sharedGLContext,
};
int configCount = 0;
mGLXConfig = g_glx.chooseFbConfig(mGLXDisplay, DefaultScreen(mGLXDisplay),
GLXFBConfig* fbConfigs = g_glx.chooseFbConfig(mGLXDisplay, DefaultScreen(mGLXDisplay),
attribs, &configCount);
if (mGLXConfig == nullptr || configCount == 0) {
if (fbConfigs == nullptr || configCount == 0) {
return nullptr;
}
mGLXConfig = fbConfigs[0];
g_x11.free(fbConfigs);
}
PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribs = (PFNGLXCREATECONTEXTATTRIBSARBPROC)
getProcAddress((GLubyte*)"glXCreateContextAttribsARB");
if (glXCreateContextAttribs == nullptr) {
if (g_glx.createContext == nullptr) {
LOG(INFO) << "Unable to retrieve function pointer for `glXCreateContextAttribs()`.";
return nullptr;
}
@@ -209,7 +209,7 @@ Driver* PlatformGLX::createDriver(void* sharedGLContext,
GL_NONE
};
mGLXContext = g_glx.createContext(mGLXDisplay, mGLXConfig[0],
mGLXContext = g_glx.createContext(mGLXDisplay, mGLXConfig,
(GLXContext)sharedGLContext, True, contextAttribs);
int pbufferAttribs[] = {
@@ -218,7 +218,7 @@ Driver* PlatformGLX::createDriver(void* sharedGLContext,
GL_NONE
};
mDummySurface = g_glx.createPbuffer(mGLXDisplay, mGLXConfig[0], pbufferAttribs);
mDummySurface = g_glx.createPbuffer(mGLXDisplay, mGLXConfig, pbufferAttribs);
g_glx.setCurrentContext(mGLXDisplay, mDummySurface, mDummySurface, mGLXContext);
int result = bluegl::bind();
@@ -246,7 +246,7 @@ Platform::SwapChain* PlatformGLX::createSwapChain(
GLX_PBUFFER_HEIGHT, int(height),
GL_NONE
};
GLXPbuffer sur = g_glx.createPbuffer(mGLXDisplay, mGLXConfig[0], pbufferAttribs);
GLXPbuffer sur = g_glx.createPbuffer(mGLXDisplay, mGLXConfig, pbufferAttribs);
if (sur) {
mPBuffers.push_back(sur);
}
@@ -113,7 +113,7 @@ private:
}// anonymous namespace
Driver* PlatformOSMesa::createDriver(void* sharedGLContext,
const DriverConfig& driverConfig) noexcept {
const DriverConfig& driverConfig) {
OSMesaAPI* api = new OSMesaAPI();
mOsMesaApi = api;
@@ -75,7 +75,7 @@ struct WGLSwapChain {
static PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribs = nullptr;
Driver* PlatformWGL::createDriver(void* sharedGLContext,
const Platform::DriverConfig& driverConfig) noexcept {
const Platform::DriverConfig& driverConfig) {
int result = 0;
int pixelFormat = 0;
DWORD dwError = 0;
@@ -124,8 +124,6 @@ Driver* PlatformWGL::createDriver(void* sharedGLContext,
(PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress("wglCreateContextAttribsARB");
// try all versions down, from GL 4.5 to 4.1
for (int minor = 5; minor >= 1; minor--) {
mAttribs = {
WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
@@ -144,6 +142,18 @@ Driver* PlatformWGL::createDriver(void* sharedGLContext,
goto error;
}
// Create shared contexts here for use by other threads. This is a Windows specific workaround
// necessitated by the requirement that shared contexts must be initialized on the same thread
// as the primary context. If more shared contexts are necessary, the constant
// SHARED_CONTEXT_NUM must be updated.
for (int i = 0; i < SHARED_CONTEXT_NUM; ++i) {
HGLRC context = wglCreateContextAttribs(mWhdc, mContext, mAttribs.data());
if (context) {
mAdditionalContexts.push_back(context);
}
}
// Delete the temporary context
wglMakeCurrent(NULL, NULL);
wglDeleteContext(tempContext);
tempContext = NULL;
@@ -169,13 +179,17 @@ error:
}
bool PlatformWGL::isExtraContextSupported() const noexcept {
return false;
return true;
}
void PlatformWGL::createContext(bool shared) {
HGLRC context = wglCreateContextAttribs(mWhdc, shared ? mContext : nullptr, mAttribs.data());
wglMakeCurrent(mWhdc, context);
mAdditionalContexts.push_back(context);
int nextIndex = mNextFreeSharedContextIndex.fetch_add(1, std::memory_order_relaxed);
FILAMENT_CHECK_PRECONDITION(nextIndex < SHARED_CONTEXT_NUM)
<< "Shared context index out of range. Increase SHARED_CONTEXT_NUM.";
HGLRC context = mAdditionalContexts[nextIndex];
BOOL result = wglMakeCurrent(mWhdc, context);
FILAMENT_CHECK_POSTCONDITION(result) << "Failed to make current.";
}
void PlatformWGL::terminate() noexcept {
@@ -21,7 +21,7 @@ namespace filament::backend {
using namespace backend;
Driver* PlatformWebGL::createDriver(void* sharedGLContext,
const Platform::DriverConfig& driverConfig) noexcept {
const Platform::DriverConfig& driverConfig) {
return OpenGLPlatform::createDefaultDriver(this, sharedGLContext, driverConfig);
}
@@ -0,0 +1,82 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "VulkanAsyncHandles.h"
#include <backend/DriverEnums.h>
#include <utils/debug.h>
#include <cstdint>
#include <mutex>
#include <shared_mutex>
#include <chrono>
using namespace bluevk;
namespace filament::backend {
FenceStatus VulkanCmdFence::wait(VkDevice device, uint64_t const timeout,
std::chrono::steady_clock::time_point const until) {
std::shared_lock l(mLock);
// If the vulkan fence has not been submitted yet, we need to wait for that before we
// can use vkWaitForFences()
if (mStatus == VK_INCOMPLETE) {
bool const success = mCond.wait_until(l, until, [this] {
// Internally we use the VK_INCOMPLETE status to mean "not yet submitted".
// When this fence gets submitted, its status changes to VK_NOT_READY.
return mStatus != VK_INCOMPLETE;
});
if (!success) {
// !success indicates a timeout
return FenceStatus::TIMEOUT_EXPIRED;
}
}
// The fence could have already signaled, avoid calling into vkWaitForFences()
if (mStatus == VK_SUCCESS) {
return FenceStatus::CONDITION_SATISFIED;
}
// If we're here, we know that vkQueueSubmit has been called (because it sets the status
// to VK_NOT_READY).
// Now really wait for the fence while holding the shared_lock, this allows several
// threads to call vkWaitForFences(), but will prevent vkResetFence from taking
// place simultaneously. vkResetFence is only called once it knows the fence has signaled,
// which guaranties that vkResetFence won't have to wait too long, just enough for
// all the vkWaitForFences() to return.
mStatus = vkWaitForFences(device, 1, &mFence, VK_TRUE, timeout);
if (mStatus == VK_SUCCESS) {
return FenceStatus::CONDITION_SATISFIED;
}
if (mStatus == VK_TIMEOUT) {
return FenceStatus::TIMEOUT_EXPIRED;
}
return FenceStatus::ERROR; // not supported
}
void VulkanCmdFence::resetFence(VkDevice device) {
// This lock prevents vkResetFences() from being called simultaneously with vkWaitForFences(),
// but by construction, when we're here, we know that the fence has signaled and
// vkWaitForFences() will return shortly.
std::lock_guard const l(mLock);
assert_invariant(mStatus == VK_SUCCESS);
vkResetFences(device, 1, &mFence);
}
} // namespace filament::backend
@@ -20,37 +20,81 @@
#include <bluevk/BlueVK.h>
#include "DriverBase.h"
#include "backend/DriverEnums.h"
#include "backend/Platform.h"
#include "vulkan/memory/Resource.h"
#include <utils/Mutex.h>
#include <utils/Condition.h>
#include <chrono>
#include <cstdint>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <utility>
#include <vector>
namespace filament::backend {
// Wrapper to enable use of shared_ptr for implementing shared ownership of low-level Vulkan fences.
struct VulkanCmdFence {
VulkanCmdFence(VkResult initialStatus) {
// Internally we use the VK_INCOMPLETE status to mean "not yet submitted". When this fence
// gets submitted, its status changes to VK_NOT_READY. Finally, when the GPU actually
// finishes executing the command buffer, the status changes to VK_SUCCESS.
status.store(initialStatus);
}
explicit VulkanCmdFence(VkFence fence) : mFence(fence) { }
~VulkanCmdFence() = default;
void setStatus(VkResult value) { status.store(value); }
void setStatus(VkResult const value) {
std::lock_guard const l(mLock);
mStatus = value;
mCond.notify_all();
}
VkResult getStatus() { return status.load(std::memory_order_acquire); }
VkResult getStatus() {
std::shared_lock const l(mLock);
return mStatus;
}
void resetFence(VkDevice device);
FenceStatus wait(VkDevice device, uint64_t timeout,
std::chrono::steady_clock::time_point until);
private:
std::atomic<VkResult> status;
std::shared_mutex mLock; // NOLINT(*-include-cleaner)
std::condition_variable_any mCond;
// Internally we use the VK_INCOMPLETE status to mean "not yet submitted". When this fence
// gets submitted, its status changes to VK_NOT_READY. Finally, when the GPU actually
// finishes executing the command buffer, the status changes to VK_SUCCESS.
VkResult mStatus{ VK_INCOMPLETE };
VkFence mFence;
};
struct VulkanFence : public HwFence, fvkmemory::ThreadSafeResource {
VulkanFence() {}
std::shared_ptr<VulkanCmdFence> fence;
void setFence(std::shared_ptr<VulkanCmdFence> fence) {
std::lock_guard lock(mState->lock);
mState->sharedFence = std::move(fence);
mState->cond.notify_all();
}
std::shared_ptr<VulkanCmdFence>& getSharedFence() {
std::lock_guard lock(mState->lock);
return mState->sharedFence;
}
std::shared_ptr<VulkanCmdFence> wait(std::chrono::steady_clock::time_point const until) {
// hold a reference so that our state doesn't disappear while we wait
std::shared_ptr state{ mState };
std::unique_lock lock(state->lock);
state->cond.wait_until(lock, until, [&state] { return bool(state->sharedFence); });
// here mSharedFence will be null if we timed out
return state->sharedFence;
}
private:
struct State {
std::mutex lock;
std::condition_variable cond;
std::shared_ptr<VulkanCmdFence> sharedFence;
};
std::shared_ptr<State> mState{ std::make_shared<State>() };
};
struct VulkanSync : fvkmemory::ThreadSafeResource, public HwSync {
@@ -72,12 +116,12 @@ struct VulkanTimerQuery : public HwTimerQuery, fvkmemory::ThreadSafeResource {
mStoppingQueryIndex(stoppingIndex) {}
void setFence(std::shared_ptr<VulkanCmdFence> fence) noexcept {
std::unique_lock<utils::Mutex> lock(mFenceMutex);
mFence = fence;
std::unique_lock const lock(mFenceMutex);
mFence = std::move(fence);
}
bool isCompleted() noexcept {
std::unique_lock<utils::Mutex> lock(mFenceMutex);
std::unique_lock const lock(mFenceMutex);
// QueryValue is a synchronous call and might occur before beginTimerQuery has written
// anything into the command buffer, which is an error according to the validation layer
// that ships in the Android NDK. Even when AVAILABILITY_BIT is set, validation seems to
@@ -28,24 +28,24 @@ namespace filament::backend {
namespace {
VkBufferUsageFlags getVkBufferUsage(VulkanBufferUsage usage) {
VkBufferUsageFlags getVkBufferUsage(VulkanBufferBinding usage) {
switch (usage) {
case VulkanBufferUsage::VERTEX:
case VulkanBufferBinding::VERTEX:
return VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
case VulkanBufferUsage::INDEX:
case VulkanBufferBinding::INDEX:
return VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
case VulkanBufferUsage::UNIFORM:
case VulkanBufferBinding::UNIFORM:
return VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
case VulkanBufferUsage::SHADER_STORAGE:
case VulkanBufferBinding::SHADER_STORAGE:
return VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
case VulkanBufferUsage::UNKNOWN:
case VulkanBufferBinding::UNKNOWN:
return 0;
}
return 0;
}
}// namespace
} // namespace
VulkanBufferCache::VulkanBufferCache(VulkanContext const& context,
fvkmemory::ResourceManager& resourceManager, VmaAllocator allocator)
@@ -53,11 +53,11 @@ VulkanBufferCache::VulkanBufferCache(VulkanContext const& context,
mResourceManager(resourceManager),
mAllocator(allocator) {}
fvkmemory::resource_ptr<VulkanBuffer> VulkanBufferCache::acquire(VulkanBufferUsage usage,
fvkmemory::resource_ptr<VulkanBuffer> VulkanBufferCache::acquire(VulkanBufferBinding binding,
uint32_t numBytes) noexcept {
assert_invariant(usage != VulkanBufferUsage::UNKNOWN);
assert_invariant(binding != VulkanBufferBinding::UNKNOWN);
BufferPool& bufferPool = getPool(usage);
BufferPool& bufferPool = getPool(binding);
// First check if an allocation exists whose capacity is greater than or equal to the requested
// size.
@@ -71,7 +71,7 @@ fvkmemory::resource_ptr<VulkanBuffer> VulkanBufferCache::acquire(VulkanBufferUsa
// We were not able to find a sufficiently large allocation, so create a new one that is
// recycled after being yielded.
VulkanGpuBuffer const* gpuBuffer = allocate(usage, numBytes);
VulkanGpuBuffer const* gpuBuffer = allocate(binding, numBytes);
return fvkmemory::resource_ptr<VulkanBuffer>::construct(&mResourceManager, gpuBuffer,
[this](VulkanGpuBuffer const* gpuBuffer) { this->release(gpuBuffer); });
}
@@ -93,9 +93,10 @@ void VulkanBufferCache::gc() noexcept {
if (poolIter->second.lastAccessed < evictionTime) {
#if FVK_ENABLED(FVK_DEBUG_VULKAN_BUFFER_CACHE)
FVK_LOGD << "VulkanBufferCache - Destroyed vkBuffer "
<< poolIter->second.gpuBuffer->vkbuffer << " with usage "
<< static_cast<int>(poolIter->second.gpuBuffer->usage) << utils::io::endl;
#endif// FVK_DEBUG_VULKAN_BUFFER_CACHE
<< poolIter->second.gpuBuffer->vkbuffer << " with binding "
<< static_cast<int>(poolIter->second.gpuBuffer->binding)
<< utils::io::endl;
#endif // FVK_DEBUG_VULKAN_BUFFER_CACHE
destroy(poolIter->second.gpuBuffer);
poolIter = bufferPool.erase(poolIter);
@@ -120,35 +121,33 @@ void VulkanBufferCache::terminate() noexcept {
void VulkanBufferCache::release(VulkanGpuBuffer const* gpuBuffer) noexcept {
assert_invariant(gpuBuffer != nullptr);
BufferPool& bufferPool = getPool(gpuBuffer->usage);
BufferPool& bufferPool = getPool(gpuBuffer->binding);
bufferPool.insert(std::make_pair(gpuBuffer->numBytes, UnusedGpuBuffer{
.lastAccessed = mCurrentFrame,
.gpuBuffer = gpuBuffer,
}));
}
VulkanGpuBuffer const* VulkanBufferCache::allocate(VulkanBufferUsage usage,
VulkanGpuBuffer const* VulkanBufferCache::allocate(VulkanBufferBinding binding,
uint32_t numBytes) noexcept {
VkBufferCreateInfo const bufferInfo{
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.size = numBytes,
// `VK_BUFFER_USAGE_TRANSFER_DST_BIT` is needed to allow updating the buffer through
// a staging using `vkCmdCopyBuffer`.
.usage = getVkBufferUsage(usage) | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
.usage = getVkBufferUsage(binding) | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
};
VmaAllocationCreateFlags vmaFlags = 0;
if (usage == VulkanBufferUsage::UNIFORM) {
// In the case of UMA, the uniform buffers will always be mappable
if (mContext.isUnifiedMemoryArchitecture()) {
vmaFlags |= VMA_ALLOCATION_CREATE_MAPPED_BIT |
VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT;
}
// In the case of UMA, the buffers will always be mappable
if (mContext.isUnifiedMemoryArchitecture()) {
vmaFlags |= VMA_ALLOCATION_CREATE_MAPPED_BIT |
VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT;
}
VulkanGpuBuffer* gpuBuffer = new VulkanGpuBuffer{
.numBytes = numBytes,
.usage = usage,
.binding = binding,
};
VmaAllocationCreateInfo const allocInfo{
.flags = vmaFlags,
@@ -161,14 +160,14 @@ VulkanGpuBuffer const* VulkanBufferCache::allocate(VulkanBufferUsage usage,
#if FVK_ENABLED(FVK_DEBUG_VULKAN_BUFFER_CACHE)
if (result != VK_SUCCESS) {
FVK_LOGE << "VulkanBufferCache - failed to allocate a new vkBuffer of size " << numBytes
<< " and usage " << static_cast<int>(usage) << ", error: " << result
<< " and binding " << static_cast<int>(binding) << ", error: " << result
<< utils::io::endl;
} else {
FVK_LOGD << "VulkanBufferCache - allocated a vkBuffer " << gpuBuffer->vkbuffer
<< " of size " << numBytes << " and usage = " << static_cast<int>(usage)
<< " of size " << numBytes << " and binding = " << static_cast<int>(binding)
<< " successfully" << utils::io::endl;
}
#endif// FVK_DEBUG_VULKAN_BUFFER_CACHE
#endif // FVK_DEBUG_VULKAN_BUFFER_CACHE
return gpuBuffer;
}
@@ -179,24 +178,24 @@ void VulkanBufferCache::destroy(VulkanGpuBuffer const* gpuBuffer) noexcept {
gpuBuffer = nullptr;
}
VulkanBufferCache::BufferPool& VulkanBufferCache::getPool(VulkanBufferUsage usage) noexcept {
VulkanBufferCache::BufferPool& VulkanBufferCache::getPool(VulkanBufferBinding binding) noexcept {
int poolIndex = -1;
switch (usage) {
case VulkanBufferUsage::VERTEX:
switch (binding) {
case VulkanBufferBinding::VERTEX:
poolIndex = 0;
break;
case VulkanBufferUsage::INDEX:
case VulkanBufferBinding::INDEX:
poolIndex = 1;
break;
case VulkanBufferUsage::UNIFORM:
case VulkanBufferBinding::UNIFORM:
poolIndex = 2;
break;
case VulkanBufferUsage::SHADER_STORAGE:
case VulkanBufferBinding::SHADER_STORAGE:
poolIndex = 3;
break;
case VulkanBufferUsage::UNKNOWN:
PANIC_LOG("There's no pool for buffers with unkown usage.");
case VulkanBufferBinding::UNKNOWN:
PANIC_LOG("There's no pool for buffers with unkown binding.");
break;
}
@@ -204,4 +203,4 @@ VulkanBufferCache::BufferPool& VulkanBufferCache::getPool(VulkanBufferUsage usag
return mGpuBufferPools[poolIndex];
}
}// namespace filament::backend
} // namespace filament::backend
@@ -38,7 +38,7 @@ public:
// Allocates or reuse a new VkBuffer that is device local.
// In the case of Unified memory architecture, uniform buffers are also host visible.
fvkmemory::resource_ptr<VulkanBuffer> acquire(VulkanBufferUsage usage,
fvkmemory::resource_ptr<VulkanBuffer> acquire(VulkanBufferBinding binding,
uint32_t numBytes) noexcept;
// Evicts old unused `VulkanGpuBuffer` and bumps the current frame number
@@ -60,12 +60,12 @@ private:
void release(VulkanGpuBuffer const* gpuBuffer) noexcept;
// Allocate a new VkBuffer from the VMA pool of the corresponding `numBytes` and `usage`.
VulkanGpuBuffer const* allocate(VulkanBufferUsage usage, uint32_t numBytes) noexcept;
VulkanGpuBuffer const* allocate(VulkanBufferBinding binding, uint32_t numBytes) noexcept;
// Destroy the corresponding VkBuffer and return the VkDeviceMemory to the VMA pool.
void destroy(VulkanGpuBuffer const* gpuBuffer) noexcept;
BufferPool& getPool(VulkanBufferUsage usage) noexcept;
BufferPool& getPool(VulkanBufferBinding binding) noexcept;
VulkanContext const& mContext;
fvkmemory::ResourceManager& mResourceManager;
@@ -19,22 +19,25 @@
#include "VulkanBufferCache.h"
#include "VulkanCommands.h"
#include "VulkanContext.h"
#include "VulkanMemory.h"
#include "VulkanHandles.h"
#include "VulkanMemory.h"
#include <backend/DriverEnums.h>
using namespace bluevk;
namespace filament::backend {
VulkanBufferProxy::VulkanBufferProxy(VulkanContext const& context, VmaAllocator allocator,
VulkanStagePool& stagePool, VulkanBufferCache& bufferCache, VulkanBufferUsage usage,
uint32_t numBytes)
VulkanStagePool& stagePool, VulkanBufferCache& bufferCache, VulkanBufferBinding binding,
BufferUsage usage, uint32_t numBytes)
: mStagingBufferBypassEnabled(context.stagingBufferBypassEnabled()),
mAllocator(allocator),
mStagePool(stagePool),
mBufferCache(bufferCache),
mBuffer(mBufferCache.acquire(usage, numBytes)),
mLastReadAge(0) {}
mBuffer(mBufferCache.acquire(binding, numBytes)),
mLastReadAge(0),
mUsage(usage) {}
void VulkanBufferProxy::loadFromCpu(VulkanCommandBuffer& commands, const void* cpuData,
uint32_t byteOffset, uint32_t numBytes) {
@@ -49,12 +52,18 @@ void VulkanBufferProxy::loadFromCpu(VulkanCommandBuffer& commands, const void* c
commands.acquire(mBuffer);
// Check if we can just memcpy directly to the GPU memory.
// This is only allowed for UNIFORMS that are AVAILABLE and the memory is HOST_VISIBLE
// (supports memcpy from host). This works regardless if it's a full or partial update of the
// buffer.
bool const isMemcopyable = mBuffer->getGpuBuffer()->allocationInfo.pMappedData != nullptr;
bool const isUniform = getUsage() == VulkanBufferUsage::UNIFORM;
bool const useMemcpy = isUniform && isMemcopyable && isAvailable && mStagingBufferBypassEnabled;
// In the case of UNIFORMS, check that is available to see to know if a memcpy is possible.
// This works regardless if it's a full or partial update of the buffer.
bool const isUniformAndAvailable = getBinding() == VulkanBufferBinding::UNIFORM && isAvailable;
// In the case the content is marked as memory mapped or static, is guaranteed to be safe to do
// a memcpy if its available.
bool const isStaticOrShared =
any(mUsage & (BufferUsage::STATIC | BufferUsage::SHARED_WRITE_BIT));
bool const useMemcpy = (isUniformAndAvailable || isStaticOrShared) && isMemcopyable &&
mStagingBufferBypassEnabled;
if (useMemcpy) {
char* dest = static_cast<char*>(mBuffer->getGpuBuffer()->allocationInfo.pMappedData) +
byteOffset;
@@ -81,13 +90,13 @@ void VulkanBufferProxy::loadFromCpu(VulkanCommandBuffer& commands, const void* c
if (!isAvailable) {
VkAccessFlags srcAccess = 0;
VkPipelineStageFlags srcStage = 0;
if (getUsage() == VulkanBufferUsage::UNIFORM) {
if (getBinding() == VulkanBufferBinding::UNIFORM) {
srcAccess = VK_ACCESS_SHADER_READ_BIT;
srcStage = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
} else if (getUsage() == VulkanBufferUsage::VERTEX) {
} else if (getBinding() == VulkanBufferBinding::VERTEX) {
srcAccess = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
srcStage = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
} else if (getUsage() == VulkanBufferUsage::INDEX) {
} else if (getBinding() == VulkanBufferBinding::INDEX) {
srcAccess = VK_ACCESS_INDEX_READ_BIT;
srcStage = VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
}
@@ -120,16 +129,16 @@ void VulkanBufferProxy::loadFromCpu(VulkanCommandBuffer& commands, const void* c
VkAccessFlags dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
VkPipelineStageFlags dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
if (getUsage() == VulkanBufferUsage::VERTEX) {
if (getBinding() == VulkanBufferBinding::VERTEX) {
dstAccessMask |= VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT;
dstStageMask |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
} else if (getUsage() == VulkanBufferUsage::INDEX) {
} else if (getBinding() == VulkanBufferBinding::INDEX) {
dstAccessMask |= VK_ACCESS_INDEX_READ_BIT;
dstStageMask |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
} else if (getUsage() == VulkanBufferUsage::UNIFORM) {
} else if (getBinding() == VulkanBufferBinding::UNIFORM) {
dstAccessMask |= VK_ACCESS_SHADER_READ_BIT;
dstStageMask |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT;
} else if (getUsage() == VulkanBufferUsage::SHADER_STORAGE) {
} else if (getBinding() == VulkanBufferBinding::SHADER_STORAGE) {
// TODO: implement me
}
@@ -152,8 +161,8 @@ VkBuffer VulkanBufferProxy::getVkBuffer() const noexcept {
return mBuffer->getGpuBuffer()->vkbuffer;
}
VulkanBufferUsage VulkanBufferProxy::getUsage() const noexcept {
return mBuffer->getGpuBuffer()->usage;
VulkanBufferBinding VulkanBufferProxy::getBinding() const noexcept {
return mBuffer->getGpuBuffer()->binding;
}
void VulkanBufferProxy::referencedBy(VulkanCommandBuffer& commands) {
@@ -23,6 +23,8 @@
#include "VulkanMemory.h"
#include "VulkanStagePool.h"
#include <backend/DriverEnums.h>
namespace filament::backend {
struct VulkanDescriptorSet;
@@ -33,8 +35,8 @@ struct VulkanCommandBuffer;
class VulkanBufferProxy {
public:
VulkanBufferProxy(VulkanContext const& context, VmaAllocator allocator,
VulkanStagePool& stagePool, VulkanBufferCache& bufferCache, VulkanBufferUsage usage,
uint32_t numBytes);
VulkanStagePool& stagePool, VulkanBufferCache& bufferCache, VulkanBufferBinding binding,
BufferUsage usage, uint32_t numBytes);
void loadFromCpu(VulkanCommandBuffer& commands, const void* cpuData, uint32_t byteOffset,
uint32_t numBytes);
@@ -44,7 +46,7 @@ public:
void referencedBy(VulkanCommandBuffer& commands);
private:
VulkanBufferUsage getUsage() const noexcept;
VulkanBufferBinding getBinding() const noexcept;
bool const mStagingBufferBypassEnabled;
VmaAllocator mAllocator;
@@ -54,6 +56,7 @@ private:
fvkmemory::resource_ptr<VulkanBuffer> mBuffer;
uint32_t mLastReadAge;
BufferUsage mUsage;
};
} // namespace filament::backend
+36 -27
View File
@@ -90,18 +90,17 @@ bool VulkanGroupMarkers::empty() const noexcept {
uint32_t VulkanCommandBuffer::sAgeCounter = 0;
VulkanCommandBuffer::VulkanCommandBuffer(VulkanContext const& context, VkDevice device,
VkQueue queue, VkCommandPool pool, bool isProtected)
VkQueue queue, VkCommandPool pool, VulkanSemaphoreManager* semaphoreManager,
bool isProtected)
: mContext(context),
mMarkerCount(0),
isProtected(isProtected),
mDevice(device),
mQueue(queue),
mSemaphoreManager(semaphoreManager),
mBuffer(createCommandBuffer(device, pool)),
mFenceStatus(std::make_shared<VulkanCmdFence>(VK_INCOMPLETE)),
mSubmission(semaphoreManager->acquire()),
mAge(++sAgeCounter) {
VkSemaphoreCreateInfo sci{.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
vkCreateSemaphore(mDevice, &sci, VKALLOC, &mSubmission);
VkFenceCreateInfo fenceCreateInfo{.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};
VkExportFenceCreateInfo exportFenceCreateInfo{
.sType = VK_STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO,
@@ -113,10 +112,11 @@ VulkanCommandBuffer::VulkanCommandBuffer(VulkanContext const& context, VkDevice
fenceCreateInfo.pNext = &exportFenceCreateInfo;
}
vkCreateFence(device, &fenceCreateInfo, VKALLOC, &mFence);
mFenceStatus = std::make_shared<VulkanCmdFence>(mFence);
}
VulkanCommandBuffer::~VulkanCommandBuffer() {
vkDestroySemaphore(mDevice, mSubmission, VKALLOC);
vkDestroyFence(mDevice, mFence, VKALLOC);
}
@@ -126,12 +126,15 @@ void VulkanCommandBuffer::reset() noexcept {
mWaitSemaphores.clear();
mWaitSemaphoreStages.clear();
mAge = ++sAgeCounter;
mSubmission = mSemaphoreManager->acquire();
// reset the fence with proper host synchronization
mFenceStatus->resetFence(mDevice);
// Internally we use the VK_INCOMPLETE status to mean "not yet submitted". When this fence
// gets, gets submitted, its status changes to VK_NOT_READY. Finally, when the GPU actually
// finishes executing the command buffer, the status changes to VK_SUCCESS.
mFenceStatus = std::make_shared<VulkanCmdFence>(VK_INCOMPLETE);
vkResetFences(mDevice, 1, &mFence);
mFenceStatus = std::make_shared<VulkanCmdFence>(mFence);
}
void VulkanCommandBuffer::pushMarker(char const* marker) noexcept {
@@ -190,13 +193,14 @@ void VulkanCommandBuffer::begin() noexcept {
vkBeginCommandBuffer(mBuffer, &binfo);
}
VkSemaphore VulkanCommandBuffer::submit() {
fvkmemory::resource_ptr<VulkanSemaphore> VulkanCommandBuffer::submit() {
while (mMarkerCount > 0) {
popMarker();
}
vkEndCommandBuffer(mBuffer);
VkSemaphore submissionSemaphore = mSubmission->getVkSemaphore();
VkSubmitInfo submitInfo{
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.waitSemaphoreCount = mWaitSemaphores.size(),
@@ -205,7 +209,7 @@ VkSemaphore VulkanCommandBuffer::submit() {
.commandBufferCount = 1u,
.pCommandBuffers = &mBuffer,
.signalSemaphoreCount = 1u,
.pSignalSemaphores = &mSubmission,
.pSignalSemaphores = &submissionSemaphore,
};
// add submit protection if needed
VkProtectedSubmitInfo protectedSubmitInfo{
@@ -226,13 +230,13 @@ VkSemaphore VulkanCommandBuffer::submit() {
<< (s < mWaitSemaphores.size() - 1 ? "\n" : "");
}
FVK_LOGI << ") "
<< " signal=" << mSubmission
<< " signal=" << submissionSemaphore
<< " fence=" << mFence;
#endif
mFenceStatus->setStatus(VK_NOT_READY);
UTILS_UNUSED_IN_RELEASE VkResult result =
vkQueueSubmit(mQueue, 1, &submitInfo, mFence);
mFenceStatus->setStatus(VK_NOT_READY);
#if FVK_ENABLED(FVK_DEBUG_COMMAND_BUFFER)
if (result != VK_SUCCESS) {
@@ -245,7 +249,7 @@ VkSemaphore VulkanCommandBuffer::submit() {
}
CommandBufferPool::CommandBufferPool(VulkanContext const& context, VkDevice device, VkQueue queue,
uint8_t queueFamilyIndex, bool isProtected)
uint8_t queueFamilyIndex, VulkanSemaphoreManager* semaphoreManager, bool isProtected)
: mDevice(device),
mRecording(INVALID) {
VkCommandPoolCreateInfo createInfo = {
@@ -258,8 +262,8 @@ CommandBufferPool::CommandBufferPool(VulkanContext const& context, VkDevice devi
vkCreateCommandPool(device, &createInfo, VKALLOC, &mPool);
for (size_t i = 0; i < CAPACITY; ++i) {
mBuffers.emplace_back(
std::make_unique<VulkanCommandBuffer>(context, device, queue, mPool, isProtected));
mBuffers.emplace_back(std::make_unique<VulkanCommandBuffer>(
context, device, queue, mPool, semaphoreManager, isProtected));
}
}
@@ -331,10 +335,10 @@ void CommandBufferPool::update() {
});
}
VkSemaphore CommandBufferPool::flush() {
fvkmemory::resource_ptr<VulkanSemaphore> CommandBufferPool::flush() {
// We're not recording right now.
if (!isRecording()) {
return VK_NULL_HANDLE;
return {};
}
auto submitSemaphore = mBuffers[mRecording]->submit();
mSubmitted.set(mRecording, true);
@@ -396,16 +400,21 @@ void CommandBufferPool::insertEvent(char const* marker) {
#endif // FVK_DEBUG_GROUP_MARKERS
VulkanCommands::VulkanCommands(VkDevice device, VkQueue queue, uint32_t queueFamilyIndex,
VkQueue protectedQueue, uint32_t protectedQueueFamilyIndex, VulkanContext const& context)
VkQueue protectedQueue, uint32_t protectedQueueFamilyIndex, VulkanContext const& context,
VulkanSemaphoreManager* semaphoreManager)
: mDevice(device),
mProtectedQueue(protectedQueue),
mProtectedQueueFamilyIndex(protectedQueueFamilyIndex),
mContext(context),
mPool(std::make_unique<CommandBufferPool>(context, device, queue, queueFamilyIndex, false)) {}
mSemaphoreManager(semaphoreManager),
mPool(std::make_unique<CommandBufferPool>(
context, device, queue, queueFamilyIndex, semaphoreManager, false)) {}
void VulkanCommands::terminate() {
mPool.reset();
mProtectedPool.reset();
mLastSubmit = {};
mLastFenceStatus = {};
}
VulkanCommandBuffer& VulkanCommands::get() {
@@ -418,7 +427,7 @@ VulkanCommandBuffer& VulkanCommands::getProtected() {
if (!mProtectedPool) {
mProtectedPool = std::make_unique<CommandBufferPool>(mContext, mDevice, mProtectedQueue,
mProtectedQueueFamilyIndex, true);
mProtectedQueueFamilyIndex, mSemaphoreManager, true);
}
auto& ret = mProtectedPool->getRecording();
return ret;
@@ -430,8 +439,8 @@ bool VulkanCommands::flush() {
return false;
}
VkSemaphore dependency = mInjectedDependency;
VkSemaphore lastSubmit = mLastSubmit;
VkSemaphore injectedDependency = mInjectedDependency;
fvkmemory::resource_ptr<VulkanSemaphore> dependency;
bool hasFlushed = false;
VkFence flushedFence = VK_NULL_HANDLE;
@@ -444,19 +453,19 @@ bool VulkanCommands::flush() {
if (!pool || !pool->isRecording()) {
continue;
}
if (dependency != VK_NULL_HANDLE) {
pool->waitFor(dependency, mInjectedDependencyWaitStage);
if (injectedDependency != VK_NULL_HANDLE) {
pool->waitFor(injectedDependency, mInjectedDependencyWaitStage);
}
if (lastSubmit != VK_NULL_HANDLE) {
if (mLastSubmit) {
// Note that the stage we're waiting on is the fragment shader stage. This assumes
// that the subsequent command buffer will only depend on
// 1) fragment output of the previous command buffer
// 2) reading/writing of buffers (i.e. UBO) of the previous command buffer
// Restricting the wait stages will allow for vertex work to proceed (more overlapping
// vertex/fragment work).
pool->waitFor(lastSubmit,
pool->waitFor(mLastSubmit->getVkSemaphore(),
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT);
lastSubmit = VK_NULL_HANDLE;
mLastSubmit = {};
}
flushedFence = pool->getRecording().getVkFence();
flushedFenceStatus = pool->getRecording().getFenceStatus();
+15 -12
View File
@@ -24,6 +24,7 @@
#include "VulkanAsyncHandles.h"
#include "VulkanConstants.h"
#include "VulkanContext.h"
#include "VulkanSemaphoreManager.h"
#include "vulkan/memory/ResourcePointer.h"
#include "vulkan/utils/StaticVector.h"
@@ -63,8 +64,8 @@ private:
// DriverApi fence object and should not be destroyed until both the DriverApi object is freed and
// we're done waiting on the most recent submission of the given command buffer.
struct VulkanCommandBuffer {
VulkanCommandBuffer(VulkanContext const& mContext,
VkDevice device, VkQueue queue, VkCommandPool pool, bool isProtected);
VulkanCommandBuffer(VulkanContext const& mContext, VkDevice device, VkQueue queue,
VkCommandPool pool, VulkanSemaphoreManager* semaphoreManager, bool isProtected);
VulkanCommandBuffer(VulkanCommandBuffer const&) = delete;
VulkanCommandBuffer& operator=(VulkanCommandBuffer const&) = delete;
@@ -87,7 +88,7 @@ struct VulkanCommandBuffer {
void insertEvent(char const* marker) noexcept;
void begin() noexcept;
VkSemaphore submit();
fvkmemory::resource_ptr<VulkanSemaphore> submit();
inline void setComplete() {
mFenceStatus->setStatus(VK_SUCCESS);
@@ -121,10 +122,11 @@ private:
bool const isProtected;
VkDevice mDevice;
VkQueue mQueue;
VulkanSemaphoreManager* mSemaphoreManager;
fvkutils::StaticVector<VkSemaphore, 2> mWaitSemaphores;
fvkutils::StaticVector<VkPipelineStageFlags, 2> mWaitSemaphoreStages;
VkCommandBuffer mBuffer;
VkSemaphore mSubmission;
fvkmemory::resource_ptr<VulkanSemaphore> mSubmission;
VkFence mFence;
std::shared_ptr<VulkanCmdFence> mFenceStatus;
std::vector<fvkmemory::resource_ptr<Resource>> mResources;
@@ -136,14 +138,14 @@ struct CommandBufferPool {
static constexpr int8_t INVALID = -1;
CommandBufferPool(VulkanContext const& context, VkDevice device, VkQueue queue,
uint8_t queueFamilyIndex, bool isProtected);
uint8_t queueFamilyIndex, VulkanSemaphoreManager* semaphoreManager, bool isProtected);
~CommandBufferPool();
VulkanCommandBuffer& getRecording();
void gc();
void update();
VkSemaphore flush();
fvkmemory::resource_ptr<VulkanSemaphore> flush();
void wait();
void waitFor(VkSemaphore previousAction, VkPipelineStageFlags waitStage);
@@ -204,7 +206,7 @@ class VulkanCommands {
public:
VulkanCommands(VkDevice device, VkQueue queue, uint32_t queueFamilyIndex,
VkQueue protectedQueue, uint32_t protectedQueueFamilyIndex,
VulkanContext const& context);
VulkanContext const& context, VulkanSemaphoreManager* semaphoreManager);
void terminate();
@@ -222,10 +224,10 @@ public:
// Returns the "rendering finished" semaphore for the most recent flush and removes
// it from the existing dependency chain. This is especially useful for setting up
// vkQueuePresentKHR.
VkSemaphore acquireFinishedSignal() {
VkSemaphore ret = mLastSubmit;
mLastSubmit = VK_NULL_HANDLE;
return ret;
fvkmemory::resource_ptr<VulkanSemaphore> acquireFinishedSignal() {
fvkmemory::resource_ptr<VulkanSemaphore> sem = mLastSubmit;
mLastSubmit = {};
return sem;
}
VkFence getMostRecentFence() {
@@ -266,12 +268,13 @@ private:
// For defered initialization if/when we need protected content
uint32_t const mProtectedQueueFamilyIndex;
VulkanContext const& mContext;
VulkanSemaphoreManager* mSemaphoreManager;
std::unique_ptr<CommandBufferPool> mPool;
std::unique_ptr<CommandBufferPool> mProtectedPool;
VkSemaphore mInjectedDependency = VK_NULL_HANDLE;
VkSemaphore mLastSubmit = VK_NULL_HANDLE;
fvkmemory::resource_ptr<VulkanSemaphore> mLastSubmit;
VkFence mLastFence = VK_NULL_HANDLE;
std::shared_ptr<VulkanCmdFence> mLastFenceStatus;
+56 -47
View File
@@ -37,12 +37,15 @@
#include <utils/compiler.h>
#include <utils/CString.h>
#include <utils/ImmutableCString.h>
#include <utils/Panic.h>
#ifndef NDEBUG
#include <set> // For VulkanDriver::debugCommandBegin
#endif
#include <chrono>
using namespace bluevk;
#if defined(__clang__)
@@ -222,9 +225,10 @@ VulkanDriver::VulkanDriver(VulkanPlatform* platform, VulkanContext& context,
mAllocator(createAllocator(mPlatform->getInstance(), mPlatform->getPhysicalDevice(),
mPlatform->getDevice())),
mContext(context),
mSemaphoreManager(mPlatform->getDevice(), &mResourceManager),
mCommands(mPlatform->getDevice(), mPlatform->getGraphicsQueue(),
mPlatform->getGraphicsQueueFamilyIndex(), mPlatform->getProtectedGraphicsQueue(),
mPlatform->getProtectedGraphicsQueueFamilyIndex(), mContext),
mPlatform->getProtectedGraphicsQueueFamilyIndex(), mContext, &mSemaphoreManager),
mPipelineLayoutCache(mPlatform->getDevice()),
mPipelineCache(mPlatform->getDevice()),
mStagePool(mAllocator, &mResourceManager, &mCommands, &mContext.getPhysicalDeviceLimits()),
@@ -319,8 +323,9 @@ ShaderModel VulkanDriver::getShaderModel() const noexcept {
#endif
}
ShaderLanguage VulkanDriver::getShaderLanguage() const noexcept {
return ShaderLanguage::SPIRV;
utils::FixedCapacityVector<ShaderLanguage> VulkanDriver::getShaderLanguages(
ShaderLanguage /*prefferedLanguage*/) const noexcept {
return { ShaderLanguage::SPIRV };
}
void VulkanDriver::terminate() {
@@ -365,6 +370,9 @@ void VulkanDriver::terminate() {
// reclaimed, as they perform cleanup within the stage pool.
mStagePool.terminate();
// By this point, all of the VkSemaphores should have been returned to the pool.
mSemaphoreManager.terminate();
#if FVK_ENABLED(FVK_DEBUG_RESOURCE_LEAK)
mResourceManager.print();
#endif
@@ -517,7 +525,7 @@ void VulkanDriver::finish(int dummy) {
void VulkanDriver::createRenderPrimitiveR(Handle<HwRenderPrimitive> rph,
Handle<HwVertexBuffer> vbh, Handle<HwIndexBuffer> ibh,
PrimitiveType pt, utils::CString&& tag) {
PrimitiveType pt, utils::ImmutableCString&& tag) {
FVK_SYSTRACE_SCOPE();
auto vb = resource_ptr<VulkanVertexBuffer>::cast(&mResourceManager, vbh);
auto ib = resource_ptr<VulkanIndexBuffer>::cast(&mResourceManager, ibh);
@@ -536,7 +544,7 @@ void VulkanDriver::destroyRenderPrimitive(Handle<HwRenderPrimitive> rph) {
}
void VulkanDriver::createVertexBufferInfoR(Handle<HwVertexBufferInfo> vbih, uint8_t bufferCount,
uint8_t attributeCount, AttributeArray attributes, utils::CString&& tag) {
uint8_t attributeCount, AttributeArray attributes, utils::ImmutableCString&& tag) {
FVK_SYSTRACE_SCOPE();
auto vbi = resource_ptr<VulkanVertexBufferInfo>::make(&mResourceManager, vbih, bufferCount,
attributeCount, attributes);
@@ -554,7 +562,7 @@ void VulkanDriver::destroyVertexBufferInfo(Handle<HwVertexBufferInfo> vbih) {
}
void VulkanDriver::createVertexBufferR(Handle<HwVertexBuffer> vbh, uint32_t vertexCount,
Handle<HwVertexBufferInfo> vbih, utils::CString&& tag) {
Handle<HwVertexBufferInfo> vbih, utils::ImmutableCString&& tag) {
FVK_SYSTRACE_SCOPE();
auto vbi = resource_ptr<VulkanVertexBufferInfo>::cast(&mResourceManager, vbih);
auto vb = resource_ptr<VulkanVertexBuffer>::make(&mResourceManager, vbh, mContext, mStagePool,
@@ -573,7 +581,7 @@ void VulkanDriver::destroyVertexBuffer(Handle<HwVertexBuffer> vbh) {
}
void VulkanDriver::createIndexBufferR(Handle<HwIndexBuffer> ibh, ElementType elementType,
uint32_t indexCount, BufferUsage usage, utils::CString&& tag) {
uint32_t indexCount, BufferUsage usage, utils::ImmutableCString&& tag) {
FVK_SYSTRACE_SCOPE();
auto elementSize = (uint8_t) getElementTypeSize(elementType);
auto ib = resource_ptr<VulkanIndexBuffer>::make(&mResourceManager, ibh, mContext, mAllocator,
@@ -592,10 +600,10 @@ void VulkanDriver::destroyIndexBuffer(Handle<HwIndexBuffer> ibh) {
}
void VulkanDriver::createBufferObjectR(Handle<HwBufferObject> boh, uint32_t byteCount,
BufferObjectBinding bindingType, BufferUsage usage, utils::CString&& tag) {
BufferObjectBinding bindingType, BufferUsage usage, utils::ImmutableCString&& tag) {
FVK_SYSTRACE_SCOPE();
auto bo = resource_ptr<VulkanBufferObject>::make(&mResourceManager, boh, mContext, mAllocator,
mStagePool, mBufferCache, byteCount, bindingType);
mStagePool, mBufferCache, byteCount, bindingType, usage);
bo.inc();
mResourceManager.associateHandle(boh.getId(), std::move(tag));
}
@@ -611,7 +619,7 @@ void VulkanDriver::destroyBufferObject(Handle<HwBufferObject> boh) {
void VulkanDriver::createTextureR(Handle<HwTexture> th, SamplerType target, uint8_t levels,
TextureFormat format, uint8_t samples, uint32_t w, uint32_t h, uint32_t depth,
TextureUsage usage, utils::CString&& tag) {
TextureUsage usage, utils::ImmutableCString&& tag) {
FVK_SYSTRACE_SCOPE();
auto texture = resource_ptr<VulkanTexture>::make(&mResourceManager, th, mPlatform->getDevice(),
mPlatform->getPhysicalDevice(), mContext, mAllocator, &mResourceManager, &mCommands,
@@ -628,7 +636,7 @@ void VulkanDriver::createTextureR(Handle<HwTexture> th, SamplerType target, uint
}
void VulkanDriver::createTextureViewR(Handle<HwTexture> th, Handle<HwTexture> srch,
uint8_t baseLevel, uint8_t levelCount, utils::CString&& tag) {
uint8_t baseLevel, uint8_t levelCount, utils::ImmutableCString&& tag) {
auto src = resource_ptr<VulkanTexture>::cast(&mResourceManager, srch);
auto texture = resource_ptr<VulkanTexture>::make(&mResourceManager, th, mPlatform->getDevice(),
mPlatform->getPhysicalDevice(), mContext, mAllocator, &mCommands, src, baseLevel,
@@ -639,7 +647,7 @@ void VulkanDriver::createTextureViewR(Handle<HwTexture> th, Handle<HwTexture> sr
void VulkanDriver::createTextureViewSwizzleR(Handle<HwTexture> th, Handle<HwTexture> srch,
backend::TextureSwizzle r, backend::TextureSwizzle g, backend::TextureSwizzle b,
backend::TextureSwizzle a, utils::CString&& tag) {
backend::TextureSwizzle a, utils::ImmutableCString&& tag) {
TextureSwizzle const swizzleArray[] = { r, g, b, a };
VkComponentMapping const swizzle = fvkutils::getSwizzleMap(swizzleArray);
auto src = resource_ptr<VulkanTexture>::cast(&mResourceManager, srch);
@@ -651,7 +659,7 @@ void VulkanDriver::createTextureViewSwizzleR(Handle<HwTexture> th, Handle<HwText
void VulkanDriver::createTextureExternalImage2R(Handle<HwTexture> th, backend::SamplerType target,
backend::TextureFormat format, uint32_t width, uint32_t height, backend::TextureUsage usage,
Platform::ExternalImageHandleRef externalImage, utils::CString&& tag) {
Platform::ExternalImageHandleRef externalImage, utils::ImmutableCString&& tag) {
FVK_SYSTRACE_SCOPE();
auto metadata = mPlatform->extractExternalImageMetadata(externalImage);
@@ -702,7 +710,7 @@ void VulkanDriver::createTextureExternalImage2R(Handle<HwTexture> th, backend::S
void VulkanDriver::createTextureExternalImageR(Handle<HwTexture> th, backend::SamplerType target,
backend::TextureFormat format, uint32_t width, uint32_t height, backend::TextureUsage usage,
void* externalImage, utils::CString&& tag) {
void* externalImage, utils::ImmutableCString&& tag) {
FVK_SYSTRACE_SCOPE();
assert_invariant(false && "Not supported in Vulkan backend");
// not supported in this backend
@@ -710,14 +718,14 @@ void VulkanDriver::createTextureExternalImageR(Handle<HwTexture> th, backend::Sa
void VulkanDriver::createTextureExternalImagePlaneR(Handle<HwTexture> th,
backend::TextureFormat format, uint32_t width, uint32_t height, backend::TextureUsage usage,
void* image, uint32_t plane, utils::CString&& tag) {
void* image, uint32_t plane, utils::ImmutableCString&& tag) {
assert_invariant(false && "Not supported in Vulkan backend");
}
void VulkanDriver::importTextureR(Handle<HwTexture> th, intptr_t id,
SamplerType target, uint8_t levels,
TextureFormat format, uint8_t samples, uint32_t w, uint32_t h, uint32_t depth,
TextureUsage usage, utils::CString&& tag) {
TextureUsage usage, utils::ImmutableCString&& tag) {
// not supported in this backend
assert_invariant(false && "Not supported in Vulkan backend");
mResourceManager.associateHandle(th.getId(), std::move(tag));
@@ -733,7 +741,7 @@ void VulkanDriver::destroyTexture(Handle<HwTexture> th) {
mExternalImageManager.removeExternallySampledTexture(texture);
}
void VulkanDriver::createProgramR(Handle<HwProgram> ph, Program&& program, utils::CString&& tag) {
void VulkanDriver::createProgramR(Handle<HwProgram> ph, Program&& program, utils::ImmutableCString&& tag) {
FVK_SYSTRACE_SCOPE();
auto vprogram = resource_ptr<VulkanProgram>::make(&mResourceManager, ph, mPlatform->getDevice(),
program);
@@ -749,7 +757,7 @@ void VulkanDriver::destroyProgram(Handle<HwProgram> ph) {
vprogram.dec();
}
void VulkanDriver::createDefaultRenderTargetR(Handle<HwRenderTarget> rth, utils::CString&& tag) {
void VulkanDriver::createDefaultRenderTargetR(Handle<HwRenderTarget> rth, utils::ImmutableCString&& tag) {
assert_invariant(mDefaultRenderTarget); // Default render target should already exist.
auto renderTarget = resource_ptr<VulkanRenderTarget>::make(&mResourceManager, rth,
@@ -762,7 +770,7 @@ void VulkanDriver::createDefaultRenderTargetR(Handle<HwRenderTarget> rth, utils:
void VulkanDriver::createRenderTargetR(Handle<HwRenderTarget> rth,
TargetBufferFlags targets, uint32_t width, uint32_t height, uint8_t samples,
uint8_t layerCount, MRT color, TargetBufferInfo depth, TargetBufferInfo stencil,
utils::CString&& tag) {
utils::ImmutableCString&& tag) {
FVK_SYSTRACE_SCOPE();
@@ -839,7 +847,7 @@ void VulkanDriver::destroyRenderTarget(Handle<HwRenderTarget> rth) {
}
}
void VulkanDriver::createFenceR(Handle<HwFence> fh, utils::CString&& tag) {
void VulkanDriver::createFenceR(Handle<HwFence> fh, utils::ImmutableCString&& tag) {
VulkanCommandBuffer* cmdbuf;
if (mCurrentRenderPass.commandBuffer) {
cmdbuf = mCurrentRenderPass.commandBuffer;
@@ -850,11 +858,11 @@ void VulkanDriver::createFenceR(Handle<HwFence> fh, utils::CString&& tag) {
// it with appropriate VulkanCmdFence, which is associated with the current, recording command
// buffer.
auto fence = resource_ptr<VulkanFence>::cast(&mResourceManager, fh);
fence->fence = cmdbuf->getFenceStatus();
fence->setFence(cmdbuf->getFenceStatus());
mResourceManager.associateHandle(fh.getId(), std::move(tag));
}
void VulkanDriver::createSyncR(Handle<HwSync> sh, utils::CString&& tag) {
void VulkanDriver::createSyncR(Handle<HwSync> sh, utils::ImmutableCString&& tag) {
auto sync = resource_ptr<VulkanSync>::cast(&mResourceManager, sh);
VkFence fence = VK_NULL_HANDLE;
std::shared_ptr<VulkanCmdFence> fenceStatus;
@@ -885,7 +893,7 @@ void VulkanDriver::createSyncR(Handle<HwSync> sh, utils::CString&& tag) {
}
void VulkanDriver::createSwapChainR(Handle<HwSwapChain> sch, void* nativeWindow, uint64_t flags,
utils::CString&& tag) {
utils::ImmutableCString&& tag) {
FVK_SYSTRACE_SCOPE();
// Running gc() to guard against an edge case where the old swapchains need to have been
// destroyed before the new swapchain can be created. Otherwise, we would fail
@@ -914,7 +922,7 @@ void VulkanDriver::createSwapChainR(Handle<HwSwapChain> sch, void* nativeWindow,
}
void VulkanDriver::createSwapChainHeadlessR(Handle<HwSwapChain> sch, uint32_t width,
uint32_t height, uint64_t flags, utils::CString&& tag) {
uint32_t height, uint64_t flags, utils::ImmutableCString&& tag) {
if ((flags & backend::SWAP_CHAIN_CONFIG_SRGB_COLORSPACE) != 0 && !isSRGBSwapChainSupported()) {
FVK_LOGW << "sRGB swapchain requested, but Platform does not support it";
flags = flags | ~(backend::SWAP_CHAIN_CONFIG_SRGB_COLORSPACE);
@@ -927,13 +935,13 @@ void VulkanDriver::createSwapChainHeadlessR(Handle<HwSwapChain> sch, uint32_t wi
mResourceManager.associateHandle(sch.getId(), std::move(tag));
}
void VulkanDriver::createTimerQueryR(Handle<HwTimerQuery> tqh, utils::CString&& tag) {
void VulkanDriver::createTimerQueryR(Handle<HwTimerQuery> tqh, utils::ImmutableCString&& tag) {
// nothing to do, timer query was constructed in createTimerQueryS
mResourceManager.associateHandle(tqh.getId(), std::move(tag));
}
void VulkanDriver::createDescriptorSetLayoutR(Handle<HwDescriptorSetLayout> dslh,
backend::DescriptorSetLayout&& info, utils::CString&& tag) {
backend::DescriptorSetLayout&& info, utils::ImmutableCString&& tag) {
FVK_SYSTRACE_SCOPE();
auto layout = mDescriptorSetLayoutCache.createLayout(dslh, std::move(info));
layout.inc();
@@ -941,7 +949,7 @@ void VulkanDriver::createDescriptorSetLayoutR(Handle<HwDescriptorSetLayout> dslh
}
void VulkanDriver::createDescriptorSetR(Handle<HwDescriptorSet> dsh,
Handle<HwDescriptorSetLayout> dslh, utils::CString&& tag) {
Handle<HwDescriptorSetLayout> dslh, utils::ImmutableCString&& tag) {
FVK_SYSTRACE_SCOPE();
fvkmemory::resource_ptr<VulkanDescriptorSetLayout> layout =
fvkmemory::resource_ptr<VulkanDescriptorSetLayout>::cast(&mResourceManager, dslh);
@@ -957,7 +965,7 @@ void VulkanDriver::createDescriptorSetR(Handle<HwDescriptorSet> dsh,
void VulkanDriver::mapBufferR(MemoryMappedBufferHandle mmbh,
BufferObjectHandle boh, size_t offset,
size_t size, MapBufferAccessFlags access, utils::CString&& tag) {
size_t size, MapBufferAccessFlags access, utils::ImmutableCString&& tag) {
FVK_SYSTRACE_SCOPE();
auto mmb = resource_ptr<VulkanMemoryMappedBuffer>::make(&mResourceManager, mmbh,
boh, offset, size, access);
@@ -1124,11 +1132,11 @@ void VulkanDriver::destroyDescriptorSet(Handle<HwDescriptorSet> dsh) {
}
}
Handle<HwStream> VulkanDriver::createStreamNative(void* nativeStream, utils::CString tag) {
Handle<HwStream> VulkanDriver::createStreamNative(void* nativeStream, utils::ImmutableCString tag) {
return {};
}
Handle<HwStream> VulkanDriver::createStreamAcquired(utils::CString tag) {
Handle<HwStream> VulkanDriver::createStreamAcquired(utils::ImmutableCString tag) {
return {};
}
@@ -1151,29 +1159,30 @@ void VulkanDriver::destroyFence(Handle<HwFence> fh) {
fence.dec();
}
FenceStatus VulkanDriver::getFenceStatus(Handle<HwFence> fh) {
FenceStatus VulkanDriver::getFenceStatus(Handle<HwFence> const fh) {
return fenceWait(fh, 0);
}
FenceStatus VulkanDriver::fenceWait(FenceHandle const fh, uint64_t const timeout) {
auto fence = resource_ptr<VulkanFence>::cast(&mResourceManager, fh);
auto& cmdfence = fence->fence;
// we have to take into account that the STL's wait_for() actually works with
// time_points relative to steady_clock::now() internally.
using namespace std::chrono;
auto const now = steady_clock::now();
steady_clock::time_point until = steady_clock::time_point::max();
if (now <= steady_clock::time_point::max() - nanoseconds(timeout)) {
until = now + nanoseconds(timeout);
}
std::shared_ptr const cmdfence = fence->wait(until);
if (!cmdfence) {
// If wait is called before a fence actually exists, we return timeout. This matches the
// current behavior in OpenGLDriver, but we should eventually reconsider a different error
// code.
return FenceStatus::TIMEOUT_EXPIRED;
}
// Internally we use the VK_INCOMPLETE status to mean "not yet submitted".
// When this fence gets submitted, its status changes to VK_NOT_READY.
if (cmdfence->getStatus() == VK_SUCCESS) {
return FenceStatus::CONDITION_SATISFIED;
}
// Two other states are possible:
// - VK_INCOMPLETE: the corresponding buffer has not yet been submitted.
// - VK_NOT_READY: the buffer has been submitted but not yet signaled.
// In either case, we return TIMEOUT_EXPIRED to indicate the fence has not been signaled.
return FenceStatus::TIMEOUT_EXPIRED;
// now we are holding a reference to our VulkanCmdFence, so we know it can't
// disappear while we wait
return cmdfence->wait(mPlatform->getDevice(), timeout, until);
}
void VulkanDriver::getPlatformSync(Handle<HwSync> sh, CallbackHandler* handler,
+5 -1
View File
@@ -28,6 +28,7 @@
#include "VulkanQueryManager.h"
#include "VulkanReadPixels.h"
#include "VulkanSamplerCache.h"
#include "VulkanSemaphoreManager.h"
#include "VulkanStagePool.h"
#include "VulkanYcbcrConversionCache.h"
#include "vulkan/VulkanDescriptorSetCache.h"
@@ -43,6 +44,7 @@
#include "DriverBase.h"
#include "private/backend/Driver.h"
#include <utils/FixedCapacityVector.h>
#include <utils/Allocator.h>
#include <utils/compiler.h>
@@ -100,7 +102,8 @@ private:
Dispatcher getDispatcher() const noexcept final;
ShaderModel getShaderModel() const noexcept final;
ShaderLanguage getShaderLanguage() const noexcept final;
utils::FixedCapacityVector<ShaderLanguage> getShaderLanguages(
ShaderLanguage preferredLanguage) const noexcept final;
template<typename T>
friend class ConcreteDispatcher;
@@ -139,6 +142,7 @@ private:
VulkanContext& mContext;
VulkanSemaphoreManager mSemaphoreManager;
VulkanCommands mCommands;
VulkanPipelineLayoutCache mPipelineLayoutCache;
VulkanPipelineCache mPipelineCache;
@@ -40,18 +40,18 @@ namespace filament::backend {
namespace {
inline VulkanBufferUsage getBufferObjectUsage(BufferObjectBinding bindingType) noexcept {
inline VulkanBufferBinding getBufferObjectBinding(BufferObjectBinding bindingType) noexcept {
switch (bindingType) {
case BufferObjectBinding::VERTEX:
return VulkanBufferUsage::VERTEX;
return VulkanBufferBinding::VERTEX;
case BufferObjectBinding::UNIFORM:
return VulkanBufferUsage::UNIFORM;
return VulkanBufferBinding::UNIFORM;
case BufferObjectBinding::SHADER_STORAGE:
return VulkanBufferUsage::SHADER_STORAGE;
return VulkanBufferBinding::SHADER_STORAGE;
// when adding more buffer-types here, make sure to update VulkanBuffer::loadFromCpu()
// if necessary.
}
return VulkanBufferUsage::UNKNOWN;
return VulkanBufferBinding::UNKNOWN;
}
void flipVertically(VkViewport* rect, uint32_t framebufferHeight) {
@@ -614,10 +614,11 @@ void VulkanVertexBuffer::setBuffer(fvkmemory::resource_ptr<VulkanBufferObject> b
VulkanBufferObject::VulkanBufferObject(VulkanContext const& context, VmaAllocator allocator,
VulkanStagePool& stagePool, VulkanBufferCache& bufferCache, uint32_t byteCount,
BufferObjectBinding bindingType)
BufferObjectBinding bindingType, BufferUsage usage)
: HwBufferObject(byteCount),
bindingType(bindingType),
mBuffer(context, allocator, stagePool, bufferCache, getBufferObjectUsage(bindingType), byteCount) {}
mBuffer(context, allocator, stagePool, bufferCache, getBufferObjectBinding(bindingType),
usage, byteCount) {}
VulkanRenderPrimitive::VulkanRenderPrimitive(PrimitiveType pt,
fvkmemory::resource_ptr<VulkanVertexBuffer> vb,
+3 -3
View File
@@ -477,8 +477,8 @@ struct VulkanIndexBuffer : public HwIndexBuffer, fvkmemory::Resource {
uint32_t indexCount)
: HwIndexBuffer(elementSize, indexCount),
indexType(elementSize == 2 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32),
mBuffer(context, allocator, stagePool, bufferCache, VulkanBufferUsage::INDEX,
elementSize * indexCount) {}
mBuffer(context, allocator, stagePool, bufferCache, VulkanBufferBinding::INDEX,
BufferUsage::STATIC, elementSize * indexCount) {}
inline void loadFromCpu(VulkanCommandBuffer& commands, const void* cpuData, uint32_t byteOffset,
uint32_t numBytes) {
@@ -496,7 +496,7 @@ private:
struct VulkanBufferObject : public HwBufferObject, fvkmemory::Resource {
VulkanBufferObject(VulkanContext const& context, VmaAllocator allocator,
VulkanStagePool& stagePool, VulkanBufferCache& bufferCache, uint32_t byteCount,
BufferObjectBinding bindingType);
BufferObjectBinding bindingType, BufferUsage usage);
inline void loadFromCpu(VulkanCommandBuffer& commands, const void* cpuData, uint32_t byteOffset,
uint32_t numBytes) {
+2 -2
View File
@@ -39,7 +39,7 @@ VK_DEFINE_HANDLE(VmaPool)
namespace filament::backend {
enum class VulkanBufferUsage : uint8_t {
enum class VulkanBufferBinding : uint8_t {
UNKNOWN,
VERTEX,
INDEX,
@@ -52,7 +52,7 @@ struct VulkanGpuBuffer {
VmaAllocation vmaAllocation = VK_NULL_HANDLE;
VmaAllocationInfo allocationInfo;
uint32_t numBytes = 0;
VulkanBufferUsage usage = VulkanBufferUsage::UNKNOWN;
VulkanBufferBinding binding = VulkanBufferBinding::UNKNOWN;
};
} // namespace filament::backend
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2017 The Android Open Source Project
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,17 +14,16 @@
* limitations under the License.
*/
#ifndef TNT_SPIRVREMAPWRAPPER_H
#define TNT_SPIRVREMAPWRAPPER_H
#include "vulkan/VulkanSemaphore.h"
#include "vulkan/VulkanSemaphoreManager.h"
#include <cstdint>
#include <vector>
namespace filament::backend {
namespace filamat {
VulkanSemaphore::VulkanSemaphore(VulkanSemaphoreManager* manager, VkSemaphore semaphore)
: mManager(manager), mSemaphore(semaphore) {}
void SpirvRemapWrapperSetUp();
void SpirvRemapWrapperRemap(std::vector<uint32_t>& spirv);
VulkanSemaphore::~VulkanSemaphore() {
mManager->recycle(mSemaphore);
}
} // namespace filamat
#endif //TNT_SPIRVREMAPWRAPPER_H
} // namespace filament::backend
@@ -0,0 +1,42 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TNT_FILAMENT_BACKEND_VULKAN_VULKANSEMAPHORE_H
#define TNT_FILAMENT_BACKEND_VULKAN_VULKANSEMAPHORE_H
#include "memory/Resource.h"
#include <bluevk/BlueVK.h>
namespace filament::backend {
class VulkanSemaphoreManager;
struct VulkanSemaphore : public fvkmemory::Resource {
public:
VulkanSemaphore(VulkanSemaphoreManager* manager, VkSemaphore semaphore);
~VulkanSemaphore();
VkSemaphore getVkSemaphore() const { return mSemaphore; }
private:
VulkanSemaphoreManager* mManager;
VkSemaphore mSemaphore;
};
} // namespace filament::backend
#endif // TNT_FILAMENT_BACKEND_VULKAN_VULKANSEMAPHORE_H
@@ -0,0 +1,70 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "VulkanSemaphoreManager.h"
#include "VulkanConstants.h"
using namespace bluevk;
namespace {
constexpr size_t INITIAL_POOL_SIZE = FVK_MAX_COMMAND_BUFFERS;
VkSemaphore createSemaphore(VkDevice device) {
VkSemaphore semaphore;
VkSemaphoreCreateInfo semaphoreInfo = {
.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
};
vkCreateSemaphore(device, &semaphoreInfo, VKALLOC, &semaphore);
return semaphore;
}
} // namespace
namespace filament::backend {
VulkanSemaphoreManager::VulkanSemaphoreManager(VkDevice device,
fvkmemory::ResourceManager* resourceManager)
: mDevice(device),
mResourceManager(resourceManager) {
for (size_t i= 0; i < INITIAL_POOL_SIZE; ++i) {
mPool.push_back(createSemaphore(mDevice));
}
}
void VulkanSemaphoreManager::terminate() {
for (VkSemaphore semaphore : mPool) {
vkDestroySemaphore(mDevice, semaphore, VKALLOC);
}
mPool.clear();
}
VulkanSemaphoreManager::Semaphore VulkanSemaphoreManager::acquire() {
VkSemaphore semaphore;
if (!mPool.empty()) {
semaphore = mPool.back();
mPool.pop_back();
} else {
semaphore = createSemaphore(mDevice);
}
return Semaphore::construct(mResourceManager, this, semaphore);
}
void VulkanSemaphoreManager::recycle(VkSemaphore semaphore) {
mPool.push_back(semaphore);
}
} // namespace filament::backend
@@ -0,0 +1,51 @@
/*
* Copyright (C) 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TNT_FILAMENT_BACKEND_VULKAN_VULKANSEMAPHOREMANAGER_H
#define TNT_FILAMENT_BACKEND_VULKAN_VULKANSEMAPHOREMANAGER_H
#include "vulkan/VulkanSemaphore.h"
#include "vulkan/memory/ResourceManager.h"
#include "vulkan/memory/ResourcePointer.h"
#include <bluevk/BlueVK.h>
#include <vector>
namespace filament::backend {
class VulkanSemaphoreManager {
public:
using Semaphore = fvkmemory::resource_ptr<VulkanSemaphore>;
VulkanSemaphoreManager(VkDevice device, fvkmemory::ResourceManager* resourceManager);
~VulkanSemaphoreManager() = default;
void terminate();
Semaphore acquire();
private:
friend struct VulkanSemaphore;
void recycle(VkSemaphore semaphore);
VkDevice mDevice;
fvkmemory::ResourceManager* mResourceManager;
std::vector<VkSemaphore> mPool;
};
} // namespace filament::backend
#endif // TNT_FILAMENT_BACKEND_VULKAN_VULKANSEMAPHOREMANAGER_H
@@ -59,7 +59,10 @@ VulkanSwapChain::~VulkanSwapChain() {
mColors = {};
mDepth = {};
for (auto& semaphore : mFinishedDrawing) {
semaphore = {};
}
mFinishedDrawing.clear();
mPlatform->destroy(swapChain);
}
@@ -67,9 +70,17 @@ void VulkanSwapChain::update() {
mColors.clear();
auto const bundle = mPlatform->getSwapChainBundle(swapChain);
size_t const swapChainCount = bundle.colors.size();
mColors.reserve(bundle.colors.size());
VkDevice const device = mPlatform->getDevice();
mFinishedDrawing.clear();
mFinishedDrawing.reserve(swapChainCount);
mFinishedDrawing.resize(swapChainCount);
for (size_t i = 0; i < swapChainCount; ++i) {
mFinishedDrawing[i] = {};
}
TextureUsage depthUsage = TextureUsage::DEPTH_ATTACHMENT;
TextureUsage colorUsage = TextureUsage::COLOR_ATTACHMENT;
if (bundle.isProtected) {
@@ -110,8 +121,10 @@ void VulkanSwapChain::present(DriverBase& driver) {
// We only present if it is not headless. No-op for headless.
if (!mHeadless) {
VkSemaphore const finishedDrawing = mCommands->acquireFinishedSignal();
VkResult const result = mPlatform->present(swapChain, mCurrentSwapIndex, finishedDrawing);
auto finishedDrawing = mCommands->acquireFinishedSignal();
mFinishedDrawing[mCurrentSwapIndex] = finishedDrawing;
VkResult const result =
mPlatform->present(swapChain, mCurrentSwapIndex, finishedDrawing->getVkSemaphore());
FILAMENT_CHECK_POSTCONDITION(result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR ||
result == VK_ERROR_OUT_OF_DATE_KHR)
<< "Cannot present in swapchain. error=" << static_cast<int32_t>(result);
@@ -149,6 +162,7 @@ void VulkanSwapChain::acquire(bool& resized) {
VulkanPlatform::ImageSyncData imageSyncData;
VkResult const result = mPlatform->acquire(swapChain, &imageSyncData);
mCurrentSwapIndex = imageSyncData.imageIndex;
mFinishedDrawing[mCurrentSwapIndex] = {};
FILAMENT_CHECK_POSTCONDITION(result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR)
<< "Cannot acquire in swapchain. error=" << static_cast<int32_t>(result);
if (imageSyncData.imageReadySemaphore != VK_NULL_HANDLE) {

Some files were not shown because too many files have changed in this diff Show More