Commit graph

12 commits

Author SHA1 Message Date
Matty Weatherley
c60dcea231
Derivative access patterns for curves (#16503)
# Objective

- For curves that also include derivatives, make accessing derivative
information via the `Curve` API ergonomic: that is, provide access to a
curve that also samples derivative information.
- Implement this functionality for cubic spline curves provided by
`bevy_math`.

Ultimately, this is to serve the purpose of doing more geometric
operations on curves, like reparametrization by arclength and the
construction of moving frames.

## Solution

This has several parts, some of which may seem redundant. However, care
has been put into this to satisfy the following constraints:
- Accessing a `Curve` that samples derivative information should be not
just possible but easy and non-error-prone. For example, given a
differentiable `Curve<Vec2>`, one should be able to access something
like a `Curve<(Vec2, Vec2)>` ergonomically, and not just sample the
derivatives piecemeal from point to point.
- Derivative access should not step on the toes of ordinary curve usage.
In particular, in the above scenario, we want to avoid simply making the
same curve both a `Curve<Vec2>` and a `Curve<(Vec2, Vec2)>` because this
requires manual disambiguation when the API is used.
- Derivative access must work gracefully in both owned and borrowed
contexts.

### `HasTangent`

We introduce a trait `HasTangent` that provides an associated `Tangent`
type for types that have tangent spaces:
```rust
pub trait HasTangent {
    /// The tangent type.
    type Tangent: VectorSpace;
}
```

(Mathematically speaking, it would be more precise to say that these are
types that represent spaces which are canonically
[parallelized](https://en.wikipedia.org/wiki/Parallelizable_manifold). )

The idea here is that a point moving through a `HasTangent` type may
have a derivative valued in the associated `Tangent` type at each time
in its journey. We reify this with a `WithDerivative<T>` type that uses
`HasTangent` to include derivative information:
```rust
pub struct WithDerivative<T>
where
    T: HasTangent,
{
    /// The underlying value.
    pub value: T,

    /// The derivative at `value`.
    pub derivative: T::Tangent,
}
```

And we can play the same game with second derivatives as well, since
every `VectorSpace` type is `HasTangent` where `Tangent` is itself (we
may want to be more restrictive with this in practice, but this holds
mathematically).
```rust
pub struct WithTwoDerivatives<T>
where
    T: HasTangent,
{
    /// The underlying value.
    pub value: T,

    /// The derivative at `value`.
    pub derivative: T::Tangent,

    /// The second derivative at `value`.
    pub second_derivative: <T::Tangent as HasTangent>::Tangent,
}
```

In this PR, `HasTangent` is only implemented for `VectorSpace` types,
but it would be valuable to have this implementation for types like
`Rot2` and `Quat` as well. We could also do it for the isometry types
and, potentially, transforms as well. (This is in decreasing order of
value in my opinion.)

### `CurveWithDerivative`

This is a trait for a `Curve<T>` which allows the construction of a
`Curve<WithDerivative<T>>` when derivative information is known
intrinsically. It looks like this:
```rust
/// Trait for curves that have a well-defined notion of derivative, allowing for
/// derivatives to be extracted along with values.
pub trait CurveWithDerivative<T>
where
    T: HasTangent,
{
    /// This curve, but with its first derivative included in sampling.
    fn with_derivative(self) -> impl Curve<WithDerivative<T>>;
}
```

The idea here is to provide patterns like this:
```rust
let value_and_derivative = my_curve.with_derivative().sample_clamped(t);
```

One of the main points here is that `Curve<WithDerivative<T>>` is useful
as an output because it can be used durably. For example, in a dynamic
context, something that needs curves with derivatives can store
something like a `Box<dyn Curve<WithDerivative<T>>>`. Note that
`CurveWithDerivative` is not dyn-compatible.

### `SampleDerivative`

Many curves "know" how to sample their derivatives instrinsically, but
implementing `CurveWithDerivative` as given would be onerous or require
an annoying amount of boilerplate. There are also hurdles to overcome
that involve references to curves: for the `Curve` API, the expectation
is that curve transformations like `with_derivative` take things by
value, with the contract that they can still be used by reference
through deref-magic by including `by_ref` in a method chain.

These problems are solved simultaneously by a trait `SampleDerivative`
which, when implemented, automatically derives `CurveWithDerivative` for
a type and all types that dereference to it. It just looks like this:
```rust
pub trait SampleDerivative<T>: Curve<T>
where
    T: HasTangent,
{
    fn sample_with_derivative_unchecked(&self, t: f32) -> WithDerivative<T>;
    // ... other sampling variants as default methods
}
```

The point is that the output of `with_derivative` is a
`Curve<WithDerivative<T>>` that uses the `SampleDerivative`
implementation. On a `SampleDerivative` type, you can also just call
`my_curve.sample_with_derivative(t)` instead of something like
`my_curve.by_ref().with_derivative().sample(t)`, which is more verbose
and less accessible.

In practice, `CurveWithDerivative<T>` is actually a "sealed" extension
trait of `SampleDerivative<T>`.

## Adaptors

`SampleDerivative` has automatic implementations on all curve adaptors
except for `FunctionCurve`, `MapCurve`, and `ReparamCurve` (because we
do not have a notion of differentiable Rust functions).

For example, `CurveReparamCurve` (the reparametrization of a curve by
another curve) can compute derivatives using the chain rule in the case
both its constituents have them.

## Testing

Tests for derivatives on the curve adaptors are included.

---

## Showcase

This development allows derivative information to be included with and
extracted from curves using the `Curve` API.
```rust
let points = [
    vec2(-1.0, -20.0),
    vec2(3.0, 2.0),
    vec2(5.0, 3.0),
    vec2(9.0, 8.0),
];

// A cubic spline curve that goes through `points`.
let curve = CubicCardinalSpline::new(0.3, points).to_curve().unwrap();

// Calling `with_derivative` causes derivative output to be included in the output of the curve API.
let curve_with_derivative = curve.with_derivative();

// A `Curve<f32>` that outputs the speed of the original.
let speed_curve = curve_with_derivative.map(|x| x.derivative.norm());
```

---

## Questions

- ~~Maybe we should seal `WithDerivative` or make it require
`SampleDerivative` (i.e. make it unimplementable except through
`SampleDerivative`).~~ I decided this is a good idea.
- ~~Unclear whether `VectorSpace: HasTangent` blanket implementation is
really appropriate. For colors, for example, I'm not sure that the
derivative values can really be interpreted as a color. In any case, it
should still remain the case that `VectorSpace` types are `HasTangent`
and that `HasTangent::Tangent: HasTangent`.~~ I think this is fine.
- Infinity bikeshed on names of traits and things.

## Future

- Faster implementations of `SampleDerivative` for cubic spline curves.
- Improve ergonomics for accessing only derivatives (and other kinds of
transformations on derivative curves).
- Implement `HasTangent` for:
  - `Rot2`/`Quat`
  - `Isometry` types
  - `Transform`, maybe
- Implement derivatives for easing curves.
- Marker traits for continuous/differentiable curves. (It's actually
unclear to me how much value this has in practice, but we have discussed
it in the past.)

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-12-10 20:27:37 +00:00
homersimpsons
a6b5f80715
⬆️ Upgrade typos and its configuration (#16712)
# Objective

Fixes #16610, related to #16702

## Solution

Upgrade typos and its configuration

## Testing

- Did you test these changes? If so, how? No
- Are there any parts that need more testing? No
- How can other people (reviewers) test your changes? Is there anything
specific they need to know? No
- If relevant, what platforms did you test these changes on, and are
there any important ones you can't test? Not applicable
2024-12-08 17:25:10 +00:00
Rob Parrett
30d84519a2
Use en-us locale for typos (#16037)
# Objective

Bevy seems to want to standardize on "American English" spellings. Not
sure if this is laid out anywhere in writing, but see also #15947.

While perusing the docs for `typos`, I noticed that it has a `locale`
config option and tried it out.

## Solution

Switch to `en-us` locale in the `typos` config and run `typos -w`

## Migration Guide

The following methods or fields have been renamed from `*dependants*` to
`*dependents*`.

- `ProcessorAssetInfo::dependants`
- `ProcessorAssetInfos::add_dependant`
- `ProcessorAssetInfos::non_existent_dependants`
- `AssetInfo::dependants_waiting_on_load`
- `AssetInfo::dependants_waiting_on_recursive_dep_load`
- `AssetInfos::loader_dependants`
- `AssetInfos::remove_dependants_and_labels`
2024-10-20 18:55:17 +00:00
Ben Frankel
b0fd3d524f
Typo-check .hidden files (#16035)
# Objective

Typo-check .hidden files like `.cargo/config_fast_builds.toml` and
`.github/*`. Context: https://github.com/bevyengine/bevy/pull/16025.

## Solution

- Add `ignore-hidden = false` to `typos.toml` to override the default
value of `true`.
- Add an exception to keep `.git/` ignored in `typos.toml`.
- Fix newly-found typos so CI passes.

## Testing

Running `typos` locally finds no further typos.
2024-10-20 17:13:14 +00:00
Patrick Walton
2ae5a21009
Implement percentage-closer soft shadows (PCSS). (#13497)
[*Percentage-closer soft shadows*] are a technique from 2004 that allow
shadows to become blurrier farther from the objects that cast them. It
works by introducing a *blocker search* step that runs before the normal
shadow map sampling. The blocker search step detects the difference
between the depth of the fragment being rasterized and the depth of the
nearby samples in the depth buffer. Larger depth differences result in a
larger penumbra and therefore a blurrier shadow.

To enable PCSS, fill in the `soft_shadow_size` value in
`DirectionalLight`, `PointLight`, or `SpotLight`, as appropriate. This
shadow size value represents the size of the light and should be tuned
as appropriate for your scene. Higher values result in a wider penumbra
(i.e. blurrier shadows).

When using PCSS, temporal shadow maps
(`ShadowFilteringMethod::Temporal`) are recommended. If you don't use
`ShadowFilteringMethod::Temporal` and instead use
`ShadowFilteringMethod::Gaussian`, Bevy will use the same technique as
`Temporal`, but the result won't vary over time. This produces a rather
noisy result. Doing better would likely require downsampling the shadow
map, which would be complex and slower (and would require PR #13003 to
land first).

In addition to PCSS, this commit makes the near Z plane for the shadow
map configurable on a per-light basis. Previously, it had been hardcoded
to 0.1 meters. This change was necessary to make the point light shadow
map in the example look reasonable, as otherwise the shadows appeared
far too aliased.

A new example, `pcss`, has been added. It demonstrates the
percentage-closer soft shadow technique with directional lights, point
lights, spot lights, non-temporal operation, and temporal operation. The
assets are my original work.

Both temporal and non-temporal shadows are rather noisy in the example,
and, as mentioned before, this is unavoidable without downsampling the
depth buffer, which we can't do yet. Note also that the shadows don't
look particularly great for point lights; the example simply isn't an
ideal scene for them. Nevertheless, I felt that the benefits of the
ability to do a side-by-side comparison of directional and point lights
outweighed the unsightliness of the point light shadows in that example,
so I kept the point light feature in.

Fixes #3631.

[*Percentage-closer soft shadows*]:
https://developer.download.nvidia.com/shaderlibrary/docs/shadow_PCSS.pdf

## Changelog

### Added

* Percentage-closer soft shadows (PCSS) are now supported, allowing
shadows to become blurrier as they stretch away from objects. To use
them, set the `soft_shadow_size` field in `DirectionalLight`,
`PointLight`, or `SpotLight`, as applicable.

* The near Z value for shadow maps is now customizable via the
`shadow_map_near_z` field in `DirectionalLight`, `PointLight`, and
`SpotLight`.

## Screenshots

PCSS off:
![Screenshot 2024-05-24
120012](https://github.com/bevyengine/bevy/assets/157897/0d35fe98-245b-44fb-8a43-8d0272a73b86)

PCSS on:
![Screenshot 2024-05-24
115959](https://github.com/bevyengine/bevy/assets/157897/83397ef8-1317-49dd-bfb3-f8286d7610cd)

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Torstein Grindvik <52322338+torsteingrindvik@users.noreply.github.com>
2024-09-18 18:07:17 +00:00
François Mockers
d5ccb096b5
remove changelog file (#14564)
# Objective

- Remove CHANGELOG.md
- it's redundant with the release blog / the git log
- it's an extra step that may be forgotten in the release process (it
was not updated for the 0.14)
- it's an extra file at the root

## Solution

- Remove it
2024-07-31 22:24:33 +00:00
Patrick Walton
ace4c6023b
Implement subpixel morphological antialiasing, or SMAA. (#13423)
This commit implements a large subset of [*subpixel morphological
antialiasing*], better known as SMAA. SMAA is a 2011 antialiasing
technique that detects jaggies in an aliased image and smooths them out.
Despite its age, it's been a continual staple of games for over a
decade. Four quality presets are available: *low*, *medium*, *high*, and
*ultra*. I set the default to *high*, on account of modern GPUs being
significantly faster than they were in 2011.

Like the already-implemented FXAA, SMAA works on an unaliased image.
Unlike FXAA, it requires three passes: (1) edge detection; (2) blending
weight calculation; (3) neighborhood blending. Each of the first two
passes writes an intermediate texture for use by the next pass. The
first pass also writes to a stencil buffer in order to dramatically
reduce the number of pixels that the second pass has to examine. Also
unlike FXAA, two built-in lookup textures are required; I bundle them
into the library in compressed KTX2 format.

The [reference implementation of SMAA] is in HLSL, with abundant use of
preprocessor macros to achieve GLSL compatibility. Unfortunately, the
reference implementation predates WGSL by over a decade, so I had to
translate the HLSL to WGSL manually. As much as was reasonably possible
without sacrificing readability, I tried to translate line by line,
preserving comments, both to aid reviewing and to allow patches to the
HLSL to more easily apply to the WGSL. Most of SMAA's features are
supported, but in the interests of making this patch somewhat less huge,
I skipped a few of the more exotic ones:

* The temporal variant is currently unsupported. This is and has been
used in shipping games, so supporting temporal SMAA would be useful
follow-up work. It would, however, require some significant work on TAA
to ensure compatibility, so I opted to skip it in this patch.

* Depth- and chroma-based edge detection are unimplemented; only luma
is. Depth is lower-quality, but faster; chroma is higher-quality, but
slower. Luma is the suggested default edge detection algorithm. (Note
that depth-based edge detection wouldn't work on WebGL 2 anyway, because
of the Naga bug whereby depth sampling is miscompiled in GLSL. This is
the same bug that prevents depth of field from working on that
platform.)

* Predicated thresholding is currently unsupported.

* My implementation is incompatible with SSAA and MSAA, unlike the
original; MSAA must be turned off to use SMAA in Bevy. I believe this
feature was rarely used in practice.

The `anti_aliasing` example has been updated to allow experimentation
with and testing of the different SMAA quality presets. Along the way, I
refactored the example's help text rendering code a bit to eliminate
code repetition.

SMAA is fully supported on WebGL 2.

Fixes #9819.

[*subpixel morphological antialiasing*]: https://www.iryoku.com/smaa/

[reference implementation of SMAA]: https://github.com/iryoku/smaa

## Changelog

### Added

* Subpixel morphological antialiasing, or SMAA, is now available. To use
it, add the `SmaaSettings` component to your `Camera`.

![Screenshot 2024-05-18
134311](https://github.com/bevyengine/bevy/assets/157897/ffbd611c-1b32-4491-b2e2-e410688852ee)

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
2024-06-04 17:07:34 +00:00
Patrick Walton
df8ccb8735
Implement PBR anisotropy per KHR_materials_anisotropy. (#13450)
This commit implements support for physically-based anisotropy in Bevy's
`StandardMaterial`, following the specification for the
[`KHR_materials_anisotropy`] glTF extension.

[*Anisotropy*] (not to be confused with [anisotropic filtering]) is a
PBR feature that allows roughness to vary along the tangent and
bitangent directions of a mesh. In effect, this causes the specular
light to stretch out into lines instead of a round lobe. This is useful
for modeling brushed metal, hair, and similar surfaces. Support for
anisotropy is a common feature in major game and graphics engines;
Unity, Unreal, Godot, three.js, and Blender all support it to varying
degrees.

Two new parameters have been added to `StandardMaterial`:
`anisotropy_strength` and `anisotropy_rotation`. Anisotropy strength,
which ranges from 0 to 1, represents how much the roughness differs
between the tangent and the bitangent of the mesh. In effect, it
controls how stretched the specular highlight is. Anisotropy rotation
allows the roughness direction to differ from the tangent of the model.

In addition to these two fixed parameters, an *anisotropy texture* can
be supplied. Such a texture should be a 3-channel RGB texture, where the
red and green values specify a direction vector using the same
conventions as a normal map ([0, 1] color values map to [-1, 1] vector
values), and the the blue value represents the strength. This matches
the format that the [`KHR_materials_anisotropy`] specification requires.
Such textures should be loaded as linear and not sRGB. Note that this
texture does consume one additional texture binding in the standard
material shader.

The glTF loader has been updated to properly parse the
`KHR_materials_anisotropy` extension.

A new example, `anisotropy`, has been added. This example loads and
displays the barn lamp example from the [`glTF-Sample-Assets`]
repository. Note that the textures were rather large, so I shrunk them
down and converted them to a mixture of JPEG and KTX2 format, in the
interests of saving space in the Bevy repository.

[*Anisotropy*]:
https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel

[anisotropic filtering]:
https://en.wikipedia.org/wiki/Anisotropic_filtering

[`KHR_materials_anisotropy`]:
https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_anisotropy/README.md

[`glTF-Sample-Assets`]:
https://github.com/KhronosGroup/glTF-Sample-Assets/

## Changelog

### Added

* Physically-based anisotropy is now available for materials, which
enhances the look of surfaces such as brushed metal or hair. glTF scenes
can use the new feature with the `KHR_materials_anisotropy` extension.

## Screenshots

With anisotropy:
![Screenshot 2024-05-20
233414](https://github.com/bevyengine/bevy/assets/157897/379f1e42-24e9-40b6-a430-f7d1479d0335)

Without anisotropy:
![Screenshot 2024-05-20
233420](https://github.com/bevyengine/bevy/assets/157897/aa220f05-b8e7-417c-9671-b242d4bf9fc4)
2024-06-03 23:46:06 +00:00
BD103
52d6147e91
Fix asset-source-website.patch line number (#13286)
# Objective

- Ever since #13177, the `check-example-showcase-patches-still-work` job
has been failing in the merge queue.
- Specifically, the `asset-source-website.patch` file which modifies
`bevy_asset`'s `lib.rs`.

## Solution

- Re-create the patch.
  - Due to new content being added, the line numbers were off.
- Also, turns out that `typos` was checking patch files. This turned
into a CI error, so I disabled that too. Patches shouldn't really be
modified manually, the original source should be. (Also it was erroring
on the commit hash.)

## Testing

- Test the new patch works by running `git apply
tools/example-showcase/asset-source-website.patch`.
- Verify the merge queue passes with the
`check-example-showcase-patches-still-work` job succeeding.
2024-05-12 20:49:43 +00:00
Martín Maita
3fc0c6869d
Bump crate-ci/typos from 1.19.0 to 1.20.4 (#12907)
# Objective

- Adopting https://github.com/bevyengine/bevy/pull/12903.

## Solution

- Bump crate-ci/typos from 1.19.0 to 1.20.4.
- Fixed a typo in `crates/bevy_pbr/src/render/pbr_functions.wgsl` file.
- Added "PNG", "iy" and "SME" as exceptions to prevent false positives.

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-08 15:31:11 +00:00
Ame
e32791e97a
remove comment in typos.toml (#12303)
I don't know how this ended here 🤷
2024-03-04 20:34:22 +00:00
Ame
c97d0103cc
Add typos - Source code spell checker (#12036)
# Objective

- Avoid misspellings throughout the codebase by using
[`typos`](https://github.com/crate-ci/typos) in CI

Inspired by https://github.com/gfx-rs/wgpu/pull/5191

Typos is a minimal code speller written in rust that finds and corrects
spelling mistakes among source code.
 - Fast enough to run on monorepos
 - Low false positives so you can run on PRs


## Solution

- Use
[typos-action](https://github.com/marketplace/actions/typos-action) in
CI
- Add how to use typos in the Contribution Guide

---------

Co-authored-by: François <mockersf@gmail.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: Joona Aalto <jondolf.dev@gmail.com>
2024-02-26 16:19:40 +00:00