mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 20:14:31 +01:00
Merge remote-tracking branch 'upstream/main' into next-sync-1124
# Conflicts: # .github/workflows/workspace.yml # Cargo.lock # crates/font-manager/Cargo.toml # crates/font-manager/README.md # crates/font-manager/src/lib.rs # crates/font-manager/src/panel/app.rs # crates/font-manager/src/panel/browse.rs # crates/font-manager/src/panel/details.rs # crates/font-manager/src/panel/faces.rs # crates/font-manager/src/panel/mod.rs # crates/font-manager/src/store.rs # crates/font-manager/tests/flows.rs # crates/font-store/src/language_packs.rs # crates/font-store/src/lib.rs # crates/font-store/src/store.rs # crates/font-store/src/tests.rs
This commit is contained in:
commit
2476d07bdd
116 files changed
+34597
-184
No files matched your search
+14
-3
@@ -12,9 +12,10 @@ author, source and license. Library code and original assets are under the repos
|
||||
| `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft contributors; generated by `craft_cms::synth::coated_cmyk` | [PhotoCraft `crates/cms`](https://github.com/storytold/photocraft/tree/b3222ee8e7e6bcb4799c37f904c595f20f9baf5e/crates/cms) | CC0-1.0 |
|
||||
| `crates/cms/profiles/craft-coated-fogra39.icc` | craft-libs contributors; generated by `crates/cms/tests/fogra39.rs` from the FOGRA39 data below | this repository | CC0-1.0 |
|
||||
| `crates/ppt-binary/tests/fixtures/old-talk.pps` | DeckCraft contributors; a one-slide PowerPoint 97-2003 show built from records by `crates/ppt-binary/src/tests.rs` (`the_pps_fixture_is_a_built_presentation`, with `CRAFT_WRITE_PPT_FIXTURE=1`); no PowerPoint involved | [storytold/deckcraft#1137](https://github.com/storytold/deckcraft/pull/1137) | CC0-1.0 |
|
||||
| `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
|
||||
| `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
|
||||
| `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
|
||||
| `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@995ef20](https://github.com/aiongg/craft-font-index/tree/995ef2000a0159d70da245e22cfa0797a0756ae8) | Apache-2.0 |
|
||||
| `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@995ef20](https://github.com/aiongg/craft-font-index/tree/995ef2000a0159d70da245e22cfa0797a0756ae8) | Apache-2.0 |
|
||||
| `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@995ef20](https://github.com/aiongg/craft-font-index/tree/995ef2000a0159d70da245e22cfa0797a0756ae8) | Apache-2.0 |
|
||||
| `crates/font-manager/tests/data/preview-vectors.json` (sample sentences) | Google Fonts `lang/` contributors; texts from the Universal Declaration of Human Rights via Eric Muller's UDHR in Unicode (translations' own terms not checked); the Iroha poem is public domain | [google/fonts `lang/`](https://github.com/google/fonts/tree/45e3d5269e4a17d823f6d84470bc084dc5ae46f6/lang) at `45e3d52` | Apache-2.0 |
|
||||
| `crates/cms/tests/data/FOGRA39.txt` (unmodified) | Fogra | [Fogra characterisation data](https://fogra.org/en/downloads/work-tools/characterisation-data), `FOGRA39_to_FOGRA60_v2.zip` | Fogra terms: free use and redistribution, unmodified, with Fogra identified as the source; "FOGRA39" identifies the reference data only and implies no certification, approval or endorsement by Fogra (full text in [NOTICE](NOTICE)) |
|
||||
| `vendor/linesweeper/tests/regression/`, `vendor/linesweeper/proptest-regressions/`, the `.snap` files under `vendor/linesweeper/src/` and the path data in `vendor/linesweeper/benches/painted_dreams.rs` (all unmodified; hashes in `vendor/linesweeper/SOURCE.json`) | As published in the package, whose manifest names Joe Neeman as author and records no other source | [linesweeper 0.5.0](https://crates.io/crates/linesweeper/0.5.0) | MIT OR Apache-2.0 (the package's `license` field) |
|
||||
| `crates/i18n/data/collation.postcard` | Unicode, Inc. (ICU 78.1 collation data, CLDR 48.2.1); generated by `crates/i18n/data/generate-collation.sh` | [ICU](https://github.com/unicode-org/icu/releases/tag/release-78.1rc) | Unicode-3.0 |
|
||||
@@ -189,3 +190,13 @@ Retained XFDF source contributors (move-aware blame): Brandon Thomas, Marco Arnu
|
||||
`crates/media-source/src/y4m.rs` adapts the in-house [FilmCraft Y4mSource at 3f137a7e](https://github.com/storytold/filmcraft/blob/3f137a7ed420cac79b32145f5243b7f98b31f71c/crates/codecs/src/y4m.rs), MIT OR Apache-2.0. Original playback by Lloyd Nicholson ([FilmCraft #1303](https://github.com/storytold/filmcraft/pull/1303)); shared-parser integration by Dylan M. Taylor ([FilmCraft #4862](https://github.com/storytold/filmcraft/pull/4862)). The adaptation changes source/frame types and declines payloads above the shared media allocation ceiling before playback. The parser and its previous header-safety work remain in `craft-y4m` ([craft-libs #933](https://github.com/storytold/craft-libs/pull/933)).
|
||||
|
||||
`crates/media-source/tests/it/y4m.rs` contains original repository-authored synthetic test data under MIT OR Apache-2.0: literal YUV samples and a sparse reader that reports only the length of an oversized frame. It does not use external media or decoder output.
|
||||
|
||||
## Material graph runtime
|
||||
|
||||
`crates/material-graph` moves the graph text format, parser, evaluator, pixel-program compiler, and tests from
|
||||
[TextureCraft's SPP importer at 22a37c29](https://github.com/vangel76/texturecraft/tree/22a37c29e98d8e6fc8c5e611e22f0ab95b83243d/crates/graph)
|
||||
(MIT OR Apache-2.0). [xilefenko introduced this runtime in TextureCraft](https://github.com/vangel76/texturecraft/commit/af862722be61bd7050ac782ec57a5e8938a5b017),
|
||||
adapting code from [PiJellyPin's MaterialCraft](https://github.com/PiJellyPin/MaterialCraft). See the crate's
|
||||
`NOTICE` for the original attribution. This extraction retains vangel76's subsequent evaluator and GPU work.
|
||||
The format reference and tests are from the same TextureCraft source. The tests' numerical rule tables document
|
||||
their provenance in their headers.
|
||||
Generated
+12
-1
@@ -1846,6 +1846,7 @@ dependencies = [
|
||||
"craft-lottie",
|
||||
"craft-macho",
|
||||
"craft-markdown",
|
||||
"craft-material-graph",
|
||||
"craft-materialx",
|
||||
"craft-math",
|
||||
"craft-mcmat",
|
||||
@@ -2754,7 +2755,9 @@ dependencies = [
|
||||
"epaint_default_fonts",
|
||||
"log",
|
||||
"serde",
|
||||
"skrifa 0.44.0",
|
||||
"serde_json",
|
||||
"skrifa 0.47.0",
|
||||
"wuff",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3229,6 +3232,14 @@ dependencies = [
|
||||
"craft-wordmodel",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-material-graph"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libm",
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-materialx"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -170,6 +170,7 @@ craft-math = { path = "crates/math" }
|
||||
craft-media = { path = "crates/media", default-features = false }
|
||||
craft-media-source = { path = "crates/media-source" }
|
||||
craft-materialx = { path = "crates/materialx" }
|
||||
craft-material-graph = { path = "crates/material-graph" }
|
||||
craft-media-testkit = { path = "crates/media-testkit" }
|
||||
craft-midi = { path = "crates/midi" }
|
||||
craft-sf2 = { path = "crates/sf2" }
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
//! name), `FilmCraft Frame Size` and `FilmCraft Audio Sample Rate` (on the composition).
|
||||
|
||||
mod ids;
|
||||
pub mod linked_audio;
|
||||
pub mod properties;
|
||||
mod read;
|
||||
pub(crate) mod store;
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
//! WAV/PCM FileDescriptor metadata, without loading a SourceMob or touching its locators.
|
||||
|
||||
use super::ids::{cls, pid};
|
||||
|
||||
/// The two audio descriptor classes commonly attached to an external WAV source.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DescriptorKind {
|
||||
Wave,
|
||||
Pcm,
|
||||
}
|
||||
|
||||
impl DescriptorKind {
|
||||
/// Classify a compound-file storage's CLSID in AAF on-disk AUID byte order
|
||||
/// (little-endian GUID fields, not RFC 4122/network order).
|
||||
pub fn from_auid_le(class: [u8; 16]) -> Option<Self> {
|
||||
match class {
|
||||
cls::WAVE_DESCRIPTOR => Some(Self::Wave),
|
||||
cls::PCM_DESCRIPTOR => Some(Self::Pcm),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One property from an already framed and caller-validated object.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DescriptorProperty<'a> {
|
||||
Missing,
|
||||
OtherForm,
|
||||
Data(&'a [u8]),
|
||||
}
|
||||
|
||||
/// Why a descriptor field is unavailable.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DescriptorFieldError {
|
||||
Missing,
|
||||
OtherForm,
|
||||
Truncated,
|
||||
}
|
||||
|
||||
/// A lazy descriptor view over a caller's property store. This neither opens
|
||||
/// the media file nor determines whether the AAF source is external.
|
||||
pub struct AudioFileDescriptor<F> {
|
||||
kind: DescriptorKind,
|
||||
property: F,
|
||||
}
|
||||
|
||||
impl<'a, F: Fn(u16) -> DescriptorProperty<'a>> AudioFileDescriptor<F> {
|
||||
/// Supply the property view for this class; the descriptor chooses AAF property IDs.
|
||||
pub fn new(kind: DescriptorKind, property: F) -> Self {
|
||||
Self { kind, property }
|
||||
}
|
||||
|
||||
/// `FileDescriptor::SampleRate` as the signed numerator and denominator on
|
||||
/// the wire. The caller's rational policy (including zero) is not applied.
|
||||
pub fn sample_rate(&self) -> Result<(i32, i32), DescriptorFieldError> {
|
||||
let [a, b, c, d, e, f, g, h] = self.bytes(pid::SAMPLE_RATE)?;
|
||||
Ok((i32::from_le_bytes([a, b, c, d]), i32::from_le_bytes([e, f, g, h])))
|
||||
}
|
||||
|
||||
/// `FileDescriptor::Length` in sample-rate units, before validating clip ranges.
|
||||
pub fn length(&self) -> Result<i64, DescriptorFieldError> {
|
||||
self.bytes(pid::FILE_LENGTH).map(i64::from_le_bytes)
|
||||
}
|
||||
|
||||
/// `SoundDescriptor::Channels` for a PCM descriptor. A WAVEDescriptor has
|
||||
/// no such declared count here; an absent PCM field is also left to the caller.
|
||||
pub fn pcm_channels(&self) -> Result<Option<u32>, DescriptorFieldError> {
|
||||
if self.kind == DescriptorKind::Wave {
|
||||
return Ok(None);
|
||||
}
|
||||
match self.bytes(pid::CHANNELS) {
|
||||
Ok(bytes) => Ok(Some(u32::from_le_bytes(bytes))),
|
||||
Err(DescriptorFieldError::Missing) => Ok(None),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
fn bytes<const N: usize>(&self, pid: u16) -> Result<[u8; N], DescriptorFieldError> {
|
||||
match (self.property)(pid) {
|
||||
DescriptorProperty::Data(data) => data.first_chunk().copied().ok_or(DescriptorFieldError::Truncated),
|
||||
DescriptorProperty::Missing => Err(DescriptorFieldError::Missing),
|
||||
DescriptorProperty::OtherForm => Err(DescriptorFieldError::OtherForm),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn descriptor_class_and_little_endian_fields_are_typed() {
|
||||
assert_eq!(DescriptorKind::from_auid_le([1, 1, 1, 13, 1, 1, 0, 0x48, 6, 14, 43, 52, 2, 6, 1, 1]), Some(DescriptorKind::Pcm));
|
||||
assert_eq!(DescriptorKind::from_auid_le(cls::WAVE_DESCRIPTOR), Some(DescriptorKind::Wave));
|
||||
assert_eq!(DescriptorKind::from_auid_le(cls::CDCI_DESCRIPTOR), None);
|
||||
let file = AudioFileDescriptor::new(DescriptorKind::Pcm, |tag| match tag {
|
||||
pid::SAMPLE_RATE => DescriptorProperty::Data(&[0x80, 0xbb, 0, 0, 1, 0, 0, 0]),
|
||||
pid::FILE_LENGTH => DescriptorProperty::Data(&[2, 1, 0, 0, 0, 0, 0, 0, 99]),
|
||||
pid::CHANNELS => DescriptorProperty::Data(&[2, 0, 0, 0]),
|
||||
_ => DescriptorProperty::Missing,
|
||||
});
|
||||
assert_eq!(file.sample_rate(), Ok((48000, 1)));
|
||||
assert_eq!(file.length(), Ok(258));
|
||||
assert_eq!(file.pcm_channels(), Ok(Some(2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn descriptor_fields_are_lazy_and_distinguish_missing_form_and_short_data() {
|
||||
let wave = AudioFileDescriptor::new(DescriptorKind::Wave, |tag| match tag {
|
||||
pid::SAMPLE_RATE => DescriptorProperty::OtherForm,
|
||||
pid::FILE_LENGTH => DescriptorProperty::Data(&[0; 7]),
|
||||
_ => panic!("unexpected field read"),
|
||||
});
|
||||
assert_eq!(wave.pcm_channels(), Ok(None));
|
||||
assert_eq!(wave.sample_rate(), Err(DescriptorFieldError::OtherForm));
|
||||
assert_eq!(wave.length(), Err(DescriptorFieldError::Truncated));
|
||||
let pcm = AudioFileDescriptor::new(DescriptorKind::Pcm, |_| DescriptorProperty::Missing);
|
||||
assert_eq!(pcm.pcm_channels(), Ok(None));
|
||||
assert_eq!(pcm.sample_rate(), Err(DescriptorFieldError::Missing));
|
||||
}
|
||||
}
|
||||
+229
-25
@@ -3,7 +3,7 @@
|
||||
//! orientation, SDK level…). Simple and complex (bag) entries, sparse and 16-bit offset tables.
|
||||
|
||||
use crate::Error;
|
||||
use crate::axml::{ResValue, StringPool, chunk};
|
||||
use crate::axml::{MAX_RETAINED_VALUE_BYTES, ResValue, StringPool, ValueBudget, chunk, report_partial_string_pool};
|
||||
use crate::bytes::Reader;
|
||||
use serde::Serialize;
|
||||
|
||||
@@ -21,14 +21,18 @@ const MAX_BAG: usize = 4096;
|
||||
pub struct Limits {
|
||||
/// Most entries decoded across all types and configurations.
|
||||
pub max_entries: usize,
|
||||
/// Most bytes retained in formatted simple-entry and bag values.
|
||||
pub max_value_bytes: usize,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Limits { max_entries: 2_000_000 }
|
||||
Limits { max_entries: 2_000_000, max_value_bytes: MAX_RETAINED_VALUE_BYTES }
|
||||
}
|
||||
}
|
||||
|
||||
const VALUE_BUDGET_WARNING: &str = "resource value budget reached; remaining values were omitted";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct TypeInfo {
|
||||
pub id: u8,
|
||||
@@ -300,30 +304,32 @@ pub fn parse(data: &[u8], limits: Limits) -> Result<Table, Error> {
|
||||
let r = Reader::new(data);
|
||||
let mut table = Table::default();
|
||||
let mut global = StringPool::default();
|
||||
let mut value_budget = ValueBudget::new(limits.max_value_bytes);
|
||||
let mut pos = h;
|
||||
while pos < size {
|
||||
let Some((ct, _ch, cs)) = chunk(&r, pos) else {
|
||||
table.truncated = true;
|
||||
table.warnings.push(format!("unreadable chunk at offset {pos}"));
|
||||
break;
|
||||
};
|
||||
match ct {
|
||||
crate::axml::RES_STRING_POOL => match StringPool::parse(data, pos) {
|
||||
Ok(p) => {
|
||||
if p.strings.len() < p.declared {
|
||||
table.truncated = true;
|
||||
table.warnings.push(format!("global string pool was capped at {} of {} strings", p.strings.len(), p.declared));
|
||||
}
|
||||
report_partial_string_pool(&p, "global string pool", &mut table.truncated, &mut table.warnings);
|
||||
table.global_strings = p.declared;
|
||||
global = p;
|
||||
}
|
||||
Err(e) => table.warnings.push(format!("global string pool: {e}")),
|
||||
Err(e) => {
|
||||
table.truncated = true;
|
||||
table.warnings.push(format!("global string pool: {e}"));
|
||||
}
|
||||
},
|
||||
RES_PACKAGE => {
|
||||
if table.packages.len() >= MAX_PACKAGES {
|
||||
table.truncated = true;
|
||||
table.warnings.push("too many packages; the rest were skipped".into());
|
||||
} else {
|
||||
parse_package(data, pos, cs, &global, &mut table, limits);
|
||||
parse_package(data, pos, cs, &global, &mut table, limits, &mut value_budget);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -336,14 +342,16 @@ pub fn parse(data: &[u8], limits: Limits) -> Result<Table, Error> {
|
||||
Ok(table)
|
||||
}
|
||||
|
||||
fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: &mut Table, limits: Limits) {
|
||||
fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: &mut Table, limits: Limits, value_budget: &mut ValueBudget) {
|
||||
let Some(data) = pos.checked_add(cs).and_then(|end| data.get(..end)) else {
|
||||
table.truncated = true;
|
||||
table.warnings.push("package runs past its resource table".into());
|
||||
return;
|
||||
};
|
||||
let r = Reader::new(data);
|
||||
let hsize = usize::from(r.u16_le(pos + 2).unwrap_or(0));
|
||||
if hsize < 284 {
|
||||
table.truncated = true;
|
||||
table.warnings.push(format!("package at offset {pos}: incomplete header"));
|
||||
return;
|
||||
}
|
||||
@@ -365,22 +373,17 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table:
|
||||
return StringPool::default();
|
||||
}
|
||||
let Some(start) = pos.checked_add(offset).filter(|&start| offset >= hsize && start < end) else {
|
||||
table.truncated = true;
|
||||
table.warnings.push(format!("package {name}: {label} string pool is outside its payload"));
|
||||
return StringPool::default();
|
||||
};
|
||||
match StringPool::parse(data, start) {
|
||||
Ok(pool) => {
|
||||
if pool.strings.len() < pool.declared {
|
||||
table.truncated = true;
|
||||
table.warnings.push(format!(
|
||||
"package {name}: {label} string pool was capped at {} of {} strings",
|
||||
pool.strings.len(),
|
||||
pool.declared
|
||||
));
|
||||
}
|
||||
report_partial_string_pool(&pool, &format!("package {name}: {label} string pool"), &mut table.truncated, &mut table.warnings);
|
||||
pool
|
||||
}
|
||||
Err(error) => {
|
||||
table.truncated = true;
|
||||
table.warnings.push(format!("package {name}: {label} string pool: {error}"));
|
||||
StringPool::default()
|
||||
}
|
||||
@@ -393,12 +396,14 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table:
|
||||
let mut c = pos.saturating_add(hsize.max(8));
|
||||
while c < end {
|
||||
let Some((ct, ch, sz)) = chunk(&r, c) else {
|
||||
table.truncated = true;
|
||||
table.warnings.push(format!("package {name}: unreadable chunk at offset {c}"));
|
||||
break;
|
||||
};
|
||||
// Each child was checked against its package; reads within it must also stop before
|
||||
// the next sibling, including fixed-width library records and bag headers.
|
||||
let Some(child) = data.get(..c.saturating_add(sz)) else {
|
||||
table.truncated = true;
|
||||
table.warnings.push(format!("package {name}: child chunk runs past its package"));
|
||||
break;
|
||||
};
|
||||
@@ -437,7 +442,7 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table:
|
||||
}
|
||||
}
|
||||
}
|
||||
parse_type(&r, c, (ch, sz), (cfg, locale), &p, tid, global, table, limits);
|
||||
parse_type(&r, c, (ch, sz), (cfg, locale), &p, tid, global, table, limits, value_budget);
|
||||
}
|
||||
(RES_TYPE_SPEC | RES_TYPE, None) if ch >= 16 => {
|
||||
table.truncated = true;
|
||||
@@ -449,6 +454,9 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table:
|
||||
if n > available {
|
||||
table.warnings.push(format!("package {name}: library records run past their chunk"));
|
||||
}
|
||||
if n > available.min(256) {
|
||||
table.truncated = true;
|
||||
}
|
||||
for i in 0..n.min(256).min(available) {
|
||||
let e = c + ch + i * 260;
|
||||
if let Some(lid) = r.u32_le(e) {
|
||||
@@ -457,6 +465,7 @@ fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table:
|
||||
}
|
||||
}
|
||||
(RES_TYPE_SPEC | RES_TYPE | RES_LIBRARY, _) => {
|
||||
table.truncated = true;
|
||||
table.warnings.push(format!("package {name}: incomplete chunk header at offset {c}"));
|
||||
}
|
||||
_ => {}
|
||||
@@ -480,6 +489,7 @@ fn parse_type(
|
||||
global: &StringPool,
|
||||
table: &mut Table,
|
||||
limits: Limits,
|
||||
value_budget: &mut ValueBudget,
|
||||
) {
|
||||
let tid = r.u8(c + 8).unwrap_or(0);
|
||||
let flags = r.u8(c + 9).unwrap_or(0);
|
||||
@@ -493,10 +503,12 @@ fn parse_type(
|
||||
let mut slots: Vec<(u32, usize)> = Vec::new();
|
||||
let table_bytes = if sparse || off16 { count.saturating_mul(if sparse { 4 } else { 2 }) } else { count.saturating_mul(4) };
|
||||
if c.saturating_add(ch).saturating_add(table_bytes) > end {
|
||||
table.truncated = true;
|
||||
table.warnings.push(format!("{tname} ({cfg}): entry table runs past its chunk"));
|
||||
return;
|
||||
}
|
||||
if count != 0 && (entries_start < ch.saturating_add(table_bytes) || entries_start > sz) {
|
||||
table.truncated = true;
|
||||
table.warnings.push(format!("{tname} ({cfg}): invalid entry data start"));
|
||||
return;
|
||||
}
|
||||
@@ -517,15 +529,16 @@ fn parse_type(
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut skipped = 0usize;
|
||||
for (idx, o) in slots {
|
||||
if table.entries.len() >= limits.max_entries {
|
||||
table.truncated = true;
|
||||
return;
|
||||
break;
|
||||
}
|
||||
let Some(e) = c.checked_add(entries_start).and_then(|x| x.checked_add(o)) else { continue };
|
||||
if e.saturating_add(8) > end {
|
||||
let Some(e) = c.checked_add(entries_start).and_then(|x| x.checked_add(o)).filter(|e| e.saturating_add(8) <= end) else {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let esize = usize::from(r.u16_le(e).unwrap_or(0));
|
||||
let eflags = r.u16_le(e + 2).unwrap_or(0);
|
||||
let id = (p.id << 24) | (u32::from(type_id) << 16) | (idx & 0xffff);
|
||||
@@ -546,7 +559,7 @@ fn parse_type(
|
||||
// Compact entry: key index in the size field, type in the high byte of flags.
|
||||
entry.key = p.keys.get(u32::from(r.u16_le(e).unwrap_or(0))).unwrap_or("").to_string();
|
||||
let v = ResValue { data_type: (eflags >> 8) as u8, data: r.u32_le(e + 4).unwrap_or(0) };
|
||||
entry.value = Some(v.format(global));
|
||||
entry.value = value_budget.take(v.format(global), &mut table.truncated, &mut table.warnings, VALUE_BUDGET_WARNING);
|
||||
entry.value_type = Some(v.type_name());
|
||||
entry.raw = Some(v);
|
||||
} else {
|
||||
@@ -579,21 +592,30 @@ fn parse_type(
|
||||
}
|
||||
let name = r.u32_le(m).unwrap_or(0);
|
||||
let v = ResValue { data_type: r.u8(m + 7).unwrap_or(0), data: r.u32_le(m + 8).unwrap_or(0) };
|
||||
entry.bag.push(BagItem { name: format!("@{name:#010x}"), value: v.format(global), value_type: v.type_name() });
|
||||
let value =
|
||||
value_budget.take(v.format(global), &mut table.truncated, &mut table.warnings, VALUE_BUDGET_WARNING).unwrap_or_default();
|
||||
entry.bag.push(BagItem { name: format!("@{name:#010x}"), value, value_type: v.type_name() });
|
||||
m += 12;
|
||||
}
|
||||
} else {
|
||||
let v_at = e.saturating_add(esize.max(8));
|
||||
if v_at.saturating_add(8) <= end {
|
||||
let v = ResValue { data_type: r.u8(v_at + 3).unwrap_or(0), data: r.u32_le(v_at + 4).unwrap_or(0) };
|
||||
entry.value = Some(v.format(global));
|
||||
entry.value = value_budget.take(v.format(global), &mut table.truncated, &mut table.warnings, VALUE_BUDGET_WARNING);
|
||||
entry.value_type = Some(v.type_name());
|
||||
entry.raw = Some(v);
|
||||
} else {
|
||||
table.truncated = true;
|
||||
table.warnings.push(format!("{tname} ({cfg}): incomplete value"));
|
||||
}
|
||||
}
|
||||
}
|
||||
table.entries.push(entry);
|
||||
}
|
||||
if skipped > 0 {
|
||||
table.truncated = true;
|
||||
table.warnings.push(format!("{tname} ({cfg}): {skipped} entries run past their chunk"));
|
||||
}
|
||||
}
|
||||
|
||||
impl Table {
|
||||
@@ -642,6 +664,30 @@ mod tests {
|
||||
assert_eq!(style.config, "night-xhdpi-v21");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skipped_type_chunks_and_entries_mark_the_table_partial() {
|
||||
let bytes = fx::resources_arsc();
|
||||
// The French type chunk: RES_TYPE, an 84-byte header, and "fr" in its configuration.
|
||||
let fr = (0..bytes.len() - 30).find(|&i| bytes[i..i + 4] == [0x01, 0x02, 84, 0] && &bytes[i + 28..i + 30] == b"fr").unwrap();
|
||||
let corrupt = |at: usize, value: u32| {
|
||||
let mut b = bytes.clone();
|
||||
b[at..at + 4].copy_from_slice(&value.to_le_bytes());
|
||||
parse(&b, Limits::default()).unwrap()
|
||||
};
|
||||
for (what, t) in [
|
||||
("entry table past its chunk", corrupt(fr + 12, 1000)),
|
||||
("invalid entry data start", corrupt(fr + 16, 0xffff)),
|
||||
("an entry past its chunk", corrupt(fr + 84, 0x1000)),
|
||||
// The second entry's header fits, but its value runs past the chunk.
|
||||
("a value past its chunk", corrupt(fr + 88, 24)),
|
||||
] {
|
||||
let french = t.entries.iter().filter(|e| e.locale == "fr" && e.value.is_some()).count();
|
||||
assert!(french < 2, "{what}: the corruption should lose a French value");
|
||||
assert!(t.truncated, "{what}: lost content must mark the table partial");
|
||||
assert!(!t.warnings.is_empty(), "{what}: lost content must be reported");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_locale_scripts_and_variants_keep_separate_keys() {
|
||||
let mut cfg = [0u8; 64];
|
||||
@@ -674,4 +720,162 @@ mod tests {
|
||||
assert_eq!(q, "es-rMX-land");
|
||||
assert_eq!(l, "es-rMX");
|
||||
}
|
||||
|
||||
fn le_u16(v: &mut Vec<u8>, x: u16) {
|
||||
v.extend_from_slice(&x.to_le_bytes());
|
||||
}
|
||||
|
||||
fn le_u32(v: &mut Vec<u8>, x: u32) {
|
||||
v.extend_from_slice(&x.to_le_bytes());
|
||||
}
|
||||
|
||||
fn type_spec(id: u8, entries: u32) -> Vec<u8> {
|
||||
let mut c = Vec::new();
|
||||
le_u16(&mut c, 0x0202);
|
||||
le_u16(&mut c, 16);
|
||||
le_u32(&mut c, 16 + 4 * entries);
|
||||
c.push(id);
|
||||
c.push(0);
|
||||
le_u16(&mut c, 0);
|
||||
le_u32(&mut c, entries);
|
||||
for _ in 0..entries {
|
||||
le_u32(&mut c, 0);
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
fn type_chunk(id: u8, entries: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut cfg = vec![0u8; 64];
|
||||
cfg[0] = 64;
|
||||
let header = 20 + cfg.len();
|
||||
let start = header + 4 * entries.len();
|
||||
let mut body = Vec::new();
|
||||
let mut offs = Vec::new();
|
||||
for e in entries {
|
||||
offs.push(body.len() as u32);
|
||||
body.extend_from_slice(e);
|
||||
}
|
||||
let mut c = Vec::new();
|
||||
le_u16(&mut c, 0x0201);
|
||||
le_u16(&mut c, header as u16);
|
||||
le_u32(&mut c, (start + body.len()) as u32);
|
||||
c.push(id);
|
||||
c.push(0);
|
||||
le_u16(&mut c, 0);
|
||||
le_u32(&mut c, entries.len() as u32);
|
||||
le_u32(&mut c, start as u32);
|
||||
c.extend_from_slice(&cfg);
|
||||
for o in offs {
|
||||
le_u32(&mut c, o);
|
||||
}
|
||||
c.extend(body);
|
||||
c
|
||||
}
|
||||
|
||||
fn table_with_entries(pool: &[&str], type_name: &str, keys: &[&str], entries: &[Vec<u8>]) -> Vec<u8> {
|
||||
let global = fx::string_pool(pool, true);
|
||||
let types = fx::string_pool(&[type_name], false);
|
||||
let key_pool = fx::string_pool(keys, false);
|
||||
let mut chunks = type_spec(1, entries.len() as u32);
|
||||
chunks.extend(type_chunk(1, entries));
|
||||
let header = 288usize;
|
||||
let mut pkg = Vec::new();
|
||||
le_u16(&mut pkg, 0x0200);
|
||||
le_u16(&mut pkg, header as u16);
|
||||
le_u32(&mut pkg, (header + types.len() + key_pool.len() + chunks.len()) as u32);
|
||||
le_u32(&mut pkg, 0x7f);
|
||||
pkg.extend(vec![0u8; 256]);
|
||||
le_u32(&mut pkg, header as u32);
|
||||
le_u32(&mut pkg, 1);
|
||||
le_u32(&mut pkg, (header + types.len()) as u32);
|
||||
le_u32(&mut pkg, keys.len() as u32);
|
||||
le_u32(&mut pkg, 0);
|
||||
pkg.extend(types);
|
||||
pkg.extend(key_pool);
|
||||
pkg.extend(chunks);
|
||||
let mut out = Vec::new();
|
||||
le_u16(&mut out, 0x0002);
|
||||
le_u16(&mut out, 12);
|
||||
le_u32(&mut out, (12 + global.len() + pkg.len()) as u32);
|
||||
le_u32(&mut out, 1);
|
||||
out.extend(global);
|
||||
out.extend(pkg);
|
||||
out
|
||||
}
|
||||
|
||||
fn simple_string_entry(key: u32, pool_index: u32) -> Vec<u8> {
|
||||
let mut e = Vec::new();
|
||||
le_u16(&mut e, 8);
|
||||
le_u16(&mut e, 0);
|
||||
le_u32(&mut e, key);
|
||||
le_u16(&mut e, 8);
|
||||
e.push(0);
|
||||
e.push(0x03);
|
||||
le_u32(&mut e, pool_index);
|
||||
e
|
||||
}
|
||||
|
||||
fn compact_string_entry(key: u16, pool_index: u32) -> Vec<u8> {
|
||||
let mut e = Vec::new();
|
||||
le_u16(&mut e, key);
|
||||
le_u16(&mut e, 0x0308);
|
||||
le_u32(&mut e, pool_index);
|
||||
e
|
||||
}
|
||||
|
||||
fn bag_string_entry(key: u32, pool_indices: &[u32]) -> Vec<u8> {
|
||||
let mut e = Vec::new();
|
||||
le_u16(&mut e, 16);
|
||||
le_u16(&mut e, 1);
|
||||
le_u32(&mut e, key);
|
||||
le_u32(&mut e, 0);
|
||||
le_u32(&mut e, pool_indices.len() as u32);
|
||||
for (i, idx) in pool_indices.iter().enumerate() {
|
||||
le_u32(&mut e, 0x0101_0000 + i as u32);
|
||||
le_u16(&mut e, 8);
|
||||
e.push(0);
|
||||
e.push(0x03);
|
||||
le_u32(&mut e, *idx);
|
||||
}
|
||||
e
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn value_budget_omits_long_copies_and_keeps_a_later_short_value() {
|
||||
let long = "x".repeat(16);
|
||||
let tight = Limits { max_value_bytes: 20, ..Limits::default() };
|
||||
let keys = ["a", "b", "c"];
|
||||
|
||||
let simple =
|
||||
table_with_entries(&[&long, "ok"], "string", &keys, &[simple_string_entry(0, 0), simple_string_entry(1, 0), simple_string_entry(2, 1)]);
|
||||
let complete = parse(&simple, Limits::default()).unwrap();
|
||||
assert!(!complete.truncated, "{:?}", complete.warnings);
|
||||
assert_eq!(complete.entries.iter().map(|e| e.value.as_deref()).collect::<Vec<_>>(), [Some(long.as_str()), Some(long.as_str()), Some("ok")]);
|
||||
|
||||
let partial = parse(&simple, tight).unwrap();
|
||||
assert!(partial.truncated);
|
||||
assert!(partial.warnings.iter().any(|w| w.contains("value budget")), "{:?}", partial.warnings);
|
||||
assert_eq!(partial.entries.iter().map(|e| e.value.as_deref()).collect::<Vec<_>>(), [Some(long.as_str()), None, Some("ok")]);
|
||||
|
||||
let compact = table_with_entries(
|
||||
&[&long, "ok"],
|
||||
"string",
|
||||
&keys,
|
||||
&[compact_string_entry(0, 0), compact_string_entry(1, 0), compact_string_entry(2, 1)],
|
||||
);
|
||||
let partial = parse(&compact, tight).unwrap();
|
||||
assert!(partial.truncated);
|
||||
assert!(partial.warnings.iter().any(|w| w.contains("value budget")), "{:?}", partial.warnings);
|
||||
assert_eq!(partial.entries.iter().map(|e| e.value.as_deref()).collect::<Vec<_>>(), [Some(long.as_str()), None, Some("ok")]);
|
||||
|
||||
let bag = table_with_entries(&[&long, "ok"], "style", &["theme"], &[bag_string_entry(0, &[0, 0, 1])]);
|
||||
let complete = parse(&bag, Limits::default()).unwrap();
|
||||
assert!(!complete.truncated, "{:?}", complete.warnings);
|
||||
assert_eq!(complete.entries[0].bag.iter().map(|i| i.value.as_str()).collect::<Vec<_>>(), [long.as_str(), long.as_str(), "ok"]);
|
||||
|
||||
let partial = parse(&bag, tight).unwrap();
|
||||
assert!(partial.truncated);
|
||||
assert!(partial.warnings.iter().any(|w| w.contains("value budget")), "{:?}", partial.warnings);
|
||||
assert_eq!(partial.entries[0].bag.iter().map(|i| i.value.as_str()).collect::<Vec<_>>(), [long.as_str(), "", "ok"]);
|
||||
}
|
||||
}
|
||||
+150
-19
@@ -20,8 +20,10 @@ const XML_RESOURCE_MAP: u16 = 0x0180;
|
||||
const MAX_STRINGS: usize = 1_000_000;
|
||||
/// Longest string kept (characters).
|
||||
const MAX_STRING: usize = 64 * 1024;
|
||||
/// Default budget for copied resource and XML values, and the base string-pool byte cap.
|
||||
pub(crate) const MAX_RETAINED_VALUE_BYTES: usize = 64 << 20;
|
||||
/// Base budget for decoded string bytes; larger chunks allow at most three times their size.
|
||||
const BASE_POOL_BYTES: usize = 64 << 20;
|
||||
const BASE_POOL_BYTES: usize = MAX_RETAINED_VALUE_BYTES;
|
||||
/// Most extra UTF-8 length candidates examined across one string pool.
|
||||
const MAX_RECOVERY_PROBES: usize = 65_536;
|
||||
/// Most XML nodes decoded.
|
||||
@@ -54,6 +56,8 @@ pub struct StringPool {
|
||||
pub utf8: bool,
|
||||
/// Strings the pool declared (may exceed `strings.len()` when capped).
|
||||
pub declared: usize,
|
||||
/// Entries left empty because the UTF-8 recovery probe budget ran out.
|
||||
pub recovery_omitted: usize,
|
||||
}
|
||||
|
||||
impl StringPool {
|
||||
@@ -104,12 +108,13 @@ impl StringPool {
|
||||
let strings_reader = Reader::new(string_bytes);
|
||||
let mut strings = Vec::with_capacity(count.min(MAX_STRINGS).min(65_536));
|
||||
let mut bytes_left = BASE_POOL_BYTES.max(size.saturating_mul(3));
|
||||
let mut recovery_omitted = 0;
|
||||
for i in 0..count.min(MAX_STRINGS) {
|
||||
let at = r.u32_le(hdr + i * 4).ok_or_else(|| Error::Truncated("string offsets".into()))? as usize;
|
||||
let s = if at >= string_bytes.len() {
|
||||
None
|
||||
} else if utf8 {
|
||||
utf8_string(&strings_reader, at, string_bytes.len(), recovery_left)
|
||||
utf8_string(&strings_reader, at, string_bytes.len(), recovery_left, &mut recovery_omitted)
|
||||
} else {
|
||||
utf16_string(&strings_reader, at, string_bytes.len())
|
||||
};
|
||||
@@ -120,7 +125,7 @@ impl StringPool {
|
||||
bytes_left -= s.len();
|
||||
strings.push(s);
|
||||
}
|
||||
Ok(StringPool { strings, utf8, declared: count })
|
||||
Ok(StringPool { strings, utf8, declared: count, recovery_omitted })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,7 +139,7 @@ fn utf8_len(r: &Reader<'_>, at: usize) -> Option<(usize, usize)> {
|
||||
}
|
||||
}
|
||||
|
||||
fn utf8_string(r: &Reader<'_>, at: usize, end: usize, recovery_left: &mut usize) -> Option<String> {
|
||||
fn utf8_string(r: &Reader<'_>, at: usize, end: usize, recovery_left: &mut usize, recovery_omitted: &mut usize) -> Option<String> {
|
||||
let (_chars, n1) = utf8_len(r, at)?;
|
||||
let (mut bytes, n2) = utf8_len(r, at.checked_add(n1)?)?;
|
||||
let start = at.checked_add(n1 + n2)?;
|
||||
@@ -146,7 +151,11 @@ fn utf8_string(r: &Reader<'_>, at: usize, end: usize, recovery_left: &mut usize)
|
||||
}
|
||||
// The declared candidate costs one read per entry, already bounded by MAX_STRINGS.
|
||||
if bytes >= 0x8000 {
|
||||
*recovery_left = recovery_left.checked_sub(1)?;
|
||||
if *recovery_left == 0 {
|
||||
*recovery_omitted += 1;
|
||||
return None;
|
||||
}
|
||||
*recovery_left -= 1;
|
||||
}
|
||||
if r.u8(terminator)? == 0 {
|
||||
break;
|
||||
@@ -173,6 +182,56 @@ fn utf16_string(r: &Reader<'_>, at: usize, end: usize) -> Option<String> {
|
||||
Some(String::from_utf16_lossy(&units))
|
||||
}
|
||||
|
||||
/// Record that a string pool was capped or omitted recovery entries.
|
||||
pub(crate) fn report_partial_string_pool(pool: &StringPool, prefix: &str, truncated: &mut bool, warnings: &mut Vec<String>) {
|
||||
if pool.strings.len() < pool.declared {
|
||||
*truncated = true;
|
||||
warnings.push(format!("{prefix} was capped at {} of {} strings", pool.strings.len(), pool.declared));
|
||||
}
|
||||
if pool.recovery_omitted > 0 {
|
||||
*truncated = true;
|
||||
warnings.push(format!("{prefix} omitted {} strings after the UTF-8 recovery budget was exhausted", pool.recovery_omitted));
|
||||
}
|
||||
}
|
||||
|
||||
/// Charge `value` against a retained-byte budget. When it does not fit, report truncation once
|
||||
/// and return `None`, so a later shorter value can still be kept.
|
||||
pub(crate) fn retain_value(
|
||||
left: &mut usize,
|
||||
value: String,
|
||||
truncated: &mut bool,
|
||||
warned: &mut bool,
|
||||
warnings: &mut Vec<String>,
|
||||
warning: &str,
|
||||
) -> Option<String> {
|
||||
if value.len() > *left {
|
||||
if !*warned {
|
||||
warnings.push(warning.to_string());
|
||||
*warned = true;
|
||||
}
|
||||
*truncated = true;
|
||||
None
|
||||
} else {
|
||||
*left -= value.len();
|
||||
Some(value)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct ValueBudget {
|
||||
left: usize,
|
||||
warned: bool,
|
||||
}
|
||||
|
||||
impl ValueBudget {
|
||||
pub(crate) fn new(max_bytes: usize) -> Self {
|
||||
Self { left: max_bytes, warned: false }
|
||||
}
|
||||
|
||||
pub(crate) fn take(&mut self, value: String, truncated: &mut bool, warnings: &mut Vec<String>, warning: &str) -> Option<String> {
|
||||
retain_value(&mut self.left, value, truncated, &mut self.warned, warnings, warning)
|
||||
}
|
||||
}
|
||||
|
||||
/// A typed value (`Res_value`): data type and 32-bit data.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
pub struct ResValue {
|
||||
@@ -313,10 +372,10 @@ pub fn framework_attr(id: u32) -> Option<&'static str> {
|
||||
|
||||
/// Decode a binary XML file.
|
||||
pub fn parse(data: &[u8]) -> Result<Document, Error> {
|
||||
parse_with_limits(data, MAX_NODES, MAX_DEPTH)
|
||||
parse_with_limits(data, MAX_NODES, MAX_DEPTH, MAX_RETAINED_VALUE_BYTES)
|
||||
}
|
||||
|
||||
fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result<Document, Error> {
|
||||
fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize, max_value_bytes: usize) -> Result<Document, Error> {
|
||||
let r = Reader::new(data);
|
||||
let (t, h, size) = chunk(&r, 0).ok_or_else(|| Error::Truncated("binary XML header".into()))?;
|
||||
if t != RES_XML {
|
||||
@@ -329,6 +388,7 @@ fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result<
|
||||
let mut pos = h;
|
||||
let mut depth = 0usize;
|
||||
let mut ns_stack: Vec<(String, String)> = Vec::new();
|
||||
let mut value_budget = ValueBudget::new(max_value_bytes);
|
||||
while pos < size {
|
||||
let Some((ct, ch, cs)) = chunk(&r, pos) else {
|
||||
doc.truncated = true;
|
||||
@@ -354,10 +414,7 @@ fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result<
|
||||
match ct {
|
||||
RES_STRING_POOL => match StringPool::parse(data, pos) {
|
||||
Ok(p) => {
|
||||
if p.strings.len() < p.declared {
|
||||
doc.truncated = true;
|
||||
doc.warnings.push(format!("string pool was capped at {} of {} strings", p.strings.len(), p.declared));
|
||||
}
|
||||
report_partial_string_pool(&p, "string pool", &mut doc.truncated, &mut doc.warnings);
|
||||
doc.pool = p;
|
||||
}
|
||||
Err(e) => doc.warnings.push(format!("string pool: {e}")),
|
||||
@@ -431,6 +488,9 @@ fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result<
|
||||
} else {
|
||||
raw.format(&doc.pool)
|
||||
};
|
||||
let value = value_budget
|
||||
.take(value, &mut doc.truncated, &mut doc.warnings, "XML value budget reached; remaining values were omitted")
|
||||
.unwrap_or_default();
|
||||
attributes.push(Attribute {
|
||||
namespace: ans,
|
||||
name: aname,
|
||||
@@ -450,6 +510,9 @@ fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result<
|
||||
}
|
||||
XML_CDATA => {
|
||||
let text = r.u32_le(pos + ch).and_then(|i| doc.pool.get(i)).unwrap_or("").to_string();
|
||||
let text = value_budget
|
||||
.take(text, &mut doc.truncated, &mut doc.warnings, "XML value budget reached; remaining values were omitted")
|
||||
.unwrap_or_default();
|
||||
doc.nodes.push(Node::Text { depth, text });
|
||||
}
|
||||
_ => {}
|
||||
@@ -639,6 +702,7 @@ mod tests {
|
||||
assert_eq!(parsed.get(1), parsed.get(0));
|
||||
assert_eq!(parsed.get(2), Some(""));
|
||||
assert_eq!(parsed.get(3), Some("ok"));
|
||||
assert_eq!(parsed.recovery_omitted, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -655,6 +719,7 @@ mod tests {
|
||||
assert_eq!(parsed.get(1).map(str::len), Some(0x8000));
|
||||
assert_eq!(parsed.get(2), Some(""));
|
||||
assert_eq!(parsed.get(3), Some("ok"));
|
||||
assert_eq!(parsed.recovery_omitted, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -670,6 +735,7 @@ mod tests {
|
||||
assert_eq!(left, remaining);
|
||||
assert_eq!(parsed.get(0).map(str::len), Some(length));
|
||||
assert_eq!(parsed.get(1), Some("ok"));
|
||||
assert_eq!(parsed.recovery_omitted, usize::from(length == 0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -681,10 +747,10 @@ mod tests {
|
||||
assert_eq!(left, 7);
|
||||
assert_eq!(parsed.get(0), Some(""));
|
||||
assert_eq!(parsed.get(1), Some("ok"));
|
||||
assert_eq!(parsed.recovery_omitted, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_pool_budget_stops_repeated_recovery_before_later_long_strings() {
|
||||
fn utf8_recovery_exhausted_pool() -> (Vec<u8>, usize) {
|
||||
let mut strings = vec![b'x'; 2 * 0x8000 + 16];
|
||||
strings[..4].copy_from_slice(&[0x80, 0, 0x80, 0]);
|
||||
let long = append_legacy_ascii(&mut strings, 0x8000);
|
||||
@@ -694,13 +760,78 @@ mod tests {
|
||||
let repeated = MAX_RECOVERY_PROBES / 3 + 1;
|
||||
let mut offsets = vec![0; repeated];
|
||||
offsets.extend([long, short]);
|
||||
let data = pool_with_offsets(&offsets, &strings);
|
||||
(pool_with_offsets(&offsets, &strings), repeated)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_pool_budget_stops_repeated_recovery_before_later_long_strings() {
|
||||
let (data, repeated) = utf8_recovery_exhausted_pool();
|
||||
let parsed = StringPool::parse(&data, 0).unwrap();
|
||||
assert_eq!(parsed.declared, repeated + 2);
|
||||
assert_eq!(parsed.strings.len(), repeated + 2);
|
||||
assert!(parsed.strings[..repeated].iter().all(String::is_empty));
|
||||
assert_eq!(parsed.get(repeated as u32), Some(""));
|
||||
assert_eq!(parsed.get((repeated + 1) as u32), Some("ok"));
|
||||
assert!(parsed.recovery_omitted > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xml_and_resource_tables_disclose_recovery_omissions() {
|
||||
let (pool, repeated) = utf8_recovery_exhausted_pool();
|
||||
let short_index = (repeated + 1) as u32;
|
||||
{
|
||||
let doc = parse(&pool_container(RES_XML, 8, &pool)).unwrap();
|
||||
assert!(doc.truncated);
|
||||
assert!(doc.warnings.iter().any(|w| w.contains("string pool") && w.contains("UTF-8 recovery budget")));
|
||||
assert_eq!(doc.pool.get(short_index), Some("ok"));
|
||||
assert!(doc.pool.recovery_omitted > 0);
|
||||
}
|
||||
let table = crate::arsc::parse(&pool_container(2, 12, &pool), crate::arsc::Limits::default()).unwrap();
|
||||
assert!(table.truncated);
|
||||
assert!(table.warnings.iter().any(|w| w.contains("global string pool") && w.contains("UTF-8 recovery budget")));
|
||||
for (field, label) in [(268, "type"), (276, "key")] {
|
||||
let mut package = pool_container(0x0200, 288, &pool);
|
||||
package[8..12].copy_from_slice(&0x7fu32.to_le_bytes());
|
||||
package[field..field + 4].copy_from_slice(&288u32.to_le_bytes());
|
||||
let table = crate::arsc::parse(&pool_container(2, 12, &package), crate::arsc::Limits::default()).unwrap();
|
||||
assert!(table.truncated, "{label}");
|
||||
assert!(
|
||||
table.warnings.iter().any(|w| w.contains(&format!("{label} string pool")) && w.contains("UTF-8 recovery budget")),
|
||||
"{label}: {:?}",
|
||||
table.warnings
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xml_value_budget_omits_long_copies_and_keeps_a_later_short_value() {
|
||||
let long = "x".repeat(16);
|
||||
let attrs = vec![
|
||||
fx::AxAttr { name: "a", res_id: None, val: fx::AxVal::Str(&long) },
|
||||
fx::AxAttr { name: "b", res_id: None, val: fx::AxVal::Str(&long) },
|
||||
fx::AxAttr { name: "c", res_id: None, val: fx::AxVal::Str("ok") },
|
||||
];
|
||||
let bytes = fx::axml(&[fx::AxNode::Start("root", attrs), fx::AxNode::End("root")]);
|
||||
let complete = parse(&bytes).unwrap();
|
||||
assert!(!complete.truncated);
|
||||
let Node::Start { attributes, .. } = complete.nodes.iter().find(|n| matches!(n, Node::Start { name, .. } if name == "root")).unwrap() else {
|
||||
panic!("expected the root start");
|
||||
};
|
||||
assert_eq!(
|
||||
attributes.iter().map(|a| (a.name.as_str(), a.value.as_str())).collect::<Vec<_>>(),
|
||||
[("a", long.as_str()), ("b", long.as_str()), ("c", "ok")]
|
||||
);
|
||||
|
||||
let partial = parse_with_limits(&bytes, MAX_NODES, MAX_DEPTH, 20).unwrap();
|
||||
assert!(partial.truncated);
|
||||
assert!(partial.warnings.iter().any(|w| w.contains("value budget")));
|
||||
let Node::Start { attributes, .. } = partial.nodes.iter().find(|n| matches!(n, Node::Start { name, .. } if name == "root")).unwrap() else {
|
||||
panic!("expected the root start");
|
||||
};
|
||||
assert_eq!(
|
||||
attributes.iter().map(|a| (a.name.as_str(), a.value.as_str())).collect::<Vec<_>>(),
|
||||
[("a", long.as_str()), ("b", ""), ("c", "ok")]
|
||||
);
|
||||
}
|
||||
|
||||
fn chunk_at(data: &[u8], kind: u16) -> usize {
|
||||
@@ -757,11 +888,11 @@ mod tests {
|
||||
#[test]
|
||||
fn dropping_a_close_event_marks_the_document_partial() {
|
||||
let bytes = fx::axml(&[fx::AxNode::Start("root", vec![]), fx::AxNode::End("root")]);
|
||||
let complete = parse_with_limits(&bytes, 3, 1).unwrap();
|
||||
let complete = parse_with_limits(&bytes, 3, 1, MAX_RETAINED_VALUE_BYTES).unwrap();
|
||||
assert!(!complete.truncated);
|
||||
assert!(matches!(complete.nodes.last(), Some(Node::End { depth: 0, .. })));
|
||||
|
||||
let partial = parse_with_limits(&bytes, 2, 1).unwrap();
|
||||
let partial = parse_with_limits(&bytes, 2, 1, MAX_RETAINED_VALUE_BYTES).unwrap();
|
||||
assert!(partial.truncated);
|
||||
assert_eq!(partial.nodes, complete.nodes[..2]);
|
||||
}
|
||||
@@ -770,19 +901,19 @@ mod tests {
|
||||
fn nesting_limit_keeps_an_exact_prefix_instead_of_saturating_depth() {
|
||||
let bytes =
|
||||
fx::axml(&[fx::AxNode::Start("root", vec![]), fx::AxNode::Start("child", vec![]), fx::AxNode::End("child"), fx::AxNode::End("root")]);
|
||||
let complete = parse_with_limits(&bytes, 5, 2).unwrap();
|
||||
let complete = parse_with_limits(&bytes, 5, 2, MAX_RETAINED_VALUE_BYTES).unwrap();
|
||||
assert!(!complete.truncated);
|
||||
assert!(matches!(complete.nodes[3], Node::End { depth: 1, .. }));
|
||||
assert!(matches!(complete.nodes[4], Node::End { depth: 0, .. }));
|
||||
|
||||
let partial = parse_with_limits(&bytes, 5, 1).unwrap();
|
||||
let partial = parse_with_limits(&bytes, 5, 1, MAX_RETAINED_VALUE_BYTES).unwrap();
|
||||
assert!(partial.truncated);
|
||||
assert_eq!(partial.nodes, complete.nodes[..2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_format() {
|
||||
let p = StringPool { strings: vec!["x".into()], utf8: false, declared: 1 };
|
||||
let p = StringPool { strings: vec!["x".into()], utf8: false, declared: 1, recovery_omitted: 0 };
|
||||
assert_eq!(ResValue { data_type: 0x05, data: (16 << 8) | 1 }.format(&p), "16dp");
|
||||
assert_eq!(ResValue { data_type: 0x12, data: 0xffff_ffff }.format(&p), "true");
|
||||
assert_eq!(ResValue { data_type: 0x1c, data: 0xff00_ff00 }.format(&p), "#ff00ff00");
|
||||
|
||||
@@ -109,6 +109,7 @@ craft-kra = { workspace = true, optional = true }
|
||||
craft-latex = { workspace = true, optional = true }
|
||||
craft-lottie = { workspace = true, optional = true }
|
||||
craft-markdown = { workspace = true, optional = true }
|
||||
craft-material-graph = { workspace = true, optional = true }
|
||||
craft-materialx = { workspace = true, optional = true }
|
||||
craft-math = { workspace = true, optional = true }
|
||||
craft-mesh = { workspace = true, optional = true }
|
||||
@@ -609,6 +610,8 @@ macho-serde = ["macho", "craft-macho/serde"]
|
||||
|
||||
markdown = ["dep:craft-markdown"]
|
||||
|
||||
material-graph = ["dep:craft-material-graph"]
|
||||
|
||||
materialx = ["dep:craft-materialx"]
|
||||
|
||||
math = ["dep:craft-math"]
|
||||
|
||||
@@ -221,6 +221,8 @@ pub use craft_lottie as lottie;
|
||||
pub use craft_macho as macho;
|
||||
#[cfg(feature = "markdown")]
|
||||
pub use craft_markdown as markdown;
|
||||
#[cfg(feature = "material-graph")]
|
||||
pub use craft_material_graph as material_graph;
|
||||
#[cfg(feature = "materialx")]
|
||||
pub use craft_materialx as materialx;
|
||||
#[cfg(feature = "math")]
|
||||
|
||||
@@ -67,10 +67,10 @@ mod whites_blacks;
|
||||
|
||||
pub use local_tone::{LocalTone, ToneKind, TonePass};
|
||||
pub use per_pixel::{
|
||||
CURVE_LUT, Grade, Grain, PerPixel, Vignette, VignetteStyle, WB_STEPS, WhitesBlacks, WhitesBlacksModel, per_pixel, spatial, white_black_points,
|
||||
whites_blacks_model,
|
||||
CURVE_LUT, Grade, Grain, PerPixel, Vignette, VignetteStyle, WB_STEPS, WhitesBlacks, WhitesBlacksModel, per_pixel, spatial, spatial_tone,
|
||||
white_black_points, whites_blacks_model,
|
||||
};
|
||||
pub use spatial::{Clarity, Dehaze, Texture};
|
||||
pub use spatial::{Clarity, Dehaze, Detail, Texture};
|
||||
|
||||
/// How the pixels encode light: the sRGB curve (gamma 0) or a pure power law (ProPhoto's 1.8,
|
||||
/// Adobe RGB's 2.2). The tone controls work on light, so the document's own curve decodes it.
|
||||
@@ -243,6 +243,7 @@ fn box_mean(v: &[f32], w: usize, h: usize, r: usize) -> Vec<f32> {
|
||||
}
|
||||
|
||||
/// Approximate Gaussian (three box passes).
|
||||
#[cfg(test)]
|
||||
fn gauss(v: &[f32], w: usize, h: usize, sigma: f32) -> Vec<f32> {
|
||||
box_means(v, w, h, &spatial::gauss_radii(sigma))
|
||||
}
|
||||
@@ -484,7 +485,6 @@ pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: &
|
||||
if px.is_empty() || p.is_identity() {
|
||||
return;
|
||||
}
|
||||
let ps = inputs.pixel_scale.clamp(0.01, 1.0);
|
||||
// 1. White balance + exposure in linear light.
|
||||
if let Some(g) = per_pixel::gains(p) {
|
||||
par_rows(px, w, 1, |_, row| {
|
||||
@@ -629,8 +629,8 @@ pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: &
|
||||
});
|
||||
}
|
||||
// 8. Detail.
|
||||
if p.noise_luminance > 0.0 || p.noise_color > 0.0 || p.sharpen_amount > 0.0 {
|
||||
detail(px, w, h, p, ps);
|
||||
if let Some(d) = Detail::new(p, inputs) {
|
||||
detail(px, w, h, &d);
|
||||
}
|
||||
// 9. Effects.
|
||||
if p.vignette_amount != 0.0 {
|
||||
@@ -843,54 +843,41 @@ fn sharpening_detail(detail: f32) -> f32 {
|
||||
detail / 100.0
|
||||
}
|
||||
|
||||
fn detail(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, ps: f32) {
|
||||
// The controls' documented 0..=100 range: raw values drive the filter radii below.
|
||||
let [nl, nld, nc, ncd] = [p.noise_luminance, p.noise_luminance_detail, p.noise_color, p.noise_color_detail].map(|v| v.clamp(0.0, 100.0));
|
||||
fn detail(px: &mut [[f32; 4]], w: usize, h: usize, d: &Detail) {
|
||||
// Work in Y + chroma (BT.709 luma, B−Y, R−Y).
|
||||
let mut y: Vec<f32> = px.iter().map(|q| luma([q[0], q[1], q[2]])).collect();
|
||||
let mut cb: Vec<f32> = px.iter().zip(&y).map(|(q, l)| q[2] - l).collect();
|
||||
let mut cr: Vec<f32> = px.iter().zip(&y).map(|(q, l)| q[0] - l).collect();
|
||||
if nl > 0.0 {
|
||||
let n = nl / 100.0;
|
||||
let r = ((1.0 + 3.0 * n) * ps).round().max(1.0) as usize;
|
||||
let smooth = guided(&y, &y, w, h, r, (n * 0.06).powi(2) + 1e-6);
|
||||
let keep = nld / 100.0 * 0.5;
|
||||
if let Some(n) = &d.luminance {
|
||||
let smooth = guided(&y, &y, w, h, n.radius, n.eps);
|
||||
for i in 0..w * h {
|
||||
y[i] = smooth[i] + (y[i] - smooth[i]) * keep;
|
||||
y[i] = smooth[i] + (y[i] - smooth[i]) * n.keep;
|
||||
}
|
||||
}
|
||||
if nc > 0.0 {
|
||||
let sigma = (nc / 100.0 * 6.0 * ps).max(0.3);
|
||||
let (bcb, bcr) = (gauss(&cb, w, h, sigma), gauss(&cr, w, h, sigma));
|
||||
let keep = ncd / 100.0 * 0.3;
|
||||
if let Some(c) = &d.color {
|
||||
let (bcb, bcr) = (box_means(&cb, w, h, &c.radii), box_means(&cr, w, h, &c.radii));
|
||||
for i in 0..w * h {
|
||||
cb[i] = bcb[i] + (cb[i] - bcb[i]) * keep;
|
||||
cr[i] = bcr[i] + (cr[i] - bcr[i]) * keep;
|
||||
cb[i] = bcb[i] + (cb[i] - bcb[i]) * c.keep;
|
||||
cr[i] = bcr[i] + (cr[i] - bcr[i]) * c.keep;
|
||||
}
|
||||
}
|
||||
if p.sharpen_amount > 0.0 {
|
||||
let sigma = (p.sharpen_radius.clamp(0.5, 3.0) * ps).max(0.3);
|
||||
let blur = gauss(&y, w, h, sigma);
|
||||
if let Some(s) = &d.sharpen {
|
||||
let blur = box_means(&y, w, h, &s.radii);
|
||||
// Masking: an edge mask from the gradient of a smoothed luminance.
|
||||
let mask: Option<Vec<f32>> = (p.sharpen_masking > 0.0).then(|| {
|
||||
let s = gauss(&y, w, h, 1.0 * ps.max(0.5));
|
||||
let t = p.sharpen_masking / 100.0 * 0.08;
|
||||
let mask: Option<Vec<f32>> = s.mask.as_ref().map(|(radii, [e0, e1])| {
|
||||
let s = box_means(&y, w, h, radii);
|
||||
util::par_map(w * h, |i| {
|
||||
let (x, yy) = (i % w, i / w);
|
||||
let gx = s[yy * w + (x + 1).min(w - 1)] - s[yy * w + x.saturating_sub(1)];
|
||||
let gy = s[(yy + 1).min(h - 1) * w + x] - s[yy.saturating_sub(1) * w + x];
|
||||
smoothstep(t * 0.5, t + 1e-4, gx.hypot(gy))
|
||||
smoothstep(*e0, *e1, gx.hypot(gy))
|
||||
})
|
||||
});
|
||||
let amt = p.sharpen_amount / 100.0 * 1.2;
|
||||
let det = sharpening_detail(p.sharpen_detail);
|
||||
for i in 0..w * h {
|
||||
let hp = y[i] - blur[i];
|
||||
// Low Detail damps large (halo-producing) differences.
|
||||
let limit = 0.03 + det * 0.3;
|
||||
let hp = hp.clamp(-limit, limit) * (0.5 + 0.5 * det);
|
||||
let hp = (y[i] - blur[i]).clamp(-s.limit, s.limit) * s.scale;
|
||||
let m = mask.as_ref().map_or(1.0, |m| m[i]);
|
||||
y[i] += amt * hp * m;
|
||||
y[i] += s.amount * hp * m;
|
||||
}
|
||||
}
|
||||
for i in 0..w * h {
|
||||
@@ -1204,6 +1191,23 @@ mod tests {
|
||||
assert!(per_pixel(&cr! { exposure: 0.5}, 2, 2, false, None).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detail_reaches_the_per_pixel_stages_after_measured_whites_and_blacks() {
|
||||
// Detail runs after Whites and Blacks, so another implementation can take its parameters
|
||||
// and still measure the points on the per-pixel image.
|
||||
let sharpened = cr! { sharpen_amount: 60.0, noise_luminance: 30.0, whites: 20.0};
|
||||
let stages = per_pixel(&sharpened, 8, 8, false, Some((0.05, 0.9))).expect("Detail alone stays on the per-pixel stages");
|
||||
assert_eq!(stages.detail, Detail::new(&sharpened, &DevelopInputs::default()));
|
||||
assert!(stages.detail.is_some() && stages.whites_blacks.is_some() && stages.measure_whites_blacks.is_none());
|
||||
let px = vec![[0.4f32, 0.5, 0.6, 1.0]; 64];
|
||||
assert!(white_black_points(&px, 8, 8, &sharpened, &DevelopInputs::default()).is_some());
|
||||
// A stage before Whites and Blacks still leaves the measuring to whatever runs it.
|
||||
let clarified = cr!(sharpened.clone() => clarity: 30.0);
|
||||
assert!(white_black_points(&px, 8, 8, &clarified, &DevelopInputs::default()).is_none());
|
||||
assert!(per_pixel(&clarified, 8, 8, false, None).is_some_and(|s| s.measure_whites_blacks.is_some()));
|
||||
assert!(spatial(&sharpened) && !spatial_tone(&sharpened) && spatial_tone(&clarified));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calibration_turns_primaries_keeps_neutrals_and_tints_shadows() {
|
||||
let w = calibration_weights(0.0);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
//! Develop's stages resolved for one image: every constant and table the per-pixel ones use, so
|
||||
//! another implementation of them (the GPU preview, `photocraft_gpu::CameraRawDevelop`) runs the
|
||||
//! same maths. [`develop`](super::develop) builds its own constants with the same functions.
|
||||
//! The spatial stages other than Detail come as their parameters: Dehaze, Clarity and Texture
|
||||
//! (see [`spatial`](super::spatial)), Shadows and Highlights as a [`LocalTone`].
|
||||
//! The spatial stages come as their parameters: Dehaze, Clarity, Texture and Detail (see
|
||||
//! [`spatial`](super::spatial)), Shadows and Highlights as a [`LocalTone`].
|
||||
|
||||
use super::local_tone::{LocalTone, WORK_SIDE};
|
||||
use super::spatial::{Clarity, Dehaze, Texture};
|
||||
use super::spatial::{Clarity, Dehaze, Detail, Texture};
|
||||
use super::types::VignetteStyle as StoredStyle;
|
||||
use super::{
|
||||
CameraRaw, DevelopInputs, Encoding, Wheel, calibration_neutral, curve_lut, grade_neutral, hsl_neutral, hsv_to_rgb, is_linear, luma,
|
||||
@@ -177,7 +177,7 @@ pub struct PerPixel {
|
||||
/// 3b. Whites and Blacks, in the document's encoding.
|
||||
pub whites_blacks: Option<WhitesBlacks>,
|
||||
/// 3b. Whites and Blacks to measure the image's points for (the sliders, −100 … 100), when a
|
||||
/// spatial stage is set: the points then depend on its output, so whatever runs it
|
||||
/// spatial stage before them is set (any but Detail): the points then depend on its output, so whatever runs it
|
||||
/// measures them and picks the curves from [`whites_blacks_model`]. `whites_blacks` is
|
||||
/// then `None`.
|
||||
pub measure_whites_blacks: Option<[f32; 2]>,
|
||||
@@ -193,6 +193,8 @@ pub struct PerPixel {
|
||||
pub hsl: Option<[[f32; 8]; 3]>,
|
||||
/// 7. Color Grading.
|
||||
pub grade: Option<Grade>,
|
||||
/// 8. Detail: noise reduction and sharpening.
|
||||
pub detail: Option<Detail>,
|
||||
/// 9. Vignette.
|
||||
pub vignette: Option<Vignette>,
|
||||
/// 9. Grain.
|
||||
@@ -204,20 +206,22 @@ pub struct PerPixel {
|
||||
/// Whether developing needs a stage that reads neighbouring pixels: Dehaze, Shadows and
|
||||
/// Highlights, Texture, Clarity, sharpening or noise reduction.
|
||||
pub fn spatial(p: &CameraRaw) -> bool {
|
||||
p.dehaze != 0.0 || [p.highlights, p.shadows, p.texture, p.clarity].iter().any(|v| *v != 0.0) || detail_on(p)
|
||||
spatial_tone(p) || p.sharpen_amount > 0.0 || p.noise_luminance > 0.0 || p.noise_color > 0.0
|
||||
}
|
||||
|
||||
/// Whether developing needs Detail: sharpening or noise reduction.
|
||||
fn detail_on(p: &CameraRaw) -> bool {
|
||||
p.sharpen_amount > 0.0 || p.noise_luminance > 0.0 || p.noise_color > 0.0
|
||||
/// Whether a stage before Whites and Blacks reads neighbouring pixels: Dehaze, Shadows and
|
||||
/// Highlights, Texture or Clarity (all of [`spatial`] but Detail). The image's points then
|
||||
/// depend on its output.
|
||||
pub fn spatial_tone(p: &CameraRaw) -> bool {
|
||||
p.dehaze != 0.0 || [p.highlights, p.shadows, p.texture, p.clarity].iter().any(|v| *v != 0.0)
|
||||
}
|
||||
|
||||
/// The image's black and white points that Whites and Blacks adapt to, for `px` (`w × h`,
|
||||
/// display-encoded) developed per pixel with `p`: what [`develop`](super::develop) measures
|
||||
/// after white balance and Contrast. `None` when Whites and Blacks are 0 or `p` needs a
|
||||
/// spatial stage.
|
||||
/// spatial stage before them ([`spatial_tone`]; Detail comes after).
|
||||
pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: &DevelopInputs) -> Option<(f32, f32)> {
|
||||
if (p.whites == 0.0 && p.blacks == 0.0) || spatial(p) || px.len() != w.saturating_mul(h) {
|
||||
if (p.whites == 0.0 && p.blacks == 0.0) || spatial_tone(p) || px.len() != w.saturating_mul(h) {
|
||||
return None;
|
||||
}
|
||||
let enc = Encoding::of(inputs.encoding_gamma);
|
||||
@@ -228,14 +232,14 @@ pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw, in
|
||||
}))
|
||||
}
|
||||
|
||||
/// Develop's stages for settings without Detail or Calibration, on a `w × h` image; `points` are
|
||||
/// the image's [`white_black_points`]. `None` when `p` needs Detail or Calibration (these stages
|
||||
/// run neither), Shadows or Highlights on a frame wider than the filter's working copy (the
|
||||
/// Develop's stages for settings without Calibration, on a `w × h` image; `points` are the image's
|
||||
/// [`white_black_points`]. `None` when `p` needs Calibration (these stages don't run it), Shadows
|
||||
/// or Highlights on a frame wider than the filter's working copy (the
|
||||
/// develop then filters a reduced copy) or only 2 pixels on its short side, or Whites or Blacks
|
||||
/// without a spatial stage and without `points`. The points themselves leave Calibration out, so a
|
||||
/// caller may cache them across Calibration changes.
|
||||
pub fn per_pixel(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize, float: bool, points: Option<(f32, f32)>) -> Option<PerPixel> {
|
||||
if detail_on(p) || !calibration_neutral(p) {
|
||||
if !calibration_neutral(p) {
|
||||
return None;
|
||||
}
|
||||
// The develop leaves frames under 2 pixels on a side alone.
|
||||
@@ -277,6 +281,7 @@ pub fn per_pixel(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize, floa
|
||||
point: [pts(&p.point_curve), pts(&p.point_curve_red), pts(&p.point_curve_green), pts(&p.point_curve_blue)],
|
||||
hsl: (!hsl_neutral(p)).then_some([p.hsl_hue, p.hsl_sat, p.hsl_lum]),
|
||||
grade: (!grade_neutral(p)).then(|| Grade::new(p)),
|
||||
detail: Detail::new(p, inputs),
|
||||
vignette: (p.vignette_amount != 0.0).then(|| Vignette::new(w, h, p)),
|
||||
grain: (p.grain_amount > 0.0).then(|| Grain::new(p, inputs)),
|
||||
clamp: !float && !identity,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))]
|
||||
|
||||
//! Dehaze, Clarity and Texture resolved for one frame: the sizes, radii and constants their
|
||||
//! Dehaze, Clarity, Texture and Detail resolved for one frame: the sizes, radii and constants their
|
||||
//! filters use, so another implementation of them (the GPU preview,
|
||||
//! `photocraft_gpu::CameraRawDevelop`) runs the same filters. [`develop`](super::develop) builds
|
||||
//! its own from the same constructors.
|
||||
@@ -13,6 +13,9 @@
|
||||
//! J. Sun, *Fast Guided Filter*, arXiv 2015), weighted toward the midtones.
|
||||
//! - **Texture** raises its difference from a Gaussian blur (three box passes), limited to
|
||||
//! ±[`TEXTURE_LIMIT`].
|
||||
//! - **Detail** works on BT.709 luminance and two chroma planes: a guided filter of the luminance
|
||||
//! by itself for luminance noise, a Gaussian of the chroma for colour noise, then an unsharp
|
||||
//! mask of the luminance, optionally weighted by its smoothed gradient.
|
||||
|
||||
use super::{CameraRaw, DevelopInputs};
|
||||
|
||||
@@ -144,6 +147,80 @@ impl Texture {
|
||||
}
|
||||
}
|
||||
|
||||
/// Detail (noise reduction, then sharpening) on BT.709 luminance Y and the chroma B − Y, R − Y,
|
||||
/// resolved for one frame. Each part is `None` when it is off.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Detail {
|
||||
pub luminance: Option<LuminanceNoise>,
|
||||
pub color: Option<ColorNoise>,
|
||||
pub sharpen: Option<Sharpen>,
|
||||
}
|
||||
|
||||
/// Luminance noise reduction: a guided filter of Y by itself, with some of the detail kept.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct LuminanceNoise {
|
||||
/// The guided filter's radius.
|
||||
pub radius: usize,
|
||||
/// Its regularisation.
|
||||
pub eps: f32,
|
||||
/// The share of Y's difference from the filter that stays.
|
||||
pub keep: f32,
|
||||
}
|
||||
|
||||
/// Colour noise reduction: a Gaussian of both chroma planes, with some of the detail kept.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ColorNoise {
|
||||
/// The Gaussian's box radii, in order.
|
||||
pub radii: Vec<usize>,
|
||||
/// The share of the chroma's difference from the blur that stays.
|
||||
pub keep: f32,
|
||||
}
|
||||
|
||||
/// Sharpening: Y plus `amount` times its difference from a Gaussian (after noise reduction),
|
||||
/// clamped to ±`limit` and scaled by `scale`, optionally weighted by an edge mask.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Sharpen {
|
||||
/// The Gaussian's box radii, in order.
|
||||
pub radii: Vec<usize>,
|
||||
pub amount: f32,
|
||||
pub limit: f32,
|
||||
pub scale: f32,
|
||||
/// Masking: the box radii of another Gaussian of Y, and the smoothstep edges its gradient's
|
||||
/// length is weighed between.
|
||||
pub mask: Option<(Vec<usize>, [f32; 2])>,
|
||||
}
|
||||
|
||||
impl Detail {
|
||||
/// Detail for `p` at the job's pixel scale; `None` when sharpening and both noise reductions
|
||||
/// are off.
|
||||
pub fn new(p: &CameraRaw, inputs: &DevelopInputs) -> Option<Self> {
|
||||
let ps = inputs.pixel_scale.clamp(0.01, 1.0);
|
||||
// The controls' documented 0..=100 range: raw values drive the filter radii below.
|
||||
let [nl, nld, nc, ncd] = [p.noise_luminance, p.noise_luminance_detail, p.noise_color, p.noise_color_detail].map(|v| v.clamp(0.0, 100.0));
|
||||
let luminance = (nl > 0.0).then(|| {
|
||||
let n = nl / 100.0;
|
||||
LuminanceNoise { radius: ((1.0 + 3.0 * n) * ps).round().max(1.0) as usize, eps: (n * 0.06).powi(2) + 1e-6, keep: nld / 100.0 * 0.5 }
|
||||
});
|
||||
let color = (nc > 0.0).then(|| ColorNoise { radii: gauss_radii((nc / 100.0 * 6.0 * ps).max(0.3)), keep: ncd / 100.0 * 0.3 });
|
||||
let sharpen = (p.sharpen_amount > 0.0).then(|| {
|
||||
let det = super::sharpening_detail(p.sharpen_detail);
|
||||
// Masking: an edge mask from the gradient of a smoothed luminance.
|
||||
let mask = (p.sharpen_masking > 0.0).then(|| {
|
||||
let t = p.sharpen_masking / 100.0 * 0.08;
|
||||
(gauss_radii(1.0 * ps.max(0.5)), [t * 0.5, t + 1e-4])
|
||||
});
|
||||
Sharpen {
|
||||
radii: gauss_radii((p.sharpen_radius.clamp(0.5, 3.0) * ps).max(0.3)),
|
||||
amount: p.sharpen_amount / 100.0 * 1.2,
|
||||
limit: 0.03 + det * 0.3,
|
||||
scale: 0.5 + 0.5 * det,
|
||||
mask,
|
||||
}
|
||||
});
|
||||
(luminance.is_some() || color.is_some() || sharpen.is_some()).then_some(Detail { luminance, color, sharpen })
|
||||
}
|
||||
}
|
||||
|
||||
/// The box radii of develop's Gaussian of `sigma`: none below 0.3.
|
||||
pub(crate) fn gauss_radii(sigma: f32) -> Vec<usize> {
|
||||
if sigma < 0.3 {
|
||||
@@ -189,6 +266,31 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detail_parts_follow_their_sliders_and_shrink_on_a_proxy() {
|
||||
let full = DevelopInputs::default();
|
||||
let scale = |pixel_scale| DevelopInputs { pixel_scale, ..full };
|
||||
assert!(Detail::new(&CameraRaw::default(), &full).is_none());
|
||||
// Each part is on only when its own slider is.
|
||||
let parts = |p: &CameraRaw| Detail::new(p, &full).map(|d| (d.luminance.is_some(), d.color.is_some(), d.sharpen.is_some()));
|
||||
assert_eq!(parts(&cr! { noise_luminance: 40.0}), Some((true, false, false)));
|
||||
assert_eq!(parts(&cr! { noise_color: 40.0}), Some((false, true, false)));
|
||||
assert_eq!(parts(&cr! { sharpen_amount: 40.0}), Some((false, false, true)));
|
||||
let masked = |m| Detail::new(&cr! { sharpen_amount: 40.0, sharpen_masking: m}, &full).and_then(|d| d.sharpen).map(|s| s.mask.is_some());
|
||||
assert_eq!((masked(0.0), masked(50.0)), (Some(false), Some(true)));
|
||||
// Out-of-range noise sliders act as their ends.
|
||||
assert_eq!(Detail::new(&cr! { noise_luminance: 1e30}, &full), Detail::new(&cr! { noise_luminance: 100.0}, &full));
|
||||
// On the dialog's proxy the filters are no wider than at full size.
|
||||
let p = cr! { noise_luminance: 80.0, noise_color: 80.0, sharpen_amount: 80.0, sharpen_radius: 3.0, sharpen_masking: 50.0};
|
||||
let (big, small) = (Detail::new(&p, &full).unwrap(), Detail::new(&p, &scale(0.143)).unwrap());
|
||||
let reach = |r: &[usize]| r.iter().sum::<usize>();
|
||||
let (bl, sl) = (big.luminance.unwrap(), small.luminance.unwrap());
|
||||
assert!(sl.radius < bl.radius);
|
||||
assert!(reach(&small.color.unwrap().radii) < reach(&big.color.unwrap().radii));
|
||||
let (bs, ss) = (big.sharpen.unwrap(), small.sharpen.unwrap());
|
||||
assert!(reach(&ss.radii) < reach(&bs.radii) && reach(&ss.mask.unwrap().0) <= reach(&bs.mask.unwrap().0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dehaze_cells_average_blocks_after_white_balance_and_refuse_a_wrong_size() {
|
||||
let d = Dehaze::new(&cr! { dehaze: 10.0}, 3, 1).unwrap();
|
||||
|
||||
@@ -168,7 +168,7 @@ impl RawDevelopExt for RawImage {
|
||||
|
||||
fn develop_balanced_masked(&self, method: Method, wb: [f32; 3], clip: f32) -> Result<(Rgb32f, Option<Vec<u8>>)> {
|
||||
let n = self.normalized()?;
|
||||
let mask = clip_mask(self, &n, method, clip);
|
||||
let mask = raw_clip_mask(self, &n, method, clip);
|
||||
Ok((develop_full(self, n, method, Some(wb)), mask))
|
||||
}
|
||||
|
||||
@@ -253,17 +253,34 @@ fn scale_mosaic(n: &mut Normalized, method: Method, gains: [f32; 3]) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn clip_mask(raw: &RawImage, n: &Normalized, method: Method, clip: f32) -> Option<Vec<u8>> {
|
||||
fn raw_clip_mask(raw: &RawImage, n: &Normalized, method: Method, clip: f32) -> Option<Vec<u8>> {
|
||||
let crop = raw.develop_crop(n.width, n.height);
|
||||
if !raw.opcodes.list3.is_empty() || stretched_height(crop.height, raw.pixel_aspect) != crop.height {
|
||||
return None;
|
||||
}
|
||||
clip_mask(n, crop, method, clip)
|
||||
}
|
||||
|
||||
/// The [`highlight::reconstruct_masked`] mask for the output of [`demosaic()`] with `method` on the single-plane CFA
|
||||
/// mosaic `n`, cropped to `crop` (one entry per pixel of `crop`, row-major). `n` holds sensor values normalised so
|
||||
/// that 1.0 is white and before white balance; samples at or above `clip` count as clipped. Use it when the mosaic
|
||||
/// is demosaicked by the caller (for example white-balanced first) rather than through [`RawDevelopExt`].
|
||||
/// `None` when nothing is clipped, `n` is not a single-plane RGB CFA mosaic, `crop` does not fit inside it, or `clip`
|
||||
/// is not a positive finite level.
|
||||
pub fn clip_mask(n: &Normalized, crop: Rect, method: Method, clip: f32) -> Option<Vec<u8>> {
|
||||
use highlight::{CLIPPED_BITS, FROM_CLIPPED_BITS};
|
||||
|
||||
// This radius covers samples read directly by the directional interpolators. Estimates
|
||||
// that build on interpolated green can depend on samples farther away.
|
||||
const REACH: usize = 2;
|
||||
|
||||
let cfa = n.cfa.as_ref().filter(|_| n.cpp == 1)?;
|
||||
let cfa = n.cfa.as_ref().filter(|c| n.cpp == 1 && cfa_valid(c) && c.pattern.iter().all(|&p| p <= 2))?;
|
||||
let (w, h) = (n.width, n.height);
|
||||
let crop = raw.develop_crop(w, h);
|
||||
if !clip.is_finite() || clip <= 0.0 || !raw.opcodes.list3.is_empty() || stretched_height(crop.height, raw.pixel_aspect) != crop.height {
|
||||
let fits = crop.width > 0
|
||||
&& crop.height > 0
|
||||
&& crop.x.checked_add(crop.width).is_some_and(|r| r <= w)
|
||||
&& crop.y.checked_add(crop.height).is_some_and(|b| b <= h);
|
||||
if !clip.is_finite() || clip <= 0.0 || !fits || w.checked_mul(h) != Some(n.data.len()) {
|
||||
return None;
|
||||
}
|
||||
let is_clipped = |v: &f32| *v >= clip;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Original synthetic RAW scenes from storytold/lightcraft#1463, generated in these tests.
|
||||
|
||||
use craft_develop::raster::Rgb32f;
|
||||
use craft_develop::sensor::{Method, RawDevelopExt, highlight};
|
||||
use craft_develop::sensor::{self, Method, RawDevelopExt, highlight};
|
||||
use craft_raw::opcodes::{Opcode, OpcodeLists};
|
||||
use craft_raw::{BlackLevel, Cfa, ColorData, Orientation, RawData, RawFormat, RawImage, Rect};
|
||||
|
||||
@@ -355,6 +355,30 @@ fn the_clip_mask_marks_the_colours_interpolated_from_clipped_samples() {
|
||||
assert!(raw.develop_balanced_masked(Method::Ahd, DAYLIGHT, CLIP).unwrap().1.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caller_demosaicking_its_own_mosaic_gets_the_same_clip_mask() {
|
||||
let (w, h) = (40usize, 30usize);
|
||||
let light = photograph(w, h, |x, y| if (x - 18.0).powi(2) + (y - 14.0).powi(2) < 49.0 { 6.0 } else { 0.4 });
|
||||
let mut cases = layouts();
|
||||
cases.push(("RGGB bilinear".into(), Cfa::bayer("RGGB").unwrap(), Method::Bilinear));
|
||||
for (name, cfa, method) in cases {
|
||||
let mut raw = raw_of(w, h, &cfa, DAYLIGHT, |x, y| [light[y * w + x]; 3]);
|
||||
raw.crop = Rect::new(2, 1, 33, 27);
|
||||
let (_, expected) = raw.develop_balanced_masked(method, DAYLIGHT, CLIP).unwrap();
|
||||
let n = raw.normalized().unwrap();
|
||||
let crop = raw.develop_crop(n.width, n.height);
|
||||
assert_eq!(sensor::clip_mask(&n, crop, method, CLIP), expected, "{name}");
|
||||
assert!(expected.is_some(), "{name}: clipped samples");
|
||||
let outside = Rect::new(crop.x + 1, crop.y, n.width - crop.x, crop.height);
|
||||
assert!(sensor::clip_mask(&n, outside, method, CLIP).is_none(), "{name}: a crop past the mosaic");
|
||||
let mut four_colour = n.clone();
|
||||
four_colour.cfa.as_mut().unwrap().pattern[0] = 3;
|
||||
assert!(sensor::clip_mask(&four_colour, crop, method, CLIP).is_none(), "{name}: a colour index past blue");
|
||||
let huge = sensor::Normalized { width: usize::MAX, height: 2, data: Vec::new(), ..n.clone() };
|
||||
assert!(sensor::clip_mask(&huge, Rect::new(0, 0, 1, 1), method, CLIP).is_none(), "{name}: dimensions past usize");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ppg_clip_mask_marks_same_colour_dependencies() {
|
||||
let cfa = Cfa::bayer("RGGB").unwrap();
|
||||
|
||||
@@ -46,7 +46,9 @@ craft-theme = { workspace = true, optional = true }
|
||||
serde = { workspace = true, optional = true }
|
||||
log = { version = "0.4", optional = true }
|
||||
# Variation axes and named instances of a face (`axes`), on every feature set.
|
||||
skrifa = { version = "0.44", default-features = false, features = ["std"] }
|
||||
skrifa = { version = "0.47", default-features = false, features = ["std"] }
|
||||
# Decodes the preview service's WOFF2 subsets; pure Rust. Brotli only: WOFF 1 isn't served.
|
||||
wuff = { version = "0.2.9", default-features = false, features = ["brotli"] }
|
||||
|
||||
[build-dependencies]
|
||||
# The Arabic sample story's face, from the craft fonts set when `CRAFT_FONTS_DIR` names one.
|
||||
@@ -54,6 +56,8 @@ craft-fonts-build = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
craft-font-manager = { path = ".", features = ["suite"] }
|
||||
# The shared preview test vectors.
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[[test]]
|
||||
name = "it"
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
pub mod filter;
|
||||
pub mod index;
|
||||
pub mod installed;
|
||||
pub mod remote;
|
||||
pub mod store;
|
||||
|
||||
pub mod axes;
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
//! Sample text: a sentence in the language the catalogue is filtered by, or in a family's own
|
||||
//! script when it has no Latin, so a sample never comes out as boxes.
|
||||
//! Sample text: a family's own sentence from the index (its script's, by `sample_script`), the
|
||||
//! one the preview service's sample subsets hold; a sentence in the language the catalogue is
|
||||
//! filtered by; and built-in sentences by script for families the index has no sample for.
|
||||
|
||||
use crate::index::{Family, Index};
|
||||
use crate::panel::app::list_file;
|
||||
|
||||
/// The English pangram, the sample for Latin.
|
||||
pub const PANGRAM: &str = "The quick brown fox jumps over the lazy dog";
|
||||
@@ -81,6 +85,12 @@ pub fn for_script(script: &str) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The sample of the face the list shows for `family`, from the index: the sentence of the
|
||||
/// face's `sample_script` (else the family's), or the face's own text.
|
||||
pub fn of_family<'a>(index: &'a Index, family: &'a Family) -> Option<&'a str> {
|
||||
list_file(family).and_then(|file| index.sample_text(family, file))
|
||||
}
|
||||
|
||||
/// The sample for a family with `scripts`: the pangram when it has Latin, else a sentence in the
|
||||
/// first of its scripts there is one for.
|
||||
pub fn for_scripts<'a>(scripts: impl IntoIterator<Item = &'a str>) -> &'static str {
|
||||
|
||||
@@ -0,0 +1,683 @@
|
||||
//! The font preview service's client: subset URLs, a pool that fetches and decodes them, and a
|
||||
//! disk cache.
|
||||
//!
|
||||
//! The service serves a small subset of one font file per preview, addressed by the upstream
|
||||
//! file's sha256: the face's default sample, printable ASCII, or a set of codepoints, at the
|
||||
//! instance the list shows or with every axis kept. Responses never change, so the cache never
|
||||
//! revalidates. With the service at `https://fonts.example.com`, the list's sample of a face is
|
||||
//! `https://fonts.example.com/v1/faces/<sha256>/list/sample-<h>.woff2`.
|
||||
//!
|
||||
//! [`Previews`] requests nothing unless a preview service is set and previews are enabled
|
||||
//! ([`Installer::preview_service`], [`Installer::previews_enabled`]). Previews are on by default;
|
||||
//! a user setting turns them off. There is no prompt, and the install consent
|
||||
//! ([`Installer::downloads_allowed`]) is not consulted: previews are fetched whether or not
|
||||
//! installs are allowed. With previews off nothing goes to the network, but previews already in
|
||||
//! the disk cache are still used. Without a service the panel keeps its whole-family previews.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::fmt::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use craft_font_store::{Cancel, Client, FetchError, Timeouts, is_font, sha256_hex};
|
||||
|
||||
use crate::store::Installer;
|
||||
|
||||
/// The most codepoints one request may name; the service rejects more.
|
||||
pub const MAX_CODEPOINTS: usize = 256;
|
||||
|
||||
/// The largest response accepted. Subsets are a few KB; a `var` subset of CJK text is the largest.
|
||||
pub const MAX_PREVIEW_BYTES: u64 = 8 << 20;
|
||||
|
||||
/// The disk cache's size.
|
||||
pub const CACHE_LIMIT: u64 = 50 << 20;
|
||||
|
||||
/// Requests at a time.
|
||||
pub const WORKERS: usize = 8;
|
||||
|
||||
/// A set of codepoints, as a subset request names them.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct Codepoints(BTreeSet<char>);
|
||||
|
||||
impl Codepoints {
|
||||
/// The characters of `text` without C0 and C1 controls and DEL, which no font draws.
|
||||
pub fn from_text(text: &str) -> Codepoints {
|
||||
text.chars().collect()
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
|
||||
pub fn contains(&self, c: char) -> bool {
|
||||
self.0.contains(&c)
|
||||
}
|
||||
|
||||
/// In ascending order.
|
||||
pub fn iter(&self) -> impl Iterator<Item = char> + '_ {
|
||||
self.0.iter().copied()
|
||||
}
|
||||
|
||||
/// Keeps the codepoints `keep` accepts, such as those a face covers.
|
||||
pub fn retain(&mut self, mut keep: impl FnMut(char) -> bool) {
|
||||
self.0.retain(|&c| keep(c));
|
||||
}
|
||||
|
||||
/// The canonical form the service accepts, and so the cache key: ascending lowercase hex
|
||||
/// without leading zeros, a run of two or more as `first-last`, joined by commas
|
||||
/// (`20,41-5a,e9`). Empty for the empty set.
|
||||
pub fn encode(&self) -> String {
|
||||
let mut out = String::new();
|
||||
let mut rest = self.0.iter().map(|&c| c as u32).peekable();
|
||||
while let Some(first) = rest.next() {
|
||||
let mut last = first;
|
||||
while rest.peek() == Some(&(last + 1)) {
|
||||
last += 1;
|
||||
rest.next();
|
||||
}
|
||||
if !out.is_empty() {
|
||||
out.push(',');
|
||||
}
|
||||
let _ = if last == first { write!(out, "{first:x}") } else { write!(out, "{first:x}-{last:x}") };
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl FromIterator<char> for Codepoints {
|
||||
/// Without C0 and C1 controls and DEL.
|
||||
fn from_iter<I: IntoIterator<Item = char>>(chars: I) -> Codepoints {
|
||||
Codepoints(chars.into_iter().filter(|&c| !matches!(c as u32, 0..0x20 | 0x7f..=0x9f)).collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// Which instance of a face a subset is drawn at.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Instance {
|
||||
/// What the list shows: the "Regular" named instance of a variable face, else its default,
|
||||
/// pinned to a static font.
|
||||
List,
|
||||
/// Every axis kept, for the detail view's styles and sliders.
|
||||
Var,
|
||||
}
|
||||
|
||||
impl Instance {
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Instance::List => "list",
|
||||
Instance::Var => "var",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The first 12 lowercase hex digits of the sha256 of a sample text (UTF-8, as the index has
|
||||
/// it), which names the sample subset for that text.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct SampleHash(String);
|
||||
|
||||
impl SampleHash {
|
||||
pub fn of(text: &str) -> SampleHash {
|
||||
SampleHash(sha256_hex(text.as_bytes())[..12].to_string())
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Which characters a subset holds.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Subset {
|
||||
/// The face's default sample (its script's sentence from the index) and the family name.
|
||||
/// The hash names the text the client has; the service answers 404 for any other.
|
||||
Sample(SampleHash),
|
||||
/// Printable ASCII, U+0020 to U+007E, for faces that cover Latin.
|
||||
Ascii,
|
||||
/// These codepoints, for typed text the static subsets don't cover.
|
||||
Codepoints(Codepoints),
|
||||
}
|
||||
|
||||
/// One subset of one face: a request, a cache entry and the key results come back under.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct PreviewKey {
|
||||
sha256: String,
|
||||
instance: Instance,
|
||||
subset: Subset,
|
||||
}
|
||||
|
||||
impl PreviewKey {
|
||||
/// The subset of the font file with this sha256 (as the index has it). `None` for a sha256
|
||||
/// that isn't 64 hex digits, and for codepoints that are empty or more than
|
||||
/// [`MAX_CODEPOINTS`].
|
||||
pub fn new(sha256: &str, instance: Instance, subset: Subset) -> Option<PreviewKey> {
|
||||
if sha256.len() != 64 || !sha256.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
if let Subset::Codepoints(c) = &subset
|
||||
&& (c.is_empty() || c.len() > MAX_CODEPOINTS)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(PreviewKey { sha256: sha256.to_ascii_lowercase(), instance, subset })
|
||||
}
|
||||
|
||||
pub fn sha256(&self) -> &str {
|
||||
&self.sha256
|
||||
}
|
||||
|
||||
pub fn instance(&self) -> Instance {
|
||||
self.instance
|
||||
}
|
||||
|
||||
pub fn subset(&self) -> &Subset {
|
||||
&self.subset
|
||||
}
|
||||
|
||||
/// The path below the service's base URL: `v1/faces/<sha256>/<instance>/sample-<h>.woff2`,
|
||||
/// `.../ascii.woff2` or `.../u/<codepoints>.woff2`.
|
||||
pub fn path(&self) -> String {
|
||||
let what = match &self.subset {
|
||||
Subset::Sample(h) => format!("sample-{}", h.as_str()),
|
||||
Subset::Ascii => "ascii".to_string(),
|
||||
Subset::Codepoints(c) => format!("u/{}", c.encode()),
|
||||
};
|
||||
format!("v1/faces/{}/{}/{what}.woff2", self.sha256, self.instance.as_str())
|
||||
}
|
||||
|
||||
/// The URL at the service whose base URL is `service`.
|
||||
pub fn url(&self, service: &str) -> String {
|
||||
format!("{}/{}", service.trim_end_matches('/'), self.path())
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a preview didn't load.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum PreviewError {
|
||||
/// The user turned previews off, and the subset isn't cached.
|
||||
PreviewsOff,
|
||||
/// No preview service is set.
|
||||
NoService,
|
||||
/// The request failed: the network, an HTTP status (503 while the service is busy), the
|
||||
/// size limit.
|
||||
Failed(String),
|
||||
/// The service has no such subset (HTTP 404): for a sample, its text isn't the client's.
|
||||
NotFound,
|
||||
/// The response isn't a WOFF2 font with outlines.
|
||||
NotAFont,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for PreviewError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
PreviewError::PreviewsOff => f.write_str("font previews are turned off"),
|
||||
PreviewError::NoService => f.write_str("no preview service is set"),
|
||||
PreviewError::Failed(e) => f.write_str(e),
|
||||
PreviewError::NotFound => f.write_str("the service has no such preview"),
|
||||
PreviewError::NotAFont => f.write_str("the preview is not a font, or a damaged one"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for PreviewError {}
|
||||
|
||||
/// A finished request.
|
||||
#[derive(Debug)]
|
||||
pub struct Preview {
|
||||
pub key: PreviewKey,
|
||||
/// The decoded font file (TrueType or OpenType), ready to register.
|
||||
pub font: Result<Vec<u8>, PreviewError>,
|
||||
}
|
||||
|
||||
/// How the pool downloads: craft-font-store's [`Client`], or a stand-in in tests.
|
||||
pub trait Fetch: Send + Sync {
|
||||
/// GETs `url`, built from the preview-service setting, at most `max` bytes, stopping soon after `cancel` is set.
|
||||
fn get(&self, url: &str, max: u64, cancel: &Cancel) -> Result<Vec<u8>, FetchError>;
|
||||
}
|
||||
|
||||
impl Fetch for Client {
|
||||
fn get(&self, url: &str, max: u64, cancel: &Cancel) -> Result<Vec<u8>, FetchError> {
|
||||
Client::get_from_service(self, url, max, cancel, &mut |_| {})
|
||||
}
|
||||
}
|
||||
|
||||
/// Subsets as the service sent them (WOFF2), one file per key, named by the sha256 of the key's
|
||||
/// path. The least recently used go once the folder holds more than its limit. Several apps can
|
||||
/// share the folder: a file another one removed is a miss.
|
||||
pub struct DiskCache {
|
||||
dir: PathBuf,
|
||||
limit: u64,
|
||||
/// Read from the folder on first use.
|
||||
entries: Mutex<Option<Entries>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Entries {
|
||||
/// File name to its size and last use.
|
||||
files: HashMap<String, (u64, u64)>,
|
||||
/// Last use to file name, oldest first.
|
||||
order: BTreeMap<u64, String>,
|
||||
total: u64,
|
||||
tick: u64,
|
||||
}
|
||||
|
||||
impl Entries {
|
||||
fn touch(&mut self, name: &str, size: u64) {
|
||||
self.tick += 1;
|
||||
if let Some((old_size, old_tick)) = self.files.insert(name.to_string(), (size, self.tick)) {
|
||||
self.order.remove(&old_tick);
|
||||
self.total = self.total.saturating_sub(old_size);
|
||||
}
|
||||
self.order.insert(self.tick, name.to_string());
|
||||
self.total = self.total.saturating_add(size);
|
||||
}
|
||||
|
||||
fn forget(&mut self, name: &str) {
|
||||
if let Some((size, tick)) = self.files.remove(name) {
|
||||
self.order.remove(&tick);
|
||||
self.total = self.total.saturating_sub(size);
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the oldest files, except `keep`, until the rest fit in `limit`.
|
||||
fn evict(&mut self, dir: &Path, limit: u64, keep: Option<&str>) {
|
||||
while self.total > limit {
|
||||
let Some(name) = self.order.values().find(|n| Some(n.as_str()) != keep).cloned() else { break };
|
||||
let _ = std::fs::remove_file(dir.join(&name));
|
||||
self.forget(&name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A temporary file older than this belongs to a write that never finished.
|
||||
const STALE_TEMP: Duration = Duration::from_secs(600);
|
||||
|
||||
impl DiskCache {
|
||||
/// A cache in `dir` (created on the first write) of at most `limit` bytes.
|
||||
pub fn new(dir: impl Into<PathBuf>, limit: u64) -> DiskCache {
|
||||
DiskCache { dir: dir.into(), limit, entries: Mutex::new(None) }
|
||||
}
|
||||
|
||||
pub fn dir(&self) -> &Path {
|
||||
&self.dir
|
||||
}
|
||||
|
||||
/// The bytes cached for `path` ([`PreviewKey::path`]), marking them as just used.
|
||||
pub fn get(&self, path: &str) -> Option<Vec<u8>> {
|
||||
let name = file_name(path);
|
||||
let file = self.dir.join(&name);
|
||||
let bytes = std::fs::metadata(&file).ok().filter(|m| m.len() <= MAX_PREVIEW_BYTES).and_then(|_| std::fs::read(&file).ok());
|
||||
match bytes {
|
||||
Some(bytes) => {
|
||||
self.with(|e| e.touch(&name, bytes.len() as u64));
|
||||
// The modification time keeps the order for the next session.
|
||||
let _ = std::fs::File::options().write(true).open(&file).and_then(|f| f.set_modified(SystemTime::now()));
|
||||
Some(bytes)
|
||||
}
|
||||
None => {
|
||||
self.with(|e| e.forget(&name));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` is cached, without marking it used. Asks the folder, which another app
|
||||
/// sharing it may have added to since it was read.
|
||||
pub fn contains(&self, path: &str) -> bool {
|
||||
std::fs::metadata(self.dir.join(file_name(path))).is_ok_and(|m| m.is_file())
|
||||
}
|
||||
|
||||
/// Caches `bytes` for `path`, then removes the least recently used past the limit. Bytes
|
||||
/// larger than the whole limit aren't cached.
|
||||
pub fn put(&self, path: &str, bytes: &[u8]) {
|
||||
let size = bytes.len() as u64;
|
||||
if size > self.limit {
|
||||
return;
|
||||
}
|
||||
let name = file_name(path);
|
||||
if std::fs::create_dir_all(&self.dir).is_err() {
|
||||
return;
|
||||
}
|
||||
// A reader never sees half a file: write beside it, then rename.
|
||||
static N: AtomicU64 = AtomicU64::new(0);
|
||||
let temp = self.dir.join(format!(".tmp-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
|
||||
if std::fs::write(&temp, bytes).and_then(|()| std::fs::rename(&temp, self.dir.join(&name))).is_err() {
|
||||
let _ = std::fs::remove_file(&temp);
|
||||
return;
|
||||
}
|
||||
self.with(|e| {
|
||||
e.touch(&name, size);
|
||||
e.evict(&self.dir, self.limit, Some(&name));
|
||||
});
|
||||
}
|
||||
|
||||
/// Removes the entry for `path`, as when it doesn't decode.
|
||||
pub fn remove(&self, path: &str) {
|
||||
let name = file_name(path);
|
||||
let _ = std::fs::remove_file(self.dir.join(&name));
|
||||
self.with(|e| e.forget(&name));
|
||||
}
|
||||
|
||||
/// Bytes held.
|
||||
pub fn size(&self) -> u64 {
|
||||
self.with(|e| e.total)
|
||||
}
|
||||
|
||||
fn with<R>(&self, f: impl FnOnce(&mut Entries) -> R) -> R {
|
||||
let mut guard = self.entries.lock().unwrap_or_else(|e| e.into_inner());
|
||||
f(guard.get_or_insert_with(|| self.scan()))
|
||||
}
|
||||
|
||||
/// The files in the folder, oldest modification first; drops stale temporary files and
|
||||
/// whatever no longer fits.
|
||||
fn scan(&self) -> Entries {
|
||||
let mut found = Vec::new();
|
||||
for entry in std::fs::read_dir(&self.dir).into_iter().flatten().flatten() {
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
let Ok(meta) = entry.metadata() else { continue };
|
||||
let modified = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH);
|
||||
if name.starts_with(".tmp-") {
|
||||
if modified.elapsed().is_ok_and(|age| age > STALE_TEMP) {
|
||||
let _ = std::fs::remove_file(entry.path());
|
||||
}
|
||||
} else if meta.is_file() && is_entry_name(&name) {
|
||||
found.push((modified, name, meta.len()));
|
||||
}
|
||||
}
|
||||
found.sort();
|
||||
let mut entries = Entries::default();
|
||||
for (_, name, size) in found {
|
||||
entries.touch(&name, size);
|
||||
}
|
||||
entries.evict(&self.dir, self.limit, None);
|
||||
entries
|
||||
}
|
||||
}
|
||||
|
||||
fn file_name(path: &str) -> String {
|
||||
format!("{}.woff2", sha256_hex(path.as_bytes()))
|
||||
}
|
||||
|
||||
fn is_entry_name(name: &str) -> bool {
|
||||
name.strip_suffix(".woff2").is_some_and(|h| h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
}
|
||||
|
||||
type Wake = Arc<dyn Fn() + Send + Sync>;
|
||||
|
||||
/// Fetches subsets on [`WORKERS`] threads of its own, separate from the panel's jobs, highest
|
||||
/// priority first. Results wait in [`Previews::poll`]; a cancelled request delivers nothing.
|
||||
///
|
||||
/// Each request reads the disk cache first. Only on a miss, and only while previews are enabled
|
||||
/// and a service is set, does it go to the network; the response is decoded, checked and cached.
|
||||
/// Without a service, requests come back as [`PreviewError::NoService`] at once and nothing is
|
||||
/// read or fetched.
|
||||
pub struct Previews {
|
||||
installer: Arc<dyn Installer>,
|
||||
fetcher: Arc<dyn Fetch>,
|
||||
cache: Option<Arc<DiskCache>>,
|
||||
wake: Option<Wake>,
|
||||
workers: usize,
|
||||
shared: Arc<Shared>,
|
||||
tx: Sender<Preview>,
|
||||
rx: Receiver<Preview>,
|
||||
}
|
||||
|
||||
struct Shared {
|
||||
state: Mutex<State>,
|
||||
ready: Condvar,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
/// Waiting: priority and order of arrival.
|
||||
queued: HashMap<PreviewKey, (u32, u64)>,
|
||||
/// Being fetched: the job's id and its cancel flag.
|
||||
running: HashMap<PreviewKey, (u64, Cancel)>,
|
||||
next: u64,
|
||||
started: bool,
|
||||
stop: bool,
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// The highest priority, then the oldest.
|
||||
fn take_next(&mut self) -> Option<PreviewKey> {
|
||||
let key = self.queued.iter().max_by_key(|(_, (priority, seq))| (*priority, std::cmp::Reverse(*seq))).map(|(k, _)| k.clone())?;
|
||||
self.queued.remove(&key);
|
||||
Some(key)
|
||||
}
|
||||
|
||||
fn is_running(&self, key: &PreviewKey) -> bool {
|
||||
self.running.get(key).is_some_and(|(_, c)| !c.is_cancelled())
|
||||
}
|
||||
}
|
||||
|
||||
impl Previews {
|
||||
/// A pool fetching with the installer's client ([`Installer::http_client`]) given short timeouts
|
||||
/// (10 s to connect, 15 s to respond, 30 s overall; the down state stays shared), else with its
|
||||
/// own craft-font-store [`Client`]. A network failure of the service pauses its requests for a
|
||||
/// minute, for every user of the same client (installs too). It caches in the store's
|
||||
/// [`Installer::preview_cache`] folder, up to [`CACHE_LIMIT`]. It starts its threads on the
|
||||
/// first request.
|
||||
pub fn new(installer: Arc<dyn Installer>) -> Previews {
|
||||
let timeouts = Timeouts { connect: Duration::from_secs(10), response: Duration::from_secs(15), overall: Duration::from_secs(30) };
|
||||
let client = installer.http_client().map_or_else(|| Client::new(timeouts), |c| c.with_timeouts(timeouts));
|
||||
let cache = installer.preview_cache().map(|dir| Arc::new(DiskCache::new(dir, CACHE_LIMIT)));
|
||||
let (tx, rx) = channel();
|
||||
Previews {
|
||||
installer,
|
||||
fetcher: Arc::new(client),
|
||||
cache,
|
||||
wake: None,
|
||||
workers: WORKERS,
|
||||
shared: Arc::new(Shared { state: Mutex::new(State::default()), ready: Condvar::new() }),
|
||||
tx,
|
||||
rx,
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches through `fetcher` instead.
|
||||
pub fn with_fetcher(mut self, fetcher: Arc<dyn Fetch>) -> Previews {
|
||||
self.fetcher = fetcher;
|
||||
self
|
||||
}
|
||||
|
||||
/// Caches in `cache`, or with `None` not at all.
|
||||
pub fn with_cache(mut self, cache: Option<DiskCache>) -> Previews {
|
||||
self.cache = cache.map(Arc::new);
|
||||
self
|
||||
}
|
||||
|
||||
/// Runs `workers` requests at a time (at least one) instead of [`WORKERS`].
|
||||
pub fn with_workers(mut self, workers: usize) -> Previews {
|
||||
self.workers = workers.max(1);
|
||||
self
|
||||
}
|
||||
|
||||
/// Calls `wake` from a worker thread after each result, such as egui's `request_repaint`.
|
||||
pub fn on_ready(mut self, wake: impl Fn() + Send + Sync + 'static) -> Previews {
|
||||
self.wake = Some(Arc::new(wake));
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether a preview service is set and previews are enabled. It reads the store's settings, so callers ask when the
|
||||
/// panel opens or its settings change, not every frame.
|
||||
pub fn available(&self) -> bool {
|
||||
self.installer.preview_service().is_some() && self.installer.previews_enabled()
|
||||
}
|
||||
|
||||
/// The disk cache, if there is one.
|
||||
pub fn cache(&self) -> Option<&DiskCache> {
|
||||
self.cache.as_deref()
|
||||
}
|
||||
|
||||
/// Queues `key` at `priority` (higher first; the same priority in the order asked). A key
|
||||
/// already queued takes the new priority; one being fetched is left alone.
|
||||
pub fn request(&self, key: PreviewKey, priority: u32) {
|
||||
let mut state = self.lock();
|
||||
if state.is_running(&key) {
|
||||
return;
|
||||
}
|
||||
if !state.started {
|
||||
state.started = true;
|
||||
self.start();
|
||||
}
|
||||
let seq = state.next;
|
||||
state.next += 1;
|
||||
let entry = state.queued.entry(key).or_insert((priority, seq));
|
||||
entry.0 = priority;
|
||||
drop(state);
|
||||
self.shared.ready.notify_one();
|
||||
}
|
||||
|
||||
/// Drops `key` from the queue, or stops fetching it. Nothing is delivered for it, unless it
|
||||
/// finished before the call.
|
||||
pub fn cancel(&self, key: &PreviewKey) {
|
||||
self.retain(|k| k != key);
|
||||
}
|
||||
|
||||
/// Cancels every queued and running request `keep` rejects, such as rows that scrolled out
|
||||
/// of the window.
|
||||
pub fn retain(&self, mut keep: impl FnMut(&PreviewKey) -> bool) {
|
||||
let mut state = self.lock();
|
||||
state.queued.retain(|k, _| keep(k));
|
||||
for (key, (_, cancel)) in &state.running {
|
||||
if !keep(key) {
|
||||
cancel.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `key` is queued or being fetched.
|
||||
pub fn is_pending(&self, key: &PreviewKey) -> bool {
|
||||
let state = self.lock();
|
||||
state.queued.contains_key(key) || state.is_running(key)
|
||||
}
|
||||
|
||||
/// Requests queued or being fetched.
|
||||
pub fn pending(&self) -> usize {
|
||||
let state = self.lock();
|
||||
state.queued.len() + state.running.values().filter(|(_, c)| !c.is_cancelled()).count()
|
||||
}
|
||||
|
||||
/// The results since the last call.
|
||||
pub fn poll(&self) -> Vec<Preview> {
|
||||
self.rx.try_iter().collect()
|
||||
}
|
||||
|
||||
fn lock(&self) -> MutexGuard<'_, State> {
|
||||
self.shared.state.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn start(&self) {
|
||||
for i in 0..self.workers {
|
||||
let worker = Worker {
|
||||
installer: Arc::clone(&self.installer),
|
||||
fetcher: Arc::clone(&self.fetcher),
|
||||
cache: self.cache.clone(),
|
||||
wake: self.wake.clone(),
|
||||
shared: Arc::clone(&self.shared),
|
||||
tx: self.tx.clone(),
|
||||
};
|
||||
// A pool short of threads still works, more slowly; with none, requests stay queued.
|
||||
let _ = std::thread::Builder::new().name(format!("font-previews-{i}")).spawn(move || worker.run());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Previews {
|
||||
fn drop(&mut self) {
|
||||
let mut state = self.lock();
|
||||
state.stop = true;
|
||||
state.queued.clear();
|
||||
for (_, cancel) in state.running.values() {
|
||||
cancel.cancel();
|
||||
}
|
||||
drop(state);
|
||||
self.shared.ready.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
struct Worker {
|
||||
installer: Arc<dyn Installer>,
|
||||
fetcher: Arc<dyn Fetch>,
|
||||
cache: Option<Arc<DiskCache>>,
|
||||
wake: Option<Wake>,
|
||||
shared: Arc<Shared>,
|
||||
tx: Sender<Preview>,
|
||||
}
|
||||
|
||||
impl Worker {
|
||||
fn run(self) {
|
||||
while let Some((key, id, cancel)) = self.next() {
|
||||
let font = self.load(&key, &cancel);
|
||||
let mut state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if state.running.get(&key).is_some_and(|(i, _)| *i == id) {
|
||||
state.running.remove(&key);
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
continue;
|
||||
}
|
||||
// Sent under the lock, so a cancel that returned has either dropped it or comes after.
|
||||
let _ = self.tx.send(Preview { key, font });
|
||||
drop(state);
|
||||
if let Some(wake) = &self.wake {
|
||||
wake();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for a request; `None` once the pool is dropped.
|
||||
fn next(&self) -> Option<(PreviewKey, u64, Cancel)> {
|
||||
let mut state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner());
|
||||
loop {
|
||||
if state.stop {
|
||||
return None;
|
||||
}
|
||||
if let Some(key) = state.take_next() {
|
||||
let id = state.next;
|
||||
state.next += 1;
|
||||
let cancel = Cancel::new();
|
||||
state.running.insert(key.clone(), (id, cancel.clone()));
|
||||
return Some((key, id, cancel));
|
||||
}
|
||||
state = self.shared.ready.wait(state).unwrap_or_else(|e| e.into_inner());
|
||||
}
|
||||
}
|
||||
|
||||
fn load(&self, key: &PreviewKey, cancel: &Cancel) -> Result<Vec<u8>, PreviewError> {
|
||||
let Some(service) = self.installer.preview_service() else { return Err(PreviewError::NoService) };
|
||||
let path = key.path();
|
||||
if let Some(cache) = &self.cache
|
||||
&& let Some(bytes) = cache.get(&path)
|
||||
{
|
||||
match decode(&bytes) {
|
||||
Ok(font) => return Ok(font),
|
||||
Err(_) => cache.remove(&path),
|
||||
}
|
||||
}
|
||||
if !self.installer.previews_enabled() {
|
||||
return Err(PreviewError::PreviewsOff);
|
||||
}
|
||||
let bytes = self.fetcher.get(&key.url(&service), MAX_PREVIEW_BYTES, cancel).map_err(|e| match e {
|
||||
FetchError::Failed(m) if m == "HTTP 404" => PreviewError::NotFound,
|
||||
e => PreviewError::Failed(e.to_string()),
|
||||
})?;
|
||||
let font = decode(&bytes)?;
|
||||
if let Some(cache) = &self.cache {
|
||||
cache.put(&path, &bytes);
|
||||
}
|
||||
Ok(font)
|
||||
}
|
||||
}
|
||||
|
||||
/// The font file inside a WOFF2 response, when it parses and has outlines.
|
||||
fn decode(woff2: &[u8]) -> Result<Vec<u8>, PreviewError> {
|
||||
let font = wuff::decompress_woff2(woff2).map_err(|_| PreviewError::NotAFont)?;
|
||||
if is_font(&font) { Ok(font) } else { Err(PreviewError::NotAFont) }
|
||||
}
|
||||
@@ -13,9 +13,9 @@ use std::sync::{Condvar, Mutex};
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use craft_font_catalog::Catalog;
|
||||
pub use craft_font_store::UserSource;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use craft_font_store::{Cancel, Client, Face, FontStore, Network, PINNED_INDEX, verify_font};
|
||||
pub use craft_font_store::{LegalText, PREVIEW_SERVICE_ENV, PreviewServiceSource, UserSource};
|
||||
|
||||
use crate::index::{Family, Index};
|
||||
|
||||
@@ -147,6 +147,56 @@ pub trait Installer: Send + Sync {
|
||||
fn remove_user_source(&self, _url: &str) -> Result<(), StoreError> {
|
||||
Err(StoreError(NO_FOLDER.into()))
|
||||
}
|
||||
|
||||
/// The preview service's base URL, if one is set: [`craft_font_store::PREVIEW_SERVICE_ENV`], else the font
|
||||
/// store's `preview_service` setting, else the host's default
|
||||
/// ([`SuiteStore::with_default_preview_service`]). Installs try it as a mirror first.
|
||||
fn preview_service(&self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Where [`Installer::preview_service`] comes from: the environment variable (the setting
|
||||
/// can't change it), the saved setting, the host's default
|
||||
/// ([`PreviewServiceSource::Default`]), or nowhere.
|
||||
fn preview_service_source(&self) -> PreviewServiceSource {
|
||||
PreviewServiceSource::None
|
||||
}
|
||||
|
||||
/// The store's HTTP client, if it has one. [`Previews`](crate::remote::Previews) fetches
|
||||
/// with it, so a preview service that installs found unreachable is skipped by previews too,
|
||||
/// and the reverse.
|
||||
fn http_client(&self) -> Option<Client> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether previews may be fetched from the preview service: the user's setting, on by
|
||||
/// default.
|
||||
fn previews_enabled(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Turns previews on or off, as the user's own action.
|
||||
fn set_previews_enabled(&self, _enabled: bool) -> Result<(), StoreError> {
|
||||
Err(StoreError(NO_FOLDER.into()))
|
||||
}
|
||||
|
||||
/// Sets or clears the preview service (https, or http for a loopback host), as the user's own
|
||||
/// action.
|
||||
fn set_preview_service(&self, _url: Option<&str>) -> Result<(), StoreError> {
|
||||
Err(StoreError(NO_FOLDER.into()))
|
||||
}
|
||||
|
||||
/// The folder [`crate::remote::Previews`] caches preview subsets in; none keeps them only
|
||||
/// for as long as the caller holds them.
|
||||
fn preview_cache(&self) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The text of `family`'s licence or NOTICE file: the installed copy, else downloaded when
|
||||
/// downloads are allowed. `None` when the family has no such file.
|
||||
fn legal_text(&self, _index: &Index, _family: &Family, _which: LegalText) -> Result<Option<String>, StoreError> {
|
||||
Err(StoreError(NO_FOLDER.into()))
|
||||
}
|
||||
}
|
||||
|
||||
const NO_FOLDER: &str = "there is no folder for the font store";
|
||||
@@ -155,7 +205,6 @@ const NO_FOLDER: &str = "there is no folder for the font store";
|
||||
/// craft-font-store's store, in the user's font store folder.
|
||||
pub struct SuiteStore {
|
||||
store: FontStore,
|
||||
client: Client,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -163,7 +212,25 @@ impl SuiteStore {
|
||||
/// The store the catalog's environment names, rescanning `catalog` after each change.
|
||||
pub fn for_user(catalog: Arc<Catalog>) -> Option<SuiteStore> {
|
||||
let store = FontStore::for_user(catalog.env())?.with_catalog(catalog);
|
||||
Some(SuiteStore { store, client: Client::default() })
|
||||
Some(SuiteStore { store })
|
||||
}
|
||||
|
||||
/// Uses `url` as the preview service while neither [`PREVIEW_SERVICE_ENV`] nor the user's
|
||||
/// setting names one; see [`FontStore::with_default_preview_service`]. Never saved.
|
||||
pub fn with_default_preview_service(self, url: &str) -> SuiteStore {
|
||||
SuiteStore { store: self.store.with_default_preview_service(url) }
|
||||
}
|
||||
|
||||
/// Uses `network` for "Allow font downloads" while the user hasn't chosen; see
|
||||
/// [`FontStore::with_default_network`]. Never saved.
|
||||
pub fn with_default_network(self, network: Network) -> SuiteStore {
|
||||
SuiteStore { store: self.store.with_default_network(network) }
|
||||
}
|
||||
|
||||
/// The store's HTTP client. Clones share the preview service's down state with installs;
|
||||
/// [`Previews::new`](crate::remote::Previews::new) takes it through [`Installer::http_client`].
|
||||
pub fn client(&self) -> Client {
|
||||
self.store.client()
|
||||
}
|
||||
|
||||
/// The store's source and name for the family holding `files`, which can differ from the
|
||||
@@ -222,7 +289,7 @@ impl Installer for SuiteStore {
|
||||
let mut reasons = Vec::new();
|
||||
for url in index.file_urls(family, file) {
|
||||
let mut on_bytes = |n: u64| progress(Progress { done: before.saturating_add(n), total });
|
||||
match self.client.get(&url, file.size, &cancel, &mut on_bytes) {
|
||||
match self.store.client().get(&url, file.size, &cancel, &mut on_bytes) {
|
||||
Ok(bytes) => match verify_font(file, &bytes) {
|
||||
Ok(()) => {
|
||||
out.push(Downloaded { path: file.path.clone(), bytes });
|
||||
@@ -261,6 +328,38 @@ impl Installer for SuiteStore {
|
||||
fn remove_user_source(&self, url: &str) -> Result<(), StoreError> {
|
||||
self.store.remove_user_source(url).map_err(err)
|
||||
}
|
||||
|
||||
fn preview_service(&self) -> Option<String> {
|
||||
self.store.preview_service()
|
||||
}
|
||||
|
||||
fn preview_service_source(&self) -> PreviewServiceSource {
|
||||
self.store.preview_service_source()
|
||||
}
|
||||
|
||||
fn http_client(&self) -> Option<Client> {
|
||||
Some(self.store.client())
|
||||
}
|
||||
|
||||
fn set_preview_service(&self, url: Option<&str>) -> Result<(), StoreError> {
|
||||
self.store.set_preview_service(url).map_err(err)
|
||||
}
|
||||
|
||||
fn preview_cache(&self) -> Option<PathBuf> {
|
||||
Some(self.store.previews_dir())
|
||||
}
|
||||
|
||||
fn previews_enabled(&self) -> bool {
|
||||
self.store.previews_enabled()
|
||||
}
|
||||
|
||||
fn set_previews_enabled(&self, enabled: bool) -> Result<(), StoreError> {
|
||||
self.store.set_previews_enabled(enabled).map_err(err)
|
||||
}
|
||||
|
||||
fn legal_text(&self, index: &Index, family: &Family, which: LegalText) -> Result<Option<String>, StoreError> {
|
||||
self.store.legal_text(index, family, which, &Cancel::new()).map_err(err)
|
||||
}
|
||||
}
|
||||
|
||||
/// The store when the system names no folder for it (no home folder): nothing installs.
|
||||
|
||||
@@ -4,6 +4,7 @@ use super::{
|
||||
AtomicBool, Condvar, Downloaded, Family, HashMap, Index, Installer, Mutex, Ordering, Path, PathBuf, Progress, RemoveRequest, StoreError,
|
||||
UserSource, err,
|
||||
};
|
||||
use super::{LegalText, PreviewServiceSource};
|
||||
|
||||
/// What a [`FakeStore`] was asked to do.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -35,6 +36,8 @@ pub struct FakeStore {
|
||||
/// Index files user sources "download", by URL.
|
||||
served_indexes: HashMap<String, Vec<u8>>,
|
||||
user: Mutex<Vec<UserSource>>,
|
||||
preview_service: Mutex<Option<String>>,
|
||||
previews: Mutex<bool>,
|
||||
/// User sources downloaded so far, and those whose file changed since.
|
||||
fetched: Mutex<Vec<String>>,
|
||||
changed: Mutex<Vec<String>>,
|
||||
@@ -55,6 +58,8 @@ impl FakeStore {
|
||||
builtin: None,
|
||||
served_indexes: HashMap::new(),
|
||||
user: Mutex::new(Vec::new()),
|
||||
preview_service: Mutex::new(None),
|
||||
previews: Mutex::new(true),
|
||||
fetched: Mutex::new(Vec::new()),
|
||||
changed: Mutex::new(Vec::new()),
|
||||
held: (Mutex::new(false), Condvar::new()),
|
||||
@@ -265,4 +270,45 @@ impl Installer for FakeStore {
|
||||
self.user.lock().map_err(err)?.retain(|s| s.url != url);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn preview_service(&self) -> Option<String> {
|
||||
self.preview_service.lock().ok()?.clone()
|
||||
}
|
||||
|
||||
fn preview_service_source(&self) -> PreviewServiceSource {
|
||||
if self.preview_service().is_some() { PreviewServiceSource::Saved } else { PreviewServiceSource::None }
|
||||
}
|
||||
|
||||
fn previews_enabled(&self) -> bool {
|
||||
self.previews.lock().map_or(true, |p| *p)
|
||||
}
|
||||
|
||||
fn set_previews_enabled(&self, enabled: bool) -> Result<(), StoreError> {
|
||||
*self.previews.lock().map_err(err)? = enabled;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_preview_service(&self, url: Option<&str>) -> Result<(), StoreError> {
|
||||
let url = url.map(craft_font_store::check_preview_service).transpose().map_err(err)?;
|
||||
*self.preview_service.lock().map_err(err)? = url;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn preview_cache(&self) -> Option<PathBuf> {
|
||||
Some(self.dir.join("previews"))
|
||||
}
|
||||
|
||||
/// Served from the file table by the index path, like a font.
|
||||
fn legal_text(&self, _: &Index, family: &Family, which: LegalText) -> Result<Option<String>, StoreError> {
|
||||
let path = match which {
|
||||
LegalText::License => family.license_file.as_ref().map(|f| f.path.as_str()).or(family.license_path.as_deref()),
|
||||
LegalText::Notice => family.notice_file.as_ref().map(|f| f.path.as_str()),
|
||||
};
|
||||
let Some(path) = path else { return Ok(None) };
|
||||
if !self.downloads_allowed() {
|
||||
return Err(StoreError("downloading fonts is turned off".into()));
|
||||
}
|
||||
let bytes = self.files.get(path).ok_or_else(|| StoreError(format!("{path} isn't available")))?;
|
||||
Ok(Some(String::from_utf8_lossy(bytes).into_owned()))
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,105 @@
|
||||
{
|
||||
"about": "Shared test vectors for font-preview-service (server, B2) and craft-font-manager's preview client (C3). Both must produce exactly these strings.",
|
||||
"rules": {
|
||||
"codepoints": "The codepoints of the text, minus C0 controls (< U+0020), C1 controls and DEL (U+007F-009F) and surrogates; deduplicated and sorted. Written as lowercase hex without leading zeros; a run of two or more consecutive codepoints is written first-last; items joined by commas. The empty set is the empty string. At most 256 codepoints.",
|
||||
"closure": "Server only: the codepoints above, plus the NFKD decomposition of each kept character, plus U+0020, U+200C, U+200D and U+25CC. Applied before subsetting; not part of the URL."
|
||||
},
|
||||
"vectors": [
|
||||
{
|
||||
"text": "Whereas recognition of the inherent dignity",
|
||||
"codepoints": "20,57,61,63-69,6e-6f,72-74,79",
|
||||
"closure": "20,57,61,63-69,6e-6f,72-74,79,200c-200d,25cc"
|
||||
},
|
||||
{
|
||||
"text": "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz",
|
||||
"codepoints": "20,41-5a,61-7a",
|
||||
"closure": "20,41-5a,61-7a,200c-200d,25cc"
|
||||
},
|
||||
{
|
||||
"text": "0123456789 & ? ! @ # % ( ) [ ] { } $ € £ ¥",
|
||||
"codepoints": "20-21,23-26,28-29,30-39,3f-40,5b,5d,7b,7d,a3,a5,20ac",
|
||||
"closure": "20-21,23-26,28-29,30-39,3f-40,5b,5d,7b,7d,a3,a5,200c-200d,20ac,25cc"
|
||||
},
|
||||
{
|
||||
"text": "aab",
|
||||
"codepoints": "61-62",
|
||||
"closure": "20,61-62,200c-200d,25cc"
|
||||
},
|
||||
{
|
||||
"text": "ab",
|
||||
"codepoints": "61-62",
|
||||
"closure": "20,61-62,200c-200d,25cc"
|
||||
},
|
||||
{
|
||||
"text": "abc",
|
||||
"codepoints": "61-63",
|
||||
"closure": "20,61-63,200c-200d,25cc"
|
||||
},
|
||||
{
|
||||
"text": "Line one\nLine two\t!",
|
||||
"codepoints": "20-21,4c,65,69,6e-6f,74,77",
|
||||
"closure": "20-21,4c,65,69,6e-6f,74,77,200c-200d,25cc"
|
||||
},
|
||||
{
|
||||
"text": "โดยที่การไม่นำพาและการหมิ่นในคุณค่าของสิทธิมนุษยชน",
|
||||
"codepoints": "e01-e02,e04,e07,e0a,e13-e14,e17-e19,e1e,e21-e23,e25,e29-e2b,e2d,e30,e32-e35,e38,e41-e44,e48",
|
||||
"closure": "20,e01-e02,e04,e07,e0a,e13-e14,e17-e19,e1e,e21-e23,e25,e29-e2b,e2d,e30,e32-e35,e38,e41-e44,e48,e4d,200c-200d,25cc"
|
||||
},
|
||||
{
|
||||
"text": "ສະບາຍດີ ນຳ",
|
||||
"codepoints": "20,e8d,e94,e99-e9a,eaa,eb0,eb2-eb3,eb5",
|
||||
"closure": "20,e8d,e94,e99-e9a,eaa,eb0,eb2-eb3,eb5,ecd,200c-200d,25cc"
|
||||
},
|
||||
{
|
||||
"text": "चूंकि मानव परिवार के सभी सदस्यों",
|
||||
"codepoints": "20,902,915,91a,926,928,92a,92d-930,935,938,93e-940,942,947,94b,94d",
|
||||
"closure": "20,902,915,91a,926,928,92a,92d-930,935,938,93e-940,942,947,94b,94d,200c-200d,25cc"
|
||||
},
|
||||
{
|
||||
"text": "لمّا كان الاعتراف بالكرامة",
|
||||
"codepoints": "20,627-62a,631,639,641,643-646,651",
|
||||
"closure": "20,627-62a,631,639,641,643-646,651,200c-200d,25cc"
|
||||
},
|
||||
{
|
||||
"text": "人類社会のすべての構成員",
|
||||
"codepoints": "3059,3066,306e,3079,4eba,4f1a,54e1,6210,69cb,793e,985e",
|
||||
"closure": "20,200c-200d,25cc,3059,3066,306e,3078-3079,3099,4eba,4f1a,54e1,6210,69cb,793e,985e"
|
||||
},
|
||||
{
|
||||
"text": "Œuvre fine ²",
|
||||
"codepoints": "20,65,6e,72,75-76,b2,152,fb01",
|
||||
"closure": "20,32,65-66,69,6e,72,75-76,b2,152,200c-200d,25cc,fb01"
|
||||
},
|
||||
{
|
||||
"text": "😀 👍🏽",
|
||||
"codepoints": "20,1f3fd,1f44d,1f600",
|
||||
"closure": "20,200c-200d,25cc,1f3fd,1f44d,1f600"
|
||||
},
|
||||
{
|
||||
"text": "",
|
||||
"codepoints": "",
|
||||
"closure": "20,200c-200d,25cc"
|
||||
}
|
||||
],
|
||||
"sample_hash": {
|
||||
"rule": "The {h} of /v1/faces/{sha256}/{inst}/sample-{h}.woff2: the first 12 lowercase hex characters of the sha256 of the face's sample text exactly as the index gives it (the file's sample_text, else samples[file.sample_script ?? family.sample_script].text), as UTF-8 bytes, with no normalisation and newlines kept. The subset itself also covers the family name; h covers only the sample text. A request whose h is not the face's current one gets 404; the client then falls back to u/{codepoints}.",
|
||||
"vectors": [
|
||||
{
|
||||
"text": "Whereas recognition of the inherent dignity",
|
||||
"h": "a79fe905fc38"
|
||||
},
|
||||
{
|
||||
"text": "โดยที่การไม่นำพาและการหมิ่นในคุณค่าของสิทธิมนุษยชน",
|
||||
"h": "ea9257b96f35"
|
||||
},
|
||||
{
|
||||
"text": "𐊪𐊾𐊠𐊽𐊾𐊲𐊸𐊫𐊷𐋉𐋃𐊷𐊲𐊷𐊲𐊰𐊫𐋇𐊫𐊰𐊪𐊫𐊣\n𐊪𐊾𐊠𐊽𐊾𐊲𐊸𐊫𐊷𐋉𐋃𐊷𐊲𐊷𐊲𐊰𐊫𐋇𐊫𐊰𐊪𐊫𐊣",
|
||||
"h": "259046b056a5"
|
||||
},
|
||||
{
|
||||
"text": "Hello",
|
||||
"h": "185f8db32271"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
//! The preview service client against the shared test vectors and a local fake service.
|
||||
//!
|
||||
//! `data/Tiny-glyf.woff2` is `crates/fonts-build/tests/fixture/subset/Tiny-glyf.ttf` compressed
|
||||
//! with fontTools 4.67.0: `fonttools ttLib.woff2 compress -o Tiny-glyf.woff2 Tiny-glyf.ttf`.
|
||||
//! `data/preview-vectors.json` is shared with the preview service, unchanged, so the client's
|
||||
//! URLs and the service's cache keys can't drift.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Condvar, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use craft_font_manager::craft_font_catalog::Os;
|
||||
use craft_font_manager::remote::{Codepoints, DiskCache, Instance, MAX_CODEPOINTS, Preview, PreviewError, PreviewKey, Previews, SampleHash, Subset};
|
||||
use craft_font_manager::store::{FakeStore, Installer, SuiteStore};
|
||||
use craft_font_manager::{Catalog, FontEnv};
|
||||
use craft_font_store::{Client, is_font};
|
||||
|
||||
const WOFF2: &[u8] = include_bytes!("data/Tiny-glyf.woff2");
|
||||
|
||||
fn sha(n: u8) -> String {
|
||||
format!("{n:02x}").repeat(32)
|
||||
}
|
||||
|
||||
fn temp(name: &str) -> PathBuf {
|
||||
let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("remote").join(name);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_codepoints_match_the_shared_vectors() {
|
||||
let vectors: serde_json::Value = serde_json::from_str(include_str!("data/preview-vectors.json")).unwrap();
|
||||
let vectors = vectors["vectors"].as_array().unwrap();
|
||||
assert!(vectors.len() > 10);
|
||||
for v in vectors {
|
||||
let text = v["text"].as_str().unwrap();
|
||||
let expected = v["codepoints"].as_str().unwrap();
|
||||
let codepoints = Codepoints::from_text(text);
|
||||
assert_eq!(codepoints.encode(), expected, "{text:?}");
|
||||
let key = PreviewKey::new(&sha(0xab), Instance::List, Subset::Codepoints(codepoints));
|
||||
match key {
|
||||
Some(key) => assert_eq!(key.path(), format!("v1/faces/{}/list/u/{expected}.woff2", sha(0xab))),
|
||||
None => assert_eq!(expected, "", "only the empty set has no URL"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subset_urls() {
|
||||
let key = |inst, subset| PreviewKey::new(&sha(0x0a), inst, subset).map(|k| k.url("https://fonts.example.com/"));
|
||||
let base = format!("https://fonts.example.com/v1/faces/{}", sha(0x0a));
|
||||
assert_eq!(key(Instance::List, Subset::Sample(SampleHash::of("Hello"))), Some(format!("{base}/list/sample-185f8db32271.woff2")));
|
||||
assert_eq!(key(Instance::List, Subset::Ascii), Some(format!("{base}/list/ascii.woff2")));
|
||||
assert_eq!(key(Instance::Var, Subset::Sample(SampleHash::of("Hello"))), Some(format!("{base}/var/sample-185f8db32271.woff2")));
|
||||
assert_eq!(key(Instance::Var, Subset::Codepoints(Codepoints::from_text("ab"))), Some(format!("{base}/var/u/61-62.woff2")));
|
||||
|
||||
let upper = PreviewKey::new(&"AB".repeat(32), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap();
|
||||
assert_eq!(upper.sha256(), "ab".repeat(32));
|
||||
assert!(PreviewKey::new("../../etc", Instance::List, Subset::Sample(SampleHash::of("Hello"))).is_none());
|
||||
assert!(PreviewKey::new(&"g".repeat(64), Instance::List, Subset::Sample(SampleHash::of("Hello"))).is_none());
|
||||
let many: Codepoints = ('\u{4e00}'..).take(MAX_CODEPOINTS + 1).collect();
|
||||
assert!(PreviewKey::new(&sha(1), Instance::List, Subset::Codepoints(many.clone())).is_none());
|
||||
let mut fits = many;
|
||||
fits.retain(|c| c != '\u{4e00}');
|
||||
assert!(PreviewKey::new(&sha(1), Instance::List, Subset::Codepoints(fits)).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disk_cache_drops_the_least_recently_used() {
|
||||
let dir = temp("cache");
|
||||
let cache = DiskCache::new(&dir, 300);
|
||||
let bytes = |b: u8| vec![b; 100];
|
||||
cache.put("a", &bytes(1));
|
||||
cache.put("b", &bytes(2));
|
||||
cache.put("c", &bytes(3));
|
||||
assert_eq!(cache.get("a"), Some(bytes(1)));
|
||||
cache.put("d", &bytes(4));
|
||||
assert!(!cache.contains("b"), "b was used least recently");
|
||||
assert!(cache.contains("a") && cache.contains("c") && cache.contains("d"));
|
||||
assert_eq!(cache.size(), 300);
|
||||
assert_eq!(cache.get("b"), None);
|
||||
|
||||
// Larger than the whole cache: not kept, and nothing else goes for it.
|
||||
cache.put("e", &vec![5; 301]);
|
||||
assert!(!cache.contains("e") && cache.contains("a"));
|
||||
|
||||
// Another session reads the same entries, and a smaller limit trims them at once.
|
||||
std::fs::write(dir.join(".tmp-1-1"), b"half").unwrap();
|
||||
let files = || std::fs::read_dir(&dir).unwrap().filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().ends_with(".woff2")).count();
|
||||
assert_eq!(files(), 3);
|
||||
let again = DiskCache::new(&dir, 300);
|
||||
assert_eq!(again.size(), 300);
|
||||
assert_eq!(again.get("d"), Some(bytes(4)));
|
||||
let smaller = DiskCache::new(&dir, 200);
|
||||
assert_eq!(smaller.size(), 200);
|
||||
assert_eq!(files(), 2);
|
||||
// A file another session cached after this one read the folder.
|
||||
smaller.put("f", &bytes(6));
|
||||
assert!(again.contains("f"));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// What the fake service answers for a path.
|
||||
#[derive(Clone)]
|
||||
enum Reply {
|
||||
Ok(Vec<u8>),
|
||||
/// Waits for [`Service::release`], then answers with the fixture.
|
||||
Held,
|
||||
}
|
||||
|
||||
/// A local HTTP server standing in for the preview service.
|
||||
struct Service {
|
||||
base: String,
|
||||
routes: Arc<Mutex<HashMap<String, Reply>>>,
|
||||
log: Arc<Mutex<Vec<String>>>,
|
||||
gate: Arc<(Mutex<bool>, Condvar)>,
|
||||
}
|
||||
|
||||
impl Service {
|
||||
fn start() -> Service {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let base = format!("http://{}", listener.local_addr().unwrap());
|
||||
let service = Service { base, routes: Arc::default(), log: Arc::default(), gate: Arc::default() };
|
||||
let (routes, log, gate) = (service.routes.clone(), service.log.clone(), service.gate.clone());
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(stream) = stream else { continue };
|
||||
let (routes, log, gate) = (routes.clone(), log.clone(), gate.clone());
|
||||
std::thread::spawn(move || answer(stream, &routes, &log, &gate));
|
||||
}
|
||||
});
|
||||
service
|
||||
}
|
||||
|
||||
fn serve(&self, key: &PreviewKey, reply: Reply) {
|
||||
self.routes.lock().unwrap().insert(format!("/{}", key.path()), reply);
|
||||
}
|
||||
|
||||
fn requests(&self) -> Vec<String> {
|
||||
self.log.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
fn release(&self) {
|
||||
*self.gate.0.lock().unwrap() = true;
|
||||
self.gate.1.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
fn answer(mut s: TcpStream, routes: &Mutex<HashMap<String, Reply>>, log: &Mutex<Vec<String>>, gate: &(Mutex<bool>, Condvar)) {
|
||||
let mut head = Vec::new();
|
||||
let mut b = [0u8; 1];
|
||||
while !head.ends_with(b"\r\n\r\n") {
|
||||
match s.read(&mut b) {
|
||||
Ok(1) => head.push(b[0]),
|
||||
_ => return,
|
||||
}
|
||||
}
|
||||
let path = String::from_utf8_lossy(&head).split_whitespace().nth(1).unwrap_or("/").to_string();
|
||||
log.lock().unwrap().push(path.clone());
|
||||
let reply = routes.lock().unwrap().get(&path).cloned();
|
||||
let body = match reply {
|
||||
Some(Reply::Ok(body)) => body,
|
||||
Some(Reply::Held) => {
|
||||
let mut open = gate.0.lock().unwrap();
|
||||
while !*open {
|
||||
open = gate.1.wait(open).unwrap();
|
||||
}
|
||||
WOFF2.to_vec()
|
||||
}
|
||||
None => {
|
||||
let _ = write!(s, "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Type: font/woff2\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
|
||||
let _ = s.write_all(&body);
|
||||
}
|
||||
|
||||
/// The results until `n` have come, or two seconds.
|
||||
fn wait_for(previews: &Previews, n: usize) -> Vec<Preview> {
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
let mut out = Vec::new();
|
||||
while out.len() < n && Instant::now() < deadline {
|
||||
out.extend(previews.poll());
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn wait_until(mut done: impl FnMut() -> bool) {
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
while !done() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn previews_come_from_the_service_then_the_cache_and_only_with_consent() {
|
||||
let service = Service::start();
|
||||
let dir = temp("service");
|
||||
let store = Arc::new(FakeStore::new(&dir, HashMap::new()));
|
||||
let sample = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap();
|
||||
let broken = PreviewKey::new(&sha(2), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap();
|
||||
service.serve(&sample, Reply::Ok(WOFF2.to_vec()));
|
||||
service.serve(&broken, Reply::Ok(b"wOF2 but not really".to_vec()));
|
||||
let previews = Previews::new(store.clone());
|
||||
|
||||
// No service: nothing happens.
|
||||
assert!(!previews.available());
|
||||
previews.request(sample.clone(), 1);
|
||||
let got = wait_for(&previews, 1);
|
||||
assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::NoService));
|
||||
|
||||
// A service, but previews off: no request.
|
||||
store.set_preview_service(Some(&service.base)).unwrap();
|
||||
store.set_previews_enabled(false).unwrap();
|
||||
assert!(!previews.available());
|
||||
previews.request(sample.clone(), 1);
|
||||
let got = wait_for(&previews, 1);
|
||||
assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::PreviewsOff));
|
||||
assert!(service.requests().is_empty());
|
||||
|
||||
// Previews on (the default), installs not allowed: decoded, checked and cached anyway.
|
||||
store.set_previews_enabled(true).unwrap();
|
||||
assert!(previews.available() && !store.downloads_allowed());
|
||||
previews.request(sample.clone(), 1);
|
||||
previews.request(broken.clone(), 1);
|
||||
let got = wait_for(&previews, 2);
|
||||
let font = |key: &PreviewKey| got.iter().find(|p| &p.key == key).map(|p| p.font.clone());
|
||||
assert!(font(&sample).unwrap().is_ok_and(|f| is_font(&f)));
|
||||
assert_eq!(font(&broken), Some(Err(PreviewError::NotAFont)));
|
||||
assert_eq!(service.requests().len(), 2);
|
||||
let cache = previews.cache().unwrap();
|
||||
assert!(cache.dir().starts_with(&dir) && cache.contains(&sample.path()) && !cache.contains(&broken.path()));
|
||||
|
||||
// A new session reads the disk cache, even with previews off.
|
||||
store.set_previews_enabled(false).unwrap();
|
||||
let later = Previews::new(store.clone());
|
||||
later.request(sample.clone(), 1);
|
||||
assert!(wait_for(&later, 1).first().is_some_and(|p| p.font.as_ref().is_ok_and(|f| is_font(f))));
|
||||
assert_eq!(service.requests().len(), 2);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_suite_store_and_its_previews_share_the_service_down_state() {
|
||||
let root = temp("suite");
|
||||
let env = FontEnv { os: Os::Unix, root: root.clone(), font_store: Some(root.join("store")), ..FontEnv::default() };
|
||||
let store = SuiteStore::for_user(Arc::new(Catalog::new(env).with_font_service(false))).unwrap();
|
||||
let client = store.http_client().unwrap();
|
||||
let svc = "https://fonts.example.com";
|
||||
assert!(!client.service_is_down(svc) && !store.client().service_is_down(svc));
|
||||
client.mark_service_down(svc);
|
||||
assert!(store.client().service_is_down(svc));
|
||||
// The pool's client has its own timeouts and the same down state.
|
||||
let pool_client = client.with_timeouts(craft_font_store::Timeouts::default());
|
||||
assert!(pool_client.service_is_down(svc));
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_service_marked_down_gets_no_requests() {
|
||||
let service = Service::start();
|
||||
let dir = temp("down");
|
||||
let store = Arc::new(FakeStore::new(&dir, HashMap::new()));
|
||||
store.set_preview_service(Some(&service.base)).unwrap();
|
||||
store.allow_downloads(true).unwrap();
|
||||
let key = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap();
|
||||
service.serve(&key, Reply::Ok(WOFF2.to_vec()));
|
||||
// The client is shared with, say, the store's installs, which found the service unreachable.
|
||||
let client = Client::default();
|
||||
client.mark_service_down(&service.base);
|
||||
let previews = Previews::new(store.clone()).with_fetcher(Arc::new(client));
|
||||
previews.request(key, 1);
|
||||
let got = wait_for(&previews, 1);
|
||||
assert!(matches!(got.first().map(|p| p.font.clone()), Some(Err(PreviewError::Failed(_)))));
|
||||
assert!(service.requests().is_empty());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highest_priority_first_and_cancelled_requests_deliver_nothing() {
|
||||
let service = Service::start();
|
||||
let dir = temp("cancel");
|
||||
let store = Arc::new(FakeStore::new(&dir, HashMap::new()));
|
||||
store.allow_downloads(true).unwrap();
|
||||
store.set_preview_service(Some(&service.base)).unwrap();
|
||||
let keys: Vec<PreviewKey> = (1..=4).map(|n| PreviewKey::new(&sha(n), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap()).collect();
|
||||
let [held, low, high, dropped] = [&keys[0], &keys[1], &keys[2], &keys[3]];
|
||||
service.serve(held, Reply::Held);
|
||||
for key in [low, high, dropped] {
|
||||
service.serve(key, Reply::Ok(WOFF2.to_vec()));
|
||||
}
|
||||
let previews = Previews::new(store.clone()).with_cache(None).with_workers(1);
|
||||
|
||||
previews.request(held.clone(), 9);
|
||||
wait_until(|| !service.requests().is_empty());
|
||||
previews.request(low.clone(), 1);
|
||||
previews.request(dropped.clone(), 1);
|
||||
previews.request(high.clone(), 5);
|
||||
assert_eq!(previews.pending(), 4);
|
||||
previews.cancel(dropped);
|
||||
assert!(!previews.is_pending(dropped));
|
||||
// The running request stops while the service still sends nothing.
|
||||
previews.cancel(held);
|
||||
|
||||
let got = wait_for(&previews, 2);
|
||||
assert_eq!(got.iter().map(|p| &p.key).collect::<Vec<_>>(), [high, low]);
|
||||
let path = |k: &PreviewKey| format!("/{}", k.path());
|
||||
assert_eq!(service.requests(), [path(held), path(high), path(low)]);
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
assert!(previews.poll().is_empty());
|
||||
assert_eq!(previews.pending(), 0);
|
||||
service.release();
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sample_hash_is_the_sha256_prefix_of_the_exact_text() {
|
||||
let vectors: serde_json::Value = serde_json::from_str(include_str!("data/preview-vectors.json")).unwrap();
|
||||
let vectors = vectors["sample_hash"]["vectors"].as_array().unwrap();
|
||||
assert!(vectors.len() >= 4);
|
||||
for v in vectors {
|
||||
let text = v["text"].as_str().unwrap();
|
||||
assert_eq!(SampleHash::of(text).as_str(), v["h"].as_str().unwrap(), "{text:?}");
|
||||
}
|
||||
assert_ne!(SampleHash::of("Hello\n"), SampleHash::of("Hello"));
|
||||
let a = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("a"))).unwrap();
|
||||
let b = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("b"))).unwrap();
|
||||
assert_ne!(a.path(), b.path(), "the disk cache key names the text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_404_comes_back_as_not_found() {
|
||||
let service = Service::start();
|
||||
let dir = temp("notfound");
|
||||
let store = Arc::new(FakeStore::new(&dir, HashMap::new()));
|
||||
store.set_preview_service(Some(&service.base)).unwrap();
|
||||
let key = PreviewKey::new(&sha(1), Instance::List, Subset::Sample(SampleHash::of("Hello"))).unwrap();
|
||||
let previews = Previews::new(store.clone());
|
||||
previews.request(key, 1);
|
||||
let got = wait_for(&previews, 1);
|
||||
assert_eq!(got.first().map(|p| p.font.clone().unwrap_err()), Some(PreviewError::NotFound));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
@@ -25,10 +25,13 @@ A source the user adds is an index file at an https URL (`.json` or `.json.gz`).
|
||||
|
||||
| Rule | How |
|
||||
|---|---|
|
||||
| Off until the user turns it on | `FontStore::network()` is `Network::Off` until `enable_network()`. The setting is `settings.json` in the store folder, so it holds for every app. |
|
||||
| Off until the user turns it on | `FontStore::network()` is `Network::Off` until `enable_network()`. The setting is `settings.json` in the store folder, so it holds for every app. A host may give its own default for a user who hasn't chosen (`FontStore::with_default_network`); it is never saved, and the user's `enable_network()` or `disable_network()` beats it. A `settings.json` that exists but can't be read, is too large or doesn't parse reads as `Network::Off`, whatever the host's default, and the next saved setting starts from that. |
|
||||
| Only the user turns it on | `FontStore::for_user` is for the app's own interface; call `enable_network()` from a setting or from the user's Install click. `FontStore::for_agent` (MCP, CLI, scripting) gets `Error::NotAllowed`. An agent can install while the user has the network on. |
|
||||
| No requests at startup | Nothing in the crate makes a request on its own. Only `fetch_indexes` and the installs do, and they return `Error::NetworkOff` without one while the network is off. |
|
||||
| One HTTP client | `Client`: ureq with rustls and the webpki roots, HTTPS only, no cookies, `User-Agent: craft-font-store/<version>`. Timeouts: 15 s to connect, 30 s to the response headers, 10 minutes per file. |
|
||||
| Optional preview service | Off unless set: craft-libs has no default address. `CRAFT_FONT_PREVIEW_URL`, else the `preview_service` field of `settings.json` (`FontStore::set_preview_service`, user only, `Error::NotAllowed` for an agent), else the host's default (`FontStore::with_default_preview_service`), which is never saved, so clearing the setting brings it back and other apps sharing the store don't see it. `FontStore::preview_service()` returns the one in effect and `preview_service_source()` says whether it is `Env`, `Saved`, `Default` or `None`; the variable's name is `PREVIEW_SERVICE_ENV`. A `settings.json` that exists but can't be read or parsed means no saved service and no host default. Installs and `legal_text` try the service's mirror only for curated families (the built-in sources, `Family::is_curated`), so the hashes of files from sources the user added are never sent to it. https only; http is accepted only for the addresses `127.0.0.1` and `::1`, never for a host name, which a resolver can point off the machine. A trailing slash is dropped. Example: `CRAFT_FONT_PREVIEW_URL=https://fonts.example.com`. |
|
||||
| Previews setting | `previews` in `settings.json`, on by default: `FontStore::previews_enabled()`, `set_previews_enabled(bool)` (user only, `Error::NotAllowed` for an agent). The app fetches previews from a set service only while it is on; installs ignore it. |
|
||||
| Mirror first | With a service set, an install requests `<service>/v1/files/<sha256>` for each font file and `<service>/v1/licences/<sha256>` for a licence (when the index gives its sha256) before the index's URLs. The size and sha256 checks are the same, and a response that fails them moves on to the next URL. |
|
||||
| One HTTP client | `Client`: ureq with rustls and the webpki roots, HTTPS only (plain http only to `127.0.0.1` or `::1`, following no redirects, for a preview service run locally), no cookies, `User-Agent: craft-font-store/<version>`. Timeouts: 15 s to connect, 30 s to the response headers, 10 minutes per file. |
|
||||
|
||||
A file's URLs come from its source's URL templates, best first. Both built-in sources use `https://cdn.jsdelivr.net/gh/{repo}@{ref}/{path}`, then `https://raw.githubusercontent.com/{repo}/{ref}/{path}`. The store tries the next URL after any failure: a network error, an HTTP error (jsDelivr answers 403 for files over 20 MB, such as the Noto Serif CJK fonts), or bytes that don't verify.
|
||||
|
||||
@@ -52,6 +55,10 @@ Reading checks every entry: the version (a major version other than 1 is refused
|
||||
| `index.sources()`, `index.source_of(family)` | Each source's name, homepage, curated flag, commit, and families left out with why. |
|
||||
| `family.source`, `family.is_curated()` | The family's source ID, and whether that source is curated. |
|
||||
| `index.file_urls(family, file)`, `index.license_urls(family)` | The URLs to try, best first. |
|
||||
| `family.tags`, `family.copyright`, `family.reserved_names`, `family.notice_file`, `family.upstream` | Format 1.2: design traits, the copyright notice, the Reserved Font Names (a client that modifies a font renames it when there are any), an Apache family's `NOTICE` file and where the family is developed. Absent in a 1.1 index: empty or `None`. |
|
||||
| `file.instances`, `file.list_instance` | Format 1.2: a variable font's named instances, and the position of the one a font list shows (`None`: the default instance). |
|
||||
| `index.samples()`, `index.sample(script)` | Format 1.2: the default preview text of each script. When sources have one for the same script, the first source's wins. |
|
||||
| `index.sample_text(family, file)` | The file's preview text: its own `sample_text`, else the sample of its `sample_script`, else of the family's `sample_script`. |
|
||||
|
||||
## Exact matches only
|
||||
|
||||
@@ -93,6 +100,7 @@ When every file has passed, the store takes `.lock`, moves the files into the fa
|
||||
settings.json the network setting and the sources the user added
|
||||
manifest.json what is installed
|
||||
indexes/ the last indexes fetched: sources.json, <source>.json.gz, user-<hash>
|
||||
previews/ preview subsets (WOFF2) craft-font-manager caches, at most 50 MB
|
||||
<family folder>/ the font files and the licence
|
||||
language-packs/ installed Language packs, one folder per locale
|
||||
language-packs.json which Language packs are installed
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,4 +1,4 @@
|
||||
{"schema":1,"version":"1.1","indexes":[
|
||||
{"source":"google/fonts","name":"Google Fonts","curated":true,"path":"indexes/google-fonts.json","size":4724581,"sha256":"72ea418e43785d572e73350ad08e9e6601a5a12f93315805f92bd3e092618a63","gz_path":"indexes/google-fonts.json.gz","gz_size":596893,"gz_sha256":"62d1d5645417a691e4710f6d1b895f925284ea9c804de268a97432bd67e9c1f6","commit":"45e3d5269e4a17d823f6d84470bc084dc5ae46f6","families":2040,"files":3781},
|
||||
{"source":"notofonts","name":"Noto","curated":true,"path":"indexes/noto.json","size":117706,"sha256":"8243d697c407776ec4fb19fa892c089279a4a528eb4e04cd970ac6ec14ce142a","gz_path":"indexes/noto.json.gz","gz_size":18192,"gz_sha256":"0d467fb79bcd3afe10350ed3caba2ff57af02aedbc413292e06bc78c02994999","commit":"93fac8abebe6c7fed0c5b7d2456d8fa484fa146c","families":30,"files":130}
|
||||
{"schema":1,"version":"1.2","indexes":[
|
||||
{"source":"google/fonts","name":"Google Fonts","curated":true,"path":"indexes/google-fonts.json","size":5672345,"sha256":"89ec33d9c7644963f24c9d749787af85c347b94c3586a5f3a5bd22fe6ae6f8eb","gz_path":"indexes/google-fonts.json.gz","gz_size":721528,"gz_sha256":"85e0678cd48f381e858e6728fd93d865e0f502caa12cec4354e954a27bec82f2","commit":"45e3d5269e4a17d823f6d84470bc084dc5ae46f6","families":2040,"files":3781},
|
||||
{"source":"notofonts","name":"Noto","curated":true,"path":"indexes/noto.json","size":123691,"sha256":"3c9a615d287f9a4e5a745ce94748dd10dbbcf4eb75370e98456e47534629da55","gz_path":"indexes/noto.json.gz","gz_size":19722,"gz_sha256":"0ffe5e43faa4a3d8218faf3bb97145493760ec74c5779f973f0812fd98b05fcb","commit":"93fac8abebe6c7fed0c5b7d2456d8fa484fa146c","families":30,"files":130}
|
||||
]}
|
||||
+121
-15
@@ -1,11 +1,13 @@
|
||||
//! The one HTTP client: blocking HTTPS GET through ureq with rustls, timeouts, a size cap,
|
||||
//! progress and cancellation.
|
||||
//! progress and cancellation. Plain http only to a loopback host, and only when the caller opts
|
||||
//! in for a preview service run locally.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::Read;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{self, RecvTimeoutError};
|
||||
use std::time::Duration;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// Cancels a download from another thread. Clones share the flag.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -47,6 +49,14 @@ impl Default for Timeouts {
|
||||
}
|
||||
}
|
||||
|
||||
impl FetchError {
|
||||
/// Whether the server couldn't be reached or didn't answer in time, as opposed to answering
|
||||
/// with an HTTP status or too much data.
|
||||
pub fn is_network(&self) -> bool {
|
||||
matches!(self, FetchError::Failed(m) if !m.starts_with("HTTP "))
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a request failed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum FetchError {
|
||||
@@ -64,13 +74,34 @@ pub enum FetchError {
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
/// How long a preview service that failed on the network is skipped.
|
||||
pub const SERVICE_BACKOFF: Duration = Duration::from_secs(60);
|
||||
|
||||
/// `scheme://host:port` of `url`, lowercased.
|
||||
fn service_origin(url: &str) -> String {
|
||||
let (scheme, rest) = url.split_once("://").unwrap_or(("", url));
|
||||
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
|
||||
format!("{}://{}", scheme.to_ascii_lowercase(), authority.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
fn now_millis() -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64)
|
||||
}
|
||||
|
||||
/// The User-Agent every request sends: the crate and its version, nothing about the user.
|
||||
pub const USER_AGENT: &str = concat!("craft-font-store/", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
/// The HTTP client. HTTPS only; no cookies, no credentials.
|
||||
/// The HTTP client. HTTPS only, except [`Client::get_from_service`], which also speaks plain
|
||||
/// http to `127.0.0.1` or `::1`; no cookies, no credentials.
|
||||
#[derive(Clone)]
|
||||
pub struct Client {
|
||||
agent: ureq::Agent,
|
||||
/// For `http://` to a loopback host. It follows no redirects, so it never leaves the machine.
|
||||
loopback: ureq::Agent,
|
||||
/// The origins of preview services that failed on the network, each with when it may be
|
||||
/// tried again. Clones share it.
|
||||
service_down: Arc<Mutex<HashMap<String, u64>>>,
|
||||
https_only: bool,
|
||||
/// URL prefixes the tests serve from a local server.
|
||||
#[cfg(test)]
|
||||
pub(crate) rewrite: Vec<(String, String)>,
|
||||
@@ -95,17 +126,26 @@ impl Client {
|
||||
}
|
||||
|
||||
fn build(t: Timeouts, https_only: bool) -> Self {
|
||||
let config = ureq::Agent::config_builder()
|
||||
.https_only(https_only)
|
||||
.user_agent(USER_AGENT)
|
||||
.timeout_connect(Some(t.connect))
|
||||
.timeout_recv_response(Some(t.response))
|
||||
.timeout_global(Some(t.overall))
|
||||
.max_redirects(3)
|
||||
.http_status_as_error(true)
|
||||
.build();
|
||||
let agent = |https_only: bool, redirects: u32| {
|
||||
let builder = ureq::Agent::config_builder();
|
||||
// A loopback request never goes through an environment proxy.
|
||||
let builder = if https_only || redirects > 0 { builder } else { builder.proxy(None) };
|
||||
let config = builder
|
||||
.https_only(https_only)
|
||||
.user_agent(USER_AGENT)
|
||||
.timeout_connect(Some(t.connect))
|
||||
.timeout_recv_response(Some(t.response))
|
||||
.timeout_global(Some(t.overall))
|
||||
.max_redirects(redirects)
|
||||
.http_status_as_error(true)
|
||||
.build();
|
||||
ureq::Agent::new_with_config(config)
|
||||
};
|
||||
Self {
|
||||
agent: ureq::Agent::new_with_config(config),
|
||||
agent: agent(https_only, 3),
|
||||
loopback: agent(false, 0),
|
||||
service_down: Arc::new(Mutex::new(HashMap::new())),
|
||||
https_only,
|
||||
#[cfg(test)]
|
||||
rewrite: Vec::new(),
|
||||
}
|
||||
@@ -117,6 +157,18 @@ impl Client {
|
||||
Self::build(t, false)
|
||||
}
|
||||
|
||||
/// A client with other timeouts that shares this one's preview-service down state, so a
|
||||
/// pool with short timeouts (previews) and the installs agree on which service is down.
|
||||
pub fn with_timeouts(&self, timeouts: Timeouts) -> Client {
|
||||
let fresh = Self::build(timeouts, self.https_only);
|
||||
Client {
|
||||
service_down: Arc::clone(&self.service_down),
|
||||
#[cfg(test)]
|
||||
rewrite: self.rewrite.clone(),
|
||||
..fresh
|
||||
}
|
||||
}
|
||||
|
||||
/// Plain `http://` to a local test server, with `https://` prefixes mapped onto it.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn for_tests(t: Timeouts, rewrite: Vec<(String, String)>) -> Self {
|
||||
@@ -136,12 +188,52 @@ impl Client {
|
||||
/// GETs `url`, at most `max` bytes, calling `on_bytes` with the bytes read so far. The
|
||||
/// request runs on a helper thread, so `cancel` stops it even while the server sends nothing.
|
||||
pub fn get(&self, url: &str, max: u64, cancel: &Cancel, on_bytes: &mut dyn FnMut(u64)) -> Result<Vec<u8>, FetchError> {
|
||||
self.request(url, max, cancel, on_bytes, false)
|
||||
}
|
||||
|
||||
/// [`Client::get`] for a URL built from the validated preview-service setting: plain `http://`
|
||||
/// to a loopback host is allowed, without following redirects. Never call it with a URL from
|
||||
/// an index or a user source.
|
||||
///
|
||||
/// After a network failure (no connection, a timeout; not an HTTP status) that service (its
|
||||
/// scheme, host and port) counts as down for [`SERVICE_BACKOFF`]: calls in that time fail at once, so a service that is off
|
||||
/// doesn't make every request wait out the timeouts. Clones of the client share this.
|
||||
pub fn get_from_service(&self, url: &str, max: u64, cancel: &Cancel, on_bytes: &mut dyn FnMut(u64)) -> Result<Vec<u8>, FetchError> {
|
||||
if self.service_is_down(url) {
|
||||
return Err(FetchError::Failed("the preview service is down".into()));
|
||||
}
|
||||
let got = self.request(url, max, cancel, on_bytes, true);
|
||||
if got.as_ref().is_err_and(FetchError::is_network) {
|
||||
self.mark_service_down(url);
|
||||
}
|
||||
got
|
||||
}
|
||||
|
||||
/// Whether a network failure of the preview service at `service` (its URL or any URL on it)
|
||||
/// is recent enough to skip it. Another service is not down.
|
||||
pub fn service_is_down(&self, service: &str) -> bool {
|
||||
let down = self.service_down.lock().unwrap_or_else(|e| e.into_inner());
|
||||
down.get(&service_origin(service)).is_some_and(|until| now_millis() < *until)
|
||||
}
|
||||
|
||||
/// Marks the preview service at `service` as down for [`SERVICE_BACKOFF`].
|
||||
pub fn mark_service_down(&self, service: &str) {
|
||||
let until = now_millis() + SERVICE_BACKOFF.as_millis() as u64;
|
||||
let mut down = self.service_down.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let now = now_millis();
|
||||
down.retain(|_, until| now < *until);
|
||||
down.insert(service_origin(service), until);
|
||||
}
|
||||
|
||||
fn request(&self, url: &str, max: u64, cancel: &Cancel, on_bytes: &mut dyn FnMut(u64), allow_loopback_http: bool) -> Result<Vec<u8>, FetchError> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(FetchError::Cancelled);
|
||||
}
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let (agent, url, flag) = (self.agent.clone(), self.url(url), Arc::clone(&stop));
|
||||
let url = self.url(url);
|
||||
let agent = if allow_loopback_http && is_loopback_http(&url) { self.loopback.clone() } else { self.agent.clone() };
|
||||
let flag = Arc::clone(&stop);
|
||||
std::thread::Builder::new()
|
||||
.name("font-store-fetch".into())
|
||||
.spawn(move || {
|
||||
@@ -168,6 +260,20 @@ impl Client {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `url` is `http://` to `127.0.0.1` or `[::1]`.
|
||||
pub(crate) fn is_loopback_http(url: &str) -> bool {
|
||||
let Some(rest) = url.get(..7).filter(|s| s.eq_ignore_ascii_case("http://")).and_then(|_| url.get(7..)) else { return false };
|
||||
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
|
||||
if authority.contains('@') {
|
||||
return false;
|
||||
}
|
||||
let host = match authority.strip_prefix('[') {
|
||||
Some(v6) => v6.split(']').next().unwrap_or_default(),
|
||||
None => authority.split(':').next().unwrap_or_default(),
|
||||
};
|
||||
matches!(host.to_ascii_lowercase().as_str(), "127.0.0.1" | "::1")
|
||||
}
|
||||
|
||||
enum Msg {
|
||||
Bytes(u64),
|
||||
Done(Result<Vec<u8>, FetchError>),
|
||||
|
||||
@@ -76,6 +76,29 @@ pub struct Script {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// A script's default preview text.
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize)]
|
||||
pub struct Sample {
|
||||
/// The text: a sentence for `udhr`, the poem for `iroha`, characters for `exemplar`.
|
||||
pub text: String,
|
||||
/// Where it comes from: `udhr`, `iroha` or `exemplar`.
|
||||
#[serde(default)]
|
||||
pub method: String,
|
||||
/// The gflanguages ID of the text's language.
|
||||
#[serde(default)]
|
||||
pub language: String,
|
||||
}
|
||||
|
||||
/// A named instance of a variable font.
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize)]
|
||||
pub struct Instance {
|
||||
/// The instance's subfamily name (`Bold`).
|
||||
pub name: String,
|
||||
/// The user coordinate of each axis, by axis tag.
|
||||
#[serde(default)]
|
||||
pub coordinates: BTreeMap<String, f32>,
|
||||
}
|
||||
|
||||
/// A variation axis of a font file.
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize)]
|
||||
pub struct Axis {
|
||||
@@ -110,6 +133,19 @@ pub struct FontFile {
|
||||
/// PostScript names: the face's and, for a variable font, each named instance's.
|
||||
#[serde(default)]
|
||||
pub postscript: Vec<String>,
|
||||
/// Format 1.2: a variable font's named instances, in font order; empty for a static font.
|
||||
#[serde(default)]
|
||||
pub instances: Vec<Instance>,
|
||||
/// Format 1.2: the instance a font list shows, as a position in `instances`; none when the
|
||||
/// list shows the default instance.
|
||||
#[serde(default)]
|
||||
pub list_instance: Option<usize>,
|
||||
/// Format 1.2: the file's own preview script, when not the family's `sample_script`.
|
||||
#[serde(default)]
|
||||
pub sample_script: Option<String>,
|
||||
/// Format 1.2: the file's own preview text, when no script sample fits it.
|
||||
#[serde(default)]
|
||||
pub sample_text: Option<String>,
|
||||
/// The repository holding the file, when not the family's.
|
||||
#[serde(default)]
|
||||
pub repo: Option<String>,
|
||||
@@ -216,6 +252,25 @@ pub struct Family {
|
||||
/// The licence file, with its size and sha256.
|
||||
#[serde(default)]
|
||||
pub license_file: Option<LicenseFile>,
|
||||
/// Format 1.2: design traits, sorted, from the index's tag vocabulary.
|
||||
#[serde(default)]
|
||||
pub tags: Vec<String>,
|
||||
/// Format 1.2: the script whose sample previews the family.
|
||||
#[serde(default)]
|
||||
pub sample_script: Option<String>,
|
||||
/// Format 1.2: the copyright notice.
|
||||
#[serde(default)]
|
||||
pub copyright: Option<String>,
|
||||
/// Format 1.2: the Reserved Font Names the OFL notice declares. A client that modifies a font
|
||||
/// must rename it when this isn't empty.
|
||||
#[serde(default)]
|
||||
pub reserved_names: Vec<String>,
|
||||
/// Format 1.2: an Apache family's `NOTICE` file, located like the licence file.
|
||||
#[serde(default)]
|
||||
pub notice_file: Option<LicenseFile>,
|
||||
/// Format 1.2: where the family is developed.
|
||||
#[serde(default)]
|
||||
pub upstream: Option<String>,
|
||||
/// The repository holding the files, when not the source's.
|
||||
#[serde(default)]
|
||||
pub repo: Option<String>,
|
||||
@@ -399,7 +454,7 @@ pub struct SourceProblem {
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
pub(crate) type Part = (FontSource, Vec<Language>, Vec<Script>, Vec<Family>);
|
||||
pub(crate) type Part = (FontSource, Vec<Language>, Vec<Script>, BTreeMap<String, Sample>, Vec<Family>);
|
||||
|
||||
/// The checked indexes of one or more sources. Families are sorted by name; families of the same
|
||||
/// name are in source order (built-in sources in `sources.json` order, then the user's), and
|
||||
@@ -410,6 +465,9 @@ pub struct Index {
|
||||
problems: Vec<SourceProblem>,
|
||||
languages: Vec<Language>,
|
||||
scripts: Vec<Script>,
|
||||
samples: BTreeMap<String, Sample>,
|
||||
/// Each source's own samples, by its position in `sources`, for [`Index::merge`].
|
||||
source_samples: Vec<BTreeMap<String, Sample>>,
|
||||
families: Vec<Family>,
|
||||
by_name: HashMap<String, Vec<usize>>,
|
||||
by_postscript: HashMap<String, Vec<(usize, usize)>>,
|
||||
@@ -454,10 +512,10 @@ impl Index {
|
||||
for part in parts {
|
||||
problems.extend(part.problems);
|
||||
let mut families = part.families;
|
||||
for source in part.sources {
|
||||
for (source, samples) in part.sources.into_iter().zip(part.source_samples) {
|
||||
let (mine, rest): (Vec<Family>, Vec<Family>) = families.into_iter().partition(|f| f.source == source.id);
|
||||
families = rest;
|
||||
list.push((source, part.languages.clone(), part.scripts.clone(), mine));
|
||||
list.push((source, part.languages.clone(), part.scripts.clone(), samples, mine));
|
||||
}
|
||||
}
|
||||
Self::assemble(list, problems)
|
||||
@@ -480,8 +538,10 @@ impl Index {
|
||||
let mut sources: Vec<FontSource> = Vec::new();
|
||||
let mut languages: BTreeMap<String, Language> = BTreeMap::new();
|
||||
let mut scripts: BTreeMap<String, Script> = BTreeMap::new();
|
||||
let mut samples: BTreeMap<String, Sample> = BTreeMap::new();
|
||||
let mut source_samples = Vec::new();
|
||||
let mut families: Vec<(Family, Vec<String>)> = Vec::new();
|
||||
for (source, langs, scrs, fams) in parts {
|
||||
for (source, langs, scrs, smps, fams) in parts {
|
||||
if sources.iter().any(|s| s.id == source.id) {
|
||||
problems.push(SourceProblem {
|
||||
source: source.user_url.clone().unwrap_or_else(|| source.id.clone()),
|
||||
@@ -500,6 +560,10 @@ impl Index {
|
||||
for s in scrs {
|
||||
scripts.entry(s.id.clone()).or_insert(s);
|
||||
}
|
||||
for (script, sample) in &smps {
|
||||
samples.entry(script.clone()).or_insert_with(|| sample.clone());
|
||||
}
|
||||
source_samples.push(smps);
|
||||
sources.push(source);
|
||||
}
|
||||
let position: HashMap<&str, usize> = languages.keys().enumerate().map(|(i, id)| (id.as_str(), i)).collect();
|
||||
@@ -533,6 +597,8 @@ impl Index {
|
||||
problems,
|
||||
languages: languages.into_values().collect(),
|
||||
scripts: scripts.into_values().collect(),
|
||||
samples,
|
||||
source_samples,
|
||||
families: merged,
|
||||
by_name,
|
||||
by_postscript,
|
||||
@@ -574,6 +640,29 @@ impl Index {
|
||||
&self.scripts
|
||||
}
|
||||
|
||||
/// The default preview text of every script, by ISO 15924 code. When several sources have one
|
||||
/// for a script, the first source's wins.
|
||||
pub fn samples(&self) -> &BTreeMap<String, Sample> {
|
||||
&self.samples
|
||||
}
|
||||
|
||||
/// The default preview text of a script.
|
||||
pub fn sample(&self, script: &str) -> Option<&Sample> {
|
||||
self.samples.get(script)
|
||||
}
|
||||
|
||||
/// The preview text of a file of `family`: the file's own `sample_text`, else the sample of
|
||||
/// its `sample_script`. A file with its own `sample_script` has none when that script has no
|
||||
/// sample; only a file without one uses the family's.
|
||||
pub fn sample_text<'a>(&'a self, family: &'a Family, file: &'a FontFile) -> Option<&'a str> {
|
||||
if let Some(text) = &file.sample_text {
|
||||
return Some(text);
|
||||
}
|
||||
let sample = |script: &Option<String>| script.as_deref().and_then(|s| self.sample(s));
|
||||
let script = if file.sample_script.is_some() { &file.sample_script } else { &family.sample_script };
|
||||
sample(script).map(|s| s.text.as_str())
|
||||
}
|
||||
|
||||
/// The family of this name, ignoring case, from the first source that has it. Only the whole
|
||||
/// name matches.
|
||||
pub fn family(&self, name: &str) -> Option<&Family> {
|
||||
@@ -646,6 +735,11 @@ impl Index {
|
||||
}
|
||||
}
|
||||
|
||||
/// The URLs of `family`'s NOTICE file, best first; empty when it has none.
|
||||
pub fn notice_urls(&self, family: &Family) -> Vec<String> {
|
||||
family.notice_file.as_ref().map(|f| self.urls(family, &f.path, f.repo.as_deref(), f.git_ref.as_deref())).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn urls(&self, family: &Family, path: &str, repo: Option<&str>, git_ref: Option<&str>) -> Vec<String> {
|
||||
let Some(source) = self.source_of(family) else { return Vec::new() };
|
||||
let repo = repo.or(family.repo.as_deref()).or(source.repo.as_deref());
|
||||
|
||||
@@ -44,7 +44,7 @@ impl FontStore {
|
||||
let bytes = match source {
|
||||
IndexSource::Pinned(pin) => {
|
||||
let check = |b: &[u8]| if sha256_hex(b) == pin.sha256 { Ok(()) } else { Err(VerifyError::Sha256) };
|
||||
self.fetch(&[pin.url.to_string()], MAX_PACK_INDEX_BYTES, "the Language pack index", cancel, &mut |_| {}, &check)?
|
||||
self.fetch(&[pin.url.to_string()], 0, MAX_PACK_INDEX_BYTES, "the Language pack index", cancel, &mut |_| {}, &check)?
|
||||
}
|
||||
IndexSource::Override(at) => self.get_local(at, MAX_PACK_INDEX_BYTES, "the Language pack index", cancel, &mut |_| {}, &|_| Ok(()))?,
|
||||
};
|
||||
@@ -65,7 +65,7 @@ impl FontStore {
|
||||
check: &dyn Fn(&[u8]) -> Result<(), VerifyError>,
|
||||
) -> Result<Vec<u8>, Error> {
|
||||
let bytes = match local_source(at) {
|
||||
Some(Ok(url)) if url.starts_with("https://") => return self.fetch(&[url.to_string()], max, what, cancel, on_bytes, check),
|
||||
Some(Ok(url)) if url.starts_with("https://") => return self.fetch(&[url.to_string()], 0, max, what, cancel, on_bytes, check),
|
||||
Some(Ok(url)) => Client::allowing_http(Timeouts::default())
|
||||
.get(url, max, cancel, on_bytes)
|
||||
.map_err(|e| Error::Download { what: what.to_string(), reasons: vec![e.to_string()] })?,
|
||||
@@ -129,7 +129,7 @@ impl FontStore {
|
||||
let bytes = if local {
|
||||
self.get_local(&pack.url, size, &what, cancel, &mut on_bytes, &check)?
|
||||
} else if pack.url.starts_with("https://") {
|
||||
self.fetch(std::slice::from_ref(&pack.url), size, &what, cancel, &mut on_bytes, &check)?
|
||||
self.fetch(std::slice::from_ref(&pack.url), 0, size, &what, cancel, &mut on_bytes, &check)?
|
||||
} else {
|
||||
return Err(Error::BadUrl(pack.url.chars().take(200).collect()));
|
||||
};
|
||||
|
||||
@@ -36,8 +36,8 @@ mod language_packs;
|
||||
mod store;
|
||||
|
||||
pub use index::{
|
||||
Axis, Face, Family, FontFile, FontSource, GOOGLE_FONTS, Index, IndexError, LICENSES, Language, LicenseFile, MAJOR_VERSION, MAX_FILE_BYTES,
|
||||
MAX_INDEX_BYTES, MAX_LICENSE_BYTES, Script, SourceProblem, Unavailable, parse_style,
|
||||
Axis, Face, Family, FontFile, FontSource, GOOGLE_FONTS, Index, IndexError, Instance, LICENSES, Language, LicenseFile, MAJOR_VERSION,
|
||||
MAX_FILE_BYTES, MAX_INDEX_BYTES, MAX_LICENSE_BYTES, Sample, Script, SourceProblem, Unavailable, parse_style,
|
||||
};
|
||||
pub use pin::{IndexPin, PINNED_INDEX};
|
||||
pub use sources::{SourceEntry, SourcesFile};
|
||||
@@ -65,7 +65,10 @@ pub use language_packs::{
|
||||
MAX_PACK_INDEX_BYTES, MAX_PACK_UNPACKED_BYTES, PackEntry, PackIndex, PackIndexPin, language_pack_index_overridden,
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use store::{Caller, Error, FontStore, InstalledFamily, InstalledFile, Network, Problem, Progress};
|
||||
pub use store::{
|
||||
Caller, Error, FontStore, InstalledFamily, InstalledFile, LegalText, Network, PREVIEW_SERVICE_ENV, PreviewServiceSource, Problem, Progress,
|
||||
check_preview_service,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -29,10 +29,10 @@ impl IndexPin {
|
||||
}
|
||||
}
|
||||
|
||||
/// The built-in sources of this build: aiongg/craft-font-index at `5a9a7f8` (Google Fonts at
|
||||
/// The built-in sources of this build: aiongg/craft-font-index at `995ef20` (Google Fonts at
|
||||
/// google/fonts `45e3d52`, and Noto), the copy `Index::bundled` compiles in.
|
||||
pub const PINNED_INDEX: IndexPin = IndexPin {
|
||||
repo: "aiongg/craft-font-index",
|
||||
commit: "5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f",
|
||||
sha256: "4b0c2b9cdec1885027dc3316cdc013ccfbc0d63b6ed9950138d762afaff72e23",
|
||||
commit: "995ef2000a0159d70da245e22cfa0797a0756ae8",
|
||||
sha256: "743cfb4c57176befe8190108efcba43f315de33e747b15ec8694c0625a14c24f",
|
||||
};
|
||||
@@ -1,16 +1,18 @@
|
||||
//! Reading and checking one source's index file, and its URL templates.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::index::{
|
||||
Family, FontSource, GOOGLE_FONTS, Index, IndexError, LICENSES, Language, MAJOR_VERSION, MAX_FILE_BYTES, MAX_INDEX_BYTES, MAX_LICENSE_BYTES,
|
||||
Script,
|
||||
Sample, Script,
|
||||
};
|
||||
|
||||
pub(crate) const MAX_STR: usize = 1024;
|
||||
const MAX_LIST: usize = 4096;
|
||||
/// The most characters a file's own `sample_text` has.
|
||||
const MAX_SAMPLE_CHARS: usize = 60;
|
||||
const MAX_FAMILIES: usize = 50_000;
|
||||
const MAX_FILES: usize = 200_000;
|
||||
const MAX_SEGMENT: usize = 64;
|
||||
@@ -60,6 +62,8 @@ struct Raw {
|
||||
languages: Vec<Language>,
|
||||
#[serde(default)]
|
||||
scripts: Vec<Script>,
|
||||
#[serde(default)]
|
||||
samples: BTreeMap<String, Sample>,
|
||||
families: Vec<Family>,
|
||||
}
|
||||
|
||||
@@ -80,8 +84,13 @@ pub(crate) fn check_version(version: &str) -> Result<(), IndexError> {
|
||||
if major == Some(MAJOR_VERSION) { Ok(()) } else { Err(IndexError::Version(version.chars().take(40).collect())) }
|
||||
}
|
||||
|
||||
/// Direction marks, embeddings and isolates, which can reorder the text around them.
|
||||
fn is_bidi_control(c: char) -> bool {
|
||||
matches!(c, '\u{61c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
|
||||
}
|
||||
|
||||
pub(crate) fn check_str(what: &str, s: &str) -> Result<(), IndexError> {
|
||||
if s.len() > MAX_STR || s.chars().any(char::is_control) {
|
||||
if s.len() > MAX_STR || s.chars().any(|c| c.is_control() || is_bidi_control(c)) {
|
||||
return invalid(format!("{what} is too long or has control characters"));
|
||||
}
|
||||
Ok(())
|
||||
@@ -317,8 +326,17 @@ fn check(raw: Raw, origin: Origin<'_>) -> Result<Index, IndexError> {
|
||||
}
|
||||
};
|
||||
let curated = curated && host.is_none();
|
||||
if raw.families.len() > MAX_FAMILIES || raw.languages.len() > MAX_FAMILIES * 4 || raw.scripts.len() > MAX_LIST {
|
||||
return invalid("too many families, languages or scripts");
|
||||
if raw.families.len() > MAX_FAMILIES || raw.languages.len() > MAX_FAMILIES * 4 || raw.scripts.len() > MAX_LIST || raw.samples.len() > MAX_LIST {
|
||||
return invalid("too many families, languages, scripts or samples");
|
||||
}
|
||||
for (script, sample) in &raw.samples {
|
||||
for s in [script, &sample.method, &sample.language] {
|
||||
check_str("sample", s)?;
|
||||
}
|
||||
// Some samples are several lines (Nüshu, Carian).
|
||||
if sample.text.len() > MAX_STR || sample.text.chars().any(|c| c.is_control() && c != '\n') {
|
||||
return invalid(format!("the `{}` sample is too long or has control characters", short(script)));
|
||||
}
|
||||
}
|
||||
for l in &raw.languages {
|
||||
check_str("language", &l.id)?;
|
||||
@@ -380,7 +398,7 @@ fn check(raw: Raw, origin: Origin<'_>) -> Result<Index, IndexError> {
|
||||
repo: raw.repo,
|
||||
git_ref: raw.git_ref,
|
||||
};
|
||||
Ok(Index::assemble(vec![(source, raw.languages, raw.scripts, families)], Vec::new()))
|
||||
Ok(Index::assemble(vec![(source, raw.languages, raw.scripts, raw.samples, families)], Vec::new()))
|
||||
}
|
||||
|
||||
/// The family folder in google/fonts: every file at `<ofl|apache|ufl>/<dir>/<file>`.
|
||||
@@ -419,13 +437,20 @@ fn check_family(fam: &mut Family, ctx: &Ctx<'_>) -> Result<(), IndexError> {
|
||||
if fam.files.is_empty() {
|
||||
return invalid(format!("`{name}` has no files"));
|
||||
}
|
||||
let lists = [fam.categories.len(), fam.subsets.len(), fam.languages.len(), fam.scripts.len(), fam.files.len()];
|
||||
let lists =
|
||||
[fam.categories.len(), fam.subsets.len(), fam.languages.len(), fam.scripts.len(), fam.files.len(), fam.tags.len(), fam.reserved_names.len()];
|
||||
if lists.iter().any(|&n| n > MAX_LIST) {
|
||||
return invalid(format!("`{name}` has too many entries"));
|
||||
}
|
||||
for s in fam.categories.iter().chain(&fam.subsets).chain(&fam.scripts) {
|
||||
check_str("category, subset or script", s)?;
|
||||
}
|
||||
for s in fam.tags.iter().chain(&fam.reserved_names).chain(&fam.sample_script).chain(&fam.copyright) {
|
||||
check_str("tag, reserved name, sample script or copyright", s)?;
|
||||
}
|
||||
if fam.upstream.as_deref().is_some_and(|u| !is_source_url(u)) {
|
||||
return invalid(format!("the upstream of `{name}` is not an https URL"));
|
||||
}
|
||||
if fam.languages.iter().any(|&i| i >= ctx.languages) {
|
||||
return invalid(format!("`{name}` names a language the index doesn't have"));
|
||||
}
|
||||
@@ -463,6 +488,26 @@ fn check_family(fam: &mut Family, ctx: &Ctx<'_>) -> Result<(), IndexError> {
|
||||
return invalid(format!("`{}` has a bad axis", short(&f.path)));
|
||||
}
|
||||
}
|
||||
if (!f.instances.is_empty() && f.axes.is_empty()) || f.instances.len() > MAX_LIST || f.list_instance.is_some_and(|i| i >= f.instances.len()) {
|
||||
return invalid(format!("`{}` has a bad list instance", short(&f.path)));
|
||||
}
|
||||
// Every instance has a coordinate for each axis and for no other.
|
||||
for s in f.sample_script.iter().chain(&f.sample_text) {
|
||||
check_str("sample script or text", s)?;
|
||||
}
|
||||
if f.sample_text.as_deref().is_some_and(|t| t.chars().count() > MAX_SAMPLE_CHARS) {
|
||||
return invalid(format!("`{}` has a sample text over {MAX_SAMPLE_CHARS} characters", short(&f.path)));
|
||||
}
|
||||
for i in &f.instances {
|
||||
check_str("instance name", &i.name)?;
|
||||
if i.coordinates.len() != f.axes.len() || f.axes.iter().any(|a| !i.coordinates.contains_key(&a.tag)) {
|
||||
return invalid(format!("`{}` has an instance without its axes", short(&f.path)));
|
||||
}
|
||||
let in_range = |a: &crate::index::Axis| i.coordinates.get(&a.tag).is_some_and(|c| c.is_finite() && (a.min..=a.max).contains(c));
|
||||
if !f.axes.iter().all(in_range) {
|
||||
return invalid(format!("`{}` has an instance outside its axes' ranges", short(&f.path)));
|
||||
}
|
||||
}
|
||||
for ps in &f.postscript {
|
||||
check_str("PostScript name", ps)?;
|
||||
if ps.is_empty() {
|
||||
@@ -472,22 +517,24 @@ fn check_family(fam: &mut Family, ctx: &Ctx<'_>) -> Result<(), IndexError> {
|
||||
check_repo_ref(&f.path, f.repo.as_deref(), f.git_ref.as_deref())?;
|
||||
fill(ctx.templates, &f.path, repo(f.repo.clone()).as_deref(), git_ref(f.git_ref.clone()).as_deref())?;
|
||||
}
|
||||
let beside = |path: &str| -> Result<(), IndexError> {
|
||||
let beside = |what: &str, path: &str| -> Result<(), IndexError> {
|
||||
if names.contains(&check_path(path)?.to_ascii_lowercase()) {
|
||||
return invalid(format!("the licence of `{name}` has a font file's name"));
|
||||
return invalid(format!("the {what} of `{name}` has a font file's name"));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
if let Some(lf) = &fam.license_file {
|
||||
beside(&lf.path)?;
|
||||
// The licence and the NOTICE file are checked alike.
|
||||
for (what, lf) in [("licence", &fam.license_file), ("notice", &fam.notice_file)] {
|
||||
let Some(lf) = lf else { continue };
|
||||
beside(what, &lf.path)?;
|
||||
if !is_sha256(&lf.sha256) || lf.size == 0 || lf.size > MAX_LICENSE_BYTES {
|
||||
return invalid(format!("the licence of `{name}` has a bad sha256 or size"));
|
||||
return invalid(format!("the {what} of `{name}` has a bad sha256 or size"));
|
||||
}
|
||||
check_repo_ref(&lf.path, lf.repo.as_deref(), lf.git_ref.as_deref())?;
|
||||
fill(ctx.templates, &lf.path, repo(lf.repo.clone()).as_deref(), git_ref(lf.git_ref.clone()).as_deref())?;
|
||||
}
|
||||
if let Some(lp) = &fam.license_path {
|
||||
beside(lp)?;
|
||||
beside("licence", lp)?;
|
||||
if fam.license_file.is_none() {
|
||||
fill(ctx.templates, lp, repo(None).as_deref(), git_ref(None).as_deref())?;
|
||||
}
|
||||
|
||||
+236
-15
@@ -6,6 +6,7 @@
|
||||
//! settings.json the consent setting and the sources the user added
|
||||
//! manifest.json what is installed
|
||||
//! indexes/ the last indexes fetched: sources.json, one file per source
|
||||
//! previews/ preview subsets from the preview service (WOFF2), a cache of at most 50 MB
|
||||
//! <family dir>/ google/fonts' folder name, or <source>/<family>: the fonts and the licence
|
||||
//! language-packs/ installed Language packs, one folder per locale (`crate::language_packs`)
|
||||
//! language-packs.json which Language packs are installed, from which index entry
|
||||
@@ -25,7 +26,9 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::UserSource;
|
||||
use crate::http::{Cancel, Client, FetchError};
|
||||
use crate::index::{Face, Family, FontFile, GOOGLE_FONTS, Index, IndexError, MAX_INDEX_BYTES, MAX_LICENSE_BYTES, SourceProblem, Unavailable};
|
||||
use crate::index::{
|
||||
Face, Family, FontFile, GOOGLE_FONTS, Index, IndexError, LicenseFile, MAX_INDEX_BYTES, MAX_LICENSE_BYTES, SourceProblem, Unavailable,
|
||||
};
|
||||
use crate::pin::IndexPin;
|
||||
use crate::source::{is_source_url, safe_dir, safe_file_name, slug};
|
||||
use crate::sources::{MAX_SOURCES_BYTES, SourceEntry, SourcesFile};
|
||||
@@ -40,6 +43,7 @@ use transaction::{Commit, merge_entry};
|
||||
const SETTINGS: &str = "settings.json";
|
||||
const MANIFEST: &str = "manifest.json";
|
||||
pub(crate) const INDEX_CACHE: &str = "indexes";
|
||||
const PREVIEWS: &str = "previews";
|
||||
const SOURCES_CACHE: &str = "sources.json";
|
||||
const STAGING: &str = ".staging";
|
||||
const LOCK: &str = ".lock";
|
||||
@@ -82,6 +86,9 @@ pub enum Error {
|
||||
/// Not an https URL a source can be added from.
|
||||
#[error("{0} is not an https URL")]
|
||||
BadUrl(String),
|
||||
/// Not a usable preview service address.
|
||||
#[error("{0} is not an https URL, or an http URL to 127.0.0.1 or [::1]")]
|
||||
BadServiceUrl(String),
|
||||
/// No exact match in the index.
|
||||
#[error(transparent)]
|
||||
Unavailable(#[from] Unavailable),
|
||||
@@ -184,12 +191,39 @@ fn google_fonts() -> String {
|
||||
GOOGLE_FONTS.into()
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
struct Settings {
|
||||
#[serde(default)]
|
||||
network: Network,
|
||||
/// `None` until the user chooses. Files written before this field could be absent always
|
||||
/// hold a value, so an `off` there counts as the user's choice.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
network: Option<Network>,
|
||||
#[serde(default)]
|
||||
user_sources: Vec<UserSource>,
|
||||
#[serde(default)]
|
||||
preview_service: Option<String>,
|
||||
#[serde(default = "on")]
|
||||
previews: bool,
|
||||
/// The file exists but couldn't be read or parsed.
|
||||
#[serde(skip)]
|
||||
unreadable: bool,
|
||||
}
|
||||
|
||||
fn on() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self { network: None, user_sources: Vec::new(), preview_service: None, previews: true, unreadable: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
/// What a `settings.json` that can't be read or parsed stands for: the network off and no
|
||||
/// preview service, not even the host's default. A write starts from these.
|
||||
fn unreadable() -> Self {
|
||||
Self { network: Some(Network::Off), unreadable: true, ..Self::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Something [`FontStore::verify`] found wrong with an installed file.
|
||||
@@ -203,6 +237,25 @@ pub struct Problem {
|
||||
pub error: Option<VerifyError>,
|
||||
}
|
||||
|
||||
/// Which of a family's legal texts [`FontStore::legal_text`] reads.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum LegalText {
|
||||
/// The licence file (`OFL.txt`, `LICENSE.txt`).
|
||||
License,
|
||||
/// An Apache family's `NOTICE` file.
|
||||
Notice,
|
||||
}
|
||||
|
||||
/// A licence or NOTICE file's size and sha256, when the index has them. A format 1.0 index has
|
||||
/// neither for the licence: the size cap is then the only check.
|
||||
fn check_license(file: Option<&LicenseFile>, bytes: &[u8]) -> Result<(), VerifyError> {
|
||||
match file {
|
||||
Some(f) if bytes.len() as u64 != f.size => Err(VerifyError::Size { expected: f.size, actual: bytes.len() as u64 }),
|
||||
Some(f) if sha256_hex(bytes) != f.sha256 => Err(VerifyError::Sha256),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The suite's font store.
|
||||
///
|
||||
/// Nothing here touches the network on its own: only [`FontStore::fetch_indexes`] and the installs
|
||||
@@ -214,6 +267,14 @@ pub struct FontStore {
|
||||
catalog: Option<Arc<Catalog>>,
|
||||
pub(crate) pack_removal_cursor: AtomicUsize,
|
||||
pub(crate) pack_removal_round_end: AtomicUsize,
|
||||
/// The host's preview service, used while neither the environment nor the setting names one.
|
||||
/// Never saved.
|
||||
default_preview_service: Option<String>,
|
||||
/// The host's network setting, used while the user hasn't chosen. Never saved.
|
||||
default_network: Option<Network>,
|
||||
/// Tests: stands in for the environment variable.
|
||||
#[cfg(test)]
|
||||
preview_env: Option<Option<String>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for FontStore {
|
||||
@@ -243,9 +304,47 @@ impl FontStore {
|
||||
catalog: None,
|
||||
pack_removal_cursor: AtomicUsize::new(0),
|
||||
pack_removal_round_end: AtomicUsize::new(0),
|
||||
default_preview_service: None,
|
||||
default_network: None,
|
||||
#[cfg(test)]
|
||||
preview_env: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests: reads `env` instead of [`PREVIEW_SERVICE_ENV`].
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_preview_env(mut self, env: Option<&str>) -> Self {
|
||||
self.preview_env = Some(env.map(str::to_string));
|
||||
self
|
||||
}
|
||||
|
||||
/// The download client. Clones share the preview service's down state, so a pool built on one
|
||||
/// stops asking a service the store found unreachable, and the reverse.
|
||||
pub fn client(&self) -> Client {
|
||||
self.client.clone()
|
||||
}
|
||||
|
||||
/// Uses `url` as the preview service while neither [`PREVIEW_SERVICE_ENV`] nor the user's
|
||||
/// setting names one. The host's default is never written to `settings.json`, so clearing
|
||||
/// the setting brings it back, and other apps sharing the store don't see it. An unusable
|
||||
/// URL counts as none.
|
||||
pub fn with_default_preview_service(mut self, url: &str) -> Self {
|
||||
self.default_preview_service = normalize_service_url(url);
|
||||
debug_assert!(self.default_preview_service.is_some(), "unusable preview service URL {url:?}");
|
||||
self
|
||||
}
|
||||
|
||||
/// Uses `network` while the user hasn't chosen (no saved choice in `settings.json`). The
|
||||
/// host's default is never saved: the user's [`FontStore::enable_network`] or
|
||||
/// [`FontStore::disable_network`] beats it from then on, and other apps sharing the store
|
||||
/// don't see it. An agent's store ignores it, as an agent can never turn the network on.
|
||||
pub fn with_default_network(mut self, network: Network) -> Self {
|
||||
if self.caller == Caller::User {
|
||||
self.default_network = Some(network);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Uses `client` for downloads (other timeouts).
|
||||
pub fn with_client(mut self, client: Client) -> Self {
|
||||
self.client = client;
|
||||
@@ -264,6 +363,12 @@ impl FontStore {
|
||||
&self.dir
|
||||
}
|
||||
|
||||
/// The folder for the preview service's subsets, which craft-font-manager caches. The store
|
||||
/// itself never reads or writes it.
|
||||
pub fn previews_dir(&self) -> PathBuf {
|
||||
self.dir.join(PREVIEWS)
|
||||
}
|
||||
|
||||
/// Who drives this store.
|
||||
pub fn caller(&self) -> Caller {
|
||||
self.caller
|
||||
@@ -317,7 +422,10 @@ impl FontStore {
|
||||
for (i, file) in wanted.iter().enumerate() {
|
||||
let mut on_bytes = |n: u64| progress(Progress { file: i, files: wanted.len(), done: done_before + n, total });
|
||||
let check = |bytes: &[u8]| verify_font(file, bytes);
|
||||
let bytes = self.fetch(&index.file_urls(family, file), file.size, file.file_name(), cancel, &mut on_bytes, &check)?;
|
||||
let mut urls = self.mirror_urls(family, "files", &file.sha256);
|
||||
let mirrors = urls.len();
|
||||
urls.extend(index.file_urls(family, file));
|
||||
let bytes = self.fetch(&urls, mirrors, file.size, file.file_name(), cancel, &mut on_bytes, &check)?;
|
||||
done_before += file.size;
|
||||
staged.push((file.file_name().to_string(), stage.write(file.file_name(), &bytes)?));
|
||||
}
|
||||
@@ -325,12 +433,12 @@ impl FontStore {
|
||||
// A format 1.0 index has no size or sha256 for the licence: the size cap is the only
|
||||
// check.
|
||||
let max = family.license_file.as_ref().map_or(MAX_LICENSE_BYTES, |f| f.size);
|
||||
let check = |bytes: &[u8]| match &family.license_file {
|
||||
Some(f) if bytes.len() as u64 != f.size => Err(VerifyError::Size { expected: f.size, actual: bytes.len() as u64 }),
|
||||
Some(f) if sha256_hex(bytes) != f.sha256 => Err(VerifyError::Sha256),
|
||||
_ => Ok(()),
|
||||
};
|
||||
let bytes = self.fetch(&index.license_urls(family), max, name, cancel, &mut |_| {}, &check)?;
|
||||
let check = |bytes: &[u8]| check_license(family.license_file.as_ref(), bytes);
|
||||
// Without a sha256 there is no mirror address.
|
||||
let mut urls = family.license_file.as_ref().map(|f| self.mirror_urls(family, "licences", &f.sha256)).unwrap_or_default();
|
||||
let mirrors = urls.len();
|
||||
urls.extend(index.license_urls(family));
|
||||
let bytes = self.fetch(&urls, mirrors, max, name, cancel, &mut |_| {}, &check)?;
|
||||
staged.push((name.to_string(), stage.write(name, &bytes)?));
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
@@ -358,10 +466,50 @@ impl FontStore {
|
||||
result
|
||||
}
|
||||
|
||||
/// Downloads from each URL in turn until one gives bytes that pass `check`.
|
||||
/// The text of `family`'s licence or NOTICE file: the copy installed beside its fonts, else
|
||||
/// downloaded and checked like an install's licence, from the preview service first.
|
||||
/// `Ok(None)` when the family has no such file.
|
||||
pub fn legal_text(&self, index: &Index, family: &Family, which: LegalText, cancel: &Cancel) -> Result<Option<String>, Error> {
|
||||
let (file, name, urls) = match which {
|
||||
LegalText::License => (family.license_file.as_ref(), family.license_file_name(), index.license_urls(family)),
|
||||
LegalText::Notice => (family.notice_file.as_ref(), family.notice_file.as_ref().map(LicenseFile::file_name), index.notice_urls(family)),
|
||||
};
|
||||
let Some(name) = name else { return Ok(None) };
|
||||
let max = file.map_or(MAX_LICENSE_BYTES, |f| f.size);
|
||||
let text = |bytes: &[u8]| String::from_utf8_lossy(bytes).into_owned();
|
||||
let installed = self.dir.join(family.dir()).join(name);
|
||||
if std::fs::metadata(&installed).is_ok_and(|m| m.is_file() && m.len() <= max)
|
||||
&& let Ok(bytes) = std::fs::read(&installed)
|
||||
&& check_license(file, &bytes).is_ok()
|
||||
{
|
||||
return Ok(Some(text(&bytes)));
|
||||
}
|
||||
self.require_network()?;
|
||||
let mut all = file.map(|f| self.mirror_urls(family, "licences", &f.sha256)).unwrap_or_default();
|
||||
let mirrors = all.len();
|
||||
all.extend(urls);
|
||||
let bytes = self.fetch(&all, mirrors, max, name, cancel, &mut |_| {}, &|b| check_license(file, b))?;
|
||||
Ok(Some(text(&bytes)))
|
||||
}
|
||||
|
||||
/// The preview service's address for a file of `family` by its sha256; empty without a
|
||||
/// service, and for a family the user's sources added: the service holds only the built-in
|
||||
/// sources' files, and asking would tell it the file's hash.
|
||||
fn mirror_urls(&self, family: &Family, kind: &str, sha256: &str) -> Vec<String> {
|
||||
if !family.is_curated() {
|
||||
return Vec::new();
|
||||
}
|
||||
self.preview_service().map(|base| format!("{base}/v1/{kind}/{sha256}")).into_iter().collect()
|
||||
}
|
||||
|
||||
/// Downloads from each URL in turn until one gives bytes that pass `check`. The first
|
||||
/// `mirrors` URLs come from the preview-service setting and may use loopback http; the rest
|
||||
/// are https only.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn fetch(
|
||||
&self,
|
||||
urls: &[String],
|
||||
mirrors: usize,
|
||||
max: u64,
|
||||
what: &str,
|
||||
cancel: &Cancel,
|
||||
@@ -369,14 +517,19 @@ impl FontStore {
|
||||
check: &dyn Fn(&[u8]) -> Result<(), VerifyError>,
|
||||
) -> Result<Vec<u8>, Error> {
|
||||
let mut reasons = Vec::new();
|
||||
// A rejection by an index URL is a corrupt file; a mirror's alone is one more failed source.
|
||||
let mut rejected = None;
|
||||
for url in urls {
|
||||
match self.client.get(url, max, cancel, on_bytes) {
|
||||
for (i, url) in urls.iter().enumerate() {
|
||||
let got =
|
||||
if i < mirrors { self.client.get_from_service(url, max, cancel, on_bytes) } else { self.client.get(url, max, cancel, on_bytes) };
|
||||
match got {
|
||||
Ok(bytes) => match check(&bytes) {
|
||||
Ok(()) => return Ok(bytes),
|
||||
Err(e) => {
|
||||
reasons.push(format!("{}: {e}", host(url)));
|
||||
rejected.get_or_insert(e);
|
||||
if i >= mirrors {
|
||||
rejected.get_or_insert(e);
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(FetchError::Cancelled) => return Err(Error::Cancelled),
|
||||
@@ -537,6 +690,74 @@ pub(crate) fn read_limited(path: &Path, max: u64) -> Option<Vec<u8>> {
|
||||
std::fs::read(path).ok()
|
||||
}
|
||||
|
||||
/// The environment variable that sets the preview service's base URL; it beats the saved setting.
|
||||
pub const PREVIEW_SERVICE_ENV: &str = "CRAFT_FONT_PREVIEW_URL";
|
||||
|
||||
/// Where the preview service in effect comes from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PreviewServiceSource {
|
||||
/// [`PREVIEW_SERVICE_ENV`]; the setting can't change it.
|
||||
Env,
|
||||
/// The `preview_service` setting in `settings.json`.
|
||||
Saved,
|
||||
/// The host's default, [`FontStore::with_default_preview_service`].
|
||||
Default,
|
||||
/// There is no service.
|
||||
None,
|
||||
}
|
||||
|
||||
/// The environment value when set and not empty, else the setting; an unusable value counts as
|
||||
/// unset.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn resolve_preview_service(env: Option<&str>, setting: Option<&str>) -> Option<String> {
|
||||
resolve_preview_source(env, setting, None).0
|
||||
}
|
||||
|
||||
/// The service in effect and where it came from: the environment value when set and not empty
|
||||
/// (alone: an unusable one means no service), else the setting when usable, else the host's
|
||||
/// default.
|
||||
pub(crate) fn resolve_preview_source(env: Option<&str>, setting: Option<&str>, default: Option<&str>) -> (Option<String>, PreviewServiceSource) {
|
||||
let (url, source) = match env.map(str::trim).filter(|e| !e.is_empty()) {
|
||||
Some(e) => (normalize_service_url(e), PreviewServiceSource::Env),
|
||||
None => match setting.and_then(normalize_service_url) {
|
||||
Some(url) => (Some(url), PreviewServiceSource::Saved),
|
||||
None => (default.and_then(normalize_service_url), PreviewServiceSource::Default),
|
||||
},
|
||||
};
|
||||
if url.is_some() { (url, source) } else { (None, PreviewServiceSource::None) }
|
||||
}
|
||||
|
||||
/// The preview-service address `url` stands for: without a trailing slash, when it is an https URL,
|
||||
/// or an http one for a loopback host, with no credentials, query or fragment. [`Error::BadServiceUrl`]
|
||||
/// otherwise.
|
||||
pub fn check_preview_service(url: &str) -> Result<String, Error> {
|
||||
normalize_service_url(url).ok_or_else(|| Error::BadServiceUrl(url.trim().chars().take(200).collect()))
|
||||
}
|
||||
|
||||
/// `url` without a trailing slash, when it is an https URL, or an http one for a loopback host,
|
||||
/// with no credentials, query or fragment.
|
||||
fn normalize_service_url(url: &str) -> Option<String> {
|
||||
let url = url.trim().trim_end_matches('/');
|
||||
if url.len() > 2000 || url.chars().any(|c| c.is_control() || c.is_whitespace() || c == '\\') {
|
||||
return None;
|
||||
}
|
||||
let (https, rest) = match (url.strip_prefix("https://"), url.strip_prefix("http://")) {
|
||||
(Some(r), _) => (true, r),
|
||||
(None, Some(r)) => (false, r),
|
||||
_ => return None,
|
||||
};
|
||||
let authority = rest.split('/').next().unwrap_or_default();
|
||||
if authority.is_empty() || authority.contains('@') || url.contains(['?', '#']) {
|
||||
return None;
|
||||
}
|
||||
let host = match authority.strip_prefix('[') {
|
||||
Some(v6) => v6.split(']').next().unwrap_or_default(),
|
||||
None => authority.split(':').next().unwrap_or_default(),
|
||||
};
|
||||
let loopback = matches!(host.to_ascii_lowercase().as_str(), "127.0.0.1" | "::1");
|
||||
(https || loopback).then(|| url.to_string())
|
||||
}
|
||||
|
||||
fn host(url: &str) -> &str {
|
||||
url.split("://").nth(1).and_then(|r| r.split('/').next()).unwrap_or(url)
|
||||
}
|
||||
@@ -2,20 +2,29 @@
|
||||
|
||||
use super::{
|
||||
Caller, Cancel, Error, FontStore, INDEX_CACHE, Index, IndexError, IndexPin, MAX_INDEX_BYTES, MAX_SETTINGS_BYTES, MAX_SOURCES_BYTES,
|
||||
MAX_USER_SOURCES, Network, PathBuf, SETTINGS, SOURCES_CACHE, Settings, SourceEntry, SourceProblem, SourcesFile, SystemTime, UserSource,
|
||||
VerifyError, io, is_source_url, read_limited, sha256_hex, slug,
|
||||
MAX_USER_SOURCES, Network, PREVIEW_SERVICE_ENV, PathBuf, PreviewServiceSource, SETTINGS, SOURCES_CACHE, Settings, SourceEntry, SourceProblem,
|
||||
SourcesFile, SystemTime, UserSource, VerifyError, check_preview_service, io, is_source_url, read_limited, resolve_preview_source, sha256_hex,
|
||||
slug,
|
||||
};
|
||||
|
||||
impl FontStore {
|
||||
// ----- consent
|
||||
|
||||
/// The user's setting; [`Network::Off`] when it was never set or can't be read.
|
||||
/// The user's saved choice, else the host's default ([`FontStore::with_default_network`]),
|
||||
/// else [`Network::Off`]. A missing `settings.json` is no choice; one that can't be read or
|
||||
/// parsed is [`Network::Off`].
|
||||
pub fn network(&self) -> Network {
|
||||
self.settings().network
|
||||
self.settings().network.or(self.default_network).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The saved settings: the defaults without a file, [`Settings::unreadable`] for a file that
|
||||
/// can't be read, is too large or doesn't parse.
|
||||
fn settings(&self) -> Settings {
|
||||
read_limited(&self.dir.join(SETTINGS), MAX_SETTINGS_BYTES).and_then(|b| serde_json::from_slice::<Settings>(&b).ok()).unwrap_or_default()
|
||||
let path = self.dir.join(SETTINGS);
|
||||
if std::fs::metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) {
|
||||
return Settings::default();
|
||||
}
|
||||
read_limited(&path, MAX_SETTINGS_BYTES).and_then(|b| serde_json::from_slice::<Settings>(&b).ok()).unwrap_or_else(Settings::unreadable)
|
||||
}
|
||||
|
||||
/// Turns downloading on: call it only from the user's own action (a setting, an Install
|
||||
@@ -24,12 +33,71 @@ impl FontStore {
|
||||
if self.caller != Caller::User {
|
||||
return Err(Error::NotAllowed);
|
||||
}
|
||||
self.change_settings(|s| s.network = Network::On)
|
||||
self.change_settings(|s| s.network = Some(Network::On))
|
||||
}
|
||||
|
||||
/// The preview service's base URL, or `None` while there is none: [`PREVIEW_SERVICE_ENV`]
|
||||
/// environment variable when set and not empty, else the `preview_service` setting, else the
|
||||
/// host's default ([`FontStore::with_default_preview_service`]); no host default while
|
||||
/// `settings.json` can't be read or parsed. Installs of curated families
|
||||
/// ([`crate::Family::is_curated`]) try its mirror (`<service>/v1/files/<sha256>`,
|
||||
/// `<service>/v1/licences/<sha256>`) before the index's URLs. A value that is not a usable URL
|
||||
/// counts as unset.
|
||||
pub fn preview_service(&self) -> Option<String> {
|
||||
self.preview_service_and_source().0
|
||||
}
|
||||
|
||||
/// Where [`FontStore::preview_service`] gets its value: the environment, the saved setting,
|
||||
/// the host's default, or nowhere. An unusable value counts as unset, as there.
|
||||
pub fn preview_service_source(&self) -> PreviewServiceSource {
|
||||
self.preview_service_and_source().1
|
||||
}
|
||||
|
||||
fn preview_service_and_source(&self) -> (Option<String>, PreviewServiceSource) {
|
||||
#[cfg(test)]
|
||||
let env = self.preview_env.clone().unwrap_or_else(|| std::env::var(PREVIEW_SERVICE_ENV).ok());
|
||||
#[cfg(not(test))]
|
||||
let env = std::env::var(PREVIEW_SERVICE_ENV).ok();
|
||||
let settings = self.settings();
|
||||
let default = if settings.unreadable { None } else { self.default_preview_service.as_deref() };
|
||||
resolve_preview_source(env.as_deref(), settings.preview_service.as_deref(), default)
|
||||
}
|
||||
|
||||
/// Sets (or with `None` clears) the preview service in `settings.json`, from the user's own
|
||||
/// action. Only https URLs are accepted, and http for a loopback host. The environment
|
||||
/// variable still takes precedence; while the setting is clear, the host's default applies.
|
||||
/// Installs and [`FontStore::legal_text`] ask the service only for curated families
|
||||
/// ([`crate::Family::is_curated`]), never with the hashes of files from the user's sources.
|
||||
/// [`Error::NotAllowed`] for an agent, [`Error::BadServiceUrl`] for an unusable URL.
|
||||
pub fn set_preview_service(&self, url: Option<&str>) -> Result<(), Error> {
|
||||
if self.caller != Caller::User {
|
||||
return Err(Error::NotAllowed);
|
||||
}
|
||||
let url = match url {
|
||||
Some(u) => Some(check_preview_service(u)?),
|
||||
None => None,
|
||||
};
|
||||
self.change_settings(|s| s.preview_service = url)
|
||||
}
|
||||
|
||||
/// Turns downloading off. Anyone may.
|
||||
pub fn disable_network(&self) -> Result<(), Error> {
|
||||
self.change_settings(|s| s.network = Network::Off)
|
||||
self.change_settings(|s| s.network = Some(Network::Off))
|
||||
}
|
||||
|
||||
/// Whether the app may fetch font previews from the preview service. On unless the user
|
||||
/// turned it off. It matters only while a service is set; it doesn't affect installs.
|
||||
pub fn previews_enabled(&self) -> bool {
|
||||
self.settings().previews
|
||||
}
|
||||
|
||||
/// Turns previews from the preview service on or off, from the user's own action.
|
||||
/// [`Error::NotAllowed`] for an agent.
|
||||
pub fn set_previews_enabled(&self, enabled: bool) -> Result<(), Error> {
|
||||
if self.caller != Caller::User {
|
||||
return Err(Error::NotAllowed);
|
||||
}
|
||||
self.change_settings(|s| s.previews = enabled)
|
||||
}
|
||||
|
||||
fn change_settings(&self, change: impl FnOnce(&mut Settings)) -> Result<(), Error> {
|
||||
@@ -140,7 +208,7 @@ impl FontStore {
|
||||
pub fn fetch_indexes(&self, pin: &IndexPin, cancel: &Cancel) -> Result<Index, Error> {
|
||||
self.require_network()?;
|
||||
let check = |bytes: &[u8]| if sha256_hex(bytes) == pin.sha256 { Ok(()) } else { Err(VerifyError::Sha256) };
|
||||
let bytes = self.fetch(&pin.urls(), MAX_SOURCES_BYTES as u64, "sources.json", cancel, &mut |_| {}, &check)?;
|
||||
let bytes = self.fetch(&pin.urls(), 0, MAX_SOURCES_BYTES as u64, "sources.json", cancel, &mut |_| {}, &check)?;
|
||||
let sources = SourcesFile::from_json(&bytes)?;
|
||||
let cache = self.dir.join(INDEX_CACHE);
|
||||
std::fs::create_dir_all(&cache).map_err(io("creating the index folder"))?;
|
||||
@@ -175,14 +243,14 @@ impl FontStore {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
let bytes = self.fetch(&pin.file_urls(path), size, &entry.name, cancel, &mut |_| {}, &check)?;
|
||||
let bytes = self.fetch(&pin.file_urls(path), 0, size, &entry.name, cancel, &mut |_| {}, &check)?;
|
||||
let index = entry.read(&bytes, entry.gz().is_some())?;
|
||||
self.write_file(&format!("{INDEX_CACHE}/{}", builtin_cache_name(entry)), &bytes)?;
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
fn fetch_user(&self, user: &UserSource, cancel: &Cancel) -> Result<Index, Error> {
|
||||
let bytes = self.fetch(std::slice::from_ref(&user.url), MAX_INDEX_BYTES as u64, &user.url, cancel, &mut |_| {}, &|_| Ok(()))?;
|
||||
let bytes = self.fetch(std::slice::from_ref(&user.url), 0, MAX_INDEX_BYTES as u64, &user.url, cancel, &mut |_| {}, &|_| Ok(()))?;
|
||||
let index = user_index(&bytes, user)?;
|
||||
if let Some(name) = self.user_cache(&user.url).file_name().and_then(|n| n.to_str()) {
|
||||
self.write_file(&format!("{INDEX_CACHE}/{name}"), &bytes)?;
|
||||
|
||||
@@ -136,6 +136,86 @@ fn the_index_is_read_and_checked() {
|
||||
assert!(matches!(Index::from_json(b"{"), Err(IndexError::Json(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_1_2_adds_tags_and_samples_and_1_1_still_loads() {
|
||||
let f = fixture();
|
||||
let mut v1_1 = f.index.clone();
|
||||
v1_1["version"] = json!("1.1");
|
||||
let old = index_of(&v1_1).unwrap();
|
||||
let sans = old.family("Test Sans").unwrap();
|
||||
assert!(sans.tags.is_empty() && sans.sample_script.is_none() && old.samples().is_empty());
|
||||
assert_eq!(old.sample_text(sans, &sans.files[0]), None);
|
||||
|
||||
let sample = |text: &str| json!({"text": text, "method": "udhr", "language": "xx"});
|
||||
let mut first = f.index.clone();
|
||||
first["version"] = json!("1.2");
|
||||
first["samples"] = json!({"Latn": sample("Hello"), "Thai": sample("first")});
|
||||
first["families"][2]["tags"] = json!(["Sans", "Display/Playful"]);
|
||||
first["families"][2]["sample_script"] = json!("Latn");
|
||||
first["families"][2]["reserved_names"] = json!(["Test"]);
|
||||
first["families"][2]["files"][0]["sample_script"] = json!("Thai");
|
||||
first["families"][2]["files"][1]["sample_text"] = json!("Own text");
|
||||
first["families"][2]["files"][2]["sample_script"] = json!("Zsym");
|
||||
first["families"][3]["files"][0]["instances"] = json!([{"name": "Regular", "coordinates": {"wght": 400.0}}]);
|
||||
first["families"][3]["files"][0]["list_instance"] = json!(0);
|
||||
let mut second = noto_fixture().index;
|
||||
second["samples"] = json!({"Thai": sample("second"), "Jpan": sample("Japanese")});
|
||||
let index = Index::merge([index_of(&first).unwrap(), index_of(&second).unwrap()]);
|
||||
|
||||
let sans = index.family_from(GOOGLE_FONTS, "Test Sans").unwrap();
|
||||
assert_eq!(
|
||||
(sans.tags.as_slice(), sans.reserved_names.as_slice()),
|
||||
(&["Sans".to_string(), "Display/Playful".to_string()][..], &["Test".to_string()][..])
|
||||
);
|
||||
assert_eq!(index.samples().keys().collect::<Vec<_>>(), ["Jpan", "Latn", "Thai"]);
|
||||
assert_eq!(index.sample("Thai").unwrap().text, "first");
|
||||
// Own text, then the file's script, which has no fallback (Zsym has no sample).
|
||||
assert_eq!(index.sample_text(sans, &sans.files[1]), Some("Own text"));
|
||||
assert_eq!(index.sample_text(sans, &sans.files[0]), Some("first"));
|
||||
assert_eq!(index.sample_text(sans, &sans.files[2]), None);
|
||||
let var = index.family_from(GOOGLE_FONTS, "Test Var").unwrap();
|
||||
assert_eq!((var.files[0].instances[0].name.as_str(), var.files[0].list_instance), ("Regular", Some(0)));
|
||||
|
||||
first["families"][3]["files"][0]["list_instance"] = json!(1);
|
||||
assert!(index_of(&first).is_err());
|
||||
first["families"][3]["files"][0]["list_instance"] = json!(0);
|
||||
first["samples"]["Latn"]["text"] = json!("bad\u{7}");
|
||||
assert!(index_of(&first).is_err());
|
||||
first["samples"]["Latn"] = sample("Hello");
|
||||
// An instance gives a coordinate for every axis, and only those.
|
||||
first["families"][3]["files"][0]["instances"] = json!([{"name": "Regular", "coordinates": {"wdth": 100.0}}]);
|
||||
assert!(index_of(&first).is_err());
|
||||
first["families"][3]["files"][0]["instances"] = json!([{"name": "Regular", "coordinates": {"wght": 400.0}}]);
|
||||
assert!(index_of(&first).is_ok());
|
||||
// Named instances belong to variable fonts only.
|
||||
first["families"][2]["files"][0]["instances"] = json!([{"name": "Bold", "coordinates": {}}]);
|
||||
assert!(index_of(&first).is_err());
|
||||
|
||||
// Every 1.2 string a user source can set is checked, one case at a time.
|
||||
let mut check = first.clone();
|
||||
check["families"][2]["files"][0]["instances"] = json!([]);
|
||||
check["families"][2]["copyright"] = json!("Copyright 2020 Test");
|
||||
check["families"][3]["files"][0]["instances"] = json!([{"name": "Regular", "coordinates": {"wght": 400.0}}]);
|
||||
assert!(index_of(&check).is_ok());
|
||||
fn reject(v: &mut serde_json::Value, path: &dyn Fn(&mut serde_json::Value) -> &mut serde_json::Value, bad: serde_json::Value, what: &str) {
|
||||
let good = std::mem::replace(path(v), bad);
|
||||
assert!(index_of(v).is_err(), "{what}");
|
||||
*path(v) = good;
|
||||
assert!(index_of(v).is_ok(), "{what} restored");
|
||||
}
|
||||
reject(&mut check, &|v| &mut v["families"][2]["tags"][0], json!("Sans\u{202e}"), "bidi control in a tag");
|
||||
reject(&mut check, &|v| &mut v["families"][2]["copyright"], json!("Copyright 2020\nTest"), "line break in a copyright");
|
||||
reject(&mut check, &|v| &mut v["families"][2]["files"][1]["sample_text"], json!("x".repeat(61)), "long sample text");
|
||||
reject(&mut check, &|v| &mut v["families"][3]["files"][0]["instances"][0]["coordinates"]["wght"], json!(900.0), "coordinate out of range");
|
||||
check["families"][3]["upstream"] = json!("https://example.org/repo");
|
||||
check["families"][3]["notice_file"] = json!({"path": "apache/testvar/NOTICE", "size": 1, "sha256": sha256_hex(b"x")});
|
||||
assert!(index_of(&check).is_ok());
|
||||
reject(&mut check, &|v| &mut v["families"][3]["upstream"], json!("http://example.org/repo"), "non-https upstream");
|
||||
reject(&mut check, &|v| &mut v["families"][3]["notice_file"]["sha256"], json!("abc"), "bad notice sha256");
|
||||
reject(&mut check, &|v| &mut v["families"][3]["notice_file"]["path"], json!("apache/testvar/TestVar[wght].ttf"), "notice named like a font");
|
||||
}
|
||||
|
||||
#[cfg(feature = "bundled-index")]
|
||||
const NOTO_COMMIT: &str = "93fac8abebe6c7fed0c5b7d2456d8fa484fa146c";
|
||||
const VAR_PATH: &str = "fonts/NotoSerifTest/full/variable-ttf/NotoSerifTest[wdth,wght].ttf";
|
||||
const CJK_PATH: &str = "Sans/OTF/Japanese/NotoSansCJKtest-Regular.otf";
|
||||
@@ -356,6 +436,261 @@ mod store {
|
||||
|
||||
fn none(_: Progress) {}
|
||||
|
||||
#[test]
|
||||
fn preview_service_is_a_mirror_tried_first() {
|
||||
let server = Server::start();
|
||||
let f = fixture();
|
||||
server.serve_fixture(&f);
|
||||
let index = index_of(&f.index).unwrap();
|
||||
let face = index.find_face("Test Sans", "Bold").unwrap();
|
||||
let sha = face.file.sha256.clone();
|
||||
let dir = temp("mirror");
|
||||
let user = FontStore::new(dir.clone(), Caller::User).with_client(server.client()).with_preview_env(None);
|
||||
user.enable_network().unwrap();
|
||||
|
||||
// No service: only the index's URLs.
|
||||
user.install_face(&index, face, &Cancel::new(), &mut none).unwrap();
|
||||
assert!(server.requests().iter().all(|r| !r.starts_with("/mirror/")));
|
||||
user.remove_family(&face.family.source, &face.family.family).unwrap();
|
||||
let before = server.requests().len();
|
||||
|
||||
// A service answering with the right bytes is the only request for the file.
|
||||
let bytes = f.files.iter().find(|(p, _)| p == &face.file.path).unwrap().1.clone();
|
||||
server.serve("mirror", &format!("v1/files/{sha}"), Reply::Ok(bytes));
|
||||
user.set_preview_service(Some(&format!("{}mirror/", server.base))).unwrap();
|
||||
user.install_face(&index, face, &Cancel::new(), &mut none).unwrap();
|
||||
let after = server.requests()[before..].to_vec();
|
||||
assert_eq!(after.first().map(String::as_str), Some(format!("/mirror/v1/files/{sha}").as_str()));
|
||||
assert!(after.iter().all(|r| !r.starts_with("/cdn/") || r.contains("LICENSE") || r.contains("OFL")), "{after:?}");
|
||||
user.remove_family(&face.family.source, &face.family.family).unwrap();
|
||||
|
||||
// The mirror is plain http to 127.0.0.1 and is fetched by a client that is https only
|
||||
// for everything else.
|
||||
let strict = {
|
||||
let mut c = Client::new(Timeouts::default());
|
||||
c.rewrite = vec![
|
||||
("https://cdn.jsdelivr.net/".into(), format!("{}cdn/", server.base)),
|
||||
("https://raw.githubusercontent.com/".into(), format!("{}raw/", server.base)),
|
||||
];
|
||||
c
|
||||
};
|
||||
let strict_user = FontStore::new(dir.clone(), Caller::User).with_client(strict).with_preview_env(None);
|
||||
server.serve("mirror", &format!("v1/files/{sha}"), Reply::Ok(f.files.iter().find(|(p, _)| p == &face.file.path).unwrap().1.clone()));
|
||||
let before = server.requests().len();
|
||||
// The licence has no mirror address here, and its index URLs are refused, so the install
|
||||
// fails; the file itself came from the mirror and nothing else was requested.
|
||||
let err = strict_user.install_face(&index, face, &Cancel::new(), &mut none).unwrap_err();
|
||||
let licence = face.family.license_file_name().unwrap();
|
||||
assert!(matches!(&err, Error::Download { what, .. } if what == licence), "{err:?}");
|
||||
assert_eq!(server.requests()[before..], [format!("/mirror/v1/files/{sha}")]);
|
||||
|
||||
// Bytes that fail the sha256 fall through to the index's URLs.
|
||||
server.serve("mirror", &format!("v1/files/{sha}"), Reply::Ok(b"not the font".to_vec()));
|
||||
user.install_face(&index, face, &Cancel::new(), &mut none).unwrap();
|
||||
assert!(user.is_installed(face.family, face.file));
|
||||
|
||||
// A family from a source the user added never goes to the service.
|
||||
let added = Index::from_user_bytes(f.index.to_string().as_bytes(), "https://fonts.example.org/index.json").unwrap();
|
||||
let face = added.find_face("Test Sans", "Bold").unwrap();
|
||||
let before = server.requests().len();
|
||||
user.legal_text(&added, face.family, crate::LegalText::License, &Cancel::new()).unwrap();
|
||||
user.install_face(&added, face, &Cancel::new(), &mut none).unwrap();
|
||||
assert!(server.requests()[before..].iter().all(|r| !r.starts_with("/mirror/")), "{:?}", &server.requests()[before..]);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_service_setting_is_user_only_and_https() {
|
||||
let dir = temp("service");
|
||||
let user = FontStore::new(dir.clone(), Caller::User).with_preview_env(None);
|
||||
let agent = FontStore::new(dir.clone(), Caller::Agent).with_preview_env(None);
|
||||
assert!(matches!(agent.set_preview_service(Some("https://fonts.example.com")), Err(Error::NotAllowed)));
|
||||
assert!(matches!(user.set_preview_service(Some("http://fonts.example.com")), Err(Error::BadServiceUrl(_))));
|
||||
assert!(matches!(user.set_preview_service(Some("ftp://fonts.example.com")), Err(Error::BadServiceUrl(_))));
|
||||
assert!(matches!(user.set_preview_service(Some("https://user@fonts.example.com")), Err(Error::BadServiceUrl(_))));
|
||||
assert!(matches!(user.set_preview_service(Some("http://localhost:8080/")), Err(Error::BadServiceUrl(_))));
|
||||
user.set_preview_service(Some("http://[::1]:8080/")).unwrap();
|
||||
assert_eq!(crate::check_preview_service(" http://127.0.0.1:9/x/ ").as_deref().ok(), Some("http://127.0.0.1:9/x"));
|
||||
assert!(matches!(crate::check_preview_service("https://fonts.example.com/?k=v"), Err(Error::BadServiceUrl(_))));
|
||||
user.set_preview_service(Some("https://fonts.example.com/")).unwrap();
|
||||
assert_eq!(agent.preview_service().as_deref(), Some("https://fonts.example.com"));
|
||||
user.set_preview_service(None).unwrap();
|
||||
assert_eq!(agent.preview_service(), None);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_preview_service_that_refuses_connections_is_tried_once_per_install() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let accepted = Arc::new(AtomicUsize::new(0));
|
||||
let count = Arc::clone(&accepted);
|
||||
// Takes each connection and drops it unanswered: a network failure.
|
||||
std::thread::spawn(move || {
|
||||
for _ in listener.incoming() {
|
||||
count.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
let server = Server::start();
|
||||
let f = fixture();
|
||||
server.serve_fixture(&f);
|
||||
let index = index_of(&f.index).unwrap();
|
||||
let family = index.family("Test Sans").unwrap();
|
||||
let dir = temp("down-mirror");
|
||||
let client = server.client();
|
||||
let user = FontStore::new(dir.clone(), Caller::User).with_client(client.clone()).with_preview_env(None);
|
||||
user.enable_network().unwrap();
|
||||
user.set_preview_service(Some(&format!("http://127.0.0.1:{port}"))).unwrap();
|
||||
user.install_family(&index, family, &Cancel::new(), &mut none).unwrap();
|
||||
// Three files and a licence, one attempt at the mirror.
|
||||
assert_eq!(accepted.load(Ordering::Relaxed), 1);
|
||||
assert!(client.service_is_down(&format!("http://127.0.0.1:{port}")));
|
||||
assert!(!client.service_is_down("https://fonts.example.com"));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_bytes_that_fail_the_check_are_not_a_corrupt_file_when_the_index_is_unreachable() {
|
||||
let server = Server::start();
|
||||
let f = fixture();
|
||||
let index = index_of(&f.index).unwrap();
|
||||
let face = index.find_face("Test Sans", "Bold").unwrap();
|
||||
server.serve("mirror", &format!("v1/files/{}", face.file.sha256), Reply::Ok(b"not the font".to_vec()));
|
||||
let dir = temp("bad-mirror");
|
||||
let user = FontStore::new(dir.clone(), Caller::User).with_client(server.client()).with_preview_env(None);
|
||||
user.enable_network().unwrap();
|
||||
user.set_preview_service(Some(&format!("{}mirror/", server.base))).unwrap();
|
||||
// The index's URLs are not served: they fail, so every reason is reported.
|
||||
match user.install_face(&index, face, &Cancel::new(), &mut none) {
|
||||
Err(Error::Download { reasons, .. }) => assert!(reasons.len() > 1 && reasons[0].contains("127.0.0.1"), "{reasons:?}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_with_other_timeouts_shares_the_down_state() {
|
||||
let client = Client::default();
|
||||
let short =
|
||||
client.with_timeouts(Timeouts { connect: Duration::from_secs(1), response: Duration::from_secs(1), overall: Duration::from_secs(2) });
|
||||
client.mark_service_down("https://fonts.example.com");
|
||||
assert!(short.service_is_down("https://fonts.example.com/v1/x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_service_marked_down_does_not_block_another() {
|
||||
let server = Server::start();
|
||||
server.serve("b", "x", Reply::Ok(b"ok".to_vec()));
|
||||
let client = server.client();
|
||||
client.mark_service_down("https://fonts.example.com/a");
|
||||
assert!(client.service_is_down("https://Fonts.example.com/b"));
|
||||
let url = format!("{}b/x", server.base);
|
||||
assert_eq!(client.get_from_service(&url, 100, &Cancel::new(), &mut |_| {}).unwrap(), b"ok");
|
||||
client.mark_service_down("https://other.example.com");
|
||||
assert!(client.service_is_down("https://fonts.example.com/a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loopback_http_is_refused_outside_the_preview_service() {
|
||||
let server = Server::start();
|
||||
server.serve("user", "index.json", Reply::Ok(b"{}".to_vec()));
|
||||
let mut client = Client::new(Timeouts::default());
|
||||
client.rewrite = vec![("https://fonts.example.org/".into(), server.base.clone())];
|
||||
let url = "https://fonts.example.org/user/index.json";
|
||||
let got = client.get(url, 1000, &Cancel::new(), &mut |_| {});
|
||||
assert!(matches!(got, Err(FetchError::Failed(_))), "{got:?}");
|
||||
assert!(server.requests().is_empty());
|
||||
assert_eq!(client.get_from_service(url, 1000, &Cancel::new(), &mut |_| {}).unwrap(), b"{}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn previews_are_on_by_default_and_only_the_user_turns_them_off() {
|
||||
let dir = temp("previews-setting");
|
||||
let user = FontStore::new(dir.clone(), Caller::User);
|
||||
let agent = FontStore::new(dir.clone(), Caller::Agent);
|
||||
assert!(user.previews_enabled());
|
||||
assert!(matches!(agent.set_previews_enabled(false), Err(Error::NotAllowed)));
|
||||
user.set_previews_enabled(false).unwrap();
|
||||
assert!(!agent.previews_enabled());
|
||||
// Other settings don't bring it back.
|
||||
user.set_preview_service(Some("https://fonts.example.com")).unwrap();
|
||||
assert!(!user.previews_enabled());
|
||||
user.set_previews_enabled(true).unwrap();
|
||||
assert!(user.previews_enabled());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_service_env_beats_the_setting() {
|
||||
let (env, setting) = (Some("https://a.example.com/"), Some("https://b.example.com"));
|
||||
assert_eq!(crate::store::resolve_preview_service(env, setting).as_deref(), Some("https://a.example.com"));
|
||||
assert_eq!(crate::store::resolve_preview_service(Some(""), setting).as_deref(), Some("https://b.example.com"));
|
||||
assert_eq!(crate::store::resolve_preview_service(None, None), None);
|
||||
let source = |env, setting| crate::store::resolve_preview_source(env, setting, None).1;
|
||||
assert_eq!(
|
||||
(source(env, setting), source(Some(" "), setting), source(None, None)),
|
||||
(PreviewServiceSource::Env, PreviewServiceSource::Saved, PreviewServiceSource::None)
|
||||
);
|
||||
assert_eq!(source(Some("http://fonts.example.com"), setting), PreviewServiceSource::None);
|
||||
assert_eq!(crate::store::resolve_preview_service(Some("http://fonts.example.com"), setting), None);
|
||||
assert_eq!(crate::store::resolve_preview_service(Some("http://127.0.0.1:9"), None).as_deref(), Some("http://127.0.0.1:9"));
|
||||
assert_eq!(crate::store::resolve_preview_service(Some("http://[::1]:9/x/"), None).as_deref(), Some("http://[::1]:9/x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_default_preview_service_comes_after_env_and_setting_and_is_never_saved() {
|
||||
let dir = temp("preview-default");
|
||||
let store =
|
||||
|env| FontStore::new(dir.clone(), Caller::User).with_default_preview_service("https://default.example.com/").with_preview_env(env);
|
||||
let user = store(None);
|
||||
let in_effect = |s: &FontStore| (s.preview_service(), s.preview_service_source());
|
||||
assert_eq!(in_effect(&user), (Some("https://default.example.com".into()), PreviewServiceSource::Default));
|
||||
user.set_preview_service(Some("https://saved.example.com")).unwrap();
|
||||
assert_eq!(in_effect(&user), (Some("https://saved.example.com".into()), PreviewServiceSource::Saved));
|
||||
assert_eq!(in_effect(&store(Some("https://env.example.com"))), (Some("https://env.example.com".into()), PreviewServiceSource::Env));
|
||||
user.set_preview_service(None).unwrap();
|
||||
assert_eq!(in_effect(&user), (Some("https://default.example.com".into()), PreviewServiceSource::Default));
|
||||
assert!(!std::fs::read_to_string(dir.join("settings.json")).unwrap().contains("default.example.com"));
|
||||
// Another app sharing the store without a default has no service.
|
||||
assert_eq!(FontStore::new(dir.clone(), Caller::User).with_preview_env(None).preview_service(), None);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_network_choice_beats_the_host_default_which_beats_off() {
|
||||
let dir = temp("network-default");
|
||||
let host = |network| FontStore::new(dir.clone(), Caller::User).with_default_network(network);
|
||||
assert_eq!(FontStore::new(dir.clone(), Caller::User).network(), Network::Off);
|
||||
assert_eq!(host(Network::On).network(), Network::On);
|
||||
assert_eq!(FontStore::new(dir.clone(), Caller::Agent).with_default_network(Network::On).network(), Network::Off);
|
||||
// Another setting saved meanwhile is not a network choice.
|
||||
host(Network::On).set_previews_enabled(false).unwrap();
|
||||
assert_eq!(host(Network::On).network(), Network::On);
|
||||
assert!(!std::fs::read_to_string(dir.join("settings.json")).unwrap().contains("network"));
|
||||
host(Network::On).disable_network().unwrap();
|
||||
assert_eq!(host(Network::On).network(), Network::Off);
|
||||
host(Network::Off).enable_network().unwrap();
|
||||
assert_eq!(host(Network::Off).network(), Network::On);
|
||||
// A file from before the choice could be absent: its "off" is the user's.
|
||||
std::fs::write(dir.join("settings.json"), br#"{"network":"off","user_sources":[]}"#).unwrap();
|
||||
assert_eq!(host(Network::On).network(), Network::Off);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_settings_file_that_does_not_parse_fails_closed() {
|
||||
let dir = temp("settings-broken");
|
||||
let host = |network| FontStore::new(dir.clone(), Caller::User).with_default_network(network);
|
||||
std::fs::write(dir.join("settings.json"), b"{not json").unwrap();
|
||||
// No network and no preview service, not even the host's; a setting saved over the file
|
||||
// keeps the network off.
|
||||
let broken = host(Network::On).with_default_preview_service("https://default.example.com").with_preview_env(None);
|
||||
assert_eq!((broken.network(), broken.preview_service(), broken.previews_enabled()), (Network::Off, None, true));
|
||||
broken.set_previews_enabled(true).unwrap();
|
||||
assert_eq!(host(Network::On).network(), Network::Off);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_verify_and_remove_a_family() {
|
||||
let server = Server::start();
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "craft-material-graph"
|
||||
description = "Text material graphs with a CPU reference evaluator and GPU acceleration interfaces"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# One implementation of sin, exp, pow ... for every platform, so renders are the same bits everywhere (MIT).
|
||||
libm = "0.2.16"
|
||||
# Data-parallel loops (MIT OR Apache-2.0).
|
||||
rayon = { workspace = true }
|
||||
@@ -0,0 +1,8 @@
|
||||
craft-material-graph
|
||||
Derived from MaterialCraft by PiJellyPin and contributors (https://github.com/PiJellyPin/MaterialCraft, not
|
||||
storytold/materialcraft): copied and adapted, not a dependency.
|
||||
Adapted for the original TextureCraft SPP importer by xilefenko with subsequent contributions from vangel76.
|
||||
The original notice also covers the PNG encoder copy in TextureCraft's original project reader.
|
||||
Extracted into craft-libs from TextureCraft at 22a37c29e98d8e6fc8c5e611e22f0ab95b83243d.
|
||||
|
||||
Dual licensed under the Apache License 2.0 or the MIT License, at your option.
|
||||
@@ -0,0 +1,95 @@
|
||||
//! Writes the node kind versions caches key on (`src/versions.rs`), from the source of what each node kind reaches:
|
||||
//! see `build/source`. Nothing is written by hand, so changing a node can't be forgotten.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[path = "build/digest.rs"]
|
||||
mod digest;
|
||||
#[allow(dead_code)]
|
||||
#[path = "build/source/mod.rs"]
|
||||
mod source;
|
||||
|
||||
use digest::{Fingerprint, epoch_in, with_epoch};
|
||||
use source::items::Dispatcher;
|
||||
use source::modules::reachable;
|
||||
use source::{SourceFile, SourceTree, included_files};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The functions that pick by node kind.
|
||||
const DISPATCHERS: &[Dispatcher] = &[
|
||||
Dispatcher { file: "src/graph.rs", function: "compute" },
|
||||
Dispatcher { file: "src/graph.rs", function: "compute_generator" },
|
||||
Dispatcher { file: "src/graph.rs", function: "compute_host_node" },
|
||||
Dispatcher { file: "src/graph.rs", function: "compute_resident_image" },
|
||||
Dispatcher { file: "src/graph.rs", function: "compute_resident_grey" },
|
||||
Dispatcher { file: "src/nodes2.rs", function: "compute" },
|
||||
Dispatcher { file: "src/atomic.rs", function: "compute" },
|
||||
Dispatcher { file: "src/compiled_ops.rs", function: "compute" },
|
||||
];
|
||||
|
||||
/// What every kind goes through: evaluating a graph, and reading and writing images.
|
||||
const SHARED: &[&str] = &["eval_node", "evaluate_with_inputs", "parse", "encode", "decode"];
|
||||
|
||||
/// The code results come out of: what this file's module paths reach.
|
||||
const START: &str = "src/graph.rs";
|
||||
|
||||
fn rust_files(dir: &Path, root: &Path, out: &mut Vec<SourceFile>) {
|
||||
let Ok(list) = std::fs::read_dir(dir) else { return };
|
||||
let mut paths: Vec<PathBuf> = list.flatten().map(|e| e.path()).collect();
|
||||
paths.sort();
|
||||
for path in paths {
|
||||
if path.is_dir() {
|
||||
rust_files(&path, root, out);
|
||||
} else if path.extension().is_some_and(|e| e == "rs") {
|
||||
let Ok(text) = std::fs::read_to_string(&path) else { continue };
|
||||
let name = path.strip_prefix(root).unwrap_or(&path).display().to_string().replace('\\', "/");
|
||||
let included = included_files(&text, path.parent().unwrap_or(root));
|
||||
out.push(SourceFile { name, text, included });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What isn't source but changes results: the compiler, its settings, the dependencies.
|
||||
fn toolchain(lock: &Path) -> String {
|
||||
let mut f = Fingerprint::of("toolchain");
|
||||
let rustc = std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_string());
|
||||
let version = std::process::Command::new(rustc).arg("-vV").output().map(|o| o.stdout).unwrap_or_default();
|
||||
f.bytes(&version);
|
||||
for name in ["TARGET", "OPT_LEVEL", "PROFILE", "CARGO_CFG_TARGET_FEATURE", "CARGO_ENCODED_RUSTFLAGS"] {
|
||||
f.text(name);
|
||||
f.text(&std::env::var(name).unwrap_or_default());
|
||||
}
|
||||
f.bytes(&std::fs::read(lock).unwrap_or_default());
|
||||
f.finish().to_hex()
|
||||
}
|
||||
|
||||
fn main() -> std::io::Result<()> {
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
println!("cargo:rerun-if-changed=build");
|
||||
println!("cargo:rerun-if-changed=src");
|
||||
let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap_or_default());
|
||||
// the workspace's lock file, two folders up (`crates/material-graph`)
|
||||
let lock = manifest.join("../../Cargo.lock");
|
||||
println!("cargo:rerun-if-changed={}", lock.display());
|
||||
// the number a developer bumps for a change the source doesn't show: it goes into every version
|
||||
let epoch = epoch_in(&std::fs::read_to_string(manifest.join("src/versions.rs")).unwrap_or_default());
|
||||
let mut files = Vec::new();
|
||||
rust_files(&manifest.join("src"), &manifest, &mut files);
|
||||
let engine: Vec<SourceFile> = reachable(&files, "src", &[START]).into_iter().cloned().collect();
|
||||
let tree = SourceTree::scan(&engine, DISPATCHERS);
|
||||
|
||||
let mut out = String::new();
|
||||
out.push_str(&format!("pub const TOOLCHAIN: &str = {:?};\n", toolchain(&lock)));
|
||||
out.push_str(&format!("pub const ALL: &str = {:?};\n", with_epoch(&epoch, &tree.all("all kinds")).to_hex()));
|
||||
out.push_str(&format!("pub const FILES: usize = {};\n", engine.len()));
|
||||
out.push_str("pub const KINDS: &[(&str, &str)] = &[\n");
|
||||
for kind in tree.kinds() {
|
||||
if let Some(version) = tree.kind_version(kind, SHARED) {
|
||||
out.push_str(&format!(" ({kind:?}, {:?}),\n", with_epoch(&epoch, &version).to_hex()));
|
||||
}
|
||||
}
|
||||
out.push_str("];\n");
|
||||
let dir = PathBuf::from(std::env::var("OUT_DIR").unwrap_or_default());
|
||||
// a failure stops the build: an older file left in `OUT_DIR` would give a new evaluator the old versions
|
||||
std::fs::write(dir.join("kind_versions.rs"), out)
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//! [`Fingerprint`]: SHA-256 (FIPS 180-4) over typed values. A collision would be a stale result that nothing could
|
||||
//! detect, which rules out the 64-bit hashes the in-memory caches get away with. Every value is written with its length
|
||||
//! or a fixed width, so that two different sequences of values never give the same bytes.
|
||||
|
||||
/// The round constants: the first 32 bits of the fractional parts of the cube roots of the first 64 primes.
|
||||
const K: [u32; 64] = [
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
|
||||
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
|
||||
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
|
||||
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
||||
];
|
||||
|
||||
const START: [u32; 8] = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
|
||||
|
||||
/// A finished fingerprint.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct Digest(pub [u8; 32]);
|
||||
|
||||
impl Digest {
|
||||
pub fn to_hex(self) -> String {
|
||||
let mut out = String::with_capacity(64);
|
||||
for b in self.0 {
|
||||
out.push(char::from_digit(u32::from(b >> 4), 16).unwrap_or('0'));
|
||||
out.push(char::from_digit(u32::from(b & 15), 16).unwrap_or('0'));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The digest `hex` spells, as [`Digest::to_hex`] writes it.
|
||||
pub fn from_hex(hex: &str) -> Option<Digest> {
|
||||
let bytes = hex.as_bytes();
|
||||
if bytes.len() != 64 {
|
||||
return None;
|
||||
}
|
||||
let mut out = [0u8; 32];
|
||||
for (o, [high, low]) in out.iter_mut().zip(bytes.as_chunks::<2>().0) {
|
||||
let digit = |b: u8| char::from(b).to_digit(16);
|
||||
*o = (digit(*high)? * 16 + digit(*low)?) as u8;
|
||||
}
|
||||
Some(Digest(out))
|
||||
}
|
||||
}
|
||||
|
||||
/// A running SHA-256 over typed values.
|
||||
#[derive(Clone)]
|
||||
pub struct Fingerprint {
|
||||
state: [u32; 8],
|
||||
block: [u8; 64],
|
||||
filled: usize,
|
||||
length: u64,
|
||||
}
|
||||
|
||||
impl Default for Fingerprint {
|
||||
fn default() -> Self {
|
||||
Fingerprint { state: START, block: [0; 64], filled: 0, length: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Fingerprint {
|
||||
/// A fingerprint of one purpose: results of different kinds never meet, even over equal values.
|
||||
pub fn of(purpose: &str) -> Fingerprint {
|
||||
let mut f = Fingerprint::default();
|
||||
f.text(purpose);
|
||||
f
|
||||
}
|
||||
|
||||
/// Raw bytes, with no length: for a sequence whose length is written apart.
|
||||
pub fn raw(&mut self, mut data: &[u8]) {
|
||||
self.length = self.length.wrapping_add(data.len() as u64);
|
||||
if self.filled > 0 {
|
||||
let room = 64 - self.filled;
|
||||
let (now, rest) = data.split_at(room.min(data.len()));
|
||||
if let Some(slot) = self.block.get_mut(self.filled..self.filled + now.len()) {
|
||||
slot.copy_from_slice(now);
|
||||
}
|
||||
self.filled += now.len();
|
||||
data = rest;
|
||||
if self.filled < 64 {
|
||||
return;
|
||||
}
|
||||
let block = self.block;
|
||||
self.compress(&block);
|
||||
self.filled = 0;
|
||||
}
|
||||
let (blocks, rest) = data.as_chunks::<64>();
|
||||
for block in blocks {
|
||||
self.compress(block);
|
||||
}
|
||||
if let Some(slot) = self.block.get_mut(..rest.len()) {
|
||||
slot.copy_from_slice(rest);
|
||||
}
|
||||
self.filled = rest.len();
|
||||
}
|
||||
|
||||
pub fn u64(&mut self, v: u64) {
|
||||
self.raw(&v.to_le_bytes());
|
||||
}
|
||||
|
||||
/// Bytes with their length.
|
||||
pub fn bytes(&mut self, data: &[u8]) {
|
||||
self.u64(data.len() as u64);
|
||||
self.raw(data);
|
||||
}
|
||||
|
||||
pub fn text(&mut self, text: &str) {
|
||||
self.bytes(text.as_bytes());
|
||||
}
|
||||
|
||||
pub fn digest(&mut self, d: &Digest) {
|
||||
self.raw(&d.0);
|
||||
}
|
||||
|
||||
/// Floats by their bits: a different bit pattern is a different input.
|
||||
pub fn floats(&mut self, values: &[f32]) {
|
||||
self.u64(values.len() as u64);
|
||||
let mut buffer = [0u8; 4096];
|
||||
for chunk in values.chunks(buffer.len() / 4) {
|
||||
for (o, v) in buffer.as_chunks_mut::<4>().0.iter_mut().zip(chunk) {
|
||||
o.copy_from_slice(&v.to_bits().to_le_bytes());
|
||||
}
|
||||
if let Some(used) = buffer.get(..chunk.len() * 4) {
|
||||
self.raw(used);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finish(mut self) -> Digest {
|
||||
let bits = self.length.wrapping_mul(8);
|
||||
self.raw(&[0x80]);
|
||||
while self.filled != 56 {
|
||||
self.raw(&[0]);
|
||||
}
|
||||
self.raw(&bits.to_be_bytes());
|
||||
let mut out = [0u8; 32];
|
||||
for (o, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(self.state) {
|
||||
o.copy_from_slice(&s.to_be_bytes());
|
||||
}
|
||||
Digest(out)
|
||||
}
|
||||
|
||||
fn compress(&mut self, block: &[u8; 64]) {
|
||||
let mut w = [0u32; 64];
|
||||
for (o, c) in w.iter_mut().zip(block.as_chunks::<4>().0) {
|
||||
*o = u32::from_be_bytes(*c);
|
||||
}
|
||||
for i in 16..64 {
|
||||
let at = |k: usize| w.get(i - k).copied().unwrap_or(0);
|
||||
let s0 = at(15).rotate_right(7) ^ at(15).rotate_right(18) ^ (at(15) >> 3);
|
||||
let s1 = at(2).rotate_right(17) ^ at(2).rotate_right(19) ^ (at(2) >> 10);
|
||||
let value = at(16).wrapping_add(s0).wrapping_add(at(7)).wrapping_add(s1);
|
||||
if let Some(slot) = w.get_mut(i) {
|
||||
*slot = value;
|
||||
}
|
||||
}
|
||||
let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = self.state;
|
||||
for (word, constant) in w.iter().zip(K) {
|
||||
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
|
||||
let ch = (e & f) ^ (!e & g);
|
||||
let t1 = h.wrapping_add(s1).wrapping_add(ch).wrapping_add(constant).wrapping_add(*word);
|
||||
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
|
||||
let maj = (a & b) ^ (a & c) ^ (b & c);
|
||||
let t2 = s0.wrapping_add(maj);
|
||||
(h, g, f, e, d, c, b, a) = (g, f, e, d.wrapping_add(t1), c, b, a, t1.wrapping_add(t2));
|
||||
}
|
||||
for (s, v) in self.state.iter_mut().zip([a, b, c, d, e, f, g, h]) {
|
||||
*s = s.wrapping_add(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What `pub const EPOCH` is set to in the text of `versions.rs`; empty when it isn't found.
|
||||
pub fn epoch_in(text: &str) -> String {
|
||||
let line = text.lines().find(|l| l.trim_start().starts_with("pub const EPOCH"));
|
||||
line.and_then(|l| l.split('=').nth(1)).map(|v| v.trim().trim_end_matches(';').trim().to_string()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `version` with `epoch` mixed in: bumping the epoch changes every version that goes through here.
|
||||
pub fn with_epoch(epoch: &str, version: &Digest) -> Digest {
|
||||
let mut f = Fingerprint::of("epoch");
|
||||
f.text(epoch);
|
||||
f.digest(version);
|
||||
f.finish()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_epoch_is_read_and_changes_every_version() {
|
||||
assert_eq!(epoch_in("/// docs\npub const EPOCH: u32 = 12;\nmod generated {}"), "12");
|
||||
assert_eq!(epoch_in("nothing"), "");
|
||||
let version = Fingerprint::of("kind").finish();
|
||||
assert_ne!(with_epoch("1", &version), with_epoch("2", &version));
|
||||
assert_ne!(with_epoch("1", &version), version);
|
||||
assert_eq!(with_epoch("1", &version), with_epoch("1", &version));
|
||||
}
|
||||
|
||||
fn sha(data: &[u8]) -> String {
|
||||
let mut f = Fingerprint::default();
|
||||
f.raw(data);
|
||||
f.finish().to_hex()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_answers() {
|
||||
assert_eq!(sha(b""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
|
||||
assert_eq!(sha(b"abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
|
||||
assert_eq!(
|
||||
sha(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
|
||||
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
|
||||
);
|
||||
assert_eq!(sha(&[b'a'; 1_000_000]), "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feeding_in_pieces_gives_the_same() {
|
||||
let data: Vec<u8> = (0..1000u32).map(|v| v as u8).collect();
|
||||
let mut pieces = Fingerprint::default();
|
||||
for chunk in data.chunks(7) {
|
||||
pieces.raw(chunk);
|
||||
}
|
||||
assert_eq!(pieces.finish().to_hex(), sha(&data));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_do_not_run_into_each_other() {
|
||||
let of = |parts: &[&str]| {
|
||||
let mut f = Fingerprint::of("test");
|
||||
parts.iter().for_each(|p| f.text(p));
|
||||
f.finish()
|
||||
};
|
||||
assert_ne!(of(&["ab", "c"]), of(&["a", "bc"]));
|
||||
assert_ne!(Fingerprint::of("one").finish(), Fingerprint::of("two").finish());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_round_trip() {
|
||||
let d = Fingerprint::of("x").finish();
|
||||
assert_eq!(Digest::from_hex(&d.to_hex()), Some(d));
|
||||
assert_eq!(Digest::from_hex("zz"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,640 @@
|
||||
//! Source files as items: functions, types, constants and macros, each with its tokens and what it names. Whatever
|
||||
//! isn't recognised as an item ends up in [`Item::loose`] and counts for every result, so that not understanding some
|
||||
//! syntax can only invalidate too much.
|
||||
|
||||
use super::tokens::{Token, tokenize};
|
||||
use std::path::Path;
|
||||
|
||||
/// One thing an item names.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub enum Mention {
|
||||
/// `name`, `.name`
|
||||
Name(String),
|
||||
/// `Owner::name`
|
||||
Path(String, String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ItemKind {
|
||||
Function,
|
||||
/// A struct, enum, union, trait or type alias.
|
||||
Type,
|
||||
/// A constant, static or macro.
|
||||
Value,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Item {
|
||||
pub name: String,
|
||||
pub kind: ItemKind,
|
||||
/// The type an `impl` or `trait` block gives it.
|
||||
pub owner: Option<String>,
|
||||
/// Inside `impl Trait for Owner`: operators, `Drop`, `Default` and the like run without being named.
|
||||
pub trait_impl: bool,
|
||||
/// What the digest is taken over.
|
||||
pub tokens: Vec<Token>,
|
||||
pub mentions: Vec<Mention>,
|
||||
/// Counts for every result.
|
||||
pub loose: bool,
|
||||
/// A file `include_bytes!` and the like pull in, relative to the source file.
|
||||
pub includes: Vec<String>,
|
||||
/// The file it is in, for telling a developer what a version covers.
|
||||
pub file: String,
|
||||
}
|
||||
|
||||
/// `use a::b as c`: `c` stands for `b`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Alias {
|
||||
pub alias: String,
|
||||
pub target: String,
|
||||
}
|
||||
|
||||
/// A match arm naming a node kind, cut out of a [`Dispatcher`]'s function.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Arm {
|
||||
pub kinds: Vec<String>,
|
||||
/// How many arms that aren't literal-only (a guard, a binding) come before it in the match. The first arm that
|
||||
/// matches wins, so moving a literal arm past such an arm changes what runs.
|
||||
pub after: usize,
|
||||
pub tokens: Vec<Token>,
|
||||
pub mentions: Vec<Mention>,
|
||||
}
|
||||
|
||||
/// A function whose outermost `match` picks by node kind. Each literal arm counts only for the kinds it names.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Dispatcher<'a> {
|
||||
pub file: &'a str,
|
||||
pub function: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Parsed {
|
||||
pub items: Vec<Item>,
|
||||
pub aliases: Vec<Alias>,
|
||||
pub arms: Vec<Arm>,
|
||||
}
|
||||
|
||||
const NOT_NAMES: &[&str] = &[
|
||||
"as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod",
|
||||
"move", "mut", "pub", "ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where", "while",
|
||||
"async", "await", "dyn",
|
||||
];
|
||||
|
||||
/// What `tokens` name. `owner` stands for `Self`.
|
||||
pub fn mentions_in(tokens: &[Token], owner: Option<&str>) -> Vec<Mention> {
|
||||
let mut out = Vec::new();
|
||||
for (i, t) in tokens.iter().enumerate() {
|
||||
let Some(name) = t.ident() else { continue };
|
||||
let double_colon_at = |k: usize| tokens.get(k).is_some_and(|c| c.is_punct(':')) && tokens.get(k + 1).is_some_and(|c| c.is_punct(':'));
|
||||
// `Owner::name`, with the owner possibly `Self`
|
||||
if i >= 3 && double_colon_at(i - 2) {
|
||||
let before = tokens.get(i - 3).and_then(Token::ident);
|
||||
let before = if before == Some("Self") { owner } else { before };
|
||||
if let Some(path_owner) = before.filter(|b| !NOT_NAMES.contains(b)) {
|
||||
if !NOT_NAMES.contains(&name) {
|
||||
out.push(Mention::Path(path_owner.to_string(), name.to_string()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if !NOT_NAMES.contains(&name) {
|
||||
out.push(Mention::Name(name.to_string()));
|
||||
}
|
||||
}
|
||||
if tokens.iter().any(|t| t.is("Self")) {
|
||||
out.extend(owner.map(|o| Mention::Name(o.to_string())));
|
||||
}
|
||||
out.sort();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// The files `include_bytes!("x")`, `include_str!`, `include!` in `tokens` name.
|
||||
pub fn includes_in(tokens: &[Token]) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
for (i, t) in tokens.iter().enumerate() {
|
||||
if t.is("include_bytes") || t.is("include_str") || t.is("include") {
|
||||
let text = tokens.iter().skip(i + 1).take(3).find_map(|x| match x {
|
||||
Token::Text(s) | Token::Raw(s) => Some(s.clone()),
|
||||
_ => None,
|
||||
});
|
||||
out.extend(text);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn opens(t: &Token) -> bool {
|
||||
t.is_punct('{') || t.is_punct('(') || t.is_punct('[')
|
||||
}
|
||||
|
||||
fn closes(t: &Token) -> bool {
|
||||
t.is_punct('}') || t.is_punct(')') || t.is_punct(']')
|
||||
}
|
||||
|
||||
/// The index just past the bracket closing the one at `open`.
|
||||
fn past_group(tokens: &[Token], open: usize) -> usize {
|
||||
let mut depth = 0usize;
|
||||
for (i, t) in tokens.iter().enumerate().skip(open) {
|
||||
if opens(t) {
|
||||
depth += 1;
|
||||
} else if closes(t) {
|
||||
depth = depth.saturating_sub(1);
|
||||
if depth == 0 {
|
||||
return i + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
tokens.len()
|
||||
}
|
||||
|
||||
/// The index just past the item starting at `from`, which ends with `;` or, when `braces` allows, a `{…}` outside any
|
||||
/// other bracket.
|
||||
pub(super) fn past_item(tokens: &[Token], from: usize, braces: bool) -> usize {
|
||||
let mut i = from;
|
||||
while let Some(t) = tokens.get(i) {
|
||||
if t.is_punct(';') {
|
||||
return i + 1;
|
||||
}
|
||||
if t.is_punct('{') && braces {
|
||||
return past_group(tokens, i);
|
||||
}
|
||||
i = if opens(t) { past_group(tokens, i) } else { i + 1 };
|
||||
}
|
||||
tokens.len()
|
||||
}
|
||||
|
||||
struct Parser<'a> {
|
||||
tokens: &'a [Token],
|
||||
file: &'a str,
|
||||
out: Parsed,
|
||||
/// Tokens no item took.
|
||||
loose: Vec<Token>,
|
||||
/// The attributes and name of the enclosing inline modules that have attributes: `#[cfg(unix)] mod backend`
|
||||
/// decides whether what is inside exists, so it goes into the digest of each item inside.
|
||||
scope: Vec<Token>,
|
||||
}
|
||||
|
||||
impl Parser<'_> {
|
||||
fn add(&mut self, from: usize, to: usize, name: &str, kind: ItemKind, owner: Option<&str>, trait_impl: bool) {
|
||||
let tokens = self.tokens.get(from..to).unwrap_or(&[]);
|
||||
let includes = includes_in(tokens);
|
||||
let tokens = self.scoped(tokens);
|
||||
self.out.items.push(Item {
|
||||
name: name.to_string(),
|
||||
kind,
|
||||
owner: owner.map(str::to_string),
|
||||
trait_impl,
|
||||
mentions: mentions_in(&tokens, owner),
|
||||
tokens,
|
||||
loose: false,
|
||||
includes,
|
||||
file: self.file.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
/// `tokens` after the attributes of the modules around them.
|
||||
fn scoped(&self, tokens: &[Token]) -> Vec<Token> {
|
||||
let mut out = self.scope.clone();
|
||||
out.extend_from_slice(tokens);
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the item starting at `start` has attributes.
|
||||
fn has_attributes(&self, start: usize) -> bool {
|
||||
self.tokens.get(start).is_some_and(|t| t.is_punct('#'))
|
||||
}
|
||||
|
||||
/// `use` declarations: their `as` renames.
|
||||
fn aliases(&mut self, from: usize, to: usize) {
|
||||
let tokens = self.tokens.get(from..to).unwrap_or(&[]);
|
||||
for (i, t) in tokens.iter().enumerate() {
|
||||
if t.is("as") && i > 0 {
|
||||
let target = tokens.get(i - 1).and_then(Token::ident);
|
||||
let alias = tokens.get(i + 1).and_then(Token::ident);
|
||||
if let (Some(target), Some(alias)) = (target, alias) {
|
||||
self.out.aliases.push(Alias { alias: alias.to_string(), target: target.to_string() });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `use` declaration at `at` (its attributes start at `start`); the index past it.
|
||||
fn use_declaration(&mut self, start: usize, at: usize) -> usize {
|
||||
let end = past_item(self.tokens, at, false);
|
||||
self.aliases(at, end);
|
||||
if self.has_attributes(start) {
|
||||
// `#[cfg(unix)] use a::shade;` decides which `shade` runs: it counts for every result
|
||||
let tokens = self.tokens;
|
||||
self.loose.extend_from_slice(tokens.get(start..end).unwrap_or(&[]));
|
||||
}
|
||||
end
|
||||
}
|
||||
|
||||
/// The `mod` at `at` (its attributes start at `start`); the index past it. An inline module's items are parsed.
|
||||
fn module(&mut self, start: usize, at: usize) -> usize {
|
||||
let end = past_item(self.tokens, at, true);
|
||||
if end > 0 && self.tokens.get(end - 1).is_some_and(|c| c.is_punct('}')) {
|
||||
let outer = self.scope.len();
|
||||
if self.has_attributes(start) {
|
||||
let tokens = self.tokens;
|
||||
self.scope.extend_from_slice(tokens.get(start..at + 2).unwrap_or(&[]));
|
||||
}
|
||||
self.items(at + 3, end - 1, None, false);
|
||||
self.scope.truncate(outer);
|
||||
}
|
||||
end
|
||||
}
|
||||
|
||||
/// The items of a module or `impl` body, from `from` to `to`.
|
||||
fn items(&mut self, from: usize, to: usize, owner: Option<&str>, trait_impl: bool) {
|
||||
let mut i = from;
|
||||
let mut attributes = from;
|
||||
while i < to {
|
||||
let Some(t) = self.tokens.get(i) else { return };
|
||||
// attributes stay with their item; `#[cfg(test)]` takes it out
|
||||
if t.is_punct('#') && self.tokens.get(i + 1).is_some_and(|n| n.is_punct('[')) {
|
||||
let end = past_group(self.tokens, i + 1);
|
||||
let test = self.tokens.get(i + 2).is_some_and(|n| n.is("cfg")) && self.tokens.get(i + 4).is_some_and(|n| n.is("test"));
|
||||
if test {
|
||||
i = past_item(self.tokens, end, true);
|
||||
attributes = i;
|
||||
} else {
|
||||
i = end;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if t.is("pub") {
|
||||
i += 1;
|
||||
if self.tokens.get(i).is_some_and(|n| n.is_punct('(')) {
|
||||
i = past_group(self.tokens, i);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if t.is("unsafe") || t.is("async") || t.is("default") {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let next = self.tokens.get(i + 1);
|
||||
if t.is("extern") {
|
||||
// `extern "C" fn`, `extern crate x;`
|
||||
i += if matches!(next, Some(Token::Text(_))) { 2 } else { 1 };
|
||||
continue;
|
||||
}
|
||||
if t.is("const") && next.is_some_and(|n| n.is("fn") || n.is("unsafe") || n.is("extern")) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let name = next.and_then(Token::ident).unwrap_or("").to_string();
|
||||
let start = attributes;
|
||||
let end = if t.is("fn") {
|
||||
let end = past_item(self.tokens, i, true);
|
||||
self.add(start, end, &name, ItemKind::Function, owner, trait_impl);
|
||||
end
|
||||
} else if t.is("struct") || t.is("enum") || t.is("union") {
|
||||
let end = past_item(self.tokens, i, true);
|
||||
self.add(start, end, &name, ItemKind::Type, owner, trait_impl);
|
||||
end
|
||||
} else if t.is("type") {
|
||||
let end = past_item(self.tokens, i, false);
|
||||
self.add(start, end, &name, ItemKind::Type, owner, trait_impl);
|
||||
end
|
||||
} else if t.is("const") || t.is("static") {
|
||||
let name =
|
||||
if next.is_some_and(|n| n.is("mut")) { self.tokens.get(i + 2).and_then(Token::ident).unwrap_or("").to_string() } else { name };
|
||||
let end = past_item(self.tokens, i, false);
|
||||
self.add(start, end, &name, ItemKind::Value, owner, trait_impl);
|
||||
end
|
||||
} else if t.is("use") {
|
||||
self.use_declaration(start, i)
|
||||
} else if t.is("mod") {
|
||||
self.module(start, i)
|
||||
} else if t.is("trait") {
|
||||
let end = past_item(self.tokens, i, true);
|
||||
self.body_block(start, i, end, &name, ItemKind::Type, false);
|
||||
end
|
||||
} else if t.is("impl") {
|
||||
let end = past_item(self.tokens, i, true);
|
||||
let target = impl_target(self.tokens.get(i..end).unwrap_or(&[]));
|
||||
let first = self.out.items.len();
|
||||
self.body_block(start, i, end, &target.owner, ItemKind::Value, target.is_trait);
|
||||
if target.blanket {
|
||||
self.out.items.iter_mut().skip(first).for_each(|item| item.loose = true);
|
||||
}
|
||||
end
|
||||
} else if t.is("macro_rules") {
|
||||
let name = self.tokens.get(i + 2).and_then(Token::ident).unwrap_or("").to_string();
|
||||
let end = past_item(self.tokens, i, true);
|
||||
self.add(start, end, &name, ItemKind::Value, owner, trait_impl);
|
||||
end
|
||||
} else if t.is("thread_local") {
|
||||
let open = i + 2;
|
||||
let end = past_group(self.tokens, open);
|
||||
self.items(open + 1, end.saturating_sub(1), owner, trait_impl);
|
||||
end + usize::from(self.tokens.get(end).is_some_and(|n| n.is_punct(';')))
|
||||
} else {
|
||||
self.loose.push(t.clone());
|
||||
i + 1
|
||||
};
|
||||
i = end;
|
||||
attributes = i;
|
||||
}
|
||||
}
|
||||
|
||||
/// A `trait` or `impl` block: its header (and what isn't a function) is one item named `name`, its functions are
|
||||
/// items of their own.
|
||||
fn body_block(&mut self, start: usize, keyword: usize, end: usize, name: &str, kind: ItemKind, trait_impl: bool) {
|
||||
let Some(open) = (keyword..end).find(|&k| self.tokens.get(k).is_some_and(|t| t.is_punct('{'))) else { return };
|
||||
// the header's tokens with no body: a change of bounds or of the target counts
|
||||
let header = self.tokens.get(start..open).unwrap_or(&[]);
|
||||
let header = self.scoped(header);
|
||||
self.out.items.push(Item {
|
||||
name: name.to_string(),
|
||||
kind,
|
||||
owner: Some(name.to_string()),
|
||||
trait_impl,
|
||||
mentions: mentions_in(&header, Some(name)),
|
||||
tokens: header,
|
||||
loose: false,
|
||||
includes: Vec::new(),
|
||||
file: self.file.to_string(),
|
||||
});
|
||||
self.items(open + 1, end.saturating_sub(1), Some(name), trait_impl);
|
||||
}
|
||||
}
|
||||
|
||||
struct ImplTarget {
|
||||
owner: String,
|
||||
is_trait: bool,
|
||||
/// `impl<T> X for T`: for every type, so for every result.
|
||||
blanket: bool,
|
||||
}
|
||||
|
||||
/// The type an `impl` block's header is for: the last segment of the path after `for`, or else the first path.
|
||||
fn impl_target(tokens: &[Token]) -> ImplTarget {
|
||||
let open = tokens.iter().position(|t| t.is_punct('{')).unwrap_or(tokens.len());
|
||||
let header = tokens.get(1..open).unwrap_or(&[]);
|
||||
// the generic parameters right after `impl`
|
||||
let mut params = Vec::new();
|
||||
let mut skip = 0;
|
||||
if header.first().is_some_and(|t| t.is_punct('<')) {
|
||||
let mut depth = 0i32;
|
||||
for (i, t) in header.iter().enumerate() {
|
||||
if t.is_punct('<') {
|
||||
depth += 1;
|
||||
} else if t.is_punct('>') && !header.get(i.wrapping_sub(1)).is_some_and(|p| p.is_punct('-')) {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
skip = i + 1;
|
||||
break;
|
||||
}
|
||||
} else if depth == 1 && header.get(i.wrapping_sub(1)).is_some_and(|p| p.is_punct('<') || p.is_punct(',')) {
|
||||
params.extend(t.ident().map(str::to_string));
|
||||
}
|
||||
}
|
||||
}
|
||||
let rest = header.get(skip..).unwrap_or(&[]);
|
||||
let after_for = rest.iter().enumerate().find(|(i, t)| t.is("for") && !rest.get(i + 1).is_some_and(|n| n.is_punct('<'))).map(|(i, _)| i + 1);
|
||||
let target = rest.get(after_for.unwrap_or(0)..).unwrap_or(&[]);
|
||||
// the path's last segment before its generics
|
||||
let mut owner = String::new();
|
||||
for t in target {
|
||||
if t.is_punct('<') || t.is_punct('{') || t.is("where") {
|
||||
break;
|
||||
}
|
||||
if let Some(name) = t.ident().filter(|n| *n != "dyn" && *n != "mut") {
|
||||
owner = name.to_string();
|
||||
}
|
||||
}
|
||||
let blanket = params.contains(&owner);
|
||||
ImplTarget { owner, is_trait: after_for.is_some(), blanket }
|
||||
}
|
||||
|
||||
/// One source file's items. `dispatchers` names functions to cut into arms.
|
||||
pub fn parse(source: &str, file: &str, dispatchers: &[Dispatcher]) -> Parsed {
|
||||
let tokens = tokenize(source);
|
||||
let mut parser = Parser { tokens: &tokens, file, out: Parsed::default(), loose: Vec::new(), scope: Vec::new() };
|
||||
parser.items(0, tokens.len(), None, false);
|
||||
let Parser { out: mut parsed, loose, .. } = parser;
|
||||
if !loose.is_empty() {
|
||||
parsed.items.push(Item {
|
||||
name: String::new(),
|
||||
kind: ItemKind::Value,
|
||||
owner: None,
|
||||
trait_impl: false,
|
||||
mentions: mentions_in(&loose, None),
|
||||
tokens: loose,
|
||||
loose: true,
|
||||
includes: Vec::new(),
|
||||
file: file.to_string(),
|
||||
});
|
||||
}
|
||||
for d in dispatchers.iter().filter(|d| d.file == file || Path::new(file).ends_with(d.file)) {
|
||||
cut_arms(&mut parsed, d.function);
|
||||
}
|
||||
parsed
|
||||
}
|
||||
|
||||
/// Cuts the literal arms out of function `function`'s outermost `match` over a kind: what remains of the function counts
|
||||
/// for every kind, an arm for those it names.
|
||||
fn cut_arms(parsed: &mut Parsed, function: &str) {
|
||||
let Some(item) = parsed.items.iter_mut().find(|i| i.name == function && i.kind == ItemKind::Function) else { return };
|
||||
let tokens = std::mem::take(&mut item.tokens);
|
||||
let Some(start) = dispatch_match(&tokens) else {
|
||||
item.tokens = tokens;
|
||||
return;
|
||||
};
|
||||
let end = past_group(&tokens, start);
|
||||
let mut kept: Vec<Token> = tokens.get(..=start).unwrap_or(&[]).to_vec();
|
||||
let mut i = start + 1;
|
||||
let last = end.saturating_sub(1);
|
||||
let mut after = 0;
|
||||
while i < last {
|
||||
let arm_end = past_arm(&tokens, i, last);
|
||||
let arm = tokens.get(i..arm_end).unwrap_or(&[]);
|
||||
match literal_kinds(arm) {
|
||||
Some(kinds) => parsed.arms.push(Arm { kinds, after, tokens: arm.to_vec(), mentions: mentions_in(arm, None) }),
|
||||
None => {
|
||||
after += 1;
|
||||
kept.extend_from_slice(arm);
|
||||
}
|
||||
}
|
||||
i = arm_end;
|
||||
}
|
||||
kept.extend_from_slice(tokens.get(last..).unwrap_or(&[]));
|
||||
item.mentions = mentions_in(&kept, item.owner.as_deref());
|
||||
item.tokens = kept;
|
||||
}
|
||||
|
||||
/// The opening brace of the first `match` whose arms start with a string literal.
|
||||
fn dispatch_match(tokens: &[Token]) -> Option<usize> {
|
||||
let mut i = 0;
|
||||
while let Some(t) = tokens.get(i) {
|
||||
if t.is("match") {
|
||||
let open = (i..tokens.len()).find(|&k| tokens.get(k).is_some_and(|x| x.is_punct('{')))?;
|
||||
if matches!(tokens.get(open + 1), Some(Token::Text(_))) {
|
||||
return Some(open);
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The index past the arm starting at `from`: its `=>`, then a block with an optional comma, or an expression up to a comma
|
||||
/// outside brackets.
|
||||
fn past_arm(tokens: &[Token], from: usize, last: usize) -> usize {
|
||||
let mut i = from;
|
||||
while i < last {
|
||||
let Some(t) = tokens.get(i) else { return last };
|
||||
if t.is_punct('=') && tokens.get(i + 1).is_some_and(|n| n.is_punct('>')) {
|
||||
i += 2;
|
||||
break;
|
||||
}
|
||||
i = if opens(t) { past_group(tokens, i) } else { i + 1 };
|
||||
}
|
||||
if tokens.get(i).is_some_and(|t| t.is_punct('{')) {
|
||||
let end = past_group(tokens, i);
|
||||
// a block that goes on as an expression (`{ … }.foo()`) runs up to its comma as well
|
||||
let ends_arm = end >= last || tokens.get(end).is_some_and(|t| t.is_punct(',') || !t.is_punct('.') && !t.is_punct('?'));
|
||||
if ends_arm {
|
||||
return (end + usize::from(tokens.get(end).is_some_and(|t| t.is_punct(',')))).min(last);
|
||||
}
|
||||
i = end;
|
||||
}
|
||||
while i < last {
|
||||
let Some(t) = tokens.get(i) else { return last };
|
||||
if t.is_punct(',') {
|
||||
return i + 1;
|
||||
}
|
||||
i = if opens(t) { past_group(tokens, i) } else { i + 1 };
|
||||
}
|
||||
last
|
||||
}
|
||||
|
||||
/// The kinds of an arm whose pattern is only string literals (no guard).
|
||||
fn literal_kinds(arm: &[Token]) -> Option<Vec<String>> {
|
||||
let mut kinds = Vec::new();
|
||||
for (i, t) in arm.iter().enumerate() {
|
||||
match t {
|
||||
Token::Text(s) => kinds.push(s.clone()),
|
||||
Token::Punct('|') => {}
|
||||
Token::Punct('=') if arm.get(i + 1).is_some_and(|n| n.is_punct('>')) => {
|
||||
return (!kinds.is_empty()).then_some(kinds);
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn names(p: &Parsed) -> Vec<(&str, Option<&str>)> {
|
||||
p.items.iter().map(|i| (i.name.as_str(), i.owner.as_deref())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn items_with_their_owners() {
|
||||
let p = parse(
|
||||
"pub fn a() -> u8 { b() } struct S { x: u8 } impl S { pub fn m(&self) {} const C: u8 = 1; } const K: [u8; 2] = [1, 2]; static mut V: u8 = 0;",
|
||||
"x.rs",
|
||||
&[],
|
||||
);
|
||||
assert_eq!(names(&p), [("a", None), ("S", None), ("S", Some("S")), ("m", Some("S")), ("C", Some("S")), ("K", None), ("V", None)]);
|
||||
assert!(p.items.iter().all(|i| !i.loose));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_attributes_of_a_module_are_part_of_what_is_inside() {
|
||||
let of = |text: &str| {
|
||||
let p = parse(text, "x.rs", &[]);
|
||||
p.items.iter().map(|i| (i.name.clone(), i.tokens.clone(), i.loose)).collect::<Vec<_>>()
|
||||
};
|
||||
let one = of("#[cfg(unix)] mod backend { pub fn shade() { 1 } } #[cfg(not(unix))] mod backend { pub fn shade() { 2 } }");
|
||||
let swapped = of("#[cfg(not(unix))] mod backend { pub fn shade() { 1 } } #[cfg(unix)] mod backend { pub fn shade() { 2 } }");
|
||||
assert_ne!(one, swapped);
|
||||
// a module with no attributes brings nothing but its items
|
||||
assert_eq!(of("mod m { fn a() {} }"), of("pub mod m { fn a() {} }"));
|
||||
// a `use` under `cfg` counts for every result, a plain one does not
|
||||
assert!(of("#[cfg(unix)] use a::shade;").iter().any(|(_, _, loose)| *loose));
|
||||
assert!(of("use a::shade;").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_code_does_not_count() {
|
||||
let p = parse("fn a() {} #[cfg(test)] mod tests { fn b() {} } fn c() {}", "x.rs", &[]);
|
||||
assert_eq!(names(&p), [("a", None), ("c", None)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_modules_and_nested_bodies() {
|
||||
let p = parse("mod m { pub fn a() { fn inner() {} } } fn b() {}", "x.rs", &[]);
|
||||
assert_eq!(names(&p), [("a", None), ("b", None)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trait_impls_are_marked_and_blanket_ones_count_everywhere() {
|
||||
let p =
|
||||
parse("impl std::ops::Add for V { fn add(self, o: V) -> V { o } } impl<T: X> Y for T {} impl<'a, T> W<'a, T> { fn f() {} }", "x.rs", &[]);
|
||||
let add = p.items.iter().find(|i| i.name == "add").unwrap();
|
||||
assert!(add.trait_impl);
|
||||
assert_eq!(add.owner.as_deref(), Some("V"));
|
||||
assert!(p.items.iter().any(|i| i.name == "T" && i.loose));
|
||||
let blanket = parse("impl<T: X> Y for T { fn one(&self) {} fn two(&self) {} }", "x.rs", &[]);
|
||||
assert!(blanket.items.iter().all(|i| i.loose), "the whole block, not its last function");
|
||||
assert_eq!(p.items.iter().find(|i| i.name == "f").unwrap().owner.as_deref(), Some("W"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_not_understood_counts_everywhere() {
|
||||
let p = parse("some_macro!(generated_thing); fn a() {}", "x.rs", &[]);
|
||||
let loose = p.items.iter().find(|i| i.loose).unwrap();
|
||||
assert!(loose.tokens.iter().any(|t| t.is("generated_thing")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renames_and_includes() {
|
||||
let p = parse(r#"use a::b as c; const D: &[u8] = include_bytes!("d.bin");"#, "x.rs", &[]);
|
||||
assert_eq!(p.aliases, [Alias { alias: "c".into(), target: "b".into() }]);
|
||||
assert_eq!(p.items[0].includes, ["d.bin"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mentions_tell_paths_from_names() {
|
||||
let tokens = tokenize("ops::blur(x); y.sample(); Self::go(); Tex::new()");
|
||||
let m = mentions_in(&tokens, Some("Me"));
|
||||
assert!(m.contains(&Mention::Path("ops".into(), "blur".into())));
|
||||
assert!(m.contains(&Mention::Name("sample".into())));
|
||||
assert!(m.contains(&Mention::Path("Me".into(), "go".into())));
|
||||
assert!(m.contains(&Mention::Path("Tex".into(), "new".into())));
|
||||
assert!(m.contains(&Mention::Name("Tex".into())), "an owner is named too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arms_are_cut_out_of_a_dispatcher() {
|
||||
let source = r#"fn compute(kind: &str) -> u8 {
|
||||
let shared = helper();
|
||||
match kind {
|
||||
"a" | "b" => one(),
|
||||
"c" => { two(); 3 }
|
||||
other if other.len() > 3 => three(),
|
||||
_ => fallback(),
|
||||
}
|
||||
}"#;
|
||||
let p = parse(source, "x.rs", &[Dispatcher { file: "x.rs", function: "compute" }]);
|
||||
assert_eq!(p.arms.len(), 2);
|
||||
assert_eq!(p.arms[0].kinds, ["a", "b"]);
|
||||
assert!(p.arms[0].mentions.contains(&Mention::Name("one".into())));
|
||||
assert_eq!(p.arms[1].kinds, ["c"]);
|
||||
let compute = &p.items[0];
|
||||
for name in ["helper", "three", "fallback"] {
|
||||
assert!(compute.mentions.contains(&Mention::Name(name.into())), "{name} stays shared");
|
||||
}
|
||||
for name in ["one", "two"] {
|
||||
assert!(!compute.mentions.contains(&Mention::Name(name.into())), "{name} went with its arm");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
//! Engine versions from source: [`SourceTree`] reads Rust files into items, follows what an item names to what it
|
||||
//! depends on, and takes a digest over that closure. A node kind's version covers the kind's match arms, everything
|
||||
//! they reach and everything shared by all kinds, so changing a node changes the version of the kinds that reach the
|
||||
//! change and of no others, with no version number to remember to bump.
|
||||
//!
|
||||
//! It errs towards invalidating, by construction:
|
||||
//! - names are followed by name, not by type: `.sample()` reaches every function called `sample`;
|
||||
//! - a type brings every `impl Trait for` it, since operators, `Drop` and the like run without being named;
|
||||
//! - what the parser doesn't recognise as an item counts for every kind ([`items`]);
|
||||
//! - a kind with no arm has no version of its own: callers use [`SourceTree::all`], which covers every file.
|
||||
//!
|
||||
//! Comments and layout change no version. What it can't see is listed in the result cache's documentation: the
|
||||
//! dependencies and the compiler go into [`Toolchain`]; anything else that changes results goes into the epoch.
|
||||
|
||||
pub mod items;
|
||||
pub mod modules;
|
||||
pub mod tokens;
|
||||
|
||||
use crate::digest::{Digest, Fingerprint};
|
||||
use items::{Alias, Arm, Dispatcher, Item, ItemKind, Mention, parse};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use tokens::Token;
|
||||
|
||||
/// One source file.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SourceFile {
|
||||
/// Its path, as a stable name: relative to the workspace.
|
||||
pub name: String,
|
||||
pub text: String,
|
||||
/// The files it includes, by the name it uses, with their contents.
|
||||
pub included: Vec<(String, Vec<u8>)>,
|
||||
}
|
||||
|
||||
/// The contents of the files `text` names in `include_bytes!` and the like, relative to `folder`. It reads the same
|
||||
/// tokens as the parser, so a spacing like `include_bytes!( "x" )` finds the file the digest asks for.
|
||||
pub fn included_files(text: &str, folder: &std::path::Path) -> Vec<(String, Vec<u8>)> {
|
||||
let mut out = Vec::new();
|
||||
for name in items::includes_in(&tokens::tokenize(text)) {
|
||||
if let Ok(data) = std::fs::read(folder.join(&name)) {
|
||||
out.push((name, data));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What a closure is made of, for telling a developer what a version covers.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Covered {
|
||||
pub functions: usize,
|
||||
pub files: BTreeSet<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct SourceTree {
|
||||
items: Vec<Item>,
|
||||
/// By name, every item of that name whatever its owner.
|
||||
by_name: HashMap<String, Vec<usize>>,
|
||||
/// By owner and name.
|
||||
by_owner: HashMap<(String, String), Vec<usize>>,
|
||||
/// By type, its `impl Trait for` items.
|
||||
trait_impls: HashMap<String, Vec<usize>>,
|
||||
aliases: HashMap<String, Vec<String>>,
|
||||
arms: Vec<Arm>,
|
||||
arms_of: BTreeMap<String, Vec<usize>>,
|
||||
/// Items in every closure.
|
||||
loose: Vec<usize>,
|
||||
included: BTreeMap<(String, String), Vec<u8>>,
|
||||
/// Per item and arm, so that the closures of many kinds don't hash the same text over and over.
|
||||
digests: Vec<Digest>,
|
||||
arm_digests: Vec<Digest>,
|
||||
}
|
||||
|
||||
impl SourceTree {
|
||||
/// Reads `files`; the functions of `dispatchers` are cut into arms.
|
||||
pub fn scan(files: &[SourceFile], dispatchers: &[Dispatcher]) -> SourceTree {
|
||||
let mut tree = SourceTree::default();
|
||||
for file in files {
|
||||
let parsed = parse(&file.text, &file.name, dispatchers);
|
||||
parsed.aliases.into_iter().for_each(|a| tree.alias(a));
|
||||
for arm in parsed.arms {
|
||||
let at = tree.arms.len();
|
||||
arm.kinds.iter().for_each(|k| tree.arms_of.entry(k.clone()).or_default().push(at));
|
||||
tree.arms.push(arm);
|
||||
}
|
||||
parsed.items.into_iter().for_each(|i| tree.add(i));
|
||||
for (name, data) in &file.included {
|
||||
tree.included.insert((file.name.clone(), name.clone()), data.clone());
|
||||
}
|
||||
}
|
||||
tree.digests = tree.items.iter().map(|i| tree.item_digest(i)).collect();
|
||||
tree.arm_digests = tree
|
||||
.arms
|
||||
.iter()
|
||||
.map(|a| {
|
||||
let mut f = Fingerprint::of("arm");
|
||||
f.u64(a.after as u64);
|
||||
let mut text = String::new();
|
||||
a.tokens.iter().for_each(|t: &Token| t.write(&mut text));
|
||||
f.text(&text);
|
||||
f.finish()
|
||||
})
|
||||
.collect();
|
||||
tree
|
||||
}
|
||||
|
||||
fn alias(&mut self, a: Alias) {
|
||||
self.aliases.entry(a.alias).or_default().push(a.target);
|
||||
}
|
||||
|
||||
fn add(&mut self, item: Item) {
|
||||
let at = self.items.len();
|
||||
self.by_name.entry(item.name.clone()).or_default().push(at);
|
||||
if let Some(owner) = &item.owner {
|
||||
self.by_owner.entry((owner.clone(), item.name.clone())).or_default().push(at);
|
||||
if item.trait_impl {
|
||||
self.trait_impls.entry(owner.clone()).or_default().push(at);
|
||||
}
|
||||
}
|
||||
if item.loose {
|
||||
self.loose.push(at);
|
||||
}
|
||||
self.items.push(item);
|
||||
}
|
||||
|
||||
/// Every kind with an arm.
|
||||
pub fn kinds(&self) -> impl Iterator<Item = &str> {
|
||||
self.arms_of.keys().map(String::as_str)
|
||||
}
|
||||
|
||||
fn named(&self, name: &str) -> Vec<usize> {
|
||||
let mut out = self.by_name.get(name).cloned().unwrap_or_default();
|
||||
for target in self.aliases.get(name).into_iter().flatten() {
|
||||
out.extend(self.by_name.get(target).into_iter().flatten());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn resolve(&self, mention: &Mention) -> Vec<usize> {
|
||||
match mention {
|
||||
Mention::Name(name) => self.named(name),
|
||||
// the owner's own item of that name where it has one, else anything of that name (a module's function)
|
||||
Mention::Path(owner, name) => {
|
||||
let owners = std::iter::once(owner).chain(self.aliases.get(owner).into_iter().flatten());
|
||||
let own: Vec<usize> = owners.filter_map(|o| self.by_owner.get(&(o.clone(), name.clone()))).flatten().copied().collect();
|
||||
if own.is_empty() { self.named(name) } else { own }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The items reached from `mentions`, with those in every closure.
|
||||
fn closure(&self, mentions: &[Mention], roots: &[usize]) -> BTreeSet<usize> {
|
||||
let mut seen: BTreeSet<usize> = BTreeSet::new();
|
||||
let mut queue: Vec<usize> = roots.iter().chain(&self.loose).copied().collect();
|
||||
let mut asked: BTreeSet<&Mention> = BTreeSet::new();
|
||||
mentions.iter().for_each(|m| {
|
||||
if asked.insert(m) {
|
||||
queue.extend(self.resolve(m));
|
||||
}
|
||||
});
|
||||
while let Some(at) = queue.pop() {
|
||||
let Some(item) = self.items.get(at).filter(|_| seen.insert(at)) else { continue };
|
||||
for m in &item.mentions {
|
||||
if asked.insert(m) {
|
||||
queue.extend(self.resolve(m));
|
||||
}
|
||||
}
|
||||
if item.kind == ItemKind::Type {
|
||||
queue.extend(self.trait_impls.get(&item.name).into_iter().flatten());
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// The digest of one item: where it is, its tokens and the files it includes.
|
||||
fn item_digest(&self, item: &Item) -> Digest {
|
||||
let mut f = Fingerprint::of("item");
|
||||
f.text(&item.file);
|
||||
let mut text = String::new();
|
||||
item.tokens.iter().for_each(|t: &Token| t.write(&mut text));
|
||||
f.text(&text);
|
||||
for include in &item.includes {
|
||||
f.text(include);
|
||||
match self.included.get(&(item.file.clone(), include.clone())) {
|
||||
Some(data) => f.bytes(data),
|
||||
None => f.text("missing"),
|
||||
}
|
||||
}
|
||||
f.finish()
|
||||
}
|
||||
|
||||
fn digest_items(&self, purpose: &str, seen: &BTreeSet<usize>, arms: &[usize]) -> Digest {
|
||||
// sorted by content, not by index: a new item elsewhere moves every index and must not change this
|
||||
let mut parts: Vec<Digest> = seen.iter().filter_map(|at| self.digests.get(*at).copied()).collect();
|
||||
parts.extend(arms.iter().filter_map(|at| self.arm_digests.get(*at).copied()));
|
||||
parts.sort_unstable();
|
||||
let mut f = Fingerprint::of(purpose);
|
||||
parts.iter().for_each(|d| f.digest(d));
|
||||
f.finish()
|
||||
}
|
||||
|
||||
/// The version of what `roots` (function or type names) reach: for a part of the program as a whole.
|
||||
pub fn version_of(&self, purpose: &str, roots: &[&str]) -> Digest {
|
||||
let mentions: Vec<Mention> = roots.iter().map(|r| Mention::Name((*r).to_string())).collect();
|
||||
self.digest_items(purpose, &self.closure(&mentions, &[]), &[])
|
||||
}
|
||||
|
||||
/// The version of node kind `kind`: its arms, what they reach and what `shared` (names every kind goes through)
|
||||
/// reaches. `None` for a kind with no arm.
|
||||
pub fn kind_version(&self, kind: &str, shared: &[&str]) -> Option<Digest> {
|
||||
let arms = self.arms_of.get(kind)?;
|
||||
let mut mentions: Vec<Mention> = shared.iter().map(|r| Mention::Name((*r).to_string())).collect();
|
||||
for at in arms {
|
||||
mentions.extend(self.arms.get(*at).into_iter().flat_map(|a| a.mentions.iter().cloned()));
|
||||
}
|
||||
Some(self.digest_items(kind, &self.closure(&mentions, &[]), arms))
|
||||
}
|
||||
|
||||
/// The names of the functions `kind`'s version covers (`None`: only what `shared` reaches), by file: for telling a
|
||||
/// developer what a version covers.
|
||||
pub fn functions_covered(&self, kind: Option<&str>, shared: &[&str]) -> BTreeMap<String, BTreeSet<String>> {
|
||||
let mut mentions: Vec<Mention> = shared.iter().map(|r| Mention::Name((*r).to_string())).collect();
|
||||
for at in kind.and_then(|k| self.arms_of.get(k)).into_iter().flatten() {
|
||||
mentions.extend(self.arms.get(*at).into_iter().flat_map(|a| a.mentions.iter().cloned()));
|
||||
}
|
||||
let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
|
||||
for item in self.closure(&mentions, &[]).iter().filter_map(|at| self.items.get(*at)) {
|
||||
if item.kind == ItemKind::Function {
|
||||
out.entry(item.file.clone()).or_default().insert(item.name.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What the kind's version covers.
|
||||
pub fn kind_covers(&self, kind: &str, shared: &[&str]) -> Option<Covered> {
|
||||
let arms = self.arms_of.get(kind)?;
|
||||
let mut mentions: Vec<Mention> = shared.iter().map(|r| Mention::Name((*r).to_string())).collect();
|
||||
for at in arms {
|
||||
mentions.extend(self.arms.get(*at).into_iter().flat_map(|a| a.mentions.iter().cloned()));
|
||||
}
|
||||
let seen = self.closure(&mentions, &[]);
|
||||
let items = seen.iter().filter_map(|at| self.items.get(*at));
|
||||
let (mut functions, mut files) = (0, BTreeSet::new());
|
||||
for item in items {
|
||||
functions += usize::from(item.kind == ItemKind::Function);
|
||||
files.insert(item.file.clone());
|
||||
}
|
||||
Some(Covered { functions, files })
|
||||
}
|
||||
|
||||
/// The version of everything scanned: what a kind without arms, or a part nobody has split up, goes by.
|
||||
pub fn all(&self, purpose: &str) -> Digest {
|
||||
let everything: BTreeSet<usize> = (0..self.items.len()).collect();
|
||||
let arms: Vec<usize> = (0..self.arms.len()).collect();
|
||||
self.digest_items(purpose, &everything, &arms)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const DISPATCH: &[Dispatcher] = &[Dispatcher { file: "a.rs", function: "compute" }];
|
||||
|
||||
fn tree(a: &str, b: &str) -> SourceTree {
|
||||
let file = |name: &str, text: &str| SourceFile { name: name.into(), text: text.into(), included: Vec::new() };
|
||||
SourceTree::scan(&[file("a.rs", a), file("b.rs", b)], DISPATCH)
|
||||
}
|
||||
|
||||
const A: &str = r#"
|
||||
fn eval() { compute("x"); }
|
||||
fn compute(kind: &str) -> f32 {
|
||||
let k = shared_helper();
|
||||
match kind {
|
||||
"blur" => blur(k),
|
||||
"sharpen" | "unsharp" => sharpen(k),
|
||||
"two_steps" => { let a = blur(k); sharpen(a) }
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
"#;
|
||||
const B: &str = "fn shared_helper() -> f32 { 1.0 } fn blur(v: f32) -> f32 { v * 2.0 } fn sharpen(v: f32) -> f32 { v * 3.0 } fn unrelated() {}";
|
||||
const SHARED: &[&str] = &["eval"];
|
||||
|
||||
fn versions(t: &SourceTree) -> BTreeMap<String, Digest> {
|
||||
t.kinds().map(|k| (k.to_string(), t.kind_version(k, SHARED).unwrap())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_a_node_changes_the_kinds_that_reach_it_and_no_others() {
|
||||
let before = versions(&tree(A, B));
|
||||
let after = versions(&tree(A, &B.replace("v * 2.0", "v * 2.5")));
|
||||
assert_ne!(before["blur"], after["blur"]);
|
||||
assert_ne!(before["two_steps"], after["two_steps"]);
|
||||
assert_eq!(before["sharpen"], after["sharpen"]);
|
||||
assert_eq!(before["unsharp"], after["unsharp"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_an_arm_changes_that_arm_only() {
|
||||
let before = versions(&tree(A, B));
|
||||
let after = versions(&tree(&A.replace("blur(k),", "blur(k) + 1.0,"), B));
|
||||
assert_ne!(before["blur"], after["blur"]);
|
||||
assert_eq!(before["sharpen"], after["sharpen"]);
|
||||
assert_eq!(before["two_steps"], after["two_steps"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_what_all_share_changes_all() {
|
||||
let before = versions(&tree(A, B));
|
||||
let after = versions(&tree(A, &B.replace("{ 1.0 }", "{ 1.5 }")));
|
||||
assert!(before.iter().all(|(k, v)| after[k] != *v));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_layout_and_unrelated_code_change_nothing() {
|
||||
let before = versions(&tree(A, B));
|
||||
let commented = B.replace("v * 2.0", "/* why */ v * 2.0 // more\n");
|
||||
assert_eq!(before, versions(&tree(A, &commented)));
|
||||
let unrelated = B.replace("fn unrelated() {}", "fn unrelated() { let _ = 1; } fn added() {}");
|
||||
assert_eq!(before, versions(&tree(A, &unrelated)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn operators_are_reached_through_their_type() {
|
||||
let b = "struct V(f32); impl std::ops::Add for V { type Output = V; fn add(self, o: V) -> V { V(self.0 + o.0) } } fn blur(v: V) -> V { v } fn sharpen() {} fn shared_helper() {}";
|
||||
let before = versions(&tree(A, b));
|
||||
let after = versions(&tree(A, &b.replace("self.0 + o.0", "self.0 - o.0")));
|
||||
assert_ne!(before["blur"], after["blur"], "`+` names no function, but the operator is the type's");
|
||||
assert_eq!(before["sharpen"], after["sharpen"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renames_and_constants_are_followed() {
|
||||
let b =
|
||||
"use x::shared_helper as sh; const FACTOR: f32 = 2.0; fn blur(v: f32) -> f32 { v * FACTOR * sh() } fn sharpen() {} fn shared_helper() {}";
|
||||
let before = versions(&tree(A, b));
|
||||
assert_ne!(before["blur"], versions(&tree(A, &b.replace("= 2.0", "= 3.0")))["blur"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_cannot_be_read_counts_for_all() {
|
||||
let before = versions(&tree(A, B));
|
||||
let with = format!("{B} mystery_macro!(one);");
|
||||
let changed = format!("{B} mystery_macro!(two);");
|
||||
let (with, changed) = (versions(&tree(A, &with)), versions(&tree(A, &changed)));
|
||||
assert_ne!(before["blur"], with["blur"]);
|
||||
assert!(with.iter().all(|(k, v)| changed[k] != *v));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn included_files_count() {
|
||||
let source = r#"fn blur() { let _ = include_bytes!("table.bin"); } fn sharpen() {} fn shared_helper() {}"#;
|
||||
let of = |data: &[u8]| {
|
||||
let a = SourceFile { name: "a.rs".into(), text: A.into(), included: Vec::new() };
|
||||
let b = SourceFile { name: "b.rs".into(), text: source.into(), included: vec![("table.bin".into(), data.to_vec())] };
|
||||
versions(&SourceTree::scan(&[a, b], DISPATCH))
|
||||
};
|
||||
assert_ne!(of(b"one")["blur"], of(b"two")["blur"]);
|
||||
assert_eq!(of(b"one")["sharpen"], of(b"two")["sharpen"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_include_is_found_however_it_is_spaced() {
|
||||
let folder = std::env::temp_dir().join(format!("craft_material_graph_include_{}", std::process::id()));
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
std::fs::write(folder.join("table.bin"), b"data").unwrap();
|
||||
for text in [
|
||||
r#"include_bytes!("table.bin")"#,
|
||||
r#"include_bytes!( "table.bin" )"#,
|
||||
"include_bytes! (\n \"table.bin\",\n)",
|
||||
r##"include_bytes!(r#"table.bin"#)"##,
|
||||
] {
|
||||
assert_eq!(included_files(text, &folder), [("table.bin".to_string(), b"data".to_vec())], "{text}");
|
||||
}
|
||||
assert!(included_files(r#"include_bytes!("absent.bin")"#, &folder).is_empty());
|
||||
std::fs::remove_dir_all(&folder).unwrap();
|
||||
}
|
||||
|
||||
/// The first arm that matches runs: a guarded arm in front of a literal one is not the same program as behind it.
|
||||
#[test]
|
||||
fn the_order_of_arms_that_can_overlap_counts() {
|
||||
let guarded = r#"fn eval() { compute("x", true); } fn compute(kind: &str, flag: bool) -> f32 { let k = shared_helper(); match kind { "blur" if flag => blur(k), "blur" => sharpen(k), _ => 0.0 } }"#;
|
||||
let swapped = r#"fn eval() { compute("x", true); } fn compute(kind: &str, flag: bool) -> f32 { let k = shared_helper(); match kind { "blur" => sharpen(k), "blur" if flag => blur(k), _ => 0.0 } }"#;
|
||||
assert_ne!(versions(&tree(guarded, B))["blur"], versions(&tree(swapped, B))["blur"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_attribute_on_a_module_changes_what_is_inside() {
|
||||
let backend = |first: &str, second: &str| {
|
||||
format!(
|
||||
"#[cfg({first})] mod backend {{ pub fn shade() -> f32 {{ 1.0 }} }} #[cfg({second})] mod backend {{ pub fn shade() -> f32 {{ 2.0 }} }}"
|
||||
)
|
||||
};
|
||||
let b = |attrs: String| format!("{attrs} fn blur(v: f32) -> f32 {{ v * backend::shade() }} fn sharpen() {{}} fn shared_helper() {{}}");
|
||||
let (one, other) = (b(backend("unix", "not(unix)")), b(backend("not(unix)", "unix")));
|
||||
assert_ne!(versions(&tree(A, &one))["blur"], versions(&tree(A, &other))["blur"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_source_change_reaches_the_version_of_everything() {
|
||||
let before = tree(A, B).all("all");
|
||||
assert_ne!(before, tree(A, &B.replace("fn unrelated() {}", "fn unrelated() { 1; }")).all("all"));
|
||||
assert_eq!(before, tree(A, &format!("{B} // a comment")).all("all"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kind_with_no_arm_has_no_version_of_its_own() {
|
||||
assert_eq!(tree(A, B).kind_version("nobody", SHARED), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
//! Which files a part of the program can reach at all, by the module paths its code spells (`crate::tex`, `super::x`,
|
||||
//! `use crate::paint::{par, other}`, `mod child;`). Names are followed by name within those files only: without this, a
|
||||
//! `.parse()` in the graph engine would reach every function called `parse` in the whole program, and every kind would
|
||||
//! depend on everything. Sound because code can only name what its module paths lead to, and a value of a type from
|
||||
//! elsewhere arrives through a function whose file names that type's module.
|
||||
|
||||
use super::SourceFile;
|
||||
use super::items::past_item;
|
||||
use super::tokens::{Token, tokenize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
/// Tokens of `#[cfg(test)]`.
|
||||
const TEST_ATTRIBUTE: usize = 7;
|
||||
|
||||
fn is_test_attribute(tokens: &[Token], at: usize) -> bool {
|
||||
let is_punct = |k: usize, c: char| tokens.get(at + k).is_some_and(|t| t.is_punct(c));
|
||||
is_punct(0, '#')
|
||||
&& is_punct(1, '[')
|
||||
&& tokens.get(at + 2).is_some_and(|t| t.is("cfg"))
|
||||
&& is_punct(3, '(')
|
||||
&& tokens.get(at + 4).is_some_and(|t| t.is("test"))
|
||||
&& is_punct(5, ')')
|
||||
&& is_punct(6, ']')
|
||||
}
|
||||
|
||||
/// A folder of modules and how a file sits in it.
|
||||
fn children_folder(file: &str) -> String {
|
||||
let path = file.trim_end_matches(".rs");
|
||||
match path.rsplit_once('/') {
|
||||
Some((folder, "mod" | "lib" | "main")) => folder.to_string(),
|
||||
_ => path.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn parent_folder(folder: &str) -> String {
|
||||
folder.rsplit_once('/').map_or(String::new(), |(p, _)| p.to_string())
|
||||
}
|
||||
|
||||
struct Lookup<'a> {
|
||||
files: &'a BTreeMap<&'a str, &'a SourceFile>,
|
||||
root: String,
|
||||
}
|
||||
|
||||
impl Lookup<'_> {
|
||||
/// The file of module `name` in `folder`.
|
||||
fn module(&self, folder: &str, name: &str) -> Option<String> {
|
||||
let candidates = [format!("{folder}/{name}.rs"), format!("{folder}/{name}/mod.rs")];
|
||||
candidates.into_iter().find(|c| self.files.contains_key(c.as_str()))
|
||||
}
|
||||
|
||||
/// The file of the module whose children are in `folder`.
|
||||
fn file_of_folder(&self, folder: &str) -> Option<String> {
|
||||
let candidates = [format!("{folder}/mod.rs"), format!("{folder}.rs"), format!("{folder}/lib.rs")];
|
||||
candidates.into_iter().find(|c| self.files.contains_key(c.as_str()))
|
||||
}
|
||||
|
||||
/// Follows `segments` from `folder` as far as they are modules, into `out`: the deepest one reached, which is where
|
||||
/// the path's item is.
|
||||
fn follow(&self, folder: &str, segments: &[String], out: &mut BTreeSet<String>) {
|
||||
let mut folder = folder.to_string();
|
||||
let mut last = None;
|
||||
for s in segments {
|
||||
let Some(file) = self.module(&folder, s) else { break };
|
||||
folder = children_folder(&file);
|
||||
last = Some(file);
|
||||
}
|
||||
out.extend(last);
|
||||
}
|
||||
|
||||
/// The paths in `tokens` from a `::` chain's first word, with `{a, b::c}` groups spread out.
|
||||
fn paths(&self, tokens: &[Token], at: usize, prefix: Vec<String>, out: &mut Vec<Vec<String>>) -> usize {
|
||||
let mut path = prefix;
|
||||
let mut i = at;
|
||||
loop {
|
||||
match tokens.get(i) {
|
||||
Some(Token::Ident(name)) => {
|
||||
path.push(name.clone());
|
||||
i += 1;
|
||||
}
|
||||
Some(t) if t.is_punct('{') => {
|
||||
i += 1;
|
||||
while tokens.get(i).is_some_and(|t| !t.is_punct('}')) {
|
||||
i = self.paths(tokens, i, path.clone(), out);
|
||||
if tokens.get(i).is_some_and(|t| t.is_punct(',')) {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return i + 1;
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
let more = tokens.get(i).is_some_and(|t| t.is_punct(':')) && tokens.get(i + 1).is_some_and(|t| t.is_punct(':'));
|
||||
if !more {
|
||||
break;
|
||||
}
|
||||
i += 2;
|
||||
}
|
||||
out.push(path);
|
||||
i.max(at + 1)
|
||||
}
|
||||
|
||||
fn references(&self, file: &SourceFile) -> BTreeSet<String> {
|
||||
let tokens = tokenize(&file.text);
|
||||
let own = children_folder(&file.name);
|
||||
let parent = parent_folder(&own);
|
||||
let mut out = BTreeSet::new();
|
||||
let mut i = 0;
|
||||
while let Some(t) = tokens.get(i) {
|
||||
// test code doesn't run in a result, and a test module's `super` would reach the whole crate
|
||||
if is_test_attribute(&tokens, i) {
|
||||
i = past_item(&tokens, i + TEST_ATTRIBUTE, true);
|
||||
continue;
|
||||
}
|
||||
let Some(word) = t.ident() else {
|
||||
i += 1;
|
||||
continue;
|
||||
};
|
||||
if word == "mod" {
|
||||
if let Some(name) = tokens.get(i + 1).and_then(Token::ident).filter(|_| tokens.get(i + 2).is_some_and(|n| n.is_punct(';'))) {
|
||||
out.extend(self.module(&own, name));
|
||||
}
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
let chained = tokens.get(i + 1).is_some_and(|n| n.is_punct(':')) && tokens.get(i + 2).is_some_and(|n| n.is_punct(':'));
|
||||
if !chained {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let mut paths = Vec::new();
|
||||
let next = self.paths(&tokens, i, Vec::new(), &mut paths);
|
||||
for path in &paths {
|
||||
let Some((first, rest)) = path.split_first() else { continue };
|
||||
match first.as_str() {
|
||||
"crate" => self.follow(&self.root, rest, &mut out),
|
||||
"self" => self.follow(&own, rest, &mut out),
|
||||
"super" => {
|
||||
let mut folder = parent.clone();
|
||||
let mut rest = rest;
|
||||
while let Some(("super", more)) = rest.split_first().map(|(a, b)| (a.as_str(), b)) {
|
||||
folder = parent_folder(&folder);
|
||||
rest = more;
|
||||
}
|
||||
// `super::helper()` and `use super::*` name what is in the parent's own file
|
||||
out.extend(self.file_of_folder(&folder));
|
||||
self.follow(&folder, rest, &mut out);
|
||||
}
|
||||
// a child of this module, or a sibling a `use` brought in under that name
|
||||
_ => {
|
||||
self.follow(&own, path, &mut out);
|
||||
self.follow(&parent, path, &mut out);
|
||||
}
|
||||
}
|
||||
}
|
||||
i = next.max(i + 1);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The files of `files` reachable from `start` (file names), all of them in one crate with its modules under `root`.
|
||||
pub fn reachable<'a>(files: &'a [SourceFile], root: &str, start: &[&str]) -> Vec<&'a SourceFile> {
|
||||
let by_name: BTreeMap<&str, &SourceFile> = files.iter().map(|f| (f.name.as_str(), f)).collect();
|
||||
let lookup = Lookup { files: &by_name, root: root.to_string() };
|
||||
let mut seen: BTreeSet<String> = BTreeSet::new();
|
||||
let mut queue: Vec<String> = start.iter().map(|s| (*s).to_string()).collect();
|
||||
while let Some(name) = queue.pop() {
|
||||
if !seen.insert(name.clone()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(file) = by_name.get(name.as_str()) {
|
||||
queue.extend(lookup.references(file));
|
||||
}
|
||||
}
|
||||
files.iter().filter(|f| seen.contains(&f.name)).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn file(name: &str, text: &str) -> SourceFile {
|
||||
SourceFile { name: name.into(), text: text.into(), included: Vec::new() }
|
||||
}
|
||||
|
||||
fn names(files: &[SourceFile], start: &[&str]) -> Vec<String> {
|
||||
reachable(files, "src", start).iter().map(|f| f.name.clone()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follows_paths_and_groups_and_stops_at_what_is_not_named() {
|
||||
let files = [
|
||||
file("src/a.rs", "use crate::b::f; fn x() { crate::c::g(); }"),
|
||||
file("src/b.rs", "use crate::{d, e::{h, i}};"),
|
||||
file("src/c.rs", ""),
|
||||
file("src/d.rs", ""),
|
||||
file("src/e/mod.rs", "mod h; mod i;"),
|
||||
file("src/e/h.rs", ""),
|
||||
file("src/e/i.rs", ""),
|
||||
file("src/e/j.rs", ""),
|
||||
file("src/far.rs", ""),
|
||||
];
|
||||
assert_eq!(names(&files, &["src/a.rs"]), ["src/a.rs", "src/b.rs", "src/c.rs", "src/d.rs", "src/e/h.rs", "src/e/i.rs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deep_path_does_not_bring_the_whole_module() {
|
||||
let files = [
|
||||
file("src/a.rs", "fn x() { crate::big::small::go(); }"),
|
||||
file("src/big/mod.rs", "pub mod small; pub mod huge;"),
|
||||
file("src/big/small.rs", ""),
|
||||
file("src/big/huge.rs", ""),
|
||||
];
|
||||
assert_eq!(names(&files, &["src/a.rs"]), ["src/a.rs", "src/big/small.rs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reexport_brings_the_module_with_its_children() {
|
||||
let files =
|
||||
[file("src/a.rs", "use crate::big::Thing;"), file("src/big/mod.rs", "mod small; pub use small::Thing;"), file("src/big/small.rs", "")];
|
||||
assert_eq!(names(&files, &["src/a.rs"]), ["src/a.rs", "src/big/mod.rs", "src/big/small.rs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_reaches_what_it_uses_of_its_parent() {
|
||||
let files = [
|
||||
file("src/a.rs", "fn x() { crate::big::small::go(); crate::other::child::go(); }"),
|
||||
file("src/big/mod.rs", "pub fn helper() {}"),
|
||||
file("src/big/small.rs", "fn go() { super::helper(); }"),
|
||||
file("src/other.rs", "mod child; pub fn helper() {}"),
|
||||
file("src/other/child.rs", "use super::*; fn go() { helper(); }"),
|
||||
];
|
||||
assert_eq!(names(&files, &["src/a.rs"]), ["src/a.rs", "src/big/mod.rs", "src/big/small.rs", "src/other.rs", "src/other/child.rs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_code_reaches_nothing() {
|
||||
let files = [
|
||||
file("src/lib.rs", "mod a; mod far;"),
|
||||
file("src/a.rs", "fn x() {} #[cfg(test)] mod tests { use super::*; use crate::far; }"),
|
||||
file("src/far.rs", ""),
|
||||
];
|
||||
assert_eq!(names(&files, &["src/a.rs"]), ["src/a.rs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_paths() {
|
||||
let files = [
|
||||
file("src/m/mod.rs", "mod child; use self::child::f;"),
|
||||
file("src/m/child.rs", "use super::sister::g; use super::super::top;"),
|
||||
file("src/m/sister.rs", ""),
|
||||
file("src/top.rs", ""),
|
||||
];
|
||||
assert_eq!(names(&files, &["src/m/mod.rs"]).len(), 4);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
//! Rust source as tokens: comments and layout are gone, so a change to either changes no version.
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Token {
|
||||
Ident(String),
|
||||
/// A string literal's contents as written.
|
||||
Text(String),
|
||||
/// A raw string literal's contents: `r"\n"` is two characters, `"\n"` one, so the two never compare equal.
|
||||
Raw(String),
|
||||
/// A number or character literal, a lifetime.
|
||||
Literal(String),
|
||||
Punct(char),
|
||||
}
|
||||
|
||||
impl Token {
|
||||
pub fn is(&self, word: &str) -> bool {
|
||||
matches!(self, Token::Ident(i) if i == word)
|
||||
}
|
||||
|
||||
pub fn is_punct(&self, c: char) -> bool {
|
||||
matches!(self, Token::Punct(p) if *p == c)
|
||||
}
|
||||
|
||||
pub fn ident(&self) -> Option<&str> {
|
||||
match self {
|
||||
Token::Ident(i) => Some(i),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The token as it goes into a digest.
|
||||
pub fn write(&self, out: &mut String) {
|
||||
match self {
|
||||
Token::Ident(s) | Token::Literal(s) => out.push_str(s),
|
||||
Token::Text(s) => {
|
||||
out.push('"');
|
||||
out.push_str(s);
|
||||
out.push('"');
|
||||
}
|
||||
Token::Raw(s) => {
|
||||
out.push_str("r\"");
|
||||
out.push_str(s);
|
||||
out.push('"');
|
||||
}
|
||||
Token::Punct(c) => out.push(*c),
|
||||
}
|
||||
out.push(' ');
|
||||
}
|
||||
}
|
||||
|
||||
struct Cursor<'a> {
|
||||
chars: &'a [char],
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl Cursor<'_> {
|
||||
fn peek(&self, ahead: usize) -> Option<char> {
|
||||
self.chars.get(self.at + ahead).copied()
|
||||
}
|
||||
|
||||
fn take_while(&mut self, keep: impl Fn(char) -> bool) -> String {
|
||||
let mut out = String::new();
|
||||
while let Some(c) = self.peek(0).filter(|c| keep(*c)) {
|
||||
out.push(c);
|
||||
self.at += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn skip_block_comment(&mut self) {
|
||||
self.at += 2;
|
||||
let mut depth = 1;
|
||||
while depth > 0 && self.at < self.chars.len() {
|
||||
match (self.peek(0), self.peek(1)) {
|
||||
(Some('/'), Some('*')) => {
|
||||
depth += 1;
|
||||
self.at += 2;
|
||||
}
|
||||
(Some('*'), Some('/')) => {
|
||||
depth -= 1;
|
||||
self.at += 2;
|
||||
}
|
||||
_ => self.at += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A `"` string with escapes; the cursor is on the opening quote.
|
||||
fn string(&mut self) -> String {
|
||||
self.at += 1;
|
||||
let mut out = String::new();
|
||||
while let Some(c) = self.peek(0) {
|
||||
self.at += 1;
|
||||
match c {
|
||||
'"' => break,
|
||||
'\\' => {
|
||||
out.push(c);
|
||||
out.extend(self.peek(0));
|
||||
self.at += 1;
|
||||
}
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A raw string, if one starts here (`r"`, `r#"`, with the cursor on the `r`).
|
||||
fn raw_string(&mut self) -> Option<String> {
|
||||
let mut hashes = 0;
|
||||
while self.peek(1 + hashes) == Some('#') {
|
||||
hashes += 1;
|
||||
}
|
||||
if self.peek(1 + hashes) != Some('"') {
|
||||
return None;
|
||||
}
|
||||
self.at += 2 + hashes;
|
||||
let mut out = String::new();
|
||||
while let Some(c) = self.peek(0) {
|
||||
if c == '"' && (0..hashes).all(|k| self.peek(1 + k) == Some('#')) {
|
||||
self.at += 1 + hashes;
|
||||
break;
|
||||
}
|
||||
out.push(c);
|
||||
self.at += 1;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A character literal or a lifetime; the cursor is on the `'`.
|
||||
fn quote(&mut self) -> String {
|
||||
let closes = match self.peek(1) {
|
||||
Some('\\') => true,
|
||||
Some(_) => self.peek(2) == Some('\''),
|
||||
None => false,
|
||||
};
|
||||
let mut out = String::from("'");
|
||||
self.at += 1;
|
||||
if closes {
|
||||
while let Some(c) = self.peek(0) {
|
||||
self.at += 1;
|
||||
out.push(c);
|
||||
if c == '\\' {
|
||||
out.extend(self.peek(0));
|
||||
self.at += 1;
|
||||
} else if c == '\'' {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
out.push_str(&self.take_while(is_ident));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn is_ident(c: char) -> bool {
|
||||
c.is_alphanumeric() || c == '_'
|
||||
}
|
||||
|
||||
/// `source` as tokens.
|
||||
pub fn tokenize(source: &str) -> Vec<Token> {
|
||||
let chars: Vec<char> = source.chars().collect();
|
||||
let mut cur = Cursor { chars: &chars, at: 0 };
|
||||
let mut out = Vec::new();
|
||||
while let Some(c) = cur.peek(0) {
|
||||
match (c, cur.peek(1)) {
|
||||
(_, _) if c.is_whitespace() => cur.at += 1,
|
||||
('/', Some('/')) => {
|
||||
cur.take_while(|c| c != '\n');
|
||||
}
|
||||
('/', Some('*')) => cur.skip_block_comment(),
|
||||
('"', _) => out.push(Token::Text(cur.string())),
|
||||
('\'', _) => out.push(Token::Literal(cur.quote())),
|
||||
('b', Some('"')) => {
|
||||
cur.at += 1;
|
||||
out.push(Token::Text(cur.string()));
|
||||
}
|
||||
('b', Some('\'')) => {
|
||||
cur.at += 1;
|
||||
out.push(Token::Literal(cur.quote()));
|
||||
}
|
||||
('r' | 'b', Some('"' | '#' | 'r')) => {
|
||||
let at = cur.at;
|
||||
if c == 'b' && cur.peek(1) == Some('r') {
|
||||
cur.at += 1;
|
||||
}
|
||||
match cur.raw_string() {
|
||||
Some(text) => out.push(Token::Raw(text)),
|
||||
None => {
|
||||
cur.at = at;
|
||||
out.push(Token::Ident(cur.take_while(is_ident)));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ if c.is_ascii_digit() => {
|
||||
// a `.` belongs to the number only when a digit follows: `0..n` and `x.0.foo` stay apart
|
||||
let mut text = cur.take_while(is_ident);
|
||||
if cur.peek(0) == Some('.') && cur.peek(1).is_some_and(|d| d.is_ascii_digit()) {
|
||||
cur.at += 1;
|
||||
text.push('.');
|
||||
text.push_str(&cur.take_while(is_ident));
|
||||
}
|
||||
out.push(Token::Literal(text));
|
||||
}
|
||||
_ if is_ident(c) => out.push(Token::Ident(cur.take_while(is_ident))),
|
||||
_ => {
|
||||
out.push(Token::Punct(c));
|
||||
cur.at += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn idents(s: &str) -> Vec<String> {
|
||||
tokenize(s).iter().filter_map(|t| t.ident().map(str::to_string)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_and_layout_do_not_count() {
|
||||
assert_eq!(tokenize("fn a( ) /* x /* y */ z */ { // c\n 1 }"), tokenize("fn a(){1}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_do_not_hide_or_invent_code() {
|
||||
assert_eq!(idents(r#"a("b // c"); d"#), ["a", "d"]);
|
||||
assert_eq!(idents(r##"a(r#"b " c"#); d(br"e"); f(b"g\""); h"##), ["a", "d", "f", "h"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_raw_string_is_not_its_escaped_spelling() {
|
||||
assert_ne!(tokenize(r#""\n""#), tokenize(r##"r"\n""##));
|
||||
assert_eq!(tokenize(r##"r"a""##), tokenize(r###"r#"a"#"###));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_inside_a_string_is_a_change() {
|
||||
assert_ne!(tokenize(r#"a("x")"#), tokenize(r#"a("y")"#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifetimes_chars_and_numbers() {
|
||||
assert_eq!(idents("fn f<'a>(x: &'a str) -> char { 'x' }"), ["fn", "f", "x", "str", "char"]);
|
||||
assert_eq!(idents(r"let q = '\''; let y = b'\n'; z"), ["let", "q", "let", "y", "z"]);
|
||||
assert_eq!(idents("0..n; x.0.foo; 1.5e3f32"), ["n", "x", "foo"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
# Same as PhotoCraft: the never-panic lints that new crates deny at their root (AGENTS.md) don't apply to tests.
|
||||
allow-unwrap-in-tests = true
|
||||
allow-expect-in-tests = true
|
||||
allow-panic-in-tests = true
|
||||
allow-indexing-slicing-in-tests = true
|
||||
|
||||
# The engine's own: the platform's transcendental functions round differently from one C library to the next, so renders
|
||||
# would differ by machine. `crate::math` has the same functions from one implementation.
|
||||
disallowed-methods = [
|
||||
{ path = "f32::sin", reason = "use crate::math::sin (same bits on every platform)" },
|
||||
{ path = "f32::cos", reason = "use crate::math::cos (same bits on every platform)" },
|
||||
{ path = "f32::sin_cos", reason = "use crate::math::sin_cos (same bits on every platform)" },
|
||||
{ path = "f32::tan", reason = "use crate::math::tan (same bits on every platform)" },
|
||||
{ path = "f32::asin", reason = "use crate::math::asin (same bits on every platform)" },
|
||||
{ path = "f32::acos", reason = "use crate::math::acos (same bits on every platform)" },
|
||||
{ path = "f32::atan", reason = "use crate::math::atan (same bits on every platform)" },
|
||||
{ path = "f32::atan2", reason = "use crate::math::atan2 (same bits on every platform)" },
|
||||
{ path = "f32::sinh", reason = "add it to crate::math (same bits on every platform)" },
|
||||
{ path = "f32::cosh", reason = "add it to crate::math (same bits on every platform)" },
|
||||
{ path = "f32::tanh", reason = "add it to crate::math (same bits on every platform)" },
|
||||
{ path = "f32::exp", reason = "use crate::math::exp (same bits on every platform)" },
|
||||
{ path = "f32::exp2", reason = "add it to crate::math (same bits on every platform)" },
|
||||
{ path = "f32::exp_m1", reason = "add it to crate::math (same bits on every platform)" },
|
||||
{ path = "f32::ln", reason = "use crate::math::ln (same bits on every platform)" },
|
||||
{ path = "f32::ln_1p", reason = "add it to crate::math (same bits on every platform)" },
|
||||
{ path = "f32::log", reason = "add it to crate::math (same bits on every platform)" },
|
||||
{ path = "f32::log2", reason = "use crate::math::log2 (same bits on every platform)" },
|
||||
{ path = "f32::log10", reason = "add it to crate::math (same bits on every platform)" },
|
||||
{ path = "f32::powf", reason = "use crate::math::powf (same bits on every platform)" },
|
||||
{ path = "f32::powi", reason = "use crate::math::powi (a fixed order of multiplications)" },
|
||||
{ path = "f32::cbrt", reason = "use crate::math::cbrt (same bits on every platform)" },
|
||||
{ path = "f32::hypot", reason = "use crate::math::hypot (same bits on every platform)" },
|
||||
{ path = "f64::sin", reason = "use crate::math::sin (same bits on every platform)" },
|
||||
{ path = "f64::cos", reason = "use crate::math::cos (same bits on every platform)" },
|
||||
{ path = "f64::sin_cos", reason = "use crate::math::sin_cos (same bits on every platform)" },
|
||||
{ path = "f64::tan", reason = "use crate::math::tan (same bits on every platform)" },
|
||||
{ path = "f64::asin", reason = "use crate::math::asin (same bits on every platform)" },
|
||||
{ path = "f64::acos", reason = "use crate::math::acos (same bits on every platform)" },
|
||||
{ path = "f64::atan", reason = "use crate::math::atan (same bits on every platform)" },
|
||||
{ path = "f64::atan2", reason = "use crate::math::atan2 (same bits on every platform)" },
|
||||
{ path = "f64::sinh", reason = "add it to crate::math (same bits on every platform)" },
|
||||
{ path = "f64::cosh", reason = "add it to crate::math (same bits on every platform)" },
|
||||
{ path = "f64::tanh", reason = "add it to crate::math (same bits on every platform)" },
|
||||
{ path = "f64::exp", reason = "use crate::math::exp (same bits on every platform)" },
|
||||
{ path = "f64::exp2", reason = "add it to crate::math (same bits on every platform)" },
|
||||
{ path = "f64::exp_m1", reason = "add it to crate::math (same bits on every platform)" },
|
||||
{ path = "f64::ln", reason = "use crate::math::ln (same bits on every platform)" },
|
||||
{ path = "f64::ln_1p", reason = "add it to crate::math (same bits on every platform)" },
|
||||
{ path = "f64::log", reason = "add it to crate::math (same bits on every platform)" },
|
||||
{ path = "f64::log2", reason = "use crate::math::log2 (same bits on every platform)" },
|
||||
{ path = "f64::log10", reason = "add it to crate::math (same bits on every platform)" },
|
||||
{ path = "f64::powf", reason = "use crate::math::powf (same bits on every platform)" },
|
||||
{ path = "f64::powi", reason = "use crate::math::powi (a fixed order of multiplications)" },
|
||||
{ path = "f64::cbrt", reason = "use crate::math::cbrt (same bits on every platform)" },
|
||||
{ path = "f64::hypot", reason = "use crate::math::hypot (same bits on every platform)" },
|
||||
]
|
||||
@@ -0,0 +1,355 @@
|
||||
# Material graph text format
|
||||
|
||||
`craft-material-graph` parses text material graphs and evaluates them to float RGBA images. The loose file extension
|
||||
is `.tcgraph`. This page describes format 3, the version written by `graph::FORMAT_VERSION`.
|
||||
|
||||
## Lines
|
||||
|
||||
One directive per line. `#` starts a comment that runs to the end of the line; blank lines are ignored. Values are
|
||||
whitespace-separated tokens; a value with spaces is written in double quotes.
|
||||
|
||||
| Directive | Meaning |
|
||||
|---|---|
|
||||
| `format <n>` | The format version the text was written with. Texts without it are version 1. A version newer than the runtime's is refused with an error. |
|
||||
| `size <w> [<h>]` | The graph's nominal size in pixels (the height defaults to the width). An evaluation may ask for another size (1 to 8192); node results scale with it. |
|
||||
| `seed_offset <n>` | Added to every random seed in the graph. |
|
||||
| `meta <key> "<value>"` | Free key/value data. `meta kind "function"`, `"fxmap"` or `"patterns"` marks a subgraph as a function graph, an FX-map program or a pattern program; `meta label` names the graph. |
|
||||
| `node <id> <kind> [key=value ...]` | A node. `id` is a whole number, unique in its graph; `kind` is one of the node kinds below. `key=@<id>` connects input slot `key` to node `id`, `key=@<id>.<output>` to a named output of a node with several. A number value is a parameter; anything else is a text parameter. `_x=` and `_y=` are the node's position in an editor. |
|
||||
| `output <name> <id>[.<output>]` | A graph output named `name`, taken from node `id`. Graphs may instead carry `output` nodes (`usage`, `identifier`). |
|
||||
| `subgraph <name>` ... `end` | A graph defined inside this one, in the same format, used by `subgraph` nodes (`graph="<name>"`), by `pixel_processor`/`value_processor` nodes (`fn="<name>"`), by `fx_map` (`program="<name>"`) or by `pattern_program` (`program="<name>"`). |
|
||||
| `resource <name> <base64>` | Bytes carried by the text (an image a `bitmap` node reads by `file="<name>"`). |
|
||||
| `expose <label> <node> <param> <min> <max>` | A parameter shown to users under `label`, clamped to the range. |
|
||||
| `link <name> "<path>" ["<graph>"]` | A live link: the graph is read from another file (relative to this one) whenever the text is loaded, and used through `subgraph` nodes named `name`. Native builds only. |
|
||||
| `comment <x> <y> <w> <h> <color> <text>` | An editor note; ignored by evaluation. |
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
format 3
|
||||
size 256
|
||||
node 1 perlin scale=8 seed=3
|
||||
node 2 levels in=@1 low=0.2 high=0.8
|
||||
node 3 blend bg=@1 fg=@2 mode="multiply" opacity=0.5
|
||||
output height 3
|
||||
```
|
||||
|
||||
## Named values
|
||||
|
||||
A node keeps these as numbers in memory; the text writes a name where one exists. Reading accepts the name or the
|
||||
number. The tables are in `src/names.rs`.
|
||||
|
||||
| Node kind | Key | Names |
|
||||
|---|---|---|
|
||||
| every kind | `format` (output format) | `graph` (the graph's own), `u8`, `u16`, `f16`, `f32`, and `u8_compiled`, `u16_compiled`, `f16_compiled`, which quantise the way compiled graphs do (their own rounding, and blurs and levels that keep the format on the way) |
|
||||
| `blend` | `mode` | `copy`, `add`, `subtract`, `multiply`, `screen`, `overlay`, `max`, `min`, `difference`, `soft_light`, `color_dodge`, `color_burn`, `linear_burn`, `hard_light`, `exclusion`, `divide`, `linear_light`, `color`, `luminosity`, `dissolve`, `add_sub`, `switch`, and `add_compiled`, `subtract_compiled`, `add_sub_compiled`, `divide_compiled`, `soft_light_compiled` (opacity acts before the result is limited) |
|
||||
| `pp_quadrant` | `pattern` | `square`, `disc`, `paraboloid`, `bell`, `gaussian`, `thorn`, `pyramid`, `brick`, `gradation`, `waves`, `half_bell`, `ridged_bell`, `crescent`, `capsule`, `cone`, `gradation_offset`, `hemisphere` |
|
||||
| `f_random` | `lcg` | which 24-bit generator a draw comes from, by where the function runs: `pixel`, `value`, `parameter`, `size`, `fx_luminance`, `fx_branch_offset`, `fx_pattern_offset`, `fx_size`, `fx_rotation`, `fx_variation`, `fx_switch_condition`, `fx_iterate_count`, `fx_image_index` |
|
||||
|
||||
Older spellings still read the same: the key `ofmt=<n>` for `format`, numbers in place of the names, and seven function
|
||||
ops under their format-2 names (`f_fsin`, `f_fcos`, `f_flog`, `f_fdiv`, `f_fatan2`, `f_gsin`, `f_gcos`, now
|
||||
`f_sin_poly`, `f_cos_poly`, `f_log_floor`, `f_div_large`, `f_atan2_approx`, `f_sin_f32turns`, `f_cos_f32turns`).
|
||||
|
||||
## Evaluation
|
||||
|
||||
- Results are float RGBA. The same text, size and parameters give the same bits on every platform and thread count:
|
||||
transcendental functions come from one implementation (`crate::math`), parallel loops split work at fixed indices,
|
||||
and results never depend on which thread computed them.
|
||||
- Evaluation never panics on a hostile text: sizes are limited to 8192 per side, subgraphs nest at most 8 deep, function
|
||||
calls at most 8 deep, a function graph runs at most 2048 nodes deep per pixel, FX-maps draw at most 500,000 markers,
|
||||
and loops are bounded.
|
||||
- The host stops an evaluation with a cancel flag (`context::Cancel`); the runtime never reads a clock. Files a graph
|
||||
names but does not carry are read through the host's `context::FileSource` (none on the web).
|
||||
- `versions::of_kind` gives a version per node kind, derived at build time from the source each kind reaches, for
|
||||
caches of results.
|
||||
|
||||
## Node kinds
|
||||
|
||||
Function graphs (`meta kind "function"`) carry values (float, float2-4, integer, integer2-4, boolean, string) instead of
|
||||
images and never produce NaN or infinity. FX-map programs (`meta kind "fxmap"`) are run by the `fx_map` node; pattern
|
||||
programs (`meta kind "patterns"`) by `pattern_program`. The tables below are the runtime's own node definitions
|
||||
(`graph::SPECS`, `compiled_ops::SPECS`, `atomic::SPECS`, `func::FUNC_SPECS`, `fxmap::FXM_SPECS`, `patterns::SPECS`).
|
||||
|
||||
### Image nodes
|
||||
|
||||
| Node | Category | Inputs | Description and parameters |
|
||||
|---|---|---|---|
|
||||
| `color` | Generators | | constant colour: r g b a |
|
||||
| `white_noise` | Generators | | per-pixel random: seed distribution(0 uniform,1 gaussian,2 triangle) |
|
||||
| `gaussian_noise` | Generators | | gaussian-distributed per-pixel noise: seed scale contrast invert disorder disorder_speed anisotropy anisotropy_angle tile_x tile_y |
|
||||
| `perlin` | Generators | | perlin noise: scale scale_x scale_y seed disorder disorder_speed tile_x tile_y |
|
||||
| `fbm` | Generators | | fractal noise/clouds: scale octaves gain seed mode(0 fbm,1 ridged,2 turbulence) disorder disorder_speed anisotropy anisotropy_angle tile_x tile_y |
|
||||
| `voronoi` | Generators | | cellular: scale jitter seed mode(0 f1,1 cell id,2 edge,3 f2,4 f2-f1,5 f1*f2,6 f1/f2) aspect offset_x offset_y distortion distortion_scale distance_mode(0 euclid,1 manhattan,2 chebyshev,3 minkowski) minkowski edge_thickness rounded distance_scale color_seed_mode color_seed invert |
|
||||
| `voronoi_fractal` | Generators | | layered voronoi: scale jitter seed mode aspect offset_x offset_y distortion distortion_scale distance_mode minkowski edge_thickness rounded distance_scale min_level max_level roughness lacunarity opacity blend(0 add,1 max,2 min) color_seed_mode color_seed invert |
|
||||
| `gradient` | Generators | | gradient: mode(0 linear,1 radial) angle |
|
||||
| `circle` | Generators | | radius softness |
|
||||
| `rect` | Generators | | width height softness |
|
||||
| `polygon` | Generators | | sides radius softness rotation |
|
||||
| `checker` | Generators | | tiles |
|
||||
| `bricks` | Generators | | rows cols mortar bevel offset lum_var seed |
|
||||
| `fx_map` | Generators | in (optional), in2 (optional), in3 (optional), in4 (optional) | run a pattern program: program="name" depth seed blend (0 max 1 add 2 over 3 min 4 multiply) color bg bg_r bg_g bg_b |
|
||||
| `curve` | Filters | in | tone curves: points (master), points_r points_g points_b points_a as "x:y,x:y" lists |
|
||||
| `svg` | Generators | | vector image: file="art.svg" fit (0 contain 1 stretch 2 cover) scale x y |
|
||||
| `text` | Generators | | text: text="..." font="face.ttf" (optional) size x y align (0 left 1 centre 2 right) spacing line_spacing rotation value |
|
||||
| `channel_shuffle` | Filters | in, in2 (optional) | rebuild channels: src_r src_g src_b src_a (0-3 channels of in, 4-7 channels of in2, 8 zero, 9 one), inv_r inv_g inv_b inv_a |
|
||||
| `input_value` | Utility | | graph parameter read by functions: name, type (0 float, 1 int, 2 bool, 3 float2, 4 float3, 5 float4, 6 int2, 7 int3, 8 int4, 9 string), v / x y z w, min max, label |
|
||||
| `pixel_processor` | Generators | in (optional), in2 (optional), in3 (optional), in4 (optional), in5 (optional), in6 (optional), in7 (optional), in8 (optional), in9 (optional), in10 (optional), in11 (optional), in12 (optional), in13 (optional), in14 (optional), in15 (optional), in16 (optional), in17 (optional), in18 (optional), in19 (optional), in20 (optional), in21 (optional), in22 (optional), in23 (optional), in24 (optional), in25 (optional), in26 (optional), in27 (optional), in28 (optional), in29 (optional), in30 (optional), in31 (optional), in32 (optional) | per-pixel expr / expr_g / expr_b / expr_a (string params), or fn="function" to run a function graph per pixel |
|
||||
| `value_processor` | Generators | in (optional), in2 (optional), in3 (optional), in4 (optional) | run fn="function" once; the result (float, float3 or float4) fills the image. The function can read image statistics |
|
||||
| `sdf_shape` | SDF | | 2D signed distance shape: shape(0 circle,1 box,2 polygon,3 ring) size aspect sides rotation round x y range |
|
||||
| `sdf_op` | SDF | a, b | combine SDFs: op(0 union,1 subtract,2 intersect) smooth range |
|
||||
| `sdf_mask` | SDF | in | SDF -> mask: offset softness |
|
||||
| `sdf_form` | SDF | | procedural 3D SDF form as height: shape(0 sphere,1 box,2 torus,3 cylinder) size repeat round scatter seed height |
|
||||
| `bitmap` | Utility | | flip_x flip_y gray; imported PNG bitmap: file="path.png" |
|
||||
| `input` | Utility | | subgraph input: idx |
|
||||
| `subgraph` | Utility | in0 (optional), in1 (optional), in2 (optional), in3 (optional) | instance of a reusable subgraph: graph="name" |
|
||||
| `shape` | Generators | | procedural shape: square, disc, paraboloid, gaussian, diamond, pyramid, half sphere, cone |
|
||||
| `tile_sampler` | Generators | pattern (optional), pattern2 (optional), pattern3 (optional), pattern4 (optional), pattern5 (optional), pattern6 (optional), mask (optional), scale_map (optional), rotation_map (optional), displacement_map (optional), color_map (optional), distribution_map (optional), background (optional) | grid of pattern instances: x_amount y_amount size aspect size_mode scale scale_random size_random rotation rotation_random pattern_rotation symmetry_random position_random offset offset_mode offset_random global_offset_x global_offset_y color color_random lum_by_number lum_by_scale mask_threshold mask_invert mask_random mask_checker invert_mask blending opacity background reverse_order pattern_type pattern_specific pattern_distribution |
|
||||
| `tile_generator` | Generators | pattern (optional), pattern2 (optional), pattern3 (optional), pattern4 (optional), pattern5 (optional), pattern6 (optional), mask (optional), scale_map (optional), rotation_map (optional), displacement_map (optional), color_map (optional), distribution_map (optional), background (optional) | brick-style tiles: x_amount y_amount size aspect size_mode scale scale_random size_random rotation rotation_random pattern_rotation symmetry_random position_random offset offset_mode offset_random global_offset_x global_offset_y color color_random lum_by_number lum_by_scale mask_checker mask_horizontal mask_vertical mask_random invert_mask blending opacity background reverse_order pattern_type pattern_specific pattern_distribution |
|
||||
| `splatter` | Generators | pattern (optional), pattern2 (optional), pattern3 (optional), pattern4 (optional), pattern5 (optional), pattern6 (optional) | random scatter of a pattern: count grid_number scale scale_var aspect rotation rot_var pattern_rotation lum_var disorder pan_x pan_y symmetry_random gain output_min output_max background blending opacity pattern_type pattern_specific pattern_distribution |
|
||||
| `splatter_circular` | Generators | pattern (optional), pattern2 (optional), pattern3 (optional), pattern4 (optional), pattern5 (optional), pattern6 (optional) | instances on one or more circles: number amount_random rings radius radius_random ring_radius_multiplier angle_random spiral_factor spread size size_random scale_by_number scale_by_ring rotation rotation_random center_orientation ring_rotation ring_rotation_random position_random color luminance_random lum_by_number lum_by_ring mask_random background blending opacity pattern_type pattern_specific pattern_distribution |
|
||||
| `clouds` | Generators | | soft cloud noise: scale seed contrast invert disorder disorder_speed anisotropy anisotropy_angle tile_x tile_y |
|
||||
| `bnw_spots` | Generators | | black and white spots: scale seed contrast invert variant disorder disorder_speed anisotropy anisotropy_angle tile_x tile_y |
|
||||
| `crystal` | Generators | | faceted crystal cells: scale disorder seed contrast invert variant |
|
||||
| `directional_noise` | Generators | | streak noise, seamless at any angle: scale stretch angle seed contrast invert disorder disorder_speed anisotropy anisotropy_angle tile_x tile_y |
|
||||
| `grunge` | Generators | | grunge masks: variant(0 concrete,1 scratches,2 spots,3 smudges) balance large_variation base_noisiness dirt_specks_opacity invert_dirt scratches_opacity sharpen quantity scratch_width scratch_length details coverage coverage_contrast disorder disorder_speed seed contrast invert |
|
||||
| `plasma` | Generators | | smooth plasma waves |
|
||||
| `stripes` | Generators | | stripes: count angle softness width tile(1 = snap to seamless angle, 0 = exact) |
|
||||
| `weave` | Generators | | woven threads: count width |
|
||||
| `star` | Generators | | star shape: points inner size softness rotation |
|
||||
| `gradient_axial` | Generators | | symmetric gradient: angle |
|
||||
| `gradient_circular` | Generators | | angular gradient: offset |
|
||||
| `switch` | Filters | a (optional), b (optional), c (optional), d (optional) | pass one of up to four inputs: index |
|
||||
| `flood_fill` | Filters | in | label connected regions of a mask |
|
||||
| `flood_fill_random` | Filters | in | random grayscale per flood-fill region |
|
||||
| `flood_fill_color` | Filters | in | random color per flood-fill region |
|
||||
| `flood_fill_to_index` | Filters | in | region number of each flood-fill region as a gray level |
|
||||
| `flood_fill_to_position` | Filters | in | centre of each flood-fill region (outputs: position, x, y) |
|
||||
| `flood_fill_to_bbox_size` | Filters | in | bounding-box size of each flood-fill region (outputs: size, width, height) |
|
||||
| `flood_fill_gradient` | Filters | in | gradient across each flood-fill region |
|
||||
| `vector_warp` | Filters | in, vector | displace by a vector map: intensity directx |
|
||||
| `slope_blur` | Filters | in, slope | blur along a slope map: samples intensity mode |
|
||||
| `blur_hq` | Filters | in | high quality blur: intensity quality |
|
||||
| `histogram_range` | Filters | in | select a range of values: position range contrast invert |
|
||||
| `bevel` | Filters | in | bevel a shape: distance smoothing threshold use_as_normal normal_intensity corner(0 round,1 angular) directx |
|
||||
| `distance` | Filters | in | distance field of a mask: distance mode |
|
||||
| `color_match` | Filters | in, reference (optional), src_color (optional), target_color (optional) | recolour: method(0 statistics transfer from reference,1 colour swap) strength source_mode(0 average,1 colour,2 input) src_r src_g src_b target_mode(0 colour,1 input) target_r target_g target_b custom_variation variation_hue variation_chroma variation_luma use_mask mask_hue_range mask_chroma_range mask_luma_range mask_smoothness |
|
||||
| `curvature_smooth` | Material | in | smooth curvature from a normal map |
|
||||
| `height_blend` | Material | bg, fg, mask (optional) | blend two height maps: opacity contrast output |
|
||||
| `make_it_tile_photo` | Filters | in | make a photo tile: width width_v |
|
||||
| `make_it_tile_patch` | Filters | in | make an image tile with random patches |
|
||||
| `clamp` | Filters | in | clamp values: low high apply_alpha |
|
||||
| `highpass` | Filters | in | high-pass filter: radius |
|
||||
| `swirl` | Filters | in | swirl distortion: amount radius |
|
||||
| `edge_wear` | Material | in, noise (optional) | edge wear mask from a height map: amount width contrast |
|
||||
| `dirt` | Material | in, noise (optional) | dirt mask from an ambient occlusion map: amount contrast |
|
||||
| `dust` | Material | in, noise (optional) | dust mask from a normal map: amount contrast |
|
||||
| `output` | Utility | in (optional) | graph output: usage identifier |
|
||||
| `dot` | Utility | in | re-route a link |
|
||||
| `blur` | Filters | in | gaussian blur: radius |
|
||||
| `directional_blur` | Filters | in | angle length |
|
||||
| `sharpen` | Filters | in | radius amount |
|
||||
| `levels` | Filters | in | low high gamma out_low out_high |
|
||||
| `adjust` | Filters | in | brightness contrast |
|
||||
| `invert` | Filters | in | invert colours: invert |
|
||||
| `threshold` | Filters | in | binary threshold: threshold softness mode(0 greater,1 greater or equal,2 lower,3 lower or equal) |
|
||||
| `histogram_scan` | Filters | in | position width |
|
||||
| `quantize` | Filters | in | steps |
|
||||
| `to_gray` | Filters | in | luminance |
|
||||
| `channel` | Filters | in | ch(0 r,1 g,2 b,3 a) |
|
||||
| `merge` | Filters | r (optional), g (optional), b (optional), a (optional) | combine channels |
|
||||
| `tint` | Filters | in | multiply by colour: r g b |
|
||||
| `colorize` | Filters | in | gradient map: interp(0 linear,1 smooth,2 step,3 smoother) smoothness addressing(0 clamp,1 repeat) use_alpha stops p0 r0 g0 b0 a0 ... p15 r15 g15 b15 a15 |
|
||||
| `hsl` | Filters | in | hue sat val |
|
||||
| `transform` | Filters | in | offset_x offset_y scale_x scale_y rotation(turns) |
|
||||
| `mirror` | Filters | in | mirror an image: axis(0 x,1 y,2 both,3 corner) offset_x offset_y invert_x invert_y corner(0 top left,1 top right,2 bottom left,3 bottom right) |
|
||||
| `warp` | Filters | in, warp | slope warp: intensity filtering(0 bilinear,1 nearest,2 bicubic) |
|
||||
| `directional_warp` | Filters | in, warp | warp in one direction: angle intensity offset filtering(0 bilinear,1 nearest,2 bicubic) |
|
||||
| `blend` | Filters | fg, bg, mask (optional) | blend two images: mode (copy, add, subtract, multiply, screen, overlay, max, min, difference, soft_light, color_dodge, color_burn, linear_burn, hard_light, exclusion, divide, linear_light, color, luminosity, dissolve, add_sub, switch, and as compiled graphs blend: add_compiled, subtract_compiled, add_sub_compiled, divide_compiled, soft_light_compiled) opacity alpha_mode(0 source alpha,1 ignore alpha,2 straight,3 premultiplied) crop_x0 crop_y0 crop_x1 crop_y1 |
|
||||
| `normal` | Material | in | height->normal (OpenGL +Y): strength directx alpha_from_input |
|
||||
| `normal_blend` | Material | a, b, mask (optional) | blend normal maps (a = background, b = foreground): opacity |
|
||||
| `ao` | Material | in | ambient occlusion: mode(0 blur,1 horizon) radius intensity hbao_radius hbao_intensity quality(0 4,1 8,2 16 samples) use_world_units height_depth surface_size height_depth_cm |
|
||||
| `quantize_color` | Filters | in | reduce to few colours (k-means): color_amount contour_smoothing dithering dithering_pattern(0 noise,1 bayer) ignore_alpha distance_color_space(0 lab,1 rgb) |
|
||||
| `curvature` | Material | in | curvature of a normal map: mode(0 normal map,1 height map) intensity directx radius |
|
||||
| `edge_detect` | Filters | in | edge lines: mode(0 lines,1 sobel) edge_width edge_roundness invert tolerance intensity |
|
||||
| `emboss` | Filters | in | angle intensity |
|
||||
| `non_uniform_blur` | Filters | in, mask | blur by a mask: intensity |
|
||||
| `radial_blur` | Filters | in | spin blur around a centre: mode(0 spin,1 zoom) samples angle x y amount radius |
|
||||
| `anisotropic_blur` | Filters | in | blur stretched in one direction: intensity anisotropy angle |
|
||||
| `symmetry` | Filters | in | mirror the image around a line: axis(0 x,1 y,2 both,3 diagonal,4 anti-diagonal,5 eight-fold) offset flip transfer(0 copy,1 add,2 sub,3 mul,4 add sub,5 max,6 min) |
|
||||
| `skew` | Filters | in | shear that keeps tiling: skew_x skew_y (whole numbers) align(0 centre,1 top left,2 bottom right) |
|
||||
| `auto_levels` | Filters | in | stretch values to the full range: per_channel |
|
||||
| `channel_mixer` | Filters | in | mix colour channels: rr rg rb gr gg gb br bg bb mono |
|
||||
| `alpha_merge` | Filters | rgb, alpha (optional) | put a grayscale image into the alpha channel |
|
||||
| `color_to_mask` | Filters | in | mask of pixels close to a colour: r g b range softness |
|
||||
| `replace_color` | Filters | in | replace one colour with another: src_r src_g src_b dst_r dst_g dst_b range softness |
|
||||
| `pow` | Filters | in | raise values to a power: exponent |
|
||||
| `histogram_shift` | Filters | in | shift all values: position |
|
||||
| `grayscale_conversion` | Filters | in | weighted grayscale: r g b |
|
||||
| `cells` | Generators | color (optional) | cellular noise: scale jitter seed variant(0 cells1,1 cells2,2 cells3,3 cells4) luminance_random color_source(0 random,1 pseudorandom,2 image) pseudorandom_seed edge_width hardness contrast invert disorder disorder_speed anisotropy anisotropy_angle tile_x tile_y |
|
||||
| `fractal_sum` | Generators | | sum of noise octaves: scale min_level max_level roughness seed mode(0 base,1 turbulence,2 creased) contrast invert disorder disorder_speed |
|
||||
| `waveform` | Generators | | tileable wave pattern: count angle warp warp_scale seed shape(0 sine,1 triangle,2 saw,3 square) contrast invert disorder disorder_speed |
|
||||
| `gaussian_spots` | Generators | | soft gaussian spots: scale size size_variation seed contrast invert disorder disorder_speed anisotropy anisotropy_angle tile_x tile_y |
|
||||
| `normal_invert` | Material | in | flip normal map channels: invert_x invert_y invert_z invert_a |
|
||||
| `normal_normalize` | Material | in | renormalise a normal map |
|
||||
| `normal_vector_rotation` | Material | in, rotation (optional) | rotate normal vectors: angle directx |
|
||||
| `normal_to_height` | Material | in | integrate a normal map into a height map: directx relief_balance opacity |
|
||||
| `sobel` | Filters | in | sobel edge magnitude: intensity |
|
||||
| `glow` | Filters | in | glow around bright areas: width intensity clear glow_r glow_g glow_b |
|
||||
| `mosaic` | Filters | in, mosaic_map (optional) | mosaic of the map regions (or a pixel grid without a map): count intensity |
|
||||
| `non_uniform_directional_warp` | Filters | in, intensity, angle (optional) | warp along a direction chosen per pixel: intensity angle |
|
||||
| `multi_directional_warp` | Filters | in, warp | warp in several directions at once: intensity directions(0 one,1 two,2 four) angle mode(0 average,1 max,2 min,3 chain) |
|
||||
| `normal_combine` | Material | base, detail | combine two normal maps: technique(0 whiteout,1 channel mixer,2 detail oriented) |
|
||||
| `triangle_grid` | Generators | | grid of triangles: style(0 squares,1 jittered mesh) count border variation x_amount y_amount random_position_multiplier quincunx_offset_x quincunx_offset_y triangulation(0 fixed,1 alternate,2 random) output(0 smooth,1 flat,2 edge distance) height_random thin_lines distance_to_edge_thickness thin_line_color thin_line_background seed contrast invert |
|
||||
| `grunge_map` | Generators | | grunge map 1-15: map balance contrast brush_pattern cracks disorder coverage seed invert |
|
||||
| `rgba_split` | Filters | in | split into R, G, B and A grayscale outputs |
|
||||
| `alpha_split` | Filters | in | split into an RGB output and an alpha output |
|
||||
| `weave_generator` | Generators | | woven threads with gaps: tile_x tile_y weave shape gap_x gap_y contrast invert |
|
||||
| `starburst` | Generators | | star-like rays: count rays sharpness size rotation rotation_random seed contrast invert |
|
||||
| `gradient_reflected` | Generators | | gradient that goes 0-1-0: count angle contrast invert |
|
||||
| `shape_stroke` | Filters | in | outline of a shape: width offset softness threshold opacity color_r color_g color_b |
|
||||
| `shape_glow` | Filters | in | glow around a shape: width softness intensity threshold opacity spread color_r color_g color_b |
|
||||
| `chrominance_extract` | Filters | in | colour without brightness |
|
||||
| `shape_drop_shadow` | Filters | in | drop shadow of a mask: angle distance blur opacity spread |
|
||||
|
||||
### Compiled-graph image nodes
|
||||
|
||||
| Node | Inputs | Description and parameters |
|
||||
|---|---|---|
|
||||
| `curve_keys` | in | tone curve from Bezier keys: n, then per key k xk yk (point) lxk lyk (left handle) rxk ryk (right handle); ramp=1 draws the curve left to right instead of applying it |
|
||||
| `triangle_strips` | | white triangle strips on black: strips="...", each strip hex digits, 8 per vertex (yyyyxxxx, 0..ffff across the image), strips apart by a space |
|
||||
| `distance_map` | in, source (optional) | distance from the mask's bright pixels: distance (reach in 1/256 of the image, default 10), aspect_x aspect_y, tile_x tile_y (1, the default: across the image's edge); with a source, the colour of the nearest mask pixel, fade=1 fading it out with distance |
|
||||
| `normal_map` | in | tangent-space normals from a height: intensity (default 1, scaled by width/256), flip_y, alpha=1 keeps the height in alpha, aspect_x aspect_y |
|
||||
| `emboss_map` | in, map | adds the slope of map along a direction: intensity (default 1, scaled by width/256), angle (turns), aspect_x aspect_y |
|
||||
| `gradient_dynamic` | in, grad | look up the grad image with the input: in picks the column (vertical=1 the row), position the other coordinate |
|
||||
|
||||
### Atomic image nodes
|
||||
|
||||
| Node | Inputs | Description and parameters |
|
||||
|---|---|---|
|
||||
| `levels_mid` | in | levels with a midpoint: low high mid out_low out_high; per channel with suffix _r _g _b _a (e.g. low_r) |
|
||||
| `hsl_centered` | in | hue, saturation and lightness shifts, 0.5 = unchanged, twice the distance from 0.5 is added: hue (turns) sat lum |
|
||||
| `transform_matrix` | in | transform by a matrix around the centre, reading the input at (m00 x + m10 y + offset_x, m01 x + m11 y + offset_y) from the centre: tile_x tile_y (1 repeat, 0 bg_r bg_g bg_b bg_a outside, default none) filter (1 bilinear, 0 nearest) mip (level, 31 from the scale) |
|
||||
| `dir_warp` | in, map | move each pixel along a direction by the brightness of map: intensity (1/256 of the image per unit of map), angle (turns), map_offset (brightness that moves nothing), tile_x tile_y (1 repeat, 0 repeat the edge) |
|
||||
| `grad_warp` | in, map | move each pixel along the slope of map: intensity (default 1; 1/256 of the image per unit of slope in uv), aspect_x, aspect_y (default 1), tile_x tile_y (1 repeat, 0 keep the edge: no slope across it, edge value read) |
|
||||
| `box_blur` | in | blur with a box in both axes reaching intensity pixels of a 256 pixel image each way: intensity aspect_x aspect_y (scale it per axis) tile_x tile_y (1 repeat, 0 repeat the edge) |
|
||||
| `line_blur` | in | average along a line reaching intensity pixels of a 256 pixel image each way, by shearing the image, a box along the longer axis and shearing back: intensity aspect_x aspect_y (scale it per axis) angle (turns) tile_x tile_y (1 repeat, 0 repeat the edge) |
|
||||
| `laplacian_sharpen` | in | add intensity times the difference to the four neighbours, limited to 0..1: intensity aspect_x aspect_y (scale it per axis) tile_x tile_y (1 repeat, 0 repeat the edge) |
|
||||
| `pattern_program` | in (optional), in2 (optional), in3 (optional), in4 (optional), in5 (optional), in6 (optional), in7 (optional), in8 (optional), in9 (optional), in10 (optional), in11 (optional), in12 (optional), in13 (optional), in14 (optional), in15 (optional), in16 (optional), in17 (optional), in18 (optional), in19 (optional), in20 (optional), in21 (optional), in22 (optional), in23 (optional), in24 (optional), in25 (optional), in26 (optional), in27 (optional), in28 (optional), in29 (optional), in30 (optional), in31 (optional), in32 (optional), bg (optional) | run a pattern program: program="name" seed color(0/1); bg is an image the canvas starts from |
|
||||
|
||||
### Function-graph nodes
|
||||
|
||||
| Node | Inputs | Description and parameters |
|
||||
|---|---|---|
|
||||
| `f_out` | in | result of the function |
|
||||
| `f_pin` | a | re-route a value link |
|
||||
| `f_float` | | constant float: v |
|
||||
| `f_int` | | constant integer: v |
|
||||
| `f_bool` | | constant boolean: v (0 or 1) |
|
||||
| `f_string` | | constant string: v |
|
||||
| `f_vec2` | x (optional), y (optional) | float2 from parts (x y, linked parts win over the typed values) |
|
||||
| `f_vec3` | x (optional), y (optional), z (optional) | float3 from parts |
|
||||
| `f_vec4` | x (optional), y (optional), z (optional), w (optional) | float4 from parts |
|
||||
| `f_ivec2` | x (optional), y (optional) | integer2 from parts |
|
||||
| `f_ivec3` | x (optional), y (optional), z (optional) | integer3 from parts |
|
||||
| `f_ivec4` | x (optional), y (optional), z (optional), w (optional) | integer4 from parts |
|
||||
| `f_swizzle` | a | pick or reorder components: mask (xyzw or rgba, e.g. "zyx") |
|
||||
| `f_neg` | a | negate |
|
||||
| `f_abs` | a | absolute value |
|
||||
| `f_sqrt` | a | square root (0 for negative input) |
|
||||
| `f_exp` | a | e to the power a |
|
||||
| `f_log` | a | natural logarithm (0 for input <= 0) |
|
||||
| `f_log_floor` | a | natural logarithm, very low for input <= 0 (the engine of compiled graphs) |
|
||||
| `f_log2` | a | base-2 logarithm (0 for input <= 0) |
|
||||
| `f_sin` | a | sine (radians) |
|
||||
| `f_cos` | a | cosine (radians) |
|
||||
| `f_sin_poly` | a | sine by the polynomial of the engine of compiled graphs' fx-maps and node parameters |
|
||||
| `f_cos_poly` | a | cosine by the polynomial of the engine of compiled graphs' fx-maps and node parameters |
|
||||
| `f_sin_f32turns` | a | sine as a compiled graph's pixel processor has it on a GPU: the turn count truncated in single precision |
|
||||
| `f_cos_f32turns` | a | cosine as a compiled graph's pixel processor has it on a GPU: the turn count truncated in single precision |
|
||||
| `f_tan` | a | tangent (radians) |
|
||||
| `f_asin` | a | inverse sine (input clamped to -1..1) |
|
||||
| `f_acos` | a | inverse cosine (input clamped to -1..1) |
|
||||
| `f_atan` | a | inverse tangent |
|
||||
| `f_radians` | a | degrees to radians |
|
||||
| `f_degrees` | a | radians to degrees |
|
||||
| `f_floor` | a | round down |
|
||||
| `f_ceil` | a | round up |
|
||||
| `f_round` | a | round to nearest |
|
||||
| `f_fract` | a | fractional part |
|
||||
| `f_sign` | a | -1, 0 or 1 |
|
||||
| `f_saturate` | a | clamp to 0..1 |
|
||||
| `f_not` | a | boolean not |
|
||||
| `f_length` | a | length of a vector |
|
||||
| `f_normalize` | a | vector of length 1 (zero stays zero) |
|
||||
| `f_add` | a, b | a + b |
|
||||
| `f_sub` | a, b | a - b |
|
||||
| `f_mul` | a, b | a * b |
|
||||
| `f_div` | a, b | a / b (0 when b is 0; integer division truncates) |
|
||||
| `f_div_large` | a, b | a / b, very large when b is 0 and a is not (the engine of compiled graphs) |
|
||||
| `f_mod` | a, b | remainder of a / b with the sign of b (0 when b is 0) |
|
||||
| `f_pow` | a, b | a to the power b |
|
||||
| `f_min` | a, b | smaller value |
|
||||
| `f_max` | a, b | larger value |
|
||||
| `f_atan2` | a, b | angle of the point (b, a) |
|
||||
| `f_atan2_approx` | a, b | angle of the point (b, a), by the approximation of the engine of compiled graphs |
|
||||
| `f_step` | a, b | 0 when b < a, else 1 |
|
||||
| `f_dot` | a, b | dot product |
|
||||
| `f_cross` | a, b | cross product of two float3 |
|
||||
| `f_distance` | a, b | distance between two points |
|
||||
| `f_clamp` | a, b, c | clamp a between b (low) and c (high) |
|
||||
| `f_lerp` | a, b, c | a + (b - a) * c |
|
||||
| `f_smoothstep` | a, b, c | smooth 0..1 ramp of c between edges a and b |
|
||||
| `f_eq` | a, b | a == b |
|
||||
| `f_ne` | a, b | a != b |
|
||||
| `f_lt` | a, b | a < b |
|
||||
| `f_le` | a, b | a <= b |
|
||||
| `f_gt` | a, b | a > b |
|
||||
| `f_ge` | a, b | a >= b |
|
||||
| `f_and` | a, b | boolean and |
|
||||
| `f_or` | a, b | boolean or |
|
||||
| `f_xor` | a, b | boolean exclusive or |
|
||||
| `f_if` | cond, a, b | a when cond is true, else b (only the chosen branch runs) |
|
||||
| `f_sequence` | a, b | run a, then b; returns b |
|
||||
| `f_loop` | a, c, b (optional) | run a, then c again and again: until b is true, or `passes` times; returns 0 |
|
||||
| `f_set` | a | store a in the variable `name`; returns a |
|
||||
| `f_get` | | read the variable `name` (0 until it is set); type: what it holds, for type checks (default float) |
|
||||
| `f_random` | a (optional), b (optional), s (optional) | random float between a (default 0) and b (default 1); `seed` shifts the sequence; `lcg` draws from a 24-bit generator as compiled graphs do, by where the function runs (pixel, value, parameter, size, fx_luminance ... fx_image_index; see names::LCG_SITES and lcg_rand), with seed s and draw number k |
|
||||
| `f_sample_gray` | a | brightness of input image `slot` (default in) at the position a (float2, 0..1); filter: bit 0 bilinear, else nearest, bit 1 keep the edge, else repeat (default bilinear, repeat) |
|
||||
| `f_sample_color` | a | colour (float4) of input image `slot` at the position a; filter as for f_sample_gray |
|
||||
| `f_image_avg` | | average colour (float4) of input image `slot` |
|
||||
| `f_image_min` | | smallest channel values (float4) of input image `slot` |
|
||||
| `f_image_max` | | largest channel values (float4) of input image `slot` |
|
||||
| `f_pos` | | position being evaluated (float2, 0..1) |
|
||||
| `f_size` | | output size in pixels (float2) |
|
||||
| `f_own_size` | | size in pixels (float2) of the node whose parameter this computes; the output size elsewhere |
|
||||
| `f_cell_size` | | size of the cell a pattern program is walking, in uv (float; 1 elsewhere) |
|
||||
| `f_cell_depth` | | how many quadrants deep the cell of a pattern program is (float; 0 elsewhere) |
|
||||
| `f_index` | | instance / iteration number (integer) |
|
||||
| `f_count` | | number of instances / iterations (integer) |
|
||||
| `f_seed` | | random seed of the caller (integer) |
|
||||
| `f_input` | | input of this function: name, type (0 float, 1 int, 2 bool, 3 float2, 4 float3, 5 float4, 6 int2, 7 int3, 8 int4, 9 string), default v / x y z w |
|
||||
| `f_graph_input` | | value of an Input Value node of the graph the caller lives in: name, type, default v / x y z w |
|
||||
| `f_to_float` | a | convert to float |
|
||||
| `f_to_int` | a | convert to integer (drops the fraction) |
|
||||
| `f_to_bool` | a | non-zero is true |
|
||||
| `f_to_string` | a | text of a value |
|
||||
| `f_concat` | a, b | join two strings |
|
||||
| `f_call` | a (optional), b (optional), c (optional), d (optional) | run another function (`fn`); a b c d fill its inputs in the order of their node numbers |
|
||||
|
||||
### FX-map program nodes
|
||||
|
||||
| Node | Inputs | Description and parameters |
|
||||
|---|---|---|
|
||||
| `fxm_out` | in | start of a pattern program |
|
||||
| `fxm_marker` | | draw a shape: shape (0 circle 1 square 2 diamond 3 image) src x y w h rot value r g b softness rnd_pos rnd_scale rnd_rot rnd_val rnd_color |
|
||||
| `fxm_quadrant` | q0 (optional), q1 (optional), q2 (optional), q3 (optional) | split the cell in four: scale off_x off_y p0..p3 (chance) v0..v3 (value) r0..r3 (rotation) rnd_pos rnd_scale rnd_rot rnd_val |
|
||||
| `fxm_iterate` | body (optional) | repeat body: count dx dy dscale drot dval, or grid_x grid_y stagger; rnd_x rnd_y rnd_scale rnd_rot rnd_val |
|
||||
| `fxm_switch` | a (optional), b (optional), c (optional), d (optional) | run one branch: mode (0 index, 1 random) index w0..w3 |
|
||||
|
||||
### Pattern-program nodes
|
||||
|
||||
| Node | Inputs | Description and parameters |
|
||||
|---|---|---|
|
||||
| `pp_out` | in | start of a pattern program; fn.init, then fn.background, fn.roughness, fn.opacity, fn.frame and fn.frame_offset run first |
|
||||
| `pp_iterate` | first (optional), body (optional) | run first once, then body count times (count or fn.count); f_index is the iteration |
|
||||
| `pp_switch` | a (optional), b (optional) | run b when cond (or fn.cond) is true, else a |
|
||||
| `pp_quadrant` | q0 (optional), q1 (optional), q2 (optional), q3 (optional) | one cell, split in four for q0..q3: draws pattern (square, disc, paraboloid, bell, gaussian, thorn, pyramid, brick, gradation, waves, half_bell, ridged_bell, crescent, capsule, cone, gradation_offset, hemisphere), or with image=1 the input image_index, with luminance, branch_offset_x/y, offset_x/y, size_x/y, rotation, variation, max (each also fn.<name>) |
|
||||
@@ -0,0 +1,258 @@
|
||||
//! Optional host accelerators for whole-image graph operations.
|
||||
|
||||
use std::{any::Any, fmt::Debug, sync::Arc};
|
||||
|
||||
use crate::context::Cancel;
|
||||
use crate::func::{FnEnv, PixelShader, Prog};
|
||||
use crate::tex::{Grey, Grey16, ImgRef, Tex};
|
||||
|
||||
pub struct PixelRequest<'a> {
|
||||
pub program: &'a Prog,
|
||||
pub environment: &'a FnEnv<'a>,
|
||||
pub size: [usize; 2],
|
||||
pub cancel: &'a Cancel,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum PixelOutput {
|
||||
Grey(Grey),
|
||||
Rgba(Tex),
|
||||
}
|
||||
|
||||
/// Whole-image operations on the compiled graph's 16-bit grayscale values.
|
||||
pub enum GreyPass<'a> {
|
||||
/// A wrapped bilinear identity transform enlarging through successive doublings.
|
||||
Enlarge { source: &'a Grey16, side: usize },
|
||||
/// A full-frame unmasked blend that keeps the background alpha.
|
||||
Blend { foreground: &'a Grey16, background: &'a Grey16, mode: u32, opacity: f32 },
|
||||
}
|
||||
|
||||
/// Packed, quantized grayscale pixels owned by an accelerator.
|
||||
pub trait ResidentGreyPixels: Debug + Send + Sync {
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
fn read(&self, cancel: &Cancel) -> Result<Vec<u16>, String>;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ResidentGrey16 {
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
pub div: f32,
|
||||
pub alpha: f32,
|
||||
pub pixels: Arc<dyn ResidentGreyPixels>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum GreyInput<'a> {
|
||||
Host(&'a Grey16),
|
||||
Device(&'a ResidentGrey16),
|
||||
}
|
||||
|
||||
impl GreyInput<'_> {
|
||||
pub fn info(self) -> (usize, usize, f32, f32) {
|
||||
match self {
|
||||
Self::Host(t) => (t.w, t.h, t.div, t.alpha),
|
||||
Self::Device(t) => (t.w, t.h, t.div, t.alpha),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Transfers an opaque grayscale float image when a downstream operation needs CPU pixels.
|
||||
pub trait ResidentFloatPixels: Debug + Send + Sync {
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
fn read(&self, cancel: &Cancel) -> Result<Vec<f32>, String>;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ResidentGreyFloat {
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
pub pixels: Arc<dyn ResidentFloatPixels>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum GreyTransformInput<'a> {
|
||||
Quantized(GreyInput<'a>),
|
||||
Float(&'a ResidentGreyFloat),
|
||||
}
|
||||
|
||||
/// The wrapped bilinear identity transform that builds half-float graph pyramids.
|
||||
pub struct HalfTransform<'a> {
|
||||
pub source: GreyTransformInput<'a>,
|
||||
pub side: usize,
|
||||
/// An explicit pyramid level, or automatic resizing when absent.
|
||||
pub mip: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum PixelImageInput<'a> {
|
||||
Host(ImgRef<'a>),
|
||||
Float(&'a ResidentGreyFloat),
|
||||
}
|
||||
|
||||
pub enum ResidentGreyPass<'a> {
|
||||
Enlarge {
|
||||
source: GreyInput<'a>,
|
||||
side: usize,
|
||||
},
|
||||
Reduce {
|
||||
source: GreyInput<'a>,
|
||||
side: usize,
|
||||
},
|
||||
/// Full-frame blend with its constant result alpha resolved by the graph.
|
||||
Blend {
|
||||
foreground: GreyInput<'a>,
|
||||
background: GreyInput<'a>,
|
||||
mask: Option<GreyInput<'a>>,
|
||||
mode: u32,
|
||||
opacity: f32,
|
||||
alpha: f32,
|
||||
},
|
||||
Levels {
|
||||
source: GreyInput<'a>,
|
||||
curve: Vec<u16>,
|
||||
div: f32,
|
||||
alpha: f32,
|
||||
},
|
||||
}
|
||||
|
||||
/// Full-frame blend modes that operate independently on each color channel.
|
||||
pub fn packed_blend_mode(mode: u32) -> bool {
|
||||
matches!(mode, 0..=16 | 20..=21 | 32..=36)
|
||||
}
|
||||
|
||||
/// Packed RGBA in the compiled graph's unsigned 16-bit steps.
|
||||
#[derive(Debug)]
|
||||
pub struct ResidentColor16 {
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
pub alpha: Option<f32>,
|
||||
pub pixels: Arc<dyn ResidentGreyPixels>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum ColorInput<'a> {
|
||||
Grey(GreyInput<'a>),
|
||||
Host(&'a Tex),
|
||||
Device(&'a ResidentColor16),
|
||||
}
|
||||
|
||||
/// Parameters shared by the grayscale, color and reference directional warps.
|
||||
pub struct DirectionalWarpParams {
|
||||
pub intensity: f32,
|
||||
pub offset: f32,
|
||||
pub direction: [f32; 2],
|
||||
pub aspect: [f32; 2],
|
||||
pub tile: [bool; 2],
|
||||
}
|
||||
|
||||
pub enum ResidentColorPass<'a> {
|
||||
Blend {
|
||||
foreground: ColorInput<'a>,
|
||||
background: ColorInput<'a>,
|
||||
mask: Option<ColorInput<'a>>,
|
||||
mode: u32,
|
||||
opacity: f32,
|
||||
alpha_mode: u32,
|
||||
alpha: Option<f32>,
|
||||
},
|
||||
Grayscale {
|
||||
source: ColorInput<'a>,
|
||||
weights: [f32; 4],
|
||||
/// Known binary alpha allows storage in the packed grayscale path.
|
||||
alpha: Option<f32>,
|
||||
},
|
||||
DirectionalWarp {
|
||||
source: ColorInput<'a>,
|
||||
map: GreyInput<'a>,
|
||||
settings: DirectionalWarpParams,
|
||||
alpha: Option<f32>,
|
||||
},
|
||||
WrappedAffine {
|
||||
source: &'a ResidentColor16,
|
||||
matrix: [f32; 4],
|
||||
offset: [f32; 2],
|
||||
},
|
||||
}
|
||||
|
||||
pub enum ResidentColorOutput {
|
||||
Grey(ResidentGrey16),
|
||||
Color(ResidentColor16),
|
||||
}
|
||||
|
||||
pub struct ResidentFilter<'a> {
|
||||
pub source: GreyInput<'a>,
|
||||
pub size: [usize; 2],
|
||||
pub tile: [bool; 2],
|
||||
pub div: f32,
|
||||
pub operation: FilterOperation<'a>,
|
||||
}
|
||||
|
||||
pub enum FilterOperation<'a> {
|
||||
DirectionalWarp { map: GreyInput<'a>, intensity: f32, offset: f32, direction: [f32; 2], aspect: [f32; 2] },
|
||||
GradientWarp { map: GreyInput<'a>, displacement: [f32; 2] },
|
||||
Box { radius: [f32; 2] },
|
||||
ShortLine { major: usize, slope: f32, radius: f32 },
|
||||
ShearedLine { major: usize, slope: f32, radius: f32 },
|
||||
Sharpen { weights: [f32; 2] },
|
||||
Affine { matrix: [f32; 4], offset: [f32; 2], bilinear: bool, mip_side: Option<usize>, edge_fade: [usize; 2] },
|
||||
}
|
||||
|
||||
pub trait Accelerator: Send + Sync {
|
||||
/// Identifies changes to rendered pixels for the host's result caches.
|
||||
fn cache_tag(&self) -> &str;
|
||||
|
||||
/// `None` leaves this operation to the reference evaluator.
|
||||
fn pixel(&self, _request: PixelRequest<'_>) -> Result<Option<PixelOutput>, String> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Draw the ordered instances of a procedural pattern program.
|
||||
fn pattern(&self, _request: crate::patterns::RasterRequest<'_>) -> Result<Option<crate::patterns::RasterOutput>, String> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn grey_pass(&self, _pass: GreyPass<'_>, _cancel: &Cancel) -> Result<Option<Grey16>, String> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Execute a grayscale operation without fetching its result back to the host.
|
||||
fn resident_grey(&self, _pass: ResidentGreyPass<'_>, _cancel: &Cancel) -> Result<Option<ResidentGrey16>, String> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn resident_color(&self, _pass: ResidentColorPass<'_>, _cancel: &Cancel) -> Result<Option<ResidentColorOutput>, String> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Execute a grayscale pixel program whose image inputs and output use packed integer samples.
|
||||
fn resident_pixel(
|
||||
&self,
|
||||
_shader: PixelShader,
|
||||
_images: &[GreyInput<'_>],
|
||||
_size: [usize; 2],
|
||||
_cancel: &Cancel,
|
||||
) -> Result<Option<ResidentGrey16>, String> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Execute a spatial filter on packed compiled grayscale graph pixels.
|
||||
fn resident_filter(&self, _filter: ResidentFilter<'_>, _cancel: &Cancel) -> Result<Option<ResidentGrey16>, String> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn resident_half_transform(&self, _pass: HalfTransform<'_>, _cancel: &Cancel) -> Result<Option<ResidentGreyFloat>, String> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Writes packed grayscale while sampling resident float images and any remaining host images.
|
||||
fn resident_textured_pixel(
|
||||
&self,
|
||||
_shader: PixelShader,
|
||||
_images: &[PixelImageInput<'_>],
|
||||
_size: [usize; 2],
|
||||
_cancel: &Cancel,
|
||||
) -> Result<Option<ResidentGrey16>, String> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,178 @@
|
||||
//! Checksums used by the container formats: CRC-32 (PNG chunks, ZIP entries) and Adler-32 (zlib streams).
|
||||
//! Both come as a one-shot function and as an incremental hasher for streamed data.
|
||||
|
||||
/// Slicing-by-8 tables for the reflected CRC-32 polynomial 0xEDB88320, built at compile time.
|
||||
const CRC_TABLES: [[u32; 256]; 8] = crc_tables();
|
||||
|
||||
// Only ever evaluated at compile time (for `CRC_TABLES`), where an out-of-range index is a build error, not a runtime
|
||||
// panic; `get`/`get_mut` are not usable in const fns.
|
||||
#[allow(clippy::indexing_slicing)]
|
||||
const fn crc_tables() -> [[u32; 256]; 8] {
|
||||
let mut t = [[0u32; 256]; 8];
|
||||
let mut n = 0;
|
||||
while n < 256 {
|
||||
let mut c = n as u32;
|
||||
let mut k = 0;
|
||||
while k < 8 {
|
||||
c = if c & 1 != 0 { 0xedb8_8320 ^ (c >> 1) } else { c >> 1 };
|
||||
k += 1;
|
||||
}
|
||||
t[0][n] = c;
|
||||
n += 1;
|
||||
}
|
||||
let mut s = 1;
|
||||
while s < 8 {
|
||||
let mut n = 0;
|
||||
while n < 256 {
|
||||
let prev = t[s - 1][n];
|
||||
t[s][n] = (prev >> 8) ^ t[0][(prev & 0xff) as usize];
|
||||
n += 1;
|
||||
}
|
||||
s += 1;
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// Incremental CRC-32 (ISO 3309 / ITU-T V.42, as used by PNG, ZIP and gzip).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Crc32 {
|
||||
state: u32,
|
||||
}
|
||||
|
||||
impl Default for Crc32 {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Crc32 {
|
||||
pub fn new() -> Self {
|
||||
Crc32 { state: 0xffff_ffff }
|
||||
}
|
||||
|
||||
pub fn update(&mut self, data: &[u8]) {
|
||||
let [t0, t1, t2, t3, t4, t5, t6, t7] = &CRC_TABLES;
|
||||
let mut c = self.state;
|
||||
let (words, rest) = data.as_chunks::<8>();
|
||||
for &[b0, b1, b2, b3, b4, b5, b6, b7] in words {
|
||||
let lo = c ^ u32::from_le_bytes([b0, b1, b2, b3]);
|
||||
c = at(t7, lo)
|
||||
^ at(t6, lo >> 8)
|
||||
^ at(t5, lo >> 16)
|
||||
^ at(t4, lo >> 24)
|
||||
^ at(t3, b4 as u32)
|
||||
^ at(t2, b5 as u32)
|
||||
^ at(t1, b6 as u32)
|
||||
^ at(t0, b7 as u32);
|
||||
}
|
||||
for &b in rest {
|
||||
c = at(t0, c ^ b as u32) ^ (c >> 8);
|
||||
}
|
||||
self.state = c;
|
||||
}
|
||||
|
||||
pub fn finish(&self) -> u32 {
|
||||
self.state ^ 0xffff_ffff
|
||||
}
|
||||
}
|
||||
|
||||
/// Table entry for the low byte of `i` (the mask keeps the index in range, so the check folds away).
|
||||
#[inline(always)]
|
||||
fn at(t: &[u32; 256], i: u32) -> u32 {
|
||||
t.get((i & 0xff) as usize).copied().unwrap_or(0)
|
||||
}
|
||||
|
||||
/// CRC-32 of `data`.
|
||||
pub fn crc32(data: &[u8]) -> u32 {
|
||||
let mut h = Crc32::new();
|
||||
h.update(data);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Incremental Adler-32 (RFC 1950).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Adler32 {
|
||||
a: u32,
|
||||
b: u32,
|
||||
}
|
||||
|
||||
impl Default for Adler32 {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Adler32 {
|
||||
const MOD: u32 = 65521;
|
||||
/// Largest n such that 255 n (n + 1) / 2 + (n + 1)(MOD - 1) fits in u32: the sums can be deferred that long.
|
||||
const NMAX: usize = 5552;
|
||||
|
||||
pub fn new() -> Self {
|
||||
Adler32 { a: 1, b: 0 }
|
||||
}
|
||||
|
||||
pub fn update(&mut self, data: &[u8]) {
|
||||
let (mut a, mut b) = (self.a, self.b);
|
||||
for block in data.chunks(Self::NMAX) {
|
||||
for &d in block {
|
||||
a += d as u32;
|
||||
b += a;
|
||||
}
|
||||
a %= Self::MOD;
|
||||
b %= Self::MOD;
|
||||
}
|
||||
self.a = a;
|
||||
self.b = b;
|
||||
}
|
||||
|
||||
pub fn finish(&self) -> u32 {
|
||||
(self.b << 16) | self.a
|
||||
}
|
||||
}
|
||||
|
||||
/// Adler-32 of `data`.
|
||||
pub fn adler32(data: &[u8]) -> u32 {
|
||||
let mut h = Adler32::new();
|
||||
h.update(data);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn known_values() {
|
||||
assert_eq!(crc32(b""), 0);
|
||||
assert_eq!(crc32(b"123456789"), 0xcbf4_3926);
|
||||
assert_eq!(crc32(b"The quick brown fox jumps over the lazy dog"), 0x414f_a339);
|
||||
assert_eq!(adler32(b""), 1);
|
||||
assert_eq!(adler32(b"Wikipedia"), 0x11e6_0398);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incremental_matches_one_shot() {
|
||||
let data: Vec<u8> = (0..100_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect();
|
||||
let (mut c, mut a) = (Crc32::new(), Adler32::new());
|
||||
for part in data.chunks(777) {
|
||||
c.update(part);
|
||||
a.update(part);
|
||||
}
|
||||
assert_eq!(c.finish(), crc32(&data));
|
||||
assert_eq!(a.finish(), adler32(&data));
|
||||
// Bytewise reference for the sliced CRC.
|
||||
let mut r = 0xffff_ffffu32;
|
||||
for &b in &data {
|
||||
r = CRC_TABLES[0][((r ^ b as u32) & 0xff) as usize] ^ (r >> 8);
|
||||
}
|
||||
assert_eq!(r ^ 0xffff_ffff, crc32(&data));
|
||||
// Reference Adler with a modulo per byte, over 0xff bytes (worst case for deferred reduction).
|
||||
let ff = vec![0xffu8; 20_000];
|
||||
let (mut x, mut y) = (1u32, 0u32);
|
||||
for &d in &ff {
|
||||
x = (x + d as u32) % 65521;
|
||||
y = (y + x) % 65521;
|
||||
}
|
||||
assert_eq!((y << 16) | x, adler32(&ff));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,590 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! More image operations with the conventions of compiled node graphs, each measured against the original renderer:
|
||||
//! see the crate's decompiler for how compiled nodes map onto them. `compute` returns Ok(None) for kinds it does not
|
||||
//! know.
|
||||
|
||||
use crate::graph::{Error, Node, Spec};
|
||||
use crate::math;
|
||||
use crate::measured::INTENSITY_SPAN;
|
||||
use crate::tex::Tex;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc as Rc;
|
||||
|
||||
/// What a node's text leaves out. Distance: 10, measurement "Operations identified, by fitting" (0x2a "Default distance 10").
|
||||
/// Normal: 1, the same section (0x25 "default 1"). Emboss: 1, no measurement, a guess.
|
||||
const DISTANCE_DEFAULT: f32 = 10.0;
|
||||
const NORMAL_DEFAULT_INTENSITY: f32 = 1.0;
|
||||
const EMBOSS_DEFAULT_INTENSITY: f32 = 1.0;
|
||||
/// A distance mask's pixel is set from this value on. Measurement "Operations identified, by fitting" (0x2a: "to the nearest
|
||||
/// pixel >= 0.5").
|
||||
const DISTANCE_SET_FROM: f32 = 0.5;
|
||||
/// An aspect this small counts as this, so the axis reaches nowhere instead of dividing by zero (a guard).
|
||||
const ASPECT_FLOOR_SQ: f32 = 1e-6;
|
||||
/// Format data: a vector shape's vertices are 16-bit fixed point, `k / 65535` of the image. Measurement "Operations identified,
|
||||
/// by fitting" (0x0a: "n u16 x,y pairs").
|
||||
const STRIP_COORD_STEPS: f32 = 65535.0;
|
||||
|
||||
pub const SPECS: &[Spec] = &[
|
||||
Spec {
|
||||
kind: "curve_keys",
|
||||
req: &["in"],
|
||||
opt: &[],
|
||||
doc: "tone curve from Bezier keys: n, then per key k xk yk (point) lxk lyk (left handle) rxk ryk (right handle); ramp=1 draws the curve left to right instead of applying it",
|
||||
},
|
||||
Spec {
|
||||
kind: "triangle_strips",
|
||||
req: &[],
|
||||
opt: &[],
|
||||
doc: "white triangle strips on black: strips=\"...\", each strip hex digits, 8 per vertex (yyyyxxxx, 0..ffff across the image), strips apart by a space",
|
||||
},
|
||||
Spec {
|
||||
kind: "distance_map",
|
||||
req: &["in"],
|
||||
opt: &["source"],
|
||||
doc: "distance from the mask's bright pixels: distance (reach in 1/256 of the image, default 10), aspect_x aspect_y, tile_x tile_y (1, the default: across the image's edge); with a source, the colour of the nearest mask pixel, fade=1 fading it out with distance",
|
||||
},
|
||||
Spec {
|
||||
kind: "normal_map",
|
||||
req: &["in"],
|
||||
opt: &[],
|
||||
doc: "tangent-space normals from a height: intensity (default 1, scaled by width/256), flip_y, alpha=1 keeps the height in alpha, aspect_x aspect_y",
|
||||
},
|
||||
Spec {
|
||||
kind: "emboss_map",
|
||||
req: &["in", "map"],
|
||||
opt: &[],
|
||||
doc: "adds the slope of map along a direction: intensity (default 1, scaled by width/256), angle (turns), aspect_x aspect_y",
|
||||
},
|
||||
Spec {
|
||||
kind: "gradient_dynamic",
|
||||
req: &["in", "grad"],
|
||||
opt: &[],
|
||||
doc: "look up the grad image with the input: in picks the column (vertical=1 the row), position the other coordinate",
|
||||
},
|
||||
];
|
||||
|
||||
/// Run a node of this module. Ok(None) = not one of ours.
|
||||
pub fn compute(kind: &str, id: u32, n: &Node, ins: &BTreeMap<String, Rc<Tex>>, size: [usize; 2]) -> Result<Option<Tex>, Error> {
|
||||
let f = |k: &str, d: f32| n.nums.get(k).copied().unwrap_or(d);
|
||||
let need = |slot: &str| -> Result<&Tex, Error> { ins.get(slot).map(|r| r.as_ref()).ok_or_else(|| Error::MissingInput(id, slot.to_string())) };
|
||||
Ok(Some(match kind {
|
||||
"curve_keys" => {
|
||||
let keys: Vec<CurveKey> = (0..f("n", 0.0).max(0.0) as usize)
|
||||
.map(|k| {
|
||||
let g = |name: &str| f(&format!("{name}{k}"), 0.0);
|
||||
CurveKey { point: [g("x"), g("y")], left: [g("lx"), g("ly")], right: [g("rx"), g("ry")] }
|
||||
})
|
||||
.collect();
|
||||
let table = curve_table(&keys);
|
||||
let t = need("in")?;
|
||||
if f("ramp", 0.0) > 0.5 {
|
||||
let (w, h) = (t.w, t.h);
|
||||
Tex::gray_fn(w, h, |u, _| table_ramp(&table, u, w))
|
||||
} else {
|
||||
t.map(|p| [table_lookup(&table, p[0]), table_lookup(&table, p[1]), table_lookup(&table, p[2]), p[3]])
|
||||
}
|
||||
}
|
||||
"triangle_strips" => {
|
||||
let strips = parse_strips(n.strs.get("strips").map_or("", String::as_str)).ok_or_else(|| Error::BadParam(id, "bad strips".into()))?;
|
||||
let (w, h) = (size[0], size[1]);
|
||||
let c = strips_coverage(&strips, w, h);
|
||||
let mut t = Tex::solid(w, h, [0.0, 0.0, 0.0, 1.0]);
|
||||
for (p, v) in t.px.iter_mut().zip(c) {
|
||||
*p = [v, v, v, 1.0];
|
||||
}
|
||||
t
|
||||
}
|
||||
"distance_map" => {
|
||||
let t = need("in")?;
|
||||
let reach = f("distance", DISTANCE_DEFAULT) * t.w as f32 / INTENSITY_SPAN;
|
||||
// the distance is in the units across, so on a node of another shape a pixel down counts width/height pixels (measured:
|
||||
// leather_strip #546, 512 x 128, falls off over 112.57/256 of the height down; pipe_rack #47, 256 x 32, over 32/256 of the
|
||||
// width across)
|
||||
let (ax, ay) = (f("aspect_x", 1.0), f("aspect_y", 1.0) * t.h as f32 / t.w as f32);
|
||||
let field = NearestField::new(
|
||||
t.w,
|
||||
t.h,
|
||||
|x, y| t.px_at(y * t.w + x)[0] >= DISTANCE_SET_FROM,
|
||||
ax,
|
||||
ay,
|
||||
[f("tile_x", 1.0) > 0.5, f("tile_y", 1.0) > 0.5],
|
||||
);
|
||||
let source = ins.get("source").map(|r| r.as_ref());
|
||||
let fade = f("fade", 0.0) > 0.5;
|
||||
let mut out = Tex::solid(t.w, t.h, [0.0, 0.0, 0.0, 1.0]);
|
||||
for y in 0..t.h {
|
||||
for x in 0..t.w {
|
||||
let Some((d2, nx, ny)) = field.at(x, y) else { continue };
|
||||
let d = d2.sqrt();
|
||||
let falloff = if reach > 0.0 { (1.0 - d / reach).clamp(0.0, 1.0) } else { f32::from(u8::from(d2 == 0.0)) };
|
||||
let v = match source {
|
||||
None => [falloff, falloff, falloff, 1.0],
|
||||
Some(s) => {
|
||||
let c = s.px_at((ny * s.h / t.h) * s.w + nx * s.w / t.w);
|
||||
if fade {
|
||||
[c[0] * falloff, c[1] * falloff, c[2] * falloff, c[3]]
|
||||
} else if d < reach || d2 == 0.0 {
|
||||
c
|
||||
} else {
|
||||
[0.0, 0.0, 0.0, 1.0]
|
||||
}
|
||||
}
|
||||
};
|
||||
out.set_px(y * t.w + x, v);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
"normal_map" => {
|
||||
let t = need("in")?;
|
||||
let k = f("intensity", NORMAL_DEFAULT_INTENSITY) * t.w as f32 / INTENSITY_SPAN;
|
||||
// on a node of another shape the slope down is in the same units as across, height over width per pixel (measured on
|
||||
// 512 x 128 nodes: leather_strip #363 at intensity 64 has 64 across and 16 down per pixel step; bandage #42 and
|
||||
// fabric_edge_wear #26 with their aspect expressions come out equal, ours 4 times that down: means 15 to 21 off)
|
||||
let (kx, ky) = (k * f("aspect_x", 1.0), k * f("aspect_y", 1.0) * t.h as f32 / t.w as f32);
|
||||
let sign_y = if f("flip_y", 0.0) > 0.5 { 1.0 } else { -1.0 };
|
||||
let alpha = f("alpha", 0.0) > 0.5;
|
||||
per_pixel(t, |x, y| {
|
||||
let (gx, gy) = backward_slope(t, x, y, 0);
|
||||
let (nx, ny) = (-kx * gx, sign_y * ky * gy);
|
||||
let len = (nx * nx + ny * ny + 1.0).sqrt();
|
||||
[0.5 * nx / len + 0.5, 0.5 * ny / len + 0.5, 0.5 / len + 0.5, if alpha { t.px_at(y * t.w + x)[0] } else { 1.0 }]
|
||||
})
|
||||
}
|
||||
"emboss_map" => {
|
||||
let (t, map) = (need("in")?, need("map")?);
|
||||
let k = f("intensity", EMBOSS_DEFAULT_INTENSITY) * t.w as f32 / INTENSITY_SPAN;
|
||||
let (sn, cs) = math::sin_cos(f("angle", 0.0) * std::f32::consts::TAU);
|
||||
let (kx, ky) = (k * f("aspect_x", 1.0) * cs, k * f("aspect_y", 1.0) * sn);
|
||||
per_pixel(t, |x, y| {
|
||||
let (gx, gy) = backward_slope(map, x * map.w / t.w, y * map.h / t.h, 0);
|
||||
let add = kx * gx + ky * gy;
|
||||
let p = t.px_at(y * t.w + x);
|
||||
[(p[0] + add).clamp(0.0, 1.0), (p[1] + add).clamp(0.0, 1.0), (p[2] + add).clamp(0.0, 1.0), p[3]]
|
||||
})
|
||||
}
|
||||
"gradient_dynamic" => {
|
||||
let (t, grad) = (need("in")?, need("grad")?);
|
||||
let vertical = f("vertical", 0.0) > 0.5;
|
||||
let position = f("position", 0.0).clamp(0.0, 1.0);
|
||||
let (gw, gh) = (grad.w.saturating_sub(1) as f32, grad.h.saturating_sub(1) as f32);
|
||||
t.map(|p| {
|
||||
let v = p[0].clamp(0.0, 1.0);
|
||||
if vertical { texel_lerp(grad, position * gw, v * gh) } else { texel_lerp(grad, v * gw, position * gh) }
|
||||
})
|
||||
}
|
||||
_ => return Ok(None),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Vertices (0..1) of the strips in the text form of `triangle_strips`.
|
||||
fn parse_strips(text: &str) -> Option<Vec<Vec<[f32; 2]>>> {
|
||||
text.split_whitespace()
|
||||
.map(|strip| {
|
||||
let bytes = strip.as_bytes();
|
||||
bytes
|
||||
.chunks(8)
|
||||
.map(|c| {
|
||||
let v = u32::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok()?;
|
||||
Some([(v & 0xffff) as f32 / STRIP_COORD_STEPS, (v >> 16) as f32 / STRIP_COORD_STEPS])
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Fraction of each pixel covered by the strips: their union, sampled 4 x 4 per pixel (a choice: measurement "Operations identified,
|
||||
/// by fitting" (0x0a) has 99.2 to 99.8% of pixels, the edges off). A pixel's samples are at
|
||||
/// (i + 0.5) / 4 of it. Triangles without area leave no trace (strips join their parts with such triangles).
|
||||
fn strips_coverage(strips: &[Vec<[f32; 2]>], w: usize, h: usize) -> Vec<f32> {
|
||||
const SS: usize = 4;
|
||||
let (sw, sh) = (w * SS, h * SS);
|
||||
let rows: Vec<Vec<u8>> = crate::tex::par_map(h, |py| {
|
||||
let mut row = vec![0u8; w];
|
||||
let mut mask = vec![false; sw];
|
||||
for sy in py * SS..(py + 1) * SS {
|
||||
mask.fill(false);
|
||||
let y = sy as f32 + 0.5;
|
||||
for strip in strips {
|
||||
for tri in strip.windows(3) {
|
||||
let &[ta, tb, tc] = tri else { continue };
|
||||
let p = |q: [f32; 2]| [q[0] * sw as f32, q[1] * sh as f32];
|
||||
let (a, b, c) = (p(ta), p(tb), p(tc));
|
||||
// the span of this sample row inside the triangle
|
||||
let (mut lo, mut hi) = (f32::INFINITY, f32::NEG_INFINITY);
|
||||
for (s, e) in [(a, b), (b, c), (c, a)] {
|
||||
if (s[1] <= y) != (e[1] <= y) {
|
||||
let x = s[0] + (y - s[1]) / (e[1] - s[1]) * (e[0] - s[0]);
|
||||
lo = lo.min(x);
|
||||
hi = hi.max(x);
|
||||
}
|
||||
}
|
||||
if lo < hi {
|
||||
let from = (lo - 0.5).ceil().max(0.0) as usize;
|
||||
let to = ((hi - 0.5).floor() + 1.0).clamp(0.0, sw as f32) as usize;
|
||||
if from < to
|
||||
&& let Some(m) = mask.get_mut(from..to)
|
||||
{
|
||||
m.fill(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (cell, m) in row.iter_mut().zip(mask.as_chunks::<SS>().0) {
|
||||
*cell += m.iter().filter(|m| **m).count() as u8;
|
||||
}
|
||||
}
|
||||
row
|
||||
});
|
||||
rows.into_iter().flatten().map(|v| f32::from(v) / (SS * SS) as f32).collect()
|
||||
}
|
||||
|
||||
/// A texture from a function of the pixel. Runs multi-threaded.
|
||||
fn per_pixel<F: Fn(usize, usize) -> [f32; 4] + Sync>(t: &Tex, f: F) -> Tex {
|
||||
let (w, h) = (t.w, t.h);
|
||||
Tex::from_fn(w, h, |u, v| f(((u * w as f32) as usize).min(w - 1), ((v * h as f32) as usize).min(h - 1)))
|
||||
}
|
||||
|
||||
/// The change of channel `c` from the pixel before, along x and y, wrapped.
|
||||
fn backward_slope(t: &Tex, x: usize, y: usize, c: usize) -> (f32, f32) {
|
||||
let at = |x: usize, y: usize| t.px_at(y * t.w + x).get(c).copied().unwrap_or(0.0);
|
||||
(at(x, y) - at((x + t.w - 1) % t.w, y), at(x, y) - at(x, (y + t.h - 1) % t.h))
|
||||
}
|
||||
|
||||
/// Bilinear between texels, by texel coordinates, stopping at the edges.
|
||||
fn texel_lerp(t: &Tex, x: f32, y: f32) -> [f32; 4] {
|
||||
let (x0, y0) = (x as usize, y as usize);
|
||||
let (x1, y1) = ((x0 + 1).min(t.w.saturating_sub(1)), (y0 + 1).min(t.h.saturating_sub(1)));
|
||||
let (fx, fy) = (x - x0 as f32, y - y0 as f32);
|
||||
let at = |x: usize, y: usize| t.px_at(y * t.w + x);
|
||||
let (a, b, c, d) = (at(x0, y0), at(x1, y0), at(x0, y1), at(x1, y1));
|
||||
let mix = |a: f32, b: f32, c: f32, d: f32| (a * (1.0 - fx) + b * fx) * (1.0 - fy) + (c * (1.0 - fx) + d * fx) * fy;
|
||||
[mix(a[0], b[0], c[0], d[0]), mix(a[1], b[1], c[1], d[1]), mix(a[2], b[2], c[2], d[2]), mix(a[3], b[3], c[3], d[3])]
|
||||
}
|
||||
|
||||
/// The nearest set pixel of a mask for every pixel, with a distance that may weigh the axes differently, across the edges on
|
||||
/// the axes that repeat.
|
||||
struct NearestField {
|
||||
w: usize,
|
||||
/// Per pixel: squared distance and the nearest set pixel; `None` everywhere when no pixel is set.
|
||||
cells: Vec<Option<(f32, usize, usize)>>,
|
||||
}
|
||||
|
||||
impl NearestField {
|
||||
/// Exact Euclidean distances in two passes: along each column, then the lower envelope of parabolas along each
|
||||
/// row, over three periods so that the nearest pixel may lie across the wrap (one when the axis doesn't repeat).
|
||||
fn new(w: usize, h: usize, set: impl Fn(usize, usize) -> bool + Sync, ax: f32, ay: f32, tile: [bool; 2]) -> NearestField {
|
||||
// for each column: distance (in rows, wrapped) to the nearest set pixel and that pixel's row
|
||||
let columns: Vec<Vec<Option<(usize, usize)>>> = crate::tex::par_map(w, |x| {
|
||||
let rows: Vec<usize> = (0..h).filter(|&y| set(x, y)).collect();
|
||||
let Some((&first, &last)) = rows.first().zip(rows.last()) else { return vec![None; h] };
|
||||
let mut out = vec![None; h];
|
||||
let mut next = 0;
|
||||
for (y, cell) in out.iter_mut().enumerate() {
|
||||
while rows.get(next).is_some_and(|&r| r < y) {
|
||||
next += 1;
|
||||
}
|
||||
// past the last or first set pixel the nearest one is across the edge, or else very far
|
||||
let far = (usize::MAX / 4, first);
|
||||
let below = rows.get(next).copied().map_or(if tile[1] { (first + h - y, first) } else { far }, |r| (r - y, r));
|
||||
let above = if let Some(&r) = next.checked_sub(1).and_then(|i| rows.get(i)) {
|
||||
(y - r, r)
|
||||
} else if tile[1] {
|
||||
(y + h - last, last)
|
||||
} else {
|
||||
far
|
||||
};
|
||||
*cell = Some(if above.0 < below.0 { above } else { below });
|
||||
}
|
||||
out
|
||||
});
|
||||
// the aspect divides: at 0 an axis doesn't reach across at all
|
||||
let weight = |a: f32| 1.0 / (a * a).max(ASPECT_FLOOR_SQ);
|
||||
let (ax2, ay2) = (weight(ax), weight(ay));
|
||||
let rows: Vec<Vec<Option<(f32, usize, usize)>>> = crate::tex::par_map(h, |y| {
|
||||
// parabolas at x + k w with height g^2, k = -1, 0, 1; without repeating only those of k = 0
|
||||
let (n, base) = if tile[0] { (3 * w, 0) } else { (2 * w, w) };
|
||||
let mut site = vec![0usize; n];
|
||||
let mut from = vec![0f32; n];
|
||||
let mut top = 0usize;
|
||||
let mut any = false;
|
||||
let column = |i: usize| columns.get(i % w).and_then(|c| c.get(y)).copied().flatten();
|
||||
let height = |i: usize| column(i).map(|(g, _)| (g * g) as f32 * ay2);
|
||||
let site_at = |site: &[usize], k: usize| site.get(k).copied().unwrap_or(0);
|
||||
let from_at = |from: &[f32], k: usize| from.get(k).copied().unwrap_or(f32::NEG_INFINITY);
|
||||
let put = |v: &mut [usize], k: usize, x: usize| {
|
||||
if let Some(e) = v.get_mut(k) {
|
||||
*e = x;
|
||||
}
|
||||
};
|
||||
for i in base..n {
|
||||
let Some(hi) = height(i) else { continue };
|
||||
if !any {
|
||||
any = true;
|
||||
put(&mut site, 0, i);
|
||||
if let Some(e) = from.first_mut() {
|
||||
*e = f32::NEG_INFINITY;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let cross = |p: usize| {
|
||||
let hp = height(p).unwrap_or(0.0);
|
||||
let (pf, qf) = (p as f32, i as f32);
|
||||
(hi - hp + ax2 * (qf * qf - pf * pf)) / (2.0 * ax2 * (qf - pf))
|
||||
};
|
||||
let mut s = cross(site_at(&site, top));
|
||||
while s <= from_at(&from, top) && top > 0 {
|
||||
top -= 1;
|
||||
s = cross(site_at(&site, top));
|
||||
}
|
||||
if s <= from_at(&from, top) {
|
||||
put(&mut site, top, i);
|
||||
} else {
|
||||
top += 1;
|
||||
put(&mut site, top, i);
|
||||
if let Some(e) = from.get_mut(top) {
|
||||
*e = s;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !any {
|
||||
return vec![None; w];
|
||||
}
|
||||
let mut k = 0;
|
||||
(0..w)
|
||||
.map(|x| {
|
||||
let q = (x + w) as f32;
|
||||
while k < top && from.get(k + 1).is_some_and(|&f| f < q) {
|
||||
k += 1;
|
||||
}
|
||||
let i = site_at(&site, k);
|
||||
let (g, row) = column(i)?;
|
||||
let dx = q - i as f32;
|
||||
Some((ax2 * dx * dx + (g * g) as f32 * ay2, i % w, row))
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
NearestField { w, cells: rows.into_iter().flatten().collect() }
|
||||
}
|
||||
|
||||
/// Squared distance and the nearest set pixel of pixel (x, y).
|
||||
fn at(&self, x: usize, y: usize) -> Option<(f32, usize, usize)> {
|
||||
self.cells.get(y * self.w + x).copied().flatten()
|
||||
}
|
||||
}
|
||||
|
||||
/// One key of a tone curve.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct CurveKey {
|
||||
pub point: [f32; 2],
|
||||
pub left: [f32; 2],
|
||||
pub right: [f32; 2],
|
||||
}
|
||||
|
||||
/// Entries of the table a curve is evaluated through; measured, it shows where a curve is very steep. Measurement "Operations
|
||||
/// identified, by fitting" (0x2c: "Bezier keys through a 1024-entry table").
|
||||
const CURVE_TABLE: usize = 1024;
|
||||
|
||||
/// The curve's value at `CURVE_TABLE` evenly spaced inputs from 0 to 1. Before the first key and after the last the
|
||||
/// value stays that key's.
|
||||
pub fn curve_table(keys: &[CurveKey]) -> Vec<f32> {
|
||||
let bezier = |a: f32, b: f32, c: f32, d: f32, t: f32| {
|
||||
let s = 1.0 - t;
|
||||
s * s * s * a + 3.0 * s * s * t * b + 3.0 * s * t * t * c + t * t * t * d
|
||||
};
|
||||
(0..CURVE_TABLE)
|
||||
.map(|i| {
|
||||
let x = i as f32 / (CURVE_TABLE - 1) as f32;
|
||||
let (Some(first), Some(last)) = (keys.first(), keys.last()) else { return x };
|
||||
if x <= first.point[0] {
|
||||
return first.point[1];
|
||||
}
|
||||
if x >= last.point[0] {
|
||||
return last.point[1];
|
||||
}
|
||||
let Some((a, b)) = keys.windows(2).find_map(|p| match *p {
|
||||
[a, b] if x < b.point[0] => Some((a, b)),
|
||||
_ => None,
|
||||
}) else {
|
||||
return last.point[1];
|
||||
};
|
||||
// the x of a segment rises with t, so bisection finds the t of this input
|
||||
let (mut lo, mut hi) = (0.0f32, 1.0f32);
|
||||
for _ in 0..32 {
|
||||
let t = 0.5 * (lo + hi);
|
||||
if bezier(a.point[0], a.right[0], b.left[0], b.point[0], t) > x {
|
||||
hi = t;
|
||||
} else {
|
||||
lo = t;
|
||||
}
|
||||
}
|
||||
bezier(a.point[1], a.right[1], b.left[1], b.point[1], 0.5 * (lo + hi))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Linear interpolation in the table, for an input clamped to 0..1.
|
||||
fn table_lookup(table: &[f32], v: f32) -> f32 {
|
||||
let p = v.clamp(0.0, 1.0) * table.len().saturating_sub(1) as f32;
|
||||
let i = (p as usize).min(table.len().saturating_sub(2));
|
||||
let t = p - i as f32;
|
||||
let at = |i: usize| table.get(i).copied().unwrap_or(0.0);
|
||||
at(i) * (1.0 - t) + at(i + 1) * t
|
||||
}
|
||||
|
||||
/// The table stretched over an image `w` pixels wide, by texels: u = (x + 0.5) / w.
|
||||
fn table_ramp(table: &[f32], u: f32, w: usize) -> f32 {
|
||||
let n = table.len();
|
||||
let p = u * n as f32 - 0.5;
|
||||
if w >= n {
|
||||
let i = p.floor().clamp(0.0, n.saturating_sub(2) as f32);
|
||||
let t = (p - i).clamp(0.0, 1.0);
|
||||
let i = i as usize;
|
||||
let at = |i: usize| table.get(i).copied().unwrap_or(0.0);
|
||||
return at(i) * (1.0 - t) + at(i + 1) * t;
|
||||
}
|
||||
// shrinking by a whole factor is a box filter
|
||||
let k = n / w;
|
||||
let start = ((u * n as f32) as usize).saturating_sub(k / 2).min(n - k);
|
||||
table.get(start..start + k).unwrap_or_default().iter().sum::<f32>() / k as f32
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::graph::Graph;
|
||||
|
||||
#[test]
|
||||
fn a_straight_curve_is_the_identity_and_outside_the_keys_it_holds() {
|
||||
let k = |x: f32, y: f32, dx: f32, dy: f32| CurveKey { point: [x, y], left: [x - dx, y - dy], right: [x + dx, y + dy] };
|
||||
let table = curve_table(&[k(0.25, 0.25, 0.1, 0.1), k(0.75, 0.75, 0.1, 0.1)]);
|
||||
assert!((table_lookup(&table, 0.5) - 0.5).abs() < 1e-3);
|
||||
assert_eq!(table_lookup(&table, 0.1), 0.25);
|
||||
assert_eq!(table_lookup(&table, 0.9), 0.75);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_bend_the_curve_as_a_cubic() {
|
||||
// (0,0) to (1,1) with handles (0,1) and (1,0): at t = 1/2 the point is (0.5, 0.5), at t = 1/4 x = 0.15625, y = 0.4375
|
||||
let a = CurveKey { point: [0.0, 0.0], left: [0.0, 0.0], right: [0.0, 1.0] };
|
||||
let b = CurveKey { point: [1.0, 1.0], left: [1.0, 0.0], right: [1.0, 1.0] };
|
||||
let table = curve_table(&[a, b]);
|
||||
assert!((table_lookup(&table, 0.5) - 0.5).abs() < 1e-3);
|
||||
assert!((table_lookup(&table, 0.15625) - 0.4375).abs() < 2e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ramp_draws_the_curve_from_left_to_right_and_ignores_the_input() {
|
||||
let g = "size 64\nnode 1 color r=0 g=0 b=0\nnode 2 curve_keys in=@1 ramp=1 n=2 x0=0 y0=1 lx0=0 ly0=1 rx0=0.25 ry0=0.75 x1=1 y1=0 lx1=0.75 ly1=0.25 rx1=1 ry1=0\noutput o 2\n";
|
||||
let t = &Graph::parse(g).unwrap_or_else(|e| panic!("{e}")).evaluate(Some(64)).unwrap()["o"];
|
||||
assert!(t.px[10 * 64 + 1][0] > 0.9 && t.px[10 * 64 + 62][0] < 0.1, "{:?}", t.px[10 * 64 + 1]);
|
||||
assert_eq!(t.px[3 * 64 + 40], t.px[60 * 64 + 40]);
|
||||
}
|
||||
|
||||
fn eval(body: &str) -> Tex {
|
||||
Graph::parse(&format!("size 64\n{body}")).unwrap_or_else(|e| panic!("{e}")).evaluate(Some(64)).unwrap()["o"].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distance_falls_off_linearly_and_wraps() {
|
||||
// a white column at the left edge of a texture; reach 16/256 of 64 = 4 pixels
|
||||
let field = NearestField::new(64, 64, |x, _| x == 0, 1.0, 1.0, [true, true]);
|
||||
assert_eq!(field.at(3, 5), Some((9.0, 0, 5)));
|
||||
// across the wrap: pixel 62 is 2 from pixel 0
|
||||
assert_eq!(field.at(62, 5), Some((4.0, 0, 5)));
|
||||
// everything is mask here, so everything is at distance 0
|
||||
let t = eval("node 1 color r=1 g=1 b=1\nnode 2 distance_map in=@1 distance=16\noutput o 2\n");
|
||||
assert_eq!(t.px[9][0], 1.0);
|
||||
// an empty mask has nothing near it
|
||||
let t = eval("node 1 color r=0 g=0 b=0\nnode 2 distance_map in=@1 distance=16\noutput o 2\n");
|
||||
assert_eq!(t.px[9][0], 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distance_does_not_cross_an_edge_that_does_not_repeat() {
|
||||
let field = NearestField::new(64, 64, |x, y| x == 0 && y == 0, 1.0, 1.0, [false, false]);
|
||||
assert_eq!(field.at(62, 0), Some((62.0 * 62.0, 0, 0)));
|
||||
assert_eq!(field.at(0, 62), Some((62.0 * 62.0, 0, 0)));
|
||||
let wrapped = NearestField::new(64, 64, |x, y| x == 0 && y == 0, 1.0, 1.0, [true, false]);
|
||||
assert_eq!(wrapped.at(62, 0), Some((4.0, 0, 0)));
|
||||
assert_eq!(wrapped.at(0, 62), Some((62.0 * 62.0, 0, 0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distance_weighs_the_axes_by_the_aspect() {
|
||||
let field = NearestField::new(32, 32, |x, y| x == 0 && y == 0, 0.5, 2.0, [true, true]);
|
||||
// 2 pixels along x weigh 4, 8 along y weigh 4
|
||||
assert_eq!(field.at(2, 8), Some((32.0, 0, 0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distance_down_a_non_square_node_is_in_the_units_across() {
|
||||
// a white row at the top of a 64 x 16 node; reach 64/256 of the width across is 16 pixels, a quarter of the height
|
||||
// down, so 2 rows below the line (an eighth of the height) is half way
|
||||
let g = "size 64\nsubgraph top\nmeta kind \"function\"\nnode 2 f_pos\nnode 3 f_swizzle a=@2 mask=\"y\"\nnode 4 f_float v=0.05\nnode 5 f_lt a=@3 b=@4\nnode 1 f_out in=@5\nend\nnode 1 pixel_processor fn=\"top\" osize_log2_x=6 osize_log2_y=4\nnode 2 distance_map in=@1 distance=64 tile_y=0 osize_log2_x=6 osize_log2_y=4\noutput o 2\n";
|
||||
let t = &Graph::parse(g).unwrap_or_else(|e| panic!("{e}")).evaluate(Some(64)).unwrap()["o"];
|
||||
assert_eq!((t.w, t.h), (64, 16));
|
||||
assert!((t.px[2 * 64 + 10][0] - 0.5).abs() < 1e-5, "{:?}", t.px[2 * 64 + 10]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distance_gives_the_nearest_source_within_reach_only() {
|
||||
let g = "node 1 color r=1 g=1 b=1\nnode 2 color r=0.25 g=0.5 b=0.75\nnode 3 distance_map in=@1 source=@2 distance=4\noutput o 3\n";
|
||||
let t = eval(g);
|
||||
assert_eq!(t.px[10], [0.25, 0.5, 0.75, 1.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_points_away_from_a_slope_and_flat_is_up() {
|
||||
// a uv ramp along x rises 1/64 per pixel; intensity 64 at width 64 gives k = 16, nx = -16/64 = -0.25 before normalizing
|
||||
let ramp = "subgraph c\nmeta kind \"function\"\nnode 2 f_pos\nnode 3 f_swizzle a=@2 mask=\"x\"\nnode 1 f_out in=@3\nend\nnode 1 pixel_processor fn=\"c\"\n";
|
||||
let t = eval(&format!("{ramp}node 2 normal_map in=@1 intensity=64\noutput o 2\n"));
|
||||
let n = t.px[5 * 64 + 20];
|
||||
let expect = -0.25 / (1.0f32 + 0.0625).sqrt() * 0.5 + 0.5;
|
||||
assert!((n[0] - expect).abs() < 1e-3, "{n:?}");
|
||||
assert!((n[1] - 0.5).abs() < 1e-5);
|
||||
let flat = eval("node 1 color r=0.7 g=0.7 b=0.7\nnode 2 normal_map in=@1 intensity=64 alpha=1\noutput o 2\n");
|
||||
assert_eq!(flat.px[3], [0.5, 0.5, 1.0, 0.7]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_normal_down_a_non_square_node_is_the_square_one() {
|
||||
// a uv ramp along y on a 64 x 16 node steps 1/16 per pixel, four times the square node's 1/64, and gives the same normal
|
||||
let ramp = "subgraph c\nmeta kind \"function\"\nnode 2 f_pos\nnode 3 f_swizzle a=@2 mask=\"y\"\nnode 1 f_out in=@3\nend\nnode 1 pixel_processor fn=\"c\"";
|
||||
let at = |size: &str, w: usize| eval(&format!("{ramp} {size}\nnode 2 normal_map in=@1 intensity=64 {size}\noutput o 2\n")).px[5 * w + 20];
|
||||
let (square, wide) = (at("", 64), at("osize_log2_x=6 osize_log2_y=4", 64));
|
||||
assert!((square[1] - wide[1]).abs() < 1e-4, "{square:?} {wide:?}");
|
||||
assert!((square[1] - 0.5).abs() > 0.05);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emboss_adds_the_slope_along_the_angle() {
|
||||
let ramp = "subgraph c\nmeta kind \"function\"\nnode 2 f_pos\nnode 3 f_swizzle a=@2 mask=\"y\"\nnode 1 f_out in=@3\nend\nnode 1 pixel_processor fn=\"c\"\nnode 2 color r=0.5 g=0.5 b=0.5\n";
|
||||
// along y, slope 1/64 per pixel, gain 16 * 64/256 = 4: adds 1/16
|
||||
let t = eval(&format!("{ramp}node 3 emboss_map in=@2 map=@1 intensity=16 angle=0.25\noutput o 3\n"));
|
||||
assert!((t.px[20 * 64 + 5][0] - 0.5625).abs() < 1e-3, "{:?}", t.px[20 * 64 + 5]);
|
||||
// along x the ramp has no slope
|
||||
let t = eval(&format!("{ramp}node 3 emboss_map in=@2 map=@1 intensity=16\noutput o 3\n"));
|
||||
assert!((t.px[20 * 64 + 5][0] - 0.5).abs() < 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_dynamic_maps_the_input_to_the_last_texel_at_one() {
|
||||
let ramp = "subgraph c\nmeta kind \"function\"\nnode 2 f_pos\nnode 3 f_swizzle a=@2 mask=\"x\"\nnode 1 f_out in=@3\nend\nnode 1 pixel_processor fn=\"c\"\nnode 2 color r=1 g=1 b=1\n";
|
||||
let t = eval(&format!("{ramp}node 3 gradient_dynamic in=@2 grad=@1\noutput o 3\n"));
|
||||
assert!((t.px[100][0] - 63.5 / 64.0).abs() < 1e-4, "{:?}", t.px[100]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_cover_their_triangles_and_no_more() {
|
||||
// a strip over the left half (with a zero-area triangle joining a second triangle at the far corner)
|
||||
let g = "node 1 triangle_strips strips=\"0000000000007fffffff0000ffff7fff\"\noutput o 1\n";
|
||||
let t = eval(g);
|
||||
assert_eq!(t.px[10 * 64 + 10][0], 1.0);
|
||||
assert_eq!(t.px[10 * 64 + 50][0], 0.0);
|
||||
// the exact edge at x = 0.5 falls between pixels
|
||||
assert_eq!(t.px[10 * 64 + 31][0], 1.0);
|
||||
let thin = strips_coverage(&[vec![[0.0, 0.0], [1.0, 1.0], [1.0, 1.0]]], 8, 8);
|
||||
assert!(thin.iter().all(|v| *v == 0.0), "a triangle without area draws nothing");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! What one evaluation runs with, chosen by its host: when to stop ([`Cancel`]), what to print ([`Logging`]), who
|
||||
//! measures it ([`crate::profile::Profiler`]) and where its memory is counted ([`LiveBytes`]). Nothing here changes what
|
||||
//! is computed.
|
||||
//!
|
||||
//! The evaluation entry points (`Graph::evaluate_in` and the others taking an [`EvalContext`]) carry the context
|
||||
//! through the evaluation. The node code below them (the image operations and their parallel loops) does not take it
|
||||
//! as an argument: the entry points make it the *current* context of the evaluating thread for the duration of the
|
||||
//! call ([`scoped`]), and the parallel helpers in [`crate::tex`] and [`crate::par`] hand it on to the threads they
|
||||
//! use. So two evaluations on different threads never see each other's context, and nothing is shared process-wide.
|
||||
//!
|
||||
//! Cancelling is a flag the host sets ([`Cancel::cancel`]); the engine never reads a clock to decide it. A host with a
|
||||
//! time limit sets the flag from a timer of its own.
|
||||
//!
|
||||
//! Files a graph names but does not carry (a bitmap, a font, an SVG) are read through the host's [`FileSource`]
|
||||
//! ([`EvalContext::files`]); evaluation never opens a file itself.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed};
|
||||
|
||||
/// A flag the host sets to stop an evaluation. Clones share the flag. An evaluation that sees it stops at the next
|
||||
/// node or the next few rows of a parallel loop, and returns `Error::Cancelled` (its partial results must be thrown
|
||||
/// away).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Cancel(Arc<AtomicBool>);
|
||||
|
||||
impl Cancel {
|
||||
/// A flag not set yet.
|
||||
pub fn new() -> Cancel {
|
||||
Cancel::default()
|
||||
}
|
||||
|
||||
/// Asks every evaluation holding this flag to stop.
|
||||
pub fn cancel(&self) {
|
||||
self.0.store(true, Relaxed);
|
||||
}
|
||||
|
||||
pub fn is_cancelled(&self) -> bool {
|
||||
self.0.load(Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Diagnostics an evaluation prints to stderr. They never change what is computed.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Logging {
|
||||
/// One line per evaluation: node count, its own peak and what the evaluations sharing its [`LiveBytes`] hold.
|
||||
pub memory: bool,
|
||||
/// One line per node computed, with its time (read from the system clock; on the web, without the time).
|
||||
pub node_times: bool,
|
||||
}
|
||||
|
||||
/// Bytes of node results held now and the most held at once, by every evaluation given this counter. Clones share
|
||||
/// the counts: a host that wants one figure for all its evaluations gives them all the same counter.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct LiveBytes(Arc<(AtomicUsize, AtomicUsize)>);
|
||||
|
||||
impl LiveBytes {
|
||||
pub fn new() -> LiveBytes {
|
||||
LiveBytes::default()
|
||||
}
|
||||
|
||||
/// (held now, most held at once).
|
||||
pub fn get(&self) -> (usize, usize) {
|
||||
(self.0.0.load(Relaxed), self.0.1.load(Relaxed))
|
||||
}
|
||||
|
||||
pub(crate) fn add(&self, b: usize) {
|
||||
let now = self.0.0.fetch_add(b, Relaxed) + b;
|
||||
self.0.1.fetch_max(now, Relaxed);
|
||||
}
|
||||
|
||||
pub(crate) fn sub(&self, b: usize) {
|
||||
// a compare-exchange loop: `fetch_update` is deprecated on newer toolchains and `try_update` is not on older ones
|
||||
let mut now = self.0.0.load(Relaxed);
|
||||
while let Err(seen) = self.0.0.compare_exchange_weak(now, now.saturating_sub(b), Relaxed, Relaxed) {
|
||||
now = seen;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where an evaluation reads the files a graph names but does not carry in its resources. Paths are as the graph
|
||||
/// writes them (graphs written on Windows use backslashes).
|
||||
pub trait FileSource: Send + Sync {
|
||||
/// The bytes of the file, or why there are none (shown in the node's error).
|
||||
fn read(&self, path: &str) -> Result<Vec<u8>, String>;
|
||||
/// Something that changes when the file does (on disk: its length and modification time), for caches that keep
|
||||
/// results between evaluations; `None` when there is no such file.
|
||||
fn stamp(&self, path: &str) -> Option<(u64, u64)>;
|
||||
}
|
||||
|
||||
/// No files at all: every read fails.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct NoFiles;
|
||||
|
||||
impl FileSource for NoFiles {
|
||||
fn read(&self, path: &str) -> Result<Vec<u8>, String> {
|
||||
Err(format!("no file system to read '{path}' from"))
|
||||
}
|
||||
|
||||
fn stamp(&self, _path: &str) -> Option<(u64, u64)> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The file system of the machine, for native hosts: a path with backslashes that isn't found is tried again with
|
||||
/// slashes.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct DiskFiles;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl FileSource for DiskFiles {
|
||||
fn read(&self, path: &str) -> Result<Vec<u8>, String> {
|
||||
std::fs::read(path).or_else(|e| if path.contains('\\') { std::fs::read(path.replace('\\', "/")) } else { Err(e) }).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn stamp(&self, path: &str) -> Option<(u64, u64)> {
|
||||
let m = std::fs::metadata(path).or_else(|_| std::fs::metadata(path.replace('\\', "/"))).ok()?;
|
||||
let modified = m.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_nanos() as u64).unwrap_or(0);
|
||||
Some((m.len(), modified))
|
||||
}
|
||||
}
|
||||
|
||||
/// The files an evaluation reads ([`FileSource`]). The default is the machine's file system ([`DiskFiles`]) on native
|
||||
/// targets and no files ([`NoFiles`]) on the web.
|
||||
#[derive(Clone)]
|
||||
pub struct Files(pub Arc<dyn FileSource>);
|
||||
|
||||
impl Files {
|
||||
/// No files: every read fails.
|
||||
pub fn none() -> Files {
|
||||
Files(Arc::new(NoFiles))
|
||||
}
|
||||
|
||||
/// The machine's file system.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub fn disk() -> Files {
|
||||
Files(Arc::new(DiskFiles))
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Files {
|
||||
fn default() -> Files {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
return Files::disk();
|
||||
#[cfg(target_family = "wasm")]
|
||||
return Files::none();
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for Files {
|
||||
type Target = dyn FileSource;
|
||||
fn deref(&self) -> &(dyn FileSource + 'static) {
|
||||
&*self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything an evaluation takes from its host besides the graph. The default runs to the end, prints nothing,
|
||||
/// measures nothing and counts its memory on its own.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct EvalContext {
|
||||
pub cancel: Cancel,
|
||||
pub logging: Logging,
|
||||
/// Measures named spans around nodes and stages; `None` measures nothing.
|
||||
pub profiler: Option<Arc<dyn crate::profile::Profiler>>,
|
||||
pub accelerator: Option<Arc<dyn crate::accelerator::Accelerator>>,
|
||||
pub live: LiveBytes,
|
||||
/// The threads the evaluation's parallel loops run on; `None`: the pool the caller is in (rayon's global pool
|
||||
/// outside any). A host whose own parallel work waits on evaluations gives them a pool of their own, so that its
|
||||
/// waiting threads can never be the ones an evaluation needs.
|
||||
pub pool: Option<Arc<rayon::ThreadPool>>,
|
||||
/// Where files the graph names but does not carry are read from.
|
||||
pub files: Files,
|
||||
/// Counts the graph's own nodes as they finish (not those inside subgraphs), for a host showing a render's progress
|
||||
/// against [`crate::Graph::work_nodes`]; `None` counts nothing. Nothing computed depends on it.
|
||||
pub nodes_done: Option<Arc<std::sync::atomic::AtomicUsize>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for EvalContext {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("EvalContext")
|
||||
.field("cancel", &self.cancel)
|
||||
.field("logging", &self.logging)
|
||||
.field("profiler", &self.profiler.is_some())
|
||||
.field("accelerator", &self.accelerator.is_some())
|
||||
.field("live", &self.live)
|
||||
.field("pool", &self.pool.as_ref().map(|p| p.current_num_threads()))
|
||||
.field("files", &"..")
|
||||
.field("nodes_done", &self.nodes_done)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl EvalContext {
|
||||
/// The default context with `cancel` as its flag.
|
||||
pub fn with_cancel(cancel: Cancel) -> EvalContext {
|
||||
EvalContext { cancel, ..EvalContext::default() }
|
||||
}
|
||||
|
||||
pub fn is_cancelled(&self) -> bool {
|
||||
self.cancel.is_cancelled()
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static CURRENT: RefCell<Option<EvalContext>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Runs `f` with `ec` as this thread's current context, and puts the previous one back afterwards (also when `f`
|
||||
/// panics). The engine's entry points do this themselves; a host calls it to run its own work on the engine's
|
||||
/// parallel helpers under a context (so that the work stops when the context is cancelled).
|
||||
pub fn scoped<R>(ec: &EvalContext, f: impl FnOnce() -> R) -> R {
|
||||
struct Restore(Option<EvalContext>);
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
let previous = self.0.take();
|
||||
CURRENT.with(|c| *c.borrow_mut() = previous);
|
||||
}
|
||||
}
|
||||
let _restore = Restore(CURRENT.with(|c| c.replace(Some(ec.clone()))));
|
||||
f()
|
||||
}
|
||||
|
||||
/// A pool of its own for evaluations ([`EvalContext::pool`]), as many threads as rayon's default, named `name-N`.
|
||||
/// `None` when the system gives no threads.
|
||||
pub fn own_pool(name: &str) -> Option<Arc<rayon::ThreadPool>> {
|
||||
let name = name.to_string();
|
||||
rayon::ThreadPoolBuilder::new().thread_name(move |i| format!("{name}-{i}")).build().ok().map(Arc::new)
|
||||
}
|
||||
|
||||
/// Runs `f` under `ec` when there is one, as it is otherwise: how the parallel helpers hand the caller's context to
|
||||
/// their threads.
|
||||
pub(crate) fn scoped_opt<R>(ec: Option<&EvalContext>, f: impl FnOnce() -> R) -> R {
|
||||
match ec {
|
||||
Some(ec) => scoped(ec, f),
|
||||
None => f(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `f` on the pool of `ec` when it names one, else where it is called.
|
||||
pub(crate) fn in_pool<R: Send>(ec: Option<&EvalContext>, f: impl FnOnce() -> R + Send) -> R {
|
||||
match ec.and_then(|ec| ec.pool.as_ref()) {
|
||||
Some(pool) => pool.install(f),
|
||||
None => f(),
|
||||
}
|
||||
}
|
||||
|
||||
/// This thread's current context, if an evaluation (or [`scoped`]) set one.
|
||||
pub fn current() -> Option<EvalContext> {
|
||||
CURRENT.with(|c| c.borrow().clone())
|
||||
}
|
||||
|
||||
/// Calls `f` with this thread's current context, without cloning it.
|
||||
pub(crate) fn with_current<R>(f: impl FnOnce(Option<&EvalContext>) -> R) -> R {
|
||||
CURRENT.with(|c| f(c.borrow().as_ref()))
|
||||
}
|
||||
|
||||
/// The flag of this thread's current context, for a parallel loop to check on its threads.
|
||||
pub(crate) fn current_cancel() -> Option<Cancel> {
|
||||
with_current(|ec| ec.map(|ec| ec.cancel.clone()))
|
||||
}
|
||||
|
||||
/// True when `cancel` (a flag from [`current_cancel`]) is set.
|
||||
#[inline]
|
||||
pub(crate) fn is_set(cancel: &Option<Cancel>) -> bool {
|
||||
cancel.as_ref().is_some_and(Cancel::is_cancelled)
|
||||
}
|
||||
|
||||
/// True when this thread's current context has been cancelled.
|
||||
pub fn cancelled() -> bool {
|
||||
with_current(|ec| ec.is_some_and(EvalContext::is_cancelled))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn scoped_contexts_nest_and_are_put_back() {
|
||||
assert!(current().is_none());
|
||||
let outer = EvalContext::default();
|
||||
let inner = EvalContext::with_cancel(Cancel::new());
|
||||
inner.cancel.cancel();
|
||||
scoped(&outer, || {
|
||||
assert!(!cancelled());
|
||||
scoped(&inner, || assert!(cancelled()));
|
||||
assert!(!cancelled());
|
||||
});
|
||||
assert!(current().is_none());
|
||||
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| scoped(&inner, || panic!("unwinds"))));
|
||||
assert!(current().is_none(), "a panic must not leave the context behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_bytes_are_shared_by_clones_and_keep_their_peak() {
|
||||
let a = LiveBytes::new();
|
||||
let b = a.clone();
|
||||
a.add(100);
|
||||
b.add(50);
|
||||
a.sub(120);
|
||||
assert_eq!(b.get(), (30, 150));
|
||||
a.sub(1000);
|
||||
assert_eq!(a.get().0, 0, "never below zero");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Tone curves: a list of control points joined by smooth cubic segments, baked into a lookup table.
|
||||
//!
|
||||
//! Text form (used by the `curve` node): `x:y` points separated by commas, e.g. `0:0,0.5:0.7,1:1`.
|
||||
//! A point may carry a slope (`x:y:s`, the same slope on both sides) or two (`x:y:sin:sout`).
|
||||
//! Points without a slope get a smooth, overshoot-free slope from their neighbours.
|
||||
|
||||
use crate::tex::Tex;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Curve {
|
||||
/// (x, y, slope in, slope out), sorted by x
|
||||
pub pts: Vec<(f32, f32, f32, f32)>,
|
||||
}
|
||||
|
||||
pub const LUT: usize = 1024;
|
||||
|
||||
impl Curve {
|
||||
pub fn identity() -> Curve {
|
||||
Curve::new(vec![(0.0, 0.0, None, None), (1.0, 1.0, None, None)])
|
||||
}
|
||||
|
||||
/// Points with optional explicit slopes; computes the automatic ones.
|
||||
pub fn new(mut raw: Vec<(f32, f32, Option<f32>, Option<f32>)>) -> Curve {
|
||||
raw.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
|
||||
raw.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6);
|
||||
if raw.is_empty() {
|
||||
return Curve::identity();
|
||||
}
|
||||
if let [p] = raw.as_slice() {
|
||||
let y = p.1;
|
||||
raw = vec![(0.0, y, None, None), (1.0, y, None, None)];
|
||||
}
|
||||
let n = raw.len();
|
||||
// secant slopes and Fritsch-Carlson monotone tangents
|
||||
let sec: Vec<f32> = raw
|
||||
.windows(2)
|
||||
.map(|w| match w {
|
||||
[a, b] => (b.1 - a.1) / (b.0 - a.0),
|
||||
_ => 0.0,
|
||||
})
|
||||
.collect();
|
||||
let mut auto = vec![0.0f32; n];
|
||||
if let (Some(a), Some(&s)) = (auto.first_mut(), sec.first()) {
|
||||
*a = s;
|
||||
}
|
||||
if let (Some(a), Some(&s)) = (auto.last_mut(), sec.last()) {
|
||||
*a = s;
|
||||
}
|
||||
for (a, w) in auto.iter_mut().skip(1).zip(sec.windows(2)) {
|
||||
if let [s0, s1] = *w {
|
||||
*a = if s0 * s1 <= 0.0 { 0.0 } else { (s0 + s1) * 0.5 };
|
||||
}
|
||||
}
|
||||
for (i, &si) in sec.iter().enumerate() {
|
||||
let (Some(&ai), Some(&ai1)) = (auto.get(i), auto.get(i + 1)) else { continue };
|
||||
let (ni, ni1) = if si == 0.0 {
|
||||
(0.0, 0.0)
|
||||
} else {
|
||||
let (a, b) = (ai / si, ai1 / si);
|
||||
let s = a * a + b * b;
|
||||
if s > 9.0 {
|
||||
let t = 3.0 / s.sqrt();
|
||||
(t * a * si, t * b * si)
|
||||
} else {
|
||||
(ai, ai1)
|
||||
}
|
||||
};
|
||||
if let Some(v) = auto.get_mut(i) {
|
||||
*v = ni;
|
||||
}
|
||||
if let Some(v) = auto.get_mut(i + 1) {
|
||||
*v = ni1;
|
||||
}
|
||||
}
|
||||
let pts = raw
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, p)| {
|
||||
let ai = auto.get(i).copied().unwrap_or(0.0);
|
||||
let s_in = p.2.unwrap_or(ai);
|
||||
let s_out = p.3.or(p.2).unwrap_or(ai);
|
||||
(p.0.clamp(0.0, 1.0), p.1.clamp(0.0, 1.0), s_in, s_out)
|
||||
})
|
||||
.collect();
|
||||
Curve { pts }
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Result<Curve, String> {
|
||||
let mut raw = Vec::new();
|
||||
for item in text.split(',').map(str::trim).filter(|s| !s.is_empty()) {
|
||||
let parts: Vec<&str> = item.split(':').collect();
|
||||
let num =
|
||||
|s: &str| s.trim().parse::<f32>().ok().filter(|v| v.is_finite()).ok_or_else(|| format!("bad number '{s}' in curve point '{item}'"));
|
||||
match *parts.as_slice() {
|
||||
[x, y] => raw.push((num(x)?, num(y)?, None, None)),
|
||||
[x, y, s] => raw.push((num(x)?, num(y)?, Some(num(s)?), None)),
|
||||
[x, y, si, so] => raw.push((num(x)?, num(y)?, Some(num(si)?), Some(num(so)?))),
|
||||
_ => return Err(format!("curve point '{item}' must look like x:y")),
|
||||
}
|
||||
}
|
||||
if raw.is_empty() {
|
||||
return Err("a curve needs at least one point".into());
|
||||
}
|
||||
Ok(Curve::new(raw))
|
||||
}
|
||||
|
||||
pub fn to_text(&self) -> String {
|
||||
self.pts.iter().map(|p| format!("{}:{}:{}:{}", p.0, p.1, p.2, p.3)).collect::<Vec<_>>().join(",")
|
||||
}
|
||||
|
||||
pub fn eval(&self, x: f32) -> f32 {
|
||||
let p = &self.pts;
|
||||
let (Some(&first), Some(&last)) = (p.first(), p.last()) else { return 0.0 };
|
||||
if x <= first.0 {
|
||||
return first.1;
|
||||
}
|
||||
if x >= last.0 {
|
||||
return last.1;
|
||||
}
|
||||
let i = p.partition_point(|q| q.0 <= x).saturating_sub(1);
|
||||
let (Some(&a), Some(&b)) = (p.get(i), p.get(i + 1)) else { return last.1 };
|
||||
let h = b.0 - a.0;
|
||||
let t = (x - a.0) / h;
|
||||
let (t2, t3) = (t * t, t * t * t);
|
||||
let y = (2.0 * t3 - 3.0 * t2 + 1.0) * a.1 + (t3 - 2.0 * t2 + t) * h * a.3 + (-2.0 * t3 + 3.0 * t2) * b.1 + (t3 - t2) * h * b.2;
|
||||
y.clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
pub fn lut(&self) -> Vec<f32> {
|
||||
(0..LUT).map(|i| self.eval(i as f32 / (LUT - 1) as f32)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn lookup(lut: &[f32], x: f32) -> f32 {
|
||||
let f = x.clamp(0.0, 1.0) * (LUT - 1) as f32;
|
||||
let i = (f as usize).min(LUT - 2);
|
||||
let t = f - i as f32;
|
||||
let (a, b) = (lut.get(i).copied().unwrap_or(0.0), lut.get(i + 1).copied().unwrap_or(0.0));
|
||||
a + (b - a) * t
|
||||
}
|
||||
|
||||
/// Apply the master curve to R, G and B, then the per-channel curves (r, g, b, a).
|
||||
pub fn apply(t: &Tex, master: &Curve, ch: [&Curve; 4]) -> Tex {
|
||||
let m = master.lut();
|
||||
let l: Vec<Vec<f32>> = ch.iter().map(|c| c.lut()).collect();
|
||||
let mut out = t.clone();
|
||||
let [l0, l1, l2, l3] = [0, 1, 2, 3].map(|k| l.get(k).map_or(&[] as &[f32], Vec::as_slice));
|
||||
for p in out.px.iter_mut() {
|
||||
p[0] = lookup(l0, lookup(&m, p[0]));
|
||||
p[1] = lookup(l1, lookup(&m, p[1]));
|
||||
p[2] = lookup(l2, lookup(&m, p[2]));
|
||||
p[3] = lookup(l3, p[3]);
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! LSB-first bit writer, the packing order DEFLATE uses.
|
||||
|
||||
pub(super) struct BitWriter {
|
||||
out: Vec<u8>,
|
||||
acc: u64,
|
||||
n: u32,
|
||||
}
|
||||
|
||||
impl BitWriter {
|
||||
pub fn with_capacity(cap: usize) -> Self {
|
||||
BitWriter { out: Vec::with_capacity(cap), acc: 0, n: 0 }
|
||||
}
|
||||
|
||||
/// Append the low `count` bits of `bits` (count <= 32).
|
||||
#[inline]
|
||||
pub fn put(&mut self, bits: u32, count: u32) {
|
||||
debug_assert!(count <= 32 && (count == 32 || bits >> count == 0));
|
||||
self.acc |= (bits as u64) << self.n;
|
||||
self.n += count;
|
||||
if self.n >= 32 {
|
||||
self.out.extend_from_slice(&(self.acc as u32).to_le_bytes());
|
||||
self.acc >>= 32;
|
||||
self.n -= 32;
|
||||
}
|
||||
}
|
||||
|
||||
/// Pad with zero bits up to the next byte boundary.
|
||||
pub fn align(&mut self) {
|
||||
while self.n > 0 {
|
||||
self.out.push(self.acc as u8);
|
||||
self.acc >>= 8;
|
||||
self.n = self.n.saturating_sub(8);
|
||||
}
|
||||
self.acc = 0;
|
||||
}
|
||||
|
||||
/// Append whole bytes; the writer must be byte-aligned.
|
||||
pub fn put_bytes(&mut self, bytes: &[u8]) {
|
||||
debug_assert_eq!(self.n, 0);
|
||||
self.out.extend_from_slice(bytes);
|
||||
}
|
||||
|
||||
pub fn finish(mut self) -> Vec<u8> {
|
||||
self.align();
|
||||
self.out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn packs_lsb_first() {
|
||||
let mut w = BitWriter::with_capacity(0);
|
||||
w.put(1, 1);
|
||||
w.put(0b10, 2);
|
||||
w.put(0x1ff, 9);
|
||||
w.put(0xdead_beef, 32);
|
||||
w.align();
|
||||
w.put_bytes(&[7]);
|
||||
w.put(1, 3);
|
||||
let out = w.finish();
|
||||
let mut expect: u64 = 1 | (0b10 << 1) | (0x1ff << 3) | (0xdead_beef << 12);
|
||||
let mut bytes = Vec::new();
|
||||
for _ in 0..6 {
|
||||
bytes.push(expect as u8);
|
||||
expect >>= 8;
|
||||
}
|
||||
bytes.extend_from_slice(&[7, 1]);
|
||||
assert_eq!(out, bytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
//! Block encoding: collects LZ77 tokens with their symbol statistics and writes each block in whichever of the
|
||||
//! three DEFLATE block types (stored, fixed Huffman, dynamic Huffman) is smallest.
|
||||
|
||||
use super::bits::BitWriter;
|
||||
use super::huffman::{canonical_codes, code_lengths};
|
||||
use super::tables::{
|
||||
CODE_LENGTH_ORDER, DIST_BASE, DIST_EXTRA, END_OF_BLOCK, LENGTH_BASE, LENGTH_EXTRA, dist_code, fixed_literal_lengths, length_code,
|
||||
};
|
||||
|
||||
/// A literal byte (`dist == 0`) or a back-reference of `len` bytes at distance `dist`.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Token {
|
||||
len_or_byte: u16,
|
||||
dist: u16,
|
||||
}
|
||||
|
||||
/// Number of literal/length and distance symbols the format defines (286 and 30, of which 286/287 never occur).
|
||||
const NUM_LIT: usize = 286;
|
||||
const NUM_DIST: usize = 30;
|
||||
const MAX_STORED: usize = 65535;
|
||||
|
||||
/// Tokens of the block being built, with their symbol frequencies.
|
||||
pub(super) struct Block {
|
||||
tokens: Vec<Token>,
|
||||
lit_freq: [u32; NUM_LIT],
|
||||
dist_freq: [u32; NUM_DIST],
|
||||
/// Uncompressed bytes the tokens cover.
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
impl Block {
|
||||
pub fn with_capacity(cap: usize) -> Self {
|
||||
Block { tokens: Vec::with_capacity(cap), lit_freq: [0; NUM_LIT], dist_freq: [0; NUM_DIST], bytes: 0 }
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.tokens.len()
|
||||
}
|
||||
|
||||
pub fn bytes(&self) -> usize {
|
||||
self.bytes
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn literal(&mut self, b: u8) {
|
||||
self.tokens.push(Token { len_or_byte: b as u16, dist: 0 });
|
||||
if let Some(f) = self.lit_freq.get_mut(b as usize) {
|
||||
*f += 1;
|
||||
}
|
||||
self.bytes += 1;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn copy(&mut self, len: usize, dist: usize) {
|
||||
self.tokens.push(Token { len_or_byte: len as u16, dist: dist as u16 });
|
||||
if let Some(f) = self.lit_freq.get_mut(257 + length_code(len)) {
|
||||
*f += 1;
|
||||
}
|
||||
if let Some(f) = self.dist_freq.get_mut(dist_code(dist)) {
|
||||
*f += 1;
|
||||
}
|
||||
self.bytes += len;
|
||||
}
|
||||
|
||||
/// Write the block; `raw` must be exactly the uncompressed bytes it covers. Clears the block afterwards.
|
||||
pub fn write(&mut self, w: &mut BitWriter, raw: &[u8], last: bool) {
|
||||
debug_assert_eq!(raw.len(), self.bytes);
|
||||
self.lit_freq[END_OF_BLOCK] = 1;
|
||||
let dynamic = DynamicHeader::new(&self.lit_freq, &self.dist_freq);
|
||||
let fixed_lit = fixed_literal_lengths();
|
||||
let fixed_dist = [5u8; NUM_DIST];
|
||||
let dynamic_bits = dynamic.cost() + self.data_cost(&dynamic.lit_lens, &dynamic.dist_lens);
|
||||
let fixed_bits = 3 + self.data_cost(&fixed_lit, &fixed_dist);
|
||||
// Header, alignment to a byte (worst case), LEN/NLEN, payload; repeated per 64 KiB chunk.
|
||||
let stored_bits = raw.len().div_ceil(MAX_STORED).max(1) as u64 * (3 + 7 + 32) + raw.len() as u64 * 8;
|
||||
|
||||
if stored_bits <= fixed_bits.min(dynamic_bits) {
|
||||
write_stored(w, raw, last);
|
||||
} else if fixed_bits <= dynamic_bits {
|
||||
w.put(last as u32, 1);
|
||||
w.put(1, 2);
|
||||
// All 288 lengths: canonical codes depend on the counts of the unused symbols 286 and 287 too.
|
||||
self.write_tokens(w, &fixed_lit, &fixed_dist);
|
||||
} else {
|
||||
w.put(last as u32, 1);
|
||||
w.put(2, 2);
|
||||
dynamic.write(w);
|
||||
self.write_tokens(w, &dynamic.lit_lens, &dynamic.dist_lens);
|
||||
}
|
||||
self.tokens.clear();
|
||||
self.lit_freq = [0; NUM_LIT];
|
||||
self.dist_freq = [0; NUM_DIST];
|
||||
self.bytes = 0;
|
||||
}
|
||||
|
||||
/// Bits for the block's symbols (with extra bits) under the given code lengths.
|
||||
fn data_cost(&self, lit_lens: &[u8], dist_lens: &[u8]) -> u64 {
|
||||
let mut bits = 0u64;
|
||||
for (s, (&f, &len)) in self.lit_freq.iter().zip(lit_lens).enumerate() {
|
||||
let extra = if s > END_OF_BLOCK { LENGTH_EXTRA.get(s - 257).copied().unwrap_or(0) as u64 } else { 0 };
|
||||
bits += f as u64 * (len as u64 + extra);
|
||||
}
|
||||
for ((&f, &len), &extra) in self.dist_freq.iter().zip(dist_lens).zip(&DIST_EXTRA) {
|
||||
bits += f as u64 * (len as u64 + extra as u64);
|
||||
}
|
||||
bits
|
||||
}
|
||||
|
||||
fn write_tokens(&self, w: &mut BitWriter, lit_lens: &[u8], dist_lens: &[u8]) {
|
||||
let lit_codes = canonical_codes(lit_lens);
|
||||
let dist_codes = canonical_codes(dist_lens);
|
||||
// (code, length) of a symbol; every symbol written has both (the tables cover the whole alphabet).
|
||||
let lit = |s: usize| (lit_codes.get(s).copied().unwrap_or(0) as u32, lit_lens.get(s).copied().unwrap_or(0) as u32);
|
||||
let dist_sym = |s: usize| (dist_codes.get(s).copied().unwrap_or(0) as u32, dist_lens.get(s).copied().unwrap_or(0) as u32);
|
||||
for t in &self.tokens {
|
||||
if t.dist == 0 {
|
||||
let (code, n) = lit(t.len_or_byte as usize);
|
||||
w.put(code, n);
|
||||
} else {
|
||||
let len = t.len_or_byte as usize;
|
||||
let lc = length_code(len);
|
||||
let (code, n) = lit(257 + lc);
|
||||
w.put(code, n);
|
||||
let (base, extra) = (LENGTH_BASE.get(lc).copied().unwrap_or(0), LENGTH_EXTRA.get(lc).copied().unwrap_or(0));
|
||||
w.put((len - base as usize) as u32, extra as u32);
|
||||
let dist = t.dist as usize;
|
||||
let dc = dist_code(dist);
|
||||
let (code, n) = dist_sym(dc);
|
||||
w.put(code, n);
|
||||
let (base, extra) = (DIST_BASE.get(dc).copied().unwrap_or(0), DIST_EXTRA.get(dc).copied().unwrap_or(0));
|
||||
w.put((dist - base as usize) as u32, extra as u32);
|
||||
}
|
||||
}
|
||||
let (code, n) = lit(END_OF_BLOCK);
|
||||
w.put(code, n);
|
||||
}
|
||||
}
|
||||
|
||||
/// Stored (uncompressed) block(s): one per 64 KiB of `raw`, at least one.
|
||||
pub(super) fn write_stored(w: &mut BitWriter, raw: &[u8], last: bool) {
|
||||
let mut chunks = raw.chunks(MAX_STORED).peekable();
|
||||
let empty: &[u8] = &[];
|
||||
if chunks.peek().is_none() {
|
||||
write_stored_chunk(w, empty, last);
|
||||
}
|
||||
while let Some(c) = chunks.next() {
|
||||
write_stored_chunk(w, c, last && chunks.peek().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
fn write_stored_chunk(w: &mut BitWriter, chunk: &[u8], last: bool) {
|
||||
w.put(last as u32, 1);
|
||||
w.put(0, 2);
|
||||
w.align();
|
||||
let len = chunk.len() as u16;
|
||||
w.put(len as u32 | ((!len as u32) << 16), 32);
|
||||
w.align();
|
||||
w.put_bytes(chunk);
|
||||
}
|
||||
|
||||
/// Code lengths of a dynamic block and their run-length-encoded transmission form.
|
||||
struct DynamicHeader {
|
||||
lit_lens: Vec<u8>,
|
||||
dist_lens: Vec<u8>,
|
||||
hlit: usize,
|
||||
hdist: usize,
|
||||
/// (code-length symbol 0..18, extra-bit value)
|
||||
rle: Vec<(u8, u8)>,
|
||||
cl_lens: Vec<u8>,
|
||||
hclen: usize,
|
||||
}
|
||||
|
||||
impl DynamicHeader {
|
||||
fn new(lit_freq: &[u32; NUM_LIT], dist_freq: &[u32; NUM_DIST]) -> Self {
|
||||
let lit_lens = code_lengths(lit_freq, 15);
|
||||
let dist_lens = code_lengths(dist_freq, 15);
|
||||
let hlit = 257 + lit_lens.iter().skip(257).rposition(|&l| l != 0).map_or(0, |p| p + 1);
|
||||
let hdist = 1 + dist_lens.iter().rposition(|&l| l != 0).unwrap_or(0);
|
||||
let mut all: Vec<u8> = lit_lens.iter().take(hlit).copied().collect();
|
||||
all.extend(dist_lens.iter().take(hdist));
|
||||
let rle = run_length_encode(&all);
|
||||
let mut cl_freq = [0u32; 19];
|
||||
for &(s, _) in &rle {
|
||||
if let Some(f) = cl_freq.get_mut(s as usize) {
|
||||
*f += 1;
|
||||
}
|
||||
}
|
||||
let cl_lens = code_lengths(&cl_freq, 7);
|
||||
let hclen = 4.max(1 + CODE_LENGTH_ORDER.iter().rposition(|&s| cl_lens.get(s).is_some_and(|&l| l != 0)).unwrap_or(0));
|
||||
DynamicHeader { lit_lens, dist_lens, hlit, hdist, rle, cl_lens, hclen }
|
||||
}
|
||||
|
||||
/// Header size in bits, including the 3-bit block header.
|
||||
fn cost(&self) -> u64 {
|
||||
let mut bits = 3 + 5 + 5 + 4 + 3 * self.hclen as u64;
|
||||
for &(s, _) in &self.rle {
|
||||
bits += self.cl_lens.get(s as usize).copied().unwrap_or(0) as u64 + rle_extra_bits(s) as u64;
|
||||
}
|
||||
bits
|
||||
}
|
||||
|
||||
fn write(&self, w: &mut BitWriter) {
|
||||
w.put((self.hlit - 257) as u32, 5);
|
||||
w.put((self.hdist - 1) as u32, 5);
|
||||
w.put((self.hclen - 4) as u32, 4);
|
||||
for &s in CODE_LENGTH_ORDER.iter().take(self.hclen) {
|
||||
w.put(self.cl_lens.get(s).copied().unwrap_or(0) as u32, 3);
|
||||
}
|
||||
let codes = canonical_codes(&self.cl_lens);
|
||||
for &(s, extra) in &self.rle {
|
||||
let i = s as usize;
|
||||
w.put(codes.get(i).copied().unwrap_or(0) as u32, self.cl_lens.get(i).copied().unwrap_or(0) as u32);
|
||||
w.put(extra as u32, rle_extra_bits(s));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn rle_extra_bits(sym: u8) -> u32 {
|
||||
match sym {
|
||||
16 => 2,
|
||||
17 => 3,
|
||||
18 => 7,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode a code-length sequence with the repeat symbols 16 (previous, 3-6), 17 (zeros, 3-10), 18 (zeros, 11-138).
|
||||
fn run_length_encode(lens: &[u8]) -> Vec<(u8, u8)> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while let Some(rest) = lens.get(i..)
|
||||
&& let Some(&v) = rest.first()
|
||||
{
|
||||
let run = rest.iter().take_while(|&&x| x == v).count();
|
||||
let mut left = run;
|
||||
if v == 0 {
|
||||
while left >= 11 {
|
||||
let n = left.min(138);
|
||||
out.push((18, (n - 11) as u8));
|
||||
left -= n;
|
||||
}
|
||||
if left >= 3 {
|
||||
out.push((17, (left - 3) as u8));
|
||||
left = 0;
|
||||
}
|
||||
} else {
|
||||
out.push((v, 0));
|
||||
left -= 1;
|
||||
while left >= 3 {
|
||||
let n = left.min(6);
|
||||
out.push((16, (n - 3) as u8));
|
||||
left -= n;
|
||||
}
|
||||
}
|
||||
out.extend(std::iter::repeat_n((v, 0), left));
|
||||
i += run;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn expand(rle: &[(u8, u8)]) -> Vec<u8> {
|
||||
let mut out: Vec<u8> = Vec::new();
|
||||
for &(s, e) in rle {
|
||||
match s {
|
||||
16 => {
|
||||
let p = *out.last().unwrap();
|
||||
out.extend(std::iter::repeat_n(p, 3 + e as usize));
|
||||
}
|
||||
17 => out.extend(std::iter::repeat_n(0, 3 + e as usize)),
|
||||
18 => out.extend(std::iter::repeat_n(0, 11 + e as usize)),
|
||||
v => out.push(v),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rle_round_trips() {
|
||||
let cases: Vec<Vec<u8>> = vec![
|
||||
vec![],
|
||||
vec![0; 2],
|
||||
vec![0; 3],
|
||||
vec![0; 11],
|
||||
vec![0; 150],
|
||||
vec![0; 300],
|
||||
vec![5; 1],
|
||||
vec![5; 4],
|
||||
vec![5; 7],
|
||||
vec![5; 20],
|
||||
vec![1, 2, 2, 2, 2, 0, 0, 0, 0, 3, 3],
|
||||
];
|
||||
for c in cases {
|
||||
assert_eq!(expand(&run_length_encode(&c)), c);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
//! Length-limited Huffman code construction and canonical code assignment.
|
||||
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::BinaryHeap;
|
||||
|
||||
/// Optimal-ish code lengths for `freq`, none longer than `limit`. Symbols with zero frequency get length 0.
|
||||
/// At least two symbols always get a code, so the result is a complete prefix code (which strict decoders such as
|
||||
/// zlib require); with fewer than two used symbols, unused ones are borrowed.
|
||||
pub(super) fn code_lengths(freq: &[u32], limit: u8) -> Vec<u8> {
|
||||
let n = freq.len();
|
||||
let mut lens = vec![0u8; n];
|
||||
let mut used: Vec<usize> = freq.iter().enumerate().filter(|&(_, &f)| f > 0).map(|(s, _)| s).collect();
|
||||
if used.len() < 2 {
|
||||
// Pad with the lowest unused symbols so the code is complete.
|
||||
for s in 0..n {
|
||||
if used.len() >= 2 {
|
||||
break;
|
||||
}
|
||||
if !used.contains(&s) {
|
||||
used.push(s);
|
||||
}
|
||||
}
|
||||
for &s in &used {
|
||||
if let Some(l) = lens.get_mut(s) {
|
||||
*l = 1;
|
||||
}
|
||||
}
|
||||
return lens;
|
||||
}
|
||||
|
||||
// Plain Huffman via a min-heap; nodes 0..used.len() are leaves.
|
||||
let leaves = used.len();
|
||||
let mut parent = vec![usize::MAX; 2 * leaves - 1];
|
||||
let mut heap: BinaryHeap<Reverse<(u64, usize)>> =
|
||||
used.iter().enumerate().map(|(i, &s)| Reverse((freq.get(s).copied().unwrap_or(0) as u64, i))).collect();
|
||||
let mut next = leaves;
|
||||
while heap.len() > 1 {
|
||||
let (Some(Reverse((fa, a))), Some(Reverse((fb, b)))) = (heap.pop(), heap.pop()) else {
|
||||
break;
|
||||
};
|
||||
for node in [a, b] {
|
||||
if let Some(p) = parent.get_mut(node) {
|
||||
*p = next;
|
||||
}
|
||||
}
|
||||
heap.push(Reverse((fa + fb, next)));
|
||||
next += 1;
|
||||
}
|
||||
let root = next - 1;
|
||||
let mut depth = vec![0u32; 2 * leaves - 1];
|
||||
for node in (0..root).rev() {
|
||||
let up = parent.get(node).and_then(|&p| depth.get(p)).copied().unwrap_or(0);
|
||||
if let Some(d) = depth.get_mut(node) {
|
||||
*d = up + 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Histogram of lengths, then push overlong codes down to `limit` while keeping the Kraft sum exact.
|
||||
let limit = limit as usize;
|
||||
let mut count = vec![0u32; limit + 1];
|
||||
for &d in depth.iter().take(leaves) {
|
||||
if let Some(c) = count.get_mut((d as usize).min(limit)) {
|
||||
*c += 1;
|
||||
}
|
||||
}
|
||||
let mut kraft: u64 = count.iter().enumerate().skip(1).map(|(l, &c)| (c as u64) << (limit - l)).sum();
|
||||
while kraft > 1u64 << limit {
|
||||
if let Some(c) = count.get_mut(limit) {
|
||||
*c -= 1;
|
||||
}
|
||||
for l in (1..limit).rev() {
|
||||
if let Some([c, next]) = count.get_mut(l..l + 2)
|
||||
&& *c > 0
|
||||
{
|
||||
*c -= 1;
|
||||
*next += 2;
|
||||
break;
|
||||
}
|
||||
}
|
||||
kraft -= 1;
|
||||
}
|
||||
|
||||
// Hand out lengths: the most frequent symbols get the shortest codes.
|
||||
used.sort_by_key(|&s| Reverse(freq.get(s).copied().unwrap_or(0)));
|
||||
let mut it = used.into_iter();
|
||||
for (l, &c) in count.iter().enumerate().skip(1) {
|
||||
for _ in 0..c {
|
||||
if let Some(len) = it.next().and_then(|s| lens.get_mut(s)) {
|
||||
*len = l as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
lens
|
||||
}
|
||||
|
||||
/// Canonical codes for `lens`, bit-reversed so they can be written LSB-first.
|
||||
pub(super) fn canonical_codes(lens: &[u8]) -> Vec<u16> {
|
||||
let mut count = [0u16; 16];
|
||||
for &l in lens {
|
||||
if let Some(c) = count.get_mut(l as usize) {
|
||||
*c += 1;
|
||||
}
|
||||
}
|
||||
count[0] = 0;
|
||||
let mut next = [0u16; 16];
|
||||
let mut code = 0u16;
|
||||
// next[bits] for bits 1..16 from count[bits - 1].
|
||||
for (n, &c) in next.iter_mut().skip(1).zip(&count) {
|
||||
code = (code + c) << 1;
|
||||
*n = code;
|
||||
}
|
||||
lens.iter()
|
||||
.map(|&l| {
|
||||
if l == 0 {
|
||||
return 0;
|
||||
}
|
||||
let Some(n) = next.get_mut(l as usize) else {
|
||||
return 0;
|
||||
};
|
||||
let c = *n;
|
||||
*n += 1;
|
||||
c.reverse_bits() >> (16 - l as u32)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn kraft(lens: &[u8], limit: u8) -> u64 {
|
||||
lens.iter().filter(|&&l| l > 0).map(|&l| 1u64 << (limit - l)).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn complete_and_limited() {
|
||||
// Fibonacci frequencies produce a maximally deep tree.
|
||||
let mut f = vec![1u32, 1];
|
||||
while f.len() < 30 {
|
||||
let k = f.len();
|
||||
f.push(f[k - 1] + f[k - 2]);
|
||||
}
|
||||
for limit in [7u8, 15] {
|
||||
let l = code_lengths(&f, limit);
|
||||
assert!(l.iter().all(|&x| x >= 1 && x <= limit));
|
||||
assert_eq!(kraft(&l, limit), 1 << limit);
|
||||
}
|
||||
assert_eq!(code_lengths(&[0, 0, 5, 0], 15), vec![1, 0, 1, 0]);
|
||||
assert_eq!(code_lengths(&[0, 0, 0], 15), vec![1, 1, 0]);
|
||||
assert_eq!(code_lengths(&[3, 3, 3, 3], 15), vec![2, 2, 2, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_matches_rfc_example() {
|
||||
// RFC 1951 3.2.2: lengths (3,3,3,3,3,2,4,4) -> 010 011 100 101 110 00 1110 1111.
|
||||
let codes = canonical_codes(&[3, 3, 3, 3, 3, 2, 4, 4]);
|
||||
let expect = [0b010u16, 0b011, 0b100, 0b101, 0b110, 0b00, 0b1110, 0b1111];
|
||||
let lens = [3u32, 3, 3, 3, 3, 2, 4, 4];
|
||||
for i in 0..8 {
|
||||
assert_eq!(codes[i], expect[i].reverse_bits() >> (16 - lens[i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
//! DEFLATE decompression (RFC 1951), the counterpart of [`super::compress`]. Used by PNG, ZIP and OpenEXR.
|
||||
|
||||
use super::tables::{CODE_LENGTH_ORDER, DIST_BASE as DBASE, DIST_EXTRA as DEXT, LENGTH_BASE as LBASE, LENGTH_EXTRA as LEXT};
|
||||
|
||||
struct BitR<'a> {
|
||||
d: &'a [u8],
|
||||
pos: usize,
|
||||
bit: u32,
|
||||
cnt: u32,
|
||||
}
|
||||
|
||||
impl<'a> BitR<'a> {
|
||||
fn bits(&mut self, n: u32) -> Result<u32, String> {
|
||||
while self.cnt < n {
|
||||
let b = *self.d.get(self.pos).ok_or_else(|| "unexpected end of compressed data".to_string())?;
|
||||
self.bit |= (b as u32) << self.cnt;
|
||||
self.pos += 1;
|
||||
self.cnt += 8;
|
||||
}
|
||||
let v = self.bit & ((1u32 << n) - 1);
|
||||
self.bit >>= n;
|
||||
self.cnt -= n;
|
||||
Ok(v)
|
||||
}
|
||||
}
|
||||
|
||||
struct Huff {
|
||||
count: [u16; 16],
|
||||
symbol: Vec<u16>,
|
||||
}
|
||||
|
||||
fn build(lengths: &[u8]) -> Huff {
|
||||
let mut count = [0u16; 16];
|
||||
for &l in lengths {
|
||||
if let Some(c) = count.get_mut(l as usize & 15) {
|
||||
*c += 1;
|
||||
}
|
||||
}
|
||||
// offs[i + 1] = offs[i] + count[i] for i in 1..15 (offs[0] = offs[1] = 0).
|
||||
let mut offs = [0u16; 16];
|
||||
let mut acc = 0u16;
|
||||
for (o, &c) in offs.iter_mut().skip(2).zip(count.iter().skip(1)) {
|
||||
acc += c;
|
||||
*o = acc;
|
||||
}
|
||||
let mut symbol = vec![0u16; lengths.len()];
|
||||
for (s, &l) in lengths.iter().enumerate() {
|
||||
if l != 0
|
||||
&& let Some(o) = offs.get_mut(l as usize & 15)
|
||||
{
|
||||
if let Some(slot) = symbol.get_mut(*o as usize) {
|
||||
*slot = s as u16;
|
||||
}
|
||||
*o += 1;
|
||||
}
|
||||
}
|
||||
Huff { count, symbol }
|
||||
}
|
||||
|
||||
fn decode_sym(br: &mut BitR, h: &Huff) -> Result<u16, String> {
|
||||
let (mut code, mut first, mut index) = (0i32, 0i32, 0i32);
|
||||
for &count in h.count.iter().skip(1) {
|
||||
code |= br.bits(1)? as i32;
|
||||
let count = count as i32;
|
||||
if code - count < first {
|
||||
return h.symbol.get((index + (code - first)) as usize).copied().ok_or_else(|| "bad huffman code".to_string());
|
||||
}
|
||||
index += count;
|
||||
first += count;
|
||||
first <<= 1;
|
||||
code <<= 1;
|
||||
}
|
||||
Err("bad huffman code".into())
|
||||
}
|
||||
|
||||
fn codes(br: &mut BitR, out: &mut Vec<u8>, lh: &Huff, dh: &Huff) -> Result<(), String> {
|
||||
loop {
|
||||
let sym = decode_sym(br, lh)? as usize;
|
||||
if sym < 256 {
|
||||
out.push(sym as u8);
|
||||
} else if sym == 256 {
|
||||
return Ok(());
|
||||
} else {
|
||||
let s = sym - 257;
|
||||
let (Some(&lbase), Some(&lext)) = (LBASE.get(s), LEXT.get(s)) else {
|
||||
return Err("bad length symbol".into());
|
||||
};
|
||||
let len = lbase as usize + br.bits(lext as u32)? as usize;
|
||||
let ds = decode_sym(br, dh)? as usize;
|
||||
let (Some(&dbase), Some(&dext)) = (DBASE.get(ds), DEXT.get(ds)) else {
|
||||
return Err("bad distance symbol".into());
|
||||
};
|
||||
let dist = dbase as usize + br.bits(dext as u32)? as usize;
|
||||
if dist > out.len() {
|
||||
return Err("distance too far back".into());
|
||||
}
|
||||
for _ in 0..len {
|
||||
// dist <= out.len() (checked above) and out only grows, so this is always in range.
|
||||
let b = *out.get(out.len() - dist).ok_or("distance too far back")?;
|
||||
out.push(b);
|
||||
}
|
||||
}
|
||||
if out.len() > (1 << 30) {
|
||||
return Err("decompressed data too large".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn inflate(data: &[u8]) -> Result<Vec<u8>, String> {
|
||||
let mut br = BitR { d: data, pos: 0, bit: 0, cnt: 0 };
|
||||
let mut out = Vec::new();
|
||||
loop {
|
||||
let last = br.bits(1)?;
|
||||
match br.bits(2)? {
|
||||
0 => {
|
||||
br.bit = 0;
|
||||
br.cnt = 0;
|
||||
let p = br.pos;
|
||||
let Some(&[l0, l1, n0, n1]) = data.get(p..p.saturating_add(4)) else {
|
||||
return Err("truncated stored block".into());
|
||||
};
|
||||
let len = u16::from_le_bytes([l0, l1]) as usize;
|
||||
let nlen = u16::from_le_bytes([n0, n1]) as usize;
|
||||
// p + 4 cannot overflow: the four bytes above exist.
|
||||
let end = (p + 4).checked_add(len).ok_or("bad stored block")?;
|
||||
let stored = data.get(p + 4..end).filter(|_| len == (!nlen & 0xffff)).ok_or("bad stored block")?;
|
||||
out.extend_from_slice(stored);
|
||||
br.pos = end;
|
||||
}
|
||||
1 => {
|
||||
let mut l = [0u8; 288];
|
||||
for (i, v) in l.iter_mut().enumerate() {
|
||||
*v = if i < 144 {
|
||||
8
|
||||
} else if i < 256 {
|
||||
9
|
||||
} else if i < 280 {
|
||||
7
|
||||
} else {
|
||||
8
|
||||
};
|
||||
}
|
||||
codes(&mut br, &mut out, &build(&l), &build(&[5u8; 30]))?;
|
||||
}
|
||||
2 => {
|
||||
let nlen = br.bits(5)? as usize + 257;
|
||||
let ndist = br.bits(5)? as usize + 1;
|
||||
let ncode = br.bits(4)? as usize + 4;
|
||||
if nlen > 286 || ndist > 30 {
|
||||
return Err("bad dynamic header".into());
|
||||
}
|
||||
let mut lengths = [0u8; 320];
|
||||
for &o in CODE_LENGTH_ORDER.iter().take(ncode) {
|
||||
let v = br.bits(3)? as u8;
|
||||
if let Some(l) = lengths.get_mut(o) {
|
||||
*l = v;
|
||||
}
|
||||
}
|
||||
let lc = build(&lengths[..19]);
|
||||
let mut idx = 0;
|
||||
let total = nlen + ndist;
|
||||
let mut ll = [0u8; 320];
|
||||
while idx < total {
|
||||
let sym = decode_sym(&mut br, &lc)?;
|
||||
if sym < 16 {
|
||||
*ll.get_mut(idx).ok_or("too many lengths")? = sym as u8;
|
||||
idx += 1;
|
||||
} else {
|
||||
let (prev, rep) = match sym {
|
||||
16 => {
|
||||
let Some(&prev) = idx.checked_sub(1).and_then(|i| ll.get(i)) else {
|
||||
return Err("bad repeat".into());
|
||||
};
|
||||
(prev, 3 + br.bits(2)? as usize)
|
||||
}
|
||||
17 => (0, 3 + br.bits(3)? as usize),
|
||||
_ => (0, 11 + br.bits(7)? as usize),
|
||||
};
|
||||
if idx + rep > total {
|
||||
return Err("too many lengths".into());
|
||||
}
|
||||
ll.get_mut(idx..idx + rep).ok_or("too many lengths")?.fill(prev);
|
||||
idx += rep;
|
||||
}
|
||||
}
|
||||
let (Some(lit), Some(dist)) = (ll.get(..nlen), ll.get(nlen..total)) else {
|
||||
return Err("bad dynamic header".into());
|
||||
};
|
||||
codes(&mut br, &mut out, &build(lit), &build(dist))?;
|
||||
}
|
||||
_ => return Err("bad block type".into()),
|
||||
}
|
||||
if last == 1 {
|
||||
return Ok(out);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
//! LZ77 match finding with hash chains over the 32 KiB window, and the greedy/lazy parse built on it.
|
||||
|
||||
use super::tables::{MAX_MATCH, MIN_MATCH, WINDOW};
|
||||
|
||||
const HASH_BITS: u32 = 15;
|
||||
const HASH_SIZE: usize = 1 << HASH_BITS;
|
||||
const WINDOW_MASK: usize = WINDOW - 1;
|
||||
/// Length-3 matches further back than this cost more than three literals.
|
||||
const TOO_FAR: usize = 4096;
|
||||
|
||||
/// Search effort knobs (the same ones zlib tunes per level).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) struct Params {
|
||||
/// Maximum hash-chain links followed per search.
|
||||
pub max_chain: usize,
|
||||
/// Stop searching once a match this long is found.
|
||||
pub nice_len: usize,
|
||||
/// Lazy parse only: when the pending match is at least this long, search a quarter of the chain.
|
||||
pub good_len: usize,
|
||||
/// Lazy parse: matches at least this long are taken without looking one byte ahead. 0 = greedy parse.
|
||||
pub max_lazy: usize,
|
||||
/// Greedy parse: positions inside matches longer than this are not added to the hash chains (speed).
|
||||
pub max_insert: usize,
|
||||
}
|
||||
|
||||
/// Receives the parse.
|
||||
pub(super) trait TokenSink {
|
||||
fn literal(&mut self, byte: u8);
|
||||
fn copy(&mut self, len: usize, dist: usize);
|
||||
}
|
||||
|
||||
/// Hash chains: `head[h]` is the newest position with hash h, `prev[p % WINDOW]` the previous one with the same hash.
|
||||
/// Positions are stored plus one so that 0 means "none".
|
||||
struct Chains {
|
||||
head: Vec<usize>,
|
||||
prev: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Chains {
|
||||
fn new() -> Self {
|
||||
Chains { head: vec![0; HASH_SIZE], prev: vec![0; WINDOW] }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn hash(data: &[u8], pos: usize) -> usize {
|
||||
let Some(&[a, b, c]) = data.get(pos..pos.saturating_add(3)) else {
|
||||
return 0;
|
||||
};
|
||||
let v = (a as u32) | (b as u32) << 8 | (c as u32) << 16;
|
||||
(v.wrapping_mul(0x9e37_79b1) >> (32 - HASH_BITS)) as usize
|
||||
}
|
||||
|
||||
/// Link `pos` into its chain (needs three bytes of input from `pos`).
|
||||
#[inline]
|
||||
fn insert(&mut self, data: &[u8], pos: usize) {
|
||||
if pos + MIN_MATCH <= data.len() {
|
||||
let h = Self::hash(data, pos);
|
||||
if let (Some(head), Some(prev)) = (self.head.get_mut(h), self.prev.get_mut(pos & WINDOW_MASK)) {
|
||||
*prev = *head;
|
||||
*head = pos + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Longest match for `pos` (which must already be inserted) that is longer than `better_than`.
|
||||
fn longest(&self, data: &[u8], pos: usize, better_than: usize, mut chain: usize, nice: usize) -> Option<(usize, usize)> {
|
||||
let max_len = MAX_MATCH.min(data.len() - pos);
|
||||
if max_len < MIN_MATCH || better_than >= max_len {
|
||||
return None;
|
||||
}
|
||||
let nice = nice.min(max_len);
|
||||
let mut best = (better_than, 0usize);
|
||||
let mut cand = self.link(pos);
|
||||
while cand != 0 && chain > 0 {
|
||||
let c = cand - 1;
|
||||
let dist = pos - c;
|
||||
if dist > WINDOW {
|
||||
break;
|
||||
}
|
||||
// Cheap reject: the byte that would extend the best match must agree.
|
||||
if data.get(c + best.0) == data.get(pos + best.0) {
|
||||
let len = match_len(data, c, pos, max_len);
|
||||
if len > best.0 && (len > MIN_MATCH || dist <= TOO_FAR) {
|
||||
best = (len, dist);
|
||||
if len >= nice {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let next = self.link(c);
|
||||
// A slot overwritten by a newer position ends the chain (positions only decrease along it).
|
||||
if next >= cand {
|
||||
break;
|
||||
}
|
||||
cand = next;
|
||||
chain -= 1;
|
||||
}
|
||||
(best.1 != 0).then_some(best)
|
||||
}
|
||||
|
||||
/// `prev` entry of position `pos` (0 = none).
|
||||
#[inline]
|
||||
fn link(&self, pos: usize) -> usize {
|
||||
self.prev.get(pos & WINDOW_MASK).copied().unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Length of the common prefix of `data[a..]` and `data[b..]`, at most `max` (a < b, b + max <= len).
|
||||
#[inline]
|
||||
fn match_len(data: &[u8], a: usize, b: usize, max: usize) -> usize {
|
||||
let (Some(x), Some(y)) = (data.get(a..a.saturating_add(max)), data.get(b..b.saturating_add(max))) else {
|
||||
return 0;
|
||||
};
|
||||
let ((xw, xr), (yw, yr)) = (x.as_chunks::<8>(), y.as_chunks::<8>());
|
||||
let mut n = 0;
|
||||
for (&p, &q) in xw.iter().zip(yw) {
|
||||
let (p, q) = (u64::from_le_bytes(p), u64::from_le_bytes(q));
|
||||
if p != q {
|
||||
return n + ((p ^ q).trailing_zeros() / 8) as usize;
|
||||
}
|
||||
n += 8;
|
||||
}
|
||||
n + xr.iter().zip(yr).take_while(|(p, q)| p == q).count()
|
||||
}
|
||||
|
||||
/// Parse `data` into literals and back-references.
|
||||
pub(super) fn parse(data: &[u8], p: Params, sink: &mut impl TokenSink) {
|
||||
let mut chains = Chains::new();
|
||||
if p.max_lazy == 0 {
|
||||
greedy(data, p, &mut chains, sink);
|
||||
} else {
|
||||
lazy(data, p, &mut chains, sink);
|
||||
}
|
||||
}
|
||||
|
||||
fn greedy(data: &[u8], p: Params, chains: &mut Chains, sink: &mut impl TokenSink) {
|
||||
let mut pos = 0;
|
||||
while let Some(&byte) = data.get(pos) {
|
||||
chains.insert(data, pos);
|
||||
match chains.longest(data, pos, MIN_MATCH - 1, p.max_chain, p.nice_len) {
|
||||
Some((len, dist)) => {
|
||||
sink.copy(len, dist);
|
||||
if len <= p.max_insert {
|
||||
for q in pos + 1..pos + len {
|
||||
chains.insert(data, q);
|
||||
}
|
||||
}
|
||||
pos += len;
|
||||
}
|
||||
None => {
|
||||
sink.literal(byte);
|
||||
pos += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// zlib-style lazy evaluation: a match is only taken if the match starting one byte later is not longer.
|
||||
fn lazy(data: &[u8], p: Params, chains: &mut Chains, sink: &mut impl TokenSink) {
|
||||
let mut pos = 0;
|
||||
// Match found at pos - 1 whose emission was deferred.
|
||||
let mut pending: Option<(usize, usize)> = None;
|
||||
while let Some(&byte) = data.get(pos) {
|
||||
chains.insert(data, pos);
|
||||
let (better_than, chain) = match pending {
|
||||
Some((len, _)) if len >= p.good_len => (len, p.max_chain / 4),
|
||||
Some((len, _)) => (len, p.max_chain),
|
||||
None => (MIN_MATCH - 1, p.max_chain),
|
||||
};
|
||||
let skip_search = matches!(pending, Some((len, _)) if len >= p.max_lazy);
|
||||
let cur = if skip_search { None } else { chains.longest(data, pos, better_than, chain, p.nice_len) };
|
||||
match (pending, cur) {
|
||||
(Some((len, dist)), None) => {
|
||||
// The deferred match wins: it started at pos - 1.
|
||||
sink.copy(len, dist);
|
||||
let end = pos - 1 + len;
|
||||
for q in pos + 1..end {
|
||||
chains.insert(data, q);
|
||||
}
|
||||
pos = end;
|
||||
pending = None;
|
||||
}
|
||||
(Some(_), Some(m)) => {
|
||||
// pos >= 1 whenever a match is pending.
|
||||
sink.literal(data.get(pos.wrapping_sub(1)).copied().unwrap_or(0));
|
||||
pending = Some(m);
|
||||
pos += 1;
|
||||
}
|
||||
(None, Some(m)) if m.0 < p.max_lazy => {
|
||||
pending = Some(m);
|
||||
pos += 1;
|
||||
}
|
||||
(None, Some((len, dist))) => {
|
||||
sink.copy(len, dist);
|
||||
for q in pos + 1..pos + len {
|
||||
chains.insert(data, q);
|
||||
}
|
||||
pos += len;
|
||||
}
|
||||
(None, None) => {
|
||||
sink.literal(byte);
|
||||
pos += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((len, dist)) = pending {
|
||||
sink.copy(len, dist);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Rebuilds the input from the parse, checking every token is legal.
|
||||
struct Replay(Vec<u8>);
|
||||
|
||||
impl TokenSink for Replay {
|
||||
fn literal(&mut self, b: u8) {
|
||||
self.0.push(b);
|
||||
}
|
||||
fn copy(&mut self, len: usize, dist: usize) {
|
||||
assert!((MIN_MATCH..=MAX_MATCH).contains(&len) && (1..=WINDOW).contains(&dist) && dist <= self.0.len());
|
||||
for _ in 0..len {
|
||||
let b = self.0[self.0.len() - dist];
|
||||
self.0.push(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_reproduce_input() {
|
||||
let mut data = Vec::new();
|
||||
let mut s = 1u32;
|
||||
for i in 0..200_000u32 {
|
||||
s = s.wrapping_mul(1_103_515_245).wrapping_add(12345);
|
||||
data.push(if i % 1000 < 500 { (s >> 24) as u8 & 7 } else { b"abcabcabd"[(i % 9) as usize] });
|
||||
}
|
||||
for max_lazy in [0, 16, 258] {
|
||||
let p = Params { max_chain: 64, nice_len: 128, good_len: 8, max_lazy, max_insert: 8 };
|
||||
let mut r = Replay(Vec::new());
|
||||
parse(&data, p, &mut r);
|
||||
assert!(r.0 == data, "max_lazy {max_lazy}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
//! DEFLATE compression (RFC 1951) and its zlib wrapper (RFC 1950). Decompression lives in `png::inflate`.
|
||||
//!
|
||||
//! LZ77 with hash chains (`lz77`) feeds blocks (`block`) that are written as dynamic Huffman, fixed Huffman or stored,
|
||||
//! whichever is smallest.
|
||||
|
||||
mod bits;
|
||||
mod block;
|
||||
mod huffman;
|
||||
mod inflate;
|
||||
mod lz77;
|
||||
pub(crate) mod tables;
|
||||
|
||||
use crate::checksum::adler32;
|
||||
use bits::BitWriter;
|
||||
use block::Block;
|
||||
use lz77::{Params, TokenSink};
|
||||
|
||||
pub use inflate::inflate;
|
||||
|
||||
/// Compression effort.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Level {
|
||||
/// No compression: stored blocks only.
|
||||
Store,
|
||||
/// Greedy parse, short hash chains (about zlib level 1-2).
|
||||
Fast,
|
||||
/// Lazy parse (about zlib level 6).
|
||||
#[default]
|
||||
Default,
|
||||
/// Lazy parse with long chains (about zlib level 9).
|
||||
Best,
|
||||
}
|
||||
|
||||
impl Level {
|
||||
fn params(self) -> Option<Params> {
|
||||
match self {
|
||||
Level::Store => None,
|
||||
Level::Fast => Some(Params { max_chain: 8, nice_len: 32, good_len: 0, max_lazy: 0, max_insert: 6 }),
|
||||
Level::Default => Some(Params { max_chain: 128, nice_len: 128, good_len: 8, max_lazy: 16, max_insert: 0 }),
|
||||
Level::Best => Some(Params { max_chain: 4096, nice_len: 258, good_len: 32, max_lazy: 258, max_insert: 0 }),
|
||||
}
|
||||
}
|
||||
|
||||
/// The FLEVEL hint of the zlib header.
|
||||
fn zlib_flevel(self) -> u8 {
|
||||
match self {
|
||||
Level::Store => 0,
|
||||
Level::Fast => 1,
|
||||
Level::Default => 2,
|
||||
Level::Best => 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tokens per block: bounds memory and lets the Huffman codes adapt to changing data.
|
||||
const BLOCK_TOKENS: usize = 16 * 1024;
|
||||
|
||||
/// Turns the parse into blocks as they fill up.
|
||||
struct BlockSink<'a> {
|
||||
data: &'a [u8],
|
||||
out: BitWriter,
|
||||
block: Block,
|
||||
/// Offset in `data` where the current block starts.
|
||||
start: usize,
|
||||
}
|
||||
|
||||
impl BlockSink<'_> {
|
||||
fn flush(&mut self, last: bool) {
|
||||
let end = self.start + self.block.bytes();
|
||||
// `start..end` is always inside `data`: the blocks cover the parsed prefix.
|
||||
self.block.write(&mut self.out, self.data.get(self.start..end).unwrap_or(&[]), last);
|
||||
self.start = end;
|
||||
}
|
||||
}
|
||||
|
||||
impl TokenSink for BlockSink<'_> {
|
||||
fn literal(&mut self, byte: u8) {
|
||||
self.block.literal(byte);
|
||||
if self.block.len() >= BLOCK_TOKENS {
|
||||
self.flush(false);
|
||||
}
|
||||
}
|
||||
|
||||
fn copy(&mut self, len: usize, dist: usize) {
|
||||
self.block.copy(len, dist);
|
||||
if self.block.len() >= BLOCK_TOKENS {
|
||||
self.flush(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compress `data` to a raw DEFLATE stream.
|
||||
pub fn compress(data: &[u8], level: Level) -> Vec<u8> {
|
||||
let Some(params) = level.params() else {
|
||||
let mut w = BitWriter::with_capacity(data.len() + data.len() / 65535 * 5 + 5);
|
||||
block::write_stored(&mut w, data, true);
|
||||
return w.finish();
|
||||
};
|
||||
let mut sink = BlockSink { data, out: BitWriter::with_capacity(data.len() / 3 + 64), block: Block::with_capacity(BLOCK_TOKENS), start: 0 };
|
||||
lz77::parse(data, params, &mut sink);
|
||||
// Always end with a final block, even if it is empty.
|
||||
sink.flush(true);
|
||||
sink.out.finish()
|
||||
}
|
||||
|
||||
/// Compress `data` to a zlib stream (2-byte header, DEFLATE data, Adler-32 of the input).
|
||||
pub fn zlib_compress(data: &[u8], level: Level) -> Vec<u8> {
|
||||
// CMF: deflate with a 32 KiB window. FLG: level hint, FCHECK so that (CMF * 256 + FLG) % 31 == 0.
|
||||
let cmf = 0x78u8;
|
||||
let flg_base = level.zlib_flevel() << 6;
|
||||
let flg = flg_base + (31 - ((cmf as u16 * 256 + flg_base as u16) % 31) as u8) % 31;
|
||||
let mut out = vec![cmf, flg];
|
||||
out.extend_from_slice(&compress(data, level));
|
||||
out.extend_from_slice(&adler32(data).to_be_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::png::inflate;
|
||||
|
||||
const LEVELS: [Level; 4] = [Level::Store, Level::Fast, Level::Default, Level::Best];
|
||||
|
||||
fn noise(n: usize, seed: u32) -> Vec<u8> {
|
||||
let mut s = seed;
|
||||
(0..n)
|
||||
.map(|_| {
|
||||
s ^= s << 13;
|
||||
s ^= s >> 17;
|
||||
s ^= s << 5;
|
||||
s as u8
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn text(n: usize) -> Vec<u8> {
|
||||
let words = ["material", "craft", "paint", "layer", "mask", "the", "of", "roughness", "normal", "height", " ", ", ", ".\n"];
|
||||
let r = noise(n, 7);
|
||||
let mut out = Vec::with_capacity(n + 16);
|
||||
let mut i = 0;
|
||||
while out.len() < n {
|
||||
out.extend_from_slice(words[r[i % r.len()] as usize % words.len()].as_bytes());
|
||||
i += 1;
|
||||
}
|
||||
out.truncate(n);
|
||||
out
|
||||
}
|
||||
|
||||
fn roundtrip(data: &[u8]) {
|
||||
for level in LEVELS {
|
||||
let z = compress(data, level);
|
||||
assert_eq!(inflate(&z).expect("inflate"), data, "{level:?}, {} bytes", data.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edge_cases_round_trip() {
|
||||
roundtrip(&[]);
|
||||
roundtrip(&[42]);
|
||||
roundtrip(&[1, 2]);
|
||||
roundtrip(b"aaa");
|
||||
roundtrip(b"abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc");
|
||||
roundtrip(&[0u8; 300_000]);
|
||||
roundtrip(&noise(100_000, 1));
|
||||
roundtrip(&text(300_000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_small_inputs_round_trip() {
|
||||
// Small inputs exercise the fixed-Huffman path and degenerate dynamic trees.
|
||||
let r = noise(3_000_000, 11);
|
||||
let mut k = 0;
|
||||
for i in 0..3000 {
|
||||
let n = r[k] as usize + (i % 3) * 200;
|
||||
let alphabet = r[k + 1] % 8 + 1;
|
||||
let d: Vec<u8> = r[k + 2..k + 2 + n].iter().map(|&b| (b % alphabet).wrapping_mul(37)).collect();
|
||||
k += n + 2;
|
||||
roundtrip(&d);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_range_repeats_round_trip() {
|
||||
// A 50 KiB random block repeated: matches at distances near and beyond the 32 KiB window.
|
||||
let mut data = noise(50_000, 3);
|
||||
data.extend_from_within(..);
|
||||
data.extend_from_slice(&noise(20_000, 4));
|
||||
data.extend_from_within(..40_000);
|
||||
roundtrip(&data);
|
||||
// Period exactly at the window size.
|
||||
let mut w = noise(32_768, 5);
|
||||
w.extend_from_within(..);
|
||||
w.extend_from_within(..);
|
||||
roundtrip(&w);
|
||||
let z = compress(&w, Level::Default);
|
||||
assert!(z.len() < 40_000, "window-sized period should be found: {}", z.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ratios_are_sensible() {
|
||||
assert!(compress(&[0u8; 1 << 20], Level::Default).len() < 2_000);
|
||||
let t = text(200_000);
|
||||
let (fast, def, best) = (compress(&t, Level::Fast).len(), compress(&t, Level::Default).len(), compress(&t, Level::Best).len());
|
||||
assert!(best <= def && def <= fast && fast < t.len() / 2, "{fast} {def} {best}");
|
||||
// Incompressible data falls back to stored blocks: tiny overhead.
|
||||
let r = noise(200_000, 9);
|
||||
assert!(compress(&r, Level::Default).len() <= r.len() + r.len() / 1000 + 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zlib_wrapper() {
|
||||
for level in LEVELS {
|
||||
let z = zlib_compress(b"hello hello hello", level);
|
||||
assert_eq!(z[0], 0x78);
|
||||
assert_eq!((z[0] as u16 * 256 + z[1] as u16) % 31, 0);
|
||||
assert_eq!(inflate(&z[2..z.len() - 4]).unwrap(), b"hello hello hello");
|
||||
assert_eq!(&z[z.len() - 4..], &adler32(b"hello hello hello").to_be_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
//! Fixed tables of RFC 1951: length/distance bases and extra bits, and the symbol lookups built from them.
|
||||
//! Shared by the compressor and by the decoder in `png::inflate`.
|
||||
|
||||
pub(crate) const LENGTH_BASE: [u16; 29] =
|
||||
[3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258];
|
||||
pub(crate) const LENGTH_EXTRA: [u8; 29] = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0];
|
||||
pub(crate) const DIST_BASE: [u16; 30] =
|
||||
[1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577];
|
||||
pub(crate) const DIST_EXTRA: [u8; 30] = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];
|
||||
/// Order in which code-length code lengths are transmitted in a dynamic block header.
|
||||
pub(crate) const CODE_LENGTH_ORDER: [usize; 19] = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
|
||||
|
||||
pub(super) const END_OF_BLOCK: usize = 256;
|
||||
pub(super) const MIN_MATCH: usize = 3;
|
||||
pub(super) const MAX_MATCH: usize = 258;
|
||||
pub(super) const WINDOW: usize = 32768;
|
||||
|
||||
/// Length code index (0..29) for each match length 0..=258 (entries below 3 are unused).
|
||||
// Evaluated at compile time only: an out-of-range index is a build error, not a runtime panic (and `get_mut` is not
|
||||
// usable in const context).
|
||||
#[allow(clippy::indexing_slicing)]
|
||||
const LENGTH_CODE: [u8; 259] = {
|
||||
let mut t = [0u8; 259];
|
||||
let mut code = 0;
|
||||
while code < 29 {
|
||||
let mut l = LENGTH_BASE[code] as usize;
|
||||
let end = l + (1 << LENGTH_EXTRA[code]);
|
||||
while l < end && l <= MAX_MATCH {
|
||||
t[l] = code as u8;
|
||||
l += 1;
|
||||
}
|
||||
code += 1;
|
||||
}
|
||||
t
|
||||
};
|
||||
|
||||
/// Distance code index: `[d - 1]` for d <= 256, then `[256 + ((d - 1) >> 7)]`.
|
||||
// Evaluated at compile time only: an out-of-range index is a build error, not a runtime panic (and `get_mut` is not
|
||||
// usable in const context).
|
||||
#[allow(clippy::indexing_slicing)]
|
||||
const DIST_CODE: [u8; 512] = {
|
||||
let mut t = [0u8; 512];
|
||||
let mut code = 0;
|
||||
while code < 30 {
|
||||
let mut d = DIST_BASE[code] as usize;
|
||||
let end = d + (1 << DIST_EXTRA[code]);
|
||||
while d < end {
|
||||
let x = d - 1;
|
||||
if x < 256 {
|
||||
t[x] = code as u8;
|
||||
} else {
|
||||
t[256 + (x >> 7)] = code as u8;
|
||||
}
|
||||
d += 1;
|
||||
}
|
||||
code += 1;
|
||||
}
|
||||
t
|
||||
};
|
||||
|
||||
/// Index (0..29) of the length code for a match length in 3..=258.
|
||||
pub(super) fn length_code(len: usize) -> usize {
|
||||
LENGTH_CODE.get(len).copied().unwrap_or(0) as usize
|
||||
}
|
||||
|
||||
/// Index (0..30) of the distance code for a distance in 1..=32768.
|
||||
pub(super) fn dist_code(dist: usize) -> usize {
|
||||
let x = dist - 1;
|
||||
let i = if x < 256 { x } else { 256 + (x >> 7) };
|
||||
DIST_CODE.get(i).copied().unwrap_or(0) as usize
|
||||
}
|
||||
|
||||
/// Code lengths of the fixed literal/length code (block type 1).
|
||||
pub(super) fn fixed_literal_lengths() -> [u8; 288] {
|
||||
let mut l = [0u8; 288];
|
||||
for (i, v) in l.iter_mut().enumerate() {
|
||||
*v = match i {
|
||||
0..=143 => 8,
|
||||
144..=255 => 9,
|
||||
256..=279 => 7,
|
||||
_ => 8,
|
||||
};
|
||||
}
|
||||
l
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lookups_agree_with_bases() {
|
||||
for len in MIN_MATCH..=MAX_MATCH {
|
||||
let c = length_code(len);
|
||||
let base = LENGTH_BASE[c] as usize;
|
||||
assert!(len >= base && len - base < (1 << LENGTH_EXTRA[c]) || len == 258 && c == 28, "len {len}");
|
||||
}
|
||||
assert_eq!(length_code(258), 28);
|
||||
assert_eq!(length_code(257), 27);
|
||||
for dist in 1..=WINDOW {
|
||||
let c = dist_code(dist);
|
||||
let base = DIST_BASE[c] as usize;
|
||||
assert!(dist >= base && dist - base < (1 << DIST_EXTRA[c]), "dist {dist}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Mini expression language for the Pixel Processor / function nodes.
|
||||
use crate::math;
|
||||
use crate::noise;
|
||||
use crate::tex::{Tex, lum};
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Op {
|
||||
Add,
|
||||
Sub,
|
||||
Mul,
|
||||
Div,
|
||||
Pow,
|
||||
Mod,
|
||||
Lt,
|
||||
Gt,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum Func {
|
||||
Sin,
|
||||
Cos,
|
||||
Abs,
|
||||
Sqrt,
|
||||
Min,
|
||||
Max,
|
||||
Pow,
|
||||
Floor,
|
||||
Fract,
|
||||
Clamp,
|
||||
Mix,
|
||||
Step,
|
||||
Smoothstep,
|
||||
Noise,
|
||||
Rand,
|
||||
Tex,
|
||||
Atan2,
|
||||
Exp,
|
||||
Log,
|
||||
}
|
||||
|
||||
const FUNCS: &[(&str, Func, usize)] = &[
|
||||
("sin", Func::Sin, 1),
|
||||
("cos", Func::Cos, 1),
|
||||
("abs", Func::Abs, 1),
|
||||
("sqrt", Func::Sqrt, 1),
|
||||
("min", Func::Min, 2),
|
||||
("max", Func::Max, 2),
|
||||
("pow", Func::Pow, 2),
|
||||
("floor", Func::Floor, 1),
|
||||
("fract", Func::Fract, 1),
|
||||
("clamp", Func::Clamp, 3),
|
||||
("mix", Func::Mix, 3),
|
||||
("step", Func::Step, 2),
|
||||
("smoothstep", Func::Smoothstep, 3),
|
||||
("noise", Func::Noise, 3),
|
||||
("rand", Func::Rand, 2),
|
||||
("tex", Func::Tex, 2),
|
||||
("atan2", Func::Atan2, 2),
|
||||
("exp", Func::Exp, 1),
|
||||
("log", Func::Log, 1),
|
||||
];
|
||||
|
||||
/// Variables: u v (0..1), x y (pixel), w h (size), r g b (input colour), l (input luminance)
|
||||
pub const VARS: [&str; 10] = ["u", "v", "x", "y", "w", "h", "r", "g", "b", "l"];
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Ex {
|
||||
Num(f32),
|
||||
Var(usize),
|
||||
Neg(Box<Ex>),
|
||||
Bin(Op, Box<Ex>, Box<Ex>),
|
||||
Call(Func, Vec<Ex>),
|
||||
}
|
||||
|
||||
pub struct Env<'a> {
|
||||
pub vars: [f32; 10],
|
||||
pub tex: Option<&'a Tex>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
enum Tok {
|
||||
Num(f32),
|
||||
Id(String),
|
||||
Sym(char),
|
||||
}
|
||||
|
||||
fn tokenize(s: &str) -> Result<Vec<Tok>, String> {
|
||||
let cs: Vec<char> = s.chars().collect();
|
||||
let mut i = 0;
|
||||
let mut out = Vec::new();
|
||||
let at = |i: usize| cs.get(i).copied().unwrap_or('\0');
|
||||
while let Some(c) = cs.get(i).copied() {
|
||||
if c.is_whitespace() {
|
||||
i += 1;
|
||||
} else if c.is_ascii_digit() || c == '.' {
|
||||
let st = i;
|
||||
while i < cs.len() && (at(i).is_ascii_digit() || at(i) == '.') {
|
||||
i += 1;
|
||||
}
|
||||
let t: String = cs.iter().take(i).skip(st).collect();
|
||||
out.push(Tok::Num(t.parse::<f32>().map_err(|_| format!("bad number '{t}'"))?));
|
||||
} else if c.is_alphabetic() || c == '_' {
|
||||
let st = i;
|
||||
while i < cs.len() && (at(i).is_alphanumeric() || at(i) == '_') {
|
||||
i += 1;
|
||||
}
|
||||
out.push(Tok::Id(cs.iter().take(i).skip(st).collect()));
|
||||
} else if "+-*/^%<>(),".contains(c) {
|
||||
out.push(Tok::Sym(c));
|
||||
i += 1;
|
||||
} else {
|
||||
return Err(format!("unexpected character '{c}'"));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
struct P {
|
||||
t: Vec<Tok>,
|
||||
i: usize,
|
||||
/// how many brackets, signs and powers the parser is inside now (each is a few calls deeper)
|
||||
nest: usize,
|
||||
}
|
||||
|
||||
/// The most tokens an expression may have: evaluating it recurses along its tree, which a chain of terms makes as deep
|
||||
/// as it is long.
|
||||
const MAX_TOKENS: usize = 4096;
|
||||
/// The most brackets, signs and powers one inside the other.
|
||||
const MAX_NESTING: usize = 256;
|
||||
|
||||
impl P {
|
||||
fn peek(&self) -> Option<&Tok> {
|
||||
self.t.get(self.i)
|
||||
}
|
||||
fn sym(&mut self, c: char) -> bool {
|
||||
if self.peek() == Some(&Tok::Sym(c)) {
|
||||
self.i += 1;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
fn cmp(&mut self) -> Result<Ex, String> {
|
||||
let mut l = self.add()?;
|
||||
loop {
|
||||
let op = if self.sym('<') {
|
||||
Op::Lt
|
||||
} else if self.sym('>') {
|
||||
Op::Gt
|
||||
} else {
|
||||
return Ok(l);
|
||||
};
|
||||
let r = self.add()?;
|
||||
l = Ex::Bin(op, Box::new(l), Box::new(r));
|
||||
}
|
||||
}
|
||||
fn add(&mut self) -> Result<Ex, String> {
|
||||
let mut l = self.mul()?;
|
||||
loop {
|
||||
let op = if self.sym('+') {
|
||||
Op::Add
|
||||
} else if self.sym('-') {
|
||||
Op::Sub
|
||||
} else {
|
||||
return Ok(l);
|
||||
};
|
||||
let r = self.mul()?;
|
||||
l = Ex::Bin(op, Box::new(l), Box::new(r));
|
||||
}
|
||||
}
|
||||
fn mul(&mut self) -> Result<Ex, String> {
|
||||
let mut l = self.unary()?;
|
||||
loop {
|
||||
let op = if self.sym('*') {
|
||||
Op::Mul
|
||||
} else if self.sym('/') {
|
||||
Op::Div
|
||||
} else if self.sym('%') {
|
||||
Op::Mod
|
||||
} else {
|
||||
return Ok(l);
|
||||
};
|
||||
let r = self.unary()?;
|
||||
l = Ex::Bin(op, Box::new(l), Box::new(r));
|
||||
}
|
||||
}
|
||||
fn unary(&mut self) -> Result<Ex, String> {
|
||||
if self.nest >= MAX_NESTING {
|
||||
return Err(format!("expression nested more than {MAX_NESTING} deep"));
|
||||
}
|
||||
self.nest += 1;
|
||||
let r = self.unary_inner();
|
||||
self.nest -= 1;
|
||||
r
|
||||
}
|
||||
fn unary_inner(&mut self) -> Result<Ex, String> {
|
||||
if self.sym('-') {
|
||||
return Ok(Ex::Neg(Box::new(self.unary()?)));
|
||||
}
|
||||
let b = self.primary()?;
|
||||
if self.sym('^') {
|
||||
let e = self.unary()?;
|
||||
return Ok(Ex::Bin(Op::Pow, Box::new(b), Box::new(e)));
|
||||
}
|
||||
Ok(b)
|
||||
}
|
||||
fn primary(&mut self) -> Result<Ex, String> {
|
||||
match self.t.get(self.i).cloned() {
|
||||
Some(Tok::Num(n)) => {
|
||||
self.i += 1;
|
||||
Ok(Ex::Num(n))
|
||||
}
|
||||
Some(Tok::Sym('(')) => {
|
||||
self.i += 1;
|
||||
let e = self.cmp()?;
|
||||
if !self.sym(')') {
|
||||
return Err("expected ')'".into());
|
||||
}
|
||||
Ok(e)
|
||||
}
|
||||
Some(Tok::Id(name)) => {
|
||||
self.i += 1;
|
||||
if self.sym('(') {
|
||||
let (f, arity) =
|
||||
FUNCS.iter().find(|(n, _, _)| *n == name).map(|(_, f, a)| (*f, *a)).ok_or_else(|| format!("unknown function '{name}'"))?;
|
||||
let mut args = Vec::new();
|
||||
if !self.sym(')') {
|
||||
loop {
|
||||
args.push(self.cmp()?);
|
||||
if self.sym(')') {
|
||||
break;
|
||||
}
|
||||
if !self.sym(',') {
|
||||
return Err("expected ',' or ')'".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
if args.len() != arity {
|
||||
return Err(format!("{name}() takes {arity} argument(s), got {}", args.len()));
|
||||
}
|
||||
Ok(Ex::Call(f, args))
|
||||
} else if name == "pi" {
|
||||
Ok(Ex::Num(std::f32::consts::PI))
|
||||
} else {
|
||||
VARS.iter().position(|v| *v == name).map(Ex::Var).ok_or_else(|| format!("unknown variable '{name}'"))
|
||||
}
|
||||
}
|
||||
other => Err(format!("unexpected token {:?}", other)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(src: &str) -> Result<Ex, String> {
|
||||
let t = tokenize(src)?;
|
||||
if t.len() > MAX_TOKENS {
|
||||
return Err(format!("expression longer than {MAX_TOKENS} tokens"));
|
||||
}
|
||||
let mut p = P { t, i: 0, nest: 0 };
|
||||
let e = p.cmp()?;
|
||||
if p.i != p.t.len() {
|
||||
return Err("trailing tokens in expression".into());
|
||||
}
|
||||
Ok(e)
|
||||
}
|
||||
|
||||
fn smooth(a: f32, b: f32, x: f32) -> f32 {
|
||||
let d = b - a;
|
||||
let t = if d.abs() < 1e-9 { 0.0 } else { ((x - a) / d).clamp(0.0, 1.0) };
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
|
||||
pub fn eval(e: &Ex, env: &Env) -> f32 {
|
||||
let r = match e {
|
||||
Ex::Num(n) => *n,
|
||||
Ex::Var(i) => env.vars.get(*i).copied().unwrap_or(0.0),
|
||||
Ex::Neg(a) => -eval(a, env),
|
||||
Ex::Bin(op, a, b) => {
|
||||
let (x, y) = (eval(a, env), eval(b, env));
|
||||
match op {
|
||||
Op::Add => x + y,
|
||||
Op::Sub => x - y,
|
||||
Op::Mul => x * y,
|
||||
Op::Div => {
|
||||
if y == 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
x / y
|
||||
}
|
||||
}
|
||||
Op::Pow => math::powf(x, y),
|
||||
Op::Mod => {
|
||||
if y == 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
x.rem_euclid(y)
|
||||
}
|
||||
}
|
||||
Op::Lt => (x < y) as i32 as f32,
|
||||
Op::Gt => (x > y) as i32 as f32,
|
||||
}
|
||||
}
|
||||
Ex::Call(f, a) => {
|
||||
// (the parser checked the number of arguments; none takes more than three)
|
||||
let mut v = [0.0f32; 3];
|
||||
for (v, x) in v.iter_mut().zip(a) {
|
||||
*v = eval(x, env);
|
||||
}
|
||||
match f {
|
||||
Func::Sin => math::sin(v[0]),
|
||||
Func::Cos => math::cos(v[0]),
|
||||
Func::Abs => v[0].abs(),
|
||||
Func::Sqrt => v[0].max(0.0).sqrt(),
|
||||
Func::Min => v[0].min(v[1]),
|
||||
Func::Max => v[0].max(v[1]),
|
||||
Func::Pow => math::powf(v[0], v[1]),
|
||||
Func::Floor => v[0].floor(),
|
||||
Func::Fract => v[0] - v[0].floor(),
|
||||
Func::Clamp => v[0].max(v[1].min(v[2])).min(v[1].max(v[2])),
|
||||
Func::Mix => v[0] + (v[1] - v[0]) * v[2],
|
||||
Func::Step => (v[1] >= v[0]) as i32 as f32,
|
||||
Func::Smoothstep => smooth(v[0], v[1], v[2]),
|
||||
Func::Noise => {
|
||||
let p = v[2].round().clamp(1.0, 4096.0) as i32;
|
||||
noise::perlin(v[0], v[1], p, p, 0)
|
||||
}
|
||||
Func::Rand => noise::rnd(v[0].floor() as i32, v[1].floor() as i32, 1),
|
||||
Func::Tex => env.tex.map(|t| lum(t.sample(v[0], v[1]))).unwrap_or(0.0),
|
||||
Func::Atan2 => math::atan2(v[0], v[1]),
|
||||
Func::Exp => math::exp(v[0].min(80.0)),
|
||||
Func::Log => math::ln(v[0].max(1e-12)),
|
||||
}
|
||||
}
|
||||
};
|
||||
if r.is_finite() { r } else { 0.0 }
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
//! Per-block compression schemes: NONE, RLE (read only), ZIPS and ZIP. RLE and ZIP share the same preprocessing:
|
||||
//! bytes are split into even/odd halves and delta-coded before the entropy stage.
|
||||
|
||||
use crate::deflate::{self, Level};
|
||||
|
||||
/// Block compression of a scanline file.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Compression {
|
||||
None,
|
||||
/// Run-length encoding (decode only).
|
||||
Rle,
|
||||
/// zlib, one scanline per block.
|
||||
Zips,
|
||||
/// zlib, sixteen scanlines per block.
|
||||
Zip,
|
||||
}
|
||||
|
||||
impl Compression {
|
||||
pub(super) fn code(self) -> u8 {
|
||||
match self {
|
||||
Compression::None => 0,
|
||||
Compression::Rle => 1,
|
||||
Compression::Zips => 2,
|
||||
Compression::Zip => 3,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn from_code(c: u8) -> Result<Self, String> {
|
||||
match c {
|
||||
0 => Ok(Compression::None),
|
||||
1 => Ok(Compression::Rle),
|
||||
2 => Ok(Compression::Zips),
|
||||
3 => Ok(Compression::Zip),
|
||||
4 => Err("PIZ compression is not supported".into()),
|
||||
5 => Err("PXR24 compression is not supported".into()),
|
||||
6 | 7 => Err("B44 compression is not supported".into()),
|
||||
8 | 9 => Err("DWA compression is not supported".into()),
|
||||
_ => Err(format!("unknown compression {c}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Scanlines per block.
|
||||
pub(super) fn lines_per_block(self) -> usize {
|
||||
match self {
|
||||
Compression::Zip => 16,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Upper bound of uncompressed/compressed size, used to reject absurd headers before allocating.
|
||||
pub(super) fn max_expansion(self) -> usize {
|
||||
match self {
|
||||
Compression::None => 1,
|
||||
Compression::Rle => 128,
|
||||
Compression::Zips | Compression::Zip => 1032,
|
||||
}
|
||||
}
|
||||
|
||||
/// Compress one block of raw (little-endian, planar per scanline) bytes. Returns the raw bytes when compressing
|
||||
/// would not make them smaller, as the format requires.
|
||||
pub(super) fn compress(self, raw: &[u8]) -> Vec<u8> {
|
||||
let packed = match self {
|
||||
Compression::None | Compression::Rle => return raw.to_vec(),
|
||||
Compression::Zips | Compression::Zip => deflate::zlib_compress(&predict(&interleave(raw)), Level::Default),
|
||||
};
|
||||
if packed.len() < raw.len() { packed } else { raw.to_vec() }
|
||||
}
|
||||
|
||||
/// Inverse of `compress`; `expected` is the raw block size.
|
||||
pub(super) fn decompress(self, data: &[u8], expected: usize) -> Result<Vec<u8>, String> {
|
||||
if data.len() == expected || self == Compression::None {
|
||||
return if data.len() == expected { Ok(data.to_vec()) } else { Err("block size mismatch".into()) };
|
||||
}
|
||||
let mut t = match self {
|
||||
Compression::Rle => rle_decode(data, expected)?,
|
||||
_ => match (data.first(), data.get(2..)) {
|
||||
(Some(&cmf), Some(body)) if data.len() >= 6 && cmf & 0x0f == 8 => crate::deflate::inflate(body)?,
|
||||
_ => return Err("bad zlib block".into()),
|
||||
},
|
||||
};
|
||||
if t.len() != expected {
|
||||
return Err("block decompressed to the wrong size".into());
|
||||
}
|
||||
unpredict(&mut t);
|
||||
Ok(deinterleave(&t))
|
||||
}
|
||||
}
|
||||
|
||||
/// First half: bytes 0, 2, 4...; second half: bytes 1, 3, 5...
|
||||
fn interleave(raw: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(raw.len());
|
||||
out.extend(raw.iter().step_by(2));
|
||||
out.extend(raw.iter().skip(1).step_by(2));
|
||||
out
|
||||
}
|
||||
|
||||
fn deinterleave(t: &[u8]) -> Vec<u8> {
|
||||
// Even output bytes come from the first half, odd ones from the second (one shorter for odd lengths).
|
||||
let (even, odd) = t.split_at(t.len().div_ceil(2));
|
||||
let mut out = Vec::with_capacity(t.len());
|
||||
let mut odd = odd.iter();
|
||||
for &e in even {
|
||||
out.push(e);
|
||||
out.extend(odd.next());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn predict(t: &[u8]) -> Vec<u8> {
|
||||
let mut out = t.to_vec();
|
||||
for (o, (&prev, &cur)) in out.iter_mut().skip(1).zip(t.iter().zip(t.iter().skip(1))) {
|
||||
*o = cur.wrapping_sub(prev).wrapping_add(128);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn unpredict(t: &mut [u8]) {
|
||||
let Some((first, rest)) = t.split_first_mut() else {
|
||||
return;
|
||||
};
|
||||
let mut prev = *first;
|
||||
for x in rest {
|
||||
*x = prev.wrapping_add(*x).wrapping_sub(128);
|
||||
prev = *x;
|
||||
}
|
||||
}
|
||||
|
||||
/// OpenEXR RLE: a negative count -n is followed by n literal bytes; a count n >= 0 by one byte repeated n + 1 times.
|
||||
fn rle_decode(data: &[u8], expected: usize) -> Result<Vec<u8>, String> {
|
||||
let mut out = Vec::with_capacity(expected);
|
||||
let mut i = 0;
|
||||
while let Some(&count) = data.get(i) {
|
||||
let n = count as i8;
|
||||
i += 1;
|
||||
if n < 0 {
|
||||
let run = data.get(i..i + (-(n as i32)) as usize).ok_or("truncated RLE block")?;
|
||||
out.extend_from_slice(run);
|
||||
i += run.len();
|
||||
} else {
|
||||
let b = *data.get(i).ok_or("truncated RLE block")?;
|
||||
out.extend(std::iter::repeat_n(b, n as usize + 1));
|
||||
i += 1;
|
||||
}
|
||||
if out.len() > expected {
|
||||
return Err("RLE block too long".into());
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn preprocessing_inverts() {
|
||||
for n in [0usize, 1, 2, 7, 100] {
|
||||
let raw: Vec<u8> = (0..n).map(|i| (i * 37 % 256) as u8).collect();
|
||||
let mut p = predict(&interleave(&raw));
|
||||
unpredict(&mut p);
|
||||
assert_eq!(deinterleave(&p), raw);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rle_decodes() {
|
||||
// Reference RLE of [1,1,1,1,2,3]: run of 4 ones (count 3), then two literals (count -2).
|
||||
let mut packed = vec![3u8, 1, (-2i8) as u8, 2, 3];
|
||||
let pre = rle_decode(&packed, 6).unwrap();
|
||||
assert_eq!(pre, [1, 1, 1, 1, 2, 3]);
|
||||
packed.pop();
|
||||
assert!(rle_decode(&packed, 6).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zip_block_round_trip() {
|
||||
let raw: Vec<u8> = (0..4096).map(|i| ((i / 64) as u8).wrapping_mul(3)).collect();
|
||||
for c in [Compression::Zips, Compression::Zip] {
|
||||
let z = c.compress(&raw);
|
||||
assert!(z.len() < raw.len() / 4);
|
||||
assert_eq!(c.decompress(&z, raw.len()).unwrap(), raw);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
//! Reading: header, line-offset table, then every chunk, each placed by the y coordinate it carries.
|
||||
|
||||
use super::header::Header;
|
||||
use super::{ExrChannel, ExrImage, SampleKind};
|
||||
use crate::half::f16_to_f32;
|
||||
|
||||
/// Decode a single-part scanline OpenEXR file (NONE, RLE, ZIPS or ZIP compression). Channels come back sorted by
|
||||
/// name; the data window becomes the image (its origin is dropped).
|
||||
pub fn decode(b: &[u8]) -> Result<ExrImage, String> {
|
||||
let (header, table_at) = Header::read(b)?;
|
||||
// `Header::read` bounds the data window (65536 per side, 2^28 pixels), so `w * h` cannot overflow.
|
||||
let (w, h) = (header.width(), header.height());
|
||||
let lines = header.compression.lines_per_block();
|
||||
let blocks = h.div_ceil(lines);
|
||||
|
||||
// Refuse sizes the file cannot possibly hold before allocating anything.
|
||||
let line_bytes = header.line_bytes();
|
||||
let raw_total = line_bytes.checked_mul(h).ok_or("image too large")?;
|
||||
if raw_total / header.compression.max_expansion() > b.len() {
|
||||
return Err("image larger than the file can hold".into());
|
||||
}
|
||||
let table_end = blocks.checked_mul(8).and_then(|n| n.checked_add(table_at)).ok_or("image too large")?;
|
||||
let table = b.get(table_at..table_end).ok_or("truncated line offset table")?;
|
||||
|
||||
let mut channels = Vec::with_capacity(header.channels.len());
|
||||
for (name, kind) in &header.channels {
|
||||
let mut data = Vec::new();
|
||||
data.try_reserve_exact(w * h).map_err(|_| "image too large")?;
|
||||
data.resize(w * h, 0.0);
|
||||
channels.push(ExrChannel::new(name, *kind, data));
|
||||
}
|
||||
let mut seen = vec![false; blocks];
|
||||
for &entry in table.as_chunks::<8>().0 {
|
||||
let offset = u64::from_le_bytes(entry);
|
||||
let at = usize::try_from(offset).map_err(|_| "chunk offset out of range")?;
|
||||
let Some(&[y0, y1, y2, y3, s0, s1, s2, s3]) = b.get(at..at.checked_add(8).ok_or("chunk offset out of range")?) else {
|
||||
return Err("chunk offset out of range".into());
|
||||
};
|
||||
let y = i32::from_le_bytes([y0, y1, y2, y3]) as i64;
|
||||
let size = usize::try_from(i32::from_le_bytes([s0, s1, s2, s3])).map_err(|_| "negative chunk size")?;
|
||||
// at + 8 cannot overflow: those eight bytes exist.
|
||||
let data = b.get(at + 8..(at + 8).checked_add(size).ok_or("truncated chunk")?).ok_or("truncated chunk")?;
|
||||
|
||||
let rel = y - header.data_window[1] as i64;
|
||||
if rel < 0 || rel as usize >= h || !(rel as usize).is_multiple_of(lines) {
|
||||
return Err(format!("chunk has invalid y {y}"));
|
||||
}
|
||||
let block = rel as usize / lines;
|
||||
let Some(seen) = seen.get_mut(block) else {
|
||||
return Err(format!("chunk has invalid y {y}"));
|
||||
};
|
||||
if std::mem::replace(seen, true) {
|
||||
return Err(format!("duplicate chunk for y {y}"));
|
||||
}
|
||||
let y0 = rel as usize;
|
||||
let n_lines = lines.min(h - y0);
|
||||
// n_lines * line_bytes <= raw_total, checked above.
|
||||
let raw = header.compression.decompress(data, n_lines * line_bytes)?;
|
||||
let mut pos = 0;
|
||||
for line in y0..y0 + n_lines {
|
||||
for ch in channels.iter_mut() {
|
||||
let bytes = w * ch.sample.size();
|
||||
// `raw` holds exactly n_lines * line_bytes bytes and every line of `data` exists (line < h).
|
||||
let (Some(src), Some(dst)) = (raw.get(pos..pos + bytes), ch.data.get_mut(line * w..(line + 1) * w)) else {
|
||||
return Err("block decompressed to the wrong size".into());
|
||||
};
|
||||
read_samples(src, ch.sample, dst);
|
||||
pos += bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(ExrImage { width: w, height: h, channels })
|
||||
}
|
||||
|
||||
fn read_samples(src: &[u8], kind: SampleKind, dst: &mut [f32]) {
|
||||
match kind {
|
||||
SampleKind::Half => src.as_chunks::<2>().0.iter().zip(dst).for_each(|(&s, d)| *d = f16_to_f32(u16::from_le_bytes(s))),
|
||||
SampleKind::Float => src.as_chunks::<4>().0.iter().zip(dst).for_each(|(&s, d)| *d = f32::from_le_bytes(s)),
|
||||
SampleKind::Uint => src.as_chunks::<4>().0.iter().zip(dst).for_each(|(&s, d)| *d = u32::from_le_bytes(s) as f32),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Writing: header, line-offset table, then one chunk (y, size, data) per block of scanlines.
|
||||
|
||||
use super::header::Header;
|
||||
use super::{Compression, ExrChannel, ExrImage, SampleKind};
|
||||
use crate::half::f32_to_f16;
|
||||
|
||||
/// Encode with ZIP compression (lossless; the usual choice for HDR maps).
|
||||
pub fn encode(img: &ExrImage) -> Result<Vec<u8>, String> {
|
||||
encode_with(img, Compression::Zip)
|
||||
}
|
||||
|
||||
/// Encode with the given compression (`Rle` is read-only and rejected).
|
||||
pub fn encode_with(img: &ExrImage, compression: Compression) -> Result<Vec<u8>, String> {
|
||||
validate(img)?;
|
||||
if compression == Compression::Rle {
|
||||
return Err("writing RLE-compressed OpenEXR is not supported".into());
|
||||
}
|
||||
let mut order: Vec<&ExrChannel> = img.channels.iter().collect();
|
||||
order.sort_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes()));
|
||||
let header = Header {
|
||||
channels: order.iter().map(|c| (c.name.clone(), c.sample)).collect(),
|
||||
compression,
|
||||
data_window: [0, 0, img.width as i32 - 1, img.height as i32 - 1],
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
header.write(&mut out);
|
||||
|
||||
let lines = compression.lines_per_block();
|
||||
let blocks = img.height.div_ceil(lines);
|
||||
let table_at = out.len();
|
||||
out.resize(table_at + blocks * 8, 0);
|
||||
let mut raw = Vec::with_capacity(lines * header.line_bytes());
|
||||
for block in 0..blocks {
|
||||
let y0 = block * lines;
|
||||
raw.clear();
|
||||
for y in y0..(y0 + lines).min(img.height) {
|
||||
for ch in &order {
|
||||
// `validate` checked every channel holds width * height samples.
|
||||
let row = ch.data.get(y * img.width..(y + 1) * img.width).ok_or("channel too short")?;
|
||||
write_samples(row, ch.sample, &mut raw);
|
||||
}
|
||||
}
|
||||
let data = compression.compress(&raw);
|
||||
let offset = out.len() as u64;
|
||||
let slot = table_at + block * 8;
|
||||
out.get_mut(slot..slot + 8).ok_or("line offset table")?.copy_from_slice(&offset.to_le_bytes());
|
||||
out.extend_from_slice(&(y0 as i32).to_le_bytes());
|
||||
out.extend_from_slice(&(data.len() as i32).to_le_bytes());
|
||||
out.extend_from_slice(&data);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn validate(img: &ExrImage) -> Result<(), String> {
|
||||
if img.width == 0 || img.height == 0 || img.width > i32::MAX as usize || img.height > i32::MAX as usize {
|
||||
return Err(format!("bad image size {}x{}", img.width, img.height));
|
||||
}
|
||||
if img.channels.is_empty() {
|
||||
return Err("image has no channels".into());
|
||||
}
|
||||
let n = img.width.checked_mul(img.height).ok_or("image too large")?;
|
||||
for (i, c) in img.channels.iter().enumerate() {
|
||||
if c.name.is_empty() || c.name.len() > 255 || c.name.contains('\0') {
|
||||
return Err(format!("bad channel name '{}'", c.name));
|
||||
}
|
||||
if img.channels.iter().take(i).any(|o| o.name == c.name) {
|
||||
return Err(format!("duplicate channel '{}'", c.name));
|
||||
}
|
||||
if c.data.len() != n {
|
||||
return Err(format!("channel '{}' has {} samples, expected {n}", c.name, c.data.len()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_samples(row: &[f32], kind: SampleKind, out: &mut Vec<u8>) {
|
||||
match kind {
|
||||
SampleKind::Half => row.iter().for_each(|&v| out.extend_from_slice(&f32_to_f16(v).to_le_bytes())),
|
||||
SampleKind::Float => row.iter().for_each(|&v| out.extend_from_slice(&v.to_le_bytes())),
|
||||
// Saturating cast: negatives and NaN become 0.
|
||||
SampleKind::Uint => row.iter().for_each(|&v| out.extend_from_slice(&(v as u32).to_le_bytes())),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
//! The file header: magic number, version flags and the attribute list.
|
||||
|
||||
use super::{Compression, SampleKind};
|
||||
|
||||
const MAGIC: [u8; 4] = [0x76, 0x2f, 0x31, 0x01];
|
||||
const VERSION: u32 = 2;
|
||||
const FLAG_TILED: u32 = 0x200;
|
||||
const FLAG_LONG_NAMES: u32 = 0x400;
|
||||
const FLAG_DEEP: u32 = 0x800;
|
||||
const FLAG_MULTIPART: u32 = 0x1000;
|
||||
/// Attribute and channel names longer than this need the long-names flag.
|
||||
const SHORT_NAME_MAX: usize = 31;
|
||||
const LONG_NAME_MAX: usize = 255;
|
||||
/// Largest data window read: 65536 per side and 2^28 pixels (1 GiB per float channel). Keeps every size computed from
|
||||
/// it far from overflowing, also with a 32-bit `usize`.
|
||||
pub(super) const MAX_SIDE: i64 = 1 << 16;
|
||||
pub(super) const MAX_PIXELS: i64 = 1 << 28;
|
||||
|
||||
/// What the codec needs from a header.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(super) struct Header {
|
||||
/// Sorted by name, as stored.
|
||||
pub channels: Vec<(String, SampleKind)>,
|
||||
pub compression: Compression,
|
||||
/// Data window: x_min, y_min, x_max, y_max (inclusive).
|
||||
pub data_window: [i32; 4],
|
||||
}
|
||||
|
||||
impl Header {
|
||||
pub fn width(&self) -> usize {
|
||||
(self.data_window[2] as i64 - self.data_window[0] as i64 + 1) as usize
|
||||
}
|
||||
|
||||
pub fn height(&self) -> usize {
|
||||
(self.data_window[3] as i64 - self.data_window[1] as i64 + 1) as usize
|
||||
}
|
||||
|
||||
/// Bytes of one scanline across all channels (saturating: a huge channel list cannot fit any file anyway).
|
||||
pub fn line_bytes(&self) -> usize {
|
||||
self.width().saturating_mul(self.channels.iter().map(|(_, k)| k.size()).fold(0usize, usize::saturating_add))
|
||||
}
|
||||
|
||||
/// Magic, version and all required attributes (alphabetical, as OpenEXR writes them).
|
||||
pub fn write(&self, out: &mut Vec<u8>) {
|
||||
let long = self.channels.iter().any(|(n, _)| n.len() > SHORT_NAME_MAX);
|
||||
out.extend_from_slice(&MAGIC);
|
||||
out.extend_from_slice(&(VERSION | if long { FLAG_LONG_NAMES } else { 0 }).to_le_bytes());
|
||||
|
||||
let mut chlist = Vec::new();
|
||||
for (name, kind) in &self.channels {
|
||||
chlist.extend_from_slice(name.as_bytes());
|
||||
chlist.push(0);
|
||||
chlist.extend_from_slice(&kind.code().to_le_bytes());
|
||||
chlist.extend_from_slice(&[0, 0, 0, 0]); // pLinear, reserved
|
||||
chlist.extend_from_slice(&1i32.to_le_bytes()); // xSampling
|
||||
chlist.extend_from_slice(&1i32.to_le_bytes()); // ySampling
|
||||
}
|
||||
chlist.push(0);
|
||||
let window: Vec<u8> = self.data_window.iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||
attribute(out, "channels", "chlist", &chlist);
|
||||
attribute(out, "compression", "compression", &[self.compression.code()]);
|
||||
attribute(out, "dataWindow", "box2i", &window);
|
||||
attribute(out, "displayWindow", "box2i", &window);
|
||||
attribute(out, "lineOrder", "lineOrder", &[0]); // INCREASING_Y
|
||||
attribute(out, "pixelAspectRatio", "float", &1f32.to_le_bytes());
|
||||
attribute(out, "screenWindowCenter", "v2f", &[0; 8]);
|
||||
attribute(out, "screenWindowWidth", "float", &1f32.to_le_bytes());
|
||||
out.push(0);
|
||||
}
|
||||
|
||||
/// Parse the header at the start of `b`; returns it and the offset of the line-offset table.
|
||||
pub fn read(b: &[u8]) -> Result<(Header, usize), String> {
|
||||
let Some(&[m0, m1, m2, m3, f0, f1, f2, f3]) = b.get(..8) else {
|
||||
return Err("not an OpenEXR file".into());
|
||||
};
|
||||
if [m0, m1, m2, m3] != MAGIC {
|
||||
return Err("not an OpenEXR file".into());
|
||||
}
|
||||
let flags = u32::from_le_bytes([f0, f1, f2, f3]);
|
||||
if flags & 0xff != VERSION {
|
||||
return Err(format!("unsupported OpenEXR version {}", flags & 0xff));
|
||||
}
|
||||
if flags & (FLAG_TILED | FLAG_DEEP | FLAG_MULTIPART) != 0 {
|
||||
return Err("only single-part scanline OpenEXR files are supported".into());
|
||||
}
|
||||
let name_max = if flags & FLAG_LONG_NAMES != 0 { LONG_NAME_MAX } else { SHORT_NAME_MAX };
|
||||
let mut pos = 8;
|
||||
let (mut channels, mut compression, mut data_window) = (None, None, None);
|
||||
loop {
|
||||
let name = cstr(b, &mut pos, name_max)?;
|
||||
if name.is_empty() {
|
||||
break;
|
||||
}
|
||||
let kind = cstr(b, &mut pos, name_max)?;
|
||||
let size = i32::from_le_bytes(take(b, &mut pos, 4)?.try_into().map_err(|_| "bad attribute size")?);
|
||||
let size = usize::try_from(size).map_err(|_| "negative attribute size")?;
|
||||
let value = take(b, &mut pos, size)?;
|
||||
match (name, kind) {
|
||||
("channels", "chlist") => channels = Some(parse_chlist(value, name_max)?),
|
||||
("compression", "compression") if size == 1 => {
|
||||
if let &[c] = value {
|
||||
compression = Some(Compression::from_code(c)?);
|
||||
}
|
||||
}
|
||||
("dataWindow", "box2i") if size == 16 => {
|
||||
if let &[x0, y0, x1, y1] = value.as_chunks::<4>().0 {
|
||||
data_window = Some([x0, y0, x1, y1].map(i32::from_le_bytes));
|
||||
}
|
||||
}
|
||||
("type", "string") if value != b"scanlineimage" => return Err("only scanline images are supported".into()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let channels = channels.ok_or("missing channels attribute")?;
|
||||
let compression = compression.ok_or("missing compression attribute")?;
|
||||
let data_window = data_window.ok_or("missing dataWindow attribute")?;
|
||||
if data_window[2] < data_window[0] || data_window[3] < data_window[1] {
|
||||
return Err("empty data window".into());
|
||||
}
|
||||
let (w, h) = (data_window[2] as i64 - data_window[0] as i64 + 1, data_window[3] as i64 - data_window[1] as i64 + 1);
|
||||
if w > MAX_SIDE || h > MAX_SIDE || w * h > MAX_PIXELS {
|
||||
return Err(format!("data window too large ({w}x{h})"));
|
||||
}
|
||||
if channels.is_empty() {
|
||||
return Err("no channels".into());
|
||||
}
|
||||
Ok((Header { channels, compression, data_window }, pos))
|
||||
}
|
||||
}
|
||||
|
||||
fn attribute(out: &mut Vec<u8>, name: &str, kind: &str, value: &[u8]) {
|
||||
out.extend_from_slice(name.as_bytes());
|
||||
out.push(0);
|
||||
out.extend_from_slice(kind.as_bytes());
|
||||
out.push(0);
|
||||
out.extend_from_slice(&(value.len() as i32).to_le_bytes());
|
||||
out.extend_from_slice(value);
|
||||
}
|
||||
|
||||
fn take<'a>(b: &'a [u8], pos: &mut usize, n: usize) -> Result<&'a [u8], String> {
|
||||
let s = b.get(*pos..pos.checked_add(n).ok_or("bad length")?).ok_or("truncated header")?;
|
||||
*pos += n;
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// A NUL-terminated name of at most `max` bytes.
|
||||
fn cstr<'a>(b: &'a [u8], pos: &mut usize, max: usize) -> Result<&'a str, String> {
|
||||
let rest = b.get(*pos..).ok_or("truncated header")?;
|
||||
let len = rest.iter().take(max + 1).position(|&c| c == 0).ok_or("truncated header or name too long")?;
|
||||
let s = std::str::from_utf8(rest.get(..len).unwrap_or(&[])).map_err(|_| "name is not UTF-8")?;
|
||||
*pos += len + 1;
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
fn parse_chlist(v: &[u8], name_max: usize) -> Result<Vec<(String, SampleKind)>, String> {
|
||||
let mut pos = 0;
|
||||
let mut out: Vec<(String, SampleKind)> = Vec::new();
|
||||
loop {
|
||||
let name = cstr(v, &mut pos, name_max)?;
|
||||
if name.is_empty() {
|
||||
break;
|
||||
}
|
||||
let f = take(v, &mut pos, 16)?;
|
||||
// pixel type, pLinear + reserved, xSampling, ySampling
|
||||
let &[kind, _, x_sampling, y_sampling] = f.as_chunks::<4>().0 else {
|
||||
return Err("truncated header".into());
|
||||
};
|
||||
let kind = SampleKind::from_code(i32::from_le_bytes(kind)).ok_or_else(|| format!("channel '{name}': unknown pixel type"))?;
|
||||
if i32::from_le_bytes(x_sampling) != 1 || i32::from_le_bytes(y_sampling) != 1 {
|
||||
return Err(format!("channel '{name}': subsampled channels are not supported"));
|
||||
}
|
||||
out.push((name.to_string(), kind));
|
||||
}
|
||||
// Pixel data is laid out in name order whatever order the list was written in (OpenEXR keeps it in a map).
|
||||
out.sort_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes()));
|
||||
if out.windows(2).any(|p| matches!(p, [a, b] if a.0 == b.0)) {
|
||||
return Err("duplicate channel name".into());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn header_round_trip() {
|
||||
let h = Header {
|
||||
channels: vec![("B".into(), SampleKind::Half), ("G".into(), SampleKind::Float), ("R".into(), SampleKind::Uint)],
|
||||
compression: Compression::Zip,
|
||||
data_window: [0, 0, 99, 49],
|
||||
};
|
||||
let mut b = Vec::new();
|
||||
h.write(&mut b);
|
||||
let (back, end) = Header::read(&b).unwrap();
|
||||
assert_eq!(back, h);
|
||||
assert_eq!(end, b.len());
|
||||
assert_eq!((back.width(), back.height(), back.line_bytes()), (100, 50, 1000));
|
||||
for n in 0..b.len() {
|
||||
assert!(Header::read(&b[..n]).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
//! OpenEXR read/write for single-part scanline images with HALF, FLOAT or UINT channels at full resolution.
|
||||
//! Writes NONE, ZIPS or ZIP compression and also reads RLE.
|
||||
//!
|
||||
//! ```
|
||||
//! use craft_material_graph::exr::{self, ExrChannel, ExrImage, SampleKind};
|
||||
//! let img = ExrImage { width: 2, height: 1, channels: vec![ExrChannel::new("R", SampleKind::Half, vec![0.5, 4.0])] };
|
||||
//! let back = exr::decode(&exr::encode(&img).unwrap()).unwrap();
|
||||
//! assert_eq!(back, img);
|
||||
//! ```
|
||||
|
||||
mod compression;
|
||||
mod decode;
|
||||
mod encode;
|
||||
mod header;
|
||||
// Main's dependency-free Tex writers (uncompressed EXR and Radiance HDR) used by export; merged in from main
|
||||
// unchanged and re-exported so `exr::encode_exr` etc. keep their paths.
|
||||
mod tex_writers;
|
||||
|
||||
pub use compression::Compression;
|
||||
pub use decode::decode;
|
||||
pub use encode::{encode, encode_with};
|
||||
pub use tex_writers::{encode_exr, encode_hdr, f32_to_half, half_to_f32};
|
||||
|
||||
/// Stored sample type of a channel. Samples are handled as f32: HALF values convert exactly both ways after the
|
||||
/// first rounding, UINT values are exact up to 2^24.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum SampleKind {
|
||||
Uint,
|
||||
Half,
|
||||
Float,
|
||||
}
|
||||
|
||||
impl SampleKind {
|
||||
fn code(self) -> i32 {
|
||||
match self {
|
||||
SampleKind::Uint => 0,
|
||||
SampleKind::Half => 1,
|
||||
SampleKind::Float => 2,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_code(c: i32) -> Option<Self> {
|
||||
match c {
|
||||
0 => Some(SampleKind::Uint),
|
||||
1 => Some(SampleKind::Half),
|
||||
2 => Some(SampleKind::Float),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes per stored sample.
|
||||
fn size(self) -> usize {
|
||||
match self {
|
||||
SampleKind::Half => 2,
|
||||
SampleKind::Uint | SampleKind::Float => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One channel: `data` holds `width * height` samples, row-major, top row first.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ExrChannel {
|
||||
pub name: String,
|
||||
pub sample: SampleKind,
|
||||
pub data: Vec<f32>,
|
||||
}
|
||||
|
||||
impl ExrChannel {
|
||||
pub fn new(name: &str, sample: SampleKind, data: Vec<f32>) -> Self {
|
||||
ExrChannel { name: name.to_string(), sample, data }
|
||||
}
|
||||
}
|
||||
|
||||
/// A scanline image. Channel order is free; files store channels sorted by name and `decode` returns them that way.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ExrImage {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub channels: Vec<ExrChannel>,
|
||||
}
|
||||
|
||||
impl ExrImage {
|
||||
pub fn channel(&self, name: &str) -> Option<&ExrChannel> {
|
||||
self.channels.iter().find(|c| c.name == name)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample_image(w: usize, h: usize) -> ExrImage {
|
||||
let ramp = |k: f32| (0..w * h).map(|i| ((i % w) as f32 / w as f32 + (i / w) as f32 * k) * 3.0 - 0.5).collect::<Vec<f32>>();
|
||||
let half = |v: Vec<f32>| v.into_iter().map(|x| crate::half::f16_to_f32(crate::half::f32_to_f16(x))).collect::<Vec<f32>>();
|
||||
ExrImage {
|
||||
width: w,
|
||||
height: h,
|
||||
channels: vec![
|
||||
ExrChannel::new("A", SampleKind::Half, half(ramp(0.01))),
|
||||
ExrChannel::new("B", SampleKind::Float, ramp(0.3)),
|
||||
ExrChannel::new("G", SampleKind::Half, half(ramp(-0.2))),
|
||||
ExrChannel::new("R", SampleKind::Float, ramp(1.0)),
|
||||
ExrChannel::new("id", SampleKind::Uint, (0..w * h).map(|i| (i * 7 % 1000) as f32).collect()),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_every_compression() {
|
||||
for (w, h) in [(1, 1), (5, 3), (64, 40), (300, 17)] {
|
||||
let img = sample_image(w, h);
|
||||
for c in [Compression::None, Compression::Zips, Compression::Zip] {
|
||||
let bytes = encode_with(&img, c).unwrap();
|
||||
assert_eq!(decode(&bytes).unwrap(), img, "{w}x{h} {c:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channels_are_sorted_on_write() {
|
||||
let mut img = sample_image(4, 4);
|
||||
img.channels.reverse();
|
||||
let back = decode(&encode(&img).unwrap()).unwrap();
|
||||
let names: Vec<&str> = back.channels.iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(names, ["A", "B", "G", "R", "id"]);
|
||||
assert_eq!(back.channel("R"), img.channel("R"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn special_values_survive() {
|
||||
let v = vec![0.0, -0.0, f32::INFINITY, f32::NEG_INFINITY, 65504.0, 6.0e-8, 1e30, -1e-30];
|
||||
let img = ExrImage {
|
||||
width: 8,
|
||||
height: 1,
|
||||
channels: vec![ExrChannel::new("F", SampleKind::Float, v.clone()), ExrChannel::new("H", SampleKind::Half, v)],
|
||||
};
|
||||
let back = decode(&encode(&img).unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
back.channels[0].data.iter().map(|x| x.to_bits()).collect::<Vec<_>>(),
|
||||
img.channels[0].data.iter().map(|x| x.to_bits()).collect::<Vec<_>>()
|
||||
);
|
||||
let h = &back.channels[1].data;
|
||||
assert_eq!((h[2], h[3], h[4]), (f32::INFINITY, f32::NEG_INFINITY, 65504.0));
|
||||
assert_eq!((h[5], h[6]), (crate::half::f16_to_f32(1), f32::INFINITY));
|
||||
assert!(h[7] == 0.0 && h[7].is_sign_negative());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_images_are_rejected() {
|
||||
let bad = |img: ExrImage| assert!(encode(&img).is_err());
|
||||
bad(ExrImage { width: 0, height: 1, channels: vec![ExrChannel::new("R", SampleKind::Half, vec![])] });
|
||||
bad(ExrImage { width: 1, height: 1, channels: vec![] });
|
||||
bad(ExrImage { width: 2, height: 1, channels: vec![ExrChannel::new("R", SampleKind::Half, vec![1.0])] });
|
||||
bad(ExrImage {
|
||||
width: 1,
|
||||
height: 1,
|
||||
channels: vec![ExrChannel::new("R", SampleKind::Half, vec![1.0]), ExrChannel::new("R", SampleKind::Float, vec![1.0])],
|
||||
});
|
||||
bad(ExrImage { width: 1, height: 1, channels: vec![ExrChannel::new("", SampleKind::Half, vec![1.0])] });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncations_and_corruption_error() {
|
||||
let img = sample_image(9, 20);
|
||||
for c in [Compression::None, Compression::Zip] {
|
||||
let bytes = encode_with(&img, c).unwrap();
|
||||
for n in 0..bytes.len() {
|
||||
assert!(decode(&bytes[..n]).is_err(), "{c:?} prefix {n}");
|
||||
}
|
||||
// Flipping bytes must never panic (it may or may not be detected).
|
||||
for i in (0..bytes.len()).step_by(3) {
|
||||
let mut b = bytes.clone();
|
||||
b[i] ^= 0x5a;
|
||||
let _ = decode(&b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Dependency-free writers for high dynamic range images: OpenEXR (uncompressed scanlines, half or float RGBA) and
|
||||
//! Radiance HDR (RGBE). EXR writes values as they are, so results above 1.0 or below 0.0 survive (to the sample
|
||||
//! precision); RGBE stores no sign, so negative components become zero.
|
||||
use crate::math;
|
||||
use crate::tex::Tex;
|
||||
|
||||
/// f32 -> IEEE half, rounded to nearest even; overflow becomes infinity, tiny values become zero or subnormals.
|
||||
pub fn f32_to_half(f: f32) -> u16 {
|
||||
let b = f.to_bits();
|
||||
let sign = ((b >> 16) & 0x8000) as u16;
|
||||
let exp = ((b >> 23) & 0xff) as i32;
|
||||
let man = b & 0x007f_ffff;
|
||||
if exp == 0xff {
|
||||
return sign | 0x7c00 | if man != 0 { 0x200 } else { 0 };
|
||||
}
|
||||
let e = exp - 127 + 15;
|
||||
if e >= 0x1f {
|
||||
return sign | 0x7c00;
|
||||
}
|
||||
if e <= 0 {
|
||||
if e < -10 {
|
||||
return sign;
|
||||
}
|
||||
let m = man | 0x0080_0000;
|
||||
let shift = (14 - e) as u32;
|
||||
let mut h = (m >> shift) as u16;
|
||||
let rem = m & ((1 << shift) - 1);
|
||||
let half = 1u32 << (shift - 1);
|
||||
if rem > half || (rem == half && (h & 1) == 1) {
|
||||
h += 1;
|
||||
}
|
||||
return sign | h;
|
||||
}
|
||||
let mut h = sign | ((e as u16) << 10) | (man >> 13) as u16;
|
||||
let rem = man & 0x1fff;
|
||||
if rem > 0x1000 || (rem == 0x1000 && (h & 1) == 1) {
|
||||
h += 1; // may carry into the exponent, which is the correct rounding
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
fn attr(out: &mut Vec<u8>, name: &str, ty: &str, value: &[u8]) {
|
||||
out.extend_from_slice(name.as_bytes());
|
||||
out.push(0);
|
||||
out.extend_from_slice(ty.as_bytes());
|
||||
out.push(0);
|
||||
out.extend_from_slice(&(value.len() as i32).to_le_bytes());
|
||||
out.extend_from_slice(value);
|
||||
}
|
||||
|
||||
/// OpenEXR, single part, scanline, no compression. `float` selects 32-bit float channels, otherwise half.
|
||||
pub fn encode_exr(t: &Tex, float: bool) -> Vec<u8> {
|
||||
let (w, h) = (t.w, t.h);
|
||||
let ptype: i32 = if float { 2 } else { 1 };
|
||||
let bytes = if float { 4 } else { 2 };
|
||||
let mut out = vec![0x76, 0x2f, 0x31, 0x01, 2, 0, 0, 0];
|
||||
let mut ch = Vec::new();
|
||||
for name in ["A", "B", "G", "R"] {
|
||||
ch.extend_from_slice(name.as_bytes());
|
||||
ch.push(0);
|
||||
ch.extend_from_slice(&ptype.to_le_bytes());
|
||||
ch.extend_from_slice(&[0, 0, 0, 0]); // pLinear + 3 reserved
|
||||
ch.extend_from_slice(&1i32.to_le_bytes());
|
||||
ch.extend_from_slice(&1i32.to_le_bytes());
|
||||
}
|
||||
ch.push(0);
|
||||
attr(&mut out, "channels", "chlist", &ch);
|
||||
attr(&mut out, "compression", "compression", &[0]);
|
||||
let mut bx = Vec::new();
|
||||
for v in [0i32, 0, w as i32 - 1, h as i32 - 1] {
|
||||
bx.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
attr(&mut out, "dataWindow", "box2i", &bx);
|
||||
attr(&mut out, "displayWindow", "box2i", &bx);
|
||||
attr(&mut out, "lineOrder", "lineOrder", &[0]);
|
||||
attr(&mut out, "pixelAspectRatio", "float", &1.0f32.to_le_bytes());
|
||||
let mut sc = Vec::new();
|
||||
sc.extend_from_slice(&0.0f32.to_le_bytes());
|
||||
sc.extend_from_slice(&0.0f32.to_le_bytes());
|
||||
attr(&mut out, "screenWindowCenter", "v2f", &sc);
|
||||
attr(&mut out, "screenWindowWidth", "float", &1.0f32.to_le_bytes());
|
||||
out.push(0); // end of header
|
||||
let line_bytes = 4 * w * bytes;
|
||||
let table = out.len();
|
||||
let first = table + 8 * h;
|
||||
for y in 0..h {
|
||||
out.extend_from_slice(&((first + y * (8 + line_bytes)) as u64).to_le_bytes());
|
||||
}
|
||||
for y in 0..h {
|
||||
out.extend_from_slice(&(y as i32).to_le_bytes());
|
||||
out.extend_from_slice(&(line_bytes as u32).to_le_bytes());
|
||||
for c in [3usize, 2, 1, 0] {
|
||||
for x in 0..w {
|
||||
// A short pixel buffer (never the case for a valid Tex) reads as zeros instead of panicking.
|
||||
let v = t.px.get(y * w + x).and_then(|p| p.get(c)).copied().unwrap_or(0.0);
|
||||
if float {
|
||||
out.extend_from_slice(&v.to_le_bytes());
|
||||
} else {
|
||||
out.extend_from_slice(&f32_to_half(v).to_le_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Radiance RGBE (`.hdr`), uncompressed pixels, alpha is dropped.
|
||||
pub fn encode_hdr(t: &Tex) -> Vec<u8> {
|
||||
let mut out = format!("#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y {} +X {}\n", t.h, t.w).into_bytes();
|
||||
for p in &t.px {
|
||||
let m = p[0].max(p[1]).max(p[2]);
|
||||
// (NaN too: it isn't finite)
|
||||
if m <= 1e-32 || !m.is_finite() {
|
||||
out.extend_from_slice(&[0, 0, 0, 0]);
|
||||
continue;
|
||||
}
|
||||
// m = frac * 2^e with frac in [0.5, 1)
|
||||
let e = math::log2(m).floor() as i32 + 1;
|
||||
let scale = 256.0 / math::powi(2f32, e);
|
||||
out.extend_from_slice(&[(p[0].max(0.0) * scale) as u8, (p[1].max(0.0) * scale) as u8, (p[2].max(0.0) * scale) as u8, (e + 128) as u8]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// IEEE half -> f32 (exact).
|
||||
pub fn half_to_f32(h: u16) -> f32 {
|
||||
let sign = if h & 0x8000 != 0 { -1.0f32 } else { 1.0 };
|
||||
let e = ((h >> 10) & 0x1f) as i32;
|
||||
let m = (h & 0x3ff) as f32;
|
||||
match e {
|
||||
0 => sign * m * math::powi(2.0f32, -24),
|
||||
0x1f => {
|
||||
if m == 0.0 {
|
||||
sign * f32::INFINITY
|
||||
} else {
|
||||
f32::NAN
|
||||
}
|
||||
}
|
||||
_ => sign * (1.0 + m / 1024.0) * math::powi(2.0f32, e - 15),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,514 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Fonts for the text node: a small built-in bitmap face and a reader for TrueType outline fonts (`.ttf`).
|
||||
//!
|
||||
//! The reader handles the common case: a single TrueType face with a Unicode `cmap` (format 4 or 12) and `glyf`
|
||||
//! outlines, including composite glyphs. Not supported: OpenType/CFF outlines (`.otf`), font collections, hinting,
|
||||
//! kerning, complex-script shaping and composite components placed by matching points (only x/y offsets).
|
||||
|
||||
use crate::vector::{P, Poly, Seg, Xf, flatten};
|
||||
|
||||
pub const GLYPHS: [[u8; 10]; 95] = [
|
||||
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
[0, 4, 4, 4, 4, 4, 0, 4, 0, 0],
|
||||
[0, 10, 10, 0, 0, 0, 0, 0, 0, 0],
|
||||
[0, 10, 10, 31, 10, 31, 10, 10, 0, 0],
|
||||
[0, 4, 15, 20, 14, 5, 30, 4, 0, 0],
|
||||
[0, 25, 25, 2, 4, 8, 19, 19, 0, 0],
|
||||
[0, 12, 18, 20, 8, 21, 18, 13, 0, 0],
|
||||
[0, 4, 4, 0, 0, 0, 0, 0, 0, 0],
|
||||
[0, 2, 4, 8, 8, 8, 4, 2, 0, 0],
|
||||
[0, 8, 4, 2, 2, 2, 4, 8, 0, 0],
|
||||
[0, 0, 21, 14, 31, 14, 21, 0, 0, 0],
|
||||
[0, 0, 4, 4, 31, 4, 4, 0, 0, 0],
|
||||
[0, 0, 0, 0, 0, 12, 4, 8, 0, 0],
|
||||
[0, 0, 0, 0, 31, 0, 0, 0, 0, 0],
|
||||
[0, 0, 0, 0, 0, 0, 12, 12, 0, 0],
|
||||
[0, 1, 1, 2, 4, 8, 16, 16, 0, 0],
|
||||
[0, 14, 17, 19, 21, 25, 17, 14, 0, 0],
|
||||
[0, 4, 12, 4, 4, 4, 4, 14, 0, 0],
|
||||
[0, 14, 17, 1, 2, 4, 8, 31, 0, 0],
|
||||
[0, 30, 1, 1, 14, 1, 1, 30, 0, 0],
|
||||
[0, 2, 6, 10, 18, 31, 2, 2, 0, 0],
|
||||
[0, 31, 16, 30, 1, 1, 17, 14, 0, 0],
|
||||
[0, 14, 16, 16, 30, 17, 17, 14, 0, 0],
|
||||
[0, 31, 1, 2, 4, 8, 8, 8, 0, 0],
|
||||
[0, 14, 17, 17, 14, 17, 17, 14, 0, 0],
|
||||
[0, 14, 17, 17, 15, 1, 1, 14, 0, 0],
|
||||
[0, 0, 12, 12, 0, 12, 12, 0, 0, 0],
|
||||
[0, 0, 12, 12, 0, 12, 4, 8, 0, 0],
|
||||
[0, 2, 4, 8, 16, 8, 4, 2, 0, 0],
|
||||
[0, 0, 0, 31, 0, 31, 0, 0, 0, 0],
|
||||
[0, 8, 4, 2, 1, 2, 4, 8, 0, 0],
|
||||
[0, 14, 17, 1, 2, 4, 0, 4, 0, 0],
|
||||
[0, 14, 17, 23, 21, 23, 16, 14, 0, 0],
|
||||
[0, 14, 17, 17, 31, 17, 17, 17, 0, 0],
|
||||
[0, 30, 17, 17, 30, 17, 17, 30, 0, 0],
|
||||
[0, 14, 17, 16, 16, 16, 17, 14, 0, 0],
|
||||
[0, 30, 17, 17, 17, 17, 17, 30, 0, 0],
|
||||
[0, 31, 16, 16, 30, 16, 16, 31, 0, 0],
|
||||
[0, 31, 16, 16, 30, 16, 16, 16, 0, 0],
|
||||
[0, 14, 17, 16, 23, 17, 17, 15, 0, 0],
|
||||
[0, 17, 17, 17, 31, 17, 17, 17, 0, 0],
|
||||
[0, 14, 4, 4, 4, 4, 4, 14, 0, 0],
|
||||
[0, 7, 2, 2, 2, 2, 18, 12, 0, 0],
|
||||
[0, 17, 18, 20, 24, 20, 18, 17, 0, 0],
|
||||
[0, 16, 16, 16, 16, 16, 16, 31, 0, 0],
|
||||
[0, 17, 27, 21, 21, 17, 17, 17, 0, 0],
|
||||
[0, 17, 25, 21, 19, 17, 17, 17, 0, 0],
|
||||
[0, 14, 17, 17, 17, 17, 17, 14, 0, 0],
|
||||
[0, 30, 17, 17, 30, 16, 16, 16, 0, 0],
|
||||
[0, 14, 17, 17, 17, 21, 18, 13, 0, 0],
|
||||
[0, 30, 17, 17, 30, 20, 18, 17, 0, 0],
|
||||
[0, 15, 16, 16, 14, 1, 1, 30, 0, 0],
|
||||
[0, 31, 4, 4, 4, 4, 4, 4, 0, 0],
|
||||
[0, 17, 17, 17, 17, 17, 17, 14, 0, 0],
|
||||
[0, 17, 17, 17, 17, 17, 10, 4, 0, 0],
|
||||
[0, 17, 17, 17, 21, 21, 27, 17, 0, 0],
|
||||
[0, 17, 17, 10, 4, 10, 17, 17, 0, 0],
|
||||
[0, 17, 17, 10, 4, 4, 4, 4, 0, 0],
|
||||
[0, 31, 1, 2, 4, 8, 16, 31, 0, 0],
|
||||
[0, 14, 8, 8, 8, 8, 8, 14, 0, 0],
|
||||
[0, 16, 16, 8, 4, 2, 1, 1, 0, 0],
|
||||
[0, 14, 2, 2, 2, 2, 2, 14, 0, 0],
|
||||
[0, 4, 10, 17, 0, 0, 0, 0, 0, 0],
|
||||
[0, 0, 0, 0, 0, 0, 0, 31, 0, 0],
|
||||
[0, 8, 4, 0, 0, 0, 0, 0, 0, 0],
|
||||
[0, 0, 0, 14, 1, 15, 17, 15, 0, 0],
|
||||
[0, 16, 16, 30, 17, 17, 17, 30, 0, 0],
|
||||
[0, 0, 0, 14, 17, 16, 17, 14, 0, 0],
|
||||
[0, 1, 1, 15, 17, 17, 17, 15, 0, 0],
|
||||
[0, 0, 0, 14, 17, 31, 16, 14, 0, 0],
|
||||
[0, 6, 9, 8, 28, 8, 8, 8, 0, 0],
|
||||
[0, 0, 0, 15, 17, 17, 15, 1, 17, 14],
|
||||
[0, 16, 16, 30, 17, 17, 17, 17, 0, 0],
|
||||
[0, 4, 0, 12, 4, 4, 4, 14, 0, 0],
|
||||
[0, 2, 0, 6, 2, 2, 2, 2, 18, 12],
|
||||
[0, 16, 16, 18, 20, 24, 20, 18, 0, 0],
|
||||
[0, 12, 4, 4, 4, 4, 4, 14, 0, 0],
|
||||
[0, 0, 0, 26, 21, 21, 21, 21, 0, 0],
|
||||
[0, 0, 0, 30, 17, 17, 17, 17, 0, 0],
|
||||
[0, 0, 0, 14, 17, 17, 17, 14, 0, 0],
|
||||
[0, 0, 0, 30, 17, 17, 30, 16, 16, 16],
|
||||
[0, 0, 0, 15, 17, 17, 15, 1, 1, 1],
|
||||
[0, 0, 0, 22, 25, 16, 16, 16, 0, 0],
|
||||
[0, 0, 0, 15, 16, 14, 1, 30, 0, 0],
|
||||
[0, 8, 8, 30, 8, 8, 9, 6, 0, 0],
|
||||
[0, 0, 0, 17, 17, 17, 19, 13, 0, 0],
|
||||
[0, 0, 0, 17, 17, 17, 10, 4, 0, 0],
|
||||
[0, 0, 0, 17, 17, 21, 21, 10, 0, 0],
|
||||
[0, 0, 0, 17, 10, 4, 10, 17, 0, 0],
|
||||
[0, 0, 0, 17, 17, 17, 15, 1, 17, 14],
|
||||
[0, 0, 0, 31, 2, 4, 8, 31, 0, 0],
|
||||
[0, 6, 8, 8, 16, 8, 8, 6, 0, 0],
|
||||
[0, 4, 4, 4, 4, 4, 4, 4, 0, 0],
|
||||
[0, 12, 2, 2, 1, 2, 2, 12, 0, 0],
|
||||
[0, 0, 0, 13, 22, 0, 0, 0, 0, 0],
|
||||
];
|
||||
|
||||
pub enum Font {
|
||||
Builtin,
|
||||
TrueType(Box<Ttf>),
|
||||
}
|
||||
|
||||
pub struct Ttf {
|
||||
data: Vec<u8>,
|
||||
units: f32,
|
||||
loca: usize,
|
||||
loca_long: bool,
|
||||
glyf: usize,
|
||||
glyf_len: usize,
|
||||
hmtx: usize,
|
||||
n_hmtx: usize,
|
||||
n_glyphs: usize,
|
||||
cmap: Vec<(u32, u32, u32, i32)>, // start, end, first glyph or 0 for delta mapping, delta
|
||||
cmap4: Option<(usize, usize)>,
|
||||
ascent: f32,
|
||||
}
|
||||
|
||||
fn u16_at(d: &[u8], o: usize) -> Option<u16> {
|
||||
let b = d.get(o..o.checked_add(2)?)?;
|
||||
Some(u16::from_be_bytes(b.try_into().ok()?))
|
||||
}
|
||||
fn i16_at(d: &[u8], o: usize) -> Option<i16> {
|
||||
u16_at(d, o).map(|v| v as i16)
|
||||
}
|
||||
fn u32_at(d: &[u8], o: usize) -> Option<u32> {
|
||||
let b = d.get(o..o.checked_add(4)?)?;
|
||||
Some(u32::from_be_bytes(b.try_into().ok()?))
|
||||
}
|
||||
|
||||
impl Ttf {
|
||||
pub fn parse(data: &[u8]) -> Result<Ttf, String> {
|
||||
let tag = data.get(0..4).ok_or("font file is too short")?;
|
||||
if tag == b"OTTO" {
|
||||
return Err("OpenType fonts with CFF outlines are not supported; use a TrueType (.ttf) font".into());
|
||||
}
|
||||
if tag == b"ttcf" {
|
||||
return Err("font collections (.ttc) are not supported".into());
|
||||
}
|
||||
if tag != [0, 1, 0, 0] && tag != b"true" {
|
||||
return Err("not a TrueType font".into());
|
||||
}
|
||||
let n = u16_at(data, 4).ok_or("bad font header")? as usize;
|
||||
let table = |name: &[u8; 4]| -> Option<(usize, usize)> {
|
||||
(0..n).find_map(|i| {
|
||||
let r = 12 + i * 16;
|
||||
if data.get(r..r + 4)? == name { Some((u32_at(data, r + 8)? as usize, u32_at(data, r + 12)? as usize)) } else { None }
|
||||
})
|
||||
};
|
||||
let (head, _) = table(b"head").ok_or("font has no head table")?;
|
||||
let (maxp, _) = table(b"maxp").ok_or("font has no maxp table")?;
|
||||
let (hhea, _) = table(b"hhea").ok_or("font has no hhea table")?;
|
||||
let (hmtx, _) = table(b"hmtx").ok_or("font has no hmtx table")?;
|
||||
let (loca, _) = table(b"loca").ok_or("font has no loca table (not a TrueType outline font)")?;
|
||||
let (glyf, glyf_len) = table(b"glyf").ok_or("font has no glyf table (not a TrueType outline font)")?;
|
||||
let (cmap, cmap_len) = table(b"cmap").ok_or("font has no cmap table")?;
|
||||
let units = u16_at(data, head + 18).ok_or("bad head table")? as f32;
|
||||
if units < 16.0 {
|
||||
return Err("bad units-per-em".into());
|
||||
}
|
||||
let loca_long = i16_at(data, head + 50).ok_or("bad head table")? != 0;
|
||||
let n_glyphs = u16_at(data, maxp + 4).ok_or("bad maxp table")? as usize;
|
||||
let n_hmtx = u16_at(data, hhea + 34).ok_or("bad hhea table")? as usize;
|
||||
let ascent = i16_at(data, hhea + 4).ok_or("bad hhea table")? as f32;
|
||||
// pick a Unicode subtable
|
||||
let count = u16_at(data, cmap + 2).ok_or("bad cmap")? as usize;
|
||||
let mut best: Option<(usize, u16)> = None;
|
||||
for i in 0..count {
|
||||
let r = cmap + 4 + i * 8;
|
||||
let (pid, eid, off) =
|
||||
(u16_at(data, r).ok_or("bad cmap")?, u16_at(data, r + 2).ok_or("bad cmap")?, u32_at(data, r + 4).ok_or("bad cmap")? as usize);
|
||||
let fmt = u16_at(data, cmap + off).unwrap_or(0);
|
||||
let unicode = pid == 0 || (pid == 3 && (eid == 1 || eid == 10));
|
||||
if unicode && (fmt == 4 || fmt == 12) && best.map(|b| fmt == 12 && b.1 != 12).unwrap_or(true) {
|
||||
best = Some((cmap + off, fmt));
|
||||
}
|
||||
}
|
||||
let (sub, fmt) = best.ok_or("font has no Unicode character map this reader understands")?;
|
||||
let _ = cmap_len;
|
||||
let mut font =
|
||||
Ttf { data: data.to_vec(), units, loca, loca_long, glyf, glyf_len, hmtx, n_hmtx, n_glyphs, cmap: Vec::new(), cmap4: None, ascent };
|
||||
if fmt == 12 {
|
||||
let groups = u32_at(data, sub + 12).ok_or("bad cmap")? as usize;
|
||||
for g in 0..groups.min(100_000) {
|
||||
let r = sub + 16 + g * 12;
|
||||
let (s, e, gl) = (u32_at(data, r).ok_or("bad cmap")?, u32_at(data, r + 4).ok_or("bad cmap")?, u32_at(data, r + 8).ok_or("bad cmap")?);
|
||||
font.cmap.push((s, e, gl, 0));
|
||||
}
|
||||
} else {
|
||||
font.cmap4 = Some((sub, 0));
|
||||
}
|
||||
Ok(font)
|
||||
}
|
||||
|
||||
pub fn glyph_index(&self, ch: char) -> usize {
|
||||
let c = ch as u32;
|
||||
if let Some((sub, _)) = self.cmap4 {
|
||||
let d = &self.data;
|
||||
let segx2 = u16_at(d, sub + 6).unwrap_or(0) as usize;
|
||||
let seg = segx2 / 2;
|
||||
let ends = sub + 14;
|
||||
let starts = ends + segx2 + 2;
|
||||
let deltas = starts + segx2;
|
||||
let ranges = deltas + segx2;
|
||||
for i in 0..seg {
|
||||
let end = u16_at(d, ends + i * 2).unwrap_or(0) as u32;
|
||||
if c <= end {
|
||||
let start = u16_at(d, starts + i * 2).unwrap_or(0) as u32;
|
||||
if c < start {
|
||||
return 0;
|
||||
}
|
||||
let delta = i16_at(d, deltas + i * 2).unwrap_or(0) as i32;
|
||||
let ro = u16_at(d, ranges + i * 2).unwrap_or(0) as usize;
|
||||
let g = if ro == 0 {
|
||||
(c as i32 + delta) as u32 & 0xffff
|
||||
} else {
|
||||
let at = ranges + i * 2 + ro + (c - start) as usize * 2;
|
||||
match u16_at(d, at) {
|
||||
Some(0) | None => 0,
|
||||
Some(g) => (g as i32 + delta) as u32 & 0xffff,
|
||||
}
|
||||
};
|
||||
return g as usize;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
for &(s, e, g, _) in &self.cmap {
|
||||
if c >= s && c <= e {
|
||||
return g.wrapping_add(c - s) as usize;
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
pub fn advance(&self, glyph: usize) -> f32 {
|
||||
let i = glyph.min(self.n_hmtx.saturating_sub(1));
|
||||
u16_at(&self.data, self.hmtx + i * 4).unwrap_or(0) as f32 / self.units
|
||||
}
|
||||
|
||||
fn glyph_range(&self, g: usize) -> Option<(usize, usize)> {
|
||||
if g >= self.n_glyphs {
|
||||
return None;
|
||||
}
|
||||
let (a, b) = if self.loca_long {
|
||||
(u32_at(&self.data, self.loca + g * 4)? as usize, u32_at(&self.data, self.loca + g * 4 + 4)? as usize)
|
||||
} else {
|
||||
(u16_at(&self.data, self.loca + g * 2)? as usize * 2, u16_at(&self.data, self.loca + g * 2 + 2)? as usize * 2)
|
||||
};
|
||||
if b <= a || b > self.glyf_len {
|
||||
return None;
|
||||
}
|
||||
Some((self.glyf + a, self.glyf + b))
|
||||
}
|
||||
|
||||
/// Outline in em units (y up), as path segments.
|
||||
pub fn outline(&self, glyph: usize, depth: u32) -> Vec<Seg> {
|
||||
let mut segs = Vec::new();
|
||||
let Some((start, end)) = self.glyph_range(glyph) else { return segs };
|
||||
// the table directory's glyf length is not checked against the file size
|
||||
let d = self.data.get(..end).unwrap_or(&self.data);
|
||||
let Some(nc) = i16_at(d, start) else { return segs };
|
||||
let u = self.units;
|
||||
if nc >= 0 {
|
||||
let nc = nc as usize;
|
||||
let mut o = start + 10;
|
||||
let mut ends = Vec::with_capacity(nc);
|
||||
for _ in 0..nc {
|
||||
let Some(e) = u16_at(d, o) else { return segs };
|
||||
ends.push(e as usize);
|
||||
o += 2;
|
||||
}
|
||||
let npts = ends.last().map(|e| e + 1).unwrap_or(0);
|
||||
let Some(il) = u16_at(d, o) else { return segs };
|
||||
o += 2 + il as usize;
|
||||
let mut flags = Vec::with_capacity(npts);
|
||||
while flags.len() < npts {
|
||||
let Some(&f) = d.get(o) else { return segs };
|
||||
o += 1;
|
||||
flags.push(f);
|
||||
if f & 8 != 0 {
|
||||
let Some(&r) = d.get(o) else { return segs };
|
||||
o += 1;
|
||||
for _ in 0..r {
|
||||
if flags.len() < npts {
|
||||
flags.push(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut read = |short: u8, same: u8| -> Option<Vec<i32>> {
|
||||
let mut v = Vec::with_capacity(npts);
|
||||
let mut cur = 0i32;
|
||||
for &f in &flags {
|
||||
if f & short != 0 {
|
||||
let b = *d.get(o)? as i32;
|
||||
o += 1;
|
||||
cur = cur.wrapping_add(if f & same != 0 { b } else { -b });
|
||||
} else if f & same == 0 {
|
||||
cur = cur.wrapping_add(i16_at(d, o)? as i32);
|
||||
o += 2;
|
||||
}
|
||||
v.push(cur);
|
||||
}
|
||||
Some(v)
|
||||
};
|
||||
let (Some(xs), Some(ys)) = (read(2, 16), read(4, 32)) else { return segs };
|
||||
let mut first = 0usize;
|
||||
for &e in &ends {
|
||||
if e < first || e >= npts {
|
||||
break;
|
||||
}
|
||||
let (Some(xr), Some(yr), Some(fr)) = (xs.get(first..=e), ys.get(first..=e), flags.get(first..=e)) else { break };
|
||||
let pts: Vec<(P, bool)> = xr.iter().zip(yr).zip(fr).map(|((&x, &y), &f)| ([x as f32 / u, y as f32 / u], f & 1 != 0)).collect();
|
||||
contour(&pts, &mut segs);
|
||||
first = e + 1;
|
||||
}
|
||||
} else if depth < 4 {
|
||||
let mut o = start + 10;
|
||||
while let (Some(fl), Some(gi)) = (u16_at(d, o), u16_at(d, o + 2)) {
|
||||
o += 4;
|
||||
let (dx, dy) = if fl & 1 != 0 {
|
||||
let r = (i16_at(d, o).unwrap_or(0) as f32, i16_at(d, o + 2).unwrap_or(0) as f32);
|
||||
o += 4;
|
||||
r
|
||||
} else {
|
||||
let r = (*d.get(o).unwrap_or(&0) as i8 as f32, *d.get(o + 1).unwrap_or(&0) as i8 as f32);
|
||||
o += 2;
|
||||
r
|
||||
};
|
||||
let f2 = |o: usize| i16_at(d, o).unwrap_or(0) as f32 / 16384.0;
|
||||
let (mut a, mut b, mut c, mut dd) = (1.0, 0.0, 0.0, 1.0);
|
||||
if fl & 8 != 0 {
|
||||
a = f2(o);
|
||||
dd = a;
|
||||
o += 2;
|
||||
} else if fl & 0x40 != 0 {
|
||||
a = f2(o);
|
||||
dd = f2(o + 2);
|
||||
o += 4;
|
||||
} else if fl & 0x80 != 0 {
|
||||
a = f2(o);
|
||||
b = f2(o + 2);
|
||||
c = f2(o + 4);
|
||||
dd = f2(o + 6);
|
||||
o += 8;
|
||||
}
|
||||
// only offsets are supported for placing a component (point matching is rare)
|
||||
let (dx, dy) = if fl & 2 != 0 { (dx / u, dy / u) } else { (0.0, 0.0) };
|
||||
let xf = Xf([a, b, c, dd, dx, dy]);
|
||||
for s in self.outline(gi as usize, depth + 1) {
|
||||
segs.push(match s {
|
||||
Seg::Move(p) => Seg::Move(xf.apply(p)),
|
||||
Seg::Line(p) => Seg::Line(xf.apply(p)),
|
||||
Seg::Quad(c1, p) => Seg::Quad(xf.apply(c1), xf.apply(p)),
|
||||
Seg::Cubic(c1, c2, p) => Seg::Cubic(xf.apply(c1), xf.apply(c2), xf.apply(p)),
|
||||
Seg::Close => Seg::Close,
|
||||
});
|
||||
}
|
||||
if fl & 0x20 == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
segs
|
||||
}
|
||||
}
|
||||
|
||||
fn contour(pts: &[(P, bool)], out: &mut Vec<Seg>) {
|
||||
if pts.len() < 2 {
|
||||
return;
|
||||
}
|
||||
let mid = |a: P, b: P| [(a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5];
|
||||
// start at an on-curve point, or at the midpoint of two off-curve points
|
||||
let n = pts.len();
|
||||
let (Some(&(p_first, _)), Some(&(p_last, _))) = (pts.first(), pts.last()) else { return };
|
||||
let (start, begin) = match pts.iter().enumerate().find(|(_, p)| p.1) {
|
||||
Some((i, p)) => (p.0, i + 1),
|
||||
None => (mid(p_first, p_last), 0),
|
||||
};
|
||||
out.push(Seg::Move(start));
|
||||
let mut ctrl: Option<P> = None;
|
||||
let count = if pts.iter().any(|p| p.1) { n - 1 } else { n };
|
||||
for k in 0..count {
|
||||
let Some(&(p, on)) = pts.get((begin + k) % n) else { continue };
|
||||
match (ctrl, on) {
|
||||
(None, true) => out.push(Seg::Line(p)),
|
||||
(None, false) => ctrl = Some(p),
|
||||
(Some(c), true) => {
|
||||
out.push(Seg::Quad(c, p));
|
||||
ctrl = None;
|
||||
}
|
||||
(Some(c), false) => {
|
||||
out.push(Seg::Quad(c, mid(c, p)));
|
||||
ctrl = Some(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(c) = ctrl {
|
||||
out.push(Seg::Quad(c, start));
|
||||
}
|
||||
out.push(Seg::Close);
|
||||
}
|
||||
|
||||
impl Font {
|
||||
pub fn load(bytes: &[u8]) -> Result<Font, String> {
|
||||
Ok(Font::TrueType(Box::new(Ttf::parse(bytes)?)))
|
||||
}
|
||||
|
||||
/// Advance of one character in em units.
|
||||
fn advance(&self, ch: char) -> f32 {
|
||||
match self {
|
||||
Font::Builtin => 0.65,
|
||||
Font::TrueType(t) => t.advance(t.glyph_index(ch)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Line height in em units.
|
||||
pub fn line_height(&self) -> f32 {
|
||||
match self {
|
||||
Font::Builtin => 1.2,
|
||||
Font::TrueType(t) => (t.ascent / t.units * 1.45).max(1.0),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ascent(&self) -> f32 {
|
||||
match self {
|
||||
Font::Builtin => 0.9,
|
||||
Font::TrueType(t) => t.ascent / t.units,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn text_width(&self, line: &str, spacing: f32) -> f32 {
|
||||
line.chars().map(|c| self.advance(c) + spacing).sum::<f32>() - if line.is_empty() { 0.0 } else { spacing }
|
||||
}
|
||||
|
||||
/// Glyph outlines of one character as polygons in em units (y down, baseline at 0), origin at the pen.
|
||||
fn glyph_polys(&self, ch: char, pen: f32, xf_after: &Xf) -> Vec<Poly> {
|
||||
match self {
|
||||
Font::Builtin => {
|
||||
let code = ch as u32;
|
||||
if !(32..127).contains(&code) {
|
||||
return vec![];
|
||||
}
|
||||
let Some(rows) = GLYPHS.get((code - 32) as usize) else { return vec![] };
|
||||
// 5 x 10 cell: 1 em = 9 rows, cap height is 7 rows, baseline below row 7
|
||||
let px = 1.0 / 9.0 * 0.9;
|
||||
let mut out = Vec::new();
|
||||
for (r, bits) in rows.iter().enumerate() {
|
||||
for c in 0..5 {
|
||||
if bits & (1 << (4 - c)) != 0 {
|
||||
let x0 = pen + c as f32 * px * 1.0;
|
||||
let y0 = (r as f32 - 8.0) * px;
|
||||
out.push(Poly {
|
||||
pts: vec![
|
||||
xf_after.apply([x0, y0]),
|
||||
xf_after.apply([x0 + px, y0]),
|
||||
xf_after.apply([x0 + px, y0 + px]),
|
||||
xf_after.apply([x0, y0 + px]),
|
||||
],
|
||||
closed: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
Font::TrueType(t) => {
|
||||
let segs = t.outline(t.glyph_index(ch), 0);
|
||||
// font units are y-up: flip, then move to the pen position
|
||||
let xf = Xf([1.0, 0.0, 0.0, -1.0, pen, 0.0]).then(*xf_after);
|
||||
flatten(&segs, &xf)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lay out text (lines split at '\n') as polygons in pixel space.
|
||||
/// `size`: em height in pixels; `align`: 0 left, 1 centre, 2 right; the block is centred on (0, 0) and moved by `xf`.
|
||||
pub fn layout(&self, text: &str, size: f32, align: u32, spacing: f32, line_spacing: f32, xf: &Xf) -> Vec<Poly> {
|
||||
let lines: Vec<&str> = text.split('\n').collect();
|
||||
let lh = self.line_height() * line_spacing;
|
||||
let block_h = lh * lines.len() as f32;
|
||||
let mut out = Vec::new();
|
||||
for (li, line) in lines.iter().enumerate() {
|
||||
let w = self.text_width(line, spacing);
|
||||
let mut pen = match align {
|
||||
1 => -w * 0.5,
|
||||
2 => -w,
|
||||
_ => 0.0,
|
||||
};
|
||||
if align == 0 {
|
||||
pen = -self.text_width(lines.iter().max_by_key(|l| l.chars().count()).unwrap_or(&""), spacing) * 0.5;
|
||||
} else if align == 2 {
|
||||
pen += self.text_width(lines.iter().max_by_key(|l| l.chars().count()).unwrap_or(&""), spacing) * 0.5;
|
||||
}
|
||||
let base_y = (li as f32 + 0.5) * lh - block_h * 0.5 + self.ascent() * 0.35;
|
||||
for ch in line.chars() {
|
||||
let local = Xf::translate(0.0, base_y).then(Xf::scale(size, size)).then(*xf);
|
||||
out.extend(self.glyph_polys(ch, pen, &local));
|
||||
pen += self.advance(ch) + spacing;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,277 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! The form a function graph runs in: a flat table of instructions, one register per node, plus what is known about each
|
||||
//! node without running it. A node's *class* says what its value can depend on:
|
||||
//!
|
||||
//! * `Const`: nothing (literals and what is computed from them only). Computed once for a [`super::vm::Frame`].
|
||||
//! * `Env`: the caller's environment (size, seed, inputs, images, but not the position). Once per binding.
|
||||
//! * `Run`: the position. Once per run.
|
||||
//! * variables (`f_get`), or an `f_set`, `f_random` or `f_loop` (`impure`): once per run and again in each pass of a loop.
|
||||
//!
|
||||
//! The first three cannot be told apart from running them every time, except by the time it takes.
|
||||
|
||||
use super::{Op, Prog, Value, coerce, loop_passes, type_pin};
|
||||
use crate::graph::Pin;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// "No such operand / table entry".
|
||||
pub const NONE: u32 = u32::MAX;
|
||||
|
||||
/// Indices into `Frame::floors`: a register is valid when its stamp is at or above the floor its instruction names.
|
||||
pub const FLOOR_CONST: u32 = 0;
|
||||
pub const FLOOR_ENV: u32 = 1;
|
||||
pub const FLOOR_RUN: u32 = 2;
|
||||
pub const FLOOR_PASS: u32 = 3;
|
||||
pub const FLOORS: usize = 4;
|
||||
|
||||
/// The compiled value and size sites restart from the given seed for each indexed draw.
|
||||
/// They neither read the pixel position nor change the caller's generator state.
|
||||
pub(super) fn indexed_lcg_draw(site: i32) -> bool {
|
||||
matches!(site, 2 | 5)
|
||||
}
|
||||
|
||||
pub struct Inst {
|
||||
pub op: Op,
|
||||
pub impure: bool,
|
||||
/// operands in slot order, already past any `f_pin`
|
||||
pub ins: [u32; 4],
|
||||
/// variable of an `f_set` / `f_get`, or index into the table of its kind
|
||||
pub x: u32,
|
||||
/// the type an `f_get` declares ([`Code::get_pins`])
|
||||
pub y: u32,
|
||||
}
|
||||
|
||||
/// An `f_input` / `f_graph_input`.
|
||||
pub struct InputInfo {
|
||||
pub pin: Pin,
|
||||
pub default: Value,
|
||||
/// for `f_input`, where its value is bound in `Frame::args`
|
||||
pub arg: u32,
|
||||
}
|
||||
|
||||
/// The image slot and sampling mode of an image read.
|
||||
pub struct SampleInfo {
|
||||
pub slot: String,
|
||||
pub filter: Option<u32>,
|
||||
}
|
||||
|
||||
pub struct Code {
|
||||
pub insts: Vec<Inst>,
|
||||
/// Initial validity class of each register.
|
||||
pub floor: Vec<u32>,
|
||||
pub out: u32,
|
||||
pub literals: Vec<(u32, Value)>,
|
||||
pub vec_defaults: Vec<[f64; 4]>,
|
||||
/// reads of a swizzle: `None` when the mask is not plain (the slow path then reports the problem)
|
||||
pub swizzles: Vec<Option<([u8; 4], u8)>>,
|
||||
pub seeds: Vec<u32>,
|
||||
pub samples: Vec<SampleInfo>,
|
||||
pub inputs: Vec<InputInfo>,
|
||||
pub passes: Vec<usize>,
|
||||
/// the site and draw number `k` of a random number drawn as compiled graphs draw it (see `lcg_rand`); `None` for the plain sequence
|
||||
pub lcg_draws: Vec<Option<(i32, u32)>>,
|
||||
pub get_pins: Vec<Option<Pin>>,
|
||||
pub var_names: Vec<String>,
|
||||
pub arg_names: Vec<String>,
|
||||
/// where each of `Prog::inputs` is bound
|
||||
pub input_args: Vec<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum Class {
|
||||
Const,
|
||||
Env,
|
||||
Run,
|
||||
Vars,
|
||||
Impure,
|
||||
}
|
||||
|
||||
pub fn build(p: &Prog) -> Code {
|
||||
let n = p.nodes.len();
|
||||
// an `f_pin` / `f_out` is its source: both finish together, so both are valid together
|
||||
let mut alias: Vec<u32> = (0..n as u32).collect();
|
||||
for (i, node) in p.nodes.iter().enumerate() {
|
||||
// (a node's inputs come before it)
|
||||
if matches!(node.op, Op::Out | Op::Pin)
|
||||
&& let Some(j) = node.ins[0]
|
||||
&& let Some(a) = alias.get(j).copied()
|
||||
&& let Some(d) = alias.get_mut(i)
|
||||
{
|
||||
*d = a;
|
||||
}
|
||||
}
|
||||
let mut c = Code {
|
||||
insts: Vec::with_capacity(n),
|
||||
floor: vec![FLOOR_CONST; n],
|
||||
out: alias.get(p.out).copied().unwrap_or(NONE),
|
||||
literals: Vec::new(),
|
||||
vec_defaults: Vec::new(),
|
||||
swizzles: Vec::new(),
|
||||
seeds: Vec::new(),
|
||||
samples: Vec::new(),
|
||||
inputs: Vec::new(),
|
||||
passes: Vec::new(),
|
||||
lcg_draws: Vec::new(),
|
||||
get_pins: Vec::new(),
|
||||
var_names: Vec::new(),
|
||||
arg_names: Vec::new(),
|
||||
input_args: Vec::new(),
|
||||
};
|
||||
let mut var_ids: HashMap<&str, u32> = HashMap::new();
|
||||
let mut arg_ids: HashMap<&str, u32> = HashMap::new();
|
||||
let mut class = vec![Class::Const; n];
|
||||
for (name, _, _) in &p.inputs {
|
||||
let next = arg_ids.len() as u32;
|
||||
let a = *arg_ids.entry(name.as_str()).or_insert(next);
|
||||
if a == next {
|
||||
c.arg_names.push(name.clone());
|
||||
}
|
||||
c.input_args.push(a);
|
||||
}
|
||||
for (i, node) in p.nodes.iter().enumerate() {
|
||||
let num = |k: &str| node.num.get(k).copied().unwrap_or(0.0);
|
||||
let mut inst = Inst { op: node.op, impure: false, ins: [NONE; 4], x: NONE, y: NONE };
|
||||
for (d, j) in inst.ins.iter_mut().zip(node.ins) {
|
||||
if let Some(j) = j {
|
||||
*d = alias.get(j).copied().unwrap_or(NONE);
|
||||
}
|
||||
}
|
||||
let var_of = |name: &str, c: &mut Code| -> u32 {
|
||||
if let Some(v) = var_ids.get(name) {
|
||||
return *v;
|
||||
}
|
||||
let v = c.var_names.len() as u32;
|
||||
c.var_names.push(name.to_string());
|
||||
v
|
||||
};
|
||||
let mut own = match node.op {
|
||||
Op::Float
|
||||
| Op::Int
|
||||
| Op::Bool
|
||||
| Op::Str
|
||||
| Op::Out
|
||||
| Op::Pin
|
||||
| Op::Vec(..)
|
||||
| Op::Swizzle
|
||||
| Op::Un(_)
|
||||
| Op::Bin(_)
|
||||
| Op::Clamp
|
||||
| Op::Lerp
|
||||
| Op::Smooth
|
||||
| Op::If
|
||||
| Op::Seq => Class::Const,
|
||||
Op::ToFloat | Op::ToInt | Op::ToBool | Op::ToStr | Op::Concat => Class::Const,
|
||||
Op::Stat(_)
|
||||
| Op::Size
|
||||
| Op::OwnSize
|
||||
| Op::CellSize
|
||||
| Op::CellDepth
|
||||
| Op::Index
|
||||
| Op::Count
|
||||
| Op::Seed
|
||||
| Op::Input
|
||||
| Op::GraphInput
|
||||
| Op::SampleGray
|
||||
| Op::SampleColor => Class::Env,
|
||||
Op::Pos | Op::Call => Class::Run,
|
||||
Op::Get => Class::Vars,
|
||||
Op::Set | Op::Loop | Op::Random => Class::Impure,
|
||||
};
|
||||
match node.op {
|
||||
Op::Float => c.literals.push((i as u32, Value::float(num("v")))),
|
||||
Op::Int => c.literals.push((i as u32, Value::int(num("v").trunc() as i64))),
|
||||
Op::Bool => c.literals.push((i as u32, Value::Bool(num("v") != 0.0))),
|
||||
Op::Str => c.literals.push((i as u32, Value::text(&node.text))),
|
||||
Op::Vec(..) => {
|
||||
inst.x = c.vec_defaults.len() as u32;
|
||||
c.vec_defaults.push([num("x"), num("y"), num("z"), num("w")]);
|
||||
}
|
||||
Op::Swizzle => {
|
||||
inst.x = c.swizzles.len() as u32;
|
||||
c.swizzles.push(plain_mask(&node.text));
|
||||
}
|
||||
Op::Random => {
|
||||
inst.x = c.seeds.len() as u32;
|
||||
c.seeds.push(num("seed") as u32);
|
||||
c.lcg_draws.push(node.num.contains_key("lcg").then(|| (num("lcg") as i32, num("k") as u32)));
|
||||
}
|
||||
Op::SampleGray | Op::SampleColor => {
|
||||
inst.x = c.samples.len() as u32;
|
||||
let slot = if node.name.is_empty() { "in".to_string() } else { node.name.clone() };
|
||||
c.samples.push(SampleInfo { slot, filter: node.num.get("filter").map(|f| *f as u32) });
|
||||
}
|
||||
Op::Input | Op::GraphInput => {
|
||||
let pin = type_pin(num("type").round() as i32);
|
||||
let default = match pin {
|
||||
Pin::Bool => Value::Bool(num("v") != 0.0),
|
||||
Pin::Text => Value::text(&node.text),
|
||||
q if q.lanes() == 1 => coerce(&Value::float(num("v")), q),
|
||||
q => coerce(&Value::vec(q.lanes() as u8, [num("x"), num("y"), num("z"), num("w")]), q),
|
||||
};
|
||||
let mut arg = NONE;
|
||||
if node.op == Op::Input {
|
||||
let next = arg_ids.len() as u32;
|
||||
arg = *arg_ids.entry(node.name.as_str()).or_insert(next);
|
||||
if arg == next {
|
||||
c.arg_names.push(node.name.clone());
|
||||
}
|
||||
}
|
||||
inst.x = c.inputs.len() as u32;
|
||||
c.inputs.push(InputInfo { pin, default, arg });
|
||||
}
|
||||
Op::Loop => {
|
||||
inst.x = c.passes.len() as u32;
|
||||
c.passes.push(loop_passes(&node.num));
|
||||
}
|
||||
Op::Set | Op::Get => {
|
||||
let v = var_of(&node.name, &mut c);
|
||||
var_ids.insert(node.name.as_str(), v);
|
||||
inst.x = v;
|
||||
if node.op == Op::Get {
|
||||
inst.y = c.get_pins.len() as u32;
|
||||
// a declared type shapes what is read; the value's own shape otherwise
|
||||
c.get_pins.push(if node.num.contains_key("type") { Some(type_pin(num("type").round() as i32)) } else { None });
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// a call starts with variables and random numbers of its own, so nothing in it is visible here but the result, which
|
||||
// depends at most on the position
|
||||
for j in inst.ins.iter().copied().filter(|j| *j != NONE) {
|
||||
own = own.max(class.get(j as usize).copied().unwrap_or(Class::Const));
|
||||
}
|
||||
if let Some(d) = class.get_mut(i) {
|
||||
*d = own;
|
||||
}
|
||||
inst.impure = own == Class::Impure;
|
||||
if let Some(d) = c.floor.get_mut(i) {
|
||||
*d = match own {
|
||||
Class::Const => FLOOR_CONST,
|
||||
Class::Env => FLOOR_ENV,
|
||||
Class::Run => FLOOR_RUN,
|
||||
Class::Impure | Class::Vars => FLOOR_PASS,
|
||||
};
|
||||
}
|
||||
c.insts.push(inst);
|
||||
}
|
||||
|
||||
c
|
||||
}
|
||||
|
||||
fn plain_mask(mask: &str) -> Option<([u8; 4], u8)> {
|
||||
let (mut idx, mut len) = ([0u8; 4], 0usize);
|
||||
for ch in mask.chars() {
|
||||
if len == 4 {
|
||||
return None;
|
||||
}
|
||||
let slot = idx.get_mut(len)?;
|
||||
*slot = match ch {
|
||||
'x' | 'r' => 0,
|
||||
'y' | 'g' => 1,
|
||||
'z' | 'b' => 2,
|
||||
'w' | 'a' => 3,
|
||||
_ => return None,
|
||||
};
|
||||
len += 1;
|
||||
}
|
||||
(len > 0).then_some((idx, len as u8))
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Holds the fast interpreter to the reference tree walk: random functions, heavy on the things whose order matters
|
||||
//! (variables, loops, random numbers, nodes shared between users), must give the same results, the same errors and
|
||||
//! leave the same variables and random position.
|
||||
|
||||
use super::*;
|
||||
use crate::math;
|
||||
use crate::tex::Tex;
|
||||
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
fn below(&mut self, n: usize) -> usize {
|
||||
(self.next() % n.max(1) as u64) as usize
|
||||
}
|
||||
fn chance(&mut self, pct: usize) -> bool {
|
||||
self.below(100) < pct
|
||||
}
|
||||
}
|
||||
|
||||
const VARS: [&str; 4] = ["a", "b", "c", "long_name"];
|
||||
|
||||
/// Text of a random function of about `n` nodes. `style` shifts what it is made of.
|
||||
fn random_function(r: &mut Rng, n: usize, style: usize, callee: Option<&str>) -> String {
|
||||
let mut lines = Vec::new();
|
||||
let mut at = 2u32;
|
||||
let pick = |r: &mut Rng, at: u32| -> u32 {
|
||||
// mostly recent nodes, so chains build up and nodes get shared
|
||||
if at <= 2 {
|
||||
return 2;
|
||||
}
|
||||
if r.chance(70) { at - 1 - r.below((at as usize - 2).min(6)) as u32 } else { 2 + r.below(at as usize - 2) as u32 }
|
||||
};
|
||||
lines.push("node 2 f_float v=1.5".to_string());
|
||||
at += 1;
|
||||
for _ in 0..n {
|
||||
let (x, y, z) = (pick(r, at), pick(r, at), pick(r, at));
|
||||
let v = VARS[r.below(VARS.len())];
|
||||
let kinds = match style {
|
||||
0 => r.below(14),
|
||||
1 => [6, 7, 7, 8, 9, 9, 10, 0, 11, 8, 6, 13][r.below(12)],
|
||||
_ => r.below(30),
|
||||
};
|
||||
let line = match kinds {
|
||||
0 => format!("f_add a=@{x} b=@{y}"),
|
||||
1 => format!("f_mul a=@{x} b=@{y}"),
|
||||
2 => format!("f_float v={}", r.below(9) as f32 * 0.25 - 1.0),
|
||||
3 => "f_pos".to_string(),
|
||||
4 => format!("f_vec2 x=@{x} y=@{y}"),
|
||||
5 => format!("f_swizzle a=@{x} mask=\"{}\"", ["x", "yx", "xy", "z", "xxyy", "q"][r.below(6)]),
|
||||
6 => format!("f_set a=@{x} name=\"{v}\""),
|
||||
7 => format!("f_get name=\"{v}\""),
|
||||
8 => format!("f_sequence a=@{x} b=@{y}"),
|
||||
9 => {
|
||||
lines.push(format!("node {at} f_gt a=@{x} b=@{y}"));
|
||||
at += 1;
|
||||
format!("f_if cond=@{} a=@{y} b=@{z}", at - 1)
|
||||
}
|
||||
10 => match r.below(4) {
|
||||
0 => format!("f_random seed={} b=@{x} s=@{y} lcg={} k={}", r.below(3), [1, 2, 3, 5, 10, 12][r.below(6)], r.below(3)),
|
||||
_ => format!("f_random seed={} b=@{x}", r.below(3)),
|
||||
},
|
||||
11 => {
|
||||
if r.chance(50) {
|
||||
format!("f_loop a=@{x} c=@{y} passes={}", r.below(4))
|
||||
} else {
|
||||
lines.push(format!("node {at} f_gt a=@{x} b=@{z}"));
|
||||
at += 1;
|
||||
format!("f_loop a=@{x} b=@{} c=@{y} passes={}", at - 1, r.below(5))
|
||||
}
|
||||
}
|
||||
12 => format!("f_sub a=@{x} b=@{y}"),
|
||||
13 => format!("f_to_float a=@{x}"),
|
||||
14 => format!("f_to_int a=@{x}"),
|
||||
15 => format!("f_int v={}", r.below(6)),
|
||||
16 => format!("f_get name=\"{v}\" type={}", [0, 1, 3, 4, 5, 2][r.below(6)]),
|
||||
17 => "f_size".to_string(),
|
||||
18 => "f_index".to_string(),
|
||||
19 => format!("f_input name=\"p{}\" type={} v=0.25", r.below(3), r.below(6)),
|
||||
20 => format!("f_graph_input name=\"g{}\" type={} v=0.5", r.below(3), r.below(6)),
|
||||
21 => format!("f_sample_gray a=@{x}"),
|
||||
22 => format!("f_sample_color a=@{x} filter={}", r.below(4)),
|
||||
23 => format!("f_lerp a=@{x} b=@{y} c=@{z}"),
|
||||
24 => format!("f_div_large a=@{x} b=@{y}"),
|
||||
25 => format!("f_to_bool a=@{x}"),
|
||||
26 => match callee {
|
||||
Some(f) => format!("f_call fn=\"{f}\" a=@{x} b=@{y} d=@{z}"),
|
||||
None => "f_seed".to_string(),
|
||||
},
|
||||
27 => format!("f_string v=\"t{}\"", r.below(2)),
|
||||
28 => "f_image_avg".to_string(),
|
||||
_ => format!("f_vec3 x=@{x} z=@{y}"),
|
||||
};
|
||||
lines.push(format!("node {at} {line}"));
|
||||
at += 1;
|
||||
}
|
||||
// reach a good part of what was made, in sequence
|
||||
let mut last = at - 1;
|
||||
for _ in 0..r.below(6) {
|
||||
let x = 2 + r.below(at as usize - 2) as u32;
|
||||
lines.push(format!("node {at} f_sequence a=@{x} b=@{last}"));
|
||||
last = at;
|
||||
at += 1;
|
||||
}
|
||||
lines.push(format!("node 1 f_out in=@{last}"));
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
fn same_result(a: &Result<Value, String>, b: &Result<Value, String>) -> bool {
|
||||
match (a, b) {
|
||||
(Ok(Value::Num(x)), Ok(Value::Num(y))) => x.lanes == y.lanes && x.int == y.int && x.v.map(f64::to_bits) == y.v.map(f64::to_bits),
|
||||
_ => a == b,
|
||||
}
|
||||
}
|
||||
|
||||
fn sorted(s: &FnState) -> Vec<(String, Value)> {
|
||||
let mut v = s.vars.clone();
|
||||
v.sort_by(|p, q| p.0.cmp(&q.0));
|
||||
// a variable set to what an unset one reads as is the same to everything that can look
|
||||
v.retain(|(_, x)| *x != Value::float(0.0));
|
||||
v
|
||||
}
|
||||
|
||||
fn check(src: &str, lib: &BTreeMap<String, Graph>, images: &[(&str, &Tex)], ginputs: &BTreeMap<String, Value>) -> (bool, bool) {
|
||||
let g = Graph::parse_unchecked(&format!("meta kind \"function\"\n{src}")).unwrap_or_else(|e| panic!("{e:?}\n{src}"));
|
||||
let Ok(p) = Prog::compile(&g, lib) else { return (false, false) };
|
||||
let mut env = FnEnv::new([16.0, 32.0]);
|
||||
env.seed = 5;
|
||||
env.index = 3;
|
||||
env.graph_inputs = ginputs;
|
||||
env.images = images.iter().map(|(n, t)| (*n, (*t).into())).collect();
|
||||
env = env.with_stats();
|
||||
env.args.insert("p1".into(), Value::vec(2, [0.5, -0.5, 0.0, 0.0]));
|
||||
let mut frame = p.frame();
|
||||
p.bind(&env, &mut frame);
|
||||
let mut any_ok = false;
|
||||
// the same frame over several runs: what carries over must not show
|
||||
for pos in [[0.25, 0.75], [0.5, 0.5], [0.25, 0.75], [0.0, 1.0]] {
|
||||
let want = p.ref_run(&env, pos);
|
||||
let got = p.run_bound(&env, pos, &mut frame);
|
||||
assert!(same_result(&want, &got), "at {pos:?}: reference {want:?}, got {got:?}\n{src}");
|
||||
any_ok |= want.is_ok();
|
||||
}
|
||||
// carried state: a run that starts from what the last one left
|
||||
let (mut sa, mut sb) = (FnState::default(), FnState::default());
|
||||
let mut f2 = p.frame();
|
||||
p.bind(&env, &mut f2);
|
||||
for pos in [[0.25, 0.75], [0.5, 0.5], [0.5, 0.5]] {
|
||||
let want = p.ref_run_in(&env, pos, &mut sa);
|
||||
let got = p.run_in_bound(&env, pos, &mut sb, &mut f2);
|
||||
assert!(same_result(&want, &got), "in state at {pos:?}: reference {want:?}, got {got:?}\n{src}");
|
||||
assert_eq!(sa.rng, sb.rng, "random position differs\n{src}");
|
||||
assert_eq!(sa.lcg_state, sb.lcg_state, "generator state differs\n{src}");
|
||||
assert_eq!(sorted(&sa), sorted(&sb), "variables differ\n{src}");
|
||||
}
|
||||
// a new binding: nothing from the old environment may survive
|
||||
env.seed = 9;
|
||||
env.index = 4;
|
||||
env.args.insert("p0".into(), Value::float(2.0));
|
||||
p.bind(&env, &mut frame);
|
||||
for pos in [[0.25, 0.75], [0.5, 0.5]] {
|
||||
let want = p.ref_run(&env, pos);
|
||||
let got = p.run_bound(&env, pos, &mut frame);
|
||||
assert!(same_result(&want, &got), "after rebinding at {pos:?}: reference {want:?}, got {got:?}\n{src}");
|
||||
}
|
||||
(true, any_ok)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_functions_match_the_reference() {
|
||||
let tex = Tex::from_fn(4, 4, |u, v| [u, v, u * v, 1.0]);
|
||||
let images: Vec<(&str, &Tex)> = vec![("in", &tex)];
|
||||
let mut ginputs = BTreeMap::new();
|
||||
ginputs.insert("g1".to_string(), Value::int(3));
|
||||
ginputs.insert("g0".to_string(), Value::vec(3, [1.0, 2.0, 3.0, 0.0]));
|
||||
let mut r = Rng(0x9E3779B97F4A7C15);
|
||||
let (mut compiled, mut ran) = (0, 0);
|
||||
let rounds = std::env::var("TC_FUZZ_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(6000);
|
||||
for round in 0..rounds {
|
||||
let n = 3 + r.below(if round % 10 == 0 { 45 } else { 18 });
|
||||
let mut lib = BTreeMap::new();
|
||||
let callee_src = random_function(&mut r, 6, round % 2, None);
|
||||
lib.insert(
|
||||
"callee".to_string(),
|
||||
Graph::parse_unchecked(&format!("meta kind \"function\"\nnode 90 f_input name=\"p0\"\nnode 91 f_input name=\"p1\" type=3\n{callee_src}"))
|
||||
.unwrap_or_else(|e| panic!("{e:?}")),
|
||||
);
|
||||
let src = random_function(&mut r, n, round % 3, Some("callee"));
|
||||
let (c, k) = check(&src, &lib, &images, &ginputs);
|
||||
compiled += c as usize;
|
||||
ran += k as usize;
|
||||
}
|
||||
// a generator that only makes broken functions would prove nothing
|
||||
eprintln!("{rounds} functions: {compiled} compiled, {ran} ran");
|
||||
assert!(compiled > rounds / 2 && ran > rounds / 4, "compiled {compiled}, ran {ran}");
|
||||
}
|
||||
|
||||
/// A sum of terms where each term sets variables from the sum before it, reading that sum twice: each node runs once.
|
||||
fn doubling(terms: usize) -> String {
|
||||
let mut s = String::from("node 2 f_float v=1\nnode 3 f_set a=@2 name=\"v\"\n");
|
||||
let mut sum = 3u32;
|
||||
let mut at = 4u32;
|
||||
for k in 0..terms {
|
||||
s += &format!("node {at} f_float v={}\n", k as f32 * 0.5);
|
||||
s += &format!("node {} f_set a=@{at} name=\"v\"\n", at + 1);
|
||||
s += &format!("node {} f_set a=@{sum} name=\"w\"\n", at + 2);
|
||||
s += &format!("node {} f_sequence a=@{} b=@{}\n", at + 3, at + 1, at + 2);
|
||||
s += &format!("node {} f_add a=@{sum} b=@{}\n", at + 4, at + 3);
|
||||
sum = at + 4;
|
||||
at += 5;
|
||||
}
|
||||
s += &format!("node 1 f_out in=@{sum}\n");
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chains_that_read_themselves_twice_stay_linear() {
|
||||
let lib = BTreeMap::new();
|
||||
let env = FnEnv::new([8.0, 8.0]);
|
||||
let small = Graph::parse_unchecked(&format!("meta kind \"function\"\n{}", doubling(12))).unwrap();
|
||||
let p = Prog::compile(&small, &lib).unwrap();
|
||||
assert_eq!(p.ref_run(&env, [0.5, 0.5]), p.run(&env, [0.5, 0.5]));
|
||||
let large = Graph::parse_unchecked(&format!("meta kind \"function\"\n{}", doubling(200))).unwrap();
|
||||
let p = Prog::compile(&large, &lib).unwrap();
|
||||
let mut f = p.frame();
|
||||
p.bind(&env, &mut f);
|
||||
p.run_bound(&env, [0.5, 0.5], &mut f).unwrap();
|
||||
assert!(f.counts.computed < 10_000, "{:?}", f.counts);
|
||||
}
|
||||
|
||||
/// Not a test: `TC_COUNT_GRAPH=x.tcgraph cargo test --release --lib func::differential::count -- --ignored --nocapture` shows how
|
||||
/// much a run of each function of a graph computes, which is where its time goes.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn count_work_of_a_graph() {
|
||||
let path = std::env::var("TC_COUNT_GRAPH").unwrap_or_default();
|
||||
let g = Graph::parse(&std::fs::read_to_string(path).unwrap_or_default()).unwrap_or_else(|e| panic!("{e:?}"));
|
||||
let tex = Tex::from_fn(8, 8, |u, v| [u, v, u * v, 1.0]);
|
||||
let names: Vec<&String> = g.subgraphs.iter().filter(|(_, f)| is_function(f)).map(|(k, _)| k).collect();
|
||||
let ginputs = graph_inputs(&g);
|
||||
let mut rows = Vec::new();
|
||||
for name in names {
|
||||
let Ok(p) = compile_named(&g.subgraphs, name) else { continue };
|
||||
let mut env = FnEnv::new([64.0, 64.0]);
|
||||
env.graph_inputs = &ginputs;
|
||||
for slot in crate::graph::IMAGE_SLOTS {
|
||||
env.images.push((slot, (&tex).into()));
|
||||
}
|
||||
env = env.with_stats();
|
||||
let mut f = p.frame();
|
||||
p.bind(&env, &mut f);
|
||||
let first = p.run_bound(&env, [0.3, 0.7], &mut f);
|
||||
let c1 = f.counts;
|
||||
for k in 0..20 {
|
||||
let _ = p.run_bound(&env, [0.3 + 0.01 * k as f64, 0.2], &mut f);
|
||||
}
|
||||
let c2 = f.counts;
|
||||
let t = std::time::Instant::now();
|
||||
let mut runs = 0;
|
||||
while t.elapsed().as_secs_f64() < 0.02 && runs < 2000 {
|
||||
let _ = p.run_bound(&env, [0.3 + 0.001 * (runs % 500) as f64, 0.2], &mut f);
|
||||
runs += 1;
|
||||
}
|
||||
let per_run = t.elapsed().as_secs_f64() / runs as f64 * 1e6;
|
||||
rows.push((c2.computed - c1.computed, name.clone(), p.nodes.len(), c1, c2, per_run, first.is_ok()));
|
||||
}
|
||||
rows.sort_by_key(|r| std::cmp::Reverse(r.0));
|
||||
for r in rows.iter().take(8) {
|
||||
println!("{:>12} per 20 runs {} nodes={} first={:?} after={:?} {:.1}us/run ok={}", r.0, r.1, r.2, r.3, r.4, r.5, r.6);
|
||||
}
|
||||
}
|
||||
|
||||
/// Not a test by default: `TC_GRAPH_CORPUS=dir cargo test --release --lib func::differential::corpus -- --ignored --nocapture` runs
|
||||
/// every function of every `.tcgraph` in `dir` with the reference and the fast form, at a few positions over one frame. Functions
|
||||
/// the reference can't finish within its step budget are counted as skipped, not as matching.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn corpus_functions_match_the_reference() {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
let dir = std::env::var("TC_GRAPH_CORPUS").unwrap_or_default();
|
||||
let budget = std::env::var("TC_GRAPH_BUDGET").ok().and_then(|v| v.parse().ok()).unwrap_or(3_000_000u64);
|
||||
let threads = std::env::var("TC_GRAPH_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(8usize);
|
||||
let filter = std::env::var("TC_GRAPH_ONLY").unwrap_or_default();
|
||||
let mut files: Vec<_> = std::fs::read_dir(&dir)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().path())
|
||||
.filter(|p| p.extension().is_some_and(|x| x == "tcgraph") && p.to_string_lossy().contains(&filter))
|
||||
.collect();
|
||||
files.sort();
|
||||
let tex = Tex::from_fn(16, 16, |u, v| [u, v, math::sin(u * 37.0).abs(), 0.5 + 0.5 * math::cos(v * 23.0)]);
|
||||
let next = AtomicUsize::new(0);
|
||||
let (same, skipped, failed, errors) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0));
|
||||
let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).stack_size(64 << 20).build().unwrap();
|
||||
pool.scope(|s| {
|
||||
for _ in 0..threads {
|
||||
s.spawn(|_| {
|
||||
loop {
|
||||
let Some(path) = files.get(next.fetch_add(1, Ordering::Relaxed)) else { return };
|
||||
let Ok(g) = Graph::parse(&std::fs::read_to_string(path).unwrap_or_default()) else { continue };
|
||||
let ginputs = graph_inputs(&g);
|
||||
let (mut ok, mut skip, mut bad, mut err) = (0, 0, 0, 0);
|
||||
for (name, f) in g.subgraphs.iter().filter(|(_, f)| is_function(f)) {
|
||||
let Ok(p) = compile_named(&g.subgraphs, name) else { continue };
|
||||
let _ = f;
|
||||
let mut env = FnEnv::new([64.0, 128.0]);
|
||||
env.graph_inputs = &ginputs;
|
||||
env.seed = 3;
|
||||
for slot in crate::graph::IMAGE_SLOTS.iter().take(4) {
|
||||
env.images.push((slot, (&tex).into()));
|
||||
}
|
||||
if p.uses_stats {
|
||||
env = env.with_stats();
|
||||
}
|
||||
let mut frame = p.frame();
|
||||
p.bind(&env, &mut frame);
|
||||
for pos in [[0.5, 0.5], [0.1, 0.8], [0.73, 0.21], [0.1, 0.8]] {
|
||||
let want = p.ref_run_budget(&env, pos, budget);
|
||||
let got = p.run_bound(&env, pos, &mut frame);
|
||||
if matches!(&want, Err(e) if e == reference::OVER_BUDGET) {
|
||||
skip += 1;
|
||||
} else if same_result(&want, &got) {
|
||||
ok += 1;
|
||||
err += want.is_err() as usize;
|
||||
} else {
|
||||
bad += 1;
|
||||
eprintln!("DIFF {} {name} at {pos:?}: reference {want:?}, got {got:?}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
println!("{} same {ok} (errors {err}) skipped {skip} different {bad}", path.file_stem().unwrap_or_default().to_string_lossy());
|
||||
same.fetch_add(ok, Ordering::Relaxed);
|
||||
skipped.fetch_add(skip, Ordering::Relaxed);
|
||||
failed.fetch_add(bad, Ordering::Relaxed);
|
||||
errors.fetch_add(err, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
println!(
|
||||
"TOTAL same {} (of which errors {}) skipped {} different {}",
|
||||
same.into_inner(),
|
||||
errors.into_inner(),
|
||||
skipped.into_inner(),
|
||||
failed.load(Ordering::Relaxed)
|
||||
);
|
||||
assert_eq!(failed.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! The tree walk that defines what function graphs mean, node by node with a memo that every pass of a loop clears. It stays
|
||||
//! here so the tests can hold [`super::vm`] to it.
|
||||
|
||||
use super::*;
|
||||
|
||||
struct State {
|
||||
memo: Vec<Option<(Value, u64)>>,
|
||||
epoch: u64,
|
||||
vars: Vec<(String, Value)>,
|
||||
rng: u32,
|
||||
/// The state of the compiled-graph generator (`lcg_rand`), once it has started.
|
||||
lcg_state: Option<u32>,
|
||||
steps: u64,
|
||||
/// steps this run may take before it gives up with [`OVER_BUDGET`]: some real functions would take longer than the universe has
|
||||
budget: u64,
|
||||
}
|
||||
|
||||
pub(super) const OVER_BUDGET: &str = "node over budget";
|
||||
|
||||
impl Prog {
|
||||
/// Run the function at `pos` (uv, 0..1).
|
||||
pub(super) fn ref_run(&self, env: &FnEnv, pos: [f64; 2]) -> Result<Value, String> {
|
||||
self.ref_run_budget(env, pos, u64::MAX)
|
||||
}
|
||||
|
||||
/// [`Self::ref_run`] that gives up after `budget` steps.
|
||||
pub(super) fn ref_run_budget(&self, env: &FnEnv, pos: [f64; 2], budget: u64) -> Result<Value, String> {
|
||||
let mut st = State { memo: vec![None; self.nodes.len()], epoch: 0, vars: Vec::new(), rng: 0, lcg_state: None, steps: 0, budget };
|
||||
self.eval(self.out, env, pos, &mut st)
|
||||
}
|
||||
|
||||
/// Run the function with variables and random sequence carried in `state` (read before, updated after).
|
||||
pub(super) fn ref_run_in(&self, env: &FnEnv, pos: [f64; 2], state: &mut FnState) -> Result<Value, String> {
|
||||
let mut st = State {
|
||||
memo: vec![None; self.nodes.len()],
|
||||
epoch: 0,
|
||||
vars: std::mem::take(&mut state.vars),
|
||||
rng: state.rng,
|
||||
lcg_state: state.lcg_state,
|
||||
steps: 0,
|
||||
budget: u64::MAX,
|
||||
};
|
||||
let r = self.eval(self.out, env, pos, &mut st);
|
||||
state.vars = st.vars;
|
||||
state.rng = st.rng;
|
||||
state.lcg_state = st.lcg_state;
|
||||
r
|
||||
}
|
||||
|
||||
fn eval(&self, i: usize, env: &FnEnv, pos: [f64; 2], st: &mut State) -> Result<Value, String> {
|
||||
if let Some((v, e)) = &st.memo[i]
|
||||
&& *e == st.epoch
|
||||
{
|
||||
return Ok(v.clone());
|
||||
}
|
||||
st.steps += 1;
|
||||
if st.steps > st.budget {
|
||||
return Err(OVER_BUDGET.into());
|
||||
}
|
||||
let n = &self.nodes[i];
|
||||
let r = self
|
||||
.eval_node(n, env, pos, st)
|
||||
.map_err(|e| if e.starts_with("node ") { e } else { format!("node {} ({}): {e}", n.id, kind_of(n.op)) })?;
|
||||
let r = if self.single { super::to_single(r) } else { r };
|
||||
st.memo[i] = Some((r.clone(), st.epoch));
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn arg(&self, n: &PNode, k: usize, env: &FnEnv, pos: [f64; 2], st: &mut State) -> Result<Value, String> {
|
||||
match n.ins[k] {
|
||||
Some(j) => self.eval(j, env, pos, st),
|
||||
None => Err("an input is not connected".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn opt_arg(&self, n: &PNode, k: usize, env: &FnEnv, pos: [f64; 2], st: &mut State) -> Result<Option<Value>, String> {
|
||||
match n.ins[k] {
|
||||
Some(j) => self.eval(j, env, pos, st).map(Some),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn eval_loop(&self, n: &PNode, env: &FnEnv, pos: [f64; 2], st: &mut State) -> Result<Value, String> {
|
||||
self.arg(n, 0, env, pos, st)?;
|
||||
let passes = super::loop_passes(&n.num);
|
||||
// every pass reads the variables anew, so nothing computed in the pass before counts
|
||||
for _ in 0..passes {
|
||||
st.epoch += 1;
|
||||
// a condition read back from a variable comes as a number
|
||||
match self.opt_arg(n, 2, env, pos, st)? {
|
||||
Some(Value::Bool(true)) => break,
|
||||
Some(Value::Num(x)) if x.v[0] != 0.0 => break,
|
||||
Some(Value::Str(_)) => return Err("the loop's condition must be a boolean".into()),
|
||||
_ => {}
|
||||
}
|
||||
st.epoch += 1;
|
||||
self.arg(n, 1, env, pos, st)?;
|
||||
}
|
||||
st.epoch += 1;
|
||||
Ok(Value::float(0.0))
|
||||
}
|
||||
|
||||
fn eval_if(&self, n: &PNode, env: &FnEnv, pos: [f64; 2], st: &mut State) -> Result<Value, String> {
|
||||
match self.arg(n, 0, env, pos, st)? {
|
||||
Value::Bool(true) => self.arg(n, 1, env, pos, st),
|
||||
Value::Bool(false) => self.arg(n, 2, env, pos, st),
|
||||
_ => Err("the condition must be a boolean".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn eval_node(&self, n: &PNode, env: &FnEnv, pos: [f64; 2], st: &mut State) -> Result<Value, String> {
|
||||
let num = |k: &str| n.num.get(k).copied().unwrap_or(0.0);
|
||||
Ok(match n.op {
|
||||
Op::Out | Op::Pin => self.arg(n, 0, env, pos, st)?,
|
||||
Op::Float => Value::float(num("v")),
|
||||
Op::Int => Value::int(num("v").trunc() as i64),
|
||||
Op::Bool => Value::Bool(num("v") != 0.0),
|
||||
Op::Str => Value::text(&n.text),
|
||||
Op::Vec(lanes, int) => {
|
||||
let mut parts: [Option<Value>; 4] = [None, None, None, None];
|
||||
for (k, p) in parts.iter_mut().enumerate() {
|
||||
*p = self.opt_arg(n, k, env, pos, st)?;
|
||||
}
|
||||
build_vec_ref(
|
||||
lanes,
|
||||
int,
|
||||
[parts[0].as_ref(), parts[1].as_ref(), parts[2].as_ref(), parts[3].as_ref()],
|
||||
[num("x"), num("y"), num("z"), num("w")],
|
||||
)?
|
||||
}
|
||||
Op::Swizzle => swizzle(&self.arg(n, 0, env, pos, st)?, &n.text)?,
|
||||
Op::Un(u) => unary(u, &self.arg(n, 0, env, pos, st)?)?,
|
||||
Op::Bin(b) => {
|
||||
let (x, y) = (self.arg(n, 0, env, pos, st)?, self.arg(n, 1, env, pos, st)?);
|
||||
binary(b, &x, &y)?
|
||||
}
|
||||
Op::Clamp => {
|
||||
let (x, y, z) = (self.arg(n, 0, env, pos, st)?, self.arg(n, 1, env, pos, st)?, self.arg(n, 2, env, pos, st)?);
|
||||
clamp3(&x, &y, &z)?
|
||||
}
|
||||
Op::Lerp => {
|
||||
let (x, y, z) = (self.arg(n, 0, env, pos, st)?, self.arg(n, 1, env, pos, st)?, self.arg(n, 2, env, pos, st)?);
|
||||
lerp3(&x, &y, &z)?
|
||||
}
|
||||
Op::Smooth => {
|
||||
let (x, y, z) = (self.arg(n, 0, env, pos, st)?, self.arg(n, 1, env, pos, st)?, self.arg(n, 2, env, pos, st)?);
|
||||
smooth3(&x, &y, &z)?
|
||||
}
|
||||
Op::If => self.eval_if(n, env, pos, st)?,
|
||||
Op::Seq => {
|
||||
self.arg(n, 0, env, pos, st)?;
|
||||
self.arg(n, 1, env, pos, st)?
|
||||
}
|
||||
Op::Loop => self.eval_loop(n, env, pos, st)?,
|
||||
Op::Set => {
|
||||
let v = self.arg(n, 0, env, pos, st)?;
|
||||
match st.vars.iter_mut().find(|(k, _)| *k == n.name) {
|
||||
Some(slot) => slot.1 = v.clone(),
|
||||
None => st.vars.push((n.name.clone(), v.clone())),
|
||||
}
|
||||
// nothing runs again for this: outside a loop every instruction runs once per run (measured)
|
||||
v
|
||||
}
|
||||
// with a declared type the value takes that shape: reading two lanes of a variable set with four gives the first two
|
||||
Op::Get => {
|
||||
let v = st.vars.iter().find(|(k, _)| *k == n.name).map(|(_, v)| v.clone()).unwrap_or_else(|| Value::float(0.0));
|
||||
match num("type").round() as i32 {
|
||||
0 if !n.num.contains_key("type") => v,
|
||||
t if matches!(v, Value::Num(_)) && !matches!(type_pin(t), Pin::Bool | Pin::Text) => coerce(&v, type_pin(t)),
|
||||
_ => v,
|
||||
}
|
||||
}
|
||||
Op::Random if n.num.contains_key("lcg") => {
|
||||
let hi = self.opt_arg(n, 1, env, pos, st)?.map(|v| v.as_f32() as f64).unwrap_or(1.0);
|
||||
let seed = match self.opt_arg(n, 2, env, pos, st)? {
|
||||
Some(Value::Num(x)) => x.v[0] as i64 as u32,
|
||||
_ => 0,
|
||||
};
|
||||
use crate::lcg_rand as sr;
|
||||
let state = match num("lcg") as i32 {
|
||||
// a value processor's, computed where it is read: draw number `k` from its own start
|
||||
2 => (0..num("k") as u32).fold(sr::pixel_state(seed, 0.0, 0.0), |s, _| sr::step(sr::FUNCTION, s)),
|
||||
// a size expression's: runs once, so the same draw at every pixel
|
||||
5 => (0..num("k") as u32).fold(seed & 0xff_ffff, |s, _| sr::step(sr::PARAMETER, s)),
|
||||
1 => {
|
||||
let s = st.lcg_state.unwrap_or_else(|| sr::pixel_state(seed, pos[0] as f32, pos[1] as f32));
|
||||
sr::step(sr::FUNCTION, s)
|
||||
}
|
||||
3 => sr::step(sr::PARAMETER, st.lcg_state.unwrap_or(seed & 0xff_ffff)),
|
||||
// a fx-map's expression: the program set the state
|
||||
m => sr::step(sr::FX_SITES[(m - 10).clamp(0, sr::FX_SITES.len() as i32 - 1) as usize], st.lcg_state.unwrap_or(0)),
|
||||
};
|
||||
if !matches!(num("lcg") as i32, 2 | 5) {
|
||||
st.lcg_state = Some(state);
|
||||
}
|
||||
Value::float(hi * sr::output(state))
|
||||
}
|
||||
Op::Random => {
|
||||
let lo = self.opt_arg(n, 0, env, pos, st)?.map(|v| v.as_f32() as f64).unwrap_or(0.0);
|
||||
let hi = self.opt_arg(n, 1, env, pos, st)?.map(|v| v.as_f32() as f64).unwrap_or(1.0);
|
||||
st.rng = st.rng.wrapping_add(1);
|
||||
let seed = env.seed.wrapping_add(num("seed") as u32).wrapping_add(st.rng.wrapping_mul(7919));
|
||||
let r = rnd((pos[0] * 4096.0) as i32 ^ (n.id as i32).wrapping_mul(131), (pos[1] * 4096.0) as i32 ^ env.index as i32, seed) as f64;
|
||||
Value::float(lo + (hi - lo) * r)
|
||||
}
|
||||
Op::SampleGray | Op::SampleColor => {
|
||||
let p = self.arg(n, 0, env, pos, st)?.num()?;
|
||||
if p.lanes != 2 {
|
||||
return Err("the sample position must be a float2".into());
|
||||
}
|
||||
let slot = if n.name.is_empty() { "in" } else { n.name.as_str() };
|
||||
// a slot nothing is connected to reads 0, as in `vm`
|
||||
let (u, v) = (p.v[0] as f32, p.v[1] as f32);
|
||||
let c = match (env.image(slot), n.num.get("filter")) {
|
||||
(None, _) => [0.0; 4],
|
||||
(Some(t), Some(f)) => sample_filtered(t, u, v, *f as u32),
|
||||
(Some(t), None) => t.sample(u, v),
|
||||
};
|
||||
if n.op == Op::SampleGray { Value::float(lum(c) as f64) } else { Value::vec(4, [c[0] as f64, c[1] as f64, c[2] as f64, c[3] as f64]) }
|
||||
}
|
||||
Op::Stat(k) => {
|
||||
let slot = if n.name.is_empty() { "in" } else { n.name.as_str() };
|
||||
let s = env.stats.iter().find(|s| s.0 == slot).ok_or_else(|| format!("no input image '{slot}' for the statistic"))?;
|
||||
let a = match k {
|
||||
0 => s.1,
|
||||
1 => s.2,
|
||||
_ => s.3,
|
||||
};
|
||||
Value::vec(4, [a[0] as f64, a[1] as f64, a[2] as f64, a[3] as f64])
|
||||
}
|
||||
Op::Pos => Value::vec(2, [pos[0], pos[1], 0.0, 0.0]),
|
||||
Op::Size => Value::vec(2, [env.size[0], env.size[1], 0.0, 0.0]),
|
||||
Op::OwnSize => {
|
||||
let o = env.own.unwrap_or(env.size);
|
||||
Value::vec(2, [o[0], o[1], 0.0, 0.0])
|
||||
}
|
||||
Op::CellSize => Value::float(env.cell[0]),
|
||||
Op::CellDepth => Value::float(env.cell[1]),
|
||||
Op::Index => Value::int(env.index),
|
||||
Op::Count => Value::int(env.count),
|
||||
Op::Seed => Value::int(env.seed as i64),
|
||||
Op::Input | Op::GraphInput => input_value(n, env),
|
||||
Op::ToFloat => {
|
||||
let v = self.arg(n, 0, env, pos, st)?;
|
||||
let nn = v.num()?;
|
||||
Value::Num(Num { int: false, ..nn })
|
||||
}
|
||||
Op::ToInt => {
|
||||
let nn = self.arg(n, 0, env, pos, st)?.num()?;
|
||||
map1(&nn, true, |x| x.trunc())
|
||||
}
|
||||
Op::ToBool => {
|
||||
let v = self.arg(n, 0, env, pos, st)?;
|
||||
Value::Bool(match &v {
|
||||
Value::Bool(b) => *b,
|
||||
Value::Str(s) => !s.is_empty(),
|
||||
Value::Num(nn) => (0..nn.lanes as usize).any(|i| nn.v[i] != 0.0),
|
||||
})
|
||||
}
|
||||
Op::ToStr => Value::text(&self.arg(n, 0, env, pos, st)?.show()),
|
||||
Op::Concat => match (self.arg(n, 0, env, pos, st)?, self.arg(n, 1, env, pos, st)?) {
|
||||
(Value::Str(a), Value::Str(b)) => Value::text(&format!("{a}{b}")),
|
||||
_ => return Err("f_concat needs two strings".into()),
|
||||
},
|
||||
Op::Call => {
|
||||
let callee = n.callee.as_ref().ok_or("call without a function")?;
|
||||
let mut sub_env = FnEnv {
|
||||
size: env.size,
|
||||
index: env.index,
|
||||
own: env.own,
|
||||
cell: env.cell,
|
||||
count: env.count,
|
||||
seed: env.seed,
|
||||
images: env.images.clone(),
|
||||
graph_inputs: env.graph_inputs,
|
||||
args: BTreeMap::new(),
|
||||
stats: env.stats.clone(),
|
||||
};
|
||||
for (k, (name, pin, _)) in callee.inputs.iter().enumerate().take(4) {
|
||||
if let Some(v) = self.opt_arg(n, k, env, pos, st)? {
|
||||
sub_env.args.insert(name.clone(), coerce(&v, *pin));
|
||||
}
|
||||
}
|
||||
callee.ref_run_budget(&sub_env, pos, st.budget)?
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn input_value(n: &PNode, env: &FnEnv) -> Value {
|
||||
let num = |k: &str| n.num.get(k).copied().unwrap_or(0.0);
|
||||
let pin = type_pin(num("type").round() as i32);
|
||||
let default = {
|
||||
let g = |k: &str| num(k);
|
||||
match pin {
|
||||
Pin::Bool => Value::Bool(g("v") != 0.0),
|
||||
Pin::Text => Value::text(&n.text),
|
||||
p if p.lanes() == 1 => coerce(&Value::float(g("v")), p),
|
||||
p => coerce(&Value::vec(p.lanes() as u8, [g("x"), g("y"), g("z"), g("w")]), p),
|
||||
}
|
||||
};
|
||||
let from = if n.op == Op::Input { env.args.get(&n.name) } else { env.graph_inputs.get(&n.name) };
|
||||
match from {
|
||||
Some(v) => coerce(v, pin),
|
||||
None => default,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,680 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Runs a [`Code`]. The rule of the graph language, which the tree walk in `reference.rs` states and the tests compare with:
|
||||
//!
|
||||
//! > A node runs on demand, once per run; each step of a loop starts anew, so what a pass demands runs again in it. An
|
||||
//! > `f_set` starts nothing anew: what was computed from a variable before it keeps its value for the rest of the pass.
|
||||
//!
|
||||
//! So what remains to save is what can't change from run to run: nodes that depend on nothing, on this binding or on this run
|
||||
//! keep their value that long (the classes in [`super::code`]). Whatever reads a variable or has a side effect lasts one
|
||||
//! pass. That can't be stretched: a pass fixes what a node reads at its first demand, for it and everything below it,
|
||||
//! so a node would have to be visited in a pass even when its variables haven't changed.
|
||||
|
||||
use super::code::{Code, FLOOR_ENV, FLOOR_PASS, FLOOR_RUN, FLOORS, Inst, NONE, build};
|
||||
use super::{
|
||||
B, FnEnv, FnState, Num, Op, Prog, Value, binary, build_vec_ref, clamp3, clean, coerce, div_large, kind_of, lerp3, lum, map1, rnd,
|
||||
sample_filtered, smooth3, swizzle,
|
||||
};
|
||||
use crate::graph::Pin;
|
||||
use crate::lcg_rand as sr;
|
||||
use crate::tex::get;
|
||||
|
||||
type Fail = Box<String>;
|
||||
type R = Result<(), Fail>;
|
||||
|
||||
/// The two low bits of a register's stamp hold its validity class, fixed during compilation.
|
||||
const CLOCK_STEP: u64 = 4;
|
||||
const FLOOR_MASK: u64 = CLOCK_STEP - 1;
|
||||
|
||||
/// What a register the program doesn't have reads as. `code::build` gives every operand a register, so only a broken
|
||||
/// table could ask for one; reading this keeps that from being a panic.
|
||||
static NO_VALUE: Value = Value::Bool(false);
|
||||
|
||||
/// The value in register `i`.
|
||||
#[inline(always)]
|
||||
fn reg(fr: &Frame, i: usize) -> &Value {
|
||||
fr.values.get(i).unwrap_or(&NO_VALUE)
|
||||
}
|
||||
|
||||
/// Entry `i` of one of the code's tables.
|
||||
#[inline(always)]
|
||||
fn entry<T: Copy>(table: &[T], i: u32) -> Option<T> {
|
||||
table.get(i as usize).copied()
|
||||
}
|
||||
|
||||
#[cold]
|
||||
fn no_instruction(i: usize) -> Fail {
|
||||
Box::new(format!("no instruction {i}"))
|
||||
}
|
||||
|
||||
/// What a worker needs to run a [`Prog`]: registers and what is known to be valid. One per thread; made for one program,
|
||||
/// and kept over many runs because that is what makes values last.
|
||||
pub struct Frame {
|
||||
values: Vec<Value>,
|
||||
/// Each stamp combines its clock value with the register's validity class. A cache hit needs only this
|
||||
/// compact table and the frame's floors, without also fetching the code or the register's value.
|
||||
stamps: Vec<u64>,
|
||||
floors: [u64; FLOORS],
|
||||
clock: u64,
|
||||
vars: Vec<Value>,
|
||||
wrote: Vec<u64>,
|
||||
rng: u32,
|
||||
pos: [f64; 2],
|
||||
/// the compiled-graph generator's state (`lcg_rand`), once it has started
|
||||
lcg_state: Option<u32>,
|
||||
args: Vec<Option<Value>>,
|
||||
/// Image positions in the bound environment; None as a whole in a frame for a nested function call.
|
||||
images: Option<Vec<Option<usize>>>,
|
||||
kids: Vec<Option<Box<Frame>>>,
|
||||
run_start: u64,
|
||||
#[cfg(test)]
|
||||
pub(super) counts: Counts,
|
||||
}
|
||||
|
||||
/// How much work a run did, for tests that want to see that it stays small.
|
||||
#[cfg(test)]
|
||||
#[derive(Default, Debug, Clone, Copy)]
|
||||
pub(super) struct Counts {
|
||||
pub computed: u64,
|
||||
}
|
||||
|
||||
impl Frame {
|
||||
fn new(c: &Code, kids: usize) -> Frame {
|
||||
let mut values = vec![NO_VALUE.clone(); c.insts.len()];
|
||||
let mut stamps: Vec<_> = c.floor.iter().copied().map(u64::from).collect();
|
||||
for (i, v) in &c.literals {
|
||||
if let (Some(value), Some(stamp)) = (values.get_mut(*i as usize), stamps.get_mut(*i as usize)) {
|
||||
*value = v.clone();
|
||||
*stamp |= CLOCK_STEP;
|
||||
}
|
||||
}
|
||||
Frame {
|
||||
values,
|
||||
stamps,
|
||||
floors: [CLOCK_STEP; FLOORS],
|
||||
clock: 2 * CLOCK_STEP,
|
||||
vars: vec![Value::float(0.0); c.var_names.len()],
|
||||
wrote: vec![0; c.var_names.len()],
|
||||
rng: 0,
|
||||
pos: [0.0; 2],
|
||||
lcg_state: None,
|
||||
args: vec![None; c.arg_names.len()],
|
||||
images: None,
|
||||
kids: (0..kids).map(|_| None).collect(),
|
||||
run_start: 0,
|
||||
#[cfg(test)]
|
||||
counts: Counts::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_floor(&mut self, floor: u32, t: u64) {
|
||||
if let Some(f) = self.floors.get_mut(floor as usize) {
|
||||
*f = t;
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything computed from the caller's environment stops counting.
|
||||
fn new_binding(&mut self) {
|
||||
self.clock += CLOCK_STEP;
|
||||
self.set_floor(FLOOR_ENV, self.clock);
|
||||
}
|
||||
|
||||
fn new_run(&mut self, pos: [f64; 2]) {
|
||||
self.clock += CLOCK_STEP;
|
||||
let t = self.clock;
|
||||
self.set_floor(FLOOR_RUN, t);
|
||||
self.set_floor(FLOOR_PASS, t);
|
||||
for v in &mut self.vars {
|
||||
*v = Value::float(0.0);
|
||||
}
|
||||
self.rng = 0;
|
||||
self.lcg_state = None;
|
||||
self.pos = pos;
|
||||
self.run_start = t;
|
||||
}
|
||||
|
||||
/// A pass of a loop begins or ends: nodes with side effects and what reads variables run again.
|
||||
#[inline]
|
||||
fn new_pass(&mut self) {
|
||||
self.clock += CLOCK_STEP;
|
||||
self.set_floor(FLOOR_PASS, self.clock);
|
||||
}
|
||||
}
|
||||
|
||||
impl Prog {
|
||||
pub(super) fn code(&self) -> &Code {
|
||||
self.code.get_or_init(|| build(self))
|
||||
}
|
||||
|
||||
pub(super) fn uniform_value(&self, env: &FnEnv, frame: &mut Frame, index: usize) -> Option<Value> {
|
||||
ensure(self, self.code(), index, env, frame).ok()?;
|
||||
frame.values.get(index).cloned()
|
||||
}
|
||||
|
||||
/// Registers for running this program; reuse them over many runs (and bind again when the environment changes).
|
||||
pub fn frame(&self) -> Frame {
|
||||
let c = self.code();
|
||||
Frame::new(c, self.nodes.len())
|
||||
}
|
||||
|
||||
/// Tell `frame` about a new environment: what was computed from the old one is not used again.
|
||||
pub fn bind(&self, env: &FnEnv, frame: &mut Frame) {
|
||||
let c = self.code();
|
||||
for (slot, name) in frame.args.iter_mut().zip(&c.arg_names) {
|
||||
*slot = env.args.get(name).cloned();
|
||||
}
|
||||
if !c.samples.is_empty() {
|
||||
let images = frame.images.get_or_insert_with(Vec::new);
|
||||
images.clear();
|
||||
images.extend(c.samples.iter().map(|sample| env.images.iter().position(|(name, _)| *name == sample.slot)));
|
||||
}
|
||||
frame.new_binding();
|
||||
}
|
||||
|
||||
/// Run the function at `pos` (uv, 0..1).
|
||||
pub fn run(&self, env: &FnEnv, pos: [f64; 2]) -> Result<Value, String> {
|
||||
let mut f = self.frame();
|
||||
self.bind(env, &mut f);
|
||||
self.run_bound(env, pos, &mut f)
|
||||
}
|
||||
|
||||
/// As [`Prog::run`], in a frame that was last bound to `env`. Anything computed for an earlier run that still holds is
|
||||
/// not computed again.
|
||||
pub fn run_bound(&self, env: &FnEnv, pos: [f64; 2], fr: &mut Frame) -> Result<Value, String> {
|
||||
fr.new_run(pos);
|
||||
let c = self.code();
|
||||
self.go(c, env, fr)
|
||||
}
|
||||
|
||||
/// Run the function with variables and random sequence carried in `state` (read before, updated after).
|
||||
pub fn run_in(&self, env: &FnEnv, pos: [f64; 2], state: &mut FnState) -> Result<Value, String> {
|
||||
let mut f = self.frame();
|
||||
self.bind(env, &mut f);
|
||||
self.run_in_bound(env, pos, state, &mut f)
|
||||
}
|
||||
|
||||
/// As [`Prog::run_in`], in a frame that was last bound to `env`.
|
||||
pub fn run_in_bound(&self, env: &FnEnv, pos: [f64; 2], state: &mut FnState, fr: &mut Frame) -> Result<Value, String> {
|
||||
fr.new_run(pos);
|
||||
let c = self.code();
|
||||
fr.rng = state.rng;
|
||||
fr.lcg_state = state.lcg_state;
|
||||
for (k, name) in c.var_names.iter().enumerate() {
|
||||
if let Some((_, v)) = state.vars.iter().find(|(n, _)| n == name)
|
||||
&& let Some(d) = fr.vars.get_mut(k)
|
||||
{
|
||||
*d = v.clone();
|
||||
}
|
||||
}
|
||||
let r = self.go(c, env, fr);
|
||||
for (k, name) in c.var_names.iter().enumerate() {
|
||||
if fr.wrote.get(k).is_some_and(|w| *w >= fr.run_start)
|
||||
&& let Some(v) = fr.vars.get(k)
|
||||
{
|
||||
match state.vars.iter_mut().find(|(n, _)| n == name) {
|
||||
Some(slot) => slot.1 = v.clone(),
|
||||
None => state.vars.push((name.clone(), v.clone())),
|
||||
}
|
||||
}
|
||||
}
|
||||
state.rng = fr.rng;
|
||||
state.lcg_state = fr.lcg_state;
|
||||
r
|
||||
}
|
||||
|
||||
fn go(&self, c: &Code, env: &FnEnv, fr: &mut Frame) -> Result<Value, String> {
|
||||
ensure(self, c, c.out as usize, env, fr).map_err(|e| *e)?;
|
||||
Ok(reg(fr, c.out as usize).clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn ensure(p: &Prog, c: &Code, i: usize, env: &FnEnv, fr: &mut Frame) -> R {
|
||||
if let Some(&stamp) = fr.stamps.get(i)
|
||||
&& stamp >= fr.floors.get((stamp & FLOOR_MASK) as usize).copied().unwrap_or(u64::MAX)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
compute(p, c, i, env, fr)
|
||||
}
|
||||
|
||||
fn compute(p: &Prog, c: &Code, i: usize, env: &FnEnv, fr: &mut Frame) -> R {
|
||||
let Some(inst) = c.insts.get(i) else { return Err(no_instruction(i)) };
|
||||
if let Err(e) = body_inner(p, c, i, inst, env, fr) {
|
||||
return Err(wrap(p, i, e));
|
||||
}
|
||||
if let Some(stamp) = fr.stamps.get_mut(i) {
|
||||
*stamp = fr.clock | (*stamp & FLOOR_MASK);
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
fr.counts.computed += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cold]
|
||||
fn wrap(p: &Prog, i: usize, e: Fail) -> Fail {
|
||||
if e.starts_with("node ") {
|
||||
return e;
|
||||
}
|
||||
let Some(n) = p.nodes.get(i) else { return e };
|
||||
Box::new(format!("node {} ({}): {e}", n.id, kind_of(n.op)))
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn scalar_float(v: &Value) -> Option<f64> {
|
||||
match v {
|
||||
Value::Num(Num { lanes: 1, int: false, v }) => Some(v[0]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn float1(x: f64) -> Value {
|
||||
Value::Num(Num { lanes: 1, int: false, v: [clean(x), 0.0, 0.0, 0.0] })
|
||||
}
|
||||
|
||||
/// Binary operation with the common case (two float scalars) handled directly; everything else as [`binary`] has it.
|
||||
#[inline(always)]
|
||||
fn fast_binary(op: B, x: &Value, y: &Value) -> Result<Value, String> {
|
||||
if let (Some(p), Some(q)) = (scalar_float(x), scalar_float(y)) {
|
||||
match op {
|
||||
B::Add => return Ok(float1(p + q)),
|
||||
B::Sub => return Ok(float1(p - q)),
|
||||
B::Mul => return Ok(float1(p * q)),
|
||||
B::Div => return Ok(float1(if q != 0.0 { p / q } else { 0.0 })),
|
||||
B::DivLarge => return Ok(float1(div_large(p, q))),
|
||||
B::Step => return Ok(float1(if q < p { 0.0 } else { 1.0 })),
|
||||
B::Min => return Ok(float1(p.min(q))),
|
||||
B::Max => return Ok(float1(p.max(q))),
|
||||
B::Lt => return Ok(Value::Bool(p < q)),
|
||||
B::Le => return Ok(Value::Bool(p <= q)),
|
||||
B::Gt => return Ok(Value::Bool(p > q)),
|
||||
B::Ge => return Ok(Value::Bool(p >= q)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// float vectors, or a vector and a scalar: the same lane by lane
|
||||
if let (Value::Num(a), Value::Num(b)) = (x, y)
|
||||
&& !a.int
|
||||
&& !b.int
|
||||
&& (a.lanes == b.lanes || a.lanes == 1 || b.lanes == 1)
|
||||
&& matches!(op, B::Add | B::Sub | B::Mul | B::DivLarge | B::Min | B::Max)
|
||||
{
|
||||
let lanes = a.lanes.max(b.lanes);
|
||||
let mut v = [0.0; 4];
|
||||
for (i, o) in v.iter_mut().enumerate().take(lanes as usize) {
|
||||
let (p, q) = (if a.lanes == 1 { a.v[0] } else { get(&a.v, i) }, if b.lanes == 1 { b.v[0] } else { get(&b.v, i) });
|
||||
*o = clean(match op {
|
||||
B::Add => p + q,
|
||||
B::Sub => p - q,
|
||||
B::DivLarge => div_large(p, q),
|
||||
B::Min => p.min(q),
|
||||
B::Max => p.max(q),
|
||||
_ => p * q,
|
||||
});
|
||||
}
|
||||
return Ok(Value::Num(Num { lanes, int: false, v }));
|
||||
}
|
||||
binary(op, x, y)
|
||||
}
|
||||
|
||||
/// Swizzle with a mask known to be plain letters.
|
||||
#[inline(always)]
|
||||
fn fast_swizzle(x: &Value, mask: Option<([u8; 4], u8)>, text: &str) -> Result<Value, String> {
|
||||
if let (Value::Num(n), Some((idx, len))) = (x, mask) {
|
||||
let mut v = [0.0; 4];
|
||||
let lanes = n.lanes as usize;
|
||||
for (o, at) in v.iter_mut().zip(idx).take(len as usize) {
|
||||
let at = at as usize;
|
||||
if at >= lanes && !(lanes == 1 && at == 0) {
|
||||
return swizzle(x, text);
|
||||
}
|
||||
*o = get(&n.v, at);
|
||||
}
|
||||
return Ok(Value::Num(Num { lanes: len, int: n.int, v }));
|
||||
}
|
||||
swizzle(x, text)
|
||||
}
|
||||
|
||||
/// Clones an operand: what impure nodes do, since a later operand can run this one again.
|
||||
#[inline(always)]
|
||||
fn val(p: &Prog, c: &Code, j: u32, env: &FnEnv, fr: &mut Frame) -> Result<Value, Fail> {
|
||||
ensure(p, c, j as usize, env, fr)?;
|
||||
Ok(reg(fr, j as usize).clone())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn opt_val(p: &Prog, c: &Code, j: u32, env: &FnEnv, fr: &mut Frame) -> Result<Option<Value>, Fail> {
|
||||
if j == NONE { Ok(None) } else { val(p, c, j, env, fr).map(Some) }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn body_inner(p: &Prog, c: &Code, i: usize, inst: &Inst, env: &FnEnv, fr: &mut Frame) -> R {
|
||||
let [a, b, ..] = inst.ins;
|
||||
let (au, bu) = (a as usize, b as usize);
|
||||
let r: Value = match inst.op {
|
||||
// a literal holds its value from the start; `f_pin` and `f_out` are read through
|
||||
Op::Float | Op::Int | Op::Bool | Op::Str => return Ok(()),
|
||||
Op::Out | Op::Pin => {
|
||||
ensure(p, c, au, env, fr)?;
|
||||
reg(fr, au).clone()
|
||||
}
|
||||
Op::Swizzle => {
|
||||
ensure(p, c, au, env, fr)?;
|
||||
fast_swizzle(reg(fr, au), entry(&c.swizzles, inst.x).flatten(), p.nodes.get(i).map_or("", |n| n.text.as_str()))?
|
||||
}
|
||||
Op::Un(u) => {
|
||||
ensure(p, c, au, env, fr)?;
|
||||
super::unary(u, reg(fr, au))?
|
||||
}
|
||||
Op::Bin(o) => {
|
||||
if inst.impure {
|
||||
let x = val(p, c, a, env, fr)?;
|
||||
ensure(p, c, bu, env, fr)?;
|
||||
fast_binary(o, &x, reg(fr, bu))?
|
||||
} else {
|
||||
ensure(p, c, au, env, fr)?;
|
||||
ensure(p, c, bu, env, fr)?;
|
||||
fast_binary(o, reg(fr, au), reg(fr, bu))?
|
||||
}
|
||||
}
|
||||
Op::Seq => {
|
||||
ensure(p, c, au, env, fr)?;
|
||||
ensure(p, c, bu, env, fr)?;
|
||||
reg(fr, bu).clone()
|
||||
}
|
||||
// the rest in a function of its own: a chain of the operations above recurses through this frame only, so it
|
||||
// stays small (a deep function's run takes this frame once per node one behind the other)
|
||||
_ => body_rest(p, c, i, inst, env, fr)?,
|
||||
};
|
||||
if let Some(value) = fr.values.get_mut(i) {
|
||||
*value = if p.single { super::to_single(r) } else { r };
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The operations [`body_inner`] doesn't do itself.
|
||||
#[inline(never)]
|
||||
fn body_rest(p: &Prog, c: &Code, i: usize, inst: &Inst, env: &FnEnv, fr: &mut Frame) -> Result<Value, Fail> {
|
||||
let [a, b, d, e] = inst.ins;
|
||||
let (au, bu, du) = (a as usize, b as usize, d as usize);
|
||||
Ok(match inst.op {
|
||||
Op::Vec(lanes, int) => {
|
||||
let defaults = entry(&c.vec_defaults, inst.x).unwrap_or([0.0; 4]);
|
||||
if inst.impure {
|
||||
impure_vec(p, c, inst, lanes, int, defaults, env, fr)?
|
||||
} else {
|
||||
for j in inst.ins {
|
||||
if j != NONE {
|
||||
ensure(p, c, j as usize, env, fr)?;
|
||||
}
|
||||
}
|
||||
let part = |j: u32| if j == NONE { None } else { Some(reg(fr, j as usize)) };
|
||||
build_vec_ref(lanes, int, [part(a), part(b), part(d), part(e)], defaults)?
|
||||
}
|
||||
}
|
||||
Op::Clamp | Op::Lerp | Op::Smooth => {
|
||||
let f = match inst.op {
|
||||
Op::Clamp => clamp3,
|
||||
Op::Lerp => lerp3,
|
||||
_ => smooth3,
|
||||
};
|
||||
if inst.impure {
|
||||
let (x, y) = (val(p, c, a, env, fr)?, val(p, c, b, env, fr)?);
|
||||
ensure(p, c, du, env, fr)?;
|
||||
f(&x, &y, reg(fr, du))?
|
||||
} else {
|
||||
ensure(p, c, au, env, fr)?;
|
||||
ensure(p, c, bu, env, fr)?;
|
||||
ensure(p, c, du, env, fr)?;
|
||||
f(reg(fr, au), reg(fr, bu), reg(fr, du))?
|
||||
}
|
||||
}
|
||||
Op::If => {
|
||||
ensure(p, c, au, env, fr)?;
|
||||
let pick = match reg(fr, au) {
|
||||
Value::Bool(true) => bu,
|
||||
Value::Bool(false) => du,
|
||||
_ => return Err(Box::new("the condition must be a boolean".to_string())),
|
||||
};
|
||||
ensure(p, c, pick, env, fr)?;
|
||||
reg(fr, pick).clone()
|
||||
}
|
||||
Op::Loop => {
|
||||
ensure(p, c, au, env, fr)?;
|
||||
// every pass reads the variables anew, so nothing computed in the pass before counts
|
||||
for pass in 0..entry(&c.passes, inst.x).unwrap_or(0) {
|
||||
// a compiled graph's loop can run billions of passes: it stops when the evaluation is cancelled
|
||||
if pass & 0xfff == 0xfff && crate::context::cancelled() {
|
||||
return Err(Box::new("cancelled".to_string()));
|
||||
}
|
||||
fr.new_pass();
|
||||
if d != NONE {
|
||||
ensure(p, c, du, env, fr)?;
|
||||
// a condition read back from a variable comes as a number
|
||||
match reg(fr, du) {
|
||||
Value::Bool(true) => break,
|
||||
Value::Num(x) if x.v[0] != 0.0 => break,
|
||||
Value::Str(_) => return Err(Box::new("the loop's condition must be a boolean".to_string())),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
fr.new_pass();
|
||||
ensure(p, c, bu, env, fr)?;
|
||||
}
|
||||
fr.new_pass();
|
||||
Value::float(0.0)
|
||||
}
|
||||
Op::Set => {
|
||||
ensure(p, c, au, env, fr)?;
|
||||
let v = reg(fr, au).clone();
|
||||
if let Some(w) = fr.wrote.get_mut(inst.x as usize) {
|
||||
*w = fr.clock;
|
||||
}
|
||||
if let Some(d) = fr.vars.get_mut(inst.x as usize) {
|
||||
*d = v.clone();
|
||||
}
|
||||
v
|
||||
}
|
||||
// with a declared type the value takes that shape: reading two lanes of a variable set with four gives the first two
|
||||
Op::Get => {
|
||||
let v = fr.vars.get(inst.x as usize).unwrap_or(&NO_VALUE);
|
||||
match entry(&c.get_pins, inst.y).flatten() {
|
||||
Some(pin) if matches!(v, Value::Num(_)) && !matches!(pin, Pin::Bool | Pin::Text) => coerce(v, pin),
|
||||
_ => v.clone(),
|
||||
}
|
||||
}
|
||||
Op::Random => random(p, c, i, env, fr)?,
|
||||
Op::SampleGray | Op::SampleColor => sample(p, c, inst, env, fr)?,
|
||||
Op::Stat(k) => stat(p, i, k, env)?,
|
||||
Op::Pos => Value::vec(2, [fr.pos[0], fr.pos[1], 0.0, 0.0]),
|
||||
Op::Size => Value::vec(2, [env.size[0], env.size[1], 0.0, 0.0]),
|
||||
Op::OwnSize => {
|
||||
let o = env.own.unwrap_or(env.size);
|
||||
Value::vec(2, [o[0], o[1], 0.0, 0.0])
|
||||
}
|
||||
Op::CellSize => Value::float(env.cell[0]),
|
||||
Op::CellDepth => Value::float(env.cell[1]),
|
||||
Op::Index => Value::int(env.index),
|
||||
Op::Count => Value::int(env.count),
|
||||
Op::Seed => Value::int(env.seed as i64),
|
||||
Op::Input | Op::GraphInput => input(p, c, i, env, fr),
|
||||
Op::ToFloat => {
|
||||
ensure(p, c, au, env, fr)?;
|
||||
let n = reg(fr, au).num()?;
|
||||
Value::Num(Num { int: false, ..n })
|
||||
}
|
||||
Op::ToInt => {
|
||||
ensure(p, c, au, env, fr)?;
|
||||
let n = reg(fr, au).num()?;
|
||||
map1(&n, true, |x| x.trunc())
|
||||
}
|
||||
Op::ToBool => {
|
||||
ensure(p, c, au, env, fr)?;
|
||||
Value::Bool(match reg(fr, au) {
|
||||
Value::Bool(t) => *t,
|
||||
Value::Str(s) => !s.is_empty(),
|
||||
Value::Num(n) => n.v.iter().take(n.lanes as usize).any(|x| *x != 0.0),
|
||||
})
|
||||
}
|
||||
Op::ToStr | Op::Concat => text_op(p, c, i, env, fr)?,
|
||||
Op::Call => call(p, c, i, env, fr)?,
|
||||
// done by body_inner
|
||||
Op::Float | Op::Int | Op::Bool | Op::Str | Op::Out | Op::Pin | Op::Swizzle | Op::Un(_) | Op::Bin(_) | Op::Seq => reg(fr, i).clone(),
|
||||
})
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn impure_vec(p: &Prog, c: &Code, inst: &Inst, lanes: u8, int: bool, defaults: [f64; 4], env: &FnEnv, fr: &mut Frame) -> Result<Value, Fail> {
|
||||
let [a, b, d, e] = inst.ins;
|
||||
let parts = [opt_val(p, c, a, env, fr)?, opt_val(p, c, b, env, fr)?, opt_val(p, c, d, env, fr)?, opt_val(p, c, e, env, fr)?];
|
||||
let refs = [parts[0].as_ref(), parts[1].as_ref(), parts[2].as_ref(), parts[3].as_ref()];
|
||||
Ok(build_vec_ref(lanes, int, refs, defaults)?)
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
fn random(p: &Prog, c: &Code, i: usize, env: &FnEnv, fr: &mut Frame) -> Result<Value, Fail> {
|
||||
let Some(inst) = c.insts.get(i) else { return Err(no_instruction(i)) };
|
||||
let [a, b, s, _] = inst.ins;
|
||||
if let Some((mode, k)) = entry(&c.lcg_draws, inst.x).flatten() {
|
||||
let hi = if b == NONE { 1.0 } else { val(p, c, b, env, fr)?.as_f32() as f64 };
|
||||
let seed = match opt_val(p, c, s, env, fr)? {
|
||||
Some(Value::Num(x)) => x.v[0] as i64 as u32,
|
||||
_ => 0,
|
||||
};
|
||||
let state = match mode {
|
||||
// a value processor's, computed where it is read: draw number `k` from its own start
|
||||
2 => (0..k).fold(sr::pixel_state(seed, 0.0, 0.0), |s, _| sr::step(sr::FUNCTION, s)),
|
||||
// a size expression's: runs once, so the same draw at every pixel
|
||||
5 => (0..k).fold(seed & 0xff_ffff, |s, _| sr::step(sr::PARAMETER, s)),
|
||||
1 => {
|
||||
let s = fr.lcg_state.unwrap_or_else(|| sr::pixel_state(seed, fr.pos[0] as f32, fr.pos[1] as f32));
|
||||
sr::step(sr::FUNCTION, s)
|
||||
}
|
||||
3 => sr::step(sr::PARAMETER, fr.lcg_state.unwrap_or(seed & 0xff_ffff)),
|
||||
// a fx-map's expression: the program set the state
|
||||
m => {
|
||||
let site = sr::FX_SITES.get((m - 10).clamp(0, sr::FX_SITES.len() as i32 - 1) as usize).copied().unwrap_or(sr::FUNCTION);
|
||||
sr::step(site, fr.lcg_state.unwrap_or(0))
|
||||
}
|
||||
};
|
||||
if !super::code::indexed_lcg_draw(mode) {
|
||||
fr.lcg_state = Some(state);
|
||||
}
|
||||
return Ok(Value::float(hi * sr::output(state)));
|
||||
}
|
||||
let lo = if a == NONE { 0.0 } else { val(p, c, a, env, fr)?.as_f32() as f64 };
|
||||
let hi = if b == NONE { 1.0 } else { val(p, c, b, env, fr)?.as_f32() as f64 };
|
||||
fr.rng = fr.rng.wrapping_add(1);
|
||||
let seed = env.seed.wrapping_add(entry(&c.seeds, inst.x).unwrap_or(0)).wrapping_add(fr.rng.wrapping_mul(7919));
|
||||
let pos = fr.pos;
|
||||
let id = p.nodes.get(i).map_or(0, |n| n.id);
|
||||
let r = rnd((pos[0] * 4096.0) as i32 ^ (id as i32).wrapping_mul(131), (pos[1] * 4096.0) as i32 ^ env.index as i32, seed) as f64;
|
||||
Ok(Value::float(lo + (hi - lo) * r))
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
fn sample(p: &Prog, c: &Code, inst: &Inst, env: &FnEnv, fr: &mut Frame) -> Result<Value, Fail> {
|
||||
let au = inst.ins[0] as usize;
|
||||
ensure(p, c, au, env, fr)?;
|
||||
let (u, v) = match reg(fr, au) {
|
||||
Value::Num(Num { lanes: 2, v, .. }) => (v[0] as f32, v[1] as f32),
|
||||
Value::Str(_) => return Err(Box::new("a string cannot be used as a number".to_string())),
|
||||
_ => return Err(Box::new("the sample position must be a float2".to_string())),
|
||||
};
|
||||
let info = c.samples.get(inst.x as usize);
|
||||
let image = match &fr.images {
|
||||
Some(bound) => entry(bound, inst.x).flatten().and_then(|index| env.images.get(index).map(|(_, image)| *image)),
|
||||
None => info.and_then(|info| env.image(&info.slot)),
|
||||
};
|
||||
// A slot without an image reads zero.
|
||||
let s = match (image, info.and_then(|info| info.filter)) {
|
||||
(None, _) => [0.0; 4],
|
||||
(Some(t), Some(f)) => sample_filtered(t, u, v, f),
|
||||
(Some(t), None) => t.sample(u, v),
|
||||
};
|
||||
Ok(if inst.op == Op::SampleGray { Value::float(lum(s) as f64) } else { Value::vec(4, [s[0] as f64, s[1] as f64, s[2] as f64, s[3] as f64]) })
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
fn stat(p: &Prog, i: usize, k: u8, env: &FnEnv) -> Result<Value, Fail> {
|
||||
let name = p.nodes.get(i).map_or("", |n| n.name.as_str());
|
||||
let slot = if name.is_empty() { "in" } else { name };
|
||||
let s = env.stats.iter().find(|s| s.0 == slot).ok_or_else(|| format!("no input image '{slot}' for the statistic"))?;
|
||||
let q = match k {
|
||||
0 => s.1,
|
||||
1 => s.2,
|
||||
_ => s.3,
|
||||
};
|
||||
Ok(Value::vec(4, [q[0] as f64, q[1] as f64, q[2] as f64, q[3] as f64]))
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
fn input(p: &Prog, c: &Code, i: usize, env: &FnEnv, fr: &Frame) -> Value {
|
||||
let Some((inst, info)) = c.insts.get(i).and_then(|inst| Some((inst, c.inputs.get(inst.x as usize)?))) else { return NO_VALUE.clone() };
|
||||
let from = if inst.op == Op::Input {
|
||||
fr.args.get(info.arg as usize).and_then(Option::as_ref)
|
||||
} else {
|
||||
env.graph_inputs.get(p.nodes.get(i).map_or("", |n| n.name.as_str()))
|
||||
};
|
||||
match from {
|
||||
Some(v) => coerce(v, info.pin),
|
||||
None => info.default.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
fn text_op(p: &Prog, c: &Code, i: usize, env: &FnEnv, fr: &mut Frame) -> Result<Value, Fail> {
|
||||
let Some(inst) = c.insts.get(i) else { return Err(no_instruction(i)) };
|
||||
let [a, b, ..] = inst.ins;
|
||||
if inst.op == Op::ToStr {
|
||||
ensure(p, c, a as usize, env, fr)?;
|
||||
return Ok(Value::text(®(fr, a as usize).show()));
|
||||
}
|
||||
let x = val(p, c, a, env, fr)?;
|
||||
ensure(p, c, b as usize, env, fr)?;
|
||||
match (&x, reg(fr, b as usize)) {
|
||||
(Value::Str(s), Value::Str(t)) => Ok(Value::text(&format!("{s}{t}"))),
|
||||
_ => Err(Box::new("f_concat needs two strings".to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `f_call`: the callee gets variables and a random sequence of its own, so all the caller sees is the result.
|
||||
#[inline(never)]
|
||||
fn call(p: &Prog, c: &Code, i: usize, env: &FnEnv, fr: &mut Frame) -> Result<Value, Fail> {
|
||||
let callee = p.nodes.get(i).and_then(|n| n.callee.as_ref()).ok_or_else(|| "call without a function".to_string())?;
|
||||
let cc = callee.code();
|
||||
let mut kid = fr.kids.get_mut(i).and_then(Option::take).unwrap_or_else(|| Box::new(callee.frame()));
|
||||
kid.args.fill(None);
|
||||
let Some(inst) = c.insts.get(i) else { return Err(no_instruction(i)) };
|
||||
let mut failed = None;
|
||||
for (k, ((_, pin, _), operand)) in callee.inputs.iter().zip(inst.ins).enumerate() {
|
||||
match opt_val(p, c, operand, env, fr) {
|
||||
Ok(Some(v)) => {
|
||||
if let Some(arg) = cc.input_args.get(k).and_then(|a| kid.args.get_mut(*a as usize)) {
|
||||
*arg = Some(coerce(&v, *pin));
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
failed = Some(e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(e) = failed {
|
||||
if let Some(k) = fr.kids.get_mut(i) {
|
||||
*k = Some(kid);
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
kid.new_binding();
|
||||
kid.new_run(fr.pos);
|
||||
let r = callee.go(cc, env, &mut kid);
|
||||
if let Some(k) = fr.kids.get_mut(i) {
|
||||
*k = Some(kid);
|
||||
}
|
||||
Ok(r?)
|
||||
}
|
||||
@@ -0,0 +1,510 @@
|
||||
//! Lower the position-dependent part of a pure single-precision pixel program to compute shader expressions.
|
||||
|
||||
use std::fmt::Write;
|
||||
|
||||
use super::code::{Code, FLOOR_ENV, NONE, indexed_lcg_draw};
|
||||
use super::{B, FnEnv, Op, Prog, U, Value};
|
||||
use crate::accelerator::{GreyInput, PixelImageInput};
|
||||
use crate::graph::Pin;
|
||||
use crate::tex::{GreyIn, ImgRef};
|
||||
|
||||
pub struct PixelShader {
|
||||
pub source: String,
|
||||
/// Position-independent registers, evaluated by the same VM as the CPU path.
|
||||
pub uniforms: Vec<[f32; 4]>,
|
||||
/// Indices into the function's bound images, in texture binding order.
|
||||
pub images: Vec<usize>,
|
||||
pub grey: bool,
|
||||
}
|
||||
|
||||
impl Prog {
|
||||
pub fn pixel_shader(&self, env: &FnEnv<'_>) -> Option<PixelShader> {
|
||||
let images: Vec<_> = env.images.iter().map(|&(name, image)| (name, SampleImage::Host(image))).collect();
|
||||
self.emit_pixel_shader(env, &images)
|
||||
}
|
||||
|
||||
pub(crate) fn packed_pixel_shader(&self, env: &FnEnv<'_>, images: &[(&str, GreyInput<'_>)]) -> Option<PixelShader> {
|
||||
if !self.can_sample_resident_images() {
|
||||
return None;
|
||||
}
|
||||
let images: Vec<_> = images.iter().map(|&(name, image)| (name, SampleImage::Packed(image))).collect();
|
||||
self.emit_pixel_shader(env, &images).filter(|shader| shader.grey)
|
||||
}
|
||||
|
||||
pub(crate) fn textured_pixel_shader(&self, env: &FnEnv<'_>, images: &[(&str, PixelImageInput<'_>)]) -> Option<PixelShader> {
|
||||
if !self.can_sample_resident_images() {
|
||||
return None;
|
||||
}
|
||||
let images = images
|
||||
.iter()
|
||||
.map(|&(name, image)| {
|
||||
let sampled = match image {
|
||||
PixelImageInput::Host(image) => SampleImage::Host(image),
|
||||
PixelImageInput::Float(_) => SampleImage::Float,
|
||||
};
|
||||
(name, sampled)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
self.emit_pixel_shader(env, &images).filter(|shader| shader.grey)
|
||||
}
|
||||
|
||||
fn can_sample_resident_images(&self) -> bool {
|
||||
let code = self.code();
|
||||
// These values are evaluated on the CPU while binding a program. They cannot read GPU images.
|
||||
!self.uses_stats
|
||||
&& !code.insts.iter().zip(&code.floor).any(|(inst, &floor)| floor <= FLOOR_ENV && matches!(inst.op, Op::SampleColor | Op::SampleGray))
|
||||
}
|
||||
|
||||
fn emit_pixel_shader(&self, env: &FnEnv<'_>, inputs: &[(&str, SampleImage<'_>)]) -> Option<PixelShader> {
|
||||
if !self.single {
|
||||
return None;
|
||||
}
|
||||
let code = self.code();
|
||||
let count = code.insts.len();
|
||||
let mut frame = self.frame();
|
||||
self.bind(env, &mut frame);
|
||||
let root_index = code.out as usize;
|
||||
let root = code.insts.get(root_index)?;
|
||||
// Some compiled functions initialise locals before the expression that varies per pixel.
|
||||
// Run that initialiser once in the ordinary VM and bind subsequent reads as uniforms.
|
||||
let (out, initialised) = if root.op == Op::Seq && *code.floor.get(root_index)? > FLOOR_ENV {
|
||||
let [initialiser, out, ..] = root.ins;
|
||||
if !uniform_initialiser(code, initialiser) {
|
||||
return None;
|
||||
}
|
||||
self.uniform_value(env, &mut frame, initialiser as usize)?;
|
||||
(out, true)
|
||||
} else {
|
||||
(code.out, false)
|
||||
};
|
||||
let uniform_register = |index: usize| {
|
||||
code.floor.get(index).is_some_and(|&floor| floor <= FLOOR_ENV)
|
||||
|| (initialised && code.insts.get(index).is_some_and(|inst| inst.op == Op::Get))
|
||||
};
|
||||
let mut need = vec![false; count];
|
||||
let mut todo = vec![out];
|
||||
while let Some(index) = todo.pop() {
|
||||
let index = index as usize;
|
||||
let visit = need.get_mut(index)?;
|
||||
if std::mem::replace(visit, true) || uniform_register(index) {
|
||||
continue;
|
||||
}
|
||||
todo.extend(code.insts.get(index)?.ins.into_iter().filter(|&i| i != NONE));
|
||||
}
|
||||
|
||||
let mut shader = PixelShader { source: String::new(), uniforms: Vec::new(), images: Vec::new(), grey: false };
|
||||
let mut bindings = Vec::new();
|
||||
let mut types = vec![None; count];
|
||||
let result = self.type_of(out as usize, &mut types).ok()?;
|
||||
let mut body = String::new();
|
||||
for (index, &used) in need.iter().enumerate() {
|
||||
if !used {
|
||||
continue;
|
||||
}
|
||||
let pin = self.type_of(index, &mut types).ok()?;
|
||||
let expression = if uniform_register(index) {
|
||||
let value = self.uniform_value(env, &mut frame, index)?;
|
||||
if code.insts.get(index)?.op == Op::Get && value.pin() != pin {
|
||||
return None;
|
||||
}
|
||||
let slot = shader.uniforms.len();
|
||||
shader.uniforms.push(uniform(value)?);
|
||||
let read = format!("parameters[{}]", slot + 1);
|
||||
if pin == Pin::Bool { format!("{read}.x != 0.0") } else { format!("{read}{}", suffix(pin.lanes())?) }
|
||||
} else {
|
||||
if matches!(pin, Pin::Int | Pin::Int2 | Pin::Int3 | Pin::Int4 | Pin::Text) {
|
||||
return None;
|
||||
}
|
||||
expression(code, index, &types, inputs, &mut shader.images, &mut bindings)?
|
||||
};
|
||||
writeln!(body, " let r{index} = {expression};").ok()?;
|
||||
}
|
||||
for (slot, &image) in shader.images.iter().enumerate() {
|
||||
let (_, image) = *inputs.get(image)?;
|
||||
if let SampleImage::Packed(image) = image {
|
||||
let (w, h, div, alpha) = image.info();
|
||||
let param = shader.uniforms.len() + 1;
|
||||
shader.uniforms.push([w as f32, h as f32, div, alpha]);
|
||||
writeln!(shader.source, "@group(0) @binding({}) var<storage, read> input_{slot}: array<u32>;", slot + 2).ok()?;
|
||||
writeln!(shader.source, "{}", packed_sampler(slot, param)).ok()?;
|
||||
continue;
|
||||
}
|
||||
let (sample_type, sample) = match image {
|
||||
SampleImage::Host(ImgRef::Grey(GreyIn::Q(grey))) => {
|
||||
let div = shader.uniforms.len() + 1;
|
||||
shader.uniforms.push([grey.div, 0.0, 0.0, 0.0]);
|
||||
let alpha = grey.alpha;
|
||||
("u32", format!("vec4f(vec3f(tc_sample_steps(input_{slot}, uv, mode, parameters[{div}].x)), {alpha:.1})"))
|
||||
}
|
||||
SampleImage::Host(ImgRef::Grey(grey)) => ("f32", format!("vec4f(vec3f(tc_sample(input_{slot}, uv, mode).x), {:.1})", grey.alpha())),
|
||||
SampleImage::Host(ImgRef::Rgba(_)) => ("f32", format!("tc_sample(input_{slot}, uv, mode)")),
|
||||
SampleImage::Float => ("f32", format!("vec4f(vec3f(tc_sample(input_{slot}, uv, mode).x), 1.0)")),
|
||||
SampleImage::Packed(_) => return None,
|
||||
};
|
||||
writeln!(shader.source, "@group(0) @binding({}) var input_{slot}: texture_2d<{sample_type}>;", slot + 2).ok()?;
|
||||
writeln!(shader.source, "fn sample_{slot}(uv: vec2f, mode: u32) -> vec4f {{ return {sample}; }}").ok()?;
|
||||
}
|
||||
let last = format!("r{out}");
|
||||
let (ty, expression) = match result {
|
||||
Pin::Bool => ("f32", format!("select(0.0, 1.0, {last})")),
|
||||
Pin::Float | Pin::Int => ("f32", last),
|
||||
Pin::Float2 | Pin::Int2 => ("vec4f", format!("vec4f({last}, 0.0, 1.0)")),
|
||||
Pin::Float3 | Pin::Int3 => ("vec4f", format!("vec4f({last}, 1.0)")),
|
||||
Pin::Float4 | Pin::Int4 => ("vec4f", last),
|
||||
_ => return None,
|
||||
};
|
||||
shader.grey = ty == "f32";
|
||||
writeln!(shader.source, "fn evaluate_pixel(pos: vec2f) -> {ty} {{\n{body} return {expression};\n}}").ok()?;
|
||||
Some(shader)
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole prefix has to be independent of the current pixel and leave only local values for the shader body.
|
||||
/// The shader expression emitter separately rejects writes and other effects in that body.
|
||||
fn uniform_initialiser(code: &Code, root: u32) -> bool {
|
||||
let mut seen = vec![false; code.insts.len()];
|
||||
let mut todo = vec![root];
|
||||
while let Some(index) = todo.pop() {
|
||||
let Some(visited) = seen.get_mut(index as usize) else { return false };
|
||||
if std::mem::replace(visited, true) {
|
||||
continue;
|
||||
}
|
||||
let Some(inst) = code.insts.get(index as usize) else { return false };
|
||||
if matches!(inst.op, Op::Pos | Op::SampleGray | Op::SampleColor | Op::Stat(_) | Op::Loop | Op::Call) {
|
||||
return false;
|
||||
}
|
||||
if inst.op == Op::Random && !code.lcg_draws.get(inst.x as usize).copied().flatten().is_some_and(|(site, _)| indexed_lcg_draw(site)) {
|
||||
return false;
|
||||
}
|
||||
todo.extend(inst.ins.into_iter().filter(|&i| i != NONE));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum SampleImage<'a> {
|
||||
Host(ImgRef<'a>),
|
||||
Packed(GreyInput<'a>),
|
||||
Float,
|
||||
}
|
||||
|
||||
fn packed_sampler(slot: usize, param: usize) -> String {
|
||||
format!(
|
||||
"fn load_{slot}(p: vec2i, width: i32, div: f32) -> f32 {{
|
||||
let i = u32(p.y * width + p.x);
|
||||
return f32((input_{slot}[i / 2u] >> ((i & 1u) * 16u)) & 0xffffu) / div;
|
||||
}}
|
||||
fn sample_{slot}(uv: vec2f, mode: u32) -> vec4f {{
|
||||
let p = parameters[{param}];
|
||||
let n = vec2i(p.xy);
|
||||
let position = tc_sample_position(uv);
|
||||
if ((mode & 1u) == 0u) {{
|
||||
return vec4f(vec3f(load_{slot}(tc_nearest(position, n, mode), n.x, p.z)), p.w);
|
||||
}}
|
||||
let sample = tc_bilinear(position, n, mode);
|
||||
let p00 = load_{slot}(sample.a, n.x, p.z);
|
||||
let p10 = load_{slot}(vec2i(sample.b.x, sample.a.y), n.x, p.z);
|
||||
let p01 = load_{slot}(vec2i(sample.a.x, sample.b.y), n.x, p.z);
|
||||
let p11 = load_{slot}(sample.b, n.x, p.z);
|
||||
let top = p00 + (p10 - p00) * sample.t.x;
|
||||
let bottom = p01 + (p11 - p01) * sample.t.x;
|
||||
return vec4f(vec3f(top + (bottom - top) * sample.t.y), p.w);
|
||||
}}"
|
||||
)
|
||||
}
|
||||
|
||||
fn uniform(value: Value) -> Option<[f32; 4]> {
|
||||
match value {
|
||||
Value::Bool(value) => Some([f32::from(value), 0.0, 0.0, 0.0]),
|
||||
Value::Num(value) => {
|
||||
let floats = value.v.map(|v| v as f32);
|
||||
floats.iter().zip(value.v).all(|(&f, v)| f.is_finite() && (!value.int || f64::from(f) == v)).then_some(floats)
|
||||
}
|
||||
Value::Str(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn suffix(lanes: usize) -> Option<&'static str> {
|
||||
Some(match lanes {
|
||||
1 => ".x",
|
||||
2 => ".xy",
|
||||
3 => ".xyz",
|
||||
4 => "",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn sample_binding(
|
||||
sample: u32,
|
||||
input_name: &str,
|
||||
inputs: &[(&str, SampleImage<'_>)],
|
||||
images: &mut Vec<usize>,
|
||||
bindings: &mut Vec<(u32, Option<usize>)>,
|
||||
) -> Option<usize> {
|
||||
if let Some((_, binding)) = bindings.iter().find(|(i, _)| *i == sample) {
|
||||
*binding
|
||||
} else {
|
||||
let binding = inputs.iter().position(|(name, _)| *name == input_name).map(|image| {
|
||||
if let Some(slot) = images.iter().position(|&source| source == image) {
|
||||
slot
|
||||
} else {
|
||||
let slot = images.len();
|
||||
images.push(image);
|
||||
slot
|
||||
}
|
||||
});
|
||||
bindings.push((sample, binding));
|
||||
binding
|
||||
}
|
||||
}
|
||||
|
||||
fn swizzle_expression(v: &str, input: usize, components: &[u8; 4], n: u8) -> Option<String> {
|
||||
let parts = components
|
||||
.iter()
|
||||
.take(n as usize)
|
||||
.map(|&component| match (input, component) {
|
||||
(1, 0) => v.to_owned(),
|
||||
(l, c) if usize::from(c) < l => format!("{v}[{c}u]"),
|
||||
_ => "0.0".to_owned(),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if n == 1 { parts.into_iter().next() } else { Some(format!("vec{n}f({})", parts.join(", "))) }
|
||||
}
|
||||
|
||||
fn float_expression(src: u32, src_pin: Pin, lanes: usize) -> String {
|
||||
let mut expr = format!("r{src}");
|
||||
if src_pin == Pin::Bool {
|
||||
expr = format!("select(0.0, 1.0, {expr})");
|
||||
}
|
||||
if src_pin.lanes() == 1 && lanes > 1 {
|
||||
expr = format!("vec{lanes}f({expr})");
|
||||
}
|
||||
expr
|
||||
}
|
||||
|
||||
fn sample_expression(binding: Option<usize>, filter: u32, grey: bool, coordinates: impl FnOnce() -> Option<String>) -> Option<String> {
|
||||
let read = match binding {
|
||||
Some(binding) => format!("sample_{binding}({}, {filter}u)", coordinates()?),
|
||||
None => "vec4f(0.0)".into(),
|
||||
};
|
||||
Some(if grey { format!("tc_lum({read})") } else { read })
|
||||
}
|
||||
|
||||
/// A `vecNf(..)` of the scalar parts of a vector node (`defaults` stand in for the parts that are not linked). A linked
|
||||
/// vector fills several lanes on the CPU, which this cannot say, so it is left to the CPU (`None`).
|
||||
fn vec_expression(
|
||||
n: u8,
|
||||
defaults: &[f64; 4],
|
||||
operand: &dyn Fn(usize) -> Option<u32>,
|
||||
pin: &dyn Fn(u32) -> Option<Pin>,
|
||||
float: &dyn Fn(usize, usize) -> Option<String>,
|
||||
) -> Option<String> {
|
||||
if has_vector_part(operand, pin) {
|
||||
return None;
|
||||
}
|
||||
let values = defaults
|
||||
.iter()
|
||||
.take(n as usize)
|
||||
.enumerate()
|
||||
.map(|(i, &d)| if operand(i).is_none() { Some(format!("bitcast<f32>({}u)", (d as f32).to_bits())) } else { float(i, 1) })
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
Some(format!("vec{n}f({})", values.join(", ")))
|
||||
}
|
||||
|
||||
/// WGSL for "`value` is not zero": a vector is true when one of its lanes is.
|
||||
fn non_zero(value: &str, lanes: usize) -> String {
|
||||
if lanes > 1 { format!("any({value} != vec{lanes}f(0.0))") } else { format!("{value} != 0.0") }
|
||||
}
|
||||
|
||||
/// Whether any of an instruction's four operands is a vector (more than one lane).
|
||||
fn has_vector_part(operand: &dyn Fn(usize) -> Option<u32>, pin: &dyn Fn(u32) -> Option<Pin>) -> bool {
|
||||
(0..4).any(|slot| operand(slot).and_then(pin).is_some_and(|p| p.lanes() > 1))
|
||||
}
|
||||
|
||||
fn expression(
|
||||
code: &Code,
|
||||
index: usize,
|
||||
pins: &[Option<Pin>],
|
||||
inputs: &[(&str, SampleImage<'_>)],
|
||||
images: &mut Vec<usize>,
|
||||
bindings: &mut Vec<(u32, Option<usize>)>,
|
||||
) -> Option<String> {
|
||||
let instruction = code.insts.get(index)?;
|
||||
let operand = |slot: usize| instruction.ins.get(slot).copied().filter(|&i| i != NONE);
|
||||
let pin = |id: u32| pins.get(id as usize).copied().flatten();
|
||||
let value = |slot: usize| Some(format!("r{}", operand(slot)?));
|
||||
let float = |slot: usize, lanes: usize| {
|
||||
let src = operand(slot)?;
|
||||
Some(float_expression(src, pin(src)?, lanes))
|
||||
};
|
||||
let lanes = pins.get(index)?.as_ref()?.lanes();
|
||||
let input_lanes = |slot| operand(slot).and_then(pin).map_or(1, Pin::lanes);
|
||||
Some(match instruction.op {
|
||||
Op::Pos => "pos".into(),
|
||||
Op::Un(U::Not) => format!("!{}", value(0)?),
|
||||
Op::Un(op) => unary(op, &float(0, input_lanes(0))?, input_lanes(0))?,
|
||||
Op::Bin(B::And) => format!("{} && {}", value(0)?, value(1)?),
|
||||
Op::Bin(B::Or) => format!("{} || {}", value(0)?, value(1)?),
|
||||
Op::Bin(B::Eq | B::Ne | B::Xor) if operand(0).and_then(pin) == Some(Pin::Bool) && operand(1).and_then(pin) == Some(Pin::Bool) => {
|
||||
format!("{} {} {}", value(0)?, if instruction.op == Op::Bin(B::Eq) { "==" } else { "!=" }, value(1)?)
|
||||
}
|
||||
Op::Bin(op) => {
|
||||
let n = input_lanes(0).max(input_lanes(1));
|
||||
binary(op, &float(0, n)?, &float(1, n)?, n)?
|
||||
}
|
||||
Op::Vec(n, false) => vec_expression(n, code.vec_defaults.get(instruction.x as usize)?, &operand, &pin, &float)?,
|
||||
Op::Swizzle => {
|
||||
let (components, n) = code.swizzles.get(instruction.x as usize)?.as_ref()?;
|
||||
swizzle_expression(&float(0, 1)?, input_lanes(0), components, *n)?
|
||||
}
|
||||
Op::SampleColor | Op::SampleGray => {
|
||||
let info = code.samples.get(instruction.x as usize)?;
|
||||
let binding = sample_binding(instruction.x, &info.slot, inputs, images, bindings);
|
||||
sample_expression(binding, info.filter.unwrap_or(1), instruction.op == Op::SampleGray, || float(0, 2))?
|
||||
}
|
||||
Op::Clamp => {
|
||||
let (a, lo, hi) = (float(0, lanes)?, float(1, lanes)?, float(2, lanes)?);
|
||||
format!("clamp({a}, min({lo}, {hi}), max({lo}, {hi}))")
|
||||
}
|
||||
Op::Lerp => {
|
||||
let (a, b, t) = (float(0, lanes)?, float(1, lanes)?, float(2, lanes)?);
|
||||
format!("{a} + ({b} - {a}) * {t}")
|
||||
}
|
||||
Op::Smooth => call_lanes("tc_smooth", &[float(0, lanes)?, float(1, lanes)?, float(2, lanes)?], lanes),
|
||||
Op::If => {
|
||||
let condition = value(0)?;
|
||||
let read =
|
||||
if pins.get(index).copied().flatten() == Some(Pin::Bool) { [value(1)?, value(2)?] } else { [float(1, lanes)?, float(2, lanes)?] };
|
||||
let [on_true, on_false] = read;
|
||||
format!("select({on_false}, {on_true}, {condition})")
|
||||
}
|
||||
Op::ToFloat => float(0, lanes)?,
|
||||
Op::ToBool => {
|
||||
let n = input_lanes(0);
|
||||
non_zero(&float(0, if n > 1 { n } else { 1 })?, n)
|
||||
}
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn call_lanes(function: &str, args: &[String], n: usize) -> String {
|
||||
if n == 1 {
|
||||
return format!("{function}({})", args.join(", "));
|
||||
}
|
||||
let lanes = (0..n)
|
||||
.map(|i| {
|
||||
let fields = args.iter().map(|v| format!("{v}[{i}u]")).collect::<Vec<_>>();
|
||||
format!("{function}({})", fields.join(", "))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
format!("vec{n}f({})", lanes.join(", "))
|
||||
}
|
||||
|
||||
fn unary(op: U, a: &str, n: usize) -> Option<String> {
|
||||
let broadcast = |v: &str| if n == 1 { v.to_owned() } else { format!("vec{n}f({v})") };
|
||||
let z = broadcast("0.0");
|
||||
let one = broadcast("1.0");
|
||||
let call = |f| format!("{f}({a})");
|
||||
Some(match op {
|
||||
U::Neg => format!("-{a}"),
|
||||
U::Abs => call("abs"),
|
||||
U::Sqrt => format!("sqrt(max({a}, {z}))"),
|
||||
U::Exp => format!("exp(min({a}, {}))", broadcast("80.0")),
|
||||
U::Log | U::LogFloor | U::Log2 => format!(
|
||||
"select({}, {f}({a}), {a} > {z})",
|
||||
if op == U::LogFloor { broadcast("-1e30") } else { z.clone() },
|
||||
f = if op == U::Log2 { "log2" } else { "log" }
|
||||
),
|
||||
U::Sin => call("sin"),
|
||||
U::Cos => call("cos"),
|
||||
U::SinPoly | U::CosPoly | U::SinF32Turns | U::CosF32Turns => {
|
||||
let f = match op {
|
||||
U::SinPoly => "tc_sin_poly",
|
||||
U::CosPoly => "tc_cos_poly",
|
||||
U::SinF32Turns => "tc_sin_turns",
|
||||
_ => "tc_cos_turns",
|
||||
};
|
||||
call_lanes(f, &[a.to_owned()], n)
|
||||
}
|
||||
U::Tan => call("tan"),
|
||||
U::Asin | U::Acos => format!("{}(clamp({a}, {}, {one}))", if op == U::Asin { "asin" } else { "acos" }, broadcast("-1.0")),
|
||||
U::Atan => call("atan"),
|
||||
U::Rad => call("radians"),
|
||||
U::Deg => call("degrees"),
|
||||
U::Floor => call("floor"),
|
||||
U::Ceil => call("ceil"),
|
||||
U::Round => format!("sign({a}) * floor(abs({a}) + {})", broadcast("0.5")),
|
||||
U::Fract => call("fract"),
|
||||
U::Sign => call("sign"),
|
||||
U::Sat => call("saturate"),
|
||||
U::Length => call(if n == 1 { "abs" } else { "length" }),
|
||||
U::Normalize if n == 1 => format!("select(0.0, sign({a}), abs({a}) > 1e-12)"),
|
||||
U::Normalize => format!("select({z}, {a} / length({a}), length({a}) > 1e-12)"),
|
||||
U::Not => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn binary(op: B, a: &str, b: &str, n: usize) -> Option<String> {
|
||||
let zero = if n == 1 { "0.0".to_owned() } else { format!("vec{n}f(0.0)") };
|
||||
let call = |f| format!("{f}({a}, {b})");
|
||||
let map = |f| call_lanes(f, &[a.to_owned(), b.to_owned()], n);
|
||||
Some(match op {
|
||||
B::Add => format!("{a} + {b}"),
|
||||
B::Sub => format!("{a} - {b}"),
|
||||
B::Mul => format!("{a} * {b}"),
|
||||
B::Div => format!("select({zero}, {a} / {b}, {b} != {zero})"),
|
||||
B::DivLarge => map("tc_div_large"),
|
||||
B::Mod => format!("select({zero}, {a} - {b} * floor({a} / {b}), {b} != {zero})"),
|
||||
B::Pow => map("tc_pow"),
|
||||
B::Min => call("min"),
|
||||
B::Max => call("max"),
|
||||
B::Atan2 => call("atan2"),
|
||||
B::Atan2Approx => map("tc_atan2"),
|
||||
B::Step => call("step"),
|
||||
B::Dot if n == 1 => format!("{a} * {b}"),
|
||||
B::Dot => call("dot"),
|
||||
B::Cross => call("cross"),
|
||||
B::Distance if n == 1 => format!("abs({a} - {b})"),
|
||||
B::Distance => call("distance"),
|
||||
B::Eq if n == 1 => format!("{a} == {b}"),
|
||||
B::Ne if n == 1 => format!("{a} != {b}"),
|
||||
B::Eq => format!("all({a} == {b})"),
|
||||
B::Ne => format!("any({a} != {b})"),
|
||||
B::Lt => format!("{a} < {b}"),
|
||||
B::Le => format!("{a} <= {b}"),
|
||||
B::Gt => format!("{a} > {b}"),
|
||||
B::Ge => format!("{a} >= {b}"),
|
||||
B::And | B::Or | B::Xor => return None,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::graph::Graph;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The pixel shader of a single-precision function made of `body`, if it can be lowered.
|
||||
fn shader(body: &str) -> Option<PixelShader> {
|
||||
let g = Graph::parse_unchecked(&format!("meta kind \"function\"\nmeta float32 \"1\"\n{body}")).unwrap();
|
||||
Prog::compile(&g, &BTreeMap::new()).unwrap().pixel_shader(&FnEnv::new([8.0, 8.0]))
|
||||
}
|
||||
|
||||
/// A float2 is true when one of its lanes is: comparing a `vec2f` with the scalar `0.0` is not valid WGSL.
|
||||
#[test]
|
||||
fn a_vector_is_reduced_to_a_bool_with_any() {
|
||||
let s = shader("node 1 f_pos\nnode 2 f_to_bool a=@1\nnode 3 f_out in=@2\n").expect("a shader for the position test");
|
||||
assert!(s.source.contains("any(") && s.source.contains("!= vec2f(0.0))"), "{}", s.source);
|
||||
let s =
|
||||
shader("node 1 f_pos\nnode 4 f_swizzle a=@1 mask=\"x\"\nnode 2 f_to_bool a=@4\nnode 3 f_out in=@2\n").expect("a shader for the scalar");
|
||||
assert!(!s.source.contains("any("), "a scalar is compared as it is: {}", s.source);
|
||||
}
|
||||
|
||||
/// A linked vector fills several lanes of the vector on the CPU, which `vec2f(r1, 0.5)` in WGSL would not say.
|
||||
#[test]
|
||||
fn a_vector_part_of_a_vector_is_left_to_the_cpu() {
|
||||
assert!(shader("node 1 f_pos\nnode 2 f_vec4 x=@1 y=0.5\nnode 3 f_out in=@2\n").is_none());
|
||||
// scalar parts still lower
|
||||
assert!(shader("node 1 f_pos\nnode 4 f_swizzle a=@1 mask=\"x\"\nnode 2 f_vec4 x=@4 y=0.5\nnode 3 f_out in=@2\n").is_some());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Recursive pattern construction ("pattern programs").
|
||||
//!
|
||||
//! A pattern program is a small graph (meta `kind "fxmap"`) of `fxm_*` nodes that is walked from its `fxm_out` node.
|
||||
//! The walk carries a *cell*: a centre, a size, a rotation, a value and a colour. Nodes either change the cell and
|
||||
//! run children (`fxm_quadrant`, `fxm_iterate`, `fxm_switch`) or draw into the canvas (`fxm_marker`).
|
||||
//! The `fx_map` node of a texture graph runs a program and rasterises the markers; the canvas wraps at its edges so
|
||||
//! the result tiles.
|
||||
|
||||
use crate::graph::{Graph, Node};
|
||||
use crate::math;
|
||||
use crate::noise::rnd;
|
||||
use crate::tex::{Tex, lum};
|
||||
|
||||
/// Most markers one pattern program may draw (a guard, not measured).
|
||||
pub const MAX_MARKERS: usize = 500_000;
|
||||
|
||||
pub const FXM_KINDS: &[&str] = &["fxm_out", "fxm_marker", "fxm_quadrant", "fxm_iterate", "fxm_switch"];
|
||||
|
||||
pub fn is_program(g: &Graph) -> bool {
|
||||
g.meta.get("kind").map(|k| k == "fxmap").unwrap_or(false)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Cell {
|
||||
x: f32,
|
||||
y: f32,
|
||||
w: f32,
|
||||
h: f32,
|
||||
rot: f32,
|
||||
val: f32,
|
||||
col: [f32; 3],
|
||||
}
|
||||
|
||||
/// Settings of one run.
|
||||
pub struct Run<'a> {
|
||||
pub depth: u32,
|
||||
pub seed: u32,
|
||||
/// 0 max, 1 add, 2 over (alpha blend), 3 min, 4 multiply
|
||||
pub blend: u32,
|
||||
pub color: bool,
|
||||
pub patterns: &'a [Option<&'a Tex>; 4],
|
||||
}
|
||||
|
||||
struct Walk<'a> {
|
||||
g: &'a Graph,
|
||||
run: &'a Run<'a>,
|
||||
canvas: Tex,
|
||||
markers: usize,
|
||||
counter: u32,
|
||||
over: bool,
|
||||
}
|
||||
|
||||
fn n(node: &Node, k: &str, d: f32) -> f32 {
|
||||
node.nums.get(k).copied().unwrap_or(d)
|
||||
}
|
||||
|
||||
impl<'a> Walk<'a> {
|
||||
fn rand(&mut self, salt: u32) -> f32 {
|
||||
self.counter = self.counter.wrapping_add(1);
|
||||
rnd(self.counter as i32, salt as i32, self.run.seed)
|
||||
}
|
||||
|
||||
fn signed(&mut self, salt: u32) -> f32 {
|
||||
self.rand(salt) * 2.0 - 1.0
|
||||
}
|
||||
|
||||
fn visit(&mut self, id: u32, cell: Cell, depth: u32) {
|
||||
if depth > self.run.depth || self.markers >= MAX_MARKERS || self.over {
|
||||
return;
|
||||
}
|
||||
let Some(node) = self.g.nodes.get(&id) else { return };
|
||||
match node.kind.as_str() {
|
||||
"fxm_out" => {
|
||||
if let Some(c) = node.ins.get("in") {
|
||||
self.visit(*c, cell, depth + 1);
|
||||
}
|
||||
}
|
||||
"fxm_marker" => self.marker(node, cell),
|
||||
"fxm_quadrant" => {
|
||||
let (sin, cos) = math::sin_cos(cell.rot);
|
||||
let scale = n(node, "scale", 0.5).max(0.0);
|
||||
for q in 0..4usize {
|
||||
let Some(child) = node.ins.get(&format!("q{q}")) else { continue };
|
||||
if self.rand(10 + q as u32) > n(node, &format!("p{q}"), 1.0) {
|
||||
continue;
|
||||
}
|
||||
// quadrant centres at (-1/4, -1/4), (1/4, -1/4), (-1/4, 1/4), (1/4, 1/4) of the cell
|
||||
let (qx, qy) = (if q % 2 == 0 { -0.25 } else { 0.25 }, if q < 2 { -0.25 } else { 0.25 });
|
||||
let (ox, oy) = (qx * cell.w + n(node, "off_x", 0.0) * cell.w, qy * cell.h + n(node, "off_y", 0.0) * cell.h);
|
||||
let rx = n(node, "rnd_pos", 0.0) * cell.w * self.signed(20 + q as u32);
|
||||
let ry = n(node, "rnd_pos", 0.0) * cell.h * self.signed(30 + q as u32);
|
||||
let rs = 1.0 + n(node, "rnd_scale", 0.0) * self.signed(40 + q as u32);
|
||||
let rr = n(node, "rnd_rot", 0.0).to_radians() * self.signed(50 + q as u32);
|
||||
let rv = 1.0 + n(node, "rnd_val", 0.0) * self.signed(60 + q as u32);
|
||||
let c = Cell {
|
||||
x: cell.x + (ox + rx) * cos - (oy + ry) * sin,
|
||||
y: cell.y + (ox + rx) * sin + (oy + ry) * cos,
|
||||
w: cell.w * scale * rs,
|
||||
h: cell.h * scale * rs,
|
||||
rot: cell.rot + n(node, &format!("r{q}"), 0.0).to_radians() + rr,
|
||||
val: cell.val * n(node, &format!("v{q}"), 1.0) * rv,
|
||||
col: cell.col,
|
||||
};
|
||||
self.visit(*child, c, depth + 1);
|
||||
}
|
||||
}
|
||||
"fxm_iterate" => {
|
||||
let Some(body) = node.ins.get("body").copied() else { return };
|
||||
let (gx, gy) = (n(node, "grid_x", 0.0).round() as i32, n(node, "grid_y", 0.0).round() as i32);
|
||||
let count = if gx > 0 && gy > 0 { gx * gy } else { n(node, "count", 4.0).round().clamp(0.0, 100_000.0) as i32 };
|
||||
let (sin, cos) = math::sin_cos(cell.rot);
|
||||
let mut cur = cell;
|
||||
for i in 0..count {
|
||||
if self.markers >= MAX_MARKERS {
|
||||
break;
|
||||
}
|
||||
let mut c = cur;
|
||||
if gx > 0 && gy > 0 {
|
||||
// a grid of equal cells filling the current one
|
||||
let (ix, iy) = (i % gx, i / gx);
|
||||
let stagger = if iy % 2 == 1 { n(node, "stagger", 0.0) } else { 0.0 };
|
||||
let (lx, ly) = (((ix as f32 + 0.5 + stagger) / gx as f32 - 0.5) * cell.w, ((iy as f32 + 0.5) / gy as f32 - 0.5) * cell.h);
|
||||
c.x = cell.x + lx * cos - ly * sin;
|
||||
c.y = cell.y + lx * sin + ly * cos;
|
||||
c.w = cell.w / gx as f32;
|
||||
c.h = cell.h / gy as f32;
|
||||
}
|
||||
let rx = n(node, "rnd_x", 0.0) * cur.w * self.signed(70);
|
||||
let ry = n(node, "rnd_y", 0.0) * cur.h * self.signed(71);
|
||||
c.x += rx * cos - ry * sin;
|
||||
c.y += rx * sin + ry * cos;
|
||||
let rs = 1.0 + n(node, "rnd_scale", 0.0) * self.signed(72);
|
||||
c.w *= rs;
|
||||
c.h *= rs;
|
||||
c.rot += n(node, "rnd_rot", 0.0).to_radians() * self.signed(73);
|
||||
c.val *= 1.0 + n(node, "rnd_val", 0.0) * self.signed(74);
|
||||
self.visit(body, c, depth + 1);
|
||||
// per-iteration change of the running cell
|
||||
let (dx, dy) = (n(node, "dx", 0.0) * cur.w, n(node, "dy", 0.0) * cur.h);
|
||||
let (s2, c2) = math::sin_cos(cur.rot);
|
||||
cur.x += dx * c2 - dy * s2;
|
||||
cur.y += dx * s2 + dy * c2;
|
||||
let ds = n(node, "dscale", 1.0);
|
||||
cur.w *= ds;
|
||||
cur.h *= ds;
|
||||
cur.rot += n(node, "drot", 0.0).to_radians();
|
||||
cur.val *= n(node, "dval", 1.0);
|
||||
}
|
||||
}
|
||||
"fxm_switch" => {
|
||||
let slots = ["a", "b", "c", "d"];
|
||||
let live: Vec<usize> = slots.iter().enumerate().filter(|(_, s)| node.ins.contains_key(**s)).map(|(i, _)| i).collect();
|
||||
let Some(last) = live.last().copied() else { return };
|
||||
let pick = if n(node, "mode", 0.0) > 0.5 {
|
||||
// weighted random choice among the connected slots
|
||||
let total: f32 = live.iter().map(|i| n(node, &format!("w{i}"), 1.0).max(0.0)).sum();
|
||||
if total <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let mut r = self.rand(80) * total;
|
||||
let mut chosen = last;
|
||||
for i in &live {
|
||||
r -= n(node, &format!("w{i}"), 1.0).max(0.0);
|
||||
if r <= 0.0 {
|
||||
chosen = *i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
chosen
|
||||
} else {
|
||||
let want = n(node, "index", 0.0).round().max(0.0) as usize;
|
||||
live.get(want % live.len()).copied().unwrap_or(last)
|
||||
};
|
||||
if let Some(child) = slots.get(pick).and_then(|s| node.ins.get(*s)) {
|
||||
self.visit(*child, cell, depth + 1);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn marker(&mut self, node: &Node, cell: Cell) {
|
||||
self.markers += 1;
|
||||
let (px, py) = (n(node, "x", 0.0), n(node, "y", 0.0));
|
||||
let (sin, cos) = math::sin_cos(cell.rot);
|
||||
let rx = n(node, "rnd_pos", 0.0) * self.signed(90);
|
||||
let ry = n(node, "rnd_pos", 0.0) * self.signed(91);
|
||||
let ox = (px + rx) * cell.w;
|
||||
let oy = (py + ry) * cell.h;
|
||||
let cx = cell.x + ox * cos - oy * sin;
|
||||
let cy = cell.y + ox * sin + oy * cos;
|
||||
let rs = 1.0 + n(node, "rnd_scale", 0.0) * self.signed(92);
|
||||
let (w, h) = (cell.w * n(node, "w", 1.0) * rs, cell.h * n(node, "h", 1.0) * rs);
|
||||
let rot = cell.rot + n(node, "rot", 0.0).to_radians() + n(node, "rnd_rot", 0.0).to_radians() * self.signed(93);
|
||||
let val = (cell.val * n(node, "value", 1.0) * (1.0 + n(node, "rnd_val", 0.0) * self.signed(94))).max(0.0);
|
||||
let mut col = cell.col;
|
||||
let rc = n(node, "rnd_color", 0.0);
|
||||
let tint = [n(node, "r", 1.0), n(node, "g", 1.0), n(node, "b", 1.0)];
|
||||
for (k, (c, tint)) in col.iter_mut().zip(tint).enumerate() {
|
||||
*c *= tint * (1.0 + rc * self.signed(95 + k as u32));
|
||||
}
|
||||
let shape = n(node, "shape", 0.0).round() as i32;
|
||||
let soft = n(node, "softness", 0.02).clamp(0.0, 1.0);
|
||||
let src = n(node, "src", 0.0).round().clamp(0.0, 3.0) as usize;
|
||||
let pattern = if shape == 3 { self.run.patterns.get(src).copied().flatten() } else { None };
|
||||
let (cw, ch) = (self.canvas.w as i32, self.canvas.h as i32);
|
||||
let (pxw, pxh) = (cw as f32, ch as f32);
|
||||
// pixel bounding circle of the rotated rectangle
|
||||
let rad = 0.5 * (w * w + h * h).sqrt();
|
||||
if rad <= 0.0 || !rad.is_finite() {
|
||||
return;
|
||||
}
|
||||
let (x0, x1) = (((cx - rad) * pxw).floor() as i32, ((cx + rad) * pxw).ceil() as i32);
|
||||
let (y0, y1) = (((cy - rad) * pxh).floor() as i32, ((cy + rad) * pxh).ceil() as i32);
|
||||
if (x1 - x0) > cw * 2 || (y1 - y0) > ch * 2 {
|
||||
return;
|
||||
}
|
||||
let (rs_, rc_) = math::sin_cos(-rot);
|
||||
for y in y0..=y1 {
|
||||
for x in x0..=x1 {
|
||||
let (u, v) = ((x as f32 + 0.5) / pxw - cx, (y as f32 + 0.5) / pxh - cy);
|
||||
let (lx, ly) = ((u * rc_ - v * rs_) / (w * 0.5).max(1e-6), (u * rs_ + v * rc_) / (h * 0.5).max(1e-6));
|
||||
let (cover, pat_col) = match shape {
|
||||
1 => (edge(lx.abs().max(ly.abs()), soft), None),
|
||||
2 => (edge(lx.abs() + ly.abs(), soft), None),
|
||||
3 => {
|
||||
if lx.abs() > 1.0 || ly.abs() > 1.0 {
|
||||
(0.0, None)
|
||||
} else if let Some(t) = pattern {
|
||||
let c = t.sample(lx * 0.5 + 0.5, ly * 0.5 + 0.5);
|
||||
(lum(c) * c[3], Some([c[0], c[1], c[2]]))
|
||||
} else {
|
||||
(1.0, None)
|
||||
}
|
||||
}
|
||||
_ => (edge((lx * lx + ly * ly).sqrt(), soft), None),
|
||||
};
|
||||
if cover <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let (wx, wy) = (x.rem_euclid(cw) as usize, y.rem_euclid(ch) as usize);
|
||||
let Some(dst) = self.canvas.px.get_mut(wy * cw as usize + wx) else { continue };
|
||||
let src_c = match (self.run.color, pat_col) {
|
||||
(true, Some(p)) => [p[0] * col[0], p[1] * col[1], p[2] * col[2]],
|
||||
(true, None) => [col[0], col[1], col[2]],
|
||||
(false, Some(p)) => {
|
||||
let l = (p[0] + p[1] + p[2]) / 3.0;
|
||||
[l, l, l]
|
||||
}
|
||||
(false, None) => [1.0, 1.0, 1.0],
|
||||
};
|
||||
for (d, src_c) in dst.iter_mut().zip(src_c) {
|
||||
let sv = src_c * val;
|
||||
let s = sv * if pat_col.is_some() { 1.0 } else { cover };
|
||||
let c = cover.min(1.0);
|
||||
*d = match self.run.blend {
|
||||
1 => *d + s,
|
||||
2 => *d + (sv - *d) * c,
|
||||
3 => *d + (d.min(sv) - *d) * c,
|
||||
4 => *d * (1.0 + (sv - 1.0) * c),
|
||||
_ => d.max(s),
|
||||
};
|
||||
}
|
||||
dst[3] = 1.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 1 inside, 0 outside, soft over the outer `soft` of the unit radius.
|
||||
fn edge(d: f32, soft: f32) -> f32 {
|
||||
if d >= 1.0 {
|
||||
0.0
|
||||
} else if soft <= 1e-4 || d <= 1.0 - soft {
|
||||
1.0
|
||||
} else {
|
||||
let t = (1.0 - d) / soft;
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `program` on a `w` by `h` canvas filled with `background`.
|
||||
pub fn render(program: &Graph, w: usize, h: usize, background: [f32; 3], run: &Run) -> Result<Tex, String> {
|
||||
let outs: Vec<u32> = program.nodes.iter().filter(|(_, n)| n.kind == "fxm_out").map(|(i, _)| *i).collect();
|
||||
let root = match outs.as_slice() {
|
||||
[one] => *one,
|
||||
[] => return Err("the pattern program has no Output node".into()),
|
||||
_ => return Err("the pattern program has more than one Output node".into()),
|
||||
};
|
||||
for (id, node) in &program.nodes {
|
||||
if !FXM_KINDS.contains(&node.kind.as_str()) {
|
||||
return Err(format!("node {id} ({}) is not a pattern-program node", node.kind));
|
||||
}
|
||||
}
|
||||
program.check_cycles().map_err(|e| e.to_string())?;
|
||||
let mut walk =
|
||||
Walk { g: program, run, canvas: Tex::solid(w, h, [background[0], background[1], background[2], 1.0]), markers: 0, counter: 0, over: false };
|
||||
let start = Cell { x: 0.5, y: 0.5, w: 1.0, h: 1.0, rot: 0.0, val: 1.0, col: [1.0, 1.0, 1.0] };
|
||||
walk.visit(root, start, 0);
|
||||
if walk.markers >= MAX_MARKERS {
|
||||
return Err(format!("the pattern program draws more than {MAX_MARKERS} markers"));
|
||||
}
|
||||
Ok(walk.canvas)
|
||||
}
|
||||
|
||||
pub const FXM_SPECS: &[crate::graph::Spec] = &[
|
||||
crate::graph::Spec { kind: "fxm_out", req: &["in"], opt: &[], doc: "start of a pattern program" },
|
||||
crate::graph::Spec {
|
||||
kind: "fxm_marker",
|
||||
req: &[],
|
||||
opt: &[],
|
||||
doc: "draw a shape: shape (0 circle 1 square 2 diamond 3 image) src x y w h rot value r g b softness rnd_pos rnd_scale rnd_rot rnd_val rnd_color",
|
||||
},
|
||||
crate::graph::Spec {
|
||||
kind: "fxm_quadrant",
|
||||
req: &[],
|
||||
opt: &["q0", "q1", "q2", "q3"],
|
||||
doc: "split the cell in four: scale off_x off_y p0..p3 (chance) v0..v3 (value) r0..r3 (rotation) rnd_pos rnd_scale rnd_rot rnd_val",
|
||||
},
|
||||
crate::graph::Spec {
|
||||
kind: "fxm_iterate",
|
||||
req: &[],
|
||||
opt: &["body"],
|
||||
doc: "repeat body: count dx dy dscale drot dval, or grid_x grid_y stagger; rnd_x rnd_y rnd_scale rnd_rot rnd_val",
|
||||
},
|
||||
crate::graph::Spec { kind: "fxm_switch", req: &[], opt: &["a", "b", "c", "d"], doc: "run one branch: mode (0 index, 1 random) index w0..w3" },
|
||||
];
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,110 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Our own grunge map family (fifteen procedural looks: specks, drips, blotches, scratches, crazing, cracks).
|
||||
//! Each recipe builds a tileable "dirt" field from our noise primitives; `GrungeP` then thresholds it with balance /
|
||||
//! contrast like a grunge map. The recipes are our own procedural designs.
|
||||
//! [`GrungeVariant`] holds the four looks of the `grunge` node (concrete, scratches, spots, smudges).
|
||||
use crate::math;
|
||||
use crate::noise;
|
||||
|
||||
mod variants;
|
||||
|
||||
pub use variants::{GrungeVariant, Variant};
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct GrungeP {
|
||||
pub map: u32,
|
||||
pub seed: u32,
|
||||
pub balance: f32,
|
||||
pub contrast: f32,
|
||||
pub brush: f32,
|
||||
pub cracks: f32,
|
||||
pub disorder: f32,
|
||||
}
|
||||
|
||||
fn smooth(a: f32, b: f32, x: f32) -> f32 {
|
||||
let t = ((x - a) / (b - a).max(1e-6)).clamp(0.0, 1.0);
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
|
||||
/// Coverage threshold of each map (dirt where the field exceeds it); tuned so the default looks have a similar
|
||||
/// amount of dirt to the originals.
|
||||
pub const T0: [f32; 15] = [0.846, 0.733, 0.695, 0.214, 0.849, 0.775, 0.672, 0.504, 0.695, 0.405, 0.432, 0.797, 0.473, 0.701, 0.783];
|
||||
|
||||
fn blot(a: f32, b: f32, px: i32, seed: u32) -> f32 {
|
||||
noise::fbm(a, b, px, px, 5, 0.55, seed, 0)
|
||||
}
|
||||
|
||||
fn streak(a: f32, b: f32, px: i32, py: i32, seed: u32) -> f32 {
|
||||
noise::fbm(a, b, px, py, 4, 0.55, seed, 0)
|
||||
}
|
||||
|
||||
fn vband(b: f32, centre: f32) -> f32 {
|
||||
0.5 + 0.5 * math::cos(std::f32::consts::TAU * (b - centre))
|
||||
}
|
||||
|
||||
fn crack(a: f32, b: f32, px: i32, seed: u32, width: f32) -> f32 {
|
||||
// jagged hairline cracks: a fine warp roughens the cell borders, the width wanders along each crack, short gaps
|
||||
// break them up and a second, smaller network adds branches
|
||||
let jx = noise::fbm(a, b, 48, 48, 3, 0.6, seed.wrapping_add(61), 0) - 0.5;
|
||||
let jy = noise::fbm(a, b, 48, 48, 3, 0.6, seed.wrapping_add(62), 0) - 0.5;
|
||||
let (ja, jb) = ((a + jx * 0.03).rem_euclid(1.0), (b + jy * 0.03).rem_euclid(1.0));
|
||||
let wv = 0.35 + 1.3 * noise::fbm(a, b, 36, 36, 2, 0.5, seed.wrapping_add(63), 0);
|
||||
let gap = smooth(0.28, 0.5, noise::fbm(a, b, 28, 28, 3, 0.55, seed.wrapping_add(64), 0));
|
||||
let (f1, f2, _) = noise::voronoi(ja, jb, px, px, seed, 1.0);
|
||||
let main = 1.0 - smooth(0.0, width * wv, f2 - f1);
|
||||
let (g1, g2, _) = noise::voronoi(ja, jb, px * 2 + 1, px * 2 + 1, seed.wrapping_add(65), 1.0);
|
||||
let branch = (1.0 - smooth(0.0, width * 0.5 * wv, g2 - g1)) * smooth(0.45, 0.65, noise::fbm(a, b, 14, 14, 3, 0.55, seed.wrapping_add(66), 0));
|
||||
(main.max(branch * 0.9)) * gap
|
||||
}
|
||||
|
||||
/// Dirt field in 0..1 (higher = more dirt) for map 1..=15.
|
||||
pub fn dirt(p: &GrungeP, u: f32, v: f32) -> f32 {
|
||||
let s = p.seed;
|
||||
let (mut a, mut b) = (u, v);
|
||||
if p.disorder > 0.0 {
|
||||
let w = noise::fbm(u, v, 4, 4, 3, 0.5, s.wrapping_add(900), 0) - 0.5;
|
||||
let w2 = noise::fbm(u, v, 4, 4, 3, 0.5, s.wrapping_add(901), 0) - 0.5;
|
||||
a = (u + w * p.disorder * 0.2).rem_euclid(1.0);
|
||||
b = (v + w2 * p.disorder * 0.2).rem_euclid(1.0);
|
||||
}
|
||||
// every map gets a ragged edge: a small turbulent warp plus fine grain, so nothing looks like a clean cell or disc
|
||||
let rag = if matches!(p.map, 9..=11 | 13) { 0.02 } else { 0.03 };
|
||||
let (wu, wv) = (noise::fbm(a, b, 20, 20, 4, 0.55, s.wrapping_add(940), 0) - 0.5, noise::fbm(a, b, 20, 20, 4, 0.55, s.wrapping_add(941), 0) - 0.5);
|
||||
let (a, b) = ((a + wu * rag * 2.0).rem_euclid(1.0), (b + wv * rag * 2.0).rem_euclid(1.0));
|
||||
let grain = (noise::fbm(a, b, 200, 200, 2, 0.6, s.wrapping_add(950), 0) - 0.5) * 0.25;
|
||||
let d = match p.map {
|
||||
1 => 0.55 * blot(a, b, 6, s) + 0.45 * noise::fbm(a, b, 96, 96, 2, 0.5, s.wrapping_add(1), 0),
|
||||
2 => 0.6 * streak(a, b, 48, 3, s) + 0.4 * blot(a, b, 4, s.wrapping_add(2)),
|
||||
3 => 0.65 * streak(a, b, 24, 2, s) + 0.35 * blot(a, b, 3, s.wrapping_add(3)),
|
||||
4 => 1.0 - noise::spots(a, b, 7, 7, s, |id| (0.2, 0.3 + id * 0.35), 0.0) * smooth(0.25, 0.5, blot(a, b, 3, s.wrapping_add(4))).max(0.35),
|
||||
5 => streak(a, b, 96, 2, s),
|
||||
6 => 0.5 * blot(a, b, 4, s) + 0.5 * math::powi(vband(b, 0.95), 2),
|
||||
7 => {
|
||||
let w = blot(a, b, 5, s.wrapping_add(6));
|
||||
0.7 * blot((a + w * 0.1).rem_euclid(1.0), (b + w * 0.1).rem_euclid(1.0), 7, s)
|
||||
+ 0.3 * noise::fbm(a, b, 40, 40, 3, 0.5, s.wrapping_add(1), 0)
|
||||
}
|
||||
8 => noise::spots(a, b, 40, 40, s, |id| (0.04, 0.08 + id * 0.1), 0.0) * 0.6 + 0.6 * blot(a, b, 6, s.wrapping_add(7)) - 0.2,
|
||||
9 => 0.5 * blot(a, b, 8, s) + 0.5 * noise::fbm(a, b, 128, 128, 2, 0.6, s.wrapping_add(8), 0),
|
||||
10 => 0.7 * crack(a, b, 14, s, 0.05) * smooth(0.35, 0.6, blot(a, b, 5, s.wrapping_add(20))) + 0.65 * blot(a, b, 6, s.wrapping_add(9)) - 0.15,
|
||||
11 => {
|
||||
p.cracks * 1.0 * crack(a, b, 10, s, 0.06) * smooth(0.3, 0.55, blot(a, b, 4, s.wrapping_add(21))) + 0.5 * blot(a, b, 6, s.wrapping_add(10))
|
||||
}
|
||||
12 => noise::spots(a, b, 56, 56, s, |id| (0.03, 0.06 + id * 0.05), 0.0) * 0.7 + 0.45 * blot(a, b, 8, s.wrapping_add(12)),
|
||||
13 => {
|
||||
p.cracks * 0.9 * crack(a, b, 6, s, 0.04) * smooth(0.4, 0.6, blot(a, b, 4, s.wrapping_add(22))) + 0.45 * blot(a, b, 6, s.wrapping_add(11))
|
||||
}
|
||||
14 => 0.6 * streak(a, b, 30, 2, s) + 0.4 * blot(a, b, 5, s.wrapping_add(13)) * 1.2,
|
||||
_ => streak(a, b, 120, 6, s) * (0.55 + 0.6 * vband(b, 0.0)),
|
||||
};
|
||||
let d = if p.brush > 0.0 { d * (1.0 + p.brush * (streak(a, b, 60, 4, s.wrapping_add(31)) - 0.5) * 1.5) } else { d };
|
||||
(d + grain).clamp(0.0, 1.5)
|
||||
}
|
||||
|
||||
/// Final grunge value: white where clean, black where dirty (before inversion).
|
||||
pub fn grunge_map(p: &GrungeP, u: f32, v: f32, t0: f32) -> f32 {
|
||||
let d = dirt(p, u, v);
|
||||
let x = 0.5 + (t0 - d) * 1.5 + (p.balance - 0.5) * 0.5;
|
||||
let w = (1.0 - p.contrast.clamp(0.0, 1.0)) * 0.45 + 0.01;
|
||||
smooth(0.5 - w, 0.5 + w, x)
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! [`GrungeVariant`]: the four looks of the `grunge` node (concrete, scratches, spots, smudges) as a point
|
||||
//! function of (u, v), tileable with period 1. Our own looks built from our noise primitives.
|
||||
|
||||
use crate::noise::{self, smoothstep as smooth};
|
||||
|
||||
/// Which look.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Variant {
|
||||
Concrete,
|
||||
Scratches,
|
||||
Spots,
|
||||
Smudges,
|
||||
}
|
||||
|
||||
impl Variant {
|
||||
/// 0 concrete, 1 scratches, 2 spots, anything else smudges.
|
||||
pub fn from_index(i: u32) -> Variant {
|
||||
match i {
|
||||
0 => Variant::Concrete,
|
||||
1 => Variant::Scratches,
|
||||
2 => Variant::Spots,
|
||||
_ => Variant::Smudges,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The settings of one grunge look. Ranges as the node clamps them.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct GrungeVariant {
|
||||
pub variant: Variant,
|
||||
pub seed: u32,
|
||||
/// 0..1, 0.5 neutral: added to the value.
|
||||
pub balance: f32,
|
||||
// concrete
|
||||
pub large_variation: f32,
|
||||
pub base_noisiness: f32,
|
||||
pub dirt_specks: f32,
|
||||
pub invert_dirt: bool,
|
||||
pub scratches: f32,
|
||||
pub sharpen: f32,
|
||||
// scratches
|
||||
/// Scratch columns (1..=32).
|
||||
pub quantity: i32,
|
||||
pub scratch_width: f32,
|
||||
pub scratch_length: f32,
|
||||
// spots
|
||||
/// Spot cells per side (1..=128).
|
||||
pub details: i32,
|
||||
pub coverage: f32,
|
||||
pub coverage_contrast: f32,
|
||||
}
|
||||
|
||||
impl GrungeVariant {
|
||||
/// The node's defaults for `variant`.
|
||||
pub fn new(variant: Variant, seed: u32) -> GrungeVariant {
|
||||
GrungeVariant {
|
||||
variant,
|
||||
seed,
|
||||
balance: 0.5,
|
||||
large_variation: 0.55,
|
||||
base_noisiness: 0.45,
|
||||
dirt_specks: 0.0,
|
||||
invert_dirt: false,
|
||||
scratches: 0.0,
|
||||
sharpen: 0.0,
|
||||
quantity: 3,
|
||||
scratch_width: 0.4,
|
||||
scratch_length: 0.45,
|
||||
details: 22,
|
||||
coverage: 0.35,
|
||||
coverage_contrast: 0.25,
|
||||
}
|
||||
}
|
||||
|
||||
/// The value at (a, b) (already warped by the caller, if at all), 0..1.
|
||||
pub fn value(&self, a: f32, b: f32) -> f32 {
|
||||
let seed = self.seed;
|
||||
let val = match self.variant {
|
||||
Variant::Concrete => {
|
||||
let n = noise::fbm(a, b, 8, 8, 6, 0.55, seed, 0) * self.large_variation
|
||||
+ noise::fbm(a, b, 40, 40, 3, 0.5, seed.wrapping_add(1), 0) * self.base_noisiness;
|
||||
let mut c = ((n - 0.35) * 2.2).clamp(0.0, 1.0);
|
||||
if self.dirt_specks > 0.0 {
|
||||
let sp = noise::spots(a, b, 64, 64, seed.wrapping_add(11), |id| (0.1, 0.18 + id * 0.2), 0.0);
|
||||
c = if self.invert_dirt { c + (1.0 - c) * sp * self.dirt_specks } else { c * (1.0 - sp * self.dirt_specks) };
|
||||
}
|
||||
if self.scratches > 0.0 {
|
||||
let line = noise::perlin(a * 3.0 % 1.0, b, 3, 160, seed.wrapping_add(13));
|
||||
c = (c + smooth(0.62, 0.7, line) * self.scratches).clamp(0.0, 1.0);
|
||||
}
|
||||
if self.sharpen > 0.0 {
|
||||
c += (smooth(0.0, 1.0, c) - c) * self.sharpen;
|
||||
}
|
||||
c
|
||||
}
|
||||
Variant::Scratches => {
|
||||
let (quant, width, length) = (self.quantity, self.scratch_width, self.scratch_length);
|
||||
let q = quant as f32;
|
||||
let line = noise::perlin(a * q % 1.0, b, quant, 90, seed);
|
||||
let m = noise::fbm(a, b, 5, 5, 4, 0.5, seed.wrapping_add(3), 0);
|
||||
smooth(1.0 - width, 1.1 - width, line) * smooth(length, length + 0.15, m)
|
||||
}
|
||||
Variant::Spots => {
|
||||
let (details, cover, cover_c) = (self.details, self.coverage, self.coverage_contrast);
|
||||
let m = noise::fbm(a, b, 6, 6, 4, 0.5, seed.wrapping_add(4), 0);
|
||||
noise::spots(a, b, details, details, seed, |id| (0.12, 0.2 + id * 0.3), 0.0) * smooth(cover, cover + cover_c, m)
|
||||
}
|
||||
Variant::Smudges => {
|
||||
let n = noise::fbm(a, b, 3, 3, 5, 0.6, seed, 2);
|
||||
smooth(0.2, 0.8, n)
|
||||
}
|
||||
};
|
||||
(val + (self.balance - 0.5)).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! IEEE 754 half-precision (f16) conversion, stored as `u16` bits.
|
||||
|
||||
/// Exact conversion: every f16 value is representable as f32.
|
||||
pub fn f16_to_f32(h: u16) -> f32 {
|
||||
let sign = ((h >> 15) as u32) << 31;
|
||||
let exp = ((h >> 10) & 0x1f) as u32;
|
||||
let man = (h & 0x3ff) as u32;
|
||||
let bits = match (exp, man) {
|
||||
(0, 0) => sign,
|
||||
(0, _) => {
|
||||
// subnormal: normalise the mantissa
|
||||
let shift = man.leading_zeros() - 21;
|
||||
let man = (man << shift) & 0x3ff;
|
||||
sign | ((113 - shift) << 23) | (man << 13)
|
||||
}
|
||||
(0x1f, 0) => sign | 0x7f80_0000,
|
||||
(0x1f, _) => sign | 0x7fc0_0000 | (man << 13),
|
||||
_ => sign | ((exp + 112) << 23) | (man << 13),
|
||||
};
|
||||
f32::from_bits(bits)
|
||||
}
|
||||
|
||||
/// Rounds to nearest, ties to even. Values too large become ±infinity; NaN stays NaN.
|
||||
pub fn f32_to_f16(f: f32) -> u16 {
|
||||
let bits = f.to_bits();
|
||||
let sign = ((bits >> 16) & 0x8000) as u16;
|
||||
let exp = ((bits >> 23) & 0xff) as i32;
|
||||
let man = bits & 0x7f_ffff;
|
||||
if exp == 0xff {
|
||||
return sign | 0x7c00 | if man != 0 { 0x200 } else { 0 };
|
||||
}
|
||||
let e = exp - 127 + 15;
|
||||
if e >= 0x1f {
|
||||
return sign | 0x7c00;
|
||||
}
|
||||
if e <= 0 {
|
||||
if e < -10 {
|
||||
return sign;
|
||||
}
|
||||
// subnormal half: shift the full mantissa (with implicit 1) into place, then round
|
||||
let m = man | 0x80_0000;
|
||||
let shift = (14 - e) as u32;
|
||||
let half = 1u32 << (shift - 1);
|
||||
let rest = m & ((1 << shift) - 1);
|
||||
let mut out = m >> shift;
|
||||
if rest > half || (rest == half && out & 1 == 1) {
|
||||
out += 1;
|
||||
}
|
||||
return sign | out as u16;
|
||||
}
|
||||
let mut out = ((e as u32) << 10) | (man >> 13);
|
||||
let rest = man & 0x1fff;
|
||||
if rest > 0x1000 || (rest == 0x1000 && out & 1 == 1) {
|
||||
out += 1; // may carry into the exponent, which is still correct (up to infinity)
|
||||
}
|
||||
sign | out as u16
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_finite_half_round_trips() {
|
||||
for h in 0..=u16::MAX {
|
||||
let f = f16_to_f32(h);
|
||||
if h & 0x7c00 == 0x7c00 && h & 0x3ff != 0 {
|
||||
assert!(f.is_nan(), "half bits {h:#06x} must decode to NaN");
|
||||
assert!(f32_to_f16(f) & 0x7c00 == 0x7c00 && f32_to_f16(f) & 0x3ff != 0);
|
||||
} else {
|
||||
assert_eq!(f32_to_f16(f), h, "half bits {h:#06x} -> {f}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rounds_and_saturates() {
|
||||
assert_eq!(f32_to_f16(1.0), 0x3c00);
|
||||
assert_eq!(f32_to_f16(65520.0), 0x7c00);
|
||||
assert_eq!(f32_to_f16(-1e-9), 0x8000);
|
||||
assert_eq!(f16_to_f32(f32_to_f16(0.1)), 0.099975586);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! The random numbers of the compiled-graph engine, worked out from images the reference app renders:
|
||||
//! each generator is a 24-bit linear congruential generator; a draw is the state's top 23 bits as a fraction, times the argument.
|
||||
//! All of it: measurement "Random numbers: solved, from rendered images only"; the rule table `lcg_draws.tsv`.
|
||||
|
||||
/// Multiplier and increment of one generator, modulo 2^24.
|
||||
pub type Lcg = (u32, u32);
|
||||
|
||||
/// `rand` in a pixel processor or a value processor.
|
||||
pub const FUNCTION: Lcg = (0x37_573B, 0xC7C1);
|
||||
/// `rand` in a node's parameter expression. Each expression starts again from the node's seed.
|
||||
pub const PARAMETER: Lcg = (0xF8_A3ED, 0xA0_1D31);
|
||||
/// `rand` in a fx-map's expressions, by what the expression computes. Each starts again from the quadrant's state. measurement
|
||||
/// "Random numbers: solved" (the first table, fx-map rows).
|
||||
pub const FX_SITES: [Lcg; 9] = [
|
||||
FUNCTION, // luminance
|
||||
(0xD7_FCD1, 0xC72D), // branch offset
|
||||
(0x1B_D4C1, 0xC613), // pattern offset
|
||||
(0x58_B04D, 0xC4EB), // size
|
||||
(0x34_F3F5, 0xC3D3), // rotation
|
||||
(0xBC_F1A6, 0xC5D7), // variation
|
||||
(0xDC_B7DC, 0xC3BF), // a switch's condition
|
||||
(0x90_FB9D, 0xC59F), // an iterate's count
|
||||
(0x19_660D, 0x6E_F35F), // which image a quadrant draws
|
||||
];
|
||||
/// From a fx-map iterate's state to the state of each of its iterations, one step per iteration. Measurement "Random numbers:
|
||||
/// solved" ("Iterate: ... a=0x8232B9, c=0x38C5").
|
||||
pub const ITERATION: Lcg = (0x82_32B9, 0x38C5);
|
||||
/// From a quadrant's state to its children's at depth `k + 1`, one step per child (a child left out still takes its step).
|
||||
/// Measurement "Random numbers: solved" (the depth table; measured to depth 16).
|
||||
pub const QUADRANT: [Lcg; 16] = [
|
||||
(0x19_CF16, 0xCD93),
|
||||
(0x54_A406, 0xCDC1),
|
||||
(0x13_AC69, 0xCDE7),
|
||||
(0xA1_EBE2, 0xCE0B),
|
||||
(0x27_BAB1, 0xCE47),
|
||||
(0xC6_90C5, 0xCE7B),
|
||||
(0xDC_FAA7, 0xCC19),
|
||||
(0x49_D83B, 0xCC41),
|
||||
(0x3B_9CA8, 0xCC61),
|
||||
(0x3F_FD4B, 0xCC9B),
|
||||
(0x47_0DA9, 0xCCE5),
|
||||
(0x36_4C22, 0xCD1F),
|
||||
(0x76_F899, 0xCD3F),
|
||||
(0x34_48BE, 0xCBDD),
|
||||
(0xAF_DC7A, 0xCAD9),
|
||||
(0xDC_7A18, 0xCD5B),
|
||||
];
|
||||
|
||||
/// States are 24 bits. Measurement "Random numbers: solved" ("an LCG modulo 2^24").
|
||||
const MASK: u32 = 0xFF_FFFF;
|
||||
|
||||
/// The next state of a generator.
|
||||
pub fn step((a, c): Lcg, state: u32) -> u32 {
|
||||
a.wrapping_mul(state).wrapping_add(c) & MASK
|
||||
}
|
||||
|
||||
/// The generator's output for a state, in 0..1: its top 23 bits. Measurement "Random numbers: solved" (`rand(x) = x * (s >> 1) / 2^23`).
|
||||
pub fn output(state: u32) -> f64 {
|
||||
f64::from((state & MASK) >> 1) / f64::from(1u32 << 23)
|
||||
}
|
||||
|
||||
/// The state of a pixel: Jenkins' one-at-a-time hash of the seed and the bits of the pixel's position as floats, low 24 bits.
|
||||
/// A value processor is the same with position (0, 0). Measurement "Random numbers: solved" ("H is Jenkins' one-at-a-time over
|
||||
/// three 32-bit words").
|
||||
pub fn pixel_state(seed: u32, u: f32, v: f32) -> u32 {
|
||||
let mut h = 0u32;
|
||||
for w in [seed, u.to_bits(), v.to_bits()] {
|
||||
h = h.wrapping_add(w);
|
||||
h = h.wrapping_add(h << 10);
|
||||
h ^= h >> 6;
|
||||
}
|
||||
h = h.wrapping_add(h << 3);
|
||||
h ^= h >> 11;
|
||||
h = h.wrapping_add(h << 15);
|
||||
h & MASK
|
||||
}
|
||||
|
||||
/// A quadrant's state to the state of its child number `q` (0..4), `depth` the child's depth (the first quadrant has 0).
|
||||
pub fn child_state(state: u32, q: usize, depth: usize) -> u32 {
|
||||
let lcg = QUADRANT.get(depth.saturating_sub(1)).or(QUADRANT.last()).copied().unwrap_or(ITERATION);
|
||||
(0..=q).fold(state, |s, _| step(lcg, s))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn matches_reference_draws() {
|
||||
// seed 0, 256 x 256, pixel (0, 0): first draw; state from the export's 16 bits at both offsets
|
||||
let s = step(FUNCTION, pixel_state(0, 0.5 / 256.0, 0.5 / 256.0));
|
||||
assert_eq!(s >> 1, 0x41_C501);
|
||||
assert_eq!(step(FUNCTION, s) >> 1, 0x6E_CDB9);
|
||||
// a value processor with seed 1: first and second draw
|
||||
let s = step(FUNCTION, pixel_state(1, 0.0, 0.0));
|
||||
assert_eq!(s >> 1, 0x5C_EC02);
|
||||
assert_eq!(step(FUNCTION, s) >> 1, 0x29_21F4);
|
||||
// a parameter with seed 5, two draws
|
||||
let s = step(PARAMETER, 5);
|
||||
assert_eq!(s >> 1, 0x3D_A869);
|
||||
assert_eq!(step(PARAMETER, s) >> 1, 0x57_D2CD);
|
||||
// a quadrant's children, seed 0
|
||||
assert_eq!(child_state(0, 0, 1), 0xCD93);
|
||||
assert_eq!(child_state(0, 1, 1), 0xA7_5535);
|
||||
assert_eq!(child_state(0, 3, 1), 0x57_1169);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Material graphs parsed from text and evaluated to float RGBA images. The CPU evaluator provides a reference
|
||||
//! implementation. Hosts can supply an [`accelerator::Accelerator`] to evaluate supported operations on a GPU.
|
||||
//! Callers provide per-evaluation settings through [`context::EvalContext`] and allocate their own [`graph::NodeCache`].
|
||||
//! The graph text format is documented in [`docs/format.md`](../docs/format.md).
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
pub mod accelerator;
|
||||
pub mod atomic;
|
||||
pub mod checksum;
|
||||
pub mod compiled_ops;
|
||||
pub mod context;
|
||||
pub mod curve;
|
||||
pub mod deflate;
|
||||
pub mod expr;
|
||||
pub mod exr;
|
||||
pub mod font;
|
||||
pub mod func;
|
||||
pub mod fxmap;
|
||||
pub mod graph;
|
||||
pub mod grunge;
|
||||
pub mod half;
|
||||
pub mod lcg_rand;
|
||||
pub mod math;
|
||||
pub mod measured;
|
||||
pub mod names;
|
||||
pub mod nodes2;
|
||||
pub mod noise;
|
||||
pub mod ops;
|
||||
pub mod par;
|
||||
pub mod params;
|
||||
pub mod patterns;
|
||||
pub mod png;
|
||||
pub mod profile;
|
||||
pub mod scatter;
|
||||
pub mod tex;
|
||||
pub mod vector;
|
||||
pub mod versions;
|
||||
|
||||
/// The data-parallel library the engine runs on, for hosts that build an [`context::EvalContext::pool`].
|
||||
pub use rayon;
|
||||
|
||||
#[cfg(test)]
|
||||
mod rule_tables;
|
||||
@@ -0,0 +1,268 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! The transcendental functions the engine uses (`sin`, `cos`, `exp`, `ln`, `powf`, `atan2` ...), from one pure-Rust
|
||||
//! implementation (the `libm` crate) for every target, so a graph renders to the same bits on any operating system,
|
||||
//! C library, compiler version and on the web.
|
||||
//!
|
||||
//! `f32::sin` and the like call the platform's maths library (glibc, the macOS or Windows one; none on wasm), and
|
||||
//! those round some results differently by an ulp, which changes render hashes from one machine to the next. The
|
||||
//! operations IEEE 754 defines exactly (`+ - * /`, `sqrt`, `floor`, `round`, `abs`, `%` ...) give the same bits
|
||||
//! everywhere and stay as they are. `clippy.toml` in this crate forbids the platform versions.
|
||||
//!
|
||||
//! Each function works on `f32` and `f64` alike (the single-precision functions for `f32`).
|
||||
|
||||
/// The `f32` and `f64` versions of each function.
|
||||
pub trait Real: Copy {
|
||||
fn sin_(self) -> Self;
|
||||
fn cos_(self) -> Self;
|
||||
fn tan_(self) -> Self;
|
||||
fn asin_(self) -> Self;
|
||||
fn acos_(self) -> Self;
|
||||
fn atan_(self) -> Self;
|
||||
fn atan2_(self, x: Self) -> Self;
|
||||
fn exp_(self) -> Self;
|
||||
fn ln_(self) -> Self;
|
||||
fn log2_(self) -> Self;
|
||||
fn powf_(self, e: Self) -> Self;
|
||||
fn cbrt_(self) -> Self;
|
||||
fn hypot_(self, y: Self) -> Self;
|
||||
fn one() -> Self;
|
||||
fn mul(self, b: Self) -> Self;
|
||||
fn div(self, b: Self) -> Self;
|
||||
}
|
||||
|
||||
macro_rules! real {
|
||||
($t:ty, $sin:ident, $cos:ident, $tan:ident, $asin:ident, $acos:ident, $atan:ident, $atan2:ident, $exp:ident, $ln:ident, $log2:ident, $pow:ident, $cbrt:ident, $hypot:ident) => {
|
||||
impl Real for $t {
|
||||
#[inline]
|
||||
fn sin_(self) -> Self {
|
||||
libm::$sin(self)
|
||||
}
|
||||
#[inline]
|
||||
fn cos_(self) -> Self {
|
||||
libm::$cos(self)
|
||||
}
|
||||
#[inline]
|
||||
fn tan_(self) -> Self {
|
||||
libm::$tan(self)
|
||||
}
|
||||
#[inline]
|
||||
fn asin_(self) -> Self {
|
||||
libm::$asin(self)
|
||||
}
|
||||
#[inline]
|
||||
fn acos_(self) -> Self {
|
||||
libm::$acos(self)
|
||||
}
|
||||
#[inline]
|
||||
fn atan_(self) -> Self {
|
||||
libm::$atan(self)
|
||||
}
|
||||
#[inline]
|
||||
fn atan2_(self, x: Self) -> Self {
|
||||
libm::$atan2(self, x)
|
||||
}
|
||||
#[inline]
|
||||
fn exp_(self) -> Self {
|
||||
libm::$exp(self)
|
||||
}
|
||||
#[inline]
|
||||
fn ln_(self) -> Self {
|
||||
libm::$ln(self)
|
||||
}
|
||||
#[inline]
|
||||
fn log2_(self) -> Self {
|
||||
libm::$log2(self)
|
||||
}
|
||||
#[inline]
|
||||
fn powf_(self, e: Self) -> Self {
|
||||
libm::$pow(self, e)
|
||||
}
|
||||
#[inline]
|
||||
fn cbrt_(self) -> Self {
|
||||
libm::$cbrt(self)
|
||||
}
|
||||
#[inline]
|
||||
fn hypot_(self, y: Self) -> Self {
|
||||
libm::$hypot(self, y)
|
||||
}
|
||||
#[inline]
|
||||
fn one() -> Self {
|
||||
1.0
|
||||
}
|
||||
#[inline]
|
||||
fn mul(self, b: Self) -> Self {
|
||||
self * b
|
||||
}
|
||||
#[inline]
|
||||
fn div(self, b: Self) -> Self {
|
||||
self / b
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
real!(f32, sinf, cosf, tanf, asinf, acosf, atanf, atan2f, expf, logf, log2f, powf, cbrtf, hypotf);
|
||||
real!(f64, sin, cos, tan, asin, acos, atan, atan2, exp, log, log2, pow, cbrt, hypot);
|
||||
|
||||
#[inline]
|
||||
pub fn sin<T: Real>(x: T) -> T {
|
||||
x.sin_()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn cos<T: Real>(x: T) -> T {
|
||||
x.cos_()
|
||||
}
|
||||
|
||||
/// `(sin x, cos x)`, as `f32::sin_cos` gives them (each on its own).
|
||||
#[inline]
|
||||
pub fn sin_cos<T: Real>(x: T) -> (T, T) {
|
||||
(x.sin_(), x.cos_())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn tan<T: Real>(x: T) -> T {
|
||||
x.tan_()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn asin<T: Real>(x: T) -> T {
|
||||
x.asin_()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn acos<T: Real>(x: T) -> T {
|
||||
x.acos_()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn atan<T: Real>(x: T) -> T {
|
||||
x.atan_()
|
||||
}
|
||||
|
||||
/// The angle of `(x, y)`, as `y.atan2(x)`.
|
||||
#[inline]
|
||||
pub fn atan2<T: Real>(y: T, x: T) -> T {
|
||||
y.atan2_(x)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn exp<T: Real>(x: T) -> T {
|
||||
x.exp_()
|
||||
}
|
||||
|
||||
/// The natural logarithm.
|
||||
#[inline]
|
||||
pub fn ln<T: Real>(x: T) -> T {
|
||||
x.ln_()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn log2<T: Real>(x: T) -> T {
|
||||
x.log2_()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn powf<T: Real>(x: T, e: T) -> T {
|
||||
x.powf_(e)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn cbrt<T: Real>(x: T) -> T {
|
||||
x.cbrt_()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn hypot<T: Real>(x: T, y: T) -> T {
|
||||
x.hypot_(y)
|
||||
}
|
||||
|
||||
/// `x` to the integer power `n` by repeated squaring, the same multiplications in the same order as the compiler's
|
||||
/// own `powi` (`__powisf2`/`__powidf2`, which constant exponents also expand to), but fixed here: LLVM leaves the order
|
||||
/// of `powi`'s multiplications open.
|
||||
#[inline]
|
||||
pub fn powi<T: Real>(x: T, n: i32) -> T {
|
||||
let mut a = x;
|
||||
let mut b = n;
|
||||
let mut r = T::one();
|
||||
loop {
|
||||
if b & 1 != 0 {
|
||||
r = r.mul(a);
|
||||
}
|
||||
b /= 2;
|
||||
if b == 0 {
|
||||
break;
|
||||
}
|
||||
a = a.mul(a);
|
||||
}
|
||||
if n < 0 { T::one().div(r) } else { r }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn samples() -> Vec<f64> {
|
||||
let mut v = vec![0.0, -0.0, 0.5, -0.5, 1.0, -1.0, 2.0, 1e-3, 3.25, -7.5, 1e3, f64::INFINITY, f64::NEG_INFINITY, f64::NAN];
|
||||
let mut x = 0x9e37_79b9_7f4a_7c15u64;
|
||||
for _ in 0..20_000 {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 7;
|
||||
x ^= x << 17;
|
||||
v.push((x >> 11) as f64 / (1u64 << 53) as f64 * 40.0 - 20.0);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The fixed `powi` gives what the compiler's gives (on the machine the tests run on), constant exponents included.
|
||||
/// Windows' MSVC toolchain multiplies negative powers in another order (0.001^-12 lands 2 ulp away), so the
|
||||
/// comparison only holds where `powi` is compiler-rt's `__powidf2`.
|
||||
#[test]
|
||||
#[cfg_attr(target_env = "msvc", ignore = "the MSVC toolchain's powi is not compiler-rt's")]
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
fn powi_matches_the_compilers() {
|
||||
for x in samples() {
|
||||
let xf = x as f32;
|
||||
for n in -12..=24 {
|
||||
assert_eq!(powi(x, n).to_bits(), x.powi(n).to_bits(), "{x}^{n}");
|
||||
assert_eq!(powi(xf, n).to_bits(), xf.powi(n).to_bits(), "{xf}^{n} (f32)");
|
||||
}
|
||||
assert_eq!(powi(x, 2).to_bits(), (x * x).to_bits());
|
||||
assert_eq!(powi(xf, 3).to_bits(), xf.powi(3).to_bits());
|
||||
assert_eq!(powi(xf, 4).to_bits(), xf.powi(4).to_bits());
|
||||
}
|
||||
}
|
||||
|
||||
/// Within an ulp or two of the platform's functions: the same functions, rounded the way one implementation does.
|
||||
#[test]
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
fn close_to_the_platform_functions() {
|
||||
let ulps32 = |a: f32, b: f32| if a.is_nan() && b.is_nan() { 0 } else { (a.to_bits() as i64 - b.to_bits() as i64).unsigned_abs() };
|
||||
for x in samples() {
|
||||
let f = x as f32;
|
||||
let g = (f * 0.05).clamp(-1.0, 1.0);
|
||||
for (name, ours, theirs) in [
|
||||
("sin", sin(f), f.sin()),
|
||||
("cos", cos(f), f.cos()),
|
||||
("tan", tan(f * 0.07), (f * 0.07).tan()),
|
||||
("asin", asin(g), g.asin()),
|
||||
("acos", acos(g), g.acos()),
|
||||
("atan", atan(f), f.atan()),
|
||||
("atan2", atan2(f, 0.75), f.atan2(0.75)),
|
||||
("exp", exp(f), f.exp()),
|
||||
("ln", ln(f.abs()), f.abs().ln()),
|
||||
("log2", log2(f.abs()), f.abs().log2()),
|
||||
("powf", powf(f.abs(), 2.2), f.abs().powf(2.2)),
|
||||
("cbrt", cbrt(f), f.cbrt()),
|
||||
("hypot", hypot(f, 3.0), f.hypot(3.0)),
|
||||
] {
|
||||
assert!(ulps32(ours, theirs) <= 2, "{name}({f}): {ours} vs {theirs}");
|
||||
}
|
||||
if !x.is_finite() {
|
||||
continue;
|
||||
}
|
||||
assert!((sin(x) - x.sin()).abs() <= 2.0 * f64::EPSILON * x.sin().abs().max(1e-300), "sin({x})");
|
||||
assert!((powf(x.abs(), 1.7) - x.abs().powf(1.7)).abs() <= 4.0 * f64::EPSILON * x.abs().powf(1.7), "pow({x})");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Constants of the compiled format's engine that more than one module uses, each measured against the reference app.
|
||||
//! Every one names the measurement it comes from; the rule tables in
|
||||
//! `tests/rules/` hold the rules built on them as plain numbers.
|
||||
//!
|
||||
//! Constants used in one place only are named where they are used, with their own pointers.
|
||||
|
||||
/// Steps of a 16-bit value: a node holding 16 bits, a rounded read, a pyramid level and an export hold `k / 65535`.
|
||||
/// Measurement "Random numbers: solved" (export `round(x * 65535)`) and "One-effect projects" › "What nodes hold and how
|
||||
/// they read" (16-bit nodes, reads rounded half up to a 16-bit step).
|
||||
pub const STEPS_16: f64 = 65535.0;
|
||||
|
||||
/// Steps of an 8-bit value (`k / 255`). Measurement "Node formats" (8-bit conversion).
|
||||
pub const STEPS_8: u32 = 255;
|
||||
|
||||
/// A bilinear read takes its weights in steps of 1/256, rounded. Measurement "Transforms" ("Bilinear reads take weights in
|
||||
/// steps of 1/256") and "What nodes hold and how they read" (`(a (256 - w) + b w + 128) >> 8`); the directional blur's
|
||||
/// shear too: "Directional blur, exact form" ("Lerp weights in steps of 1/256").
|
||||
pub const WEIGHT_STEPS: f64 = 256.0;
|
||||
|
||||
/// Intensities and distances of compiled nodes count in pixels of a 256-pixel image: a node `W` wide moves, blurs or
|
||||
/// reaches `intensity W / 256` pixels. Measurement "Operations identified with it" (directional and gradient warp,
|
||||
/// `intensity/256`), "Operations identified, by fitting" (distance, normal, emboss: `W / 256`) and "Directional blur,
|
||||
/// exact form" (`rx = intensity W/256 aspect_x`).
|
||||
pub const INTENSITY_SPAN: f32 = 256.0;
|
||||
|
||||
/// A node holding 8 bits: `fine = round(v 65535) >> 4` (16 bits cut to 12), then `(255 fine + 2047) >> 12`, a tie going
|
||||
/// down. Measurement "Node formats" (`fine = floor(v 4096); out = (255 fine + 2047) >> 12`, 0.5 gives 127) and "Fx-map
|
||||
/// frames, draw order and small rules" › "Images" (8-bit nodes: to 16 bits to the nearest, cut to 12 bits, then to 8).
|
||||
pub const CUT_16_TO_12: u32 = 4;
|
||||
pub const FINE_8: u32 = 1 << 12;
|
||||
pub const FINE_8_TIE_DOWN: u32 = FINE_8 / 2 - 1;
|
||||
|
||||
/// A node holding 16 bits: `fine = floor(v 2^20)`, then `(65535 fine + 2^19 - 1) >> 20`, a tie going down. Measurement "What
|
||||
/// nodes hold and how they read" (16 bits: `fine = floor(v 2^20); (65535 fine + 2^19 - 1) >> 20`).
|
||||
pub const FINE_16_BITS: u32 = 20;
|
||||
pub const FINE_16: u64 = 1 << FINE_16_BITS;
|
||||
pub const FINE_16_TIE_DOWN: u64 = FINE_16 / 2 - 1;
|
||||
|
||||
/// What a node holds, as `ops::apply_format` takes it. 1 to 3 are this engine's own per-node output formats (8- and
|
||||
/// 16-bit integers rounded to the nearest, half floats rounded to the nearest), a choice of ours and not measured. 5 to
|
||||
/// 7 are the compiled format's node formats, flags bits 4-5 of the node (0x09, 0x19, 0x29), each held as measured:
|
||||
/// Measurement "What nodes hold and how they read" (0x09 8 bits, 0x19 16 bits, 0x29 half float cut towards zero).
|
||||
pub const FORMAT_8_BIT: u32 = 1;
|
||||
pub const FORMAT_16_BIT: u32 = 2;
|
||||
pub const FORMAT_HALF: u32 = 3;
|
||||
pub const COMPILED_8_BIT: u32 = 5;
|
||||
pub const COMPILED_16_BIT: u32 = 6;
|
||||
pub const COMPILED_HALF: u32 = 7;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_named_values_are_the_numbers_they_replace() {
|
||||
assert_eq!((FINE_8, FINE_8_TIE_DOWN, CUT_16_TO_12), (4096, 2047, 4));
|
||||
assert_eq!((FINE_16, FINE_16_TIE_DOWN), (1_048_576, 524_287));
|
||||
assert_eq!((FINE_16 as f64, FINE_16_TIE_DOWN as f64), (1_048_576.0, 524_287.0));
|
||||
assert_eq!((STEPS_16, STEPS_16 as f32, STEPS_8 as f32), (65535.0, 65535.0f32, 255.0f32));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
//! Named values of the graph language: the words a graph text (format 3 on) writes where formats 1 and 2 wrote numbers,
|
||||
//! and the old spellings it still reads.
|
||||
//!
|
||||
//! A node keeps these values as numbers in memory (`Node::nums`), so the evaluator and the editor see the same thing they
|
||||
//! always did; only the text changes. Reading accepts both a name and the old number, writing gives the name whenever
|
||||
//! the number has one (a number without a name is written as the number, which every version reads).
|
||||
//!
|
||||
//! | node kind | text key | in memory | values |
|
||||
//! |---|---|---|---|
|
||||
//! | every kind | `format` | `ofmt` | [`OUTPUT_FORMATS`] |
|
||||
//! | `blend` | `mode` | `mode` | [`BLEND_MODES`] |
|
||||
//! | `pp_quadrant` | `pattern` | `pattern` | [`PATTERN_SHAPES`] |
|
||||
//! | `f_random` | `lcg` | `lcg` | [`LCG_SITES`] |
|
||||
//!
|
||||
//! Older spellings read as well: the key `ofmt=<n>`, numbers in place of the names, and the function ops of
|
||||
//! [`RENAMED_OPS`] under their old names. The numbers of the compiled format are not here: the decompiler has its own
|
||||
//! table from them to these names.
|
||||
|
||||
use crate::graph::Node;
|
||||
|
||||
/// Function ops renamed in format 3: (old name, name).
|
||||
pub const RENAMED_OPS: &[(&str, &str)] = &[
|
||||
("f_fsin", "f_sin_poly"),
|
||||
("f_fcos", "f_cos_poly"),
|
||||
("f_flog", "f_log_floor"),
|
||||
("f_fdiv", "f_div_large"),
|
||||
("f_fatan2", "f_atan2_approx"),
|
||||
("f_gsin", "f_sin_f32turns"),
|
||||
("f_gcos", "f_cos_f32turns"),
|
||||
];
|
||||
|
||||
/// A node's Output Format: 0 the graph's own, 1 to 4 plain quantising (4 forces 32-bit float), 5 to 7 quantising as
|
||||
/// compiled graphs do it (rounding of their own, and blurs and levels that hold the format on the way).
|
||||
pub const OUTPUT_FORMATS: &[(u32, &str)] =
|
||||
&[(0, "graph"), (1, "u8"), (2, "u16"), (3, "f16"), (4, "f32"), (5, "u8_compiled"), (6, "u16_compiled"), (7, "f16_compiled")];
|
||||
|
||||
/// Modes of the `blend` node (`ops::blend_ex`). 32 to 36 are compiled graphs' own versions, whose opacity acts before
|
||||
/// the result is limited (soft light: a square root above the middle).
|
||||
pub const BLEND_MODES: &[(u32, &str)] = &[
|
||||
(0, "copy"),
|
||||
(1, "add"),
|
||||
(2, "subtract"),
|
||||
(3, "multiply"),
|
||||
(4, "screen"),
|
||||
(5, "overlay"),
|
||||
(6, "max"),
|
||||
(7, "min"),
|
||||
(8, "difference"),
|
||||
(9, "soft_light"),
|
||||
(10, "color_dodge"),
|
||||
(11, "color_burn"),
|
||||
(12, "linear_burn"),
|
||||
(13, "hard_light"),
|
||||
(14, "exclusion"),
|
||||
(15, "divide"),
|
||||
(16, "linear_light"),
|
||||
(17, "color"),
|
||||
(18, "luminosity"),
|
||||
(19, "dissolve"),
|
||||
(20, "add_sub"),
|
||||
(21, "switch"),
|
||||
(32, "add_compiled"),
|
||||
(33, "subtract_compiled"),
|
||||
(34, "add_sub_compiled"),
|
||||
(35, "divide_compiled"),
|
||||
(36, "soft_light_compiled"),
|
||||
];
|
||||
|
||||
/// Shapes a pattern program's quadrant draws (`patterns::shape`).
|
||||
pub const PATTERN_SHAPES: &[(u32, &str)] = &[
|
||||
(0, "square"),
|
||||
(1, "disc"),
|
||||
(2, "paraboloid"),
|
||||
(3, "bell"),
|
||||
(4, "gaussian"),
|
||||
(5, "thorn"),
|
||||
(6, "pyramid"),
|
||||
(7, "brick"),
|
||||
(8, "gradation"),
|
||||
(9, "waves"),
|
||||
(10, "half_bell"),
|
||||
(11, "ridged_bell"),
|
||||
(12, "crescent"),
|
||||
(13, "capsule"),
|
||||
(14, "cone"),
|
||||
(15, "gradation_offset"),
|
||||
(16, "hemisphere"),
|
||||
];
|
||||
|
||||
/// Which 24-bit generator `f_random` draws from, by where the function runs (`lcg_rand`): a pixel processor per pixel,
|
||||
/// a value node once (draw `k`), a node's parameter expression, a pixel processor's size expression (draw `k`), and
|
||||
/// the expressions of a fx-map's quadrant by what they compute (`lcg_rand::FX_SITES` in this order).
|
||||
pub const LCG_SITES: &[(u32, &str)] = &[
|
||||
(1, "pixel"),
|
||||
(2, "value"),
|
||||
(3, "parameter"),
|
||||
(5, "size"),
|
||||
(10, "fx_luminance"),
|
||||
(11, "fx_branch_offset"),
|
||||
(12, "fx_pattern_offset"),
|
||||
(13, "fx_size"),
|
||||
(14, "fx_rotation"),
|
||||
(15, "fx_variation"),
|
||||
(16, "fx_switch_condition"),
|
||||
(17, "fx_iterate_count"),
|
||||
(18, "fx_image_index"),
|
||||
];
|
||||
|
||||
/// One named value: on which kinds (`None` = all), its key in the text, its key in memory and its names.
|
||||
struct Named {
|
||||
kind: Option<&'static str>,
|
||||
key: &'static str,
|
||||
memory: &'static str,
|
||||
table: &'static [(u32, &'static str)],
|
||||
}
|
||||
|
||||
const NAMED: &[Named] = &[
|
||||
Named { kind: None, key: "format", memory: "ofmt", table: OUTPUT_FORMATS },
|
||||
Named { kind: Some("blend"), key: "mode", memory: "mode", table: BLEND_MODES },
|
||||
Named { kind: Some("pp_quadrant"), key: "pattern", memory: "pattern", table: PATTERN_SHAPES },
|
||||
Named { kind: Some("f_random"), key: "lcg", memory: "lcg", table: LCG_SITES },
|
||||
];
|
||||
|
||||
fn applies(n: &Named, kind: &str) -> bool {
|
||||
n.kind.is_none_or(|k| k == kind)
|
||||
}
|
||||
|
||||
/// The name of `code` in a table.
|
||||
pub fn name_of(table: &[(u32, &'static str)], code: u32) -> Option<&'static str> {
|
||||
table.iter().find(|(c, _)| *c == code).map(|(_, n)| *n)
|
||||
}
|
||||
|
||||
/// The number of `name` in a table.
|
||||
pub fn code_of(table: &[(u32, &str)], name: &str) -> Option<u32> {
|
||||
table.iter().find(|(_, n)| *n == name).map(|(c, _)| *c)
|
||||
}
|
||||
|
||||
/// The op's current name, for one written under an old name.
|
||||
pub fn current_op(kind: &str) -> Option<&'static str> {
|
||||
RENAMED_OPS.iter().find(|(old, _)| *old == kind).map(|(_, new)| *new)
|
||||
}
|
||||
|
||||
/// A node just read from a text, to its form in memory: old op names and keys to the current ones, names to numbers.
|
||||
pub fn read_node(n: &mut Node) -> Result<(), String> {
|
||||
if let Some(new) = current_op(&n.kind) {
|
||||
n.kind = new.to_string();
|
||||
}
|
||||
for named in NAMED.iter().filter(|x| applies(x, &n.kind)) {
|
||||
if let Some(name) = n.strs.remove(named.key) {
|
||||
let code = code_of(named.table, &name).ok_or_else(|| format!("unknown {} '{name}' (known: {})", named.key, names(named.table)))?;
|
||||
n.nums.insert(named.memory.to_string(), code as f32);
|
||||
} else if named.key != named.memory
|
||||
&& let Some(v) = n.nums.remove(named.key)
|
||||
{
|
||||
// the new key with a number
|
||||
n.nums.insert(named.memory.to_string(), v);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn names(table: &[(u32, &str)]) -> String {
|
||||
table.iter().map(|(_, n)| *n).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
/// How a number of a node of `kind` is written: `Some(key, name)` when it has a name.
|
||||
pub fn written_name(kind: &str, key: &str, v: f32) -> Option<(&'static str, &'static str)> {
|
||||
let named = NAMED.iter().find(|x| x.memory == key && applies(x, kind))?;
|
||||
if v < 0.0 || v.fract() != 0.0 || v > u32::MAX as f32 {
|
||||
return None;
|
||||
}
|
||||
name_of(named.table, v as u32).map(|name| (named.key, name))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_table_is_one_to_one() {
|
||||
for t in [OUTPUT_FORMATS, BLEND_MODES, PATTERN_SHAPES, LCG_SITES] {
|
||||
for (i, (c, n)) in t.iter().enumerate() {
|
||||
assert!(t.iter().skip(i + 1).all(|(c2, n2)| c2 != c && n2 != n), "{n} twice");
|
||||
assert!(n.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'), "{n} is one word");
|
||||
}
|
||||
}
|
||||
for (i, (old, new)) in RENAMED_OPS.iter().enumerate() {
|
||||
assert!(RENAMED_OPS.iter().skip(i + 1).all(|(o, n)| o != old && n != new));
|
||||
assert!(crate::func::FUNC_SPECS.iter().any(|s| s.kind == *new), "{new} is an op");
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph written in format 2: every number and old name this module renames (`f_random`'s generator as a number).
|
||||
const OLD: &str = "size 16
|
||||
meta compiled \"1\"
|
||||
subgraph px
|
||||
meta kind \"function\"
|
||||
node 2 f_seed
|
||||
node 3 f_float v=1
|
||||
node 4 f_random b=@3 lcg=1 s=@2
|
||||
node 5 f_fsin a=@4
|
||||
node 6 f_fcos a=@4
|
||||
node 7 f_gsin a=@4
|
||||
node 8 f_gcos a=@4
|
||||
node 9 f_flog a=@4
|
||||
node 10 f_fdiv a=@5 b=@6
|
||||
node 11 f_fatan2 a=@7 b=@8
|
||||
node 12 f_add a=@10 b=@11
|
||||
node 13 f_add a=@12 b=@9
|
||||
node 14 f_random b=@3 lcg=5 s=@2 k=2
|
||||
node 15 f_add a=@13 b=@14
|
||||
node 1 f_out in=@15
|
||||
end
|
||||
subgraph lum
|
||||
meta kind \"function\"
|
||||
node 2 f_float v=1
|
||||
node 3 f_random b=@2 lcg=10
|
||||
node 1 f_out in=@3
|
||||
end
|
||||
subgraph p
|
||||
meta kind \"patterns\"
|
||||
node 1 pp_quadrant pattern=4 draws=1 fn.luminance=\"lum\" size_x=0.5 size_y=0.5
|
||||
node 2 pp_quadrant draws=0 q0=@1 q1=@1 q2=@1 q3=@1
|
||||
node 3 pp_out in=@2
|
||||
end
|
||||
node 1 pixel_processor fn=\"px\" ofmt=5
|
||||
node 2 pattern_program program=\"p\" ofmt=7
|
||||
node 3 blend mode=21 alpha_mode=1 bg=@1 fg=@2 opacity=0.5
|
||||
node 4 blend mode=34 alpha_mode=1 bg=@3 fg=@1 opacity=0.25 ofmt=6
|
||||
output o 4
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn old_spellings_read_as_the_new_names_and_give_the_same_image() {
|
||||
let old = crate::graph::Graph::parse(OLD).unwrap_or_else(|e| panic!("{e}"));
|
||||
let text = old.to_text();
|
||||
assert!(text.starts_with(&format!("format {}\n", crate::graph::FORMAT_VERSION)));
|
||||
for gone in ["ofmt", "f_fsin", "f_fcos", "f_gsin", "f_gcos", "f_flog", "f_fdiv", "f_fatan2", "mode=21", "pattern=4"] {
|
||||
assert!(!text.contains(gone), "{gone} still written:\n{text}");
|
||||
}
|
||||
for name in [
|
||||
"lcg=\"pixel\"",
|
||||
"lcg=\"size\"",
|
||||
"lcg=\"fx_luminance\"",
|
||||
"f_sin_poly",
|
||||
"f_cos_poly",
|
||||
"f_sin_f32turns",
|
||||
"f_cos_f32turns",
|
||||
"f_log_floor",
|
||||
"f_div_large",
|
||||
"f_atan2_approx",
|
||||
"format=\"u8_compiled\"",
|
||||
"format=\"u16_compiled\"",
|
||||
"format=\"f16_compiled\"",
|
||||
"mode=\"switch\"",
|
||||
"mode=\"add_sub_compiled\"",
|
||||
"pattern=\"gaussian\"",
|
||||
] {
|
||||
assert!(text.contains(name), "{name} not written:\n{text}");
|
||||
}
|
||||
let new = crate::graph::Graph::parse(&text).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert_eq!(new.to_text(), text, "writing again changes nothing");
|
||||
let (a, b) = (&old.evaluate(Some(16)).unwrap()["o"], &new.evaluate(Some(16)).unwrap()["o"]);
|
||||
let bits = |t: &crate::tex::Tex| t.px.iter().flat_map(|p| p.map(f32::to_bits)).collect::<Vec<_>>();
|
||||
assert_eq!(bits(a), bits(b));
|
||||
assert!(a.px.iter().any(|p| p[0] != a.px[0][0]), "the test graph draws something");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_without_a_name_stays_a_number_and_an_unknown_name_is_refused() {
|
||||
let g = crate::graph::Graph::parse("size 4\nnode 1 color r=1 g=1 b=1\nnode 2 blend mode=25 bg=@1 fg=@1 ofmt=9\noutput o 2\n").unwrap();
|
||||
let text = g.to_text();
|
||||
assert!(text.contains(" mode=25") && text.contains(" ofmt=9"), "{text}");
|
||||
assert_eq!(crate::graph::Graph::parse(&text).unwrap().to_text(), text);
|
||||
let e = crate::graph::Graph::parse("size 4\nnode 1 color r=1 g=1 b=1\nnode 2 blend mode=\"sideways\" bg=@1 fg=@1\noutput o 2\n").unwrap_err();
|
||||
assert!(e.to_string().contains("unknown mode 'sideways'"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_quadrant_reads_its_input_from_image_index_or_the_old_pattern_number() {
|
||||
let text = |q: &str| {
|
||||
format!(
|
||||
"size 8\nsubgraph p\nmeta kind \"patterns\"\nnode 1 pp_quadrant {q} draws=1 image=1 image_filter=2\nnode 2 pp_out in=@1\nend\nnode 1 color r=1 g=0 b=0\nnode 2 color r=0 g=1 b=0\nnode 3 pattern_program program=\"p\" color=1 in=@1 in2=@2\noutput o 3\n"
|
||||
)
|
||||
};
|
||||
let render = |q: &str| crate::graph::Graph::parse(&text(q)).unwrap_or_else(|e| panic!("{e}")).evaluate(Some(8)).unwrap()["o"].px.clone();
|
||||
assert_eq!(render("image_index=1"), render("pattern=1"));
|
||||
assert_ne!(render("image_index=1"), render("image_index=0"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,708 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Second set of nodes (batch 1). `compute` returns Ok(None) for kinds it does not know, so the
|
||||
//! main evaluator can fall back to it. Every node here is tileable and independent of the output resolution:
|
||||
//! pixel-sized parameters are given for a 512 px texture and scaled by `size / 512`.
|
||||
use crate::graph::{Error, Node};
|
||||
use crate::math;
|
||||
use crate::noise;
|
||||
use crate::ops;
|
||||
use crate::tex::{Tex, lum};
|
||||
use std::collections::BTreeMap;
|
||||
use std::f32::consts::TAU;
|
||||
use std::sync::Arc as Rc;
|
||||
|
||||
fn smooth(a: f32, b: f32, x: f32) -> f32 {
|
||||
let d = b - a;
|
||||
let t = if d.abs() < 1e-9 { if x >= b { 1.0 } else { 0.0 } } else { ((x - a) / d).clamp(0.0, 1.0) };
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
|
||||
fn lerp(a: f32, b: f32, t: f32) -> f32 {
|
||||
a + (b - a) * t
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- FFT (used by Normal To Height)
|
||||
fn fft(a: &mut [[f32; 2]], inverse: bool) {
|
||||
let n = a.len();
|
||||
let mut j = 0usize;
|
||||
for i in 1..n {
|
||||
let mut bit = n >> 1;
|
||||
while j & bit != 0 {
|
||||
j ^= bit;
|
||||
bit >>= 1;
|
||||
}
|
||||
j ^= bit;
|
||||
if i < j {
|
||||
a.swap(i, j);
|
||||
}
|
||||
}
|
||||
let mut len = 2;
|
||||
while len <= n {
|
||||
let ang = if inverse { TAU } else { -TAU } / len as f32;
|
||||
let (ws, wc) = math::sin_cos(ang);
|
||||
// `n` is a power of two, so the blocks are whole
|
||||
for block in a.chunks_exact_mut(len) {
|
||||
let (mut cr, mut ci) = (1.0f32, 0.0f32);
|
||||
let (lo, hi) = block.split_at_mut(len / 2);
|
||||
for (x, y) in lo.iter_mut().zip(hi.iter_mut()) {
|
||||
let (u, v) = (*x, *y);
|
||||
let t = [v[0] * cr - v[1] * ci, v[0] * ci + v[1] * cr];
|
||||
*x = [u[0] + t[0], u[1] + t[1]];
|
||||
*y = [u[0] - t[0], u[1] - t[1]];
|
||||
let nr = cr * wc - ci * ws;
|
||||
ci = cr * ws + ci * wc;
|
||||
cr = nr;
|
||||
}
|
||||
}
|
||||
len <<= 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn transpose_c(a: &[[f32; 2]], n: usize) -> Vec<[f32; 2]> {
|
||||
let mut o = vec![[0.0; 2]; n * n];
|
||||
for (y, row) in a.chunks_exact(n.max(1)).take(n).enumerate() {
|
||||
for (x, &c) in row.iter().enumerate() {
|
||||
if let Some(e) = o.get_mut(x * n + y) {
|
||||
*e = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
fn fft2(a: &mut Vec<[f32; 2]>, n: usize, inverse: bool) {
|
||||
for r in a.chunks_mut(n) {
|
||||
fft(r, inverse);
|
||||
}
|
||||
let mut t = transpose_c(a, n);
|
||||
for r in t.chunks_mut(n) {
|
||||
fft(r, inverse);
|
||||
}
|
||||
*a = transpose_c(&t, n);
|
||||
}
|
||||
|
||||
/// Integrate a tangent-space normal map back into a height map (periodic Poisson solve in the Fourier domain).
|
||||
fn normal_to_height(nm: &Tex, directx: bool, relief: f32, opacity: f32) -> Tex {
|
||||
let n = nm.w.next_power_of_two().clamp(2, 4096);
|
||||
let src = if nm.w == n && nm.h == n { nm.clone() } else { ops::resize(nm, n) };
|
||||
let mut gx = vec![[0.0f32; 2]; n * n];
|
||||
let mut gy = vec![[0.0f32; 2]; n * n];
|
||||
for ((p, gxi), gyi) in src.px.iter().zip(gx.iter_mut()).zip(gy.iter_mut()) {
|
||||
let (x, y, z) = ((p[0] - 0.5) * 2.0, (p[1] - 0.5) * 2.0, ((p[2] - 0.5) * 2.0).max(0.05));
|
||||
gxi[0] = -x / z;
|
||||
gyi[0] = (if directx { -y } else { y }) / z;
|
||||
}
|
||||
fft2(&mut gx, n, false);
|
||||
fft2(&mut gy, n, false);
|
||||
let mut h = vec![[0.0f32; 2]; n * n];
|
||||
for ky in 0..n {
|
||||
let sy = math::sin(TAU * ky as f32 / n as f32);
|
||||
for kx in 0..n {
|
||||
let sx = math::sin(TAU * kx as f32 / n as f32);
|
||||
let d = sx * sx + sy * sy;
|
||||
if d < 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let i = ky * n + kx;
|
||||
let (Some(gxi), Some(gyi), Some(hi)) = (gx.get(i), gy.get(i), h.get_mut(i)) else { continue };
|
||||
// h = -i (sx gx + sy gy) / (sx^2 + sy^2)
|
||||
let (re, im) = (sx * gxi[0] + sy * gyi[0], sx * gxi[1] + sy * gyi[1]);
|
||||
// relief balance: 0.5 = plain integration, above favours large shapes, below favours fine detail
|
||||
let wgt = if (relief - 0.5).abs() > 1e-4 { math::powf(d, 0.5 - relief) } else { 1.0 };
|
||||
*hi = [im / d * wgt, -re / d * wgt];
|
||||
}
|
||||
}
|
||||
fft2(&mut h, n, true);
|
||||
let vals: Vec<f32> = h.iter().map(|c| c[0] / (n * n) as f32).collect();
|
||||
let (mn, mx) = vals.iter().fold((f32::MAX, f32::MIN), |a, v| (a.0.min(*v), a.1.max(*v)));
|
||||
let k = if mx - mn > 1e-9 { 1.0 / (mx - mn) } else { 0.0 };
|
||||
let out = Tex {
|
||||
w: n,
|
||||
h: n,
|
||||
px: vals
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let g = if k > 0.0 { (v - mn) * k } else { 0.5 };
|
||||
let g = 0.5 + (g - 0.5) * opacity;
|
||||
[g, g, g, 1.0]
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
if nm.w == n && nm.h == n { out } else { ops::resize_to(&out, nm.w, nm.h) }
|
||||
}
|
||||
|
||||
/// Run a node of this module. Ok(None) = not one of ours.
|
||||
pub fn compute(kind: &str, id: u32, n: &Node, ins: &BTreeMap<String, Rc<Tex>>, s: usize, hs: usize, seed: u32) -> Result<Option<Tex>, Error> {
|
||||
let f = |k: &str, d: f32| n.nums.get(k).copied().unwrap_or(d);
|
||||
let need = |slot: &str| -> Result<&Tex, Error> { ins.get(slot).map(|r| r.as_ref()).ok_or_else(|| Error::MissingInput(id, slot.to_string())) };
|
||||
let opt = |slot: &str| -> Option<&Tex> { ins.get(slot).map(|r| r.as_ref()) };
|
||||
let rs = s as f32 / 512.0;
|
||||
let per = |k: &str, d: f32| f(k, d).round().clamp(1.0, 256.0) as i32;
|
||||
let (con, inv) = (f("contrast", 1.0), f("invert", 0.0) > 0.5);
|
||||
let dz = noise::Disorder::new(seed, f("disorder", 0.0), f("disorder_speed", 1.0), f("anisotropy", 0.0), f("anisotropy_angle", 0.0));
|
||||
let fin = |t: Tex| -> Tex { if (con - 1.0).abs() > 1e-4 || inv { ops::contrast_invert(&t, con, inv) } else { t } };
|
||||
let out = match kind {
|
||||
// ------------------------------------------------ blurs and warps
|
||||
"non_uniform_blur" => {
|
||||
let (t, m) = (need("in")?, need("mask")?);
|
||||
let max = f("intensity", 8.0).clamp(0.0, 64.0) * rs;
|
||||
let lv: Vec<Tex> = (0..=4).map(|i| if i == 0 { t.clone() } else { ops::blur(t, max * i as f32 / 4.0) }).collect();
|
||||
Tex::from_fn(t.w, t.h, |u, v| {
|
||||
let k = lum(m.sample(u, v)).clamp(0.0, 1.0) * 4.0;
|
||||
let i = (k.floor() as usize).min(3);
|
||||
let fr = k - i as f32;
|
||||
let (Some(la), Some(lb)) = (lv.get(i), lv.get(i + 1)) else { return [0.0; 4] };
|
||||
let (a, b) = (la.sample(u, v), lb.sample(u, v));
|
||||
[lerp(a[0], b[0], fr), lerp(a[1], b[1], fr), lerp(a[2], b[2], fr), lerp(a[3], b[3], fr)]
|
||||
})
|
||||
}
|
||||
"radial_blur" => {
|
||||
let t = need("in")?;
|
||||
let (cx, cy) = (0.5 + f("x", 0.0), 0.5 + f("y", 0.0));
|
||||
if f("mode", 0.0) > 0.5 {
|
||||
// legacy zoom blur
|
||||
let (amount, rad) = (f("amount", 0.1).clamp(0.0, 1.0), f("radius", 0.5).clamp(0.01, 0.5));
|
||||
let taps = 24;
|
||||
Tex::from_fn(t.w, t.h, |u, v| {
|
||||
let (dx, dy) = (ops::wrapd(u - cx), ops::wrapd(v - cy));
|
||||
let r = (dx * dx + dy * dy).sqrt();
|
||||
let amt = amount * smooth(0.0, 1.0, 1.0 - r / rad);
|
||||
let mut a = [0.0f32; 4];
|
||||
for k in 0..taps {
|
||||
let sc = 1.0 - amt * (k as f32 / (taps - 1) as f32);
|
||||
let p = t.sample(cx + dx * sc, cy + dy * sc);
|
||||
for (ac, pc) in a.iter_mut().zip(p) {
|
||||
*ac += pc / taps as f32;
|
||||
}
|
||||
}
|
||||
a
|
||||
})
|
||||
} else {
|
||||
// spin blur, `samples` taps along an arc of `angle` turns around the centre
|
||||
let n = f("samples", 64.0).round().clamp(1.0, 128.0) as usize;
|
||||
let arc = f("angle", 0.125).clamp(0.0, 0.5) * TAU;
|
||||
Tex::from_fn(t.w, t.h, |u, v| {
|
||||
let (dx, dy) = (ops::wrapd(u - cx), ops::wrapd(v - cy));
|
||||
// the blur fades out towards the image border so the result still tiles
|
||||
let fade = ((0.5 - (dx * dx + dy * dy).sqrt()) / 0.15).clamp(0.0, 1.0);
|
||||
let mut a = [0.0f32; 4];
|
||||
for k in 0..n {
|
||||
let th = if n > 1 { (k as f32 / (n - 1) as f32 - 0.5) * arc * fade } else { 0.0 };
|
||||
let (sn, cs) = math::sin_cos(th);
|
||||
let p = t.sample(cx + dx * cs - dy * sn, cy + dx * sn + dy * cs);
|
||||
for (ac, pc) in a.iter_mut().zip(p) {
|
||||
*ac += pc / n as f32;
|
||||
}
|
||||
}
|
||||
a
|
||||
})
|
||||
}
|
||||
}
|
||||
"anisotropic_blur" => {
|
||||
let t = need("in")?;
|
||||
let (inten, an) = (f("intensity", 8.0).clamp(0.0, 64.0), f("anisotropy", 0.8).clamp(0.0, 1.0));
|
||||
let a = ops::blur(t, inten * (1.0 - an) * rs);
|
||||
ops::directional_blur(&a, f("angle", 0.0), inten * an * 4.0 / 512.0)
|
||||
}
|
||||
// ------------------------------------------------ transforms
|
||||
"symmetry" => {
|
||||
let t = need("in")?;
|
||||
let (axis, c) = (f("axis", 0.0) as u32, f("offset", 0.0));
|
||||
let sg = if f("flip", 0.0) > 0.5 { -1.0 } else { 1.0 };
|
||||
let tm = f("transfer", 0.0).round() as u32; // 0 copy, 1 add, 2 subtract, 3 multiply, 4 add sub, 5 max, 6 min
|
||||
let fold = move |p: f32| 0.5 + c + sg * ops::wrapd(p - 0.5 - c).abs();
|
||||
let diag = move |u: f32, v: f32| {
|
||||
// mirror across the line u = v
|
||||
let (x, y) = (ops::wrapd(u - v), u + v);
|
||||
let x = x.abs() * sg;
|
||||
((y + x) * 0.5, (y - x) * 0.5)
|
||||
};
|
||||
Tex::from_fn(t.w, t.h, |u, v| {
|
||||
let (a, b) = match axis {
|
||||
0 => (fold(u), v),
|
||||
1 => (u, fold(v)),
|
||||
2 => (fold(u), fold(v)),
|
||||
3 => diag(u, v),
|
||||
4 => {
|
||||
// anti-diagonal: mirror across the line u + v = 0 (mod 1)
|
||||
let (x, y) = (ops::wrapd(u + v), u - v);
|
||||
let x = x.abs() * sg;
|
||||
((y + x) * 0.5, (x - y) * 0.5)
|
||||
}
|
||||
_ => diag(fold(u), fold(v)), // 8-fold: both axes plus the diagonal
|
||||
};
|
||||
let m = t.sample(a, b);
|
||||
if tm == 0 {
|
||||
return m;
|
||||
}
|
||||
let o = t.sample(u, v);
|
||||
let mut r = o;
|
||||
for ((rk, ok), mk) in r.iter_mut().zip(o).zip(m).take(3) {
|
||||
*rk = match tm {
|
||||
1 => ok + mk,
|
||||
2 => ok - mk,
|
||||
3 => ok * mk,
|
||||
4 => ok + (mk - 0.5) * 2.0,
|
||||
5 => ok.max(mk),
|
||||
_ => ok.min(mk),
|
||||
}
|
||||
.clamp(0.0, 1.0);
|
||||
}
|
||||
r
|
||||
})
|
||||
}
|
||||
"skew" => {
|
||||
let t = need("in")?;
|
||||
// whole numbers keep the lattice periodic: the skewed texture still tiles
|
||||
let (kx, ky) = (f("skew_x", 1.0).round().clamp(-32.0, 32.0), f("skew_y", 0.0).round().clamp(-32.0, 32.0));
|
||||
// align = the line the shear pivots around: 0 centre, 1 top left (default), 2 bottom right
|
||||
let o = match f("align", 1.0).round() as u32 {
|
||||
0 => 0.5,
|
||||
2 => 1.0,
|
||||
_ => 0.0,
|
||||
};
|
||||
Tex::from_fn(t.w, t.h, |u, v| t.sample_cubic(u + kx * (v - o), v + ky * (u - o)))
|
||||
}
|
||||
// ------------------------------------------------ adjustments
|
||||
"auto_levels" => {
|
||||
let t = need("in")?;
|
||||
let per_ch = f("per_channel", 0.0) > 0.5;
|
||||
let mut lo = [f32::MAX; 3];
|
||||
let mut hi = [f32::MIN; 3];
|
||||
for p in &t.px {
|
||||
for ((l, h), &pc) in lo.iter_mut().zip(hi.iter_mut()).zip(p) {
|
||||
*l = l.min(pc);
|
||||
*h = h.max(pc);
|
||||
}
|
||||
}
|
||||
if !per_ch {
|
||||
let (l, h) = (lo[0].min(lo[1]).min(lo[2]), hi[0].max(hi[1]).max(hi[2]));
|
||||
lo = [l; 3];
|
||||
hi = [h; 3];
|
||||
}
|
||||
t.map(|p| {
|
||||
let mut o = p;
|
||||
for ((oc, pc), (l, h)) in o.iter_mut().zip(p).zip(lo.into_iter().zip(hi)) {
|
||||
*oc = if h - l > 1e-6 { (pc - l) / (h - l) } else { pc };
|
||||
}
|
||||
o
|
||||
})
|
||||
}
|
||||
"channel_mixer" => {
|
||||
let t = need("in")?;
|
||||
let m =
|
||||
[[f("rr", 1.0), f("rg", 0.0), f("rb", 0.0)], [f("gr", 0.0), f("gg", 1.0), f("gb", 0.0)], [f("br", 0.0), f("bg", 0.0), f("bb", 1.0)]];
|
||||
let mono = f("mono", 0.0) > 0.5;
|
||||
t.map(|p| {
|
||||
let mut o = p;
|
||||
for (oc, mc) in o.iter_mut().zip(&m) {
|
||||
*oc = (mc[0] * p[0] + mc[1] * p[1] + mc[2] * p[2]).clamp(-8.0, 8.0);
|
||||
}
|
||||
if mono {
|
||||
let g = lum(o);
|
||||
o = [g, g, g, p[3]];
|
||||
}
|
||||
o
|
||||
})
|
||||
}
|
||||
"alpha_merge" => {
|
||||
let rgb = need("rgb")?;
|
||||
match opt("alpha") {
|
||||
Some(a) => Tex::from_fn(rgb.w, rgb.h, |u, v| {
|
||||
let p = rgb.sample(u, v);
|
||||
[p[0], p[1], p[2], lum(a.sample(u, v))]
|
||||
}),
|
||||
None => rgb.clone(),
|
||||
}
|
||||
}
|
||||
"color_to_mask" => {
|
||||
let t = need("in")?;
|
||||
let (cr, cg, cb) = (f("r", 1.0), f("g", 0.0), f("b", 0.0));
|
||||
let (range, soft) = (f("range", 0.2).max(0.0), f("softness", 0.1).max(0.0));
|
||||
t.map(|p| {
|
||||
let d = ((math::powi(p[0] - cr, 2) + math::powi(p[1] - cg, 2) + math::powi(p[2] - cb, 2)) / 3.0).sqrt();
|
||||
let m = 1.0 - smooth(range, range + soft.max(1e-4), d);
|
||||
[m, m, m, 1.0]
|
||||
})
|
||||
}
|
||||
"replace_color" => {
|
||||
let t = need("in")?;
|
||||
let src = [f("src_r", 1.0), f("src_g", 0.0), f("src_b", 0.0)];
|
||||
let dst = [f("dst_r", 0.0), f("dst_g", 0.0), f("dst_b", 1.0)];
|
||||
let (range, soft) = (f("range", 0.25).max(0.0), f("softness", 0.15).max(0.0));
|
||||
t.map(|p| {
|
||||
let d = ((math::powi(p[0] - src[0], 2) + math::powi(p[1] - src[1], 2) + math::powi(p[2] - src[2], 2)) / 3.0).sqrt();
|
||||
let m = 1.0 - smooth(range, range + soft.max(1e-4), d);
|
||||
[p[0] + (dst[0] - src[0]) * m, p[1] + (dst[1] - src[1]) * m, p[2] + (dst[2] - src[2]) * m, p[3]]
|
||||
})
|
||||
}
|
||||
"pow" => {
|
||||
let t = need("in")?;
|
||||
let e = f("exponent", 2.0).clamp(0.0, 32.0);
|
||||
t.map(|p| [math::powf(p[0].max(0.0), e), math::powf(p[1].max(0.0), e), math::powf(p[2].max(0.0), e), p[3]])
|
||||
}
|
||||
"histogram_shift" => {
|
||||
let t = need("in")?;
|
||||
let d = (f("position", 0.5) - 0.5) * 2.0;
|
||||
t.map(|p| [(p[0] + d).clamp(0.0, 1.0), (p[1] + d).clamp(0.0, 1.0), (p[2] + d).clamp(0.0, 1.0), p[3]])
|
||||
}
|
||||
"grayscale_conversion" => {
|
||||
let t = need("in")?;
|
||||
let (wr, wg, wb, wa) = (f("r", 0.3), f("g", 0.59), f("b", 0.11), f("a", 0.0));
|
||||
let (lo, hi) = if f("limit", 0.0) > 0.5 { (0.0, 1.0) } else { (f32::MIN, f32::MAX) };
|
||||
t.map(|p| {
|
||||
let g = (p[0] * wr + p[1] * wg + p[2] * wb + p[3] * wa).clamp(lo, hi);
|
||||
[g, g, g, p[3]]
|
||||
})
|
||||
}
|
||||
// ------------------------------------------------ generators
|
||||
"cells" => {
|
||||
let mut cells = noise::Cells::new(f("variant", 0.0) as u32, per("scale", 8.0), seed);
|
||||
cells.jitter = f("jitter", 1.0).clamp(0.0, 1.0);
|
||||
(cells.luminance_random, cells.edge_width, cells.hardness) =
|
||||
(f("luminance_random", 0.0).clamp(0.0, 1.0), f("edge_width", 0.25).clamp(0.01, 1.0), f("hardness", 2.0).clamp(0.1, 16.0));
|
||||
let (src, pseed) = (f("color_source", 0.0) as u32, f("pseudorandom_seed", 0.0) as u32);
|
||||
// cell value of Cells 4: random, pseudorandom (re-rolled with its own seed) or the input image at the cell centre
|
||||
cells.source = if src == 1 { noise::CellSource::Pseudorandom(pseed) } else { noise::CellSource::Random };
|
||||
let img = if src == 2 { opt("color") } else { None };
|
||||
cells.output = f("_out", 0.0).round().max(0.0) as u32;
|
||||
if f("square_cells", 0.0) > 0.5 {
|
||||
cells.rows = ((cells.scale as f32 * hs as f32 / s as f32).round().max(1.0)) as i32;
|
||||
}
|
||||
let image = img.map(|t| move |x: f32, y: f32| lum(t.sample(x, y)));
|
||||
fin(Tex::gray_fn(s, hs, move |u, v| {
|
||||
let (u, v) = dz.warp(u, v);
|
||||
cells.value_with(u, v, image.as_ref().map(|i| i as &dyn Fn(f32, f32) -> f32))
|
||||
}))
|
||||
}
|
||||
"fractal_sum" => {
|
||||
let (p, lo, hi) = (per("scale", 2.0), f("min_level", 0.0).clamp(0.0, 10.0) as u32, f("max_level", 6.0).clamp(0.0, 10.0) as u32);
|
||||
let rough = f("roughness", 0.5).clamp(0.0, 1.5);
|
||||
let mode = f("mode", 0.0) as u32;
|
||||
let hi = hi.max(lo);
|
||||
let grids: Vec<(noise::GradGrid, f32)> = (lo..=hi)
|
||||
.map(|o| {
|
||||
let q = (p as i64 * (1i64 << o)).clamp(1, 1024) as i32;
|
||||
(noise::GradGrid::new(q, q, seed.wrapping_add(o * 31)), math::powi(rough, (o - lo) as i32))
|
||||
})
|
||||
.collect();
|
||||
let norm: f32 = grids.iter().map(|g| g.1).sum::<f32>().max(1e-6);
|
||||
fin(Tex::gray_fn(s, hs, move |u, v| {
|
||||
let (u, v) = dz.warp(u, v);
|
||||
let mut acc = 0.0;
|
||||
for (g, a) in &grids {
|
||||
let x = g.sample(u, v);
|
||||
acc += a * match mode {
|
||||
1 => (x * 2.0 - 1.0).abs(),
|
||||
2 => 1.0 - (x * 2.0 - 1.0).abs(),
|
||||
_ => x,
|
||||
};
|
||||
}
|
||||
(acc / norm).clamp(0.0, 1.0)
|
||||
}))
|
||||
}
|
||||
"waveform" => {
|
||||
let (a, b) = ops::tileable_wave(f("count", 8.0), f("angle", 0.0));
|
||||
let (warp, w) = (f("warp", 0.3).clamp(0.0, 4.0), per("warp_scale", 4.0));
|
||||
let shape = f("shape", 0.0) as u32;
|
||||
fin(Tex::gray_fn(s, hs, move |u, v| {
|
||||
let (u, v) = dz.warp(u, v);
|
||||
let ph = (a as f32 * u + b as f32 * v) + (noise::perlin(u, v, w, w, seed) - 0.5) * warp;
|
||||
let x = ph - ph.floor();
|
||||
match shape {
|
||||
1 => 1.0 - (x * 2.0 - 1.0).abs(),
|
||||
2 => x,
|
||||
3 => {
|
||||
if x < 0.5 {
|
||||
1.0
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
_ => 0.5 + 0.5 * math::sin(x * TAU),
|
||||
}
|
||||
}))
|
||||
}
|
||||
"gaussian_spots" => {
|
||||
let spots = noise::GaussianSpots {
|
||||
scale: per("scale", 8.0),
|
||||
seed,
|
||||
size: f("size", 0.5).clamp(0.05, 1.0),
|
||||
size_variation: f("size_variation", 0.5).clamp(0.0, 1.0),
|
||||
};
|
||||
fin(Tex::gray_fn(s, hs, move |u, v| {
|
||||
let (u, v) = dz.warp(u, v);
|
||||
spots.value(u, v)
|
||||
}))
|
||||
}
|
||||
// ------------------------------------------------ normals and surface
|
||||
"normal_invert" => {
|
||||
let t = need("in")?;
|
||||
let (ix, iy, iz, ia) = (f("invert_x", 0.0) > 0.5, f("invert_y", 1.0) > 0.5, f("invert_z", 0.0) > 0.5, f("invert_a", 0.0) > 0.5);
|
||||
t.map(|p| {
|
||||
[
|
||||
if ix { 1.0 - p[0] } else { p[0] },
|
||||
if iy { 1.0 - p[1] } else { p[1] },
|
||||
if iz { 1.0 - p[2] } else { p[2] },
|
||||
if ia { 1.0 - p[3] } else { p[3] },
|
||||
]
|
||||
})
|
||||
}
|
||||
"normal_normalize" => need("in")?.map(|p| {
|
||||
let (x, y, z) = ((p[0] - 0.5) * 2.0, (p[1] - 0.5) * 2.0, (p[2] - 0.5) * 2.0);
|
||||
let l = (x * x + y * y + z * z).sqrt().max(1e-6);
|
||||
[x / l * 0.5 + 0.5, y / l * 0.5 + 0.5, z / l * 0.5 + 0.5, p[3]]
|
||||
}),
|
||||
"normal_vector_rotation" => {
|
||||
let t = need("in")?;
|
||||
let (ang, gs) = (f("angle", 0.0) * TAU, if f("directx", 0.0) > 0.5 { -1.0f32 } else { 1.0 });
|
||||
let rot = opt("rotation");
|
||||
Tex::from_fn(t.w, t.h, |u, v| {
|
||||
let p = t.sample(u, v);
|
||||
// the optional rotation map scales the angle per pixel
|
||||
let a = ang * rot.map(|m| lum(m.sample(u, v))).unwrap_or(1.0);
|
||||
let (sn, cs) = math::sin_cos(a);
|
||||
let (x, y) = ((p[0] - 0.5) * 2.0, gs * (p[1] - 0.5) * 2.0);
|
||||
let (rx, ry) = (cs * x - sn * y, sn * x + cs * y);
|
||||
[rx * 0.5 + 0.5, gs * ry * 0.5 + 0.5, p[2], p[3]]
|
||||
})
|
||||
}
|
||||
"normal_to_height" => {
|
||||
normal_to_height(need("in")?, f("directx", 0.0) > 0.5, f("relief_balance", 0.5).clamp(0.0, 1.0), f("opacity", 1.0).clamp(0.0, 1.0))
|
||||
}
|
||||
"sobel" => {
|
||||
let t = need("in")?;
|
||||
let k = f("intensity", 1.0).clamp(0.0, 64.0) * (t.w as f32 / 512.0).max(0.25);
|
||||
Tex::from_fn(t.w, t.h, |u, v| {
|
||||
let (x, y) = ((u * t.w as f32) as i64, (v * t.h as f32) as i64);
|
||||
let g = |i: i64, j: i64| t.gray_at(x + i, y + j);
|
||||
let gx = g(1, -1) + 2.0 * g(1, 0) + g(1, 1) - g(-1, -1) - 2.0 * g(-1, 0) - g(-1, 1);
|
||||
let gy = g(-1, 1) + 2.0 * g(0, 1) + g(1, 1) - g(-1, -1) - 2.0 * g(0, -1) - g(1, -1);
|
||||
let m = ((gx * gx + gy * gy).sqrt() * k * 0.25).clamp(0.0, 1.0);
|
||||
[m, m, m, 1.0]
|
||||
})
|
||||
}
|
||||
// ------------------------------------------------ effects
|
||||
"glow" => {
|
||||
let t = need("in")?;
|
||||
let (w, inten) = (f("width", 8.0).clamp(0.0, 128.0) * rs, f("intensity", 1.0).clamp(0.0, 8.0));
|
||||
let b = ops::blur(t, w);
|
||||
// clear amount cuts the faint tail of the glow off; the colour tints it (white = unchanged)
|
||||
let (clear, gc) = (f("clear", 0.0).clamp(0.0, 0.99), [f("glow_r", 1.0), f("glow_g", 1.0), f("glow_b", 1.0)]);
|
||||
Tex::from_fn(t.w, t.h, |u, v| {
|
||||
let (p, q) = (t.sample(u, v), b.sample(u, v));
|
||||
let cut = |x: f32| ((x - clear) / (1.0 - clear)).max(0.0);
|
||||
[
|
||||
(p[0] + cut(q[0]) * gc[0] * inten).clamp(0.0, 1.0),
|
||||
(p[1] + cut(q[1]) * gc[1] * inten).clamp(0.0, 1.0),
|
||||
(p[2] + cut(q[2]) * gc[2] * inten).clamp(0.0, 1.0),
|
||||
p[3],
|
||||
]
|
||||
})
|
||||
}
|
||||
"mosaic" => {
|
||||
let t = need("in")?;
|
||||
if let Some(m) = opt("mosaic_map") {
|
||||
ops::mosaic_map(t, m, f("intensity", 1.0))
|
||||
} else {
|
||||
// no map: a plain grid of `count` cells per side
|
||||
let c = per("count", 16.0) as f32;
|
||||
Tex::from_fn(t.w, t.h, |u, v| t.sample(((u * c).floor() + 0.5) / c, ((v * c).floor() + 0.5) / c))
|
||||
}
|
||||
}
|
||||
"shape_drop_shadow" => {
|
||||
let t = need("in")?;
|
||||
let (ang, dist) = (f("angle", 0.125) * TAU, f("distance", 0.03).clamp(0.0, 0.5));
|
||||
let (sn, cs) = math::sin_cos(ang);
|
||||
let shifted = Tex::from_fn(t.w, t.h, |u, v| t.sample(u - cs * dist, v - sn * dist));
|
||||
let sh = ops::blur(&shifted, f("blur", 6.0).clamp(0.0, 128.0) * rs);
|
||||
let op = f("opacity", 0.8).clamp(0.0, 1.0);
|
||||
let spread = f("spread", 0.0).clamp(0.0, 1.0);
|
||||
Tex::from_fn(t.w, t.h, |u, v| {
|
||||
// spread raises the blur cut-off so the shadow stays solid for longer
|
||||
let sv = (lum(sh.sample(u, v)) / (1.0 - spread * 0.99)).min(1.0);
|
||||
let m = lum(t.sample(u, v)).max(sv * op).clamp(0.0, 1.0);
|
||||
[m, m, m, 1.0]
|
||||
})
|
||||
}
|
||||
// ------------------------------------------------ batch 1b: warps, patterns, strokes
|
||||
"non_uniform_directional_warp" => {
|
||||
let (t, m) = (need("in")?, need("intensity")?);
|
||||
let (k, base) = (f("intensity", 0.1).clamp(-2.0, 2.0), f("angle", 0.0) * TAU);
|
||||
let am = opt("angle");
|
||||
Tex::from_fn(t.w, t.h, |u, v| {
|
||||
let a = base + am.map(|a| (lum(a.sample(u, v)) - 0.5) * TAU).unwrap_or(0.0);
|
||||
let d = (lum(m.sample(u, v)) - 0.5) * 2.0 * k;
|
||||
t.sample_cubic(u + math::cos(a) * d, v + math::sin(a) * d)
|
||||
})
|
||||
}
|
||||
"multi_directional_warp" => {
|
||||
let (t, m) = (need("in")?, need("warp")?);
|
||||
let (k, a0) = (f("intensity", 0.1).clamp(-2.0, 2.0), f("angle", 0.0));
|
||||
// Directions: 0 = 1 (the angle and its opposite), 1 = 2 (plus the perpendicular axis), 2 = 4 (plus the 45 degree
|
||||
// steps). Larger values from older graphs keep meaning "that many samples".
|
||||
let dv = f("directions", 2.0).round().max(0.0) as usize;
|
||||
let n = match dv {
|
||||
0 => 2,
|
||||
1 => 4,
|
||||
2 => 8,
|
||||
_ => dv.min(16),
|
||||
};
|
||||
let mode = f("mode", 0.0).round() as u32; // 0 average, 1 max, 2 min, 3 chain
|
||||
if mode == 3 {
|
||||
// each direction warps the result of the previous one
|
||||
let mut cur = t.clone();
|
||||
for i in 0..n {
|
||||
let a = (a0 + i as f32 / n as f32) * TAU;
|
||||
let src = cur.clone();
|
||||
cur = Tex::from_fn(t.w, t.h, |u, v| {
|
||||
let d = (lum(m.sample(u, v)) - 0.5) * 2.0 * k / n as f32;
|
||||
src.sample(u + math::cos(a) * d, v + math::sin(a) * d)
|
||||
});
|
||||
}
|
||||
cur
|
||||
} else {
|
||||
Tex::from_fn(t.w, t.h, |u, v| {
|
||||
let d = (lum(m.sample(u, v)) - 0.5) * 2.0 * k;
|
||||
let mut acc = if mode == 1 {
|
||||
[f32::MIN; 4]
|
||||
} else if mode == 2 {
|
||||
[f32::MAX; 4]
|
||||
} else {
|
||||
[0.0f32; 4]
|
||||
};
|
||||
for i in 0..n {
|
||||
let a = (a0 + i as f32 / n as f32) * TAU;
|
||||
let p = t.sample(u + math::cos(a) * d, v + math::sin(a) * d);
|
||||
for (ac, pc) in acc.iter_mut().zip(p) {
|
||||
match mode {
|
||||
1 => *ac = ac.max(pc),
|
||||
2 => *ac = ac.min(pc),
|
||||
_ => *ac += pc / n as f32,
|
||||
}
|
||||
}
|
||||
}
|
||||
acc
|
||||
})
|
||||
}
|
||||
}
|
||||
"normal_combine" => {
|
||||
// technique 0 whiteout, 1 channel mixer (partial derivatives added), 2 detail oriented (reoriented normal mapping:
|
||||
// the detail normal is rotated into the surface of the base normal)
|
||||
let (b, d) = (need("base")?, need("detail")?);
|
||||
let tech = f("technique", 2.0).round() as u32;
|
||||
Tex::from_fn(b.w, b.h, |u, v| {
|
||||
let (pb, pd) = (b.sample(u, v), d.sample(u, v));
|
||||
if tech < 2 {
|
||||
let (bx, by, bz) = ((pb[0] - 0.5) * 2.0, (pb[1] - 0.5) * 2.0, ((pb[2] - 0.5) * 2.0).max(0.05));
|
||||
let (dx, dy, dz) = ((pd[0] - 0.5) * 2.0, (pd[1] - 0.5) * 2.0, ((pd[2] - 0.5) * 2.0).max(0.05));
|
||||
let r = if tech == 0 { [bx + dx, by + dy, bz * dz] } else { [bx / bz + dx / dz, by / bz + dy / dz, 1.0] };
|
||||
let l = (r[0] * r[0] + r[1] * r[1] + r[2] * r[2]).sqrt().max(1e-6);
|
||||
return [r[0] / l * 0.5 + 0.5, r[1] / l * 0.5 + 0.5, r[2] / l * 0.5 + 0.5, 1.0];
|
||||
}
|
||||
let tt = [(pb[0] - 0.5) * 2.0, (pb[1] - 0.5) * 2.0, (pb[2] - 0.5) * 2.0 + 1.0];
|
||||
let uu = [-(pd[0] - 0.5) * 2.0, -(pd[1] - 0.5) * 2.0, (pd[2] - 0.5) * 2.0];
|
||||
let dot = tt[0] * uu[0] + tt[1] * uu[1] + tt[2] * uu[2];
|
||||
let tz = if tt[2].abs() < 1e-4 { 1e-4 } else { tt[2] };
|
||||
let r = [tt[0] * dot / tz - uu[0], tt[1] * dot / tz - uu[1], tt[2] * dot / tz - uu[2]];
|
||||
let l = (r[0] * r[0] + r[1] * r[1] + r[2] * r[2]).sqrt().max(1e-6);
|
||||
[r[0] / l * 0.5 + 0.5, r[1] / l * 0.5 + 0.5, r[2] / l * 0.5 + 0.5, 1.0]
|
||||
})
|
||||
}
|
||||
"triangle_grid" if f("style", 0.0) >= 0.5 => {
|
||||
let lattice = noise::TriangleLattice {
|
||||
nx: per("x_amount", 16.0).clamp(1, 64),
|
||||
ny: per("y_amount", 16.0).clamp(1, 64),
|
||||
amp: f("random_position_multiplier", 1.0).clamp(0.0, 2.0).min(1.0) * 0.32,
|
||||
quincunx: (f("quincunx_offset_x", 0.0).clamp(0.0, 1.0), f("quincunx_offset_y", 0.0).clamp(0.0, 1.0)),
|
||||
height_random: f("height_random", 1.0).clamp(0.0, 1.0),
|
||||
triangulation: f("triangulation", 0.0).round() as i32,
|
||||
output: f("output", 0.0).round() as i32,
|
||||
line_thickness: f("distance_to_edge_thickness", 0.025).clamp(0.0, 0.1),
|
||||
line_color: f("thin_line_color", 1.0),
|
||||
line_background: f("thin_line_background", 0.0),
|
||||
lines: f("thin_lines", 0.0) > 0.5,
|
||||
seed,
|
||||
};
|
||||
fin(Tex::gray_fn(s, hs, move |u, v| lattice.value(u, v)))
|
||||
}
|
||||
"triangle_grid" => {
|
||||
let grid = noise::TriangleGrid {
|
||||
count: per("count", 8.0),
|
||||
border: f("border", 0.06).clamp(0.0, 0.5),
|
||||
variation: f("variation", 1.0).clamp(0.0, 1.0),
|
||||
seed,
|
||||
};
|
||||
fin(Tex::gray_fn(s, hs, move |u, v| grid.value(u, v)))
|
||||
}
|
||||
"weave_generator" => {
|
||||
let mut weave = noise::WeaveGenerator::new(
|
||||
(per("tile_x", 1.0).clamp(1, 20), per("tile_y", 1.0).clamp(1, 20)),
|
||||
per("weave", 2.0).clamp(1, 10),
|
||||
f("shape", 0.5).clamp(0.0, 1.0),
|
||||
(f("gap_x", 0.1).clamp(0.0, 0.9), f("gap_y", 0.1).clamp(0.0, 0.9)),
|
||||
);
|
||||
weave.output = f("_out", 0.0).round().max(0.0) as u32;
|
||||
let t = Tex::gray_fn(s, hs, move |u, v| weave.value(u, v));
|
||||
if weave.output == 0 { fin(t) } else { t }
|
||||
}
|
||||
"starburst" => {
|
||||
let star = noise::Starburst {
|
||||
count: per("count", 3.0),
|
||||
rays: f("rays", 8.0).round().clamp(2.0, 64.0),
|
||||
sharpness: f("sharpness", 2.0).clamp(0.1, 16.0),
|
||||
size: f("size", 1.0).clamp(0.05, 2.0),
|
||||
rotation: f("rotation", 0.0),
|
||||
rotation_random: f("rotation_random", 0.0).clamp(0.0, 1.0),
|
||||
seed,
|
||||
};
|
||||
fin(Tex::gray_fn(s, hs, move |u, v| star.value(u, v)))
|
||||
}
|
||||
"gradient_reflected" => {
|
||||
let (a, b) = ops::tileable_wave(f("count", 1.0), f("angle", 0.0));
|
||||
fin(Tex::gray_fn(s, hs, move |u, v| {
|
||||
let ph = a as f32 * u + b as f32 * v;
|
||||
1.0 - (2.0 * (ph - ph.floor()) - 1.0).abs()
|
||||
}))
|
||||
}
|
||||
"shape_stroke" | "shape_glow" => {
|
||||
let t = need("in")?;
|
||||
let w = (f("width", 8.0).clamp(0.5, 256.0) * rs).max(2.0);
|
||||
let mask: Vec<bool> = t.px.iter().map(|p| lum(*p) > f("threshold", 0.5)).collect();
|
||||
let inside = ops::distance_field(&mask, t.w, t.h);
|
||||
let inv: Vec<bool> = mask.iter().map(|m| !m).collect();
|
||||
let outside = ops::distance_field(&inv, t.w, t.h);
|
||||
let stroke = kind == "shape_stroke";
|
||||
let (off, soft, inten) = (f("offset", 0.0).clamp(-1.0, 1.0), f("softness", 0.5).clamp(0.0, 1.0), f("intensity", 1.0).clamp(0.0, 4.0));
|
||||
let (opacity, spread) = (f("opacity", 1.0).clamp(0.0, 1.0), f("spread", 0.0).clamp(0.0, 1.0));
|
||||
let col = [f("color_r", 1.0), f("color_g", 1.0), f("color_b", 1.0)];
|
||||
let px = mask
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &mi)| {
|
||||
let (ins, outs) = (inside.get(i).copied().unwrap_or(0.0), outside.get(i).copied().unwrap_or(0.0));
|
||||
// signed distance in pixels: positive outside the shape
|
||||
let sd = if mi { -(ins.min(1e8) - 0.5) } else { outs.min(1e8) - 0.5 };
|
||||
let g = if stroke {
|
||||
let c = off * w * 0.5;
|
||||
1.0 - smooth(w * 0.5 * (1.0 - soft), w * 0.5 + 0.5, (sd - c).abs())
|
||||
} else if mi {
|
||||
1.0
|
||||
} else {
|
||||
math::powf(1.0 - (sd / w).clamp(0.0, 1.0), 1.0 + soft * 3.0) * inten
|
||||
};
|
||||
let g = if stroke { g } else { g / (1.0 - spread * 0.99) };
|
||||
let g = g.clamp(0.0, 1.0) * opacity;
|
||||
[g * col[0], g * col[1], g * col[2], 1.0]
|
||||
})
|
||||
.collect();
|
||||
Tex { w: t.w, h: t.h, px }
|
||||
}
|
||||
"chrominance_extract" => need("in")?.map(|p| {
|
||||
let l = lum(p).max(1e-3);
|
||||
[(p[0] / l * 0.5).clamp(0.0, 1.0), (p[1] / l * 0.5).clamp(0.0, 1.0), (p[2] / l * 0.5).clamp(0.0, 1.0), p[3]]
|
||||
}),
|
||||
_ => return Ok(None),
|
||||
};
|
||||
Ok(Some(out))
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Seeded, tileable procedural noise, and the cell, spot and pattern looks built on it ([`cells`], [`patterns`]).
|
||||
use crate::math;
|
||||
use std::f32::consts::TAU;
|
||||
|
||||
pub mod cells;
|
||||
pub mod patterns;
|
||||
|
||||
pub use cells::{BnwSpots, CellSource, Cells, Crystal, GaussianSpots, VoronoiFractal, VoronoiSettings};
|
||||
pub use patterns::{Starburst, TriangleGrid, TriangleLattice, Weave, WeaveGenerator};
|
||||
|
||||
/// Smooth Hermite step from 0 at `a` to 1 at `b` (a hard step when `a == b`).
|
||||
pub fn smoothstep(a: f32, b: f32, x: f32) -> f32 {
|
||||
let d = b - a;
|
||||
let t = if d.abs() < 1e-9 { if x >= b { 1.0 } else { 0.0 } } else { ((x - a) / d).clamp(0.0, 1.0) };
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
|
||||
pub fn hash2(x: i32, y: i32, seed: u32) -> u32 {
|
||||
let mut h = (x as u32).wrapping_mul(0x27d4_eb2d) ^ (y as u32).wrapping_mul(0x1656_67b1) ^ seed.wrapping_mul(0x9e37_79b9);
|
||||
h ^= h >> 15;
|
||||
h = h.wrapping_mul(0x85eb_ca6b);
|
||||
h ^= h >> 13;
|
||||
h = h.wrapping_mul(0xc2b2_ae35);
|
||||
h ^= h >> 16;
|
||||
h
|
||||
}
|
||||
|
||||
/// `x.rem_euclid(n)` that never panics: 0 for `n == 0`, and the wrapped result for `i32::MIN % -1`.
|
||||
#[inline]
|
||||
pub(crate) fn wrem(x: i32, n: i32) -> i32 {
|
||||
if n == 0 { 0 } else { x.wrapping_rem_euclid(n) }
|
||||
}
|
||||
|
||||
pub fn rnd(x: i32, y: i32, seed: u32) -> f32 {
|
||||
(hash2(x, y, seed) >> 8) as f32 / 16_777_216.0
|
||||
}
|
||||
|
||||
fn fade(t: f32) -> f32 {
|
||||
t * t * t * (t * (t * 6.0 - 15.0) + 10.0)
|
||||
}
|
||||
|
||||
fn lerp(a: f32, b: f32, t: f32) -> f32 {
|
||||
a + (b - a) * t
|
||||
}
|
||||
|
||||
/// Unit gradient vectors for 4096 evenly spaced angles (replaces a cos/sin per lattice corner).
|
||||
fn grad_table() -> &'static [[f32; 2]; 4096] {
|
||||
static T: std::sync::OnceLock<Box<[[f32; 2]; 4096]>> = std::sync::OnceLock::new();
|
||||
T.get_or_init(|| {
|
||||
let mut t = Box::new([[0.0f32; 2]; 4096]);
|
||||
for (i, e) in t.iter_mut().enumerate() {
|
||||
let a = i as f32 / 4096.0 * TAU;
|
||||
*e = [math::cos(a), math::sin(a)];
|
||||
}
|
||||
t
|
||||
})
|
||||
}
|
||||
|
||||
/// Gradient at a lattice point: same pseudo-random angle as `rnd(x, y, seed) * TAU`, quantised to 4096 steps.
|
||||
#[inline]
|
||||
fn grad_at(x: i32, y: i32, seed: u32) -> [f32; 2] {
|
||||
grad_table().get((hash2(x, y, seed) >> 20) as usize).copied().unwrap_or([0.0; 2])
|
||||
}
|
||||
|
||||
/// Tileable gradient (Perlin) noise in 0..1. `px`,`py` are integer lattice periods.
|
||||
pub fn perlin(u: f32, v: f32, px: i32, py: i32, seed: u32) -> f32 {
|
||||
let px = px.max(1);
|
||||
let py = py.max(1);
|
||||
let x = u * px as f32;
|
||||
let y = v * py as f32;
|
||||
let fxl = x.floor();
|
||||
let fyl = y.floor();
|
||||
let ix = fxl as i32;
|
||||
let iy = fyl as i32;
|
||||
let fx = x - fxl;
|
||||
let fy = y - fyl;
|
||||
let tab = grad_table();
|
||||
let g = |cx: i32, cy: i32, dx: f32, dy: f32| {
|
||||
let c = tab.get((hash2(cx.rem_euclid(px), cy.rem_euclid(py), seed) >> 20) as usize).copied().unwrap_or([0.0; 2]);
|
||||
c[0] * dx + c[1] * dy
|
||||
};
|
||||
let n00 = g(ix, iy, fx, fy);
|
||||
let n10 = g(ix.wrapping_add(1), iy, fx - 1.0, fy);
|
||||
let n01 = g(ix, iy.wrapping_add(1), fx, fy - 1.0);
|
||||
let n11 = g(ix.wrapping_add(1), iy.wrapping_add(1), fx - 1.0, fy - 1.0);
|
||||
let sx = fade(fx);
|
||||
let sy = fade(fy);
|
||||
let n = lerp(lerp(n00, n10, sx), lerp(n01, n11, sx), sy);
|
||||
(n * std::f32::consts::FRAC_1_SQRT_2 + 0.5).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// Fractal noise. mode: 0 = fBm, 1 = ridged, 2 = turbulence.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn fbm(u: f32, v: f32, px: i32, py: i32, octaves: u32, gain: f32, seed: u32, mode: u32) -> f32 {
|
||||
let mut amp = 1.0;
|
||||
let mut sum = 0.0;
|
||||
let mut norm = 0.0;
|
||||
let cx = px.max(1);
|
||||
let cy = py.max(1);
|
||||
// Every octave is rotated by about 26.6 degrees and scaled by sqrt(5) with the INTEGER matrix [[2, -1], [1, 2]], so
|
||||
// the lattice directions of different octaves never line up (no visible grid) and the noise still tiles exactly.
|
||||
let (mut a, mut b) = (u, v);
|
||||
for o in 0..octaves.clamp(1, 12) {
|
||||
let n = perlin(a, b, cx, cy, seed.wrapping_add(o.wrapping_mul(131)));
|
||||
let n = match mode {
|
||||
1 => 1.0 - (2.0 * n - 1.0).abs(),
|
||||
2 => (2.0 * n - 1.0).abs(),
|
||||
_ => n,
|
||||
};
|
||||
sum += n * amp;
|
||||
norm += amp;
|
||||
amp *= gain;
|
||||
let (na, nb) = (2.0 * a - b, a + 2.0 * b);
|
||||
// keep the coordinates small: whole periods do not change a periodic function
|
||||
a = na.rem_euclid(1.0);
|
||||
b = nb.rem_euclid(1.0);
|
||||
}
|
||||
if norm > 0.0 {
|
||||
// averaged octaves cluster around mid grey; stretch them so the result uses most of the 0..1 range
|
||||
let m = sum / norm;
|
||||
let k = match mode {
|
||||
0 => 1.7,
|
||||
_ => 1.35,
|
||||
};
|
||||
(0.5 + (m - 0.5) * k).clamp(0.0, 1.0)
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Fractal noise with the gradient lattices of all octaves built once (no hashing per pixel). Gives exactly the same
|
||||
/// values as `fbm`; use it when many pixels share the same parameters.
|
||||
pub struct Fbm {
|
||||
grids: Vec<GradGrid>,
|
||||
px: i32,
|
||||
py: i32,
|
||||
octaves: u32,
|
||||
gain: f32,
|
||||
seed: u32,
|
||||
mode: u32,
|
||||
}
|
||||
|
||||
impl Fbm {
|
||||
pub fn new(px: i32, py: i32, octaves: u32, gain: f32, seed: u32, mode: u32) -> Fbm {
|
||||
let (cx, cy) = (px.max(1), py.max(1));
|
||||
let octaves = octaves.clamp(1, 12);
|
||||
// very coarse lattices would need huge tables: those fall back to hashing in `sample`
|
||||
let grids = if (cx as i64) * (cy as i64) <= (1 << 20) {
|
||||
(0..octaves).map(|o| GradGrid::new(cx, cy, seed.wrapping_add(o.wrapping_mul(131)))).collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
Fbm { grids, px: cx, py: cy, octaves, gain, seed, mode }
|
||||
}
|
||||
|
||||
pub fn sample(&self, u: f32, v: f32) -> f32 {
|
||||
if self.grids.is_empty() {
|
||||
return fbm(u, v, self.px, self.py, self.octaves, self.gain, self.seed, self.mode);
|
||||
}
|
||||
let (mut amp, mut sum, mut norm) = (1.0f32, 0.0f32, 0.0f32);
|
||||
let (mut a, mut b) = (u, v);
|
||||
for g in &self.grids {
|
||||
let n = g.sample(a, b);
|
||||
let n = match self.mode {
|
||||
1 => 1.0 - (2.0 * n - 1.0).abs(),
|
||||
2 => (2.0 * n - 1.0).abs(),
|
||||
_ => n,
|
||||
};
|
||||
sum += n * amp;
|
||||
norm += amp;
|
||||
amp *= self.gain;
|
||||
let (na, nb) = (2.0 * a - b, a + 2.0 * b);
|
||||
a = na - crate::tex::ffloor(na);
|
||||
b = nb - crate::tex::ffloor(nb);
|
||||
}
|
||||
if norm > 0.0 {
|
||||
let m = sum / norm;
|
||||
let k = if self.mode == 0 { 1.7 } else { 1.35 };
|
||||
(0.5 + (m - 0.5) * k).clamp(0.0, 1.0)
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tileable Voronoi. Returns (f1, f2, cell_id) with distances normalised to ~0..1.
|
||||
pub fn voronoi(u: f32, v: f32, px: i32, py: i32, seed: u32, jitter: f32) -> (f32, f32, f32) {
|
||||
let px = px.max(1);
|
||||
let py = py.max(1);
|
||||
let x = u * px as f32;
|
||||
let y = v * py as f32;
|
||||
let ix = x.floor() as i32;
|
||||
let iy = y.floor() as i32;
|
||||
let mut f1 = f32::MAX;
|
||||
let mut f2 = f32::MAX;
|
||||
let mut id = 0.0;
|
||||
for dy in -1..=1 {
|
||||
for dx in -1..=1 {
|
||||
let cx = ix.wrapping_add(dx);
|
||||
let cy = iy.wrapping_add(dy);
|
||||
let wx = cx.rem_euclid(px);
|
||||
let wy = cy.rem_euclid(py);
|
||||
let fx = cx as f32 + 0.5 + (rnd(wx, wy, seed) - 0.5) * jitter;
|
||||
let fy = cy as f32 + 0.5 + (rnd(wx, wy, seed.wrapping_add(77)) - 0.5) * jitter;
|
||||
let d = (math::powi(fx - x, 2) + math::powi(fy - y, 2)).sqrt();
|
||||
if d < f1 {
|
||||
f2 = f1;
|
||||
f1 = d;
|
||||
id = rnd(wx, wy, seed.wrapping_add(999));
|
||||
} else if d < f2 {
|
||||
f2 = d;
|
||||
}
|
||||
}
|
||||
}
|
||||
let k = std::f32::consts::FRAC_1_SQRT_2;
|
||||
((f1 * k).clamp(0.0, 1.0), (f2 * k).clamp(0.0, 1.0), id)
|
||||
}
|
||||
|
||||
/// Soft round spots, one disc per cell, tileable. `shape(id)` gives the (inner, outer) radius of a cell's disc in the
|
||||
/// same normalised distance units as `voronoi`; discs may overlap the neighbouring cells, so the union of the 3x3
|
||||
/// surrounding discs is taken (no straight cuts where cells meet). `grain` is added to the distance.
|
||||
pub fn spots<F: Fn(f32) -> (f32, f32)>(u: f32, v: f32, px: i32, py: i32, seed: u32, shape: F, grain: f32) -> f32 {
|
||||
let (px, py) = (px.max(1), py.max(1));
|
||||
let (x, y) = (u * px as f32, v * py as f32);
|
||||
let (ix, iy) = (x.floor() as i32, y.floor() as i32);
|
||||
let k = std::f32::consts::FRAC_1_SQRT_2;
|
||||
let mut best = 0.0f32;
|
||||
for dy in -1..=1 {
|
||||
for dx in -1..=1 {
|
||||
let (cx, cy) = (ix.wrapping_add(dx), iy.wrapping_add(dy));
|
||||
let (wx, wy) = (cx.rem_euclid(px), cy.rem_euclid(py));
|
||||
let fx = cx as f32 + 0.5 + (rnd(wx, wy, seed) - 0.5);
|
||||
let fy = cy as f32 + 0.5 + (rnd(wx, wy, seed.wrapping_add(77)) - 0.5);
|
||||
let d = ((math::powi(fx - x, 2) + math::powi(fy - y, 2)).sqrt() * k + grain).max(0.0);
|
||||
let (lo, hi) = shape(rnd(wx, wy, seed.wrapping_add(999)));
|
||||
let t = ((d - lo) / (hi - lo).max(1e-6)).clamp(0.0, 1.0);
|
||||
best = best.max(1.0 - t * t * (3.0 - 2.0 * t));
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
pub struct Vor {
|
||||
pub f1: f32,
|
||||
pub f2: f32,
|
||||
pub id1: f32,
|
||||
pub id2: f32,
|
||||
pub dx: f32,
|
||||
pub dy: f32,
|
||||
}
|
||||
|
||||
/// Tileable Voronoi with the two nearest cells and the vector to the nearest site.
|
||||
pub fn voronoi_ext(u: f32, v: f32, px: i32, py: i32, seed: u32, jitter: f32) -> Vor {
|
||||
let px = px.max(1);
|
||||
let py = py.max(1);
|
||||
let x = u * px as f32;
|
||||
let y = v * py as f32;
|
||||
let (ix, iy) = (x.floor() as i32, y.floor() as i32);
|
||||
let mut r = Vor { f1: f32::MAX, f2: f32::MAX, id1: 0.0, id2: 0.0, dx: 0.0, dy: 0.0 };
|
||||
for dy in -1..=1 {
|
||||
for dx in -1..=1 {
|
||||
let (cx, cy) = (ix.wrapping_add(dx), iy.wrapping_add(dy));
|
||||
let (wx, wy) = (cx.rem_euclid(px), cy.rem_euclid(py));
|
||||
let fx = cx as f32 + 0.5 + (rnd(wx, wy, seed) - 0.5) * jitter;
|
||||
let fy = cy as f32 + 0.5 + (rnd(wx, wy, seed.wrapping_add(77)) - 0.5) * jitter;
|
||||
let d = (math::powi(fx - x, 2) + math::powi(fy - y, 2)).sqrt();
|
||||
let id = rnd(wx, wy, seed.wrapping_add(999));
|
||||
if d < r.f1 {
|
||||
r.f2 = r.f1;
|
||||
r.id2 = r.id1;
|
||||
r.f1 = d;
|
||||
r.id1 = id;
|
||||
r.dx = fx - x;
|
||||
r.dy = fy - y;
|
||||
} else if d < r.f2 {
|
||||
r.f2 = d;
|
||||
r.id2 = id;
|
||||
}
|
||||
}
|
||||
}
|
||||
let k = std::f32::consts::FRAC_1_SQRT_2;
|
||||
r.f1 = (r.f1 * k).clamp(0.0, 1.0);
|
||||
r.f2 = (r.f2 * k).clamp(0.0, 1.0);
|
||||
r
|
||||
}
|
||||
|
||||
/// Precomputed gradient lattice for fast, repeated tileable Perlin lookups (no hashing or trig per sample).
|
||||
/// `sample` returns exactly the same values as `perlin(u, v, px, py, seed)`.
|
||||
pub struct GradGrid {
|
||||
px: i32,
|
||||
py: i32,
|
||||
g: Vec<[f32; 2]>,
|
||||
}
|
||||
|
||||
impl GradGrid {
|
||||
pub fn new(px: i32, py: i32, seed: u32) -> GradGrid {
|
||||
let px = px.clamp(1, 4096);
|
||||
let py = py.clamp(1, 4096);
|
||||
let mut g = Vec::with_capacity((px as usize) * (py as usize));
|
||||
for y in 0..py {
|
||||
for x in 0..px {
|
||||
g.push(grad_at(x, y, seed));
|
||||
}
|
||||
}
|
||||
GradGrid { px, py, g }
|
||||
}
|
||||
|
||||
/// Periodic in u and v with period 1, for any (also negative or > 1) coordinates.
|
||||
#[inline]
|
||||
pub fn sample(&self, u: f32, v: f32) -> f32 {
|
||||
let x = u * self.px as f32;
|
||||
let y = v * self.py as f32;
|
||||
let (fxl, fyl) = (crate::tex::ffloor(x), crate::tex::ffloor(y));
|
||||
let (fx, fy) = (x - fxl, y - fyl);
|
||||
// wrap the two lattice columns / rows once instead of once per corner
|
||||
let x0 = (fxl as i64).rem_euclid(self.px as i64) as usize;
|
||||
let y0 = (fyl as i64).rem_euclid(self.py as i64) as usize;
|
||||
let x1 = if x0 + 1 == self.px as usize { 0 } else { x0 + 1 };
|
||||
let y1 = if y0 + 1 == self.py as usize { 0 } else { y0 + 1 };
|
||||
let row0 = y0 * self.px as usize;
|
||||
let row1 = y1 * self.px as usize;
|
||||
let at = |i: usize| self.g.get(i).copied().unwrap_or([0.0; 2]);
|
||||
let (c00, c10, c01, c11) = (at(row0 + x0), at(row0 + x1), at(row1 + x0), at(row1 + x1));
|
||||
let n00 = c00[0] * fx + c00[1] * fy;
|
||||
let n10 = c10[0] * (fx - 1.0) + c10[1] * fy;
|
||||
let n01 = c01[0] * fx + c01[1] * (fy - 1.0);
|
||||
let n11 = c11[0] * (fx - 1.0) + c11[1] * (fy - 1.0);
|
||||
let (sx, sy) = (fade(fx), fade(fy));
|
||||
let n = lerp(lerp(n00, n10, sx), lerp(n01, n11, sx), sy);
|
||||
(n * std::f32::consts::FRAC_1_SQRT_2 + 0.5).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The shared "Disorder" block of the noise nodes: the sampling position is displaced by a smooth, tileable random
|
||||
/// field. `disorder` is the amount, `speed` the distance it moves per unit of disorder, `aniso` (0..1) narrows the displacement
|
||||
/// to one direction and `angle_turns` sets that direction.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Disorder {
|
||||
amp: f32,
|
||||
seed: u32,
|
||||
aniso: f32,
|
||||
cs: f32,
|
||||
sn: f32,
|
||||
}
|
||||
|
||||
impl Disorder {
|
||||
pub fn new(seed: u32, disorder: f32, speed: f32, aniso: f32, angle_turns: f32) -> Disorder {
|
||||
let (sn, cs) = math::sin_cos(angle_turns * TAU);
|
||||
Disorder { amp: disorder.max(0.0) * speed.max(0.0) * 0.3, seed, aniso: aniso.clamp(0.0, 1.0), cs, sn }
|
||||
}
|
||||
pub fn warp(&self, u: f32, v: f32) -> (f32, f32) {
|
||||
if self.amp <= 0.0 {
|
||||
return (u, v);
|
||||
}
|
||||
let mut dx = (perlin(u, v, 3, 3, self.seed.wrapping_add(101)) - 0.5) * self.amp;
|
||||
let mut dy = (perlin(u, v, 3, 3, self.seed.wrapping_add(202)) - 0.5) * self.amp;
|
||||
if self.aniso > 0.0 {
|
||||
// project onto the chosen direction (the factor restores the length lost by the projection)
|
||||
let along = (dx * self.cs + dy * self.sn) * std::f32::consts::SQRT_2;
|
||||
dx += (along * self.cs - dx) * self.aniso;
|
||||
dy += (along * self.sn - dy) * self.aniso;
|
||||
}
|
||||
(u + dx, v + dy)
|
||||
}
|
||||
}
|
||||
|
||||
/// Seed of another tile of the infinite noise plane (Tile offset, integer part).
|
||||
pub fn tile_seed(seed: u32, tx: i32, ty: i32) -> u32 {
|
||||
hash2(tx, ty, seed.wrapping_add(0x7157))
|
||||
}
|
||||
|
||||
/// Distance metrics of the Voronoi node.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum Metric {
|
||||
Euclidean,
|
||||
Manhattan,
|
||||
Chebyshev,
|
||||
Minkowski(f32),
|
||||
}
|
||||
|
||||
impl Metric {
|
||||
pub fn from_index(i: u32, p: f32) -> Metric {
|
||||
match i {
|
||||
1 => Metric::Manhattan,
|
||||
2 => Metric::Chebyshev,
|
||||
3 => Metric::Minkowski(p.clamp(0.25, 16.0)),
|
||||
_ => Metric::Euclidean,
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn dist(self, dx: f32, dy: f32) -> f32 {
|
||||
let (ax, ay) = (dx.abs(), dy.abs());
|
||||
match self {
|
||||
Metric::Euclidean => (dx * dx + dy * dy).sqrt(),
|
||||
Metric::Manhattan => ax + ay,
|
||||
Metric::Chebyshev => ax.max(ay),
|
||||
Metric::Minkowski(p) => math::powf(math::powf(ax, p) + math::powf(ay, p), 1.0 / p),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tileable Voronoi with a selectable distance metric. `id_seed` seeds the random cell values (so the colours can
|
||||
/// be re-rolled without moving the cells). Distances are normalised like [`voronoi_ext`].
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn voronoi_gen(u: f32, v: f32, px: i32, py: i32, seed: u32, id_seed: u32, jitter: f32, metric: Metric) -> Vor {
|
||||
let (px, py) = (px.max(1), py.max(1));
|
||||
let (x, y) = (u * px as f32, v * py as f32);
|
||||
let (ix, iy) = (x.floor() as i32, y.floor() as i32);
|
||||
let mut r = Vor { f1: f32::MAX, f2: f32::MAX, id1: 0.0, id2: 0.0, dx: 0.0, dy: 0.0 };
|
||||
for dy in -1..=1 {
|
||||
for dx in -1..=1 {
|
||||
let (cx, cy) = (ix.wrapping_add(dx), iy.wrapping_add(dy));
|
||||
let (wx, wy) = (cx.rem_euclid(px), cy.rem_euclid(py));
|
||||
let fx = cx as f32 + 0.5 + (rnd(wx, wy, seed) - 0.5) * jitter;
|
||||
let fy = cy as f32 + 0.5 + (rnd(wx, wy, seed.wrapping_add(77)) - 0.5) * jitter;
|
||||
let d = metric.dist(fx - x, fy - y);
|
||||
let id = rnd(wx, wy, id_seed.wrapping_add(999));
|
||||
if d < r.f1 {
|
||||
r.f2 = r.f1;
|
||||
r.id2 = r.id1;
|
||||
r.f1 = d;
|
||||
r.id1 = id;
|
||||
r.dx = fx - x;
|
||||
r.dy = fy - y;
|
||||
} else if d < r.f2 {
|
||||
r.f2 = d;
|
||||
r.id2 = id;
|
||||
}
|
||||
}
|
||||
}
|
||||
let k = std::f32::consts::FRAC_1_SQRT_2;
|
||||
r.f1 = (r.f1 * k).clamp(0.0, 1.0);
|
||||
r.f2 = (r.f2 * k).clamp(0.0, 1.0);
|
||||
r
|
||||
}
|
||||
|
||||
/// Voronoi "Style": 0 F1, 1 random colour, 2 edge, 3 F2, 4 F2-F1, 5 F1*F2, 6 F1/F2.
|
||||
/// `thick` is the edge thickness, `round` rounds the edge profile (0 = linear).
|
||||
pub fn voronoi_style(r: &Vor, style: u32, thick: f32, round: f32) -> f32 {
|
||||
match style {
|
||||
1 => r.id1,
|
||||
2 => {
|
||||
let e = ((r.f2 - r.f1) / thick.max(1e-3)).clamp(0.0, 1.0);
|
||||
e + (e * e * (3.0 - 2.0 * e) - e) * round.clamp(0.0, 1.0)
|
||||
}
|
||||
3 => r.f2,
|
||||
4 => ((r.f2 - r.f1) * 2.0).clamp(0.0, 1.0),
|
||||
5 => (r.f1 * r.f2 * 3.0).clamp(0.0, 1.0),
|
||||
6 => (r.f1 / r.f2.max(1e-4)).clamp(0.0, 1.0),
|
||||
_ => r.f1,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
//! Cell and spot looks as point functions of (u, v), tileable with period 1: [`Cells`] (four styles),
|
||||
//! [`Crystal`], [`VoronoiFractal`] (one Voronoi level or a fractal sum of several), [`BnwSpots`] and
|
||||
//! [`GaussianSpots`]. Callers that warp the plane pass warped coordinates.
|
||||
|
||||
use super::{Metric, Vor, fbm, perlin, rnd, smoothstep as smooth, spots, voronoi_ext, voronoi_gen, voronoi_style};
|
||||
use crate::math;
|
||||
|
||||
/// Where a [`Cells`] style-1 cell takes its value from.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CellSource {
|
||||
/// The cell's own random id.
|
||||
Random,
|
||||
/// A value re-rolled per cell with its own seed.
|
||||
Pseudorandom(u32),
|
||||
}
|
||||
|
||||
/// Cellular noise: 0 soft cells, 1 flat cells, 2 cell borders, 3 cells with a hardness falloff.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Cells {
|
||||
pub style: u32,
|
||||
/// Cells per side.
|
||||
pub scale: i32,
|
||||
/// Cells down the texture; `scale` unless the cells are kept square on a non-square texture.
|
||||
pub rows: i32,
|
||||
pub seed: u32,
|
||||
pub jitter: f32,
|
||||
pub luminance_random: f32,
|
||||
pub edge_width: f32,
|
||||
pub hardness: f32,
|
||||
pub source: CellSource,
|
||||
/// The node's extra outputs: 0 the style's look, 1 the cell id map, 2 the distance to the centre, 3 the borders.
|
||||
pub output: u32,
|
||||
}
|
||||
|
||||
impl Cells {
|
||||
pub fn new(style: u32, scale: i32, seed: u32) -> Cells {
|
||||
Cells {
|
||||
style,
|
||||
scale,
|
||||
rows: scale,
|
||||
seed,
|
||||
jitter: 1.0,
|
||||
luminance_random: 0.0,
|
||||
edge_width: 0.25,
|
||||
hardness: 2.0,
|
||||
source: CellSource::Random,
|
||||
output: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value(&self, u: f32, v: f32) -> f32 {
|
||||
self.value_with(u, v, None)
|
||||
}
|
||||
|
||||
/// The value, with `image(u, v)` (a grey value at the cell centre) as the flat cells' value where given.
|
||||
pub fn value_with(&self, u: f32, v: f32, image: Option<&dyn Fn(f32, f32) -> f32>) -> f32 {
|
||||
let p = self.scale;
|
||||
let vr = voronoi_ext(u, v, p, self.rows, self.seed, self.jitter);
|
||||
let cell_val = || match (image, self.source) {
|
||||
(Some(img), _) => img(u + vr.dx / p as f32, v + vr.dy / p as f32),
|
||||
(None, CellSource::Pseudorandom(pseed)) => rnd(
|
||||
(((u + vr.dx / p as f32) * p as f32).floor()) as i32,
|
||||
(((v + vr.dy / p as f32) * p as f32).floor()) as i32,
|
||||
pseed.wrapping_add(4242),
|
||||
),
|
||||
(None, CellSource::Random) => vr.id1,
|
||||
};
|
||||
match self.output {
|
||||
1 => return vr.id1,
|
||||
2 => return vr.f1,
|
||||
3 => return smooth(0.0, self.edge_width, vr.f2 - vr.f1),
|
||||
_ => {}
|
||||
}
|
||||
match self.style {
|
||||
0 => (1.0 - vr.f1) * (1.0 - self.luminance_random * vr.id1),
|
||||
1 => cell_val(),
|
||||
2 => smooth(0.0, self.edge_width, vr.f2 - vr.f1),
|
||||
_ => vr.id1 * (1.0 - math::powf(vr.f1, self.hardness)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Faceted crystal cells: 0 cone facets, 1 lit planar facets.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Crystal {
|
||||
pub style: u32,
|
||||
pub scale: i32,
|
||||
pub seed: u32,
|
||||
}
|
||||
|
||||
impl Crystal {
|
||||
pub fn value(&self, u: f32, v: f32) -> f32 {
|
||||
let p = self.scale;
|
||||
let vr = voronoi_ext(u, v, p, p, self.seed, 1.0);
|
||||
let l = (vr.dx * vr.dx + vr.dy * vr.dy).sqrt().max(1e-4);
|
||||
let facet = if self.style == 0 { 1.0 - vr.f1 } else { 0.5 + 0.5 * ((vr.dx / l) * 0.6 + (vr.dy / l) * 0.8) };
|
||||
let edge = smooth(0.0, 0.08, vr.f2 - vr.f1).max(0.2);
|
||||
(vr.id1 * 0.55 + facet * 0.45) * edge
|
||||
}
|
||||
}
|
||||
|
||||
/// Voronoi with a style, metric, distortion and (as a fractal) several levels summed, maxed or min-ed.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct VoronoiFractal {
|
||||
scale: i32,
|
||||
seed: u32,
|
||||
jitter: f32,
|
||||
style: u32,
|
||||
aspect: f32,
|
||||
offset: (f32, f32),
|
||||
distortion: f32,
|
||||
distortion_scale: i32,
|
||||
metric: Metric,
|
||||
thickness: f32,
|
||||
rounded: f32,
|
||||
distance_scale: f32,
|
||||
id_seed: u32,
|
||||
opacity: f32,
|
||||
blend: u32,
|
||||
fractal: bool,
|
||||
/// (cells, amplitude) per level.
|
||||
levels: Vec<(i32, f32)>,
|
||||
norm: f32,
|
||||
}
|
||||
|
||||
/// The settings of a [`VoronoiFractal`], as the node clamps them.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct VoronoiSettings {
|
||||
pub scale: i32,
|
||||
pub seed: u32,
|
||||
pub jitter: f32,
|
||||
/// [`voronoi_style`] style.
|
||||
pub style: u32,
|
||||
pub aspect: f32,
|
||||
pub offset: (f32, f32),
|
||||
pub distortion: f32,
|
||||
pub distortion_scale: i32,
|
||||
pub metric: Metric,
|
||||
pub thickness: f32,
|
||||
pub rounded: f32,
|
||||
pub distance_scale: f32,
|
||||
/// Seed of the cell ids (usually `seed`).
|
||||
pub id_seed: u32,
|
||||
/// Fractal only: levels, roughness, lacunarity, opacity of the upper levels, blend (0 sum, 1 max, 2 min).
|
||||
pub min_level: u32,
|
||||
pub max_level: u32,
|
||||
pub roughness: f32,
|
||||
pub lacunarity: f32,
|
||||
pub opacity: f32,
|
||||
pub blend: u32,
|
||||
}
|
||||
|
||||
impl VoronoiSettings {
|
||||
/// The node's defaults.
|
||||
pub fn new(scale: i32, seed: u32) -> VoronoiSettings {
|
||||
VoronoiSettings {
|
||||
scale,
|
||||
seed,
|
||||
jitter: 1.0,
|
||||
style: 0,
|
||||
aspect: 1.0,
|
||||
offset: (0.0, 0.0),
|
||||
distortion: 0.0,
|
||||
distortion_scale: 3,
|
||||
metric: Metric::from_index(0, 2.0),
|
||||
thickness: 0.25,
|
||||
rounded: 0.0,
|
||||
distance_scale: 1.0,
|
||||
id_seed: seed,
|
||||
min_level: 0,
|
||||
max_level: 3,
|
||||
roughness: 0.5,
|
||||
lacunarity: 2.0,
|
||||
opacity: 1.0,
|
||||
blend: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl VoronoiFractal {
|
||||
/// One level (`fractal` false) or the levels `min_level..=max_level`.
|
||||
pub fn new(s: &VoronoiSettings, fractal: bool) -> VoronoiFractal {
|
||||
let (lo, hi) = (s.min_level, s.max_level.max(s.min_level));
|
||||
let p = s.scale;
|
||||
let levels: Vec<(i32, f32)> = if fractal {
|
||||
(lo..=hi)
|
||||
.map(|l| {
|
||||
(((p as f32) * math::powi(s.lacunarity, l as i32)).round().clamp(1.0, 512.0) as i32, math::powi(s.roughness, (l - lo) as i32))
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
vec![(p, 1.0)]
|
||||
};
|
||||
let norm: f32 = levels.iter().map(|l| l.1).sum::<f32>().max(1e-6);
|
||||
VoronoiFractal {
|
||||
scale: p,
|
||||
seed: s.seed,
|
||||
jitter: s.jitter,
|
||||
style: s.style,
|
||||
aspect: s.aspect,
|
||||
offset: s.offset,
|
||||
distortion: s.distortion,
|
||||
distortion_scale: s.distortion_scale,
|
||||
metric: s.metric,
|
||||
thickness: s.thickness,
|
||||
rounded: s.rounded,
|
||||
distance_scale: s.distance_scale,
|
||||
id_seed: s.id_seed,
|
||||
opacity: s.opacity,
|
||||
blend: s.blend,
|
||||
fractal,
|
||||
levels,
|
||||
norm,
|
||||
}
|
||||
}
|
||||
|
||||
fn one(&self, u: f32, v: f32, px: i32, sd: u32) -> f32 {
|
||||
let (seed, dist, dscale) = (self.seed, self.distortion, self.distortion_scale);
|
||||
let py = ((px as f32 * self.aspect).round().max(1.0)) as i32;
|
||||
let (u, v) = (u + self.offset.0, v + self.offset.1);
|
||||
let (u, v) = if dist > 0.0 {
|
||||
(
|
||||
u + (perlin(u, v, dscale, dscale, seed.wrapping_add(5)) - 0.5) * dist * 0.3,
|
||||
v + (perlin(u, v, dscale, dscale, seed.wrapping_add(6)) - 0.5) * dist * 0.3,
|
||||
)
|
||||
} else {
|
||||
(u, v)
|
||||
};
|
||||
let r: Vor = voronoi_gen(u, v, px, py, sd, self.id_seed.wrapping_add(sd.wrapping_sub(seed)), self.jitter, self.metric);
|
||||
(voronoi_style(&r, self.style, self.thickness, self.rounded) * self.distance_scale).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
pub fn value(&self, u: f32, v: f32) -> f32 {
|
||||
if !self.fractal {
|
||||
return self.one(u, v, self.scale, self.seed);
|
||||
}
|
||||
let (blend, opac) = (self.blend, self.opacity);
|
||||
let mut acc: f32 = if blend == 2 { 1.0 } else { 0.0 };
|
||||
for (i, (px, amp)) in self.levels.iter().enumerate() {
|
||||
let val = self.one(u, v, *px, self.seed.wrapping_add((i as u32).wrapping_mul(131)));
|
||||
match blend {
|
||||
1 => acc = acc.max(val * if i == 0 { 1.0 } else { opac }),
|
||||
2 => acc = acc.min(1.0 - (1.0 - val) * if i == 0 { 1.0 } else { opac }),
|
||||
_ => acc += amp * val * if i == 0 { 1.0 } else { opac },
|
||||
}
|
||||
}
|
||||
if blend == 0 { acc / self.norm } else { acc }.clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Black-and-white spots: 0 large round, 1 bigger, 2 small grainy spots.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct BnwSpots {
|
||||
pub style: u32,
|
||||
pub scale: i32,
|
||||
pub seed: u32,
|
||||
}
|
||||
|
||||
impl BnwSpots {
|
||||
pub fn value(&self, u: f32, v: f32) -> f32 {
|
||||
self.value_warped(u, v, (u, v))
|
||||
}
|
||||
|
||||
/// The spots at the warped point `(a, b)`; the grain of style 2 stays at the unwarped `(u, v)`.
|
||||
pub fn value_warped(&self, u: f32, v: f32, (a, b): (f32, f32)) -> f32 {
|
||||
let (var, p, seed) = (self.style, self.scale, self.seed);
|
||||
let grain = if var >= 2 { (fbm(u, v, p.wrapping_mul(4), p.wrapping_mul(4), 3, 0.5, seed.wrapping_add(5), 0) - 0.5) * 0.25 } else { 0.0 };
|
||||
spots(
|
||||
a,
|
||||
b,
|
||||
p,
|
||||
p,
|
||||
seed,
|
||||
|id| {
|
||||
let rad = match var {
|
||||
0 => 0.18 + 0.5 * id * id,
|
||||
1 => 0.3 + 0.55 * id,
|
||||
_ => 0.08 + 0.3 * id,
|
||||
};
|
||||
(rad * 0.8, rad)
|
||||
},
|
||||
grain,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Soft gaussian-like bumps of varying size.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct GaussianSpots {
|
||||
pub scale: i32,
|
||||
pub seed: u32,
|
||||
/// 0.05..1.
|
||||
pub size: f32,
|
||||
/// 0..1.
|
||||
pub size_variation: f32,
|
||||
}
|
||||
|
||||
impl GaussianSpots {
|
||||
pub fn value(&self, u: f32, v: f32) -> f32 {
|
||||
let (size, var) = (self.size, self.size_variation);
|
||||
// spots() blends smoothly from 1 to 0 between the inner and outer radius, i.e. a gaussian-like bump
|
||||
spots(
|
||||
u,
|
||||
v,
|
||||
self.scale,
|
||||
self.scale,
|
||||
self.seed,
|
||||
|id| {
|
||||
let r = size * 0.55 * (1.0 - var + var * id);
|
||||
(0.0, r.max(0.02))
|
||||
},
|
||||
0.0,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
//! Geometric pattern looks as point functions of (u, v), tileable with period 1: [`TriangleGrid`] (a simple
|
||||
//! split-square grid and a jittered triangulated lattice), [`Weave`], [`WeaveGenerator`] and [`Starburst`].
|
||||
|
||||
use super::{rnd, smoothstep as smooth, wrem};
|
||||
use crate::math;
|
||||
use std::f32::consts::TAU;
|
||||
|
||||
fn lerp(a: f32, b: f32, t: f32) -> f32 {
|
||||
a + (b - a) * t
|
||||
}
|
||||
|
||||
/// A grid of triangles: each square split along its diagonal, with a random value per triangle and soft borders.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct TriangleGrid {
|
||||
pub count: i32,
|
||||
pub border: f32,
|
||||
pub variation: f32,
|
||||
pub seed: u32,
|
||||
}
|
||||
|
||||
impl TriangleGrid {
|
||||
// 0.7071 (not FRAC_1_SQRT_2) keeps the node's output bit-identical to before the extraction
|
||||
#[allow(clippy::approx_constant)]
|
||||
pub fn value(&self, u: f32, v: f32) -> f32 {
|
||||
let (c, bw, var, seed) = (self.count, self.border, self.variation, self.seed);
|
||||
let (x, y) = (u * c as f32, v * c as f32);
|
||||
let (ix, iy) = (x.floor(), y.floor());
|
||||
let (fx, fy) = (x - ix, y - iy);
|
||||
let tri = (fx + fy >= 1.0) as u32;
|
||||
let d = fx.min(fy).min(1.0 - fx).min(1.0 - fy).min((fx + fy - 1.0).abs() * 0.7071);
|
||||
let id = rnd(wrem(ix as i32, c), wrem(iy as i32, c), seed.wrapping_add(tri * 131));
|
||||
(1.0 - var + var * id) * smooth(0.0, bw.max(1e-4), d)
|
||||
}
|
||||
}
|
||||
|
||||
/// A jittered lattice cut into triangles: heights interpolated over each triangle, a value per triangle or the
|
||||
/// distance to the edges; optional thin lines along the edges.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct TriangleLattice {
|
||||
pub nx: i32,
|
||||
pub ny: i32,
|
||||
/// Jitter amplitude in grid units.
|
||||
pub amp: f32,
|
||||
pub quincunx: (f32, f32),
|
||||
pub height_random: f32,
|
||||
/// 0 all the same diagonal, 1 alternating, 2 random.
|
||||
pub triangulation: i32,
|
||||
/// 0 heights, 1 a value per triangle, 2 the distance to the edges.
|
||||
pub output: i32,
|
||||
pub line_thickness: f32,
|
||||
pub line_color: f32,
|
||||
pub line_background: f32,
|
||||
pub lines: bool,
|
||||
pub seed: u32,
|
||||
}
|
||||
|
||||
impl TriangleLattice {
|
||||
/// Jittered lattice point (i, j) in grid units and its height; indices wrap so the pattern tiles.
|
||||
fn vert(&self, i: i32, j: i32) -> ([f32; 2], f32) {
|
||||
let (seed, amp) = (self.seed, self.amp);
|
||||
let (qx, qy) = self.quincunx;
|
||||
let (wi, wj) = (wrem(i, self.nx), wrem(j, self.ny));
|
||||
let jx = (rnd(wi, wj, seed) - 0.5) * 2.0 * amp;
|
||||
let jy = (rnd(wi, wj, seed.wrapping_add(7919)) - 0.5) * 2.0 * amp;
|
||||
let sh = if j.rem_euclid(2) == 1 { qx } else { 0.0 };
|
||||
let sv = if i.rem_euclid(2) == 1 { qy } else { 0.0 };
|
||||
let h = 0.5 + (rnd(wi, wj, seed.wrapping_add(104729)) - 0.5) * self.height_random;
|
||||
([i as f32 + jx + sh * 0.5, j as f32 + jy + sv * 0.5], h)
|
||||
}
|
||||
|
||||
pub fn value(&self, u: f32, v: f32) -> f32 {
|
||||
let (nx, ny, seed, hr) = (self.nx, self.ny, self.seed, self.height_random);
|
||||
let (x, y) = (u * nx as f32, v * ny as f32);
|
||||
let (ci, cj) = (x.floor() as i32, y.floor() as i32);
|
||||
let mut best = (f32::MAX, 0.0f32, 0.0f32);
|
||||
for dj in -1..=1 {
|
||||
for di in -1..=1 {
|
||||
let (i, j) = (ci.wrapping_add(di), cj.wrapping_add(dj));
|
||||
let (wi, wj) = (wrem(i, nx), wrem(j, ny));
|
||||
let alt = match self.triangulation {
|
||||
1 => i.wrapping_add(j) & 1,
|
||||
2 => (rnd(wi, wj, seed.wrapping_add(31)) > 0.5) as i32,
|
||||
_ => 0,
|
||||
};
|
||||
let (a, ha) = self.vert(i, j);
|
||||
let (b, hb) = self.vert(i.wrapping_add(1), j);
|
||||
let (c, hc) = self.vert(i, j.wrapping_add(1));
|
||||
let (d, hd) = self.vert(i.wrapping_add(1), j.wrapping_add(1));
|
||||
let tris: [([[f32; 2]; 3], [f32; 3]); 2] = if alt == 0 {
|
||||
[([a, b, d], [ha, hb, hd]), ([a, d, c], [ha, hd, hc])]
|
||||
} else {
|
||||
[([a, b, c], [ha, hb, hc]), ([b, d, c], [hb, hd, hc])]
|
||||
};
|
||||
for (t, (p, hs)) in tris.iter().enumerate() {
|
||||
let det = (p[1][1] - p[2][1]) * (p[0][0] - p[2][0]) + (p[2][0] - p[1][0]) * (p[0][1] - p[2][1]);
|
||||
if det.abs() < 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let l0 = ((p[1][1] - p[2][1]) * (x - p[2][0]) + (p[2][0] - p[1][0]) * (y - p[2][1])) / det;
|
||||
let l1 = ((p[2][1] - p[0][1]) * (x - p[2][0]) + (p[0][0] - p[2][0]) * (y - p[2][1])) / det;
|
||||
let l2 = 1.0 - l0 - l1;
|
||||
let m = l0.min(l1).min(l2);
|
||||
if m < -1e-5 {
|
||||
continue;
|
||||
}
|
||||
// distance to the nearest triangle edge in grid units
|
||||
let mut de = f32::MAX;
|
||||
for (e0, e1) in [(p[0], p[1]), (p[1], p[2]), (p[2], p[0])] {
|
||||
let (ex, ey) = (e1[0] - e0[0], e1[1] - e0[1]);
|
||||
let len = (ex * ex + ey * ey).sqrt().max(1e-9);
|
||||
de = de.min(((x - e0[0]) * ey - (y - e0[1]) * ex).abs() / len);
|
||||
}
|
||||
let tid = rnd(wi, wj, seed.wrapping_add(555 + t as u32 * 13 + alt as u32 * 3));
|
||||
let val = match self.output {
|
||||
1 => 0.5 + (tid - 0.5) * hr,
|
||||
2 => (de * 2.5).min(1.0),
|
||||
_ => l0 * hs[0] + l1 * hs[1] + l2 * hs[2],
|
||||
};
|
||||
let cand = (-m, val, de);
|
||||
if cand.0 < best.0 {
|
||||
best = cand;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let (val, de) = (best.1, best.2);
|
||||
let th = self.line_thickness;
|
||||
if self.lines && th > 0.0 {
|
||||
let w = th * 6.0;
|
||||
let k = 1.0 - smooth(w * 0.5, w, de);
|
||||
lerp(lerp(val, self.line_background, 0.0), self.line_color, k)
|
||||
} else {
|
||||
val
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Woven threads over and under each other; `count` is even so the pattern wraps.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Weave {
|
||||
pub count: f32,
|
||||
/// Thread width 0.1..1.
|
||||
pub width: f32,
|
||||
}
|
||||
|
||||
impl Weave {
|
||||
pub fn value(&self, u: f32, v: f32) -> f32 {
|
||||
let (cnt, wd) = (self.count, self.width);
|
||||
let (x, y) = (u * cnt, v * cnt);
|
||||
let (i, j) = (x.floor() as i32, y.floor() as i32);
|
||||
let (fx, fy) = (x - i as f32, y - j as f32);
|
||||
let hv = (1.0 - ((2.0 * fx - 1.0).abs() / wd).clamp(0.0, 1.0)).sqrt();
|
||||
let hh = (1.0 - ((2.0 * fy - 1.0).abs() / wd).clamp(0.0, 1.0)).sqrt();
|
||||
if i.wrapping_add(j) & 1 == 0 { hv.max(0.5 * hh) } else { hh.max(0.5 * hv) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Woven threads in slots with gaps between them.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct WeaveGenerator {
|
||||
/// Slots per side.
|
||||
pub nx: f32,
|
||||
pub ny: f32,
|
||||
/// How far a thread dips where it passes under its neighbour, 0..1.
|
||||
pub shape: f32,
|
||||
pub gap: (f32, f32),
|
||||
/// The node's extra outputs: 0 the weave, 1 the horizontal threads, 2 the vertical threads, 3 all threads (masks).
|
||||
pub output: u32,
|
||||
}
|
||||
|
||||
impl WeaveGenerator {
|
||||
/// `tile` repeats of a weave of `weave` threads.
|
||||
pub fn new(tile: (i32, i32), weave: i32, shape: f32, gap: (f32, f32)) -> WeaveGenerator {
|
||||
WeaveGenerator {
|
||||
nx: tile.0.wrapping_mul(weave).wrapping_mul(2) as f32,
|
||||
ny: tile.1.wrapping_mul(weave).wrapping_mul(2) as f32,
|
||||
shape,
|
||||
gap,
|
||||
output: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value(&self, u: f32, v: f32) -> f32 {
|
||||
let (nx, ny, shape) = (self.nx, self.ny, self.shape);
|
||||
let (gx, gy) = self.gap;
|
||||
let (nxi, nyi) = (nx as i32, ny as i32);
|
||||
let (x, y) = (u * nx, v * ny);
|
||||
let (i, j) = (x.floor() as i32, y.floor() as i32);
|
||||
let (fx, fy) = (x - i as f32, y - j as f32);
|
||||
let (i, j) = (wrem(i, nxi), wrem(j, nyi));
|
||||
let in_gx = fx < gx * 0.5 || fx > 1.0 - gx * 0.5;
|
||||
let in_gy = fy < gy * 0.5 || fy > 1.0 - gy * 0.5;
|
||||
let thread = !in_gx && !in_gy;
|
||||
let horizontal = i.wrapping_add(j) & 1 == 0;
|
||||
match self.output {
|
||||
1 => return (thread && horizontal) as u32 as f32,
|
||||
2 => return (thread && !horizontal) as u32 as f32,
|
||||
3 => return thread as u32 as f32,
|
||||
_ => {}
|
||||
}
|
||||
if in_gx && in_gy {
|
||||
return 0.0;
|
||||
}
|
||||
if in_gx || in_gy {
|
||||
return 0.5;
|
||||
}
|
||||
// a thread runs along the slot; it dips towards both ends where it passes under its neighbour
|
||||
let along = if horizontal { fx } else { fy };
|
||||
let e = (along - 0.5).abs() * 2.0;
|
||||
if shape <= 0.0 { 1.0 } else { 1.0 - 0.5 * smooth(1.0 - shape, 1.0, e) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Star-like rays, one star per cell.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Starburst {
|
||||
pub count: i32,
|
||||
pub rays: f32,
|
||||
pub sharpness: f32,
|
||||
pub size: f32,
|
||||
pub rotation: f32,
|
||||
pub rotation_random: f32,
|
||||
pub seed: u32,
|
||||
}
|
||||
|
||||
impl Starburst {
|
||||
pub fn value(&self, u: f32, v: f32) -> f32 {
|
||||
let c = self.count;
|
||||
let (x, y) = (u * c as f32, v * c as f32);
|
||||
let (ix, iy) = (x.floor(), y.floor());
|
||||
let (dx, dy) = (x - ix - 0.5, y - iy - 0.5);
|
||||
let r = (dx * dx + dy * dy).sqrt();
|
||||
let off = self.rotation + self.rotation_random * rnd(wrem(ix as i32, c), wrem(iy as i32, c), self.seed);
|
||||
let a = (math::atan2(dy, dx) / TAU + off) * self.rays;
|
||||
let ray = 1.0 - (2.0 * (a - a.floor()) - 1.0).abs();
|
||||
math::powf(ray, self.sharpness) * (1.0 - r * 2.0 / self.size).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,94 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Data-parallel helpers for the hot paths (per-pixel passes, `crate::tex::par_map`, and the paint stack's stamping
|
||||
//! and tile compositing, which uses them from here), on rayon.
|
||||
//!
|
||||
//! - Work runs on the pool of the calling thread's [`crate::context::EvalContext`] when it names one, else on the pool
|
||||
//! the caller is in (rayon's global pool outside any). The caller's context is current on every thread that runs a
|
||||
//! piece, so cancel checks and profile spans inside the pieces see it. Work that is a single run is not handed to a
|
||||
//! pool at all: the calling thread does it.
|
||||
//! - Items are split at fixed indices (runs of a given length), never by thread count, and each piece is handed to
|
||||
//! whichever thread is free, so uneven items (tiles with many dabs, tiles with none) balance.
|
||||
//!
|
||||
//! Results are deterministic: each item is visited exactly once with its index, and what a visit does may depend
|
||||
//! only on its item and index, never on which thread runs it or when.
|
||||
//!
|
||||
//! Unlike `crate::tex::par_map` these never stop early for a cancelled evaluation, so callers always get complete
|
||||
//! results.
|
||||
|
||||
use rayon::prelude::*;
|
||||
|
||||
/// Threads besides the caller that a call may use: the pool's threads less one.
|
||||
pub fn helpers() -> usize {
|
||||
crate::context::with_current(|ec| match ec.and_then(|ec| ec.pool.as_ref()) {
|
||||
Some(pool) => pool.current_num_threads(),
|
||||
None => rayon::current_num_threads(),
|
||||
})
|
||||
.saturating_sub(1)
|
||||
}
|
||||
|
||||
/// Calls `f(index, item)` for every item, spread over the available threads.
|
||||
pub fn for_each_mut<T: Send, F: Fn(usize, &mut T) + Sync>(items: &mut [T], f: F) {
|
||||
let run = items.len().div_ceil((helpers() + 1) * 4).max(1);
|
||||
for_each_run_mut(items, run, |first, chunk| {
|
||||
for (i, it) in chunk.iter_mut().enumerate() {
|
||||
f(first + i, it);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Calls `f(first_index, run)` for consecutive runs of at most `run` items covering `items` (split at multiples of
|
||||
/// `run`), spread over the available threads.
|
||||
pub fn for_each_run_mut<T: Send, F: Fn(usize, &mut [T]) + Sync>(items: &mut [T], run: usize, f: F) {
|
||||
let run = run.max(1);
|
||||
if items.len() <= run {
|
||||
// one run: no other thread to wake
|
||||
if !items.is_empty() {
|
||||
f(0, items);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let ec = crate::context::current();
|
||||
let ec = ec.as_ref();
|
||||
crate::context::in_pool(ec, || {
|
||||
items.par_chunks_mut(run).enumerate().for_each(|(ri, chunk)| crate::context::scoped_opt(ec, || f(ri * run, chunk)));
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn visits_every_item_once_with_its_index() {
|
||||
for n in [0, 1, 2, 7, 1000] {
|
||||
let mut v = vec![0usize; n];
|
||||
super::for_each_mut(&mut v, |i, x| *x += i + 1);
|
||||
assert!(v.iter().enumerate().all(|(i, &x)| x == i + 1), "{n} items");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_cover_the_items_in_order_and_respect_their_length() {
|
||||
for (n, run) in [(10, 3), (10, 10), (10, 64), (4097, 4096), (5, 0)] {
|
||||
let mut v = vec![usize::MAX; n];
|
||||
super::for_each_run_mut(&mut v, run, |first, chunk| {
|
||||
assert!(chunk.len() <= run.max(1));
|
||||
chunk.iter_mut().enumerate().for_each(|(i, x)| *x = first + i);
|
||||
});
|
||||
assert!(v.iter().enumerate().all(|(i, &x)| x == i), "{n} items in runs of {run}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pieces_see_the_callers_context() {
|
||||
use crate::context::{Cancel, EvalContext, cancelled, scoped};
|
||||
let ec = EvalContext::with_cancel(Cancel::new());
|
||||
ec.cancel.cancel();
|
||||
let mut v = vec![false; 64];
|
||||
scoped(&ec, || super::for_each_run_mut(&mut v, 1, |_, x| x[0] = cancelled()));
|
||||
assert!(v.iter().all(|x| *x), "every piece must see the cancelled context");
|
||||
let pool = std::sync::Arc::new(rayon::ThreadPoolBuilder::new().num_threads(3).build().unwrap());
|
||||
let ec = EvalContext { pool: Some(pool), ..EvalContext::default() };
|
||||
let mut threads = vec![0usize; 64];
|
||||
scoped(&ec, || super::for_each_run_mut(&mut threads, 1, |_, x| x[0] = rayon::current_num_threads()));
|
||||
assert!(threads.iter().all(|n| *n == 3), "pieces run on the context's pool");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Setting a graph's parameters by name, for hosts that render a graph with values of their own: an exposed parameter
|
||||
//! by its label ([`Graph::apply_params`]), or an `input_value` node by its `name` (the values function graphs read
|
||||
//! through `f_graph_input`).
|
||||
|
||||
use crate::graph::Graph;
|
||||
|
||||
/// The keys of an `input_value` node's value: one number, or up to four lanes.
|
||||
const LANES: [&str; 4] = ["x", "y", "z", "w"];
|
||||
|
||||
impl Graph {
|
||||
/// Sets the parameter `name` to `values`: the exposed parameter labelled `name` (one value, clamped to its range),
|
||||
/// else every `input_value` node whose `name` is `name` (one value sets `v`; two to four set the lanes `x y z w`).
|
||||
/// Non-finite values are refused. Errors name what is wrong; the graph is unchanged then.
|
||||
pub fn set_param(&mut self, name: &str, values: &[f32]) -> Result<(), String> {
|
||||
if values.is_empty() || values.len() > LANES.len() {
|
||||
return Err(format!("{name}: give one to four values, not {}", values.len()));
|
||||
}
|
||||
if values.iter().any(|v| !v.is_finite()) {
|
||||
return Err(format!("{name}: values must be finite numbers"));
|
||||
}
|
||||
if let Some(e) = self.exposed.iter().find(|e| e.label == name).cloned() {
|
||||
let [v] = values else { return Err(format!("{name}: an exposed parameter takes one value")) };
|
||||
let n = self.nodes.get_mut(&e.node).ok_or_else(|| format!("{name}: exposed node {} is missing", e.node))?;
|
||||
n.nums.insert(e.param.clone(), v.clamp(e.min.min(e.max), e.min.max(e.max)));
|
||||
return Ok(());
|
||||
}
|
||||
let ids: Vec<u32> =
|
||||
self.nodes.iter().filter(|(_, n)| n.kind == "input_value" && n.strs.get("name").is_some_and(|s| s == name)).map(|(id, _)| *id).collect();
|
||||
if ids.is_empty() {
|
||||
return Err(format!("no exposed parameter or input value named '{name}'"));
|
||||
}
|
||||
for id in ids {
|
||||
let Some(n) = self.nodes.get_mut(&id) else { continue };
|
||||
match values {
|
||||
[v] => {
|
||||
n.nums.insert("v".to_string(), *v);
|
||||
}
|
||||
lanes => {
|
||||
for (key, v) in LANES.iter().zip(lanes) {
|
||||
n.nums.insert((*key).to_string(), *v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Keeps only the graph outputs named in `names` (by identifier, as [`Graph::output_nodes`] gives them), so an
|
||||
/// evaluation computes nothing the others alone need. An output that a kept one reads from stays. Errors name an
|
||||
/// output the graph doesn't have.
|
||||
pub fn keep_outputs(&mut self, names: &[&str]) -> Result<(), String> {
|
||||
let have: Vec<String> = self.output_nodes().into_iter().map(|(_, ident, _)| ident).collect();
|
||||
if let Some(missing) = names.iter().find(|n| !have.iter().any(|h| h == *n)) {
|
||||
return Err(format!("no output '{missing}' (outputs: {})", have.join(", ")));
|
||||
}
|
||||
let keep = |ident: &str| names.contains(&ident);
|
||||
// an output node another kept output reads from stays too
|
||||
let roots: Vec<u32> = self.output_nodes().into_iter().filter(|(_, ident, _)| keep(ident)).map(|(_, _, id)| id).collect();
|
||||
let needed = crate::graph::reached(self, &roots);
|
||||
let drop: Vec<u32> = self.nodes.iter().filter(|(id, n)| n.kind == "output" && !needed.contains(id)).map(|(id, _)| *id).collect();
|
||||
for id in drop {
|
||||
self.nodes.remove(&id);
|
||||
}
|
||||
self.outputs.retain(|(name, _)| keep(name));
|
||||
let pins: Vec<String> = self.output_pins.keys().filter(|k| !keep(k)).cloned().collect();
|
||||
for k in pins {
|
||||
self.output_pins.remove(&k);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::graph::Graph;
|
||||
|
||||
const TEXT: &str = "size 8\nnode 1 input_value name=\"level\" type=0 v=0.25\nnode 2 color r=1 g=0 b=0\noutput lum 1\noutput red 2\n";
|
||||
|
||||
#[test]
|
||||
fn an_input_value_is_set_by_name_and_changes_the_render() {
|
||||
let mut g = Graph::parse(TEXT).unwrap();
|
||||
assert_eq!(g.evaluate(None).unwrap()["lum"].px[0][0], 0.25);
|
||||
g.set_param("level", &[0.75]).unwrap();
|
||||
assert_eq!(g.evaluate(None).unwrap()["lum"].px[0][0], 0.75);
|
||||
assert!(g.set_param("nothing", &[1.0]).unwrap_err().contains("nothing"));
|
||||
assert!(g.set_param("level", &[]).is_err());
|
||||
assert!(g.set_param("level", &[f32::NAN]).is_err());
|
||||
assert!(g.set_param("level", &[1.0; 5]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kept_outputs_are_the_only_ones_evaluated() {
|
||||
let mut g = Graph::parse(TEXT).unwrap();
|
||||
g.keep_outputs(&["red"]).unwrap();
|
||||
let out = g.evaluate(None).unwrap();
|
||||
assert_eq!(out.keys().collect::<Vec<_>>(), ["red"]);
|
||||
assert!(g.keep_outputs(&["blue"]).unwrap_err().contains("blue"));
|
||||
let mut m = Graph::parse(TEXT).unwrap();
|
||||
m.migrate_outputs();
|
||||
m.keep_outputs(&["lum"]).unwrap();
|
||||
assert_eq!(m.evaluate(None).unwrap().keys().collect::<Vec<_>>(), ["lum"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_output_a_kept_output_reads_is_not_dropped() {
|
||||
let text = "size 8\nnode 1 color r=1 g=0 b=0\nnode 2 output usage=\"basecolor\" identifier=\"mid\" in=@1\nnode 3 output usage=\"roughness\" identifier=\"last\" in=@2\nnode 4 output usage=\"metallic\" identifier=\"other\" in=@1\n";
|
||||
let mut g = Graph::parse(text).unwrap();
|
||||
g.keep_outputs(&["last"]).unwrap();
|
||||
assert!(!g.nodes.contains_key(&4), "an output nobody needs is dropped");
|
||||
let out = g.evaluate(None).expect("the kept output still has what it reads");
|
||||
// `mid` stays because `last` reads it, so it is evaluated and shows in the result as well
|
||||
assert_eq!(out.keys().collect::<Vec<_>>(), ["last", "mid"]);
|
||||
assert_eq!(out["last"].px[0], [1.0, 0.0, 0.0, 1.0]);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,498 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Dependency-free PNG codec: 8/16-bit gray, gray+alpha, RGB and RGBA encoding with filtering and DEFLATE
|
||||
//! compression; decoding of all standard formats to float RGBA (`decode`) or losslessly to raw samples (`decode_raw`).
|
||||
use crate::checksum::Crc32;
|
||||
use crate::deflate::{self, Level};
|
||||
|
||||
fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
|
||||
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
|
||||
out.extend_from_slice(kind);
|
||||
out.extend_from_slice(data);
|
||||
let mut crc = Crc32::new();
|
||||
crc.update(kind);
|
||||
crc.update(data);
|
||||
out.extend_from_slice(&crc.finish().to_be_bytes());
|
||||
}
|
||||
|
||||
/// Encode RGBA float pixels (0..1). `depth` must be 8 or 16 (anything else becomes 8).
|
||||
pub fn encode(w: usize, h: usize, px: &[[f32; 4]], depth: u8) -> Vec<u8> {
|
||||
let depth = if depth == 16 { 16 } else { 8 };
|
||||
let opaque = px.iter().all(|p| p[3] >= 0.9999);
|
||||
let ch = if opaque { 3 } else { 4 };
|
||||
let mut samples = Vec::with_capacity(w * h * ch * (depth / 8) as usize);
|
||||
for i in 0..w * h {
|
||||
let p = px.get(i).copied().unwrap_or([0.0; 4]);
|
||||
for c in p.iter().take(ch) {
|
||||
let v = c.clamp(0.0, 1.0);
|
||||
if depth == 16 {
|
||||
samples.extend_from_slice(&((v * 65535.0 + 0.5) as u16).to_be_bytes());
|
||||
} else {
|
||||
samples.push((v * 255.0 + 0.5) as u8);
|
||||
}
|
||||
}
|
||||
}
|
||||
encode_raw(w, h, if opaque { ColorType::Rgb } else { ColorType::Rgba }, depth, &samples, Level::Default)
|
||||
}
|
||||
|
||||
/// PNG colour types without palette.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ColorType {
|
||||
Gray,
|
||||
GrayAlpha,
|
||||
Rgb,
|
||||
Rgba,
|
||||
}
|
||||
|
||||
impl ColorType {
|
||||
pub fn channels(self) -> usize {
|
||||
match self {
|
||||
ColorType::Gray => 1,
|
||||
ColorType::GrayAlpha => 2,
|
||||
ColorType::Rgb => 3,
|
||||
ColorType::Rgba => 4,
|
||||
}
|
||||
}
|
||||
|
||||
/// The IHDR colour type code.
|
||||
fn code(self) -> u8 {
|
||||
match self {
|
||||
ColorType::Gray => 0,
|
||||
ColorType::GrayAlpha => 4,
|
||||
ColorType::Rgb => 2,
|
||||
ColorType::Rgba => 6,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_code(c: u8) -> Option<Self> {
|
||||
match c {
|
||||
0 => Some(ColorType::Gray),
|
||||
4 => Some(ColorType::GrayAlpha),
|
||||
2 => Some(ColorType::Rgb),
|
||||
6 => Some(ColorType::Rgba),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Raw image samples exactly as stored: row-major, interleaved channels, 16-bit samples big-endian.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RawImage {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub color: ColorType,
|
||||
/// 8 or 16.
|
||||
pub bit_depth: u8,
|
||||
pub samples: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Largest IDAT chunk written; big images are split over several.
|
||||
const IDAT_MAX: usize = 1 << 20;
|
||||
|
||||
/// Encode raw samples (row-major, interleaved, 16-bit big-endian). `bit_depth` is 8 or 16 (anything else becomes 8).
|
||||
/// Missing samples are written as zero, extra ones ignored. Each row gets the PNG filter with the smallest sum of
|
||||
/// absolute (signed) residuals, then the image is DEFLATE-compressed at `level`.
|
||||
pub fn encode_raw(w: usize, h: usize, color: ColorType, bit_depth: u8, samples: &[u8], level: Level) -> Vec<u8> {
|
||||
let depth = if bit_depth == 16 { 16 } else { 8 };
|
||||
let bpp = color.channels() * (depth / 8) as usize;
|
||||
let stride = w * bpp;
|
||||
let mut filtered = Vec::with_capacity(h * (stride + 1));
|
||||
let mut cur = vec![0u8; stride];
|
||||
let mut prev = vec![0u8; stride];
|
||||
let (mut trial, mut best) = (vec![0u8; stride], vec![0u8; stride]);
|
||||
for y in 0..h {
|
||||
let src = samples.get((y * stride).min(samples.len())..).unwrap_or(&[]);
|
||||
let n = src.len().min(stride);
|
||||
let (head, tail) = cur.split_at_mut(n);
|
||||
head.copy_from_slice(src.get(..n).unwrap_or(&[]));
|
||||
tail.fill(0);
|
||||
let (mut best_f, mut best_cost) = (0u8, u64::MAX);
|
||||
for f in 0..5u8 {
|
||||
filter_row(f, &cur, &prev, bpp, &mut trial);
|
||||
let cost = trial.iter().map(|&b| (b as i8).unsigned_abs() as u64).sum::<u64>();
|
||||
if cost < best_cost {
|
||||
(best_f, best_cost) = (f, cost);
|
||||
std::mem::swap(&mut trial, &mut best);
|
||||
}
|
||||
}
|
||||
filtered.push(best_f);
|
||||
filtered.extend_from_slice(&best);
|
||||
std::mem::swap(&mut cur, &mut prev);
|
||||
}
|
||||
let z = deflate::zlib_compress(&filtered, level);
|
||||
|
||||
let mut out = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
|
||||
let mut ihdr = Vec::new();
|
||||
ihdr.extend_from_slice(&(w as u32).to_be_bytes());
|
||||
ihdr.extend_from_slice(&(h as u32).to_be_bytes());
|
||||
ihdr.extend_from_slice(&[depth, color.code(), 0, 0, 0]);
|
||||
chunk(&mut out, b"IHDR", &ihdr);
|
||||
for part in z.chunks(IDAT_MAX) {
|
||||
chunk(&mut out, b"IDAT", part);
|
||||
}
|
||||
chunk(&mut out, b"IEND", &[]);
|
||||
out
|
||||
}
|
||||
|
||||
/// Apply PNG filter `f` (0 none, 1 sub, 2 up, 3 average, 4 Paeth) to `cur` given the previous row.
|
||||
/// `cur`, `prev` and `out` all have the row length.
|
||||
fn filter_row(f: u8, cur: &[u8], prev: &[u8], bpp: usize, out: &mut [u8]) {
|
||||
let predict = |a: u8, b: u8, c: u8| match f {
|
||||
0 => 0,
|
||||
1 => a,
|
||||
2 => b,
|
||||
3 => ((a as u16 + b as u16) / 2) as u8,
|
||||
_ => paeth(a, b, c),
|
||||
};
|
||||
// The first pixel has no left neighbour (a = c = 0).
|
||||
for ((o, &x), &b) in out.iter_mut().zip(cur).zip(prev).take(bpp) {
|
||||
*o = x.wrapping_sub(predict(0, b, 0));
|
||||
}
|
||||
// Then byte i is predicted from cur[i - bpp], prev[i] and prev[i - bpp].
|
||||
let rest = out.iter_mut().zip(cur).zip(prev).skip(bpp).zip(cur.iter().zip(prev));
|
||||
for (((o, &x), &b), (&a, &c)) in rest {
|
||||
*o = x.wrapping_sub(predict(a, b, c));
|
||||
}
|
||||
}
|
||||
|
||||
// ======================= decoder =======================
|
||||
use crate::tex::Tex;
|
||||
|
||||
/// DEFLATE decompression lives in [`crate::deflate`]; re-exported here because `png::inflate` is public API.
|
||||
pub use crate::deflate::inflate;
|
||||
|
||||
fn paeth(a: u8, b: u8, c: u8) -> u8 {
|
||||
let (ia, ib, ic) = (a as i32, b as i32, c as i32);
|
||||
let p = ia + ib - ic;
|
||||
let (pa, pb, pc) = ((p - ia).abs(), (p - ib).abs(), (p - ic).abs());
|
||||
if pa <= pb && pa <= pc {
|
||||
a
|
||||
} else if pb <= pc {
|
||||
b
|
||||
} else {
|
||||
c
|
||||
}
|
||||
}
|
||||
|
||||
/// The chunks of a PNG the decoders use.
|
||||
struct Parsed {
|
||||
w: usize,
|
||||
h: usize,
|
||||
depth: u8,
|
||||
ctype: u8,
|
||||
inter: u8,
|
||||
/// Channels per pixel (1 for palette).
|
||||
ch: usize,
|
||||
plte: Vec<u8>,
|
||||
trns: Vec<u8>,
|
||||
idat: Vec<u8>,
|
||||
}
|
||||
|
||||
fn parse(b: &[u8]) -> Result<Parsed, String> {
|
||||
if b.get(..8) != Some(b"\x89PNG\r\n\x1a\n".as_slice()) {
|
||||
return Err("not a PNG file".into());
|
||||
}
|
||||
let mut pos = 8;
|
||||
let (mut w, mut h, mut depth, mut ctype, mut inter) = (0usize, 0usize, 0u8, 0u8, 0u8);
|
||||
let mut plte: Vec<u8> = Vec::new();
|
||||
let mut trns: Vec<u8> = Vec::new();
|
||||
let mut idat: Vec<u8> = Vec::new();
|
||||
// Each chunk: 4-byte length, 4-byte type, data, 4-byte CRC. `pos <= b.len()` throughout, so `pos + 8` cannot
|
||||
// overflow; the 32-bit length can (on 32-bit targets), hence the checked sums.
|
||||
while let Some(&[l0, l1, l2, l3, k0, k1, k2, k3]) = b.get(pos..pos + 8) {
|
||||
let len = u32::from_be_bytes([l0, l1, l2, l3]) as usize;
|
||||
let kind = [k0, k1, k2, k3];
|
||||
let end = (pos + 8).checked_add(len).filter(|e| e.checked_add(4).is_some_and(|e4| e4 <= b.len())).ok_or("truncated chunk")?;
|
||||
let data = b.get(pos + 8..end).ok_or("truncated chunk")?;
|
||||
match &kind {
|
||||
b"IHDR" if data.len() >= 13 => {
|
||||
if let Some(&[w0, w1, w2, w3, h0, h1, h2, h3, d, c, _, _, i]) = data.get(..13) {
|
||||
w = u32::from_be_bytes([w0, w1, w2, w3]) as usize;
|
||||
h = u32::from_be_bytes([h0, h1, h2, h3]) as usize;
|
||||
(depth, ctype, inter) = (d, c, i);
|
||||
}
|
||||
}
|
||||
b"PLTE" => plte = data.to_vec(),
|
||||
b"tRNS" => trns = data.to_vec(),
|
||||
b"IDAT" => idat.extend_from_slice(data),
|
||||
b"IEND" => break,
|
||||
_ => {}
|
||||
}
|
||||
pos = end + 4;
|
||||
}
|
||||
if w == 0 || h == 0 || w > 16384 || h > 16384 {
|
||||
return Err("bad image size".into());
|
||||
}
|
||||
let ch = match (ctype, depth) {
|
||||
(0, 1 | 2 | 4 | 8 | 16) => 1,
|
||||
(2, 8 | 16) => 3,
|
||||
(3, 1 | 2 | 4 | 8) => 1,
|
||||
(4, 8 | 16) => 2,
|
||||
(6, 8 | 16) => 4,
|
||||
_ => return Err(format!("unsupported PNG format (colour type {ctype}, {depth}-bit)")),
|
||||
};
|
||||
if idat.len() < 6 {
|
||||
return Err("missing image data".into());
|
||||
}
|
||||
Ok(Parsed { w, h, depth, ctype, inter, ch, plte, trns, idat })
|
||||
}
|
||||
|
||||
/// One unfiltered Adam7 pass (or the whole image when not interlaced): pixel `(i, j)` of the pass lands at
|
||||
/// `(x0 + i * dx, y0 + j * dy)`; `img` holds `ph` rows of `stride` bytes.
|
||||
struct Pass {
|
||||
x0: usize,
|
||||
y0: usize,
|
||||
dx: usize,
|
||||
dy: usize,
|
||||
pw: usize,
|
||||
ph: usize,
|
||||
stride: usize,
|
||||
img: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Inflate the image data and undo the row filters of every pass.
|
||||
fn unfilter_passes(p: &Parsed) -> Result<Vec<Pass>, String> {
|
||||
let raw = inflate(p.idat.get(2..).ok_or("missing image data")?)?;
|
||||
let bits_pp = p.ch * p.depth as usize;
|
||||
let bpp = bits_pp.div_ceil(8).max(1);
|
||||
let layout: &[(usize, usize, usize, usize)] = if p.inter == 0 {
|
||||
&[(0, 0, 1, 1)]
|
||||
} else {
|
||||
&[(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)]
|
||||
};
|
||||
let mut passes = Vec::new();
|
||||
let mut off = 0usize;
|
||||
for &(x0, y0, dx, dy) in layout {
|
||||
if x0 >= p.w || y0 >= p.h {
|
||||
continue;
|
||||
}
|
||||
// w, h <= 16384 and at most 64 bits per pixel: these products stay below 2^31 even with a 32-bit usize.
|
||||
let pw = (p.w - x0).div_ceil(dx);
|
||||
let ph = (p.h - y0).div_ceil(dy);
|
||||
let stride = (pw * bits_pp).div_ceil(8);
|
||||
let need = ph * (stride + 1);
|
||||
let end = off.checked_add(need).ok_or("image data too short")?;
|
||||
let Some(data) = raw.get(off..end) else {
|
||||
return Err("image data too short".into());
|
||||
};
|
||||
let mut img = Vec::with_capacity(ph * stride);
|
||||
// The previous unfiltered row (zeros above the first one) and the row being unfiltered.
|
||||
let (mut up, mut cur) = (vec![0u8; stride], vec![0u8; stride]);
|
||||
for line in data.chunks_exact(stride + 1) {
|
||||
let Some((&f, src)) = line.split_first() else {
|
||||
return Err("image data too short".into());
|
||||
};
|
||||
unfilter_row(f, src, &up, bpp, &mut cur)?;
|
||||
img.extend_from_slice(&cur);
|
||||
std::mem::swap(&mut up, &mut cur);
|
||||
}
|
||||
off = end;
|
||||
passes.push(Pass { x0, y0, dx, dy, pw, ph, stride, img });
|
||||
}
|
||||
Ok(passes)
|
||||
}
|
||||
|
||||
/// Undo filter `f` on one row: `src` is the filtered row, `up` the unfiltered row above, all of `cur`'s length.
|
||||
fn unfilter_row(f: u8, src: &[u8], up: &[u8], bpp: usize, cur: &mut [u8]) -> Result<(), String> {
|
||||
// Byte i depends on byte i - bpp of this row (`left`) and of the row above (`upleft`): kept per byte of a pixel
|
||||
// (bpp <= 8), zero for the first pixel.
|
||||
let (mut left, mut upleft) = ([0u8; 8], [0u8; 8]);
|
||||
for ((cpx, spx), upx) in cur.chunks_mut(bpp).zip(src.chunks(bpp)).zip(up.chunks(bpp)) {
|
||||
for ((((o, &x), &u), l), ul) in cpx.iter_mut().zip(spx).zip(upx).zip(left.iter_mut()).zip(upleft.iter_mut()) {
|
||||
let (a, c) = (*l, *ul);
|
||||
let v = match f {
|
||||
0 => x,
|
||||
1 => x.wrapping_add(a),
|
||||
2 => x.wrapping_add(u),
|
||||
3 => x.wrapping_add(((a as u16 + u as u16) / 2) as u8),
|
||||
4 => x.wrapping_add(paeth(a, u, c)),
|
||||
_ => return Err("bad PNG filter".into()),
|
||||
};
|
||||
*o = v;
|
||||
*l = v;
|
||||
*ul = u;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `n` copies of `v`, or an error instead of an abort when the allocation is impossible (a 16384 x 16384 float image
|
||||
/// is 4 GiB, more than a 32-bit target can address).
|
||||
fn filled<T: Clone>(n: usize, v: T) -> Result<Vec<T>, String> {
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(n).map_err(|_| format!("image too large ({n} pixels or samples)"))?;
|
||||
out.resize(n, v);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Decode a PNG: gray, gray+alpha, RGB, RGBA and palette images (1-16 bit, tRNS palette alpha, Adam7 interlacing).
|
||||
pub fn decode(b: &[u8]) -> Result<Tex, String> {
|
||||
let p = parse(b)?;
|
||||
let (w, h, depth, ch) = (p.w, p.h, p.depth, p.ch);
|
||||
let maxv = ((1u32 << depth) - 1) as f32;
|
||||
let mut px = filled(w * h, [0.0f32; 4])?;
|
||||
for pass in unfilter_passes(&p)? {
|
||||
for (py, row) in pass.img.chunks_exact(pass.stride.max(1)).take(pass.ph).enumerate() {
|
||||
let sample = |idx: usize| -> u32 {
|
||||
match depth {
|
||||
16 => match row.get(idx * 2..idx * 2 + 2) {
|
||||
Some(&[hi, lo]) => u16::from_be_bytes([hi, lo]) as u32,
|
||||
_ => 0,
|
||||
},
|
||||
8 => row.get(idx).copied().unwrap_or(0) as u32,
|
||||
d => {
|
||||
let bit = idx * d as usize;
|
||||
let shift = 8 - d as usize - (bit % 8);
|
||||
row.get(bit / 8).map_or(0, |&byte| ((byte >> shift) & ((1u8 << d) - 1)) as u32)
|
||||
}
|
||||
}
|
||||
};
|
||||
for pxi in 0..pass.pw {
|
||||
let v = |k: usize| sample(pxi * ch + k) as f32 / maxv;
|
||||
let c = match p.ctype {
|
||||
0 => [v(0), v(0), v(0), 1.0],
|
||||
4 => [v(0), v(0), v(0), v(1)],
|
||||
2 => [v(0), v(1), v(2), 1.0],
|
||||
6 => [v(0), v(1), v(2), v(3)],
|
||||
_ => {
|
||||
let i = sample(pxi) as usize;
|
||||
let Some(&[r, g, b]) = p.plte.get(i * 3..i * 3 + 3) else {
|
||||
return Err("palette index out of range".into());
|
||||
};
|
||||
[r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, p.trns.get(i).map(|a| *a as f32 / 255.0).unwrap_or(1.0)]
|
||||
}
|
||||
};
|
||||
// The pass geometry keeps every pixel inside the image.
|
||||
if let Some(o) = px.get_mut((pass.y0 + py * pass.dy) * w + pass.x0 + pxi * pass.dx) {
|
||||
*o = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Tex { w, h, px })
|
||||
}
|
||||
|
||||
/// Decode an 8- or 16-bit gray, gray+alpha, RGB or RGBA PNG (interlaced or not) to its exact stored samples.
|
||||
/// Palette and 1/2/4-bit images are rejected; ancillary chunks (gamma, colour profiles, tRNS) are ignored.
|
||||
pub fn decode_raw(b: &[u8]) -> Result<RawImage, String> {
|
||||
let p = parse(b)?;
|
||||
let color = ColorType::from_code(p.ctype)
|
||||
.filter(|_| p.depth >= 8)
|
||||
.ok_or_else(|| format!("decode_raw: unsupported PNG format (colour type {}, {}-bit)", p.ctype, p.depth))?;
|
||||
let bpp = p.ch * (p.depth / 8) as usize;
|
||||
let mut samples = filled(p.w * p.h * bpp, 0u8)?;
|
||||
for pass in unfilter_passes(&p)? {
|
||||
for (py, row) in pass.img.chunks_exact(pass.stride.max(1)).take(pass.ph).enumerate() {
|
||||
let y = pass.y0 + py * pass.dy;
|
||||
if pass.dx == 1 {
|
||||
if let Some(dst) = samples.get_mut(y * p.w * bpp..(y + 1) * p.w * bpp) {
|
||||
dst.copy_from_slice(row);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
for (i, px) in row.chunks_exact(bpp).enumerate() {
|
||||
let o = (y * p.w + pass.x0 + i * pass.dx) * bpp;
|
||||
if let Some(dst) = samples.get_mut(o..o + bpp) {
|
||||
dst.copy_from_slice(px);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(RawImage { width: p.w, height: p.h, color, bit_depth: p.depth, samples })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pattern(w: usize, h: usize, color: ColorType, depth: u8) -> Vec<u8> {
|
||||
let n = w * h * color.channels() * (depth / 8) as usize;
|
||||
(0..n).map(|i| ((i * 7 + i / 13 * 3 + (i * i) % 5) % 251) as u8).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_round_trips_all_formats() {
|
||||
for color in [ColorType::Gray, ColorType::GrayAlpha, ColorType::Rgb, ColorType::Rgba] {
|
||||
for depth in [8u8, 16] {
|
||||
for (w, h) in [(1, 1), (3, 2), (17, 9), (64, 64)] {
|
||||
let s = pattern(w, h, color, depth);
|
||||
let png = encode_raw(w, h, color, depth, &s, Level::Default);
|
||||
let r = decode_raw(&png).unwrap();
|
||||
assert_eq!(r, RawImage { width: w, height: h, color, bit_depth: depth, samples: s.clone() });
|
||||
// The float decoder agrees on the first channel of the first pixel.
|
||||
let t = decode(&png).unwrap();
|
||||
let first = if depth == 16 { u16::from_be_bytes([s[0], s[1]]) as f32 / 65535.0 } else { s[0] as f32 / 255.0 };
|
||||
assert!((t.px[0][0] - first).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compresses_smooth_images() {
|
||||
let (w, h) = (256, 256);
|
||||
let s: Vec<u8> = (0..w * h * 3).map(|i| ((i / 3) % w + (i / 3) / w) as u8).collect();
|
||||
let png = encode_raw(w, h, ColorType::Rgb, 8, &s, Level::Default);
|
||||
assert!(png.len() < s.len() / 20, "{}", png.len());
|
||||
assert_eq!(decode_raw(&png).unwrap().samples, s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_float_is_lossless_at_8_bit() {
|
||||
let px: Vec<[f32; 4]> = (0..64).map(|i| [i as f32 / 63.0, (i % 8) as f32 / 255.0, 0.5, if i == 5 { 0.5 } else { 1.0 }]).collect();
|
||||
let t = decode(&encode(8, 8, &px, 8)).unwrap();
|
||||
for (a, b) in px.iter().zip(&t.px) {
|
||||
for c in 0..4 {
|
||||
assert_eq!((a[c] * 255.0 + 0.5) as u8, (b[c] * 255.0 + 0.5) as u8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_raw_handles_interlaced() {
|
||||
// A 3x3 8-bit gray Adam7 image built by hand: passes 1,4,6,7 are the only non-empty ones for this size
|
||||
// except pass 1 (0,0), pass 4 (2,0), pass 5 (0,2),(2,2), pass 6 (1,0),(1,2), pass 7 rows 1.
|
||||
let img = [[10u8, 11, 12], [13, 14, 15], [16, 17, 18]];
|
||||
let mut raw = Vec::new();
|
||||
let layout = [(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)];
|
||||
for (x0, y0, dx, dy) in layout {
|
||||
let mut y = y0;
|
||||
while y < 3 && x0 < 3 {
|
||||
raw.push(0);
|
||||
let mut x = x0;
|
||||
while x < 3 {
|
||||
raw.push(img[y][x]);
|
||||
x += dx;
|
||||
}
|
||||
y += dy;
|
||||
}
|
||||
}
|
||||
let mut out = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
|
||||
chunk(&mut out, b"IHDR", &[0, 0, 0, 3, 0, 0, 0, 3, 8, 0, 0, 0, 1]);
|
||||
chunk(&mut out, b"IDAT", &deflate::zlib_compress(&raw, Level::Default));
|
||||
chunk(&mut out, b"IEND", &[]);
|
||||
let r = decode_raw(&out).unwrap();
|
||||
assert_eq!(r.samples, img.concat());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncations_error_without_panicking() {
|
||||
let png = encode_raw(5, 4, ColorType::Rgba, 16, &pattern(5, 4, ColorType::Rgba, 16), Level::Default);
|
||||
for n in 0..png.len() - 12 {
|
||||
assert!(decode_raw(&png[..n]).is_err(), "prefix {n}");
|
||||
assert!(decode(&png[..n]).is_err(), "prefix {n}");
|
||||
}
|
||||
assert!(decode_raw(&encode_raw(0, 0, ColorType::Gray, 8, &[], Level::Fast)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inflate_rejects_every_truncation() {
|
||||
let data: Vec<u8> = (0..5000u32).map(|i| (i % 97 + i / 300) as u8).collect();
|
||||
for level in [Level::Store, Level::Fast, Level::Default] {
|
||||
let z = deflate::compress(&data, level);
|
||||
assert_eq!(inflate(&z).unwrap(), data);
|
||||
for n in 0..z.len() {
|
||||
assert!(inflate(&z[..n]).is_err(), "{level:?} prefix {n}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Where evaluation spends its time, for a host that wants to know: named spans around nodes and stages, handed to the
|
||||
//! [`Profiler`] of the current [`crate::context::EvalContext`]. Without one a span measures nothing. Nothing here
|
||||
//! touches what is computed.
|
||||
|
||||
use std::any::Any;
|
||||
|
||||
/// What measures the spans: given to an evaluation in its [`crate::context::EvalContext`].
|
||||
pub trait Profiler: Send + Sync {
|
||||
/// Whether spans are measured now: when not, evaluation skips the work only a measurement needs.
|
||||
fn enabled(&self) -> bool;
|
||||
/// Opens a span of `name`; dropping the returned value closes it.
|
||||
fn span(&self, name: &str) -> Box<dyn Any + Send>;
|
||||
/// Observes a node once its inputs are evaluated, before they are resized and the node is computed (the time of
|
||||
/// the inputs is not in it), even when span timers are disabled.
|
||||
fn node(&self, _id: u32, _kind: &str, _size: (usize, usize)) -> Option<Box<dyn Any + Send>> {
|
||||
None
|
||||
}
|
||||
/// Observes a node with its bound settings after parameter expressions have been applied.
|
||||
fn node_variant(&self, id: u32, node: &crate::graph::Node, size: (usize, usize)) -> Option<Box<dyn Any + Send>> {
|
||||
self.node(id, &node.kind, size)
|
||||
}
|
||||
/// Observes a result supplied by an accelerator, including one reused from its cache.
|
||||
fn accelerated_node(&self, _id: u32, _kind: &str) {}
|
||||
/// Observes a result still held on the accelerator and readable by compatible nodes.
|
||||
fn resident_node(&self, id: u32, kind: &str) {
|
||||
self.accelerated_node(id, kind);
|
||||
}
|
||||
/// Observes resident grayscale pixels fetched for a consumer that needs host pixels.
|
||||
fn resident_readback(&self, _id: u32, _bytes: usize) {}
|
||||
}
|
||||
|
||||
/// A timed stretch of work: runs from [`span`] until dropped.
|
||||
#[must_use = "a span measures until it is dropped"]
|
||||
pub struct Span {
|
||||
_guard: Option<Box<dyn Any + Send>>,
|
||||
}
|
||||
|
||||
/// True when spans are being measured on this thread.
|
||||
pub fn enabled() -> bool {
|
||||
crate::context::with_current(|ec| ec.and_then(|ec| ec.profiler.as_ref()).is_some_and(|p| p.enabled()))
|
||||
}
|
||||
|
||||
/// Opens a span of `name`. Spans may nest and overlap.
|
||||
pub fn span(name: &str) -> Span {
|
||||
Span { _guard: crate::context::with_current(|ec| ec.and_then(|ec| ec.profiler.as_ref()).filter(|p| p.enabled()).map(|p| p.span(name))) }
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Each table in `tests/rules/` defines the inputs and expected outputs for one rule of the compiled graph format.
|
||||
//! Run the table checks with `cargo test -p craft-material-graph --lib rule_table_`.
|
||||
|
||||
use crate::lcg_rand::{self, Lcg};
|
||||
use crate::tex::Tex;
|
||||
|
||||
/// One table: the column names and the rows, all as text.
|
||||
pub(crate) struct Table {
|
||||
pub name: &'static str,
|
||||
columns: Vec<String>,
|
||||
pub rows: Vec<Vec<String>>,
|
||||
}
|
||||
|
||||
impl Table {
|
||||
/// Reads a table: `#` lines are comments, the first other line names the columns, the rest are rows; fields are
|
||||
/// separated by tabs.
|
||||
pub fn parse(name: &'static str, text: &str) -> Table {
|
||||
let mut lines = text.lines().map(str::trim_end).filter(|l| !l.is_empty() && !l.starts_with('#'));
|
||||
let columns: Vec<String> = lines.next().unwrap_or_default().split('\t').map(str::to_string).collect();
|
||||
let rows: Vec<Vec<String>> = lines.map(|l| l.split('\t').map(str::to_string).collect()).collect();
|
||||
for (i, r) in rows.iter().enumerate() {
|
||||
assert_eq!(r.len(), columns.len(), "{name}: row {} has {} fields, the header {}", i + 1, r.len(), columns.len());
|
||||
}
|
||||
assert!(!rows.is_empty(), "{name}: no rows");
|
||||
Table { name, columns, rows }
|
||||
}
|
||||
|
||||
fn at(&self, column: &str) -> usize {
|
||||
self.columns.iter().position(|c| c == column).unwrap_or_else(|| panic!("{}: no column {column}", self.name))
|
||||
}
|
||||
|
||||
/// The text in `column` of `row`.
|
||||
pub fn text<'a>(&self, row: &'a [String], column: &str) -> &'a str {
|
||||
row.get(self.at(column)).map_or("", String::as_str)
|
||||
}
|
||||
|
||||
/// The number in `column` of `row` (`NaN` and `inf` allowed).
|
||||
pub fn num(&self, row: &[String], column: &str) -> f64 {
|
||||
let t = self.text(row, column);
|
||||
t.parse().unwrap_or_else(|_| panic!("{}: {column} = {t:?} is not a number", self.name))
|
||||
}
|
||||
|
||||
/// The number in `column` read as a single float directly (no rounding through a double).
|
||||
pub fn f32(&self, row: &[String], column: &str) -> f32 {
|
||||
let t = self.text(row, column);
|
||||
t.parse().unwrap_or_else(|_| panic!("{}: {column} = {t:?} is not a number", self.name))
|
||||
}
|
||||
|
||||
/// A whole number in `column`, decimal or `0x` hex.
|
||||
pub fn int(&self, row: &[String], column: &str) -> u64 {
|
||||
let t = self.text(row, column);
|
||||
let parsed = match t.strip_prefix("0x") {
|
||||
Some(h) => u64::from_str_radix(h, 16),
|
||||
None => t.parse(),
|
||||
};
|
||||
parsed.unwrap_or_else(|_| panic!("{}: {column} = {t:?} is not a whole number", self.name))
|
||||
}
|
||||
|
||||
/// A space-separated list of whole numbers in `column`.
|
||||
pub fn ints(&self, row: &[String], column: &str) -> Vec<u64> {
|
||||
self.text(row, column).split(' ').map(|t| t.parse().unwrap_or_else(|_| panic!("{}: {column} has {t:?}", self.name))).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The generator a table names, as ours has it.
|
||||
fn generator(name: &str) -> Lcg {
|
||||
let site = |k: usize| lcg_rand::FX_SITES.get(k).copied().unwrap_or_else(|| panic!("no fx site {k}"));
|
||||
match name {
|
||||
"function" => lcg_rand::FUNCTION,
|
||||
"parameter" => lcg_rand::PARAMETER,
|
||||
"fx_luminance" => site(0),
|
||||
"fx_branch_offset" => site(1),
|
||||
"fx_pattern_offset" => site(2),
|
||||
"fx_size" => site(3),
|
||||
"fx_rotation" => site(4),
|
||||
"fx_variation" => site(5),
|
||||
"fx_switch" => site(6),
|
||||
"fx_iterate_count" => site(7),
|
||||
"fx_image_index" => site(8),
|
||||
"iteration" => lcg_rand::ITERATION,
|
||||
other => {
|
||||
let depth: usize = other.strip_prefix("quadrant_depth_").and_then(|d| d.parse().ok()).unwrap_or_else(|| panic!("no generator {other}"));
|
||||
lcg_rand::QUADRANT.get(depth - 1).copied().unwrap_or_else(|| panic!("no quadrant depth {depth}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rule_table_node_hold() {
|
||||
let t = Table::parse("node_hold", include_str!("../tests/rules/node_hold.tsv"));
|
||||
for row in &t.rows {
|
||||
let v = t.f32(row, "value");
|
||||
let level_8 = (crate::ops::compiled_8bit(v) * 255.0).round() as u64;
|
||||
let level_16 = (crate::ops::compiled_16bit(v) * 65535.0).round() as u64;
|
||||
let half = crate::ops::compiled_half(v);
|
||||
assert_eq!(level_8, t.int(row, "level_8"), "node_hold {row:?}: 8 bits");
|
||||
assert_eq!(level_16, t.int(row, "level_16"), "node_hold {row:?}: 16 bits");
|
||||
assert_eq!(half.to_bits(), t.f32(row, "half").to_bits(), "node_hold {row:?}: half {half}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rule_table_bilinear_read() {
|
||||
let t = Table::parse("bilinear_read", include_str!("../tests/rules/bilinear_read.tsv"));
|
||||
for row in &t.rows {
|
||||
let (a, b) = (t.int(row, "a_16") as f32 / 65535.0, t.int(row, "b_16") as f32 / 65535.0);
|
||||
let image = Tex { w: 2, h: 1, px: vec![[a, a, a, 1.0], [b, b, b, 1.0]] };
|
||||
// the read at a position `fraction` of the way from texel 0's centre to texel 1's
|
||||
let u = (0.5 + t.f32(row, "fraction")) / 2.0;
|
||||
let mut read = Tex { w: 1, h: 1, px: vec![crate::atomic::sample_stepped(&image, u, 0.5)] };
|
||||
crate::ops::round_to_16bit_read(&mut read);
|
||||
let got = (read.px.first().map_or(0.0, |p| p[0]) * 65535.0).round() as u64;
|
||||
assert_eq!(got, t.int(row, "ours_16"), "bilinear_read {row:?}");
|
||||
// the integer rule, and where ours differs from it: only at an exact tie, which ours, in single precision, rounds down
|
||||
let w = t.int(row, "weight_256");
|
||||
assert_eq!(w, (f64::from(t.f32(row, "fraction")) * 256.0).round() as u64, "bilinear_read {row:?}: weight");
|
||||
let exact = t.int(row, "a_16") * (256 - w) + t.int(row, "b_16") * w;
|
||||
assert_eq!((exact + 128) >> 8, t.int(row, "rule_16"), "bilinear_read {row:?}: rule");
|
||||
assert!(got == t.int(row, "rule_16") || (exact % 256 == 128 && got + 1 == t.int(row, "rule_16")), "bilinear_read {row:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rule_table_box_blur_plan() {
|
||||
let t = Table::parse("box_blur_plan", include_str!("../tests/rules/box_blur_plan.tsv"));
|
||||
for row in &t.rows {
|
||||
let (format, steps) = match t.text(row, "format") {
|
||||
"8" => (crate::measured::COMPILED_8_BIT, 255.0),
|
||||
"16" => (crate::measured::COMPILED_16_BIT, 65535.0),
|
||||
other => panic!("box_blur_plan: no format {other}"),
|
||||
};
|
||||
let input = t.ints(row, "input");
|
||||
let image = Tex { w: input.len(), h: 1, px: input.iter().map(|&k| [k as f32 / steps; 4]).collect() };
|
||||
let mut out = crate::atomic::compiled_box_axis(&image, t.f32(row, "radius"), true, format);
|
||||
crate::ops::apply_format(&mut out, format);
|
||||
let got: Vec<u64> = out.px.iter().map(|p| (p[0] * steps).round() as u64).collect();
|
||||
assert_eq!(got, t.ints(row, "output"), "box_blur_plan: format {} radius {}", t.text(row, "format"), t.text(row, "radius"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rule_table_lcg_draws() {
|
||||
let t = Table::parse("lcg_draws", include_str!("../tests/rules/lcg_draws.tsv"));
|
||||
for row in &t.rows {
|
||||
let lcg = (t.int(row, "a") as u32, t.int(row, "c") as u32);
|
||||
assert_eq!(generator(t.text(row, "generator")), lcg, "lcg_draws {row:?}: ours has another generator");
|
||||
let mut state = t.int(row, "start") as u32;
|
||||
for _ in 0..t.int(row, "draw") {
|
||||
state = lcg_rand::step(lcg, state);
|
||||
}
|
||||
assert_eq!(state, t.int(row, "state") as u32, "lcg_draws {row:?}");
|
||||
assert_eq!(lcg_rand::output(state), t.num(row, "value"), "lcg_draws {row:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rule_table_pixel_state() {
|
||||
let t = Table::parse("pixel_state", include_str!("../tests/rules/pixel_state.tsv"));
|
||||
for row in &t.rows {
|
||||
let (x, y, w, h) = (t.int(row, "x") as f32, t.int(row, "y") as f32, t.int(row, "width") as f32, t.int(row, "height") as f32);
|
||||
let state = lcg_rand::pixel_state(t.int(row, "seed") as u32, (x + 0.5) / w, (y + 0.5) / h);
|
||||
assert_eq!(state, t.int(row, "state") as u32, "pixel_state {row:?}");
|
||||
assert_eq!(lcg_rand::output(lcg_rand::step(lcg_rand::FUNCTION, state)), t.num(row, "first_value"), "pixel_state {row:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rule_table_fx_child_state() {
|
||||
let t = Table::parse("fx_child_state", include_str!("../tests/rules/fx_child_state.tsv"));
|
||||
for row in &t.rows {
|
||||
let got = lcg_rand::child_state(t.int(row, "parent") as u32, t.int(row, "child") as usize, t.int(row, "depth") as usize);
|
||||
assert_eq!(got, t.int(row, "state") as u32, "fx_child_state {row:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rule_table_pattern_shape() {
|
||||
let t = Table::parse("pattern_shape", include_str!("../tests/rules/pattern_shape.tsv"));
|
||||
for row in &t.rows {
|
||||
let got = crate::patterns::shape(t.int(row, "pattern") as i32, t.f32(row, "x"), t.f32(row, "y"), t.f32(row, "variation"));
|
||||
match t.text(row, "value") {
|
||||
"none" => assert_eq!(got, None, "pattern_shape {row:?}"),
|
||||
_ => {
|
||||
let (got, want) = (got.unwrap_or(f32::NAN), t.f32(row, "value"));
|
||||
assert!((got - want).abs() <= 1e-6, "pattern_shape {row:?}: got {got}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,782 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Scatter nodes: Tile Sampler, Tile Generator, Splatter, Splatter Circular.
|
||||
//! Every new property defaults to the previous behaviour, so graphs saved before this module render unchanged.
|
||||
use crate::math;
|
||||
use crate::noise::rnd;
|
||||
use crate::tex::{Tex, lum};
|
||||
use std::f32::consts::TAU;
|
||||
|
||||
fn sm(a: f32, b: f32, x: f32) -> f32 {
|
||||
let d = b - a;
|
||||
let t = if d.abs() < 1e-9 { if x >= b { 1.0 } else { 0.0 } } else { ((x - a) / d).clamp(0.0, 1.0) };
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
|
||||
/// Names of the built-in pattern shapes, index 0 = "use the pattern input (or the node's default shape)".
|
||||
pub const PATTERN_NAMES: &[&str] = &[
|
||||
"Input / default",
|
||||
"Square",
|
||||
"Disc",
|
||||
"Paraboloid",
|
||||
"Bell",
|
||||
"Gaussian",
|
||||
"Thorn",
|
||||
"Pyramid",
|
||||
"Brick",
|
||||
"Gradation",
|
||||
"Waves",
|
||||
"Half Bell",
|
||||
"Ridged Bell",
|
||||
"Crescent",
|
||||
"Capsule",
|
||||
"Cone",
|
||||
];
|
||||
|
||||
/// Built-in pattern value at local coordinates (lx, ly) in 0..1 (centre 0.5). `spec` is "Pattern Specific" (0..1).
|
||||
pub fn builtin(kind: u32, lx: f32, ly: f32, spec: f32) -> f32 {
|
||||
let (x, y) = ((lx - 0.5) * 2.0, (ly - 0.5) * 2.0);
|
||||
let r = (x * x + y * y).sqrt();
|
||||
let v = match kind {
|
||||
1 => 1.0,
|
||||
2 => 1.0 - sm(0.85, 1.0, r),
|
||||
3 => 1.0 - r * r,
|
||||
4 => 0.5 + 0.5 * math::cos(r.min(1.0) * std::f32::consts::PI),
|
||||
5 => math::exp(-math::powi(r * 2.5, 2)),
|
||||
6 => math::powf((1.0 - r).max(0.0), 1.0 + spec * 6.0),
|
||||
7 => 1.0 - x.abs().max(y.abs()),
|
||||
8 => {
|
||||
let e = (1.0 - x.abs()).min(1.0 - y.abs());
|
||||
(e / (0.04 + spec * 0.5)).clamp(0.0, 1.0)
|
||||
}
|
||||
9 => lx,
|
||||
10 => 0.5 + 0.5 * math::cos(TAU * (1.0 + (spec * 8.0).round()) * lx),
|
||||
11 => 0.5 + 0.5 * math::cos(y.abs().min(1.0) * std::f32::consts::PI),
|
||||
12 => {
|
||||
let b = 0.5 + 0.5 * math::cos(r.min(1.0) * std::f32::consts::PI);
|
||||
1.0 - (1.0 - 2.0 * b).abs()
|
||||
}
|
||||
13 => {
|
||||
let o = 0.2 + spec * 0.6;
|
||||
let inner = (math::powi(x - o, 2) + y * y).sqrt();
|
||||
if r < 1.0 && inner > 0.8 { 1.0 - sm(0.85, 1.0, r) } else { 0.0 }
|
||||
}
|
||||
14 => {
|
||||
let half = 0.15 + spec * 0.7;
|
||||
let dx = (x.abs() - half).max(0.0);
|
||||
let d = (dx * dx + y * y).sqrt();
|
||||
1.0 - sm(0.85, 1.0, d)
|
||||
}
|
||||
15 => 1.0 - r,
|
||||
// the original Splatter disc (slightly wider soft edge)
|
||||
99 => 1.0 - sm(0.8, 1.0, r),
|
||||
_ => 1.0,
|
||||
};
|
||||
v.clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// The patterns a scatter node can draw: up to six inputs and/or a built-in shape.
|
||||
pub struct Patterns<'a> {
|
||||
pub inputs: Vec<&'a Tex>,
|
||||
/// 0 = use the inputs (fall back to `fallback`), 1.. = [`PATTERN_NAMES`] index
|
||||
pub builtin: u32,
|
||||
/// built-in used when no input is connected and `builtin == 0` (0 = solid)
|
||||
pub fallback: u32,
|
||||
/// 0 random per instance, 1 by instance number
|
||||
pub distribution: u32,
|
||||
}
|
||||
|
||||
impl Patterns<'_> {
|
||||
fn count(&self) -> usize {
|
||||
self.inputs.len().max(1)
|
||||
}
|
||||
/// `pick` in 0..1 selects the input (random or by number, decided by the caller).
|
||||
fn value(&self, which: usize, lx: f32, ly: f32, spec: f32) -> f32 {
|
||||
if self.builtin > 0 {
|
||||
return builtin(self.builtin, lx, ly, spec);
|
||||
}
|
||||
match self.inputs.get(which % self.count()) {
|
||||
Some(t) => lum(t.sample(lx, ly)),
|
||||
None => builtin(self.fallback, lx, ly, spec),
|
||||
}
|
||||
}
|
||||
fn choose(&self, index: usize, r: f32) -> usize {
|
||||
let n = self.count();
|
||||
if self.distribution == 1 { index % n } else { ((r * n as f32) as usize).min(n - 1) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Blending of overlapping instances.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
pub enum Blend {
|
||||
Max,
|
||||
Add,
|
||||
Over,
|
||||
AddSub,
|
||||
}
|
||||
impl Blend {
|
||||
pub fn from_index(i: u32) -> Blend {
|
||||
match i {
|
||||
1 => Blend::Add,
|
||||
2 => Blend::Over,
|
||||
3 => Blend::AddSub,
|
||||
_ => Blend::Max,
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn apply(self, acc: f32, a: f32, col: f32) -> f32 {
|
||||
match self {
|
||||
Blend::Max => acc.max(a * col),
|
||||
Blend::Add => acc + a * col,
|
||||
Blend::Over => acc + (col - acc) * a,
|
||||
Blend::AddSub => acc + a * (col * 2.0 - 1.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TileMaps<'a> {
|
||||
pub mask: Option<&'a Tex>,
|
||||
pub scale: Option<&'a Tex>,
|
||||
pub rotation: Option<&'a Tex>,
|
||||
pub displacement: Option<&'a Tex>,
|
||||
pub color: Option<&'a Tex>,
|
||||
pub distribution: Option<&'a Tex>,
|
||||
pub background: Option<&'a Tex>,
|
||||
}
|
||||
|
||||
pub struct TileP {
|
||||
pub nx: f32,
|
||||
pub ny: f32,
|
||||
pub size: f32,
|
||||
pub aspect: f32,
|
||||
pub size_mode: u32,
|
||||
pub scale: f32,
|
||||
pub scale_rand: f32,
|
||||
pub scale_seed: u32,
|
||||
pub size_rand: f32,
|
||||
pub rot: f32,
|
||||
pub rot_rand: f32,
|
||||
pub pattern_rot90: u32,
|
||||
pub symmetry_random: u32,
|
||||
pub pos_rand: f32,
|
||||
pub pos_rand_x: f32,
|
||||
pub pos_rand_y: f32,
|
||||
pub color: f32,
|
||||
pub color_rand: f32,
|
||||
pub lum_by_number: f32,
|
||||
pub lum_by_scale: f32,
|
||||
pub offset: f32,
|
||||
pub offset_mode: u32,
|
||||
pub offset_rand: f32,
|
||||
pub offset_seed: u32,
|
||||
pub global_offset: [f32; 2],
|
||||
pub seed: u32,
|
||||
pub thresh: f32,
|
||||
pub mask_invert: bool,
|
||||
pub mask_random: f32,
|
||||
pub mask_checker: u32,
|
||||
pub mask_h: bool,
|
||||
pub mask_v: bool,
|
||||
pub invert_mask: bool,
|
||||
pub scale_map_mult: f32,
|
||||
pub rotation_map_mult: f32,
|
||||
pub displacement_intensity: f32,
|
||||
pub displacement_angle: f32,
|
||||
pub color_map_mult: f32,
|
||||
pub pattern_specific: f32,
|
||||
pub pattern_specific_rand: f32,
|
||||
pub blend: Blend,
|
||||
pub opacity: f32,
|
||||
pub background: f32,
|
||||
pub reverse: bool,
|
||||
}
|
||||
|
||||
impl TileP {
|
||||
/// Defaults that reproduce the original Tile Sampler (`gen == false`) or Tile Generator (`gen == true`).
|
||||
pub fn legacy(r#gen: bool) -> TileP {
|
||||
TileP {
|
||||
nx: if r#gen { 6.0 } else { 8.0 },
|
||||
ny: if r#gen { 6.0 } else { 8.0 },
|
||||
size: if r#gen { 0.92 } else { 0.8 },
|
||||
aspect: 1.0,
|
||||
size_mode: 0,
|
||||
scale: 1.0,
|
||||
scale_rand: 0.0,
|
||||
scale_seed: 0,
|
||||
size_rand: 0.0,
|
||||
rot: 0.0,
|
||||
rot_rand: 0.0,
|
||||
pattern_rot90: 0,
|
||||
symmetry_random: 0,
|
||||
pos_rand: 0.0,
|
||||
pos_rand_x: 1.0,
|
||||
pos_rand_y: 1.0,
|
||||
color: 1.0,
|
||||
color_rand: 0.0,
|
||||
lum_by_number: 0.0,
|
||||
lum_by_scale: 0.0,
|
||||
offset: 0.5,
|
||||
offset_mode: if r#gen { 1 } else { 0 },
|
||||
offset_rand: 0.0,
|
||||
offset_seed: 0,
|
||||
global_offset: [0.0, 0.0],
|
||||
seed: 0,
|
||||
thresh: 0.5,
|
||||
mask_invert: false,
|
||||
mask_random: 0.0,
|
||||
mask_checker: 0,
|
||||
mask_h: false,
|
||||
mask_v: false,
|
||||
invert_mask: false,
|
||||
scale_map_mult: 1.0,
|
||||
rotation_map_mult: 1.0,
|
||||
displacement_intensity: 0.5,
|
||||
displacement_angle: 0.0,
|
||||
color_map_mult: 1.0,
|
||||
pattern_specific: 0.5,
|
||||
pattern_specific_rand: 0.0,
|
||||
blend: Blend::Max,
|
||||
opacity: 1.0,
|
||||
background: 0.0,
|
||||
reverse: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Inst {
|
||||
cx: f32,
|
||||
cy: f32,
|
||||
sx: f32,
|
||||
sy: f32,
|
||||
sn: f32,
|
||||
cs: f32,
|
||||
flip_x: bool,
|
||||
flip_y: bool,
|
||||
col: f32,
|
||||
pat: usize,
|
||||
spec: f32,
|
||||
key: u32,
|
||||
on: bool,
|
||||
}
|
||||
|
||||
fn tile_visible(i: i32, j: i32, mask: Option<f32>, p: &TileP) -> bool {
|
||||
let mut keep = true;
|
||||
if let Some(m) = mask {
|
||||
keep = if p.mask_invert { m < p.thresh } else { m >= p.thresh };
|
||||
}
|
||||
let mut proc_keep = true;
|
||||
if p.mask_random > 0.0 && rnd(i, j, p.seed.wrapping_add(31)) < p.mask_random {
|
||||
proc_keep = false;
|
||||
}
|
||||
match p.mask_checker {
|
||||
1 => proc_keep &= ((i + j) & 1) == 0,
|
||||
2 => proc_keep &= ((i + j) & 1) == 1,
|
||||
_ => {}
|
||||
}
|
||||
if p.mask_h {
|
||||
proc_keep &= (i & 1) == 0;
|
||||
}
|
||||
if p.mask_v {
|
||||
proc_keep &= (j & 1) == 0;
|
||||
}
|
||||
if p.invert_mask {
|
||||
proc_keep = !proc_keep;
|
||||
}
|
||||
keep && proc_keep
|
||||
}
|
||||
|
||||
/// Grid of pattern instances (Tile Sampler / Tile Generator).
|
||||
pub fn tile_grid(w: usize, h: usize, pats: &Patterns, maps: &TileMaps, p: &TileP) -> Tex {
|
||||
let nx = p.nx.round().clamp(1.0, 64.0) as i32;
|
||||
let ny = p.ny.round().clamp(1.0, 64.0) as i32;
|
||||
let (fnx, fny) = (nx as f32, ny as f32);
|
||||
let np = pats.count();
|
||||
let total = (nx * ny) as f32;
|
||||
// divisor that turns image distance into pattern-local distance
|
||||
let (dvx, dvy) = match p.size_mode {
|
||||
1 => (fnx.min(fny), fnx.min(fny)),
|
||||
2 => (1.0, 1.0),
|
||||
_ => (fnx, fny),
|
||||
};
|
||||
let samp = |t: Option<&Tex>, x: f32, y: f32| t.map(|t| lum(t.sample(x, y)));
|
||||
let mut max_half = 0.0f32;
|
||||
let mut inst: Vec<Inst> = Vec::with_capacity((nx * ny) as usize);
|
||||
for j in 0..ny {
|
||||
for i in 0..nx {
|
||||
let sd = p.seed;
|
||||
let (r1, r2, r3, r4) = (rnd(i, j, sd), rnd(i, j, sd.wrapping_add(1)), rnd(i, j, sd.wrapping_add(2)), rnd(i, j, sd.wrapping_add(3)));
|
||||
let key = (j * nx + i) as u32;
|
||||
// row / column offset
|
||||
let (line, along_row) = match p.offset_mode {
|
||||
1 | 2 => (j, true),
|
||||
_ => (i, false),
|
||||
};
|
||||
let active = match p.offset_mode {
|
||||
1 | 3 => (line & 1) == 1,
|
||||
2 | 4 => (line & 1) == 0,
|
||||
_ => false,
|
||||
};
|
||||
let mut shift = if active { p.offset } else { 0.0 };
|
||||
if p.offset_mode != 0 && p.offset_rand > 0.0 {
|
||||
shift += (rnd(line, 77, p.offset_seed.wrapping_add(sd)) - 0.5) * 2.0 * p.offset_rand;
|
||||
}
|
||||
let (mut cx, mut cy) = ((i as f32 + 0.5) / fnx, (j as f32 + 0.5) / fny);
|
||||
if along_row || p.offset_mode == 0 {
|
||||
cx += shift / fnx;
|
||||
} else {
|
||||
cy += shift / fny;
|
||||
}
|
||||
cx += (r1 - 0.5) * p.pos_rand * p.pos_rand_x / fnx + p.global_offset[0];
|
||||
cy += (r2 - 0.5) * p.pos_rand * p.pos_rand_y / fny + p.global_offset[1];
|
||||
let (cx0, cy0) = (cx, cy);
|
||||
// map inputs sampled at the tile centre
|
||||
let on = tile_visible(i, j, samp(maps.mask, cx0, cy0), p);
|
||||
if let Some(d) = samp(maps.displacement, cx0, cy0) {
|
||||
let a = p.displacement_angle * TAU;
|
||||
let k = (d - 0.5) * 2.0 * p.displacement_intensity;
|
||||
cx += math::cos(a) * k / fnx;
|
||||
cy += math::sin(a) * k / fny;
|
||||
}
|
||||
let mut s = p.size * p.scale * (1.0 + (r3 - 0.5) * 2.0 * p.size_rand);
|
||||
if p.scale_rand > 0.0 {
|
||||
s *= 1.0 + (rnd(i, j, sd.wrapping_add(p.scale_seed).wrapping_add(41)) - 0.5) * 2.0 * p.scale_rand;
|
||||
}
|
||||
if let Some(m) = samp(maps.scale, cx0, cy0) {
|
||||
s *= 1.0 + p.scale_map_mult * (m - 1.0);
|
||||
}
|
||||
let s = s.max(0.01);
|
||||
let mut turns = p.rot + (r4 - 0.5) * 2.0 * p.rot_rand + 0.25 * p.pattern_rot90 as f32;
|
||||
if let Some(m) = samp(maps.rotation, cx0, cy0) {
|
||||
turns += m * p.rotation_map_mult;
|
||||
}
|
||||
let (sn, cs) = math::sin_cos(turns * TAU);
|
||||
let mut col = p.color * (1.0 - p.color_rand * rnd(i, j, sd.wrapping_add(9)));
|
||||
if p.lum_by_number > 0.0 {
|
||||
col *= 1.0 - p.lum_by_number * (key as f32 / (total - 1.0).max(1.0));
|
||||
}
|
||||
if p.lum_by_scale > 0.0 {
|
||||
let rel = (s / (p.size * p.scale * (1.0 + p.size_rand)).max(1e-3)).clamp(0.0, 1.0);
|
||||
col *= 1.0 - p.lum_by_scale * (1.0 - rel);
|
||||
}
|
||||
if let Some(m) = samp(maps.color, cx0, cy0) {
|
||||
col *= 1.0 + p.color_map_mult * (m - 1.0);
|
||||
}
|
||||
let pick = match samp(maps.distribution, cx0, cy0) {
|
||||
Some(d) => ((d * np as f32) as usize).min(np - 1),
|
||||
None => pats.choose(key as usize, rnd(i, j, sd.wrapping_add(21))),
|
||||
};
|
||||
let (fx, fy) = match p.symmetry_random {
|
||||
1 => (rnd(i, j, sd.wrapping_add(51)) < 0.5, false),
|
||||
2 => (false, rnd(i, j, sd.wrapping_add(52)) < 0.5),
|
||||
3 => (rnd(i, j, sd.wrapping_add(51)) < 0.5, rnd(i, j, sd.wrapping_add(52)) < 0.5),
|
||||
_ => (false, false),
|
||||
};
|
||||
let spec = (p.pattern_specific + (rnd(i, j, sd.wrapping_add(61)) - 0.5) * 2.0 * p.pattern_specific_rand).clamp(0.0, 1.0);
|
||||
let (sx, sy) = (s, s * p.aspect.max(0.01));
|
||||
max_half = max_half.max(sx.max(sy) * 0.5 / dvx.min(dvy) * fnx.min(fny));
|
||||
inst.push(Inst { cx, cy, sx, sy, sn, cs, flip_x: fx, flip_y: fy, col, pat: pick, spec, key, on });
|
||||
}
|
||||
}
|
||||
// neighbourhood radius in cells: 1 normally, more when tiles are larger than their cell
|
||||
let disp = if maps.displacement.is_some() { p.displacement_intensity } else { 0.0 };
|
||||
let reach = (max_half + p.pos_rand * p.pos_rand_x.max(p.pos_rand_y) * 0.5 + disp + p.offset_rand + 0.5).ceil();
|
||||
let rad = (reach as i32).clamp(1, 3);
|
||||
let bg_in = maps.background;
|
||||
Tex::from_fn(w, h, |u, v| {
|
||||
let (ci, cj) = ((u * fnx).floor() as i32, (v * fny).floor() as i32);
|
||||
let mut cand: [(u32, f32, f32); 49] = [(0, 0.0, 0.0); 49];
|
||||
let mut seen: [u32; 49] = [0; 49];
|
||||
let mut ns = 0;
|
||||
let mut nc = 0;
|
||||
let dedupe = nx < 2 * rad + 1 || ny < 2 * rad + 1;
|
||||
for dj in -rad..=rad {
|
||||
for di in -rad..=rad {
|
||||
let (wi, wj) = (ci.wrapping_add(di).rem_euclid(nx), cj.wrapping_add(dj).rem_euclid(ny));
|
||||
let Some(it) = inst.get((wj * nx + wi) as usize) else { continue };
|
||||
if !it.on {
|
||||
continue;
|
||||
}
|
||||
if dedupe {
|
||||
// a small grid wraps onto itself: count every instance only once
|
||||
if seen.get(..ns).is_some_and(|s| s.contains(&it.key)) {
|
||||
continue;
|
||||
}
|
||||
if let Some(e) = seen.get_mut(ns) {
|
||||
*e = it.key;
|
||||
}
|
||||
ns += 1;
|
||||
}
|
||||
let dx = (u - it.cx + 0.5).rem_euclid(1.0) - 0.5;
|
||||
let dy = (v - it.cy + 0.5).rem_euclid(1.0) - 0.5;
|
||||
let lx = (it.cs * dx + it.sn * dy) * dvx / it.sx + 0.5;
|
||||
let ly = (-it.sn * dx + it.cs * dy) * dvy / it.sy + 0.5;
|
||||
if !(0.0..=1.0).contains(&lx) || !(0.0..=1.0).contains(&ly) {
|
||||
continue;
|
||||
}
|
||||
let (lx, ly) = (if it.flip_x { 1.0 - lx } else { lx }, if it.flip_y { 1.0 - ly } else { ly });
|
||||
let a = pats.value(it.pat, lx, ly, it.spec);
|
||||
if let Some(e) = cand.get_mut(nc) {
|
||||
*e = (it.key, a * p.opacity, it.col);
|
||||
nc += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let c = cand.get_mut(..nc).unwrap_or_default();
|
||||
if p.blend == Blend::Over || p.blend == Blend::AddSub {
|
||||
c.sort_by_key(|e| e.0);
|
||||
}
|
||||
let mut acc = match bg_in {
|
||||
Some(b) => lum(b.sample(u, v)),
|
||||
None => p.background,
|
||||
};
|
||||
if p.reverse {
|
||||
for e in c.iter().rev() {
|
||||
acc = p.blend.apply(acc, e.1, e.2);
|
||||
}
|
||||
} else {
|
||||
for e in c.iter() {
|
||||
acc = p.blend.apply(acc, e.1, e.2);
|
||||
}
|
||||
}
|
||||
let acc = if acc.is_finite() { acc } else { 0.0 };
|
||||
[acc, acc, acc, 1.0]
|
||||
})
|
||||
}
|
||||
|
||||
pub struct SplatterP {
|
||||
pub count: u32,
|
||||
pub grid: u32,
|
||||
pub scale: f32,
|
||||
pub scale_var: f32,
|
||||
pub aspect: f32,
|
||||
pub rot: f32,
|
||||
pub rot_var: f32,
|
||||
pub pattern_rot90: u32,
|
||||
pub lum_var: f32,
|
||||
pub disorder: f32,
|
||||
pub pan: [f32; 2],
|
||||
pub symmetry_random: u32,
|
||||
pub pattern_specific: f32,
|
||||
pub gain: f32,
|
||||
pub out_min: f32,
|
||||
pub out_max: f32,
|
||||
pub background: f32,
|
||||
pub blend: Blend,
|
||||
pub opacity: f32,
|
||||
pub seed: u32,
|
||||
}
|
||||
|
||||
impl SplatterP {
|
||||
pub fn legacy() -> SplatterP {
|
||||
SplatterP {
|
||||
count: 40,
|
||||
grid: 0,
|
||||
scale: 0.1,
|
||||
scale_var: 0.3,
|
||||
aspect: 1.0,
|
||||
rot: 0.0,
|
||||
rot_var: 1.0,
|
||||
pattern_rot90: 0,
|
||||
lum_var: 0.0,
|
||||
disorder: 1.0,
|
||||
pan: [0.0, 0.0],
|
||||
symmetry_random: 0,
|
||||
pattern_specific: 0.5,
|
||||
gain: 1.0,
|
||||
out_min: 0.0,
|
||||
out_max: 1.0,
|
||||
background: 0.0,
|
||||
blend: Blend::Max,
|
||||
opacity: 1.0,
|
||||
seed: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(acc: f32, gain: f32, lo: f32, hi: f32) -> [f32; 4] {
|
||||
let mut v = if acc.is_finite() { acc } else { 0.0 };
|
||||
if (gain - 1.0).abs() > 1e-6 {
|
||||
v = math::powf(v.clamp(0.0, 1.0), 1.0 / gain.max(1e-3));
|
||||
}
|
||||
if lo != 0.0 || hi != 1.0 {
|
||||
v = lo + (hi - lo) * v;
|
||||
}
|
||||
[v, v, v, 1.0]
|
||||
}
|
||||
|
||||
/// Random scatter of a pattern (Splatter). `grid > 0` places `grid * grid` instances on a jittered grid instead
|
||||
/// (`disorder` is the jitter).
|
||||
struct SplatInst {
|
||||
cx: f32,
|
||||
cy: f32,
|
||||
sx: f32,
|
||||
sy: f32,
|
||||
sn: f32,
|
||||
cs: f32,
|
||||
l: f32,
|
||||
fx: bool,
|
||||
fy: bool,
|
||||
pat: usize,
|
||||
}
|
||||
|
||||
/// Which per-instance value `splatter_data` writes.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SplatData {
|
||||
/// a stable random gray level per instance (0 = background)
|
||||
Id,
|
||||
/// the instance centre in uv as red / green
|
||||
Center,
|
||||
/// the instance width / height in uv as red / green
|
||||
Size,
|
||||
/// the instance's brightness factor as gray
|
||||
Luminance,
|
||||
}
|
||||
|
||||
fn splat_instances(pats: &Patterns, p: &SplatterP) -> Vec<SplatInst> {
|
||||
type S = SplatInst;
|
||||
let seed = p.seed;
|
||||
let n = if p.grid > 0 { p.grid.wrapping_mul(p.grid) } else { p.count.min(2000) };
|
||||
let inst: Vec<S> = (0..n)
|
||||
.map(|k| {
|
||||
let i = k as i32;
|
||||
let (mut cx, mut cy) = if p.grid > 0 {
|
||||
let (gx, gy) = ((k % p.grid) as f32, (k / p.grid) as f32);
|
||||
let g = p.grid as f32;
|
||||
((gx + 0.5 + (rnd(i, 1, seed) - 0.5) * p.disorder) / g, (gy + 0.5 + (rnd(i, 2, seed) - 0.5) * p.disorder) / g)
|
||||
} else {
|
||||
(rnd(i, 1, seed), rnd(i, 2, seed))
|
||||
};
|
||||
cx += p.pan[0];
|
||||
cy += p.pan[1];
|
||||
let s = (p.scale * (1.0 + (rnd(i, 3, seed) - 0.5) * 2.0 * p.scale_var)).max(1e-3);
|
||||
let r = p.rot * TAU + (rnd(i, 4, seed) - 0.5) * p.rot_var * TAU + 0.25 * TAU * p.pattern_rot90 as f32;
|
||||
let (sn, cs) = math::sin_cos(r);
|
||||
let (fx, fy) = match p.symmetry_random {
|
||||
1 => (rnd(i, 6, seed) < 0.5, false),
|
||||
2 => (false, rnd(i, 7, seed) < 0.5),
|
||||
3 => (rnd(i, 6, seed) < 0.5, rnd(i, 7, seed) < 0.5),
|
||||
_ => (false, false),
|
||||
};
|
||||
S {
|
||||
cx,
|
||||
cy,
|
||||
sx: s,
|
||||
sy: (s * p.aspect.max(0.01)).max(1e-3),
|
||||
sn,
|
||||
cs,
|
||||
l: 1.0 - p.lum_var * rnd(i, 5, seed),
|
||||
fx,
|
||||
fy,
|
||||
pat: pats.choose(k as usize, rnd(i, 8, seed)),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
inst
|
||||
}
|
||||
|
||||
/// Data of the top-most instance under every pixel. An instance covers a pixel in its box where its value times the opacity
|
||||
/// is above 0.001, so the faintest edge of a soft pattern has no data.
|
||||
pub fn splatter_data(w: usize, h: usize, pats: &Patterns, p: &SplatterP, what: SplatData) -> Tex {
|
||||
let inst = splat_instances(pats, p);
|
||||
Tex::from_fn(w, h, |u, v| {
|
||||
let mut hit: Option<(usize, &SplatInst)> = None;
|
||||
for (k, it) in inst.iter().enumerate() {
|
||||
let dx = (u - it.cx + 0.5).rem_euclid(1.0) - 0.5;
|
||||
let dy = (v - it.cy + 0.5).rem_euclid(1.0) - 0.5;
|
||||
let lx = (it.cs * dx + it.sn * dy) / it.sx + 0.5;
|
||||
let ly = (-it.sn * dx + it.cs * dy) / it.sy + 0.5;
|
||||
if !(0.0..=1.0).contains(&lx) || !(0.0..=1.0).contains(&ly) {
|
||||
continue;
|
||||
}
|
||||
let (lx, ly) = (if it.fx { 1.0 - lx } else { lx }, if it.fy { 1.0 - ly } else { ly });
|
||||
if pats.value(it.pat, lx, ly, p.pattern_specific) * p.opacity > 1e-3 {
|
||||
hit = Some((k, it));
|
||||
}
|
||||
}
|
||||
match hit {
|
||||
None => [0.0, 0.0, 0.0, 1.0],
|
||||
Some((k, it)) => match what {
|
||||
SplatData::Id => {
|
||||
let g = 0.1 + 0.9 * rnd(k as i32, 31, p.seed);
|
||||
[g, g, g, 1.0]
|
||||
}
|
||||
SplatData::Center => [it.cx.rem_euclid(1.0), it.cy.rem_euclid(1.0), 0.0, 1.0],
|
||||
SplatData::Size => [it.sx.min(1.0), it.sy.min(1.0), 0.0, 1.0],
|
||||
SplatData::Luminance => [it.l, it.l, it.l, 1.0],
|
||||
},
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn splatter(w: usize, h: usize, pats: &Patterns, p: &SplatterP) -> Tex {
|
||||
let inst = splat_instances(pats, p);
|
||||
Tex::from_fn(w, h, |u, v| {
|
||||
let mut acc = p.background;
|
||||
for it in &inst {
|
||||
let dx = (u - it.cx + 0.5).rem_euclid(1.0) - 0.5;
|
||||
let dy = (v - it.cy + 0.5).rem_euclid(1.0) - 0.5;
|
||||
let lx = (it.cs * dx + it.sn * dy) / it.sx + 0.5;
|
||||
let ly = (-it.sn * dx + it.cs * dy) / it.sy + 0.5;
|
||||
if !(0.0..=1.0).contains(&lx) || !(0.0..=1.0).contains(&ly) {
|
||||
continue;
|
||||
}
|
||||
let (lx, ly) = (if it.fx { 1.0 - lx } else { lx }, if it.fy { 1.0 - ly } else { ly });
|
||||
let a = pats.value(it.pat, lx, ly, p.pattern_specific) * p.opacity;
|
||||
acc = p.blend.apply(acc, a, it.l);
|
||||
}
|
||||
finish(acc, p.gain, p.out_min, p.out_max)
|
||||
})
|
||||
}
|
||||
|
||||
pub struct CircularP {
|
||||
pub amount: u32,
|
||||
pub amount_rand: f32,
|
||||
pub amount_rand_min: u32,
|
||||
pub rings: u32,
|
||||
pub radius: f32,
|
||||
pub radius_rand: f32,
|
||||
pub ring_mult: f32,
|
||||
pub angle_rand: f32,
|
||||
pub spiral: f32,
|
||||
pub spread: f32,
|
||||
pub size: f32,
|
||||
pub size_rand: f32,
|
||||
pub scale_by_number: f32,
|
||||
pub invert_number: bool,
|
||||
pub scale_by_ring: f32,
|
||||
pub invert_ring: bool,
|
||||
pub rot: f32,
|
||||
pub rot_rand: f32,
|
||||
pub center_orientation: f32,
|
||||
pub ring_rot: f32,
|
||||
pub ring_rot_rand: f32,
|
||||
pub ring_rot_offset: f32,
|
||||
pub pos_rand: f32,
|
||||
pub symmetry_random: u32,
|
||||
pub pattern_specific: f32,
|
||||
pub color: f32,
|
||||
pub lum_rand: f32,
|
||||
pub lum_by_number: f32,
|
||||
pub lum_by_ring: f32,
|
||||
pub mask_random: f32,
|
||||
pub background: f32,
|
||||
pub blend: Blend,
|
||||
pub opacity: f32,
|
||||
pub seed: u32,
|
||||
}
|
||||
|
||||
impl CircularP {
|
||||
pub fn legacy() -> CircularP {
|
||||
CircularP {
|
||||
amount: 12,
|
||||
amount_rand: 0.0,
|
||||
amount_rand_min: 1,
|
||||
rings: 1,
|
||||
radius: 0.3,
|
||||
radius_rand: 0.0,
|
||||
ring_mult: 0.5,
|
||||
angle_rand: 0.0,
|
||||
spiral: 0.0,
|
||||
spread: 1.0,
|
||||
size: 0.1,
|
||||
size_rand: 0.0,
|
||||
scale_by_number: 0.0,
|
||||
invert_number: false,
|
||||
scale_by_ring: 0.0,
|
||||
invert_ring: false,
|
||||
rot: 0.0,
|
||||
rot_rand: 0.0,
|
||||
center_orientation: 0.0,
|
||||
ring_rot: 0.0,
|
||||
ring_rot_rand: 0.0,
|
||||
ring_rot_offset: 0.0,
|
||||
pos_rand: 0.0,
|
||||
symmetry_random: 0,
|
||||
pattern_specific: 0.5,
|
||||
color: 1.0,
|
||||
lum_rand: 0.0,
|
||||
lum_by_number: 0.0,
|
||||
lum_by_ring: 0.0,
|
||||
mask_random: 0.0,
|
||||
background: 0.0,
|
||||
blend: Blend::Max,
|
||||
opacity: 1.0,
|
||||
seed: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Instances placed on one or more circles (Splatter Circular).
|
||||
pub fn splatter_circular(w: usize, h: usize, pats: &Patterns, p: &CircularP) -> Tex {
|
||||
struct S {
|
||||
cx: f32,
|
||||
cy: f32,
|
||||
sx: f32,
|
||||
sn: f32,
|
||||
cs: f32,
|
||||
l: f32,
|
||||
fx: bool,
|
||||
fy: bool,
|
||||
pat: usize,
|
||||
}
|
||||
let seed = p.seed;
|
||||
let rings = p.rings.clamp(1, 10);
|
||||
let mut inst: Vec<S> = Vec::new();
|
||||
let mut order = 0u32;
|
||||
for ring in 0..rings {
|
||||
let rk = ring as i32 * 977;
|
||||
let mut n = p.amount.clamp(1, 64 * 4);
|
||||
if p.amount_rand > 0.0 {
|
||||
let lo = p.amount_rand_min.clamp(1, n) as f32;
|
||||
n = (n as f32 + (lo - n as f32) * p.amount_rand * rnd(rk, 11, seed)).round().max(1.0) as u32;
|
||||
}
|
||||
let ring_frac = if rings > 1 { ring as f32 / (rings - 1) as f32 } else { 0.0 };
|
||||
let ring_r = p.radius * math::powi(p.ring_mult, ring as i32);
|
||||
let ring_spin = (p.ring_rot * ring as f32 + p.ring_rot_offset + (rnd(rk, 12, seed) - 0.5) * 2.0 * p.ring_rot_rand) * TAU;
|
||||
for k in 0..n {
|
||||
let i = (k as i32).wrapping_add(rk);
|
||||
let frac = k as f32 / n as f32;
|
||||
let a = frac * p.spread.clamp(0.0, 1.0) * TAU + ring_spin + (rnd(i, 13, seed) - 0.5) * 2.0 * p.angle_rand * TAU / n as f32;
|
||||
let rr = (ring_r * (1.0 + (rnd(i, 14, seed) - 0.5) * 2.0 * p.radius_rand) + p.spiral * 0.2 * frac).max(0.0);
|
||||
let cx = 0.5 + rr * math::cos(a) + (rnd(i, 1, seed) - 0.5) * p.pos_rand * 0.2;
|
||||
let cy = 0.5 + rr * math::sin(a) + (rnd(i, 2, seed) - 0.5) * p.pos_rand * 0.2;
|
||||
let mut s = p.size * (1.0 + (rnd(i, 3, seed) - 0.5) * 2.0 * p.size_rand);
|
||||
let num = if p.invert_number { 1.0 - frac } else { frac };
|
||||
s *= 1.0 - p.scale_by_number * (1.0 - num);
|
||||
let rng = if p.invert_ring { 1.0 - ring_frac } else { ring_frac };
|
||||
s *= 1.0 - p.scale_by_ring * (1.0 - rng);
|
||||
let s = s.max(0.005);
|
||||
let face = (a + std::f32::consts::PI) * p.center_orientation;
|
||||
let r = (p.rot + (rnd(i, 4, seed) - 0.5) * 2.0 * p.rot_rand) * TAU + face;
|
||||
let (sn, cs) = math::sin_cos(r);
|
||||
let (fx, fy) = match p.symmetry_random {
|
||||
1 => (rnd(i, 6, seed) < 0.5, false),
|
||||
2 => (false, rnd(i, 7, seed) < 0.5),
|
||||
3 => (rnd(i, 6, seed) < 0.5, rnd(i, 7, seed) < 0.5),
|
||||
_ => (false, false),
|
||||
};
|
||||
let mut l = p.color * (1.0 - p.lum_rand * rnd(i, 5, seed));
|
||||
l *= 1.0 - p.lum_by_number * (1.0 - num);
|
||||
l *= 1.0 - p.lum_by_ring * (1.0 - rng);
|
||||
if p.mask_random > 0.0 && rnd(i, 15, seed) < p.mask_random {
|
||||
continue;
|
||||
}
|
||||
let pat = if pats.distribution == 2 { ring as usize % pats.count() } else { pats.choose(order as usize, rnd(i, 8, seed)) };
|
||||
inst.push(S { cx, cy, sx: s, sn, cs, l, fx, fy, pat });
|
||||
order += 1;
|
||||
}
|
||||
}
|
||||
Tex::from_fn(w, h, |u, v| {
|
||||
let mut acc = p.background;
|
||||
for it in &inst {
|
||||
let (dx, dy) = (u - it.cx, v - it.cy);
|
||||
let (lx, ly) = ((it.cs * dx + it.sn * dy) / it.sx + 0.5, (-it.sn * dx + it.cs * dy) / it.sx + 0.5);
|
||||
if !(0.0..=1.0).contains(&lx) || !(0.0..=1.0).contains(&ly) {
|
||||
continue;
|
||||
}
|
||||
let (lx, ly) = (if it.fx { 1.0 - lx } else { lx }, if it.fy { 1.0 - ly } else { ly });
|
||||
let a = pats.value(it.pat, lx, ly, p.pattern_specific) * p.opacity;
|
||||
acc = p.blend.apply(acc, a, it.l);
|
||||
}
|
||||
finish(acc, 1.0, 0.0, 1.0)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,942 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Float images with wrapped (tileable) sampling: RGBA ([`Tex`]) or grey ([`Grey`], one value per pixel standing for
|
||||
//! the opaque RGBA pixel `[v, v, v, 1]`).
|
||||
|
||||
/// An image of `w` x `h` pixels of type `P`, row by row.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Image<P> {
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
pub px: Vec<P>,
|
||||
}
|
||||
|
||||
/// A float RGBA image.
|
||||
pub type Tex = Image<[f32; 4]>;
|
||||
|
||||
/// A grey, opaque float image: pixel `v` is the RGBA pixel `[v, v, v, 1]`. Every operation on it applies to `v` the same
|
||||
/// arithmetic the RGBA form applies to each colour channel, so expanding a grey result gives bit for bit what the RGBA
|
||||
/// computation gives on the expanded inputs.
|
||||
pub type Grey = Image<f32>;
|
||||
|
||||
/// A pixel of an [`Image`]: RGBA, or a grey value.
|
||||
pub trait Pixel: Copy + Send + Sync + std::fmt::Debug + 'static {
|
||||
/// What a read past the end of an image gives: transparent black (a grey image reads 0).
|
||||
const NONE: Self;
|
||||
/// The same function on each pair of channels.
|
||||
fn zip(self, o: Self, f: impl Fn(f32, f32) -> f32) -> Self;
|
||||
/// The same function on each channel.
|
||||
fn each(self, f: impl Fn(f32) -> f32) -> Self;
|
||||
/// As an RGBA pixel.
|
||||
fn rgba(self) -> [f32; 4];
|
||||
/// How many channels it has.
|
||||
const CH: usize;
|
||||
/// Channel `c` (0 past the last).
|
||||
fn ch(self, c: usize) -> f32;
|
||||
/// A pixel of channels `f(0)`, `f(1)`, ..
|
||||
fn from_ch(f: impl Fn(usize) -> f32) -> Self;
|
||||
}
|
||||
|
||||
impl Pixel for [f32; 4] {
|
||||
const NONE: Self = [0.0; 4];
|
||||
#[inline(always)]
|
||||
fn zip(self, o: Self, f: impl Fn(f32, f32) -> f32) -> Self {
|
||||
zip4(self, o, f)
|
||||
}
|
||||
#[inline(always)]
|
||||
fn each(self, f: impl Fn(f32) -> f32) -> Self {
|
||||
[f(self[0]), f(self[1]), f(self[2]), f(self[3])]
|
||||
}
|
||||
#[inline(always)]
|
||||
fn rgba(self) -> [f32; 4] {
|
||||
self
|
||||
}
|
||||
const CH: usize = 4;
|
||||
#[inline(always)]
|
||||
fn ch(self, c: usize) -> f32 {
|
||||
get(&self, c)
|
||||
}
|
||||
#[inline(always)]
|
||||
fn from_ch(f: impl Fn(usize) -> f32) -> Self {
|
||||
[f(0), f(1), f(2), f(3)]
|
||||
}
|
||||
}
|
||||
|
||||
impl Pixel for f32 {
|
||||
const NONE: Self = 0.0;
|
||||
#[inline(always)]
|
||||
fn zip(self, o: Self, f: impl Fn(f32, f32) -> f32) -> Self {
|
||||
f(self, o)
|
||||
}
|
||||
#[inline(always)]
|
||||
fn each(self, f: impl Fn(f32) -> f32) -> Self {
|
||||
f(self)
|
||||
}
|
||||
#[inline(always)]
|
||||
fn rgba(self) -> [f32; 4] {
|
||||
[self, self, self, 1.0]
|
||||
}
|
||||
const CH: usize = 1;
|
||||
#[inline(always)]
|
||||
fn ch(self, c: usize) -> f32 {
|
||||
if c == 0 { self } else { 0.0 }
|
||||
}
|
||||
#[inline(always)]
|
||||
fn from_ch(f: impl Fn(usize) -> f32) -> Self {
|
||||
f(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// A grey value and its alpha: the RGBA pixel `[v, v, v, a]`, computed with each of the two channels as the RGBA form
|
||||
/// computes a colour channel and its alpha.
|
||||
impl Pixel for [f32; 2] {
|
||||
const NONE: Self = [0.0; 2];
|
||||
#[inline(always)]
|
||||
fn zip(self, o: Self, f: impl Fn(f32, f32) -> f32) -> Self {
|
||||
[f(self[0], o[0]), f(self[1], o[1])]
|
||||
}
|
||||
#[inline(always)]
|
||||
fn each(self, f: impl Fn(f32) -> f32) -> Self {
|
||||
[f(self[0]), f(self[1])]
|
||||
}
|
||||
#[inline(always)]
|
||||
fn rgba(self) -> [f32; 4] {
|
||||
[self[0], self[0], self[0], self[1]]
|
||||
}
|
||||
const CH: usize = 2;
|
||||
#[inline(always)]
|
||||
fn ch(self, c: usize) -> f32 {
|
||||
get(&self, c)
|
||||
}
|
||||
#[inline(always)]
|
||||
fn from_ch(f: impl Fn(usize) -> f32) -> Self {
|
||||
[f(0), f(1)]
|
||||
}
|
||||
}
|
||||
|
||||
/// The bits of 1.0 and of +0.0: the alphas a grey image can have.
|
||||
const ONE_BITS: u32 = 0x3f80_0000;
|
||||
const ZERO_BITS: u32 = 0;
|
||||
|
||||
/// The alpha of `p` when it is grey bit for bit (the same three colour channels) with an alpha of exactly 1 or +0.
|
||||
#[inline(always)]
|
||||
pub fn grey_alpha(p: [f32; 4]) -> Option<f32> {
|
||||
let grey = p[0].to_bits() == p[1].to_bits() && p[1].to_bits() == p[2].to_bits();
|
||||
(grey && matches!(p[3].to_bits(), ONE_BITS | ZERO_BITS)).then_some(p[3])
|
||||
}
|
||||
|
||||
/// Whether `a` is an alpha a grey image holds (exactly 1 or +0).
|
||||
#[inline(always)]
|
||||
pub fn grey_alpha_ok(a: f32) -> bool {
|
||||
matches!(a.to_bits(), ONE_BITS | ZERO_BITS)
|
||||
}
|
||||
|
||||
impl Grey {
|
||||
/// As an RGBA image: each pixel `[v, v, v, alpha]`.
|
||||
pub fn expand(&self, alpha: f32) -> Tex {
|
||||
let mut px = vec![[0.0f32; 4]; self.px.len()];
|
||||
crate::par::for_each_run_mut(&mut px, 1 << 15, |first, run| {
|
||||
for (i, d) in run.iter_mut().enumerate() {
|
||||
let v = get(&self.px, first + i);
|
||||
*d = [v, v, v, alpha];
|
||||
}
|
||||
});
|
||||
Tex { w: self.w, h: self.h, px }
|
||||
}
|
||||
|
||||
/// `t` as a grey image and its alpha, when every pixel of it is grey with the same alpha of exactly 1 or +0 bit
|
||||
/// for bit ([`grey_alpha`]).
|
||||
pub fn of(t: &Tex) -> Option<(Grey, f32)> {
|
||||
// (the first pixel tells most colour images apart at once)
|
||||
let alpha = match t.px.first() {
|
||||
Some(p) => grey_alpha(*p)?,
|
||||
None => 1.0,
|
||||
};
|
||||
let mut px = vec![0.0f32; t.px.len()];
|
||||
let colour = std::sync::atomic::AtomicBool::new(false);
|
||||
crate::par::for_each_run_mut(&mut px, 1 << 15, |first, run| {
|
||||
for (i, d) in run.iter_mut().enumerate() {
|
||||
let p = t.px_at(first + i);
|
||||
if grey_alpha(p).is_none_or(|a| a.to_bits() != alpha.to_bits()) {
|
||||
colour.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
*d = p[0];
|
||||
}
|
||||
});
|
||||
(!colour.load(std::sync::atomic::Ordering::Relaxed)).then_some((Grey { w: t.w, h: t.h, px }, alpha))
|
||||
}
|
||||
}
|
||||
|
||||
/// floor() without a libm call: the baseline x86-64 target has no SSE4.1 rounding instruction, so `f32::floor` is a
|
||||
/// function call there. Exact for |x| < 2^31 (callers use texture coordinates).
|
||||
#[inline(always)]
|
||||
pub fn ffloor(x: f32) -> f32 {
|
||||
let i = x as i32 as f32;
|
||||
if i > x { i - 1.0 } else { i }
|
||||
}
|
||||
|
||||
/// `f64::floor` without a libm call (see [`ffloor`]), the same for every input: below 2^62 in size by truncation,
|
||||
/// anything else (larger, infinite, NaN) through `floor` itself.
|
||||
#[inline(always)]
|
||||
pub fn floor64(x: f64) -> f64 {
|
||||
if x == 0.0 {
|
||||
// keeps the sign of a zero, as floor() does
|
||||
x
|
||||
} else if x.abs() < 4.611_686_018_427_388e18 {
|
||||
let i = x as i64 as f64;
|
||||
if i > x { i - 1.0 } else { i }
|
||||
} else {
|
||||
x.floor()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lum(p: [f32; 4]) -> f32 {
|
||||
0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]
|
||||
}
|
||||
|
||||
fn san(v: f32) -> f32 {
|
||||
if v.is_finite() { v } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Item `i` of `s`, the default (zero) past its end: an index that can't panic.
|
||||
#[inline(always)]
|
||||
pub fn get<T: Copy + Default>(s: &[T], i: usize) -> T {
|
||||
s.get(i).copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `[f(a[0], b[0]), .. f(a[3], b[3])]`: a per-channel operation on two pixels, without indexing by a variable.
|
||||
#[inline(always)]
|
||||
pub fn zip4<A: Copy, B: Copy, R>(a: [A; 4], b: [B; 4], f: impl Fn(A, B) -> R) -> [R; 4] {
|
||||
[f(a[0], b[0]), f(a[1], b[1]), f(a[2], b[2]), f(a[3], b[3])]
|
||||
}
|
||||
|
||||
impl<P: Pixel> Image<P> {
|
||||
pub fn solid(w: usize, h: usize, c: P) -> Image<P> {
|
||||
Image { w, h, px: vec![c; w * h] }
|
||||
}
|
||||
|
||||
/// Build a texture from a per-pixel function of (u, v) in [0,1). Runs multi-threaded.
|
||||
pub fn from_fn<F: Fn(f32, f32) -> P + Sync>(w: usize, h: usize, f: F) -> Image<P> {
|
||||
Image::from_fn_with(w, h, || (), |_, u, v| f(u, v))
|
||||
}
|
||||
|
||||
/// As [`Tex::from_fn`], with working state: `init` makes it for each band of rows (one per thread), `f` gets it for
|
||||
/// each pixel.
|
||||
/// What a pixel gets must not depend on the pixels computed with the same state before it.
|
||||
pub fn from_fn_with<S, I: Fn() -> S + Sync, F: Fn(&mut S, f32, f32) -> P + Sync>(w: usize, h: usize, init: I, f: F) -> Image<P> {
|
||||
let w = w.max(1);
|
||||
let h = h.max(1);
|
||||
let mut px = vec![P::NONE; w * h];
|
||||
// one band of whole rows per thread: a state can be costly to make (a function's position-independent part
|
||||
// runs once per state), and a cancel check per row
|
||||
let rows_per = h.div_ceil(crate::par::helpers() + 1);
|
||||
let cancel = &crate::context::current_cancel();
|
||||
crate::par::for_each_run_mut(&mut px, rows_per * w, |first, chunk| {
|
||||
let mut state = init();
|
||||
for (i, p) in chunk.iter_mut().enumerate() {
|
||||
if i % w == 0 && crate::context::is_set(cancel) {
|
||||
return;
|
||||
}
|
||||
let idx = first + i;
|
||||
let x = idx % w;
|
||||
let y = idx / w;
|
||||
let o = f(&mut state, (x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32);
|
||||
*p = o.each(san);
|
||||
}
|
||||
});
|
||||
Image { w, h, px }
|
||||
}
|
||||
|
||||
/// Pixel `i` (counted row by row), [`Pixel::NONE`] past the end.
|
||||
#[inline]
|
||||
pub fn px_at(&self, i: usize) -> P {
|
||||
self.px.get(i).copied().unwrap_or(P::NONE)
|
||||
}
|
||||
|
||||
/// Sets pixel `i` (counted row by row); past the end, nothing.
|
||||
#[inline]
|
||||
pub fn set_px(&mut self, i: usize, v: P) {
|
||||
if let Some(p) = self.px.get_mut(i) {
|
||||
*p = v;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn at(&self, x: i64, y: i64) -> P {
|
||||
Texels::at(self, x, y)
|
||||
}
|
||||
|
||||
/// Bilinear, wrapped sampling in uv space.
|
||||
#[inline]
|
||||
pub fn sample(&self, u: f32, v: f32) -> P {
|
||||
Texels::sample(self, u, v)
|
||||
}
|
||||
|
||||
pub fn map<F: Fn(P) -> P + Sync>(&self, f: F) -> Image<P> {
|
||||
let mut out = self.clone();
|
||||
par_rows(&mut out.px, self.w.max(1), |_, chunk| {
|
||||
for p in chunk.iter_mut() {
|
||||
*p = f(*p);
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl Tex {
|
||||
pub fn gray_fn<F: Fn(f32, f32) -> f32 + Sync>(w: usize, h: usize, f: F) -> Tex {
|
||||
Tex::from_fn(w, h, |u, v| {
|
||||
let g = f(u, v);
|
||||
[g, g, g, 1.0]
|
||||
})
|
||||
}
|
||||
|
||||
/// Catmull-Rom (bicubic) wrapped sampling in uv space: sharper than bilinear for rotations, scaling and warps. The
|
||||
/// result stays inside the range of the four nearest texels, so it never overshoots.
|
||||
pub fn sample_cubic(&self, u: f32, v: f32) -> [f32; 4] {
|
||||
let u = if u.is_finite() { u } else { 0.0 };
|
||||
let v = if v.is_finite() { v } else { 0.0 };
|
||||
let x = u * self.w as f32 - 0.5;
|
||||
let y = v * self.h as f32 - 0.5;
|
||||
let (x0, y0) = (ffloor(x), ffloor(y));
|
||||
let (fx, fy) = (x - x0, y - y0);
|
||||
let (xi, yi) = (x0 as i64, y0 as i64);
|
||||
let wts = |t: f32| {
|
||||
[
|
||||
0.5 * (-t * t * t + 2.0 * t * t - t),
|
||||
0.5 * (3.0 * t * t * t - 5.0 * t * t + 2.0),
|
||||
0.5 * (-3.0 * t * t * t + 4.0 * t * t + t),
|
||||
0.5 * (t * t * t - t * t),
|
||||
]
|
||||
};
|
||||
let (wx, wy) = (wts(fx), wts(fy));
|
||||
let mut o = [0.0f32; 4];
|
||||
let inside = xi >= 1 && yi >= 1 && xi + 2 < self.w as i64 && yi + 2 < self.h as i64;
|
||||
for (j, wyj) in wy.iter().enumerate() {
|
||||
for (i, wxi) in wx.iter().enumerate() {
|
||||
let p = if inside {
|
||||
self.px_at((yi as usize + j - 1) * self.w + xi as usize + i - 1)
|
||||
} else {
|
||||
self.at(xi + i as i64 - 1, yi + j as i64 - 1)
|
||||
};
|
||||
let w = wxi * wyj;
|
||||
for (o, p) in o.iter_mut().zip(p) {
|
||||
*o += p * w;
|
||||
}
|
||||
}
|
||||
}
|
||||
let n = [self.at(xi, yi), self.at(xi + 1, yi), self.at(xi, yi + 1), self.at(xi + 1, yi + 1)];
|
||||
for (c, o) in o.iter_mut().enumerate() {
|
||||
let lo = n.iter().map(|p| get(p, c)).fold(f32::MAX, f32::min);
|
||||
let hi = n.iter().map(|p| get(p, c)).fold(f32::MIN, f32::max);
|
||||
// A channel that is NaN in all four texels has no bounds (the folds keep MAX and MIN): leave it as is.
|
||||
if lo <= hi {
|
||||
*o = o.clamp(lo, hi);
|
||||
}
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
pub fn gray_at(&self, x: i64, y: i64) -> f32 {
|
||||
lum(self.at(x, y))
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f(first_index, chunk)` on consecutive pieces of `px` in parallel. Pieces are 16 whole rows of width `w`, and a
|
||||
/// cancelled evaluation stops between pieces, so it gives the CPU back quickly.
|
||||
pub fn par_rows<T: Send, F: Fn(usize, &mut [T]) + Sync>(px: &mut [T], w: usize, f: F) {
|
||||
let cancel = &crate::context::current_cancel();
|
||||
crate::par::for_each_run_mut(px, w.max(1) * 16, |first, piece| {
|
||||
if !crate::context::is_set(cancel) {
|
||||
f(first, piece);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Parallel map over 0..n, preserving order.
|
||||
pub fn par_map<T: Send + Default + Clone, F: Fn(usize) -> T + Sync>(n: usize, f: F) -> Vec<T> {
|
||||
let mut out = vec![T::default(); n];
|
||||
if n == 0 {
|
||||
return out;
|
||||
}
|
||||
let cancel = &crate::context::current_cancel();
|
||||
// runs of at most 4096 items, so a cancelled evaluation stops soon
|
||||
let run = n.div_ceil((crate::par::helpers() + 1) * 4).clamp(1, 4096);
|
||||
crate::par::for_each_run_mut(&mut out, run, |first, chunk| {
|
||||
if crate::context::is_set(cancel) {
|
||||
return;
|
||||
}
|
||||
for (i, slot) in chunk.iter_mut().enumerate() {
|
||||
*slot = f(first + i);
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod fast_path_tests {
|
||||
use super::*;
|
||||
|
||||
/// Values around every kind of edge: zeros of both signs, halves, integers, the cast's limits, specials, and a sweep.
|
||||
fn edges() -> Vec<f64> {
|
||||
let mut v = vec![
|
||||
0.0,
|
||||
-0.0,
|
||||
0.5,
|
||||
-0.5,
|
||||
1.0,
|
||||
-1.0,
|
||||
1e-300,
|
||||
-1e-300,
|
||||
f64::MIN_POSITIVE,
|
||||
f64::EPSILON,
|
||||
4.5e15,
|
||||
-4.5e15,
|
||||
4.611_686_018_427_388e18,
|
||||
-9.3e18,
|
||||
1e300,
|
||||
-1e300,
|
||||
];
|
||||
v.extend([f64::INFINITY, f64::NEG_INFINITY, f64::NAN, f64::MAX, f64::MIN]);
|
||||
for k in -70i32..70 {
|
||||
let p = crate::math::powi(2f64, k);
|
||||
v.extend([p, -p, p + 0.5, -p - 0.5, p.next_up(), p.next_down(), -p.next_up(), -p.next_down()]);
|
||||
}
|
||||
let mut x = 0x1234_5678_9abc_def0u64;
|
||||
for _ in 0..200_000 {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 7;
|
||||
x ^= x << 17;
|
||||
v.push(f64::from_bits(x));
|
||||
v.push((x >> 11) as f64 / (1u64 << 40) as f64 - 4096.0);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floor64_is_floor_bit_for_bit() {
|
||||
for x in edges() {
|
||||
assert_eq!(floor64(x).to_bits(), x.floor().to_bits(), "{x:e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cubic_sampling_a_nan_channel_does_not_panic() {
|
||||
let t = Tex::solid(1, 1, [f32::NAN, 0.5, 0.5, 1.0]);
|
||||
let o = t.sample_cubic(0.3, 0.7);
|
||||
assert!(o[0].is_nan());
|
||||
assert_eq!(o[1], 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tex_at_wraps_as_rem_euclid() {
|
||||
let t = Tex::from_fn(5, 3, |u, v| [u, v, u * v, 1.0]);
|
||||
for y in -7..8i64 {
|
||||
for x in -11..12i64 {
|
||||
assert_eq!(t.at(x, y), t.px[y.rem_euclid(3) as usize * 5 + x.rem_euclid(5) as usize], "{x} {y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Images read pixel by pixel: [`Image`]s, and grey images held in steps ([`Grey16`]) read as their values. The reads
|
||||
/// here are the same arithmetic for every kind.
|
||||
pub trait Texels: Sync {
|
||||
type P: Pixel;
|
||||
fn width(&self) -> usize;
|
||||
fn height(&self) -> usize;
|
||||
/// Pixel `i` (counted row by row), [`Pixel::NONE`] past the end.
|
||||
fn texel(&self, i: usize) -> Self::P;
|
||||
|
||||
/// Pixel (x, y), wrapped.
|
||||
fn at(&self, x: i64, y: i64) -> Self::P {
|
||||
// a branch instead of a division when the pixel is inside, as most are
|
||||
let wrap = |i: i64, n: usize| if i >= 0 && (i as usize) < n { i as usize } else { i.rem_euclid((n as i64).max(1)) as usize };
|
||||
self.texel(wrap(y, self.height()) * self.width() + wrap(x, self.width()))
|
||||
}
|
||||
|
||||
/// Bilinear, wrapped sampling in uv space.
|
||||
#[inline]
|
||||
fn sample(&self, u: f32, v: f32) -> Self::P {
|
||||
let u = if u.is_finite() { u } else { 0.0 };
|
||||
let v = if v.is_finite() { v } else { 0.0 };
|
||||
let x = u * self.width() as f32 - 0.5;
|
||||
let y = v * self.height() as f32 - 0.5;
|
||||
let x0 = ffloor(x);
|
||||
let y0 = ffloor(y);
|
||||
let fx = x - x0;
|
||||
let fy = y - y0;
|
||||
let (w, h) = (self.width() as i64, self.height() as i64);
|
||||
// wrap the two columns and the two rows once (a branch instead of a division in the common case)
|
||||
let wrap = |i: i64, n: i64| if i >= 0 && i < n { i } else { i.rem_euclid(n.max(1)) };
|
||||
let (xa, ya) = (wrap(x0 as i64, w), wrap(y0 as i64, h));
|
||||
let xb = if xa + 1 == w { 0 } else { xa + 1 };
|
||||
let yb = if ya + 1 == h { 0 } else { ya + 1 };
|
||||
let (r0, r1) = ((ya * w) as usize, (yb * w) as usize);
|
||||
let a = self.texel(r0 + xa as usize);
|
||||
let b = self.texel(r0 + xb as usize);
|
||||
let c = self.texel(r1 + xa as usize);
|
||||
let d = self.texel(r1 + xb as usize);
|
||||
let top = a.zip(b, |a, b| a + (b - a) * fx);
|
||||
let bot = c.zip(d, |c, d| c + (d - c) * fx);
|
||||
top.zip(bot, |top, bot| top + (bot - top) * fy)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel> Texels for Image<P> {
|
||||
type P = P;
|
||||
#[inline(always)]
|
||||
fn width(&self) -> usize {
|
||||
self.w
|
||||
}
|
||||
#[inline(always)]
|
||||
fn height(&self) -> usize {
|
||||
self.h
|
||||
}
|
||||
#[inline(always)]
|
||||
fn texel(&self, i: usize) -> P {
|
||||
self.px_at(i)
|
||||
}
|
||||
}
|
||||
|
||||
impl Texels for Grey16 {
|
||||
type P = f32;
|
||||
#[inline(always)]
|
||||
fn width(&self) -> usize {
|
||||
self.w
|
||||
}
|
||||
#[inline(always)]
|
||||
fn height(&self) -> usize {
|
||||
self.h
|
||||
}
|
||||
#[inline(always)]
|
||||
fn texel(&self, i: usize) -> f32 {
|
||||
match self.px.get(i) {
|
||||
Some(k) => f32::from(*k) / self.div,
|
||||
None => 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A grey image held in whole steps: pixel `k` is the grey value `k as f32 / div` (an image quantised to 8 or 16 bits
|
||||
/// holds nothing else, so it is kept in a eighth of the memory of RGBA floats), its alpha `alpha` (1 or +0).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Grey16 {
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
pub px: Vec<u16>,
|
||||
pub div: f32,
|
||||
pub alpha: f32,
|
||||
}
|
||||
|
||||
impl Grey16 {
|
||||
/// `g` in steps of `1 / div`, when every value of it is exactly `k as f32 / div` for a whole `k` (bit for bit).
|
||||
pub(crate) fn of(g: &Grey, alpha: f32, div: f32) -> Option<Grey16> {
|
||||
let mut px = vec![0u16; g.px.len()];
|
||||
let inexact = std::sync::atomic::AtomicBool::new(false);
|
||||
crate::par::for_each_run_mut(&mut px, 1 << 15, |first, run| {
|
||||
for (i, d) in run.iter_mut().enumerate() {
|
||||
let v = get(&g.px, first + i);
|
||||
let k = (v * div).round();
|
||||
let q = if (0.0..=65535.0).contains(&k) { k as u16 } else { 0 };
|
||||
if !(0.0..=65535.0).contains(&k) || (f32::from(q) / div).to_bits() != v.to_bits() {
|
||||
inexact.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
*d = q;
|
||||
}
|
||||
});
|
||||
(!inexact.load(std::sync::atomic::Ordering::Relaxed)).then_some(Grey16 { w: g.w, h: g.h, px, div, alpha })
|
||||
}
|
||||
|
||||
/// The grey values.
|
||||
pub(crate) fn widen(&self) -> Grey {
|
||||
let mut px = vec![0.0f32; self.px.len()];
|
||||
let div = self.div;
|
||||
crate::par::for_each_run_mut(&mut px, 1 << 15, |first, run| {
|
||||
for (i, d) in run.iter_mut().enumerate() {
|
||||
*d = f32::from(get(&self.px, first + i)) / div;
|
||||
}
|
||||
});
|
||||
Grey { w: self.w, h: self.h, px }
|
||||
}
|
||||
|
||||
/// As an RGBA image: each pixel `[v, v, v, alpha]`.
|
||||
pub(crate) fn expand(&self) -> Tex {
|
||||
let mut px = vec![[0.0f32; 4]; self.px.len()];
|
||||
let (div, alpha) = (self.div, self.alpha);
|
||||
crate::par::for_each_run_mut(&mut px, 1 << 15, |first, run| {
|
||||
for (i, d) in run.iter_mut().enumerate() {
|
||||
let v = f32::from(get(&self.px, first + i)) / div;
|
||||
*d = [v, v, v, alpha];
|
||||
}
|
||||
});
|
||||
Tex { w: self.w, h: self.h, px }
|
||||
}
|
||||
}
|
||||
|
||||
/// A node result as the runtime holds it: RGBA, or grey (a quarter of the memory) when every pixel is grey with one
|
||||
/// alpha of 1 or +0, in whole 8- or 16-bit steps (an eighth) when its format quantises it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum Val {
|
||||
Rgba(std::sync::Arc<Tex>),
|
||||
/// grey values and their alpha
|
||||
Grey(std::sync::Arc<Grey>, f32),
|
||||
Grey16(std::sync::Arc<Grey16>),
|
||||
}
|
||||
|
||||
impl Val {
|
||||
/// `t`, held grey when it is grey bit for bit.
|
||||
pub(crate) fn of(t: Tex) -> Val {
|
||||
match Grey::of(&t) {
|
||||
Some((g, a)) => Val::Grey(std::sync::Arc::new(g), a),
|
||||
None => Val::Rgba(std::sync::Arc::new(t)),
|
||||
}
|
||||
}
|
||||
|
||||
/// As an RGBA image (a grey one expanded: a new image).
|
||||
pub(crate) fn tex(&self) -> std::sync::Arc<Tex> {
|
||||
match self {
|
||||
Val::Rgba(t) => t.clone(),
|
||||
Val::Grey(g, a) => std::sync::Arc::new(g.expand(*a)),
|
||||
Val::Grey16(g) => std::sync::Arc::new(g.expand()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Held in steps of `1 / div` when it is grey and exactly that; else as it is.
|
||||
pub(crate) fn quantised(self, div: f32) -> Val {
|
||||
match &self {
|
||||
Val::Grey(g, a) => match Grey16::of(g, *a, div) {
|
||||
Some(q) => Val::Grey16(std::sync::Arc::new(q)),
|
||||
None => self,
|
||||
},
|
||||
_ => self,
|
||||
}
|
||||
}
|
||||
|
||||
/// As an RGBA image, without a copy when nothing else holds it.
|
||||
pub(crate) fn into_tex(self) -> Tex {
|
||||
match self {
|
||||
Val::Rgba(t) => std::sync::Arc::try_unwrap(t).unwrap_or_else(|rc| (*rc).clone()),
|
||||
Val::Grey(g, a) => g.expand(a),
|
||||
Val::Grey16(g) => g.expand(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn dims(&self) -> (usize, usize) {
|
||||
match self {
|
||||
Val::Rgba(t) => (t.w, t.h),
|
||||
Val::Grey(g, _) => (g.w, g.h),
|
||||
Val::Grey16(g) => (g.w, g.h),
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes of pixels held.
|
||||
pub(crate) fn bytes(&self) -> usize {
|
||||
match self {
|
||||
Val::Rgba(t) => t.px.len() * 16,
|
||||
Val::Grey(g, _) => g.px.len() * 4,
|
||||
Val::Grey16(g) => g.px.len() * 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// As an image a function reads.
|
||||
pub(crate) fn img_ref(&self) -> ImgRef<'_> {
|
||||
match self {
|
||||
Val::Rgba(t) => ImgRef::Rgba(t),
|
||||
Val::Grey(g, a) => ImgRef::Grey(GreyIn::F(g, *a)),
|
||||
Val::Grey16(g) => ImgRef::Grey(GreyIn::Q(g)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The grey values and alpha, however they are held; `None` for RGBA.
|
||||
pub(crate) fn grey_in(&self) -> Option<GreyIn<'_>> {
|
||||
match self {
|
||||
Val::Grey(g, a) => Some(GreyIn::F(g, *a)),
|
||||
Val::Grey16(g) => Some(GreyIn::Q(g)),
|
||||
Val::Rgba(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An image a function reads: RGBA, or grey (read as `[v, v, v, alpha]`, the same values the expanded image gives).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum ImgRef<'a> {
|
||||
Rgba(&'a Tex),
|
||||
Grey(GreyIn<'a>),
|
||||
}
|
||||
|
||||
impl<'a> From<&'a Tex> for ImgRef<'a> {
|
||||
fn from(t: &'a Tex) -> ImgRef<'a> {
|
||||
ImgRef::Rgba(t)
|
||||
}
|
||||
}
|
||||
|
||||
impl ImgRef<'_> {
|
||||
pub fn w(&self) -> usize {
|
||||
match self {
|
||||
ImgRef::Rgba(t) => t.w,
|
||||
ImgRef::Grey(t) => t.width(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn h(&self) -> usize {
|
||||
match self {
|
||||
ImgRef::Rgba(t) => t.h,
|
||||
ImgRef::Grey(t) => t.height(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pixel (x, y), wrapped: [`Image::at`].
|
||||
pub fn at(&self, x: i64, y: i64) -> [f32; 4] {
|
||||
match self {
|
||||
ImgRef::Rgba(t) => t.at(x, y),
|
||||
ImgRef::Grey(t) => t.with_alpha(Texels::at(t, x, y)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Bilinear, wrapped: [`Image::sample`].
|
||||
pub fn sample(&self, u: f32, v: f32) -> [f32; 4] {
|
||||
match self {
|
||||
ImgRef::Rgba(t) => t.sample(u, v),
|
||||
ImgRef::Grey(t) => t.with_alpha(Texels::sample(t, u, v)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every pixel in order, as RGBA.
|
||||
pub fn for_each_px(&self, mut f: impl FnMut([f32; 4])) {
|
||||
match self {
|
||||
ImgRef::Rgba(t) => t.px.iter().for_each(|p| f(*p)),
|
||||
ImgRef::Grey(t) => (0..t.len()).for_each(|i| f(t.with_alpha(t.texel(i)))),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
match self {
|
||||
ImgRef::Rgba(t) => t.px.len(),
|
||||
ImgRef::Grey(t) => t.len(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
}
|
||||
|
||||
/// A grey image as held: floats (with their alpha), or steps.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum GreyIn<'a> {
|
||||
F(&'a Grey, f32),
|
||||
Q(&'a Grey16),
|
||||
}
|
||||
|
||||
impl GreyIn<'_> {
|
||||
pub fn len(&self) -> usize {
|
||||
match self {
|
||||
GreyIn::F(g, _) => g.px.len(),
|
||||
GreyIn::Q(g) => g.px.len(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
|
||||
/// Its alpha: 1 or +0.
|
||||
pub fn alpha(&self) -> f32 {
|
||||
match self {
|
||||
GreyIn::F(_, a) => *a,
|
||||
GreyIn::Q(g) => g.alpha,
|
||||
}
|
||||
}
|
||||
|
||||
/// Grey value `v` as an RGBA pixel of this image.
|
||||
#[inline(always)]
|
||||
pub fn with_alpha(&self, v: f32) -> [f32; 4] {
|
||||
[v, v, v, self.alpha()]
|
||||
}
|
||||
|
||||
/// As floats (a new image when held in steps).
|
||||
pub fn floats(&self) -> std::borrow::Cow<'_, Grey> {
|
||||
match self {
|
||||
GreyIn::F(g, _) => std::borrow::Cow::Borrowed(*g),
|
||||
GreyIn::Q(g) => std::borrow::Cow::Owned(g.widen()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Texels for GreyIn<'_> {
|
||||
type P = f32;
|
||||
#[inline(always)]
|
||||
fn width(&self) -> usize {
|
||||
match self {
|
||||
GreyIn::F(g, _) => g.w,
|
||||
GreyIn::Q(g) => g.w,
|
||||
}
|
||||
}
|
||||
#[inline(always)]
|
||||
fn height(&self) -> usize {
|
||||
match self {
|
||||
GreyIn::F(g, _) => g.h,
|
||||
GreyIn::Q(g) => g.h,
|
||||
}
|
||||
}
|
||||
#[inline(always)]
|
||||
fn texel(&self, i: usize) -> f32 {
|
||||
match self {
|
||||
GreyIn::F(g, _) => g.px_at(i),
|
||||
GreyIn::Q(g) => g.texel(i),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a node holds its values when its format is whole 8- or 16-bit steps: each value read-rounded (warps), through
|
||||
/// the format, and kept as the step `k` of `k as f32 / div` it is exactly.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Steps {
|
||||
pub read_rounding: bool,
|
||||
pub fmt: u32,
|
||||
pub div: f32,
|
||||
}
|
||||
|
||||
impl Steps {
|
||||
/// The step of value `v` as the node holds it; `None` when that value is no whole step.
|
||||
#[inline]
|
||||
pub(crate) fn step(&self, v: f32) -> Option<u16> {
|
||||
let v = if self.read_rounding { crate::ops::read_rounded(v) } else { v };
|
||||
let v = crate::ops::format_value(v, self.fmt);
|
||||
let k = (v * self.div).round();
|
||||
if !(0.0..=65535.0).contains(&k) {
|
||||
return None;
|
||||
}
|
||||
let q = k as u16;
|
||||
((f32::from(q) / self.div).to_bits() == v.to_bits()).then_some(q)
|
||||
}
|
||||
}
|
||||
|
||||
/// A grey result: floats (with its alpha), or steps already through the node's format.
|
||||
pub(crate) enum GreyOut {
|
||||
F(Grey, f32),
|
||||
Q(Grey16),
|
||||
}
|
||||
|
||||
/// The pixels `pixel(i)` (value, alpha) of a `w` x `h` image, spread over the cores in pieces of rows, as a grey image:
|
||||
/// `None` when the alphas are not all 1 or all +0. With `steps`, held in steps when every value is one (else as floats).
|
||||
pub(crate) fn fill_grey(w: usize, h: usize, pixel: impl Fn(usize) -> (f32, f32) + Sync, steps: Option<&Steps>) -> Option<GreyOut> {
|
||||
use std::sync::atomic::{AtomicU8, Ordering::Relaxed};
|
||||
const OPAQUE: u8 = 1;
|
||||
const TRANSPARENT: u8 = 2;
|
||||
const OTHER_ALPHA: u8 = 4;
|
||||
const OFF_STEP: u8 = 8;
|
||||
let flags = AtomicU8::new(0);
|
||||
let alpha_flag = |a: f32| match a.to_bits() {
|
||||
ONE_BITS => OPAQUE,
|
||||
ZERO_BITS => TRANSPARENT,
|
||||
_ => OTHER_ALPHA,
|
||||
};
|
||||
let alpha = || match flags.load(Relaxed) {
|
||||
0 | OPAQUE => Some(1.0),
|
||||
TRANSPARENT => Some(0.0),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(st) = steps {
|
||||
let mut px = vec![0u16; w * h];
|
||||
par_rows(&mut px, w, |start, chunk| {
|
||||
let mut local = 0;
|
||||
for (j, d) in chunk.iter_mut().enumerate() {
|
||||
let (v, a) = pixel(start + j);
|
||||
let Some(q) = st.step(v) else {
|
||||
flags.fetch_or(OFF_STEP, Relaxed);
|
||||
return;
|
||||
};
|
||||
*d = q;
|
||||
local |= alpha_flag(a);
|
||||
}
|
||||
flags.fetch_or(local, Relaxed);
|
||||
});
|
||||
if flags.load(Relaxed) & OFF_STEP == 0 {
|
||||
let a = alpha()?;
|
||||
return Some(GreyOut::Q(Grey16 { w, h, px, div: st.div, alpha: a }));
|
||||
}
|
||||
flags.store(0, Relaxed);
|
||||
}
|
||||
let mut px = vec![0.0f32; w * h];
|
||||
par_rows(&mut px, w, |start, chunk| {
|
||||
let mut local = 0;
|
||||
for (j, d) in chunk.iter_mut().enumerate() {
|
||||
let (v, a) = pixel(start + j);
|
||||
*d = v;
|
||||
local |= alpha_flag(a);
|
||||
}
|
||||
flags.fetch_or(local, Relaxed);
|
||||
});
|
||||
let a = alpha()?;
|
||||
Some(GreyOut::F(Grey { w, h, px }, a))
|
||||
}
|
||||
|
||||
/// [`Image::from_fn_with`] for a grey image of alpha 1, held in `steps` when every value is one (else as floats): the
|
||||
/// same pieces, states and values.
|
||||
pub(crate) fn grey_from_fn_with<S, I: Fn() -> S + Sync, F: Fn(&mut S, f32, f32) -> f32 + Sync>(
|
||||
w: usize,
|
||||
h: usize,
|
||||
init: I,
|
||||
f: F,
|
||||
steps: Option<&Steps>,
|
||||
) -> GreyOut {
|
||||
use std::sync::atomic::{AtomicBool, Ordering::Relaxed};
|
||||
let (w, h) = (w.max(1), h.max(1));
|
||||
if let Some(st) = steps {
|
||||
let off = AtomicBool::new(false);
|
||||
let mut px = vec![0u16; w * h];
|
||||
let rows_per = h.div_ceil(crate::par::helpers() + 1);
|
||||
let cancel = &crate::context::current_cancel();
|
||||
crate::par::for_each_run_mut(&mut px, rows_per * w, |first, chunk| {
|
||||
let mut state = init();
|
||||
for (i, p) in chunk.iter_mut().enumerate() {
|
||||
if i % w == 0 && (crate::context::is_set(cancel) || off.load(Relaxed)) {
|
||||
return;
|
||||
}
|
||||
let idx = first + i;
|
||||
let (x, y) = (idx % w, idx / w);
|
||||
let v = san(f(&mut state, (x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32));
|
||||
match st.step(v) {
|
||||
Some(q) => *p = q,
|
||||
None => {
|
||||
off.store(true, Relaxed);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if !off.load(Relaxed) {
|
||||
return GreyOut::Q(Grey16 { w, h, px, div: st.div, alpha: 1.0 });
|
||||
}
|
||||
}
|
||||
GreyOut::F(Grey::from_fn_with(w, h, init, f), 1.0)
|
||||
}
|
||||
|
||||
/// Where a kernel puts the pixels `f(u, v)` of its `w` x `h` result: an image of them ([`Image::from_fn`]), or a grey
|
||||
/// image in steps ([`grey_from_fn_with`]).
|
||||
pub(crate) trait Emit<P> {
|
||||
type Out;
|
||||
fn emit<F: Fn(f32, f32) -> P + Sync>(self, w: usize, h: usize, f: F) -> Self::Out;
|
||||
}
|
||||
|
||||
/// [`Emit`] into an [`Image`].
|
||||
pub(crate) struct ToImage;
|
||||
|
||||
impl<P: Pixel> Emit<P> for ToImage {
|
||||
type Out = Image<P>;
|
||||
fn emit<F: Fn(f32, f32) -> P + Sync>(self, w: usize, h: usize, f: F) -> Image<P> {
|
||||
Image::from_fn(w, h, f)
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Emit`] into a grey image of alpha 1, in steps where it can.
|
||||
pub(crate) struct ToSteps<'a>(pub Option<&'a Steps>);
|
||||
|
||||
impl Emit<f32> for ToSteps<'_> {
|
||||
type Out = GreyOut;
|
||||
fn emit<F: Fn(f32, f32) -> f32 + Sync>(self, w: usize, h: usize, f: F) -> GreyOut {
|
||||
grey_from_fn_with(w, h, || (), |_, u, v| f(u, v), self.0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,969 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Vector graphics: path flattening, an anti-aliased scanline filler, simple strokes and a reader for a practical
|
||||
//! subset of SVG (shapes, paths, transforms, solid fill and stroke colours).
|
||||
//!
|
||||
//! Not supported: gradients, patterns, clipping, masks, filters, text elements, `use` references and CSS style sheets.
|
||||
//! Unsupported parts are skipped, never an error. Stroke joins are always round, caps are butt.
|
||||
|
||||
use crate::math;
|
||||
use crate::tex::Tex;
|
||||
|
||||
pub type P = [f32; 2];
|
||||
|
||||
/// Affine transform [a b c d e f]: x' = a x + c y + e, y' = b x + d y + f.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Xf(pub [f32; 6]);
|
||||
|
||||
impl Xf {
|
||||
pub const ID: Xf = Xf([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
|
||||
pub fn then(self, o: Xf) -> Xf {
|
||||
// self applied first, then o
|
||||
let (a, b) = (self.0, o.0);
|
||||
Xf([
|
||||
b[0] * a[0] + b[2] * a[1],
|
||||
b[1] * a[0] + b[3] * a[1],
|
||||
b[0] * a[2] + b[2] * a[3],
|
||||
b[1] * a[2] + b[3] * a[3],
|
||||
b[0] * a[4] + b[2] * a[5] + b[4],
|
||||
b[1] * a[4] + b[3] * a[5] + b[5],
|
||||
])
|
||||
}
|
||||
pub fn apply(&self, p: P) -> P {
|
||||
let m = self.0;
|
||||
[m[0] * p[0] + m[2] * p[1] + m[4], m[1] * p[0] + m[3] * p[1] + m[5]]
|
||||
}
|
||||
pub fn translate(x: f32, y: f32) -> Xf {
|
||||
Xf([1.0, 0.0, 0.0, 1.0, x, y])
|
||||
}
|
||||
pub fn scale(x: f32, y: f32) -> Xf {
|
||||
Xf([x, 0.0, 0.0, y, 0.0, 0.0])
|
||||
}
|
||||
pub fn rotate(rad: f32) -> Xf {
|
||||
let (s, c) = math::sin_cos(rad);
|
||||
Xf([c, s, -s, c, 0.0, 0.0])
|
||||
}
|
||||
/// average scale factor, used to scale stroke widths
|
||||
pub fn mean_scale(&self) -> f32 {
|
||||
let m = self.0;
|
||||
(m[0] * m[3] - m[1] * m[2]).abs().sqrt()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Seg {
|
||||
Move(P),
|
||||
Line(P),
|
||||
Quad(P, P),
|
||||
Cubic(P, P, P),
|
||||
Close,
|
||||
}
|
||||
|
||||
/// A closed or open polyline.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Poly {
|
||||
pub pts: Vec<P>,
|
||||
pub closed: bool,
|
||||
}
|
||||
|
||||
/// Flatten segments into polylines; curves are split until they are within about 0.1 pixel.
|
||||
pub fn flatten(segs: &[Seg], xf: &Xf) -> Vec<Poly> {
|
||||
let mut out: Vec<Poly> = Vec::new();
|
||||
let mut cur: Vec<P> = Vec::new();
|
||||
let mut start = [0.0f32; 2];
|
||||
let mut last = [0.0f32; 2];
|
||||
let flush = |cur: &mut Vec<P>, out: &mut Vec<Poly>, closed: bool| {
|
||||
if cur.len() >= 2 || (closed && !cur.is_empty()) {
|
||||
out.push(Poly { pts: std::mem::take(cur), closed });
|
||||
} else {
|
||||
cur.clear();
|
||||
}
|
||||
};
|
||||
for s in segs {
|
||||
match *s {
|
||||
Seg::Move(p) => {
|
||||
flush(&mut cur, &mut out, false);
|
||||
let q = xf.apply(p);
|
||||
cur.push(q);
|
||||
start = q;
|
||||
last = q;
|
||||
}
|
||||
Seg::Line(p) => {
|
||||
let q = xf.apply(p);
|
||||
if cur.is_empty() {
|
||||
cur.push(last);
|
||||
}
|
||||
cur.push(q);
|
||||
last = q;
|
||||
}
|
||||
Seg::Quad(c, p) => {
|
||||
let (c, p) = (xf.apply(c), xf.apply(p));
|
||||
if cur.is_empty() {
|
||||
cur.push(last);
|
||||
}
|
||||
let c1 = [last[0] + 2.0 / 3.0 * (c[0] - last[0]), last[1] + 2.0 / 3.0 * (c[1] - last[1])];
|
||||
let c2 = [p[0] + 2.0 / 3.0 * (c[0] - p[0]), p[1] + 2.0 / 3.0 * (c[1] - p[1])];
|
||||
cubic(last, c1, c2, p, &mut cur);
|
||||
last = p;
|
||||
}
|
||||
Seg::Cubic(a, b, p) => {
|
||||
let (a, b, p) = (xf.apply(a), xf.apply(b), xf.apply(p));
|
||||
if cur.is_empty() {
|
||||
cur.push(last);
|
||||
}
|
||||
cubic(last, a, b, p, &mut cur);
|
||||
last = p;
|
||||
}
|
||||
Seg::Close => {
|
||||
flush(&mut cur, &mut out, true);
|
||||
last = start;
|
||||
}
|
||||
}
|
||||
}
|
||||
flush(&mut cur, &mut out, false);
|
||||
out
|
||||
}
|
||||
|
||||
fn cubic(p0: P, p1: P, p2: P, p3: P, out: &mut Vec<P>) {
|
||||
// number of pieces from the control polygon length
|
||||
let d = |a: P, b: P| (math::powi(a[0] - b[0], 2) + math::powi(a[1] - b[1], 2)).sqrt();
|
||||
let len = d(p0, p1) + d(p1, p2) + d(p2, p3);
|
||||
let n = ((len * 0.5).sqrt() * 1.5).ceil().clamp(2.0, 200.0) as usize;
|
||||
for i in 1..=n {
|
||||
let t = i as f32 / n as f32;
|
||||
let u = 1.0 - t;
|
||||
let (a, b, c, e) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
|
||||
out.push([a * p0[0] + b * p1[0] + c * p2[0] + e * p3[0], a * p0[1] + b * p1[1] + c * p2[1] + e * p3[1]]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Anti-aliased coverage mask.
|
||||
pub struct Mask {
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
pub a: Vec<f32>,
|
||||
}
|
||||
|
||||
const SUB: usize = 4;
|
||||
|
||||
/// Fill polygons. `even_odd` selects the fill rule (otherwise non-zero winding).
|
||||
pub fn fill(polys: &[Poly], w: usize, h: usize, even_odd: bool) -> Mask {
|
||||
let mut m = Mask { w, h, a: vec![0.0; w * h] };
|
||||
// edges (x0, y0, x1, y1, dir) with y0 < y1
|
||||
let mut edges: Vec<(f32, f32, f32, f32, i32)> = Vec::new();
|
||||
for p in polys {
|
||||
let n = p.pts.len();
|
||||
if n < 2 {
|
||||
continue;
|
||||
}
|
||||
for (&a, &b) in p.pts.iter().zip(p.pts.iter().cycle().skip(1)) {
|
||||
if !(a[0].is_finite() && a[1].is_finite() && b[0].is_finite() && b[1].is_finite()) {
|
||||
continue;
|
||||
}
|
||||
if (a[1] - b[1]).abs() < 1e-9 {
|
||||
continue;
|
||||
}
|
||||
if a[1] < b[1] {
|
||||
edges.push((a[0], a[1], b[0], b[1], 1));
|
||||
} else {
|
||||
edges.push((b[0], b[1], a[0], a[1], -1));
|
||||
}
|
||||
}
|
||||
}
|
||||
if edges.is_empty() {
|
||||
return m;
|
||||
}
|
||||
edges.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
|
||||
let mut cross: Vec<(f32, i32)> = Vec::new();
|
||||
let mut active: Vec<usize> = Vec::new();
|
||||
let mut next = 0usize;
|
||||
let weight = 1.0 / SUB as f32;
|
||||
for row in 0..h {
|
||||
for s in 0..SUB {
|
||||
let y = row as f32 + (s as f32 + 0.5) / SUB as f32;
|
||||
while edges.get(next).is_some_and(|e| e.1 <= y) {
|
||||
active.push(next);
|
||||
next += 1;
|
||||
}
|
||||
active.retain(|&e| edges.get(e).is_some_and(|e| e.3 > y));
|
||||
cross.clear();
|
||||
for &e in &active {
|
||||
let Some(&(x0, y0, x1, y1, d)) = edges.get(e) else { continue };
|
||||
cross.push((x0 + (x1 - x0) * (y - y0) / (y1 - y0), d));
|
||||
}
|
||||
cross.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
|
||||
let mut wind = 0i32;
|
||||
for (i, &(xa, ci)) in cross.iter().enumerate() {
|
||||
let before = wind;
|
||||
wind += ci;
|
||||
let inside_before = if even_odd { before & 1 != 0 } else { before != 0 };
|
||||
let inside_after = if even_odd { wind & 1 != 0 } else { wind != 0 };
|
||||
if !inside_before && inside_after {
|
||||
// span starts here; find where it ends
|
||||
let mut w2 = wind;
|
||||
let mut j = i + 1;
|
||||
while let Some(&(_, cj)) = cross.get(j) {
|
||||
w2 += cj;
|
||||
let inside = if even_odd { w2 & 1 != 0 } else { w2 != 0 };
|
||||
if !inside {
|
||||
break;
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
let xb = cross.get(j).map_or(w as f32, |c| c.0);
|
||||
if let Some(r) = m.a.get_mut(row * w..(row + 1) * w) {
|
||||
add_span(r, xa, xb, weight);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for v in m.a.iter_mut() {
|
||||
*v = v.min(1.0);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
fn add_span(row: &mut [f32], xa: f32, xb: f32, weight: f32) {
|
||||
let w = row.len() as f32;
|
||||
let (xa, xb) = (xa.clamp(0.0, w), xb.clamp(0.0, w));
|
||||
if xb <= xa {
|
||||
return;
|
||||
}
|
||||
let (ia, ib) = (xa.floor() as usize, (xb.ceil() as usize).min(row.len()));
|
||||
for (i, px) in row.iter_mut().enumerate().take(ib).skip(ia) {
|
||||
let l = (xa.max(i as f32)).min(xb);
|
||||
let r = (xb.min(i as f32 + 1.0)).max(xa);
|
||||
*px += (r - l).max(0.0) * weight;
|
||||
}
|
||||
}
|
||||
|
||||
/// Outline of a stroked polyline as a set of consistently wound polygons (quads for the segments, discs at the joints).
|
||||
pub fn stroke(polys: &[Poly], width: f32) -> Vec<Poly> {
|
||||
let hw = (width * 0.5).max(0.01);
|
||||
let mut out = Vec::new();
|
||||
let disc = |c: P, out: &mut Vec<Poly>| {
|
||||
let n = ((hw * 3.0).ceil() as usize).clamp(8, 48);
|
||||
let pts = (0..n).map(|i| {
|
||||
let a = i as f32 / n as f32 * std::f32::consts::TAU;
|
||||
[c[0] + hw * math::cos(a), c[1] + hw * math::sin(a)]
|
||||
});
|
||||
out.push(Poly { pts: pts.collect(), closed: true });
|
||||
};
|
||||
for p in polys {
|
||||
let n = p.pts.len();
|
||||
let segs = if p.closed { n } else { n.saturating_sub(1) };
|
||||
for (&a, &b) in p.pts.iter().zip(p.pts.iter().cycle().skip(1)).take(segs) {
|
||||
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
|
||||
let l = (dx * dx + dy * dy).sqrt();
|
||||
if l < 1e-6 {
|
||||
continue;
|
||||
}
|
||||
let (nx, ny) = (-dy / l * hw, dx / l * hw);
|
||||
// quad wound the same way as the discs (counter-clockwise in y-down screen terms)
|
||||
out.push(Poly {
|
||||
pts: vec![[a[0] + nx, a[1] + ny], [b[0] + nx, b[1] + ny], [b[0] - nx, b[1] - ny], [a[0] - nx, a[1] - ny]],
|
||||
closed: true,
|
||||
});
|
||||
}
|
||||
// joints
|
||||
let first = if p.closed { 0 } else { 1 };
|
||||
let last = if p.closed { n } else { n.saturating_sub(1) };
|
||||
for &q in p.pts.get(first..last).unwrap_or_default() {
|
||||
disc(q, &mut out);
|
||||
}
|
||||
if let [q] = *p.pts.as_slice() {
|
||||
disc(q, &mut out);
|
||||
}
|
||||
}
|
||||
// normalise winding so overlapping pieces add up instead of cancelling
|
||||
for q in out.iter_mut() {
|
||||
let mut area = 0.0;
|
||||
for (a, b) in q.pts.iter().zip(q.pts.iter().cycle().skip(1)) {
|
||||
area += a[0] * b[1] - b[0] * a[1];
|
||||
}
|
||||
if area < 0.0 {
|
||||
q.pts.reverse();
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ path data
|
||||
|
||||
/// Parse SVG path data into segments (absolute coordinates). Arcs become cubic curves.
|
||||
pub fn parse_path(d: &str) -> Vec<Seg> {
|
||||
let b: Vec<char> = d.chars().collect();
|
||||
let mut i = 0usize;
|
||||
let mut segs = Vec::new();
|
||||
let (mut cx, mut cy) = (0.0f32, 0.0f32);
|
||||
let (mut sx, mut sy) = (0.0f32, 0.0f32);
|
||||
let mut last_ctrl: Option<P> = None; // previous cubic control (for S)
|
||||
let mut last_q: Option<P> = None; // previous quad control (for T)
|
||||
let mut cmd = ' ';
|
||||
fn skip(b: &[char], i: &mut usize) {
|
||||
while b.get(*i).is_some_and(|&c| c.is_whitespace() || c == ',') {
|
||||
*i += 1;
|
||||
}
|
||||
}
|
||||
fn number(b: &[char], i: &mut usize) -> Option<f32> {
|
||||
skip(b, i);
|
||||
let s = *i;
|
||||
if b.get(*i).is_some_and(|&c| c == '+' || c == '-') {
|
||||
*i += 1;
|
||||
}
|
||||
let mut dot = false;
|
||||
while let Some(&c) = b.get(*i)
|
||||
&& (c.is_ascii_digit() || (c == '.' && !dot))
|
||||
{
|
||||
if c == '.' {
|
||||
dot = true;
|
||||
}
|
||||
*i += 1;
|
||||
}
|
||||
if b.get(*i).is_some_and(|&c| c == 'e' || c == 'E') {
|
||||
let save = *i;
|
||||
*i += 1;
|
||||
if b.get(*i).is_some_and(|&c| c == '+' || c == '-') {
|
||||
*i += 1;
|
||||
}
|
||||
let ds = *i;
|
||||
while b.get(*i).is_some_and(|c| c.is_ascii_digit()) {
|
||||
*i += 1;
|
||||
}
|
||||
if ds == *i {
|
||||
*i = save;
|
||||
}
|
||||
}
|
||||
if s == *i {
|
||||
return None;
|
||||
}
|
||||
b.get(s..*i)?.iter().collect::<String>().parse::<f32>().ok().filter(|v| v.is_finite())
|
||||
}
|
||||
fn flag(b: &[char], i: &mut usize) -> Option<bool> {
|
||||
skip(b, i);
|
||||
if let Some(&c) = b.get(*i)
|
||||
&& (c == '0' || c == '1')
|
||||
{
|
||||
*i += 1;
|
||||
Some(c == '1')
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
loop {
|
||||
skip(&b, &mut i);
|
||||
let Some(&c) = b.get(i) else { break };
|
||||
if c.is_ascii_alphabetic() {
|
||||
cmd = c;
|
||||
i += 1;
|
||||
if cmd == 'z' || cmd == 'Z' {
|
||||
segs.push(Seg::Close);
|
||||
cx = sx;
|
||||
cy = sy;
|
||||
last_ctrl = None;
|
||||
last_q = None;
|
||||
continue;
|
||||
}
|
||||
} else if cmd == ' ' {
|
||||
break;
|
||||
}
|
||||
let rel = cmd.is_ascii_lowercase();
|
||||
let (ox, oy) = if rel { (cx, cy) } else { (0.0, 0.0) };
|
||||
macro_rules! num {
|
||||
() => {
|
||||
match number(&b, &mut i) {
|
||||
Some(v) => v,
|
||||
None => return segs,
|
||||
}
|
||||
};
|
||||
}
|
||||
match cmd.to_ascii_uppercase() {
|
||||
'M' => {
|
||||
let (x, y) = (num!() + ox, num!() + oy);
|
||||
segs.push(Seg::Move([x, y]));
|
||||
cx = x;
|
||||
cy = y;
|
||||
sx = x;
|
||||
sy = y;
|
||||
cmd = if rel { 'l' } else { 'L' };
|
||||
last_ctrl = None;
|
||||
last_q = None;
|
||||
}
|
||||
'L' => {
|
||||
let (x, y) = (num!() + ox, num!() + oy);
|
||||
segs.push(Seg::Line([x, y]));
|
||||
cx = x;
|
||||
cy = y;
|
||||
last_ctrl = None;
|
||||
last_q = None;
|
||||
}
|
||||
'H' => {
|
||||
let x = num!() + ox;
|
||||
segs.push(Seg::Line([x, cy]));
|
||||
cx = x;
|
||||
last_ctrl = None;
|
||||
last_q = None;
|
||||
}
|
||||
'V' => {
|
||||
let y = num!() + oy;
|
||||
segs.push(Seg::Line([cx, y]));
|
||||
cy = y;
|
||||
last_ctrl = None;
|
||||
last_q = None;
|
||||
}
|
||||
'C' => {
|
||||
let (x1, y1, x2, y2, x, y) = (num!() + ox, num!() + oy, num!() + ox, num!() + oy, num!() + ox, num!() + oy);
|
||||
segs.push(Seg::Cubic([x1, y1], [x2, y2], [x, y]));
|
||||
last_ctrl = Some([x2, y2]);
|
||||
last_q = None;
|
||||
cx = x;
|
||||
cy = y;
|
||||
}
|
||||
'S' => {
|
||||
let (x2, y2, x, y) = (num!() + ox, num!() + oy, num!() + ox, num!() + oy);
|
||||
let c1 = last_ctrl.map(|c| [2.0 * cx - c[0], 2.0 * cy - c[1]]).unwrap_or([cx, cy]);
|
||||
segs.push(Seg::Cubic(c1, [x2, y2], [x, y]));
|
||||
last_ctrl = Some([x2, y2]);
|
||||
last_q = None;
|
||||
cx = x;
|
||||
cy = y;
|
||||
}
|
||||
'Q' => {
|
||||
let (x1, y1, x, y) = (num!() + ox, num!() + oy, num!() + ox, num!() + oy);
|
||||
segs.push(Seg::Quad([x1, y1], [x, y]));
|
||||
last_q = Some([x1, y1]);
|
||||
last_ctrl = None;
|
||||
cx = x;
|
||||
cy = y;
|
||||
}
|
||||
'T' => {
|
||||
let (x, y) = (num!() + ox, num!() + oy);
|
||||
let c = last_q.map(|c| [2.0 * cx - c[0], 2.0 * cy - c[1]]).unwrap_or([cx, cy]);
|
||||
segs.push(Seg::Quad(c, [x, y]));
|
||||
last_q = Some(c);
|
||||
last_ctrl = None;
|
||||
cx = x;
|
||||
cy = y;
|
||||
}
|
||||
'A' => {
|
||||
let (rx, ry, rot) = (num!(), num!(), num!());
|
||||
let (large, sweep) = match (flag(&b, &mut i), flag(&b, &mut i)) {
|
||||
(Some(a), Some(c)) => (a, c),
|
||||
_ => return segs,
|
||||
};
|
||||
let (x, y) = (num!() + ox, num!() + oy);
|
||||
arc(&mut segs, [cx, cy], rx, ry, rot, large, sweep, [x, y]);
|
||||
cx = x;
|
||||
cy = y;
|
||||
last_ctrl = None;
|
||||
last_q = None;
|
||||
}
|
||||
_ => return segs,
|
||||
}
|
||||
}
|
||||
segs
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn arc(segs: &mut Vec<Seg>, p0: P, rx: f32, ry: f32, rot_deg: f32, large: bool, sweep: bool, p1: P) {
|
||||
let (mut rx, mut ry) = (rx.abs(), ry.abs());
|
||||
if (p0[0] == p1[0] && p0[1] == p1[1]) || rx < 1e-6 || ry < 1e-6 {
|
||||
segs.push(Seg::Line(p1));
|
||||
return;
|
||||
}
|
||||
let phi = rot_deg.to_radians();
|
||||
let (sp, cp) = math::sin_cos(phi);
|
||||
let (dx, dy) = ((p0[0] - p1[0]) * 0.5, (p0[1] - p1[1]) * 0.5);
|
||||
let (x1, y1) = (cp * dx + sp * dy, -sp * dx + cp * dy);
|
||||
let lam = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry);
|
||||
if lam > 1.0 {
|
||||
let s = lam.sqrt();
|
||||
rx *= s;
|
||||
ry *= s;
|
||||
}
|
||||
let num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1;
|
||||
let den = rx * rx * y1 * y1 + ry * ry * x1 * x1;
|
||||
let mut k = if den > 0.0 { (num / den).max(0.0).sqrt() } else { 0.0 };
|
||||
if large == sweep {
|
||||
k = -k;
|
||||
}
|
||||
let (cxp, cyp) = (k * rx * y1 / ry, -k * ry * x1 / rx);
|
||||
let (cx, cy) = (cp * cxp - sp * cyp + (p0[0] + p1[0]) * 0.5, sp * cxp + cp * cyp + (p0[1] + p1[1]) * 0.5);
|
||||
let ang = |ux: f32, uy: f32, vx: f32, vy: f32| math::atan2(ux * vy - uy * vx, ux * vx + uy * vy);
|
||||
let th1 = ang(1.0, 0.0, (x1 - cxp) / rx, (y1 - cyp) / ry);
|
||||
let mut dth = ang((x1 - cxp) / rx, (y1 - cyp) / ry, (-x1 - cxp) / rx, (-y1 - cyp) / ry);
|
||||
if !sweep && dth > 0.0 {
|
||||
dth -= std::f32::consts::TAU;
|
||||
} else if sweep && dth < 0.0 {
|
||||
dth += std::f32::consts::TAU;
|
||||
}
|
||||
let n = (dth.abs() / (std::f32::consts::FRAC_PI_2)).ceil().max(1.0) as usize;
|
||||
let step = dth / n as f32;
|
||||
let t = 4.0 / 3.0 * math::tan(step / 4.0);
|
||||
let pt = |a: f32| -> (P, P) {
|
||||
let (s, c) = math::sin_cos(a);
|
||||
// point and derivative on the unrotated ellipse, then rotated and moved
|
||||
let x = rx * c;
|
||||
let y = ry * s;
|
||||
let dx = -rx * s;
|
||||
let dy = ry * c;
|
||||
([cp * x - sp * y + cx, sp * x + cp * y + cy], [cp * dx - sp * dy, sp * dx + cp * dy])
|
||||
};
|
||||
for i in 0..n {
|
||||
let (a0, a1) = (th1 + step * i as f32, th1 + step * (i + 1) as f32);
|
||||
let ((pa, da), (pb, db)) = (pt(a0), pt(a1));
|
||||
let end = if i == n - 1 { p1 } else { pb };
|
||||
segs.push(Seg::Cubic([pa[0] + t * da[0], pa[1] + t * da[1]], [pb[0] - t * db[0], pb[1] - t * db[1]], end));
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ SVG subset
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Style {
|
||||
fill: Option<[f32; 3]>,
|
||||
stroke: Option<[f32; 3]>,
|
||||
stroke_w: f32,
|
||||
opacity: f32,
|
||||
fill_op: f32,
|
||||
stroke_op: f32,
|
||||
even_odd: bool,
|
||||
color: [f32; 3],
|
||||
}
|
||||
|
||||
impl Default for Style {
|
||||
fn default() -> Self {
|
||||
Style { fill: Some([0.0; 3]), stroke: None, stroke_w: 1.0, opacity: 1.0, fill_op: 1.0, stroke_op: 1.0, even_odd: false, color: [0.0; 3] }
|
||||
}
|
||||
}
|
||||
|
||||
struct Tag {
|
||||
name: String,
|
||||
attrs: Vec<(String, String)>,
|
||||
open: bool,
|
||||
close: bool,
|
||||
}
|
||||
|
||||
fn tags(src: &str) -> Vec<Tag> {
|
||||
let b: Vec<char> = src.chars().collect();
|
||||
let at = |i: usize| b.get(i).copied();
|
||||
let text = |s: usize, e: usize| -> String { b.get(s..e).unwrap_or_default().iter().collect() };
|
||||
let mut i = 0;
|
||||
let mut out = Vec::new();
|
||||
while let Some(c0) = at(i) {
|
||||
if c0 != '<' {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// comments, declarations, CDATA
|
||||
if b.get(i..).is_some_and(|r| r.starts_with(&['<', '!', '-', '-'])) {
|
||||
let mut j = i + 4;
|
||||
while j + 2 < b.len() && b.get(j..j + 3) != Some(&['-', '-', '>'][..]) {
|
||||
j += 1;
|
||||
}
|
||||
i = j + 3;
|
||||
continue;
|
||||
}
|
||||
if at(i + 1).is_some_and(|c| c == '!' || c == '?') {
|
||||
while at(i).is_some_and(|c| c != '>') {
|
||||
i += 1;
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
let closing = at(i) == Some('/');
|
||||
if closing {
|
||||
i += 1;
|
||||
}
|
||||
let s = i;
|
||||
while at(i).is_some_and(|c| !c.is_whitespace() && c != '>' && c != '/') {
|
||||
i += 1;
|
||||
}
|
||||
let name: String = text(s, i);
|
||||
let mut attrs = Vec::new();
|
||||
let mut selfclose = false;
|
||||
while let Some(c) = at(i)
|
||||
&& c != '>'
|
||||
{
|
||||
if c == '/' {
|
||||
selfclose = true;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if c.is_whitespace() {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let ks = i;
|
||||
while at(i).is_some_and(|c| c != '=' && !c.is_whitespace() && c != '>' && c != '/') {
|
||||
i += 1;
|
||||
}
|
||||
let key: String = text(ks, i);
|
||||
while at(i).is_some_and(char::is_whitespace) {
|
||||
i += 1;
|
||||
}
|
||||
if at(i) == Some('=') {
|
||||
i += 1;
|
||||
while at(i).is_some_and(char::is_whitespace) {
|
||||
i += 1;
|
||||
}
|
||||
if let Some(q) = at(i)
|
||||
&& (q == '"' || q == '\'')
|
||||
{
|
||||
i += 1;
|
||||
let vs = i;
|
||||
while at(i).is_some_and(|c| c != q) {
|
||||
i += 1;
|
||||
}
|
||||
attrs.push((key, text(vs, i)));
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
let name = name.rsplit(':').next().unwrap_or("").to_string();
|
||||
out.push(Tag { name, attrs, open: !closing, close: closing || selfclose });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn color(s: &str, current: [f32; 3]) -> Option<Option<[f32; 3]>> {
|
||||
let s = s.trim();
|
||||
if s == "none" || s == "transparent" {
|
||||
return Some(None);
|
||||
}
|
||||
if s == "currentColor" {
|
||||
return Some(Some(current));
|
||||
}
|
||||
if let Some(h) = s.strip_prefix('#') {
|
||||
let v: Vec<u32> = h.chars().filter_map(|c| c.to_digit(16)).collect();
|
||||
return match *v.as_slice() {
|
||||
[r, g, b] => Some(Some([r as f32 * 17.0 / 255.0, g as f32 * 17.0 / 255.0, b as f32 * 17.0 / 255.0])),
|
||||
[r0, r1, g0, g1, b0, b1] | [r0, r1, g0, g1, b0, b1, _, _] => {
|
||||
Some(Some([(r0 * 16 + r1) as f32 / 255.0, (g0 * 16 + g1) as f32 / 255.0, (b0 * 16 + b1) as f32 / 255.0]))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if let Some(r) = s.strip_prefix("rgb(").and_then(|r| r.strip_suffix(')')) {
|
||||
let v: Vec<f32> = r
|
||||
.split([',', ' '])
|
||||
.filter(|t| !t.is_empty())
|
||||
.filter_map(|t| {
|
||||
if let Some(p) = t.strip_suffix('%') { p.parse::<f32>().ok().map(|x| x / 100.0) } else { t.parse::<f32>().ok().map(|x| x / 255.0) }
|
||||
})
|
||||
.collect();
|
||||
return if let [r, g, b, ..] = *v.as_slice() { Some(Some([r.clamp(0.0, 1.0), g.clamp(0.0, 1.0), b.clamp(0.0, 1.0)])) } else { None };
|
||||
}
|
||||
let named = match s {
|
||||
"black" => [0.0, 0.0, 0.0],
|
||||
"white" => [1.0, 1.0, 1.0],
|
||||
"red" => [1.0, 0.0, 0.0],
|
||||
"green" => [0.0, 0.502, 0.0],
|
||||
"lime" => [0.0, 1.0, 0.0],
|
||||
"blue" => [0.0, 0.0, 1.0],
|
||||
"yellow" => [1.0, 1.0, 0.0],
|
||||
"cyan" | "aqua" => [0.0, 1.0, 1.0],
|
||||
"magenta" | "fuchsia" => [1.0, 0.0, 1.0],
|
||||
"gray" | "grey" => [0.502, 0.502, 0.502],
|
||||
"silver" => [0.753, 0.753, 0.753],
|
||||
"orange" => [1.0, 0.647, 0.0],
|
||||
"purple" => [0.502, 0.0, 0.502],
|
||||
"brown" => [0.647, 0.165, 0.165],
|
||||
"pink" => [1.0, 0.753, 0.796],
|
||||
"navy" => [0.0, 0.0, 0.502],
|
||||
_ => return if s.starts_with("url(") { Some(Some([0.5; 3])) } else { None },
|
||||
};
|
||||
Some(Some(named))
|
||||
}
|
||||
|
||||
fn num_attr(s: &str) -> Option<f32> {
|
||||
let t: String = s.trim().chars().take_while(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')).collect();
|
||||
t.parse::<f32>().ok().filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
fn parse_transform(s: &str) -> Xf {
|
||||
let mut xf = Xf::ID;
|
||||
let mut rest = s;
|
||||
while let Some(open) = rest.find('(') {
|
||||
let name = rest.get(..open).unwrap_or("").trim().trim_start_matches(',').trim();
|
||||
let Some(close) = rest.get(open..).and_then(|r| r.find(')')) else { break };
|
||||
let args: Vec<f32> = rest
|
||||
.get(open + 1..open + close)
|
||||
.unwrap_or("")
|
||||
.split(|c: char| c == ',' || c.is_whitespace())
|
||||
.filter(|t| !t.is_empty())
|
||||
.filter_map(|t| t.parse().ok())
|
||||
.collect();
|
||||
let t = match (name, args.as_slice()) {
|
||||
("translate", &[x]) => Xf::translate(x, 0.0),
|
||||
("translate", &[x, y]) => Xf::translate(x, y),
|
||||
("scale", &[k]) => Xf::scale(k, k),
|
||||
("scale", &[x, y]) => Xf::scale(x, y),
|
||||
("rotate", &[a]) => Xf::rotate(a.to_radians()),
|
||||
("rotate", &[a, x, y]) => Xf::translate(-x, -y).then(Xf::rotate(a.to_radians())).then(Xf::translate(x, y)),
|
||||
("skewX", &[a]) => Xf([1.0, 0.0, math::tan(a.to_radians()), 1.0, 0.0, 0.0]),
|
||||
("skewY", &[a]) => Xf([1.0, math::tan(a.to_radians()), 0.0, 1.0, 0.0, 0.0]),
|
||||
("matrix", &[a, b, c, d, e, f]) => Xf([a, b, c, d, e, f]),
|
||||
_ => Xf::ID,
|
||||
};
|
||||
// later transforms in the list apply first (they are closer to the element)
|
||||
xf = t.then(xf);
|
||||
rest = rest.get(open + close + 1..).unwrap_or("");
|
||||
}
|
||||
xf
|
||||
}
|
||||
|
||||
fn apply_style(st: &mut Style, key: &str, val: &str) {
|
||||
let v = val.trim();
|
||||
match key {
|
||||
"color" => {
|
||||
if let Some(Some(c)) = color(v, st.color) {
|
||||
st.color = c;
|
||||
}
|
||||
}
|
||||
"fill" => {
|
||||
if let Some(c) = color(v, st.color) {
|
||||
st.fill = c;
|
||||
}
|
||||
}
|
||||
"stroke" => {
|
||||
if let Some(c) = color(v, st.color) {
|
||||
st.stroke = c;
|
||||
}
|
||||
}
|
||||
"stroke-width" => {
|
||||
if let Some(w) = num_attr(v) {
|
||||
st.stroke_w = w.max(0.0);
|
||||
}
|
||||
}
|
||||
"opacity" => {
|
||||
if let Some(o) = num_attr(v) {
|
||||
st.opacity = o.clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
"fill-opacity" => {
|
||||
if let Some(o) = num_attr(v) {
|
||||
st.fill_op = o.clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
"stroke-opacity" => {
|
||||
if let Some(o) = num_attr(v) {
|
||||
st.stroke_op = o.clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
"fill-rule" => st.even_odd = v == "evenodd",
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn shape_segs(t: &Tag) -> Vec<Seg> {
|
||||
let a = |k: &str| t.attrs.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str());
|
||||
let f = |k: &str| a(k).and_then(num_attr).unwrap_or(0.0);
|
||||
match t.name.as_str() {
|
||||
"rect" => {
|
||||
let (x, y, w, h) = (f("x"), f("y"), f("width"), f("height"));
|
||||
if w <= 0.0 || h <= 0.0 {
|
||||
return vec![];
|
||||
}
|
||||
let mut rx = a("rx").and_then(num_attr);
|
||||
let mut ry = a("ry").and_then(num_attr);
|
||||
if rx.is_none() {
|
||||
rx = ry;
|
||||
}
|
||||
if ry.is_none() {
|
||||
ry = rx;
|
||||
}
|
||||
let (rx, ry) = (rx.unwrap_or(0.0).clamp(0.0, w / 2.0), ry.unwrap_or(0.0).clamp(0.0, h / 2.0));
|
||||
if rx <= 0.0 || ry <= 0.0 {
|
||||
vec![Seg::Move([x, y]), Seg::Line([x + w, y]), Seg::Line([x + w, y + h]), Seg::Line([x, y + h]), Seg::Close]
|
||||
} else {
|
||||
let mut s = vec![Seg::Move([x + rx, y]), Seg::Line([x + w - rx, y])];
|
||||
arc(&mut s, [x + w - rx, y], rx, ry, 0.0, false, true, [x + w, y + ry]);
|
||||
s.push(Seg::Line([x + w, y + h - ry]));
|
||||
arc(&mut s, [x + w, y + h - ry], rx, ry, 0.0, false, true, [x + w - rx, y + h]);
|
||||
s.push(Seg::Line([x + rx, y + h]));
|
||||
arc(&mut s, [x + rx, y + h], rx, ry, 0.0, false, true, [x, y + h - ry]);
|
||||
s.push(Seg::Line([x, y + ry]));
|
||||
arc(&mut s, [x, y + ry], rx, ry, 0.0, false, true, [x + rx, y]);
|
||||
s.push(Seg::Close);
|
||||
s
|
||||
}
|
||||
}
|
||||
"circle" | "ellipse" => {
|
||||
let (cx, cy) = (f("cx"), f("cy"));
|
||||
let (rx, ry) = if t.name == "circle" { (f("r"), f("r")) } else { (f("rx"), f("ry")) };
|
||||
if rx <= 0.0 || ry <= 0.0 {
|
||||
return vec![];
|
||||
}
|
||||
let mut s = vec![Seg::Move([cx + rx, cy])];
|
||||
arc(&mut s, [cx + rx, cy], rx, ry, 0.0, false, true, [cx, cy + ry]);
|
||||
arc(&mut s, [cx, cy + ry], rx, ry, 0.0, false, true, [cx - rx, cy]);
|
||||
arc(&mut s, [cx - rx, cy], rx, ry, 0.0, false, true, [cx, cy - ry]);
|
||||
arc(&mut s, [cx, cy - ry], rx, ry, 0.0, false, true, [cx + rx, cy]);
|
||||
s.push(Seg::Close);
|
||||
s
|
||||
}
|
||||
"line" => vec![Seg::Move([f("x1"), f("y1")]), Seg::Line([f("x2"), f("y2")])],
|
||||
"polyline" | "polygon" => {
|
||||
let v: Vec<f32> = a("points")
|
||||
.unwrap_or("")
|
||||
.split(|c: char| c == ',' || c.is_whitespace())
|
||||
.filter(|t| !t.is_empty())
|
||||
.filter_map(|t| t.parse().ok())
|
||||
.collect();
|
||||
let mut s = Vec::new();
|
||||
for (i, &[x, y]) in v.as_chunks::<2>().0.iter().enumerate() {
|
||||
s.push(if i == 0 { Seg::Move([x, y]) } else { Seg::Line([x, y]) });
|
||||
}
|
||||
if t.name == "polygon" && !s.is_empty() {
|
||||
s.push(Seg::Close);
|
||||
}
|
||||
s
|
||||
}
|
||||
"path" => parse_path(a("d").unwrap_or("")),
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Rasterise an SVG document into a `w` by `h` image with straight (non-premultiplied) alpha.
|
||||
/// `fit`: 0 contain (keep the aspect ratio, centred), 1 stretch, 2 cover. `scale`, `dx`, `dy` (in image fractions) adjust it.
|
||||
pub fn render_svg(src: &str, w: usize, h: usize, fit: u32, scale: f32, dx: f32, dy: f32) -> Result<Tex, String> {
|
||||
let ts = tags(src);
|
||||
let root = ts.iter().find(|t| t.name == "svg" && t.open).ok_or("not an SVG document (no <svg> element)")?;
|
||||
let a = |k: &str| root.attrs.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str());
|
||||
let vb: Vec<f32> = a("viewBox")
|
||||
.map(|v| v.split(|c: char| c == ',' || c.is_whitespace()).filter(|t| !t.is_empty()).filter_map(|t| t.parse().ok()).collect())
|
||||
.unwrap_or_default();
|
||||
let (vx, vy, vw, vh) = if let [x0, y0, w0, h0] = *vb.as_slice()
|
||||
&& w0 > 0.0
|
||||
&& h0 > 0.0
|
||||
{
|
||||
(x0, y0, w0, h0)
|
||||
} else {
|
||||
(0.0, 0.0, a("width").and_then(num_attr).unwrap_or(100.0).max(1.0), a("height").and_then(num_attr).unwrap_or(100.0).max(1.0))
|
||||
};
|
||||
let (sx, sy) = (w as f32 / vw, h as f32 / vh);
|
||||
let (kx, ky) = match fit {
|
||||
1 => (sx, sy),
|
||||
2 => (sx.max(sy), sx.max(sy)),
|
||||
_ => (sx.min(sy), sx.min(sy)),
|
||||
};
|
||||
let (kx, ky) = (kx * scale, ky * scale);
|
||||
let base =
|
||||
Xf::translate(-vx - vw * 0.5, -vy - vh * 0.5).then(Xf::scale(kx, ky)).then(Xf::translate(w as f32 * (0.5 + dx), h as f32 * (0.5 + dy)));
|
||||
// premultiplied accumulation
|
||||
let mut acc = vec![[0.0f32; 4]; w * h];
|
||||
let mut stack: Vec<(Style, Xf)> = vec![(Style::default(), base)];
|
||||
let mut skip_depth = 0usize;
|
||||
let mut depth_names: Vec<bool> = Vec::new();
|
||||
for t in &ts {
|
||||
let hidden = matches!(
|
||||
t.name.as_str(),
|
||||
"defs"
|
||||
| "clipPath"
|
||||
| "mask"
|
||||
| "symbol"
|
||||
| "marker"
|
||||
| "pattern"
|
||||
| "linearGradient"
|
||||
| "radialGradient"
|
||||
| "style"
|
||||
| "title"
|
||||
| "desc"
|
||||
| "metadata"
|
||||
| "text"
|
||||
| "filter"
|
||||
);
|
||||
if t.open {
|
||||
if skip_depth > 0 {
|
||||
if !t.close {
|
||||
skip_depth += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if hidden {
|
||||
if !t.close {
|
||||
skip_depth = 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// the stack keeps its base entry: closing tags never pop it
|
||||
let Some((mut st, mut xf)) = stack.last().cloned() else { continue };
|
||||
apply_tag_style(t, &mut st, &mut xf);
|
||||
let segs = shape_segs(t);
|
||||
if !segs.is_empty() {
|
||||
let polys = flatten(&segs, &xf);
|
||||
if let Some(c) = st.fill {
|
||||
let m = fill(&polys, w, h, st.even_odd);
|
||||
composite(&mut acc, &m, c, st.fill_op * st.opacity);
|
||||
}
|
||||
if let Some(c) = st.stroke
|
||||
&& st.stroke_w > 0.0
|
||||
{
|
||||
let outline = stroke(&polys, st.stroke_w * xf.mean_scale());
|
||||
let m = fill(&outline, w, h, false);
|
||||
composite(&mut acc, &m, c, st.stroke_op * st.opacity);
|
||||
}
|
||||
}
|
||||
if !t.close {
|
||||
stack.push((st, xf));
|
||||
depth_names.push(true);
|
||||
}
|
||||
} else if t.close && !t.open {
|
||||
if skip_depth > 0 {
|
||||
skip_depth -= 1;
|
||||
continue;
|
||||
}
|
||||
if depth_names.pop().is_some() && stack.len() > 1 {
|
||||
stack.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Tex::solid(w, h, [0.0, 0.0, 0.0, 0.0]);
|
||||
for (o, p) in out.px.iter_mut().zip(&acc) {
|
||||
if p[3] > 1e-6 {
|
||||
*o = [p[0] / p[3], p[1] / p[3], p[2] / p[3], p[3].min(1.0)];
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn apply_tag_style(t: &Tag, st: &mut Style, xf: &mut Xf) {
|
||||
for (k, v) in &t.attrs {
|
||||
if k == "style" {
|
||||
for decl in v.split(';') {
|
||||
if let Some((kk, vv)) = decl.split_once(':') {
|
||||
apply_style(st, kk.trim(), vv);
|
||||
}
|
||||
}
|
||||
} else if k == "transform" {
|
||||
*xf = parse_transform(v).then(*xf);
|
||||
} else {
|
||||
apply_style(st, k, v);
|
||||
}
|
||||
}
|
||||
// style="" must win over presentation attributes: apply it again last
|
||||
if let Some((_, v)) = t.attrs.iter().find(|(k, _)| k == "style") {
|
||||
for decl in v.split(';') {
|
||||
if let Some((kk, vv)) = decl.split_once(':') {
|
||||
apply_style(st, kk.trim(), vv);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn composite(acc: &mut [[f32; 4]], m: &Mask, c: [f32; 3], opacity: f32) {
|
||||
for (d, &cov) in acc.iter_mut().zip(&m.a) {
|
||||
let a = cov * opacity;
|
||||
if a <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let k = 1.0 - a;
|
||||
d[0] = c[0] * a + d[0] * k;
|
||||
d[1] = c[1] * a + d[1] * k;
|
||||
d[2] = c[2] * a + d[2] * k;
|
||||
d[3] = a + d[3] * k;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// SPDX-License-Identifier: MIT OR Apache-2.0
|
||||
//! Versions of the evaluator for caches of results (in memory, on disk, or stored in a document). `build.rs` derives
|
||||
//! them from the source, per node kind: a kind's version covers its match arm, what that reaches and what every kind
|
||||
//! goes through (`build/source`). So changing a node changes the version of the kinds that reach the change, and only
|
||||
//! theirs, with nothing to bump by hand.
|
||||
//!
|
||||
//! [`EPOCH`] is the one number a developer may have to change: for a change that alters results without changing any
|
||||
//! Rust source of the evaluator (a data file read at run time, say). It is mixed into [`ALL`] and into every version
|
||||
//! in [`KINDS`]. The kinds of the graphs that nodes run (function, pattern and FX-map nodes) have no entry there: they
|
||||
//! report the fixed `hosted` string, and a change is covered through the node kinds that run them.
|
||||
|
||||
/// See the module docs.
|
||||
pub const EPOCH: u32 = 1;
|
||||
|
||||
mod generated {
|
||||
include!(concat!(env!("OUT_DIR"), "/kind_versions.rs"));
|
||||
}
|
||||
|
||||
/// [`TOOLCHAIN`]: the compiler, its settings and the dependencies (the lock file). [`ALL`]: every file of the
|
||||
/// evaluator. [`FILES`]: how many files that is. [`KINDS`]: (node kind, version), sorted by kind.
|
||||
pub use generated::{ALL, FILES, KINDS, TOOLCHAIN};
|
||||
|
||||
/// What stands for a node kind in a function or a pattern program: such a graph is only ever run by the node holding it,
|
||||
/// or by what every kind goes through, and those versions cover the code that runs it.
|
||||
const HOSTED: &str = "hosted";
|
||||
|
||||
/// True for the kinds of the graphs that nodes run, not the evaluator.
|
||||
fn is_hosted(kind: &str) -> bool {
|
||||
crate::func::FUNC_SPECS.iter().chain(crate::fxmap::FXM_SPECS).chain(crate::patterns::SPECS).any(|s| s.kind == kind)
|
||||
}
|
||||
|
||||
/// The version of node kind `kind`. A kind nothing is known about goes by the version of all the evaluator's source: it
|
||||
/// changes more often than it needs to, never less.
|
||||
pub fn of_kind(kind: &str) -> &'static str {
|
||||
match KINDS.binary_search_by(|(k, _)| (*k).cmp(kind)) {
|
||||
Ok(at) => KINDS.get(at).map_or(ALL, |(_, v)| v),
|
||||
Err(_) if is_hosted(kind) => HOSTED,
|
||||
Err(_) => ALL,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_kind_with_an_arm_has_its_own_version_and_others_go_by_everything() {
|
||||
assert!(KINDS.is_sorted_by_key(|(k, _)| *k));
|
||||
assert_ne!(of_kind("blend"), ALL);
|
||||
assert_ne!(of_kind("blend"), of_kind("transform_matrix"));
|
||||
assert_eq!(of_kind("no such kind"), ALL);
|
||||
}
|
||||
|
||||
/// A kind falling back to [`ALL`] would be recomputed for any change to any node.
|
||||
#[test]
|
||||
fn every_node_kind_has_a_version_of_its_own() {
|
||||
let specs = crate::graph::SPECS.iter().chain(crate::atomic::SPECS).chain(crate::compiled_ops::SPECS);
|
||||
let without: Vec<&str> = specs.map(|s| s.kind).filter(|k| of_kind(k) == ALL).collect();
|
||||
assert_eq!(without, Vec::<&str>::new());
|
||||
for kind in ["input", "subgraph", "pattern_program", "transform_matrix", "pixel_processor"] {
|
||||
assert_ne!(of_kind(kind), ALL, "{kind}");
|
||||
assert_ne!(of_kind(kind), HOSTED, "{kind}");
|
||||
}
|
||||
assert_eq!(of_kind("pp_out"), HOSTED);
|
||||
assert_eq!(of_kind("fxm_marker"), HOSTED);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//! Deep graphs evaluate on an ordinary thread's stack: the evaluator keeps the nodes waiting for their inputs in a list
|
||||
//! of its own instead of recursing along the graph, so a chain of any length needs no more stack than a short one. A
|
||||
//! function graph runs recursively per pixel, so how deep one may be is bounded, and a deeper one is an error.
|
||||
|
||||
use craft_material_graph::graph::Graph;
|
||||
use std::fmt::Write;
|
||||
|
||||
/// The stack of a thread spawned without asking for one (Rust's default), and of rayon's workers.
|
||||
const NORMAL_STACK: usize = 2 << 20;
|
||||
|
||||
/// The stack a function as deep as allowed is run with: the normal one in an optimised build (measured: 2040 nodes in a
|
||||
/// row take under 1 MB); an unoptimised build's frames are about fifteen times larger.
|
||||
const FUNCTION_STACK: usize = if cfg!(debug_assertions) { 32 << 20 } else { NORMAL_STACK };
|
||||
|
||||
/// Runs `f` on the one thread of a new pool with `stack` bytes of stack and returns what it returns.
|
||||
fn on_stack<R: Send + 'static>(stack: usize, f: impl FnOnce() -> R + Send + 'static) -> R {
|
||||
rayon::ThreadPoolBuilder::new().num_threads(1).stack_size(stack).build().expect("a pool").install(f)
|
||||
}
|
||||
|
||||
/// `n` invert nodes in a row behind a gradient.
|
||||
fn image_chain(n: u32) -> String {
|
||||
let mut t = String::from("size 16\nnode 0 gradient angle=0.1\n");
|
||||
for i in 1..=n {
|
||||
let _ = writeln!(t, "node {i} invert in=@{}", i - 1);
|
||||
}
|
||||
let _ = writeln!(t, "output o {n}");
|
||||
t
|
||||
}
|
||||
|
||||
/// A pixel processor running a function of `n` additions in a row on the position.
|
||||
fn function_chain(n: u32) -> String {
|
||||
let mut t = String::from("size 16\nsubgraph f\nmeta kind \"function\"\nnode 1 f_pos\nnode 2 f_swizzle a=@1 mask=\"x\"\nnode 3 f_float v=0.001\n");
|
||||
let mut last = 2;
|
||||
for i in 0..n {
|
||||
let id = 10 + i;
|
||||
let _ = writeln!(t, "node {id} f_add a=@{last} b=@3");
|
||||
last = id;
|
||||
}
|
||||
let _ = writeln!(t, "node 9 f_out in=@{last}\nend\nnode 1 pixel_processor fn=\"f\"\noutput o 1");
|
||||
t
|
||||
}
|
||||
|
||||
/// Subgraphs `levels` deep, each an invert of the one below.
|
||||
fn nested(levels: u32) -> String {
|
||||
let mut t = String::from("size 16\nsubgraph s0\nnode 1 input idx=0\nnode 2 invert in=@1\noutput o 2\nend\n");
|
||||
for l in 1..levels {
|
||||
let _ = write!(t, "subgraph s{l}\nnode 1 input idx=0\nnode 2 subgraph graph=\"s{}\" in0=@1\nnode 3 invert in=@2\noutput o 3\nend\n", l - 1);
|
||||
}
|
||||
let _ = write!(t, "node 1 gradient angle=0.1\nnode 2 subgraph graph=\"s{}\" in0=@1\noutput o 2\n", levels - 1);
|
||||
t
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chain_of_a_hundred_thousand_nodes_evaluates_on_a_normal_stack() {
|
||||
let g = Graph::parse(&image_chain(100_000)).expect("parses");
|
||||
let shallow = Graph::parse(&image_chain(2)).expect("parses");
|
||||
let (deep, two) =
|
||||
on_stack(NORMAL_STACK, move || (g.evaluate(None).map_err(|e| e.to_string()), shallow.evaluate(None).map_err(|e| e.to_string())));
|
||||
let (deep, two) = (deep.expect("evaluates"), two.expect("evaluates"));
|
||||
// an even number of inverts is the gradient again, as two are
|
||||
assert_eq!(deep["o"].px, two["o"].px);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_node_of_a_long_chain_gets_a_thumbnail_on_a_normal_stack() {
|
||||
let g = Graph::parse(&image_chain(20_000)).expect("parses");
|
||||
let all = on_stack(NORMAL_STACK, move || g.evaluate_all(16, &[20_000]));
|
||||
assert!(all.errors.is_empty(), "{:?}", all.errors.iter().next());
|
||||
assert_eq!(all.thumbs.len(), 20_001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subgraphs_nested_to_the_limit_evaluate_on_a_normal_stack() {
|
||||
let g = Graph::parse(&nested(8)).expect("parses");
|
||||
let r = on_stack(NORMAL_STACK, move || g.evaluate(None).map(|o| o.len()).map_err(|e| e.to_string()));
|
||||
assert_eq!(r, Ok(1));
|
||||
let g = Graph::parse(&nested(9)).expect("parses");
|
||||
let r = on_stack(NORMAL_STACK, move || g.evaluate(None).map_err(|e| e.to_string()));
|
||||
assert!(r.is_err_and(|e| e.contains("too deep")), "nine levels are refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_function_as_deep_as_allowed_runs_on_a_normal_stack() {
|
||||
let n = craft_material_graph::func::MAX_RUN_DEPTH as u32 - 4;
|
||||
let g = Graph::parse(&function_chain(n)).expect("parses");
|
||||
// (the pixels run on the pool's threads, so they get the same stack)
|
||||
let r = on_stack(FUNCTION_STACK, move || {
|
||||
let pool = rayon::ThreadPoolBuilder::new().num_threads(4).stack_size(FUNCTION_STACK).build().expect("pool");
|
||||
pool.install(|| g.evaluate(None).map_err(|e| e.to_string()))
|
||||
});
|
||||
let o = r.expect("evaluates");
|
||||
let px = o["o"].px[0][0];
|
||||
assert!((px - (0.5 / 16.0 + n as f32 * 0.001)).abs() < 1e-3, "{px}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_function_deeper_than_allowed_is_an_error() {
|
||||
let n = craft_material_graph::func::MAX_RUN_DEPTH as u32 + 10;
|
||||
let g = Graph::parse(&function_chain(n)).expect("parses");
|
||||
let r = on_stack(NORMAL_STACK, move || g.evaluate(None).map_err(|e| e.to_string()));
|
||||
assert!(r.as_ref().is_err_and(|e| e.contains("too deep")), "{:?}", r.map(|o| o.len()));
|
||||
}
|
||||
|
||||
/// How much stack a function `TC_PROBE_N` additions deep takes: run with `TC_PROBE_STACK` bytes of stack (a crash is
|
||||
/// too little). For choosing `MAX_RUN_DEPTH`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn probe_function_stack() {
|
||||
let n: u32 = std::env::var("TC_PROBE_N").ok().and_then(|v| v.parse().ok()).unwrap_or(1000);
|
||||
let stack: usize = std::env::var("TC_PROBE_STACK").ok().and_then(|v| v.parse().ok()).unwrap_or(NORMAL_STACK);
|
||||
let g = Graph::parse(&function_chain(n)).expect("parses");
|
||||
let r = on_stack(stack, move || {
|
||||
let pool = rayon::ThreadPoolBuilder::new().num_threads(2).stack_size(stack).build().expect("pool");
|
||||
pool.install(|| g.evaluate(None).map(|_| ()).map_err(|e| e.to_string()))
|
||||
});
|
||||
eprintln!("probe n={n} stack={stack}: {r:?}");
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//! Evaluation gives the same bytes however it is run: on one worker thread or many, and from the node cache or computed
|
||||
//! afresh. The graphs are the engine's own demo graphs (one per node kind, written for this repository), so nothing
|
||||
//! here depends on outside data.
|
||||
|
||||
use craft_material_graph::context::EvalContext;
|
||||
use craft_material_graph::graph::{self, Graph, NodeCache};
|
||||
use craft_material_graph::tex::Tex;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Rendered at a size that is not the demo graphs' own (64), so sizes scale, and large enough that the parallel loops
|
||||
/// split every image into several pieces.
|
||||
const SIDE: usize = 96;
|
||||
|
||||
fn demo_graphs() -> Vec<(&'static str, Graph)> {
|
||||
graph::SPECS
|
||||
.iter()
|
||||
.filter_map(|s| graph::demo_graph_for(s.kind).map(|t| (s.kind, t)))
|
||||
.map(|(k, t)| (k, Graph::parse(&t).unwrap_or_else(|e| panic!("the demo graph of {k} does not parse: {e}"))))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn bits(t: &Tex) -> Bits {
|
||||
(t.w, t.h, t.px.iter().flat_map(|p| p.map(f32::to_bits)).collect())
|
||||
}
|
||||
|
||||
/// An image as (width, height, the bits of every component).
|
||||
type Bits = (usize, usize, Vec<u32>);
|
||||
|
||||
/// Every output of `g`, or its error, as bits.
|
||||
fn render(g: &Graph) -> Result<BTreeMap<String, Bits>, String> {
|
||||
g.evaluate(Some(SIDE)).map(|o| o.iter().map(|(k, t)| (k.clone(), bits(t))).collect()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn in_pool<R: Send>(threads: usize, f: impl FnOnce() -> R + Send) -> R {
|
||||
rayon::ThreadPoolBuilder::new().num_threads(threads).build().expect("a thread pool").install(f)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_thread_and_eight_render_the_same_bytes() {
|
||||
let graphs = demo_graphs();
|
||||
assert!(graphs.len() > 100, "only {} demo graphs", graphs.len());
|
||||
let one = in_pool(1, || graphs.iter().map(|(_, g)| render(g)).collect::<Vec<_>>());
|
||||
let eight = in_pool(8, || graphs.iter().map(|(_, g)| render(g)).collect::<Vec<_>>());
|
||||
let differ: Vec<&str> = graphs.iter().zip(one.iter().zip(&eight)).filter(|(_, (a, b))| a != b).map(|((k, _), _)| *k).collect();
|
||||
assert!(differ.is_empty(), "these kinds render differently on 1 and 8 threads: {differ:?}");
|
||||
assert!(one.iter().filter(|r| r.is_ok()).count() > 100, "most demo graphs must render");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_and_uncached_evaluations_give_the_same_bytes() {
|
||||
let cache = Arc::new(NodeCache::new(256));
|
||||
let mut differ = Vec::new();
|
||||
let mut not_reused = Vec::new();
|
||||
for (kind, g) in demo_graphs() {
|
||||
let keep: Vec<u32> = g.nodes.keys().copied().collect();
|
||||
let fresh = g.evaluate_all(SIDE, &keep);
|
||||
let first = g.evaluate_all_cached(&EvalContext::default(), SIDE, &keep, &cache, None, &mut |_| {});
|
||||
// the second run takes every node from the cache
|
||||
let hits = cache.stats().0;
|
||||
let again = g.evaluate_all_cached(&EvalContext::default(), SIDE, &keep, &cache, None, &mut |_| {});
|
||||
if again.errors.len() < keep.len() && cache.stats().0 == hits {
|
||||
not_reused.push(kind);
|
||||
}
|
||||
for r in [&first, &again] {
|
||||
let same = keep.iter().all(|id| fresh.kept.get(id).map(|t| bits(t)) == r.kept.get(id).map(|t| bits(t)))
|
||||
&& fresh.errors == r.errors
|
||||
&& fresh.thumbs == r.thumbs;
|
||||
if !same {
|
||||
differ.push(kind);
|
||||
}
|
||||
}
|
||||
cache.clear();
|
||||
}
|
||||
assert!(differ.is_empty(), "the cache changes these kinds: {differ:?}");
|
||||
assert!(not_reused.is_empty(), "the second run took nothing from the cache for these kinds: {not_reused:?}");
|
||||
}
|
||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user