Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab552d3619 |
@@ -41,8 +41,6 @@ option(FILAMENT_LINUX_IS_MOBILE "Treat Linux as Mobile" OFF)
|
||||
|
||||
option(FILAMENT_ENABLE_ASAN_UBSAN "Enable Address and Undefined Behavior Sanitizers" OFF)
|
||||
|
||||
option(FILAMENT_ENABLE_FEATURE_LEVEL_0 "Enable Feature Level 0" ON)
|
||||
|
||||
set(FILAMENT_NDK_VERSION "" CACHE STRING
|
||||
"Android NDK version or version prefix to be used when building for Android."
|
||||
)
|
||||
@@ -67,9 +65,6 @@ set(FILAMENT_METAL_HANDLE_ARENA_SIZE_IN_MB "8" CACHE STRING
|
||||
"Size of the Metal handle arena, default 8."
|
||||
)
|
||||
|
||||
# Enable exceptions by default in spirv-cross.
|
||||
set(SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS OFF)
|
||||
|
||||
# ==================================================================================================
|
||||
# CMake policies
|
||||
# ==================================================================================================
|
||||
@@ -230,21 +225,6 @@ if (WIN32)
|
||||
# we don't need them on CI.
|
||||
string(REPLACE "/INCREMENTAL" "/INCREMENTAL:NO" ${LinkerFlag} ${${LinkerFlag}})
|
||||
endforeach()
|
||||
|
||||
# We turn off compile-time optimizations for CI, as options that speed up the compile-time
|
||||
# (e.g. /MP) might increase memory usage, leading to instabilities on limited CI machines.
|
||||
option(FILAMENT_SHORTEN_MSVC_COMPILATION "Shorten compile-time in Visual Studio" OFF)
|
||||
else()
|
||||
option(FILAMENT_SHORTEN_MSVC_COMPILATION "Shorten compile-time in Visual Studio" ON)
|
||||
endif()
|
||||
|
||||
if (MSVC)
|
||||
if (FILAMENT_SHORTEN_MSVC_COMPILATION)
|
||||
# enable multi-processor compilation
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP")
|
||||
# disable run-time STL checks to improve tools (e.g. matc) performance
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /D_ITERATOR_DEBUG_LEVEL=0")
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
@@ -357,7 +337,6 @@ endif()
|
||||
|
||||
if (CYGWIN)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-exceptions -fno-rtti")
|
||||
set(SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS ON)
|
||||
endif()
|
||||
|
||||
if (MSVC)
|
||||
@@ -394,7 +373,6 @@ endif()
|
||||
# saved by -fno-exception and 10 KiB saved by -fno-rtti).
|
||||
if (ANDROID OR IOS OR WEBGL)
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fno-exceptions -fno-rtti")
|
||||
set(SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS ON)
|
||||
|
||||
if (ANDROID OR WEBGL)
|
||||
# Omitting unwind info prevents the generation of readable stack traces in crash reports on iOS
|
||||
@@ -406,7 +384,6 @@ endif()
|
||||
# std::visit, which is not supported on iOS 11.0 when exceptions are enabled.
|
||||
if (IOS)
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fno-exceptions")
|
||||
set(SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS ON)
|
||||
endif()
|
||||
|
||||
# With WebGL, we disable RTTI even for debug builds because we pass emscripten::val back and forth
|
||||
@@ -546,11 +523,6 @@ if (FILAMENT_SUPPORTS_METAL)
|
||||
set(MATC_API_FLAGS ${MATC_API_FLAGS} -a metal)
|
||||
endif()
|
||||
|
||||
# Disable ESSL 1.0 code generation.
|
||||
if (NOT FILAMENT_ENABLE_FEATURE_LEVEL_0)
|
||||
set(MATC_API_FLAGS ${MATC_API_FLAGS} -1)
|
||||
endif()
|
||||
|
||||
# Enable debug info (preserves names in SPIR-V)
|
||||
if (FILAMENT_ENABLE_MATDBG)
|
||||
set(MATC_OPT_FLAGS ${MATC_OPT_FLAGS} -d)
|
||||
@@ -758,8 +730,6 @@ endif()
|
||||
if (FILAMENT_SUPPORTS_VULKAN)
|
||||
add_subdirectory(${LIBRARIES}/bluevk)
|
||||
add_subdirectory(${EXTERNAL}/vkmemalloc/tnt)
|
||||
set(SPIRV_HEADERS_SKIP_EXAMPLES ON)
|
||||
add_subdirectory(${EXTERNAL}/spirv-headers)
|
||||
endif()
|
||||
|
||||
set(FILAMENT_SAMPLES_BINARY_DIR ${PROJECT_BINARY_DIR}/samples)
|
||||
|
||||
@@ -7,3 +7,12 @@ for next branch cut* header.
|
||||
appropriate header in [RELEASE_NOTES.md](./RELEASE_NOTES.md).
|
||||
|
||||
## Release notes for next branch cut
|
||||
|
||||
- engine: Allow instantiating Engine at a given feature level via `Engine::Builder::featureLevel`
|
||||
- matc: Enable `GL_OES_standard_derivatives` extension in ESSL 1.0 shaders
|
||||
- matc: Fix code generation of double sided and masked materials in ESSL 1.0 shaders
|
||||
- filagui: Add support for feature level 0
|
||||
- matc: Add support for post-process materials in feature level 0
|
||||
- engine: Add `Material::getFeatureLevel()`
|
||||
- engine: Add missing `Material::getReflectionMode()` method in Java
|
||||
- engine: Support basic usage of post-processing materials on feature level 0
|
||||
|
||||
@@ -31,7 +31,7 @@ repositories {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'com.google.android.filament:filament-android:1.49.1'
|
||||
implementation 'com.google.android.filament:filament-android:1.45.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.49.1'
|
||||
pod 'Filament', '~> 1.45.0'
|
||||
```
|
||||
|
||||
### Snapshots
|
||||
|
||||
@@ -7,37 +7,6 @@ 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.49.1
|
||||
|
||||
|
||||
## v1.49.0
|
||||
|
||||
- matc: Fix ESSL 1.0 codegen when using external samplers [⚠️ **Recompile materials**]
|
||||
|
||||
## v1.48.0
|
||||
|
||||
- matc: New option `-1` to disable generation of ESSL 1.0 code in Feature Level 0 materials
|
||||
- matc: Support optimizations for ESSL 1.0 code [⚠️ **Recompile materials**]
|
||||
|
||||
## v1.47.0
|
||||
|
||||
- engine: Support up to 4 side-by-side stereoscopic eyes, configurable at Engine creation time. See
|
||||
`Engine::Config::stereoscopicEyeCount`. [⚠️ **Recompile Materials**]
|
||||
|
||||
## v1.46.0
|
||||
|
||||
- engine: Allow instantiating Engine at a given feature level via `Engine::Builder::featureLevel`
|
||||
- matc: Enable `GL_OES_standard_derivatives` extension in ESSL 1.0 shaders
|
||||
- matc: Fix code generation of double sided and masked materials in ESSL 1.0 shaders
|
||||
- filagui: Add support for feature level 0
|
||||
- matc: Add support for post-process materials in feature level 0
|
||||
- engine: Add `Material::getFeatureLevel()`
|
||||
- engine: Add missing `Material::getReflectionMode()` method in Java
|
||||
- engine: Support basic usage of post-processing materials on feature level 0
|
||||
- engine: Fix critical GLES 2.0 bugs
|
||||
- engine: Add `FILAMENT_ENABLE_FEATURE_LEVEL_0` build-time option optionally allow building Filament
|
||||
without FL0 support.
|
||||
|
||||
## v1.45.1
|
||||
|
||||
- engine: Added parameter for configuring JobSystem thread count
|
||||
|
||||
@@ -384,13 +384,6 @@ Java_com_google_android_filament_Engine_nFlushAndWait(JNIEnv*, jclass,
|
||||
engine->flushAndWait();
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT void JNICALL
|
||||
Java_com_google_android_filament_Engine_nFlush(JNIEnv*, jclass,
|
||||
jlong nativeEngine) {
|
||||
Engine* engine = (Engine*) nativeEngine;
|
||||
engine->flush();
|
||||
}
|
||||
|
||||
// Managers...
|
||||
|
||||
extern "C" JNIEXPORT jlong JNICALL
|
||||
@@ -435,13 +428,6 @@ Java_com_google_android_filament_Engine_nIsAutomaticInstancingEnabled(JNIEnv*, j
|
||||
return (jboolean)engine->isAutomaticInstancingEnabled();
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jlong JNICALL
|
||||
Java_com_google_android_filament_Engine_nGetMaxStereoscopicEyes(JNIEnv*, jclass, jlong nativeEngine) {
|
||||
Engine* engine = (Engine*) nativeEngine;
|
||||
return (jlong) engine->getMaxStereoscopicEyes();
|
||||
}
|
||||
|
||||
|
||||
extern "C" JNIEXPORT jint JNICALL
|
||||
Java_com_google_android_filament_Engine_nGetSupportedFeatureLevel(JNIEnv *, jclass,
|
||||
jlong nativeEngine) {
|
||||
@@ -484,7 +470,7 @@ extern "C" JNIEXPORT void JNICALL Java_com_google_android_filament_Engine_nSetBu
|
||||
extern "C" JNIEXPORT void JNICALL Java_com_google_android_filament_Engine_nSetBuilderConfig(JNIEnv*,
|
||||
jclass, jlong nativeBuilder, jlong commandBufferSizeMB, jlong perRenderPassArenaSizeMB,
|
||||
jlong driverHandleArenaSizeMB, jlong minCommandBufferSizeMB, jlong perFrameCommandsSizeMB,
|
||||
jlong jobSystemThreadCount, jlong stereoscopicEyeCount) {
|
||||
jlong jobSystemThreadCount) {
|
||||
Engine::Builder* builder = (Engine::Builder*) nativeBuilder;
|
||||
Engine::Config config = {
|
||||
.commandBufferSizeMB = (uint32_t) commandBufferSizeMB,
|
||||
@@ -493,7 +479,6 @@ extern "C" JNIEXPORT void JNICALL Java_com_google_android_filament_Engine_nSetBu
|
||||
.minCommandBufferSizeMB = (uint32_t) minCommandBufferSizeMB,
|
||||
.perFrameCommandsSizeMB = (uint32_t) perFrameCommandsSizeMB,
|
||||
.jobSystemThreadCount = (uint32_t) jobSystemThreadCount,
|
||||
.stereoscopicEyeCount = (uint8_t) stereoscopicEyeCount,
|
||||
};
|
||||
builder->config(&config);
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ Java_com_google_android_filament_EntityManager_nCreateArray(JNIEnv* env, jclass,
|
||||
// (which it is), but still.
|
||||
em->create((size_t) n, reinterpret_cast<Entity *>(entities));
|
||||
|
||||
env->ReleaseIntArrayElements(entities_, entities, JNI_ABORT);
|
||||
env->ReleaseIntArrayElements(entities_, entities, 0);
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jint JNICALL
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
#include <filament/Material.h>
|
||||
|
||||
#include "common/NioUtils.h"
|
||||
#include "common/CallbackUtils.h"
|
||||
|
||||
using namespace filament;
|
||||
|
||||
@@ -272,17 +271,3 @@ Java_com_google_android_filament_Material_nHasParameter(JNIEnv* env, jclass,
|
||||
env->ReleaseStringUTFChars(name_, name);
|
||||
return (jboolean) hasParameter;
|
||||
}
|
||||
|
||||
extern "C"
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_google_android_filament_Material_nCompile(JNIEnv *env, jclass clazz,
|
||||
jlong nativeMaterial, jint priority, jint variants, jobject handler, jobject runnable) {
|
||||
Material* material = (Material*) nativeMaterial;
|
||||
JniCallback* jniCallback = JniCallback::make(env, handler, runnable);
|
||||
material->compile(
|
||||
(Material::CompilerPriorityQueue) priority,
|
||||
(UserVariantFilterBit) variants,
|
||||
jniCallback->getHandler(), [jniCallback](Material*){
|
||||
JniCallback::postToJavaAndDestroy(jniCallback);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -205,7 +205,7 @@ Java_com_google_android_filament_MaterialInstance_nSetIntParameterArray(JNIEnv *
|
||||
break;
|
||||
}
|
||||
|
||||
env->ReleaseIntArrayElements(v_, v, JNI_ABORT);
|
||||
env->ReleaseIntArrayElements(v_, v, 0);
|
||||
|
||||
env->ReleaseStringUTFChars(name_, name);
|
||||
}
|
||||
|
||||
@@ -98,22 +98,3 @@ Java_com_google_android_filament_Scene_nHasEntity(JNIEnv *env, jclass type, jlon
|
||||
Entity entity = Entity::import(entityId);
|
||||
return (jboolean) scene->hasEntity(entity);
|
||||
}
|
||||
|
||||
extern "C"
|
||||
JNIEXPORT jboolean JNICALL
|
||||
Java_com_google_android_filament_Scene_nGetEntities(JNIEnv *env, jclass ,
|
||||
jlong nativeScene, jintArray outArray, jint length) {
|
||||
Scene const* const scene = (Scene*) nativeScene;
|
||||
if (length < scene->getEntityCount()) {
|
||||
// should not happen because we already checked on the java side
|
||||
return JNI_FALSE;
|
||||
}
|
||||
jint *out = (jint *) env->GetIntArrayElements(outArray, nullptr);
|
||||
scene->forEach([out, length, i = 0](Entity entity)mutable {
|
||||
if (i < length) { // this is just paranoia here
|
||||
out[i++] = (jint) entity.getId();
|
||||
}
|
||||
});
|
||||
env->ReleaseIntArrayElements(outArray, (jint*) out, 0);
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
@@ -480,17 +480,6 @@ Java_com_google_android_filament_View_nIsStencilBufferEnabled(JNIEnv *, jclass,
|
||||
return view->isStencilBufferEnabled();
|
||||
}
|
||||
|
||||
extern "C"
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_google_android_filament_View_nSetStereoscopicOptions(JNIEnv *, jclass, jlong nativeView,
|
||||
jboolean enabled) {
|
||||
View* view = (View*) nativeView;
|
||||
View::StereoscopicOptions options {
|
||||
.enabled = (bool) enabled
|
||||
};
|
||||
view->setStereoscopicOptions(options);
|
||||
}
|
||||
|
||||
extern "C"
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_google_android_filament_View_nSetGuardBandOptions(JNIEnv *, jclass,
|
||||
|
||||
@@ -111,8 +111,6 @@ public class Engine {
|
||||
|
||||
private long mNativeObject;
|
||||
|
||||
private Config mConfig;
|
||||
|
||||
@NonNull private final TransformManager mTransformManager;
|
||||
@NonNull private final LightManager mLightManager;
|
||||
@NonNull private final RenderableManager mRenderableManager;
|
||||
@@ -152,10 +150,8 @@ public class Engine {
|
||||
FEATURE_LEVEL_0,
|
||||
/** OpenGL ES 3.0 features (default) */
|
||||
FEATURE_LEVEL_1,
|
||||
/** OpenGL ES 3.1 features + 16 textures units + cubemap arrays */
|
||||
FEATURE_LEVEL_2,
|
||||
/** OpenGL ES 3.1 features + 31 textures units + cubemap arrays */
|
||||
FEATURE_LEVEL_3,
|
||||
FEATURE_LEVEL_2
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -165,7 +161,6 @@ public class Engine {
|
||||
@SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
|
||||
private final BuilderFinalizer mFinalizer;
|
||||
private final long mNativeBuilder;
|
||||
private Config mConfig;
|
||||
|
||||
public Builder() {
|
||||
mNativeBuilder = nCreateBuilder();
|
||||
@@ -207,11 +202,10 @@ public class Engine {
|
||||
* @return A reference to this Builder for chaining calls.
|
||||
*/
|
||||
public Builder config(Config config) {
|
||||
mConfig = config;
|
||||
nSetBuilderConfig(mNativeBuilder, config.commandBufferSizeMB,
|
||||
config.perRenderPassArenaSizeMB, config.driverHandleArenaSizeMB,
|
||||
config.minCommandBufferSizeMB, config.perFrameCommandsSizeMB,
|
||||
config.jobSystemThreadCount, config.stereoscopicEyeCount);
|
||||
config.jobSystemThreadCount);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -239,7 +233,7 @@ public class Engine {
|
||||
public Engine build() {
|
||||
long nativeEngine = nBuilderBuild(mNativeBuilder);
|
||||
if (nativeEngine == 0) throw new IllegalStateException("Couldn't create Engine");
|
||||
return new Engine(nativeEngine, mConfig);
|
||||
return new Engine(nativeEngine);
|
||||
}
|
||||
|
||||
private static class BuilderFinalizer {
|
||||
@@ -347,24 +341,14 @@ public class Engine {
|
||||
* the number of threads to use.
|
||||
*/
|
||||
public long jobSystemThreadCount = 0;
|
||||
|
||||
/**
|
||||
* The number of eyes to render when stereoscopic rendering is enabled. Supported values are
|
||||
* between 1 and Engine#getMaxStereoscopicEyes() (inclusive).
|
||||
*
|
||||
* @see View#setStereoscopicOptions
|
||||
* @see Engine#getMaxStereoscopicEyes
|
||||
*/
|
||||
public long stereoscopicEyeCount = 2;
|
||||
}
|
||||
|
||||
private Engine(long nativeEngine, Config config) {
|
||||
private Engine(long nativeEngine) {
|
||||
mNativeObject = nativeEngine;
|
||||
mTransformManager = new TransformManager(nGetTransformManager(nativeEngine));
|
||||
mLightManager = new LightManager(nGetLightManager(nativeEngine));
|
||||
mRenderableManager = new RenderableManager(nGetRenderableManager(nativeEngine));
|
||||
mEntityManager = new EntityManager(nGetEntityManager(nativeEngine));
|
||||
mConfig = config;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -557,37 +541,6 @@ public class Engine {
|
||||
return nIsAutomaticInstancingEnabled(getNativeObject());
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the configuration settings of this {@link Engine}.
|
||||
*
|
||||
* This method returns the configuration object that was supplied to the Engine's {@link
|
||||
* Builder#config} method during the creation of this Engine. If the {@link Builder::config}
|
||||
* method was not explicitly called (or called with null), this method returns the default
|
||||
* configuration settings.
|
||||
*
|
||||
* @return a {@link Config} object with this Engine's configuration
|
||||
* @see Builder#config
|
||||
*/
|
||||
@NonNull
|
||||
public Config getConfig() {
|
||||
if (mConfig == null) {
|
||||
mConfig = new Config();
|
||||
}
|
||||
return mConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the maximum number of stereoscopic eyes supported by Filament. The actual number of
|
||||
* eyes rendered is set at Engine creation time with the {@link
|
||||
* Engine#Config#stereoscopicEyeCount} setting.
|
||||
*
|
||||
* @return the max number of stereoscopic eyes supported
|
||||
* @see Engine#Config#stereoscopicEyeCount
|
||||
*/
|
||||
public long getMaxStereoscopicEyes() {
|
||||
return nGetMaxStereoscopicEyes(getNativeObject());
|
||||
}
|
||||
|
||||
|
||||
// SwapChain
|
||||
|
||||
@@ -1124,18 +1077,6 @@ public class Engine {
|
||||
nFlushAndWait(getNativeObject());
|
||||
}
|
||||
|
||||
/**
|
||||
* Kicks the hardware thread (e.g. the OpenGL, Vulkan or Metal thread) but does not wait
|
||||
* for commands to be either executed or the hardware finished.
|
||||
*
|
||||
* <p>This is typically used after creating a lot of objects to start draining the command
|
||||
* queue which has a limited size.</p>
|
||||
*/
|
||||
public void flush() {
|
||||
nFlush(getNativeObject());
|
||||
}
|
||||
|
||||
|
||||
@UsedByReflection("TextureHelper.java")
|
||||
public long getNativeObject() {
|
||||
if (mNativeObject == 0) {
|
||||
@@ -1208,7 +1149,6 @@ public class Engine {
|
||||
private static native boolean nIsValidSwapChain(long nativeEngine, long nativeSwapChain);
|
||||
private static native void nDestroyEntity(long nativeEngine, int entity);
|
||||
private static native void nFlushAndWait(long nativeEngine);
|
||||
private static native void nFlush(long nativeEngine);
|
||||
private static native long nGetTransformManager(long nativeEngine);
|
||||
private static native long nGetLightManager(long nativeEngine);
|
||||
private static native long nGetRenderableManager(long nativeEngine);
|
||||
@@ -1216,7 +1156,6 @@ public class Engine {
|
||||
private static native long nGetEntityManager(long nativeEngine);
|
||||
private static native void nSetAutomaticInstancingEnabled(long nativeEngine, boolean enable);
|
||||
private static native boolean nIsAutomaticInstancingEnabled(long nativeEngine);
|
||||
private static native long nGetMaxStereoscopicEyes(long nativeEngine);
|
||||
private static native int nGetSupportedFeatureLevel(long nativeEngine);
|
||||
private static native int nSetActiveFeatureLevel(long nativeEngine, int ordinal);
|
||||
private static native int nGetActiveFeatureLevel(long nativeEngine);
|
||||
@@ -1226,8 +1165,7 @@ public class Engine {
|
||||
private static native void nSetBuilderBackend(long nativeBuilder, long backend);
|
||||
private static native void nSetBuilderConfig(long nativeBuilder, long commandBufferSizeMB,
|
||||
long perRenderPassArenaSizeMB, long driverHandleArenaSizeMB,
|
||||
long minCommandBufferSizeMB, long perFrameCommandsSizeMB, long jobSystemThreadCount,
|
||||
long stereoscopicEyeCount);
|
||||
long minCommandBufferSizeMB, long perFrameCommandsSizeMB, long jobSystemThreadCount);
|
||||
private static native void nSetBuilderFeatureLevel(long nativeBuilder, int ordinal);
|
||||
private static native void nSetBuilderSharedContext(long nativeBuilder, long sharedContext);
|
||||
private static native long nBuilderBuild(long nativeBuilder);
|
||||
|
||||
@@ -18,7 +18,6 @@ package com.google.android.filament;
|
||||
|
||||
import androidx.annotation.IntRange;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.Size;
|
||||
|
||||
import com.google.android.filament.proguard.UsedByNative;
|
||||
@@ -239,31 +238,6 @@ public class Material {
|
||||
FRONT_AND_BACK
|
||||
}
|
||||
|
||||
public enum CompilerPriorityQueue {
|
||||
HIGH,
|
||||
LOW
|
||||
}
|
||||
|
||||
public static class UserVariantFilterBit {
|
||||
/** Directional lighting */
|
||||
public static int DIRECTIONAL_LIGHTING = 0x01;
|
||||
/** Dynamic lighting */
|
||||
public static int DYNAMIC_LIGHTING = 0x02;
|
||||
/** Shadow receiver */
|
||||
public static int SHADOW_RECEIVER = 0x04;
|
||||
/** Skinning */
|
||||
public static int SKINNING = 0x08;
|
||||
/** Fog */
|
||||
public static int FOG = 0x10;
|
||||
/** Variance shadow maps */
|
||||
public static int VSM = 0x20;
|
||||
/** Screen-space reflections */
|
||||
public static int SSR = 0x40;
|
||||
/** Instanced stereo rendering */
|
||||
public static int STE = 0x80;
|
||||
public static int ALL = 0xFF;
|
||||
}
|
||||
|
||||
@UsedByNative("Material.cpp")
|
||||
public static class Parameter {
|
||||
private static final Type[] sTypeValues = Type.values();
|
||||
@@ -378,55 +352,6 @@ public class Material {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Asynchronously ensures that a subset of this Material's variants are compiled. After issuing
|
||||
* several compile() calls in a row, it is recommended to call {@link Engine#flush}
|
||||
* such that the backend can start the compilation work as soon as possible.
|
||||
* The provided callback is guaranteed to be called on the main thread after all specified
|
||||
* variants of the material are compiled. This can take hundreds of milliseconds.
|
||||
*<p>
|
||||
* If all the material's variants are already compiled, the callback will be scheduled as
|
||||
* soon as possible, but this might take a few dozen millisecond, corresponding to how
|
||||
* many previous frames are enqueued in the backend. This also varies by backend. Therefore,
|
||||
* it is recommended to only call this method once per material shortly after creation.
|
||||
*</p>
|
||||
*<p>
|
||||
* If the same variant is scheduled for compilation multiple times, the first scheduling
|
||||
* takes precedence; later scheduling are ignored.
|
||||
*</p>
|
||||
*<p>
|
||||
* caveat: A consequence is that if a variant is scheduled on the low priority queue and later
|
||||
* scheduled again on the high priority queue, the later scheduling is ignored.
|
||||
* Therefore, the second callback could be called before the variant is compiled.
|
||||
* However, the first callback, if specified, will trigger as expected.
|
||||
*</p>
|
||||
*<p>
|
||||
* The callback is guaranteed to be called. If the engine is destroyed while some material
|
||||
* variants are still compiling or in the queue, these will be discarded and the corresponding
|
||||
* callback will be called. In that case however the Material pointer passed to the callback
|
||||
* is guaranteed to be invalid (either because it's been destroyed by the user already, or,
|
||||
* because it's been cleaned-up by the Engine).
|
||||
*</p>
|
||||
*<p>
|
||||
* {@link UserVariantFilterBit#ALL} should be used with caution. Only variants that an application
|
||||
* needs should be included in the variants argument. For example, the STE variant is only used
|
||||
* for stereoscopic rendering. If an application is not planning to render in stereo, this bit
|
||||
* should be turned off to avoid unnecessary material compilations.
|
||||
*</p>
|
||||
* @param priority Which priority queue to use, LOW or HIGH.
|
||||
* @param variants Variants to include to the compile command.
|
||||
* @param handler An {@link java.util.concurrent.Executor Executor}. On Android this can also be a {@link android.os.Handler Handler}.
|
||||
* @param callback callback called on the main thread when the compilation is done on
|
||||
* by backend.
|
||||
*/
|
||||
public void compile(@NonNull CompilerPriorityQueue priority,
|
||||
int variants,
|
||||
@Nullable Object handler,
|
||||
@Nullable Runnable callback) {
|
||||
nCompile(getNativeObject(), priority.ordinal(), variants, handler, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new instance of this material. Material instances should be freed using
|
||||
* {@link Engine#destroyMaterialInstance(MaterialInstance)}.
|
||||
@@ -1028,7 +953,6 @@ public class Material {
|
||||
private static native long nCreateInstanceWithName(long nativeMaterial, @NonNull String name);
|
||||
private static native long nGetDefaultInstance(long nativeMaterial);
|
||||
|
||||
private static native void nCompile(long nativeMaterial, int priority, int variants, Object handler, Runnable runnable);
|
||||
private static native String nGetName(long nativeMaterial);
|
||||
private static native int nGetShading(long nativeMaterial);
|
||||
private static native int nGetInterpolation(long nativeMaterial);
|
||||
|
||||
@@ -16,7 +16,6 @@
|
||||
|
||||
package com.google.android.filament;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
/**
|
||||
@@ -191,52 +190,6 @@ public class Scene {
|
||||
return mNativeObject;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of all entities in the Scene. If outArray is provided and large enough,
|
||||
* it is used to store the list and returned, otherwise a new array is allocated and returned.
|
||||
* @param outArray an array to store the list of entities in the scene.
|
||||
* @return outArray if it was used or a newly allocated array.
|
||||
* @see #getEntityCount
|
||||
*/
|
||||
public int[] getEntities(@Nullable int[] outArray) {
|
||||
int c = getEntityCount();
|
||||
if (outArray == null || outArray.length < c) {
|
||||
outArray = new int[c];
|
||||
}
|
||||
boolean success = nGetEntities(getNativeObject(), outArray, outArray.length);
|
||||
if (!success) {
|
||||
throw new IllegalStateException("Error retriving Scene's entities");
|
||||
}
|
||||
return outArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of all entities in the Scene in a newly allocated array.
|
||||
* @return an array containing the list of all entities in the scene.
|
||||
* @see #getEntityCount
|
||||
*/
|
||||
public int[] getEntities() {
|
||||
return getEntities(null);
|
||||
}
|
||||
|
||||
public interface EntityProcessor {
|
||||
void process(@Entity int entity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes user functor on each entity in the scene.
|
||||
*
|
||||
* It is not allowed to add or remove an entity from the scene within the functor.
|
||||
*
|
||||
* @param entityProcessor User provided functor called for each entity in the scene
|
||||
*/
|
||||
public void forEach(@NonNull EntityProcessor entityProcessor) {
|
||||
int[] entities = getEntities(null);
|
||||
for (int entity : entities) {
|
||||
entityProcessor.process(entity);
|
||||
}
|
||||
}
|
||||
|
||||
void clearNativeObject() {
|
||||
mNativeObject = 0;
|
||||
}
|
||||
@@ -251,5 +204,4 @@ public class Scene {
|
||||
private static native int nGetRenderableCount(long nativeScene);
|
||||
private static native int nGetLightCount(long nativeScene);
|
||||
private static native boolean nHasEntity(long nativeScene, int entity);
|
||||
private static native boolean nGetEntities(long nativeScene, int[] outArray, int length);
|
||||
}
|
||||
|
||||
@@ -849,10 +849,6 @@ public class Texture {
|
||||
public static final int SAMPLEABLE = 0x10;
|
||||
/** Texture can be used as a subpass input */
|
||||
public static final int SUBPASS_INPUT = 0x20;
|
||||
/** Texture can be used the source of a blit() */
|
||||
public static final int BLIT_SRC = 0x40;
|
||||
/** Texture can be used the destination of a blit() */
|
||||
public static final int BLIT_DST = 0x80;
|
||||
/** by default textures are <code>UPLOADABLE</code> and <code>SAMPLEABLE</code>*/
|
||||
public static final int DEFAULT = UPLOADABLE | SAMPLEABLE;
|
||||
}
|
||||
|
||||
@@ -75,7 +75,6 @@ public class View {
|
||||
private AmbientOcclusionOptions mAmbientOcclusionOptions;
|
||||
private BloomOptions mBloomOptions;
|
||||
private FogOptions mFogOptions;
|
||||
private StereoscopicOptions mStereoscopicOptions;
|
||||
private RenderTarget mRenderTarget;
|
||||
private BlendMode mBlendMode;
|
||||
private DepthOfFieldOptions mDepthOfFieldOptions;
|
||||
@@ -1056,51 +1055,6 @@ public class View {
|
||||
return nIsStencilBufferEnabled(getNativeObject());
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the stereoscopic rendering options for this view.
|
||||
*
|
||||
* <p>
|
||||
* Currently, only one type of stereoscopic rendering is supported: side-by-side.
|
||||
* Side-by-side stereo rendering splits the viewport into two halves: a left and right half.
|
||||
* Eye 0 will render to the left half, while Eye 1 will render into the right half.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Currently, the following features are not supported with stereoscopic rendering:
|
||||
* - post-processing
|
||||
* - shadowing
|
||||
* - punctual lights
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Stereo rendering depends on device and platform support. To check if stereo rendering is
|
||||
* supported, use {@link Engine#isStereoSupported()}. If stereo rendering is not supported, then
|
||||
* the stereoscopic options have no effect.
|
||||
* </p>
|
||||
*
|
||||
* @param options The stereoscopic options to use on this view
|
||||
* @see #getStereoscopicOptions
|
||||
*/
|
||||
public void setStereoscopicOptions(@NonNull StereoscopicOptions options) {
|
||||
mStereoscopicOptions = options;
|
||||
nSetStereoscopicOptions(getNativeObject(), options.enabled);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the stereoscopic options.
|
||||
*
|
||||
* @return options Stereoscopic options currently set.
|
||||
* @see #setStereoscopicOptions
|
||||
*/
|
||||
@NonNull
|
||||
public StereoscopicOptions getStereoscopicOptions() {
|
||||
if (mStereoscopicOptions == null) {
|
||||
mStereoscopicOptions = new StereoscopicOptions();
|
||||
}
|
||||
return mStereoscopicOptions;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* A class containing the result of a picking query
|
||||
*/
|
||||
@@ -1266,7 +1220,6 @@ public class View {
|
||||
private static native void nSetBloomOptions(long nativeView, long dirtNativeObject, float dirtStrength, float strength, int resolution, int levels, int blendMode, boolean threshold, boolean enabled, float highlight,
|
||||
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 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);
|
||||
|
||||
+162
-167
@@ -182,85 +182,28 @@ public class UiHelper {
|
||||
void detach();
|
||||
}
|
||||
|
||||
private class SurfaceViewHandler implements RenderSurface, SurfaceHolder.Callback {
|
||||
@NonNull private final SurfaceView mSurfaceView;
|
||||
private static class SurfaceViewHandler implements RenderSurface {
|
||||
private final SurfaceView mSurfaceView;
|
||||
|
||||
SurfaceViewHandler(@NonNull SurfaceView surfaceView) {
|
||||
mSurfaceView = surfaceView;
|
||||
|
||||
@NonNull SurfaceHolder holder = surfaceView.getHolder();
|
||||
holder.addCallback(this);
|
||||
|
||||
if (mDesiredWidth > 0 && mDesiredHeight > 0) {
|
||||
holder.setFixedSize(mDesiredWidth, mDesiredHeight);
|
||||
}
|
||||
|
||||
// in case the SurfaceView's surface already existed
|
||||
final Surface surface = holder.getSurface();
|
||||
if (surface != null && surface.isValid()) {
|
||||
surfaceCreated(holder);
|
||||
// there is no way to retrieve the actual PixelFormat, since it is not used
|
||||
// in the callback, we can use whatever we want.
|
||||
surfaceChanged(holder, PixelFormat.RGBA_8888,
|
||||
holder.getSurfaceFrame().width(), holder.getSurfaceFrame().height());
|
||||
}
|
||||
SurfaceViewHandler(SurfaceView surface) {
|
||||
mSurfaceView = surface;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resize(int width, int height) {
|
||||
@NonNull SurfaceHolder holder = mSurfaceView.getHolder();
|
||||
holder.setFixedSize(width, height);
|
||||
mSurfaceView.getHolder().setFixedSize(width, height);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void detach() {
|
||||
@NonNull SurfaceHolder holder = mSurfaceView.getHolder();
|
||||
holder.removeCallback(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void surfaceCreated(@NonNull SurfaceHolder holder) {
|
||||
if (LOGGING) Log.d(LOG_TAG, "surfaceCreated()");
|
||||
createSwapChain(holder.getSurface());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void surfaceChanged(
|
||||
@NonNull SurfaceHolder holder, int format, int width, int height) {
|
||||
// Note: this is always called at least once after surfaceCreated()
|
||||
if (LOGGING) Log.d(LOG_TAG, "surfaceChanged(" + width + ", " + height + ")");
|
||||
if (mRenderCallback != null) {
|
||||
mRenderCallback.onResized(width, height);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
|
||||
if (LOGGING) Log.d(LOG_TAG, "surfaceDestroyed()");
|
||||
destroySwapChain();
|
||||
}
|
||||
}
|
||||
|
||||
private class SurfaceHolderHandler implements RenderSurface, SurfaceHolder.Callback {
|
||||
private static class SurfaceHolderHandler implements RenderSurface {
|
||||
private final SurfaceHolder mSurfaceHolder;
|
||||
|
||||
SurfaceHolderHandler(@NonNull SurfaceHolder holder) {
|
||||
mSurfaceHolder = holder;
|
||||
holder.addCallback(this);
|
||||
|
||||
if (mDesiredWidth > 0 && mDesiredHeight > 0) {
|
||||
holder.setFixedSize(mDesiredWidth, mDesiredHeight);
|
||||
}
|
||||
|
||||
// in case the SurfaceHolder's surface already existed
|
||||
final Surface surface = holder.getSurface();
|
||||
if (surface != null && surface.isValid()) {
|
||||
surfaceCreated(holder);
|
||||
// there is no way to retrieve the actual PixelFormat, since it is not used
|
||||
// in the callback, we can use whatever we want.
|
||||
surfaceChanged(holder, PixelFormat.RGBA_8888,
|
||||
holder.getSurfaceFrame().width(), holder.getSurfaceFrame().height());
|
||||
}
|
||||
SurfaceHolderHandler(SurfaceHolder surface) {
|
||||
mSurfaceHolder = surface;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -270,55 +213,19 @@ public class UiHelper {
|
||||
|
||||
@Override
|
||||
public void detach() {
|
||||
mSurfaceHolder.removeCallback(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void surfaceCreated(@NonNull SurfaceHolder holder) {
|
||||
if (LOGGING) Log.d(LOG_TAG, "surfaceCreated()");
|
||||
createSwapChain(holder.getSurface());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
|
||||
// Note: this is always called at least once after surfaceCreated()
|
||||
if (LOGGING) Log.d(LOG_TAG, "surfaceChanged(" + width + ", " + height + ")");
|
||||
if (mRenderCallback != null) {
|
||||
mRenderCallback.onResized(width, height);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
|
||||
if (LOGGING) Log.d(LOG_TAG, "surfaceDestroyed()");
|
||||
destroySwapChain();
|
||||
}
|
||||
}
|
||||
|
||||
private class TextureViewHandler implements RenderSurface, TextureView.SurfaceTextureListener {
|
||||
private class TextureViewHandler implements RenderSurface {
|
||||
private final TextureView mTextureView;
|
||||
private Surface mSurface;
|
||||
|
||||
TextureViewHandler(@NonNull TextureView view) {
|
||||
mTextureView = view;
|
||||
mTextureView.setSurfaceTextureListener(this);
|
||||
// in case the View's SurfaceTexture already existed
|
||||
if (view.isAvailable()) {
|
||||
SurfaceTexture surfaceTexture = view.getSurfaceTexture();
|
||||
if (surfaceTexture != null) {
|
||||
this.onSurfaceTextureAvailable(surfaceTexture,
|
||||
mDesiredWidth, mDesiredHeight);
|
||||
}
|
||||
}
|
||||
}
|
||||
TextureViewHandler(TextureView surface) { mTextureView = surface; }
|
||||
|
||||
@Override
|
||||
public void resize(int width, int height) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
|
||||
final SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture();
|
||||
if (surfaceTexture != null) {
|
||||
surfaceTexture.setDefaultBufferSize(width, height);
|
||||
}
|
||||
mTextureView.getSurfaceTexture().setDefaultBufferSize(width, height);
|
||||
}
|
||||
if (mRenderCallback != null) {
|
||||
// the call above won't cause TextureView.onSurfaceTextureSizeChanged()
|
||||
@@ -328,69 +235,10 @@ public class UiHelper {
|
||||
|
||||
@Override
|
||||
public void detach() {
|
||||
mTextureView.setSurfaceTextureListener(null);
|
||||
setSurface(null);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void onSurfaceTextureAvailable(
|
||||
@NonNull SurfaceTexture surfaceTexture, int width, int height) {
|
||||
if (LOGGING) Log.d(LOG_TAG, "onSurfaceTextureAvailable()");
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
|
||||
if (mDesiredWidth > 0 && mDesiredHeight > 0) {
|
||||
surfaceTexture.setDefaultBufferSize(mDesiredWidth, mDesiredHeight);
|
||||
}
|
||||
}
|
||||
|
||||
final Surface surface = new Surface(surfaceTexture);
|
||||
setSurface(surface);
|
||||
createSwapChain(surface);
|
||||
|
||||
if (mRenderCallback != null) {
|
||||
// Call this the first time because onSurfaceTextureSizeChanged()
|
||||
// isn't called at initialization time
|
||||
mRenderCallback.onResized(width, height);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSurfaceTextureSizeChanged(
|
||||
@NonNull SurfaceTexture surfaceTexture, int width, int height) {
|
||||
if (LOGGING) Log.d(LOG_TAG, "onSurfaceTextureSizeChanged()");
|
||||
if (mRenderCallback != null) {
|
||||
if (mDesiredWidth > 0 && mDesiredHeight > 0) {
|
||||
surfaceTexture.setDefaultBufferSize(mDesiredWidth, mDesiredHeight);
|
||||
mRenderCallback.onResized(mDesiredWidth, mDesiredHeight);
|
||||
} else {
|
||||
mRenderCallback.onResized(width, height);
|
||||
}
|
||||
// We must recreate the SwapChain to guarantee that it sees the new size.
|
||||
// More precisely, for an EGL client, the EGLSurface must be recreated. For
|
||||
// a Vulkan client, the SwapChain must be recreated. Calling
|
||||
// onNativeWindowChanged() will accomplish that.
|
||||
// This requirement comes from SurfaceTexture.setDefaultBufferSize()
|
||||
// documentation.
|
||||
final Surface surface = getSurface();
|
||||
if (surface != null) {
|
||||
mRenderCallback.onNativeWindowChanged(surface);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surfaceTexture) {
|
||||
if (LOGGING) Log.d(LOG_TAG, "onSurfaceTextureDestroyed()");
|
||||
destroySwapChain();
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) { }
|
||||
|
||||
|
||||
private void setSurface(@Nullable Surface surface) {
|
||||
void setSurface(Surface surface) {
|
||||
if (surface == null) {
|
||||
if (mSurface != null) {
|
||||
mSurface.release();
|
||||
@@ -399,7 +247,7 @@ public class UiHelper {
|
||||
mSurface = surface;
|
||||
}
|
||||
|
||||
private Surface getSurface() {
|
||||
public Surface getSurface() {
|
||||
return mSurface;
|
||||
}
|
||||
}
|
||||
@@ -554,8 +402,48 @@ public class UiHelper {
|
||||
view.setZOrderOnTop(translucent);
|
||||
}
|
||||
|
||||
view.getHolder().setFormat(isOpaque() ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT);
|
||||
int format = isOpaque() ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT;
|
||||
view.getHolder().setFormat(format);
|
||||
|
||||
mRenderSurface = new SurfaceViewHandler(view);
|
||||
|
||||
final SurfaceHolder.Callback callback = new SurfaceHolder.Callback() {
|
||||
@Override
|
||||
public void surfaceCreated(@NonNull SurfaceHolder holder) {
|
||||
if (LOGGING) Log.d(LOG_TAG, "surfaceCreated()");
|
||||
createSwapChain(holder.getSurface());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void surfaceChanged(
|
||||
@NonNull SurfaceHolder holder, int format, int width, int height) {
|
||||
// Note: this is always called at least once after surfaceCreated()
|
||||
if (LOGGING) Log.d(LOG_TAG, "surfaceChanged(" + width + ", " + height + ")");
|
||||
if (mRenderCallback != null) {
|
||||
mRenderCallback.onResized(width, height);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
|
||||
if (LOGGING) Log.d(LOG_TAG, "surfaceDestroyed()");
|
||||
destroySwapChain();
|
||||
}
|
||||
};
|
||||
|
||||
SurfaceHolder holder = view.getHolder();
|
||||
holder.addCallback(callback);
|
||||
if (mDesiredWidth > 0 && mDesiredHeight > 0) {
|
||||
holder.setFixedSize(mDesiredWidth, mDesiredHeight);
|
||||
}
|
||||
|
||||
// in case the SurfaceView's surface already existed
|
||||
final Surface surface = holder.getSurface();
|
||||
if (surface != null && surface.isValid()) {
|
||||
callback.surfaceCreated(holder);
|
||||
callback.surfaceChanged(holder, format,
|
||||
holder.getSurfaceFrame().width(), holder.getSurfaceFrame().height());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -567,7 +455,76 @@ public class UiHelper {
|
||||
public void attachTo(@NonNull TextureView view) {
|
||||
if (attach(view)) {
|
||||
view.setOpaque(isOpaque());
|
||||
|
||||
mRenderSurface = new TextureViewHandler(view);
|
||||
|
||||
TextureView.SurfaceTextureListener listener = new TextureView.SurfaceTextureListener() {
|
||||
@Override
|
||||
public void onSurfaceTextureAvailable(
|
||||
@NonNull SurfaceTexture surfaceTexture, int width, int height) {
|
||||
if (LOGGING) Log.d(LOG_TAG, "onSurfaceTextureAvailable()");
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
|
||||
if (mDesiredWidth > 0 && mDesiredHeight > 0) {
|
||||
surfaceTexture.setDefaultBufferSize(mDesiredWidth, mDesiredHeight);
|
||||
}
|
||||
}
|
||||
|
||||
Surface surface = new Surface(surfaceTexture);
|
||||
TextureViewHandler textureViewHandler = (TextureViewHandler) mRenderSurface;
|
||||
textureViewHandler.setSurface(surface);
|
||||
|
||||
createSwapChain(surface);
|
||||
|
||||
if (mRenderCallback != null) {
|
||||
// Call this the first time because onSurfaceTextureSizeChanged()
|
||||
// isn't called at initialization time
|
||||
mRenderCallback.onResized(width, height);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSurfaceTextureSizeChanged(
|
||||
@NonNull SurfaceTexture surfaceTexture, int width, int height) {
|
||||
if (LOGGING) Log.d(LOG_TAG, "onSurfaceTextureSizeChanged()");
|
||||
if (mRenderCallback != null) {
|
||||
if (mDesiredWidth > 0 && mDesiredHeight > 0) {
|
||||
surfaceTexture.setDefaultBufferSize(mDesiredWidth, mDesiredHeight);
|
||||
mRenderCallback.onResized(mDesiredWidth, mDesiredHeight);
|
||||
} else {
|
||||
mRenderCallback.onResized(width, height);
|
||||
}
|
||||
// We must recreate the SwapChain to guarantee that it sees the new size.
|
||||
// More precisely, for an EGL client, the EGLSurface must be recreated. For
|
||||
// a Vulkan client, the SwapChain must be recreated. Calling
|
||||
// onNativeWindowChanged() will accomplish that.
|
||||
// This requirement comes from SurfaceTexture.setDefaultBufferSize()
|
||||
// documentation.
|
||||
TextureViewHandler textureViewHandler = (TextureViewHandler) mRenderSurface;
|
||||
mRenderCallback.onNativeWindowChanged(textureViewHandler.getSurface());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surfaceTexture) {
|
||||
if (LOGGING) Log.d(LOG_TAG, "onSurfaceTextureDestroyed()");
|
||||
destroySwapChain();
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) { }
|
||||
};
|
||||
|
||||
view.setSurfaceTextureListener(listener);
|
||||
|
||||
// in case the View's SurfaceTexture already existed
|
||||
if (view.isAvailable()) {
|
||||
SurfaceTexture surfaceTexture = view.getSurfaceTexture();
|
||||
if (surfaceTexture != null) {
|
||||
listener.onSurfaceTextureAvailable(surfaceTexture, mDesiredWidth, mDesiredHeight);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -578,8 +535,46 @@ public class UiHelper {
|
||||
*/
|
||||
public void attachTo(@NonNull SurfaceHolder holder) {
|
||||
if (attach(holder)) {
|
||||
holder.setFormat(isOpaque() ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT);
|
||||
int format = isOpaque() ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT;
|
||||
holder.setFormat(format);
|
||||
|
||||
mRenderSurface = new SurfaceHolderHandler(holder);
|
||||
|
||||
final SurfaceHolder.Callback callback = new SurfaceHolder.Callback() {
|
||||
@Override
|
||||
public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
|
||||
if (LOGGING) Log.d(LOG_TAG, "surfaceCreated()");
|
||||
createSwapChain(holder.getSurface());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
|
||||
// Note: this is always called at least once after surfaceCreated()
|
||||
if (LOGGING) Log.d(LOG_TAG, "surfaceChanged(" + width + ", " + height + ")");
|
||||
if (mRenderCallback != null) {
|
||||
mRenderCallback.onResized(width, height);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
|
||||
if (LOGGING) Log.d(LOG_TAG, "surfaceDestroyed()");
|
||||
destroySwapChain();
|
||||
}
|
||||
};
|
||||
|
||||
holder.addCallback(callback);
|
||||
if (mDesiredWidth > 0 && mDesiredHeight > 0) {
|
||||
holder.setFixedSize(mDesiredWidth, mDesiredHeight);
|
||||
}
|
||||
|
||||
// in case the SurfaceHolder's surface already existed
|
||||
final Surface surface = holder.getSurface();
|
||||
if (surface != null && surface.isValid()) {
|
||||
callback.surfaceCreated(holder);
|
||||
callback.surfaceChanged(holder, format,
|
||||
holder.getSurfaceFrame().width(), holder.getSurfaceFrame().height());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
GROUP=com.google.android.filament
|
||||
VERSION_NAME=1.49.1
|
||||
VERSION_NAME=1.45.0
|
||||
|
||||
POM_DESCRIPTION=Real-time physically based rendering engine for Android.
|
||||
|
||||
|
||||
-31
@@ -26,7 +26,6 @@ import android.widget.TextView
|
||||
import android.widget.Toast
|
||||
import com.google.android.filament.Fence
|
||||
import com.google.android.filament.IndirectLight
|
||||
import com.google.android.filament.Material
|
||||
import com.google.android.filament.Skybox
|
||||
import com.google.android.filament.View
|
||||
import com.google.android.filament.View.OnPickCallback
|
||||
@@ -393,36 +392,6 @@ class MainActivity : Activity() {
|
||||
Log.i(TAG, "The Filament backend took $total ms to load the model geometry.")
|
||||
modelViewer.engine.destroyFence(it)
|
||||
loadStartFence = null
|
||||
|
||||
val materials = mutableSetOf<Material>()
|
||||
val rcm = modelViewer.engine.renderableManager
|
||||
modelViewer.scene.forEach {
|
||||
val entity = it
|
||||
if (rcm.hasComponent(entity)) {
|
||||
val ri = rcm.getInstance(entity)
|
||||
val c = rcm.getPrimitiveCount(ri)
|
||||
for (i in 0 until c) {
|
||||
val mi = rcm.getMaterialInstanceAt(ri, i)
|
||||
val ma = mi.material
|
||||
materials.add(ma)
|
||||
}
|
||||
}
|
||||
}
|
||||
materials.forEach {
|
||||
it.compile(
|
||||
Material.CompilerPriorityQueue.HIGH,
|
||||
Material.UserVariantFilterBit.DIRECTIONAL_LIGHTING or
|
||||
Material.UserVariantFilterBit.DYNAMIC_LIGHTING or
|
||||
Material.UserVariantFilterBit.SHADOW_RECEIVER,
|
||||
null, null)
|
||||
it.compile(
|
||||
Material.CompilerPriorityQueue.LOW,
|
||||
Material.UserVariantFilterBit.FOG or
|
||||
Material.UserVariantFilterBit.SKINNING or
|
||||
Material.UserVariantFilterBit.SSR or
|
||||
Material.UserVariantFilterBit.VSM,
|
||||
null, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-10
@@ -20,8 +20,6 @@ import android.animation.ValueAnimator
|
||||
import android.app.Activity
|
||||
import android.opengl.Matrix
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.Choreographer
|
||||
import android.view.Surface
|
||||
import android.view.SurfaceView
|
||||
@@ -159,14 +157,6 @@ class MainActivity : Activity() {
|
||||
private fun loadMaterial() {
|
||||
readUncompressedAsset("materials/baked_color.filamat").let {
|
||||
material = Material.Builder().payload(it, it.remaining()).build(engine)
|
||||
material.compile(
|
||||
Material.CompilerPriorityQueue.HIGH,
|
||||
Material.UserVariantFilterBit.ALL,
|
||||
Handler(Looper.getMainLooper())) {
|
||||
android.util.Log.i("hellotriangle",
|
||||
"Material " + material.name + " compiled.")
|
||||
}
|
||||
engine.flush()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ function replace {
|
||||
FIND_STR="${1//\{\{VERSION\}\}/${VERSION_REGEX}}"
|
||||
REPLACE_STR="${1//\{\{VERSION\}\}/${NEW_VERSION}}"
|
||||
local FILE_NAME="$2"
|
||||
if [ $IS_DARWIN == 1 ]; then
|
||||
if [ IS_DARWIN ]; then
|
||||
sed -i '' -E "s/${FIND_STR}/${REPLACE_STR}/" "${FILE_NAME}"
|
||||
else
|
||||
sed -i -E "s/${FIND_STR}/${REPLACE_STR}/" "${FILE_NAME}"
|
||||
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+3
-28
@@ -218,6 +218,7 @@ set(MATERIAL_SRCS
|
||||
src/materials/colorGrading/customResolveAsSubpass.mat
|
||||
src/materials/debugShadowCascades.mat
|
||||
src/materials/defaultMaterial.mat
|
||||
src/materials/defaultMaterial0.mat
|
||||
src/materials/dof/dof.mat
|
||||
src/materials/dof/dofCoc.mat
|
||||
src/materials/dof/dofDownsample.mat
|
||||
@@ -228,6 +229,7 @@ set(MATERIAL_SRCS
|
||||
src/materials/dof/dofMipmap.mat
|
||||
src/materials/dof/dofMedian.mat
|
||||
src/materials/flare/flare.mat
|
||||
src/materials/blitLow.mat
|
||||
src/materials/bloom/bloomDownsample.mat
|
||||
src/materials/bloom/bloomDownsample2x.mat
|
||||
src/materials/bloom/bloomDownsample9.mat
|
||||
@@ -236,18 +238,13 @@ set(MATERIAL_SRCS
|
||||
src/materials/ssao/bilateralBlurBentNormals.mat
|
||||
src/materials/ssao/mipmapDepth.mat
|
||||
src/materials/skybox.mat
|
||||
src/materials/skybox0.mat
|
||||
src/materials/ssao/sao.mat
|
||||
src/materials/ssao/saoBentNormals.mat
|
||||
src/materials/separableGaussianBlur.mat
|
||||
src/materials/antiAliasing/fxaa.mat
|
||||
src/materials/antiAliasing/taa.mat
|
||||
src/materials/vsmMipmap.mat
|
||||
src/materials/blitLow.mat
|
||||
)
|
||||
|
||||
set(MATERIAL_FL0_SRCS
|
||||
src/materials/defaultMaterial0.mat
|
||||
src/materials/skybox0.mat
|
||||
)
|
||||
|
||||
# Embed the binary resource blob for materials.
|
||||
@@ -274,11 +271,6 @@ if (NOT DFG_LUT_SIZE)
|
||||
endif()
|
||||
message(STATUS "DFG LUT size set to ${DFG_LUT_SIZE}x${DFG_LUT_SIZE}")
|
||||
|
||||
# Whether to include FL0 materials.
|
||||
if (FILAMENT_ENABLE_FEATURE_LEVEL_0)
|
||||
add_definitions(-DFILAMENT_ENABLE_FEATURE_LEVEL_0)
|
||||
endif()
|
||||
|
||||
# ==================================================================================================
|
||||
# Definitions
|
||||
# ==================================================================================================
|
||||
@@ -320,23 +312,6 @@ foreach (mat_src ${MATERIAL_SRCS})
|
||||
list(APPEND MATERIAL_BINS ${output_path})
|
||||
endforeach()
|
||||
|
||||
if (FILAMENT_ENABLE_FEATURE_LEVEL_0 AND FILAMENT_SUPPORTS_OPENGL)
|
||||
foreach (mat_src ${MATERIAL_FL0_SRCS})
|
||||
get_filename_component(localname "${mat_src}" NAME_WE)
|
||||
get_filename_component(fullname "${mat_src}" ABSOLUTE)
|
||||
set(output_path "${MATERIAL_DIR}/${localname}.filamat")
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT ${output_path}
|
||||
COMMAND matc -a opengl -p ${MATC_TARGET} ${MATC_OPT_FLAGS} -o ${output_path} ${fullname}
|
||||
MAIN_DEPENDENCY ${fullname}
|
||||
DEPENDS matc
|
||||
COMMENT "Compiling material ${mat_src} to ${output_path}"
|
||||
)
|
||||
list(APPEND MATERIAL_BINS ${output_path})
|
||||
endforeach ()
|
||||
endif ()
|
||||
|
||||
# Additional dependencies on included files for materials
|
||||
|
||||
add_custom_command(
|
||||
|
||||
@@ -169,8 +169,6 @@ if (FILAMENT_SUPPORTS_VULKAN)
|
||||
src/vulkan/platform/VulkanPlatform.cpp
|
||||
src/vulkan/platform/VulkanPlatformSwapChainImpl.cpp
|
||||
src/vulkan/platform/VulkanPlatformSwapChainImpl.h
|
||||
src/vulkan/spirv/VulkanSpirvUtils.cpp
|
||||
src/vulkan/spirv/VulkanSpirvUtils.h
|
||||
src/vulkan/VulkanBlitter.cpp
|
||||
src/vulkan/VulkanBlitter.h
|
||||
src/vulkan/VulkanBuffer.cpp
|
||||
@@ -315,7 +313,6 @@ endif()
|
||||
|
||||
if (FILAMENT_SUPPORTS_VULKAN)
|
||||
target_link_libraries(${TARGET} PUBLIC bluevk vkmemalloc vkshaders smol-v)
|
||||
target_link_libraries(${TARGET} PRIVATE SPIRV-Headers)
|
||||
endif()
|
||||
|
||||
if (FILAMENT_SUPPORTS_METAL)
|
||||
@@ -400,8 +397,8 @@ install(DIRECTORY ${PUBLIC_HDR_DIR}/backend DESTINATION include)
|
||||
# ==================================================================================================
|
||||
option(INSTALL_BACKEND_TEST "Install the backend test library so it can be consumed on iOS" OFF)
|
||||
|
||||
if (APPLE OR LINUX)
|
||||
set(BACKEND_TEST_SRC
|
||||
if (APPLE)
|
||||
add_library(backend_test STATIC
|
||||
test/BackendTest.cpp
|
||||
test/ShaderGenerator.cpp
|
||||
test/TrianglePrimitive.cpp
|
||||
@@ -413,26 +410,19 @@ if (APPLE OR LINUX)
|
||||
test/test_BufferUpdates.cpp
|
||||
test/test_MRT.cpp
|
||||
test/test_LoadImage.cpp
|
||||
test/test_RenderExternalImage.cpp
|
||||
test/test_StencilBuffer.cpp
|
||||
test/test_Scissor.cpp
|
||||
test/test_MipLevels.cpp
|
||||
)
|
||||
set(BACKEND_TEST_LIBS
|
||||
)
|
||||
|
||||
target_link_libraries(backend_test PRIVATE
|
||||
backend
|
||||
getopt
|
||||
gtest
|
||||
imageio
|
||||
filamat
|
||||
SPIRV
|
||||
spirv-cross-glsl)
|
||||
endif()
|
||||
|
||||
if (APPLE)
|
||||
# TODO: we should expand this test to Linux and other platforms.
|
||||
list(APPEND BACKEND_TEST_SRC
|
||||
test/test_RenderExternalImage.cpp)
|
||||
add_library(backend_test STATIC ${BACKEND_TEST_SRC})
|
||||
target_link_libraries(backend_test PRIVATE ${BACKEND_TEST_LIBS})
|
||||
|
||||
set(BACKEND_TEST_DEPS
|
||||
OGLCompiler
|
||||
@@ -446,11 +436,12 @@ if (APPLE)
|
||||
glslang
|
||||
spirv-cross-core
|
||||
spirv-cross-glsl
|
||||
spirv-cross-msl)
|
||||
spirv-cross-msl
|
||||
)
|
||||
|
||||
if (NOT IOS)
|
||||
target_link_libraries(backend_test PRIVATE image imageio)
|
||||
list(APPEND BACKEND_TEST_DEPS image)
|
||||
list(APPEND BACKEND_TEST_DEPS image imageio)
|
||||
endif()
|
||||
|
||||
set(BACKEND_TEST_COMBINED_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/libbackendtest_combined.a")
|
||||
@@ -464,21 +455,15 @@ if (APPLE)
|
||||
endif()
|
||||
|
||||
set_target_properties(backend_test PROPERTIES FOLDER Tests)
|
||||
|
||||
if (APPLE AND NOT IOS)
|
||||
add_executable(backend_test_mac test/mac_runner.mm)
|
||||
target_link_libraries(backend_test_mac PRIVATE "-framework Metal -framework AppKit -framework QuartzCore")
|
||||
# Because each test case is a separate file, the -force_load flag is necessary to prevent the
|
||||
# linker from removing "unused" symbols.
|
||||
target_link_libraries(backend_test_mac PRIVATE -force_load backend_test)
|
||||
set_target_properties(backend_test_mac PROPERTIES FOLDER Tests)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if (LINUX)
|
||||
add_executable(backend_test_linux test/linux_runner.cpp ${BACKEND_TEST_SRC})
|
||||
target_link_libraries(backend_test_linux PRIVATE ${BACKEND_TEST_LIBS})
|
||||
set_target_properties(backend_test_linux PROPERTIES FOLDER Tests)
|
||||
if (APPLE AND NOT IOS)
|
||||
add_executable(backend_test_mac test/mac_runner.mm)
|
||||
target_link_libraries(backend_test_mac PRIVATE "-framework Metal -framework AppKit -framework QuartzCore")
|
||||
# Because each test case is a separate file, the -force_load flag is necessary to prevent the
|
||||
# linker from removing "unused" symbols.
|
||||
target_link_libraries(backend_test_mac PRIVATE -force_load backend_test)
|
||||
set_target_properties(backend_test_mac PROPERTIES FOLDER Tests)
|
||||
endif()
|
||||
|
||||
# ==================================================================================================
|
||||
|
||||
@@ -113,7 +113,7 @@ public:
|
||||
/**
|
||||
* Helper to create a BufferDescriptor that uses a KNOWN method pointer w/ object passed
|
||||
* by pointer as the callback. e.g.:
|
||||
* auto bd = BufferDescriptor::make<Foo, &Foo::method>(buffer, size, foo);
|
||||
* auto bd = BufferDescriptor::make(buffer, size, &Foo::method, foo);
|
||||
*
|
||||
* @param buffer Memory address of the CPU buffer to reference
|
||||
* @param size Size of the CPU buffer in bytes
|
||||
@@ -121,12 +121,12 @@ public:
|
||||
* @return a new BufferDescriptor
|
||||
*/
|
||||
template<typename T, void(T::*method)(void const*, size_t)>
|
||||
static BufferDescriptor make(void const* buffer, size_t size, T* data,
|
||||
CallbackHandler* handler = nullptr) noexcept {
|
||||
static BufferDescriptor make(
|
||||
void const* buffer, size_t size, T* data, CallbackHandler* handler = nullptr) noexcept {
|
||||
return {
|
||||
buffer, size,
|
||||
handler, [](void* b, size_t s, void* u) {
|
||||
(static_cast<T*>(u)->*method)(b, s);
|
||||
(*static_cast<T**>(u)->*method)(b, s);
|
||||
}, data
|
||||
};
|
||||
}
|
||||
@@ -145,14 +145,14 @@ public:
|
||||
* @return a new BufferDescriptor
|
||||
*/
|
||||
template<typename T>
|
||||
static BufferDescriptor make(void const* buffer, size_t size, T&& functor,
|
||||
CallbackHandler* handler = nullptr) noexcept {
|
||||
static BufferDescriptor make(
|
||||
void const* buffer, size_t size, T&& functor, CallbackHandler* handler = nullptr) noexcept {
|
||||
return {
|
||||
buffer, size,
|
||||
handler, [](void* b, size_t s, void* u) {
|
||||
T* const that = static_cast<T*>(u);
|
||||
that->operator()(b, s);
|
||||
delete that;
|
||||
T& that = *static_cast<T*>(u);
|
||||
that(b, s);
|
||||
delete &that;
|
||||
},
|
||||
new T(std::forward<T>(functor))
|
||||
};
|
||||
@@ -201,7 +201,7 @@ public:
|
||||
return mUser;
|
||||
}
|
||||
|
||||
//! CPU memory-buffer virtual address
|
||||
//! CPU mempry-buffer virtual address
|
||||
void* buffer = nullptr;
|
||||
|
||||
//! CPU memory-buffer size in bytes
|
||||
|
||||
@@ -227,7 +227,6 @@ struct Viewport {
|
||||
int32_t top() const noexcept { return bottom + int32_t(height); }
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Specifies the mapping of the near and far clipping plane to window coordinates.
|
||||
*/
|
||||
@@ -357,6 +356,13 @@ enum class SamplerFormat : uint8_t {
|
||||
SHADOW = 3 //!< shadow sampler (PCF)
|
||||
};
|
||||
|
||||
//! Texture color space
|
||||
enum class SamplerTransferFunction : uint8_t {
|
||||
UNDEFINED = 0, //!< don't care
|
||||
IDENTITY = 1, //!< sampled as-is
|
||||
SRGB_TO_LINEAR = 2, //!< sampled as sRGB and converted to linear
|
||||
};
|
||||
|
||||
/**
|
||||
* Supported element types
|
||||
*/
|
||||
@@ -659,15 +665,13 @@ enum class TextureFormat : uint16_t {
|
||||
|
||||
//! Bitmask describing the intended Texture Usage
|
||||
enum class TextureUsage : uint8_t {
|
||||
NONE = 0x00,
|
||||
COLOR_ATTACHMENT = 0x01, //!< Texture can be used as a color attachment
|
||||
DEPTH_ATTACHMENT = 0x02, //!< Texture can be used as a depth attachment
|
||||
STENCIL_ATTACHMENT = 0x04, //!< Texture can be used as a stencil attachment
|
||||
UPLOADABLE = 0x08, //!< Data can be uploaded into this texture (default)
|
||||
NONE = 0x0,
|
||||
COLOR_ATTACHMENT = 0x1, //!< Texture can be used as a color attachment
|
||||
DEPTH_ATTACHMENT = 0x2, //!< Texture can be used as a depth attachment
|
||||
STENCIL_ATTACHMENT = 0x4, //!< Texture can be used as a stencil attachment
|
||||
UPLOADABLE = 0x8, //!< Data can be uploaded into this texture (default)
|
||||
SAMPLEABLE = 0x10, //!< Texture can be sampled (default)
|
||||
SUBPASS_INPUT = 0x20, //!< Texture can be used as a subpass input
|
||||
BLIT_SRC = 0x40, //!< Texture can be used the source of a blit()
|
||||
BLIT_DST = 0x80, //!< Texture can be used the destination of a blit()
|
||||
DEFAULT = UPLOADABLE | SAMPLEABLE //!< Default texture usage
|
||||
};
|
||||
|
||||
@@ -695,17 +699,6 @@ static constexpr bool isDepthFormat(TextureFormat format) noexcept {
|
||||
}
|
||||
}
|
||||
|
||||
static constexpr bool isStencilFormat(TextureFormat format) noexcept {
|
||||
switch (format) {
|
||||
case TextureFormat::STENCIL8:
|
||||
case TextureFormat::DEPTH24_STENCIL8:
|
||||
case TextureFormat::DEPTH32F_STENCIL8:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static constexpr bool isUnsignedIntFormat(TextureFormat format) {
|
||||
switch (format) {
|
||||
case TextureFormat::R8UI:
|
||||
@@ -1194,8 +1187,8 @@ using FrameScheduledCallback = void(*)(PresentCallable callable, void* user);
|
||||
enum class Workaround : uint16_t {
|
||||
// The EASU pass must split because shader compiler flattens early-exit branch
|
||||
SPLIT_EASU,
|
||||
// Backend allows feedback loop with ancillary buffers (depth/stencil) as long as they're
|
||||
// read-only for the whole render pass.
|
||||
// Backend allows feedback loop with ancillary buffers (depth/stencil) as long as they're read-only for
|
||||
// the whole render pass.
|
||||
ALLOW_READ_ONLY_ANCILLARY_FEEDBACK_LOOP,
|
||||
// for some uniform arrays, it's needed to do an initialization to avoid crash on adreno gpu
|
||||
ADRENO_UNIFORM_ARRAY_CRASH,
|
||||
|
||||
@@ -141,7 +141,7 @@ public:
|
||||
CallbackHandler* handler = nullptr) noexcept {
|
||||
return { buffer, size, format, type, alignment, left, top, stride,
|
||||
handler, [](void* b, size_t s, void* u) {
|
||||
(static_cast<T*>(u)->*method)(b, s); }, data };
|
||||
(*static_cast<T**>(u)->*method)(b, s); }, data };
|
||||
}
|
||||
|
||||
template<typename T, void(T::*method)(void const*, size_t)>
|
||||
@@ -149,7 +149,7 @@ public:
|
||||
PixelDataFormat format, PixelDataType type, T* data,
|
||||
CallbackHandler* handler = nullptr) noexcept {
|
||||
return { buffer, size, format, type, handler, [](void* b, size_t s, void* u) {
|
||||
(static_cast<T*>(u)->*method)(b, s); }, data };
|
||||
(*static_cast<T**>(u)->*method)(b, s); }, data };
|
||||
}
|
||||
|
||||
template<typename T, void(T::*method)(void const*, size_t)>
|
||||
@@ -157,7 +157,7 @@ public:
|
||||
backend::CompressedPixelDataType format, uint32_t imageSize, T* data,
|
||||
CallbackHandler* handler = nullptr) noexcept {
|
||||
return { buffer, size, format, imageSize, handler, [](void* b, size_t s, void* u) {
|
||||
(static_cast<T*>(u)->*method)(b, s); }, data
|
||||
(*static_cast<T**>(u)->*method)(b, s); }, data
|
||||
};
|
||||
}
|
||||
|
||||
@@ -168,9 +168,9 @@ public:
|
||||
CallbackHandler* handler = nullptr) noexcept {
|
||||
return { buffer, size, format, type, alignment, left, top, stride,
|
||||
handler, [](void* b, size_t s, void* u) {
|
||||
T* const that = static_cast<T*>(u);
|
||||
that->operator()(b, s);
|
||||
delete that;
|
||||
T& that = *static_cast<T*>(u);
|
||||
that(b, s);
|
||||
delete &that;
|
||||
}, new T(std::forward<T>(functor))
|
||||
};
|
||||
}
|
||||
@@ -181,9 +181,9 @@ public:
|
||||
CallbackHandler* handler = nullptr) noexcept {
|
||||
return { buffer, size, format, type,
|
||||
handler, [](void* b, size_t s, void* u) {
|
||||
T* const that = static_cast<T*>(u);
|
||||
that->operator()(b, s);
|
||||
delete that;
|
||||
T& that = *static_cast<T*>(u);
|
||||
that(b, s);
|
||||
delete &that;
|
||||
}, new T(std::forward<T>(functor))
|
||||
};
|
||||
}
|
||||
@@ -194,9 +194,9 @@ public:
|
||||
CallbackHandler* handler = nullptr) noexcept {
|
||||
return { buffer, size, format, imageSize,
|
||||
handler, [](void* b, size_t s, void* u) {
|
||||
T* const that = static_cast<T*>(u);
|
||||
that->operator()(b, s);
|
||||
delete that;
|
||||
T& that = *static_cast<T*>(u);
|
||||
that(b, s);
|
||||
delete &that;
|
||||
}, new T(std::forward<T>(functor))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -303,6 +303,7 @@ DECL_DRIVER_API_SYNCHRONOUS_0(bool, isParallelShaderCompileSupported)
|
||||
DECL_DRIVER_API_SYNCHRONOUS_0(uint8_t, getMaxDrawBuffers)
|
||||
DECL_DRIVER_API_SYNCHRONOUS_0(size_t, getMaxUniformBufferSize)
|
||||
DECL_DRIVER_API_SYNCHRONOUS_0(math::float2, getClipSpaceParams)
|
||||
DECL_DRIVER_API_SYNCHRONOUS_0(bool, canGenerateMipmaps)
|
||||
DECL_DRIVER_API_SYNCHRONOUS_N(void, setupExternalImage, void*, image)
|
||||
DECL_DRIVER_API_SYNCHRONOUS_N(bool, getTimerQueryValue, backend::TimerQueryHandle, query, uint64_t*, elapsedTime)
|
||||
DECL_DRIVER_API_SYNCHRONOUS_N(bool, isWorkaroundNeeded, backend::Workaround, workaround)
|
||||
@@ -467,7 +468,7 @@ DECL_DRIVER_API_N(readBufferSubData,
|
||||
* --------------------
|
||||
*/
|
||||
|
||||
DECL_DRIVER_API_N(blitDEPRECATED,
|
||||
DECL_DRIVER_API_N(blit,
|
||||
backend::TargetBufferFlags, buffers,
|
||||
backend::RenderTargetHandle, dst,
|
||||
backend::Viewport, dstRect,
|
||||
@@ -475,21 +476,6 @@ DECL_DRIVER_API_N(blitDEPRECATED,
|
||||
backend::Viewport, srcRect,
|
||||
backend::SamplerMagFilter, filter)
|
||||
|
||||
DECL_DRIVER_API_N(resolve,
|
||||
backend::TextureHandle, dst,
|
||||
uint8_t, dstLevel, uint8_t, dstLayer,
|
||||
backend::TextureHandle, src,
|
||||
uint8_t, srcLevel, uint8_t, srcLayer)
|
||||
|
||||
DECL_DRIVER_API_N(blit,
|
||||
backend::TextureHandle, dst,
|
||||
uint8_t, dstLevel, uint8_t, dstLayer,
|
||||
math::uint2, dstOrigin,
|
||||
backend::TextureHandle, src,
|
||||
uint8_t, srcLevel, uint8_t, srcLayer,
|
||||
math::uint2, srcOrigin,
|
||||
math::uint2, size)
|
||||
|
||||
DECL_DRIVER_API_N(draw,
|
||||
backend::PipelineState, state,
|
||||
backend::RenderPrimitiveHandle, rph,
|
||||
|
||||
@@ -24,7 +24,8 @@
|
||||
#include <tsl/robin_map.h>
|
||||
#include <utils/Hash.h>
|
||||
|
||||
namespace filament::backend {
|
||||
namespace filament {
|
||||
namespace backend {
|
||||
|
||||
struct MetalContext;
|
||||
|
||||
@@ -34,45 +35,36 @@ public:
|
||||
|
||||
explicit MetalBlitter(MetalContext& context) noexcept;
|
||||
|
||||
enum class FormatType { NONE, COLOR, DEPTH, STENCIL, DEPTH_STENCIL };
|
||||
static FormatType getFormatType(TextureFormat format) noexcept {
|
||||
bool const depth = isDepthFormat(format);
|
||||
bool const stencil = isStencilFormat(format);
|
||||
if (depth && stencil) return FormatType::DEPTH_STENCIL;
|
||||
if (depth) return FormatType::DEPTH;
|
||||
if (stencil) return FormatType::STENCIL;
|
||||
return FormatType::COLOR;
|
||||
}
|
||||
|
||||
struct BlitArgs {
|
||||
struct Attachment {
|
||||
using Type = FormatType;
|
||||
id<MTLTexture> texture = nil;
|
||||
id<MTLTexture> color = nil;
|
||||
id<MTLTexture> depth = nil;
|
||||
MTLRegion region = {};
|
||||
uint8_t level = 0;
|
||||
uint32_t slice = 0; // must be 0 on source attachment
|
||||
Type type = Type::NONE;
|
||||
};
|
||||
|
||||
// Valid source formats: 2D, 2DArray, 2DMultisample, 3D
|
||||
// Valid destination formats: 2D, 2DArray, 3D, Cube
|
||||
Attachment source;
|
||||
Attachment destination;
|
||||
Attachment source, destination;
|
||||
SamplerMagFilter filter;
|
||||
|
||||
bool blitColor() const {
|
||||
return source.type == Attachment::Type::COLOR &&
|
||||
destination.type == Attachment::Type::COLOR;
|
||||
return source.color != nil && destination.color != nil;
|
||||
}
|
||||
|
||||
bool blitDepth() const {
|
||||
return source.type == Attachment::Type::DEPTH &&
|
||||
destination.type == Attachment::Type::DEPTH;
|
||||
return source.depth != nil && destination.depth != nil;
|
||||
}
|
||||
|
||||
bool destinationIsFullAttachment() const {
|
||||
return destination.texture.width == destination.region.size.width &&
|
||||
destination.texture.height == destination.region.size.height;
|
||||
bool colorDestinationIsFullAttachment() const {
|
||||
return destination.color.width == destination.region.size.width &&
|
||||
destination.color.height == destination.region.size.height;
|
||||
}
|
||||
|
||||
bool depthDestinationIsFullAttachment() const {
|
||||
return destination.depth.width == destination.region.size.width &&
|
||||
destination.depth.height == destination.region.size.height;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -86,8 +78,10 @@ public:
|
||||
|
||||
private:
|
||||
|
||||
static void setupAttachment(MTLRenderPassAttachmentDescriptor* descriptor,
|
||||
const BlitArgs& args, uint32_t depthPlane);
|
||||
static void setupColorAttachment(const BlitArgs& args, MTLRenderPassDescriptor* descriptor,
|
||||
uint32_t depthPlane);
|
||||
static void setupDepthAttachment(const BlitArgs& args, MTLRenderPassDescriptor* descriptor,
|
||||
uint32_t depthPlane);
|
||||
|
||||
struct BlitFunctionKey {
|
||||
bool blitColor;
|
||||
@@ -100,7 +94,7 @@ private:
|
||||
|
||||
bool isValid() const noexcept {
|
||||
// MSAA 3D textures do not exist.
|
||||
bool const hasMsaa = msaaColorSource || msaaDepthSource;
|
||||
bool hasMsaa = msaaColorSource || msaaDepthSource;
|
||||
return !(hasMsaa && sources3D);
|
||||
}
|
||||
|
||||
@@ -117,17 +111,15 @@ private:
|
||||
}
|
||||
};
|
||||
|
||||
static bool blitFastPath(id<MTLCommandBuffer> cmdBuffer,
|
||||
void blitFastPath(id<MTLCommandBuffer> cmdBuffer, bool& blitColor, bool& blitDepth,
|
||||
const BlitArgs& args, const char* label);
|
||||
|
||||
void blitSlowPath(id<MTLCommandBuffer> cmdBuffer,
|
||||
void blitSlowPath(id<MTLCommandBuffer> cmdBuffer, bool& blitColor, bool& blitDepth,
|
||||
const BlitArgs& args, const char* label);
|
||||
|
||||
void blitDepthPlane(id<MTLCommandBuffer> cmdBuffer, bool blitColor, bool blitDepth,
|
||||
const BlitArgs& args, uint32_t depthPlaneSource, uint32_t depthPlaneDest,
|
||||
const char* label);
|
||||
|
||||
id<MTLFunction> compileFragmentFunction(BlitFunctionKey key) const;
|
||||
id<MTLTexture> createIntermediateTexture(id<MTLTexture> t, MTLSize size);
|
||||
id<MTLFunction> compileFragmentFunction(BlitFunctionKey key);
|
||||
id<MTLFunction> getBlitVertexFunction();
|
||||
id<MTLFunction> getBlitFragmentFunction(BlitFunctionKey key);
|
||||
|
||||
@@ -138,9 +130,10 @@ private:
|
||||
tsl::robin_map<BlitFunctionKey, Function, HashFn> mBlitFunctions;
|
||||
|
||||
id<MTLFunction> mVertexFunction = nil;
|
||||
|
||||
};
|
||||
|
||||
} // namespace filament::backend
|
||||
|
||||
} // namespace backend
|
||||
} // namespace filament
|
||||
|
||||
#endif //TNT_METALBLITTER_H
|
||||
|
||||
@@ -21,7 +21,8 @@
|
||||
|
||||
#include <utils/Panic.h>
|
||||
|
||||
namespace filament::backend {
|
||||
namespace filament {
|
||||
namespace backend {
|
||||
|
||||
static const char* functionLibrary = R"(
|
||||
#include <metal_stdlib>
|
||||
@@ -138,116 +139,178 @@ blitterFrag(VertexOut in [[stage_in]],
|
||||
}
|
||||
)";
|
||||
|
||||
|
||||
template<typename T>
|
||||
inline bool MTLSizeEqual(T a, T b) noexcept {
|
||||
return (a.width == b.width && a.height == b.height && a.depth == b.depth);
|
||||
}
|
||||
|
||||
MetalBlitter::MetalBlitter(MetalContext& context) noexcept : mContext(context) { }
|
||||
|
||||
#define MTLSizeEqual(a, b) (a.width == b.width && a.height == b.height && a.depth == b.depth)
|
||||
|
||||
void MetalBlitter::blit(id<MTLCommandBuffer> cmdBuffer, const BlitArgs& args, const char* label) {
|
||||
bool blitColor = args.blitColor();
|
||||
bool blitDepth = args.blitDepth();
|
||||
|
||||
ASSERT_PRECONDITION(args.source.region.size.depth == args.destination.region.size.depth,
|
||||
"Blitting requires the source and destination regions to have the same depth.");
|
||||
|
||||
if (args.source.color && args.source.depth) {
|
||||
MTLTextureType colorType = args.source.color.textureType;
|
||||
MTLTextureType depthType = args.source.depth.textureType;
|
||||
|
||||
if (colorType == MTLTextureType2DMultisample) colorType = MTLTextureType2D;
|
||||
if (depthType == MTLTextureType2DMultisample) depthType = MTLTextureType2D;
|
||||
|
||||
ASSERT_PRECONDITION(colorType == depthType,
|
||||
"Blitting requires color and depth sources to be the same texture type.");
|
||||
}
|
||||
|
||||
// Determine if the blit for color or depth are eligible to use a MTLBlitCommandEncoder.
|
||||
// blitFastPath returns true upon success.
|
||||
// blitFastPath fails if either the format or sampleCount don't match (i.e. resolve)
|
||||
if (blitFastPath(cmdBuffer, args, label)) {
|
||||
// blitColor and / or blitDepth are set to false upon success, to indicate that no more work is
|
||||
// necessary for that attachment.
|
||||
blitFastPath(cmdBuffer, blitColor, blitDepth, args, label);
|
||||
|
||||
if (!blitColor && !blitDepth) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If the destination is MSAA, and we weren't able to use the fast path (meaning formats
|
||||
// didn't match or sample count didn't match), report an error, as blitting to a MSAA texture
|
||||
// isn't supported through the "slow path" yet.
|
||||
UTILS_UNUSED_IN_RELEASE
|
||||
const bool destinationIsMultisample =
|
||||
args.destination.texture.textureType == MTLTextureType2DMultisample;
|
||||
// If the destination is MSAA and we weren't able to use the fast path, report an error, as
|
||||
// blitting to a MSAA texture isn't supported through the "slow path" yet.
|
||||
const bool colorDestinationIsMultisample =
|
||||
blitColor && args.destination.color.textureType == MTLTextureType2DMultisample;
|
||||
const bool depthDestinationIsMultisample =
|
||||
blitDepth && args.destination.depth.textureType == MTLTextureType2DMultisample;
|
||||
ASSERT_PRECONDITION(!colorDestinationIsMultisample && !depthDestinationIsMultisample,
|
||||
"Blitting between MSAA render targets with differing pixel formats and/or regions is not supported.");
|
||||
|
||||
assert_invariant(!destinationIsMultisample);
|
||||
assert_invariant((args.destination.texture.usage & MTLTextureUsageRenderTarget));
|
||||
blitSlowPath(cmdBuffer, args, label);
|
||||
}
|
||||
// If the destination texture doesn't have the MTLTextureUsageRenderTarget flag, we have to blit
|
||||
// to an intermediate texture first to perform the format conversion. Then, we can perform a
|
||||
// "fast blit" to the final destination texture.
|
||||
|
||||
bool MetalBlitter::blitFastPath(id<MTLCommandBuffer> cmdBuffer,
|
||||
const BlitArgs& args, const char* label) {
|
||||
id<MTLTexture> intermediateColor = nil;
|
||||
id<MTLTexture> intermediateDepth = nil;
|
||||
BlitArgs slowBlit = args;
|
||||
BlitArgs finalBlit = args;
|
||||
|
||||
if (args.source.texture.sampleCount == args.destination.texture.sampleCount &&
|
||||
args.source.texture.pixelFormat == args.destination.texture.pixelFormat &&
|
||||
MTLSizeEqual(args.source.region.size, args.destination.region.size)) {
|
||||
MTLRegion sourceRegionNoOffset = MTLRegionMake3D(0, 0, 0,
|
||||
args.source.region.size.width, args.source.region.size.height,
|
||||
args.source.region.size.depth);
|
||||
|
||||
id<MTLBlitCommandEncoder> const blitEncoder = [cmdBuffer blitCommandEncoder];
|
||||
blitEncoder.label = @(label);
|
||||
[blitEncoder copyFromTexture:args.source.texture
|
||||
sourceSlice:args.source.slice
|
||||
sourceLevel:args.source.level
|
||||
sourceOrigin:args.source.region.origin
|
||||
sourceSize:args.source.region.size
|
||||
toTexture:args.destination.texture
|
||||
destinationSlice:args.destination.slice
|
||||
destinationLevel:args.destination.level
|
||||
destinationOrigin:args.destination.region.origin];
|
||||
[blitEncoder endEncoding];
|
||||
|
||||
return true;
|
||||
if (blitColor && !(args.destination.color.usage & MTLTextureUsageRenderTarget)) {
|
||||
intermediateColor = createIntermediateTexture(args.destination.color, args.source.region.size);
|
||||
slowBlit.destination.color = finalBlit.source.color = intermediateColor;
|
||||
slowBlit.destination.level = finalBlit.source.level = 0;
|
||||
slowBlit.destination.slice = finalBlit.source.slice = 0;
|
||||
slowBlit.destination.region = finalBlit.source.region = sourceRegionNoOffset;
|
||||
}
|
||||
return false;
|
||||
if (blitDepth && !(args.destination.depth.usage & MTLTextureUsageRenderTarget)) {
|
||||
intermediateDepth = createIntermediateTexture(args.destination.depth, args.source.region.size);
|
||||
slowBlit.destination.depth = finalBlit.source.depth = intermediateDepth;
|
||||
slowBlit.destination.level = finalBlit.source.level = 0;
|
||||
slowBlit.destination.slice = finalBlit.source.slice = 0;
|
||||
slowBlit.destination.region = finalBlit.source.region = sourceRegionNoOffset;
|
||||
}
|
||||
|
||||
blitSlowPath(cmdBuffer, blitColor, blitDepth, slowBlit, label);
|
||||
|
||||
bool finalBlitColor = intermediateColor != nil;
|
||||
bool finalBlitDepth = intermediateDepth != nil;
|
||||
blitFastPath(cmdBuffer, finalBlitColor, finalBlitDepth, finalBlit, label);
|
||||
}
|
||||
|
||||
void MetalBlitter::blitSlowPath(id<MTLCommandBuffer> cmdBuffer,
|
||||
void MetalBlitter::blitFastPath(id<MTLCommandBuffer> cmdBuffer, bool& blitColor, bool& blitDepth,
|
||||
const BlitArgs& args, const char* label) {
|
||||
bool const blitColor = args.blitColor();
|
||||
bool const blitDepth = args.blitDepth();
|
||||
// scaling in any dimension is not allowed
|
||||
assert_invariant(args.source.region.size.depth == args.destination.region.size.depth);
|
||||
// we're always blitting a single plane
|
||||
assert_invariant(blitColor != blitDepth);
|
||||
if (blitColor) {
|
||||
if (args.source.color.sampleCount == args.destination.color.sampleCount &&
|
||||
args.source.color.pixelFormat == args.destination.color.pixelFormat &&
|
||||
MTLSizeEqual(args.source.region.size, args.destination.region.size)) {
|
||||
|
||||
id<MTLBlitCommandEncoder> blitEncoder = [cmdBuffer blitCommandEncoder];
|
||||
blitEncoder.label = @(label);
|
||||
[blitEncoder copyFromTexture:args.source.color
|
||||
sourceSlice:args.source.slice
|
||||
sourceLevel:args.source.level
|
||||
sourceOrigin:args.source.region.origin
|
||||
sourceSize:args.source.region.size
|
||||
toTexture:args.destination.color
|
||||
destinationSlice:args.destination.slice
|
||||
destinationLevel:args.destination.level
|
||||
destinationOrigin:args.destination.region.origin];
|
||||
[blitEncoder endEncoding];
|
||||
|
||||
blitColor = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (blitDepth) {
|
||||
if (args.source.depth.sampleCount == args.destination.depth.sampleCount &&
|
||||
args.source.depth.pixelFormat == args.destination.depth.pixelFormat &&
|
||||
MTLSizeEqual(args.source.region.size, args.destination.region.size)) {
|
||||
|
||||
id<MTLBlitCommandEncoder> blitEncoder = [cmdBuffer blitCommandEncoder];
|
||||
blitEncoder.label = @(label);
|
||||
[blitEncoder copyFromTexture:args.source.depth
|
||||
sourceSlice:args.source.slice
|
||||
sourceLevel:args.source.level
|
||||
sourceOrigin:args.source.region.origin
|
||||
sourceSize:args.source.region.size
|
||||
toTexture:args.destination.depth
|
||||
destinationSlice:args.destination.slice
|
||||
destinationLevel:args.destination.level
|
||||
destinationOrigin:args.destination.region.origin];
|
||||
[blitEncoder endEncoding];
|
||||
|
||||
blitDepth = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MetalBlitter::blitSlowPath(id<MTLCommandBuffer> cmdBuffer, bool& blitColor, bool& blitDepth,
|
||||
const BlitArgs& args, const char* label) {
|
||||
|
||||
uint32_t depthPlaneSource = args.source.region.origin.z;
|
||||
uint32_t depthPlaneDest = args.destination.region.origin.z;
|
||||
for (NSUInteger d = 0; d < args.source.region.size.depth; d++) {
|
||||
blitDepthPlane(cmdBuffer, blitColor, blitDepth, args,
|
||||
depthPlaneSource++, depthPlaneDest++, label);
|
||||
|
||||
assert_invariant(args.source.region.size.depth == args.destination.region.size.depth);
|
||||
uint32_t depthPlaneCount = args.source.region.size.depth;
|
||||
for (NSUInteger d = 0; d < depthPlaneCount; d++) {
|
||||
blitDepthPlane(cmdBuffer, blitColor, blitDepth, args, depthPlaneSource++, depthPlaneDest++,
|
||||
label);
|
||||
}
|
||||
|
||||
blitColor = false;
|
||||
blitDepth = false;
|
||||
}
|
||||
|
||||
void MetalBlitter::blitDepthPlane(id<MTLCommandBuffer> cmdBuffer, bool blitColor, bool blitDepth,
|
||||
const BlitArgs& args, uint32_t depthPlaneSource, uint32_t depthPlaneDest,
|
||||
const char* label) {
|
||||
|
||||
assert_invariant(blitColor != blitDepth);
|
||||
|
||||
MTLRenderPassDescriptor* const descriptor = [MTLRenderPassDescriptor renderPassDescriptor];
|
||||
MTLRenderPassDescriptor* descriptor = [MTLRenderPassDescriptor renderPassDescriptor];
|
||||
|
||||
if (blitColor) {
|
||||
setupAttachment(descriptor.colorAttachments[0], args, depthPlaneDest);
|
||||
setupColorAttachment(args, descriptor, depthPlaneDest);
|
||||
}
|
||||
|
||||
if (blitDepth) {
|
||||
setupAttachment(descriptor.depthAttachment, args, depthPlaneDest);
|
||||
setupDepthAttachment(args, descriptor, depthPlaneDest);
|
||||
}
|
||||
|
||||
id<MTLRenderCommandEncoder> const encoder =
|
||||
[cmdBuffer renderCommandEncoderWithDescriptor:descriptor];
|
||||
id<MTLRenderCommandEncoder> encoder = [cmdBuffer renderCommandEncoderWithDescriptor:descriptor];
|
||||
encoder.label = @(label);
|
||||
|
||||
BlitFunctionKey key;
|
||||
key.blitColor = blitColor;
|
||||
key.blitDepth = blitDepth;
|
||||
key.msaaColorSource = blitColor && args.source.texture.textureType == MTLTextureType2DMultisample;
|
||||
key.msaaDepthSource = blitDepth && args.source.texture.textureType == MTLTextureType2DMultisample;
|
||||
key.sources3D = blitColor && args.source.texture.textureType == MTLTextureType3D;
|
||||
key.msaaColorSource = blitColor && args.source.color.textureType == MTLTextureType2DMultisample;
|
||||
key.msaaDepthSource = blitDepth && args.source.depth.textureType == MTLTextureType2DMultisample;
|
||||
key.sources3D = blitColor && args.source.color.textureType == MTLTextureType3D;
|
||||
if (key.sources3D && blitDepth) {
|
||||
assert_invariant(args.source.texture.textureType == MTLTextureType3D);
|
||||
assert_invariant(args.source.depth.textureType == MTLTextureType3D);
|
||||
}
|
||||
id<MTLFunction> const fragmentFunction = getBlitFragmentFunction(key);
|
||||
id<MTLFunction> fragmentFunction = getBlitFragmentFunction(key);
|
||||
|
||||
MetalPipelineState const pipelineState {
|
||||
MetalPipelineState pipelineState {
|
||||
.vertexFunction = getBlitVertexFunction(),
|
||||
.fragmentFunction = fragmentFunction,
|
||||
.vertexDescription = {},
|
||||
.colorAttachmentPixelFormat = {
|
||||
blitColor ? args.destination.texture.pixelFormat : MTLPixelFormatInvalid,
|
||||
blitColor ? args.destination.color.pixelFormat : MTLPixelFormatInvalid,
|
||||
MTLPixelFormatInvalid,
|
||||
MTLPixelFormatInvalid,
|
||||
MTLPixelFormatInvalid,
|
||||
@@ -257,29 +320,28 @@ void MetalBlitter::blitDepthPlane(id<MTLCommandBuffer> cmdBuffer, bool blitColor
|
||||
MTLPixelFormatInvalid
|
||||
},
|
||||
.depthAttachmentPixelFormat =
|
||||
blitDepth ? args.destination.texture.pixelFormat : MTLPixelFormatInvalid,
|
||||
blitDepth ? args.destination.depth.pixelFormat : MTLPixelFormatInvalid,
|
||||
.sampleCount = 1,
|
||||
.blendState = {}
|
||||
};
|
||||
id<MTLRenderPipelineState> const pipeline =
|
||||
mContext.pipelineStateCache.getOrCreateState(pipelineState);
|
||||
id<MTLRenderPipelineState> pipeline = mContext.pipelineStateCache.getOrCreateState(pipelineState);
|
||||
[encoder setRenderPipelineState:pipeline];
|
||||
|
||||
// For texture arrays, create a view of the texture at the given slice (layer).
|
||||
id<MTLTexture> srcTextureColor = args.source.color;
|
||||
if (srcTextureColor && srcTextureColor.textureType == MTLTextureType2DArray) {
|
||||
srcTextureColor = createTextureViewWithSingleSlice(srcTextureColor, args.source.slice);
|
||||
}
|
||||
id<MTLTexture> srcTextureDepth = args.source.depth;
|
||||
if (srcTextureDepth && srcTextureDepth.textureType == MTLTextureType2DArray) {
|
||||
srcTextureDepth = createTextureViewWithSingleSlice(srcTextureDepth, args.source.slice);
|
||||
}
|
||||
|
||||
if (blitColor) {
|
||||
id<MTLTexture> srcTextureColor = args.source.texture;
|
||||
if (srcTextureColor && srcTextureColor.textureType == MTLTextureType2DArray) {
|
||||
srcTextureColor = createTextureViewWithSingleSlice(srcTextureColor, args.source.slice);
|
||||
}
|
||||
[encoder setFragmentTexture:srcTextureColor atIndex:0];
|
||||
}
|
||||
|
||||
if (blitDepth) {
|
||||
id<MTLTexture> srcTextureDepth = args.source.texture;
|
||||
if (srcTextureDepth && srcTextureDepth.textureType == MTLTextureType2DArray) {
|
||||
srcTextureDepth = createTextureViewWithSingleSlice(srcTextureDepth, args.source.slice);
|
||||
}
|
||||
[encoder setFragmentTexture:srcTextureDepth atIndex:1];
|
||||
}
|
||||
|
||||
@@ -290,13 +352,13 @@ void MetalBlitter::blitDepthPlane(id<MTLCommandBuffer> cmdBuffer, bool blitColor
|
||||
filterMin = SamplerMinFilter::LINEAR_MIPMAP_NEAREST;
|
||||
}
|
||||
|
||||
SamplerState const s {
|
||||
SamplerState s {
|
||||
.samplerParams = {
|
||||
.filterMag = args.filter,
|
||||
.filterMin = filterMin
|
||||
}
|
||||
};
|
||||
id<MTLSamplerState> const sampler = mContext.samplerStateCache.getOrCreateState(s);
|
||||
id<MTLSamplerState> sampler = mContext.samplerStateCache.getOrCreateState(s);
|
||||
[encoder setFragmentSamplerState:sampler atIndex:0];
|
||||
|
||||
MTLViewport viewport;
|
||||
@@ -308,11 +370,11 @@ void MetalBlitter::blitDepthPlane(id<MTLCommandBuffer> cmdBuffer, bool blitColor
|
||||
viewport.zfar = 1.0;
|
||||
[encoder setViewport:viewport];
|
||||
|
||||
DepthStencilState const depthStencilState {
|
||||
DepthStencilState depthStencilState {
|
||||
.depthCompare = MTLCompareFunctionAlways,
|
||||
.depthWriteEnabled = blitDepth
|
||||
};
|
||||
id<MTLDepthStencilState> const depthStencil =
|
||||
id<MTLDepthStencilState> depthStencil =
|
||||
mContext.depthStencilStateCache.getOrCreateState(depthStencilState);
|
||||
[encoder setDepthStencilState:depthStencil];
|
||||
|
||||
@@ -348,28 +410,57 @@ void MetalBlitter::blitDepthPlane(id<MTLCommandBuffer> cmdBuffer, bool blitColor
|
||||
[encoder endEncoding];
|
||||
}
|
||||
|
||||
id<MTLTexture> MetalBlitter::createIntermediateTexture(id<MTLTexture> t, MTLSize size) {
|
||||
MTLTextureDescriptor* descriptor = [MTLTextureDescriptor new];
|
||||
descriptor.textureType = size.depth == 1 ? MTLTextureType2D : MTLTextureType3D;
|
||||
descriptor.pixelFormat = t.pixelFormat;
|
||||
descriptor.width = size.width;
|
||||
descriptor.height = size.height;
|
||||
descriptor.depth = size.depth;
|
||||
descriptor.usage = t.usage & MTLTextureUsageRenderTarget;
|
||||
return [mContext.device newTextureWithDescriptor:descriptor];
|
||||
}
|
||||
|
||||
void MetalBlitter::shutdown() noexcept {
|
||||
mBlitFunctions.clear();
|
||||
mVertexFunction = nil;
|
||||
}
|
||||
|
||||
void MetalBlitter::setupAttachment(MTLRenderPassAttachmentDescriptor* descriptor,
|
||||
const BlitArgs& args, uint32_t depthPlane) {
|
||||
descriptor.texture = args.destination.texture;
|
||||
descriptor.level = args.destination.level;
|
||||
descriptor.slice = args.destination.slice;
|
||||
descriptor.depthPlane = depthPlane;
|
||||
descriptor.loadAction = MTLLoadActionLoad;
|
||||
void MetalBlitter::setupColorAttachment(const BlitArgs& args,
|
||||
MTLRenderPassDescriptor* descriptor, uint32_t depthPlane) {
|
||||
descriptor.colorAttachments[0].texture = args.destination.color;
|
||||
descriptor.colorAttachments[0].level = args.destination.level;
|
||||
descriptor.colorAttachments[0].slice = args.destination.slice;
|
||||
descriptor.colorAttachments[0].depthPlane = depthPlane;
|
||||
|
||||
descriptor.colorAttachments[0].loadAction = MTLLoadActionLoad;
|
||||
// We don't need to load the contents of the attachment if we're blitting over all of it.
|
||||
if (args.destinationIsFullAttachment()) {
|
||||
descriptor.loadAction = MTLLoadActionDontCare;
|
||||
if (args.colorDestinationIsFullAttachment()) {
|
||||
descriptor.colorAttachments[0].loadAction = MTLLoadActionDontCare;
|
||||
}
|
||||
descriptor.storeAction = MTLStoreActionStore;
|
||||
|
||||
descriptor.colorAttachments[0].storeAction = MTLStoreActionStore;
|
||||
}
|
||||
|
||||
id<MTLFunction> MetalBlitter::compileFragmentFunction(BlitFunctionKey key) const {
|
||||
MTLCompileOptions* const options = [MTLCompileOptions new];
|
||||
NSMutableDictionary* const macros = [NSMutableDictionary dictionary];
|
||||
void MetalBlitter::setupDepthAttachment(const BlitArgs& args, MTLRenderPassDescriptor* descriptor,
|
||||
uint32_t depthPlane) {
|
||||
descriptor.depthAttachment.texture = args.destination.depth;
|
||||
descriptor.depthAttachment.level = args.destination.level;
|
||||
descriptor.depthAttachment.slice = args.destination.slice;
|
||||
descriptor.depthAttachment.depthPlane = depthPlane;
|
||||
|
||||
descriptor.depthAttachment.loadAction = MTLLoadActionLoad;
|
||||
// We don't need to load the contents of the attachment if we're blitting over all of it.
|
||||
if (args.depthDestinationIsFullAttachment()) {
|
||||
descriptor.depthAttachment.loadAction = MTLLoadActionDontCare;
|
||||
}
|
||||
|
||||
descriptor.depthAttachment.storeAction = MTLStoreActionStore;
|
||||
}
|
||||
|
||||
id<MTLFunction> MetalBlitter::compileFragmentFunction(BlitFunctionKey key) {
|
||||
MTLCompileOptions* options = [MTLCompileOptions new];
|
||||
NSMutableDictionary* macros = [NSMutableDictionary dictionary];
|
||||
if (key.blitColor) {
|
||||
macros[@"BLIT_COLOR"] = @"1";
|
||||
}
|
||||
@@ -386,13 +477,13 @@ id<MTLFunction> MetalBlitter::compileFragmentFunction(BlitFunctionKey key) const
|
||||
macros[@"SOURCES_3D"] = @"1";
|
||||
}
|
||||
options.preprocessorMacros = macros;
|
||||
NSString* const objcSource = [NSString stringWithCString:functionLibrary
|
||||
encoding:NSUTF8StringEncoding];
|
||||
NSString* objcSource = [NSString stringWithCString:functionLibrary
|
||||
encoding:NSUTF8StringEncoding];
|
||||
NSError* error = nil;
|
||||
id <MTLLibrary> const library = [mContext.device newLibraryWithSource:objcSource
|
||||
options:options
|
||||
error:&error];
|
||||
id <MTLFunction> const function = [library newFunctionWithName:@"blitterFrag"];
|
||||
id<MTLLibrary> library = [mContext.device newLibraryWithSource:objcSource
|
||||
options:options
|
||||
error:&error];
|
||||
id<MTLFunction> function = [library newFunctionWithName:@"blitterFrag"];
|
||||
|
||||
if (!library || !function) {
|
||||
if (error) {
|
||||
@@ -410,14 +501,13 @@ id<MTLFunction> MetalBlitter::getBlitVertexFunction() {
|
||||
return mVertexFunction;
|
||||
}
|
||||
|
||||
NSString* const objcSource = [NSString stringWithCString:functionLibrary
|
||||
encoding:NSUTF8StringEncoding];
|
||||
NSString* objcSource = [NSString stringWithCString:functionLibrary
|
||||
encoding:NSUTF8StringEncoding];
|
||||
NSError* error = nil;
|
||||
id <MTLLibrary> const library = [mContext.device newLibraryWithSource:objcSource
|
||||
options:nil
|
||||
error:&error];
|
||||
|
||||
id<MTLFunction> const function = [library newFunctionWithName:@"blitterVertex"];
|
||||
id<MTLLibrary> library = [mContext.device newLibraryWithSource:objcSource
|
||||
options:nil
|
||||
error:&error];
|
||||
id<MTLFunction> function = [library newFunctionWithName:@"blitterVertex"];
|
||||
|
||||
if (!library || !function) {
|
||||
if (error) {
|
||||
@@ -445,5 +535,5 @@ id<MTLFunction> MetalBlitter::getBlitFragmentFunction(BlitFunctionKey key) {
|
||||
return function;
|
||||
}
|
||||
|
||||
} // namespace filament::backend
|
||||
|
||||
} // namespace backend
|
||||
} // namespace filament
|
||||
|
||||
@@ -865,6 +865,10 @@ void MetalDriver::generateMipmaps(Handle<HwTexture> th) {
|
||||
tex->generateMipmaps();
|
||||
}
|
||||
|
||||
bool MetalDriver::canGenerateMipmaps() {
|
||||
return true;
|
||||
}
|
||||
|
||||
void MetalDriver::updateSamplerGroup(Handle<HwSamplerGroup> sbh, BufferDescriptor&& data) {
|
||||
ASSERT_PRECONDITION(!isInRenderPass(mContext),
|
||||
"updateSamplerGroup must be called outside of a render pass.");
|
||||
@@ -1252,16 +1256,14 @@ void MetalDriver::readPixels(Handle<HwRenderTarget> src, uint32_t x, uint32_t y,
|
||||
textureDescriptor.usage = MTLTextureUsageShaderWrite | MTLTextureUsageRenderTarget;
|
||||
id<MTLTexture> readPixelsTexture = [mContext->device newTextureWithDescriptor:textureDescriptor];
|
||||
|
||||
MetalBlitter::BlitArgs args{};
|
||||
MetalBlitter::BlitArgs args;
|
||||
args.filter = SamplerMagFilter::NEAREST;
|
||||
args.source.level = miplevel;
|
||||
args.source.region = MTLRegionMake2D(0, 0, srcTexture.width >> miplevel, srcTexture.height >> miplevel);
|
||||
args.source.texture = srcTexture;
|
||||
args.source.type = MetalBlitter::BlitArgs::Attachment::Type::COLOR;
|
||||
args.destination.level = 0;
|
||||
args.destination.region = MTLRegionMake2D(0, 0, readPixelsTexture.width, readPixelsTexture.height);
|
||||
args.destination.texture = readPixelsTexture;
|
||||
args.destination.type = MetalBlitter::BlitArgs::Attachment::Type::COLOR;
|
||||
args.source.color = srcTexture;
|
||||
args.destination.color = readPixelsTexture;
|
||||
|
||||
mContext->blitter->blit(getPendingCommandBuffer(mContext), args, "readPixels blit");
|
||||
|
||||
@@ -1297,119 +1299,24 @@ void MetalDriver::readBufferSubData(backend::BufferObjectHandle boh,
|
||||
scheduleDestroy(std::move(p));
|
||||
}
|
||||
|
||||
void MetalDriver::resolve(
|
||||
Handle<HwTexture> dst, uint8_t srcLevel, uint8_t srcLayer,
|
||||
Handle<HwTexture> src, uint8_t dstLevel, uint8_t dstLayer) {
|
||||
auto* const srcTexture = handle_cast<MetalTexture>(src);
|
||||
auto* const dstTexture = handle_cast<MetalTexture>(dst);
|
||||
assert_invariant(srcTexture);
|
||||
assert_invariant(dstTexture);
|
||||
|
||||
ASSERT_PRECONDITION(mContext->currentRenderPassEncoder == nil,
|
||||
"resolve() cannot be invoked inside a render pass.");
|
||||
|
||||
ASSERT_PRECONDITION(
|
||||
dstTexture->width == srcTexture->width && dstTexture->height == srcTexture->height,
|
||||
"invalid resolve: src and dst sizes don't match");
|
||||
|
||||
ASSERT_PRECONDITION(srcTexture->samples > 1 && dstTexture->samples == 1,
|
||||
"invalid resolve: src.samples=%u, dst.samples=%u",
|
||||
+srcTexture->samples, +dstTexture->samples);
|
||||
|
||||
ASSERT_PRECONDITION(srcTexture->format == dstTexture->format,
|
||||
"src and dst texture format don't match");
|
||||
|
||||
ASSERT_PRECONDITION(any(dstTexture->usage & TextureUsage::BLIT_DST),
|
||||
"texture doesn't have BLIT_DST");
|
||||
|
||||
ASSERT_PRECONDITION(any(srcTexture->usage & TextureUsage::BLIT_SRC),
|
||||
"texture doesn't have BLIT_SRC");
|
||||
|
||||
// FIXME: on metal the blit() call below always take the slow path (using a shader)
|
||||
|
||||
blit( dst, dstLevel, dstLayer, {},
|
||||
src, srcLevel, srcLayer, {},
|
||||
{ dstTexture->width, dstTexture->height });
|
||||
}
|
||||
|
||||
void MetalDriver::blit(
|
||||
Handle<HwTexture> dst, uint8_t srcLevel, uint8_t srcLayer, math::uint2 dstOrigin,
|
||||
Handle<HwTexture> src, uint8_t dstLevel, uint8_t dstLayer, math::uint2 srcOrigin,
|
||||
math::uint2 size) {
|
||||
|
||||
|
||||
auto isBlitableTextureType = [](MTLTextureType t) -> bool {
|
||||
return t == MTLTextureType2D || t == MTLTextureType2DMultisample ||
|
||||
t == MTLTextureType2DArray;
|
||||
};
|
||||
|
||||
auto* const srcTexture = handle_cast<MetalTexture>(src);
|
||||
auto* const dstTexture = handle_cast<MetalTexture>(dst);
|
||||
assert_invariant(srcTexture);
|
||||
assert_invariant(dstTexture);
|
||||
|
||||
ASSERT_PRECONDITION(mContext->currentRenderPassEncoder == nil,
|
||||
"blit() cannot be invoked inside a render pass.");
|
||||
|
||||
ASSERT_PRECONDITION(any(dstTexture->usage & TextureUsage::BLIT_DST),
|
||||
"texture doesn't have BLIT_DST");
|
||||
|
||||
ASSERT_PRECONDITION(any(srcTexture->usage & TextureUsage::BLIT_SRC),
|
||||
"texture doesn't have BLIT_SRC");
|
||||
|
||||
ASSERT_PRECONDITION(srcTexture->format == dstTexture->format,
|
||||
"src and dst texture format don't match");
|
||||
|
||||
ASSERT_PRECONDITION(isBlitableTextureType(srcTexture->getMtlTextureForRead().textureType) &&
|
||||
isBlitableTextureType(dstTexture->getMtlTextureForWrite().textureType),
|
||||
"Metal does not support blitting to/from non-2D textures.");
|
||||
|
||||
MetalBlitter::BlitArgs args{};
|
||||
args.filter = SamplerMagFilter::NEAREST;
|
||||
args.source.region = MTLRegionMake2D(
|
||||
(NSUInteger)srcOrigin.x,
|
||||
std::max(srcTexture->height - (int64_t)srcOrigin.y - size.y, (int64_t)0),
|
||||
size.x, size.y);
|
||||
args.destination.region = MTLRegionMake2D(
|
||||
(NSUInteger)dstOrigin.x,
|
||||
std::max(dstTexture->height - (int64_t)dstOrigin.y - size.y, (int64_t)0),
|
||||
size.x, size.y);
|
||||
|
||||
// FIXME: we shouldn't need to know the type here. This is an artifact of using the old API.
|
||||
|
||||
args.source.texture = srcTexture->getMtlTextureForRead();
|
||||
args.source.type = MetalBlitter::getFormatType(srcTexture->format);
|
||||
args.destination.texture = dstTexture->getMtlTextureForWrite();
|
||||
args.destination.type = MetalBlitter::getFormatType(dstTexture->format);
|
||||
args.source.level = srcLevel;
|
||||
args.source.slice = srcLayer;
|
||||
args.destination.level = dstLevel;
|
||||
args.destination.slice = dstLayer;
|
||||
|
||||
// TODO: The blit() call below always take the fast path.
|
||||
|
||||
mContext->blitter->blit(getPendingCommandBuffer(mContext), args, "blit/resolve");
|
||||
|
||||
dstTexture->extendLodRangeTo(dstLevel);
|
||||
}
|
||||
|
||||
void MetalDriver::blitDEPRECATED(TargetBufferFlags buffers,
|
||||
void MetalDriver::blit(TargetBufferFlags buffers,
|
||||
Handle<HwRenderTarget> dst, Viewport dstRect,
|
||||
Handle<HwRenderTarget> src, Viewport srcRect,
|
||||
SamplerMagFilter filter) {
|
||||
|
||||
// Note: blitDEPRECATED is only used by Renderer::copyFrame
|
||||
// It is called between beginFrame and endFrame, but should never be called in the middle of
|
||||
// a render pass.
|
||||
|
||||
ASSERT_PRECONDITION(mContext->currentRenderPassEncoder == nil,
|
||||
"blitDEPRECATED() cannot be invoked inside a render pass.");
|
||||
// If we're the in middle of a render pass, finish it.
|
||||
// This condition should only occur during copyFrame. It's okay to end the render pass because
|
||||
// we don't issue any other rendering commands.
|
||||
if (mContext->currentRenderPassEncoder) {
|
||||
[mContext->currentRenderPassEncoder endEncoding];
|
||||
mContext->currentRenderPassEncoder = nil;
|
||||
}
|
||||
|
||||
auto srcTarget = handle_cast<MetalRenderTarget>(src);
|
||||
auto dstTarget = handle_cast<MetalRenderTarget>(dst);
|
||||
|
||||
ASSERT_PRECONDITION(buffers == TargetBufferFlags::COLOR0,
|
||||
"blitDEPRECATED only supports COLOR0");
|
||||
ASSERT_PRECONDITION(
|
||||
!(buffers & (TargetBufferFlags::COLOR_ALL & ~TargetBufferFlags::COLOR0)),
|
||||
"Blitting only supports COLOR0");
|
||||
|
||||
ASSERT_PRECONDITION(srcRect.left >= 0 && srcRect.bottom >= 0 &&
|
||||
dstRect.left >= 0 && dstRect.bottom >= 0,
|
||||
@@ -1420,30 +1327,54 @@ void MetalDriver::blitDEPRECATED(TargetBufferFlags buffers,
|
||||
t == MTLTextureType2DArray;
|
||||
};
|
||||
|
||||
// We always blit from/to the COLOR0 attachment.
|
||||
MetalRenderTarget::Attachment const srcColorAttachment = srcTarget->getReadColorAttachment(0);
|
||||
MetalRenderTarget::Attachment const dstColorAttachment = dstTarget->getDrawColorAttachment(0);
|
||||
// MetalBlitter supports blitting color and depth simultaneously, but for simplicitly we'll blit
|
||||
// them separately. In practice, Filament only ever blits a single buffer at a time anyway.
|
||||
|
||||
if (srcColorAttachment && dstColorAttachment) {
|
||||
ASSERT_PRECONDITION(isBlitableTextureType(srcColorAttachment.getTexture().textureType) &&
|
||||
isBlitableTextureType(dstColorAttachment.getTexture().textureType),
|
||||
"Metal does not support blitting to/from non-2D textures.");
|
||||
if (any(buffers & TargetBufferFlags::COLOR_ALL)) {
|
||||
// We always blit from/to the COLOR0 attachment.
|
||||
MetalRenderTarget::Attachment srcColorAttachment = srcTarget->getReadColorAttachment(0);
|
||||
MetalRenderTarget::Attachment dstColorAttachment = dstTarget->getDrawColorAttachment(0);
|
||||
|
||||
MetalBlitter::BlitArgs args{};
|
||||
args.filter = filter;
|
||||
args.source.region = srcTarget->getRegionFromClientRect(srcRect);
|
||||
args.source.texture = srcColorAttachment.getTexture();
|
||||
args.source.level = srcColorAttachment.level;
|
||||
args.source.slice = srcColorAttachment.layer;
|
||||
args.source.type = MetalBlitter::FormatType::COLOR;
|
||||
if (srcColorAttachment && dstColorAttachment) {
|
||||
ASSERT_PRECONDITION(isBlitableTextureType(srcColorAttachment.getTexture().textureType) &&
|
||||
isBlitableTextureType(dstColorAttachment.getTexture().textureType),
|
||||
"Metal does not support blitting to/from non-2D textures.");
|
||||
|
||||
args.destination.region = dstTarget->getRegionFromClientRect(dstRect);
|
||||
args.destination.texture = dstColorAttachment.getTexture();
|
||||
args.destination.level = dstColorAttachment.level;
|
||||
args.destination.slice = dstColorAttachment.layer;
|
||||
args.destination.type = MetalBlitter::FormatType::COLOR;
|
||||
MetalBlitter::BlitArgs args;
|
||||
args.filter = filter;
|
||||
args.source.region = srcTarget->getRegionFromClientRect(srcRect);
|
||||
args.destination.region = dstTarget->getRegionFromClientRect(dstRect);
|
||||
args.source.color = srcColorAttachment.getTexture();
|
||||
args.destination.color = dstColorAttachment.getTexture();
|
||||
args.source.level = srcColorAttachment.level;
|
||||
args.destination.level = dstColorAttachment.level;
|
||||
args.source.slice = srcColorAttachment.layer;
|
||||
args.destination.slice = dstColorAttachment.layer;
|
||||
mContext->blitter->blit(getPendingCommandBuffer(mContext), args, "Color blit");
|
||||
}
|
||||
}
|
||||
|
||||
mContext->blitter->blit(getPendingCommandBuffer(mContext), args, "blitDEPRECATED");
|
||||
if (any(buffers & TargetBufferFlags::DEPTH)) {
|
||||
MetalRenderTarget::Attachment srcDepthAttachment = srcTarget->getDepthAttachment();
|
||||
MetalRenderTarget::Attachment dstDepthAttachment = dstTarget->getDepthAttachment();
|
||||
|
||||
if (srcDepthAttachment && dstDepthAttachment) {
|
||||
ASSERT_PRECONDITION(isBlitableTextureType(srcDepthAttachment.getTexture().textureType) &&
|
||||
isBlitableTextureType(dstDepthAttachment.getTexture().textureType),
|
||||
"Metal does not support blitting to/from non-2D textures.");
|
||||
|
||||
MetalBlitter::BlitArgs args;
|
||||
args.filter = filter;
|
||||
args.source.region = srcTarget->getRegionFromClientRect(srcRect);
|
||||
args.destination.region = dstTarget->getRegionFromClientRect(dstRect);
|
||||
args.source.depth = srcDepthAttachment.getTexture();
|
||||
args.destination.depth = dstDepthAttachment.getTexture();
|
||||
args.source.level = srcDepthAttachment.level;
|
||||
args.destination.level = dstDepthAttachment.level;
|
||||
args.source.slice = srcDepthAttachment.layer;
|
||||
args.destination.slice = dstDepthAttachment.layer;
|
||||
mContext->blitter->blit(getPendingCommandBuffer(mContext), args, "Depth blit");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -39,15 +39,7 @@ namespace filament {
|
||||
namespace backend {
|
||||
|
||||
static inline MTLTextureUsage getMetalTextureUsage(TextureUsage usage) {
|
||||
NSUInteger u = MTLTextureUsageUnknown;
|
||||
|
||||
if (any(usage & TextureUsage::SAMPLEABLE)) {
|
||||
u |= MTLTextureUsageShaderRead;
|
||||
}
|
||||
if (any(usage & TextureUsage::UPLOADABLE)) {
|
||||
// This is only needed because of the slowpath is MetalBlitter
|
||||
u |= MTLTextureUsageRenderTarget;
|
||||
}
|
||||
NSUInteger u = 0;
|
||||
if (any(usage & TextureUsage::COLOR_ATTACHMENT)) {
|
||||
u |= MTLTextureUsageRenderTarget;
|
||||
}
|
||||
@@ -57,13 +49,9 @@ static inline MTLTextureUsage getMetalTextureUsage(TextureUsage usage) {
|
||||
if (any(usage & TextureUsage::STENCIL_ATTACHMENT)) {
|
||||
u |= MTLTextureUsageRenderTarget;
|
||||
}
|
||||
if (any(usage & TextureUsage::BLIT_DST)) {
|
||||
// This is only needed because of the slowpath is MetalBlitter
|
||||
u |= MTLTextureUsageRenderTarget;
|
||||
}
|
||||
if (any(usage & TextureUsage::BLIT_SRC)) {
|
||||
u |= MTLTextureUsageShaderRead;
|
||||
}
|
||||
|
||||
// All textures can be blitted from, so they must have the UsageShaderRead flag.
|
||||
u |= MTLTextureUsageShaderRead;
|
||||
|
||||
return MTLTextureUsage(u);
|
||||
}
|
||||
@@ -768,7 +756,6 @@ void MetalTexture::loadWithBlit(uint32_t level, uint32_t slice, MTLRegion region
|
||||
#endif
|
||||
|
||||
id<MTLTexture> stagingTexture = [context.device newTextureWithDescriptor:descriptor];
|
||||
// FIXME? Why is this not just `MTLRegion sourceRegion = region;` ?
|
||||
MTLRegion sourceRegion = MTLRegionMake3D(0, 0, 0,
|
||||
region.size.width, region.size.height, region.size.depth);
|
||||
[stagingTexture replaceRegion:sourceRegion
|
||||
@@ -795,18 +782,16 @@ void MetalTexture::loadWithBlit(uint32_t level, uint32_t slice, MTLRegion region
|
||||
slices:NSMakeRange(0, slices)];
|
||||
}
|
||||
|
||||
MetalBlitter::BlitArgs args{};
|
||||
MetalBlitter::BlitArgs args;
|
||||
args.filter = SamplerMagFilter::NEAREST;
|
||||
args.source.level = 0;
|
||||
args.source.slice = 0;
|
||||
args.source.region = sourceRegion;
|
||||
args.source.texture = stagingTexture;
|
||||
args.source.type = MetalBlitter::FormatType::COLOR;
|
||||
args.destination.level = level;
|
||||
args.destination.slice = slice;
|
||||
args.destination.region = region;
|
||||
args.destination.texture = destinationTexture;
|
||||
args.destination.type = MetalBlitter::FormatType::COLOR;
|
||||
args.source.color = stagingTexture;
|
||||
args.destination.color = destinationTexture;
|
||||
context.blitter->blit(getPendingCommandBuffer(&context), args, "Texture upload blit");
|
||||
}
|
||||
|
||||
|
||||
@@ -170,6 +170,9 @@ MetalShaderCompiler::program_token_t MetalShaderCompiler::createProgram(
|
||||
CompilerPriorityQueue const priorityQueue = program.getPriorityQueue();
|
||||
mCompilerThreadPool.queue(priorityQueue, token,
|
||||
[this, name, device = mDevice, program = std::move(program), token]() {
|
||||
int sleepTime = atoi(name.c_str());
|
||||
sleep(sleepTime);
|
||||
|
||||
MetalFunctionBundle compiledProgram = compileProgram(program, device);
|
||||
|
||||
token->set(compiledProgram);
|
||||
|
||||
@@ -252,6 +252,10 @@ void NoopDriver::setExternalStream(Handle<HwTexture> th, Handle<HwStream> sh) {
|
||||
|
||||
void NoopDriver::generateMipmaps(Handle<HwTexture> th) { }
|
||||
|
||||
bool NoopDriver::canGenerateMipmaps() {
|
||||
return true;
|
||||
}
|
||||
|
||||
void NoopDriver::updateSamplerGroup(Handle<HwSamplerGroup> sbh,
|
||||
BufferDescriptor&& data) {
|
||||
scheduleDestroy(std::move(data));
|
||||
@@ -318,23 +322,12 @@ void NoopDriver::readBufferSubData(backend::BufferObjectHandle boh,
|
||||
scheduleDestroy(std::move(p));
|
||||
}
|
||||
|
||||
void NoopDriver::blitDEPRECATED(TargetBufferFlags buffers,
|
||||
void NoopDriver::blit(TargetBufferFlags buffers,
|
||||
Handle<HwRenderTarget> dst, Viewport dstRect,
|
||||
Handle<HwRenderTarget> src, Viewport srcRect,
|
||||
SamplerMagFilter filter) {
|
||||
}
|
||||
|
||||
void NoopDriver::resolve(
|
||||
Handle<HwTexture> dst, uint8_t srcLevel, uint8_t srcLayer,
|
||||
Handle<HwTexture> src, uint8_t dstLevel, uint8_t dstLayer) {
|
||||
}
|
||||
|
||||
void NoopDriver::blit(
|
||||
Handle<HwTexture> dst, uint8_t srcLevel, uint8_t srcLayer, math::uint2 dstOrigin,
|
||||
Handle<HwTexture> src, uint8_t dstLevel, uint8_t dstLayer, math::uint2 srcOrigin,
|
||||
math::uint2 size) {
|
||||
}
|
||||
|
||||
void NoopDriver::draw(PipelineState pipelineState, Handle<HwRenderPrimitive> rph,
|
||||
uint32_t instanceCount) {
|
||||
}
|
||||
|
||||
@@ -284,7 +284,6 @@ void OpenGLContext::setDefaultState() noexcept {
|
||||
|
||||
if (ext.EXT_clip_cull_distance) {
|
||||
glEnable(GL_CLIP_DISTANCE0);
|
||||
glEnable(GL_CLIP_DISTANCE1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -476,6 +475,7 @@ void OpenGLContext::initBugs(Bugs* bugs, Extensions const& exts,
|
||||
// (that should be regardless of ANGLE, but we should double-check)
|
||||
bugs->split_easu = true;
|
||||
}
|
||||
// TODO: see if we could use `bugs.allow_read_only_ancillary_feedback_loop = true`
|
||||
}
|
||||
|
||||
#ifdef BACKEND_OPENGL_VERSION_GLES
|
||||
|
||||
@@ -172,7 +172,7 @@ OpenGLDriver::OpenGLDriver(OpenGLPlatform* platform, const Platform::DriverConfi
|
||||
mShaderCompilerService(*this),
|
||||
mHandleAllocator("Handles", driverConfig.handleArenaSize),
|
||||
mSamplerMap(32) {
|
||||
|
||||
|
||||
std::fill(mSamplerBindings.begin(), mSamplerBindings.end(), nullptr);
|
||||
|
||||
// set a reasonable default value for our stream array
|
||||
@@ -262,27 +262,21 @@ void OpenGLDriver::bindTexture(GLuint unit, GLTexture const* t) noexcept {
|
||||
mContext.bindTexture(unit, t->gl.target, t->gl.id, t->gl.targetIndex);
|
||||
}
|
||||
|
||||
bool OpenGLDriver::useProgram(OpenGLProgram* p) noexcept {
|
||||
if (UTILS_UNLIKELY(!p->isValid())) {
|
||||
// If the program is not valid, we can't call use().
|
||||
return false;
|
||||
}
|
||||
|
||||
void OpenGLDriver::useProgram(OpenGLProgram* p) noexcept {
|
||||
// set-up textures and samplers in the proper TMUs (as specified in setSamplers)
|
||||
p->use(this, mContext);
|
||||
|
||||
if (UTILS_UNLIKELY(mContext.isES2())) {
|
||||
for (uint32_t i = 0; i < Program::UNIFORM_BINDING_COUNT; i++) {
|
||||
auto [id, buffer, age] = mUniformBindings[i];
|
||||
auto [buffer, age] = mUniformBindings[i];
|
||||
if (buffer) {
|
||||
p->updateUniforms(i, id, buffer, age);
|
||||
p->updateUniforms(i, buffer, age);
|
||||
}
|
||||
}
|
||||
// Set the output colorspace for this program (linear or rec709). This in only relevant
|
||||
// when mPlatform.isSRGBSwapChainSupported() is false (no need to check though).
|
||||
p->setRec709ColorSpace(mRec709OutputColorspace);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -485,7 +479,6 @@ void OpenGLDriver::createBufferObjectR(Handle<HwBufferObject> boh,
|
||||
|
||||
GLBufferObject* bo = construct<GLBufferObject>(boh, byteCount, bindingType, usage);
|
||||
if (UTILS_UNLIKELY(bindingType == BufferObjectBinding::UNIFORM && gl.isES2())) {
|
||||
bo->gl.id = ++mLastAssignedEmulatedUboId;
|
||||
bo->gl.buffer = malloc(byteCount);
|
||||
memset(bo->gl.buffer, 0, byteCount);
|
||||
} else {
|
||||
@@ -602,9 +595,8 @@ void OpenGLDriver::textureStorage(OpenGLDriver::GLTexture* t,
|
||||
}
|
||||
} else {
|
||||
glTexImage2D(t->gl.target, level, GLint(t->gl.internalFormat),
|
||||
std::max(GLsizei(1), GLsizei(width >> level)),
|
||||
std::max(GLsizei(1), GLsizei(height >> level)),
|
||||
0, format, type, nullptr);
|
||||
GLsizei(width), GLsizei(height), 0,
|
||||
format, type, nullptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1975,13 +1967,6 @@ void OpenGLDriver::makeCurrent(Handle<HwSwapChain> schDraw, Handle<HwSwapChain>
|
||||
GLSwapChain* scRead = handle_cast<GLSwapChain*>(schRead);
|
||||
mPlatform.makeCurrent(scDraw->swapChain, scRead->swapChain);
|
||||
mCurrentDrawSwapChain = scDraw;
|
||||
|
||||
// From the GL spec for glViewport and glScissor:
|
||||
// When a GL context is first attached to a window, width and height are set to the
|
||||
// dimensions of that window.
|
||||
// So basically, our viewport/scissor can be reset to "something" here.
|
||||
mContext.state.window.viewport = {};
|
||||
mContext.state.window.scissor = {};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------
|
||||
@@ -2227,7 +2212,8 @@ void OpenGLDriver::setMinMaxLevels(Handle<HwTexture> th, uint32_t minLevel, uint
|
||||
t->gl.baseLevel = (int8_t)minLevel;
|
||||
glTexParameteri(t->gl.target, GL_TEXTURE_BASE_LEVEL, t->gl.baseLevel);
|
||||
|
||||
t->gl.maxLevel = (int8_t)maxLevel; // NOTE: according to the GL spec, the default value of this 1000
|
||||
t->gl
|
||||
.maxLevel = (int8_t)maxLevel; // NOTE: according to the GL spec, the default value of this 1000
|
||||
glTexParameteri(t->gl.target, GL_TEXTURE_MAX_LEVEL, t->gl.maxLevel);
|
||||
}
|
||||
#endif
|
||||
@@ -2277,6 +2263,10 @@ void OpenGLDriver::generateMipmaps(Handle<HwTexture> th) {
|
||||
CHECK_GL_ERROR(utils::slog.e)
|
||||
}
|
||||
|
||||
bool OpenGLDriver::canGenerateMipmaps() {
|
||||
return true;
|
||||
}
|
||||
|
||||
void OpenGLDriver::setTextureData(GLTexture* t, uint32_t level,
|
||||
uint32_t xoffset, uint32_t yoffset, uint32_t zoffset,
|
||||
uint32_t width, uint32_t height, uint32_t depth,
|
||||
@@ -2911,11 +2901,7 @@ void OpenGLDriver::bindBufferRange(BufferObjectBinding bindingType, uint32_t ind
|
||||
assert_invariant(offset + size <= ub->byteCount);
|
||||
|
||||
if (UTILS_UNLIKELY(ub->bindingType == BufferObjectBinding::UNIFORM && gl.isES2())) {
|
||||
mUniformBindings[index] = {
|
||||
ub->gl.id,
|
||||
static_cast<uint8_t const*>(ub->gl.buffer) + offset,
|
||||
ub->age,
|
||||
};
|
||||
mUniformBindings[index] = { static_cast<uint8_t const*>(ub->gl.buffer) + offset, ub->age };
|
||||
} else {
|
||||
GLenum const target = GLUtils::getBufferBindingType(bindingType);
|
||||
|
||||
@@ -3433,230 +3419,75 @@ void OpenGLDriver::clearWithRasterPipe(TargetBufferFlags clearFlags,
|
||||
CHECK_GL_ERROR(utils::slog.e)
|
||||
}
|
||||
|
||||
void OpenGLDriver::resolve(
|
||||
Handle<HwTexture> dst, uint8_t srcLevel, uint8_t srcLayer,
|
||||
Handle<HwTexture> src, uint8_t dstLevel, uint8_t dstLayer) {
|
||||
DEBUG_MARKER()
|
||||
GLTexture const* const s = handle_cast<GLTexture*>(src);
|
||||
GLTexture const* const d = handle_cast<GLTexture*>(dst);
|
||||
assert_invariant(s);
|
||||
assert_invariant(d);
|
||||
|
||||
ASSERT_PRECONDITION(
|
||||
d->width == s->width && d->height == s->height,
|
||||
"invalid resolve: src and dst sizes don't match");
|
||||
|
||||
ASSERT_PRECONDITION(s->samples > 1 && d->samples == 1,
|
||||
"invalid resolve: src.samples=%u, dst.samples=%u",
|
||||
+s->samples, +d->samples);
|
||||
|
||||
blit( dst, dstLevel, dstLayer, {},
|
||||
src, srcLevel, srcLayer, {},
|
||||
{ d->width, d->height });
|
||||
}
|
||||
|
||||
void OpenGLDriver::blit(
|
||||
Handle<HwTexture> dst, uint8_t srcLevel, uint8_t srcLayer, uint2 dstOrigin,
|
||||
Handle<HwTexture> src, uint8_t dstLevel, uint8_t dstLayer, uint2 srcOrigin,
|
||||
uint2 size) {
|
||||
DEBUG_MARKER()
|
||||
UTILS_UNUSED_IN_RELEASE auto& gl = mContext;
|
||||
assert_invariant(!gl.isES2());
|
||||
|
||||
#ifndef FILAMENT_SILENCE_NOT_SUPPORTED_BY_ES2
|
||||
|
||||
GLTexture* d = handle_cast<GLTexture*>(dst);
|
||||
GLTexture* s = handle_cast<GLTexture*>(src);
|
||||
assert_invariant(d);
|
||||
assert_invariant(s);
|
||||
|
||||
ASSERT_PRECONDITION_NON_FATAL(any(d->usage & TextureUsage::BLIT_DST),
|
||||
"texture doesn't have BLIT_DST");
|
||||
|
||||
ASSERT_PRECONDITION_NON_FATAL(any(s->usage & TextureUsage::BLIT_SRC),
|
||||
"texture doesn't have BLIT_SRC");
|
||||
|
||||
ASSERT_PRECONDITION_NON_FATAL(s->format == d->format,
|
||||
"src and dst texture format don't match");
|
||||
|
||||
enum class AttachmentType : GLenum {
|
||||
COLOR = GL_COLOR_ATTACHMENT0,
|
||||
DEPTH = GL_DEPTH_ATTACHMENT,
|
||||
STENCIL = GL_STENCIL_ATTACHMENT,
|
||||
DEPTH_STENCIL = GL_DEPTH_STENCIL_ATTACHMENT,
|
||||
};
|
||||
|
||||
auto getFormatType = [](TextureFormat format) -> AttachmentType {
|
||||
bool const depth = isDepthFormat(format);
|
||||
bool const stencil = isStencilFormat(format);
|
||||
if (depth && stencil) return AttachmentType::DEPTH_STENCIL;
|
||||
if (depth) return AttachmentType::DEPTH;
|
||||
if (stencil) return AttachmentType::STENCIL;
|
||||
return AttachmentType::COLOR;
|
||||
};
|
||||
|
||||
AttachmentType const type = getFormatType(d->format);
|
||||
assert_invariant(type == getFormatType(s->format));
|
||||
|
||||
// GL_INVALID_OPERATION is generated if mask contains any of the GL_DEPTH_BUFFER_BIT or
|
||||
// GL_STENCIL_BUFFER_BIT and filter is not GL_NEAREST.
|
||||
GLbitfield mask = {};
|
||||
switch (type) {
|
||||
case AttachmentType::COLOR:
|
||||
mask = GL_COLOR_BUFFER_BIT;
|
||||
break;
|
||||
case AttachmentType::DEPTH:
|
||||
mask = GL_DEPTH_BUFFER_BIT;
|
||||
break;
|
||||
case AttachmentType::STENCIL:
|
||||
mask = GL_STENCIL_BUFFER_BIT;
|
||||
break;
|
||||
case AttachmentType::DEPTH_STENCIL:
|
||||
mask = GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT;
|
||||
break;
|
||||
};
|
||||
|
||||
GLuint fbo[2] = {};
|
||||
glGenFramebuffers(2, fbo);
|
||||
|
||||
gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo[0]);
|
||||
switch (d->target) {
|
||||
case SamplerType::SAMPLER_2D:
|
||||
if (any(d->usage & TextureUsage::SAMPLEABLE)) {
|
||||
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GLenum(type),
|
||||
GL_TEXTURE_2D, d->gl.id, dstLevel);
|
||||
} else {
|
||||
glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GLenum(type),
|
||||
GL_RENDERBUFFER, d->gl.id);
|
||||
}
|
||||
break;
|
||||
case SamplerType::SAMPLER_CUBEMAP:
|
||||
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GLenum(type),
|
||||
GL_TEXTURE_CUBE_MAP_POSITIVE_X + dstLayer, d->gl.id, dstLevel);
|
||||
break;
|
||||
case SamplerType::SAMPLER_2D_ARRAY:
|
||||
case SamplerType::SAMPLER_CUBEMAP_ARRAY:
|
||||
case SamplerType::SAMPLER_3D:
|
||||
glFramebufferTextureLayer(GL_DRAW_FRAMEBUFFER, GLenum(type),
|
||||
d->gl.id, dstLevel, dstLayer);
|
||||
break;
|
||||
case SamplerType::SAMPLER_EXTERNAL:
|
||||
break;
|
||||
}
|
||||
CHECK_GL_FRAMEBUFFER_STATUS(utils::slog.e, GL_READ_FRAMEBUFFER)
|
||||
|
||||
gl.bindFramebuffer(GL_READ_FRAMEBUFFER, fbo[1]);
|
||||
switch (s->target) {
|
||||
case SamplerType::SAMPLER_2D:
|
||||
if (any(s->usage & TextureUsage::SAMPLEABLE)) {
|
||||
glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GLenum(type),
|
||||
GL_TEXTURE_2D, s->gl.id, srcLevel);
|
||||
} else {
|
||||
glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GLenum(type),
|
||||
GL_RENDERBUFFER, s->gl.id);
|
||||
}
|
||||
break;
|
||||
case SamplerType::SAMPLER_CUBEMAP:
|
||||
glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GLenum(type),
|
||||
GL_TEXTURE_CUBE_MAP_POSITIVE_X + srcLayer, s->gl.id, srcLevel);
|
||||
break;
|
||||
case SamplerType::SAMPLER_2D_ARRAY:
|
||||
case SamplerType::SAMPLER_CUBEMAP_ARRAY:
|
||||
case SamplerType::SAMPLER_3D:
|
||||
glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GLenum(type),
|
||||
s->gl.id, srcLevel, srcLayer);
|
||||
break;
|
||||
case SamplerType::SAMPLER_EXTERNAL:
|
||||
break;
|
||||
}
|
||||
CHECK_GL_FRAMEBUFFER_STATUS(utils::slog.e, GL_DRAW_FRAMEBUFFER)
|
||||
|
||||
gl.disable(GL_SCISSOR_TEST);
|
||||
glBlitFramebuffer(
|
||||
srcOrigin.x, srcOrigin.y, srcOrigin.x + size.x, srcOrigin.y + size.y,
|
||||
dstOrigin.x, dstOrigin.y, dstOrigin.x + size.x, dstOrigin.y + size.y,
|
||||
mask, GL_NEAREST);
|
||||
CHECK_GL_ERROR(utils::slog.e)
|
||||
|
||||
gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
|
||||
gl.bindFramebuffer(GL_READ_FRAMEBUFFER, 0);
|
||||
glDeleteFramebuffers(2, fbo);
|
||||
|
||||
if (any(d->usage & TextureUsage::SAMPLEABLE)) {
|
||||
// In a sense, blitting to a texture level is similar to calling setTextureData on it; in
|
||||
// both cases, we update the base/max LOD to give shaders access to levels as they become
|
||||
// available. Note that this can only expand the LOD range (never shrink it), and that
|
||||
// users can override this range by calling setMinMaxLevels().
|
||||
updateTextureLodRange(d, int8_t(dstLevel));
|
||||
}
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
void OpenGLDriver::blitDEPRECATED(TargetBufferFlags buffers,
|
||||
void OpenGLDriver::blit(TargetBufferFlags buffers,
|
||||
Handle<HwRenderTarget> dst, Viewport dstRect,
|
||||
Handle<HwRenderTarget> src, Viewport srcRect,
|
||||
SamplerMagFilter filter) {
|
||||
|
||||
// Note: blitDEPRECATED is only used by Renderer::copyFrame
|
||||
|
||||
DEBUG_MARKER()
|
||||
UTILS_UNUSED_IN_RELEASE auto& gl = mContext;
|
||||
assert_invariant(!gl.isES2());
|
||||
|
||||
ASSERT_PRECONDITION(buffers == TargetBufferFlags::COLOR0,
|
||||
"blitDEPRECATED only supports COLOR0");
|
||||
|
||||
ASSERT_PRECONDITION(srcRect.left >= 0 && srcRect.bottom >= 0 &&
|
||||
dstRect.left >= 0 && dstRect.bottom >= 0,
|
||||
"Source and destination rects must be positive.");
|
||||
|
||||
#ifndef FILAMENT_SILENCE_NOT_SUPPORTED_BY_ES2
|
||||
GLbitfield const mask = getAttachmentBitfield(buffers);
|
||||
if (mask) {
|
||||
GLenum glFilterMode = (filter == SamplerMagFilter::NEAREST) ? GL_NEAREST : GL_LINEAR;
|
||||
if (mask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)) {
|
||||
// GL_INVALID_OPERATION is generated if mask contains any of the GL_DEPTH_BUFFER_BIT or
|
||||
// GL_STENCIL_BUFFER_BIT and filter is not GL_NEAREST.
|
||||
glFilterMode = GL_NEAREST;
|
||||
}
|
||||
|
||||
GLenum const glFilterMode = (filter == SamplerMagFilter::NEAREST) ? GL_NEAREST : GL_LINEAR;
|
||||
// note: for msaa RenderTargets with non-msaa attachments, we copy from the msaa sidecar
|
||||
// buffer -- this should produce the same output that if we copied from the resolved
|
||||
// texture. EXT_multisampled_render_to_texture seems to allow both behaviours, and this
|
||||
// is an emulation of that. We cannot use the resolved texture easily because it's not
|
||||
// actually attached to the RenderTarget. Another implementation would be to do a
|
||||
// reverse-resolve, but that wouldn't buy us anything.
|
||||
GLRenderTarget const* s = handle_cast<GLRenderTarget const*>(src);
|
||||
GLRenderTarget const* d = handle_cast<GLRenderTarget const*>(dst);
|
||||
|
||||
// note: for msaa RenderTargets with non-msaa attachments, we copy from the msaa sidecar
|
||||
// buffer -- this should produce the same output that if we copied from the resolved
|
||||
// texture. EXT_multisampled_render_to_texture seems to allow both behaviours, and this
|
||||
// is an emulation of that. We cannot use the resolved texture easily because it's not
|
||||
// actually attached to the RenderTarget. Another implementation would be to do a
|
||||
// reverse-resolve, but that wouldn't buy us anything.
|
||||
GLRenderTarget const* s = handle_cast<GLRenderTarget const*>(src);
|
||||
GLRenderTarget const* d = handle_cast<GLRenderTarget const*>(dst);
|
||||
// blit operations are only supported from RenderTargets that have only COLOR0 (or
|
||||
// no color buffer at all)
|
||||
assert_invariant(
|
||||
!(s->targets & (TargetBufferFlags::COLOR_ALL & ~TargetBufferFlags::COLOR0)));
|
||||
|
||||
// With GLES 3.x, GL_INVALID_OPERATION is generated if the value of GL_SAMPLE_BUFFERS
|
||||
// for the draw buffer is greater than zero. This works with OpenGL, so we want to
|
||||
// make sure to catch this scenario.
|
||||
assert_invariant(d->gl.samples <= 1);
|
||||
assert_invariant(
|
||||
!(d->targets & (TargetBufferFlags::COLOR_ALL & ~TargetBufferFlags::COLOR0)));
|
||||
|
||||
// GL_INVALID_OPERATION is generated if GL_SAMPLE_BUFFERS for the read buffer is greater
|
||||
// than zero and the formats of draw and read buffers are not identical.
|
||||
// However, it's not well-defined in the spec what "format" means. So it's difficult
|
||||
// to have an assert here -- especially when dealing with the default framebuffer
|
||||
// With GLES 3.x, GL_INVALID_OPERATION is generated if the value of GL_SAMPLE_BUFFERS
|
||||
// for the draw buffer is greater than zero. This works with OpenGL, so we want to
|
||||
// make sure to catch this scenario.
|
||||
assert_invariant(d->gl.samples <= 1);
|
||||
|
||||
// GL_INVALID_OPERATION is generated if GL_SAMPLE_BUFFERS for the read buffer is greater
|
||||
// than zero and (...) the source and destination rectangles are not defined with the
|
||||
// same (X0, Y0) and (X1, Y1) bounds.
|
||||
// GL_INVALID_OPERATION is generated if GL_SAMPLE_BUFFERS for the read buffer is greater
|
||||
// than zero and the formats of draw and read buffers are not identical.
|
||||
// However, it's not well-defined in the spec what "format" means. So it's difficult
|
||||
// to have an assert here -- especially when dealing with the default framebuffer
|
||||
|
||||
// Additionally, the EXT_multisampled_render_to_texture extension doesn't specify what
|
||||
// happens when blitting from an "implicit" resolve render target (does it work?), so
|
||||
// to ere on the safe side, we don't allow it.
|
||||
if (s->gl.samples > 1) {
|
||||
assert_invariant(!memcmp(&dstRect, &srcRect, sizeof(srcRect)));
|
||||
// GL_INVALID_OPERATION is generated if GL_SAMPLE_BUFFERS for the read buffer is greater
|
||||
// than zero and (...) the source and destination rectangles are not defined with the
|
||||
// same (X0, Y0) and (X1, Y1) bounds.
|
||||
|
||||
// Additionally, the EXT_multisampled_render_to_texture extension doesn't specify what
|
||||
// happens when blitting from an "implicit" resolve render target (does it work?), so
|
||||
// to ere on the safe side, we don't allow it.
|
||||
if (s->gl.samples > 1) {
|
||||
assert_invariant(!memcmp(&dstRect, &srcRect, sizeof(srcRect)));
|
||||
}
|
||||
|
||||
gl.bindFramebuffer(GL_READ_FRAMEBUFFER, s->gl.fbo);
|
||||
gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, d->gl.fbo);
|
||||
|
||||
CHECK_GL_FRAMEBUFFER_STATUS(utils::slog.e, GL_READ_FRAMEBUFFER)
|
||||
CHECK_GL_FRAMEBUFFER_STATUS(utils::slog.e, GL_DRAW_FRAMEBUFFER)
|
||||
|
||||
gl.disable(GL_SCISSOR_TEST);
|
||||
glBlitFramebuffer(
|
||||
srcRect.left, srcRect.bottom, srcRect.right(), srcRect.top(),
|
||||
dstRect.left, dstRect.bottom, dstRect.right(), dstRect.top(),
|
||||
mask, glFilterMode);
|
||||
CHECK_GL_ERROR(utils::slog.e)
|
||||
}
|
||||
|
||||
gl.bindFramebuffer(GL_READ_FRAMEBUFFER, s->gl.fbo);
|
||||
gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, d->gl.fbo);
|
||||
|
||||
CHECK_GL_FRAMEBUFFER_STATUS(utils::slog.e, GL_READ_FRAMEBUFFER)
|
||||
CHECK_GL_FRAMEBUFFER_STATUS(utils::slog.e, GL_DRAW_FRAMEBUFFER)
|
||||
|
||||
gl.disable(GL_SCISSOR_TEST);
|
||||
glBlitFramebuffer(
|
||||
srcRect.left, srcRect.bottom, srcRect.right(), srcRect.top(),
|
||||
dstRect.left, dstRect.bottom, dstRect.right(), dstRect.top(),
|
||||
GL_COLOR_BUFFER_BIT, glFilterMode);
|
||||
CHECK_GL_ERROR(utils::slog.e)
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -3687,17 +3518,18 @@ void OpenGLDriver::draw(PipelineState state, Handle<HwRenderPrimitive> rph, uint
|
||||
DEBUG_MARKER()
|
||||
auto& gl = mContext;
|
||||
|
||||
OpenGLProgram* const p = handle_cast<OpenGLProgram*>(state.program);
|
||||
OpenGLProgram* p = handle_cast<OpenGLProgram*>(state.program);
|
||||
|
||||
bool const success = useProgram(p);
|
||||
if (UTILS_UNLIKELY(!success)) {
|
||||
// Avoid fatal (or cascading) errors that can occur during the draw call when the program
|
||||
// is invalid. The shader compile error has already been dumped to the console at this
|
||||
// point, so it's fine to simply return early.
|
||||
// If the material debugger is enabled, avoid fatal (or cascading) errors and that can occur
|
||||
// during the draw call when the program is invalid. The shader compile error has already been
|
||||
// dumped to the console at this point, so it's fine to simply return early.
|
||||
if (FILAMENT_ENABLE_MATDBG && UTILS_UNLIKELY(!p->isValid())) {
|
||||
return;
|
||||
}
|
||||
|
||||
GLRenderPrimitive* const rp = handle_cast<GLRenderPrimitive*>(rph);
|
||||
useProgram(p);
|
||||
|
||||
GLRenderPrimitive* rp = handle_cast<GLRenderPrimitive *>(rph);
|
||||
|
||||
// Gracefully do nothing if the render primitive has not been set up.
|
||||
VertexBufferHandle vb = rp->gl.vertexBufferWithObjects;
|
||||
@@ -3708,7 +3540,7 @@ void OpenGLDriver::draw(PipelineState state, Handle<HwRenderPrimitive> rph, uint
|
||||
gl.bindVertexArray(&rp->gl);
|
||||
|
||||
// If necessary, mutate the bindings in the VAO.
|
||||
GLVertexBuffer const* const glvb = handle_cast<GLVertexBuffer*>(vb);
|
||||
const GLVertexBuffer* glvb = handle_cast<GLVertexBuffer*>(vb);
|
||||
if (UTILS_UNLIKELY(rp->gl.vertexBufferVersion != glvb->bufferObjectsVersion)) {
|
||||
updateVertexArrayObject(rp, glvb);
|
||||
}
|
||||
@@ -3742,16 +3574,17 @@ void OpenGLDriver::draw(PipelineState state, Handle<HwRenderPrimitive> rph, uint
|
||||
void OpenGLDriver::dispatchCompute(Handle<HwProgram> program, math::uint3 workGroupCount) {
|
||||
getShaderCompilerService().tick();
|
||||
|
||||
OpenGLProgram* const p = handle_cast<OpenGLProgram*>(program);
|
||||
OpenGLProgram* p = handle_cast<OpenGLProgram*>(program);
|
||||
|
||||
bool const success = useProgram(p);
|
||||
if (UTILS_UNLIKELY(!success)) {
|
||||
// Avoid fatal (or cascading) errors that can occur during the draw call when the program
|
||||
// is invalid. The shader compile error has already been dumped to the console at this
|
||||
// point, so it's fine to simply return early.
|
||||
// If the material debugger is enabled, avoid fatal (or cascading) errors and that can occur
|
||||
// during the draw call when the program is invalid. The shader compile error has already been
|
||||
// dumped to the console at this point, so it's fine to simply return early.
|
||||
if (FILAMENT_ENABLE_MATDBG && UTILS_UNLIKELY(!p->isValid())) {
|
||||
return;
|
||||
}
|
||||
|
||||
useProgram(p);
|
||||
|
||||
#if defined(BACKEND_OPENGL_LEVEL_GLES31)
|
||||
|
||||
#if defined(__ANDROID__)
|
||||
|
||||
@@ -83,9 +83,11 @@ public:
|
||||
}
|
||||
|
||||
struct {
|
||||
GLuint id;
|
||||
union {
|
||||
GLenum binding;
|
||||
struct {
|
||||
GLuint id;
|
||||
GLenum binding;
|
||||
};
|
||||
void* buffer;
|
||||
};
|
||||
} gl;
|
||||
@@ -318,7 +320,7 @@ private:
|
||||
|
||||
void bindTexture(GLuint unit, GLTexture const* t) noexcept;
|
||||
void bindSampler(GLuint unit, GLuint sampler) noexcept;
|
||||
inline bool useProgram(OpenGLProgram* p) noexcept;
|
||||
inline void useProgram(OpenGLProgram* p) noexcept;
|
||||
|
||||
enum class ResolveAction { LOAD, STORE };
|
||||
void resolvePass(ResolveAction action, GLRenderTarget const* rt,
|
||||
@@ -361,8 +363,7 @@ private:
|
||||
void setScissor(Viewport const& scissor) noexcept;
|
||||
|
||||
// ES2 only. Uniform buffer emulation binding points
|
||||
GLuint mLastAssignedEmulatedUboId = 0;
|
||||
std::array<std::tuple<GLuint, void const*, uint16_t>, Program::UNIFORM_BINDING_COUNT> mUniformBindings = {};
|
||||
std::array<std::pair<void const*, uint16_t>, Program::UNIFORM_BINDING_COUNT> mUniformBindings = {};
|
||||
|
||||
// sampler buffer binding points (nullptr if not used)
|
||||
std::array<GLSamplerGroup*, Program::SAMPLER_BINDING_COUNT> mSamplerBindings = {}; // 4 pointers
|
||||
|
||||
@@ -129,7 +129,7 @@ void OpenGLProgram::initializeProgramState(OpenGLContext& context, GLuint progra
|
||||
#endif
|
||||
{
|
||||
// ES2 initialization of (fake) UBOs
|
||||
UniformsRecord* const uniformsRecords = new(std::nothrow) UniformsRecord[Program::UNIFORM_BINDING_COUNT];
|
||||
UniformsRecord* const uniformsRecords = new UniformsRecord[Program::UNIFORM_BINDING_COUNT];
|
||||
UTILS_NOUNROLL
|
||||
for (GLuint binding = 0, n = Program::UNIFORM_BINDING_COUNT; binding < n; binding++) {
|
||||
Program::UniformInfo& uniforms = lazyInitializationData.bindingUniformInfo[binding];
|
||||
@@ -229,16 +229,15 @@ void OpenGLProgram::updateSamplers(OpenGLDriver* const gld) const noexcept {
|
||||
CHECK_GL_ERROR(utils::slog.e)
|
||||
}
|
||||
|
||||
void OpenGLProgram::updateUniforms(uint32_t index, GLuint id, void const* buffer, uint16_t age) noexcept {
|
||||
void OpenGLProgram::updateUniforms(uint32_t index, void const* buffer, uint16_t age) noexcept {
|
||||
assert_invariant(mUniformsRecords);
|
||||
assert_invariant(buffer);
|
||||
|
||||
// only update the uniforms if the UBO has changed since last time we updated
|
||||
UniformsRecord const& records = mUniformsRecords[index];
|
||||
if (records.id == id && records.age == age) {
|
||||
if (records.age == age) {
|
||||
return;
|
||||
}
|
||||
records.id = id;
|
||||
records.age = age;
|
||||
|
||||
assert_invariant(records.uniforms.size() == records.locations.size());
|
||||
|
||||
@@ -59,7 +59,7 @@ public:
|
||||
// - the content of any bound sampler buffer has changed
|
||||
// ... since last time we used this program
|
||||
|
||||
// Turns out the former might be relatively cheap to check, the latter requires
|
||||
// turns out the former might be relatively cheap to check, the later requires
|
||||
// a bit less. Compared to what updateSamplers() actually does, which is
|
||||
// pretty little, I'm not sure if we'll get ahead.
|
||||
|
||||
@@ -72,7 +72,7 @@ public:
|
||||
} gl; // 12 bytes
|
||||
|
||||
// For ES2 only
|
||||
void updateUniforms(uint32_t index, GLuint id, void const* buffer, uint16_t age) noexcept;
|
||||
void updateUniforms(uint32_t index, void const* buffer, uint16_t age) noexcept;
|
||||
void setRec709ColorSpace(bool rec709) const noexcept;
|
||||
|
||||
private:
|
||||
@@ -98,7 +98,6 @@ private:
|
||||
struct UniformsRecord {
|
||||
Program::UniformInfo uniforms;
|
||||
LocationInfo locations;
|
||||
mutable GLuint id = 0;
|
||||
mutable uint16_t age = std::numeric_limits<uint16_t>::max();
|
||||
};
|
||||
UniformsRecord const* mUniformsRecords = nullptr;
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
|
||||
#include <private/backend/BackendUtils.h>
|
||||
|
||||
#include <backend/platforms/OpenGLPlatform.h>
|
||||
#include <backend/Program.h>
|
||||
|
||||
#include <utils/compiler.h>
|
||||
@@ -140,37 +141,20 @@ void* ShaderCompilerService::getUserData(const program_token_t& token) noexcept
|
||||
ShaderCompilerService::ShaderCompilerService(OpenGLDriver& driver)
|
||||
: mDriver(driver),
|
||||
mBlobCache(driver.getContext()),
|
||||
mCallbackManager(driver) {
|
||||
mCallbackManager(driver),
|
||||
KHR_parallel_shader_compile(driver.getContext().ext.KHR_parallel_shader_compile) {
|
||||
}
|
||||
|
||||
ShaderCompilerService::~ShaderCompilerService() noexcept = default;
|
||||
|
||||
bool ShaderCompilerService::isParallelShaderCompileSupported() const noexcept {
|
||||
assert_invariant(mMode != Mode::UNDEFINED);
|
||||
return mMode != Mode::SYNCHRONOUS;
|
||||
return KHR_parallel_shader_compile || mShaderCompilerThreadCount;
|
||||
}
|
||||
|
||||
void ShaderCompilerService::init() noexcept {
|
||||
// Here we decide which mode we'll be using. We always prefer our own thread-pool if
|
||||
// that mode is available because, we have no control on how the compilation queues are
|
||||
// handled if done by the driver (so at the very least we'd need to decode this per-driver).
|
||||
// In theory, using Mode::ASYNCHRONOUS (a.k.a. KHR_parallel_shader_compile) could be more
|
||||
// efficient, since it doesn't require shared contexts.
|
||||
// In practice, we already know that with ANGLE, Mode::ASYNCHRONOUS can cause very long
|
||||
// pauses at glDraw() time in the situation where glLinkProgram() has been emitted, but has
|
||||
// other programs ahead of it in ANGLE's queue.
|
||||
if (mDriver.mPlatform.isExtraContextSupported()) {
|
||||
// our thread-pool if possible
|
||||
mMode = Mode::THREAD_POOL;
|
||||
} else if (mDriver.getContext().ext.KHR_parallel_shader_compile) {
|
||||
// if not, async shader compilation and link if the driver supports it
|
||||
mMode = Mode::ASYNCHRONOUS;
|
||||
} else {
|
||||
// fallback to synchronous shader compilation
|
||||
mMode = Mode::SYNCHRONOUS;
|
||||
}
|
||||
|
||||
if (mMode == Mode::THREAD_POOL) {
|
||||
// If we have KHR_parallel_shader_compile, we always use it, it should be more resource
|
||||
// friendly.
|
||||
if (!KHR_parallel_shader_compile) {
|
||||
// - on Adreno there is a single compiler object. We can't use a pool > 1
|
||||
// also glProgramBinary blocks if other threads are compiling.
|
||||
// - on Mali shader compilation can be multi-threaded, but program linking happens on
|
||||
@@ -180,42 +164,37 @@ void ShaderCompilerService::init() noexcept {
|
||||
// - on macOS (M1 MacBook Pro/Ventura) there is global lock around all GL APIs when using
|
||||
// a shared context, so parallel shader compilation yields no benefit.
|
||||
// - on windows/linux we could use more threads, tbd.
|
||||
if (mDriver.mPlatform.isExtraContextSupported()) {
|
||||
// By default, we use one thread at the same priority as the gl thread. This is the
|
||||
// safest choice that avoids priority inversions.
|
||||
uint32_t poolSize = 1;
|
||||
JobSystem::Priority priority = JobSystem::Priority::DISPLAY;
|
||||
|
||||
// By default, we use one thread at the same priority as the gl thread. This is the
|
||||
// safest choice that avoids priority inversions.
|
||||
uint32_t poolSize = 1;
|
||||
JobSystem::Priority priority = JobSystem::Priority::DISPLAY;
|
||||
auto const& renderer = mDriver.getContext().state.renderer;
|
||||
if (UTILS_UNLIKELY(strstr(renderer, "PowerVR"))) {
|
||||
// The PowerVR driver support parallel shader compilation well, so we use 2
|
||||
// threads, we can use lower priority threads here because urgent compilations
|
||||
// will most likely happen on the main gl thread. Using too many thread can
|
||||
// increase memory pressure significantly.
|
||||
poolSize = 2;
|
||||
priority = JobSystem::Priority::BACKGROUND;
|
||||
}
|
||||
|
||||
auto const& renderer = mDriver.getContext().state.renderer;
|
||||
// Some drivers support parallel shader compilation well, so we use N
|
||||
// threads, we can use lower priority threads here because urgent compilations
|
||||
// will most likely happen on the main gl thread. Using too many thread can
|
||||
// increase memory pressure significantly.
|
||||
if (UTILS_UNLIKELY(strstr(renderer, "PowerVR"))) {
|
||||
// For PowerVR, it's unclear what the cost of extra shared contexts is, so we only
|
||||
// use 2 to be safe.
|
||||
poolSize = 2;
|
||||
priority = JobSystem::Priority::BACKGROUND;
|
||||
} else if (UTILS_UNLIKELY(strstr(renderer, "ANGLE"))) {
|
||||
// Angle shared contexts are not expensive once we have two.
|
||||
poolSize = (std::thread::hardware_concurrency() + 1) / 2;
|
||||
priority = JobSystem::Priority::BACKGROUND;
|
||||
mShaderCompilerThreadCount = poolSize;
|
||||
mCompilerThreadPool.init(mShaderCompilerThreadCount,
|
||||
[&platform = mDriver.mPlatform, priority]() {
|
||||
// give the thread a name
|
||||
JobSystem::setThreadName("CompilerThreadPool");
|
||||
// run at a slightly lower priority than other filament threads
|
||||
JobSystem::setThreadPriority(priority);
|
||||
// create a gl context current to this thread
|
||||
platform.createContext(true);
|
||||
},
|
||||
[&platform = mDriver.mPlatform]() {
|
||||
// release context and thread state
|
||||
platform.releaseContext();
|
||||
});
|
||||
}
|
||||
|
||||
mShaderCompilerThreadCount = poolSize;
|
||||
mCompilerThreadPool.init(mShaderCompilerThreadCount,
|
||||
[&platform = mDriver.mPlatform, priority]() {
|
||||
// give the thread a name
|
||||
JobSystem::setThreadName("CompilerThreadPool");
|
||||
// run at a slightly lower priority than other filament threads
|
||||
JobSystem::setThreadPriority(priority);
|
||||
// create a gl context current to this thread
|
||||
platform.createContext(true);
|
||||
},
|
||||
[&platform = mDriver.mPlatform]() {
|
||||
// release context and thread state
|
||||
platform.releaseContext();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,7 +228,7 @@ ShaderCompilerService::program_token_t ShaderCompilerService::createProgram(
|
||||
token->handle = mCallbackManager.get();
|
||||
|
||||
CompilerPriorityQueue const priorityQueue = program.getPriorityQueue();
|
||||
if (mMode == Mode::THREAD_POOL) {
|
||||
if (mShaderCompilerThreadCount) {
|
||||
// queue a compile job
|
||||
mCompilerThreadPool.queue(priorityQueue, token,
|
||||
[this, &gl, program = std::move(program), token]() mutable {
|
||||
@@ -275,6 +254,8 @@ ShaderCompilerService::program_token_t ShaderCompilerService::createProgram(
|
||||
glGetProgramiv(glProgram, GL_LINK_STATUS, &status);
|
||||
programData.program = glProgram;
|
||||
|
||||
token->gl.program = programData.program;
|
||||
|
||||
// we don't need to check for success here, it'll be done on the
|
||||
// main thread side.
|
||||
token->set(programData);
|
||||
@@ -298,8 +279,7 @@ ShaderCompilerService::program_token_t ShaderCompilerService::createProgram(
|
||||
token->shaderSourceCode);
|
||||
|
||||
runAtNextTick(priorityQueue, token, [this, token](Job const&) {
|
||||
assert_invariant(mMode != Mode::THREAD_POOL);
|
||||
if (mMode == Mode::ASYNCHRONOUS) {
|
||||
if (KHR_parallel_shader_compile) {
|
||||
// don't attempt to link this program if all shaders are not done compiling
|
||||
GLint status;
|
||||
if (token->gl.program) {
|
||||
@@ -323,7 +303,7 @@ ShaderCompilerService::program_token_t ShaderCompilerService::createProgram(
|
||||
// link the program, this also cannot fail because status is checked later.
|
||||
token->gl.program = linkProgram(mDriver.getContext(),
|
||||
token->gl.shaders, token->attributes);
|
||||
if (mMode == Mode::ASYNCHRONOUS) {
|
||||
if (KHR_parallel_shader_compile) {
|
||||
// wait until the link finishes...
|
||||
return false;
|
||||
}
|
||||
@@ -357,14 +337,14 @@ GLuint ShaderCompilerService::getProgram(ShaderCompilerService::program_token_t&
|
||||
return program;
|
||||
}
|
||||
|
||||
void ShaderCompilerService::terminate(program_token_t& token) {
|
||||
/* static*/ void ShaderCompilerService::terminate(program_token_t& token) {
|
||||
assert_invariant(token);
|
||||
|
||||
token->canceled = true;
|
||||
|
||||
bool const canceled = token->compiler.cancelTickOp(token);
|
||||
bool canceled = token->compiler.cancelTickOp(token);
|
||||
|
||||
if (token->compiler.mMode == Mode::THREAD_POOL) {
|
||||
if (token->compiler.mShaderCompilerThreadCount) {
|
||||
auto job = token->compiler.mCompilerThreadPool.dequeue(token);
|
||||
if (!job) {
|
||||
// The job is being executed right now. We need to wait for it to finish to avoid a
|
||||
@@ -398,7 +378,7 @@ void ShaderCompilerService::terminate(program_token_t& token) {
|
||||
|
||||
void ShaderCompilerService::tick() {
|
||||
// we don't need to run executeTickOps() if we're using the thread-pool
|
||||
if (UTILS_UNLIKELY(mMode != Mode::THREAD_POOL)) {
|
||||
if (UTILS_UNLIKELY(!mShaderCompilerThreadCount)) {
|
||||
executeTickOps();
|
||||
}
|
||||
}
|
||||
@@ -423,7 +403,7 @@ void ShaderCompilerService::getProgramFromCompilerPool(program_token_t& token) n
|
||||
GLuint ShaderCompilerService::initialize(program_token_t& token) noexcept {
|
||||
SYSTRACE_CALL();
|
||||
if (!token->gl.program) {
|
||||
if (mMode == Mode::THREAD_POOL) {
|
||||
if (mShaderCompilerThreadCount) {
|
||||
// we need this program right now, remove it from the queue
|
||||
auto job = mCompilerThreadPool.dequeue(token);
|
||||
if (job) {
|
||||
@@ -439,7 +419,7 @@ GLuint ShaderCompilerService::initialize(program_token_t& token) noexcept {
|
||||
// Block until we get the program from the pool. Generally this wouldn't block
|
||||
// because we just compiled the program above, when executing job.
|
||||
ShaderCompilerService::getProgramFromCompilerPool(token);
|
||||
} else if (mMode == Mode::ASYNCHRONOUS) {
|
||||
} else if (KHR_parallel_shader_compile) {
|
||||
// we force the program link -- which might stall, either here or below in
|
||||
// checkProgramStatus(), but we don't have a choice, we need to use the program now.
|
||||
token->compiler.cancelTickOp(token);
|
||||
|
||||
@@ -95,42 +95,19 @@ public:
|
||||
CallbackHandler* handler, CallbackHandler::Callback callback, void* user);
|
||||
|
||||
private:
|
||||
struct Job {
|
||||
template<typename FUNC>
|
||||
Job(FUNC&& fn) : fn(std::forward<FUNC>(fn)) {}
|
||||
Job(std::function<bool(Job const& job)> fn,
|
||||
CallbackHandler* handler, void* user, CallbackHandler::Callback callback)
|
||||
: fn(std::move(fn)), handler(handler), user(user), callback(callback) {
|
||||
}
|
||||
std::function<bool(Job const& job)> fn;
|
||||
CallbackHandler* handler = nullptr;
|
||||
void* user = nullptr;
|
||||
CallbackHandler::Callback callback{};
|
||||
};
|
||||
|
||||
enum class Mode {
|
||||
UNDEFINED, // init() has not beed called yet.
|
||||
SYNCHRONOUS, // synchronous shader compilation
|
||||
THREAD_POOL, // asynchronous shader compilation using a thread-pool (most common)
|
||||
ASYNCHRONOUS // asynchronous shader compilation using KHR_parallel_shader_compile
|
||||
};
|
||||
|
||||
OpenGLDriver& mDriver;
|
||||
OpenGLBlobCache mBlobCache;
|
||||
CallbackManager mCallbackManager;
|
||||
CompilerThreadPool mCompilerThreadPool;
|
||||
|
||||
const bool KHR_parallel_shader_compile;
|
||||
uint32_t mShaderCompilerThreadCount = 0u;
|
||||
Mode mMode = Mode::UNDEFINED; // valid after init() is called
|
||||
|
||||
using ContainerType = std::tuple<CompilerPriorityQueue, program_token_t, Job>;
|
||||
std::vector<ContainerType> mRunAtNextTickOps;
|
||||
|
||||
GLuint initialize(ShaderCompilerService::program_token_t& token) noexcept;
|
||||
|
||||
static void getProgramFromCompilerPool(program_token_t& token) noexcept;
|
||||
|
||||
static void compileShaders(
|
||||
static void compileShaders(
|
||||
OpenGLContext& context,
|
||||
Program::ShaderSource shadersSource,
|
||||
utils::FixedCapacityVector<Program::SpecializationConstant> const& specializationConstants,
|
||||
@@ -150,11 +127,27 @@ private:
|
||||
|
||||
static bool checkProgramStatus(program_token_t const& token) noexcept;
|
||||
|
||||
struct Job {
|
||||
template<typename FUNC>
|
||||
Job(FUNC&& fn) : fn(std::forward<FUNC>(fn)) {}
|
||||
Job(std::function<bool(Job const& job)> fn,
|
||||
CallbackHandler* handler, void* user, CallbackHandler::Callback callback)
|
||||
: fn(std::move(fn)), handler(handler), user(user), callback(callback) {
|
||||
}
|
||||
std::function<bool(Job const& job)> fn;
|
||||
CallbackHandler* handler = nullptr;
|
||||
void* user = nullptr;
|
||||
CallbackHandler::Callback callback{};
|
||||
};
|
||||
|
||||
void runAtNextTick(CompilerPriorityQueue priority,
|
||||
const program_token_t& token, Job job) noexcept;
|
||||
void executeTickOps() noexcept;
|
||||
bool cancelTickOp(program_token_t token) noexcept;
|
||||
// order of insertion is important
|
||||
|
||||
using ContainerType = std::tuple<CompilerPriorityQueue, program_token_t, Job>;
|
||||
std::vector<ContainerType> mRunAtNextTickOps;
|
||||
};
|
||||
|
||||
} // namespace filament::backend
|
||||
|
||||
@@ -190,10 +190,8 @@ using namespace glext;
|
||||
|
||||
#if defined(GL_EXT_clip_cull_distance)
|
||||
# define GL_CLIP_DISTANCE0 GL_CLIP_DISTANCE0_EXT
|
||||
# define GL_CLIP_DISTANCE1 GL_CLIP_DISTANCE1_EXT
|
||||
#else
|
||||
# define GL_CLIP_DISTANCE0 0x3000
|
||||
# define GL_CLIP_DISTANCE1 0x3001
|
||||
#endif
|
||||
|
||||
#if defined(GL_KHR_debug)
|
||||
|
||||
@@ -293,6 +293,20 @@ io::ostream& operator<<(io::ostream& out, TextureFormat format) {
|
||||
return out;
|
||||
}
|
||||
|
||||
io::ostream& operator<<(io::ostream& out, TextureUsage usage) {
|
||||
switch (usage) {
|
||||
CASE(TextureUsage, NONE)
|
||||
CASE(TextureUsage, DEFAULT)
|
||||
CASE(TextureUsage, COLOR_ATTACHMENT)
|
||||
CASE(TextureUsage, DEPTH_ATTACHMENT)
|
||||
CASE(TextureUsage, STENCIL_ATTACHMENT)
|
||||
CASE(TextureUsage, UPLOADABLE)
|
||||
CASE(TextureUsage, SAMPLEABLE)
|
||||
CASE(TextureUsage, SUBPASS_INPUT)
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
io::ostream& operator<<(io::ostream& out, TextureCubemapFace face) {
|
||||
switch (face) {
|
||||
CASE(TextureCubemapFace, NEGATIVE_X)
|
||||
|
||||
@@ -38,68 +38,22 @@ using ImgUtil = VulkanImageUtility;
|
||||
namespace {
|
||||
|
||||
inline void blitFast(const VkCommandBuffer cmdbuffer, VkImageAspectFlags aspect, VkFilter filter,
|
||||
VulkanAttachment src, VulkanAttachment dst,
|
||||
const VkExtent2D srcExtent, VulkanAttachment src, VulkanAttachment dst,
|
||||
const VkOffset3D srcRect[2], const VkOffset3D dstRect[2]) {
|
||||
|
||||
if constexpr (FVK_ENABLED(FVK_DEBUG_BLITTER)) {
|
||||
utils::slog.d << "Fast blit from=" << src.texture->getVkImage() << ",level=" << (int) src.level
|
||||
<< " layout=" << src.getLayout()
|
||||
<< " to=" << dst.texture->getVkImage() << ",level=" << (int) dst.level
|
||||
<< " layout=" << dst.getLayout() << utils::io::endl;
|
||||
}
|
||||
|
||||
const VkImageSubresourceRange srcRange = {
|
||||
.aspectMask = aspect,
|
||||
.baseMipLevel = src.level,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = src.layer,
|
||||
.layerCount = 1,
|
||||
};
|
||||
|
||||
const VkImageSubresourceRange dstRange = {
|
||||
.aspectMask = aspect,
|
||||
.baseMipLevel = dst.level,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = dst.layer,
|
||||
.layerCount = 1,
|
||||
};
|
||||
|
||||
VulkanLayout oldSrcLayout = src.getLayout();
|
||||
VulkanLayout oldDstLayout = dst.getLayout();
|
||||
|
||||
src.texture->transitionLayout(cmdbuffer, srcRange, VulkanLayout::TRANSFER_SRC);
|
||||
dst.texture->transitionLayout(cmdbuffer, dstRange, VulkanLayout::TRANSFER_DST);
|
||||
|
||||
const VkImageBlit blitRegions[1] = {{
|
||||
.srcSubresource = { aspect, src.level, src.layer, 1 },
|
||||
.srcOffsets = { srcRect[0], srcRect[1] },
|
||||
.dstSubresource = { aspect, dst.level, dst.layer, 1 },
|
||||
.dstOffsets = { dstRect[0], dstRect[1] },
|
||||
}};
|
||||
vkCmdBlitImage(cmdbuffer,
|
||||
src.getImage(), ImgUtil::getVkLayout(VulkanLayout::TRANSFER_SRC),
|
||||
dst.getImage(), ImgUtil::getVkLayout(VulkanLayout::TRANSFER_DST),
|
||||
1, blitRegions, filter);
|
||||
.srcSubresource = {aspect, src.level, src.layer, 1},
|
||||
.srcOffsets = {srcRect[0], srcRect[1]},
|
||||
.dstSubresource = {aspect, dst.level, dst.layer, 1},
|
||||
.dstOffsets = {dstRect[0], dstRect[1]},
|
||||
}};
|
||||
|
||||
if (oldSrcLayout == VulkanLayout::UNDEFINED) {
|
||||
oldSrcLayout = ImgUtil::getDefaultLayout(src.texture->usage);
|
||||
}
|
||||
if (oldDstLayout == VulkanLayout::UNDEFINED) {
|
||||
oldDstLayout = ImgUtil::getDefaultLayout(dst.texture->usage);
|
||||
}
|
||||
src.texture->transitionLayout(cmdbuffer, srcRange, oldSrcLayout);
|
||||
dst.texture->transitionLayout(cmdbuffer, dstRange, oldDstLayout);
|
||||
}
|
||||
|
||||
inline void resolveFast(const VkCommandBuffer cmdbuffer, VkImageAspectFlags aspect,
|
||||
VulkanAttachment src, VulkanAttachment dst) {
|
||||
|
||||
if constexpr (FVK_ENABLED(FVK_DEBUG_BLITTER)) {
|
||||
utils::slog.d << "Fast blit from=" << src.texture->getVkImage() << ",level=" << (int) src.level
|
||||
<< " layout=" << src.getLayout()
|
||||
<< " to=" << dst.texture->getVkImage() << ",level=" << (int) dst.level
|
||||
<< " layout=" << dst.getLayout() << utils::io::endl;
|
||||
}
|
||||
const VkImageResolve resolveRegions[1] = {{
|
||||
.srcSubresource = {aspect, src.level, src.layer, 1},
|
||||
.srcOffset = srcRect[0],
|
||||
.dstSubresource = {aspect, dst.level, dst.layer, 1},
|
||||
.dstOffset = dstRect[0],
|
||||
.extent = {srcExtent.width, srcExtent.height, 1},
|
||||
}};
|
||||
|
||||
const VkImageSubresourceRange srcRange = {
|
||||
.aspectMask = aspect,
|
||||
@@ -117,25 +71,32 @@ inline void resolveFast(const VkCommandBuffer cmdbuffer, VkImageAspectFlags aspe
|
||||
.layerCount = 1,
|
||||
};
|
||||
|
||||
if constexpr (FVK_ENABLED(FVK_DEBUG_BLITTER)) {
|
||||
utils::slog.d << "Fast blit from=" << src.texture->getVkImage() << ",level=" << (int) src.level
|
||||
<< " layout=" << src.getLayout()
|
||||
<< " to=" << dst.texture->getVkImage() << ",level=" << (int) dst.level
|
||||
<< " layout=" << dst.getLayout() << utils::io::endl;
|
||||
}
|
||||
|
||||
VulkanLayout oldSrcLayout = src.getLayout();
|
||||
VulkanLayout oldDstLayout = dst.getLayout();
|
||||
|
||||
src.texture->transitionLayout(cmdbuffer, srcRange, VulkanLayout::TRANSFER_SRC);
|
||||
dst.texture->transitionLayout(cmdbuffer, dstRange, VulkanLayout::TRANSFER_DST);
|
||||
|
||||
assert_invariant(
|
||||
aspect != VK_IMAGE_ASPECT_DEPTH_BIT && "Resolve with depth is not yet supported.");
|
||||
const VkImageResolve resolveRegions[1] = {{
|
||||
.srcSubresource = { aspect, src.level, src.layer, 1 },
|
||||
.srcOffset = { 0, 0 },
|
||||
.dstSubresource = { aspect, dst.level, dst.layer, 1 },
|
||||
.dstOffset = { 0, 0 },
|
||||
.extent = { src.getExtent2D().width, src.getExtent2D().height, 1 },
|
||||
}};
|
||||
vkCmdResolveImage(cmdbuffer,
|
||||
src.getImage(), ImgUtil::getVkLayout(VulkanLayout::TRANSFER_SRC),
|
||||
dst.getImage(), ImgUtil::getVkLayout(VulkanLayout::TRANSFER_DST),
|
||||
1, resolveRegions);
|
||||
if (src.texture->samples > 1 && dst.texture->samples == 1) {
|
||||
assert_invariant(
|
||||
aspect != VK_IMAGE_ASPECT_DEPTH_BIT && "Resolve with depth is not yet supported.");
|
||||
vkCmdResolveImage(cmdbuffer,
|
||||
src.getImage(), ImgUtil::getVkLayout(VulkanLayout::TRANSFER_SRC),
|
||||
dst.getImage(), ImgUtil::getVkLayout(VulkanLayout::TRANSFER_DST),
|
||||
1, resolveRegions);
|
||||
} else {
|
||||
vkCmdBlitImage(cmdbuffer,
|
||||
src.getImage(), ImgUtil::getVkLayout(VulkanLayout::TRANSFER_SRC),
|
||||
dst.getImage(), ImgUtil::getVkLayout(VulkanLayout::TRANSFER_DST),
|
||||
1, blitRegions, filter);
|
||||
}
|
||||
|
||||
if (oldSrcLayout == VulkanLayout::UNDEFINED) {
|
||||
oldSrcLayout = ImgUtil::getDefaultLayout(src.texture->usage);
|
||||
@@ -168,45 +129,39 @@ void VulkanBlitter::initialize(VkPhysicalDevice physicalDevice, VkDevice device,
|
||||
mEmptyTexture = emptyTexture;
|
||||
}
|
||||
|
||||
void VulkanBlitter::resolve(VulkanAttachment dst, VulkanAttachment src) {
|
||||
|
||||
// src and dst should have the same aspect here
|
||||
VkImageAspectFlags const aspect = src.texture->getImageAspect();
|
||||
|
||||
if (aspect & VK_IMAGE_ASPECT_DEPTH_BIT &&
|
||||
src.texture->samples > 1 && dst.texture->samples == 1) {
|
||||
// we're resolving the depth here, which is not supported by the blitter in vulkan
|
||||
// I think, eventually we want to do that inside filament, instead.
|
||||
// FIXME: remove this once filament does it
|
||||
resolveSlowDepth(src, dst);
|
||||
return;
|
||||
}
|
||||
void VulkanBlitter::blitColor(BlitArgs args) {
|
||||
const VulkanAttachment src = args.srcTarget->getColor(args.targetIndex);
|
||||
const VulkanAttachment dst = args.dstTarget->getColor(0);
|
||||
const VkImageAspectFlags aspect = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
|
||||
#if FVK_ENABLED(FVK_DEBUG_BLIT_FORMAT)
|
||||
VkPhysicalDevice const gpu = mPhysicalDevice;
|
||||
VkFormatProperties info;
|
||||
vkGetPhysicalDeviceFormatProperties(gpu, src.getFormat(), &info);
|
||||
if (!ASSERT_POSTCONDITION_NON_FATAL(info.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT,
|
||||
"Depth src format is not blittable %d", src.getFormat())) {
|
||||
"Source format is not blittable %d", src.getFormat())) {
|
||||
return;
|
||||
}
|
||||
vkGetPhysicalDeviceFormatProperties(gpu, dst.getFormat(), &info);
|
||||
if (!ASSERT_POSTCONDITION_NON_FATAL(info.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_DST_BIT,
|
||||
"Depth dst format is not blittable %d", dst.getFormat())) {
|
||||
"Destination format is not blittable %d", dst.getFormat())) {
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
VulkanCommandBuffer& commands = mCommands->get();
|
||||
VkCommandBuffer const cmdbuffer = commands.buffer();
|
||||
commands.acquire(src.texture);
|
||||
commands.acquire(dst.texture);
|
||||
resolveFast(cmdbuffer, aspect, src, dst);
|
||||
|
||||
blitFast(cmdbuffer, aspect, args.filter, args.srcTarget->getExtent(), src, dst,
|
||||
args.srcRectPair, args.dstRectPair);
|
||||
}
|
||||
|
||||
void VulkanBlitter::blit(VkFilter filter,
|
||||
VulkanAttachment dst, const VkOffset3D* dstRectPair,
|
||||
VulkanAttachment src, const VkOffset3D* srcRectPair) {
|
||||
void VulkanBlitter::blitDepth(BlitArgs args) {
|
||||
const VulkanAttachment src = args.srcTarget->getDepth();
|
||||
const VulkanAttachment dst = args.dstTarget->getDepth();
|
||||
const VkImageAspectFlags aspect = VK_IMAGE_ASPECT_DEPTH_BIT;
|
||||
|
||||
#if FVK_ENABLED(FVK_DEBUG_BLIT_FORMAT)
|
||||
VkPhysicalDevice const gpu = mPhysicalDevice;
|
||||
VkFormatProperties info;
|
||||
@@ -221,13 +176,21 @@ void VulkanBlitter::blit(VkFilter filter,
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
// src and dst should have the same aspect here
|
||||
VkImageAspectFlags const aspect = src.texture->getImageAspect();
|
||||
|
||||
assert_invariant(src.texture && dst.texture);
|
||||
|
||||
if (src.texture->samples > 1 && dst.texture->samples == 1) {
|
||||
blitSlowDepth(args.filter, args.srcTarget->getExtent(), src, dst, args.srcRectPair,
|
||||
args.dstRectPair);
|
||||
return;
|
||||
}
|
||||
|
||||
VulkanCommandBuffer& commands = mCommands->get();
|
||||
VkCommandBuffer const cmdbuffer = commands.buffer();
|
||||
commands.acquire(src.texture);
|
||||
commands.acquire(dst.texture);
|
||||
blitFast(cmdbuffer, aspect, filter, src, dst, srcRectPair, dstRectPair);
|
||||
blitFast(cmdbuffer, aspect, args.filter, args.srcTarget->getExtent(), src, dst, args.srcRectPair,
|
||||
args.dstRectPair);
|
||||
}
|
||||
|
||||
void VulkanBlitter::terminate() noexcept {
|
||||
@@ -276,10 +239,10 @@ void VulkanBlitter::lazyInit() noexcept {
|
||||
VkShaderModule fragmentShader = decode(VKSHADERS_BLITDEPTHFS_DATA, VKSHADERS_BLITDEPTHFS_SIZE);
|
||||
|
||||
// Allocate one anonymous sampler at slot 0.
|
||||
VulkanProgram::CustomSamplerInfoList const samplers = {
|
||||
{ 0, 0, ShaderStageFlags::FRAGMENT },
|
||||
VulkanProgram::CustomSamplerInfoList samplers = {
|
||||
{0, 0, ShaderStageFlags::FRAGMENT},
|
||||
};
|
||||
mDepthResolveProgram = new(std::nothrow) VulkanProgram(mDevice, vertexShader, fragmentShader, samplers);
|
||||
mDepthResolveProgram = new VulkanProgram(mDevice, vertexShader, fragmentShader, samplers);
|
||||
|
||||
#if FVK_ENABLED(FVK_DEBUG_BLITTER)
|
||||
utils::slog.d << "Created Shader Module for VulkanBlitter "
|
||||
@@ -294,15 +257,15 @@ void VulkanBlitter::lazyInit() noexcept {
|
||||
+1.0f, +1.0f,
|
||||
};
|
||||
|
||||
VulkanCommandBuffer const& commands = mCommands->get();
|
||||
VulkanCommandBuffer& commands = mCommands->get();
|
||||
VkCommandBuffer const cmdbuffer = commands.buffer();
|
||||
|
||||
mTriangleBuffer = new(std::nothrow) VulkanBuffer(mAllocator, mStagePool, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
|
||||
mTriangleBuffer = new VulkanBuffer(mAllocator, mStagePool, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
|
||||
sizeof(kTriangleVertices));
|
||||
|
||||
mTriangleBuffer->loadFromCpu(cmdbuffer, kTriangleVertices, 0, sizeof(kTriangleVertices));
|
||||
|
||||
mParamsBuffer = new(std::nothrow) VulkanBuffer(mAllocator, mStagePool, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
|
||||
mParamsBuffer = new VulkanBuffer(mAllocator, mStagePool, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
|
||||
sizeof(BlitterUniforms));
|
||||
}
|
||||
|
||||
@@ -311,13 +274,10 @@ void VulkanBlitter::lazyInit() noexcept {
|
||||
// 2. Begin render pass
|
||||
// 3. Draw a big triangle
|
||||
// 4. End render pass.
|
||||
void VulkanBlitter::resolveSlowDepth(VulkanAttachment src, VulkanAttachment dst) {
|
||||
void VulkanBlitter::blitSlowDepth(VkFilter filter, const VkExtent2D srcExtent, VulkanAttachment src,
|
||||
VulkanAttachment dst, const VkOffset3D srcRect[2], const VkOffset3D dstRect[2]) {
|
||||
lazyInit();
|
||||
|
||||
const VkOffset3D dstRect[2] = {
|
||||
{ 0, 0, 0 },
|
||||
{ (int32_t)dst.texture->width, (int32_t)dst.texture->height, 1 }};
|
||||
|
||||
VulkanCommandBuffer* commands = &mCommands->get();
|
||||
VkCommandBuffer const cmdbuffer = commands->buffer();
|
||||
commands->acquire(src.texture);
|
||||
@@ -386,7 +346,7 @@ void VulkanBlitter::resolveSlowDepth(VulkanAttachment src, VulkanAttachment dst)
|
||||
|
||||
vkCmdBeginRenderPass(cmdbuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
|
||||
|
||||
VkViewport const viewport = {
|
||||
VkViewport viewport = {
|
||||
.x = (float) dstRect[0].x,
|
||||
.y = (float) dstRect[0].y,
|
||||
.width = (float) renderPassInfo.renderArea.extent.width,
|
||||
@@ -425,12 +385,12 @@ void VulkanBlitter::resolveSlowDepth(VulkanAttachment src, VulkanAttachment dst)
|
||||
VkBuffer buffers[1] = {};
|
||||
VkDeviceSize offsets[1] = {};
|
||||
buffers[0] = mTriangleBuffer->getGpuBuffer();
|
||||
VkVertexInputAttributeDescription const attribDesc = {
|
||||
VkVertexInputAttributeDescription attribDesc = {
|
||||
.location = 0,
|
||||
.binding = 0,
|
||||
.format = VK_FORMAT_R32G32_SFLOAT,
|
||||
};
|
||||
VkVertexInputBindingDescription const bufferDesc = {
|
||||
VkVertexInputBindingDescription bufferDesc = {
|
||||
.binding = 0,
|
||||
.stride = sizeof(float) * 2,
|
||||
};
|
||||
@@ -485,12 +445,12 @@ void VulkanBlitter::resolveSlowDepth(VulkanAttachment src, VulkanAttachment dst)
|
||||
|
||||
vkCmdEndRenderPass(cmdbuffer);
|
||||
|
||||
VkMemoryBarrier const barrier {
|
||||
VkMemoryBarrier barrier {
|
||||
.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER,
|
||||
.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
|
||||
.dstAccessMask = VK_ACCESS_SHADER_READ_BIT,
|
||||
};
|
||||
VkPipelineStageFlags const srcStageMask = VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
|
||||
VkPipelineStageFlags srcStageMask = VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
|
||||
vkCmdPipelineBarrier(cmdbuffer, srcStageMask,
|
||||
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT | // <== For Mali
|
||||
VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
|
||||
|
||||
@@ -38,18 +38,25 @@ public:
|
||||
void initialize(VkPhysicalDevice physicalDevice, VkDevice device, VmaAllocator allocator,
|
||||
VulkanCommands* commands, VulkanTexture* emptyTexture) noexcept;
|
||||
|
||||
void blit(VkFilter filter,
|
||||
VulkanAttachment dst, const VkOffset3D* dstRectPair,
|
||||
VulkanAttachment src, const VkOffset3D* srcRectPair);
|
||||
struct BlitArgs {
|
||||
const VulkanRenderTarget* dstTarget;
|
||||
const VkOffset3D* dstRectPair;
|
||||
const VulkanRenderTarget* srcTarget;
|
||||
const VkOffset3D* srcRectPair;
|
||||
VkFilter filter = VK_FILTER_NEAREST;
|
||||
int targetIndex = 0;
|
||||
};
|
||||
|
||||
void resolve(VulkanAttachment dst, VulkanAttachment src);
|
||||
void blitColor(BlitArgs args);
|
||||
void blitDepth(BlitArgs args);
|
||||
|
||||
void terminate() noexcept;
|
||||
|
||||
private:
|
||||
void lazyInit() noexcept;
|
||||
|
||||
void resolveSlowDepth(VulkanAttachment src, VulkanAttachment dst);
|
||||
void blitSlowDepth(VkFilter filter, const VkExtent2D srcExtent, VulkanAttachment src,
|
||||
VulkanAttachment dst, const VkOffset3D srcRect[2], const VkOffset3D dstRect[2]);
|
||||
|
||||
VulkanBuffer* mTriangleBuffer = nullptr;
|
||||
VulkanBuffer* mParamsBuffer = nullptr;
|
||||
|
||||
@@ -268,18 +268,13 @@ bool VulkanCommands::flush() {
|
||||
VK_NULL_HANDLE,
|
||||
VK_NULL_HANDLE,
|
||||
};
|
||||
uint32_t waitSemaphoreCount = 0;
|
||||
if (mSubmissionSignal) {
|
||||
signals[waitSemaphoreCount++] = mSubmissionSignal;
|
||||
}
|
||||
if (mInjectedSignal) {
|
||||
signals[waitSemaphoreCount++] = mInjectedSignal;
|
||||
}
|
||||
|
||||
VkCommandBuffer const cmdbuffer = currentbuf->buffer();
|
||||
|
||||
VkSubmitInfo submitInfo{
|
||||
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
|
||||
.waitSemaphoreCount = waitSemaphoreCount,
|
||||
.pWaitSemaphores = waitSemaphoreCount > 0 ? signals : nullptr,
|
||||
.waitSemaphoreCount = 0,
|
||||
.pWaitSemaphores = signals,
|
||||
.pWaitDstStageMask = waitDestStageMasks,
|
||||
.commandBufferCount = 1,
|
||||
.pCommandBuffers = &cmdbuffer,
|
||||
@@ -287,6 +282,19 @@ bool VulkanCommands::flush() {
|
||||
.pSignalSemaphores = &renderingFinished,
|
||||
};
|
||||
|
||||
if (mSubmissionSignal) {
|
||||
signals[submitInfo.waitSemaphoreCount++] = mSubmissionSignal;
|
||||
}
|
||||
|
||||
if (mInjectedSignal) {
|
||||
signals[submitInfo.waitSemaphoreCount++] = mInjectedSignal;
|
||||
}
|
||||
|
||||
// To address a validation warning.
|
||||
if (submitInfo.waitSemaphoreCount == 0) {
|
||||
submitInfo.pWaitSemaphores = VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
#if FVK_ENABLED(FVK_DEBUG_COMMAND_BUFFER)
|
||||
slog.i << "Submitting cmdbuffer=" << cmdbuffer
|
||||
<< " wait=(" << signals[0] << ", " << signals[1] << ") "
|
||||
|
||||
@@ -54,8 +54,7 @@ VmaAllocator createAllocator(VkInstance instance, VkPhysicalDevice physicalDevic
|
||||
VmaAllocator allocator;
|
||||
VmaVulkanFunctions const funcs {
|
||||
#if VMA_DYNAMIC_VULKAN_FUNCTIONS
|
||||
.vkGetInstanceProcAddr = vkGetInstanceProcAddr,
|
||||
.vkGetDeviceProcAddr = vkGetDeviceProcAddr,
|
||||
.vkGetInstanceProcAddr = vkGetInstanceProcAddr, .vkGetDeviceProcAddr = vkGetDeviceProcAddr,
|
||||
#else
|
||||
.vkGetPhysicalDeviceProperties = vkGetPhysicalDeviceProperties,
|
||||
.vkGetPhysicalDeviceMemoryProperties = vkGetPhysicalDeviceMemoryProperties,
|
||||
@@ -427,8 +426,7 @@ void VulkanDriver::destroyTexture(Handle<HwTexture> th) {
|
||||
}
|
||||
|
||||
void VulkanDriver::createProgramR(Handle<HwProgram> ph, Program&& program) {
|
||||
auto vkprogram
|
||||
= mResourceAllocator.construct<VulkanProgram>(ph, mPlatform->getDevice(), program);
|
||||
auto vkprogram = mResourceAllocator.construct<VulkanProgram>(ph, mPlatform->getDevice(), program);
|
||||
mResourceManager.acquire(vkprogram);
|
||||
}
|
||||
|
||||
@@ -955,43 +953,10 @@ void VulkanDriver::setExternalImagePlane(Handle<HwTexture> th, void* image, uint
|
||||
void VulkanDriver::setExternalStream(Handle<HwTexture> th, Handle<HwStream> sh) {
|
||||
}
|
||||
|
||||
void VulkanDriver::generateMipmaps(Handle<HwTexture> th) {
|
||||
auto* const t = mResourceAllocator.handle_cast<VulkanTexture*>(th);
|
||||
assert_invariant(t);
|
||||
void VulkanDriver::generateMipmaps(Handle<HwTexture> th) { }
|
||||
|
||||
int32_t layerCount = int32_t(t->depth);
|
||||
if (t->target == SamplerType::SAMPLER_CUBEMAP_ARRAY ||
|
||||
t->target == SamplerType::SAMPLER_CUBEMAP) {
|
||||
layerCount *= 6;
|
||||
}
|
||||
|
||||
// FIXME: the loop below can perform many layout transitions and back. We should be
|
||||
// able to optimize that.
|
||||
|
||||
uint8_t level = 0;
|
||||
int32_t srcw = int32_t(t->width);
|
||||
int32_t srch = int32_t(t->height);
|
||||
do {
|
||||
int32_t const dstw = std::max(srcw >> 1, 1);
|
||||
int32_t const dsth = std::max(srch >> 1, 1);
|
||||
const VkOffset3D srcOffsets[2] = {{ 0, 0, 0 }, { srcw, srch, 1 }};
|
||||
const VkOffset3D dstOffsets[2] = {{ 0, 0, 0 }, { dstw, dsth, 1 }};
|
||||
|
||||
// TODO: there should be a way to do this using layerCount in vkBlitImage
|
||||
// TODO: vkBlitImage should be able to handle 3D textures too
|
||||
for (int32_t layer = 0; layer < layerCount; layer++) {
|
||||
mBlitter.blit(VK_FILTER_LINEAR,
|
||||
{ .texture = t, .level = uint8_t(level + 1), .layer = (uint16_t)layer },
|
||||
dstOffsets,
|
||||
{ .texture = t, .level = uint8_t(level ), .layer = (uint16_t)layer },
|
||||
srcOffsets);
|
||||
}
|
||||
|
||||
level++;
|
||||
srcw = dstw;
|
||||
srch = dsth;
|
||||
} while ((srcw > 1 || srch > 1) && level < t->levels);
|
||||
t->setPrimaryRange(0, t->levels - 1);
|
||||
bool VulkanDriver::canGenerateMipmaps() {
|
||||
return false;
|
||||
}
|
||||
|
||||
void VulkanDriver::updateSamplerGroup(Handle<HwSamplerGroup> sbh,
|
||||
@@ -1472,132 +1437,50 @@ void VulkanDriver::readBufferSubData(backend::BufferObjectHandle boh,
|
||||
scheduleDestroy(std::move(p));
|
||||
}
|
||||
|
||||
void VulkanDriver::resolve(
|
||||
Handle<HwTexture> dst, uint8_t srcLevel, uint8_t srcLayer,
|
||||
Handle<HwTexture> src, uint8_t dstLevel, uint8_t dstLayer) {
|
||||
FVK_SYSTRACE_CONTEXT();
|
||||
FVK_SYSTRACE_START("resolve");
|
||||
|
||||
ASSERT_PRECONDITION(mCurrentRenderPass.renderPass == VK_NULL_HANDLE,
|
||||
"resolve() cannot be invoked inside a render pass.");
|
||||
|
||||
auto* const srcTexture = mResourceAllocator.handle_cast<VulkanTexture*>(src);
|
||||
auto* const dstTexture = mResourceAllocator.handle_cast<VulkanTexture*>(dst);
|
||||
assert_invariant(srcTexture);
|
||||
assert_invariant(dstTexture);
|
||||
|
||||
ASSERT_PRECONDITION(
|
||||
dstTexture->width == srcTexture->width && dstTexture->height == srcTexture->height,
|
||||
"invalid resolve: src and dst sizes don't match");
|
||||
|
||||
ASSERT_PRECONDITION(srcTexture->samples > 1 && dstTexture->samples == 1,
|
||||
"invalid resolve: src.samples=%u, dst.samples=%u",
|
||||
+srcTexture->samples, +dstTexture->samples);
|
||||
|
||||
ASSERT_PRECONDITION(srcTexture->format == dstTexture->format,
|
||||
"src and dst texture format don't match");
|
||||
|
||||
ASSERT_PRECONDITION(any(dstTexture->usage & TextureUsage::BLIT_DST),
|
||||
"texture doesn't have BLIT_DST");
|
||||
|
||||
ASSERT_PRECONDITION(any(srcTexture->usage & TextureUsage::BLIT_SRC),
|
||||
"texture doesn't have BLIT_SRC");
|
||||
|
||||
mBlitter.resolve(
|
||||
{ .texture = dstTexture, .level = dstLevel, .layer = dstLayer },
|
||||
{ .texture = srcTexture, .level = srcLevel, .layer = srcLayer });
|
||||
|
||||
FVK_SYSTRACE_END();
|
||||
}
|
||||
|
||||
void VulkanDriver::blit(
|
||||
Handle<HwTexture> dst, uint8_t srcLevel, uint8_t srcLayer, math::uint2 dstOrigin,
|
||||
Handle<HwTexture> src, uint8_t dstLevel, uint8_t dstLayer, math::uint2 srcOrigin,
|
||||
math::uint2 size) {
|
||||
void VulkanDriver::blit(TargetBufferFlags buffers, Handle<HwRenderTarget> dst, Viewport dstRect,
|
||||
Handle<HwRenderTarget> src, Viewport srcRect, SamplerMagFilter filter) {
|
||||
FVK_SYSTRACE_CONTEXT();
|
||||
FVK_SYSTRACE_START("blit");
|
||||
|
||||
ASSERT_PRECONDITION(mCurrentRenderPass.renderPass == VK_NULL_HANDLE,
|
||||
"blit() cannot be invoked inside a render pass.");
|
||||
assert_invariant(mCurrentRenderPass.renderPass == VK_NULL_HANDLE);
|
||||
|
||||
auto* const srcTexture = mResourceAllocator.handle_cast<VulkanTexture*>(src);
|
||||
auto* const dstTexture = mResourceAllocator.handle_cast<VulkanTexture*>(dst);
|
||||
// blit operation only support COLOR0 color buffer
|
||||
assert_invariant(
|
||||
!(buffers & (TargetBufferFlags::COLOR_ALL & ~TargetBufferFlags::COLOR0)));
|
||||
|
||||
ASSERT_PRECONDITION(any(dstTexture->usage & TextureUsage::BLIT_DST),
|
||||
"texture doesn't have BLIT_DST");
|
||||
|
||||
ASSERT_PRECONDITION(any(srcTexture->usage & TextureUsage::BLIT_SRC),
|
||||
"texture doesn't have BLIT_SRC");
|
||||
|
||||
ASSERT_PRECONDITION(srcTexture->format == dstTexture->format,
|
||||
"src and dst texture format don't match");
|
||||
|
||||
// The Y inversion below makes it so that Vk matches GL and Metal.
|
||||
|
||||
auto const srcLeft = int32_t(srcOrigin.x);
|
||||
auto const dstLeft = int32_t(dstOrigin.x);
|
||||
auto const srcTop = int32_t(srcTexture->height - (srcOrigin.y + size.y));
|
||||
auto const dstTop = int32_t(dstTexture->height - (dstOrigin.y + size.y));
|
||||
auto const srcRight = int32_t(srcOrigin.x + size.x);
|
||||
auto const dstRight = int32_t(dstOrigin.x + size.x);
|
||||
auto const srcBottom = int32_t(srcTop + size.y);
|
||||
auto const dstBottom = int32_t(dstTop + size.y);
|
||||
VkOffset3D const srcOffsets[2] = { { srcLeft, srcTop, 0 }, { srcRight, srcBottom, 1 }};
|
||||
VkOffset3D const dstOffsets[2] = { { dstLeft, dstTop, 0 }, { dstRight, dstBottom, 1 }};
|
||||
|
||||
// no scallng guaranteed
|
||||
mBlitter.blit(VK_FILTER_NEAREST,
|
||||
{ .texture = dstTexture, .level = dstLevel, .layer = dstLayer }, dstOffsets,
|
||||
{ .texture = srcTexture, .level = srcLevel, .layer = srcLayer }, srcOffsets);
|
||||
|
||||
FVK_SYSTRACE_END();
|
||||
}
|
||||
|
||||
void VulkanDriver::blitDEPRECATED(TargetBufferFlags buffers,
|
||||
Handle<HwRenderTarget> dst, Viewport dstRect,
|
||||
Handle<HwRenderTarget> src, Viewport srcRect,
|
||||
SamplerMagFilter filter) {
|
||||
FVK_SYSTRACE_CONTEXT();
|
||||
FVK_SYSTRACE_START("blitDEPRECATED");
|
||||
|
||||
// Note: blitDEPRECATED is only used for Renderer::copyFrame()
|
||||
|
||||
ASSERT_PRECONDITION(mCurrentRenderPass.renderPass == VK_NULL_HANDLE,
|
||||
"blitDEPRECATED() cannot be invoked inside a render pass.");
|
||||
|
||||
ASSERT_PRECONDITION(buffers == TargetBufferFlags::COLOR0,
|
||||
"blitDEPRECATED only supports COLOR0");
|
||||
|
||||
ASSERT_PRECONDITION(srcRect.left >= 0 && srcRect.bottom >= 0 &&
|
||||
dstRect.left >= 0 && dstRect.bottom >= 0,
|
||||
"Source and destination rects must be positive.");
|
||||
if (UTILS_UNLIKELY(mCurrentRenderPass.renderPass)) {
|
||||
utils::slog.e << "Blits cannot be invoked inside a render pass." << utils::io::endl;
|
||||
return;
|
||||
}
|
||||
|
||||
VulkanRenderTarget* dstTarget = mResourceAllocator.handle_cast<VulkanRenderTarget*>(dst);
|
||||
VulkanRenderTarget* srcTarget = mResourceAllocator.handle_cast<VulkanRenderTarget*>(src);
|
||||
|
||||
VkFilter const vkfilter = (filter == SamplerMagFilter::NEAREST) ?
|
||||
VK_FILTER_NEAREST : VK_FILTER_LINEAR;
|
||||
VkFilter vkfilter = filter == SamplerMagFilter::NEAREST ? VK_FILTER_NEAREST : VK_FILTER_LINEAR;
|
||||
|
||||
// The Y inversion below makes it so that Vk matches GL and Metal.
|
||||
|
||||
VkExtent2D const srcExtent = srcTarget->getExtent();
|
||||
VkExtent2D const dstExtent = dstTarget->getExtent();
|
||||
const VkExtent2D srcExtent = srcTarget->getExtent();
|
||||
const int32_t srcLeft = srcRect.left;
|
||||
const int32_t srcTop = srcExtent.height - srcRect.bottom - srcRect.height;
|
||||
const int32_t srcRight = srcRect.left + srcRect.width;
|
||||
const int32_t srcBottom = srcTop + srcRect.height;
|
||||
const VkOffset3D srcOffsets[2] = { { srcLeft, srcTop, 0 }, { srcRight, srcBottom, 1 }};
|
||||
|
||||
auto const dstLeft = int32_t(dstRect.left);
|
||||
auto const srcLeft = int32_t(srcRect.left);
|
||||
auto const dstTop = int32_t(dstExtent.height - (dstRect.bottom + dstRect.height));
|
||||
auto const srcTop = int32_t(srcExtent.height - (srcRect.bottom + srcRect.height));
|
||||
auto const dstRight = int32_t(dstRect.left + dstRect.width);
|
||||
auto const srcRight = int32_t(srcRect.left + srcRect.width);
|
||||
auto const dstBottom = int32_t(dstTop + dstRect.height);
|
||||
auto const srcBottom = int32_t(srcTop + srcRect.height);
|
||||
VkOffset3D const srcOffsets[2] = { { srcLeft, srcTop, 0 }, { srcRight, srcBottom, 1 }};
|
||||
VkOffset3D const dstOffsets[2] = { { dstLeft, dstTop, 0 }, { dstRight, dstBottom, 1 }};
|
||||
const VkExtent2D dstExtent = dstTarget->getExtent();
|
||||
const int32_t dstLeft = dstRect.left;
|
||||
const int32_t dstTop = dstExtent.height - dstRect.bottom - dstRect.height;
|
||||
const int32_t dstRight = dstRect.left + dstRect.width;
|
||||
const int32_t dstBottom = dstTop + dstRect.height;
|
||||
const VkOffset3D dstOffsets[2] = { { dstLeft, dstTop, 0 }, { dstRight, dstBottom, 1 }};
|
||||
|
||||
mBlitter.blit(vkfilter,
|
||||
dstTarget->getColor(0), dstOffsets,
|
||||
srcTarget->getColor(0), srcOffsets);
|
||||
if (any(buffers & TargetBufferFlags::DEPTH) && srcTarget->hasDepth() && dstTarget->hasDepth()) {
|
||||
mBlitter.blitDepth({dstTarget, dstOffsets, srcTarget, srcOffsets});
|
||||
}
|
||||
|
||||
if (any(buffers & TargetBufferFlags::COLOR0)) {
|
||||
mBlitter.blitColor({ dstTarget, dstOffsets, srcTarget, srcOffsets, vkfilter, int(0) });
|
||||
}
|
||||
FVK_SYSTRACE_END();
|
||||
}
|
||||
|
||||
|
||||
@@ -18,11 +18,10 @@
|
||||
|
||||
#include "VulkanConstants.h"
|
||||
#include "VulkanMemory.h"
|
||||
#include "spirv/VulkanSpirvUtils.h"
|
||||
|
||||
#include <backend/platforms/VulkanPlatform.h>
|
||||
|
||||
#include <utils/Panic.h> // ASSERT_POSTCONDITION
|
||||
#include <utils/Panic.h>
|
||||
|
||||
using namespace bluevk;
|
||||
|
||||
@@ -47,39 +46,61 @@ static void clampToFramebuffer(VkRect2D* rect, uint32_t fbWidth, uint32_t fbHeig
|
||||
rect->extent.height = std::max(top - y, 0);
|
||||
}
|
||||
|
||||
VulkanProgram::VulkanProgram(VkDevice device, Program const& builder) noexcept
|
||||
VulkanProgram::VulkanProgram(VkDevice device, const Program& builder) noexcept
|
||||
: HwProgram(builder.getName()),
|
||||
VulkanResource(VulkanResourceType::PROGRAM),
|
||||
mInfo(new PipelineInfo()),
|
||||
mInfo(new PipelineInfo(builder.getSpecializationConstants().size())),
|
||||
mDevice(device) {
|
||||
Program::ShaderSource const& blobs = builder.getShadersSource();
|
||||
auto& blobs = builder.getShadersSource();
|
||||
auto& modules = mInfo->shaders;
|
||||
|
||||
auto const& specializationConstants = builder.getSpecializationConstants();
|
||||
|
||||
std::vector<uint32_t> shader;
|
||||
for (size_t i = 0; i < MAX_SHADER_MODULES; i++) {
|
||||
Program::ShaderBlob const& blob = blobs[i];
|
||||
|
||||
uint32_t* data = (uint32_t*) blob.data();
|
||||
size_t dataSize = blob.size();
|
||||
|
||||
if (!specializationConstants.empty()) {
|
||||
workaroundSpecConstant(blob, specializationConstants, shader);
|
||||
data = (uint32_t*) shader.data();
|
||||
dataSize = shader.size() * 4;
|
||||
}
|
||||
|
||||
const auto& blob = blobs[i];
|
||||
uint32_t* data = (uint32_t*)blob.data();
|
||||
VkShaderModule& module = modules[i];
|
||||
VkShaderModuleCreateInfo moduleInfo = {
|
||||
.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
|
||||
.codeSize = dataSize,
|
||||
.codeSize = blob.size(),
|
||||
.pCode = data,
|
||||
};
|
||||
VkResult result = vkCreateShaderModule(mDevice, &moduleInfo, VKALLOC, &module);
|
||||
ASSERT_POSTCONDITION(result == VK_SUCCESS, "Unable to create shader module.");
|
||||
}
|
||||
|
||||
// Note that bools are 4-bytes in Vulkan
|
||||
// https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkBool32.html
|
||||
constexpr uint32_t const CONSTANT_SIZE = 4;
|
||||
|
||||
// populate the specialization constants requirements right now
|
||||
auto const& specializationConstants = builder.getSpecializationConstants();
|
||||
uint32_t const specConstCount = static_cast<uint32_t>(specializationConstants.size());
|
||||
char* specData = mInfo->specConstData.get();
|
||||
if (specConstCount > 0) {
|
||||
mInfo->specializationInfo = {
|
||||
.mapEntryCount = specConstCount,
|
||||
.pMapEntries = mInfo->specConsts.data(),
|
||||
.dataSize = specConstCount * CONSTANT_SIZE,
|
||||
.pData = specData,
|
||||
};
|
||||
}
|
||||
for (uint32_t i = 0; i < specConstCount; ++i) {
|
||||
uint32_t const offset = i * CONSTANT_SIZE;
|
||||
mInfo->specConsts[i] = {
|
||||
.constantID = specializationConstants[i].id,
|
||||
.offset = offset,
|
||||
.size = CONSTANT_SIZE,
|
||||
};
|
||||
using SpecConstant = Program::SpecializationConstant::Type;
|
||||
char const* addr = (char*)specData + offset;
|
||||
SpecConstant const& arg = specializationConstants[i].value;
|
||||
if (std::holds_alternative<bool>(arg)) {
|
||||
*((VkBool32*)addr) = std::get<bool>(arg) ? VK_TRUE : VK_FALSE;
|
||||
} else if (std::holds_alternative<float>(arg)) {
|
||||
*((float*)addr) = std::get<float>(arg);
|
||||
} else {
|
||||
*((int32_t*)addr) = std::get<int32_t>(arg);
|
||||
}
|
||||
}
|
||||
|
||||
auto& groupInfo = builder.getSamplerGroupInfo();
|
||||
auto& bindingToSamplerIndex = mInfo->bindingToSamplerIndex;
|
||||
auto& usage = mInfo->usage;
|
||||
@@ -102,7 +123,7 @@ VulkanProgram::VulkanProgram(VkDevice device, Program const& builder) noexcept
|
||||
VulkanProgram::VulkanProgram(VkDevice device, VkShaderModule vs, VkShaderModule fs,
|
||||
CustomSamplerInfoList const& samplerInfo) noexcept
|
||||
: VulkanResource(VulkanResourceType::PROGRAM),
|
||||
mInfo(new PipelineInfo()),
|
||||
mInfo(new PipelineInfo(0)),
|
||||
mDevice(device) {
|
||||
mInfo->shaders[0] = vs;
|
||||
mInfo->shaders[1] = fs;
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
#include "VulkanResources.h"
|
||||
#include "VulkanSwapChain.h"
|
||||
#include "VulkanTexture.h"
|
||||
#include "VulkanUtility.h"
|
||||
|
||||
#include "private/backend/SamplerGroup.h"
|
||||
|
||||
@@ -37,7 +38,7 @@ class VulkanTimestamps;
|
||||
|
||||
struct VulkanProgram : public HwProgram, VulkanResource {
|
||||
|
||||
VulkanProgram(VkDevice device, Program const& builder) noexcept;
|
||||
VulkanProgram(VkDevice device, const Program& builder) noexcept;
|
||||
|
||||
struct CustomSamplerInfo {
|
||||
uint8_t groupIndex;
|
||||
@@ -64,14 +65,21 @@ struct VulkanProgram : public HwProgram, VulkanResource {
|
||||
return mInfo->bindingToSamplerIndex;
|
||||
}
|
||||
|
||||
inline VkSpecializationInfo const& getSpecConstInfo() const {
|
||||
return mInfo->specializationInfo;
|
||||
}
|
||||
|
||||
private:
|
||||
// TODO: handle compute shaders.
|
||||
// The expected order of shaders - from frontend to backend - is vertex, fragment, compute.
|
||||
static constexpr uint8_t const MAX_SHADER_MODULES = 2;
|
||||
static constexpr uint8_t MAX_SHADER_MODULES = 2;
|
||||
|
||||
struct PipelineInfo {
|
||||
PipelineInfo()
|
||||
: bindingToSamplerIndex(MAX_SAMPLER_COUNT, 0xffff) {}
|
||||
PipelineInfo(size_t specConstsCount) :
|
||||
bindingToSamplerIndex(MAX_SAMPLER_COUNT, 0xffff),
|
||||
specConsts(specConstsCount, VkSpecializationMapEntry{}),
|
||||
specConstData(new char[specConstsCount * 4])
|
||||
{}
|
||||
|
||||
// This bitset maps to each of the sampler in the sampler groups associated with this
|
||||
// program, and whether each sampler is used in which shader (i.e. vert, frag, compute).
|
||||
@@ -79,7 +87,10 @@ private:
|
||||
|
||||
// We store the samplerGroupIndex as the top 8-bit and the index within each group as the lower 8-bit.
|
||||
utils::FixedCapacityVector<uint16_t> bindingToSamplerIndex;
|
||||
VkShaderModule shaders[MAX_SHADER_MODULES] = { VK_NULL_HANDLE };
|
||||
VkShaderModule shaders[MAX_SHADER_MODULES] = {VK_NULL_HANDLE};
|
||||
VkSpecializationInfo specializationInfo = {};
|
||||
utils::FixedCapacityVector<VkSpecializationMapEntry> specConsts;
|
||||
std::unique_ptr<char[]> specConstData;
|
||||
};
|
||||
|
||||
PipelineInfo* mInfo;
|
||||
|
||||
@@ -360,7 +360,9 @@ VulkanPipelineCache::PipelineCacheEntry* VulkanPipelineCache::createPipeline() n
|
||||
|
||||
// If we reach this point, we need to create and stash a brand new pipeline object.
|
||||
shaderStages[0].module = mPipelineRequirements.shaders[0];
|
||||
shaderStages[0].pSpecializationInfo = mSpecializationRequirements;
|
||||
shaderStages[1].module = mPipelineRequirements.shaders[1];
|
||||
shaderStages[1].pSpecializationInfo = mSpecializationRequirements;
|
||||
|
||||
// Expand our size-optimized structs into the proper Vk structs.
|
||||
uint32_t numVertexAttribs = 0;
|
||||
@@ -566,6 +568,7 @@ VulkanPipelineCache::PipelineLayoutCacheEntry* VulkanPipelineCache::getOrCreateP
|
||||
void VulkanPipelineCache::bindProgram(VulkanProgram* program) noexcept {
|
||||
mPipelineRequirements.shaders[0] = program->getVertexShader();
|
||||
mPipelineRequirements.shaders[1] = program->getFragmentShader();
|
||||
mSpecializationRequirements = &program->getSpecConstInfo();
|
||||
}
|
||||
|
||||
void VulkanPipelineCache::bindRasterState(const RasterState& rasterState) noexcept {
|
||||
|
||||
@@ -416,6 +416,7 @@ private:
|
||||
RasterState mCurrentRasterState;
|
||||
PipelineKey mPipelineRequirements = {};
|
||||
DescriptorKey mDescriptorRequirements = {};
|
||||
VkSpecializationInfo const* mSpecializationRequirements = nullptr;
|
||||
|
||||
// Current bindings for the pipeline and descriptor sets.
|
||||
PipelineKey mBoundPipeline = {};
|
||||
|
||||
@@ -99,16 +99,11 @@ void VulkanSwapChain::present() {
|
||||
mColors[mCurrentSwapIndex]->transitionLayout(cmdbuf, subresources, VulkanLayout::PRESENT);
|
||||
}
|
||||
mCommands->flush();
|
||||
|
||||
// We only present if it is not headless. No-op for headless (but note that we still need the
|
||||
// flush() in the above line).
|
||||
if (!mHeadless) {
|
||||
VkSemaphore const finishedDrawing = mCommands->acquireFinishedSignal();
|
||||
VkResult const result = mPlatform->present(swapChain, mCurrentSwapIndex, finishedDrawing);
|
||||
ASSERT_POSTCONDITION(result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR ||
|
||||
result == VK_ERROR_OUT_OF_DATE_KHR,
|
||||
"Cannot present in swapchain.");
|
||||
}
|
||||
VkSemaphore const finishedDrawing = mCommands->acquireFinishedSignal();
|
||||
VkResult const result = mPlatform->present(swapChain, mCurrentSwapIndex, finishedDrawing);
|
||||
ASSERT_POSTCONDITION(result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR
|
||||
|| result == VK_ERROR_OUT_OF_DATE_KHR,
|
||||
"Cannot present in swapchain.");
|
||||
|
||||
// We presented the last acquired buffer.
|
||||
mAcquired = false;
|
||||
|
||||
@@ -73,7 +73,7 @@
|
||||
#elif defined(WIN32)
|
||||
// No platform specific includes
|
||||
#else
|
||||
// Not a supported Vulkan platform
|
||||
#error Not a supported Vulkan platform
|
||||
#endif
|
||||
|
||||
using namespace bluevk;
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2023 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 "VulkanSpirvUtils.h"
|
||||
|
||||
#include <utils/compiler.h> // UTILS_UNUSED_IN_RELEASE, UTILS_FALLTHROUGH
|
||||
#include <utils/debug.h> // assert_invariant
|
||||
#include <utils/FixedCapacityVector.h>
|
||||
|
||||
#include <spirv/unified1/spirv.hpp>
|
||||
|
||||
#include <unordered_map>
|
||||
#include <variant>
|
||||
|
||||
namespace filament::backend {
|
||||
|
||||
namespace {
|
||||
|
||||
// This function transforms an OpSpecConstant instruction into just a OpConstant instruction.
|
||||
// Additionally, it will adjust the value of the constant as given by the program.
|
||||
void getTransformedConstantInst(SpecConstantValue* value, uint32_t* inst) {
|
||||
|
||||
// The first word is the size of the instruction and the instruction type.
|
||||
// The second word is the type of the instruction.
|
||||
// The third word is the "result id" (i.e. the variable to store into).
|
||||
// The fourth word (only for floats and ints) is the literal representing the value.
|
||||
// We only want to change the first and fourth words.
|
||||
constexpr size_t const OP = 0;
|
||||
constexpr size_t const VALUE = 3;
|
||||
|
||||
if (!value) {
|
||||
// If a specialization wasn't provided, just switch the opcode.
|
||||
uint32_t const op = inst[OP] & 0x0000FFFF;
|
||||
if (op == spv::Op::OpSpecConstantFalse) {
|
||||
inst[OP] = (3 << 16) | spv::Op::OpConstantFalse;
|
||||
} else if (op == spv::Op::OpSpecConstantTrue) {
|
||||
inst[OP] = (3 << 16) | spv::Op::OpConstantTrue;
|
||||
} else if (op == spv::Op::OpSpecConstant) {
|
||||
inst[OP] = (4 << 16) | spv::Op::OpConstant;
|
||||
}
|
||||
} else if (std::holds_alternative<bool>(*value)) {
|
||||
inst[OP] = (3 << 16)
|
||||
| (std::get<bool>(*value) ? spv::Op::OpConstantTrue : spv::Op::OpConstantFalse);
|
||||
} else if (std::holds_alternative<float>(*value)) {
|
||||
float const fval = std::get<float>(*value);
|
||||
inst[OP] = (4 << 16) | spv::Op::OpConstant;
|
||||
inst[VALUE] = *reinterpret_cast<uint32_t const*>(&fval);
|
||||
} else {
|
||||
int const ival = std::get<int>(*value);
|
||||
inst[OP] = (4 << 16) | spv::Op::OpConstant;
|
||||
inst[VALUE] = *reinterpret_cast<uint32_t const*>(&ival);
|
||||
}
|
||||
}
|
||||
|
||||
} // anonymous namespace
|
||||
|
||||
void workaroundSpecConstant(Program::ShaderBlob const& blob,
|
||||
utils::FixedCapacityVector<Program::SpecializationConstant> const& specConstants,
|
||||
std::vector<uint32_t>& output) {
|
||||
using WordMap = std::unordered_map<uint32_t, uint32_t>;
|
||||
using SpecValueMap = std::unordered_map<uint32_t, SpecConstantValue>;
|
||||
constexpr size_t const HEADER_SIZE = 5;
|
||||
|
||||
WordMap varToIdMap;
|
||||
SpecValueMap idToValue;
|
||||
|
||||
for (auto spec: specConstants) {
|
||||
idToValue[spec.id] = spec.value;
|
||||
}
|
||||
|
||||
// The follow loop will iterate through all the instructions and look for instructions of the
|
||||
// form:
|
||||
//
|
||||
// OpDecorate %1 SpecId 0
|
||||
// %1 = OpSpecConstantFalse %bool
|
||||
//
|
||||
// We want to track the mapping between the variable id %1 and the specId 0. And when seeing a
|
||||
// %1 as the result, we want to change that instruction to just an OpConsant where the constant
|
||||
// value is adjusted by the spec values provided in the program.
|
||||
// Additionally, we will turn the SpecId decorations to no-ops.
|
||||
size_t const dataSize = blob.size() / 4;
|
||||
|
||||
output.resize(dataSize);
|
||||
uint32_t const* data = (uint32_t*) blob.data();
|
||||
uint32_t* outputData = output.data();
|
||||
|
||||
std::memcpy(&outputData[0], &data[0], HEADER_SIZE * 4);
|
||||
size_t outputCursor = HEADER_SIZE;
|
||||
|
||||
for (uint32_t cursor = HEADER_SIZE, cursorEnd = dataSize; cursor < cursorEnd;) {
|
||||
uint32_t const firstWord = data[cursor];
|
||||
uint32_t const wordCount = firstWord >> 16;
|
||||
uint32_t const op = firstWord & 0x0000FFFF;
|
||||
|
||||
switch(op) {
|
||||
case spv::Op::OpSpecConstant:
|
||||
case spv::Op::OpSpecConstantTrue:
|
||||
case spv::Op::OpSpecConstantFalse: {
|
||||
uint32_t const targetVar = data[cursor + 2];
|
||||
|
||||
UTILS_UNUSED_IN_RELEASE WordMap::const_iterator idItr = varToIdMap.find(targetVar);
|
||||
assert_invariant(idItr != varToIdMap.end() &&
|
||||
"Cannot find variable previously decorated with SpecId");
|
||||
|
||||
auto valItr = idToValue.find(idItr->second);
|
||||
|
||||
SpecConstantValue* val = (valItr != idToValue.end()) ? &valItr->second : nullptr;
|
||||
std::memcpy(&outputData[outputCursor], &data[cursor], wordCount * 4);
|
||||
getTransformedConstantInst(val, &outputData[outputCursor]);
|
||||
outputCursor += wordCount;
|
||||
break;
|
||||
}
|
||||
case spv::Op::OpDecorate: {
|
||||
if (data[cursor + 2] == spv::Decoration::DecorationSpecId) {
|
||||
uint32_t const targetVar = data[cursor + 1];
|
||||
uint32_t const specId = data[cursor + 3];
|
||||
varToIdMap[targetVar] = specId;
|
||||
|
||||
// Note these decorations do not need to be written to the output.
|
||||
break;
|
||||
}
|
||||
// else fallthrough and copy like all other instructions
|
||||
UTILS_FALLTHROUGH;
|
||||
}
|
||||
default:
|
||||
std::memcpy(&outputData[outputCursor], &data[cursor], wordCount * 4);
|
||||
outputCursor += wordCount;
|
||||
break;
|
||||
}
|
||||
cursor += wordCount;
|
||||
}
|
||||
output.resize(outputCursor);
|
||||
}
|
||||
|
||||
} // namespace filament::backend
|
||||
@@ -1,47 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2023 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_VULKANSPIRVUTILS_H
|
||||
#define TNT_FILAMENT_BACKEND_VULKANSPIRVUTILS_H
|
||||
|
||||
#include "backend/Program.h"
|
||||
|
||||
#include <utils/FixedCapacityVector.h>
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace filament::backend {
|
||||
|
||||
using SpecConstantValue = Program::SpecializationConstant::Type;
|
||||
|
||||
// For certain drivers, using spec constant can lead to compile errors [1] or undesirable behaviors
|
||||
// [2]. In those instances, we simply change the spirv and set them to constants.
|
||||
//
|
||||
// (Implemenation note: we cannot write to the blob because spirv-validator does not properly handle
|
||||
// the Nop (no-op) instruction, and swiftshader validates the shader before compilation. So we need
|
||||
// to skip those instructions instead).
|
||||
//
|
||||
// [1]: QC driver cannot use spec constant to size fields
|
||||
// (https://github.com/google/filament/issues/6444).
|
||||
// [2]: An internal driver does not DCE a block guarded by a spec-const boolean set to false
|
||||
// (b/310603393).
|
||||
void workaroundSpecConstant(Program::ShaderBlob const& blob,
|
||||
utils::FixedCapacityVector<Program::SpecializationConstant> const& specConstants,
|
||||
std::vector<uint32_t>& output);
|
||||
|
||||
} // namespace filament::backend
|
||||
|
||||
#endif // TNT_FILAMENT_BACKEND_VULKANSPIRVUTILS_H
|
||||
@@ -86,16 +86,13 @@ void BackendTest::executeCommands() {
|
||||
}
|
||||
|
||||
void BackendTest::flushAndWait() {
|
||||
getDriverApi().finish();
|
||||
auto& api = getDriverApi();
|
||||
api.finish();
|
||||
executeCommands();
|
||||
getDriver().purge();
|
||||
}
|
||||
|
||||
Handle<HwSwapChain> BackendTest::createSwapChain() {
|
||||
const NativeView& view = getNativeView();
|
||||
if (!view.ptr) {
|
||||
return getDriverApi().createSwapChainHeadless(view.width, view.height, 0);
|
||||
}
|
||||
return getDriverApi().createSwapChain(view.ptr, 0);
|
||||
}
|
||||
|
||||
@@ -215,3 +212,4 @@ int runTests() {
|
||||
}
|
||||
|
||||
} // namespace test
|
||||
|
||||
|
||||
@@ -22,9 +22,6 @@
|
||||
|
||||
namespace test {
|
||||
|
||||
constexpr uint32_t const WINDOW_WIDTH = 512;
|
||||
constexpr uint32_t const WINDOW_HEIGHT = 512;
|
||||
|
||||
// To avoid a dependency on filabridge, the Backend enum is replicated here.
|
||||
enum class Backend : uint8_t {
|
||||
OPENGL = 1,
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2023 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 "BackendTest.h"
|
||||
#include "PlatformRunner.h"
|
||||
|
||||
#include <array>
|
||||
#include <iostream>
|
||||
|
||||
namespace test {
|
||||
|
||||
test::NativeView getNativeView() {
|
||||
return {
|
||||
.ptr = nullptr,
|
||||
.width = WINDOW_WIDTH,
|
||||
.height = WINDOW_HEIGHT,
|
||||
};
|
||||
}
|
||||
|
||||
}// namespace test
|
||||
|
||||
namespace {
|
||||
|
||||
std::array<test::Backend, 2> const VALID_BACKENDS{
|
||||
test::Backend::OPENGL,
|
||||
test::Backend::VULKAN,
|
||||
};
|
||||
|
||||
}// namespace
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
auto backend = test::parseArgumentsForBackend(argc, argv);
|
||||
|
||||
if (!std::any_of(VALID_BACKENDS.begin(), VALID_BACKENDS.end(),
|
||||
[backend](test::Backend validBackend) { return backend == validBackend; })) {
|
||||
std::cerr << "Specified an invalid backend. Only GL and Vulkan are available" << std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
test::initTests(backend, false, argc, argv);
|
||||
return test::runTests();
|
||||
}
|
||||
@@ -58,7 +58,7 @@ test::NativeView getNativeView() {
|
||||
}
|
||||
|
||||
- (NSView*)createView {
|
||||
NSRect frame = NSMakeRect(0, 0, test::WINDOW_WIDTH, test::WINDOW_HEIGHT);
|
||||
NSRect frame = NSMakeRect(0, 0, 512, 512);
|
||||
NSWindow* window = [[NSWindow alloc] initWithContentRect:frame
|
||||
styleMask:NSWindowStyleMaskBorderless
|
||||
backing:NSBackingStoreBuffered
|
||||
|
||||
@@ -193,6 +193,60 @@ static void createFaces(DriverApi& dapi, Handle<HwTexture> texture, int baseWidt
|
||||
dapi.update3DImage(texture, level, 0, 0, 0, width, height, 6, std::move(pb));
|
||||
}
|
||||
|
||||
TEST_F(BackendTest, CubemapMinify) {
|
||||
auto& api = getDriverApi();
|
||||
|
||||
Handle<HwTexture> texture = api.createTexture(
|
||||
SamplerType::SAMPLER_CUBEMAP, 4, TextureFormat::RGBA8, 1, 256, 256, 1,
|
||||
TextureUsage::SAMPLEABLE | TextureUsage::UPLOADABLE | TextureUsage::COLOR_ATTACHMENT);
|
||||
|
||||
createFaces(api, texture, 256, 256, 0, float3(0.5, 0, 0));
|
||||
|
||||
const int srcLevel = 0;
|
||||
const int dstLevel = 1;
|
||||
|
||||
const TextureCubemapFace srcFace = TextureCubemapFace::NEGATIVE_Y;
|
||||
const TextureCubemapFace dstFace = TextureCubemapFace::NEGATIVE_Y;
|
||||
|
||||
const TargetBufferInfo srcInfo = { texture, srcLevel, +srcFace };
|
||||
const TargetBufferInfo dstInfo = { texture, dstLevel, +dstFace };
|
||||
|
||||
Handle<HwRenderTarget> srcRenderTarget;
|
||||
srcRenderTarget = api.createRenderTarget( TargetBufferFlags::COLOR,
|
||||
256 >> srcLevel, 256 >> srcLevel, 1, { srcInfo }, {}, {});
|
||||
|
||||
Handle<HwRenderTarget> dstRenderTarget;
|
||||
dstRenderTarget = api.createRenderTarget( TargetBufferFlags::COLOR,
|
||||
256 >> dstLevel, 256 >> dstLevel, 1, { dstInfo }, {}, {});
|
||||
|
||||
api.blit(TargetBufferFlags::COLOR0, dstRenderTarget,
|
||||
{0, 0, 256 >> dstLevel, 256 >> dstLevel}, srcRenderTarget,
|
||||
{0, 0, 256 >> srcLevel, 256 >> srcLevel}, SamplerMagFilter::LINEAR);
|
||||
|
||||
// Push through an empty frame. Note that this test does not do
|
||||
// makeCurrent / commit and is therefore similar to renderStandaloneView.
|
||||
api.beginFrame(0, 0);
|
||||
api.endFrame(0);
|
||||
|
||||
// Grab a screenshot.
|
||||
ScreenshotParams params { 256 >> dstLevel, 256 >> dstLevel, "CubemapMinify.png" };
|
||||
api.beginFrame(0, 0);
|
||||
dumpScreenshot(api, dstRenderTarget, ¶ms);
|
||||
api.endFrame(0);
|
||||
|
||||
// Wait for the ReadPixels result to come back.
|
||||
api.finish();
|
||||
executeCommands();
|
||||
getDriver().purge();
|
||||
|
||||
// Cleanup.
|
||||
api.destroyTexture(texture);
|
||||
api.destroyRenderTarget(srcRenderTarget);
|
||||
api.destroyRenderTarget(dstRenderTarget);
|
||||
executeCommands();
|
||||
}
|
||||
|
||||
|
||||
TEST_F(BackendTest, ColorMagnify) {
|
||||
auto& api = getDriverApi();
|
||||
|
||||
@@ -209,7 +263,7 @@ TEST_F(BackendTest, ColorMagnify) {
|
||||
api.makeCurrent(swapChain, swapChain);
|
||||
|
||||
// Create a source texture.
|
||||
Handle<HwTexture> const srcTexture = api.createTexture(
|
||||
Handle<HwTexture> srcTexture = api.createTexture(
|
||||
SamplerType::SAMPLER_2D, kNumLevels, kSrcTexFormat, 1, kSrcTexWidth, kSrcTexHeight, 1,
|
||||
TextureUsage::SAMPLEABLE | TextureUsage::UPLOADABLE | TextureUsage::COLOR_ATTACHMENT);
|
||||
const bool flipY = sBackend == Backend::OPENGL;
|
||||
@@ -217,7 +271,7 @@ TEST_F(BackendTest, ColorMagnify) {
|
||||
createBitmap(api, srcTexture, kSrcTexWidth, kSrcTexHeight, 1, float3(0, 0, 0.5), flipY);
|
||||
|
||||
// Create a destination texture.
|
||||
Handle<HwTexture> const dstTexture = api.createTexture(
|
||||
Handle<HwTexture> dstTexture = api.createTexture(
|
||||
SamplerType::SAMPLER_2D, kNumLevels, kDstTexFormat, 1, kDstTexWidth, kDstTexHeight, 1,
|
||||
TextureUsage::SAMPLEABLE | TextureUsage::COLOR_ATTACHMENT);
|
||||
|
||||
@@ -233,7 +287,7 @@ TEST_F(BackendTest, ColorMagnify) {
|
||||
|
||||
// Do a "magnify" blit from level 1 of the source RT to the level 0 of the destination RT.
|
||||
const int srcLevel = 1;
|
||||
api.blitDEPRECATED(TargetBufferFlags::COLOR0, dstRenderTargets[0],
|
||||
api.blit(TargetBufferFlags::COLOR0, dstRenderTargets[0],
|
||||
{0, 0, kDstTexWidth, kDstTexHeight}, srcRenderTargets[srcLevel],
|
||||
{0, 0, kSrcTexWidth >> srcLevel, kSrcTexHeight >> srcLevel}, SamplerMagFilter::LINEAR);
|
||||
|
||||
@@ -284,7 +338,7 @@ TEST_F(BackendTest, ColorMinify) {
|
||||
api.makeCurrent(swapChain, swapChain);
|
||||
|
||||
// Create a source texture.
|
||||
Handle<HwTexture> const srcTexture = api.createTexture(
|
||||
Handle<HwTexture> srcTexture = api.createTexture(
|
||||
SamplerType::SAMPLER_2D, kNumLevels, kSrcTexFormat, 1, kSrcTexWidth, kSrcTexHeight, 1,
|
||||
TextureUsage::SAMPLEABLE | TextureUsage::UPLOADABLE | TextureUsage::COLOR_ATTACHMENT);
|
||||
const bool flipY = sBackend == Backend::OPENGL;
|
||||
@@ -292,7 +346,7 @@ TEST_F(BackendTest, ColorMinify) {
|
||||
createBitmap(api, srcTexture, kSrcTexWidth, kSrcTexHeight, 1, float3(0, 0, 0.5), flipY);
|
||||
|
||||
// Create a destination texture.
|
||||
Handle<HwTexture> const dstTexture = api.createTexture(
|
||||
Handle<HwTexture> dstTexture = api.createTexture(
|
||||
SamplerType::SAMPLER_2D, kNumLevels, kDstTexFormat, 1, kDstTexWidth, kDstTexHeight, 1,
|
||||
TextureUsage::SAMPLEABLE | TextureUsage::COLOR_ATTACHMENT);
|
||||
|
||||
@@ -308,21 +362,29 @@ TEST_F(BackendTest, ColorMinify) {
|
||||
|
||||
// Do a "minify" blit from level 1 of the source RT to the level 0 of the destination RT.
|
||||
const int srcLevel = 1;
|
||||
api.blit(TargetBufferFlags::COLOR0, dstRenderTargets[0],
|
||||
{0, 0, kDstTexWidth, kDstTexHeight}, srcRenderTargets[srcLevel],
|
||||
{0, 0, kSrcTexWidth >> srcLevel, kSrcTexHeight >> srcLevel}, SamplerMagFilter::LINEAR);
|
||||
|
||||
api.blitDEPRECATED(TargetBufferFlags::COLOR0,
|
||||
dstRenderTargets[0], {0, 0, kDstTexWidth, kDstTexHeight},
|
||||
srcRenderTargets[srcLevel], {0, 0, kSrcTexWidth >> srcLevel, kSrcTexHeight >> srcLevel},
|
||||
SamplerMagFilter::LINEAR);
|
||||
// Push through an empty frame to allow the texture to upload and the blit to execute.
|
||||
api.beginFrame(0, 0);
|
||||
api.commit(swapChain);
|
||||
api.endFrame(0);
|
||||
|
||||
// Grab a screenshot.
|
||||
ScreenshotParams params { kDstTexWidth, kDstTexHeight, "ColorMinify.png" };
|
||||
api.beginFrame(0, 0);
|
||||
dumpScreenshot(api, dstRenderTargets[0], ¶ms);
|
||||
api.commit(swapChain);
|
||||
api.endFrame(0);
|
||||
|
||||
// Wait for the ReadPixels result to come back.
|
||||
flushAndWait();
|
||||
api.finish();
|
||||
executeCommands();
|
||||
getDriver().purge();
|
||||
|
||||
// Check if the image matches perfectly to our golden run.
|
||||
const uint32_t expected = 0xf3d9c53f;
|
||||
const uint32_t expected = 0x7739bef5;
|
||||
printf("Computed hash is 0x%8.8x, Expected 0x%8.8x\n", params.pixelHashResult, expected);
|
||||
EXPECT_TRUE(params.pixelHashResult == expected);
|
||||
|
||||
@@ -335,6 +397,149 @@ TEST_F(BackendTest, ColorMinify) {
|
||||
executeCommands();
|
||||
}
|
||||
|
||||
TEST_F(BackendTest, DepthMinify) {
|
||||
auto& api = getDriverApi();
|
||||
|
||||
constexpr int kSrcTexWidth = 1024;
|
||||
constexpr int kSrcTexHeight = 1024;
|
||||
constexpr int kDstTexWidth = 256;
|
||||
constexpr int kDstTexHeight = 256;
|
||||
constexpr auto kColorTexFormat = TextureFormat::RGBA8;
|
||||
constexpr auto kDepthTexFormat = TextureFormat::DEPTH24;
|
||||
constexpr int kNumLevels = 3;
|
||||
|
||||
// Create a SwapChain and make it current. We don't really use it so the res doesn't matter.
|
||||
auto swapChain = api.createSwapChainHeadless(256, 256, 0);
|
||||
api.makeCurrent(swapChain, swapChain);
|
||||
|
||||
// Create a program.
|
||||
ProgramHandle program;
|
||||
{
|
||||
ShaderGenerator shaderGen(triangleVs, triangleFs, sBackend, sIsMobilePlatform);
|
||||
Program prog = shaderGen.getProgram(api);
|
||||
Program::Sampler psamplers[] = { utils::CString("tex"), 0 };
|
||||
prog.setSamplerGroup(0, ShaderStageFlags::ALL_SHADER_STAGE_FLAGS, psamplers, sizeof(psamplers) / sizeof(psamplers[0]));
|
||||
prog.uniformBlockBindings({{"params", 1}});
|
||||
program = api.createProgram(std::move(prog));
|
||||
}
|
||||
|
||||
// Create a VertexBuffer, IndexBuffer, and RenderPrimitive.
|
||||
TrianglePrimitive* triangle = new TrianglePrimitive(api);
|
||||
|
||||
// Create textures for the first rendering pass.
|
||||
Handle<HwTexture> srcColorTexture = api.createTexture(
|
||||
SamplerType::SAMPLER_2D, kNumLevels, kColorTexFormat, 1, kSrcTexWidth, kSrcTexHeight, 1,
|
||||
TextureUsage::SAMPLEABLE | TextureUsage::COLOR_ATTACHMENT);
|
||||
|
||||
Handle<HwTexture> srcDepthTexture = api.createTexture(
|
||||
SamplerType::SAMPLER_2D, 1, kDepthTexFormat, 1, kSrcTexWidth, kSrcTexHeight,
|
||||
1, TextureUsage::DEPTH_ATTACHMENT);
|
||||
|
||||
// Create textures for the second rendering pass.
|
||||
Handle<HwTexture> dstColorTexture = api.createTexture(
|
||||
SamplerType::SAMPLER_2D, kNumLevels, kColorTexFormat, 1, kDstTexWidth, kDstTexHeight, 1,
|
||||
TextureUsage::SAMPLEABLE | TextureUsage::COLOR_ATTACHMENT);
|
||||
|
||||
Handle<HwTexture> dstDepthTexture = api.createTexture(
|
||||
SamplerType::SAMPLER_2D, 1, kDepthTexFormat, 1, kDstTexWidth, kDstTexHeight,
|
||||
1, TextureUsage::DEPTH_ATTACHMENT);
|
||||
|
||||
// Create render targets.
|
||||
const int level = 0;
|
||||
|
||||
Handle<HwRenderTarget> srcRenderTarget = api.createRenderTarget(
|
||||
TargetBufferFlags::COLOR | TargetBufferFlags::DEPTH,
|
||||
kSrcTexWidth >> level, kSrcTexHeight >> level, 1,
|
||||
{{ srcColorTexture, level }},
|
||||
{ srcDepthTexture, level }, {});
|
||||
|
||||
Handle<HwRenderTarget> dstRenderTarget = api.createRenderTarget(
|
||||
TargetBufferFlags::COLOR | TargetBufferFlags::DEPTH,
|
||||
kDstTexWidth >> level, kDstTexHeight >> level, 1,
|
||||
{{ dstColorTexture, level }},
|
||||
{ dstDepthTexture, level }, {});
|
||||
|
||||
// Prep for rendering.
|
||||
RenderPassParams params = {};
|
||||
params.flags.clear = TargetBufferFlags::COLOR | TargetBufferFlags::DEPTH;
|
||||
params.clearColor = float4(1, 1, 0, 1);
|
||||
params.clearDepth = 1.0;
|
||||
params.viewport.width = kSrcTexWidth;
|
||||
params.viewport.height = kSrcTexHeight;
|
||||
|
||||
PipelineState state = {};
|
||||
state.rasterState.colorWrite = true;
|
||||
state.rasterState.depthWrite = true;
|
||||
state.rasterState.depthFunc = RasterState::DepthFunc::L;
|
||||
state.rasterState.culling = RasterState::CullingMode::NONE;
|
||||
state.program = program;
|
||||
auto ubuffer = api.createBufferObject(sizeof(MaterialParams),
|
||||
BufferObjectBinding::UNIFORM, BufferUsage::STATIC);
|
||||
api.makeCurrent(swapChain, swapChain);
|
||||
api.beginFrame(0, 0);
|
||||
api.bindUniformBuffer(0, ubuffer);
|
||||
|
||||
// Draw red triangle into srcRenderTarget.
|
||||
uploadUniforms(api, ubuffer, {
|
||||
.color = float4(1, 0, 0, 1),
|
||||
.scale = float4(1, 1, 0.5, 0),
|
||||
});
|
||||
api.beginRenderPass(srcRenderTarget, params);
|
||||
api.draw(state, triangle->getRenderPrimitive(), 1);
|
||||
api.endRenderPass();
|
||||
api.endFrame(0);
|
||||
|
||||
// Copy over the color buffer and the depth buffer.
|
||||
api.blit(TargetBufferFlags::COLOR | TargetBufferFlags::DEPTH, dstRenderTarget,
|
||||
{0, 0, kDstTexWidth, kDstTexHeight}, srcRenderTarget,
|
||||
{0, 0, kSrcTexWidth, kSrcTexHeight}, SamplerMagFilter::LINEAR);
|
||||
|
||||
// Draw a larger blue triangle into dstRenderTarget. We carefully place it below the red
|
||||
// triangle in order to exercise depth testing.
|
||||
api.beginFrame(0, 0);
|
||||
params.viewport.width = kDstTexWidth;
|
||||
params.viewport.height = kDstTexHeight;
|
||||
params.flags.clear = TargetBufferFlags::NONE;
|
||||
uploadUniforms(api, ubuffer, {
|
||||
.color = float4(0, 0, 1, 1),
|
||||
.scale = float4(1.2, 1.2, 0.75, 0),
|
||||
});
|
||||
api.beginRenderPass(dstRenderTarget, params);
|
||||
api.draw(state, triangle->getRenderPrimitive(), 1);
|
||||
api.endRenderPass();
|
||||
api.endFrame(0);
|
||||
|
||||
// Grab a screenshot.
|
||||
ScreenshotParams sparams { kDstTexWidth, kDstTexHeight, "DepthMinify.png" };
|
||||
api.beginFrame(0, 0);
|
||||
dumpScreenshot(api, dstRenderTarget, &sparams);
|
||||
api.commit(swapChain);
|
||||
api.endFrame(0);
|
||||
|
||||
// Wait for the ReadPixels result to come back.
|
||||
api.finish();
|
||||
executeCommands();
|
||||
getDriver().purge();
|
||||
|
||||
// Check if the image matches perfectly to our golden run.
|
||||
const uint32_t expected = 0x92b6f5c1;
|
||||
printf("Computed hash is 0x%8.8x, Expected 0x%8.8x\n", sparams.pixelHashResult, expected);
|
||||
EXPECT_TRUE(sparams.pixelHashResult == expected);
|
||||
|
||||
// Cleanup.
|
||||
api.destroyBufferObject(ubuffer);
|
||||
api.destroyProgram(program);
|
||||
api.destroyTexture(srcColorTexture);
|
||||
api.destroyTexture(dstColorTexture);
|
||||
api.destroyTexture(srcDepthTexture);
|
||||
api.destroyTexture(dstDepthTexture);
|
||||
api.destroySwapChain(swapChain);
|
||||
api.destroyRenderTarget(srcRenderTarget);
|
||||
api.destroyRenderTarget(dstRenderTarget);
|
||||
delete triangle;
|
||||
executeCommands();
|
||||
}
|
||||
|
||||
TEST_F(BackendTest, ColorResolve) {
|
||||
auto& api = getDriverApi();
|
||||
|
||||
@@ -345,82 +550,85 @@ TEST_F(BackendTest, ColorResolve) {
|
||||
constexpr auto kColorTexFormat = TextureFormat::RGBA8;
|
||||
constexpr int kSampleCount = 4;
|
||||
|
||||
// Create a SwapChain and make it current. We don't really use it so the res doesn't matter.
|
||||
auto swapChain = api.createSwapChainHeadless(256, 256, 0);
|
||||
api.makeCurrent(swapChain, swapChain);
|
||||
|
||||
// Create a program.
|
||||
ProgramHandle program;
|
||||
{
|
||||
ShaderGenerator shaderGen(triangleVs, triangleFs, sBackend, sIsMobilePlatform);
|
||||
Program prog = shaderGen.getProgram(api);
|
||||
Program::Sampler psamplers[] = { utils::CString("tex"), 0 };
|
||||
prog.setSamplerGroup(0, ShaderStageFlags::ALL_SHADER_STAGE_FLAGS, psamplers, sizeof(psamplers) / sizeof(psamplers[0]));
|
||||
prog.uniformBlockBindings({{"params", 1}});
|
||||
program = api.createProgram(std::move(prog));
|
||||
}
|
||||
|
||||
// Create a VertexBuffer, IndexBuffer, and RenderPrimitive.
|
||||
TrianglePrimitive const triangle(api);
|
||||
TrianglePrimitive* triangle = new TrianglePrimitive(api);
|
||||
|
||||
// Create 4-sample texture.
|
||||
Handle<HwTexture> const srcColorTexture = api.createTexture(
|
||||
Handle<HwTexture> srcColorTexture = api.createTexture(
|
||||
SamplerType::SAMPLER_2D, 1, kColorTexFormat, kSampleCount, kSrcTexWidth, kSrcTexHeight, 1,
|
||||
TextureUsage::COLOR_ATTACHMENT);
|
||||
|
||||
// Create 1-sample texture.
|
||||
Handle<HwTexture> const dstColorTexture = api.createTexture(
|
||||
Handle<HwTexture> dstColorTexture = api.createTexture(
|
||||
SamplerType::SAMPLER_2D, 1, kColorTexFormat, 1, kDstTexWidth, kDstTexHeight, 1,
|
||||
TextureUsage::SAMPLEABLE | TextureUsage::COLOR_ATTACHMENT);
|
||||
|
||||
// Create a 4-sample render target with the 4-sample texture.
|
||||
Handle<HwRenderTarget> const srcRenderTarget = api.createRenderTarget(
|
||||
TargetBufferFlags::COLOR, kSrcTexWidth, kSrcTexHeight, kSampleCount,
|
||||
{{ srcColorTexture }}, {}, {});
|
||||
Handle<HwRenderTarget> srcRenderTarget = api.createRenderTarget(
|
||||
TargetBufferFlags::COLOR, kSrcTexWidth, kSrcTexHeight, kSampleCount,{{ srcColorTexture }}, {}, {});
|
||||
|
||||
// Create a 1-sample render target with the 1-sample texture.
|
||||
Handle<HwRenderTarget> const dstRenderTarget = api.createRenderTarget(
|
||||
TargetBufferFlags::COLOR, kDstTexWidth, kDstTexHeight, 1,
|
||||
{{ dstColorTexture }}, {}, {});
|
||||
Handle<HwRenderTarget> dstRenderTarget = api.createRenderTarget(
|
||||
TargetBufferFlags::COLOR, kDstTexWidth, kDstTexHeight, 1, {{ dstColorTexture }}, {}, {});
|
||||
|
||||
// Prep for rendering.
|
||||
RenderPassParams params = {};
|
||||
params.flags.clear = TargetBufferFlags::COLOR;
|
||||
params.flags.discardStart = TargetBufferFlags::ALL;
|
||||
params.flags.discardEnd = TargetBufferFlags::NONE;
|
||||
params.clearColor = float4(1, 1, 0, 1);
|
||||
params.viewport.width = kSrcTexWidth;
|
||||
params.viewport.height = kSrcTexHeight;
|
||||
|
||||
PipelineState state = {};
|
||||
state.program = program;
|
||||
state.rasterState.colorWrite = true;
|
||||
state.rasterState.depthWrite = false;
|
||||
state.rasterState.depthFunc = RasterState::DepthFunc::A;
|
||||
state.rasterState.culling = CullingMode::NONE;
|
||||
|
||||
state.rasterState.culling = RasterState::CullingMode::NONE;
|
||||
state.program = program;
|
||||
auto ubuffer = api.createBufferObject(sizeof(MaterialParams),
|
||||
BufferObjectBinding::UNIFORM, BufferUsage::STATIC);
|
||||
api.makeCurrent(swapChain, swapChain);
|
||||
api.beginFrame(0, 0);
|
||||
api.bindUniformBuffer(0, ubuffer);
|
||||
|
||||
// Draw red triangle into srcRenderTarget.
|
||||
uploadUniforms(api, ubuffer, {
|
||||
.color = float4(1, 0, 0, 1),
|
||||
.scale = float4(1, 1, 0.5, 0),
|
||||
});
|
||||
|
||||
// FIXME: on Metal this triangle is not drawn. Can't understand why.
|
||||
api.beginFrame(0, 0);
|
||||
api.beginRenderPass(srcRenderTarget, params);
|
||||
api.bindUniformBuffer(0, ubuffer);
|
||||
api.draw(state, triangle.getRenderPrimitive(), 1);
|
||||
api.endRenderPass();
|
||||
api.beginRenderPass(srcRenderTarget, params);
|
||||
api.draw(state, triangle->getRenderPrimitive(), 1);
|
||||
api.endRenderPass();
|
||||
api.endFrame(0);
|
||||
|
||||
// Resolve the MSAA render target into the single-sample render target.
|
||||
api.blitDEPRECATED(TargetBufferFlags::COLOR,
|
||||
dstRenderTarget, {0, 0, kDstTexWidth, kDstTexHeight},
|
||||
srcRenderTarget, {0, 0, kSrcTexWidth, kSrcTexHeight},
|
||||
SamplerMagFilter::NEAREST);
|
||||
api.blit(TargetBufferFlags::COLOR, dstRenderTarget,
|
||||
{0, 0, kDstTexWidth, kDstTexHeight}, srcRenderTarget,
|
||||
{0, 0, kSrcTexWidth, kSrcTexHeight}, SamplerMagFilter::LINEAR);
|
||||
|
||||
// Grab a screenshot.
|
||||
ScreenshotParams sparams{ kDstTexWidth, kDstTexHeight, "ColorResolve.png" };
|
||||
ScreenshotParams sparams { kDstTexWidth, kDstTexHeight, "ColorResolve.png" };
|
||||
api.beginFrame(0, 0);
|
||||
dumpScreenshot(api, dstRenderTarget, &sparams);
|
||||
api.commit(swapChain);
|
||||
api.endFrame(0);
|
||||
|
||||
// Wait for the ReadPixels result to come back.
|
||||
flushAndWait();
|
||||
api.finish();
|
||||
executeCommands();
|
||||
getDriver().purge();
|
||||
|
||||
// Check if the image matches perfectly to our golden run.
|
||||
const uint32_t expected = 0xebfac2ef;
|
||||
@@ -432,9 +640,149 @@ TEST_F(BackendTest, ColorResolve) {
|
||||
api.destroyProgram(program);
|
||||
api.destroyTexture(srcColorTexture);
|
||||
api.destroyTexture(dstColorTexture);
|
||||
api.destroySwapChain(swapChain);
|
||||
api.destroyRenderTarget(srcRenderTarget);
|
||||
api.destroyRenderTarget(dstRenderTarget);
|
||||
flushAndWait();
|
||||
delete triangle;
|
||||
executeCommands();
|
||||
}
|
||||
|
||||
TEST_F(BackendTest, DepthResolve) {
|
||||
auto& api = getDriverApi();
|
||||
|
||||
constexpr int kSrcTexWidth = 256;
|
||||
constexpr int kSrcTexHeight = 256;
|
||||
constexpr int kDstTexWidth = 256;
|
||||
constexpr int kDstTexHeight = 256;
|
||||
constexpr auto kColorTexFormat = TextureFormat::RGBA8;
|
||||
constexpr auto kDepthTexFormat = TextureFormat::DEPTH24;
|
||||
constexpr int kSampleCount = 4;
|
||||
|
||||
// Create a SwapChain and make it current. We don't really use it so the res doesn't matter.
|
||||
auto swapChain = api.createSwapChainHeadless(256, 256, 0);
|
||||
api.makeCurrent(swapChain, swapChain);
|
||||
|
||||
// Create a program.
|
||||
ProgramHandle program;
|
||||
{
|
||||
ShaderGenerator shaderGen(triangleVs, triangleFs, sBackend, sIsMobilePlatform);
|
||||
Program prog = shaderGen.getProgram(api);
|
||||
Program::Sampler psamplers[] = { utils::CString("tex"), 0 };
|
||||
prog.setSamplerGroup(0, ShaderStageFlags::ALL_SHADER_STAGE_FLAGS, psamplers, sizeof(psamplers) / sizeof(psamplers[0]));
|
||||
prog.uniformBlockBindings({{"params", 1}});
|
||||
program = api.createProgram(std::move(prog));
|
||||
}
|
||||
|
||||
// Create a VertexBuffer, IndexBuffer, and RenderPrimitive.
|
||||
TrianglePrimitive* triangle = new TrianglePrimitive(api);
|
||||
|
||||
// Create 4-sample textures.
|
||||
Handle<HwTexture> srcColorTexture = api.createTexture(
|
||||
SamplerType::SAMPLER_2D, 1, kColorTexFormat, kSampleCount, kSrcTexWidth, kSrcTexHeight, 1,
|
||||
TextureUsage::COLOR_ATTACHMENT);
|
||||
|
||||
Handle<HwTexture> srcDepthTexture = api.createTexture(
|
||||
SamplerType::SAMPLER_2D, 1, kDepthTexFormat, kSampleCount, kSrcTexWidth, kSrcTexHeight, 1,
|
||||
TextureUsage::DEPTH_ATTACHMENT);
|
||||
|
||||
// Create 1-sample textures.
|
||||
Handle<HwTexture> dstColorTexture = api.createTexture(
|
||||
SamplerType::SAMPLER_2D, 1, kColorTexFormat, 1, kDstTexWidth, kDstTexHeight, 1,
|
||||
TextureUsage::SAMPLEABLE | TextureUsage::COLOR_ATTACHMENT);
|
||||
|
||||
Handle<HwTexture> dstDepthTexture = api.createTexture(
|
||||
SamplerType::SAMPLER_2D, 1, kDepthTexFormat, 1, kDstTexWidth, kDstTexHeight, 1,
|
||||
TextureUsage::DEPTH_ATTACHMENT);
|
||||
|
||||
// Create a 4-sample render target with 4-sample textures.
|
||||
Handle<HwRenderTarget> srcRenderTarget = api.createRenderTarget(
|
||||
TargetBufferFlags::COLOR | TargetBufferFlags::DEPTH, kSrcTexWidth, kSrcTexHeight,
|
||||
kSampleCount, {{ srcColorTexture }}, { srcDepthTexture }, {});
|
||||
|
||||
// Create a 1-sample render target with 1-sample textures.
|
||||
Handle<HwRenderTarget> dstRenderTarget = api.createRenderTarget(
|
||||
TargetBufferFlags::COLOR | TargetBufferFlags::DEPTH, kDstTexWidth, kDstTexHeight,
|
||||
1, {{ dstColorTexture }}, { dstDepthTexture }, {});
|
||||
|
||||
// Prep for rendering.
|
||||
RenderPassParams params = {};
|
||||
params.flags.clear = TargetBufferFlags::COLOR | TargetBufferFlags::DEPTH;
|
||||
params.clearColor = float4(1, 1, 0, 1);
|
||||
params.clearDepth = 1.0;
|
||||
params.flags.discardEnd = TargetBufferFlags::NONE;
|
||||
params.viewport.width = kSrcTexWidth;
|
||||
params.viewport.height = kSrcTexHeight;
|
||||
|
||||
PipelineState state = {};
|
||||
state.rasterState.colorWrite = true;
|
||||
state.rasterState.depthWrite = true;
|
||||
state.rasterState.depthFunc = RasterState::DepthFunc::L;
|
||||
state.rasterState.culling = RasterState::CullingMode::NONE;
|
||||
state.program = program;
|
||||
auto ubuffer = api.createBufferObject(sizeof(MaterialParams),
|
||||
BufferObjectBinding::UNIFORM, BufferUsage::STATIC);
|
||||
api.makeCurrent(swapChain, swapChain);
|
||||
api.beginFrame(0, 0);
|
||||
api.bindUniformBuffer(0, ubuffer);
|
||||
|
||||
// Draw red triangle into srcRenderTarget.
|
||||
uploadUniforms(api, ubuffer, {
|
||||
.color = float4(1, 0, 0, 1),
|
||||
.scale = float4(1, 1, 0.5, 0),
|
||||
});
|
||||
api.beginRenderPass(srcRenderTarget, params);
|
||||
api.draw(state, triangle->getRenderPrimitive(), 1);
|
||||
api.endRenderPass();
|
||||
api.endFrame(0);
|
||||
|
||||
// Resolve the MSAA color and depth buffers into the single-sample render target.
|
||||
api.blit(TargetBufferFlags::COLOR | TargetBufferFlags::DEPTH, dstRenderTarget,
|
||||
{0, 0, kDstTexWidth, kDstTexHeight}, srcRenderTarget,
|
||||
{0, 0, kSrcTexWidth, kSrcTexHeight}, SamplerMagFilter::LINEAR);
|
||||
|
||||
// Draw a larger blue triangle into dstRenderTarget. We carefully place it below the red
|
||||
// triangle in order to exercise depth testing.
|
||||
api.beginFrame(0, 0);
|
||||
params.viewport.width = kDstTexWidth;
|
||||
params.viewport.height = kDstTexHeight;
|
||||
params.flags.clear = TargetBufferFlags::NONE;
|
||||
uploadUniforms(api, ubuffer, {
|
||||
.color = float4(0, 0, 1, 1),
|
||||
.scale = float4(1.2, 1.2, 0.75, 0),
|
||||
});
|
||||
api.beginRenderPass(dstRenderTarget, params);
|
||||
api.draw(state, triangle->getRenderPrimitive(), 1);
|
||||
api.endRenderPass();
|
||||
|
||||
// Grab a screenshot.
|
||||
ScreenshotParams sparams { kDstTexWidth, kDstTexHeight, "DepthResolve.png" };
|
||||
api.beginFrame(0, 0);
|
||||
dumpScreenshot(api, dstRenderTarget, &sparams);
|
||||
api.commit(swapChain);
|
||||
api.endFrame(0);
|
||||
|
||||
// Wait for the ReadPixels result to come back.
|
||||
api.finish();
|
||||
executeCommands();
|
||||
getDriver().purge();
|
||||
|
||||
// Check if the image matches perfectly to our golden run.
|
||||
const uint32_t expected = 0x5a38e6ba;
|
||||
printf("Computed hash is 0x%8.8x, Expected 0x%8.8x\n", sparams.pixelHashResult, expected);
|
||||
EXPECT_TRUE(sparams.pixelHashResult == expected);
|
||||
|
||||
// Cleanup.
|
||||
api.destroyBufferObject(ubuffer);
|
||||
api.destroyProgram(program);
|
||||
api.destroyTexture(srcColorTexture);
|
||||
api.destroyTexture(dstColorTexture);
|
||||
api.destroyTexture(srcDepthTexture);
|
||||
api.destroyTexture(dstDepthTexture);
|
||||
api.destroySwapChain(swapChain);
|
||||
api.destroyRenderTarget(srcRenderTarget);
|
||||
api.destroyRenderTarget(dstRenderTarget);
|
||||
delete triangle;
|
||||
executeCommands();
|
||||
}
|
||||
|
||||
TEST_F(BackendTest, Blit2DTextureArray) {
|
||||
@@ -479,7 +827,7 @@ TEST_F(BackendTest, Blit2DTextureArray) {
|
||||
|
||||
// Do a blit from kSrcTexLayer of the source RT to kDstTexLayer of the destination RT.
|
||||
const int srcLevel = 0;
|
||||
api.blitDEPRECATED(TargetBufferFlags::COLOR0, dstRenderTarget,
|
||||
api.blit(TargetBufferFlags::COLOR0, dstRenderTarget,
|
||||
{0, 0, kDstTexWidth, kDstTexHeight}, srcRenderTarget,
|
||||
{0, 0, kSrcTexWidth >> srcLevel, kSrcTexHeight >> srcLevel}, SamplerMagFilter::LINEAR);
|
||||
|
||||
@@ -570,7 +918,7 @@ TEST_F(BackendTest, BlitRegion) {
|
||||
api.createRenderTarget(TargetBufferFlags::COLOR, kDstTexWidth >> kDstLevel,
|
||||
kDstTexHeight >> kDstLevel, 1, {dstTexture, kDstLevel, 0}, {}, {});
|
||||
|
||||
api.blitDEPRECATED(TargetBufferFlags::COLOR0, dstRenderTarget, dstRect, srcRenderTarget, srcRect,
|
||||
api.blit(TargetBufferFlags::COLOR0, dstRenderTarget, dstRect, srcRenderTarget, srcRect,
|
||||
SamplerMagFilter::LINEAR);
|
||||
|
||||
// Push through an empty frame to allow the texture to upload and the blit to execute.
|
||||
@@ -657,7 +1005,7 @@ TEST_F(BackendTest, BlitRegionToSwapChain) {
|
||||
|
||||
api.beginFrame(0, 0);
|
||||
|
||||
api.blitDEPRECATED(TargetBufferFlags::COLOR0, dstRenderTarget,
|
||||
api.blit(TargetBufferFlags::COLOR0, dstRenderTarget,
|
||||
dstRect, srcRenderTargets[srcLevel],
|
||||
srcRect, SamplerMagFilter::LINEAR);
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ layout(location = 0) out vec4 fragColor;
|
||||
|
||||
// Filament's Vulkan backend requires a descriptor set index of 1 for all samplers.
|
||||
// This parameter is ignored for other backends.
|
||||
layout(location = 0, set = 1) uniform sampler2D test_tex;
|
||||
layout(location = 0, set = 1) uniform sampler2D tex;
|
||||
|
||||
uniform Params {
|
||||
highp float fbWidth;
|
||||
@@ -61,7 +61,7 @@ uniform Params {
|
||||
void main() {
|
||||
vec2 fbsize = vec2(params.fbWidth, params.fbHeight);
|
||||
vec2 uv = (gl_FragCoord.xy + 0.5) / fbsize;
|
||||
fragColor = textureLod(test_tex, uv, params.sourceLevel);
|
||||
fragColor = textureLod(tex, uv, params.sourceLevel);
|
||||
})";
|
||||
|
||||
static uint32_t sPixelHashResult = 0;
|
||||
@@ -112,7 +112,6 @@ static void dumpScreenshot(DriverApi& dapi, Handle<HwRenderTarget> rt) {
|
||||
std::ofstream pngstrm("feedback.png", std::ios::binary | std::ios::trunc);
|
||||
ImageEncoder::encode(pngstrm, ImageEncoder::Format::PNG, image, "", "feedback.png");
|
||||
#endif
|
||||
free(buffer);
|
||||
};
|
||||
PixelBufferDescriptor pb(buffer, size, PixelDataFormat::RGBA, PixelDataType::UBYTE, cb);
|
||||
dapi.readPixels(rt, 0, 0, kTexWidth, kTexHeight, std::move(pb));
|
||||
@@ -134,24 +133,24 @@ TEST_F(BackendTest, FeedbackLoops) {
|
||||
// Create a program.
|
||||
ProgramHandle program;
|
||||
{
|
||||
SamplerInterfaceBlock const sib = filament::SamplerInterfaceBlock::Builder()
|
||||
.name("Test")
|
||||
SamplerInterfaceBlock sib = filament::SamplerInterfaceBlock::Builder()
|
||||
.name("backend_test_sib")
|
||||
.stageFlags(backend::ShaderStageFlags::ALL_SHADER_STAGE_FLAGS)
|
||||
.add( {{"tex", SamplerType::SAMPLER_2D, SamplerFormat::FLOAT, Precision::HIGH }} )
|
||||
.build();
|
||||
ShaderGenerator shaderGen(fullscreenVs, fullscreenFs, sBackend, sIsMobilePlatform, &sib);
|
||||
Program prog = shaderGen.getProgram(api);
|
||||
Program::Sampler psamplers[] = { utils::CString("test_tex"), 0 };
|
||||
Program::Sampler psamplers[] = { utils::CString("tex"), 0 };
|
||||
prog.setSamplerGroup(0, ShaderStageFlags::ALL_SHADER_STAGE_FLAGS, psamplers, sizeof(psamplers) / sizeof(psamplers[0]));
|
||||
prog.uniformBlockBindings({{"params", 1}});
|
||||
program = api.createProgram(std::move(prog));
|
||||
}
|
||||
|
||||
TrianglePrimitive const triangle(getDriverApi());
|
||||
TrianglePrimitive triangle(getDriverApi());
|
||||
|
||||
// Create a texture.
|
||||
auto usage = TextureUsage::COLOR_ATTACHMENT | TextureUsage::SAMPLEABLE;
|
||||
Handle<HwTexture> const texture = api.createTexture(
|
||||
Handle<HwTexture> texture = api.createTexture(
|
||||
SamplerType::SAMPLER_2D, kNumLevels, kTexFormat, 1, kTexWidth, kTexHeight, 1, usage);
|
||||
|
||||
// Create a RenderTarget for each miplevel.
|
||||
|
||||
@@ -174,41 +174,6 @@ static const char* getSamplerTypeName(TextureFormat textureFormat) {
|
||||
default:
|
||||
return "sampler2D";
|
||||
}
|
||||
|
||||
}
|
||||
static SamplerFormat getSamplerFormat(TextureFormat textureFormat) {
|
||||
switch (textureFormat) {
|
||||
case TextureFormat::R8UI:
|
||||
case TextureFormat::R16UI:
|
||||
case TextureFormat::RG8UI:
|
||||
case TextureFormat::RGB8UI:
|
||||
case TextureFormat::R32UI:
|
||||
case TextureFormat::RG16UI:
|
||||
case TextureFormat::RGBA8UI:
|
||||
case TextureFormat::RGB16UI:
|
||||
case TextureFormat::RG32UI:
|
||||
case TextureFormat::RGBA16UI:
|
||||
case TextureFormat::RGB32UI:
|
||||
case TextureFormat::RGBA32UI:
|
||||
return SamplerFormat::UINT;
|
||||
|
||||
case TextureFormat::R8I:
|
||||
case TextureFormat::R16I:
|
||||
case TextureFormat::RG8I:
|
||||
case TextureFormat::RGB8I:
|
||||
case TextureFormat::R32I:
|
||||
case TextureFormat::RG16I:
|
||||
case TextureFormat::RGBA8I:
|
||||
case TextureFormat::RGB16I:
|
||||
case TextureFormat::RG32I:
|
||||
case TextureFormat::RGBA16I:
|
||||
case TextureFormat::RGB32I:
|
||||
case TextureFormat::RGBA32I:
|
||||
return SamplerFormat::INT;
|
||||
|
||||
default:
|
||||
return SamplerFormat::FLOAT;
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(BackendTest, UpdateImage2D) {
|
||||
@@ -266,10 +231,9 @@ TEST_F(BackendTest, UpdateImage2D) {
|
||||
|
||||
// Test integer format uploads.
|
||||
// TODO: These cases fail on OpenGL and Vulkan.
|
||||
// TODO: These cases now also fail on Metal, but at some point previously worked.
|
||||
testCases.emplace_back("RGB_INTEGER, UBYTE -> RGB8UI", PixelDataFormat::RGB_INTEGER, PixelDataType::UBYTE, TextureFormat::RGB8UI);
|
||||
testCases.emplace_back("RGB_INTEGER, USHORT -> RGB16UI", PixelDataFormat::RGB_INTEGER, PixelDataType::USHORT, TextureFormat::RGB16UI);
|
||||
testCases.emplace_back("RGB_INTEGER, INT -> RGB32I", PixelDataFormat::RGB_INTEGER, PixelDataType::INT, TextureFormat::RGB32I);
|
||||
testCases.emplace_back("RGB_INTEGER, UBYTE -> RGB8UI", PixelDataFormat::RGB_INTEGER, PixelDataType::UBYTE, TextureFormat::RGB8UI);
|
||||
testCases.emplace_back("RGB_INTEGER, USHORT -> RGB16UI", PixelDataFormat::RGB_INTEGER, PixelDataType::USHORT, TextureFormat::RGB16UI);
|
||||
testCases.emplace_back("RGB_INTEGER, INT -> RGB32I", PixelDataFormat::RGB_INTEGER, PixelDataType::INT, TextureFormat::RGB32I);
|
||||
|
||||
// Test uploads with buffer padding.
|
||||
// TODO: Vulkan crashes with "Assertion failed: (offset + size <= allocationSize)"
|
||||
@@ -297,45 +261,48 @@ TEST_F(BackendTest, UpdateImage2D) {
|
||||
auto defaultRenderTarget = api.createDefaultRenderTarget(0);
|
||||
|
||||
// Create a program.
|
||||
SamplerInterfaceBlock const sib = filament::SamplerInterfaceBlock::Builder()
|
||||
SamplerInterfaceBlock sib = filament::SamplerInterfaceBlock::Builder()
|
||||
.name("Test")
|
||||
.stageFlags(backend::ShaderStageFlags::ALL_SHADER_STAGE_FLAGS)
|
||||
.add( {{"tex", SamplerType::SAMPLER_2D, getSamplerFormat(t.textureFormat), Precision::HIGH }} )
|
||||
.add( {{"tex", SamplerType::SAMPLER_2D, SamplerFormat::FLOAT, Precision::HIGH }} )
|
||||
.build();
|
||||
|
||||
std::string const fragment = stringReplace("{samplerType}",
|
||||
ProgramHandle program;
|
||||
std::string fragment = stringReplace("{samplerType}",
|
||||
getSamplerTypeName(t.textureFormat), fragmentTemplate);
|
||||
ShaderGenerator shaderGen(vertex, fragment, sBackend, sIsMobilePlatform, &sib);
|
||||
Program prog = shaderGen.getProgram(api);
|
||||
Program::Sampler psamplers[] = { utils::CString("test_tex"), 0 };
|
||||
Program::Sampler psamplers[] = { utils::CString("tex"), 0 };
|
||||
prog.setSamplerGroup(0, ShaderStageFlags::ALL_SHADER_STAGE_FLAGS, psamplers, sizeof(psamplers) / sizeof(psamplers[0]));
|
||||
ProgramHandle const program = api.createProgram(std::move(prog));
|
||||
program = api.createProgram(std::move(prog));
|
||||
|
||||
// Create a Texture.
|
||||
auto usage = TextureUsage::SAMPLEABLE | TextureUsage::UPLOADABLE;
|
||||
Handle<HwTexture> const texture = api.createTexture(SamplerType::SAMPLER_2D, 1,
|
||||
auto usage = TextureUsage::SAMPLEABLE;
|
||||
Handle<HwTexture> texture = api.createTexture(SamplerType::SAMPLER_2D, 1,
|
||||
t.textureFormat, 1, 512, 512, 1u, usage);
|
||||
|
||||
// Upload some pixel data.
|
||||
if (t.uploadSubregions) {
|
||||
api.update3DImage(texture, 0, 0, 0, 0, 256, 256, 1,
|
||||
checkerboardPixelBuffer(t.pixelFormat, t.pixelType, 256, t.bufferPadding));
|
||||
api.update3DImage(texture, 0, 256, 0, 0, 256, 256, 1,
|
||||
checkerboardPixelBuffer(t.pixelFormat, t.pixelType, 256, t.bufferPadding));
|
||||
api.update3DImage(texture, 0, 0, 256, 0, 256, 256, 1,
|
||||
checkerboardPixelBuffer(t.pixelFormat, t.pixelType, 256, t.bufferPadding));
|
||||
api.update3DImage(texture, 0, 256, 256, 0, 256, 256, 1,
|
||||
checkerboardPixelBuffer(t.pixelFormat, t.pixelType, 256, t.bufferPadding));
|
||||
const auto& pf = t.pixelFormat;
|
||||
const auto& pt = t.pixelType;
|
||||
PixelBufferDescriptor subregion1 = checkerboardPixelBuffer(pf, pt, 256, t.bufferPadding);
|
||||
PixelBufferDescriptor subregion2 = checkerboardPixelBuffer(pf, pt, 256, t.bufferPadding);
|
||||
PixelBufferDescriptor subregion3 = checkerboardPixelBuffer(pf, pt, 256, t.bufferPadding);
|
||||
PixelBufferDescriptor subregion4 = checkerboardPixelBuffer(pf, pt, 256, t.bufferPadding);
|
||||
api.update3DImage(texture, 0, 0, 0, 0, 256, 256, 1, std::move(subregion1));
|
||||
api.update3DImage(texture, 0, 256, 0, 0, 256, 256, 1, std::move(subregion2));
|
||||
api.update3DImage(texture, 0, 0, 256, 0, 256, 256, 1, std::move(subregion3));
|
||||
api.update3DImage(texture, 0, 256, 256, 0, 256, 256, 1, std::move(subregion4));
|
||||
} else {
|
||||
api.update3DImage(texture, 0, 0, 0, 0, 512, 512, 1,
|
||||
checkerboardPixelBuffer(t.pixelFormat, t.pixelType, 512, t.bufferPadding));
|
||||
PixelBufferDescriptor descriptor
|
||||
= checkerboardPixelBuffer(t.pixelFormat, t.pixelType, 512, t.bufferPadding);
|
||||
api.update3DImage(texture, 0, 0, 0, 0, 512, 512, 1, std::move(descriptor));
|
||||
}
|
||||
|
||||
SamplerGroup samplers(1);
|
||||
samplers.setSampler(0, { texture, {
|
||||
.filterMag = SamplerMagFilter::NEAREST,
|
||||
.filterMin = SamplerMinFilter::NEAREST_MIPMAP_NEAREST } });
|
||||
|
||||
SamplerParams sparams = {};
|
||||
sparams.filterMag = SamplerMagFilter::LINEAR;
|
||||
sparams.filterMin = SamplerMinFilter::LINEAR_MIPMAP_NEAREST;
|
||||
samplers.setSampler(0, { texture, sparams });
|
||||
auto sgroup = api.createSamplerGroup(samplers.getSize(), utils::FixedSizeString<32>("Test"));
|
||||
api.updateSamplerGroup(sgroup, samplers.toBufferDescriptor(api));
|
||||
|
||||
@@ -345,6 +312,7 @@ TEST_F(BackendTest, UpdateImage2D) {
|
||||
|
||||
readPixelsAndAssertHash(t.name, 512, 512, defaultRenderTarget, expectedHash);
|
||||
|
||||
api.flush();
|
||||
api.commit(swapChain);
|
||||
api.endFrame(0);
|
||||
|
||||
@@ -352,21 +320,25 @@ TEST_F(BackendTest, UpdateImage2D) {
|
||||
api.destroySwapChain(swapChain);
|
||||
api.destroyRenderTarget(defaultRenderTarget);
|
||||
api.destroyTexture(texture);
|
||||
|
||||
// This ensures all driver commands have finished before exiting the test.
|
||||
api.finish();
|
||||
}
|
||||
|
||||
api.finish();
|
||||
api.stopCapture();
|
||||
|
||||
flushAndWait();
|
||||
executeCommands();
|
||||
|
||||
getDriver().purge();
|
||||
}
|
||||
|
||||
TEST_F(BackendTest, UpdateImageSRGB) {
|
||||
auto& api = getDriverApi();
|
||||
api.startCapture();
|
||||
|
||||
PixelDataFormat const pixelFormat = PixelDataFormat::RGBA;
|
||||
PixelDataType const pixelType = PixelDataType::UBYTE;
|
||||
TextureFormat const textureFormat = TextureFormat::SRGB8_A8;
|
||||
PixelDataFormat pixelFormat = PixelDataFormat::RGB;
|
||||
PixelDataType pixelType = PixelDataType::UBYTE;
|
||||
TextureFormat textureFormat = TextureFormat::SRGB8_A8;
|
||||
|
||||
// Create a platform-specific SwapChain and make it current.
|
||||
auto swapChain = createSwapChain();
|
||||
@@ -374,22 +346,22 @@ TEST_F(BackendTest, UpdateImageSRGB) {
|
||||
auto defaultRenderTarget = api.createDefaultRenderTarget(0);
|
||||
|
||||
// Create a program.
|
||||
SamplerInterfaceBlock const sib = filament::SamplerInterfaceBlock::Builder()
|
||||
SamplerInterfaceBlock sib = filament::SamplerInterfaceBlock::Builder()
|
||||
.name("Test")
|
||||
.stageFlags(backend::ShaderStageFlags::ALL_SHADER_STAGE_FLAGS)
|
||||
.add( {{"tex", SamplerType::SAMPLER_2D, SamplerFormat::FLOAT, Precision::HIGH }} )
|
||||
.build();
|
||||
std::string const fragment = stringReplace("{samplerType}",
|
||||
std::string fragment = stringReplace("{samplerType}",
|
||||
getSamplerTypeName(textureFormat), fragmentTemplate);
|
||||
ShaderGenerator shaderGen(vertex, fragment, sBackend, sIsMobilePlatform, &sib);
|
||||
Program prog = shaderGen.getProgram(api);
|
||||
Program::Sampler psamplers[] = { utils::CString("test_tex"), 0 };
|
||||
Program::Sampler psamplers[] = { utils::CString("tex"), 0 };
|
||||
prog.setSamplerGroup(0, ShaderStageFlags::ALL_SHADER_STAGE_FLAGS, psamplers, sizeof(psamplers) / sizeof(psamplers[0]));
|
||||
ProgramHandle const program = api.createProgram(std::move(prog));
|
||||
ProgramHandle program = api.createProgram(std::move(prog));
|
||||
|
||||
// Create a texture.
|
||||
Handle<HwTexture> const texture = api.createTexture(SamplerType::SAMPLER_2D, 1,
|
||||
textureFormat, 1, 512, 512, 1, TextureUsage::SAMPLEABLE | TextureUsage::UPLOADABLE);
|
||||
Handle<HwTexture> texture = api.createTexture(SamplerType::SAMPLER_2D, 1,
|
||||
textureFormat, 1, 512, 512, 1, TextureUsage::SAMPLEABLE);
|
||||
|
||||
// Create image data.
|
||||
size_t components; int bpp;
|
||||
@@ -429,7 +401,7 @@ TEST_F(BackendTest, UpdateImageSRGB) {
|
||||
|
||||
renderTriangle(defaultRenderTarget, swapChain, program);
|
||||
|
||||
static const uint32_t expectedHash = 359858623;
|
||||
static const uint32_t expectedHash = 519370995;
|
||||
readPixelsAndAssertHash("UpdateImageSRGB", 512, 512, defaultRenderTarget, expectedHash);
|
||||
|
||||
api.flush();
|
||||
@@ -443,9 +415,12 @@ TEST_F(BackendTest, UpdateImageSRGB) {
|
||||
|
||||
// This ensures all driver commands have finished before exiting the test.
|
||||
api.finish();
|
||||
|
||||
api.stopCapture();
|
||||
|
||||
flushAndWait();
|
||||
executeCommands();
|
||||
|
||||
getDriver().purge();
|
||||
}
|
||||
|
||||
TEST_F(BackendTest, UpdateImageMipLevel) {
|
||||
@@ -465,26 +440,26 @@ TEST_F(BackendTest, UpdateImageMipLevel) {
|
||||
SamplerInterfaceBlock sib = filament::SamplerInterfaceBlock::Builder()
|
||||
.name("Test")
|
||||
.stageFlags(backend::ShaderStageFlags::ALL_SHADER_STAGE_FLAGS)
|
||||
.add( {{"tex", SamplerType::SAMPLER_2D, SamplerFormat::FLOAT, Precision::HIGH }} )
|
||||
.add( {{"tex", SamplerType::SAMPLER_3D, SamplerFormat::FLOAT, Precision::HIGH }} )
|
||||
.build();
|
||||
std::string const fragment = stringReplace("{samplerType}",
|
||||
std::string fragment = stringReplace("{samplerType}",
|
||||
getSamplerTypeName(textureFormat), fragmentUpdateImageMip);
|
||||
ShaderGenerator shaderGen(vertex, fragment, sBackend, sIsMobilePlatform, &sib);
|
||||
Program prog = shaderGen.getProgram(api);
|
||||
Program::Sampler psamplers[] = { utils::CString("test_tex"), 0 };
|
||||
Program::Sampler psamplers[] = { utils::CString("tex"), 0 };
|
||||
prog.setSamplerGroup(0, ShaderStageFlags::ALL_SHADER_STAGE_FLAGS, psamplers, sizeof(psamplers) / sizeof(psamplers[0]));
|
||||
ProgramHandle const program = api.createProgram(std::move(prog));
|
||||
ProgramHandle program = api.createProgram(std::move(prog));
|
||||
|
||||
// Create a texture with 3 mip levels.
|
||||
// Base level: 1024
|
||||
// Level 1: 512 <-- upload data and sample from this level
|
||||
// Level 2: 256
|
||||
Handle<HwTexture> texture = api.createTexture(SamplerType::SAMPLER_2D, 3,
|
||||
textureFormat, 1, 1024, 1024, 1, TextureUsage::SAMPLEABLE | TextureUsage::UPLOADABLE);
|
||||
textureFormat, 1, 1024, 1024, 1, TextureUsage::SAMPLEABLE);
|
||||
|
||||
// Create image data.
|
||||
PixelBufferDescriptor descriptor = checkerboardPixelBuffer(pixelFormat, pixelType, 512);
|
||||
api.update3DImage(texture, /* level*/ 1, 0, 0, 0, 512, 512, 1, std::move(descriptor));
|
||||
api.update3DImage(texture, 1, 0, 0, 0, 512, 512, 1, std::move(descriptor));
|
||||
|
||||
api.beginFrame(0, 0);
|
||||
|
||||
@@ -515,9 +490,12 @@ TEST_F(BackendTest, UpdateImageMipLevel) {
|
||||
|
||||
// This ensures all driver commands have finished before exiting the test.
|
||||
api.finish();
|
||||
|
||||
api.stopCapture();
|
||||
|
||||
flushAndWait();
|
||||
executeCommands();
|
||||
|
||||
getDriver().purge();
|
||||
}
|
||||
|
||||
TEST_F(BackendTest, UpdateImage3D) {
|
||||
@@ -528,7 +506,7 @@ TEST_F(BackendTest, UpdateImage3D) {
|
||||
PixelDataType pixelType = PixelDataType::FLOAT;
|
||||
TextureFormat textureFormat = TextureFormat::RGBA16F;
|
||||
SamplerType samplerType = SamplerType::SAMPLER_2D_ARRAY;
|
||||
TextureUsage usage = TextureUsage::SAMPLEABLE | TextureUsage::UPLOADABLE;
|
||||
TextureUsage usage = TextureUsage::SAMPLEABLE;
|
||||
|
||||
// Create a platform-specific SwapChain and make it current.
|
||||
auto swapChain = createSwapChain();
|
||||
@@ -539,15 +517,15 @@ TEST_F(BackendTest, UpdateImage3D) {
|
||||
SamplerInterfaceBlock sib = filament::SamplerInterfaceBlock::Builder()
|
||||
.name("Test")
|
||||
.stageFlags(backend::ShaderStageFlags::ALL_SHADER_STAGE_FLAGS)
|
||||
.add( {{"tex", SamplerType::SAMPLER_2D_ARRAY, SamplerFormat::FLOAT, Precision::HIGH }} )
|
||||
.add( {{"tex", SamplerType::SAMPLER_3D, SamplerFormat::FLOAT, Precision::HIGH }} )
|
||||
.build();
|
||||
std::string fragment = stringReplace("{samplerType}",
|
||||
getSamplerTypeName(samplerType), fragmentUpdateImage3DTemplate);
|
||||
ShaderGenerator shaderGen(vertex, fragment, sBackend, sIsMobilePlatform, &sib);
|
||||
Program prog = shaderGen.getProgram(api);
|
||||
Program::Sampler psamplers[] = { utils::CString("test_tex"), 0 };
|
||||
Program::Sampler psamplers[] = { utils::CString("tex"), 0 };
|
||||
prog.setSamplerGroup(0, ShaderStageFlags::ALL_SHADER_STAGE_FLAGS, psamplers, sizeof(psamplers) / sizeof(psamplers[0]));
|
||||
ProgramHandle const program = api.createProgram(std::move(prog));
|
||||
ProgramHandle program = api.createProgram(std::move(prog));
|
||||
|
||||
// Create a texture.
|
||||
Handle<HwTexture> texture = api.createTexture(samplerType, 1,
|
||||
@@ -599,9 +577,12 @@ TEST_F(BackendTest, UpdateImage3D) {
|
||||
|
||||
// This ensures all driver commands have finished before exiting the test.
|
||||
api.finish();
|
||||
|
||||
api.stopCapture();
|
||||
|
||||
flushAndWait();
|
||||
executeCommands();
|
||||
|
||||
getDriver().purge();
|
||||
}
|
||||
|
||||
} // namespace test
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
#include <utils/Hash.h>
|
||||
|
||||
#include <fstream>
|
||||
#include <algorithm>
|
||||
|
||||
using namespace filament;
|
||||
using namespace filament::backend;
|
||||
@@ -108,7 +107,7 @@ TEST_F(ReadPixelsTest, ReadPixels) {
|
||||
|
||||
// The size of the actual render target, taking mip level into account;
|
||||
size_t getRenderTargetSize () const {
|
||||
return std::max(size_t(1), renderTargetBaseSize >> mipLevel);
|
||||
return renderTargetBaseSize >> mipLevel;
|
||||
}
|
||||
|
||||
// The rect that read pixels will read from.
|
||||
@@ -170,7 +169,7 @@ TEST_F(ReadPixelsTest, ReadPixels) {
|
||||
|
||||
// The normative read pixels test case. Render a white triangle over a blue background and read
|
||||
// the full viewport into a pixel buffer.
|
||||
TestCase const t0;
|
||||
TestCase t;
|
||||
|
||||
// Check that a subregion of the render target can be read into a pixel buffer.
|
||||
TestCase t2;
|
||||
@@ -234,7 +233,7 @@ TEST_F(ReadPixelsTest, ReadPixels) {
|
||||
t8.testName = "readPixels_swapchain";
|
||||
t8.useDefaultRT = true;
|
||||
|
||||
TestCase const testCases[] = { t0, t2, t3, t4, t5, t6, t7, t8 };
|
||||
TestCase testCases[] = { t, t2, t3, t4, t5, t6, t7, t8 };
|
||||
|
||||
// Create programs.
|
||||
Handle<HwProgram> programFloat, programUint;
|
||||
@@ -265,7 +264,7 @@ TEST_F(ReadPixelsTest, ReadPixels) {
|
||||
|
||||
// Create a Texture and RenderTarget to render into.
|
||||
auto usage = TextureUsage::COLOR_ATTACHMENT | TextureUsage::SAMPLEABLE;
|
||||
Handle<HwTexture> const texture = getDriverApi().createTexture(SamplerType::SAMPLER_2D,
|
||||
Handle<HwTexture> texture = getDriverApi().createTexture(SamplerType::SAMPLER_2D,
|
||||
t.mipLevels, t.textureFormat, 1, renderTargetBaseSize, renderTargetBaseSize, 1,
|
||||
usage);
|
||||
|
||||
@@ -283,7 +282,7 @@ TEST_F(ReadPixelsTest, ReadPixels) {
|
||||
{});
|
||||
}
|
||||
|
||||
TrianglePrimitive const triangle(getDriverApi());
|
||||
TrianglePrimitive triangle(getDriverApi());
|
||||
|
||||
RenderPassParams params = {};
|
||||
fullViewport(params);
|
||||
@@ -357,6 +356,7 @@ TEST_F(ReadPixelsTest, ReadPixels) {
|
||||
getDriverApi().beginRenderPass(renderTarget, params);
|
||||
getDriverApi().endRenderPass();
|
||||
|
||||
getDriverApi().flush();
|
||||
getDriverApi().commit(swapChain);
|
||||
getDriverApi().endFrame(0);
|
||||
|
||||
@@ -369,7 +369,11 @@ TEST_F(ReadPixelsTest, ReadPixels) {
|
||||
getDriverApi().destroyProgram(programUint);
|
||||
|
||||
// This ensures all driver commands have finished before exiting the test.
|
||||
flushAndWait();
|
||||
getDriverApi().finish();
|
||||
|
||||
executeCommands();
|
||||
|
||||
getDriver().purge();
|
||||
}
|
||||
|
||||
TEST_F(ReadPixelsTest, ReadPixelsPerformance) {
|
||||
|
||||
@@ -45,10 +45,10 @@ std::string fragment (R"(#version 450 core
|
||||
layout(location = 0) out vec4 fragColor;
|
||||
layout(location = 0) in vec2 uv;
|
||||
|
||||
layout(location = 0, set = 1) uniform sampler2D test_tex;
|
||||
layout(location = 0, set = 1) uniform sampler2D tex;
|
||||
|
||||
void main() {
|
||||
fragColor = texture(test_tex, uv);
|
||||
fragColor = texture(tex, uv);
|
||||
}
|
||||
)");
|
||||
|
||||
@@ -66,7 +66,7 @@ TEST_F(BackendTest, RenderExternalImageWithoutSet) {
|
||||
auto swapChain = createSwapChain();
|
||||
|
||||
SamplerInterfaceBlock sib = filament::SamplerInterfaceBlock::Builder()
|
||||
.name("Test")
|
||||
.name("backend_test_sib")
|
||||
.stageFlags(backend::ShaderStageFlags::ALL_SHADER_STAGE_FLAGS)
|
||||
.add( {{"tex", SamplerType::SAMPLER_EXTERNAL, SamplerFormat::FLOAT, Precision::HIGH }} )
|
||||
.build();
|
||||
@@ -74,7 +74,7 @@ TEST_F(BackendTest, RenderExternalImageWithoutSet) {
|
||||
|
||||
// Create a program that samples a texture.
|
||||
Program p = shaderGen.getProgram(getDriverApi());
|
||||
Program::Sampler sampler { utils::CString("test_tex"), 0 };
|
||||
Program::Sampler sampler { utils::CString("tex"), 0 };
|
||||
p.setSamplerGroup(0, ShaderStageFlags::ALL_SHADER_STAGE_FLAGS, &sampler, 1);
|
||||
backend::Handle<HwProgram> program = getDriverApi().createProgram(std::move(p));
|
||||
|
||||
@@ -146,7 +146,7 @@ TEST_F(BackendTest, RenderExternalImage) {
|
||||
auto swapChain = createSwapChain();
|
||||
|
||||
SamplerInterfaceBlock sib = filament::SamplerInterfaceBlock::Builder()
|
||||
.name("Test")
|
||||
.name("backend_test_sib")
|
||||
.stageFlags(backend::ShaderStageFlags::ALL_SHADER_STAGE_FLAGS)
|
||||
.add( {{"tex", SamplerType::SAMPLER_EXTERNAL, SamplerFormat::FLOAT, Precision::HIGH }} )
|
||||
.build();
|
||||
@@ -154,7 +154,7 @@ TEST_F(BackendTest, RenderExternalImage) {
|
||||
|
||||
// Create a program that samples a texture.
|
||||
Program p = shaderGen.getProgram(getDriverApi());
|
||||
Program::Sampler sampler { utils::CString("test_tex"), 0 };
|
||||
Program::Sampler sampler { utils::CString("tex"), 0 };
|
||||
p.setSamplerGroup(0, ShaderStageFlags::ALL_SHADER_STAGE_FLAGS, &sampler, 1);
|
||||
auto program = getDriverApi().createProgram(std::move(p));
|
||||
|
||||
|
||||
@@ -286,20 +286,17 @@ public:
|
||||
/** Sets a custom projection matrix for each eye.
|
||||
*
|
||||
* The projectionForCulling, near, and far parameters establish a "culling frustum" which must
|
||||
* encompass anything any eye can see. All projection matrices must be set simultaneously. The
|
||||
* number of stereoscopic eyes is controlled by the stereoscopicEyeCount setting inside of
|
||||
* Engine::Config.
|
||||
* encompass anything either eye can see.
|
||||
*
|
||||
* @param projection an array of projection matrices, only the first config.stereoscopicEyeCount
|
||||
* are read
|
||||
* @param projection an array of projection matrices, only the first
|
||||
* CONFIG_STEREOSCOPIC_EYES (2) are read
|
||||
* @param count size of the projection matrix array to set, must be
|
||||
* >= config.stereoscopicEyeCount
|
||||
* >= CONFIG_STEREOSCOPIC_EYES (2)
|
||||
* @param projectionForCulling custom projection matrix for culling, must encompass both eyes
|
||||
* @param near distance in world units from the camera to the culling near plane. \p near > 0.
|
||||
* @param far distance in world units from the camera to the culling far plane. \p far > \p
|
||||
* near.
|
||||
* @see setCustomProjection
|
||||
* @see Engine::Config::stereoscopicEyeCount
|
||||
*/
|
||||
void setCustomEyeProjection(math::mat4 const* projection, size_t count,
|
||||
math::mat4 const& projectionForCulling, double near, double far);
|
||||
@@ -360,8 +357,8 @@ public:
|
||||
* The projection matrix used for rendering always has its far plane set to infinity. This
|
||||
* is why it may differ from the matrix set through setProjection() or setLensProjection().
|
||||
*
|
||||
* @param eyeId the index of the eye to return the projection matrix for, must be
|
||||
* < config.stereoscopicEyeCount
|
||||
* @param eyeId the index of the eye to return the projection matrix for, must be <
|
||||
* CONFIG_STEREOSCOPIC_EYES (2)
|
||||
* @return The projection matrix used for rendering
|
||||
*
|
||||
* @see setProjection, setLensProjection, setCustomProjection, getCullingProjectionMatrix,
|
||||
@@ -419,7 +416,7 @@ public:
|
||||
* This method is not intended to be called every frame. Instead, to update the position of the
|
||||
* head, use Camera::setModelMatrix.
|
||||
*
|
||||
* @param eyeId the index of the eye to set, must be < config.stereoscopicEyeCount
|
||||
* @param eyeId the index of the eye to set, must be < CONFIG_STEREOSCOPIC_EYES (2)
|
||||
* @param model the model matrix for an individual eye
|
||||
*/
|
||||
void setEyeModelMatrix(uint8_t eyeId, math::mat4 const& model);
|
||||
|
||||
@@ -291,15 +291,6 @@ public:
|
||||
* Currently only respected by the Metal backend.
|
||||
*/
|
||||
size_t textureUseAfterFreePoolSize = 0;
|
||||
|
||||
/*
|
||||
* The number of eyes to render when stereoscopic rendering is enabled. Supported values are
|
||||
* between 1 and Engine::getMaxStereoscopicEyes() (inclusive).
|
||||
*
|
||||
* @see View::setStereoscopicOptions
|
||||
* @see Engine::getMaxStereoscopicEyes
|
||||
*/
|
||||
uint8_t stereoscopicEyeCount = 2;
|
||||
};
|
||||
|
||||
|
||||
@@ -563,29 +554,6 @@ public:
|
||||
*/
|
||||
bool isStereoSupported() const noexcept;
|
||||
|
||||
/**
|
||||
* Retrieves the configuration settings of this Engine.
|
||||
*
|
||||
* This method returns the configuration object that was supplied to the Engine's
|
||||
* Builder::config method during the creation of this Engine. If the Builder::config method was
|
||||
* not explicitly called (or called with nullptr), this method returns the default configuration
|
||||
* settings.
|
||||
*
|
||||
* @return a Config object with this Engine's configuration
|
||||
* @see Builder::config
|
||||
*/
|
||||
const Config& getConfig() const noexcept;
|
||||
|
||||
/**
|
||||
* Returns the maximum number of stereoscopic eyes supported by Filament. The actual number of
|
||||
* eyes rendered is set at Engine creation time with the Engine::Config::stereoscopicEyeCount
|
||||
* setting.
|
||||
*
|
||||
* @return the max number of stereoscopic eyes supported
|
||||
* @see Engine::Config::stereoscopicEyeCount
|
||||
*/
|
||||
static size_t getMaxStereoscopicEyes() noexcept;
|
||||
|
||||
/**
|
||||
* @return EntityManager used by filament
|
||||
*/
|
||||
|
||||
@@ -50,11 +50,11 @@ class UTILS_PUBLIC Material : public FilamentAPI {
|
||||
struct BuilderDetails;
|
||||
|
||||
public:
|
||||
using BlendingMode = filament::BlendingMode;
|
||||
using Shading = filament::Shading;
|
||||
using Interpolation = filament::Interpolation;
|
||||
using VertexDomain = filament::VertexDomain;
|
||||
using TransparencyMode = filament::TransparencyMode;
|
||||
using BlendingMode = BlendingMode;
|
||||
using Shading = Shading;
|
||||
using Interpolation = Interpolation;
|
||||
using VertexDomain = VertexDomain;
|
||||
using TransparencyMode = TransparencyMode;
|
||||
|
||||
using ParameterType = backend::UniformType;
|
||||
using Precision = backend::Precision;
|
||||
|
||||
@@ -450,13 +450,12 @@ public:
|
||||
|
||||
/**
|
||||
* Generates all the mipmap levels automatically. This requires the texture to have a
|
||||
* color-renderable format and usage set to BLIT_SRC | BLIT_DST. If unspecified,
|
||||
* usage bits are set automatically.
|
||||
* color-renderable format.
|
||||
*
|
||||
* @param engine Engine this texture is associated to.
|
||||
*
|
||||
* @attention \p engine must be the instance passed to Builder::build()
|
||||
* @attention This Texture instance must NOT use SamplerType::SAMPLER_3D or it has no effect
|
||||
* @attention This Texture instance must NOT use Sampler::SAMPLER_CUBEMAP or it has no effect
|
||||
*/
|
||||
void generateMipmaps(Engine& engine) const noexcept;
|
||||
|
||||
|
||||
@@ -66,26 +66,26 @@ class Viewport;
|
||||
*/
|
||||
class UTILS_PUBLIC View : public FilamentAPI {
|
||||
public:
|
||||
using QualityLevel = filament::QualityLevel;
|
||||
using BlendMode = filament::BlendMode;
|
||||
using AntiAliasing = filament::AntiAliasing;
|
||||
using Dithering = filament::Dithering;
|
||||
using ShadowType = filament::ShadowType;
|
||||
using QualityLevel = QualityLevel;
|
||||
using BlendMode = BlendMode;
|
||||
using AntiAliasing = AntiAliasing;
|
||||
using Dithering = Dithering;
|
||||
using ShadowType = ShadowType;
|
||||
|
||||
using DynamicResolutionOptions = filament::DynamicResolutionOptions;
|
||||
using BloomOptions = filament::BloomOptions;
|
||||
using FogOptions = filament::FogOptions;
|
||||
using DepthOfFieldOptions = filament::DepthOfFieldOptions;
|
||||
using VignetteOptions = filament::VignetteOptions;
|
||||
using RenderQuality = filament::RenderQuality;
|
||||
using AmbientOcclusionOptions = filament::AmbientOcclusionOptions;
|
||||
using TemporalAntiAliasingOptions = filament::TemporalAntiAliasingOptions;
|
||||
using MultiSampleAntiAliasingOptions = filament::MultiSampleAntiAliasingOptions;
|
||||
using VsmShadowOptions = filament::VsmShadowOptions;
|
||||
using SoftShadowOptions = filament::SoftShadowOptions;
|
||||
using ScreenSpaceReflectionsOptions = filament::ScreenSpaceReflectionsOptions;
|
||||
using GuardBandOptions = filament::GuardBandOptions;
|
||||
using StereoscopicOptions = filament::StereoscopicOptions;
|
||||
using DynamicResolutionOptions = DynamicResolutionOptions;
|
||||
using BloomOptions = BloomOptions;
|
||||
using FogOptions = FogOptions;
|
||||
using DepthOfFieldOptions = DepthOfFieldOptions;
|
||||
using VignetteOptions = VignetteOptions;
|
||||
using RenderQuality = RenderQuality;
|
||||
using AmbientOcclusionOptions = AmbientOcclusionOptions;
|
||||
using TemporalAntiAliasingOptions = TemporalAntiAliasingOptions;
|
||||
using MultiSampleAntiAliasingOptions = MultiSampleAntiAliasingOptions;
|
||||
using VsmShadowOptions = VsmShadowOptions;
|
||||
using SoftShadowOptions = SoftShadowOptions;
|
||||
using ScreenSpaceReflectionsOptions = ScreenSpaceReflectionsOptions;
|
||||
using GuardBandOptions = GuardBandOptions;
|
||||
using StereoscopicOptions = StereoscopicOptions;
|
||||
|
||||
/**
|
||||
* Sets the View's name. Only useful for debugging.
|
||||
@@ -691,12 +691,11 @@ public:
|
||||
* - punctual lights
|
||||
*
|
||||
* Stereo rendering depends on device and platform support. To check if stereo rendering is
|
||||
* supported, use Engine::isStereoSupported(). If stereo rendering is not supported, then the
|
||||
* stereoscopic options have no effect.
|
||||
* supported, use Engine::isStereoSupported().
|
||||
*
|
||||
* @param options The stereoscopic options to use on this view
|
||||
*/
|
||||
void setStereoscopicOptions(StereoscopicOptions const& options) noexcept;
|
||||
void setStereoscopicOptions(StereoscopicOptions const& options);
|
||||
|
||||
/**
|
||||
* Returns the stereoscopic options associated with this View.
|
||||
@@ -764,10 +763,10 @@ public:
|
||||
* @param handler Handler to dispatch the callback or nullptr for the default handler.
|
||||
*/
|
||||
template<typename T, void(T::*method)(PickingQueryResult const&)>
|
||||
void pick(uint32_t x, uint32_t y, T* instance,
|
||||
backend::CallbackHandler* handler = nullptr) noexcept {
|
||||
void pick(uint32_t x, uint32_t y, T* instance, backend::CallbackHandler* handler = nullptr) noexcept {
|
||||
PickingQuery& query = pick(x, y, [](PickingQueryResult const& result, PickingQuery* pq) {
|
||||
(static_cast<T*>(pq->storage[0])->*method)(result);
|
||||
void* user = pq->storage;
|
||||
(*static_cast<T**>(user)->*method)(result);
|
||||
}, handler);
|
||||
query.storage[0] = instance;
|
||||
}
|
||||
@@ -784,11 +783,11 @@ public:
|
||||
* @param handler Handler to dispatch the callback or nullptr for the default handler.
|
||||
*/
|
||||
template<typename T, void(T::*method)(PickingQueryResult const&)>
|
||||
void pick(uint32_t x, uint32_t y, T instance,
|
||||
backend::CallbackHandler* handler = nullptr) noexcept {
|
||||
void pick(uint32_t x, uint32_t y, T instance, backend::CallbackHandler* handler = nullptr) noexcept {
|
||||
static_assert(sizeof(instance) <= sizeof(PickingQuery::storage), "user data too large");
|
||||
PickingQuery& query = pick(x, y, [](PickingQueryResult const& result, PickingQuery* pq) {
|
||||
T* const that = static_cast<T*>(reinterpret_cast<void*>(pq->storage));
|
||||
void* user = pq->storage;
|
||||
T* that = static_cast<T*>(user);
|
||||
(that->*method)(result);
|
||||
that->~T();
|
||||
}, handler);
|
||||
@@ -805,15 +804,15 @@ public:
|
||||
* @param handler Handler to dispatch the callback or nullptr for the default handler.
|
||||
*/
|
||||
template<typename T>
|
||||
void pick(uint32_t x, uint32_t y, T functor,
|
||||
backend::CallbackHandler* handler = nullptr) noexcept {
|
||||
void pick(uint32_t x, uint32_t y, T functor, backend::CallbackHandler* handler = nullptr) noexcept {
|
||||
static_assert(sizeof(functor) <= sizeof(PickingQuery::storage), "functor too large");
|
||||
PickingQuery& query = pick(x, y, handler,
|
||||
(PickingQueryResultCallback)[](PickingQueryResult const& result, PickingQuery* pq) {
|
||||
T* const that = static_cast<T*>(reinterpret_cast<void*>(pq->storage));
|
||||
that->operator()(result);
|
||||
that->~T();
|
||||
});
|
||||
void* user = pq->storage;
|
||||
T& that = *static_cast<T*>(user);
|
||||
that(result);
|
||||
that.~T();
|
||||
});
|
||||
new(query.storage) T(std::move(functor));
|
||||
}
|
||||
|
||||
|
||||
@@ -327,18 +327,10 @@ size_t Engine::getMaxAutomaticInstances() const noexcept {
|
||||
return downcast(this)->getMaxAutomaticInstances();
|
||||
}
|
||||
|
||||
const Engine::Config& Engine::getConfig() const noexcept {
|
||||
return downcast(this)->getConfig();
|
||||
}
|
||||
|
||||
bool Engine::isStereoSupported() const noexcept {
|
||||
return downcast(this)->isStereoSupported();
|
||||
}
|
||||
|
||||
size_t Engine::getMaxStereoscopicEyes() noexcept {
|
||||
return FEngine::getMaxStereoscopicEyes();
|
||||
}
|
||||
|
||||
#if defined(__EMSCRIPTEN__)
|
||||
void Engine::resetBackendState() noexcept {
|
||||
downcast(this)->resetBackendState();
|
||||
|
||||
@@ -426,6 +426,7 @@ bool ChunkSamplerInterfaceBlock::unflatten(Unflattener& unflattener,
|
||||
uint8_t fieldFormat = 0;
|
||||
uint8_t fieldPrecision = 0;
|
||||
bool fieldMultisample = false;
|
||||
uint8_t fieldTransferFunction = 0;
|
||||
|
||||
if (!unflattener.read(&fieldName)) {
|
||||
return false;
|
||||
@@ -447,10 +448,15 @@ bool ChunkSamplerInterfaceBlock::unflatten(Unflattener& unflattener,
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!unflattener.read(&fieldTransferFunction)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
builder.add({ fieldName.data(), fieldName.size() }, SamplerInterfaceBlock::Type(fieldType),
|
||||
SamplerInterfaceBlock::Format(fieldFormat),
|
||||
SamplerInterfaceBlock::Precision(fieldPrecision),
|
||||
fieldMultisample);
|
||||
fieldMultisample,
|
||||
SamplerInterfaceBlock::SamplerTransferFunction(fieldTransferFunction));
|
||||
}
|
||||
|
||||
*sib = builder.build();
|
||||
|
||||
@@ -82,8 +82,7 @@ void PerViewUniforms::prepareCamera(FEngine& engine, const CameraInfo& camera) n
|
||||
s.nearOverFarMinusNear = camera.zn / (camera.zf - camera.zn);
|
||||
|
||||
mat4f const& headFromWorld = camera.view;
|
||||
Engine::Config const& config = engine.getConfig();
|
||||
for (int i = 0; i < config.stereoscopicEyeCount; i++) {
|
||||
for (uint8_t i = 0; i < CONFIG_STEREOSCOPIC_EYES; i++) {
|
||||
mat4f const& eyeFromHead = camera.eyeFromView[i]; // identity for monoscopic rendering
|
||||
mat4f const& clipFromEye = camera.eyeProjection[i];
|
||||
// clipFromEye * eyeFromHead * headFromWorld
|
||||
|
||||
+131
-125
@@ -676,34 +676,32 @@ FrameGraphId<FrameGraphTexture> PostProcessManager::screenSpaceAmbientOcclusion(
|
||||
FrameGraphId<FrameGraphTexture> output;
|
||||
};
|
||||
|
||||
// Needed for Vulkan and GLES. Some GLES implementations don't need it. Never needed for Metal.
|
||||
auto& duplicateDepthPass = fg.addPass<DuplicateDepthPassData>("Duplicate Depth Pass",
|
||||
[&](FrameGraph::Builder& builder, auto& data) {
|
||||
// read the depth as an attachment
|
||||
data.input = builder.read(depth,
|
||||
FrameGraphTexture::Usage::BLIT_SRC);
|
||||
|
||||
FrameGraphTexture::Usage::DEPTH_ATTACHMENT);
|
||||
auto desc = builder.getDescriptor(data.input);
|
||||
desc.levels = 1; // only copy the base level
|
||||
|
||||
// create a new buffer for the copy
|
||||
data.output = builder.createTexture("Depth Texture Copy", desc);
|
||||
|
||||
// output is an attachment
|
||||
data.output = builder.write(data.output,
|
||||
FrameGraphTexture::Usage::BLIT_DST);
|
||||
FrameGraphTexture::Usage::DEPTH_ATTACHMENT);
|
||||
builder.declareRenderPass("Depth Copy RenderTarget", {{ .depth = data.output }});
|
||||
},
|
||||
[=](FrameGraphResources const& resources, auto const& data, DriverApi& driver) {
|
||||
auto const& src = resources.getTexture(data.input);
|
||||
auto const& dst = resources.getTexture(data.output);
|
||||
auto const& srcSubDesc = resources.getSubResourceDescriptor(data.input);
|
||||
auto const& dstSubDesc = resources.getSubResourceDescriptor(data.output);
|
||||
auto const& desc = resources.getDescriptor(data.output);
|
||||
assert_invariant(desc.samples == resources.getDescriptor(data.input).samples);
|
||||
// here we can guarantee that src and dst format and size match, by construction.
|
||||
driver.blit(
|
||||
dst, dstSubDesc.level, dstSubDesc.layer, { 0, 0 },
|
||||
src, srcSubDesc.level, srcSubDesc.layer, { 0, 0 },
|
||||
{ desc.width, desc.height });
|
||||
[=](FrameGraphResources const& resources,
|
||||
auto const& data, DriverApi& driver) {
|
||||
auto const& desc = resources.getDescriptor(data.input);
|
||||
auto out = resources.getRenderPassInfo();
|
||||
// create a temporary render target for source, needed for the blit.
|
||||
auto inTarget = driver.createRenderTarget(TargetBufferFlags::DEPTH,
|
||||
desc.width, desc.height, desc.samples, {},
|
||||
{ resources.getTexture(data.input) }, {});
|
||||
driver.blit(TargetBufferFlags::DEPTH,
|
||||
out.target, out.params.viewport,
|
||||
inTarget, out.params.viewport,
|
||||
SamplerMagFilter::NEAREST);
|
||||
driver.destroyRenderTarget(inTarget);
|
||||
});
|
||||
|
||||
auto& SSAOPass = fg.addPass<SSAOPassData>("SSAO Pass",
|
||||
@@ -1345,18 +1343,14 @@ FrameGraphId<FrameGraphTexture> PostProcessManager::generateMipmapSSR(
|
||||
if (desc.samples > 1 &&
|
||||
outDesc.width == desc.width && outDesc.height == desc.height &&
|
||||
desc.format == outDesc.format) {
|
||||
// Resolve directly into the destination. This guarantees a blit/resolve will be
|
||||
// performed (i.e.: the source is copied) and we also guarantee that format/scaling
|
||||
// is the same after the forwardResource call below.
|
||||
input = ppm.resolve(fg, "ssr", input, outDesc);
|
||||
// resolve directly into the destination
|
||||
input = ppm.resolveBaseLevelNoCheck(fg, "ssr", input, outDesc);
|
||||
} else {
|
||||
// First resolve (if needed), may be a no-op. Guarantees that format/size is unchanged
|
||||
// by construction.
|
||||
input = ppm.resolve(fg, "ssr", input, { .levels = 1 });
|
||||
// Then blit into an appropriate texture, this handles scaling and format conversion.
|
||||
// The input/output sizes may differ when non-homogenous DSR is enabled.
|
||||
input = ppm.blit(fg, false, input, { 0, 0, desc.width, desc.height }, outDesc,
|
||||
SamplerMagFilter::LINEAR, SamplerMinFilter::LINEAR);
|
||||
// first resolve (if needed)
|
||||
input = ppm.resolveBaseLevel(fg, "ssr", input);
|
||||
// then blit into an appropriate texture
|
||||
// this handles scaling, format conversion and mipmaping
|
||||
input = ppm.opaqueBlit(fg, input, { 0, 0, desc.width, desc.height }, outDesc);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2670,11 +2664,60 @@ FrameGraphId<FrameGraphTexture> PostProcessManager::taa(FrameGraph& fg,
|
||||
return exportHistoryPass->color;
|
||||
}
|
||||
|
||||
FrameGraphId<FrameGraphTexture> PostProcessManager::opaqueBlit(FrameGraph& fg,
|
||||
FrameGraphId<FrameGraphTexture> input, filament::Viewport const& vp,
|
||||
FrameGraphTexture::Descriptor const& outDesc,
|
||||
SamplerMagFilter filter) noexcept {
|
||||
|
||||
struct PostProcessScaling {
|
||||
FrameGraphId<FrameGraphTexture> input;
|
||||
FrameGraphId<FrameGraphTexture> output;
|
||||
};
|
||||
|
||||
auto& ppBlit = fg.addPass<PostProcessScaling>("opaque blit",
|
||||
[&](FrameGraph::Builder& builder, auto& data) {
|
||||
|
||||
// we currently have no use for this case, so we just assert. This is better for now to trap
|
||||
// cases that we might not intend.
|
||||
assert_invariant(fg.getDescriptor(input).samples <= 1);
|
||||
|
||||
data.output = builder.declareRenderPass(
|
||||
builder.createTexture("opaque blit output", outDesc));
|
||||
|
||||
data.input = builder.read(input);
|
||||
|
||||
// We use a RenderPass for the source here, instead of just creating a render
|
||||
// target from data.input in the execute closure, because data.input may refer to
|
||||
// an imported render target and in this case data.input won't resolve to an actual
|
||||
// HwTexture handle. Using a RenderPass works because data.input will resolve
|
||||
// to the actual imported render target and will have the correct viewport.
|
||||
builder.declareRenderPass("opaque blit input", {
|
||||
.attachments = { .color = { data.input }},
|
||||
.viewport = vp
|
||||
});
|
||||
},
|
||||
[=](FrameGraphResources const& resources, auto const&, DriverApi& driver) {
|
||||
auto out = resources.getRenderPassInfo(0);
|
||||
auto in = resources.getRenderPassInfo(1);
|
||||
driver.blit(TargetBufferFlags::COLOR,
|
||||
out.target, out.params.viewport,
|
||||
in.target, in.params.viewport,
|
||||
filter);
|
||||
});
|
||||
|
||||
// we rely on automatic culling of unused render passes
|
||||
return ppBlit->output;
|
||||
}
|
||||
|
||||
FrameGraphId<FrameGraphTexture> PostProcessManager::upscale(FrameGraph& fg, bool translucent,
|
||||
DynamicResolutionOptions dsrOptions, FrameGraphId<FrameGraphTexture> input,
|
||||
filament::Viewport const& vp, FrameGraphTexture::Descriptor const& outDesc,
|
||||
backend::SamplerMagFilter filter) noexcept {
|
||||
|
||||
if (UTILS_LIKELY(!translucent && dsrOptions.quality == QualityLevel::LOW)) {
|
||||
return opaqueBlit(fg, input, vp, outDesc, filter);
|
||||
}
|
||||
|
||||
// The code below cannot handle sub-resources
|
||||
assert_invariant(fg.getSubResourceDescriptor(input).layer == 0);
|
||||
assert_invariant(fg.getSubResourceDescriptor(input).level == 0);
|
||||
@@ -2872,120 +2915,83 @@ FrameGraphId<FrameGraphTexture> PostProcessManager::upscale(FrameGraph& fg, bool
|
||||
}
|
||||
|
||||
FrameGraphId<FrameGraphTexture> PostProcessManager::blit(FrameGraph& fg, bool translucent,
|
||||
FrameGraphId<FrameGraphTexture> input,
|
||||
filament::Viewport const& vp, FrameGraphTexture::Descriptor const& outDesc,
|
||||
SamplerMagFilter filterMag,
|
||||
SamplerMinFilter filterMin) noexcept {
|
||||
|
||||
// TODO: add support for sub-resources
|
||||
assert_invariant(fg.getSubResourceDescriptor(input).layer == 0);
|
||||
assert_invariant(fg.getSubResourceDescriptor(input).level == 0);
|
||||
|
||||
struct QuadBlitData {
|
||||
FrameGraphId<FrameGraphTexture> input;
|
||||
FrameGraphId<FrameGraphTexture> output;
|
||||
};
|
||||
|
||||
auto& ppQuadBlit = fg.addPass<QuadBlitData>("blitting",
|
||||
[&](FrameGraph::Builder& builder, auto& data) {
|
||||
data.input = builder.sample(input);
|
||||
data.output = builder.createTexture("upscaled output", outDesc);
|
||||
data.output = builder.write(data.output,
|
||||
FrameGraphTexture::Usage::COLOR_ATTACHMENT);
|
||||
builder.declareRenderPass(builder.getName(data.output), {
|
||||
.attachments = { .color = { data.output }},
|
||||
.clearFlags = TargetBufferFlags::DEPTH });
|
||||
},
|
||||
[=](FrameGraphResources const& resources,
|
||||
auto const& data, DriverApi& driver) {
|
||||
auto color = resources.getTexture(data.input);
|
||||
auto const& inputDesc = resources.getDescriptor(data.input);
|
||||
auto const& outputDesc = resources.getDescriptor(data.output);
|
||||
auto out = resources.getRenderPassInfo();
|
||||
|
||||
// --------------------------------------------------------------------------------
|
||||
// set uniforms
|
||||
|
||||
PostProcessMaterial const& material = getPostProcessMaterial("blitLow");
|
||||
auto* mi = material.getMaterialInstance(mEngine);
|
||||
mi->setParameter("color", color, {
|
||||
.filterMag = filterMag,
|
||||
.filterMin = filterMin
|
||||
});
|
||||
mi->setParameter("resolution",
|
||||
float4{ outputDesc.width, outputDesc.height,
|
||||
1.0f / outputDesc.width, 1.0f / outputDesc.height });
|
||||
mi->setParameter("viewport", float4{
|
||||
float(vp.left) / inputDesc.width,
|
||||
float(vp.bottom) / inputDesc.height,
|
||||
float(vp.width) / inputDesc.width,
|
||||
float(vp.height) / inputDesc.height
|
||||
});
|
||||
mi->commit(driver);
|
||||
mi->use(driver);
|
||||
|
||||
PipelineState pipeline(material.getPipelineState(mEngine));
|
||||
if (translucent) {
|
||||
pipeline.rasterState.blendFunctionSrcRGB = BlendFunction::ONE;
|
||||
pipeline.rasterState.blendFunctionSrcAlpha = BlendFunction::ONE;
|
||||
pipeline.rasterState.blendFunctionDstRGB = BlendFunction::ONE_MINUS_SRC_ALPHA;
|
||||
pipeline.rasterState.blendFunctionDstAlpha = BlendFunction::ONE_MINUS_SRC_ALPHA;
|
||||
}
|
||||
render(out, pipeline, driver);
|
||||
});
|
||||
|
||||
return ppQuadBlit->output;
|
||||
FrameGraphId<FrameGraphTexture> input, filament::Viewport const& vp,
|
||||
FrameGraphTexture::Descriptor const& outDesc,
|
||||
backend::SamplerMagFilter filter) noexcept {
|
||||
// for now, we implement this by calling upscale() with the low-quality setting.
|
||||
return upscale(fg, translucent, { .quality = QualityLevel::LOW }, input, vp, outDesc, filter);
|
||||
}
|
||||
|
||||
FrameGraphId<FrameGraphTexture> PostProcessManager::resolve(FrameGraph& fg,
|
||||
const char* outputBufferName, FrameGraphId<FrameGraphTexture> input,
|
||||
FrameGraphTexture::Descriptor outDesc) noexcept {
|
||||
|
||||
FrameGraphId<FrameGraphTexture> PostProcessManager::resolveBaseLevel(FrameGraph& fg,
|
||||
const char* outputBufferName, FrameGraphId<FrameGraphTexture> input) noexcept {
|
||||
// Don't do anything if we're not a MSAA buffer
|
||||
auto const& inDesc = fg.getDescriptor(input);
|
||||
if (inDesc.samples <= 1) {
|
||||
auto desc = fg.getDescriptor(input);
|
||||
if (desc.samples <= 1) {
|
||||
return input;
|
||||
}
|
||||
desc.samples = 0;
|
||||
desc.levels = 1;
|
||||
return resolveBaseLevelNoCheck(fg, outputBufferName, input, desc);
|
||||
}
|
||||
|
||||
outDesc.width = inDesc.width;
|
||||
outDesc.height = inDesc.height;
|
||||
outDesc.format = inDesc.format;
|
||||
outDesc.samples = 0;
|
||||
FrameGraphId<FrameGraphTexture> PostProcessManager::resolveBaseLevelNoCheck(FrameGraph& fg,
|
||||
const char* outputBufferName, FrameGraphId<FrameGraphTexture> input,
|
||||
FrameGraphTexture::Descriptor const& desc) noexcept {
|
||||
|
||||
struct ResolveData {
|
||||
FrameGraphId<FrameGraphTexture> input;
|
||||
FrameGraphId<FrameGraphTexture> output;
|
||||
backend::TargetBufferFlags inFlags;
|
||||
FrameGraphTexture::Usage usage;
|
||||
};
|
||||
|
||||
auto& ppResolve = fg.addPass<ResolveData>("resolve",
|
||||
[&](FrameGraph::Builder& builder, auto& data) {
|
||||
data.input = builder.read(input, FrameGraphTexture::Usage::BLIT_SRC);
|
||||
data.output = builder.createTexture(outputBufferName, outDesc);
|
||||
data.output = builder.write(data.output, FrameGraphTexture::Usage::BLIT_DST);
|
||||
FrameGraphRenderPass::Descriptor rpDesc;
|
||||
|
||||
auto& rpDescAttachment = isDepthFormat(desc.format) ?
|
||||
rpDesc.attachments.depth :
|
||||
rpDesc.attachments.color[0];
|
||||
|
||||
data.usage = isDepthFormat(desc.format) ?
|
||||
FrameGraphTexture::Usage::DEPTH_ATTACHMENT :
|
||||
FrameGraphTexture::Usage::COLOR_ATTACHMENT;
|
||||
|
||||
data.inFlags = isDepthFormat(desc.format) ?
|
||||
backend::TargetBufferFlags::DEPTH :
|
||||
backend::TargetBufferFlags::COLOR0;
|
||||
|
||||
data.input = builder.read(input, data.usage);
|
||||
|
||||
rpDescAttachment = builder.createTexture(outputBufferName, desc);
|
||||
rpDescAttachment = builder.write(rpDescAttachment, data.usage);
|
||||
data.output = rpDescAttachment;
|
||||
builder.declareRenderPass("Resolve Pass", rpDesc);
|
||||
},
|
||||
[](FrameGraphResources const& resources, auto const& data, DriverApi& driver) {
|
||||
auto const& src = resources.getTexture(data.input);
|
||||
auto const& dst = resources.getTexture(data.output);
|
||||
auto const& srcSubDesc = resources.getSubResourceDescriptor(data.input);
|
||||
auto const& dstSubDesc = resources.getSubResourceDescriptor(data.output);
|
||||
auto const& srcDesc = resources.getDescriptor(data.input);
|
||||
auto const& dstDesc = resources.getDescriptor(data.output);
|
||||
assert_invariant(src);
|
||||
assert_invariant(dst);
|
||||
auto inDesc = resources.getDescriptor(data.input);
|
||||
auto in = resources.getTexture(data.input);
|
||||
auto out = resources.getRenderPassInfo();
|
||||
|
||||
ASSERT_POSTCONDITION(
|
||||
srcDesc.format == dstDesc.format,
|
||||
"resolve: src (%d) and dst (%d) formats don't match.",
|
||||
srcDesc.format, dstDesc.format);
|
||||
assert_invariant(in);
|
||||
|
||||
ASSERT_POSTCONDITION(
|
||||
srcDesc.width == dstDesc.width && srcDesc.height == dstDesc.height,
|
||||
"resolve: src [%u, %u] and dst [%u, %u] sizes don't match.",
|
||||
srcDesc.width, srcDesc.height, dstDesc.width, dstDesc.height);
|
||||
Handle<HwRenderTarget> inRt;
|
||||
if (data.usage == FrameGraphTexture::Usage::COLOR_ATTACHMENT) {
|
||||
inRt = driver.createRenderTarget(data.inFlags,
|
||||
out.params.viewport.width, out.params.viewport.height,
|
||||
inDesc.samples, {{ in }}, {}, {});
|
||||
}
|
||||
if (data.usage == FrameGraphTexture::Usage::DEPTH_ATTACHMENT) {
|
||||
inRt = driver.createRenderTarget(data.inFlags,
|
||||
out.params.viewport.width, out.params.viewport.height,
|
||||
inDesc.samples, {}, { in }, {});
|
||||
}
|
||||
|
||||
driver.resolve(
|
||||
dst, dstSubDesc.level, dstSubDesc.layer,
|
||||
src, srcSubDesc.level, srcSubDesc.layer);
|
||||
driver.blit(data.inFlags,
|
||||
out.target, out.params.viewport, inRt, out.params.viewport,
|
||||
SamplerMagFilter::NEAREST);
|
||||
|
||||
driver.destroyRenderTarget(inRt);
|
||||
});
|
||||
|
||||
return ppResolve->output;
|
||||
|
||||
@@ -221,30 +221,32 @@ public:
|
||||
TemporalAntiAliasingOptions const& taaOptions,
|
||||
ColorGradingConfig const& colorGradingConfig) noexcept;
|
||||
|
||||
/*
|
||||
* Blit/rescaling/resolves
|
||||
*/
|
||||
// Blit/rescaling/resolves
|
||||
FrameGraphId<FrameGraphTexture> opaqueBlit(FrameGraph& fg,
|
||||
FrameGraphId<FrameGraphTexture> input, filament::Viewport const& vp,
|
||||
FrameGraphTexture::Descriptor const& outDesc,
|
||||
backend::SamplerMagFilter filter = backend::SamplerMagFilter::LINEAR) noexcept;
|
||||
|
||||
// high quality upscaler
|
||||
// - when translucent, reverts to LINEAR
|
||||
// - doens't handle sub-resouces
|
||||
FrameGraphId<FrameGraphTexture> upscale(FrameGraph& fg, bool translucent,
|
||||
DynamicResolutionOptions dsrOptions, FrameGraphId<FrameGraphTexture> input,
|
||||
filament::Viewport const& vp, FrameGraphTexture::Descriptor const& outDesc,
|
||||
backend::SamplerMagFilter filter) noexcept;
|
||||
backend::SamplerMagFilter filter = backend::SamplerMagFilter::LINEAR) noexcept;
|
||||
|
||||
// upscale/downscale blitter using shaders
|
||||
FrameGraphId<FrameGraphTexture> blit(FrameGraph& fg, bool translucent,
|
||||
FrameGraphId<FrameGraphTexture> input,
|
||||
filament::Viewport const& vp, FrameGraphTexture::Descriptor const& outDesc,
|
||||
backend::SamplerMagFilter filterMag,
|
||||
backend::SamplerMinFilter filterMin) noexcept;
|
||||
FrameGraphId<FrameGraphTexture> input, filament::Viewport const& vp,
|
||||
FrameGraphTexture::Descriptor const& outDesc,
|
||||
backend::SamplerMagFilter filter = backend::SamplerMagFilter::LINEAR) noexcept;
|
||||
|
||||
// Resolves base level of input and outputs a texture from outDesc.
|
||||
// outDesc with, height, format and samples will be overridden.
|
||||
FrameGraphId<FrameGraphTexture> resolve(FrameGraph& fg,
|
||||
// resolve base level of input and outputs a 1-level texture
|
||||
FrameGraphId<FrameGraphTexture> resolveBaseLevel(FrameGraph& fg,
|
||||
const char* outputBufferName, FrameGraphId<FrameGraphTexture> input) noexcept;
|
||||
|
||||
// resolves base level of input and outputs a texture from outDesc. outDesc must
|
||||
// have the same dimensions and format as input, or this will fail.
|
||||
// outDesc can have mipmaps.
|
||||
FrameGraphId<FrameGraphTexture> resolveBaseLevelNoCheck(FrameGraph& fg,
|
||||
const char* outputBufferName, FrameGraphId<FrameGraphTexture> input,
|
||||
FrameGraphTexture::Descriptor outDesc) noexcept;
|
||||
FrameGraphTexture::Descriptor const& outDesc) noexcept;
|
||||
|
||||
// VSM shadow mipmap pass
|
||||
FrameGraphId<FrameGraphTexture> vsmMipmapPass(FrameGraph& fg,
|
||||
|
||||
@@ -116,17 +116,14 @@ void RenderPass::appendCommands(FEngine& engine, CommandTypeFlags const commandT
|
||||
commandCount += 1; // for the sentinel
|
||||
Command* const curr = append(commandCount);
|
||||
|
||||
auto stereoscopicEyeCount =
|
||||
renderFlags & IS_STEREOSCOPIC ? engine.getConfig().stereoscopicEyeCount : 1;
|
||||
|
||||
const float3 cameraPosition(mCameraPosition);
|
||||
const float3 cameraForwardVector(mCameraForwardVector);
|
||||
auto work = [commandTypeFlags, curr, &soa, variant, renderFlags, visibilityMask, cameraPosition,
|
||||
cameraForwardVector, stereoscopicEyeCount]
|
||||
cameraForwardVector]
|
||||
(uint32_t startIndex, uint32_t indexCount) {
|
||||
RenderPass::generateCommands(commandTypeFlags, curr,
|
||||
soa, { startIndex, startIndex + indexCount }, variant, renderFlags, visibilityMask,
|
||||
cameraPosition, cameraForwardVector, stereoscopicEyeCount);
|
||||
cameraPosition, cameraForwardVector);
|
||||
};
|
||||
|
||||
if (vr.size() <= JOBS_PARALLEL_FOR_COMMANDS_COUNT) {
|
||||
@@ -377,8 +374,8 @@ UTILS_NOINLINE
|
||||
void RenderPass::generateCommands(uint32_t commandTypeFlags, Command* const commands,
|
||||
FScene::RenderableSoa const& soa, Range<uint32_t> range,
|
||||
Variant variant, RenderFlags renderFlags,
|
||||
FScene::VisibleMaskType visibilityMask, float3 cameraPosition, float3 cameraForward,
|
||||
uint8_t instancedStereoEyeCount) noexcept {
|
||||
FScene::VisibleMaskType visibilityMask,
|
||||
float3 cameraPosition, float3 cameraForward) noexcept {
|
||||
|
||||
SYSTRACE_CALL();
|
||||
|
||||
@@ -409,13 +406,11 @@ void RenderPass::generateCommands(uint32_t commandTypeFlags, Command* const comm
|
||||
switch (commandTypeFlags & (CommandTypeFlags::COLOR | CommandTypeFlags::DEPTH)) {
|
||||
case CommandTypeFlags::COLOR:
|
||||
curr = generateCommandsImpl<CommandTypeFlags::COLOR>(commandTypeFlags, curr,
|
||||
soa, range, variant, renderFlags, visibilityMask, cameraPosition, cameraForward,
|
||||
instancedStereoEyeCount);
|
||||
soa, range, variant, renderFlags, visibilityMask, cameraPosition, cameraForward);
|
||||
break;
|
||||
case CommandTypeFlags::DEPTH:
|
||||
curr = generateCommandsImpl<CommandTypeFlags::DEPTH>(commandTypeFlags, curr,
|
||||
soa, range, variant, renderFlags, visibilityMask, cameraPosition, cameraForward,
|
||||
instancedStereoEyeCount);
|
||||
soa, range, variant, renderFlags, visibilityMask, cameraPosition, cameraForward);
|
||||
break;
|
||||
default:
|
||||
// we should never end-up here
|
||||
@@ -438,7 +433,7 @@ RenderPass::Command* RenderPass::generateCommandsImpl(uint32_t extraFlags,
|
||||
Command* UTILS_RESTRICT curr,
|
||||
FScene::RenderableSoa const& UTILS_RESTRICT soa, Range<uint32_t> range,
|
||||
Variant const variant, RenderFlags renderFlags, FScene::VisibleMaskType visibilityMask,
|
||||
float3 cameraPosition, float3 cameraForward, uint8_t instancedStereoEyeCount) noexcept {
|
||||
float3 cameraPosition, float3 cameraForward) noexcept {
|
||||
|
||||
// generateCommands() writes both the draw and depth commands simultaneously such that
|
||||
// we go throw the list of renderables just once.
|
||||
@@ -534,7 +529,7 @@ RenderPass::Command* RenderPass::generateCommandsImpl(uint32_t extraFlags,
|
||||
// eye count.
|
||||
if (UTILS_UNLIKELY(hasInstancedStereo)) {
|
||||
cmdColor.primitive.instanceCount =
|
||||
(soaInstanceInfo[i].count * instancedStereoEyeCount) |
|
||||
(soaInstanceInfo[i].count * CONFIG_STEREOSCOPIC_EYES) |
|
||||
PrimitiveInfo::USER_INSTANCE_MASK;
|
||||
}
|
||||
|
||||
@@ -560,7 +555,7 @@ RenderPass::Command* RenderPass::generateCommandsImpl(uint32_t extraFlags,
|
||||
|
||||
if (UTILS_UNLIKELY(hasInstancedStereo)) {
|
||||
cmdColor.primitive.instanceCount =
|
||||
(soaInstanceInfo[i].count * instancedStereoEyeCount) |
|
||||
(soaInstanceInfo[i].count * CONFIG_STEREOSCOPIC_EYES) |
|
||||
PrimitiveInfo::USER_INSTANCE_MASK;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -408,15 +408,13 @@ private:
|
||||
FScene::RenderableSoa const& soa, utils::Range<uint32_t> range,
|
||||
Variant variant, RenderFlags renderFlags,
|
||||
FScene::VisibleMaskType visibilityMask,
|
||||
math::float3 cameraPosition, math::float3 cameraForward,
|
||||
uint8_t instancedStereoEyeCount) noexcept;
|
||||
math::float3 cameraPosition, math::float3 cameraForward) noexcept;
|
||||
|
||||
template<uint32_t commandTypeFlags>
|
||||
static inline Command* generateCommandsImpl(uint32_t extraFlags, Command* curr,
|
||||
FScene::RenderableSoa const& soa, utils::Range<uint32_t> range,
|
||||
Variant variant, RenderFlags renderFlags, FScene::VisibleMaskType visibilityMask,
|
||||
math::float3 cameraPosition, math::float3 cameraForward,
|
||||
uint8_t instancedStereoEyeCount) noexcept;
|
||||
math::float3 cameraPosition, math::float3 cameraForward) noexcept;
|
||||
|
||||
static void setupColorCommand(Command& cmdDraw, Variant variant,
|
||||
FMaterialInstance const* mi, bool inverseFrontFaces) noexcept;
|
||||
|
||||
@@ -89,7 +89,7 @@ FrameGraphId<FrameGraphTexture> RendererUtils::colorPass(
|
||||
data.color = builder.createTexture("Color Buffer", colorBufferDesc);
|
||||
}
|
||||
|
||||
const bool canAutoResolveDepth = engine.getDriverApi().isAutoDepthResolveSupported();
|
||||
const bool canResolveDepth = engine.getDriverApi().isAutoDepthResolveSupported();
|
||||
|
||||
if (!data.depth) {
|
||||
// clear newly allocated depth/stencil buffers, regardless of given clear flags
|
||||
@@ -114,17 +114,13 @@ FrameGraphId<FrameGraphTexture> RendererUtils::colorPass(
|
||||
data.depth = builder.createTexture(name, {
|
||||
.width = colorBufferDesc.width,
|
||||
.height = colorBufferDesc.height,
|
||||
// If the color attachment requested MS, we assume this means the MS
|
||||
// buffer must be kept, and for that reason we allocate the depth
|
||||
// buffer with MS as well.
|
||||
// On the other hand, if the color attachment was allocated without
|
||||
// MS, no need to allocate the depth buffer with MS; Either it's not
|
||||
// multi-sampled or it is auto-resolved.
|
||||
// One complication above is that some backends don't support
|
||||
// depth auto-resolve, in which case we must allocate the depth
|
||||
// buffer with MS and manually resolve it (see "Resolved Depth Buffer"
|
||||
// pass).
|
||||
.samples = canAutoResolveDepth ? colorBufferDesc.samples : uint8_t(config.msaa),
|
||||
// If the color attachment requested MS, we assume this means the MS buffer
|
||||
// must be kept, and for that reason we allocate the depth buffer with MS
|
||||
// as well. On the other hand, if the color attachment was allocated without
|
||||
// MS, no need to allocate the depth buffer with MS, if the RT is MS,
|
||||
// the tile depth buffer will be MS, but it'll be resolved to single
|
||||
// sample automatically -- which is what we want.
|
||||
.samples = canResolveDepth ? colorBufferDesc.samples : uint8_t(config.msaa),
|
||||
.format = format,
|
||||
});
|
||||
if (config.enabledStencilBuffer) {
|
||||
@@ -286,7 +282,7 @@ std::pair<FrameGraphId<FrameGraphTexture>, bool> RendererUtils::refractionPass(
|
||||
|
||||
input = RendererUtils::colorPass(fg, "Color Pass (opaque)", engine, view, {
|
||||
// When rendering the opaques, we need to conserve the sample buffer,
|
||||
// so create a config that specifies the sample count.
|
||||
// so create config that specifies the sample count.
|
||||
.width = config.physicalViewport.width,
|
||||
.height = config.physicalViewport.height,
|
||||
.samples = config.msaa,
|
||||
@@ -316,11 +312,11 @@ std::pair<FrameGraphId<FrameGraphTexture>, bool> RendererUtils::refractionPass(
|
||||
config, colorGradingConfig, pass.getExecutor(refraction, pass.end()));
|
||||
|
||||
if (config.msaa > 1 && !colorGradingConfig.asSubpass) {
|
||||
// We need to do a resolve here because later passes (such as color grading or DoF) will
|
||||
// need to sample from 'output'. However, because we have MSAA, we know we're not
|
||||
// sampleable. And this is because in the SSR case, we had to use a renderbuffer to
|
||||
// conserve the multi-sample buffer.
|
||||
output = ppm.resolve(fg, "Resolved Color Buffer", output, { .levels = 1 });
|
||||
// We need to do a resolve here because later passes (such as color grading or DoF) will need
|
||||
// to sample from 'output'. However, because we have MSAA, we know we're not sampleable.
|
||||
// And this is because in the SSR case, we had to use a renderbuffer to conserve the
|
||||
// multi-sample buffer.
|
||||
output = ppm.resolveBaseLevel(fg, "Resolved Color Buffer", output);
|
||||
}
|
||||
} else {
|
||||
output = input;
|
||||
|
||||
@@ -108,13 +108,11 @@ ShadowMap::ShaderParameters ShadowMap::updateDirectional(FEngine& engine,
|
||||
ShadowMapInfo const& shadowMapInfo,
|
||||
SceneInfo const& sceneInfo) noexcept {
|
||||
|
||||
// reset the visible shadow status
|
||||
mHasVisibleShadows = false;
|
||||
|
||||
FLightManager const& lcm = engine.getLightManager();
|
||||
FLightManager::Instance const li = lightData.elementAt<FScene::LIGHT_INSTANCE>(index);
|
||||
FLightManager::ShadowParams const params = lcm.getShadowParams(li);
|
||||
|
||||
// We can't use LISPSM in stable mode
|
||||
const auto direction = lightData.elementAt<FScene::SHADOW_DIRECTION>(index);
|
||||
|
||||
auto [Mv, znear, zfar, lsClippedShadowVolume, vertexCount, visibleShadows] =
|
||||
@@ -139,7 +137,6 @@ ShadowMap::ShaderParameters ShadowMap::updateDirectional(FEngine& engine,
|
||||
*/
|
||||
|
||||
mat4f W, Wp, L;
|
||||
// We can't use LISPSM in stable mode
|
||||
const bool useLispsm = params.options.lispsm && !params.options.stable;
|
||||
if (useLispsm) {
|
||||
// Orient the shadow map in the direction of the view vector by constructing a
|
||||
|
||||
@@ -522,7 +522,7 @@ ShadowMapManager::ShadowTechnique ShadowMapManager::updateCascadeShadowMaps(FEng
|
||||
// entire camera frustum, as if we only had a single cascade.
|
||||
ShadowMap& shadowMap = cascadedShadowMaps[0];
|
||||
|
||||
const auto direction = lightData.elementAt<FScene::SHADOW_DIRECTION>(0);
|
||||
const auto direction = options.transform * lightData.elementAt<FScene::DIRECTION>(0);
|
||||
|
||||
// We compute the directional light's model matrix using the origin's as the light position.
|
||||
// The choice of the light's origin initially doesn't matter for a directional light.
|
||||
|
||||
@@ -283,7 +283,7 @@ bool View::isStencilBufferEnabled() const noexcept {
|
||||
return downcast(this)->isStencilBufferEnabled();
|
||||
}
|
||||
|
||||
void View::setStereoscopicOptions(const StereoscopicOptions& options) noexcept {
|
||||
void View::setStereoscopicOptions(const StereoscopicOptions& options) {
|
||||
return downcast(this)->setStereoscopicOptions(options);
|
||||
}
|
||||
|
||||
|
||||
@@ -96,11 +96,11 @@ void UTILS_NOINLINE FCamera::setCustomProjection(mat4 const& p,
|
||||
|
||||
void UTILS_NOINLINE FCamera::setCustomEyeProjection(math::mat4 const* projection, size_t count,
|
||||
math::mat4 const& projectionForCulling, double near, double far) {
|
||||
const Engine::Config& config = mEngine.getConfig();
|
||||
ASSERT_PRECONDITION(count >= config.stereoscopicEyeCount,
|
||||
ASSERT_PRECONDITION(count >= CONFIG_STEREOSCOPIC_EYES,
|
||||
"All eye projections must be supplied together, count must be >= "
|
||||
"config.stereoscopicEyeCount (%d)", config.stereoscopicEyeCount);
|
||||
for (int i = 0; i < config.stereoscopicEyeCount; i++) {
|
||||
"CONFIG_STEREOSCOPIC_EYES(%d)",
|
||||
CONFIG_STEREOSCOPIC_EYES);
|
||||
for (uint8_t i = 0; i < CONFIG_STEREOSCOPIC_EYES; i++) {
|
||||
mEyeProjection[i] = projection[i];
|
||||
}
|
||||
mProjectionForCulling = projectionForCulling;
|
||||
@@ -165,8 +165,7 @@ void UTILS_NOINLINE FCamera::setProjection(Camera::Projection projection,
|
||||
}
|
||||
|
||||
math::mat4 FCamera::getProjectionMatrix(uint8_t eye) const noexcept {
|
||||
UTILS_UNUSED_IN_RELEASE const Engine::Config& config = mEngine.getConfig();
|
||||
assert_invariant(eye < config.stereoscopicEyeCount);
|
||||
assert_invariant(eye < CONFIG_STEREOSCOPIC_EYES);
|
||||
// This is where we transform the user clip-space (GL convention) to our virtual clip-space
|
||||
// (inverted DX convention)
|
||||
// Note that this math ends up setting the projection matrix' p33 to 0, which is where we're
|
||||
@@ -191,13 +190,6 @@ math::mat4 FCamera::getCullingProjectionMatrix() const noexcept {
|
||||
return m * mProjectionForCulling;
|
||||
}
|
||||
|
||||
const math::mat4& FCamera::getUserProjectionMatrix(uint8_t eyeId) const {
|
||||
const Engine::Config& config = mEngine.getConfig();
|
||||
ASSERT_PRECONDITION(eyeId < config.stereoscopicEyeCount,
|
||||
"eyeId must be < config.stereoscopicEyeCount (%d)", config.stereoscopicEyeCount);
|
||||
return mEyeProjection[eyeId];
|
||||
}
|
||||
|
||||
void UTILS_NOINLINE FCamera::setModelMatrix(const mat4f& modelMatrix) noexcept {
|
||||
FTransformManager& transformManager = mEngine.getTransformManager();
|
||||
transformManager.setTransform(transformManager.getInstance(mEntity), modelMatrix);
|
||||
@@ -209,9 +201,8 @@ void UTILS_NOINLINE FCamera::setModelMatrix(const mat4& modelMatrix) noexcept {
|
||||
}
|
||||
|
||||
void UTILS_NOINLINE FCamera::setEyeModelMatrix(uint8_t eyeId, math::mat4 const& model) {
|
||||
const Engine::Config& config = mEngine.getConfig();
|
||||
ASSERT_PRECONDITION(eyeId < config.stereoscopicEyeCount,
|
||||
"eyeId must be < config.stereoscopicEyeCount (%d)", config.stereoscopicEyeCount);
|
||||
ASSERT_PRECONDITION(eyeId < CONFIG_STEREOSCOPIC_EYES,
|
||||
"eyeId must be < CONFIG_STEREOSCOPIC_EYES(%d)", CONFIG_STEREOSCOPIC_EYES);
|
||||
mEyeFromView[eyeId] = inverse(model);
|
||||
}
|
||||
|
||||
@@ -258,15 +249,10 @@ double FCamera::computeEffectiveFov(double fovInDegrees, double focusDistance) n
|
||||
return fov * math::d::RAD_TO_DEG;
|
||||
}
|
||||
|
||||
uint8_t FCamera::getStereoscopicEyeCount() const noexcept {
|
||||
const Engine::Config& config = mEngine.getConfig();
|
||||
return config.stereoscopicEyeCount;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------
|
||||
|
||||
CameraInfo::CameraInfo(FCamera const& camera) noexcept {
|
||||
for (int i = 0; i < camera.getStereoscopicEyeCount(); i++) {
|
||||
for (uint8_t i = 0; i < CONFIG_STEREOSCOPIC_EYES; i++) {
|
||||
eyeProjection[i] = mat4f{ camera.getProjectionMatrix(i) };
|
||||
}
|
||||
cullingProjection = mat4f{ camera.getCullingProjectionMatrix() };
|
||||
@@ -282,7 +268,7 @@ CameraInfo::CameraInfo(FCamera const& camera) noexcept {
|
||||
|
||||
CameraInfo::CameraInfo(FCamera const& camera, math::mat4 const& inWorldTransform) noexcept {
|
||||
const mat4 modelMatrix{ inWorldTransform * camera.getModelMatrix() };
|
||||
for (int i = 0; i < camera.getStereoscopicEyeCount(); i++) {
|
||||
for (uint8_t i = 0; i < CONFIG_STEREOSCOPIC_EYES; i++) {
|
||||
eyeProjection[i] = mat4f{ camera.getProjectionMatrix(i) };
|
||||
eyeFromView[i] = mat4f{ camera.getEyeFromViewMatrix(i) };
|
||||
}
|
||||
|
||||
@@ -85,7 +85,11 @@ public:
|
||||
math::mat4 getEyeFromViewMatrix(uint8_t eye) const noexcept { return mEyeFromView[eye]; }
|
||||
|
||||
// viewing projection matrix set by the user
|
||||
const math::mat4& getUserProjectionMatrix(uint8_t eyeId) const;
|
||||
const math::mat4& getUserProjectionMatrix(uint8_t eyeId) const {
|
||||
ASSERT_PRECONDITION(eyeId < CONFIG_STEREOSCOPIC_EYES,
|
||||
"eyeId must be < CONFIG_STEREOSCOPIC_EYES(%d)", CONFIG_STEREOSCOPIC_EYES);
|
||||
return mEyeProjection[eyeId];
|
||||
}
|
||||
|
||||
// culling projection matrix set by the user
|
||||
math::mat4 getUserCullingProjectionMatrix() const noexcept { return mProjectionForCulling; }
|
||||
@@ -185,8 +189,6 @@ public:
|
||||
|
||||
static double computeEffectiveFov(double fovInDegrees, double focusDistance) noexcept;
|
||||
|
||||
uint8_t getStereoscopicEyeCount() const noexcept;
|
||||
|
||||
utils::Entity getEntity() const noexcept {
|
||||
return mEntity;
|
||||
}
|
||||
@@ -202,10 +204,10 @@ private:
|
||||
utils::Entity mEntity;
|
||||
|
||||
// For monoscopic cameras, mEyeProjection[0] == mEyeProjection[1].
|
||||
math::mat4 mEyeProjection[CONFIG_MAX_STEREOSCOPIC_EYES]; // projection matrix per eye (infinite far)
|
||||
math::mat4 mProjectionForCulling; // projection matrix (with far plane)
|
||||
math::mat4 mEyeFromView[CONFIG_MAX_STEREOSCOPIC_EYES]; // transforms from the main view (head)
|
||||
// space to each eye's unique view space
|
||||
math::mat4 mEyeProjection[CONFIG_STEREOSCOPIC_EYES]; // projection matrix per eye (infinite far)
|
||||
math::mat4 mProjectionForCulling; // projection matrix (with far plane)
|
||||
math::mat4 mEyeFromView[CONFIG_STEREOSCOPIC_EYES]; // transforms from the main view (head)
|
||||
// space to each eye's unique view space
|
||||
math::double2 mScalingCS = {1.0}; // additional scaling applied to projection
|
||||
math::double2 mShiftCS = {0.0}; // additional translation applied to projection
|
||||
|
||||
@@ -230,15 +232,15 @@ struct CameraInfo {
|
||||
math::mat4f projection;
|
||||
|
||||
// for stereo rendering, one matrix per eye
|
||||
math::mat4f eyeProjection[CONFIG_MAX_STEREOSCOPIC_EYES] = {};
|
||||
math::mat4f eyeProjection[CONFIG_STEREOSCOPIC_EYES] = {};
|
||||
};
|
||||
|
||||
math::mat4f cullingProjection; // projection matrix for culling
|
||||
math::mat4f model; // camera model matrix
|
||||
math::mat4f view; // camera view matrix (inverse(model))
|
||||
math::mat4f eyeFromView[CONFIG_MAX_STEREOSCOPIC_EYES]; // eye view matrix (only for stereoscopic)
|
||||
math::mat4 worldTransform; // world transform (already applied
|
||||
// to model and view)
|
||||
math::mat4f cullingProjection; // projection matrix for culling
|
||||
math::mat4f model; // camera model matrix
|
||||
math::mat4f view; // camera view matrix (inverse(model))
|
||||
math::mat4f eyeFromView[CONFIG_STEREOSCOPIC_EYES]; // eye view matrix (only for stereoscopic)
|
||||
math::mat4 worldTransform; // world transform (already applied
|
||||
// to model and view)
|
||||
math::float4 clipTransform{1, 1, 0, 0}; // clip-space transform, only for VERTEX_DOMAIN_DEVICE
|
||||
float zn{}; // distance (positive) to the near plane
|
||||
float zf{}; // distance (positive) to the far plane
|
||||
|
||||
@@ -244,10 +244,6 @@ void FEngine::init() {
|
||||
|
||||
mActiveFeatureLevel = std::min(mActiveFeatureLevel, driverApi.getFeatureLevel());
|
||||
|
||||
#ifndef FILAMENT_ENABLE_FEATURE_LEVEL_0
|
||||
assert_invariant(mActiveFeatureLevel > FeatureLevel::FEATURE_LEVEL_0);
|
||||
#endif
|
||||
|
||||
slog.i << "Backend feature level: " << int(driverApi.getFeatureLevel()) << io::endl;
|
||||
slog.i << "FEngine feature level: " << int(mActiveFeatureLevel) << io::endl;
|
||||
|
||||
@@ -332,15 +328,12 @@ void FEngine::init() {
|
||||
driverApi.update3DImage(mDummyZeroTexture, 0, 0, 0, 0, 1, 1, 1,
|
||||
{ zeroes, 4, Texture::Format::RGBA, Texture::Type::UBYTE });
|
||||
|
||||
#ifdef FILAMENT_ENABLE_FEATURE_LEVEL_0
|
||||
if (UTILS_UNLIKELY(mActiveFeatureLevel == FeatureLevel::FEATURE_LEVEL_0)) {
|
||||
FMaterial::DefaultMaterialBuilder defaultMaterialBuilder;
|
||||
defaultMaterialBuilder.package(
|
||||
MATERIALS_DEFAULTMATERIAL0_DATA, MATERIALS_DEFAULTMATERIAL0_SIZE);
|
||||
mDefaultMaterial = downcast(defaultMaterialBuilder.build(*const_cast<FEngine*>(this)));
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
} else {
|
||||
mDefaultColorGrading = downcast(ColorGrading::Builder().build(*this));
|
||||
|
||||
FMaterial::DefaultMaterialBuilder defaultMaterialBuilder;
|
||||
@@ -1273,9 +1266,6 @@ Engine::Config Engine::BuilderDetails::validateConfig(const Config* const pConfi
|
||||
// This value gets validated during driver creation, so pass it through
|
||||
config.driverHandleArenaSizeMB = config.driverHandleArenaSizeMB;
|
||||
|
||||
config.stereoscopicEyeCount =
|
||||
std::clamp(config.stereoscopicEyeCount, uint8_t(1), CONFIG_MAX_STEREOSCOPIC_EYES);
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
|
||||
@@ -184,10 +184,6 @@ public:
|
||||
|
||||
bool isStereoSupported() const noexcept { return getDriver().isStereoSupported(); }
|
||||
|
||||
static size_t getMaxStereoscopicEyes() noexcept {
|
||||
return CONFIG_MAX_STEREOSCOPIC_EYES;
|
||||
}
|
||||
|
||||
PostProcessManager const& getPostProcessManager() const noexcept {
|
||||
return mPostProcessManager;
|
||||
}
|
||||
|
||||
@@ -260,9 +260,6 @@ FMaterial::FMaterial(FEngine& engine, const Material::Builder& builder)
|
||||
mSpecializationConstants.push_back({
|
||||
+ReservedSpecializationConstants::CONFIG_POWER_VR_SHADER_WORKAROUNDS,
|
||||
(bool)powerVrShaderWorkarounds });
|
||||
mSpecializationConstants.push_back({
|
||||
+ReservedSpecializationConstants::CONFIG_STEREO_EYE_COUNT,
|
||||
(int)engine.getConfig().stereoscopicEyeCount });
|
||||
if (UTILS_UNLIKELY(engine.getShaderLanguage() == ShaderLanguage::ESSL1)) {
|
||||
// The actual value of this spec-constant is set in the OpenGLDriver backend.
|
||||
mSpecializationConstants.push_back({
|
||||
@@ -405,7 +402,6 @@ FMaterial::FMaterial(FEngine& engine, const Material::Builder& builder)
|
||||
mIsDefaultMaterial = builder->mDefaultMaterial;
|
||||
|
||||
if (UTILS_UNLIKELY(mIsDefaultMaterial)) {
|
||||
assert_invariant(mMaterialDomain == MaterialDomain::SURFACE);
|
||||
filaflat::MaterialChunk const& materialChunk{ mMaterialParser->getMaterialChunk() };
|
||||
auto variants = FixedCapacityVector<Variant>::with_capacity(materialChunk.getShaderCount());
|
||||
materialChunk.visitShaders([&variants](
|
||||
@@ -421,14 +417,12 @@ FMaterial::FMaterial(FEngine& engine, const Material::Builder& builder)
|
||||
std::swap(mDepthVariants, variants);
|
||||
}
|
||||
|
||||
if (mMaterialDomain == MaterialDomain::SURFACE) {
|
||||
if (UTILS_UNLIKELY(!mIsDefaultMaterial && !mHasCustomDepthShader)) {
|
||||
FMaterial const* const pDefaultMaterial = engine.getDefaultMaterial();
|
||||
auto& cachedPrograms = mCachedPrograms;
|
||||
for (Variant const variant: pDefaultMaterial->mDepthVariants) {
|
||||
pDefaultMaterial->prepareProgram(variant);
|
||||
cachedPrograms[variant.key] = pDefaultMaterial->getProgram(variant);
|
||||
}
|
||||
if (UTILS_UNLIKELY(!mIsDefaultMaterial && !mHasCustomDepthShader)) {
|
||||
FMaterial const* const pDefaultMaterial = engine.getDefaultMaterial();
|
||||
auto& cachedPrograms = mCachedPrograms;
|
||||
for (Variant const variant : pDefaultMaterial->mDepthVariants) {
|
||||
pDefaultMaterial->prepareProgram(variant);
|
||||
cachedPrograms[variant.key] = pDefaultMaterial->getProgram(variant);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -472,47 +466,34 @@ void FMaterial::invalidate(Variant::type_t variantMask, Variant::type_t variantV
|
||||
}
|
||||
}
|
||||
|
||||
if (mMaterialDomain == MaterialDomain::SURFACE) {
|
||||
DriverApi& driverApi = mEngine.getDriverApi();
|
||||
auto& cachedPrograms = mCachedPrograms;
|
||||
for (size_t k = 0, n = VARIANT_COUNT; k < n; ++k) {
|
||||
Variant const variant(k);
|
||||
if ((k & variantMask) == variantValue) {
|
||||
if (UTILS_LIKELY(!mIsDefaultMaterial)) {
|
||||
// The depth variants may be shared with the default material, in which case
|
||||
// we should not free it now.
|
||||
bool const isSharedVariant =
|
||||
Variant::isValidDepthVariant(variant) && !mHasCustomDepthShader;
|
||||
if (isSharedVariant) {
|
||||
// we don't own this variant, skip.
|
||||
continue;
|
||||
}
|
||||
DriverApi& driverApi = mEngine.getDriverApi();
|
||||
auto& cachedPrograms = mCachedPrograms;
|
||||
for (size_t k = 0, n = VARIANT_COUNT; k < n; ++k) {
|
||||
Variant const variant(k);
|
||||
if ((k & variantMask) == variantValue) {
|
||||
if (UTILS_LIKELY(!mIsDefaultMaterial)) {
|
||||
// The depth variants may be shared with the default material, in which case
|
||||
// we should not free it now.
|
||||
bool const isSharedVariant =
|
||||
Variant::isValidDepthVariant(variant) && !mHasCustomDepthShader;
|
||||
if (isSharedVariant) {
|
||||
// we don't own this variant, skip.
|
||||
continue;
|
||||
}
|
||||
driverApi.destroyProgram(cachedPrograms[k]);
|
||||
cachedPrograms[k].clear();
|
||||
}
|
||||
driverApi.destroyProgram(cachedPrograms[k]);
|
||||
cachedPrograms[k].clear();
|
||||
}
|
||||
}
|
||||
|
||||
if (UTILS_UNLIKELY(!mIsDefaultMaterial && !mHasCustomDepthShader)) {
|
||||
FMaterial const* const pDefaultMaterial = mEngine.getDefaultMaterial();
|
||||
for (Variant const variant: pDefaultMaterial->mDepthVariants) {
|
||||
pDefaultMaterial->prepareProgram(variant);
|
||||
if (!cachedPrograms[variant.key]) {
|
||||
cachedPrograms[variant.key] = pDefaultMaterial->getProgram(variant);
|
||||
}
|
||||
if (UTILS_UNLIKELY(!mIsDefaultMaterial && !mHasCustomDepthShader)) {
|
||||
FMaterial const* const pDefaultMaterial = mEngine.getDefaultMaterial();
|
||||
for (Variant const variant: pDefaultMaterial->mDepthVariants) {
|
||||
pDefaultMaterial->prepareProgram(variant);
|
||||
if (!cachedPrograms[variant.key]) {
|
||||
cachedPrograms[variant.key] = pDefaultMaterial->getProgram(variant);
|
||||
}
|
||||
}
|
||||
} else if (mMaterialDomain == MaterialDomain::POST_PROCESS) {
|
||||
DriverApi& driverApi = mEngine.getDriverApi();
|
||||
auto& cachedPrograms = mCachedPrograms;
|
||||
for (size_t k = 0, n = POST_PROCESS_VARIANT_COUNT; k < n; ++k) {
|
||||
if ((k & variantMask) == variantValue) {
|
||||
driverApi.destroyProgram(cachedPrograms[k]);
|
||||
cachedPrograms[k].clear();
|
||||
}
|
||||
}
|
||||
} else if (mMaterialDomain == MaterialDomain::COMPUTE) {
|
||||
// TODO: handle compute variants if any
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -365,19 +365,19 @@ void FRenderer::copyFrame(FSwapChain* dstSwapChain, filament::Viewport const& ds
|
||||
params.viewport.bottom = 0;
|
||||
params.viewport.width = std::numeric_limits<uint32_t>::max();
|
||||
params.viewport.height = std::numeric_limits<uint32_t>::max();
|
||||
driver.beginRenderPass(mRenderTargetHandle, params);
|
||||
driver.endRenderPass();
|
||||
}
|
||||
driver.beginRenderPass(mRenderTargetHandle, params);
|
||||
|
||||
// Verify that the source swap chain is readable.
|
||||
assert_invariant(mSwapChain->isReadable());
|
||||
driver.blitDEPRECATED(TargetBufferFlags::COLOR, mRenderTargetHandle,
|
||||
dstViewport, mRenderTargetHandle, srcViewport, SamplerMagFilter::LINEAR);
|
||||
|
||||
driver.blit(TargetBufferFlags::COLOR,
|
||||
mRenderTargetHandle, dstViewport, mRenderTargetHandle, srcViewport, SamplerMagFilter::LINEAR);
|
||||
if (flags & SET_PRESENTATION_TIME) {
|
||||
// TODO: Implement this properly, see https://github.com/google/filament/issues/633
|
||||
}
|
||||
|
||||
driver.endRenderPass();
|
||||
|
||||
if (flags & COMMIT) {
|
||||
dstSwapChain->commit(driver);
|
||||
}
|
||||
@@ -984,12 +984,10 @@ void FRenderer::renderJob(ArenaScope& arena, FView& view) {
|
||||
view.commitUniforms(driver);
|
||||
});
|
||||
|
||||
// Resolve depth -- which might be needed because of TAA or DoF. This pass will be culled
|
||||
// if the depth is not used below or if the depth is not MS (e.g. it could have been
|
||||
// auto-resolved).
|
||||
// In practice, this is used on Vulkan and older Metal devices.
|
||||
auto depth = blackboard.get<FrameGraphTexture>("depth");
|
||||
depth = ppm.resolve(fg, "Resolved Depth Buffer", depth, { .levels = 1 });
|
||||
// resolve depth -- which might be needed because of TAA or DoF. This pass will be culled
|
||||
// if the depth is not used below.
|
||||
auto const depth = ppm.resolveBaseLevel(fg, "Resolved Depth Buffer",
|
||||
blackboard.get<FrameGraphTexture>("depth"));
|
||||
|
||||
// Debug: CSM visualisation
|
||||
if (UTILS_UNLIKELY(engine.debug.shadowmap.visualize_cascades &&
|
||||
@@ -1059,7 +1057,7 @@ void FRenderer::renderJob(ArenaScope& arena, FView& view) {
|
||||
auto viewport = DEBUG_DYNAMIC_SCALING ? xvp : vp;
|
||||
input = ppm.upscale(fg, needsAlphaChannel, dsrOptions, input, xvp, {
|
||||
.width = viewport.width, .height = viewport.height,
|
||||
.format = colorGradingConfig.ldrFormat }, SamplerMagFilter::LINEAR);
|
||||
.format = colorGradingConfig.ldrFormat });
|
||||
xvp.left = xvp.bottom = 0;
|
||||
svp = xvp;
|
||||
}
|
||||
@@ -1082,8 +1080,7 @@ void FRenderer::renderJob(ArenaScope& arena, FView& view) {
|
||||
// TODO: in that specific scenario it would be better to just not use xvp
|
||||
// The intermediate buffer is accomplished with a "fake" opaqueBlit (i.e. blit) operation.
|
||||
|
||||
const bool outputIsSwapChain =
|
||||
(input == colorPassOutput) && (viewRenderTarget == mRenderTargetHandle);
|
||||
const bool outputIsSwapChain = (input == colorPassOutput) && (viewRenderTarget == mRenderTargetHandle);
|
||||
if (mightNeedFinalBlit) {
|
||||
if (blendModeTranslucent ||
|
||||
xvp != svp ||
|
||||
@@ -1094,9 +1091,8 @@ void FRenderer::renderJob(ArenaScope& arena, FView& view) {
|
||||
ssReflectionsOptions.enabled))) {
|
||||
assert_invariant(!scaled);
|
||||
input = ppm.blit(fg, blendModeTranslucent, input, xvp, {
|
||||
.width = vp.width, .height = vp.height,
|
||||
.format = colorGradingConfig.ldrFormat },
|
||||
SamplerMagFilter::NEAREST, SamplerMinFilter::NEAREST);
|
||||
.width = vp.width, .height = vp.height,
|
||||
.format = colorGradingConfig.ldrFormat }, SamplerMagFilter::NEAREST);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -267,16 +267,16 @@ void FScene::prepare(utils::JobSystem& js,
|
||||
// in the code below, we only transform directions, so the translation of the
|
||||
// world transform is irrelevant, and we don't need to use getWorldTransformAccurate()
|
||||
|
||||
mat3 const worldDirectionTransform =
|
||||
mat3::getTransformForNormals(tcm.getWorldTransformAccurate(ti).upperLeft());
|
||||
FLightManager::ShadowParams const params = lcm.getShadowParams(li);
|
||||
float3 const localDirection = worldDirectionTransform * lcm.getLocalDirection(li);
|
||||
double3 const shadowLocalDirection = params.options.transform * localDirection;
|
||||
float3 const localDirection = lcm.getLocalDirection(li);
|
||||
float3 const shadowLocalDirection = params.options.transform * localDirection;
|
||||
mat3 const worldDirectionTransform = tcm.getWorldTransformAccurate(ti).upperLeft();
|
||||
mat3 const shaderWorldTransform = worldTransform.upperLeft() * worldDirectionTransform;
|
||||
|
||||
// using mat3::getTransformForNormals handles non-uniform scaling
|
||||
// note: in the common case of the rigid-body transform, getTransformForNormals() returns
|
||||
// identity.
|
||||
mat3 const worlTransformNormals = mat3::getTransformForNormals(worldTransform.upperLeft());
|
||||
mat3 const worlTransformNormals = mat3::getTransformForNormals(shaderWorldTransform);
|
||||
double3 const d = worlTransformNormals * localDirection;
|
||||
double3 const s = worlTransformNormals * shadowLocalDirection;
|
||||
|
||||
@@ -290,8 +290,10 @@ void FScene::prepare(utils::JobSystem& js,
|
||||
// is pointing down, which is a common case for lights. See ShadowMap.cpp.
|
||||
return transpose(mat3::lookTo(direction, double3{ 1, 0, 0 }));
|
||||
};
|
||||
double3 const worldDirection =
|
||||
mat3::getTransformForNormals(worldDirectionTransform) * shadowLocalDirection;
|
||||
double3 const worldOrigin = transpose(worldTransform.upperLeft()) * worldTransform[3].xyz;
|
||||
mat3 const Mv = getMv(shadowLocalDirection);
|
||||
mat3 const Mv = getMv(worldDirection);
|
||||
double2 const lsReferencePoint = (Mv * worldOrigin).xy;
|
||||
|
||||
constexpr float inf = std::numeric_limits<float>::infinity();
|
||||
|
||||
@@ -118,12 +118,9 @@ FSkybox::FSkybox(FEngine& engine, const Builder& builder) noexcept
|
||||
|
||||
FMaterial const* FSkybox::createMaterial(FEngine& engine) {
|
||||
Material::Builder builder;
|
||||
#ifdef FILAMENT_ENABLE_FEATURE_LEVEL_0
|
||||
if (UTILS_UNLIKELY(engine.getActiveFeatureLevel() == Engine::FeatureLevel::FEATURE_LEVEL_0)) {
|
||||
builder.package(MATERIALS_SKYBOX0_DATA, MATERIALS_SKYBOX0_SIZE);
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
} else {
|
||||
builder.package(MATERIALS_SKYBOX_DATA, MATERIALS_SKYBOX_SIZE);
|
||||
}
|
||||
auto material = builder.build(engine);
|
||||
|
||||
@@ -58,7 +58,7 @@ struct Texture::BuilderDetails {
|
||||
uint8_t mLevels = 1;
|
||||
Sampler mTarget = Sampler::SAMPLER_2D;
|
||||
InternalFormat mFormat = InternalFormat::RGBA8;
|
||||
Usage mUsage = Usage::NONE;
|
||||
Usage mUsage = Usage::DEFAULT;
|
||||
bool mTextureIsSwizzled = false;
|
||||
std::array<Swizzle, 4> mSwizzle = {
|
||||
Swizzle::CHANNEL_0, Swizzle::CHANNEL_1,
|
||||
@@ -125,36 +125,6 @@ Texture* Texture::Builder::build(Engine& engine) {
|
||||
ASSERT_PRECONDITION(Texture::isTextureFormatSupported(engine, mImpl->mFormat),
|
||||
"Texture format %u not supported on this platform", mImpl->mFormat);
|
||||
|
||||
uint8_t maxLevelCount;
|
||||
switch (mImpl->mTarget) {
|
||||
case SamplerType::SAMPLER_2D:
|
||||
case SamplerType::SAMPLER_2D_ARRAY:
|
||||
case SamplerType::SAMPLER_CUBEMAP:
|
||||
case SamplerType::SAMPLER_EXTERNAL:
|
||||
case SamplerType::SAMPLER_CUBEMAP_ARRAY:
|
||||
maxLevelCount = FTexture::maxLevelCount(mImpl->mWidth, mImpl->mHeight);
|
||||
break;
|
||||
case SamplerType::SAMPLER_3D:
|
||||
maxLevelCount = FTexture::maxLevelCount(std::max(
|
||||
{ mImpl->mWidth, mImpl->mHeight, mImpl->mDepth }));
|
||||
break;
|
||||
}
|
||||
mImpl->mLevels = std::min(mImpl->mLevels, maxLevelCount);
|
||||
|
||||
if (mImpl->mUsage == TextureUsage::NONE) {
|
||||
mImpl->mUsage = TextureUsage::DEFAULT;
|
||||
if (mImpl->mLevels > 1 &&
|
||||
(mImpl->mWidth > 1 || mImpl->mHeight > 1) &&
|
||||
mImpl->mTarget != SamplerType::SAMPLER_EXTERNAL) {
|
||||
const bool formatMipmappable =
|
||||
downcast(engine).getDriverApi().isTextureFormatMipmappable(mImpl->mFormat);
|
||||
if (formatMipmappable) {
|
||||
// by default mipmappable textures have the BLIT usage bits set
|
||||
mImpl->mUsage |= TextureUsage::BLIT_SRC | TextureUsage::BLIT_DST;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const bool sampleable = bool(mImpl->mUsage & TextureUsage::SAMPLEABLE);
|
||||
const bool swizzled = mImpl->mTextureIsSwizzled;
|
||||
const bool imported = mImpl->mImportedId;
|
||||
@@ -193,15 +163,30 @@ Texture* Texture::Builder::build(Engine& engine) {
|
||||
// ------------------------------------------------------------------------------------------------
|
||||
|
||||
FTexture::FTexture(FEngine& engine, const Builder& builder) {
|
||||
FEngine::DriverApi& driver = engine.getDriverApi();
|
||||
mWidth = static_cast<uint32_t>(builder->mWidth);
|
||||
mHeight = static_cast<uint32_t>(builder->mHeight);
|
||||
mDepth = static_cast<uint32_t>(builder->mDepth);
|
||||
mFormat = builder->mFormat;
|
||||
mUsage = builder->mUsage;
|
||||
mTarget = builder->mTarget;
|
||||
mLevelCount = builder->mLevels;
|
||||
|
||||
uint8_t maxLevelCount;
|
||||
switch (builder->mTarget) {
|
||||
case SamplerType::SAMPLER_2D:
|
||||
case SamplerType::SAMPLER_2D_ARRAY:
|
||||
case SamplerType::SAMPLER_CUBEMAP:
|
||||
case SamplerType::SAMPLER_EXTERNAL:
|
||||
case SamplerType::SAMPLER_CUBEMAP_ARRAY:
|
||||
maxLevelCount = FTexture::maxLevelCount(mWidth, mHeight);
|
||||
break;
|
||||
case SamplerType::SAMPLER_3D:
|
||||
maxLevelCount = FTexture::maxLevelCount(std::max(mWidth, std::max(mHeight, mDepth)));
|
||||
break;
|
||||
}
|
||||
|
||||
mLevelCount = std::min(builder->mLevels, maxLevelCount);
|
||||
|
||||
FEngine::DriverApi& driver = engine.getDriverApi();
|
||||
if (UTILS_LIKELY(builder->mImportedId == 0)) {
|
||||
if (UTILS_LIKELY(!builder->mTextureIsSwizzled)) {
|
||||
mHandle = driver.createTexture(
|
||||
@@ -406,9 +391,6 @@ void FTexture::generateMipmaps(FEngine& engine) const noexcept {
|
||||
ASSERT_PRECONDITION(mTarget != SamplerType::SAMPLER_EXTERNAL,
|
||||
"External Textures are not mipmappable.");
|
||||
|
||||
ASSERT_PRECONDITION(mTarget != SamplerType::SAMPLER_3D,
|
||||
"3D Textures are not mipmappable.");
|
||||
|
||||
const bool formatMipmappable = engine.getDriverApi().isTextureFormatMipmappable(mFormat);
|
||||
ASSERT_PRECONDITION(formatMipmappable,
|
||||
"Texture format %u is not mipmappable.", (unsigned)mFormat);
|
||||
@@ -417,7 +399,74 @@ void FTexture::generateMipmaps(FEngine& engine) const noexcept {
|
||||
return;
|
||||
}
|
||||
|
||||
engine.getDriverApi().generateMipmaps(mHandle);
|
||||
if (engine.getDriverApi().canGenerateMipmaps()) {
|
||||
engine.getDriverApi().generateMipmaps(mHandle);
|
||||
return;
|
||||
}
|
||||
|
||||
auto generateMipsForLayer = [this, &engine](TargetBufferInfo proto) {
|
||||
FEngine::DriverApi& driver = engine.getDriverApi();
|
||||
|
||||
// Wrap miplevel 0 in a render target so that we can use it as a blit source.
|
||||
uint8_t level = 0;
|
||||
uint32_t srcw = mWidth;
|
||||
uint32_t srch = mHeight;
|
||||
proto.handle = mHandle;
|
||||
proto.level = level++;
|
||||
backend::Handle<backend::HwRenderTarget> srcrth = driver.createRenderTarget(
|
||||
TargetBufferFlags::COLOR, srcw, srch, mSampleCount, proto, {}, {});
|
||||
|
||||
// Perform a blit for all miplevels down to 1x1.
|
||||
backend::Handle<backend::HwRenderTarget> dstrth;
|
||||
do {
|
||||
uint32_t const dstw = std::max(srcw >> 1u, 1u);
|
||||
uint32_t const dsth = std::max(srch >> 1u, 1u);
|
||||
proto.level = level++;
|
||||
dstrth = driver.createRenderTarget(
|
||||
TargetBufferFlags::COLOR, dstw, dsth, mSampleCount, proto, {}, {});
|
||||
driver.blit(TargetBufferFlags::COLOR,
|
||||
dstrth, { 0, 0, dstw, dsth },
|
||||
srcrth, { 0, 0, srcw, srch },
|
||||
SamplerMagFilter::LINEAR);
|
||||
driver.destroyRenderTarget(srcrth);
|
||||
srcrth = dstrth;
|
||||
srcw = dstw;
|
||||
srch = dsth;
|
||||
} while ((srcw > 1 || srch > 1) && level < mLevelCount);
|
||||
driver.destroyRenderTarget(dstrth);
|
||||
};
|
||||
|
||||
switch (mTarget) {
|
||||
case SamplerType::SAMPLER_2D:
|
||||
generateMipsForLayer({});
|
||||
break;
|
||||
case SamplerType::SAMPLER_2D_ARRAY:
|
||||
UTILS_NOUNROLL
|
||||
for (uint16_t layer = 0, c = mDepth; layer < c; ++layer) {
|
||||
generateMipsForLayer({ .layer = layer });
|
||||
}
|
||||
break;
|
||||
case SamplerType::SAMPLER_CUBEMAP_ARRAY:
|
||||
UTILS_NOUNROLL
|
||||
for (uint16_t layer = 0, c = mDepth * 6; layer < c; ++layer) {
|
||||
generateMipsForLayer({ .layer = layer });
|
||||
}
|
||||
break;
|
||||
case SamplerType::SAMPLER_CUBEMAP:
|
||||
UTILS_NOUNROLL
|
||||
for (uint8_t face = 0; face < 6; ++face) {
|
||||
generateMipsForLayer({ .layer = face });
|
||||
}
|
||||
break;
|
||||
case SamplerType::SAMPLER_EXTERNAL:
|
||||
// not mipmapable
|
||||
break;
|
||||
case SamplerType::SAMPLER_3D:
|
||||
// TODO: handle SAMPLER_3D -- this can't be done with a 2D blit, this would require
|
||||
// a fragment shader
|
||||
slog.w << "Texture::generateMipmap does not support SAMPLER_3D yet on this h/w." << io::endl;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
bool FTexture::isTextureFormatSupported(FEngine& engine, InternalFormat format) noexcept {
|
||||
|
||||
@@ -1126,7 +1126,9 @@ View::PickingQuery& FView::pick(uint32_t x, uint32_t y, backend::CallbackHandler
|
||||
return *pQuery;
|
||||
}
|
||||
|
||||
void FView::setStereoscopicOptions(const StereoscopicOptions& options) noexcept {
|
||||
void FView::setStereoscopicOptions(const StereoscopicOptions& options) {
|
||||
ASSERT_PRECONDITION(!options.enabled || mIsStereoSupported,
|
||||
"Stereo rendering is not supported.");
|
||||
mStereoscopicOptions = options;
|
||||
}
|
||||
|
||||
|
||||
@@ -168,9 +168,7 @@ public:
|
||||
bool hasDPCF() const noexcept { return mShadowType == ShadowType::DPCF; }
|
||||
bool hasPCSS() const noexcept { return mShadowType == ShadowType::PCSS; }
|
||||
bool hasPicking() const noexcept { return mActivePickingQueriesList != nullptr; }
|
||||
bool hasInstancedStereo() const noexcept {
|
||||
return mIsStereoSupported && mStereoscopicOptions.enabled;
|
||||
}
|
||||
bool hasInstancedStereo() const noexcept { return mStereoscopicOptions.enabled; }
|
||||
|
||||
FrameGraphId<FrameGraphTexture> renderShadowMaps(FEngine& engine, FrameGraph& fg,
|
||||
CameraInfo const& cameraInfo, math::float4 const& userTime,
|
||||
@@ -194,7 +192,7 @@ public:
|
||||
|
||||
bool isStencilBufferEnabled() const noexcept { return mStencilBufferEnabled; }
|
||||
|
||||
void setStereoscopicOptions(StereoscopicOptions const& options) noexcept;
|
||||
void setStereoscopicOptions(StereoscopicOptions const& options);
|
||||
|
||||
FCamera const* getDirectionalLightCamera() const noexcept {
|
||||
return mShadowMapManager.getDirectionalLightCamera();
|
||||
|
||||
@@ -204,7 +204,7 @@ void FrameGraph::execute(backend::DriverApi& driver) noexcept {
|
||||
}
|
||||
|
||||
// call execute
|
||||
FrameGraphResources const resources(*this, *node);
|
||||
FrameGraphResources resources(*this, *node);
|
||||
node->execute(resources, driver);
|
||||
|
||||
// destroy concrete resources
|
||||
|
||||
@@ -527,7 +527,7 @@ private:
|
||||
|
||||
template<typename Data, typename Setup, typename Execute>
|
||||
FrameGraphPass<Data>& FrameGraph::addPass(char const* name, Setup setup, Execute&& execute) {
|
||||
static_assert(sizeof(Execute) < 2048, "Execute() lambda is capturing too much data.");
|
||||
static_assert(sizeof(Execute) < 1024, "Execute() lambda is capturing too much data.");
|
||||
|
||||
// create the FrameGraph pass
|
||||
auto* const pass = mArena.make<FrameGraphPassConcrete<Data, Execute>>(std::forward<Execute>(execute));
|
||||
|
||||
@@ -82,22 +82,22 @@ uint32_t RenderPassNode::declareRenderTarget(FrameGraph& fg, FrameGraph::Builder
|
||||
RenderPassData data;
|
||||
data.name = name;
|
||||
data.descriptor = descriptor;
|
||||
FrameGraphRenderPass::Attachments const& attachments = data.descriptor.attachments;
|
||||
|
||||
// retrieve the ResourceNode of the attachments coming to us -- this will be used later
|
||||
// to compute the discard flags.
|
||||
|
||||
DependencyGraph const& dependencyGraph = fg.getGraph();
|
||||
auto incomingEdges = dependencyGraph.getIncomingEdges(this);
|
||||
auto outgoingEdges = dependencyGraph.getOutgoingEdges(this);
|
||||
|
||||
for (size_t i = 0; i < RenderPassData::ATTACHMENT_COUNT; i++) {
|
||||
FrameGraphId<FrameGraphTexture> const& handle =
|
||||
data.descriptor.attachments.array[i];
|
||||
if (handle) {
|
||||
data.attachmentInfo[i] = handle;
|
||||
if (descriptor.attachments.array[i]) {
|
||||
data.attachmentInfo[i] = attachments.array[i];
|
||||
|
||||
// TODO: this is not very efficient
|
||||
auto incomingPos = std::find_if(incomingEdges.begin(), incomingEdges.end(),
|
||||
[&dependencyGraph, handle]
|
||||
[&dependencyGraph, handle = descriptor.attachments.array[i]]
|
||||
(DependencyGraph::Edge const* edge) {
|
||||
ResourceNode const* node = static_cast<ResourceNode const*>(
|
||||
dependencyGraph.getNode(edge->from));
|
||||
@@ -111,7 +111,7 @@ uint32_t RenderPassNode::declareRenderTarget(FrameGraph& fg, FrameGraph::Builder
|
||||
}
|
||||
|
||||
// this could be either outgoing or incoming (if there are no outgoing)
|
||||
data.outgoing[i] = fg.getActiveResourceNode(handle);
|
||||
data.outgoing[i] = fg.getActiveResourceNode(descriptor.attachments.array[i]);
|
||||
if (data.outgoing[i] == data.incoming[i]) {
|
||||
data.outgoing[i] = nullptr;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user