Compare commits

..

573 Commits

Author SHA1 Message Date
Benjamin Doherty
e902df19b2 Merge branch 'rc/1.21.1' into release 2022-04-13 10:15:50 -06:00
Benjamin Doherty
40b372dda7 Update RELEASE_NOTES for 1.21.1 2022-04-12 14:36:26 -06:00
Ben Doherty
fd330a98aa Releases: specify Python dependencies in requirements.txt file (#5402) 2022-04-08 14:35:51 -07:00
Ben Doherty
90c23a7d5d Correctly prepare color grading as subpass programs (#5384) 2022-04-04 13:24:01 -07:00
Benjamin Doherty
5710304114 Bump version to 1.21.1 2022-04-04 13:03:39 -07:00
Benjamin Doherty
0f684820bc Merge branch 'rc/1.21.0' into release 2022-04-04 13:01:35 -07:00
Benjamin Doherty
09fe495384 Release Filament 1.21.0 2022-04-04 13:00:48 -07:00
Benjamin Doherty
e1d2d6ade6 Update RELEASE_NOTES for 1.21.0 2022-04-04 12:58:54 -07:00
Mathias Agopian
e0b6f2ca71 Change version number to 1.21.0 2022-04-04 12:41:38 -07:00
Pavel Korolev
8457d6092d Use index offset provided by ImGui when rendering UI 2022-04-04 10:49:43 -07:00
Mathias Agopian
72c16e07ed remove Viewport::scale()
because a float->integer conversion is needed, it's better to let the
caller decide what they want.
2022-04-02 20:37:00 -07:00
Mathias Agopian
12b96cba04 minor cleanup: rename internal class attributes 2022-04-02 20:37:00 -07:00
Mathias Agopian
e4d943e942 update release nodes and bump material version 2022-04-02 20:36:40 -07:00
Ben Doherty
7fa66325f3 Fix Metal validation error when reading from default SwapChain (#5392) 2022-04-01 16:37:46 -07:00
Mathias Agopian
e188a7875e enable both screen-space refraction and reflection
Both "SSR" can now be used on the same material. This is made possible
by using a 2D array to store both buffers.
2022-04-01 16:22:10 -07:00
Mathias Agopian
ac9822b8c8 Fix a framegraph dependency bug when writing to subresources
The dependency graph was set incorrectly when writing to a subresource
of a subresource.
2022-04-01 16:22:10 -07:00
Mathias Agopian
edb5fddd03 one more step towards reflection+refraction support
With this change we are now generating refraction and reflections
buffer into their own layer of a 2D array -- so they can coexist.

This change doesn't actually enable both at the same time yet.

There are downsides to this approach:
- a 2d array of 2 layers is created even if only one of reflection or
  refraction is active. This could be fixed at the cost of more
  complexity.
- if reflections are active then refraction must use a RGBA16F texture
  instead of RGB_11_11_10, because they share the texture
2022-04-01 14:37:40 -07:00
Mathias Agopian
35f4a97e32 new framegraph API do add a pass without an execute stage 2022-04-01 14:37:40 -07:00
Mathias Agopian
487b10fdda repair and optimize matdbg
we add a checkProgramEdits() method that must be called periodically
on all materials. This is currently done at the beginning of a frame.
2022-03-31 16:52:26 -07:00
Mathias Agopian
271cda88aa Move vulkan backend implementation into the filament::backend namespace 2022-03-31 11:53:54 -07:00
Mathias Agopian
25b73ddcfa Move opengl backend implementation into the filament::backend namespace 2022-03-31 11:53:54 -07:00
Mathias Agopian
35b8146a87 move metal backend out of the metal namespace
this is to be consistent with other backends, which are all in
filament::backend.

had to rename metal::PipelineState to MetalPipelineState.
2022-03-31 11:53:54 -07:00
Mathias Agopian
091e5a33ac move Noop backend into filament::backend namespace 2022-03-31 11:53:54 -07:00
Ben Doherty
ffe4b7390d Correctly prepare color grading as subpass programs (#5384) 2022-03-30 16:25:27 -07:00
Mathias Agopian
604d3e34a4 avoid an extra copy during the screen-space reflection pass
unlike for refraction, the reflection buffer is distinct from "the"
color buffer, this allows an optimization (compared to ssr) when we
generate the mipmap chain -- we can allocate the mipmaped texture
and render the SSR pass directly into its level 0. This achieved
use the framegraph's forward resource feature.
2022-03-30 15:32:52 -07:00
Mathias Agopian
e116dd4aec Improve framegraph forward resource API
This add a couple methods to allow the creation and forwarding in a
single call.
2022-03-30 15:32:52 -07:00
Mathias Agopian
d53614fb0a fix a framegraph crash when forwarding a subresource
the crash would happen when forwarding a subresource of a subresource,
because in this case the parent's handle would be reset to the null
handle.
2022-03-30 15:32:30 -07:00
Mathias Agopian
c91e5df117 Add comment about how we calculate the viewport when upscaling 2022-03-30 08:58:50 -07:00
Philip Rideout
96574816b3 Fix 12x overallocation of memory in MorphTargetBuffer.
I noticed this while helping someone at Google understand our new API.
2022-03-30 08:24:40 -07:00
Mathias Agopian
b43a609ebc rename framegraph fg2/ folder to fg/ 2022-03-29 14:38:36 -07:00
Benjamin Doherty
2a35ee279b Bump version to 1.20.6 2022-03-28 18:47:38 -07:00
Benjamin Doherty
5abf780360 Merge branch 'rc/1.20.5' into release 2022-03-28 18:45:34 -07:00
Benjamin Doherty
2c490ec799 Release Filament 1.20.5 2022-03-28 18:44:56 -07:00
Benjamin Doherty
181f158ea9 Update RELEASE_NOTES for 1.20.5 2022-03-28 18:42:41 -07:00
Mathias Agopian
fbb08d338a repair the flare pass on WebGL 2022-03-28 17:01:07 -07:00
Mathias Agopian
8e1718458a remove all references to the "Blackboard" from PostPorcessManager
This makes the code simpler to follow.
2022-03-28 16:23:52 -07:00
Philip Rideout
6bcd709320 gltfio: add support for KHR_materials_emissive_strength 2022-03-28 12:57:08 -07:00
Mathias Agopian
1a6e3ec88e batch all program linking at begin renderpass time
With this change, shaders are compiled at program creation, programs
are linked at the start of the next render pass and queries are
deferred until first use.

This should improve overall performance on some drivers.
2022-03-26 13:36:35 -07:00
Mathias Agopian
f5f50eca06 programs must now be created outside of renderpasses
from now on, the backends can assume that programs are created outside
of begin/endRenderpass.
2022-03-26 13:35:48 -07:00
Mathias Agopian
886fb7fb94 fix build 2022-03-26 13:35:18 -07:00
Philip Rideout
a82b3bedb2 gltfio: material variants can now be applied to FilamentInstance. 2022-03-25 16:47:59 -07:00
Mathias Agopian
d879bbc80a Simplify OpenGLProgram sampler bindings
This reduces the size of OpenGLProgram from 64 to 32 bytes and
improves the code that sets new samplers.

The main simplification is that we're not trying to "pack" the 
texture units used in the program. For e.g. we could be using
units 0,3,4, where before it would be 0,1,2.
This allows us to do less tracking.

Another optimization is that we're discarding entirely a SamplerGroup 
if the program doesn't use any of its samplers. This helps remove
a test in updateSampler which in turn remove somem tracking data.
2022-03-25 15:35:53 -07:00
Mathias Agopian
bf437b7933 defer gl program link + query to first use (draw)
in an upcoming PR we'll move linking back a bit earlier to allow
more batching.
2022-03-25 13:47:31 -07:00
Mathias Agopian
49dff3c439 log shader source code in debug build on error 2022-03-25 09:40:11 -07:00
Mathias Agopian
0d6c017cfb cleanup OpenGLProgram
This is the first step before we defer a lot of the glGet* calls.
2022-03-25 09:40:11 -07:00
Philip Rideout
ba042db3f4 gltfio Java: add getMorphTargetNames for consistency with other methods.
Tested by hacking ModelViewer.
2022-03-24 19:23:14 -07:00
Philip Rideout
faeba6ad95 gltfio: add support for KHR_materials_variants
Tested the Java API by hacking ModelViewer.
Tested the JavaScript API by adding to filament-viewer-test.
2022-03-24 19:23:14 -07:00
Philip Rideout
163e28ca7a Update public web demos (fixes helmet demo) 2022-03-24 16:10:14 -07:00
Philip Rideout
3dbc168d76 Use newer package for LitElement. 2022-03-24 16:04:43 -07:00
Ben Doherty
fe49946852 Metal: support blitting from 2D texture arrays (#5357) 2022-03-24 11:38:51 -07:00
Mathias Agopian
6310ea46e3 fix dummy ssr history texture target type 2022-03-23 20:47:20 -07:00
LaiJF
ef8e3e5224 Fix typo. (#5355)
* Fix typo.

* Update filament/src/RenderPass.cpp

Co-authored-by: Romain Guy <romain.guy@gmail.com>

Co-authored-by: Mathias Agopian <pixelflinger@gmail.com>
Co-authored-by: Romain Guy <romain.guy@gmail.com>
2022-03-23 11:29:07 -07:00
Mathias Agopian
26cc722f74 remove SPVRemaper lib, fold it into glslang directly
This avoids a duplication of doc.cpp, the largest compilation unit
(about 650KiB).
2022-03-23 11:27:30 -07:00
Philip Rideout
043fdf7a51 Remove lite flavor from android-utils.
We noticed that the lite flavor isn't actually smaller, plus we need to
rework our Android library hierarchy anyway, so for now let's remove
this.
2022-03-23 11:18:25 -07:00
Mathias Agopian
c01105b49a Fix shadow frustum computation wrt projection matrix
Instead of recomputing the Frustum from its 8 vertices, we compute it
from the projection matrix directly. This ensures this works with any
projection matrix.  Building a Frustum object from 8 vertices required
these vertices to be given in a certain order which wasn't correct if
the projection was flipped for instance.

Removed the API to construct a Frustum from vertices.

fixes b/225975881
2022-03-23 09:41:14 -07:00
Philip Rideout
f56f5a300c Temporary workaround for WebGL builds on macOS.
Better fix is to replace etc2comp and astcenc with basis.
2022-03-22 22:21:57 -07:00
Mathias Agopian
8b79f3683e skip work when morphtarget weight is zero
fixes #5344
2022-03-22 22:21:41 -07:00
Benjamin Doherty
319bd123ce Fix, use zero texture array when SSR is of 2022-03-22 22:21:14 -07:00
Benjamin Doherty
e23243a65b Fix build breakage on Windows 2022-03-22 20:43:50 -07:00
Mathias Agopian
c4261a8c10 hide ostream implementation details into ostream.cpp
Fixes #5343
2022-03-22 16:14:13 -07:00
Mathias Agopian
009b58537e move BuilderBase to libutils and rename to PrivateImplementation 2022-03-22 16:14:13 -07:00
Mathias Agopian
e51709a4e8 Size optimizations in UniformInterfaceBlock 2022-03-22 15:28:40 -07:00
Mathias Agopian
78813ed9b7 get rid of ShaderStageFlags.h
move its content to DriverEnums.h, we do this because it is used
in libfilabridge, which has an unspoken rule that it only includes
DriverEnums.h.

filabridge also only has a header dependency, so it can't call any
method, not even operator<<.

Also cleanups and simplifications.
2022-03-22 15:28:40 -07:00
Mathias Agopian
2e649a9f16 size optimizations and cleanups of SamplerInterfaceBlock 2022-03-22 15:28:40 -07:00
Mathias Agopian
d36783cd1d cleanup a bit metal codegen for samplers
the main change here is that we actually go through all "binding points"
instead of hardcoding the ones we currently use.
2022-03-22 15:28:40 -07:00
Philip Rideout
101a59138c Update the zbloat tool
The tool now works with Python 3 and handles binaries that have multiple
embedded material archives.
2022-03-21 16:13:49 -07:00
Benjamin Doherty
f4087fc81d Bump version to 1.20.5 2022-03-21 14:45:34 -07:00
Benjamin Doherty
3809259f47 Release Filament 1.20.4 2022-03-21 14:45:00 -07:00
Benjamin Doherty
82793f9b82 Merge branch 'rc/1.20.4' into release 2022-03-21 14:43:15 -07:00
Benjamin Doherty
537576e84a Update RELEASE_NOTES for 1.20.4 2022-03-21 14:42:35 -07:00
Benjamin Doherty
375d1f55e3 Release Filament 1.20.4 2022-03-21 14:38:14 -07:00
Benjamin Doherty
597218963f Update RELEASE_NOTES for 1.20.4 2022-03-21 14:37:17 -07:00
Mathias Agopian
e103b28b41 The backend CANNOT depend on filabridge
This would mean that the backend is not independent of our material
system. Thankfully we didn't have too many dependencies that leaked
there.
2022-03-21 13:55:15 -07:00
Mathias Agopian
8e7d0c0df9 Fix a bug in Invocable that prevented function signatures that returned references from working 2022-03-21 13:55:15 -07:00
Mathias Agopian
d8845e5fcc greatly simplify SamplerBinderMap
The main simplification is that we don't need an actual map to retrieve
the global offset of a sampler, it can be easily calculated as:
  global_offset = offset_of_the_block + local_offset
2022-03-21 10:54:00 -07:00
Mathias Agopian
b2ed544ee8 More cleanups in PostProcessManager 2022-03-21 10:46:55 -07:00
Mathias Agopian
a40ee77326 minor cleanups 2022-03-21 10:46:55 -07:00
Mathias Agopian
85135e60c7 Switch SSR texture to 2D array
At this point there is no benefit from doing this, but we'll need this
in a later PR.
2022-03-21 10:46:55 -07:00
Mathias Agopian
bee9f160fa gaussian passes now handle 2d arrays better
Instead of passing the level and layer explicitly to gaussianBlurPass,
we rely on the information already contained in the handle. i.e. we
honor the "subresource" part of the handle (if it has one).
In other words, it's now possible to pass a subresource (e.g. a layer)
to generateGaussianMipmap or gaussianBlurPass and things should work as
expected.
2022-03-21 10:46:55 -07:00
Mathias Agopian
64c67258b0 fix FrameGraph dependency issue
The problem here would happen when forwarding a subresource (i.e. 
replacing an existing resource by a subresource) and the existing
resource had been written to. In this situation, the subresource's 
parent needs to depend on the subresource (i.e. as if it was written to
by it). This would normally happen during write() but in this situation,
the write had already happened.
2022-03-21 10:46:39 -07:00
Mathias Agopian
49e0f484e9 fix a framegraph dependency issue
the dependency graph would be incorrectly severed in the situation where
a subresource was written to and later its parent was read from.
In this situation, the parent node is in fact a new version of the 
original parent node, so we need a "read" dependency of the orginal to
the copy (otherwise the orginal node is not a dependent of anyone
and gets culled).
2022-03-21 10:46:39 -07:00
Philip Rideout
0d29b3ddc8 WebGL endFrame: restore additional default state. 2022-03-21 09:43:45 -07:00
Philip Rideout
e0e3b42623 WebGL: reset VAO and texture bindings when frame ends. 2022-03-21 09:43:33 -07:00
Mathias Agopian
dbc78ff0aa Fix screen-space reflections when post-processing and MSAA are off
when we're rendering directly into the swapchain, we can't have a 
history buffer, so in that case we need an intermediate buffer.
2022-03-21 09:10:51 -07:00
Romain Guy
ebca955682 Clear warnings 2022-03-19 12:58:18 -07:00
daemyung jang
d8ea26e305 Update MAX_MORPH_TARGETS to 256 2022-03-18 15:42:02 -07:00
Philip Rideout
37aafdd912 WebGL endFrame: restore additional default state. 2022-03-18 14:23:08 -07:00
Mathias Agopian
edf78afa8e fix warnings from updating macos toolchain 2022-03-17 15:45:09 -07:00
Mathias Agopian
1df4218deb fix python3 detection in cmake 2022-03-17 15:45:09 -07:00
Ben Doherty
1c5715824f Avoid linking clashes with BlueGL and OpenGL (#5323)
Some clients need to link against both Filament and OpenGL. This can lead to symbol clashes under certain circumstances. As a fix, prefix all of our `bluegl` symbols with `bluegl_`. Previously we made this naming change for Windows, but now we'll do it on all platforms for simplicity.
2022-03-17 11:41:38 -07:00
Philip Rideout
6da46b3b62 Repair A2C for opaque views, add field to FrameUniforms. 2022-03-17 10:01:27 -07:00
Philip Rideout
e8d8080928 New behavior for BlendingMode::MASKED.
The existing behavior was surprising for users who draw opaque objects
into a semitransparent views, and this was especially evident with
the labels in `TextureLinearInterpolationTest`.

We now disable blending for MASKED, which is what our existing materials
documentation already says. We also now set the fragment alpha to 1 when
the fragment is not discarded, which prevents the "punch through"
effect. This is consistent with ThreeJS.

Fixes #4576.
2022-03-17 10:01:27 -07:00
Philip Rideout
e7934314ad WebGL: reset VAO and texture bindings when frame ends. 2022-03-17 10:00:51 -07:00
daemyung jang
c79fcf6d8d Fix a typo (#5324) 2022-03-16 08:42:30 -07:00
Mathias Agopian
3eb2a20c7f fix point light lighting with ortho projection
The froxel parameter for the Z slice were not correct.

Fixes #5318
2022-03-15 21:19:25 -07:00
daemyung jang
da99fe63be Make public gltfio's math 2022-03-15 09:11:12 -07:00
daemyung jang
d9067af3a3 Retrieve skins from FilamentAsset 2022-03-15 09:10:52 -07:00
LaiJF
f10bedf186 Fix typo. (#5319) 2022-03-14 19:30:57 -07:00
Mathias Agopian
19b0ad2605 fix a race in jobsystem (2nd attempt)
We were decrementing activeJobCount after removing the job from the
queue, which could cause other threads in the pool to preempt us before
the decrement, causing them to spin forever trying to get a non-existant
job, until the decrement actually happened.

Now we always decrement first and fix-up the count if we couldn't get
a job from the queues. The race is inverted, and doesn't cause threads
to spin a long time.


fixes b/201100123
2022-03-14 16:40:02 -07:00
Philip Rideout
6e7af103d3 Vulkan: misc SwapChain-related cleanup.
This removes some special handling of the default render target lifetime
that is no longer needed, and renames "surface" to "swapChain" where it
is appropriate to do so.
2022-03-14 16:23:31 -07:00
Philip Rideout
8a91723dcf Vulkan cleanup: remove some state from the VulkanDriver class. 2022-03-14 16:23:31 -07:00
Benjamin Doherty
0995ca6614 Bump version to 1.20.4 2022-03-14 14:19:36 -07:00
Benjamin Doherty
3d741fc8d4 Merge branch 'rc/1.20.3' into release 2022-03-14 14:17:54 -07:00
Benjamin Doherty
47e30c337e Release Filament 1.20.3 2022-03-14 14:17:25 -07:00
Philip Rideout
fb627d8b66 gltfio: decouple MaterialProvider lifetime from AssetLoader.
This is a gltfio API change (!)

Jave clients now need to call destroy on MaterialProvider.

Previously, the Java AssetLoader took over ownership of a native
material provider upon construction, but this was neither documented
nor consistent with the C++ layer. (This is historical; in the past we
did not expose MaterialProvider to Java.)

One motivation for this (aside from API consistency) is that users may
wish to preserve the material cache from one run to another.

Fixes #5132.
2022-03-14 08:56:33 -07:00
Alexander Biggs
1cb59685c5 Fix precondition for morph weights. (#5308)
Was checking for `MAX - 1` instead of `MAX`.
2022-03-10 16:46:33 -08:00
Mathias Agopian
2b395f1d89 minor ResourceList cleanup 2022-03-10 16:20:36 -08:00
Mathias Agopian
e9718fa346 cleanup attributes/varyings generation
We now have a single varyings.glsl containing our varyings for both
the vertex and fragment shader. This file is included with the right
definition of VARYING as `in` or `out`.

inputs.vs is now renamed attributes.vs
2022-03-10 16:20:18 -08:00
Philip Rideout
81fc2c1d23 Always apply bone matrices, even for non-animated models.
This changes the WebGL and desktop glTF viewers so that they always
call `updateBoneMatrices`, even when there are 0 animations. Note
that our Android sample was already doing this correctly.

When combined with #5301, this fixes #5299, although users would need to
use the `recomputeBoundingBoxes` feature in gltfio (`-r` in the desktop
viewer) for this model to be scaled to fill the viewport, since its
embedded bounds are quite large.
2022-03-10 13:41:35 -08:00
Benjamin Doherty
c20772b458 Update RELEASE_NOTES for 1.20.3 2022-03-10 12:56:56 -08:00
Philip Rideout
dc60f57a9a gltfio: simplify API, make animator always available.
In the past there was an API gotcha because users had to "get" the
animator before releasing the glTF source data. This could have been
surprising because it was a getter method, not a factory method.

This was due to overeager optimization on my part, I wanted to avoid
animator overhead for non-animated models, when in fact it has very
little overhead.

Moreover, the animator is conceivably useful even when there are no
pre-supplied animations (e.g. for applying skins), so let's just create
it unconditionally.

Motivated by #5299.
2022-03-10 11:36:46 -08:00
Mathias Agopian
5c4f12fa00 create only a single "default render target"
we didn't need one per Renderer, and doing so created complexity in the
backends.

fixes #5291
2022-03-10 11:29:17 -08:00
Romain Guy
00ffd9ca74 Update README.md 2022-03-10 11:02:06 -08:00
daemyung jang
166f859c72 Retrieve morph target count from the primitive (#5297)
Morph weights can be zero even if the primitive has morph targets.
2022-03-10 10:56:50 -08:00
daemyung jang
1969186fe1 Compute the rotation between two vectors (#5288)
Co-authored-by: Mathias Agopian <pixelflinger@gmail.com>
2022-03-10 10:42:44 -08:00
Philip Rideout
e1e7854d97 BlueVK: remove flaky operator<< for flags, update GitHub paths.
Two changes:

1) Khronos has moved from "master" to "main".

2) BlueVK was attempting to generate reasonable "operator<<" support for
bit flags but this was buggy due to type aliases. Since we weren't using
it anyway, I simply removed this functionality from BlueVK.
2022-03-08 16:58:21 -08:00
Philip Rideout
9d5220e28e Regenerate BlueVK for Vulkan 1.3. 2022-03-08 16:57:56 -08:00
Philip Rideout
fc0b41d587 VulkanTexture: remove VkAspect state, derive it on the fly.
This fixes a validation warning, since not all depth textures are
necessarily used as depth attachments.
2022-03-08 14:24:44 -08:00
Benjamin Doherty
4a6b659098 Bump version to 1.20.3 2022-03-07 14:12:28 -08:00
Benjamin Doherty
2b93f08ca5 Merge branch 'rc/1.20.2' into release 2022-03-07 14:10:07 -08:00
Benjamin Doherty
e4cb861817 Release Filament 1.20.2 2022-03-07 14:09:43 -08:00
Benjamin Doherty
fca62b8fff Update RELEASE_NOTES for 1.20.2 2022-03-07 14:08:41 -08:00
Mathias Agopian
640f080ea6 fix TargetBufferInfo uses an union for the face (uint8_t) and layer (uint16_t)
Instead of having 2 fields we're following the vulkan convention of
having only the layer field.

The layer/face convention is still maintained in the public APIs.

fixes #5273
2022-03-04 17:00:37 -08:00
Philip Rideout
eed4b3b839 Add comments about validation to Vulkan backend. 2022-03-04 14:10:14 -08:00
Philip Rideout
f48dafe87e Update remote page to fix invalid generic tone mapper key. 2022-03-04 09:47:53 -08:00
Philip Rideout
daff8fea9f Android Viewer: fix URI bug when dropping some zips.
Dragging a zip file into the Remote Viewer page would fail if it
contained a glTF with `./` prefixes in the `images` section. The best
fix is to use Java's proper URI object rather than trying to parse the
string.
2022-03-04 09:15:37 -08:00
Philip Rideout
51b4a38e20 DriverAPI: add isAutoDepthResolveSupported query. 2022-03-03 14:59:20 -08:00
Philip Rideout
2171e372ce Vulkan: assert if Filament asks to resolve depth in the render pass. 2022-03-03 14:59:20 -08:00
Philip Rideout
1a30709121 Fix Android warnings in Vulkan backend. 2022-03-03 10:37:53 -08:00
Philip Rideout
2ed9b11f50 Bring back initialization of DummyMorphTarget.
This fixes "uninitialized texture" warnings from the Vulkan backend
when viewing Littlest Tokyo in a debug build.
2022-03-02 16:15:57 -08:00
Benjamin Doherty
dee6d9de2c Bump version to 1.20.2 2022-03-02 15:51:38 -08:00
Benjamin Doherty
574e3e7521 Merge branch 'rc/1.20.1' into release 2022-03-02 15:47:21 -08:00
Benjamin Doherty
1797ff5d90 Release Filament 1.20.1 2022-03-02 15:46:41 -08:00
Philip Rideout
8c46e6de9b matdbg: repair invalid JSON and display of active variants.
The JSON response to /api/active became malformed after #4465 because
raw hex strings need to be enclosed by quotes.

This commit changes the variant format in the /api/materials response
to be consistent with one used for /api/active. By using integers
instead of strings, we're avoiding the need to parse integers at run
time.

The JSON error did not appear in the Chrome console because it was being
silenced as a hack to appease "matinfo --web-server". I fix this by
removing the hack and simply emitting a valid response when there's
no live backend.

Also fixed the display of materials, which were always being marked
as active even when they had no active variants.
2022-03-02 15:01:25 -08:00
Philip Rideout
613adfa342 VulkanPipelineCache: fix use-after-free when growing pool.
We held a reference to a cache item after potentially clearing it due to
pool growth. I was able to trigger an error only after enabling ASAN and
loading a large model.  Many thanks to @jeanlemotan for catching this.
2022-03-02 14:59:10 -08:00
Philip Rideout
684b0622eb Vulkan: fix logic that determines when to grow descriptor pool.
When we added per-layout arenas for each of the 3 descriptor types, we
did not account for them when determining how much of the Vk Pool is in
use. Therefore the "growth" (really a re-creation) of the Vk Pool wasn't
always occurring when necessary, causing descriptor set allocation to
fail with large models.
2022-03-02 12:39:33 -08:00
Philip Rideout
426f345f19 Minor updates to how we include vk_mem_alloc.
In the current version of the library, it looks like the DYNAMIC config
macro has been replaced with a STATIC config macro.

Also disabled the "unused-private-field" warning since this is a 3rd
party library and its not our fault.
2022-03-02 12:37:14 -08:00
Ben Doherty
f80df6e061 Make VulkanContext compatible with vk_mem_alloc dev 2022-03-02 12:10:45 -08:00
Ben Doherty
29fdf82ac5 Make VulkanContext compatible with vk_mem_alloc dev 2022-03-02 12:10:20 -08:00
Ben Doherty
e2177e8b36 Apply some clang-tidy fixes (#5281) 2022-03-02 11:49:45 -08:00
Benjamin Doherty
c8cf2a54e8 Update RELEASE_NOTES for 1.20.1 2022-03-02 11:47:51 -08:00
Ben Doherty
bfd32e67d4 Apply some clang-tidy fixes (#5281) 2022-03-02 11:43:51 -08:00
chubei-oppen
37353cca55 android-utils: Copy bug fixes from upstream (#5279) 2022-03-01 17:32:40 -10:00
chubei-oppen
c72817fc25 Bugfix: Mat4 from Quaternion was transposed (#5277) 2022-03-01 10:08:27 -08:00
Mathias Agopian
81c1d3ed1a more code size reduction
The main change here is from ResourceList which ended-up generating
a lot of code due to inlining. This class is only used for tracking
user resources and is not in the performance path.

This saves another ~5K or so of code.
2022-03-01 10:03:31 -08:00
Mathias Agopian
0e1234c57d move the component manager thunks into their own cpp 2022-03-01 10:03:31 -08:00
Mathias Agopian
50fa816a6e fight more unnecessary inlining 2022-03-01 10:03:31 -08:00
Philip Rideout
07f4211dd3 Vulkan: cleanup as per code review. 2022-03-01 08:04:42 -08:00
Philip Rideout
44a433398f Vulkan: shrink DescriptorKey. 2022-03-01 08:04:42 -08:00
Philip Rideout
6821cb60b5 Vulkan: shrink PipelineKey from 608 bytes to 304 bytes. 2022-03-01 08:04:42 -08:00
Philip Rideout
b8788bc390 Minor refactoring in VulkanSwapChain. 2022-03-01 08:04:42 -08:00
Philip Rideout
94c59d9d97 libutils: fix inconsistent hash in StaticString
This caused a unit test failure because a StaticString constructed
from "make" had a different hash than one constructed from a literal,
even though the two strings were lexigraphically equivalent.
2022-02-28 15:42:06 -08:00
daemyung jang
5201b5a1ba Decouple the morphing from the render primitive (#5216)
Having MorphTargetBuffer in FRenderPrimitive is a concept of glTF. Filament doesn't have to follow this concept. Actually the responsibility of FRenderPrimitive is to define vertex input stream because FRenderPrimitive maps to HwRenderPrimitive in Filament. If we store MorphTargetBuffer into FRenderPrimitive then it exceeds the responsibility of FRenderPrimitive. Because MorphTargetBuffer doesn't have any information on how to set up vertex input stream. So handling morphing like skinning will be better.
2022-02-28 11:36:52 -08:00
Philip Rideout
215ef460ef Update Vulkan Memory Allocator to v2.3.0 2022-02-28 11:18:34 -08:00
Philip Rideout
90be8ebfa2 Metal: fix bad upload size in blitDepthPlane.
This was caught by ASAN.
2022-02-28 10:33:42 -08:00
Mathias Agopian
f62d58bd45 don't inline the command dispatcher ctor
We were basically getting two copies.
2022-02-25 13:19:31 -08:00
Mathias Agopian
9e5da2d75f more size optimizations 2022-02-25 13:19:31 -08:00
Mathias Agopian
e12f079ac1 don't prevent unrolling of libmath == operator
We were not unrolling the == loop because the generated code with
unrolling was very branchy; but that's not a good call either because
the loop has the same number of unpredicted branches.
Theoretically the compiler should be able to emit a branchless == but
it doesn't. At least we give it a chance.
2022-02-25 13:19:31 -08:00
Philip Rideout
3c0f18753f GLTFIO_LITE does not need volume texture. 2022-02-25 09:28:17 -08:00
Mathias Agopian
a0e4d3df32 fix android build 2022-02-24 22:43:53 -08:00
Mathias Agopian
4f590e3326 uninline some non performance critical setters 2022-02-24 20:59:21 -08:00
Mathias Agopian
6fdfe606e6 move all public trampolines into their own cpp file
This should prevent code duplication due to agressive inlining.
2022-02-24 20:59:21 -08:00
Mathias Agopian
1baab6c3ae move all 'F' classes into src/details 2022-02-24 20:59:21 -08:00
Mathias Agopian
61e67a2766 clenaup 2022-02-24 20:59:21 -08:00
Philip Rideout
8277015785 Vulkan: Fix regression with IridescentDishWithOlives.
When we introduced texture-based morphing, our custom depth resolver
needed to be updated to set up samplers correctly. This fixes a
validation error about shader stage access.
2022-02-24 15:03:23 -08:00
Philip Rideout
97952e0ddc gltfio ubershader: provide dummy texture for volume thickness.
Fixes logcat spam seen with IridescentDishWithOlives.
2022-02-24 15:02:30 -08:00
Benjamin Doherty
95915367fa Bump version to 1.20.1 2022-02-24 13:59:17 -08:00
Benjamin Doherty
b769cfda62 Merge branch 'rc/1.20.0' into release 2022-02-24 13:57:10 -08:00
Benjamin Doherty
b80d73f3cf Release Filament 1.20.0 2022-02-24 13:55:33 -08:00
Benjamin Doherty
40ac88dfed Bump MATERIAL_VERSION to 20 2022-02-24 13:53:43 -08:00
Benjamin Doherty
6d96082f07 Bump version to 1.20.0 2022-02-24 13:53:43 -08:00
Benjamin Doherty
21f913db1c Update RELEASE_NOTES for 1.20.0 2022-02-24 13:53:42 -08:00
Philip Rideout
a1bf6a427d Enhancement for FILAMENT_VULKAN_VERBOSE. 2022-02-24 11:18:48 -08:00
Philip Rideout
67144bec73 Fix build when FILAMENT_VULKAN_VERBOSE is enabled. 2022-02-24 11:11:15 -08:00
Ben Doherty
699a578966 Add SSR variant filter to matc (#5256) 2022-02-24 10:36:06 -08:00
Ben Doherty
f801763e6b Add SSR variant filter to matc (#5256) 2022-02-24 10:35:30 -08:00
Philip Rideout
542dd331d7 Vulkan: Add asserts that check render target size. 2022-02-24 09:26:32 -08:00
chubei-oppen
4ac3454dc6 Bugfix: The first image passed to Stream::SetAcquiredImage is ignored and leaked 2022-02-24 09:25:14 -08:00
chubei-oppen
23b578ef89 Bugfix: lookAt z axis negated 2022-02-24 09:24:57 -08:00
daemyung jang
b6c26ab4e4 Guarantee Texture's minimum width and height must be 1 2022-02-24 09:23:07 -08:00
Philip Rideout
4fbcfc3168 Engine: fill dummy textures with zeroes or ones. 2022-02-24 09:04:17 -08:00
Philip Rideout
9d0aab4d21 Vulkan: be graceful when apps use uninitialized textures.
This makes it so that we emit a nice error message instead of triggering
a hairy validation error due to UNDEFINED image layout.
2022-02-24 09:02:08 -08:00
Philip Rideout
babbfa1394 Vulkan: remove layout checks from SwapChain.
These asserts will come back in the next Filament release, which has
much cleaner layout tracking.
2022-02-23 13:48:13 -08:00
Philip Rideout
73f0d58e10 Vulkan: fix backend tests (especially ReadPixels Y flip). 2022-02-23 11:18:29 -08:00
Philip Rideout
6420bc6dd8 Vulkan: fix backend tests (especially ReadPixels Y flip). 2022-02-23 10:16:53 -08:00
Mathias Agopian
9fa41d06d6 FrameGraphHandle can be trivial for function calls 2022-02-23 09:52:17 -08:00
Mathias Agopian
805227d6fc improve PostProcessMaterial 2022-02-23 09:52:17 -08:00
Mathias Agopian
67d4632868 user c-array instead of vector<> in hot loop 2022-02-23 09:52:17 -08:00
Mathias Agopian
7efe967add don't inline ctor/dtor that have vector<> 2022-02-23 09:52:17 -08:00
Mathias Agopian
a8cdfc6b23 Make sure Handle<> is trivial for function calls
This allows small-struct calling convention with most ABIs.
2022-02-23 09:52:17 -08:00
Mathias Agopian
7964ebf3c5 Some method really don’t need to be inlined 2022-02-23 09:52:17 -08:00
Ben Doherty
49b8e5e5d2 Adding missing algorithm include (#5237) 2022-02-22 18:06:53 -08:00
Philip Rideout
54e6b6b24a Vulkan: fix issue with MSAA sidecar dimensions.
Every sidecar texture should have the same dimensions as its parent
texture.

Prior to this change, the sidecar texture would have the dimensions of
the RenderTarget wrapper rather than the parent texture. This was wrong
because the RenderTarget might be slightly smaller than the texture.
This caused an issue when the same texture was attached to two render
targets with different sizes, because there's only 1 cached sidecar per
texture.
2022-02-22 17:35:08 -08:00
Philip Rideout
0fe6cfb224 Vulkan: fix lifetime issue with sidecar depth.
We were passing the wrong texture object to VulkanDisposer::acquire().
MSAA depth sidecar textures are not managed by VulkanDisposer, but their
parent textures are.

Fixes #5217.
2022-02-22 17:34:31 -08:00
Philip Rideout
0ee540df9c Vulkan: fix hack, allow SSAO to read from all mips.
When we overhauled image layout transitions, we moved as many
transitions as possible into the render pass. However the transition
that we perform for "depth read only" layout needs to be applied to
multiple miplevels, so we cannot use the render pass for that.
2022-02-22 17:34:18 -08:00
Philip Rideout
249f0a80d8 gltfio: be graceful when model has > 4 weights per vert.
We now handle "too many bone weights" in the same way that we handle
"too many UV sets".  i.e. emit an error message and do not panic.

This change allows us to render the model in #5234 quite reasonably.

Fixes #5234.
2022-02-22 17:34:02 -08:00
Philip Rideout
9cb4b74bbd Fix web apps that have multiple Filament viewers.
This fixes the emscripten binding errors that we've been seeing
with the <filament-viewer> test page, which prevented us from
including web in the last few Filament releases.

The binding errors were caused by double-initializing the emscripten
module.

I fixed this by allowing clients (e.g. FilamentViewer) to call
Filament.init() more than once. We now accumulate a list of "on ready"
callbacks that get triggered after the emscripten module becomes ready.

As far as I can tell, multiple canvases were actually always broken, and
the viewer test page worked in the past only because we got lucky.
2022-02-22 16:12:13 -08:00
Philip Rideout
b3368a3fb2 Vulkan: make validation messages slightly easier to read. 2022-02-22 09:10:05 -08:00
Philip Rideout
327576274f Fix web apps that have multiple Filament viewers.
This fixes the emscripten binding errors that we've been seeing
with the <filament-viewer> test page, which prevented us from
including web in the last few Filament releases.

The binding errors were caused by double-initializing the emscripten
module.

I fixed this by allowing clients (e.g. FilamentViewer) to call
Filament.init() more than once. We now accumulate a list of "on ready"
callbacks that get triggered after the emscripten module becomes ready.

As far as I can tell, multiple canvases were actually always broken, and
the viewer test page worked in the past only because we got lucky.
2022-02-22 08:42:36 -08:00
Mathias Agopian
0e7004a7f8 Automatically set read-only depth in the framefraph 2022-02-18 14:42:35 -08:00
Philip Rideout
ca8549549c Fix build break. 2022-02-18 14:41:59 -08:00
Philip Rideout
fa6d9a4b01 Upgrade emsripten to 3.1.5 2022-02-18 14:36:20 -08:00
Mathias Agopian
3693e4909b Workaround feedback loops limitation in GLES 2022-02-18 13:51:01 -08:00
Mathias Agopian
697a8370cb There was still a case where skinning wasn’t correctly default initialized
Fixes: #5185
2022-02-18 13:49:12 -08:00
Philip Rideout
155a362d60 Fix warning. 2022-02-18 13:37:28 -08:00
Philip Rideout
fed95d70b0 Vulkan: ensure that desired present mode is actually supported. 2022-02-18 11:20:52 -08:00
Philip Rideout
cd126138e0 Clean up readOnlyDepthStencil as per code review. 2022-02-18 10:00:06 -08:00
Philip Rideout
7e7398aa92 Assert valid usage of readOnlyDepthStencil in debug builds. 2022-02-18 10:00:06 -08:00
Philip Rideout
ede7c579f9 Add new backend hint to RenderPassParams.
Previously, the Vulkan backend made an educated guess about the depth
write state during the start of the render pass. The logic for this
did not make any sense, so now we're replacing it with an explicit
hint that PostProcessManager sets up. In a sense this gives backends
a sneak peek into the raster state.
2022-02-18 10:00:06 -08:00
Philip Rideout
67aa6f1913 Update old comments about max color attachment count. 2022-02-17 12:55:31 -08:00
Philip Rideout
80eba1de10 VulkanRenderTarget: remove duplicated state tracking.
Now that VulkanRenderTarget is always backed by textures, it no longer
needs to track state that is already tracked by VulkanTexture.
2022-02-17 08:31:02 -08:00
Philip Rideout
5e05a23e94 Vulkan: Remove duplicated layout tracking. 2022-02-16 16:21:07 -08:00
Philip Rideout
8c8061a637 Vulkan: simplify management of "default" render target. 2022-02-16 16:21:07 -08:00
Philip Rideout
9ef3c59698 Vulkan: clean up the SSAO image layout workaround. 2022-02-16 16:21:07 -08:00
Mathias Agopian
5f7c6c2fbf update material version
This this needed by recent SSR changes.
2022-02-16 11:20:28 -08:00
Mathias Agopian
991360da97 Missing public modifier in Texture.java
Fixes #5210
2022-02-16 10:24:20 -08:00
Mathias Agopian
50d9fb2b5b Fix typo in documentation
Fixes #5150
2022-02-16 10:23:59 -08:00
daemyung jang
001a3e3dc8 Set the morph target buffer by builder (#5179) 2022-02-16 09:20:38 -08:00
Romain Guy
b6eca61786 Update Gradle (#5208)
* Update Gradle

* Add comment
2022-02-15 17:01:17 -08:00
Philip Rideout
cc75eb3aa2 Vulkan: add comments explaining layout strategy. 2022-02-15 15:47:17 -08:00
Philip Rideout
f5fda88cf6 Vulkan: clean up ReadPixels and Blit paths.
VulkanSwapChain is now always backed by VulkanTexture, so these
code paths can be simplified.
2022-02-15 15:47:17 -08:00
Philip Rideout
e99f13b14d Fix some RangeMap behavior and improve its unit test.
The existing unit test had an incorrect expectation in what happens
after splicing an existing range. Fixing the unit test revealed an
actual bug in the RangeMap implementation. It should never modify the
lower bound of an existing interval, because that invalidates the
iterator. It should also never retain a pointer or reference to a range
when the range is potentially removed by subsequent codelines.
2022-02-15 15:46:34 -08:00
Romain Guy
08e809bf75 Update Android tooling (#5204)
* Update Android tooling

* Don't update AGP
2022-02-15 13:22:30 -08:00
Mathias Agopian
1d6aeb5de1 Add basic support for instanced renderables
We can now specify an "instance count" per renderable during creation. 
This instance count applies to all render primitives in the 
Renderable.

This will simply draw the renderable "instance count" times. A new
method available to vertex shaders, getInstanceIndex(), allows the
material to discriminate the instances and adjust the position/transform
accordingly.

Typically this is used for particle systems.
2022-02-15 13:11:23 -08:00
Mathias Agopian
d13ccd1c26 instancing support for the backends
We just add an instance count to the backend draw command.
2022-02-15 13:11:23 -08:00
Ben Doherty
f2c8456971 Attempt to fix Windows CI builds (#5205) 2022-02-15 11:12:19 -08:00
Ben Doherty
54482e6451 Attempt to fix Windows CI builds (#5205) 2022-02-15 11:11:28 -08:00
Romain Guy
9491b36a25 It's ok compiler, it's ok 2022-02-15 08:17:10 -08:00
Mathias Agopian
d387e14d4c cleanup TAA
The new SSR code allows to clean-up TAA code a bit.
TAA should now be more standalone/abstracted.
2022-02-14 16:43:24 -08:00
daemyung jang
5c41b332ad Add Java binding to get morph target names 2022-02-14 16:40:32 -08:00
Benjamin Doherty
e571600c30 Bump version to 1.19.1 2022-02-14 13:48:59 -08:00
Benjamin Doherty
e84c94d3eb Merge branch 'rc/1.19.0' into release 2022-02-14 13:46:45 -08:00
Benjamin Doherty
fd69c7ed75 Release Filament 1.19.0 2022-02-14 13:46:06 -08:00
Benjamin Doherty
e791d4818f Update RELEASE_NOTES for 1.19.0 2022-02-14 13:45:28 -08:00
Philip Rideout
3ff8d6dc22 Incorporate code review feedback. 2022-02-14 13:00:12 -08:00
Philip Rideout
af6fd21e11 Crucial refactoring of VulkanFboCache and VulkanSwapChain.
Two big changes to simplify and fix layout transitions:

(1) The RenderPassKey struct has been reduced from 88 bytes to 56 bytes
by using custom enum types and bitmasks. It also now has separate fields
for "final" and "initial" image layouts.

(2) VulkanSwapChain now leverages VulkanTexture, which enables it to
share tracking functionality, avoid duplicated state, and have less code
overall.

In a future PR we will clean up the ReadPixels and Blit paths, and also
remove some hacks that appease Vulkan when SSAO is enabled.
2022-02-14 13:00:12 -08:00
Mathias Agopian
5bd5c50c8d Remove unit test that is not very useful. 2022-02-14 12:03:07 -08:00
Elie Michel
2c8d296044 Make sure one use the right combination of version
To avoid `Material version mismatch`
2022-02-14 10:55:55 -08:00
Mathias Agopian
df6a100fcb Improve how we compute the lod from the roughness
The main change here is that for screen-space reflections, the lod
calculation takes the camera distance into account.

We also now correctly take into account that we blur each lod
successively which increases the standard deviation by 10%. This applies
to both refraction and reflection.
2022-02-13 22:53:47 -08:00
Mathias Agopian
3f6188edff Enable rough reflections
This works by first generating a reflection buffer which gets blurred,
then the color pass samples from this buffer according to the roughness
of the surface being rendered.

A lot of the changes here involve utilizing "reserved" variants for
the new "SSR" pass and all the fallout from that.
2022-02-13 22:53:47 -08:00
Mathias Agopian
cc0486b3cc Rework material Variant filters
Variants are no longer just a bit mask, but rather a combination of
some bits, depending on the variant. Because of that the variant filer
must be updated.

Basically we now make a distinction between the "variants" as a public
material API and the actual `Variant` data type.

This change does the impedance match between the two.
2022-02-13 22:53:47 -08:00
Mathias Agopian
8314bafc0e reformat Variant.h
indentation was wrong
2022-02-13 22:53:47 -08:00
daemyung jang
764c695e4e Fix typos 2022-02-12 19:30:19 -08:00
Philip Rideout
808ca42992 Vulkan: fix segfault during shutdown. 2022-02-11 16:45:23 -08:00
Philip Rideout
4a8428318b Refactor VulkanSwapChain to prep for image layout cleanup. 2022-02-11 14:50:51 -08:00
Philip Rideout
c93059783b VulkanDriver: fix VkImageView mismatch in render pass logic. 2022-02-11 14:50:51 -08:00
Mathias Agopian
d21f092645 make sure skinning bones are correctly initialized
Fixes: #5185
2022-02-10 20:34:53 -08:00
daemyung jang
9844803b26 Add function overloading for setMorphTargetBufferAt (#5169) 2022-02-10 15:55:41 -08:00
Philip Rideout
cdadb43e50 WebGL: another fix for BufferDescriptor bindings.
The previous code would convert each element of the source data
into 8 bit-per-element, but we wnat to preserve the original format
that the user provides.

The new solution is to use `slice()` which is a robust way to clone
all the data in a typed array.

This fixes the new regression with Triangle that Ben caught.
2022-02-09 15:44:26 -08:00
Philip Rideout
2e0ace5026 WebGL: another fix for BufferDescriptor bindings.
The previous code would convert each element of the source data
into 8 bit-per-element, but we wnat to preserve the original format
that the user provides.

The new solution is to use `slice()` which is a robust way to clone
all the data in a typed array.

This fixes the new regression with Triangle that Ben caught.
2022-02-09 15:41:15 -08:00
Philip Rideout
edaff60fbf WebGL: remove buffer sharing optimization.
If emscripten grows the heap inside one of our BufferDescriptor binding
functions, then the old heap becomes "detached" and an error can
occur.

This fixes the issue seen with the Parquet demo that Ben caught.
2022-02-09 12:51:06 -08:00
Philip Rideout
b8725ffa22 WebGL: remove buffer sharing optimization.
If emscripten grows the heap inside one of our BufferDescriptor binding
functions, then the old heap becomes "detached" and an error can
occur.

This fixes the issue seen with the Parquet demo that Ben caught.
2022-02-09 12:29:54 -08:00
Mathias Agopian
d2da478923 Added Scene::forEach to iterate through a scene's entities
Fixes #3010
2022-02-08 20:23:57 -08:00
Mathias Agopian
0b3e557b65 New Invokable function wrapper 2022-02-08 20:23:57 -08:00
daemyung jang
0d2faa4573 Revert adding APIs 2022-02-08 10:31:17 -08:00
daemyung jang
1924810c17 Deprecate MorphHelper
These changes bring the loading performance optimization by removing
flush and wait.
2022-02-08 10:31:17 -08:00
daemyung jang
6ab45a4cf0 Fix an annotation for the morph target count
Filament now supports the number of morph target up to 256.
2022-02-08 10:23:49 -08:00
Benjamin Doherty
3f64e46557 Bump version to 1.19.0 2022-02-08 09:27:14 -08:00
Benjamin Doherty
32dab23bc6 Update RELEASE_NOTES for 1.18.0 2022-02-08 09:25:41 -08:00
Benjamin Doherty
362de7dd31 Merge branch 'rc/1.18.0' into release 2022-02-08 09:22:21 -08:00
Benjamin Doherty
5e2c94c31a Release Filament 1.18.0 2022-02-08 09:18:10 -08:00
Benjamin Doherty
6b01fbb903 Correct version to 1.18.0 2022-02-08 09:08:49 -08:00
Philip Rideout
4934d9f7bc Vulkan: fix leak when apps do not draw anything. 2022-02-07 14:27:06 -08:00
Philip Rideout
c1a99921b0 Vulkan: fix leak when apps do not draw anything. 2022-02-07 14:26:27 -08:00
Mathias Agopian
4a0dbbce12 fix typo in RenderTarget::build attachment size validation
the validation could fail if attachments used different LODs but the
sizes still matched.
2022-02-07 13:40:34 -08:00
Benjamin Doherty
7398183d6f Bump material version 2022-02-07 11:28:45 -08:00
Ben Doherty
ed73955b00 Initialize useLegacyMorphing to fix MSAN warning (#5164) 2022-02-07 11:28:03 -08:00
Ben Doherty
3f1f2726c4 Add a MAX_LEGACY_MORPH_TARGETS definition (#5163) 2022-02-07 11:27:45 -08:00
Benjamin Doherty
edf405c8fd Fix RELEASE_NOTES 2022-02-07 11:24:50 -08:00
Ben Doherty
4cc8f88a21 Add a MAX_LEGACY_MORPH_TARGETS definition (#5163) 2022-02-07 11:23:49 -08:00
Mathias Agopian
5dba7fdae0 move generateGaussianMipmap to PostProcessManager
also, allow it to specify the output format.
2022-02-04 16:24:27 -08:00
Ben Doherty
e2b8573bd7 Initialize useLegacyMorphing to fix MSAN warning (#5164) 2022-02-04 14:43:18 -08:00
Mathias Agopian
6eeb4c9d3a refactor refraction code
filament/src/Renderer.cpp
- make code mode readable, hopefully
- SSR mipmap generation is now more or less standalone
- when possible, resolve color buffer directly into
  mimpmapped texture's base level.
2022-02-04 11:18:16 -08:00
daemyung jang
996981b102 Change CONFIG_MAX_MORPH_TARGET_COUNT's type correctly
CONFIG_MAX_MORPH_TARGET_COUNT should be positive value so size_t is
proper than int.
2022-02-04 11:17:58 -08:00
daemyung jang
4f4330c95e Update RELEASE_NOTES.md 2022-02-04 11:17:58 -08:00
daemyung jang
e48f54a863 Fix validation errors on Metal 2022-02-04 11:17:23 -08:00
Philip Rideout
1a7bd7ea8d Rewrite VulkanPipelineCache (without changing its API).
All three types of caches (descriptor sets, pipelines, and pipeline
layouts) are now managed in exactly the same way. They all use an LRU
eviction scheme that is based on a count of command buffer flush
events.

Vulkan objects can only be destroyed if there are no in-flight command
buffers that reference them, so an easy way to know when it is safe to
evict a given entry is to wait for "N" flushes after its last use, where
"N" is the number of command buffers in the command buffer ring.

Another big simplification is that there are no more dirty flags,
instead we store two sets of state vectors for each type of cache: the
"currently bound" state, and the "current requirements" state.
2022-02-03 17:37:40 -08:00
Philip Rideout
2aa8ea4687 Rewrite VulkanPipelineCache (without changing its API).
All three types of caches (descriptor sets, pipelines, and pipeline
layouts) are now managed in exactly the same way. They all use an LRU
eviction scheme that is based on a count of command buffer flush
events.

Vulkan objects can only be destroyed if there are no in-flight command
buffers that reference them, so an easy way to know when it is safe to
evict a given entry is to wait for "N" flushes after its last use, where
"N" is the number of command buffers in the command buffer ring.

Another big simplification is that there are no more dirty flags,
instead we store two sets of state vectors for each type of cache: the
"currently bound" state, and the "current requirements" state.
2022-02-03 17:36:57 -08:00
Mathias Agopian
cde055e5bf Minor cleanups
- Rename projectToPixelMatrix to uvFromViewMatrix, this match our 
existing style better.

- slightly more efficient direction transform

- limit roughness to 0.1 instead of 0.01, because in a lot of cases, 
the roughness increases with the LOD, for instance if it comes from
a texture (to combat aliasing).
2022-02-03 14:54:03 -08:00
Mathias Agopian
19729db982 turns out GLES3.x forbids depth texture filtering
warn about this condition on debug builds
2022-02-03 14:28:28 -08:00
daemyung jang
2029c9584e Get the morph target count from glTF
glTF spec says that all primitives MUST have the same number of morph
targets in the same order so these changes are more correct.
2022-02-03 13:26:09 -08:00
Ben Doherty
d9cbe60ca6 Fix NaN values encountered with SSR and Metal (#5156) 2022-02-03 13:24:43 -08:00
Romain Guy
04337fdb68 Update Kotlin math API to latest (#5152)
Changes incorporated from github.com/romainguy/kotlin-math
2022-02-03 12:17:21 -08:00
daemyung jang
a43b17716f Pass the current variant to GLSLPostProcessor
The current Variant is need to calculate BindingIndexMap correctly.
But we can't use the current Variant when calculate BindingIndexMap
because SamplerBindingMap uses only the dummy Variant. Both are
should be same.
2022-02-02 11:59:04 -08:00
daemyung jang
63032ed0a6 Add the morphing sampler group always
The morphing sampler group can be added if skinning or morphing is
enabled. However SamplerBindingMap can't know skinning or morphing
is enabled because only dummy Variant is used. It causes generating
the different sampler bindings between SamplerBindingMap and
program's sampler groups.

Fixes #5139
2022-02-02 11:59:04 -08:00
Ben Doherty
946ea43436 Fix sampler overflow check in SamplerBindingMap (#5143) 2022-02-02 11:04:48 -08:00
Ben Doherty
b6cd6668a6 Fix sampler overflow check in SamplerBindingMap (#5143) 2022-02-02 11:04:08 -08:00
Romain Guy
dee41e6120 Fix notebook 2022-02-02 10:04:48 -08:00
Mathias Agopian
7b03cb9b76 A few screen space reflections improvements
- Make sure to disabled SSR when it's... disabled.

- Fade the reflection when the ray direction is towards de camera,
  where it will likely hit a back face

- Simplify the fading code, for near identical results.
2022-02-02 09:36:20 -08:00
Philip Rideout
8aa83d4886 VulkanPipelineCache: fix spurious SEGV.
Fixes #5142 by replacing unsafe pointers with map keys.

One of the differences between robin_map and unordered_map is the
following:

    pointers to keys or values in the map are invalidated in the same
    way as iterators to these keys-values

Therefore it is unsafe to track the pointer to a value that is stored
in a robin_map.
2022-02-01 16:35:34 -08:00
Philip Rideout
c17b3756ea VulkanPipelineCache: code cleanup and minor fixes.
This is mostly just code cleanup. One actual bug was the fact that the
dummy sampler was re-created every time a new pipeline layout was
created.

It also felt strange to use `auto&` to refer to a C-style array. I
changed this into a `std::array` which is more consistent with other
fixed size arrays in this class.
2022-02-01 16:35:34 -08:00
Philip Rideout
7f42385f5f VulkanPipelineCache: fix spurious SEGV.
Fixes #5142 by replacing unsafe pointers with map keys.

One of the differences between robin_map and unordered_map is the
following:

    pointers to keys or values in the map are invalidated in the same
    way as iterators to these keys-values

Therefore it is unsafe to track the pointer to a value that is stored
in a robin_map.
2022-02-01 16:34:34 -08:00
Philip Rideout
8845ac2b75 VulkanPipelineCache: code cleanup and minor fixes.
This is mostly just code cleanup. One actual bug was the fact that the
dummy sampler was re-created every time a new pipeline layout was
created.

It also felt strange to use `auto&` to refer to a C-style array. I
changed this into a `std::array` which is more consistent with other
fixed size arrays in this class.
2022-02-01 16:34:27 -08:00
Mathias Agopian
73e339b05d be more consistant with defines names in shaders
all defines coming from material parameters are named `MATERIAL_HAS_...` 
and all defines coming from the variant are named `VARIANT_HAS_...`
2022-01-31 22:53:48 -08:00
Ben Doherty
42172c7395 Add iterator include to Range.h (#5141) 2022-01-31 12:54:27 -08:00
Philip Rideout
fbc0b8dab5 gltf_viewer: fix bad ReadPixels size in headless mode
This fixes the gltf_viewer automated testing mode, invoked via
`--batch=default --headless`.

ReadPixels was being issued with an out-of-bounds size on high DPI
platforms, which caused weird backend errors.

Since we create an invisible SDL window while in headless mode, the
presence of the SDL window does *not* indicate headless vs non-headless.

Partial fix for #5111
2022-01-31 11:34:13 -08:00
Mathias Agopian
91b45d2890 fix an out-of-bound access when setting morphing buffer
Because the morphing buffer is actually a texture, it's possible that
the last line is not a full width when updating the buffer.
Because texture are updated via a rectangle, it was possible to read
past the malloc'ed buffer during the update.

Moreover, because the count can be specified, we can't just blindly send
more "dummy" data. 

Finally, added an offset to match the skinning API, and in that case, 
the first line can also be incomplete.


We fix this by issuing up to 3 texture update calls if needed.


The java/js API update will come later.
2022-01-30 16:53:11 -08:00
daemyung jang
9df13c1cd2 Cleanup code 2022-01-28 21:41:19 -08:00
daemyung jang
5a3853a442 Optimize memory of MorphTargetBuffer (#5046)
* Optimize memory of MorphTargetBuffer

Co-authored-by: Mathias Agopian <mathias@google.com>
2022-01-27 21:19:13 -08:00
Mathias Agopian
70e14a1757 try to workaround optimizer/compiler bugs
Fixes #5088
2022-01-27 19:24:11 -08:00
Ben Doherty
4c4a93d9b5 Support legacy morphing (#5129)
Support legacy morphing (morphing with targets supplied via VertexAttributes) for older clients. This gives clients more time to transition over to the new MorphTargetBuffer API.
2022-01-27 16:16:53 -08:00
Ben Doherty
da85001d4d Support legacy morphing (#5129)
Support legacy morphing (morphing with targets supplied via VertexAttributes) for older clients. This gives clients more time to transition over to the new MorphTargetBuffer API.
2022-01-27 16:08:46 -08:00
Mathias Agopian
001dcefd8a simplify how we select a material Variant
Instead of building the Variant based on flags in RenderPass, we just
pass the Variant itself to RenderPass. The caller has more knowledge
of what it wants to do.
2022-01-27 15:48:24 -08:00
Mathias Agopian
d114d547be update material version to 18 2022-01-26 14:49:09 -08:00
Mathias Agopian
8d15079937 update material version to 18 2022-01-26 14:32:46 -08:00
daemyung jang
adc542b5cd Bind samplers to specified shader stages (#5036)
Co-authored-by: Ben Doherty <bendoherty@google.com>
Co-authored-by: Mathias Agopian <mathias@google.com>
2022-01-26 14:31:30 -08:00
Philip Rideout
72feb044a3 Vulkan now supports offsets when uploading texture data.
This allows `MorphStressTest` to work on Vulkan.

However, `Horse` is still broken because it provides positions but not
tangents.  Separate fix for that is coming.

Partial fix for #5109.
2022-01-26 14:31:00 -08:00
Philip Rideout
c0ba260ddf Vulkan: clean up image layout management.
This fixes validation errors and makes a first pass at simplification.
VulkanTexture now tracks image layout using RangeMap, which paves the
way for further simplification.
2022-01-26 14:30:45 -08:00
Philip Rideout
2da215e8e7 RangeMap: improve naming convention, etc. 2022-01-26 14:30:23 -08:00
Philip Rideout
4d0368b5f1 RangeMap: improve the auto-merge functionality. 2022-01-26 14:30:09 -08:00
Philip Rideout
d11c78857d utils: introduce RangeMap container and unit test.
This will allow the Vulkan backend to efficiently track the subresource
image layouts for each texture.

This is a sparse container for a series of ordered non-overlapping
integer intervals, where each interval maps to a concrete value.
2022-01-26 14:29:45 -08:00
Mathias Agopian
e829d90c4a A morphing buffer must be bound when skinning is active
This is because we're using the same program variant for skinning
and morphing, in the skinning-only case, the buffer won't be accessed
in the shader, but it must be present.

fixes #5085
2022-01-26 14:20:25 -08:00
Mathias Agopian
a8006acd33 [GL backend] fix sampler binding bug
When a program had an unused SamplerInterfaceBlock, other samplers
could be bound to the wrong TMU

Fixes #5088
2022-01-26 14:20:12 -08:00
Philip Rideout
6403e0ce44 gltfio morphing: generate normals when they are missing.
This allows the `Horse.glb` model to work with Vulkan without any
validation errors. As a reminder, the glTF spec says:

```
When normals are not specified, client implementations MUST calculate
flat normals
```

Fixes #5115.
2022-01-26 13:48:05 -08:00
daemyung jang
41cf507746 Bind samplers to specified shader stages (#5036)
Co-authored-by: Ben Doherty <bendoherty@google.com>
Co-authored-by: Mathias Agopian <mathias@google.com>
2022-01-26 12:22:07 -08:00
HanYunChenLuo
c49fcf9018 WebGL: Support compile filament.wasm on Linux platform. (#5120) 2022-01-26 10:28:03 -08:00
daemyung jang
354c39be6b Get the morph target count from the renderable (#5077)
* Get the morph target count from the renderable
* Set the morph target count by Builder
* Update morph target weights partially
* Remove noexcept at functions could throw exceptions
* Update Java bindings at RenderableManager
* Add missing comments
* Update morph target weights from offset

Co-authored-by: Mathias Agopian <mathias@google.com>
2022-01-26 10:27:25 -08:00
wangjinhan
26bbe8ade1 fix build android aar on Linux because of case sensitive 2022-01-25 22:39:40 -08:00
daemyung jang
1952f0a1f7 Change morphing APIs to support LOD (#5080)
* Change morphing APIs to support LOD
* Add Java and Web bindings for morphing
* Omit and fix JS bindings
* Fix styles in MorphTargetBuffer.java
2022-01-25 21:57:11 -08:00
daemyung jang
61fdc0d375 Fix styles in SkinningBuffer.java (#5117) 2022-01-25 21:46:55 -08:00
Mathias Agopian
4060b558c7 Minor optimizations and documentation cleanup
- Document that both positions and tangents must be provided.
- Don't memset buffer before filling it
- Don't read 4 identical weights in shader
2022-01-25 17:16:43 -08:00
Philip Rideout
a783df39ba Vulkan now supports offsets when uploading texture data.
This allows `MorphStressTest` to work on Vulkan.

However, `Horse` is still broken because it provides positions but not
tangents.  Separate fix for that is coming.

Partial fix for #5109.
2022-01-25 17:06:33 -08:00
Philip Rideout
a9ccaf2ffb Vulkan: clean up image layout management.
This fixes validation errors and makes a first pass at simplification.
VulkanTexture now tracks image layout using RangeMap, which paves the
way for further simplification.
2022-01-25 15:45:58 -08:00
Mathias Agopian
f40b08d826 Simplify and optimize morphing
There is no need to go through all primitive and call updateSamplerGroup,
because the SamplerGroup never changes -- it just hold the texture that
holds the data.
2022-01-25 14:08:15 -08:00
Mathias Agopian
9fd0397d45 A morphing buffer must be bound when skinning is active
This is because we're using the same program variant for skinning
and morphing, in the skinning-only case, the buffer won't be accessed
in the shader, but it must be present.

fixes #5085
2022-01-25 13:11:02 -08:00
Philip Rideout
69fb7170a7 Fix typo in BlueVK script that caused segfault.
Fixes #5026.
2022-01-25 10:23:07 -08:00
Mathias Agopian
b69546c229 [GL backend] fix sampler binding bug
When a program had an unused SamplerInterfaceBlock, other samplers
could be bound to the wrong TMU

Fixes #5088
2022-01-25 10:09:22 -08:00
Alexey Pelykh
45054eece9 gltfio: support material extras 2022-01-25 10:04:10 -08:00
Philip Rideout
785f7de25d RangeMap: improve naming convention, etc. 2022-01-25 09:58:53 -08:00
Philip Rideout
509fb4ad23 RangeMap: improve the auto-merge functionality. 2022-01-25 09:58:53 -08:00
Philip Rideout
6577519bd7 utils: introduce RangeMap container and unit test.
This will allow the Vulkan backend to efficiently track the subresource
image layouts for each texture.

This is a sparse container for a series of ordered non-overlapping
integer intervals, where each interval maps to a concrete value.
2022-01-25 09:58:53 -08:00
Philip Rideout
43948421d7 Re-generate BlueVK and update to latest Vk headers.
Fixes #5026.
2022-01-25 09:14:23 -08:00
Philip Rideout
328650df17 BlueVK: Do not double initialize vkGetInstanceProcAddr.
This fixes a double-initialization problem for one of the function
pointers, and also updates the BlueVK generator to fix issues with the
latest Khronos XML file.

The corollary C++ changes will be made in a subsequent PR since they
will be difficult to review.

See #5026.
2022-01-24 13:40:49 -08:00
Benjamin Doherty
86ec502040 Bump version to 1.17.1 2022-01-24 12:52:22 -08:00
Benjamin Doherty
b19a73cc50 Merge branch 'rc/1.17.0' into release 2022-01-24 12:50:22 -08:00
Benjamin Doherty
b657ccd75a Release Filament 1.17.0 2022-01-24 12:48:28 -08:00
Benjamin Doherty
a99c695932 Update RELEASE_NOTES for 1.17.0 2022-01-24 12:45:05 -08:00
Ondrej Stava
11cbb3d395 Fixed VulkanTexture::copyBufferToImage for 2D texture arrays
2D array textures are initialized with .depth = 1 and layerCount = depth (see line 58 in VulkanTexture.cpp). By setting layerCount = 1 only the first layer was copied over, leaving the other layers uninitialized.
2022-01-24 10:38:03 -08:00
Mathias Agopian
c21d7c3f5e try to use the Variant type instead of uint8_t everywhere 2022-01-24 09:45:34 -08:00
Philip Rideout
975665c9c9 gltf_viewer: fix the "Export screenshot" checkbox.
This functionality (in the Automation section) was violating a
constraint that was landed in November.

1) Call postRender inside beginFrame / endFrame.

2) Use RGBA when issuing ReadPixels (required by some backends) and
   convert to RGB when dumping out the PPM file.
2022-01-24 08:32:29 -08:00
daemyung jang
613e1052c7 Make morphable entities selectable in UI 2022-01-21 16:18:19 -08:00
Mathias Agopian
ba9e7fa17f Improve (again) comments in Variants.h
- Improved formating
- Added more compile-time sanity checks
- Renamed Variant bits to 3 letters
2022-01-21 14:24:24 -08:00
daemyung jang
fa54bdd682 Update imgui to v1.86 2022-01-21 09:53:44 -08:00
Mathias Agopian
1678d02c87 Allow more flexible quality settings for the ColorGrading LUT 2022-01-20 09:55:16 -08:00
daemyung jang
5e535165a6 Get morph target names from FilamentAsset (#5066)
Get morph target names from FilamentAsset
Make morphable entities selectable in UI
2022-01-19 17:11:24 -08:00
Mathias Agopian
3de427b74f Fix integration of screen-space reflections with lighting
screen-space reflections are integrated in the indirect light computation
(similarly to screen-space refraction), this is because it can be seen as
the specular term of screen-space GI.

However, because this effect is screen-space, the data it accesses has 
the ibl luminance (and exposure) applied.

Besides some minor refactoring, this change just applies the 
screen-space reflections *after* the ibl's specular term is exposed.
2022-01-19 17:10:10 -08:00
Mathias Agopian
15899af7cf randomly jitter the ray with screen-space reflections
this helps a lot when stride is > 1
2022-01-19 17:09:54 -08:00
daemyung jang
443181c719 Enhance code readability 2022-01-19 15:54:08 -08:00
daemyung jang
02f96e2a1e Store morph weight buffer at PrimitiveInfo to avoid dereference 2022-01-19 15:54:08 -08:00
daemyung jang
67e0aa5488 Store morph target buffer at PrimitiveInfo to avoid dereference 2022-01-19 15:54:08 -08:00
daemyung jang
c969005bcc Create and bind morphing buffer if skinning is enabled
The morphing buffer is needed even if skinning is enabled
because shader is generated by HAS_SKINNING_OR_MORPHING.
2022-01-19 15:54:08 -08:00
Mathias Agopian
5417d0953b Allow screen space refraction and reflection together
We can now do screen-space refraction and reflections at the same time.
This change mostly removes the checks that were preventing it from
working.

The real change in the PR is to adjust the reprojection matrix based
on whether the SSR buffer (both for refractions and reflections) comes
from this or the previous frame.
2022-01-19 13:30:12 -08:00
Mathias Agopian
ddb4865ceb allow a scene to have both transmission and reflection
what's not allowed at this point is an object which has both screen
space refraction and reflection.

this is accomplished by just always disabling screen-space reflections
for the translucent step of the refraction pass.
2022-01-19 13:30:12 -08:00
Philip Rideout
7b5cac6d4f Do not include <algorithm> unless necessary. 2022-01-19 13:11:04 -08:00
Ben Doherty
fb76f8ed80 Add Java / WebGL bindings for screen-space reflections (#5054) 2022-01-19 12:50:32 -08:00
daemyung jang
4b572cf065 Remove duplicated APIs 2022-01-19 09:55:59 -08:00
daemyung jang
3e3fc76688 Add FilamentAsset Java bindings 2022-01-19 09:55:59 -08:00
Romain Guy
700b4d5d38 Update docs and readmes 2022-01-18 16:54:31 -08:00
daemyung jang
9e29d042b9 Add a comment for further work 2022-01-18 16:53:04 -08:00
daemyung jang
13f3ebca89 Transition the initial image layout if TextureUsage::SAMPLEABLE 2022-01-18 16:53:04 -08:00
Philip Rideout
3e30632b8c Reduce cascade of run-time warnings.
The `uint8_t` here needs to be cast to an integer to be printed
correctly. Also these warnings seem to be quite common so we should
hide them in Release builds.

These warnings probably indicate an actual problem that I do not fully
understand yet.
2022-01-18 16:04:16 -08:00
Benjamin Doherty
8cd720b53a Bump version to 1.17.0 2022-01-18 13:54:40 -08:00
Benjamin Doherty
04df79e58f Merge branch 'rc/1.16.1' into release 2022-01-18 13:53:02 -08:00
Benjamin Doherty
a8d72bb226 Release Filament 1.16.1 2022-01-18 13:52:08 -08:00
Benjamin Doherty
a4b3717762 Update RELEASE_NOTES for 1.16.1 2022-01-18 13:48:36 -08:00
Ben Doherty
bf3f7e0aef Fix, assertion with shadowReceiver = false and VSM (#5055) 2022-01-18 13:44:48 -08:00
Mathias Agopian
0fb04c576d improve structure pass performance when not used
Move the command generation of the structure pass into its execute 
block, meaning that if the structure pass is culled, the command 
generation is now skipped too.
2022-01-18 12:21:36 -08:00
Mathias Agopian
caaa404d96 add basic support for Android Thermal Manager 2022-01-18 11:37:26 -08:00
daemyung jang
2fa6e6d031 Remove an useless log 2022-01-18 10:35:39 -08:00
daemyung jang
62bb25b26d Fix, potential null dereferences in OpenGLProgram
Morphing is enabled but no morph targets in some models.
2022-01-18 10:35:39 -08:00
Mathias Agopian
8d1402d37b Bring back the 3x3 filter for PCF shadows
The same can be achieved with VSM + blur=3 however, this is noticeably
slower. Also when using transparent shadows, VSM needs a much larger
blur to iron out the dithering pattern.

Fixes #5048, #5039
2022-01-14 15:08:46 -08:00
Ben Doherty
afd657d6af Fix, incorrect refractions with screen-space reflections disabled (#5051) 2022-01-13 16:54:47 -08:00
Romain Guy
27a5158147 Update tone mapping operators notebook 2022-01-13 15:38:19 -08:00
Mathias Agopian
dead7ab2ac Use NDK29 new (and experimental) way to access NDK functions
This uses compile time guarded calls to weak symbols, and allows us to
call NDK APIs without having to dlsym() them.
2022-01-13 15:20:26 -08:00
Mathias Agopian
352acff396 improve documentation regarding post-processing and render targets
Fixes #5015
2022-01-13 09:59:58 -08:00
Ben Doherty
00d9c6921d Add initial glossy screen-space reflections (#4946) 2022-01-12 13:59:11 -08:00
daemyung jang
6805940bbf Compute morphing on GPU (#4999) 2022-01-12 11:06:47 -08:00
Romain Guy
954f9112e4 Replace generic tonemap curve with a simpler one (#5041)
* Replace generic tonemap curve with a simpler one

This change removes the shoulder parameter which had inconsistent
behaviors. The new curve is simpler and designed to still match
by default the gray point and the contrast of ACES in a bright
surround.

* Fix build
2022-01-12 09:55:35 -08:00
hzzengxiaoqi
6465b9ade8 fix bug of GLTFIO_LITE, the macro GLTFRESOURCES_LITE_LIT_BLEND_DATA is not defined anywhere, it should be GLTFRESOURCES_LITE_LIT_FADE_DATA. This solves the issue of rendering transparent objects using GLTFIO_LITE macro, i.e. using gltfresources_lite.bin. If not change this macro, the transparent objects will be rended using LIT_OPAQUE material instead of LIT_FADE material. 2022-01-11 10:31:49 -08:00
Jared Fowler
b67963176b Moving UiHelper to the constructor which allows for more composable control of the underlying views & surface 2022-01-11 08:56:42 -08:00
Ankbzpx
fb1eb35ba5 Fix aabb misalignment for skinned gltf model (#4973) 2022-01-10 15:06:23 -08:00
Mathias Agopian
047543a4a6 make our ostream thread safe
ostream internals are now protected by a lock, which ensures the
internal state stays consistant, however, this won't prevent 
multiple threads to have their output ominterfering with each other,
which is no different from the stl behavior.


This fixes #4992
2022-01-10 15:04:26 -08:00
Mathias Agopian
5e0615040d refactor our ostream
The main change here is that we factorize all the interesting code in
a single function. This should result in smaller code.
2022-01-10 15:04:26 -08:00
Mathias Agopian
1ceed1519b attempt to fix compilation failure with gcc
fix #4990
2022-01-10 15:04:09 -08:00
Benjamin Doherty
1035e442ee Bump version to 1.16.1 2022-01-10 10:47:46 -08:00
Benjamin Doherty
60d3638f15 Merge branch 'rc/1.16.0' into release 2022-01-10 10:44:36 -08:00
Benjamin Doherty
a1a3adf8af Release Filament 1.16.0 2022-01-10 10:43:35 -08:00
Benjamin Doherty
3e7d3c9035 Update RELEASE_NOTES for 1.16.0 2022-01-10 10:41:14 -08:00
jeanlemotan
eb360be2ad Fixed cubemap update 2022-01-10 10:34:49 -08:00
Ben Doherty
620a693c11 FilamentApp: use PrtScn key to capture debug frame (#5032) 2022-01-10 10:28:34 -08:00
jeanlemotan
4511af6f9e Removed code duplication, better style. 2022-01-08 06:17:56 -08:00
jeanlemotan
214e54f2ad Make sure the width/height don't reach zero. 2022-01-08 06:17:56 -08:00
jeanlemotan
2eefbe11ae Fixed cubemap update 2022-01-08 06:17:56 -08:00
Mathias Agopian
74ea3d50c2 Make sure to object are aligned properly when allocated in the renderstream
fix #4991
2022-01-07 10:49:12 -08:00
jeanlemotan
9a8159ab04 Fixed compiler warning (int -> float conversion) 2022-01-07 10:17:04 -08:00
Ben Doherty
2f3aac29da Enable GL_ARB_shading_language_packing in vertex shaders (#5022) 2022-01-06 13:17:31 -08:00
jeanlemotan
9d7f5f593e Added line/triangle strip support (#5017)
* Added line/triangle strip support

* Added strip support for Java and JS
Changed README to indicate strip support for gltf
2022-01-06 13:07:32 -08:00
Ben Doherty
2596273a94 Avoid calling std::string(nullptr) in MockConfig.cpp (#5019) 2022-01-06 10:52:01 -08:00
Benjamin Doherty
210a8c2260 Update Renderer comment 2022-01-06 10:47:54 -08:00
Benjamin Doherty
485ac8704d Bump version to 1.16.0 2022-01-04 11:55:19 -08:00
Benjamin Doherty
dc74540423 Merge branch 'rc/1.15.2' into release 2022-01-04 11:53:02 -08:00
Benjamin Doherty
eaefaf8e59 Release Filament 1.15.2 2022-01-04 11:52:31 -08:00
Benjamin Doherty
96219c22db Update RELEASE_NOTES for 1.15.2 2022-01-04 11:49:50 -08:00
Romain Guy
f3b7048775 Add missing JNI impl (#4959) 2022-01-04 11:43:19 -08:00
Romain Guy
aaed6fb376 Fix rounding math 2022-01-04 11:43:13 -08:00
Ben Doherty
7873e6f5aa Metal: clamp readPixels width and height to texture dimensions (#4994) 2021-12-28 10:27:11 -07:00
abwood
251abf0545 Add support for the glTF extension KHR_materials_emissive_strength (#4975) 2021-12-23 01:32:45 -08:00
Mathias Agopian
b5c4b30ff6 Fix a double release with Android bitmaps callbacks
The version of Texture::setBitmap() that tool an Android bitmap handled
callbacks differently and in certain case caused a "double release" of
the callback object. This didn't actually cause problems though.

We now use the same mechanism used elsewhere (i.e. JniCallback).
2021-12-15 09:18:23 -08:00
Mathias Agopian
eb941a0868 Make normal skinning more efficient
With this change the cofactor matrix is partially precomputed on the 
CPU side.
2021-12-14 10:00:10 -08:00
Mathias Agopian
304ffe0049 Fix skinning calculations
it was incorrect to store bone matrices as quaternions because it is
allowed for these matrices to have a skew component.

We now store the 4x4 matrix -- which is the same amount of data as
before, however we compute the cofactor matrix in the vertex shader when
transforming normals.

fixes #4887
2021-12-14 10:00:10 -08:00
Mathias Agopian
88edbc7df8 Fix a java global reference leak
We were acquiring a reference twice by accident.

Fix #4957
2021-12-13 15:16:48 -08:00
Mathias Agopian
6fa82ea73d Fix typo when setting cubemap faces mip levels. 2021-12-13 15:16:33 -08:00
Mathias Agopian
92e7ff3de7 fix debug checks for compressed textures
Fixes #4941
2021-12-13 15:16:33 -08:00
Romain Guy
35a5d3310f Fix preprocessor test 2021-12-13 13:53:20 -07:00
Romain Guy
2739eb146a Fix rounding math 2021-12-13 10:54:31 -08:00
Romain Guy
59ccc3021f Add missing JNI impl (#4959) 2021-12-13 10:52:47 -08:00
Romain Guy
36e9fa42f4 Fix preprocessor test 2021-12-13 10:42:07 -08:00
Benjamin Doherty
9da79a1d2d Bump version to 1.15.2 2021-12-13 11:08:28 -07:00
Benjamin Doherty
595b355d1b Merge branch 'rc/1.15.1' into release 2021-12-13 11:06:45 -07:00
Benjamin Doherty
8111c50a5a Release Filament 1.15.1 2021-12-13 11:06:12 -07:00
Romain Guy
0e5e7e940c Fix typo in JNI binding 2021-12-10 08:35:16 -08:00
Ben Doherty
9f75d34bb8 Rework color history in preparation for SSR (#4932) 2021-12-08 13:35:54 -08:00
Mathias Agopian
df42213daf update remote ui 2021-12-08 00:25:25 -06:00
Mathias Agopian
b73caceb1f fix libibl on mobile
- the hammersley sequence was completely wrong because of a missing
  highp precision qualifier

- roughness 0 was also wrong because of divide-by-0

Fixes #4668
2021-12-08 00:17:29 -06:00
Mathias Agopian
c91f28b6be fix remote UI when dropping a new .hdr ibl file
- the ibl wasn't updated in internal structures
- the previous ibl was leaked
2021-12-08 00:17:29 -06:00
Mathias Agopian
078de4e422 Add support for basic PCSS 2021-12-08 00:17:12 -06:00
Romain Guy
332d5681e6 Update dependencies 2021-12-07 09:34:28 -08:00
Benjamin Doherty
3a67d769f4 Update RELEASE_NOTES for 1.15.1 2021-12-06 16:54:28 -08:00
Romain Guy
de1281dd9f Be more specific about anisotropyDirection 2021-12-06 15:37:41 -08:00
Benjamin Doherty
f3849a1f57 Update web docs for 1.15.0 2021-12-06 12:59:23 -08:00
Mathias Agopian
3fd63b1b3d use the correct normal when calculating spotlight bias
`vertex_worldNormal` should never be used directly, for one thing it's
not guaranteed to be normalized.
2021-12-06 14:11:45 -06:00
Benjamin Doherty
6fb536a937 Bump version to 1.15.1 2021-12-06 11:17:37 -08:00
Benjamin Doherty
bb460d78d8 Merge branch 'rc/1.15.0' into release 2021-12-06 11:14:00 -08:00
Benjamin Doherty
3a33220dad Release Filament 1.15.0 2021-12-06 11:12:58 -08:00
Mathias Agopian
09a9deafc0 Fade lights out when close to light far plane
the fade takes place over 10% of the light far distance.
2021-12-06 11:45:15 -06:00
Mathias Agopian
4de3470de5 remove 'exponent' from VsmShadowOptions
this is an internal parameter and has no reason to be user settable.
2021-12-03 14:45:59 -06:00
Romain Guy
f03d654862 Update README.md 2021-12-03 09:28:02 -08:00
Mathias Agopian
b8a39c2f3d disable workaround on recent adreno drivers
A workaround for the tile load/store is no longer needed on recent
version of the GLES3.x drivers on qualcomm SoC.
2021-12-03 11:25:38 -06:00
Romain Guy
291b5dcec5 Update README.md 2021-12-02 23:36:57 -08:00
Mathias Agopian
087f29c6c9 Added support for DPCF 2021-12-03 01:20:50 -06:00
Mathias Agopian
aac3ac579c add global temporal noise uniform when TAA is enabled
this can be used to easily add temporal noise to "things" when
TAA is also enabled.
2021-12-03 01:20:50 -06:00
Benjamin Doherty
838835a715 Update RELEASE_NOTES for 1.15.0 2021-12-02 11:52:04 -08:00
Romain Guy
c275f61aeb Add missing destroy method (#4921) 2021-12-02 08:53:55 -08:00
MasTraER
f297948216 Expose Engine::destroy(SkinningBuffer*) (#4919) 2021-12-02 08:41:10 -08:00
Ben Doherty
dbe1386785 Fix live wallpaper sample with Android 12+ (#4917) 2021-12-01 12:29:11 -08:00
Joel Winarske
687f4aff13 Flags to support embedded Linux (#4911)
- FILAMENT_SKIP_SDL2=ON is used to  skip dependencies of sdl2 and sdl2 CMake

- FILAMENT_LINUX_IS_MOBILE is used for Mobile build

Signed-off-by: Joel Winarske <joel.winarske@gmail.com>
2021-12-01 08:31:06 -08:00
Romain Guy
dd4853bcc5 Replace ANDROID with __ANDROID__ (#4909)
__ANDROID__ is always set by the toolchain and less likely to cause
conflicts than ANDROID. This change also removes the -DANDROID flag
we set ourselves in our toolchain CMake files since we don't need
it anymore.
2021-11-30 16:27:56 -08:00
Benjamin Doherty
ffbfc13530 Fix RELEASE_NOTES 2021-11-30 15:52:17 -08:00
Ben Doherty
2aa160a98c Fix release build crash in gltf_viewer (#4908) 2021-11-30 12:29:45 -08:00
Ben Doherty
477a3a8771 Pin web docs Filament version (#4907) 2021-11-30 12:05:40 -08:00
Romain Guy
63acd53e23 Use __ANDROID__ instead of ANDROID 2021-11-30 11:15:49 -08:00
Romain Guy
fcd2d0457b Workaround for a build system issue 2021-11-30 11:15:42 -08:00
Romain Guy
c0e8686297 Use __ANDROID__ instead of ANDROID 2021-11-30 11:14:35 -08:00
Romain Guy
01f18caf53 Workaround for a build system issue 2021-11-30 10:05:32 -08:00
Joel Winarske
56971520a2 Fix typo and remove extraneous return
Signed-off-by: Joel Winarske <joel.winarske@gmail.com>
2021-11-30 11:18:57 -06:00
Joel Winarske
f5e38b1198 Requested changes
- remove const

- remove egl references in wayland struct

Signed-off-by: Joel Winarske <joel.winarske@gmail.com>
2021-11-30 11:18:57 -06:00
Joel Winarske
984ef2a089 Remove un-implemented test case
Signed-off-by: Joel Winarske <joel.winarske@gmail.com>
2021-11-30 11:18:57 -06:00
Joel Winarske
ad960c73b6 Remove traces of Wayland EGL
Signed-off-by: Joel Winarske <joel.winarske@gmail.com>
2021-11-30 11:18:57 -06:00
Joel Winarske
0dcc631aa8 Backout Wayland EGL backend
Signed-off-by: Joel Winarske <joel.winarske@gmail.com>
2021-11-30 11:18:57 -06:00
Joel Winarske
af9b670cfd Wayland 2021-11-30 11:18:57 -06:00
Benjamin Doherty
58fc26461b Bump version to 1.15.0 2021-11-29 14:08:28 -08:00
Benjamin Doherty
fd82f6b04e Merge branch 'rc/1.14.2' into release 2021-11-29 14:07:03 -08:00
Benjamin Doherty
519ae4d143 Release Filament 1.14.2 2021-11-29 14:05:55 -08:00
Mathias Agopian
8d72869437 Fix spotlight normal bias calculation (#4844)
The calculation was completely wrong due to several typos more or less
canceling each other, that led to some misunderstanding!
2021-11-29 14:05:40 -08:00
Romain Guy
2cbacb532a Cache calls to Enum.values() (#4902)
Each call to .values() allocates a new array. Let's cache them once
and for all to avoid unncessary allocations.
2021-11-29 11:35:58 -08:00
Romain Guy
1da2bf2f7a Update WebGl demos 2021-11-29 11:29:22 -08:00
Benjamin Doherty
cef3200533 Add additional RELEASE_NOTES for 1.14.2 2021-11-29 10:21:56 -08:00
Ben Doherty
634500c398 Fix, avoid divide-by-zero inside makeBone (#4889) 2021-11-24 16:29:33 -08:00
Ben Doherty
802bc7a5dc Fix, avoid divide-by-zero inside makeBone (#4889) 2021-11-24 16:28:44 -08:00
Romain Guy
8875806c5d Use locale-independent string->float conversion (#4885)
* Use locale-independent string->float conversion

strtof and friends are locale aware and won't parse decimal numbers
with a period ("12.6" for instance) in locales that use another
character for the decimal period ("," in French for instance).

This change introduces a new function called strtof_c that forces
the use of a specific locale (called "C") to make sure we always
parse floats in the desired "C" format ("12.6").

With C++17 we should be able to use std::from_chars but this API
is not implemented in clang for floats at the moment.

* Fix Linux
2021-11-23 12:32:54 -08:00
Benjamin Doherty
c9df807f1f Update backend-test project with filamat dependency 2021-11-23 12:14:05 -08:00
Ben Doherty
b3e294ac54 Fix Metal depth comparison initialization (#4886) 2021-11-23 12:09:43 -08:00
Ben Doherty
3feef4e84b Fix Metal depth comparison initialization (#4886) 2021-11-23 12:00:58 -08:00
Benjamin Doherty
2bf7535ad0 Update RELEASE_NOTES for 1.14.2 2021-11-22 10:16:00 -08:00
Benjamin Doherty
3315f75de9 Bump version to 1.14.2 2021-11-22 10:12:44 -08:00
Benjamin Doherty
bbe7dbfa92 Merge branch 'rc/1.14.1' into release 2021-11-22 10:11:06 -08:00
Benjamin Doherty
15001524bd Release Filament 1.14.1 2021-11-22 10:10:35 -08:00
Romain Guy
c1713e7501 Export activities on Android 12+ 2021-11-22 09:25:13 -08:00
Romain Guy
0181584735 Update build tools (#4866)
* Update build tools

SDK API level 31
NDK 23
Kotlin 1.6

* Preserve tool suffix for Windows
2021-11-17 13:19:45 -08:00
Ben Doherty
df06e8dc41 Fix material compilation error with device vertex domain (#4865)
A recent refactor was causing the following error when the vertex domain
was set to `device`:
```
ERROR: main.vs:23: 'material' : undeclared identifier
ERROR: main.vs:23: 'materialVertex' : no matching overloaded function found
```
2021-11-17 12:04:41 -08:00
Benjamin Doherty
5697922a65 Update RELEASE_NOTES for 1.14.1 2021-11-17 12:04:26 -08:00
Ben Doherty
4da83df2b9 Fix material compilation error with device vertex domain (#4865)
A recent refactor was causing the following error when the vertex domain
was set to `device`:
```
ERROR: main.vs:23: 'material' : undeclared identifier
ERROR: main.vs:23: 'materialVertex' : no matching overloaded function found
```
2021-11-17 12:03:55 -08:00
Ben Doherty
8f156d6588 Android: re-enable VSM cascade fix (#4863) 2021-11-17 10:19:09 -08:00
Ben Doherty
b0ce077ace Android: re-enable VSM cascade fix (#4863) 2021-11-17 10:14:47 -08:00
Ben Doherty
9d29d2e32c Update spirv-tools to v2021.4 (#4862) 2021-11-16 17:13:42 -08:00
Ben Doherty
a29b438161 Update glslang to eb92526 (#4861) 2021-11-16 13:26:58 -08:00
Ben Doherty
50a042bb16 Metal: fix validation error when rendering to RT without depth (#4860) 2021-11-16 11:50:23 -08:00
Benjamin Doherty
cec0871c11 Bump version to 1.14.1 2021-11-15 10:09:45 -08:00
Benjamin Doherty
41a809368b Merge branch 'rc/1.14.0' into release 2021-11-15 10:07:56 -08:00
Benjamin Doherty
f690015a88 Release Filament 1.14.0 2021-11-15 10:06:45 -08:00
Ben Doherty
342deb5a64 speed up under ThreadSanitizer (#4842) 2021-11-12 09:52:58 -08:00
Mathias Agopian
fdc480ff6e Gaussian blur is now applied only on the needed channels
The gaussian blur code was always processing 3 channels no matter the
source or destination. We now have 4 versions for all possible cases.
2021-11-11 23:35:10 -08:00
Mathias Agopian
378b7cd4dd rearrange EVSM code to make it easy to test full EVSM
We're currently only using the positive layer of EVSM which works
work small blurs and anti-aliasing. This just rearranges the code to
make it easy to test the full formulation.
2021-11-11 23:35:10 -08:00
Mathias Agopian
f779fc7a0e move the shadowmap position computation inside shadow()
This is possible because, in fact, we know if we're dealing with a
spot or directional light when we invoke shadow(). So a conditional
inside it is resolved at compile time.

This will allow more flexibility in the future. Also now the shadow()
function only needs the shadow index and cascade -- which is more
future proof (e.g. if we want to handle more than one directional
shadow or spot lights with cascades).
2021-11-11 23:35:10 -08:00
Mathias Agopian
fe11f495d6 simplify how we compute the shadow position
this effectively undoes a recent change, where we had a method for
spot lights and one for the directional light. instead, we can
calculate the bias at the correct Z on the caller side -- which is
needed only for spotlights.
2021-11-11 23:35:10 -08:00
Mathias Agopian
265876c849 store the texel size in world-space in the spot shadow structure 2021-11-11 23:35:10 -08:00
Mathias Agopian
c9c52518c0 repair transparent shadows 2021-11-10 19:48:25 -08:00
Mathias Agopian
96c9ac6f8b fix point-lights which broke recently.
The faulty commit was:

commit 23dab0a013
Author: Mathias Agopian <mathias@google.com>
Date:   Fri Oct 29 12:03:14 2021 -0700

    Fix very narrow spotlight lighting and other minor issues
2021-11-10 15:22:38 -08:00
Ben Doherty
bdeb30a847 Use workflow_dispatch instead of repository_dispatch (#4834) 2021-11-10 13:38:58 -08:00
Romain Guy
ea53eb9290 Skip task incompatible with configuration caching (#4831) 2021-11-09 15:56:00 -08:00
Benjamin Doherty
05875057c9 Update RELEASE_NOTES for 1.14.0 2021-11-09 15:51:13 -08:00
Romain Guy
d67210155b Skip task incompatible with configuration caching (#4831) 2021-11-09 15:01:02 -08:00
Mathias Agopian
ae92c50cee more robust GL compiler error parsing 2021-11-09 14:59:50 -08:00
Mathias Agopian
43429dc0ec remove depth_main.vs from source tree 2021-11-09 12:34:19 -08:00
Mathias Agopian
04cf92a27f Remove all "Shadow Receiver Plane Depth Bias" related code
Shadow Receiver Plane Depth Bias is only needed when using large PCF
filters, which we are no longer doing. Large filter kernels are now 
supported through VSM sampling.
2021-11-09 12:31:43 -08:00
Mathias Agopian
57a57f50f6 most methods can be static in CodeGenerator 2021-11-09 12:31:28 -08:00
Mathias Agopian
5e5a75e6c5 fix bug with MASKED blending mode introduced in previous PR 2021-11-09 10:27:52 -08:00
Mathias Agopian
109c86aaf7 get rid of depth_main.vs
It's functionality is now handled in main.vs which, hopefully will be
less error prone.
2021-11-09 09:54:50 -08:00
Mathias Agopian
10e7e7727a filamat cleanup
This changes how we select the "optimized depth vertex shader", but
this shouldn't change the current behavior.

We now select the "optimized depth vertex shader" if and only if the
user code is empty. In that case, we can safely assume we can remove
all the code that's not necessary for the depth, since it is all
controlled by filament.
2021-11-09 09:54:50 -08:00
Mathias Agopian
a39775050a workaround a IDE (CLion) code parsing bug
It looks like some parts of CLion don't like MaterialDomain because
it exists as an enum value
2021-11-09 09:54:50 -08:00
Benjamin Doherty
44125926d1 Disable configuration-cache 2021-11-08 17:05:34 -08:00
Benjamin Doherty
60734349de Bump version to 1.14.0 2021-11-08 11:52:50 -08:00
Benjamin Doherty
fbfd5ec0ec Merge branch 'rc/1.13.0' into release 2021-11-08 11:50:19 -08:00
Benjamin Doherty
157c0264af Release Filament 1.13.0 2021-11-08 11:49:39 -08:00
Mathias Agopian
9bacfdb390 simplify shadowing code
- remove PCF "low" quality, we only use "HARD" now, when using PCF.
  Higher quality levels are achieved by using VSM.

- added a version of PCF that doesn't use a shadowSampler for future
  use.
2021-11-04 23:01:08 -07:00
Mathias Agopian
f9aaf5c42e Fix normal bias for spotlights.
The normal bias is now computed correctly, this requires to compute
the z in lightspace in the shader.
Note that this would not work as well if we used LISPSM, but we'll
cross that bridge when we get there.
2021-11-04 14:56:00 -07:00
Ben Doherty
a74a95cc65 Call VirtualMachineEnv::JNI_OnLoad for non-Android Java builds (better fix) (#4779) 2021-11-04 13:28:17 -07:00
Ben Doherty
21db695e79 Call VirtualMachineEnv::JNI_OnLoad for non-Android Java builds (better fix) (#4779) 2021-11-04 13:28:08 -07:00
Mathias Agopian
cf917f1093 Add a (crude) way to have structs in our UBOs
The struct must be declared in common_type.fs, so custom
structures are not supported.
2021-11-04 12:43:50 -07:00
Ben Doherty
a8d3a61c25 Enforce readPixels is called within frame (#4802) 2021-11-03 10:59:25 -07:00
Mathias Agopian
80f13a8149 fix typo in comments 2021-11-03 10:54:05 -07:00
Mathias Agopian
e172f3a67f Fix java shadow biases + minor cleanups
- constant bias and normal bias default values in java didn't match
  C++ or the documentation

- stable shadows were enabled by default in java

- polygon offset biases were missing from the java API

- document and don't apply polygon offset to VSM

- remove unused code
2021-11-03 00:20:48 -07:00
Mathias Agopian
c382c0a9cc Tighten spotlights near/far further
We now cull the shadow casters before computing the near/far plane
for spotlights -- we can do that because we know the light's frustum.
So only these casters that contribute to the shadow are accounted for
when calculating the near/far plane.

This PR also include more cleanup and simplifications.
2021-11-02 14:05:09 -07:00
Benjamin Doherty
bc0ea16ff0 Update RELEASE_NOTES for 1.13.0 2021-11-02 13:15:53 -07:00
Mathias Agopian
b2dc8aa84c Fix typo that broke the directional shadowmap 2021-11-02 13:11:44 -07:00
Mathias Agopian
78b29fe967 Fix typo that broke the directional shadowmap 2021-11-01 16:41:30 -07:00
Benjamin Doherty
9987e8b6ab Bump version to 1.13.0 2021-11-01 14:59:11 -07:00
Benjamin Doherty
0d9bdcc008 Merge branch 'rc/1.12.11' into release 2021-11-01 14:55:58 -07:00
Benjamin Doherty
81fa33abeb Release Filament 1.12.11 2021-11-01 14:55:54 -07:00
Mathias Agopian
af7f87e19b make sure the near plane for spot shadows is not negative 2021-11-01 14:19:13 -07:00
Mathias Agopian
3073b03d56 Improve computation of spotlight near/far plane
Near/far plane is now computed dynamically, this significantly
improves the shadowmap depth resolution.

Quite a bit of refactoring was necessary to get all the right data 
in the right place, in particular SceneInfo is now passed around for
both directional and spot shadows.
2021-10-29 18:57:26 -07:00
Mathias Agopian
23dab0a013 Fix very narrow spotlight lighting and other minor issues
The froxel code was failing when a spotlight cone was too narrow. This
is fixed here by never using a cone smaller than 0.5 degrees during
forxelization. 

Additionally we now silently clamp the cone angles to 0.5 degrees at
the API level because, the falloff was also failing due to floating
point precision in the shader.

Finally, we clamp the inner cone upper value to the outer cone's
instead of the other way around. i.e. the outer cone defines the 
spotlight while the inner cone just controls the falloff.
2021-10-29 15:08:05 -07:00
Mathias Agopian
fd68144ba2 fix depth precision with VSM
When calculating the linear depth for VSM, we were using the whole
range between 0 and the far plane, the near plane wasn't taken into
account.

This can be a problem is the light is very far, but it's near plane is
closer to the camera/scene, in this case the depth precision wasn't
used optimally.

Note that we don't hit this problem currently, because the directional
light is constructed such that its origin is at the near plane, and the
spotlights have a fixed near plane (which is a problem and will be 
fixed at a later time).
2021-10-29 12:03:41 -07:00
Mathias Agopian
51e92cd142 Fix spotlight direction and falloff
Direction and falloff were recently changed to fp16 int the shader,
which is not enough (far from it) when a spotlight is over 100m away.
2021-10-28 21:59:01 -07:00
Mathias Agopian
50f33f7196 fix some warnings and typos 2021-10-28 21:58:45 -07:00
Benjamin Doherty
b5c634045e Update RELEASE_NOTES for 1.12.11 2021-10-28 16:13:50 -07:00
Ben Doherty
1f05531d53 Call VirtualMachineEnv::JNI_OnLoad for non-Android Java builds (better fix) (#4779) 2021-10-28 16:02:23 -07:00
Benjamin Doherty
88f382f0e3 Revert "refactor colorgrading materials"
This reverts commit fb86a77cf8.
2021-10-28 15:56:50 -07:00
Benjamin Doherty
3e59925900 Remove problematic configuration-cache setting for release build 2021-10-28 15:56:26 -07:00
Mathias Agopian
1182d30fb9 MSAA VSMs seem to now work on Qualcomm h/w
The bug that prevented them to work has been worked around, but we 
don't know when or how. The original bug still exists as demonstrated
by our standalone test apk.

For now, we reenable MSAA VSM on Adreno.
2021-10-26 16:06:20 -07:00
Romain Guy
095179eeb3 Enabled Gradle configuration caching and rename properties (#4769)
* Fix configurationg caching problems

* Enable Gradle configuration caching

* Update BUILDING.md

* Update RELEASE_NOTES.md

Co-authored-by: Mathias Agopian <mathias@google.com>

Co-authored-by: Benjamin Doherty <bendoherty@google.com>
2021-10-26 12:47:35 -07:00
Romain Guy
69b48eaadb Fix erroenous warning 2021-10-26 12:05:49 -07:00
Timo Röhling
4031c6f0d3 Simplify devendoring (#4765)
* Perform sanity check when combining static libraries

This is a small modification that simplifies Debian packaging when one
or more vendored dependencies are replaced by system shared libraries
and no longer need to be combined with a Filament library.

* Verify vendoring before including license texts

This is another small modification to simplify Debian packaging when one
or more vendored dependencies are removed and replaced by system
libraries, so they no longer need to be considered when compiling the
license texts.
2021-10-26 11:31:35 -07:00
Mathias Agopian
7a22f7dfc5 move some VSM computations into the vertex shader 2021-10-26 11:26:21 -07:00
Mathias Agopian
728ebf5023 cleanup shadowing shader code
- remove PCF MEDIUM and HIGH quality -- these were never used in
practice, and "quality" really meant "blurriness", now we have VSM
for doing that with much more control and more efficiently.

PCF_HARD is now the default. PCF_LOW is still available at compile time
for now. It shouldn't be needed though because VSM can achieve the same.

Moved the divide-by-w of light space into the shadow() method -- which
known if it should be done or not.
2021-10-26 11:26:21 -07:00
Timo Röhling
62476d2f06 Fix compatibility with libstdc++ (#4763)
The codebase needs only a few additional standard #includes to compile
against libstdc++ on Linux; presumably those headers are implicitly
included with MSVC's and Clang's standard C++ library, but even if
libstdc++ compatibility is not a goal, it is advisable to have them
included directly.
2021-10-26 11:07:39 -07:00
Benjamin Doherty
ea404f8d4f Remove problematic configuration-cache setting for release build 2021-10-26 10:09:51 -07:00
Benjamin Doherty
602a550d93 Bump version to 1.12.11 2021-10-25 12:30:37 -07:00
Benjamin Doherty
12abbe2d23 Merge branch 'rc/1.12.10' into release 2021-10-25 11:06:18 -07:00
Benjamin Doherty
5fea428243 Release Filament 1.12.10 2021-10-25 11:06:12 -07:00
Benjamin Doherty
fb0ee97588 Update RELEASE_NOTES for 1.12.10 2021-10-25 11:00:06 -07:00
Ben Doherty
56ef48c9c3 Fix, call VirtualMachineEnv::JNI_OnLoad for non-Android Java builds (#4749) 2021-10-25 10:39:24 -07:00
Benjamin Doherty
47c3dd3dd1 Revert "refactor colorgrading materials"
This reverts commit fb86a77cf8.
2021-10-25 10:37:52 -07:00
clayly
9a3c9ccbf3 android-samples-gradle-plugin-id (#4740) 2021-10-24 11:12:15 -07:00
Ben Doherty
ef4dfcecd6 Metal: support framebuffer fetch on M1 devices (#4735) 2021-10-21 11:27:05 -07:00
Ben Doherty
5943382d23 iOS: avoid precision issues with CACurrentMediaTime (#4753) 2021-10-21 11:13:51 -07:00
Benjamin Doherty
c181648bfa Bump version to 1.12.10 2021-10-20 12:15:51 -07:00
Benjamin Doherty
1dcf347b87 Release Filament 1.12.9 2021-10-20 12:11:46 -07:00
Ben Doherty
47714007f7 Fix VirtualMachineEnv.cpp with older JNI versions (#4752) 2021-10-20 11:18:03 -07:00
Mathias Agopian
54277572d2 code health: cleanup FrameInfo and FrameSkipper a bit
in particular add a terminate() method to FrameSkipper instead of
destroying driver objects in the destructor -- this matches all other
objects.

also remove dependency on FEngine which wasn't needed.
2021-10-18 18:41:59 -07:00
Mathias Agopian
52f2c0e107 don't use static initialization when not needed
static init/destruction is always dangerous
2021-10-18 15:36:17 -07:00
Mathias Agopian
59abc8cc20 use NEAREST filtering for the final blit
the final blit, when used, is never upscaling, so always use the 
NEAREST filter.
2021-10-18 12:18:57 -07:00
Mathias Agopian
e15796b348 Rewrite controller for dynamic resolution scaling
- move the control code out of FrameInfo and into
  View itself. FrameInfo now just gathers information about the 
  frames instead of also doing part of the control.

- the control code has been refactored into a more formal PIDController.

- a few bugs were fixed in the control loop and default parameters
  tuned. 


The control loop itself now outputs a relative scale factor instead
of an absolute one. The relative scale factor seems easier to
control and is less jittery, and doesn't have to rely on the "integral"
term of the PID.

It's possible that more tuning is needed, but the scaling is now 
more stable.
2021-10-18 10:06:44 -07:00
Mathias Agopian
1711eaa4d6 Minor improvements to DebugRegistry
- remove getProperties() we'll put it back if we need it some day

- use unordered_map because it generates less code than robin_map and
  here performance is not critical
2021-10-18 10:06:44 -07:00
Mathias Agopian
acbd6a5ca8 Improve dynamic resolution scaling
- defaults to 31 history points instead of 3, this gives a much better 
  estimate of the frame rate.

- make sure the calculations work for any definition of our internal
  duration<> (it's useful to use milliseconds when dealing with
  refresh periods).

- don't round to 8 pixels if the scale factor is exactly 1

- fix a few comments and warnings
2021-10-18 10:06:44 -07:00
Romain Guy
775090fdda Re-fix tests 2021-10-15 17:30:06 -07:00
Romain Guy
0915b86927 Fix tests 2021-10-15 16:23:45 -07:00
BStringhamVRSK
c10f7b01f4 Fixes normal map issues in mipgen and exposes a couple of SurfaceOrientation functions for Web
* mipgen: Linearized PNG bitmaps (such as normal maps) no longer perform gamma transform on read.

* mipgen: Using "-k normals" argument now works for all file types, not just KTX

* Web: Exposed SurfaceOrientation functions getQuatsHalf4() and getQuatsFloat()
2021-10-15 14:23:41 -07:00
Mathias Agopian
84142ac506 move platform related files into a platforms directory
this is just to improve source code readability.
2021-10-14 22:48:16 -07:00
Mathias Agopian
ff190847a1 ExternalStreamManagerAndroid actually depends on GLES
Since ExternalStreamManagerAndroid depends on GLES, move it to the 
opengl directory.
2021-10-14 22:48:16 -07:00
Mathias Agopian
3ceec28189 added a way to check for adreno driver version
not used yet, but good too have.
2021-10-14 19:35:17 -07:00
Romain Guy
481038152f Cleanup of Android projects (#4730) 2021-10-13 18:17:12 -07:00
Rupert Rawnsley
60bd72730d ASTC texture enum missing in JNI interface 2021-10-13 10:18:54 -07:00
1485 changed files with 186190 additions and 241863 deletions

View File

@@ -29,7 +29,7 @@ jobs:
build-windows:
name: build-windows
runs-on: windows-latest
runs-on: windows-2019
steps:
- uses: actions/checkout@v2.0.0

View File

@@ -1,14 +1,25 @@
name: Release
# This Workflow can be triggered two ways:
# 1. A GitHub release is created (using the GitHub web UI). This triggers all of the platforms to build and upload assets.
# 2. A repository_dispatch API event is sent. This triggers a build for only the platform specified in the dispatch event.
# 1. A GitHub release is created (using the GitHub web UI). This triggers all of the platforms to
# build and upload assets.
# 2. A workflow_dispatch event is triggered from the GitHub web UI. This triggers a build for only
# the platform specified in the dispatch event.
env:
RELEASE_TAG: ${{ github.event.client_payload.release_tag }}
RELEASE_TAG: ${{ github.event.inputs.release_tag }}
on:
repository_dispatch:
workflow_dispatch:
inputs:
platform:
description: 'Platform to build (desktop, web, android, ios, windows)'
required: true
default: 'desktop'
release_tag:
description: 'Release tag to build (e.g., v1.13.0)'
required: true
default: 'v1.13.0'
release:
types: [created]
@@ -16,7 +27,7 @@ jobs:
build-desktop:
name: build-desktop
runs-on: ${{ matrix.os }}
if: github.event_name == 'release' || github.event.client_payload.platform == 'desktop'
if: github.event_name == 'release' || github.event.inputs.platform == 'desktop'
strategy:
matrix:
@@ -39,8 +50,7 @@ jobs:
cd build/$WORKFLOW_OS && printf "y" | ./build.sh release
- name: Upload release assets
run: |
pip3 install setuptools
pip3 install PyGithub
xargs -L 1 sudo pip3 install < build/common/requirements.txt
if [ -f out/filament-release-darwin.tgz ]; then mv out/filament-release-darwin.tgz out/filament-${TAG}-mac.tgz; fi;
if [ -f out/filament-release-linux.tgz ]; then mv out/filament-release-linux.tgz out/filament-${TAG}-linux.tgz; fi;
python3 build/common/upload-assets.py ${TAG} out/*.tgz
@@ -51,7 +61,7 @@ jobs:
build-web:
name: build-web
runs-on: macos-latest
if: github.event_name == 'release' || github.event.client_payload.platform == 'web'
if: github.event_name == 'release' || github.event.inputs.platform == 'web'
steps:
- name: Decide Git ref
@@ -69,8 +79,7 @@ jobs:
cd build/web && printf "y" | ./build.sh release
- name: Upload release assets
run: |
pip3 install setuptools
pip3 install PyGithub
xargs -L 1 sudo pip3 install < build/common/requirements.txt
mv out/filament-release-web.tgz out/filament-${TAG}-web.tgz
python3 build/common/upload-assets.py ${TAG} out/*.tgz
env:
@@ -80,7 +89,7 @@ jobs:
build-android:
name: build-android
runs-on: macos-latest
if: github.event_name == 'release' || github.event.client_payload.platform == 'android'
if: github.event_name == 'release' || github.event.inputs.platform == 'android'
steps:
- name: Decide Git ref
@@ -112,15 +121,13 @@ jobs:
APK_KEYSTORE_PASS: ${{ secrets.APK_KEYSTORE_PASS }}
- name: Upload release assets
run: |
pip3 install setuptools
pip3 install PyGithub
xargs -L 1 sudo pip3 install < build/common/requirements.txt
mv out/filament-android-release.aar out/filament-${TAG}-android.aar
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
mv out/filament-utils-android-lite-release.aar out/filament-utils-${TAG}-lite-android.aar
python3 build/common/upload-assets.py ${TAG} out/*.aar out/*.apk
env:
TAG: ${{ steps.git_ref.outputs.tag }}
@@ -129,7 +136,7 @@ jobs:
build-ios:
name: build-ios
runs-on: macos-latest
if: github.event_name == 'release' || github.event.client_payload.platform == 'ios'
if: github.event_name == 'release' || github.event.inputs.platform == 'ios'
steps:
- name: Decide Git ref
@@ -147,8 +154,7 @@ jobs:
cd build/ios && printf "y" | ./build.sh release
- name: Upload release assets
run: |
pip3 install setuptools
pip3 install PyGithub
xargs -L 1 sudo pip3 install < build/common/requirements.txt
mv out/filament-release-ios.tgz out/filament-${TAG}-ios.tgz
python3 build/common/upload-assets.py ${TAG} out/*.tgz
env:
@@ -157,8 +163,8 @@ jobs:
build-windows:
name: build-windows
runs-on: windows-latest
if: github.event_name == 'release' || github.event.client_payload.platform == 'windows'
runs-on: windows-2019
if: github.event_name == 'release' || github.event.inputs.platform == 'windows'
steps:
- name: Decide Git ref

View File

@@ -10,7 +10,7 @@ on:
jobs:
build-windows:
name: build-windows
runs-on: windows-latest
runs-on: windows-2019
steps:
- uses: actions/checkout@v2.0.0

View File

@@ -15,7 +15,7 @@ To build Filament for Android you must also install the following:
- Android Studio Arctic Fox or more recent
- Android SDK
- Android NDK "side-by-side" 22.1 or higher
- Android NDK "side-by-side" 23.1 or higher
### Environment variables
@@ -291,11 +291,11 @@ Alternatively you can build the AAR from the command line by executing the follo
`android/` directory:
```
$ ./gradlew -Pfilament_dist_dir=../../out/android-release/filament assembleRelease
$ ./gradlew -Pcom.google.android.filament.dist-dir=../../out/android-release/filament assembleRelease
```
The `-Pfilament_dist_dir` can be used to specify a different installation directory (it must match
the CMake install prefix used in the previous steps).
The `-Pcom.google.android.filament.dist-dir` can be used to specify a different installation
directory (it must match the CMake install prefix used in the previous steps).
#### Using Filament's AAR
@@ -349,7 +349,7 @@ same version that our continuous builds use.
```
cd <your chosen parent folder for the emscripten SDK>
curl -L https://github.com/emscripten-core/emsdk/archive/2.0.23.zip > emsdk.zip
curl -L https://github.com/emscripten-core/emsdk/archive/refs/tags/3.1.5.zip > emsdk.zip
unzip emsdk.zip ; mv emsdk-* emsdk ; cd emsdk
python ./emsdk.py install latest
python ./emsdk.py activate latest

View File

@@ -23,6 +23,12 @@ option(FILAMENT_SUPPORTS_XCB "Include XCB support in Linux builds" ON)
option(FILAMENT_SUPPORTS_XLIB "Include XLIB support in Linux builds" ON)
option(FILAMENT_SUPPORTS_WAYLAND "Include Wayland support in Linux builds" OFF)
option(FILAMENT_SKIP_SDL2 "Skip dependencies of SDL2, and SDL2" OFF)
option(FILAMENT_LINUX_IS_MOBILE "Treat Linux as Mobile" OFF)
set(FILAMENT_NDK_VERSION "" CACHE STRING
"Android NDK version or version prefix to be used when building for Android."
)
@@ -94,20 +100,34 @@ if (UNIX AND NOT APPLE AND NOT ANDROID AND NOT WEBGL)
endif()
if (LINUX)
if (FILAMENT_SUPPORTS_XCB)
add_definitions(-DFILAMENT_SUPPORTS_XCB)
endif()
if (FILAMENT_SUPPORTS_WAYLAND)
add_definitions(-DFILAMENT_SUPPORTS_WAYLAND)
set(FILAMENT_SUPPORTS_X11 FALSE)
else ()
if (FILAMENT_SUPPORTS_XCB)
add_definitions(-DFILAMENT_SUPPORTS_XCB)
endif()
if (FILAMENT_SUPPORTS_XLIB)
add_definitions(-DFILAMENT_SUPPORTS_XLIB)
if (FILAMENT_SUPPORTS_XLIB)
add_definitions(-DFILAMENT_SUPPORTS_XLIB)
endif()
if (FILAMENT_SUPPORTS_XCB OR FILAMENT_SUPORTS_XLIB)
add_definitions(-DFILAMENT_SUPPORTS_X11)
set(FILAMENT_SUPPORTS_X11 TRUE)
endif()
endif()
endif()
if (ANDROID OR WEBGL OR IOS)
if (ANDROID OR WEBGL OR IOS OR FILAMENT_LINUX_IS_MOBILE)
set(IS_MOBILE_TARGET TRUE)
endif()
if (NOT ANDROID AND NOT WEBGL AND NOT IOS)
if (ANDROID)
add_definitions(-D__ANDROID_UNAVAILABLE_SYMBOLS_ARE_WEAK__)
endif()
if (NOT ANDROID AND NOT WEBGL AND NOT IOS AND NOT FILAMENT_LINUX_IS_MOBILE)
set(IS_HOST_PLATFORM TRUE)
endif()
@@ -248,7 +268,7 @@ if (MSVC)
set(CXX_STANDARD "/std:c++latest")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CXX_STANDARD} /W0 /Zc:__cplusplus")
else()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CXX_STANDARD} -fstrict-aliasing -Wno-unknown-pragmas -Wno-unused-function")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CXX_STANDARD} -fstrict-aliasing -Wno-unknown-pragmas -Wno-unused-function -Wno-deprecated-declarations")
endif()
if (FILAMENT_USE_EXTERNAL_GLES3)
@@ -279,7 +299,7 @@ if (LINUX)
endif()
if (ANDROID)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -Werror=unguarded-availability")
endif()
if (CYGWIN)
@@ -502,11 +522,15 @@ function(list_licenses OUTPUT MODULES)
foreach(module ${_MODULES})
set(license_path "../../third_party/${module}/LICENSE")
get_filename_component(fullname "${license_path}" ABSOLUTE)
string(APPEND CONTENT "${STR_OPENER}License and copyrights for ${module}:\n${STR_CLOSER},\n")
file(READ ${license_path} license_long)
string(REPLACE "\n" "${STR_CLOSER},\n${STR_OPENER}" license ${license_long})
string(APPEND CONTENT ${STR_OPENER}${license}\n${STR_CLOSER},)
string(APPEND CONTENT "\n\n")
if(EXISTS ${fullname})
string(APPEND CONTENT "${STR_OPENER}License and copyrights for ${module}:\n${STR_CLOSER},\n")
file(READ ${license_path} license_long)
string(REPLACE "\n" "${STR_CLOSER},\n${STR_OPENER}" license ${license_long})
string(APPEND CONTENT ${STR_OPENER}${license}\n${STR_CLOSER},)
string(APPEND CONTENT "\n\n")
else()
message(AUTHOR_WARNING "${license_path} not found. You can ignore this warning if you have devendored ${module}.")
endif()
endforeach()
configure_file(${FILAMENT}/build/licenses.inc.in ${OUTPUT})
endfunction(list_licenses)
@@ -522,7 +546,12 @@ function(combine_static_libs TARGET OUTPUT DEPS)
# Loop through the dependent libraries and query their location on disk.
set(DEPS_FILES )
foreach(DEPENDENCY ${DEPS})
list(APPEND DEPS_FILES "$<TARGET_FILE:${DEPENDENCY}>")
if(TARGET ${DEPENDENCY})
get_property(dep_type TARGET ${DEPENDENCY} PROPERTY TYPE)
if(dep_type STREQUAL "STATIC_LIBRARY")
list(APPEND DEPS_FILES "$<TARGET_FILE:${DEPENDENCY}>")
endif()
endif()
endforeach()
add_custom_command(
@@ -555,12 +584,14 @@ if (FILAMENT_USE_SWIFTSHADER)
find_library(SWIFTSHADER_VK NAMES vk_swiftshader HINTS "$ENV{SWIFTSHADER_LD_LIBRARY_PATH}")
message(STATUS "Found SwiftShader VK library in: ${SWIFTSHADER_VK}.")
add_definitions(-DFILAMENT_VKLIBRARY_PATH=\"${SWIFTSHADER_VK}\")
elseif (FILAMENT_SUPPORTS_VULKAN AND APPLE)
find_library(Vulkan_LIBRARY NAMES vulkan HINTS "$ENV{VULKAN_SDK}/lib" "$ENV{VULKAN_SDK}/macOS/lib")
if (Vulkan_LIBRARY)
set(Vulkan_FOUND ON)
message(STATUS "Found Vulkan library in SDK: ${Vulkan_LIBRARY}.")
add_definitions(-DFILAMENT_VKLIBRARY_PATH=\"${Vulkan_LIBRARY}\")
elseif (FILAMENT_SUPPORTS_VULKAN)
if (APPLE OR FILAMENT_LINUX_IS_MOBILE)
find_library(Vulkan_LIBRARY NAMES vulkan HINTS "$ENV{VULKAN_SDK}/lib" "$ENV{VULKAN_SDK}/macOS/lib")
if (Vulkan_LIBRARY)
set(Vulkan_FOUND ON)
message(STATUS "Found Vulkan library in SDK: ${Vulkan_LIBRARY}.")
add_definitions(-DFILAMENT_VKLIBRARY_PATH=\"${Vulkan_LIBRARY}\")
endif()
endif()
endif()

View File

@@ -31,7 +31,7 @@ repositories {
}
dependencies {
implementation 'com.google.android.filament:filament-android:1.12.9'
implementation 'com.google.android.filament:filament-android:1.21.1'
}
```
@@ -43,7 +43,6 @@ Here are all the libraries available in the group `com.google.android.filament`:
| [![gltfio-android](https://maven-badges.herokuapp.com/maven-central/com.google.android.filament/gltfio-android/badge.svg?subject=gltfio-android)](https://maven-badges.herokuapp.com/maven-central/com.google.android.filament/gltfio-android) | A glTF 2.0 loader for Filament, depends on `filament-android`. |
| [![gltfio-android-lite](https://maven-badges.herokuapp.com/maven-central/com.google.android.filament/gltfio-android-lite/badge.svg?subject=gltfio-android-lite)](https://maven-badges.herokuapp.com/maven-central/com.google.android.filament/gltfio-android-lite) | Trimmed version of `gltfio` that does not support some glTF extensions. |
| [![filament-utils-android](https://maven-badges.herokuapp.com/maven-central/com.google.android.filament/filament-utils-android/badge.svg?subject=filament-utils-android)](https://maven-badges.herokuapp.com/maven-central/com.google.android.filament/filament-utils-android) | KTX loading, Kotlin math, and camera utilities, depends on `gltfio-android`. |
| [![filament-utils-android-lite](https://maven-badges.herokuapp.com/maven-central/com.google.android.filament/filament-utils-android-lite/badge.svg?subject=filament-utils-lite)](https://maven-badges.herokuapp.com/maven-central/com.google.android.filament/filament-utils-android-lite) | Trimmed version of `filament-utils` that does not support some glTF features. |
| [![filamat-android](https://maven-badges.herokuapp.com/maven-central/com.google.android.filament/filamat-android/badge.svg?subject=filamat-android)](https://maven-badges.herokuapp.com/maven-central/com.google.android.filament/filamat-android) | A runtime material builder/compiler. This library is large but contains a full shader compiler/validator/optimizer and supports both OpenGL and Vulkan. |
| [![filamat-android-lite](https://maven-badges.herokuapp.com/maven-central/com.google.android.filament/filamat-android-lite/badge.svg?subject=filamat-android-lite)](https://maven-badges.herokuapp.com/maven-central/com.google.android.filament/filamat-android-lite) | A much smaller alternative to `filamat-android` that can only generate OpenGL shaders. It does not provide validation or optimizations. |
@@ -52,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.12.9'
pod 'Filament', '~> 1.21.1'
```
### Snapshots
@@ -63,7 +62,7 @@ steps:
1. Find the [commit](https://github.com/google/filament/commits/main) you're interested in.
2. Click the green check mark under the commit message.
3. Click on the _Details_ link for the platform you're interested in.
4. On the top right, click on the _Artifacts_ dropdown and choose an artifact.
4. On the top left click _Summary_, then in the _Artifacts_ section choose the desired artifact.
## Documentation
@@ -122,10 +121,11 @@ steps:
- Specular anti-aliasing
- Spot and directional light shadows
- Cascaded shadows
- EVSM or PCF shadows
- EVSM, PCSS, DPCF, or PCF shadows
- Transparent shadows
- Contact shadows
- Screen-space ambient occlusion
- Screen-space reflections
- Screen-space refraction
- Global fog
- Dynamic resolution (with support for AMD FidelityFX FSR)
@@ -151,9 +151,9 @@ steps:
- [x] Points
- [x] Lines
- [ ] Line Loop
- [ ] Line Strip
- [x] Line Strip
- [x] Triangles
- [ ] Triangle Strip
- [x] Triangle Strip
- [ ] Triangle Fan
- Animation
@@ -168,11 +168,13 @@ steps:
- [x] KHR_draco_mesh_compression
- [x] KHR_lights_punctual
- [x] KHR_materials_clearcoat
- [x] KHR_materials_emissive_strength
- [x] KHR_materials_ior
- [x] KHR_materials_pbrSpecularGlossiness
- [x] KHR_materials_sheen
- [x] KHR_materials_transmission
- [x] KHR_materials_unlit
- [x] KHR_materials_variants
- [x] KHR_materials_volume
- [x] KHR_mesh_quantization
- [x] KHR_texture_transform

View File

@@ -3,7 +3,169 @@
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.
## v1.12.9 (currently main branch)
## v1.21.2 (currently main branch)
## v1.21.1
- engine: Allow both screen-space refraction and screen-space reflections on the same object [⚠️ **Material breakage**].
- engine: Optimizations for screen-space reflections.
- engine: Remove `Viewport::scale()` [⚠️ **API Change**].
- engine: Fix 12x overallocation of memory in `MorphTargetBuffer`.
- Metal: Fix validation error when reading from default `SwapChain`.
## v1.21.0
- engine: OpenGL performance improvements with some drivers.
- engine: Fix incorrect shadows with some custom projection matrices.
- engine: Fix low frame rates seen with a lot of morph targets.
- gltfio: Add support for KHR_materials_variants.
- gltfio: Add support for KHR_materials_emissive_strength.
- gltfio: Java now exposes morph target names as an array for consistency [⚠️ **API Change**].
## v1.20.5
- engine: New behavior for MASKED to work with translucent views. [⚠️ **Recompile Materials** to get the fix]
- engine: Fix screen-space reflections when post-processing and MSAA are off.
- engine: Update MAX_MORPH_TARGETS constant to 256.
- engine: Fix point light lighting with ortho projection.
- libs: BlueGL symbols are now prefixed with `bluegl` on all platforms.
- gltfio: Add skinning getters to `FilamentAsset`.
## v1.20.4
- gltfio: Java clients must now destroy the MaterialProvider [⚠️ **API Change**].
- gltfio: Fix, bone pose not applied if glTF model doesn't have animations.
- libs: Added `math::quat::fromDirectedRotation` [**NEW API**].
- WebGL: Restore GL state when frame ends.
## v1.20.3
- Java: Fix URI bug in Android Viewer sample when dropping some zips.
- Vulkan: Fix "uninitialized texture" warnings from the Vulkan backend.
## v1.20.2
- engine: Binary size optimizations.
- engine: Fix, Mat4 from Quaternion was transposed.
- Vulkan: Internal bug fixes and robustness improvements.
- Vulkan: Reduced log spam.
## v1.20.1
- engine: Binary size improvements.
- engine: Add basic support for instanced renderables [**NEW API**].
- engine: Fix, first imaged passsed to `Stream::SetAcquiredImage` is ignored and leaked.
- Vulkan: Robustness improvements.
- Java: Fix, lookAt z axis negated.
- gltfio: Be graceful when model has > 4 weights per vert.
## v1.20.0
- engine: Support rough screen-space reflections [⚠️ **Material breakage**].
- engine: Added `Scene::forEach` API to iterate through a scene's entities.
- engine: Fix incorrect normals with skinned models.
- Vulkan: Fix segfault during shutdown.
- WebGL: Support web apps that have multiple `FilamentViewer`s.
- gltfio: Performance enhancements when loading models.
## v1.19.0
- engine: Support 256 morph targets.
- engine: Screen-space reflection improvements.
- engine: Morphing improvements and bug fixes.
- gltfio: Generate morphing normals when they are missing.
- gltfio: Support material extras.
- Java: Add bindings for new morphing API.
- Vulkan: Fix segfault on macOS.
## v1.18.0
- engine: Add support separate samplers in fragment and vertex shaders [⚠️ **Material breakage**].
- engine: Support legacy morphing mode with vertex attributes.
- engine: Allow more flexible quality settings for the ColorGrading LUT.
- engine: Improve screen-space reflections quality and allow reflections and refractions together.
- Vulkan: Bug fixes and improvements.
## v1.17.0
- engine: Add experimental glossy screen-space reflections.
- engine: Add support for GPU morphing and 128 morph targets.
- engine: Fix crash with non-shadow receiving renderables and VSM.
- engine: Bring back the 3x3 filter for PCF shadows.
- engine: Correct AABB calculation for skinned glTF models.
## v1.16.1
- engine: Added line/triangle strip support.
## v1.16.0
- engine: Fixes skinning calculations (#4887) [⚠️ **Material breakage**].
- engine: Add support for the glTF extension KHR_materials_emissive_strength.
- engine: Improvements and fixes to skinning calculations.
- engine: Fix debug checks for compressed textures.
- Metal: Fix `readPixels` when dimensions are greater than the render target's.
## v1.15.2
- engine: Add support for PCSS (Percentage Closer Soft Shadows).
- engine: Fix spotlight shadow bias.
- samples: Avoid leaking IBLs in Android sample-gltf-viewer.
- libs: Fix `libibl` on mobile.
## v1.15.1
- engine: add support for DPCF (PCF shadows with contact hardening).
- engine: add support for Wayland and Vulkan.
- engine: Fade lights out when close to light far plane.
- Java: Add missing `Engine#destroySkinningBuffer` method.
## v1.15.0
- engine: Fix spotlights normal bias calculation [⚠️ **Material breakage**].
- libimage: Fix loading spherical harmonics on certain locals.
## v1.14.2
- Metal: Fix validation error when rendering to `RenderTarget` without depth attachment.
- engine: Fix rendering glitch with zero-scale bone transforms.
## v1.14.1
- engine: Improvements to shadowing.
## v1.14.0
- engine: Internal materials can use structures as parameters [⚠️ **Material breakage**].
- engine: `readPixels` on a `SwapChain` must be called within `beginFrame` / `endFrame` [⚠️ **API
Change**].
- engine: Fix normal bias and improve spotlight quality.
- Java: Fix shadow biases.
## v1.13.0
- Android: Gradle configuration caching is now enabled.
- Android: Filament's Gradle properties have all been renamed to `com.google.android.filament.xxx`
where `xxx` is the property name. See `android/build.gradle` for a complete list [⚠️]
- Android: The Gradle property `filament_tools_dir` (now called
`com.google.android.filament.tools-dir`) does not have a default value anymore. Please specify one
in your `gradle.properties` if you reuse the Gradle plugin in your projects [⚠️]
- engine: Fix spotlights direction and falloff [⚠️ **Material breakage**].
- engine: Improvements to VSM and spotlight shadows.
## v1.12.11
- Metal: Color grading performance improvement on M1 devices.
- samples: Fix glitchy animation seen in gltf-viewer iOS sample.
## v1.12.10
- engine: rewrite dynamic resolution scaling controller for better accuracy and less jittering.
- Java: fix missing ASTC texture enum.
- tools: Fix normal map issues in mipgen.
- WebGL: expose some `SurfaceOrientation` functions.
## v1.12.9
- engine: New API: `MultiSampleAntiAliasingOptions` and HDR-aware MSAA resolve. When `customResolve`
is enabled, improves anti-aliasing quality [**NEW API**].

View File

@@ -122,20 +122,20 @@ The Gradle project used to generate the AAR is located at `<filament>\android`.
```
cd android
gradlew -Pfilament_dist_dir=..\out\android-release\filament assembleRelease
gradlew -Pcom.google.android.filament.dist-dir=..\out\android-release\filament assembleRelease
copy filament-android\build\outputs\aar\filament-android-release.aar ..\..\out\
```
If you're only interested in building for a single ABI, you'll need to pass a `filament_abis` parameter:
If you're only interested in building for a single ABI, you'll need to pass a `com.google.android.filament.abis` parameter:
```
gradlew -Pfilament_dist_dir=..\out\android-release\filament assembleRelease -Pfilament_abis=x86
gradlew -Pcom.google.android.filament.dist-dir=..\out\android-release\filament assembleRelease -Pcom.google.android.filament.abis=x86
```
If you're only interested in building SDK, you may skip samples build by passing a `filament_skip_samples` flag:
If you're only interested in building SDK, you may skip samples build by passing a `com.google.android.filament.skip-samples` flag:
```
gradlew -Pfilament_dist_dir=..\out\android-release\filament assembleRelease -Pfilament_skip_samples
gradlew -Pcom.google.android.filament.dist-dir=..\out\android-release\filament assembleRelease -Pfilament_skip_samples
```

View File

@@ -1,26 +1,28 @@
// This script accepts the following parameters:
//
// filament_dist_dir
// com.google.android.filament.dist-dir
// Path to the Filament distribution/install directory for Android
// (produced by make/ninja install). This directory must contain lib/arm64-v8a/ etc.
//
// filament_tools_dir
// com.google.android.filament.tools-dir
// Path to the Filament distribution/install directory for desktop.
// This directory must contain bin/matc.
//
// filament_exclude_vulkan
// com.google.android.filament.exclude-vulkan
// When set, support for Vulkan will be excluded.
//
// filament_skip_samples
// com.google.android.filament.skip-samples
// Exclude samples from the project. Useful to speed up compilation.
//
// filament_abis
// com.google.android.filament.abis
// List of supported ABIs to build as a comma separated list. Available options are:
// arm64-v8a, armeabi-v7a, x86_64, x86, all
// Defaults to all.
//
// Example:
// ./gradlew -Pfilament_dist_dir=../dist-android-release assembleRelease -Pfilament_abis=x86
// ./gradlew -Pcom.google.android.filament.dist-dir=../dist-android-release \
// -Pcom.google.android.filament.abis=x86 \
// assembleRelease
// Publishing to Maven Central:
// - Build and upload artifacts with ./gradlew publish
@@ -40,44 +42,58 @@
//
buildscript {
def filamentPath = file("../out/android-release/filament").absolutePath
if (project.hasProperty("filament_dist_dir")) {
filamentPath = file(project.property("filament_dist_dir")).absolutePath
}
def path = providers
.gradleProperty("com.google.android.filament.dist-dir")
.forUseAtConfigurationTime().get()
def directory = objects.fileProperty().fileValue(new File(path)).getAsFile().get()
def filamentPath = directory.absolutePath
// Our CMake scripts require a forward-slash path for the FILAMENT_DIST_DIR
// variable, so here we convert the native path to a forward-slash path.
filamentPath = filamentPath.replace(File.separator, '/')
// Warning: changing this property does not work well with incremental builds.
def excludeVulkan = project.hasProperty("filament_exclude_vulkan")
def excludeVulkan = providers
.gradleProperty("com.google.android.filament.exclude-vulkan")
.forUseAtConfigurationTime()
.isPresent()
def abis = ["arm64-v8a", "armeabi-v7a", "x86_64", "x86"]
if (project.hasProperty("filament_abis")) {
def newAbis = project.property("filament_abis").split(',')
if (!newAbis.contains("all")) {
abis = newAbis
}
def newAbis = providers
.gradleProperty("com.google.android.filament.abis")
.forUseAtConfigurationTime()
.get()
.split(',')
if (!newAbis.contains("all")) {
abis = newAbis
}
ext.versions = [
'minSdk': 19,
'targetSdk': 30,
'compileSdk': 30,
'kotlin': '1.5.30',
'buildTools': '30.0.3',
'ndk': '22.1.7171670'
'targetSdk': 31,
'compileSdk': 31,
'kotlin': '1.6.10',
'kotlin_coroutines': '1.6.0',
'buildTools': '32.0.0',
'ndk': '23.1.7779620'
]
ext.deps = [
'androidx': [
'annotations': "androidx.annotation:annotation:1.1.0",
'core': "androidx.core:core:1.3.0",
'annotations': "androidx.annotation:annotation:1.3.0",
'core': "androidx.core:core:1.7.0",
],
'kotlin': "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${versions.kotlin}"
'kotlin': "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${versions.kotlin}",
'coroutines': [
'core': "org.jetbrains.kotlinx:kotlinx-coroutines-core:${versions.kotlin_coroutines}",
'android': "org.jetbrains.kotlinx:kotlinx-coroutines-android:${versions.kotlin_coroutines}",
]
]
dependencies {
classpath 'com.android.tools.build:gradle:7.0.2'
// NOTE: See TODO in gradle.properties once we move to Gradle 7.4
classpath 'com.android.tools.build:gradle:7.1.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}"
}
@@ -118,7 +134,7 @@ buildscript {
}
plugins {
id 'io.codearte.nexus-staging' version '0.22.0'
id 'io.codearte.nexus-staging' version '0.30.0'
}
// Nexus Staging configuration
@@ -187,7 +203,8 @@ subprojects {
gradle.taskGraph.whenReady {
gradle.taskGraph.allTasks.each {
it.onlyIf {
!it.project.ext.has('isSample') || !project.hasProperty('filament_skip_samples')
!it.project.ext.has('isSample') ||
!project.hasProperty('com.google.android.filament.skip-samples')
}
}
}

View File

@@ -1,3 +1,17 @@
plugins {
id 'groovy-gradle-plugin'
}
gradlePlugin {
plugins {
create("filament-tools-plugin") {
id = "filament-tools-plugin"
implementationClass = "FilamentToolsPlugin"
}
}
}
repositories {
mavenCentral()
}

View File

@@ -1,20 +1,22 @@
// This plugin accepts the following parameters:
//
// filament_tools_dir
// com.google.android.filament.tools-dir
// Path to the Filament distribution/install directory for desktop.
// This directory must contain bin/matc.
//
// filament_exclude_vulkan
// com.google.android.filament.exclude-vulkan
// When set, support for Vulkan will be excluded.
//
// Example:
// ./gradlew -Pfilament_tools_dir=../../dist-release assembleDebug
// ./gradlew -Pcom.google.android.filament.tools-dir=../../dist-release assembleDebug
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.provider.ProviderFactory
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.FileSystemOperations
import org.gradle.api.file.FileType
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.logging.LogLevel
@@ -27,14 +29,18 @@ import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.incremental.InputFileDetails
import org.gradle.api.model.ObjectFactory
import org.gradle.internal.os.OperatingSystem
import org.gradle.process.ExecOperations
import org.gradle.work.ChangeType
import org.gradle.work.Incremental
import org.gradle.work.InputChanges
import java.nio.file.Paths
class TaskWithBinary extends DefaultTask {
import javax.inject.Inject
abstract class TaskWithBinary extends DefaultTask {
private final String binaryName
private Property<String> binaryPath = null
@@ -42,15 +48,23 @@ class TaskWithBinary extends DefaultTask {
binaryName = name
}
@Inject abstract ObjectFactory getObjects()
@Inject abstract ProviderFactory getProviders()
@Input
Property<String> getBinary() {
if (binaryPath == null) {
def tool = ["/bin/${binaryName}.exe", "/bin/${binaryName}"]
def fullPath = tool.collect { path ->
Paths.get(project.ext.filamentToolsPath.absolutePath, path).toFile()
def filamentToolsPath = providers
.gradleProperty("com.google.android.filament.tools-dir")
.forUseAtConfigurationTime().get()
def directory = objects.fileProperty()
.fileValue(new File(filamentToolsPath)).getAsFile().get()
Paths.get(directory.absolutePath, path).toFile()
}
binaryPath = project.objects.property(String.class)
binaryPath = objects.property(String.class)
binaryPath.set(
(OperatingSystem.current().isWindows() ? fullPath[0] : fullPath[1]).toString())
}
@@ -84,6 +98,11 @@ abstract class MaterialCompiler extends TaskWithBinary {
@OutputDirectory
abstract DirectoryProperty getOutputDir()
@Inject abstract FileSystemOperations getFs()
@Inject abstract ExecOperations getExec()
@Inject abstract ObjectFactory getObjects()
@Inject abstract ProviderFactory getProviders()
MaterialCompiler() {
super("matc")
}
@@ -91,7 +110,9 @@ abstract class MaterialCompiler extends TaskWithBinary {
@TaskAction
void execute(InputChanges inputs) {
if (!inputs.incremental) {
project.delete(project.fileTree(outputDir.asFile.get()).matching { include '*.filamat' })
fs.delete({
delete(objects.fileTree().from(outputDir).matching { include '*.filamat' })
})
}
inputs.getFileChanges(inputDir).each { InputFileDetails change ->
@@ -115,12 +136,15 @@ abstract class MaterialCompiler extends TaskWithBinary {
}
def matcArgs = []
if (!project.hasProperty("filament_exclude_vulkan")) {
def exclude_vulkan = providers
.gradleProperty("com.google.android.filament.exclude-vulkan")
.forUseAtConfigurationTime().present
if (!exclude_vulkan) {
matcArgs += ['-a', 'vulkan']
}
matcArgs += ['-a', 'opengl', '-p', 'mobile', '-o', getOutputFile(file), file]
project.exec {
exec.exec {
standardOutput out
errorOutput err
executable "${binary.get()}"
@@ -149,6 +173,10 @@ abstract class IblGenerator extends TaskWithBinary {
@OutputDirectory
abstract DirectoryProperty getOutputDir()
@Inject abstract FileSystemOperations getFs()
@Inject abstract ExecOperations getExec()
@Inject abstract ObjectFactory getObjects()
IblGenerator() {
super("cmgen")
}
@@ -156,7 +184,9 @@ abstract class IblGenerator extends TaskWithBinary {
@TaskAction
void execute(InputChanges inputs) {
if (!inputs.incremental) {
project.delete(project.fileTree(outputDir.asFile.get()).matching { include '*' })
fs.delete({
delete(objects.fileTree().from(outputDir).matching { include '*' })
})
}
inputs.getFileChanges(inputFile).each { InputFileDetails change ->
@@ -188,7 +218,7 @@ abstract class IblGenerator extends TaskWithBinary {
}
commandArgs = commandArgs + " " + file
project.exec {
exec.exec {
standardOutput out
errorOutput err
executable "${binary.get()}"
@@ -213,6 +243,9 @@ abstract class MeshCompiler extends TaskWithBinary {
@OutputDirectory
abstract DirectoryProperty getOutputDir()
@Inject abstract FileSystemOperations getFs()
@Inject abstract ExecOperations getExec()
MeshCompiler() {
super("filamesh")
}
@@ -220,7 +253,9 @@ abstract class MeshCompiler extends TaskWithBinary {
@TaskAction
void execute(InputChanges inputs) {
if (!inputs.incremental) {
project.delete(project.fileTree(outputDir.asFile.get()).matching { include '*.filamesh' })
fs.delete({
delete(objects.fileTree().from(outputDir).matching { include '*.filamesh' })
})
}
inputs.getFileChanges(inputFile).each { InputFileDetails change ->
@@ -243,7 +278,7 @@ abstract class MeshCompiler extends TaskWithBinary {
" Ensure Filament has been built/installed before building this app.")
}
project.exec {
exec.exec {
standardOutput out
errorOutput err
executable "${binary.get()}"
@@ -280,11 +315,6 @@ class FilamentToolsPlugin implements Plugin<Project> {
extension.meshInputFile = project.objects.fileProperty()
extension.meshOutputDir = project.objects.directoryProperty()
project.ext.filamentToolsPath = project.file("../../../out/release/filament")
if (project.hasProperty("filament_tools_dir")) {
project.ext.filamentToolsPath = project.file(project.property("filament_tools_dir"))
}
project.tasks.register("filamentCompileMaterials", MaterialCompiler) {
enabled =
extension.materialInputDir.isPresent() &&

View File

@@ -19,7 +19,7 @@
#include "private/backend/VirtualMachineEnv.h"
void acquireCallbackJni(JNIEnv* env, CallbackJni& callbackUtils) {
#ifdef ANDROID
#ifdef __ANDROID__
callbackUtils.handlerClass = env->FindClass("android/os/Handler");
callbackUtils.handlerClass = (jclass) env->NewGlobalRef(callbackUtils.handlerClass);
callbackUtils.post = env->GetMethodID(callbackUtils.handlerClass,
@@ -34,7 +34,7 @@ void acquireCallbackJni(JNIEnv* env, CallbackJni& callbackUtils) {
void releaseCallbackJni(JNIEnv* env, CallbackJni callbackUtils, jobject handler, jobject callback) {
if (handler && callback) {
#ifdef ANDROID
#ifdef __ANDROID__
if (env->IsInstanceOf(handler, callbackUtils.handlerClass)) {
env->CallBooleanMethod(handler, callbackUtils.post, callback);
}
@@ -45,7 +45,7 @@ void releaseCallbackJni(JNIEnv* env, CallbackJni callbackUtils, jobject handler,
}
env->DeleteGlobalRef(handler);
env->DeleteGlobalRef(callback);
#ifdef ANDROID
#ifdef __ANDROID__
env->DeleteGlobalRef(callbackUtils.handlerClass);
#endif
env->DeleteGlobalRef(callbackUtils.executorClass);
@@ -86,7 +86,6 @@ JniBufferCallback::JniBufferCallback(JNIEnv* env, jobject handler, jobject callb
AutoBuffer&& buffer)
: JniCallback(env, handler, callback),
mBuffer(std::move(buffer)) {
acquireCallbackJni(env, mCallbackUtils);
}
JniBufferCallback::~JniBufferCallback() = default;
@@ -109,7 +108,6 @@ JniImageCallback* JniImageCallback::make(filament::Engine*,
JniImageCallback::JniImageCallback(JNIEnv* env, jobject handler, jobject callback, long image)
: JniCallback(env, handler, callback),
mImage(image) {
acquireCallbackJni(env, mCallbackUtils);
}
JniImageCallback::~JniImageCallback() = default;

View File

@@ -25,7 +25,7 @@
#include <filament/Engine.h>
struct CallbackJni {
#ifdef ANDROID
#ifdef __ANDROID__
jclass handlerClass = nullptr;
jmethodID post = nullptr;
#endif
@@ -39,30 +39,39 @@ void releaseCallbackJni(JNIEnv* env, CallbackJni callbackUtils, jobject handler,
struct JniCallback : private filament::backend::CallbackHandler {
JniCallback(JniCallback const &) = delete;
JniCallback(JniCallback&&) = delete;
JniCallback& operator=(JniCallback const &) = delete;
JniCallback& operator=(JniCallback&&) = delete;
// create a JniCallback
static JniCallback* make(JNIEnv* env, jobject handler, jobject runnable);
// execute the callback on the java thread and destroy ourselves
static void postToJavaAndDestroy(JniCallback* callback);
// CallbackHandler interface.
void post(void* user, Callback callback) override;
// Get the CallbackHandler interface
filament::backend::CallbackHandler* getHandler() noexcept { return this; }
jobject getCallbackObject() { return mCallback; }
protected:
JniCallback(JNIEnv* env, jobject handler, jobject runnable);
explicit JniCallback() = default; // this version does nothing
virtual ~JniCallback();
jobject mHandler;
jobject mCallback;
CallbackJni mCallbackUtils;
jobject mHandler{};
jobject mCallback{};
CallbackJni mCallbackUtils{};
};
struct JniBufferCallback : public JniCallback {
// create a JniBufferCallback
static JniBufferCallback* make(filament::Engine* engine,
JNIEnv* env, jobject handler, jobject callback, AutoBuffer&& buffer);
// execute the callback on the java thread and destroy ourselves
static void postToJavaAndDestroy(void*, size_t, void* user);
private:
@@ -72,9 +81,11 @@ private:
};
struct JniImageCallback : public JniCallback {
// create a JniImageCallback
static JniImageCallback* make(filament::Engine* engine, JNIEnv* env, jobject handler,
jobject runnable, long image);
// execute the callback on the java thread and destroy ourselves
static void postToJavaAndDestroy(void*, void* user);
private:

View File

@@ -370,3 +370,10 @@ Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderVariant
auto builder = (MaterialBuilder*) nativeBuilder;
builder->variantFilter((uint8_t) variantFilter);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderUseLegacyMorphing(JNIEnv*,
jclass, jlong nativeBuilder) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->useLegacyMorphing();
}

View File

@@ -459,6 +459,19 @@ public class MaterialBuilder {
@NonNull
public MaterialBuilder variantFilter(int variantFilter) {
nMaterialBuilderVariantFilter(mNativeObject, variantFilter);
useLegacyMorphing();
return this;
}
/**
* Legacy morphing uses the data in the {@link VertexBuffer.VertexAttribute} slots
* (<code>MORPH_POSITION_0</code>, etc) and is limited to 4 morph targets.
*
* @see RenderableManager.Builder#morphing()
*/
@NonNull
public MaterialBuilder useLegacyMorphing() {
nMaterialBuilderUseLegacyMorphing(mNativeObject);
return this;
}
@@ -599,4 +612,5 @@ public class MaterialBuilder {
private static native void nMaterialBuilderOptimization(long nativeBuilder, int optimization);
private static native void nMaterialBuilderVariantFilter(long nativeBuilder,
int variantFilter);
private static native void nMaterialBuilderUseLegacyMorphing(long nativeBuilder);
}

View File

@@ -74,6 +74,7 @@ add_library(filament-jni SHARED
src/main/cpp/Material.cpp
src/main/cpp/MaterialInstance.cpp
src/main/cpp/MathUtils.cpp
src/main/cpp/MorphTargetBuffer.cpp
src/main/cpp/RenderableManager.cpp
src/main/cpp/Renderer.cpp
src/main/cpp/RenderTarget.cpp

View File

@@ -50,6 +50,19 @@ Java_com_google_android_filament_ColorGrading_nBuilderQuality(JNIEnv*, jclass, j
builder->quality(quality);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_ColorGrading_nBuilderFormat(JNIEnv*, jclass, jlong nativeBuilder, jint format_) {
ColorGrading::Builder* builder = (ColorGrading::Builder*) nativeBuilder;
ColorGrading::LutFormat format = (ColorGrading::LutFormat) format_;
builder->format(format);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_ColorGrading_nBuilderDimensions(JNIEnv*, jclass, jlong nativeBuilder, jint dim_) {
ColorGrading::Builder* builder = (ColorGrading::Builder*) nativeBuilder;
builder->dimensions((uint8_t)dim_);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_ColorGrading_nBuilderToneMapper(JNIEnv*, jclass,
jlong nativeBuilder, jlong toneMapper_) {

View File

@@ -45,12 +45,11 @@ extern "C" {
// handle. Whatever object is returned from this method must match what is in
// folder filament/src/driver/opengl/Context* in particular pay attention to
// the object type in makeCurrent method.
extern void *getNativeWindow(JNIEnv *env, jclass, jobject surface);
extern void* getNativeWindow(JNIEnv* env, jclass, jobject surface);
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_Engine_nGetBackend(JNIEnv* env,
jclass klass, jlong nativeEngine) {
Java_com_google_android_filament_Engine_nGetBackend(JNIEnv*, jclass, jlong nativeEngine) {
Engine* engine = (Engine*) nativeEngine;
return (jlong) engine->getBackend();
}
@@ -64,8 +63,8 @@ Java_com_google_android_filament_Engine_nCreateSwapChain(JNIEnv* env,
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_Engine_nCreateSwapChainHeadless(JNIEnv* env,
jclass klass, jlong nativeEngine, jint width, jint height, jlong flags) {
Java_com_google_android_filament_Engine_nCreateSwapChainHeadless(JNIEnv*,
jclass, jlong nativeEngine, jint width, jint height, jlong flags) {
Engine* engine = (Engine*) nativeEngine;
return (jlong) engine->createSwapChain(width, height, (uint64_t) flags);
}
@@ -81,7 +80,7 @@ extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_Engine_nDestroySwapChain(JNIEnv*, jclass,
jlong nativeEngine, jlong nativeSwapChain) {
Engine* engine = (Engine*) nativeEngine;
SwapChain *swapChain = (SwapChain *) nativeSwapChain;
SwapChain* swapChain = (SwapChain*) nativeSwapChain;
return engine->destroy(swapChain);
}
@@ -98,7 +97,7 @@ extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_Engine_nDestroyView(JNIEnv*, jclass,
jlong nativeEngine, jlong nativeView) {
Engine* engine = (Engine*) nativeEngine;
View *view = (View *) nativeView;
View* view = (View*) nativeView;
return engine->destroy(view);
}
@@ -115,7 +114,7 @@ extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_Engine_nDestroyRenderer(JNIEnv*, jclass,
jlong nativeEngine, jlong nativeRenderer) {
Engine* engine = (Engine*) nativeEngine;
Renderer *renderer = (Renderer *) nativeRenderer;
Renderer* renderer = (Renderer*) nativeRenderer;
return engine->destroy(renderer);
}
@@ -158,7 +157,7 @@ extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_Engine_nDestroyScene(JNIEnv*, jclass,
jlong nativeEngine, jlong nativeScene) {
Engine* engine = (Engine*) nativeEngine;
Scene *scene = (Scene *) nativeScene;
Scene* scene = (Scene*) nativeScene;
return engine->destroy(scene);
}
@@ -175,7 +174,7 @@ extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_Engine_nDestroyFence(JNIEnv*, jclass,
jlong nativeEngine, jlong nativeFence) {
Engine* engine = (Engine*) nativeEngine;
Fence *fence = (Fence *) nativeFence;
Fence* fence = (Fence*) nativeFence;
return engine->destroy(fence);
}
@@ -185,7 +184,7 @@ extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_Engine_nDestroyStream(JNIEnv*, jclass,
jlong nativeEngine, jlong nativeStream) {
Engine* engine = (Engine*) nativeEngine;
Stream *stream = (Stream *) nativeStream;
Stream* stream = (Stream*) nativeStream;
return engine->destroy(stream);
}
@@ -195,7 +194,7 @@ extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_Engine_nDestroyIndexBuffer(JNIEnv*, jclass,
jlong nativeEngine, jlong nativeIndexBuffer) {
Engine* engine = (Engine*) nativeEngine;
IndexBuffer *indexBuffer = (IndexBuffer *) nativeIndexBuffer;
IndexBuffer* indexBuffer = (IndexBuffer*) nativeIndexBuffer;
return engine->destroy(indexBuffer);
}
@@ -203,15 +202,23 @@ extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_Engine_nDestroyVertexBuffer(JNIEnv*, jclass,
jlong nativeEngine, jlong nativeVertexBuffer) {
Engine* engine = (Engine*) nativeEngine;
VertexBuffer *vertexBuffer = (VertexBuffer *) nativeVertexBuffer;
VertexBuffer* vertexBuffer = (VertexBuffer*) nativeVertexBuffer;
return engine->destroy(vertexBuffer);
}
extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_Engine_nDestroySkinningBuffer(JNIEnv*, jclass,
jlong nativeEngine, jlong nativeSkinningBuffer) {
Engine* engine = (Engine*) nativeEngine;
SkinningBuffer* skinningBuffer = (SkinningBuffer*) nativeSkinningBuffer;
return engine->destroy(skinningBuffer);
}
extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_Engine_nDestroyIndirectLight(JNIEnv*, jclass,
jlong nativeEngine, jlong nativeIndirectLight) {
Engine* engine = (Engine*) nativeEngine;
IndirectLight *indirectLight = (IndirectLight *) nativeIndirectLight;
IndirectLight* indirectLight = (IndirectLight*) nativeIndirectLight;
return engine->destroy(indirectLight);
}
@@ -219,7 +226,7 @@ extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_Engine_nDestroyMaterial(JNIEnv*, jclass,
jlong nativeEngine, jlong nativeMaterial) {
Engine* engine = (Engine*) nativeEngine;
Material *material = (Material *) nativeMaterial;
Material* material = (Material*) nativeMaterial;
return engine->destroy(material);
}
@@ -235,7 +242,7 @@ extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_Engine_nDestroySkybox(JNIEnv*, jclass,
jlong nativeEngine, jlong nativeSkybox) {
Engine* engine = (Engine*) nativeEngine;
Skybox *skybox = (Skybox *) nativeSkybox;
Skybox* skybox = (Skybox*) nativeSkybox;
return engine->destroy(skybox);
}
@@ -251,7 +258,7 @@ extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_Engine_nDestroyTexture(JNIEnv*, jclass,
jlong nativeEngine, jlong nativeTexture) {
Engine* engine = (Engine*) nativeEngine;
Texture *texture = (Texture *) nativeTexture;
Texture* texture = (Texture*) nativeTexture;
return engine->destroy(texture);
}
@@ -272,7 +279,7 @@ Java_com_google_android_filament_Engine_nDestroyEntity(JNIEnv*, jclass,
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Engine_nFlushAndWait(JNIEnv *env, jclass clazz,
Java_com_google_android_filament_Engine_nFlushAndWait(JNIEnv*, jclass,
jlong nativeEngine) {
Engine* engine = (Engine*) nativeEngine;
engine->flushAndWait();
@@ -281,22 +288,19 @@ Java_com_google_android_filament_Engine_nFlushAndWait(JNIEnv *env, jclass clazz,
// Managers...
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_Engine_nGetTransformManager(JNIEnv*, jclass,
jlong nativeEngine) {
Java_com_google_android_filament_Engine_nGetTransformManager(JNIEnv*, jclass, jlong nativeEngine) {
Engine* engine = (Engine*) nativeEngine;
return (jlong) &engine->getTransformManager();
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_Engine_nGetLightManager(JNIEnv*, jclass,
jlong nativeEngine) {
Java_com_google_android_filament_Engine_nGetLightManager(JNIEnv*, jclass, jlong nativeEngine) {
Engine* engine = (Engine*) nativeEngine;
return (jlong) &engine->getLightManager();
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_Engine_nGetRenderableManager(JNIEnv*, jclass,
jlong nativeEngine) {
Java_com_google_android_filament_Engine_nGetRenderableManager(JNIEnv*, jclass, jlong nativeEngine) {
Engine* engine = (Engine*) nativeEngine;
return (jlong) &engine->getRenderableManager();
}

View File

@@ -18,21 +18,15 @@
#include "private/backend/VirtualMachineEnv.h"
namespace filament {
extern jint JNI_OnLoad(JavaVM* vm, void* reserved);
};
JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
#if ANDROID
::filament::JNI_OnLoad(vm, reserved);
#else
// This must be called when the library is loaded. We need this to get a reference to the
// global VM
::filament::VirtualMachineEnv::JNI_OnLoad(vm);
#endif
return JNI_VERSION_1_6;
}

View File

@@ -76,8 +76,10 @@ extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_LightManager_nBuilderShadowOptions(JNIEnv* env, jclass,
jlong nativeBuilder, jint mapSize, jint cascades, jfloatArray splitPositions,
jfloat constantBias, jfloat normalBias, jfloat shadowFar, jfloat shadowNearHint,
jfloat shadowFarHint, jboolean stable, jboolean screenSpaceContactShadows, jint stepCount,
jfloat maxShadowDistance, jint vsmMsaaSamples, jfloat blurWidth) {
jfloat shadowFarHint, jboolean stable,
jfloat polygonOffsetConstant, jfloat polygonOffsetSlope,
jboolean screenSpaceContactShadows, jint stepCount,
jfloat maxShadowDistance, jint vsmMsaaSamples, jfloat blurWidth, jfloat shadowBulbRadius) {
LightManager::Builder *builder = (LightManager::Builder *) nativeBuilder;
LightManager::ShadowOptions shadowOptions {
.mapSize = (uint32_t)mapSize,
@@ -88,13 +90,16 @@ Java_com_google_android_filament_LightManager_nBuilderShadowOptions(JNIEnv* env,
.shadowNearHint = shadowNearHint,
.shadowFarHint = shadowFarHint,
.stable = (bool)stable,
.polygonOffsetConstant = polygonOffsetConstant,
.polygonOffsetSlope = polygonOffsetConstant,
.screenSpaceContactShadows = (bool)screenSpaceContactShadows,
.stepCount = uint8_t(stepCount),
.maxShadowDistance = maxShadowDistance,
.vsm = {
.msaaSamples = (uint8_t) vsmMsaaSamples,
.blurWidth = blurWidth
}
},
.shadowBulbRadius = shadowBulbRadius
};
jfloat *nativeSplits = env->GetFloatArrayElements(splitPositions, NULL);
const jsize splitCount = std::min((jsize) 3, env->GetArrayLength(splitPositions));

View File

@@ -0,0 +1,114 @@
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <jni.h>
#include <functional>
#include <stdlib.h>
#include <string.h>
#include <filament/MorphTargetBuffer.h>
#include "common/CallbackUtils.h"
#include "common/NioUtils.h"
using namespace filament;
using namespace backend;
extern "C"
JNIEXPORT jlong JNICALL
Java_com_google_android_filament_MorphTargetBuffer_nCreateBuilder(JNIEnv*, jclass) {
return (jlong) new MorphTargetBuffer::Builder();
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_MorphTargetBuffer_nDestroyBuilder(JNIEnv*, jclass,
jlong nativeBuilder) {
MorphTargetBuffer::Builder* builder = (MorphTargetBuffer::Builder *) nativeBuilder;
delete builder;
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_MorphTargetBuffer_nBuilderVertexCount(JNIEnv*, jclass,
jlong nativeBuilder, jint vertexCount) {
MorphTargetBuffer::Builder* builder = (MorphTargetBuffer::Builder *) nativeBuilder;
builder->vertexCount((size_t) vertexCount);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_MorphTargetBuffer_nBuilderCount(JNIEnv*, jclass,
jlong nativeBuilder, jint count) {
MorphTargetBuffer::Builder* builder = (MorphTargetBuffer::Builder *) nativeBuilder;
builder->count((size_t) count);
}
extern "C"
JNIEXPORT jlong JNICALL
Java_com_google_android_filament_MorphTargetBuffer_nBuilderBuild(JNIEnv*, jclass,
jlong nativeBuilder, jlong nativeEngine) {
MorphTargetBuffer::Builder* builder = (MorphTargetBuffer::Builder *) nativeBuilder;
Engine *engine = (Engine *) nativeEngine;
return (jlong) builder->build(*engine);
}
// ------------------------------------------------------------------------------------------------
extern "C"
JNIEXPORT jint JNICALL
Java_com_google_android_filament_MorphTargetBuffer_nSetPositionsAt(JNIEnv* env, jclass,
jlong nativeObject, jlong nativeEngine,
jint targetIndex, jfloatArray positions, jint count) {
MorphTargetBuffer *morphTargetBuffer = (MorphTargetBuffer *) nativeObject;
Engine *engine = (Engine *) nativeEngine;
jfloat* data = env->GetFloatArrayElements(positions, NULL);
morphTargetBuffer->setPositionsAt(*engine, targetIndex,
(math::float4*) data, size_t(count));
env->ReleaseFloatArrayElements(positions, data, JNI_ABORT);
return 0;
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_google_android_filament_MorphTargetBuffer_nSetTangentsAt(JNIEnv* env, jclass,
jlong nativeObject, jlong nativeEngine,
jint targetIndex, jshortArray tangents, jint count) {
MorphTargetBuffer *morphTargetBuffer = (MorphTargetBuffer *) nativeObject;
Engine *engine = (Engine *) nativeEngine;
jshort* data = env->GetShortArrayElements(tangents, NULL);
morphTargetBuffer->setTangentsAt(*engine, targetIndex,
(math::short4*) data, size_t(count));
env->ReleaseShortArrayElements(tangents, data, JNI_ABORT);
return 0;
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_google_android_filament_MorphTargetBuffer_nGetVertexCount(JNIEnv*, jclass,
jlong nativeObject) {
MorphTargetBuffer *morphTargetBuffer = (MorphTargetBuffer *) nativeObject;
return (jint)morphTargetBuffer->getVertexCount();
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_google_android_filament_MorphTargetBuffer_nGetCount(JNIEnv*, jclass,
jlong nativeObject) {
MorphTargetBuffer *morphTargetBuffer = (MorphTargetBuffer *) nativeObject;
return (jint)morphTargetBuffer->getCount();
}

View File

@@ -209,9 +209,18 @@ Java_com_google_android_filament_RenderableManager_nBuilderSkinningBones(JNIEnv*
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_RenderableManager_nBuilderMorphing(JNIEnv*, jclass,
jlong nativeBuilder, jboolean enabled) {
jlong nativeBuilder, jint targetCount) {
RenderableManager::Builder *builder = (RenderableManager::Builder *) nativeBuilder;
builder->morphing(enabled);
builder->morphing(targetCount);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_RenderableManager_nBuilderSetMorphTargetBufferAt(JNIEnv*, jclass,
jlong nativeBuilder, int level, int primitiveIndex, jlong nativeMorphTargetBuffer,
int offset, int count) {
RenderableManager::Builder *builder = (RenderableManager::Builder *) nativeBuilder;
MorphTargetBuffer *morphTargetBuffer = (MorphTargetBuffer *) nativeMorphTargetBuffer;
builder->morphing(level, primitiveIndex, morphTargetBuffer, offset, count);
}
extern "C" JNIEXPORT void JNICALL
@@ -221,6 +230,13 @@ Java_com_google_android_filament_RenderableManager_nBuilderLightChannel(JNIEnv*,
builder->lightChannel(channel, (bool)enable);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_RenderableManager_nBuilderInstances(JNIEnv*, jclass,
jlong nativeBuilder, jint instanceCount) {
RenderableManager::Builder *builder = (RenderableManager::Builder *) nativeBuilder;
builder->instances(instanceCount);
}
// ------------------------------------------------------------------------------------------------
extern "C" JNIEXPORT void JNICALL
@@ -267,12 +283,29 @@ Java_com_google_android_filament_RenderableManager_nSetBonesAsQuaternions(JNIEnv
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_RenderableManager_nSetMorphWeights(JNIEnv* env, jclass,
jlong nativeRenderableManager, jint instance, jfloatArray weights) {
jlong nativeRenderableManager, jint instance, jfloatArray weights, jint offset) {
RenderableManager *rm = (RenderableManager *) nativeRenderableManager;
jfloat* vec = env->GetFloatArrayElements(weights, NULL);
math::float4 floatvec(vec[0], vec[1], vec[2], vec[3]);
jsize count = env->GetArrayLength(weights);
rm->setMorphWeights((RenderableManager::Instance)instance, vec, count, offset);
env->ReleaseFloatArrayElements(weights, vec, JNI_ABORT);
rm->setMorphWeights((RenderableManager::Instance)instance, floatvec);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_RenderableManager_nSetMorphTargetBufferAt(JNIEnv*,
jclass, jlong nativeRenderableManager, jint i, int level, jint primitiveIndex,
jlong nativeMorphTargetBuffer, jint offset, jint count) {
RenderableManager *rm = (RenderableManager *) nativeRenderableManager;
MorphTargetBuffer *morphTargetBuffer = (MorphTargetBuffer *) nativeMorphTargetBuffer;
rm->setMorphTargetBufferAt((RenderableManager::Instance) i, (uint8_t) level,
(size_t) primitiveIndex, morphTargetBuffer, (size_t) offset, (size_t) count);
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_RenderableManager_nGetMorphTargetCount(JNIEnv* env, jclass,
jlong nativeRenderableManager, jint instance) {
RenderableManager *rm = (RenderableManager *) nativeRenderableManager;
return rm->getMorphTargetCount((RenderableManager::Instance)instance);
}
extern "C" JNIEXPORT void JNICALL

View File

@@ -100,7 +100,7 @@ Java_com_google_android_filament_Skybox_nSetColor(JNIEnv *, jclass,
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_Skybix_nGetTexture(JNIEnv* env, jclass,
Java_com_google_android_filament_Skybox_nGetTexture(JNIEnv* env, jclass,
jlong nativeSkybox) {
Skybox *skybox = (Skybox *) nativeSkybox;
Texture const *tex = skybox->getTexture();

View File

@@ -24,7 +24,7 @@
#include "common/NioUtils.h"
#include "common/CallbackUtils.h"
#ifdef ANDROID
#ifdef __ANDROID__
#if __has_include(<android/hardware_buffer_jni.h>)
#include <android/hardware_buffer_jni.h>
@@ -190,7 +190,7 @@ Java_com_google_android_filament_Stream_nSetAcquiredImage(JNIEnv* env, jclass, j
Engine* engine = (Engine*) nativeEngine;
Stream* stream = (Stream*) nativeStream;
#ifdef ANDROID
#ifdef __ANDROID__
// This function is not available before NDK 15 or before Android 8.
if (UTILS_UNLIKELY(!AHardwareBuffer_fromHardwareBuffer_fn)) {
@@ -201,8 +201,8 @@ Java_com_google_android_filament_Stream_nSetAcquiredImage(JNIEnv* env, jclass, j
if (!AHardwareBuffer_fromHardwareBuffer_fn) {
__android_log_print(ANDROID_LOG_WARN, "Filament", "AHardwareBuffer_fromHardwareBuffer is not available.");
sHardwareBufferSupported = false;
return;
}
return;
}
AHardwareBuffer* nativeBuffer = AHardwareBuffer_fromHardwareBuffer_fn(env, hwbuffer);

View File

@@ -19,7 +19,7 @@
#include <algorithm>
#include <functional>
#ifdef ANDROID
#ifdef __ANDROID__
#include <android/bitmap.h>
#endif
@@ -31,6 +31,8 @@
#include "common/CallbackUtils.h"
#include "common/NioUtils.h"
#include "private/backend/VirtualMachineEnv.h"
using namespace filament;
using namespace backend;
@@ -471,7 +473,7 @@ Java_com_google_android_filament_Texture_nGeneratePrefilterMipmap(JNIEnv *env, j
// ANDROID SPECIFIC BITS
////////////////////////////////////////////////////////////////////////////////////////////////////
#ifdef ANDROID
#ifdef __ANDROID__
#define BITMAP_CONFIG_ALPHA_8 0
#define BITMAP_CONFIG_RGB_565 1
@@ -480,46 +482,37 @@ Java_com_google_android_filament_Texture_nGeneratePrefilterMipmap(JNIEnv *env, j
#define BITMAP_CONFIG_RGBA_F16 4
#define BITMAP_CONFIG_HARDWARE 5
class AutoBitmap {
public:
class AutoBitmap : public JniCallback {
private:
AutoBitmap(JNIEnv* env, jobject bitmap) noexcept
: mEnv(env)
, mBitmap(env->NewGlobalRef(bitmap))
{
: JniCallback(),
mBitmap(env->NewGlobalRef(bitmap)) {
if (mBitmap) {
AndroidBitmap_getInfo(mEnv, mBitmap, &mInfo);
AndroidBitmap_lockPixels(mEnv, mBitmap, &mData);
AndroidBitmap_getInfo(env, mBitmap, &mInfo);
AndroidBitmap_lockPixels(env, mBitmap, &mData);
}
}
AutoBitmap(JNIEnv* env, jobject bitmap, jobject handler, jobject runnable) noexcept
: mEnv(env)
, mBitmap(env->NewGlobalRef(bitmap))
, mHandler(env->NewGlobalRef(handler))
, mCallback(env->NewGlobalRef(runnable))
{
acquireCallbackJni(env, mCallbackUtils);
: JniCallback(env, handler, runnable),
mBitmap(env->NewGlobalRef(bitmap)) {
if (mBitmap) {
AndroidBitmap_getInfo(mEnv, mBitmap, &mInfo);
AndroidBitmap_lockPixels(mEnv, mBitmap, &mData);
AndroidBitmap_getInfo(env, mBitmap, &mInfo);
AndroidBitmap_lockPixels(env, mBitmap, &mData);
}
}
~AutoBitmap() noexcept {
releaseCallbackJni(mEnv, mCallbackUtils, mHandler, mCallback);
void release(JNIEnv* env) {
if (mBitmap) {
AndroidBitmap_unlockPixels(mEnv, mBitmap);
mEnv->DeleteGlobalRef(mBitmap);
AndroidBitmap_unlockPixels(env, mBitmap);
env->DeleteGlobalRef(mBitmap);
}
}
AutoBitmap(AutoBitmap &&rhs) noexcept {
mEnv = rhs.mEnv;
std::swap(mData, rhs.mData);
std::swap(mBitmap, rhs.mBitmap);
std::swap(mInfo, rhs.mInfo);
}
~AutoBitmap() override = default;
public:
void* getData() const noexcept {
return mData;
}
@@ -546,28 +539,39 @@ public:
}
}
static void invoke(void* buffer, size_t n, void* user) {
AutoBitmap* data = reinterpret_cast<AutoBitmap*>(user);
delete data;
}
static AutoBitmap* make(Engine* engine, JNIEnv* env, jobject bitmap) {
return new AutoBitmap(env, bitmap);
}
static AutoBitmap* make(Engine* engine, JNIEnv* env, jobject bitmap,
jobject handler, jobject runnable) {
// create a AutoBitmap
static AutoBitmap* make(JNIEnv* env, jobject bitmap, jobject handler, jobject runnable) {
return new AutoBitmap(env, bitmap, handler, runnable);
}
// execute the callback on the java thread and destroy ourselves
static void invoke(void*, size_t, void* user) {
auto* autoBitmap = reinterpret_cast<AutoBitmap*>(user);
JNIEnv* env = filament::VirtualMachineEnv::get().getEnvironment();
releaseCallbackJni(env, autoBitmap->mCallbackUtils, autoBitmap->mHandler, autoBitmap->mCallback);
autoBitmap->release(env);
delete autoBitmap;
}
// create a AutoBitmap without a handler
static AutoBitmap* make(JNIEnv* env, jobject bitmap) {
return new AutoBitmap(env, bitmap);
}
// just destroy ourselves
static void invokeNoCallback(void*, size_t, void* user) {
auto* autoBitmap = reinterpret_cast<AutoBitmap*>(user);
JNIEnv* env = filament::VirtualMachineEnv::get().getEnvironment();
autoBitmap->release(env);
delete autoBitmap;
}
private:
JNIEnv* mEnv;
void* mData = nullptr;
jobject mBitmap = nullptr;
jobject mHandler = nullptr;
jobject mCallback = nullptr;
AndroidBitmapInfo mInfo{};
CallbackJni mCallbackUtils;
};
extern "C"
@@ -578,14 +582,14 @@ Java_com_google_android_filament_android_TextureHelper_nSetBitmap(JNIEnv* env, j
Texture* texture = (Texture*) nativeTexture;
Engine *engine = (Engine *) nativeEngine;
auto* autoBitmap = AutoBitmap::make(engine, env, bitmap);
auto* autoBitmap = AutoBitmap::make(env, bitmap);
Texture::PixelBufferDescriptor desc(
autoBitmap->getData(),
autoBitmap->getSizeInBytes(),
autoBitmap->getFormat(format),
autoBitmap->getType(format),
&AutoBitmap::invoke, autoBitmap);
&AutoBitmap::invokeNoCallback, autoBitmap);
texture->setImage(*engine, (size_t) level,
(uint32_t) xoffset, (uint32_t) yoffset,
@@ -601,14 +605,14 @@ Java_com_google_android_filament_android_TextureHelper_nSetBitmapWithCallback(JN
Texture* texture = (Texture*) nativeTexture;
Engine *engine = (Engine *) nativeEngine;
auto* autoBitmap = AutoBitmap::make(engine, env, bitmap, handler, runnable);
auto* autoBitmap = AutoBitmap::make(env, bitmap, handler, runnable);
Texture::PixelBufferDescriptor desc(
autoBitmap->getData(),
autoBitmap->getSizeInBytes(),
autoBitmap->getFormat(format),
autoBitmap->getType(format),
&AutoBitmap::invoke, autoBitmap);
autoBitmap->getHandler(), &AutoBitmap::invoke, autoBitmap);
texture->setImage(*engine, (size_t) level,
(uint32_t) xoffset, (uint32_t) yoffset,

View File

@@ -49,8 +49,8 @@ Java_com_google_android_filament_ToneMapper_nCreateFilmicToneMapper(JNIEnv*, jcl
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_ToneMapper_nCreateGenericToneMapper(JNIEnv*, jclass,
jfloat contrast, jfloat shoulder, jfloat midGrayIn, jfloat midGrayOut, jfloat hdrMax) {
return (jlong) new GenericToneMapper(contrast, shoulder, midGrayIn, midGrayOut, hdrMax);
jfloat contrast, jfloat midGrayIn, jfloat midGrayOut, jfloat hdrMax) {
return (jlong) new GenericToneMapper(contrast, midGrayIn, midGrayOut, hdrMax);
}
extern "C" JNIEXPORT jfloat JNICALL
@@ -58,11 +58,6 @@ Java_com_google_android_filament_ToneMapper_nGenericGetContrast(JNIEnv*, jclass,
return ((GenericToneMapper*) nativeObject)->getContrast();
}
extern "C" JNIEXPORT jfloat JNICALL
Java_com_google_android_filament_ToneMapper_nGenericGetShoulder(JNIEnv*, jclass, jlong nativeObject) {
return ((GenericToneMapper*) nativeObject)->getShoulder();
}
extern "C" JNIEXPORT jfloat JNICALL
Java_com_google_android_filament_ToneMapper_nGenericGetMidGrayIn(JNIEnv*, jclass, jlong nativeObject) {
return ((GenericToneMapper*) nativeObject)->getMidGrayIn();
@@ -84,12 +79,6 @@ Java_com_google_android_filament_ToneMapper_nGenericSetContrast(JNIEnv*, jclass,
((GenericToneMapper*) nativeObject)->setContrast(contrast);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_ToneMapper_nGenericSetShoulder(JNIEnv*, jclass,
jlong nativeObject, jfloat shoulder) {
((GenericToneMapper*) nativeObject)->setShoulder(shoulder);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_ToneMapper_nGenericSetMidGrayIn(JNIEnv*, jclass,
jlong nativeObject, jfloat midGrayIn) {

View File

@@ -149,18 +149,27 @@ Java_com_google_android_filament_View_nSetShadowType(JNIEnv*, jclass, jlong nati
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetVsmShadowOptions(JNIEnv*, jclass, jlong nativeView,
jint anisotropy, jboolean mipmapping, jfloat exponent, jfloat minVarianceScale,
jint anisotropy, jboolean mipmapping, jfloat minVarianceScale,
jfloat lightBleedReduction) {
View* view = (View*) nativeView;
View::VsmShadowOptions options;
options.anisotropy = (uint8_t)anisotropy;
options.mipmapping = (bool)mipmapping;
options.exponent = exponent;
options.minVarianceScale = minVarianceScale;
options.lightBleedReduction = lightBleedReduction;
view->setVsmShadowOptions(options);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetSoftShadowOptions(JNIEnv*, jclass, jlong nativeView,
jfloat penumbraScale, jfloat penumbraRatioScale) {
View* view = (View*) nativeView;
View::SoftShadowOptions options;
options.penumbraScale = penumbraScale;
options.penumbraRatioScale = penumbraRatioScale;
view->setSoftShadowOptions(options);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetRenderQuality(JNIEnv*, jclass,
@@ -381,6 +390,16 @@ Java_com_google_android_filament_View_nSetTemporalAntiAliasingOptions(JNIEnv *,
.filterWidth = filterWidth, .feedback = feedback, .enabled = (bool) enabled});
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetScreenSpaceReflectionsOptions(JNIEnv*, jclass,
jlong nativeView, jfloat thickness, jfloat bias, jfloat maxDistance, jfloat stride, jboolean enabled) {
View* view = (View*) nativeView;
view->setScreenSpaceReflectionsOptions({.thickness = thickness, .bias = bias,
.maxDistance = maxDistance, .stride = stride, .enabled = (bool) enabled
});
}
extern "C"
JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_View_nIsShadowingEnabled(JNIEnv *, jclass, jlong nativeView) {

View File

@@ -105,6 +105,14 @@ public class ColorGrading {
ULTRA
}
/**
* Color grading LUT format.
*/
public enum LutFormat {
INTEGER,
FLOAT
}
/**
* List of available tone-mapping operators.
*
@@ -162,6 +170,36 @@ public class ColorGrading {
return this;
}
/**
* When color grading is implemented using a 3D LUT, this sets the texture format of
* of the LUT. This overrides the value set by quality().
*
* The default is INTEGER
*
* @param format The desired format of the 3D LUT.
*
* @return This Builder, for chaining calls
*/
public Builder format(LutFormat format) {
nBuilderFormat(mNativeBuilder, format.ordinal());
return this;
}
/**
* When color grading is implemented using a 3D LUT, this sets the dimension of the LUT.
* This overrides the value set by quality().
*
* The default is 32
*
* @param dim The desired dimension of the LUT. Between 16 and 64.
*
* @return This Builder, for chaining calls
*/
public Builder dimensions(int dim) {
nBuilderDimensions(mNativeBuilder, dim);
return this;
}
/**
* Selects the tone mapping operator to apply to the HDR color buffer as the last
* operation of the color grading post-processing step.
@@ -557,6 +595,8 @@ public class ColorGrading {
private static native void nDestroyBuilder(long nativeBuilder);
private static native void nBuilderQuality(long nativeBuilder, int quality);
private static native void nBuilderFormat(long nativeBuilder, int format);
private static native void nBuilderDimensions(long nativeBuilder, int dim);
private static native void nBuilderToneMapper(long nativeBuilder, long toneMapper);
private static native void nBuilderToneMapping(long nativeBuilder, int toneMapping);
private static native void nBuilderLuminanceScaling(long nativeBuilder, boolean luminanceScaling);

View File

@@ -106,7 +106,10 @@ import com.google.android.filament.proguard.UsedByReflection;
* @see Renderer
*/
public class Engine {
private static final Backend[] sBackendValues = Backend.values();
private long mNativeObject;
@NonNull private final TransformManager mTransformManager;
@NonNull private final LightManager mLightManager;
@NonNull private final RenderableManager mRenderableManager;
@@ -252,7 +255,7 @@ public class Engine {
*/
@NonNull
public Backend getBackend() {
return Backend.values()[(int) nGetBackend(getNativeObject())];
return sBackendValues[(int) nGetBackend(getNativeObject())];
}
// SwapChain
@@ -513,6 +516,15 @@ public class Engine {
vertexBuffer.clearNativeObject();
}
/**
* Destroys a {@link SkinningBuffer} and frees all its associated resources.
* @param skinningBuffer the {@link SkinningBuffer} to destroy
*/
public void destroySkinningBuffer(@NonNull SkinningBuffer skinningBuffer) {
assertDestroy(nDestroySkinningBuffer(getNativeObject(), skinningBuffer.getNativeObject()));
skinningBuffer.clearNativeObject();
}
/**
* Destroys a {@link IndirectLight} and frees all its associated resources.
* @param ibl the {@link IndirectLight} to destroy
@@ -690,6 +702,7 @@ public class Engine {
private static native boolean nDestroyStream(long nativeEngine, long nativeStream);
private static native boolean nDestroyIndexBuffer(long nativeEngine, long nativeIndexBuffer);
private static native boolean nDestroyVertexBuffer(long nativeEngine, long nativeVertexBuffer);
private static native boolean nDestroySkinningBuffer(long nativeEngine, long nativeSkinningBuffer);
private static native boolean nDestroyIndirectLight(long nativeEngine, long nativeIndirectLight);
private static native boolean nDestroyMaterial(long nativeEngine, long nativeMaterial);
private static native boolean nDestroyMaterialInstance(long nativeEngine, long nativeMaterialInstance);

View File

@@ -117,6 +117,8 @@ import androidx.annotation.Size;
* </ul>
*/
public class LightManager {
private static final Type[] sTypeValues = Type.values();
private long mNativeObject;
LightManager(long nativeLightManager) {
@@ -244,13 +246,13 @@ public class LightManager {
* light. 1mm by default.
* This is ignored when the View's ShadowType is set to VSM.
*/
public float constantBias = 0.05f;
public float constantBias = 0.001f;
/** Amount by which the maximum sampling error is scaled. The resulting value is used
* to move the shadow away from the fragment normal. Should be 1.0.
* This is ignored when the View's ShadowType is set to VSM.
*/
public float normalBias = 0.4f;
public float normalBias = 1.0f;
/** Distance from the camera after which shadows are clipped. This is used to clip
* shadows that are too far and wouldn't contribute to the scene much, improving
@@ -279,7 +281,24 @@ public class LightManager {
* When set to true, all resolution enhancing features that can affect stability are
* disabling, resulting in significantly lower resolution shadows, albeit stable ones.
*/
public boolean stable = true;
public boolean stable = false;
/**
* Constant bias in depth-resolution units by which shadows are moved away from the
* light. The default value of 0.5 is used to round depth values up.
* Generally this value shouldn't be changed or at least be small and positive.
* This is ignored when the View's ShadowType is set to VSM.
*/
float polygonOffsetConstant = 0.5f;
/**
* Bias based on the change in depth in depth-resolution units by which shadows are moved
* away from the light. The default value of 2.0 works well with SHADOW_SAMPLING_PCF_LOW.
* Generally this value is between 0.5 and the size in texel of the PCF filter.
* Setting this value correctly is essential for LISPSM shadow-maps.
* This is ignored when the View's ShadowType is set to VSM.
*/
float polygonOffsetSlope = 2.0f;
/**
* Whether screen-space contact shadows are used. This applies regardless of whether a
@@ -332,6 +351,12 @@ public class LightManager {
* The maximum value is 125.
*/
public float blurWidth = 0.0f;
/**
* Light bulb radius used for soft shadows. Currently this is only used when DPCF is
* enabled. (2cm by default).
*/
public float shadowBulbRadius = 0.02f;
}
public static class ShadowCascades {
@@ -471,9 +496,11 @@ public class LightManager {
nBuilderShadowOptions(mNativeBuilder,
options.mapSize, options.shadowCascades, options.cascadeSplitPositions,
options.constantBias, options.normalBias, options.shadowFar, options.shadowNearHint,
options.shadowFarHint, options.stable, options.screenSpaceContactShadows,
options.shadowFarHint, options.stable,
options.polygonOffsetConstant, options.polygonOffsetSlope,
options.screenSpaceContactShadows,
options.stepCount, options.maxShadowDistance, options.vsmMsaaSamples,
options.blurWidth);
options.blurWidth, options.shadowBulbRadius);
return this;
}
@@ -762,7 +789,7 @@ public class LightManager {
@NonNull
public Type getType(@EntityInstance int i) {
return Type.values()[nGetType(mNativeObject, i)];
return sTypeValues[nGetType(mNativeObject, i)];
}
/**
@@ -1131,7 +1158,7 @@ public class LightManager {
private static native void nDestroyBuilder(long nativeBuilder);
private static native boolean nBuilderBuild(long nativeBuilder, long nativeEngine, int entity);
private static native void nBuilderCastShadows(long nativeBuilder, boolean enable);
private static native void nBuilderShadowOptions(long nativeBuilder, int mapSize, int cascades, float[] splitPositions, float constantBias, float normalBias, float shadowFar, float shadowNearHint, float shadowFarhint, boolean stable, boolean screenSpaceContactShadows, int stepCount, float maxShadowDistance, int vsmMsaaSamples, float blurWidth);
private static native void nBuilderShadowOptions(long nativeBuilder, int mapSize, int cascades, float[] splitPositions, float constantBias, float normalBias, float shadowFar, float shadowNearHint, float shadowFarhint, boolean stable, float polygonOffsetConstant, float polygonOffsetSlope, boolean screenSpaceContactShadows, int stepCount, float maxShadowDistance, int vsmMsaaSamples, float blurWidth, float shadowBulbRadius);
private static native void nBuilderCastLight(long nativeBuilder, boolean enabled);
private static native void nBuilderPosition(long nativeBuilder, float x, float y, float z);
private static native void nBuilderDirection(long nativeBuilder, float x, float y, float z);

View File

@@ -37,6 +37,20 @@ import java.util.Set;
* @see <a href="https://google.github.io/filament/Materials.html">Filament Materials Guide</a>
*/
public class Material {
static final class EnumCache {
private EnumCache() { }
static final Shading[] sShadingValues = Shading.values();
static final Interpolation[] sInterpolationValues = Interpolation.values();
static final BlendingMode[] sBlendingModeValues = BlendingMode.values();
static final RefractionMode[] sRefractionModeValues = RefractionMode.values();
static final RefractionType[] sRefractionTypeValues = RefractionType.values();
static final VertexDomain[] sVertexDomainValues = VertexDomain.values();
static final CullingMode[] sCullingModeValues = CullingMode.values();
static final VertexBuffer.VertexAttribute[] sVertexAttributeValues =
VertexBuffer.VertexAttribute.values();
}
private long mNativeObject;
private final MaterialInstance mDefaultInstance;
@@ -210,6 +224,8 @@ public class Material {
@UsedByNative("Material.cpp")
public static class Parameter {
private static final Type[] sTypeValues = Type.values();
public enum Type {
BOOL,
BOOL2,
@@ -275,7 +291,7 @@ public class Material {
@IntRange(from = 0) int type, @IntRange(from = 0) int precision,
@IntRange(from = 1) int count) {
parameters.add(
new Parameter(name, Type.values()[type], Precision.values()[precision], count));
new Parameter(name, sTypeValues[type], Precision.values()[precision], count));
}
}
@@ -373,7 +389,7 @@ public class Material {
* Material Models</a>
*/
public Shading getShading() {
return Shading.values()[nGetShading(getNativeObject())];
return EnumCache.sShadingValues[nGetShading(getNativeObject())];
}
/**
@@ -384,7 +400,7 @@ public class Material {
* Vertex and attributes: interpolation</a>
*/
public Interpolation getInterpolation() {
return Interpolation.values()[nGetInterpolation(getNativeObject())];
return EnumCache.sInterpolationValues[nGetInterpolation(getNativeObject())];
}
/**
@@ -395,7 +411,7 @@ public class Material {
* Blending and transparency: blending</a>
*/
public BlendingMode getBlendingMode() {
return BlendingMode.values()[nGetBlendingMode(getNativeObject())];
return EnumCache.sBlendingModeValues[nGetBlendingMode(getNativeObject())];
}
/**
@@ -406,7 +422,7 @@ public class Material {
* Blending and transparency: refraction</a>
*/
public RefractionMode getRefractionMode() {
return RefractionMode.values()[nGetRefractionMode(getNativeObject())];
return EnumCache.sRefractionModeValues[nGetRefractionMode(getNativeObject())];
}
/**
@@ -417,10 +433,9 @@ public class Material {
* Blending and transparency: refractionType</a>
*/
public RefractionType getRefractionType() {
return RefractionType.values()[nGetRefractionType(getNativeObject())];
return EnumCache.sRefractionTypeValues[nGetRefractionType(getNativeObject())];
}
/**
* Returns the vertex domain of this material.
*
@@ -429,7 +444,7 @@ public class Material {
* Vertex and attributes: vertexDomain</a>
*/
public VertexDomain getVertexDomain() {
return VertexDomain.values()[nGetVertexDomain(getNativeObject())];
return EnumCache.sVertexDomainValues[nGetVertexDomain(getNativeObject())];
}
/**
@@ -440,7 +455,7 @@ public class Material {
* Rasterization: culling</a>
*/
public CullingMode getCullingMode() {
return CullingMode.values()[nGetCullingMode(getNativeObject())];
return EnumCache.sCullingModeValues[nGetCullingMode(getNativeObject())];
}
/**
@@ -531,7 +546,7 @@ public class Material {
if (mRequiredAttributes == null) {
int bitSet = nGetRequiredAttributes(getNativeObject());
mRequiredAttributes = EnumSet.noneOf(VertexBuffer.VertexAttribute.class);
VertexBuffer.VertexAttribute[] values = VertexBuffer.VertexAttribute.values();
VertexBuffer.VertexAttribute[] values = EnumCache.sVertexAttributeValues;
for (int i = 0; i < values.length; i++) {
if ((bitSet & (1 << i)) != 0) {
mRequiredAttributes.add(values[i]);

View File

@@ -239,6 +239,10 @@ public class MaterialInstance {
/**
* Sets a texture and sampler parameter on this material's default instance.
* <p>
* Note: Depth textures can't be sampled with a linear filter unless the comparison mode is set
* to COMPARE_TO_TEXTURE.
* </p>
*
* @param name The name of the material texture parameter
* @param texture The texture to set as parameter

View File

@@ -0,0 +1,177 @@
/*
* 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.
*/
package com.google.android.filament;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import java.nio.Buffer;
import java.nio.BufferOverflowException;
import java.nio.FloatBuffer;
public class MorphTargetBuffer {
private long mNativeObject;
private MorphTargetBuffer(long nativeMorphTargetBuffer) {
mNativeObject = nativeMorphTargetBuffer;
}
public static class Builder {
@SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
// Keep to finalize native resources
private final MorphTargetBuffer.Builder.BuilderFinalizer mFinalizer;
private final long mNativeBuilder;
public Builder() {
mNativeBuilder = nCreateBuilder();
mFinalizer = new MorphTargetBuffer.Builder.BuilderFinalizer(mNativeBuilder);
}
/**
* Size of the morph targets in vertex counts.
*
* @param vertexCount Number of vertex counts the morph targets can hold.
* @return this <code>Builder</code> object for chaining calls
*/
@NonNull
public Builder vertexCount(@IntRange(from = 1) int vertexCount) {
nBuilderVertexCount(mNativeBuilder, vertexCount);
return this;
}
/**
* Size of the morph targets in targets.
*
* @param count Number of targets the morph targets can hold.
* @return this <code>Builder</code> object for chaining calls
*/
@NonNull
public Builder count(@IntRange(from = 1) int count) {
nBuilderCount(mNativeBuilder, count);
return this;
}
/**
* Creates and returns the <code>MorphTargetBuffer</code> object.
*
* @param engine reference to the {@link Engine} to associate this <code>MorphTargetBuffer</code>
* with.
*
* @return the newly created <code>MorphTargetBuffer</code> object
*
* @exception IllegalStateException if the MorphTargetBuffer could not be created
*
* @see #setMorphTargetBufferAt
*/
@NonNull
public MorphTargetBuffer build(@NonNull Engine engine) {
long nativeMorphTargetBuffer = nBuilderBuild(mNativeBuilder, engine.getNativeObject());
if (nativeMorphTargetBuffer == 0)
throw new IllegalStateException("Couldn't create MorphTargetBuffer");
return new MorphTargetBuffer(nativeMorphTargetBuffer);
}
private static class BuilderFinalizer {
private final long mNativeObject;
BuilderFinalizer(long nativeObject) {
mNativeObject = nativeObject;
}
@Override
public void finalize() {
try {
super.finalize();
} catch (Throwable t) { // Ignore
} finally {
nDestroyBuilder(mNativeObject);
}
}
}
}
/**
* 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 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,
@NonNull float[] positions, @IntRange(from = 0, to = 125) int count) {
int result = nSetPositionsAt(mNativeObject, engine.getNativeObject(), targetIndex,
positions, count);
if (result < 0) {
throw new BufferOverflowException();
}
}
/**
* 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 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,
@NonNull short[] tangents, @IntRange(from = 0, to = 125) int count) {
int result = nSetTangentsAt(mNativeObject, engine.getNativeObject(), targetIndex,
tangents, count);
if (result < 0) {
throw new BufferOverflowException();
}
}
/**
* @return number of vertex count in this {@link MorphTargetBuffer}
*/
public int getVertexCount() {
return nGetVertexCount(mNativeObject);
}
/**
* @return number of target count in this {@link MorphTargetBuffer}
*/
public int getCount() {
return nGetCount(mNativeObject);
}
public long getNativeObject() {
if (mNativeObject == 0) {
throw new IllegalStateException("Calling method on destroyed MorphTargetBuffer");
}
return mNativeObject;
}
void clearNativeObject() {
mNativeObject = 0;
}
private static native long nCreateBuilder();
private static native void nDestroyBuilder(long nativeBuilder);
private static native void nBuilderVertexCount(long nativeBuilder, int vertexCount);
private static native void nBuilderCount(long nativeBuilder, int count);
private static native long nBuilderBuild(long nativeBuilder, long nativeEngine);
private static native int nSetPositionsAt(long nativeObject, long nativeEngine, int targetIndex, float[] positions, int count);
private static native int nSetTangentsAt(long nativeObject, long nativeEngine, int targetIndex, short[] tangents, int count);
private static native int nGetVertexCount(long nativeObject);
private static native int nGetCount(long nativeObject);
}

View File

@@ -31,8 +31,10 @@ import androidx.annotation.Nullable;
* @see View
*/
public class RenderTarget {
private long mNativeObject;
private static final int ATTACHMENT_COUNT = AttachmentPoint.values().length;
private static final Texture.CubemapFace[] sCubemapFaceValues = Texture.CubemapFace.values();
private long mNativeObject;
private final Texture[] mTextures = new Texture[ATTACHMENT_COUNT];
private RenderTarget(long nativeRenderTarget, Builder builder) {
@@ -194,7 +196,7 @@ public class RenderTarget {
* a cubemap.
*/
public Texture.CubemapFace getFace(AttachmentPoint attachment) {
return Texture.CubemapFace.values()[nGetFace(getNativeObject(), attachment.ordinal())];
return sCubemapFaceValues[nGetFace(getNativeObject(), attachment.ordinal())];
}
/**

View File

@@ -58,6 +58,10 @@ import java.util.Set;
*/
public class RenderableManager {
private static final String LOG_TAG = "Filament";
private static final VertexBuffer.VertexAttribute[] sVertexAttributeValues =
VertexBuffer.VertexAttribute.values();
private long mNativeObject;
RenderableManager(long nativeRenderableManager) {
@@ -92,7 +96,9 @@ public class RenderableManager {
public enum PrimitiveType {
POINTS(0),
LINES(1),
TRIANGLES(4);
LINE_STRIP(3),
TRIANGLES(4),
TRIANGLE_STRIP(5);
private final int mType;
PrimitiveType(int value) { mType = value; }
@@ -278,6 +284,22 @@ public class RenderableManager {
return this;
}
/**
* Specifies the number of draw instance of this renderable. The default is 1 instance and
* the maximum number of instances allowed is 65535. 0 is invalid.
* All instances are culled using the same bounding box, so care must be taken to make
* sure all instances render inside the specified bounding box.
* The material can use getInstanceIndex() in the vertex shader to get the instance index and
* possibly adjust the position or transform.
*
* @param instanceCount the number of instances silently clamped between 1 and 65535.
*/
@NonNull
public Builder instances(@IntRange(from = 1, to = 65535) int instanceCount) {
nBuilderInstances(mNativeBuilder, instanceCount);
return this;
}
/**
* Controls if this renderable casts shadows, false by default.
*
@@ -394,17 +416,67 @@ public class RenderableManager {
}
/**
* Controls if the renderable has vertex morphing targets, false by default.
* Controls if the renderable has vertex morphing targets, zero by default. This is
* required to enable GPU morphing.
*
* <p>This is required to enable GPU morphing for up to 4 attributes. The attached VertexBuffer
* must provide data in the appropriate VertexAttribute slots (<code>MORPH_POSITION_0</code> etc).</p>
* <p>Filament supports two morphing modes: standard (default) and legacy.</p>
*
* <p>For standard morphing, A {@link MorphTargetBuffer} must be created and provided via
* {@link RenderableManager#setMorphTargetBufferAt}. Standard morphing supports up to
* <code>CONFIG_MAX_MORPH_TARGET_COUNT</code> morph targets.</p>
*
* For legacy morphing, the attached {@link VertexBuffer} must provide data in the
* appropriate {@link VertexBuffer.VertexAttribute} slots (<code>MORPH_POSITION_0</code> etc).
* Legacy morphing only supports up to 4 morph targets and will be deprecated in the future.
* Legacy morphing must be enabled on the material definition: either via the
* <code>legacyMorphing</code> material attribute or by calling
* {@link MaterialBuilder::useLegacyMorphing}.
*
* <p>See also {@link RenderableManager#setMorphWeights}, which can be called on a per-frame basis
* to advance the animation.</p>
*/
@NonNull
public Builder morphing(boolean enabled) {
nBuilderMorphing(mNativeBuilder, enabled);
public Builder morphing(@IntRange(from = 0, to = 255) int targetCount) {
nBuilderMorphing(mNativeBuilder, targetCount);
return this;
}
/**
* Specifies the morph target buffer for a primitive.
*
* The morph target buffer must have an associated renderable and geometry. Two conditions
* must be met:
* 1. The number of morph targets in the buffer must equal the renderable's morph target
* count.
* 2. The vertex count of each morph target must equal the geometry's vertex count.
*
* @param level the level of detail (lod), only 0 can be specified
* @param primitiveIndex zero-based index of the primitive, must be less than the count passed to Builder constructor
* @param morphTargetBuffer specifies the morph target buffer
* @param offset specifies where in the morph target buffer to start reading (expressed as a number of vertices)
* @param count number of vertices in the morph target buffer to read, must equal the geometry's count (for triangles, this should be a multiple of 3)
*/
@NonNull
public Builder morphing(@IntRange(from = 0) int level,
@IntRange(from = 0) int primitiveIndex,
@NonNull MorphTargetBuffer morphTargetBuffer,
@IntRange(from = 0) int offset,
@IntRange(from = 0) int count) {
nBuilderSetMorphTargetBufferAt(mNativeBuilder, level, primitiveIndex,
morphTargetBuffer.getNativeObject(), offset, count);
return this;
}
/**
* Utility method to specify morph target buffer for a primitive.
* For details, see the {@link RenderableManager.Builder#morphing}.
*/
@NonNull
public Builder morphing(@IntRange(from = 0) int level,
@IntRange(from = 0) int primitiveIndex,
@NonNull MorphTargetBuffer morphTargetBuffer) {
nBuilderSetMorphTargetBufferAt(mNativeBuilder, level, primitiveIndex,
morphTargetBuffer.getNativeObject(), 0, morphTargetBuffer.getVertexCount());
return this;
}
@@ -491,15 +563,50 @@ public class RenderableManager {
/**
* Updates the vertex morphing weights on a renderable, all zeroes by default.
*
* <p>This is specified using a 4-tuple, one float per morph target. If the renderable has fewer
* than 4 morph targets, then clients should fill the unused components with zeroes.</p>
* <p>The renderable must be built with morphing enabled. In legacy morphing mode, only the
* first 4 weights are considered.</p>
*
* @see Builder#morphing
*/
public void setMorphWeights(@EntityInstance int i, @NonNull float[] weights, @IntRange(from = 0) int offset) {
nSetMorphWeights(mNativeObject, i, weights, offset);
}
/**
* Changes the morph target buffer for the given primitive.
*
* <p>The renderable must be built with morphing enabled.</p>
*
* @see Builder#morphing
*/
public void setMorphWeights(@EntityInstance int i, @NonNull @Size(min = 4) float[] weights) {
nSetMorphWeights(mNativeObject, i, weights);
public void setMorphTargetBufferAt(@EntityInstance int i,
@IntRange(from = 0) int level,
@IntRange(from = 0) int primitiveIndex,
@NonNull MorphTargetBuffer morphTargetBuffer,
@IntRange(from = 0) int offset,
@IntRange(from = 0) int count) {
nSetMorphTargetBufferAt(mNativeObject, i, level, primitiveIndex,
morphTargetBuffer.getNativeObject(), offset, count);
}
/**
* Utility method to change morph target buffer for the given primitive.
* For details, see the {@link RenderableManager#setMorphTargetBufferAt}.
*/
public void setMorphTargetBufferAt(@EntityInstance int i,
@IntRange(from = 0) int level,
@IntRange(from = 0) int primitiveIndex,
@NonNull MorphTargetBuffer morphTargetBuffer) {
nSetMorphTargetBufferAt(mNativeObject, i, level, primitiveIndex,
morphTargetBuffer.getNativeObject(), 0, morphTargetBuffer.getVertexCount());
}
/**
* Gets the morph target count on a renderable.
*/
@IntRange(from = 0)
public int getMorphTargetCount(@EntityInstance int i) {
return nGetMorphTargetCount(mNativeObject, i);
}
/**
@@ -712,15 +819,19 @@ public class RenderableManager {
/**
* Retrieves the set of enabled attribute slots in the given primitive's VertexBuffer.
*/
public Set<VertexBuffer.VertexAttribute> getEnabledAttributesAt(@EntityInstance int i, @IntRange(from = 0) int primitiveIndex) {
public Set<VertexBuffer.VertexAttribute> getEnabledAttributesAt(
@EntityInstance int i, @IntRange(from = 0) int primitiveIndex) {
int bitSet = nGetEnabledAttributesAt(mNativeObject, i, primitiveIndex);
Set<VertexBuffer.VertexAttribute> requiredAttributes = EnumSet.noneOf(VertexBuffer.VertexAttribute.class);
VertexBuffer.VertexAttribute[] values = VertexBuffer.VertexAttribute.values();
Set<VertexBuffer.VertexAttribute> requiredAttributes =
EnumSet.noneOf(VertexBuffer.VertexAttribute.class);
VertexBuffer.VertexAttribute[] values = sVertexAttributeValues;
for (int j = 0; j < values.length; j++) {
if ((bitSet & (1 << j)) != 0) {
requiredAttributes.add(values[j]);
}
}
requiredAttributes = Collections.unmodifiableSet(requiredAttributes);
return requiredAttributes;
}
@@ -752,14 +863,18 @@ public class RenderableManager {
private static native void nBuilderSkinning(long nativeBuilder, int boneCount);
private static native int nBuilderSkinningBones(long nativeBuilder, int boneCount, Buffer bones, int remaining);
private static native void nBuilderSkinningBuffer(long nativeBuilder, long nativeSkinningBuffer, int boneCount, int offset);
private static native void nBuilderMorphing(long nativeBuilder, boolean enabled);
private static native void nBuilderMorphing(long nativeBuilder, int targetCount);
private static native void nBuilderSetMorphTargetBufferAt(long nativeBuilder, int level, int primitiveIndex, long nativeMorphTargetBuffer, int offset, int count);
private static native void nEnableSkinningBuffers(long nativeBuilder, boolean enabled);
private static native void nBuilderLightChannel(long nativeRenderableManager, int channel, boolean enable);
private static native void nBuilderInstances(long nativeRenderableManager, int instances);
private static native void nSetSkinningBuffer(long nativeObject, int i, long nativeSkinningBuffer, int count, int offset);
private static native int nSetBonesAsMatrices(long nativeObject, int i, Buffer matrices, int remaining, int boneCount, int offset);
private static native int nSetBonesAsQuaternions(long nativeObject, int i, Buffer quaternions, int remaining, int boneCount, int offset);
private static native void nSetMorphWeights(long nativeObject, int instance, float[] weights);
private static native void nSetMorphWeights(long nativeObject, int instance, float[] weights, int offset);
private static native void nSetMorphTargetBufferAt(long nativeObject, int i, int level, int primitiveIndex, long nativeMorphTargetBuffer, int offset, int count);
private static native int nGetMorphTargetCount(long nativeObject, int i);
private static native void nSetAxisAlignedBoundingBox(long nativeRenderableManager, int i, float cx, float cy, float cz, float ex, float ey, float ez);
private static native void nSetLayerMask(long nativeRenderableManager, int i, int select, int value);
private static native void nSetPriority(long nativeRenderableManager, int i, int priority);

View File

@@ -107,12 +107,12 @@ public class Renderer {
/**
* Rate at which the scale will change to reach the target frame rate.
*/
public float scaleRate = 0.125f;
public float scaleRate = 1.0f / 15.0f;
/**
* History size. higher values, tend to filter more (clamped to 30).
* History size. higher values, tend to filter more (clamped to 31).
*/
public int history = 9;
public int history = 15;
}
/**
@@ -309,7 +309,7 @@ public class Renderer {
*
* <p><code>render()</code> generates commands for each of the following stages:</p>
* <ul>
* <li>Shadow map pass, if needed (currently only a single shadow map is supported)</li>
* <li>Shadow map passes, if needed</li>
* <li>Depth pre-pass</li>
* <li>SSAO pass, if enabled</li>
* <li>Color pass</li>
@@ -437,8 +437,9 @@ public class Renderer {
*</pre>
*
*
* <p>Typically <code>readPixels</code> will be called after {@link #render} and before
* {@link #endFrame}.</p>
* <p><code>readPixels</code> must be called within a frame, meaning after {@link #beginFrame}
* and before {@link #endFrame}. Typically, <code>readPixels</code> will be called after
* {@link #render}.</p>
* <br>
* <p>After calling this method, the callback associated with <code>buffer</code>
* will be invoked on the main thread, indicating that the read-back has completed.

View File

@@ -118,8 +118,8 @@ public class SkinningBuffer {
* @param offset Index of the first bone to set
*/
public void setBonesAsMatrices(@NonNull Engine engine,
@NonNull Buffer matrices, @IntRange(from = 0, to = 255) int boneCount,
@IntRange(from = 0) int offset) {
@NonNull Buffer matrices, @IntRange(from = 0, to = 255) int boneCount,
@IntRange(from = 0) int offset) {
int result = nSetBonesAsMatrices(mNativeObject, engine.getNativeObject(),
matrices, matrices.remaining(), boneCount, offset);
if (result < 0) {
@@ -138,8 +138,8 @@ public class SkinningBuffer {
* @param offset Index of the first bone to set
*/
public void setBonesAsQuaternions(@NonNull Engine engine,
@NonNull Buffer quaternions, @IntRange(from = 0, to = 255) int boneCount,
@IntRange(from = 0) int offset) {
@NonNull Buffer quaternions, @IntRange(from = 0, to = 255) int boneCount,
@IntRange(from = 0) int offset) {
int result = nSetBonesAsQuaternions(mNativeObject, engine.getNativeObject(),
quaternions, quaternions.remaining(), boneCount, offset);
if (result < 0) {

View File

@@ -91,6 +91,8 @@ import java.nio.ReadOnlyBufferException;
* @see Engine#destroyStream
*/
public class Stream {
private static final StreamType[] sStreamTypeValues = StreamType.values();
private long mNativeObject;
private long mNativeEngine;
@@ -236,7 +238,7 @@ public class Stream {
* Indicates whether this <code>Stream</code> is NATIVE, TEXTURE_ID, or ACQUIRED.
*/
public StreamType getStreamType() {
return StreamType.values()[nGetStreamType(getNativeObject())];
return sStreamTypeValues[nGetStreamType(getNativeObject())];
}
/**

View File

@@ -71,6 +71,9 @@ import static com.google.android.filament.Texture.Type.COMPRESSED;
* @see MaterialInstance#setParameter(String, Texture, TextureSampler)
*/
public class Texture {
private static final Sampler[] sSamplerValues = Sampler.values();
private static final InternalFormat[] sInternalFormatValues = InternalFormat.values();
private long mNativeObject;
public Texture(long nativeTexture) {
@@ -216,7 +219,38 @@ public class Texture {
ETC2_EAC_RGBA8, ETC2_EAC_SRGBA8,
// Available everywhere except Android/iOS
DXT1_RGB, DXT1_RGBA, DXT3_RGBA, DXT5_RGBA
DXT1_RGB, DXT1_RGBA, DXT3_RGBA, DXT5_RGBA,
DXT1_SRGB, DXT1_SRGBA, DXT3_SRGBA, DXT5_SRGBA,
// ASTC formats are available with a GLES extension
RGBA_ASTC_4x4,
RGBA_ASTC_5x4,
RGBA_ASTC_5x5,
RGBA_ASTC_6x5,
RGBA_ASTC_6x6,
RGBA_ASTC_8x5,
RGBA_ASTC_8x6,
RGBA_ASTC_8x8,
RGBA_ASTC_10x5,
RGBA_ASTC_10x6,
RGBA_ASTC_10x8,
RGBA_ASTC_10x10,
RGBA_ASTC_12x10,
RGBA_ASTC_12x12,
SRGB8_ALPHA8_ASTC_4x4,
SRGB8_ALPHA8_ASTC_5x4,
SRGB8_ALPHA8_ASTC_5x5,
SRGB8_ALPHA8_ASTC_6x5,
SRGB8_ALPHA8_ASTC_6x6,
SRGB8_ALPHA8_ASTC_8x5,
SRGB8_ALPHA8_ASTC_8x6,
SRGB8_ALPHA8_ASTC_8x8,
SRGB8_ALPHA8_ASTC_10x5,
SRGB8_ALPHA8_ASTC_10x6,
SRGB8_ALPHA8_ASTC_10x8,
SRGB8_ALPHA8_ASTC_10x10,
SRGB8_ALPHA8_ASTC_12x10,
SRGB8_ALPHA8_ASTC_12x12
}
/**
@@ -231,7 +265,38 @@ public class Texture {
ETC2_EAC_RGBA8, ETC2_EAC_SRGBA8,
// Available everywhere except Android/iOS
DXT1_RGB, DXT1_RGBA, DXT3_RGBA, DXT5_RGBA
DXT1_RGB, DXT1_RGBA, DXT3_RGBA, DXT5_RGBA,
DXT1_SRGB, DXT1_SRGBA, DXT3_SRGBA, DXT5_SRGBA,
// ASTC formats are available with a GLES extension
RGBA_ASTC_4x4,
RGBA_ASTC_5x4,
RGBA_ASTC_5x5,
RGBA_ASTC_6x5,
RGBA_ASTC_6x6,
RGBA_ASTC_8x5,
RGBA_ASTC_8x6,
RGBA_ASTC_8x8,
RGBA_ASTC_10x5,
RGBA_ASTC_10x6,
RGBA_ASTC_10x8,
RGBA_ASTC_10x10,
RGBA_ASTC_12x10,
RGBA_ASTC_12x12,
SRGB8_ALPHA8_ASTC_4x4,
SRGB8_ALPHA8_ASTC_5x4,
SRGB8_ALPHA8_ASTC_5x5,
SRGB8_ALPHA8_ASTC_6x5,
SRGB8_ALPHA8_ASTC_6x6,
SRGB8_ALPHA8_ASTC_8x5,
SRGB8_ALPHA8_ASTC_8x6,
SRGB8_ALPHA8_ASTC_8x8,
SRGB8_ALPHA8_ASTC_10x5,
SRGB8_ALPHA8_ASTC_10x6,
SRGB8_ALPHA8_ASTC_10x8,
SRGB8_ALPHA8_ASTC_10x10,
SRGB8_ALPHA8_ASTC_12x10,
SRGB8_ALPHA8_ASTC_12x12
}
/**
@@ -477,7 +542,7 @@ public class Texture {
* @param alignment Alignment in bytes.
* @return Size of the buffer in bytes.
*/
static int computeDataSize(@NonNull Format format, @NonNull Type type,
public static int computeDataSize(@NonNull Format format, @NonNull Type type,
int stride, int height, @IntRange(from = 1, to = 8) int alignment) {
if (type == Type.COMPRESSED) {
return 0;
@@ -805,7 +870,7 @@ public class Texture {
*/
@NonNull
public Sampler getTarget() {
return Sampler.values()[nGetTarget(getNativeObject())];
return sSamplerValues[nGetTarget(getNativeObject())];
}
/**
@@ -813,7 +878,7 @@ public class Texture {
*/
@NonNull
public InternalFormat getFormat() {
return InternalFormat.values()[nGetInternalFormat(getNativeObject())];
return sInternalFormatValues[nGetInternalFormat(getNativeObject())];
}
// TODO: add a setImage() version that takes an android Bitmap

View File

@@ -22,6 +22,14 @@ import androidx.annotation.NonNull;
* <code>TextureSampler</code> defines how a texture is accessed.
*/
public class TextureSampler {
static final class EnumCache {
static final MinFilter[] sMinFilterValues = MinFilter.values();
static final MagFilter[] sMagFilterValues = MagFilter.values();
static final WrapMode[] sWrapModeValues = WrapMode.values();
static final CompareMode[] sCompareModeValues = CompareMode.values();
static final CompareFunction[] sCompareFunctionValues = CompareFunction.values();
}
public enum WrapMode {
/**
* The edge of the texture extends to infinity.
@@ -202,7 +210,7 @@ public class TextureSampler {
* @return the minification filter
*/
public MinFilter getMinFilter() {
return MinFilter.values()[nGetMinFilter(mSampler)];
return EnumCache.sMinFilterValues[nGetMinFilter(mSampler)];
}
/**
@@ -218,7 +226,7 @@ public class TextureSampler {
* @return the magnification filter
*/
public MagFilter getMagFilter() {
return MagFilter.values()[nGetMagFilter(mSampler)];
return EnumCache.sMagFilterValues[nGetMagFilter(mSampler)];
}
/**
@@ -234,7 +242,7 @@ public class TextureSampler {
* @return the wrapping mode in the s (horizontal) direction
*/
public WrapMode getWrapModeS() {
return WrapMode.values()[nGetWrapModeS(mSampler)];
return EnumCache.sWrapModeValues[nGetWrapModeS(mSampler)];
}
/**
@@ -249,7 +257,7 @@ public class TextureSampler {
* @return the wrapping mode in the t (vertical) direction
*/
public WrapMode getWrapModeT() {
return WrapMode.values()[nGetWrapModeT(mSampler)];
return EnumCache.sWrapModeValues[nGetWrapModeT(mSampler)];
}
/**
@@ -264,7 +272,7 @@ public class TextureSampler {
* @return the wrapping mode in the r (depth) direction
*/
public WrapMode getWrapModeR() {
return WrapMode.values()[nGetWrapModeR(mSampler)];
return EnumCache.sWrapModeValues[nGetWrapModeR(mSampler)];
}
/**
@@ -297,7 +305,7 @@ public class TextureSampler {
* @return the comparison mode
*/
public CompareMode getCompareMode() {
return CompareMode.values()[nGetCompareMode(mSampler)];
return EnumCache.sCompareModeValues[nGetCompareMode(mSampler)];
}
/**
@@ -313,7 +321,7 @@ public class TextureSampler {
* @return the comparison function
*/
public CompareFunction getCompareFunction() {
return CompareFunction.values()[nGetCompareFunction(mSampler)];
return EnumCache.sCompareFunctionValues[nGetCompareFunction(mSampler)];
}
/**

View File

@@ -109,7 +109,6 @@ public class ToneMapper {
* The tone mapping curve is defined by 5 parameters:
* <ul>
* <li>contrast: controls the contrast of the curve</li>
* <li>shoulder: controls the shoulder of the curve, i.e. how quickly scene
* referred values map to output white</li>
* <li>midGrayIn: sets the input middle gray</li>
* <li>midGrayOut: sets the output middle gray</li>
@@ -123,15 +122,14 @@ public class ToneMapper {
* the {@link ACESLegacy} tone mapper. The default values are:
*
* <ul>
* <li>contrast = 1.585f</li>
* <li>shoulder = 0.5f</li>
* <li>contrast = 1.55f</li>
* <li>midGrayIn = 0.18f</li>
* <li>midGrayOut = 0.268f</li>
* <li>midGrayOut = 0.215f</li>
* <li>hdrMax = 10.0f</li>
* </ul>
*/
public Generic() {
this(1.585f, 0.5f, 0.18f, 0.268f, 10.0f);
this(1.55f, 0.18f, 0.215f, 10.0f);
}
/**
@@ -139,16 +137,14 @@ public class ToneMapper {
*
* @param contrast: controls the contrast of the curve, must be > 0.0, values
* in the range 0.5..2.0 are recommended.
* @param shoulder: controls the shoulder of the curve, i.e. how quickly scene
* referred values map to output white, between 0.0 and 1.0.
* @param midGrayIn: sets the input middle gray, between 0.0 and 1.0.
* @param midGrayOut: sets the output middle gray, between 0.0 and 1.0.
* @param hdrMax: defines the maximum input value that will be mapped to
* output white. Must be >= 1.0.
*/
public Generic(
float contrast, float shoulder, float midGrayIn, float midGrayOut, float hdrMax) {
super(nCreateGenericToneMapper(contrast, shoulder, midGrayIn, midGrayOut, hdrMax));
float contrast, float midGrayIn, float midGrayOut, float hdrMax) {
super(nCreateGenericToneMapper(contrast, midGrayIn, midGrayOut, hdrMax));
}
/** Returns the contrast of the curve as a strictly positive value. */
@@ -161,16 +157,6 @@ public class ToneMapper {
nGenericSetContrast(getNativeObject(), contrast);
}
/** Returns how fast scene referred values map to output white as a value between 0.0 and 1.0. */
public float getShoulder() {
return nGenericGetShoulder(getNativeObject());
}
/** Sets how quickly scene referred values map to output white, between 0.0 and 1.0. */
public void setShoulder(float shoulder) {
nGenericSetShoulder(getNativeObject(), shoulder);
}
/** Returns the middle gray point for input values as a value between 0.0 and 1.0. */
public float getMidGrayIn() {
return nGenericGetMidGrayIn(getNativeObject());
@@ -209,17 +195,15 @@ public class ToneMapper {
private static native long nCreateACESLegacyToneMapper();
private static native long nCreateFilmicToneMapper();
private static native long nCreateGenericToneMapper(
float contrast, float shoulder, float midGrayIn, float midGrayOut, float hdrMax);
float contrast, float midGrayIn, float midGrayOut, float hdrMax);
// Generic tone mappper
private static native float nGenericGetContrast(long nativeObject);
private static native float nGenericGetShoulder(long nativeObject);
private static native float nGenericGetMidGrayIn(long nativeObject);
private static native float nGenericGetMidGrayOut(long nativeObject);
private static native float nGenericGetHdrMax(long nativeObject);
private static native void nGenericSetContrast(long nativeObject, float contrast);
private static native void nGenericSetShoulder(long nativeObject, float shoulder);
private static native void nGenericSetMidGrayIn(long nativeObject, float midGrayIn);
private static native void nGenericSetMidGrayOut(long nativeObject, float midGrayOut);
private static native void nGenericSetHdrMax(long nativeObject, float hdrMax);

View File

@@ -59,6 +59,10 @@ import static com.google.android.filament.Colors.LinearColor;
* @see RenderTarget
*/
public class View {
private static final AntiAliasing[] sAntiAliasingValues = AntiAliasing.values();
private static final Dithering[] sDitheringValues = Dithering.values();
private static final AmbientOcclusion[] sAmbientOcclusionValues = AmbientOcclusion.values();
private long mNativeObject;
private String mName;
private Scene mScene;
@@ -75,8 +79,10 @@ public class View {
private VignetteOptions mVignetteOptions;
private ColorGrading mColorGrading;
private TemporalAntiAliasingOptions mTemporalAntiAliasingOptions;
private ScreenSpaceReflectionsOptions mScreenSpaceReflectionsOptions;
private MultiSampleAntiAliasingOptions mMultiSampleAntiAliasingOptions;
private VsmShadowOptions mVsmShadowOptions;
private SoftShadowOptions mSoftShadowOptions;
/**
* Generic quality level.
@@ -330,6 +336,28 @@ public class View {
public boolean enabled = false;
};
/**
* Options for Screen-space Reflections.
* @see View#setScreenSpaceReflectionOptions
*/
public static class ScreenSpaceReflectionsOptions {
/** ray thickness, in world units */
public float thickness = 0.1f;
/** bias, in world units, to prevent self-intersections */
public float bias = 0.01f;
/** maximum distance, in world units, to raycast */
public float maxDistance = 3.0f;
/** stride, in texels, for samples along the ray. */
public float stride = 2.0f;
/** enables or disables screen-space reflections */
public boolean enabled = false;
};
/**
* Options for controlling the Bloom effect
*
@@ -732,7 +760,17 @@ public class View {
/**
* Variance shadows.
*/
VSM
VSM,
/**
* Percentage-closer filtered shadows, with contact hardening simulation.
*/
DPCF,
/**
* Percentage-closer soft shadows
*/
PCSS
}
/**
@@ -760,13 +798,6 @@ public class View {
*/
public boolean mipmapping = false;
/**
* EVSM exponent
* The maximum value permissible is 5.54 for a shadow map in fp16, or 42.0 for a
* shadow map in fp32. Currently the shadow map bit depth is always fp16.
*/
public float exponent = 5.54f;
/**
* VSM minimum variance scale, must be positive.
*/
@@ -778,6 +809,29 @@ public class View {
public float lightBleedReduction = 0.2f;
}
/**
* View-level options for DPCF and PCSS Shadowing.
*
* <strong>Warning: This API is still experimental and subject to change.</strong>
*
* @see View#setSoftShadowOptions
*/
public static class SoftShadowOptions {
/**
* Globally scales the penumbra of all DPCF and PCSS shadows
* Acceptable values are greater than 0
*/
public float penumbraScale = 1.0f;
/**
* Globally scales the computed penumbra ratio of all DPCF and PCSS shadows.
* This effectively controls the strength of contact hardening effect and is useful for
* artistic purposes. Higher values make the shadows become softer faster.
* Acceptable values are equal to or greater than 1.
*/
public float penumbraRatioScale = 1.0f;
}
/**
* Used to select buffers.
*/
@@ -1116,7 +1170,7 @@ public class View {
*/
@NonNull
public AntiAliasing getAntiAliasing() {
return AntiAliasing.values()[nGetAntiAliasing(getNativeObject())];
return sAntiAliasingValues[nGetAntiAliasing(getNativeObject())];
}
/**
@@ -1154,6 +1208,17 @@ public class View {
options.feedback, options.filterWidth, options.enabled);
}
/**
* Enables or disable screen-space reflections. Disabled by default.
*
* @param options screen-space reflections options
*/
public void setScreenSpaceReflectionsOptions(@NonNull ScreenSpaceReflectionsOptions options) {
mScreenSpaceReflectionsOptions = options;
nSetScreenSpaceReflectionsOptions(getNativeObject(), options.thickness, options.bias,
options.maxDistance, options.stride, options.enabled);
}
/**
* Returns temporal anti-aliasing options.
*
@@ -1167,6 +1232,19 @@ public class View {
return mTemporalAntiAliasingOptions;
}
/**
* Returns screen-space reflections options.
*
* @return screen-space reflections options
*/
@NonNull
public ScreenSpaceReflectionsOptions getScreenSpaceReflectionsOptions() {
if (mScreenSpaceReflectionsOptions == null) {
mScreenSpaceReflectionsOptions = new ScreenSpaceReflectionsOptions();
}
return mScreenSpaceReflectionsOptions;
}
/**
* Enables or disables tone-mapping in the post-processing stage. Enabled by default.
*
@@ -1229,7 +1307,7 @@ public class View {
*/
@NonNull
public Dithering getDithering() {
return Dithering.values()[nGetDithering(getNativeObject())];
return sDitheringValues[nGetDithering(getNativeObject())];
}
/**
@@ -1306,21 +1384,26 @@ public class View {
*
* <p>Post-processing includes:</p>
* <ul>
* <li>Tone-mapping & gamma encoding</li>
* <li>Depth-of-field</li>
* <li>Bloom</li>
* <li>Vignetting</li>
* <li>Temporal Anti-aliasing (TAA)</li>
* <li>Color grading & gamma encoding</li>
* <li>Dithering</li>
* <li>MSAA</li>
* <li>FXAA</li>
* <li>Dynamic scaling</li>
* </ul>
*
* <p>
* Disabling post-processing forgoes color correctness as well as anti-aliasing and
* should only be used experimentally (e.g., for UI overlays).
* Disabling post-processing forgoes color correctness as well as some anti-aliasing techniques
* and should only be used for debugging, UI overlays or when using custom render targets
* (see RenderTarget).
* </p>
*
* @param enabled true enables post processing, false disables it
*
* @see #setToneMapping
* @see #setBloomOptions
* @see #setColorGrading
* @see #setAntiAliasing
* @see #setDithering
* @see #setSampleCount
@@ -1415,7 +1498,7 @@ public class View {
public void setVsmShadowOptions(@NonNull VsmShadowOptions options) {
mVsmShadowOptions = options;
nSetVsmShadowOptions(getNativeObject(), options.anisotropy, options.mipmapping,
options.exponent, options.minVarianceScale, options.lightBleedReduction);
options.minVarianceScale, options.lightBleedReduction);
}
/**
@@ -1431,6 +1514,37 @@ public class View {
return mVsmShadowOptions;
}
/**
* Sets soft shadowing options that apply across the entire View.
*
* Additional light-specific VSM options can be set with
* {@link LightManager.Builder#shadowOptions}.
*
* Only applicable when shadow type is set to ShadowType.DPCF.
*
* <strong>Warning: This API is still experimental and subject to change.</strong>
*
* @param options Options for shadowing.
* @see #setShadowType
*/
public void setSoftShadowOptions(@NonNull SoftShadowOptions options) {
mSoftShadowOptions = options;
nSetSoftShadowOptions(getNativeObject(), options.penumbraScale, options.penumbraRatioScale);
}
/**
* Gets soft shadowing options associated with this View.
* @see #setSoftShadowOptions
* @return soft shadow options currently set.
*/
@NonNull
public SoftShadowOptions getSoftShadowOptions() {
if (mSoftShadowOptions == null) {
mSoftShadowOptions = new SoftShadowOptions();
}
return mSoftShadowOptions;
}
/**
* Activates or deactivates ambient occlusion.
* @see #setAmbientOcclusionOptions
@@ -1449,7 +1563,7 @@ public class View {
@Deprecated
@NonNull
public AmbientOcclusion getAmbientOcclusion() {
return AmbientOcclusion.values()[nGetAmbientOcclusion(getNativeObject())];
return sAmbientOcclusionValues[nGetAmbientOcclusion(getNativeObject())];
}
/**
@@ -1696,7 +1810,8 @@ public class View {
private static native void nSetRenderQuality(long nativeView, int hdrColorBufferQuality);
private static native void nSetDynamicLightingOptions(long nativeView, float zLightNear, float zLightFar);
private static native void nSetShadowType(long nativeView, int type);
private static native void nSetVsmShadowOptions(long nativeView, int anisotropy, boolean mipmapping, float exponent, float minVarianceScale, float lightBleedReduction);
private static native void nSetVsmShadowOptions(long nativeView, int anisotropy, boolean mipmapping, float minVarianceScale, float lightBleedReduction);
private static native void nSetSoftShadowOptions(long nativeView, float penumbraScale, float penumbraRatioScale);
private static native void nSetColorGrading(long nativeView, long nativeColorGrading);
private static native void nSetPostProcessingEnabled(long nativeView, boolean enabled);
private static native boolean nIsPostProcessingEnabled(long nativeView);
@@ -1714,6 +1829,7 @@ public class View {
boolean nativeResolution, int foregroundRingCount, int backgroundRingCount, int fastGatherRingCount, int maxForegroundCOC, int maxBackgroundCOC);
private static native void nSetVignetteOptions(long nativeView, float midPoint, float roundness, float feather, float r, float g, float b, float a, boolean enabled);
private static native void nSetTemporalAntiAliasingOptions(long nativeView, float feedback, float filterWidth, boolean enabled);
private static native void nSetScreenSpaceReflectionsOptions(long nativeView, float thickness, float bias, float maxDistance, float stride, boolean enabled);
private static native void nSetMultiSampleAntiAliasingOptions(long nativeView, boolean enabled, int sampleCount, boolean customResolve);
private static native boolean nIsShadowingEnabled(long nativeView);
private static native void nSetScreenSpaceRefractionEnabled(long nativeView, boolean enabled);

View File

@@ -1,30 +1,16 @@
apply plugin: 'kotlin-android'
android {
flavorDimensions "functionality"
productFlavors {
full {
dimension "functionality"
}
lite {
dimension "functionality"
externalNativeBuild {
cmake {
// hack: this is needed because filament-utils-android/CMakeLists.txt builds
// gltfio from source, which needs this defined
arguments.add("-DGLTFIO_LITE=ON")
}
}
}
}
sourceSets {
main {
kotlin.srcDirs += "src/main/java"
}
}
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:
@@ -51,13 +37,11 @@ dependencies {
implementation deps.kotlin
implementation deps.androidx.annotations
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
implementation deps.coroutines.core
implementation deps.coroutines.android
api project(':filament-android')
fullApi module("com.google.android.filament:gltfio-android:${VERSION_NAME}")
liteApi module("com.google.android.filament:gltfio-android-lite:${VERSION_NAME}")
api module("com.google.android.filament:gltfio-android:${VERSION_NAME}")
}
apply from: rootProject.file('gradle/gradle-mvn-push.gradle')
@@ -65,14 +49,9 @@ apply from: rootProject.file('gradle/gradle-mvn-push.gradle')
afterEvaluate {
publishing {
publications {
fullRelease(MavenPublication) {
artifactId = POM_ARTIFACT_ID_FULL
from components.fullRelease
}
liteRelease(MavenPublication) {
artifactId = POM_ARTIFACT_ID_LITE
from components.liteRelease
release(MavenPublication) {
artifactId = POM_ARTIFACT_ID
from components.release
}
}
}

View File

@@ -1,4 +1,3 @@
POM_NAME=Filament Android Utilities
POM_ARTIFACT_ID_FULL=filament-utils-android
POM_ARTIFACT_ID_LITE=filament-utils-android-lite
POM_ARTIFACT_ID=filament-utils-android
POM_PACKAGING=aar

View File

@@ -32,7 +32,9 @@ import androidx.annotation.Size;
* @see Bookmark
*/
public class Manipulator {
private long mNativeObject;
private static final Mode[] sModeValues = Mode.values();
private final long mNativeObject;
private Manipulator(long nativeIndexBuffer) {
mNativeObject = nativeIndexBuffer;
@@ -320,7 +322,7 @@ public class Manipulator {
/**
* Gets the immutable mode of the manipulator.
*/
public Mode getMode() { return Mode.values()[nGetMode(mNativeObject)]; }
public Mode getMode() { return sModeValues[nGetMode(mNativeObject)]; }
/**
* Sets the viewport dimensions in terms of pixels.

View File

@@ -14,6 +14,8 @@
* limitations under the License.
*/
@file:Suppress("unused")
package com.google.android.filament.utils
import kotlin.math.*
@@ -22,6 +24,10 @@ enum class MatrixColumn {
X, Y, Z, W
}
enum class RotationsOrder {
XYZ, XZY, YXZ, YZX, ZXY, ZYX
}
data class Mat2(
var x: Float2 = Float2(x = 1.0f),
var y: Float2 = Float2(y = 1.0f)) {
@@ -39,14 +45,14 @@ data class Mat2(
fun identity() = Mat2()
}
operator fun get(column: Int) = when(column) {
operator fun get(column: Int) = when (column) {
0 -> x
1 -> y
else -> throw IllegalArgumentException("column must be in 0..1")
}
operator fun get(column: Int, row: Int) = get(column)[row]
operator fun get(column: MatrixColumn) = when(column) {
operator fun get(column: MatrixColumn) = when (column) {
MatrixColumn.X -> x
MatrixColumn.Y -> y
else -> throw IllegalArgumentException("column must be X or Y")
@@ -64,16 +70,8 @@ data class Mat2(
}
operator fun unaryMinus() = Mat2(-x, -y)
operator fun inc(): Mat2 {
x++
y++
return this
}
operator fun dec(): Mat2 {
x--
y--
return this
}
operator fun inc() = Mat2(x++, y++)
operator fun dec() = Mat2(x--, y--)
operator fun plus(v: Float) = Mat2(x + v, y + v)
operator fun minus(v: Float) = Mat2(x - v, y - v)
@@ -130,7 +128,7 @@ data class Mat3(
fun identity() = Mat3()
}
operator fun get(column: Int) = when(column) {
operator fun get(column: Int) = when (column) {
0 -> x
1 -> y
2 -> z
@@ -138,7 +136,7 @@ data class Mat3(
}
operator fun get(column: Int, row: Int) = get(column)[row]
operator fun get(column: MatrixColumn) = when(column) {
operator fun get(column: MatrixColumn) = when (column) {
MatrixColumn.X -> x
MatrixColumn.Y -> y
MatrixColumn.Z -> z
@@ -157,18 +155,8 @@ data class Mat3(
}
operator fun unaryMinus() = Mat3(-x, -y, -z)
operator fun inc(): Mat3 {
x++
y++
z++
return this
}
operator fun dec(): Mat3 {
x--
y--
z--
return this
}
operator fun inc() = Mat3(x++, y++, z++)
operator fun dec() = Mat3(x--, y--, z--)
operator fun plus(v: Float) = Mat3(x + v, y + v, z + v)
operator fun minus(v: Float) = Mat3(x - v, y - v, z - v)
@@ -279,7 +267,7 @@ data class Mat4(
inline val upperLeft: Mat3
get() = Mat3(x.xyz, y.xyz, z.xyz)
operator fun get(column: Int) = when(column) {
operator fun get(column: Int) = when (column) {
0 -> x
1 -> y
2 -> z
@@ -288,7 +276,7 @@ data class Mat4(
}
operator fun get(column: Int, row: Int) = get(column)[row]
operator fun get(column: MatrixColumn) = when(column) {
operator fun get(column: MatrixColumn) = when (column) {
MatrixColumn.X -> x
MatrixColumn.Y -> y
MatrixColumn.Z -> z
@@ -307,20 +295,8 @@ data class Mat4(
}
operator fun unaryMinus() = Mat4(-x, -y, -z, -w)
operator fun inc(): Mat4 {
x++
y++
z++
w++
return this
}
operator fun dec(): Mat4 {
x--
y--
z--
w--
return this
}
operator fun inc() = Mat4(x++, y++, z++, w++)
operator fun dec() = Mat4(x--, y--, z--, w--)
operator fun plus(v: Float) = Mat4(x + v, y + v, z + v, w + v)
operator fun minus(v: Float) = Mat4(x - v, y - v, z - v, w - v)
@@ -361,6 +337,8 @@ data class Mat4(
x.w * v.x + y.w * v.y + z.w * v.z+ w.w * v.w
)
fun toQuaternion() = quaternion(this)
fun toFloatArray() = floatArrayOf(
x.x, y.x, z.x, w.x,
x.y, y.y, z.y, w.y,
@@ -408,7 +386,7 @@ fun inverse(m: Mat3): Mat3 {
val det = a * A + b * B + c * C
return Mat3.of(
A / det, B / det, C / det,
A / det, B / det, C / det,
(c * h - b * i) / det, (a * i - c * g) / det, (b * g - a * h) / det,
(b * f - c * e) / det, (c * d - a * f) / det, (a * e - b * d) / det
)
@@ -496,18 +474,90 @@ fun translation(t: Float3) = Mat4(w = Float4(t, 1.0f))
fun translation(m: Mat4) = translation(m.translation)
fun rotation(m: Mat4) = Mat4(normalize(m.right), normalize(m.up), normalize(m.forward))
fun rotation(d: Float3): Mat4 {
val r = transform(d, ::radians)
val c = transform(r) { x -> cos(x) }
val s = transform(r) { x -> sin(x) }
return Mat4.of(
c.y * c.z, -c.x * s.z + s.x * s.y * c.z, s.x * s.z + c.x * s.y * c.z, 0.0f,
c.y * s.z, c.x * c.z + s.x * s.y * s.z, -s.x * c.z + c.x * s.y * s.z, 0.0f,
-s.y , s.x * c.y , c.x * c.y , 0.0f,
0.0f , 0.0f , 0.0f , 1.0f
)
/**
* Construct a rotation matrix from Euler angles using YPR around a specified order
*
* Uses intrinsic Tait-Bryan angles. This means that rotations are performed with respect to the
* local coordinate system.
* That is, for order 'XYZ', the rotation is first around the X axis (which is the same as the
* world-X axis), then around local-Y (which may now be different from the world Y-axis),
* then local-Z (which may be different from the world Z-axis)
*
* @param d Per axis Euler angles in degrees
* Yaw, pitch, roll (YPR) are taken accordingly to the rotations order input.
* @param order The order in which to apply rotations.
* Default is [RotationsOrder.ZYX] which means that the object will first be rotated around its Z
* axis, then its Y axis and finally its X axis.
*
* @return The rotation matrix
*/
fun rotation(d: Float3, order: RotationsOrder = RotationsOrder.ZYX): Mat4 {
val r = transform(d, ::radians)
return when(order) {
RotationsOrder.XZY -> rotation(r.x, r.z, r.y)
RotationsOrder.XYZ -> rotation(r.x, r.y, r.z)
RotationsOrder.YXZ -> rotation(r.y, r.x, r.z)
RotationsOrder.YZX -> rotation(r.y, r.z, r.x)
RotationsOrder.ZYX -> rotation(r.z, r.y, r.x)
RotationsOrder.ZXY -> rotation(r.z, r.x, r.y)
}
}
/**
* Construct a rotation matrix from Euler yaw, pitch, roll around a specified order.
*
* @param roll about 1st rotation axis in radians. Z in case of ZYX order
* @param pitch about 2nd rotation axis in radians. Y in case of ZYX order
* @param yaw about 3rd rotation axis in radians. X in case of ZYX order
* @param order The order in which to apply rotations.
* Default is [RotationsOrder.ZYX] which means that the object will first be rotated around its Z
* axis, then its Y axis and finally its X axis.
*
* @return The rotation matrix
*/
fun rotation(yaw: Float = 0.0f, pitch: Float = 0.0f, roll: Float = 0.0f, order: RotationsOrder = RotationsOrder.ZYX): Mat4 {
val c1 = cos(yaw)
val s1 = sin(yaw)
val c2 = cos(pitch)
val s2 = sin(pitch)
val c3 = cos(roll)
val s3 = sin(roll)
return when (order) {
RotationsOrder.XZY -> Mat4.of(
c2 * c3, -s2, c2 * s3, 0.0f,
s1 * s3 + c1 * c3 * s2, c1 * c2, c1 * s2 * s3 - c3 * s1, 0.0f,
c3 * s1 * s2 - c1 * s3, c2 * s1, c1 * c3 + s1 * s2 * s3, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f)
RotationsOrder.XYZ -> Mat4.of(
c2 * c3, -c2 * s3, s2, 0.0f,
c1 * s3 + c3 * s1 * s2, c1 * c3 - s1 * s2 * s3, -c2 * s1, 0.0f,
s1 * s3 - c1 * c3 * s2, c3 * s1 + c1 * s2 * s3, c1 * c2, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f)
RotationsOrder.YXZ -> Mat4.of(
c1 * c3 + s1 * s2 * s3, c3 * s1 * s2 - c1 * s3, c2 * s1, 0.0f,
c2 * s3, c2 * c3, -s2, 0.0f,
c1 * s2 * s3 - c3 * s1, c1 * c3 * s2 + s1 * s3, c1 * c2, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f)
RotationsOrder.YZX -> Mat4.of(
c1 * c2, s1 * s3 - c1 * c3 * s2, c3 * s1 + c1 * s2 * s3, 0.0f,
s2, c2 * c3, -c2 * s3, 0.0f,
-c2 * s1, c1 * s3 + c3 * s1 * s2, c1 * c3 - s1 * s2 * s3, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f)
RotationsOrder.ZYX -> Mat4.of(
c1 * c2, c1 * s2 * s3 - c3 * s1, s1 * s3 + c1 * c3 * s2, 0.0f,
c2 * s1, c1 * c3 + s1 * s2 * s3, c3 * s1 * s2 - c1 * s3, 0.0f,
-s2, c2 * s3, c2 * c3, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f)
RotationsOrder.ZXY -> Mat4.of(
c1 * c3 - s1 * s2 * s3, -c2 * s1, c1 * s3 + c3 * s1 * s2, 0.0f,
c3 * s1 + c1 * s2 * s3, c1 * c2, s1 * s3 - c1 * c3 * s2, 0.0f,
-c2 * s3, s2, c2 * c3, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f)
}
}
fun rotation(axis: Float3, angle: Float): Mat4 {
val x = axis.x
val y = axis.y
@@ -519,10 +569,85 @@ fun rotation(axis: Float3, angle: Float): Mat4 {
val d = 1.0f - c
return Mat4.of(
x * x * d + c , x * y * d - z * s, x * z * d + y * s, 0.0f,
y * x * d + z * s, y * y * d + c , y * z * d - x * s, 0.0f,
z * x * d - y * s, z * y * d + x * s, z * z * d + c , 0.0f,
0.0f , 0.0f , 0.0f , 1.0f
x * x * d + c, x * y * d - z * s, x * z * d + y * s, 0.0f,
y * x * d + z * s, y * y * d + c, y * z * d - x * s, 0.0f,
z * x * d - y * s, z * y * d + x * s, z * z * d + c, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
)
}
/**
* Construct a Quaternion Rotation Matrix following the Hamilton convention
*
* Assume the destination and local coordinate spaces are initially aligned, and the local
* coordinate space is then rotated counter-clockwise about a unit-length axis, k, by an angle,
* theta.
*/
fun rotation(quaternion: Quaternion): Mat4 {
val n = normalize(quaternion)
return Mat4(
Float4(
1.0f - 2.0f * (n.y * n.y + n.z * n.z),
2.0f * (n.x * n.y + n.z * n.w),
2.0f * (n.x * n.z - n.y * n.w),
),
Float4(
2.0f * (n.x * n.y - n.z * n.w),
1.0f - 2.0f * (n.x * n.x + n.z * n.z),
2.0f * (n.y * n.z + n.x * n.w),
),
Float4(
2.0f * (n.x * n.z + n.y * n.w),
2.0f * (n.y * n.z - n.x * n.w),
1.0f - 2.0f * (n.x * n.x + n.y * n.y),
)
)
}
/**
* Extract Quaternion rotation from a Matrix
*/
fun quaternion(m: Mat4): Quaternion {
val trace = m.x.x + m.y.y + m.z.z
return normalize(
when {
trace > 0.0f -> {
val s = 2.0f * sqrt(trace + 1.0f)
Quaternion(
(m.y.z - m.z.y) / s,
(m.z.x - m.x.z) / s,
(m.x.y - m.y.x) / s,
0.25f * s
)
}
m.x.x > m.y.y && m.x.x > m.z.z -> {
val s = 2.0f * sqrt(1.0f + m.x.x - m.y.y - m.z.z)
Quaternion(
0.25f * s,
(m.y.x + m.x.y) / s,
(m.z.x + m.x.z) / s,
(m.y.z - m.z.y) / s
)
}
m.y.y > m.z.z -> {
val s = 2.0f * sqrt(1.0f + m.y.y - m.x.x - m.z.z)
Quaternion(
(m.y.x + m.x.y) / s,
0.25f * s,
(m.z.y + m.y.z) / s,
(m.z.x - m.x.z) / s
)
}
else -> {
val s = 2.0f * sqrt(1.0f + m.z.z - m.x.x - m.y.y)
Quaternion(
(m.z.x + m.x.z) / s,
(m.z.y + m.y.z) / s,
0.25f * s,
(m.x.y - m.y.x) / s
)
}
}
)
}
@@ -536,7 +661,7 @@ fun lookTowards(eye: Float3, forward: Float3, up: Float3 = Float3(z = 1.0f)): Ma
val f = normalize(forward)
val r = normalize(f x up)
val u = normalize(r x f)
return Mat4(Float4(r), Float4(u), Float4(f), Float4(eye, 1.0f))
return Mat4(Float4(r), Float4(u), Float4(-f), Float4(eye, 1.0f))
}
fun perspective(fov: Float, ratio: Float, near: Float, far: Float): Mat4 {

View File

@@ -58,7 +58,10 @@ private const val kSensitivity = 100f
*
* See `sample-gltf-viewer` for a usage example.
*/
class ModelViewer(val engine: Engine) : android.view.View.OnTouchListener {
class ModelViewer(
val engine: Engine,
private val uiHelper: UiHelper
) : android.view.View.OnTouchListener {
var asset: FilamentAsset? = null
private set
@@ -71,6 +74,7 @@ class ModelViewer(val engine: Engine) : android.view.View.OnTouchListener {
var normalizeSkinningWeights = true
var recomputeBoundingBoxes = false
var ignoreBindTransform = false
var cameraFocalLength = 28f
set(value) {
@@ -84,7 +88,6 @@ class ModelViewer(val engine: Engine) : android.view.View.OnTouchListener {
val renderer: Renderer
@Entity val light: Int
private val uiHelper: UiHelper = UiHelper(UiHelper.ContextErrorPolicy.DONT_CHECK)
private lateinit var displayHelper: DisplayHelper
private lateinit var cameraManipulator: Manipulator
private lateinit var gestureDetector: GestureDetector
@@ -95,6 +98,7 @@ class ModelViewer(val engine: Engine) : android.view.View.OnTouchListener {
private var swapChain: SwapChain? = null
private var assetLoader: AssetLoader
private var materialProvider: MaterialProvider
private var resourceLoader: ResourceLoader
private val readyRenderables = IntArray(128) // add up to 128 entities at a time
@@ -110,8 +114,9 @@ class ModelViewer(val engine: Engine) : android.view.View.OnTouchListener {
view.scene = scene
view.camera = camera
assetLoader = AssetLoader(engine, UbershaderLoader(engine), EntityManager.get())
resourceLoader = ResourceLoader(engine, normalizeSkinningWeights, recomputeBoundingBoxes)
materialProvider = UbershaderLoader(engine)
assetLoader = AssetLoader(engine, materialProvider, EntityManager.get())
resourceLoader = ResourceLoader(engine, normalizeSkinningWeights, recomputeBoundingBoxes, ignoreBindTransform)
// Always add a direct light source since it is required for shadowing.
// We highly recommend adding an indirect light as well.
@@ -129,7 +134,12 @@ class ModelViewer(val engine: Engine) : android.view.View.OnTouchListener {
scene.addEntity(light)
}
constructor(surfaceView: SurfaceView, engine: Engine = Engine.create(), manipulator: Manipulator? = null) : this(engine) {
constructor(
surfaceView: SurfaceView,
engine: Engine = Engine.create(),
uiHelper: UiHelper = UiHelper(UiHelper.ContextErrorPolicy.DONT_CHECK),
manipulator: Manipulator? = null
) : this(engine, uiHelper) {
cameraManipulator = manipulator ?: Manipulator.Builder()
.targetPosition(kDefaultObjectPosition.x, kDefaultObjectPosition.y, kDefaultObjectPosition.z)
.viewport(surfaceView.width, surfaceView.height)
@@ -144,7 +154,12 @@ class ModelViewer(val engine: Engine) : android.view.View.OnTouchListener {
}
@Suppress("unused")
constructor(textureView: TextureView, engine: Engine = Engine.create(), manipulator: Manipulator? = null) : this(engine) {
constructor(
textureView: TextureView,
engine: Engine = Engine.create(),
uiHelper: UiHelper = UiHelper(UiHelper.ContextErrorPolicy.DONT_CHECK),
manipulator: Manipulator? = null
) : this(engine, uiHelper) {
cameraManipulator = manipulator ?: Manipulator.Builder()
.targetPosition(kDefaultObjectPosition.x, kDefaultObjectPosition.y, kDefaultObjectPosition.z)
.viewport(textureView.width, textureView.height)
@@ -215,8 +230,8 @@ class ModelViewer(val engine: Engine) : android.view.View.OnTouchListener {
fun transformToUnitCube(centerPoint: Float3 = kDefaultObjectPosition) {
asset?.let { asset ->
val tm = engine.transformManager
var center = asset.boundingBox.center.let { v-> Float3(v[0], v[1], v[2]) }
val halfExtent = asset.boundingBox.halfExtent.let { v-> Float3(v[0], v[1], v[2]) }
var center = asset.boundingBox.center.let { v -> Float3(v[0], v[1], v[2]) }
val halfExtent = asset.boundingBox.halfExtent.let { v -> Float3(v[0], v[1], v[2]) }
val maxExtent = 2.0f * max(halfExtent)
val scaleFactor = 2.0f / maxExtent
center -= centerPoint / scaleFactor
@@ -284,9 +299,9 @@ class ModelViewer(val engine: Engine) : android.view.View.OnTouchListener {
private fun populateScene(asset: FilamentAsset) {
val rcm = engine.renderableManager
var count = 0
val popRenderables = {count = asset.popRenderables(readyRenderables); count != 0}
val popRenderables = { count = asset.popRenderables(readyRenderables); count != 0 }
while (popRenderables()) {
for (i in 0..count-1) {
for (i in 0..count - 1) {
val ri = rcm.getInstance(readyRenderables[i])
rcm.setScreenSpaceContactShadows(ri, true)
}
@@ -303,6 +318,8 @@ class ModelViewer(val engine: Engine) : android.view.View.OnTouchListener {
destroyModel()
assetLoader.destroy()
materialProvider.destroyMaterials()
materialProvider.destroy()
resourceLoader.destroy()
engine.destroyEntity(light)
@@ -383,4 +400,4 @@ class ModelViewer(val engine: Engine) : android.view.View.OnTouchListener {
companion object {
private val kDefaultObjectPosition = Float3(0.0f, 0.0f, -4.0f)
}
}
}

View File

@@ -0,0 +1,342 @@
/*
* Copyright (C) 2022 Romain Guy
*
* 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.
*/
@file:Suppress("NOTHING_TO_INLINE", "unused")
package com.google.android.filament.utils
import kotlin.math.*
enum class QuaternionComponent {
X, Y, Z, W
}
/**
* Construct Quaternion and set each value.
* The Quaternion will be normalized during construction
* Default: Identity
*/
data class Quaternion(
var x: Float = 0.0f,
var y: Float = 0.0f,
var z: Float = 0.0f,
var w: Float = 0.0f) {
constructor(v: Float3, w: Float = 0.0f) : this(v.x, v.y, v.z, w)
constructor(v: Float4) : this(v.x, v.y, v.z, v.w)
constructor(q: Quaternion) : this(q.x, q.y, q.z, q.w)
companion object {
/**
* Construct a Quaternion from an axis and angle in degrees
*
* @param axis Rotation direction
* @param angle Angle size in degrees
*/
fun fromAxisAngle(axis: Float3, angle: Float): Quaternion {
val r = radians(angle)
return Quaternion(sin(r * 0.5f) * normalize(axis), cos(r * 0.5f))
}
/**
* Construct a Quaternion from Euler angles using YPR around ZYX respectively
*
* The Euler angles are applied in ZYX order.
* i.e: a vector is first rotated about X (roll) then Y (pitch) and then Z (yaw).
*
* @param d Per axis Euler angles in degrees
*/
fun fromEuler(d: Float3): Quaternion {
val r = transform(d, ::radians)
return fromEulerZYX(r.z, r.y, r.x)
}
/**
* Construct a Quaternion from Euler angles using YPR around ZYX respectively
*
* The Euler angles are applied in ZYX order.
* i.e: a vector is first rotated about X (roll) then Y (pitch) and then Z (yaw).
*
* @param roll about X axis in radians
* @param pitch about Y axis in radians
* @param yaw about Z axis in radians
*/
fun fromEulerZYX(yaw: Float = 0.0f, pitch: Float = 0.0f, roll: Float = 0.0f): Quaternion {
val cy = cos(yaw * 0.5f)
val sy = sin(yaw * 0.5f)
val cp = cos(pitch * 0.5f)
val sp = sin(pitch * 0.5f)
val cr = cos(roll * 0.5f)
val sr = sin(roll * 0.5f)
return Quaternion(
sr * cp * cy - cr * sp * sy,
cr * sp * cy + sr * cp * sy,
cr * cp * sy - sr * sp * cy,
cr * cp * cy + sr * sp * sy
)
}
}
inline var xyz: Float3
get() = Float3(x, y, z)
set(value) {
x = value.x
y = value.y
z = value.z
}
inline var imaginary: Float3
get() = xyz
set(value) {
x = value.x
y = value.y
z = value.z
}
inline var real: Float
get() = w
set(value) {
w = value
}
inline var xyzw: Float4
get() = Float4(x, y, z, w)
set(value) {
x = value.x
y = value.y
z = value.z
w = value.w
}
operator fun get(index: QuaternionComponent) = when (index) {
QuaternionComponent.X -> x
QuaternionComponent.Y -> y
QuaternionComponent.Z -> z
QuaternionComponent.W -> w
}
operator fun get(
index1: QuaternionComponent,
index2: QuaternionComponent,
index3: QuaternionComponent): Float3 {
return Float3(get(index1), get(index2), get(index3))
}
operator fun get(
index1: QuaternionComponent,
index2: QuaternionComponent,
index3: QuaternionComponent,
index4: QuaternionComponent): Quaternion {
return Quaternion(get(index1), get(index2), get(index3), get(index4))
}
operator fun get(index: Int) = when (index) {
0 -> x
1 -> y
2 -> z
3 -> w
else -> throw IllegalArgumentException("index must be in 0..3")
}
operator fun get(index1: Int, index2: Int, index3: Int): Float3 {
return Float3(get(index1), get(index2), get(index3))
}
operator fun get(index1: Int, index2: Int, index3: Int, index4: Int): Quaternion {
return Quaternion(get(index1), get(index2), get(index3), get(index4))
}
inline operator fun invoke(index: Int) = get(index - 1)
operator fun set(index: Int, v: Float) = when (index) {
0 -> x = v
1 -> y = v
2 -> z = v
3 -> w = v
else -> throw IllegalArgumentException("index must be in 0..3")
}
operator fun set(index1: Int, index2: Int, v: Float) {
set(index1, v)
set(index2, v)
}
operator fun set(index1: Int, index2: Int, index3: Int, v: Float) {
set(index1, v)
set(index2, v)
set(index3, v)
}
operator fun set(index1: Int, index2: Int, index3: Int, index4: Int, v: Float) {
set(index1, v)
set(index2, v)
set(index3, v)
set(index4, v)
}
operator fun set(index: QuaternionComponent, v: Float) = when (index) {
QuaternionComponent.X -> x = v
QuaternionComponent.Y -> y = v
QuaternionComponent.Z -> z = v
QuaternionComponent.W -> w = v
}
operator fun set(index1: QuaternionComponent, index2: QuaternionComponent, v: Float) {
set(index1, v)
set(index2, v)
}
operator fun set(
index1: QuaternionComponent, index2: QuaternionComponent, index3: QuaternionComponent, v: Float) {
set(index1, v)
set(index2, v)
set(index3, v)
}
operator fun set(
index1: QuaternionComponent, index2: QuaternionComponent,
index3: QuaternionComponent, index4: QuaternionComponent, v: Float) {
set(index1, v)
set(index2, v)
set(index3, v)
set(index4, v)
}
operator fun unaryMinus() = Quaternion(-x, -y, -z, -w)
inline operator fun plus(v: Float) = Quaternion(x + v, y + v, z + v, w + v)
inline operator fun minus(v: Float) = Quaternion(x - v, y - v, z - v, w - v)
inline operator fun times(v: Float) = Quaternion(x * v, y * v, z * v, w * v)
inline operator fun div(v: Float) = Quaternion(x / v, y / v, z / v, w / v)
inline operator fun times(v: Float3) = (this * Quaternion(v, 0.0f) * inverse(this)).xyz
inline operator fun plus(q: Quaternion) = Quaternion(x + q.x, y + q.y, z + q.z, w + q.w)
inline operator fun minus(q: Quaternion) = Quaternion(x - q.x, y - q.y, z - q.z, w - q.w)
inline operator fun times(q: Quaternion) = Quaternion(
w * q.x + x * q.w + y * q.z - z * q.y,
w * q.y - x * q.z + y * q.w + z * q.x,
w * q.z + x * q.y - y * q.x + z * q.w,
w * q.w - x * q.x - y * q.y - z * q.z)
inline fun transform(block: (Float) -> Float): Quaternion {
x = block(x)
y = block(y)
z = block(z)
w = block(w)
return this
}
fun toEulerAngles() = eulerAngles(this)
fun toMatrix() = rotation(this)
fun toFloatArray() = floatArrayOf(x, y, z, w)
}
inline operator fun Float.plus(q: Quaternion) = Quaternion(this + q.x, this + q.y, this + q.z, this + q.w)
inline operator fun Float.minus(q: Quaternion) = Quaternion(this - q.x, this - q.y, this - q.z, this - q.w)
inline operator fun Float.times(q: Quaternion) = Quaternion(this * q.x, this * q.y, this * q.z, this * q.w)
inline operator fun Float.div(q: Quaternion) = Quaternion(this / q.x, this / q.y, this / q.z, this / q.w)
inline fun abs(q: Quaternion) = Quaternion(abs(q.x), abs(q.y), abs(q.z), abs(q.w))
inline fun length(q: Quaternion) = sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w)
inline fun length2(q: Quaternion) = q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w
inline fun dot(a: Quaternion, b: Quaternion) = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w
/**
* Rescale the Quaternion to the unit length
*/
fun normalize(q: Quaternion): Quaternion {
val l = 1.0f / length(q)
return Quaternion(q.x * l, q.y * l, q.z * l, q.w * l)
}
fun conjugate(q: Quaternion): Quaternion = Quaternion(-q.x, -q.y, -q.z, q.w)
fun inverse(q: Quaternion): Quaternion {
val d = 1.0f / dot(q, q)
return Quaternion(-q.x * d, -q.y * d, -q.z * d, q.w * d)
}
fun cross(a: Quaternion, b: Quaternion): Quaternion {
val m = a * b
return Quaternion(m.x, m.y, m.z, 0.0f)
}
/**
* Spherical linear interpolation between two given orientations
*
* If t is 0 this returns a.
* As t approaches 1 slerp may approach either b or -b (whichever is closest to a)
* If t is above 1 or below 0 the result will be extrapolated.
* @param a The beginning value
* @param b The ending value
* @param t The ratio between the two floats
* @param valueEps Prevent blowing up when slerping between two quaternions that are very near each
* other. Linear interpolation (lerp) is returned in this case.
*
* @return Interpolated value between the two floats
*/
fun slerp(a: Quaternion, b: Quaternion, t: Float, valueEps: Float = 0.0000000001f): Quaternion {
// could also be computed as: pow(q * inverse(p), t) * p;
val d = dot(a, b)
val absd = abs(d)
// Prevent blowing up when slerping between two quaternions that are very near each other.
if ((1.0f - absd) < valueEps) {
return normalize(lerp(if (d < 0.0f) -a else a, b, t))
}
val npq = sqrt(dot(a, a) * dot(b, b)) // ||p|| * ||q||
val acos = acos(clamp(absd / npq, -1.0f, 1.0f))
val acos0 = acos * (1.0f - t)
val acos1 = acos * t
val sina = sin(acos)
if (sina < valueEps) {
return normalize(lerp(a, b, t))
}
val isina = 1.0f / sina
val s0 = sin(acos0) * isina
val s1 = sin(acos1) * isina
// ensure we're taking the "short" side
return normalize(s0 * a + (if (d < 0.0f) -s1 else (s1)) * b)
}
fun lerp(a: Quaternion, b: Quaternion, t: Float): Quaternion {
return ((1 - t) * a) + (t * b)
}
fun nlerp(a: Quaternion, b: Quaternion, t: Float): Quaternion {
return normalize(lerp(a, b, t))
}
/**
* Convert a Quaternion to Euler angles using YPR around ZYX respectively
*
* The Euler angles are applied in ZYX order
*/
fun eulerAngles(q: Quaternion): Float3 {
val nq = normalize(q)
return Float3(
// roll (x-axis rotation)
degrees(atan2(2.0f * (nq.y * nq.z + nq.w * nq.x),
nq.w * nq.w - nq.x * nq.x - nq.y * nq.y + nq.z * nq.z)),
// pitch (y-axis rotation)
degrees(asin(-2.0f * (nq.x * nq.z - nq.w * nq.y))),
// yaw (z-axis rotation)
degrees(atan2(2.0f * (nq.x * nq.y + nq.w * nq.z),
nq.w * nq.w + nq.x * nq.x - nq.y * nq.y - nq.z * nq.z)))
}

View File

@@ -18,6 +18,8 @@
package com.google.android.filament.utils
import kotlin.math.pow
const val FPI = 3.1415926536f
const val HALF_PI = FPI * 0.5f
const val TWO_PI = FPI * 2.0f
@@ -40,4 +42,4 @@ inline fun fract(v: Float) = v % 1
inline fun sqr(v: Float) = v * v
inline fun pow(x: Float, y: Float) = StrictMath.pow(x.toDouble(), y.toDouble()).toFloat()
inline fun pow(x: Float, y: Float) = (x.toDouble().pow(y.toDouble())).toFloat()

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE")
@file:Suppress("NOTHING_TO_INLINE", "unused")
package com.google.android.filament.utils
@@ -117,17 +117,8 @@ data class Float2(var x: Float = 0.0f, var y: Float = 0.0f) {
}
operator fun unaryMinus() = Float2(-x, -y)
operator fun inc(): Float2 {
x += 1.0f
y += 1.0f
return this
}
operator fun dec(): Float2 {
x -= 1.0f
y -= 1.0f
return this
}
operator fun inc() = Float2(x++, y++)
operator fun dec() = Float2(x--, y--)
inline operator fun plus(v: Float) = Float2(x + v, y + v)
inline operator fun minus(v: Float) = Float2(x - v, y - v)
@@ -144,6 +135,8 @@ data class Float2(var x: Float = 0.0f, var y: Float = 0.0f) {
y = block(y)
return this
}
fun toFloatArray() = floatArrayOf(x, y)
}
data class Float3(var x: Float = 0.0f, var y: Float = 0.0f, var z: Float = 0.0f) {
@@ -284,29 +277,15 @@ data class Float3(var x: Float = 0.0f, var y: Float = 0.0f, var z: Float = 0.0f)
}
operator fun set(
index1: VectorComponent,
index2: VectorComponent,
index3: VectorComponent,
v: Float) {
index1: VectorComponent, index2: VectorComponent, index3: VectorComponent, v: Float) {
set(index1, v)
set(index2, v)
set(index3, v)
}
operator fun unaryMinus() = Float3(-x, -y, -z)
operator fun inc(): Float3 {
x += 1.0f
y += 1.0f
z += 1.0f
return this
}
operator fun dec(): Float3 {
x -= 1.0f
y -= 1.0f
z -= 1.0f
return this
}
operator fun inc() = Float3(x++, y++, z++)
operator fun dec() = Float3(x--, y--, z--)
inline operator fun plus(v: Float) = Float3(x + v, y + v, z + v)
inline operator fun minus(v: Float) = Float3(x - v, y - v, z - v)
@@ -329,6 +308,8 @@ data class Float3(var x: Float = 0.0f, var y: Float = 0.0f, var z: Float = 0.0f)
z = block(z)
return this
}
fun toFloatArray() = floatArrayOf(x, y, z)
}
data class Float4(
@@ -529,14 +510,15 @@ data class Float4(
set(index2, v)
}
operator fun set(index1: VectorComponent, index2: VectorComponent, index3: VectorComponent,
v: Float) {
operator fun set(
index1: VectorComponent, index2: VectorComponent, index3: VectorComponent, v: Float) {
set(index1, v)
set(index2, v)
set(index3, v)
}
operator fun set(index1: VectorComponent, index2: VectorComponent,
operator fun set(
index1: VectorComponent, index2: VectorComponent,
index3: VectorComponent, index4: VectorComponent, v: Float) {
set(index1, v)
set(index2, v)
@@ -545,21 +527,8 @@ data class Float4(
}
operator fun unaryMinus() = Float4(-x, -y, -z, -w)
operator fun inc(): Float4 {
x += 1.0f
y += 1.0f
z += 1.0f
w += 1.0f
return this
}
operator fun dec(): Float4 {
x -= 1.0f
y -= 1.0f
z -= 1.0f
w -= 1.0f
return this
}
operator fun inc() = Float4(x++, y++, z++, w++)
operator fun dec() = Float4(x--, y--, z--, w--)
inline operator fun plus(v: Float) = Float4(x + v, y + v, z + v, w + v)
inline operator fun minus(v: Float) = Float4(x - v, y - v, z - v, w - v)
@@ -588,6 +557,8 @@ data class Float4(
w = block(w)
return this
}
fun toFloatArray() = floatArrayOf(x, y, z, w)
}
inline operator fun Float.plus(v: Float2) = Float2(this + v.x, this + v.y)
@@ -615,25 +586,29 @@ fun refract(i: Float2, n: Float2, eta: Float): Float2 {
inline fun clamp(v: Float2, min: Float, max: Float): Float2 {
return Float2(
clamp(v.x, min, max),
clamp(v.y, min, max))
clamp(v.y, min, max)
)
}
inline fun clamp(v: Float2, min: Float2, max: Float2): Float2 {
return Float2(
clamp(v.x, min.x, max.x),
clamp(v.y, min.y, max.y))
clamp(v.y, min.y, max.y)
)
}
inline fun mix(a: Float2, b: Float2, x: Float): Float2 {
return Float2(
mix(a.x, b.x, x),
mix(a.y, b.y, x))
mix(a.y, b.y, x)
)
}
inline fun mix(a: Float2, b: Float2, x: Float2): Float2 {
return Float2(
mix(a.x, b.x, x.x),
mix(a.y, b.y, x.y))
mix(a.y, b.y, x.y)
)
}
inline fun min(v: Float2) = min(v.x, v.y)
@@ -704,28 +679,32 @@ inline fun clamp(v: Float3, min: Float, max: Float): Float3 {
return Float3(
clamp(v.x, min, max),
clamp(v.y, min, max),
clamp(v.z, min, max))
clamp(v.z, min, max)
)
}
inline fun clamp(v: Float3, min: Float3, max: Float3): Float3 {
return Float3(
clamp(v.x, min.x, max.x),
clamp(v.y, min.y, max.y),
clamp(v.z, min.z, max.z))
clamp(v.z, min.z, max.z)
)
}
inline fun mix(a: Float3, b: Float3, x: Float): Float3 {
return Float3(
mix(a.x, b.x, x),
mix(a.y, b.y, x),
mix(a.z, b.z, x))
mix(a.z, b.z, x)
)
}
inline fun mix(a: Float3, b: Float3, x: Float3): Float3 {
return Float3(
mix(a.x, b.x, x.x),
mix(a.y, b.y, x.y),
mix(a.z, b.z, x.z))
mix(a.z, b.z, x.z)
)
}
inline fun min(v: Float3) = min(v.x, min(v.y, v.z))
@@ -784,7 +763,8 @@ inline fun clamp(v: Float4, min: Float, max: Float): Float4 {
clamp(v.x, min, max),
clamp(v.y, min, max),
clamp(v.z, min, max),
clamp(v.w, min, max))
clamp(v.w, min, max)
)
}
inline fun clamp(v: Float4, min: Float4, max: Float4): Float4 {
@@ -792,7 +772,8 @@ inline fun clamp(v: Float4, min: Float4, max: Float4): Float4 {
clamp(v.x, min.x, max.x),
clamp(v.y, min.y, max.y),
clamp(v.z, min.z, max.z),
clamp(v.w, min.z, max.w))
clamp(v.w, min.z, max.w)
)
}
inline fun mix(a: Float4, b: Float4, x: Float): Float4 {
@@ -800,7 +781,8 @@ inline fun mix(a: Float4, b: Float4, x: Float): Float4 {
mix(a.x, b.x, x),
mix(a.y, b.y, x),
mix(a.z, b.z, x),
mix(a.w, b.w, x))
mix(a.w, b.w, x)
)
}
inline fun mix(a: Float4, b: Float4, x: Float4): Float4 {
@@ -1075,10 +1057,7 @@ data class Bool3(var x: Boolean = false, var y: Boolean = false, var z: Boolean
}
operator fun set(
index1: VectorComponent,
index2: VectorComponent,
index3: VectorComponent,
v: Boolean) {
index1: VectorComponent, index2: VectorComponent, index3: VectorComponent, v: Boolean) {
set(index1, v)
set(index2, v)
set(index3, v)
@@ -1282,14 +1261,15 @@ data class Bool4(
set(index2, v)
}
operator fun set(index1: VectorComponent, index2: VectorComponent, index3: VectorComponent,
v: Boolean) {
operator fun set(
index1: VectorComponent, index2: VectorComponent, index3: VectorComponent, v: Boolean) {
set(index1, v)
set(index2, v)
set(index3, v)
}
operator fun set(index1: VectorComponent, index2: VectorComponent,
operator fun set(
index1: VectorComponent, index2: VectorComponent,
index3: VectorComponent, index4: VectorComponent, v: Boolean) {
set(index1, v)
set(index2, v)

View File

@@ -32,6 +32,7 @@ set(GLTFIO_SRCS
${GLTFIO_DIR}/include/gltfio/ResourceLoader.h
${GLTFIO_DIR}/include/gltfio/FilamentAsset.h
${GLTFIO_DIR}/include/gltfio/FilamentInstance.h
${GLTFIO_DIR}/include/gltfio/math.h
${GLTFIO_DIR}/src/Animator.cpp
${GLTFIO_DIR}/src/AssetLoader.cpp
@@ -45,15 +46,12 @@ set(GLTFIO_SRCS
${GLTFIO_DIR}/src/FilamentInstance.cpp
${GLTFIO_DIR}/src/GltfEnums.h
${GLTFIO_DIR}/src/MaterialProvider.cpp
${GLTFIO_DIR}/src/MorphHelper.h
${GLTFIO_DIR}/src/MorphHelper.cpp
${GLTFIO_DIR}/src/ResourceLoader.cpp
${GLTFIO_DIR}/src/TangentsJob.h
${GLTFIO_DIR}/src/TangentsJob.cpp
${GLTFIO_DIR}/src/UbershaderLoader.cpp
${GLTFIO_DIR}/src/Wireframe.cpp
${GLTFIO_DIR}/src/Wireframe.h
${GLTFIO_DIR}/src/math.h
${GLTFIO_DIR}/src/upcast.h
${GLTFIO_DIR}/src/Image.cpp

View File

@@ -69,7 +69,7 @@ public:
jclass providerClass = env->GetObjectClass(provider);
mCreateMaterialInstance = env->GetMethodID(providerClass, "createMaterialInstance",
"(L" JAVA_MATERIAL_KEY ";[ILjava/lang/String;)Lcom/google/android/filament/MaterialInstance;");
"(L" JAVA_MATERIAL_KEY ";[ILjava/lang/String;Ljava/lang/String;)Lcom/google/android/filament/MaterialInstance;");
assert_invariant(mCreateMaterialInstance);
mGetMaterials = env->GetMethodID(providerClass, "getMaterials",
@@ -89,7 +89,7 @@ public:
delete mPreviousMaterials;
}
MaterialInstance* createMaterialInstance(MaterialKey* config, UvMap* uvmap, const char* label) override {
MaterialInstance* createMaterialInstance(MaterialKey* config, UvMap* uvmap, const char* label, const char* extras) override {
// Create a Java object for the material key and copy the native fields into it.
jobject javaKey = mEnv->NewObject(mMaterialKeyClass, mMaterialKeyConstructor);
@@ -99,12 +99,15 @@ public:
// Convert the optional label into a Java string.
jstring stringLabel = label ? mEnv->NewStringUTF(label) : nullptr;
// Convert the optional extras into a Java string.
jstring stringExtras = extras ? mEnv->NewStringUTF(extras) : nullptr;
// Allocate space for the output argument.
jintArray uvMapArray = mEnv->NewIntArray(8);
// Call the Java-based material provider.
jobject materialInstance = mEnv->CallObjectMethod(mJavaProvider, mCreateMaterialInstance,
javaKey, uvMapArray, stringLabel);
javaKey, uvMapArray, stringLabel, stringExtras);
// Copy the UvMap results from the JVM array into the native array.
if (uvmap) {
@@ -125,6 +128,10 @@ public:
mEnv->DeleteLocalRef(stringLabel);
}
if (stringExtras) {
mEnv->DeleteLocalRef(stringExtras);
}
if (materialInstance == nullptr) {
return nullptr;
}
@@ -194,7 +201,6 @@ extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_AssetLoader_nDestroyAssetLoader(JNIEnv*, jclass,
jlong nativeLoader) {
AssetLoader* loader = (AssetLoader*) nativeLoader;
delete loader->getMaterialProvider();
NameComponentManager* names = loader->getNames();
AssetLoader::destroy(&loader);
delete names;
@@ -239,6 +245,14 @@ Java_com_google_android_filament_gltfio_AssetLoader_nCreateInstancedAsset(JNIEnv
return asset;
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_gltfio_AssetLoader_nCreateInstance(JNIEnv* env, jclass,
jlong nativeLoader, jlong nativeAsset) {
AssetLoader* loader = (AssetLoader*) nativeLoader;
FilamentAsset* primary = (FilamentAsset*) nativeAsset;
return (jlong) loader->createInstance(primary);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_AssetLoader_nEnableDiagnostics(JNIEnv*, jclass,
jlong nativeLoader, jboolean enable) {

View File

@@ -226,6 +226,49 @@ Java_com_google_android_filament_gltfio_FilamentAsset_nGetResourceUris(JNIEnv* e
}
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_gltfio_FilamentAsset_nGetMorphTargetCount(JNIEnv*, jclass,
jlong nativeAsset, jint entityId) {
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
Entity entity = Entity::import(entityId);
return (jint) asset->getMorphTargetCountAt(entity);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_FilamentAsset_nGetMorphTargetNames(JNIEnv* env, jclass,
jlong nativeAsset, jint entityId, jobjectArray result) {
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
Entity entity = Entity::import(entityId);
for (int i = 0, n = asset->getMorphTargetCountAt(entity); i < n; ++i) {
const char* name = asset->getMorphTargetNameAt(entity, i);
env->SetObjectArrayElement(result, (jsize) i, env->NewStringUTF(name));
}
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_gltfio_FilamentAsset_nGetMaterialVariantCount(JNIEnv*, jclass,
jlong nativeAsset) {
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
return (jint) asset->getMaterialVariantCount();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_FilamentAsset_nGetMaterialVariantNames(JNIEnv* env, jclass,
jlong nativeAsset, jobjectArray result) {
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
for (int i = 0; i < asset->getMaterialVariantCount(); ++i) {
const char* name = asset->getMaterialVariantName(i);
env->SetObjectArrayElement(result, (jsize) i, env->NewStringUTF(name));
}
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_FilamentAsset_nApplyMaterialVariant(JNIEnv* env, jclass,
jlong nativeAsset, jint variantIndex) {
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
asset->applyMaterialVariant(variantIndex);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_FilamentAsset_nReleaseSourceData(JNIEnv* env, jclass,
jlong nativeAsset) {

View File

@@ -54,3 +54,10 @@ Java_com_google_android_filament_gltfio_FilamentInstance_nGetAnimator(JNIEnv* ,
FilamentInstance* instance = (FilamentInstance*) nativeInstance;
return (jlong) instance->getAnimator();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_FilamentInstance_nApplyMaterialVariant(JNIEnv* env, jclass,
jlong nativeInstance, jint variantIndex) {
FilamentInstance* instance = (FilamentInstance*) nativeInstance;
instance->applyMaterialVariant(variantIndex);
}

View File

@@ -35,10 +35,11 @@ static void destroy(void*, size_t, void *userData) {
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_gltfio_ResourceLoader_nCreateResourceLoader(JNIEnv*, jclass,
jlong nativeEngine, jboolean normalizeSkinningWeights, jboolean recomputeBoundingBoxes) {
jlong nativeEngine, jboolean normalizeSkinningWeights, jboolean recomputeBoundingBoxes,
jboolean ignoreBindTransform) {
Engine* engine = (Engine*) nativeEngine;
return (jlong) new ResourceLoader({ engine, {}, (bool) normalizeSkinningWeights,
(bool) recomputeBoundingBoxes });
(bool) recomputeBoundingBoxes, (bool) ignoreBindTransform});
}
extern "C" JNIEXPORT void JNICALL

View File

@@ -45,7 +45,8 @@ import java.nio.Buffer;
*
* ...
*
* assetLoader = AssetLoader(engine, UbershaderLoader(engine), EntityManager.get())
* materialProvider = UbershaderLoader(engine)
* assetLoader = AssetLoader(engine, materialProvider, EntityManager.get())
*
* filamentAsset = assets.open("models/lucy.gltf").use { input -&gt;
* val bytes = ByteArray(input.available())
@@ -60,7 +61,6 @@ import java.nio.Buffer;
* }
* resourceLoader.loadResources(filamentAsset)
* resourceLoader.destroy()
* animator = asset.getAnimator()
* filamentAsset.releaseSourceData();
*
* scene.addEntities(filamentAsset.entities)
@@ -104,10 +104,12 @@ public class AssetLoader {
}
/**
* Frees all memory consumed by the native <code>AssetLoader</code> and its material cache.
* Frees all memory consumed by the native <code>AssetLoader</code>
*
* This does not not automatically free the cache of materials, nor
* does it free the entities for created assets (see destroyAsset).
*/
public void destroy() {
mMaterialCache.destroyMaterials();
nDestroyAssetLoader(mNativeObject);
mNativeObject = 0;
}

View File

@@ -16,6 +16,7 @@
package com.google.android.filament.gltfio;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
@@ -197,11 +198,11 @@ public class FilamentAsset {
}
/**
* Creates or retrieves the <code>Animator</code> interface for this asset.
* Retrieves the <code>Animator</code> interface for this asset.
*
* <p>When calling this for the first time, this must be called after
* {@link ResourceLoader#loadResources}. When the asset is destroyed, its
* animator becomes invalid.</p>
* {@link ResourceLoader#loadResources} or {@link ResourceLoader#asyncBeginLoad}. When the asset
* is destroyed, its animator becomes invalid.</p>
*/
public @NonNull Animator getAnimator() {
if (mAnimator != null) {
@@ -215,6 +216,15 @@ public class FilamentAsset {
return mAnimator;
}
/**
* Gets the names of all morph targets in the given entity.
*/
public @NonNull String[] getMorphTargetNames(@Entity int entity) {
String[] names = new String[nGetMorphTargetCount(mNativeObject, entity)];
nGetMorphTargetNames(mNativeObject, entity, names);
return names;
}
/**
* Gets resource URIs for all externally-referenced buffers.
*/
@@ -224,12 +234,37 @@ public class FilamentAsset {
return uris;
}
/**
* Returns the names of all material variants.
*/
public @NonNull String[] getMaterialVariantNames() {
String[] names = new String[nGetMaterialVariantCount(mNativeObject)];
nGetMaterialVariantNames(mNativeObject, names);
return names;
}
/**
* Applies the given material variant to all primitives that it affects.
*
* This is efficient because it merely swaps around persistent MaterialInstances. If you change
* a material parameter while a certain variant is active, the updated value will be remembered
* after you re-apply that variant.
*
* If the asset is instanced, this affects all instances in the same way.
* To set the variant on an individual instance, use FilamentInstance#applyMaterialVariant.
*
* Ignored if variantIndex is out of bounds.
*/
public void applyMaterialVariant(@IntRange(from = 0) int variantIndex) {
nApplyMaterialVariant(getNativeObject(), variantIndex);
}
/**
* Reclaims CPU-side memory for URI strings, binding lists, and raw animation data.
*
* This should only be called after ResourceLoader#loadResources().
* If using Animator, this should be called after getAnimator().
* If this is an instanced asset, this prevents creation of new instances.
* This should only be called after ResourceLoader#loadResources() or
* ResourceLoader#asyncBeginLoad(). If this is an instanced asset, this prevents creation of new
* instances.
*/
public void releaseSourceData() {
nReleaseSourceData(mNativeObject);
@@ -260,10 +295,17 @@ public class FilamentAsset {
private static native int nGetMaterialInstanceCount(long nativeAsset);
private static native void nGetMaterialInstances(long nativeAsset, long[] nativeResults);
private static native int nGetMaterialVariantCount(long nativeAsset);
private static native void nGetMaterialVariantNames(long nativeAsset, String[] result);
private static native int nGetMorphTargetCount(long nativeAsset, int entity);
private static native void nGetMorphTargetNames(long nativeAsset, int entity, String[] result);
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);
private static native long nGetAnimator(long nativeAsset);
private static native void nApplyMaterialVariant(long nativeAsset, int variantIndex);
private static native int nGetResourceUriCount(long nativeAsset);
private static native void nGetResourceUris(long nativeAsset, String[] result);
private static native void nReleaseSourceData(long nativeAsset);

View File

@@ -16,6 +16,7 @@
package com.google.android.filament.gltfio;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import com.google.android.filament.Entity;
@@ -74,10 +75,7 @@ public class FilamentInstance {
}
/**
* Creates or retrieves the <code>Animator</code> for this instance.
*
* <p>When calling this for the first time, this must be called after
* {@link ResourceLoader#loadResources}.</p>
* Retrieves the <code>Animator</code> for this instance.
*/
public @NonNull Animator getAnimator() {
if (mAnimator != null) {
@@ -87,8 +85,18 @@ public class FilamentInstance {
return mAnimator;
}
/**
* Applies the given material variant to all primitives in this instance.
*
* Ignored if variantIndex is out of bounds.
*/
void applyMaterialVariant(@IntRange(from = 0) int variantIndex) {
nApplyMaterialVariant(mNativeObject, variantIndex);
}
private static native int nGetRoot(long nativeAsset);
private static native int nGetEntityCount(long nativeAsset);
private static native void nGetEntities(long nativeAsset, int[] result);
private static native long nGetAnimator(long nativeAsset);
private static native void nApplyMaterialVariant(long nativeAsset, int variantIndex);
}

View File

@@ -99,9 +99,10 @@ public interface MaterialProvider {
* @param uvmap Output argument that gets populated with a small table that maps from a glTF uv
* index to a Filament uv index (0 = UNUSED, 1 = UV0, 2 = UV1).
* @param label Optional tag that is not a part of the cache key.
* @param extras Optional extras as stringified JSON (not a part of the cache key).
*/
public @Nullable MaterialInstance createMaterialInstance(MaterialKey config,
@NonNull @Size(min = 8) int[] uvmap, @Nullable String label);
@NonNull @Size(min = 8) int[] uvmap, @Nullable String label, @Nullable String extras);
/**
* Creates and returns an array containing all cached materials.
@@ -126,4 +127,10 @@ public interface MaterialProvider {
* clients to take ownership of the cache if desired.
*/
public void destroyMaterials();
/**
* Frees memory consumed by the native <code>MaterialProvider</code>, but does not destroy
* cached materials.
*/
public void destroy();
}

View File

@@ -45,7 +45,7 @@ public class ResourceLoader {
*/
public ResourceLoader(@NonNull Engine engine) {
long nativeEngine = engine.getNativeObject();
mNativeObject = nCreateResourceLoader(nativeEngine, false, false);
mNativeObject = nCreateResourceLoader(nativeEngine, false, false, false);
}
/**
@@ -54,14 +54,15 @@ public class ResourceLoader {
* @param engine the engine that gets passed to all builder methods
* @param normalizeSkinningWeights scale non-conformant skinning weights so they sum to 1
* @param recomputeBoundingBoxes use computed bounding boxes rather than the ones in the asset
* @param ignoreBindTransform ignore skinned primitives bind transform when compute bounding boxes
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public ResourceLoader(@NonNull Engine engine, boolean normalizeSkinningWeights,
boolean recomputeBoundingBoxes) {
boolean recomputeBoundingBoxes, boolean ignoreBindTransform) {
long nativeEngine = engine.getNativeObject();
mNativeObject = nCreateResourceLoader(nativeEngine, normalizeSkinningWeights,
recomputeBoundingBoxes);
recomputeBoundingBoxes, ignoreBindTransform);
}
/**
@@ -166,7 +167,7 @@ public class ResourceLoader {
}
private static native long nCreateResourceLoader(long nativeEngine,
boolean normalizeSkinningWeights, boolean recomputeBoundingBoxes);
boolean normalizeSkinningWeights, boolean recomputeBoundingBoxes, boolean ignoreBindTransform);
private static native void nDestroyResourceLoader(long nativeLoader);
private static native void nAddResourceData(long nativeLoader, String url, Buffer buffer,
int remaining);

View File

@@ -32,6 +32,9 @@ import androidx.annotation.Size;
* Client applications do not need to call methods on it.</p>
*/
public class UbershaderLoader implements MaterialProvider {
private static final VertexBuffer.VertexAttribute[] sVertexAttributesValues =
VertexBuffer.VertexAttribute.values();
private long mNativeObject;
/**
@@ -53,7 +56,7 @@ public class UbershaderLoader implements MaterialProvider {
}
public @Nullable MaterialInstance createMaterialInstance(MaterialKey config,
@NonNull @Size(min = 8) int[] uvmap, @Nullable String label) {
@NonNull @Size(min = 8) int[] uvmap, @Nullable String label, @Nullable String extras) {
long nativeMaterialInstance = nCreateMaterialInstance(mNativeObject, config, uvmap, label);
return nativeMaterialInstance == 0 ? null : new MaterialInstance(null, nativeMaterialInstance);
}
@@ -70,7 +73,7 @@ public class UbershaderLoader implements MaterialProvider {
}
public boolean needsDummyData(int attrib) {
VertexBuffer.VertexAttribute vattrib = VertexBuffer.VertexAttribute.values()[attrib];
VertexBuffer.VertexAttribute vattrib = sVertexAttributesValues[attrib];
switch (vattrib) {
case UV0:
case UV1:
@@ -92,7 +95,8 @@ public class UbershaderLoader implements MaterialProvider {
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);
private static native long nCreateMaterialInstance(long nativeProvider,
MaterialKey config, int[] uvmap, String label);
private static native int nGetMaterialCount(long nativeProvider);
private static native void nGetMaterials(long nativeProvider, long[] result);
}

View File

@@ -1,5 +1,5 @@
GROUP=com.google.android.filament
VERSION_NAME=1.12.9
VERSION_NAME=1.21.1
POM_DESCRIPTION=Real-time physically based rendering engine for Android.
@@ -18,3 +18,11 @@ POM_DEVELOPER_NAME=Filament Team
org.gradle.jvmargs=-Xmx1536m
android.useAndroidX=true
org.gradle.unsafe.configuration-cache=true
# TODO: Remove this when we switch to Gradle 7.4
org.gradle.unsafe.configuration-cache.max-problems=3
com.google.android.filament.tools-dir=../../../out/release/filament
com.google.android.filament.dist-dir=../out/android-release/filament
com.google.android.filament.abis=all

View File

@@ -1,5 +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.0.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -1,6 +1,8 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: FilamentToolsPlugin
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'filament-tools-plugin'
}
project.ext.isSample = true
@@ -30,12 +32,17 @@ 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 {
includeInApk = false
}
}
dependencies {
implementation deps.kotlin
implementation deps.coroutines.core
implementation project(':filament-android')
implementation project(':gltfio-android')
implementation project(':filament-utils-android')
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0'
}

View File

@@ -12,7 +12,9 @@
android:supportsRtl="true"
android:largeHeap="true"
android:theme="@android:style/Theme.NoTitleBar">
<activity android:name="com.google.android.filament.gltf.MainActivity"
<activity
android:exported="true"
android:name="com.google.android.filament.gltf.MainActivity"
android:screenOrientation="fullSensor"
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden">
<intent-filter>

View File

@@ -36,6 +36,7 @@ import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileInputStream
import java.io.RandomAccessFile
import java.net.URI
import java.nio.Buffer
import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets
@@ -118,7 +119,7 @@ class MainActivity : Activity() {
}
// FXAA is pretty cheap and helps a lot
view.antiAliasing = View.AntiAliasing.FXAA;
view.antiAliasing = View.AntiAliasing.FXAA
// ambient occlusion is the cheapest effect that adds a lot of quality
view.ambientOcclusionOptions = view.ambientOcclusionOptions.apply {
@@ -217,12 +218,17 @@ class MainActivity : Activity() {
val sky = Skybox.Builder().environment(skyboxTexture).build(engine)
specularFilter.destroy();
equirectToCubemap.destroy();
context.destroy();
specularFilter.destroy()
equirectToCubemap.destroy()
context.destroy()
// destroy the previous IBl
engine.destroyIndirectLight(modelViewer.scene.indirectLight!!)
engine.destroySkybox(modelViewer.scene.skybox!!)
modelViewer.scene.skybox = sky
modelViewer.scene.indirectLight = ibl
viewerContent.indirectLight = ibl
}
}
}
@@ -238,7 +244,7 @@ class MainActivity : Activity() {
val (zipStream, zipFile) = withContext(Dispatchers.IO) {
val file = File.createTempFile("incoming", "zip", cacheDir)
val raf = RandomAccessFile(file, "rw")
raf.getChannel().write(message.buffer);
raf.channel.write(message.buffer)
message.buffer = null
raf.seek(0)
Pair(FileInputStream(file), file)
@@ -293,19 +299,16 @@ class MainActivity : Activity() {
// The gltf is often not at the root level (e.g. if a folder is zipped) so
// we need to extract its path in order to resolve the embedded uri strings.
var gltfPrefix = gltfPath!!.substringBeforeLast('/', "")
if (gltfPrefix.isNotEmpty()) {
gltfPrefix += "/"
}
var prefix = URI(gltfPath!!).resolve("..")
withContext(Dispatchers.Main) {
if (gltfPath!!.endsWith(".glb")) {
modelViewer.loadModelGlb(gltfBuffer)
} else {
modelViewer.loadModelGltf(gltfBuffer) { uri ->
val path = gltfPrefix + uri
val path = prefix.resolve(uri).toString()
if (!pathToBufferMapping.contains(path)) {
Log.e(TAG, "Could not find $path in the zip.")
Log.e(TAG, "Could not find '$uri' in zip using prefix '$prefix'")
setStatusText("Zip is missing $path")
}
pathToBufferMapping[path]
@@ -338,12 +341,10 @@ class MainActivity : Activity() {
clearStatusText()
titlebarHint.text = message.label
CoroutineScope(Dispatchers.IO).launch {
if (message.label.endsWith(".zip")) {
loadZip(message)
} else if (message.label.endsWith(".hdr")) {
loadHdr(message)
} else {
loadGlb(message)
when {
message.label.endsWith(".zip") -> loadZip(message)
message.label.endsWith(".hdr") -> loadHdr(message)
else -> loadGlb(message)
}
}
}

View File

@@ -1,6 +1,8 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: FilamentToolsPlugin
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'filament-tools-plugin'
}
project.ext.isSample = true
@@ -17,10 +19,16 @@ android {
compileSdkVersion versions.compileSdk
defaultConfig {
applicationId "com.google.android.filament.hellocamera"
minSdkVersion versions.minSdk
minSdkVersion 23
targetSdkVersion versions.targetSdk
}
// 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 {
includeInApk = false
}
// We use the .filamat extension for materials compiled with matc
// Telling aapt to not compress them allows to load them efficiently
aaptOptions {

View File

@@ -31,7 +31,9 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<activity
android:exported="true"
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>

View File

@@ -33,7 +33,9 @@ import android.graphics.ImageFormat
import android.hardware.HardwareBuffer
import android.media.ImageReader
import android.opengl.Matrix
import android.view.Display
import android.os.Build
import android.os.Looper
import androidx.annotation.RequiresApi
import com.google.android.filament.*
@@ -44,7 +46,7 @@ import java.util.concurrent.TimeUnit
* Toy class that handles all interaction with the Android camera2 API.
* Sets the "textureTransform" and "videoTexture" parameters on the given Filament material.
*/
class CameraHelper(val activity: Activity, private val filamentEngine: Engine, private val filamentMaterial: MaterialInstance, private val display: Display) {
class CameraHelper(val activity: Activity, private val filamentEngine: Engine, private val filamentMaterial: MaterialInstance) {
private lateinit var cameraId: String
private lateinit var captureRequest: CaptureRequest
@@ -63,6 +65,20 @@ class CameraHelper(val activity: Activity, private val filamentEngine: Engine, p
kImageReaderMaxImages,
HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE)
@Suppress("deprecation")
private val display = if (Build.VERSION.SDK_INT >= 30) {
Api30Impl.getDisplay(activity)
} else {
activity.windowManager.defaultDisplay!!
}
@RequiresApi(30)
class Api30Impl {
companion object {
fun getDisplay(context: Context) = context.display!!
}
}
private val cameraCallback = object : CameraDevice.StateCallback() {
override fun onOpened(cameraDevice: CameraDevice) {
cameraOpenCloseLock.release()
@@ -87,7 +103,9 @@ class CameraHelper(val activity: Activity, private val filamentEngine: Engine, p
val stream = filamentStream
if (stream != null) {
imageReader.acquireLatestImage()?.also {
stream.setAcquiredImage(it.hardwareBuffer, Handler()) { it.close() }
stream.setAcquiredImage(it.hardwareBuffer, Handler(Looper.getMainLooper())) {
it.close()
}
}
}
}

View File

@@ -94,7 +94,7 @@ class MainActivity : Activity(), ActivityCompat.OnRequestPermissionsResultCallba
setupView()
setupScene()
cameraHelper = CameraHelper(this, engine, materialInstance, windowManager.defaultDisplay)
cameraHelper = CameraHelper(this, engine, materialInstance)
cameraHelper.openCamera()
}

View File

@@ -1,6 +1,8 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: FilamentToolsPlugin
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'filament-tools-plugin'
}
project.ext.isSample = true
@@ -21,6 +23,12 @@ android {
targetSdkVersion versions.targetSdk
}
// 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 {
includeInApk = false
}
// We use the .filamat extension for materials compiled with matc
// Telling aapt to not compress them allows to load them efficiently
aaptOptions {

View File

@@ -9,7 +9,9 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<activity
android:exported="true"
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>

View File

@@ -1,6 +1,8 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: FilamentToolsPlugin
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'filament-tools-plugin'
}
project.ext.isSample = true
@@ -27,6 +29,12 @@ android {
targetSdkVersion versions.targetSdk
}
// 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 {
includeInApk = false
}
// We use the .filamat extension for materials compiled with matc
// Telling aapt to not compress them allows to load them efficiently
aaptOptions {

View File

@@ -11,7 +11,9 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<activity
android:exported="true"
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>

View File

@@ -1,6 +1,8 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: FilamentToolsPlugin
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'filament-tools-plugin'
}
project.ext.isSample = true
@@ -20,6 +22,12 @@ android {
targetSdkVersion versions.targetSdk
}
// 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 {
includeInApk = false
}
// We use the .filamat extension for materials compiled with matc
// Telling aapt to not compress them allows to load them efficiently
aaptOptions {

View File

@@ -9,7 +9,9 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<activity
android:exported="true"
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>

View File

@@ -10,9 +10,16 @@ android {
minSdkVersion versions.minSdk
targetSdkVersion versions.targetSdk
}
// 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 {
includeInApk = false
}
}
dependencies {
implementation deps.kotlin
implementation deps.androidx.annotations
implementation project(':filament-android')
}

View File

@@ -12,6 +12,7 @@
android:supportsRtl="true"
android:theme="@style/AppTheme">
<service
android:exported="true"
android:name=".FilamentLiveWallpaper"
android:label="@string/wallpaper_label"
android:permission="android.permission.BIND_WALLPAPER">

View File

@@ -18,19 +18,21 @@ package com.google.android.filament.livewallpaper
import android.animation.ValueAnimator
import android.app.Service
import android.content.Context
import android.graphics.Color
import android.graphics.PixelFormat
import android.os.Build
import android.service.wallpaper.WallpaperService
import android.view.Choreographer
import android.view.Surface
import android.view.SurfaceHolder
import android.view.WindowManager
import android.view.animation.LinearInterpolator
import androidx.annotation.RequiresApi
import com.google.android.filament.*
import com.google.android.filament.android.DisplayHelper
import com.google.android.filament.android.UiHelper
class FilamentLiveWallpaper : WallpaperService() {
// Make sure to initialize Filament first
// This loads the JNI library needed by most API calls
@@ -196,9 +198,14 @@ class FilamentLiveWallpaper : WallpaperService() {
override fun onNativeWindowChanged(surface: Surface) {
swapChain?.let { engine.destroySwapChain(it) }
swapChain = engine.createSwapChain(surface)
val display =
(application.getSystemService(Service.WINDOW_SERVICE) as WindowManager)
.defaultDisplay
@Suppress("deprecation")
val display = if (Build.VERSION.SDK_INT >= 30) {
Api30Impl.getDisplay(displayContext!!)
} else {
(getSystemService(Service.WINDOW_SERVICE) as WindowManager).defaultDisplay
}
displayHelper.attach(renderer, display)
}
@@ -222,4 +229,11 @@ class FilamentLiveWallpaper : WallpaperService() {
}
}
}
@RequiresApi(30)
class Api30Impl {
companion object {
fun getDisplay(context: Context) = context.display!!
}
}
}

View File

@@ -1,6 +1,8 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: FilamentToolsPlugin
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'filament-tools-plugin'
}
project.ext.isSample = true
@@ -31,6 +33,12 @@ android {
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 {
includeInApk = false
}
// We use the .filamat extension for materials compiled with matc
// Telling aapt to not compress them allows to load them efficiently
aaptOptions {

View File

@@ -9,7 +9,9 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<activity
android:exported="true"
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>

View File

@@ -1,6 +1,8 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: FilamentToolsPlugin
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'filament-tools-plugin'
}
project.ext.isSample = true
@@ -20,6 +22,12 @@ android {
targetSdkVersion versions.targetSdk
}
// 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 {
includeInApk = false
}
// We use the .filamat extension for materials compiled with matc
// Telling aapt to not compress them allows to load them efficiently
aaptOptions {

View File

@@ -9,7 +9,9 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<activity
android:exported="true"
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>

View File

@@ -1,5 +1,8 @@
apply plugin: 'com.android.application'
apply plugin: FilamentToolsPlugin
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'filament-tools-plugin'
}
project.ext.isSample = true
@@ -22,6 +25,12 @@ android {
targetSdkVersion versions.targetSdk
}
// 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 {
includeInApk = false
}
// We use the .filamat extension for materials compiled with matc
// Telling aapt to not compress them allows to load them efficiently
aaptOptions {
@@ -31,5 +40,5 @@ android {
dependencies {
implementation project(':filament-android')
implementation 'androidx.annotation:annotation:1.1.0'
implementation deps.androidx.annotations
}

View File

@@ -9,7 +9,9 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<activity
android:exported="true"
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>

View File

@@ -70,11 +70,11 @@ public class MainActivity extends Activity
private Page mPage;
private PageMaterials mPageMaterials;
private Scene mScene;
private Texture[] mTextures = new Texture[2];
private final Texture[] mTextures = new Texture[2];
private @Entity int mLight;
private IndirectLight mIndirectLight;
private float[] mTouchDownPoint = new float[2];
private final float[] mTouchDownPoint = new float[2];
private float mTouchDownValue = 0;
private float mPageAnimationRadians = 0;
private float mPageAnimationValue = 0;

View File

@@ -1,6 +1,8 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: FilamentToolsPlugin
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'filament-tools-plugin'
}
project.ext.isSample = true
@@ -17,10 +19,16 @@ android {
compileSdkVersion versions.compileSdk
defaultConfig {
applicationId "com.google.android.filament.streamtest"
minSdkVersion versions.minSdk
minSdkVersion 23
targetSdkVersion versions.targetSdk
}
// 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 {
includeInApk = false
}
// We use the .filamat extension for materials compiled with matc
// Telling aapt to not compress them allows to load them efficiently
aaptOptions {

View File

@@ -26,7 +26,9 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<activity
android:exported="true"
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>

View File

@@ -18,6 +18,7 @@ package com.google.android.filament.streamtest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.Choreographer
import android.view.Surface
@@ -33,7 +34,9 @@ import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.channels.Channels
import android.opengl.*
import android.os.Build
import android.view.MotionEvent
import androidx.annotation.RequiresApi
import com.google.android.filament.android.DisplayHelper
@@ -78,6 +81,13 @@ class MainActivity : Activity(), ActivityCompat.OnRequestPermissionsResultCallba
private var externalTextureID: Int = 0
@RequiresApi(30)
class Api30Impl {
companion object {
fun getDisplay(context: Context) = context.display!!
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -94,7 +104,15 @@ class MainActivity : Activity(), ActivityCompat.OnRequestPermissionsResultCallba
setupScene()
externalTextureID = createExternalTexture()
streamHelper = StreamHelper(engine, materialInstance, windowManager.defaultDisplay, externalTextureID)
@Suppress("deprecation")
val display = if (Build.VERSION.SDK_INT >= 30) {
Api30Impl.getDisplay(this)
} else {
windowManager.defaultDisplay!!
}
streamHelper = StreamHelper(engine, materialInstance, display, externalTextureID)
this.title = streamHelper.getTestName()
}

View File

@@ -24,6 +24,7 @@ import android.view.Surface
import android.graphics.*
import android.media.ImageReader
import android.opengl.Matrix
import android.os.Looper
import android.view.Display
import com.google.android.filament.*
@@ -32,7 +33,12 @@ import com.google.android.filament.*
/**
* Demonstrates Filament's various texture sharing mechanisms.
*/
class StreamHelper(private val filamentEngine: Engine, private val filamentMaterial: MaterialInstance, private val display: Display, private val externalTextureId: Int) {
class StreamHelper(
private val filamentEngine: Engine,
private val filamentMaterial: MaterialInstance,
private val display: Display,
private val externalTextureId: Int
) {
/**
* The StreamSource configures the source data for the texture.
*
@@ -50,7 +56,7 @@ class StreamHelper(private val filamentEngine: Engine, private val filamentMater
}
private var streamSource = StreamSource.CANVAS_STREAM_NATIVE
private val directImageHandler = Handler()
private val directImageHandler = Handler(Looper.getMainLooper())
private var resolution = Size(640, 480)
private var surfaceTexture: SurfaceTexture? = null
private var imageReader: ImageReader? = null
@@ -93,11 +99,30 @@ class StreamHelper(private val filamentEngine: Engine, private val filamentMater
val canvas = surface.lockCanvas(null)
val movingPaint = Paint()
movingPaint.shader = LinearGradient(kGradientOffset, 0.0f, kGradientOffset + kGradientScale, 0.0f, kGradientColors, kGradientStops, Shader.TileMode.REPEAT)
canvas.drawRect(Rect(0, resolution.height / 2, resolution.width, resolution.height), movingPaint)
movingPaint.shader = LinearGradient(
kGradientOffset,
0.0f,
kGradientOffset + kGradientScale,
0.0f,
kGradientColors,
kGradientStops,
Shader.TileMode.REPEAT
)
canvas.drawRect(
Rect(0, resolution.height / 2, resolution.width, resolution.height),
movingPaint
)
val staticPaint = Paint()
staticPaint.shader = LinearGradient(0.0f, 0.0f, kGradientScale, 0.0f, kGradientColors, kGradientStops, Shader.TileMode.REPEAT)
staticPaint.shader = LinearGradient(
0.0f,
0.0f,
kGradientScale,
0.0f,
kGradientColors,
kGradientStops,
Shader.TileMode.REPEAT
)
canvas.drawRect(Rect(0, 0, resolution.width, resolution.height / 2), staticPaint)
surface.unlockCanvasAndPost(canvas)
@@ -108,7 +133,10 @@ class StreamHelper(private val filamentEngine: Engine, private val filamentMater
if (streamSource == StreamSource.CANVAS_STREAM_ACQUIRED) {
val image = imageReader!!.acquireLatestImage()
filamentStream!!.setAcquiredImage(image.hardwareBuffer!!, directImageHandler) { image.close() }
filamentStream!!.setAcquiredImage(
image.hardwareBuffer!!,
directImageHandler
) { image.close() }
}
}
@@ -136,7 +164,9 @@ class StreamHelper(private val filamentEngine: Engine, private val filamentMater
val filamentTexture = this.filamentTexture!!
val sampler = TextureSampler(TextureSampler.MinFilter.LINEAR, TextureSampler.MagFilter.LINEAR, TextureSampler.WrapMode.REPEAT)
val sampler = TextureSampler(
TextureSampler.MinFilter.LINEAR, TextureSampler.MagFilter.LINEAR,
TextureSampler.WrapMode.REPEAT)
// We are texturing a front-facing square shape so we need to generate a matrix that transforms (u, v, 0, 1)
// into a new UV coordinate according to the screen rotation and the aspect ratio of the camera image.
@@ -164,7 +194,8 @@ class StreamHelper(private val filamentEngine: Engine, private val filamentMater
// Connect the Stream to the Texture and the Texture to the MaterialInstance.
filamentMaterial.setParameter("videoTexture", filamentTexture, sampler)
filamentMaterial.setParameter("textureTransform", MaterialInstance.FloatElement.MAT4, textureTransform, 0, 1)
filamentMaterial.setParameter("textureTransform",
MaterialInstance.FloatElement.MAT4, textureTransform, 0, 1)
if (streamSource == StreamSource.CANVAS_STREAM_NATIVE) {
@@ -207,7 +238,9 @@ class StreamHelper(private val filamentEngine: Engine, private val filamentMater
filamentTexture.setExternalStream(filamentEngine, filamentStream!!)
this.imageReader = ImageReader.newInstance(resolution.width, resolution.height, ImageFormat.RGB_565, kImageReaderMaxImages).apply {
this.imageReader = ImageReader.newInstance(
resolution.width, resolution.height, ImageFormat.RGB_565, kImageReaderMaxImages
).apply {
canvasSurface = surface
}
}

View File

@@ -1,6 +1,8 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: FilamentToolsPlugin
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'filament-tools-plugin'
}
project.ext.isSample = true
@@ -21,6 +23,12 @@ android {
targetSdkVersion versions.targetSdk
}
// 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 {
includeInApk = false
}
// We use the .filamat extension for materials compiled with matc
// Telling aapt to not compress them allows to load them efficiently
aaptOptions {

View File

@@ -9,7 +9,9 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<activity
android:exported="true"
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>

View File

@@ -1,6 +1,8 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: FilamentToolsPlugin
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'filament-tools-plugin'
}
project.ext.isSample = true
@@ -28,6 +30,12 @@ android {
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 {
includeInApk = false
}
// We use the .filamat extension for materials compiled with matc
// Telling aapt to not compress them allows to load them efficiently
aaptOptions {

View File

@@ -9,7 +9,9 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name="com.google.android.filament.textured.MainActivity">
<activity
android:exported="true"
android:name="com.google.android.filament.textured.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>

View File

@@ -1,6 +1,8 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: FilamentToolsPlugin
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'filament-tools-plugin'
}
project.ext.isSample = true
@@ -21,6 +23,12 @@ android {
targetSdkVersion versions.targetSdk
}
// 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 {
includeInApk = false
}
// We use the .filamat extension for materials compiled with matc
// Telling aapt to not compress them allows to load them efficiently
aaptOptions {

View File

@@ -9,7 +9,9 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name="com.google.android.filament.transparentrendering.MainActivity">
<activity
android:exported="true"
android:name="com.google.android.filament.transparentrendering.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>

View File

@@ -281,7 +281,7 @@ class MainActivity : Activity() {
// Stop the animation and any pending frame
choreographer.removeFrameCallback(frameScheduler)
animator.cancel();
animator.cancel()
// Always detach the surface before destroying the engine
uiHelper.detach()
@@ -328,11 +328,11 @@ class MainActivity : Activity() {
override fun onNativeWindowChanged(surface: Surface) {
swapChain?.let { engine.destroySwapChain(it) }
swapChain = engine.createSwapChain(surface, uiHelper.swapChainFlags)
displayHelper.attach(renderer, surfaceView.display);
displayHelper.attach(renderer, surfaceView.display)
}
override fun onDetachedFromSurface() {
displayHelper.detach();
displayHelper.detach()
swapChain?.let {
engine.destroySwapChain(it)
// Required to ensure we don't return before Filament is done executing the
@@ -353,6 +353,7 @@ class MainActivity : Activity() {
}
}
@Suppress("SameParameterValue")
private fun readUncompressedAsset(assetName: String): ByteBuffer {
assets.openFd(assetName).use { fd ->
val input = fd.createInputStream()

View File

@@ -453,23 +453,23 @@ function build_android {
if [[ "${ISSUE_DEBUG_BUILD}" == "true" ]]; then
./gradlew \
-Pfilament_dist_dir=../out/android-debug/filament \
-Pfilament_abis=${ABI_GRADLE_OPTION} \
-Pcom.google.android.filament.dist-dir=../out/android-debug/filament \
-Pcom.google.android.filament.abis=${ABI_GRADLE_OPTION} \
${VULKAN_ANDROID_GRADLE_OPTION} \
:filament-android:assembleDebug \
:gltfio-android:assembleDebug \
:filament-utils-android:assembleDebug
./gradlew \
-Pfilament_dist_dir=../out/android-debug/filament \
-Pfilament_abis=${ABI_GRADLE_OPTION} \
-Pcom.google.android.filament.dist-dir=../out/android-debug/filament \
-Pcom.google.android.filament.abis=${ABI_GRADLE_OPTION} \
:filamat-android:assembleDebug
if [[ "${BUILD_ANDROID_SAMPLES}" == "true" ]]; then
for sample in ${ANDROID_SAMPLES}; do
./gradlew \
-Pfilament_dist_dir=../out/android-debug/filament \
-Pfilament_abis=${ABI_GRADLE_OPTION} \
-Pcom.google.android.filament.dist-dir=../out/android-debug/filament \
-Pcom.google.android.filament.abis=${ABI_GRADLE_OPTION} \
:samples:${sample}:assembleDebug
done
fi
@@ -487,8 +487,7 @@ function build_android {
cp gltfio-android/build/outputs/aar/gltfio-android-full-debug.aar ../out/gltfio-android-debug.aar
echo "Installing out/filament-utils-android-debug.aar..."
cp filament-utils-android/build/outputs/aar/filament-utils-android-lite-debug.aar ../out/
cp filament-utils-android/build/outputs/aar/filament-utils-android-full-debug.aar ../out/filament-utils-android-debug.aar
cp filament-utils-android/build/outputs/aar/filament-utils-android-debug.aar ../out/filament-utils-android-debug.aar
if [[ "${BUILD_ANDROID_SAMPLES}" == "true" ]]; then
for sample in ${ANDROID_SAMPLES}; do
@@ -502,23 +501,23 @@ function build_android {
if [[ "${ISSUE_RELEASE_BUILD}" == "true" ]]; then
./gradlew \
-Pfilament_dist_dir=../out/android-release/filament \
-Pfilament_abis=${ABI_GRADLE_OPTION} \
-Pcom.google.android.filament.dist-dir=../out/android-release/filament \
-Pcom.google.android.filament.abis=${ABI_GRADLE_OPTION} \
${VULKAN_ANDROID_GRADLE_OPTION} \
:filament-android:assembleRelease \
:gltfio-android:assembleRelease \
:filament-utils-android:assembleRelease
./gradlew \
-Pfilament_dist_dir=../out/android-release/filament \
-Pfilament_abis=${ABI_GRADLE_OPTION} \
-Pcom.google.android.filament.dist-dir=../out/android-release/filament \
-Pcom.google.android.filament.abis=${ABI_GRADLE_OPTION} \
:filamat-android:assembleRelease
if [[ "${BUILD_ANDROID_SAMPLES}" == "true" ]]; then
for sample in ${ANDROID_SAMPLES}; do
./gradlew \
-Pfilament_dist_dir=../out/android-release/filament \
-Pfilament_abis=${ABI_GRADLE_OPTION} \
-Pcom.google.android.filament.dist-dir=../out/android-release/filament \
-Pcom.google.android.filament.abis=${ABI_GRADLE_OPTION} \
:samples:${sample}:assembleRelease
done
fi
@@ -536,8 +535,7 @@ function build_android {
cp gltfio-android/build/outputs/aar/gltfio-android-full-release.aar ../out/gltfio-android-release.aar
echo "Installing out/filament-utils-android-release.aar..."
cp filament-utils-android/build/outputs/aar/filament-utils-android-lite-release.aar ../out/
cp filament-utils-android/build/outputs/aar/filament-utils-android-full-release.aar ../out/filament-utils-android-release.aar
cp filament-utils-android/build/outputs/aar/filament-utils-android-release.aar ../out/filament-utils-android-release.aar
if [[ "${BUILD_ANDROID_SAMPLES}" == "true" ]]; then
for sample in ${ANDROID_SAMPLES}; do
@@ -831,7 +829,7 @@ while getopts ":hacCfijmp:q:uvslwtdk:" opt; do
;;
v)
VULKAN_ANDROID_OPTION="-DFILAMENT_SUPPORTS_VULKAN=OFF"
VULKAN_ANDROID_GRADLE_OPTION="-Pfilament_exclude_vulkan"
VULKAN_ANDROID_GRADLE_OPTION="-Pcom.google.android.filament.exclude-vulkan"
echo "Disabling support for Vulkan in the core Filament library."
echo "Consider using -c after changing this option to clear the Gradle cache."
;;

View File

@@ -52,11 +52,11 @@ if [[ ! -d "${ANDROID_HOME}/ndk/$FILAMENT_NDK_VERSION" ]]; then
${ANDROID_HOME}/tools/bin/sdkmanager "ndk;$FILAMENT_NDK_VERSION" > /dev/null
fi
# Only build 1 32 bit and 1 64 bit target during presubmit to cut down build times
# Only build 1 64 bit target during presubmit to cut down build times during presubmit
# Continuous builds will build everything
ANDROID_ABIS=
if [[ "$TARGET" == "presubmit" ]]; then
ANDROID_ABIS="-q arm64-v8a,x86"
ANDROID_ABIS="-q arm64-v8a"
fi
# Build the Android sample-gltf-viewer APK during release.

View File

@@ -1 +1 @@
22.1.7171670
23.1.7779620

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