mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 06:53:19 -10:00
Compare commits
149
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a18b7c757c | ||
|
|
a2f91a82c3 | ||
|
|
be71820281 | ||
|
|
1c63d49e8b | ||
|
|
e3b55f2990 | ||
|
|
584be72747 | ||
|
|
8bc4afdd4a | ||
|
|
2dbedfe1d2 | ||
|
|
cdd44b172d | ||
|
|
4797b5ca61 | ||
|
|
3c8fc66bc0 | ||
|
|
c2e10d5181 | ||
|
|
eb5ce854ca | ||
|
|
cd03baf109 | ||
|
|
f8c16d2656 | ||
|
|
c6c165ca4c | ||
|
|
97e3fc3892 | ||
|
|
2487f40dd1 | ||
|
|
e9909de88f | ||
|
|
ee42e31469 | ||
|
|
d30c4a687a | ||
|
|
f2bf93cbee | ||
|
|
1dee25c609 | ||
|
|
cb40dca08b | ||
|
|
177f74e376 | ||
|
|
b3c2394cb7 | ||
|
|
737468b8cd | ||
|
|
82f1fb4052 | ||
|
|
99c3f52524 | ||
|
|
a691968e57 | ||
|
|
8bd79bd034 | ||
|
|
3796d708db | ||
|
|
2929ce6a04 | ||
|
|
929c03d5e4 | ||
|
|
4d5deeedac | ||
|
|
9efe6f8919 | ||
|
|
79d304f87d | ||
|
|
d0eb2424a6 | ||
|
|
b45cbe4085 | ||
|
|
5a4060df5e | ||
|
|
4a5612ae10 | ||
|
|
b8e2a3d6d2 | ||
|
|
4506c0ca2b | ||
|
|
9ae63e33c2 | ||
|
|
cb0d9c5482 | ||
|
|
aaa6f50339 | ||
|
|
87f8ac9a85 | ||
|
|
d1faf4f06f | ||
|
|
4cec0645fb | ||
|
|
cdc7ad98a4 | ||
|
|
a058f87048 | ||
|
|
304604231e | ||
|
|
d58fade59c | ||
|
|
9edcbf507c | ||
|
|
fc7edcdc49 | ||
|
|
30edd5d1a6 | ||
|
|
52ee3e0438 | ||
|
|
1c7b3afeb8 | ||
|
|
b1fafa9bf9 | ||
|
|
fe1383442f | ||
|
|
59bfe93107 | ||
|
|
089e62ee4c | ||
|
|
2ab92392d4 | ||
|
|
2ca930d81e | ||
|
|
4946bf9c00 | ||
|
|
a0dad6afbc | ||
|
|
425d7439b9 | ||
|
|
ca161bcb73 | ||
|
|
da31c4b3c6 | ||
|
|
e35a7769c0 | ||
|
|
0dfab1dbfd | ||
|
|
39369393f7 | ||
|
|
4202a87850 | ||
|
|
2fd0c7f14a | ||
|
|
1c5993d5a4 | ||
|
|
8cc12db395 | ||
|
|
bc42f11ff2 | ||
|
|
0c9fc255f2 | ||
|
|
7a1520bc3b | ||
|
|
9d237cf06a | ||
|
|
abead7eae4 | ||
|
|
c2044c2899 | ||
|
|
e8eafcdedb | ||
|
|
20e3eba1e7 | ||
|
|
1cf7dbf59a | ||
|
|
7be6b93b3f | ||
|
|
590ec633f8 | ||
|
|
35ce4cfdb3 | ||
|
|
15af3be4b1 | ||
|
|
7bc06bb777 | ||
|
|
67d85113fd | ||
|
|
3a98e0a52d | ||
|
|
2aa85c456a | ||
|
|
8f92302403 | ||
|
|
d2242ed6e6 | ||
|
|
666acf6050 | ||
|
|
94dae14946 | ||
|
|
ec01569901 | ||
|
|
56ff2a7031 | ||
|
|
88ff2b6967 | ||
|
|
e708783013 | ||
|
|
90182e445b | ||
|
|
edbcb15e81 | ||
|
|
0a77ecb65e | ||
|
|
90f138fba0 | ||
|
|
bdd30b7c65 | ||
|
|
71ee5ab583 | ||
|
|
3469759329 | ||
|
|
18b37c421c | ||
|
|
f70360f1ee | ||
|
|
fcbfba57b9 | ||
|
|
8b1cef58d5 | ||
|
|
da20262976 | ||
|
|
6dc089b82c | ||
|
|
34bf8eb021 | ||
|
|
6e1d7ceee0 | ||
|
|
4bdc4749e4 | ||
|
|
d83975535f | ||
|
|
f7147d52c0 | ||
|
|
9d311f5fde | ||
|
|
ba2dc6ade7 | ||
|
|
c3dd6b7d52 | ||
|
|
f4b524f896 | ||
|
|
0d01e4ef43 | ||
|
|
83d8f8e305 | ||
|
|
9e03e5fe4b | ||
|
|
5a73a7d5b4 | ||
|
|
2c0d626432 | ||
|
|
031d1357ca | ||
|
|
a6f59c198f | ||
|
|
6073b116b7 | ||
|
|
6298d127e5 | ||
|
|
5a57a5e128 | ||
|
|
328aba8849 | ||
|
|
af925441a8 | ||
|
|
d203d64944 | ||
|
|
af2b35f439 | ||
|
|
1858bf9bef | ||
|
|
0daaeb5b38 | ||
|
|
6a4ff18a0b | ||
|
|
24b8bf33e4 | ||
|
|
68433ab526 | ||
|
|
70cb98d3e8 | ||
|
|
6c7bf70a4e | ||
|
|
dc956173f1 | ||
|
|
d90b05017e | ||
|
|
5f55c55d57 | ||
|
|
86fe5d3673 | ||
|
|
822b73fc7d |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
# vendor/bevy_pbr's shaders keep LF on every checkout. raea replaces some of them with its own forks only after checking
|
||||
# Bevy's is still the one the fork was taken from, by its bytes' hash (raea_sys_frame::bevy_api::swap_embedded_shader),
|
||||
# and a Windows checkout turns LF into CRLF: 0.1.9-rc1's Windows build panicked on volumetric_fog.wesl at its first render
|
||||
vendor/bevy_pbr/**/*.wesl text eol=lf
|
||||
vendor/bevy_pbr/**/*.wgsl text eol=lf
|
||||
+3
-3
@@ -1,11 +1,11 @@
|
||||
# gitleaks: the default rules, minus raea's asset ledgers, whose "key" field is a content hash of the made file
|
||||
# (prompt, seed and model), not a credential; and Bevy's batching code, whose `prev_key = item.sort_key.0` is a
|
||||
# render-phase sort key.
|
||||
# render-phase sort key and whose `Opaque3dBinKey` and `Wireframe3dBinKey` (vendor/bevy_pbr) are bin keys' type names.
|
||||
[extend]
|
||||
useDefault = true
|
||||
|
||||
[allowlist]
|
||||
description = "asset ledgers and Bevy sort keys"
|
||||
description = "asset ledgers and Bevy sort and bin keys"
|
||||
paths = ['''(^|/)assets/made\.jsonl$''']
|
||||
regexTarget = "line"
|
||||
regexes = ['''prev_key = item\.sort_key''']
|
||||
regexes = ['''prev_key = item\.sort_key''', '''(bin_key|BinKey) = [A-Za-z0-9]+BinKey\b''']
|
||||
Generated
+181
-9
@@ -3065,8 +3065,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "bevy_pbr"
|
||||
version = "0.20.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fb760932d1e683e7c00011f5c99e4e1cc893646a3a7b7224da6daf9bfa94853d"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"bevy_app",
|
||||
@@ -3438,8 +3436,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "bevy_rich_text3d"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97b3cfe8f7187fb6f8e4889b8e7dcf39ff36bf7a84fcbd4f7b69f7d3b8a7bfe4"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"cosmic-text",
|
||||
@@ -13636,6 +13632,22 @@ version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "019b4b213425016d7d84a153c4c73afb0946fbb4840e4eece7ba8848b9d6da22"
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-ask"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-core-ask",
|
||||
"raea-io-assets",
|
||||
"raea-io-clef",
|
||||
"raea-io-home",
|
||||
"raea-io-trace",
|
||||
"raea-sys-fingerprint",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-capcut"
|
||||
version = "0.1.0"
|
||||
@@ -13725,6 +13737,7 @@ name = "raea-app-direction"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"image",
|
||||
"raea-app-check",
|
||||
"raea-app-check-text",
|
||||
"raea-app-notes",
|
||||
@@ -13732,6 +13745,7 @@ dependencies = [
|
||||
"raea-core-brief",
|
||||
"raea-core-facts",
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-io-trace",
|
||||
"raea-runtime-bundle",
|
||||
"raea-runtime-react",
|
||||
@@ -13739,6 +13753,21 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-double"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-app-ask",
|
||||
"raea-core-ask",
|
||||
"raea-io-assets",
|
||||
"raea-io-clef",
|
||||
"raea-sys-columns",
|
||||
"raea-sys-fingerprint",
|
||||
"raea-sys-fingerprint-use",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-engines"
|
||||
version = "0.1.0"
|
||||
@@ -13762,6 +13791,7 @@ dependencies = [
|
||||
"dunce",
|
||||
"fastrand",
|
||||
"raea-app-check",
|
||||
"raea-app-double",
|
||||
"raea-io-home",
|
||||
"raea-sys-columns",
|
||||
"raea-sys-fingerprint",
|
||||
@@ -13808,14 +13838,13 @@ dependencies = [
|
||||
name = "raea-app-judge"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dunce",
|
||||
"image",
|
||||
"raea-core-ask",
|
||||
"raea-core-facts",
|
||||
"raea-io-clef",
|
||||
"raea-io-home",
|
||||
"raea-runtime-bundle",
|
||||
"serde_json",
|
||||
"ureq 2.12.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -13897,11 +13926,26 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-scene"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-core-facts",
|
||||
"raea-runtime-bundle",
|
||||
"raea-runtime-export",
|
||||
"raea-sys-contact",
|
||||
"raea-sys-light-meter",
|
||||
"raea-sys-stage",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-app-solid"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"raea-app-ask",
|
||||
"raea-app-judge",
|
||||
"raea-core-facts",
|
||||
"raea-core-meshcheck",
|
||||
@@ -13955,7 +13999,6 @@ dependencies = [
|
||||
"dunce",
|
||||
"raea-app-check",
|
||||
"raea-app-registry",
|
||||
"raea-core-brief",
|
||||
"raea-core-facts",
|
||||
"raea-io-assets",
|
||||
"raea-io-home",
|
||||
@@ -14176,6 +14219,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"dunce",
|
||||
"raea-app-ask",
|
||||
"raea-app-capcut",
|
||||
"raea-app-check",
|
||||
"raea-app-ci",
|
||||
@@ -14188,6 +14232,7 @@ dependencies = [
|
||||
"raea-app-media",
|
||||
"raea-app-notes",
|
||||
"raea-app-play",
|
||||
"raea-app-scene",
|
||||
"raea-app-solid",
|
||||
"raea-app-sound",
|
||||
"raea-app-targets",
|
||||
@@ -14234,6 +14279,15 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-core-ask"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"ts-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-core-brief"
|
||||
version = "0.1.0"
|
||||
@@ -14464,6 +14518,20 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-io-clef"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"raea-core-ask",
|
||||
"raea-io-assets",
|
||||
"raea-io-ffmpeg",
|
||||
"raea-io-home",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"ureq 2.12.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-io-codec"
|
||||
version = "0.1.0"
|
||||
@@ -14654,6 +14722,16 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-lightbench"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"bytemuck",
|
||||
"meshopt",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-modules"
|
||||
version = "0.1.0"
|
||||
@@ -14735,6 +14813,7 @@ dependencies = [
|
||||
"raea-io-media",
|
||||
"raea-io-net-calls",
|
||||
"raea-io-os",
|
||||
"raea-io-trace",
|
||||
"raea-page",
|
||||
"raea-page-sound",
|
||||
"raea-page-stage",
|
||||
@@ -14771,6 +14850,7 @@ dependencies = [
|
||||
"blitz-dom",
|
||||
"raea-gpu-device",
|
||||
"raea-io-home",
|
||||
"raea-io-trace",
|
||||
"raea-runtime-bake",
|
||||
"raea-runtime-dom",
|
||||
"raea-runtime-js",
|
||||
@@ -14832,11 +14912,13 @@ dependencies = [
|
||||
"raea-runtime-view",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-compute",
|
||||
"raea-sys-engine-shaders",
|
||||
"raea-sys-environment",
|
||||
"raea-sys-fog",
|
||||
"raea-sys-fog-half",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-framepass",
|
||||
"raea-sys-gi",
|
||||
"raea-sys-grass",
|
||||
"raea-sys-grid",
|
||||
"raea-sys-hold",
|
||||
@@ -14873,7 +14955,11 @@ dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2-metal 0.3.2",
|
||||
"objc2-metal-fx",
|
||||
"raea-io-home",
|
||||
"raea-io-trace",
|
||||
"raea-sys-engine-shaders",
|
||||
"raea-sys-post",
|
||||
"raea-sys-rt",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
@@ -14890,6 +14976,7 @@ name = "raea-rune-bevy"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-io-trace",
|
||||
"rune",
|
||||
"wgpu",
|
||||
]
|
||||
@@ -15017,6 +15104,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-io-home",
|
||||
"raea-io-trace",
|
||||
"raea-modules",
|
||||
"raea-runtime-bundle",
|
||||
"raea-runtime-react",
|
||||
@@ -15033,6 +15121,7 @@ dependencies = [
|
||||
"raea-core-scene",
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-io-trace",
|
||||
"raea-native",
|
||||
"raea-runtime-bundle-lib",
|
||||
"raea-runtime-cssurls",
|
||||
@@ -15066,6 +15155,7 @@ dependencies = [
|
||||
"raea-core-shape",
|
||||
"raea-io-media",
|
||||
"raea-io-net",
|
||||
"raea-io-trace",
|
||||
"raea-native",
|
||||
"raea-runtime-plugins",
|
||||
"raea-runtime-wear",
|
||||
@@ -15106,6 +15196,7 @@ dependencies = [
|
||||
"keyboard-types",
|
||||
"raea-core-wire",
|
||||
"raea-io-net",
|
||||
"raea-io-trace",
|
||||
"raea-runtime-dom-media",
|
||||
"raea-runtime-js",
|
||||
"raea-runtime-twins",
|
||||
@@ -15123,6 +15214,7 @@ dependencies = [
|
||||
"bevy",
|
||||
"blitz-dom",
|
||||
"raea-io-net",
|
||||
"raea-io-trace",
|
||||
"raea-runtime-js",
|
||||
"raea-sys-image",
|
||||
"raea-sys-page",
|
||||
@@ -15163,6 +15255,17 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-endchecks"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"raea-core-facts",
|
||||
"raea-core-scene",
|
||||
"raea-sys-contact",
|
||||
"raea-sys-stage",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-export"
|
||||
version = "0.1.0"
|
||||
@@ -15179,10 +15282,12 @@ dependencies = [
|
||||
"raea-io-assets",
|
||||
"raea-io-media",
|
||||
"raea-io-net",
|
||||
"raea-io-trace",
|
||||
"raea-page",
|
||||
"raea-render",
|
||||
"raea-runtime-bake",
|
||||
"raea-runtime-encode",
|
||||
"raea-runtime-endchecks",
|
||||
"raea-runtime-page",
|
||||
"raea-runtime-pagestore",
|
||||
"raea-runtime-react",
|
||||
@@ -15196,6 +15301,8 @@ dependencies = [
|
||||
"raea-sys-light-meter",
|
||||
"raea-sys-mix",
|
||||
"raea-sys-page",
|
||||
"raea-sys-rt",
|
||||
"raea-sys-stage",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
@@ -15209,6 +15316,7 @@ dependencies = [
|
||||
"raea-core-k",
|
||||
"raea-core-program",
|
||||
"raea-gpu-device",
|
||||
"raea-io-trace",
|
||||
"raea-runtime-view",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-k",
|
||||
@@ -15246,6 +15354,7 @@ dependencies = [
|
||||
"raea-io-net",
|
||||
"raea-io-net-calls",
|
||||
"raea-io-os",
|
||||
"raea-io-trace",
|
||||
"raea-runtime-bundle",
|
||||
"raea-runtime-jsengine",
|
||||
"serde",
|
||||
@@ -15260,6 +15369,7 @@ dependencies = [
|
||||
"miniz_oxide 0.8.9",
|
||||
"objc2 0.6.5",
|
||||
"raea-io-home",
|
||||
"raea-io-trace",
|
||||
"rquickjs",
|
||||
]
|
||||
|
||||
@@ -15347,6 +15457,7 @@ dependencies = [
|
||||
"raea-bevy-world",
|
||||
"raea-core-program",
|
||||
"raea-core-shape",
|
||||
"raea-io-trace",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-material",
|
||||
"raea-sys-shader",
|
||||
@@ -15423,6 +15534,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-io-trace",
|
||||
"raea-runtime-plugins",
|
||||
"raea-sys-compute",
|
||||
"raea-sys-copies",
|
||||
@@ -15435,6 +15547,7 @@ dependencies = [
|
||||
"raea-sys-post",
|
||||
"raea-sys-sampler",
|
||||
"raea-sys-shader",
|
||||
"raea-sys-share",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
@@ -15445,6 +15558,7 @@ dependencies = [
|
||||
"muxide",
|
||||
"raea-io-codec",
|
||||
"raea-io-media",
|
||||
"raea-io-trace",
|
||||
"re_mp4",
|
||||
]
|
||||
|
||||
@@ -15476,6 +15590,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-io-assets",
|
||||
"raea-io-trace",
|
||||
"raea-runtime-calls",
|
||||
"raea-runtime-react",
|
||||
"raea-seedling",
|
||||
@@ -15529,6 +15644,7 @@ dependencies = [
|
||||
"raea-gpu-device",
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-io-trace",
|
||||
"raea-page",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-k",
|
||||
@@ -15583,6 +15699,7 @@ dependencies = [
|
||||
"bevy_seedling",
|
||||
"firewheel",
|
||||
"raea-io-media",
|
||||
"raea-io-trace",
|
||||
"raea-sys-mix",
|
||||
"raea-sys-tone",
|
||||
"serde_json",
|
||||
@@ -15673,11 +15790,14 @@ name = "raea-sys-compose"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"bytemuck",
|
||||
"indexmap",
|
||||
"raea-core-program",
|
||||
"raea-io-trace",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-rt",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -15701,6 +15821,7 @@ dependencies = [
|
||||
"raea-core-meshcheck",
|
||||
"raea-core-scene",
|
||||
"raea-core-shape",
|
||||
"raea-io-trace",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
@@ -15723,6 +15844,17 @@ dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-engine-shaders"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-io-trace",
|
||||
"raea-sys-frame",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-environment"
|
||||
version = "0.1.0"
|
||||
@@ -15799,8 +15931,11 @@ dependencies = [
|
||||
"bevy",
|
||||
"bytemuck",
|
||||
"raea-core-program",
|
||||
"raea-io-trace",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-rt",
|
||||
"raea-sys-volume",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -15885,6 +16020,16 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-gi"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-sys-compose",
|
||||
"raea-sys-rt",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-glb"
|
||||
version = "0.1.0"
|
||||
@@ -16030,6 +16175,8 @@ name = "raea-sys-lod"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-io-trace",
|
||||
"raea-sys-frame",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -16064,6 +16211,7 @@ dependencies = [
|
||||
"raea-core-program",
|
||||
"raea-core-shape",
|
||||
"raea-io-net",
|
||||
"raea-io-trace",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-mesh",
|
||||
"raea-sys-sampler",
|
||||
@@ -16102,7 +16250,9 @@ dependencies = [
|
||||
"audioadapter-buffers",
|
||||
"cpal 0.15.3",
|
||||
"firewheel",
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-io-trace",
|
||||
"raea-sys-mix-level",
|
||||
"raea-sys-tone",
|
||||
"serde_json",
|
||||
@@ -16147,8 +16297,10 @@ dependencies = [
|
||||
"blitz-traits",
|
||||
"color",
|
||||
"parley",
|
||||
"raea-core-facts",
|
||||
"raea-core-wire",
|
||||
"raea-gpu-device",
|
||||
"raea-io-trace",
|
||||
"raea-sys-filters",
|
||||
"raea-sys-fonts",
|
||||
"raea-sys-image",
|
||||
@@ -16307,6 +16459,13 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-share"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-shots"
|
||||
version = "0.1.0"
|
||||
@@ -16324,6 +16483,7 @@ dependencies = [
|
||||
"ort",
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-io-trace",
|
||||
"raea-sys-vision",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -16363,6 +16523,17 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-stage"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-facts",
|
||||
"raea-core-scene",
|
||||
"raea-core-shape",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-text3d"
|
||||
version = "0.1.0"
|
||||
@@ -16447,6 +16618,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"raea-core-program",
|
||||
"raea-io-trace",
|
||||
"raea-sys-frame",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
+15
@@ -4,6 +4,7 @@
|
||||
resolver = "2"
|
||||
members = [
|
||||
"core/animate",
|
||||
"core/ask",
|
||||
"core/brief",
|
||||
"core/facts",
|
||||
"core/ease",
|
||||
@@ -61,6 +62,7 @@ members = [
|
||||
"io/codec",
|
||||
"io/media",
|
||||
"io/assets",
|
||||
"io/clef",
|
||||
"io/gen",
|
||||
"io/gen-comfy",
|
||||
"io/gen-core",
|
||||
@@ -114,6 +116,7 @@ members = [
|
||||
"systems/page-net",
|
||||
"systems/page-ops",
|
||||
"systems/frame",
|
||||
"systems/engine-shaders",
|
||||
"systems/shots",
|
||||
"systems/hold",
|
||||
"systems/body",
|
||||
@@ -121,11 +124,14 @@ members = [
|
||||
"systems/layers",
|
||||
"systems/splat",
|
||||
"systems/sprite",
|
||||
"systems/stage",
|
||||
"systems/rt",
|
||||
"systems/gi",
|
||||
"systems/text3d",
|
||||
"runtime/gpuframe",
|
||||
"runtime/scene3d",
|
||||
"systems/copies",
|
||||
"systems/share",
|
||||
"systems/screen",
|
||||
"systems/matchmove",
|
||||
"systems/grid",
|
||||
@@ -167,6 +173,7 @@ members = [
|
||||
"runtime/cssurls",
|
||||
"bench/bridge",
|
||||
"bench/bevy-parity",
|
||||
"bench/lightbench",
|
||||
"bench/bridge/swatch",
|
||||
"bench/rerender/ios",
|
||||
"core/alloc",
|
||||
@@ -179,6 +186,7 @@ members = [
|
||||
"runtime/wear",
|
||||
"runtime/canvas",
|
||||
"runtime/export",
|
||||
"runtime/endchecks",
|
||||
"runtime/live",
|
||||
"runtime/page",
|
||||
"runtime/appscreen",
|
||||
@@ -187,6 +195,8 @@ members = [
|
||||
"runtime/scene",
|
||||
"runtime/scene2d",
|
||||
"runtime/shared",
|
||||
"apps/ask",
|
||||
"apps/double",
|
||||
"apps/check",
|
||||
"apps/check/cause",
|
||||
"apps/check/flash",
|
||||
@@ -206,6 +216,7 @@ members = [
|
||||
"apps/interchange",
|
||||
"apps/judge",
|
||||
"apps/solid",
|
||||
"apps/scene",
|
||||
"apps/media",
|
||||
"apps/targets",
|
||||
"apps/game",
|
||||
@@ -324,6 +335,8 @@ muxide = { path = "vendor/muxide" }
|
||||
usvg = { path = "vendor/usvg" }
|
||||
# bevy_seedling 0.8.0 without its cpal 0.18 paths, ported to Bevy 0.20 (changes marked "raea:")
|
||||
bevy_seedling = { path = "vendor/bevy_seedling" }
|
||||
# bevy_rich_text3d 0.8.0 whose glyph that grows the atlas is drawn whole (changes marked "raea:", docs/stage-guards.feature SG3)
|
||||
bevy_rich_text3d = { path = "vendor/bevy_rich_text3d" }
|
||||
# bevy_text 0.20.0 on parley 0.12, so one parley builds (changes marked "raea:", docs/bevy-upgrade.md)
|
||||
bevy_text = { path = "vendor/bevy_text" }
|
||||
# bevy_ui 0.20.0 on Taffy 0.15, Blitz's, so one Taffy builds (changes marked "raea:", docs/bevy-upgrade.md)
|
||||
@@ -332,6 +345,8 @@ bevy_ui = { path = "vendor/bevy_ui" }
|
||||
# uv_transform, and a panorama's sun sampled as a light rather than found by reflection rays alone (changes marked
|
||||
# "raea:", docs/raytracing.feature RT6). Back to upstream once Solari has these.
|
||||
bevy_solari = { path = "vendor/bevy_solari" }
|
||||
# the sun's far shadow map (raea-sys-rt far.rs) bound in Bevy's mesh view group (docs/bevy-upgrade.md, docs/realism.feature LT21)
|
||||
bevy_pbr = { path = "vendor/bevy_pbr" }
|
||||
# bevy_ui_widgets 0.20.0 on parley 0.12, Blitz's (docs/blitz-bevy.feature B0a)
|
||||
bevy_ui_widgets = { path = "vendor/bevy_ui_widgets" }
|
||||
# blitz-paint 0.3.0-beta.4 with angled gradients in tiles laid out around the tile, many-tile gradient layers drawn
|
||||
|
||||
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,25 +0,0 @@
|
||||
Copyright (c) 2020 Dario Nieuwenhuis
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,316 +0,0 @@
|
||||
AWS Libcrypto (AWS-LC)
|
||||
|
||||
AWS-LC is a fork of BoringSSL, which is itself a fork of OpenSSL.
|
||||
Content from these and other sources retains their original licensing,
|
||||
as described below. New files from AWS-LC are made available under the Apache-2.0 license OR the ISC
|
||||
license. These licenses are reproduced at the bottom of this file.
|
||||
|
||||
```
|
||||
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
SPDX-License-Identifier: Apache-2.0 OR ISC
|
||||
```
|
||||
|
||||
|
||||
================================================================================
|
||||
BoringSSL
|
||||
================================================================================
|
||||
|
||||
BoringSSL is a Google-maintained fork of OpenSSL. Historically, code
|
||||
authored by Google for BoringSSL was licensed under the ISC License.
|
||||
BoringSSL has since relicensed upstream to Apache License 2.0. Existing
|
||||
AWS-LC code originating from BoringSSL retains its ISC license, while
|
||||
newer code taken from BoringSSL is licensed under Apache License 2.0.
|
||||
|
||||
```
|
||||
Copyright (c) 2014-2024 Google Inc.
|
||||
SPDX-License-Identifier: ISC
|
||||
```
|
||||
|
||||
Additional individual contributions to BoringSSL-derived code are
|
||||
covered under the ISC license:
|
||||
|
||||
- Brian Smith (Copyright 2016)
|
||||
- Robert Nagy (Copyright 2022)
|
||||
- Arm Ltd (Copyright 2020)
|
||||
|
||||
```
|
||||
Copyright (c) 2025-2026 Google Inc.
|
||||
SPDX-License-Identifier: Apache-2.0
|
||||
```
|
||||
|
||||
================================================================================
|
||||
OpenSSL
|
||||
================================================================================
|
||||
|
||||
Code derived from the OpenSSL project is licensed under the
|
||||
Apache License, Version 2.0.
|
||||
|
||||
```
|
||||
Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved.
|
||||
SPDX-License-Identifier: Apache-2.0
|
||||
```
|
||||
|
||||
Some OpenSSL-derived files also carry the original SSLeay copyright:
|
||||
|
||||
```
|
||||
Copyright (c) 1995-1998 Eric Young ([email protected]). All rights reserved.
|
||||
SPDX-License-Identifier: Apache-2.0
|
||||
```
|
||||
|
||||
Portions of OpenSSL-derived code include contributions from:
|
||||
|
||||
- Sun Microsystems, Inc. (Copyright 2002)
|
||||
- Nokia (Copyright 2005)
|
||||
- Intel Corporation (Copyright 2012-2021)
|
||||
|
||||
These contributions are covered under the Apache-2.0 license.
|
||||
|
||||
================================================================================
|
||||
mlkem-native
|
||||
================================================================================
|
||||
|
||||
Code from the mlkem-native project is licensed under Apache License 2.0 or MIT or ISC.
|
||||
|
||||
```
|
||||
Copyright (c) The mlkem-native project authors.
|
||||
SPDX-License-Identifier: Apache-2.0 OR ISC OR MIT
|
||||
```
|
||||
|
||||
================================================================================
|
||||
mldsa-native
|
||||
================================================================================
|
||||
|
||||
Code from the mldsa-native project is licensed under Apache License 2.0 or MIT or ISC
|
||||
|
||||
```
|
||||
Copyright (c) The mldsa-native project authors.
|
||||
SPDX-License-Identifier: Apache-2.0 OR ISC OR MIT
|
||||
```
|
||||
|
||||
================================================================================
|
||||
Third-Party Libraries (compiled into libcrypto/libssl)
|
||||
================================================================================
|
||||
|
||||
Fiat Cryptography
|
||||
-----------------
|
||||
Synthesizing Correct-by-Construction Code for Cryptographic Primitives.
|
||||
See third_party/fiat/LICENSE.
|
||||
|
||||
```
|
||||
Copyright (c) 2015-2020 the fiat-crypto authors.
|
||||
SPDX-License-Identifier: MIT
|
||||
```
|
||||
|
||||
s2n-bignum
|
||||
----------
|
||||
Integer arithmetic routines for cryptography.
|
||||
See third_party/s2n-bignum/s2n-bignum-imported/LICENSE.
|
||||
|
||||
```
|
||||
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
SPDX-License-Identifier: Apache-2.0 OR ISC OR MIT-0
|
||||
```
|
||||
|
||||
Note: ML-KEM/SHA3 code within s2n-bignum is licensed as
|
||||
Apache-2.0 OR ISC OR MIT (with attribution), sourced from the
|
||||
mlkem-native project.
|
||||
|
||||
Jitter Entropy RNG
|
||||
-------------------
|
||||
CPU Jitter Random Number Generator Library.
|
||||
See third_party/jitterentropy/jitterentropy-library/LICENSE.
|
||||
|
||||
The Jitter Entropy library is dual-licensed under a BSD-style license
|
||||
and the GNU General Public License Version 2. Amazon expressly elects
|
||||
to distribute the package under the 3-Clause BSD License and NOT under
|
||||
GNU General Public License Version 2.
|
||||
|
||||
```
|
||||
Copyright (C) 2017 - 2025, Stephan Mueller <[email protected]>.
|
||||
SPDX-License-Identifier: BSD-3-Clause
|
||||
```
|
||||
|
||||
Keccak / AES Reference Implementations
|
||||
---------------------------------------
|
||||
Public domain (CC0) contributions.
|
||||
https://creativecommons.org/public-domain/cc0
|
||||
|
||||
Code from sources and by authors listed in comments on top of the respective files.
|
||||
|
||||
|
||||
================================================================================
|
||||
Third-Party Libraries (NOT compiled into libcrypto/libssl)
|
||||
================================================================================
|
||||
|
||||
The following are used for testing and build tooling only. Distributing
|
||||
code linked against AWS-LC (libcrypto/libssl) does NOT trigger these
|
||||
license obligations.
|
||||
|
||||
Google Test
|
||||
-----------
|
||||
See third_party/googletest/LICENSE.
|
||||
|
||||
```
|
||||
Copyright 2008 Google Inc.
|
||||
SPDX-License-Identifier: BSD-3-Clause
|
||||
```
|
||||
|
||||
Go Standard Library
|
||||
-------------------
|
||||
Code in ssl/test/runner/ is derived from the Go standard library.
|
||||
|
||||
```
|
||||
Copyright (c) The Go Authors. All rights reserved.
|
||||
SPDX-License-Identifier: BSD-3-Clause
|
||||
```
|
||||
|
||||
Wycheproof Test Vectors
|
||||
------------------------
|
||||
Project Wycheproof is a community managed repository of test vectors that can be used by cryptography library
|
||||
developers to test against known attacks, specification inconsistencies, and other various implementation bugs.
|
||||
|
||||
See third_party/wycheproof_testvectors/LICENSE.
|
||||
|
||||
```
|
||||
SPDX-License-Identifier: Apache-2.0
|
||||
```
|
||||
|
||||
|
||||
================================================================================
|
||||
Full License Texts
|
||||
================================================================================
|
||||
|
||||
Apache License 2.0
|
||||
------------------
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
||||
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
||||
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
||||
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
||||
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
||||
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
||||
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
||||
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
||||
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
||||
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
ISC License
|
||||
-----------
|
||||
Permission to use, copy, modify, and/or distribute this software for
|
||||
any purpose with or without fee is hereby granted, provided that the
|
||||
above copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
|
||||
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
|
||||
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
|
||||
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
|
||||
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
|
||||
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
MIT License
|
||||
-----------
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
BSD 3-Clause License
|
||||
--------------------
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
MIT No Attribution (MIT-0)
|
||||
--------------------------
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,25 +0,0 @@
|
||||
Copyright (c) 2020-2025 The RustCrypto Project Developers
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,176 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
@@ -1,25 +0,0 @@
|
||||
Copyright (c) 2023 Thomas Pendock
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,202 +0,0 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,25 +0,0 @@
|
||||
Copyright (c) 2018 Jorge Aparicio
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,25 +0,0 @@
|
||||
Copyright (c) 2017 Jorge Aparicio
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 Dzmitry Malyshau
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,25 +0,0 @@
|
||||
Copyright (c) 2019 Anthony James Munns
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,12 +0,0 @@
|
||||
Copyrights in the Rand project are retained by their contributors. No
|
||||
copyright assignment is required to contribute to the Rand project.
|
||||
|
||||
For full authorship information, see the version control history.
|
||||
|
||||
Except as otherwise noted (below and/or in individual files), Rand is
|
||||
licensed under the Apache License, Version 2.0 <LICENSE-APACHE> or
|
||||
<http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
<LICENSE-MIT> or <http://opensource.org/licenses/MIT>, at your option.
|
||||
|
||||
The Rand project includes code from the Rust project
|
||||
published under these same licenses.
|
||||
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
https://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,26 +0,0 @@
|
||||
Copyright 2018 Developers of the Rand project
|
||||
Copyright (c) 2014 The Rust Project Developers
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,10 +0,0 @@
|
||||
Rustls is distributed under the following three licenses:
|
||||
|
||||
- Apache License version 2.0.
|
||||
- MIT license.
|
||||
- ISC license.
|
||||
|
||||
These are included as LICENSE-APACHE, LICENSE-MIT and LICENSE-ISC
|
||||
respectively. You may use this software under the terms of any
|
||||
of these licenses, at your option.
|
||||
|
||||
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,15 +0,0 @@
|
||||
ISC License (ISC)
|
||||
Copyright (c) 2016, Joseph Birr-Pixton <[email protected]>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for
|
||||
any purpose with or without fee is hereby granted, provided that the
|
||||
above copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
|
||||
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
|
||||
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
|
||||
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
|
||||
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
||||
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||
THIS SOFTWARE.
|
||||
@@ -1,25 +0,0 @@
|
||||
Copyright (c) 2016 Joseph Birr-Pixton <[email protected]>
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,20 +0,0 @@
|
||||
rustls-platform-verifier-android 0.2.0 ships no licence file of its own. Its Cargo.toml declares MIT OR Apache-2.0, by its authors.
|
||||
|
||||
---- Apache-2.0: the text is LICENSES/texts/Apache-2.0.txt ----
|
||||
|
||||
---- MIT ----
|
||||
|
||||
Copyright (c) its authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
|
||||
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
|
||||
persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
|
||||
Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
|
||||
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,6 +0,0 @@
|
||||
Copyright 2021 Travis Veazey
|
||||
|
||||
Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
|
||||
http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
|
||||
http://opensource.org/licenses/MIT>, at your option. This file may not be
|
||||
copied, modified, or distributed except according to those terms.
|
||||
@@ -1,202 +0,0 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,25 +0,0 @@
|
||||
Copyright (c) 2016 The Amethyst Project Developers
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,21 +0,0 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Mathijs van de Nes
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,20 +0,0 @@
|
||||
© 2016 Bertram Truong
|
||||
© 2021 Kornel Lesiński
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
@@ -27,7 +27,9 @@ paths for Windows in runtime/bundle). Its bin\ also carries, each with its licen
|
||||
and libvpx 1.17.0's decoders (BSD-3-Clause with the WebM project's patent grant: libvpx-LICENSE.txt,
|
||||
libvpx-PATENTS.txt) by tools/release/ffmpeg-win.sh, its H.264 encoder Windows' own (Media Foundation), its source
|
||||
published as the release tools-ffmpeg-9.0.2-lgpl;
|
||||
uv (uv.exe; Astral, MIT OR Apache-2.0).
|
||||
uv (uv.exe; Astral, MIT OR Apache-2.0);
|
||||
Microsoft's DirectX Shader Compiler v1.8.2502 (dxcompiler.dll, dxil.dll), DX12's shader compiler, redistributed under
|
||||
its licence terms (dxc-LICENSE-MS.txt; its LLVM parts under dxc-LICENSE-LLVM.txt and dxc-LICENSE-MIT.txt).
|
||||
The Windows app adds Git for Windows with Git LFS (dugite-native; GPLv2 and its parts' licences, in git\), which raea
|
||||
runs as a separate program; its complete corresponding source is published as the release tools-git-<tag>-sources.
|
||||
raea.exe, on a PC with no Git, fetches the same build once into its tools cache (io/assets git()).
|
||||
@@ -66,7 +68,6 @@ LICENSES/<crate>-<version>/.
|
||||
async-recursion 1.2.0: MIT OR Apache-2.0
|
||||
async-signal 0.2.14: Apache-2.0 OR MIT
|
||||
atomic-arena 0.1.2: MIT OR Apache-2.0
|
||||
atomic-polyfill 1.0.3: MIT OR Apache-2.0
|
||||
atspi-common 0.13.0: Apache-2.0 OR MIT
|
||||
atspi-proxies 0.13.0: Apache-2.0 OR MIT
|
||||
atspi 0.29.0: Apache-2.0 OR MIT
|
||||
@@ -74,8 +75,6 @@ LICENSES/<crate>-<version>/.
|
||||
avian_derive 0.2.3: MIT OR Apache-2.0
|
||||
avian2d 0.8.0: MIT OR Apache-2.0
|
||||
avian3d 0.8.0: MIT OR Apache-2.0
|
||||
aws-lc-rs 1.18.2: ISC AND (Apache-2.0 OR ISC)
|
||||
aws-lc-sys 0.46.0: ISC AND (Apache-2.0 OR ISC) AND Apache-2.0 AND MIT AND BSD-3-Clause AND (Apache-2.0 OR ISC OR MIT) AND (Apache-2.0 OR ISC OR MIT-0)
|
||||
az 1.3.0: MIT/Apache-2.0
|
||||
basis-universal-sys 0.3.1: MIT OR Apache-2.0
|
||||
basis-universal 0.3.1: MIT OR Apache-2.0
|
||||
@@ -172,7 +171,6 @@ LICENSES/<crate>-<version>/.
|
||||
deluxe-core 0.5.0: MIT
|
||||
deluxe-macros 0.5.0: MIT
|
||||
deluxe 0.5.0: MIT
|
||||
der_derive 0.8.0: Apache-2.0 OR MIT
|
||||
der-parser 10.0.0: MIT OR Apache-2.0
|
||||
deranged 0.5.9: MIT OR Apache-2.0
|
||||
derive-getters 0.5.0: MIT
|
||||
@@ -192,15 +190,12 @@ LICENSES/<crate>-<version>/.
|
||||
enumflags2 0.7.12: MIT OR Apache-2.0
|
||||
epaint_default_fonts 0.36.2: (MIT OR Apache-2.0) AND OFL-1.1 AND Ubuntu-font-1.0
|
||||
epaint 0.36.2: MIT OR Apache-2.0
|
||||
fastbloom 0.17.0: MIT OR Apache-2.0
|
||||
fastnoise-lite 1.1.1: MIT
|
||||
fid-rs 0.2.0: MIT OR Apache-2.0
|
||||
file-id 0.2.3: MIT OR Apache-2.0
|
||||
fixed 1.31.0: MIT/Apache-2.0
|
||||
flagset 0.4.7: Apache-2.0
|
||||
float_next_after 2.0.0: MIT
|
||||
float-ord 0.3.2: MIT / Apache-2.0
|
||||
fs_extra 1.3.0: MIT
|
||||
fsevent-sys 4.1.0: MIT
|
||||
futures-timer 3.0.4: MIT/Apache-2.0
|
||||
fuzzy-matcher 0.3.7: MIT
|
||||
@@ -213,8 +208,6 @@ LICENSES/<crate>-<version>/.
|
||||
glam 0.19.0: MIT OR Apache-2.0
|
||||
gloo-timers 0.3.0: MIT OR Apache-2.0
|
||||
governor 0.10.4: MIT
|
||||
hash32 0.2.1: MIT OR Apache-2.0
|
||||
heapless 0.7.17: MIT OR Apache-2.0
|
||||
heck 0.4.1: MIT OR Apache-2.0
|
||||
httlib-huffman 0.3.4: MIT
|
||||
i_float 1.16.0: MIT
|
||||
@@ -276,7 +269,6 @@ LICENSES/<crate>-<version>/.
|
||||
metis 0.2.2: MIT OR Apache-2.0
|
||||
metrics-util 0.20.4: MIT
|
||||
metrics 0.24.6: MIT
|
||||
mint 0.5.9: MIT
|
||||
mock_instant 0.6.1: 0BSD
|
||||
moonshine-save 0.8.0: MIT
|
||||
moonshine-util 0.6.0: MIT
|
||||
@@ -316,7 +308,6 @@ LICENSES/<crate>-<version>/.
|
||||
pollster 1.0.1: Apache-2.0/MIT
|
||||
poly1305 0.8.0: Apache-2.0 OR MIT
|
||||
polyanya 0.18.0: MIT OR Apache-2.0
|
||||
postcard-derive 0.2.2: MIT OR Apache-2.0
|
||||
powerfmt 0.2.1: MIT OR Apache-2.0
|
||||
proc-macro-crate 1.3.1: MIT OR Apache-2.0
|
||||
proc-macro-error-attr 1.0.4: MIT OR Apache-2.0
|
||||
@@ -328,7 +319,6 @@ LICENSES/<crate>-<version>/.
|
||||
quick-xml 0.31.0: MIT
|
||||
quick-xml 0.38.4: MIT
|
||||
radix_trie 0.2.1: MIT
|
||||
rand_chacha 0.3.1: MIT OR Apache-2.0
|
||||
rand_xorshift 0.3.0: MIT OR Apache-2.0
|
||||
rand_xoshiro 0.7.0: MIT OR Apache-2.0
|
||||
rapidhash 4.5.1: MIT OR Apache-2.0
|
||||
@@ -347,13 +337,9 @@ LICENSES/<crate>-<version>/.
|
||||
rune-staging 0.0.1: MIT
|
||||
rune 0.0.1: MIT
|
||||
rusticata-macros 4.1.0: MIT/Apache-2.0
|
||||
rustls-native-certs 0.8.5: Apache-2.0 OR ISC OR MIT
|
||||
rustls-pemfile 2.2.0: Apache-2.0 OR ISC OR MIT
|
||||
rustls-platform-verifier-android 0.2.0: MIT OR Apache-2.0
|
||||
rustls-platform-verifier 0.7.1: MIT OR Apache-2.0
|
||||
seahash 4.1.0: MIT
|
||||
selectors 0.38.0: MPL-2.0
|
||||
serde_arrays 0.2.0: MIT OR Apache-2.0
|
||||
serde_flexitos 0.2.2: Apache-2.0
|
||||
serde_regex 1.2.0: MIT OR Apache-2.0
|
||||
serde_repr 0.1.21: MIT OR Apache-2.0
|
||||
@@ -363,7 +349,6 @@ LICENSES/<crate>-<version>/.
|
||||
sif-itree 0.4.1: MIT OR Apache-2.0
|
||||
sketches-ddsketch 0.3.1: Apache-2.0
|
||||
smart-default 0.7.1: MIT
|
||||
spin 0.9.9: MIT
|
||||
spinning_top 0.3.0: MIT/Apache-2.0
|
||||
spki 0.8.1: Apache-2.0 OR MIT
|
||||
steamworks-sys 0.13.0: MIT / Apache-2.0
|
||||
@@ -394,7 +379,6 @@ LICENSES/<crate>-<version>/.
|
||||
unicode-general-category 1.1.0: Apache-2.0
|
||||
universal-hash 0.5.1: MIT OR Apache-2.0
|
||||
unsafe-libyaml 0.2.11: MIT
|
||||
urlencoding 2.1.3: MIT
|
||||
usvg 0.45.1: Apache-2.0 OR MIT
|
||||
vleue_navigator 0.17.0: MIT OR Apache-2.0
|
||||
voracious_radix_sort 1.2.0: MIT
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "raea-app-ask"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea ask: questions about a piece's picture and sound, prepared from what raea knows of it, asked of clef in parallel from the person's plan, and every answer kept"
|
||||
|
||||
[dependencies]
|
||||
# the question format and the standard sets; the one clef client, routed to the person's plan first (docs/ask.feature)
|
||||
raea-core-ask = { path = "../../core/ask" }
|
||||
raea-io-clef = { path = "../../io/clef" }
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
# the fingerprint's AUC, quantile and gates, so a question is calibrated as an axis is (AK7)
|
||||
raea-sys-fingerprint = { path = "../../systems/fingerprint" }
|
||||
# today's date for a calibration
|
||||
raea-io-trace = { path = "../../io/trace" }
|
||||
dunce = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sha2 = "0.10"
|
||||
|
||||
[dev-dependencies]
|
||||
raea-io-assets = { path = "../../io/assets" }
|
||||
@@ -0,0 +1,214 @@
|
||||
//! Calibration (docs/ask.feature AK7): a question's answers held to the person's labels (labels.rs), per version of its
|
||||
//! words. Clef isn't trained on the labels, so its AUC on them is held out already; the one thing fitted is the
|
||||
//! threshold, the problem score that flags 10% of the clean labels. The gates are the fingerprint's (16 labels of each
|
||||
//! kind, from 3 projects, an AUC of 0.8). A question that passes is calibrated at its threshold: its answers are
|
||||
//! findings, and the person's calibration replaces raea's shipped one. One under 0.6 after 32 labels doesn't separate,
|
||||
//! and says which labels it missed, so its words can be fixed. `raea ask try` asks new words of the labelled clips and
|
||||
//! sets both AUCs side by side.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use raea_core_ask::{Calibration, Question};
|
||||
use raea_io_clef::Media;
|
||||
use raea_sys_fingerprint::head::{auc, quantile};
|
||||
use raea_sys_fingerprint::train::{GATE_AUC, GATE_LABELS, GATE_PROJECTS};
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::labels::{self, Label};
|
||||
use crate::prepare::Piece;
|
||||
use crate::record;
|
||||
use crate::runner::{self, Event, Group, Kept, Opts, Summary};
|
||||
|
||||
pub const FILE: &str = "calibration.json";
|
||||
/// An AUC under this after twice the gate's labels: the words don't separate the problem.
|
||||
const SEPARATES: f64 = 0.6;
|
||||
|
||||
/// The person's calibrations that passed the gates, by question version.
|
||||
pub fn local() -> BTreeMap<String, Calibration> {
|
||||
std::fs::read_to_string(record::dir().join(FILE)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A question with the person's calibration in place of raea's, when it has one.
|
||||
pub fn apply(q: &mut Question, local: &BTreeMap<String, Calibration>) {
|
||||
if let Some(c) = local.get(&q.version()) {
|
||||
q.calibration = Some(c.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// A label the answers missed: a problem it scored low, or clean work it scored high.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Miss {
|
||||
pub file: String,
|
||||
pub span: String,
|
||||
pub problem: f64,
|
||||
pub bad: bool,
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
/// One version's standing.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Standing {
|
||||
pub id: String,
|
||||
pub version: String,
|
||||
pub ask: String,
|
||||
pub problems: usize,
|
||||
pub clean: usize,
|
||||
pub projects: usize,
|
||||
pub auc: Option<f64>,
|
||||
pub threshold: Option<f64>,
|
||||
/// calibrated, advice or "doesn't separate"
|
||||
pub state: String,
|
||||
pub why: String,
|
||||
pub misses: Vec<Miss>,
|
||||
/// other eyes' labels on its clips, kept and not counted
|
||||
pub others: usize,
|
||||
}
|
||||
|
||||
/// Each labelled clip's latest problem score for one version, beside its label.
|
||||
fn scored<'a>(version: &str, standing: &HashMap<(String, String), &'a Label>, calls: &HashMap<String, Value>) -> Vec<(f64, &'a Label)> {
|
||||
let mut latest: HashMap<String, (f64, &Label)> = HashMap::new();
|
||||
for a in record::rows("answers.jsonl").iter().filter(|a| a["version"] == version) {
|
||||
let (Some(p), Some(call)) = (a["problem"].as_f64(), calls.get(a["call"].as_str().unwrap_or_default())) else { continue };
|
||||
let key = (a["question"].as_str().unwrap_or_default().to_string(), labels::media_key(call));
|
||||
if let Some(l) = standing.get(&key) {
|
||||
latest.insert(key.1, (p, l));
|
||||
}
|
||||
}
|
||||
latest.into_values().collect()
|
||||
}
|
||||
|
||||
/// One version held to its labels.
|
||||
pub fn standing_of(q: &Question, all: &[Label], calls: &HashMap<String, Value>) -> Standing {
|
||||
let standing = labels::standing(all);
|
||||
let s = scored(&q.version(), &standing, calls);
|
||||
let score = |bad: bool| s.iter().filter(|(_, l)| l.bad == bad).map(|(p, _)| *p as f32).collect::<Vec<f32>>();
|
||||
let (pos, neg) = (score(true), score(false));
|
||||
let projects = s.iter().map(|(_, l)| l.project.as_str()).collect::<BTreeSet<_>>().len();
|
||||
let a = Some(auc(&pos, &neg)).filter(|a| a.is_finite());
|
||||
let threshold = Some(quantile(&neg, 0.9) as f64).filter(|t| t.is_finite());
|
||||
let mut why = Vec::new();
|
||||
if pos.len() < GATE_LABELS || neg.len() < GATE_LABELS {
|
||||
why.push(format!("{} problem and {} clean labels (needs {GATE_LABELS} of each)", pos.len(), neg.len()));
|
||||
}
|
||||
if projects < GATE_PROJECTS {
|
||||
why.push(format!("labels from {projects} projects (needs {GATE_PROJECTS})"));
|
||||
}
|
||||
match a {
|
||||
Some(v) if v < GATE_AUC => why.push(format!("AUC {v:.2} (needs {GATE_AUC})")),
|
||||
None => why.push("no AUC yet: it needs labels of both kinds".into()),
|
||||
_ => {}
|
||||
}
|
||||
let stuck = s.len() >= 2 * GATE_LABELS && a.is_some_and(|v| v < SEPARATES);
|
||||
let mut misses: Vec<Miss> = Vec::new();
|
||||
if stuck {
|
||||
let mut by: Vec<&(f64, &Label)> = s.iter().collect();
|
||||
by.sort_by(|x, y| x.0.total_cmp(&y.0));
|
||||
let low = by.iter().filter(|(_, l)| l.bad).take(5);
|
||||
let high = by.iter().rev().filter(|(_, l)| !l.bad).take(5);
|
||||
misses = low.chain(high).map(|(p, l)| Miss { file: l.file.clone(), span: labels::span(l.from, l.to), problem: *p, bad: l.bad, note: l.note.clone() }).collect();
|
||||
}
|
||||
let others = all.iter().filter(|l| !l.counted() && l.question == q.id).count();
|
||||
let state = match (why.is_empty(), stuck) {
|
||||
(true, _) => "calibrated",
|
||||
(false, true) => "doesn't separate",
|
||||
(false, false) => "advice",
|
||||
};
|
||||
let why = if why.is_empty() { format!("earned: {} labels from {projects} projects, flags past {:.2}", s.len(), threshold.unwrap_or(0.0)) } else { why.join("; ") };
|
||||
Standing { id: q.id.clone(), version: q.version(), ask: q.ask.clone(), problems: pos.len(), clean: neg.len(), projects, auc: a, threshold, state: state.into(), why, misses, others }
|
||||
}
|
||||
|
||||
/// Every labelled question's versions as the record kept them (or only `id`'s), newest wording last.
|
||||
fn versions(only: Option<&str>, all: &[Label]) -> Vec<Question> {
|
||||
let labelled: BTreeSet<&str> = all.iter().map(|l| l.question.as_str()).collect();
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut out = Vec::new();
|
||||
for a in record::rows("answers.jsonl") {
|
||||
let id = a["question"].as_str().unwrap_or_default();
|
||||
if only.is_some_and(|o| o != id) || !labelled.contains(id) || !seen.insert(a["version"].as_str().unwrap_or_default().to_string()) {
|
||||
continue;
|
||||
}
|
||||
out.push(labels::question_of(&a));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `raea ask calibrate [ID]`: the feed's labels read again, then every labelled version held to them. The ones that
|
||||
/// pass are kept as the person's calibration; one that no longer passes loses it.
|
||||
pub fn calibrate(only: Option<&str>) -> Result<(Vec<Standing>, (usize, usize)), String> {
|
||||
let feed = labels::from_feed()?;
|
||||
let (all, calls) = (labels::all(), labels::calls());
|
||||
let out: Vec<Standing> = versions(only, &all).iter().map(|q| standing_of(q, &all, &calls)).collect();
|
||||
let mut keep = local();
|
||||
for s in &out {
|
||||
keep.remove(&s.version);
|
||||
if s.state == "calibrated" {
|
||||
let n = (s.problems + s.clean) as u32;
|
||||
let c = Calibration { auc: s.auc.unwrap_or(0.0), n, positives: s.problems as u32, threshold: s.threshold, date: today(), by: "you".into() };
|
||||
keep.insert(s.version.clone(), c);
|
||||
}
|
||||
}
|
||||
record::write_whole(FILE, &serde_json::to_string_pretty(&keep).map_err(|e| e.to_string())?)?;
|
||||
Ok((out, feed))
|
||||
}
|
||||
|
||||
/// YYYY-MM-DD, UTC.
|
||||
fn today() -> String {
|
||||
raea_io_trace::utc(std::time::SystemTime::now()).0.chars().take(10).collect()
|
||||
}
|
||||
|
||||
/// The groups `raea ask try` sends: the new question on each labelled clip set, with the state it was asked with.
|
||||
pub fn try_groups(like: &str, words: &str) -> Result<(Question, Question, Vec<Group>), String> {
|
||||
let all = labels::all();
|
||||
let standing = labels::standing(&all);
|
||||
let rows = record::rows("answers.jsonl");
|
||||
let old = rows.iter().rev().find(|a| a["question"] == like).map(labels::question_of).ok_or_else(|| format!("ask try: no answers to {like} in the record"))?;
|
||||
let new = Question { ask: words.to_string(), calibration: None, ..old.clone() };
|
||||
let calls = labels::calls();
|
||||
let mut groups: Vec<Group> = Vec::new();
|
||||
let mut sent = BTreeSet::new();
|
||||
for call in calls.values().filter(|c| standing.contains_key(&(like.to_string(), labels::media_key(c)))) {
|
||||
let names: Vec<&str> = call["media"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
|
||||
let Some(kept) = media(&names) else { continue };
|
||||
if !sent.insert(labels::media_key(call)) {
|
||||
continue;
|
||||
}
|
||||
let piece = Arc::new(Piece { file: PathBuf::from(call["file"].as_str().unwrap_or_default()), project: call["project"].as_str().map(PathBuf::from), ..Default::default() });
|
||||
let (from, to) = (call["from"].as_f64().unwrap_or(0.0), call["to"].as_f64());
|
||||
let seconds = to.map_or(60.0, |t| t - from);
|
||||
let kept = Kept { video_seconds: if kept.videos.is_empty() { 0.0 } else { seconds }, sound_seconds: if kept.sounds.is_empty() { 0.0 } else { seconds }, media: kept, state: call["state"].as_str().unwrap_or_default().into() };
|
||||
groups.push(Group { piece, from, to, sees: new.sees, hears: new.hears, with: vec![], questions: vec![new.clone()], kept: Some(Arc::new(kept)) });
|
||||
}
|
||||
if groups.is_empty() {
|
||||
return Err(format!("ask try: none of {like}'s labelled clips are still kept (raea ask calibrate lists its labels)"));
|
||||
}
|
||||
Ok((old, new, groups))
|
||||
}
|
||||
|
||||
/// A call's clips from the kept media, in the kinds they were sent as; None when one has been pruned.
|
||||
fn media(names: &[&str]) -> Option<Media> {
|
||||
let mut m = Media::default();
|
||||
for n in names {
|
||||
let bytes = record::media(n)?;
|
||||
match n.rsplit('.').next() {
|
||||
Some("mp4") => m.videos.push(bytes),
|
||||
Some("mp3") => m.sounds.push(bytes),
|
||||
_ => m.stills.push(bytes),
|
||||
}
|
||||
}
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// `raea ask try "WORDS" --like ID`: the new words asked of the old question's labelled clips, and both versions held to
|
||||
/// the same labels.
|
||||
pub fn try_words(like: &str, words: &str, o: &Opts, out: &mut dyn FnMut(Event)) -> Result<(Summary, Option<(Standing, Standing)>), String> {
|
||||
let (old, new, groups) = try_groups(like, words)?;
|
||||
let sum = runner::run_groups(groups, Vec::new(), o, out);
|
||||
if o.dry {
|
||||
return Ok((sum, None));
|
||||
}
|
||||
let (all, calls) = (labels::all(), labels::calls());
|
||||
Ok((sum, Some((standing_of(&old, &all, &calls), standing_of(&new, &all, &calls)))))
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
//! Labels (docs/ask.feature AK6): whether a question's problem was really there in what one call sent, so the question
|
||||
//! can be calibrated on the person's own eye (calibrate.rs). A label belongs to a question and to the clips a call sent
|
||||
//! (by their hashes), never to one answer: the same question reworded, asked again of the same clips, has the same
|
||||
//! labels, which is what lets `raea ask try` measure new words.
|
||||
//!
|
||||
//! Where labels come from:
|
||||
//! - `raea ask verdict ANSWER WORD`: the person answers the question themselves, in its own terms (yes or no, an option,
|
||||
//! a level). Theirs counts first.
|
||||
//! - The feed: a note of the person's on the render (its copy in the project's feed, known by `record::ident`), pinned
|
||||
//! inside the window or not pinned at all, holding one of the question's label words, is a yes; an approved post (done)
|
||||
//! with no such note is a no. Read again by every `raea ask calibrate`.
|
||||
//! - Another eye (`verdict --eye agent`: an agent's own look) is kept as `eye:NAME` and never counted, as the
|
||||
//! fingerprint keeps another eye's readings (FP6d).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_ask::{Kind, Question};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::record;
|
||||
|
||||
pub const FILE: &str = "labels.jsonl";
|
||||
|
||||
/// A note pinned at t covers 1.5 s before it to 0.5 s after (the fingerprint's span).
|
||||
const BEFORE: f64 = 1.5;
|
||||
const AFTER: f64 = 0.5;
|
||||
|
||||
/// Whether a question's problem is there in one call's clips, and who said so.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Label {
|
||||
pub question: String,
|
||||
/// the clips the call sent, by hash
|
||||
pub media: String,
|
||||
pub bad: bool,
|
||||
/// "verdict" (the person's), "note" or "approval" (read from the feed), or "eye:NAME" (kept, never counted)
|
||||
pub source: String,
|
||||
pub project: String,
|
||||
pub file: String,
|
||||
pub from: f64,
|
||||
pub to: Option<f64>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub note: Option<String>,
|
||||
pub at: String,
|
||||
}
|
||||
|
||||
impl Label {
|
||||
/// The person's own: a verdict, a note or an approval.
|
||||
pub fn counted(&self) -> bool {
|
||||
self.rank() > 0
|
||||
}
|
||||
fn rank(&self) -> u8 {
|
||||
match self.source.as_str() {
|
||||
"verdict" => 3,
|
||||
"note" => 2,
|
||||
"approval" => 1,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The clips a call sent, as one key.
|
||||
pub fn media_key(call: &Value) -> String {
|
||||
let mut m: Vec<&str> = call["media"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
|
||||
m.sort_unstable();
|
||||
m.join("+")
|
||||
}
|
||||
|
||||
/// The feed a call's render was posted to: its project's, else the nearest one above its file.
|
||||
fn feed_of(call: &Value) -> Option<PathBuf> {
|
||||
let file = Path::new(call["file"].as_str().unwrap_or_default());
|
||||
call["project"].as_str().map(Path::new).into_iter().chain(file.ancestors()).map(|d| d.join(".raea/feed")).find(|d| d.is_dir())
|
||||
}
|
||||
|
||||
/// A call's project: the folder holding its brief, else the folder holding the feed it was posted to, else its file's.
|
||||
pub fn project_of(call: &Value) -> String {
|
||||
if let Some(p) = call["project"].as_str() {
|
||||
return p.to_string();
|
||||
}
|
||||
let home = feed_of(call).and_then(|f| f.parent()?.parent().map(Path::to_path_buf));
|
||||
let file = Path::new(call["file"].as_str().unwrap_or_default());
|
||||
home.as_deref().or(file.parent()).map(|p| p.display().to_string()).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn all() -> Vec<Label> {
|
||||
record::rows(FILE).into_iter().filter_map(|v| serde_json::from_value(v).ok()).collect()
|
||||
}
|
||||
|
||||
fn write(labels: &[Label]) -> Result<(), String> {
|
||||
record::write_whole(FILE, &labels.iter().filter_map(|l| serde_json::to_string(l).ok()).map(|l| l + "\n").collect::<String>())
|
||||
}
|
||||
|
||||
/// The label that stands for each question and clips: the person's verdict, else a note, else an approval.
|
||||
pub fn standing(labels: &[Label]) -> HashMap<(String, String), &Label> {
|
||||
let mut out: HashMap<(String, String), &Label> = HashMap::new();
|
||||
for l in labels.iter().filter(|l| l.counted()) {
|
||||
let key = (l.question.clone(), l.media.clone());
|
||||
if out.get(&key).is_none_or(|was| l.rank() >= was.rank()) {
|
||||
out.insert(key, l);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A question as its answer kept it (the whole question, else its words).
|
||||
pub fn question_of(answer: &Value) -> Question {
|
||||
serde_json::from_value(answer["q"].clone()).unwrap_or_else(|_| Question::plain(answer["question"].as_str().unwrap_or("q"), answer["ask"].as_str().unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// Whether the answer the person gives means the problem is there: yes's flagged answer (yes, or no for a question
|
||||
/// flagged on no), a flagged option, or a grade or rate in its lower half.
|
||||
pub fn means_problem(q: &Question, said: &str) -> Result<bool, String> {
|
||||
let said = said.trim().to_lowercase();
|
||||
let levels = q.levels();
|
||||
if q.kind == Kind::Yes {
|
||||
return match said.as_str() {
|
||||
"yes" | "no" => Ok((said == "yes") != q.flags.first().is_some_and(|f| f == "no")),
|
||||
_ => Err(format!("{}: answer yes or no", q.id)),
|
||||
};
|
||||
}
|
||||
if q.kind == Kind::Choose && q.flags.is_empty() {
|
||||
return Err(format!("{} picks without a wrong answer, so it isn't calibrated", q.id));
|
||||
}
|
||||
let Some(i) = levels.iter().position(|l| l.to_lowercase() == said) else { return Err(format!("{}: answer one of {}", q.id, levels.join(", "))) };
|
||||
Ok(match q.kind {
|
||||
Kind::Choose => q.flags.iter().any(|f| f.to_lowercase() == said),
|
||||
_ => (i as f64) < (levels.len().max(2) - 1) as f64 / 2.0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Every call in the record, by id.
|
||||
pub fn calls() -> HashMap<String, Value> {
|
||||
record::rows("calls.jsonl").into_iter().filter_map(|c| Some((c["id"].as_str()?.to_string(), c))).collect()
|
||||
}
|
||||
|
||||
fn label(q: &str, call: &Value, bad: bool, source: &str, note: Option<String>) -> Label {
|
||||
Label {
|
||||
question: q.to_string(),
|
||||
media: media_key(call),
|
||||
bad,
|
||||
source: source.into(),
|
||||
project: project_of(call),
|
||||
file: call["file"].as_str().unwrap_or_default().into(),
|
||||
from: call["from"].as_f64().unwrap_or(0.0),
|
||||
to: call["to"].as_f64(),
|
||||
note,
|
||||
at: record::now(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `raea ask verdict ANSWER WORD [--eye NAME]`: the person's answer to the question on that answer's clips (or another
|
||||
/// eye's, kept and never counted). A verdict given again replaces the last from the same source.
|
||||
pub fn verdict(answer: &str, said: &str, eye: Option<&str>) -> Result<String, String> {
|
||||
let row = record::rows("answers.jsonl").into_iter().find(|a| a["id"] == answer).ok_or_else(|| format!("ask verdict: no answer {answer} in {}", record::dir().display()))?;
|
||||
let call = calls().remove(row["call"].as_str().unwrap_or_default()).ok_or_else(|| format!("ask verdict: answer {answer}'s call isn't in the record"))?;
|
||||
let q = question_of(&row);
|
||||
let bad = means_problem(&q, said)?;
|
||||
let source = eye.map_or_else(|| "verdict".to_string(), |e| format!("eye:{e}"));
|
||||
let new = label(&q.id, &call, bad, &source, None);
|
||||
let mut labels = all();
|
||||
labels.retain(|l| !(l.question == new.question && l.media == new.media && l.source == new.source));
|
||||
let line = format!("{}: {} on {} ({}){}", q.id, if bad { "the problem is there" } else { "no problem" }, new.file, span(new.from, new.to), if eye.is_some() { format!(", kept as {source} and not counted") } else { String::new() });
|
||||
labels.push(new);
|
||||
write(&labels)?;
|
||||
Ok(line)
|
||||
}
|
||||
|
||||
pub fn span(from: f64, to: Option<f64>) -> String {
|
||||
match to {
|
||||
Some(t) => format!("{from:.1}-{t:.1} s"),
|
||||
None if from > 0.0 => format!("from {from:.1} s"),
|
||||
None => "the whole file".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// One post of a feed: whether it's approved, its person's notes (pinned second or none, words), and its files.
|
||||
struct Post {
|
||||
done: bool,
|
||||
notes: Vec<(Option<f64>, String)>,
|
||||
files: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
fn posts(feed: &Path) -> Vec<Post> {
|
||||
let project = feed.parent().and_then(Path::parent).unwrap_or(feed);
|
||||
let lib = raea_io_home::user_home().unwrap_or_default().join(".raea/feed/media");
|
||||
let mut out = Vec::new();
|
||||
for e in std::fs::read_dir(feed).into_iter().flatten().flatten() {
|
||||
let Some(p) = std::fs::read_to_string(e.path()).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()) else { continue };
|
||||
let notes = p["notes"].as_array().into_iter().flatten().filter(|n| n["author"]["kind"] == "person").filter_map(|n| Some((n["pin"]["t"].as_f64(), n["text"].as_str()?.to_lowercase()))).collect();
|
||||
let files = p["media"].as_array().into_iter().flatten().filter_map(|m| m["path"].as_str()).filter_map(|m| [lib.join(m), project.join(m)].into_iter().find(|f| f.is_file())).collect();
|
||||
out.push(Post { done: p["status"] == "done", notes, files });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Labels read again from the person's notes and approvals, for every recorded answer whose question has label words.
|
||||
/// The feed's labels replace the last ones read; verdicts and other eyes' stay. Says how many of each it found.
|
||||
pub fn from_feed() -> Result<(usize, usize), String> {
|
||||
let calls = calls();
|
||||
let mut feeds: HashMap<PathBuf, Vec<Post>> = HashMap::new();
|
||||
let mut idents: HashMap<PathBuf, Option<String>> = HashMap::new();
|
||||
let mut found: HashMap<(String, String), Label> = HashMap::new();
|
||||
for row in record::rows("answers.jsonl") {
|
||||
let q = question_of(&row);
|
||||
let Some(call) = calls.get(row["call"].as_str().unwrap_or_default()) else { continue };
|
||||
let (Some(ident), false) = (call["ident"].as_str(), q.label_words.is_empty()) else { continue };
|
||||
let Some(dir) = feed_of(call) else { continue };
|
||||
let len = record::ident_len(ident);
|
||||
let same = |f: &PathBuf, idents: &mut HashMap<PathBuf, Option<String>>| {
|
||||
std::fs::metadata(f).is_ok_and(|m| Some(m.len()) == len) && idents.entry(f.clone()).or_insert_with(|| record::ident(f)).as_deref() == Some(ident)
|
||||
};
|
||||
let (from, to) = (call["from"].as_f64().unwrap_or(0.0), call["to"].as_f64().unwrap_or(f64::INFINITY));
|
||||
let words: Vec<String> = q.label_words.iter().map(|w| w.to_lowercase()).collect();
|
||||
for post in feeds.entry(dir.clone()).or_insert_with(|| posts(&dir)).iter().filter(|p| p.files.iter().any(|f| same(f, &mut idents))) {
|
||||
let inside = |t: &Option<f64>| t.is_none_or(|t| t - BEFORE < to && t + AFTER > from);
|
||||
let seen = post.notes.iter().find(|(t, text)| inside(t) && words.iter().any(|w| text.contains(w.as_str())));
|
||||
let l = match (seen, post.done) {
|
||||
(Some((_, text)), _) => label(&q.id, call, true, "note", Some(text.clone())),
|
||||
(None, true) => label(&q.id, call, false, "approval", None),
|
||||
(None, false) => continue,
|
||||
};
|
||||
let key = (l.question.clone(), l.media.clone());
|
||||
if found.get(&key).is_none_or(|was| l.rank() > was.rank()) {
|
||||
found.insert(key, l);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut labels = all();
|
||||
labels.retain(|l| !matches!(l.source.as_str(), "note" | "approval"));
|
||||
let yes = found.values().filter(|l| l.bad).count();
|
||||
let no = found.len() - yes;
|
||||
labels.extend(found.into_values());
|
||||
write(&labels)?;
|
||||
Ok((yes, no))
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use raea_core_ask::{Kind, Question, Reading};
|
||||
use raea_io_clef::{Answered, Call, Fail};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::labels::{self, means_problem};
|
||||
use crate::prepare::Piece;
|
||||
use crate::runner::{self, Entry, Opts};
|
||||
use crate::{calibrate, record};
|
||||
|
||||
/// The labels and calibration files are rewritten whole: one test at a time.
|
||||
static LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn reading(p: f64) -> Reading {
|
||||
Reading { value: p, problem: Some(p), choice: None, says: format!("{p:.2}") }
|
||||
}
|
||||
|
||||
fn question(id: &str, words: &[&str]) -> Question {
|
||||
let mut q = Question::plain(id, &format!("Is there a problem the {id} test names?"));
|
||||
q.label_words = words.iter().map(|w| w.to_string()).collect();
|
||||
q
|
||||
}
|
||||
|
||||
/// A call and its answer kept, as the runner keeps them; the answer's id.
|
||||
fn asked(file: &Path, project: &str, clip: &str, q: &Question, p: f64) -> String {
|
||||
let call = record::call(&file.display().to_string(), Some(project), 0.0, Some(5.0), "a test", &[clip.to_string()], "a test", 0.0, false);
|
||||
record::answer(&call, &file.display().to_string(), q, &reading(p), p >= 0.5)
|
||||
}
|
||||
|
||||
fn write(p: &Path, bytes: &[u8]) {
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, bytes).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_persons_note_on_the_posted_render_labels_it_and_an_approval_labels_it_clean() {
|
||||
crate::tests::setup();
|
||||
let _one = LOCK.lock().unwrap();
|
||||
let proj = std::env::temp_dir().join(format!("raea-ask-notes-{}", std::process::id()));
|
||||
let (a, b, other) = (proj.join("out/a.mp4"), proj.join("out/b.mp4"), proj.join("old/a.mp4"));
|
||||
write(&a, b"render one");
|
||||
write(&b, b"render two");
|
||||
write(&other, b"another render, the same name");
|
||||
let post = |media: &str, status: &str, notes: serde_json::Value| json!({"media": [{"kind": "video", "path": media}], "status": status, "notes": notes});
|
||||
let person = |text: &str, t: Option<f64>| json!({"author": {"kind": "person", "name": "me"}, "text": text, "pin": t.map(|t| json!({"t": t}))});
|
||||
write(&proj.join(".raea/feed/1.json"), post("out/a.mp4", "seen", json!([person("The caption runs OVER HER FACE here", Some(2.0))])).to_string().as_bytes());
|
||||
let agent = json!({"author": {"kind": "agent"}, "text": "over her face"});
|
||||
write(&proj.join(".raea/feed/2.json"), post("out/b.mp4", "done", json!([agent, person("lovely", None)])).to_string().as_bytes());
|
||||
let q = question("notes.face", &["over her face"]);
|
||||
let project = proj.display().to_string();
|
||||
asked(&a, &project, "na.mp4", &q, 0.7);
|
||||
asked(&b, &project, "nb.mp4", &q, 0.2);
|
||||
asked(&other, &project, "nc.mp4", &q, 0.6);
|
||||
assert_eq!(labels::from_feed().unwrap(), (1, 1));
|
||||
let mine: Vec<_> = labels::all().into_iter().filter(|l| l.question == "notes.face").collect();
|
||||
let on = |clip: &str| mine.iter().find(|l| l.media == clip).unwrap_or_else(|| panic!("{clip}: {mine:?}"));
|
||||
assert!(on("na.mp4").bad && on("na.mp4").source == "note" && on("na.mp4").note.as_deref().is_some_and(|n| n.contains("over her face")));
|
||||
assert!(!on("nb.mp4").bad && on("nb.mp4").source == "approval", "an agent's note isn't the person's");
|
||||
assert!(!mine.iter().any(|l| l.media == "nc.mp4"), "another render with the same name isn't the one posted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_verdict_reads_in_the_questions_terms_and_another_eyes_isnt_counted() {
|
||||
crate::tests::setup();
|
||||
let _one = LOCK.lock().unwrap();
|
||||
let mut q = question("verdict.logo", &[]);
|
||||
assert!(means_problem(&q, "Yes").unwrap() && !means_problem(&q, "no").unwrap());
|
||||
q.flags = vec!["no".into()];
|
||||
assert!(means_problem(&q, "no").unwrap(), "a question flagged on no: no is the problem");
|
||||
let mut g = q.clone();
|
||||
g.kind = Kind::Grade;
|
||||
assert!(means_problem(&g, "weak").unwrap() && !means_problem(&g, "acceptable").unwrap());
|
||||
g.kind = Kind::Choose;
|
||||
g.options = vec!["first".into(), "second".into()];
|
||||
g.flags = vec![];
|
||||
assert!(means_problem(&g, "first").is_err(), "a pick has no wrong answer");
|
||||
let file = std::env::temp_dir().join("raea-ask-verdict.mp4");
|
||||
let id = asked(&file, "p", "v1.mp4", &q, 0.3);
|
||||
labels::verdict(&id, "no", Some("agent")).unwrap();
|
||||
let said = labels::verdict(&id, "no", None).unwrap();
|
||||
assert!(said.contains("the problem is there"), "{said}");
|
||||
let all = labels::all();
|
||||
let standing = labels::standing(&all);
|
||||
let l = standing.get(&("verdict.logo".to_string(), "v1.mp4".to_string())).unwrap();
|
||||
assert!(l.bad && l.source == "verdict");
|
||||
assert!(all.iter().any(|l| l.source == "eye:agent" && !l.counted()));
|
||||
}
|
||||
|
||||
/// clef as a fake: yes to anything sent a clip whose bytes start "bad".
|
||||
fn sees_bad(call: &Call) -> Result<Answered, Fail> {
|
||||
let p = if call.media.videos.iter().any(|v| v.starts_with(b"bad")) { 0.9 } else { 0.1 };
|
||||
let answers = call.questions.iter().map(|q| (q.id.clone(), json!({"noul": p}))).collect();
|
||||
Ok(Answered { answers, cost: 0.001, cached: false, route: "a test".into(), pool_left: None })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_from_three_projects_calibrate_a_question_and_new_words_are_measured_on_the_same_clips() {
|
||||
crate::tests::setup();
|
||||
let _one = LOCK.lock().unwrap();
|
||||
let (good, flat) = (question("cal.good", &[]), question("cal.flat", &[]));
|
||||
let file = PathBuf::from("/nowhere/cal.mp4");
|
||||
for i in 0..36 {
|
||||
let bad = i % 2 == 0;
|
||||
let clip = record::keep_media(format!("{}{i}", if bad { "bad" } else { "ok" }).as_bytes(), "mp4");
|
||||
let project = format!("p{}", i % 3);
|
||||
let call = record::call(&file.display().to_string(), Some(&project), 0.0, Some(3.0), "a test", &[clip], "a test", 0.0, false);
|
||||
let (p, word) = if bad { (0.6 + i as f64 / 1000.0, "yes") } else { (0.3 + i as f64 / 1000.0, "no") };
|
||||
for (q, p) in [(&good, p), (&flat, 0.5)] {
|
||||
let id = record::answer(&call, &file.display().to_string(), q, &reading(p), false);
|
||||
labels::verdict(&id, word, None).unwrap();
|
||||
}
|
||||
}
|
||||
let (all, _) = calibrate::calibrate(None).unwrap();
|
||||
let of = |id: &str| all.iter().find(|s| s.id == id).unwrap_or_else(|| panic!("{id}: {all:?}"));
|
||||
let g = of("cal.good");
|
||||
assert_eq!((g.state.as_str(), g.problems, g.clean, g.projects, g.auc), ("calibrated", 18, 18, 3, Some(1.0)), "{g:?}");
|
||||
let f = of("cal.flat");
|
||||
assert_eq!(f.state, "doesn't separate", "{f:?}");
|
||||
assert!(!f.misses.is_empty() && f.auc == Some(0.5));
|
||||
// the person's calibration goes out with the question from now on
|
||||
let piece = Arc::new(Piece { file: file.clone(), ..Default::default() });
|
||||
let (groups, _) = runner::plan(&[Entry { piece, window: None, questions: vec![good.clone()], dropped: vec![], with: vec![] }]);
|
||||
let sent = &groups[0].questions[0];
|
||||
assert!(sent.calibrated() && sent.calibration.as_ref().is_some_and(|c| c.by == "you"), "{sent:?}");
|
||||
// new words for the flat question, asked of its labelled clips
|
||||
let (sum, both) = calibrate::try_words("cal.flat", "Does anything look broken?", &Opts { jobs: 4, dry: false, ask: sees_bad }, &mut |_| {}).unwrap();
|
||||
let (old, new) = both.unwrap();
|
||||
assert_eq!(sum.calls, 36);
|
||||
assert_eq!((old.auc, new.auc, new.problems + new.clean), (Some(0.5), Some(1.0), 36), "{new:?}");
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
//! `raea ask` (docs/ask.feature AK2-AK3): questions about a piece's picture and sound. `prepare` reads what raea knows
|
||||
//! of the piece and keeps the questions that apply; `runner` plans the calls, cuts each clip once and asks in parallel;
|
||||
//! `record` keeps every call and answer; `labels` reads the person's verdicts, notes and approvals into labels, and
|
||||
//! `calibrate` holds each question to them (AK6-AK7); `verbs` is the command. `raea check`, the app's critique and the
|
||||
//! fingerprint's double-check go through the same runner.
|
||||
|
||||
pub mod calibrate;
|
||||
pub mod labels;
|
||||
pub mod prepare;
|
||||
pub mod record;
|
||||
pub mod runner;
|
||||
pub mod verbs;
|
||||
|
||||
pub use verbs::{USAGE, cli};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod labels_tests;
|
||||
@@ -0,0 +1,164 @@
|
||||
//! Ask understands a question before it spends (docs/ask.feature AK2): what the file holds (ffprobe), what the project's
|
||||
//! brief says it's for, whether anyone speaks in it, and from those which questions can be asked, which are swapped for
|
||||
//! their variant (sound for sound-silent) and which are dropped, each with why. The state paragraph tells clef what the
|
||||
//! piece is, as the app's critique writes it. When it isn't known whether anyone speaks, both variants are kept, the
|
||||
//! voice question goes in the same call (runner.rs), free, and the variant that doesn't apply is set aside.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_ask::{Facts, Question, library};
|
||||
use raea_io_clef::media::{self, Probe};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The question asked beside the rest when no one knows yet whether anyone speaks in the piece.
|
||||
pub const VOICE: &str = "voice-heard";
|
||||
|
||||
/// What raea knows of the piece.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Piece {
|
||||
pub file: PathBuf,
|
||||
pub probe: Probe,
|
||||
/// the brief's fields, as `raea spec brief.ts --as brief` reads them ({} without a brief)
|
||||
pub brief: Value,
|
||||
/// the project's folder (the one holding the brief), when there is one
|
||||
pub project: Option<PathBuf>,
|
||||
/// the words heard, when a words file was given
|
||||
pub words: Option<String>,
|
||||
/// someone speaks: from --voice, or from the words file (none heard is no)
|
||||
pub voice: Option<bool>,
|
||||
/// what the caller adds to the state (what raea measured, the platform)
|
||||
pub extra: Option<String>,
|
||||
}
|
||||
|
||||
/// The brief nearest the file: brief.ts in its folder or any folder above it.
|
||||
pub fn brief_near(file: &Path) -> Option<PathBuf> {
|
||||
let abs = dunce::canonicalize(file).ok()?;
|
||||
abs.ancestors().skip(1).map(|d| d.join("brief.ts")).find(|b| b.is_file())
|
||||
}
|
||||
|
||||
/// A brief's fields, through `raea spec FILE --as brief` (this raea), or {} when it can't be read.
|
||||
fn brief_of(path: &Path) -> Value {
|
||||
let Ok(exe) = std::env::current_exe() else { return json!({}) };
|
||||
let Ok(out) = std::process::Command::new(exe).args(["spec"]).arg(path).args(["--as", "brief"]).output() else { return json!({}) };
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
let v: Value = text.find('{').and_then(|i| serde_json::from_str(&text[i..]).ok()).unwrap_or_else(|| json!({}));
|
||||
v.get("brief").cloned().unwrap_or(v)
|
||||
}
|
||||
|
||||
/// The words heard, from a words file (a JSON list of words, each a string or {word} or {text}): their text, and
|
||||
/// whether anyone speaks (an empty list is no one).
|
||||
pub fn words_of(path: &Path) -> Result<(String, bool), String> {
|
||||
let v: Value = serde_json::from_str(&std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let list = v.as_array().or(v["words"].as_array()).ok_or_else(|| format!("{}: a list of words", path.display()))?;
|
||||
let words: Vec<&str> = list.iter().filter_map(|w| w.as_str().or(w["word"].as_str()).or(w["text"].as_str())).collect();
|
||||
Ok((words.join(" "), !words.is_empty()))
|
||||
}
|
||||
|
||||
impl Piece {
|
||||
/// The piece as raea finds it: the file probed, its brief (given or the nearest), its words.
|
||||
pub fn read(file: &Path, brief: Option<&Path>, words: Option<&Path>, voice: Option<bool>, extra: Option<String>) -> Result<Piece, String> {
|
||||
let probe = media::probe(file)?;
|
||||
// "none": no brief, even with one near (a caller that writes the whole state itself, as the app's critique does)
|
||||
let brief_file = match brief {
|
||||
Some(p) if p.as_os_str() == "none" => None,
|
||||
Some(p) => Some(p.to_path_buf()),
|
||||
None => brief_near(file),
|
||||
};
|
||||
let (words, heard) = match words {
|
||||
Some(w) => words_of(w).map(|(t, h)| (Some(t).filter(|t| !t.is_empty()), Some(h)))?,
|
||||
None => (None, None),
|
||||
};
|
||||
Ok(Piece {
|
||||
file: file.to_path_buf(),
|
||||
probe,
|
||||
brief: brief_file.as_deref().map(brief_of).unwrap_or_else(|| json!({})),
|
||||
project: brief_file.and_then(|b| b.parent().map(Path::to_path_buf)),
|
||||
words,
|
||||
voice: voice.or(heard).or((!probe.sound).then_some(false)),
|
||||
extra,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn modes(&self) -> Vec<String> {
|
||||
let m = &self.brief["mode"];
|
||||
let list: Vec<&str> = m.as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_else(|| m.as_str().into_iter().collect());
|
||||
list.iter().flat_map(|s| s.split(',')).map(|s| s.replace("(assumed)", "").trim().to_string()).filter(|s| !s.is_empty()).collect()
|
||||
}
|
||||
|
||||
pub fn facts(&self) -> Facts {
|
||||
let modes = self.modes();
|
||||
Facts { game: modes.iter().any(|m| m == "play"), modes, voice: self.voice, sound: self.probe.sound, video: self.probe.video }
|
||||
}
|
||||
|
||||
/// What clef reads before the media: what the piece is and what's known of it.
|
||||
pub fn state(&self) -> String {
|
||||
let b = &self.brief;
|
||||
let modes = self.modes();
|
||||
let what = if modes.is_empty() { "video".to_string() } else { modes.join(" and ") };
|
||||
// with no brief and the caller's own state, the caller says what the piece is
|
||||
let briefless = b.as_object().is_none_or(|o| o.is_empty());
|
||||
let mut s = match (b["title"].as_str(), briefless && self.extra.is_some()) {
|
||||
(_, true) => vec![],
|
||||
(Some(t), _) => vec![format!("A {what} piece: \"{t}\".")],
|
||||
(None, _) => vec![format!("A {what} piece.")],
|
||||
};
|
||||
for (k, say) in [("audience", "It's for"), ("believe", "It should leave them believing"), ("logline", "Its storyboard"), ("voice", "Its voice")] {
|
||||
if let Some(v) = b[k].as_str().filter(|v| !v.trim().is_empty()) {
|
||||
s.push(format!("{say}: {}.", v.trim().trim_end_matches('.')));
|
||||
}
|
||||
}
|
||||
if self.voice == Some(false) {
|
||||
s.push("No one speaks in it: its sound is the music and the effects, with no voice.".into());
|
||||
}
|
||||
if let Some(w) = &self.words {
|
||||
let cut: String = w.chars().take(1200).collect();
|
||||
s.push(format!("The words heard: \"{cut}{}\"", if cut.len() < w.len() { "..." } else { "" }));
|
||||
}
|
||||
if self.probe.seconds > 0.0 {
|
||||
s.push(format!("It runs {:.0} s.", self.probe.seconds));
|
||||
}
|
||||
if let Some(x) = &self.extra {
|
||||
s.push(x.trim().to_string());
|
||||
}
|
||||
s.join(" ")
|
||||
}
|
||||
}
|
||||
|
||||
/// Is anyone heard speaking: asked beside the questions that depend on it, at no cost (clef costs by media, not by
|
||||
/// questions), when no one knows yet.
|
||||
pub fn voice_question() -> Question {
|
||||
let mut v = Question::plain(VOICE, "Is anyone heard speaking in it (a voice saying words, not singing)?");
|
||||
v.sees = raea_core_ask::Sees::Nothing;
|
||||
v
|
||||
}
|
||||
|
||||
/// The questions kept for this piece, and those dropped with why. A question that doesn't apply is swapped for its
|
||||
/// variant when that one does; not knowing whether anyone speaks, both are kept.
|
||||
pub fn keep(questions: Vec<Question>, f: &Facts, rubric_md: Option<&str>) -> (Vec<Question>, Vec<(String, String)>) {
|
||||
let mut asked: Vec<Question> = Vec::new();
|
||||
let mut dropped = Vec::new();
|
||||
let add = |q: Question, asked: &mut Vec<Question>| {
|
||||
if !asked.iter().any(|a| a.id == q.id) {
|
||||
asked.push(q);
|
||||
}
|
||||
};
|
||||
for q in questions {
|
||||
let Some(why) = q.not_for(f) else {
|
||||
// not knowing whether anyone speaks, its variant goes in too: one call answers either way
|
||||
let twin = (f.voice.is_none() && q.when.voice.is_some()).then(|| q.swap.as_deref().and_then(|s| library::find(s, rubric_md))).flatten();
|
||||
add(q, &mut asked);
|
||||
if let Some(t) = twin {
|
||||
add(t, &mut asked);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
match q.swap.as_deref().and_then(|s| library::find(s, rubric_md)).filter(|s| s.not_for(f).is_none()) {
|
||||
Some(s) => {
|
||||
dropped.push((q.id.clone(), format!("{why}: asked {} instead", s.id)));
|
||||
add(s, &mut asked);
|
||||
}
|
||||
None => dropped.push((q.id.clone(), why)),
|
||||
}
|
||||
}
|
||||
(asked, dropped)
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Every answer kept (docs/ask.feature AK3), so a question can be labelled, calibrated and reworded later (AK6, AK7):
|
||||
//! each call in calls.jsonl (the file, the window, the state, the clips it sent by hash, the route and the cost) and each
|
||||
//! answer in answers.jsonl (the call, the question and its version, the reading). The clips themselves are kept by hash
|
||||
//! in media/, at most 2 GB, the oldest out first, so new words can be asked of the same media. A call keeps what its
|
||||
//! file was (`ident`), so a note on the render's copy in the feed labels it (labels.rs), and an answer keeps its whole
|
||||
//! question, so a verdict reads in its terms and `raea ask try` can reword it.
|
||||
|
||||
use std::io::Write as _;
|
||||
use std::io::{Read as _, Seek as _, SeekFrom};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_ask::{Question, Reading};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
/// How much cut media is kept.
|
||||
pub const MEDIA_CAP: u64 = 2 << 30;
|
||||
|
||||
pub fn dir() -> PathBuf {
|
||||
raea_io_clef::cache::dir()
|
||||
}
|
||||
|
||||
/// A new id: a prefix and twelve hex digits, from the time, the process and a counter.
|
||||
pub fn new_id(prefix: &str) -> String {
|
||||
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let t = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
|
||||
let seed = format!("{t}-{}-{}", std::process::id(), N.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
|
||||
let h = seed.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ b as u64).wrapping_mul(0x0100_0000_01b3));
|
||||
format!("{prefix}-{:012x}", h & 0xffff_ffff_ffff)
|
||||
}
|
||||
|
||||
pub fn now() -> String {
|
||||
let s = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
||||
s.to_string()
|
||||
}
|
||||
|
||||
fn append(file: &str, row: &Value) {
|
||||
let d = dir();
|
||||
if std::fs::create_dir_all(&d).is_err() {
|
||||
return;
|
||||
}
|
||||
// one write a row: several runs (a script's, two at once) append to the same file, and a row written in pieces
|
||||
// could be split by another's
|
||||
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(d.join(file)) {
|
||||
let _ = f.write_all(format!("{row}\n").as_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
fn hex(digest: &[u8]) -> String {
|
||||
digest.iter().take(16).map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// What a file is, cheaply: its size and a hash of its first and last MB. A render is known again by its copy in the
|
||||
/// feed, and a later render to the same path isn't taken for it.
|
||||
pub fn ident(path: &Path) -> Option<String> {
|
||||
const MB: u64 = 1 << 20;
|
||||
let mut f = std::fs::File::open(path).ok()?;
|
||||
let len = f.metadata().ok()?.len();
|
||||
let mut h = Sha256::new();
|
||||
let mut part = vec![0u8; len.min(MB) as usize];
|
||||
f.read_exact(&mut part).ok()?;
|
||||
h.update(&part);
|
||||
if len > 2 * MB {
|
||||
f.seek(SeekFrom::Start(len - MB)).ok()?;
|
||||
f.read_exact(&mut part).ok()?;
|
||||
h.update(&part);
|
||||
}
|
||||
Some(format!("{len}-{}", hex(&h.finalize())))
|
||||
}
|
||||
|
||||
/// The size an ident names, to pass over files that can't be it without reading them.
|
||||
pub fn ident_len(ident: &str) -> Option<u64> {
|
||||
ident.split_once('-')?.0.parse().ok()
|
||||
}
|
||||
|
||||
/// One of the record's files written whole, through a temporary file, so a reader never sees half of it.
|
||||
pub fn write_whole(file: &str, text: &str) -> Result<(), String> {
|
||||
let d = dir();
|
||||
let tmp = d.join(format!("{file}.{}.tmp", std::process::id()));
|
||||
let put = || -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(&d)?;
|
||||
std::fs::write(&tmp, text)?;
|
||||
std::fs::rename(&tmp, d.join(file))
|
||||
};
|
||||
put().map_err(|e| format!("{}: {e}", d.display()))
|
||||
}
|
||||
|
||||
/// A clip kept by its hash, as `HASH.EXT` (already kept is left alone).
|
||||
pub fn keep_media(bytes: &[u8], ext: &str) -> String {
|
||||
let name = format!("{}.{ext}", hex(&Sha256::digest(bytes)));
|
||||
let d = dir().join("media");
|
||||
let p = d.join(&name);
|
||||
if !p.is_file() && std::fs::create_dir_all(&d).is_ok() {
|
||||
let _ = std::fs::write(&p, bytes);
|
||||
prune(MEDIA_CAP);
|
||||
}
|
||||
name
|
||||
}
|
||||
|
||||
/// A kept clip's bytes, by its name.
|
||||
pub fn media(name: &str) -> Option<Vec<u8>> {
|
||||
std::fs::read(dir().join("media").join(name)).ok()
|
||||
}
|
||||
|
||||
/// The kept media held to `cap` bytes, the least recently written going first.
|
||||
pub fn prune(cap: u64) {
|
||||
let Ok(rd) = std::fs::read_dir(dir().join("media")) else { return };
|
||||
let mut files: Vec<(std::time::SystemTime, u64, PathBuf)> = rd
|
||||
.flatten()
|
||||
.filter_map(|e| e.metadata().ok().and_then(|m| Some((m.modified().ok()?, m.len(), e.path()))))
|
||||
.collect();
|
||||
let mut total: u64 = files.iter().map(|f| f.1).sum();
|
||||
files.sort();
|
||||
for (_, len, p) in files {
|
||||
if total <= cap {
|
||||
break;
|
||||
}
|
||||
if std::fs::remove_file(&p).is_ok() {
|
||||
total -= len;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One call kept; its id.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn call(file: &str, project: Option<&str>, from: f64, to: Option<f64>, state: &str, media: &[String], route: &str, cost: f64, cached: bool) -> String {
|
||||
let id = new_id("c");
|
||||
let row = json!({
|
||||
"id": id, "at": now(), "file": file, "ident": ident(Path::new(file)), "project": project, "from": from, "to": to, "state": state,
|
||||
"media": media, "route": route, "cost": cost, "cached": cached,
|
||||
});
|
||||
append("calls.jsonl", &row);
|
||||
id
|
||||
}
|
||||
|
||||
/// One answer kept; its id.
|
||||
pub fn answer(call: &str, file: &str, q: &Question, r: &Reading, flagged: bool) -> String {
|
||||
let id = new_id("a");
|
||||
let whole = serde_json::to_value(Question { calibration: None, ..q.clone() }).unwrap_or_default();
|
||||
let row = json!({
|
||||
"id": id, "at": now(), "call": call, "file": file, "question": q.id, "version": q.version(), "ask": q.ask,
|
||||
"value": r.value, "problem": r.problem, "choice": r.choice, "says": r.says, "flagged": flagged, "calibrated": q.calibrated(),
|
||||
"q": whole,
|
||||
});
|
||||
append("answers.jsonl", &row);
|
||||
id
|
||||
}
|
||||
|
||||
/// Every row of one of the record's files.
|
||||
pub fn rows(file: &str) -> Vec<Value> {
|
||||
std::fs::read_to_string(dir().join(file)).unwrap_or_default().lines().filter_map(|l| serde_json::from_str(l).ok()).collect()
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
//! One runner for every caller (docs/ask.feature AK3): a batch planned into calls (grouped by file, window, the files
|
||||
//! beside it and what of the picture its questions look at, at most 64 questions a call, the voice question added to a
|
||||
//! call whose questions depend on whether anyone speaks when that isn't known), each clip cut once, the calls
|
||||
//! made in parallel, the answers streamed back as they come and kept. A pool that's spent partway keeps what came and
|
||||
//! reports the rest as waiting for it. `dry` cuts the media and says what would be sent, and spends nothing. A group can
|
||||
//! carry clips kept from an earlier call instead of a file to cut (`raea ask try`), and every question goes out with the
|
||||
//! person's own calibration when it has earned one (calibrate.rs).
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex, mpsc};
|
||||
|
||||
use raea_core_ask::{Kind, Picks, Question, Sees, Window, limits};
|
||||
use raea_io_clef::{Answered, Call, Fail, Media, media};
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::prepare::{self, Piece, VOICE};
|
||||
use crate::{calibrate, record};
|
||||
|
||||
/// What to ask of one file: its questions (prepared), those dropped with why, a window over all of them (else each
|
||||
/// question's own), and files set beside it (to pick between, or before and after).
|
||||
pub struct Entry {
|
||||
pub piece: Arc<Piece>,
|
||||
pub window: Option<Window>,
|
||||
pub questions: Vec<Question>,
|
||||
pub dropped: Vec<(String, String)>,
|
||||
pub with: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
/// One call's worth.
|
||||
pub struct Group {
|
||||
pub piece: Arc<Piece>,
|
||||
pub from: f64,
|
||||
pub to: Option<f64>,
|
||||
pub sees: Sees,
|
||||
pub hears: bool,
|
||||
pub with: Vec<PathBuf>,
|
||||
pub questions: Vec<Question>,
|
||||
/// clips kept from an earlier call, sent again in place of cutting the file
|
||||
pub kept: Option<Arc<Kept>>,
|
||||
}
|
||||
|
||||
/// An earlier call's clips and state, and their seconds of video and sound (for the estimate).
|
||||
pub struct Kept {
|
||||
pub media: Media,
|
||||
pub state: String,
|
||||
pub video_seconds: f64,
|
||||
pub sound_seconds: f64,
|
||||
}
|
||||
|
||||
/// One answer, or why a question wasn't asked or still waits: the line `raea ask --json` prints for each.
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct Answer {
|
||||
/// its id in the record (`raea ask verdict` takes it)
|
||||
pub answer: Option<String>,
|
||||
pub file: String,
|
||||
pub id: String,
|
||||
pub version: String,
|
||||
pub from: f64,
|
||||
pub to: Option<f64>,
|
||||
pub says: Option<String>,
|
||||
pub value: Option<f64>,
|
||||
pub problem: Option<f64>,
|
||||
pub choice: Option<String>,
|
||||
pub flagged: bool,
|
||||
pub calibrated: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub not_asked: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub waits: Option<String>,
|
||||
pub route: Option<String>,
|
||||
pub cached: bool,
|
||||
}
|
||||
|
||||
/// What the run came to.
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct Summary {
|
||||
pub asked: usize,
|
||||
pub answered: usize,
|
||||
pub calls: usize,
|
||||
pub cost: f64,
|
||||
pub estimate: f64,
|
||||
pub pool_left: Option<f64>,
|
||||
pub waiting: usize,
|
||||
pub flagged: usize,
|
||||
pub flagged_calibrated: usize,
|
||||
pub routes: BTreeSet<String>,
|
||||
/// the clips cut (each once, however many calls used it)
|
||||
pub clips: usize,
|
||||
}
|
||||
|
||||
/// What the runner tells its caller as it goes: an answer, or (dry) a call it would make.
|
||||
pub enum Event<'a> {
|
||||
Answer(&'a Answer),
|
||||
Would(&'a Value),
|
||||
}
|
||||
|
||||
pub struct Opts {
|
||||
pub jobs: usize,
|
||||
pub dry: bool,
|
||||
/// how a call is made: `raea_io_clef::ask` (a test gives its own)
|
||||
pub ask: fn(&Call) -> Result<Answered, Fail>,
|
||||
}
|
||||
|
||||
impl Opts {
|
||||
pub fn new(jobs: usize, dry: bool) -> Opts {
|
||||
Opts { jobs, dry, ask: raea_io_clef::ask }
|
||||
}
|
||||
}
|
||||
|
||||
const NAMES: [&str; 4] = ["first", "second", "third", "fourth"];
|
||||
|
||||
/// A pick's options: the files given, in order (all, or all but the first, the reference).
|
||||
fn picks(p: Picks, files: usize) -> Vec<String> {
|
||||
let n = files.min(NAMES.len());
|
||||
let skip = usize::from(p == Picks::AfterFirst);
|
||||
NAMES[skip.min(n)..n].iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
/// The batch as calls.
|
||||
pub fn plan(entries: &[Entry]) -> (Vec<Group>, Vec<Answer>) {
|
||||
let mut groups: Vec<Group> = Vec::new();
|
||||
let mut unasked = Vec::new();
|
||||
let mine = calibrate::local();
|
||||
for e in entries {
|
||||
let file = e.piece.file.display().to_string();
|
||||
for (id, why) in &e.dropped {
|
||||
unasked.push(Answer { file: file.clone(), id: id.clone(), not_asked: Some(why.clone()), ..Default::default() });
|
||||
}
|
||||
for q in &e.questions {
|
||||
let w = e.window.or(q.window).unwrap_or_default();
|
||||
let (from, to) = (w.from.unwrap_or(0.0).max(0.0), w.to);
|
||||
let mut q = q.clone();
|
||||
calibrate::apply(&mut q, &mine);
|
||||
if let Some(p) = q.picks {
|
||||
q.kind = Kind::Choose;
|
||||
q.options = picks(p, 1 + e.with.len());
|
||||
}
|
||||
let compares = q.picks.is_some_and(|_| q.options.len() < 2) || (q.uses.iter().any(|u| u == "with") && e.with.is_empty());
|
||||
if compares {
|
||||
unasked.push(Answer { file: file.clone(), version: q.version(), not_asked: Some("it compares files: set one or more beside it (--with)".into()), id: q.id, ..Default::default() });
|
||||
continue;
|
||||
}
|
||||
// one place in each call is kept for the voice question
|
||||
let same = |g: &&mut Group| Arc::ptr_eq(&g.piece, &e.piece) && g.from == from && g.to == to && g.sees == q.sees && g.with == e.with && g.questions.len() < limits::QUESTIONS - 1;
|
||||
match groups.iter_mut().find(same) {
|
||||
Some(g) => {
|
||||
g.hears |= q.hears;
|
||||
g.questions.push(q);
|
||||
}
|
||||
None => groups.push(Group { piece: e.piece.clone(), from, to, sees: q.sees, hears: q.hears, with: e.with.clone(), questions: vec![q], kept: None }),
|
||||
}
|
||||
}
|
||||
}
|
||||
for g in &mut groups {
|
||||
g.hears &= g.piece.probe.sound || g.with.iter().any(|f| media::probe(f).is_ok_and(|p| p.sound));
|
||||
if g.hears && g.piece.voice.is_none() && g.questions.iter().any(|q| q.when.voice.is_some()) {
|
||||
g.questions.push(prepare::voice_question());
|
||||
}
|
||||
}
|
||||
(groups, unasked)
|
||||
}
|
||||
|
||||
/// Clips cut once a run, by what they are.
|
||||
type Cuts = Mutex<HashMap<String, Result<Arc<Vec<u8>>, String>>>;
|
||||
|
||||
fn cut(cuts: &Cuts, key: String, make: impl FnOnce() -> Result<Vec<u8>, String>) -> Result<Arc<Vec<u8>>, String> {
|
||||
if let Some(r) = cuts.lock().unwrap().get(&key) {
|
||||
return r.clone();
|
||||
}
|
||||
let r = make().map(Arc::new);
|
||||
cuts.lock().unwrap().insert(key, r.clone());
|
||||
r
|
||||
}
|
||||
|
||||
/// A group's media, and its seconds of video and of sound (for the estimate).
|
||||
fn media_of(g: &Group, cuts: &Cuts) -> Result<(Media, f64, f64), String> {
|
||||
if let Some(k) = &g.kept {
|
||||
return Ok((k.media.clone(), k.video_seconds, k.sound_seconds));
|
||||
}
|
||||
let files: Vec<&Path> = std::iter::once(g.piece.file.as_path()).chain(g.with.iter().map(PathBuf::as_path)).collect();
|
||||
let (from, to) = (g.from, g.to);
|
||||
let span = |p: &media::Probe| (to.unwrap_or(p.seconds) - from).clamp(0.0, p.seconds.max(0.1));
|
||||
let mut m = Media::default();
|
||||
let (mut vs, mut ss) = (0.0, 0.0);
|
||||
for f in &files {
|
||||
let p = if *f == g.piece.file.as_path() { g.piece.probe } else { media::probe(f)? };
|
||||
let k = |what: &str| format!("{what}:{}:{from}:{to:?}", f.display());
|
||||
match g.sees {
|
||||
Sees::Video if p.video => {
|
||||
m.videos.push(cut(cuts, k("video"), || media::video(f, from, to))?.to_vec());
|
||||
vs += span(&p).min(limits::VIDEO_SECONDS);
|
||||
}
|
||||
Sees::Video | Sees::Stills if !p.video => m.stills.push(cut(cuts, k("still"), || media::still(f, None))?.to_vec()),
|
||||
Sees::Stills if files.len() == 1 => {
|
||||
let len = span(&p);
|
||||
for i in 0..limits::STILLS {
|
||||
let at = from + len * (i as f64 + 0.5) / limits::STILLS as f64;
|
||||
m.stills.push(cut(cuts, k(&format!("frame{i}")), || media::still(f, Some(at)))?.to_vec());
|
||||
}
|
||||
}
|
||||
Sees::Stills => m.stills.push(cut(cuts, k("frame"), || media::still(f, Some(from + span(&p) / 2.0)))?.to_vec()),
|
||||
_ => {}
|
||||
}
|
||||
if g.hears && p.sound {
|
||||
m.sounds.push(cut(cuts, k("sound"), || media::sound(f, from, to))?.to_vec());
|
||||
ss += span(&p).min(limits::SOUND_SECONDS);
|
||||
}
|
||||
}
|
||||
if m.videos.len() > limits::VIDEOS || m.stills.len() > limits::STILLS || m.sounds.len() > limits::SOUNDS {
|
||||
return Err(format!("too many files for one call: at most {} videos, {} stills and {} sounds", limits::VIDEOS, limits::STILLS, limits::SOUNDS));
|
||||
}
|
||||
Ok((m, vs, ss))
|
||||
}
|
||||
|
||||
enum Done {
|
||||
Asked(Answered, Vec<String>, String),
|
||||
Would(Value),
|
||||
Failed(String),
|
||||
Waits(String),
|
||||
}
|
||||
|
||||
/// Every entry asked, at most `jobs` calls at once, each event told to `out` as it comes (in the caller's thread).
|
||||
pub fn run(entries: Vec<Entry>, o: &Opts, out: &mut dyn FnMut(Event)) -> Summary {
|
||||
let (groups, unasked) = plan(&entries);
|
||||
run_groups(groups, unasked, o, out)
|
||||
}
|
||||
|
||||
/// Planned groups asked, the questions not asked told first.
|
||||
pub fn run_groups(groups: Vec<Group>, unasked: Vec<Answer>, o: &Opts, out: &mut dyn FnMut(Event)) -> Summary {
|
||||
let mut sum = Summary::default();
|
||||
for a in &unasked {
|
||||
out(Event::Answer(a));
|
||||
}
|
||||
let cuts: Cuts = Mutex::default();
|
||||
let (next, spent) = (AtomicUsize::new(0), AtomicBool::new(false));
|
||||
let spent_why = Mutex::new(String::new());
|
||||
let (tx, rx) = mpsc::channel::<(usize, Done)>();
|
||||
std::thread::scope(|s| {
|
||||
for _ in 0..o.jobs.clamp(1, 16).min(groups.len().max(1)) {
|
||||
let (tx, groups, cuts, next, spent, spent_why) = (tx.clone(), &groups, &cuts, &next, &spent, &spent_why);
|
||||
s.spawn(move || {
|
||||
loop {
|
||||
let i = next.fetch_add(1, Ordering::Relaxed);
|
||||
let Some(g) = groups.get(i) else { break };
|
||||
let done = if spent.load(Ordering::Relaxed) {
|
||||
Done::Waits(spent_why.lock().unwrap().clone())
|
||||
} else {
|
||||
match media_of(g, cuts) {
|
||||
Err(e) => Done::Failed(e),
|
||||
Ok((m, vs, ss)) => {
|
||||
let state = g.kept.as_ref().map_or_else(|| g.piece.state(), |k| k.state.clone());
|
||||
let call = Call { state, questions: g.questions.clone(), media: m };
|
||||
let estimate = limits::estimate(vs, ss, call.media.stills.len(), call.state.len(), call.questions.len());
|
||||
if o.dry {
|
||||
Done::Would(would(g, &call, estimate))
|
||||
} else {
|
||||
match (o.ask)(&call) {
|
||||
Ok(a) => Done::Asked(a, kept(&call.media), call.state),
|
||||
Err(Fail::Spent(why)) => {
|
||||
spent.store(true, Ordering::Relaxed);
|
||||
*spent_why.lock().unwrap() = why.clone();
|
||||
Done::Waits(why)
|
||||
}
|
||||
Err(f) => Done::Failed(f.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if tx.send((i, done)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
drop(tx);
|
||||
for (i, done) in rx {
|
||||
told(&groups[i], done, &mut sum, out);
|
||||
}
|
||||
});
|
||||
sum.clips = cuts.lock().unwrap().values().filter(|c| c.is_ok()).count();
|
||||
sum
|
||||
}
|
||||
|
||||
/// The clips a call sent, kept by hash for `raea ask try`.
|
||||
fn kept(m: &Media) -> Vec<String> {
|
||||
let each = |v: &[Vec<u8>], ext: &str| v.iter().map(|b| record::keep_media(b, ext)).collect::<Vec<_>>();
|
||||
[each(&m.videos, "mp4"), each(&m.stills, "jpg"), each(&m.sounds, "mp3")].concat()
|
||||
}
|
||||
|
||||
fn would(g: &Group, call: &Call, estimate: f64) -> Value {
|
||||
let sizes = |v: &[Vec<u8>]| v.iter().map(Vec::len).collect::<Vec<_>>();
|
||||
json!({
|
||||
"file": g.piece.file.display().to_string(), "from": g.from, "to": g.to,
|
||||
"questions": call.questions.iter().map(|q| json!({"id": q.id, "ask": q.ask, "type": q.kind})).collect::<Vec<_>>(),
|
||||
"state": call.state,
|
||||
"media": {"videos": sizes(&call.media.videos), "stills": sizes(&call.media.stills), "sounds": sizes(&call.media.sounds)},
|
||||
"estimate_usd": estimate,
|
||||
})
|
||||
}
|
||||
|
||||
/// A finished call's answers told, kept and counted. When the voice question went along, the variant that doesn't
|
||||
/// apply (sound where no one speaks, sound-silent where someone does) is set aside.
|
||||
fn told(g: &Group, done: Done, sum: &mut Summary, out: &mut dyn FnMut(Event)) {
|
||||
let file = g.piece.file.display().to_string();
|
||||
// the voice question only decides between variants: it isn't told
|
||||
let asked: Vec<&Question> = g.questions.iter().filter(|q| q.id != VOICE).collect();
|
||||
let base = |q: &Question| Answer { file: file.clone(), id: q.id.clone(), version: q.version(), from: g.from, to: g.to, calibrated: q.calibrated(), ..Default::default() };
|
||||
match done {
|
||||
Done::Would(v) => {
|
||||
sum.calls += 1;
|
||||
sum.estimate += v["estimate_usd"].as_f64().unwrap_or(0.0);
|
||||
out(Event::Would(&v));
|
||||
}
|
||||
Done::Failed(why) | Done::Waits(why) if g.questions.is_empty() => drop(why),
|
||||
Done::Failed(why) => asked.iter().for_each(|q| out(Event::Answer(&Answer { not_asked: Some(why.clone()), ..base(q) }))),
|
||||
Done::Waits(why) => {
|
||||
sum.waiting += asked.len();
|
||||
asked.iter().for_each(|q| out(Event::Answer(&Answer { waits: Some(format!("waits for the pool: {why}")), ..base(q) })));
|
||||
}
|
||||
Done::Asked(a, clips, state) => {
|
||||
sum.calls += 1;
|
||||
sum.asked += asked.len();
|
||||
sum.cost += a.cost;
|
||||
sum.pool_left = a.pool_left.or(sum.pool_left);
|
||||
sum.routes.insert(a.route.clone());
|
||||
let project = g.piece.project.as_ref().map(|p| p.display().to_string());
|
||||
let call = record::call(&file, project.as_deref(), g.from, g.to, &state, &clips, &a.route, a.cost, a.cached);
|
||||
let heard = a.answers.get(VOICE).and_then(|v| v["noul"].as_f64());
|
||||
for q in g.questions.iter().filter(|q| q.id != VOICE) {
|
||||
let Some(ans) = a.answers.get(&q.id) else {
|
||||
out(Event::Answer(&Answer { not_asked: Some("no answer came back for it".into()), ..base(q) }));
|
||||
continue;
|
||||
};
|
||||
if let (Some(p), Some(v)) = (heard, q.when.voice) {
|
||||
if v != (p >= 0.5) {
|
||||
let who = if p >= 0.5 { "someone speaks" } else { "no one speaks" };
|
||||
out(Event::Answer(&Answer { not_asked: Some(format!("set aside: {who} ({p:.2})")), ..base(q) }));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let r = q.read(ans);
|
||||
let flagged = q.flagged(&r);
|
||||
sum.answered += 1;
|
||||
sum.flagged += usize::from(flagged);
|
||||
sum.flagged_calibrated += usize::from(flagged && q.calibrated());
|
||||
let id = record::answer(&call, &file, q, &r, flagged);
|
||||
out(Event::Answer(&Answer {
|
||||
answer: Some(id),
|
||||
says: Some(r.says),
|
||||
value: Some(r.value),
|
||||
problem: r.problem,
|
||||
choice: r.choice,
|
||||
flagged,
|
||||
route: Some(a.route.clone()),
|
||||
cached: a.cached,
|
||||
..base(q)
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use raea_core_ask::{Facts, Kind, Picks, Question, Sees, Window, library};
|
||||
use raea_io_clef::media::Probe;
|
||||
use raea_io_clef::{Answered, Call, Fail};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::prepare::{self, Piece, VOICE};
|
||||
use crate::runner::{self, Answer, Entry, Event, Opts};
|
||||
|
||||
fn rubric() -> String {
|
||||
std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../sdk/guides/craft/rubric.md")).expect("the craft rubric")
|
||||
}
|
||||
|
||||
pub(crate) fn setup() {
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
// SAFETY: set once, before any test reads it, to the same value for every test
|
||||
ONCE.call_once(|| unsafe { std::env::set_var("RAEA_ASK_DIR", std::env::temp_dir().join(format!("raea-ask-test-{}", std::process::id()))) });
|
||||
}
|
||||
|
||||
fn ids(qs: &[Question]) -> Vec<&str> {
|
||||
qs.iter().map(|q| q.id.as_str()).collect()
|
||||
}
|
||||
|
||||
fn piece(file: &str, voice: Option<bool>) -> Arc<Piece> {
|
||||
let probe = Probe { seconds: 10.0, video: true, still: false, sound: true };
|
||||
Arc::new(Piece { file: PathBuf::from(file), probe, voice, ..Default::default() })
|
||||
}
|
||||
|
||||
fn entry(p: &Arc<Piece>, window: Option<Window>, questions: Vec<Question>) -> Entry {
|
||||
Entry { piece: p.clone(), window, questions, dropped: vec![], with: vec![] }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_one_speaking_asks_sound_silent_and_a_file_without_sound_isnt_listened_to() {
|
||||
let r = rubric();
|
||||
let sound = library::find("sound", Some(&r)).unwrap();
|
||||
let silent = Facts { voice: Some(false), sound: true, video: true, ..Default::default() };
|
||||
let (asked, dropped) = prepare::keep(vec![sound.clone()], &silent, Some(&r));
|
||||
assert_eq!(ids(&asked), ["sound-silent"]);
|
||||
assert!(dropped[0].1.contains("no one speaks") && dropped[0].1.contains("sound-silent instead"), "{dropped:?}");
|
||||
let mut listen = Question::plain("loud", "Is it loud?");
|
||||
listen.sees = Sees::Nothing;
|
||||
let (asked, dropped) = prepare::keep(vec![listen], &Facts { video: true, ..Default::default() }, None);
|
||||
assert!(asked.is_empty() && dropped[0].1.contains("no sound"), "{dropped:?}");
|
||||
// not knowing whether anyone speaks, both are kept, and the plan adds the voice question to their call
|
||||
let unknown = Facts { sound: true, video: true, ..Default::default() };
|
||||
let (asked, _) = prepare::keep(vec![sound], &unknown, Some(&r));
|
||||
assert_eq!(ids(&asked), ["sound", "sound-silent"]);
|
||||
let (groups, _) = runner::plan(&[entry(&piece("a.mp4", None), None, asked)]);
|
||||
assert_eq!(groups.len(), 1);
|
||||
assert_eq!(ids(&groups[0].questions), ["sound", "sound-silent", VOICE]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_state_says_what_the_piece_is() {
|
||||
let mut p = (*piece("a.mp4", Some(false))).clone();
|
||||
p.brief = json!({"title": "Spring launch", "mode": ["pitch"], "audience": "busy founders", "believe": "it saves them an hour."});
|
||||
p.extra = Some("raea measured -14 LUFS.".into());
|
||||
let s = p.state();
|
||||
for want in ["A pitch piece: \"Spring launch\".", "It's for: busy founders.", "believing: it saves them an hour.", "No one speaks", "runs 10 s", "-14 LUFS"] {
|
||||
assert!(s.contains(want), "{want}: {s}");
|
||||
}
|
||||
assert_eq!(p.facts().modes, ["pitch"]);
|
||||
// no brief and the caller's own state: the caller says what the piece is
|
||||
let own = Piece { extra: Some("A game: \"Rover\".".into()), ..(*piece("a.mp4", None)).clone() };
|
||||
assert_eq!(own.state(), "It runs 10 s. A game: \"Rover\".");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calls_hold_64_questions_and_split_by_window_and_what_they_look_at() {
|
||||
let p = piece("a.mp4", Some(true));
|
||||
let many: Vec<Question> = (0..65).map(|i| Question::plain(&format!("q{i}"), "Is it loud?")).collect();
|
||||
let (groups, _) = runner::plan(&[entry(&p, None, many)]);
|
||||
assert_eq!(groups.iter().map(|g| g.questions.len()).collect::<Vec<_>>(), [63, 2], "one place a call is kept for the voice question");
|
||||
let hook = Window { from: Some(0.0), to: Some(3.0) };
|
||||
let mut still = Question::plain("s", "Is the text readable?");
|
||||
still.sees = Sees::Stills;
|
||||
let (groups, _) = runner::plan(&[entry(&p, None, vec![Question::plain("a", "Is it loud?"), still]), entry(&p, Some(hook), vec![Question::plain("b", "Is it loud?")])]);
|
||||
assert_eq!(groups.len(), 3);
|
||||
let mut pick = Question::plain("best", "Which suits the brief best?");
|
||||
pick.picks = Some(Picks::All);
|
||||
let (groups, unasked) = runner::plan(&[entry(&p, None, vec![pick])]);
|
||||
assert!(groups.is_empty() && unasked[0].not_asked.as_deref().is_some_and(|n| n.contains("--with")), "{unasked:?}");
|
||||
let (groups, unasked) = runner::plan(&[entry(&p, None, vec![library::find("decide.changed", None).unwrap()])]);
|
||||
assert!(groups.is_empty() && !unasked[0].version.is_empty(), "{unasked:?}");
|
||||
}
|
||||
|
||||
/// clef's answers as a fake gives them: yes 0.8 to every yes question (0.9 to the voice question), the lowest level of
|
||||
/// a grade.
|
||||
fn answers(call: &Call) -> Map<String, Value> {
|
||||
call.questions
|
||||
.iter()
|
||||
.map(|q| {
|
||||
let a = match q.kind {
|
||||
Kind::Yes => json!({"noul": if q.id == VOICE { 0.9 } else { 0.8 }}),
|
||||
_ => json!({"choice": q.levels()[0], "probabilities": {q.levels()[0].clone(): 1.0}}),
|
||||
};
|
||||
(q.id.clone(), a)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn answered(call: &Call) -> Answered {
|
||||
Answered { answers: answers(call), cost: 0.001, cached: false, route: "a test".into(), pool_left: Some(1.5) }
|
||||
}
|
||||
|
||||
/// A 2 s clip with a picture and a tone, made with FFmpeg.
|
||||
fn clip(name: &str) -> PathBuf {
|
||||
let out = std::env::temp_dir().join(format!("raea-ask-{}-{name}.mp4", std::process::id()));
|
||||
let ff = raea_io_assets::ffmpeg_tool("ffmpeg", false).expect("FFmpeg");
|
||||
let ok = std::process::Command::new(ff)
|
||||
.args(["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc=size=320x240:rate=10:duration=2", "-f", "lavfi", "-i", "sine=frequency=440:duration=2"])
|
||||
.args(["-c:v", "mpeg4", "-c:a", "aac", "-shortest"])
|
||||
.arg(&out)
|
||||
.status()
|
||||
.expect("FFmpeg ran");
|
||||
assert!(ok.success());
|
||||
out
|
||||
}
|
||||
|
||||
fn run(entries: Vec<Entry>, jobs: usize, ask: fn(&Call) -> Result<Answered, Fail>) -> (runner::Summary, Vec<Answer>) {
|
||||
setup();
|
||||
let mut got = Vec::new();
|
||||
let sum = runner::run(entries, &Opts { jobs, dry: false, ask }, &mut |e| {
|
||||
if let Event::Answer(a) = e {
|
||||
got.push(a.clone());
|
||||
}
|
||||
});
|
||||
(sum, got)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_clip_is_cut_once_and_the_voice_answer_sets_a_variant_aside() {
|
||||
let file = clip("once");
|
||||
let p = Arc::new(Piece::read(&file, None, None, None, None).unwrap());
|
||||
assert!(p.probe.video && p.probe.sound && p.voice.is_none());
|
||||
let r = rubric();
|
||||
let (asked, _) = prepare::keep(vec![library::find("sound", Some(&r)).unwrap()], &p.facts(), Some(&r));
|
||||
let mut listen = Question::plain("loud", "Is it too loud?");
|
||||
listen.sees = Sees::Nothing;
|
||||
let (sum, got) = run(vec![entry(&p, None, [asked, vec![listen]].concat())], 4, |c| Ok(answered(c)));
|
||||
assert_eq!((sum.calls, sum.clips), (2, 2), "the picture's call and the sound's call share one cut of the sound");
|
||||
let by = |id: &str| got.iter().find(|a| a.id == id).unwrap_or_else(|| panic!("{id}: {got:?}"));
|
||||
assert!(by("sound").says.is_some() && by("loud").flagged);
|
||||
assert!(by("sound-silent").not_asked.as_deref().is_some_and(|n| n.contains("someone speaks (0.90)")), "{:?}", by("sound-silent"));
|
||||
assert!(!got.iter().any(|a| a.id == VOICE), "the voice question isn't told");
|
||||
assert_eq!((sum.answered, sum.cost, sum.pool_left), (2, 0.002, Some(1.5)));
|
||||
}
|
||||
|
||||
static CALLS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
#[test]
|
||||
fn a_pool_spent_partway_keeps_what_came_and_the_rest_waits() {
|
||||
let file = clip("spent");
|
||||
let p = Arc::new(Piece::read(&file, None, None, Some(true), None).unwrap());
|
||||
let at = |s: f64| Some(Window { from: Some(s), to: Some(s + 0.5) });
|
||||
let entries = (0..4).map(|i| entry(&p, at(i as f64 * 0.4), vec![Question::plain(&format!("w{i}"), "Is it loud?")])).collect();
|
||||
let (sum, got) = run(entries, 1, |c| match CALLS.fetch_add(1, Ordering::SeqCst) {
|
||||
2 => Err(Fail::Spent("this month's pool is used up".into())),
|
||||
_ => Ok(answered(c)),
|
||||
});
|
||||
assert_eq!((sum.calls, sum.answered, sum.waiting), (2, 2, 2));
|
||||
assert_eq!(got.iter().filter(|a| a.waits.as_deref().is_some_and(|w| w.contains("used up"))).count(), 2);
|
||||
assert_eq!(CALLS.load(Ordering::SeqCst), 3, "nothing is sent after the pool is spent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_words_keep_their_id() {
|
||||
assert_eq!(crate::verbs::own_id("Does the music fight the voice?"), "own-does-the-music-fight-the-voice");
|
||||
assert_eq!(crate::verbs::own_id("Does the music fight the voice?"), crate::verbs::own_id("does the MUSIC fight the voice"));
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
//! `raea ask` (docs/ask.feature AK3): questions about a piece's picture and sound, from the command line or a batch,
|
||||
//! prepared (prepare.rs), asked in parallel (runner.rs) and kept (record.rs). It prints as answers come: words and a
|
||||
//! probability a line, or with `--json` one JSON object a line (an answer, a call `--dry` would make, then the summary).
|
||||
//! `--gate` exits 1 when a calibrated question flags (`--gate any`: when any does), for a pipeline. `verdict`,
|
||||
//! `calibrate` and `try` label the answers, calibrate the questions on them and measure new words (labels.rs,
|
||||
//! calibrate.rs; AK6-AK7).
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::io::Read as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use raea_core_ask::{Kind, Question, Window, library};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::labels::{self, span};
|
||||
use crate::prepare::{self, Piece};
|
||||
use crate::runner::{self, Entry, Event, Opts};
|
||||
use crate::{calibrate, record};
|
||||
|
||||
pub const USAGE: &str = "raea ask FILE [QUESTION...] [--choose A,B,C] [--grade] [--rate N] [--flag ANSWERS] [--set NAME] [--std ID] [--from S] [--to S] [--at S] [--with FILE2] [--brief brief.ts|none] [--words words.json] [--voice yes|no] [--state TEXT] [--dry] [--json] [--gate [any]] [--jobs N] | ask --batch FILE [--dry] [--json] [--gate [any]] [--jobs N] | ask list [SET] [--json] | ask verdict ANSWER WORD [--eye NAME] | ask calibrate [ID] [--json] | ask try WORDS --like ID [--dry] [--json] [--jobs N] (questions about a piece's picture and sound, answered by clef-omni and paid from your raea plan's pool when the app is signed in, else RAEA_AGENT_KEY's, else your own Cloudflare keys: your own words, or the standard sets (rubric, av, defects, platform, decide); every question about one clip goes in one call, --batch (a JSON list or JSON lines, - for stdin) asks many clips in parallel; --dry says what would be sent and spends nothing; answers are advice until a question is calibrated: verdict labels an answer, calibrate holds each question to your verdicts, notes and approvals, try asks new words of its labelled clips)";
|
||||
|
||||
const VALUED: [&str; 17] = ["--choose", "--rate", "--flag", "--set", "--std", "--from", "--to", "--at", "--with", "--brief", "--words", "--voice", "--state", "--jobs", "--batch", "--eye", "--like"];
|
||||
const BARE: [&str; 4] = ["--grade", "--dry", "--json", "--gate"];
|
||||
|
||||
/// The arguments: the words that aren't flags, each flag's values, and whether `--gate` is `--gate any`.
|
||||
#[derive(Default)]
|
||||
struct Args {
|
||||
words: Vec<String>,
|
||||
flags: BTreeMap<String, Vec<String>>,
|
||||
gate_any: bool,
|
||||
}
|
||||
|
||||
impl Args {
|
||||
fn parse(args: &[String]) -> Result<Args, String> {
|
||||
let mut a = Args::default();
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
let s = args[i].as_str();
|
||||
if VALUED.contains(&s) {
|
||||
let v = args.get(i + 1).ok_or_else(|| format!("ask: {s} takes a value\nusage: {USAGE}"))?;
|
||||
a.flags.entry(s.into()).or_default().push(v.clone());
|
||||
i += 1;
|
||||
} else if BARE.contains(&s) {
|
||||
a.flags.entry(s.into()).or_default();
|
||||
if s == "--gate" && args.get(i + 1).is_some_and(|v| v == "any") {
|
||||
a.gate_any = true;
|
||||
i += 1;
|
||||
}
|
||||
} else if s.starts_with("--") {
|
||||
return Err(format!("ask doesn't take {s}\nusage: {USAGE}"));
|
||||
} else {
|
||||
a.words.push(s.into());
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
Ok(a)
|
||||
}
|
||||
fn has(&self, f: &str) -> bool {
|
||||
self.flags.contains_key(f)
|
||||
}
|
||||
fn one(&self, f: &str) -> Option<&str> {
|
||||
self.flags.get(f).and_then(|v| v.last()).map(String::as_str)
|
||||
}
|
||||
fn num(&self, f: &str) -> Result<Option<f64>, String> {
|
||||
self.one(f).map(|v| v.parse::<f64>().map_err(|_| format!("ask: {f} takes seconds, got {v:?}"))).transpose()
|
||||
}
|
||||
fn list(&self, f: &str) -> Vec<String> {
|
||||
self.flags.get(f).into_iter().flatten().flat_map(|v| v.split(',')).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The craft rubric's text, where the guides are installed, for the `rubric` set.
|
||||
pub fn rubric_md() -> Option<String> {
|
||||
std::fs::read_to_string(raea_io_home::home().join("sdk/guides/craft/rubric.md")).ok()
|
||||
}
|
||||
|
||||
/// A question's id from its words: `own-` and its first words, so the same words keep their id.
|
||||
pub fn own_id(words: &str) -> String {
|
||||
let slug: Vec<String> = words.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()).take(6).map(str::to_lowercase).collect();
|
||||
let mut id = format!("own-{}", slug.join("-"));
|
||||
id.truncate(raea_core_ask::limits::ID_LEN);
|
||||
id
|
||||
}
|
||||
|
||||
/// The questions an entry names: its own words (shaped by the kind flags), its sets and its standard ids.
|
||||
fn named(own: &[Question], sets: &[String], std: &[String], rubric: Option<&str>) -> Result<Vec<Question>, String> {
|
||||
let mut qs = own.to_vec();
|
||||
for s in sets {
|
||||
qs.extend(library::set(s, rubric)?);
|
||||
}
|
||||
for id in std {
|
||||
qs.push(library::find(id, rubric).ok_or_else(|| format!("ask: no standard question {id} (raea ask list)"))?);
|
||||
}
|
||||
Ok(qs)
|
||||
}
|
||||
|
||||
fn shaped(words: &str, a: &Args) -> Result<Question, String> {
|
||||
let mut q = Question::plain(&own_id(words), words);
|
||||
if let Some(c) = a.one("--choose") {
|
||||
q.kind = Kind::Choose;
|
||||
q.options = c.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
|
||||
} else if let Some(n) = a.one("--rate") {
|
||||
let n: usize = n.parse().map_err(|_| format!("ask: --rate takes how many levels, got {n:?}"))?;
|
||||
q.kind = Kind::Rate;
|
||||
q.options = (1..=n).map(|i| i.to_string()).collect();
|
||||
} else if a.has("--grade") {
|
||||
q.kind = Kind::Grade;
|
||||
}
|
||||
q.flags = a.list("--flag");
|
||||
if let Some(why) = raea_core_ask::limits::check(&q) {
|
||||
return Err(format!("ask: {why}"));
|
||||
}
|
||||
Ok(q)
|
||||
}
|
||||
|
||||
/// The window from --from, --to and --at (three seconds around it).
|
||||
fn window(a: &Args) -> Result<Option<Window>, String> {
|
||||
if let Some(at) = a.num("--at")? {
|
||||
return Ok(Some(Window { from: Some((at - 1.5).max(0.0)), to: Some(at + 1.5) }));
|
||||
}
|
||||
let (from, to) = (a.num("--from")?, a.num("--to")?);
|
||||
Ok((from.is_some() || to.is_some()).then_some(Window { from, to }))
|
||||
}
|
||||
|
||||
fn voice(v: Option<&str>) -> Result<Option<bool>, String> {
|
||||
match v {
|
||||
None => Ok(None),
|
||||
Some("yes" | "true") => Ok(Some(true)),
|
||||
Some("no" | "false") => Ok(Some(false)),
|
||||
Some(v) => Err(format!("ask: --voice takes yes or no, got {v:?}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pieces read once a run, by what they were read with.
|
||||
type Pieces = HashMap<String, Arc<Piece>>;
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn piece(pieces: &mut Pieces, file: &str, brief: Option<&str>, words: Option<&str>, voice: Option<bool>, state: Option<String>) -> Result<Arc<Piece>, String> {
|
||||
let key = format!("{file}\u{1f}{brief:?}\u{1f}{words:?}\u{1f}{voice:?}\u{1f}{state:?}");
|
||||
if let Some(p) = pieces.get(&key) {
|
||||
return Ok(p.clone());
|
||||
}
|
||||
let p = Arc::new(Piece::read(Path::new(file), brief.map(Path::new), words.map(Path::new), voice, state).map_err(|e| format!("ask: {e}"))?);
|
||||
pieces.insert(key, p.clone());
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
fn entry(p: Arc<Piece>, window: Option<Window>, qs: Vec<Question>, with: Vec<PathBuf>, rubric: Option<&str>) -> Entry {
|
||||
let (questions, dropped) = prepare::keep(qs, &p.facts(), rubric);
|
||||
Entry { piece: p, window, questions, dropped, with }
|
||||
}
|
||||
|
||||
/// The command line's one entry.
|
||||
fn from_args(a: &Args, rubric: Option<&str>, pieces: &mut Pieces) -> Result<Vec<Entry>, String> {
|
||||
let Some((file, words)) = a.words.split_first() else { return Err(USAGE.into()) };
|
||||
let own = words.iter().map(|w| shaped(w, a)).collect::<Result<Vec<_>, _>>()?;
|
||||
let qs = named(&own, &a.list("--set"), &a.list("--std"), rubric)?;
|
||||
if qs.is_empty() {
|
||||
return Err(format!("ask: nothing to ask: give a question in words, --set or --std (raea ask list)\nusage: {USAGE}"));
|
||||
}
|
||||
let p = piece(pieces, file, a.one("--brief"), a.one("--words"), voice(a.one("--voice"))?, a.one("--state").map(str::to_string))?;
|
||||
let with = a.flags.get("--with").into_iter().flatten().map(PathBuf::from).collect();
|
||||
Ok(vec![entry(p, window(a)?, qs, with, rubric)])
|
||||
}
|
||||
|
||||
/// A batch: a JSON list of entries or JSON lines, from a file or stdin (`-`). Each entry is {file, window?, questions?
|
||||
/// (words or questions), set?, std?, with?, brief?, words?, voice?, state?}.
|
||||
fn from_batch(path: &str, rubric: Option<&str>, pieces: &mut Pieces) -> Result<Vec<Entry>, String> {
|
||||
let text = match path {
|
||||
"-" => {
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_to_string(&mut s).map_err(|e| format!("ask: stdin: {e}"))?;
|
||||
s
|
||||
}
|
||||
p => std::fs::read_to_string(p).map_err(|e| format!("ask: {p}: {e}"))?,
|
||||
};
|
||||
let rows: Vec<Value> = match serde_json::from_str::<Value>(text.trim()) {
|
||||
Ok(Value::Array(a)) => a,
|
||||
Ok(v @ Value::Object(_)) => vec![v],
|
||||
_ => text.lines().filter(|l| !l.trim().is_empty()).enumerate().map(|(i, l)| serde_json::from_str(l).map_err(|e| format!("ask: {path} line {}: {e}", i + 1))).collect::<Result<_, _>>()?,
|
||||
};
|
||||
let strs = |v: &Value| -> Vec<String> {
|
||||
match v {
|
||||
Value::String(s) => s.split(',').map(|s| s.trim().to_string()).collect(),
|
||||
Value::Array(a) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(),
|
||||
_ => vec![],
|
||||
}
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for (n, r) in rows.iter().enumerate() {
|
||||
let at = |e: String| format!("ask: {path} entry {}: {e}", n + 1);
|
||||
let file = r["file"].as_str().ok_or_else(|| at("it has no file".into()))?;
|
||||
let own = r["questions"].as_array().into_iter().flatten().map(|q| match q {
|
||||
Value::String(w) => Ok(Question::plain(&own_id(w), w)),
|
||||
q => serde_json::from_value::<Question>(q.clone()).map_err(|e| e.to_string()),
|
||||
});
|
||||
let own = own.collect::<Result<Vec<_>, _>>().map_err(at)?;
|
||||
let qs = named(&own, &strs(&r["set"]), &strs(&r["std"]), rubric).map_err(at)?;
|
||||
let window: Option<Window> = serde_json::from_value(r["window"].clone()).ok();
|
||||
let v = voice(r["voice"].as_str()).map_err(at)?.or(r["voice"].as_bool());
|
||||
let p = piece(pieces, file, r["brief"].as_str(), r["words"].as_str(), v, r["state"].as_str().map(str::to_string)).map_err(at)?;
|
||||
out.push(entry(p, window, qs, strs(&r["with"]).into_iter().map(PathBuf::from).collect(), rubric));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `raea ask list [SET]`: the standard questions.
|
||||
fn list(a: &Args, rubric: Option<&str>) -> Result<String, String> {
|
||||
let sets: Vec<String> = match a.words.get(1) {
|
||||
Some(s) => vec![s.clone()],
|
||||
None => library::SETS.iter().map(|s| s.to_string()).collect(),
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
let mine = calibrate::local();
|
||||
for s in &sets {
|
||||
let mut qs = library::set(s, rubric)?;
|
||||
qs.iter_mut().for_each(|q| calibrate::apply(q, &mine));
|
||||
if a.has("--json") {
|
||||
out.push(json!({"set": s, "questions": qs}).to_string());
|
||||
continue;
|
||||
}
|
||||
out.push(format!("{s}:"));
|
||||
for q in qs {
|
||||
let how = if q.calibrated() { "calibrated" } else { "advice" };
|
||||
out.push(format!(" {:<28} {:<6} {:<10} {}", q.id, format!("{:?}", q.kind).to_lowercase(), how, q.ask));
|
||||
}
|
||||
}
|
||||
Ok(out.join("\n"))
|
||||
}
|
||||
|
||||
/// An event as a line of text.
|
||||
fn line(e: &Event, files: usize) -> String {
|
||||
match e {
|
||||
Event::Would(v) => {
|
||||
let qs: Vec<&str> = v["questions"].as_array().into_iter().flatten().filter_map(|q| q["id"].as_str()).collect();
|
||||
let m = &v["media"];
|
||||
let kb = |k: &str| m[k].as_array().map(|a| a.iter().filter_map(Value::as_u64).map(|b| format!("{} KB", b / 1024)).collect::<Vec<_>>().join(", ")).unwrap_or_default();
|
||||
format!(
|
||||
"would ask {} ({}) about {}:\n {}\n videos [{}], stills [{}], sounds [{}], about ${:.4}\n state: {}",
|
||||
qs.len(),
|
||||
span(v["from"].as_f64().unwrap_or(0.0), v["to"].as_f64()),
|
||||
v["file"].as_str().unwrap_or(""),
|
||||
qs.join(", "),
|
||||
kb("videos"),
|
||||
kb("stills"),
|
||||
kb("sounds"),
|
||||
v["estimate_usd"].as_f64().unwrap_or(0.0),
|
||||
v["state"].as_str().unwrap_or("")
|
||||
)
|
||||
}
|
||||
Event::Answer(a) => {
|
||||
let who = if files > 1 { format!("{}: ", a.file) } else { String::new() };
|
||||
let what = match (&a.says, &a.not_asked, &a.waits) {
|
||||
(Some(s), ..) => format!("{s} [{}]{}", span(a.from, a.to), if a.flagged && a.calibrated { " <- finding" } else if a.flagged { " <- flagged" } else { "" }),
|
||||
(_, Some(n), _) => format!("not asked: {n}"),
|
||||
(.., Some(w)) => w.clone(),
|
||||
_ => "no answer".into(),
|
||||
};
|
||||
format!("{who}{:<34} {what}", a.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `raea ask ...` with its exit code: 0, or 1 when it couldn't ask or a gate failed.
|
||||
pub fn cli(args: &[String]) -> i32 {
|
||||
match run(args) {
|
||||
Ok(code) => code,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run(args: &[String]) -> Result<i32, String> {
|
||||
let a = Args::parse(args)?;
|
||||
let rubric = rubric_md();
|
||||
let jobs = a.one("--jobs").map(|j| j.parse::<usize>().map_err(|_| format!("ask: --jobs takes a number, got {j:?}"))).transpose()?.unwrap_or(4);
|
||||
let sub = a.words.first().map(String::as_str).filter(|w| !Path::new(w).exists());
|
||||
match sub {
|
||||
Some("list") => {
|
||||
println!("{}", list(&a, rubric.as_deref())?);
|
||||
return Ok(0);
|
||||
}
|
||||
Some("verdict") => {
|
||||
let [_, answer, said] = a.words.as_slice() else { return Err(format!("ask verdict ANSWER WORD: the answer's id (from --json or {}) and your answer to its question", record::dir().join("answers.jsonl").display())) };
|
||||
println!("{}", labels::verdict(answer, said, a.one("--eye"))?);
|
||||
return Ok(0);
|
||||
}
|
||||
Some("calibrate") => return calibrated(&a),
|
||||
Some("try") => return tried(&a, jobs),
|
||||
_ => {}
|
||||
}
|
||||
let mut pieces = Pieces::new();
|
||||
let entries = match a.one("--batch") {
|
||||
Some(b) => from_batch(b, rubric.as_deref(), &mut pieces)?,
|
||||
None => from_args(&a, rubric.as_deref(), &mut pieces)?,
|
||||
};
|
||||
let (json_out, dry) = (a.has("--json"), a.has("--dry"));
|
||||
let files = pieces.len();
|
||||
let sum = runner::run(entries, &Opts::new(jobs, dry), &mut |e| {
|
||||
match (&e, json_out) {
|
||||
(Event::Answer(r), true) => println!("{}", serde_json::to_string(r).unwrap_or_default()),
|
||||
(Event::Would(v), true) => println!("{}", json!({"would": v})),
|
||||
(e, false) => println!("{}", line(e, files)),
|
||||
}
|
||||
});
|
||||
if json_out {
|
||||
println!("{}", json!({"summary": sum}));
|
||||
} else if dry {
|
||||
println!("{} call{}, about ${:.4}; nothing was sent", sum.calls, if sum.calls == 1 { "" } else { "s" }, sum.estimate);
|
||||
} else if sum.calls > 0 {
|
||||
let routes: Vec<&str> = sum.routes.iter().map(String::as_str).collect();
|
||||
let left = sum.pool_left.map(|l| format!(", ${l:.2} left this month")).unwrap_or_default();
|
||||
let waiting = if sum.waiting > 0 { format!("; {} wait for the pool", sum.waiting) } else { String::new() };
|
||||
println!(
|
||||
"asked {} question{} in {} call{} through {}: ${:.4}{left}{waiting}. Answers are advice until a question is calibrated (docs/ask.feature AK7).",
|
||||
sum.asked,
|
||||
if sum.asked == 1 { "" } else { "s" },
|
||||
sum.calls,
|
||||
if sum.calls == 1 { "" } else { "s" },
|
||||
routes.join(" and "),
|
||||
sum.cost
|
||||
);
|
||||
}
|
||||
if !dry && sum.calls == 0 {
|
||||
return Err("ask: nothing was asked (each question's line says why)".into());
|
||||
}
|
||||
// a gate fails on a flag (a calibrated one, or with `any` any), and on questions still waiting for the pool
|
||||
let flagged = if a.gate_any { sum.flagged } else { sum.flagged_calibrated };
|
||||
Ok(i32::from(a.has("--gate") && (flagged > 0 || sum.waiting > 0)))
|
||||
}
|
||||
|
||||
/// A version's standing as a line, with its misses below when it doesn't separate.
|
||||
fn standing_line(s: &calibrate::Standing) -> String {
|
||||
let auc = s.auc.map_or_else(|| "no AUC".to_string(), |a| format!("AUC {a:.2}"));
|
||||
let mut out = format!("{} ({}) \"{}\": {}, {auc} on {} labels; {}", s.id, &s.version[..8.min(s.version.len())], s.ask, s.state, s.problems + s.clean, s.why);
|
||||
if s.others > 0 {
|
||||
out += &format!(" ({} from other eyes, not counted)", s.others);
|
||||
}
|
||||
for m in &s.misses {
|
||||
let what = if m.bad { "a problem it scored" } else { "clean work it scored" };
|
||||
out += &format!("\n {what} {:.2}: {} ({}){}", m.problem, m.file, m.span, m.note.as_ref().map(|n| format!(" \"{n}\"")).unwrap_or_default());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `raea ask calibrate [ID]`: the feed's labels read again and each labelled question held to its labels.
|
||||
fn calibrated(a: &Args) -> Result<i32, String> {
|
||||
let (all, (yes, no)) = calibrate::calibrate(a.words.get(1).map(String::as_str))?;
|
||||
if a.has("--json") {
|
||||
println!("{}", json!({"feed": {"problems": yes, "clean": no}}));
|
||||
all.iter().for_each(|s| println!("{}", serde_json::to_string(s).unwrap_or_default()));
|
||||
return Ok(0);
|
||||
}
|
||||
println!("from the feed: {yes} note{} that saw a problem, {no} approval{} without one", if yes == 1 { "" } else { "s" }, if no == 1 { "" } else { "s" });
|
||||
if all.is_empty() {
|
||||
println!("no labelled questions yet: raea ask verdict ANSWER WORD labels one, and your notes on a posted render do too");
|
||||
}
|
||||
all.iter().for_each(|s| println!("{}", standing_line(s)));
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
/// `raea ask try WORDS --like ID`: new words asked of a question's labelled clips, both held to the same labels.
|
||||
fn tried(a: &Args, jobs: usize) -> Result<i32, String> {
|
||||
let words = a.words[1..].join(" ");
|
||||
let like = a.one("--like").ok_or("ask try WORDS --like ID: the question whose labelled clips the new words are asked of")?;
|
||||
if words.trim().is_empty() {
|
||||
return Err("ask try WORDS --like ID: the new words".into());
|
||||
}
|
||||
let json_out = a.has("--json");
|
||||
let (sum, both) = calibrate::try_words(like, &words, &Opts::new(jobs, a.has("--dry")), &mut |e| match (&e, json_out) {
|
||||
(Event::Would(v), true) => println!("{}", json!({"would": v})),
|
||||
(Event::Answer(r), true) => println!("{}", serde_json::to_string(r).unwrap_or_default()),
|
||||
(e, false) => println!("{}", line(e, 2)),
|
||||
})?;
|
||||
match (both, json_out) {
|
||||
(None, true) => println!("{}", json!({"summary": sum})),
|
||||
(None, false) => println!("{} call{}, about ${:.4}; nothing was sent", sum.calls, if sum.calls == 1 { "" } else { "s" }, sum.estimate),
|
||||
(Some((old, new)), true) => println!("{}", json!({"summary": sum, "old": old, "new": new})),
|
||||
(Some((old, new)), false) => println!("${:.4} for {} calls\nold words: {}\nnew words: {}", sum.cost, sum.calls, standing_line(&old), standing_line(&new)),
|
||||
}
|
||||
Ok(i32::from(!a.has("--dry") && sum.calls == 0))
|
||||
}
|
||||
@@ -76,9 +76,10 @@ struct Taste {
|
||||
line: String,
|
||||
}
|
||||
|
||||
/// The checks among a person's taste rules (taste.ts and its kinds), each with the line it stands for.
|
||||
/// The checks among a person's taste rules (taste.ts and its kinds) that a video alone shows (the six forms), each
|
||||
/// with the line it stands for.
|
||||
fn taste_rules(tastes: &[raea_core_brief::Taste]) -> Vec<Taste> {
|
||||
tastes.iter().flat_map(|t| &t.sections).flat_map(|s| &s.rules).filter_map(|r| r.check.map(|c| Taste { form: c.form(), value: c.value(), line: r.text.clone() })).collect()
|
||||
tastes.iter().flat_map(|t| t.checks()).map(|(line, c)| Taste { form: c.form(), value: c.value(), line: line.to_string() }).collect()
|
||||
}
|
||||
|
||||
fn taste_of<'a>(rules: &'a [Taste], form: &str) -> Option<&'a Taste> {
|
||||
|
||||
@@ -170,7 +170,7 @@ pub(crate) fn blotching_from(video: &str, probe: &Probe, scores: &[Option<f64>],
|
||||
let t = k as f64 * 2.0;
|
||||
seen += 1;
|
||||
worst = worst.max(s);
|
||||
if std::env::var_os("RAEA_CHECK_DEBUG").is_some() {
|
||||
if raea_io_trace::stat("RAEA_CHECK_DEBUG") {
|
||||
eprintln!("blotch {t:6.1}s {s:.3}");
|
||||
}
|
||||
if s > BLOTCHY {
|
||||
|
||||
@@ -14,8 +14,11 @@ raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
# a render's record named by when it was (UTC)
|
||||
raea-io-trace = { path = "../../io/trace" }
|
||||
# frame purity (SG9): the video's frames decoded, the stills read
|
||||
raea-io-media = { path = "../../io/media", default-features = false, features = ["apple", "soft"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
serde_json = "1"
|
||||
# `raea check PROJECT | EDIT.tsx` (DR4): taste and controllers' rules, the floor on a composition's newest render, the
|
||||
# `raea check PROJECT | EDIT.tsx` (DR4): the taste files' rules, the floor on a composition's newest render, the
|
||||
# project's compositions
|
||||
raea-core-brief = { path = "../../core/brief" }
|
||||
raea-app-check = { path = "../check" }
|
||||
|
||||
+16
-25
@@ -1,13 +1,13 @@
|
||||
//! `raea check PROJECT|EDIT.tsx` (docs/direction.feature DR4): every check that applies, run over each
|
||||
//! composition's worlds. The rules come from raea's floor, the person's taste (and the workspace's), and the
|
||||
//! workspace's and the project's controllers; each is one of raea's named checks (systems.rs) or a project's TS check
|
||||
//! (ts.rs), and where it was written changes nothing about how it runs. A check that needs a render runs on the
|
||||
//! composition's worlds. The rules come from raea's floor and the taste files: the person's, the workspace's and the
|
||||
//! project's; each is one of raea's named checks (systems.rs) or a project's TS check (ts.rs), and where it was
|
||||
//! written changes nothing about how it runs. A check that needs a render runs on the
|
||||
//! composition's newest render; with none, it waits, and the command says what for. `raea check VIDEO.mp4` is the
|
||||
//! floor alone (apps/check).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use raea_core_brief::{controller, taste};
|
||||
use raea_core_brief::taste;
|
||||
use raea_core_facts::{finding, record, Facts, Finding, Level, Rule, Shot};
|
||||
use raea_runtime_bundle::flag;
|
||||
use raea_runtime_world::{Ask, Render};
|
||||
@@ -18,7 +18,7 @@ use crate::ts;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
pub const USAGE: &str = "raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--taste T] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's taste, the workspace's and the project's rules (a controller's rule fields: one of raea's checks by name, or a project's .ts check); what needs a render and has none waits, and says so)";
|
||||
pub const USAGE: &str = "raea check [PROJECT|EDIT.tsx] [--composition ID] [--only ID] [--taste T] [--render OUT | --no-render] [--json] (every check that applies to each composition, over its frames: raea's floor on its newest render, the person's, the workspace's and the project's taste.ts (each line's check: one of raea's forms or checks by name, or a project's .ts check); what needs a render and has none waits, and says so)";
|
||||
|
||||
/// The flags raea check takes with a value (its own, and the floor's on a video).
|
||||
const TAKES: [&str; 10] = ["--composition", "--only", "--taste", "--render", "--manifest", "--words", "--perception", "--shape", "--platform", "-o"];
|
||||
@@ -71,7 +71,12 @@ fn tastes(project: &Path, given: Vec<PathBuf>, host: &Host) -> Vec<PathBuf> {
|
||||
}
|
||||
}
|
||||
}
|
||||
out.extend(record::up(project, ".raea/workspace").map(|ws| ws.join("taste.ts")).filter(|f| f.is_file()));
|
||||
// the workspace's, then the project's own (the same file when the project is the workspace's folder)
|
||||
for f in record::up(project, ".raea/workspace").map(|ws| ws.join("taste.ts")).into_iter().chain([project.join("taste.ts")]) {
|
||||
if f.is_file() && !out.contains(&f) {
|
||||
out.push(f);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -98,8 +103,8 @@ fn rules(project: &Path, given: Vec<PathBuf>, host: &Host) -> (Vec<Rule>, Vec<Fi
|
||||
(out, bad, notes)
|
||||
}
|
||||
|
||||
/// raea's floor, the person's taste and the workspace's and project's controllers' rules, and a finding for each file
|
||||
/// of them raea couldn't read.
|
||||
/// raea's floor and every taste file's rules (the person's, the workspace's, the project's), and a finding for each
|
||||
/// file of them raea couldn't read.
|
||||
fn held(project: &Path, given: Vec<PathBuf>, host: &Host) -> (Vec<Rule>, Vec<Finding>) {
|
||||
// raea's own: the floor, and the reading check (DR28: its findings keep their own levels, so no rule level)
|
||||
let read = Rule { level: None, ..Rule::named("text-read", "text can be read for as long as it needs, and OCR reads it", Default::default(), Level::Warn, "raea") };
|
||||
@@ -107,26 +112,12 @@ fn held(project: &Path, given: Vec<PathBuf>, host: &Host) -> (Vec<Rule>, Vec<Fin
|
||||
let mut bad = Vec::new();
|
||||
let name = |f: &Path| f.strip_prefix(project).unwrap_or(f).display().to_string();
|
||||
for f in tastes(project, given, host) {
|
||||
let (dir, by) = (f.parent().unwrap_or(Path::new(".")).to_path_buf(), format!("taste {}", name(&f)));
|
||||
match (host.ts.eval)(&f).and_then(|j| raea_core_brief::read::<taste::Taste>(&name(&f), &j)) {
|
||||
Ok(t) => out.extend(t.sections.iter().flat_map(|s| &s.rules).filter_map(|r| Some(Rule::of_taste(&r.text, r.check?, &name(&f))))),
|
||||
Ok(t) => out.extend(t.sections.iter().flat_map(|s| &s.rules).filter_map(|r| Rule::of_taste(r, &dir, &by))),
|
||||
Err(e) => bad.push(Finding::new("taste", Level::Error, format!("raea can't read it: {e}"), "raea check").about(name(&f), None)),
|
||||
}
|
||||
}
|
||||
let ws = record::up(project, ".raea/workspace");
|
||||
for (dir, scope) in ws.iter().map(|w| (raea_app_registry::shared_dir(w, "controllers"), "workspace")).chain([(project.join("controllers"), "project")]) {
|
||||
// a workspace's own folder is its project's too: read once
|
||||
if scope == "project" && ws.as_deref() == Some(project) {
|
||||
continue;
|
||||
}
|
||||
let mut files: Vec<PathBuf> = std::fs::read_dir(&dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "ts")).collect();
|
||||
files.sort();
|
||||
for f in files {
|
||||
match (host.ts.eval)(&f).and_then(|j| controller::of_json(&j)) {
|
||||
Ok(c) => out.extend(Rule::of_controller(&c, &dir, &format!("{scope} {}", name(&f)))),
|
||||
Err(e) => bad.push(Finding::new("controller", Level::Error, format!("raea can't read it: {e}"), "raea check").about(name(&f), None)),
|
||||
}
|
||||
}
|
||||
}
|
||||
(out, bad)
|
||||
}
|
||||
|
||||
@@ -134,7 +125,7 @@ fn held(project: &Path, given: Vec<PathBuf>, host: &Host) -> (Vec<Rule>, Vec<Fin
|
||||
fn compositions(target: &Path, args: &[String]) -> R<Vec<(PathBuf, Option<String>)>> {
|
||||
let one = flag(args, "--composition");
|
||||
let (dir, file) = if target.is_dir() { (target.to_path_buf(), None) } else { (target.parent().unwrap_or(Path::new(".")).to_path_buf(), Some(dunce::canonicalize(&target).map_err(|e| format!("{}: {e}", target.display()))?)) };
|
||||
let reg = raea_app_registry::scan(&dir, &[]);
|
||||
let reg = raea_app_registry::scan(&dir);
|
||||
let mut out: Vec<(PathBuf, Option<String>)> = Vec::new();
|
||||
for c in ®.compositions {
|
||||
let path = reg.dir.join(&c.file);
|
||||
|
||||
@@ -7,6 +7,8 @@ pub use world::{cli, find, Find, USAGE};
|
||||
// how `raea render` ends: its findings counted last, and 1 on an error not let through (DR3)
|
||||
mod rendered;
|
||||
pub use rendered::rendered;
|
||||
// frame purity at a render's end: a sample of its frames rendered again and held to the video's (SG9)
|
||||
mod pure;
|
||||
|
||||
// `raea findings`: the project's record read back, fixed, new and carried (DR3)
|
||||
pub mod findings;
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
//! SG9 (docs/stage-guards.feature): a frame looks the same however it is reached. When a video render with 3D in it ends,
|
||||
//! a sample of its frames is rendered again by one more raea (`render --at`: each frame reached by a jump, none by the
|
||||
//! frames before it) and held to the same frame of the video. A patch that differs beyond the encoder's noise means a
|
||||
//! part kept state from an earlier frame: a shape, words, a colour or another part's row held over (SG1–SG4's faults,
|
||||
//! and any later one of their kind). That frame is rendered alone (`--frame N`, in its own process) to be sure, and the
|
||||
//! error names the frame, the patch, the parts under it (the stills' manifest, raea-sys-stage's on_screen) and where
|
||||
//! the two pictures are kept. A frame that differs only when reached by a jump is the engine's fault, not the
|
||||
//! composition's: a warning. RAEA_FRAME_PURE=0 skips the check (the stills it renders set it).
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use raea_core_facts::{Finding, Level};
|
||||
use serde_json::Value;
|
||||
|
||||
/// Sampled: every this many frames, the last frame, and the frame after each remount (more than 20 parts mounting or
|
||||
/// unmounting at once, as the render's manifest lists them), for a render of more than MIN_FRAMES
|
||||
const EVERY: u64 = 300;
|
||||
const MIN_FRAMES: u64 = 60;
|
||||
/// at most this many samples, spread evenly
|
||||
const MOST: usize = 64;
|
||||
/// A pixel differs when a channel differs by more than this (of 255) through a 3x3 erosion, which drops lone pixels (a
|
||||
/// glyph's edge noise, the encoder's, its colour bleeding along an edge) and keeps a patch: tools/frame-pure-3d.sh's
|
||||
/// bar, where a cut letter was 318. The largest channel, not luma: an orange part over a grey floor differs by 68 in
|
||||
/// luma and 116 in blue, and a part that kept another frame's colour is often as bright as its own
|
||||
const LEVELS: f32 = 96.0;
|
||||
/// A frame differs when more of its pixels than this share differ (207 at 1080p), and at least LEAST
|
||||
const SHARE: f64 = 1e-4;
|
||||
const LEAST: usize = 64;
|
||||
/// The flags of the render the stills repeat (each takes a value, then the bare ones): what it draws and at what size
|
||||
const KEEP: [&str; 9] = ["--composition", "--w", "--h", "--fps", "--frames", "--words", "--perception", "--input", "--stage"];
|
||||
const KEEP_BARE: [&str; 2] = ["--clay", "--lite"];
|
||||
const BY: &str = "raea render (frame-pure)";
|
||||
|
||||
/// The frames to sample of a render `length` frames long, given its remounts.
|
||||
pub(crate) fn samples(length: u64, remounts: &[u64]) -> Vec<u64> {
|
||||
if length <= MIN_FRAMES {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut s: Vec<u64> = (1..).map(|k| k * EVERY).take_while(|f| *f < length).collect();
|
||||
s.push(length - 1);
|
||||
s.extend(remounts.iter().map(|f| f + 1).filter(|f| *f < length));
|
||||
s.sort_unstable();
|
||||
s.dedup();
|
||||
// more than MOST: the last of each of MOST even runs, so the last frame stays
|
||||
let n = s.len();
|
||||
if n > MOST {
|
||||
s = s.into_iter().enumerate().filter(|(i, _)| (i + 1) * MOST / n > i * MOST / n).map(|(_, f)| f).collect();
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Where two RGBA frames of one size differ: the count of pixels with a channel off by more than LEVELS through a 3x3
|
||||
/// erosion (every pixel round it differs too), and their box [x0, y0, x1, y1].
|
||||
pub(crate) fn patch(a: &[u8], b: &[u8], w: usize, h: usize) -> (usize, [usize; 4]) {
|
||||
let d: Vec<f32> = (0..w * h)
|
||||
.map(|i| {
|
||||
let c = |k: usize| (f32::from(a[i * 4 + k]) - f32::from(b[i * 4 + k])).abs();
|
||||
c(0).max(c(1)).max(c(2))
|
||||
})
|
||||
.collect();
|
||||
let (mut n, mut bx) = (0, [usize::MAX, usize::MAX, 0, 0]);
|
||||
for y in 1..h.saturating_sub(1) {
|
||||
for x in 1..w.saturating_sub(1) {
|
||||
if (y - 1..=y + 1).all(|yy| (x - 1..=x + 1).all(|xx| d[yy * w + xx] > LEVELS)) {
|
||||
n += 1;
|
||||
bx = [bx[0].min(x), bx[1].min(y), bx[2].max(x + 1), bx[3].max(y + 1)];
|
||||
}
|
||||
}
|
||||
}
|
||||
(n, if n == 0 { [0; 4] } else { bx })
|
||||
}
|
||||
|
||||
fn differs(n: usize, w: usize, h: usize) -> bool {
|
||||
n > LEAST.max((SHARE * (w * h) as f64) as usize)
|
||||
}
|
||||
|
||||
/// The render's own flags the stills repeat.
|
||||
fn kept(args: &[String]) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
for (i, a) in args.iter().enumerate() {
|
||||
if KEEP.contains(&a.as_str()) {
|
||||
out.extend(args.get(i..i + 2).into_iter().flatten().cloned());
|
||||
} else if KEEP_BARE.contains(&a.as_str()) {
|
||||
out.push(a.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One more raea rendering `file` at `at` into `dir` (its stills, frame-00000.png on, in `at`'s order, and its
|
||||
/// manifest); its own errors are let through, since these are pictures to compare, not the render. Stills past 3,600
|
||||
/// frames make their 3D live at each (render_bundle's LIVE_PAST): 64 of a 13,175-frame film reached by rows went past
|
||||
/// 30 GB and were killed.
|
||||
fn stills(file: &str, args: &[String], at: &[u64], dir: &Path) -> Result<Value, String> {
|
||||
let me = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let list: Vec<String> = at.iter().map(u64::to_string).collect();
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let manifest = dir.join("stills.json");
|
||||
let (flag, out) = if at.len() == 1 { ("--frame", dir.join("frame-00000.png").display().to_string()) } else { ("--at", format!("{}/", dir.display())) };
|
||||
let o = Command::new(me).arg("render").arg(file).args(kept(args)).args([flag, &list.join(","), "-o", &out, "--manifest"]).arg(&manifest).env("RAEA_RECORD", "off").env("RAEA_FRAME_PURE", "0").env("RAEA_DESPITE", "all: frame-pure's own stills")
|
||||
// nothing here reads the stills' clipping or staging, only their pictures and parts on screen: the checks cost
|
||||
// the film's 44 stills 1.6 GB, beside the render that's still held (SG4a: its 8.6 GB peak)
|
||||
.env("RAEA_CLIP_CHECK", "0").env("RAEA_STAGE_CHECK", "0").output().map_err(|e| e.to_string())?;
|
||||
let m = std::fs::read(&manifest).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok());
|
||||
m.ok_or_else(|| format!("the stills didn't render: {}", String::from_utf8_lossy(&o.stderr).lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no message")))
|
||||
}
|
||||
|
||||
fn png(p: &Path) -> Option<(Vec<u8>, usize, usize)> {
|
||||
let img = image::open(p).ok()?.into_rgba8();
|
||||
let (w, h) = img.dimensions();
|
||||
Some((img.into_raw(), w as usize, h as usize))
|
||||
}
|
||||
|
||||
/// The parts on screen at `frame` whose boxes meet `bx`, most overlap first (the manifest of the frame rendered alone:
|
||||
/// its `parts` hold that one frame).
|
||||
fn under(m: &Value, frame: u64, bx: [usize; 4]) -> Vec<String> {
|
||||
let at = &m["parts"][0];
|
||||
if at["frame"] != frame {
|
||||
return Vec::new();
|
||||
}
|
||||
let b = bx.map(|v| v as f64);
|
||||
let mut hit: Vec<(f64, String)> = at["parts"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|p| {
|
||||
let r: Vec<f64> = p[1].as_array()?.iter().filter_map(Value::as_f64).collect();
|
||||
let r: [f64; 4] = r.try_into().ok()?;
|
||||
let over = (b[2].min(r[2]) - b[0].max(r[0])).max(0.0) * (b[3].min(r[3]) - b[1].max(r[1])).max(0.0);
|
||||
(over > 0.0).then(|| (over, p[0].as_str().unwrap_or("a part").to_string()))
|
||||
})
|
||||
.collect();
|
||||
hit.sort_by(|a, b| b.0.total_cmp(&a.0));
|
||||
hit.into_iter().map(|h| h.1).take(3).collect()
|
||||
}
|
||||
|
||||
/// SG9 on a finished render: its findings, none when it isn't a video with 3D in it of more than MIN_FRAMES.
|
||||
pub fn check(args: &[String], out: &Path, manifest: &Value) -> Vec<Finding> {
|
||||
let (Some(file), true) = (args.get(1), manifest["has3d"].as_bool() == Some(true)) else { return Vec::new() };
|
||||
if std::env::var("RAEA_FRAME_PURE").as_deref() == Ok("0") || args.iter().any(|a| a == "--frame" || a == "--at") {
|
||||
return Vec::new();
|
||||
}
|
||||
let remounts: Vec<u64> = manifest["remounts"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect();
|
||||
let at = samples(manifest["length"].as_u64().unwrap_or(0), &remounts);
|
||||
let fps = manifest["fps"].as_f64().unwrap_or(30.0);
|
||||
if at.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("raea-frame-pure-{}", std::process::id()));
|
||||
let found = run(file, args, out, &at, fps, &dir).unwrap_or_else(|e| vec![Finding::new("frame-pure", Level::Note, format!("frame purity wasn't checked: {e}"), BY)]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
found
|
||||
}
|
||||
|
||||
fn run(file: &str, args: &[String], out: &Path, at: &[u64], fps: f64, dir: &Path) -> Result<Vec<Finding>, String> {
|
||||
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
|
||||
stills(file, args, at, &dir.join("at"))?;
|
||||
let mut video = raea_io_media::preferred().into_iter().find_map(|b| b.open_video(out).ok()).ok_or_else(|| format!("{}: no decoder opens it", out.display()))?;
|
||||
let keep = out.with_extension("frame-pure");
|
||||
let mut found = Vec::new();
|
||||
for (i, &f) in at.iter().enumerate() {
|
||||
let Some((jump, w, h)) = png(&dir.join(format!("at/frame-{i:05}.png"))) else { continue };
|
||||
let v = video.frame_at((f as f64 + 0.5) / fps)?;
|
||||
if (v.width as usize, v.height as usize) != (w, h) {
|
||||
return Err(format!("the video is {}x{}, its stills {w}x{h}", v.width, v.height));
|
||||
}
|
||||
if !differs(patch(&v.rgba, &jump, w, h).0, w, h) {
|
||||
continue;
|
||||
}
|
||||
// reached by a jump it differs: rendered alone, in its own process, to be sure
|
||||
let one = dir.join(format!("alone-{f}"));
|
||||
let alone_m = stills(file, args, &[f], &one)?;
|
||||
let Some((alone, _, _)) = png(&one.join("frame-00000.png")) else { continue };
|
||||
let (n, bx) = patch(&v.rgba, &alone, w, h);
|
||||
let parts = under(&alone_m, f, bx);
|
||||
let named = if parts.is_empty() { String::new() } else { format!(" over {}", parts.join(", ")) };
|
||||
let finding = if differs(n, w, h) {
|
||||
std::fs::create_dir_all(&keep).map_err(|e| e.to_string())?;
|
||||
let (seq, own) = (keep.join(format!("frame-{f:05}-render.png")), keep.join(format!("frame-{f:05}-alone.png")));
|
||||
image::save_buffer(&seq, &v.rgba, w as u32, h as u32, image::ColorType::Rgba8).map_err(|e| e.to_string())?;
|
||||
std::fs::copy(one.join("frame-00000.png"), &own).map_err(|e| e.to_string())?;
|
||||
let mut x = Finding::new("frame-pure", Level::Error, format!("{n} pixels{named} (x {}-{}, y {}-{}) differ from the frame rendered alone: a part kept an earlier frame's shape, words, colour or row. The two are {} and {}", bx[0], bx[2], bx[1], bx[3], seq.display(), own.display()), BY).frames(f as i64, f as i64 + 1).measure("pixels", n as f64, "px", Some(LEAST.max((SHARE * (w * h) as f64) as usize) as f64));
|
||||
for p in &parts {
|
||||
x = x.about(p.clone(), None);
|
||||
}
|
||||
x.fix("find what that part takes from the frames before (a key it keeps, a prop read once), or `raea bug` with both pictures when it's raea's")
|
||||
} else {
|
||||
Finding::new("frame-pure-jump", Level::Warn, format!("frame {f}{named} differs when the render jumps to it from frame {}, not alone or in sequence: raea's, not the composition's (`raea bug` with this line)", if i > 0 { at[i - 1].to_string() } else { "0".into() }), BY).frames(f as i64, f as i64 + 1)
|
||||
};
|
||||
found.push(finding);
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn samples_every_300th_the_last_and_after_each_remount() {
|
||||
assert!(samples(60, &[]).is_empty());
|
||||
assert_eq!(samples(180, &[]), vec![179]);
|
||||
assert_eq!(samples(1000, &[40, 599, 999]), vec![41, 300, 600, 900, 999]);
|
||||
let many = samples(1_000_000, &[]);
|
||||
assert_eq!((many.len(), many.last()), (MOST, Some(&999_999)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_patch_counts_but_lone_pixels_and_noise_dont() {
|
||||
let (w, h) = (64, 32);
|
||||
let a = vec![40u8; w * h * 4];
|
||||
let mut b = a.clone();
|
||||
// noise: every pixel off by 20, and lone pixels off by 200
|
||||
b.iter_mut().for_each(|v| *v += 20);
|
||||
for i in (0..w * h).step_by(7) {
|
||||
b[i * 4..i * 4 + 3].copy_from_slice(&[240, 240, 240]);
|
||||
}
|
||||
assert_eq!(patch(&a, &b, w, h).0, 0);
|
||||
// a 10x6 block of words turned white at x 20, y 8: its eroded inside, 8x4
|
||||
for y in 8..14 {
|
||||
for x in 20..30 {
|
||||
b[(y * w + x) * 4..(y * w + x) * 4 + 3].copy_from_slice(&[255, 255, 255]);
|
||||
}
|
||||
}
|
||||
let (n, bx) = patch(&a, &b, w, h);
|
||||
assert_eq!(n, 32);
|
||||
assert_eq!(bx, [21, 9, 29, 13]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stills_repeat_what_the_render_draws_and_nothing_else() {
|
||||
let a: Vec<String> = ["render", "e.tsx", "-o", "out.mp4", "--composition", "k3", "--kbps", "8000", "--clay", "--despite", "type-small", "why", "--frames", "90"].iter().map(|s| s.to_string()).collect();
|
||||
assert_eq!(kept(&a), ["--composition", "k3", "--clay", "--frames", "90"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_parts_under_a_patch_most_overlap_first() {
|
||||
let m = serde_json::json!({"parts": [{"frame": 600, "parts": [["floor", [0.0, 500.0, 1920.0, 1080.0]], ["counter", [800.0, 300.0, 1000.0, 400.0]], ["sky", [0.0, 0.0, 1920.0, 200.0]]]}]});
|
||||
assert_eq!(under(&m, 600, [850, 350, 1000, 520]), ["counter", "floor"]);
|
||||
assert!(under(&m, 300, [850, 350, 1000, 520]).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -47,8 +47,9 @@ pub fn rendered(args: &[String]) -> i32 {
|
||||
if let Some(m) = manifest {
|
||||
if let Some(mut v) = std::fs::read(&m).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok()) {
|
||||
// a video's text, held to the check's text rules as it finishes, a check's round sooner
|
||||
if out.as_deref().and_then(|o| o.extension()).is_some_and(|x| x == "mp4" || x == "mov") {
|
||||
for f in text_found(&v) {
|
||||
if let Some(o) = out.as_deref().filter(|o| matches!(o.extension().and_then(|x| x.to_str()), Some("mp4" | "mov"))) {
|
||||
// and a sample of its frames rendered again, each held to the video's (SG9, pure.rs)
|
||||
for f in text_found(&v).into_iter().chain(crate::pure::check(args, o, &v)) {
|
||||
println!("{}", f.line());
|
||||
found.push(f);
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ fn placement_and_margin_name_the_worst_frame_of_a_run() {
|
||||
|
||||
#[test]
|
||||
fn a_rule_with_no_value_says_so() {
|
||||
let r = Rule { level: Some(Level::Warn), ..Rule::named("text-hold", "", Map::new(), Level::Error, "project controllers/rules.ts") };
|
||||
let r = Rule { level: Some(Level::Warn), ..Rule::named("text-hold", "", Map::new(), Level::Error, "taste taste.ts") };
|
||||
let got = text(&r, &piece(3, |_| vec![]));
|
||||
assert_eq!((got.len(), got[0].level), (1, Level::Warn));
|
||||
assert!(got[0].says.contains("needs a value"));
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "raea-app-double"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "The fingerprint's flags asked again of the decision model (docs/ask.feature AK8): each flagged moment in its axis's own words on its own window, the answers beside the flags and kept as another eye's evidence"
|
||||
|
||||
[dependencies]
|
||||
# the runner every ask goes through, and the question format
|
||||
raea-app-ask = { path = "../ask" }
|
||||
raea-core-ask = { path = "../../core/ask" }
|
||||
# the score's moments, the axes' words and the evidence rows clef's answers become
|
||||
raea-sys-fingerprint = { path = "../../systems/fingerprint" }
|
||||
raea-sys-fingerprint-use = { path = "../../systems/fingerprint-use" }
|
||||
raea-sys-columns = { path = "../../systems/columns" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# a clip made with FFmpeg, and clef's answers as the tests give them
|
||||
raea-io-assets = { path = "../../io/assets" }
|
||||
raea-io-clef = { path = "../../io/clef" }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,167 @@
|
||||
//! The fingerprint's flags asked again (docs/ask.feature AK8). `raea fingerprint score FILE --ask flags` (or `ask:
|
||||
//! "flags"` in fingerprint.ts) puts each flagged moment to the decision model in its axis's own words, on that moment's
|
||||
//! window alone, so it costs by the flags and never by the piece; `--ask unsure` also asks each window an axis puts in
|
||||
//! its plausible band without flagging it. Moments on the same window share a call. Each flag then says "clef agrees
|
||||
//! (0.71)" or "clef doesn't see it (0.08)", and each answer becomes an `eye:clef` evidence row, which trains the axis's
|
||||
//! head and never counts as the person's (FP6d). The question carries the axis's words as its label words, so the
|
||||
//! person's notes calibrate it as they do any question (AK6, AK7).
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use raea_app_ask::prepare::Piece;
|
||||
use raea_app_ask::runner::{self, Entry, Event};
|
||||
pub use raea_app_ask::runner::Opts;
|
||||
use raea_core_ask::{Question, Sees, Window};
|
||||
use raea_sys_columns::Columns;
|
||||
use raea_sys_columns::window::Modality;
|
||||
use raea_sys_fingerprint::evidence::{Row, features};
|
||||
use raea_sys_fingerprint::folder::Folder;
|
||||
use raea_sys_fingerprint::taxonomy::{Axis, Fingerprint};
|
||||
use raea_sys_fingerprint_use::score::{Scored, clock};
|
||||
use serde::Serialize;
|
||||
|
||||
/// One moment asked again.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Double {
|
||||
pub a: f64,
|
||||
pub b: f64,
|
||||
pub axis: String,
|
||||
/// the axis in the person's words
|
||||
pub words: String,
|
||||
/// whether the fingerprint flagged it (else it was unsure of it)
|
||||
pub flagged: bool,
|
||||
/// clef's problem score, when it answered
|
||||
pub problem: Option<f64>,
|
||||
/// clef agrees: past even odds, or past the question's threshold once the person's labels calibrated it
|
||||
pub agrees: Option<bool>,
|
||||
/// its answer's id in raea ask's record, for `raea ask verdict`
|
||||
pub answer: Option<String>,
|
||||
/// why it wasn't asked or still waits
|
||||
pub not_asked: Option<String>,
|
||||
}
|
||||
|
||||
impl Double {
|
||||
/// What clef made of it, as a flag's line says it.
|
||||
pub fn said(&self) -> String {
|
||||
match (self.agrees, self.problem, &self.not_asked) {
|
||||
(Some(true), Some(p), _) => format!("clef agrees ({p:.2})"),
|
||||
(Some(false), Some(p), _) => format!("clef doesn't see it ({p:.2})"),
|
||||
(_, _, Some(why)) => format!("clef wasn't asked: {why}"),
|
||||
_ => "clef gave no answer".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The moments asked again, a line each under the score's summary, as its flags are written (the app reads them).
|
||||
pub fn lines(ds: &[Double]) -> String {
|
||||
let each = ds.iter().map(|d| format!(" {}-{} {}: {}{}\n", clock(d.a), clock(d.b), d.axis, d.said(), if d.flagged { "" } else { " (the fingerprint was unsure)" }));
|
||||
format!("asked again of clef ({} moment{}):\n{}", ds.len(), if ds.len() == 1 { "" } else { "s" }, each.collect::<String>())
|
||||
}
|
||||
|
||||
/// The moments to ask: every flag, and with `unsure` each run of windows an axis puts in its plausible band unflagged.
|
||||
pub fn moments(s: &Scored, fp: &Fingerprint, which: &str) -> Vec<Double> {
|
||||
let words = |axis: &str| fp.axis(axis).and_then(|a| a.words.first().cloned()).unwrap_or_else(|| axis.to_string());
|
||||
let one = |a: f64, b: f64, axis: &str, flagged: bool| Double { a, b, axis: axis.into(), words: words(axis), flagged, problem: None, agrees: None, answer: None, not_asked: None };
|
||||
let mut out: Vec<Double> = s.moments.iter().map(|m| one(m.a, m.b, &m.axis, true)).collect();
|
||||
if which == "unsure" {
|
||||
for w in &s.windows {
|
||||
for x in w.axes.iter().filter(|x| !x.flagged && x.band == Some("plausible")) {
|
||||
match out.iter_mut().rev().find(|d| d.axis == x.axis && !d.flagged) {
|
||||
Some(d) if w.a <= d.b => d.b = w.b,
|
||||
_ => out.push(one(w.a, w.b, &x.axis, false)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An axis as a question: is its defect there (or, for a quality, is it there), looking or listening as it does.
|
||||
pub fn question(axis: &Axis) -> Question {
|
||||
let words = axis.words.first().cloned().unwrap_or_else(|| axis.name.replace(['-', '_'], " "));
|
||||
let good = axis.polarity == "good";
|
||||
let ask = if good { format!("Is this {words}?") } else { format!("Is there {words} here?") };
|
||||
let mut q = Question::plain(&format!("fp.{}", axis.name), &ask);
|
||||
if good {
|
||||
q.flags = vec!["no".into()];
|
||||
}
|
||||
let listens = matches!(axis.modality, Modality::Sound | Modality::Events);
|
||||
q.sees = if listens { Sees::Nothing } else { Sees::Video };
|
||||
q.hears = listens;
|
||||
q.label_words = axis.words.clone();
|
||||
q
|
||||
}
|
||||
|
||||
/// Each moment asked of `file`, a call a window, at most `o.jobs` at once; the moments with clef's answers. A moment
|
||||
/// that couldn't be asked (no route, the pool spent, the file unreadable) says why, and the score goes on without it.
|
||||
pub fn ask(file: &Path, fp: &Fingerprint, mut ds: Vec<Double>, o: &Opts) -> Vec<Double> {
|
||||
let piece = match Piece::read(file, None, None, None, None) {
|
||||
Ok(p) => Arc::new(p),
|
||||
Err(why) => {
|
||||
for d in &mut ds {
|
||||
d.not_asked = Some(format!("the file couldn't be read: {why}"));
|
||||
}
|
||||
return ds;
|
||||
}
|
||||
};
|
||||
let entries = ds
|
||||
.iter()
|
||||
.filter_map(|d| {
|
||||
let q = question(fp.axis(&d.axis)?);
|
||||
Some(Entry { piece: piece.clone(), window: Some(Window { from: Some(d.a), to: Some(d.b) }), questions: vec![q], dropped: vec![], with: vec![] })
|
||||
})
|
||||
.collect();
|
||||
runner::run(entries, o, &mut |e| {
|
||||
let Event::Answer(r) = e else { return };
|
||||
let Some(d) = ds.iter_mut().find(|d| format!("fp.{}", d.axis) == r.id && d.a == r.from && r.to == Some(d.b)) else { return };
|
||||
d.problem = r.problem;
|
||||
d.agrees = r.says.as_ref().map(|_| r.flagged);
|
||||
d.answer = r.answer.clone();
|
||||
d.not_asked = r.not_asked.clone().or_else(|| r.waits.clone());
|
||||
});
|
||||
ds
|
||||
}
|
||||
|
||||
/// The answered moments kept in the fingerprint's ledger as clef's evidence, over the file's columns; a moment asked
|
||||
/// again replaces clef's last row for it. How many it kept.
|
||||
pub fn keep(dir: &Folder, c: &Columns, project: &str, ds: &[Double]) -> Result<usize, String> {
|
||||
let rows: Vec<Row> = ds.iter().filter_map(|d| row(d, &c.media, project)).collect();
|
||||
if rows.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let mut l = dir.ledger().map_err(|e| e.to_string())?;
|
||||
let mut n = 0;
|
||||
for r in rows {
|
||||
l.retain(|x| !(x.source == r.source && x.media == r.media && x.axis == r.axis && x.a == r.a && x.b == r.b));
|
||||
let f = features(c, r.a, r.b);
|
||||
l.push(r, &f);
|
||||
n += 1;
|
||||
}
|
||||
dir.write_ledger(&l).map_err(|e| e.to_string())?;
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// An answered moment as another eye's evidence row.
|
||||
pub fn row(d: &Double, media: &str, project: &str) -> Option<Row> {
|
||||
Some(Row {
|
||||
media: media.into(),
|
||||
a: d.a,
|
||||
b: d.b,
|
||||
axis: d.axis.clone(),
|
||||
bad: d.agrees?,
|
||||
weight: 1.0,
|
||||
who: "clef".into(),
|
||||
source: "eye:clef".into(),
|
||||
project: project.into(),
|
||||
kind: None,
|
||||
region: None,
|
||||
words: None,
|
||||
at: 0,
|
||||
pin: None,
|
||||
band: None,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,88 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use raea_app_ask::runner::Opts;
|
||||
use raea_core_ask::Sees;
|
||||
use raea_io_clef::{Answered, Call, Fail};
|
||||
use raea_sys_fingerprint::taxonomy::base;
|
||||
use raea_sys_fingerprint_use::score::{AxisScore, Moment, Scored, Window};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{ask, lines, moments, question, row};
|
||||
|
||||
fn moment(a: f64, b: f64, axis: &str) -> Moment {
|
||||
Moment { a, b, axis: axis.into(), words: String::new(), by: "head", state: "gating".into(), band: Some("strong"), gating: true, peak: 1.0, at: None }
|
||||
}
|
||||
|
||||
fn window(a: f64, axis: &str, band: &'static str, flagged: bool) -> Window {
|
||||
let s = AxisScore { axis: axis.into(), value: 0.5, by: "head", state: "advice".into(), band: Some(band), flagged, gating: false };
|
||||
Window { a, b: a + 2.0, axes: vec![s], seen: None, heard: None, level: -20.0, overall: None }
|
||||
}
|
||||
|
||||
fn scored(moments: Vec<Moment>, windows: Vec<Window>) -> Scored {
|
||||
Scored { file: "a.mp4".into(), media: "m".into(), dur: 10.0, fingerprint: "test".into(), moments, windows }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_are_asked_and_unsure_adds_the_plausible_windows_run_together() {
|
||||
let fp = base("test");
|
||||
let s = scored(vec![moment(0.0, 3.0, "blur")], vec![window(4.0, "glitch", "plausible", false), window(5.0, "glitch", "plausible", false), window(8.0, "glitch", "weak", false)]);
|
||||
assert_eq!(moments(&s, &fp, "flags").len(), 1);
|
||||
let unsure = moments(&s, &fp, "unsure");
|
||||
assert_eq!(unsure.iter().map(|d| (d.a, d.b, d.axis.as_str(), d.flagged)).collect::<Vec<_>>(), [(0.0, 3.0, "blur", true), (4.0, 7.0, "glitch", false)]);
|
||||
assert!(unsure[0].words.contains("blurry"), "an axis is asked in its own words: {}", unsure[0].words);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_axis_asks_as_it_senses_and_a_quality_is_flagged_on_no() {
|
||||
let fp = base("test");
|
||||
let blur = question(fp.axis("blur").unwrap());
|
||||
assert!(blur.ask.starts_with("Is there a blurry") && blur.sees == Sees::Video && !blur.hears && blur.flags.is_empty());
|
||||
assert_eq!(blur.label_words, fp.axis("blur").unwrap().words, "the person's notes in the axis's words label it");
|
||||
let muffled = question(fp.axis("muffled voice").unwrap());
|
||||
assert!(muffled.sees == Sees::Nothing && muffled.hears);
|
||||
let mut good = fp.axis("blur").unwrap().clone();
|
||||
good.polarity = "good".into();
|
||||
let q = question(&good);
|
||||
assert!(q.ask.starts_with("Is this ") && q.flags == ["no"]);
|
||||
}
|
||||
|
||||
/// clef as a fake: yes to the blur question, no to anything else.
|
||||
fn blur_only(call: &Call) -> Result<Answered, Fail> {
|
||||
let answers = call.questions.iter().map(|q| (q.id.clone(), json!({"noul": if q.id == "fp.blur" { 0.8 } else { 0.1 }}))).collect();
|
||||
Ok(Answered { answers, cost: 0.001, cached: false, route: "a test".into(), pool_left: None })
|
||||
}
|
||||
|
||||
/// A 6 s clip with a picture and a tone.
|
||||
fn clip() -> PathBuf {
|
||||
let out = std::env::temp_dir().join(format!("raea-double-{}.mp4", std::process::id()));
|
||||
let ff = raea_io_assets::ffmpeg_tool("ffmpeg", false).expect("FFmpeg");
|
||||
let ok = std::process::Command::new(ff)
|
||||
.args(["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc=size=320x240:rate=10:duration=6", "-f", "lavfi", "-i", "sine=frequency=440:duration=6"])
|
||||
.args(["-c:v", "mpeg4", "-c:a", "aac", "-shortest"])
|
||||
.arg(&out)
|
||||
.status()
|
||||
.expect("FFmpeg ran");
|
||||
assert!(ok.success());
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_flag_is_asked_on_its_own_window_and_said_beside_it_and_kept_as_clefs() {
|
||||
// SAFETY: this crate's only test that reads it, set before the runner starts
|
||||
unsafe { std::env::set_var("RAEA_ASK_DIR", std::env::temp_dir().join(format!("raea-double-ask-{}", std::process::id()))) };
|
||||
let fp = base("test");
|
||||
let file = clip();
|
||||
let s = scored(vec![moment(0.0, 2.0, "blur"), moment(0.0, 2.0, "glitch"), moment(3.0, 5.0, "muffled voice")], vec![]);
|
||||
let ds = ask(&file, &fp, moments(&s, &fp, "flags"), &Opts { jobs: 2, dry: false, ask: blur_only });
|
||||
let said: Vec<String> = ds.iter().map(|d| format!("{}: {}", d.axis, d.said())).collect();
|
||||
assert_eq!(said, ["blur: clef agrees (0.80)", "glitch: clef doesn't see it (0.10)", "muffled voice: clef doesn't see it (0.10)"]);
|
||||
assert!(lines(&ds).starts_with("asked again of clef (3 moments):\n 0:00-0:02 blur: clef agrees (0.80)\n"), "{}", lines(&ds));
|
||||
let gone = ask(&std::env::temp_dir().join("raea-double-none.mp4"), &fp, moments(&s, &fp, "flags"), &Opts { jobs: 2, dry: false, ask: blur_only });
|
||||
assert!(gone.iter().all(|d| d.agrees.is_none() && d.said().starts_with("clef wasn't asked")), "a file it can't read asks nothing: {gone:?}");
|
||||
let r = row(&ds[0], "m", "p").unwrap();
|
||||
assert!(r.bad && r.source == "eye:clef" && r.who == "clef" && (r.a, r.b) == (0.0, 2.0));
|
||||
assert!(!row(&ds[1], "m", "p").unwrap().bad);
|
||||
let mut unanswered = ds[0].clone();
|
||||
unanswered.agrees = None;
|
||||
assert!(row(&unanswered, "m", "p").is_none(), "a moment clef didn't answer isn't evidence");
|
||||
}
|
||||
@@ -33,7 +33,7 @@ pub(crate) fn session(entry: &str, file: Option<&Path>, rest: &[String], secs: f
|
||||
let bridge = blender_bridge::start(&bin, file, rest)?;
|
||||
*BRIDGE.lock().map_err(|e| e.to_string())? = Some((bridge.port, bridge.token.clone()));
|
||||
let out = std::env::temp_dir().join(format!("raea-blender-{}.js", std::process::id()));
|
||||
let ran = raea_runtime_bundle::bundle_entry(entry, &out, &[]).and_then(|_| raea_runtime_export::run_bundle(&out, secs));
|
||||
let ran = raea_runtime_bundle::bundle_entry(entry, &out, &[]).and_then(|_| raea_runtime_export::run_bundle_to_terminal(&out, secs));
|
||||
let _ = std::fs::remove_file(&out);
|
||||
let _ = post(&json!({ "sid": "raea", "ops": [{ "o": "quit" }] }));
|
||||
*BRIDGE.lock().map_err(|e| e.to_string())? = None;
|
||||
|
||||
@@ -13,6 +13,8 @@ raea-io-home = { path = "../../io/home" }
|
||||
raea-sys-fingerprint = { path = "../../systems/fingerprint" }
|
||||
# scoring and the sheet, which one judges a piece, diff and profiles
|
||||
raea-sys-fingerprint-use = { path = "../../systems/fingerprint-use" }
|
||||
# score --ask: each flag asked again of the decision model (docs/ask.feature AK8)
|
||||
raea-app-double = { path = "../double" }
|
||||
raea-sys-fingerprint-things = { path = "../../systems/fingerprint-things" }
|
||||
# the encoders and the columns they make
|
||||
raea-sys-columns = { path = "../../systems/columns" }
|
||||
|
||||
@@ -21,7 +21,7 @@ use std::path::Path;
|
||||
|
||||
pub use serve::serve;
|
||||
|
||||
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)";
|
||||
pub const USAGE: &str = "raea fingerprint new NAME [--who W] [--about TEXT] [--extends FP] [--kinds K,K] [--tags T,T] | raea fingerprint bootstrap FILE... [--from LIST] [--per N] | raea fingerprint teach FILE --axis A --at T [--bad|--good] [--span S] [--box x0,y0,x1,y1] [--words W] [--project P] | raea fingerprint approve FILE... [--project P] | raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2] | raea fingerprint versions V1 V2... | raea fingerprint profile REFS... --as NAME [--against LIST] | raea fingerprint score FILE [--was OLD] [--ask flags|unsure] [--json] [--sheet out.png] [--timeline] [--profile NAME] | raea fingerprint report [--json] | raea fingerprint which [PATH] [--json] | raea fingerprint use NAME [--in project|workspace] [PATH] | raea fingerprint diff A B [--json] | raea fingerprint share NAME [--in project|workspace] [PATH] | raea fingerprint reembed PLACE... | raea fingerprint read PROJECT [--by kimi|claude] | raea fingerprint readings [PROJECT] [--ask N] [--tally] | raea fingerprint learn-notes [PROJECT] | raea fingerprint move [--fp CHILD] [--to PARENT] [--axis A] [--source S] [--project P] | raea fingerprint postmortem [PROJECT] [--ask N] [--tally] | raea fingerprint things FILE [--project P] [--json] | raea fingerprint stop [--fp NAME] (a person's sense of good work as axes with small heads over on-device encoders, docs/fingerprint.md: new makes ~/.raea/fingerprints/NAME with raea's base taxonomy in fingerprint.ts (or FP's axes with --extends), what it's for, the kinds of piece and project tags it judges, and every axis scoring from its words; bootstrap puts known defects into windows of real work and trains the mechanical axes, held out by source, and patch heads that say where in the frame a picture defect is; teach adds a label at a moment; approve makes approved work clean on every axis, away from its notes; pair says one moment is better than another on an axis (a pick, a hand edit); versions makes weak pairs of noted moments the next version changed; score prints the moments it expects a note on first (where in the frame, and the layers there, when its patch head points held out), then every axis per window with --json, a sheet PNG with --sheet, or the piece second by second in words with --timeline, and with --was OLD whether each of OLD's gating flags is fixed, still there, or looks disguised (nearer the axis's disguised defects than clean work), and with --ask flags each flag put to clef again on its own window, whether clef agrees said beside it and kept as clef's evidence (unsure: the moments it's unsure of too); profile takes the ranges of work you admire (loudness, tilt, cut rate, motion, brightness, contrast, saturation, sharpness), checked leave-one-out, and score --profile says what falls outside them, where and which way; report says each head's held-out score, labels, cheats, gate and what it can't judge; which says the one that judges a piece (its project's, its workspace's, then yours) and why, use pins one there, diff lists the axes two fingerprints rank the same evidence most differently on, and share copies one's taxonomy and evidence (no heads, no media) into a project or workspace for its team; reembed moves a fingerprint's evidence to this machine's encoders, re-embedding the rows whose media it finds; read has a fresh kimi or claude session read a project's pinned notes into kinds and axes, readings puts them to you to check and tallies your answers, and learn-notes makes the defects and praise evidence once you've agreed with 45 kinds and 40 axes in 50, each project's in the fingerprint that judges it; move takes a child's own labels (by axis, source or project) up into a fingerprint it extends, which never reads them otherwise; postmortem scores every version in a project's feed and asks you at most ten yes/no questions in the app, each with its moment playing, where the fingerprint disagrees with your labels or is least sure, and --tally makes your answers evidence and says how each head's held-out score moved; things finds a piece's shots, its things (a render's layers, and the marks drawn on its notes) with their depth, and the camera's path, and says where a thing floats, two pass through each other, the camera lurches mid-move or nothing is on screen, as JSON for `raea check --things` with --json)";
|
||||
|
||||
/// Evaluates a .ts file's default export to its JSON (the CLI's spec host)
|
||||
pub type Eval = fn(&Path) -> Result<String, String>;
|
||||
|
||||
@@ -303,6 +303,16 @@ fn scored(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result
|
||||
let found = checks(&file);
|
||||
arbitrate(&mut s, &fp, &found);
|
||||
raea_sys_fingerprint_things::located::locate(enc, &file, &raea_sys_fingerprint_use::patch::load(&dir.dir), &mut s)?;
|
||||
// AK8: each flag asked again of the decision model on its own window, the answers kept as clef's evidence
|
||||
let doubles = match flag(args, "--ask").map(str::to_string).or_else(|| fp.ask.clone()) {
|
||||
Some(which) => {
|
||||
anyhow::ensure!(which == "flags" || which == "unsure", "--ask takes flags or unsure, not {which}");
|
||||
let d = raea_app_double::ask(&file, &fp, raea_app_double::moments(&s, &fp, &which), &raea_app_double::Opts::new(4, false));
|
||||
raea_app_double::keep(&dir, &c, &project_of(&file), &d).map_err(|e| anyhow!(e))?;
|
||||
d
|
||||
}
|
||||
None => Vec::new(),
|
||||
};
|
||||
// FP9a: each gating flag on the cut before, judged on this one, and its axis's disguises rerun on the fix
|
||||
let fixes = match flag(args, "--was") {
|
||||
Some(old) => {
|
||||
@@ -314,7 +324,7 @@ fn scored(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result
|
||||
None => None,
|
||||
};
|
||||
let mut out = if has(args, "--json") {
|
||||
serde_json::to_string_pretty(&json!({"fingerprint": {"name": fp.name, "about": fp.about, "why": why}, "scored": s, "checks": found.iter().map(|(r, a, b, says)| json!({"check": r, "a": a, "b": b, "says": says})).collect::<Vec<_>>(), "fixes": fixes}))?
|
||||
serde_json::to_string_pretty(&json!({"fingerprint": {"name": fp.name, "about": fp.about, "why": why}, "scored": s, "clef": doubles, "checks": found.iter().map(|(r, a, b, says)| json!({"check": r, "a": a, "b": b, "says": says})).collect::<Vec<_>>(), "fixes": fixes}))?
|
||||
} else if let Some(f) = &fixes {
|
||||
let mut t = format!("judged by {}: {why}\n", fp.name);
|
||||
t += &raea_sys_fingerprint_use::fixed::said(f);
|
||||
@@ -323,6 +333,9 @@ fn scored(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result
|
||||
} else {
|
||||
let mut t = format!("judged by {}: {why}\n", fp.name);
|
||||
t += &summary(&s);
|
||||
if !doubles.is_empty() {
|
||||
t += &raea_app_double::lines(&doubles);
|
||||
}
|
||||
t += &format!("checks: {}\n", if found.is_empty() { "no findings".to_string() } else { format!("{} findings", found.len()) });
|
||||
for (r, a, _, says) in &found {
|
||||
t += &format!(" {} {r}: {says}\n", clock(*a));
|
||||
|
||||
@@ -74,11 +74,11 @@ pub fn export(args: &[String]) -> R<String> {
|
||||
}
|
||||
};
|
||||
if !player.exists() {
|
||||
return Err(format!("no player at {} (build it: cargo build --profile game -p raea-app-game --bin raea-game --features player)", player.display()));
|
||||
return Err(format!("no game player at {}: this raea ships without raea-game, which a game's export is made from; `raea bug \"export-game: no player\"` asks for it (docs/nobuild.feature NB3a)", player.display()));
|
||||
}
|
||||
// the release build's player is ~128 MB stripped, the game profile's ~74 MB (fat LTO, one codegen unit; lightspeed
|
||||
// R7): say so when the bigger one ships because it's the newer
|
||||
if !player.to_string_lossy().contains("/game/") && flag(args, "--player").is_none() {
|
||||
// R7): say so when the bigger one ships because it's the newer, to a checkout's build (an installed raea has only its own)
|
||||
if !player.to_string_lossy().contains("/game/") && player.to_string_lossy().contains("/target/") && flag(args, "--player").is_none() {
|
||||
let mb = std::fs::metadata(&player).map(|m| m.len() as f64 / 1048576.0).unwrap_or(0.0);
|
||||
eprintln!("raea export-game: shipping the release build's player ({mb:.0} MB before stripping): `cargo build --profile game -p raea-app-game --bin raea-game --features player` makes the ~74 MB one, which ships when it's the newer");
|
||||
}
|
||||
|
||||
@@ -13,6 +13,6 @@ raea-io-home = { path = "../../io/home" }
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
serde_json = "1"
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
ureq = { version = "2", features = ["json"] }
|
||||
base64 = "0.22"
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
|
||||
# the one clef client: the question format and the call, routed to the person's plan first (docs/ask.feature AK1b)
|
||||
raea-core-ask = { path = "../../core/ask" }
|
||||
raea-io-clef = { path = "../../io/clef" }
|
||||
@@ -1,37 +0,0 @@
|
||||
//! One clef-omni call on Workers AI (as apps/app/host/critique.ts makes it): the state paragraph, the questions by id,
|
||||
//! the images as data URLs (each made a JPEG at most 1600 px wide first). Keys: CLOUDFLARE_ACCOUNT_ID and
|
||||
//! CLOUDFLARE_API_TOKEN from raea's settings (the environment, then ~/.raea/env).
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use base64::Engine as _;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn jpeg(p: &PathBuf) -> Result<String, String> {
|
||||
let img = image::open(p).map_err(|e| format!("{}: {e}", p.display()))?;
|
||||
let img = if img.width() > 1600 { img.resize(1600, u32::MAX, image::imageops::FilterType::Triangle) } else { img };
|
||||
let mut buf = std::io::Cursor::new(Vec::new());
|
||||
img.to_rgb8().write_to(&mut buf, image::ImageFormat::Jpeg).map_err(|e| e.to_string())?;
|
||||
Ok(format!("data:image/jpeg;base64,{}", base64::engine::general_purpose::STANDARD.encode(buf.into_inner())))
|
||||
}
|
||||
|
||||
/// The answers by question id, and the call's cost in dollars ($0.15 a million input tokens).
|
||||
pub fn ask(state: &str, questions: &Value, images: &[PathBuf]) -> Result<(Value, f64), String> {
|
||||
let (Some(acct), Some(token)) = (raea_io_home::setting("CLOUDFLARE_ACCOUNT_ID"), raea_io_home::setting("CLOUDFLARE_API_TOKEN")) else {
|
||||
return Err("judge: clef-omni on Workers AI needs CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN (the environment or ~/.raea/env)".into());
|
||||
};
|
||||
let imgs: Vec<String> = images.iter().map(jpeg).collect::<Result<_, _>>()?;
|
||||
let body = json!({"state": state, "questions": questions, "images": imgs});
|
||||
let url = format!("https://api.cloudflare.com/client/v4/accounts/{acct}/ai/run/@cf/cloudflare/clef-omni");
|
||||
let res = ureq::post(&url).set("authorization", &format!("Bearer {token}")).timeout(std::time::Duration::from_secs(180)).send_json(body);
|
||||
let j: Value = match res {
|
||||
Ok(r) => r.into_json().map_err(|e| format!("clef: {e}"))?,
|
||||
Err(ureq::Error::Status(code, r)) => return Err(format!("clef: HTTP {code}: {}", r.into_string().unwrap_or_default().chars().take(300).collect::<String>())),
|
||||
Err(e) => return Err(format!("clef: {e}")),
|
||||
};
|
||||
if j["success"] != true {
|
||||
return Err(format!("clef: {}", j["errors"].to_string().chars().take(300).collect::<String>()));
|
||||
}
|
||||
let cost = j["result"]["usage"]["input_tokens"].as_f64().unwrap_or(0.0) * 0.15 / 1e6;
|
||||
Ok((j["result"]["answers"].clone(), cost))
|
||||
}
|
||||
+12
-2
@@ -10,7 +10,6 @@
|
||||
//! each a fresh call) and the stall (the mean up by less than a point over two rounds) are read from it.
|
||||
|
||||
mod agent;
|
||||
mod clef;
|
||||
mod eye;
|
||||
pub mod rubric;
|
||||
|
||||
@@ -24,6 +23,17 @@ use serde_json::{Value, json};
|
||||
|
||||
pub const USAGE: &str = "raea judge DIR [--by clef|kimi|claude] [--brief brief.ts] [--target T.png] [--json] [--dry] | judge eye DIR (CATEGORY=SCORE ... [--pass yes|no] | --by kimi|claude) | judge calibrate [--json] (a --review folder's sheets judged blind: clef-omni on the frozen rubric, or a fresh kimi or claude session on the judge prompt; the pass decided in code; clef advises until calibrated against your eye or an agent's)";
|
||||
|
||||
/// One call through raea's one clef client (raea-io-clef: the person's plan first, then their own Cloudflare keys),
|
||||
/// with the rubric's questions as written and each sheet as a JPEG still.
|
||||
fn ask(state: &str, questions: &Value, images: &[PathBuf]) -> Result<(Value, f64), String> {
|
||||
let qs = questions.as_object().ok_or("judge: the questions aren't a map")?;
|
||||
let questions = qs.iter().map(|(id, w)| raea_core_ask::Question::from_wire(id, w).ok_or(format!("judge: {id} isn't one of clef's question types"))).collect::<Result<_, _>>()?;
|
||||
let stills = images.iter().map(|p| raea_io_clef::media::still(p, None)).collect::<Result<_, _>>()?;
|
||||
let call = raea_io_clef::Call { state: state.into(), questions, media: raea_io_clef::Media { stills, ..Default::default() } };
|
||||
let a = raea_io_clef::ask(&call).map_err(|f| f.to_string())?;
|
||||
Ok((Value::Object(a.answers), a.cost))
|
||||
}
|
||||
|
||||
/// The brief's words, from `raea spec brief.ts --as brief` (look, logline, notDoing), or nothing.
|
||||
fn brief_of(path: Option<&str>) -> Result<Value, String> {
|
||||
let Some(p) = path else { return Ok(json!({})) };
|
||||
@@ -104,7 +114,7 @@ pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
let mut photo = Value::Null;
|
||||
let mut cost = 0.0;
|
||||
for (sheet, st, q, images) in &calls {
|
||||
let (answers, c) = clef::ask(st, q, images)?;
|
||||
let (answers, c) = ask(st, q, images)?;
|
||||
cost += c;
|
||||
if *sheet == "blind" {
|
||||
photo = json!(answers["photo"]["noul"].as_f64().map(|p| (p * 1000.0).round() / 1000.0));
|
||||
|
||||
@@ -63,7 +63,7 @@ fn numbered<'a>(project: &Path, notes: &'a [Kept]) -> Vec<(u32, &'a Kept, &'a ra
|
||||
}
|
||||
|
||||
/// The notes' asks that have a check, each as a rule: the ask's id (n3.2) and words, its check (a .ts check's path
|
||||
/// from the note's folder, as a controller's is from its own), its values, `by` the ask; and each note that can't be
|
||||
/// from the note's folder, as a taste line's is from its file's), its values, `by` the ask; and each note that can't be
|
||||
/// read, as a finding.
|
||||
pub fn rules(project: &Path, notes: &[Kept]) -> (Vec<Rule>, Vec<Finding>) {
|
||||
let bad = notes.iter().filter_map(|k| k.note.as_ref().err().map(|e| Finding::new("note", Level::Error, format!("raea can't read it: {e}"), "raea notes").about(k.file.display().to_string(), None))).collect();
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "raea-app-scene"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "raea scene lint|explain|light|stage: a composition's frames stepped without drawing and held to the contact, light and stage checks"
|
||||
|
||||
[dependencies]
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
raea-runtime-export = { path = "../../runtime/export" }
|
||||
raea-sys-contact = { path = "../../systems/contact" }
|
||||
raea-sys-light-meter = { path = "../../systems/light-meter" }
|
||||
raea-sys-stage = { path = "../../systems/stage" }
|
||||
# its results as Findings (docs/direction.feature DR3)
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
dunce = "1"
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,59 @@
|
||||
//! `raea scene lint|explain|light|stage`: a composition's frames stepped without drawing and handed to raea-sys-contact
|
||||
//! (what each part rests on, and parts that clip), raea-sys-light-meter (the light on a subject) and raea-sys-stage (3D
|
||||
//! type that can't be read, parts that snap, a camera that lurches, empty frames: docs/stage-guards.feature).
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use raea_runtime_bundle::{bundle_composition, comp_opts};
|
||||
use raea_runtime_export::{frame_of, items};
|
||||
|
||||
mod light;
|
||||
mod stage;
|
||||
|
||||
pub const USAGE: &str = "raea scene lint|explain|light|stage EDIT.tsx [--composition ID] [--frame N] [--part NAME] [--from N] [--to N] [--json]";
|
||||
|
||||
/// `raea scene lint|explain EDIT.tsx [--composition ID] [--frame N] [--json]`: the frame's parts measured
|
||||
/// (frame 0 by default). `lint` says the faults (errors fail it: floating, sunk, clipping; warnings: in the air,
|
||||
/// tilted); `explain` says what every part rests on. --json prints the findings (each part's support, gap and the y
|
||||
/// that fixes it) instead. `light` and `stage` are light.rs's and stage.rs's.
|
||||
pub fn cli(args: &[String]) -> Result<String, String> {
|
||||
let usage = USAGE;
|
||||
let (Some(mode), Some(edit)) = (args.get(1).map(String::as_str), args.get(2)) else { return Err(usage.into()) };
|
||||
match mode {
|
||||
"light" => return light::cli(args),
|
||||
"stage" => return stage::cli(args),
|
||||
"lint" | "explain" => {}
|
||||
_ => return Err(usage.into()),
|
||||
}
|
||||
let tsx = dunce::canonicalize(&std::path::PathBuf::from(edit)).map_err(|e| format!("{edit}: {e}"))?;
|
||||
let dir = tsx.parent().unwrap().to_path_buf();
|
||||
let frame = frame_of(args)?;
|
||||
let js = std::env::temp_dir().join(format!("raea-scene-{}.js", std::process::id()));
|
||||
bundle_composition(&tsx, &js, &comp_opts(args)?, None)?;
|
||||
// and the frame after it, to see what moves
|
||||
let got = raea_runtime_export::scene_frames(&js, &dir, frame + 2, false, &[frame, frame + 1]);
|
||||
let _ = std::fs::remove_file(&js);
|
||||
let (frames, ..) = got?.ok_or("the composition has no 3D")?;
|
||||
let k = frames.iter().position(|(f, _)| *f == frame).ok_or_else(|| format!("no frame {frame}"))?;
|
||||
// the frame, and the next (or the one before, at the end) to see what moves
|
||||
let other = if k + 1 < frames.len() { k + 1 } else { k.saturating_sub(1) };
|
||||
let (mut found, errors) = raea_sys_contact::lint(&items(&frames[k].1), &items(&frames[other].1));
|
||||
// and the Blender steps its models call for (a format raea can't load, triangles over budget for the distance)
|
||||
let (more, unloadable) = raea_sys_contact::assets(&items(&frames[k].1));
|
||||
found.extend(more);
|
||||
let (errors, json_out) = (errors + unloadable, args.iter().any(|a| a == "--json"));
|
||||
let parts = found.iter().filter(|v| v["check"] != "clips" && v["check"] != "tilted" && v["check"] != "skipped").count();
|
||||
if mode == "lint" {
|
||||
// its faults as Findings (DR3), worst first, every one shown, the count last; errors fail it, with nothing after
|
||||
let fs = raea_core_facts::finding::ranked(raea_sys_contact::lint_findings(&found, frame, "raea scene lint"));
|
||||
let text = if json_out { serde_json::to_string_pretty(&json!({"frame": frame, "findings": fs})).unwrap_or_default() } else { fs.iter().map(raea_core_facts::Finding::line).chain([format!("frame {frame}: {parts} parts; {}", raea_core_facts::finding::count(&fs))]).collect::<Vec<_>>().join("\n") };
|
||||
if errors > 0 {
|
||||
println!("{text}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
return Ok(text);
|
||||
}
|
||||
// explain: every part's support
|
||||
let t: Vec<String> = found.iter().map(|v| format!("{:<8} {}", v["level"].as_str().unwrap_or(""), v["says"].as_str().unwrap_or(""))).collect();
|
||||
Ok(if json_out { serde_json::to_string_pretty(&json!({"frame": frame, "errors": errors, "found": found})).unwrap_or_default() } else { format!("{}\nframe {frame}: {parts} parts, {errors} errors", t.join("\n")) })
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//! `raea scene light`: the light on a shot's subject, metered (raea-sys-light-meter; docs/scene.feature, "A light plan").
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use raea_runtime_bundle::{bundle_composition, comp_opts, flag};
|
||||
use raea_runtime_export::{Frame, all_items, scene_frames_to};
|
||||
|
||||
/// One composition's frames, stepped.
|
||||
fn frames_of(args: &[String], tsx: &std::path::Path, comp: &str) -> Result<(Vec<(i64, Frame)>, f32), String> {
|
||||
let dir = tsx.parent().unwrap().to_path_buf();
|
||||
let mut opts = comp_opts(args)?;
|
||||
opts.composition = Some(comp.to_string()).filter(|c| !c.is_empty());
|
||||
let js = std::env::temp_dir().join(format!("raea-light-{}-{comp}.js", std::process::id()));
|
||||
bundle_composition(tsx, &js, &opts, None)?;
|
||||
let got = scene_frames_to(&js, &dir, 1);
|
||||
let _ = std::fs::remove_file(&js);
|
||||
let (frames, w, h, _) = got?.ok_or("the composition has no 3D")?;
|
||||
Ok((frames, w as f32 / h.max(1) as f32))
|
||||
}
|
||||
|
||||
/// `raea scene light`: the light on a shot's subject, metered (raea-sys-light-meter; docs/scene.feature, "A light plan").
|
||||
pub(crate) fn cli(args: &[String]) -> Result<String, String> {
|
||||
let usage = "raea scene light EDIT.tsx [--composition ID[,ID...]] [--frame N|last] [--part NAME] [--json]";
|
||||
let Some(edit) = args.get(2) else { return Err(usage.into()) };
|
||||
let tsx = dunce::canonicalize(&std::path::PathBuf::from(edit)).map_err(|e| format!("{edit}: {e}"))?;
|
||||
let flag = |k: &str| flag(args, k);
|
||||
let comps: Vec<String> = flag("--composition").map(|c| c.split(',').map(str::to_string).collect()).unwrap_or_else(|| vec![String::new()]);
|
||||
let part = flag("--part");
|
||||
let json_out = args.iter().any(|a| a == "--json");
|
||||
let pick = |frames: &[(i64, Frame)], which: &str| -> Result<usize, String> {
|
||||
match which {
|
||||
"last" => Ok(frames.len() - 1),
|
||||
f => {
|
||||
let f: i64 = f.parse().map_err(|_| "--frame takes a frame number or last")?;
|
||||
frames.iter().position(|(n, _)| *n == f).ok_or_else(|| format!("no frame {f}"))
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut shots: Vec<(String, Vec<(i64, Value)>)> = Vec::new();
|
||||
for c in &comps {
|
||||
let (frames, aspect) = frames_of(args, &tsx, c)?;
|
||||
let all = all_items(&frames);
|
||||
// one composition: the frame asked for; a sequence: each shot's first and last, for its cuts
|
||||
let at: Vec<usize> = if comps.len() == 1 { vec![pick(&frames, flag("--frame").as_deref().unwrap_or("0"))?] } else { vec![0, frames.len() - 1] };
|
||||
let mut m = Vec::new();
|
||||
for k in at {
|
||||
m.push((frames[k].0, raea_sys_light_meter::meter(&all[k], part.as_deref(), aspect).map_err(|e| format!("{c} frame {}: {e}", frames[k].0))?));
|
||||
}
|
||||
shots.push((c.clone(), m));
|
||||
}
|
||||
let cuts = raea_sys_light_meter::cuts(&shots);
|
||||
if json_out {
|
||||
let shots: Vec<Value> = shots.iter().map(|(c, m)| json!({"composition": c, "frames": m.iter().map(|(f, v)| json!({"frame": f, "meter": v})).collect::<Vec<_>>()})).collect();
|
||||
return Ok(serde_json::to_string_pretty(&json!({"shots": shots, "cuts": cuts, "findings": raea_sys_light_meter::cut_findings(&cuts)})).unwrap_or_default());
|
||||
}
|
||||
// each shot's meter, each cut, and the cuts' jumps and drifts as Findings (DR3), counted last
|
||||
Ok(raea_sys_light_meter::report(&shots, &cuts))
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//! `raea scene stage EDIT.tsx [--composition ID] [--from N] [--to N] [--json]`: every frame's scene stepped without
|
||||
//! drawing and held to the stage checks a render runs at its end (raea-sys-stage, docs/stage-guards.feature SG10-SG14):
|
||||
//! 3D type that can't be read, parts that snap, a camera that lurches or reverses, frames with nothing composed in
|
||||
//! them. Errors fail it, as they fail a render, so it's the cheap look before one.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use raea_core_facts::{Level, finding};
|
||||
use raea_runtime_bundle::{bundle_composition, comp_opts, flag};
|
||||
use raea_runtime_export::{all_items, scene_frames_to};
|
||||
|
||||
pub(crate) fn cli(args: &[String]) -> Result<String, String> {
|
||||
let usage = "raea scene stage EDIT.tsx [--composition ID] [--from N] [--to N] [--json]";
|
||||
let Some(edit) = args.get(2) else { return Err(usage.into()) };
|
||||
let tsx = dunce::canonicalize(&std::path::PathBuf::from(edit)).map_err(|e| format!("{edit}: {e}"))?;
|
||||
let dir = tsx.parent().unwrap().to_path_buf();
|
||||
let frame = |k: &str| flag(args, k).map(|v| v.parse::<i64>().map_err(|_| format!("{k} takes a frame number"))).transpose();
|
||||
let (from, to) = (frame("--from")?.unwrap_or(0), frame("--to")?);
|
||||
let js = std::env::temp_dir().join(format!("raea-stage-{}.js", std::process::id()));
|
||||
bundle_composition(&tsx, &js, &comp_opts(args)?, None)?;
|
||||
let got = scene_frames_to(&js, &dir, 1);
|
||||
let _ = std::fs::remove_file(&js);
|
||||
let (frames, w, h, fps) = got?.ok_or("the composition has no 3D")?;
|
||||
let frames: Vec<_> = frames.into_iter().filter(|(f, _)| *f >= from && to.is_none_or(|t| *f <= t)).collect();
|
||||
let (Some(first), Some(last)) = (frames.first().map(|f| f.0), frames.last().map(|f| f.0)) else { return Err(format!("no frames from {from}")) };
|
||||
let nums: Vec<i64> = frames.iter().map(|(f, _)| *f).collect();
|
||||
let fs = raea_sys_stage::check(&all_items(&frames), &nums, w, h, fps, "raea scene stage");
|
||||
let text = if args.iter().any(|a| a == "--json") {
|
||||
serde_json::to_string_pretty(&json!({"frames": [first, last], "findings": fs})).unwrap_or_default()
|
||||
} else {
|
||||
fs.iter().map(raea_core_facts::Finding::line).chain([format!("frames {first} to {last}: {}", finding::count(&fs))]).collect::<Vec<_>>().join("\n")
|
||||
};
|
||||
if fs.iter().any(|f| f.level == Level::Error) {
|
||||
println!("{text}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
@@ -16,6 +16,7 @@ serde_json = "1"
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
# `raea judge`, dispatched with `raea solid` (verb())
|
||||
raea-app-judge = { path = "../judge" }
|
||||
raea-app-ask = { path = "../ask" }
|
||||
# `raea solid export`: the solid built, written as .glb and read back (core/shape), named and coloured (core/meshcheck)
|
||||
raea-core-shape = { path = "../../core/shape" }
|
||||
raea-core-meshcheck = { path = "../../core/meshcheck" }
|
||||
@@ -91,11 +91,13 @@ fn parse_set(s: &str) -> Result<Map<String, Value>, String> {
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
/// `raea solid ...` and `raea judge ...`, the scene loop's verbs (engine/cli hands them over), or None for another verb.
|
||||
/// `raea solid ...`, `raea judge ...` and `raea ask ...` (docs/ask.feature AK3, which prints as it goes and exits with
|
||||
/// its own code), the verbs that build and judge a piece (engine/cli hands them over), or None for another verb.
|
||||
pub fn verb(args: &[String]) -> Option<Result<String, String>> {
|
||||
match args.first().map(String::as_str) {
|
||||
Some("solid") => Some(cli(args)),
|
||||
Some("judge") => Some(raea_app_judge::cli(args)),
|
||||
Some("ask") => std::process::exit(raea_app_ask::cli(&args[1..])),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ pub fn song(args: &[String]) -> R<String> {
|
||||
}
|
||||
let bin = raea_io_assets::perceive_bin();
|
||||
if !bin.is_file() {
|
||||
return Err("song: the map is made by raea-perceive, which isn't installed beside raea. Update raea (`curl -fsSL https://raea.io/install | sh`: releases ship it in ~/.raea/bin), or from a checkout `cargo build --release -p raea-perceive`, or point RAEA_PERCEIVE at one".into());
|
||||
return Err("song: the map is made by raea-perceive, which isn't installed beside raea. Update raea (`curl -fsSL https://raea.io/install | sh`: releases ship it in ~/.raea/bin), or point RAEA_PERCEIVE at one".into());
|
||||
}
|
||||
// its beat model (Beat This!, MIT): an install keeps it in share/raea/models; raea-perceive reads it from
|
||||
// raea_io_home::models() (~/.local/share/raea-models; %LOCALAPPDATA%\raea\models on Windows)
|
||||
|
||||
@@ -4,17 +4,15 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "`raea workspace`, `raea project` and `raea controller`: a workspace's folders, projects and controllers, each change a commit"
|
||||
description = "`raea workspace` and `raea project`: a workspace's folders and projects, each change a commit"
|
||||
|
||||
[dependencies]
|
||||
dunce = "1"
|
||||
# the controller schema (core/brief controller.rs): a controller file is checked and normalized against it
|
||||
raea-core-brief = { path = "../../core/brief" }
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
# git, which a workspace is: the PATH's, else on Windows the app's or raea's own (raea_io_assets::git)
|
||||
raea-io-assets = { path = "../../io/assets" }
|
||||
serde_json = "1"
|
||||
# a project's compositions, components and controllers read from their source (docs/projects.feature PJ8)
|
||||
# a project's compositions and components read from their source (docs/projects.feature PJ8)
|
||||
raea-app-registry = { path = "registry" }
|
||||
# the project's record of what renders and checks found, which raea next reads (docs/direction.feature DR3)
|
||||
raea-core-facts = { path = "../../core/facts" }
|
||||
|
||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "A raea project's compositions, components and controllers, read from their source without running it, and lint for what isn't connected (docs/projects.feature PJ8)"
|
||||
description = "A raea project's compositions and components, read from their source without running it, and lint for what isn't connected (docs/projects.feature PJ8)"
|
||||
|
||||
[dependencies]
|
||||
dunce = "1"
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
//! A project's compositions, components and controllers, registered by reading its files (docs/projects.feature PJ8),
|
||||
//! A project's compositions and components, registered by reading its files (docs/projects.feature PJ8),
|
||||
//! so the raea app, `raea project scan`, `raea doctor` and `raea next` agree on what each file is:
|
||||
//! - a composition is each <Composition> a registerRoot registers (its props read from the source, not rendered), or a
|
||||
//! .tsx's default export with none that no other file imports, registered for it under its file's name (versions
|
||||
//! NAME-vN.tsx are one composition), sized from its newest render's manifest when it has one;
|
||||
//! - a component is a .tsx a composition imports, directly or through another;
|
||||
//! - a controller is a module whose default export is `controller({...})` from "raea/brief".
|
||||
//! What isn't connected is linted (lint.rs), each with its file and line and the fix. raea-app-workspace wraps `scan`
|
||||
//! with the project's controller overrides (read from .raea/project's git config) and runs it for `raea project scan`,
|
||||
//! `raea doctor`, `raea next` and `raea context`.
|
||||
//! - a component is a .tsx a composition imports, directly or through another.
|
||||
//! What isn't connected is linted (lint.rs), each with its file and line and the fix. raea-app-workspace runs `scan`
|
||||
//! for `raea project scan`, `raea doctor`, `raea next` and `raea context`.
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -22,9 +20,9 @@ pub use read::{Facts, Prop};
|
||||
/// The nearest folder at or above a path that holds a marker (.raea/workspace, .raea/project), as the record finds it.
|
||||
pub use raea_core_facts::record::up;
|
||||
|
||||
/// The workspace's shared folder of one kind (docs/layout.feature: shared/compositions, components, controllers, assets,
|
||||
/// artifacts), which every project can call on as @shared/<kind>/. A workspace from before shared/ keeps that kind at
|
||||
/// its root (controllers/, artifacts/) until `raea workspace tidy` moves it, and it's read there meanwhile.
|
||||
/// The workspace's shared folder of one kind (docs/layout.feature: shared/compositions, components, assets, artifacts),
|
||||
/// which every project can call on as @shared/<kind>/. A workspace from before shared/ keeps that kind at its root
|
||||
/// (artifacts/) until `raea workspace tidy` moves it, and it's read there meanwhile.
|
||||
pub fn shared_dir(ws: &Path, kind: &str) -> PathBuf {
|
||||
let old = ws.join(kind);
|
||||
if !ws.join("shared").is_dir() && old.is_dir() {
|
||||
@@ -33,7 +31,7 @@ pub fn shared_dir(ws: &Path, kind: &str) -> PathBuf {
|
||||
ws.join("shared").join(kind)
|
||||
}
|
||||
|
||||
/// A name as a folder: lowercase, dashes. A controller's id from its title is this (core/brief fills it the same way).
|
||||
/// A name as a folder: lowercase, dashes.
|
||||
pub fn slug(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for c in s.trim().to_lowercase().chars() {
|
||||
@@ -82,13 +80,6 @@ pub struct Component {
|
||||
pub used_by: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Controller {
|
||||
pub id: Option<String>,
|
||||
pub file: String,
|
||||
pub line: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Registry {
|
||||
pub dir: PathBuf,
|
||||
@@ -96,7 +87,6 @@ pub struct Registry {
|
||||
pub project: bool,
|
||||
pub compositions: Vec<Composition>,
|
||||
pub components: Vec<Component>,
|
||||
pub controllers: Vec<Controller>,
|
||||
pub lint: Vec<Lint>,
|
||||
}
|
||||
|
||||
@@ -180,9 +170,8 @@ fn manifest(path: &Path) -> Option<Value> {
|
||||
serde_json::from_str(&std::fs::read_to_string(f).ok()?).ok()
|
||||
}
|
||||
|
||||
/// The folder's registry. `overridden`: the controller ids the project's overrides name, each checked against the
|
||||
/// controllers there (the folder's and its workspace's controllers/).
|
||||
pub fn scan(dir: &Path, overridden: &[String]) -> Registry {
|
||||
/// The folder's registry.
|
||||
pub fn scan(dir: &Path) -> Registry {
|
||||
let dir = dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
|
||||
let project = up(&dir, ".raea/project").is_some();
|
||||
let mut found = Vec::new();
|
||||
@@ -243,10 +232,9 @@ pub fn scan(dir: &Path, overridden: &[String]) -> Registry {
|
||||
.filter(|f| f.rel.ends_with(".tsx") && !comp_files.contains(f.rel.as_str()) && used_by.contains_key(&f.rel))
|
||||
.map(|f| Component { file: f.rel.clone(), used_by: used_by[&f.rel].iter().cloned().collect() })
|
||||
.collect();
|
||||
let controllers = files.iter().filter_map(|f| f.facts.controller.as_ref().map(|c| Controller { id: c.id.clone(), file: f.rel.clone(), line: c.line })).collect();
|
||||
|
||||
let mut reg = Registry { dir, project, compositions, components, controllers, lint: Vec::new() };
|
||||
reg.lint = lint::lint(®, &files, &used_by, overridden);
|
||||
let mut reg = Registry { dir, project, compositions, components, lint: Vec::new() };
|
||||
reg.lint = lint::lint(®, &files, &used_by);
|
||||
reg
|
||||
}
|
||||
|
||||
@@ -280,13 +268,12 @@ impl Registry {
|
||||
"component": c.component, "width": p(&c.width), "height": p(&c.height), "fps": p(&c.fps), "frames": p(&c.frames),
|
||||
})).collect::<Vec<_>>(),
|
||||
"components": self.components.iter().map(|c| json!({ "file": c.file, "usedBy": c.used_by })).collect::<Vec<_>>(),
|
||||
"controllers": self.controllers.iter().map(|c| json!({ "id": c.id, "file": c.file, "line": c.line })).collect::<Vec<_>>(),
|
||||
"findings": self.lint.iter().map(Lint::finding).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
|
||||
/// For an agent (`raea context`): each composition with its id, file, size, fps and length, the components and
|
||||
/// controllers, and what isn't connected (its warnings, at most ten; the notes are `raea project scan`'s).
|
||||
/// For an agent (`raea context`): each composition with its id, file, size, fps and length, the components, and
|
||||
/// what isn't connected (its warnings, at most ten; the notes are `raea project scan`'s).
|
||||
pub fn summary(&self) -> String {
|
||||
let p = |v: &Option<Prop>| match v {
|
||||
Some(Prop::Num(n)) => format!("{n}"),
|
||||
@@ -304,9 +291,6 @@ impl Registry {
|
||||
if !self.components.is_empty() {
|
||||
out.push_str(&format!("components: {}\n", self.components.iter().map(|c| c.file.as_str()).collect::<Vec<_>>().join(", ")));
|
||||
}
|
||||
if !self.controllers.is_empty() {
|
||||
out.push_str(&format!("controllers: {}\n", self.controllers.iter().map(|c| format!("{} ({})", c.id.as_deref().unwrap_or("?"), c.file)).collect::<Vec<_>>().join(", ")));
|
||||
}
|
||||
let warn: Vec<&Lint> = self.warnings().collect();
|
||||
if !warn.is_empty() {
|
||||
out.push_str(&format!("\nnot connected ({}; raea doctor --fix fixes what it can):\n", warn.len()));
|
||||
@@ -321,11 +305,10 @@ impl Registry {
|
||||
/// each about its file:line with the fix, and their count last.
|
||||
pub fn text(&self) -> String {
|
||||
let mut out = format!(
|
||||
"{}: {} compositions, {} components, {} controllers",
|
||||
"{}: {} compositions, {} components",
|
||||
self.dir.display(),
|
||||
self.compositions.len(),
|
||||
self.components.len(),
|
||||
self.controllers.len()
|
||||
self.components.len()
|
||||
);
|
||||
for c in &self.compositions {
|
||||
out.push_str(&format!("\n composition {} ({}:{}{})", c.id, c.file, c.line, if c.how == How::Default { ", its default export" } else { "" }));
|
||||
|
||||
@@ -20,8 +20,6 @@ pub enum Level {
|
||||
pub enum Fix {
|
||||
/// registers a default export: an import line at the top (when one is missing) and a registerRoot at the end
|
||||
Register { file: PathBuf, import: Option<String>, root: String },
|
||||
/// a controller moved to the workspace's (or the project's) controllers/
|
||||
Move { from: PathBuf, to: PathBuf },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -66,13 +64,12 @@ fn warn(file: &str, line: usize, rule: &'static str, says: String, fix: impl Int
|
||||
Lint { file: file.into(), line, rule, level: Level::Warn, says, fix: fix.into(), action: None }
|
||||
}
|
||||
|
||||
pub(super) fn lint(reg: &Registry, files: &[File], used_by: &BTreeMap<String, BTreeSet<String>>, overridden: &[String]) -> Vec<Lint> {
|
||||
pub(super) fn lint(reg: &Registry, files: &[File], used_by: &BTreeMap<String, BTreeSet<String>>) -> Vec<Lint> {
|
||||
let mut out = Vec::new();
|
||||
if !reg.project && !(reg.compositions.is_empty() && reg.controllers.is_empty()) {
|
||||
if !reg.project && !reg.compositions.is_empty() {
|
||||
out.push(warn("", 0, "not-a-project", "this folder isn't in a raea project (no .raea/project at or above it)".into(), "raea project new NAME and move the files in, or raea workspace adopt the folder"));
|
||||
}
|
||||
let comp_files: BTreeSet<&str> = reg.compositions.iter().map(|c| c.file.as_str()).collect();
|
||||
let controller_files: BTreeSet<&str> = reg.controllers.iter().map(|c| c.file.as_str()).collect();
|
||||
// the workspace's shared/, which a project reaches as @shared/
|
||||
let shared = super::up(®.dir, ".raea/workspace").map(|w| {
|
||||
let s = w.join("shared");
|
||||
@@ -89,7 +86,7 @@ pub(super) fn lint(reg: &Registry, files: &[File], used_by: &BTreeMap<String, BT
|
||||
out.push(Lint { file: f.rel.clone(), line: 1, rule: "computed-root", level: Level::Info, says: "registers its root through code the scan doesn't follow (a helper that makes its <Composition>s), so its compositions aren't listed".into(), fix: "known when it renders; write each <Composition> inside registerRoot to have them listed before".into(), action: None });
|
||||
}
|
||||
// a .tsx that is neither a composition nor reached from one
|
||||
if f.rel.ends_with(".tsx") && !f.facts.roots && !comp_files.contains(f.rel.as_str()) && !used_by.contains_key(&f.rel) && !controller_files.contains(f.rel.as_str()) {
|
||||
if f.rel.ends_with(".tsx") && !f.facts.roots && !comp_files.contains(f.rel.as_str()) && !used_by.contains_key(&f.rel) {
|
||||
out.push(warn(&f.rel, 1, "orphan", "isn't a composition, and no composition imports it".into(), "register it (a default export or a registerRoot <Composition>), import it from a composition, or delete it"));
|
||||
}
|
||||
for (spec, line) in f.facts.imports.iter().filter(|(s, _)| is_path(s)) {
|
||||
@@ -197,54 +194,6 @@ pub(super) fn lint(reg: &Registry, files: &[File], used_by: &BTreeMap<String, BT
|
||||
}
|
||||
}
|
||||
|
||||
// controllers: where they're kept, one id each, and every override naming one that's there
|
||||
let ws = super::up(®.dir, ".raea/workspace");
|
||||
// a project keeps its own (its controllers/); the workspace's own folder keeps the shared ones (docs/layout.feature LY3)
|
||||
let home = match &ws {
|
||||
Some(w) if w != ®.dir => reg.dir.join("controllers"),
|
||||
Some(w) => super::shared_dir(w, "controllers"),
|
||||
None => reg.dir.join("controllers"),
|
||||
};
|
||||
let mut ids: BTreeMap<String, Vec<&str>> = BTreeMap::new();
|
||||
for c in ®.controllers {
|
||||
let f = files.iter().find(|f| f.rel == c.file).expect("a controller's file was read");
|
||||
if let Some(id) = &c.id {
|
||||
ids.entry(id.clone()).or_default().push(&c.file);
|
||||
}
|
||||
let in_home = f.path.parent().and_then(Path::file_name).is_some_and(|n| n == "controllers");
|
||||
if !in_home {
|
||||
let id = c.id.clone().unwrap_or_else(|| stem(&c.file));
|
||||
let to = home.join(format!("{id}.ts"));
|
||||
out.push(Lint {
|
||||
file: c.file.clone(),
|
||||
line: c.line,
|
||||
rule: "controller-home",
|
||||
level: Level::Warn,
|
||||
says: "a controller outside controllers/: `raea controller` and the app don't read it".into(),
|
||||
fix: format!("move it to {}", to.display()),
|
||||
action: (!to.exists()).then(|| Fix::Move { from: f.path.clone(), to }),
|
||||
});
|
||||
}
|
||||
}
|
||||
for (id, at) in ids.iter().filter(|(_, at)| at.len() > 1) {
|
||||
for f in at {
|
||||
out.push(warn(f, 1, "controller-duplicate", format!("controller \"{id}\" is declared in {} files", at.len()), "keep one: the others' fields override nothing"));
|
||||
}
|
||||
}
|
||||
// the workspace's controllers too, read the same way, for overrides naming them
|
||||
let mut known: BTreeSet<String> = ids.keys().cloned().collect();
|
||||
for e in std::fs::read_dir(&home).into_iter().flatten().flatten() {
|
||||
let src = std::fs::read_to_string(e.path()).unwrap_or_default();
|
||||
if let Some(id) = super::read::read(&src, false).controller.and_then(|c| c.id) {
|
||||
known.insert(id);
|
||||
}
|
||||
}
|
||||
let mut named = BTreeSet::new();
|
||||
for id in overridden {
|
||||
if !known.contains(id) && named.insert(id.clone()) {
|
||||
out.push(warn(".raea/project", 0, "override-missing", format!("overrides controller \"{id}\", which isn't there"), format!("raea controller ls lists the ones there; remove the override with git config --file .raea/project --remove-section controller.{id}")));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -257,12 +206,5 @@ pub fn apply(fix: &Fix) -> Result<String, String> {
|
||||
std::fs::write(file, text).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
Ok(format!("registered {}", file.display()))
|
||||
}
|
||||
Fix::Move { from, to } => {
|
||||
if let Some(d) = to.parent() {
|
||||
std::fs::create_dir_all(d).map_err(|e| e.to_string())?;
|
||||
}
|
||||
std::fs::rename(from, to).map_err(|e| format!("{}: {e}", from.display()))?;
|
||||
Ok(format!("moved {} to {}", from.display(), to.display()))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
//! What one .tsx or .ts file declares, read from its source without running it (docs/projects.feature PJ8): the
|
||||
//! compositions its registerRoot registers, each <Composition>'s id, component, size, fps and length (a value written
|
||||
//! out, or the expression that computes it); its default export; what it imports; and whether its default export is a
|
||||
//! controller (`export default controller({...})` from "raea/brief"). A prop written as a top-level constant, or simple
|
||||
//! arithmetic on them (`const FPS = 30; … durationInFrames={15 * FPS}`), is read as its value.
|
||||
//! out, or the expression that computes it); its default export; and what it imports. A prop written as a top-level
|
||||
//! constant, or simple arithmetic on them (`const FPS = 30; … durationInFrames={15 * FPS}`), is read as its value.
|
||||
use oxc::allocator::Allocator;
|
||||
use oxc::ast::ast::*;
|
||||
use oxc::ast_visit::{Visit, walk};
|
||||
@@ -43,13 +42,6 @@ pub struct Registered {
|
||||
pub frames: Option<Prop>,
|
||||
}
|
||||
|
||||
/// A controller the file's default export declares: its id (written, else from its title), at a line.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Declared {
|
||||
pub line: usize,
|
||||
pub id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Facts {
|
||||
pub registered: Vec<Registered>,
|
||||
@@ -57,7 +49,6 @@ pub struct Facts {
|
||||
pub default: Option<Option<String>>,
|
||||
/// each import or re-export's module, at its line
|
||||
pub imports: Vec<(String, usize)>,
|
||||
pub controller: Option<Declared>,
|
||||
/// the names it imports from "raea" (a fix that registers its default export adds only what's missing)
|
||||
pub raea_names: Vec<String>,
|
||||
/// why it didn't parse (the first diagnostic), when it didn't
|
||||
@@ -78,7 +69,6 @@ pub fn read(source: &str, tsx: bool) -> Facts {
|
||||
f.broken = Some(d.to_string());
|
||||
return f;
|
||||
}
|
||||
let mut controller_fn = None;
|
||||
for s in &parsed.program.body {
|
||||
match s {
|
||||
Statement::ImportDeclaration(d) => {
|
||||
@@ -86,15 +76,6 @@ pub fn read(source: &str, tsx: bool) -> Facts {
|
||||
if d.source.value == "raea" {
|
||||
f.raea_names.extend(d.specifiers.iter().flatten().map(|sp| sp.local().name.to_string()));
|
||||
}
|
||||
if d.source.value == "raea/brief" {
|
||||
for sp in d.specifiers.iter().flatten() {
|
||||
if let ImportDeclarationSpecifier::ImportSpecifier(x) = sp
|
||||
&& x.imported.name() == "controller"
|
||||
{
|
||||
controller_fn = Some(sp.local().name.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Statement::ExportFromDeclaration(d) => f.imports.push((d.source.value.to_string(), line(d.span.start))),
|
||||
Statement::ExportAllDeclaration(d) => f.imports.push((d.source.value.to_string(), line(d.span.start))),
|
||||
@@ -110,12 +91,6 @@ pub fn read(source: &str, tsx: bool) -> Facts {
|
||||
ExportDefaultDeclarationKind::Identifier(x) => Some(x.name.to_string()),
|
||||
_ => None,
|
||||
});
|
||||
if let ExportDefaultDeclarationKind::CallExpression(c) = &d.declaration
|
||||
&& let Expression::Identifier(callee) = &c.callee
|
||||
&& controller_fn.as_deref() == Some(callee.name.as_str())
|
||||
{
|
||||
f.controller = Some(Declared { line: line(d.span.start), id: controller_id(c) });
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -130,21 +105,6 @@ pub fn read(source: &str, tsx: bool) -> Facts {
|
||||
f
|
||||
}
|
||||
|
||||
/// A controller's id as written, else from its title (core/brief fills an id in from the title the same way).
|
||||
fn controller_id(c: &CallExpression) -> Option<String> {
|
||||
let Some(Argument::ObjectExpression(o)) = c.arguments.first() else { return None };
|
||||
let text = |key: &str| {
|
||||
o.properties.iter().find_map(|p| match p {
|
||||
ObjectPropertyKind::ObjectProperty(p) if p.key.static_name().as_deref() == Some(key) => match &p.value {
|
||||
Expression::StringLiteral(s) => Some(s.value.to_string()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
text("id").or_else(|| text("title").map(|t| super::slug(&t)))
|
||||
}
|
||||
|
||||
/// The file's top-level numeric constants, in order: `const FPS = 30`, `const DUR = 15 * FPS`, and an object constant's
|
||||
/// numeric properties as `NAME.prop` (`const edit = { fps: 30 }`).
|
||||
fn consts(p: &Program) -> HashMap<String, f64> {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! PJ8: a project's files read as compositions, components and controllers, and what isn't connected linted.
|
||||
//! PJ8: a project's files read as compositions and components, and what isn't connected linted.
|
||||
use super::*;
|
||||
|
||||
fn project() -> (tempdir::Dir, PathBuf) {
|
||||
@@ -21,8 +21,6 @@ fn project() -> (tempdir::Dir, PathBuf) {
|
||||
w("bare.render.json", "{\"width\": 1080, \"height\": 1080, \"fps\": 30, \"frames\": [{}, {}, {}]}");
|
||||
w("anon.tsx", "export default () => <div />;\n");
|
||||
w("broken.tsx", "export default function (\n");
|
||||
w("controllers/delivery.ts", "import { controller } from \"raea/brief\";\nexport default controller({ id: \"delivery\", title: \"Delivery\", groups: [] });\n");
|
||||
w("settings/look.ts", "import { controller } from \"raea/brief\";\n\nexport default controller({ title: \"Look and feel\", groups: [] });\n");
|
||||
std::fs::write(t.0.join("outside.tsx"), "export const far = 1;\n").unwrap();
|
||||
(t, p)
|
||||
}
|
||||
@@ -46,9 +44,9 @@ mod tempdir {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compositions_components_and_controllers_are_read_from_the_files() {
|
||||
fn compositions_and_components_are_read_from_the_files() {
|
||||
let (_t, p) = project();
|
||||
let r = scan(&p, &[]);
|
||||
let r = scan(&p);
|
||||
assert!(r.project);
|
||||
let comps: Vec<(&str, &str, How)> = r.compositions.iter().map(|c| (c.id.as_str(), c.file.as_str(), c.how)).collect();
|
||||
assert!(comps.contains(&("promo", "promo.tsx", How::Registered)));
|
||||
@@ -65,14 +63,12 @@ fn compositions_components_and_controllers_are_read_from_the_files() {
|
||||
// card is imported by promo, glyph through card (a default export, but imported): both components, used by promo
|
||||
let comps: Vec<(&str, Vec<&str>)> = r.components.iter().map(|c| (c.file.as_str(), c.used_by.iter().map(String::as_str).collect())).collect();
|
||||
assert_eq!(comps, [("card.tsx", vec!["promo.tsx"]), ("lib/glyph.tsx", vec!["promo.tsx"])]);
|
||||
let ctl: Vec<(Option<&str>, &str)> = r.controllers.iter().map(|c| (c.id.as_deref(), c.file.as_str())).collect();
|
||||
assert_eq!(ctl, [(Some("delivery"), "controllers/delivery.ts"), (Some("look-and-feel"), "settings/look.ts")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_isnt_connected_is_linted_with_its_place_and_fix() {
|
||||
let (_t, p) = project();
|
||||
let r = scan(&p, &[]);
|
||||
let r = scan(&p);
|
||||
let has = |rule: &str, file: &str, line: usize| r.lint.iter().any(|l| l.rule == rule && l.file == file && l.line == line);
|
||||
assert!(has("orphan", "stray.tsx", 1));
|
||||
assert!(!r.lint.iter().any(|l| l.rule == "orphan" && ["card.tsx", "lib/glyph.tsx", "promo.tsx"].contains(&l.file.as_str())));
|
||||
@@ -83,8 +79,6 @@ fn what_isnt_connected_is_linted_with_its_place_and_fix() {
|
||||
assert!(has("duplicate-id", "teaser.tsx", 4));
|
||||
assert!(r.lint.iter().filter(|l| l.rule == "duplicate-id").all(|l| l.says.contains("teaser") || l.file == "teaser.tsx"));
|
||||
assert!(has("computed", "promo.tsx", 5));
|
||||
assert!(has("controller-home", "settings/look.ts", 3));
|
||||
assert!(!r.lint.iter().any(|l| l.file == "controllers/delivery.ts"));
|
||||
// a default export with a render is registered by --fix; a nameless one says how
|
||||
let bare = r.lint.iter().find(|l| l.rule == "unregistered" && l.file == "bare.tsx").unwrap();
|
||||
assert!(bare.action.is_some());
|
||||
@@ -94,44 +88,37 @@ fn what_isnt_connected_is_linted_with_its_place_and_fix() {
|
||||
assert!(!r.lint.iter().any(|l| l.rule == "orphan" && l.file == "shots.tsx"));
|
||||
assert!(has("computed-root", "shots.tsx", 1));
|
||||
// as Findings (DR3): about the file at its line, a fix --fix applies saying so, the count last
|
||||
let home = r.lint.iter().find(|l| l.rule == "controller-home").unwrap().finding();
|
||||
assert_eq!((home.about[0].key.as_deref(), home.fix.as_deref().map(|f| f.starts_with("raea doctor --fix does it: move it to"))), (Some("settings/look.ts:3"), Some(true)));
|
||||
let stray = r.lint.iter().find(|l| l.rule == "orphan" && l.file == "stray.tsx").unwrap().finding();
|
||||
assert_eq!((stray.about[0].key.as_deref(), stray.fix.as_deref().map(|f| f.starts_with("register it"))), (Some("stray.tsx:1"), Some(true)));
|
||||
let bare = bare.finding();
|
||||
assert_eq!((bare.about[0].key.as_deref(), bare.fix.as_deref().map(|f| f.starts_with("raea doctor --fix registers it"))), (Some("bare.tsx:1"), Some(true)), "a fix --fix applies says so");
|
||||
assert!(r.text().lines().last().unwrap().starts_with("raea project scan: 0 errors, "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixes_register_a_default_export_and_move_a_controller_home() {
|
||||
fn a_fix_registers_a_default_export() {
|
||||
let (_t, p) = project();
|
||||
let r = scan(&p, &[]);
|
||||
let r = scan(&p);
|
||||
for l in r.lint.iter().filter(|l| l.action.is_some()) {
|
||||
lint::apply(l.action.as_ref().unwrap()).unwrap();
|
||||
}
|
||||
let bare = std::fs::read_to_string(p.join("bare.tsx")).unwrap();
|
||||
assert!(bare.starts_with("import { Composition, registerRoot } from \"raea\";\nimport { AbsoluteFill }"), "{bare}");
|
||||
assert!(bare.ends_with("registerRoot(() => <Composition id=\"bare\" component={Bare} width={1080} height={1080} fps={30} durationInFrames={3} />);\n"), "{bare}");
|
||||
assert!(p.join("controllers/look-and-feel.ts").is_file() && !p.join("settings/look.ts").exists());
|
||||
let again = scan(&p, &[]);
|
||||
let again = scan(&p);
|
||||
assert_eq!(again.compositions.iter().find(|c| c.file == "bare.tsx").unwrap().how, How::Registered);
|
||||
assert!(!again.lint.iter().any(|l| l.rule == "controller-home" || (l.rule == "unregistered" && l.file == "bare.tsx")));
|
||||
assert!(!again.lint.iter().any(|l| l.rule == "unregistered" && l.file == "bare.tsx"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_outside_any_project_says_so() {
|
||||
let t = tempdir::Dir::new();
|
||||
std::fs::write(t.0.join("a.tsx"), "export default function A() { return null; }\n").unwrap();
|
||||
let r = scan(&t.0, &[]);
|
||||
let r = scan(&t.0);
|
||||
assert!(!r.project);
|
||||
assert!(r.lint.iter().any(|l| l.rule == "not-a-project"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_override_naming_a_controller_that_isnt_there_is_linted() {
|
||||
let (_t, p) = project();
|
||||
let r = scan(&p, &["delivery".into(), "gone".into(), "gone".into()]);
|
||||
let named: Vec<&str> = r.lint.iter().filter(|l| l.rule == "override-missing").map(|l| l.says.as_str()).collect();
|
||||
assert_eq!(named, ["overrides controller \"gone\", which isn't there"], "once, and not for one that's there");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn versions_share_a_stem() {
|
||||
assert_eq!(stem("promo-v12.tsx"), "promo");
|
||||
@@ -145,7 +132,7 @@ fn versions_share_a_stem() {
|
||||
fn real_folder() {
|
||||
let Some(dir) = std::env::var_os("RAEA_SCAN_DIR") else { return };
|
||||
let t = std::time::Instant::now();
|
||||
let r = scan(Path::new(&dir), &[]);
|
||||
let r = scan(Path::new(&dir));
|
||||
println!("{}\n({} ms)", r.text(), t.elapsed().as_millis());
|
||||
}
|
||||
|
||||
@@ -165,7 +152,7 @@ fn a_project_in_the_layout_reaches_shared_and_says_whats_out_of_place() {
|
||||
w("projects/a/compositions/main.tsx", "import { Desk } from \"@shared/components/desk\";\nimport { Leg } from \"../components/leg\";\nimport { Desk as D2 } from \"../../../shared/components/desk\";\nexport default () => <><Desk /><Leg /><D2 /></>;\n");
|
||||
w("projects/a/components/leg.tsx", "export function Leg() { return <i />; }\n");
|
||||
w("projects/a/loose.tsx", "export default () => <b />;\n");
|
||||
let r = scan(&t.0.join("projects/a"), &[]);
|
||||
let r = scan(&t.0.join("projects/a"));
|
||||
let says = |rule: &str| r.lint.iter().filter(|l| l.rule == rule).map(|l| format!("{} {}: {}", l.file, l.says, l.fix)).collect::<Vec<_>>();
|
||||
assert!(says("unresolved").is_empty(), "{:?}", says("unresolved"));
|
||||
let outside = says("outside");
|
||||
@@ -177,7 +164,7 @@ fn a_project_in_the_layout_reaches_shared_and_says_whats_out_of_place() {
|
||||
w("projects/old/.raea/project", "[project]\n\tid = pj-old\n");
|
||||
w("projects/old/promo.tsx", "import { Card } from \"./card\";\nexport default () => <Card />;\n");
|
||||
w("projects/old/card.tsx", "export function Card() { return <i />; }\n");
|
||||
let r = scan(&t.0.join("projects/old"), &[]);
|
||||
let r = scan(&t.0.join("projects/old"));
|
||||
let old: Vec<_> = r.lint.iter().filter(|l| l.rule == "old-layout").collect();
|
||||
assert!(old.len() == 1 && old[0].says.contains("2 files loose") && old[0].fix.contains("raea project tidy"), "{:?}", r.lint);
|
||||
assert!(!r.lint.iter().any(|l| l.rule == "misplaced"));
|
||||
|
||||
@@ -1,209 +0,0 @@
|
||||
//! A workspace's controllers on disk (docs/projects.feature PJ2): shared/controllers/<id>.ts (docs/layout.feature; a
|
||||
//! workspace from before shared/ keeps controllers/ at its root), each `export default
|
||||
//! controller({...})` from "raea/brief", checked by core/brief's normalize. A project overrides a field's value in its
|
||||
//! .raea/project (`[controller "delivery.format"] aspect-ratio = 16:9`), so the project's value wins, as git config's
|
||||
//! own scopes do. Every change is a commit by who made it ("you", or the agent's name with --by).
|
||||
use super::*;
|
||||
use raea_core_brief::controller::{self as ctl, Controller, Field, Kind};
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
const USAGE: &str = "usage: raea controller ls [--json] | get PATH [--json] | set PATH VALUE [--project] [--by NAME] | write FILE.ts [--by NAME] | rm ID [--by NAME]\n (PATH is controller.group.field; a VALUE is JSON for numbers, toggles and lists, else text)";
|
||||
|
||||
fn workspace_dir() -> R<PathBuf> {
|
||||
let here = std::env::current_dir().map_err(|e| e.to_string())?;
|
||||
workspace::up(&here, ".raea/workspace").ok_or_else(|| "not in a workspace: raea workspace init NAME makes one".to_string())
|
||||
}
|
||||
|
||||
/// Every controller in the workspace, checked, in file order.
|
||||
pub fn load(ws: &Path, eval: Eval) -> R<Vec<(PathBuf, Controller)>> {
|
||||
let mut files: Vec<PathBuf> = std::fs::read_dir(raea_app_registry::shared_dir(ws, "controllers")).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "ts")).collect();
|
||||
files.sort();
|
||||
files.into_iter().map(|f| read(&f, eval).map(|c| (f, c))).collect()
|
||||
}
|
||||
|
||||
fn read(f: &Path, eval: Eval) -> R<Controller> {
|
||||
ctl::of_json(&eval(f)?).map_err(|e| format!("{}: {e}", f.display()))
|
||||
}
|
||||
|
||||
/// The module a controller is kept as.
|
||||
pub fn module(c: &Controller) -> String {
|
||||
format!("import {{ controller }} from \"raea/brief\";\n\nexport default controller({});\n", ts_literal(&serde_json::to_value(c).unwrap_or_default(), 0))
|
||||
}
|
||||
|
||||
/// A field's value as JSON (its kind's `value`).
|
||||
fn value_of(f: &Field) -> serde_json::Value {
|
||||
serde_json::to_value(&f.kind).ok().and_then(|v| v.get("value").cloned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The git-config key for a field's override: `controller.<controller>.<group>.<field>`, which git reads as section
|
||||
/// controller, subsection "<controller>.<group>", key <field>.
|
||||
fn key(path: &str) -> String {
|
||||
format!("controller.{path}")
|
||||
}
|
||||
|
||||
/// A value as typed on the command line or kept in git config: JSON when it parses as JSON of the field's kind, else
|
||||
/// the text itself (a choice, a text field).
|
||||
fn parse(f: &Field, s: &str) -> R<serde_json::Value> {
|
||||
let v = match (&f.kind, serde_json::from_str::<serde_json::Value>(s)) {
|
||||
(Kind::Text { .. } | Kind::Choice { .. }, Ok(serde_json::Value::String(t))) => serde_json::Value::String(t),
|
||||
(Kind::Text { .. } | Kind::Choice { .. }, _) => serde_json::Value::String(s.to_string()),
|
||||
(_, Ok(v)) => v,
|
||||
(_, Err(_)) => serde_json::Value::String(s.to_string()),
|
||||
};
|
||||
ctl::check_value(f, &v)
|
||||
}
|
||||
|
||||
/// The overrides of the project `from` is in, by path.
|
||||
pub(crate) fn overrides(from: &Path) -> Vec<(String, String)> {
|
||||
let Some(p) = workspace::up(from, ".raea/project") else { return vec![] };
|
||||
let text = workspace::config(Some(&p.join(".raea/project")), &["--get-regexp", "^controller\\."]).unwrap_or_default();
|
||||
text.lines().filter_map(|l| l.split_once(' ')).map(|(k, v)| (k.trim_start_matches("controller.").to_string(), v.to_string())).collect()
|
||||
}
|
||||
|
||||
fn commit(ws: &Path, paths: &[&Path], what: &str, by: &str) -> R<()> {
|
||||
let mut add = Command::new(workspace::program());
|
||||
add.arg("-C").arg(ws).args(["add", "-A", "--"]).args(paths);
|
||||
add.status().map_err(workspace::missing)?;
|
||||
let ok = workspace::git_cmd().arg("-C").arg(ws).args(["-c", &format!("user.name={by}"), "commit", "-q", "-m", &format!("{by}: {what}"), "--"]).args(paths).status().map_err(workspace::missing)?;
|
||||
if ok.success() { Ok(()) } else { Err(format!("couldn't commit {what}")) }
|
||||
}
|
||||
|
||||
/// `raea controller …`, its specs evaluated by `eval`
|
||||
pub fn controller(args: &[String], eval: Eval) -> R<String> {
|
||||
let json_out = args.iter().any(|a| a == "--json");
|
||||
let by = workspace::flag(args, "--by").unwrap_or("you").trim_start_matches('@').to_string();
|
||||
let w: Vec<&str> = args.iter().enumerate().filter(|(i, a)| !a.starts_with("--") && !(*i > 0 && args[i - 1] == "--by")).map(|(_, a)| a.as_str()).collect();
|
||||
let ws = workspace_dir()?;
|
||||
match w.as_slice() {
|
||||
["ls"] | [] => ls(&ws, json_out, eval),
|
||||
["get", path] => get(&ws, path, json_out, eval),
|
||||
["set", path, value] => set(&ws, path, value, args.iter().any(|a| a == "--project"), &by, eval),
|
||||
["write", file] => write(&ws, Path::new(file), &by, eval),
|
||||
["rm", id] => rm(&ws, id, &by),
|
||||
_ => Err(USAGE.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The controllers as `raea controller ls` prints them, with the overrides of the project `from` is in: what `raea
|
||||
/// context` shows an agent. None outside a workspace or when it has no controllers.
|
||||
pub fn summary(from: &Path, eval: Eval) -> Option<String> {
|
||||
let ws = workspace::up(from, ".raea/workspace")?;
|
||||
load(&ws, eval).ok().filter(|cs| !cs.is_empty())?;
|
||||
ls_from(&ws, from, false, eval).ok()
|
||||
}
|
||||
|
||||
fn ls(ws: &Path, json_out: bool, eval: Eval) -> R<String> {
|
||||
ls_from(ws, &std::env::current_dir().map_err(|e| e.to_string())?, json_out, eval)
|
||||
}
|
||||
|
||||
fn ls_from(ws: &Path, from: &Path, json_out: bool, eval: Eval) -> R<String> {
|
||||
let cs = load(ws, eval)?;
|
||||
let over = overrides(from);
|
||||
let mut rows = vec![];
|
||||
for (_, c) in &cs {
|
||||
for g in &c.groups {
|
||||
for f in &g.fields {
|
||||
let path = format!("{}.{}.{}", c.id, g.id, f.id);
|
||||
let mine = over.iter().find(|(k, _)| *k == path).and_then(|(_, v)| parse(f, v).ok());
|
||||
rows.push((path, f, mine.clone().unwrap_or_else(|| value_of(f)), mine.is_some()));
|
||||
}
|
||||
}
|
||||
}
|
||||
if json_out {
|
||||
let fields: Vec<_> = rows.iter().map(|(p, f, v, o)| json!({"path": p, "label": f.label, "type": serde_json::to_value(&f.kind).ok().and_then(|k| k.get("type").cloned()), "value": v, "project": o})).collect();
|
||||
let list: Vec<_> = cs.iter().map(|(_, c)| serde_json::to_value(c).map(|v| tidy_deep(&v)).unwrap_or_default()).collect();
|
||||
return Ok(json!({"controllers": list, "fields": fields}).to_string());
|
||||
}
|
||||
if cs.is_empty() {
|
||||
return Ok("no controllers yet: raea controller write FILE.ts adds one (`export default controller({ title, groups })` from \"raea/brief\")".into());
|
||||
}
|
||||
let mut out = String::new();
|
||||
for (_, c) in &cs {
|
||||
out.push_str(&format!("{} ({})\n", c.title, c.id));
|
||||
for (p, f, v, o) in rows.iter().filter(|r| r.0.starts_with(&format!("{}.", c.id))) {
|
||||
out.push_str(&format!(" {p} {}: {}{}\n", f.label, tidy(v), if *o { " (this project)" } else { "" }));
|
||||
}
|
||||
}
|
||||
Ok(out.trim_end().to_string())
|
||||
}
|
||||
|
||||
/// Where a path's field is: its controller, group and field, by index.
|
||||
fn locate(cs: &[(PathBuf, Controller)], path: &str) -> R<(usize, usize, usize)> {
|
||||
let mut p = path.splitn(3, '.');
|
||||
let (c, g, f) = (p.next().unwrap_or(""), p.next().unwrap_or(""), p.next().unwrap_or(""));
|
||||
let ci = cs.iter().position(|x| x.1.id == c);
|
||||
let gi = ci.and_then(|ci| cs[ci].1.groups.iter().position(|y| y.id == g));
|
||||
let fi = ci.zip(gi).and_then(|(ci, gi)| cs[ci].1.groups[gi].fields.iter().position(|z| z.id == f));
|
||||
match (ci, gi, fi) {
|
||||
(Some(c), Some(g), Some(f)) => Ok((c, g, f)),
|
||||
_ => Err(format!("no field at {path}: raea controller ls lists the paths (controller.group.field)")),
|
||||
}
|
||||
}
|
||||
|
||||
fn find<'a>(cs: &'a [(PathBuf, Controller)], path: &str) -> R<&'a Field> {
|
||||
let (c, g, f) = locate(cs, path)?;
|
||||
Ok(&cs[c].1.groups[g].fields[f])
|
||||
}
|
||||
|
||||
fn get(ws: &Path, path: &str, json_out: bool, eval: Eval) -> R<String> {
|
||||
let cs = load(ws, eval)?;
|
||||
let f = find(&cs, path)?;
|
||||
let here = std::env::current_dir().map_err(|e| e.to_string())?;
|
||||
let mine = overrides(&here).into_iter().find(|(k, _)| k == path).map(|(_, v)| parse(f, &v)).transpose()?;
|
||||
let v = mine.clone().unwrap_or_else(|| value_of(f));
|
||||
let v = tidy(&v);
|
||||
Ok(if json_out { json!({"path": path, "value": v, "project": mine.is_some()}).to_string() } else { v.to_string() })
|
||||
}
|
||||
|
||||
fn set(ws: &Path, path: &str, value: &str, project: bool, by: &str, eval: Eval) -> R<String> {
|
||||
let mut cs = load(ws, eval)?;
|
||||
let v = parse(find(&cs, path)?, value)?;
|
||||
if project {
|
||||
let here = std::env::current_dir().map_err(|e| e.to_string())?;
|
||||
let p = workspace::up(&here, ".raea/project").ok_or("--project: not in a project")?;
|
||||
let text = match &v {
|
||||
serde_json::Value::String(s) => s.clone(),
|
||||
v => v.to_string(),
|
||||
};
|
||||
let file = p.join(".raea/project");
|
||||
workspace::set(&file, &key(path), &text)?;
|
||||
// a submodule project is its own repo; an inline one commits in the workspace
|
||||
let repo = if p.join(".git").exists() { p.clone() } else { ws.to_path_buf() };
|
||||
commit(&repo, &[&file], &format!("{path} = {text} for this project"), by)?;
|
||||
return Ok(format!("{path} = {text} (this project)"));
|
||||
}
|
||||
let (c, g, f) = locate(&cs, path)?;
|
||||
let (file, ctrl) = &mut cs[c];
|
||||
let field = &mut ctrl.groups[g].fields[f];
|
||||
let mut kind = serde_json::to_value(&field.kind).map_err(|e| e.to_string())?;
|
||||
kind["value"] = v.clone();
|
||||
field.kind = serde_json::from_value(kind).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&*file, module(ctrl)).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
let file = file.clone();
|
||||
let v = tidy(&v);
|
||||
let said = v.as_str().map(String::from).unwrap_or_else(|| v.to_string());
|
||||
commit(ws, &[&file], &format!("{path} = {said}"), by)?;
|
||||
Ok(format!("{path} = {v}"))
|
||||
}
|
||||
|
||||
fn write(ws: &Path, file: &Path, by: &str, eval: Eval) -> R<String> {
|
||||
let c = read(file, eval)?;
|
||||
let to = raea_app_registry::shared_dir(ws, "controllers").join(format!("{}.ts", c.id));
|
||||
let new = !to.exists();
|
||||
std::fs::create_dir_all(raea_app_registry::shared_dir(ws, "controllers")).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&to, module(&c)).map_err(|e| format!("{}: {e}", to.display()))?;
|
||||
commit(ws, &[&to], &format!("{} controller {}", if new { "add" } else { "rewrite" }, c.id), by)?;
|
||||
let n = |k: usize, what: &str| format!("{k} {what}{}", if k == 1 { "" } else { "s" });
|
||||
Ok(format!("{}: {} ({}, {})", to.display(), c.title, n(c.groups.len(), "group"), n(c.groups.iter().map(|g| g.fields.len()).sum(), "field")))
|
||||
}
|
||||
|
||||
fn rm(ws: &Path, id: &str, by: &str) -> R<String> {
|
||||
let file = raea_app_registry::shared_dir(ws, "controllers").join(format!("{id}.ts"));
|
||||
if !file.is_file() {
|
||||
return Err(format!("no controller {id}: raea controller ls lists them"));
|
||||
}
|
||||
std::fs::remove_file(&file).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
commit(ws, &[&file], &format!("remove controller {id}"), by)?;
|
||||
Ok(format!("removed {id} (git revert brings it back)"))
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
//! repo's git config), and an agent's copy of the raea skill from another version. `raea context` runs the same checks
|
||||
//! and prints CONTEXT_STALE when any finds something, so they stay cheap: file reads and git config, no engine.
|
||||
//! It also lists what in the project isn't connected to raea's project system (docs/projects.feature PJ8, registry.rs):
|
||||
//! `--fix` registers a default export and moves a stray controller to controllers/, as a commit.
|
||||
//! `--fix` registers a default export, as a commit. A controller left from before 11-20 is listed with where its parts
|
||||
//! go, and kept: raea reads none since, and only the person knows which still hold.
|
||||
use super::*;
|
||||
use crate::workspace::{get, git, include, new_id, set};
|
||||
|
||||
@@ -69,6 +70,32 @@ fn format(repo: &Path, file: &Path, keys: &[(&str, String)], out: &mut Vec<Findi
|
||||
}
|
||||
}
|
||||
|
||||
/// Controllers, which raea no longer reads (11-20): each .ts in the project's or the workspace's controllers/ (or the
|
||||
/// workspace's shared/controllers/), with where its parts go. Nothing is moved or deleted.
|
||||
fn old_controllers(base: &Path, ws: Option<&Path>, out: &mut Vec<Finding>) {
|
||||
let mut dirs = vec![base.join("controllers")];
|
||||
dirs.extend(ws.into_iter().flat_map(|w| [w.join("controllers"), w.join("shared/controllers")]));
|
||||
dirs.dedup();
|
||||
for d in dirs {
|
||||
let mut files: Vec<PathBuf> = std::fs::read_dir(&d).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "ts")).collect();
|
||||
files.sort();
|
||||
for f in files {
|
||||
let says = format!("{}: a controller, which raea no longer reads; move what still holds (a standing rule or preference to a line in taste.ts, with a check when raea can measure it; a decision for now to a feed post with an ask; a piece's settings into its composition), then delete it", f.display());
|
||||
out.push(Finding { says, fix: Fix::No });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A brief.ts that still keeps tasks in `stages` (docs/plan.feature PL8a): they read, unread, and belong in plan.org.
|
||||
fn briefs_with_tasks(base: &Path, out: &mut Vec<Finding>) {
|
||||
let f = base.join("brief.ts");
|
||||
let Ok(text) = std::fs::read_to_string(&f) else { return };
|
||||
if text.lines().any(|l| l.trim_start().starts_with("stages:") || l.trim_start().starts_with("\"stages\":")) {
|
||||
let says = format!("{}: keeps tasks in `stages`, which raea no longer reads; move each to the project's plan.org (an Org heading under its stage, its mark as TODO, DONE or DROPPED), then delete `stages`", f.display());
|
||||
out.push(Finding { says, fix: Fix::No });
|
||||
}
|
||||
}
|
||||
|
||||
/// The `version:` in a SKILL.md's front matter.
|
||||
fn skill_version(md: &Path) -> Option<String> {
|
||||
let text = std::fs::read_to_string(md).ok()?;
|
||||
@@ -83,6 +110,8 @@ pub fn findings(from: &Path, skills: &[(&str, PathBuf)], version: &str) -> Vec<F
|
||||
let project = up(from, ".raea/project");
|
||||
let base = project.clone().or_else(|| ws.clone()).unwrap_or_else(|| from.to_path_buf());
|
||||
old_briefs(&base, if project.is_some() { 2 } else { 1 }, &mut out);
|
||||
old_controllers(&base, ws.as_deref(), &mut out);
|
||||
briefs_with_tasks(&base, &mut out);
|
||||
if let Some(ws) = &ws {
|
||||
let name = ws.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let keys = [("workspace.id", new_id("ws")), ("workspace.name", name), ("workspace.layout", "monorepo".to_string())];
|
||||
@@ -154,7 +183,7 @@ pub fn doctor(args: &[String], skills: &[(&str, PathBuf)], version: &str, reinst
|
||||
let mut found = findings(&from, skills, version);
|
||||
found.extend(registry_findings(&from));
|
||||
if found.is_empty() {
|
||||
return Ok("CHECKED nothing to fix: this folder's files and the agents' raea skill match this raea, and its compositions, components and controllers are connected".into());
|
||||
return Ok("CHECKED nothing to fix: this folder's files and the agents' raea skill match this raea, and its compositions and components are connected".into());
|
||||
}
|
||||
let mut touched = Vec::new();
|
||||
let mut lines = Vec::new();
|
||||
@@ -165,10 +194,8 @@ pub fn doctor(args: &[String], skills: &[(&str, PathBuf)], version: &str, reinst
|
||||
(Fix::Include(repo, file), true) => include(repo, file).map(|_| true),
|
||||
(Fix::Skills(agent), true) => reinstall(agent).map(|_| true),
|
||||
(Fix::Registry(r), true) => {
|
||||
touched.extend(match r {
|
||||
crate::registry::Fix::Register { file, .. } => vec![file.clone()],
|
||||
crate::registry::Fix::Move { from, to } => vec![from.clone(), to.clone()],
|
||||
});
|
||||
let crate::registry::Fix::Register { file, .. } = r;
|
||||
touched.push(file.clone());
|
||||
crate::registry::apply(r).map(|_| true)
|
||||
}
|
||||
_ => Ok(false),
|
||||
|
||||
@@ -1,28 +1,20 @@
|
||||
//! A workspace's folders and files (docs/projects.feature PJ1-PJ4): `raea workspace`, `raea project` (with split and
|
||||
//! join) and `raea controller`. A workspace is a git repo raea changes by commits; its controllers are spec modules,
|
||||
//! which the raea CLI evaluates on the engine and hands in as an `Eval`, so this crate needs no engine of its own.
|
||||
//! A workspace's folders and files (docs/projects.feature PJ1-PJ4): `raea workspace` and `raea project` (with split
|
||||
//! and join). A workspace is a git repo raea changes by commits.
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
mod controllers;
|
||||
pub mod doctor;
|
||||
mod literal;
|
||||
mod repair;
|
||||
pub mod next;
|
||||
pub mod registry;
|
||||
mod storage;
|
||||
mod workspace;
|
||||
|
||||
pub use controllers::{controller, module, summary};
|
||||
pub use registry::context;
|
||||
pub use literal::{tidy, tidy_deep, ts_literal};
|
||||
pub use workspace::{default_root, project, projects, root, slug, up, workspace};
|
||||
|
||||
pub type R<T> = Result<T, String>;
|
||||
|
||||
/// A spec module's default export as JSON: the raea CLI's spec_json, which runs it on the engine.
|
||||
pub type Eval = fn(&Path) -> R<String>;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,37 +0,0 @@
|
||||
//! Spec modules as raea writes them: a value as a TypeScript literal, and whole numbers kept whole.
|
||||
/// A value as a TypeScript literal for a spec module: unquoted keys where they can be, nulls and empty lists left out.
|
||||
pub fn ts_literal(v: &serde_json::Value, indent: usize) -> String {
|
||||
use serde_json::Value;
|
||||
let (pad, end) = (" ".repeat(indent + 1), " ".repeat(indent));
|
||||
match v {
|
||||
Value::Array(a) if a.iter().all(Value::is_string) && v.to_string().len() < 70 => format!("[{}]", a.iter().map(Value::to_string).collect::<Vec<_>>().join(", ")),
|
||||
Value::Array(a) => format!("[\n{}{end}]", a.iter().map(|x| format!("{pad}{},\n", ts_literal(x, indent + 1))).collect::<String>()),
|
||||
Value::Object(o) => {
|
||||
let ident = |k: &str| k.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
|
||||
let kept = o.iter().filter(|(_, x)| !x.is_null() && !x.as_array().is_some_and(Vec::is_empty));
|
||||
let body: String = kept.map(|(k, x)| format!("{pad}{}: {},\n", if ident(k) { k.clone() } else { Value::String(k.clone()).to_string() }, ts_literal(x, indent + 1))).collect();
|
||||
format!("{{\n{body}{end}}}")
|
||||
}
|
||||
v => tidy(v).to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A number that's whole (as f64 values from Rust are, 45.0) written as an integer.
|
||||
pub fn tidy(v: &serde_json::Value) -> serde_json::Value {
|
||||
match v.as_f64() {
|
||||
Some(n) if v.is_f64() && n.fract() == 0.0 && n.abs() < 1e15 => serde_json::Value::from(n as i64),
|
||||
_ => match v {
|
||||
serde_json::Value::Array(a) => serde_json::Value::Array(a.iter().map(tidy).collect()),
|
||||
v => v.clone(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// `tidy` through a whole value: objects and arrays too.
|
||||
pub fn tidy_deep(v: &serde_json::Value) -> serde_json::Value {
|
||||
match v {
|
||||
serde_json::Value::Object(o) => serde_json::Value::Object(o.iter().filter(|(_, x)| !x.is_null()).map(|(k, x)| (k.clone(), tidy_deep(x))).collect()),
|
||||
serde_json::Value::Array(a) => serde_json::Value::Array(a.iter().map(tidy_deep).collect()),
|
||||
v => tidy(v),
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,9 @@
|
||||
//! A project's compositions, components and controllers (docs/projects.feature PJ8): raea-app-registry's reading of
|
||||
//! its files, with the project's controller overrides from .raea/project checked against the controllers there.
|
||||
//! A project's compositions and components (docs/projects.feature PJ8): raea-app-registry's reading of its files.
|
||||
use std::path::Path;
|
||||
|
||||
use crate::Eval;
|
||||
pub use raea_app_registry::{Component, Composition, Controller, Fix, How, Level, Lint, Prop, Registry, apply};
|
||||
pub use raea_app_registry::{Component, Composition, Fix, How, Level, Lint, Prop, Registry, apply, scan};
|
||||
|
||||
/// The folder's registry.
|
||||
pub fn scan(dir: &Path) -> Registry {
|
||||
let ids: Vec<String> = crate::controllers::overrides(dir).into_iter().filter_map(|(path, _)| path.split('.').next().map(str::to_string)).collect();
|
||||
raea_app_registry::scan(dir, &ids)
|
||||
}
|
||||
|
||||
/// What `raea context` reads of the workspace, as (section, text): its controllers with this project's overrides, and
|
||||
/// the project's compositions, components and controllers as raea reads them.
|
||||
pub fn context(from: &Path, eval: Eval) -> Vec<(String, String)> {
|
||||
let mut out = Vec::new();
|
||||
if let Some(text) = crate::summary(from, eval) {
|
||||
out.push(("CONTROLLERS (raea controller ls; a project's own values marked)".to_string(), text));
|
||||
}
|
||||
if let Some(dir) = crate::doctor::registry_dir(from) {
|
||||
out.push(("PROJECT FILES (raea project scan)".to_string(), scan(&dir).summary()));
|
||||
}
|
||||
out
|
||||
/// What `raea context` reads of the project, as (section, text): its compositions and components as raea reads them.
|
||||
pub fn context(from: &Path) -> Vec<(String, String)> {
|
||||
crate::doctor::registry_dir(from).map(|dir| ("PROJECT FILES (raea project scan)".to_string(), scan(&dir).summary())).into_iter().collect()
|
||||
}
|
||||
@@ -6,20 +6,6 @@ fn a_name_is_its_folder() {
|
||||
assert_eq!(slug(" CJ / Reel 2 "), "cj-reel-2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spec_module_is_tidy_typescript() {
|
||||
// keys unquoted where they can be, nulls and empty lists left out, whole numbers whole, short string lists inline
|
||||
let v = json!({"id": "delivery", "help": null, "tags": [], "n": 45.0, "options": ["9:16", "16:9"], "odd-key": 1});
|
||||
// the keys' order is serde_json's: sorted on its own, as written when a crate built alongside turns on
|
||||
// preserve_order (raea-cli does), so the lines are held as a set (#90)
|
||||
fn lines(s: &str) -> Vec<&str> {
|
||||
let mut l: Vec<&str> = s.lines().collect();
|
||||
l.sort_unstable();
|
||||
l
|
||||
}
|
||||
assert_eq!(lines(&ts_literal(&v, 0)), lines("{\n id: \"delivery\",\n n: 45,\n \"odd-key\": 1,\n options: [\"9:16\", \"16:9\"],\n}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn up_finds_the_nearest_marker() {
|
||||
let root = dunce::canonicalize(std::env::temp_dir()).unwrap().join(format!("raea-ws-up-{}", std::process::id()));
|
||||
@@ -95,15 +81,19 @@ fn doctor_connects_a_projects_files() {
|
||||
std::fs::create_dir_all(d.join(".raea")).unwrap();
|
||||
std::fs::write(d.join(".raea/project"), "").unwrap();
|
||||
std::fs::write(d.join("loose.tsx"), "export const Loose = () => null;\n").unwrap();
|
||||
std::fs::write(d.join("pace.ts"), "import { controller } from \"raea/brief\";\nexport default controller({ title: \"Pace\", fields: {} });\n").unwrap();
|
||||
std::fs::create_dir_all(d.join("controllers")).unwrap();
|
||||
std::fs::write(d.join("controllers/pace.ts"), "import { controller } from \"raea/brief\";\nexport default controller({ title: \"Pace\", fields: {} });\n").unwrap();
|
||||
std::fs::write(d.join("brief.ts"), "import { brief } from \"raea/brief\";\nexport default brief({\n title: \"Old\",\n stages: [{ name: \"\", tasks: [{ text: \"Write the plan\" }] }],\n});\n").unwrap();
|
||||
let found = doctor::registry_findings(&d);
|
||||
let says: Vec<&String> = found.iter().map(|f| &f.says).collect();
|
||||
assert_eq!(found.len(), 2, "{says:?}");
|
||||
assert_eq!(found.len(), 1, "{says:?}");
|
||||
assert!(says[0].contains("loose.tsx:1: isn't a composition") && !found[0].fixable(), "{says:?}");
|
||||
assert!(says[1].contains("pace.ts:2: a controller outside controllers/") && found[1].fixable(), "{says:?}");
|
||||
// a controller from before 11-20 is told where its parts go, and kept
|
||||
let out = doctor::doctor(&["--fix".into(), d.display().to_string()], &[], "0.0.1", &|_| Ok(String::new())).unwrap();
|
||||
assert!(out.starts_with("APPLIED 3 of 4 fixed") && out.contains("fixed ") && d.join("controllers/pace.ts").is_file() && !d.join("pace.ts").exists(), "{out}");
|
||||
assert_eq!(doctor::registry_findings(&d).len(), 1, "only the loose file is left");
|
||||
assert!(out.starts_with("APPLIED 2 of 5 fixed") && out.contains("controllers/pace.ts: a controller, which raea no longer reads") && out.contains("taste.ts"), "{out}");
|
||||
// a brief's old tasks are said to belong in plan.org (docs/plan.feature PL8a), and kept
|
||||
assert!(out.contains("brief.ts: keeps tasks in `stages`") && out.contains("plan.org"), "{out}");
|
||||
assert!(d.join("controllers/pace.ts").is_file() && std::fs::read_to_string(d.join("brief.ts")).unwrap().contains("stages"), "nothing of the person's is deleted");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
|
||||
@@ -98,8 +98,8 @@ fn words(args: &[String]) -> Vec<&str> {
|
||||
raea_app_check::words(args, &["--layout", "--storage", "--name", "--remote"])
|
||||
}
|
||||
|
||||
// a name as a folder (slug), and the nearest folder holding a marker (up): the registry's, which reads controller ids
|
||||
// and projects with them
|
||||
// a name as a folder (slug), and the nearest folder holding a marker (up): the registry's, which reads projects with
|
||||
// them
|
||||
pub use raea_app_registry::{slug, up};
|
||||
|
||||
/// A new id: the prefix and eight hex digits from the clock and the process.
|
||||
@@ -188,10 +188,10 @@ pub(crate) fn commit(repo: &Path, paths: &[&str], what: &str) -> R<()> {
|
||||
git(repo, &["commit", "-q", "-m", &format!("raea: {what}"), "--"]).map(|_| ())
|
||||
}
|
||||
|
||||
const AGENTS_PROJECT: &str = "# Agents\n\nRun `raea context .` here before any work: the taste, this project's brief.ts and script.ts, its look and the guides\nits modes need, in the order to read them. Specs are TypeScript (`export default brief({...})` from \"raea/brief\").\n\nWhere files go (docs/layout.feature):\n\n- compositions/: what renders, a registerRoot <Composition> or a default export; versions are NAME-v2.tsx\n- components/: what compositions import; every prop is a component whose props animate it\n- controllers/: this project's controllers, over the workspace's shared ones by id\n- assets/: media in (footage, stills, audio, models, fonts) and the brand kit in assets/brand/\n- artifacts/: the small React apps posted to the feed\n- out/: renders\n\nThe workspace's shared/ holds the same five folders for every project: import them as\n`@shared/components/desk`, never by a relative path out of this folder.\n";
|
||||
const AGENTS_PROJECT: &str = "# Agents\n\nRun `raea context .` here before any work: the taste, this project's brief.ts and script.ts, its look and the guides\nits modes need, in the order to read them. Specs are TypeScript (`export default brief({...})` from \"raea/brief\").\n\nWhere files go (docs/layout.feature):\n\n- compositions/: what renders, a registerRoot <Composition> or a default export; versions are NAME-v2.tsx\n- components/: what compositions import; every prop is a component whose props animate it\n- assets/: media in (footage, stills, audio, models, fonts) and the brand kit in assets/brand/\n- artifacts/: the small React apps posted to the feed\n- out/: renders\n\nThe workspace's shared/ holds the same five folders for every project: import them as\n`@shared/components/desk`, never by a relative path out of this folder.\n";
|
||||
|
||||
/// The kinds of file a project, and the workspace's shared/, keep a folder each for (docs/layout.feature).
|
||||
pub const KINDS: [&str; 5] = ["compositions", "components", "controllers", "assets", "artifacts"];
|
||||
pub const KINDS: [&str; 4] = ["compositions", "components", "assets", "artifacts"];
|
||||
|
||||
/// LFS for media in and renders out, at any depth: in each project and in shared/ (a pattern with a slash is anchored to
|
||||
/// the workspace root, so the old media/** never matched a project's media/)
|
||||
@@ -362,7 +362,7 @@ pub fn project(args: &[String]) -> R<String> {
|
||||
Some("new") => new_project(w.get(1).ok_or(USAGE)?, flag(args, "--storage")),
|
||||
Some("split") => storage::split(w.get(1).ok_or(USAGE)?, flag(args, "--remote")),
|
||||
Some("join") => storage::join(w.get(1).ok_or(USAGE)?),
|
||||
// PJ8: the folder's compositions, components and controllers, and what isn't connected
|
||||
// PJ8: the folder's compositions and components, and what isn't connected
|
||||
Some("scan") => {
|
||||
let dir = w.get(1).map(PathBuf::from).map_or_else(|| std::env::current_dir().map_err(|e| e.to_string()), Ok)?;
|
||||
let r = crate::registry::scan(&dir);
|
||||
@@ -428,17 +428,12 @@ fn show_project(json_out: bool) -> R<String> {
|
||||
let dir = up(&here, ".raea/project").ok_or("not in a project: raea project new NAME (in a workspace) makes one")?;
|
||||
let file = dir.join(".raea/project");
|
||||
let ws = up(&dir, ".raea/workspace").filter(|w| *w != dir);
|
||||
let overrides: Vec<(String, String)> = all(&file).into_iter().filter(|(k, _)| k.starts_with("controller.")).collect();
|
||||
if json_out {
|
||||
let o: serde_json::Map<String, serde_json::Value> = overrides.iter().map(|(k, v)| (k.trim_start_matches("controller.").to_string(), json!(v))).collect();
|
||||
return Ok(json!({"path": dir, "id": get(&file, "project.id"), "name": get(&file, "project.name"), "workspace": ws, "controllers": o}).to_string());
|
||||
return Ok(json!({"path": dir, "id": get(&file, "project.id"), "name": get(&file, "project.name"), "workspace": ws}).to_string());
|
||||
}
|
||||
let mut out = format!("{} ({})\n{}\n", get(&file, "project.name").unwrap_or_default(), get(&file, "project.id").unwrap_or_default(), dir.display());
|
||||
if let Some(ws) = &ws {
|
||||
out.push_str(&format!("in workspace {}\n", ws.display()));
|
||||
}
|
||||
for (k, v) in overrides {
|
||||
out.push_str(&format!(" {} = {v}\n", k.trim_start_matches("controller.")));
|
||||
}
|
||||
Ok(out.trim_end().to_string())
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
// The proof project's rules (docs/direction.feature DR4): each a rule field naming the check that holds it, a .ts
|
||||
// check by its path from here, with its values. `raea check FILE.tsx --only ID` runs one.
|
||||
import { controller } from "raea/brief";
|
||||
|
||||
export default controller({
|
||||
title: "Proof rules",
|
||||
groups: [
|
||||
{
|
||||
title: "What the pieces are held to",
|
||||
fields: [
|
||||
{ label: "Sung lines are flat 2D type, inside the frame, behind the subject", type: "rule", check: "../checks/lyric.ts" },
|
||||
{ label: "Cuts land on a word's end", type: "rule", check: "../checks/cut.ts" },
|
||||
{ label: "Cues are heard where they are placed", type: "rule", check: "../checks/cue.ts" },
|
||||
{ label: "Captions clear the button band", type: "rule", check: "../checks/caption.ts", values: { band: 0.8 } },
|
||||
{ label: "The rider turns with its seat and is in no part of it", type: "rule", check: "../checks/rider.ts", values: { rider: "rider", seat: "seat" } },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -1,8 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
# DR4's proof (docs/direction.feature): five checks written as systems over the world (checks/*.ts, none importing
|
||||
# Bevy), each run by `raea check` on a piece that holds it and on a cheat that must fail it, and a taste line run as
|
||||
# the named check of its form beside them. Its media are made here with ffmpeg (nothing downloaded); the two pieces
|
||||
# whose checks need a render are rendered first. Every case runs in a copy, so the bench folder stays clean.
|
||||
# Bevy), each a line in the project's taste.ts run by `raea check` on a piece that holds it and on a cheat that must
|
||||
# fail it, and a taste line run as the named check of its form beside them. Its media are made here with ffmpeg
|
||||
# (nothing downloaded); the two pieces whose checks need a render are rendered first. Every case runs in a copy, so the
|
||||
# bench folder stays clean.
|
||||
#
|
||||
# RAEA_BIN=path/to/raea bash bench/direction/proof/proof.sh
|
||||
set -uo pipefail
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// DR4's proof, the 3D scene as asked: a seat turning, and a rider on it that turns with it and sits forward, clear of
|
||||
// the back (seat.tsx). checks/rider.ts holds it, with the parts named in controllers/rules.ts.
|
||||
// the back (seat.tsx). checks/rider.ts holds it, with the parts named in taste.ts.
|
||||
import { Composition, registerRoot, useCurrentFrame } from "raea";
|
||||
import { Seat } from "./seat";
|
||||
|
||||
|
||||
@@ -1,8 +1,21 @@
|
||||
// The proof's taste (passed with --taste): one line raea measures, run as the named check of its form (text-above)
|
||||
// beside the project's own checks.
|
||||
// The proof project's taste (docs/direction.feature DR4): its rules, each a line with the check that holds it. A .ts
|
||||
// check by its path from here, with its values, or one of raea's forms (text-above), which the two taste cases pass
|
||||
// with --taste. `raea check FILE.tsx --only ID` runs one.
|
||||
import { taste } from "raea/brief";
|
||||
|
||||
export default taste({
|
||||
title: "Proof taste",
|
||||
sections: [{ heading: "Text", rules: [{ text: "Captions sit above three quarters of the frame.", check: { form: "text-above", value: 75 } }] }],
|
||||
sections: [
|
||||
{
|
||||
heading: "What the pieces are held to",
|
||||
rules: [
|
||||
{ text: "Sung lines are flat 2D type, inside the frame, behind the subject", check: "checks/lyric.ts" },
|
||||
{ text: "Cuts land on a word's end", check: "checks/cut.ts" },
|
||||
{ text: "Cues are heard where they are placed", check: "checks/cue.ts" },
|
||||
{ text: "Captions clear the button band", check: "checks/caption.ts", values: { band: 0.8 } },
|
||||
{ text: "The rider turns with its seat and is in no part of it", check: "checks/rider.ts", values: { rider: "rider", seat: "seat" } },
|
||||
],
|
||||
},
|
||||
{ heading: "Text", rules: [{ text: "Captions sit above three quarters of the frame.", check: { form: "text-above", value: 75 } }] },
|
||||
],
|
||||
});
|
||||
Executable
+37
@@ -0,0 +1,37 @@
|
||||
#!/bin/bash
|
||||
# #125: a 2160x3840 page with many filtered elements draws, as Chrome draws it.
|
||||
# squares.tsx: twelve blurred full-frame wrappers, each around a 200 px square (the issue's repro, two rows). Each
|
||||
# filter's layer is what its element draws, not its box, so all twelve fit; each square's middle is white and the
|
||||
# page between them #333.
|
||||
# frames.tsx: ten full-frame filtered layers whose boxes draw, so each is a frame-sized image: the atlas grows to the
|
||||
# device's largest texture (16384 on Apple silicon). The page's middle is 184 (nine layers would be 176).
|
||||
# Either refused ("has no room for them") is a failure. Exits 1 on one.
|
||||
# bench/filter-atlas/check.sh (RAEA_BIN: the raea to run, default target/release/raea)
|
||||
cd "$(dirname "$0")/../.." || exit 2
|
||||
BIN=${RAEA_BIN:-$PWD/target/release/raea}
|
||||
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0
|
||||
OUT=$(mktemp -d "${TMPDIR:-/tmp}/raea-filter-atlas.XXXXXX")
|
||||
trap 'rm -rf "${OUT:?}"' EXIT
|
||||
status=0
|
||||
for c in squares frames; do
|
||||
mkdir -p "$OUT/$c"
|
||||
if ! "$BIN" render bench/filter-atlas/$c.tsx --at 0 -o "$OUT/$c" > "$OUT/$c.log" 2>&1 || [ ! -f "$OUT/$c/frame-00000.png" ]; then
|
||||
echo "FAIL $c.tsx: $(grep -m1 -E 'REFUSED|error' "$OUT/$c.log" | cut -c1-220)"; status=1
|
||||
fi
|
||||
done
|
||||
grey() { # FRAME X,Y: the pixel's red channel, 0-255
|
||||
magick "$OUT/$1/frame-00000.png" -alpha off -format "%[fx:int(255*p{$2}.r+0.5)]" info:
|
||||
}
|
||||
near() { # GOT WANT WHAT
|
||||
(( $1 - $2 <= 3 && $2 - $1 <= 3 )) || { echo "FAIL $3: $1, wanted $2"; status=1; }
|
||||
}
|
||||
if [ -f "$OUT/squares/frame-00000.png" ]; then
|
||||
for i in $(seq 0 11); do
|
||||
x=$((200 + (i % 6) * 340)); y=$((1600 + i / 6 * 500))
|
||||
near "$(grey squares $x,$y)" 255 "squares.tsx: square $i's middle ($x,$y)"
|
||||
done
|
||||
near "$(grey squares 1080,3000)" 51 "squares.tsx: the page below the squares"
|
||||
fi
|
||||
[ -f "$OUT/frames/frame-00000.png" ] && near "$(grey frames 1080,1920)" 184 "frames.tsx: ten white layers at 10% over #333"
|
||||
[ $status = 0 ] && echo "PASS a 2160x3840 page of twelve blurred wrappers and ten frame-sized filtered layers draws"
|
||||
exit $status
|
||||
@@ -0,0 +1,16 @@
|
||||
// #125: ten full-frame layers at 2160x3840 whose own boxes draw (a white background at 10%), each under a filter that
|
||||
// leaves white as it is. Each is an image the size of the frame in Vello's atlas: 8192 px a side holds six, the
|
||||
// device's largest texture (16384 on Apple silicon) holds 28. Over #333 the ten make 255 - 204 * 0.9^10 = 184; nine
|
||||
// would be 176. bench/filter-atlas/check.sh
|
||||
import { AbsoluteFill, Composition, registerRoot } from "raea";
|
||||
const N = 10;
|
||||
function C() {
|
||||
return (
|
||||
<AbsoluteFill style={{ background: "#333" }}>
|
||||
{Array.from({ length: N }, (_, i) => (
|
||||
<AbsoluteFill key={i} style={{ filter: "grayscale(1)", background: "rgba(255, 255, 255, 0.1)" }} />
|
||||
))}
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
registerRoot(() => <Composition id="frames" component={C} width={2160} height={3840} fps={30} durationInFrames={1} />);
|
||||
@@ -0,0 +1,18 @@
|
||||
// #125: twelve full-frame wrappers at 2160x3840, each blurred and each around a 200 px white square. A wrapper's box
|
||||
// draws nothing, so its filter's layer is the square grown by the blur's reach, as Chrome sizes a filter's input. Made
|
||||
// from the wrapper's box, each layer was a frame-sized image, Vello's atlas held six and the frame was refused from the
|
||||
// seventh. bench/filter-atlas/check.sh
|
||||
import { AbsoluteFill, Composition, registerRoot } from "raea";
|
||||
const N = 12;
|
||||
function C() {
|
||||
return (
|
||||
<AbsoluteFill style={{ background: "#333" }}>
|
||||
{Array.from({ length: N }, (_, i) => (
|
||||
<AbsoluteFill key={i} style={{ filter: "blur(4px)" }}>
|
||||
<div style={{ position: "absolute", left: 100 + (i % 6) * 340, top: 1500 + Math.floor(i / 6) * 500, width: 200, height: 200, background: "white" }} />
|
||||
</AbsoluteFill>
|
||||
))}
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
registerRoot(() => <Composition id="squares" component={C} width={2160} height={3840} fps={30} durationInFrames={1} />);
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "raea-lightbench"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "LightBench: a small Rust + Bevy renderer that proves lighting and geometry techniques against its own all-lights reference before they move into raea (docs/lightbench.feature)"
|
||||
|
||||
[[bin]]
|
||||
name = "lightbench"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
# bench/bevy-parity's Bevy (engine/render's features, and winit for the window), so it builds against the Bevy raea compiled
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "default_font", "system_font_discovery", "ghost_nodes", "multi_threaded", "3d_bevy_render", "ui_bevy_render", "png", "jpeg", "tonemapping_luts", "ktx2", "zstd_rust", "smaa_luts", "experimental_pbr_pcss", "area_light_luts", "dfg_lut", "bluenoise_texture", "bevy_gilrs", "bevy_winit", "bevy_scene", "bevy_camera_controller", "free_camera", "pan_camera", "pan_orbit_camera", "bevy_gizmos", "bevy_gizmos_render", "bevy_state", "picking", "mesh_picking", "sprite_picking", "ui_picking", "hdr", "exr", "webp", "bevy_dev_tools", "bevy_ui_widgets", "bevy_feathers", "bevy_audio", "vorbis", "wav", "mp3", "morph_animation", "bevy_input_focus", "custom_cursor", "serialize", "reflect_functions", "pbr_multi_layer_material_textures"] }
|
||||
bytemuck = { version = "1.25", features = ["derive"] }
|
||||
# meshoptimizer (MIT): the simplifier and clusterizer behind the LODs and the cluster hierarchy
|
||||
meshopt = "0.6.2"
|
||||
# Bevy's wgpu, for the lighting pass's timestamp queries
|
||||
wgpu = "=30.0.1"
|
||||
@@ -0,0 +1,312 @@
|
||||
//! The scene's triangles in one BVH, built once on the CPU (binned SAH) and flattened depth-first for the GPU's shadow
|
||||
//! rays: an inner node's left child is the next node and its right child is at `a`; a leaf holds `count` triangles
|
||||
//! from `a`. Every triangle is in it, the ones off screen too, so a caster the camera can't see still casts.
|
||||
|
||||
use bevy::math::Vec3;
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Pod, Zeroable, Default, Debug)]
|
||||
pub struct Node {
|
||||
pub min: [f32; 3],
|
||||
pub a: u32,
|
||||
pub max: [f32; 3],
|
||||
pub count: u32,
|
||||
}
|
||||
|
||||
/// A triangle as the GPU tests it: v0, v1 - v0 and v2 - v0, each padded to a vec4 whose w holds the triangle's
|
||||
/// albedo (linear r, g, b), so a bounce ray knows the colour of what it hits.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Pod, Zeroable, Default, Debug)]
|
||||
pub struct Tri {
|
||||
pub v0: [f32; 4],
|
||||
pub e1: [f32; 4],
|
||||
pub e2: [f32; 4],
|
||||
}
|
||||
|
||||
pub struct Bvh {
|
||||
pub nodes: Vec<Node>,
|
||||
pub tris: Vec<Tri>,
|
||||
}
|
||||
|
||||
const LEAF: usize = 4;
|
||||
const BINS: usize = 16;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Aabb {
|
||||
min: Vec3,
|
||||
max: Vec3,
|
||||
}
|
||||
|
||||
impl Aabb {
|
||||
const EMPTY: Self = Self { min: Vec3::INFINITY, max: Vec3::NEG_INFINITY };
|
||||
fn grow(&mut self, p: Vec3) {
|
||||
self.min = self.min.min(p);
|
||||
self.max = self.max.max(p);
|
||||
}
|
||||
/// The bin of BINS a centre falls in along an axis of this box (the centres' box)
|
||||
fn bin(&self, c: Vec3, axis: usize) -> usize {
|
||||
(((c[axis] - self.min[axis]) / (self.max[axis] - self.min[axis]) * BINS as f32) as usize).min(BINS - 1)
|
||||
}
|
||||
fn join(&mut self, b: &Aabb) {
|
||||
self.min = self.min.min(b.min);
|
||||
self.max = self.max.max(b.max);
|
||||
}
|
||||
fn area(&self) -> f32 {
|
||||
let d = (self.max - self.min).max(Vec3::ZERO);
|
||||
2.0 * (d.x * d.y + d.y * d.z + d.z * d.x)
|
||||
}
|
||||
}
|
||||
|
||||
/// The BVH over `tris`, each with its albedo (`albedo` one a triangle, or empty for black).
|
||||
pub fn build(tris: &[[Vec3; 3]], albedo: &[Vec3]) -> Bvh {
|
||||
let boxes: Vec<Aabb> = tris
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let mut b = Aabb::EMPTY;
|
||||
t.iter().for_each(|p| b.grow(*p));
|
||||
b
|
||||
})
|
||||
.collect();
|
||||
let cents: Vec<Vec3> = boxes.iter().map(|b| (b.min + b.max) * 0.5).collect();
|
||||
let mut idx: Vec<u32> = (0..tris.len() as u32).collect();
|
||||
let mut nodes = Vec::with_capacity(tris.len() / 2 + 1);
|
||||
split(&boxes, ¢s, &mut idx, 0, tris.len(), &mut nodes);
|
||||
let tris = idx
|
||||
.iter()
|
||||
.map(|&i| {
|
||||
let [a, b, c] = tris[i as usize];
|
||||
let k = albedo.get(i as usize).copied().unwrap_or(Vec3::ZERO);
|
||||
Tri { v0: a.extend(k.x).into(), e1: (b - a).extend(k.y).into(), e2: (c - a).extend(k.z).into() }
|
||||
})
|
||||
.collect();
|
||||
Bvh { nodes, tris }
|
||||
}
|
||||
|
||||
/// Builds the node for idx[lo..hi] and its subtree; returns its index.
|
||||
fn split(boxes: &[Aabb], cents: &[Vec3], idx: &mut [u32], lo: usize, hi: usize, nodes: &mut Vec<Node>) -> usize {
|
||||
let me = nodes.len();
|
||||
nodes.push(Node::default());
|
||||
let (mut bounds, mut cb) = (Aabb::EMPTY, Aabb::EMPTY);
|
||||
for &i in &idx[lo..hi] {
|
||||
bounds.join(&boxes[i as usize]);
|
||||
cb.grow(cents[i as usize]);
|
||||
}
|
||||
nodes[me].min = bounds.min.into();
|
||||
nodes[me].max = bounds.max.into();
|
||||
let n = hi - lo;
|
||||
let leaf = |nodes: &mut Vec<Node>| {
|
||||
nodes[me].a = lo as u32;
|
||||
nodes[me].count = n as u32;
|
||||
me
|
||||
};
|
||||
if n <= LEAF {
|
||||
return leaf(nodes);
|
||||
}
|
||||
// the cheapest of BINS-1 planes on each axis by the surface area heuristic
|
||||
let ext = cb.max - cb.min;
|
||||
let mut best = (f32::INFINITY, 0usize, 0usize);
|
||||
for axis in 0..3 {
|
||||
if ext[axis] <= 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let mut bins = [(Aabb::EMPTY, 0usize); BINS];
|
||||
for &i in &idx[lo..hi] {
|
||||
let b = &mut bins[cb.bin(cents[i as usize], axis)];
|
||||
b.0.join(&boxes[i as usize]);
|
||||
b.1 += 1;
|
||||
}
|
||||
let mut right = [(0.0f32, 0usize); BINS];
|
||||
let (mut acc, mut cnt) = (Aabb::EMPTY, 0);
|
||||
for s in (1..BINS).rev() {
|
||||
acc.join(&bins[s].0);
|
||||
cnt += bins[s].1;
|
||||
right[s] = (acc.area(), cnt);
|
||||
}
|
||||
let (mut acc, mut cnt) = (Aabb::EMPTY, 0);
|
||||
for s in 1..BINS {
|
||||
acc.join(&bins[s - 1].0);
|
||||
cnt += bins[s - 1].1;
|
||||
if cnt == 0 || right[s].1 == 0 {
|
||||
continue;
|
||||
}
|
||||
let cost = acc.area() * cnt as f32 + right[s].0 * right[s].1 as f32;
|
||||
if cost < best.0 {
|
||||
best = (cost, axis, s);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut mid = lo;
|
||||
if best.0.is_finite() {
|
||||
let (axis, s) = (best.1, best.2);
|
||||
for k in lo..hi {
|
||||
if cb.bin(cents[idx[k] as usize], axis) < s {
|
||||
idx.swap(k, mid);
|
||||
mid += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if mid == lo || mid == hi {
|
||||
// centroids all in one place: halve by index
|
||||
mid = lo + n / 2;
|
||||
}
|
||||
split(boxes, cents, idx, lo, mid, nodes);
|
||||
let right = split(boxes, cents, idx, mid, hi, nodes);
|
||||
nodes[me].a = right as u32;
|
||||
nodes[me].count = 0;
|
||||
me
|
||||
}
|
||||
|
||||
impl Bvh {
|
||||
/// Whether anything lies on the ray from `o` along unit `d` before `tmax`: the shader's `occluded`, on the CPU.
|
||||
pub fn occluded(&self, o: Vec3, d: Vec3, tmax: f32) -> bool {
|
||||
let inv = Vec3::ONE / d.map(|c| if c.abs() < 1e-12 { 1e-12 } else { c });
|
||||
let mut stack = Vec::with_capacity(64);
|
||||
let mut i = 0usize;
|
||||
loop {
|
||||
let n = &self.nodes[i];
|
||||
if hit_box(o, inv, n.min.into(), n.max.into(), tmax) {
|
||||
if n.count > 0 {
|
||||
let t = &self.tris[n.a as usize..(n.a + n.count) as usize];
|
||||
if t.iter().any(|t| hit_tri(o, d, t, tmax)) {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
stack.push(n.a as usize);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
match stack.pop() {
|
||||
Some(j) => i = j,
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The nearest triangle on the ray before `tmax`, and how far: the shader's `closest`, on the CPU.
|
||||
pub fn closest(&self, o: Vec3, d: Vec3, tmax: f32) -> Option<(f32, usize)> {
|
||||
let inv = Vec3::ONE / d.map(|c| if c.abs() < 1e-12 { 1e-12 } else { c });
|
||||
let mut stack = Vec::with_capacity(64);
|
||||
let (mut best, mut i) = (None, 0usize);
|
||||
let mut far = tmax;
|
||||
loop {
|
||||
let n = &self.nodes[i];
|
||||
if hit_box(o, inv, n.min.into(), n.max.into(), far) {
|
||||
if n.count > 0 {
|
||||
for k in n.a as usize..(n.a + n.count) as usize {
|
||||
let t = tri_t(o, d, &self.tris[k]);
|
||||
if t < far {
|
||||
(far, best) = (t, Some((t, k)));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
stack.push(n.a as usize);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
match stack.pop() {
|
||||
Some(j) => i = j,
|
||||
None => return best,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The deepest leaf's depth: the GPU's traversal stack must hold it.
|
||||
pub fn depth(&self) -> usize {
|
||||
fn go(b: &Bvh, i: usize) -> usize {
|
||||
let n = &b.nodes[i];
|
||||
if n.count > 0 { 1 } else { 1 + go(b, i + 1).max(go(b, n.a as usize)) }
|
||||
}
|
||||
go(self, 0)
|
||||
}
|
||||
}
|
||||
|
||||
fn hit_box(o: Vec3, inv: Vec3, min: Vec3, max: Vec3, tmax: f32) -> bool {
|
||||
let (t0, t1) = ((min - o) * inv, (max - o) * inv);
|
||||
let near = t0.min(t1).max_element().max(0.0);
|
||||
let far = t0.max(t1).min_element().min(tmax);
|
||||
near <= far
|
||||
}
|
||||
|
||||
pub fn hit_tri(o: Vec3, d: Vec3, t: &Tri, tmax: f32) -> bool {
|
||||
tri_t(o, d, t) < tmax
|
||||
}
|
||||
|
||||
/// Möller-Trumbore, both sides: how far along the ray the triangle is, infinity if it isn't on it.
|
||||
pub fn tri_t(o: Vec3, d: Vec3, t: &Tri) -> f32 {
|
||||
let (v0, e1, e2) = (Vec3::from_slice(&t.v0[..3]), Vec3::from_slice(&t.e1[..3]), Vec3::from_slice(&t.e2[..3]));
|
||||
let pv = d.cross(e2);
|
||||
let det = e1.dot(pv);
|
||||
if det.abs() < 1e-12 {
|
||||
return f32::INFINITY;
|
||||
}
|
||||
let inv = 1.0 / det;
|
||||
let tv = o - v0;
|
||||
let u = tv.dot(pv) * inv;
|
||||
if !(0.0..=1.0).contains(&u) {
|
||||
return f32::INFINITY;
|
||||
}
|
||||
let qv = tv.cross(e1);
|
||||
let v = d.dot(qv) * inv;
|
||||
if v < 0.0 || u + v > 1.0 {
|
||||
return f32::INFINITY;
|
||||
}
|
||||
let t = e2.dot(qv) * inv;
|
||||
if t > 0.0 { t } else { f32::INFINITY }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
struct Lcg(u64);
|
||||
impl Lcg {
|
||||
fn f(&mut self) -> f32 {
|
||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
(self.0 >> 40) as f32 / (1u64 << 24) as f32
|
||||
}
|
||||
fn v(&mut self, s: f32) -> Vec3 {
|
||||
Vec3::new(self.f(), self.f(), self.f()) * 2.0 * s - s
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bvh_answers_as_every_triangle_does() {
|
||||
let mut r = Lcg(7);
|
||||
let soup: Vec<[Vec3; 3]> = (0..3000)
|
||||
.map(|_| {
|
||||
let c = r.v(5.0);
|
||||
[c + r.v(0.4), c + r.v(0.4), c + r.v(0.4)]
|
||||
})
|
||||
.collect();
|
||||
let bvh = build(&soup, &[]);
|
||||
let all: Vec<Tri> = build(&soup, &[]).tris;
|
||||
assert_eq!(all.len(), soup.len());
|
||||
let (mut hits, mut n) = (0, 0);
|
||||
for _ in 0..20000 {
|
||||
let o = r.v(6.0);
|
||||
let d = r.v(1.0).normalize_or(Vec3::X);
|
||||
let tmax = r.f() * 12.0;
|
||||
let brute = all.iter().any(|t| hit_tri(o, d, t, tmax));
|
||||
assert_eq!(bvh.occluded(o, d, tmax), brute, "ray {o} {d} {tmax}");
|
||||
// the nearest hit too, as LB5's bounce rays find it
|
||||
let near = all.iter().enumerate().map(|(k, t)| (tri_t(o, d, t), k)).filter(|h| h.0 < tmax).min_by(|a, b| a.0.total_cmp(&b.0));
|
||||
assert_eq!(bvh.closest(o, d, tmax).map(|h| h.1), near.map(|h| h.1), "nearest on ray {o} {d} {tmax}");
|
||||
hits += brute as u32;
|
||||
n += 1;
|
||||
}
|
||||
// both answers turn up, so the test means something
|
||||
assert!(hits > n / 10 && hits < n * 9 / 10, "{hits} of {n} rays hit");
|
||||
assert!(bvh.depth() < 48, "depth {}", bvh.depth());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coincident_triangles_still_split() {
|
||||
let t = [Vec3::ZERO, Vec3::X, Vec3::Y];
|
||||
let bvh = build(&vec![t; 100], &[]);
|
||||
assert!(bvh.occluded(Vec3::new(0.2, 0.2, 1.0), Vec3::NEG_Z, 2.0));
|
||||
assert!(!bvh.occluded(Vec3::new(0.8, 0.8, 1.0), Vec3::NEG_Z, 2.0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
// LightBench's world radiance cache (LB7, joined after light.wgsl and trace.wgsl): a hash table of cells over the
|
||||
// scene's surfaces, each the size of its distance from the camera (base size at 1 m, doubling with each doubling of
|
||||
// distance) and one of six normal directions, holding the irradiance there. A pixel's bounce ray reads the cell it
|
||||
// hits instead of tracing on, and adds a fresh sample to it: that point's direct light plus one more ray, which brings
|
||||
// the next surface's cell; so each frame the cache carries light one bounce further, and a pixel gets every bounce
|
||||
// for the price of two rays. After the pixels, `resolve` folds each cell's samples into its light and frees cells no
|
||||
// ray has touched for a while. The idea of NVIDIA's SHaRC and Bevy Solari's world cache.
|
||||
|
||||
// a cell is six words: its key (0 empty), the last frame a ray touched it, then this frame's summed light (r, g, b, in
|
||||
// 1/FIX steps) and how many samples
|
||||
@group(0) @binding(14) var<storage, read_write> cells: array<atomic<u32>>;
|
||||
// each cell's light: irradiance (rgb) and how many samples it holds (w)
|
||||
@group(0) @binding(15) var<storage, read_write> cell_light: array<vec4<f32>>;
|
||||
|
||||
const CELLS: u32 = 262144u;
|
||||
const WORDS: u32 = 6u;
|
||||
const FIX: f32 = 256.0;
|
||||
// a sample brighter than this is clipped as it goes in (a light right against a surface), so a sum can't overflow
|
||||
const CELL_MAX: f32 = 64.0;
|
||||
// frames a cell lives without a ray touching it
|
||||
const CELL_LIFE: u32 = 120u;
|
||||
|
||||
// the cell at a point: (where its probe starts, its key; never 0)
|
||||
fn cell_key(pos: vec3<f32>, n: vec3<f32>) -> vec2<u32> {
|
||||
let level = u32(clamp(ceil(log2(max(length(pos - p.eye.xyz), 1.0))), 0.0, 15.0));
|
||||
let q = bitcast<vec3<u32>>(vec3<i32>(floor(pos / (p.cache.x * exp2(f32(level))))));
|
||||
let a = abs(n);
|
||||
let axis = select(select(2u, 1u, a.y >= a.z), 0u, a.x >= a.y && a.x >= a.z);
|
||||
let dir = axis * 2u + select(0u, 1u, n[axis] < 0.0);
|
||||
let at = pcg(q.x ^ pcg(q.y ^ pcg(q.z ^ pcg(level * 8u + dir))));
|
||||
let key = pcg(level * 8u + dir + pcg(q.z + pcg(q.y + pcg(q.x + 0x2545f491u)))) | 1u;
|
||||
return vec2(at, key);
|
||||
}
|
||||
|
||||
// the cell's slot, made if `make` and there's room along its probe; CELLS if it has none
|
||||
fn cell(pos: vec3<f32>, n: vec3<f32>, make: bool) -> u32 {
|
||||
let h = cell_key(pos, n);
|
||||
for (var k = 0u; k < 8u; k++) {
|
||||
let i = (h.x + k) % CELLS;
|
||||
var key = atomicLoad(&cells[i * WORDS]);
|
||||
if key == 0u {
|
||||
if !make {
|
||||
return CELLS;
|
||||
}
|
||||
let r = atomicCompareExchangeWeak(&cells[i * WORDS], 0u, h.y);
|
||||
// a weak exchange can fail with the slot still empty: try again next frame rather than probe past it
|
||||
key = select(r.old_value, h.y, r.exchanged);
|
||||
if key == 0u {
|
||||
return CELLS;
|
||||
}
|
||||
}
|
||||
if key == h.y {
|
||||
atomicMax(&cells[i * WORDS + 1u], p.size.w);
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return CELLS;
|
||||
}
|
||||
|
||||
fn cell_add(i: u32, e: vec3<f32>) {
|
||||
let v = vec3<u32>(min(e, vec3(CELL_MAX)) * FIX + 0.5);
|
||||
atomicAdd(&cells[i * WORDS + 2u], v.x);
|
||||
atomicAdd(&cells[i * WORDS + 3u], v.y);
|
||||
atomicAdd(&cells[i * WORDS + 4u], v.z);
|
||||
atomicAdd(&cells[i * WORDS + 5u], 1u);
|
||||
}
|
||||
|
||||
// the nearest surface along d from o: its point, its normal facing the ray, its albedo; w of the first 0 on a miss
|
||||
struct Surface { pos: vec4<f32>, n: vec3<f32>, albedo: vec3<f32> }
|
||||
|
||||
fn surface(o: vec3<f32>, d: vec3<f32>) -> Surface {
|
||||
let h = closest(o, d, 1e4);
|
||||
if h.i == 0xFFFFFFFFu {
|
||||
return Surface(vec4(0.0), vec3(0.0), vec3(0.0));
|
||||
}
|
||||
let v0 = tris[3u * h.i];
|
||||
let e1 = tris[3u * h.i + 1u];
|
||||
let e2 = tris[3u * h.i + 2u];
|
||||
var n = normalize(cross(e1.xyz, e2.xyz));
|
||||
n = select(n, -n, dot(n, d) > 0.0);
|
||||
return Surface(vec4(o + d * h.t, 1.0), n, vec3(v0.w, e1.w, e2.w));
|
||||
}
|
||||
|
||||
// a pixel's bounced light by way of the cache: one ray to the nearest surface, whose cell's light it takes (or the
|
||||
// fresh sample, until the cell holds any); the fresh sample goes into the cell
|
||||
fn cached(n0: vec3<f32>, o0: vec3<f32>) -> vec3<f32> {
|
||||
let s1 = surface(o0, cosine_dir(n0));
|
||||
if s1.pos.w == 0.0 {
|
||||
return PI * p.sky.rgb;
|
||||
}
|
||||
let o1 = s1.pos.xyz + s1.n * (2e-3 + 5e-4 * length(s1.pos.xyz - p.eye.xyz));
|
||||
var e = lit_at(s1.pos.xyz, s1.n, o1, 1u);
|
||||
let s2 = surface(o1, cosine_dir(s1.n));
|
||||
if s2.pos.w == 0.0 {
|
||||
e += PI * p.sky.rgb;
|
||||
} else {
|
||||
let j = cell(s2.pos.xyz, s2.n, false);
|
||||
if j < CELLS {
|
||||
e += s2.albedo * cell_light[j].rgb;
|
||||
}
|
||||
}
|
||||
let i = cell(s1.pos.xyz, s1.n, true);
|
||||
if i == CELLS {
|
||||
return s1.albedo * e;
|
||||
}
|
||||
cell_add(i, e);
|
||||
let held = cell_light[i];
|
||||
return s1.albedo * select(e, held.rgb, held.w > 0.0);
|
||||
}
|
||||
|
||||
// after the pixels: each cell's samples folded into its light (a running mean over at most p.cache.y samples), and a
|
||||
// cell no ray has touched in CELL_LIFE frames freed
|
||||
@compute @workgroup_size(64, 1, 1)
|
||||
fn resolve(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
let i = id.x;
|
||||
if i >= CELLS || atomicLoad(&cells[i * WORDS]) == 0u {
|
||||
return;
|
||||
}
|
||||
let b = i * WORDS;
|
||||
let n = atomicLoad(&cells[b + 5u]);
|
||||
if p.size.w - atomicLoad(&cells[b + 1u]) > CELL_LIFE {
|
||||
atomicStore(&cells[b], 0u);
|
||||
cell_light[i] = vec4(0.0);
|
||||
} else if n > 0u {
|
||||
let mean = vec3(f32(atomicLoad(&cells[b + 2u])), f32(atomicLoad(&cells[b + 3u])), f32(atomicLoad(&cells[b + 4u]))) / (FIX * f32(n));
|
||||
let was = cell_light[i];
|
||||
let held = min(was.w, p.cache.y);
|
||||
cell_light[i] = vec4(mix(was.rgb, mean, f32(n) / (f32(n) + held)), held + f32(n));
|
||||
}
|
||||
for (var k = 2u; k < WORDS; k++) {
|
||||
atomicStore(&cells[b + k], 0u);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! LB2's scene (--scene field): knots receding from the camera, each drawing the clusters of one shared hierarchy
|
||||
//! that its distance and the view ask for (lod.rs), chosen on the CPU each frame and rebuilt into its mesh when the
|
||||
//! choice changes. Instances outside the view are culled. --detail full draws every finest triangle instead, and
|
||||
//! --view lod colours each cluster by its level.
|
||||
|
||||
use crate::{lod, scene, Opts};
|
||||
use bevy::{
|
||||
asset::RenderAssetUsages,
|
||||
mesh::{Indices, PrimitiveTopology},
|
||||
prelude::*,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The hierarchy every knot shares, in the knot's own space.
|
||||
#[derive(Resource)]
|
||||
pub struct Field {
|
||||
pos: Vec<Vec3>,
|
||||
nor: Vec<Vec3>,
|
||||
dag: Arc<Vec<lod::Cluster>>,
|
||||
/// the whole knot's bounds
|
||||
center: Vec3,
|
||||
radius: f32,
|
||||
finest: usize,
|
||||
}
|
||||
|
||||
/// A knot of the field: its mesh, and the clusters it drew last.
|
||||
#[derive(Component)]
|
||||
pub struct Knot {
|
||||
mesh: Handle<Mesh>,
|
||||
drawn: Vec<usize>,
|
||||
}
|
||||
|
||||
/// The knots' colour.
|
||||
pub const COLOUR: Color = Color::srgb(0.85, 0.42, 0.18);
|
||||
|
||||
const LEVEL_COLOURS: [[f32; 3]; 8] = [[1.0, 1.0, 1.0], [0.3, 0.9, 0.3], [0.95, 0.9, 0.2], [1.0, 0.55, 0.1], [0.95, 0.2, 0.2], [0.85, 0.3, 0.9], [0.3, 0.5, 1.0], [0.2, 0.9, 0.9]];
|
||||
|
||||
/// The knots' places: rows from 3 m to about 60 m away, each a little different in size and turn.
|
||||
pub fn places(rows: u32) -> Vec<Transform> {
|
||||
let mut out = Vec::new();
|
||||
for r in 0..rows {
|
||||
let z = 1.0 - (r as f32).powf(1.6) * 2.2;
|
||||
let across = 3 + r / 2;
|
||||
for c in 0..across {
|
||||
let x = (c as f32 - (across - 1) as f32 * 0.5) * (2.6 + r as f32 * 0.35);
|
||||
let k = (r * 31 + c * 17) as f32;
|
||||
let s = 0.3 + 0.25 * (0.5 + 0.5 * (k * 1.7).sin());
|
||||
out.push(Transform::from_xyz(x, s * 3.4, z).with_rotation(Quat::from_rotation_y(k)).with_scale(Vec3::splat(s)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The field's knots: their meshes start as the full knot and the BVH holds every finest triangle of every knot.
|
||||
pub fn spawn(commands: &mut Commands, opts: &Opts, meshes: &mut Assets<Mesh>, mats: &mut Assets<StandardMaterial>, tris: &mut Vec<[Vec3; 3]>) {
|
||||
let (pos, nor, idx) = scene::knot_data(2, 3, opts.detail, opts.detail / 32, 0.33);
|
||||
let t0 = std::time::Instant::now();
|
||||
let dag = lod::dag(&pos, &idx);
|
||||
let levels = dag.iter().map(|c| c.level).max().unwrap_or(0) + 1;
|
||||
info!("lightbench: the knot's hierarchy: {} clusters in {levels} levels from {} triangles, built in {:.0} ms", dag.len(), idx.len() / 3, t0.elapsed().as_secs_f64() * 1000.0);
|
||||
let (mut lo, mut hi) = (Vec3::INFINITY, Vec3::NEG_INFINITY);
|
||||
pos.iter().for_each(|p| {
|
||||
lo = lo.min(*p);
|
||||
hi = hi.max(*p);
|
||||
});
|
||||
let center = (lo + hi) * 0.5;
|
||||
let radius = pos.iter().map(|p| p.distance(center)).fold(0.0, f32::max);
|
||||
let material = mats.add(StandardMaterial { base_color: COLOUR, perceptual_roughness: 0.6, ..default() });
|
||||
let lod_material = mats.add(StandardMaterial { base_color: Color::WHITE, perceptual_roughness: 0.6, ..default() });
|
||||
for at in places(opts.rows) {
|
||||
let m = at.to_matrix();
|
||||
tris.extend(idx.chunks_exact(3).map(|t| [0, 1, 2].map(|k| m.transform_point3(pos[t[k] as usize]))));
|
||||
let mesh = meshes.add(build(&pos, &nor, &dag, &(0..dag.len()).filter(|&c| dag[c].level == 0).collect::<Vec<_>>(), opts.view == 6));
|
||||
let mat = if opts.view == 6 { lod_material.clone() } else { material.clone() };
|
||||
commands.spawn((Mesh3d(mesh.clone()), MeshMaterial3d(mat), at, Knot { mesh, drawn: Vec::new() }));
|
||||
}
|
||||
commands.insert_resource(Field { pos, nor, dag: Arc::new(dag), center, radius, finest: idx.len() / 3 });
|
||||
}
|
||||
|
||||
/// A knot's mesh from clusters: indexed into the shared vertices, or (coloured by level) a corner each.
|
||||
fn build(pos: &[Vec3], nor: &[Vec3], dag: &[lod::Cluster], drawn: &[usize], coloured: bool) -> Mesh {
|
||||
let mesh = Mesh::new(PrimitiveTopology::TriangleList, RenderAssetUsages::default());
|
||||
if !coloured {
|
||||
let idx = lod::indices_of(dag, drawn);
|
||||
return mesh.with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, pos.to_vec()).with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, nor.to_vec()).with_inserted_indices(Indices::U32(idx));
|
||||
}
|
||||
let (mut p, mut n, mut c) = (Vec::new(), Vec::new(), Vec::new());
|
||||
for &k in drawn {
|
||||
let [r, g, b] = LEVEL_COLOURS[dag[k].level as usize % LEVEL_COLOURS.len()];
|
||||
// each cluster a little lighter or darker, so cluster edges show within a level
|
||||
let shade = 0.75 + 0.25 * ((k as f32 * 12.9898).sin() * 43758.5).fract().abs();
|
||||
for &i in &dag[k].indices {
|
||||
p.push(pos[i as usize]);
|
||||
n.push(nor[i as usize]);
|
||||
c.push([r * shade, g * shade, b * shade, 1.0]);
|
||||
}
|
||||
}
|
||||
mesh.with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, p).with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, n).with_inserted_attribute(Mesh::ATTRIBUTE_COLOR, c)
|
||||
}
|
||||
|
||||
/// Triangles drawn this frame, and of how many, for the shot's line.
|
||||
#[derive(Resource, Default, Clone, Copy)]
|
||||
pub struct Counts {
|
||||
pub knots: usize,
|
||||
pub culled: usize,
|
||||
pub drawn: usize,
|
||||
pub full: usize,
|
||||
}
|
||||
|
||||
/// Each knot's clusters for this frame's camera: culled when its bounds are outside the view, all the finest with
|
||||
/// --detail full, else the hierarchy's choice at --tau pixels.
|
||||
pub fn choose(
|
||||
field: Option<Res<Field>>,
|
||||
opts: Res<Opts>,
|
||||
cam: Query<(&GlobalTransform, &Projection), With<Camera3d>>,
|
||||
mut knots: Query<(&GlobalTransform, &mut Knot, &mut Visibility)>,
|
||||
mut meshes: ResMut<Assets<Mesh>>,
|
||||
mut counts: ResMut<Counts>,
|
||||
) {
|
||||
let (Some(f), Ok((eye, proj))) = (field, cam.single()) else { return };
|
||||
let Projection::Perspective(pp) = proj else { return };
|
||||
let focal = lod::focal_px(pp.fov, opts.size.y as f32);
|
||||
let (half_y, half_x) = ((pp.fov * 0.5).tan(), (pp.fov * 0.5).tan() * pp.aspect_ratio);
|
||||
let view_from_world = eye.to_matrix().inverse();
|
||||
let at = eye.translation();
|
||||
let mut c = Counts::default();
|
||||
for (xf, mut knot, mut vis) in &mut knots {
|
||||
let (scale, _, _) = xf.to_scale_rotation_translation();
|
||||
let (s, center) = (scale.x, xf.transform_point(f.center));
|
||||
let r = f.radius * s;
|
||||
// outside the view's four sides or behind it
|
||||
let v = view_from_world.transform_point3(center);
|
||||
let depth = -v.z;
|
||||
let outside = depth < -r || v.x.abs() - half_x * depth > r * (1.0 + half_x * half_x).sqrt() || v.y.abs() - half_y * depth > r * (1.0 + half_y * half_y).sqrt();
|
||||
c.knots += 1;
|
||||
c.full += f.finest;
|
||||
if outside {
|
||||
c.culled += 1;
|
||||
*vis = Visibility::Hidden;
|
||||
continue;
|
||||
}
|
||||
*vis = Visibility::Inherited;
|
||||
let drawn: Vec<usize> = if opts.full {
|
||||
f.dag.iter().enumerate().filter(|(_, c)| c.level == 0).map(|(k, _)| k).collect()
|
||||
} else {
|
||||
let to_obj = xf.to_matrix().inverse();
|
||||
let eye_obj = to_obj.transform_point3(at);
|
||||
// in the knot's own space distances shrink by its scale, so the error's pixels come out the same
|
||||
lod::select(&f.dag, 1.0, eye_obj, focal, opts.tau)
|
||||
};
|
||||
c.drawn += drawn.iter().map(|&k| f.dag[k].indices.len() / 3).sum::<usize>();
|
||||
if drawn != knot.drawn {
|
||||
if let Some(mut m) = meshes.get_mut(&knot.mesh) {
|
||||
*m = build(&f.pos, &f.nor, &f.dag, &drawn, opts.view == 6);
|
||||
}
|
||||
knot.drawn = drawn;
|
||||
}
|
||||
}
|
||||
*counts = c;
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
//! The light grid (docs/lightbench.feature LB3c): world cells over everything the lights reach, each listing the lights
|
||||
//! whose range touches it, so a pixel weighs only its cell's lights rather than all of them. A light that doesn't touch
|
||||
//! a cell can't reach any point in it, so choosing among the cell's lights is still unbiased; outside the grid no light
|
||||
//! reaches at all. Built on the CPU each frame as the lights move (a count, then the lists, cell by cell).
|
||||
|
||||
use crate::scene::GpuLight;
|
||||
use bevy::math::{UVec3, Vec3};
|
||||
|
||||
pub struct Grid {
|
||||
pub min: Vec3,
|
||||
pub cell: f32,
|
||||
pub dims: UVec3,
|
||||
/// cell c's lights are idx[start[c]..start[c + 1]]
|
||||
pub start: Vec<u32>,
|
||||
pub idx: Vec<u32>,
|
||||
}
|
||||
|
||||
/// At most this many cells along an axis; the cell grows past `cell` to keep to it.
|
||||
const MAX_DIM: f32 = 96.0;
|
||||
|
||||
pub fn build(lights: &[GpuLight], cell: f32) -> Grid {
|
||||
let (mut lo, mut hi) = (Vec3::INFINITY, Vec3::NEG_INFINITY);
|
||||
for l in lights {
|
||||
let p = Vec3::from(l.pos);
|
||||
lo = lo.min(p - l.range);
|
||||
hi = hi.max(p + l.range);
|
||||
}
|
||||
if lights.is_empty() {
|
||||
(lo, hi) = (Vec3::ZERO, Vec3::ONE);
|
||||
}
|
||||
let cell = cell.max((hi - lo).max_element() / MAX_DIM);
|
||||
let dims = ((hi - lo) / cell).ceil().max(Vec3::ONE).as_uvec3();
|
||||
let n = (dims.x * dims.y * dims.z) as usize;
|
||||
let at = |x: u32, y: u32, z: u32| ((z * dims.y + y) * dims.x + x) as usize;
|
||||
// each light's cells: those its range sphere touches
|
||||
let mut pairs: Vec<(u32, u32)> = Vec::new();
|
||||
for (i, l) in lights.iter().enumerate() {
|
||||
let p = Vec3::from(l.pos);
|
||||
let a = ((p - l.range - lo) / cell).floor().max(Vec3::ZERO).as_uvec3().min(dims - 1);
|
||||
let b = ((p + l.range - lo) / cell).floor().max(Vec3::ZERO).as_uvec3().min(dims - 1);
|
||||
for z in a.z..=b.z {
|
||||
for y in a.y..=b.y {
|
||||
for x in a.x..=b.x {
|
||||
let c0 = lo + Vec3::new(x as f32, y as f32, z as f32) * cell;
|
||||
let near = p.clamp(c0, c0 + cell);
|
||||
if near.distance_squared(p) <= l.range * l.range {
|
||||
pairs.push((at(x, y, z) as u32, i as u32));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut start = vec![0u32; n + 1];
|
||||
pairs.iter().for_each(|(c, _)| start[*c as usize + 1] += 1);
|
||||
for c in 0..n {
|
||||
start[c + 1] += start[c];
|
||||
}
|
||||
let mut fill = start.clone();
|
||||
let mut idx = vec![0u32; pairs.len().max(1)];
|
||||
for (c, i) in pairs {
|
||||
idx[fill[c as usize] as usize] = i;
|
||||
fill[c as usize] += 1;
|
||||
}
|
||||
Grid { min: lo, cell, dims, start, idx }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_light_that_reaches_a_point_is_in_its_cell() {
|
||||
let lights: Vec<GpuLight> = (0..300)
|
||||
.map(|i| {
|
||||
let f = i as f32;
|
||||
GpuLight { pos: [(f * 7.3).sin() * 20.0, 1.0 + (f * 1.1).cos(), (f * 3.7).cos() * 30.0 - 20.0], range: 2.0 + (f * 0.37).sin().abs() * 5.0, power: [1.0; 3], radius: 0.05 }
|
||||
})
|
||||
.collect();
|
||||
let g = build(&lights, 2.0);
|
||||
let mut checked = 0;
|
||||
for k in 0..20000 {
|
||||
let f = k as f32;
|
||||
let p = Vec3::new((f * 0.731).sin() * 24.0, (f * 0.217).cos() * 3.0 + 1.0, (f * 0.393).cos() * 36.0 - 20.0);
|
||||
let c = ((p - g.min) / g.cell).floor();
|
||||
let inside = c.cmpge(Vec3::ZERO).all() && c.cmplt(g.dims.as_vec3()).all();
|
||||
for (i, l) in lights.iter().enumerate() {
|
||||
if Vec3::from(l.pos).distance(p) < l.range {
|
||||
assert!(inside, "{p} is reached by light {i} but is outside the grid");
|
||||
let c = c.as_uvec3();
|
||||
let cell = ((c.z * g.dims.y + c.y) * g.dims.x + c.x) as usize;
|
||||
assert!(g.idx[g.start[cell] as usize..g.start[cell + 1] as usize].contains(&(i as u32)), "light {i} reaches {p} but isn't in its cell");
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(checked > 1000, "{checked}");
|
||||
// and the lists are far shorter than all the lights
|
||||
let mean = g.idx.len() as f32 / (g.start.len() - 1) as f32;
|
||||
assert!(mean < 30.0, "{mean} lights a cell");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// LightBench's half-resolution bounce (LB7, joined after the other three): `trace_half` traces the bounce for one
|
||||
// pixel of each 2 x 2 block, a different one each frame so four frames cover them all, into `bounce_half`; the lighting pass
|
||||
// then takes each pixel's bounce from the four nearest blocks' samples, weighted by distance and by how near each
|
||||
// sample's surface is to the pixel's (its normal, and the pixel's plane), as Lumen and MegaLights upsample theirs.
|
||||
|
||||
// each block's bounced light (rgb) and 1 where it holds a surface's
|
||||
@group(0) @binding(13) var<storage, read_write> bounce_half: array<vec4<f32>>;
|
||||
|
||||
// a G-buffer pixel's surface: its point, its normal, and w of the point 0 for the sky
|
||||
struct Pixel { pos: vec4<f32>, n: vec3<f32> }
|
||||
|
||||
fn pixel_at(px: vec2<i32>) -> Pixel {
|
||||
let depth = textureLoad(depth_tex, px, 0);
|
||||
if depth <= 0.0 {
|
||||
return Pixel(vec4(0.0), vec3(0.0));
|
||||
}
|
||||
let g = textureLoad(gbuf, px, 0);
|
||||
let n = oct_decode(vec2(f32(g.a & 0xFFFu), f32((g.a >> 12u) & 0xFFFu)) / 4095.0);
|
||||
let uv = (vec2<f32>(px) + 0.5) / vec2<f32>(p.size.xy);
|
||||
let w = p.world_from_clip * vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);
|
||||
return Pixel(vec4(w.xyz / w.w, 1.0), n);
|
||||
}
|
||||
|
||||
fn half_size() -> vec2<u32> {
|
||||
return (p.size.xy + 1u) / 2u;
|
||||
}
|
||||
|
||||
// the pixel block b samples this frame
|
||||
fn half_pixel(b: vec2<u32>) -> vec2<i32> {
|
||||
let o = array(vec2(0u, 0u), vec2(1u, 1u), vec2(1u, 0u), vec2(0u, 1u))[p.size.w % 4u];
|
||||
return vec2<i32>(min(b * 2u + o, p.size.xy - 1u));
|
||||
}
|
||||
|
||||
@compute @workgroup_size(8, 8, 1)
|
||||
fn trace_half(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
let hs = half_size();
|
||||
if id.x >= hs.x || id.y >= hs.y {
|
||||
return;
|
||||
}
|
||||
let b = id.y * hs.x + id.x;
|
||||
let px = half_pixel(id.xy);
|
||||
let s = pixel_at(px);
|
||||
if s.pos.w == 0.0 {
|
||||
bounce_half[b] = vec4(0.0);
|
||||
return;
|
||||
}
|
||||
seed = pcg(u32(px.x) + u32(px.y) * p.size.x + p.size.w * p.size.x * p.size.y + 0x68e31da4u);
|
||||
rays = 0u;
|
||||
let o = s.pos.xyz + s.n * (2e-3 + 5e-4 * length(s.pos.xyz - p.eye.xyz));
|
||||
var e = vec3(0.0);
|
||||
if p.gi.y != 0u {
|
||||
e = cached(s.n, o);
|
||||
} else {
|
||||
e = bounced(s.n, o);
|
||||
}
|
||||
bounce_half[b] = vec4(e, 1.0);
|
||||
if rays > 0u {
|
||||
atomicAdd(&stats[0], rays);
|
||||
}
|
||||
}
|
||||
|
||||
// a pixel's bounced light from the four blocks around it
|
||||
fn upsampled(px: vec2<i32>, pos: vec3<f32>, n: vec3<f32>, dist: f32) -> vec3<f32> {
|
||||
let hs = vec2<i32>(half_size());
|
||||
let b0 = (px - 1) / 2;
|
||||
var sum = vec3(0.0);
|
||||
var wsum = 0.0;
|
||||
for (var k = 0; k < 4; k++) {
|
||||
let b = clamp(b0 + vec2(k & 1, k >> 1), vec2(0), hs - 1);
|
||||
let v = bounce_half[u32(b.y * hs.x + b.x)];
|
||||
if v.w == 0.0 {
|
||||
continue;
|
||||
}
|
||||
let spx = half_pixel(vec2<u32>(b));
|
||||
let s = pixel_at(spx);
|
||||
let near = max(0.0, 1.0 - length(vec2<f32>(spx - px)) / 3.0);
|
||||
let facing = pow(max(dot(n, s.n), 0.0), 8.0);
|
||||
let plane = exp(-abs(dot(n, s.pos.xyz - pos)) / (0.01 * dist + 0.005));
|
||||
let w = (near + 1e-3) * facing * plane;
|
||||
sum += v.rgb * w;
|
||||
wsum += w;
|
||||
}
|
||||
return select(vec3(0.0), sum / wsum, wsum > 1e-6);
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
// LightBench's lighting (docs/lightbench.feature LB1, LB3): each pixel of Bevy's G-buffer (the depth prepass and the
|
||||
// deferred prepass's albedo and normal) lit by point lights, every light (the reference) or K of them chosen at random,
|
||||
// each through one shadow ray in LightBench's own BVH. Both use `unshadowed` and `visible`, so they differ only in
|
||||
// which lights they look at. With --bounce (LB5) each pixel also follows a cosine-chosen ray through the BVH to the
|
||||
// nearest surface and lights that point the same way (one light sample in the sampled modes, every light in the
|
||||
// reference), so the reference and the sampled path still differ only in the lights they look at. The result goes
|
||||
// into the camera's HDR main texture, before Bevy's tonemapping.
|
||||
|
||||
struct Params {
|
||||
world_from_clip: mat4x4<f32>,
|
||||
// xyz: the camera, w: exposure
|
||||
eye: vec4<f32>,
|
||||
// width, height, lights, frame
|
||||
size: vec4<u32>,
|
||||
// mode (0 every light, 1 uniform, 2 weighted), K, view (0 lit, 1 normal, 2 albedo, 3 depth, 4 rays, 5 history,
|
||||
// 6 lod, 7 bounce: the bounced light alone),
|
||||
// brute force
|
||||
mode: vec4<u32>,
|
||||
// the previous frame's camera, to find where a point was
|
||||
prev_clip_from_world: mat4x4<f32>,
|
||||
// xyz: the previous camera
|
||||
prev_eye: vec4<f32>,
|
||||
// raw (no history), reset (a camera cut, or the first frame), the history's length in frames, 0
|
||||
temporal: vec4<u32>,
|
||||
// the light grid: its corner (xyz) and cell size (w); its cells along x, y, z, and whether the sampled modes use it
|
||||
grid_min: vec4<f32>,
|
||||
grid_dims: vec4<u32>,
|
||||
// diffuse bounces a pixel follows (0 none), whether its bounce reads the radiance cache instead (cache.wgsl),
|
||||
// whether the bounce is traced at half resolution and upsampled (half.wgsl), 0
|
||||
gi: vec4<u32>,
|
||||
// the sun (LB6): xyz the unit direction toward it, w its angular radius in radians; its irradiance (rgb, 0 off)
|
||||
sun: vec4<f32>,
|
||||
sun_e: vec4<f32>,
|
||||
// the sky's radiance (rgb): what a bounce ray that leaves the scene brings back
|
||||
sky: vec4<f32>,
|
||||
// the radiance cache: a cell's size at 1 m from the camera, the samples a cell holds at most, 0, 0
|
||||
cache: vec4<f32>,
|
||||
}
|
||||
|
||||
struct Node { mn: vec3<f32>, a: u32, mx: vec3<f32>, count: u32 }
|
||||
struct Light { pos: vec3<f32>, range: f32, power: vec3<f32>, radius: f32 }
|
||||
|
||||
@group(0) @binding(0) var<uniform> p: Params;
|
||||
@group(0) @binding(1) var depth_tex: texture_depth_2d;
|
||||
@group(0) @binding(2) var gbuf: texture_2d<u32>;
|
||||
@group(0) @binding(3) var<storage, read> nodes: array<Node>;
|
||||
// three a triangle: v0, v1 - v0, v2 - v0; their w the triangle's albedo (linear r, g, b), for the bounce
|
||||
@group(0) @binding(4) var<storage, read> tris: array<vec4<f32>>;
|
||||
@group(0) @binding(5) var<storage, read> lights: array<Light>;
|
||||
@group(0) @binding(6) var out: texture_storage_2d<rgba16float, write>;
|
||||
// the light so far at each pixel (rgb, before albedo) and how many frames it holds (a); the surface it was for
|
||||
// (its normal, and its distance from that frame's camera); last frame's to read, this frame's to write
|
||||
@group(0) @binding(7) var hist_in: texture_2d<f32>;
|
||||
@group(0) @binding(8) var geo_in: texture_2d<f32>;
|
||||
// (in f32: a long history's 1 / n steps are below an f16's resolution, and its mean stops moving)
|
||||
@group(0) @binding(9) var hist_out: texture_storage_2d<rgba32float, write>;
|
||||
@group(0) @binding(10) var geo_out: texture_storage_2d<rgba16float, write>;
|
||||
// this frame's shadow rays, lit pixels and the most rays any pixel traced (LB4's rays a pixel)
|
||||
@group(0) @binding(11) var<storage, read_write> stats: array<atomic<u32>, 4>;
|
||||
|
||||
// the light grid's two lists in one: cell c's lights are grid[grid[c]..grid[c + 1]] (its starts count from the buffer's
|
||||
// beginning, the lights' indices following the starts)
|
||||
@group(0) @binding(12) var<storage, read> grid: array<u32>;
|
||||
|
||||
var<workgroup> wg_rays: atomic<u32>;
|
||||
var<workgroup> wg_px: atomic<u32>;
|
||||
var<workgroup> wg_max: atomic<u32>;
|
||||
|
||||
const PI: f32 = 3.14159265;
|
||||
const MAX_K: u32 = 16u;
|
||||
const STACK: u32 = 48u;
|
||||
|
||||
var<private> seed: u32;
|
||||
var<private> rays: u32;
|
||||
|
||||
// Bevy's octahedral_decode (bevy_render utils), for the deferred prepass's normal
|
||||
fn oct_decode(v: vec2<f32>) -> vec3<f32> {
|
||||
let f = v * 2.0 - 1.0;
|
||||
var n = vec3(f.xy, 1.0 - abs(f.x) - abs(f.y));
|
||||
let t = saturate(-n.z);
|
||||
let w = select(vec2(t), vec2(-t), n.xy >= vec2(0.0));
|
||||
n = vec3(n.xy + w, n.z);
|
||||
return normalize(n);
|
||||
}
|
||||
|
||||
// a light's light at a point before its shadow: its power times the cosine and the falloff (an inverse square that
|
||||
// stops growing inside its radius and fades to nothing at its range); all zero where it can't reach
|
||||
fn unshadowed(l: Light, pos: vec3<f32>, n: vec3<f32>) -> vec3<f32> {
|
||||
let v = l.pos - pos;
|
||||
let d2 = max(dot(v, v), 1e-8);
|
||||
let d = sqrt(d2);
|
||||
let ndl = dot(n, v / d);
|
||||
if ndl <= 0.0 || d >= l.range {
|
||||
return vec3(0.0);
|
||||
}
|
||||
let x = d / l.range;
|
||||
let win = saturate(1.0 - x * x * x * x);
|
||||
return l.power * (ndl * win * win / max(d2, l.radius * l.radius));
|
||||
}
|
||||
|
||||
fn visible(o: vec3<f32>, l: Light) -> f32 {
|
||||
let v = l.pos - o;
|
||||
let d = length(v);
|
||||
return select(1.0, 0.0, occluded(o, v / d, d - 1e-3));
|
||||
}
|
||||
|
||||
// the candidate lights at a point: (first, count) into grid_idx, or with the grid off every light (count with first
|
||||
// = 0xFFFFFFFF); outside the grid no light reaches
|
||||
fn candidates(pos: vec3<f32>) -> vec2<u32> {
|
||||
if p.grid_dims.w == 0u {
|
||||
return vec2(0xFFFFFFFFu, p.size.z);
|
||||
}
|
||||
let c = vec3<i32>(floor((pos - p.grid_min.xyz) / p.grid_min.w));
|
||||
let d = vec3<i32>(p.grid_dims.xyz);
|
||||
if any(c < vec3(0)) || any(c >= d) {
|
||||
return vec2(0u, 0u);
|
||||
}
|
||||
let cell = u32((c.z * d.y + c.y) * d.x + c.x);
|
||||
return vec2(grid[cell], grid[cell + 1u] - grid[cell]);
|
||||
}
|
||||
|
||||
fn candidate(range: vec2<u32>, j: u32) -> u32 {
|
||||
return select(grid[range.x + j], j, range.x == 0xFFFFFFFFu);
|
||||
}
|
||||
|
||||
fn lum(c: vec3<f32>) -> f32 {
|
||||
return dot(c, vec3(0.2126, 0.7152, 0.0722));
|
||||
}
|
||||
|
||||
// the light reaching a point (pos, its normal n, o just off it) from the lights: every light with its shadow ray, or
|
||||
// k shadow rays to lights chosen uniformly or by their light from the point's cell
|
||||
fn lit_at(pos: vec3<f32>, n: vec3<f32>, o: vec3<f32>, k: u32) -> vec3<f32> {
|
||||
let nl = p.size.z;
|
||||
var c = vec3(0.0);
|
||||
if p.mode.x == 0u {
|
||||
for (var i = 0u; i < nl; i++) {
|
||||
let u = unshadowed(lights[i], pos, n);
|
||||
if lum(u) > 0.0 {
|
||||
c += u * visible(o, lights[i]);
|
||||
}
|
||||
}
|
||||
} else if p.mode.x == 1u {
|
||||
// uniform: each candidate 1 / their number
|
||||
let cand = candidates(pos);
|
||||
let m = cand.y;
|
||||
if m > 0u {
|
||||
for (var s = 0u; s < k; s++) {
|
||||
let i = candidate(cand, min(u32(rnd() * f32(m)), m - 1u));
|
||||
let u = unshadowed(lights[i], pos, n);
|
||||
if lum(u) > 0.0 {
|
||||
c += u * visible(o, lights[i]) * f32(m);
|
||||
}
|
||||
}
|
||||
c /= f32(k);
|
||||
}
|
||||
} else {
|
||||
// weighted: K reservoirs over every light by its unshadowed light, so any light that adds light can be chosen
|
||||
var pick: array<u32, MAX_K>;
|
||||
var pw: array<f32, MAX_K>;
|
||||
var wsum = 0.0;
|
||||
let cand = candidates(pos);
|
||||
for (var j = 0u; j < cand.y; j++) {
|
||||
let i = candidate(cand, j);
|
||||
let wi = lum(unshadowed(lights[i], pos, n));
|
||||
if wi <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
wsum += wi;
|
||||
for (var s = 0u; s < k; s++) {
|
||||
if rnd() * wsum < wi {
|
||||
pick[s] = i;
|
||||
pw[s] = wi;
|
||||
}
|
||||
}
|
||||
}
|
||||
if wsum > 0.0 {
|
||||
for (var s = 0u; s < k; s++) {
|
||||
let l = lights[pick[s]];
|
||||
c += unshadowed(l, pos, n) * visible(o, l) * (wsum / pw[s]);
|
||||
}
|
||||
c /= f32(k);
|
||||
}
|
||||
}
|
||||
// the sun, the same in every mode: one shadow ray to a point on its disc, so its shadows soften with its size
|
||||
let ns = dot(n, p.sun.xyz);
|
||||
if ns > 0.0 && lum(p.sun_e.rgb) > 0.0 && !occluded(o, cone_dir(p.sun.xyz, cos(p.sun.w)), 1e4) {
|
||||
c += p.sun_e.rgb * ns;
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
// the light reaching a point by way of other surfaces, p.gi.x bounces deep: from the point a cosine-chosen ray to the
|
||||
// nearest triangle, that point lit as a pixel is (one light sample, or every light in the reference), and on from
|
||||
// there. A cosine-chosen ray's pdf cancels the cosine and the 1 / PI of the hit's diffuse light, so each bounce adds
|
||||
// the albedos so far times the light at the hit. A ray that leaves the scene brings the sky: PI times its radiance,
|
||||
// for the same reason.
|
||||
fn bounced(n0: vec3<f32>, o0: vec3<f32>) -> vec3<f32> {
|
||||
var e = vec3(0.0);
|
||||
var through = vec3(1.0);
|
||||
var n = n0;
|
||||
var o = o0;
|
||||
for (var b = 0u; b < p.gi.x; b++) {
|
||||
let d = cosine_dir(n);
|
||||
let h = closest(o, d, 1e4);
|
||||
if h.i == 0xFFFFFFFFu {
|
||||
e += through * PI * p.sky.rgb;
|
||||
break;
|
||||
}
|
||||
let v0 = tris[3u * h.i];
|
||||
let e1 = tris[3u * h.i + 1u];
|
||||
let e2 = tris[3u * h.i + 2u];
|
||||
var nh = normalize(cross(e1.xyz, e2.xyz));
|
||||
if dot(nh, d) > 0.0 {
|
||||
nh = -nh;
|
||||
}
|
||||
let hp = o + d * h.t;
|
||||
let oh = hp + nh * (2e-3 + 5e-4 * length(hp - p.eye.xyz));
|
||||
through *= vec3(v0.w, e1.w, e2.w);
|
||||
e += through * lit_at(hp, nh, oh, 1u);
|
||||
n = nh;
|
||||
o = oh;
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
// one pixel: its light, its history; (shadow rays traced, 1 if it is a lit pixel)
|
||||
fn shade(id: vec3<u32>) -> vec2<u32> {
|
||||
if id.x >= p.size.x || id.y >= p.size.y {
|
||||
return vec2(0u);
|
||||
}
|
||||
let px = vec2<i32>(id.xy);
|
||||
let depth = textureLoad(depth_tex, px, 0);
|
||||
// the sky (reverse Z: far is 0) keeps Bevy's clear colour, and holds no history
|
||||
if depth <= 0.0 {
|
||||
textureStore(hist_out, px, vec4(0.0));
|
||||
textureStore(geo_out, px, vec4(0.0, 0.0, 0.0, -1.0));
|
||||
return vec2(0u);
|
||||
}
|
||||
let g = textureLoad(gbuf, px, 0);
|
||||
let albedo = pow(unpack4x8unorm(g.r).rgb, vec3(2.2));
|
||||
let n = oct_decode(vec2(f32(g.a & 0xFFFu), f32((g.a >> 12u) & 0xFFFu)) / 4095.0);
|
||||
let uv = (vec2<f32>(id.xy) + 0.5) / vec2<f32>(p.size.xy);
|
||||
let w = p.world_from_clip * vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);
|
||||
let pos = w.xyz / w.w;
|
||||
let dist = length(pos - p.eye.xyz);
|
||||
let view = p.mode.z;
|
||||
if view == 1u {
|
||||
textureStore(out, px, vec4(n * 0.5 + 0.5, 1.0));
|
||||
return vec2(0u);
|
||||
}
|
||||
if view == 2u || view == 6u {
|
||||
textureStore(out, px, vec4(albedo, 1.0));
|
||||
return vec2(0u);
|
||||
}
|
||||
if view == 3u {
|
||||
textureStore(out, px, vec4(vec3(dist / 20.0), 1.0));
|
||||
return vec2(0u);
|
||||
}
|
||||
seed = pcg(id.x + id.y * p.size.x + p.size.w * p.size.x * p.size.y);
|
||||
rays = 0u;
|
||||
// off the surface along its normal, more the farther it is (depth precision)
|
||||
let o = pos + n * (2e-3 + 5e-4 * dist);
|
||||
var c = vec3(0.0);
|
||||
if view != 7u {
|
||||
c = lit_at(pos, n, o, clamp(p.mode.y, 1u, MAX_K));
|
||||
}
|
||||
if p.gi.z != 0u {
|
||||
c += upsampled(px, pos, n, dist);
|
||||
} else if p.gi.y != 0u {
|
||||
c += cached(n, o);
|
||||
} else if p.gi.x > 0u {
|
||||
c += bounced(n, o);
|
||||
}
|
||||
// the history: where this point was last frame, kept only if the same surface was there
|
||||
var held = 0.0;
|
||||
var acc = c;
|
||||
if p.temporal.x == 0u && p.temporal.y == 0u {
|
||||
let was = p.prev_clip_from_world * vec4(pos, 1.0);
|
||||
let ndc = was.xy / was.w;
|
||||
let at = vec2<i32>(floor(vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * vec2<f32>(p.size.xy)));
|
||||
if was.w > 0.0 && all(at >= vec2(0)) && all(at < vec2<i32>(p.size.xy)) {
|
||||
let geo = textureLoad(geo_in, at, 0);
|
||||
let expect = length(pos - p.prev_eye.xyz);
|
||||
if geo.w > 0.0 && abs(geo.w - expect) < 0.02 * expect + 0.01 && dot(geo.xyz, n) > 0.9 {
|
||||
let h = textureLoad(hist_in, at, 0);
|
||||
held = min(h.a, f32(p.temporal.z) - 1.0);
|
||||
acc = mix(h.rgb, c, 1.0 / (held + 1.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
textureStore(hist_out, px, vec4(acc, held + 1.0));
|
||||
textureStore(geo_out, px, vec4(n, dist));
|
||||
if view == 4u {
|
||||
textureStore(out, px, vec4(vec3(f32(rays) / 16.0), 1.0));
|
||||
return vec2(rays, 1u);
|
||||
}
|
||||
if view == 5u {
|
||||
textureStore(out, px, vec4(vec3((held + 1.0) / f32(p.temporal.z)), 1.0));
|
||||
return vec2(rays, 1u);
|
||||
}
|
||||
textureStore(out, px, vec4(acc * albedo / PI * p.eye.w, 1.0));
|
||||
return vec2(rays, 1u);
|
||||
}
|
||||
|
||||
@compute @workgroup_size(8, 8, 1)
|
||||
fn main(@builtin(global_invocation_id) id: vec3<u32>, @builtin(local_invocation_index) li: u32) {
|
||||
let r = shade(id);
|
||||
atomicAdd(&wg_rays, r.x);
|
||||
atomicAdd(&wg_px, r.y);
|
||||
atomicMax(&wg_max, r.x);
|
||||
workgroupBarrier();
|
||||
if li == 0u {
|
||||
atomicAdd(&stats[0], atomicLoad(&wg_rays));
|
||||
atomicAdd(&stats[1], atomicLoad(&wg_px));
|
||||
atomicMax(&stats[2], atomicLoad(&wg_max));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
//! Adaptive geometry (docs/lightbench.feature LB2): detail chosen by how many pixels its error covers,
|
||||
//! projected_px = focal_px * error * scale / depth, where depth is the distance to the bounds' near side (so a camera
|
||||
//! inside them asks for full detail).
|
||||
//!
|
||||
//! Two ways, the second built on the first's checks: discrete LODs (the whole mesh simplified by halves, the coarsest
|
||||
//! whose error stays under the threshold drawn), and a cluster hierarchy in the manner of Nanite. Its clusters of up to
|
||||
//! 128 triangles are grouped by meshopt, each group simplified to half with its border locked, and split again into
|
||||
//! the next level's clusters. Every cluster keeps its own error and bounds and its parent group's, both monotonic up
|
||||
//! the hierarchy, so a cluster is drawn exactly when its own error projects within the threshold and its parent's
|
||||
//! doesn't: a parent or its children, never both, and the locked borders keep the cut crack-free.
|
||||
|
||||
use bevy::math::Vec3;
|
||||
use meshopt::{SimplifyOptions, VertexDataAdapter};
|
||||
|
||||
fn adapter(pos: &[Vec3]) -> VertexDataAdapter<'_> {
|
||||
VertexDataAdapter::new(bytemuck::cast_slice(pos), 12, 0).expect("positions")
|
||||
}
|
||||
|
||||
/// The pixels an error of `error` metres covers at bounds (`center`, `radius`) scaled by `scale`, from `eye`.
|
||||
pub fn projected_px(error: f32, center: Vec3, radius: f32, scale: f32, eye: Vec3, focal_px: f32) -> f32 {
|
||||
if !error.is_finite() {
|
||||
return f32::INFINITY;
|
||||
}
|
||||
let depth = (center.distance(eye) - radius * scale).max(1e-3);
|
||||
focal_px * error * scale / depth
|
||||
}
|
||||
|
||||
/// The focal length in pixels of a vertical field of view over `height` pixels.
|
||||
pub fn focal_px(fov_y: f32, height: f32) -> f32 {
|
||||
height * 0.5 / (fov_y * 0.5).tan()
|
||||
}
|
||||
|
||||
fn sphere(pos: &[Vec3], idx: &[u32]) -> (Vec3, f32) {
|
||||
let (mut lo, mut hi) = (Vec3::INFINITY, Vec3::NEG_INFINITY);
|
||||
idx.iter().for_each(|&i| {
|
||||
lo = lo.min(pos[i as usize]);
|
||||
hi = hi.max(pos[i as usize]);
|
||||
});
|
||||
let c = (lo + hi) * 0.5;
|
||||
(c, idx.iter().map(|&i| pos[i as usize].distance(c)).fold(0.0, f32::max))
|
||||
}
|
||||
|
||||
/// One discrete level: its triangles and its error in metres (object space).
|
||||
pub struct Level {
|
||||
pub indices: Vec<u32>,
|
||||
pub error: f32,
|
||||
}
|
||||
|
||||
/// The mesh, then halves of it, until simplifying stops halving or `levels` are made.
|
||||
pub fn chain(pos: &[Vec3], idx: &[u32], levels: usize) -> Vec<Level> {
|
||||
let a = adapter(pos);
|
||||
let mut out = vec![Level { indices: idx.to_vec(), error: 0.0 }];
|
||||
while out.len() < levels {
|
||||
let last = out.last().unwrap();
|
||||
let mut err = 0.0;
|
||||
let next = meshopt::simplify(&last.indices, &a, last.indices.len() / 2, f32::MAX, SimplifyOptions::ErrorAbsolute, Some(&mut err));
|
||||
if next.len() as f32 > last.indices.len() as f32 * 0.8 {
|
||||
break;
|
||||
}
|
||||
let error = err.max(last.error);
|
||||
out.push(Level { indices: next, error });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The coarsest level whose error projects within `tau` pixels.
|
||||
pub fn pick(levels: &[Level], center: Vec3, radius: f32, scale: f32, eye: Vec3, focal: f32, tau: f32) -> usize {
|
||||
(0..levels.len()).rev().find(|&l| projected_px(levels[l].error, center, radius, scale, eye, focal) <= tau).unwrap_or(0)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Cluster {
|
||||
pub indices: Vec<u32>,
|
||||
pub level: u32,
|
||||
/// its own error and bounds (the group it was simplified in; zero error at the finest level)
|
||||
pub error: f32,
|
||||
pub center: Vec3,
|
||||
pub radius: f32,
|
||||
/// its parent group's (infinite error at the roots)
|
||||
pub parent_error: f32,
|
||||
pub parent_center: Vec3,
|
||||
pub parent_radius: f32,
|
||||
}
|
||||
|
||||
fn clusters_of(pos: &[Vec3], idx: &[u32]) -> Vec<Vec<u32>> {
|
||||
let m = meshopt::build_meshlets(idx, &adapter(pos), 128, 128, 0.0);
|
||||
m.iter().map(|c| c.triangles.iter().map(|&t| c.vertices[usize::from(t)]).collect()).collect()
|
||||
}
|
||||
|
||||
/// The named clusters' triangles as one index list.
|
||||
pub fn indices_of(all: &[Cluster], which: &[usize]) -> Vec<u32> {
|
||||
which.iter().flat_map(|&c| all[c].indices.iter().copied()).collect()
|
||||
}
|
||||
|
||||
/// The cluster hierarchy of a closed mesh.
|
||||
pub fn dag(pos: &[Vec3], idx: &[u32]) -> Vec<Cluster> {
|
||||
let a = adapter(pos);
|
||||
let mut all: Vec<Cluster> = Vec::new();
|
||||
let mut level: Vec<usize> = Vec::new();
|
||||
for c in clusters_of(pos, idx) {
|
||||
let (center, radius) = sphere(pos, &c);
|
||||
level.push(all.len());
|
||||
all.push(Cluster { indices: c, level: 0, error: 0.0, center, radius, parent_error: f32::INFINITY, parent_center: center, parent_radius: radius });
|
||||
}
|
||||
for depth in 1.. {
|
||||
if level.len() <= 1 {
|
||||
break;
|
||||
}
|
||||
// groups of about four clusters that share vertices
|
||||
let counts: Vec<u32> = level.iter().map(|&c| all[c].indices.len() as u32).collect();
|
||||
let flat = indices_of(&all, &level);
|
||||
let mut part = vec![0u32; level.len()];
|
||||
let groups = meshopt::partition_clusters(&mut part, &flat, &counts, pos.len(), 4);
|
||||
let mut next = Vec::new();
|
||||
for g in 0..groups {
|
||||
let members: Vec<usize> = level.iter().zip(&part).filter(|(_, p)| **p as usize == g).map(|(c, _)| *c).collect();
|
||||
let merged = indices_of(&all, &members);
|
||||
let mut err = 0.0;
|
||||
let simple = meshopt::simplify(&merged, &a, merged.len() / 2, f32::MAX, SimplifyOptions::LockBorder | SimplifyOptions::ErrorAbsolute, Some(&mut err));
|
||||
// a group that won't halve stays as it is: its clusters are roots
|
||||
if members.len() < 2 || simple.len() as f32 > merged.len() as f32 * 0.85 {
|
||||
continue;
|
||||
}
|
||||
// the group's bounds hold its children's, and its error is at least theirs: both only grow upward
|
||||
let (center, mut radius) = sphere(pos, &merged);
|
||||
for &c in &members {
|
||||
radius = radius.max(center.distance(all[c].center) + all[c].radius);
|
||||
}
|
||||
let error = members.iter().map(|&c| all[c].error).fold(err, f32::max);
|
||||
for &c in &members {
|
||||
(all[c].parent_error, all[c].parent_center, all[c].parent_radius) = (error, center, radius);
|
||||
}
|
||||
for c in clusters_of(pos, &simple) {
|
||||
next.push(all.len());
|
||||
all.push(Cluster { indices: c, level: depth, error, center, radius, parent_error: f32::INFINITY, parent_center: center, parent_radius: radius });
|
||||
}
|
||||
}
|
||||
if next.is_empty() {
|
||||
break;
|
||||
}
|
||||
level = next;
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
/// The clusters to draw: each whose own error projects within `tau` and whose parent's doesn't.
|
||||
pub fn select(dag: &[Cluster], scale: f32, eye: Vec3, focal: f32, tau: f32) -> Vec<usize> {
|
||||
(0..dag.len())
|
||||
.filter(|&i| {
|
||||
let c = &dag[i];
|
||||
projected_px(c.error, c.center, c.radius, scale, eye, focal) <= tau && projected_px(c.parent_error, c.parent_center, c.parent_radius, scale, eye, focal) > tau
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn knot() -> (Vec<Vec3>, Vec<u32>) {
|
||||
let (p, _, i) = crate::scene::knot_data(2, 3, 512, 16, 0.33);
|
||||
(p, i)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn farther_is_coarser_and_a_narrower_view_finer() {
|
||||
let (p, i) = knot();
|
||||
let levels = chain(&p, &i, 8);
|
||||
assert!(levels.len() >= 5, "{} levels", levels.len());
|
||||
assert!(levels.windows(2).all(|w| w[1].error >= w[0].error && w[1].indices.len() < w[0].indices.len()));
|
||||
let f45 = focal_px(45f32.to_radians(), 720.0);
|
||||
let at = |d: f32, f: f32| pick(&levels, Vec3::ZERO, 3.3, 0.5, Vec3::new(0.0, 0.0, d), f, 1.0);
|
||||
let by_distance: Vec<usize> = [2.0, 5.0, 10.0, 20.0, 40.0, 80.0].iter().map(|&d| at(d, f45)).collect();
|
||||
assert!(by_distance.windows(2).all(|w| w[1] >= w[0]) && by_distance[5] > by_distance[0], "{by_distance:?}");
|
||||
let f15 = focal_px(15f32.to_radians(), 720.0);
|
||||
assert!(at(20.0, f15) < at(20.0, f45), "15 deg {} 45 deg {}", at(20.0, f15), at(20.0, f45));
|
||||
// a camera inside the bounds asks for full detail
|
||||
assert_eq!(at(0.5, f45), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_hierarchy_draws_a_parent_or_its_children_and_never_cracks() {
|
||||
let (p, i) = knot();
|
||||
let dag = dag(&p, &i);
|
||||
let top = dag.iter().map(|c| c.level).max().unwrap();
|
||||
assert!(top >= 3, "{top} levels");
|
||||
for c in &dag {
|
||||
assert!(c.parent_error >= c.error && c.parent_radius >= c.radius * 0.999, "{c:?}");
|
||||
}
|
||||
let f = focal_px(45f32.to_radians(), 720.0);
|
||||
let full = i.len() / 3;
|
||||
let mut drawn = Vec::new();
|
||||
for (d, tau) in [(1.0, 1.0), (4.0, 1.0), (12.0, 1.0), (30.0, 1.0), (90.0, 1.0), (12.0, 4.0), (12.0, 0.25), (12.0, 0.0)] {
|
||||
let eye = Vec3::new(0.3, 0.2, d);
|
||||
let pick = select(&dag, 0.5, eye, f, tau);
|
||||
// a closed mesh: every edge of what's drawn is shared by exactly two triangles
|
||||
let mut edges: HashMap<(u32, u32), u32> = HashMap::new();
|
||||
let mut tris = 0;
|
||||
for &c in &pick {
|
||||
for t in dag[c].indices.chunks_exact(3) {
|
||||
tris += 1;
|
||||
for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
|
||||
*edges.entry((a.min(b), a.max(b))).or_default() += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let open = edges.values().filter(|&&n| n != 2).count();
|
||||
assert_eq!(open, 0, "at {d} m, {tau} px: {open} edges not shared by two triangles");
|
||||
drawn.push(tris);
|
||||
}
|
||||
// a threshold of nothing draws every finest triangle; up close, the knot's near side is finest, its far side not
|
||||
assert_eq!(drawn[7], full);
|
||||
assert!(drawn[0] > full / 2, "{drawn:?}");
|
||||
assert!(drawn[0] >= drawn[1] && drawn[1] >= drawn[2] && drawn[2] >= drawn[3] && drawn[3] >= drawn[4] && drawn[4] < full / 8, "{drawn:?}");
|
||||
// a looser threshold draws fewer, a tighter one more
|
||||
assert!(drawn[5] <= drawn[2] && drawn[6] >= drawn[2], "{drawn:?}");
|
||||
println!("triangles drawn (full {full}): {drawn:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
//! LightBench (docs/lightbench.feature): a small Rust + Bevy renderer that proves lighting and geometry techniques
|
||||
//! against its own all-lights reference before they move into raea. `lightbench --help` lists the switches; with
|
||||
//! `--shot FILE` it draws headless, saves frame `--frames` as a PNG and exits, so every claim is a repeatable run.
|
||||
|
||||
mod bvh;
|
||||
mod field;
|
||||
mod grid;
|
||||
mod lod;
|
||||
mod pass;
|
||||
mod scene;
|
||||
|
||||
use bevy::{
|
||||
camera::{CameraMainTextureUsages, Hdr, RenderTarget},
|
||||
core_pipeline::prepass::{DeferredPrepass, DepthPrepass},
|
||||
pbr::DefaultOpaqueRendererMethod,
|
||||
prelude::*,
|
||||
render::{
|
||||
render_resource::{TextureFormat, TextureUsages},
|
||||
view::screenshot::{Screenshot, ScreenshotCaptured},
|
||||
},
|
||||
window::ExitCondition,
|
||||
};
|
||||
|
||||
const HELP: &str = "lightbench [switches]
|
||||
--mode all|uniform|weighted every light (the reference), or K chosen uniformly or by their light (all)
|
||||
--k K light samples a pixel, 1 to 16 (4)
|
||||
--lights N point lights, the pillar's first (16)
|
||||
--view lit|normal|albedo|depth|rays what to show (lit)
|
||||
--bounce N diffuse bounces each pixel follows through the BVH, each hit lit by the same light
|
||||
sampling as the pixel (one sample; every light with --mode all) (0)
|
||||
--view bounce the bounced light alone
|
||||
--brute test every triangle for each shadow ray instead of the BVH
|
||||
--detail N the knot's segments; its triangles are N * N / 16 (2048; the field's knots 512)
|
||||
--size WxH pixels (1280x720)
|
||||
--t SECONDS hold the lights where they are at this time (they move otherwise)
|
||||
--exposure X linear exposure (1)
|
||||
--shot FILE draw headless, save frame --frames as a PNG, exit
|
||||
--frames N the lit frame --shot saves (4)
|
||||
--bench N with --shot: time N more lit frames first and print the mean (frame time, its own run)
|
||||
--no-pillar leave out the pillar outside the view (its shadow should go with it)
|
||||
--raw no temporal accumulation: each frame's samples alone
|
||||
--history N frames the history holds at most (32)
|
||||
--camera still|orbit|cut the camera holds, circles slowly, or jumps to a second view at lit frame --cut-at (still)
|
||||
--cut-at N the lit frame --camera cut jumps on (8)
|
||||
--view history frames of history at each pixel, white when full
|
||||
--scene knot|field|room one knot by a wall (lighting), rows of knots into the distance (detail), or the knot
|
||||
and wall in a closed room lit by the sun through a window (bounce: --sun on, --sky
|
||||
0.25, --bounce 2 unless given) (knot)
|
||||
--sun on|off a low sun from the left, one shadow ray to a point on its disc a pixel (off)
|
||||
--sun-size DEG the sun's angular diameter: larger, softer shadows (0.53)
|
||||
--cache on|off the bounce reads a world radiance cache at its first hit instead of tracing on, and
|
||||
feeds it: every bounce for two rays a pixel (off)
|
||||
--bounce-res full|half the bounce traced at every pixel, or at one of each 2 x 2 block (a different one each
|
||||
frame) and upsampled by depth and normal (full)
|
||||
--cell M the cache's cell size at 1 m from the camera, doubling with each doubling (0.1)
|
||||
--sky X the sky's radiance (a blue-white), brought by bounce rays that leave the scene (0)
|
||||
--rows N the field's rows (6)
|
||||
--detail full|adaptive every finest triangle, or the clusters each knot's distance asks for (adaptive)
|
||||
--tau PX the error in pixels a cluster may show (1)
|
||||
--fov DEG the vertical field of view (45)
|
||||
--view lod each cluster coloured by its level (white the finest), unlit
|
||||
--grid on|off the sampled modes weigh only the lights whose range reaches the pixel's cell (on)";
|
||||
|
||||
#[derive(Resource, Clone)]
|
||||
pub struct Opts {
|
||||
pub mode: u32,
|
||||
pub k: u32,
|
||||
pub lights: u32,
|
||||
pub view: u32,
|
||||
pub brute: bool,
|
||||
pub detail: u32,
|
||||
pub size: UVec2,
|
||||
pub t: Option<f32>,
|
||||
pub exposure: f32,
|
||||
pub shot: Option<String>,
|
||||
pub frames: u32,
|
||||
pub bench: u32,
|
||||
pub pillar: bool,
|
||||
pub raw: bool,
|
||||
pub history: u32,
|
||||
/// 0 still, 1 orbit, 2 cut
|
||||
pub camera: u32,
|
||||
pub cut_at: u32,
|
||||
/// 0 knot, 1 field
|
||||
pub scene: u32,
|
||||
pub rows: u32,
|
||||
pub full: bool,
|
||||
pub tau: f32,
|
||||
pub fov: f32,
|
||||
pub grid: bool,
|
||||
pub bounces: u32,
|
||||
pub sun: bool,
|
||||
pub sun_size: f32,
|
||||
pub sky: f32,
|
||||
pub cache: bool,
|
||||
pub cell: f32,
|
||||
pub half: bool,
|
||||
}
|
||||
|
||||
fn opts() -> Result<Opts, String> {
|
||||
let mut o = Opts { mode: 0, k: 4, lights: 16, view: 0, brute: false, detail: 0, size: UVec2::new(1280, 720), t: None, exposure: 1.0, shot: None, frames: 4, bench: 0, pillar: true, raw: false, history: 32, camera: 0, cut_at: 8, scene: 0, rows: 6, full: false, tau: 1.0, fov: 45.0, grid: true, bounces: 0, sun: false, sun_size: 0.53, sky: 0.0, cache: false, cell: 0.1, half: false };
|
||||
// what --scene room turns on, unless the switches say otherwise
|
||||
let (mut sun, mut sky, mut bounces) = (None, None, None);
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(a) = args.next() {
|
||||
let mut val = || args.next().ok_or(format!("{a} needs a value"));
|
||||
let num = |v: String| v.parse::<f32>().map_err(|_| format!("{a}: {v} isn't a number"));
|
||||
match a.as_str() {
|
||||
"--mode" => {
|
||||
let v = val()?;
|
||||
o.mode = ["all", "uniform", "weighted"].iter().position(|m| *m == v).ok_or("--mode: all, uniform or weighted")? as u32;
|
||||
}
|
||||
"--view" => {
|
||||
let v = val()?;
|
||||
o.view = ["lit", "normal", "albedo", "depth", "rays", "history", "lod", "bounce"].iter().position(|m| *m == v).ok_or("--view: lit, normal, albedo, depth, rays, history, lod or bounce")? as u32;
|
||||
}
|
||||
"--k" => o.k = (num(val()?)? as u32).clamp(1, 16),
|
||||
"--lights" => o.lights = (num(val()?)? as u32).max(1),
|
||||
"--brute" => o.brute = true,
|
||||
"--detail" => {
|
||||
let v = val()?;
|
||||
match v.as_str() {
|
||||
"full" => o.full = true,
|
||||
"adaptive" => o.full = false,
|
||||
n => o.detail = (num(n.into())? as u32).max(64),
|
||||
}
|
||||
}
|
||||
"--scene" => {
|
||||
let v = val()?;
|
||||
o.scene = ["knot", "field", "room"].iter().position(|m| *m == v).ok_or("--scene: knot, field or room")? as u32;
|
||||
}
|
||||
"--rows" => o.rows = (num(val()?)? as u32).max(1),
|
||||
"--tau" => o.tau = num(val()?)?.max(0.0),
|
||||
"--fov" => o.fov = num(val()?)?.clamp(1.0, 170.0),
|
||||
"--grid" => o.grid = val()? != "off",
|
||||
"--bounce" => bounces = Some((num(val()?)? as u32).min(8)),
|
||||
"--sun" => sun = Some(val()? != "off"),
|
||||
"--sun-size" => o.sun_size = num(val()?)?.clamp(0.0, 30.0),
|
||||
"--sky" => sky = Some(num(val()?)?.max(0.0)),
|
||||
"--cache" => o.cache = val()? != "off",
|
||||
"--cell" => o.cell = num(val()?)?.clamp(0.01, 10.0),
|
||||
"--bounce-res" => o.half = val()? == "half",
|
||||
"--size" => {
|
||||
let v = val()?;
|
||||
let (w, h) = v.split_once('x').ok_or("--size: WxH")?;
|
||||
o.size = UVec2::new(num(w.into())? as u32, num(h.into())? as u32);
|
||||
}
|
||||
"--t" => o.t = Some(num(val()?)?),
|
||||
"--exposure" => o.exposure = num(val()?)?,
|
||||
"--shot" => o.shot = Some(val()?),
|
||||
"--frames" => o.frames = (num(val()?)? as u32).max(1),
|
||||
"--bench" => o.bench = num(val()?)? as u32,
|
||||
"--no-pillar" => o.pillar = false,
|
||||
"--raw" => o.raw = true,
|
||||
"--history" => o.history = (num(val()?)? as u32).max(1),
|
||||
"--cut-at" => o.cut_at = num(val()?)? as u32,
|
||||
"--camera" => {
|
||||
let v = val()?;
|
||||
o.camera = ["still", "orbit", "cut"].iter().position(|m| *m == v).ok_or("--camera: still, orbit or cut")? as u32;
|
||||
}
|
||||
"--help" | "-h" => return Err(HELP.into()),
|
||||
_ => return Err(format!("unknown switch {a}\n{HELP}")),
|
||||
}
|
||||
}
|
||||
let room = o.scene == 2;
|
||||
(o.sun, o.sky, o.bounces) = (sun.unwrap_or(room), sky.unwrap_or(if room { 0.25 } else { 0.0 }), bounces.unwrap_or(if room { 2 } else { 0 }));
|
||||
if o.detail == 0 {
|
||||
o.detail = if o.scene == 1 { 512 } else { 2048 };
|
||||
}
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
/// Whether this run times its frames (--bench), read before the app is built.
|
||||
pub fn timing() -> bool {
|
||||
std::env::args().any(|a| a == "--bench")
|
||||
}
|
||||
|
||||
/// The image a headless run draws into.
|
||||
#[derive(Resource)]
|
||||
struct Target(Handle<Image>);
|
||||
|
||||
fn main() {
|
||||
let o = match opts() {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
std::process::exit(if e == HELP { 0 } else { 2 });
|
||||
}
|
||||
};
|
||||
let (sky, x) = (o.sky, o.exposure);
|
||||
let mut app = App::new();
|
||||
// timing runs ask the GPU for timestamps at a pass's start and end (Apple's GPUs have no others), for its time
|
||||
let mut wgpu = bevy::render::settings::WgpuSettings::default();
|
||||
if timing() {
|
||||
wgpu.features |= bevy::render::settings::WgpuFeatures::TIMESTAMP_QUERY;
|
||||
}
|
||||
let render = bevy::render::RenderPlugin { render_creation: bevy::render::settings::RenderCreation::Automatic(Box::new(wgpu)), ..default() };
|
||||
if o.shot.is_some() {
|
||||
app.add_plugins(
|
||||
DefaultPlugins
|
||||
.set(WindowPlugin { primary_window: None, exit_condition: ExitCondition::DontExit, ..default() })
|
||||
.set(render)
|
||||
.disable::<bevy::winit::WinitPlugin>(),
|
||||
)
|
||||
.add_plugins(bevy::app::ScheduleRunnerPlugin::run_loop(std::time::Duration::ZERO));
|
||||
} else {
|
||||
let window = Window { title: "LightBench".into(), resolution: (o.size.x, o.size.y).into(), ..default() };
|
||||
app.add_plugins(DefaultPlugins.set(WindowPlugin { primary_window: Some(window), ..default() }).set(render));
|
||||
}
|
||||
app.insert_resource(o)
|
||||
.insert_resource(DefaultOpaqueRendererMethod::deferred())
|
||||
// the sky seen past the scene: the bounce's sky, exposed as the lighting pass exposes, else near black
|
||||
.insert_resource(ClearColor(if sky > 0.0 { Color::linear_rgb(SKY.x * sky * x, SKY.y * sky * x, SKY.z * sky * x) } else { Color::srgb(0.02, 0.025, 0.035) }))
|
||||
.add_plugins(pass::LightPass)
|
||||
.add_systems(Startup, (scene::spawn, camera))
|
||||
.init_resource::<field::Counts>()
|
||||
.add_systems(Update, (tick, field::choose.after(tick), shoot.after(field::choose)))
|
||||
.run();
|
||||
}
|
||||
|
||||
fn camera(mut commands: Commands, o: Res<Opts>, mut images: ResMut<Assets<Image>>) {
|
||||
let usages = TextureUsages::RENDER_ATTACHMENT | TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_SRC | TextureUsages::STORAGE_BINDING;
|
||||
let mut cam = commands.spawn((
|
||||
Camera3d::default(),
|
||||
Hdr,
|
||||
Msaa::Off,
|
||||
DepthPrepass,
|
||||
DeferredPrepass,
|
||||
CameraMainTextureUsages(usages),
|
||||
Projection::Perspective(PerspectiveProjection { fov: o.fov.to_radians(), ..default() }),
|
||||
eye(&o, 0),
|
||||
));
|
||||
if o.shot.is_some() {
|
||||
let mut image = Image::new_target_texture(o.size.x, o.size.y, TextureFormat::Rgba8UnormSrgb, None);
|
||||
image.texture_descriptor.usage |= TextureUsages::COPY_SRC;
|
||||
let handle = images.add(image);
|
||||
cam.insert(RenderTarget::Image(handle.clone().into()));
|
||||
commands.insert_resource(Target(handle));
|
||||
}
|
||||
}
|
||||
|
||||
/// The sun (LB6): toward it from the scene, low on the left and a little behind the knot, so in --scene room it comes
|
||||
/// through the window onto the floor in front of the knot; its irradiance, warm; the sky's colour, which --sky scales.
|
||||
const SUN_TO: Vec3 = Vec3::new(-1.0, 0.55, -0.45);
|
||||
const SUN_E: Vec3 = Vec3::new(3.2, 2.9, 2.5);
|
||||
const SKY: Vec3 = Vec3::new(0.55, 0.75, 1.0);
|
||||
|
||||
const EYE: Vec3 = Vec3::new(0.0, 2.2, 7.0);
|
||||
const LOOK: Vec3 = Vec3::new(0.0, 1.3, 0.0);
|
||||
|
||||
/// Where the camera is on lit frame `n`: held, circling slowly, or cut to a second view at --cut-at.
|
||||
fn eye(o: &Opts, n: u32) -> Transform {
|
||||
match o.camera {
|
||||
1 => {
|
||||
let a = n as f32 * 0.004;
|
||||
Transform::from_translation(LOOK + Quat::from_rotation_y(a) * (EYE - LOOK)).looking_at(LOOK, Vec3::Y)
|
||||
}
|
||||
2 if n >= o.cut_at => Transform::from_xyz(4.5, 3.2, 4.5).looking_at(LOOK, Vec3::Y),
|
||||
_ => Transform::from_translation(EYE).looking_at(LOOK, Vec3::Y),
|
||||
}
|
||||
}
|
||||
|
||||
/// The camera and the lights where they are this frame, and the switches, for the render world. A cut is a jump of
|
||||
/// more than a metre or 20 degrees in one frame: the history starts again.
|
||||
fn tick(o: Res<Opts>, time: Res<Time>, mut frame: ResMut<pass::Frame>, mut cam: Query<&mut Transform, With<Camera3d>>) {
|
||||
let t = o.t.unwrap_or(time.elapsed_secs());
|
||||
let n = pass::DRAWN.load(std::sync::atomic::Ordering::Relaxed);
|
||||
let mut cut = false;
|
||||
if let Ok(mut at) = cam.single_mut() {
|
||||
let to = eye(&o, n);
|
||||
cut = at.translation.distance(to.translation) > 1.0 || at.rotation.angle_between(to.rotation) > 20f32.to_radians();
|
||||
*at = to;
|
||||
}
|
||||
let lights = scene::lights(o.lights, t, o.scene == 1);
|
||||
let g = grid::build(&lights, 2.0);
|
||||
*frame = pass::Frame {
|
||||
grid_min: g.min.extend(g.cell),
|
||||
grid_dims: g.dims.extend(o.grid as u32),
|
||||
// the starts count from the buffer's beginning, the indices following them
|
||||
grid: g.start.iter().map(|s| s + g.start.len() as u32).chain(g.idx.iter().copied()).collect(),
|
||||
lights,
|
||||
mode: o.mode,
|
||||
k: o.k,
|
||||
view: o.view,
|
||||
frame: frame.frame.wrapping_add(1),
|
||||
exposure: o.exposure,
|
||||
brute: o.brute,
|
||||
raw: o.raw,
|
||||
cut,
|
||||
history: o.history,
|
||||
bounces: o.bounces,
|
||||
sun: SUN_TO.normalize().extend((o.sun_size * 0.5).to_radians()),
|
||||
sun_e: if o.sun { SUN_E.extend(0.0) } else { Vec4::ZERO },
|
||||
sky: (SKY * o.sky).extend(0.0),
|
||||
cache: o.cache,
|
||||
cell: o.cell,
|
||||
half: o.half,
|
||||
};
|
||||
}
|
||||
|
||||
fn shoot(mut commands: Commands, o: Res<Opts>, counts: Res<field::Counts>, target: Option<Res<Target>>, mut done: Local<bool>, mut clock: Local<Option<(std::time::Instant, u32)>>, mut gpu0: Local<Option<(u64, u32)>>) {
|
||||
let (Some(path), Some(target)) = (o.shot.clone(), target) else { return };
|
||||
// counted from the lighting pass's first frame, not from startup (its pipeline compiles meanwhile)
|
||||
let drawn = pass::DRAWN.load(std::sync::atomic::Ordering::Relaxed);
|
||||
if *done || drawn < o.frames + o.bench {
|
||||
if drawn >= o.frames && clock.is_none() {
|
||||
*clock = Some((std::time::Instant::now(), drawn));
|
||||
*gpu0 = Some((pass::GPU_NS.load(std::sync::atomic::Ordering::Relaxed), pass::GPU_FRAMES.load(std::sync::atomic::Ordering::Relaxed)));
|
||||
}
|
||||
return;
|
||||
}
|
||||
*done = true;
|
||||
if o.scene == 1 {
|
||||
let c = *counts;
|
||||
println!("LOD {} knots, {} culled, {} of {} triangles drawn ({:.1}%), detail {}, tau {} px, fov {} deg", c.knots, c.culled, c.drawn, c.full, c.drawn as f64 * 100.0 / c.full.max(1) as f64, if o.full { "full" } else { "adaptive" }, o.tau, o.fov);
|
||||
}
|
||||
if o.bench > 0 {
|
||||
let (t0, d0) = clock.unwrap();
|
||||
let ms = t0.elapsed().as_secs_f64() * 1000.0 / (drawn - d0).max(1) as f64;
|
||||
let r = |k: usize| pass::RAYS[k].load(std::sync::atomic::Ordering::Relaxed);
|
||||
println!("RAYS {:.2} a lit pixel (most {}), {} lit pixels", r(0) as f64 / r(1).max(1) as f64, r(2), r(1));
|
||||
let (ns, n) = (pass::GPU_NS.load(std::sync::atomic::Ordering::Relaxed), pass::GPU_FRAMES.load(std::sync::atomic::Ordering::Relaxed));
|
||||
let (ns0, n0) = gpu0.unwrap_or((0, 0));
|
||||
if n > n0 {
|
||||
println!("GPU lighting pass {:.2} ms ({} frames timed)", (ns - ns0) as f64 / 1e6 / (n - n0) as f64, n - n0);
|
||||
}
|
||||
println!("FRAME {ms:.2} ms, the GPU waited for ({} frames, {}x{}, {} lights, mode {} k {}, bounces {}{}{})", drawn - d0, o.size.x, o.size.y, o.lights, ["all", "uniform", "weighted"][o.mode as usize], o.k, o.bounces, if o.cache { ", cache" } else { "" }, if o.half { ", half-res" } else { "" });
|
||||
}
|
||||
commands.spawn(Screenshot::image(target.0.clone())).observe(move |shot: On<ScreenshotCaptured>, mut exit: MessageWriter<AppExit>| {
|
||||
match shot.image.clone().try_into_dynamic() {
|
||||
Ok(img) => match img.to_rgb8().save(&path) {
|
||||
Ok(()) => println!("SHOT {path}"),
|
||||
Err(e) => eprintln!("lightbench: saving {path}: {e}"),
|
||||
},
|
||||
Err(e) => eprintln!("lightbench: the frame: {e:?}"),
|
||||
}
|
||||
exit.write(AppExit::Success);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
//! The lighting pass (light.wgsl) in Bevy's render world: after Bevy's opaque pass has filled the depth and deferred
|
||||
//! prepasses, a compute pass lights every pixel into the camera's HDR main texture, which Bevy then tonemaps. The
|
||||
//! BVH's buffers are made once; the lights and the parameters each frame.
|
||||
|
||||
use crate::scene::{GpuLight, SceneGpu};
|
||||
use bevy::{
|
||||
core_pipeline::{
|
||||
core_3d::{main_opaque_pass_3d, main_transparent_pass_3d},
|
||||
prepass::ViewPrepassTextures,
|
||||
schedule::Core3d,
|
||||
Core3dSystems,
|
||||
},
|
||||
prelude::*,
|
||||
render::{
|
||||
extract_resource::{ExtractResource, ExtractResourcePlugin},
|
||||
render_resource::{
|
||||
binding_types::{storage_buffer_read_only_sized, storage_buffer_sized, texture_2d, texture_depth_2d, texture_storage_2d, uniform_buffer},
|
||||
*,
|
||||
},
|
||||
renderer::{RenderContext, RenderDevice, RenderQueue, ViewQuery},
|
||||
view::{ExtractedView, ViewTarget},
|
||||
RenderApp, RenderStartup,
|
||||
},
|
||||
};
|
||||
use std::sync::{atomic::{AtomicU32, Ordering}, Arc};
|
||||
|
||||
/// Frames the lighting pass has drawn, so a headless shot waits for its pipeline rather than for a number of frames.
|
||||
pub static DRAWN: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
/// The last frame read back (timing runs only): shadow rays, lit pixels, the most rays one pixel traced.
|
||||
pub static RAYS: [AtomicU32; 3] = [AtomicU32::new(0), AtomicU32::new(0), AtomicU32::new(0)];
|
||||
|
||||
/// The lighting pass's GPU time (timing runs, where the GPU has timestamps): nanoseconds summed, and frames timed.
|
||||
pub static GPU_NS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
pub static GPU_FRAMES: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
/// What this frame draws: the lights where they are now, and the switches.
|
||||
#[derive(Resource, Clone, Default, ExtractResource)]
|
||||
#[extract_app(RenderApp)]
|
||||
pub struct Frame {
|
||||
pub lights: Vec<GpuLight>,
|
||||
/// 0 every light, 1 uniform, 2 weighted
|
||||
pub mode: u32,
|
||||
pub k: u32,
|
||||
/// 0 lit, 1 normal, 2 albedo, 3 depth, 4 rays, 5 history, 6 lod, 7 bounce
|
||||
pub view: u32,
|
||||
pub frame: u32,
|
||||
pub exposure: f32,
|
||||
pub brute: bool,
|
||||
/// no history (--raw)
|
||||
pub raw: bool,
|
||||
/// the camera cut this frame: the history starts again
|
||||
pub cut: bool,
|
||||
/// the history's length in frames
|
||||
pub history: u32,
|
||||
/// the light grid (grid.rs): its corner and cell size, its cells along each axis and whether to use it, its lists
|
||||
pub grid_min: Vec4,
|
||||
pub grid_dims: UVec4,
|
||||
/// the grid's lists in one: the cells' starts (counted from the buffer's beginning), then the lights' indices
|
||||
pub grid: Vec<u32>,
|
||||
/// diffuse bounces a pixel follows (LB5)
|
||||
pub bounces: u32,
|
||||
/// the sun (LB6): the unit direction toward it and its angular radius; its irradiance (zero: none); the sky's
|
||||
/// radiance, which bounce rays that leave the scene bring back
|
||||
pub sun: Vec4,
|
||||
pub sun_e: Vec4,
|
||||
pub sky: Vec4,
|
||||
/// the bounce reads the radiance cache (LB7); a cell's size at 1 m from the camera
|
||||
pub cache: bool,
|
||||
pub cell: f32,
|
||||
/// the bounce traced for one pixel of each 2 x 2 block and upsampled (LB7)
|
||||
pub half: bool,
|
||||
}
|
||||
|
||||
pub struct LightPass;
|
||||
|
||||
impl Plugin for LightPass {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.init_resource::<Frame>().add_plugins((ExtractResourcePlugin::<Frame>::default(), ExtractResourcePlugin::<SceneGpu>::default()));
|
||||
let Some(render) = app.get_sub_app_mut(RenderApp) else { return };
|
||||
// timing a run (--bench): each frame waits for the GPU, so the frame time counts the GPU's work too
|
||||
if crate::timing() {
|
||||
render.add_systems(bevy::render::Render, wait.in_set(bevy::render::RenderSystems::Cleanup));
|
||||
}
|
||||
render.init_resource::<Buffers>().add_systems(RenderStartup, init).add_systems(
|
||||
Core3d,
|
||||
light.in_set(Core3dSystems::MainPass).after(main_opaque_pass_3d).before(main_transparent_pass_3d),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(ShaderType, Clone, Copy)]
|
||||
struct Params {
|
||||
world_from_clip: Mat4,
|
||||
eye: Vec4,
|
||||
size: UVec4,
|
||||
mode: UVec4,
|
||||
prev_clip_from_world: Mat4,
|
||||
prev_eye: Vec4,
|
||||
temporal: UVec4,
|
||||
grid_min: Vec4,
|
||||
grid_dims: UVec4,
|
||||
gi: UVec4,
|
||||
sun: Vec4,
|
||||
sun_e: Vec4,
|
||||
sky: Vec4,
|
||||
cache: Vec4,
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
struct Pipeline {
|
||||
layout: BindGroupLayoutDescriptor,
|
||||
id: CachedComputePipelineId,
|
||||
/// the radiance cache's resolve, after the pixels
|
||||
resolve: CachedComputePipelineId,
|
||||
/// the half-resolution bounce, before them
|
||||
half: CachedComputePipelineId,
|
||||
}
|
||||
|
||||
/// The BVH on the GPU, made from the SceneGpu it came from (by its pointer); the history's two pairs of textures
|
||||
/// (light, surface), read one frame and written the next; and the last frame's camera.
|
||||
#[derive(Resource, Default)]
|
||||
struct Buffers {
|
||||
from: Option<(usize, Buffer, Buffer)>,
|
||||
history: Option<(UVec2, [(Texture, TextureView); 4])>,
|
||||
prev: Option<(Mat4, Vec3)>,
|
||||
/// the ray counts the shader adds to, and where a timing run reads them back
|
||||
stats: Option<(Buffer, Buffer)>,
|
||||
/// the pass's start and end timestamps, resolved, read back; nanoseconds a tick
|
||||
timer: Option<(wgpu::QuerySet, wgpu::Buffer, wgpu::Buffer, f64)>,
|
||||
/// the radiance cache (cache.wgsl): its cells and their light
|
||||
cache: Option<(Buffer, Buffer)>,
|
||||
/// the half-resolution bounce (half.wgsl), one vec4 a 2 x 2 block
|
||||
half: Option<Buffer>,
|
||||
}
|
||||
|
||||
/// The radiance cache's slots (cache.wgsl's CELLS) and the words each takes.
|
||||
const CELLS: u64 = 262144;
|
||||
|
||||
fn init(mut commands: Commands, assets: Res<AssetServer>, cache: Res<PipelineCache>) {
|
||||
let read = |n: u64| storage_buffer_read_only_sized(false, std::num::NonZeroU64::new(n));
|
||||
let layout = BindGroupLayoutDescriptor::new(
|
||||
"lightbench_light",
|
||||
&BindGroupLayoutEntries::sequential(
|
||||
ShaderStages::COMPUTE,
|
||||
(
|
||||
uniform_buffer::<Params>(false),
|
||||
texture_depth_2d(),
|
||||
texture_2d(TextureSampleType::Uint),
|
||||
read(32),
|
||||
read(48),
|
||||
read(32),
|
||||
texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),
|
||||
texture_2d(TextureSampleType::Float { filterable: false }),
|
||||
texture_2d(TextureSampleType::Float { filterable: false }),
|
||||
texture_storage_2d(TextureFormat::Rgba32Float, StorageTextureAccess::WriteOnly),
|
||||
texture_storage_2d(TextureFormat::Rgba16Float, StorageTextureAccess::WriteOnly),
|
||||
storage_buffer_sized(false, std::num::NonZeroU64::new(16)),
|
||||
read(4),
|
||||
storage_buffer_sized(false, std::num::NonZeroU64::new(16)),
|
||||
storage_buffer_sized(false, std::num::NonZeroU64::new(24)),
|
||||
storage_buffer_sized(false, std::num::NonZeroU64::new(16)),
|
||||
),
|
||||
),
|
||||
);
|
||||
// the lighting, the rays it traces and the radiance cache, one module
|
||||
let shader = assets.add(bevy::shader::Shader::from_wgsl(concat!(include_str!("light.wgsl"), "\n", include_str!("trace.wgsl"), "\n", include_str!("cache.wgsl"), "\n", include_str!("half.wgsl")), "lightbench/light.wgsl"));
|
||||
// three entry points of one module, on one layout
|
||||
let base = ComputePipelineDescriptor { layout: vec![layout.clone()], shader, ..default() };
|
||||
let queue = |entry: &'static str| cache.queue_compute_pipeline(ComputePipelineDescriptor { label: Some(format!("lightbench_{entry}").into()), entry_point: Some(entry.into()), ..base.clone() });
|
||||
let (id, resolve, half) = (queue("main"), queue("resolve"), queue("trace_half"));
|
||||
commands.insert_resource(Pipeline { layout, id, resolve, half });
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
/// A 16-byte buffer: the ray counts and the timer's resolve and read-back.
|
||||
fn small(d: &wgpu::Device, label: &str, usage: wgpu::BufferUsages) -> wgpu::Buffer {
|
||||
d.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: 16, usage, mapped_at_creation: false })
|
||||
}
|
||||
|
||||
fn light(
|
||||
view: ViewQuery<(&ExtractedView, &ViewTarget, Option<&ViewPrepassTextures>)>,
|
||||
p: Option<Res<Pipeline>>,
|
||||
scene: Option<Res<SceneGpu>>,
|
||||
frame: Res<Frame>,
|
||||
mut bufs: ResMut<Buffers>,
|
||||
cache: Res<PipelineCache>,
|
||||
queue: Res<RenderQueue>,
|
||||
mut ctx: RenderContext,
|
||||
) {
|
||||
let (Some(p), Some(scene)) = (p, scene) else { return };
|
||||
let (extracted, target, prepass) = view.into_inner();
|
||||
let (Some(pipeline), Some(resolve), Some(half)) = (cache.get_compute_pipeline(p.id), cache.get_compute_pipeline(p.resolve), cache.get_compute_pipeline(p.half)) else { return };
|
||||
let Some(prepass) = prepass else { return };
|
||||
let (Some(depth), Some(gbuf)) = (prepass.depth_only_view(), prepass.deferred_view()) else { return };
|
||||
if target.main_texture_format() != TextureFormat::Rgba16Float || frame.lights.is_empty() {
|
||||
return;
|
||||
}
|
||||
let device: RenderDevice = ctx.render_device().clone();
|
||||
let key = Arc::as_ptr(&scene.tris) as usize;
|
||||
if bufs.from.as_ref().map(|b| b.0) != Some(key) {
|
||||
let make = |label: &str, bytes: &[u8]| device.create_buffer_with_data(&BufferInitDescriptor { label: Some(label), contents: bytes, usage: BufferUsages::STORAGE });
|
||||
let nodes = make("lightbench_nodes", bytemuck::cast_slice(&scene.nodes));
|
||||
let tris = make("lightbench_tris", bytemuck::cast_slice(&scene.tris));
|
||||
bufs.from = Some((key, nodes, tris));
|
||||
}
|
||||
let lights = device.create_buffer_with_data(&BufferInitDescriptor { label: Some("lightbench_lights"), contents: bytemuck::cast_slice(&frame.lights), usage: BufferUsages::STORAGE });
|
||||
let list = |label: &str, v: &[u32]| device.create_buffer_with_data(&BufferInitDescriptor { label: Some(label), contents: bytemuck::cast_slice(if v.is_empty() { &[0u32][..] } else { v }), usage: BufferUsages::STORAGE });
|
||||
let grid = list("lightbench_grid", &frame.grid);
|
||||
let size = target.main_texture().size();
|
||||
let want = UVec2::new(size.width, size.height);
|
||||
let fresh = bufs.history.as_ref().map(|h| h.0) != Some(want);
|
||||
if fresh {
|
||||
let make = |i: usize| {
|
||||
let t = device.create_texture(&TextureDescriptor {
|
||||
label: Some(["lightbench_hist_a", "lightbench_geo_a", "lightbench_hist_b", "lightbench_geo_b"][i]),
|
||||
size: Extent3d { width: want.x, height: want.y, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: TextureDimension::D2,
|
||||
// the light in f32 (a long history's 1 / n steps vanish in f16), the surface in f16
|
||||
format: if i % 2 == 0 { TextureFormat::Rgba32Float } else { TextureFormat::Rgba16Float },
|
||||
usage: TextureUsages::STORAGE_BINDING | TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
});
|
||||
let v = t.create_view(&TextureViewDescriptor::default());
|
||||
(t, v)
|
||||
};
|
||||
bufs.history = Some((want, [make(0), make(1), make(2), make(3)]));
|
||||
// a block's bounce, a 2 x 2 block a vec4
|
||||
let blocks = (want.x.div_ceil(2) * want.y.div_ceil(2)) as u64;
|
||||
bufs.half = Some(device.create_buffer(&BufferDescriptor { label: Some("lightbench_bounce_half"), size: blocks * 16, usage: BufferUsages::STORAGE, mapped_at_creation: false }));
|
||||
}
|
||||
let world_from_clip = extracted.world_from_view.to_matrix() * extracted.clip_from_view.inverse();
|
||||
let clip_from_world = extracted.clip_from_view * extracted.world_from_view.to_matrix().inverse();
|
||||
let eye = extracted.world_from_view.translation();
|
||||
let (prev_clip_from_world, prev_eye) = bufs.prev.unwrap_or((clip_from_world, eye));
|
||||
let reset = fresh || frame.cut || bufs.prev.is_none();
|
||||
bufs.prev = Some((clip_from_world, eye));
|
||||
if bufs.stats.is_none() {
|
||||
let make = |label: &str, usage: BufferUsages| Buffer::from(small(device.wgpu_device(), label, usage));
|
||||
bufs.stats = Some((make("lightbench_stats", BufferUsages::STORAGE | BufferUsages::COPY_DST | BufferUsages::COPY_SRC), make("lightbench_stats_read", BufferUsages::MAP_READ | BufferUsages::COPY_DST)));
|
||||
}
|
||||
if bufs.timer.is_none() && crate::timing() && device.features().contains(WgpuFeatures::TIMESTAMP_QUERY) {
|
||||
let d = device.wgpu_device();
|
||||
let set = d.create_query_set(&wgpu::QuerySetDescriptor { label: Some("lightbench_timer"), ty: wgpu::QueryType::Timestamp, count: 2 });
|
||||
let resolve = small(d, "lightbench_timer_resolve", wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC);
|
||||
let read = small(d, "lightbench_timer_read", wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ);
|
||||
bufs.timer = Some((set, resolve, read, queue.get_timestamp_period() as f64));
|
||||
}
|
||||
if bufs.cache.is_none() {
|
||||
let make = |label: &str, size: u64| device.create_buffer(&BufferDescriptor { label: Some(label), size, usage: BufferUsages::STORAGE, mapped_at_creation: false });
|
||||
bufs.cache = Some((make("lightbench_cells", CELLS * 6 * 4), make("lightbench_cell_light", CELLS * 16)));
|
||||
}
|
||||
let (cells, cell_light) = bufs.cache.as_ref().unwrap();
|
||||
let half_res = frame.half && (frame.cache || frame.bounces > 0);
|
||||
let (stats, readback) = bufs.stats.as_ref().unwrap();
|
||||
queue.write_buffer(stats, 0, &[0u8; 16]);
|
||||
let (_, nodes, tris) = bufs.from.as_ref().unwrap();
|
||||
// even frames read pair a and write pair b, odd frames the other way
|
||||
let h = &bufs.history.as_ref().unwrap().1;
|
||||
let (r, w) = if frame.frame % 2 == 0 { (0, 2) } else { (2, 0) };
|
||||
let mut params = UniformBuffer::from(Params {
|
||||
world_from_clip,
|
||||
eye: extracted.world_from_view.translation().extend(frame.exposure),
|
||||
size: UVec4::new(size.width, size.height, frame.lights.len() as u32, frame.frame),
|
||||
mode: UVec4::new(frame.mode, frame.k, frame.view, frame.brute as u32),
|
||||
prev_clip_from_world,
|
||||
prev_eye: prev_eye.extend(0.0),
|
||||
temporal: UVec4::new(frame.raw as u32, reset as u32, frame.history.max(1), 0),
|
||||
grid_min: frame.grid_min,
|
||||
grid_dims: frame.grid_dims,
|
||||
gi: UVec4::new(frame.bounces, frame.cache as u32, half_res as u32, 0),
|
||||
sun: frame.sun,
|
||||
sun_e: frame.sun_e,
|
||||
sky: frame.sky,
|
||||
cache: Vec4::new(frame.cell, 4096.0, 0.0, 0.0),
|
||||
});
|
||||
params.write_buffer(&device, &queue);
|
||||
let group = device.create_bind_group(
|
||||
"lightbench_light",
|
||||
&cache.get_bind_group_layout(&p.layout),
|
||||
&BindGroupEntries::sequential((params.binding().unwrap(), depth, gbuf, nodes.as_entire_binding(), tris.as_entire_binding(), lights.as_entire_binding(), target.main_texture_view(), &h[r].1, &h[r + 1].1, &h[w].1, &h[w + 1].1, stats.as_entire_binding(), grid.as_entire_binding(), bufs.half.as_ref().unwrap().as_entire_binding(), cells.as_entire_binding(), cell_light.as_entire_binding())),
|
||||
);
|
||||
let encoder = ctx.command_encoder();
|
||||
// timed at the pass's own start and end: Apple's GPUs take timestamps there, not inside passes or between them
|
||||
let timer = bufs.timer.as_ref();
|
||||
let writes = timer.map(|(set, ..)| wgpu::ComputePassTimestampWrites { query_set: set, beginning_of_pass_write_index: Some(0), end_of_pass_write_index: Some(1) });
|
||||
let mut pass = encoder.begin_compute_pass(&ComputePassDescriptor { label: Some("lightbench_light"), timestamp_writes: writes });
|
||||
pass.set_bind_group(0, &group, &[]);
|
||||
// the bounce at half resolution first, so the pixels can take it up
|
||||
if half_res {
|
||||
pass.set_pipeline(half);
|
||||
pass.dispatch_workgroups(size.width.div_ceil(2).div_ceil(8), size.height.div_ceil(2).div_ceil(8), 1);
|
||||
}
|
||||
pass.set_pipeline(pipeline);
|
||||
pass.dispatch_workgroups(size.width.div_ceil(8), size.height.div_ceil(8), 1);
|
||||
// a dispatch is its own usage scope, so the resolve sees every pixel's samples
|
||||
if frame.cache {
|
||||
pass.set_pipeline(resolve);
|
||||
pass.dispatch_workgroups((CELLS / 64) as u32, 1, 1);
|
||||
}
|
||||
drop(pass);
|
||||
encoder.copy_buffer_to_buffer(stats, 0, readback, 0, 16);
|
||||
if let Some(t) = timer {
|
||||
encoder.resolve_query_set(&t.0, 0..2, &t.1, 0);
|
||||
encoder.copy_buffer_to_buffer(&t.1, 0, &t.2, 0, 16);
|
||||
}
|
||||
DRAWN.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn wait(device: Res<RenderDevice>, bufs: Res<Buffers>) {
|
||||
let _ = device.poll(PollType::wait_indefinitely());
|
||||
// the frame is done: read its ray counts back
|
||||
let Some((_, readback)) = bufs.stats.as_ref() else { return };
|
||||
let slice = readback.slice(..);
|
||||
slice.map_async(MapMode::Read, |_| {});
|
||||
let _ = device.poll(PollType::wait_indefinitely());
|
||||
{
|
||||
let Ok(data) = slice.get_mapped_range() else { return };
|
||||
let v: &[u32] = bytemuck::cast_slice(&data);
|
||||
for (k, n) in RAYS.iter().enumerate() {
|
||||
n.store(v[k], Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
readback.unmap();
|
||||
let Some((_, _, read, period)) = bufs.timer.as_ref() else { return };
|
||||
let slice = read.slice(..);
|
||||
slice.map_async(wgpu::MapMode::Read, |_| {});
|
||||
let _ = device.poll(PollType::wait_indefinitely());
|
||||
{
|
||||
let Ok(data) = slice.get_mapped_range() else { return };
|
||||
let t: &[u64] = bytemuck::cast_slice(&data);
|
||||
if t[1] > t[0] {
|
||||
GPU_NS.fetch_add(((t[1] - t[0]) as f64 * period) as u64, Ordering::Relaxed);
|
||||
GPU_FRAMES.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
read.unmap();
|
||||
}
|
||||
Loaded 100 of 706 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user