Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

SG3: a glyph that grows the 3D text atlas is drawn whole

shinyobjectzba2dc6ade7c7
diff --git a/Cargo.lock b/Cargo.lock
index a63d49a9..74687353 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3438,8 +3438,6 @@ dependencies = [
[[package]]
name = "bevy_rich_text3d"
version = "0.8.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "97b3cfe8f7187fb6f8e4889b8e7dcf39ff36bf7a84fcbd4f7b69f7d3b8a7bfe4"
dependencies = [
"bevy",
"cosmic-text",
diff --git a/Cargo.toml b/Cargo.toml
index 49d09d87..b9ff57f2 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -328,6 +328,8 @@ muxide = { path = "vendor/muxide" }
usvg = { path = "vendor/usvg" }
# bevy_seedling 0.8.0 without its cpal 0.18 paths, ported to Bevy 0.20 (changes marked "raea:")
bevy_seedling = { path = "vendor/bevy_seedling" }
+# bevy_rich_text3d 0.8.0 whose glyph that grows the atlas is drawn whole (changes marked "raea:", docs/stage-guards.feature SG3)
+bevy_rich_text3d = { path = "vendor/bevy_rich_text3d" }
# bevy_text 0.20.0 on parley 0.12, so one parley builds (changes marked "raea:", docs/bevy-upgrade.md)
bevy_text = { path = "vendor/bevy_text" }
# bevy_ui 0.20.0 on Taffy 0.15, Blitz's, so one Taffy builds (changes marked "raea:", docs/bevy-upgrade.md)
diff --git a/docs/stage-guards.feature b/docs/stage-guards.feature
index efded9d2..1d23f458 100644
--- a/docs/stage-guards.feature
+++ b/docs/stage-guards.feature
@@ -74,8 +74,10 @@ Feature: Stage guards: a 3D render an agent can't break
# Status 11-21: built and green on main after SG1 and SG2 (f4b524f896): every sampled frame of the three repros
# matches at SSIM 0.9998 or more. The bar is tight enough: a sequence's frame 28 against frame 29 alone scores
# 0.986, so a part held since its first frame can't pass. Before SG1 the same repros showed frame 0's sphere,
- # box, words, colour and size in a sequence. The atlas's cut glyph is one frame, not a sequence: its repro and
- # test come with SG3.
+ # box, words, colour and size in a sequence. The atlas's cut glyph is one frame, not a sequence: its repro
+ # (glyph-atlas-probe.tsx, a cold atlas against a warm one) came with SG3, and with it a second measure, since SSIM
+ # over a whole frame scored the cut letter 0.9996: no more than 16 pixels off by over 96 levels, after an erosion
+ # drops lone pixels (a revealed word's edge noise).
Rule: The engine stops doing it
@@ -111,11 +113,20 @@ Feature: Stage guards: a 3D render an agent can't break
# Status 11-21 (branch stage-guards): text blocks are rows by identity; a_new_text_never_takes_an_old_ones_row
# passes. Fires, fog volumes, plates and the other kinds a live frame diffs whole still take their frame's id.
+ @done
Scenario: SG3. The atlas allocates before it draws
Given bevy_rich_text3d 0.8 reads the atlas's size before it allocates a glyph (tess_glyph)
When raea patches it ([patch] in Cargo.toml, a vendored copy, with the upstream issue filed)
+ Given the plan
+ | crate | file | lines | job |
+ | bevy_rich_text3d | vendor/bevy_rich_text3d/src/tess.rs | +5 | the atlas image's size read after the glyph is allocated, in both branches (stroked, filled) |
+ | (workspace) | Cargo.toml, vendor/vendor.toml | +8 | the [patch] and the vendor entry: why, and the exit (an upstream release that reads the size after allocating) |
+ | raea-render (test) | engine/render/tests/diag/glyph-atlas-probe.tsx | 35 | "cold" (the film's glyph set into a fresh atlas) and "warm" (six Inter weights first, out of shot) |
+ | (script) | tools/frame-pure-3d.sh | +25 | a repro with cold and warm compositions: the two frames must match |
Then glyph-atlas-probe.tsx draws every glyph whole with no warm-up text
- And projects/mobile-ads components/stage.tsx Warm() comes out
+ And projects/mobile-ads components/stage.tsx Warm() comes out once the project renders on a raea with SG3 (0.1.9)
+ # Status 11-21: on a build without the fix the cold probe cuts a Space Mono H (179 pixels off against warm); with
+ # it, 0 pixels off (SSIM 0.99996). The upstream issue is drafted, not filed: filing it is a public post.
Scenario: SG4. A part that won't despawn fails the render
# Status 11-21: a live scene now drops the rows under another first (a block's glyphs, a part's components), in a
diff --git a/engine/render/tests/diag/glyph-atlas-probe.tsx b/engine/render/tests/diag/glyph-atlas-probe.tsx
new file mode 100644
index 00000000..a3bc8acb
--- /dev/null
+++ b/engine/render/tests/diag/glyph-atlas-probe.tsx
@@ -0,0 +1,34 @@
+// The glyph atlas (docs/stage-guards.feature SG3). bevy_rich_text3d's atlas starts at 512x512 and doubles its height when
+// a glyph doesn't fit. "cold" draws the film's glyph set in League Gothic and Space Mono into a fresh atlas, so the
+// atlas doubles while those glyphs are allocated; "warm" first fills it with six weights of Inter out of shot, so it
+// has doubled before them. Before SG3 the glyph whose allocation doubled the atlas was drawn into the old bounds and
+// stayed cut ("cold" cut a Space Mono H; "warm" cut nothing, which is why the film warmed its atlas). The two must match
+// (tools/frame-pure-3d.sh compares them).
+import React from "react";
+import { AbsoluteFill, Composition, registerRoot } from "raea";
+import { Canvas3D, Entity, RichText } from "raea/3d";
+import { Camera3d } from "raea/camera";
+import { Transform } from "raea/transform";
+
+const G = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 .,:;!?()[]{}<>/|-_=+*#&%$@~^`·–—…’“”×'\"\\\\";
+
+function Probe({ warm }: { warm: number }) {
+ const weights = [100, 300, 500, 700, 900, 200].slice(0, warm);
+ return (
+ <AbsoluteFill style={{ background: "#F2EADB" }}>
+ <Canvas3D>
+ <Camera3d transform={Transform.fromXyz(0, 0, 6).lookingAt([0, 0, 0])} />
+ {weights.map((w, i) => <Entity key={i} transform={Transform.fromXyz(0, -60 - i, 0)}><RichText size={0.1} font="Inter" weight={w} unlit>{G}</RichText></Entity>)}
+ <Entity transform={Transform.fromXyz(0, 0.6, 0)}><RichText size={0.3} maxWidth={8} font="League Gothic" weight={400} color="#141414" unlit>{G}</RichText></Entity>
+ <Entity transform={Transform.fromXyz(0, -0.9, 0)}><RichText size={0.22} maxWidth={8} font="Space Mono" weight={700} color="#141414" unlit>{G}</RichText></Entity>
+ </Canvas3D>
+ </AbsoluteFill>
+ );
+}
+
+registerRoot(() => (
+ <>
+ <Composition id="cold" component={() => <Probe warm={0} />} width={1920} height={1080} fps={30} durationInFrames={1} />
+ <Composition id="warm" component={() => <Probe warm={6} />} width={1920} height={1080} fps={30} durationInFrames={1} />
+ </>
+));
diff --git a/tools/frame-pure-3d.sh b/tools/frame-pure-3d.sh
index 6ed35186..a4bc2931 100755
--- a/tools/frame-pure-3d.sh
+++ b/tools/frame-pure-3d.sh
@@ -9,14 +9,45 @@ set -uo pipefail
ROOT=$(cd "$(dirname "$0")/.." && pwd)
R=${RAEA_BIN:-$ROOT/target/release/raea}
BAR=${FRAME_PURE_BAR:-0.999}
+PX=${FRAME_PURE_PX:-16}
[ -x "$R" ] || { echo "frame-pure-3d: no raea at $R (cargo build --release -p raea-cli)" >&2; exit 2; }
command -v ffmpeg >/dev/null || { echo "frame-pure-3d: needs ffmpeg on PATH" >&2; exit 2; }
W=$(mktemp -d "${TMPDIR:-/tmp}/frame-pure-3d.XXXX")
trap 'rm -rf "$W"' EXIT
[ $# -gt 0 ] || set -- "$ROOT"/engine/render/tests/diag/*.tsx
fail=0
+ssim() {
+ ffmpeg -v info -i "$1" -i "$2" -lavfi "[0:v]format=rgb24[a];[1:v]format=rgb24[b];[a][b]ssim" -f null - 2>&1 | grep -oE 'All:[0-9.]+' | cut -d: -f2
+}
+# pixels that differ by more than 96 of 255 levels, in patches: SSIM over a whole frame hides one small part (a cut
+# letter scored 0.9996), and this doesn't. An erosion first drops lone pixels, the edge noise of a glyph drawn from
+# another place in the atlas (17 of them along two revealed words), and keeps a patch (a cut letter: 318)
+bad_px() {
+ ffmpeg -v error -i "$1" -i "$2" -filter_complex "[0:v]format=rgb24[a];[1:v]format=rgb24[b];[a][b]blend=all_mode=difference,format=gray,erosion" -f rawvideo - |
+ python3 -I -c 'import sys; d = sys.stdin.buffer.read(); print(len(d) - len(d.translate(None, bytes(range(97, 256))) ))'
+}
+# a pair matches when its SSIM is at the bar and no more than PX pixels differ by more than 96 levels
+differ() {
+ local s p
+ s=$(ssim "$1" "$2"); p=$(bad_px "$1" "$2")
+ echo "SSIM ${s:-none}, ${p:-?} pixels off"
+ [ -z "$s" ] || [ -z "$p" ] || awk -v s="$s" -v b="$BAR" -v p="$p" -v m="$PX" 'BEGIN { exit !(s < b || p > m) }'
+}
for t in "$@"; do
n=$(basename "$t" .tsx)
+ # a repro with a "cold" and a "warm" composition (the glyph atlas, SG3): what a cold atlas draws must match a warm one
+ if grep -q 'id="cold"' "$t" && grep -q 'id="warm"' "$t"; then
+ for c in cold warm; do
+ "$R" render "$t" --composition "$c" --frame 0 -o "$W/$n-$c.png" >"$W/$n-$c.log" 2>&1 || { echo "frame-pure-3d: $n: $c didn't render:"; tail -3 "$W/$n-$c.log"; fail=1; }
+ done
+ if m=$(differ "$W/$n-cold.png" "$W/$n-warm.png"); then
+ echo "frame-pure-3d: $n: drawn into a cold atlas it differs from a warm one ($m; bar SSIM $BAR, $PX pixels): a glyph allocated as the atlas grew is cut"
+ fail=1
+ else
+ echo "frame-pure-3d: $n: cold and warm atlas match ($m)"
+ fi
+ continue
+ fi
len=$(grep -oE 'durationInFrames=\{[0-9]+\}' "$t" | head -1 | grep -oE '[0-9]+')
[ "${len:-1}" -gt 1 ] || continue
if ! "$R" render "$t" -o "$W/$n/" >"$W/$n.log" 2>&1; then
@@ -27,12 +58,11 @@ for t in "$@"; do
echo "frame-pure-3d: $n: frame $f alone didn't render:"; tail -3 "$W/$n-$f.log"; fail=1; continue
fi
seq=$(printf '%s/%s/frame-%05d.png' "$W" "$n" "$f")
- s=$(ffmpeg -v info -i "$seq" -i "$W/$n-alone-$f.png" -lavfi "[0:v]format=rgb24[a];[1:v]format=rgb24[b];[a][b]ssim" -f null - 2>&1 | grep -oE 'All:[0-9.]+' | cut -d: -f2)
- if [ -z "$s" ] || awk -v s="$s" -v b="$BAR" 'BEGIN { exit !(s < b) }'; then
- echo "frame-pure-3d: $n frame $f: the sequence's frame differs from the frame rendered alone (SSIM ${s:-none}, bar $BAR): a 3D part kept an earlier frame's inputs or took another's row"
+ if m=$(differ "$seq" "$W/$n-alone-$f.png"); then
+ echo "frame-pure-3d: $n frame $f: the sequence's frame differs from the frame rendered alone ($m; bar SSIM $BAR, $PX pixels): a 3D part kept an earlier frame's inputs or took another's row"
fail=1
else
- echo "frame-pure-3d: $n frame $f: SSIM $s"
+ echo "frame-pure-3d: $n frame $f: $m"
fi
done
done
diff --git a/vendor/bevy_rich_text3d/Cargo.toml b/vendor/bevy_rich_text3d/Cargo.toml
new file mode 100644
index 00000000..46de7288
--- /dev/null
+++ b/vendor/bevy_rich_text3d/Cargo.toml
@@ -0,0 +1,108 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2024"
+name = "bevy_rich_text3d"
+version = "0.8.0"
+authors = ["Mincong Lu <[email protected]>"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+# raea: the examples left out of the vendored copy, with their entries
+autotests = false
+autobenches = false
+description = """
+Mesh based raster rich text implementation for bevy.
+"""
+readme = "README.md"
+keywords = [
+ "bevy",
+ "text",
+ "font",
+]
+license = "MIT OR Apache-2.0"
+repository = "https://github.com/mintlu8/bevy_rich_text3d"
+
+[features]
+a11y = []
+default = ["a11y"]
+reflect = []
+
+[lib]
+name = "bevy_rich_text3d"
+path = "src/lib.rs"
+
+[dependencies.bevy]
+version = "0.20.0"
+features = [
+ "bevy_log",
+ "bevy_image",
+ "bevy_render",
+ "bevy_asset",
+ "bevy_window",
+]
+default-features = false
+
+[dependencies.cosmic-text]
+version = "0.19"
+features = [
+ "fontconfig",
+ "std",
+]
+default-features = false
+
+[dependencies.fastrand]
+version = "2.3.0"
+default-features = false
+
+[dependencies.rustc-hash]
+version = "2.1.1"
+
+[dependencies.sys-locale]
+version = "0.3.2"
+
+[dependencies.thiserror]
+version = "2.0.9"
+
+[dependencies.tiny-skia]
+version = "0.12.0"
+features = [
+ "std",
+ "simd",
+]
+default-features = false
+
+[dependencies.ttf-parser]
+version = "0.25.1"
+
+[dependencies.write-fonts]
+version = "0.46.0"
+features = ["read"]
+
+[dev-dependencies.accesskit]
+version = "0.24.1"
+
+[dev-dependencies.bevy]
+version = "0.20.0"
+
+[dev-dependencies.bevy_rectray]
+version = "0.7.0"
+
+[dev-dependencies.fastrand]
+version = "2.3.0"
+
+[profile.dev]
+opt-level = 3
+
+[profile.dev.package."*"]
+opt-level = 3
diff --git a/vendor/bevy_rich_text3d/LICENSE-APACHE b/vendor/bevy_rich_text3d/LICENSE-APACHE
new file mode 100644
index 00000000..5a22fbc7
--- /dev/null
+++ b/vendor/bevy_rich_text3d/LICENSE-APACHE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2024 Mincong Lu
+
+ 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.
\ No newline at end of file
diff --git a/vendor/bevy_rich_text3d/LICENSE-MIT b/vendor/bevy_rich_text3d/LICENSE-MIT
new file mode 100644
index 00000000..21338db8
--- /dev/null
+++ b/vendor/bevy_rich_text3d/LICENSE-MIT
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2024 Mincong Lu
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/vendor/bevy_rich_text3d/README.md b/vendor/bevy_rich_text3d/README.md
new file mode 100644
index 00000000..3801b8da
--- /dev/null
+++ b/vendor/bevy_rich_text3d/README.md
@@ -0,0 +1,144 @@
+# bevy_rich_text3d
+
+[![Crates.io](https://img.shields.io/crates/v/bevy_rich_text3d.svg)](https://crates.io/crates/bevy_rich_text3d)
+[![Docs](https://docs.rs/bevy_rich_text3d/badge.svg)](https://docs.rs/bevy_rich_text3d/latest/bevy_rich_text3d/)
+[![Bevy tracking](https://img.shields.io/badge/Bevy%20tracking-released%20version-lightblue)](https://bevyengine.org/learn/book/plugin-development/)
+
+Mesh based raster rich text implementation for `bevy`.
+
+## Overview
+
+This crate is similar to `bevy_text` but aims to be more user friendly and powerful.
+
+Unlike `bevy_text`, this crate renders text as a `Mesh` and an `Image` atlas. This not only works
+with `StandardMaterial` but also can be empowered by user defined shaders.
+
+We render each glyph as a separate quad, meaning in shaders, we can easily manipulate
+individual glyphs for different effects. Additionally we support exporting specific values
+like glyph count, glyph position or user defined magic numbers via either `uv1` or custom mesh attributes.
+
+## Getting Started
+
+Add plugins:
+
+```rust, ignore
+app.add_plugins(Text3dPlugin{
+ default_atlas_dimension: (1024, 1024),
+ load_system_fonts: true,
+ ..Default::default()
+});
+
+// Add fonts via the `LoadFonts` resource.
+app.insert_resource(LoadFonts {
+ font_paths: vec!["assets/roboto.ttf".to_owned()],
+ font_directories: vec!["assets/fonts".to_owned()],
+ ..Default::default()
+});
+```
+
+Spawn a `Text3d`.
+
+```rust, ignore
+commands.spawn(
+ Text3d::new("Hello, World!"),
+ // Mesh2d also works
+ Mesh3d::default(),
+ MeshMaterial3d(materials.add(
+ StandardMaterial {
+ base_color_texture: Some(TextAtlas::DEFAULT_IMAGE.clone()),
+ alpha_mode: AlphaMode::Blend,
+ ..Default::default()
+ }
+ ))
+)
+```
+
+## Rich Text
+
+Rich text can be created from a string using the `Text3d::parse` function. We support a
+straightforward syntax:
+
+* `{style:value}`: equivalent to `<style>value</style>` in html.
+* `{value}` (without `:`): parse as a dynamic value that can be fetched from the world.
+
+See documentation on `Text3d::parse` for up-to-date syntax.
+
+## Dependencies
+
+* `cosmic_text`
+
+A minimal subset of Cosmic text is used for layout.
+
+* `tiny_skia`
+
+Used for tesselation.
+
+* `bevy`
+
+Bevy's asset system functions as an alternative to `swash`.
+
+## Glyph Atlas
+
+We store rendered glyphs inside a texture atlas in the component `TextAtlasHandle`.
+If you did not create a new one, all glyphs will be cached inside the same
+default texture, and you can use the convenient `TextAtlas::DEFAULT_IMAGE` as the image in your materials.
+
+However, if you need more control over where your glyphs are stored, you can manually
+create a `TextAtlas` and `Image` alongside your `Text3d`, they can be managed the same way
+as other assets.
+
+## Atlas Resize
+
+Atlas resize used to be a out of the box supported feature, since bevy 0.19 manual change detection
+is no longer needed as long as atlas is not resized, the feature is now optional. If you need
+atlas resize to work correctly, trigger change detection on your materials when `Text3dDimensionOut`
+is changed.
+
+## FAQ
+
+* How do I add fonts?
+
+Add them to the `LoadFonts` resource before the app starts.
+
+* Some glyphs are displaying as `▮▮▮▮`
+
+This means the placeholder glyphs for emojis are getting prioritized. You should
+either set the font family in `Text3dStyle` or set a default serif font in the plugin.
+
+* How do I use this crate on wasm?
+
+The easiest way to use this crate is to embed your fonts into the binary via `include_bytes!`,
+then add them to `LoadFonts` via `font_embedded`.
+
+## Showcase
+
+![image1](./showcase/a.gif)
+![image2](./showcase/b.gif)
+![image3](./showcase/c.gif)
+![image4](./showcase/d.gif)
+
+## Versions
+
+| bevy | bevy_rich_text3d |
+|------|------------------|
+| 0.15 | 0.1-0.2 |
+| 0.16 | 0.3-0.4 |
+| 0.17 | 0.5 |
+| 0.18 | 0.6 |
+| 0.19 | 0.7 |
+| 0.20 | 0.8-latest |
+
+## License
+
+Licensed under either of
+
+* Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
+* MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
+
+at your option.
+
+### Contribution
+
+Unless you explicitly state otherwise, any contribution intentionally submitted
+for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any
+additional terms or conditions.
diff --git a/vendor/bevy_rich_text3d/src/atlas.rs b/vendor/bevy_rich_text3d/src/atlas.rs
new file mode 100644
index 00000000..8e5c96f9
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/atlas.rs
@@ -0,0 +1,142 @@
+use std::marker::PhantomData;
+
+use bevy::{
+ asset::{Asset, Assets, Handle, RenderAssetUsages, uuid::Uuid},
+ ecs::component::Component,
+ image::Image,
+ log::{info, warn_once},
+ math::{IRect, IVec2, Vec2},
+ render::render_resource::{Extent3d, TextureDimension, TextureFormat},
+};
+use rustc_hash::FxHashMap;
+
+use crate::styling::GlyphEntry;
+
+#[cfg(feature = "reflect")]
+use bevy::{ecs::reflect::ReflectComponent, reflect::Reflect};
+
+/// Backing image handle and atlas of [`Text3d`](crate::Text3d).
+#[derive(Debug, Clone, Default, Asset)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+#[cfg_attr(not(feature = "reflect"), derive(bevy::reflect::TypePath))]
+pub struct TextAtlas {
+ pub(crate) image: Handle<Image>,
+ #[cfg_attr(feature = "reflect", reflect(ignore))]
+ pub(crate) glyphs: FxHashMap<GlyphEntry, (IRect, Vec2)>,
+ pub(crate) pointer: IVec2,
+ pub(crate) descent: usize,
+}
+
+const PADDING: usize = 2;
+
+impl TextAtlas {
+ /// The image used by [`TextAtlas::default()`].
+ #[allow(deprecated)]
+ pub const DEFAULT_IMAGE: Handle<Image> = Handle::Uuid(
+ Uuid::from_u128(0x9a5c50eb057602509c7836bb327807e1),
+ PhantomData,
+ );
+
+ /// Create a new empty [`TextAtlas`].
+ ///
+ /// The image can be created via [`TextAtlas::empty_image`].
+ pub fn new(image: Handle<Image>) -> Self {
+ Self {
+ image,
+ ..Default::default()
+ }
+ }
+
+ /// Create an empty [`Image`] filled with transparent white `(255, 255, 255, 0)`.
+ pub fn empty_image(width: usize, height: usize) -> Image {
+ Image::new(
+ Extent3d {
+ width: width as u32,
+ height: height as u32,
+ depth_or_array_layers: 1,
+ },
+ TextureDimension::D2,
+ vec![[255, 255, 255, 0]; width * height].into_flattened(),
+ TextureFormat::Rgba8Unorm,
+ RenderAssetUsages::all(),
+ )
+ }
+
+ /// Allocate space for a glyph, resizes if necessary but does not draw.
+ pub fn allocate(
+ &mut self,
+ image: &mut Image,
+ glyph: GlyphEntry,
+ base: Vec2,
+ width: usize,
+ height: usize,
+ ) -> IRect {
+ if let Some((rect, _)) = self.glyphs.get(&glyph) {
+ return *rect;
+ }
+ if self.pointer.x as usize + width + PADDING > image.width() as usize {
+ self.pointer.x = 0;
+ self.pointer.y += self.descent.max(height) as i32 + PADDING as i32;
+ self.descent = 0;
+ }
+ if image.data.is_none() {
+ return Default::default();
+ }
+ macro_rules! data {
+ ($($tt:tt)*) => {
+ image.data.as_mut().unwrap()[$($tt)*]
+ };
+ }
+ self.descent = self.descent.max(height);
+ if self.pointer.y as usize + self.descent + PADDING >= image.height() as usize {
+ info!("Text atlas size expanded!");
+ warn_once!(
+ "Text atlas expansion currently requires manually triggering change detection on materials to work."
+ );
+ let old_dim = (image.width() * image.height()) as usize;
+ image.resize(Extent3d {
+ width: image.width(),
+ height: image.height() * 2,
+ depth_or_array_layers: 1,
+ });
+ for i in old_dim..old_dim * 2 {
+ data![i * 4] = 255;
+ data![i * 4 + 1] = 255;
+ data![i * 4 + 2] = 255;
+ }
+ };
+ let dimension = IVec2::new(width as i32, height as i32);
+
+ let output = IRect {
+ min: self.pointer,
+ max: self.pointer + dimension,
+ };
+
+ self.glyphs.insert(glyph, (output, base));
+ self.pointer.x += dimension.x + PADDING as i32;
+
+ output
+ }
+
+ /// Clear all cached glyphs and repaint the image as transparent white.
+ pub fn clear(&mut self, images: &mut Assets<Image>) {
+ self.pointer = IVec2::ZERO;
+ self.glyphs.clear();
+ if let Some(mut img) = images.get_mut(self.image.id()) {
+ for chunk in img.data.as_mut().unwrap().chunks_mut(4) {
+ chunk[0] = 255;
+ chunk[1] = 255;
+ chunk[2] = 255;
+ chunk[3] = 0;
+ }
+ }
+ }
+}
+
+/// [`Component`] of a [`Handle<TextAtlas>`](TextAtlas), if left as default,
+/// will use the shared [`TextAtlas::DEFAULT_IMAGE`] as
+/// the underlying image.
+#[derive(Debug, Clone, Component, Default)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+#[cfg_attr(feature = "reflect", reflect(Component))]
+pub struct TextAtlasHandle(pub Handle<TextAtlas>);
diff --git a/vendor/bevy_rich_text3d/src/color_table.rs b/vendor/bevy_rich_text3d/src/color_table.rs
new file mode 100644
index 00000000..d48c7419
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/color_table.rs
@@ -0,0 +1,188 @@
+use bevy::color::palettes::css;
+use bevy::color::{ColorToPacked, Srgba};
+use bevy::math::VectorSpace;
+
+pub fn parse_color(s: &str) -> Option<Srgba> {
+ if s.starts_with('#') {
+ return parse_hex_color(s.split_at(1).1);
+ }
+ Some(match s {
+ "transparent" => Srgba::ZERO,
+ "aqua" => css::AQUA,
+ "black" => css::BLACK,
+ "blue" => css::BLUE,
+ "fuchsia" => css::FUCHSIA,
+ "gray" => css::GRAY,
+ "green" => css::GREEN,
+ "lime" => css::LIME,
+ "maroon" => css::MAROON,
+ "navy" => css::NAVY,
+ "olive" => css::OLIVE,
+ "purple" => css::PURPLE,
+ "red" => css::RED,
+ "silver" => css::SILVER,
+ "teal" => css::TEAL,
+ "white" => css::WHITE,
+ "yellow" => css::YELLOW,
+ "alice-blue" => css::ALICE_BLUE,
+ "antique-white" => css::ANTIQUE_WHITE,
+ "aquamarine" => css::AQUAMARINE,
+ "azure" => css::AZURE,
+ "beige" => css::BEIGE,
+ "bisque" => css::BISQUE,
+ "blanched-almond" => css::BLANCHED_ALMOND,
+ "blue-violet" => css::BLUE_VIOLET,
+ "brown" => css::BROWN,
+ "burlywood" => css::BURLYWOOD,
+ "cadet-blue" => css::CADET_BLUE,
+ "chartreuse" => css::CHARTREUSE,
+ "chocolate" => css::CHOCOLATE,
+ "coral" => css::CORAL,
+ "cornflower-blue" => css::CORNFLOWER_BLUE,
+ "cornsilk" => css::CORNSILK,
+ "crimson" => css::CRIMSON,
+ "dark-blue" => css::DARK_BLUE,
+ "dark-cyan" => css::DARK_CYAN,
+ "dark-goldenrod" => css::DARK_GOLDENROD,
+ "dark-gray" => css::DARK_GRAY,
+ "dark-green" => css::DARK_GREEN,
+ "dark-grey" => css::DARK_GREY,
+ "dark-khaki" => css::DARK_KHAKI,
+ "dark-magenta" => css::DARK_MAGENTA,
+ "dark-olivegreen" => css::DARK_OLIVEGREEN,
+ "dark-orange" => css::DARK_ORANGE,
+ "dark-orchid" => css::DARK_ORCHID,
+ "dark-red" => css::DARK_RED,
+ "dark-salmon" => css::DARK_SALMON,
+ "dark-sea-green" => css::DARK_SEA_GREEN,
+ "dark-slate-blue" => css::DARK_SLATE_BLUE,
+ "dark-slate-gray" => css::DARK_SLATE_GRAY,
+ "dark-slate-grey" => css::DARK_SLATE_GREY,
+ "dark-turquoise" => css::DARK_TURQUOISE,
+ "dark-violet" => css::DARK_VIOLET,
+ "deep-pink" => css::DEEP_PINK,
+ "deep-sky-blue" => css::DEEP_SKY_BLUE,
+ "dim-gray" => css::DIM_GRAY,
+ "dim-grey" => css::DIM_GREY,
+ "dodger-blue" => css::DODGER_BLUE,
+ "fire-brick" => css::FIRE_BRICK,
+ "floral-white" => css::FLORAL_WHITE,
+ "forest-green" => css::FOREST_GREEN,
+ "gainsboro" => css::GAINSBORO,
+ "ghost-white" => css::GHOST_WHITE,
+ "gold" => css::GOLD,
+ "goldenrod" => css::GOLDENROD,
+ "green-yellow" => css::GREEN_YELLOW,
+ "grey" => css::GREY,
+ "honeydew" => css::HONEYDEW,
+ "hot-pink" => css::HOT_PINK,
+ "indian-red" => css::INDIAN_RED,
+ "indigo" => css::INDIGO,
+ "ivory" => css::IVORY,
+ "khaki" => css::KHAKI,
+ "lavender" => css::LAVENDER,
+ "lavender-blush" => css::LAVENDER_BLUSH,
+ "lawn-green" => css::LAWN_GREEN,
+ "lemon-chiffon" => css::LEMON_CHIFFON,
+ "light-blue" => css::LIGHT_BLUE,
+ "light-coral" => css::LIGHT_CORAL,
+ "light-cyan" => css::LIGHT_CYAN,
+ "light-goldenrod-yellow" => css::LIGHT_GOLDENROD_YELLOW,
+ "light-gray" => css::LIGHT_GRAY,
+ "light-green" => css::LIGHT_GREEN,
+ "light-grey" => css::LIGHT_GREY,
+ "light-pink" => css::LIGHT_PINK,
+ "light-salmon" => css::LIGHT_SALMON,
+ "light-sea-green" => css::LIGHT_SEA_GREEN,
+ "light-sky-blue" => css::LIGHT_SKY_BLUE,
+ "light-slate-gray" => css::LIGHT_SLATE_GRAY,
+ "light-slate-grey" => css::LIGHT_SLATE_GREY,
+ "light-steel-blue" => css::LIGHT_STEEL_BLUE,
+ "light-yellow" => css::LIGHT_YELLOW,
+ "limegreen" => css::LIMEGREEN,
+ "linen" => css::LINEN,
+ "magenta" => css::MAGENTA,
+ "medium-aquamarine" => css::MEDIUM_AQUAMARINE,
+ "medium-blue" => css::MEDIUM_BLUE,
+ "medium-orchid" => css::MEDIUM_ORCHID,
+ "medium-purple" => css::MEDIUM_PURPLE,
+ "medium-sea-green" => css::MEDIUM_SEA_GREEN,
+ "medium-slate-blue" => css::MEDIUM_SLATE_BLUE,
+ "medium-spring-green" => css::MEDIUM_SPRING_GREEN,
+ "medium-turquoise" => css::MEDIUM_TURQUOISE,
+ "medium-violet-red" => css::MEDIUM_VIOLET_RED,
+ "midnight-blue" => css::MIDNIGHT_BLUE,
+ "mint-cream" => css::MINT_CREAM,
+ "misty-rose" => css::MISTY_ROSE,
+ "moccasin" => css::MOCCASIN,
+ "navajo-white" => css::NAVAJO_WHITE,
+ "old-lace" => css::OLD_LACE,
+ "olive-drab" => css::OLIVE_DRAB,
+ "orange" => css::ORANGE,
+ "orange-red" => css::ORANGE_RED,
+ "orchid" => css::ORCHID,
+ "pale-goldenrod" => css::PALE_GOLDENROD,
+ "pale-green" => css::PALE_GREEN,
+ "pale-turquoise" => css::PALE_TURQUOISE,
+ "pale-violetred" => css::PALE_VIOLETRED,
+ "papaya-whip" => css::PAPAYA_WHIP,
+ "peachpuff" => css::PEACHPUFF,
+ "peru" => css::PERU,
+ "pink" => css::PINK,
+ "plum" => css::PLUM,
+ "powder-blue" => css::POWDER_BLUE,
+ "rebecca-purple" => css::REBECCA_PURPLE,
+ "rosy-brown" => css::ROSY_BROWN,
+ "royal-blue" => css::ROYAL_BLUE,
+ "saddle-brown" => css::SADDLE_BROWN,
+ "salmon" => css::SALMON,
+ "sandy-brown" => css::SANDY_BROWN,
+ "sea-green" => css::SEA_GREEN,
+ "seashell" => css::SEASHELL,
+ "sienna" => css::SIENNA,
+ "sky-blue" => css::SKY_BLUE,
+ "slate-blue" => css::SLATE_BLUE,
+ "slate-gray" => css::SLATE_GRAY,
+ "slate-grey" => css::SLATE_GREY,
+ "snow" => css::SNOW,
+ "spring-green" => css::SPRING_GREEN,
+ "steel-blue" => css::STEEL_BLUE,
+ "tan" => css::TAN,
+ "thistle" => css::THISTLE,
+ "tomato" => css::TOMATO,
+ "turquoise" => css::TURQUOISE,
+ "violet" => css::VIOLET,
+ "wheat" => css::WHEAT,
+ "white-smoke" => css::WHITE_SMOKE,
+ "yellow-green" => css::YELLOW_GREEN,
+ _ => return None,
+ })
+}
+
+pub fn parse_hex_color(s: &str) -> Option<Srgba> {
+ fn h(b: &u8) -> Option<u8> {
+ match b {
+ b'0'..=b'9' => Some(*b - b'0'),
+ b'a'..=b'f' => Some(*b - b'a' + 10),
+ b'A'..=b'F' => Some(*b - b'A' + 10),
+ _ => None,
+ }
+ }
+ Some(Srgba::from_u8_array(match s.as_bytes() {
+ [r, g, b] => [h(r)? * 0x11, h(g)? * 0x11, h(b)? * 0x11, 255],
+ [r, g, b, a] => [h(r)? * 0x11, h(g)? * 0x11, h(b)? * 0x11, h(a)? * 0x11],
+ [r1, r2, g1, g2, b1, b2] => [
+ h(r1)? * 0x10 + h(r2)?,
+ h(g1)? * 0x10 + h(g2)?,
+ h(b1)? * 0x10 + h(b2)?,
+ 255,
+ ],
+ [r1, r2, g1, g2, b1, b2, a1, a2] => [
+ h(r1)? * 0x10 + h(r2)?,
+ h(g1)? * 0x10 + h(g2)?,
+ h(b1)? * 0x10 + h(b2)?,
+ h(a1)? * 0x10 + h(a2)?,
+ ],
+ _ => return None,
+ }))
+}
diff --git a/vendor/bevy_rich_text3d/src/emoji.rs b/vendor/bevy_rich_text3d/src/emoji.rs
new file mode 100644
index 00000000..716b3bf5
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/emoji.rs
@@ -0,0 +1,140 @@
+use write_fonts::{
+ OffsetMarker,
+ read::tables::glyf::CurvePoint,
+ tables::{
+ cmap::{Cmap, CmapSubtable, EncodingRecord, PlatformId, SequentialMapGroup},
+ glyf::{Bbox, Contour, GlyfLocaBuilder, SimpleGlyph},
+ head::Head,
+ hhea::Hhea,
+ hmtx::Hmtx,
+ maxp::Maxp,
+ name::{Name, NameRecord},
+ vmtx::LongMetric,
+ },
+ types::{FWord, NameId},
+};
+
+pub fn create_emoji_font(name: &str, widths: &[f32], c: char) -> Vec<u8> {
+ use write_fonts::FontBuilder;
+
+ let mut builder = FontBuilder::new();
+
+ let _ = builder.add_table(&Name {
+ name_record: vec![
+ NameRecord::new(0, 0, 0, NameId::FAMILY_NAME, OffsetMarker::new(name.into())),
+ NameRecord::new(
+ 0,
+ 0,
+ 0,
+ NameId::SUBFAMILY_NAME,
+ OffsetMarker::new("Regular".into()),
+ ),
+ NameRecord::new(0, 0, 0, NameId::UNIQUE_ID, OffsetMarker::new(name.into())),
+ NameRecord::new(0, 0, 0, NameId::FULL_NAME, OffsetMarker::new(name.into())),
+ NameRecord::new(
+ 0,
+ 0,
+ 0,
+ NameId::POSTSCRIPT_NAME,
+ OffsetMarker::new(name.into()),
+ ),
+ NameRecord::new(
+ 0,
+ 0,
+ 0,
+ NameId::TYPOGRAPHIC_FAMILY_NAME,
+ OffsetMarker::new(name.into()),
+ ),
+ ],
+ lang_tag_record: None,
+ });
+
+ let _ = builder.add_table(&Head {
+ units_per_em: 1000,
+ ..Default::default()
+ });
+
+ let _ = builder.add_table(&Hhea {
+ ascender: FWord::new(800),
+ descender: FWord::new(-200),
+ number_of_h_metrics: widths.len() as u16,
+ ..Default::default()
+ });
+
+ let _ = builder.add_table(&Maxp {
+ num_glyphs: widths.len() as u16,
+ ..Default::default()
+ });
+
+ let _ = builder.add_table(&Hmtx {
+ h_metrics: widths
+ .iter()
+ .copied()
+ .map(|width| LongMetric::new((1000.0 * width) as u16, 0))
+ .collect(),
+ left_side_bearings: vec![],
+ });
+
+ let mut glyph_loca_builder = GlyfLocaBuilder::new();
+
+ for width in widths {
+ let x = 0;
+ let y = -200;
+ let w = (1000.0 * width) as i16;
+ let h = 800;
+ let _ = glyph_loca_builder.add_glyph(&SimpleGlyph {
+ bbox: Bbox {
+ x_min: x,
+ y_min: y,
+ x_max: w,
+ y_max: h,
+ },
+ // needed because cosmic-text/fontdb currently ignores bbox
+ contours: vec![Contour::from(vec![
+ CurvePoint {
+ x,
+ y,
+ on_curve: true,
+ },
+ CurvePoint {
+ x: w,
+ y,
+ on_curve: true,
+ },
+ CurvePoint {
+ x: w,
+ y: h,
+ on_curve: true,
+ },
+ CurvePoint {
+ x,
+ y: h,
+ on_curve: true,
+ },
+ ])],
+ instructions: vec![],
+ });
+ }
+
+ let (glyf, loca, _) = glyph_loca_builder.build();
+
+ let _ = builder.add_table(&glyf);
+ let _ = builder.add_table(&loca);
+
+ let _ = builder.add_table(&Cmap {
+ encoding_records: vec![EncodingRecord {
+ platform_id: PlatformId::Unicode,
+ encoding_id: 1,
+ subtable: OffsetMarker::new(CmapSubtable::format_12(
+ 0,
+ vec![SequentialMapGroup {
+ start_char_code: c as u32,
+ end_char_code: c as u32 + widths.len() as u32 - 1,
+ start_glyph_id: 0,
+ }],
+ )),
+ }],
+ });
+
+ builder.build()
+}
diff --git a/vendor/bevy_rich_text3d/src/export.rs b/vendor/bevy_rich_text3d/src/export.rs
new file mode 100644
index 00000000..6598cca0
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/export.rs
@@ -0,0 +1,253 @@
+use bevy::mesh::{Mesh, MeshVertexAttribute, VertexAttributeValues};
+#[cfg(feature = "reflect")]
+use bevy::prelude::Reflect;
+
+/// Determines what kind of data each field in [`MeshExport`] carry.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+#[non_exhaustive]
+pub enum GlyphMeta {
+ /// Left to right count of the glyph, `0`, `1`, etc.
+ #[default]
+ Index,
+ /// Returns x position in `em` of a vertex as if the text is rendered in a single line.
+ Advance,
+ /// Returns x position in `em` of the center of a glyph as if the text is rendered in a single line.
+ PerGlyphAdvance,
+ /// Returns a random value between `0..1` per glyph.
+ RandomPerGlyph,
+ /// Returns a random value between `0..1` per vertex.
+ RandomPerVertex,
+ /// The `uv.x` as if the text block is a rectangular sprite.
+ UvX,
+ /// The `uv.y` as if the text block is a rectangular sprite.
+ UvY,
+ /// Returns `0` for left corners and `1` for right corners.
+ GlyphUvX,
+ /// Returns `0` for bottom corners and `1` for top corners.
+ GlyphUvY,
+ /// Returns `0` for fill, `1` for stroke, `2` for shadow, `3` for image/emoji.
+ Category,
+ /// The [`SegmentStyle::magic_number`](crate::SegmentStyle::magic_number) field
+ MagicNumber,
+}
+
+/// Determines what data to export as a part of the mesh.
+#[derive(Debug, Clone, Default)]
+pub enum MeshExport {
+ /// Export nothing.
+ #[default]
+ None,
+ /// Export two values as `uv1`.
+ ///
+ /// This does not require modification to the pipeline.
+ Uv1(GlyphMeta, GlyphMeta),
+ /// Export as an arbitrary amount of custom attributes.
+ Custom(Vec<MeshExportEntry>),
+}
+
+impl MeshExport {
+ pub fn init_cache(&self, mesh: &mut Mesh) -> Vec<MeshExportCache> {
+ macro_rules! reuse {
+ ($attr: expr, $data: ident) => {
+ if let Some(VertexAttributeValues::$data(mut data)) = mesh.remove_attribute($attr) {
+ data.clear();
+ data
+ } else {
+ Vec::new()
+ }
+ };
+ }
+ match self {
+ MeshExport::None => Vec::new(),
+ MeshExport::Uv1(x, y) => vec![MeshExportCache {
+ entry: MeshExportEntry {
+ id: Mesh::ATTRIBUTE_UV_1,
+ len: 2,
+ meta: [*x, *y, *x, *y],
+ },
+ data: MeshExportCacheData::F2(reuse!(Mesh::ATTRIBUTE_UV_1, Float32x2)),
+ }],
+ MeshExport::Custom(items) => items
+ .iter()
+ .map(|x| MeshExportCache {
+ entry: *x,
+ data: match x.len {
+ 1 => MeshExportCacheData::F1(reuse!(x.id, Float32)),
+ 2 => MeshExportCacheData::F2(reuse!(x.id, Float32x2)),
+ 3 => MeshExportCacheData::F3(reuse!(x.id, Float32x3)),
+ _ => MeshExportCacheData::F4(reuse!(x.id, Float32x4)),
+ },
+ })
+ .collect(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct MeshExportEntry {
+ pub(crate) id: MeshVertexAttribute,
+ pub(crate) len: usize,
+ pub(crate) meta: [GlyphMeta; 4],
+}
+
+impl MeshExportEntry {
+ /// Create a new export attribute.
+ ///
+ /// # Panics
+ ///
+ /// If attribute is not a float vector or if number of elements mismatches.
+ pub fn new(entry: MeshVertexAttribute, meta: &[GlyphMeta]) -> Self {
+ use bevy::mesh::VertexFormat::*;
+ let len = meta.len().min(4);
+ match entry.format {
+ Float32 => assert_eq!(len, 1, "Expected 1 item."),
+ Float32x2 => assert_eq!(len, 2, "Expected 2 items."),
+ Float32x3 => assert_eq!(len, 3, "Expected 3 items."),
+ Float32x4 => assert_eq!(len, 4, "Expected 4 items."),
+ _ => panic!("Expected float vector."),
+ };
+ MeshExportEntry {
+ id: entry,
+ len: meta.len().min(4),
+ meta: std::array::from_fn(|i| meta.get(i).copied().unwrap_or_default()),
+ }
+ }
+
+ pub fn iter(&self) -> impl Iterator<Item = (usize, GlyphMeta)> + '_ {
+ self.meta.iter().copied().enumerate().take(self.len)
+ }
+}
+pub struct MeshExportCache {
+ pub(crate) entry: MeshExportEntry,
+ pub(crate) data: MeshExportCacheData,
+}
+
+pub enum MeshExportCacheData {
+ F1(Vec<f32>),
+ F2(Vec<[f32; 2]>),
+ F3(Vec<[f32; 3]>),
+ F4(Vec<[f32; 4]>),
+}
+
+impl MeshExportCacheData {
+ pub fn extend_empty(&mut self) {
+ match self {
+ MeshExportCacheData::F1(items) => {
+ items.extend([0.; 4]);
+ }
+ MeshExportCacheData::F2(items) => {
+ items.extend([[0.; 2]; 4]);
+ }
+ MeshExportCacheData::F3(items) => {
+ items.extend([[0.; 3]; 4]);
+ }
+ MeshExportCacheData::F4(items) => {
+ items.extend([[0.; 4]; 4]);
+ }
+ }
+ }
+
+ pub fn with_inserted_quad(&mut self, index: usize, mut f: impl FnMut(usize, &mut f32)) {
+ match self {
+ MeshExportCacheData::F1(items) => {
+ if let Some(chunk) = items.last_chunk_mut::<4>() {
+ chunk
+ .iter_mut()
+ .enumerate()
+ .for_each(|(vertex, item)| f(vertex, item))
+ }
+ }
+ MeshExportCacheData::F2(items) => {
+ if let Some(chunk) = items.last_chunk_mut::<4>() {
+ chunk.iter_mut().enumerate().for_each(|(vertex, item)| {
+ if let Some(item) = item.get_mut(index) {
+ f(vertex, item)
+ }
+ })
+ }
+ }
+ MeshExportCacheData::F3(items) => {
+ if let Some(chunk) = items.last_chunk_mut::<4>() {
+ chunk.iter_mut().enumerate().for_each(|(vertex, item)| {
+ if let Some(item) = item.get_mut(index) {
+ f(vertex, item)
+ }
+ })
+ }
+ }
+ MeshExportCacheData::F4(items) => {
+ if let Some(chunk) = items.last_chunk_mut::<4>() {
+ chunk.iter_mut().enumerate().for_each(|(vertex, item)| {
+ if let Some(item) = item.get_mut(index) {
+ f(vertex, item)
+ }
+ })
+ }
+ }
+ }
+ }
+
+ pub fn for_each_zipped_mut<I: IntoIterator>(
+ &mut self,
+ joined: I,
+ mut f: impl FnMut(&mut [f32], I::Item),
+ ) {
+ match self {
+ MeshExportCacheData::F1(items) => {
+ items
+ .iter_mut()
+ .map(|x| std::array::from_mut(x) as &mut [f32])
+ .zip(joined)
+ .for_each(|(a, b)| f(a, b));
+ }
+ MeshExportCacheData::F2(items) => {
+ items
+ .iter_mut()
+ .map(|x| x as &mut [f32])
+ .zip(joined)
+ .for_each(|(a, b)| f(a, b));
+ }
+ MeshExportCacheData::F3(items) => {
+ items
+ .iter_mut()
+ .map(|x| x as &mut [f32])
+ .zip(joined)
+ .for_each(|(a, b)| f(a, b));
+ }
+ MeshExportCacheData::F4(items) => {
+ items
+ .iter_mut()
+ .map(|x| x as &mut [f32])
+ .zip(joined)
+ .for_each(|(a, b)| f(a, b));
+ }
+ }
+ }
+}
+
+impl From<MeshExportCacheData> for VertexAttributeValues {
+ fn from(val: MeshExportCacheData) -> Self {
+ match val {
+ MeshExportCacheData::F1(items) => VertexAttributeValues::Float32(items),
+ MeshExportCacheData::F2(items) => VertexAttributeValues::Float32x2(items),
+ MeshExportCacheData::F3(items) => VertexAttributeValues::Float32x3(items),
+ MeshExportCacheData::F4(items) => VertexAttributeValues::Float32x4(items),
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy)]
+#[repr(u8)]
+pub enum TextMeshFaceCategory {
+ Fill = 0,
+ Stroke = 1,
+ Shadow = 2,
+ Image = 3,
+}
+
+impl TextMeshFaceCategory {
+ pub fn as_value(&self) -> f32 {
+ (*self) as u8 as f32
+ }
+}
diff --git a/vendor/bevy_rich_text3d/src/fetch.rs b/vendor/bevy_rich_text3d/src/fetch.rs
new file mode 100644
index 00000000..60d9098b
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/fetch.rs
@@ -0,0 +1,119 @@
+use std::{borrow::Borrow, ops::Deref, str::FromStr};
+
+use bevy::ecs::{component::Component, world::Mut};
+#[cfg(feature = "reflect")]
+use bevy::prelude::{Reflect, ReflectComponent, ReflectDefault};
+
+use crate::Text3dSegment;
+
+/// If alongside a [`FetchedText`] or [`FetchedCondition`], prevent [`Text3d`](crate::Text3d) from despawning the entity on remove.
+#[derive(Debug, Clone, Copy, Component, Default)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+#[cfg_attr(feature = "reflect", reflect(Component, Default))]
+pub struct SharedSegment;
+
+/// A string segment on an [`Entity`](bevy::ecs::entity::Entity) that can be referenced by a [`Text3d`](crate::Text3d).
+///
+/// By default [`Text3d`](crate::Text3d) removes all linked [`FetchedText`] on remove,
+/// add [`SharedSegment`] to prevent this behavior.
+///
+/// # Change Detection
+///
+/// As long as change detection is triggered on this component, associated text will be rebuilt.
+/// Users should take care to not mutably dereference this component if no changes are needed,
+/// functions like [`FetchedText::write_if_changed`] or [`FetchedText::set_if_changed`] can help
+/// in this regard.
+#[derive(Debug, Clone, Component, Default)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+#[cfg_attr(feature = "reflect", reflect(Component, Default))]
+pub struct FetchedText(pub String);
+
+impl FetchedText {
+ pub const EMPTY: Self = Self(String::new());
+
+ pub fn as_str(&self) -> &str {
+ self.0.as_str()
+ }
+
+ /// Set and trigger change detection if a string like value is changed.
+ pub fn set_if_changed(mut this: Mut<Self>, value: impl AsRef<str> + ToString) {
+ if this.0 != value.as_ref() {
+ this.0 = value.to_string()
+ }
+ }
+
+ /// Set and trigger change detection if a parsable value is changed.
+ pub fn write_if_changed<T: ToString + FromStr + Eq>(mut this: Mut<Self>, value: T) {
+ if let Ok(val) = this.0.parse::<T>() {
+ if val == value {
+ return;
+ }
+ }
+ this.0 = value.to_string()
+ }
+}
+
+impl Text3dSegment {
+ /// Set and trigger change detection if a string like value is changed.
+ pub fn set_if_changed(mut this: Mut<String>, value: impl AsRef<str> + ToString) {
+ if *this != value.as_ref() {
+ *this = value.to_string()
+ }
+ }
+
+ /// Set and trigger change detection if a parsable value is changed.
+ pub fn write_if_changed<T: ToString + FromStr + Eq>(mut this: Mut<String>, value: T) {
+ if let Ok(val) = this.parse::<T>() {
+ if val == value {
+ return;
+ }
+ }
+ *this = value.to_string()
+ }
+}
+
+impl AsRef<str> for FetchedText {
+ fn as_ref(&self) -> &str {
+ self.as_str()
+ }
+}
+
+impl Borrow<str> for FetchedText {
+ fn borrow(&self) -> &str {
+ self.as_str()
+ }
+}
+
+impl Deref for FetchedText {
+ type Target = str;
+
+ fn deref(&self) -> &Self::Target {
+ self.as_str()
+ }
+}
+
+/// A boolean condition on an [`Entity`](bevy::ecs::entity::Entity) that can be referenced by a [`Text3d`](crate::Text3d).
+///
+/// By default [`Text3d`](crate::Text3d) removes all linked [`FetchedCondition`] on remove,
+/// add [`SharedSegment`] to prevent this behavior.
+///
+/// # Change Detection
+///
+/// As long as change detection is triggered on this component, associated text will be rebuilt.
+#[derive(Debug, Clone, Component, Default)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+#[cfg_attr(feature = "reflect", reflect(Component, Default))]
+pub struct FetchedCondition(pub bool);
+
+impl FetchedCondition {
+ pub const fn get(&self) -> bool {
+ self.0
+ }
+
+ /// Set and trigger change detection if value is changed.
+ pub fn set_if_changed(mut this: Mut<Self>, value: bool) {
+ if this.0 != value {
+ this.0 = value
+ }
+ }
+}
diff --git a/vendor/bevy_rich_text3d/src/layers.rs b/vendor/bevy_rich_text3d/src/layers.rs
new file mode 100644
index 00000000..de2f1035
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/layers.rs
@@ -0,0 +1,143 @@
+use std::{
+ num::NonZero,
+ ops::{BitOr, BitOrAssign},
+};
+
+use bevy::{asset::AssetId, color::Srgba, image::Image, math::Vec2};
+
+use crate::{
+ SegmentStyle, Text3dSegment, Text3dStyle, export::TextMeshFaceCategory, line::LineMode,
+};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub struct Layer(u8);
+
+impl BitOr for Layer {
+ type Output = Layer;
+
+ fn bitor(self, rhs: Self) -> Self::Output {
+ Layer(self.0 | rhs.0)
+ }
+}
+
+impl BitOrAssign for Layer {
+ fn bitor_assign(&mut self, rhs: Self) {
+ self.0 |= rhs.0;
+ }
+}
+
+#[allow(non_upper_case_globals)]
+impl Layer {
+ pub const NoShadow: Layer = Layer(0x80);
+ pub const Strikethrough: Layer = Layer(0x4);
+ /// Depend on the offset, either fill or stroke.
+ pub const Higher: Layer = Layer(0x2);
+ pub const Underline: Layer = Layer(0x1);
+
+ pub const None: Layer = Layer(0);
+}
+
+pub enum DrawType {
+ Glyph(Option<NonZero<u32>>),
+ Line(Option<NonZero<u32>>, LineMode),
+ Image(AssetId<Image>),
+}
+
+pub struct DrawRequest {
+ pub sort: Layer,
+ pub request: DrawType,
+ pub color: Srgba,
+ pub offset: Vec2,
+ pub category: TextMeshFaceCategory,
+}
+
+impl Text3dStyle {
+ /// Note: Things drawn last gets rendered first.
+ pub(crate) fn fill_draw_requests(
+ &self,
+ segment: &Text3dSegment,
+ attrs: &SegmentStyle,
+ requests: &mut Vec<DrawRequest>,
+ ) {
+ requests.clear();
+ if let Text3dSegment::Image(image) = segment {
+ let color = attrs.fill_color.unwrap_or(self.color);
+ requests.push(DrawRequest {
+ sort: Layer::None,
+ request: DrawType::Image(image.handle.id()),
+ color,
+ offset: Vec2::ZERO,
+ category: TextMeshFaceCategory::Image,
+ });
+ return;
+ }
+ #[allow(non_snake_case)]
+ let FILL = if self.stroke_in_front {
+ Layer::None
+ } else {
+ Layer::Higher
+ };
+ #[allow(non_snake_case)]
+ let STROKE = if self.stroke_in_front {
+ Layer::Higher
+ } else {
+ Layer::None
+ };
+ let fill = attrs.fill.unwrap_or(self.fill);
+ let stroke = attrs.stroke.or(self.stroke);
+ let fill_color = attrs.fill_color.unwrap_or(self.color);
+ let stroke_color = attrs.stroke_color.unwrap_or(self.stroke_color);
+ let fill_stroke: &[_] = match (fill, stroke) {
+ (true, None) => &[(None, fill_color, FILL)],
+ (true, Some(stroke)) => &[
+ (None, fill_color, FILL),
+ (Some(stroke), stroke_color, STROKE),
+ ],
+ (false, None) => &[],
+ (false, Some(stroke)) => &[(Some(stroke), stroke_color, STROKE)],
+ };
+ let normal_shadow: &[_] = match self.text_shadow {
+ Some((color, offset)) => &[
+ (None, Vec2::ZERO, Layer::NoShadow),
+ (Some(color), offset, Layer::None),
+ ],
+ None => &[(None, Vec2::ZERO, Layer::None)],
+ };
+ for (shadow_color, offset, shadow_layer) in normal_shadow.iter().copied() {
+ for (stroke, color, regular_layer) in fill_stroke.iter().copied() {
+ let category = if shadow_color.is_some() {
+ TextMeshFaceCategory::Shadow
+ } else if stroke.is_some() {
+ TextMeshFaceCategory::Stroke
+ } else {
+ TextMeshFaceCategory::Fill
+ };
+ requests.push(DrawRequest {
+ request: DrawType::Glyph(stroke),
+ color: shadow_color.unwrap_or(color),
+ offset,
+ sort: regular_layer | shadow_layer,
+ category,
+ });
+ if attrs.underline.is_some_and(|x| x) {
+ requests.push(DrawRequest {
+ request: DrawType::Line(stroke, LineMode::Underline),
+ color: shadow_color.unwrap_or(color),
+ offset,
+ sort: regular_layer | shadow_layer | Layer::Underline,
+ category,
+ });
+ }
+ if attrs.strikethrough.is_some_and(|x| x) {
+ requests.push(DrawRequest {
+ request: DrawType::Line(stroke, LineMode::Strikethrough),
+ color: shadow_color.unwrap_or(color),
+ offset,
+ sort: regular_layer | shadow_layer | Layer::Strikethrough,
+ category,
+ });
+ }
+ }
+ }
+ }
+}
diff --git a/vendor/bevy_rich_text3d/src/lib.rs b/vendor/bevy_rich_text3d/src/lib.rs
new file mode 100644
index 00000000..0a13c6c0
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/lib.rs
@@ -0,0 +1,274 @@
+#![doc = include_str!("../README.md")]
+#![allow(clippy::type_complexity)]
+#![allow(clippy::too_many_arguments)]
+#![allow(clippy::collapsible_if)]
+mod atlas;
+mod color_table;
+mod emoji;
+mod export;
+mod fetch;
+mod layers;
+mod line;
+mod loading;
+mod mesh_util;
+mod misc;
+mod parse;
+mod parse_util;
+mod prepare;
+mod render;
+mod styling;
+mod tess;
+mod text3d;
+
+pub use prepare::{DrawStyle, FontSystemGuard, TextProgressReportCallback, TextRenderer};
+
+pub use atlas::{TextAtlas, TextAtlasHandle};
+#[cfg(feature = "reflect")]
+use bevy::prelude::{Reflect, ReflectDefault, ReflectResource};
+use bevy::{
+ app::{App, First, Plugin, PostUpdate},
+ asset::{AssetApp, AssetId, Assets},
+ ecs::{
+ query::With,
+ resource::Resource,
+ schedule::{IntoScheduleConfigs, SystemSet, common_conditions::resource_exists},
+ system::{Query, ResMut},
+ world::Ref,
+ },
+ image::Image,
+ math::FloatOrd,
+ transform::TransformSystems,
+ window::{PrimaryWindow, Window},
+};
+
+pub use export::{GlyphMeta, MeshExport, MeshExportEntry};
+pub use fetch::{FetchedCondition, FetchedText, SharedSegment};
+use loading::{LoadCosmicFonts, load_cosmic_fonts_system};
+pub use misc::*;
+pub use parse_util::{ConditionOutput, ParseBuilder, ParseError};
+pub use styling::{SegmentSize, SegmentStyle, Text3dStyle};
+#[allow(deprecated)]
+pub type Text3dStyling = Text3dStyle;
+#[allow(deprecated)]
+pub type SharedTextSegment = SharedSegment;
+#[allow(deprecated)]
+pub type FetchedTextSegment = FetchedText;
+pub use text3d::{Text3d, Text3dImage, Text3dSegment};
+
+fn synchronize_scale_factor(
+ mut settings: ResMut<Text3dPlugin>,
+ main_window: Query<Ref<Window>, With<PrimaryWindow>>,
+ mut atlases: ResMut<Assets<TextAtlas>>,
+ mut images: ResMut<Assets<Image>>,
+) {
+ if settings.sync_scale_factor_with_main_window {
+ if let Ok(window) = main_window.single() {
+ if window.scale_factor() != settings.scale_factor {
+ settings.scale_factor = window.scale_factor();
+ for (_, atlas) in atlases.iter_mut() {
+ atlas.clear(&mut images);
+ }
+ }
+ }
+ }
+}
+
+/// Text3d Plugin.
+#[derive(Debug, Resource, Clone)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+#[cfg_attr(feature = "reflect", reflect(Resource, Default))]
+pub struct Text3dPlugin {
+ /// Size of the default font atlas, by default `(512, 512)`, we only extend the atlas by doubling in size vertically.
+ ///
+ /// Ideally this should be able to contain all glyphs to avoid inefficiencies.
+ ///
+ /// Trying to cache a glyph bigger than this size will cause a panic.
+ pub default_atlas_dimension: (usize, usize),
+ /// This should be the primary window's `scale_factor`. For example if this value is 2, a 32 x 32 glyph will
+ /// take up 64 x 64 pixels.
+ pub scale_factor: f32,
+ /// Currently the [`Window`]'s scale factor is not correct at app startup,
+ /// if true synchronizes scale factor with the [`PrimaryWindow`]'s scale factor.
+ ///
+ /// # Note
+ ///
+ /// If the window's scale factor changes, ALL text will be redrawn.
+ pub sync_scale_factor_with_main_window: bool,
+ /// If size is less than or equal to this value, double the scale factor used.
+ ///
+ /// This can produce better results for smaller text since we cannot perform hinting unlike `bevy_ui`.
+ ///
+ /// For more complex behaviors, use `world_scale`.
+ pub double_scale_factor_threshold: f32,
+ /// System locale, like `en-US`.
+ pub locale: Option<String>,
+ /// If true, load system fonts,
+ pub load_system_fonts: bool,
+ /// If false, loading system fonts might increase startup time.
+ ///
+ /// If true, load fonts in a separate thread, will panic on platforms like
+ /// wasm where threads are not supported.
+ pub asynchronous_load: bool,
+ /// Family name for placeholder glyphs used for placing emojis.
+ pub placeholder_family: String,
+ /// Pre-defines all glyph widths used by emojis, this generates a placeholder font containing glyphs with various sizes.
+ ///
+ /// Value represents `value * em`, so `1.0` represents a square.
+ ///
+ /// Emoji rendered will choose the placeholder glyph closest in width.
+ pub placeholder_glyph_widths: Vec<f32>,
+ /// The first character used in placeholder glyphs, usually '!'.
+ pub placeholder_glyph_origin: char,
+ /// Placeholder glyphs, does not need to be specified by the user.
+ pub placeholder_glyphs_generated: Vec<(f32, String)>,
+ /// If not empty, set the default serif font.
+ pub serif_family: String,
+ /// If not empty, set the default sans serif font.
+ pub sans_serif_family: String,
+ /// If not empty, set the default cursive font.
+ pub cursive_family: String,
+ /// If not empty, set the default monospace font.
+ pub monospace_family: String,
+ /// If not empty, set the default fantasy font.
+ pub fantasy_family: String,
+}
+
+impl Text3dPlugin {
+ pub fn get_placeholder_glyph(&self, size: f32) -> &str {
+ let Some((_, s)) = self
+ .placeholder_glyphs_generated
+ .iter()
+ .min_by_key(|(s, _)| FloatOrd((size - *s).abs()))
+ else {
+ return " ";
+ };
+ s
+ }
+}
+
+/// A [`Resource`] that contains paths of fonts to be loaded.
+///
+/// This can be modified before startup in other plugins.
+#[derive(Debug, Resource, Default, Clone)]
+pub struct LoadFonts {
+ /// Path of fonts to be loaded.
+ pub font_paths: Vec<String>,
+ /// Path of font directories to be loaded.
+ pub font_directories: Vec<String>,
+ /// Fonts embedded in the executable.
+ pub font_embedded: Vec<&'static [u8]>,
+}
+
+impl Default for Text3dPlugin {
+ fn default() -> Self {
+ Self {
+ default_atlas_dimension: (1024, 1024),
+ scale_factor: 1.0,
+ double_scale_factor_threshold: f32::NEG_INFINITY,
+ sync_scale_factor_with_main_window: true,
+ load_system_fonts: false,
+ asynchronous_load: false,
+ locale: None,
+ serif_family: String::new(),
+ sans_serif_family: String::new(),
+ cursive_family: String::new(),
+ monospace_family: String::new(),
+ fantasy_family: String::new(),
+ placeholder_family: "_Placeholder".into(),
+ placeholder_glyph_widths: vec![
+ 0.1,
+ 0.2,
+ 0.25,
+ 1.0 / 3.0,
+ 0.4,
+ 0.5,
+ 2.0 / 3.0,
+ 0.75,
+ std::f32::consts::GOLDEN_RATIO / 2.,
+ 1.0,
+ std::f32::consts::SQRT_2,
+ 1.5,
+ std::f32::consts::GOLDEN_RATIO,
+ 2.0,
+ 2.5,
+ 3.0,
+ 3.5,
+ 4.0,
+ 5.0,
+ 6.0,
+ ],
+ placeholder_glyph_origin: '!',
+ placeholder_glyphs_generated: Vec::new(),
+ }
+ }
+}
+
+/// [`SystemSet`] of text3d rendering in [`PostUpdate`] before transforms.
+///
+/// Manually order this before other transform related systems if applicable.
+#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, SystemSet)]
+pub struct Text3dSet;
+
+impl Plugin for Text3dPlugin {
+ fn build(&self, app: &mut App) {
+ app.init_asset::<TextAtlas>();
+ app.init_resource::<LoadFonts>();
+ let mut res = self.clone();
+ res.placeholder_glyphs_generated = self
+ .placeholder_glyph_widths
+ .iter()
+ .copied()
+ .enumerate()
+ .map(|(i, x)| {
+ (
+ x,
+ char::from_u32(self.placeholder_glyph_origin as u32 + i as u32)
+ .unwrap_or(' ')
+ .to_string(),
+ )
+ })
+ .collect();
+ app.insert_resource::<Text3dPlugin>(res);
+ let (x, y) = self.default_atlas_dimension;
+ let _ = app
+ .world_mut()
+ .resource_mut::<Assets<Image>>()
+ .insert(&TextAtlas::DEFAULT_IMAGE, TextAtlas::empty_image(x, y));
+ let _ = app
+ .world_mut()
+ .resource_mut::<Assets<TextAtlas>>()
+ .insert(AssetId::default(), TextAtlas::new(TextAtlas::DEFAULT_IMAGE));
+ app.add_systems(First, synchronize_scale_factor);
+ app.add_systems(
+ First,
+ load_cosmic_fonts_system.run_if(resource_exists::<LoadCosmicFonts>),
+ );
+ app.add_systems(
+ PostUpdate,
+ render::text_render
+ .run_if(resource_exists::<TextRenderer>)
+ .in_set(Text3dSet),
+ );
+ app.configure_sets(PostUpdate, Text3dSet.before(TransformSystems::Propagate));
+
+ #[cfg(feature = "reflect")]
+ app.register_type::<Text3d>()
+ .register_type::<Text3dStyle>()
+ .register_type::<Text3dSegment>()
+ .register_type::<SharedSegment>()
+ .register_type::<FetchedText>()
+ .register_type::<Text3dPlugin>();
+ }
+
+ fn cleanup(&self, app: &mut App) {
+ let fonts = app
+ .world_mut()
+ .remove_resource::<LoadFonts>()
+ .unwrap_or_default();
+ if self.asynchronous_load {
+ app.insert_resource(self.load_fonts_concurrent(fonts));
+ } else {
+ app.insert_resource(self.load_fonts_blocking(fonts));
+ }
+ }
+}
diff --git a/vendor/bevy_rich_text3d/src/line.rs b/vendor/bevy_rich_text3d/src/line.rs
new file mode 100644
index 00000000..5c977336
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/line.rs
@@ -0,0 +1,293 @@
+use std::num::NonZero;
+
+use bevy::{
+ image::Image,
+ math::{Rect, Vec2},
+};
+use cosmic_text::{FontSystem, LayoutGlyph, fontdb::ID};
+use ttf_parser::Face;
+
+use crate::{
+ SegmentStyle, Text3dSegment, Text3dStyle, TextAtlas,
+ styling::{FloatDecimal, GlyphEntry, GlyphTextureOf},
+ tess::PathEncoder,
+};
+
+#[derive(Debug, Clone, Copy)]
+pub(crate) struct LineRun {
+ pub min_index: usize,
+ pub max_index: usize,
+ pub min_offset: f32,
+ pub max_offset: f32,
+ pub size: f32,
+}
+
+#[derive(Debug, Clone, Copy)]
+pub(crate) enum LineMode {
+ Underline,
+ Strikethrough,
+}
+
+/// So that contains never returns true.
+impl Default for LineRun {
+ fn default() -> Self {
+ Self {
+ min_index: usize::MAX,
+ max_index: usize::MAX,
+ min_offset: 0.0,
+ max_offset: 0.0,
+ size: 0.0,
+ }
+ }
+}
+
+impl LineRun {
+ pub fn contains(&self, glyph: &LayoutGlyph) -> bool {
+ !(self.min_index > glyph.end || self.max_index < glyph.start)
+ }
+
+ pub fn uv_range(&self, min: f32, max: f32, stroke: f32) -> UvRanges {
+ let r_min = self.min_offset - stroke;
+ let r_max = self.max_offset + stroke;
+ let corner = (r_max - r_min).min(self.size + stroke * 2.0) / 2.0;
+ let f = |x| match x {
+ x if x <= self.min_offset => 0.0,
+ x if x >= self.max_offset => 1.0,
+ x if x <= self.min_offset + corner => (x - self.min_offset) / corner / 2.0,
+ x if x >= self.max_offset - corner => (self.max_offset - x) / corner / 2.0 + 0.5,
+ _ => 0.5,
+ };
+ if min < min + corner && max > min + corner {
+ let center = min + corner;
+ UvRanges::Two([((min, f(min)), (center, 0.5)), ((center, 0.5), (max, 0.5))])
+ } else if min < max - corner && max > max - corner {
+ let center = max - corner;
+ UvRanges::Two([((min, 0.5), (center, 0.5)), ((center, 0.5), (max, f(max)))])
+ } else {
+ UvRanges::One(((min, f(min)), (max, f(max))))
+ }
+ }
+}
+
+pub enum UvRanges {
+ One(((f32, f32), (f32, f32))),
+ Two([((f32, f32), (f32, f32)); 2]),
+}
+
+impl UvRanges {
+ pub fn iter(&self) -> impl Iterator<Item = ((f32, f32), (f32, f32))> + use<'_> {
+ match self {
+ UvRanges::One(v) => std::array::from_ref(v).iter().copied(),
+ UvRanges::Two(v) => v.iter().copied(),
+ }
+ }
+}
+
+impl From<LineMode> for GlyphTextureOf {
+ fn from(value: LineMode) -> Self {
+ match value {
+ LineMode::Underline => GlyphTextureOf::UnderlineTexture,
+ LineMode::Strikethrough => GlyphTextureOf::StrikethroughTexture,
+ }
+ }
+}
+
+impl LineMode {
+ pub fn select<T>(&self, underline: T, strikethrough: T) -> T {
+ match self {
+ LineMode::Underline => underline,
+ LineMode::Strikethrough => strikethrough,
+ }
+ }
+
+ /// Requires a valid first point.
+ pub fn new_run(
+ &self,
+ size: f32,
+ mut index: usize,
+ glyphs: &[LayoutGlyph],
+ text: &[(Text3dSegment, SegmentStyle)],
+ ) -> LineRun {
+ let first = &glyphs[index];
+ let mut result = LineRun {
+ min_index: first.start,
+ max_index: first.end,
+ min_offset: first.x,
+ max_offset: first.x + first.w,
+ size,
+ };
+ loop {
+ index += 1;
+ let Some(next) = glyphs.get(index) else {
+ break;
+ };
+ if next.font_id != first.font_id || next.font_size != first.font_size {
+ break;
+ }
+ let Some((_, next_style)) = text.get(next.metadata) else {
+ break;
+ };
+ if !self.validate(next_style) {
+ break;
+ }
+ result.max_index = next.end;
+ result.max_offset = next.x + next.w;
+ }
+ result
+ }
+
+ pub fn validate(&self, style: &SegmentStyle) -> bool {
+ match self {
+ LineMode::Underline => style.underline.unwrap_or_default(),
+ LineMode::Strikethrough => style.strikethrough.unwrap_or_default(),
+ }
+ }
+
+ pub fn boundary(
+ &self,
+ glyphs: &[LayoutGlyph],
+ segments: &[(Text3dSegment, SegmentStyle)],
+ index: usize,
+ stroke: f32,
+ ) -> (f32, f32) {
+ let current = &glyphs[index];
+ let mut min = current.x - stroke;
+ let mut max = current.x + current.w + stroke;
+ if let Some(prev) = glyphs.get(index.wrapping_sub(1)) {
+ if prev.font_id == current.font_id && prev.font_size == current.font_size {
+ if let Some((_, style)) = segments.get(prev.metadata) {
+ if self.validate(style) {
+ min = (prev.x + prev.w + current.x) / 2.;
+ }
+ }
+ }
+ }
+ if let Some(next) = glyphs.get(index.wrapping_add(1)) {
+ if next.font_id == current.font_id && next.font_size == current.font_size {
+ if let Some((_, style)) = segments.get(next.metadata) {
+ if self.validate(style) {
+ max = (current.x + current.w + next.x) / 2.;
+ }
+ }
+ }
+ }
+ (min, max)
+ }
+
+ pub fn size(&self, font_system: &mut FontSystem, id: ID, size: f32) -> f32 {
+ font_system
+ .db()
+ .with_face_data(id, |file, _| {
+ let Ok(face) = Face::parse(file, 0) else {
+ return None;
+ };
+ let metrics = match self {
+ LineMode::Underline => face.underline_metrics()?,
+ LineMode::Strikethrough => face.underline_metrics()?,
+ };
+ Some(metrics.thickness as f32 / face.units_per_em() as f32 * size)
+ })
+ .flatten()
+ .unwrap_or(size)
+ }
+
+ pub fn get_line_rect(
+ &self,
+ font_system: &mut FontSystem,
+ size: f32,
+ min: f32,
+ max: f32,
+ stroke: f32,
+ glyph: &LayoutGlyph,
+ ) -> Option<Rect> {
+ font_system
+ .db()
+ .with_face_data(glyph.font_id, |file, _| {
+ let Ok(face) = Face::parse(file, 0) else {
+ return None;
+ };
+ let metrics = match self {
+ LineMode::Underline => face.underline_metrics()?,
+ LineMode::Strikethrough => face.strikeout_metrics()?,
+ };
+ let base = metrics.position as f32 / face.units_per_em() as f32 * size;
+ let height = metrics.thickness as f32 / face.units_per_em() as f32 * size;
+ Some(Rect {
+ min: Vec2::new(min, base - height - stroke),
+ max: Vec2::new(max, base + stroke),
+ })
+ })
+ .flatten()
+ }
+
+ pub fn get_atlas_rect(
+ &self,
+ font_system: &mut FontSystem,
+ font: ID,
+ scale_factor: f32,
+ atlas: &mut TextAtlas,
+ image: &mut Image,
+ attrs: &SegmentStyle,
+ style: &Text3dStyle,
+ stroke: Option<NonZero<u32>>,
+ ) -> Option<Rect> {
+ let entry = GlyphEntry::Glyph {
+ font,
+ glyph_id: (*self).into(),
+ join: style.stroke_join,
+ real_size: FloatDecimal::new(style.size * scale_factor),
+ weight: attrs.weight.unwrap_or(style.weight),
+ stroke,
+ };
+ atlas
+ .glyphs
+ .get(&entry)
+ .copied()
+ .map(|(a, _)| a.as_rect())
+ .or_else(|| {
+ font_system
+ .db()
+ .with_face_data(font, |file, _| {
+ let Ok(face) = Face::parse(file, 0) else {
+ return None;
+ };
+ self.cache_texture(
+ entry,
+ style.size,
+ scale_factor,
+ atlas,
+ image,
+ stroke,
+ face,
+ )
+ })
+ .flatten()
+ })
+ }
+
+ pub fn cache_texture(
+ &self,
+ entry: GlyphEntry,
+ size: f32,
+ scale_factor: f32,
+ atlas: &mut TextAtlas,
+ image: &mut Image,
+ stroke: Option<NonZero<u32>>,
+ face: Face,
+ ) -> Option<Rect> {
+ let metrics = match self {
+ LineMode::Underline => face.underline_metrics(),
+ LineMode::Strikethrough => face.strikeout_metrics(),
+ }?;
+ let unit_per_em = face.units_per_em() as f32;
+ let d = metrics.thickness as f32 / unit_per_em * size * scale_factor;
+
+ let mut tess_commands = PathEncoder::default();
+ tess_commands.push_rect(0., 0., d, d);
+ let stroke = stroke.map(|x| x.get() as f32 * size / 100.);
+
+ tess_commands
+ .tess_glyph(stroke, 1., atlas, image, entry)
+ .map(|(x, _)| x.as_rect())
+ }
+}
diff --git a/vendor/bevy_rich_text3d/src/loading.rs b/vendor/bevy_rich_text3d/src/loading.rs
new file mode 100644
index 00000000..40248ea6
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/loading.rs
@@ -0,0 +1,128 @@
+use std::sync::{Arc, OnceLock};
+
+use crate::{LoadFonts, Text3dPlugin, TextRenderer, emoji::create_emoji_font};
+use bevy::{
+ ecs::resource::Resource,
+ ecs::system::{Commands, ResMut},
+ log::error,
+};
+use cosmic_text::fontdb::Database;
+
+#[derive(Debug, Resource)]
+pub struct LoadCosmicFonts(pub(crate) Arc<OnceLock<TextRenderer>>);
+
+impl Text3dPlugin {
+ pub fn load_fonts_blocking(&self, fonts: LoadFonts) -> TextRenderer {
+ let empty = Database::new();
+ let locale = self
+ .locale
+ .clone()
+ .or_else(sys_locale::get_locale)
+ .unwrap_or_else(|| "en-US".to_string());
+ let mut system = cosmic_text::FontSystem::new_with_locale_and_db(locale, empty);
+ if self.load_system_fonts {
+ system.db_mut().load_system_fonts();
+ }
+ for path in &fonts.font_paths {
+ if let Err(err) = system.db_mut().load_font_file(path) {
+ error!("Error loading font {path}: {err}.");
+ };
+ }
+ for path in fonts.font_directories {
+ system.db_mut().load_fonts_dir(path);
+ }
+ for data in fonts.font_embedded {
+ system.db_mut().load_font_data(data.to_vec());
+ }
+ if !self.serif_family.is_empty() {
+ system.db_mut().set_serif_family(&self.serif_family);
+ }
+ if !self.sans_serif_family.is_empty() {
+ system
+ .db_mut()
+ .set_sans_serif_family(&self.sans_serif_family);
+ }
+ if !self.cursive_family.is_empty() {
+ system.db_mut().set_cursive_family(&self.cursive_family);
+ }
+ if !self.monospace_family.is_empty() {
+ system.db_mut().set_monospace_family(&self.monospace_family);
+ }
+ if !self.fantasy_family.is_empty() {
+ system.db_mut().set_fantasy_family(&self.fantasy_family);
+ }
+ system.db_mut().load_font_data(create_emoji_font(
+ &self.placeholder_family,
+ &self.placeholder_glyph_widths,
+ self.placeholder_glyph_origin,
+ ));
+ TextRenderer::new(system)
+ }
+
+ pub fn load_fonts_concurrent(&self, fonts: LoadFonts) -> LoadCosmicFonts {
+ let locale = self
+ .locale
+ .clone()
+ .or_else(sys_locale::get_locale)
+ .unwrap_or_else(|| "en-US".to_string());
+
+ let sender = Arc::new(OnceLock::new());
+ let receiver = sender.clone();
+
+ let settings = self.clone();
+
+ std::thread::spawn(move || {
+ let empty = cosmic_text::fontdb::Database::new();
+ let mut system = cosmic_text::FontSystem::new_with_locale_and_db(locale, empty);
+ if settings.load_system_fonts {
+ system.db_mut().load_system_fonts();
+ }
+ for path in fonts.font_paths {
+ if let Err(err) = system.db_mut().load_font_file(&path) {
+ error!("Error loading font {path}: {err}.");
+ };
+ }
+ for path in fonts.font_directories {
+ system.db_mut().load_fonts_dir(path);
+ }
+ for data in fonts.font_embedded {
+ system.db_mut().load_font_data(data.to_vec());
+ }
+ if !settings.serif_family.is_empty() {
+ system.db_mut().set_serif_family(&settings.serif_family);
+ }
+ if !settings.sans_serif_family.is_empty() {
+ system
+ .db_mut()
+ .set_sans_serif_family(&settings.sans_serif_family);
+ }
+ if !settings.cursive_family.is_empty() {
+ system.db_mut().set_cursive_family(&settings.cursive_family);
+ }
+ if !settings.monospace_family.is_empty() {
+ system
+ .db_mut()
+ .set_monospace_family(&settings.monospace_family);
+ }
+ if !settings.fantasy_family.is_empty() {
+ system.db_mut().set_fantasy_family(&settings.fantasy_family);
+ }
+ system.db_mut().load_font_data(create_emoji_font(
+ &settings.placeholder_family,
+ &settings.placeholder_glyph_widths,
+ settings.placeholder_glyph_origin,
+ ));
+ sender.set(TextRenderer::new(system))
+ });
+ LoadCosmicFonts(receiver)
+ }
+}
+
+pub fn load_cosmic_fonts_system(mut commands: Commands, mut load: ResMut<LoadCosmicFonts>) {
+ if let Some(system) = Arc::get_mut(&mut load.0) {
+ if let Some(system) = system.take() {
+ commands.insert_resource(system);
+ commands.remove_resource::<LoadCosmicFonts>();
+ }
+ }
+}
diff --git a/vendor/bevy_rich_text3d/src/mesh_util.rs b/vendor/bevy_rich_text3d/src/mesh_util.rs
new file mode 100644
index 00000000..83f5a403
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/mesh_util.rs
@@ -0,0 +1,290 @@
+use bevy::{
+ color::{ColorToComponents, LinearRgba, Srgba},
+ image::Image,
+ math::{Rect, Vec2},
+ mesh::{Indices, Mesh, VertexAttributeValues},
+};
+
+use crate::{
+ GlyphMeta, Text3dStyle,
+ export::{MeshExportCache, MeshExportCacheData, TextMeshFaceCategory},
+ layers::Layer,
+};
+
+// Take the allocation if possible but clear the data.
+macro_rules! recycle_mesh {
+ ($mesh: expr, $attr: ident, $ty: ident) => {
+ if let Some(VertexAttributeValues::$ty(mut v)) = $mesh.remove_attribute(Mesh::$attr) {
+ v.clear();
+ v
+ } else {
+ Vec::new()
+ }
+ };
+}
+
+fn corners_z(rect: Rect, z: f32) -> [[f32; 3]; 4] {
+ [
+ [rect.min.x, rect.min.y, z],
+ [rect.max.x, rect.min.y, z],
+ [rect.min.x, rect.max.y, z],
+ [rect.max.x, rect.max.y, z],
+ ]
+}
+
+fn corners(rect: Rect) -> [[f32; 2]; 4] {
+ [
+ [rect.min.x, rect.min.y],
+ [rect.max.x, rect.min.y],
+ [rect.min.x, rect.max.y],
+ [rect.max.x, rect.max.y],
+ ]
+}
+
+pub(crate) struct ExtractedMesh<'t> {
+ pub mesh: &'t mut Mesh,
+ pub positions: Vec<[f32; 3]>,
+ pub normals: Vec<[f32; 3]>,
+ pub uv0: Vec<[f32; 2]>,
+ pub exports: Vec<MeshExportCache>,
+ pub colors: Vec<[f32; 4]>,
+ pub indices: Vec<u16>,
+ pub sort: &'t mut Vec<(Layer, [u16; 6])>,
+ pub layer_offset: f32,
+}
+
+impl<'t> ExtractedMesh<'t> {
+ pub fn new(
+ mesh: &'t mut Mesh,
+ sort_buffer: &'t mut Vec<(Layer, [u16; 6])>,
+ style: &Text3dStyle,
+ ) -> Self {
+ sort_buffer.clear();
+ let positions = recycle_mesh!(mesh, ATTRIBUTE_POSITION, Float32x3);
+ let normals = recycle_mesh!(mesh, ATTRIBUTE_NORMAL, Float32x3);
+ let uv0 = recycle_mesh!(mesh, ATTRIBUTE_UV_0, Float32x2);
+ let colors = recycle_mesh!(mesh, ATTRIBUTE_COLOR, Float32x4);
+ let exports = style.export.init_cache(mesh);
+
+ let mut indices = if let Some(Indices::U16(indices)) = mesh.remove_indices() {
+ indices
+ } else {
+ Vec::new()
+ };
+ indices.clear();
+ ExtractedMesh {
+ mesh,
+ positions,
+ normals,
+ uv0,
+ exports,
+ colors,
+ indices,
+ sort: sort_buffer,
+ layer_offset: style.layer_offset,
+ }
+ }
+
+ pub fn pixel_to_uv(&mut self, image: &Image) {
+ let inv_width = 1.0 / image.width() as f32;
+ let inv_height = 1.0 / image.height() as f32;
+
+ self.uv0.iter_mut().for_each(|[x, y]| {
+ *x *= inv_width;
+ *y *= inv_height;
+ });
+ }
+
+ pub fn post_process(&mut self, min: Vec2, dimension: Vec2) {
+ let w = dimension.x.max(0.0001);
+ let h = dimension.y.max(0.0001);
+ for item in &mut self.exports {
+ for (idx, meta_type) in item.entry.iter() {
+ match meta_type {
+ GlyphMeta::UvX => {
+ item.data
+ .for_each_zipped_mut(&self.positions, |arr, position| {
+ arr[idx] = (position[0] - min.x) / w;
+ })
+ }
+ GlyphMeta::UvY => {
+ item.data
+ .for_each_zipped_mut(&self.positions, |arr, position| {
+ arr[idx] = (position[1] - min.y) / h;
+ })
+ }
+ _ => (),
+ }
+ }
+ }
+ }
+
+ pub fn translate(&mut self, mut f: impl FnMut(&mut Vec2)) {
+ for [x, y, _] in &mut self.positions {
+ let mut v = Vec2::new(*x, *y);
+ f(&mut v);
+ *x = v.x;
+ *y = v.y;
+ }
+ }
+
+ pub fn cache_rectangle(
+ &mut self,
+ base: Vec2,
+ dimension: Vec2,
+ texture: Rect,
+ color: Srgba,
+ layer: Layer,
+ real_index: usize,
+ advance: f32,
+ magic_number: f32,
+ category: TextMeshFaceCategory,
+ styling: &Text3dStyle,
+ rng: &mut fastrand::Rng,
+ ) {
+ let mesh_rect = Rect {
+ min: base,
+ max: base + dimension,
+ };
+ self.cache_rectangle2(
+ mesh_rect,
+ texture,
+ color,
+ layer,
+ real_index,
+ advance,
+ magic_number,
+ category,
+ styling,
+ rng,
+ );
+ }
+
+ pub fn cache_rectangle2(
+ &mut self,
+ mesh_rect: Rect,
+ texture: Rect,
+ color: Srgba,
+ layer: Layer,
+ real_index: usize,
+ advance: f32,
+ magic_number: f32,
+ category: TextMeshFaceCategory,
+ styling: &Text3dStyle,
+ rng: &mut fastrand::Rng,
+ ) {
+ let i = self.positions.len() as u16;
+ self.sort
+ .push((layer, [i, i + 1, i + 2, i + 1, i + 3, i + 2]));
+
+ self.positions.extend(corners_z(mesh_rect, 0.));
+ self.normals.extend([[0., 0., 1.]; 4]);
+ self.colors
+ .extend([LinearRgba::from(color).to_f32_array(); 4]);
+
+ // First we cache the pixel position since the texture may be resized.
+ self.uv0.extend(corners(texture));
+
+ for item in &mut self.exports {
+ item.data.extend_empty();
+ for (index, meta) in item.entry.iter() {
+ let random_per_glyph = rng.f32();
+ item.data
+ .with_inserted_quad(index, |vertex, item| match meta {
+ GlyphMeta::Index => {
+ *item = real_index as f32;
+ }
+ GlyphMeta::Advance => {
+ if vertex & 1 == 0 {
+ *item = advance / styling.size;
+ } else {
+ *item = (advance + mesh_rect.width()) / styling.size;
+ }
+ }
+ GlyphMeta::PerGlyphAdvance => {
+ *item = (advance + mesh_rect.width() / 2.0) / styling.size;
+ }
+ GlyphMeta::MagicNumber => {
+ *item = magic_number;
+ }
+ GlyphMeta::RandomPerGlyph => *item = random_per_glyph,
+ GlyphMeta::RandomPerVertex => *item = rng.f32(),
+ GlyphMeta::GlyphUvX => *item = if vertex & 1 == 0 { 0.0 } else { 1.0 },
+ GlyphMeta::GlyphUvY => *item = if vertex < 2 { 0.0 } else { 1.0 },
+ GlyphMeta::UvX => (),
+ GlyphMeta::UvY => (),
+ GlyphMeta::Category => *item = category.as_value(),
+ });
+ }
+ }
+ }
+}
+
+impl Drop for ExtractedMesh<'_> {
+ fn drop(&mut self) {
+ use std::mem::take;
+ self.sort.sort_by_key(|x| x.0);
+ if self.layer_offset != 0.0 {
+ let mut offset = 0.0;
+ let mut layer = self.sort.last().map(|x| x.0).unwrap_or(Layer::None);
+ for (l, entry) in self.sort.iter().rev() {
+ if layer != *l {
+ offset -= self.layer_offset;
+ layer = *l;
+ }
+ for idx in entry {
+ if let Some([_, _, z]) = self.positions.get_mut(*idx as usize) {
+ *z = offset;
+ }
+ }
+ }
+ }
+ self.indices
+ .extend(self.sort.drain(..).flat_map(|(_, v)| v));
+ if !self.positions.is_empty() {
+ self.mesh
+ .insert_attribute(Mesh::ATTRIBUTE_POSITION, take(&mut self.positions));
+ self.mesh
+ .insert_attribute(Mesh::ATTRIBUTE_NORMAL, take(&mut self.normals));
+ self.mesh
+ .insert_attribute(Mesh::ATTRIBUTE_COLOR, take(&mut self.colors));
+ self.mesh
+ .insert_attribute(Mesh::ATTRIBUTE_UV_0, take(&mut self.uv0));
+ for entry in take(&mut self.exports) {
+ self.mesh.insert_attribute(entry.entry.id, entry.data);
+ }
+ self.mesh
+ .insert_indices(Indices::U16(take(&mut self.indices)));
+ } else {
+ // Placeholder, since empty mesh panics on some platforms.
+ self.mesh
+ .insert_attribute(Mesh::ATTRIBUTE_POSITION, vec![[0.0, 0.0, 0.0]; 3]);
+ self.mesh
+ .insert_attribute(Mesh::ATTRIBUTE_NORMAL, vec![[0.0, 1.0, 0.0]; 3]);
+ self.mesh
+ .insert_attribute(Mesh::ATTRIBUTE_COLOR, vec![[0.0, 0.0, 0.0, 0.0]; 3]);
+ self.mesh
+ .insert_attribute(Mesh::ATTRIBUTE_UV_0, vec![[0.0, 0.0]; 3]);
+ for entry in take(&mut self.exports) {
+ match entry.data {
+ MeshExportCacheData::F1(_) => {
+ self.mesh.insert_attribute(entry.entry.id, vec![0.0; 3]);
+ }
+ MeshExportCacheData::F2(_) => {
+ self.mesh
+ .insert_attribute(entry.entry.id, vec![[0.0; 2]; 3]);
+ }
+ MeshExportCacheData::F3(_) => {
+ self.mesh
+ .insert_attribute(entry.entry.id, vec![[0.0; 3]; 3]);
+ }
+ MeshExportCacheData::F4(_) => {
+ self.mesh
+ .insert_attribute(entry.entry.id, vec![[0.0; 4]; 3]);
+ }
+ }
+ }
+ self.mesh.insert_indices(Indices::U16(vec![0, 1, 2]));
+ }
+ }
+}
diff --git a/vendor/bevy_rich_text3d/src/misc.rs b/vendor/bevy_rich_text3d/src/misc.rs
new file mode 100644
index 00000000..024843be
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/misc.rs
@@ -0,0 +1,202 @@
+use bevy::{
+ ecs::component::Component,
+ math::{IVec2, Vec2},
+};
+use cosmic_text::{Style as CosmicStyle, Weight as CosmicWeight};
+use std::ops::{Deref, DerefMut};
+
+#[cfg(feature = "reflect")]
+use bevy::{
+ ecs::reflect::ReflectComponent,
+ prelude::{Reflect, ReflectDefault},
+};
+
+/// Horizontal align of text.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+pub enum TextAlign {
+ #[default]
+ Left,
+ Center,
+ Right,
+}
+
+impl TextAlign {
+ pub fn as_fac(&self) -> f32 {
+ match self {
+ TextAlign::Left => 0.,
+ TextAlign::Center => 0.5,
+ TextAlign::Right => 1.0,
+ }
+ }
+}
+
+/// Determines the maximum width of rendered text, by default infinite.
+#[derive(Debug, Component)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+#[cfg_attr(feature = "reflect", reflect(Component, Default))]
+pub struct Text3dBounds {
+ pub width: f32,
+}
+
+impl Default for Text3dBounds {
+ fn default() -> Self {
+ Self { width: f32::MAX }
+ }
+}
+
+/// Anchor of a text block, usually in `(-0.5, -0.5)..=(0.5, 0.5)`.
+#[derive(Debug, Clone, Copy, Default, PartialEq)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+pub struct TextAnchor(pub Vec2);
+
+impl Deref for TextAnchor {
+ type Target = Vec2;
+
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+impl DerefMut for TextAnchor {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.0
+ }
+}
+
+impl TextAnchor {
+ pub const BOTTOM_LEFT: TextAnchor = TextAnchor::new(-0.5, -0.5);
+ pub const BOTTOM_CENTER: TextAnchor = TextAnchor::new(0., -0.5);
+ pub const BOTTOM_RIGHT: TextAnchor = TextAnchor::new(0.5, -0.5);
+
+ pub const CENTER_LEFT: TextAnchor = TextAnchor::new(-0.5, 0.);
+ pub const CENTER: TextAnchor = TextAnchor::new(0., 0.);
+ pub const CENTER_RIGHT: TextAnchor = TextAnchor::new(0.5, 0.);
+
+ pub const TOP_LEFT: TextAnchor = TextAnchor::new(-0.5, 0.5);
+ pub const TOP_CENTER: TextAnchor = TextAnchor::new(0., 0.5);
+ pub const TOP_RIGHT: TextAnchor = TextAnchor::new(0.5, 0.5);
+
+ pub const fn new(x: f32, y: f32) -> Self {
+ TextAnchor(Vec2::new(x, y))
+ }
+}
+
+/// Size of the output mesh's `Aabb`.
+#[derive(Debug, Component, Default)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+#[cfg_attr(feature = "reflect", reflect(Component))]
+pub struct Text3dDimensionOut {
+ /// Returns `aabb`'s x and y derived from font's line height.
+ pub dimension: Vec2,
+ pub(crate) atlas_dimension: IVec2,
+ pub(crate) initialized: bool,
+}
+
+/// Allows italic or oblique faces to be selected.
+#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+pub enum Style {
+ /// A face that is neither italic not obliqued.
+ Normal,
+ /// A form that is generally cursive in nature.
+ Italic,
+ /// A typically-sloped version of the regular face.
+ Oblique,
+}
+
+impl Default for Style {
+ #[inline]
+ fn default() -> Style {
+ Style::Normal
+ }
+}
+
+impl From<Style> for CosmicStyle {
+ fn from(val: Style) -> Self {
+ match val {
+ Style::Normal => CosmicStyle::Normal,
+ Style::Italic => CosmicStyle::Italic,
+ Style::Oblique => CosmicStyle::Oblique,
+ }
+ }
+}
+
+impl From<CosmicStyle> for Style {
+ fn from(val: CosmicStyle) -> Self {
+ match val {
+ CosmicStyle::Normal => Style::Normal,
+ CosmicStyle::Italic => Style::Italic,
+ CosmicStyle::Oblique => Style::Oblique,
+ }
+ }
+}
+
+/// Specifies the weight of glyphs in the font, their degree of blackness or stroke thickness.
+#[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Debug, Hash)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+pub struct Weight(pub u16);
+
+impl Default for Weight {
+ #[inline]
+ fn default() -> Weight {
+ Weight::NORMAL
+ }
+}
+
+impl Weight {
+ /// Thin weight (100), the thinnest value.
+ pub const THIN: Weight = Weight(CosmicWeight::THIN.0);
+ /// Extra light weight (200).
+ pub const EXTRA_LIGHT: Weight = Weight(CosmicWeight::EXTRA_LIGHT.0);
+ /// Light weight (300).
+ pub const LIGHT: Weight = Weight(CosmicWeight::LIGHT.0);
+ /// Normal (400).
+ pub const NORMAL: Weight = Weight(CosmicWeight::NORMAL.0);
+ /// Medium weight (500, higher than normal).
+ pub const MEDIUM: Weight = Weight(CosmicWeight::MEDIUM.0);
+ /// Semibold weight (600).
+ pub const SEMIBOLD: Weight = Weight(CosmicWeight::SEMIBOLD.0);
+ /// Bold weight (700).
+ pub const BOLD: Weight = Weight(CosmicWeight::BOLD.0);
+ /// Extra-bold weight (800).
+ pub const EXTRA_BOLD: Weight = Weight(CosmicWeight::EXTRA_BOLD.0);
+ /// Black weight (900), the thickest value.
+ pub const BLACK: Weight = Weight(CosmicWeight::BLACK.0);
+}
+
+impl From<Weight> for CosmicWeight {
+ fn from(val: Weight) -> Self {
+ CosmicWeight(val.0)
+ }
+}
+
+impl From<CosmicWeight> for Weight {
+ fn from(val: CosmicWeight) -> Self {
+ Weight(val.0)
+ }
+}
+
+/// Specifies how corners are drawn when a shape is stroked.
+///
+/// Join affects the four corners of a stroked rectangle, and the connected segments in a stroked path.
+///
+/// Usually [`StrokeJoin::Round`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+pub enum StrokeJoin {
+ #[default]
+ Round,
+ Miter,
+ Bevel,
+}
+
+impl From<StrokeJoin> for tiny_skia::LineJoin {
+ fn from(val: StrokeJoin) -> Self {
+ match val {
+ StrokeJoin::Round => tiny_skia::LineJoin::Round,
+ StrokeJoin::Bevel => tiny_skia::LineJoin::Bevel,
+ StrokeJoin::Miter => tiny_skia::LineJoin::Miter,
+ }
+ }
+}
diff --git a/vendor/bevy_rich_text3d/src/parse.rs b/vendor/bevy_rich_text3d/src/parse.rs
new file mode 100644
index 00000000..d9e2654f
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/parse.rs
@@ -0,0 +1,415 @@
+use std::{cell::OnceCell, iter::repeat_n, num::NonZeroU32, ops::Range, str::FromStr};
+
+use bevy::log::warn;
+
+use crate::{
+ SegmentSize, SegmentStyle, Text3d, Text3dSegment,
+ color_table::parse_color,
+ misc::{Style, Weight},
+ parse_util::{
+ ConditionOutput, Flip, ParseBuilder, ParseConditionFn, ParseError, ParseErrorType,
+ ParseStyleFn, ParseValueFn,
+ },
+};
+
+fn trim_mut(s: &mut String) {
+ let trimmed = s.trim();
+ let start = trimmed.as_ptr() as usize - s.as_ptr() as usize;
+ let end = start + trimmed.len();
+
+ s.truncate(end);
+ s.drain(..start);
+}
+
+fn sub_span(origin: usize, sub: &str, main: &str, fallback: usize) -> Range<usize> {
+ if let Some(r) = main.substr_range(sub) {
+ r.start + origin..r.end + origin
+ } else {
+ fallback..fallback + 1
+ }
+}
+
+impl Text3d {
+ /// Parse rich text with no custom parsing functions, only standard styles are supported.
+ ///
+ #[doc = include_str!("parse_doc.md")]
+ pub fn parse_raw(text: &str) -> Result<Self, ParseError<'_>> {
+ Text3d::parse(text, ParseBuilder::new())
+ }
+
+ /// Parse rich text string.
+ ///
+ #[doc = include_str!("parse_doc.md")]
+ pub fn parse(
+ text: &str,
+ parser: ParseBuilder<impl ParseStyleFn, impl ParseValueFn, impl ParseConditionFn>,
+ ) -> Result<Self, ParseError<'_>> {
+ match Text3d::parse_with_errors(text, parser) {
+ (_result, Some(error)) => Err(error),
+ (result, None) => Ok(result),
+ }
+ }
+
+ /// Parse rich text with no custom parsing functions, only standard styles are supported.
+ ///
+ /// This function always produces a valid result and can capture owned strings, therefore easier to use with bsn.
+ ///
+ #[doc = include_str!("parse_doc.md")]
+ pub fn bsn_parse_raw(text: impl AsRef<str>) -> Self {
+ let (result, error) = Text3d::parse_with_errors(text.as_ref(), ParseBuilder::new());
+ if let Some(error) = error {
+ warn!("{error}");
+ }
+ result
+ }
+
+ /// Parse rich text string.
+ ///
+ /// This function always produces a valid result and can capture owned strings, therefore easier to use with bsn.
+ ///
+ #[doc = include_str!("parse_doc.md")]
+ pub fn bsn_parse(
+ text: impl AsRef<str>,
+ parser: ParseBuilder<impl ParseStyleFn, impl ParseValueFn, impl ParseConditionFn>,
+ ) -> Self {
+ let (result, error) = Text3d::parse_with_errors(text.as_ref(), parser);
+ if let Some(error) = error {
+ warn!("{error}");
+ }
+ result
+ }
+}
+
+impl Text3d {
+ /// Parse rich text string, always produces a result and returns the first error occurred.
+ ///
+ #[doc = include_str!("parse_doc.md")]
+ pub fn parse_with_errors(
+ text: &str,
+ mut parser: ParseBuilder<impl ParseStyleFn, impl ParseValueFn, impl ParseConditionFn>,
+ ) -> (Self, Option<ParseError<'_>>) {
+ #[derive(Debug, Clone, Copy)]
+ enum ParseState {
+ Text,
+ Command,
+ Conditional(bool),
+ }
+
+ let style_backup = SegmentStyle::default();
+ let mut buffer = String::new();
+ let mut state = ParseState::Text;
+ let mut segments = Vec::new();
+ let mut stack: Vec<(SegmentStyle, Option<usize>)> = vec![(SegmentStyle::default(), None)];
+ let mut error = OnceCell::new();
+ let mut span_start = 0;
+ let mut pos = 0;
+
+ macro_rules! push_seg {
+ () => {
+ let style = style!();
+ if !buffer.is_empty() {
+ segments.push((Text3dSegment::String(core::mem::take(&mut buffer)), style));
+ }
+ };
+ }
+ macro_rules! style {
+ () => {
+ stack
+ .last()
+ .map(|x| &x.0)
+ .unwrap_or_else(|| {
+ let _ = error.set(ParseError {
+ text,
+ span: (pos..pos + 1),
+ error: ParseErrorType::BracketMismatch,
+ });
+ &style_backup
+ })
+ .clone()
+ };
+ ($($tt: tt)*) => {
+ {
+ let _ = stack
+ .last_mut()
+ .map(|x| &mut x.0)
+ .map($($tt)*);
+ }
+ };
+ }
+ use ParseState::*;
+ let mut iter = text.char_indices().peekable();
+
+ macro_rules! peek {
+ () => {
+ iter.peek().map(|x| x.1)
+ };
+ }
+
+ while let Some((i, c)) = iter.next() {
+ pos = i;
+ match (c, state) {
+ ('{', Text) => {
+ push_seg!();
+ span_start = i + 1;
+ state = Command;
+ }
+ (' ', Command) if buffer.is_empty() => {}
+ ('?', Command) if buffer.is_empty() => {
+ span_start = i + 1;
+ state = Conditional(true);
+ }
+ ('!', Conditional(true)) if buffer.is_empty() => {
+ span_start = i + 1;
+ state = Conditional(false);
+ }
+ (':', Command) => {
+ let mut style = style!();
+ for s in buffer.trim().split(",") {
+ match parse_style(s.trim(), &mut parser.parse_style) {
+ Ok(s) => style = style.join(s),
+ Err(e) => {
+ let span = sub_span(span_start, s, &buffer, pos);
+ let _ = error.set(ParseError {
+ text,
+ span,
+ error: ParseErrorType::StyleError(e),
+ });
+ }
+ }
+ }
+ stack.push((style, None));
+ buffer.clear();
+ state = Text;
+ }
+ (':', Conditional(should_be)) => {
+ let s = buffer.trim();
+ match parser.parse_condition.call(s) {
+ Ok(ConditionOutput::Constant(b)) if b == should_be => {
+ // start a scope and do nothing
+ stack.push((style!(), None));
+ }
+ Ok(ConditionOutput::Constant(_)) => {
+ // skip all wrapped items.
+ let mut depth = 1;
+ while depth > 0 {
+ match iter.next() {
+ Some((_, '{')) => depth += 1,
+ Some((_, '}')) => depth -= 1,
+ _ => (),
+ }
+ }
+ }
+ Ok(ConditionOutput::Dynamic(entity)) => {
+ let pos = segments.len();
+ segments.push((
+ Text3dSegment::SkipIf {
+ condition: entity,
+ skip_if: !should_be,
+ offset: 0,
+ },
+ style!(),
+ ));
+ stack.push((style!(), Some(pos)));
+ }
+ Err(e) => {
+ // start a scope and do nothing
+ stack.push((style!(), None));
+
+ let span = sub_span(span_start, s, &buffer, pos);
+ let _ = error.set(ParseError {
+ text,
+ span,
+ error: ParseErrorType::ConditionError(e),
+ });
+ }
+ }
+ buffer.clear();
+ state = Text;
+ }
+ ('}', Text) => {
+ trim_mut(&mut buffer);
+ push_seg!();
+ if let Some((_, Some(r))) = stack.pop() {
+ let l = segments.len().saturating_sub(1 + r);
+ if let Text3dSegment::SkipIf { offset, .. } = &mut segments[r].0 {
+ *offset = l;
+ }
+ };
+ }
+ ('}', Command) => {
+ let s = buffer.trim();
+ match parser.parse_value.call(segments.len(), s) {
+ Ok((segment, style)) => {
+ let style = style!().join(style);
+ segments.push((segment, style));
+ }
+ Err(e) => {
+ let span = sub_span(span_start, s, &buffer, pos);
+ let _ = error.set(ParseError {
+ text,
+ span,
+ error: ParseErrorType::ValueError(e),
+ });
+ }
+ }
+ buffer.clear();
+ state = Text;
+ }
+ ('}', Conditional(_)) => {} // do nothing, failing is too harsh.
+ ('*', Text) => {
+ push_seg!();
+ let mut stars = 1;
+ while let Some(c) = peek!() {
+ if c == '*' {
+ stars += 1;
+ iter.next();
+ } else {
+ break;
+ }
+ }
+ match stars {
+ 1 => style!(|s| s.style.flip()),
+ 2 => style!(|s| s.weight.flip()),
+ 3 => {
+ style!(|s| s.style.flip());
+ style!(|s| s.weight.flip());
+ }
+ n if n % 2 == 0 => (),
+ _ => style!(|s| s.style.flip()),
+ }
+ }
+ ('_', Text) if peek!() == Some('_') => {
+ push_seg!();
+ iter.next();
+ style!(|s| s.underline.flip());
+ }
+ ('~', Text) if peek!() == Some('~') => {
+ push_seg!();
+ iter.next();
+ style!(|s| s.strikethrough.flip());
+ }
+ (c, Command | Conditional(_)) => buffer.push(c),
+ ('\\', Text) => {
+ if let Some(c) = peek!() {
+ buffer.push(c);
+ iter.next();
+ }
+ }
+ (c, Text) if c.is_whitespace() => {
+ let mut linebreaks = if c == '\n' { 1 } else { 0 };
+ while let Some(c) = peek!() {
+ if !c.is_whitespace() {
+ break;
+ } else if c == '\n' {
+ linebreaks += 1;
+ }
+ iter.next();
+ }
+ match linebreaks {
+ 0 => buffer.push(' '),
+ n => buffer.extend(repeat_n('\n', n)),
+ }
+ }
+ (c, Text) => {
+ buffer.push(c);
+ }
+ }
+ }
+ push_seg!();
+ (Text3d { segments }, error.take())
+ }
+}
+
+fn parse_style(
+ style: &str,
+ stylesheet: &mut impl ParseStyleFn,
+) -> Result<SegmentStyle, Option<String>> {
+ if let Some(number) = style.strip_prefix("v-") {
+ if let Ok(magic_number) = f32::from_str(number) {
+ Ok(SegmentStyle {
+ magic_number: Some(magic_number),
+ ..Default::default()
+ })
+ } else {
+ stylesheet.call(style)
+ }
+ } else if let Some(name) = style.strip_prefix("s-") {
+ if let Ok(int) = u32::from_str(name) {
+ Ok(SegmentStyle {
+ stroke: NonZeroU32::new(int),
+ ..Default::default()
+ })
+ } else if let Some(color) = parse_color(name) {
+ Ok(SegmentStyle {
+ stroke_color: Some(color),
+ ..Default::default()
+ })
+ } else {
+ stylesheet.call(style)
+ }
+ } else if let Some(name) = style.strip_prefix("f-") {
+ Ok(SegmentStyle {
+ font: Some(name.into()),
+ ..Default::default()
+ })
+ } else if let Some(name) = style.strip_prefix("$") {
+ if let Ok(size) = name.parse::<f32>() {
+ Ok(SegmentStyle {
+ size: Some(SegmentSize::Flat(size)),
+ ..Default::default()
+ })
+ } else {
+ stylesheet.call(style)
+ }
+ } else if let Some(name) = style.strip_prefix("*") {
+ if let Ok(size) = name.parse::<f32>() {
+ Ok(SegmentStyle {
+ size: Some(SegmentSize::Multiply(size)),
+ ..Default::default()
+ })
+ } else {
+ stylesheet.call(style)
+ }
+ } else if let Some(color) = parse_color(style) {
+ Ok(SegmentStyle {
+ fill_color: Some(color),
+ ..Default::default()
+ })
+ } else {
+ match style {
+ "bold" => Ok(SegmentStyle {
+ weight: Some(Weight::BOLD),
+ ..Default::default()
+ }),
+ "italic" => Ok(SegmentStyle {
+ style: Some(Style::Italic),
+ ..Default::default()
+ }),
+ "underline" => Ok(SegmentStyle {
+ underline: Some(true),
+ ..Default::default()
+ }),
+ "strikethrough" => Ok(SegmentStyle {
+ strikethrough: Some(true),
+ ..Default::default()
+ }),
+ "h1" => Ok(SegmentStyle {
+ size: Some(SegmentSize::Multiply(2.0)),
+ ..Default::default()
+ }),
+ "h2" => Ok(SegmentStyle {
+ size: Some(SegmentSize::Multiply(1.75)),
+ ..Default::default()
+ }),
+ "h3" => Ok(SegmentStyle {
+ size: Some(SegmentSize::Multiply(1.5)),
+ ..Default::default()
+ }),
+ "h4" => Ok(SegmentStyle {
+ size: Some(SegmentSize::Multiply(1.25)),
+ ..Default::default()
+ }),
+ _ => stylesheet.call(style),
+ }
+ }
+}
diff --git a/vendor/bevy_rich_text3d/src/parse_doc.md b/vendor/bevy_rich_text3d/src/parse_doc.md
new file mode 100644
index 00000000..b5411c61
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/parse_doc.md
@@ -0,0 +1,92 @@
+# Example
+
+```md
+"Deals **{blue:{damage_number}}** {red:fire} damage to the enemy."
+```
+
+# Syntax
+
+## Style
+
+```md
+{style:value}
+```
+
+This is equivalent to `<style>value</style>` in html.
+The left hand side is the name of the style, it will be passed to the `stylesheet` function.
+
+`value` will be trimmed of whitespace, so the correct syntax is to add whitespace outside of the braces:
+
+```md
+Hello {style:World}! // Hello World!
+Hello{style: World}! // HelloWorld!
+```
+
+Style commands also can be chained:
+
+```md
+Deals {red, s-black, s-10: 10} damage!
+```
+
+## Standard Styles
+
+These will be parsed regardless of the `stylesheet` function:
+
+* `red` Parses Css color names as fill color.
+* `#ff00ff` Parses hex color (accepts 3, 4, 6, 8 digits) as fill color.
+* `s-4` Sets stroke to a number.
+* `s-red` Parses color names as stroke color.
+* `v-4.0` Sets the `magic_number` field.
+* `f-Roboto` Sets the font to Roboto.
+* `$18` Sets font size to `18`.
+* `*1.5` Sets font size to `1.5` times the original.
+* `h1` - `h4` Sets font size to `2`, `1.75`, `1.5`, `1.25` times the original.
+
+## Dynamic value
+
+```md
+{ value }
+```
+
+Without `:` values in brackets are treated as dynamic values and passed to the `fetch_string` function.
+The result should either be a string fetched from the world
+or an [`Entity`](bevy::ecs::entity::Entity) with a [`FetchedTextSegment`](crate::FetchedTextSegment) component.
+
+## Conditions
+
+```md
+{ ?condition : value }
+{ ?!condition : value } // flips the condition
+```
+
+Displays value only when `condition` is true (or false with `?!`).
+The result should either be a boolean value fetched from the world
+or an [`Entity`](bevy::ecs::entity::Entity) with a [`FetchedCondition`](crate::FetchedCondition) component.
+
+## Markdown
+
+A subset of markdown features are supported:
+
+* `*emphasis*`
+* `**strong**`
+* `__underline__`
+* `~~strikethrough~~`
+* `\*` escape character
+
+## Whitespace Rule
+
+Consecutive whitespaces are rendered either as one whitespace or multiple linebreaks.
+
+## Inputs
+
+* [`ParseValueFn`]
+ * [`Text3dSegment::String`] should be returned for static values.
+ * [`Text3dSegment::Extract`] should be returned after spawning a [`FetchedText`](crate::FetchedText) for dynamic values.
+ * Since an index is provided, it is possible to return an empty segment and manually update it.
+* [`ParseStyleFn`]
+ Parses strings as [`SegmentStyle`].
+* [`ParseConditionFn`]
+ * [`ConditionOutput::Constant`] should be returned for static condition.
+ * [`ConditionOutput::Dynamic`] should be returned after spawning a [`FetchedCondition`](crate::FetchedCondition) for dynamic values.
+
+We trim whitespaces before passing arguments to these functions.
diff --git a/vendor/bevy_rich_text3d/src/parse_util.rs b/vendor/bevy_rich_text3d/src/parse_util.rs
new file mode 100644
index 00000000..3089c45a
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/parse_util.rs
@@ -0,0 +1,288 @@
+use std::{
+ fmt::{Display, Write},
+ ops::Range,
+};
+
+use bevy::ecs::entity::Entity;
+
+use crate::{SegmentStyle, Style, Text3dSegment, Weight};
+
+pub(crate) trait Flip {
+ fn flip(&mut self);
+}
+
+impl Flip for Option<Weight> {
+ fn flip(&mut self) {
+ *self = match *self {
+ Some(w) if w <= Weight::NORMAL => Some(Weight::BOLD),
+ None => Some(Weight::BOLD),
+ _ => Some(Weight::NORMAL),
+ }
+ }
+}
+
+impl Flip for Option<Style> {
+ fn flip(&mut self) {
+ *self = match *self {
+ Some(Style::Normal) | None => Some(Style::Italic),
+ _ => Some(Style::Italic),
+ }
+ }
+}
+
+impl Flip for Option<bool> {
+ fn flip(&mut self) {
+ *self = match *self {
+ Some(false) | None => Some(true),
+ Some(true) => Some(false),
+ }
+ }
+}
+
+/// Error emitted when parsing rich text.
+#[derive(Debug)]
+pub enum ParseErrorType {
+ BracketMismatch,
+ StyleError(Option<String>),
+ ValueError(Option<String>),
+ ConditionError(Option<String>),
+}
+
+/// Error emitted when parsing rich text.
+#[derive(Debug)]
+pub struct ParseError<'t> {
+ pub(crate) text: &'t str,
+ pub(crate) span: Range<usize>,
+ pub(crate) error: ParseErrorType,
+}
+
+/// Output for parsing condition.
+///
+/// Constant may skip a portion of the text entirely while dynamic checks [`FetchedCondition`](crate::FetchedCondition) at runtime.
+#[derive(Debug, Clone, Copy)]
+pub enum ConditionOutput {
+ Constant(bool),
+ Dynamic(Entity),
+}
+
+/// Placeholder default value.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct DefaultFn;
+
+pub trait ParseStyleFn {
+ fn call(&mut self, s: &str) -> Result<SegmentStyle, Option<String>>;
+}
+
+pub trait ParseValueFn {
+ fn call(
+ &mut self,
+ index: usize,
+ s: &str,
+ ) -> Result<(Text3dSegment, SegmentStyle), Option<String>>;
+}
+
+pub trait ParseConditionFn {
+ fn call(&mut self, s: &str) -> Result<ConditionOutput, Option<String>>;
+}
+
+impl ParseStyleFn for DefaultFn {
+ fn call(&mut self, _s: &str) -> Result<SegmentStyle, Option<String>> {
+ Err(None)
+ }
+}
+
+impl ParseValueFn for DefaultFn {
+ fn call(
+ &mut self,
+ _index: usize,
+ _s: &str,
+ ) -> Result<(Text3dSegment, SegmentStyle), Option<String>> {
+ Err(None)
+ }
+}
+
+impl ParseConditionFn for DefaultFn {
+ fn call(&mut self, _s: &str) -> Result<ConditionOutput, Option<String>> {
+ Err(None)
+ }
+}
+
+impl<T: FnMut(&str) -> Result<SegmentStyle, Option<String>>> ParseStyleFn for T {
+ fn call(&mut self, s: &str) -> Result<SegmentStyle, Option<String>> {
+ self(s)
+ }
+}
+
+impl<T: FnMut(&str) -> Result<(Text3dSegment, SegmentStyle), Option<String>>> ParseValueFn for T {
+ fn call(
+ &mut self,
+ _index: usize,
+ s: &str,
+ ) -> Result<(Text3dSegment, SegmentStyle), Option<String>> {
+ self(s)
+ }
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct IndexedPVF<T>(T);
+
+impl<T: FnMut(usize, &str) -> Result<(Text3dSegment, SegmentStyle), Option<String>>> ParseValueFn
+ for IndexedPVF<T>
+{
+ fn call(
+ &mut self,
+ index: usize,
+ s: &str,
+ ) -> Result<(Text3dSegment, SegmentStyle), Option<String>> {
+ self.0(index, s)
+ }
+}
+
+impl<T: FnMut(&str) -> Result<ConditionOutput, Option<String>>> ParseConditionFn for T {
+ fn call(&mut self, s: &str) -> Result<ConditionOutput, Option<String>> {
+ self(s)
+ }
+}
+
+/// Builder pattern input for parsing rich text.
+#[derive(Debug, Clone, Copy)]
+pub struct ParseBuilder<
+ Style: ParseStyleFn = DefaultFn,
+ Value: ParseValueFn = DefaultFn,
+ Condition: ParseConditionFn = DefaultFn,
+> {
+ pub(crate) parse_style: Style,
+ pub(crate) parse_value: Value,
+ pub(crate) parse_condition: Condition,
+}
+
+impl Default for ParseBuilder {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl ParseBuilder {
+ pub const fn new() -> Self {
+ Self {
+ parse_style: DefaultFn,
+ parse_value: DefaultFn,
+ parse_condition: DefaultFn,
+ }
+ }
+}
+
+impl<B: ParseValueFn, C: ParseConditionFn> ParseBuilder<DefaultFn, B, C> {
+ pub fn with_parse_style<F: FnMut(&str) -> Result<SegmentStyle, Option<String>>>(
+ self,
+ f: F,
+ ) -> ParseBuilder<F, B, C> {
+ ParseBuilder {
+ parse_style: f,
+ parse_value: self.parse_value,
+ parse_condition: self.parse_condition,
+ }
+ }
+}
+
+impl<A: ParseStyleFn, C: ParseConditionFn> ParseBuilder<A, DefaultFn, C> {
+ pub fn with_parse_value<
+ F: FnMut(&str) -> Result<(Text3dSegment, SegmentStyle), Option<String>>,
+ >(
+ self,
+ f: F,
+ ) -> ParseBuilder<A, F, C> {
+ ParseBuilder {
+ parse_style: self.parse_style,
+ parse_value: f,
+ parse_condition: self.parse_condition,
+ }
+ }
+
+ pub fn with_parse_value_indexed<
+ F: FnMut(usize, &str) -> Result<(Text3dSegment, SegmentStyle), Option<String>>,
+ >(
+ self,
+ f: F,
+ ) -> ParseBuilder<A, IndexedPVF<F>, C> {
+ ParseBuilder {
+ parse_style: self.parse_style,
+ parse_value: IndexedPVF(f),
+ parse_condition: self.parse_condition,
+ }
+ }
+}
+
+impl<A: ParseStyleFn, B: ParseValueFn> ParseBuilder<A, B, DefaultFn> {
+ pub fn with_parse_condition<F: FnMut(&str) -> Result<ConditionOutput, Option<String>>>(
+ self,
+ f: F,
+ ) -> ParseBuilder<A, B, F> {
+ ParseBuilder {
+ parse_style: self.parse_style,
+ parse_value: self.parse_value,
+ parse_condition: f,
+ }
+ }
+}
+
+impl Display for ParseError<'_> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ pub use ParseErrorType::*;
+ f.write_str("ParseError: ")?;
+ let substr = self.text.get(self.span.clone()).unwrap_or("");
+ match &self.error {
+ BracketMismatch => f.write_str("bracket mismatch")?,
+ StyleError(None) => write!(f, "invalid style: `{}`", substr)?,
+ ValueError(None) => write!(f, "invalid value: `{}`", substr)?,
+ ConditionError(None) => write!(f, "invalid condition: `{}`", substr)?,
+ StyleError(Some(message)) => {
+ write!(f, "error parsing style `{}`: {}", substr, message)?
+ }
+ ValueError(Some(message)) => {
+ write!(f, "error parsing value `{}`: {}", substr, message)?
+ }
+ ConditionError(Some(message)) => {
+ write!(f, "error parsing condition `{}`: {}", substr, message)?
+ }
+ }
+ let mut start = 0;
+ let mut line_number = 0;
+ for (idx, char) in self.text.char_indices() {
+ if idx >= self.span.start {
+ break;
+ }
+ if char == '\n' {
+ start = idx + 1;
+ line_number += 1;
+ }
+ }
+ let (_, text) = self.text.split_at(start);
+
+ write!(f, "\n |\n{line_number:<3}| ")?;
+ let mut buf2 = " | ".to_owned();
+
+ for (idx, char) in text.char_indices() {
+ let idx = idx + start;
+ if char == '\n' {
+ line_number += 1;
+ writeln!(f, "\n{}", buf2)?;
+ buf2.truncate(5);
+ if idx >= self.span.end {
+ return Ok(());
+ } else {
+ write!(f, "{line_number:<3}|")?;
+ }
+ } else {
+ f.write_char(char)?;
+ if self.span.contains(&idx) {
+ buf2.push('^');
+ } else {
+ buf2.push(' ');
+ }
+ }
+ }
+ writeln!(f, "\n{}", buf2)?;
+ Ok(())
+ }
+}
diff --git a/vendor/bevy_rich_text3d/src/prepare.rs b/vendor/bevy_rich_text3d/src/prepare.rs
new file mode 100644
index 00000000..edb2bbed
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/prepare.rs
@@ -0,0 +1,233 @@
+use std::{
+ collections::VecDeque,
+ num::NonZero,
+ ops::{Deref, DerefMut},
+ sync::{Arc, Mutex, MutexGuard},
+};
+
+use bevy::{
+ asset::{AssetId, Assets},
+ ecs::resource::Resource,
+ image::Image,
+};
+use cosmic_text::{Attrs, Buffer, Family, FontSystem, Metrics, Shaping, Style, Weight};
+use ttf_parser::Face;
+
+use crate::{StrokeJoin, Text3dPlugin, TextAtlas, render::cache_glyph};
+
+/// An [`Arc<Mutex>`] around [`cosmic_text::FontSystem`],
+/// rendering fonts require exclusive access.
+#[derive(Debug, Resource, Clone)]
+pub struct TextRenderer(pub(crate) Arc<Mutex<TextRendererInner>>);
+
+impl TextRenderer {
+ pub fn new(font_system: FontSystem) -> Self {
+ Self(Arc::new(Mutex::new(TextRendererInner {
+ font_system,
+ queue: VecDeque::new(),
+ })))
+ }
+
+ // Methods uses `mut` to deter `Res` usage as that would block.
+
+ /// Obtain the underlying [`FontSystem`].
+ pub fn lock(&mut self) -> FontSystemGuard<'_> {
+ FontSystemGuard(self.0.lock().unwrap())
+ }
+
+ /// Obtain the underlying [`FontSystem`] if not loading.
+ pub fn try_lock(&mut self) -> Option<FontSystemGuard<'_>> {
+ self.0.try_lock().ok().map(FontSystemGuard)
+ }
+}
+
+/// Mutex guard over a [`FontSystem`].
+pub struct FontSystemGuard<'t>(MutexGuard<'t, TextRendererInner>);
+
+impl Deref for FontSystemGuard<'_> {
+ type Target = FontSystem;
+
+ fn deref(&self) -> &Self::Target {
+ &self.0.font_system
+ }
+}
+
+impl DerefMut for FontSystemGuard<'_> {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.0.font_system
+ }
+}
+
+#[derive(Debug)]
+pub(crate) struct TextRendererInner {
+ pub(crate) font_system: FontSystem,
+ pub(crate) queue: VecDeque<(AssetId<TextAtlas>, TextAtlas, Image)>,
+}
+
+/// Style that only concerns drawing but not layout.
+#[derive(Debug, Clone, Default)]
+pub struct DrawStyle {
+ pub family: Arc<str>,
+ pub size: f32,
+ pub stroke: Option<NonZero<u32>>,
+ pub stroke_join: StrokeJoin,
+ pub weight: Weight,
+ pub style: Style,
+}
+
+pub(crate) fn family(name: &str) -> Family<'_> {
+ match name {
+ "" | "serif" => Family::Serif,
+ "sans-serif" => Family::SansSerif,
+ "monospace" => Family::Monospace,
+ "cursive" => Family::Cursive,
+ "fantasy" => Family::Fantasy,
+ _ => Family::Name(name),
+ }
+}
+
+impl DrawStyle {
+ pub fn as_attrs(&self) -> Attrs<'_> {
+ Attrs::new()
+ .family(family(&self.family))
+ .weight(self.weight)
+ .style(self.style)
+ }
+}
+
+/// A callback function that helps a loading screen keep track of progress.
+///
+/// If no callback is needed use `()`.
+pub trait TextProgressReportCallback: Send + Sync + 'static {
+ /// Called every time a glyph is drawn.
+ fn glyph_drawn(&mut self) {}
+ /// Called every time a style entry is drawn.
+ fn style_drawn(&mut self) {}
+ /// Called every time an atlas is drawn.
+ fn atlas_drawn(&mut self) {}
+}
+
+impl TextProgressReportCallback for () {}
+
+impl TextRenderer {
+ /// Creates a function task that renders text to a [`TextAtlas`].
+ ///
+ /// This function should either be ran synchronously before app startup
+ /// or be sent to another thread during a loading screen.
+ ///
+ /// While the task is running concurrently, the text rendering system
+ /// will be paused and no new text will be drawn.
+ ///
+ /// The [`TextAtlas`] and [`Image`] will be REPLACED after the task finishes.
+ /// You should not call `prepare_task` with the same atlas
+ /// or image multiple times, or modify them concurrently in the `World`.
+ pub fn prepare_task<S, I>(
+ &self,
+ settings: &Text3dPlugin,
+ workload: impl IntoIterator<Item = (AssetId<TextAtlas>, TextAtlas, Image, I)>
+ + Send
+ + Sync
+ + 'static,
+ mut callback: impl TextProgressReportCallback,
+ ) -> impl FnOnce() + Send + Sync + 'static
+ where
+ S: AsRef<str> + 'static,
+ I: IntoIterator<Item = (S, DrawStyle)>,
+ {
+ let font_system = self.clone();
+ let scale_factor = settings.scale_factor;
+ move || {
+ let mut guard = font_system.0.lock().unwrap();
+ let TextRendererInner { font_system, queue } = guard.deref_mut();
+ for (id, mut atlas, mut image, workload) in workload {
+ for (str, style) in workload {
+ let mut buffer = Buffer::new(font_system, Metrics::new(style.size, style.size));
+ buffer.set_text(str.as_ref(), &style.as_attrs(), Shaping::Advanced, None);
+ buffer.shape_until_scroll(font_system, false);
+ let join = style.stroke_join;
+ let stroke = style.stroke;
+ let weight = style.weight;
+ for run in buffer.layout_runs() {
+ for glyph in run.glyphs {
+ font_system.db().with_face_data(glyph.font_id, |file, _| {
+ let Ok(face) = Face::parse(file, 0) else {
+ return;
+ };
+ cache_glyph(
+ scale_factor,
+ &mut atlas,
+ &mut image,
+ glyph,
+ stroke,
+ join,
+ weight,
+ face,
+ );
+ });
+ callback.glyph_drawn();
+ }
+ }
+ callback.style_drawn();
+ }
+ queue.push_back((id, atlas, image));
+ callback.atlas_drawn();
+ }
+ }
+ }
+
+ /// Creates a function task that renders text to a [`TextAtlas`].
+ ///
+ /// This function prepare atlases by cloning the underlying images.
+ /// See [`TextRenderer::prepare_task`] for details.
+ pub fn prepare_images_cloned<S, I>(
+ &self,
+ settings: &Text3dPlugin,
+ workload: impl IntoIterator<Item = (AssetId<TextAtlas>, I)> + Send + Sync + 'static,
+ atlases: &mut Assets<TextAtlas>,
+ images: &mut Assets<Image>,
+ callback: impl TextProgressReportCallback,
+ ) -> impl FnOnce() + Send + Sync + 'static
+ where
+ S: AsRef<str> + 'static,
+ I: IntoIterator<Item = (S, DrawStyle)> + Send + Sync + 'static,
+ {
+ let workload: Vec<_> = workload
+ .into_iter()
+ .filter_map(|(id, iter)| {
+ let atlas = atlases.get(id)?.clone();
+ let image = images.get(atlas.image.id())?.clone();
+ Some((id, atlas, image, iter))
+ })
+ .collect();
+ self.prepare_task(settings, workload, callback)
+ }
+
+ /// Creates a function task that renders text to a [`TextAtlas`].
+ ///
+ /// This function prepare atlases by removing the underlying atlases and images
+ /// and readd them after the task finishes.
+ /// If spawned as a thread, the images will not be available until render finishes.
+ /// See [`TextRenderer::prepare_task`] for details.
+ pub fn prepare_images<S, I>(
+ &self,
+ settings: &Text3dPlugin,
+ workload: impl IntoIterator<Item = (AssetId<TextAtlas>, I)> + Send + Sync + 'static,
+ atlases: &mut Assets<TextAtlas>,
+ images: &mut Assets<Image>,
+ callback: impl TextProgressReportCallback,
+ ) -> impl FnOnce() + Send + Sync + 'static
+ where
+ S: AsRef<str> + 'static,
+ I: IntoIterator<Item = (S, DrawStyle)> + Send + Sync + 'static,
+ {
+ let workload: Vec<_> = workload
+ .into_iter()
+ .filter_map(|(id, iter)| {
+ let atlas = atlases.remove(id)?.clone();
+ let image = images.remove(atlas.image.id())?.clone();
+ Some((id, atlas, image, iter))
+ })
+ .collect();
+ self.prepare_task(settings, workload, callback)
+ }
+}
diff --git a/vendor/bevy_rich_text3d/src/render.rs b/vendor/bevy_rich_text3d/src/render.rs
new file mode 100644
index 00000000..bc2eae23
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/render.rs
@@ -0,0 +1,612 @@
+use bevy::{
+ a11y::AccessibilityNode,
+ asset::{AssetId, Assets, RenderAssetUsages},
+ ecs::{
+ change_detection::DetectChanges,
+ system::{Local, Query, Res, ResMut},
+ world::{Mut, Ref},
+ },
+ image::Image,
+ math::{IRect, IVec2, Rect, Vec2, Vec3, Vec4},
+ mesh::{Indices, Mesh, Mesh2d, Mesh3d, PrimitiveTopology, VertexAttributeValues},
+};
+use cosmic_text::{Attrs, Buffer, Family, FontSystem, LayoutGlyph, Metrics, Shaping, Weight, Wrap};
+use std::{mem, num::NonZero};
+use ttf_parser::{Face, GlyphId};
+
+use crate::{
+ SegmentStyle, StrokeJoin, Text3dBounds, Text3dDimensionOut, Text3dPlugin, Text3dStyle,
+ TextAtlas, TextAtlasHandle, TextRenderer,
+ fetch::{FetchedCondition, FetchedText},
+ layers::{DrawRequest, DrawType, Layer},
+ line::LineRun,
+ mesh_util::ExtractedMesh,
+ styling::{FloatDecimal, GlyphEntry},
+ tess::PathEncoder,
+ text3d::{Text3d, Text3dSegment},
+};
+
+fn default_mesh() -> Mesh {
+ Mesh::new(PrimitiveTopology::TriangleList, RenderAssetUsages::all())
+ .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, Vec::<Vec3>::new())
+ .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, Vec::<Vec3>::new())
+ .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, Vec::<Vec2>::new())
+ .with_inserted_attribute(Mesh::ATTRIBUTE_COLOR, Vec::<Vec4>::new())
+ .with_inserted_indices(Indices::U16(Vec::new()))
+}
+
+fn get_mesh<'t>(
+ mesh2d: &mut Option<Mut<Mesh2d>>,
+ mesh3d: &mut Option<Mut<Mesh3d>>,
+ meshes: &'t mut Assets<Mesh>,
+) -> Option<&'t mut Mesh> {
+ let mut id = mesh2d
+ .as_ref()
+ .map(|x| x.id())
+ .or_else(|| mesh3d.as_ref().map(|x| x.id()))?;
+ if id == AssetId::default() {
+ let handle = meshes.add(default_mesh());
+ id = handle.id();
+ if let Some(handle_2d) = mesh2d {
+ handle_2d.0 = handle.clone();
+ }
+ if let Some(handle_3d) = mesh3d {
+ handle_3d.0 = handle;
+ }
+ }
+ meshes.get_mut(id).map(|x| x.into_inner())
+}
+
+mod private {
+ pub struct TextRng(pub fastrand::Rng);
+
+ impl Default for TextRng {
+ fn default() -> Self {
+ Self(fastrand::Rng::with_seed(0))
+ }
+ }
+}
+
+pub fn text_render(
+ settings: Res<Text3dPlugin>,
+ font_system: ResMut<TextRenderer>,
+ mut meshes: ResMut<Assets<Mesh>>,
+ mut images: ResMut<Assets<Image>>,
+ mut atlases: ResMut<Assets<TextAtlas>>,
+ mut text_query: Query<(
+ Ref<Text3d>,
+ Ref<Text3dBounds>,
+ Ref<Text3dStyle>,
+ &TextAtlasHandle,
+ Option<&mut Mesh2d>,
+ Option<&mut Mesh3d>,
+ &mut Text3dDimensionOut,
+ Option<&mut AccessibilityNode>,
+ )>,
+ segments: Query<Ref<FetchedText>>,
+ conditions: Query<Ref<FetchedCondition>>,
+ mut draw_requests: Local<Vec<DrawRequest>>,
+ mut sort_buffer: Local<Vec<(Layer, [u16; 6])>>,
+ mut rng: Local<private::TextRng>,
+) {
+ let Ok(mut lock) = font_system.0.try_lock() else {
+ return;
+ };
+ let mut redraw = false;
+ if font_system.is_changed() {
+ redraw = true;
+ }
+ // Add asynchronously drawn text.
+ for (id, atlas, image) in lock.queue.drain(..) {
+ let img_id = atlas.image.id();
+ let _ = images.insert(img_id, image);
+ let _ = atlases.insert(id, atlas);
+ redraw = true;
+ }
+ let font_system = &mut lock.font_system;
+ let scale_factor = settings.scale_factor;
+ 'main: for (text, bounds, styling, atlas, mut mesh2d, mut mesh3d, mut output, access_node) in
+ text_query.iter_mut()
+ {
+ let Some(atlas) = atlases.get_mut(atlas.0.id()) else {
+ continue;
+ };
+
+ let atlas = atlas.into_inner();
+
+ if atlas.image.id() == AssetId::default() || !images.contains(atlas.image.id()) {
+ atlas.image = images.add(TextAtlas::empty_image(
+ settings.default_atlas_dimension.0,
+ settings.default_atlas_dimension.1,
+ ))
+ };
+
+ if !images.contains(atlas.image.id()) {
+ continue;
+ }
+
+ for segment in &text.segments {
+ if let Text3dSegment::Image(image) = &segment.0 {
+ if !images.contains(&image.handle) {
+ output.initialized = false;
+ continue 'main;
+ }
+ }
+ }
+
+ // Change detection.
+ if !redraw
+ && output.initialized
+ && !text.is_changed()
+ && !bounds.is_changed()
+ && !styling.is_changed()
+ {
+ let mut unchanged = true;
+ for segment in &text.segments {
+ if let Text3dSegment::Extract(entity) = &segment.0 {
+ if segments.get(*entity).is_ok_and(|x| x.is_changed()) {
+ unchanged = false;
+ break;
+ }
+ }
+ if let Text3dSegment::SkipIf { condition, .. } = &segment.0 {
+ if conditions.get(*condition).is_ok_and(|x| x.is_changed()) {
+ unchanged = false;
+ break;
+ }
+ }
+ }
+ if unchanged {
+ let Some(image) = images.get(atlas.image.id()) else {
+ continue;
+ };
+ let new_dimension = IVec2::new(image.width() as i32, image.height() as i32);
+ if output.atlas_dimension == new_dimension {
+ continue;
+ }
+
+ let Some(mesh) = get_mesh(&mut mesh2d, &mut mesh3d, &mut meshes) else {
+ continue;
+ };
+
+ let Some(VertexAttributeValues::Float32x2(uv0)) =
+ mesh.attribute_mut(Mesh::ATTRIBUTE_UV_0)
+ else {
+ continue;
+ };
+ for [x, y] in uv0 {
+ *x *= output.atlas_dimension.x as f32 / new_dimension.x as f32;
+ *y *= output.atlas_dimension.y as f32 / new_dimension.y as f32;
+ }
+ output.atlas_dimension = new_dimension;
+ continue;
+ }
+ }
+
+ let mut buffer = Buffer::new(
+ font_system,
+ Metrics::new(styling.size, styling.size * styling.line_height),
+ );
+ let width_limit = if let Some(world_scale) = styling.world_scale {
+ bounds.width * styling.size / world_scale.x
+ } else {
+ bounds.width
+ };
+ buffer.set_wrap(Wrap::WordOrGlyph);
+ buffer.set_size(Some(width_limit), None);
+ buffer.set_tab_width(styling.tab_width);
+
+ #[cfg(feature = "a11y")]
+ let mut alt_text = String::new();
+
+ let mut to_skip = 0;
+ buffer.set_rich_text(
+ text.segments
+ .iter()
+ .enumerate()
+ .filter_map(|(idx, (text, style))| {
+ if to_skip > 0 {
+ to_skip -= 1;
+ return None;
+ }
+ Some((
+ match text {
+ Text3dSegment::String(s) => {
+ #[cfg(feature = "a11y")]
+ alt_text.push_str(s.as_str());
+ s.as_str()
+ }
+ Text3dSegment::Extract(e) => {
+ let s = segments
+ .get(*e)
+ .map(|x| x.into_inner().as_str())
+ .unwrap_or("");
+ #[cfg(feature = "a11y")]
+ alt_text.push_str(s);
+ s
+ }
+ Text3dSegment::Image(image) => {
+ #[cfg(feature = "a11y")]
+ alt_text.push_str(&image.alt_text);
+ settings.get_placeholder_glyph(image.width)
+ }
+ Text3dSegment::SkipIf {
+ condition,
+ skip_if,
+ offset,
+ } => {
+ if let Ok(condition) = conditions.get(*condition) {
+ if condition.0 == *skip_if {
+ to_skip = *offset;
+ }
+ }
+ return None;
+ }
+ },
+ match text {
+ Text3dSegment::Image { .. } => style
+ .as_attr(&styling)
+ .metadata(idx)
+ .family(Family::Name(&settings.placeholder_family)),
+ _ => style.as_attr(&styling).metadata(idx),
+ },
+ ))
+ }),
+ &Attrs::new()
+ .family(Family::Name(&styling.font))
+ .style(styling.style.into())
+ .weight(styling.weight.into()),
+ Shaping::Advanced,
+ None,
+ );
+
+ #[cfg(feature = "a11y")]
+ if let Some(mut node) = access_node {
+ node.0.set_label(alt_text);
+ }
+
+ buffer.shape_until_scroll(font_system, true);
+
+ let Some(mesh) = get_mesh(&mut mesh2d, &mut mesh3d, &mut meshes) else {
+ continue;
+ };
+
+ let mut mesh = ExtractedMesh::new(mesh, &mut sort_buffer, &styling);
+
+ let mut width = 0.0f32;
+ let mut advance = 0.0f32;
+ let mut real_index = 0;
+
+ let mut height = 0.0f32;
+
+ let mut image = Image::default_uninit();
+ let image = &mut image;
+
+ // Validated before so should always work.
+ if let Some(mut im) = images.get_mut(atlas.image.id()) {
+ mem::swap(image, &mut im);
+ };
+
+ for run in buffer.layout_runs() {
+ width = width.max(run.line_w);
+ height = height.max(run.line_top + run.line_height);
+ let mut underline_run = LineRun::default();
+ let mut strikethrough_run = LineRun::default();
+ for glyph_index in 0..run.glyphs.len() {
+ let glyph = &run.glyphs[glyph_index];
+ let Some((seg, attrs)) = text.segments.get(glyph.metadata) else {
+ continue;
+ };
+ let line_start = -run.line_w * styling.align.as_fac();
+
+ styling.fill_draw_requests(seg, attrs, &mut draw_requests);
+
+ let magic_number = attrs.magic_number.unwrap_or(0.);
+
+ let scale_factor = if glyph.font_size <= settings.double_scale_factor_threshold {
+ scale_factor * 2.0
+ } else {
+ scale_factor
+ };
+
+ for DrawRequest {
+ request,
+ color,
+ offset,
+ sort: layer,
+ category,
+ } in draw_requests.drain(..)
+ {
+ match request {
+ DrawType::Glyph(stroke) => {
+ let Some((pixel_rect, base)) = get_atlas_rect(
+ font_system,
+ scale_factor,
+ &styling,
+ atlas,
+ image,
+ glyph,
+ attrs,
+ stroke,
+ ) else {
+ continue;
+ };
+
+ let line_advance = glyph.x + base.x;
+
+ let base = Vec2::new(glyph.x, glyph.y)
+ + base
+ + offset
+ + Vec2::new(line_start, -run.line_y);
+
+ mesh.cache_rectangle(
+ base,
+ pixel_rect.size() / scale_factor,
+ pixel_rect,
+ color,
+ layer,
+ real_index,
+ advance + line_advance,
+ magic_number,
+ category,
+ &styling,
+ &mut rng.0,
+ );
+ }
+
+ DrawType::Image(id) => {
+ let Some(emoji_image) = images.get(id) else {
+ continue;
+ };
+ let Some(pixel_rect) = get_atlas_emoji(atlas, id, image, emoji_image)
+ else {
+ continue;
+ };
+
+ let Some(Some((Some(bb), units_per_em))) =
+ font_system.db().with_face_data(glyph.font_id, |file, _| {
+ let Ok(face) = Face::parse(file, 0) else {
+ return None;
+ };
+ Some((
+ face.glyph_bounding_box(GlyphId(glyph.glyph_id)),
+ face.units_per_em(),
+ ))
+ })
+ else {
+ continue;
+ };
+
+ let bx = bb.x_min as f32 / units_per_em as f32 * glyph.font_size;
+ let by = bb.y_min as f32 / units_per_em as f32 * glyph.font_size;
+
+ let w = bb.width() as f32 / units_per_em as f32 * glyph.font_size;
+ let h = bb.height() as f32 / units_per_em as f32 * glyph.font_size;
+
+ let base = Vec2::new(glyph.x + bx, glyph.y + by)
+ + offset
+ + Vec2::new(line_start, -run.line_y);
+
+ mesh.cache_rectangle(
+ base,
+ Vec2::new(w, h),
+ pixel_rect,
+ color,
+ layer,
+ real_index,
+ advance + glyph.x,
+ magic_number,
+ category,
+ &styling,
+ &mut rng.0,
+ );
+ }
+ DrawType::Line(stroke, mode) => {
+ let line = mode.select(&mut underline_run, &mut strikethrough_run);
+ if !line.contains(glyph) {
+ *line = mode.new_run(
+ mode.size(font_system, glyph.font_id, glyph.font_size),
+ glyph_index,
+ run.glyphs,
+ &text.segments,
+ );
+ }
+ let stroke_size = stroke.map(|x| x.get()).unwrap_or(0) as f32
+ * glyph.font_size
+ / 200.;
+ let Some(uv_rect) = mode.get_atlas_rect(
+ font_system,
+ glyph.font_id,
+ scale_factor,
+ atlas,
+ image,
+ attrs,
+ &styling,
+ stroke,
+ ) else {
+ continue;
+ };
+ let (min, max) =
+ mode.boundary(run.glyphs, &text.segments, glyph_index, stroke_size);
+ for ((min, uv_min), (max, uv_max)) in
+ line.uv_range(min, max, stroke_size).iter()
+ {
+ let Some(rect) = mode.get_line_rect(
+ font_system,
+ styling.size,
+ min,
+ max,
+ stroke_size,
+ glyph,
+ ) else {
+ continue;
+ };
+ let rect = Rect {
+ min: rect.min + offset + Vec2::new(line_start, -run.line_y),
+ max: rect.max + offset + Vec2::new(line_start, -run.line_y),
+ };
+ let result_rect = Rect {
+ min: Vec2::new(
+ uv_rect.min.x + uv_rect.size().x * uv_min,
+ uv_rect.min.y,
+ ),
+ max: Vec2::new(
+ uv_rect.min.x + uv_rect.size().x * uv_max,
+ uv_rect.max.y,
+ ),
+ };
+ mesh.cache_rectangle2(
+ rect,
+ result_rect,
+ color,
+ layer,
+ real_index,
+ advance + min,
+ magic_number,
+ category,
+ &styling,
+ &mut rng.0,
+ );
+ }
+ }
+ };
+ }
+ real_index += 1;
+ }
+ advance += run.line_w;
+ }
+
+ let dimension = Vec2::new(width, height);
+ let center = Vec2::new(width * (0.5 - styling.align.as_fac()), -height / 2.);
+ let offset = -*styling.anchor * dimension - center;
+ let bb_min = Vec2::new(width * -styling.align.as_fac(), -height);
+
+ mesh.post_process(bb_min, dimension);
+
+ if let Some(world_scale) = styling.world_scale {
+ mesh.translate(|v| *v = (*v + offset) * world_scale / styling.size);
+ output.dimension = dimension * world_scale / styling.size;
+ } else {
+ mesh.translate(|v| *v += offset);
+ output.dimension = dimension;
+ }
+
+ output.atlas_dimension = IVec2::new(image.width() as i32, image.height() as i32);
+
+ mesh.pixel_to_uv(image);
+
+ if let Some(mut im) = images.get_mut(atlas.image.id()) {
+ mem::swap(image, &mut im);
+ };
+ output.initialized = true;
+ }
+}
+
+fn get_atlas_rect(
+ font_system: &mut FontSystem,
+ scale_factor: f32,
+ styling: &Text3dStyle,
+ atlas: &mut TextAtlas,
+ image: &mut Image,
+ glyph: &LayoutGlyph,
+ attrs: &SegmentStyle,
+ stroke: Option<NonZero<u32>>,
+) -> Option<(Rect, Vec2)> {
+ atlas
+ .glyphs
+ .get(&GlyphEntry::Glyph {
+ font: glyph.font_id,
+ glyph_id: glyph.glyph_id.into(),
+ real_size: FloatDecimal::new(glyph.font_size * scale_factor),
+ weight: styling.weight,
+ join: styling.stroke_join,
+ stroke,
+ })
+ .copied()
+ .or_else(|| {
+ font_system
+ .db()
+ .with_face_data(glyph.font_id, |file, _| {
+ let Ok(face) = Face::parse(file, 0) else {
+ return None;
+ };
+ cache_glyph(
+ scale_factor,
+ atlas,
+ image,
+ glyph,
+ stroke,
+ styling.stroke_join,
+ attrs.weight.unwrap_or(styling.weight).into(),
+ face,
+ )
+ })
+ .flatten()
+ })
+ .map(|(rect, offset)| (rect.as_rect(), offset / scale_factor))
+}
+
+fn get_atlas_emoji(
+ atlas: &mut TextAtlas,
+ id: AssetId<Image>,
+ atlas_image: &mut Image,
+ emoji_image: &Image,
+) -> Option<Rect> {
+ let entry = GlyphEntry::Image(id);
+ if let Some((rect, _)) = atlas.glyphs.get(&entry) {
+ return Some(rect.as_rect());
+ }
+ let rect = atlas.allocate(
+ atlas_image,
+ entry,
+ Vec2::ZERO,
+ emoji_image.width() as usize,
+ emoji_image.height() as usize,
+ );
+ let w_a = atlas_image.width() as usize * 4;
+ let w = emoji_image.width() as usize * 4;
+ let h = emoji_image.height() as usize;
+ let atlas_buf = atlas_image.data.as_mut()?;
+ let image_buf = emoji_image.data.as_ref()?;
+ let origin = rect.min.y as usize * w_a + rect.min.x as usize * 4;
+ // Should not happen normally but just here to avoid panics.
+ if atlas_buf.len() < origin + h * w_a {
+ return None;
+ }
+ if image_buf.len() < h * w {
+ return None;
+ }
+ for i in 0..h {
+ let r_i = h - i - 1;
+ // reversed to match the svg renderer's coordinate system.
+ atlas_buf[origin + i * w_a..origin + i * w_a + w]
+ .copy_from_slice(&image_buf[r_i * w..r_i * w + w]);
+ }
+ Some(rect.as_rect())
+}
+
+pub(crate) fn cache_glyph(
+ scale_factor: f32,
+ atlas: &mut TextAtlas,
+ image: &mut Image,
+ glyph: &cosmic_text::LayoutGlyph,
+ stroke: Option<NonZero<u32>>,
+ stroke_join: StrokeJoin,
+ weight: Weight,
+ face: Face,
+) -> Option<(IRect, Vec2)> {
+ let unit_per_em = face.units_per_em() as f32;
+ let entry = GlyphEntry::Glyph {
+ font: glyph.font_id,
+ glyph_id: glyph.glyph_id.into(),
+ real_size: FloatDecimal::new(glyph.font_size * scale_factor),
+ weight: weight.into(),
+ stroke,
+ join: stroke_join,
+ };
+ let mut tess_commands = PathEncoder::default();
+ face.outline_glyph(GlyphId(glyph.glyph_id), &mut tess_commands)?;
+ let stroke = stroke.map(|x| x.get() as f32 * glyph.font_size / 100.);
+ let scale = glyph.font_size / unit_per_em * scale_factor;
+ tess_commands.tess_glyph(stroke, scale, atlas, image, entry)
+}
diff --git a/vendor/bevy_rich_text3d/src/styling.rs b/vendor/bevy_rich_text3d/src/styling.rs
new file mode 100644
index 00000000..11ba9442
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/styling.rs
@@ -0,0 +1,203 @@
+use crate::{MeshExport, StrokeJoin, Style, TextAlign, TextAnchor, Weight, prepare::family};
+use bevy::asset::AssetId;
+use bevy::image::Image;
+use bevy::{color::Srgba, ecs::component::Component, math::Vec2};
+use cosmic_text::Metrics;
+use cosmic_text::{Attrs, fontdb::ID};
+use std::fmt::Debug;
+use std::{num::NonZeroU32, sync::Arc};
+
+#[cfg(feature = "reflect")]
+use bevy::prelude::{Reflect, ReflectComponent, ReflectDefault};
+
+/// Default text style of a rich text component.
+#[derive(Debug, Component, Clone)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+#[cfg_attr(feature = "reflect", reflect(Component, Default))]
+pub struct Text3dStyle {
+ /// Size of the font, corresponding to world space units.
+ ///
+ /// Ths is cached per unique value so keep the amount of unique values of `size` low,
+ /// use [`Text3dStyle::world_scale`] instead for small variations.
+ pub size: f32,
+ /// Name of the font, by default `"serif"`.
+ ///
+ /// For `"serif"`, `"sans-serif"`, `"monospace"`, `"cursive"` and `"fantasy"`,
+ /// use one of the default fonts set in `cosmic_text`.
+ pub font: Arc<str>,
+ /// Style of the font, i.e. italic.
+ pub style: Style,
+ /// Weight of the font, i.e. bold.
+ pub weight: Weight,
+ /// Horizontal alignment of the font.
+ pub align: TextAlign,
+ /// Where local `[0, 0]` is inside the text block's Aabb.
+ pub anchor: TextAnchor,
+ /// Height of a line multiplied by font size, by default `1.0`.
+ pub line_height: f32,
+ /// Color of fill.
+ pub color: Srgba,
+ /// Color of stroke.
+ pub stroke_color: Srgba,
+ /// If not set, will not render the fill of the font, making it hollow.
+ pub fill: bool,
+ /// If set, renders a stroke or outline of the font.
+ ///
+ /// The value represents a percentage of the font size and should be
+ /// in `1..10` for hollow text and `1..20` for outline.
+ ///
+ /// Ths is cached per unique value so be sure not to use too many of them.
+ pub stroke: Option<NonZeroU32>,
+ /// If true, render stroke in front.
+ pub stroke_in_front: bool,
+ /// The shape of the stroke line joins, usually [`StrokeJoin::Round`].
+ pub stroke_join: StrokeJoin,
+ /// Sets the distance between different layers, i.e. stroke and fill.
+ ///
+ /// `0.0` likely works for transparent render modes and opaque2d, but
+ /// not for opaque3d.
+ pub layer_offset: f32,
+ /// Determines what to extract as uv1.
+ #[cfg_attr(feature = "reflect", reflect(ignore))]
+ pub export: MeshExport,
+ /// Tab in terms of spaces, default 4.
+ pub tab_width: u16,
+ /// If set, overwrite the size of `em` in the generated mesh.
+ ///
+ /// By default the mesh size is relative to [`Text3dStyle::size`], which is equivalent to `Some((size, size))`.
+ pub world_scale: Option<Vec2>,
+ /// If `Some`, render a text shadow.
+ pub text_shadow: Option<(Srgba, Vec2)>,
+}
+
+impl Default for Text3dStyle {
+ fn default() -> Self {
+ Self {
+ size: 16.,
+ color: Srgba::WHITE,
+ font: Default::default(),
+ style: Default::default(),
+ weight: Default::default(),
+ align: Default::default(),
+ anchor: TextAnchor::CENTER,
+ stroke_color: Srgba::WHITE,
+ fill: true,
+ stroke: Default::default(),
+ line_height: 1.0,
+ layer_offset: 0.01,
+ stroke_in_front: false,
+ stroke_join: StrokeJoin::Round,
+ export: MeshExport::None,
+ tab_width: 4,
+ world_scale: None,
+ text_shadow: None,
+ }
+ }
+}
+
+/// Size of a segment.
+#[derive(Debug, Clone, Copy)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+pub enum SegmentSize {
+ Flat(f32),
+ Multiply(f32),
+}
+
+/// Text style of a segment.
+#[derive(Debug, Default, Clone)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+pub struct SegmentStyle {
+ pub font: Option<Arc<str>>,
+ pub size: Option<SegmentSize>,
+ pub fill_color: Option<Srgba>,
+ pub stroke_color: Option<Srgba>,
+ pub fill: Option<bool>,
+ pub stroke: Option<NonZeroU32>,
+ pub weight: Option<Weight>,
+ pub style: Option<Style>,
+ pub underline: Option<bool>,
+ pub strikethrough: Option<bool>,
+ /// Can be referenced by [`GlyphMeta::MagicNumber`](crate::GlyphMeta::MagicNumber).
+ pub magic_number: Option<f32>,
+}
+
+impl SegmentStyle {
+ pub fn as_attr<'t>(&'t self, base: &'t Text3dStyle) -> Attrs<'t> {
+ let family_name = self.font.as_ref().map(Arc::as_ref).unwrap_or(&base.font);
+ let family = family(family_name);
+
+ match self.size {
+ Some(SegmentSize::Flat(size)) => {
+ Attrs::new().metrics(Metrics::new(size, size * base.line_height))
+ }
+ Some(SegmentSize::Multiply(size)) => {
+ let size = base.size * size;
+ Attrs::new().metrics(Metrics::new(size, size * base.line_height))
+ }
+ None => Attrs::new(),
+ }
+ .weight(self.weight.unwrap_or(base.weight).into())
+ .style(self.style.unwrap_or(base.style).into())
+ .family(family)
+ }
+
+ pub fn join(&self, other: Self) -> Self {
+ SegmentStyle {
+ font: other.font.or_else(|| self.font.clone()),
+ size: other.size.or(self.size),
+ fill_color: other.fill_color.or(self.fill_color),
+ stroke_color: other.stroke_color.or(self.stroke_color),
+ fill: other.fill.or(self.fill),
+ stroke: other.stroke.or(self.stroke),
+ weight: other.weight.or(self.weight),
+ underline: other.underline.or(self.underline),
+ strikethrough: other.strikethrough.or(self.strikethrough),
+ style: other.style.or(self.style),
+ magic_number: other.magic_number.or(self.magic_number),
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum GlyphEntry {
+ Glyph {
+ font: ID,
+ glyph_id: GlyphTextureOf,
+ join: StrokeJoin,
+ /// Multiplied by scale factor.
+ real_size: FloatDecimal,
+ weight: Weight,
+ stroke: Option<NonZeroU32>,
+ },
+ Image(AssetId<Image>),
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum GlyphTextureOf {
+ Id(u16),
+ UnderlineTexture,
+ StrikethroughTexture,
+}
+
+impl From<u16> for GlyphTextureOf {
+ fn from(id: u16) -> Self {
+ GlyphTextureOf::Id(id)
+ }
+}
+
+/// A floating point hashmap key
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+pub struct FloatDecimal(i32);
+
+impl FloatDecimal {
+ pub fn new(input: f32) -> Self {
+ Self((input * 100.).round() as i32)
+ }
+}
+
+impl Debug for FloatDecimal {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let value = self.0 as f32 / 100.;
+ f.debug_tuple("FloatDecimal").field(&value).finish()
+ }
+}
diff --git a/vendor/bevy_rich_text3d/src/tess.rs b/vendor/bevy_rich_text3d/src/tess.rs
new file mode 100644
index 00000000..d8155e0d
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/tess.rs
@@ -0,0 +1,112 @@
+use crate::{TextAtlas, styling::GlyphEntry};
+use bevy::{
+ image::Image,
+ math::{IRect, Vec2},
+};
+use tiny_skia::{
+ BlendMode, Color, ColorSpace, FillRule, LineCap, Paint, PathBuilder, PixmapMut,
+ Rect as SkiaRect, Shader, Stroke, Transform,
+};
+use ttf_parser::OutlineBuilder;
+
+#[derive(Debug, Default)]
+pub(crate) struct PathEncoder {
+ pub commands: PathBuilder,
+}
+
+impl OutlineBuilder for PathEncoder {
+ fn move_to(&mut self, x: f32, y: f32) {
+ self.commands.move_to(x, y);
+ }
+
+ fn line_to(&mut self, x: f32, y: f32) {
+ self.commands.line_to(x, y);
+ }
+
+ fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
+ self.commands.quad_to(x1, y1, x, y);
+ }
+
+ fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
+ self.commands.cubic_to(x1, y1, x2, y2, x, y);
+ }
+
+ fn close(&mut self) {
+ self.commands.close();
+ }
+}
+
+impl PathEncoder {
+ pub fn push_rect(&mut self, min_x: f32, min_y: f32, max_x: f32, max_y: f32) {
+ if let Some(rect) = SkiaRect::from_ltrb(min_x, min_y, max_x, max_y) {
+ self.commands.push_rect(rect);
+ }
+ }
+}
+
+impl PathEncoder {
+ /// Returns a rectangle and an additional offset, keep in mind both has to be applied scale factor before usage.
+ ///
+ /// * `scale`: the value multiplied to the original glyph of size `units_per_em` (usually 1000 or so),
+ /// so size * scale_factor / units_per_em for regular usage
+ pub fn tess_glyph(
+ self,
+ stroke: Option<f32>,
+ scale: f32,
+ atlas: &mut TextAtlas,
+ image: &mut Image,
+ entry: GlyphEntry,
+ ) -> Option<(IRect, Vec2)> {
+ // raea: the image's size is read after the glyph is allocated (below), never before: allocating can double the
+ // raea: atlas's height, and the glyph that grew it was drawn into the old bounds and stayed cut (raea's
+ // raea: docs/stage-guards.feature SG3)
+ let paint = Paint {
+ shader: Shader::SolidColor(Color::WHITE),
+ blend_mode: BlendMode::Source,
+ anti_alias: true,
+ colorspace: ColorSpace::Linear,
+ force_hq_pipeline: false,
+ };
+ let path = self.commands.finish()?;
+ let path = path.transform(Transform::from_scale(scale, scale))?;
+ let boundary = path.compute_tight_bounds()?;
+ if let Some(stroke) = stroke {
+ let boundary = boundary.outset(stroke, stroke).unwrap();
+ let w = boundary.width().ceil() as usize;
+ let h = boundary.height().ceil() as usize;
+ let base = Vec2::new(boundary.left(), boundary.top());
+ let pixel_rect = atlas.allocate(image, entry, base, w, h);
+ let (image_width, image_height) = (image.width(), image.height()); // raea: after the allocation
+ let line_join = match entry {
+ GlyphEntry::Glyph { join, .. } => join,
+ GlyphEntry::Image(_) => Default::default(),
+ };
+ let stroke = Stroke {
+ // Different from the original zeno implementation.
+ width: stroke * 2.0,
+ miter_limit: 4.0,
+ line_cap: LineCap::Round,
+ line_join: line_join.into(),
+ dash: None,
+ };
+ let v = pixel_rect.min.as_vec2() - base;
+ let transform = Transform::from_translate(v.x, v.y);
+ let bytes = image.data.as_mut()?;
+ let mut pixmap = PixmapMut::from_bytes(bytes, image_width, image_height)?;
+ pixmap.stroke_path(&path, &paint, &stroke, transform, None);
+ Some((pixel_rect, base))
+ } else {
+ let w = boundary.width().ceil() as usize;
+ let h = boundary.height().ceil() as usize;
+ let base = Vec2::new(boundary.left(), boundary.top());
+ let pixel_rect = atlas.allocate(image, entry, base, w, h);
+ let (image_width, image_height) = (image.width(), image.height()); // raea: after the allocation
+ let v = pixel_rect.min.as_vec2() - base;
+ let transform = Transform::from_translate(v.x, v.y);
+ let bytes = image.data.as_mut()?;
+ let mut pixmap = PixmapMut::from_bytes(bytes, image_width, image_height)?;
+ pixmap.fill_path(&path, &paint, FillRule::Winding, transform, None);
+ Some((pixel_rect, base))
+ }
+ }
+}
diff --git a/vendor/bevy_rich_text3d/src/text3d.rs b/vendor/bevy_rich_text3d/src/text3d.rs
new file mode 100644
index 00000000..ab6ed9a7
--- /dev/null
+++ b/vendor/bevy_rich_text3d/src/text3d.rs
@@ -0,0 +1,226 @@
+use std::fmt::Write;
+
+use bevy::{
+ asset::Handle,
+ ecs::{
+ component::Component,
+ entity::Entity,
+ lifecycle::HookContext,
+ world::{DeferredWorld, Mut},
+ },
+ image::Image,
+};
+#[cfg(feature = "reflect")]
+use bevy::{ecs::reflect::ReflectComponent, reflect::Reflect};
+
+use crate::{
+ SharedSegment, Text3dBounds, Text3dDimensionOut, Text3dStyle, TextAtlasHandle,
+ styling::SegmentStyle,
+};
+
+/// A rich text component.
+///
+/// Requires [`Text3dStyle`], [`Text3dBounds`], [`TextAtlasHandle`], [`Text3dDimensionOut`].
+#[derive(Debug, Clone, Component, Default)]
+#[require(Text3dDimensionOut, Text3dBounds, TextAtlasHandle, Text3dStyle)]
+#[component(on_remove = text_3d_on_remove)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+#[cfg_attr(feature = "reflect", reflect(Component))]
+pub struct Text3d {
+ pub segments: Vec<(Text3dSegment, SegmentStyle)>,
+}
+
+/// Needed for BSN unpin specialization.
+impl Unpin for Text3d {}
+
+/// An image or emoji in [`Text3d`].
+#[derive(Debug, Clone)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+pub struct Text3dImage {
+ /// Image asset.
+ pub handle: Handle<Image>,
+ /// Represents width / em, usually `1.0` for squares.
+ pub width: f32,
+ /// Text for screen readers.
+ pub alt_text: String,
+}
+
+impl Default for Text3dImage {
+ fn default() -> Self {
+ Self {
+ handle: Handle::default(),
+ width: 1.0,
+ alt_text: String::new(),
+ }
+ }
+}
+
+/// A string segment in [`Text3d`].
+///
+/// `Extract` reads data from an entity's [`FetchedTextSegment`](crate::FetchedTextSegment) component.
+#[derive(Debug, Clone)]
+#[cfg_attr(feature = "reflect", derive(Reflect))]
+pub enum Text3dSegment {
+ /// A string segment.
+ String(String),
+ /// [`FetchedText`](crate::FetchedText) on an entity.
+ Extract(Entity),
+ /// Renders an image or emoji inside the text.
+ ///
+ /// # Limitations
+ ///
+ /// The image will be copied into the text atlas as is regardless of font size.
+ /// The image is only loaded once and cannot change.
+ Image(Text3dImage),
+ /// [`FetchedCondition`](crate::FetchedCondition) on an entity.
+ SkipIf {
+ condition: Entity,
+ skip_if: bool,
+ offset: usize,
+ },
+}
+
+impl From<&str> for Text3dSegment {
+ fn from(value: &str) -> Self {
+ Text3dSegment::String(value.into())
+ }
+}
+
+impl From<String> for Text3dSegment {
+ fn from(value: String) -> Self {
+ Text3dSegment::String(value)
+ }
+}
+
+impl Text3dSegment {
+ pub fn image(image: Handle<Image>, width: f32) -> Text3dSegment {
+ Text3dSegment::Image(Text3dImage {
+ handle: image,
+ width,
+ alt_text: String::new(),
+ })
+ }
+
+ pub fn image_alt_text(image: Handle<Image>, width: f32, alt_text: String) -> Text3dSegment {
+ Text3dSegment::Image(Text3dImage {
+ handle: image,
+ width,
+ alt_text,
+ })
+ }
+
+ pub fn get_external_segment(&self) -> Option<Entity> {
+ match self {
+ Text3dSegment::Extract(entity) => Some(*entity),
+ Text3dSegment::SkipIf { condition, .. } => Some(*condition),
+ _ => None,
+ }
+ }
+}
+
+fn text_3d_on_remove(mut world: DeferredWorld, cx: HookContext) {
+ let Ok(entity) = world.get_entity(cx.entity) else {
+ return;
+ };
+ let Some(text) = entity.get::<Text3d>() else {
+ return;
+ };
+ let to_be_dropped: Vec<_> = text
+ .segments
+ .iter()
+ .filter_map(|x| x.0.get_external_segment())
+ .filter(|entity| {
+ world
+ .get_entity(*entity)
+ .is_ok_and(|e| !e.contains::<SharedSegment>())
+ })
+ .collect();
+ let mut commands = world.commands();
+ for entity in to_be_dropped {
+ commands.entity(entity).try_despawn();
+ }
+}
+
+impl Text3d {
+ /// Create a simple string without parsing.
+ ///
+ /// To parse rich text, see [`Text3d::parse`].
+ pub fn new(s: impl ToString) -> Self {
+ let string = s.to_string();
+ Self {
+ segments: vec![(Text3dSegment::String(string), Default::default())],
+ }
+ }
+
+ /// Create a [`Text3d`] with an empty string segment.
+ ///
+ /// To parse rich text, see [`Text3d::parse`].
+ pub fn new_empty() -> Self {
+ Self {
+ segments: vec![(Text3dSegment::String(String::new()), Default::default())],
+ }
+ }
+
+ /// Create a string from a [`FetchedTextSegment`](crate::FetchedTextSegment) on an entity.
+ pub fn from_extract(entity: Entity) -> Self {
+ Self {
+ segments: vec![(Text3dSegment::Extract(entity), Default::default())],
+ }
+ }
+
+ /// If only contains an owned segment, return that segment as a `&str`.
+ pub fn get_single(&self) -> Option<&str> {
+ if self.segments.len() != 1 {
+ None
+ } else if let Some((Text3dSegment::String(s), _)) = self.segments.first() {
+ Some(s)
+ } else {
+ None
+ }
+ }
+
+ /// If only contains an owned segment, return that segment mutably.
+ pub fn get_single_mut(&mut self) -> Option<&mut String> {
+ if self.segments.len() != 1 {
+ None
+ } else if let Some((Text3dSegment::String(s), _)) = self.segments.get_mut(0) {
+ Some(s)
+ } else {
+ None
+ }
+ }
+
+ /// If only contains an owned segment, set that segment to a value.
+ pub fn set_single(&mut self, value: &str) -> bool {
+ if self.segments.len() == 1
+ && let Some((Text3dSegment::String(s), _)) = self.segments.get_mut(0)
+ {
+ s.clear();
+ let _ = s.write_str(value);
+ true
+ } else {
+ false
+ }
+ }
+
+ /// If only contains an owned segment, return that segment mutably,
+ /// without triggering change detection.
+ pub fn map_single_mut<'a>(this: &'a mut Mut<Self>) -> Option<Mut<'a, String>> {
+ this.reborrow().filter_map_unchanged(Self::get_single_mut)
+ }
+
+ /// Obtain a segment from index.
+ pub fn get_segment_mut(&mut self, index: usize) -> Option<&mut String> {
+ if let Some((Text3dSegment::String(s), _)) = self.segments.get_mut(index) {
+ Some(s)
+ } else {
+ None
+ }
+ }
+
+ /// Obtain a segment from index without triggering change detection.
+ pub fn map_segment_mut<'a>(this: &'a mut Mut<Self>, index: usize) -> Option<Mut<'a, String>> {
+ this.reborrow()
+ .filter_map_unchanged(|v| Self::get_segment_mut(v, index))
+ }
+}
diff --git a/vendor/vendor.toml b/vendor/vendor.toml
index 7c6bdb67..68cfa063 100644
--- a/vendor/vendor.toml
+++ b/vendor/vendor.toml
@@ -172,6 +172,13 @@ kind = "patch"
reason = "frame-pure particles (raea #52): a new particle seeded by its spawn index, not the dead slot it recycles (vfx_init.wesl), and blended effects sorted by view depth from the main camera, far first as Bevy sorts its transparent phase, through the ribbons' sort pass (mod.rs, sort.rs, vfx_sort_fill.wesl); examples and GPU tests dropped; and no colon in a shader module's label (mod.rs's utils, the contract tests'), which DX12's DXC takes as a file name that names no file on Windows (raea #196)"
exit = "a hanabi with a deterministic mode (both changes offered upstream); then back to the git dependency and drop the copy"
+[bevy_rich_text3d]
+path = "vendor/bevy_rich_text3d"
+upstream = "crates.io:0.8.0"
+kind = "patch"
+reason = "a glyph that grows the atlas is drawn whole: tess_glyph read the atlas image's size before allocating, and the allocation that doubled the atlas's height left that glyph drawn into the old bounds, cut (raea docs/stage-guards.feature SG3); the examples left out"
+exit = "a bevy_rich_text3d release that reads the atlas's size after allocating; then back to the crates.io crate"
+
[usvg]
path = "vendor/usvg"
upstream = "crates.io:0.48.1"