mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 06:53:19 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
61f6113845 | ||
|
|
1ff507df80 | ||
|
|
5cc53609a8 | ||
|
|
b4aede8ae6 | ||
|
|
3df38e170a | ||
|
|
b593ebb070 | ||
|
|
9a6cd12d5f | ||
|
|
0b8171cdae | ||
|
|
2c54a94c00 | ||
|
|
6ee015071d | ||
|
|
8d44a1e865 | ||
|
|
c93042ff7f | ||
|
|
3db55f345d | ||
|
|
43e35b2302 | ||
|
|
9c5ab64141 | ||
|
|
620cfe0744 | ||
|
|
de4d619270 | ||
|
|
e946a5a0d7 | ||
|
|
6c390a4a17 | ||
|
|
ab2a085a05 | ||
|
|
b7f796aa5e | ||
|
|
e8ce27fd62 | ||
|
|
9202d88e69 | ||
|
|
2a5bb19904 | ||
|
|
09c2df6e8c | ||
|
|
2a98bbcb03 | ||
|
|
8443ecf2e7 | ||
|
|
4a8c5c04ad | ||
|
|
57e0737edd | ||
|
|
75c6e74d6d | ||
|
|
4b1cb9ec9a | ||
|
|
db3cbfcaf5 | ||
|
|
25afb7cbf5 | ||
|
|
1046ee9a83 | ||
|
|
dc2e7a56bb | ||
|
|
977ec312aa | ||
|
|
9aee93e518 | ||
|
|
32dcec11b9 | ||
|
|
3a646fa4bb | ||
|
|
28f4c2289b | ||
|
|
80fbde3c58 | ||
|
|
c30bcfbbef | ||
|
|
3ad88f635a | ||
|
|
3cd7f72b4b | ||
|
|
2262e1cc7d | ||
|
|
4f354e97fc | ||
|
|
1afb2de58d | ||
|
|
b0cd52fd85 | ||
|
|
b5425278b3 | ||
|
|
373b47b964 | ||
|
|
2b9a95366a | ||
|
|
4a27753595 | ||
|
|
ab0fc62c4c | ||
|
|
0cf78fb053 | ||
|
|
6d8a15ac55 | ||
|
|
cdebceb9d9 | ||
|
|
523fd30929 | ||
|
|
688e99c971 | ||
|
|
71b354007f | ||
|
|
8883c30c53 | ||
|
|
9586aa9689 | ||
|
|
760aea017d | ||
|
|
1c004cc225 | ||
|
|
a0f85c9023 | ||
|
|
fc32762987 | ||
|
|
9365faa43b | ||
|
|
7c32e7cec9 |
No files matched your search
Generated
+33
@@ -13975,6 +13975,7 @@ dependencies = [
|
||||
"raea-io-media",
|
||||
"raea-runtime-bundle",
|
||||
"raea-runtime-export",
|
||||
"raea-sys-kimodo",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
@@ -14730,6 +14731,7 @@ dependencies = [
|
||||
"blitz-traits",
|
||||
"image",
|
||||
"keyboard-types",
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-io-net-calls",
|
||||
"raea-io-os",
|
||||
@@ -14988,6 +14990,24 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-appscreen"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bevy",
|
||||
"blitz-traits",
|
||||
"keyboard-types",
|
||||
"raea-io-home",
|
||||
"raea-page",
|
||||
"raea-runtime-bundle",
|
||||
"raea-runtime-dom",
|
||||
"raea-runtime-js",
|
||||
"raea-runtime-jsengine",
|
||||
"raea-sys-fonts",
|
||||
"raea-sys-page",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-runtime-bake"
|
||||
version = "0.1.0"
|
||||
@@ -15283,6 +15303,7 @@ dependencies = [
|
||||
"raea-io-net",
|
||||
"raea-page",
|
||||
"raea-render",
|
||||
"raea-runtime-appscreen",
|
||||
"raea-runtime-input",
|
||||
"raea-runtime-react",
|
||||
"raea-runtime-twins",
|
||||
@@ -15866,6 +15887,18 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-kimodo"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"mlx-rs",
|
||||
"raea-sys-ml",
|
||||
"raea-sys-mlx",
|
||||
"serde_json",
|
||||
"tokenizers",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-layers"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -81,6 +81,7 @@ members = [
|
||||
"systems/mix",
|
||||
"systems/ml",
|
||||
"systems/mlx",
|
||||
"systems/kimodo",
|
||||
"systems/speech",
|
||||
"systems/layout",
|
||||
"systems/vision",
|
||||
@@ -167,6 +168,7 @@ members = [
|
||||
"runtime/export",
|
||||
"runtime/live",
|
||||
"runtime/page",
|
||||
"runtime/appscreen",
|
||||
"runtime/sound",
|
||||
"runtime/look",
|
||||
"runtime/scene",
|
||||
|
||||
@@ -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,23 +0,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, 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.
|
||||
@@ -175,7 +175,6 @@ LICENSES/<crate>-<version>/.
|
||||
deterministic-hash 1.0.2: MIT
|
||||
disjoint-sets 0.4.2: MIT/Apache-2.0
|
||||
dot_vox 5.2.0: MIT
|
||||
dyn-clone 1.0.20: MIT OR Apache-2.0
|
||||
dyn-eq 0.1.3: MPL-2.0
|
||||
dyn-hash 1.0.0: MIT OR Apache-2.0
|
||||
earcut 0.4.5: ISC
|
||||
|
||||
+1
-10
@@ -101,10 +101,7 @@ pub fn export(args: &[String]) -> R<String> {
|
||||
gather(&mut bundle, &dir, &game, &mut got)?;
|
||||
std::fs::write(&js, &bundle).map_err(|e| e.to_string())?;
|
||||
|
||||
// an app screen needs a player with the surface runtime (the `surfaces` feature), which the size-built one leaves out
|
||||
if got.files.iter().any(|(rel, _)| rel.ends_with(raea_runtime_page::screen::BUNDLED)) && !player_has_surfaces(&player)? {
|
||||
return Err(format!("this game has an app screen (<Screen app>), and the player {} can't run one: build it with them (cargo build --profile game -p raea-app-game --bin raea-game --features player,surfaces) and export again", player.display()));
|
||||
}
|
||||
// an app screen (<Screen app>) draws on the player's own Blitz page (raea-runtime-appscreen): every player has one
|
||||
|
||||
// 3. what play works out at open, worked out now from the package itself (so the package is known to load)
|
||||
let src = std::fs::read_to_string(&tsx).unwrap_or_default();
|
||||
@@ -255,12 +252,6 @@ pub(crate) fn imported(dir: &Path, file: &Path) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether the player at `bin` was built with the surface runtime (app screens): its shim's text is in it.
|
||||
pub(crate) fn player_has_surfaces(bin: &Path) -> R<bool> {
|
||||
let bytes = std::fs::read(bin).map_err(|e| format!("{}: {e}", bin.display()))?;
|
||||
Ok(bytes.windows(14).any(|w| w == b"__surfaceFrame"))
|
||||
}
|
||||
|
||||
pub(crate) fn default_name(tsx: &Path) -> String {
|
||||
let stem = tsx.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
|
||||
let base = if stem == "edit" { tsx.parent().and_then(|p| p.file_name()).map(|s| s.to_string_lossy().to_string()).unwrap_or(stem) } else { stem };
|
||||
|
||||
+13
-5
@@ -105,13 +105,21 @@ pub(crate) fn gather(bundle: &mut String, dir: &Path, game: &Path, got: &mut Gat
|
||||
let ext = file.extension().and_then(|x| x.to_str()).unwrap_or("").to_ascii_lowercase();
|
||||
if SOURCE_EXTS.contains(&ext.as_str()) || file.file_name().is_some_and(|n| n == MANIFEST) {
|
||||
// an app screen's module (`<Screen app="chat.tsx">`, a component on react-dom): bundled now with its npm
|
||||
// packages beside where it was, as `chat.tsx.surface.js`, which the player opens (it bundles nothing)
|
||||
// packages beside where it was, as `chat.tsx.surface.js` and its CSS `chat.tsx.surface.css`, which the
|
||||
// player opens (it bundles nothing; raea-runtime-appscreen code_of)
|
||||
if matches!(ext.as_str(), "tsx" | "jsx") && std::fs::read_to_string(&file).is_ok_and(|t| t.contains("export default") && !t.contains("registerRoot(")) && !imported(dir, &file) {
|
||||
if let Some(rel) = inside(&file) {
|
||||
let rel = format!("{rel}{}", raea_runtime_page::screen::BUNDLED);
|
||||
if !got.has(&rel) {
|
||||
raea_runtime_react::scene::bundle_surface(&file, &game.join(&rel))?;
|
||||
got.files.push((rel, file.clone()));
|
||||
let (js_rel, css_rel) = (format!("{rel}{}", raea_runtime_page::screen::BUNDLED), format!("{rel}{}", raea_runtime_page::screen::BUNDLED_CSS));
|
||||
if !got.has(&js_rel) {
|
||||
let (js, css) = raea_runtime_page::screen::build_app(&file)?;
|
||||
for (r, text) in [(&js_rel, js), (&css_rel, css)] {
|
||||
let out = game.join(r);
|
||||
if let Some(d) = out.parent() {
|
||||
std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
|
||||
}
|
||||
std::fs::write(&out, text).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
got.files.push((r.clone(), file.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,6 +237,10 @@ pub(crate) fn offscreen(mut run: Run, json: Option<String>, flat_out: bool, snap
|
||||
if let Some((x, y, down)) = run.pointer {
|
||||
e["pointer"] = serde_json::json!({"x": x, "y": y, "down": down});
|
||||
}
|
||||
// what reached its app screens (the keys they took aren't the page's above), given them again in a render
|
||||
if let Some(apps) = live.app_input() {
|
||||
e["apps"] = apps;
|
||||
}
|
||||
// the session's seed and start with its first frame: a render of the log draws the same Math.random and Date
|
||||
if logged.is_empty() {
|
||||
e["session"] = live.session();
|
||||
|
||||
+59
-10
@@ -1,6 +1,7 @@
|
||||
//! `raea app bundle` on the web target: a Mac app that opens the page in raea-page-host's window. App.app/Contents has
|
||||
//! the page host, the app's script and stylesheet in Resources/, and a launcher in MacOS/ that starts the host on them
|
||||
//! at the app's title and size, signed by the developer (sign.rs, T1d).
|
||||
//! at the app's title and size, signed by the developer (sign.rs, T1d). The launcher runs the host as its child and
|
||||
//! waits for it: a launcher that execs it leaves the app without a pid in AppKit (#163, `launcher`).
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -37,6 +38,20 @@ fn sh(s: &str) -> String {
|
||||
format!("'{}'", s.replace('\'', "'\\''"))
|
||||
}
|
||||
|
||||
/// The app's executable (Contents/MacOS/NAME): the page host in Resources, on the app's script and stylesheet, in a
|
||||
/// window at the app's title and size. The host is this script's child, never exec'd in its place: when the process
|
||||
/// macOS launched execs another program, AppKit keeps the app's bundle id but loses its pid (NSRunningApplication's
|
||||
/// processIdentifier -1), so window managers that find an app's windows by its pid never see the window (#163). The
|
||||
/// host still checks in as the app, from inside it; a signal to the launcher is passed on to it.
|
||||
fn launcher(name: &str, size: (u32, u32)) -> String {
|
||||
format!(
|
||||
"#!/bin/sh\n# made by raea app bundle: the page in raea-page-host's window, the host this script's child (an exec loses the app's pid)\nR=\"$(cd \"$(dirname \"$0\")/../Resources\" && pwd)\"\n\"$R/raea-page-host\" \"$R/app.js\" --css \"$R/app.css\" --window --title {} --size {}x{} &\nhost=$!\ntrap 'kill -TERM \"$host\" 2>/dev/null' TERM INT HUP\nwait \"$host\"\n",
|
||||
sh(name),
|
||||
size.0,
|
||||
size.1
|
||||
)
|
||||
}
|
||||
|
||||
/// The bundle id from the title: ascii letters and digits, under app.raea.local
|
||||
fn bundle_id(title: &str) -> String {
|
||||
let id: String = title.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_lowercase();
|
||||
@@ -58,20 +73,54 @@ pub fn web(a: &Ask) -> Result<String, String> {
|
||||
std::fs::copy(&host, res.join("raea-page-host")).map_err(|e| format!("{}: {e}", host.display()))?;
|
||||
let name = &a.title;
|
||||
std::fs::write(contents.join("Info.plist"), plist(name, &bundle_id(name))).map_err(|e| e.to_string())?;
|
||||
let launcher = macos.join(name);
|
||||
let script = format!(
|
||||
"#!/bin/sh\n# made by raea app bundle: the page in raea-page-host's window\nR=\"$(cd \"$(dirname \"$0\")/../Resources\" && pwd)\"\nexec \"$R/raea-page-host\" \"$R/app.js\" --css \"$R/app.css\" --window --title {} --size {}x{}\n",
|
||||
sh(name),
|
||||
a.size.0,
|
||||
a.size.1
|
||||
);
|
||||
std::fs::write(&launcher, script).map_err(|e| e.to_string())?;
|
||||
let exe = macos.join(name);
|
||||
std::fs::write(&exe, launcher(name, a.size)).map_err(|e| e.to_string())?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).map_err(|e| e.to_string())?;
|
||||
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let mut said = crate::sign::sign(&out, &a.sign)?;
|
||||
said.push(format!("{} (web)", out.display()));
|
||||
Ok(said.join("\n"))
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::process::Command;
|
||||
|
||||
/// The launcher run as macOS runs an app's executable, with a page host that writes down its own pid, its parent's
|
||||
/// and its arguments, and exits 3: the host must be the launcher's child (an exec ran it in the launcher's
|
||||
/// process, the pid macOS launched, and AppKit lost the app's pid: #163), on the app's files, and the launcher must
|
||||
/// end with the host's status.
|
||||
#[test]
|
||||
fn the_host_runs_as_the_launchers_child() {
|
||||
// canonical, so the launcher's own `pwd` names Resources as this test does (macOS's temp folder is a link)
|
||||
let dir = std::env::temp_dir().canonicalize().unwrap().join(format!("raea-macapp-launcher-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let (macos, res) = (dir.join("T.app/Contents/MacOS"), dir.join("T.app/Contents/Resources"));
|
||||
std::fs::create_dir_all(&macos).unwrap();
|
||||
std::fs::create_dir_all(&res).unwrap();
|
||||
let ran = res.join("ran");
|
||||
let host = res.join("raea-page-host");
|
||||
std::fs::write(&host, format!("#!/bin/sh\necho \"$$ $PPID $*\" > '{}'\nexit 3\n", ran.display())).unwrap();
|
||||
let exe = macos.join("T");
|
||||
std::fs::write(&exe, super::launcher("My App", (800, 600))).unwrap();
|
||||
for f in [&host, &exe] {
|
||||
std::fs::set_permissions(f, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let mut child = Command::new(&exe).spawn().unwrap();
|
||||
let launched = child.id().to_string();
|
||||
let status = child.wait().unwrap();
|
||||
let said = std::fs::read_to_string(&ran).unwrap();
|
||||
let mut words = said.split_whitespace();
|
||||
let (pid, parent) = (words.next().unwrap(), words.next().unwrap());
|
||||
assert_ne!(pid, launched, "the host ran in the launcher's own process (exec'd): {said}");
|
||||
assert_eq!(parent, launched, "the host isn't the launcher's child: {said}");
|
||||
let args = format!("{0}/app.js --css {0}/app.css --window --title My App --size 800x600", res.display());
|
||||
assert_eq!(said.trim_end().splitn(3, ' ').nth(2), Some(args.as_str()));
|
||||
assert_eq!(status.code(), Some(3), "the launcher didn't end with the host's status");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,7 @@ pub fn host(args: &[String]) -> Result<String, String> {
|
||||
let p = Path::new(a);
|
||||
if p.extension().is_some_and(|x| x == "tsx" || x == "ts" || x == "jsx") && p.is_file() {
|
||||
std::fs::create_dir_all(&work).map_err(|e| format!("{}: {e}", work.display()))?;
|
||||
let (js, css) = raea_runtime_bundle::inproc::app::bundle(p, &raea_io_home::home())?;
|
||||
let (js, css) = raea_runtime_bundle::inproc::app::bundle(p, &raea_io_home::home(), raea_runtime_bundle::inproc::app::WINDOW)?;
|
||||
let script = work.join(format!("{}.js", p.file_stem().unwrap_or_default().to_string_lossy()));
|
||||
std::fs::write(&script, js).map_err(|e| format!("{}: {e}", script.display()))?;
|
||||
handed.push(script.display().to_string());
|
||||
|
||||
@@ -24,7 +24,7 @@ pub struct Built {
|
||||
pub fn build(app: &Path, dir: &Path) -> Result<Built, String> {
|
||||
let app = raea_io_home::plain(app.canonicalize().map_err(|e| format!("{}: {e}", app.display()))?);
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let (js, imported) = raea_runtime_bundle::inproc::app::bundle(&app, &raea_io_home::home())?;
|
||||
let (js, imported) = raea_runtime_bundle::inproc::app::bundle(&app, &raea_io_home::home(), raea_runtime_bundle::inproc::app::WINDOW)?;
|
||||
let folder = app.parent().unwrap_or(Path::new("."));
|
||||
let tw = raea_runtime_bundle::styles::tailwind(folder)?;
|
||||
let built = Built { js: dir.join("app.js"), css: dir.join("app.css") };
|
||||
|
||||
@@ -16,3 +16,7 @@ serde_json = "1"
|
||||
# the verbs' flags read as a render reads its own
|
||||
raea-runtime-bundle = { path = "../../runtime/bundle" }
|
||||
raea-runtime-export = { path = "../../runtime/export" }
|
||||
|
||||
# `raea motion`: Kimodo on MLX, Apple silicon's
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
raea-sys-kimodo = { path = "../../systems/kimodo" }
|
||||
@@ -4,6 +4,8 @@
|
||||
//! made.app, fal, Replicate, OpenRouter, Modal and ComfyUI, with sao as the local model: apps/tools/src/generate.rs).
|
||||
|
||||
pub mod generate;
|
||||
/// `raea motion`: body motion made on this Mac by Kimodo on MLX (raea-sys-kimodo)
|
||||
pub mod motion;
|
||||
pub mod song;
|
||||
pub mod sound;
|
||||
pub mod splat;
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
//! `raea motion "LINE" [--keys KEYS.json] ...`: body motion made on this Mac by Kimodo (raea-sys-kimodo, on MLX): a
|
||||
//! SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a
|
||||
//! root path: what sdk/body/tools/between.ts writes). The clip is the file sdk/body/tools/fromkimodo.ts reads, the
|
||||
//! same one the cloud runner wrote (docs/character.feature CH15b, CH15c).
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use raea_runtime_bundle::flag;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
pub const USAGE: &str = "raea motion \"LINE\" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--steps 100] [-o CLIP.json]";
|
||||
pub const ABOUT: &str = "body motion made on this Mac by Kimodo (NVIDIA, on MLX): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads; the first use fetches the motion model (1.1 GB) into raea's models folder, and the first new line its text encoder (8.8 GB: Llama 3 8B in 8 bits with LLM2Vec's adapters); a line's words are read once and kept. Licences: Kimodo's weights NVIDIA's Open Model License, Meta Llama 3 the Meta Llama 3 Community License, LLM2Vec's adapters MIT";
|
||||
|
||||
fn number(args: &[String], name: &str, default: f64) -> R<f64> {
|
||||
match flag(args, name) {
|
||||
None => Ok(default),
|
||||
Some(v) => v.parse::<f64>().ok().filter(|n| n.is_finite() && *n >= 0.0).ok_or(format!("{name} takes a number, got `{v}`")),
|
||||
}
|
||||
}
|
||||
|
||||
fn line(args: &[String]) -> String {
|
||||
const WITH_VALUE: [&str; 6] = ["--keys", "--seconds", "--frames", "--seed", "--steps", "-o"];
|
||||
let mut out = Vec::new();
|
||||
let mut i = 1;
|
||||
while i < args.len() {
|
||||
if WITH_VALUE.contains(&args[i].as_str()) {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if !args[i].starts_with("--") {
|
||||
out.push(args[i].as_str());
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
out.join(" ")
|
||||
}
|
||||
|
||||
/// what a call asks for, read from its words and flags
|
||||
struct Ask {
|
||||
words: String,
|
||||
keys: Option<String>,
|
||||
constraints: Option<serde_json::Value>,
|
||||
frames: usize,
|
||||
seed: u64,
|
||||
steps: usize,
|
||||
out: Option<String>,
|
||||
}
|
||||
|
||||
pub fn motion(args: &[String]) -> R<String> {
|
||||
let words = line(args);
|
||||
let keys = flag(args, "--keys");
|
||||
if words.trim().is_empty() && keys.is_none() {
|
||||
return Err(format!("{USAGE}\n ({ABOUT})"));
|
||||
}
|
||||
let frames = match flag(args, "--frames") {
|
||||
Some(_) => number(args, "--frames", 150.0)? as usize,
|
||||
None => (number(args, "--seconds", 5.0)? * 30.0).round() as usize,
|
||||
};
|
||||
if !(2..=600).contains(&frames) {
|
||||
return Err(format!("a clip is 2 to 600 frames (20 s at 30 a second), asked {frames}"));
|
||||
}
|
||||
let constraints = match &keys {
|
||||
Some(p) => Some(serde_json::from_str::<serde_json::Value>(&std::fs::read_to_string(p).map_err(|e| format!("{p}: {e}"))?).map_err(|e| format!("{p}: {e}"))?),
|
||||
None => None,
|
||||
};
|
||||
let (seed, steps) = (number(args, "--seed", 1.0)? as u64, (number(args, "--steps", 100.0)? as usize).max(2));
|
||||
make(Ask { words, keys, constraints, frames, seed, steps, out: flag(args, "-o") })
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn make(ask: Ask) -> R<String> {
|
||||
Err(format!("raea motion runs Kimodo on MLX, on Apple silicon's GPU: {:?} can be made on a Mac", ask.words))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn make(ask: Ask) -> R<String> {
|
||||
// float32 as checked against PyTorch: MLX's TF32 matmuls off, before the first one
|
||||
if std::env::var_os("MLX_ENABLE_TF32").is_none() {
|
||||
unsafe { std::env::set_var("MLX_ENABLE_TF32", "0") };
|
||||
}
|
||||
let t0 = std::time::Instant::now();
|
||||
// a line every 512 MB of each file fetched
|
||||
let mut shown = std::collections::HashMap::<String, u64>::new();
|
||||
let mut progress = |file: &str, n: u64| {
|
||||
if shown.insert(file.to_string(), n >> 29) != Some(n >> 29) {
|
||||
eprintln!("raea motion: fetching {file}: {} MB", n >> 20);
|
||||
}
|
||||
};
|
||||
let mut k = raea_sys_kimodo::Kimodo::fetch(&mut progress).map_err(|e| format!("raea motion: {e}"))?;
|
||||
let (clean, emb) = k.encode(&ask.words).map_err(|e| format!("raea motion: {e}"))?;
|
||||
let load_s = t0.elapsed().as_secs_f64();
|
||||
let made_from = raea_sys_kimodo::Ask { line: &ask.words, frames: ask.frames, seed: ask.seed, steps: ask.steps, constraints: ask.constraints.as_ref(), cfg: (2.0, 2.0) };
|
||||
let t1 = std::time::Instant::now();
|
||||
let made = k.make(&made_from, emb.as_deref(), None).map_err(|e| format!("raea motion: {e}"))?;
|
||||
let gen_s = t1.elapsed().as_secs_f64();
|
||||
let clip = raea_sys_kimodo::decode::clip_json(&made.motion, &k.skeleton, ask.seed, ask.steps, &clean, ask.constraints.is_some());
|
||||
// without -o, the line's words name the file
|
||||
let out = PathBuf::from(ask.out.unwrap_or_else(|| {
|
||||
let slug = clean.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()).map(str::to_lowercase).collect::<Vec<_>>().join("-");
|
||||
format!("{}.clip.json", if slug.is_empty() { "keys".to_string() } else { slug.chars().take(60).collect() })
|
||||
}));
|
||||
std::fs::write(&out, serde_json::to_string(&clip).unwrap_or_default()).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
let r = &made.motion.root;
|
||||
let (a, b) = (r[0], r[r.len() - 1]);
|
||||
let travel = ((b[0] - a[0]).powi(2) + (b[2] - a[2]).powi(2)).sqrt();
|
||||
Ok(format!(
|
||||
"APPLIED motion {:?}{}, {} frames ({:.1} s), seed {}, {} steps -> {} (made on this Mac in {gen_s:.1} s after {load_s:.1} s loading and reading the line; the hips end {travel:.2} m from where they start)",
|
||||
clean,
|
||||
if ask.keys.is_some() { " with keys" } else { "" },
|
||||
ask.frames,
|
||||
ask.frames as f64 / 30.0,
|
||||
ask.seed,
|
||||
ask.steps,
|
||||
out.display()
|
||||
))
|
||||
}
|
||||
Executable
+29
@@ -0,0 +1,29 @@
|
||||
#!/bin/bash
|
||||
# #159: --aov and RAEA_PASS on a multisampled 3D camera write every frame. Both read the camera's prepasses as
|
||||
# single-sampled textures, so they turn its multisampling off; the camera row's post-processing turned it back on: in
|
||||
# a render, on the first frame whose post changed (ramp.tsx's bloom ramps); in a game, on every frame its rows set
|
||||
# (game.tsx). Frame 2 was then refused ("Texture binding 0 expects multisampled = false, but given a view with
|
||||
# samples = 4"), with frames 0 and 1 written. Here frames 0 to 5 of each are rendered: --aov must write each frame's
|
||||
# depth and motion at the frame's size (320 x 180 floats: 4 and 8 bytes a pixel), the depth not all zero (something
|
||||
# drawn), and RAEA_PASS=depth all six pictures. Exits 1 on a failure.
|
||||
# bench/aov-msaa/check.sh (RAEA_BIN: the raea to run, default target/release/raea)
|
||||
cd "$(dirname "$0")/../.." || exit 2
|
||||
BIN=${RAEA_BIN:-$PWD/target/release/raea}
|
||||
AT=0,1,2,3,4,5
|
||||
export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0 RAEA_AUDIO_MUTE=1
|
||||
OUT=$(mktemp -d "${TMPDIR:-/tmp}/raea-aov-msaa.XXXXXX")
|
||||
trap 'rm -rf "$OUT"' EXIT
|
||||
refused() { grep -m1 REFUSED "$1" || tail -3 "$1"; }
|
||||
for c in ramp game; do
|
||||
"$BIN" render "bench/aov-msaa/$c.tsx" --at "$AT" --aov -o "$OUT/$c" > "$OUT/$c.log" 2>&1 || { echo "FAIL: $c --aov: the render failed"; refused "$OUT/$c.log"; exit 1; }
|
||||
for i in 0 1 2 3 4 5; do
|
||||
n=$(printf '%05d' "$i")
|
||||
[ "$(wc -c < "$OUT/$c/depth/frame-$n.f32" 2>/dev/null | tr -d ' ')" = 230400 ] || { echo "FAIL: $c --aov: frame $i's depth is missing or not 320 x 180"; exit 1; }
|
||||
[ "$(wc -c < "$OUT/$c/motion/frame-$n.f32" 2>/dev/null | tr -d ' ')" = 460800 ] || { echo "FAIL: $c --aov: frame $i's motion is missing or not 320 x 180"; exit 1; }
|
||||
[ "$(LC_ALL=C tr -d '\0' < "$OUT/$c/depth/frame-$n.f32" | head -c 1 | wc -c | tr -d ' ')" = 1 ] || { echo "FAIL: $c --aov: frame $i's depth is all zero"; exit 1; }
|
||||
done
|
||||
echo "PASS: $c --aov: frames 0 to 5, each with its depth and motion"
|
||||
done
|
||||
RAEA_PASS=depth RAEA_READBACK=rgba "$BIN" render bench/aov-msaa/ramp.tsx --at "$AT" -o "$OUT/pass" > "$OUT/pass.log" 2>&1 || { echo "FAIL: ramp RAEA_PASS=depth: the render failed"; refused "$OUT/pass.log"; exit 1; }
|
||||
[ "$(ls "$OUT/pass"/frame-*.png 2>/dev/null | wc -l | tr -d ' ')" = 6 ] || { echo "FAIL: ramp RAEA_PASS=depth: not six frames"; exit 1; }
|
||||
echo "PASS: ramp RAEA_PASS=depth: frames 0 to 5"
|
||||
@@ -0,0 +1,31 @@
|
||||
// #159: a game's 3D (its rows set on the live engine each frame, so raea-sys-post's msaa_for_3d sees them): a
|
||||
// multisampled camera, a still bloom and a box that moves, rendered with --aov (check.sh).
|
||||
import { AbsoluteFill, registerRoot, Composition, useGameState } from "raea";
|
||||
import { Bloom, Canvas3D, ToneMapping, manifold } from "raea/3d";
|
||||
import { Camera3d } from "raea/camera";
|
||||
import { AmbientLight, DirectionalLight } from "raea/light";
|
||||
import { Mesh3d } from "raea/mesh";
|
||||
import { StandardMaterial } from "raea/pbr";
|
||||
import { Transform } from "raea/transform";
|
||||
|
||||
const GROUND = manifold.box(20, 1, 20).move(0, -0.5, 0);
|
||||
const BOX = manifold.box(1.5, 1.5, 1.5);
|
||||
|
||||
function Game() {
|
||||
const t = useGameState({ t: 0 }, (s) => ({ t: s.t + 1 })).t;
|
||||
return (
|
||||
<AbsoluteFill style={{ background: "#202830" }}>
|
||||
<Canvas3D>
|
||||
<Camera3d transform={Transform.fromXyz(6, 3, 8).lookingAt([0, 0.8, 0], [0, 1, 0])} projection={{ Perspective: { fov: 0.8, near: 0.1, far: 100 } }} />
|
||||
<DirectionalLight name="sun" transform={Transform.fromXyz(10, 20, 5).lookingAt([0, 0, 0], [0, 1, 0])} illuminance={20000} shadow_maps_enabled />
|
||||
<AmbientLight brightness={200} />
|
||||
<Mesh3d name="ground" shape={GROUND}><StandardMaterial base_color="#6a7a50" perceptual_roughness={0.9} /></Mesh3d>
|
||||
<Mesh3d name="box" shape={BOX} transform={Transform.fromXyz(-1.5 + t * 0.2, 0.75, 0)}><StandardMaterial base_color="#d03020" emissive="#ffe0a0" emissive_intensity={4} /></Mesh3d>
|
||||
<ToneMapping mode="agx" />
|
||||
<Bloom intensity={0.3} threshold={0.8} />
|
||||
</Canvas3D>
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
registerRoot(() => <Composition id="game" component={Game} width={320} height={180} fps={30} durationInFrames={10} />);
|
||||
@@ -0,0 +1,31 @@
|
||||
// #159: a multisampled 3D camera (no AO or <AntiAliasing>) whose post-processing changes on every frame (a bloom ramp),
|
||||
// rendered with --aov and with RAEA_PASS (check.sh). Its frames read the camera's rows through raea-sys-post's sync.
|
||||
import { AbsoluteFill, interpolate, registerRoot, Composition, useCurrentFrame } from "raea";
|
||||
import { Bloom, Canvas3D, ToneMapping, manifold } from "raea/3d";
|
||||
import { Camera3d } from "raea/camera";
|
||||
import { AmbientLight, DirectionalLight } from "raea/light";
|
||||
import { Mesh3d } from "raea/mesh";
|
||||
import { StandardMaterial } from "raea/pbr";
|
||||
import { Transform } from "raea/transform";
|
||||
|
||||
const GROUND = manifold.box(20, 1, 20).move(0, -0.5, 0);
|
||||
const BOX = manifold.box(1.5, 1.5, 1.5);
|
||||
|
||||
function Ramp() {
|
||||
const f = useCurrentFrame();
|
||||
return (
|
||||
<AbsoluteFill style={{ background: "#202830" }}>
|
||||
<Canvas3D>
|
||||
<Camera3d transform={Transform.fromXyz(6, 3, 8).lookingAt([0, 0.8, 0], [0, 1, 0])} projection={{ Perspective: { fov: 0.8, near: 0.1, far: 100 } }} />
|
||||
<DirectionalLight name="sun" transform={Transform.fromXyz(10, 20, 5).lookingAt([0, 0, 0], [0, 1, 0])} illuminance={20000} shadow_maps_enabled />
|
||||
<AmbientLight brightness={200} />
|
||||
<Mesh3d name="ground" shape={GROUND}><StandardMaterial base_color="#6a7a50" perceptual_roughness={0.9} /></Mesh3d>
|
||||
<Mesh3d name="box" shape={BOX} transform={Transform.fromXyz(-1.5 + f * 0.2, 0.75, 0)}><StandardMaterial base_color="#d03020" emissive="#ffe0a0" emissive_intensity={4} /></Mesh3d>
|
||||
<ToneMapping mode="agx" />
|
||||
<Bloom intensity={interpolate(f, [0, 9], [0.1, 0.6])} threshold={0.8} />
|
||||
</Canvas3D>
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
registerRoot(() => <Composition id="ramp" component={Ramp} width={320} height={180} fps={30} durationInFrames={10} />);
|
||||
Executable
+46
@@ -0,0 +1,46 @@
|
||||
#!/bin/bash
|
||||
# #162: every still of a batch (--at A,B,C in one run) shows its own frame's time, as it does alone and as a scene
|
||||
# stepped through every frame before it does. Since #77 a still of a scene no plugin carries state for isn't stepped to,
|
||||
# and the plugins' clock then never moved: every still sampled globals.time 0, and a batch's later frames drew its
|
||||
# first frame's <Material> uniforms (they land as keyed rows). time.tsx's face shows globals.time on its left half and
|
||||
# a uniform the frame gives its time on its right, so the halves match only when Time is the frame's. Its "time"
|
||||
# composition is drawn at 90, 30, 60 in one run (the clock forwards and back) and at 90 alone, and must step no frame
|
||||
# to reach them; "stepped" (the same face with an animation player, so its stills are stepped to, as 0.1.0 drew every
|
||||
# still) at the same three. Each frame's halves must match within 1 level, each "time" frame must match the "stepped"
|
||||
# one and 90 alone the batch's 90 (within 1 level), and 90 must be brighter than 60 and 60 than 30. Exits 1 on a failure.
|
||||
# bench/at-time/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-at-time.XXXXXX")
|
||||
trap 'rm -rf "$OUT"' EXIT
|
||||
draw() { # NAME COMPOSITION AT: the frames in $OUT/NAME, the plugin clock's trace in $OUT/NAME.log
|
||||
RAEA_PLUGIN_TRACE=1 "$BIN" render bench/at-time/time.tsx --composition "$2" --at "$3" -o "$OUT/$1" > "$OUT/$1.log" 2>&1 && [ -f "$OUT/$1/frame-00000.png" ] || { echo "FAIL $1: the render failed"; grep -v "^plugin clock" "$OUT/$1.log" | tail -4 | sed 's/^/ /'; exit 1; }
|
||||
}
|
||||
draw batch time 90,30,60
|
||||
draw lone time 90
|
||||
draw stepped stepped 90,30,60
|
||||
status=0
|
||||
fail() { echo "FAIL $*"; status=1; }
|
||||
steps() { grep -c "^plugin clock: .* step$" "$OUT/$1.log"; }
|
||||
(( $(steps batch) == 0 && $(steps lone) == 0 )) || fail "the time stills stepped $(steps batch) and $(steps lone) frames, wanted none (it has nothing a plugin carries)"
|
||||
(( $(steps stepped) > 0 )) || fail "the stepped stills stepped no frame, so they show nothing of the stepped clock"
|
||||
half() { magick "$1" -crop "24x48+$2+8" +repage -format "%[fx:int(255*mean.r+0.5)]" info:; } # FILE X: a half's grey
|
||||
apart() { magick "$1" "$2" -compose difference -composite -format "%[fx:int(255*maxima+0.5)]" info:; }
|
||||
k=0
|
||||
for at in 90 30 60; do
|
||||
f=$(printf 'frame-%05d.png' $k)
|
||||
for run in batch stepped; do
|
||||
t=$(half "$OUT/$run/$f" 4) u=$(half "$OUT/$run/$f" 36)
|
||||
(( t - u <= 1 && u - t <= 1 )) && echo "ok $run frame $at: globals.time's half $t, the uniform's $u" || fail "$run frame $at: globals.time's half is $t and the uniform's $u: Time isn't the frame's"
|
||||
done
|
||||
d=$(apart "$OUT/batch/$f" "$OUT/stepped/$f")
|
||||
(( d <= 1 )) || fail "frame $at differs from the stepped scene's by up to $d levels"
|
||||
eval "grey_$at=$(half "$OUT/batch/$f" 4)"
|
||||
k=$((k + 1))
|
||||
done
|
||||
d=$(apart "$OUT/lone/frame-00000.png" "$OUT/batch/frame-00000.png")
|
||||
(( d <= 1 )) && echo "ok frame 90 alone matches the batch's frame 90" || fail "frame 90 alone differs from the batch's frame 90 by up to $d levels"
|
||||
(( grey_90 > grey_60 && grey_60 > grey_30 )) || fail "the batch's frames 30, 60 and 90 are $grey_30, $grey_60 and $grey_90: frozen, not moving on"
|
||||
[ $status = 0 ] && echo "PASS every still of a batch shows its own frame's time, as alone and as stepped to"
|
||||
exit $status
|
||||
@@ -0,0 +1,35 @@
|
||||
// #162's composition, which bench/at-time/check.sh draws: one face, its left half grey by Bevy's globals.time and its
|
||||
// right half by a <Material> uniform the frame gives its time in seconds (each at a quarter of it), so the halves match
|
||||
// only when Time is the frame drawn's. "time" holds nothing a plugin carries, so a still draws only its own frame
|
||||
// (#77); "stepped" is the same face with an animation player on it (it plays nothing), which Bevy carries from frame
|
||||
// to frame, so a still is stepped to through every frame before it.
|
||||
import { Composition, registerRoot, useCurrentFrame } from "raea";
|
||||
import { Transform } from "raea/transform";
|
||||
import { Camera3d } from "raea/camera";
|
||||
import { Cuboid, Mesh3d } from "raea/mesh";
|
||||
import { BevyComponent } from "raea/3d";
|
||||
import { Material } from "@raea/render/bevy3d";
|
||||
|
||||
function Shot({ stepped }: { stepped: boolean }) {
|
||||
const f = useCurrentFrame();
|
||||
return (
|
||||
<>
|
||||
<Mesh3d transform={Transform.fromXyz(0, 0, 0)}>
|
||||
<Cuboid half_size={[2, 2, 0.01]} />
|
||||
<Material fragment="time.wesl" uniforms={{ seconds: f / 30 }} />
|
||||
{stepped ? <BevyComponent type="bevy_animation::AnimationPlayer" value={{ active_animations: {} }} /> : null}
|
||||
</Mesh3d>
|
||||
<Camera3d transform={Transform.fromXyz(0, 0, 3).lookingAt([0, 0, 0])} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const Pure = () => <Shot stepped={false} />;
|
||||
const Stepped = () => <Shot stepped />;
|
||||
|
||||
registerRoot(() => (
|
||||
<>
|
||||
<Composition id="time" component={Pure} width={64} height={64} fps={30} durationInFrames={120} />
|
||||
<Composition id="stepped" component={Stepped} width={64} height={64} fps={30} durationInFrames={120} />
|
||||
</>
|
||||
));
|
||||
@@ -0,0 +1,13 @@
|
||||
// The left half grey by Bevy's globals.time, the right by the uniform the frame gives: each a quarter of its seconds.
|
||||
import bevy_pbr::render::{
|
||||
mesh_view_bindings::globals,
|
||||
forward_io::VertexOutput,
|
||||
};
|
||||
|
||||
@group(constants::MATERIAL_BIND_GROUP) @binding(0) var<uniform> seconds: f32;
|
||||
|
||||
@fragment
|
||||
fn fragment(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
let t = select(seconds, globals.time, in.uv.x < 0.5) / 4.0;
|
||||
return vec4<f32>(t, t, t, 1.0);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"0": ["Pointer:480:60"],
|
||||
"6": ["Pointer:480:260"],
|
||||
"10": ["Pointer:480:260:down"],
|
||||
"12": ["Pointer:480:260"],
|
||||
"21": ["Pointer:480:60"]
|
||||
}
|
||||
@@ -8,7 +8,8 @@
|
||||
# React on the page with 3D in the world, picking and input replay are all here: the games (pong and platformer on
|
||||
# the page, arena3d's 3D drawn live), bevy-ts' live cases (keys, the pointer, a gamepad, the window and the World's
|
||||
# components through useQuery), the bridge's Engine reads (engine3d: a cube the World moves, React's marker reading it)
|
||||
# and pick3d (on* on 3D parts: hover, press, leave); an <R3F>'s own pointer events and <OrbitControls> (r3f live/pointer)
|
||||
# and pick3d (on* on 3D parts: hover, press, leave); an <R3F>'s own pointer events and <OrbitControls> (r3f live/pointer);
|
||||
# an app screen's button clicked through the 3D, its own timer on the frame's clock (appscreen: blitz-bevy H12)
|
||||
sdk/react/bench/games/pong/edit.tsx keys:ArrowUp,ArrowDown,,ArrowUp 0.25 0.75 1.25 1.75
|
||||
sdk/react/bench/games/platformer/edit.tsx keys:ArrowRight,ArrowRight+ArrowUp,ArrowRight, 0.25 0.75 1.25 1.75
|
||||
sdk/react/bench/games/arena3d/edit.tsx keys:ArrowRight,ArrowUp,ArrowLeft+ArrowUp,ArrowDown, 0.25 0.75 1.25 1.75
|
||||
@@ -22,3 +23,4 @@ sdk/raea/bench/bevy-ts/cases/text3d-readback.tsx script:sdk/raea/bench/bevy-ts/c
|
||||
bench/bridge/engine3d.tsx - 0.3 0.9 1.25
|
||||
sdk/raea/bench/bevy/pick3d/edit.tsx script:bench/render-play/pick3d.json 0.1 0.2 0.3 0.4 0.6 0.9
|
||||
sdk/r3f/test/live/pointer.tsx script:sdk/r3f/test/live/pointer.json 0.2 0.4 0.6 0.9
|
||||
sdk/raea/bench/bevy/appscreen/edit.tsx script:bench/render-play/appscreen.json 0.2 0.4 0.6 0.9
|
||||
|
Can't render this file because it contains an unexpected character in line 5 and column 29.
|
+135
-3
@@ -7,6 +7,9 @@ Feature: The character SDK as one system: SOMA bodies, Kimodo motion, generated
|
||||
settled, a generative or procedural clothing system, perhaps with the mannequin as the base input and an image
|
||||
model on top, layered.
|
||||
|
||||
The user, 11-16: the character SDK ships as raea 0.1.7, and 0.1.6 is a patch for the app. What of it is on main
|
||||
before then ships in 0.1.6's binary unannounced, as 0.1.5's did.
|
||||
|
||||
This file is the map. The detail stays where it is: docs/hands.feature (arms and hands, the SOMA rule),
|
||||
docs/creatures.feature (four legs), docs/drawn-characters.feature (a drawing as a character),
|
||||
docs/character.md (the five layers and eleven principles of the rebuilt SDK, which still hold except principle
|
||||
@@ -195,11 +198,45 @@ Feature: The character SDK as one system: SOMA bodies, Kimodo motion, generated
|
||||
# sit at a switch; the run curve also jolts 23 degrees against 22), slide in the jog curve, the turn of
|
||||
# 180 and errands (4 to 9 cm), and the head rolling 18 to 20 degrees on curves against 13 to 16 in the
|
||||
# captures. Moving the body at a switch onto the new clip's planted foot (align) is not the pops' cause:
|
||||
# off, it takes away a few and the walk curve slides 15 cm.
|
||||
# off, it takes away a few and the walk curve slides 15 cm. The cause: a switch blended the pose's turns
|
||||
# and the hips' height but not the hips' speed over the floor, so a run handing to a run turn at another
|
||||
# pace jumped it in a frame. Carried into the decaying offset (perform's carry, on unless no foot is down
|
||||
# in both clips, where carrying it slid a run turn's foot 22 cm): pops 36 to 21, at switches 31 to 12,
|
||||
# every other number unchanged.
|
||||
Then a body goes where a path says, by the situations the chooser allows, with every switch inertialized
|
||||
and every planted foot held
|
||||
And the turbo suite's cases pass on a SOMA person at least as well as they do today
|
||||
|
||||
@done
|
||||
Scenario: CH14b. The suite's eight cases pass on SOMA, and paths drawn at random are run beside them
|
||||
# 11-15, sdk/body (the private repository, 58fed86 and 4b1781f): 8 of 8, from 0. What each failure was:
|
||||
# Hip pops: tuning the matcher only moved the same few jumps from one path to another (the adjustment
|
||||
# toward the path comes on as a foot lifts, a turn goes about another ankle, a switch changes pace), so
|
||||
# the hips' path is evened afterwards to the captures' own largest change of speed in a frame, before the
|
||||
# feet are held (perform.ts evenHips, hipLimit): no pop in any case, the path moved by millimetres.
|
||||
# The run's curve: a straight run could not turn, so a curve of 7 m was two turn captures handed back and
|
||||
# forth every 17 frames. A curve gentler than 0.2 radians a metre is now a straight clip steered about its
|
||||
# planted ankle, and the matcher is asked for the path with that bend taken out.
|
||||
# A run's corner: the guide went through a corner of 90 degrees at 3.6 m/s and the body ran half a metre
|
||||
# past it. The guide now comes into a corner at the pace the turn captures take one (guide.ts cornerSpeed:
|
||||
# 45 degrees at 3 m/s, 90 at 1.9), and a run slowing for it may come down through run to walk.
|
||||
# The head on curves: a walk came to rest in the sway capture, filed as a way of standing, its head 19
|
||||
# degrees over. Sway is its own situation.
|
||||
# Slides: a foot in the air rode down with the hips when they came down for the other leg, and a stop's
|
||||
# closing step came in 1 cm over the floor for 20 cm. It is lifted over where the lowered hips leave it,
|
||||
# and its lift eased over as many frames as a hold (let down in three, the shin jolted 16 degrees).
|
||||
# The suite itself: jolt bars per gait (the run captures' own foot strikes failed a bar set mostly by
|
||||
# walks, in 8 to 10 per cent of their frames), slide measured on the performance's own floor.
|
||||
# Beside the eight, `SWEEP=40 bun sdk/body/tools/suite.ts` draws 40 paths at random (one to three legs, a
|
||||
# walk, a jog or a run, some with a wait): 45 of 48 pass, from 33 before the slide's cause was found. Left:
|
||||
# three paths 34 to 39 cm off their line at a sharp turn (the bar is 30).
|
||||
# Tried and taken back: the adjustment on a spring (20 to 30 cm wider at a run's corner), contacts taken
|
||||
# from the playing captures, a sole's speed read with the adjustment's carrying taken off (both held feet
|
||||
# the blend was still moving: slides of metres), a standing body held to the start captures (one path
|
||||
# ended 4 m past its mark).
|
||||
Then `bun sdk/body/tools/suite.ts` prints 8 of 8 on SOMA
|
||||
And with SWEEP=40 at least 45 of the 48 paths pass
|
||||
|
||||
@done
|
||||
Scenario: CH15a. Two situations the captures lack, made by Kimodo from two of their poses
|
||||
# 11-15. sdk/body/tools/between.ts writes Kimodo's full-body keyframes from two library frames (the first at
|
||||
@@ -240,7 +277,7 @@ Feature: The character SDK as one system: SOMA bodies, Kimodo motion, generated
|
||||
# `mps` device), so the earlier line that it does not run on a Mac is untested, not true.
|
||||
Then a stage `do` line gets a clip made from its words, checked, and kept in the project
|
||||
|
||||
Scenario: CH15c. Kimodo on the user's own machine, in MLX (planned)
|
||||
Scenario: CH15c. Kimodo on the user's own machine, in MLX
|
||||
# The user, 11-15: "lets plan that if kimodo works well we port it mlx weights or go find some". Gated on
|
||||
# an eval first: about ten lines (wave, point, shrug, clap, nod, bow, look at a watch, cross the arms,
|
||||
# scratch the head, stretch), each with a check of its own (which hand rises, where the head turns) and a look
|
||||
@@ -252,6 +289,26 @@ Feature: The character SDK as one system: SOMA bodies, Kimodo motion, generated
|
||||
# model (a small diffusion transformer): its weights converted and run in MLX, checked against the PyTorch
|
||||
# motion for the same line, constraints, seed and noise. Before anything ships to users: the licences of
|
||||
# converted weights (NVIDIA's Open Model License for Kimodo, Meta's Llama 3 licence for the encoder).
|
||||
# 11-16. Done in Rust, no Python: raea-sys-kimodo runs Kimodo-SOMA-RP-v1's denoiser and LLM2Vec on MLX from
|
||||
# the checkpoints' own files (nothing converted: mlx-community's 8-bit Llama 3 8B Instruct, McGill-NLP's two
|
||||
# adapters run beside it unmerged), and `raea motion "LINE" [--keys KEYS.json]` writes the clip fromkimodo.ts
|
||||
# reads. Against PyTorch: the denoiser within 2e-3; a whole 100-step generation from the same noise and text
|
||||
# within 0.002 cm on every joint; constraints become the same conditions. The stated tolerance is the 8-bit
|
||||
# encoder's: cosine 0.99993 to float32, which moves the joints 0.01 to 0.74 cm on average and 1.44 cm at
|
||||
# worst over eight lines (4-bit moved them 8 cm and is not used). A seed's noise is not torch's, so a seed is
|
||||
# not the cloud's motion for that seed; measured by what it does, the local wave falls in the cloud's three
|
||||
# (a hand above the shoulder 54 to 67 of 120 frames against 48 to 59, the hips within 3 cm). Cost: the
|
||||
# motion model 1.1 GB and the encoder 8.8 GB once, then 5 s to load and read a new line (a line's numbers
|
||||
# are kept, so a line is read once) and about 8 s a 4 s clip on an M5 Pro, against the cloud's 130 s
|
||||
# loading. The eval (sdk/body tools/doeval.ts, each line's check measured on the joints; clips by
|
||||
# tools/makedo.ts, three seeds a line between standing keys): every clip passes the bar of the captures that
|
||||
# end standing; the seed kept is the one whose upper body moves most (a do line fails by standing through
|
||||
# it: one seed of three stood still through "scratch the head"), and the kept ten all do what they say
|
||||
# (seed 1 alone 7 of 10, seed 2 8, seed 3 7). Film: sheet3d out/do-eval-v1.mp4, posted for the user's look
|
||||
# (i-show-mwj21c0d-1). The user's look, 11-16: "All ten read right". Open: the user's word on shipping the
|
||||
# downloads (i-show-mwj24i8o-2: Kimodo under NVIDIA's
|
||||
# Open Model License; Meta Llama 3 under its Community License, fetched from mlx-community's ungated 8-bit
|
||||
# copy; the adapters MIT); Kimodo's own post-processing (its C++ foot-skate clean-up) is not ported.
|
||||
Given the eval's lines pass
|
||||
Then a do line's clip is made on a Mac with no GPU in the cloud, matching the cloud's within a stated
|
||||
tolerance
|
||||
@@ -371,6 +428,36 @@ Feature: The character SDK as one system: SOMA bodies, Kimodo motion, generated
|
||||
# and the head's ears, which the face session is rebuilding.
|
||||
Then a generated head is drawn on SOMA's body as a part, joined at the collar
|
||||
|
||||
@done
|
||||
Scenario: CH20b. The body's skin is graded to the head at the collar
|
||||
# 11-15. Measured first (sheet3d compositions/seam_check.tsx: the headless body at rest with the head as a
|
||||
# part, lit evenly, seen close from the front, both sides and the back, the collar on the middle row): the
|
||||
# body, built in the head's neck colour, stood 8 levels of 255 lighter than the head's skin across the
|
||||
# collar at the front, 1 to 3 at the sides and back, and the line showed. `raea clothes wear ... --head
|
||||
# HEAD_DIR` (engine/cli/src/grade.ts) now writes the join into the body it dresses: the skin takes the
|
||||
# head's neck colour, and each vertex under the collar takes the colour the head's own skin has above it
|
||||
# (head.json's ring colours, evened over five round the ring: one texel a vertex drew streaks), easing into
|
||||
# the neck colour 8 cm down, as vertex colours on body.glb. The step at the front is under 1 level, 1 to 4
|
||||
# round the rest. Left: the head's own strip above the collar repeats one texel a column (its ring takes
|
||||
# its nearest rim vertex's place in the picture), the neck's outline stops flaring for 2 cm above the
|
||||
# collar, and the body's skin has none of the head's fine detail.
|
||||
Given a headless body and the head joined to its collar
|
||||
Then the body dressed with that head named has its skin in the head's neck colour, graded to the head's
|
||||
own skin at the collar, and no step of colour shows across the join
|
||||
|
||||
@done
|
||||
Scenario: CH20c. The eyes take a look target
|
||||
# 11-15. `<Character gaze={[x, y, z]}>` (sdk/character/src/character/eyes.ts): each eye joint is turned to
|
||||
# the point on top of the pose, in its head's frame, so the eyes cover what the head has not turned; no
|
||||
# further than an eye goes (35 degrees to a side, 25 down, 17 up: the head's upper lid has no morph that
|
||||
# lifts it, and at 25 up the iris went under it). A part that has the eye joints has its upper lids ride
|
||||
# the eyes down (its blink morphs raised to 0.45 at the lowest): without that the white showed over the
|
||||
# iris. Seen on the first head, straight, to each side, up and down (sheet3d compositions/gaze_check.tsx).
|
||||
# Not yet: lids that lift, and a stage act's `look` sending the eyes as well as the head.
|
||||
Given a body whose head has eye joints, and a point in the scene
|
||||
Then the eyes turn to it within their range, whatever the neck and head are doing
|
||||
And the upper lids come down with them
|
||||
|
||||
Scenario: CH21. Hair
|
||||
# Agreed with the face session 11-15. sdk/body/src/cloth.ts already moves hair and clothes that follow
|
||||
# skin. Hair cards are the face session's working choice, pending its tests; strand hair stays a reference
|
||||
@@ -387,9 +474,30 @@ Feature: The character SDK as one system: SOMA bodies, Kimodo motion, generated
|
||||
# generated head joined at the neck, hair and glasses, generated clothes in two layers, walking by motion
|
||||
# matching. Not yet: the hair moving (the follower does not read the stray attribute from a part), and
|
||||
# raea's own hair shading on it (that shader wants tangents the cards do not carry, so it is drawn with
|
||||
# its own material).
|
||||
# its own material). Both since: CH21b.
|
||||
Then a person is a body folder and parts, each made by its own flow
|
||||
|
||||
@done
|
||||
Scenario: CH21b. Generated hair moves on the follower
|
||||
# 11-15. `bun sdk/body/tools/hair.ts SKELETON.json HAIR.glb POSES.json OUT.bind.rseq SKIN.glb...` reads a
|
||||
# head's hair cards as cloth (each vertex free by its stray attribute), carries them through a
|
||||
# performance on the cloth follower, kept outside the skin as drawn (the head, the body, what it wears),
|
||||
# and writes the frames in the hair's own bind pose; a Character part draws them with
|
||||
# `cloth: { src, frame }`, so the hair keeps its cut-out and raea's hair shader (the cards carry tangents
|
||||
# now). Measured on the first head's loose hair (33,191 particles, three quarters free) over SOMA's 449
|
||||
# frame locomotion clip, as free particles more than 3 mm inside the skin, the worst of every tenth
|
||||
# frame: 3,874 carried by the head alone, 223 on the follower; the hair leaves its skinned place by 13 mm
|
||||
# on average. Three causes found on the way. The hair is generated for the head alone and hung straight
|
||||
# through the upper back (4,982 particles in the skin at rest): it is laid over the body at rest first.
|
||||
# Brought out one particle at a time, each lock was kinked at every vertex and drew as zigzags over the
|
||||
# shoulders: what the fit moves is evened along each lock. And the follower starts as the skin has it,
|
||||
# in the shoulders of the first pose: the first pose is held for 20 frames first. Left: a few locks
|
||||
# stretch down an arm (a particle strays 15 cm at most, its limit 6), the bake runs at 0.36 s a frame, and
|
||||
# the frames are baked for one performance, not followed live in play.
|
||||
Given a head's hair cards, a body with what it wears, and a performance
|
||||
Then the hair is carried by the follower through it, outside the head, the body and the clothes
|
||||
And it is drawn as a part of the character with raea's hair shader
|
||||
|
||||
Rule: Creatures
|
||||
|
||||
# The creature flow is the raccoon session's, end to end, in docs/creatures.feature (its sandbox is the
|
||||
@@ -625,6 +733,30 @@ Feature: The character SDK as one system: SOMA bodies, Kimodo motion, generated
|
||||
# garment a call; an outfit is several calls, innermost first.
|
||||
Then a garment is made by one command from words or by procedure, and an outfit is worn by one more
|
||||
|
||||
@done
|
||||
Scenario: CH45c. `raea clothes make` sews; the picture-measured garments are gone
|
||||
# 11-15 night. `raea clothes make NAME ["WORDS"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB]` makes a
|
||||
# sewn garment (CH47a's patterns, CH48c's model) in the project: assets/clothes/NAME.json (kind "sewn") and
|
||||
# assets/clothes/NAME/ (the glb, the design, the flat pattern, four pictures). The design is the garment
|
||||
# model's from the words, or GarmentCode's plain base with --plain or no words; each --set changes one of its
|
||||
# 122 settings by path, checked against its options or range (a wrong one says what is allowed);
|
||||
# `raea clothes settings` lists them. The first use sets up raea's models folder (garments/): GarmentCode
|
||||
# cloned at a fixed commit and checked by it, a Python 3.11 environment made by uv from a pinned list, SOMA's
|
||||
# body as a distance grid. `wear` takes sewn garments beside ones laid on the skin: each sewn glb is copied
|
||||
# and the skin under it left out (tools/garments/hide_under.py). Measured before building: the model alone
|
||||
# is not enough ("a short-sleeved t-shirt" came out an open flared tunic with ruffled cuffs, "straight
|
||||
# trousers" knee-length culottes, colours by chance), so the settings are the control and the words a first
|
||||
# guess. A tee and trousers by settings, 18 and 28 seconds, $0, worn with the generated head and walked
|
||||
# (sheet3d compositions/soma_sewn.tsx): they read as clothes, with a cut, a hem and folds. Taken out: `make`
|
||||
# by four drawn pictures measured onto the skin, `remeasure`, the mannequin's views (wardrobe.ts's drawing,
|
||||
# tools/clothes/garment.py's measure, mannequin.py); a garment measured that way is refused by `wear` with
|
||||
# what to do instead. `cover` stays for what is skin-tight. Wrong still: an outer garment is draped on the
|
||||
# bare body (the trousers' waistband shows through the tee's hem); trousers at length 0.9 drag on the
|
||||
# floor; a sewn garment is skinned in motion, not simulated (CH44); the words model is not fetched by a
|
||||
# release yet (only this machine's models folder has one).
|
||||
Then a garment is sewn by one command from words or from settings, for nothing, and worn by one more
|
||||
And no garment is measured from pictures any more
|
||||
|
||||
Scenario: CH45. From words to a wardrobe
|
||||
Then `raea` takes a description of an outfit, draws its layers and views, builds the garments, and writes
|
||||
them beside the body, saying what each picture cost; the pictures are kept with the garment as its source
|
||||
|
||||
@@ -451,6 +451,29 @@ Feature: Procedural arms and hands: a character reaches for, takes, holds, carri
|
||||
lift is slower; a light one moves with the wrist
|
||||
And a throw's wind-up and follow-through scale with it
|
||||
|
||||
@done
|
||||
Scenario: HG19. On SOMA's own skin a held thing has no skin of the hand in it
|
||||
# 11-15, the audit (tools/hands-audit) on SOMA's body: fingers stood 17 to 36 mm inside a held box and cup.
|
||||
# Three causes, each in the system. A joint bent until its own bone met the surface, and carried the bones
|
||||
# past it in (a knuckle 60 degrees onto a box's face, the next two bones 24 and 35 mm inside): it now stops
|
||||
# when any bone past it meets. The curl read each bone's skin as riding that bone alone, where the skin is
|
||||
# carried by several joints' weights (the ball of the thumb is half the hand's): it reads it as drawn. And
|
||||
# the ball of the thumb is the palm's: the hand's frame sets the palm's height on it too, and only on skin
|
||||
# the hand mostly carries itself (the web to the thumb stood 13 mm proud). Now, worst over each take: 0 to
|
||||
# 1 mm in the thing (3 mm passing a cup hand to hand), 4 to 5 pads on, the palm 1 to 6 mm off.
|
||||
# Then the table (fingers 20 to 37 mm into it at a box's grab) and the body's own thighs. A reach leans the
|
||||
# chest, and the second hand's lean carried the first hand 6 cm off its hold with its fingers still shaped
|
||||
# for the hold: every hand but the last is solved again with the trunk left where it is. A travelling hand is
|
||||
# kept off solids by its skin as its fingers are that frame (opened, they go further than at rest). The
|
||||
# audit's own standing pose hung SOMA's fingers 31 mm inside the thighs before any take began: it now hangs
|
||||
# the arms as near the sides as keeps them out. Five of the six takes now: 0 to 2 mm of hand in the thing,
|
||||
# none in the scene, 0 to 6 mm in the body's own solids, every holding hand's five pads on. The sixth (a
|
||||
# box from the floor to a table, squatting) still has 8 mm in the box, 20 in the table and 50 in the thighs.
|
||||
Given SOMA's body, its skin samples on the joints that carry them
|
||||
Then through each of the audit's six takes no skin of a hand is more than 3 mm inside the thing it holds
|
||||
And every hand that holds has four pads or more on it, its palm within 6 mm
|
||||
And no skin of a hand or forearm is in the scene's solids, nor more than 6 mm in the body's own
|
||||
|
||||
Rule: Wider, for the character SDK
|
||||
|
||||
Scenario: HG11. Creatures' motion from generated video
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
@spec
|
||||
Feature: img2raea: a picture made into raea objects, props, environments and scene data, and held to three.js
|
||||
Goal, 2026-11-16: "lets work on the img2threejs as also a way to get 3js perfect parity and how we can expand the
|
||||
skill for our own skills like img2raea and how we can do the same with environments, scene data, and what places we
|
||||
can use procedural tools or nueral networks or any kidn fo machine learnign to get it right".
|
||||
|
||||
img2threejs (github.com/img2threejs/img2threejs, Apache-2.0, read at 0c0c49bc) is an agent skill that turns one
|
||||
picture into a procedural three.js model: a factory, `createXModel(): THREE.Group`, built in gated passes (blockout,
|
||||
structure, form, material, surface, lighting, interaction, optimisation) against an ObjectSculptSpec, each pass
|
||||
checked by renders in a browser (the "Divine Eye" views, a turntable, self-intersection, attachment and chirality
|
||||
gates). Its showcase (img2threejs-showcase, 638b5c73, three ^0.169) has no licence and holds other people's IP, so
|
||||
it is measured locally and never committed; the corpus we keep comes from running img2threejs on our own pictures.
|
||||
|
||||
Found on 11-16: a factory runs in raea unchanged as `<R3F><primitive object={createXModel()} /></R3F>` (the Talon
|
||||
knife, its tick animation included). So img2threejs's output is already raea's input; what is left is making the
|
||||
two renderers agree (parity), giving the skill a raea target (img2raea), and doing the same for places and scenes.
|
||||
|
||||
Rule: three.js parity, measured on img2threejs's output
|
||||
|
||||
@needs
|
||||
Scenario: IR1. The showcase as a parity corpus
|
||||
Given the showcase's single-file factories (15 on 11-16: a rifle, a bike, three knives, a chest, a house, a
|
||||
mascot, a pistol, a shotgun, a humanoid, earbuds' case, a rocket, a truck), fetched at a pinned commit into a
|
||||
cache outside git
|
||||
When each is centred, scaled to 2 m on its longest side, seen from one camera at 640 x 400, and drawn by raea's
|
||||
<R3F> (`raea render`) and by three.js's own <Canvas> in headless Chrome (sdk/r3f/tools/chrome.ts: Chrome only as
|
||||
three.js's reference renderer, as R3F8 uses it)
|
||||
And under four rigs: neutral (a hemisphere and two directional lights), direct (the two directional lights),
|
||||
dark (direct with an ambient light of 0) and lookdev (the author's own lights, moved and scaled with the model)
|
||||
Then each pair is scored on the model's own box (the union of both pictures' non-background boxes, padded 8 px):
|
||||
SSIM and RMSE there, the frame's SSIM beside them; the frame's SSIM is not the score, as a model that fills a
|
||||
tenth of the frame scores 0.99 with its face missing
|
||||
And the plan
|
||||
| crate | file | lines | job |
|
||||
| tools | tools/img2raea/parity.sh | 80 | fetch the pinned showcase into ~/.raea/cache, run both sides, score, sheet |
|
||||
| tools | tools/img2raea/shoot.ts | 70 | three.js's side: the page bundled with sdk/r3f's three and R3F, shot |
|
||||
| tools | tools/img2raea/scene.tsx | 80 | one case's scene for both sides: fit, seeded Math.random, the four rigs |
|
||||
| tools | tools/img2raea/score.sh | 40 | crop to the model's box, SSIM and RMSE, side-by-side pairs, contact sheets |
|
||||
And 11-16, so far: built and run in a scratch folder (not yet in tools/): 60 cases in 6.5 minutes on this Mac,
|
||||
raea's renders 5.8 GB peak; 14 of the 15 factories draw (the humanoid throws: IR6); under the dark rig 12 of the
|
||||
14 score 0.95 or better on the crop (the rocket 0.81: IR4; the chest 0.94: its gold edges' highlights); under
|
||||
the neutral rig the earbuds' case, the rocket and the chest fall to 0.80-0.84 (IR3); the mascot scores 0.976
|
||||
with its face missing (IR5), so a per-part or edge score has to join SSIM before 0.95 can mean "the same"
|
||||
And not yet diagnosed: the bike's tyre lettering is missing in raea (a canvas texture repeated -1 x 1, so a
|
||||
negative repeat is the first suspect) and the truck's ground ring loses its soft glow (additive blending is
|
||||
mapped, input/material.ts, so something else)
|
||||
|
||||
@done
|
||||
Scenario: IR2. No ambient light means none
|
||||
Given a three.js scene with no AmbientLight, HemisphereLight or LightProbe
|
||||
Then raea draws it with no ambient light either
|
||||
And today it doesn't: <R3F> sends no ambient, so the camera falls back to Bevy's GlobalAmbientLight (white, 80),
|
||||
which raea never sets; a metal then shows its colour everywhere where three.js shows black outside its
|
||||
highlights (the earbuds' copper lid, the chest's gold corners, a knife's blade)
|
||||
And measured 11-16: the earbuds' case, direct rig, crop SSIM 0.83; with an explicit <ambientLight intensity={0}>
|
||||
0.996; the chest 0.88 to 0.94, the Gerber knife 0.94 to 0.98
|
||||
And the fix is one of: sdk/r3f's input/lights.ts sends AmbientLight 0 when the scene has none, or raea's engine
|
||||
sets GlobalAmbientLight to 0 (a raea scene without an ambient light would then be darker too: decide which)
|
||||
And 11-16, built in sdk/r3f (input/scene.ts convert): a scene with no AmbientLight, HemisphereLight or LightProbe
|
||||
gets an AmbientLight of 0, white so it lends no colour (raea sums a camera's ambient lights and takes the first
|
||||
non-white one's colour, so a composition's own AmbientLight beside the <R3F> is kept as it was); the engine's
|
||||
GlobalAmbientLight is unchanged (Shane's call, through the 0.1.6 release session). Measured: under the direct
|
||||
rig the earbuds' case 0.83 to 0.996, the Gerber knife 0.94 to 0.98, the chest 0.88 to 0.94, the mascot 0.96
|
||||
to 0.99; R3F8's 43 cases as before (one, in-drei, 0.9935 to 0.9943); test/input.test.tsx "ambient light"
|
||||
|
||||
@needs
|
||||
Scenario: IR3. three.js's ambient lights only diffuse
|
||||
Given a three.js AmbientLight or HemisphereLight
|
||||
Then it lights a surface's diffuse colour only, as three.js does (irradiance x diffuse; a metal has none)
|
||||
And today raea's AmbientLight is Bevy's, which also lights specular through the environment BRDF, so under a
|
||||
hemisphere light a metal glows evenly: the earbuds' case, neutral rig, crop SSIM 0.80
|
||||
And the fix: a diffuse-only ambient for lights read from three.js (an ambient term raea's PBR shader can switch,
|
||||
or the hemisphere light as an irradiance-only environment)
|
||||
|
||||
@needs
|
||||
Scenario: IR4. Anisotropic metal
|
||||
Given a MeshPhysicalMaterial with anisotropy and anisotropyRotation (the rocket's brushed steel: 0.65, pi/2)
|
||||
Then raea's highlight stretches along the brushing as three.js's does
|
||||
And today the steel blows out in hard white and black halves: crop SSIM 0.81; with anisotropy 0, 0.94
|
||||
And what to check first: the mesh's tangents (Bevy's anisotropy reads ATTRIBUTE_TANGENT; a three.js geometry
|
||||
has none unless computed), then the rotation's sense and the strength's mapping
|
||||
|
||||
@needs
|
||||
Scenario: IR5. Overlays drawn without the depth test
|
||||
Given meshes with material.depthTest false and a renderOrder above the body's (the mascot's eyes, mouth and
|
||||
cheeks: decals whose vertices lie on the body shell, drawn on top in renderOrder 3 and 4)
|
||||
Then raea draws them after the meshes before them, over what is already drawn, as three.js does
|
||||
And today they are depth-tested and lost inside the shell: the face is missing (crop SSIM 0.976, which hides it:
|
||||
the face is a small part of the box; IR1's sheet shows it); sdk/r3f passes depthTest on for a patched or
|
||||
shader material (input/patched.ts, input/shader.ts) but not for the standard ones (input/material.ts), and
|
||||
renderOrder is read only for render targets (input/targets.ts)
|
||||
And 11-16, built in sdk/r3f: a basic material drawn without the depth test is three's own basic program
|
||||
(shader.ts builtinPart, as matcap and normal are), a standard or physical one its patched program (patched.ts),
|
||||
and any ThreeShaderMaterial without the depth test goes with the transparent ones, after everything opaque, as
|
||||
raea's opaque pass has no order; the mascot's face is drawn (crop SSIM 0.96 to 0.99 under the direct rig);
|
||||
test/patched.test.ts "a material drawn without the depth test"
|
||||
And left: renderOrder among such overlays (the eye's highlight over the eye) is still raea's transparent sort,
|
||||
by distance; three's order needs a sort bias from renderOrder in raea-sys-three-shader (Material::depth_bias),
|
||||
an engine change
|
||||
|
||||
@needs
|
||||
Scenario: IR6. A browser's globals a factory reads
|
||||
Given a factory that reads window.location.search (the humanoid's debug switches) or other browser globals
|
||||
Then raea's JS host has a location (about:blank's: an empty search), so the factory runs
|
||||
And today the composition throws at frame 0: "undefined is not an object (evaluating 'window.location.search')"
|
||||
|
||||
Rule: img2raea, the skill
|
||||
|
||||
@needs
|
||||
Scenario: IR7. img2threejs with raea as its target
|
||||
Given img2threejs's emission target socket (docs/EMISSION_TARGET_SOCKET.md: `--target <kind>`, a plugin step
|
||||
with `provides`, run after the model is action-ready)
|
||||
When a raea target plugin is added, installed as ~/.img2/plugins/raea/ and read by their forge/_shared/targets.py:
|
||||
plugin.json `{"schema": 1, "id": "raea", "requires": {"harness": RANGE, "coreApi": 1}, "capabilities":
|
||||
[{"from": "sculpt-spec", "to": "raea-tsx"}]}`, and a steps.json row `{"id": "emit-raea", "command":
|
||||
"{plugin_dir}/emit.sh {workspace} {spec}", "provides": {"version": 1, "from": "sculpt-spec", "to": "raea-tsx",
|
||||
"artifact": {"kind": "raea-tsx", "path": ".img2/artifacts/raea/model.tsx"}}}`, its gates in gates.json
|
||||
Then `--target raea-tsx` writes a raea composition that draws the factory (`<R3F><primitive
|
||||
object={createXModel()} /></R3F>`, its tick from useFrame) and its lights, beside the factory, the same bytes
|
||||
on every run (their socket runs a target twice and refuses a mismatch)
|
||||
And raea is the render authority for the gates that need pictures:
|
||||
| img2threejs gate | raea |
|
||||
| Divine Eye views | `raea render EDIT.tsx --review DIR`: hero, front, right, top, iso, low, colour and clay |
|
||||
| turntable | a composition turning the model, `raea render` to frames |
|
||||
| self-intersection | `raea scene lint` (clipping), `raea scene explain` |
|
||||
| attachment anchor | `raea scene lint`: what rests on what, what floats or sinks |
|
||||
| surface and lighting pass | `raea render --aov` (normals, depth) and the light meter |
|
||||
| chirality | the review's front and right views against the reference |
|
||||
And the gates also pass IR1's parity on the model, so what the skill approved in raea looks the same in three.js
|
||||
|
||||
@needs
|
||||
Scenario: IR8. img2raea in raea's own skill
|
||||
Given the raea skill (skills/, the public raea-skills)
|
||||
Then it teaches the same method natively, credited to img2threejs (Apache-2.0: its NOTICE kept with what is
|
||||
adapted): the picture read into a spec of parts (ObjectSculptSpec's fields), then built in passes in raea's
|
||||
own vocabulary, each pass checked by `raea render --review` before the next
|
||||
And raea's vocabulary for it: core/shape's CSG for hard surfaces, core/sdf for organic ones, core/grow for the
|
||||
numerous (leaves, rocks, terrain), raea's standard material and systems/procmat for surfaces
|
||||
And a picture's thing can come out as either: a three.js factory raea draws (IR7), or a raea part
|
||||
|
||||
@needs
|
||||
Scenario: IR9. Tried on our own pictures
|
||||
Given pictures we make (`raea gen image`, under $10) of a prop, a hard-surface thing and a character
|
||||
When img2raea builds each
|
||||
Then each is scored against its picture from the picture's own view: the silhouette's IoU (SAM 2's mask of the
|
||||
picture against raea's alpha render), and SigLIP's similarity of the two crops (on the CPU: Core ML's GPU path
|
||||
gets SigLIP wrong on this Mac)
|
||||
And these become the kept corpus (CC0, ours), in IR1's runner beside the showcase
|
||||
|
||||
Rule: Scene data
|
||||
|
||||
Scenario: IR10. A three.js scene's geometry in scene lint, explain and export
|
||||
Given an R3F or <Three program> scene, whose geometry raea holds as <BufferMesh> shape "buffer:{positions,
|
||||
indices, normals, uvs}"
|
||||
Then contact, `raea scene lint|explain` and `raea scene export` read it as its triangles, and export writes each
|
||||
such part as GLB (POSITION, NORMAL, TEXCOORD_0) and OBJ (v, vn, vt), without Manifold, as it needn't be closed
|
||||
And 11-16: built on branch img2raea (core/shape/src/buffer.rs; raea-sys-mesh re-exports buffer_tris), unit tests
|
||||
in core-shape and interchange pass; before it every such part stopped `raea scene` with "unexpected ':' in a
|
||||
shape"; the knife's end-to-end export waits for a raea rebuild
|
||||
|
||||
@needs:IR10
|
||||
Scenario: IR11. Materials go with the geometry
|
||||
Given a part `raea scene export` writes as a mesh
|
||||
Then its GLB carries its material (base colour, metallic, roughness, emissive, the maps raea has as files), so
|
||||
Blender and Godot open it looking as it does in raea, not grey
|
||||
|
||||
@needs:IR10
|
||||
Scenario: IR12. An import measured both ways
|
||||
Given a scene exported by `raea scene export` (scene.json and its meshes)
|
||||
When it is opened in three.js and in Blender
|
||||
Then it is held to raea's own render by IR1's scoring from the same camera, so import and export are measured
|
||||
as the R3F parity is
|
||||
|
||||
Rule: Environments
|
||||
|
||||
@needs
|
||||
Scenario: IR13. A place from one picture
|
||||
Given a picture of a place (a room, a street, a clearing)
|
||||
Then it is made in raea in stages, each checked against the picture from its camera:
|
||||
| stage | what | how |
|
||||
| camera | the lens's field of view and the camera's height and tilt | MoGe-2's point map (MIT, ViT-S 35M) |
|
||||
| layout | the ground and walls as planes, so things stand on them | planes fitted to the point map (RANSAC) |
|
||||
| things | a mask and a name for each thing | SAM 2.1 (Apache-2.0), OWLv2 (Apache-2.0) |
|
||||
| props | each thing as a part at its depth and size | img2raea (IR8), or an image-to-3D model |
|
||||
| far away | what has no depth worth building: a panorama or splat behind | <Environment>, <Splat> (raea splat) |
|
||||
| light | the sun's and sky's direction and colour, then exposure | the picture's shading; systems/light-meter |
|
||||
| contact | nothing floats, sinks or clips | `raea scene lint` |
|
||||
And what can be made procedurally is: terrain, rocks and trees by core/grow, grass by systems/grass, floors and
|
||||
walls by systems/procmat, the picture giving their settings rather than their meshes
|
||||
|
||||
Rule: Where procedural tools, neural networks and measurement belong
|
||||
|
||||
@needs
|
||||
Scenario: IR14. The map
|
||||
Then each step uses what gets it right on this Mac (16 GB first) under a commercial-permissive licence:
|
||||
| step | method | model or tool | licence |
|
||||
| parity score | measure | crop SSIM and RMSE now; LPIPS or DINO next | ours |
|
||||
| a thing's mask | neural | SAM 2.1 (Core ML build exists) | Apache-2.0 |
|
||||
| a thing's name | neural | OWLv2; Apple Vision (systems/vision) | Apache-2.0; system |
|
||||
| depth, lens, normals | neural | MoGe-2 ViT-S; Depth Anything V2 Small, DA3 Small, Base, Mono-L, Metric-L | MIT; Apache-2.0 |
|
||||
| parts of a thing | procedural, fitted | core/shape CSG, core/sdf, core/grow | ours |
|
||||
| a fit's settings | search, judged by measure | render, score against the picture, adjust (CMA-ES or coordinate search) | ours |
|
||||
| a whole object's mesh | neural, as a reference or a start | TripoSG (geometry only, about 8 GB) | MIT |
|
||||
| a character | neural | Idol (sheet3d's route, about 3 GB) | as docs/character.feature |
|
||||
| how close to the picture | neural, as a critic | SigLIP 2 (on the CPU), silhouette IoU | Apache-2.0; ours |
|
||||
| a surface's look | procedural, fitted | systems/procmat's kinds, colours from the mask's lit pixels | ours |
|
||||
And left out, by licence or size: Depth Anything V2 Base and Large and DA3 Large and Giant (CC BY-NC), Depth Pro
|
||||
and SHARP (research only), Hunyuan3D (not the EU, UK or South Korea), TRELLIS.2 (MIT but 24 GB: a reference to
|
||||
compare against, not a step), SAM 3D Objects (SAM Licence, no published memory, reported out of memory at 20 GB)
|
||||
And neural models make or name things; measurement decides whether they are right; procedural parts are what is
|
||||
kept, so a result can be edited as raea's own parts rather than as a mesh no one can change
|
||||
@@ -0,0 +1,159 @@
|
||||
@spec
|
||||
Feature: A render in layers: captions, text, graphics, footage and sound apart, for CapCut, Premiere, Resolve and raea's timeline
|
||||
wackyza, 2026-11-16: "export a rendered video, in all its component layers (video, audio, graphics, all separate) to
|
||||
Premiere, Resolve and Capcut ... keep graphics on one overlay track. Titles aka text elements should be their own
|
||||
track. And captions, if applicable, should be their own track. I think this separation would be valuable for the
|
||||
internal (in-app) timeline as well ... the best order of events might be to get the layers rendering really robust,
|
||||
then be able to push it to the in-app timeline and all the ext editors".
|
||||
|
||||
A cut finished in another editor needs its parts, not one flattened movie. `raea export capcut` (docs/capcut.feature)
|
||||
already hands CapCut the footage and sounds as clips of their own files and everything raea draws as one
|
||||
transparent overlay. This spec takes that split out of the CapCut export, makes it finer (captions and text apart
|
||||
from the other graphics), proves it against the render, and gives it to every editor from one place: CapCut,
|
||||
Premiere Pro and DaVinci Resolve, and the layout of raea's own timeline.
|
||||
|
||||
What there is to build on (read 11-16):
|
||||
- apps/capcut: the manifest's frames grouped into runs of footage and sound (plan.rs), the overlay rendered with
|
||||
the footage hidden (RAEA_HIDE_MEDIA=1) and what's under it (RAEA_HIDE_MEDIA=under), written as a CapCut draft
|
||||
(io/capcut). Its plan is written in CapCut's types, so no other editor can use it as it is.
|
||||
- systems/layers: hide.rs hides layers by key (RAEA_HIDE_LAYERS) and the footage (RAEA_HIDE_MEDIA) as page CSS;
|
||||
page.rs already calls an element whose children are all text "text", and footage "video".
|
||||
- io/alpha: transparent movies without ffmpeg (CC1): ProRes 4444, HEVC with alpha, QuickTime Animation, PNG.
|
||||
- sdk/timeline: tracks by kind (effect, text, overlay, main, sound, TL1a); the captions operation (TL7c) puts
|
||||
lines on a track named Captions, and read.ts writes each line into the composition as a `text` op, the same op
|
||||
a title is written with, so once in the code a caption and a title can't be told apart.
|
||||
|
||||
The layers, top to bottom, and what each is:
|
||||
| layer | what it holds | what the editor gets |
|
||||
| captions | the words said, as raea draws them (CA1) | a transparent movie + an .srt beside |
|
||||
| text | titles and other words on the picture that aren't captions | a transparent movie |
|
||||
| graphics | everything else raea draws over the footage: shapes, 3D, FX | a transparent movie |
|
||||
| footage | each <Video>'s file, at its trims, place and size (CC2a) | clips of the original files |
|
||||
| under | what raea draws beneath the footage: the backgrounds of what | a movie, left out when all black |
|
||||
| | holds it (CC2b) | |
|
||||
| sound | each sound clip, and footage's own sound linked to its clip | audio clips of the original files |
|
||||
A layer with nothing in it is left out, and costs no render.
|
||||
|
||||
The passes cost time only at export. Rendering a composition, in the app or with `raea render`, draws it once, as
|
||||
it does today; the marks LA1 adds are attributes in the code and draw nothing; raea's timeline reads the code (TL0c)
|
||||
and renders no layer. Only `raea export` (layers, capcut, premiere, resolve) renders the layers, each pass once.
|
||||
|
||||
Background:
|
||||
Given a composition renders with --manifest (render.json), as docs/capcut.feature's Background says
|
||||
And the reference render is the composition as `raea render` draws it, every layer at once
|
||||
|
||||
Rule: LA1. Captions and text are marked, so every pass and every tool tells them apart
|
||||
Scenario: LA1a. A caption carries data-raea-role="caption"
|
||||
Given words drawn as captions: lines the captions operation (TL7c) wrote, or a caption the SDK or an agent draws
|
||||
Then the element holding each caption's words carries data-raea-role="caption", and so does everything inside it
|
||||
(a word highlighted as it's said is part of its caption)
|
||||
And the captions operation's `text` ops say they are captions, and the code they write keeps the mark, so a
|
||||
timeline read back from the code (TL0c) puts them on the Captions track again
|
||||
And the raea skill's caption guide says to mark captions this way, and `raea check` names words that look like
|
||||
captions (timed to the transcript, one line at a time, at the bottom third) and aren't marked
|
||||
|
||||
Scenario: LA1b. Text is what Premiere, Resolve and CapCut call text
|
||||
Given a text item in each editor is words and their own style: Premiere's text layer (Essential Graphics),
|
||||
Resolve's Text+, CapCut's text, each with its font, fill, stroke, shadow and a background box of its own
|
||||
Then an element is text when it carries data-raea-role="text", or when it isn't a caption and its children are
|
||||
all words (page.rs's "text"), and it draws as those editors' text does: its words, its stroke and shadow, its
|
||||
own background
|
||||
And the elements around it (a lower third's bar, a card, a shape) are graphics, as a shape is its own item in
|
||||
each editor, so an editor can move the words apart from what they sit on
|
||||
And an element can opt out with data-raea-role="graphics" (a logo set in a font, a number in a chart)
|
||||
|
||||
Rule: LA2. Each layer is a pass of its own, rendered transparent, only when exported
|
||||
Scenario: LA2o. A render that isn't an export draws once
|
||||
Given a composition with captions, text, graphics and footage
|
||||
When it is rendered in the app or with `raea render`
|
||||
Then it is drawn in one pass, in the same time as before this spec, and no layer is written
|
||||
And an export of a version already rendered takes that render as its reference, and doesn't draw it again
|
||||
|
||||
Scenario: LA2a. The passes
|
||||
When the composition is exported in layers
|
||||
Then it is rendered once for each layer that has something in it, --alpha, with RAEA_LAYER naming the layer:
|
||||
| RAEA_LAYER | draws |
|
||||
| captions | only captions |
|
||||
| text | only text |
|
||||
| graphics | what RAEA_HIDE_MEDIA=1 draws today, less captions and text |
|
||||
| under | what RAEA_HIDE_MEDIA=under draws today |
|
||||
And RAEA_HIDE_MEDIA keeps working as it does, so `raea export capcut` from before this spec is unchanged
|
||||
And a pass is cut into clips where it draws something, frames that draw nothing a gap (CC2b)
|
||||
|
||||
Scenario: LA2b. Captions also go out as SubRip
|
||||
Then each run of frames a caption shows one line of words is an entry of NAME.srt: its words as the page shows
|
||||
them (a word highlight doesn't start a new entry), its first frame and the frame after its last, in timecode
|
||||
And the .srt is written beside the export for the person to upload to a network or keep, and no editor's
|
||||
project imports it (the captions movie is what the timeline shows, in raea's own style)
|
||||
|
||||
Rule: LA3. The layers put back together are the render
|
||||
Scenario: LA3a. The layers composited over each other match the reference render
|
||||
Given the layers' movies and the footage's frames as the manifest places them
|
||||
When they are composited bottom to top (under, footage, graphics, text, captions), each over the last
|
||||
Then every frame matches the reference render within the alpha codec's error (CC1a's numbers), checked at
|
||||
least at each clip's first, middle and last frame
|
||||
And a frame that doesn't match names the layer and the element (its key, file:line:col) that draws there
|
||||
|
||||
Scenario: LA3b. What can't be pulled apart is moved, and said
|
||||
Then a caption or a text element that something drawn after it covers goes down into the graphics layer, so
|
||||
what's in front stays in front, and the export says which and why
|
||||
And an element whose look depends on what's under it (mix-blend-mode, backdrop-filter, a mask over footage)
|
||||
stays in the layer that draws what it mixes with, or is named when no layer can hold it
|
||||
And CC2e's notes (filters, rotations, masks, notes and <Mix>) are said as they are
|
||||
|
||||
Scenario: LA3c. A fixture of each kind passes
|
||||
Given fixtures: full-frame footage with a title and captions; a lower third (bar and words); a picture in
|
||||
picture on a coloured card; captions with a word highlight; a title behind a graphic; 3D over footage
|
||||
Then LA3a passes for each, and LA3b's moves and notes are the ones listed for it
|
||||
|
||||
Rule: LA4. One layered timeline, written by `raea export layers`, read by every editor's export
|
||||
Scenario: LA4a. `raea export layers EDIT.tsx -o DIR` writes the layers and their timeline
|
||||
Then DIR holds layers.json, each layer's movie, NAME.srt when there are captions, and reference.mp4 (the
|
||||
reference render, to compare the editor's timeline against; on no timeline)
|
||||
And layers.json says the frame rate, size and length, and the tracks top to bottom, each with its layer and
|
||||
its clips: the file, where it starts and how long, its first source frame, its place and size, its gain and
|
||||
fades, and the id of the clip it's linked to (footage and its own sound)
|
||||
And it says what LA3b moved and what CC2e notes, the same lines the command prints
|
||||
And it names no editor's format: CapCut's draft, Premiere's and Resolve's XML are written from it
|
||||
|
||||
Scenario: LA4b. The CapCut export reads it
|
||||
Then `raea export capcut` is layers.json written as a CapCut draft, with a captions track and a text track
|
||||
above the overlay, and apps/capcut's tests pass as before for a composition with no captions or text
|
||||
And CapCut's tracks keep CapCut's order (TL1a): text above overlays above the main track, sound below
|
||||
And reference.mp4 is copied into the draft's folder, on no track, where CC2d kept it only beside the draft;
|
||||
every export's folder holds it, so the person can compare what the editor plays with what raea rendered
|
||||
|
||||
Rule: LA5. Premiere Pro and DaVinci Resolve take the same XML
|
||||
Scenario: LA5a. `raea export premiere EDIT.tsx` and `raea export resolve EDIT.tsx` write an FCP7 XML project
|
||||
Then each writes a folder: NAME.xml (xmeml version 5), the layers' movies, the .srt (LA2b) and reference.mp4,
|
||||
which the sequence doesn't use
|
||||
And the sequence has the composition's frame rate and size, its video tracks bottom to top under, footage
|
||||
(main, then each picture in picture on a track above), graphics, text, captions, and its audio tracks below
|
||||
And each clip of the original footage points at its file where it is, never copied (CapCut's draft copies,
|
||||
since sandboxed CapCut reads only its own folder, CC2d), at its trim, scaled and placed to its
|
||||
box (Basic Motion), at its gain (Audio Levels)
|
||||
And a video clip and its own sound are linked clipitems, so they move together, and each editor's own control
|
||||
separates them: in Premiere, Unlink; in Resolve, Link Clips off (Cmd/Ctrl+Shift+L); in CapCut, Extract audio
|
||||
And the two commands differ only where Premiere and Resolve read the same XML differently (found in LA5b)
|
||||
|
||||
Scenario: LA5b. Premiere and Resolve open it as raea rendered it
|
||||
Given the LA3c fixtures exported
|
||||
When the XML is imported (Premiere: File, Import; Resolve: File, Import, Timeline)
|
||||
Then every track and clip is where layers.json puts it, nothing is offline, and the frame at each clip's
|
||||
middle matches the reference render
|
||||
And which alpha codecs stay transparent in each is recorded here, with the version tested, and each command
|
||||
uses the first that does
|
||||
|
||||
Rule: LA6. raea's timeline is laid out the same way (raea-feed, after LA1)
|
||||
Scenario: LA6a. A timeline read from the code puts captions, text and graphics on their own tracks
|
||||
Given a composition read as a timeline (TL0c)
|
||||
Then elements marked or found as captions are on the Captions track, text on text tracks and other graphics
|
||||
on overlay tracks, as LA1 says, so the timeline and the exports agree on what each element is
|
||||
And they stay what TL0c makes them: clips that edit the code, not movies
|
||||
|
||||
Rule: LA7. The skill teaches it
|
||||
Scenario: LA7a. The delivery guide teaches layers
|
||||
Then sdk/guides/craft/motion/delivery.md says a cut an editor finishes goes out with raea export capcut,
|
||||
premiere or resolve, that captions arrive styled on their own track with an .srt beside them, and that words
|
||||
are fixed in raea and exported again, since the editors get them as pictures
|
||||
And it says to mark captions (LA1a) and to pass on what the export notes
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "raea blender"
|
||||
summary: "Run a Blender Python script headless, with raea's library of mesh scripts: convert, decimate, repair, split, bake, rig, cloth."
|
||||
order: 105
|
||||
order: 106
|
||||
sources: ["apps/tools/src/blender.rs", "apps/engines/src/blender_ts.rs"]
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
title: "raea bug"
|
||||
summary: "Report a bug in raea itself to raea's server: a line saying what's wrong and what happened, with raea's version and the OS added, no account needed."
|
||||
order: 129
|
||||
sources: ["engine/cli/src/bug.ts", "engine/cli/src/cli.rs"]
|
||||
---
|
||||
|
||||
Report a bug in raea itself to raea's server: a line saying what's wrong and what happened, with raea's version and the OS added, no account needed.
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea bug TITLE... --text TEXT [--command CMD] [--error TEXT] [--agent NAME] [--dry-run] (a bug in raea itself, not in your own composition, sent to raea's server with raea's version and the OS, no account needed: words only, paths, emails and keys taken out before it goes; five a day from a machine, the same bug again counted on the first report; --dry-run prints what would go and sends nothing)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
|
||||
|
||||
## Flags
|
||||
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--agent` | `NAME` | Who is reporting: the agent or harness's name (claude-code, codex, kimi). Unless said, `RAEA_AGENT`, else the harness raea finds it running under. |
|
||||
| `--command` | `CMD` | The raea command that went wrong, as you ran it (paths in it are taken out). |
|
||||
| `--dry-run` | – | Print exactly what would be sent, raea's version and the OS included, and send nothing. |
|
||||
| `--error` | `TEXT` | What the command printed when it went wrong, up to 4,000 characters (paths, emails and keys taken out). |
|
||||
| `--text` | `TEXT` | What you did, what you expected and what happened instead, up to 4,000 characters. Needed. |
|
||||
|
||||
<!-- generated:end -->
|
||||
|
||||
`raea bug` is how an agent tells raea about a bug it thinks it found in raea itself: a command that fails or hangs, a
|
||||
result that's wrong, or help that says one thing while raea does another. It's for raea's bugs, not the composition
|
||||
you're writing. It works in any shell, headless or in the app, and needs no account.
|
||||
|
||||
The report is words only. raea adds its version and the OS, and takes out paths, emails and anything shaped like a
|
||||
key or token before it leaves the machine; raea's server takes them out again. A machine sends at most five a day,
|
||||
and the same bug sent again (by the same line, numbers and paths aside, on the same version) is counted on the first
|
||||
report instead of being kept twice. `--dry-run` prints exactly what would be sent and sends nothing.
|
||||
|
||||
```sh
|
||||
raea bug "raea render stops at frame 12 with no error" \
|
||||
--text "Rendered compositions/teaser.tsx to mp4; it printed frame 12 of 240 and exited 0 with no file." \
|
||||
--command "raea render compositions/teaser.tsx -o out/teaser.mp4" --error "frame 12/240"
|
||||
```
|
||||
@@ -1,18 +1,18 @@
|
||||
---
|
||||
title: "raea clothes"
|
||||
summary: "Clothes for SOMA's body from words: make has an image model (flux_2_pro, one picture a view, at most N cents each, 10 unless said) dress SOMA's grey mannequin from the front, back, left and right, then measures the pictures onto SOMA's own vertices as assets/clothes/NAME.json, its pictures in assets/clothes/NAME/."
|
||||
summary: "Clothes for SOMA's body from words: make sews a garment from a sewing pattern (GarmentCode, MIT), cut to SOMA's measurements and draped by raea's own cloth, as assets/clothes/NAME.json and its .glb; cover lays one on the skin by procedure; wear puts garments on a body."
|
||||
order: 104
|
||||
sources: ["engine/cli/src/cli.rs"]
|
||||
---
|
||||
|
||||
Clothes for SOMA's body from words: make has an image model (flux_2_pro, one picture a view, at most N cents each, 10 unless said) dress SOMA's grey mannequin from the front, back, left and right, then measures the pictures onto SOMA's own vertices as assets/clothes/NAME.json, its pictures in assets/clothes/NAME/.
|
||||
Clothes for SOMA's body from words: make sews a garment from a sewing pattern (GarmentCode, MIT), cut to SOMA's measurements and draped by raea's own cloth, as assets/clothes/NAME.json and its .glb; cover lays one on the skin by procedure; wear puts garments on a body.
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea clothes [make NAME "WHAT IT IS, AS WORN" [--over UNDER[,UNDER...]] [--max-cents N] | remeasure NAME | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] | wear OUT_DIR GARMENT... [--body DIR]] (clothes for SOMA's body from words: make has an image model (flux_2_pro, one picture a view, at most N cents each, 10 unless said) dress SOMA's grey mannequin from the front, back, left and right, then measures the pictures onto SOMA's own vertices as assets/clothes/NAME.json, its pictures in assets/clothes/NAME/; --over draws it over garments already made (innermost first), as the next layer, a garment made by procedure drawn on the mannequin first; remeasure measures a garment again from its kept pictures (after raea's measuring changed), nothing drawn or paid for; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said); wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder and needs Blender: raea setup blender)
|
||||
raea clothes [make NAME ["WHAT IT IS"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] [--hard [--sole MM] [--sole-colour #RRGGBB] [--panels #RRGGBB,...]] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make sews a garment: a sewing pattern (GarmentCode, MIT) from the words, or the plain base with --plain, its settings changed by --set PATH=VALUE (settings lists them and what each may be), cut to SOMA's measurements, draped by raea's own cloth and baked, as assets/clothes/NAME.json and its .glb, in --colour or the palette's next; the first make sets up GarmentCode and its Python in raea's models folder; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said), --over a garment already made as the one under it; wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder and needs Blender: raea setup blender)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
|
||||
@@ -22,23 +22,32 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--body` | `DIR` | With `wear`: dress this SOMA body folder (body.glb, skeleton.json) instead of SOMA's own, such as a headless body that a generated head joins at the collar. |
|
||||
| `--colour` | `#RRGGBB` | With `cover`: the garment's one colour. |
|
||||
| `--max-cents` | `N` | With `make`: the most one of the four pictures may cost, in cents (10 unless said). |
|
||||
| `--over` | `UNDER` | With `make`: draw the garment over garments already made, innermost first, comma-separated, as the next layer. With `cover`: lay it over one garment, a layer's thickness off it. |
|
||||
| `--colour` | `#RRGGBB` | The garment's one colour. With `make` it is optional: one is picked from the name unless said. |
|
||||
| `--hard` | – | With `cover`: footwear, made as a hard piece. Each foot gets its own shape: a rounded last around the foot, so the toes and the foot's small forms go under it. Underneath is a flat sole, and the top over the leg is left open as the collar. It is skinned to the foot like the skin it covers, and it does not swing. |
|
||||
| `--head` | `HEAD_DIR` | With `wear`: the head folder (head.json, head.glb) that joins a headless body at the collar. The body's skin takes the head's neck colour and is graded to the head's own skin just under the collar, so no step of colour shows at the join. |
|
||||
| `--over` | `UNDER` | With `cover`: lay it over one garment made by `cover`, a layer's thickness off it. |
|
||||
| `--panels` | `#RRGGBB,...` | With `cover --hard`: the colours of up to three panels, in this order: a toe cap, a heel, and a band along each side. |
|
||||
| `--parts` | `PART` | With `cover`: the body's parts the garment covers, comma-separated; a limb takes a share, how far along it from its top (`foreArm:0.5` is the half nearest the elbow). |
|
||||
| `--plain` | – | With `make`: start from the plain base (a short-sleeved top) instead of a pattern guessed from words. The default when no words are given. |
|
||||
| `--set` | `PATH=VALUE,...` | With `make`: change settings of the garment's pattern by path, comma-separated (`sleeve.length=0.9,meta.bottom=Pants`). A choice must be one of its options and a number within its range; `raea clothes settings` lists them. |
|
||||
| `--sole` | `MM` | With `cover --hard`: the sole's thickness in millimetres (10 unless said, at most 60). Most of it is painted up the side; the bottom sits at most 8 mm below the bare foot, so the person does not sink into the floor. |
|
||||
| `--sole-colour` | `#RRGGBB` | With `cover --hard`: the sole's colour (an off-white unless said). |
|
||||
| `--stand` | `MM` | With `cover`: how far the cloth stands off the skin, in millimetres (6 unless said). |
|
||||
|
||||
<!-- generated:end -->
|
||||
|
||||
## An outfit, layer by layer
|
||||
## An outfit
|
||||
|
||||
```sh
|
||||
raea clothes cover tee --parts chest,torso,waist,upperArm:0.45 --colour "#e8e4da"
|
||||
raea clothes cover shorts --parts hips,thigh:0.55 --colour "#2b3a55" --stand 7
|
||||
raea clothes make overshirt "a red and black buffalo-check flannel overshirt, worn open" --over tee,shorts
|
||||
raea clothes wear assets/characters/flannel tee shorts overshirt
|
||||
raea clothes make tee --plain --set shirt.length=1.5 --colour "#e8e2d6"
|
||||
raea clothes make trousers --set meta.upper=none,meta.bottom=Pants,meta.wb=StraightWB,pants.length=0.8 --colour "#2f3b52"
|
||||
raea clothes wear assets/characters/dressed trousers tee
|
||||
```
|
||||
|
||||
The first two are made by procedure and cost nothing. The third has an image model draw the mannequin's four views over the first two, one picture a view (about 20 cents), and measures them onto SOMA's vertices; look at its pictures in `assets/clothes/overshirt/views` before you wear it. `wear` writes a body folder and prints the lines that put it in a composition: `registerBody` with the folder, and each garment's `.glb` as one of `<Character>`'s `parts`.
|
||||
`make` sews a garment: a sewing pattern (flat pieces joined by seams) cut to SOMA's measurements, draped on the body by gravity and baked to a skinned glb. It costs nothing and takes about 20 seconds. The pattern comes from the plain base (a short-sleeved top) with `--plain` or when no words are given, and each `--set PATH=VALUE` changes one of its settings; `raea clothes settings` lists them all with what each may be. Given words (`raea clothes make hoodie "a hooded sweatshirt"`), the pattern is the garment model's first guess from them; the command says what it made, and `--set` corrects it.
|
||||
|
||||
A garment is a file on SOMA's template vertices, so the same file dresses every SOMA body. It lies on the skin at a measured stand-off: cloth that hangs free of the body (a skirt, a coat's tails, a shirt hanging over the hips) is not made by this command yet.
|
||||
The first use sets up what sewing runs on in raea's models folder (`garments/`): GarmentCode's pattern components (MIT) at a fixed commit, a Python 3.11 environment made by `uv`, and SOMA's body as a distance grid for the drape.
|
||||
|
||||
A sewn garment is `assets/clothes/NAME.json` with its files in `assets/clothes/NAME/`: the glb, the design, the flat pattern and four pictures of it on the mannequin. Look at the pictures before you wear it.
|
||||
|
||||
`cover` lays a garment on the skin by procedure, for what is skin-tight; it can't hang free. `wear` writes a body folder with each garment's glb and the body without the skin that is wholly under cloth; with `--head`, the body's skin is graded to the head at the collar.
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "raea godot"
|
||||
summary: "Run a TypeScript script against Godot's whole API in a headless Godot with GodotJS, record what it draws as frames, or open the editor on the project."
|
||||
order: 106
|
||||
order: 107
|
||||
sources: ["apps/engines/src/godot.rs", "apps/engines/src/godot_run.rs"]
|
||||
---
|
||||
|
||||
|
||||
@@ -104,13 +104,14 @@ Music read, foley and instruments made on this machine.
|
||||
|
||||
## Generate and 3D tools
|
||||
|
||||
Generated media, physics bakes, clothes for SOMA's body, Blender and Godot.
|
||||
Generated media, physics bakes, clothes and motion for SOMA's body, Blender and Godot.
|
||||
|
||||
| Verb | What it does |
|
||||
| --- | --- |
|
||||
| [`raea gen`](gen.md) | Generate images, video, music, sound, speech, 3D models and text through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI. |
|
||||
| [`raea physics`](physics.md) | Make the bakes <Physics> and <Goo> play: rigid bodies, soft goo, and parts cut out of a .glb. |
|
||||
| [`raea clothes`](clothes.md) | Clothes for SOMA's body from words: make has an image model (flux_2_pro, one picture a view, at most N cents each, 10 unless said) dress SOMA's grey mannequin from the front, back, left and right, then measures the pictures onto SOMA's own vertices as assets/clothes/NAME.json, its pictures in assets/clothes/NAME/. |
|
||||
| [`raea clothes`](clothes.md) | Clothes for SOMA's body from words: make sews a garment from a sewing pattern (GarmentCode, MIT), cut to SOMA's measurements and draped by raea's own cloth, as assets/clothes/NAME.json and its .glb; cover lays one on the skin by procedure; wear puts garments on a body. |
|
||||
| [`raea motion`](motion.md) | Body motion made on this Mac by Kimodo (NVIDIA, on MLX): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads. |
|
||||
| [`raea blender`](blender.md) | Run a Blender Python script headless, with raea's library of mesh scripts: convert, decimate, repair, split, bake, rig, cloth. |
|
||||
| [`raea godot`](godot.md) | Run a TypeScript script against Godot's whole API in a headless Godot with GodotJS, record what it draws as frames, or open the editor on the project. |
|
||||
|
||||
@@ -127,5 +128,6 @@ What an agent reads and shows the person, and the tools raea installs.
|
||||
| [`raea skill`](skill.md) | Print the agent skill this raea ships, matched to its version, or one of its references. |
|
||||
| [`raea skills`](skills.md) | Install raea's agent skill where Claude Code, Codex, Kimi or Gemini read skills, with its MCP server and hook. |
|
||||
| [`raea setup`](setup.md) | Find Blender, or download its current LTS, and install raea's add-on and the MCP add-on. |
|
||||
| [`raea bug`](bug.md) | Report a bug in raea itself to raea's server: a line saying what's wrong and what happened, with raea's version and the OS added, no account needed. |
|
||||
|
||||
<!-- generated:end -->
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
title: "raea motion"
|
||||
summary: "Body motion made on this Mac by Kimodo (NVIDIA, on MLX): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads."
|
||||
order: 105
|
||||
sources: ["engine/cli/src/cli.rs"]
|
||||
---
|
||||
|
||||
Body motion made on this Mac by Kimodo (NVIDIA, on MLX): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads.
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
raea motion "LINE" [--keys KEYS.json] [--seconds 5 | --frames N] [--seed 1] [--steps 100] [-o CLIP.json] (body motion made on this Mac by Kimodo (NVIDIA, on MLX): a SOMA clip from a line of words and, with --keys, Kimodo constraints (full-body keyframes, hand or foot targets, a root path, as sdk/body/tools/between.ts writes them), as the clip sdk/body/tools/fromkimodo.ts reads; the first use fetches the motion model (1.1 GB) into raea's models folder, and the first new line its text encoder (8.8 GB: Llama 3 8B in 8 bits with LLM2Vec's adapters); a line's words are read once and kept. Licences: Kimodo's weights NVIDIA's Open Model License, Meta Llama 3 the Meta Llama 3 Community License, LLM2Vec's adapters MIT)
|
||||
```
|
||||
|
||||
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
|
||||
|
||||
## Flags
|
||||
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--frames` | `N` | The clip's length in frames at 30 a second, 2 to 600. Instead of `--seconds`. |
|
||||
| `--keys` | `KEYS.json` | Kimodo constraints the motion must meet: full-body keyframes, a hand or foot at a place on a frame, a path for the hips. `bun sdk/body/tools/between.ts` writes them between two poses of the body library. |
|
||||
| `--seconds` | `5` | The clip's length in seconds (5 unless said). |
|
||||
| `--seed` | `1` | Which of the motions the line could be: another seed is another take of the same line. A seed here is not that seed on Kimodo's PyTorch code (the noise is drawn differently). |
|
||||
| `--steps` | `100` | Denoising steps (Kimodo's 100). Fewer is faster and rougher. |
|
||||
| `-o` | `CLIP.json` | Where the clip goes: `{fps, names, root, turns, contacts, ...}`, Kimodo's 77 SOMA joints as each one's turn in the world from the T-pose. Without it, the line's words name the file in the working folder. |
|
||||
|
||||
<!-- generated:end -->
|
||||
|
||||
## Example
|
||||
|
||||
A stage's `do` line made into a clip: the body stands at the start and the end, and the motion between comes from the
|
||||
words.
|
||||
|
||||
```sh
|
||||
bun sdk/body/tools/between.ts skeleton.json LIBDIR aMale2_A1_Stand:0 aMale2_A1_Stand:0 stand.json 4 0,0 0
|
||||
raea motion "A person waves at the camera with their right hand" --keys stand.json --seconds 4 --seed 2 -o wave.clip.json
|
||||
```
|
||||
|
||||
A clip takes about 8 seconds on an M5 Pro. `bun sdk/body/tools/makedo.ts` does the whole of it for a stage's lines:
|
||||
three seeds a line, each checked against the captures the body hands on to, and the one that does the most kept in the
|
||||
project's made clips.
|
||||
@@ -12,9 +12,15 @@ with [`raea setup-audio`](setup-audio.md)).
|
||||
|
||||
```sh
|
||||
raea sao "a heavy wooden door creaks open" --seconds 3 -o door.wav
|
||||
raea sao "rain on a tin roof" --seconds 8 --seed 4
|
||||
raea sao "rain on a tin roof" --seconds 8 --seed 4 -o media/sfx/rain-4.wav
|
||||
```
|
||||
|
||||
A take is up to 11.9 s long; a longer `--seconds` comes back that long. Another `--seed` is another take of the same
|
||||
prompt: `sao()` in a composition has no seed, so play a seed's take from its file (`staticFile("sfx/rain-4.wav")`).
|
||||
Stable Audio Open Small does better on effects and field recordings than on music, so build an effect from short
|
||||
layers (a transient, a body, a tail) and write music as notes on instruments (`raea guide music`). Its licence is
|
||||
Stability AI's Community License: [`raea setup-audio`](setup-audio.md) says what that means.
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -14,6 +14,35 @@ raea setup-audio --check
|
||||
raea setup-audio tokensynth
|
||||
```
|
||||
|
||||
Each model's script (`share/raea/tools/sao/setup.sh` and `share/raea/tools/tokensynth/setup.sh` beside an installed
|
||||
raea) installs it into `~/.cache/raea-sao` or `~/.cache/raea-tokensynth` (`RAEA_SAO` and `RAEA_TOKENSYNTH` move them):
|
||||
|
||||
- **SAO, about 2 GB:** Stable Audio Open Small's Core ML models from a Hugging Face mirror at a pinned revision, each
|
||||
file checked against its SHA-256, t5-base's tokenizer, a small Python environment, and a T5 encoder converted once.
|
||||
Its licence is Stability AI's Community License
|
||||
([stability.ai/community-license-agreement](https://stability.ai/community-license-agreement)), not an open one.
|
||||
As between you and Stability, you own the sounds it makes, as far as the law allows; they may not be used to
|
||||
create or improve another generative AI model, and Stability's acceptable use policy applies to them. What else
|
||||
the licence asks, of raea and of a commercial user, raea hasn't written down yet: read it before an SAO sound goes
|
||||
into a commercial piece.
|
||||
- **TokenSynth, about 6 GB:** its code from GitHub, a Python environment with torch, and its weights, DAC and CLAP
|
||||
from Hugging Face, then a converted fp16 runtime. MIT.
|
||||
|
||||
Both need a network connection and [uv](https://docs.astral.sh/uv/) on the PATH; TokenSynth also needs `git`. On a
|
||||
Mac without them, `share/raea/tools/ensure.sh uv` and `ensure.sh git` install raea's pinned builds (uv 0.12.24 and
|
||||
git 2.56.0, each download checked against its SHA-256) and print where; put those folders on the PATH:
|
||||
|
||||
```sh
|
||||
B=$(dirname "$(realpath "$(command -v raea)")"); T=$B/../share/raea/tools; [ -d "$T" ] || T=$B/../../tools # an install, or a checkout
|
||||
PATH="$(dirname "$(bash "$T/ensure.sh" uv)"):$(dirname "$(bash "$T/ensure.sh" git)"):$PATH" raea setup-audio
|
||||
```
|
||||
|
||||
When a setup fails, the error names its script: run that with `sh` to see why. Exit status 127 is uv not found; 1
|
||||
with `xcrun: error: invalid active developer path` is macOS's stand-in git on a Mac without the Command Line Tools
|
||||
(use the git `ensure.sh` installs); 75 is another setup running in the same folder. `RAEA_OFFLINE` refuses the
|
||||
download. `RAEA_AUDIO_AUTOSETUP=0` stops a render from installing a model itself, and stops `raea setup-audio` and
|
||||
`ensure.sh` too: with it set, run the model's script yourself (`sh share/raea/tools/sao/setup.sh`).
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -11,10 +11,16 @@ Tone.js `Sampler`. For a pitched instrument it takes one sample per note, at the
|
||||
|
||||
```sh
|
||||
raea sounds piano
|
||||
raea sounds get vcsl/upright-piano --notes C2,C3,C4,C5 -o media/piano/
|
||||
raea sounds get vcsl/bass-drum --all
|
||||
raea sounds get vcsl/upright-piano-knight --notes C2,C3,C4,C5 -o media/piano/
|
||||
raea sounds get vcsl/bass-drum-1 --all
|
||||
```
|
||||
|
||||
The ids are exact: `raea sounds kick` lists the kicks by their ids (`vcsl/bass-drum-1`, `-2`, `-3-legacy`). A drum or a
|
||||
hit comes as its first 12 takes unless `--all` is given. The four libraries are Salamander's grand piano, FluidR3's
|
||||
General MIDI set and tonejs-instruments (all three CC-BY 3.0: credit them), and the Versilian Community Sample Library
|
||||
(CC0). Larger libraries, effect packs and MIDI grooves are fetched by hand: `raea guide sources` lists them with
|
||||
their licences and the command that fetches each.
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
|
||||
## Usage
|
||||
@@ -29,7 +35,7 @@ Headless: it needs nothing running and opens no window. Takes up to 2 arguments
|
||||
|
||||
| Flag | Takes | What it does |
|
||||
| --- | --- | --- |
|
||||
| `--all` | – | Fetch every sample the instrument has: every note, dynamic and round robin. |
|
||||
| `--all` | – | Fetch every sample: a pitched instrument's every sampled note (still one take a note, at the middle dynamic), a drum's every take. |
|
||||
| `--notes` | `..\|--all` | Fetch only these notes, comma-separated (`C2,C4`). |
|
||||
| `-o` | `DIR` | The folder the samples go to. |
|
||||
|
||||
|
||||
@@ -11,9 +11,13 @@ writes one file per note: a sample set for a Sampler. Like `raea sao`, it shares
|
||||
|
||||
```sh
|
||||
raea tokensynth "warm analog bass" --notes C1,C2,C3 -o media/bass/
|
||||
raea tokensynth "glassy bell pad" --seconds 4 --velocity 80
|
||||
raea tokensynth "a bowed saw, close, eerie" --notes C3,E3,G#3,C4 --seconds 4 --velocity 80 --seed 7
|
||||
```
|
||||
|
||||
Use it for a timbre no recorded library has ([`raea sounds`](sounds.md) first for a piano, strings or drums). A take
|
||||
can miss its pitch or come out as hiss, so make a few seeds of each root and keep the ones that pass
|
||||
(`raea guide music`, "Instruments from TokenSynth"). A note is held under 5 s.
|
||||
|
||||
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -288,6 +288,7 @@ Used in: [ui/widgets/viewport_node](https://github.com/shinyobjectz/raea/blob/ma
|
||||
Light from all around, out of a panorama: soft light from the sky and reflections of it in every glossy or metal
|
||||
surface (image-based lighting), and with `background` the panorama as the sky. Put it inside the Canvas3D, once a
|
||||
frame; its src, intensity, rotation and background may change from frame to frame (a cut from a hall to a street).
|
||||
With `room` in place of a panorama it is three.js's RoomEnvironment, soft studio light with no file.
|
||||
Bevy's EnvironmentMapLight with maps already filtered is <EnvironmentMapLight>.
|
||||
Its panorama is filtered by Bevy's generator and, with `background`, drawn as the sky (engine/render
|
||||
environment.rs):
|
||||
@@ -1522,7 +1523,9 @@ The props of [`Entity`](#entity), tabled there.
|
||||
|
||||
| Field | Type | What it is |
|
||||
| --- | --- | --- |
|
||||
| `src` (required) | `string` | an equirectangular panorama in the media folder: a Radiance.hdr (Poly Haven's), an OpenEXR.exr, or an 8-bit.png/.jpg. Change it between frames to cut from one place to another |
|
||||
| `src` | `string` | an equirectangular panorama in the media folder: a Radiance.hdr (Poly Haven's), an OpenEXR.exr, or an 8-bit.png/.jpg. Change it between frames to cut from one place to another. Give it or `room`, not both |
|
||||
| `room` | `boolean` | three.js's RoomEnvironment in place of a panorama: a white studio room with soft light boxes, made by raea with no file. It is the light a three.js scene gets from PMREMGenerator.fromScene(new RoomEnvironment(), blur), which <R3F> turns into this |
|
||||
| `blur` | `number` | with `room`, its blur in radians before it lights (fromScene's sigma: three's examples use 0.04); 0 by default |
|
||||
| `intensity` | `number` | how strongly it lights the scene (1 by default: a sky about as bright as an AmbientLight of 2.5 overall); animate it, or set 0 to switch it off for a shot |
|
||||
| `rotation` | `number` | a turn about the vertical axis, in radians, for both the light and the sky: puts the sun where the shot wants it |
|
||||
| `background` | `boolean` | draw the panorama as the sky behind everything (off by default: light only) |
|
||||
@@ -2281,7 +2284,7 @@ The props of [`Screen`](#screen), tabled there.
|
||||
| `background` | `string` | behind the picture ("#000000"). A see-through one ("#ffffff00", "transparent", rgba(..., 0.5)) makes the screen see-through where its page paints nothing, so what's behind it in the scene shows (a flat screen: a layer of a page pulled apart in 3D); an opaque one keeps the screen opaque, which writes depth for DepthOfField |
|
||||
| `brightness` | `number` | a flat screen's (`crt={false}`) light: 1, the default, draws its page at the page's own colours, unlit (scene lights don't touch it); above 1 it glows, and blooms under a <Bloom>. A tone curve on the camera bends it like the rest of the frame: give the scene <ToneMapping mode="none" /> to keep the page's colours exact. A CRT's is `crt.brightness` |
|
||||
| `src` | `string` | a video to show instead of children: staticFile("clip.mp4"), filling the picture |
|
||||
| `app` | `string` | an app to show instead of children: a module's path from the composition's folder ("chat.tsx"), its default export a React component given {width, height}. It runs on real react-dom in a document of its own, so npm's React libraries work on it (assistant-ui, Radix; installed with `raea add`). In play the pointer reaches it through the 3D, where it lands on the picture, and a press on it gives it the keys (the game doesn't get them) until a press elsewhere or Escape; in a render it runs on the frame's clock, so the render repeats |
|
||||
| `app` | `string` | an app to show instead of children: a module's path from the composition's folder ("chat.tsx"), its default export a React component given {width, height}. It runs on react-dom (@raea/ui's) in a Blitz document of its own, so npm's React libraries work on it (assistant-ui, Radix; installed with `raea add`). In play the pointer reaches it through the 3D, where it lands on the picture, and a press on it gives it the keys (the game doesn't get them) until a press elsewhere or Escape; in a render it runs on the frame's clock, so the render repeats |
|
||||
| `children` | `ReactNode` | the nested composition or game |
|
||||
|
||||
### `Section`
|
||||
|
||||
@@ -17,8 +17,8 @@ import { Audio, Mix } from "raea/audio";
|
||||
function Soundtrack() {
|
||||
return (
|
||||
<Mix lufs={-14} ceiling={-1}>
|
||||
<Audio src={staticFile("media/voice.wav")} bus="voice" />
|
||||
<Audio src={staticFile("media/bed.m4a")} bus="music" gainDb={-12} fadeOut={1.5} />
|
||||
<Audio src={staticFile("voice.wav")} bus="voice" />
|
||||
<Audio src={staticFile("rain.m4a")} bus="ambience" gainDb={-18} fadeOut={1.5} />
|
||||
</Mix>
|
||||
);
|
||||
}
|
||||
@@ -40,7 +40,7 @@ Sound in step with the frame; no picture. A muted or ended Audio is silent.
|
||||
|
||||
| Prop | Type | What it does |
|
||||
| --- | --- | --- |
|
||||
| `src` (required) | `string \| GeneratedAsset` | a file URL, or a generated asset from lyria() or sao() |
|
||||
| `src` (required) | `string \| GeneratedAsset` | a file URL (staticFile), or a generated sound from sao() |
|
||||
|
||||
Also takes the props of [`MediaProps`](video.md#mediaprops).
|
||||
|
||||
|
||||
@@ -90,6 +90,7 @@ Used in: [ui/render_ui_to_texture](https://github.com/shinyobjectz/raea/blob/mai
|
||||
Light from all around, out of a panorama: soft light from the sky and reflections of it in every glossy or metal
|
||||
surface (image-based lighting), and with `background` the panorama as the sky. Put it inside the Canvas3D, once a
|
||||
frame; its src, intensity, rotation and background may change from frame to frame (a cut from a hall to a street).
|
||||
With `room` in place of a panorama it is three.js's RoomEnvironment, soft studio light with no file.
|
||||
Bevy's EnvironmentMapLight with maps already filtered is <EnvironmentMapLight>.
|
||||
Its panorama is filtered by Bevy's generator and, with `background`, drawn as the sky (engine/render
|
||||
environment.rs):
|
||||
@@ -384,7 +385,9 @@ The props of [`DirectionalLight`](#directionallight), tabled there.
|
||||
|
||||
| Field | Type | What it is |
|
||||
| --- | --- | --- |
|
||||
| `src` (required) | `string` | an equirectangular panorama in the media folder: a Radiance.hdr (Poly Haven's), an OpenEXR.exr, or an 8-bit.png/.jpg. Change it between frames to cut from one place to another |
|
||||
| `src` | `string` | an equirectangular panorama in the media folder: a Radiance.hdr (Poly Haven's), an OpenEXR.exr, or an 8-bit.png/.jpg. Change it between frames to cut from one place to another. Give it or `room`, not both |
|
||||
| `room` | `boolean` | three.js's RoomEnvironment in place of a panorama: a white studio room with soft light boxes, made by raea with no file. It is the light a three.js scene gets from PMREMGenerator.fromScene(new RoomEnvironment(), blur), which <R3F> turns into this |
|
||||
| `blur` | `number` | with `room`, its blur in radians before it lights (fromScene's sigma: three's examples use 0.04); 0 by default |
|
||||
| `intensity` | `number` | how strongly it lights the scene (1 by default: a sky about as bright as an AmbientLight of 2.5 overall); animate it, or set 0 to switch it off for a shot |
|
||||
| `rotation` | `number` | a turn about the vertical axis, in radians, for both the light and the sky: puts the sun where the shot wants it |
|
||||
| `background` | `boolean` | draw the panorama as the sky behind everything (off by default: light only) |
|
||||
|
||||
@@ -69,7 +69,7 @@ Sound in step with the frame; no picture. A muted or ended Audio is silent.
|
||||
|
||||
| Prop | Type | What it does |
|
||||
| --- | --- | --- |
|
||||
| `src` (required) | `string \| GeneratedAsset` | a file URL, or a generated asset from lyria() or sao() |
|
||||
| `src` (required) | `string \| GeneratedAsset` | a file URL (staticFile), or a generated sound from sao() |
|
||||
|
||||
Also takes the props of [`MediaProps`](video.md#mediaprops).
|
||||
|
||||
|
||||
+61
-1
@@ -25,12 +25,15 @@ Feature: Plans: a project's plan.org, kept by its agents
|
||||
# (Rust, engine/cli), so reference/files.md, generated from it, doesn't list one; the page makes it on the first
|
||||
# write. The brief page (BriefView, unmounted) still draws a brief's own ## Tasks. Compositions can't import
|
||||
# @raea/task until sdk/tsconfig.base.json and raea's bundler map it.
|
||||
# 11-16: PL7, agents finish what they plan (raea-feed plan-finish: plan/keeper.ts, PlanKeeper.tsx; sdk/task tools.ts).
|
||||
# Checked in raea's window: e2e chat-plan 2 of 2 with a real ACP stand-in planning through the tool port, and
|
||||
# chat-goal, respawn, todo, outside, heads, primary, consolidate, ai-login unchanged; vitest 1621; sdk/task 33.
|
||||
|
||||
Background:
|
||||
Given the app's code is apps/app (raea-feed), the SDK sdk/task, the skill skills/raea/plan.md in raea-skills
|
||||
And the plan's tests: sdk/task/test/*.test.ts (PL2, PL3, PL5, PL6), apps/app src/plan/plan.test.ts (PL1c, PL4, PL4c,
|
||||
PL5), src/plan/agent.test.ts (PL5a, PL5b), host/plan.test.ts (PL4, PL5), src/feed/todo.test.ts and outside.test.ts
|
||||
(PL4b), e2e/todo.spec.ts (PL4b)
|
||||
(PL4b), e2e/todo.spec.ts (PL4b), apps/app src/plan/keeper.test.ts and e2e/chat-plan.spec.ts (PL7)
|
||||
|
||||
Rule: PL1. A project's plan is plan.org at the top of its folder
|
||||
# Why there: it's the project's own file, versioned with it in the workspace's repo, found by anyone who opens the
|
||||
@@ -198,3 +201,60 @@ Feature: Plans: a project's plan.org, kept by its agents
|
||||
Then usePlan(text or source) gives the plan, its text and edit; useView a registered view; TaskLine, PlanOutline,
|
||||
Agenda and BoardLanes draw them, with toggled for a checkbox's edit
|
||||
And none of it uses a dynamic import or dangerouslySetInnerHTML, so raea's window bundle (one IIFE) holds it
|
||||
|
||||
Rule: PL7. An agent finishes what it planned
|
||||
# Shane, 2026-11-16: "i notice often that it makes tasks but never completes them itself". His plans that morning:
|
||||
# TarotChess's agent posted a first pass and left its own follow-ups TODO (frame rate, a clipping score, a dark
|
||||
# encode); Cadence's said "all six masters are finished and posted" over a plan still saying Track MAKING and Build,
|
||||
# Render and Masters TODO (it had woken itself on a render's report, a turn raea sends no plan with); v0.1.5's
|
||||
# closed five tasks with every checkbox unticked, so the list read 0/4 on finished work; and its last turn ended
|
||||
# with Film v2's tasks MAKING, "waiting on three helpers", when the session stopped under them. Nothing asked any
|
||||
# of them to go on: only a /goal does that, and only when the person sets one.
|
||||
|
||||
@done
|
||||
Scenario: PL7a. Each time an agent stops with tasks of its own open, raea asks it to settle them
|
||||
Given a chat in a project whose agent's turn ends (apps/app src/plan/PlanKeeper.tsx, beside GoalKeeper)
|
||||
And tasks of its own are TODO or MAKING in the plan, read from the file first
|
||||
Then raea's next turn to it lists them by id ("[raea plan] Ask N: ...") and says how each is settled: closed with
|
||||
the item it made, done now and closed, REVIEW saying what it needs from the person, dropped with why, or a
|
||||
line starting "WAITING:" naming the job of its own that will report back
|
||||
And it asks again each time the agent stops while one is TODO or MAKING; REVIEW is the person's, and ends it
|
||||
And the rule each turn carries says the same: finish what you planned; before you stop, every task of yours is
|
||||
closed, REVIEW or waiting on a job; close what a job finished when it reports back in a turn you started
|
||||
|
||||
@done
|
||||
Scenario: PL7b. The asks stop
|
||||
Then they stop when none of its tasks is TODO or MAKING, or pause, saying why, when the person presses Stop, its
|
||||
session closes or the turn fails, its reply has a WAITING: line, two asks in a row leave the plan as it was, or
|
||||
12 have gone since the person's last message
|
||||
And the person's next message starts them again from nothing, and Continue over the composer asks at once
|
||||
And a chat with an open /goal is the goal's: its checks keep it going, and the plan's asks wait until it's met
|
||||
|
||||
@done
|
||||
Scenario: PL7c. Which tasks are the agent's
|
||||
Then a task is the chat's when its agent (or the chat) holds it; or nobody holds it and it stands on an item the
|
||||
chat posted (its :ITEM:, or a note's item in its :FROM:: an agent writing plan.org by hand leaves :AGENT: out);
|
||||
or nobody holds it and it's MAKING while no other agent holds open work
|
||||
And a task nobody holds otherwise is the person's (written in the to-do list or Emacs, moved from a brief): never
|
||||
pushed on whoever is chatting; one SCHEDULED for a later day waits for that day
|
||||
|
||||
@done
|
||||
Scenario: PL7d. Done means its checkboxes and subtasks are done
|
||||
When an agent marks a task done (plan_close, or plan_update's state) while a checkbox under it is unticked or a
|
||||
subtask open, as Org's org-enforce-todo-dependencies refuses
|
||||
Then the tool refuses, naming each by its place or id, and nothing is written
|
||||
And plan_close with all: true ticks them and closes the subtasks with it; ticked in the same call, it closes
|
||||
And dropped closes whatever is under it as it is; the person's own check-off in the to-do list isn't refused
|
||||
|
||||
@done
|
||||
Scenario: PL7e. A post names what's still open
|
||||
Given an agent's feed_post in a project
|
||||
Then its answer carries the agent's open tasks and asks it to close what the post finished, with the item, so a
|
||||
turn the agent started itself (a job reporting back carries no plan) still closes them
|
||||
|
||||
@done
|
||||
Scenario: PL7f. Seen in the chat
|
||||
Then each ask is a small line of its own ("Finishing the plan (2): 3 open"), never the marker in the person's words
|
||||
And over the composer, while it asks or after it pauses with tasks open, one line: "Plan 3 of its tasks open",
|
||||
"Finishing · ask 2" with × to stop asking until the next message, or "Paused · Continue" with why on hover
|
||||
|
||||
@@ -261,6 +261,28 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
|
||||
fromCubemap are left out with a warning naming them, the scene drawn without them
|
||||
And test/errors.test.tsx holds it
|
||||
|
||||
@done
|
||||
Scenario: R3F15b. three's RoomEnvironment lights an R3F scene (#165)
|
||||
Given an <R3F> scene whose scene.environment is new PMREMGenerator(gl).fromScene(new RoomEnvironment(), sigma)
|
||||
.texture, three's own recipe for soft studio light with no HDR file
|
||||
When raea renders it
|
||||
Then it is lit by the same room, made by raea's engine: <Environment room blur={sigma}>, which src/input/pmrem.ts
|
||||
and lights.ts make of it (its intensity, its turn about +Y, and as the background when the room is that too)
|
||||
And the room is three's (systems/environment room.rs): RoomEnvironment's boxes, light boxes and point light,
|
||||
each direction from fromScene's cube camera traced to what it hits and lit by three's formulas, blurred by
|
||||
sigma as fromScene blurs it, then filtered like any panorama
|
||||
And fromScene of any other scene, and fromCubemap, are still left out with a warning naming them
|
||||
And raea's own <Environment room> is drawn by three as RoomEnvironment through fromScene (src/three/scene.ts),
|
||||
and the source export writes it so (src/export/emit.ts)
|
||||
Status (11-16): done. The front face of #131's box, 136,76,58 before (no environment), is 255,189,155; three
|
||||
draws 255,195,160. Two grey boxes lit by the room alone at half intensity: 137 and 125 against three's 140 and
|
||||
127 (23 and 19 before). three's pixels come from test/room/three.ts, which runs three 0.185's PMREM (the room
|
||||
in its 256 cube, the GGX filter chain, textureCubeUV) and MeshStandardMaterial's shading on the CPU, so the
|
||||
check needs no browser; test/room/check.sh renders test/room/room.tsx and holds each pixel within 8 levels.
|
||||
The room's light at 14 directions matches three's own RoomEnvironment object to 1e-3 (room.rs tests); Bevy's
|
||||
filter in place of three's PMREM puts the rest within 3 to 6 levels. Not done: fromScene's options.position
|
||||
(a cube camera away from the origin) is drawn from the origin, with a warning
|
||||
|
||||
Rule: What three.js work online is made of draws in raea (0.1.5)
|
||||
|
||||
Goal, 2026-11-15: "ship all of this in 0.1.5". An audit that day rendered 25 probes of what people post online made
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
@spec
|
||||
Feature: Sound for picture: the local models on any Mac, open libraries and packs one command away, music composed
|
||||
Asked for on 2026-11-16: rewrite the music and sound notes so that SAO and TokenSynth can be downloaded, every open
|
||||
instrument library and sound-effect pack raea knows is easy to reach, and music is never a default: "it tends to
|
||||
result in drones and pads and not actually design real complex music, scoring, sound effects, diegetic and
|
||||
non-diegetic."
|
||||
|
||||
Where it stands (2026-11-16): `raea setup-audio` installs both models through tools/sao/setup.sh and
|
||||
tools/tokensynth/setup.sh, and `raea sounds` reaches four libraries (sdk/raea/library/sounds/catalog.json:
|
||||
salamander, fluid, tonejs-instruments, vcsl). The guides teach deciding what each scene is heard as, spotting the
|
||||
cut and composing for it (sdk/guides/craft/motion/music.md, sound.md), and list every vetted source with its licence
|
||||
and how to fetch it (motion/sources.md). What those guides had to write down as a gap is below.
|
||||
|
||||
Rule: The local models install on any Mac, and say what they are
|
||||
|
||||
Scenario: SN1. setup-audio works on a clean Mac
|
||||
Given a Mac with no uv, no git and no Python of its own
|
||||
When `raea setup-audio` runs
|
||||
Then each setup gets uv and git through tools/ensure.sh, which every release ships, instead of the PATH
|
||||
And TokenSynth's code is cloned at a pinned commit and its weights fetched at a pinned revision, each file
|
||||
checked against its SHA-256, as SAO's already are
|
||||
And a missing tool, a full disk or a failed download is named in the error with the one command that fixes it
|
||||
And it is proven from a release build on a fresh macOS user account, with the sizes it reports
|
||||
|
||||
Scenario: SN2. raea meets SAO's licence, and says what is left for the person
|
||||
Given Stable Audio Open Small is under Stability AI's Community License (stability.ai/community-license-agreement),
|
||||
which isn't an open licence, and raea hands the model on to everyone who uses raea, so the licence's duties for
|
||||
whoever distributes it, or a product that uses it, are raea's
|
||||
When setup-audio installs it
|
||||
Then it writes a copy of the agreement and a NOTICE file beside the model (~/.cache/raea-sao), the notice
|
||||
holding the attribution the licence gives word for word ("This Stability AI Model is licensed under the
|
||||
Stability AI Community License, Copyright © Stability AI Ltd. All Rights Reserved"), and saying that the
|
||||
model raea installs is a changed one and how (a Core ML conversion from a Hugging Face mirror)
|
||||
And raea shows "Powered by Stability AI" where it documents SAO (the manual's setup-audio page, the app's about
|
||||
page)
|
||||
And raea's maker has registered its commercial use with Stability, and knows the licence ends for raea when
|
||||
raea and its affiliates make more than USD 1 million a year, from anything, unless Stability grants it an
|
||||
enterprise licence
|
||||
And `raea setup-audio --check` names each model's licence and where its copy is
|
||||
And what applies to the person is decided and written in motion/sources.md: whether the licence's clause for
|
||||
someone who gets the model "as part of an integrated end user product" takes them out of its commercial
|
||||
section, and what remains (the outputs are theirs as far as the law allows; no training another generative
|
||||
model on them; Stability's acceptable use policy)
|
||||
And until then the guides tell the agent to name the licence and link it before an SAO sound goes into a
|
||||
commercial piece, and to say nothing about what it requires of the person
|
||||
|
||||
Scenario: SN3. The app offers the local models before a piece needs them
|
||||
Given the raea app on a Mac without the models
|
||||
When a piece first needs SAO or TokenSynth
|
||||
Then the app says what will be downloaded (its size, licence and folder) and installs it on a yes, with progress
|
||||
And a render never blocks on a download of gigabytes it didn't say it would make
|
||||
|
||||
Rule: Open libraries and packs are one command away
|
||||
|
||||
Scenario: SN4. raea sounds reaches the vetted packs
|
||||
Given the packs motion/sources.md lists as fetched by hand
|
||||
When `raea sounds get` names one, an instrument of it or a sound in it (VSCO 2 CE's celli, Kenney's impacts,
|
||||
Groove MIDI's funk grooves)
|
||||
Then it downloads only that, once, into ~/.cache/raea-sounds, checked against a pinned SHA-256
|
||||
And it copies what the piece uses into media/ with its LICENCE.txt and the credit line it needs
|
||||
And it converts what raea can't read (Ogg, Opus) to WAV on the way in
|
||||
And a pack whose licence forbids passing it on (Sonniss's bundles, Pixabay's and Mixkit's sounds) is never
|
||||
mirrored: raea links to it and indexes the person's own download
|
||||
And nothing non-commercial, no-derivatives, Sampling+, share-alike or GPL is in the catalogue
|
||||
And until it does, motion/sources.md gives a one-line fetch for every pack with a stable address, into
|
||||
~/Music/raea-sounds/PACK/ with its licence beside it
|
||||
And Freesound is searched from raea only under a commercial licence for its API from Freesound's owners
|
||||
|
||||
Scenario: SN5. A sampled instrument keeps its dynamics and round robins
|
||||
Given a library with several velocity layers and round robins a note (VCSL, VSCO 2 CE, Salamander V3)
|
||||
When `raea sounds get` fetches it, or a composition loads its SFZ map
|
||||
Then every layer comes, and one Sampler plays the layer each note's velocity asks for and turns through the
|
||||
round robins
|
||||
And `humanize` on a Part, a Sequence or a Loop moves each note by a seeded few milliseconds, the same every render
|
||||
|
||||
Scenario: SN6. A MIDI file plays on sampled instruments
|
||||
Given a MIDI file: a Groove MIDI drum performance, or a public-domain score exported from MuseScore
|
||||
When a composition imports it (`import groove from "./media/grooves/funk-92.mid"`)
|
||||
Then it gets the file's tracks and notes in raea/music's MidiFile shape (parseMidi's), to play on Samplers and
|
||||
Players, the same shape motion/sources.md's converter writes as JSON today
|
||||
And a drum track maps onto a kit by note number, in General MIDI's map or a named kit's (Roland's, which
|
||||
Groove MIDI was recorded on, adds hi-hat edges at 22 and 26)
|
||||
And a note-on with no note-off ends where the file does, as the converter has it, instead of being dropped
|
||||
And a SoundFont bank (.sf2, .sf3) can play it in raea, without a render outside it
|
||||
|
||||
Rule: Music is composed for the cut, and a drone is caught
|
||||
|
||||
Scenario: SN7. raea check says when a cue is a drone
|
||||
Given a render whose music bus holds a cue longer than 15 s
|
||||
When `raea check` measures it from the render's note events
|
||||
Then it reports, by timecode, a cue that holds still, by these measures: the distinct pitches its lead plays in
|
||||
8 bars, the longest any one chord holds, its note onsets a beat over 4 bars across all its parts (the notes of
|
||||
a chord struck together count as one onset, and a bar with no onset counts as a held one), the spread of its
|
||||
velocities, how many timbres it uses, and whether it ends on a cut or fades out
|
||||
And its first fixtures are the cues in the guides' own examples (motion/music's cue and game loop, motion/sound's
|
||||
cue, the game bench's loop), which must all pass whatever their length, and a held pad and a sine sub under
|
||||
a long reverb, which must fail
|
||||
And its thresholds are set from those fixtures, approved scores and known drones before it ranks anything above
|
||||
P3 (a first guess, not measured: under 5 lead pitches in 8 bars, a chord held past 2 bars, under 1 onset a
|
||||
beat, a velocity spread under 8 of 127)
|
||||
@@ -184,7 +184,7 @@ fn open(names: &[String], fps: f64, serve: Option<u16>) -> R<Peer> {
|
||||
// no plugin named: the clock still steps by frames
|
||||
let dt = Duration::from_secs_f64(1.0 / fps.max(1.0));
|
||||
app.world_mut().resource_mut::<Time<Fixed>>().set_timestep(dt);
|
||||
app.insert_resource(PluginClock { stepped: 0, dt, advancing: false, steps: 0 });
|
||||
app.insert_resource(PluginClock { stepped: 0, dt, advancing: false, steps: 0, pure: false });
|
||||
}
|
||||
if let Some(port) = serve {
|
||||
#[cfg(feature = "remote")]
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
// `raea bug`: what an agent's report of a bug in raea carries to the host, which sends it to raea's server
|
||||
// (raea.io/v1/bugs/agent): a line and words, scrubbed of paths, emails and keys before it leaves, the harness as the
|
||||
// agent, --dry-run sending nothing. The host (native.ts bug: raea's version, the OS, curl) is faked: this is the
|
||||
// command's side; the server has its own test.
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { bugVerb, scrub } from "../src/bug.ts";
|
||||
|
||||
function run(args: string[], answer: Record<string, unknown> = { id: "bug_0123456789abcdef", count: 1, known: false }, env: Record<string, string> = {}) {
|
||||
const ops: { op: string; b: Record<string, unknown> }[] = [];
|
||||
const ask = (op: string, b: Record<string, unknown>) => {
|
||||
ops.push({ op, b });
|
||||
if (op === "harness") return { name: "claude-code" };
|
||||
return b.dry ? { sent: { ...(b.report as object), raea: "0.1.5" } } : answer;
|
||||
};
|
||||
return { out: bugVerb(ask, args, env), ops, sent: () => ops.find((o) => o.op === "bug")!.b };
|
||||
}
|
||||
|
||||
describe("raea bug", () => {
|
||||
test("a report needs a line and --text", () => {
|
||||
expect(() => run(["render hangs"])).toThrow(/--text/);
|
||||
expect(() => run(["--text", "it hangs"])).toThrow(/a line saying what's wrong/);
|
||||
});
|
||||
|
||||
test("it sends the line, the words, the command and the error, with the harness as the agent", () => {
|
||||
const r = run(["render", "hangs", "at", "frame", "12", "--text", "Rendered a teaser; it stopped.", "--command", "raea render t.tsx", "--error", "frame 12/240"]);
|
||||
expect(r.sent()).toEqual({ report: { title: "render hangs at frame 12", text: "Rendered a teaser; it stopped.", command: "raea render t.tsx", error: "frame 12/240", agent: "claude-code" }, dry: false });
|
||||
expect(r.out).toContain("Sent to raea as bug_0123456789abcdef");
|
||||
// RAEA_AGENT or --agent name it instead
|
||||
expect((run(["x y", "--text", "z"], undefined, { RAEA_AGENT: "codex" }).sent().report as { agent: string }).agent).toBe("codex");
|
||||
expect((run(["x y", "--text", "z", "--agent", "kimi"]).sent().report as { agent: string }).agent).toBe("kimi");
|
||||
});
|
||||
|
||||
test("paths, emails and keys are taken out before it leaves", () => {
|
||||
const r = run(["render of /Users/you/Client Work/cut.tsx hangs", "--text", "Mail [email protected]; key sk-live1234567890abcdefXYZ; file ~/Movies/a.mov", "--error", "panicked at /Users/you/raea/src/x.rs:12"]);
|
||||
const sent = JSON.stringify(r.sent());
|
||||
for (const s of ["/Users/", "[email protected]", "sk-live", "Client Work", "~/Movies"]) expect(sent).not.toContain(s);
|
||||
expect(sent).toContain("<path>");
|
||||
expect(sent).toContain("<email>");
|
||||
expect(sent).toContain("<secret>");
|
||||
// raea's own files keep where in raea they are
|
||||
expect(scrub("at /Applications/raea.app/Contents/MacOS/raea")).toContain("raea.app/Contents/MacOS/raea");
|
||||
});
|
||||
|
||||
test("--dry-run sends nothing and prints what would go", () => {
|
||||
const r = run(["render hangs", "--text", "words", "--dry-run"]);
|
||||
expect(r.sent().dry).toBe(true);
|
||||
expect(r.out).toContain("nothing sent");
|
||||
expect(r.out).toContain('"raea": "0.1.5"');
|
||||
});
|
||||
|
||||
test("the same bug again says it was counted; a refusal says where else to report", () => {
|
||||
expect(run(["a b", "--text", "c"], { id: "bug_0123456789abcdef", count: 3, known: true }).out).toContain("counted, 3 reports now");
|
||||
expect(() => run(["a b", "--text", "c"], { status: 429, message: "This machine has sent 5 reports today" })).toThrow(/429.*5 reports today.*github.com/);
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,11 @@
|
||||
// `raea clothes`: what the command sends the host for a garment made from words or garments put on a body (docs/
|
||||
// character.feature CH45), and what it refuses before anything is drawn or paid for. The host (src/wardrobe.ts, which
|
||||
// runs Blender and the image model) is faked: this is the command's side.
|
||||
// `raea clothes`: what the command sends the host for a garment sewn from words or settings, one made by procedure,
|
||||
// or garments put on a body (docs/character.feature CH45c), and what it refuses before anything is made. The host
|
||||
// (src/wardrobe.ts and sewn.ts, which run the sewing tools and Blender) is faked: this is the command's side.
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { clothesVerb } from "../src/clothes.ts";
|
||||
|
||||
/** clothesVerb with a host that keeps each op it was asked and answers as the host does */
|
||||
function run(args: string[], garments: { name: string; layer: number; vertices: number; over?: string }[] = []) {
|
||||
function run(args: string[], garments: { name: string; layer: number; vertices?: number; over?: string; sewn?: string }[] = []) {
|
||||
const ops: Record<string, unknown>[] = [];
|
||||
const ask = (op: string, b: Record<string, unknown>) => {
|
||||
expect(op).toBe("clothes");
|
||||
@@ -17,15 +17,18 @@ function run(args: string[], garments: { name: string; layer: number; vertices:
|
||||
|
||||
describe("raea clothes", () => {
|
||||
test("alone, it lists the project's garments, and says how to make one when there are none", () => {
|
||||
expect(run([]).out).toContain('raea clothes make NAME "what it is, as worn"');
|
||||
const { out } = run(["list"], [{ name: "tee-jeans", layer: 0, vertices: 11873 }, { name: "bomber", layer: 1, vertices: 6120, over: "tee-jeans" }]);
|
||||
expect(out).toBe("tee-jeans layer 0, 11873 of SOMA's vertices\nbomber layer 1, 6120 of SOMA's vertices, over tee-jeans\n");
|
||||
expect(run([]).out).toContain('raea clothes make NAME "what it is"');
|
||||
const { out } = run(["list"], [{ name: "shorts", layer: 0, vertices: 769 }, { name: "bomber", layer: 1, vertices: 6120, over: "shorts" }, { name: "trousers", layer: 0, sewn: "trousers, a waistband" }]);
|
||||
expect(out).toBe("shorts layer 0, 769 of SOMA's vertices\nbomber layer 1, 6120 of SOMA's vertices, over shorts\ntrousers sewn: trousers, a waistband\n");
|
||||
});
|
||||
|
||||
test("make sends the name, the words, the layer under it and the most a picture may cost", () => {
|
||||
const { ops } = run(["make", "bomber", "an olive bomber jacket, zipped", "--over", "tee-jeans", "--max-cents", "8"]);
|
||||
expect(ops).toEqual([{ op: "make", name: "bomber", words: "an olive bomber jacket, zipped", over: "tee-jeans", cents: 8 }]);
|
||||
expect(run(["make", "tee", "a white tee"]).ops[0]).toMatchObject({ over: undefined, cents: 10 });
|
||||
test("make sends the name, the words or the plain base, the settings changed and the colour", () => {
|
||||
const { ops } = run(["make", "hoodie", "a hooded sweatshirt", "--set", "sleeve.length=0.9, shirt.length=1.6", "--colour", "3f5a3c"]);
|
||||
expect(ops).toEqual([{ op: "make", name: "hoodie", words: "a hooded sweatshirt", set: ["sleeve.length=0.9", "shirt.length=1.6"], plain: false, colour: "#3f5a3c" }]);
|
||||
expect(run(["make", "tee", "--plain"]).ops[0]).toEqual({ op: "make", name: "tee", words: undefined, set: [], plain: true, colour: undefined });
|
||||
expect(run(["make", "trousers", "--set", "meta.upper=none,meta.bottom=Pants"]).ops[0]).toMatchObject({ words: undefined, plain: true, set: ["meta.upper=none", "meta.bottom=Pants"] });
|
||||
expect(run(["make", "tee", "--plain", "a white tee"]).ops[0]).toMatchObject({ words: undefined, plain: true });
|
||||
expect(run(["settings"]).ops).toEqual([{ op: "settings" }]);
|
||||
});
|
||||
|
||||
test("cover sends the parts, the colour and the stand-off in metres, for a garment with no picture", () => {
|
||||
@@ -37,16 +40,17 @@ describe("raea clothes", () => {
|
||||
test("wear sends the folder, the garments innermost first and the body", () => {
|
||||
const { ops } = run(["wear", "assets/characters/dressed", "tee-jeans", "bomber", "--body", "assets/characters/soma-headless"]);
|
||||
expect(ops).toEqual([{ op: "wear", out: "assets/characters/dressed", garments: ["tee-jeans", "bomber"], body: "assets/characters/soma-headless" }]);
|
||||
expect(run(["wear", "out", "tee", "--body", "headless", "--head", "assets/characters/heads/real"]).ops[0]).toMatchObject({ body: "headless", head: "assets/characters/heads/real" });
|
||||
});
|
||||
|
||||
test("what doesn't fit is said before anything is drawn", () => {
|
||||
const refused = (args: string[], says: string) => expect(() => run(args)).toThrow(says);
|
||||
refused(["make", "tee"], 'raea clothes make NAME "WHAT IT IS, AS WORN"');
|
||||
refused(["make", "tee", "a white tee", "and more"], 'raea clothes make NAME "WHAT IT IS, AS WORN"');
|
||||
refused(["make", "tee"], "say what tee is, or make it from the plain base");
|
||||
refused(["make", "tee", "a white tee", "and more"], 'raea clothes make NAME ["WHAT IT IS"]');
|
||||
refused(["make", "../tee", "a white tee"], "a garment's name is letters, digits, - and _");
|
||||
refused(["make", "tee", "a white tee", "--over", "a b"], "--over a b: name garments already made");
|
||||
expect(run(["make", "jacket", "a denim jacket", "--over", "tee,shorts"]).ops[0]).toMatchObject({ over: "tee,shorts" });
|
||||
refused(["make", "tee", "a white tee", "--max-cents", "0"], "--max-cents takes the most one picture may cost");
|
||||
refused(["make", "tee", "a white tee", "--set", "sleeve length 3"], "--set sleeve length 3: a setting is PATH=VALUE");
|
||||
refused(["make", "tee", "a white tee", "--colour", "white"], "--colour white: a colour is #RRGGBB");
|
||||
refused(["settings", "tee"], "raea clothes settings takes nothing after it");
|
||||
refused(["cover", "tee", "--parts", "chest"], "raea clothes cover NAME --parts");
|
||||
refused(["cover", "tee", "--parts", "belly", "--colour", "#ffffff"], "--parts: no part belly");
|
||||
refused(["cover", "tee", "--parts", "shin:1.5", "--colour", "#ffffff"], "a share is how far along the limb");
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// A headless body's skin graded to its head at the collar (engine/cli/src/grade.ts, docs/character.feature CH20b): a
|
||||
// vertex at the collar takes the ring's colour above it, one a fade's length down keeps the neck colour.
|
||||
import { expect, test } from "bun:test";
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { gradeToHead } from "../src/grade";
|
||||
|
||||
test("a body's skin takes the head's colours at the collar and its neck colour below", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "grade-"));
|
||||
// three vertices: at the collar in front, at the collar behind, and 10 cm under the collar in front
|
||||
const pos = Buffer.alloc(36);
|
||||
[[0, 1.5, 0.05], [0, 1.5, -0.05], [0, 1.4, 0.05]].flat().forEach((v, i) => pos.writeFloatLE(v, i * 4));
|
||||
const gltf = { asset: { version: "2.0" }, buffers: [{ byteLength: 36 }], bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: 36 }],
|
||||
accessors: [{ bufferView: 0, componentType: 5126, count: 3, type: "VEC3" }], materials: [{ name: "skin", pbrMetallicRoughness: { baseColorFactor: [1, 1, 1, 1] } }],
|
||||
meshes: [{ primitives: [{ attributes: { POSITION: 0 }, material: 0 }] }] };
|
||||
let json = Buffer.from(JSON.stringify(gltf));
|
||||
json = Buffer.concat([json, Buffer.alloc((4 - (json.length % 4)) % 4, 0x20)]);
|
||||
const h = Buffer.alloc(20), bh = Buffer.alloc(8);
|
||||
h.write("glTF", 0, "latin1"); h.writeUInt32LE(2, 4); h.writeUInt32LE(28 + json.length + 36, 8); h.writeUInt32LE(json.length, 12); h.write("JSON", 16, "latin1");
|
||||
bh.writeUInt32LE(36, 0); bh.write("BIN\0", 4, "latin1");
|
||||
writeFileSync(join(dir, "body.glb"), Buffer.concat([h, json, bh, pos]));
|
||||
// a ring of eight: the front half one colour, the back half another; the neck colour between
|
||||
const ring = Array.from({ length: 8 }, (_, k) => [0.05 * Math.sin((k / 8) * 2 * Math.PI), 1.5, 0.05 * Math.cos((k / 8) * 2 * Math.PI)]);
|
||||
const front = (k: number) => Math.cos((k / 8) * 2 * Math.PI) > 0.5, back = (k: number) => Math.cos((k / 8) * 2 * Math.PI) < -0.5;
|
||||
writeFileSync(join(dir, "head.json"), JSON.stringify({ neck_colour_srgb: [0.5, 0.5, 0.5], collar_ring: { positions: ring },
|
||||
collar: { ring_colours_srgb: ring.map((_, k) => (front(k) ? [0.6, 0.5, 0.5] : back(k) ? [0.4, 0.5, 0.5] : [0.5, 0.5, 0.5])) } }));
|
||||
expect(gradeToHead(join(dir, "body.glb"), join(dir, "head.json"))).toContain("3 vertices");
|
||||
const b = readFileSync(join(dir, "body.glb")), n = b.readUInt32LE(12), g = JSON.parse(b.subarray(20, 20 + n).toString("utf8"));
|
||||
const bin = b.subarray(28 + n), a = g.accessors[g.meshes[0].primitives[0].attributes.COLOR_0], at = g.bufferViews[a.bufferView].byteOffset;
|
||||
const red = (i: number) => bin.readFloatLE(at + i * 16);
|
||||
expect(a.type).toBe("VEC4");
|
||||
expect(red(0)).toBeGreaterThan(1.1); // the front of the collar: redder than the neck colour
|
||||
expect(red(1)).toBeLessThan(0.9); // the back: less red
|
||||
expect(red(2)).toBeCloseTo(1, 5); // a fade's length down: the neck colour itself
|
||||
expect(g.materials[0].pbrMetallicRoughness.baseColorFactor[0]).toBeCloseTo(0.5 ** 2.2, 5);
|
||||
expect(() => gradeToHead(join(dir, "body.glb"), join(dir, "body.glb"))).toThrow();
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
// `raea bug`: an agent tells raea about a bug it thinks it found in raea itself (Shane 11-16: "a way for the agent to
|
||||
// safely submit bug reports to our server ... any time an agent using raea even headlessly outside the app can report
|
||||
// a bug it thinks it found in raea"). It goes to raea's own server (raea.io/v1/bugs/agent), words only, with no
|
||||
// account needed: raea's version and the Mac's OS are added, and paths, emails and anything shaped like a key are
|
||||
// taken out here, before it leaves (the server takes them out again). The same bug sent again is counted on the first
|
||||
// report. --dry-run prints what would go and sends nothing. The host (op "bug", native.ts) adds the version and sends.
|
||||
|
||||
type Ask = (op: string, args: Record<string, unknown>) => any;
|
||||
|
||||
export const BUG_USAGE = `raea bug TITLE... --text TEXT [--command CMD] [--error TEXT] [--agent NAME] [--dry-run]
|
||||
TITLE: what's wrong, in a line. TEXT: what you did, what you expected, what happened. CMD: the raea command that
|
||||
went wrong. --error: what it printed. A bug in raea itself (a command that fails or hangs, a wrong result, help that says one thing while raea does
|
||||
another), not in your own composition. Words only; paths, emails and keys are taken out before it's sent. Five a day
|
||||
from one machine; the same bug again is counted on the first report.
|
||||
`;
|
||||
|
||||
/** What an agent wrote, safe to send: a path (/Users/..., ~/...) as <path>, an email as <email>, a key or token as
|
||||
* <secret>. The server (apps/site/api src/bugs.ts scrubAgent) does the same again. */
|
||||
export function scrub(text: string): string {
|
||||
return text
|
||||
.replace(/\b(?:Bearer|token|key|secret|password)\s*[:=]?\s*["']?[A-Za-z0-9._~+/=-]{12,}["']?/gi, "<secret>")
|
||||
.replace(/\b(?:sk|pk|rk|ghp|gho|ghs|github_pat|xox[abpr]|AKIA|AIza)[-_A-Za-z0-9]{10,}/g, "<secret>")
|
||||
.replace(/\b[A-Za-z0-9+/_-]{32,}={0,2}/g, (m) => (/[0-9]/.test(m) && /[A-Za-z]/.test(m) ? "<secret>" : m))
|
||||
.replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g, "<email>")
|
||||
.replace(/(?:file:\/\/)?(?:~|\/(?:Users|home|private|var|tmp|Volumes|opt))\/[^\s'"`()<>,;]*(?: [^\s'"`()<>,;/]+\/[^\s'"`()<>,;]*)*/g, (p) => {
|
||||
const i = p.indexOf("raea.app/Contents/");
|
||||
return i >= 0 ? p.slice(i) : "<path>";
|
||||
});
|
||||
}
|
||||
|
||||
const flagOf = (args: string[], name: string) => {
|
||||
const i = args.indexOf(name);
|
||||
return i >= 0 ? args[i + 1] : undefined;
|
||||
};
|
||||
const BARE = new Set(["--dry-run"]);
|
||||
const plain = (args: string[]) => args.filter((a, i) => !a.startsWith("--") && (!args[i - 1]?.startsWith("--") || BARE.has(args[i - 1])));
|
||||
|
||||
export function bugVerb(ask: Ask, args: string[], env: Record<string, string | undefined> = {}): string {
|
||||
const title = plain(args).join(" ").trim();
|
||||
const text = flagOf(args, "--text")?.trim();
|
||||
if (!title || !text) throw new Error(`a report needs a line saying what's wrong and --text saying what you did, what you expected and what happened.\n${BUG_USAGE}`);
|
||||
const harness = (() => {
|
||||
try {
|
||||
return (ask("harness", {}) as { name?: string } | undefined)?.name;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
const opt = (s: string | undefined, n: number) => (s?.trim() ? scrub(s.trim()).slice(0, n) : undefined);
|
||||
const report = {
|
||||
title: scrub(title).slice(0, 160),
|
||||
text: scrub(text).slice(0, 4000),
|
||||
command: opt(flagOf(args, "--command"), 300),
|
||||
error: opt(flagOf(args, "--error"), 4000),
|
||||
agent: flagOf(args, "--agent") ?? env.RAEA_AGENT ?? harness,
|
||||
};
|
||||
const dry = args.includes("--dry-run");
|
||||
const r = ask("bug", { report, dry }) as { sent?: Record<string, unknown>; id?: string; count?: number; known?: boolean; status?: number; message?: string };
|
||||
if (dry) return `Would send to raea (nothing sent):\n${JSON.stringify(r.sent ?? report, null, 2)}\n`;
|
||||
if (!r.id) throw new Error(`raea's server didn't take it${r.status ? ` (${r.status})` : ""}: ${r.message ?? "no answer"}. github.com/shinyobjectz/raea/issues takes it too.`);
|
||||
return r.known
|
||||
? `Sent: raea already had this one (${r.id}); it's counted, ${r.count} reports now. Thank you.\n`
|
||||
: `Sent to raea as ${r.id}. Thank you. What was sent:\n${JSON.stringify(r.sent ?? report, null, 2)}\n`;
|
||||
}
|
||||
@@ -134,8 +134,12 @@ pub fn run(args: &[String]) -> R<String> {
|
||||
// `raea library` (engine/cli/src/library.ts) and `raea show` (show.ts: in the raea app, not Preview, Shane 11-09), under render's usage
|
||||
let usage = format!("{usage}\n raea library [new NAME [--cloud] | add LIBRARY PATH | files LIBRARY | tag SHA TAGS | status | scan ...] | raea library search \"WORDS\" [--library LIBRARY] [--kind KIND] [--limit N] [--sound] (the person's libraries in the raea app: folders and drives indexed on this machine, searched by meaning; a folder an agent adds waits for the person's yes)");
|
||||
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), or questions, all of them one item, each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
|
||||
// clothes for SOMA's body from words (docs/character.feature CH45): engine/cli/src/clothes.ts and wardrobe.ts
|
||||
let usage = format!("{usage}\n raea clothes [make NAME \"WHAT IT IS, AS WORN\" [--over UNDER[,UNDER...]] [--max-cents N] | remeasure NAME | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] | wear OUT_DIR GARMENT... [--body DIR]] (clothes for SOMA's body from words: make has an image model (flux_2_pro, one picture a view, at most N cents each, 10 unless said) dress SOMA's grey mannequin from the front, back, left and right, then measures the pictures onto SOMA's own vertices as assets/clothes/NAME.json, its pictures in assets/clothes/NAME/; --over draws it over garments already made (innermost first), as the next layer, a garment made by procedure drawn on the mannequin first; remeasure measures a garment again from its kept pictures (after raea's measuring changed), nothing drawn or paid for; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said); wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder and needs Blender: raea setup blender)");
|
||||
// clothes for SOMA's body, sewn or laid on the skin (docs/character.feature CH45c): engine/cli/src/clothes.ts, wardrobe.ts and sewn.ts
|
||||
let usage = format!("{usage}\n raea clothes [make NAME [\"WHAT IT IS\"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] | settings | cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] [--hard [--sole MM] [--sole-colour #RRGGBB] [--panels #RRGGBB,...]] | wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]] (clothes for SOMA's body from words: make sews a garment: a sewing pattern (GarmentCode, MIT) from the words, or the plain base with --plain, its settings changed by --set PATH=VALUE (settings lists them and what each may be), cut to SOMA's measurements, draped by raea's own cloth and baked, as assets/clothes/NAME.json and its .glb, in --colour or the palette's next; the first make sets up GarmentCode and its Python in raea's models folder; cover makes one by procedure in the same file, no picture: the skin of the parts named (hips, waist, torso, chest, neck, head, upperArm, foreArm, hand, thigh, shin, foot, toes; a limb's SHARE is how far along it from its top), in one colour, MM off the skin (6 unless said), --over a garment already made as the one under it; wear puts garments on a body, innermost first (each GARMENT a name or its .json): OUT_DIR/NAME.glb each, with OUT_DIR/body.glb the body without the skin wholly under cloth; --body DIR another SOMA body folder (a headless one for a head part); --head HEAD_DIR the head that joins it (head.json), whose skin the body's is graded to at the collar; alone, the project's garments. The first use fetches SOMA's body (NVlabs/SOMA-X, Apache-2.0) into raea's models folder and needs Blender: raea setup blender)");
|
||||
// body motion made on this Mac by Kimodo on MLX (docs/character.feature CH15c): apps/tools/src/motion.rs
|
||||
let usage = format!("{usage}\n {} ({})", tools::motion::USAGE, tools::motion::ABOUT);
|
||||
// an agent's report of a bug in raea itself, to raea's server (engine/cli/src/bug.ts; Shane 11-16)
|
||||
let usage = format!("{usage}\n raea bug TITLE... --text TEXT [--command CMD] [--error TEXT] [--agent NAME] [--dry-run] (a bug in raea itself, not in your own composition, sent to raea's server with raea's version and the OS, no account needed: words only, paths, emails and keys taken out before it goes; five a day from a machine, the same bug again counted on the first report; --dry-run prints what would go and sends nothing)");
|
||||
// a workspace's files and specs (docs/projects.feature), listed under render's usage like library
|
||||
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
|
||||
let (export_game, capcut, scene, physics, splat) = (raea_app_game::USAGE, raea_app_capcut::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);
|
||||
@@ -253,6 +257,8 @@ pub fn run(args: &[String]) -> R<String> {
|
||||
Some("song") => return tools::song::song(args),
|
||||
// `track CLIP.mp4 [--subject X,Y,W,H] [--from S]`: the clip's camera solved for <Matchmove> (motion/track.rs)
|
||||
Some("track") => return motion::track::track(args),
|
||||
// `motion "LINE" [--keys KEYS.json]`: body motion made on this Mac by Kimodo on MLX (apps/tools motion.rs, raea-sys-kimodo)
|
||||
Some("motion") => return tools::motion::motion(args),
|
||||
// `gen …`: generation flows on made.app, fal, Replicate, OpenRouter, Modal and ComfyUI, and ComfyUI workflows read
|
||||
// and written (raea-io-gen, through apps/tools generate.rs for the local models)
|
||||
Some("gen") => return raea_app_tools::generate::generate(args),
|
||||
|
||||
+36
-28
@@ -1,26 +1,29 @@
|
||||
// `raea clothes`: clothes for SOMA's body from words (raea docs/character.feature CH40 to CH45). make has an image
|
||||
// model dress the mannequin's four views, one view a call, and measures the pictures onto SOMA's template vertices
|
||||
// (a garment rides any SOMA body); wear puts garments on a body, innermost first. The work is the host's (op
|
||||
// "clothes": engine/cli/src/wardrobe.ts on the native raea); this file reads the words and says what was done.
|
||||
// `raea clothes`: clothes for SOMA's body (raea docs/character.feature CH45c). make sews a garment: a pattern from
|
||||
// words (the garment model's first guess) or from the plain base, any setting changed by path, cut to SOMA, draped
|
||||
// and baked; cover makes one by procedure on the skin; wear puts garments on a body. The work is the host's (op
|
||||
// "clothes": engine/cli/src/wardrobe.ts and sewn.ts on the native raea); this file reads the words and says what
|
||||
// was done.
|
||||
|
||||
type Ask = (op: string, args: Record<string, unknown>) => any;
|
||||
|
||||
/** the body's parts a garment made by procedure covers (tools/clothes/garment.py's PARTS) */
|
||||
export const PARTS = ["chest", "foot", "foreArm", "hand", "head", "hips", "neck", "shin", "thigh", "toes", "torso", "upperArm", "waist"];
|
||||
|
||||
export const CLOTHES_USAGE = `raea clothes (the project's garments: assets/clothes/NAME.json, their pictures in assets/clothes/NAME/)
|
||||
raea clothes make NAME "WHAT IT IS, AS WORN" [--over UNDER[,UNDER...]] [--max-cents N] (drawn over the garments named; N: the most one picture may cost, 10 unless said)
|
||||
raea clothes remeasure NAME (measured again from its kept pictures, after raea's measuring changed: nothing drawn or paid for)
|
||||
raea clothes cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] (by procedure, no picture: ${PARTS.join(", ")}; a limb's share is how far along it from its top, foreArm:0.5)
|
||||
raea clothes wear OUT_DIR GARMENT... [--body DIR] (GARMENT: a garment's name or its .json, innermost first; DIR: a SOMA body folder, SOMA's own unless said)
|
||||
export const CLOTHES_USAGE = `raea clothes (the project's garments: assets/clothes/NAME.json, their files in assets/clothes/NAME/)
|
||||
raea clothes make NAME ["WHAT IT IS"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB] (a sewn garment: its pattern from the words, or from the plain base with --plain or no words; each PATH=VALUE changes one setting)
|
||||
raea clothes settings (a sewn garment's settings: each path, its value in the plain base, what it may be)
|
||||
raea clothes cover NAME --parts PART[:SHARE],... --colour #RRGGBB [--stand MM] [--over UNDER] [--hard [--sole MM] [--sole-colour #RRGGBB] [--panels #RRGGBB,...]] (by procedure on the skin; --hard: footwear, on a last round the foot with a sole under it: ${PARTS.join(", ")}; a limb's share is how far along it from the end that joins the rest: upperArm,foreArm:0.5 from the elbow, foot,shin:0.4 from the ankle)
|
||||
raea clothes wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR] (GARMENT: a garment's name or its .json, innermost first; DIR: a SOMA body folder, SOMA's own unless said; HEAD_DIR: the head that joins a headless body, whose skin is graded to it at the collar)
|
||||
`;
|
||||
|
||||
const flagOf = (args: string[], name: string) => {
|
||||
const i = args.indexOf(name);
|
||||
return i >= 0 ? args[i + 1] : undefined;
|
||||
};
|
||||
/** the flags that take no value */
|
||||
const BARE = new Set(["--plain", "--hard"]);
|
||||
/** the words that aren't flags or a flag's value */
|
||||
const plain = (args: string[]) => args.filter((a, i) => !a.startsWith("--") && !args[i - 1]?.startsWith("--"));
|
||||
const plain = (args: string[]) => args.filter((a, i) => !a.startsWith("--") && (!args[i - 1]?.startsWith("--") || BARE.has(args[i - 1])));
|
||||
const NAME = /^[a-z0-9][a-z0-9_-]*$/i;
|
||||
|
||||
export function clothesVerb(ask: Ask, args: string[]): string {
|
||||
@@ -29,25 +32,23 @@ export function clothesVerb(ask: Ask, args: string[]): string {
|
||||
switch (sub) {
|
||||
case undefined:
|
||||
case "list": {
|
||||
const gs: { name: string; layer: number; vertices: number; over?: string }[] = q("list").garments;
|
||||
if (!gs.length) return 'No garments yet. raea clothes make NAME "what it is, as worn" makes one.\n';
|
||||
return gs.map((g) => `${g.name} layer ${g.layer}, ${g.vertices} of SOMA's vertices${g.over ? `, over ${g.over}` : ""}`).join("\n") + "\n";
|
||||
const gs: { name: string; layer: number; vertices?: number; over?: string; sewn?: string }[] = q("list").garments;
|
||||
if (!gs.length) return 'No garments yet. raea clothes make NAME "what it is" sews one.\n';
|
||||
return gs.map((g) => (g.sewn !== undefined ? `${g.name} sewn: ${g.sewn}` : `${g.name} layer ${g.layer}, ${g.vertices} of SOMA's vertices${g.over ? `, over ${g.over}` : ""}`)).join("\n") + "\n";
|
||||
}
|
||||
case "make": {
|
||||
const [name, words, ...more] = plain(rest);
|
||||
if (!name || !words || more.length) throw new Error(`raea clothes make NAME "WHAT IT IS, AS WORN" [--over UNDER] [--max-cents N]\n${CLOTHES_USAGE}`);
|
||||
const plainBase = rest.includes("--plain"), [name, words, ...more] = plain(rest.filter((x) => x !== "--plain"));
|
||||
if (!name || more.length) throw new Error(`raea clothes make NAME ["WHAT IT IS"] [--plain] [--set PATH=VALUE,...] [--colour #RRGGBB]\n${CLOTHES_USAGE}`);
|
||||
if (!NAME.test(name)) throw new Error(`${name}: a garment's name is letters, digits, - and _ (it names its file)`);
|
||||
const over = flagOf(rest, "--over"), cents = Number(flagOf(rest, "--max-cents") ?? 10);
|
||||
if (over !== undefined && !over.split(",").every((o) => NAME.test(o))) throw new Error(`--over ${over}: name garments already made, innermost first, with commas between (raea clothes lists them)`);
|
||||
if (!(cents > 0)) throw new Error("--max-cents takes the most one picture may cost, in cents");
|
||||
return q("make", { name, words, over, cents }).said;
|
||||
}
|
||||
case "remeasure": {
|
||||
const [name, ...more] = plain(rest);
|
||||
if (!name || more.length) throw new Error(`raea clothes remeasure NAME (measured again from its kept pictures; nothing is drawn or paid for)\n${CLOTHES_USAGE}`);
|
||||
if (!NAME.test(name)) throw new Error(`${name}: a garment's name is letters, digits, - and _ (it names its file)`);
|
||||
return q("remeasure", { name }).said;
|
||||
const set = flagOf(rest, "--set")?.split(",").map((x) => x.trim()).filter(Boolean) ?? [], colour = flagOf(rest, "--colour");
|
||||
for (const x of set) if (!/^[a-z][a-z0-9_.-]*=[^=]+$/i.test(x)) throw new Error(`--set ${x}: a setting is PATH=VALUE, sleeve.length=0.3 (raea clothes settings lists them)`);
|
||||
if (colour !== undefined && !/^#?[0-9a-f]{6}$/i.test(colour)) throw new Error(`--colour ${colour}: a colour is #RRGGBB`);
|
||||
if (!words && !plainBase && !set.length) throw new Error(`say what ${name} is, or make it from the plain base: --plain, --set PATH=VALUE,...\n${CLOTHES_USAGE}`);
|
||||
return q("make", { name, words: plainBase ? undefined : words, set, plain: plainBase || !words, colour: colour === undefined ? undefined : colour.startsWith("#") ? colour : `#${colour}` }).said;
|
||||
}
|
||||
case "settings":
|
||||
if (rest.length) throw new Error(`raea clothes settings takes nothing after it\n${CLOTHES_USAGE}`);
|
||||
return q("settings").said;
|
||||
case "cover": {
|
||||
const [name, ...more] = plain(rest);
|
||||
const parts = flagOf(rest, "--parts"), colour = flagOf(rest, "--colour"), over = flagOf(rest, "--over"), mm = Number(flagOf(rest, "--stand") ?? 6);
|
||||
@@ -61,12 +62,19 @@ export function clothesVerb(ask: Ask, args: string[]): string {
|
||||
if (!/^#?[0-9a-f]{6}$/i.test(colour)) throw new Error(`--colour ${colour}: a colour is #RRGGBB`);
|
||||
if (!(mm > 0 && mm <= 80)) throw new Error("--stand takes how far the cloth stands off the skin, in millimetres (above 0, at most 80)");
|
||||
if (over !== undefined && !NAME.test(over)) throw new Error(`--over ${over}: name a garment already made (raea clothes lists them)`);
|
||||
return q("cover", { name, parts: parts.replace(/\s+/g, ""), colour: colour.startsWith("#") ? colour : `#${colour}`, stand: mm / 1000, over }).said;
|
||||
// a hard piece (footwear): its own shape on a last round the foot, a sole under it, panels in their colours
|
||||
const hard = rest.includes("--hard"), sole = flagOf(rest, "--sole"), soleColour = flagOf(rest, "--sole-colour"), panels = flagOf(rest, "--panels");
|
||||
if (!hard && (sole ?? soleColour ?? panels) !== undefined) throw new Error("--sole, --sole-colour and --panels are a hard piece's: add --hard");
|
||||
if (sole !== undefined && !(Number(sole) >= 0 && Number(sole) <= 60)) throw new Error("--sole takes the sole's thickness in millimetres (0 to 60)");
|
||||
for (const c of [soleColour, ...(panels?.split(",") ?? [])]) if (c !== undefined && !/^#?[0-9a-f]{6}$/i.test(c.trim())) throw new Error(`${c}: a colour is #RRGGBB`);
|
||||
const hex = (c: string) => (c.trim().startsWith("#") ? c.trim() : `#${c.trim()}`);
|
||||
return q("cover", { name, parts: parts.replace(/\s+/g, ""), colour: colour.startsWith("#") ? colour : `#${colour}`, stand: mm / 1000, over,
|
||||
...(hard ? { hard: { sole: sole === undefined ? undefined : Number(sole), soleColour: soleColour && hex(soleColour), panels: panels?.split(",").map(hex) } } : {}) }).said;
|
||||
}
|
||||
case "wear": {
|
||||
const [out, ...garments] = plain(rest);
|
||||
if (!out || !garments.length) throw new Error(`raea clothes wear OUT_DIR GARMENT... [--body DIR]\n${CLOTHES_USAGE}`);
|
||||
return q("wear", { out, garments, body: flagOf(rest, "--body") }).said;
|
||||
if (!out || !garments.length) throw new Error(`raea clothes wear OUT_DIR GARMENT... [--body DIR] [--head HEAD_DIR]\n${CLOTHES_USAGE}`);
|
||||
return q("wear", { out, garments, body: flagOf(rest, "--body"), head: flagOf(rest, "--head") }).said;
|
||||
}
|
||||
default:
|
||||
throw new Error(CLOTHES_USAGE);
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
// A headless body's skin graded to the head that joins it (docs/character.feature CH20): the body's skin takes the
|
||||
// head's neck colour, and just under the collar each vertex takes the colour the head's own skin has above it there
|
||||
// (head.json's collar.ring_colours_srgb, one for each vertex of the ring, evened round the ring), easing into the
|
||||
// neck colour over `fade` metres down. The colours are written into body.glb as vertex colours (COLOR_0, which
|
||||
// multiplies the material's colour), so the body needs no picture and the join needs no weld. Measured on the first
|
||||
// head (compositions/seam_check.tsx in the sheet3d project): the step across the collar at the front went from 8
|
||||
// levels of 255 to under 1.
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
|
||||
type Vec3 = [number, number, number];
|
||||
interface HeadJson { neck_colour_srgb?: number[]; collar_ring?: { positions?: Vec3[] }; collar?: { ring_colours_srgb?: number[][] } }
|
||||
interface Gltf {
|
||||
accessors: { bufferView: number; byteOffset?: number; componentType: number; count: number; type: string }[];
|
||||
bufferViews: { buffer: number; byteOffset?: number; byteLength: number; byteStride?: number; target?: number }[];
|
||||
buffers: { byteLength: number }[];
|
||||
materials?: { name?: string; pbrMetallicRoughness?: { baseColorFactor?: number[] } }[];
|
||||
meshes: { primitives: { attributes: Record<string, number>; material?: number }[] }[];
|
||||
}
|
||||
|
||||
const linear = (c: number[]): Vec3 => [c[0] ** 2.2, c[1] ** 2.2, c[2] ** 2.2];
|
||||
const near = (a: number, b: number) => Math.abs(((a - b + 3 * Math.PI) % (2 * Math.PI)) - Math.PI);
|
||||
|
||||
/** body.glb at `glb` graded to the head whose head.json is at `head`, in place; what was done, in a line */
|
||||
export function gradeToHead(glb: string, head: string, fade = 0.08): string {
|
||||
const h = JSON.parse(readFileSync(head, "utf8")) as HeadJson;
|
||||
const ring = h.collar_ring?.positions, cols = h.collar?.ring_colours_srgb, tone = h.neck_colour_srgb;
|
||||
if (!ring?.length || !cols || cols.length !== ring.length || !tone) throw new Error(`${head}: no collar ring with its colours and no neck colour: the head was not joined to a body's collar`);
|
||||
// (bytes read through a DataView: the native raea's readFileSync gives a plain Uint8Array, not Node's Buffer)
|
||||
const b = new Uint8Array(readFileSync(glb)), dv = new DataView(b.buffer, b.byteOffset, b.byteLength), n = dv.getUint32(12, true);
|
||||
const g = JSON.parse(new TextDecoder().decode(b.subarray(20, 20 + n))) as Gltf;
|
||||
const at0 = 20 + n + 8, len0 = dv.getUint32(20 + n, true), f32 = (o: number) => dv.getFloat32(at0 + o, true);
|
||||
const mid = ring.reduce((s, p) => [s[0] + p[0] / ring.length, s[1] + p[1] / ring.length, s[2] + p[2] / ring.length], [0, 0, 0]);
|
||||
// the ring's colours by their angle round the neck, each the mean of itself and two neighbours on each side (one
|
||||
// texel's colour a vertex, carried down the neck, drew streaks)
|
||||
const lin = cols.map(linear), k = ring.length;
|
||||
const even = lin.map((_, i) => [0, 1, 2].map((c) => [-2, -1, 0, 1, 2].reduce((s, d) => s + lin[(i + d + k) % k][c], 0) / 5) as Vec3);
|
||||
const angle = ring.map((p) => Math.atan2(p[0] - mid[0], p[2] - mid[2]));
|
||||
const t = linear(tone);
|
||||
const added: Uint8Array[] = [];
|
||||
let at = len0 + ((4 - (len0 % 4)) % 4), graded = 0;
|
||||
for (const mesh of g.meshes) for (const p of mesh.primitives) {
|
||||
if (g.materials?.[p.material ?? -1]?.name !== "skin" || p.attributes.POSITION === undefined) continue;
|
||||
const a = g.accessors[p.attributes.POSITION], v = g.bufferViews[a.bufferView], from = (v.byteOffset ?? 0) + (a.byteOffset ?? 0), step = v.byteStride ?? 12;
|
||||
const out = new Float32Array(a.count * 4);
|
||||
for (let i = 0; i < a.count; i++) {
|
||||
const x = f32(from + i * step), y = f32(from + i * step + 4), z = f32(from + i * step + 8);
|
||||
const u = Math.min(1, Math.max(0, mid[1] - y) / fade), w = u * u * (3 - 2 * u), ang = Math.atan2(x - mid[0], z - mid[2]);
|
||||
let best = 0;
|
||||
for (let r = 1; r < k; r++) if (near(angle[r], ang) < near(angle[best], ang)) best = r;
|
||||
for (let c = 0; c < 3; c++) out[i * 4 + c] = (even[best][c] * (1 - w) + t[c] * w) / t[c];
|
||||
out[i * 4 + 3] = 1;
|
||||
}
|
||||
g.bufferViews.push({ buffer: 0, byteOffset: at, byteLength: out.byteLength, target: 34962 });
|
||||
g.accessors.push({ bufferView: g.bufferViews.length - 1, componentType: 5126, count: a.count, type: "VEC4" });
|
||||
p.attributes.COLOR_0 = g.accessors.length - 1;
|
||||
const m = g.materials![p.material!];
|
||||
m.pbrMetallicRoughness = { ...m.pbrMetallicRoughness, baseColorFactor: [...t, 1] };
|
||||
added.push(new Uint8Array(out.buffer));
|
||||
at += out.byteLength;
|
||||
graded += a.count;
|
||||
}
|
||||
if (!graded) throw new Error(`${glb}: no mesh with a material named "skin" to grade`);
|
||||
g.buffers[0].byteLength = at;
|
||||
const text = new TextEncoder().encode(JSON.stringify(g)), jlen = text.length + ((4 - (text.length % 4)) % 4);
|
||||
// the file again: its header, the JSON padded with spaces to four bytes, the buffer with the colours after it
|
||||
const file = new Uint8Array(12 + 8 + jlen + 8 + at), w = new DataView(file.buffer);
|
||||
const tag = (o: number, t4: string) => [...t4].forEach((ch, i) => (file[o + i] = ch.charCodeAt(0)));
|
||||
tag(0, "glTF"); w.setUint32(4, 2, true); w.setUint32(8, file.length, true);
|
||||
w.setUint32(12, jlen, true); tag(16, "JSON"); file.fill(0x20, 20, 20 + jlen); file.set(text, 20);
|
||||
w.setUint32(20 + jlen, at, true); tag(24 + jlen, "BIN\0");
|
||||
file.set(b.subarray(at0, at0 + len0), 28 + jlen);
|
||||
let o = 28 + jlen + len0 + ((4 - (len0 % 4)) % 4);
|
||||
for (const c of added) { file.set(c, o); o += c.length; }
|
||||
writeFileSync(glb, file);
|
||||
return `the skin graded to the head at the collar: ${graded} vertices, the neck colour ${tone.map((c) => c.toFixed(3)).join(", ")}, eased over ${Math.round(fade * 100)} cm`;
|
||||
}
|
||||
@@ -27,6 +27,8 @@ import { libraryVerb } from "./library";
|
||||
import { showVerb } from "./show";
|
||||
// `raea clothes` (clothes.ts): garments for SOMA's body from words
|
||||
import { clothesVerb } from "./clothes";
|
||||
// `raea bug` (bug.ts): an agent's report of a bug in raea, to raea's server
|
||||
import { bugVerb } from "./bug";
|
||||
|
||||
function flag(args: string[], name: string): string | undefined {
|
||||
const i = args.indexOf(name);
|
||||
@@ -95,9 +97,11 @@ Layout: <AbsoluteFill>, <Sequence from durationInFrames>, <Series><Series.Sequen
|
||||
Media: <Video src startFrom endAt volume playbackRate muted framing="face" punchIn style> (framing="face" keeps the
|
||||
eyes 38% down as the speaker moves; an objectPosition or transform turns it off), <Audio src startFrom endAt volume={n | (f) => n} gainDb fadeIn fadeOut>,
|
||||
<Img src>. Media files import as modules: import take from
|
||||
"./media/x.mov". Sound: music in Tone.js (import * as Tone from "raea/tone"): instruments in a Tone.Sampler
|
||||
playing a Part or Sequence, the instrument's notes from Tone.tokensynth("a warm upright bass", ["C2", "C3", "C4"]) or a
|
||||
sample library (\`raea sounds\`); sao("prompt", {seconds}) for an effect, as an <Audio src>; narration
|
||||
"./media/x.mov". Sound: decide what each scene is heard as first (silence, its own sound, score, effects); music,
|
||||
where there is some, in Tone.js (import * as Tone from "raea/tone"), composed for the cut (a motif, chords that move,
|
||||
a part with rhythm, ending on a cut; never a pad or drone by default): instruments in a Tone.Sampler playing Parts and
|
||||
Sequences, the notes from a sample library (\`raea sounds\`, \`raea guide sources\`) or, for a timbre no library has,
|
||||
Tone.tokensynth("a bowed saw, close", ["C3", "C4", "C5"]); sao("prompt", {seconds}) for an effect, as an <Audio src>; narration
|
||||
is <Speech text start> from raea/speech (Pocket TTS). All of it local. <Mix lufs ceiling> masters the sound.
|
||||
Words: useWords() -> [{text, from, to}] (frames, the cuts' words), word("phrase") -> the frame it's said,
|
||||
findPhrase(words, "phrase", {occurrence, edge: "start" | "end"}).
|
||||
@@ -267,6 +271,8 @@ export function raeaHandler(host?: Host, engine?: Engine) {
|
||||
return out(showVerb(ask, args.slice(1), c.cwd, (globalThis as { process?: { env: Record<string, string | undefined> } }).process?.env ?? {}));
|
||||
case "clothes":
|
||||
return out(clothesVerb(ask, args.slice(1)));
|
||||
case "bug":
|
||||
return out(bugVerb(ask, args.slice(1), (globalThis as { process?: { env: Record<string, string | undefined> } }).process?.env ?? {}));
|
||||
default:
|
||||
return await native();
|
||||
}
|
||||
|
||||
@@ -304,6 +304,27 @@ function frame(a: { take: string; at?: number }): string {
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/** `raea bug`'s report (bug.ts) to raea's server, with raea's version and the OS added; RAEA_API names the server
|
||||
* (https://raea.io, where raea's server takes reports). No account: the server takes a report from anyone. */
|
||||
function bug(a: { report: Record<string, unknown>; dry?: boolean }) {
|
||||
const version = (spawnSync(raea, ["--version"], { encoding: "utf8" }).stdout ?? "").trim().split(/\s+/).pop() || undefined;
|
||||
const mac = process.platform === "darwin" ? (spawnSync("sw_vers", ["-productVersion"], { encoding: "utf8" }).stdout ?? "").trim() : "";
|
||||
const sent = { ...a.report, raea: version, os: mac ? `macOS ${mac}` : `${process.platform} ${process.arch}` };
|
||||
if (a.dry) return { sent };
|
||||
const api = (process.env.RAEA_API ?? "https://raea.io").replace(/\/$/, "");
|
||||
const r = spawnSync("curl", ["-sS", "--max-time", "20", "-X", "POST", "-H", "content-type: application/json", "--data-binary", "@-", "-w", "\n%{http_code}", `${api}/v1/bugs/agent`], { input: JSON.stringify(sent), encoding: "utf8" });
|
||||
const text = r.stdout ?? "";
|
||||
const cut = text.lastIndexOf("\n");
|
||||
const status = Number(text.slice(cut + 1)) || 0;
|
||||
let answer: { id?: string; count?: number; known?: boolean; message?: string } = {};
|
||||
try {
|
||||
answer = JSON.parse(text.slice(0, cut));
|
||||
} catch {
|
||||
answer = { message: (r.stderr ?? "").trim() || text.slice(0, 200) };
|
||||
}
|
||||
return { ...answer, status, sent };
|
||||
}
|
||||
|
||||
/** One request by curl (the host steps are synchronous): its body and where it ended up, or why it failed */
|
||||
function curl(url: string, o: { out?: string; secs?: number } = {}): { body: string; url: string } {
|
||||
// a browser's agent: some sites send a bare page, or none, to anything else
|
||||
@@ -391,6 +412,8 @@ const host: Host = (op, a) => {
|
||||
return show(a);
|
||||
case "clothes":
|
||||
return clothesHost(raea, cwd, process.env, a);
|
||||
case "bug":
|
||||
return bug(a as { report: Record<string, unknown>; dry?: boolean });
|
||||
case "harness":
|
||||
return harness();
|
||||
case "task":
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
// Sewn garments for `raea clothes` (docs/character.feature CH45c): a garment is a sewing pattern (GarmentCode's
|
||||
// components, MIT) cut to SOMA's measurements, draped on the body by raea's own cloth on the GPU and baked to a
|
||||
// skinned glb, by tools/garments/sew.sh. Its design comes from words (the garment model, when raea's models folder
|
||||
// has one) or from the plain base, with any setting changed by path. A project's sewn garment is
|
||||
// assets/clothes/NAME.json (kind "sewn") with its files in assets/clothes/NAME/.
|
||||
//
|
||||
// What it runs on, in raea's models folder under garments/ (or named by GARMENTCODE, GARMENT_PY, GARMENT_MODEL):
|
||||
// GarmentCode at a fixed commit (cloned the first time and checked by that commit), a Python 3.11 environment made
|
||||
// by uv from a pinned list, the body as a distance grid (made once from SOMA's body), and the words model.
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join, relative } from "node:path";
|
||||
|
||||
type Env = Record<string, string | undefined>;
|
||||
|
||||
const GARMENTCODE = "d449629979028123a5c4dc9e732a2ec19b7fce31";
|
||||
/** the environment's packages, as the first one was made (uv pip freeze), less what they bring with them */
|
||||
const PACKAGES = ["numpy==1.26.4", "scipy==1.17.1", "pyyaml==6.0.3", "svgwrite==1.4.3", "svgpathtools==1.8.0", "cairosvg==2.9.1", "matplotlib==3.11.2", "cgal==6.0.1.post202410241521", "trimesh==5.2.1", "psutil==7.2.2", "networkx==3.6.1", "shapely==2.2.0", "rtree==1.4.1", "libigl==2.6.3", "pillow==13.0.0", "mlx==0.32.4", "onnxruntime==1.32.0", "tokenizers==0.23.3"];
|
||||
|
||||
export type Sewn = { name: string; kind: "sewn"; layer: number; words: string; made: string; colour: string; set: string[]; plain: boolean; glb: string; vertices: number; ok: boolean };
|
||||
|
||||
const run = (cmd: string, args: string[], env?: Env) => spawnSync(cmd, args, { encoding: "utf8", maxBuffer: 64 << 20, env: env as NodeJS.ProcessEnv });
|
||||
const tail = (r: { stdout?: string; stderr?: string }) => `${r.stdout ?? ""}${r.stderr ?? ""}`.trim().split("\n").slice(-6).join("\n");
|
||||
|
||||
/** tools/garments: in RAEA_HOME, beside a release's bin/raea (share/raea/tools), or in the tree a built raea is in */
|
||||
function tools(raea: string, env: Env): string {
|
||||
const bin = dirname(realpathSync(raea));
|
||||
const found = [env.RAEA_HOME && join(env.RAEA_HOME, "tools/garments"), join(bin, "../share/raea/tools/garments"), join(bin, "../../tools/garments")].find((p) => p && existsSync(join(p, "sew.sh")));
|
||||
if (!found) throw new Error(`no tools/garments/sew.sh beside ${bin} (a release keeps it in share/raea/tools/garments)`);
|
||||
return found;
|
||||
}
|
||||
|
||||
/** What sewing runs on, set up the first time; `made` says what was fetched or built */
|
||||
function setup(raea: string, env: Env, models: string, body: string): { env: Env; model: string | undefined; made: string[] } {
|
||||
const dir = join(models, "garments"), made: string[] = [], t = tools(raea, env);
|
||||
const gc = env.GARMENTCODE ?? join(dir, "GarmentCode"), py = env.GARMENT_PY ?? join(dir, "venv/bin/python");
|
||||
if (!existsSync(join(gc, "assets/design_params/t-shirt.yaml"))) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
rmSync(gc, { recursive: true, force: true });
|
||||
const c = run("git", ["clone", "--quiet", "https://github.com/maria-korosteleva/GarmentCode", gc]);
|
||||
if (c.status !== 0) throw new Error(`couldn't fetch GarmentCode (the sewing patterns): ${tail(c)}`);
|
||||
const o = run("git", ["-C", gc, "checkout", "--quiet", GARMENTCODE]), at = run("git", ["-C", gc, "rev-parse", "HEAD"]).stdout?.trim();
|
||||
if (o.status !== 0 || at !== GARMENTCODE) {
|
||||
rmSync(gc, { recursive: true, force: true });
|
||||
throw new Error(`GarmentCode has no commit ${GARMENTCODE}; nothing was kept`);
|
||||
}
|
||||
made.push(`fetched GarmentCode (MIT) at ${GARMENTCODE.slice(0, 7)}: ${gc}`);
|
||||
}
|
||||
if (!existsSync(py)) {
|
||||
const venv = dirname(dirname(py));
|
||||
const v = run("uv", ["venv", "--quiet", "--python", "3.11", venv]);
|
||||
if (v.error) throw new Error("sewing needs uv to make its Python environment (https://docs.astral.sh/uv: brew install uv), or GARMENT_PY naming one that has tools/garments/README.md's packages");
|
||||
if (v.status !== 0) throw new Error(`couldn't make the sewing environment: ${tail(v)}`);
|
||||
const p = run("uv", ["pip", "install", "--quiet", "--python", py, ...PACKAGES]);
|
||||
if (p.status !== 0) {
|
||||
rmSync(venv, { recursive: true, force: true });
|
||||
throw new Error(`couldn't install the sewing environment's packages: ${tail(p)}`);
|
||||
}
|
||||
made.push(`made the sewing environment (Python 3.11, ${PACKAGES.length} packages): ${venv}`);
|
||||
}
|
||||
const sdf = join(dir, "soma_sdf.npz");
|
||||
if (!existsSync(sdf)) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const r = run(py, ["-I", join(t, "sdf_igl.py"), join(body, "body.glb"), sdf]);
|
||||
if (r.status !== 0 || !existsSync(sdf)) throw new Error(`couldn't measure SOMA's body for the drape: ${tail(r)}`);
|
||||
made.push(`measured SOMA's body as a distance grid for the drape: ${sdf}`);
|
||||
}
|
||||
const model = env.GARMENT_MODEL ?? join(dir, "garment-words.npz");
|
||||
return { env: { ...env, GARMENTCODE: gc, GARMENT_PY: py, GARMENT_SDF: sdf, SOMA_BODY: join(body, "body.glb"), RAEA_BIN: raea, PATH: `${dirname(realpathSync(raea))}:${env.PATH ?? ""}` }, model: existsSync(model) ? model : undefined, made };
|
||||
}
|
||||
|
||||
/** every setting of a design: its path, its value in the plain base, what it may be */
|
||||
export function settings(raea: string, env: Env, models: string, body: string): { said: string } {
|
||||
const s = setup(raea, env, models, body), r = run(s.env.GARMENT_PY!, ["-I", join(tools(raea, env), "design.py"), join(s.env.GARMENTCODE!, "assets/design_params/t-shirt.yaml")]);
|
||||
if (r.status !== 0) throw new Error(tail(r));
|
||||
return { said: [...s.made, "A sewn garment's settings, as the plain base has them (raea clothes make NAME --plain --set PATH=VALUE,...):", r.stdout.trim()].join("\n") + "\n" };
|
||||
}
|
||||
|
||||
/** One sewn garment made in the project: assets/clothes/NAME.json and assets/clothes/NAME/ */
|
||||
export function sew(raea: string, cwd: string, env: Env, models: string, body: string, a: { name: string; words?: string; set?: string[]; plain?: boolean; colour?: string; layer?: number }): { said: string } {
|
||||
const s = setup(raea, env, models, body), clothes = join(cwd, "assets/clothes"), own = join(clothes, a.name), file = join(clothes, `${a.name}.json`);
|
||||
const plain = a.plain || !a.words;
|
||||
if (!plain && !s.model) throw new Error(`no words model here yet (${join(models, "garments/garment-words.npz")}): make it from the plain base, raea clothes make ${a.name} --plain --set PATH=VALUE,... (raea clothes settings lists the settings)`);
|
||||
mkdirSync(clothes, { recursive: true });
|
||||
const args = [clothes, a.name, a.words ?? "", ...(plain ? ["--plain"] : []), ...(a.set ?? []).flatMap((x) => ["--set", x]), ...(a.colour ? ["--colour", a.colour] : [])];
|
||||
const r = run("bash", [join(tools(raea, env), "sew.sh"), ...args], { ...s.env, ...(s.model ? { GARMENT_MODEL: s.model } : {}) });
|
||||
const lines = `${r.stdout ?? ""}`.split("\n").filter((l) => l.startsWith("sew: ")).map((l) => l.slice(5));
|
||||
if (r.status !== 0 || !existsSync(join(own, `${a.name}.glb`))) {
|
||||
const why = `${r.stderr ?? ""}`.split("\n").filter((l) => l.startsWith("sew: FAILED") || l.startsWith("design: ")).map((l) => l.replace(/^(sew: FAILED |design: )/, "")).join("; ");
|
||||
if (!existsSync(file)) rmSync(own, { recursive: true, force: true }); // (nothing half-made left beside the project's garments)
|
||||
throw new Error(`${a.name} wasn't sewn: ${why || tail(r)}`);
|
||||
}
|
||||
const bake = JSON.parse(readFileSync(join(own, `${a.name}.bake.json`), "utf8")) as { colour: string; vertices: number };
|
||||
const drape = JSON.parse(readFileSync(join(own, `${a.name}.drape.json`), "utf8")) as { ok: boolean };
|
||||
const made = existsSync(join(own, "caption.txt")) ? readFileSync(join(own, "caption.txt"), "utf8").trim() : a.name;
|
||||
// (the drape's working files are not the garment: its pattern, its design and its pictures are kept)
|
||||
for (const f of [`${a.name}.draped.npz`, `${a.name}.panels.json`, "make.log", "nearest.yaml"]) rmSync(join(own, f), { force: true });
|
||||
const g: Sewn = { name: a.name, kind: "sewn", layer: a.layer ?? 0, words: a.words ?? "", made, colour: bake.colour, set: a.set ?? [], plain, glb: `${a.name}/${a.name}.glb`, vertices: bake.vertices, ok: drape.ok };
|
||||
writeFileSync(file, `${JSON.stringify(g, null, 1)}\n`);
|
||||
return {
|
||||
said: [...s.made, ...lines, `${relative(cwd, file)}, its pictures in ${relative(cwd, own)} (${a.name}_front.png ...): look at them, and change it with --set (raea clothes settings).`, `raea clothes wear assets/characters/NAME ${a.name} puts it on SOMA's body.`].join("\n") + "\n",
|
||||
};
|
||||
}
|
||||
|
||||
/** Sewn garments put on a body folder already written at `out`: each one's glb beside the body, and the body's skin
|
||||
* wholly under them left out (tools/garments/hide_under.py); the lines said */
|
||||
export function wearSewn(raea: string, cwd: string, env: Env, out: string, files: string[]): string[] {
|
||||
const glbs = files.map((f) => {
|
||||
const g = JSON.parse(readFileSync(f, "utf8")) as Sewn, to = join(out, `${g.name}.glb`);
|
||||
copyFileSync(join(dirname(f), g.glb), to);
|
||||
return to;
|
||||
});
|
||||
const body = join(out, "body.glb"), r = run(raea, ["blender", "run", join(tools(raea, env), "hide_under.py"), body, body, ...glbs]);
|
||||
const said = `${r.stdout ?? ""}${r.stderr ?? ""}`.split("\n").filter((l) => l.startsWith("hide_under: ")).map((l) => `the body under ${files.length > 1 ? "the sewn garments" : "the sewn garment"}: ${l.slice(12)}`);
|
||||
if (r.status !== 0 || !said.length) throw new Error(`couldn't leave out the skin under the sewn garments: ${tail(r)}`);
|
||||
return [...glbs.map((g) => `wore ${relative(cwd, g)}`), ...said];
|
||||
}
|
||||
@@ -96,7 +96,7 @@ pub fn mezz(args: &[String]) -> R<String> {
|
||||
|
||||
|
||||
/// The agent shell's own verbs (engine/cli/src/index.ts) this binary runs; the rest come one by one (docs/agent-surfaces.md)
|
||||
pub const SHELL: &[&str] = &["init", "cut", "frame", "component", "part", "brand", "library", "show", "clothes"];
|
||||
pub const SHELL: &[&str] = &["init", "cut", "frame", "component", "part", "brand", "library", "show", "clothes", "bug"];
|
||||
|
||||
/// One of SHELL's verbs: @raea/cli's handler, run by engine/cli/src/native.ts on raea's JavaScriptCore with Node's core, so the
|
||||
/// verb's one source is its TypeScript. native.ts answers the host's ops it needs, and runs this binary for the engine's verbs.
|
||||
|
||||
+39
-121
@@ -1,13 +1,16 @@
|
||||
// The host's side of `raea clothes` (clothes.ts) on the native raea. SOMA-X's two body files are fetched once at a
|
||||
// fixed commit (NVlabs/SOMA-X, Apache-2.0, checked by their SHA-256 and kept with the licence in raea's models
|
||||
// folder, soma/), SOMA's body and the mannequin's views are made from them once by Blender (tools/clothes/body.py,
|
||||
// mannequin.py), each view is dressed by `raea gen image`, and garments are measured and worn by
|
||||
// tools/clothes/garment.py. A project's garments are assets/clothes/NAME.json, with their pictures in
|
||||
// assets/clothes/NAME/.
|
||||
// folder, soma/) and SOMA's body is made from them once by Blender (tools/clothes/body.py). A garment is sewn
|
||||
// (sewn.ts: a pattern cut to SOMA, draped and baked) or made by procedure on the skin (tools/clothes/garment.py
|
||||
// cover); both are worn by `wear`. A project's garments are assets/clothes/NAME.json, their files in
|
||||
// assets/clothes/NAME/. (Garments measured from four drawn pictures were taken out on 11-15: paint on a
|
||||
// skin-tight shell showed no cut, hem or fold, and four pictures never agreed.)
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync } from "node:fs";
|
||||
import { basename, dirname, isAbsolute, join, relative } from "node:path";
|
||||
import { gradeToHead } from "./grade";
|
||||
import { settings, sew, wearSewn } from "./sewn";
|
||||
|
||||
type Env = Record<string, string | undefined>;
|
||||
type Said = { said: string };
|
||||
@@ -17,17 +20,6 @@ const SOMA_X: Record<string, string> = {
|
||||
"SOMA_template_rig.usda": "a952cb7bdf4ccd801e355d53122d395b985b69d0d9181439edad5081bb171856",
|
||||
"SOMA_neutral.npz": "5829af4a5333abdba5ad449360b868faacee99d395971e62f35c0e7169432b63",
|
||||
};
|
||||
const VIEWS = ["front", "back", "left", "right"];
|
||||
// what every picture must keep, so it lies over the mannequin pixel for pixel and the measure can read it
|
||||
const KEEP =
|
||||
"Keep EXACTLY the pose, the proportions, the place of every limb and finger, the size in the frame and the camera view. Where no clothing covers it the mannequin stays featureless dark grey. Flat, even, unlit colour: no cast shadows, no highlights, plain light grey #C8C8C8 background, no text.";
|
||||
const seen = (v: string) =>
|
||||
v === "front"
|
||||
? "seen from the FRONT"
|
||||
: v === "back"
|
||||
? "seen from BEHIND: we see its back, the back of its head and its heels, and only the back of each garment (no front opening, zip or buttons)"
|
||||
: `seen exactly from its ${v} side, in profile`;
|
||||
|
||||
/** raea's models folder (raea_io_home::models): ~/.local/share/raea-models, %LOCALAPPDATA%\raea\models on Windows */
|
||||
const modelsDir = (env: Env) => (process.platform === "win32" && env.LOCALAPPDATA ? join(env.LOCALAPPDATA, "raea", "models") : join(env.HOME ?? "", ".local/share/raea-models"));
|
||||
|
||||
@@ -69,135 +61,57 @@ function somaX(dir: string): { rig: string; shapes: string } {
|
||||
return { rig: join(dir, "SOMA_template_rig.usda"), shapes: join(dir, "SOMA_neutral.npz") };
|
||||
}
|
||||
|
||||
/** SOMA's body (soma/body: body.glb, skeleton.json) and the mannequin's four views (soma/mannequin), made once */
|
||||
function soma(raea: string, env: Env): { rig: string; body: string; mannequin: string; made: string[] } {
|
||||
/** SOMA's body (soma/body: body.glb, skeleton.json), made once */
|
||||
function soma(raea: string, env: Env): { rig: string; body: string; made: string[] } {
|
||||
const dir = join(modelsDir(env), "soma"), x = somaX(dir), made: string[] = [];
|
||||
const body = join(dir, "body"), mannequin = join(dir, "mannequin");
|
||||
const body = join(dir, "body");
|
||||
if (!["body.glb", "skeleton.json", "joint.glb"].every((f) => existsSync(join(body, f)))) made.push(...blender(raea, env, "body.py", [x.rig, x.shapes, body]));
|
||||
if (!VIEWS.every((v) => existsSync(join(mannequin, `mannequin_${v}.png`)))) made.push(...blender(raea, env, "mannequin.py", [join(body, "body.glb"), mannequin]));
|
||||
return { rig: x.rig, body, mannequin, made };
|
||||
return { rig: x.rig, body, made };
|
||||
}
|
||||
|
||||
type Garment = { name: string; layer: number; vertices: number[]; stand: number[]; over?: string; topology?: string; source?: { views?: string } };
|
||||
type Garment = { name: string; layer: number; vertices: number[]; stand: number[]; over?: string; topology?: string; kind?: string; made?: string };
|
||||
const readGarment = (file: string) => JSON.parse(readFileSync(file, "utf8")) as Garment;
|
||||
|
||||
/** a garment and what it is over, innermost first */
|
||||
function chainOf(clothes: string, name: string, depth = 0): string[] {
|
||||
const file = join(clothes, `${name}.json`);
|
||||
if (!existsSync(file)) throw new Error(`no garment ${name} (assets/clothes/${name}.json): raea clothes lists the ones made`);
|
||||
// (over several at once: "tee+shorts")
|
||||
const g = readGarment(file), under = g.over && depth < 8 ? g.over.split("+").flatMap((o) => chainOf(clothes, o, depth + 1)) : [];
|
||||
return [...new Set(under.filter((n) => n !== name)), name];
|
||||
}
|
||||
|
||||
/** What a new garment is drawn over: the pictures to draw on and measure against, and the layer beneath as one
|
||||
* garment file. One garment drawn from pictures is its own pictures; a garment made by procedure (no pictures), or
|
||||
* several at once, is drawn: the mannequin wearing them, innermost first, by Blender. */
|
||||
function beneath(raea: string, env: Env, s: { rig: string; body: string }, clothes: string, own: string, over: string[]): { views: string; file: string; said: string[] } {
|
||||
const one = over.length === 1 ? readGarment(join(clothes, `${over[0]}.json`)) : undefined;
|
||||
if (one?.source?.views && existsSync(join(clothes, over[0], "views", "front.jpg"))) return { views: join(clothes, over[0], "views"), file: join(clothes, `${over[0]}.json`), said: [] };
|
||||
const names = [...new Set(over.flatMap((n) => chainOf(clothes, n)))], files = names.map((n) => join(clothes, `${n}.json`));
|
||||
const worn = join(own, "under"), views = join(own, "under", "views");
|
||||
blender(raea, env, "garment.py", ["wear", join(s.body, "body.glb"), s.rig, worn, ...files]);
|
||||
blender(raea, env, "mannequin.py", [join(worn, "body.glb"), views, "1024", ...names.map((n) => join(worn, `${n}.glb`))]);
|
||||
// the layers beneath as one: every vertex any of them covers, at the farthest any stands off
|
||||
const gs = files.map(readGarment), stand = new Map<number, number>();
|
||||
for (const g of gs) g.vertices.forEach((v, k) => stand.set(v, Math.max(stand.get(v) ?? 0, g.stand[k])));
|
||||
const ids = [...stand.keys()].sort((x, y) => x - y), file = join(worn, "beneath.json");
|
||||
writeFileSync(file, JSON.stringify({ name: over.join("+"), layer: Math.max(...gs.map((g) => g.layer)), vertices: ids, stand: ids.map((v) => stand.get(v)) }));
|
||||
return { views, file, said: [`drew the mannequin wearing ${names.join(", ")} to draw over (${views})`] };
|
||||
}
|
||||
|
||||
function list(cwd: string) {
|
||||
const dir = join(cwd, "assets/clothes");
|
||||
const files = existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith(".json")).sort() : [];
|
||||
const garments = files.map((f) => readGarment(join(dir, f))).filter((g) => g.topology?.startsWith("SOMA"));
|
||||
return { garments: garments.map((g) => ({ name: g.name, layer: g.layer, vertices: g.vertices.length, over: g.over })) };
|
||||
const garments = files.map((f) => readGarment(join(dir, f))).filter((g) => g.kind === "sewn" || g.topology?.startsWith("SOMA"));
|
||||
return { garments: garments.map((g) => (g.kind === "sewn" ? { name: g.name, layer: g.layer, sewn: g.made ?? "" } : { name: g.name, layer: g.layer, vertices: g.vertices.length, over: g.over })) };
|
||||
}
|
||||
|
||||
/** what one picture cost: the gen log's last "cents" (its total; the ones before are its steps') */
|
||||
const centsOf = (log: string) => Number([...readFileSync(log, "utf8").matchAll(/"cents":\s*(\d+(?:\.\d+)?)/g)].pop()?.[1] ?? 0);
|
||||
|
||||
/** The four views dressed by the image model at once, each its own call (a sheet of views, or a second picture to
|
||||
* follow, loses the registration), kept as OWN/views/VIEW.jpg; what they cost, in cents */
|
||||
function draw(raea: string, cwd: string, own: string, sources: (v: string) => string, layered: boolean, words: string, cents: number): number {
|
||||
const views = join(own, "views");
|
||||
mkdirSync(views, { recursive: true });
|
||||
const jobs = VIEWS.flatMap((v) => {
|
||||
const src = sources(v);
|
||||
if (!existsSync(src)) throw new Error(`${src}: the ${v} view to draw on is missing`);
|
||||
const prompt = layered
|
||||
? `This dressed mannequin is ${seen(v)}. Add exactly one thing and keep everything else pixel for pixel: ${words}, worn over what it already wears. ${KEEP}`
|
||||
: `This grey mannequin is ${seen(v)}. Turn it into the same mannequin, still ${seen(v)}, wearing ${words}; only the surface changes where clothing covers it. ${KEEP}`;
|
||||
rmSync(join(own, `gen_${v}`), { recursive: true, force: true });
|
||||
return [prompt, src, join(own, `gen_${v}`), String(cents)];
|
||||
});
|
||||
const run = 'r=$1; shift; while [ $# -gt 0 ]; do ( "$r" gen image "$1" --model flux_2_pro --image "$2" --aspect 1:1 -o "$3" --max-cents "$4" > "$3.log" 2>&1 ) & shift 4; done; wait';
|
||||
spawnSync("bash", ["-c", run, "clothes", raea, ...jobs], { encoding: "utf8" });
|
||||
let spent = 0;
|
||||
for (const v of VIEWS) {
|
||||
const dir = join(own, `gen_${v}`), pic = existsSync(dir) ? readdirSync(dir).find((f) => /^out\.(jpe?g|png|webp)$/.test(f)) : undefined;
|
||||
if (!pic) throw new Error(`no picture for the ${v} view: ${relative(cwd, `${dir}.log`)} says why`);
|
||||
copyFileSync(join(dir, pic), join(views, `${v}.jpg`));
|
||||
spent += centsOf(`${dir}.log`);
|
||||
}
|
||||
return spent;
|
||||
}
|
||||
|
||||
/** make draws and measures; again (remeasure) measures the pictures already kept, drawing nothing */
|
||||
function make(raea: string, cwd: string, env: Env, a: { name: string; words?: string; over?: string; cents?: number; again?: boolean }): Said {
|
||||
const clothes = join(cwd, "assets/clothes"), own = join(clothes, a.name), views = join(own, "views"), file = join(clothes, `${a.name}.json`);
|
||||
let over = a.over ? a.over.split(",") : [];
|
||||
if (a.again) {
|
||||
if (!existsSync(file)) throw new Error(`no garment ${a.name} (assets/clothes/${a.name}.json): raea clothes lists the ones made`);
|
||||
const g = readGarment(file);
|
||||
if (!g.source?.views || !VIEWS.every((v) => existsSync(join(views, `${v}.jpg`)))) throw new Error(`${a.name} has no pictures to measure (${relative(cwd, views)}): one made by procedure is made again with raea clothes cover`);
|
||||
over = g.over ? g.over.split("+") : [];
|
||||
}
|
||||
for (const o of over) if (!existsSync(join(clothes, `${o}.json`))) throw new Error(`no garment ${o} (assets/clothes/${o}.json): raea clothes lists the ones made`);
|
||||
if (over.includes(a.name)) throw new Error("a garment can't be drawn over itself");
|
||||
const s = soma(raea, env);
|
||||
mkdirSync(own, { recursive: true });
|
||||
const under = over.length ? beneath(raea, env, s, clothes, own, over) : undefined;
|
||||
const cents = a.again ? 0 : draw(raea, cwd, own, (v) => (under ? join(under.views, `${v}.jpg`) : join(s.mannequin, `mannequin_${v}.png`)), !!under, a.words ?? "", a.cents ?? 10);
|
||||
const said = blender(raea, env, "garment.py", ["measure", join(s.body, "body.glb"), s.rig, views, file, ...(under ? [under.file, under.views] : [])]);
|
||||
if (!existsSync(file)) throw new Error(`the pictures didn't measure into a garment (${relative(cwd, views)})`);
|
||||
const worn = [...new Set(over.flatMap((o) => chainOf(clothes, o))), a.name].join(" ");
|
||||
return {
|
||||
said: [
|
||||
...s.made,
|
||||
...(under?.said ?? []),
|
||||
a.again ? `${a.name}: measured again from its four pictures (${relative(cwd, views)}), nothing drawn` : `${a.name}: four pictures, ${cents} cents (${relative(cwd, views)})`,
|
||||
...said,
|
||||
`${relative(cwd, file)}. raea clothes wear assets/characters/NAME ${worn} puts it on SOMA's body; look at its pictures before you do.`,
|
||||
].join("\n") + "\n",
|
||||
};
|
||||
}
|
||||
|
||||
function cover(raea: string, cwd: string, env: Env, a: { name: string; parts: string; colour: string; stand: number; over?: string }): Said {
|
||||
function cover(raea: string, cwd: string, env: Env, a: { name: string; parts: string; colour: string; stand: number; over?: string; hard?: { sole?: number; soleColour?: string; panels?: string[] } }): Said {
|
||||
const clothes = join(cwd, "assets/clothes"), file = join(clothes, `${a.name}.json`), under = a.over ? join(clothes, `${a.over}.json`) : undefined;
|
||||
if (under && !existsSync(under)) throw new Error(`no garment ${a.over} (assets/clothes/${a.over}.json): raea clothes lists the ones made`);
|
||||
if (a.over === a.name) throw new Error("a garment can't be laid over itself");
|
||||
const s = soma(raea, env);
|
||||
mkdirSync(clothes, { recursive: true });
|
||||
const said = blender(raea, env, "garment.py", ["cover", join(s.body, "body.glb"), s.rig, file, a.parts, a.colour, String(a.stand), ...(under ? [under] : [])]);
|
||||
const hard = a.hard ? ["--hard", ...(a.hard.sole !== undefined ? ["--sole", String(a.hard.sole)] : []), ...(a.hard.soleColour ? ["--sole-colour", a.hard.soleColour] : []), ...(a.hard.panels?.length ? ["--panels", a.hard.panels.join(",")] : [])] : [];
|
||||
const said = blender(raea, env, "garment.py", ["cover", join(s.body, "body.glb"), s.rig, file, a.parts, a.colour, String(a.stand), ...(under ? [under] : []), ...hard]);
|
||||
if (!existsSync(file)) throw new Error("no garment was written");
|
||||
return { said: [...s.made, ...said, `${relative(cwd, file)}. raea clothes wear assets/characters/NAME ${a.over ? `${a.over} ` : ""}${a.name} puts it on SOMA's body.`].join("\n") + "\n" };
|
||||
}
|
||||
|
||||
function wear(raea: string, cwd: string, env: Env, a: { out: string; garments: string[]; body?: string }): Said {
|
||||
function wear(raea: string, cwd: string, env: Env, a: { out: string; garments: string[]; body?: string; head?: string }): Said {
|
||||
const at = (p: string) => (isAbsolute(p) ? p : join(cwd, p));
|
||||
const files = a.garments.map((g) => (g.endsWith(".json") ? at(g) : join(cwd, "assets/clothes", `${g}.json`)));
|
||||
for (const f of files) if (!existsSync(f)) throw new Error(`no garment ${relative(cwd, f)}: raea clothes lists the ones made`);
|
||||
// innermost first: a garment drawn over another goes after it
|
||||
const layers = files.map((f) => readGarment(f).layer);
|
||||
// sewn garments are their own meshes; the ones made on the skin are laid on it innermost first
|
||||
const sewn = files.filter((f) => readGarment(f).kind === "sewn"), onSkin = files.filter((f) => !sewn.includes(f));
|
||||
const layers = onSkin.map((f) => readGarment(f).layer);
|
||||
if (layers.some((l, k) => k > 0 && l < layers[k - 1])) throw new Error(`put the garments innermost first (their layers are ${layers.join(", ")})`);
|
||||
const s = soma(raea, env), body = a.body ? at(a.body) : s.body, out = at(a.out);
|
||||
if (!existsSync(join(body, "body.glb"))) throw new Error(`${a.body}: not a body folder (no body.glb)`);
|
||||
mkdirSync(out, { recursive: true });
|
||||
const said = blender(raea, env, "garment.py", ["wear", join(body, "body.glb"), s.rig, out, ...files]);
|
||||
const said = blender(raea, env, "garment.py", ["wear", join(body, "body.glb"), s.rig, out, ...onSkin]);
|
||||
if (sewn.length) said.push(...wearSewn(raea, cwd, env, out, sewn));
|
||||
// the dressed body is a body folder of its own: its skeleton, its joints' stand-in and a headless body's collar
|
||||
for (const f of ["skeleton.json", "joint.glb", "collar.json"]) if (existsSync(join(body, f))) copyFileSync(join(body, f), join(out, f));
|
||||
// a head that joins the body at the collar: the body's skin graded to the head's (grade.ts)
|
||||
if (a.head) {
|
||||
const json = join(at(a.head), "head.json");
|
||||
if (!existsSync(json)) throw new Error(`${a.head}: not a head folder (no head.json)`);
|
||||
said.push(gradeToHead(join(out, "body.glb"), json));
|
||||
}
|
||||
const served = relative(join(cwd, "assets"), out);
|
||||
const use = served.startsWith("..")
|
||||
? ""
|
||||
@@ -205,15 +119,19 @@ function wear(raea: string, cwd: string, env: Env, a: { out: string; garments: s
|
||||
return { said: [...s.made, ...said].join("\n") + use + "\n" };
|
||||
}
|
||||
|
||||
/** host op "clothes": list, make, remeasure, cover or wear */
|
||||
/** host op "clothes": list, settings, make, cover or wear */
|
||||
export function clothesHost(raea: string, cwd: string, env: Env, a: Record<string, unknown>): unknown {
|
||||
switch (a.op) {
|
||||
case "list":
|
||||
return list(cwd);
|
||||
case "make":
|
||||
return make(raea, cwd, env, a as Parameters<typeof make>[3]);
|
||||
case "remeasure":
|
||||
return make(raea, cwd, env, { name: String(a.name), again: true });
|
||||
case "settings": {
|
||||
const s = soma(raea, env), r = settings(raea, env, modelsDir(env), s.body);
|
||||
return { said: [...s.made, r.said].join("\n") };
|
||||
}
|
||||
case "make": {
|
||||
const s = soma(raea, env), r = sew(raea, cwd, env, modelsDir(env), s.body, a as Parameters<typeof sew>[5]);
|
||||
return { said: [...s.made, r.said].join("\n") };
|
||||
}
|
||||
case "cover":
|
||||
return cover(raea, cwd, env, a as Parameters<typeof cover>[3]);
|
||||
case "wear":
|
||||
|
||||
@@ -33,6 +33,8 @@ raea-page-window = { path = "../window" }
|
||||
raea-sys-page = { path = "../../../systems/page" }
|
||||
# headless, the system calls are scripted (docs/targets.feature T2d)
|
||||
raea-io-os = { path = "../../../io/os" }
|
||||
# raea's settings file (~/.raea/env): the window's perf switches, set where the app's window has no shell (main.rs)
|
||||
raea-io-home = { path = "../../../io/home" }
|
||||
raea-sys-fonts = { path = "../../../systems/fonts" }
|
||||
raea-runtime-dom = { path = "../../../runtime/dom" }
|
||||
raea-runtime-input = { path = "../../../runtime/input" }
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
//! The window at rest (on by default since 0.1.6; RAEA_IDLE_GATE=0 draws every frame). Bevy's default runs the whole
|
||||
//! frame 60 times a second, focused or behind other windows, though a page painted the same isn't drawn again (draw.rs):
|
||||
//! the page's step, its restyle and paint, and Bevy's render and present of a picture that didn't change were 0.29 of a
|
||||
//! core with the app's feed open and still (11-16). After half a second in which no page was drawn and none is
|
||||
//! animating, the window waits for input before its next frame (or 50 ms when focused, 250 ms behind other windows, so
|
||||
//! a page's timers and answers still arrive); the first frame that draws a page puts it back to every frame. A playing
|
||||
//! video, a game on the stage and any view draw their page every frame, so they never rest.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy::winit::{UpdateMode, WinitSettings};
|
||||
|
||||
/// Frames in a row with nothing drawn before the window rests.
|
||||
const QUIET: u32 = 30;
|
||||
|
||||
pub struct IdlePlugin;
|
||||
|
||||
impl Plugin for IdlePlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(Last, rest);
|
||||
}
|
||||
}
|
||||
|
||||
fn rest(settings: Option<ResMut<WinitSettings>>, docs: Option<NonSend<raea_sys_page::Docs>>, mut last: Local<u64>, mut quiet: Local<u32>) {
|
||||
let Some(mut settings) = settings else { return };
|
||||
let drawn = raea_sys_page::DRAWS.load(std::sync::atomic::Ordering::Relaxed);
|
||||
let moved = drawn != *last || docs.is_some_and(|d| d.0.values().any(|d| d.is_animating()));
|
||||
*last = drawn;
|
||||
*quiet = quieter(*quiet, moved);
|
||||
let (focused, unfocused) = modes(*quiet);
|
||||
if settings.focused_mode != focused || settings.unfocused_mode != unfocused {
|
||||
settings.focused_mode = focused;
|
||||
settings.unfocused_mode = unfocused;
|
||||
}
|
||||
}
|
||||
|
||||
/// The frames in a row with nothing drawn after this one: none when a page was drawn or one is animating.
|
||||
fn quieter(quiet: u32, moved: bool) -> u32 {
|
||||
if moved { 0 } else { quiet.saturating_add(1) }
|
||||
}
|
||||
|
||||
/// The window's update modes, focused and behind other windows, `quiet` frames into a run with nothing drawn: every
|
||||
/// frame until QUIET, then waiting for input (or 50 ms focused, 250 ms behind, for a page's timers and answers).
|
||||
fn modes(quiet: u32) -> (UpdateMode, UpdateMode) {
|
||||
if quiet >= QUIET {
|
||||
(UpdateMode::reactive(Duration::from_millis(50)), UpdateMode::reactive_low_power(Duration::from_millis(250)))
|
||||
} else {
|
||||
(UpdateMode::Continuous, UpdateMode::Continuous)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_window_rests_after_half_a_second_with_nothing_drawn_and_wakes_on_the_next_draw() {
|
||||
let mut quiet = 0;
|
||||
// a page drawn every frame (a video playing, a game): never rests
|
||||
for _ in 0..100 {
|
||||
quiet = quieter(quiet, true);
|
||||
assert_eq!(modes(quiet).0, UpdateMode::Continuous);
|
||||
}
|
||||
// nothing drawn: every frame for QUIET frames, then waiting
|
||||
for n in 1..=QUIET {
|
||||
quiet = quieter(quiet, false);
|
||||
assert_eq!(modes(quiet).0 == UpdateMode::Continuous, n < QUIET, "frame {n} of the quiet run");
|
||||
}
|
||||
assert_eq!(modes(quiet), (UpdateMode::reactive(Duration::from_millis(50)), UpdateMode::reactive_low_power(Duration::from_millis(250))));
|
||||
// the first frame that draws (a key, an answer, a timer's change) puts it back to every frame at once
|
||||
quiet = quieter(quiet, true);
|
||||
assert_eq!(modes(quiet), (UpdateMode::Continuous, UpdateMode::Continuous));
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ pub mod brp;
|
||||
pub use raea_page_window::{chrome, native};
|
||||
/// the live stage, in raea-page-stage
|
||||
pub use raea_page_stage as stage;
|
||||
#[cfg(feature = "window")]
|
||||
pub mod idle;
|
||||
pub mod inject;
|
||||
pub mod mcp;
|
||||
pub mod page;
|
||||
|
||||
@@ -105,6 +105,24 @@ fn main() {
|
||||
// each update draws its own frame: the frame `ui` reports is the one rendered
|
||||
.disable::<PipelinedRenderingPlugin>(),
|
||||
);
|
||||
// every schedule on one thread: the window's ~290 systems a frame are each a few µs, and the multi-threaded executor
|
||||
// spent more waking its workers for them than they took (35% of the window's busy time at rest). On one thread, the
|
||||
// app's window used 34% less CPU at rest, 8% less through a drag and 4% less playing a film, its frames as long
|
||||
// (11-16, three rounds each). Systems' own par_iter still use the task pools. On by default since 0.1.6 (the
|
||||
// developer, 11-16); RAEA_ST=0 for Bevy's multi-threaded one, in the environment or raea's settings file
|
||||
// (~/.raea/env: the app's window has no shell to set it in). Known: playback's "a seek while it plays" shows one more
|
||||
// frame from where it was after the seek (3 runs of 3; the multi-threaded run shows two, as the spec allows)
|
||||
if raea_io_home::setting("RAEA_ST").as_deref() != Some("0") {
|
||||
// a schedule that's running is out of Schedules: First sets the rest, Last sets First (Main is one system)
|
||||
app.add_systems(First, single_threaded).add_systems(Last, single_threaded);
|
||||
app.sub_app_mut(bevy::render::RenderApp).add_systems(bevy::render::ExtractSchedule, single_threaded).add_systems(bevy::render::Render, single_threaded);
|
||||
}
|
||||
// on screen, a window with nothing changing waits for input (raea_page_host::idle): on by default since 0.1.6 (the
|
||||
// developer, 11-16), RAEA_IDLE_GATE=0 (the environment or ~/.raea/env, as RAEA_ST) for every frame drawn
|
||||
#[cfg(feature = "window")]
|
||||
if a.window && raea_io_home::setting("RAEA_IDLE_GATE").as_deref() != Some("0") {
|
||||
app.add_plugins(raea_page_host::idle::IdlePlugin);
|
||||
}
|
||||
// on screen, bevy_winit's event loop is the runner (a ScheduleRunner here replaced it: no window, 11-04)
|
||||
if !a.window && !app.is_plugin_added::<ScheduleRunnerPlugin>() {
|
||||
// 60 frames a second, as most screens; RAEA_PAGE_FPS stands in for another screen's rate (a 120 Hz one, to
|
||||
@@ -149,3 +167,15 @@ fn main() {
|
||||
app.add_systems(Last, page::tree.before(tree::answer));
|
||||
app.run();
|
||||
}
|
||||
|
||||
/// Every schedule of this world that isn't running now, on the single-threaded executor (once, in each schedule it's in).
|
||||
fn single_threaded(world: &mut World, mut done: Local<bool>) {
|
||||
if std::mem::replace(&mut *done, true) {
|
||||
return;
|
||||
}
|
||||
if let Some(mut schedules) = world.get_resource_mut::<bevy::ecs::schedule::Schedules>() {
|
||||
for (_, s) in schedules.iter_mut() {
|
||||
s.set_executor(bevy::ecs::schedule::SingleThreadedExecutor::new());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,8 +14,9 @@
|
||||
//!
|
||||
//! Live only on screen (--window) and without RAEA_NO_OPEN=1: otherwise every call is recorded and answered as if done,
|
||||
//! so headless runs never touch the person's clipboard, browser or notifications. Notifications and raea:// links need
|
||||
//! the app's identity: the window running as raea.app's own process (tools/raea-app/launch.sh execs it from
|
||||
//! Contents/MacOS); elsewhere notify answers an error that says so.
|
||||
//! the app's identity: the window's program in raea.app's Contents/MacOS, which makes raea.app its main bundle
|
||||
//! (tools/raea-app/launch.sh starts it there as its child, never exec'd: an exec left the app without a pid in AppKit,
|
||||
//! #163); elsewhere notify answers an error that says so.
|
||||
//! AppKit is called on the main thread: the calls queue here and `drain` (a NonSend system) runs them.
|
||||
|
||||
use std::sync::Mutex;
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
//! RT1 (docs/raytracing.feature): each frame's motion vectors and depth, the guide data a neural or denoising pass
|
||||
//! after the render needs (MLX-DLSS's run-sequence, MetalFX). Asked for with `want_aov`, before the first draw: the 3D
|
||||
//! cameras then draw Bevy's depth and motion-vector prepasses (MSAA off: a multisampled prepass can't be read), and
|
||||
//! cameras then draw Bevy's depth and motion-vector prepasses (MSAA off on every frame: they're read single-sampled), and
|
||||
//! each frame's first draw reads both back (`take_aov`). A redraw of the same frame keeps the first draw's: drawn
|
||||
//! again, every mesh's last pose is its pose now, and its motion would read zero.
|
||||
|
||||
use super::*;
|
||||
use bevy::core_pipeline::prepass::{DepthPrepass, MotionVectorPrepass, ViewPrepassTextures};
|
||||
use raea_sys_compose::passes::PrepassRead;
|
||||
|
||||
/// One frame's guide data at the prepass's size (the frame's, times RAEA_SS).
|
||||
pub struct Aov {
|
||||
@@ -24,9 +25,13 @@ pub(crate) struct AovWanted {
|
||||
last: Option<Aov>,
|
||||
}
|
||||
|
||||
fn aov_prepasses(mut cmd: Commands, q: Query<Entity, (With<Camera3d>, Without<MotionVectorPrepass>)>) {
|
||||
/// Each 3D camera draws both prepasses, single-sampled on every frame: PrepassRead keeps the row's post-processing from
|
||||
/// putting MSAA back (#159: raea-sys-post's sync did on the first frame whose post changed, msaa_for_3d on each frame
|
||||
/// of a live scene, and frame 2's readback was refused). Marked by PrepassRead, not by the motion-vector prepass, which
|
||||
/// a camera with motion blur has already.
|
||||
fn aov_prepasses(mut cmd: Commands, q: Query<Entity, (With<Camera3d>, Or<(Without<PrepassRead>, Without<DepthPrepass>, Without<MotionVectorPrepass>)>)>) {
|
||||
for e in &q {
|
||||
cmd.entity(e).insert((DepthPrepass, MotionVectorPrepass, Msaa::Off));
|
||||
cmd.entity(e).insert((DepthPrepass, MotionVectorPrepass, Msaa::Off, PrepassRead));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,6 +98,12 @@ impl Engine {
|
||||
.ok_or("no 3D camera drew a depth and motion-vector prepass")?;
|
||||
// the target is a row taller than the frame (the frame tag's row, open.rs), at the frame's scale (RAEA_SS)
|
||||
let (w, h) = (pick.size.width, pick.size.height.min(self.h * (pick.size.width / self.w.max(1)).max(1)));
|
||||
// the bindings below are single-sampled: a multisampled prepass is said here, not given to the GPU, whose
|
||||
// validation error stops the render
|
||||
let samples = pick.motion_vectors.as_ref().unwrap().texture.texture.sample_count();
|
||||
if samples > 1 {
|
||||
return Err(format!("the prepass is multisampled ({samples} samples)"));
|
||||
}
|
||||
let depth = pick.depth_only_view().ok_or("the prepass has no depth view")?.clone();
|
||||
let motion = pick.motion_vectors.as_ref().unwrap().texture.default_view.clone();
|
||||
let device = rw.resource::<bevy::render::renderer::RenderDevice>().wgpu_device().clone();
|
||||
|
||||
@@ -15,6 +15,12 @@ impl Engine {
|
||||
}
|
||||
// kept (and the frames before a frame stepped through: catch_up) only when the rows need steps (#77)
|
||||
self.replay = (plugins::active(self.app.world()) && plugins::steps(inserted)).then(|| (prog.clone(), inserted.to_vec()));
|
||||
// without them, the plugins' clock steps nothing: Time and the keyed rows are each frame's however it's reached
|
||||
// (a still at frame 200, a batch's second frame, a seek), not frozen at the first frame drawn (#162)
|
||||
let pure = self.replay.is_none();
|
||||
if let Some(mut c) = self.app.world_mut().get_resource_mut::<plugins::PluginClock>() {
|
||||
c.pure = pure;
|
||||
}
|
||||
self.drawn = None;
|
||||
let world = self.app.world_mut();
|
||||
let g = world.resource::<Gen>().0;
|
||||
|
||||
@@ -12,7 +12,7 @@ fn home() -> PathBuf {
|
||||
|
||||
/// `file`'s script
|
||||
pub fn script(file: &Path) -> String {
|
||||
raea_runtime_bundle_lib::app::bundle(file, &home()).unwrap().0
|
||||
raea_runtime_bundle_lib::app::bundle(file, &home(), raea_runtime_bundle_lib::app::WINDOW).unwrap().0
|
||||
}
|
||||
|
||||
/// tests/apps/`name`
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "raea-runtime-appscreen"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "FSL-1.1-ALv2"
|
||||
publish = false
|
||||
description = "App screens (<Screen app>): a module on @raea/ui's react-dom in a Blitz document of its own at the screen's size, stepped once a frame on the frame's clock with the input routed to it"
|
||||
|
||||
[dependencies]
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "bevy_render", "bevy_window"] }
|
||||
blitz-traits = "=0.3.0-beta.4"
|
||||
keyboard-types = "0.8"
|
||||
serde_json = "1"
|
||||
raea-page = { path = "../../engine/page" }
|
||||
raea-runtime-dom = { path = "../dom" }
|
||||
raea-runtime-js = { path = "../js" }
|
||||
raea-runtime-jsengine = { path = "../jsengine" }
|
||||
raea-runtime-bundle = { path = "../bundle" }
|
||||
raea-sys-page = { path = "../../systems/page" }
|
||||
raea-sys-fonts = { path = "../../systems/fonts" }
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
@@ -0,0 +1,299 @@
|
||||
//! App screens (`<Screen app="kit.tsx">`, docs/blitz-bevy.feature H12): each one's module, its default export a React
|
||||
//! component given `{width, height}`, runs on @raea/ui's react-dom in a Blitz document of its own at the screen's
|
||||
//! size, on a page App of its own (raea-page's BlitzPage), so it is stepped exactly once a frame however often the
|
||||
//! composition's page is synced or drawn. A step sends the input routed to it as Blitz's pointer, wheel and key
|
||||
//! events, then runs one update that runs its JS (its frame, timers and commits) with the JS clock held at the
|
||||
//! frame's time (raea-runtime-jsengine `at_clock`), and paints it. A render and its play step it on the same frames
|
||||
//! with the same input, so the screen shows the same picture in both. Its picture goes where a nested <Screen>'s
|
||||
//! goes: its texture on the shared device in play (Engine::copy_screen), read back in a render.
|
||||
//!
|
||||
//! An app's own timers and performance.now follow the frames; its Date doesn't (a module reading the wall clock draws
|
||||
//! another time in a render).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use bevy::input::ButtonState;
|
||||
use bevy::input::mouse::{MouseButton, MouseButtonInput, MouseScrollUnit, MouseWheel};
|
||||
use bevy::input::touch::TouchPhase;
|
||||
use bevy::prelude::*;
|
||||
use bevy::render::settings::RenderCreation;
|
||||
use bevy::window::{CursorLeft, CursorMoved, WindowEvent};
|
||||
use blitz_traits::events::{BlitzKeyEvent, KeyState, UiEvent};
|
||||
use keyboard_types::{Code, Key, Location, Modifiers};
|
||||
use raea_page::motion::BlitzPage;
|
||||
use raea_runtime_dom::host::{self, WindowInput};
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
/// What a prebuilt app screen's script is called beside its module (`kit.tsx` -> `kit.tsx.surface.js`): an exported
|
||||
/// game's, which bundles nothing (apps/game gather.rs). Its CSS is beside it as [`BUNDLED_CSS`].
|
||||
pub const BUNDLED: &str = ".surface.js";
|
||||
pub const BUNDLED_CSS: &str = ".surface.css";
|
||||
|
||||
/// One frame's input for an app screen: the pointer on its picture (its px) and whether it's down, the keys held
|
||||
/// for it (while it has the focus), and the wheel's turns over it (CSS px, down positive, as the DOM's deltaY).
|
||||
#[derive(Default, Clone, Debug, PartialEq)]
|
||||
pub struct Input {
|
||||
pub pointer: Option<(f64, f64, bool)>,
|
||||
pub keys: Vec<String>,
|
||||
pub wheel: Vec<f64>,
|
||||
}
|
||||
|
||||
/// What reached the app screens in a frame, from live play's routing (runtime/page screen.rs route) or a render's input
|
||||
/// log of it: the screen with the focus and the keys held for it, the pointer on a screen (its name, x and y on its
|
||||
/// picture, whether it's down) and the wheel's turns there (`Wheel:Y DY`).
|
||||
#[derive(Default, Clone, Debug, PartialEq)]
|
||||
pub struct Routed {
|
||||
pub focus: Option<String>,
|
||||
pub keys: Vec<String>,
|
||||
pub pointer: Option<(String, f64, f64, bool)>,
|
||||
pub wheel: Vec<String>,
|
||||
}
|
||||
|
||||
impl Routed {
|
||||
/// App screen `name`'s input: the pointer when it's on it (with the wheel turned there), the keys while it has the
|
||||
/// focus (a DOM key's name; the live wire's marked keys, "Mouse:Right" or "Pad0:South", aren't keys to it).
|
||||
pub fn input_of(&self, name: &str) -> Input {
|
||||
let on = self.pointer.as_ref().filter(|p| p.0 == name);
|
||||
let focused = self.focus.as_deref() == Some(name);
|
||||
Input {
|
||||
pointer: on.map(|p| (p.1, p.2, p.3)),
|
||||
keys: self.keys.iter().filter(|k| focused && (k.chars().count() == 1 || !k.contains(':'))).cloned().collect(),
|
||||
wheel: self.wheel.iter().filter(|_| on.is_some()).filter_map(|w| w.strip_prefix("Wheel:Y ")?.trim().parse().ok()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// As the input log keeps it (`apps`); None when nothing reached an app screen.
|
||||
pub fn logged(&self) -> Option<serde_json::Value> {
|
||||
let any = self.focus.is_some() || self.pointer.is_some() || !self.wheel.is_empty();
|
||||
any.then(|| serde_json::json!({ "focus": self.focus, "keys": self.keys, "pointer": self.pointer.as_ref().map(|p| serde_json::json!([p.0, p.1, p.2, p.3])), "wheel": self.wheel }))
|
||||
}
|
||||
|
||||
/// From a log's entry (`logged`'s); nothing reached them when there's none.
|
||||
pub fn from_log(v: Option<&serde_json::Value>) -> Routed {
|
||||
let Some(v) = v else { return Routed::default() };
|
||||
let texts = |k: &str| v[k].as_array().into_iter().flatten().filter_map(|s| s.as_str().map(String::from)).collect();
|
||||
let p = v["pointer"].as_array();
|
||||
let pointer = p.and_then(|p| Some((p.first()?.as_str()?.to_string(), p.get(1)?.as_f64()?, p.get(2)?.as_f64()?, p.get(3)?.as_bool()?)));
|
||||
Routed { focus: v["focus"].as_str().map(String::from), keys: texts("keys"), pointer, wheel: texts("wheel") }
|
||||
}
|
||||
}
|
||||
|
||||
/// Set for the one update a step runs the page's JS in (the draw's later updates, while faces and images load, only
|
||||
/// paint).
|
||||
#[derive(Resource, Default)]
|
||||
struct StepNow(bool);
|
||||
|
||||
fn step_once(world: &mut World) {
|
||||
if std::mem::take(&mut world.resource_mut::<StepNow>().0) {
|
||||
host::step(world);
|
||||
}
|
||||
}
|
||||
|
||||
/// An app screen's document, open.
|
||||
pub struct AppScreen {
|
||||
page: BlitzPage,
|
||||
root: Entity,
|
||||
/// the module, as the composition names it
|
||||
pub module: String,
|
||||
pub size: (u32, u32),
|
||||
window: WindowInput,
|
||||
was: Input,
|
||||
stepped: Option<i64>,
|
||||
}
|
||||
|
||||
/// Frame `f`'s time in ms at `fps`.
|
||||
fn ms_at(f: i64, fps: f64) -> f64 {
|
||||
f as f64 * 1000.0 / fps.max(1.0)
|
||||
}
|
||||
|
||||
impl AppScreen {
|
||||
/// `module` (a path from `dir`, the composition's folder) opened `w` x `h` at frame `f` of `fps`: its script (see
|
||||
/// [`code_of`]) mounted on a Blitz page on the device `render` makes (None: Bevy's own), in raea's bundled faces.
|
||||
pub fn open(dir: &Path, module: &str, w: u32, h: u32, f: i64, fps: f64, render: Option<RenderCreation>) -> R<AppScreen> {
|
||||
let (code, css) = code_of(&dir.join(module))?;
|
||||
let fonts = raea_io_home::home().join("core/fonts");
|
||||
let mut page = BlitzPage::new_on(w.max(1), h.max(1), Some(&fonts), render)?;
|
||||
page.not_dumped();
|
||||
let app = page.app();
|
||||
app.init_resource::<StepNow>();
|
||||
app.add_systems(PreUpdate, step_once.in_set(raea_sys_page::PageSystems::Step));
|
||||
let world = app.world_mut();
|
||||
world.init_resource::<raea_runtime_js::HostCalls>();
|
||||
world.insert_resource(raea_runtime_js::UiFrame(f.max(0) as u64));
|
||||
let root = raea_runtime_jsengine::at_clock(ms_at(f, fps), || host::mount(world, w.max(1), h.max(1), &code, &[], Some(raea_sys_fonts::context(&fonts))))?;
|
||||
// as raea's page host mounts an app (engine/page/host page.rs)
|
||||
host::add_style(world, root, "html, body { height: 100%; }");
|
||||
if !css.trim().is_empty() {
|
||||
host::add_style(world, root, &css);
|
||||
}
|
||||
page.show(root);
|
||||
Ok(AppScreen { page, root, module: module.to_string(), size: (w, h), window: WindowInput::default(), was: Input::default(), stepped: None })
|
||||
}
|
||||
|
||||
/// Stepped to frame `f` of `fps` with `input`: its events, then one update running its JS on the frame's clock, drawn.
|
||||
/// Once a frame: stepped again at the same frame, nothing happens.
|
||||
pub fn step(&mut self, f: i64, fps: f64, input: &Input) {
|
||||
if self.stepped == Some(f) {
|
||||
return;
|
||||
}
|
||||
self.stepped = Some(f);
|
||||
let events = self.events(input);
|
||||
self.was = input.clone();
|
||||
let root = self.root;
|
||||
let page = &mut self.page;
|
||||
raea_runtime_jsengine::at_clock(ms_at(f, fps), || {
|
||||
page.at_frame(f, fps);
|
||||
let world = page.app().world_mut();
|
||||
world.insert_resource(raea_runtime_js::UiFrame(f.max(0) as u64));
|
||||
for (press, ev) in events {
|
||||
// each press a click of its own (a double click needs presses closer than a frame apart)
|
||||
if press {
|
||||
host::set_clicks(world, root, 1);
|
||||
}
|
||||
host::input(world, root, ev);
|
||||
}
|
||||
world.resource_mut::<StepNow>().0 = true;
|
||||
page.draw();
|
||||
});
|
||||
}
|
||||
|
||||
/// Its picture as last drawn: its texture on the page's device (sRGB-encoded premultiplied RGBA, as a nested
|
||||
/// <Screen>'s).
|
||||
pub fn texture(&self) -> Option<bevy::render::render_resource::Texture> {
|
||||
self.page.texture()
|
||||
}
|
||||
|
||||
/// Its picture as last drawn, read back: RGBA rows at its size.
|
||||
pub fn rgba(&mut self) -> R<Vec<u8>> {
|
||||
self.page.frame()
|
||||
}
|
||||
|
||||
/// The events that take the document from the last step's input to `now`'s, as Blitz takes them, each marked
|
||||
/// when it's a press: the pointer's move, press and release (a release, then a leave, when it goes off the
|
||||
/// picture), the wheel, the keys let go and the keys pressed.
|
||||
fn events(&mut self, now: &Input) -> Vec<(bool, UiEvent)> {
|
||||
let window = Entity::PLACEHOLDER;
|
||||
let was = self.was.clone();
|
||||
let mut out = Vec::new();
|
||||
let mut put = |w: &mut WindowInput, ev: WindowEvent, press: bool| {
|
||||
if let Some(e) = w.event(&ev) {
|
||||
out.push((press, e));
|
||||
}
|
||||
};
|
||||
let button = |state| WindowEvent::MouseButtonInput(MouseButtonInput { button: MouseButton::Left, state, window });
|
||||
let held = was.pointer.is_some_and(|p| p.2);
|
||||
match now.pointer {
|
||||
Some((x, y, down)) => {
|
||||
if was.pointer.is_none_or(|(bx, by, _)| bx != x || by != y) {
|
||||
put(&mut self.window, WindowEvent::CursorMoved(CursorMoved { window, position: Vec2::new(x as f32, y as f32), delta: None }), false);
|
||||
}
|
||||
if down && !held {
|
||||
put(&mut self.window, button(ButtonState::Pressed), true);
|
||||
}
|
||||
if !down && held {
|
||||
put(&mut self.window, button(ButtonState::Released), false);
|
||||
}
|
||||
}
|
||||
None if was.pointer.is_some() => {
|
||||
if held {
|
||||
put(&mut self.window, button(ButtonState::Released), false);
|
||||
}
|
||||
put(&mut self.window, WindowEvent::CursorLeft(CursorLeft { window }), false);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
for dy in &now.wheel {
|
||||
// Blitz's wheel is Bevy's way up (raea-runtime-dom gives the DOM -y)
|
||||
put(&mut self.window, WindowEvent::MouseWheel(MouseWheel { unit: MouseScrollUnit::Pixel, x: 0.0, y: -(*dy as f32), window, phase: TouchPhase::Moved }), false);
|
||||
}
|
||||
let mods = mods_of(&now.keys);
|
||||
for k in was.keys.iter().filter(|k| !now.keys.contains(k)) {
|
||||
out.push((false, UiEvent::KeyUp(key_event(k, mods, false))));
|
||||
}
|
||||
for k in now.keys.iter().filter(|k| !was.keys.contains(k)) {
|
||||
out.push((false, UiEvent::KeyDown(key_event(k, mods, true))));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The modifiers the held keys (by their DOM names) make.
|
||||
fn mods_of(keys: &[String]) -> Modifiers {
|
||||
let mut m = Modifiers::empty();
|
||||
for (name, bit) in [("Shift", Modifiers::SHIFT), ("Control", Modifiers::CONTROL), ("Alt", Modifiers::ALT), ("Meta", Modifiers::META)] {
|
||||
if keys.iter().any(|k| k == name) {
|
||||
m |= bit;
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Key `name` (the DOM's: a character, or a named key like "Enter") pressed or let go: a character types itself
|
||||
/// unless Control or Meta is held.
|
||||
fn key_event(name: &str, modifiers: Modifiers, down: bool) -> BlitzKeyEvent {
|
||||
let name = if name == "Space" { " " } else { name };
|
||||
let key = name.parse::<Key>().unwrap_or_else(|_| Key::Character(name.into()));
|
||||
let types = matches!(key, Key::Character(_)) && !modifiers.intersects(Modifiers::CONTROL | Modifiers::META);
|
||||
BlitzKeyEvent {
|
||||
key,
|
||||
code: Code::Unidentified,
|
||||
modifiers,
|
||||
location: Location::Standard,
|
||||
is_auto_repeating: false,
|
||||
is_composing: false,
|
||||
state: if down { KeyState::Pressed } else { KeyState::Released },
|
||||
text: (types && down).then(|| blitz_traits::SmolStr::new(name)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The module's script and CSS: its prebuilt bundle beside it (an exported game's, [`BUNDLED`]), or [`build`] now.
|
||||
pub fn code_of(file: &Path) -> R<(String, String)> {
|
||||
let pre = PathBuf::from(format!("{}{BUNDLED}", file.display()));
|
||||
if pre.is_file() {
|
||||
let js = std::fs::read_to_string(&pre).map_err(|e| format!("{}: {e}", pre.display()))?;
|
||||
let css = std::fs::read_to_string(format!("{}{BUNDLED_CSS}", file.display())).unwrap_or_default();
|
||||
return Ok((js, css));
|
||||
}
|
||||
build(file)
|
||||
}
|
||||
|
||||
/// `file` bundled as an app screen (raea-runtime-bundle-lib's app bundle, its default export given the screen's size):
|
||||
/// its script, and its CSS, what its modules import, then Tailwind's for the classes its folder uses, as `raea app`
|
||||
/// builds an app's (apps/targets web.rs).
|
||||
pub fn build(file: &Path) -> R<(String, String)> {
|
||||
if !file.is_file() {
|
||||
return Err(format!("{}: no such module", file.display()));
|
||||
}
|
||||
let (js, imported) = raea_runtime_bundle::inproc::app::bundle(file, &raea_io_home::home(), raea_runtime_bundle::inproc::app::SCREEN)?;
|
||||
let tw = raea_runtime_bundle::styles::tailwind(file.parent().unwrap_or(Path::new(".")))?;
|
||||
Ok((js, format!("{imported}\n{tw}")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn keys_type_characters_but_not_with_control() {
|
||||
let a = key_event("a", Modifiers::empty(), true);
|
||||
assert_eq!(a.text.as_deref(), Some("a"));
|
||||
assert!(key_event("a", Modifiers::CONTROL, true).text.is_none());
|
||||
assert!(key_event("a", Modifiers::empty(), false).text.is_none());
|
||||
let enter = key_event("Enter", Modifiers::empty(), true);
|
||||
assert!(matches!(enter.key, Key::Named(_)) && enter.text.is_none());
|
||||
assert_eq!(key_event("Space", Modifiers::empty(), true).text.as_deref(), Some(" "));
|
||||
assert_eq!(mods_of(&["Shift".into(), "a".into()]), Modifiers::SHIFT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_logged_input_comes_back_the_same() {
|
||||
let r = Routed { focus: Some("kit".into()), keys: vec!["a".into(), "Pad0:South".into()], pointer: Some(("kit".into(), 12.5, 40.0, true)), wheel: vec!["Wheel:Y 120".into()] };
|
||||
let v = r.logged().unwrap();
|
||||
let back = Routed::from_log(Some(&v));
|
||||
assert_eq!(back, r);
|
||||
assert_eq!(back.input_of("kit"), Input { pointer: Some((12.5, 40.0, true)), keys: vec!["a".into()], wheel: vec![120.0] });
|
||||
assert_eq!(back.input_of("other"), Input::default());
|
||||
assert_eq!(Routed::from_log(None).logged(), None);
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,10 @@
|
||||
use std::path::Path;
|
||||
|
||||
/// The entry every app is mounted by: the DOM installed before the app's module runs, its default export mounted at
|
||||
/// the root (an app that mounts itself with createRoot needs no default export)
|
||||
fn entry(app: &Path) -> String {
|
||||
/// the root with `props` (JS; an app's none) (an app that mounts itself with createRoot needs no default export)
|
||||
fn entry(app: &Path, props: &str) -> String {
|
||||
format!(
|
||||
"import \"@raea/ui/dom-globals\";\nimport {{ createElement }} from \"react\";\nimport {{ mount }} from \"@raea/ui/react\";\nimport * as M from {:?};\nconst App = (M as any).default;\nif (typeof App === \"function\") mount(createElement(App), 0, {{ dom: true }});\n",
|
||||
"import \"@raea/ui/dom-globals\";\nimport {{ createElement }} from \"react\";\nimport {{ mount }} from \"@raea/ui/react\";\nimport * as M from {:?};\nconst App = (M as any).default;\nif (typeof App === \"function\") mount(createElement(App, {props}), 0, {{ dom: true }});\n",
|
||||
app.display().to_string()
|
||||
)
|
||||
}
|
||||
@@ -36,8 +36,17 @@ fn ui(home: &Path) -> serde_json::Value {
|
||||
m.into()
|
||||
}
|
||||
|
||||
/// `app` bundled against `home`: its script and the CSS its modules import
|
||||
pub fn bundle(app: &Path, home: &Path) -> Result<(String, String), String> {
|
||||
/// What an app's default export is given, for `bundle`: nothing, as an app in a window of its own is (it reads the
|
||||
/// window)
|
||||
pub const WINDOW: &str = "null";
|
||||
|
||||
/// What an app screen's module (`<Screen app="kit.tsx">`, docs/blitz-bevy.feature H12) is given: `{width, height}`, the
|
||||
/// screen's size (its document's, so one bundle serves a screen of any size)
|
||||
pub const SCREEN: &str = "{ width: innerWidth, height: innerHeight }";
|
||||
|
||||
/// `app` bundled against `home`, its default export mounted with `props` (WINDOW or SCREEN): its script and the CSS its
|
||||
/// modules import
|
||||
pub fn bundle(app: &Path, home: &Path, props: &str) -> Result<(String, String), String> {
|
||||
// canonical, and on Windows without canonicalize()'s verbatim \\?\ prefix: Rolldown can't resolve an entry that
|
||||
// imports a path written with it (T1f: the Windows release check, 11-07)
|
||||
let app = raea_io_home::plain(app.canonicalize().map_err(|e| format!("{}: {e}", app.display()))?);
|
||||
@@ -49,7 +58,7 @@ pub fn bundle(app: &Path, home: &Path) -> Result<(String, String), String> {
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
std::fs::create_dir_all(&work).map_err(|e| format!("{}: {e}", work.display()))?;
|
||||
let entry_file = work.join("entry.tsx");
|
||||
let wrote = std::fs::write(&entry_file, entry(&app)).and_then(|_| std::fs::write(work.join("tsconfig.json"), tsconfig(home)));
|
||||
let wrote = std::fs::write(&entry_file, entry(&app, props)).and_then(|_| std::fs::write(work.join("tsconfig.json"), tsconfig(home)));
|
||||
let r = wrote.map_err(|e| e.to_string()).and_then(|_| {
|
||||
let opts = serde_json::json!({
|
||||
"script": {"js": home.join("sdk/react/js"), "motion": home.join("sdk/raea/src"), "shell": home.join("sdk/shell/src/index.ts"), "aliases": ui(home), "stubs": []},
|
||||
|
||||
@@ -25,28 +25,6 @@ fn spec(p: &Path) -> String {
|
||||
dunce::simplified(p).display().to_string()
|
||||
}
|
||||
|
||||
/// A react-dom page's bundle (a surface): the module at `src` (its default
|
||||
/// export a React component) rendered by react-dom into #root with the page's width and height, again on each resize,
|
||||
/// bundled with its packages (the project's node_modules, raea-io-npm's) into `out`. The bundle's text. A legacy-app panel's
|
||||
/// and a `<Screen app>`'s.
|
||||
pub fn bundle_surface(src: &Path, out: &Path) -> R<String> {
|
||||
let entry = format!(
|
||||
r#"// raea writes this (motion.rs bundle_surface): {src} on react-dom, at the surface's size, again on each resize.
|
||||
import {{ createElement }} from "react";
|
||||
import {{ createRoot }} from "react-dom/client";
|
||||
import Page from {src:?};
|
||||
|
||||
const root = createRoot(document.getElementById("root")!);
|
||||
const draw = () => root.render(createElement(Page as any, {{ width: innerWidth, height: innerHeight }}));
|
||||
addEventListener("resize", draw);
|
||||
draw();
|
||||
"#,
|
||||
src = spec(src)
|
||||
);
|
||||
bundle_entry(&entry, out, &[])?;
|
||||
std::fs::read_to_string(out).map_err(|e| format!("{}: {e}", out.display()))
|
||||
}
|
||||
|
||||
/// `entry` (TypeScript source) bundled into `out` by raea-bundle's library (engine/bundle/src/script.rs's resolution); `extra`
|
||||
/// are bundle.ts's flags (--define K=V, --alias SPEC=PATH, --node-stub a,b).
|
||||
pub fn bundle_entry(entry: &str, out: &Path, extra: &[&str]) -> R<()> {
|
||||
|
||||
@@ -119,6 +119,10 @@ pub fn sync(doc: &mut BaseDocument, nodes: &Nodes, medias: &mut Medias, out: &mu
|
||||
{
|
||||
m.seeking = Some(t);
|
||||
st.ask(Cmd::Seek(t));
|
||||
// the frames decoded ahead for where it was are never shown: a seek while playing went on showing up
|
||||
// to a quarter second of them (and telling their times) until its own frame came, a stretch played
|
||||
// again after a seek back (11-16)
|
||||
m.ahead.clear();
|
||||
}
|
||||
m.seek = seek;
|
||||
}
|
||||
@@ -142,6 +146,8 @@ pub fn sync(doc: &mut BaseDocument, nodes: &Nodes, medias: &mut Medias, out: &mu
|
||||
out.push(if m.video { json!({"id": id, "type": "loadedmetadata", "w": w, "h": h, "duration": duration}) } else { json!({"id": id, "type": "loadedmetadata", "duration": duration}) });
|
||||
}
|
||||
Msg::Fail(err) => {
|
||||
// a seek that failed lands nowhere: the frames after it aren't held back for it
|
||||
m.seeking = None;
|
||||
bevy::log::warn!("raea-page: media: {err}");
|
||||
out.push(json!({"id": id, "type": "error", "message": err}));
|
||||
}
|
||||
@@ -166,9 +172,10 @@ pub fn sync(doc: &mut BaseDocument, nodes: &Nodes, medias: &mut Medias, out: &mu
|
||||
told(m, id, t, out);
|
||||
}
|
||||
}
|
||||
// a playing video's frame, for later; one that comes after a pause is for nothing
|
||||
// a playing video's frame, for later; one that comes after a pause is for nothing, and so is one decoded
|
||||
// before a seek still on its way (the decoder answers a seek with its frame first, then plays on from it)
|
||||
Msg::Due(t, f, due, halves) => {
|
||||
if m.playing {
|
||||
if keep_due(m.playing, m.seeking) {
|
||||
m.ahead.push_back((t, (f.width, f.height, f.rgba), due, halves));
|
||||
}
|
||||
}
|
||||
@@ -274,6 +281,12 @@ fn due_by<T>(ahead: &mut VecDeque<(f64, T, Instant, Halvings)>, reach: Instant)
|
||||
(due, passed)
|
||||
}
|
||||
|
||||
/// Whether a playing video's frame decoded ahead (`Msg::Due`) waits to be shown: not after a pause, and not while a
|
||||
/// seek is on its way, when it was decoded for where the video was before the seek.
|
||||
fn keep_due(playing: bool, seeking: Option<f64>) -> bool {
|
||||
playing && seeking.is_none()
|
||||
}
|
||||
|
||||
/// A playing element's time: each as `time` (its currentTime), and a `timeupdate` four times a second.
|
||||
fn told(m: &mut Media, id: u64, t: f64, out: &mut Vec<Value>) {
|
||||
out.push(json!({"id": id, "type": "time", "time": t}));
|
||||
@@ -322,6 +335,15 @@ fn set_image(doc: &mut BaseDocument, n: blitz_dom::NodeId, w: u32, h: u32, rgba:
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A frame decoded ahead waits only while playing and no seek is on its way: one that comes between a seek and
|
||||
/// its answer was decoded for where the video was, and shown it played that stretch again (11-16).
|
||||
#[test]
|
||||
fn frames_decoded_before_a_seek_are_not_kept() {
|
||||
assert!(keep_due(true, None));
|
||||
assert!(!keep_due(true, Some(2.0)));
|
||||
assert!(!keep_due(false, None));
|
||||
}
|
||||
|
||||
/// At a sync the frame shown is the latest one due by then; earlier ones due are passed over, later ones wait.
|
||||
#[test]
|
||||
fn the_frame_due_is_the_latest_whose_moment_has_come() {
|
||||
|
||||
@@ -71,6 +71,8 @@ pub struct Root {
|
||||
frames_seen: std::collections::HashSet<(NodeId, String)>,
|
||||
/// a context call committed the JS's writes before the drain did (PageSync::commit)
|
||||
synced: bool,
|
||||
/// its JS engine's free pages given back, and with RAEA_INSPECT its heap logged (raea_runtime_jsengine::Upkeep)
|
||||
upkeep: raea_runtime_js::js::Upkeep,
|
||||
}
|
||||
|
||||
/// What a root's JS calls lend its context host calls (raea_runtime_js::calls::on_sync_ctx: style.computed's resolve, a
|
||||
|
||||
@@ -107,7 +107,7 @@ pub(crate) fn root_on(world: &mut World, page: Entity, nodes: Nodes, w: u32, h:
|
||||
}
|
||||
scripts.extend(preamble.iter().enumerate().map(|(i, s)| (s.clone(), format!("preamble{i}.js"))));
|
||||
scripts.push((code.to_string(), "bundle.js".into()));
|
||||
let mut root = Root { page, js, out, nodes, queue: Vec::new(), ticking: false, clicks: 1, capture: None, hover_frozen: None, medias: Default::default(), views: Default::default(), fonts_wait: None, bevy_ui: false, placed_videos: false, frame, frames_seen: Default::default(), synced: false };
|
||||
let mut root = Root { page, js, out, nodes, queue: Vec::new(), ticking: false, clicks: 1, capture: None, hover_frozen: None, medias: Default::default(), views: Default::default(), fonts_wait: None, bevy_ui: false, placed_videos: false, frame, frames_seen: Default::default(), synced: false, upkeep: raea_runtime_js::js::Upkeep::from_env() };
|
||||
for (src, name) in &scripts {
|
||||
root.js(world, |js| js.eval(src, name)).map_err(|e| format!("{name}: {e}"))?;
|
||||
}
|
||||
|
||||
@@ -56,6 +56,8 @@ pub fn step(world: &mut World) {
|
||||
committed |= drain(world, r);
|
||||
}
|
||||
r.js(world, |js| js.idle());
|
||||
// (no host calls in it: a collection, the engine's pages, its heap's numbers)
|
||||
r.upkeep.tick(r.js.as_mut());
|
||||
if let Some(f) = &r.frame {
|
||||
swap_frame(world, r.page, f);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ pub use raea_render::{dir_of, inserted_of, save_png};
|
||||
pub mod html;
|
||||
mod sound;
|
||||
pub use sound::*;
|
||||
mod progress;
|
||||
mod render;
|
||||
pub use render::*;
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//! What a render is doing while it runs, for whatever shows it: the raea app's chat draws a meter from it (the
|
||||
//! developer, 11-16: "in the chat ui having something that if its rendering we can see a progress meter"). One small
|
||||
//! JSON file per render, `<renders>/<pid>-<n>.json`:
|
||||
//!
|
||||
//! `{"pid", "out", "cwd", "frames", "done", "started", "updated"}` (times in ms since the epoch)
|
||||
//!
|
||||
//! It's written when the render starts, as its frames finish (at most four times a second, and at the last frame),
|
||||
//! and taken away when the render ends, however it ends; one left by a process that died is a reader's to pass over
|
||||
//! (its pid is gone). `<renders>` is $RAEA_RENDERS, else ~/.raea/renders; `RAEA_RENDERS=off` writes none.
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
static SEQ: AtomicUsize = AtomicUsize::new(0);
|
||||
const EVERY: Duration = Duration::from_millis(250);
|
||||
|
||||
/// A render's progress, kept on disk while it lives.
|
||||
pub struct Progress {
|
||||
file: Option<PathBuf>,
|
||||
out: String,
|
||||
cwd: String,
|
||||
frames: usize,
|
||||
done: usize,
|
||||
started: u64,
|
||||
last: Option<Instant>,
|
||||
}
|
||||
|
||||
fn dir() -> Option<PathBuf> {
|
||||
let named = std::env::var_os("RAEA_RENDERS").filter(|v| !v.is_empty());
|
||||
if named.as_deref() == Some(std::ffi::OsStr::new("off")) {
|
||||
return None;
|
||||
}
|
||||
// unset: ~/.raea/renders, the home being USERPROFILE on Windows, which has no HOME
|
||||
match (named, std::env::var_os("HOME").or(std::env::var_os("USERPROFILE"))) {
|
||||
(Some(d), _) => Some(PathBuf::from(d)),
|
||||
(None, Some(home)) => Some(Path::new(&home).join(".raea/renders")),
|
||||
(None, None) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn now_ms() -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
/// A render of `frames` frames to `out`, starting.
|
||||
pub fn start(out: &Path, frames: usize) -> Self {
|
||||
Self::start_in(dir(), out, frames)
|
||||
}
|
||||
|
||||
fn start_in(dir: Option<PathBuf>, out: &Path, frames: usize) -> Self {
|
||||
let file = dir.and_then(|d| std::fs::create_dir_all(&d).ok().map(|_| d.join(format!("{}-{}.json", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed)))));
|
||||
let out = std::path::absolute(out).unwrap_or_else(|_| out.to_path_buf()).display().to_string();
|
||||
let cwd = std::env::current_dir().map(|d| d.display().to_string()).unwrap_or_default();
|
||||
let mut p = Progress { file, out, cwd, frames, done: 0, started: now_ms(), last: None };
|
||||
p.write();
|
||||
p
|
||||
}
|
||||
|
||||
/// One more frame done.
|
||||
pub fn frame(&mut self) {
|
||||
self.done += 1;
|
||||
if self.done >= self.frames || self.last.is_none_or(|t| t.elapsed() >= EVERY) {
|
||||
self.write();
|
||||
}
|
||||
}
|
||||
|
||||
fn write(&mut self) {
|
||||
let Some(f) = &self.file else { return };
|
||||
self.last = Some(Instant::now());
|
||||
let body = serde_json::json!({"pid": std::process::id(), "out": self.out, "cwd": self.cwd, "frames": self.frames, "done": self.done, "started": self.started, "updated": now_ms()});
|
||||
// written whole beside it, then put in its place: a reader never sees half of one
|
||||
let part = f.with_extension("json.part");
|
||||
if std::fs::write(&part, body.to_string()).is_ok() {
|
||||
let _ = std::fs::rename(&part, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Progress {
|
||||
fn drop(&mut self) {
|
||||
if let Some(f) = &self.file {
|
||||
let _ = std::fs::remove_file(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn written_as_frames_finish_and_gone_when_the_render_ends() {
|
||||
let d = std::env::temp_dir().join(format!("raea-renders-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
let read = || -> serde_json::Value {
|
||||
let f = std::fs::read_dir(&d).unwrap().filter_map(|e| e.ok()).map(|e| e.path()).find(|p| p.extension().is_some_and(|x| x == "json")).unwrap();
|
||||
serde_json::from_str(&std::fs::read_to_string(f).unwrap()).unwrap()
|
||||
};
|
||||
let mut p = Progress::start_in(Some(d.clone()), Path::new("film.mp4"), 3);
|
||||
let v = read();
|
||||
assert_eq!((v["frames"].as_u64(), v["done"].as_u64(), v["pid"].as_u64()), (Some(3), Some(0), Some(std::process::id() as u64)));
|
||||
assert!(v["out"].as_str().unwrap().ends_with("film.mp4") && Path::new(v["out"].as_str().unwrap()).is_absolute());
|
||||
p.frame();
|
||||
p.frame();
|
||||
p.frame();
|
||||
// the last frame is always written, however soon after the one before
|
||||
assert_eq!(read()["done"].as_u64(), Some(3));
|
||||
drop(p);
|
||||
assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0);
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
@@ -103,8 +103,11 @@ pub fn render_fed(
|
||||
}
|
||||
let t_frames = std::time::Instant::now();
|
||||
let mut n = 0;
|
||||
// how far it's got, for whatever shows it (progress.rs)
|
||||
let mut meter = crate::progress::Progress::start(out, list.len());
|
||||
let dt = v.render_nv12_fed(&list, feed, |f, px| {
|
||||
n += 1;
|
||||
meter.frame();
|
||||
direct_sink(tx.as_ref(), &mut lines, f, px)
|
||||
});
|
||||
drop(tx);
|
||||
@@ -197,7 +200,9 @@ pub fn render_with(prog: &Program, rows: &[Tup], dir: &Path, out: &Path, ro: &Re
|
||||
}));
|
||||
}
|
||||
let t_frames = std::time::Instant::now();
|
||||
let mut meter = crate::progress::Progress::start(out, list.len());
|
||||
let tm = v.render_nv12(&list, |f, px| {
|
||||
meter.frame();
|
||||
if let Some(tx) = tx.as_ref() {
|
||||
return tx.send(px).map_err(|_| "the encoder stopped".to_string());
|
||||
}
|
||||
@@ -269,8 +274,10 @@ pub fn render_with(prog: &Program, rows: &[Tup], dir: &Path, out: &Path, ro: &Re
|
||||
}
|
||||
let t_frames = std::time::Instant::now();
|
||||
let mut n = 0;
|
||||
let mut meter = crate::progress::Progress::start(out, list.len());
|
||||
let dt = v
|
||||
.render_nv12(&list, |f, px| {
|
||||
meter.frame();
|
||||
match pngs {
|
||||
true => save_png(&if still { out.to_path_buf() } else { out.join(format!("frame-{f:05}.png")) }, &straight(px), w, h)?,
|
||||
false => direct_sink(tx.as_ref(), &mut lines, f, px)?,
|
||||
|
||||
@@ -35,6 +35,10 @@ pub fn render(args: &[String]) -> R<String> {
|
||||
// the edit's words.json and perception.json beside it, as play loads them (a render without the flags lost the
|
||||
// captions its words drive; the corpus found 10 edits so); a flag still wins
|
||||
let mut o = comp_opts(args)?;
|
||||
// an input log's `apps`, what reached the app screens in the play it came from, given them again frame by frame
|
||||
// (docs/blitz-bevy.feature H12): the render draws what was played
|
||||
let apps: std::collections::BTreeMap<i64, serde_json::Value> = o.input.as_ref().and_then(|v| v.as_object()).into_iter().flatten().filter_map(|(f, v)| Some((f.parse().ok()?, v.get("apps")?.clone()))).collect();
|
||||
*raea_runtime_page::screen::APP_LOG.lock().unwrap() = (!apps.is_empty()).then_some(apps);
|
||||
for (slot, file) in [(&mut o.words, "words.json"), (&mut o.perception, "perception.json")] {
|
||||
if slot.is_none() && dir.join(file).exists() {
|
||||
let v = json_file(&dir.join(file).display().to_string())?;
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
pub use raea_runtime_jsengine::{Arg, Engine, JsEngine, now_ms};
|
||||
pub use raea_runtime_jsengine::{Arg, Engine, JsEngine, Upkeep, now_ms};
|
||||
use raea_runtime_jsengine::{Native, Ret, arg, clock};
|
||||
|
||||
/// What a root's JS handed the host since it was last drained.
|
||||
|
||||
+14
-130
@@ -147,13 +147,17 @@ impl<'a> Player<'a> {
|
||||
}
|
||||
}
|
||||
if let Some(t) = seek {
|
||||
// the frame at exactly the time asked (the element's `seeked`), and a playing clock goes on from it
|
||||
if self.clock.is_some() {
|
||||
self.go(t);
|
||||
}
|
||||
// the frame at exactly the time asked (the element's `seeked`), and a playing clock goes on from it once
|
||||
// it is sent: started before, the seek's decode (from the keyframe before it: 30 to 300 ms at 4K) ran
|
||||
// on the clock, and the frames after it were skipped to catch up (11-16)
|
||||
if !self.frame(t, &tx) {
|
||||
return self.stop();
|
||||
}
|
||||
if self.clock.is_some() {
|
||||
self.go(t);
|
||||
// the frame showing at t has gone: the next one is the first to decode
|
||||
self.cursor = Self::index_at(t, self.fps) + 1;
|
||||
}
|
||||
}
|
||||
if let Some((at, looping)) = play {
|
||||
self.looping = looping;
|
||||
@@ -186,6 +190,11 @@ impl<'a> Player<'a> {
|
||||
Duration::from_secs_f64(wait)
|
||||
}
|
||||
|
||||
/// The index (at fps) of the frame showing at `t`: one on fps's grid is its own, not the one before for a rounding.
|
||||
fn index_at(t: f64, fps: f64) -> i64 {
|
||||
(t * fps + 1e-6).floor() as i64
|
||||
}
|
||||
|
||||
/// The cursor's frame's time on the clock.
|
||||
fn cursor_time(&self) -> f64 {
|
||||
self.cursor as f64 / self.fps + self.lap
|
||||
@@ -335,129 +344,4 @@ impl<'a> Player<'a> {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::media_html::stream::{self, Cmd, Msg, Stream};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The next news within `within`, polled as the page host polls it (each frame).
|
||||
fn next(st: &Stream, within: Duration) -> Option<Msg> {
|
||||
let t = Instant::now();
|
||||
while t.elapsed() < within {
|
||||
if let Some(m) = st.next() {
|
||||
return Some(m);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A second of 30 fps picture and a tone (ffmpeg's test sources), or None without ffmpeg.
|
||||
fn clip() -> Option<std::path::PathBuf> {
|
||||
let p = std::env::temp_dir().join(format!("raea-media-play-{}.mp4", std::process::id()));
|
||||
let ok = std::process::Command::new("ffmpeg")
|
||||
.args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=30", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000", "-t", "1", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest"])
|
||||
.arg(&p)
|
||||
.status()
|
||||
.is_ok_and(|s| s.success());
|
||||
ok.then_some(p)
|
||||
}
|
||||
|
||||
/// A halving's pixel is the mean of the four it stands for; an odd last row or column is left out; a picture a
|
||||
/// pixel wide has none; and a frame is sent whole when none are asked for.
|
||||
#[test]
|
||||
fn halvings_are_means_of_four() {
|
||||
use crate::media_html::stream::{halvings, sent};
|
||||
let px: Vec<u8> = (0..5 * 3 * 4).map(|i| (i * 3) as u8).collect();
|
||||
let h = halvings(5, 3, &px, 3);
|
||||
assert_eq!(h.iter().map(|(w, h, p)| (*w, *h, p.len())).collect::<Vec<_>>(), vec![(2, 1, 8)]);
|
||||
let mean = |x: usize, c: usize| ((px[x * 4 + c] as u16 + px[(x + 1) * 4 + c] as u16 + px[(5 + x) * 4 + c] as u16 + px[(5 + x + 1) * 4 + c] as u16 + 2) / 4) as u8;
|
||||
assert_eq!(h[0].2, vec![mean(0, 0), mean(0, 1), mean(0, 2), mean(0, 3), mean(2, 0), mean(2, 1), mean(2, 2), mean(2, 3)]);
|
||||
let f = raea_io_media::Frame { pts: 0.0, width: 5, height: 3, rgba: px.clone() };
|
||||
let (whole, none) = sent(f.clone(), 0);
|
||||
assert!(whole.rgba == px && none.is_empty());
|
||||
let (size, one) = sent(f, 1);
|
||||
assert!(size.rgba.is_empty() && (size.width, size.height) == (5, 3) && one == vec![h[0].clone()]);
|
||||
}
|
||||
|
||||
/// Played on the wall's clock (RAEA_AUDIO_MUTE=1: no device), a video's frames come as they fall due and it ends
|
||||
/// at its end; a seek answers with the frame at exactly its time; looping, it goes round; paused, it stops.
|
||||
#[test]
|
||||
fn plays_seeks_loops_and_pauses() {
|
||||
// SAFETY: set before any stream reads it, and nothing else in this test binary reads it concurrently
|
||||
unsafe { std::env::set_var("RAEA_AUDIO_MUTE", "1") };
|
||||
let Some(path) = clip() else { return eprintln!("no ffmpeg: skipped") };
|
||||
let mut st = stream::open(path.to_str().unwrap(), true).expect("a stream");
|
||||
assert!(matches!(next(&st, Duration::from_secs(10)), Some(Msg::Meta { w: 160, h: 90, .. })));
|
||||
assert!(matches!(next(&st, Duration::from_secs(5)), Some(Msg::Frame(t, ..)) if t == 0.0));
|
||||
|
||||
let began = Instant::now();
|
||||
st.ask(Cmd::Play { at: 0.0, looping: false });
|
||||
assert!(matches!(next(&st, Duration::from_secs(1)), Some(Msg::Playing(t)) if t == 0.0));
|
||||
let (mut frames, mut last, mut ended) = (0, -1.0, None);
|
||||
while let Some(m) = next(&st, Duration::from_secs(3)) {
|
||||
match m {
|
||||
Msg::Due(t, f, due, _) => {
|
||||
assert!(t > last, "frames in order: {t} after {last}");
|
||||
assert_eq!((f.width, f.height), (160, 90));
|
||||
// each is due when its time comes on the clock (the wall's, here), sent before then
|
||||
let on_clock = due.duration_since(began).as_secs_f64();
|
||||
assert!((on_clock - t).abs() < 0.06, "the frame at {t} is due at {on_clock}");
|
||||
(frames, last) = (frames + 1, t);
|
||||
}
|
||||
Msg::Ended(t) => {
|
||||
ended = Some((t, began.elapsed().as_secs_f64()));
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (end, took) = ended.expect("it ended");
|
||||
assert!((end - 1.0).abs() < 0.05, "ended at its duration: {end}");
|
||||
assert!((0.85..1.4).contains(&took), "a second's clip took {took} s");
|
||||
assert!(frames >= 25, "{frames} frames of 30");
|
||||
|
||||
st.ask(Cmd::Seek(0.5));
|
||||
assert!(matches!(next(&st, Duration::from_secs(2)), Some(Msg::Frame(t, ..)) if t == 0.5));
|
||||
|
||||
let looped = Instant::now();
|
||||
st.ask(Cmd::Play { at: 0.5, looping: true });
|
||||
let (mut wrapped, mut last, mut laps, until) = (false, 0.5, 0.0, Instant::now() + Duration::from_millis(2300));
|
||||
while Instant::now() < until {
|
||||
match next(&st, Duration::from_millis(200)) {
|
||||
Some(Msg::Due(t, _, due, _)) => {
|
||||
// the first frame of the next lap is sent before the last frame of this one has gone
|
||||
if t < last {
|
||||
wrapped = true;
|
||||
laps += 1.0;
|
||||
assert!(due > Instant::now(), "the loop's first frame came after it was due");
|
||||
}
|
||||
// round the loop a frame is still due when the clock is at its time: half a second of play
|
||||
// to the end, then a second a lap
|
||||
let on_clock = due.duration_since(looped).as_secs_f64();
|
||||
assert!((on_clock - (t - 0.5 + laps)).abs() < 0.06, "lap {laps}: the frame at {t} is due {on_clock} s after play");
|
||||
last = t;
|
||||
}
|
||||
Some(Msg::Ended(_)) => panic!("a looping source doesn't end"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert!(wrapped, "looping went round");
|
||||
|
||||
st.ask(Cmd::Pause);
|
||||
// paused, asked for two halvings: the picture showing comes again as its size and its second halving
|
||||
while next(&st, Duration::from_millis(300)).is_some() {}
|
||||
st.ask(Cmd::Halvings(2));
|
||||
match next(&st, Duration::from_secs(2)) {
|
||||
Some(Msg::Frame(_, f, halves)) => {
|
||||
assert_eq!((f.width, f.height), (160, 90));
|
||||
assert!(f.rgba.is_empty(), "the frame's own pixels stay behind");
|
||||
assert_eq!(halves.iter().map(|(w, h, px)| (*w, *h, px.len())).collect::<Vec<_>>(), vec![(40, 22, 40 * 22 * 4)]);
|
||||
}
|
||||
_ => panic!("no frame with its halvings"),
|
||||
}
|
||||
// what was on its way comes; then nothing more
|
||||
while next(&st, Duration::from_millis(300)).is_some() {}
|
||||
assert!(next(&st, Duration::from_millis(300)).is_none(), "frames after pausing");
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
@@ -0,0 +1,189 @@
|
||||
//! The decoder's tests (media_play.rs): play, seek, loop and pause; a seek while playing; halvings.
|
||||
|
||||
use crate::media_html::stream::{self, Cmd, Msg, Stream};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The next news within `within`, polled as the page host polls it (each frame).
|
||||
fn next(st: &Stream, within: Duration) -> Option<Msg> {
|
||||
let t = Instant::now();
|
||||
while t.elapsed() < within {
|
||||
if let Some(m) = st.next() {
|
||||
return Some(m);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A second of 30 fps picture and a tone (ffmpeg's test sources), or None without ffmpeg.
|
||||
fn clip() -> Option<std::path::PathBuf> {
|
||||
clip_of("1", "one")
|
||||
}
|
||||
|
||||
/// `seconds` of 30 fps picture and a tone, named `name` among this run's clips, or None without ffmpeg.
|
||||
fn clip_of(seconds: &str, name: &str) -> Option<std::path::PathBuf> {
|
||||
let p = std::env::temp_dir().join(format!("raea-media-play-{}-{name}.mp4", std::process::id()));
|
||||
let ok = std::process::Command::new("ffmpeg")
|
||||
.args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=30", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000", "-t", seconds, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest"])
|
||||
.arg(&p)
|
||||
.status()
|
||||
.is_ok_and(|s| s.success());
|
||||
ok.then_some(p)
|
||||
}
|
||||
|
||||
/// A seek while playing (raea feed's timeline, 11-16: a stretch played twice): the decoder answers with the frame
|
||||
/// at the time asked before any other news from its new place, nothing it decoded for the old place comes after
|
||||
/// that frame, and play goes on from the frame after it, due on a clock started once it was sent.
|
||||
#[test]
|
||||
fn a_seek_while_playing_answers_first_and_plays_on_from_there() {
|
||||
// SAFETY: set before any stream reads it, and nothing else in this test binary reads it concurrently
|
||||
unsafe { std::env::set_var("RAEA_AUDIO_MUTE", "1") };
|
||||
let Some(path) = clip_of("3", "seek") else { return eprintln!("no ffmpeg: skipped") };
|
||||
let mut st = stream::open(path.to_str().unwrap(), true).expect("a stream");
|
||||
assert!(matches!(next(&st, Duration::from_secs(10)), Some(Msg::Meta { .. })));
|
||||
assert!(matches!(next(&st, Duration::from_secs(5)), Some(Msg::Frame(t, ..)) if t == 0.0));
|
||||
st.ask(Cmd::Play { at: 0.0, looping: false });
|
||||
// play until frames from past a second are coming
|
||||
let until = Instant::now() + Duration::from_secs(3);
|
||||
let mut furthest = 0.0;
|
||||
while Instant::now() < until && furthest < 1.2 {
|
||||
if let Some(Msg::Due(t, ..)) = next(&st, Duration::from_millis(200)) {
|
||||
furthest = f64::max(furthest, t);
|
||||
}
|
||||
}
|
||||
assert!(furthest >= 1.2, "played to {furthest}");
|
||||
// back to 0.5 while playing: what was on its way may come first, then the seek's frame
|
||||
let asked = Instant::now();
|
||||
st.ask(Cmd::Seek(0.5));
|
||||
let mut answered = None;
|
||||
let (mut after, mut last) = (Vec::new(), 0.5);
|
||||
let until = Instant::now() + Duration::from_secs(2);
|
||||
while Instant::now() < until && after.len() < 10 {
|
||||
match next(&st, Duration::from_millis(300)) {
|
||||
Some(Msg::Frame(t, ..)) => {
|
||||
assert_eq!(t, 0.5, "the seek's frame");
|
||||
answered = Some(Instant::now());
|
||||
}
|
||||
Some(Msg::Due(t, _, due, _)) if answered.is_some() => {
|
||||
assert!(t > last, "after the seek, frames in order from it: {t} after {last}");
|
||||
last = t;
|
||||
after.push((t, due));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let answered = answered.expect("the seek answered with its frame");
|
||||
assert!(answered.duration_since(asked) < Duration::from_secs(1));
|
||||
// the frame after the seek's (index 15 at 30 fps is 0.5 itself): the seek's frame isn't sent twice
|
||||
let first = after.first().expect("play went on after the seek").0;
|
||||
assert!((first - 16.0 / 30.0).abs() < 1e-9, "the first frame after the seek is at {first}");
|
||||
// each due a frame on from the seek's moment, on a clock started when the seek's frame went (not before its
|
||||
// decode), so none had to be skipped: ten frames in a row
|
||||
for (i, (t, _)) in after.iter().enumerate() {
|
||||
assert!((t - (16 + i) as f64 / 30.0).abs() < 1e-9, "frame {i} after the seek is at {t}");
|
||||
}
|
||||
let (t1, due1) = after[0];
|
||||
let on_clock = due1.saturating_duration_since(answered).as_secs_f64();
|
||||
assert!(on_clock <= t1 - 0.5 + 0.03, "the first frame after the seek is due {on_clock} s after its answer");
|
||||
st.ask(Cmd::Pause);
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
|
||||
/// A halving's pixel is the mean of the four it stands for; an odd last row or column is left out; a picture a
|
||||
/// pixel wide has none; and a frame is sent whole when none are asked for.
|
||||
#[test]
|
||||
fn halvings_are_means_of_four() {
|
||||
use crate::media_html::stream::{halvings, sent};
|
||||
let px: Vec<u8> = (0..5 * 3 * 4).map(|i| (i * 3) as u8).collect();
|
||||
let h = halvings(5, 3, &px, 3);
|
||||
assert_eq!(h.iter().map(|(w, h, p)| (*w, *h, p.len())).collect::<Vec<_>>(), vec![(2, 1, 8)]);
|
||||
let mean = |x: usize, c: usize| ((px[x * 4 + c] as u16 + px[(x + 1) * 4 + c] as u16 + px[(5 + x) * 4 + c] as u16 + px[(5 + x + 1) * 4 + c] as u16 + 2) / 4) as u8;
|
||||
assert_eq!(h[0].2, vec![mean(0, 0), mean(0, 1), mean(0, 2), mean(0, 3), mean(2, 0), mean(2, 1), mean(2, 2), mean(2, 3)]);
|
||||
let f = raea_io_media::Frame { pts: 0.0, width: 5, height: 3, rgba: px.clone() };
|
||||
let (whole, none) = sent(f.clone(), 0);
|
||||
assert!(whole.rgba == px && none.is_empty());
|
||||
let (size, one) = sent(f, 1);
|
||||
assert!(size.rgba.is_empty() && (size.width, size.height) == (5, 3) && one == vec![h[0].clone()]);
|
||||
}
|
||||
|
||||
/// Played on the wall's clock (RAEA_AUDIO_MUTE=1: no device), a video's frames come as they fall due and it ends
|
||||
/// at its end; a seek answers with the frame at exactly its time; looping, it goes round; paused, it stops.
|
||||
#[test]
|
||||
fn plays_seeks_loops_and_pauses() {
|
||||
// SAFETY: set before any stream reads it, and nothing else in this test binary reads it concurrently
|
||||
unsafe { std::env::set_var("RAEA_AUDIO_MUTE", "1") };
|
||||
let Some(path) = clip() else { return eprintln!("no ffmpeg: skipped") };
|
||||
let mut st = stream::open(path.to_str().unwrap(), true).expect("a stream");
|
||||
assert!(matches!(next(&st, Duration::from_secs(10)), Some(Msg::Meta { w: 160, h: 90, .. })));
|
||||
assert!(matches!(next(&st, Duration::from_secs(5)), Some(Msg::Frame(t, ..)) if t == 0.0));
|
||||
|
||||
let began = Instant::now();
|
||||
st.ask(Cmd::Play { at: 0.0, looping: false });
|
||||
assert!(matches!(next(&st, Duration::from_secs(1)), Some(Msg::Playing(t)) if t == 0.0));
|
||||
let (mut frames, mut last, mut ended) = (0, -1.0, None);
|
||||
while let Some(m) = next(&st, Duration::from_secs(3)) {
|
||||
match m {
|
||||
Msg::Due(t, f, due, _) => {
|
||||
assert!(t > last, "frames in order: {t} after {last}");
|
||||
assert_eq!((f.width, f.height), (160, 90));
|
||||
// each is due when its time comes on the clock (the wall's, here), sent before then
|
||||
let on_clock = due.duration_since(began).as_secs_f64();
|
||||
assert!((on_clock - t).abs() < 0.06, "the frame at {t} is due at {on_clock}");
|
||||
(frames, last) = (frames + 1, t);
|
||||
}
|
||||
Msg::Ended(t) => {
|
||||
ended = Some((t, began.elapsed().as_secs_f64()));
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (end, took) = ended.expect("it ended");
|
||||
assert!((end - 1.0).abs() < 0.05, "ended at its duration: {end}");
|
||||
assert!((0.85..1.4).contains(&took), "a second's clip took {took} s");
|
||||
assert!(frames >= 25, "{frames} frames of 30");
|
||||
|
||||
st.ask(Cmd::Seek(0.5));
|
||||
assert!(matches!(next(&st, Duration::from_secs(2)), Some(Msg::Frame(t, ..)) if t == 0.5));
|
||||
|
||||
let looped = Instant::now();
|
||||
st.ask(Cmd::Play { at: 0.5, looping: true });
|
||||
let (mut wrapped, mut last, mut laps, until) = (false, 0.5, 0.0, Instant::now() + Duration::from_millis(2300));
|
||||
while Instant::now() < until {
|
||||
match next(&st, Duration::from_millis(200)) {
|
||||
Some(Msg::Due(t, _, due, _)) => {
|
||||
// the first frame of the next lap is sent before the last frame of this one has gone
|
||||
if t < last {
|
||||
wrapped = true;
|
||||
laps += 1.0;
|
||||
assert!(due > Instant::now(), "the loop's first frame came after it was due");
|
||||
}
|
||||
// round the loop a frame is still due when the clock is at its time: half a second of play
|
||||
// to the end, then a second a lap
|
||||
let on_clock = due.duration_since(looped).as_secs_f64();
|
||||
assert!((on_clock - (t - 0.5 + laps)).abs() < 0.06, "lap {laps}: the frame at {t} is due {on_clock} s after play");
|
||||
last = t;
|
||||
}
|
||||
Some(Msg::Ended(_)) => panic!("a looping source doesn't end"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert!(wrapped, "looping went round");
|
||||
|
||||
st.ask(Cmd::Pause);
|
||||
// paused, asked for two halvings: the picture showing comes again as its size and its second halving
|
||||
while next(&st, Duration::from_millis(300)).is_some() {}
|
||||
st.ask(Cmd::Halvings(2));
|
||||
match next(&st, Duration::from_secs(2)) {
|
||||
Some(Msg::Frame(_, f, halves)) => {
|
||||
assert_eq!((f.width, f.height), (160, 90));
|
||||
assert!(f.rgba.is_empty(), "the frame's own pixels stay behind");
|
||||
assert_eq!(halves.iter().map(|(w, h, px)| (*w, *h, px.len())).collect::<Vec<_>>(), vec![(40, 22, 40 * 22 * 4)]);
|
||||
}
|
||||
_ => panic!("no frame with its halvings"),
|
||||
}
|
||||
// what was on its way comes; then nothing more
|
||||
while next(&st, Duration::from_millis(300)).is_some() {}
|
||||
assert!(next(&st, Duration::from_millis(300)).is_none(), "frames after pausing");
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
+197
-12
@@ -13,10 +13,20 @@ use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
||||
const NONE: u64 = u64::MAX;
|
||||
|
||||
struct Shared {
|
||||
/// where the sound is in the source, in source samples (f64 bits): only the device's callback writes it
|
||||
/// where the sound is in the source, in source samples (f64 bits): the end of what the device's callback last
|
||||
/// wrote, or where `start` put it
|
||||
pos: AtomicU64,
|
||||
/// where that callback's samples began, in source samples (f64 bits): the time is read from here, on the wall's
|
||||
/// clock since the callback, and never past `pos`
|
||||
from: AtomicU64,
|
||||
/// when that callback ran (or `start`), in ns since `base()`
|
||||
when: AtomicU64,
|
||||
/// a time asked for, in source samples (f64 bits), taken by the next callback; NONE when there's none
|
||||
jump: AtomicU64,
|
||||
/// counts `start`s: a callback that ran across one doesn't write where it got to over the jump
|
||||
starts: AtomicU64,
|
||||
/// the clock's last reading, in seconds (f64 bits): it never goes back between starts
|
||||
read: AtomicU64,
|
||||
/// the device's delay from a callback to its sound reaching the speaker, in seconds (f64 bits)
|
||||
delay: AtomicU64,
|
||||
muted: AtomicBool,
|
||||
@@ -25,6 +35,88 @@ struct Shared {
|
||||
running: AtomicBool,
|
||||
}
|
||||
|
||||
/// The moment the sound clocks count from (Shared::when).
|
||||
fn base() -> std::time::Instant {
|
||||
static BASE: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
|
||||
*BASE.get_or_init(std::time::Instant::now)
|
||||
}
|
||||
|
||||
/// Now, in ns since `base()`.
|
||||
fn now_ns() -> u64 {
|
||||
base().elapsed().as_nanos() as u64
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
fn new(muted: bool) -> Shared {
|
||||
let zero = 0f64.to_bits();
|
||||
Shared { pos: AtomicU64::new(zero), from: AtomicU64::new(zero), when: AtomicU64::new(now_ns()), jump: AtomicU64::new(NONE), starts: AtomicU64::new(0), read: AtomicU64::new(zero), delay: AtomicU64::new(zero), muted: AtomicBool::new(muted), volume: AtomicU32::new(1f32.to_bits()), running: AtomicBool::new(false) }
|
||||
}
|
||||
|
||||
/// A callback beginning: where its samples start (a jump asked for, else where the last one ended), and the
|
||||
/// `start`s so far, to hand back to `wrote`.
|
||||
fn begin(&self) -> (f64, u64) {
|
||||
let starts = self.starts.load(Relaxed);
|
||||
let jump = self.jump.swap(NONE, Relaxed);
|
||||
(if jump != NONE { f64::from_bits(jump) } else { f64::from_bits(self.pos.load(Relaxed)) }, starts)
|
||||
}
|
||||
|
||||
/// A callback's samples written, `from` to `to` (source samples), at `when` (ns since `base()`). One that ran
|
||||
/// across a `start` leaves the jump it asked for in place: written over it, the clock read the old place until
|
||||
/// the next callback (a seek back read as the end of the film: the loop went round twice, frames came twice).
|
||||
fn wrote(&self, from: f64, to: f64, when: u64, starts: u64) {
|
||||
if self.starts.load(Relaxed) != starts {
|
||||
return;
|
||||
}
|
||||
self.from.store(from.to_bits(), Relaxed);
|
||||
self.when.store(when, Relaxed);
|
||||
self.pos.store(to.to_bits(), Relaxed);
|
||||
}
|
||||
|
||||
/// Plays from `p` (source samples): the next callback starts there, and the clock reads from there at once.
|
||||
fn start(&self, p: f64) {
|
||||
self.starts.fetch_add(1, Relaxed);
|
||||
self.jump.store(p.to_bits(), Relaxed);
|
||||
self.from.store(p.to_bits(), Relaxed);
|
||||
self.pos.store(p.to_bits(), Relaxed);
|
||||
self.when.store(now_ns(), Relaxed);
|
||||
self.read.store(f64::NEG_INFINITY.to_bits(), Relaxed);
|
||||
}
|
||||
|
||||
/// The source time reaching the speaker at `now` (ns since `base()`), in seconds, from `rate` samples a second:
|
||||
/// the last callback's start, moved on by the wall's time since it ran, never past what it wrote (a late callback
|
||||
/// holds the picture rather than run ahead of the sound) and never back from the last reading. Read as the end of
|
||||
/// what was last written, as it was, the clock stood still between callbacks and jumped a buffer at each (10 ms
|
||||
/// steps on this Mac), and a 60 fps film's frames came 6 to 27 ms apart where 16.7 is even.
|
||||
fn time_at(&self, now: u64, rate: f64) -> f64 {
|
||||
let (from, to) = (f64::from_bits(self.from.load(Relaxed)), f64::from_bits(self.pos.load(Relaxed)));
|
||||
let since = now.saturating_sub(self.when.load(Relaxed)) as f64 / 1e9;
|
||||
let t = (from / rate + since).min(to / rate) - f64::from_bits(self.delay.load(Relaxed));
|
||||
let last = f64::from_bits(self.read.fetch_max_f64(t));
|
||||
t.max(last)
|
||||
}
|
||||
}
|
||||
|
||||
/// `fetch_max` for an f64 kept as its bits.
|
||||
trait FetchMaxF64 {
|
||||
/// Stores the larger of what's there and `v`; returns what was there.
|
||||
fn fetch_max_f64(&self, v: f64) -> u64;
|
||||
}
|
||||
|
||||
impl FetchMaxF64 for AtomicU64 {
|
||||
fn fetch_max_f64(&self, v: f64) -> u64 {
|
||||
let mut cur = self.load(Relaxed);
|
||||
loop {
|
||||
if f64::from_bits(cur) >= v {
|
||||
return cur;
|
||||
}
|
||||
match self.compare_exchange_weak(cur, v.to_bits(), Relaxed, Relaxed) {
|
||||
Ok(_) => return cur,
|
||||
Err(now) => cur = now,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The device's stream for one element's sound.
|
||||
pub struct Sound {
|
||||
stream: cpal::Stream,
|
||||
@@ -52,7 +144,7 @@ impl Sound {
|
||||
let ch = (def.channels() as usize).max(1);
|
||||
let rate = audio.rate as f64;
|
||||
let step = rate / def.sample_rate().0 as f64;
|
||||
let shared = Arc::new(Shared { pos: AtomicU64::new(0f64.to_bits()), jump: AtomicU64::new(NONE), delay: AtomicU64::new(0f64.to_bits()), muted: AtomicBool::new(muted), volume: AtomicU32::new(1f32.to_bits()), running: AtomicBool::new(false) });
|
||||
let shared = Arc::new(Shared::new(muted));
|
||||
let s = shared.clone();
|
||||
let src = audio.channels;
|
||||
let last = len - 1;
|
||||
@@ -66,15 +158,16 @@ impl Sound {
|
||||
c[i] + (c[i + 1] - c[i]) * f
|
||||
};
|
||||
let callback = move |out: &mut [f32], info: &cpal::OutputCallbackInfo| {
|
||||
let when = now_ns();
|
||||
let ts = info.timestamp();
|
||||
if let Some(d) = ts.playback.duration_since(&ts.callback) {
|
||||
s.delay.store(d.as_secs_f64().to_bits(), Relaxed);
|
||||
}
|
||||
let jump = s.jump.swap(NONE, Relaxed);
|
||||
let mut p = if jump != NONE { f64::from_bits(jump) } else { f64::from_bits(s.pos.load(Relaxed)) };
|
||||
let (from, starts) = s.begin();
|
||||
let mut p = from;
|
||||
if !s.running.load(Relaxed) {
|
||||
out.fill(0.0);
|
||||
s.pos.store(p.to_bits(), Relaxed);
|
||||
s.wrote(p, p, when, starts);
|
||||
return;
|
||||
}
|
||||
let gain = if s.muted.load(Relaxed) { 0.0 } else { f32::from_bits(s.volume.load(Relaxed)) };
|
||||
@@ -92,7 +185,7 @@ impl Sound {
|
||||
}
|
||||
p += step;
|
||||
}
|
||||
s.pos.store(p.to_bits(), Relaxed);
|
||||
s.wrote(from, p, when, starts);
|
||||
};
|
||||
let stream = dev.build_output_stream(&def.config(), callback, |e| eprintln!("raea-runtime-js: media sound: {e}"), None).map_err(|e| format!("audio stream: {e}"))?;
|
||||
Ok(Sound { stream, shared, rate, len: len as f64 / rate })
|
||||
@@ -100,9 +193,7 @@ impl Sound {
|
||||
|
||||
/// Plays from `t` seconds on.
|
||||
pub fn start(&self, t: f64) {
|
||||
let p = (t.max(0.0) * self.rate).to_bits();
|
||||
self.shared.jump.store(p, Relaxed);
|
||||
self.shared.pos.store(p, Relaxed);
|
||||
self.shared.start(t.max(0.0) * self.rate);
|
||||
self.shared.running.store(true, Relaxed);
|
||||
let _ = self.stream.play();
|
||||
}
|
||||
@@ -122,9 +213,103 @@ impl Sound {
|
||||
self.shared.volume.store(v.to_bits(), Relaxed);
|
||||
}
|
||||
|
||||
/// The source time now reaching the speaker: what the picture shows to be in step with it.
|
||||
/// The source time now reaching the speaker: what the picture shows to be in step with it (`Shared::time_at`).
|
||||
pub fn time(&self) -> f64 {
|
||||
let t = f64::from_bits(self.shared.pos.load(Relaxed)) / self.rate - f64::from_bits(self.shared.delay.load(Relaxed));
|
||||
t.clamp(0.0, self.len)
|
||||
self.shared.time_at(now_ns(), self.rate).clamp(0.0, self.len)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const RATE: f64 = 48_000.0;
|
||||
/// a device's buffer: 512 samples, 10.7 ms at 48 kHz
|
||||
const BUF: f64 = 512.0;
|
||||
const MS: u64 = 1_000_000;
|
||||
|
||||
/// A callback at `at` (ns since `base()`) writing one buffer on from where the last ended.
|
||||
fn callback(s: &Shared, at: u64) {
|
||||
let (from, starts) = s.begin();
|
||||
s.wrote(from, from + BUF, at, starts);
|
||||
}
|
||||
|
||||
/// Between two callbacks the clock moves on with the wall's, a millisecond a millisecond: read as the end of
|
||||
/// what was last written, it stood still for a buffer and then jumped one (11-16).
|
||||
#[test]
|
||||
fn the_clock_moves_between_callbacks() {
|
||||
let s = Shared::new(false);
|
||||
s.start(0.0);
|
||||
let t0 = now_ns();
|
||||
let (mut last, mut most) = (f64::NAN, 0f64);
|
||||
for ms in 0..60u64 {
|
||||
// a callback each buffer, right on time
|
||||
let at = t0 + ms * MS;
|
||||
if ms % 11 == 0 {
|
||||
callback(&s, at);
|
||||
}
|
||||
let t = s.time_at(at, RATE);
|
||||
if !last.is_nan() {
|
||||
most = most.max(t - last);
|
||||
assert!(t >= last, "the clock went back: {t} after {last}");
|
||||
}
|
||||
last = t;
|
||||
}
|
||||
assert!(most < 0.0015, "the clock stepped {most} s in a millisecond");
|
||||
// and it keeps the wall's pace: 59 ms on, about 59 ms of sound
|
||||
assert!((last - 0.059).abs() < 0.003, "{last}");
|
||||
}
|
||||
|
||||
/// A callback that comes late holds the clock at the end of what was written rather than running ahead of the
|
||||
/// sound; the next one takes it on from there.
|
||||
#[test]
|
||||
fn a_late_callback_holds_the_clock() {
|
||||
let s = Shared::new(false);
|
||||
s.start(0.0);
|
||||
let t0 = now_ns();
|
||||
callback(&s, t0);
|
||||
let end = BUF / RATE;
|
||||
assert!((s.time_at(t0 + 30 * MS, RATE) - end).abs() < 1e-9, "held at the buffer's end");
|
||||
callback(&s, t0 + 30 * MS);
|
||||
assert!((s.time_at(t0 + 31 * MS, RATE) - (end + 0.001)).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// A start (a seek, a loop going round) made while a callback runs isn't written over by that callback: the clock
|
||||
/// reads the new place at once and after it ends, and the next callback plays from there.
|
||||
#[test]
|
||||
fn a_start_during_a_callback_stands() {
|
||||
let s = Shared::new(false);
|
||||
s.start(10.0 * RATE);
|
||||
let t0 = now_ns();
|
||||
callback(&s, t0);
|
||||
// a callback begins, the film goes back to 2 s, the callback ends
|
||||
let (from, starts) = s.begin();
|
||||
s.start(2.0 * RATE);
|
||||
s.wrote(from, from + BUF, t0 + 11 * MS, starts);
|
||||
let t = s.time_at(now_ns(), RATE);
|
||||
assert!((2.0..2.1).contains(&t), "read {t} after the start at 2 s");
|
||||
// the next callback takes the jump
|
||||
let (p, _) = s.begin();
|
||||
assert_eq!(p, 2.0 * RATE);
|
||||
}
|
||||
|
||||
/// The delay to the speaker is taken off, and a delay that grows doesn't take the clock back.
|
||||
#[test]
|
||||
fn the_delay_never_takes_it_back() {
|
||||
let s = Shared::new(false);
|
||||
s.start(RATE);
|
||||
let t0 = now_ns();
|
||||
callback(&s, t0);
|
||||
let before = s.time_at(t0 + 5 * MS, RATE);
|
||||
assert!((before - 1.005).abs() < 1e-6);
|
||||
s.delay.store(0.02f64.to_bits(), Relaxed);
|
||||
assert_eq!(s.time_at(t0 + 6 * MS, RATE), before, "held while the delay is made up");
|
||||
// (at 10 ms on, 1.010 - 0.02 is still behind what was read)
|
||||
assert_eq!(s.time_at(t0 + 10 * MS, RATE), before);
|
||||
// once a callback brings the sound past it, the clock goes on from there
|
||||
callback(&s, t0 + 11 * MS);
|
||||
callback(&s, t0 + 22 * MS);
|
||||
let t = s.time_at(t0 + 30 * MS, RATE);
|
||||
assert!((t - (1.0 + 2.0 * BUF / RATE + 0.008 - 0.02)).abs() < 1e-6, "{t}");
|
||||
}
|
||||
}
|
||||
+20
-19
@@ -20,6 +20,14 @@ unsafe extern "C" {
|
||||
}
|
||||
const RTLD_DEFAULT: *mut c_void = -2isize as *mut c_void;
|
||||
|
||||
/// A call JavaScriptCore exports without declaring it (not in the SDK's headers, or newer than it), looked up by name:
|
||||
/// None where this system has none. `F` is its `unsafe extern "C" fn` type.
|
||||
fn spi<F: Copy>(name: &std::ffi::CStr) -> Option<F> {
|
||||
let p = unsafe { dlsym(RTLD_DEFAULT, name.as_ptr()) };
|
||||
// SAFETY: a symbol of that name is that function, and F is a function pointer, the size of p
|
||||
(!p.is_null()).then(|| unsafe { std::mem::transmute_copy::<*mut c_void, F>(&p) })
|
||||
}
|
||||
|
||||
#[link(name = "CoreFoundation", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
static kCFRunLoopDefaultMode: *const c_void;
|
||||
@@ -71,6 +79,7 @@ unsafe extern "C" {
|
||||
fn JSValueMakeUndefined(ctx: Ctx) -> Val;
|
||||
fn JSObjectMakeError(ctx: Ctx, argc: usize, argv: *const Val, exception: *mut Val) -> Obj;
|
||||
fn JSGarbageCollect(ctx: Ctx);
|
||||
fn JSValueCreateJSONString(ctx: Ctx, value: Val, indent: u32, exception: *mut Val) -> Str;
|
||||
fn JSContextGetGroup(ctx: Ctx) -> *const c_void;
|
||||
fn JSValueUnprotect(ctx: Ctx, v: Val);
|
||||
fn JSClassCreate(definition: *const ClassDefinition) -> *mut c_void;
|
||||
@@ -182,10 +191,7 @@ pub fn options() {
|
||||
pub fn release_free_memory() -> Option<f64> {
|
||||
type Release = unsafe extern "C" fn();
|
||||
static RELEASE: std::sync::OnceLock<Option<Release>> = std::sync::OnceLock::new();
|
||||
let f = RELEASE.get_or_init(|| unsafe {
|
||||
let p = dlsym(RTLD_DEFAULT, c"_ZN3WTF27releaseFastMallocFreeMemoryEv".as_ptr());
|
||||
(!p.is_null()).then(|| std::mem::transmute::<*mut c_void, Release>(p))
|
||||
});
|
||||
let f = RELEASE.get_or_init(|| spi(c"_ZN3WTF27releaseFastMallocFreeMemoryEv"));
|
||||
let f = (*f)?;
|
||||
let t = std::time::Instant::now();
|
||||
unsafe { f() };
|
||||
@@ -285,7 +291,11 @@ impl Default for Context {
|
||||
impl Context {
|
||||
pub fn new() -> Context {
|
||||
options();
|
||||
Context { ctx: unsafe { JSGlobalContextCreate(null_mut()) } }
|
||||
let ctx = unsafe { JSGlobalContextCreate(null_mut()) };
|
||||
if crate::inspect() {
|
||||
inspect::inspectable(ctx);
|
||||
}
|
||||
Context { ctx }
|
||||
}
|
||||
|
||||
fn c(&self) -> Ctx {
|
||||
@@ -376,12 +386,8 @@ impl Context {
|
||||
unsafe extern "C" fn stop(_: Ctx, _: *mut c_void) -> bool {
|
||||
true
|
||||
}
|
||||
unsafe {
|
||||
let p = dlsym(RTLD_DEFAULT, c"JSContextGroupSetExecutionTimeLimit".as_ptr());
|
||||
if !p.is_null() {
|
||||
let f = std::mem::transmute::<*mut c_void, SetLimit>(p);
|
||||
f(JSContextGetGroup(self.c()), limit.as_secs_f64(), Some(stop), null_mut());
|
||||
}
|
||||
if let Some(f) = spi::<SetLimit>(c"JSContextGroupSetExecutionTimeLimit") {
|
||||
unsafe { f(JSContextGetGroup(self.c()), limit.as_secs_f64(), Some(stop), null_mut()) };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -402,10 +408,7 @@ impl Context {
|
||||
pub fn collect_young(&self) -> bool {
|
||||
type Eden = unsafe extern "C" fn(Ctx);
|
||||
static EDEN: std::sync::OnceLock<Option<Eden>> = std::sync::OnceLock::new();
|
||||
let f = EDEN.get_or_init(|| unsafe {
|
||||
let p = dlsym(RTLD_DEFAULT, c"JSSynchronousEdenCollectForDebugging".as_ptr());
|
||||
(!p.is_null()).then(|| std::mem::transmute::<*mut c_void, Eden>(p))
|
||||
});
|
||||
let f = EDEN.get_or_init(|| spi(c"JSSynchronousEdenCollectForDebugging"));
|
||||
match f {
|
||||
Some(f) => {
|
||||
unsafe { f(self.c()) };
|
||||
@@ -437,10 +440,7 @@ impl Context {
|
||||
pub fn collect(&self) {
|
||||
type Sync = unsafe extern "C" fn(Ctx);
|
||||
static SYNC: std::sync::OnceLock<Option<Sync>> = std::sync::OnceLock::new();
|
||||
let f = SYNC.get_or_init(|| unsafe {
|
||||
let p = dlsym(RTLD_DEFAULT, c"JSSynchronousGarbageCollectForDebugging".as_ptr());
|
||||
(!p.is_null()).then(|| std::mem::transmute::<*mut c_void, Sync>(p))
|
||||
});
|
||||
let f = SYNC.get_or_init(|| spi(c"JSSynchronousGarbageCollectForDebugging"));
|
||||
unsafe {
|
||||
match f {
|
||||
Some(f) => f(self.c()),
|
||||
@@ -464,4 +464,5 @@ impl Drop for Context {
|
||||
pub mod modules;
|
||||
|
||||
mod host;
|
||||
mod inspect;
|
||||
pub use host::Jsc;
|
||||
@@ -75,4 +75,8 @@ impl JsEngine for Jsc {
|
||||
fn idle(&mut self) {
|
||||
pump();
|
||||
}
|
||||
|
||||
fn heap(&mut self) -> Option<String> {
|
||||
self.ctx.heap()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//! What a JavaScriptCore context holds, for the heap log (crate::Upkeep, RAEA_INSPECT), and the context opened to
|
||||
//! Safari's Web Inspector: both through calls the system exports without declaring them (super::spi).
|
||||
|
||||
use super::*;
|
||||
|
||||
impl Context {
|
||||
/// What the heap holds, as JSON: JavaScriptCore's own statistics (JSGetMemoryUsageStatistics, exported by the system
|
||||
/// though not in its headers: heapSize, heapCapacity, extraMemorySize, objectCount, protectedObjectCount,
|
||||
/// objectTypeCounts by class), found at run time. None where the system doesn't export it.
|
||||
pub fn heap(&self) -> Option<String> {
|
||||
type Stats = unsafe extern "C" fn(Ctx) -> Obj;
|
||||
static STATS: std::sync::OnceLock<Option<Stats>> = std::sync::OnceLock::new();
|
||||
let f = (*STATS.get_or_init(|| spi(c"JSGetMemoryUsageStatistics")))?;
|
||||
unsafe {
|
||||
let stats = f(self.c());
|
||||
if stats.is_null() {
|
||||
return None;
|
||||
}
|
||||
let json = JSValueCreateJSONString(self.c(), stats as Val, 0, null_mut());
|
||||
if json.is_null() {
|
||||
return None;
|
||||
}
|
||||
let v = JSValueMakeString(self.c(), json);
|
||||
JSStringRelease(json);
|
||||
Some(to_string(self.c(), v))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The context listed in Safari's Develop menu, for its Web Inspector (heap snapshots, what holds an object, the
|
||||
/// console), when RAEA_INSPECT is on: JSGlobalContextSetInspectable, macOS 13.3 and later, found at run time so an older
|
||||
/// system starts as before.
|
||||
pub(super) fn inspectable(ctx: GCtx) {
|
||||
type Set = unsafe extern "C" fn(GCtx, bool);
|
||||
match spi::<Set>(c"JSGlobalContextSetInspectable") {
|
||||
Some(f) => unsafe { f(ctx, true) },
|
||||
None => eprintln!("raea-runtime-jsengine: this system's JavaScriptCore can't be inspected (macOS 13.3 or later)"),
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@ use std::rc::Rc;
|
||||
pub mod jsc;
|
||||
#[cfg(any(feature = "portable", not(target_vendor = "apple")))]
|
||||
mod quickjs;
|
||||
mod upkeep;
|
||||
pub use upkeep::{Upkeep, inspect};
|
||||
|
||||
/// An argument to a global function.
|
||||
pub enum Arg<'a> {
|
||||
@@ -36,11 +38,21 @@ pub type Native = Box<dyn Fn(&[String]) -> Result<Ret, String>>;
|
||||
|
||||
thread_local! {
|
||||
static T0: std::time::Instant = std::time::Instant::now();
|
||||
static HELD: std::cell::Cell<Option<f64>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// ms since this thread first asked: the clock a host's JS timers run on.
|
||||
/// ms since this thread first asked: the clock a host's JS timers run on (or the time `at_clock` holds it at).
|
||||
pub fn now_ms() -> f64 {
|
||||
T0.with(|t| t.elapsed().as_secs_f64() * 1e3)
|
||||
HELD.with(|h| h.get()).unwrap_or_else(|| T0.with(|t| t.elapsed().as_secs_f64() * 1e3))
|
||||
}
|
||||
|
||||
/// `f` run with this thread's JS clock held at `ms`: a root stepped on a composition's frames (an app screen, frame
|
||||
/// over fps) sees the same timers and performance.now in a render and its play, so the render repeats.
|
||||
pub fn at_clock<T>(ms: f64, f: impl FnOnce() -> T) -> T {
|
||||
let was = HELD.with(|h| h.replace(Some(ms)));
|
||||
let out = f();
|
||||
HELD.with(|h| h.set(was));
|
||||
out
|
||||
}
|
||||
|
||||
/// A native answering `now_ms()`, a host's `now` for its JS.
|
||||
@@ -87,6 +99,11 @@ pub trait JsEngine {
|
||||
}
|
||||
/// Between frames: the engine's own upkeep (JavaScriptCore's GC timers live on the thread's run loop).
|
||||
fn idle(&mut self) {}
|
||||
/// What its heap holds now, as one JSON object, for the heap log (Upkeep): JavaScriptCore's statistics (its size and
|
||||
/// objects counted by type), QuickJS's memory usage. None where the engine can't say.
|
||||
fn heap(&mut self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `error` is a run stopped by its time limit (JavaScriptCore's watchdog, QuickJS's interrupt).
|
||||
|
||||
@@ -158,4 +158,12 @@ impl JsEngine for Quick {
|
||||
fn collect(&mut self) {
|
||||
self.rt.run_gc();
|
||||
}
|
||||
|
||||
fn heap(&mut self) -> Option<String> {
|
||||
let m = self.rt.memory_usage();
|
||||
Some(format!(
|
||||
r#"{{"mallocSize":{},"memoryUsed":{},"objectCount":{},"objectSize":{},"propertyCount":{},"stringCount":{},"stringSize":{},"arrayCount":{},"functionCount":{},"shapeCount":{},"binaryObjectCount":{},"binaryObjectSize":{}}}"#,
|
||||
m.malloc_size, m.memory_used_size, m.obj_count, m.obj_size, m.prop_count, m.str_count, m.str_size, m.array_count, m.js_func_count, m.shape_count, m.binary_object_count, m.binary_object_size
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//! A page's JS engine looked after between frames, the same on every engine.
|
||||
//!
|
||||
//! - Its free pages go back to the system every few seconds (RAEA_JSC_RELEASE_S, 5; 0 never), as raea-runtime-react's
|
||||
//! JS thread already gives them back. A page's JS didn't: JavaScriptCore keeps what it frees resident until asked,
|
||||
//! and the 0.1.6 app's window showed ~300 MB of its JS memory reclaimable and still held (11-16).
|
||||
//! - With RAEA_INSPECT on, its heap is logged: every RAEA_JS_HEAP_S seconds (30; 0 never) a full collection, then one
|
||||
//! JSON line in ~/.raea/logs/js-heap-<pid>-<n>.jsonl (the process's nth engine). So what a page holds can be read over a
|
||||
//! whole session, on any engine, without a debugger: what grows from line to line (JavaScriptCore's
|
||||
//! objectTypeCounts, QuickJS's object and string counts) is what it keeps. The collection stops the page's thread
|
||||
//! (gc_ms in each line says for how long), which is why the log is off unless asked for.
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use crate::JsEngine;
|
||||
|
||||
/// RAEA_INSPECT is on (set and not "0"): the heap log, and on JavaScriptCore the context listed in Safari's Develop
|
||||
/// menu for its Web Inspector.
|
||||
pub fn inspect() -> bool {
|
||||
!matches!(std::env::var("RAEA_INSPECT").as_deref(), Err(_) | Ok("" | "0"))
|
||||
}
|
||||
|
||||
pub struct Upkeep {
|
||||
release_every: f64,
|
||||
released: Instant,
|
||||
heap_every: f64,
|
||||
logged: Instant,
|
||||
log: Option<File>,
|
||||
started: Instant,
|
||||
}
|
||||
|
||||
impl Upkeep {
|
||||
/// Its settings from the environment; with the heap log on, its file opened (one per engine).
|
||||
pub fn from_env() -> Upkeep {
|
||||
let secs = |k: &str| std::env::var(k).ok().and_then(|v| v.parse::<f64>().ok());
|
||||
let heap_every = secs("RAEA_JS_HEAP_S").unwrap_or(if inspect() { 30.0 } else { 0.0 });
|
||||
let log = if heap_every > 0.0 { open_log() } else { None };
|
||||
let now = Instant::now();
|
||||
Upkeep { release_every: secs("RAEA_JSC_RELEASE_S").unwrap_or(5.0), released: now, heap_every, logged: now, log, started: now }
|
||||
}
|
||||
|
||||
/// Between frames: what's due of the two.
|
||||
pub fn tick(&mut self, js: &mut dyn JsEngine) {
|
||||
if self.release_every > 0.0 && self.released.elapsed().as_secs_f64() >= self.release_every {
|
||||
js.release_memory();
|
||||
self.released = Instant::now();
|
||||
}
|
||||
if self.log.is_some() && self.logged.elapsed().as_secs_f64() >= self.heap_every {
|
||||
self.write(js);
|
||||
self.logged = Instant::now();
|
||||
}
|
||||
}
|
||||
|
||||
fn write(&mut self, js: &mut dyn JsEngine) {
|
||||
let t = Instant::now();
|
||||
js.collect();
|
||||
let gc_ms = t.elapsed().as_secs_f64() * 1e3;
|
||||
let Some(heap) = js.heap() else {
|
||||
eprintln!("raea-runtime-jsengine: {} doesn't say what its heap holds; no heap log", js.name());
|
||||
self.log = None;
|
||||
return;
|
||||
};
|
||||
let at = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
||||
let up = self.started.elapsed().as_secs();
|
||||
let engine = js.name();
|
||||
if let Some(f) = self.log.as_mut() {
|
||||
let _ = writeln!(f, r#"{{"at":{at},"up_s":{up},"engine":"{engine}","gc_ms":{gc_ms:.1},"heap":{heap}}}"#);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn open_log() -> Option<File> {
|
||||
static N: AtomicU32 = AtomicU32::new(0);
|
||||
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
|
||||
let dir = PathBuf::from(home).join(".raea").join("logs");
|
||||
if let Err(e) = std::fs::create_dir_all(&dir) {
|
||||
eprintln!("raea-runtime-jsengine: no heap log in {}: {e}", dir.display());
|
||||
return None;
|
||||
}
|
||||
let path = dir.join(format!("js-heap-{}-{}.jsonl", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
|
||||
match File::options().create(true).append(true).open(&path) {
|
||||
Ok(f) => {
|
||||
eprintln!("raea-runtime-jsengine: the JS heap's log: {}", path.display());
|
||||
Some(f)
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("raea-runtime-jsengine: no heap log at {}: {e}", path.display());
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
-41
@@ -19,6 +19,8 @@ mod pick3d;
|
||||
pub use pick3d::want_wire;
|
||||
pub use sound::warm_audio;
|
||||
mod draw;
|
||||
mod react;
|
||||
pub use react::needs_react;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
@@ -58,6 +60,9 @@ pub struct Live {
|
||||
frame: i64,
|
||||
/// the gamepads' marked keys the last frame was given beside its input ("Pad0:South"), for its input log
|
||||
pads: Vec<String>,
|
||||
/// the keys an app screen took from the last frame (the page didn't get them), left out of its input log, which
|
||||
/// keeps them under `apps` (`app_input`)
|
||||
taken: Vec<String>,
|
||||
/// the pointer on the page's elements, as the last frame left it (pointer.rs)
|
||||
pointer: pointer::PagePointer,
|
||||
/// generated sounds' files, by what they were made from (looked up once)
|
||||
@@ -202,6 +207,9 @@ impl Live {
|
||||
self.lag = (lag, std::time::Instant::now());
|
||||
self.frame = f;
|
||||
self.pads.clear();
|
||||
self.taken.clear();
|
||||
// the app screens step to this frame at the page's next sync (screen.rs step_all)
|
||||
self.page.set_app_frame(f, self.fps);
|
||||
let t0 = std::time::Instant::now();
|
||||
if self.baked.is_some() {
|
||||
// a baked timeline: its recorded commits, no JS; the clips it cuts to soon opened ahead; the page styled at
|
||||
@@ -224,6 +232,9 @@ impl Live {
|
||||
Some(e) => Some(raea_runtime_page::screen::route(&mut self.page, e, keys, pointer, (self.w, self.h))),
|
||||
None => None,
|
||||
};
|
||||
if let Some(r) = &routed {
|
||||
self.taken = keys.iter().filter(|k| !r.contains(k)).cloned().collect();
|
||||
}
|
||||
let keys = routed.as_deref().unwrap_or(keys);
|
||||
// the pointer on the page's elements: their on* handlers, before the frame's step (pointer.rs)
|
||||
if let Some(p) = pointer {
|
||||
@@ -317,29 +328,6 @@ fn components_use_config(dir: &Path) -> bool {
|
||||
std::fs::read_dir(dir.join("components")).into_iter().flatten().flatten().any(|e| std::fs::read_to_string(e.path()).is_ok_and(|t| t.contains("useVideoConfig(")))
|
||||
}
|
||||
|
||||
/// Whether the edit's own sources (its folder, not node_modules) import React Three Fiber (`raea/r3f`,
|
||||
/// `@react-three/...`): R3F runs a reconciler of its own on React, which live play's runtime (sdk/react/js/lite) isn't,
|
||||
/// so such a play keeps React, as RAEA_LIVE_REACT=1 does (docs/r3f.feature R3F27)
|
||||
pub fn needs_react(dir: &Path) -> bool {
|
||||
fn walk(d: &Path, depth: usize) -> bool {
|
||||
let Ok(rd) = std::fs::read_dir(d) else { return false };
|
||||
rd.flatten().any(|e| {
|
||||
let name = e.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
let p = e.path();
|
||||
if name.starts_with('.') || name == "node_modules" || name == "target" {
|
||||
false
|
||||
} else if p.is_dir() {
|
||||
depth < 4 && walk(&p, depth + 1)
|
||||
} else {
|
||||
[".tsx", ".ts", ".jsx", ".js"].iter().any(|x| name.ends_with(x))
|
||||
&& std::fs::read_to_string(&p).is_ok_and(|t| t.contains("raea/r3f") || t.contains("@react-three/"))
|
||||
}
|
||||
})
|
||||
}
|
||||
walk(dir, 0)
|
||||
}
|
||||
|
||||
/// What a composition's sound is made of: its bundle and every file in its project (path, size, time), hashed, so a
|
||||
/// sound worked out from them (the mastered track) is found again until one of them changes.
|
||||
fn sound_key(js: &Path, dir: &Path) -> u64 {
|
||||
@@ -389,7 +377,13 @@ impl Live {
|
||||
/// The keys the last frame stepped was given: `keys` and the gamepads marked beside them, as its input log records
|
||||
/// them, so a render of the log gives the game the same pads (bench/render-play's live-gamepad).
|
||||
pub fn played_keys(&self, keys: &[String]) -> Vec<String> {
|
||||
keys.iter().chain(&self.pads).cloned().collect()
|
||||
keys.iter().chain(&self.pads).filter(|k| !self.taken.contains(k)).cloned().collect()
|
||||
}
|
||||
|
||||
/// What reached the app screens in the last frame stepped, as its input log keeps it (`apps`): a render of the
|
||||
/// log gives them the same (runtime/page/src/screen.rs).
|
||||
pub fn app_input(&self) -> Option<serde_json::Value> {
|
||||
raea_runtime_page::screen::logged(&self.page)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -475,20 +469,3 @@ mod frame_event_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod needs_react_tests {
|
||||
#[test]
|
||||
fn an_edit_importing_r3f_keeps_react_and_one_whose_packages_do_doesnt() {
|
||||
let d = std::env::temp_dir().join(format!("raea-needs-react-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(d.join("node_modules/drei")).unwrap();
|
||||
std::fs::write(d.join("edit.tsx"), "import { Composition } from \"raea\";").unwrap();
|
||||
std::fs::write(d.join("node_modules/drei/index.js"), "import \"@react-three/fiber\";").unwrap();
|
||||
assert!(!super::needs_react(&d));
|
||||
std::fs::create_dir_all(d.join("src/scene")).unwrap();
|
||||
std::fs::write(d.join("src/scene/ball.tsx"), "import { R3F } from \"raea/r3f\";").unwrap();
|
||||
assert!(super::needs_react(&d));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
@@ -65,7 +65,7 @@ impl Live {
|
||||
let (w, h) = if responsive { (stage.0.max(1), stage.1.max(1)) } else { (cw, ch) };
|
||||
let page = raea_runtime_page::BevyPage::new(w, h, &dir)?;
|
||||
let brand = raea_runtime_react::scene::page_css(&dir, w, &js);
|
||||
let mut live = Live { app, dir: dir.clone(), page, brand, dirty: true, mixer: None, mixer_failed: false, lag: (0.0, std::time::Instant::now()), w, h, fps, frames, responsive, js, master: None, master_wav: None, game_master: None, game_gain: None, scene_rx: None, scene: None, live3d: None, frame: 0, pads: Vec::new(), pointer: Default::default(), made: Default::default(), sound_buf: Vec::new(), holders: Vec::new(), baked: None, applied: -1, session: new_session() };
|
||||
let mut live = Live { app, dir: dir.clone(), page, brand, dirty: true, mixer: None, mixer_failed: false, lag: (0.0, std::time::Instant::now()), w, h, fps, frames, responsive, js, master: None, master_wav: None, game_master: None, game_gain: None, scene_rx: None, scene: None, live3d: None, frame: 0, pads: Vec::new(), taken: Vec::new(), pointer: Default::default(), made: Default::default(), sound_buf: Vec::new(), holders: Vec::new(), baked: None, applied: -1, session: new_session() };
|
||||
if responsive {
|
||||
live.send("raea-size", json!({"w": w, "h": h}));
|
||||
}
|
||||
@@ -117,7 +117,7 @@ impl Live {
|
||||
raea_runtime_react::scene::one_thread(&mut app);
|
||||
let page = raea_runtime_page::BevyPage::new(w, h, &dir)?;
|
||||
let brand = raea_runtime_react::scene::page_css(&dir, w, &js);
|
||||
let mut live = Live { app, dir: dir.clone(), page, brand, dirty: true, mixer: None, mixer_failed: false, lag: (0.0, std::time::Instant::now()), w, h, fps, frames, responsive: false, js, master: None, master_wav: None, game_master: None, game_gain: None, scene_rx: None, scene: None, live3d: None, frame: 0, pads: Vec::new(), pointer: Default::default(), made: Default::default(), sound_buf: Vec::new(), holders: Vec::new(), baked: None, applied: -1, session: new_session() };
|
||||
let mut live = Live { app, dir: dir.clone(), page, brand, dirty: true, mixer: None, mixer_failed: false, lag: (0.0, std::time::Instant::now()), w, h, fps, frames, responsive: false, js, master: None, master_wav: None, game_master: None, game_gain: None, scene_rx: None, scene: None, live3d: None, frame: 0, pads: Vec::new(), taken: Vec::new(), pointer: Default::default(), made: Default::default(), sound_buf: Vec::new(), holders: Vec::new(), baked: None, applied: -1, session: new_session() };
|
||||
for b in &baked.init {
|
||||
live.app.world().resource::<raea_runtime_react::ReplayFeed>().feed(b.clone());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Which live plays keep React (docs/r3f.feature R3F27).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// Whether the edit's own sources (its folder, not node_modules) import React Three Fiber (`raea/r3f`,
|
||||
/// `@react-three/...`): R3F runs a reconciler of its own on React, which live play's runtime (sdk/react/js/lite) isn't,
|
||||
/// so such a play keeps React, as RAEA_LIVE_REACT=1 does (docs/r3f.feature R3F27)
|
||||
pub fn needs_react(dir: &Path) -> bool {
|
||||
fn walk(d: &Path, depth: usize) -> bool {
|
||||
let Ok(rd) = std::fs::read_dir(d) else { return false };
|
||||
rd.flatten().any(|e| {
|
||||
let name = e.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
let p = e.path();
|
||||
if name.starts_with('.') || name == "node_modules" || name == "target" {
|
||||
false
|
||||
} else if p.is_dir() {
|
||||
depth < 4 && walk(&p, depth + 1)
|
||||
} else {
|
||||
[".tsx", ".ts", ".jsx", ".js"].iter().any(|x| name.ends_with(x))
|
||||
&& std::fs::read_to_string(&p).is_ok_and(|t| t.contains("raea/r3f") || t.contains("@react-three/"))
|
||||
}
|
||||
})
|
||||
}
|
||||
walk(dir, 0)
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod needs_react_tests {
|
||||
#[test]
|
||||
fn an_edit_importing_r3f_keeps_react_and_one_whose_packages_do_doesnt() {
|
||||
let d = std::env::temp_dir().join(format!("raea-needs-react-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(d.join("node_modules/drei")).unwrap();
|
||||
std::fs::write(d.join("edit.tsx"), "import { Composition } from \"raea\";").unwrap();
|
||||
std::fs::write(d.join("node_modules/drei/index.js"), "import \"@react-three/fiber\";").unwrap();
|
||||
assert!(!super::needs_react(&d));
|
||||
std::fs::create_dir_all(d.join("src/scene")).unwrap();
|
||||
std::fs::write(d.join("src/scene/ball.tsx"), "import { R3F } from \"raea/r3f\";").unwrap();
|
||||
assert!(super::needs_react(&d));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,15 @@ pub fn env_shown(sent: Option<&V>, cam: &mut BTreeMap<String, V>) {
|
||||
cam.insert("env_srcs".into(), V::S(serde_json::to_string(&list).unwrap_or_default()));
|
||||
}
|
||||
|
||||
/// An <Environment>'s source in env_srcs: its panorama's path, or for <Environment room> `room:` and its blur (three's
|
||||
/// RoomEnvironment, which raea-sys-environment's room.rs makes, #165).
|
||||
pub fn env_src(e: &Item) -> Option<String> {
|
||||
if e.props.get("room") == Some(&Value::Bool(true)) {
|
||||
return Some(format!("room:{}", n(&e.props, "blur", 0.0)));
|
||||
}
|
||||
e.props.get("src").and_then(Value::as_str).map(src_path)
|
||||
}
|
||||
|
||||
/// The camera row (`row`, id "cam": the scene's first camera) and a row for each camera after it (cam1, cam2, ...), each
|
||||
/// drawn in its `order` over the ones before, cleared or not by its `clear` (<Camera3d order clear_color>, Bevy's
|
||||
/// Camera: two_passes, split_screen), clearing to the first's colour when it clears.
|
||||
@@ -157,11 +166,8 @@ fn lit(all: &[Vec<Item>], p: &mut Program, row: &mut BTreeMap<String, V>, id: &s
|
||||
let envs: Vec<Option<&Item>> = all.iter().map(|its| its.iter().find(|i| i.kind == "environment" && !i.props.contains_key("diffuse_map"))).collect();
|
||||
if envs.iter().any(Option::is_some) {
|
||||
let mut srcs: Vec<String> = Vec::new();
|
||||
let idx: Vec<f64> = envs.iter().map(|e| match e.and_then(|e| e.props.get("src")).and_then(Value::as_str) {
|
||||
Some(s) => {
|
||||
let s = src_path(s);
|
||||
(srcs.iter().position(|x| *x == s).unwrap_or_else(|| { srcs.push(s); srcs.len() - 1 })) as f64
|
||||
}
|
||||
let idx: Vec<f64> = envs.iter().map(|e| match e.and_then(|e| env_src(e)) {
|
||||
Some(s) => (srcs.iter().position(|x| *x == s).unwrap_or_else(|| { srcs.push(s); srcs.len() - 1 })) as f64,
|
||||
None => -1.0,
|
||||
}).collect();
|
||||
row.insert("env_srcs".into(), V::S(serde_json::to_string(&srcs).unwrap_or_default()));
|
||||
|
||||
@@ -48,3 +48,23 @@ fn a_camera_with_a_rotation_keeps_it_exactly_and_one_without_has_none() {
|
||||
camera(&[vec![cam(json!({ "position": [4, 3, 6], "lookAt": [0, 0.2, 0], "rotation": [0.1, 0.2, 0.3] }))]], &mut Program::default(), &mut plain);
|
||||
assert!(!plain.contains_key("rot_qw"), "a rotation that isn't a quaternion places nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_environment_room_is_a_source_of_its_own_by_its_blur() {
|
||||
// <Environment room blur> (three's RoomEnvironment, #165): no file, the engine makes it; the same room on two
|
||||
// frames is one source, a file beside it another
|
||||
let env = |p: serde_json::Value| Item { kind: "environment", props: Arc::new(p.as_object().unwrap().clone()), shape: None, material: None, at: None, world: Mat4::IDENTITY };
|
||||
let frames = vec![
|
||||
vec![cam(json!({ "position": [0, 0, 5] })), env(json!({ "room": true, "blur": 0.04, "intensity": 1 }))],
|
||||
vec![cam(json!({ "position": [0, 0, 5] })), env(json!({ "room": true, "blur": 0.04, "intensity": 0.5 }))],
|
||||
vec![cam(json!({ "position": [0, 0, 5] })), env(json!({ "src": "sky.hdr" }))],
|
||||
vec![cam(json!({ "position": [0, 0, 5] })), env(json!({ "room": true }))],
|
||||
];
|
||||
let mut row: BTreeMap<String, V> = [("id".to_string(), V::S("cam".into()))].into();
|
||||
camera(&frames, &mut Program::default(), &mut row);
|
||||
let srcs: Vec<String> = match row.get("env_srcs") {
|
||||
Some(V::S(s)) => serde_json::from_str(s).unwrap(),
|
||||
other => panic!("no env_srcs: {other:?}"),
|
||||
};
|
||||
assert_eq!(srcs, ["room:0.04", "sky.hdr", "room:0"]);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ description = "A composition's page in Bevy: React's elements laid out and paint
|
||||
|
||||
[dependencies]
|
||||
raea-runtime-view = { path = "../view" }
|
||||
raea-runtime-appscreen = { path = "../appscreen" }
|
||||
raea-sys-frame = { path = "../../systems/frame" }
|
||||
raea-io-assets = { path = "../../io/assets" }
|
||||
raea-io-net = { path = "../../io/net" }
|
||||
|
||||
@@ -98,11 +98,7 @@ impl BevyPage {
|
||||
}
|
||||
}
|
||||
crate::screen::retire(&mut self.apps, &self.app_screens);
|
||||
for (name, _, _, app) in &self.app_screens {
|
||||
if self.apps.failed.insert(name.clone(), app.clone()).is_none() {
|
||||
eprintln!("raea: screen {name:?}: its app {app:?} isn't drawn yet: app screens move to raea-runtime-js roots of their own (ts-native P27)");
|
||||
}
|
||||
}
|
||||
crate::screen::step_all(&mut self.apps, &self.app_screens, &self.dir);
|
||||
self.page.place_videos(videos)
|
||||
}
|
||||
|
||||
@@ -147,12 +143,21 @@ impl BevyPage {
|
||||
/// The page and each <Screen>'s picture drawn and read back: the page's premultiplied RGBA, and each screen's name,
|
||||
/// size and RGBA.
|
||||
pub fn frame_all(&mut self) -> R<(Vec<u8>, Vec<(String, u32, u32, Vec<u8>)>)> {
|
||||
self.page.frame_all()
|
||||
let (px, mut pics) = self.page.frame_all()?;
|
||||
pics.extend(crate::screen::pictures(&mut self.apps)?);
|
||||
Ok((px, pics))
|
||||
}
|
||||
|
||||
/// The page drawn at frame `f` of a composition at `fps`: its CSS animations and transitions where they are then.
|
||||
/// The page drawn at frame `f` of a composition at `fps`: its CSS animations and transitions where they are then,
|
||||
/// and its app screens stepped there.
|
||||
pub fn at_frame(&mut self, f: i64, fps: f64) {
|
||||
self.page.at_frame(f, fps);
|
||||
self.set_app_frame(f, fps);
|
||||
}
|
||||
|
||||
/// The frame the app screens step to at the next sync (live play, whose page keeps its own CSS clock).
|
||||
pub fn set_app_frame(&mut self, f: i64, fps: f64) {
|
||||
self.apps.frame = Some((f, fps));
|
||||
}
|
||||
|
||||
/// The page drawn and read back: premultiplied RGBA rows, `w` x `h`.
|
||||
@@ -276,9 +281,10 @@ impl BevyPage {
|
||||
&mut self.apps
|
||||
}
|
||||
|
||||
/// Each <Screen>'s picture as last drawn, by name: its texture on the shared device.
|
||||
/// Each <Screen>'s picture as last drawn, by name: its texture on the shared device (an app screen's too).
|
||||
pub fn screen_textures(&self) -> Vec<(String, wgpu::Texture)> {
|
||||
self.page.sub_textures().into_iter().map(|(k, t, _, _)| (k, (*t).clone())).collect()
|
||||
let apps = crate::screen::textures(&self.apps);
|
||||
self.page.sub_textures().into_iter().map(|(k, t, _, _)| (k, t)).chain(apps).map(|(k, t)| (k, (*t).clone())).collect()
|
||||
}
|
||||
|
||||
/// The page's picture as last drawn, on the shared device (`Rgba8UnormSrgb`, premultiplied).
|
||||
|
||||
+93
-35
@@ -5,28 +5,40 @@
|
||||
//! (engine/render/src/engine/screen.rs). A render's screen equals its play's, and a game on a screen plays live with the
|
||||
//! player's input (the nested game reads the same useInput).
|
||||
//!
|
||||
//! An app screen (`<Screen app="chat.tsx">`) shows a page of its own instead: the module's component on @raea/ui's
|
||||
//! react-dom in a raea-runtime-js root of its own. In live play the pointer reaches it through the 3D (`route`: the camera's
|
||||
//! ray to the screen, Engine::screen_at): a press on an app screen gives it the keys, which the game then doesn't get,
|
||||
//! until a press anywhere else or Escape.
|
||||
//! An app screen (`<Screen app="chat.tsx">`, docs/blitz-bevy.feature H12) shows a page of its own instead: the module's
|
||||
//! component on @raea/ui's react-dom in a Blitz document of its own (raea-runtime-appscreen), stepped once a frame
|
||||
//! (`step_all`, from the page's sync) and drawn into its picture, which goes to the 3D as a nested screen's does. In
|
||||
//! live play the pointer reaches it through the 3D (`route`: the camera's ray to the screen, Engine::screen_at): a
|
||||
//! press on an app screen gives it the keys, which the game then doesn't get, until a press anywhere else or Escape.
|
||||
//! What reached the app screens each frame goes in the input log (Routed::logged), and a render of the log gives them
|
||||
//! the same (`APP_LOG`), so the render draws what was played.
|
||||
|
||||
/// What an app's prebuilt bundle is called beside its module (`chat.tsx` -> `chat.tsx.surface.js`): an exported game's
|
||||
/// (game.rs gather).
|
||||
pub const BUNDLED: &str = ".surface.js";
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
/// The page's app screens: the input live play routed to them for their next step.
|
||||
use raea_runtime_appscreen::{AppScreen, Routed};
|
||||
use serde_json::Value;
|
||||
|
||||
/// What an app's prebuilt bundle is called beside its module (`chat.tsx` -> `chat.tsx.surface.js`, its CSS
|
||||
/// `chat.tsx.surface.css`): an exported game's (game.rs gather).
|
||||
pub use raea_runtime_appscreen::{BUNDLED, BUNDLED_CSS, build as build_app};
|
||||
|
||||
/// A render's input log, by frame: what reached the app screens in the play it logged (its `apps`), given them again
|
||||
/// in place of live play's routing. Set by `raea render --input`; None in play.
|
||||
pub static APP_LOG: std::sync::Mutex<Option<BTreeMap<i64, Value>>> = std::sync::Mutex::new(None);
|
||||
|
||||
/// The page's app screens: their documents, and the input live play routed to them for their next step.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Apps {
|
||||
/// each app screen's document, by name
|
||||
docs: HashMap<String, AppScreen>,
|
||||
/// the frame and fps the next step is at (BevyPage::at_frame, set_app_frame)
|
||||
pub(crate) frame: Option<(i64, f64)>,
|
||||
/// screens whose app didn't open, with the module (said once)
|
||||
pub(crate) failed: std::collections::HashMap<String, String>,
|
||||
/// the app screen the keys go to (the one last pressed on), and the keys held for it
|
||||
focus: Option<String>,
|
||||
keys: Vec<String>,
|
||||
/// where the pointer is on an app screen (its picture's pixels) and whether it's down
|
||||
pointer: Option<(String, f64, f64, bool)>,
|
||||
pub(crate) failed: HashMap<String, String>,
|
||||
/// what reaches them this frame: the focus and its keys, the pointer and the wheel
|
||||
pub(crate) r: Routed,
|
||||
/// whether the pointer was down last frame (a press is its going down)
|
||||
down: bool,
|
||||
/// the wheel's turns this frame (`Wheel:Y DY`), for the app screen under the pointer
|
||||
wheel: Vec<String>,
|
||||
}
|
||||
|
||||
/// Live play's input split between the page and its app screens: the pointer where it lands on an app screen (the
|
||||
@@ -37,55 +49,101 @@ pub fn route(page: &mut crate::BevyPage, engine: &mut raea_render::engine::Engin
|
||||
let apps = page.app_screens();
|
||||
let a = page.apps();
|
||||
if apps.is_empty() {
|
||||
a.focus = None;
|
||||
a.pointer = None;
|
||||
a.r.focus = None;
|
||||
a.r.pointer = None;
|
||||
return keys.to_vec();
|
||||
}
|
||||
let hit = pointer.and_then(|(x, y, _)| engine.screen_at(x / size.0.max(1) as f64, y / size.1.max(1) as f64));
|
||||
let on = hit.and_then(|(name, u, v)| apps.iter().find(|s| s.0 == name).map(|s| (name, u * s.1 as f64, v * s.2 as f64)));
|
||||
let down = pointer.is_some_and(|p| p.2);
|
||||
if down && !a.down {
|
||||
a.focus = on.as_ref().map(|o| o.0.clone());
|
||||
a.r.focus = on.as_ref().map(|o| o.0.clone());
|
||||
}
|
||||
a.down = down;
|
||||
a.pointer = on.map(|(name, x, y)| (name, x, y, down));
|
||||
let r = &mut a.r;
|
||||
r.pointer = on.map(|(name, x, y)| (name, x, y, down));
|
||||
// the wheel over an app screen scrolls it, and the page doesn't get it
|
||||
a.wheel.clear();
|
||||
let keys: Vec<String> = match &a.pointer {
|
||||
Some(_) => keys.iter().filter(|k| !(k.starts_with("Wheel:Y ") && { a.wheel.push(k.to_string()); true })).cloned().collect(),
|
||||
r.wheel.clear();
|
||||
let keys: Vec<String> = match &r.pointer {
|
||||
Some(_) => keys.iter().filter(|k| !(k.starts_with("Wheel:Y ") && { r.wheel.push(k.to_string()); true })).cloned().collect(),
|
||||
None => keys.to_vec(),
|
||||
};
|
||||
let keys = &keys[..];
|
||||
let (mine, page_keys): (Vec<String>, Vec<String>) = keys.iter().cloned().partition(|k| !(k.starts_with("feed:") || k.starts_with("action:") || k.starts_with("space:")));
|
||||
match &a.focus {
|
||||
match &r.focus {
|
||||
Some(_) if mine.iter().any(|k| k == "Escape") => {
|
||||
a.focus = None;
|
||||
a.keys.clear();
|
||||
r.focus = None;
|
||||
r.keys.clear();
|
||||
page_keys
|
||||
}
|
||||
Some(_) => {
|
||||
a.keys = mine;
|
||||
r.keys = mine;
|
||||
page_keys
|
||||
}
|
||||
None => {
|
||||
a.keys.clear();
|
||||
keys.to_vec()
|
||||
r.keys.clear();
|
||||
keys
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What reached the page's app screens this frame, for the input log (Routed::logged): None when nothing did.
|
||||
pub fn logged(page: &crate::BevyPage) -> Option<Value> {
|
||||
page.apps.r.logged()
|
||||
}
|
||||
|
||||
/// The app screens that went let go of: their focus, pointer and failures forgotten, so a screen back again opens
|
||||
/// fresh. `screens`: each app screen now, its name, size and module.
|
||||
pub(crate) fn retire(a: &mut Apps, screens: &[(String, u32, u32, String)]) {
|
||||
let now = |name: &str, app: &str| screens.iter().any(|s| s.0 == name && s.3 == app);
|
||||
a.failed.retain(|name, app| now(name, app));
|
||||
// a document goes with its screen, or when the screen shows another module or size (opened again fresh)
|
||||
a.docs.retain(|name, d| screens.iter().any(|s| &s.0 == name && s.3 == d.module && (s.1, s.2) == d.size));
|
||||
let shown = |name: &str| screens.iter().any(|s| s.0 == name);
|
||||
if a.focus.as_deref().is_some_and(|f| !shown(f)) {
|
||||
a.focus = None;
|
||||
a.keys.clear();
|
||||
if a.r.focus.as_deref().is_some_and(|f| !shown(f)) {
|
||||
a.r.focus = None;
|
||||
a.r.keys.clear();
|
||||
}
|
||||
if a.pointer.as_ref().is_some_and(|p| !shown(&p.0)) {
|
||||
a.pointer = None;
|
||||
if a.r.pointer.as_ref().is_some_and(|p| !shown(&p.0)) {
|
||||
a.r.pointer = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Each app screen stepped to the page's frame with its input (`dir`: the composition's folder, its modules' from),
|
||||
/// its document opened the first frame it's seen; one that won't open is said once and left blank.
|
||||
pub(crate) fn step_all(a: &mut Apps, screens: &[(String, u32, u32, String)], dir: &std::path::Path) {
|
||||
let (f, fps) = a.frame.unwrap_or((0, 30.0));
|
||||
if let Some(log) = APP_LOG.lock().unwrap().as_ref() {
|
||||
a.r = Routed::from_log(log.get(&f));
|
||||
}
|
||||
for (name, w, h, module) in screens {
|
||||
if a.failed.contains_key(name) || *w == 0 || *h == 0 {
|
||||
continue;
|
||||
}
|
||||
if !a.docs.contains_key(name) {
|
||||
match AppScreen::open(dir, module, *w, *h, f, fps, Some(raea_runtime_view::render_creation())) {
|
||||
Ok(d) => {
|
||||
a.docs.insert(name.clone(), d);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("raea: screen {name:?}: its app {module:?} didn't open: {e}");
|
||||
a.failed.insert(name.clone(), module.clone());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
let input = a.r.input_of(name);
|
||||
if let Some(d) = a.docs.get_mut(name) {
|
||||
d.step(f, fps, &input);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Each app screen's picture as last drawn, read back: its name, size and RGBA.
|
||||
pub(crate) fn pictures(a: &mut Apps) -> Result<Vec<(String, u32, u32, Vec<u8>)>, String> {
|
||||
a.docs.iter_mut().map(|(name, d)| Ok((name.clone(), d.size.0, d.size.1, d.rgba()?))).collect()
|
||||
}
|
||||
|
||||
/// Each app screen's picture as last drawn: its texture on the shared device.
|
||||
pub(crate) fn textures(a: &Apps) -> Vec<(String, bevy::render::render_resource::Texture)> {
|
||||
a.docs.iter().filter_map(|(name, d)| Some((name.clone(), d.texture()?))).collect()
|
||||
}
|
||||
@@ -15,6 +15,9 @@
|
||||
//! by zero. A frame reached by a jump is stepped to through the frames between, and a frame before the last stepped one
|
||||
//! reloads the edit and steps from 0, so a plugin's state at frame f is always f steps from the load, however f was
|
||||
//! reached (a render of one frame, a play, a seek).
|
||||
//!
|
||||
//! A load whose rows give the plugins nothing to carry from frame to frame (`steps` false) isn't stepped (#77): its
|
||||
//! clock is `pure`, and Time and the keyed rows are the frame drawn's, f / fps from 0, however it was reached (#162).
|
||||
|
||||
use std::any::TypeId;
|
||||
use std::collections::BTreeMap;
|
||||
@@ -92,6 +95,11 @@ pub struct PluginClock {
|
||||
pub dt: Duration,
|
||||
pub advancing: bool,
|
||||
pub steps: u64,
|
||||
/// the load gives the plugins nothing to step (`steps` false): nothing is stepped, and Time and the keyed rows are
|
||||
/// the frame drawn's however it was reached (pure_time, keyed_rows). Stepping only on the frame after the last
|
||||
/// stepped one froze them: a still at frame 200 sampled globals.time 0, and a batch's second frame drew the
|
||||
/// first's <Material> uniforms (#162)
|
||||
pub pure: bool,
|
||||
}
|
||||
|
||||
/// A mesh whose Transform a plugin owns (sync_meshes leaves it alone).
|
||||
@@ -200,7 +208,28 @@ fn install_list(app: &mut App, fps: f64, list: Vec<fn(&mut App)>) {
|
||||
}
|
||||
app.insert_resource(TimeUpdateStrategy::ManualDuration(Duration::ZERO));
|
||||
app.world_mut().resource_mut::<Time<Fixed>>().set_timestep(dt);
|
||||
app.insert_resource(PluginClock { stepped: 0, dt, advancing: false, steps: 0 });
|
||||
app.insert_resource(PluginClock { stepped: 0, dt, advancing: false, steps: 0, pure: false });
|
||||
app.add_systems(First, pure_time.after(bevy::time::TimeSystems));
|
||||
}
|
||||
|
||||
/// A pure clock's Time: the frame drawn's, f / fps from 0, whatever was drawn before it (a still alone, a batch's
|
||||
/// next frame, a seek back in live play); Time<Virtual> too, which the fixed loop copies back into Time. It moves by
|
||||
/// one step on an update that draws another frame than the last, and by none on the same frame drawn again.
|
||||
fn pure_time(clock: Option<Res<Clock>>, pc: Option<Res<PluginClock>>, mut virt: ResMut<Time<Virtual>>, mut time: ResMut<Time>, mut last: Local<Option<i64>>) {
|
||||
let (Some(f), Some(c)) = (clock, pc) else { return };
|
||||
if !c.pure {
|
||||
*last = None;
|
||||
return;
|
||||
}
|
||||
let f = f.0.max(0);
|
||||
let at = c.dt * u32::try_from(f).unwrap_or(u32::MAX);
|
||||
let step = if *last == Some(f) { Duration::ZERO } else { c.dt.min(at) };
|
||||
*last = Some(f);
|
||||
let mut v = Time::<Virtual>::default();
|
||||
v.advance_by(at - step);
|
||||
v.advance_by(step);
|
||||
*time = v.as_generic();
|
||||
*virt = v;
|
||||
}
|
||||
|
||||
pub fn active(world: &World) -> bool {
|
||||
@@ -228,6 +257,12 @@ pub fn steps(inserted: &[Tup]) -> bool {
|
||||
pub fn arm(world: &mut World) {
|
||||
let f = world.resource::<Clock>().0;
|
||||
let Some(mut c) = world.get_resource_mut::<PluginClock>() else { return };
|
||||
if c.pure {
|
||||
// nothing stepped: Time is the frame's (pure_time), and its real clock doesn't move
|
||||
c.advancing = false;
|
||||
world.insert_resource(TimeUpdateStrategy::ManualDuration(Duration::ZERO));
|
||||
return;
|
||||
}
|
||||
let step = f == c.stepped + 1;
|
||||
c.advancing = step;
|
||||
if std::env::var_os("RAEA_PLUGIN_TRACE").is_some() {
|
||||
@@ -244,12 +279,18 @@ pub fn arm(world: &mut World) {
|
||||
}
|
||||
|
||||
/// Keyed rows whose frame has come, set on the update that draws it (so a plugin's steps after it see them): with a
|
||||
/// plugin, on the frame its clock steps to; without one, on the frame drawn, whichever way it was reached.
|
||||
/// plugin that steps, on the frame its clock steps to; without one, or with a pure clock, on the frame drawn, whichever
|
||||
/// way it was reached.
|
||||
/// A live engine (a fed render's, live play's) takes them too: its frames' rows set the values that change
|
||||
/// (apply_live_rows), but a row held for its `from` never changes after the load, so nothing else sets it (a render to
|
||||
/// MP4 left a rigid body from frame 36 asleep for good). Each lands once, on its frame.
|
||||
fn keyed_rows(world: &mut World) {
|
||||
let f = match world.get_resource::<PluginClock>() {
|
||||
// a pure clock steps nothing: the frame drawn's rows, as without a plugin (#162)
|
||||
Some(c) if c.pure => match world.get_resource::<Clock>() {
|
||||
Some(c) => c.0,
|
||||
None => return,
|
||||
},
|
||||
Some(c) if !c.advancing => return,
|
||||
Some(c) => c.stepped,
|
||||
None => match world.get_resource::<Clock>() {
|
||||
|
||||
@@ -145,3 +145,62 @@ fn only_rows_a_plugin_carries_from_frame_to_frame_need_the_frames_before_a_still
|
||||
assert!(steps(&rows), "{more:?} needs its frames stepped");
|
||||
}
|
||||
}
|
||||
|
||||
/// A load with nothing to step (#77) has a pure clock: its keyed rows land on the frame drawn, not frozen until a step
|
||||
/// that never comes. A still at frame 200 alone drew none, and a batch's second frame drew the first's (#162)
|
||||
#[test]
|
||||
fn a_pure_clock_takes_each_frames_keyed_rows_however_it_was_reached() {
|
||||
let mut app = app();
|
||||
let w = app.world_mut();
|
||||
let a = w.spawn_empty().id();
|
||||
let ty = "bevy_transform::components::transform::Transform".to_string();
|
||||
let rows = [0, 60, 200].map(|f| (Some(a), ty.clone(), json!({"translation": [f as f64, 0.0, 0.0]}), f)).to_vec();
|
||||
w.insert_resource(Keyed { rows, ..default() });
|
||||
w.insert_resource(Error(None));
|
||||
w.insert_resource(PluginClock { stepped: 0, dt: Duration::from_secs_f64(1.0 / 30.0), advancing: false, steps: 0, pure: true });
|
||||
let x = |w: &World| w.get::<Transform>(a).map(|t| t.translation.x);
|
||||
for (f, want) in [(200, 200.0), (60, 60.0), (61, 60.0), (200, 200.0), (0, 0.0)] {
|
||||
w.insert_resource(Clock(f));
|
||||
arm(w);
|
||||
keyed_rows(w);
|
||||
assert_eq!(x(w), Some(want), "frame {f}");
|
||||
}
|
||||
// a clock that steps still holds them for its step (a plugin's state needs them on the update it steps)
|
||||
w.resource_mut::<PluginClock>().pure = false;
|
||||
w.insert_resource(Clock(200));
|
||||
arm(w);
|
||||
keyed_rows(w);
|
||||
assert_eq!(x(w), Some(0.0), "held: 200 isn't the frame after the last stepped");
|
||||
}
|
||||
|
||||
/// A pure clock's Time is the frame's, f / fps, in any order: what globals.time and a shader's animation read (#162)
|
||||
#[test]
|
||||
fn a_pure_clocks_time_is_the_frame_drawns() {
|
||||
let mut app = App::new();
|
||||
app.add_plugins(bevy::time::TimePlugin);
|
||||
app.insert_resource(TimeUpdateStrategy::ManualDuration(Duration::ZERO));
|
||||
app.add_systems(First, pure_time.after(bevy::time::TimeSystems));
|
||||
// what reads Time in Update, after the fixed loop has copied Time<Virtual> back into it
|
||||
#[derive(Resource, Default)]
|
||||
struct Seen(Vec<(f64, f64)>);
|
||||
app.init_resource::<Seen>();
|
||||
app.add_systems(Update, |t: Res<Time>, mut s: ResMut<Seen>| s.0.push((t.elapsed_secs_f64(), t.delta_secs_f64())));
|
||||
let dt = Duration::from_secs_f64(1.0 / 30.0);
|
||||
app.insert_resource(PluginClock { stepped: 0, dt, advancing: false, steps: 0, pure: true });
|
||||
fn at(app: &mut App, f: i64) -> (f64, f64) {
|
||||
app.insert_resource(Clock(f));
|
||||
arm(app.world_mut());
|
||||
app.update();
|
||||
*app.world().resource::<Seen>().0.last().unwrap()
|
||||
}
|
||||
let near = |(t, d): (f64, f64), want: (f64, f64)| (t - want.0).abs() < 1e-6 && (d - want.1).abs() < 1e-6;
|
||||
let step = 1.0 / 30.0;
|
||||
for (f, want) in [(60, (2.0, step)), (60, (2.0, 0.0)), (200, (200.0 / 30.0, step)), (61, (61.0 / 30.0, step)), (0, (0.0, 0.0)), (1, (step, step))] {
|
||||
let got = at(&mut app, f);
|
||||
assert!(near(got, want), "frame {f}: Time {got:?}, want {want:?}");
|
||||
}
|
||||
// a clock that steps is left to its steps
|
||||
app.world_mut().resource_mut::<PluginClock>().pure = false;
|
||||
let held = at(&mut app, 500);
|
||||
assert!(held.0 < 1.0, "a stepping clock's Time isn't set to the frame's: {held:?}");
|
||||
}
|
||||
@@ -8,6 +8,7 @@ export * from "./fingers";
|
||||
export * from "./captured";
|
||||
export * from "./solve";
|
||||
export * from "./face";
|
||||
export * from "./eyes";
|
||||
export * from "./hair";
|
||||
export * from "./skin";
|
||||
export * from "./drawing";
|
||||
|
||||
@@ -6,7 +6,7 @@ import { SKIN_LOOK, SKIN_SURFACE, SKIN_WESL, type SkinLook, type SkinSurface } f
|
||||
import { ExtendedMaterial, LinearRgba, ShaderExtension, Srgba, StandardMaterial } from "@raea/render/bevy3d";
|
||||
import type { Glitch } from "@raea/physics/physics";
|
||||
import { staticFile } from "@raea/video/media";
|
||||
import { Goals, Pose, Side, Skeleton, add, eulerXYZ, faceWeights, pose, qmul, qrot, qyaw, rest, scale3, skinJoints, solve, sub, type Face } from "./all";
|
||||
import { Goals, Pose, Side, Skeleton, add, eulerXYZ, eyesTo, faceWeights, lidsFor, pose, qmul, qrot, qyaw, rest, scale3, skinJoints, solve, sub, type Face } from "./all";
|
||||
|
||||
// ---------------------------------------------------------------- placement
|
||||
|
||||
@@ -81,6 +81,11 @@ export interface CharacterProps extends Placement {
|
||||
* "mouth-open", "eyebrows-left-up" ...) and presets mixed from them (FACE_PRESETS: blink, smile, frown, surprise,
|
||||
* sad, and the lips' open, pucker and wide), 0 to 1; they add */
|
||||
face?: Face;
|
||||
/** a point in the scene the eyes turn to (character/eyes.ts): each eye joint turned to it on top of the pose, no
|
||||
* further than an eye goes (35 degrees to a side, 17 up, 25 down), so the eyes cover what the head has not turned.
|
||||
* For a body whose head has eye joints (SOMA's LeftEye and RightEye, which a generated head's eyes follow); a part
|
||||
* that has those joints has its upper lids ride the eyes down (its blink_left and blink_right morphs raised) */
|
||||
gaze?: Vec3;
|
||||
/** the hair drawn as hair (character/hair.ts: strand highlights on the body's "hair" material, after lighting): on by
|
||||
* default, false for the plain surface, or settings over HAIR_LOOK; `coverage: true` softens the cards' cut edges
|
||||
* (alphaMode "coverage", for a scene with <AntiAliasing mode="msaa">: without MSAA the cards draw solid); `color`
|
||||
@@ -175,6 +180,7 @@ export function Character(props: CharacterProps) {
|
||||
const k = at.scale ?? 1;
|
||||
let p = props.pose ?? rest(skel);
|
||||
if (props.goals) p = solve(skel, p, goalsToBody(at, props.goals));
|
||||
if (props.gaze) p = eyesTo(skel, p, toBody(at, props.gaze));
|
||||
const w = pose(skel, p);
|
||||
const turn = qyaw(at.yaw ?? 0);
|
||||
// the skin stands at the origin scaled by k, so its joints go where they are in the scene over k
|
||||
@@ -199,8 +205,11 @@ export function Character(props: CharacterProps) {
|
||||
</Model>
|
||||
{(props.parts ?? []).map((part) => {
|
||||
const id = part.src.split("/").pop()!.replace(/\.glb$/, "");
|
||||
// (a head's lids ride its eyes down: character/eyes.ts)
|
||||
const lids = props.gaze && part.joints?.some((j) => j === "LeftEye" || j === "eye_l") ? lidsFor(skel, p) : 0;
|
||||
const pm = lids > 0 ? { ...part.morphs, blink_left: Math.min(1, (part.morphs?.blink_left ?? 0) + lids), blink_right: Math.min(1, (part.morphs?.blink_right ?? 0) + lids) } : part.morphs;
|
||||
return (
|
||||
<Model key={id} name={`${name}-${id}`} src={part.src} bones={part.joints ? Object.fromEntries(part.joints.filter((j) => j in bones).map((j) => [j, bones[j]])) : bones} scale={k} {...(glitch ? { glitch } : {})} {...pass} {...(part.morphs && Object.keys(part.morphs).length ? { morphs: part.morphs } : {})} {...(part.cloth ? { cloth: part.cloth } : {})}>
|
||||
<Model key={id} name={`${name}-${id}`} src={part.src} bones={part.joints ? Object.fromEntries(part.joints.filter((j) => j in bones).map((j) => [j, bones[j]])) : bones} scale={k} {...(glitch ? { glitch } : {})} {...pass} {...(pm && Object.keys(pm).length ? { morphs: pm } : {})} {...(part.cloth ? { cloth: part.cloth } : {})}>
|
||||
{part.children}
|
||||
{id.includes("hair") && props.hair !== false && hairMaterial(props.hair)}
|
||||
</Model>
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
// The eyes' look target (docs/character.feature CH20c): each eye joint turned to a point, within what an eye does,
|
||||
// on top of whatever the body's motion has done with the neck and head. A head part's eyes are skinned to SOMA's
|
||||
// LeftEye and RightEye joints (a creature's eye_l and eye_r), which no clip turns: this is what turns them.
|
||||
import { I, norm, qaxis, qinv, qmul, qrot, sub, pose, type Pose, type Quat, type Skeleton, type Vec3 } from "./all";
|
||||
|
||||
/** how far an eye turns from straight ahead in its head, radians: to a side, up and down. (Up is the least: a head's
|
||||
* upper lid has no morph that lifts it, and at 25 degrees up the iris went under it.) */
|
||||
export const EYE_RANGE = { side: 0.61, up: 0.3, down: 0.44 };
|
||||
const EYES = [["LeftEye", "RightEye"], ["eye_l", "eye_r"]];
|
||||
|
||||
/** A pose with its eyes turned to `target` (a point in the body's frame), each no further than `range` from straight
|
||||
* ahead in the head: past that the eye stops at its limit, and the rest is the head's to turn. A body with no eye
|
||||
* joints comes back as it was. */
|
||||
export function eyesTo(skel: Skeleton, p: Pose, target: Vec3, range = EYE_RANGE): Pose {
|
||||
const idx = (n: string) => skel.joints.findIndex((j) => j.name === n);
|
||||
const eyes = (EYES.find((pair) => pair.every((n) => idx(n) >= 0)) ?? []).map(idx);
|
||||
if (!eyes.length) return p;
|
||||
const turns: Quat[] = skel.joints.map((_, j) => p.turns[j] ?? I);
|
||||
const w = pose(skel, { root: p.root, turns });
|
||||
const clamp = (v: number, lim: number) => Math.max(-lim, Math.min(lim, v));
|
||||
for (const i of eyes) {
|
||||
// the way to the target in the head's own frame (the eye's parent): at rest an eye looks along +z
|
||||
const d = qrot(qinv(w.rot[skel.joints[i].parent]), norm(sub(target, w.pos[i])));
|
||||
const side = clamp(Math.atan2(d[0], d[2]), range.side), up = Math.max(-range.down, Math.min(range.up, Math.atan2(d[1], Math.hypot(d[0], d[2]))));
|
||||
turns[i] = qmul(qaxis([0, 1, 0], side), qaxis([1, 0, 0], -up));
|
||||
}
|
||||
return { root: p.root, turns };
|
||||
}
|
||||
|
||||
/** How far the upper lids come down with the eyes in a pose (0 to 1 of a blink): a lid rides its eye, so eyes
|
||||
* turned all the way down lower it to `most` of shut, and eyes level or raised leave it open. For the head's
|
||||
* blink_left and blink_right morphs, added to whatever blink it has. */
|
||||
export function lidsFor(skel: Skeleton, p: Pose, most = 0.45, range = EYE_RANGE): number {
|
||||
const i = skel.joints.findIndex((j) => j.name === "LeftEye" || j.name === "eye_l"), q = i >= 0 ? p.turns[i] : undefined;
|
||||
if (!q) return 0;
|
||||
// how far below level the eye's own +z points, in its head's frame
|
||||
const down = Math.asin(Math.max(-1, Math.min(1, 2 * (q[3] * q[0] - q[1] * q[2]))));
|
||||
return Math.max(0, Math.min(1, down / range.down)) * most;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// The eyes' look target (src/character/eyes.ts, docs/character.feature CH20c): the eye joints turned to a point within
|
||||
// an eye's range, on top of the head's turn, and the lids riding the eyes down.
|
||||
import { expect, test } from "bun:test";
|
||||
import { EYE_RANGE, eyesTo, lidsFor, pose, qaxis, qrot, type Pose, type Skeleton } from "../src/character/all";
|
||||
|
||||
const J = (name: string, parent: number, head: [number, number, number]) => ({ name, parent, head, tail: [head[0], head[1] + 0.02, head[2]] as [number, number, number] });
|
||||
const skel = { name: "t", height: 1.7, joints: [J("Hips", -1, [0, 1, 0]), J("Head", 0, [0, 1.6, 0]), J("LeftEye", 1, [0.03, 1.65, 0.06]), J("RightEye", 1, [-0.03, 1.65, 0.06])] } as unknown as Skeleton;
|
||||
const rest: Pose = { root: [0, 1, 0], turns: skel.joints.map(() => [0, 0, 0, 1]) };
|
||||
const ahead = (p: Pose, i: number) => qrot(pose(skel, p).rot[i], [0, 0, 1]);
|
||||
const angle = (a: number[], b: number[]) => Math.acos(Math.min(1, a[0] * b[0] + a[1] * b[1] + a[2] * b[2]));
|
||||
|
||||
test("each eye points at a target within its range", () => {
|
||||
const t: [number, number, number] = [0.4, 1.75, 1.5], p = eyesTo(skel, rest, t);
|
||||
for (const i of [2, 3]) {
|
||||
const e = skel.joints[i].head, d = [t[0] - e[0], t[1] - e[1], t[2] - e[2]], l = Math.hypot(...d);
|
||||
expect(angle(ahead(p, i), d.map((v) => v / l))).toBeLessThan(1e-3);
|
||||
}
|
||||
});
|
||||
|
||||
test("past its range an eye stops: 35 degrees to a side, 17 up, 25 down", () => {
|
||||
const side = ahead(eyesTo(skel, rest, [9, 1.65, 0.06]), 2), up = ahead(eyesTo(skel, rest, [0.03, 9, 0.5]), 2), down = ahead(eyesTo(skel, rest, [0.03, -9, 0.5]), 2);
|
||||
expect(Math.atan2(side[0], side[2])).toBeCloseTo(EYE_RANGE.side, 4);
|
||||
expect(Math.asin(up[1])).toBeCloseTo(EYE_RANGE.up, 4);
|
||||
expect(Math.asin(-down[1])).toBeCloseTo(EYE_RANGE.down, 4);
|
||||
});
|
||||
|
||||
test("the eyes cover what the head has not turned", () => {
|
||||
// the head turned 20 degrees to its left, the target straight ahead of the body: the eyes turn back toward it
|
||||
const turned: Pose = { root: rest.root, turns: [rest.turns[0], qaxis([0, 1, 0], 0.35), rest.turns[2], rest.turns[3]] };
|
||||
const w = pose(skel, turned), t: [number, number, number] = [0, 1.65, 3], p = eyesTo(skel, turned, t);
|
||||
const d = [t[0] - w.pos[2][0], t[1] - w.pos[2][1], t[2] - w.pos[2][2]], l = Math.hypot(...d);
|
||||
expect(angle(ahead(p, 2), d.map((v) => v / l))).toBeLessThan(1e-3);
|
||||
});
|
||||
|
||||
test("the lids come down with the eyes, and stay up otherwise", () => {
|
||||
expect(lidsFor(skel, rest)).toBe(0);
|
||||
expect(lidsFor(skel, eyesTo(skel, rest, [0.03, 9, 0.5]))).toBe(0);
|
||||
expect(lidsFor(skel, eyesTo(skel, rest, [0.03, -9, 0.5]))).toBeCloseTo(0.45, 3);
|
||||
expect(eyesTo({ ...skel, joints: skel.joints.slice(0, 2) } as Skeleton, rest, [0, 0, 1])).toBe(rest);
|
||||
});
|
||||
Loaded 100 of 207 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user