Compare commits

..
Author SHA1 Message Date
Benjamin Doherty 791f51dcb4 Update glslang to e3bca2a 2022-05-04 12:29:21 -07:00
Benjamin Doherty 4621f3ec5d Filament specific changes 2022-05-04 12:06:26 -07:00
Benjamin Doherty ab9c09d0d9 Update spirv-tools to 46492aa 2022-05-04 12:00:04 -07:00
Benjamin Doherty dbf51c1c7d Update SPIRV-Cross to 0c8a79b 2022-05-04 11:07:15 -07:00
1605 changed files with 98595 additions and 59042 deletions
@@ -1,10 +0,0 @@
FROM python:3.10.4
RUN pip3 install pygithub==1.55
ENV PYTHONUNBUFFERED=1
COPY verify_release_notes.py /verify_release_notes.py
RUN chmod +x /verify_release_notes.py
ENTRYPOINT [ "/verify_release_notes.py" ]
@@ -1,35 +0,0 @@
name: 'Verify Release Notes'
description: 'Verifies that a RELEASE_NOTES file has been modified'
inputs:
repo-token:
description: 'The GitHub token'
required: true
pull-request-number:
description: 'The Pull Request number'
required: true
bypass-label-name:
description: 'The Label used to bypass this check'
required: false
default: 'internal'
release-notes-file:
description: 'The path to the RELEASE_NOTES file'
required: false
default: 'RELEASE_NOTES.md'
pull-request-repo-full-name:
description: 'The full name of the Pull Request repo'
required: false
default: ${{ github.event.pull_request.head.repo.full_name }}
pull-request-head-ref:
description: 'The HEAD ref of the Pull Request'
required: false
default: ${{ github.event.pull_request.head.ref }}
runs:
using: 'docker'
image: 'Dockerfile'
args:
- ${{ inputs.repo-token }}
- ${{ inputs.pull-request-number }}
- ${{ inputs.bypass-label-name }}
- ${{ inputs.release-notes-file }}
- ${{ inputs.pull-request-repo-full-name }}
- ${{ inputs.pull-request-head-ref }}
@@ -1,100 +0,0 @@
#!/usr/bin/env python3
# Copyright (C) 2022 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.
from github import Github
import sys, os
def print_usage():
print('Verify that a GitHub pull request modifies a RELEASE_NOTES file')
print()
print('Usage:')
print(' verify_release_notes.py [arguments]')
print()
print('Arguments:')
print('1. github token')
print('2. pull request number')
print('3. bypass label name')
print('4. release notes file path')
print('5. pull request repo full name')
print('6. pull request head ref')
print()
print('The GITHUB_REPOSITORY environment variable must be set (e.g., google/filament).')
def leave_single_comment(pull_request, comment_body):
""" Leaves a comment on a PR once, without leaving a duplicate comment. """
# To avoid spamming the PR author, we'll use this comment tag (which will render invisibly on
# GitHub) to check if we've already left a comment on this PR.
COMMENT_TAG = '<!-- verify_release_notes -->\n'
comments = pull_request.get_issue_comments()
for comment in comments:
if comment.body.find(COMMENT_TAG) != -1:
return
# The GitHub token may not have WRITE permissions to leave a comment (for example, for 3P
# contributors). In that case, we simply won't leave a comment.
try:
pull_request.create_issue_comment(f'{COMMENT_TAG}{comment_body}')
except:
print("Unable to leave comment. Continuing.")
# The first argument is the path to this script.
if len(sys.argv) != 7:
print_usage()
sys.exit(1)
authentication_token = sys.argv[1]
pull_number = sys.argv[2]
bypass_label_name = sys.argv[3]
release_notes_file = sys.argv[4]
pr_repo_full_name = sys.argv[5]
pr_head_ref = sys.argv[6]
g = Github(authentication_token)
repo_name = os.environ.get('GITHUB_REPOSITORY')
if repo_name is None:
print("The GITHUB_REPOSITORY environment variable must be set.")
sys.exit(1)
repo = g.get_repo(repo_name)
pull_request = repo.get_pull(int(pull_number))
# First check if the PR has the "bypass" label. This label is used for PRs that don't need to update
# RELEASE_NOTES. If so, we can exit immediately.
labels = [l.name for l in pull_request.labels]
if bypass_label_name in labels:
print(f"PR number {pull_number} in repo {repo_name} contains the '{bypass_label_name}' label.")
print("Exiting with success.")
sys.exit(0)
# Next, check if the release notes file (RELEASE_NOTES.md or similar) has been modified.
files = pull_request.get_files()
for file in files:
if file.filename == release_notes_file:
print(f"PR number {pull_number} in repo {repo_name} modifies '{release_notes_file}'.")
print("Exiting with success.")
sys.exit(0)
# At this point, we issue a warning to the PR author to remember to modify the release notes, and
# exit with failure.
edit_url = f"https://github.com/{pr_repo_full_name}/edit/{pr_head_ref}/{release_notes_file}"
comment = (f"Please add a release note line to [{release_notes_file}]({edit_url}). "
f"If this PR does not warrant a release note, add the '{bypass_label_name}' label "
f"to this PR.")
print(comment)
leave_single_comment(pull_request, comment)
sys.exit(1)
+4
View File
@@ -33,6 +33,10 @@ jobs:
with:
name: gltfio-android-release
path: out/gltfio-android-release.aar
- uses: actions/upload-artifact@v1.0.0
with:
name: gltfio-android-lite-release
path: out/gltfio-android-lite-release.aar
- uses: actions/upload-artifact@v1.0.0
with:
name: filament-utils-android-release
+1
View File
@@ -126,6 +126,7 @@ jobs:
mv out/filamat-android-release.aar out/filamat-${TAG}-android.aar
mv out/filamat-android-lite-release.aar out/filamat-${TAG}-lite-android.aar
mv out/gltfio-android-release.aar out/gltfio-${TAG}-android.aar
mv out/gltfio-android-lite-release.aar out/gltfio-${TAG}-lite-android.aar
mv out/filament-utils-android-release.aar out/filament-utils-${TAG}-android.aar
python3 build/common/upload-assets.py ${TAG} out/*.aar out/*.apk
env:
@@ -1,26 +0,0 @@
name: Verify Release Notes
on:
pull_request:
branches:
- main
types: [opened, synchronize, reopened, labeled]
jobs:
verify-release-notes:
name: Verify Release Notes
runs-on: ubuntu-latest
steps:
# We *only* need to check out the .github/ directory.
# The verify RELEASE_NOTES script uses the GitHub API to verify that RELEASE_NOTES was
# modified.
- name: Check out action
uses: Bhacaz/checkout-files@73e17cfbe8d7e0c6b2672b20cb05a718e20d18d4
with:
files: .github
token: ${{ secrets.GITHUB_TOKEN }}
- name: Verify release notes
uses: ./.github/actions/verify-release-notes
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
pull-request-number: ${{ github.event.pull_request.number }}
+5 -3
View File
@@ -650,7 +650,6 @@ add_subdirectory(${LIBRARIES}/image)
add_subdirectory(${LIBRARIES}/ktxreader)
add_subdirectory(${LIBRARIES}/math)
add_subdirectory(${LIBRARIES}/mathio)
add_subdirectory(${LIBRARIES}/uberz)
add_subdirectory(${LIBRARIES}/utils)
add_subdirectory(${LIBRARIES}/viewer)
add_subdirectory(${FILAMENT}/filament)
@@ -688,6 +687,10 @@ if (FILAMENT_SUPPORTS_VULKAN)
add_subdirectory(${EXTERNAL}/vkmemalloc/tnt)
endif()
if (APPLE)
add_subdirectory(${EXTERNAL}/moltenvk/tnt)
endif()
set(FILAMENT_SAMPLES_BINARY_DIR ${PROJECT_BINARY_DIR}/samples)
if (WEBGL)
@@ -722,10 +725,9 @@ if (IS_HOST_PLATFORM)
add_subdirectory(${TOOLS}/rgb-to-lmsr)
add_subdirectory(${TOOLS}/roughness-prefilter)
add_subdirectory(${TOOLS}/specular-color)
add_subdirectory(${TOOLS}/uberz)
endif()
# Generate exported executables for cross-compiled builds (Android, WebGL, and iOS)
if (NOT CMAKE_CROSSCOMPILING)
export(TARGETS matc cmgen filamesh mipgen resgen uberz glslminifier FILE ${IMPORT_EXECUTABLES})
export(TARGETS matc cmgen filamesh mipgen resgen glslminifier FILE ${IMPORT_EXECUTABLES})
endif()
+2 -2
View File
@@ -31,7 +31,7 @@ repositories {
}
dependencies {
implementation 'com.google.android.filament:filament-android:1.24.0'
implementation 'com.google.android.filament:filament-android:1.21.3'
}
```
@@ -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:
```
pod 'Filament', '~> 1.24.0'
pod 'Filament', '~> 1.21.3'
```
### Snapshots
+4 -4
View File
@@ -50,13 +50,13 @@ Do not push to origin yet.
git cherry-pick rc/$RELEASE
```
Update the headers. The "main branch" header becomes a header for $NEXT_RELEASE, and a new "main
branch" header is added.
Update the headers. The "Next release" header becomes a header for $NEXT_RELEASE, and a new "Next
release" header is added.
For example, this:
```
## main branch
## Next release (main branch)
- foo
- bar
@@ -68,7 +68,7 @@ For example, this:
becomes:
```
## main branch
## Next release (main branch)
## v1.9.4
- foo
+1 -69
View File
@@ -3,80 +3,12 @@
This file contains one line summaries of commits that are worthy of mentioning in release notes.
A new header is inserted each time a *tag* is created.
## main branch
## v1.24.0
- ImGuiHelper: add support for Y flip.
- Metal: ignore `MTLTexture` formatting when importing external textures.
- materials: add a new `instanced` material parameter that is now mandatory in order to call `getInstanceIndex()`
- gltfio: UbershaderProvider now takes the ubershader archive in its constructor [⚠️ **API Change**]
- gltfio: Fix morphing with sparse accessors.
- gltfio: Fix models that use signed integers for morphing.
- engine: Documentation improvements regarding SkinningBuffer and fix an off-by-one assert when setting a SkinningBuffer.
- picking is now exposed to JavaScript
- gltf_viewer: Exercise picking functionality.
- OpenGL: add WebGL support for ReadPixels
- Vulkan: add assert and error message for OOM (debug builds)
- Vulkan: fix crash with picking and 2-component ReadPixels.
- backend: workaround broken GLES timer query on some Mali-Gxx old drivers
- backend: revert c049a1 & reenable b2cdf9 ("don't issue a flush systematically after framegraph's execute")
- gltfio: namespace now lives under Filament [⚠️ **API Change**]
- gltfio: UbershaderLoader renamed to UbershaderProvider [⚠️ **API Change**]
- gltfio: MaterialGenerator renamed to JitShaderProvider [⚠️ **API Change**]
## v1.23.2
- gltfio: Fix morphing for un-packed accessors.
- gltfio: Ubershaders are now packaged into flexible archives.
- gltfio: Remove poorly maintained lite flavor.
- engine: Disable user scissor while rendering the Shadow Maps.
- engine: Merge identical backend `RenderPrimitives` together.
- engine: Improve `ResourceAllocator` performance a bit by reserving 128 cache entries.
- utils: Remove `std::hash<T>` definitions for `libutils` types. Use `T::Hasher` explicitly instead. [⚠️ **API Change**]
- backend: Fix WGL context attributes.
- Metal: Fix potential invalid shaders when using gltfio in Ubershader mode. [⚠️ **Recompile Materials to get the fix**]
## v1.23.1
- gltfio: support skinning with bones that do not belong to any scene.
- gltfio: add `attachSkin` / `detachSkin` method to FilamentAsset.
- gltfio: ubershader mode: set sheen to `OPAQUE`.
- Metal: fix issues seen with dynamic resolution on M1 Macs.
- engine: add a "global" mode for render primitive's `blendOrder`.
- engine: remove `RenderManager::setGeometryAt(index, count)`. [⚠️ **API Change**]
- engine: fix overallocation by about 17MB.
- WebGL: Add JS bindings for Texture class methods.
## v1.23.0
- engine: Changed UBOs layout [⚠️ **Material breakage**].
- engine: Normals on morphed models have been fixed (core Filament change).
- Java: View has several minor changes due to generated code, such as field ordering.
- gltfio: Fix crash when reloading glTF assets.
- gltfio: introduce cross-fade animation API [**NEW API**].
## v1.22.2
- Java: Minor API change: rename `ssctStartTraceDistance` to `ssctShadowDistance`. [⚠️ **API Change**]
- Java: Minor API change: rename `blendingMode` to `blendMode`. [⚠️ **API Change**]
- engine: Fix some memory leaks.
## v1.22.1
- Metal: Shaders now use `half` floating-point arithmetic when possible for improved performance. [⚠️ **Recompile Materials**]
- engine: add support for presentation time in `Renderer`
- engine: added guard bands support for screen-space effects
- gltfio: Add multi-scene support.
- gltfio: Various glTF-related cleanup and enhancements.
- gltfio: Add support for KHR_texture_basisu.
## v1.22.1 (currently main branch)
## v1.22.0
- engine: Changed UBOs layout [⚠️ **Material breakage**].
- engine: Improve effects relying on mipmapping
- engine: Fix assert seen with VSM shadows.
- WebGL: Fix `isTextureFormatSupported` for ETC2 formats.
## v1.21.3
+6 -10
View File
@@ -81,10 +81,10 @@ buildscript {
'minSdk': 19,
'targetSdk': 31,
'compileSdk': 31,
'kotlin': '1.6.21',
'kotlin_coroutines': '1.6.1',
'kotlin': '1.6.10',
'kotlin_coroutines': '1.6.0',
'buildTools': '32.0.0',
'ndk': '24.0.8215888'
'ndk': '23.1.7779620'
]
ext.deps = [
@@ -101,12 +101,11 @@ buildscript {
dependencies {
// NOTE: See TODO in gradle.properties once we move to Gradle 7.4
classpath 'com.android.tools.build:gradle:7.2.0'
classpath 'com.android.tools.build:gradle:7.1.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}"
}
ext.cmakeArgs = [
"--no-warn-unused-cli",
"-DANDROID_PIE=ON",
"-DANDROID_PLATFORM=21",
"-DANDROID_STL=c++_static",
@@ -118,6 +117,8 @@ buildscript {
ext.cppFlags = [
"-std=c++17",
"-Wno-unused-command-line-argument",
"-Wl,--hash-style=both", // Required to support API levels below 23
"-fno-stack-protector",
"-fno-exceptions",
"-fno-unwind-tables",
@@ -130,13 +131,8 @@ buildscript {
"-fomit-frame-pointer",
"-ffunction-sections",
"-fdata-sections",
"-no-canonical-prefixes",
"-Wformat",
"-Werror=format-security",
"-Wno-unused-command-line-argument",
"-Wl,--gc-sections",
"-Wl,-Bsymbolic-functions",
"-Wl,--hash-style=both", // Required to support API levels below 23
]
ext.abis = abis
+1
View File
@@ -1,3 +1,4 @@
plugins {
id 'groovy-gradle-plugin'
}
-2
View File
@@ -1,6 +1,4 @@
android {
namespace 'com.google.android.filament.filamat'
flavorDimensions "functionality"
productFlavors {
full {
-4
View File
@@ -1,7 +1,3 @@
android {
namespace 'com.google.android.filament'
}
dependencies {
implementation deps.androidx.annotations
}
@@ -120,14 +120,6 @@ Java_com_google_android_filament_RenderableManager_nBuilderBlendOrder(JNIEnv*, j
builder->blendOrder((size_t) index, (uint16_t) blendOrder);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_RenderableManager_nBuilderGlobalBlendOrderEnabled(JNIEnv*, jclass,
jlong nativeBuilder, jint index, jboolean enabled) {
RenderableManager::Builder *builder = (RenderableManager::Builder *) nativeBuilder;
builder->globalBlendOrderEnabled((size_t) index, (bool) enabled);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_RenderableManager_nBuilderBoundingBox(JNIEnv*, jclass,
jlong nativeBuilder, jfloat cx, jfloat cy, jfloat cz, jfloat ex, jfloat ey, jfloat ez) {
@@ -430,6 +422,15 @@ Java_com_google_android_filament_RenderableManager_nSetGeometryAt__JIIIJJII(JNIE
(size_t) offset, (size_t) count);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_RenderableManager_nSetGeometryAt__JIIIII(JNIEnv*, jclass,
jlong nativeRenderableManager, jint i, jint primitiveIndex, jint primitiveType, jint offset,
jint count) {
RenderableManager *rm = (RenderableManager *) nativeRenderableManager;
rm->setGeometryAt((RenderableManager::Instance) i, (size_t) primitiveIndex,
(RenderableManager::PrimitiveType) primitiveType, (size_t) offset, (size_t) count);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_RenderableManager_nSetBlendOrderAt(JNIEnv*, jclass,
jlong nativeRenderableManager, jint i, jint primitiveIndex, jint blendOrder) {
@@ -438,14 +439,6 @@ Java_com_google_android_filament_RenderableManager_nSetBlendOrderAt(JNIEnv*, jcl
(uint16_t) blendOrder);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_RenderableManager_nSetGlobalBlendOrderEnabledAt(JNIEnv*, jclass,
jlong nativeRenderableManager, jint i, jint primitiveIndex, jboolean enabled) {
RenderableManager *rm = (RenderableManager *) nativeRenderableManager;
rm->setGlobalBlendOrderEnabledAt((RenderableManager::Instance) i, (size_t) primitiveIndex,
(bool) enabled);
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_RenderableManager_nGetEnabledAttributesAt(JNIEnv*, jclass,
jlong nativeRenderableManager, jint i, jint primitiveIndex) {
@@ -156,9 +156,12 @@ Java_com_google_android_filament_Renderer_nResetUserTime(JNIEnv*, jclass, jlong
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Renderer_nSetDisplayInfo(JNIEnv*, jclass, jlong nativeRenderer, jfloat refreshRate) {
Java_com_google_android_filament_Renderer_nSetDisplayInfo(JNIEnv*, jclass, jlong nativeRenderer,
jfloat refreshRate, jlong presentationDeadlineNanos, jlong vsyncOffsetNanos) {
Renderer *renderer = (Renderer *) nativeRenderer;
renderer->setDisplayInfo({ .refreshRate = refreshRate });
renderer->setDisplayInfo({ .refreshRate = refreshRate,
.presentationDeadlineNanos = (uint64_t)presentationDeadlineNanos,
.vsyncOffsetNanos = (uint64_t)vsyncOffsetNanos });
}
extern "C" JNIEXPORT void JNICALL
@@ -180,10 +183,3 @@ Java_com_google_android_filament_Renderer_nSetClearOptions(JNIEnv *, jclass ,
.clear = (bool) clear,
.discard = (bool) discard});
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Renderer_nSetPresentationTime(JNIEnv *, jclass ,
jlong nativeRenderer, jlong monotonicClockNanos) {
Renderer *renderer = (Renderer *) nativeRenderer;
renderer->setPresentationTime(monotonicClockNanos);
}
+2 -10
View File
@@ -259,14 +259,14 @@ Java_com_google_android_filament_View_nSetAmbientOcclusionOptions(JNIEnv*, jclas
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetSSCTOptions(JNIEnv *, jclass, jlong nativeView,
jfloat ssctLightConeRad, jfloat ssctShadowDistance, jfloat ssctContactDistanceMax,
jfloat ssctLightConeRad, jfloat ssctStartTraceDistance, jfloat ssctContactDistanceMax,
jfloat ssctIntensity, jfloat ssctLightDirX, jfloat ssctLightDirY, jfloat ssctLightDirZ,
jfloat ssctDepthBias, jfloat ssctDepthSlopeBias, jint ssctSampleCount,
jint ssctRayCount, jboolean ssctEnabled) {
View* view = (View*) nativeView;
View::AmbientOcclusionOptions options = view->getAmbientOcclusionOptions();
options.ssct.lightConeRad = ssctLightConeRad;
options.ssct.shadowDistance = ssctShadowDistance;
options.ssct.shadowDistance = ssctStartTraceDistance;
options.ssct.contactDistanceMax = ssctContactDistanceMax;
options.ssct.intensity = ssctIntensity;
options.ssct.lightDirection = math::float3{ ssctLightDirX, ssctLightDirY, ssctLightDirZ };
@@ -461,11 +461,3 @@ Java_com_google_android_filament_View_nPick(JNIEnv* env, jclass,
JniCallback::postToJavaAndDestroy(callback);
}, callback->getHandler());
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetGuardBandOptions(JNIEnv *, jclass,
jlong nativeView, jboolean enabled) {
View* view = (View*) nativeView;
view->setGuardBandOptions({ .enabled = (bool)enabled });
}
@@ -104,12 +104,12 @@ public class MorphTargetBuffer {
}
/**
* Updates float4 positions for the given morph target.
* Updates positions of morph target at the index.
*
* @param engine {@link Engine} instance
* @param targetIndex The index of morph target to be updated
* @param positions An array with at least count*4 floats
* @param count Number of float4 vectors in positions to be consumed
* @param positions Pointer to at least count positions
* @param count Number of position elements in positions
*/
public void setPositionsAt(@NonNull Engine engine,
@IntRange(from = 0) int targetIndex,
@@ -122,15 +122,12 @@ public class MorphTargetBuffer {
}
/**
* Updates tangents for the given morph target.
*
* These quaternions must be represented as signed shorts, where real numbers in the [-1,+1]
* range multiplied by 32767.
* Updates tangents of morph target at the index.
*
* @param engine {@link Engine} instance
* @param targetIndex The index of morph target to be updated
* @param tangents An array with at least "count*4" shorts
* @param count number of short4 quaternions in tangents
* @param tangents Pointer to at least count tangents
* @param count Number of tangent elements in tangents
*/
public void setTangentsAt(@NonNull Engine engine,
@IntRange(from = 0) int targetIndex,
@@ -143,14 +140,14 @@ public class MorphTargetBuffer {
}
/**
* @return number of vertices in this {@link MorphTargetBuffer}
* @return number of vertex count in this {@link MorphTargetBuffer}
*/
public int getVertexCount() {
return nGetVertexCount(mNativeObject);
}
/**
* @return number of morph targets in this {@link MorphTargetBuffer}
* @return number of target count in this {@link MorphTargetBuffer}
*/
public int getCount() {
return nGetCount(mNativeObject);
@@ -191,9 +191,7 @@ public class RenderableManager {
}
/**
* Sets the drawing order for blended primitives. The drawing order is either global or
* local (default) to this Renderable. In either case, the Renderable priority takes
* precedence.
* Sets an ordering index for blended primitives that all live at the same Z value.
*
* @param index the primitive of interest
* @param blendOrder draw order number (0 by default). Only the lowest 15 bits are used.
@@ -205,18 +203,6 @@ public class RenderableManager {
return this;
}
/**
* Sets whether the blend order is global or local to this Renderable (by default).
*
* @param index the primitive of interest
* @param enabled true for global, false for local blend ordering.
*/
@NonNull
public Builder globalBlendOrderEnabled(@IntRange(from = 0) int index, boolean enabled) {
nBuilderGlobalBlendOrderEnabled(mNativeBuilder, index, enabled);
return this;
}
/**
* The axis-aligned bounding box of the renderable.
*
@@ -806,9 +792,18 @@ public class RenderableManager {
0, indices.getIndexCount());
}
/**
* Changes the drawing order for blended primitives. The drawing order is either global or
* local (default) to this Renderable. In either case, the Renderable priority takes precedence.
/**
* Changes the geometry for the given primitive.
*
* @see Builder#geometry Builder.geometry
*/
public void setGeometryAt(@EntityInstance int i, @IntRange(from = 0) int primitiveIndex,
@NonNull PrimitiveType type, @IntRange(from = 0) int offset, @IntRange(from = 0) int count) {
nSetGeometryAt(mNativeObject, i, primitiveIndex, type.getValue(), offset, count);
}
/**
* Changes the ordering index for blended primitives that all live at the same Z value.
*
* @see Builder#blendOrder
*
@@ -821,20 +816,6 @@ public class RenderableManager {
nSetBlendOrderAt(mNativeObject, instance, primitiveIndex, blendOrder);
}
/**
* Changes whether the blend order is global or local to this Renderable (by default).
*
* @see Builder#globalBlendOrderEnabled
*
* @param instance the renderable of interest
* @param primitiveIndex the primitive of interest
* @param enabled true for global, false for local blend ordering.
*/
public void setGlobalBlendOrderEnabledAt(@EntityInstance int instance, @IntRange(from = 0) int primitiveIndex,
boolean enabled) {
nSetGlobalBlendOrderEnabledAt(mNativeObject, instance, primitiveIndex, enabled);
}
/**
* Retrieves the set of enabled attribute slots in the given primitive's VertexBuffer.
*/
@@ -872,7 +853,6 @@ public class RenderableManager {
private static native void nBuilderGeometry(long nativeBuilder, int index, int value, long nativeVertexBuffer, long nativeIndexBuffer, int offset, int minIndex, int maxIndex, int count);
private static native void nBuilderMaterial(long nativeBuilder, int index, long nativeMaterialInstance);
private static native void nBuilderBlendOrder(long nativeBuilder, int index, int blendOrder);
private static native void nBuilderGlobalBlendOrderEnabled(long nativeBuilder, int index, boolean enabled);
private static native void nBuilderBoundingBox(long nativeBuilder, float cx, float cy, float cz, float ex, float ey, float ez);
private static native void nBuilderLayerMask(long nativeBuilder, int select, int value);
private static native void nBuilderPriority(long nativeBuilder, int priority);
@@ -911,7 +891,7 @@ public class RenderableManager {
private static native void nSetMaterialInstanceAt(long nativeRenderableManager, int i, int primitiveIndex, long nativeMaterialInstance);
private static native long nGetMaterialInstanceAt(long nativeRenderableManager, int i, int primitiveIndex);
private static native void nSetGeometryAt(long nativeRenderableManager, int i, int primitiveIndex, int primitiveType, long nativeVertexBuffer, long nativeIndexBuffer, int offset, int count);
private static native void nSetGeometryAt(long nativeRenderableManager, int i, int primitiveIndex, int primitiveType, int offset, int count);
private static native void nSetBlendOrderAt(long nativeRenderableManager, int i, int primitiveIndex, int blendOrder);
private static native void nSetGlobalBlendOrderEnabledAt(long nativeRenderableManager, int i, int primitiveIndex, boolean enabled);
private static native int nGetEnabledAttributesAt(long nativeRenderableManager, int i, int primitiveIndex);
}
@@ -61,17 +61,13 @@ public class Renderer {
/**
* How far in advance a buffer must be queued for presentation at a given time in ns
* On Android you can use {@link android.view.Display#getPresentationDeadlineNanos()}.
* @deprecated this value is ignored
*/
@Deprecated
public long presentationDeadlineNanos = 0;
/**
* Offset by which vsyncSteadyClockTimeNano provided in beginFrame() is offset in ns
* On Android you can use {@link android.view.Display#getAppVsyncOffsetNanos()}.
* @deprecated this value is ignored
*/
@Deprecated
public long vsyncOffsetNanos = 0;
};
@@ -179,7 +175,8 @@ public class Renderer {
*/
public void setDisplayInfo(@NonNull DisplayInfo info) {
mDisplayInfo = info;
nSetDisplayInfo(getNativeObject(), info.refreshRate);
nSetDisplayInfo(getNativeObject(),
info.refreshRate, info.presentationDeadlineNanos, info.vsyncOffsetNanos);
}
/**
@@ -250,23 +247,6 @@ public class Renderer {
return mEngine;
}
/**
* Set the time at which the frame must be presented to the display.
* <p>
* This must be called between {@link #beginFrame} and {@link #endFrame}.
* </p>
*
* @param monotonicClockNanos The time in nanoseconds corresponding to the system monotonic
* up-time clock. The presentation time is typically set in the
* middle of the period of interest and cannot be too far in the
* future as it is limited by how many buffers are available in
* the display sub-system. Typically it is set to 1 or 2 vsync
* periods away.
*/
public void setPresentationTime(long monotonicClockNanos) {
nSetPresentationTime(getNativeObject(), monotonicClockNanos);
}
/**
* Sets up a frame for this <code>Renderer</code>.
* <p><code>beginFrame</code> manages frame pacing, and returns whether or not a frame should be
@@ -684,7 +664,6 @@ public class Renderer {
mNativeObject = 0;
}
private static native void nSetPresentationTime(long nativeObject, long monotonicClockNanos);
private static native boolean nBeginFrame(long nativeRenderer, long nativeSwapChain, long frameTimeNanos);
private static native void nEndFrame(long nativeRenderer);
private static native void nRender(long nativeRenderer, long nativeView);
@@ -706,7 +685,8 @@ public class Renderer {
Object handler, Runnable callback);
private static native double nGetUserTime(long nativeRenderer);
private static native void nResetUserTime(long nativeRenderer);
private static native void nSetDisplayInfo(long nativeRenderer, float refreshRate);
private static native void nSetDisplayInfo(long nativeRenderer,
float refreshRate, long presentationDeadlineNanos, long vsyncOffsetNanos);
private static native void nSetFrameRateOptions(long nativeRenderer,
float interval, float headRoomRatio, float scaleRate, int history);
private static native void nSetClearOptions(long nativeRenderer,
File diff suppressed because it is too large Load Diff
@@ -157,6 +157,8 @@ public class DisplayHelper {
info = new Renderer.DisplayInfo();
}
info.refreshRate = DisplayHelper.getRefreshRate(display);
info.presentationDeadlineNanos = DisplayHelper.getPresentationDeadlineNanos(display);
info.vsyncOffsetNanos = DisplayHelper.getAppVsyncOffsetNanos(display);
return info;
}
+7 -9
View File
@@ -1,8 +1,6 @@
apply plugin: 'kotlin-android'
android {
namespace 'com.google.android.filament.utils'
sourceSets {
main {
kotlin.srcDirs += "src/main/java"
@@ -12,14 +10,14 @@ android {
defaultConfig {
missingDimensionStrategy 'functionality', 'full'
}
// No need to package up the following shared libs, which arise as a side effect of our
// externalNativeBuild dependencies. When clients pick and choose from project-level gradle
// dependencies, these shared libs already get pulled in, so we need to avoid the error:
// "More than one file was found with OS independent path ..."
packagingOptions {
// No need to package up the following shared libs, which arise as a side effect of our
// externalNativeBuild dependencies. When clients pick and choose from project-level gradle
// dependencies, these shared libs already get pulled in, so we need to avoid the error:
// "More than one file was found with OS independent path ..."
jniLibs {
excludes += ['lib/*/libfilament-jni.so', 'lib/*/libgltfio-jni.so']
}
exclude 'lib/*/libfilament-jni.so'
exclude 'lib/*/libgltfio-jni.so'
}
}
@@ -114,7 +114,7 @@ class ModelViewer(
view.scene = scene
view.camera = camera
materialProvider = UbershaderProvider(engine)
materialProvider = UbershaderLoader(engine)
assetLoader = AssetLoader(engine, materialProvider, EntityManager.get())
resourceLoader = ResourceLoader(engine, normalizeSkinningWeights, recomputeBoundingBoxes, ignoreBindTransform)
+30 -30
View File
@@ -23,57 +23,48 @@ add_library(basis_transcoder STATIC IMPORTED)
set_target_properties(basis_transcoder PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libbasis_transcoder.a)
add_library(zstd STATIC IMPORTED)
set_target_properties(zstd PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libzstd.a)
add_library(utils STATIC IMPORTED)
set_target_properties(utils PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libutils.a)
add_library(uberzlib STATIC IMPORTED)
set_target_properties(uberzlib PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libuberzlib.a)
add_library(gltfio_resources STATIC IMPORTED)
set_target_properties(gltfio_resources PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libgltfio_resources.a)
add_library(uberarchive STATIC IMPORTED)
set_target_properties(uberarchive PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libuberarchive.a)
add_library(gltfio_resources_lite STATIC IMPORTED)
set_target_properties(gltfio_resources_lite PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libgltfio_resources_lite.a)
set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} -Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/libgltfio-jni.map")
set(GLTFIO_SRCS
${GLTFIO_DIR}/include/gltfio/Animator.h
${GLTFIO_DIR}/include/gltfio/AssetLoader.h
${GLTFIO_DIR}/include/gltfio/MaterialProvider.h
${GLTFIO_DIR}/include/gltfio/ResourceLoader.h
${GLTFIO_DIR}/include/gltfio/FilamentAsset.h
${GLTFIO_DIR}/include/gltfio/FilamentInstance.h
${GLTFIO_DIR}/include/gltfio/MaterialProvider.h
${GLTFIO_DIR}/include/gltfio/NodeManager.h
${GLTFIO_DIR}/include/gltfio/ResourceLoader.h
${GLTFIO_DIR}/include/gltfio/TextureProvider.h
${GLTFIO_DIR}/include/gltfio/math.h
${GLTFIO_DIR}/src/ArchiveCache.cpp
${GLTFIO_DIR}/src/ArchiveCache.h
${GLTFIO_DIR}/src/Animator.cpp
${GLTFIO_DIR}/src/AssetLoader.cpp
${GLTFIO_DIR}/src/DependencyGraph.cpp
${GLTFIO_DIR}/src/DependencyGraph.h
${GLTFIO_DIR}/src/DracoCache.cpp
${GLTFIO_DIR}/src/DracoCache.h
${GLTFIO_DIR}/src/DependencyGraph.cpp
${GLTFIO_DIR}/src/DependencyGraph.h
${GLTFIO_DIR}/src/FFilamentAsset.h
${GLTFIO_DIR}/src/FFilamentInstance.h
${GLTFIO_DIR}/src/FilamentAsset.cpp
${GLTFIO_DIR}/src/FFilamentInstance.h
${GLTFIO_DIR}/src/FilamentInstance.cpp
${GLTFIO_DIR}/src/FNodeManager.h
${GLTFIO_DIR}/src/GltfEnums.h
${GLTFIO_DIR}/src/Ktx2Provider.cpp
${GLTFIO_DIR}/src/MaterialProvider.cpp
${GLTFIO_DIR}/src/NodeManager.cpp
${GLTFIO_DIR}/src/ResourceLoader.cpp
${GLTFIO_DIR}/src/StbProvider.cpp
${GLTFIO_DIR}/src/TangentsJob.cpp
${GLTFIO_DIR}/src/TangentsJob.h
${GLTFIO_DIR}/src/UbershaderProvider.cpp
${GLTFIO_DIR}/src/TangentsJob.cpp
${GLTFIO_DIR}/src/UbershaderLoader.cpp
${GLTFIO_DIR}/src/Wireframe.cpp
${GLTFIO_DIR}/src/Wireframe.h
${GLTFIO_DIR}/src/upcast.h
@@ -84,10 +75,11 @@ set(GLTFIO_SRCS
src/main/cpp/FilamentInstance.cpp
src/main/cpp/MaterialKey.cpp
src/main/cpp/MaterialKey.h
src/main/cpp/UbershaderProvider.cpp
src/main/cpp/UbershaderLoader.cpp
src/main/cpp/ResourceLoader.cpp
${FILAMENT_DIR}/include/gltfio/materials/uberarchive.h
${FILAMENT_DIR}/include/gltfio/resources/gltfresources_lite.h
${FILAMENT_DIR}/include/gltfio/resources/gltfresources.h
../common/NioUtils.cpp
)
@@ -95,9 +87,9 @@ set(GLTFIO_SRCS
set(GLTFIO_INCLUDE_DIRS
..
${FILAMENT_DIR}/include
${FILAMENT_DIR}/include/gltfio/resources
../../filament/backend/include
../../libs/gltfio/include
../../third_party/basisu/zstd
../../third_party/cgltf
../../third_party/robin-map
../../third_party/hat-trie
@@ -110,8 +102,16 @@ add_library(gltfio-jni SHARED ${GLTFIO_SRCS})
target_include_directories(gltfio-jni PRIVATE ${GLTFIO_INCLUDE_DIRS})
set_target_properties(gltfio-jni PROPERTIES LINK_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/libgltfio-jni.symbols)
set_target_properties(gltfio-jni PROPERTIES LINK_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/libgltfio-jni.map)
target_link_libraries(gltfio-jni filament-jni utils uberzlib log stb ktxreader basis_transcoder zstd uberarchive)
target_link_libraries(gltfio-jni dracodec)
target_compile_definitions(gltfio-jni PUBLIC GLTFIO_DRACO_SUPPORTED=1)
target_include_directories(gltfio-jni PRIVATE ${DRACO_DIR}/src)
target_include_directories(gltfio-jni PRIVATE ${DRACO_DIR}/tnt)
if(GLTFIO_LITE)
target_compile_definitions(gltfio-jni PUBLIC GLTFIO_LITE=1)
target_link_libraries(gltfio-jni filament-jni utils log stb ktxreader basis_transcoder gltfio_resources_lite)
else()
target_link_libraries(gltfio-jni filament-jni utils log stb ktxreader basis_transcoder gltfio_resources)
# Enable Draco in the non-lite variant of gltfio.
target_link_libraries(gltfio-jni dracodec)
target_compile_definitions(gltfio-jni PUBLIC GLTFIO_DRACO_SUPPORTED=1)
target_include_directories(gltfio-jni PRIVATE ${DRACO_DIR}/src)
target_include_directories(gltfio-jni PRIVATE ${DRACO_DIR}/tnt)
endif()
+22 -10
View File
@@ -1,21 +1,28 @@
android {
namespace 'com.google.android.filament.gltfio'
flavorDimensions "functionality"
productFlavors {
full {
dimension "functionality"
}
}
packagingOptions {
// No need to package up the following shared libs, which arise as a side effect of our
// externalNativeBuild dependencies. When clients pick and choose from project-level gradle
// dependencies, these shared libs already get pulled in, so we need to avoid the error:
// "More than one file was found with OS independent path ..."
jniLibs {
excludes += ['lib/*/libfilament-jni.so']
lite {
dimension "functionality"
externalNativeBuild {
cmake {
arguments.add("-DGLTFIO_LITE=ON")
}
}
}
}
// No need to package up the following shared libs, which arise as a side effect of our
// externalNativeBuild dependencies. When clients pick and choose from project-level gradle
// dependencies, these shared libs already get pulled in, so we need to avoid the error:
// "More than one file was found with OS independent path ..."
packagingOptions {
exclude 'lib/*/libfilament-jni.so'
}
}
dependencies {
@@ -33,6 +40,11 @@ afterEvaluate { project ->
artifactId = POM_ARTIFACT_ID_FULL
from components.fullRelease
}
liteRelease(MavenPublication) {
artifactId = POM_ARTIFACT_ID_LITE
from components.liteRelease
}
}
}
}
@@ -20,7 +20,7 @@
using namespace filament;
using namespace filament::math;
using namespace filament::gltfio;
using namespace gltfio;
using namespace utils;
extern "C" JNIEXPORT void JNICALL
@@ -36,13 +36,6 @@ Java_com_google_android_filament_gltfio_Animator_nUpdateBoneMatrices(JNIEnv*, jc
animator->updateBoneMatrices();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_Animator_nApplyCrossFade(JNIEnv*, jclass, jlong nativeAnimator,
jint previousAnimIndex, jfloat previousAnimTime, jfloat alpha) {
Animator* animator = (Animator*) nativeAnimator;
animator->applyCrossFade(previousAnimIndex, previousAnimTime, alpha);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_Animator_nResetBoneMatrices(JNIEnv*, jclass, jlong nativeAnimator) {
Animator* animator = (Animator*) nativeAnimator;
@@ -30,7 +30,7 @@
#include "MaterialKey.h"
using namespace filament;
using namespace filament::gltfio;
using namespace gltfio;
using namespace utils;
class JavaMaterialProvider : public MaterialProvider {
@@ -20,7 +20,7 @@
using namespace filament;
using namespace filament::math;
using namespace filament::gltfio;
using namespace gltfio;
using namespace utils;
extern "C" JNIEXPORT jint JNICALL
@@ -120,34 +120,10 @@ extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_FilamentAsset_nGetLightEntities(JNIEnv* env, jclass,
jlong nativeAsset, jintArray result) {
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
const jsize available = env->GetArrayLength(result);
const size_t minCount = std::min(available, (jsize) asset->getLightEntityCount());
if (minCount == 0) {
return;
}
jsize available = env->GetArrayLength(result);
Entity* entities = (Entity*) env->GetIntArrayElements(result, nullptr);
std::copy_n(asset->getLightEntities(), minCount, entities);
env->ReleaseIntArrayElements(result, (jint*) entities, 0);
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_gltfio_FilamentAsset_nGetRenderableEntityCount(JNIEnv*, jclass,
jlong nativeAsset) {
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
return asset->getRenderableEntityCount();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_FilamentAsset_nGetRenderableEntities(JNIEnv* env, jclass,
jlong nativeAsset, jintArray result) {
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
const jsize available = env->GetArrayLength(result);
const size_t minCount = std::min(available, (jsize) asset->getRenderableEntityCount());
if (minCount == 0) {
return;
}
Entity* entities = (Entity*) env->GetIntArrayElements(result, nullptr);
std::copy_n(asset->getRenderableEntities(), minCount, entities);
std::copy_n(asset->getLightEntities(),
std::min(available, (jsize) asset->getLightEntityCount()), entities);
env->ReleaseIntArrayElements(result, (jint*) entities, 0);
}
@@ -155,13 +131,10 @@ extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_FilamentAsset_nGetCameraEntities(JNIEnv* env, jclass,
jlong nativeAsset, jintArray result) {
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
const jsize available = env->GetArrayLength(result);
const size_t minCount = std::min(available, (jsize) asset->getCameraEntityCount());
if (minCount == 0) {
return;
}
jsize available = env->GetArrayLength(result);
Entity* entities = (Entity*) env->GetIntArrayElements(result, nullptr);
std::copy_n(asset->getCameraEntities(), minCount, entities);
std::copy_n(asset->getCameraEntities(),
std::min(available, (jsize) asset->getCameraEntityCount()), entities);
env->ReleaseIntArrayElements(result, (jint*) entities, 0);
}
@@ -340,19 +313,3 @@ Java_com_google_android_filament_gltfio_FilamentAsset_nReleaseSourceData(JNIEnv*
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
asset->releaseSourceData();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_FilamentAsset_nAttachSkin(JNIEnv* env, jclass,
jlong nativeAsset, jint skinIndex, jint targetEntity) {
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
Entity target = Entity::import(targetEntity);
asset->attachSkin(skinIndex, target);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_FilamentAsset_nDetachSkin(JNIEnv* env, jclass,
jlong nativeAsset, jint skinIndex, jint targetEntity) {
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
Entity target = Entity::import(targetEntity);
asset->detachSkin(skinIndex, target);
}
@@ -20,7 +20,7 @@
#include <algorithm>
using namespace filament::gltfio;
using namespace gltfio;
using namespace utils;
extern "C" JNIEXPORT jint JNICALL
@@ -20,7 +20,7 @@
#include "MaterialKey.h"
using namespace filament::gltfio;
using namespace gltfio;
MaterialKeyHelper& MaterialKeyHelper::get() {
static MaterialKeyHelper helper;
@@ -22,12 +22,10 @@
class MaterialKeyHelper {
public:
using MaterialKey = filament::gltfio::MaterialKey;
static MaterialKeyHelper& get();
void copy(JNIEnv* env, MaterialKey& dst, jobject src);
void copy(JNIEnv* env, jobject dst, const MaterialKey& src);
void copy(JNIEnv* env, gltfio::MaterialKey& dst, jobject src);
void copy(JNIEnv* env, jobject dst, const gltfio::MaterialKey& src);
void init(JNIEnv* env); // called only from the Java static class constructor
@@ -26,7 +26,7 @@
#include "common/NioUtils.h"
using namespace filament;
using namespace filament::gltfio;
using namespace gltfio;
using namespace utils;
static void destroy(void*, size_t, void *userData) {
@@ -17,38 +17,37 @@
#include <jni.h>
#include <gltfio/MaterialProvider.h>
#include <gltfio/materials/uberarchive.h>
#include <utils/debug.h>
#include "MaterialKey.h"
using namespace filament;
using namespace filament::gltfio;
using namespace gltfio;
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_gltfio_UbershaderProvider_nCreateUbershaderProvider(JNIEnv*, jclass,
Java_com_google_android_filament_gltfio_UbershaderLoader_nCreateUbershaderLoader(JNIEnv*, jclass,
jlong nativeEngine) {
Engine* engine = (Engine*) nativeEngine;
return (jlong) createUbershaderProvider(engine, UBERARCHIVE_DEFAULT_DATA, UBERARCHIVE_DEFAULT_SIZE);
return (jlong) createUbershaderLoader(engine);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_UbershaderProvider_nDestroyUbershaderProvider(JNIEnv*, jclass,
Java_com_google_android_filament_gltfio_UbershaderLoader_nDestroyUbershaderLoader(JNIEnv*, jclass,
jlong nativeProvider) {
auto provider = (MaterialProvider*) nativeProvider;
delete provider;
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_UbershaderProvider_nDestroyMaterials(JNIEnv*, jclass,
Java_com_google_android_filament_gltfio_UbershaderLoader_nDestroyMaterials(JNIEnv*, jclass,
jlong nativeProvider) {
auto provider = (MaterialProvider*) nativeProvider;
provider->destroyMaterials();
}
extern "C" JNIEXPORT long JNICALL
Java_com_google_android_filament_gltfio_UbershaderProvider_nCreateMaterialInstance(JNIEnv* env, jclass,
Java_com_google_android_filament_gltfio_UbershaderLoader_nCreateMaterialInstance(JNIEnv* env, jclass,
jlong nativeProvider, jobject materialKey, jintArray uvmap, jstring label) {
MaterialKey nativeKey = {};
@@ -81,14 +80,14 @@ Java_com_google_android_filament_gltfio_UbershaderProvider_nCreateMaterialInstan
}
extern "C" JNIEXPORT int JNICALL
Java_com_google_android_filament_gltfio_UbershaderProvider_nGetMaterialCount(JNIEnv*, jclass,
Java_com_google_android_filament_gltfio_UbershaderLoader_nGetMaterialCount(JNIEnv*, jclass,
jlong nativeProvider) {
auto provider = (MaterialProvider*) nativeProvider;
return provider->getMaterialsCount();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_UbershaderProvider_nGetMaterials(JNIEnv* env, jclass,
Java_com_google_android_filament_gltfio_UbershaderLoader_nGetMaterials(JNIEnv* env, jclass,
jlong nativeProvider, jlongArray result) {
auto provider = (MaterialProvider *) nativeProvider;
auto materials = provider->getMaterials();
@@ -66,27 +66,6 @@ public class Animator {
nUpdateBoneMatrices(getNativeObject());
}
/**
* Applies a blended transform to the union of nodes affected by two animations.
* Used for cross-fading from a previous skinning-based animation or rigid body animation.
*
* First, this stashes the current transform hierarchy into a transient memory buffer.
*
* Next, this applies previousAnimIndex / previousAnimTime to the actual asset by internally
* calling applyAnimation().
*
* Finally, the stashed local transforms are lerped (via the scale / translation / rotation
* components) with their live counterparts, and the results are pushed to the asset.
*
* To achieve a cross fade effect with skinned models, clients will typically call animator
* methods in this order: (1) applyAnimation (2) applyCrossFade (3) updateBoneMatrices. The
* animation that clients pass to applyAnimation is the "current" animation corresponding to
* alpha=1, while the "previous" animation passed to applyCrossFade corresponds to alpha=0.
*/
public void applyCrossFade(int previousAnimIndex, float previousAnimTime, float alpha) {
nApplyCrossFade(getNativeObject(), previousAnimIndex, previousAnimTime, alpha);
}
/**
* Pass the identity matrix into all bone nodes, useful for returning to the T pose.
*
@@ -139,7 +118,6 @@ public class Animator {
private static native void nApplyAnimation(long nativeAnimator, int index, float time);
private static native void nUpdateBoneMatrices(long nativeAnimator);
private static native void nApplyCrossFade(long nativeAnimator, int animIndex, float animTime, float alpha);
private static native void nResetBoneMatrices(long nativeAnimator);
private static native int nGetAnimationCount(long nativeAnimator);
private static native float nGetAnimationDuration(long nativeAnimator, int index);
@@ -45,7 +45,7 @@ import java.nio.Buffer;
*
* ...
*
* materialProvider = UbershaderProvider(engine)
* materialProvider = UbershaderLoader(engine)
* assetLoader = AssetLoader(engine, materialProvider, EntityManager.get())
*
* filamentAsset = assets.open("models/lucy.gltf").use { input -&gt;
@@ -30,9 +30,9 @@ import com.google.android.filament.MaterialInstance;
*
* <p>For usage instructions, see the documentation for {@link AssetLoader}.</p>
*
* <p>This class owns a hierarchy of entities that have been loaded from a glTF asset. Every entity
* has a <code>TransformManager</code> component, and some entities also have compnents managed by
* <code>NameComponentManager</code>, <code>RenderableManager</code>, and others.</p>
* <p>This class owns a hierarchy of entities that have been loaded from a glTF asset. Every entity has
* a <code>TransformManager</code> component, and some entities also have
* <code>NameComponentManager</code> and/or <code>RenderableManager</code> components.</p>
*
* <p>In addition to the aforementioned entities, an asset has strong ownership over a list of
* <code>VertexBuffer</code>, <code>IndexBuffer</code>, <code>MaterialInstance</code>, and
@@ -113,15 +113,6 @@ public class FilamentAsset {
return result;
}
/**
* Gets only the entities that have renderable components.
*/
public @NonNull @Entity int[] getRenderableEntities() {
int[] result = new int[nGetRenderableEntityCount(mNativeObject)];
nGetRenderableEntities(mNativeObject, result);
return result;
}
/**
* Gets only the entities that have camera components.
*
@@ -241,37 +232,17 @@ public class FilamentAsset {
return result;
}
/**
* Attaches the given skin to the given node, which must have an associated mesh with
* BONE_INDICES and BONE_WEIGHTS attributes.
*
* This is a no-op if the given skin index or target is invalid.
*/
public void attachSkin(@IntRange(from = 0) int skinIndex, @Entity int target) {
nAttachSkin(getNativeObject(), skinIndex, target);
}
/**
* Attaches the given skin to the given node, which must have an associated mesh with
* BONE_INDICES and BONE_WEIGHTS attributes.
*
* This is a no-op if the given skin index or target is invalid.
*/
public void detachSkin(@IntRange(from = 0) int skinIndex, @Entity int target) {
nDetachSkin(getNativeObject(), skinIndex, target);
}
/**
* Gets the joint count at skin index in this asset.
*/
public int getJointCountAt(@IntRange(from = 0) int skinIndex) {
public int getJointCountAt(int skinIndex) {
return nGetJointCountAt(getNativeObject(), skinIndex);
}
/**
* Gets joints at skin index in this asset.
*/
public @NonNull @Entity int[] getJointsAt(@IntRange(from = 0) int skinIndex) {
public @NonNull @Entity int[] getJointsAt(int skinIndex) {
int[] result = new int[getJointCountAt(skinIndex)];
nGetJointsAt(getNativeObject(), skinIndex, result);
return result;
@@ -350,9 +321,6 @@ public class FilamentAsset {
private static native int nGetLightEntityCount(long nativeAsset);
private static native void nGetLightEntities(long nativeAsset, int[] result);
private static native int nGetRenderableEntityCount(long nativeAsset);
private static native void nGetRenderableEntities(long nativeAsset, int[] result);
private static native int nGetCameraEntityCount(long nativeAsset);
private static native void nGetCameraEntities(long nativeAsset, int[] result);
@@ -365,9 +333,6 @@ public class FilamentAsset {
private static native int nGetMorphTargetCount(long nativeAsset, int entity);
private static native void nGetMorphTargetNames(long nativeAsset, int entity, String[] result);
private static native void nAttachSkin(long nativeAsset, int skinIndex, int entity);
private static native void nDetachSkin(long nativeAsset, int skinIndex, int entity);
private static native void nGetBoundingBox(long nativeAsset, float[] box);
private static native String nGetName(long nativeAsset, int entity);
private static native String nGetExtras(long nativeAsset, int entity);
@@ -31,7 +31,7 @@ import androidx.annotation.Size;
* <p>This class is used by {@link AssetLoader} to create Filament materials.
* Client applications do not need to call methods on it.</p>
*/
public class UbershaderProvider implements MaterialProvider {
public class UbershaderLoader implements MaterialProvider {
private static final VertexBuffer.VertexAttribute[] sVertexAttributesValues =
VertexBuffer.VertexAttribute.values();
@@ -42,16 +42,16 @@ public class UbershaderProvider implements MaterialProvider {
*
* @param engine the engine used to create materials
*/
public UbershaderProvider(Engine engine) {
public UbershaderLoader(Engine engine) {
long nativeEngine = engine.getNativeObject();
mNativeObject = nCreateUbershaderProvider(nativeEngine);
mNativeObject = nCreateUbershaderLoader(nativeEngine);
}
/**
* Frees memory associated with the native material provider.
* */
public void destroy() {
nDestroyUbershaderProvider(mNativeObject);
nDestroyUbershaderLoader(mNativeObject);
mNativeObject = 0;
}
@@ -92,8 +92,8 @@ public class UbershaderProvider implements MaterialProvider {
return mNativeObject;
}
private static native long nCreateUbershaderProvider(long nativeEngine);
private static native void nDestroyUbershaderProvider(long nativeProvider);
private static native long nCreateUbershaderLoader(long nativeEngine);
private static native void nDestroyUbershaderLoader(long nativeProvider);
private static native void nDestroyMaterials(long nativeProvider);
private static native long nCreateMaterialInstance(long nativeProvider,
MaterialKey config, int[] uvmap, String label);
+1 -1
View File
@@ -1,5 +1,5 @@
GROUP=com.google.android.filament
VERSION_NAME=1.24.0
VERSION_NAME=1.21.3
POM_DESCRIPTION=Real-time physically based rendering engine for Android.
+1 -1
View File
@@ -1,6 +1,6 @@
#Wed Nov 17 10:40:18 PST 2021
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
@@ -25,8 +25,6 @@ clean.doFirst {
}
android {
namespace 'com.google.android.filament.gltf'
compileSdkVersion versions.compileSdk
defaultConfig {
applicationId "com.google.android.filament.gltf"
@@ -34,7 +32,6 @@ android {
targetSdkVersion versions.targetSdk
missingDimensionStrategy 'functionality', 'full'
}
// NOTE: This is a workaround required because the AGP task collectReleaseDependencies
// is not configuration-cache friendly yet; this is only useful for Play publication
dependenciesInfo {
@@ -16,8 +16,6 @@ clean.doFirst {
}
android {
namespace 'com.google.android.filament.hellocam'
compileSdkVersion versions.compileSdk
defaultConfig {
applicationId "com.google.android.filament.hellocamera"
@@ -16,8 +16,6 @@ clean.doFirst {
}
android {
namespace 'com.google.android.filament.hellotriangle'
compileSdkVersion versions.compileSdk
defaultConfig {
applicationId "com.google.android.filament.hellotriangle"
@@ -22,8 +22,6 @@ clean.doFirst {
}
android {
namespace 'com.google.android.filament.ibl'
compileSdkVersion versions.compileSdk
defaultConfig {
applicationId "com.google.android.filament.ibl"
@@ -15,8 +15,6 @@ clean.doFirst {
delete "src/main/assets"
}
android {
namespace 'com.google.android.filament.litcube'
compileSdkVersion versions.compileSdk
defaultConfig {
applicationId "com.google.android.filament.litcube"
@@ -4,8 +4,6 @@ apply plugin: 'kotlin-android'
project.ext.isSample = true
android {
namespace 'com.google.android.filament.livewallpaper'
compileSdkVersion versions.compileSdk
defaultConfig {
applicationId "com.google.android.filament.livewallpaper"
@@ -19,8 +19,6 @@ clean.doFirst {
}
android {
namespace 'com.google.android.filament.material_builder'
compileSdkVersion versions.compileSdk
defaultConfig {
applicationId "com.google.android.filament.material_builder"
@@ -15,8 +15,6 @@ clean.doFirst {
delete "src/main/assets"
}
android {
namespace 'com.google.android.filament.multiview'
compileSdkVersion versions.compileSdk
defaultConfig {
applicationId "com.google.android.filament.multiview"
@@ -18,8 +18,6 @@ clean.doFirst {
}
android {
namespace 'com.google.android.filament.pagecurl'
compileSdkVersion versions.compileSdk
defaultConfig {
applicationId "com.google.android.filament.pagecurl"
@@ -16,8 +16,6 @@ clean.doFirst {
}
android {
namespace 'com.google.android.filament.streamtest'
compileSdkVersion versions.compileSdk
defaultConfig {
applicationId "com.google.android.filament.streamtest"
@@ -16,8 +16,6 @@ clean.doFirst {
}
android {
namespace 'com.google.android.filament.textureview'
compileSdkVersion versions.compileSdk
defaultConfig {
applicationId "com.google.android.filament.textureview"
@@ -22,8 +22,6 @@ clean.doFirst {
}
android {
namespace 'com.google.android.filament.textured'
compileSdkVersion versions.compileSdk
defaultConfig {
applicationId "com.google.android.filament.textured"
@@ -16,8 +16,6 @@ clean.doFirst {
}
android {
namespace 'com.google.android.filament.transparentrendering'
compileSdkVersion versions.compileSdk
defaultConfig {
applicationId "com.google.android.filament.textureview"
+4 -1
View File
@@ -2,7 +2,7 @@
set -e
# Host tools required by Android, WebGL, and iOS builds
MOBILE_HOST_TOOLS="matc resgen cmgen filamesh uberz"
MOBILE_HOST_TOOLS="matc resgen cmgen filamesh"
WEB_HOST_TOOLS="${MOBILE_HOST_TOOLS} mipgen filamesh"
function print_help {
@@ -478,12 +478,14 @@ function build_android {
if [[ "${INSTALL_COMMAND}" ]]; then
echo "Installing out/filamat-android-debug.aar..."
cp filamat-android/build/outputs/aar/filamat-android-lite-debug.aar ../out/
cp filamat-android/build/outputs/aar/filamat-android-full-debug.aar ../out/filamat-android-debug.aar
echo "Installing out/filament-android-debug.aar..."
cp filament-android/build/outputs/aar/filament-android-debug.aar ../out/
echo "Installing out/gltfio-android-debug.aar..."
cp gltfio-android/build/outputs/aar/gltfio-android-lite-debug.aar ../out/
cp gltfio-android/build/outputs/aar/gltfio-android-full-debug.aar ../out/gltfio-android-debug.aar
echo "Installing out/filament-utils-android-debug.aar..."
@@ -532,6 +534,7 @@ function build_android {
cp filament-android/build/outputs/aar/filament-android-release.aar ../out/
echo "Installing out/gltfio-android-release.aar..."
cp gltfio-android/build/outputs/aar/gltfio-android-lite-release.aar ../out/
cp gltfio-android/build/outputs/aar/gltfio-android-full-release.aar ../out/gltfio-android-release.aar
echo "Installing out/filament-utils-android-release.aar..."
+1 -2
View File
@@ -49,8 +49,7 @@ FILAMENT_NDK_VERSION=${FILAMENT_NDK_VERSION:-$(cat `dirname $0`/ndk.version)}
# Install the required NDK version specifically (if not present)
if [[ ! -d "${ANDROID_HOME}/ndk/$FILAMENT_NDK_VERSION" ]]; then
# NOTE: We MUST use Java 1.8 to run sdkmanager currently, it fails starting with Java 11
JAVA_HOME=${JAVA_HOME_8_X64} ${ANDROID_HOME}/tools/bin/sdkmanager "ndk;$FILAMENT_NDK_VERSION" > /dev/null
${ANDROID_HOME}/tools/bin/sdkmanager "ndk;$FILAMENT_NDK_VERSION" > /dev/null
fi
# Only build 1 64 bit target during presubmit to cut down build times during presubmit
+1 -1
View File
@@ -1 +1 @@
24.0.8215888
23.1.7779620
+1 -1
View File
@@ -7,7 +7,7 @@ Deprecated==1.2.13
idna==3.3
pycparser==2.21
PyGithub==1.55
PyJWT==2.4.0
PyJWT==2.3.0
PyNaCl==1.5.0
requests==2.27.1
urllib3==1.26.9
+3 -2
View File
@@ -119,8 +119,9 @@ cmake ..\.. ^
:: Some resource libraries require significant heap space to compile, so first compile them serially.
@echo on
cmake --build . --target filagui --config %config% || exit /b
cmake --build . --target uberarchive --config %config% || exit /b
cmake --build . --target gltf-demo-resources --config %config% || exit /b
cmake --build . --target gltfio_resources --config %config% || exit /b
cmake --build . --target gltfio_resources_lite --config %config% || exit /b
cmake --build . --target gltf-resources --config %config% || exit /b
cmake --build . --target filamentapp-resources --config %config% || exit /b
cmake --build . --target sample-resources --config %config% || exit /b
cmake --build . --target suzanne-resources --config %config% || exit /b
+13 -39
View File
@@ -118,7 +118,6 @@ counter-increment: h6;margin-right:10px}
&nbsp;&nbsp;&nbsp;&nbsp;<a href="#materialdefinitions/materialblock/shading:customsurfaceshading" class="level3"><span class="tocNumber">4.2.31&nbsp; </span>Shading: customSurfaceShading</a><br>
&nbsp;&nbsp;<a href="#materialdefinitions/vertexblock" class="level2"><span class="tocNumber">4.3&nbsp; </span>Vertex block</a><br>
&nbsp;&nbsp;&nbsp;&nbsp;<a href="#materialdefinitions/vertexblock/materialvertexinputs" class="level3"><span class="tocNumber">4.3.1&nbsp; </span>Material vertex inputs</a><br>
&nbsp;&nbsp;&nbsp;&nbsp;<a href="#materialdefinitions/vertexblock/customvertexattributes" class="level3"><span class="tocNumber">4.3.2&nbsp; </span>Custom vertex attributes</a><br>
&nbsp;&nbsp;<a href="#materialdefinitions/fragmentblock" class="level2"><span class="tocNumber">4.4&nbsp; </span>Fragment block</a><br>
&nbsp;&nbsp;&nbsp;&nbsp;<a href="#materialdefinitions/fragmentblock/preparematerialfunction" class="level3"><span class="tocNumber">4.4.1&nbsp; </span>prepareMaterial function</a><br>
&nbsp;&nbsp;&nbsp;&nbsp;<a href="#materialdefinitions/fragmentblock/materialfragmentinputs" class="level3"><span class="tocNumber">4.4.2&nbsp; </span>Material fragment inputs</a><br>
@@ -1537,7 +1536,7 @@ non-shader data.
</p><dl><dt>Type</dt><dd><p> array of <code>string</code>
</p></dd><dt>Value</dt><dd><p> Each entry must be any of <code>dynamicLighting</code>, <code>directionalLighting</code>, <code>shadowReceiver</code>,<code>skinning</code> or <code>ssr</code>.
</p></dd><dt>Value</dt><dd><p> Each entry must be any of <code>dynamicLighting</code>, <code>directionalLighting</code>, <code>shadowReceiver</code> or <code>skinning</code>.
</p></dd><dt>Description</dt><dd><p> Used to specify a list of shader variants that the application guarantees will never be
needed. These shader variants are skipped during the code generation phase, thus reducing
@@ -1562,9 +1561,7 @@ non-shader data.
</li>
<li class="minus"><code>fog</code>, used when global fog is applied to the scene
</li>
<li class="minus"><code>vsm</code>, used when VSM shadows are enabled and the object is a shadow receiver
</li>
<li class="minus"><code>ssr</code>, used when screen-space reflections are enabled in the View</li></ul>
<li class="minus"><code>vsm</code>, used when VSM shadows are enabled and the object is a shadow receiver</li></ul>
<p></p><pre class="listing tilde"><code><span class="line">material {</span>
<span class="line"> name : <span class="hljs-string">"Invisible shadow plane"</span>,</span>
@@ -1610,8 +1607,7 @@ non-shader data.
</p><dl><dt>Type</dt><dd><p> array of <code>string</code>
</p></dd><dt>Value</dt><dd><p> Each entry must be any of <code>uv0</code>, <code>uv1</code>, <code>color</code>, <code>position</code>, <code>tangents</code>, <code>custom0</code>
through <code>custom7</code>.
</p></dd><dt>Value</dt><dd><p> Each entry must be any of <code>uv0</code>, <code>uv1</code>, <code>color</code>, <code>position</code>, <code>tangents</code>.
</p></dd><dt>Description</dt><dd><p> Lists the vertex attributes required by the material. The <code>position</code> attribute is always
required and does not need to be specified. The <code>tangents</code> attribute is automatically required
@@ -1626,8 +1622,7 @@ non-shader data.
<span class="line"> },</span>
<span class="line"> ],</span>
<span class="line"> requires : [</span>
<span class="line"> uv0,</span>
<span class="line"> custom0</span>
<span class="line"> uv0</span>
<span class="line"> ],</span>
<span class="line"> shadingModel : lit,</span>
<span class="line">}</span>
@@ -1636,7 +1631,6 @@ non-shader data.
<span class="line"> void material(inout MaterialInputs material) {</span>
<span class="line"> prepareMaterial(material);</span>
<span class="line"> material.baseColor = texture(materialParams_texture, getUV0());</span>
<span class="line"> material.baseColor.rgb *= getCustom0().rgb;</span>
<span class="line"> }</span>
<span class="line">}</span></code></pre>
<a class="target" name="vertexandattributes:variables">&nbsp;</a><a class="target" name="materialdefinitions/materialblock/vertexandattributes:variables">&nbsp;</a><a class="target" name="toc4.2.8">&nbsp;</a><h3>Vertex and attributes: variables</h3>
@@ -1765,9 +1759,8 @@ non-shader data.
render target is brightened.
</li>
<li class="minus"><strong class="asterisk">Masked</strong>: blending is disabled. This blending mode enables alpha masking. The alpha channel
of the material's output defines whether a fragment is discarded or not. Additionally,
ALPHA_TO_COVERAGE is enabled for non-translucent views. See the maskThreshold section for more
information.</li></ul>
of the material's output defines whether a fragment is discarded or not. See the maskThreshold
section for more information.</li></ul>
<p></p></dd></dl><p></p><pre class="listing tilde"><code><span class="line">material {</span>
<span class="line"> blending : transparent</span>
@@ -1858,9 +1851,8 @@ and sorting issues are minimized or eliminated</span></center></div></center>
</p></dd><dt>Value</dt><dd><p> A value between <code>0.0</code> and <code>1.0</code>. Defaults to <code>0.4</code>.
</p></dd><dt>Description</dt><dd><p> Sets the minimum alpha value a fragment must have to not be discarded when the <code>blending</code> mode
is set to <code>masked</code>. If the fragment is not discarded, its source alpha is set to 1. When the
blending mode is not <code>masked</code>, this value is ignored. This value can be used to controlled the
appearance of alpha-masked objects.
is set to <code>masked</code>. When the blending mode is not <code>masked</code>, this value is ignored. This value
can be used to controlled the appearance of alpha-masked objects.
</p></dd></dl><p></p><pre class="listing tilde"><code><span class="line">material {</span>
<span class="line"> blending : masked,</span>
@@ -2282,31 +2274,15 @@ APIs listed in the <a href="#shaderpublicapis">Shader public APIs</a> section.
this behavior using the <code>flipUV</code> property and setting it to <code>false</code>.</p></div>
<p></p>
<a class="target" name="customvertexattributes">&nbsp;</a><a class="target" name="materialdefinitions/vertexblock/customvertexattributes">&nbsp;</a><a class="target" name="toc4.3.2">&nbsp;</a><h3>Custom vertex attributes</h3>
<p>
You can use up to 8 custom vertex attributes, all of type <code>float4</code>. These attributes can be accessed
using the vertex block shader functions <code>getCustom0()</code> to <code>getCustom7()</code>. However, before using
custom attributes, you <em class="asterisk">must</em> declare those attributes as required in the <code>requires</code> property of
the material:
</p><pre class="listing tilde"><code><span class="line">material {</span>
<span class="line"> requires : [</span>
<span class="line"> custom0,</span>
<span class="line"> custom1,</span>
<span class="line"> custom2</span>
<span class="line"> ]</span>
<span class="line">}</span></code></pre>
<a class="target" name="fragmentblock">&nbsp;</a><a class="target" name="materialdefinitions/fragmentblock">&nbsp;</a><a class="target" name="toc4.4">&nbsp;</a><h2>Fragment block</h2>
<p>
The fragment block must be used to control the fragment shading stage of the material. The fragment
The fragment block must be used to control the fragment shading stage of the material. The vertex
block must contain valid
<a href="https://www.khronos.org/registry/OpenGL/specs/es/3.0/GLSL_ES_Specification_3.00.pdf">ESSL 3.0</a>
code (the version of GLSL supported in OpenGL ES 3.0). You are free to create multiple functions
inside the fragment block but you <strong class="asterisk">must</strong> declare the <code>material</code> function:
inside the vertex block but you <strong class="asterisk">must</strong> declare the <code>material</code> function:
</p><pre class="listing tilde"><code><span class="line">fragment {</span>
<span class="line"> <span class="hljs-type">void</span> material(<span class="hljs-keyword">inout</span> MaterialInputs material) {</span>
@@ -2340,7 +2316,7 @@ standard lit shading model:
Note that you <strong class="asterisk">must</strong> call <code>prepareMaterial(material)</code> before exiting the <code>material()</code> function.
This <code>prepareMaterial</code> function sets up the internal state of the material model. Some of the APIs
This <code>prepareMaterial</code> function sets up the internal state of the material mdoel. Some of the APIs
described in the Fragment APIs section - like <code>shading_normal</code> for instance - can only be accessed
<em class="underscore">after</em> invoking <code>prepareMaterial()</code>.
@@ -2640,7 +2616,7 @@ type aliases:
<p>
</p><div class="table"><table class="table"><tbody><tr><th style="text-align:left"> Name </th><th style="text-align:center"> Type </th><th style="text-align:left"> Description </th></tr>
<tr><td style="text-align:left"> <strong class="asterisk">getResolution()</strong> </td><td style="text-align:center"> float4 </td><td style="text-align:left"> Dimensions of the view's effective viewport in pixels: <code>width</code>, <code>height</code>, <code>1 / width</code>, <code>1 / height</code>. This might be different from <code>View::getViewport()</code> for instance because of added rendering guard-bands. This can be used in conjunction with <code>getNormalizedViewportCoord()</code> to generate pixel coordinates. </td></tr>
<tr><td style="text-align:left"> <strong class="asterisk">getResolution()</strong> </td><td style="text-align:center"> float4 </td><td style="text-align:left"> Resolution of the view in pixels: <code>width</code>, <code>height</code>, <code>1 / width</code>, <code>1 / height</code> </td></tr>
<tr><td style="text-align:left"> <strong class="asterisk">getWorldCameraPosition()</strong> </td><td style="text-align:center"> float3 </td><td style="text-align:left"> Position of the camera/eye in world space </td></tr>
<tr><td style="text-align:left"> <strong class="asterisk">getWorldOffset()</strong> </td><td style="text-align:center"> float3 </td><td style="text-align:left"> The shift required to obtain API-level world space </td></tr>
<tr><td style="text-align:left"> <strong class="asterisk">getTime()</strong> </td><td style="text-align:center"> float </td><td style="text-align:left"> Current time as a remainder of 1 second. Yields a value between 0 and 1 </td></tr>
@@ -2845,9 +2821,7 @@ variants:
</li>
<li class="minus"><code>fog</code>, used when global fog is applied to the scene
</li>
<li class="minus"><code>vsm</code>, used when VSM shadows are enabled and the object is a shadow receiver
</li>
<li class="minus"><code>ssr</code>, used when screen-space reflections are enabled in the View</li></ul>
<li class="minus"><code>vsm</code>, used when VSM shadows are enabled and the object is a shadow receiver</li></ul>
<p></p><p>
+5 -46
View File
@@ -1119,35 +1119,13 @@ material {
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
### General: instanced
Type
: `boolean`
Value
: `true` or `false`. Defaults to `false`.
Description
: Allows a material to access the instance index (i.e.: **`gl_InstanceIndex`**) of instanced
primitives using `getInstanceIndex()` in the material's shader code. Never use
**`gl_InstanceIndex`** directly. This is typically used with
`RenderableManager::Builder::instances()`. `getInstanceIndex()` is available in both the
vertex and fragment shader.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ JSON
material {
instanced : true
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
### Vertex and attributes: requires
Type
: array of `string`
Value
: Each entry must be any of `uv0`, `uv1`, `color`, `position`, `tangents`, `custom0`
through `custom7`.
: Each entry must be any of `uv0`, `uv1`, `color`, `position`, `tangents`.
Description
: Lists the vertex attributes required by the material. The `position` attribute is always
@@ -1164,8 +1142,7 @@ material {
},
],
requires : [
uv0,
custom0
uv0
],
shadingModel : lit,
}
@@ -1174,7 +1151,6 @@ fragment {
void material(inout MaterialInputs material) {
prepareMaterial(material);
material.baseColor = texture(materialParams_texture, getUV0());
material.baseColor.rgb *= getCustom0().rgb;
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -1865,30 +1841,13 @@ struct MaterialVertexInputs {
of the current mesh: `material.uv0 = vec2(mesh_uv0.x, 1.0 - mesh_uv0.y)`. You can control
this behavior using the `flipUV` property and setting it to `false`.
### Custom vertex attributes
You can use up to 8 custom vertex attributes, all of type `float4`. These attributes can be accessed
using the vertex block shader functions `getCustom0()` to `getCustom7()`. However, before using
custom attributes, you *must* declare those attributes as required in the `requires` property of
the material:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ JSON
material {
requires : [
custom0,
custom1,
custom2
]
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
## Fragment block
The fragment block must be used to control the fragment shading stage of the material. The fragment
The fragment block must be used to control the fragment shading stage of the material. The vertex
block must contain valid
[ESSL 3.0](https://www.khronos.org/registry/OpenGL/specs/es/3.0/GLSL_ES_Specification_3.00.pdf)
code (the version of GLSL supported in OpenGL ES 3.0). You are free to create multiple functions
inside the fragment block but you **must** declare the `material` function:
inside the vertex block but you **must** declare the `material` function:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GLSL
fragment {
@@ -1923,7 +1882,7 @@ fragment {
### prepareMaterial function
Note that you **must** call `prepareMaterial(material)` before exiting the `material()` function.
This `prepareMaterial` function sets up the internal state of the material model. Some of the APIs
This `prepareMaterial` function sets up the internal state of the material mdoel. Some of the APIs
described in the Fragment APIs section - like `shading_normal` for instance - can only be accessed
_after_ invoking `prepareMaterial()`.
+19 -43
View File
@@ -15,17 +15,22 @@
*/
// If you are bundling this with rollup, webpack, or esbuild, the following URL should be trimmed.
import { LitElement, html, css } from "https://unpkg.com/lit?module";
import { LitElement, html, css } from "https://unpkg.com/lit-element?module";
// This little utility checks if the Filament module is ready for action.
// If so, it immediately calls the given function. If not, it asks the Filament
// loader to call it as soon as the module becomes ready.
// To allow the DOM to render before the Filament WASM module is ready, we maintain a little
// queue of tasks that get invoked as soon as the module is done loading.
class FilamentTasks {
constructor() {
this.tasks = []
if (!Filament.Engine) {
Filament.init([], () => { for (const task of this.tasks) task(); });
}
}
add(callback) {
if (Filament.isReady) {
callback();
if (!Filament.Engine) {
this.tasks.push(callback);
} else {
Filament.init([], callback);
callback();
}
}
}
@@ -63,7 +68,6 @@ class FilamentViewer extends LitElement {
this.sky = null; // Path to skybox ktx.
this.enableDrop = null; // Enables drag and drop.
this.intensity = 30000; // Intensity of the image based light.
this.materialVariant = 0; // Index of material variant.
// Private properties:
this.filamentTasks = new FilamentTasks();
@@ -80,7 +84,6 @@ class FilamentViewer extends LitElement {
sky: { type: String },
enableDrop: { type: Boolean },
intensity: { type: Number },
materialVariant: { type: Number },
}
}
@@ -113,7 +116,6 @@ class FilamentViewer extends LitElement {
if (props.has("intensity") && this.indirectLight) {
this.indirectLight.setIntensity(this.intensity);
}
if (props.has("materialVariant") && this.asset) this._applyMaterialVariant();
}
static get styles() {
@@ -246,7 +248,7 @@ class FilamentViewer extends LitElement {
return response.arrayBuffer();
}).then(arrayBuffer => {
const ktxData = new Uint8Array(arrayBuffer);
this.indirectLight = this.engine.createIblFromKtx1(ktxData);
this.indirectLight = this.engine.createIblFromKtx(ktxData);
this.indirectLight.setIntensity(this.intensity);
this.scene.setIndirectLight(this.indirectLight);
});
@@ -264,7 +266,7 @@ class FilamentViewer extends LitElement {
return response.arrayBuffer();
}).then(arrayBuffer => {
const ktxData = new Uint8Array(arrayBuffer);
this.skybox = this.engine.createSkyFromKtx1(ktxData);
this.skybox = this.engine.createSkyFromKtx(ktxData);
this.scene.setSkybox(this.skybox);
});
}
@@ -309,7 +311,7 @@ class FilamentViewer extends LitElement {
asyncInterval: 30
};
const doneAddingResources = (resourceLoader, stbProvider, ktx2Provider) => {
const doneAddingResources = resourceLoader => {
this.srcBlobResources = {};
resourceLoader.asyncBeginLoad(this.asset);
const timer = setInterval(() => {
@@ -318,8 +320,6 @@ class FilamentViewer extends LitElement {
if (progress >= 1) {
clearInterval(timer);
resourceLoader.delete();
stbProvider.delete();
ktx2Provider.delete();
this.animator = this.asset.getAnimator();
this.animationStartTime = Date.now();
}
@@ -337,20 +337,13 @@ class FilamentViewer extends LitElement {
config.recomputeBoundingBoxes,
config.ignoreBindTransform);
const stbProvider = new Filament.gltfio$StbProvider(this.engine);
const ktx2Provider = new Filament.gltfio$Ktx2Provider(this.engine);
resourceLoader.addStbProvider("image/jpeg", stbProvider);
resourceLoader.addStbProvider("image/png", stbProvider);
resourceLoader.addKtx2Provider("image/ktx2", ktx2Provider);
let remaining = Object.keys(this.srcBlobResources).length;
for (const name in this.srcBlobResources) {
this.srcBlobResources[name].arrayBuffer().then(buffer => {
const desc = getBufferDescriptor(new Uint8Array(buffer));
resourceLoader.addResourceData(name, getBufferDescriptor(desc));
if (--remaining === 0) {
doneAddingResources(resourceLoader, stbProvider, ktx2Provider);
doneAddingResources(resourceLoader);
}
});
}
@@ -382,7 +375,6 @@ class FilamentViewer extends LitElement {
this.asset.loadResources(() => {
this.animator = this.asset.getAnimator();
this.animationStartTime = Date.now();
this._applyMaterialVariant();
}, null, basePath);
this._updateOverlay();
@@ -391,11 +383,9 @@ class FilamentViewer extends LitElement {
_updateAsset() {
// Invoke the first glTF animation if it exists.
if (this.animator) {
if (this.animator.getAnimationCount() > 0) {
const ms = Date.now() - this.animationStartTime;
this.animator.applyAnimation(0, ms / 1000);
}
if (this.animator && this.animator.getAnimationCount() > 0) {
const ms = Date.now() - this.animationStartTime;
this.animator.applyAnimation(0, ms / 1000);
this.animator.updateBoneMatrices();
}
@@ -436,20 +426,6 @@ class FilamentViewer extends LitElement {
window.requestAnimationFrame(this._renderFrame.bind(this));
}
_applyMaterialVariant() {
if (!this.hasAttribute("materialVariant")) {
return;
}
const names = this.asset.getMaterialVariantNames();
const index = this.materialVariant;
if (index < 0 || index >= names.length) {
console.error(`Material variant ${index} does not exist in this asset.`);
return;
}
console.info(this.src, `Applying material variant: ${names[index]}`);
this.asset.applyMaterialVariant(index);
}
}
customElements.define("filament-viewer", FilamentViewer);
+1 -1
View File
@@ -43,7 +43,7 @@ filament-viewer::part(canvas) {
</p>
</main>
<script src="https://unpkg.com/filament@1.22.0/filament.js"></script>
<script src="https://unpkg.com/filament/filament.js"></script>
<script src="https://unpkg.com/gltumble"></script>
<script src="filament-viewer.js" type="module"></script>
</body>
-31
View File
@@ -63,7 +63,6 @@ set(SRCS
src/FrameSkipper.cpp
src/Froxelizer.cpp
src/Frustum.cpp
src/HwRenderPrimitiveFactory.cpp
src/IndexBuffer.cpp
src/IndirectLight.cpp
src/LightManager.cpp
@@ -132,7 +131,6 @@ set(SRCS
set(PRIVATE_HDRS
src/Allocators.h
src/BufferPoolAllocator.h
src/ColorSpace.h
src/Culler.h
src/DFG.h
@@ -141,7 +139,6 @@ set(PRIVATE_HDRS
src/FrameInfo.h
src/FrameSkipper.h
src/Froxelizer.h
src/HwRenderPrimitiveFactory.h
src/Intersections.h
src/MaterialParser.h
src/PerViewUniforms.h
@@ -459,34 +456,6 @@ add_custom_command(
APPEND
)
add_custom_command(
OUTPUT "${MATERIAL_DIR}/separableGaussianBlur1L.filamat"
DEPENDS src/materials/separableGaussianBlur.vs
DEPENDS src/materials/separableGaussianBlur.fs
APPEND
)
add_custom_command(
OUTPUT "${MATERIAL_DIR}/separableGaussianBlur2L.filamat"
DEPENDS src/materials/separableGaussianBlur.vs
DEPENDS src/materials/separableGaussianBlur.fs
APPEND
)
add_custom_command(
OUTPUT "${MATERIAL_DIR}/separableGaussianBlur3L.filamat"
DEPENDS src/materials/separableGaussianBlur.vs
DEPENDS src/materials/separableGaussianBlur.fs
APPEND
)
add_custom_command(
OUTPUT "${MATERIAL_DIR}/separableGaussianBlur4L.filamat"
DEPENDS src/materials/separableGaussianBlur.vs
DEPENDS src/materials/separableGaussianBlur.fs
APPEND
)
add_custom_command(
OUTPUT ${RESGEN_OUTPUTS}
COMMAND resgen ${RESGEN_FLAGS} ${MATERIAL_BINS}
-3
View File
@@ -49,9 +49,6 @@ To use the Vulkan backend on macOS you must also make the following libraries av
- `libMoltenVK.dylib`
- `libvulkan.1.dylib`
The easiest way to install those files is to use the macOS
[LunarG Vulkan SDK](https://www.lunarg.com/vulkan-sdk/) installer.
## Linking against Filament
This walkthrough will get you successfully compiling and linking native code
+13 -1
View File
@@ -389,7 +389,6 @@ if (APPLE)
test/test_MRT.cpp
test/test_LoadImage.cpp
test/test_RenderExternalImage.cpp
test/test_StencilBuffer.cpp
)
target_link_libraries(backend_test PRIVATE
@@ -438,3 +437,16 @@ if (APPLE AND NOT IOS)
target_link_libraries(backend_test_mac PRIVATE -force_load backend_test)
endif()
if (APPLE AND NOT Vulkan_LIBRARY AND NOT FILAMENT_USE_SWIFTSHADER)
message(STATUS "No Vulkan SDK was found, using prebuilt MoltenVK.")
set(MOLTENVK_DIR "../../third_party/moltenvk")
configure_file(
${MOLTENVK_DIR}/libvulkan.1.dylib
${PROJECT_BINARY_DIR}/libvulkan.1.dylib COPYONLY)
configure_file(
${MOLTENVK_DIR}/MoltenVK_icd.json
${PROJECT_BINARY_DIR}/MoltenVK_icd.json COPYONLY)
configure_file(
${MOLTENVK_DIR}/libMoltenVK.dylib
${PROJECT_BINARY_DIR}/libMoltenVK.dylib COPYONLY)
endif()
+20 -53
View File
@@ -128,6 +128,7 @@ inline constexpr TargetBufferFlags getTargetBufferFlagsAt(size_t index) noexcept
enum class BufferUsage : uint8_t {
STATIC, //!< content modified once, used many times
DYNAMIC, //!< content modified frequently, used many times
STREAM, //!< content invalidated and modified frequently, used many times
};
/**
@@ -718,7 +719,7 @@ enum class SamplerCompareMode : uint8_t {
COMPARE_TO_TEXTURE = 1
};
//! comparison function for the depth / stencil sampler
//! comparison function for the depth sampler
enum class SamplerCompareFunc : uint8_t {
// don't change the enums values
LE = 0, //!< Less or equal
@@ -727,11 +728,11 @@ enum class SamplerCompareFunc : uint8_t {
G, //!< Strictly greater than
E, //!< Equal
NE, //!< Not equal
A, //!< Always. Depth / stencil testing is deactivated.
N //!< Never. The depth / stencil test always fails.
A, //!< Always. Depth testing is deactivated.
N //!< Never. The depth test always fails.
};
//! Sampler parameters
//! Sampler paramters
struct SamplerParams { // NOLINT
union {
struct {
@@ -784,18 +785,6 @@ enum class BlendFunction : uint8_t {
SRC_ALPHA_SATURATE //!< f(src, dst) = (1,1,1) * min(src.a, 1 - dst.a), 1
};
//! stencil operation
enum class StencilOperation : uint8_t {
KEEP, //!< Keeps the current value.
ZERO, //!< Sets the value to 0.
REPLACE, //!< Sets the value to the stencil reference value.
INCR, //!< Increments the current value. Clamps to the maximum representable unsigned value.
INCR_WRAP, //!< Increments the current value. Wraps value to zero when incrementing the maximum representable unsigned value.
DECR, //!< Decrements the current value. Clamps to 0.
DECR_WRAP, //!< Decrements the current value. Wraps value to the maximum representable unsigned value when decrementing a value of zero.
INVERT, //!< Bitwise inverts the current value.
};
//! Stream for external textures
enum class StreamType {
NATIVE, //!< Not synchronized but copy-free. Good for video.
@@ -828,11 +817,9 @@ struct RasterState {
using DepthFunc = backend::SamplerCompareFunc;
using BlendEquation = backend::BlendEquation;
using BlendFunction = backend::BlendFunction;
using StencilFunction = backend::SamplerCompareFunc;
using StencilOperation = backend::StencilOperation;
RasterState() noexcept { // NOLINT
static_assert(sizeof(RasterState) == sizeof(uint64_t),
static_assert(sizeof(RasterState) == sizeof(uint32_t),
"RasterState size not what was intended");
culling = CullingMode::BACK;
blendEquationRGB = BlendEquation::ADD;
@@ -841,10 +828,6 @@ struct RasterState {
blendFunctionSrcAlpha = BlendFunction::ONE;
blendFunctionDstRGB = BlendFunction::ZERO;
blendFunctionDstAlpha = BlendFunction::ZERO;
stencilFunc = StencilFunction::A;
stencilOpStencilFail = StencilOperation::KEEP;
stencilOpDepthFail = StencilOperation::KEEP;
stencilOpDepthStencilPass = StencilOperation::KEEP;
}
bool operator == (RasterState rhs) const noexcept { return u == rhs.u; }
@@ -873,56 +856,40 @@ struct RasterState {
union {
struct {
//! culling mode
CullingMode culling : 2; // 2
CullingMode culling : 2; // 2
//! blend equation for the red, green and blue components
BlendEquation blendEquationRGB : 3; // 5
BlendEquation blendEquationRGB : 3; // 5
//! blend equation for the alpha component
BlendEquation blendEquationAlpha : 3; // 8
BlendEquation blendEquationAlpha : 3; // 8
//! blending function for the source color
BlendFunction blendFunctionSrcRGB : 4; // 12
BlendFunction blendFunctionSrcRGB : 4; // 12
//! blending function for the source alpha
BlendFunction blendFunctionSrcAlpha : 4; // 16
BlendFunction blendFunctionSrcAlpha : 4; // 16
//! blending function for the destination color
BlendFunction blendFunctionDstRGB : 4; // 20
BlendFunction blendFunctionDstRGB : 4; // 20
//! blending function for the destination alpha
BlendFunction blendFunctionDstAlpha : 4; // 24
BlendFunction blendFunctionDstAlpha : 4; // 24
//! Whether depth-buffer writes are enabled
bool depthWrite : 1; // 25
bool depthWrite : 1; // 25
//! Depth test function
DepthFunc depthFunc : 3; // 28
DepthFunc depthFunc : 3; // 28
//! Whether color-buffer writes are enabled
bool colorWrite : 1; // 29
bool colorWrite : 1; // 29
//! use alpha-channel as coverage mask for anti-aliasing
bool alphaToCoverage : 1; // 30
bool alphaToCoverage : 1; // 30
//! whether front face winding direction must be inverted
bool inverseFrontFaces : 1; // 31
bool inverseFrontFaces : 1; // 31
//! Whether stencil-buffer writes are enabled
bool stencilWrite : 1; // 32
//! Stencil reference value
uint8_t stencilRef : 8; // 40
//! Stencil test function
StencilFunction stencilFunc : 3; // 43
//! Stencil operation when stencil test fails
StencilOperation stencilOpStencilFail : 3; // 46
//! padding, must be 0
uint8_t padding0 : 2; // 48
//! Stencil operation when stencil test passes but depth test fails
StencilOperation stencilOpDepthFail : 3; // 51
//! Stencil operation when both stencil and depth test pass
StencilOperation stencilOpDepthStencilPass : 3; // 54
//! padding, must be 0
uint8_t padding1 : 2; // 56
//! padding, must be 0
uint8_t padding2 : 8; // 64
uint8_t padding : 1; // 32
};
uint64_t u = 0;
uint32_t u = 0;
};
};
@@ -26,7 +26,6 @@
#include <stdint.h>
#include <limits>
#include <type_traits>
namespace filament::backend {
@@ -34,7 +34,6 @@
#include <utils/compiler.h>
#include <utils/ThreadUtils.h>
#include <cstddef>
#include <functional>
#include <tuple>
#include <thread>
@@ -26,8 +26,6 @@
#include <utils/compiler.h>
#include <functional>
#include <stdint.h>
// Command debugging off. debugging virtuals are not called.
@@ -217,14 +217,7 @@ DECL_DRIVER_API_R_N(backend::TextureHandle, importTexture,
DECL_DRIVER_API_R_N(backend::SamplerGroupHandle, createSamplerGroup,
uint32_t, size)
DECL_DRIVER_API_R_N(backend::RenderPrimitiveHandle, createRenderPrimitive,
backend::VertexBufferHandle, vbh,
backend::IndexBufferHandle, ibh,
backend::PrimitiveType, pt,
uint32_t, offset,
uint32_t, minIndex,
uint32_t, maxIndex,
uint32_t, count)
DECL_DRIVER_API_R_0(backend::RenderPrimitiveHandle, createRenderPrimitive)
DECL_DRIVER_API_R_N(backend::ProgramHandle, createProgram,
backend::Program&&, program)
@@ -325,14 +318,6 @@ DECL_DRIVER_API_N(updateBufferObject,
backend::BufferDescriptor&&, data,
uint32_t, byteOffset)
DECL_DRIVER_API_N(updateBufferObjectUnsynchronized,
backend::BufferObjectHandle, ibh,
backend::BufferDescriptor&&, data,
uint32_t, byteOffset)
DECL_DRIVER_API_N(resetBufferObject,
backend::BufferObjectHandle, ibh)
DECL_DRIVER_API_N(updateSamplerGroup,
backend::SamplerGroupHandle, ubh,
backend::SamplerGroup&&, samplerGroup)
@@ -392,6 +377,19 @@ DECL_DRIVER_API_0(endRenderPass)
DECL_DRIVER_API_0(nextSubpass)
DECL_DRIVER_API_N(setRenderPrimitiveBuffer,
backend::RenderPrimitiveHandle, rph,
backend::VertexBufferHandle, vbh,
backend::IndexBufferHandle, ibh)
DECL_DRIVER_API_N(setRenderPrimitiveRange,
backend::RenderPrimitiveHandle, rph,
backend::PrimitiveType, pt,
uint32_t, offset,
uint32_t, minIndex,
uint32_t, maxIndex,
uint32_t, count)
DECL_DRIVER_API_N(beginTimerQuery,
backend::TimerQueryHandle, query)
@@ -67,8 +67,6 @@ public:
utils::Invocable<utils::io::ostream&(utils::io::ostream& out)>&& logger);
// sets one of the program's shader (e.g. vertex, fragment)
// string-based shaders are null terminated, consequently the size parameter must include the
// null terminating character.
Program& shader(Shader shader, void const* data, size_t size) noexcept;
// sets the 'bindingPoint' uniform block's name for this program.
@@ -86,14 +84,10 @@ public:
Program& setSamplerGroup(size_t bindingPoint, ShaderStageFlags stageFlags,
Sampler const* samplers, size_t count) noexcept;
// string-based shaders are null terminated, consequently the size parameter must include the
// null terminating character.
Program& withVertexShader(void const* data, size_t size) {
return shader(Shader::VERTEX, data, size);
}
// string-based shaders are null terminated, consequently the size parameter must include the
// null terminating character.
Program& withFragmentShader(void const* data, size_t size) {
return shader(Shader::FRAGMENT, data, size);
}
@@ -17,18 +17,17 @@
#ifndef TNT_FILAMENT_BACKEND_PRIVATE_SAMPLERGROUP_H
#define TNT_FILAMENT_BACKEND_PRIVATE_SAMPLERGROUP_H
#include <array>
#include <stddef.h>
#include <utils/compiler.h>
#include <utils/bitset.h>
#include <backend/DriverEnums.h>
#include <backend/Handle.h>
#include <array>
#include <memory>
#include <stddef.h>
namespace filament::backend {
namespace filament {
namespace backend {
class SamplerGroup {
public:
@@ -152,6 +151,7 @@ private:
mutable utils::bitset32 mDirty;
};
} // namespace filament::backend
} // namespace backend
} // namespace filament
#endif // TNT_FILAMENT_BACKEND_PRIVATE_SAMPLERGROUP_H
+22 -12
View File
@@ -58,16 +58,26 @@ public:
}
}
// Converts a n-channel image of UBYTE, INT, UINT, or FLOAT to a different type.
// Converts a 4-channel image of UBYTE, INT, UINT, or FLOAT to a different type.
template<typename dstComponentType, typename srcComponentType>
static void reshapeImage(uint8_t* dest, const uint8_t* src, size_t srcBytesPerRow,
size_t srcChannelCount, size_t dstBytesPerRow, size_t dstChannelCount,
size_t width, size_t height, bool swizzle) {
size_t dstBytesPerRow, size_t dstChannelCount, size_t height, bool swizzle, bool flip) {
const size_t srcChannelCount = 4;
const dstComponentType dstMaxValue = getMaxValue<dstComponentType>();
const srcComponentType srcMaxValue = getMaxValue<srcComponentType>();
const size_t width = (srcBytesPerRow / sizeof(srcComponentType)) / srcChannelCount;
const size_t minChannelCount = filament::math::min(srcChannelCount, dstChannelCount);
assert_invariant(minChannelCount <= 4);
const int inds[4] = {swizzle ? 2 : 0, 1, swizzle ? 0 : 2, 3};
int srcStride;
if (flip) {
src += srcBytesPerRow * (height - 1);
srcStride = -srcBytesPerRow;
} else {
srcStride = srcBytesPerRow;
}
for (size_t row = 0; row < height; ++row) {
const srcComponentType* in = (const srcComponentType*) src;
dstComponentType* out = (dstComponentType*) dest;
@@ -87,15 +97,15 @@ public:
in += srcChannelCount;
out += dstChannelCount;
}
src += srcBytesPerRow;
src += srcStride;
dest += dstBytesPerRow;
}
}
// Converts a n-channel image of UBYTE, INT, UINT, or FLOAT to a different type.
// Converts a 4-channel image of UBYTE, INT, UINT, or FLOAT to a different type.
static bool reshapeImage(PixelBufferDescriptor* dst, PixelDataType srcType,
uint32_t srcChannelCount, const uint8_t* srcBytes, int srcBytesPerRow, int width,
int height, bool swizzle) {
const uint8_t* srcBytes, int srcBytesPerRow, int width, int height, bool swizzle,
bool flip) {
size_t dstChannelCount;
switch (dst->format) {
case PixelDataFormat::R_INTEGER: dstChannelCount = 1; break;
@@ -108,9 +118,8 @@ public:
case PixelDataFormat::RGBA: dstChannelCount = 4; break;
default: return false;
}
void (*reshaper)(uint8_t* dest, const uint8_t* src, size_t srcBytesPerRow,
size_t srcChannelCount, size_t dstBytesPerRow, size_t dstChannelCount,
size_t width, size_t height, bool swizzle) = nullptr;
void (*reshaper)(uint8_t*, const uint8_t*, size_t, size_t, size_t, size_t, bool, bool)
= nullptr;
constexpr auto UBYTE = PixelDataType::UBYTE, FLOAT = PixelDataType::FLOAT,
UINT = PixelDataType::UINT, INT = PixelDataType::INT;
switch (dst->type) {
@@ -156,10 +165,11 @@ public:
uint8_t* dstBytes = (uint8_t*) dst->buffer;
const int dstBytesPerRow = PixelBufferDescriptor::computeDataSize(dst->format, dst->type,
dst->stride ? dst->stride : width, 1, dst->alignment);
reshaper(dstBytes, srcBytes, srcBytesPerRow, srcChannelCount, dstBytesPerRow,
dstChannelCount, width, height, swizzle);
reshaper(dstBytes, srcBytes, srcBytesPerRow, dstBytesPerRow, dstChannelCount, height,
swizzle, flip);
return true;
}
};
template<> inline float getMaxValue() { return 1.0f; }
+11 -2
View File
@@ -42,8 +42,7 @@ public:
* Update the buffer with data inside src. Potentially allocates a new buffer allocation to hold
* the bytes which will be released when the current frame is finished.
*/
void copyIntoBuffer(void* src, size_t size, size_t byteOffset);
void copyIntoBufferUnsynchronized(void* src, size_t size, size_t byteOffset);
void copyIntoBuffer(void* src, size_t size, size_t byteOffset = 0);
/**
* Denotes that this buffer is used for a draw call ensuring that its allocation remains valid
@@ -58,6 +57,12 @@ public:
*/
id<MTLBuffer> getGpuBufferForDraw(id<MTLCommandBuffer> cmdBuffer) noexcept;
/**
* Returns the offset into the buffer returned by getGpuBufferForDraw. This is always 0 for
* non-STREAM buffers.
*/
size_t getGpuBufferStreamOffset() noexcept { return mCurrentStreamStart; }
void* getCpuBuffer() const noexcept { return mCpuBuffer; }
enum Stage {
@@ -79,9 +84,13 @@ private:
BufferUsage mUsage;
size_t mBufferSize = 0;
size_t mCurrentStreamStart = 0;
size_t mCurrentStreamEnd = 0;
const MetalBufferPoolEntry* mBufferPoolEntry = nullptr;
void* mCpuBuffer = nullptr;
MetalContext& mContext;
void copyIntoStreamBuffer(void* src, size_t size);
};
} // namespace backend
+39 -4
View File
@@ -28,6 +28,11 @@ MetalBuffer::MetalBuffer(MetalContext& context, BufferUsage usage, size_t size,
// If the buffer is less than 4K in size and is updated frequently, we don't use an explicit
// buffer. Instead, we use immediate command encoder methods like setVertexBytes:length:atIndex:.
if (size <= 4 * 1024) {
// We'll take the same approach for STREAM buffers under 4K.
if (usage == BufferUsage::STREAM) {
usage = BufferUsage::DYNAMIC;
}
if (usage == BufferUsage::DYNAMIC && !forceGpuBuffer) {
mBufferPoolEntry = nullptr;
mCpuBuffer = malloc(size);
@@ -56,6 +61,13 @@ void MetalBuffer::copyIntoBuffer(void* src, size_t size, size_t byteOffset) {
"Attempting to copy %d bytes into a buffer of size %d at offset %d",
size, mBufferSize, byteOffset);
if (mUsage == BufferUsage::STREAM) {
// byteOffset must be 0 for STREAM buffers.
assert_invariant(byteOffset == 0);
copyIntoStreamBuffer(src, size);
return;
}
// Either copy into the Metal buffer or into our cpu buffer.
if (mCpuBuffer) {
memcpy(static_cast<uint8_t*>(mCpuBuffer) + byteOffset, src, size);
@@ -72,9 +84,32 @@ void MetalBuffer::copyIntoBuffer(void* src, size_t size, size_t byteOffset) {
memcpy(static_cast<uint8_t*>(mBufferPoolEntry->buffer.contents) + byteOffset, src, size);
}
void MetalBuffer::copyIntoBufferUnsynchronized(void* src, size_t size, size_t byteOffset) {
// TODO: implement the unsynchronized version
copyIntoBuffer(src, size, byteOffset);
void MetalBuffer::copyIntoStreamBuffer(void* src, size_t size) {
// Stream buffers are handled a bit differently. In STREAM mode, we have a single large buffer.
// At each update we "advance" into the buffer, keeping track of the where we're at, and bind
// the buffer at that location. Effectively, "byteOffset" is managed automatically.
assert_invariant(size <= mBufferSize);
assert_invariant(!mCpuBuffer);
mCurrentStreamStart = mCurrentStreamEnd;
mCurrentStreamEnd += size;
if (mCurrentStreamEnd > mBufferSize) {
// Allocate a new buffer and reset the stream offset.
mCurrentStreamStart = 0;
mCurrentStreamEnd = size;
if (mBufferPoolEntry) { mContext.bufferPool->releaseBuffer(mBufferPoolEntry); }
mBufferPoolEntry = mContext.bufferPool->acquireBuffer(mBufferSize);
}
// Lazily acquire a new buffer if we haven't already.
if (!mBufferPoolEntry) {
mBufferPoolEntry = mContext.bufferPool->acquireBuffer(mBufferSize);
}
memcpy(static_cast<uint8_t*>(mBufferPoolEntry->buffer.contents) + mCurrentStreamStart, src, size);
}
id<MTLBuffer> MetalBuffer::getGpuBufferForDraw(id<MTLCommandBuffer> cmdBuffer) noexcept {
@@ -128,7 +163,7 @@ void MetalBuffer::bindBuffers(id<MTLCommandBuffer> cmdBuffer, id<MTLRenderComman
continue;
}
metalBuffers[b] = gpuBuffer;
metalOffsets[b] = offsets[b];
metalOffsets[b] = offsets[b] + buffer->mCurrentStreamStart;
}
if (stages & Stage::VERTEX) {
-6
View File
@@ -118,12 +118,6 @@ private:
mHandleAllocator.deallocate(handle, p);
}
inline void setRenderPrimitiveBuffer(Handle<HwRenderPrimitive> rph,
Handle<HwVertexBuffer> vbh, Handle<HwIndexBuffer> ibh);
inline void setRenderPrimitiveRange(Handle<HwRenderPrimitive> rph, PrimitiveType pt,
uint32_t offset, uint32_t minIndex, uint32_t maxIndex, uint32_t count);
void enumerateSamplerGroups(const MetalProgram* program, ShaderType shaderType,
const std::function<void(const SamplerGroup::Sampler*, size_t)>& f);
void enumerateBoundUniformBuffers(const std::function<void(const UniformBufferState&,
+49 -35
View File
@@ -262,6 +262,10 @@ void MetalDriver::importTextureR(Handle<HwTexture> th, intptr_t i,
ASSERT_PRECONDITION(metalTexture.mipmapLevelCount == levels,
"Imported id<MTLTexture> levels (%d) != Filament texture levels (%d)",
metalTexture.mipmapLevelCount, levels);
MTLPixelFormat filamentMetalFormat = getMetalFormat(mContext, format);
ASSERT_PRECONDITION(metalTexture.pixelFormat == filamentMetalFormat,
"Imported id<MTLTexture> format (%d) != Filament texture format (%d)",
metalTexture.pixelFormat, filamentMetalFormat);
MTLTextureType filamentMetalType = getMetalType(target);
ASSERT_PRECONDITION(metalTexture.textureType == filamentMetalType,
"Imported id<MTLTexture> type (%d) != Filament texture type (%d)",
@@ -274,13 +278,8 @@ void MetalDriver::createSamplerGroupR(Handle<HwSamplerGroup> sbh, uint32_t size)
mContext->samplerGroups.insert(construct_handle<MetalSamplerGroup>(sbh, size));
}
void MetalDriver::createRenderPrimitiveR(Handle<HwRenderPrimitive> rph,
Handle<HwVertexBuffer> vbh, Handle<HwIndexBuffer> ibh,
PrimitiveType pt, uint32_t offset,
uint32_t minIndex, uint32_t maxIndex, uint32_t count) {
void MetalDriver::createRenderPrimitiveR(Handle<HwRenderPrimitive> rph, int dummy) {
construct_handle<MetalRenderPrimitive>(rph);
MetalDriver::setRenderPrimitiveBuffer(rph, vbh, ibh);
MetalDriver::setRenderPrimitiveRange(rph, pt, offset, minIndex, maxIndex, count);
}
void MetalDriver::createProgramR(Handle<HwProgram> rph, Program&& program) {
@@ -704,22 +703,6 @@ void MetalDriver::updateBufferObject(Handle<HwBufferObject> boh, BufferDescripto
scheduleDestroy(std::move(data));
}
void MetalDriver::updateBufferObjectUnsynchronized(Handle<HwBufferObject> boh,
BufferDescriptor&& data, uint32_t byteOffset) {
auto* bo = handle_cast<MetalBufferObject>(boh);
bo->updateBufferUnsynchronized(data.buffer, data.size, byteOffset);
scheduleDestroy(std::move(data));
}
void MetalDriver::resetBufferObject(Handle<HwBufferObject> boh) {
// TODO: implement resetBufferObject(). This is equivalent to calling
// destroyBufferObject() followed by createBufferObject() keeping the same handle.
// It is actually okay to keep a no-op implementation, the intention here is to "orphan" the
// buffer (and possibly return it to a pool) and allocate a new one (or get it from a pool),
// so that no further synchronization with the GPU is needed.
// This is only useful if updateBufferObjectUnsynchronized() is implemented unsynchronizedly.
}
void MetalDriver::setVertexBufferObject(Handle<HwVertexBuffer> vbh, uint32_t index,
Handle<HwBufferObject> boh) {
auto* vertexBuffer = handle_cast<MetalVertexBuffer>(vbh);
@@ -1085,13 +1068,33 @@ void MetalDriver::blit(TargetBufferFlags buffers,
dstRect.left >= 0 && dstRect.bottom >= 0,
"Source and destination rects must be positive.");
// Metal's texture coordinates have (0, 0) at the top-left of the texture, but Filament's
// coordinates have (0, 0) at bottom-left.
const NSInteger srcHeight =
srcTarget->isDefaultRenderTarget() ?
mContext->currentReadSwapChain->getSurfaceHeight() : srcTarget->height;
MTLRegion srcRegion = MTLRegionMake2D(
(NSUInteger) srcRect.left,
srcHeight - (NSUInteger) srcRect.bottom - srcRect.height,
srcRect.width, srcRect.height);
const NSInteger dstHeight =
dstTarget->isDefaultRenderTarget() ?
mContext->currentDrawSwapChain->getSurfaceHeight() : dstTarget->height;
MTLRegion dstRegion = MTLRegionMake2D(
(NSUInteger) dstRect.left,
dstHeight - (NSUInteger) dstRect.bottom - dstRect.height,
dstRect.width, dstRect.height);
auto isBlitableTextureType = [](MTLTextureType t) {
return t == MTLTextureType2D || t == MTLTextureType2DMultisample ||
t == MTLTextureType2DArray;
};
// 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.
MetalBlitter::BlitArgs args;
args.filter = filter;
args.source.region = srcRegion;
args.destination.region = dstRegion;
if (any(buffers & TargetBufferFlags::COLOR_ALL)) {
// We always blit from/to the COLOR0 attachment.
@@ -1103,17 +1106,12 @@ void MetalDriver::blit(TargetBufferFlags buffers,
isBlitableTextureType(dstColorAttachment.getTexture().textureType),
"Metal does not support blitting to/from non-2D textures.");
MetalBlitter::BlitArgs args;
args.filter = filter;
args.source.region = srcColorAttachment.getRegionFromClientRect(srcRect);
args.destination.region = dstColorAttachment.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);
}
}
@@ -1126,19 +1124,34 @@ void MetalDriver::blit(TargetBufferFlags buffers,
isBlitableTextureType(dstDepthAttachment.getTexture().textureType),
"Metal does not support blitting to/from non-2D textures.");
MetalBlitter::BlitArgs args;
args.filter = filter;
args.source.region = srcDepthAttachment.getRegionFromClientRect(srcRect);
args.destination.region = dstDepthAttachment.getRegionFromClientRect(dstRect);
args.source.depth = srcDepthAttachment.getTexture();
args.destination.depth = dstDepthAttachment.getTexture();
if (args.blitColor()) {
// If blitting color, we've already set the source and destination levels and slices.
// Check that they match the requested depth levels/slices.
ASSERT_PRECONDITION(args.source.level == srcDepthAttachment.level,
"Color and depth source LOD must match. (%d != %d)",
args.source.level, srcDepthAttachment.level);
ASSERT_PRECONDITION(args.destination.level == dstDepthAttachment.level,
"Color and depth destination LOD must match. (%d != %d)",
args.destination.level, dstDepthAttachment.level);
ASSERT_PRECONDITION(args.source.slice == srcDepthAttachment.layer,
"Color and depth source layer must match. (%d != %d)",
args.source.slice, srcDepthAttachment.layer);
ASSERT_PRECONDITION(args.destination.slice == dstDepthAttachment.layer,
"Color and depth destination layer must match. (%d != %d)",
args.destination.slice, dstDepthAttachment.layer);
}
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);
}
}
mContext->blitter->blit(getPendingCommandBuffer(mContext), args);
}
void MetalDriver::draw(PipelineState ps, Handle<HwRenderPrimitive> rph, uint32_t instanceCount) {
@@ -1389,11 +1402,12 @@ void MetalDriver::draw(PipelineState ps, Handle<HwRenderPrimitive> rph, uint32_t
id<MTLCommandBuffer> cmdBuffer = getPendingCommandBuffer(mContext);
id<MTLBuffer> metalIndexBuffer = indexBuffer->buffer.getGpuBufferForDraw(cmdBuffer);
size_t offset = indexBuffer->buffer.getGpuBufferStreamOffset();
[mContext->currentRenderPassEncoder drawIndexedPrimitives:getMetalPrimitiveType(primitive->type)
indexCount:primitive->count
indexType:getIndexType(indexBuffer->elementSize)
indexBuffer:metalIndexBuffer
indexBufferOffset:primitive->offset
indexBufferOffset:primitive->offset + offset
instanceCount:instanceCount];
}
+1 -12
View File
@@ -102,7 +102,7 @@ private:
// These two fields store a callback and user data to notify the client that a frame is ready
// for presentation.
// If frameScheduledCallback is nullptr, then the Metal backend automatically calls
// presentDrawable when the frame is committed.
// presentDrawable when the frame is commited.
// Otherwise, the Metal backend will not automatically present the frame. Instead, clients bear
// the responsibility of presenting the frame by calling the PresentCallable object.
FrameScheduledCallback frameScheduledCallback = nullptr;
@@ -117,7 +117,6 @@ public:
MetalBufferObject(MetalContext& context, BufferUsage usage, uint32_t byteCount);
void updateBuffer(void* data, size_t size, uint32_t byteOffset);
void updateBufferUnsynchronized(void* data, size_t size, uint32_t byteOffset);
MetalBuffer* getBuffer() { return &buffer; }
// Tracks which uniform buffers this buffer object is bound into.
@@ -258,16 +257,6 @@ public:
return texture ? texture.pixelFormat : MTLPixelFormatInvalid;
}
MTLRegion getRegionFromClientRect(Viewport rect) {
// Convert the Filament rect into Metal texture coordinates, taking into account Metal's
// inverted texture space and the mip level. Note that the underlying Texture could be
// larger than the RenderTarget. Metal's texture coordinates have (0, 0) at the top-left
// of the texture, but Filament's coordinates have (0, 0) at bottom-left.
const auto mipheight = texture.height >> level;
return MTLRegionMake2D((NSUInteger)rect.left,
mipheight - (NSUInteger)rect.bottom - rect.height, rect.width, rect.height);
}
explicit operator bool() const {
return texture != nil;
}
+1 -33
View File
@@ -28,9 +28,6 @@
#include <utils/trap.h>
#include <utils/debug.h>
#include <math/vec2.h>
#include <math/scalar.h>
#include <math.h>
namespace filament {
@@ -276,10 +273,6 @@ void MetalBufferObject::updateBuffer(void* data, size_t size, uint32_t byteOffse
buffer.copyIntoBuffer(data, size, byteOffset);
}
void MetalBufferObject::updateBufferUnsynchronized(void* data, size_t size, uint32_t byteOffset) {
buffer.copyIntoBufferUnsynchronized(data, size, byteOffset);
}
MetalVertexBuffer::MetalVertexBuffer(MetalContext& context, uint8_t bufferCount,
uint8_t attributeCount, uint32_t vertexCount, AttributeArray const& attributes)
: HwVertexBuffer(bufferCount, attributeCount, vertexCount, attributes), buffers(bufferCount, nullptr) {}
@@ -353,11 +346,8 @@ MetalProgram::MetalProgram(id<MTLDevice> device, const Program& program) noexcep
continue;
}
assert_invariant( source[source.size() - 1] == '\0' );
// the shader string is null terminated and the length includes the null character
NSString* objcSource = [[NSString alloc] initWithBytes:source.data()
length:source.size() - 1
length:source.size()
encoding:NSUTF8StringEncoding];
NSError* error = nil;
// When options is nil, Metal uses the most recent language version available.
@@ -813,10 +803,6 @@ void MetalTexture::updateLodRange(uint32_t level) {
MetalRenderTarget::MetalRenderTarget(MetalContext* context, uint32_t width, uint32_t height,
uint8_t samples, Attachment colorAttachments[MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT], Attachment depthAttachment) :
HwRenderTarget(width, height), context(context), samples(samples) {
UTILS_UNUSED_IN_RELEASE math::vec2<uint32_t> tmin = {std::numeric_limits<size_t>::max()};
UTILS_UNUSED_IN_RELEASE math::vec2<uint32_t> tmax = {0};
UTILS_UNUSED_IN_RELEASE size_t attachmentCount = 0;
for (size_t i = 0; i < MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT; i++) {
if (!colorAttachments[i]) {
continue;
@@ -827,13 +813,6 @@ MetalRenderTarget::MetalRenderTarget(MetalContext* context, uint32_t width, uint
"MetalRenderTarget was initialized with a MSAA COLOR%d texture, but sample count is %d.",
i, samples);
auto t = color[i].metalTexture;
const auto twidth = std::max(1u, t->width >> color[i].level);
const auto theight = std::max(1u, t->height >> color[i].level);
tmin = { std::min(tmin.x, twidth), std::min(tmin.y, theight) };
tmax = { std::max(tmax.x, twidth), std::max(tmax.y, theight) };
attachmentCount++;
// If we were given a single-sampled texture but the samples parameter is > 1, we create
// a multisampled sidecar texture and do a resolve automatically.
if (samples > 1 && color[i].getSampleCount() == 1) {
@@ -852,13 +831,6 @@ MetalRenderTarget::MetalRenderTarget(MetalContext* context, uint32_t width, uint
"MetalRenderTarget was initialized with a MSAA DEPTH texture, but sample count is %d.",
samples);
auto t = depth.metalTexture;
const auto twidth = std::max(1u, t->width >> depth.level);
const auto theight = std::max(1u, t->height >> depth.level);
tmin = { math::min(tmin.x, twidth), math::min(tmin.y, theight) };
tmax = { math::max(tmax.x, twidth), math::max(tmax.y, theight) };
attachmentCount++;
// If we were given a single-sampled texture but the samples parameter is > 1, we create
// a multisampled sidecar texture and do a resolve automatically.
if (samples > 1 && depth.getSampleCount() == 1) {
@@ -869,10 +841,6 @@ MetalRenderTarget::MetalRenderTarget(MetalContext* context, uint32_t width, uint
}
}
}
// Verify that all attachments have the same dimensions.
assert_invariant(attachmentCount > 0);
assert_invariant(tmin == tmax);
}
void MetalRenderTarget::setUpRenderPassAttachments(MTLRenderPassDescriptor* descriptor,
+9 -8
View File
@@ -195,14 +195,6 @@ void NoopDriver::updateBufferObject(Handle<HwBufferObject> ibh, BufferDescriptor
scheduleDestroy(std::move(p));
}
void NoopDriver::updateBufferObjectUnsynchronized(Handle<HwBufferObject> ibh, BufferDescriptor&& p,
uint32_t byteOffset) {
scheduleDestroy(std::move(p));
}
void NoopDriver::resetBufferObject(Handle<HwBufferObject> boh) {
}
void NoopDriver::setVertexBufferObject(Handle<HwVertexBuffer> vbh, uint32_t index,
Handle<HwBufferObject> boh) {
}
@@ -270,6 +262,15 @@ void NoopDriver::endRenderPass(int) {
void NoopDriver::nextSubpass(int) {
}
void NoopDriver::setRenderPrimitiveBuffer(Handle<HwRenderPrimitive> rph,
Handle<HwVertexBuffer> vbh, Handle<HwIndexBuffer> ibh) {
}
void NoopDriver::setRenderPrimitiveRange(Handle<HwRenderPrimitive> rph,
PrimitiveType pt, uint32_t offset,
uint32_t minIndex, uint32_t maxIndex, uint32_t count) {
}
void NoopDriver::makeCurrent(Handle<HwSwapChain> drawSch, Handle<HwSwapChain> readSch) {
}
+1 -3
View File
@@ -35,8 +35,6 @@ public:
private:
ShaderModel getShaderModel() const noexcept final;
uint64_t nextFakeHandle = 1;
/*
* Driver interface
*/
@@ -52,7 +50,7 @@ private:
#define DECL_DRIVER_API_RETURN(RetType, methodName, paramsDecl, params) \
RetType methodName##S() noexcept override { \
return RetType((RetType::HandleId)nextFakeHandle++); } \
return RetType((RetType::HandleId)0xDEAD0000); } \
UTILS_ALWAYS_INLINE inline void methodName##R(RetType, paramsDecl) { }
#include "private/backend/DriverAPI.inc"
+2 -18
View File
@@ -108,7 +108,8 @@ constexpr inline GLenum getBufferUsage(BufferUsage usage) noexcept {
switch (usage) {
case BufferUsage::STATIC:
return GL_STATIC_DRAW;
default:
case BufferUsage::DYNAMIC:
case BufferUsage::STREAM:
return GL_DYNAMIC_DRAW;
}
}
@@ -254,23 +255,6 @@ constexpr inline GLenum getDepthFunc(SamplerCompareFunc func) noexcept {
return getTextureCompareFunc(func);
}
constexpr inline GLenum getStencilFunc(SamplerCompareFunc func) noexcept {
return getTextureCompareFunc(func);
}
constexpr inline GLenum getStencilOp(StencilOperation op) noexcept {
switch (op) {
case StencilOperation::KEEP: return GL_KEEP;
case StencilOperation::ZERO: return GL_ZERO;
case StencilOperation::REPLACE: return GL_REPLACE;
case StencilOperation::INCR: return GL_INCR;
case StencilOperation::INCR_WRAP: return GL_INCR_WRAP;
case StencilOperation::DECR: return GL_DECR;
case StencilOperation::DECR_WRAP: return GL_DECR_WRAP;
case StencilOperation::INVERT: return GL_INVERT;
}
}
constexpr inline GLenum getFormat(PixelDataFormat format) noexcept {
using PixelDataFormat = PixelDataFormat;
switch (format) {
+2 -20
View File
@@ -103,7 +103,7 @@ OpenGLContext::OpenGLContext() noexcept {
int c = sscanf(state.version, "OpenGL ES %d.%d V@%d.%d", // NOLINT(cert-err34-c)
&maj, &min, &driverMajor, &driverMinor);
if (c == 4) {
// Workarounds based on version here.
// workarounds based on version here.
// notes:
// bugs.invalidate_end_only_if_invalidate_start
// - appeared at least in
@@ -130,25 +130,7 @@ OpenGLContext::OpenGLContext() noexcept {
bugs.dont_use_timer_query = true;
}
if (strstr(state.renderer, "Mali-G")) {
// assume we don't have working timer queries
bugs.dont_use_timer_query = true;
int maj, min, driverVersion, driverRevision, driverPatch;
int c = sscanf(state.version, "OpenGL ES %d.%d v%d.r%dp%d", // NOLINT(cert-err34-c)
&maj, &min, &driverVersion, &driverRevision, &driverPatch);
if (c == 5) {
// Workarounds based on version here.
// notes:
// bugs.dont_use_timer_query : on some Mali-Gxx drivers timer query seems
// to cause memory corruptions in some cases on some devices (see b/233754398).
// - appeared at least in
// "OpenGL ES 3.2 v1.r26p0-01eac0"
// - wasn't present in
// "OpenGL ES 3.2 v1.r32p1-00pxl1"
if (driverVersion >= 2 || (driverVersion == 1 && driverRevision >= 32)) {
bugs.dont_use_timer_query = false;
}
}
// note: We have verified that timer queries work well at least on some Mali-G.
}
// Mali seems to have no problem with this (which is good for us)
bugs.allow_read_only_ancillary_feedback_loop = true;
+1 -42
View File
@@ -101,9 +101,6 @@ public:
inline void colorMask(GLboolean flag) noexcept;
inline void depthMask(GLboolean flag) noexcept;
inline void depthFunc(GLenum func) noexcept;
inline void stencilFunc(GLenum func, GLint ref, GLuint mask) noexcept;
inline void stencilOp(GLenum sfail, GLenum dpfail, GLenum dppass) noexcept;
inline void stencilMask(GLuint mask) noexcept;
inline void polygonOffset(GLfloat factor, GLfloat units) noexcept;
inline void beginQuery(GLenum target, GLuint query) noexcept;
inline void endQuery(GLenum target) noexcept;
@@ -292,23 +289,6 @@ private:
GLboolean colorMask = GL_TRUE;
GLboolean depthMask = GL_TRUE;
GLenum depthFunc = GL_LESS;
struct StencilFunc {
GLenum func = GL_ALWAYS;
GLint ref = 0;
GLuint mask = ~GLuint(0);
bool operator != (StencilFunc const& rhs) const noexcept {
return func != rhs.func || ref != rhs.ref || mask != rhs.mask;
}
} stencilFunc;
struct StencilOp {
GLenum sfail = GL_KEEP;
GLenum dpfail = GL_KEEP;
GLenum dppass = GL_KEEP;
bool operator != (StencilOp const& rhs) const noexcept {
return sfail != rhs.sfail || dpfail != rhs.dpfail || dppass != rhs.dppass;
}
} stencilOp;
GLuint stencilMask = ~GLuint(0);
} raster;
struct PolygonOffset {
@@ -654,27 +634,6 @@ void OpenGLContext::depthFunc(GLenum func) noexcept {
});
}
void OpenGLContext::stencilFunc(GLenum func, GLint ref, GLuint mask) noexcept {
// WARNING: don't call this without updating mRasterState
update_state(state.raster.stencilFunc, {func, ref, mask}, [&]() {
glStencilFunc(func, ref, mask);
});
}
void OpenGLContext::stencilOp(GLenum sfail, GLenum dpfail, GLenum dppass) noexcept {
// WARNING: don't call this without updating mRasterState
update_state(state.raster.stencilOp, {sfail, dpfail, dppass}, [&]() {
glStencilOp(sfail, dpfail, dppass);
});
}
void OpenGLContext::stencilMask(GLuint mask) noexcept {
// WARNING: don't call this without updating mRasterState
update_state(state.raster.stencilMask, mask, [&]() {
glStencilMask(mask);
});
}
void OpenGLContext::polygonOffset(GLfloat factor, GLfloat units) noexcept {
update_state(state.polygonOffset, { factor, units }, [&]() {
if (factor != 0 || units != 0) {
@@ -720,6 +679,6 @@ GLuint OpenGLContext::getQuery(GLenum target) const noexcept {
return 0;
}
}
} // namespace filament
} // namesapce filament
#endif //TNT_FILAMENT_BACKEND_OPENGLCONTEXT_H
+114 -116
View File
@@ -294,19 +294,6 @@ void OpenGLDriver::setRasterStateSlow(RasterState rs) noexcept {
gl.depthMask(GLboolean(rs.depthWrite));
}
// stencil test / operation
if (rs.stencilFunc == RasterState::StencilFunction::A && !rs.stencilWrite) {
gl.disable(GL_STENCIL_TEST);
} else {
gl.enable(GL_STENCIL_TEST);
gl.stencilFunc(getStencilFunc(rs.stencilFunc), rs.stencilRef, ~GLuint(0));
gl.stencilOp(getStencilOp(rs.stencilOpStencilFail),
getStencilOp(rs.stencilOpDepthFail),
getStencilOp(rs.stencilOpDepthStencilPass));
GLuint stencilMask = rs.stencilWrite ? ~GLuint(0) : 0x00;
gl.stencilMask(stencilMask);
}
// write masks
gl.colorMask(GLboolean(rs.colorWrite));
@@ -431,37 +418,11 @@ void OpenGLDriver::createBufferObjectR(Handle<HwBufferObject> boh,
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::createRenderPrimitiveR(Handle<HwRenderPrimitive> rph,
Handle<HwVertexBuffer> vbh, Handle<HwIndexBuffer> ibh,
PrimitiveType pt, uint32_t offset,
uint32_t minIndex, uint32_t maxIndex, uint32_t count) {
void OpenGLDriver::createRenderPrimitiveR(Handle<HwRenderPrimitive> rph, int) {
DEBUG_MARKER()
auto& gl = mContext;
GLVertexBuffer const* const eb = handle_cast<const GLVertexBuffer*>(vbh);
GLIndexBuffer const* const ib = handle_cast<const GLIndexBuffer*>(ibh);
assert_invariant(ib->elementSize == 2 || ib->elementSize == 4);
GLRenderPrimitive* rp = handle_cast<GLRenderPrimitive*>(rph);
rp->gl.indicesSize = (ib->elementSize == 4u) ? 4u : 2u;
rp->gl.vertexBufferWithObjects = vbh;
rp->type = pt;
rp->offset = offset * rp->gl.indicesSize;
rp->count = count;
rp->minIndex = minIndex;
rp->maxIndex = maxIndex > minIndex ? maxIndex : rp->maxVertexCount - 1; // sanitize max index
glGenVertexArrays(1, &rp->gl.vao);
gl.bindVertexArray(&rp->gl);
// update the VBO bindings in the VAO
updateVertexArrayObject(rp, eb);
// this records the index buffer into the currently bound VAO
gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib->gl.buffer);
CHECK_GL_ERROR(utils::slog.e)
}
@@ -1076,17 +1037,12 @@ void OpenGLDriver::createRenderTargetR(Handle<HwRenderTarget> rth,
rt->gl.samples = samples;
rt->targets = targets;
UTILS_UNUSED_IN_RELEASE math::vec2<uint32_t> tmin = {std::numeric_limits<uint32_t>::max()};
UTILS_UNUSED_IN_RELEASE math::vec2<uint32_t> tmax = {0};
if (any(targets & TargetBufferFlags::COLOR_ALL)) {
GLenum bufs[MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT] = { GL_NONE };
const size_t maxDrawBuffers = getMaxDrawBuffers();
for (size_t i = 0; i < maxDrawBuffers; i++) {
if (any(targets & getTargetBufferFlagsAt(i))) {
auto t = rt->gl.color[i] = handle_cast<GLTexture*>(color[i].handle);
tmin = { std::min(tmin.x, t->width), std::min(tmin.y, t->height) };
tmax = { std::max(tmax.x, t->width), std::max(tmax.y, t->height) };
rt->gl.color[i] = handle_cast<GLTexture*>(color[i].handle);
framebufferTexture(color[i], rt, GL_COLOR_ATTACHMENT0 + i);
bufs[i] = GL_COLOR_ATTACHMENT0 + i;
}
@@ -1099,9 +1055,7 @@ void OpenGLDriver::createRenderTargetR(Handle<HwRenderTarget> rth,
bool specialCased = false;
if ((targets & TargetBufferFlags::DEPTH_AND_STENCIL) == TargetBufferFlags::DEPTH_AND_STENCIL) {
assert_invariant(!stencil.handle || stencil.handle == depth.handle);
auto t = rt->gl.depth = handle_cast<GLTexture*>(depth.handle);
tmin = { std::min(tmin.x, t->width), std::min(tmin.y, t->height) };
tmax = { std::max(tmax.x, t->width), std::max(tmax.y, t->height) };
rt->gl.depth = handle_cast<GLTexture*>(depth.handle);
if (any(rt->gl.depth->usage & TextureUsage::SAMPLEABLE) ||
(!depth.handle && !stencil.handle)) {
// special case: depth & stencil requested, and both provided as the same texture
@@ -1113,23 +1067,15 @@ void OpenGLDriver::createRenderTargetR(Handle<HwRenderTarget> rth,
if (!specialCased) {
if (any(targets & TargetBufferFlags::DEPTH)) {
auto t = rt->gl.depth = handle_cast<GLTexture*>(depth.handle);
tmin = { std::min(tmin.x, t->width), std::min(tmin.y, t->height) };
tmax = { std::max(tmax.x, t->width), std::max(tmax.y, t->height) };
rt->gl.depth = handle_cast<GLTexture*>(depth.handle);
framebufferTexture(depth, rt, GL_DEPTH_ATTACHMENT);
}
if (any(targets & TargetBufferFlags::STENCIL)) {
auto t = rt->gl.stencil = handle_cast<GLTexture*>(stencil.handle);
tmin = { std::min(tmin.x, t->width), std::min(tmin.y, t->height) };
tmax = { std::max(tmax.x, t->width), std::max(tmax.y, t->height) };
rt->gl.stencil = handle_cast<GLTexture*>(stencil.handle);
framebufferTexture(stencil, rt, GL_STENCIL_ATTACHMENT);
}
}
// Verify that all attachments have the same dimensions.
assert_invariant(any(targets & TargetBufferFlags::ALL));
assert_invariant(tmin == tmax);
CHECK_GL_ERROR(utils::slog.e)
}
@@ -1662,17 +1608,22 @@ void OpenGLDriver::updateBufferObject(
assert_invariant(bd.size + byteOffset <= bo->byteCount);
if (bo->gl.binding == GL_ARRAY_BUFFER) {
gl.bindVertexArray(nullptr);
}
gl.bindBuffer(bo->gl.binding, bo->gl.id);
if (byteOffset == 0 && bd.size == bo->byteCount) {
// it looks like it's generally faster (or not worse) to use glBufferData()
glBufferData(bo->gl.binding, bd.size, bd.buffer, getBufferUsage(bo->usage));
if (bo->gl.binding == GL_UNIFORM_BUFFER) {
// TODO: use updateBuffer() for all types of buffer? Make sure GL supports that.
updateBuffer(bo, bd, byteOffset, (uint32_t)gl.gets.uniform_buffer_offset_alignment);
} else {
// glBufferSubData() could be catastrophically inefficient if several are
// issued during the same frame. Currently, we're not doing that though.
glBufferSubData(bo->gl.binding, byteOffset, bd.size, bd.buffer);
if (bo->gl.binding == GL_ARRAY_BUFFER) {
gl.bindVertexArray(nullptr);
}
gl.bindBuffer(bo->gl.binding, bo->gl.id);
if (byteOffset == 0 && bd.size == bo->byteCount) {
// it looks like it's generally faster (or not worse) to use glBufferData()
glBufferData(bo->gl.binding, bd.size, bd.buffer, getBufferUsage(bo->usage));
} else {
// glBufferSubData() could be catastrophically inefficient if several are
// issued during the same frame. Currently, we're not doing that though.
glBufferSubData(bo->gl.binding, byteOffset, bd.size, bd.buffer);
}
}
scheduleDestroy(std::move(bd));
@@ -1680,58 +1631,73 @@ void OpenGLDriver::updateBufferObject(
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::updateBufferObjectUnsynchronized(
Handle<HwBufferObject> boh, BufferDescriptor&& bd, uint32_t byteOffset) {
DEBUG_MARKER()
void OpenGLDriver::updateBuffer(GLBufferObject* buffer, BufferDescriptor const& p,
uint32_t byteOffset, uint32_t alignment) noexcept {
assert_invariant(buffer->byteCount >= p.size);
assert_invariant(buffer->gl.id);
if constexpr (!HAS_MAPBUFFERS) {
updateBufferObject(boh, std::move(bd), byteOffset);
} else {
GLBufferObject* bo = handle_cast<GLBufferObject*>(boh);
auto& gl = mContext;
gl.bindBuffer(buffer->gl.binding, buffer->gl.id);
if (buffer->usage == BufferUsage::STREAM) {
assert_invariant(bo->gl.id);
assert_invariant(bd.size + byteOffset <= bo->byteCount);
// in streaming mode it's meaningless to have an offset specified
assert_invariant(byteOffset == 0);
if (bo->gl.binding != GL_UNIFORM_BUFFER) {
// TODO: use updateBuffer() for all types of buffer? Make sure GL supports that.
updateBufferObject(boh, std::move(bd), byteOffset);
} else {
auto& gl = mContext;
gl.bindBuffer(bo->gl.binding, bo->gl.id);
retry:
void* const vaddr = glMapBufferRange(bo->gl.binding, byteOffset, bd.size,
buffer->size = (uint32_t)p.size;
// If MapBufferRange is supported, then attempt to use that instead of BufferSubData, which
// can be quite inefficient on some platforms. Note that WebGL does not support
// MapBufferRange, but we still allow STREAM semantics for the web platform.
if (HAS_MAPBUFFERS) {
uint32_t offset = buffer->base + buffer->size;
offset = (offset + (alignment - 1u)) & ~(alignment - 1u);
if (offset + p.size > buffer->byteCount) {
// if we've reached the end of the buffer, we orphan it and allocate a new one.
// this is assuming the driver actually does that as opposed to stalling. This is
// the case for Mali and Adreno -- we could use fences instead.
offset = 0;
glBufferData(buffer->gl.binding, buffer->byteCount, nullptr, getBufferUsage(buffer->usage));
}
retry:
void* vaddr = glMapBufferRange(buffer->gl.binding, offset, p.size,
GL_MAP_WRITE_BIT |
GL_MAP_INVALIDATE_RANGE_BIT |
GL_MAP_UNSYNCHRONIZED_BIT);
if (UTILS_LIKELY(vaddr)) {
memcpy(vaddr, bd.buffer, bd.size);
if (UTILS_UNLIKELY(glUnmapBuffer(bo->gl.binding) == GL_FALSE)) {
if (vaddr) {
memcpy(vaddr, p.buffer, p.size);
if (glUnmapBuffer(buffer->gl.binding) == GL_FALSE) {
// According to the spec, UnmapBuffer can return FALSE in rare conditions (e.g.
// during a screen mode change). Note that this is not a GL error, and we can handle
// during a screen mode change). Note that is not a GL error, and we can handle
// it by simply making a second attempt.
goto retry; // NOLINT(cppcoreguidelines-avoid-goto,hicpp-avoid-goto)
}
} else {
// handle mapping error, revert to glBufferSubData()
glBufferSubData(bo->gl.binding, byteOffset, bd.size, bd.buffer);
glBufferSubData(buffer->gl.binding, offset, p.size, p.buffer);
}
}
buffer->base = offset;
scheduleDestroy(std::move(bd));
CHECK_GL_ERROR(utils::slog.e)
} else {
// In stream mode we're allowed to allocate a whole new buffer
glBufferData(buffer->gl.binding, p.size, p.buffer, getBufferUsage(buffer->usage));
}
} else {
if (byteOffset == 0 && p.size == buffer->byteCount) {
// it looks like it's generally faster (or not worse) to use glBufferData()
glBufferData(buffer->gl.binding, buffer->byteCount, p.buffer,
getBufferUsage(buffer->usage));
} else {
// glBufferSubData() could be catastrophically inefficient if several are
// issued during the same frame. Currently, we're not doing that though.
glBufferSubData(buffer->gl.binding, byteOffset, p.size, p.buffer);
}
}
CHECK_GL_ERROR(utils::slog.e)
}
void OpenGLDriver::resetBufferObject(Handle<HwBufferObject> boh) {
DEBUG_MARKER()
auto& gl = mContext;
GLBufferObject* bo = handle_cast<GLBufferObject*>(boh);
assert_invariant(bo->gl.id);
gl.bindBuffer(bo->gl.binding, bo->gl.id);
glBufferData(bo->gl.binding, bo->byteCount, nullptr, getBufferUsage(bo->usage));
}
void OpenGLDriver::updateSamplerGroup(Handle<HwSamplerGroup> sbh,
SamplerGroup&& samplerGroup) {
@@ -2392,6 +2358,47 @@ GLsizei OpenGLDriver::getAttachments(AttachmentArray& attachments,
return attachmentCount;
}
void OpenGLDriver::setRenderPrimitiveBuffer(Handle<HwRenderPrimitive> rph,
Handle<HwVertexBuffer> vbh, Handle<HwIndexBuffer> ibh) {
DEBUG_MARKER()
auto& gl = mContext;
if (rph) {
GLRenderPrimitive* const rp = handle_cast<GLRenderPrimitive*>(rph);
GLVertexBuffer const* const eb = handle_cast<const GLVertexBuffer*>(vbh);
GLIndexBuffer const* const ib = handle_cast<const GLIndexBuffer*>(ibh);
assert_invariant(ib->elementSize == 2 || ib->elementSize == 4);
gl.bindVertexArray(&rp->gl);
CHECK_GL_ERROR(utils::slog.e)
rp->gl.indicesSize = (ib->elementSize == 4u) ? 4u : 2u;
rp->gl.vertexBufferWithObjects = vbh;
// update the VBO bindings in the VAO
updateVertexArrayObject(rp, eb);
// this records the index buffer into the currently bound VAO
gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib->gl.buffer);
CHECK_GL_ERROR(utils::slog.e)
}
}
void OpenGLDriver::setRenderPrimitiveRange(Handle<HwRenderPrimitive> rph,
PrimitiveType pt, uint32_t offset,
uint32_t minIndex, uint32_t maxIndex, uint32_t count) {
DEBUG_MARKER()
GLRenderPrimitive* const rp = handle_cast<GLRenderPrimitive*>(rph);
rp->type = pt;
rp->offset = offset * rp->gl.indicesSize;
rp->count = count;
rp->minIndex = minIndex;
rp->maxIndex = maxIndex > minIndex ? maxIndex : rp->maxVertexCount - 1; // sanitize max index
}
// Sets up a scissor rectangle that automatically gets clipped against the viewport.
void OpenGLDriver::setViewportScissor(Viewport const& viewportScissor) noexcept {
auto& gl = mContext;
@@ -2462,6 +2469,7 @@ void OpenGLDriver::bindUniformBuffer(uint32_t index, Handle<HwBufferObject> ubh)
auto& gl = mContext;
GLBufferObject* ub = handle_cast<GLBufferObject *>(ubh);
assert_invariant(ub->gl.binding == GL_UNIFORM_BUFFER);
assert_invariant(ub->base == 0);
gl.bindBufferRange(ub->gl.binding, GLuint(index), ub->gl.id, 0, ub->byteCount);
CHECK_GL_ERROR(utils::slog.e)
}
@@ -2473,8 +2481,8 @@ void OpenGLDriver::bindUniformBufferRange(uint32_t index, Handle<HwBufferObject>
GLBufferObject* ub = handle_cast<GLBufferObject *>(ubh);
assert_invariant(ub->gl.binding == GL_UNIFORM_BUFFER);
assert_invariant(offset + size <= ub->byteCount);
gl.bindBufferRange(ub->gl.binding, GLuint(index), ub->gl.id, offset, size);
assert_invariant(ub->base + offset + size <= ub->byteCount);
gl.bindBufferRange(ub->gl.binding, GLuint(index), ub->gl.id, ub->base + offset, size);
CHECK_GL_ERROR(utils::slog.e)
}
@@ -2616,15 +2624,7 @@ void OpenGLDriver::readPixels(Handle<HwRenderTarget> src,
PixelBufferDescriptor& p = *pUserBuffer;
auto& gl = mContext;
gl.bindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
void* vaddr = nullptr;
std::unique_ptr<uint8_t> clientBuffer;
#if defined(__EMSCRIPTEN__)
clientBuffer.reset(new uint8_t(p.size));
glGetBufferSubData(GL_PIXEL_PACK_BUFFER, 0, p.size, clientBuffer.get());
vaddr = clientBuffer.get();
#else
vaddr = glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, p.size, GL_MAP_READ_BIT);
#endif
void* vaddr = glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, p.size, GL_MAP_READ_BIT);
if (vaddr) {
// now we need to flip the buffer vertically to match our API
size_t stride = p.stride ? p.stride : width;
@@ -2639,9 +2639,7 @@ void OpenGLDriver::readPixels(Handle<HwRenderTarget> src,
head += bpr;
tail -= bpr;
}
#if !defined(__EMSCRIPTEN__)
glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
#endif
}
gl.bindBuffer(GL_PIXEL_PACK_BUFFER, 0);
glDeleteBuffers(1, &pbo);
@@ -79,6 +79,8 @@ public:
GLuint id = 0;
GLenum binding = 0;
} gl;
uint32_t base = 0;
uint32_t size = 0;
BufferUsage usage = {};
};
@@ -355,6 +357,8 @@ private:
OpenGLPlatform& mPlatform;
void updateStreamAcquired(GLTexture* t, DriverApi* driver) noexcept;
void updateBuffer(GLBufferObject* buffer, BufferDescriptor const& p,
uint32_t byteOffset, uint32_t alignment = 16) noexcept;
void updateTextureLodRange(GLTexture* texture, int8_t targetLevel) noexcept;
void setExternalTexture(GLTexture* t, void* image);
@@ -186,11 +186,7 @@ highp uint packHalf2x16(vec2 v) {
GLuint shaderId = glCreateShader(glShaderType);
{ // scope for source/length (we don't want them to leak out)
const char* const source = shaderView.data();
// the shader string is null terminated and the length includes the null character
const GLint length = (GLint)shaderView.length() - 1;
assert_invariant( source[length] == '\0' );
const GLint length = (GLint)shaderView.length();
glShaderSource(shaderId, 1, &source, &length);
glCompileShader(shaderId);
#ifndef NDEBUG
-7
View File
@@ -115,13 +115,6 @@
#endif
// This is an odd duck function that exists in WebGL 2.0 but not in OpenGL ES.
#if defined(__EMSCRIPTEN__)
extern "C" {
void glGetBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, void *data);
}
#endif
#if (!defined(GL_ES_VERSION_2_0) && !defined(GL_VERSION_4_1))
#error "Minimum header version must be OpenGL ES 2.0 or OpenGL 4.1"
#endif
@@ -145,6 +145,7 @@ Driver* PlatformCocoaGL::createDriver(void* sharedContext) noexcept {
NSOpenGLPFADepthSize, (NSOpenGLPixelFormatAttribute) 24,
NSOpenGLPFADoubleBuffer, (NSOpenGLPixelFormatAttribute) true,
NSOpenGLPFAAccelerated, (NSOpenGLPixelFormatAttribute) true,
NSOpenGLPFANoRecovery, (NSOpenGLPixelFormatAttribute) true,
0, 0,
};
@@ -42,7 +42,6 @@ using namespace backend;
struct PlatformCocoaTouchGLImpl {
EAGLContext* mGLContext = nullptr;
CAEAGLLayer* mCurrentGlLayer = nullptr;
std::vector<CAEAGLLayer*> mHeadlessGlLayers;
CGRect mCurrentGlLayerRect;
GLuint mDefaultFramebuffer = 0;
GLuint mDefaultColorbuffer = 0;
@@ -109,28 +108,11 @@ Platform::SwapChain* PlatformCocoaTouchGL::createSwapChain(void* nativewindow, u
}
Platform::SwapChain* PlatformCocoaTouchGL::createSwapChain(uint32_t width, uint32_t height, uint64_t& flags) noexcept {
CAEAGLLayer* glLayer = [CAEAGLLayer layer];
glLayer.frame = CGRectMake(0, 0, width, height);
// adding the pointer to the array retains the CAEAGLLayer
pImpl->mHeadlessGlLayers.push_back(glLayer);
return (__bridge SwapChain*) glLayer;
// TODO: implement headless SwapChain
return nullptr;
}
void PlatformCocoaTouchGL::destroySwapChain(Platform::SwapChain* swapChain) noexcept {
CAEAGLLayer* glLayer = (__bridge CAEAGLLayer*) swapChain;
if (pImpl->mCurrentGlLayer == glLayer) {
pImpl->mCurrentGlLayer = nullptr;
}
auto& v = pImpl->mHeadlessGlLayers;
auto it = std::find(v.begin(), v.end(), glLayer);
if(it != v.end()) {
// removing the pointer from the array releases the CAEAGLLayer
v.erase(it);
}
}
void PlatformCocoaTouchGL::createDefaultRenderTarget(uint32_t& framebuffer, uint32_t& colorbuffer,
@@ -103,6 +103,7 @@ Driver* PlatformWGL::createDriver(void* const sharedGLContext) noexcept {
int attribs[] = {
WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
WGL_CONTEXT_MINOR_VERSION_ARB, 1,
WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_PROFILE_MASK_ARB,
0
};
+1
View File
@@ -96,6 +96,7 @@ io::ostream& operator<<(io::ostream& out, BufferUsage usage) {
switch (usage) {
CASE(BufferUsage, STATIC)
CASE(BufferUsage, DYNAMIC)
CASE(BufferUsage, STREAM)
}
return out;
}
@@ -267,10 +267,6 @@ void VulkanContext::createLogicalDevice() {
timestamps_lock.unlock();
const VmaVulkanFunctions funcs {
#if VMA_DYNAMIC_VULKAN_FUNCTIONS
.vkGetInstanceProcAddr = vkGetInstanceProcAddr,
.vkGetDeviceProcAddr = vkGetDeviceProcAddr,
#else
.vkGetPhysicalDeviceProperties = vkGetPhysicalDeviceProperties,
.vkGetPhysicalDeviceMemoryProperties = vkGetPhysicalDeviceMemoryProperties,
.vkAllocateMemory = vkAllocateMemory,
@@ -290,7 +286,6 @@ void VulkanContext::createLogicalDevice() {
.vkCmdCopyBuffer = vkCmdCopyBuffer,
.vkGetBufferMemoryRequirements2KHR = vkGetBufferMemoryRequirements2KHR,
.vkGetImageMemoryRequirements2KHR = vkGetImageMemoryRequirements2KHR
#endif
};
const VmaAllocatorCreateInfo allocatorInfo {
.physicalDevice = physicalDevice,
+16 -57
View File
@@ -405,13 +405,8 @@ void VulkanDriver::createSamplerGroupR(Handle<HwSamplerGroup> sbh, uint32_t coun
construct<VulkanSamplerGroup>(sbh, count);
}
void VulkanDriver::createRenderPrimitiveR(Handle<HwRenderPrimitive> rph,
Handle<HwVertexBuffer> vbh, Handle<HwIndexBuffer> ibh,
PrimitiveType pt, uint32_t offset,
uint32_t minIndex, uint32_t maxIndex, uint32_t count) {
void VulkanDriver::createRenderPrimitiveR(Handle<HwRenderPrimitive> rph, int) {
construct<VulkanRenderPrimitive>(rph);
VulkanDriver::setRenderPrimitiveBuffer(rph, vbh, ibh);
VulkanDriver::setRenderPrimitiveRange(rph, pt, offset, minIndex, maxIndex, count);
}
void VulkanDriver::destroyRenderPrimitive(Handle<HwRenderPrimitive> rph) {
@@ -539,10 +534,6 @@ void VulkanDriver::createDefaultRenderTargetR(Handle<HwRenderTarget> rth, int) {
void VulkanDriver::createRenderTargetR(Handle<HwRenderTarget> rth,
TargetBufferFlags targets, uint32_t width, uint32_t height, uint8_t samples,
MRT color, TargetBufferInfo depth, TargetBufferInfo stencil) {
UTILS_UNUSED_IN_RELEASE math::vec2<uint32_t> tmin = {std::numeric_limits<uint32_t>::max()};
UTILS_UNUSED_IN_RELEASE math::vec2<uint32_t> tmax = {0};
UTILS_UNUSED_IN_RELEASE size_t attachmentCount = 0;
VulkanAttachment colorTargets[MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT] = {};
for (int i = 0; i < MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT; i++) {
if (color[i].handle) {
@@ -552,9 +543,7 @@ void VulkanDriver::createRenderTargetR(Handle<HwRenderTarget> rth,
.layer = color[i].layer,
};
UTILS_UNUSED_IN_RELEASE VkExtent2D extent = colorTargets[i].getExtent2D();
tmin = { std::min(tmin.x, extent.width), std::min(tmin.y, extent.height) };
tmax = { std::max(tmax.x, extent.width), std::max(tmax.y, extent.height) };
attachmentCount++;
assert_invariant(extent.width >= width && extent.height >= height);
}
}
@@ -566,9 +555,7 @@ void VulkanDriver::createRenderTargetR(Handle<HwRenderTarget> rth,
.layer = depth.layer,
};
UTILS_UNUSED_IN_RELEASE VkExtent2D extent = depthStencil[0].getExtent2D();
tmin = { std::min(tmin.x, extent.width), std::min(tmin.y, extent.height) };
tmax = { std::max(tmax.x, extent.width), std::max(tmax.y, extent.height) };
attachmentCount++;
assert_invariant(extent.width >= width && extent.height >= height);
}
if (stencil.handle) {
@@ -578,17 +565,9 @@ void VulkanDriver::createRenderTargetR(Handle<HwRenderTarget> rth,
.layer = stencil.layer,
};
UTILS_UNUSED_IN_RELEASE VkExtent2D extent = depthStencil[1].getExtent2D();
tmin = { std::min(tmin.x, extent.width), std::min(tmin.y, extent.height) };
tmax = { std::max(tmax.x, extent.width), std::max(tmax.y, extent.height) };
attachmentCount++;
assert_invariant(extent.width >= width && extent.height >= height);
}
// All attachments must have the same dimensions, which must be greater than or equal to the
// render target dimensions.
assert_invariant(attachmentCount > 0);
assert_invariant(tmin == tmax);
assert_invariant(tmin.x >= width && tmin.y >= height);
auto renderTarget = construct<VulkanRenderTarget>(rth, mContext,
width, height, samples, colorTargets, depthStencil, mStagePool);
mDisposer.createDisposable(renderTarget, [this, rth] () {
@@ -905,24 +884,6 @@ void VulkanDriver::updateBufferObject(Handle<HwBufferObject> boh, BufferDescript
scheduleDestroy(std::move(bd));
}
void VulkanDriver::updateBufferObjectUnsynchronized(Handle<HwBufferObject> boh,
BufferDescriptor&& bd, uint32_t byteOffset) {
auto bo = handle_cast<VulkanBufferObject*>(boh);
// TODO: implement unsynchronized version
bo->buffer.loadFromCpu(mContext, mStagePool, bd.buffer, byteOffset, bd.size);
mDisposer.acquire(bo);
scheduleDestroy(std::move(bd));
}
void VulkanDriver::resetBufferObject(Handle<HwBufferObject> boh) {
// TODO: implement resetBufferObject(). This is equivalent to calling
// destroyBufferObject() followed by createBufferObject() keeping the same handle.
// It is actually okay to keep a no-op implementation, the intention here is to "orphan" the
// buffer (and possibly return it to a pool) and allocate a new one (or get it from a pool),
// so that no further synchronization with the GPU is needed.
// This is only useful if updateBufferObjectUnsynchronized() is implemented unsynchronizedly.
}
void VulkanDriver::update2DImage(Handle<HwTexture> th,
uint32_t level, uint32_t xoffset, uint32_t yoffset, uint32_t width, uint32_t height,
PixelBufferDescriptor&& data) {
@@ -1639,8 +1600,8 @@ void VulkanDriver::readPixels(Handle<HwRenderTarget> src, uint32_t x, uint32_t y
vkMapMemory(device, stagingMemory, 0, VK_WHOLE_SIZE, 0, (void**) &srcPixels);
srcPixels += subResourceLayout.offset;
if (!DataReshaper::reshapeImage(&pbd, getComponentType(srcFormat), getComponentCount(srcFormat),
srcPixels, subResourceLayout.rowPitch, width, height, swizzle)) {
if (!DataReshaper::reshapeImage(&pbd, getComponentType(srcFormat), srcPixels,
subResourceLayout.rowPitch, width, height, swizzle, false)) {
utils::slog.e << "Unsupported PixelDataFormat or PixelDataType" << utils::io::endl;
}
@@ -1672,21 +1633,19 @@ void VulkanDriver::blit(TargetBufferFlags buffers, Handle<HwRenderTarget> dst, V
VkFilter vkfilter = filter == SamplerMagFilter::NEAREST ? VK_FILTER_NEAREST : VK_FILTER_LINEAR;
// The Y inversion below makes it so that Vk matches GL and Metal.
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 }};
const int32_t srcLeft = std::min(srcRect.left, (int32_t) srcExtent.width);
const int32_t srcBottom = std::min(srcRect.bottom, (int32_t) srcExtent.height);
const int32_t srcRight = std::min(srcRect.left + srcRect.width, srcExtent.width);
const int32_t srcTop = std::min(srcRect.bottom + srcRect.height, srcExtent.height);
const VkOffset3D srcOffsets[2] = { { srcLeft, srcBottom, 0 }, { srcRight, srcTop, 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 }};
const int32_t dstLeft = std::min(dstRect.left, (int32_t) dstExtent.width);
const int32_t dstBottom = std::min(dstRect.bottom, (int32_t) dstExtent.height);
const int32_t dstRight = std::min(dstRect.left + dstRect.width, dstExtent.width);
const int32_t dstTop = std::min(dstRect.bottom + dstRect.height, dstExtent.height);
const VkOffset3D dstOffsets[2] = { { dstLeft, dstBottom, 0 }, { dstRight, dstTop, 1 }};
if (any(buffers & TargetBufferFlags::DEPTH) && srcTarget->hasDepth() && dstTarget->hasDepth()) {
mBlitter.blitDepth({dstTarget, dstOffsets, srcTarget, srcOffsets});
@@ -133,12 +133,6 @@ private:
mHandleAllocator.deallocate(handle, ptr);
}
inline void setRenderPrimitiveBuffer(Handle<HwRenderPrimitive> rph,
Handle<HwVertexBuffer> vbh, Handle<HwIndexBuffer> ibh);
inline void setRenderPrimitiveRange(Handle<HwRenderPrimitive> rph, PrimitiveType pt,
uint32_t offset, uint32_t minIndex, uint32_t maxIndex, uint32_t count);
void refreshSwapChain();
void collectGarbage();
@@ -24,9 +24,6 @@
#pragma clang diagnostic ignored "-Wunused-private-field"
#pragma clang diagnostic ignored "-Wunused-variable"
#pragma clang diagnostic ignored "-Wweak-vtables"
#pragma clang diagnostic ignored "-Wnullability-completeness"
#pragma clang diagnostic ignored "-Wextra-semi"
#pragma clang diagnostic ignored "-Wc++98-compat-extra-semi"
static const PFN_vkGetInstanceProcAddr& vkGetInstanceProcAddr = bluevk::vkGetInstanceProcAddr;
static const PFN_vkGetDeviceProcAddr& vkGetDeviceProcAddr = bluevk::vkGetDeviceProcAddr;
@@ -19,10 +19,6 @@
#include <bluevk/BlueVK.h> // must be included before vk_mem_alloc
#define VMA_STATIC_VULKAN_FUNCTIONS 0
#pragma clang diagnostic ignored "-Wc++98-compat-extra-semi"
#include "vk_mem_alloc.h"
#endif // TNT_FILAMENT_BACKEND_VULKANMEMORY_H
@@ -51,14 +51,8 @@ VulkanStage const* VulkanStagePool::acquireStage(uint32_t numBytes) {
.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
};
VmaAllocationCreateInfo allocInfo { .pool = mContext.vmaPoolCPU };
UTILS_UNUSED_IN_RELEASE VkResult result = vmaCreateBuffer(mContext.allocator, &bufferInfo,
&allocInfo, &stage->buffer, &stage->memory, nullptr);
#ifndef NDEBUG
if (result != VK_SUCCESS) {
utils::slog.e << "Allocation error: " << result << utils::io::endl;
}
#endif
vmaCreateBuffer(mContext.allocator, &bufferInfo, &allocInfo, &stage->buffer, &stage->memory,
nullptr);
return stage;
}
@@ -229,7 +229,6 @@ void VulkanTexture::updateImage(const PixelBufferDescriptor& data, uint32_t widt
// Otherwise, use vkCmdCopyBufferToImage.
void* mapped = nullptr;
VulkanStage const* stage = mStagePool.acquireStage(hostData->size);
assert_invariant(stage->memory);
vmaMapMemory(mContext.allocator, stage->memory, &mapped);
memcpy(mapped, hostData->buffer, hostData->size);
vmaUnmapMemory(mContext.allocator, stage->memory);
@@ -471,109 +471,6 @@ PixelDataType getComponentType(VkFormat format) {
return {};
}
uint32_t getComponentCount(VkFormat format) {
switch (format) {
case VK_FORMAT_R8_UNORM:
case VK_FORMAT_R8_SNORM:
case VK_FORMAT_R8_USCALED:
case VK_FORMAT_R8_SSCALED:
case VK_FORMAT_R8_UINT:
case VK_FORMAT_R8_SINT:
case VK_FORMAT_R8_SRGB:
case VK_FORMAT_R16_UNORM:
case VK_FORMAT_R16_SNORM:
case VK_FORMAT_R16_USCALED:
case VK_FORMAT_R16_SSCALED:
case VK_FORMAT_R16_UINT:
case VK_FORMAT_R16_SINT:
case VK_FORMAT_R16_SFLOAT:
case VK_FORMAT_R32_UINT:
case VK_FORMAT_R32_SINT:
case VK_FORMAT_R32_SFLOAT:
return 1;
case VK_FORMAT_R8G8_UNORM:
case VK_FORMAT_R8G8_SNORM:
case VK_FORMAT_R8G8_USCALED:
case VK_FORMAT_R8G8_SSCALED:
case VK_FORMAT_R8G8_UINT:
case VK_FORMAT_R8G8_SINT:
case VK_FORMAT_R8G8_SRGB:
case VK_FORMAT_R16G16_UNORM:
case VK_FORMAT_R16G16_SNORM:
case VK_FORMAT_R16G16_USCALED:
case VK_FORMAT_R16G16_SSCALED:
case VK_FORMAT_R16G16_UINT:
case VK_FORMAT_R16G16_SINT:
case VK_FORMAT_R16G16_SFLOAT:
case VK_FORMAT_R32G32_UINT:
case VK_FORMAT_R32G32_SINT:
case VK_FORMAT_R32G32_SFLOAT:
return 2;
case VK_FORMAT_R8G8B8_UNORM:
case VK_FORMAT_R8G8B8_SNORM:
case VK_FORMAT_R8G8B8_USCALED:
case VK_FORMAT_R8G8B8_SSCALED:
case VK_FORMAT_R8G8B8_UINT:
case VK_FORMAT_R8G8B8_SINT:
case VK_FORMAT_R8G8B8_SRGB:
case VK_FORMAT_B8G8R8_UNORM:
case VK_FORMAT_B8G8R8_SNORM:
case VK_FORMAT_B8G8R8_USCALED:
case VK_FORMAT_B8G8R8_SSCALED:
case VK_FORMAT_B8G8R8_UINT:
case VK_FORMAT_B8G8R8_SINT:
case VK_FORMAT_B8G8R8_SRGB:
case VK_FORMAT_R16G16B16_UNORM:
case VK_FORMAT_R16G16B16_SNORM:
case VK_FORMAT_R16G16B16_USCALED:
case VK_FORMAT_R16G16B16_SSCALED:
case VK_FORMAT_R16G16B16_UINT:
case VK_FORMAT_R16G16B16_SINT:
case VK_FORMAT_R16G16B16_SFLOAT:
case VK_FORMAT_R32G32B32_UINT:
case VK_FORMAT_R32G32B32_SINT:
case VK_FORMAT_R32G32B32_SFLOAT:
return 3;
case VK_FORMAT_R8G8B8A8_UNORM:
case VK_FORMAT_R8G8B8A8_SNORM:
case VK_FORMAT_R8G8B8A8_USCALED:
case VK_FORMAT_R8G8B8A8_SSCALED:
case VK_FORMAT_R8G8B8A8_UINT:
case VK_FORMAT_R8G8B8A8_SINT:
case VK_FORMAT_R8G8B8A8_SRGB:
case VK_FORMAT_B8G8R8A8_UNORM:
case VK_FORMAT_B8G8R8A8_SNORM:
case VK_FORMAT_B8G8R8A8_USCALED:
case VK_FORMAT_B8G8R8A8_SSCALED:
case VK_FORMAT_B8G8R8A8_UINT:
case VK_FORMAT_B8G8R8A8_SINT:
case VK_FORMAT_B8G8R8A8_SRGB:
case VK_FORMAT_A8B8G8R8_UNORM_PACK32:
case VK_FORMAT_A8B8G8R8_SNORM_PACK32:
case VK_FORMAT_A8B8G8R8_USCALED_PACK32:
case VK_FORMAT_A8B8G8R8_SSCALED_PACK32:
case VK_FORMAT_A8B8G8R8_UINT_PACK32:
case VK_FORMAT_A8B8G8R8_SINT_PACK32:
case VK_FORMAT_A8B8G8R8_SRGB_PACK32:
case VK_FORMAT_R16G16B16A16_UNORM:
case VK_FORMAT_R16G16B16A16_SNORM:
case VK_FORMAT_R16G16B16A16_USCALED:
case VK_FORMAT_R16G16B16A16_SSCALED:
case VK_FORMAT_R16G16B16A16_UINT:
case VK_FORMAT_R16G16B16A16_SINT:
case VK_FORMAT_R16G16B16A16_SFLOAT:
case VK_FORMAT_R32G32B32A32_UINT:
case VK_FORMAT_R32G32B32A32_SINT:
case VK_FORMAT_R32G32B32A32_SFLOAT:
return 4;
default: assert_invariant(false && "Unknown data type, conversion is not supported.");
}
return {};
}
VkComponentMapping getSwizzleMap(TextureSwizzle swizzle[4]) {
VkComponentMapping map;
VkComponentSwizzle* dst = &map.r;
@@ -649,7 +546,6 @@ void transitionImageLayout(VkCommandBuffer cmdbuffer, VulkanLayoutTransition tra
if (transition.oldLayout == transition.newLayout) {
return;
}
assert_invariant(transition.image != VK_NULL_HANDLE && "Please call bindToSwapChain.");
VkImageMemoryBarrier barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = transition.oldLayout;

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