mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 15:53:26 -10:00
Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0426a01e82 | ||
|
|
02f9cf3e6b | ||
|
|
33f7257e47 | ||
|
|
2921f44e5c | ||
|
|
1e91511f93 | ||
|
|
daf0231c0c | ||
|
|
92adc524ca | ||
|
|
9f0e0ebc96 | ||
|
|
a911bcc165 | ||
|
|
5bedfa4d11 | ||
|
|
e52af0cee0 | ||
|
|
fbdba0e545 | ||
|
|
6cdab6b95d | ||
|
|
e92faf763d | ||
|
|
305c36fb25 | ||
|
|
fc9e69a7a7 | ||
|
|
c9525d76c4 | ||
|
|
451922c217 | ||
|
|
92ea594a2a |
No files matched your search
@@ -20,9 +20,7 @@ pub fn load_demo(file_name: &str) -> DocumentMessageHandler {
|
|||||||
DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {path}: {e:?}"))
|
DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {path}: {e:?}"))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Dev tool for the flip: runs each demo through the full open-time migration and writes the
|
/// Dev tool: writes each demo's migrated re-save into the directory named by `DEMO_OUT`, leaving the checked-in originals untouched.
|
||||||
/// re-saved form into the directory named by `DEMO_OUT`, so the CLI can render migrated copies
|
|
||||||
/// while the checked-in originals stay pristine until the flip's re-save.
|
|
||||||
#[test]
|
#[test]
|
||||||
#[ignore = "dev tool: set DEMO_OUT and run explicitly"]
|
#[ignore = "dev tool: set DEMO_OUT and run explicitly"]
|
||||||
fn migrate_demo_artwork_into_demo_out() {
|
fn migrate_demo_artwork_into_demo_out() {
|
||||||
|
|||||||
@@ -576,7 +576,7 @@ mod test_artboard {
|
|||||||
|
|
||||||
/// A leveled wire introspects as its whole legacy list, so each `extend`
|
/// A leveled wire introspects as its whole legacy list, so each `extend`
|
||||||
/// occurrence yields one list rather than one element.
|
/// occurrence yields one list rather than one element.
|
||||||
async fn get_artboards(editor: &mut EditorTestUtils) -> List<Artboard> {
|
async fn get_artboards(editor: &mut EditorTestUtils) -> List<Artboard<'_>> {
|
||||||
let instrumented = match editor.eval_graph().await {
|
let instrumented = match editor.eval_graph().await {
|
||||||
Ok(instrumented) => instrumented,
|
Ok(instrumented) => instrumented,
|
||||||
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
||||||
|
|||||||
@@ -208,8 +208,7 @@ mod test_fill {
|
|||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
use graphene_std::vector::fill;
|
use graphene_std::vector::fill;
|
||||||
|
|
||||||
/// Paint inputs are single-typed now, so the monitored wire carries the
|
/// The monitored fill wire carries `Color`; the `Graphic` conversion sits downstream of the monitor.
|
||||||
/// colors themselves and the `Graphic` conversion sits downstream of it.
|
|
||||||
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Color> {
|
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Color> {
|
||||||
let instrumented = match editor.eval_graph().await {
|
let instrumented = match editor.eval_graph().await {
|
||||||
Ok(instrumented) => instrumented,
|
Ok(instrumented) => instrumented,
|
||||||
|
|||||||
@@ -179,6 +179,8 @@ impl Spawner for WasmSpawner {
|
|||||||
impl NodeRuntime {
|
impl NodeRuntime {
|
||||||
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>) -> Self {
|
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>) -> Self {
|
||||||
#[cfg(not(target_family = "wasm"))]
|
#[cfg(not(target_family = "wasm"))]
|
||||||
|
// The box is a trait object, so `Box::default()` cannot name the concrete spawner.
|
||||||
|
#[allow(clippy::box_default)]
|
||||||
let spawner: Box<DynSpawner> = Box::new(TokioSpawner::new());
|
let spawner: Box<DynSpawner> = Box::new(TokioSpawner::new());
|
||||||
#[cfg(target_family = "wasm")]
|
#[cfg(target_family = "wasm")]
|
||||||
let spawner: Box<DynSpawner> = Box::new(WasmSpawner);
|
let spawner: Box<DynSpawner> = Box::new(WasmSpawner);
|
||||||
@@ -544,10 +546,10 @@ impl NodeRuntime {
|
|||||||
Some(())
|
Some(())
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
if result.is_err() {
|
if let Err(_error) = result {
|
||||||
// TODO: Fix the root of the issue causing the spam of this warning (this at least temporarily disables it in release builds)
|
// TODO: Fix the root of the issue causing the spam of this warning (this at least temporarily disables it in release builds)
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
warn!("Failed to introspect monitor node {}", result.unwrap_err());
|
warn!("Failed to introspect monitor node {}", _error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,10 +7,10 @@ use core_types::color::SRGBA8;
|
|||||||
use core_types::context::Context;
|
use core_types::context::Context;
|
||||||
use core_types::gpoll::GPoll;
|
use core_types::gpoll::GPoll;
|
||||||
use core_types::list::List;
|
use core_types::list::List;
|
||||||
use core_types::registry::EdgeHandle;
|
use core_types::registry::SourceHandle;
|
||||||
use core_types::transform::Footprint;
|
use core_types::transform::Footprint;
|
||||||
use core_types::uuid::NodeId;
|
use core_types::uuid::NodeId;
|
||||||
use core_types::value::{leveled_record_value_edge, record_value_edge};
|
use core_types::value::{leveled_record_value_source, record_value_source};
|
||||||
use core_types::{CacheHash, Color, ContextModification, MemoHash, Type, TypeDescriptor};
|
use core_types::{CacheHash, Color, ContextModification, MemoHash, Type, TypeDescriptor};
|
||||||
use dyn_any::DynAny;
|
use dyn_any::DynAny;
|
||||||
pub use dyn_any::StaticType;
|
pub use dyn_any::StaticType;
|
||||||
@@ -310,12 +310,12 @@ macro_rules! tagged_value {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Materializes the value as [`Self::to_dynany`] does, wrapped in a value source typed by [`Self::ty`].
|
/// Materializes the value as [`Self::to_dynany`] does, wrapped in a value source typed by [`Self::ty`].
|
||||||
pub fn to_edge(self) -> Result<EdgeHandle, String> {
|
pub fn to_edge(self) -> Result<SourceHandle, String> {
|
||||||
match self {
|
match self {
|
||||||
// ===============
|
// ===============
|
||||||
// MANUAL VARIANTS
|
// MANUAL VARIANTS
|
||||||
// ===============
|
// ===============
|
||||||
Self::None => Ok(record_value_edge(())),
|
Self::None => Ok(record_value_source(())),
|
||||||
Self::TypeDefault(td) => {
|
Self::TypeDefault(td) => {
|
||||||
let name = td.name.as_ref();
|
let name = td.name.as_ref();
|
||||||
// The list-typed defaults serve an empty level; the rest construct
|
// The list-typed defaults serve an empty level; the rest construct
|
||||||
@@ -323,7 +323,7 @@ macro_rules! tagged_value {
|
|||||||
macro_rules! check_level {
|
macro_rules! check_level {
|
||||||
($list:ty, $element:ty) => {
|
($list:ty, $element:ty) => {
|
||||||
if name == core_types::normalize_type_name(std::any::type_name::<$list>()) {
|
if name == core_types::normalize_type_name(std::any::type_name::<$list>()) {
|
||||||
return Ok(leveled_record_value_edge(Vec::<$element>::new()));
|
return Ok(leveled_record_value_source(Vec::<$element>::new()));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -332,51 +332,51 @@ macro_rules! tagged_value {
|
|||||||
check_level!(List<Raster<CPU>>, Raster<CPU>);
|
check_level!(List<Raster<CPU>>, Raster<CPU>);
|
||||||
// One default lane rather than an empty level: an unwired path input
|
// One default lane rather than an empty level: an unwired path input
|
||||||
// starts from a blank vector, as the legacy path modify synthesized itself.
|
// starts from a blank vector, as the legacy path modify synthesized itself.
|
||||||
if name == core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) { return Ok(leveled_record_value_edge(vec![Vector::default()])); }
|
if name == core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) { return Ok(leveled_record_value_source(vec![Vector::default()])); }
|
||||||
check_level!(List<String>, String);
|
check_level!(List<String>, String);
|
||||||
if name == core_types::normalize_type_name(std::any::type_name::<DocumentNode>()) { return Ok(record_value_edge(DocumentNode::default())); }
|
if name == core_types::normalize_type_name(std::any::type_name::<DocumentNode>()) { return Ok(record_value_source(DocumentNode::default())); }
|
||||||
if name == core_types::normalize_type_name(std::any::type_name::<Resource>()) { return Ok(record_value_edge(Resource::default())); }
|
if name == core_types::normalize_type_name(std::any::type_name::<Resource>()) { return Ok(record_value_source(Resource::default())); }
|
||||||
Self::from_type_or_none(&Type::Concrete(td)).to_edge()
|
Self::from_type_or_none(&Type::Concrete(td)).to_edge()
|
||||||
}
|
}
|
||||||
Self::F64Array(values) => Ok(leveled_record_value_edge(values)),
|
Self::F64Array(values) => Ok(leveled_record_value_source(values)),
|
||||||
Self::Color(color) => Ok(leveled_record_value_edge(color.into_iter().collect::<Vec<_>>())),
|
Self::Color(color) => Ok(leveled_record_value_source(color.into_iter().collect::<Vec<_>>())),
|
||||||
Self::Gradient(stops) => Ok(leveled_record_value_edge(vec![stops])),
|
Self::Gradient(stops) => Ok(leveled_record_value_source(vec![stops])),
|
||||||
Self::BrushStrokes(strokes) => Ok(leveled_record_value_edge(strokes)),
|
Self::BrushStrokes(strokes) => Ok(leveled_record_value_source(strokes)),
|
||||||
// =======================
|
// =======================
|
||||||
// AUTO-GENERATED VARIANTS
|
// AUTO-GENERATED VARIANTS
|
||||||
// =======================
|
// =======================
|
||||||
$( Self::$identifier(x) => Ok(record_value_edge(x)), )*
|
$( Self::$identifier(x) => Ok(record_value_source(x)), )*
|
||||||
// =======================
|
// =======================
|
||||||
// NON-SERIALIZED VARIANTS
|
// NON-SERIALIZED VARIANTS
|
||||||
// =======================
|
// =======================
|
||||||
Self::RenderOutput(x) => Ok(record_value_edge(x)),
|
Self::RenderOutput(x) => Ok(record_value_source(x)),
|
||||||
Self::NodeIdPath(path) => Ok(record_value_edge(path)),
|
Self::NodeIdPath(path) => Ok(record_value_source(path)),
|
||||||
Self::DocumentNode(node) => Ok(record_value_edge(node)),
|
Self::DocumentNode(node) => Ok(record_value_source(node)),
|
||||||
Self::ContextModification(modification) => Ok(record_value_edge(modification)),
|
Self::ContextModification(modification) => Ok(record_value_source(modification)),
|
||||||
Self::EditorApi(x) => Ok(record_value_edge(x)),
|
Self::EditorApi(x) => Ok(record_value_source(x)),
|
||||||
Self::ResourceHash(x) => Ok(record_value_edge(x)),
|
Self::ResourceHash(x) => Ok(record_value_source(x)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluates a typed source and converts the landed value into a tagged value, with the coverage of [`Self::try_from_any`].
|
/// Evaluates a typed source and converts the landed value into a tagged value, with the coverage of [`Self::try_from_any`].
|
||||||
pub fn from_edge<'f>(handle: EdgeHandle, ctx: &Context<'f>, frames: &core_types::record::Frames<'f>) -> Result<GPoll<Self>, String> {
|
pub fn from_edge<'f>(handle: SourceHandle, ctx: &Context<'f>, frames: &core_types::record::Frames<'f>) -> Result<GPoll<Self>, String> {
|
||||||
let ty = handle.ty().clone();
|
let ty = handle.ty().clone();
|
||||||
// =======================
|
// =======================
|
||||||
// RECORD WIRES, WHICH LAND AS THEIR ELEMENT
|
// RECORD WIRES, WHICH LAND AS THEIR ELEMENT
|
||||||
// =======================
|
// =======================
|
||||||
if ty == core_types::registry::record_edge_type::<()>() {
|
if ty == core_types::registry::record_source_type::<()>() {
|
||||||
let edge = handle.downcast_record::<()>().map_err(|e| format!("{e:?}"))?;
|
let edge = handle.downcast_record::<()>().map_err(|e| format!("{e:?}"))?;
|
||||||
return Ok(core_types::record::serve_input(&edge, ctx, frames).map(|_| TaggedValue::None));
|
return Ok(core_types::record::serve_input(&edge, ctx, frames).map(|_| TaggedValue::None));
|
||||||
}
|
}
|
||||||
$(
|
$(
|
||||||
if ty == core_types::registry::record_edge_type::<$ty>() {
|
if ty == core_types::registry::record_source_type::<$ty>() {
|
||||||
let layout = handle.layout().clone();
|
let layout = handle.layout().clone();
|
||||||
let edge = handle.downcast_record::<$ty>().map_err(|e| format!("{e:?}"))?;
|
let edge = handle.downcast_record::<$ty>().map_err(|e| format!("{e:?}"))?;
|
||||||
return Ok(core_types::record::serve_input(&edge, ctx, frames)
|
return Ok(core_types::record::serve_input(&edge, ctx, frames)
|
||||||
.map(|value| TaggedValue::$identifier(unsafe { core_types::record::read_element::<$ty>(layout.rec(&value)) })));
|
.map(|value| TaggedValue::$identifier(unsafe { core_types::record::read_element::<$ty>(layout.rec(&value)) })));
|
||||||
}
|
}
|
||||||
)*
|
)*
|
||||||
if ty == core_types::registry::record_edge_type::<RenderOutput>() {
|
if ty == core_types::registry::record_source_type::<RenderOutput>() {
|
||||||
let layout = handle.layout().clone();
|
let layout = handle.layout().clone();
|
||||||
let edge = handle.downcast_record::<RenderOutput>().map_err(|e| format!("{e:?}"))?;
|
let edge = handle.downcast_record::<RenderOutput>().map_err(|e| format!("{e:?}"))?;
|
||||||
return Ok(core_types::record::serve_input(&edge, ctx, frames)
|
return Ok(core_types::record::serve_input(&edge, ctx, frames)
|
||||||
@@ -919,27 +919,27 @@ mod typedefault_dispatch {
|
|||||||
mod leveled_edges {
|
mod leveled_edges {
|
||||||
use super::*;
|
use super::*;
|
||||||
use core_types::descriptor;
|
use core_types::descriptor;
|
||||||
use core_types::registry::record_edge_type;
|
use core_types::registry::record_source_type;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn list_variants_produce_leveled_edges_typed_by_element() {
|
fn list_variants_produce_leveled_edges_typed_by_element() {
|
||||||
let edge = TaggedValue::F64Array(vec![1., 2., 3.]).to_edge().unwrap();
|
let edge = TaggedValue::F64Array(vec![1., 2., 3.]).to_edge().unwrap();
|
||||||
assert_eq!(edge.ty(), &record_edge_type::<f64>());
|
assert_eq!(edge.ty(), &record_source_type::<f64>());
|
||||||
assert_eq!(edge.layout().depth, 1);
|
assert_eq!(edge.layout().depth, 1);
|
||||||
|
|
||||||
let edge = TaggedValue::Color(Some(Color::default())).to_edge().unwrap();
|
let edge = TaggedValue::Color(Some(Color::default())).to_edge().unwrap();
|
||||||
assert_eq!(edge.ty(), &record_edge_type::<Color>());
|
assert_eq!(edge.ty(), &record_source_type::<Color>());
|
||||||
assert_eq!(edge.layout().depth, 1);
|
assert_eq!(edge.layout().depth, 1);
|
||||||
|
|
||||||
let edge = TaggedValue::TypeDefault(descriptor!(List<Graphic>)).to_edge().unwrap();
|
let edge = TaggedValue::TypeDefault(descriptor!(List<Graphic>)).to_edge().unwrap();
|
||||||
assert_eq!(edge.ty(), &record_edge_type::<Graphic>());
|
assert_eq!(edge.ty(), &record_source_type::<Graphic>());
|
||||||
assert_eq!(edge.layout().depth, 1);
|
assert_eq!(edge.layout().depth, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn scalar_variants_keep_their_rank_zero_edges() {
|
fn scalar_variants_keep_their_rank_zero_edges() {
|
||||||
let edge = TaggedValue::Bool(true).to_edge().unwrap();
|
let edge = TaggedValue::Bool(true).to_edge().unwrap();
|
||||||
assert_eq!(edge.ty(), &record_edge_type::<bool>());
|
assert_eq!(edge.ty(), &record_source_type::<bool>());
|
||||||
assert_eq!(edge.layout().depth, 0);
|
assert_eq!(edge.layout().depth, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -961,7 +961,7 @@ mod leveled_edges {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod record_defaults {
|
mod record_defaults {
|
||||||
use super::*;
|
use super::*;
|
||||||
use core_types::registry::record_edge_type;
|
use core_types::registry::record_source_type;
|
||||||
|
|
||||||
// The registry can present a record row first (wasm registration order),
|
// The registry can present a record row first (wasm registration order),
|
||||||
// so primitive defaults must parse through the record wrapping.
|
// so primitive defaults must parse through the record wrapping.
|
||||||
@@ -969,7 +969,7 @@ mod record_defaults {
|
|||||||
fn primitive_defaults_parse_through_record_wires() {
|
fn primitive_defaults_parse_through_record_wires() {
|
||||||
let leveled = core_types::registry::record_type::<f64>();
|
let leveled = core_types::registry::record_type::<f64>();
|
||||||
assert_eq!(TaggedValue::from_primitive_string("2.", &leveled), Some(TaggedValue::F64(2.)));
|
assert_eq!(TaggedValue::from_primitive_string("2.", &leveled), Some(TaggedValue::F64(2.)));
|
||||||
assert_eq!(TaggedValue::from_primitive_string("5", &record_edge_type::<u32>()), Some(TaggedValue::U32(5)));
|
assert_eq!(TaggedValue::from_primitive_string("5", &record_source_type::<u32>()), Some(TaggedValue::U32(5)));
|
||||||
assert_eq!(TaggedValue::from_primitive_string("true", &record_edge_type::<bool>()), Some(TaggedValue::Bool(true)));
|
assert_eq!(TaggedValue::from_primitive_string("true", &record_source_type::<bool>()), Some(TaggedValue::Bool(true)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1041,7 +1041,6 @@ fn valid_type(from: &Type, to: &Type) -> bool {
|
|||||||
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
|
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
|
||||||
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
|
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
|
||||||
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
|
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
|
||||||
// A lend input is substitutable exactly when the lent values are.
|
|
||||||
// A record input is substitutable exactly when the elements are.
|
// A record input is substitutable exactly when the elements are.
|
||||||
(Type::Record(in1), Type::Record(in2)) => valid_type(in1, in2),
|
(Type::Record(in1), Type::Record(in2)) => valid_type(in1, in2),
|
||||||
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
|
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use crate::node_registry;
|
|||||||
use core_types::arena::Arena;
|
use core_types::arena::Arena;
|
||||||
use core_types::context::{ContextImpl, DynSlot, EvalScope, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, VarArg, VarArgLink, VarArgSlots};
|
use core_types::context::{ContextImpl, DynSlot, EvalScope, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, VarArg, VarArgLink, VarArgSlots};
|
||||||
use core_types::gpoll::GPoll;
|
use core_types::gpoll::GPoll;
|
||||||
use core_types::registry::EdgeHandle;
|
use core_types::registry::SourceHandle;
|
||||||
use core_types::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, NoopSpawner};
|
use core_types::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, NoopSpawner};
|
||||||
use graph_craft::Type;
|
use graph_craft::Type;
|
||||||
use graph_craft::document::NodeId;
|
use graph_craft::document::NodeId;
|
||||||
@@ -178,7 +178,7 @@ impl DynamicExecutor {
|
|||||||
let result = self.tree.introspect(node_path)?;
|
let result = self.tree.introspect(node_path)?;
|
||||||
if result.downcast_ref::<core_types::context::CtxSnapshot>().is_some() {
|
if result.downcast_ref::<core_types::context::CtxSnapshot>().is_some() {
|
||||||
return self
|
return self
|
||||||
.introspect_with(node_path, |layout, batch, arena| graphic_types::boundary::batch_to_legacy(layout, batch, arena))
|
.introspect_with(node_path, graphic_types::boundary::batch_to_legacy)
|
||||||
.map(Arc::from);
|
.map(Arc::from);
|
||||||
}
|
}
|
||||||
Ok(result)
|
Ok(result)
|
||||||
@@ -197,7 +197,7 @@ impl DynamicExecutor {
|
|||||||
let edge = self
|
let edge = self
|
||||||
.tree
|
.tree
|
||||||
.get_by_path(node_path)
|
.get_by_path(node_path)
|
||||||
.and_then(EdgeHandle::record_edge)
|
.and_then(SourceHandle::record_source)
|
||||||
.ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
|
.ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
|
||||||
let arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
|
let arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
let persistent = self.persistent.lock().unwrap_or_else(PoisonError::into_inner);
|
let persistent = self.persistent.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
@@ -363,7 +363,7 @@ impl std::fmt::Display for IntrospectError {
|
|||||||
///
|
///
|
||||||
/// # Fields
|
/// # Fields
|
||||||
///
|
///
|
||||||
/// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`EdgeHandle`] and [`Path`].
|
/// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`SourceHandle`] and [`Path`].
|
||||||
/// This stores the actual node instances and their associated paths.
|
/// This stores the actual node instances and their associated paths.
|
||||||
///
|
///
|
||||||
/// * `source_map`: A [`HashMap`] from [`Path`] to tuples of [`NodeId`] and [`NodeTypes`].
|
/// * `source_map`: A [`HashMap`] from [`Path`] to tuples of [`NodeId`] and [`NodeTypes`].
|
||||||
@@ -373,7 +373,7 @@ impl std::fmt::Display for IntrospectError {
|
|||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct BorrowTree {
|
pub struct BorrowTree {
|
||||||
/// A hashmap of node IDs and dynamically typed nodes.
|
/// A hashmap of node IDs and dynamically typed nodes.
|
||||||
nodes: HashMap<NodeId, (EdgeHandle, Path)>,
|
nodes: HashMap<NodeId, (SourceHandle, Path)>,
|
||||||
/// A hashmap from the document path to the proto node ID.
|
/// A hashmap from the document path to the proto node ID.
|
||||||
source_map: HashMap<Path, (NodeId, NodeTypes)>,
|
source_map: HashMap<Path, (NodeId, NodeTypes)>,
|
||||||
/// The record-stack reserve, folded from the graph at construction.
|
/// The record-stack reserve, folded from the graph at construction.
|
||||||
@@ -410,27 +410,27 @@ impl BorrowTree {
|
|||||||
Ok((new_nodes, old_nodes))
|
Ok((new_nodes, old_nodes))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn node_deps(&self, nodes: &[NodeId]) -> Vec<EdgeHandle> {
|
fn node_deps(&self, nodes: &[NodeId]) -> Vec<SourceHandle> {
|
||||||
nodes.iter().map(|node| self.nodes.get(node).unwrap().0.duplicate()).collect()
|
nodes.iter().map(|node| self.nodes.get(node).unwrap().0.duplicate()).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn store_node(&mut self, node: EdgeHandle, id: NodeId, path: Path) {
|
fn store_node(&mut self, node: SourceHandle, id: NodeId, path: Path) {
|
||||||
self.nodes.insert(id, (node, path));
|
self.nodes.insert(id, (node, path));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Calls the `Node::serialize` for that specific node, returning for example the captured io record for a monitor node. The node path must match the document node path.
|
/// Calls the `Node::serialize` for that specific node, returning for example the captured context snapshot for a monitor node. The node path must match the document node path.
|
||||||
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
||||||
let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
|
let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
|
||||||
let (node, _path) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?;
|
let (node, _path) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?;
|
||||||
node.serialize().ok_or(IntrospectError::NoData)
|
node.serialize().ok_or(IntrospectError::NoData)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get(&self, id: NodeId) -> Option<EdgeHandle> {
|
pub fn get(&self, id: NodeId) -> Option<SourceHandle> {
|
||||||
self.nodes.get(&id).map(|(node, _)| node.duplicate())
|
self.nodes.get(&id).map(|(node, _)| node.duplicate())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The edge handle for the node at a document path.
|
/// The edge handle for the node at a document path.
|
||||||
pub fn get_by_path(&self, node_path: &[NodeId]) -> Option<EdgeHandle> {
|
pub fn get_by_path(&self, node_path: &[NodeId]) -> Option<SourceHandle> {
|
||||||
let (id, _) = self.source_map.get(node_path)?;
|
let (id, _) = self.source_map.get(node_path)?;
|
||||||
self.get(*id)
|
self.get(*id)
|
||||||
}
|
}
|
||||||
@@ -788,7 +788,7 @@ mod test {
|
|||||||
|
|
||||||
let executor = build_executor(network);
|
let executor = build_executor(network);
|
||||||
let value = executor.tree().get(NodeId(0)).unwrap();
|
let value = executor.tree().get(NodeId(0)).unwrap();
|
||||||
assert_eq!(value.ty(), &core_types::registry::record_edge_type::<f64>());
|
assert_eq!(value.ty(), &core_types::registry::record_source_type::<f64>());
|
||||||
assert_eq!(value.layout().depth, 0);
|
assert_eq!(value.layout().depth, 0);
|
||||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
|
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use graphene_std::raster::GPU;
|
|||||||
#[cfg(feature = "gpu")]
|
#[cfg(feature = "gpu")]
|
||||||
use graphene_std::SourceId;
|
use graphene_std::SourceId;
|
||||||
use graphene_std::raster::{CPU, Raster};
|
use graphene_std::raster::{CPU, Raster};
|
||||||
use graphene_std::registry::{ConstructionError, EdgeHandle, NodeIOTypes, RegistryEntry};
|
use graphene_std::registry::{ConstructionError, SourceHandle, NodeIOTypes, RegistryEntry};
|
||||||
#[cfg(feature = "gpu")]
|
#[cfg(feature = "gpu")]
|
||||||
use graphene_std::runtime::RuntimeHandle;
|
use graphene_std::runtime::RuntimeHandle;
|
||||||
|
|
||||||
@@ -217,7 +217,7 @@ mod node_registry_macros {
|
|||||||
io: NodeIOTypes::new(
|
io: NodeIOTypes::new(
|
||||||
concrete!(Context),
|
concrete!(Context),
|
||||||
core_types::registry::record_type::<$to>(),
|
core_types::registry::record_type::<$to>(),
|
||||||
vec![core_types::registry::record_edge_type::<$from>()],
|
vec![core_types::registry::record_source_type::<$from>()],
|
||||||
),
|
),
|
||||||
constructor: |inputs| {
|
constructor: |inputs| {
|
||||||
if inputs.len() != 1 {
|
if inputs.len() != 1 {
|
||||||
@@ -227,7 +227,7 @@ mod node_registry_macros {
|
|||||||
let handle = inputs.next().unwrap();
|
let handle = inputs.next().unwrap();
|
||||||
let layout = handle.layout().clone();
|
let layout = handle.layout().clone();
|
||||||
let node = graphene_std::ops::IntoNode::<$to, _, $from>::new(handle.downcast_record::<$from>()?, &layout);
|
let node = graphene_std::ops::IntoNode::<$to, _, $from>::new(handle.downcast_record::<$from>()?, &layout);
|
||||||
Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
Ok(SourceHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -284,10 +284,10 @@ mod node_registry_macros {
|
|||||||
concrete!(Context),
|
concrete!(Context),
|
||||||
core_types::registry::record_type::<$to>(),
|
core_types::registry::record_type::<$to>(),
|
||||||
vec![
|
vec![
|
||||||
core_types::registry::record_edge_type::<$from>(),
|
core_types::registry::record_source_type::<$from>(),
|
||||||
core_types::registry::record_edge_type::<$convert>(),
|
core_types::registry::record_source_type::<$convert>(),
|
||||||
core_types::registry::record_edge_type::<RuntimeHandle>(),
|
core_types::registry::record_source_type::<RuntimeHandle>(),
|
||||||
core_types::registry::record_edge_type::<SourceId>(),
|
core_types::registry::record_source_type::<SourceId>(),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
constructor: |inputs| {
|
constructor: |inputs| {
|
||||||
@@ -314,7 +314,7 @@ mod node_registry_macros {
|
|||||||
&runtime_layout,
|
&runtime_layout,
|
||||||
&source_layout,
|
&source_layout,
|
||||||
);
|
);
|
||||||
Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
Ok(SourceHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -327,7 +327,7 @@ mod node_registry_macros {
|
|||||||
io: NodeIOTypes::new(
|
io: NodeIOTypes::new(
|
||||||
concrete!(Context),
|
concrete!(Context),
|
||||||
core_types::registry::record_type::<$to>(),
|
core_types::registry::record_type::<$to>(),
|
||||||
vec![core_types::registry::record_edge_type::<$from>(), core_types::registry::record_edge_type::<$convert>()],
|
vec![core_types::registry::record_source_type::<$from>(), core_types::registry::record_source_type::<$convert>()],
|
||||||
),
|
),
|
||||||
constructor: |inputs| {
|
constructor: |inputs| {
|
||||||
if inputs.len() != 2 {
|
if inputs.len() != 2 {
|
||||||
@@ -344,7 +344,7 @@ mod node_registry_macros {
|
|||||||
&value_layout,
|
&value_layout,
|
||||||
&converter_layout,
|
&converter_layout,
|
||||||
);
|
);
|
||||||
Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
Ok(SourceHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -196,7 +196,7 @@ impl Arena {
|
|||||||
let count = COUNT.fetch_add(1, Ordering::Relaxed);
|
let count = COUNT.fetch_add(1, Ordering::Relaxed);
|
||||||
if reserved.is_none() {
|
if reserved.is_none() {
|
||||||
eprintln!("arena> EXHAUSTED after {count} allocations, wanted {size} bytes\n{}", std::backtrace::Backtrace::force_capture());
|
eprintln!("arena> EXHAUSTED after {count} allocations, wanted {size} bytes\n{}", std::backtrace::Backtrace::force_capture());
|
||||||
} else if count % 20000 == 0 {
|
} else if count.is_multiple_of(20000) {
|
||||||
eprintln!("arena> {count} allocations, offset {}, this {size} bytes", self.offset.load(Ordering::Relaxed));
|
eprintln!("arena> {count} allocations, offset {}, this {size} bytes", self.offset.load(Ordering::Relaxed));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ pub trait Attribute: 'static {
|
|||||||
|
|
||||||
/// Re-parks the owned clone [`Self::read_erased`] produced into fresh
|
/// Re-parks the owned clone [`Self::read_erased`] produced into fresh
|
||||||
/// field storage; `None` for plain values, which ride the byte copy.
|
/// field storage; `None` for plain values, which ride the byte copy.
|
||||||
const REPARK: Option<unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>> = None;
|
const REPARK: Option<crate::list::ReparkFn> = None;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A kernel-facing attribute value. A parameter `Attr<A>` is a read of `A`
|
/// A kernel-facing attribute value. A parameter `Attr<A>` is a read of `A`
|
||||||
@@ -381,7 +381,7 @@ attribute! {
|
|||||||
/// Maps the unit square `[(0, 0), (1, 1)]` (top-left convention) onto the 'Text' node's
|
/// Maps the unit square `[(0, 0), (1, 1)]` (top-left convention) onto the 'Text' node's
|
||||||
/// text frame in this item's local space. Each item carries the frame relative to its own
|
/// text frame in this item's local space. Each item carries the frame relative to its own
|
||||||
/// glyph origin so it survives 'Index Elements' filtering. The Text tool reads this to
|
/// glyph origin so it survives 'Index Elements' filtering. The Text tool reads this to
|
||||||
/// position its drag cage. Stored as an affine to allow non-axis-aligned frames in the future.
|
/// position its drag cage.
|
||||||
pub EditorTextFrame("editor:text_frame"): DAffine2;
|
pub EditorTextFrame("editor:text_frame"): DAffine2;
|
||||||
/// Byte offset where a regex match begins ('Regex Find All' and 'Regex Capture' text nodes).
|
/// Byte offset where a regex match begins ('Regex Find All' and 'Regex Capture' text nodes).
|
||||||
pub Start("start"): u64;
|
pub Start("start"): u64;
|
||||||
|
|||||||
@@ -85,6 +85,12 @@ pub trait AnyAttributeValue: std::any::Any + Send + Sync {
|
|||||||
fn into_attribute(self: Box<Self>, key: &str, preceding_defaults: usize) -> Box<dyn AnyAttribute>;
|
fn into_attribute(self: Box<Self>, key: &str, preceding_defaults: usize) -> Box<dyn AnyAttribute>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Re-parks an owned attribute value into fresh field storage; `None` reports arena exhaustion.
|
||||||
|
pub type ReparkFn = unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>;
|
||||||
|
|
||||||
|
/// Replays an owned attribute value into a serving arena; `Some(None)` is unchanged, `None` reports arena exhaustion.
|
||||||
|
pub type FieldReplayFn = fn(&dyn AnyAttributeValue, &crate::arena::Arena) -> Option<Option<Box<dyn AnyAttributeValue>>>;
|
||||||
|
|
||||||
impl<T: Clone + Send + Sync + Default + Sized + Debug + PartialEq + CacheHash + 'static> AnyAttributeValue for T {
|
impl<T: Clone + Send + Sync + Default + Sized + Debug + PartialEq + CacheHash + 'static> AnyAttributeValue for T {
|
||||||
/// Clones this value into a new boxed trait object.
|
/// Clones this value into a new boxed trait object.
|
||||||
fn clone_box(&self) -> Box<dyn AnyAttributeValue> {
|
fn clone_box(&self) -> Box<dyn AnyAttributeValue> {
|
||||||
|
|||||||
@@ -212,8 +212,7 @@ impl<'a, T> Deref for Lane<'a, T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A materialized nesting level handed to a folding kernel: a thin element-typed
|
/// A materialized nesting level handed to a folding kernel: a thin element-typed
|
||||||
/// view over the [`RecordBatch`] the level was collected into. The eventual
|
/// view over the [`RecordBatch`] the level was collected into.
|
||||||
/// `List` once `IList` is renamed.
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct List<'a, T> {
|
pub struct List<'a, T> {
|
||||||
batch: RecordBatch<'a>,
|
batch: RecordBatch<'a>,
|
||||||
|
|||||||
@@ -38,7 +38,6 @@ impl<'r> Rec<'r> {
|
|||||||
|
|
||||||
/// An opaque record value: every non-empty record spills to a claimed frame
|
/// An opaque record value: every non-empty record spills to a claimed frame
|
||||||
/// and the value carries its pointer, while an empty record carries nothing.
|
/// and the value carries its pointer, while an empty record carries nothing.
|
||||||
/// Only [`Layout::rec`] reads it, against the wiring-proven layout.
|
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
pub struct RecordValue<'e> {
|
pub struct RecordValue<'e> {
|
||||||
pub(in crate::record) ptr: *const u8,
|
pub(in crate::record) ptr: *const u8,
|
||||||
|
|||||||
@@ -176,7 +176,6 @@ mod tests {
|
|||||||
let scope = frames.scope();
|
let scope = frames.scope();
|
||||||
let mut claim = scope.claim(&layout);
|
let mut claim = scope.claim(&layout);
|
||||||
addresses.push(claim.dst() as usize);
|
addresses.push(claim.dst() as usize);
|
||||||
drop(claim);
|
|
||||||
drop(scope);
|
drop(scope);
|
||||||
assert_eq!(frames.free_words(), free, "the scope returns its claims");
|
assert_eq!(frames.free_words(), free, "the scope returns its claims");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -207,8 +207,6 @@ impl<'a, 'e, N> RecordInput<'a, 'e, N> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The raw lazy input handed to a poll kernel whose input rides records while
|
|
||||||
/// the kernel consumes the plain element.
|
|
||||||
/// # Safety
|
/// # Safety
|
||||||
/// `rec` must be a record of the layout the offsets were resolved against
|
/// `rec` must be a record of the layout the offsets were resolved against
|
||||||
/// and `El` its element type; both are proven at wiring.
|
/// and `El` its element type; both are proven at wiring.
|
||||||
@@ -216,6 +214,8 @@ unsafe fn element_only<El: Clone>(rec: Rec<'_>, _reads: &[Option<usize>]) -> El
|
|||||||
unsafe { read_element::<El>(rec) }
|
unsafe { read_element::<El>(rec) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The raw lazy input handed to a poll kernel whose input rides records while
|
||||||
|
/// the kernel consumes the plain element.
|
||||||
pub struct ElementInput<'a, 'e, Out, N> {
|
pub struct ElementInput<'a, 'e, Out, N> {
|
||||||
node: &'a N,
|
node: &'a N,
|
||||||
layout: &'a Layout,
|
layout: &'a Layout,
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ pub struct FieldWrite {
|
|||||||
pub align: usize,
|
pub align: usize,
|
||||||
pub type_id: std::any::TypeId,
|
pub type_id: std::any::TypeId,
|
||||||
pub read_erased: unsafe fn(*const u8) -> Box<dyn crate::list::AnyAttributeValue>,
|
pub read_erased: unsafe fn(*const u8) -> Box<dyn crate::list::AnyAttributeValue>,
|
||||||
pub repark: Option<unsafe fn(&dyn crate::list::AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>>,
|
pub repark: Option<crate::list::ReparkFn>,
|
||||||
/// Hashes the field's content. `None` means the stored bytes are the
|
/// Hashes the field's content. `None` means the stored bytes are the
|
||||||
/// content, which holds for every unparked value.
|
/// content, which holds for every unparked value.
|
||||||
pub content_hash: Option<unsafe fn(*const u8, &mut dyn core::hash::Hasher)>,
|
pub content_hash: Option<unsafe fn(*const u8, &mut dyn core::hash::Hasher)>,
|
||||||
@@ -33,7 +33,7 @@ impl FieldWrite {
|
|||||||
unsafe { &*ptr.cast::<V>() }.cache_hash(&mut state);
|
unsafe { &*ptr.cast::<V>() }.cache_hash(&mut state);
|
||||||
}
|
}
|
||||||
unsafe fn content_eq<V: PartialEq>(a: *const u8, b: *const u8) -> bool {
|
unsafe fn content_eq<V: PartialEq>(a: *const u8, b: *const u8) -> bool {
|
||||||
unsafe { &*a.cast::<V>() == &*b.cast::<V>() }
|
unsafe { *a.cast::<V>() == *b.cast::<V>() }
|
||||||
}
|
}
|
||||||
Self {
|
Self {
|
||||||
name: A::NAME,
|
name: A::NAME,
|
||||||
@@ -64,7 +64,7 @@ pub struct FieldDesc {
|
|||||||
pub align: usize,
|
pub align: usize,
|
||||||
pub type_id: std::any::TypeId,
|
pub type_id: std::any::TypeId,
|
||||||
pub read_erased: unsafe fn(*const u8) -> Box<dyn crate::list::AnyAttributeValue>,
|
pub read_erased: unsafe fn(*const u8) -> Box<dyn crate::list::AnyAttributeValue>,
|
||||||
pub repark: Option<unsafe fn(&dyn crate::list::AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>>,
|
pub repark: Option<crate::list::ReparkFn>,
|
||||||
/// Hashes the field's content. `None` means the stored bytes are the
|
/// Hashes the field's content. `None` means the stored bytes are the
|
||||||
/// content, which holds for every unparked value.
|
/// content, which holds for every unparked value.
|
||||||
pub content_hash: Option<unsafe fn(*const u8, &mut dyn core::hash::Hasher)>,
|
pub content_hash: Option<unsafe fn(*const u8, &mut dyn core::hash::Hasher)>,
|
||||||
@@ -334,7 +334,6 @@ pub fn empty_layout() -> &'static Layout {
|
|||||||
EMPTY.get_or_init(Layout::default)
|
EMPTY.get_or_init(Layout::default)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Declarative record-io metadata for a node type, emitted by the macro into
|
|
||||||
/// A record node's output layout with the frame size and carrier copy plan derived from it.
|
/// A record node's output layout with the frame size and carrier copy plan derived from it.
|
||||||
#[derive(Clone, Debug, Default)]
|
#[derive(Clone, Debug, Default)]
|
||||||
pub struct RecordLayout {
|
pub struct RecordLayout {
|
||||||
@@ -347,6 +346,7 @@ pub struct RecordLayout {
|
|||||||
pub lane_invariant: u32,
|
pub lane_invariant: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Declarative record-io metadata for a node type, emitted by the macro into
|
||||||
/// its registry entry so the compiler can fold each input's layout without
|
/// its registry entry so the compiler can fold each input's layout without
|
||||||
/// running the node's constructor. [`fold`](LayoutMeta::fold) reproduces the
|
/// running the node's constructor. [`fold`](LayoutMeta::fold) reproduces the
|
||||||
/// layout the constructor derives at wiring today; the compiler layout pass
|
/// layout the constructor derives at wiring today; the compiler layout pass
|
||||||
@@ -436,13 +436,13 @@ impl LayoutMeta {
|
|||||||
let layout = self.fold(inputs);
|
let layout = self.fold(inputs);
|
||||||
let frame_bytes = layout.frame_bytes();
|
let frame_bytes = layout.frame_bytes();
|
||||||
let plan = match self.sources.first() {
|
let plan = match self.sources.first() {
|
||||||
// A reducer collapses its carrier's levels, so it writes a fresh record rather than copying fields down.
|
|
||||||
Some(&source) if self.level_delta >= 0 => {
|
Some(&source) if self.level_delta >= 0 => {
|
||||||
let from = inputs[source as usize].expect("layout resolve source input has no layout");
|
let from = inputs[source as usize].expect("layout resolve source input has no layout");
|
||||||
let carry_element = matches!(self.element, ElementSpec::Carried);
|
let carry_element = matches!(self.element, ElementSpec::Carried);
|
||||||
let removes: Vec<(&str, u8)> = self.removes.clone();
|
let removes: Vec<(&str, u8)> = self.removes.clone();
|
||||||
copy_plan(from, &layout, carry_element, &removes)
|
copy_plan(from, &layout, carry_element, &removes)
|
||||||
}
|
}
|
||||||
|
// A reducer collapses its carrier's levels, so it writes a fresh record rather than copying fields down.
|
||||||
_ => Vec::new(),
|
_ => Vec::new(),
|
||||||
};
|
};
|
||||||
RecordLayout {
|
RecordLayout {
|
||||||
@@ -656,7 +656,7 @@ mod tests {
|
|||||||
#[derive(Clone, dyn_any::DynAny)]
|
#[derive(Clone, dyn_any::DynAny)]
|
||||||
struct Opaque;
|
struct Opaque;
|
||||||
|
|
||||||
let hashed = (&ElementWritePick::<String>(std::marker::PhantomData)).element_write();
|
let hashed = ElementWritePick::<String>(std::marker::PhantomData).element_write();
|
||||||
assert!(hashed.content_hash.is_some() && hashed.content_eq.is_some());
|
assert!(hashed.content_hash.is_some() && hashed.content_eq.is_some());
|
||||||
let plain = (&ElementWritePick::<Opaque>(std::marker::PhantomData)).element_write();
|
let plain = (&ElementWritePick::<Opaque>(std::marker::PhantomData)).element_write();
|
||||||
assert!(plain.content_hash.is_none() && plain.content_eq.is_none());
|
assert!(plain.content_hash.is_none() && plain.content_eq.is_none());
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ pub(in crate::record) fn deep_element_glue(type_id: std::any::TypeId) -> Option<
|
|||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
pub(in crate::record) struct DeepFieldGlue {
|
pub(in crate::record) struct DeepFieldGlue {
|
||||||
pub(in crate::record) copy_out: fn(&dyn crate::list::AnyAttributeValue) -> Option<Box<dyn crate::list::AnyAttributeValue>>,
|
pub(in crate::record) copy_out: fn(&dyn crate::list::AnyAttributeValue) -> Option<Box<dyn crate::list::AnyAttributeValue>>,
|
||||||
pub(in crate::record) replay: fn(&dyn crate::list::AnyAttributeValue, &crate::arena::Arena) -> Option<Option<Box<dyn crate::list::AnyAttributeValue>>>,
|
pub(in crate::record) replay: crate::list::FieldReplayFn,
|
||||||
}
|
}
|
||||||
|
|
||||||
static DEEP_FIELD_VALUES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, DeepFieldGlue>>> = std::sync::LazyLock::new(Default::default);
|
static DEEP_FIELD_VALUES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, DeepFieldGlue>>> = std::sync::LazyLock::new(Default::default);
|
||||||
@@ -52,7 +52,7 @@ static DEEP_FIELD_VALUES: std::sync::LazyLock<std::sync::Mutex<std::collections:
|
|||||||
/// Called at startup from the crate that owns the type.
|
/// Called at startup from the crate that owns the type.
|
||||||
pub fn register_deep_field_value<T: 'static>(
|
pub fn register_deep_field_value<T: 'static>(
|
||||||
copy_out: fn(&dyn crate::list::AnyAttributeValue) -> Option<Box<dyn crate::list::AnyAttributeValue>>,
|
copy_out: fn(&dyn crate::list::AnyAttributeValue) -> Option<Box<dyn crate::list::AnyAttributeValue>>,
|
||||||
replay: fn(&dyn crate::list::AnyAttributeValue, &crate::arena::Arena) -> Option<Option<Box<dyn crate::list::AnyAttributeValue>>>,
|
replay: crate::list::FieldReplayFn,
|
||||||
) {
|
) {
|
||||||
DEEP_FIELD_VALUES.lock().unwrap().insert(std::any::TypeId::of::<T>(), DeepFieldGlue { copy_out, replay });
|
DEEP_FIELD_VALUES.lock().unwrap().insert(std::any::TypeId::of::<T>(), DeepFieldGlue { copy_out, replay });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -370,7 +370,7 @@ mod tests {
|
|||||||
let bounds = (base as usize, buffer.len() * 8);
|
let bounds = (base as usize, buffer.len() * 8);
|
||||||
let length = "shared across lanes".len();
|
let length = "shared across lanes".len();
|
||||||
unsafe { write_element_sized(base, String::from("shared across lanes"), &transient, length) }.unwrap();
|
unsafe { write_element_sized(base, String::from("shared across lanes"), &transient, length) }.unwrap();
|
||||||
// A carried field byte-copies the reference, so both lanes name the one park.
|
// A carried element byte-copies its park reference, so both lanes name the one park.
|
||||||
let shared = unsafe { base.cast::<*const u8>().read() };
|
let shared = unsafe { base.cast::<*const u8>().read() };
|
||||||
unsafe { base.add(stride).cast::<*const u8>().write(shared) };
|
unsafe { base.add(stride).cast::<*const u8>().write(shared) };
|
||||||
|
|
||||||
|
|||||||
@@ -97,7 +97,7 @@ where
|
|||||||
let Some(plan) = &self.plan else {
|
let Some(plan) = &self.plan else {
|
||||||
return self.edge.serve(input, slot);
|
return self.edge.serve(input, slot);
|
||||||
};
|
};
|
||||||
match serve_input(&self.edge, input, &mut slot.frames().reborrow()) {
|
match serve_input(&self.edge, input, &slot.frames().reborrow()) {
|
||||||
GPoll::Final(value) => {
|
GPoll::Final(value) => {
|
||||||
// SAFETY: the value came from this source, so it carries the
|
// SAFETY: the value came from this source, so it carries the
|
||||||
// plan's source layout.
|
// plan's source layout.
|
||||||
|
|||||||
@@ -151,9 +151,7 @@ struct OwnedLanes {
|
|||||||
fields: Vec<(usize, Vec<Box<dyn crate::list::AnyAttributeValue>>)>,
|
fields: Vec<(usize, Vec<Box<dyn crate::list::AnyAttributeValue>>)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
// SAFETY: the same argument as for `RecordValue`. The element bounds and the
|
// SAFETY: as for `RecordValue`.
|
||||||
// parking discipline make the record bytes thread-safe, and their validity
|
|
||||||
// is tied to the shared arena.
|
|
||||||
unsafe impl Send for GroupItem<'_> {}
|
unsafe impl Send for GroupItem<'_> {}
|
||||||
// SAFETY: as `Send`.
|
// SAFETY: as `Send`.
|
||||||
unsafe impl Sync for GroupItem<'_> {}
|
unsafe impl Sync for GroupItem<'_> {}
|
||||||
@@ -173,7 +171,7 @@ impl<'e> GroupItem<'e> {
|
|||||||
// A run already living in the target region needs no copy: the arena is
|
// A run already living in the target region needs no copy: the arena is
|
||||||
// insert-only within a generation, so the lanes cannot move or change
|
// insert-only within a generation, so the lanes cannot move or change
|
||||||
// while the adopting item borrows them.
|
// while the adopting item borrows them.
|
||||||
if batch.len() > 0 && arena.contains(batch.frames_ptr()) {
|
if !batch.is_empty() && arena.contains(batch.frames_ptr()) {
|
||||||
return Some(Self {
|
return Some(Self {
|
||||||
layout,
|
layout,
|
||||||
storage: ItemStorage::Resident(batch.frames_ptr()),
|
storage: ItemStorage::Resident(batch.frames_ptr()),
|
||||||
@@ -314,8 +312,8 @@ impl<'e> GroupItem<'e> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Re-parks an owned item's lanes into `arena`, restoring the resident
|
/// Re-parks an owned item's lanes into `arena`, restoring the resident
|
||||||
/// form; `None` reports arena exhaustion. A resident item returns a plain
|
/// form; `None` reports arena exhaustion. A resident item re-adopts into
|
||||||
/// clone.
|
/// `arena`, sharing only where its lanes already live there.
|
||||||
pub fn replay<'a>(&self, arena: &'a crate::arena::Arena) -> Option<GroupItem<'a>> {
|
pub fn replay<'a>(&self, arena: &'a crate::arena::Arena) -> Option<GroupItem<'a>> {
|
||||||
let ItemStorage::Owned(owned) = &self.storage else {
|
let ItemStorage::Owned(owned) = &self.storage else {
|
||||||
// A resident item re-serves at the target arena's own lifetime,
|
// A resident item re-serves at the target arena's own lifetime,
|
||||||
@@ -480,8 +478,7 @@ impl<T: crate::bounds::BoundingBox + dyn_any::StaticTypeSized> crate::bounds::Bo
|
|||||||
|
|
||||||
/// Records nested inside one element: a single homogeneous run. The `row`
|
/// Records nested inside one element: a single homogeneous run. The `row`
|
||||||
/// holds the group's own attribute record. A group that sits on a lane leaves
|
/// holds the group's own attribute record. A group that sits on a lane leaves
|
||||||
/// it `None`, because that lane's record carries the attributes. The typed
|
/// it `None`, because that lane's record carries the attributes.
|
||||||
/// segment stack returns when merge constructs segments.
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct Group<'e> {
|
pub struct Group<'e> {
|
||||||
pub row: Option<GroupItem<'e>>,
|
pub row: Option<GroupItem<'e>>,
|
||||||
@@ -584,7 +581,7 @@ impl graphene_hash::CacheHash for GroupItem<'_> {
|
|||||||
let stride = self.layout.lane_stride();
|
let stride = self.layout.lane_stride();
|
||||||
let frames = self.frames();
|
let frames = self.frames();
|
||||||
for lane in 0..self.len {
|
for lane in 0..self.len {
|
||||||
// SAFETY: `adopt` filled `len` lanes of `layout`.
|
// SAFETY: the constructors store `len` lanes of `layout` at the layout's stride.
|
||||||
unsafe { record_content_hash(&self.layout, frames.add(lane * stride), state) };
|
unsafe { record_content_hash(&self.layout, frames.add(lane * stride), state) };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ pub struct NodeMetadata {
|
|||||||
pub context_features: Vec<ContextFeature>,
|
pub context_features: Vec<ContextFeature>,
|
||||||
pub memoize: bool,
|
pub memoize: bool,
|
||||||
pub inject_scope: bool,
|
pub inject_scope: bool,
|
||||||
/// The macro appended its hidden `_runtime` and `_source` fields as the last two entries of `fields`.
|
/// Set where `_runtime` and `_source` are the last two entries of `fields`.
|
||||||
pub async_source_fields: bool,
|
pub async_source_fields: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,20 +79,20 @@ pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>> + Send + Sync;
|
|||||||
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>>;
|
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>>;
|
||||||
|
|
||||||
#[cfg(not(target_family = "wasm"))]
|
#[cfg(not(target_family = "wasm"))]
|
||||||
type DynEdge = dyn std::any::Any + Send + Sync;
|
type DynSource = dyn std::any::Any + Send + Sync;
|
||||||
#[cfg(target_family = "wasm")]
|
#[cfg(target_family = "wasm")]
|
||||||
type DynEdge = dyn std::any::Any;
|
type DynSource = dyn std::any::Any;
|
||||||
|
|
||||||
pub fn record_type<T: 'static>() -> Type {
|
pub fn record_type<T: 'static>() -> Type {
|
||||||
Type::Record(Box::new(concrete!(T)))
|
Type::Record(Box::new(concrete!(T)))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn record_edge_type<T: 'static>() -> Type {
|
pub fn record_source_type<T: 'static>() -> Type {
|
||||||
Type::Fn(Box::new(concrete!(Context)), Box::new(record_type::<T>()))
|
Type::Fn(Box::new(concrete!(Context)), Box::new(record_type::<T>()))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The record edge type of a token row, generic over the element.
|
/// The record source type of a token row, generic over the element.
|
||||||
pub fn generic_record_edge_type(name: &'static str) -> Type {
|
pub fn generic_record_source_type(name: &'static str) -> Type {
|
||||||
Type::Fn(Box::new(concrete!(Context)), Box::new(Type::Record(Box::new(Type::Generic(std::borrow::Cow::Borrowed(name))))))
|
Type::Fn(Box::new(concrete!(Context)), Box::new(Type::Record(Box::new(Type::Generic(std::borrow::Cow::Borrowed(name))))))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,9 +143,6 @@ impl<Input, N> Node<Input> for SharedSource<N>
|
|||||||
where
|
where
|
||||||
N: Node<Input> + ?Sized,
|
N: Node<Input> + ?Sized,
|
||||||
{
|
{
|
||||||
/// A node takes exactly its own frame out of its caller's free space: the
|
|
||||||
/// caller minted the claim and kept the cursor, so the frame accounting is
|
|
||||||
/// structural here and asserted where a claim is split.
|
|
||||||
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> crate::gpoll::GPoll<crate::record::Served<'e>>
|
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> crate::gpoll::GPoll<crate::record::Served<'e>>
|
||||||
where
|
where
|
||||||
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||||
@@ -188,31 +185,31 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct EdgeHandle {
|
pub struct SourceHandle {
|
||||||
node: Box<DynEdge>,
|
node: Box<DynSource>,
|
||||||
share: fn(&DynEdge) -> Box<DynEdge>,
|
share: fn(&DynSource) -> Box<DynSource>,
|
||||||
serialize: fn(&DynEdge) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>,
|
serialize: fn(&DynSource) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>,
|
||||||
layout: fn(&DynEdge) -> &crate::record::Layout,
|
layout: fn(&DynSource) -> &crate::record::Layout,
|
||||||
set_layout: fn(&mut DynEdge, crate::record::RecordLayout),
|
set_layout: fn(&mut DynSource, crate::record::RecordLayout),
|
||||||
ty: Type,
|
ty: Type,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Debug for EdgeHandle {
|
impl std::fmt::Debug for SourceHandle {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
f.debug_struct("EdgeHandle").field("ty", &self.ty).finish_non_exhaustive()
|
f.debug_struct("SourceHandle").field("ty", &self.ty).finish_non_exhaustive()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SAFETY: wasm is single threaded, so the marker-free payload never actually crosses a thread.
|
// SAFETY: wasm is single threaded, so the marker-free payload never actually crosses a thread.
|
||||||
#[cfg(target_family = "wasm")]
|
#[cfg(target_family = "wasm")]
|
||||||
unsafe impl Send for EdgeHandle {}
|
unsafe impl Send for SourceHandle {}
|
||||||
// SAFETY: as in Send.
|
// SAFETY: as in Send.
|
||||||
#[cfg(target_family = "wasm")]
|
#[cfg(target_family = "wasm")]
|
||||||
unsafe impl Sync for EdgeHandle {}
|
unsafe impl Sync for SourceHandle {}
|
||||||
|
|
||||||
impl EdgeHandle {
|
impl SourceHandle {
|
||||||
pub fn new_record<T: 'static>(node: std::sync::Arc<ErasedRecordNode>) -> Self {
|
pub fn new_record<T: 'static>(node: std::sync::Arc<ErasedRecordNode>) -> Self {
|
||||||
Self::new_erased(node, record_edge_type::<T>())
|
Self::new_erased(node, record_source_type::<T>())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn new_erased<N>(node: std::sync::Arc<N>, ty: Type) -> Self
|
pub fn new_erased<N>(node: std::sync::Arc<N>, ty: Type) -> Self
|
||||||
@@ -263,12 +260,12 @@ impl EdgeHandle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn downcast_record<T: 'static>(self) -> Result<SharedSource<ErasedRecordNode>, ConstructionError> {
|
pub fn downcast_record<T: 'static>(self) -> Result<SharedSource<ErasedRecordNode>, ConstructionError> {
|
||||||
self.downcast_erased(record_edge_type::<T>())
|
self.downcast_erased(record_source_type::<T>())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The erased record edge, for callers that dispatch on the layout rather
|
/// The erased record source, for callers that dispatch on the layout rather
|
||||||
/// than a static element type. `None` for an edge erased to another node type.
|
/// than a static element type. `None` for a source erased to another node type.
|
||||||
pub fn record_edge(self) -> Option<SharedSource<ErasedRecordNode>> {
|
pub fn record_source(self) -> Option<SharedSource<ErasedRecordNode>> {
|
||||||
self.node.downcast::<SharedSource<ErasedRecordNode>>().ok().map(|edge| *edge)
|
self.node.downcast::<SharedSource<ErasedRecordNode>>().ok().map(|edge| *edge)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -281,19 +278,19 @@ impl EdgeHandle {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type NodeConstructor = fn(Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError>;
|
pub type NodeConstructor = fn(Vec<SourceHandle>) -> Result<SourceHandle, ConstructionError>;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct RegistryEntry {
|
pub struct RegistryEntry {
|
||||||
pub io: NodeIOTypes,
|
pub io: NodeIOTypes,
|
||||||
pub constructor: NodeConstructor,
|
pub constructor: NodeConstructor,
|
||||||
/// Declarative record-io metadata for the compiler layout pass; `None` for
|
/// Declarative record-io metadata for the compiler layout pass; `None` for
|
||||||
/// nodes whose layout the pass does not yet fold (routing/opaque, hand-written
|
/// nodes whose layout the pass does not fold (routing/opaque, hand-written
|
||||||
/// rows), which keep the construction-time path.
|
/// rows), which keep the construction-time path.
|
||||||
pub layout_meta: Option<crate::record::LayoutMeta>,
|
pub layout_meta: Option<crate::record::LayoutMeta>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn construct(entry: &RegistryEntry, inputs: Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError> {
|
pub fn construct(entry: &RegistryEntry, inputs: Vec<SourceHandle>) -> Result<SourceHandle, ConstructionError> {
|
||||||
if inputs.len() != entry.io.inputs.len() {
|
if inputs.len() != entry.io.inputs.len() {
|
||||||
return Err(ConstructionError::Arity {
|
return Err(ConstructionError::Arity {
|
||||||
expected: entry.io.inputs.len(),
|
expected: entry.io.inputs.len(),
|
||||||
@@ -379,7 +376,7 @@ mod tests {
|
|||||||
|
|
||||||
let node = LendNode::new("held");
|
let node = LendNode::new("held");
|
||||||
let layout = Node::<ContextImpl>::layout(&node).clone();
|
let layout = Node::<ContextImpl>::layout(&node).clone();
|
||||||
let handle = EdgeHandle::new_erased(Arc::new(node) as Arc<ErasedRecordNode>, concrete!(String));
|
let handle = SourceHandle::new_erased(Arc::new(node) as Arc<ErasedRecordNode>, concrete!(String));
|
||||||
assert_eq!(*handle.ty(), concrete!(String));
|
assert_eq!(*handle.ty(), concrete!(String));
|
||||||
|
|
||||||
let wired = handle.downcast_erased::<ErasedRecordNode>(concrete!(String)).unwrap();
|
let wired = handle.downcast_erased::<ErasedRecordNode>(concrete!(String)).unwrap();
|
||||||
@@ -392,8 +389,8 @@ mod tests {
|
|||||||
assert_eq!(held.len(), 4);
|
assert_eq!(held.len(), 4);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluates its content at three promoted index levels and serves the
|
/// Evaluates its content at three indices of one promoted level and serves
|
||||||
/// collected elements.
|
/// the collected elements.
|
||||||
struct RepeatNode<Node0, T> {
|
struct RepeatNode<Node0, T> {
|
||||||
content: Node0,
|
content: Node0,
|
||||||
inner: Layout,
|
inner: Layout,
|
||||||
@@ -554,29 +551,29 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn construct_checks_arity_and_types() {
|
fn construct_checks_arity_and_types() {
|
||||||
fn construct_strlen(args: Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError> {
|
fn construct_strlen(args: Vec<SourceHandle>) -> Result<SourceHandle, ConstructionError> {
|
||||||
let mut args = args.into_iter();
|
let mut args = args.into_iter();
|
||||||
let value = args.next().ok_or(ConstructionError::Arity { expected: 1, got: 0 })?.downcast_record::<String>()?;
|
let value = args.next().ok_or(ConstructionError::Arity { expected: 1, got: 0 })?.downcast_record::<String>()?;
|
||||||
drop(value);
|
drop(value);
|
||||||
Ok(crate::value::record_value_edge(0u32))
|
Ok(crate::value::record_value_source(0u32))
|
||||||
}
|
}
|
||||||
let entry = RegistryEntry {
|
let entry = RegistryEntry {
|
||||||
layout_meta: None,
|
layout_meta: None,
|
||||||
io: NodeIOTypes::new(concrete!(Context), record_type::<u32>(), vec![record_edge_type::<String>()]),
|
io: NodeIOTypes::new(concrete!(Context), record_type::<u32>(), vec![record_source_type::<String>()]),
|
||||||
constructor: construct_strlen,
|
constructor: construct_strlen,
|
||||||
};
|
};
|
||||||
|
|
||||||
let owned = crate::value::record_value_edge("typed".to_string());
|
let owned = crate::value::record_value_source("typed".to_string());
|
||||||
assert!(construct(&entry, vec![owned]).is_ok());
|
assert!(construct(&entry, vec![owned]).is_ok());
|
||||||
|
|
||||||
assert_eq!(construct(&entry, vec![]).unwrap_err(), ConstructionError::Arity { expected: 1, got: 0 });
|
assert_eq!(construct(&entry, vec![]).unwrap_err(), ConstructionError::Arity { expected: 1, got: 0 });
|
||||||
|
|
||||||
let mistyped = crate::value::record_value_edge(1.0f64);
|
let mistyped = crate::value::record_value_source(1.0f64);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
construct(&entry, vec![mistyped]).unwrap_err(),
|
construct(&entry, vec![mistyped]).unwrap_err(),
|
||||||
ConstructionError::Type {
|
ConstructionError::Type {
|
||||||
expected: Box::new(record_edge_type::<String>()),
|
expected: Box::new(record_source_type::<String>()),
|
||||||
found: Box::new(record_edge_type::<f64>()),
|
found: Box::new(record_source_type::<f64>()),
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -590,9 +587,9 @@ mod tests {
|
|||||||
|
|
||||||
let counting = counting();
|
let counting = counting();
|
||||||
let layout = Node::<ContextImpl>::layout(&counting).clone();
|
let layout = Node::<ContextImpl>::layout(&counting).clone();
|
||||||
let handle = EdgeHandle::new_record::<u32>(Arc::new(counting) as Arc<ErasedRecordNode>);
|
let handle = SourceHandle::new_record::<u32>(Arc::new(counting) as Arc<ErasedRecordNode>);
|
||||||
let duplicate = handle.duplicate();
|
let duplicate = handle.duplicate();
|
||||||
assert_eq!(*duplicate.ty(), record_edge_type::<u32>());
|
assert_eq!(*duplicate.ty(), record_source_type::<u32>());
|
||||||
let frames = crate::record::test_frames(1 << 12);
|
let frames = crate::record::test_frames(1 << 12);
|
||||||
|
|
||||||
let first = handle.downcast_record::<u32>().unwrap();
|
let first = handle.downcast_record::<u32>().unwrap();
|
||||||
|
|||||||
@@ -33,12 +33,12 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The native record edge of a constant.
|
/// The native record source of a constant.
|
||||||
pub fn record_value_edge<T: Clone + Send + Sync + dyn_any::StaticTypeSized + 'static>(value: T) -> crate::registry::EdgeHandle
|
pub fn record_value_source<T: Clone + Send + Sync + dyn_any::StaticTypeSized + 'static>(value: T) -> crate::registry::SourceHandle
|
||||||
where
|
where
|
||||||
T::Static: Clone + Send + Sync,
|
T::Static: Clone + Send + Sync,
|
||||||
{
|
{
|
||||||
crate::registry::EdgeHandle::new_record::<T>(std::sync::Arc::new(ValueSource::new(value)) as std::sync::Arc<crate::registry::ErasedRecordNode>)
|
crate::registry::SourceHandle::new_record::<T>(std::sync::Arc::new(ValueSource::new(value)) as std::sync::Arc<crate::registry::ErasedRecordNode>)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The node behind a leveled value source: a constant list served as one level,
|
/// The node behind a leveled value source: a constant list served as one level,
|
||||||
@@ -90,10 +90,10 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The native record edge of a constant level: the edge type is the element's.
|
/// The native record source of a constant level: the source type is the element's.
|
||||||
pub fn leveled_record_value_edge<T: Clone + Send + Sync + crate::CacheHash + PartialEq + dyn_any::StaticTypeSized + 'static>(values: Vec<T>) -> crate::registry::EdgeHandle
|
pub fn leveled_record_value_source<T: Clone + Send + Sync + crate::CacheHash + PartialEq + dyn_any::StaticTypeSized + 'static>(values: Vec<T>) -> crate::registry::SourceHandle
|
||||||
where
|
where
|
||||||
T::Static: Clone + Send + Sync,
|
T::Static: Clone + Send + Sync,
|
||||||
{
|
{
|
||||||
crate::registry::EdgeHandle::new_record::<T>(std::sync::Arc::new(LeveledValueSource::new(values)) as std::sync::Arc<crate::registry::ErasedRecordNode>)
|
crate::registry::SourceHandle::new_record::<T>(std::sync::Arc::new(LeveledValueSource::new(values)) as std::sync::Arc<crate::registry::ErasedRecordNode>)
|
||||||
}
|
}
|
||||||
@@ -238,8 +238,7 @@ impl_tuple!(A, B, C, D, E);
|
|||||||
impl_tuple!(A, B, C, D, E, F);
|
impl_tuple!(A, B, C, D, E, F);
|
||||||
|
|
||||||
/// rustc-hash's polynomial hash with the state pinned to u64, so keys match across native and wasm targets.
|
/// rustc-hash's polynomial hash with the state pinned to u64, so keys match across native and wasm targets.
|
||||||
/// The state starts at a nonzero seed: zero-initialized fx absorbs leading zero words, which produced
|
/// The state starts at a nonzero seed, since zero-initialized fx absorbs leading zero words.
|
||||||
/// a real wrong-value memo hit in the prototype.
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct FxHasher64 {
|
pub struct FxHasher64 {
|
||||||
hash: u64,
|
hash: u64,
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ impl<'e> Artboard<'e> {
|
|||||||
Self(content)
|
Self(content)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn as_graphic_list(&self) -> &List<Graphic> {
|
pub fn as_graphic_list(&self) -> &List<Graphic<'_>> {
|
||||||
&self.0
|
&self.0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ use glam::{DAffine2, DVec2};
|
|||||||
use vector_types::GradientStops;
|
use vector_types::GradientStops;
|
||||||
|
|
||||||
/// The outcome of materializing a leveled wire into a group.
|
/// The outcome of materializing a leveled wire into a group.
|
||||||
|
// The group is the render path's success payload; boxing it would add a heap allocation per materialized level.
|
||||||
|
#[allow(clippy::large_enum_variant)]
|
||||||
pub enum LevelGroup<'e> {
|
pub enum LevelGroup<'e> {
|
||||||
Group(Group<'e>, Finality),
|
Group(Group<'e>, Finality),
|
||||||
Pending,
|
Pending,
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,469 @@
|
|||||||
|
//! The record-crossing glue: group interiors carried between the owned, resident, and persistent regions.
|
||||||
|
|
||||||
|
use super::Graphic;
|
||||||
|
use core_types::Color;
|
||||||
|
use core_types::list::{Item, List};
|
||||||
|
use raster_types::{CPU, Raster};
|
||||||
|
use vector_types::Vector;
|
||||||
|
|
||||||
|
/// The graphic with every `Group` deep-copied to its owned form, which
|
||||||
|
/// survives the arena generation but cannot be read until
|
||||||
|
/// [`map_groups_to_resident`] re-parks it into a serving arena.
|
||||||
|
pub fn map_groups_to_owned<'out>(graphic: &Graphic<'_>) -> Graphic<'out> {
|
||||||
|
match graphic {
|
||||||
|
Graphic::Group(group) => Graphic::Group(group.copy_out()),
|
||||||
|
Graphic::Graphic(children) => {
|
||||||
|
let mut out = List::new();
|
||||||
|
for item in children.clone().into_iter() {
|
||||||
|
let (element, attributes) = item.into_parts();
|
||||||
|
out.push(Item::from_parts(map_groups_to_owned(&element), attributes));
|
||||||
|
}
|
||||||
|
Graphic::Graphic(out)
|
||||||
|
}
|
||||||
|
Graphic::Vector(vector) => Graphic::Vector(vector.clone()),
|
||||||
|
Graphic::RasterCPU(raster) => Graphic::RasterCPU(raster.clone()),
|
||||||
|
Graphic::RasterGPU(raster) => Graphic::RasterGPU(raster.clone()),
|
||||||
|
Graphic::Color(color) => Graphic::Color(*color),
|
||||||
|
Graphic::Gradient(gradient) => Graphic::Gradient(gradient.clone()),
|
||||||
|
Graphic::Text(text) => Graphic::Text(text.clone()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The graphic with every owned `Group` re-parked into `arena`; `None`
|
||||||
|
/// reports arena exhaustion.
|
||||||
|
pub fn map_groups_to_resident<'a>(graphic: &Graphic<'a>, arena: &'a core_types::arena::Arena) -> Option<Graphic<'a>> {
|
||||||
|
match graphic {
|
||||||
|
Graphic::Group(group) => group.replay(arena).map(Graphic::Group),
|
||||||
|
Graphic::Graphic(children) => {
|
||||||
|
let mut children = children.clone();
|
||||||
|
for child in children.iter_element_values_mut() {
|
||||||
|
*child = map_groups_to_resident(child, arena)?;
|
||||||
|
}
|
||||||
|
Some(Graphic::Graphic(children))
|
||||||
|
}
|
||||||
|
other => Some(other.clone()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The deep copy-out for `Graphic` elements: a plain clone of a group
|
||||||
|
/// interior would carry frame pointers into the evaluation's arena, so memo
|
||||||
|
/// and capture seams copy out the owned-group form.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// `ptr` must point at a live parked `Graphic` element field.
|
||||||
|
unsafe fn deep_clone_graphic(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
|
||||||
|
let graphic = unsafe { core_types::record::borrow_element::<Graphic>(core_types::record::Rec::new(ptr)) };
|
||||||
|
Box::new(map_groups_to_owned(graphic))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The deep re-park for `Graphic` elements: owned groups replay into the
|
||||||
|
/// serving arena before the graphic parks.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// `value` must hold a `Graphic` and `dst` must be a live `Graphic` element
|
||||||
|
/// field.
|
||||||
|
unsafe fn deep_repark_graphic(value: &(dyn std::any::Any + Send + Sync), dst: *mut u8, arena: &core_types::arena::Arena) -> Option<()> {
|
||||||
|
let graphic = value.downcast_ref::<Graphic>().expect("an element replays at its own type");
|
||||||
|
let resident = map_groups_to_resident(graphic, arena)?;
|
||||||
|
let retained = graphic_retained_heap(&resident);
|
||||||
|
unsafe { core_types::record::write_element_sized(dst, resident, arena, retained) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The graphic with every `Group` promoted into the persistent region: an
|
||||||
|
/// interior already living there is shared rather than copied, so the cost is
|
||||||
|
/// what this level newly produced. `None` reports arena exhaustion.
|
||||||
|
pub fn map_groups_to_persistent<'p>(graphic: &Graphic<'_>, promotion: &core_types::record::Promotion<'p>) -> Option<Graphic<'p>> {
|
||||||
|
match graphic {
|
||||||
|
Graphic::Group(group) => group.to_persistent(promotion).map(Graphic::Group),
|
||||||
|
Graphic::Graphic(children) => {
|
||||||
|
let mut out = List::new();
|
||||||
|
for item in children.clone().into_iter() {
|
||||||
|
let (element, attributes) = item.into_parts();
|
||||||
|
out.push(Item::from_parts(map_groups_to_persistent(&element, promotion)?, attributes));
|
||||||
|
}
|
||||||
|
Some(Graphic::Graphic(out))
|
||||||
|
}
|
||||||
|
Graphic::Vector(vector) => Some(Graphic::Vector(vector.clone())),
|
||||||
|
Graphic::RasterCPU(raster) => Some(Graphic::RasterCPU(raster.clone())),
|
||||||
|
Graphic::RasterGPU(raster) => Some(Graphic::RasterGPU(raster.clone())),
|
||||||
|
Graphic::Color(color) => Some(Graphic::Color(*color)),
|
||||||
|
Graphic::Gradient(gradient) => Some(Graphic::Gradient(gradient.clone())),
|
||||||
|
Graphic::Text(text) => Some(Graphic::Text(text.clone())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The promote for `Graphic` elements: the generic path would deep-copy every
|
||||||
|
/// interior through an owned intermediate, while this shares the interiors the
|
||||||
|
/// persistent region already holds. A group-free graphic references nothing the
|
||||||
|
/// evaluation owns, so its header moves and its heap is never copied.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// `src` must point at a live parked `Graphic` element field, and `dst` at the
|
||||||
|
/// element field the promoted reference is written to.
|
||||||
|
unsafe fn promote_graphic(src: *const u8, dst: *mut u8, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
|
||||||
|
let graphic = unsafe { core_types::record::borrow_element::<Graphic>(core_types::record::Rec::new(src)) };
|
||||||
|
if !graphic_contains_groups(graphic) {
|
||||||
|
// SAFETY: a parked element slot holds one reference at offset 0, and a
|
||||||
|
// group-free graphic owns all of its content.
|
||||||
|
let header = unsafe { src.cast::<*const u8>().read() };
|
||||||
|
if let Some(moved) = unsafe { promotion.move_park::<Graphic<'static>>(header, graphic_retained_heap(graphic)) } {
|
||||||
|
// SAFETY: as above, into the promoted image's own element slot.
|
||||||
|
unsafe { dst.cast::<*const Graphic<'static>>().write(moved) };
|
||||||
|
return Some(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let promoted = map_groups_to_persistent(graphic, promotion)?;
|
||||||
|
let retained = graphic_retained_heap(&promoted);
|
||||||
|
unsafe { core_types::record::write_element_sized(dst, promoted, promotion.persistent(), retained) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The heap a graphic's own payload owns. Group interiors are excluded: their
|
||||||
|
/// lanes park through this same glue and are counted as they land.
|
||||||
|
fn graphic_retained_heap(graphic: &Graphic<'_>) -> usize {
|
||||||
|
match graphic {
|
||||||
|
Graphic::Vector(vector) => vector_retained_heap(vector),
|
||||||
|
Graphic::RasterCPU(raster) => raster.data.len() * size_of::<Color>(),
|
||||||
|
Graphic::Text(text) => text.len(),
|
||||||
|
Graphic::Gradient(gradient) => gradient.len() * size_of::<(f64, Color)>(),
|
||||||
|
Graphic::Graphic(children) => (0..children.len()).filter_map(|index| children.element(index)).map(graphic_retained_heap).sum(),
|
||||||
|
Graphic::Group(_) | Graphic::RasterGPU(_) | Graphic::Color(_) => 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The heap a vector's domain columns own, summed over the columns it
|
||||||
|
/// exposes, so the segment domain's private parallel columns are undercounted.
|
||||||
|
fn vector_retained_heap(vector: &Vector) -> usize {
|
||||||
|
size_of_val(vector.point_domain.ids())
|
||||||
|
+ size_of_val(vector.point_domain.positions())
|
||||||
|
+ size_of_val(vector.segment_domain.ids())
|
||||||
|
+ size_of_val(vector.region_domain.ids())
|
||||||
|
+ size_of_val(vector.colinear_manipulators.as_slice())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn graphic_contains_groups(graphic: &Graphic) -> bool {
|
||||||
|
match graphic {
|
||||||
|
Graphic::Group(_) => true,
|
||||||
|
Graphic::Graphic(children) => list_contains_groups(children),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn list_contains_groups(list: &List<Graphic>) -> bool {
|
||||||
|
(0..list.len()).any(|index| list.element(index).is_some_and(graphic_contains_groups))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The heap a graphic list's elements own, group interiors excluded as
|
||||||
|
/// [`graphic_retained_heap`] excludes them.
|
||||||
|
fn list_retained_heap(list: &List<Graphic>) -> usize {
|
||||||
|
(0..list.len()).filter_map(|index| list.element(index)).map(graphic_retained_heap).sum()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The deep copy-out for graphic-list field values (the paint markers' owned
|
||||||
|
/// form): content groups leave in their owned form. Declines (`None`) for
|
||||||
|
/// group-free content, which already owns everything.
|
||||||
|
fn deep_clone_graphic_list(value: &dyn core_types::list::AnyAttributeValue) -> Option<Box<dyn core_types::list::AnyAttributeValue>> {
|
||||||
|
let list = value.as_any().downcast_ref::<Option<List<Graphic>>>().expect("a graphic list field deep-copies at its own type");
|
||||||
|
let list = list.as_ref().filter(|list| list_contains_groups(list))?;
|
||||||
|
let mut list = list.clone();
|
||||||
|
for element in list.iter_element_values_mut() {
|
||||||
|
*element = map_groups_to_owned(element);
|
||||||
|
}
|
||||||
|
Some(Box::new(Some(list)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The deep replay for graphic-list field values: owned content groups replay
|
||||||
|
/// into the serving arena before the field re-parks. `Some(None)` declines
|
||||||
|
/// for group-free content; `None` reports arena exhaustion.
|
||||||
|
fn deep_repark_graphic_list(value: &dyn core_types::list::AnyAttributeValue, arena: &core_types::arena::Arena) -> Option<Option<Box<dyn core_types::list::AnyAttributeValue>>> {
|
||||||
|
let list = value.as_any().downcast_ref::<Option<List<Graphic>>>().expect("a graphic list field replays at its own type");
|
||||||
|
let Some(list) = list.as_ref().filter(|list| list_contains_groups(list)) else {
|
||||||
|
return Some(None);
|
||||||
|
};
|
||||||
|
let mut list = list.clone();
|
||||||
|
for element in list.iter_element_values_mut() {
|
||||||
|
*element = map_groups_to_resident(element, arena)?;
|
||||||
|
}
|
||||||
|
let list = unsafe { core_types::record::erase_static(list) };
|
||||||
|
Some(Some(Box::new(Some(list))))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The promote for graphic-list fields, the deep field glue's third half: the
|
||||||
|
/// owned halves copy content groups out to the owned form and replay them back,
|
||||||
|
/// while this maps the content transient-to-persistent in one pass.
|
||||||
|
///
|
||||||
|
/// THE TWO-LEVEL SHARING LAW: the field's own header is not provenance-shared.
|
||||||
|
/// It moves where the content is group-free, since the payload then owns all of
|
||||||
|
/// its content and the transient arena confirms the reference is its own park,
|
||||||
|
/// and otherwise it clones into a fresh persistent park. One level inside, a
|
||||||
|
/// content group's interior is arena-resident and its provenance is decidable,
|
||||||
|
/// so it takes [`map_groups_to_persistent`]'s Cow dispatch: an interior the
|
||||||
|
/// persistent region already holds is shared pointer for pointer.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// `src` must point at a live parked graphic-list field, and `dst` at the field
|
||||||
|
/// slot the promoted reference is written to.
|
||||||
|
unsafe fn promote_graphic_list(src: *const u8, dst: *mut u8, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
|
||||||
|
// SAFETY: the caller's contract; the slot holds one optional reference.
|
||||||
|
let Some(list) = (unsafe { src.cast::<Option<&List<Graphic<'static>>>>().read() }) else {
|
||||||
|
// SAFETY: as above, into the promoted image's own field slot.
|
||||||
|
unsafe { dst.cast::<Option<&List<Graphic<'static>>>>().write(None) };
|
||||||
|
return Some(());
|
||||||
|
};
|
||||||
|
let retained = list_retained_heap(list);
|
||||||
|
if !list_contains_groups(list) {
|
||||||
|
// SAFETY: a group-free list owns all of its content, and the arena
|
||||||
|
// declines a reference that is not a park at the list's own address
|
||||||
|
// and size.
|
||||||
|
if let Some(moved) = unsafe { promotion.move_park::<List<Graphic<'static>>>(std::ptr::from_ref(list).cast(), retained) } {
|
||||||
|
// SAFETY: the move published a live list in the persistent region.
|
||||||
|
unsafe { dst.cast::<Option<&List<Graphic<'static>>>>().write(Some(&*moved)) };
|
||||||
|
return Some(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut promoted = list.clone();
|
||||||
|
for element in promoted.iter_element_values_mut() {
|
||||||
|
*element = map_groups_to_persistent(element, promotion)?;
|
||||||
|
}
|
||||||
|
// SAFETY: every borrow the clone carried was replaced by persistent content
|
||||||
|
// above, so the erased form outlives the evaluation.
|
||||||
|
let promoted = unsafe { core_types::record::erase_static(promoted) };
|
||||||
|
let (parked, _) = promotion.persistent().alloc_sized(promoted, retained)?;
|
||||||
|
// SAFETY: the slot holds one optional reference.
|
||||||
|
unsafe { dst.cast::<Option<&List<Graphic<'static>>>>().write(Some(parked)) };
|
||||||
|
Some(())
|
||||||
|
}
|
||||||
|
|
||||||
|
const _: () = {
|
||||||
|
fn register_all() {
|
||||||
|
core_types::record::register_deep_element_clone::<Graphic>(deep_clone_graphic, deep_repark_graphic);
|
||||||
|
core_types::record::register_deep_field_value::<Option<List<Graphic>>>(deep_clone_graphic_list, deep_repark_graphic_list);
|
||||||
|
core_types::record::register_field_promote::<Option<&'static List<Graphic<'static>>>>(promote_graphic_list);
|
||||||
|
core_types::record::register_element_promote::<Graphic>(promote_graphic);
|
||||||
|
core_types::record::register_retained_heap::<Graphic>(|value| value.downcast_ref::<Graphic>().map_or(0, graphic_retained_heap));
|
||||||
|
core_types::record::register_retained_heap::<Vector>(|value| value.downcast_ref::<Vector>().map_or(0, vector_retained_heap));
|
||||||
|
core_types::record::register_retained_heap::<Raster<CPU>>(|value| value.downcast_ref::<Raster<CPU>>().map_or(0, |raster| raster.data.len() * size_of::<Color>()));
|
||||||
|
core_types::record::register_retained_heap::<String>(|value| value.downcast_ref::<String>().map_or(0, String::len));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_family = "wasm"))]
|
||||||
|
#[core_types::ctor::ctor]
|
||||||
|
fn register() {
|
||||||
|
register_all();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_family = "wasm")]
|
||||||
|
#[unsafe(export_name = "__node_registry_deep_element_graphic")]
|
||||||
|
extern "C" fn register() {
|
||||||
|
register_all();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod run_tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::graphic::test_support::{native_group_paint, unit_square_at};
|
||||||
|
use crate::graphic::{group_to_legacy_list, map_groups_to_legacy};
|
||||||
|
use crate::markers::Fill;
|
||||||
|
use core_types::attribute::Attribute;
|
||||||
|
use core_types::lane::LaneSource;
|
||||||
|
use core_types::record::{FieldWrite, RunBuilder, RunView, element_write_hashed};
|
||||||
|
use glam::DVec2;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_owned_group_replays_content_equal_after_the_source_dies() {
|
||||||
|
let paint = List::new_from_element(Graphic::Color(Color::BLACK));
|
||||||
|
let vector = unit_square_at(DVec2::ZERO);
|
||||||
|
|
||||||
|
let source = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||||
|
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||||
|
let lane = builder.push(vector.clone()).unwrap();
|
||||||
|
builder.attr::<Fill>(lane, Some(&paint));
|
||||||
|
let group = core_types::record::Group { row: None, content: builder.finish() };
|
||||||
|
let expected = group_to_legacy_list(&group);
|
||||||
|
let owned = map_groups_to_owned(&Graphic::Group(group));
|
||||||
|
drop(source);
|
||||||
|
|
||||||
|
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||||
|
let resident = map_groups_to_resident(&owned, &arena).expect("the arena holds the replay");
|
||||||
|
let Graphic::Group(group) = &resident else { panic!("the replay keeps the group form") };
|
||||||
|
assert_eq!(group_to_legacy_list(group), expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_owned_group_replays_nested_groups_through_the_element_glue() {
|
||||||
|
let vector = unit_square_at(DVec2::ZERO);
|
||||||
|
let source = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||||
|
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[], 1).unwrap();
|
||||||
|
builder.push(vector.clone()).unwrap();
|
||||||
|
let nested = Graphic::Group(core_types::record::Group { row: None, content: builder.finish() });
|
||||||
|
|
||||||
|
let mut builder = RunBuilder::new(&source, element_write_hashed::<Graphic>(), &[], 1).unwrap();
|
||||||
|
builder.push(nested).unwrap();
|
||||||
|
let group = core_types::record::Group { row: None, content: builder.finish() };
|
||||||
|
let expected = group_to_legacy_list(&group);
|
||||||
|
let owned = map_groups_to_owned(&Graphic::Group(group));
|
||||||
|
drop(source);
|
||||||
|
|
||||||
|
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||||
|
let resident = map_groups_to_resident(&owned, &arena).expect("the arena holds the replay");
|
||||||
|
let Graphic::Group(group) = &resident else { panic!("the replay keeps the group form") };
|
||||||
|
assert_eq!(group_to_legacy_list(group), expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_owned_run_deep_copies_graphic_list_fields() {
|
||||||
|
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||||
|
let source = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||||
|
// SAFETY: the erased native list serves only while `source` is live; the
|
||||||
|
// deep glue under test replaces its borrows at the copy-out seam.
|
||||||
|
let paint = unsafe { core_types::record::erase_static(native_group_paint(&inner_vector, &source)) };
|
||||||
|
|
||||||
|
let vector = unit_square_at(DVec2::new(4., 4.));
|
||||||
|
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||||
|
let lane = builder.push(vector.clone()).unwrap();
|
||||||
|
builder.attr::<Fill>(lane, Some(&paint));
|
||||||
|
let item = builder.finish();
|
||||||
|
let owned = item.copy_out();
|
||||||
|
let expected = map_groups_to_legacy(paint.element(0).unwrap());
|
||||||
|
drop(item);
|
||||||
|
drop(paint);
|
||||||
|
drop(source);
|
||||||
|
|
||||||
|
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||||
|
let replayed = owned.replay(&arena).expect("the arena holds the replay");
|
||||||
|
let run = RunView::<Vector>::new(&replayed).expect("the run holds vector elements");
|
||||||
|
let served = run.attr::<Fill>(0).expect("the fill replays present");
|
||||||
|
assert_eq!(map_groups_to_legacy(served.element(0).unwrap()), expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_owned_record_deep_copies_graphic_list_fields() {
|
||||||
|
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||||
|
let source = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||||
|
// SAFETY: the erased native list serves only while `source` is live; the
|
||||||
|
// deep glue under test replaces its borrows at the copy-out seam.
|
||||||
|
let paint = unsafe { core_types::record::erase_static(native_group_paint(&inner_vector, &source)) };
|
||||||
|
|
||||||
|
let vector = unit_square_at(DVec2::new(4., 4.));
|
||||||
|
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||||
|
let lane = builder.push(vector.clone()).unwrap();
|
||||||
|
builder.attr::<Fill>(lane, Some(&paint));
|
||||||
|
let item = builder.finish();
|
||||||
|
let layout = item.layout().clone();
|
||||||
|
let offset = layout.offset_of(Fill::NAME, 0).unwrap();
|
||||||
|
// SAFETY: the item's lane is a live record of `layout`.
|
||||||
|
let owned = unsafe { core_types::record::OwnedRecord::copy_out(&layout, item.lanes().get(0).rec()) };
|
||||||
|
let expected = map_groups_to_legacy(paint.element(0).unwrap());
|
||||||
|
drop(item);
|
||||||
|
drop(paint);
|
||||||
|
drop(source);
|
||||||
|
|
||||||
|
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||||
|
let frames = core_types::record::test_frames(layout.frame_bytes());
|
||||||
|
let mut slot = frames.claim(&layout);
|
||||||
|
owned.replay_into(&mut slot, &arena).expect("the arena holds the replay");
|
||||||
|
// SAFETY: the replay completes the record in the claimed frame.
|
||||||
|
let value = unsafe { slot.finish() };
|
||||||
|
// SAFETY: the replay wrote a record of `layout`.
|
||||||
|
let served = unsafe { layout.rec(&value).read::<Option<&List<Graphic>>>(offset) }.expect("the fill replays present");
|
||||||
|
assert_eq!(map_groups_to_legacy(served.element(0).unwrap()), expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `lanes`-long frame promoted out of `transient` into `persistent`, with
|
||||||
|
/// `fill` written into the paint field of every lane. The frame buffer comes
|
||||||
|
/// back so it outlives the promote's reads.
|
||||||
|
fn promote_paint_field(
|
||||||
|
fill: Option<&List<Graphic<'static>>>,
|
||||||
|
lanes: usize,
|
||||||
|
transient: &core_types::arena::Arena,
|
||||||
|
persistent: &core_types::arena::Arena,
|
||||||
|
) -> (core_types::record::Layout, core_types::record::MaterializedSpan, Vec<u64>) {
|
||||||
|
use core_types::record::{Layout, MaterializedSpan, Promotion, element_write, write_field};
|
||||||
|
|
||||||
|
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[FieldWrite::of::<Fill>(0)]);
|
||||||
|
let offset = layout.offset_of(Fill::NAME, 0).unwrap();
|
||||||
|
let stride = layout.lane_stride();
|
||||||
|
let mut buffer = vec![0u64; (lanes * stride).div_ceil(8)];
|
||||||
|
let base = buffer.as_mut_ptr().cast::<u8>();
|
||||||
|
let bounds = (base as usize, buffer.len() * 8);
|
||||||
|
for lane in 0..lanes {
|
||||||
|
// SAFETY: the frame is this layout's, written at the element slot and
|
||||||
|
// at the paint field's own offset.
|
||||||
|
unsafe {
|
||||||
|
base.add(lane * stride).cast::<f64>().write(lane as f64);
|
||||||
|
write_field::<Option<&List<Graphic<'static>>>>(base.add(lane * stride), offset, fill);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// SAFETY: the frames hold `lanes` live records of `layout`.
|
||||||
|
let batch = unsafe { core_types::node::RecordBatch::new(base.cast_const(), lanes, &layout) };
|
||||||
|
let promotion = Promotion::new(transient, bounds, persistent);
|
||||||
|
// SAFETY: as above.
|
||||||
|
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) }.expect("the region holds the promote");
|
||||||
|
(layout, span, buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The promoted paint of one lane, at the layout the promote published.
|
||||||
|
fn promoted_paint<'p>(
|
||||||
|
span: &core_types::record::MaterializedSpan,
|
||||||
|
layout: &core_types::record::Layout,
|
||||||
|
lane: usize,
|
||||||
|
persistent: &'p core_types::arena::Arena,
|
||||||
|
) -> &'p List<Graphic<'p>> {
|
||||||
|
let offset = layout.offset_of(Fill::NAME, 0).unwrap();
|
||||||
|
let batch = span.batch(persistent, layout).expect("the span resolves in its own region");
|
||||||
|
// SAFETY: the promote wrote a record of `layout` into every lane.
|
||||||
|
unsafe { batch.get(lane).rec().read::<Option<&List<Graphic>>>(offset) }.expect("the paint promotes present")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_promoted_paint_field_shares_persistent_interiors() {
|
||||||
|
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||||
|
let transient = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||||
|
let persistent = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||||
|
|
||||||
|
// The interior an upstream promote already published, named by a paint
|
||||||
|
// list the evaluation parked.
|
||||||
|
let published = native_group_paint(&inner_vector, &persistent);
|
||||||
|
let interior = {
|
||||||
|
let Some(Graphic::Group(group)) = published.element(0) else { panic!("the paint carries a native group") };
|
||||||
|
group.content.lanes().get(0).rec().ptr()
|
||||||
|
};
|
||||||
|
// SAFETY: the list serves only while `persistent` is live, and the
|
||||||
|
// promote under test replaces every borrow it carries.
|
||||||
|
let (paint, _) = transient.alloc_sized_keyed(unsafe { core_types::record::erase_static(published) }, 0).unwrap();
|
||||||
|
|
||||||
|
let occupied = persistent.occupancy();
|
||||||
|
let (layout, span, _frames) = promote_paint_field(Some(paint), 1, &transient, &persistent);
|
||||||
|
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||||
|
|
||||||
|
let Some(Graphic::Group(group)) = served.element(0) else { panic!("the promote keeps the group form") };
|
||||||
|
assert_eq!(group.content.lanes().get(0).rec().ptr(), interior, "a persistent interior is shared pointer for pointer");
|
||||||
|
assert!(
|
||||||
|
persistent.occupancy() - occupied <= layout.frame_bytes() + size_of::<List<Graphic>>() + align_of::<List<Graphic>>(),
|
||||||
|
"the promote allocated the lane slab and the field's own header, never the owned form of the shared interior"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_group_free_paint_field_moves_its_parked_header() {
|
||||||
|
let mut transient = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||||
|
let persistent = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||||
|
|
||||||
|
let paint = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::ZERO)));
|
||||||
|
let heap = {
|
||||||
|
let Some(Graphic::Vector(vector)) = paint.element(0) else { panic!("the paint carries a vector") };
|
||||||
|
vector.point_domain.positions().as_ptr()
|
||||||
|
};
|
||||||
|
let (paint, _) = transient.alloc_sized_keyed(paint, 0).unwrap();
|
||||||
|
|
||||||
|
let (layout, span, _frames) = promote_paint_field(Some(paint), 2, &transient, &persistent);
|
||||||
|
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||||
|
let Some(Graphic::Vector(vector)) = served.element(0) else { panic!("the promote keeps the vector") };
|
||||||
|
assert_eq!(vector.point_domain.positions().as_ptr(), heap, "the promote moved the header, so the served paint names the pre-promote heap");
|
||||||
|
assert!(std::ptr::eq(served, promoted_paint(&span, &layout, 1, &persistent)), "a paint two lanes share moves once");
|
||||||
|
|
||||||
|
transient.reset();
|
||||||
|
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||||
|
assert!(matches!(served.element(0), Some(Graphic::Vector(_))), "the moved paint survives the transient reset");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
//! The legacy bridge: record-backed groups rebuilt as owned legacy lists.
|
||||||
|
|
||||||
|
use super::walk::push_lane_paint_into_interiors;
|
||||||
|
use super::{Graphic, detable_items};
|
||||||
|
use crate::markers::{ATTR_FILL, ATTR_STROKE};
|
||||||
|
use core_types::Color;
|
||||||
|
use core_types::list::{AttributeValueDyn, Item, List};
|
||||||
|
use raster_types::{CPU, GPU, Raster};
|
||||||
|
use vector_types::{GradientStops, Vector};
|
||||||
|
|
||||||
|
/// One typed run as an owned list, elements cloned and every attribute copied
|
||||||
|
/// through its erased read. Content keeps its native form; the legacy
|
||||||
|
/// conversions layer their mapping on top.
|
||||||
|
pub fn run_to_list<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(item: &core_types::record::GroupItem) -> Option<List<T>> {
|
||||||
|
let lanes = item.typed_lanes::<T>()?;
|
||||||
|
let mut list = List::new();
|
||||||
|
for lane in 0..lanes.len() {
|
||||||
|
list.push(Item::new_from_element(lanes.element_ref(lane).clone()));
|
||||||
|
}
|
||||||
|
for field in &item.layout().fields {
|
||||||
|
for lane in 0..lanes.len() {
|
||||||
|
// SAFETY: the offset comes from the item's own layout.
|
||||||
|
let value = unsafe { (field.read_erased)(item.lanes().get(lane).rec().ptr().add(field.offset)) };
|
||||||
|
list.set_attribute_value_dyn(field.name, lane, AttributeValueDyn(value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(list)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Converts the group content of the list's paint attribute values to legacy
|
||||||
|
/// form, so a legacy product owns everything its attributes reach.
|
||||||
|
pub fn map_paint_attrs_to_legacy<T>(list: &mut List<T>) {
|
||||||
|
for key in [ATTR_FILL, ATTR_STROKE, crate::markers::ATTR_EDITOR_MERGED_LAYERS] {
|
||||||
|
let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(key) else { continue };
|
||||||
|
for value in values.flatten() {
|
||||||
|
for element in value.iter_element_values_mut() {
|
||||||
|
*element = map_groups_to_legacy(element);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One typed run as a legacy list: [`run_to_list`] with the paint attribute
|
||||||
|
/// contents converted to their legacy form.
|
||||||
|
pub(crate) fn run_to_legacy_list<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(item: &core_types::record::GroupItem) -> Option<List<T>> {
|
||||||
|
let mut list = run_to_list::<T>(item)?;
|
||||||
|
map_paint_attrs_to_legacy(&mut list);
|
||||||
|
Some(list)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The graphic with every `Group` converted to its legacy form.
|
||||||
|
pub fn map_groups_to_legacy<'out>(graphic: &Graphic<'_>) -> Graphic<'out> {
|
||||||
|
match graphic {
|
||||||
|
Graphic::Group(group) => group_to_legacy_graphic(group),
|
||||||
|
Graphic::Graphic(children) => {
|
||||||
|
let mut out = List::new();
|
||||||
|
for item in children.clone().into_iter() {
|
||||||
|
let (element, attributes) = item.into_parts();
|
||||||
|
out.push(Item::from_parts(map_groups_to_legacy(&element), attributes));
|
||||||
|
}
|
||||||
|
map_paint_attrs_to_legacy(&mut out);
|
||||||
|
Graphic::Graphic(out)
|
||||||
|
}
|
||||||
|
Graphic::Vector(vector) => Graphic::Vector(vector.clone()),
|
||||||
|
Graphic::RasterCPU(raster) => Graphic::RasterCPU(raster.clone()),
|
||||||
|
Graphic::RasterGPU(raster) => Graphic::RasterGPU(raster.clone()),
|
||||||
|
Graphic::Color(color) => Graphic::Color(*color),
|
||||||
|
Graphic::Gradient(gradient) => Graphic::Gradient(gradient.clone()),
|
||||||
|
Graphic::Text(text) => Graphic::Text(text.clone()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The group as one legacy graphic. A bare (row-less) wrap of a single typed
|
||||||
|
/// run keeps the run's typed variant, matching the `Into<Graphic>` the
|
||||||
|
/// pre-flip wrap applied; everything else becomes the legacy group list.
|
||||||
|
pub fn group_to_legacy_graphic(group: &core_types::record::Group) -> Graphic<'static> {
|
||||||
|
if group.row.is_none() {
|
||||||
|
let item = &group.content;
|
||||||
|
let typed = None
|
||||||
|
.or_else(|| run_to_legacy_list::<Vector>(item).map(|list| detable_items(list, Graphic::Vector)))
|
||||||
|
.or_else(|| run_to_legacy_list::<Raster<CPU>>(item).map(|list| detable_items(list, Graphic::RasterCPU)))
|
||||||
|
.or_else(|| run_to_legacy_list::<Raster<GPU>>(item).map(|list| detable_items(list, Graphic::RasterGPU)))
|
||||||
|
.or_else(|| run_to_legacy_list::<Color>(item).map(|list| detable_items(list, Graphic::Color)))
|
||||||
|
.or_else(|| run_to_legacy_list::<GradientStops>(item).map(|list| detable_items(list, Graphic::Gradient)))
|
||||||
|
.or_else(|| run_to_legacy_list::<String>(item).map(|list| detable_items(list, Graphic::Text)));
|
||||||
|
if let Some(typed) = typed {
|
||||||
|
return Graphic::Graphic(typed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Graphic::Graphic(group_to_legacy_list(group))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The group as a legacy `List<Graphic>`: a `Graphic` run becomes the items,
|
||||||
|
/// another typed run becomes one de-tabled leaf item per lane.
|
||||||
|
pub fn group_to_legacy_list(group: &core_types::record::Group) -> List<Graphic<'static>> {
|
||||||
|
let item = &group.content;
|
||||||
|
if let Some(mut list) = run_to_legacy_list::<Graphic>(item) {
|
||||||
|
for element in list.iter_element_values_mut() {
|
||||||
|
*element = map_groups_to_legacy(element);
|
||||||
|
}
|
||||||
|
push_lane_paint_into_interiors(&mut list);
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
None.or_else(|| run_to_legacy_list::<Vector>(item).map(|list| detable_items(list, Graphic::Vector)))
|
||||||
|
.or_else(|| run_to_legacy_list::<Raster<CPU>>(item).map(|list| detable_items(list, Graphic::RasterCPU)))
|
||||||
|
.or_else(|| run_to_legacy_list::<Raster<GPU>>(item).map(|list| detable_items(list, Graphic::RasterGPU)))
|
||||||
|
.or_else(|| run_to_legacy_list::<Color>(item).map(|list| detable_items(list, Graphic::Color)))
|
||||||
|
.or_else(|| run_to_legacy_list::<GradientStops>(item).map(|list| detable_items(list, Graphic::Gradient)))
|
||||||
|
.or_else(|| run_to_legacy_list::<String>(item).map(|list| detable_items(list, Graphic::Text)))
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod run_tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::graphic::test_support::{native_group_paint, unit_square_at};
|
||||||
|
use crate::markers::Fill;
|
||||||
|
use core_types::attribute::Attribute;
|
||||||
|
use core_types::record::{FieldWrite, RunBuilder, element_write_hashed};
|
||||||
|
use glam::DVec2;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_legacy_list_owns_its_paint_attr_content() {
|
||||||
|
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||||
|
let source = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||||
|
// SAFETY: the erased native list serves only while `source` is live; the
|
||||||
|
// deep glue under test replaces its borrows at the copy-out seam.
|
||||||
|
let paint = unsafe { core_types::record::erase_static(native_group_paint(&inner_vector, &source)) };
|
||||||
|
|
||||||
|
let vector = unit_square_at(DVec2::new(4., 4.));
|
||||||
|
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||||
|
let lane = builder.push(vector.clone()).unwrap();
|
||||||
|
builder.attr::<Fill>(lane, Some(&paint));
|
||||||
|
let item = builder.finish();
|
||||||
|
let legacy = run_to_legacy_list::<Vector>(&item).expect("the run lowers to a legacy vector list");
|
||||||
|
let expected = map_groups_to_legacy(paint.element(0).unwrap());
|
||||||
|
drop(item);
|
||||||
|
drop(paint);
|
||||||
|
drop(source);
|
||||||
|
|
||||||
|
let served = legacy.attribute::<Option<List<Graphic>>>(Fill::NAME, 0).expect("the fill attribute rides the list");
|
||||||
|
let served = served.as_ref().expect("the fill is present");
|
||||||
|
assert_eq!(served.element(0).unwrap(), &expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_run_list_keeps_native_group_elements() {
|
||||||
|
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||||
|
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||||
|
let content = native_group_paint(&inner_vector, &arena);
|
||||||
|
let element = content.element(0).unwrap();
|
||||||
|
|
||||||
|
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Graphic>(), &[], 1).unwrap();
|
||||||
|
builder.push(element.clone()).unwrap();
|
||||||
|
let item = builder.finish();
|
||||||
|
let list = run_to_list::<Graphic>(&item).expect("the run holds graphic lanes");
|
||||||
|
assert!(matches!(list.element(0), Some(Graphic::Group(_))), "the list keeps the native group form");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,697 @@
|
|||||||
|
mod glue;
|
||||||
|
mod legacy;
|
||||||
|
mod paint;
|
||||||
|
mod walk;
|
||||||
|
|
||||||
|
pub(crate) use glue::list_contains_groups;
|
||||||
|
pub use glue::{map_groups_to_owned, map_groups_to_persistent, map_groups_to_resident};
|
||||||
|
pub(crate) use legacy::run_to_legacy_list;
|
||||||
|
pub use legacy::{group_to_legacy_graphic, group_to_legacy_list, map_groups_to_legacy, map_paint_attrs_to_legacy, run_to_list};
|
||||||
|
pub use paint::{
|
||||||
|
LanePaint, PaintColumns, PaintOverlay, PaintOverlayColumn, PaintReach, bake_paint_transforms, has_paint, is_paint_present, paint_graphics, set_paint_attribute, set_paint_attribute_at,
|
||||||
|
vector_can_reduce_to_clip_path,
|
||||||
|
};
|
||||||
|
pub use walk::{GraphicLevel, GraphicLevelColumn, RowStep, VectorRow, direct_vector_len, flatten_vector_rows, group_is_empty, lane_attributes, run_lane_attributes, walk_vector_rows};
|
||||||
|
use walk::{group_all_clipped, group_bounding_box, group_is_fully_transparent, group_is_opaque, group_render_complexity};
|
||||||
|
|
||||||
|
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||||
|
use core_types::graphene_hash::CacheHash;
|
||||||
|
use core_types::list::{Item, List};
|
||||||
|
use core_types::ops::{FromAnchorPosition, ListConvert};
|
||||||
|
use core_types::render_complexity::RenderComplexity;
|
||||||
|
use core_types::uuid::NodeId;
|
||||||
|
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||||
|
use dyn_any::DynAny;
|
||||||
|
use glam::{DAffine2, DVec2};
|
||||||
|
use raster_types::{CPU, GPU, Raster};
|
||||||
|
use vector_types::GradientStops;
|
||||||
|
pub use vector_types::Vector;
|
||||||
|
|
||||||
|
/// The possible forms of graphical content that can be rendered by the Render node into either an image or SVG syntax.
|
||||||
|
/// A leaf holds its element directly; its attributes ride the containing
|
||||||
|
/// lane. Multi-element content is a [`core_types::record::Group`] run, or
|
||||||
|
/// transitionally the legacy `Graphic` list.
|
||||||
|
#[derive(Clone, Debug, CacheHash, PartialEq, DynAny)]
|
||||||
|
pub enum Graphic<'e> {
|
||||||
|
Graphic(List<Graphic<'e>>),
|
||||||
|
Vector(Vector),
|
||||||
|
RasterCPU(Raster<CPU>),
|
||||||
|
RasterGPU(Raster<GPU>),
|
||||||
|
Color(Color),
|
||||||
|
Gradient(GradientStops),
|
||||||
|
Text(String),
|
||||||
|
Group(core_types::record::Group<'e>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Graphic<'_> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::Graphic(List::new())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A typed legacy list as a legacy graphic list: each item de-tables to a
|
||||||
|
/// leaf element, keeping its attributes on the containing lane.
|
||||||
|
pub(in crate::graphic) fn detable_items<'e, T: Clone + Send + Sync + 'static>(list: List<T>, leaf: fn(T) -> Graphic<'e>) -> List<Graphic<'e>> {
|
||||||
|
let mut out = List::new();
|
||||||
|
for item in list.into_iter() {
|
||||||
|
let (element, attributes) = item.into_parts();
|
||||||
|
out.push(Item::from_parts(leaf(element), attributes));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The element-space coercion into `Graphic`: a leaf converts in place and a
|
||||||
|
/// legacy list becomes a native group built over the arena, so the coercion
|
||||||
|
/// never constructs a legacy interior.
|
||||||
|
pub trait IntoGraphicElement: Clone + Send + Sync + CacheHash + 'static {
|
||||||
|
/// `None` reports arena exhaustion.
|
||||||
|
fn into_graphic_element(self, arena: &core_types::arena::Arena) -> Option<Graphic<'_>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn list_group<T: Clone + Send + Sync + CacheHash + PartialEq + dyn_any::StaticTypeSized>(list: List<T>, arena: &core_types::arena::Arena) -> Option<Graphic<'_>>
|
||||||
|
where
|
||||||
|
T::Static: Clone + Send + Sync,
|
||||||
|
{
|
||||||
|
Some(Graphic::Group(core_types::record::Group {
|
||||||
|
row: None,
|
||||||
|
content: core_types::record::GroupItem::from_list(list, arena)?,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! into_graphic_element {
|
||||||
|
($($leaf:ident: $element:ty;)*) => {
|
||||||
|
$(
|
||||||
|
impl IntoGraphicElement for $element {
|
||||||
|
fn into_graphic_element(self, _arena: &core_types::arena::Arena) -> Option<Graphic<'_>> {
|
||||||
|
Some(Graphic::$leaf(self))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoGraphicElement for List<$element> {
|
||||||
|
fn into_graphic_element(self, arena: &core_types::arena::Arena) -> Option<Graphic<'_>> {
|
||||||
|
list_group(self, arena)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)*
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
into_graphic_element! {
|
||||||
|
Vector: Vector;
|
||||||
|
RasterCPU: Raster<CPU>;
|
||||||
|
RasterGPU: Raster<GPU>;
|
||||||
|
Color: Color;
|
||||||
|
Gradient: GradientStops;
|
||||||
|
Text: String;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoGraphicElement for Graphic<'static> {
|
||||||
|
fn into_graphic_element(self, _arena: &core_types::arena::Arena) -> Option<Graphic<'_>> {
|
||||||
|
Some(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoGraphicElement for List<Graphic<'static>> {
|
||||||
|
fn into_graphic_element(self, arena: &core_types::arena::Arena) -> Option<Graphic<'_>> {
|
||||||
|
list_group(self, arena)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Vector
|
||||||
|
impl From<Vector> for Graphic<'_> {
|
||||||
|
fn from(vector: Vector) -> Self {
|
||||||
|
Graphic::Vector(vector)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Raster<CPU>
|
||||||
|
impl From<Raster<CPU>> for Graphic<'_> {
|
||||||
|
fn from(raster: Raster<CPU>) -> Self {
|
||||||
|
Graphic::RasterCPU(raster)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Raster<GPU>
|
||||||
|
impl From<Raster<GPU>> for Graphic<'_> {
|
||||||
|
fn from(raster: Raster<GPU>) -> Self {
|
||||||
|
Graphic::RasterGPU(raster)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Color
|
||||||
|
impl From<Color> for Graphic<'_> {
|
||||||
|
fn from(color: Color) -> Self {
|
||||||
|
Graphic::Color(color)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Note: List<Color> -> Option<Color> is in gcore (Color is defined there)
|
||||||
|
|
||||||
|
// GradientStops
|
||||||
|
impl From<GradientStops> for Graphic<'_> {
|
||||||
|
fn from(gradient: GradientStops) -> Self {
|
||||||
|
Graphic::Gradient(gradient)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// String
|
||||||
|
impl From<String> for Graphic<'_> {
|
||||||
|
fn from(text: String) -> Self {
|
||||||
|
Graphic::Text(text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deeply flattens a `List<Graphic>`, collecting only elements matching a specific variant (extracted by `extract_variant`)
|
||||||
|
/// and discarding all other non-matching content. Recursion through `Graphic::Graphic` sub-`List`s composes transforms and opacity.
|
||||||
|
fn flatten_graphic_list<T>(content: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) -> List<T> {
|
||||||
|
fn flatten_recursive<T>(output: &mut List<T>, current_graphic_list: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>, parent_layer_path: Option<&[NodeId]>) {
|
||||||
|
for current_graphic_item in current_graphic_list.into_iter() {
|
||||||
|
// Whether the parent carries each attribute: a structural fact (column presence), never a value comparison.
|
||||||
|
// Flattening composes a parent attribute onto its children only when the parent has it,
|
||||||
|
// so an absent parent attribute never invents a column the children didn't already have.
|
||||||
|
let parent_has_transform = current_graphic_item.attribute::<DAffine2>(ATTR_TRANSFORM).is_some();
|
||||||
|
let parent_has_opacity = current_graphic_item.attribute::<f64>(ATTR_OPACITY).is_some();
|
||||||
|
let parent_has_fill = current_graphic_item.attribute::<f64>(ATTR_OPACITY_FILL).is_some();
|
||||||
|
|
||||||
|
let current_transform: DAffine2 = current_graphic_item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||||
|
let current_opacity: f64 = current_graphic_item.attribute_cloned_or(ATTR_OPACITY, 1.);
|
||||||
|
let current_fill: f64 = current_graphic_item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
|
||||||
|
let lane_layer_path: Option<Vec<NodeId>> = current_graphic_item.attribute::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH).cloned();
|
||||||
|
|
||||||
|
let (element, attributes) = current_graphic_item.into_parts();
|
||||||
|
match element {
|
||||||
|
// Compose the parent's transform/opacity/fill onto each child, but only for attributes the parent carries.
|
||||||
|
// A child lacking one is padded with the composition identity (`1.` for opacity/fill, identity for transform), so composing through it is a no-op.
|
||||||
|
Graphic::Graphic(mut sub_list) => {
|
||||||
|
if parent_has_transform {
|
||||||
|
for v in sub_list.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||||
|
*v = current_transform * *v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if parent_has_opacity {
|
||||||
|
for v in sub_list.iter_attribute_values_mut_or_default::<f64>(ATTR_OPACITY) {
|
||||||
|
*v *= current_opacity;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if parent_has_fill {
|
||||||
|
for v in sub_list.iter_attribute_values_mut_or_default::<f64>(ATTR_OPACITY_FILL) {
|
||||||
|
*v *= current_fill;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
flatten_recursive(output, sub_list, extract_variant, lane_layer_path.as_deref());
|
||||||
|
}
|
||||||
|
// A bridge row's native group flattens through its legacy lowering.
|
||||||
|
Graphic::Group(group) => {
|
||||||
|
let lowered = List::new_from_item(Item::from_parts(group_to_legacy_graphic(&group), attributes.clone()));
|
||||||
|
flatten_recursive(output, lowered, extract_variant, parent_layer_path);
|
||||||
|
}
|
||||||
|
// A de-tabled leaf is one attr-less element; the extracted row rides with its containing lane's full attributes, paint included.
|
||||||
|
// The enclosing group lane's own layer path overrides, one hop only, matching the native walk.
|
||||||
|
other => {
|
||||||
|
if let Some(typed_list) = extract_variant(other) {
|
||||||
|
for item in typed_list.into_iter() {
|
||||||
|
let mut row = Item::from_parts(item.into_element(), attributes.clone());
|
||||||
|
if let Some(layer_path) = parent_layer_path {
|
||||||
|
row.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.to_vec());
|
||||||
|
}
|
||||||
|
output.push(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut output = List::new();
|
||||||
|
flatten_recursive(&mut output, content, extract_variant, None);
|
||||||
|
output
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Maps from a concrete element type to its corresponding `Graphic` enum variant,
|
||||||
|
/// enabling type-directed casting of typed `List`s from a `Graphic` value.
|
||||||
|
pub trait TryFromGraphic: Clone + Sized {
|
||||||
|
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFromGraphic for Vector {
|
||||||
|
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||||
|
if let Graphic::Vector(t) = graphic { Some(List::new_from_element(t)) } else { None }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFromGraphic for Raster<CPU> {
|
||||||
|
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||||
|
if let Graphic::RasterCPU(t) = graphic { Some(List::new_from_element(t)) } else { None }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFromGraphic for Color {
|
||||||
|
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||||
|
if let Graphic::Color(t) = graphic { Some(List::new_from_element(t)) } else { None }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFromGraphic for GradientStops {
|
||||||
|
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||||
|
if let Graphic::Gradient(t) = graphic { Some(List::new_from_element(t)) } else { None }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFromGraphic for String {
|
||||||
|
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||||
|
if let Graphic::Text(t) = graphic { Some(List::new_from_element(t)) } else { None }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Local trait to convert types to List<Graphic> (avoids orphan rule issues)
|
||||||
|
pub trait IntoGraphicList: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static {
|
||||||
|
fn into_graphic_list(self) -> List<Graphic<'static>>;
|
||||||
|
|
||||||
|
/// Deeply flattens any content of type `T` within a `List<Graphic>`, discarding all other content, and returning a flat `List<T>`.
|
||||||
|
fn into_flattened_list<T: TryFromGraphic>(self) -> List<T>
|
||||||
|
where
|
||||||
|
Self: std::marker::Sized,
|
||||||
|
{
|
||||||
|
flatten_graphic_list(self.into_graphic_list(), T::try_from_graphic)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoGraphicList for List<Graphic<'static>> {
|
||||||
|
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoGraphicList for List<Vector> {
|
||||||
|
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||||
|
detable_items(self, Graphic::Vector)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoGraphicList for List<Raster<CPU>> {
|
||||||
|
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||||
|
detable_items(self, Graphic::RasterCPU)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoGraphicList for List<Raster<GPU>> {
|
||||||
|
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||||
|
detable_items(self, Graphic::RasterGPU)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoGraphicList for List<Color> {
|
||||||
|
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||||
|
detable_items(self, Graphic::Color)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoGraphicList for List<GradientStops> {
|
||||||
|
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||||
|
detable_items(self, Graphic::Gradient)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoGraphicList for List<String> {
|
||||||
|
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||||
|
detable_items(self, Graphic::Text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoGraphicList for DAffine2 {
|
||||||
|
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||||
|
List::new_from_element(Graphic::default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// DAffine2
|
||||||
|
impl From<DAffine2> for Graphic<'_> {
|
||||||
|
fn from(_: DAffine2) -> Self {
|
||||||
|
Graphic::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// DVec2
|
||||||
|
impl From<DVec2> for Graphic<'_> {
|
||||||
|
fn from(position: DVec2) -> Self {
|
||||||
|
Graphic::Vector(Vector::from_anchor_position(position))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Note: List conversions handled by blanket impl in gcore
|
||||||
|
|
||||||
|
impl<'e> Graphic<'e> {
|
||||||
|
pub fn as_graphic(&self) -> Option<&List<Graphic<'_>>> {
|
||||||
|
match self {
|
||||||
|
Graphic::Graphic(graphic) => Some(graphic),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_graphic_mut(&mut self) -> Option<&mut List<Graphic<'e>>> {
|
||||||
|
match self {
|
||||||
|
Graphic::Graphic(graphic) => Some(graphic),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_vector(&self) -> Option<&Vector> {
|
||||||
|
match self {
|
||||||
|
Graphic::Vector(vector) => Some(vector),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_raster(&self) -> Option<&Raster<CPU>> {
|
||||||
|
match self {
|
||||||
|
Graphic::RasterCPU(raster) => Some(raster),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_raster_mut(&mut self) -> Option<&mut Raster<CPU>> {
|
||||||
|
match self {
|
||||||
|
Graphic::RasterCPU(raster) => Some(raster),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A leaf carries no clipping attribute, which rides its containing lane.
|
||||||
|
pub fn had_clip_enabled(&self) -> bool {
|
||||||
|
fn all_clipped<T>(list: &List<T>) -> bool {
|
||||||
|
list.iter_attribute_values_or_default::<bool>(ATTR_CLIPPING_MASK).all(|clip| clip)
|
||||||
|
}
|
||||||
|
|
||||||
|
match self {
|
||||||
|
Graphic::Graphic(list) => all_clipped(list),
|
||||||
|
Graphic::Group(group) => group_all_clipped(group),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn can_reduce_to_clip_path(&self) -> bool {
|
||||||
|
match self {
|
||||||
|
Graphic::Vector(vector) => vector_can_reduce_to_clip_path(&core_types::lane::Single(vector)),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_opaque(&self) -> bool {
|
||||||
|
match self {
|
||||||
|
Graphic::Graphic(list) => !list.is_empty() && list.iter_element_values().all(Graphic::is_opaque),
|
||||||
|
// A bare leaf carries no paint attribute, which rides its lane, so
|
||||||
|
// nothing here claims opacity.
|
||||||
|
Graphic::Vector(_) => false,
|
||||||
|
Graphic::Color(color) => color.is_opaque(),
|
||||||
|
Graphic::Gradient(stops) => stops.iter().all(|stop| stop.color.is_opaque()),
|
||||||
|
Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Text(_) => false,
|
||||||
|
Graphic::Group(group) => group_is_opaque(group),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_fully_transparent(&self) -> bool {
|
||||||
|
match self {
|
||||||
|
Graphic::Graphic(list) => list.iter_element_values().all(Graphic::is_fully_transparent),
|
||||||
|
// A bare leaf carries no paint attribute, so only an unstroked
|
||||||
|
// vector is invisible on its own.
|
||||||
|
Graphic::Vector(vector) => vector.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke()),
|
||||||
|
Graphic::Color(color) => color.a() == 0.,
|
||||||
|
Graphic::Gradient(stops) => stops.iter().all(|stop| stop.color.a() == 0.),
|
||||||
|
Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Text(_) => false,
|
||||||
|
Graphic::Group(group) => group_is_fully_transparent(group),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True if this paint opaquely covers the entire fill region.
|
||||||
|
/// Vector, Raster, and a nested Graphic may leave gaps, so they return false.
|
||||||
|
pub fn covers_opaquely(&self) -> bool {
|
||||||
|
matches!(self, Graphic::Color(_) | Graphic::Gradient(_)) && self.is_opaque()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the graphic holds no content: a leaf always holds its element.
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
match self {
|
||||||
|
Graphic::Graphic(list) => list.is_empty(),
|
||||||
|
Graphic::Group(group) => group_is_empty(group),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BoundingBox for Graphic<'_> {
|
||||||
|
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||||
|
match self {
|
||||||
|
Graphic::Vector(vector) => BoundingBox::bounding_box(vector, transform, include_stroke),
|
||||||
|
Graphic::RasterCPU(raster) => raster.bounding_box(transform, include_stroke),
|
||||||
|
Graphic::RasterGPU(raster) => raster.bounding_box(transform, include_stroke),
|
||||||
|
Graphic::Graphic(list) => list.bounding_box(transform, include_stroke),
|
||||||
|
Graphic::Color(color) => color.bounding_box(transform, include_stroke),
|
||||||
|
Graphic::Gradient(gradient) => gradient.bounding_box(transform, include_stroke),
|
||||||
|
Graphic::Text(text) => text.bounding_box(transform, include_stroke),
|
||||||
|
Graphic::Group(group) => group_bounding_box(group, transform, include_stroke, false),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||||
|
match self {
|
||||||
|
Graphic::Vector(vector) => vector.thumbnail_bounding_box(transform, include_stroke),
|
||||||
|
Graphic::RasterCPU(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
|
||||||
|
Graphic::RasterGPU(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
|
||||||
|
Graphic::Graphic(graphic) => graphic.thumbnail_bounding_box(transform, include_stroke),
|
||||||
|
Graphic::Color(color) => color.thumbnail_bounding_box(transform, include_stroke),
|
||||||
|
Graphic::Gradient(gradient) => gradient.thumbnail_bounding_box(transform, include_stroke),
|
||||||
|
Graphic::Text(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||||
|
Graphic::Group(group) => group_bounding_box(group, transform, include_stroke, true),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'e> ListConvert<Graphic<'e>> for Vector {
|
||||||
|
fn convert_item(self) -> Graphic<'e> {
|
||||||
|
Graphic::Vector(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<'e> ListConvert<Graphic<'e>> for Raster<CPU> {
|
||||||
|
fn convert_item(self) -> Graphic<'e> {
|
||||||
|
Graphic::RasterCPU(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<'e> ListConvert<Graphic<'e>> for Raster<GPU> {
|
||||||
|
fn convert_item(self) -> Graphic<'e> {
|
||||||
|
Graphic::RasterGPU(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RenderComplexity for Graphic<'_> {
|
||||||
|
fn render_complexity(&self) -> usize {
|
||||||
|
match self {
|
||||||
|
Self::Graphic(list) => list.render_complexity(),
|
||||||
|
Self::Vector(list) => list.render_complexity(),
|
||||||
|
Self::RasterCPU(list) => list.render_complexity(),
|
||||||
|
Self::RasterGPU(list) => list.render_complexity(),
|
||||||
|
Self::Color(list) => list.render_complexity(),
|
||||||
|
Self::Gradient(list) => list.render_complexity(),
|
||||||
|
Self::Text(list) => list.render_complexity(),
|
||||||
|
Self::Group(group) => group_render_complexity(group),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Node definitions moved to graphic-nodes crate
|
||||||
|
|
||||||
|
pub trait AtIndex {
|
||||||
|
type Output;
|
||||||
|
fn at_index(&self, index: usize) -> Option<Self::Output>;
|
||||||
|
fn at_index_from_end(&self, index: usize) -> Option<Self::Output>;
|
||||||
|
}
|
||||||
|
impl<T: Clone> AtIndex for Vec<T> {
|
||||||
|
type Output = T;
|
||||||
|
|
||||||
|
fn at_index(&self, index: usize) -> Option<Self::Output> {
|
||||||
|
self.get(index).cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn at_index_from_end(&self, index: usize) -> Option<Self::Output> {
|
||||||
|
if index == 0 || index > self.len() { None } else { self.get(self.len() - index).cloned() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T: Clone> AtIndex for List<T> {
|
||||||
|
type Output = List<T>;
|
||||||
|
|
||||||
|
fn at_index(&self, index: usize) -> Option<Self::Output> {
|
||||||
|
self.clone_item(index).map(|item| {
|
||||||
|
let mut result_list = Self::default();
|
||||||
|
result_list.push(item);
|
||||||
|
result_list
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn at_index_from_end(&self, index: usize) -> Option<Self::Output> {
|
||||||
|
if index == 0 || index > self.len() { None } else { self.at_index(self.len() - index) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait OmitIndex {
|
||||||
|
fn omit_index(&self, index: usize) -> Self;
|
||||||
|
fn omit_index_from_end(&self, index: usize) -> Self;
|
||||||
|
}
|
||||||
|
impl<T: Clone> OmitIndex for Vec<T> {
|
||||||
|
fn omit_index(&self, index: usize) -> Self {
|
||||||
|
self.iter().enumerate().filter(|(i, _)| *i != index).map(|(_, v)| v.clone()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn omit_index_from_end(&self, index: usize) -> Self {
|
||||||
|
if index == 0 || index > self.len() {
|
||||||
|
return self.clone();
|
||||||
|
}
|
||||||
|
self.omit_index(self.len() - index)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T: Clone> OmitIndex for List<T> {
|
||||||
|
fn omit_index(&self, index: usize) -> Self {
|
||||||
|
let mut result = Self::default();
|
||||||
|
for i in 0..self.len() {
|
||||||
|
if i != index
|
||||||
|
&& let Some(item) = self.clone_item(i)
|
||||||
|
{
|
||||||
|
result.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
fn omit_index_from_end(&self, index: usize) -> Self {
|
||||||
|
if index == 0 || index > self.len() {
|
||||||
|
return self.clone();
|
||||||
|
}
|
||||||
|
self.omit_index(self.len() - index)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use core_types::list::List;
|
||||||
|
|
||||||
|
fn vector_graphic() -> Graphic<'static> {
|
||||||
|
Graphic::Vector(Vector::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Flattening must not invent attribute columns that neither the parent graphic nor the child carried
|
||||||
|
#[test]
|
||||||
|
fn flatten_does_not_invent_attributes() {
|
||||||
|
let graphics = List::new_from_element(vector_graphic());
|
||||||
|
let flattened: List<Vector> = graphics.into_flattened_list();
|
||||||
|
for key in [ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, ATTR_EDITOR_LAYER_PATH] {
|
||||||
|
assert!(!flattened.attribute_keys().any(|k| k == key), "flatten invented the `{key}` attribute");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A parent attribute that is present must compose onto the flattened children
|
||||||
|
#[test]
|
||||||
|
fn flatten_propagates_present_attributes() {
|
||||||
|
let mut graphics = List::new_from_element(vector_graphic());
|
||||||
|
graphics.set_attribute(ATTR_OPACITY, 0, 0.5_f64);
|
||||||
|
let flattened: List<Vector> = graphics.into_flattened_list();
|
||||||
|
assert_eq!(flattened.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 0), 0.5);
|
||||||
|
|
||||||
|
let mut group = List::new_from_element(Graphic::Graphic(List::new_from_element(vector_graphic())));
|
||||||
|
group.set_attribute(ATTR_OPACITY, 0, 0.5_f64);
|
||||||
|
let flattened: List<Vector> = group.into_flattened_list();
|
||||||
|
assert_eq!(flattened.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 0), 0.5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod graphic_is_opaque_tests {
|
||||||
|
use vector_types::GradientStop;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn color_graphic(alpha: f64) -> Graphic<'static> {
|
||||||
|
let color = Color::from_rgbaf32(1., 0., 0., alpha as f32).unwrap();
|
||||||
|
Graphic::Color(color)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn gradient_graphic(gradient: GradientStops) -> Graphic<'static> {
|
||||||
|
Graphic::Gradient(gradient)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn opaque_color_is_opaque() {
|
||||||
|
let g = color_graphic(1.);
|
||||||
|
assert!(g.is_opaque());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn transparent_color_is_not_opaque() {
|
||||||
|
let g = color_graphic(0.5);
|
||||||
|
assert!(!g.is_opaque());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vector_is_not_opaque() {
|
||||||
|
let g = Graphic::Vector(Vector::default());
|
||||||
|
assert!(!g.is_opaque());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gradient_with_all_opaque_stops_is_opaque() {
|
||||||
|
let color_1 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
|
||||||
|
let color_2 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
|
||||||
|
let gradient = GradientStops::new(vec![
|
||||||
|
GradientStop {
|
||||||
|
position: 0.,
|
||||||
|
midpoint: 0.5,
|
||||||
|
color: color_1,
|
||||||
|
},
|
||||||
|
GradientStop {
|
||||||
|
position: 1.,
|
||||||
|
midpoint: 0.5,
|
||||||
|
color: color_2,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
let g = gradient_graphic(gradient);
|
||||||
|
assert!(g.is_opaque());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gradient_with_transparent_stop_is_not_opaque() {
|
||||||
|
let color_1 = Color::from_rgbaf32(1., 0., 0., 0.5).unwrap();
|
||||||
|
let color_2 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
|
||||||
|
let gradient = GradientStops::new(vec![
|
||||||
|
GradientStop {
|
||||||
|
position: 0.,
|
||||||
|
midpoint: 0.5,
|
||||||
|
color: color_1,
|
||||||
|
},
|
||||||
|
GradientStop {
|
||||||
|
position: 1.,
|
||||||
|
midpoint: 0.5,
|
||||||
|
color: color_2,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
let g = gradient_graphic(gradient);
|
||||||
|
assert!(!g.is_opaque());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test_support {
|
||||||
|
use super::Graphic;
|
||||||
|
use core_types::list::List;
|
||||||
|
use core_types::record::{RunBuilder, element_write_hashed};
|
||||||
|
use glam::DVec2;
|
||||||
|
use vector_types::Vector;
|
||||||
|
use vector_types::subpath::Subpath;
|
||||||
|
use vector_types::vector::PointId;
|
||||||
|
|
||||||
|
pub(in crate::graphic) fn unit_square_at(corner: DVec2) -> Vector {
|
||||||
|
Vector::from_subpath(Subpath::<PointId>::new_rectangle(corner, corner + DVec2::ONE))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(in crate::graphic) fn native_group_paint<'a>(vector: &Vector, arena: &'a core_types::arena::Arena) -> List<Graphic<'a>> {
|
||||||
|
let mut builder = RunBuilder::new(arena, element_write_hashed::<Vector>(), &[], 1).unwrap();
|
||||||
|
builder.push(vector.clone()).unwrap();
|
||||||
|
List::new_from_element(Graphic::Group(core_types::record::Group { row: None, content: builder.finish() }))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,272 @@
|
|||||||
|
//! The paint column level: fill and stroke read as lane columns and threaded down to the elements they reach.
|
||||||
|
|
||||||
|
use super::{Graphic, IntoGraphicList};
|
||||||
|
use crate::markers::{ATTR_FILL, ATTR_STROKE, Fill, Stroke};
|
||||||
|
use core_types::ATTR_TRANSFORM;
|
||||||
|
use core_types::attribute::{Attribute, Opacity};
|
||||||
|
use core_types::lane::{LaneColumn, LaneSource};
|
||||||
|
use core_types::list::{ItemAttributeValues, List};
|
||||||
|
use glam::DAffine2;
|
||||||
|
use vector_types::Vector;
|
||||||
|
|
||||||
|
/// Whether a normalized paint graphic list actually carries renderable paint.
|
||||||
|
/// A 0-item list, or a list whose first graphic is empty, is treated as no paint.
|
||||||
|
pub fn is_paint_present(graphic_list: &List<Graphic>) -> bool {
|
||||||
|
graphic_list.element(0).is_some_and(|graphic| !graphic.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Look up the paint graphics stored under the marker `A`, in the canonical `List<Graphic>` form.
|
||||||
|
pub fn paint_graphics<'a, A, S>(source: &'a S, index: usize) -> Option<&'a List<Graphic<'static>>>
|
||||||
|
where
|
||||||
|
S: LaneSource,
|
||||||
|
A: Attribute<Value<'a> = Option<&'a List<Graphic<'static>>>>,
|
||||||
|
{
|
||||||
|
source
|
||||||
|
.attr::<A>(index)
|
||||||
|
// Treat a blank paint attribute as absent so an empty attribute doesn't count as painted
|
||||||
|
.filter(|graphic_list| is_paint_present(graphic_list))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the item carries a non-blank canonical `List<Graphic>` paint under the marker `A`,
|
||||||
|
/// checked by borrowing without cloning the renderable list.
|
||||||
|
pub fn has_paint<'a, A, S>(source: &'a S, index: usize) -> bool
|
||||||
|
where
|
||||||
|
S: LaneSource,
|
||||||
|
A: Attribute<Value<'a> = Option<&'a List<Graphic<'static>>>>,
|
||||||
|
{
|
||||||
|
paint_graphics::<A, S>(source, index).is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether every lane of a vector source draws as a plain clip path: fully
|
||||||
|
/// opaque, fill absent or opaque, stroke invisible or fully transparent.
|
||||||
|
pub fn vector_can_reduce_to_clip_path<S: LaneSource<Element = Vector>>(source: &S) -> bool {
|
||||||
|
(0..source.lane_count()).all(|index| {
|
||||||
|
let Some(element) = source.element(index) else { return false };
|
||||||
|
let opacity: f64 = source.attr::<Opacity>(index);
|
||||||
|
|
||||||
|
let fill_opaque_or_absent = paint_graphics::<Fill, _>(source, index).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_opaque()));
|
||||||
|
|
||||||
|
let stroke_invisible_or_transparent = element.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke())
|
||||||
|
|| paint_graphics::<Stroke, _>(source, index).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_fully_transparent()));
|
||||||
|
|
||||||
|
opacity > 1. - f64::EPSILON && fill_opaque_or_absent && stroke_invisible_or_transparent
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The paint a lane carries for its interiors, in the reference form
|
||||||
|
/// [`PaintOverlay`] threads down.
|
||||||
|
#[derive(Clone, Copy, Default)]
|
||||||
|
pub struct LanePaint<'a> {
|
||||||
|
pub fill: Option<&'a List<Graphic<'static>>>,
|
||||||
|
pub stroke: Option<&'a List<Graphic<'static>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> LanePaint<'a> {
|
||||||
|
pub const NONE: Self = Self { fill: None, stroke: None };
|
||||||
|
|
||||||
|
pub fn is_present(&self) -> bool {
|
||||||
|
self.fill.is_some() || self.stroke.is_some()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A source's fill and stroke columns, resolved once for per-lane reads.
|
||||||
|
pub struct PaintColumns<'a, S: LaneSource + 'a> {
|
||||||
|
fill: S::Column<'a, Fill>,
|
||||||
|
stroke: S::Column<'a, Stroke>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, S: LaneSource> PaintColumns<'a, S> {
|
||||||
|
pub fn new(source: &'a S) -> Self {
|
||||||
|
Self {
|
||||||
|
fill: source.column::<Fill>(),
|
||||||
|
stroke: source.column::<Stroke>(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The lane's present, non-blank paint.
|
||||||
|
pub fn read(&self, lane: usize) -> LanePaint<'a> {
|
||||||
|
let present = |value: Option<Option<&'a List<Graphic<'static>>>>| value.flatten().filter(|list| is_paint_present(list));
|
||||||
|
LanePaint {
|
||||||
|
fill: present(self.fill.try_get(lane)),
|
||||||
|
stroke: present(self.stroke.try_get(lane)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How far a lane's paint reaches into the element beneath it, mirroring the
|
||||||
|
/// legacy conversion's paint push: vector interiors directly and vector
|
||||||
|
/// children of a nested graphic list, one level deep.
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub struct PaintReach<'a> {
|
||||||
|
pub paint: LanePaint<'a>,
|
||||||
|
hops: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> PaintReach<'a> {
|
||||||
|
pub const NONE: Self = Self { paint: LanePaint::NONE, hops: 0 };
|
||||||
|
|
||||||
|
/// The lane's effective reach: an inherited paint stays authoritative
|
||||||
|
/// (lane paint below a push's origin is inert in the legacy model), an
|
||||||
|
/// absent one reads the lane's own paint.
|
||||||
|
pub fn for_lane<S: LaneSource>(self, columns: &PaintColumns<'a, S>, index: usize) -> Self {
|
||||||
|
match self.paint.is_present() {
|
||||||
|
true => self,
|
||||||
|
false => Self { paint: columns.read(index), hops: 2 },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn applies(&self) -> bool {
|
||||||
|
self.hops > 0 && self.paint.is_present()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The reach one graphic nesting level further down.
|
||||||
|
pub fn nested(self) -> Self {
|
||||||
|
Self {
|
||||||
|
paint: self.paint,
|
||||||
|
hops: self.hops.saturating_sub(1),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The reach entering a group's own graphic run: a spent or absent reach
|
||||||
|
/// resets so the group's own lane paint applies at its own boundary.
|
||||||
|
pub fn into_group_graphics(self) -> Self {
|
||||||
|
match self.applies() {
|
||||||
|
true => self.nested(),
|
||||||
|
false => Self::NONE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A source with a lane's paint forced over its fill and stroke columns,
|
||||||
|
/// reaching the interiors the legacy conversion's paint push reached.
|
||||||
|
pub struct PaintOverlay<'a, S> {
|
||||||
|
inner: &'a S,
|
||||||
|
paint: LanePaint<'a>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, S> PaintOverlay<'a, S> {
|
||||||
|
pub fn new(inner: &'a S, paint: LanePaint<'a>) -> Self {
|
||||||
|
Self { inner, paint }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct PaintOverlayColumn<'a, S: LaneSource + 'a, A: Attribute> {
|
||||||
|
inner: S::Column<'a, A>,
|
||||||
|
forced: Option<A::Value<'a>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, S: LaneSource, A: Attribute> LaneColumn<'a, A> for PaintOverlayColumn<'a, S, A> {
|
||||||
|
fn try_get(&self, lane: usize) -> Option<A::Value<'a>> {
|
||||||
|
match self.forced {
|
||||||
|
Some(forced) => Some(forced),
|
||||||
|
None => self.inner.try_get(lane),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The forced value for the marker `A`: the lane paint where `A` is this
|
||||||
|
/// crate's fill or stroke marker, absent otherwise.
|
||||||
|
fn forced_paint<'a, A: Attribute>(paint: LanePaint<'a>) -> Option<A::Value<'a>> {
|
||||||
|
let slot = match A::NAME {
|
||||||
|
name if name == Fill::NAME => paint.fill,
|
||||||
|
name if name == Stroke::NAME => paint.stroke,
|
||||||
|
_ => None,
|
||||||
|
}?;
|
||||||
|
assert_eq!(
|
||||||
|
std::any::TypeId::of::<A::Value<'static>>(),
|
||||||
|
std::any::TypeId::of::<Option<&'static List<Graphic<'static>>>>(),
|
||||||
|
"attribute `{}` is declared at another value type than this crate's paint form",
|
||||||
|
A::NAME
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
size_of::<A::Value<'a>>(),
|
||||||
|
size_of::<Option<&'a List<Graphic<'a>>>>(),
|
||||||
|
"the paint value form must span the marker's value"
|
||||||
|
);
|
||||||
|
// SAFETY: the census admits one value type per attribute name, so a `fill` or `stroke` marker carries this crate's `Option<&List<Graphic>>` at the asserted size.
|
||||||
|
Some(unsafe { std::mem::transmute_copy::<Option<&'a List<Graphic>>, A::Value<'a>>(&Some(slot)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, S: LaneSource> LaneSource for PaintOverlay<'a, S> {
|
||||||
|
type Element = S::Element;
|
||||||
|
type Column<'b, A: Attribute>
|
||||||
|
= PaintOverlayColumn<'b, S, A>
|
||||||
|
where
|
||||||
|
Self: 'b;
|
||||||
|
|
||||||
|
fn lane_count(&self) -> usize {
|
||||||
|
self.inner.lane_count()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn element(&self, lane: usize) -> Option<&S::Element> {
|
||||||
|
self.inner.element(lane)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn column<A: Attribute>(&self) -> PaintOverlayColumn<'_, S, A> {
|
||||||
|
PaintOverlayColumn {
|
||||||
|
inner: self.inner.column::<A>(),
|
||||||
|
forced: forced_paint::<A>(self.paint),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stores a paint attribute in the paint marker's owned form, the only representation paint readers accept.
|
||||||
|
pub fn set_paint_attribute(attributes: &mut ItemAttributeValues, key: &str, paint: impl IntoGraphicList) {
|
||||||
|
attributes.insert(key, Some(paint.into_graphic_list()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stores a paint attribute at a list index in the paint marker's owned form, the only representation paint readers accept.
|
||||||
|
pub fn set_paint_attribute_at<T>(list: &mut List<T>, index: usize, key: &str, paint: impl IntoGraphicList) {
|
||||||
|
list.set_attribute(key, index, Some(paint.into_graphic_list()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bake the provided transform into the per-item transforms of the paint graphics stored under the
|
||||||
|
/// canonical `List<Graphic>` fill and stroke attributes.
|
||||||
|
pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DAffine2) {
|
||||||
|
fn bake_graphic_paint_transform(graphics: &mut List<Graphic>, transform: DAffine2) {
|
||||||
|
for item_transform in graphics.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||||
|
*item_transform = transform * *item_transform;
|
||||||
|
}
|
||||||
|
for graphic in graphics.iter_element_values_mut() {
|
||||||
|
if let Graphic::Graphic(list) = graphic {
|
||||||
|
bake_graphic_paint_transform(list, transform);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for paint_key in [ATTR_FILL, ATTR_STROKE] {
|
||||||
|
if let Some(Some(graphics)) = attributes.get_mut::<Option<List<Graphic>>>(paint_key) {
|
||||||
|
bake_graphic_paint_transform(graphics, transform);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod run_tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::graphic::run_to_legacy_list;
|
||||||
|
use crate::graphic::test_support::unit_square_at;
|
||||||
|
use core_types::Color;
|
||||||
|
use core_types::record::{FieldWrite, RunBuilder, RunView, element_write_hashed};
|
||||||
|
use glam::DVec2;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_run_serves_the_parked_paint_reference() {
|
||||||
|
let paint = List::new_from_element(Graphic::Color(Color::BLACK));
|
||||||
|
let vector = unit_square_at(DVec2::ZERO);
|
||||||
|
|
||||||
|
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||||
|
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||||
|
let lane = builder.push(vector.clone()).unwrap();
|
||||||
|
builder.attr::<Fill>(lane, Some(&paint));
|
||||||
|
let item = builder.finish();
|
||||||
|
let run = RunView::<Vector>::new(&item).expect("the run holds vector elements");
|
||||||
|
|
||||||
|
assert_eq!(run.attr::<Fill>(0), Some(&paint));
|
||||||
|
assert_eq!(paint_graphics::<Fill, _>(&run, 0), Some(&paint));
|
||||||
|
assert_eq!(paint_graphics::<Stroke, _>(&run, 0), None);
|
||||||
|
|
||||||
|
let legacy = run_to_legacy_list::<Vector>(&item).expect("the run lowers to a legacy vector list");
|
||||||
|
assert_eq!(paint_graphics::<Fill, _>(&legacy, 0), paint_graphics::<Fill, _>(&run, 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,572 @@
|
|||||||
|
//! The native-content walk: vector rows reached through a graphic's own storage, with no legacy conversion.
|
||||||
|
|
||||||
|
use super::Graphic;
|
||||||
|
use super::paint::{LanePaint, PaintColumns, PaintReach, is_paint_present, paint_graphics, set_paint_attribute_at};
|
||||||
|
use crate::markers::{ATTR_FILL, ATTR_STROKE, Fill};
|
||||||
|
use core_types::attribute::{Attribute, ClippingMask, EditorLayerPath, Opacity, OpacityFill, Transform};
|
||||||
|
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||||
|
use core_types::lane::LaneSource;
|
||||||
|
use core_types::list::{AttributeValueDyn, Item, ItemAttributeValues, List};
|
||||||
|
use core_types::record::FieldOffset;
|
||||||
|
use core_types::render_complexity::RenderComplexity;
|
||||||
|
use core_types::uuid::NodeId;
|
||||||
|
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||||
|
use glam::{DAffine2, DVec2};
|
||||||
|
use raster_types::{CPU, GPU, Raster};
|
||||||
|
use vector_types::{GradientStops, Vector};
|
||||||
|
|
||||||
|
/// One run's attribute tokens, minted once so the lane loops read at an offset.
|
||||||
|
struct RunAttrs {
|
||||||
|
transform: Option<FieldOffset<Transform>>,
|
||||||
|
opacity: Option<FieldOffset<Opacity>>,
|
||||||
|
opacity_fill: Option<FieldOffset<OpacityFill>>,
|
||||||
|
clipping_mask: Option<FieldOffset<ClippingMask>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RunAttrs {
|
||||||
|
fn of(item: &core_types::record::GroupItem) -> Self {
|
||||||
|
let layout = item.layout();
|
||||||
|
Self {
|
||||||
|
transform: FieldOffset::of(layout, 0),
|
||||||
|
opacity: FieldOffset::of(layout, 0),
|
||||||
|
opacity_fill: FieldOffset::of(layout, 0),
|
||||||
|
clipping_mask: FieldOffset::of(layout, 0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_or<'i, A: Attribute>(item: &'i core_types::record::GroupItem, field: Option<FieldOffset<A>>, lane: usize, default: A::Value<'i>) -> A::Value<'i> {
|
||||||
|
match field.and_then(|field| item.lanes().get(lane).try_attr_at(field)) {
|
||||||
|
Some(value) => value,
|
||||||
|
None => default,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn group_is_empty(group: &core_types::record::Group) -> bool {
|
||||||
|
group.content.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(in crate::graphic) fn group_all_clipped(group: &core_types::record::Group) -> bool {
|
||||||
|
let item = &group.content;
|
||||||
|
let attrs = RunAttrs::of(item);
|
||||||
|
(0..item.len()).all(|lane| RunAttrs::read_or(item, attrs.clipping_mask, lane, false))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(in crate::graphic) fn group_is_opaque(group: &core_types::record::Group) -> bool {
|
||||||
|
let item = &group.content;
|
||||||
|
let attrs = RunAttrs::of(item);
|
||||||
|
let lanes = item.typed_lanes::<Graphic>();
|
||||||
|
!item.is_empty()
|
||||||
|
&& (0..item.len()).all(|lane| {
|
||||||
|
RunAttrs::read_or(item, attrs.opacity, lane, 1.) >= 1.
|
||||||
|
&& RunAttrs::read_or(item, attrs.opacity_fill, lane, 1.) >= 1.
|
||||||
|
&& lanes.as_ref().is_some_and(|lanes| lanes.element_ref(lane).is_opaque())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(in crate::graphic) fn group_is_fully_transparent(group: &core_types::record::Group) -> bool {
|
||||||
|
let item = &group.content;
|
||||||
|
let attrs = RunAttrs::of(item);
|
||||||
|
let lanes = item.typed_lanes::<Graphic>();
|
||||||
|
(0..item.len()).all(|lane| RunAttrs::read_or(item, attrs.opacity, lane, 1.) <= 0. || lanes.as_ref().is_some_and(|lanes| lanes.element_ref(lane).is_fully_transparent()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(in crate::graphic) fn group_bounding_box(group: &core_types::record::Group, transform: DAffine2, include_stroke: bool, thumbnail: bool) -> RenderBoundingBox {
|
||||||
|
fn combine(combined: &mut Option<[DVec2; 2]>, any_infinite: &mut bool, bounds: RenderBoundingBox, thumbnail: bool) -> Option<RenderBoundingBox> {
|
||||||
|
match bounds {
|
||||||
|
RenderBoundingBox::None => None,
|
||||||
|
RenderBoundingBox::Infinite if thumbnail => {
|
||||||
|
*any_infinite = true;
|
||||||
|
None
|
||||||
|
}
|
||||||
|
RenderBoundingBox::Infinite => Some(RenderBoundingBox::Infinite),
|
||||||
|
RenderBoundingBox::Rectangle(bounds) => {
|
||||||
|
*combined = Some(match *combined {
|
||||||
|
Some(existing) => core_types::math::quad::Quad::combine_bounds(existing, bounds),
|
||||||
|
None => bounds,
|
||||||
|
});
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn typed_run<T: dyn_any::StaticTypeSized + BoundingBox>(item: &core_types::record::GroupItem, transform: DAffine2, include_stroke: bool, thumbnail: bool) -> Option<RenderBoundingBox> {
|
||||||
|
let lanes = item.typed_lanes::<T>()?;
|
||||||
|
let transform_offset = RunAttrs::of(item).transform;
|
||||||
|
let mut combined = None;
|
||||||
|
let mut any_infinite = false;
|
||||||
|
for lane in 0..lanes.len() {
|
||||||
|
let lane_transform = transform * RunAttrs::read_or(item, transform_offset, lane, DAffine2::IDENTITY);
|
||||||
|
let element = lanes.element_ref(lane);
|
||||||
|
let bounds = match thumbnail {
|
||||||
|
true => element.thumbnail_bounding_box(lane_transform, include_stroke),
|
||||||
|
false => element.bounding_box(lane_transform, include_stroke),
|
||||||
|
};
|
||||||
|
if let Some(short_circuit) = combine(&mut combined, &mut any_infinite, bounds, thumbnail) {
|
||||||
|
return Some(short_circuit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(match (combined, any_infinite) {
|
||||||
|
(Some(bounds), _) => RenderBoundingBox::Rectangle(bounds),
|
||||||
|
(None, true) => RenderBoundingBox::Infinite,
|
||||||
|
(None, false) => RenderBoundingBox::None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn run_bounding_box(item: &core_types::record::GroupItem, transform: DAffine2, include_stroke: bool, thumbnail: bool) -> RenderBoundingBox {
|
||||||
|
None.or_else(|| typed_run::<Graphic>(item, transform, include_stroke, thumbnail))
|
||||||
|
.or_else(|| typed_run::<Vector>(item, transform, include_stroke, thumbnail))
|
||||||
|
.or_else(|| typed_run::<Raster<CPU>>(item, transform, include_stroke, thumbnail))
|
||||||
|
.or_else(|| typed_run::<Raster<GPU>>(item, transform, include_stroke, thumbnail))
|
||||||
|
.or_else(|| typed_run::<Color>(item, transform, include_stroke, thumbnail))
|
||||||
|
.or_else(|| typed_run::<GradientStops>(item, transform, include_stroke, thumbnail))
|
||||||
|
.or_else(|| typed_run::<String>(item, transform, include_stroke, thumbnail))
|
||||||
|
.unwrap_or(RenderBoundingBox::Infinite)
|
||||||
|
}
|
||||||
|
run_bounding_box(&group.content, transform, include_stroke, thumbnail)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One step of the vector-row walk: continue to the next row or stop early.
|
||||||
|
pub enum RowStep {
|
||||||
|
Continue,
|
||||||
|
Stop,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ancestor composition a flattened row inherits: transform, opacity and
|
||||||
|
/// fill opacity multiply down, each composing only where some ancestor
|
||||||
|
/// carries the attribute, matching the legacy flatten.
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
struct FlattenScale {
|
||||||
|
has_transform: bool,
|
||||||
|
transform: DAffine2,
|
||||||
|
has_opacity: bool,
|
||||||
|
opacity: f64,
|
||||||
|
has_fill_opacity: bool,
|
||||||
|
fill_opacity: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FlattenScale {
|
||||||
|
const ROOT: Self = Self {
|
||||||
|
has_transform: false,
|
||||||
|
transform: DAffine2::IDENTITY,
|
||||||
|
has_opacity: false,
|
||||||
|
opacity: 1.,
|
||||||
|
has_fill_opacity: false,
|
||||||
|
fill_opacity: 1.,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn composed<S: LaneSource>(self, source: &S, lane: usize) -> Self {
|
||||||
|
let transform = source.try_attr::<Transform>(lane);
|
||||||
|
let opacity = source.try_attr::<Opacity>(lane);
|
||||||
|
let fill_opacity = source.try_attr::<OpacityFill>(lane);
|
||||||
|
Self {
|
||||||
|
has_transform: self.has_transform || transform.is_some(),
|
||||||
|
transform: self.transform * transform.unwrap_or(DAffine2::IDENTITY),
|
||||||
|
has_opacity: self.has_opacity || opacity.is_some(),
|
||||||
|
opacity: self.opacity * opacity.unwrap_or(1.),
|
||||||
|
has_fill_opacity: self.has_fill_opacity || fill_opacity.is_some(),
|
||||||
|
fill_opacity: self.fill_opacity * fill_opacity.unwrap_or(1.),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A graphic level in either of its two storages, as one lane source.
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub enum GraphicLevel<'a> {
|
||||||
|
Legacy(&'a List<Graphic<'a>>),
|
||||||
|
Run(&'a core_types::record::GroupItem<'a>),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum GraphicLevelColumn<'a, A: Attribute> {
|
||||||
|
Legacy(core_types::list::ListColumn<'a, A>),
|
||||||
|
Run(core_types::record::RunColumn<'a, A>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, A: Attribute> core_types::lane::LaneColumn<'a, A> for GraphicLevelColumn<'a, A> {
|
||||||
|
fn try_get(&self, lane: usize) -> Option<A::Value<'a>> {
|
||||||
|
match self {
|
||||||
|
GraphicLevelColumn::Legacy(column) => column.try_get(lane),
|
||||||
|
GraphicLevelColumn::Run(column) => column.try_get(lane),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> LaneSource for GraphicLevel<'a> {
|
||||||
|
type Element = Graphic<'a>;
|
||||||
|
type Column<'b, A: Attribute>
|
||||||
|
= GraphicLevelColumn<'b, A>
|
||||||
|
where
|
||||||
|
Self: 'b;
|
||||||
|
|
||||||
|
fn lane_count(&self) -> usize {
|
||||||
|
match self {
|
||||||
|
GraphicLevel::Legacy(list) => list.len(),
|
||||||
|
GraphicLevel::Run(item) => item.len(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn element(&self, lane: usize) -> Option<&Graphic<'a>> {
|
||||||
|
match self {
|
||||||
|
GraphicLevel::Legacy(list) => list.element(lane),
|
||||||
|
GraphicLevel::Run(item) => {
|
||||||
|
let lanes = item.typed_lanes::<Graphic>()?;
|
||||||
|
if lane >= lanes.len() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
// SAFETY: the layout records the element type, and a parked
|
||||||
|
// element stores its reference at offset 0.
|
||||||
|
Some(unsafe { core_types::record::borrow_element::<Graphic>(item.lanes().get(lane).rec()) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn column<A: Attribute>(&self) -> GraphicLevelColumn<'_, A> {
|
||||||
|
match self {
|
||||||
|
GraphicLevel::Legacy(list) => GraphicLevelColumn::Legacy(list.column::<A>()),
|
||||||
|
GraphicLevel::Run(item) => GraphicLevelColumn::Run(core_types::record::RunColumn::of(item)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The lane's attributes as an owned set, read through the erased glue.
|
||||||
|
pub fn run_lane_attributes(item: &core_types::record::GroupItem, lane: usize) -> ItemAttributeValues {
|
||||||
|
let mut scratch: List<Vector> = List::new_from_element(Vector::default());
|
||||||
|
for field in &item.layout().fields {
|
||||||
|
// SAFETY: the offset comes from the item's own layout.
|
||||||
|
let value = unsafe { (field.read_erased)(item.lanes().get(lane).rec().ptr().add(field.offset)) };
|
||||||
|
scratch.set_attribute_value_dyn(field.name, 0, AttributeValueDyn(value));
|
||||||
|
}
|
||||||
|
scratch.clone_item_attributes(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The lane's attributes as an owned set, from either level storage.
|
||||||
|
pub fn lane_attributes(level: GraphicLevel<'_>, lane: usize) -> ItemAttributeValues {
|
||||||
|
match level {
|
||||||
|
GraphicLevel::Legacy(list) => list.clone_item_attributes(lane),
|
||||||
|
GraphicLevel::Run(item) => run_lane_attributes(item, lane),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One flattened vector row served by [`walk_vector_rows`]: cheap probes
|
||||||
|
/// first, the full row built on demand.
|
||||||
|
pub struct VectorRow<'w> {
|
||||||
|
source: RowSourceRef<'w>,
|
||||||
|
scale: FlattenScale,
|
||||||
|
layer_path: Option<&'w [NodeId]>,
|
||||||
|
paint: LanePaint<'w>,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum RowSourceRef<'w> {
|
||||||
|
/// A de-tabled vector leaf on a graphic lane: the lane is the row.
|
||||||
|
Lane(GraphicLevel<'w>, usize),
|
||||||
|
/// A lane of a vector run.
|
||||||
|
Run(&'w core_types::record::RunView<'w, Vector>, &'w core_types::record::GroupItem<'w>, usize),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VectorRow<'_> {
|
||||||
|
/// The row's vector, borrowed.
|
||||||
|
pub fn element(&self) -> &Vector {
|
||||||
|
match &self.source {
|
||||||
|
RowSourceRef::Lane(level, index) => level.element(*index).and_then(Graphic::as_vector).expect("the walk visits vector lanes"),
|
||||||
|
RowSourceRef::Run(run, _, index) => LaneSource::element(*run, *index).expect("the walk visits held lanes"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the built row will carry fill paint: the reaching lane paint,
|
||||||
|
/// else the row's own.
|
||||||
|
pub fn has_fill(&self) -> bool {
|
||||||
|
if self.paint.fill.is_some() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
match &self.source {
|
||||||
|
RowSourceRef::Lane(level, index) => paint_graphics::<Fill, _>(level, *index).is_some(),
|
||||||
|
RowSourceRef::Run(run, _, index) => paint_graphics::<Fill, _>(*run, *index).is_some(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the row at the end of `out`, applying the reach paint and the
|
||||||
|
/// inherited composition.
|
||||||
|
pub fn build_into(&self, out: &mut List<Vector>) {
|
||||||
|
let index = out.len();
|
||||||
|
match &self.source {
|
||||||
|
RowSourceRef::Lane(level, lane) => {
|
||||||
|
let vector = self.element().clone();
|
||||||
|
out.push(Item::from_parts(vector, lane_attributes(*level, *lane)));
|
||||||
|
}
|
||||||
|
RowSourceRef::Run(run, item, lane) => {
|
||||||
|
let vector = LaneSource::element(*run, *lane).expect("the walk visits held lanes").clone();
|
||||||
|
out.push(Item::from_parts(vector, run_lane_attributes(item, *lane)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (key, slot) in [(ATTR_FILL, self.paint.fill), (ATTR_STROKE, self.paint.stroke)] {
|
||||||
|
if let Some(paint) = slot {
|
||||||
|
set_paint_attribute_at(out, index, key, paint.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.scale.has_transform || out.attribute::<DAffine2>(ATTR_TRANSFORM, index).is_some() {
|
||||||
|
let row_transform: DAffine2 = out.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||||
|
out.set_attribute(ATTR_TRANSFORM, index, self.scale.transform * row_transform);
|
||||||
|
}
|
||||||
|
if self.scale.has_opacity || out.attribute::<f64>(ATTR_OPACITY, index).is_some() {
|
||||||
|
let row_opacity: f64 = out.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||||
|
out.set_attribute(ATTR_OPACITY, index, self.scale.opacity * row_opacity);
|
||||||
|
}
|
||||||
|
if self.scale.has_fill_opacity || out.attribute::<f64>(ATTR_OPACITY_FILL, index).is_some() {
|
||||||
|
let row_fill: f64 = out.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||||
|
out.set_attribute(ATTR_OPACITY_FILL, index, self.scale.fill_opacity * row_fill);
|
||||||
|
}
|
||||||
|
if let Some(layer_path) = self.layer_path {
|
||||||
|
out.set_attribute(ATTR_EDITOR_LAYER_PATH, index, layer_path.to_vec());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn walk_rows_of_run(item: &core_types::record::GroupItem, scale: FlattenScale, layer_path: Option<&[NodeId]>, paint: LanePaint<'_>, visit: &mut dyn FnMut(VectorRow<'_>) -> RowStep) -> RowStep {
|
||||||
|
let Some(run) = core_types::record::RunView::<Vector>::new(item) else {
|
||||||
|
return RowStep::Continue;
|
||||||
|
};
|
||||||
|
for lane in 0..item.len() {
|
||||||
|
if let RowStep::Stop = visit(VectorRow {
|
||||||
|
source: RowSourceRef::Run(&run, item, lane),
|
||||||
|
scale,
|
||||||
|
layer_path,
|
||||||
|
paint,
|
||||||
|
}) {
|
||||||
|
return RowStep::Stop;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
RowStep::Continue
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Walks a graphic level into its flattened vector rows, matching the legacy
|
||||||
|
/// push-then-flatten lowering: lane paint threads with [`PaintReach`],
|
||||||
|
/// ancestor transform, opacity and fill opacity compose down, the containing
|
||||||
|
/// level's parent layer path overwrites its rows, and non-vector content is
|
||||||
|
/// discarded. A de-tabled leaf's row is its lane, attributes included.
|
||||||
|
pub fn walk_vector_rows(level: GraphicLevel<'_>, visit: &mut dyn FnMut(VectorRow<'_>) -> RowStep) {
|
||||||
|
walk_vector_rows_impl(level, FlattenScale::ROOT, None, PaintReach::NONE, visit);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn walk_vector_rows_impl<'a>(
|
||||||
|
level: GraphicLevel<'a>,
|
||||||
|
scale: FlattenScale,
|
||||||
|
parent_layer_path: Option<&'a [NodeId]>,
|
||||||
|
inherited: PaintReach<'a>,
|
||||||
|
visit: &mut dyn FnMut(VectorRow<'_>) -> RowStep,
|
||||||
|
) -> RowStep {
|
||||||
|
if let GraphicLevel::Run(item) = level {
|
||||||
|
// A vector-typed run is already its rows.
|
||||||
|
if item.typed_lanes::<Vector>().is_some() {
|
||||||
|
let paint = match inherited.applies() {
|
||||||
|
true => inherited.paint,
|
||||||
|
false => LanePaint::NONE,
|
||||||
|
};
|
||||||
|
return walk_rows_of_run(item, scale, parent_layer_path, paint, visit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let columns = PaintColumns::new(&level);
|
||||||
|
for index in 0..level.lane_count() {
|
||||||
|
let Some(element) = level.element(index) else { continue };
|
||||||
|
let reach = inherited.for_lane(&columns, index);
|
||||||
|
let row_paint = match reach.applies() {
|
||||||
|
true => reach.paint,
|
||||||
|
false => LanePaint::NONE,
|
||||||
|
};
|
||||||
|
let step = match element {
|
||||||
|
Graphic::Vector(_) => visit(VectorRow {
|
||||||
|
source: RowSourceRef::Lane(level, index),
|
||||||
|
scale,
|
||||||
|
layer_path: parent_layer_path,
|
||||||
|
paint: row_paint,
|
||||||
|
}),
|
||||||
|
Graphic::Graphic(children) => walk_vector_rows_impl(
|
||||||
|
GraphicLevel::Legacy(children),
|
||||||
|
scale.composed(&level, index),
|
||||||
|
level.try_attr::<EditorLayerPath>(index),
|
||||||
|
reach.nested(),
|
||||||
|
visit,
|
||||||
|
),
|
||||||
|
Graphic::Group(group) => {
|
||||||
|
let item = &group.content;
|
||||||
|
if item.typed_lanes::<Vector>().is_some() {
|
||||||
|
walk_rows_of_run(item, scale.composed(&level, index), level.try_attr::<EditorLayerPath>(index), row_paint, visit)
|
||||||
|
} else if item.typed_lanes::<Graphic>().is_some() {
|
||||||
|
walk_vector_rows_impl(
|
||||||
|
GraphicLevel::Run(item),
|
||||||
|
scale.composed(&level, index),
|
||||||
|
level.try_attr::<EditorLayerPath>(index),
|
||||||
|
reach.into_group_graphics(),
|
||||||
|
visit,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
RowStep::Continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => RowStep::Continue,
|
||||||
|
};
|
||||||
|
if let RowStep::Stop = step {
|
||||||
|
return RowStep::Stop;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
RowStep::Continue
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The level's flattened vector rows as one owned list, the walk's collect
|
||||||
|
/// form.
|
||||||
|
pub fn flatten_vector_rows(level: GraphicLevel<'_>) -> List<Vector> {
|
||||||
|
let mut out = List::new();
|
||||||
|
walk_vector_rows(level, &mut |row| {
|
||||||
|
row.build_into(&mut out);
|
||||||
|
RowStep::Continue
|
||||||
|
});
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The transitional paint placement: a lane-level fill or stroke paint
|
||||||
|
/// attribute moves onto the vector interiors the legacy paint readers
|
||||||
|
/// inspect, reaching as far as the pre-flip broadcast did.
|
||||||
|
pub(in crate::graphic) fn push_lane_paint_into_interiors(list: &mut List<Graphic>) {
|
||||||
|
for index in 0..list.len() {
|
||||||
|
for key in [ATTR_FILL, ATTR_STROKE] {
|
||||||
|
let stored = list.attribute::<Option<List<Graphic>>>(key, index).and_then(|optional| optional.as_ref());
|
||||||
|
let Some(paint) = stored.filter(|paint| is_paint_present(paint)).cloned() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(Graphic::Graphic(children)) = list.element_mut(index) else { continue };
|
||||||
|
for child in 0..children.len() {
|
||||||
|
if matches!(children.element(child), Some(Graphic::Vector(_))) {
|
||||||
|
set_paint_attribute_at(children, child, key, paint.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The count [`map_groups_to_legacy`] would expose through [`Graphic::as_vector`],
|
||||||
|
/// read from the run's lanes instead of materializing the legacy list. Mirrors
|
||||||
|
/// [`group_to_legacy_graphic`]'s typed-run path, where `Vector` is tried first.
|
||||||
|
pub fn direct_vector_len(graphic: &Graphic) -> usize {
|
||||||
|
match graphic {
|
||||||
|
Graphic::Vector(_) => 1,
|
||||||
|
Graphic::Group(group) => match &group.row {
|
||||||
|
None => group.content.typed_lanes::<Vector>().map_or(0, |lanes| lanes.len()),
|
||||||
|
_ => 0,
|
||||||
|
},
|
||||||
|
_ => 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(in crate::graphic) fn group_render_complexity(group: &core_types::record::Group) -> usize {
|
||||||
|
fn typed_run<T: dyn_any::StaticTypeSized + RenderComplexity>(item: &core_types::record::GroupItem) -> Option<usize> {
|
||||||
|
let lanes = item.typed_lanes::<T>()?;
|
||||||
|
Some((0..lanes.len()).map(|lane| lanes.element_ref(lane).render_complexity()).sum())
|
||||||
|
}
|
||||||
|
let item = &group.content;
|
||||||
|
None.or_else(|| typed_run::<Graphic>(item))
|
||||||
|
.or_else(|| typed_run::<Vector>(item))
|
||||||
|
.or_else(|| typed_run::<Raster<CPU>>(item))
|
||||||
|
.or_else(|| typed_run::<Raster<GPU>>(item))
|
||||||
|
.or_else(|| typed_run::<Color>(item))
|
||||||
|
.or_else(|| typed_run::<GradientStops>(item))
|
||||||
|
.or_else(|| typed_run::<String>(item))
|
||||||
|
.unwrap_or(item.len())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod run_tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::graphic::test_support::unit_square_at;
|
||||||
|
use crate::graphic::{IntoGraphicList, map_groups_to_legacy, run_to_legacy_list};
|
||||||
|
use core_types::record::{FieldWrite, RunBuilder, RunView, element_write_hashed};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_vector_row_walk_matches_the_legacy_flatten() {
|
||||||
|
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||||
|
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||||
|
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[], 1).unwrap();
|
||||||
|
builder.push(inner_vector.clone()).unwrap();
|
||||||
|
let inner_item = builder.finish();
|
||||||
|
|
||||||
|
let mut painted = List::new();
|
||||||
|
painted.push(Item::new_from_element(Graphic::Vector(unit_square_at(DVec2::ZERO))));
|
||||||
|
painted.push(Item::new_from_element(Graphic::Vector(unit_square_at(DVec2::ONE))));
|
||||||
|
painted.set_attribute(core_types::ATTR_TRANSFORM, 0, DAffine2::from_translation(DVec2::new(1., 0.)));
|
||||||
|
painted.set_attribute(core_types::ATTR_TRANSFORM, 1, DAffine2::from_translation(DVec2::new(0., 1.)));
|
||||||
|
set_paint_attribute_at(&mut painted, 1, ATTR_FILL, List::new_from_element(Graphic::Color(Color::WHITE)));
|
||||||
|
|
||||||
|
let mut nested = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(2., 2.))));
|
||||||
|
nested.set_attribute(core_types::ATTR_TRANSFORM, 0, DAffine2::from_scale(DVec2::splat(2.)));
|
||||||
|
|
||||||
|
let mut top = List::new();
|
||||||
|
top.push(Item::new_from_element(Graphic::Graphic(painted)));
|
||||||
|
top.push(Item::new_from_element(Graphic::Graphic(nested)));
|
||||||
|
top.push(Item::new_from_element(Graphic::Group(core_types::record::Group { row: None, content: inner_item })));
|
||||||
|
top.push(Item::new_from_element(Graphic::Color(Color::BLACK)));
|
||||||
|
top.push(Item::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(6., 0.)))));
|
||||||
|
top.set_attribute(core_types::ATTR_TRANSFORM, 0, DAffine2::from_translation(DVec2::new(5., 5.)));
|
||||||
|
top.set_attribute(core_types::ATTR_EDITOR_LAYER_PATH, 0, vec![core_types::uuid::NodeId(7)]);
|
||||||
|
set_paint_attribute_at(&mut top, 0, ATTR_FILL, List::new_from_element(Graphic::Color(Color::BLACK)));
|
||||||
|
top.set_attribute(core_types::ATTR_OPACITY, 1, 0.5);
|
||||||
|
top.set_attribute(core_types::ATTR_TRANSFORM, 2, DAffine2::from_scale(DVec2::splat(3.)));
|
||||||
|
top.set_attribute(core_types::ATTR_TRANSFORM, 4, DAffine2::from_translation(DVec2::new(0., 7.)));
|
||||||
|
top.set_attribute(core_types::ATTR_EDITOR_LAYER_PATH, 4, vec![core_types::uuid::NodeId(9)]);
|
||||||
|
set_paint_attribute_at(&mut top, 4, ATTR_FILL, List::new_from_element(Graphic::Color(Color::WHITE)));
|
||||||
|
|
||||||
|
let legacy = {
|
||||||
|
let mut list = List::new();
|
||||||
|
for item in top.clone().into_iter() {
|
||||||
|
let (element, attributes) = item.into_parts();
|
||||||
|
list.push(Item::from_parts(map_groups_to_legacy(&element), attributes));
|
||||||
|
}
|
||||||
|
push_lane_paint_into_interiors(&mut list);
|
||||||
|
list.into_flattened_list::<Vector>()
|
||||||
|
};
|
||||||
|
let native = flatten_vector_rows(GraphicLevel::Legacy(&top));
|
||||||
|
assert_eq!(native.len(), legacy.len());
|
||||||
|
for row in 0..native.len() {
|
||||||
|
assert_eq!(
|
||||||
|
native.attribute::<DAffine2>(core_types::ATTR_TRANSFORM, row),
|
||||||
|
legacy.attribute::<DAffine2>(core_types::ATTR_TRANSFORM, row),
|
||||||
|
"transform, row {row}"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
native.attribute::<f64>(core_types::ATTR_OPACITY, row),
|
||||||
|
legacy.attribute::<f64>(core_types::ATTR_OPACITY, row),
|
||||||
|
"opacity, row {row}"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
native.attribute::<Vec<core_types::uuid::NodeId>>(core_types::ATTR_EDITOR_LAYER_PATH, row),
|
||||||
|
legacy.attribute::<Vec<core_types::uuid::NodeId>>(core_types::ATTR_EDITOR_LAYER_PATH, row),
|
||||||
|
"layer path, row {row}"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
native.attribute::<Option<List<Graphic>>>(ATTR_FILL, row),
|
||||||
|
legacy.attribute::<Option<List<Graphic>>>(ATTR_FILL, row),
|
||||||
|
"fill, row {row}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(native, legacy);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_run_and_its_legacy_list_agree_on_bounding_boxes() {
|
||||||
|
let vectors = [unit_square_at(DVec2::ZERO), unit_square_at(DVec2::new(4., 4.))];
|
||||||
|
let transforms = [DAffine2::from_translation(DVec2::new(1., 2.)), DAffine2::from_scale(DVec2::splat(3.))];
|
||||||
|
|
||||||
|
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||||
|
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[FieldWrite::of::<core_types::attribute::Transform>(0)], 2).unwrap();
|
||||||
|
for (vector, transform) in vectors.iter().zip(transforms) {
|
||||||
|
let lane = builder.push(vector.clone()).unwrap();
|
||||||
|
builder.attr::<core_types::attribute::Transform>(lane, transform);
|
||||||
|
}
|
||||||
|
let item = builder.finish();
|
||||||
|
let run = RunView::<Vector>::new(&item).expect("the run holds vector elements");
|
||||||
|
let legacy = run_to_legacy_list::<Vector>(&item).expect("the run lowers to a legacy vector list");
|
||||||
|
|
||||||
|
let outer = DAffine2::from_angle(0.3);
|
||||||
|
for include_stroke in [false, true] {
|
||||||
|
let bounds = run.bounding_box(outer, include_stroke);
|
||||||
|
assert_eq!(bounds, legacy.bounding_box(outer, include_stroke));
|
||||||
|
assert!(matches!(bounds, RenderBoundingBox::Rectangle(_)));
|
||||||
|
assert_eq!(run.thumbnail_bounding_box(outer, include_stroke), legacy.thumbnail_bounding_box(outer, include_stroke));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -197,7 +197,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
|||||||
let field_pushed_levels: Vec<u8> = regular_fields
|
let field_pushed_levels: Vec<u8> = regular_fields
|
||||||
.iter()
|
.iter()
|
||||||
.map(|field| match &field.ty {
|
.map(|field| match &field.ty {
|
||||||
ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 0 => *list_levels as u8,
|
ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 0 => *list_levels,
|
||||||
ParsedFieldType::Node(_) => pushed_levels,
|
ParsedFieldType::Node(_) => pushed_levels,
|
||||||
_ => 0,
|
_ => 0,
|
||||||
})
|
})
|
||||||
@@ -728,7 +728,7 @@ pub(crate) struct NodePlan {
|
|||||||
|
|
||||||
/// The field and generic derivation shared by the struct/metadata side and the
|
/// The field and generic derivation shared by the struct/metadata side and the
|
||||||
/// impl side, computed once in [`generate_node_code`] and passed to
|
/// impl side, computed once in [`generate_node_code`] and passed to
|
||||||
/// [`generate_node_impl`]. `regular_fields` is the carrier-skipped slice both
|
/// [`generate_node_impl`]. `regular_fields` is the non-data field slice both
|
||||||
/// sides agree on.
|
/// sides agree on.
|
||||||
pub(crate) struct NodeFields<'a> {
|
pub(crate) struct NodeFields<'a> {
|
||||||
pub(crate) data_fields: Vec<&'a ParsedField>,
|
pub(crate) data_fields: Vec<&'a ParsedField>,
|
||||||
@@ -1399,8 +1399,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// A flip value or a routing non-source value rides a record input; the
|
// A flip value or a routing non-source value rides a record input; the
|
||||||
// element copies out into `name`. The mark/rewind that reclaims the
|
// element copies out into `name`.
|
||||||
// record's frame is applied by the step lowering (see `reads_out`).
|
|
||||||
ValueBinding::RecordElement => {
|
ValueBinding::RecordElement => {
|
||||||
let slot = format_ident!("__in_{index}");
|
let slot = format_ident!("__in_{index}");
|
||||||
quote! {
|
quote! {
|
||||||
@@ -1531,8 +1530,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
|||||||
});
|
});
|
||||||
|
|
||||||
// The extent override is the leveled `extent_at`; consumers query the
|
// The extent override is the leveled `extent_at`; consumers query the
|
||||||
// composite `extent(ctx, Level)`, which the trait derives from it. A node
|
// composite `extent(ctx, Level)`, which the trait derives from it.
|
||||||
// without `extent = fn` keeps the scalar default (one item at every level).
|
|
||||||
// The typed extent surface: the node's inputs in declaration order (values
|
// The typed extent surface: the node's inputs in declaration order (values
|
||||||
// readable without unsafe, inputs as per-level extent queries, derived
|
// readable without unsafe, inputs as per-level extent queries, derived
|
||||||
// content promoted per copy), then the level paired with the node's depth.
|
// content promoted per copy), then the level paired with the node's depth.
|
||||||
@@ -2435,20 +2433,20 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
|||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.filter(|(index, _)| ir::materialized_levels(&node, *index) == 0)
|
.filter(|(index, _)| ir::materialized_levels(&node, *index) == 0)
|
||||||
.filter_map(|(_, field)| match &field.ty {
|
.map(|(_, field)| match &field.ty {
|
||||||
// The conditional arena-park moves a lend element once.
|
// The conditional arena-park moves a lend element once.
|
||||||
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => Some({
|
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => {
|
||||||
let ty = &crate::codegen::classify::substitute_lifetimes(ty, "'static");
|
let ty = &crate::codegen::classify::substitute_lifetimes(ty, "'static");
|
||||||
quote!(#ty: ::core::marker::Send + ::core::marker::Sync + 'static)
|
quote!(#ty: ::core::marker::Send + ::core::marker::Sync + 'static)
|
||||||
}),
|
}
|
||||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => Some({
|
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => {
|
||||||
let ty = &crate::codegen::classify::substitute_lifetimes(ty, "'static");
|
let ty = &crate::codegen::classify::substitute_lifetimes(ty, "'static");
|
||||||
quote!(#ty: ::core::clone::Clone)
|
quote!(#ty: ::core::clone::Clone)
|
||||||
}),
|
}
|
||||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => Some({
|
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => {
|
||||||
let output_type = &crate::codegen::classify::substitute_lifetimes(output_type, "'static");
|
let output_type = &crate::codegen::classify::substitute_lifetimes(output_type, "'static");
|
||||||
quote!(#output_type: ::core::clone::Clone)
|
quote!(#output_type: ::core::clone::Clone)
|
||||||
}),
|
}
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
let out = crate::codegen::classify::substitute_lifetimes(&slot_value_type(&parsed.output_type), "'static");
|
let out = crate::codegen::classify::substitute_lifetimes(&slot_value_type(&parsed.output_type), "'static");
|
||||||
|
|||||||
@@ -120,7 +120,7 @@ pub(crate) fn routing_value_indices(regular_fields: &[&ParsedField], generic: &I
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The lazy inputs declaring attribute reads, with their indices into the
|
/// The lazy inputs declaring attribute reads, with their indices into the
|
||||||
/// unit-skipped regular fields.
|
/// regular fields.
|
||||||
pub(crate) fn lazy_read_fields<'a>(regular_fields: &[&'a ParsedField]) -> Vec<(usize, &'a ParsedField)> {
|
pub(crate) fn lazy_read_fields<'a>(regular_fields: &[&'a ParsedField]) -> Vec<(usize, &'a ParsedField)> {
|
||||||
regular_fields
|
regular_fields
|
||||||
.iter()
|
.iter()
|
||||||
@@ -130,7 +130,7 @@ pub(crate) fn lazy_read_fields<'a>(regular_fields: &[&'a ParsedField]) -> Vec<(u
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The indices (into the unit-skipped regular fields) of value inputs whose
|
/// The indices (into the regular fields) of value inputs whose
|
||||||
/// reads resolve against their own input rather than the carrier's.
|
/// reads resolve against their own input rather than the carrier's.
|
||||||
pub(crate) fn reading_secondary_indices(regular_fields: &[&ParsedField], skips_carrier: bool) -> Vec<usize> {
|
pub(crate) fn reading_secondary_indices(regular_fields: &[&ParsedField], skips_carrier: bool) -> Vec<usize> {
|
||||||
regular_fields
|
regular_fields
|
||||||
@@ -312,7 +312,7 @@ pub(crate) fn record_shape(parsed: &ParsedNodeFn) -> Option<RecordShape> {
|
|||||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => is_served(output_type) || crate::codegen::ir::strip_ilist(output_type).1 > 0 || !field.attribute_reads.is_empty(),
|
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => is_served(output_type) || crate::codegen::ir::strip_ilist(output_type).1 > 0 || !field.attribute_reads.is_empty(),
|
||||||
ParsedFieldType::Regular(_) => false,
|
ParsedFieldType::Regular(_) => false,
|
||||||
};
|
};
|
||||||
if parsed.fields.iter().skip(lazy_carrier as usize).any(|field| unsupported_lazy_secondary(field)) {
|
if parsed.fields.iter().skip(lazy_carrier as usize).any(unsupported_lazy_secondary) {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
let reads_well_placed = parsed.fields.iter().enumerate().all(|(index, field)| {
|
let reads_well_placed = parsed.fields.iter().enumerate().all(|(index, field)| {
|
||||||
@@ -423,10 +423,7 @@ pub(crate) fn flip_carrier(parsed: &ParsedNodeFn) -> bool {
|
|||||||
!(async_kernel && lend.is_some())
|
!(async_kernel && lend.is_some())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether a plain node's lowering flips onto record inputs: sync,
|
/// Whether any value input declares `IList` nesting, so the node materializes a ranked input.
|
||||||
/// fully-concrete value-input nodes in this cut; batch, shader, async, lend,
|
|
||||||
/// lazy, and generic nodes keep the plain lowering until their record forms
|
|
||||||
/// land.
|
|
||||||
pub(crate) fn has_materialized_input(parsed: &ParsedNodeFn) -> bool {
|
pub(crate) fn has_materialized_input(parsed: &ParsedNodeFn) -> bool {
|
||||||
parsed
|
parsed
|
||||||
.fields
|
.fields
|
||||||
@@ -434,6 +431,7 @@ pub(crate) fn has_materialized_input(parsed: &ParsedNodeFn) -> bool {
|
|||||||
.any(|field| matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 0))
|
.any(|field| matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 0))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether a plain node's lowering flips onto record inputs.
|
||||||
pub(crate) fn record_flip(parsed: &ParsedNodeFn) -> bool {
|
pub(crate) fn record_flip(parsed: &ParsedNodeFn) -> bool {
|
||||||
if record_shape(parsed).is_some() || has_record_io(parsed) || routing_io(parsed).is_some() || record_opaque(parsed) {
|
if record_shape(parsed).is_some() || has_record_io(parsed) || routing_io(parsed).is_some() || record_opaque(parsed) {
|
||||||
return false;
|
return false;
|
||||||
@@ -577,7 +575,7 @@ pub(crate) fn routing_io(parsed: &ParsedNodeFn) -> Option<RoutingIo> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
(sources > 0).then(|| RoutingIo { generic: ident })
|
(sources > 0).then_some(RoutingIo { generic: ident })
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn bare_ident(ty: &Type) -> Option<&Ident> {
|
pub(crate) fn bare_ident(ty: &Type) -> Option<&Ident> {
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let alias_params: Vec<&GenericParam> = candidate_params.iter().zip(&kept).filter(|(_, kept)| **kept).map(|(param, _)| *param).collect();
|
let alias_params: Vec<&GenericParam> = candidate_params.iter().zip(&kept).filter(|(_, kept)| **kept).map(|(param, _)| *param).collect();
|
||||||
let alias_param_idents: Vec<Ident> = alias_params.iter().map(|param| param_ident(param)).collect();
|
let alias_param_idents: Vec<Ident> = alias_params.iter().map(param_ident).collect();
|
||||||
let alias_param_tokens: Vec<TokenStream2> = alias_params.iter().map(|param| quote!(#param)).collect();
|
let alias_param_tokens: Vec<TokenStream2> = alias_params.iter().map(|param| quote!(#param)).collect();
|
||||||
let output_alias = format_ident!("__{}_output", fn_name);
|
let output_alias = format_ident!("__{}_output", fn_name);
|
||||||
let alias_def = match alias_param_tokens.is_empty() {
|
let alias_def = match alias_param_tokens.is_empty() {
|
||||||
@@ -130,7 +130,7 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
|||||||
};
|
};
|
||||||
let assignment_types = assignment_types.iter();
|
let assignment_types = assignment_types.iter();
|
||||||
let turbofish = quote!(::<#(#node_underscores,)* #(#assignment_types,)*>);
|
let turbofish = quote!(::<#(#node_underscores,)* #(#assignment_types,)*>);
|
||||||
let input_types = row.iter().map(|ty| quote!(gcore::registry::record_edge_type::<#ty>()));
|
let input_types = row.iter().map(|ty| quote!(gcore::registry::record_source_type::<#ty>()));
|
||||||
let downcasts = names.iter().zip(row.iter()).enumerate().map(|(index, (name, ty))| {
|
let downcasts = names.iter().zip(row.iter()).enumerate().map(|(index, (name, ty))| {
|
||||||
let handle = format_ident!("__handle_{index}");
|
let handle = format_ident!("__handle_{index}");
|
||||||
let layout = format_ident!("__layout_{index}");
|
let layout = format_ident!("__layout_{index}");
|
||||||
@@ -161,7 +161,7 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
|||||||
let mut inputs = inputs.into_iter();
|
let mut inputs = inputs.into_iter();
|
||||||
#(#downcasts)*
|
#(#downcasts)*
|
||||||
let __node = #struct_name #turbofish::new(#(#names,)* #(#layout_args)*);
|
let __node = #struct_name #turbofish::new(#(#names,)* #(#layout_args)*);
|
||||||
Ok(gcore::registry::EdgeHandle::new_record::<#row_output>(::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>))
|
Ok(gcore::registry::SourceHandle::new_record::<#row_output>(::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>))
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -339,8 +339,8 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
|||||||
}
|
}
|
||||||
|
|
||||||
let input_types = slots.iter().map(|slot| match slot {
|
let input_types = slots.iter().map(|slot| match slot {
|
||||||
SlotKind::BaseGeneric(name) => quote!(gcore::registry::generic_record_edge_type(#name)),
|
SlotKind::BaseGeneric(name) => quote!(gcore::registry::generic_record_source_type(#name)),
|
||||||
SlotKind::BaseConcrete(ty) | SlotKind::Value(ty) | SlotKind::Extracted(ty) | SlotKind::Ranked(ty) => quote!(gcore::registry::record_edge_type::<#ty>()),
|
SlotKind::BaseConcrete(ty) | SlotKind::Value(ty) | SlotKind::Extracted(ty) | SlotKind::Ranked(ty) => quote!(gcore::registry::record_source_type::<#ty>()),
|
||||||
});
|
});
|
||||||
|
|
||||||
let downcasts = names.iter().zip(&slots).enumerate().map(|(index, (name, slot))| {
|
let downcasts = names.iter().zip(&slots).enumerate().map(|(index, (name, slot))| {
|
||||||
@@ -394,7 +394,7 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
|||||||
let (io_output, wrap) = match &output_element {
|
let (io_output, wrap) = match &output_element {
|
||||||
Some(element) => (
|
Some(element) => (
|
||||||
quote!(gcore::registry::record_type::<#element>()),
|
quote!(gcore::registry::record_type::<#element>()),
|
||||||
quote!(Ok(gcore::registry::EdgeHandle::new_record::<#element>(::std::sync::Arc::new(__node)))),
|
quote!(Ok(gcore::registry::SourceHandle::new_record::<#element>(::std::sync::Arc::new(__node)))),
|
||||||
),
|
),
|
||||||
None => {
|
None => {
|
||||||
let name = match &node.output.shape.element {
|
let name = match &node.output.shape.element {
|
||||||
@@ -404,7 +404,7 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
|||||||
let base_ty = format_ident!("__ty_{}", base_indices[0]);
|
let base_ty = format_ident!("__ty_{}", base_indices[0]);
|
||||||
(
|
(
|
||||||
quote!(gcore::Type::Record(Box::new(gcore::Type::Generic(::std::borrow::Cow::Borrowed(#name))))),
|
quote!(gcore::Type::Record(Box::new(gcore::Type::Generic(::std::borrow::Cow::Borrowed(#name))))),
|
||||||
quote!(Ok(gcore::registry::EdgeHandle::new_erased(::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>, #base_ty))),
|
quote!(Ok(gcore::registry::SourceHandle::new_erased(::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>, #base_ty))),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ fn generics(parsed: &ParsedNodeFn) -> Vec<Generic> {
|
|||||||
|
|
||||||
fn inputs(parsed: &ParsedNodeFn, fields: &[&ParsedField], generics: &[Ident]) -> Vec<Input> {
|
fn inputs(parsed: &ParsedNodeFn, fields: &[&ParsedField], generics: &[Ident]) -> Vec<Input> {
|
||||||
let routing = routing_io(parsed);
|
let routing = routing_io(parsed);
|
||||||
let carrier_subject = flip_carrier(parsed) || record_shape(parsed).map_or(false, |shape| !shape.skips_carrier());
|
let carrier_subject = flip_carrier(parsed) || record_shape(parsed).is_some_and(|shape| !shape.skips_carrier());
|
||||||
fields
|
fields
|
||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
@@ -263,13 +263,16 @@ fn ilist_inner(ty: &Type) -> Option<Type> {
|
|||||||
/// caller since it is the one row-dependent facet; the rest folds from the node.
|
/// caller since it is the one row-dependent facet; the rest folds from the node.
|
||||||
pub(crate) fn layout_meta_tokens(node: &Node, element_spec: TokenStream2, core_types: &TokenStream2) -> TokenStream2 {
|
pub(crate) fn layout_meta_tokens(node: &Node, element_spec: TokenStream2, core_types: &TokenStream2) -> TokenStream2 {
|
||||||
let sources = layout_sources(node).into_iter().map(|index| index as u8);
|
let sources = layout_sources(node).into_iter().map(|index| index as u8);
|
||||||
let reads = node.inputs.iter().enumerate().filter_map(|(index, input)| {
|
let reads = node
|
||||||
(matches!(input.evaluation, Evaluation::Eager) && !input.shape.attrs.is_empty()).then(|| {
|
.inputs
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(_, input)| matches!(input.evaluation, Evaluation::Eager) && !input.shape.attrs.is_empty())
|
||||||
|
.map(|(index, input)| {
|
||||||
let descs = field_writes(&input.shape.attrs, core_types);
|
let descs = field_writes(&input.shape.attrs, core_types);
|
||||||
let index = index as u8;
|
let index = index as u8;
|
||||||
quote!(#core_types::record::InputReads { input: #index, reads: ::std::vec![#(#descs),*] })
|
quote!(#core_types::record::InputReads { input: #index, reads: ::std::vec![#(#descs),*] })
|
||||||
})
|
});
|
||||||
});
|
|
||||||
let writes = field_writes(&node.output.shape.attrs, core_types);
|
let writes = field_writes(&node.output.shape.attrs, core_types);
|
||||||
let removes = node.output.removes.iter().map(|attr| {
|
let removes = node.output.removes.iter().map(|attr| {
|
||||||
let marker = &attr.marker;
|
let marker = &attr.marker;
|
||||||
@@ -547,6 +550,8 @@ pub(crate) struct ItemShape {
|
|||||||
pub(crate) attrs: Vec<LevelAttr>,
|
pub(crate) attrs: Vec<LevelAttr>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Macro IR built once per node at expansion time, so the variant spread costs nothing at runtime.
|
||||||
|
#[allow(clippy::large_enum_variant)]
|
||||||
pub(crate) enum Element {
|
pub(crate) enum Element {
|
||||||
Concrete(Type),
|
Concrete(Type),
|
||||||
/// Indexes [`Node::generics`].
|
/// Indexes [`Node::generics`].
|
||||||
@@ -857,9 +862,7 @@ mod tests {
|
|||||||
let routing_source = |ty: &Type| generic.as_ref().is_some_and(|generic| crate::codegen::classify::routing_source_output(ty, generic));
|
let routing_source = |ty: &Type| generic.as_ref().is_some_and(|generic| crate::codegen::classify::routing_source_output(ty, generic));
|
||||||
match &field.ty {
|
match &field.ty {
|
||||||
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => {
|
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => {
|
||||||
if record && !skips_carrier && index == 0 {
|
if index == 0 && ((record && !skips_carrier) || carrier_flip) {
|
||||||
"carrier"
|
|
||||||
} else if carrier_flip && index == 0 {
|
|
||||||
"carrier"
|
"carrier"
|
||||||
} else if flip && lend.is_some() {
|
} else if flip && lend.is_some() {
|
||||||
"lend"
|
"lend"
|
||||||
|
|||||||
@@ -619,10 +619,10 @@ impl Parse for NodeFnAttributes {
|
|||||||
let parsed_path: Path = meta.parse_args().map_err(|_| Error::new_spanned(meta, "Expected a valid path for 'batch', e.g., batch(my_batch)"))?;
|
let parsed_path: Path = meta.parse_args().map_err(|_| Error::new_spanned(meta, "Expected a valid path for 'batch', e.g., batch(my_batch)"))?;
|
||||||
batch = Some(parsed_path);
|
batch = Some(parsed_path);
|
||||||
}
|
}
|
||||||
// Instructs the generated eval to report `Pending` instead of passing partial upstream values into this node.
|
// Keeps the plain-input lowering for this node during the record transition.
|
||||||
//
|
//
|
||||||
// Example usage:
|
// Example usage:
|
||||||
// #[node_macro::node(..., no_partial, ...)]
|
// #[node_macro::node(..., plain, ...)]
|
||||||
"plain" => {
|
"plain" => {
|
||||||
let path = meta.require_path_only()?;
|
let path = meta.require_path_only()?;
|
||||||
if plain {
|
if plain {
|
||||||
@@ -630,6 +630,10 @@ impl Parse for NodeFnAttributes {
|
|||||||
}
|
}
|
||||||
plain = true;
|
plain = true;
|
||||||
}
|
}
|
||||||
|
// Instructs the generated eval to report `Pending` instead of passing partial upstream values into this node.
|
||||||
|
//
|
||||||
|
// Example usage:
|
||||||
|
// #[node_macro::node(..., no_partial, ...)]
|
||||||
"no_partial" => {
|
"no_partial" => {
|
||||||
let path = meta.require_path_only()?;
|
let path = meta.require_path_only()?;
|
||||||
if no_partial {
|
if no_partial {
|
||||||
|
|||||||
@@ -83,10 +83,7 @@ fn brush_stamp_generator(_: impl Ctx, #[unit(" px")] diameter: f64, color: Color
|
|||||||
|
|
||||||
/// Used to efficiently paint brush strokes. Applies the same texture repeatedly at different positions with proper blending and boundary handling.
|
/// Used to efficiently paint brush strokes. Applies the same texture repeatedly at different positions with proper blending and boundary handling.
|
||||||
#[node_macro::node(category(""), skip_impl)]
|
#[node_macro::node(category(""), skip_impl)]
|
||||||
fn blit<BlendFn>(_: impl Ctx, mut target: List<Raster<CPU>>, texture: Raster<CPU>, positions: Vec<DVec2>, blend_mode: BlendFn) -> List<Raster<CPU>>
|
fn blit<BlendFn: Fn(Color, Color) -> Color>(_: impl Ctx, mut target: List<Raster<CPU>>, texture: Raster<CPU>, positions: Vec<DVec2>, blend_mode: BlendFn) -> List<Raster<CPU>> {
|
||||||
where
|
|
||||||
BlendFn: Fn(Color, Color) -> Color,
|
|
||||||
{
|
|
||||||
if positions.is_empty() {
|
if positions.is_empty() {
|
||||||
return target;
|
return target;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ fn read_gradient(ctx: impl Ctx + ExtractVarArgs) -> List<GradientStops> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The mapped row riding as vararg 0, in the production single-item shape.
|
/// The mapped row riding as vararg 0, in the production single-item shape.
|
||||||
fn vararg_list<'a, T: 'static>(ctx: &'a impl ExtractVarArgs) -> Option<&'a List<T>> {
|
fn vararg_list<T: 'static>(ctx: &impl ExtractVarArgs) -> Option<&List<T>> {
|
||||||
let arg = ctx.vararg(0).ok()?;
|
let arg = ctx.vararg(0).ok()?;
|
||||||
(arg as &dyn std::any::Any).downcast_ref::<List<T>>()
|
(arg as &dyn std::any::Any).downcast_ref::<List<T>>()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -86,7 +86,7 @@ fn memoize<'e, 'l>(
|
|||||||
return serve(entry, slot);
|
return serve(entry, slot);
|
||||||
}
|
}
|
||||||
if leveled {
|
if leveled {
|
||||||
return match content.materialize_level(&ctx, ctx.arena()) {
|
return match content.materialize_level(ctx, ctx.arena()) {
|
||||||
LevelStatus::Batch(batch, finality) => {
|
LevelStatus::Batch(batch, finality) => {
|
||||||
let layout = content.layout();
|
let layout = content.layout();
|
||||||
// SAFETY: the batch came from this input, so it carries the input's layout.
|
// SAFETY: the batch came from this input, so it carries the input's layout.
|
||||||
@@ -107,7 +107,7 @@ fn memoize<'e, 'l>(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
// The output layout is the content's, so the claim is the content's frame.
|
// The output layout is the content's, so the claim is the content's frame.
|
||||||
let result = content.serve(&ctx, slot);
|
let result = content.serve(ctx, slot);
|
||||||
let publishable = match &result {
|
let publishable = match &result {
|
||||||
GPoll::Final(served) => Some((served.record(), Finality::AllFinal)),
|
GPoll::Final(served) => Some((served.record(), Finality::AllFinal)),
|
||||||
GPoll::Partial(served) => Some((served.record(), Finality::Partial)),
|
GPoll::Partial(served) => Some((served.record(), Finality::Partial)),
|
||||||
@@ -185,7 +185,7 @@ fn frame_memo<'e, 'l>(
|
|||||||
};
|
};
|
||||||
let past_end = || GPoll::Error(Box::new(core_types::gpoll::GraphError::past_end()));
|
let past_end = || GPoll::Error(Box::new(core_types::gpoll::GraphError::past_end()));
|
||||||
let entry = cache.lock().unwrap().as_ref().filter(|entry| entry.key == key).map(|entry| (entry.span, entry.finality));
|
let entry = cache.lock().unwrap().as_ref().filter(|entry| entry.key == key).map(|entry| (entry.span, entry.finality));
|
||||||
// A span that no longer resolves was flushed; the miss below re-publishes.
|
// A span that no longer resolves was flushed.
|
||||||
if let Some((span, finality)) = entry
|
if let Some((span, finality)) = entry
|
||||||
&& let Some(published) = span.batch(persistent, content.layout())
|
&& let Some(published) = span.batch(persistent, content.layout())
|
||||||
{
|
{
|
||||||
@@ -196,7 +196,7 @@ fn frame_memo<'e, 'l>(
|
|||||||
return serve(published.get(lane).rec().ptr(), finality, slot);
|
return serve(published.get(lane).rec().ptr(), finality, slot);
|
||||||
}
|
}
|
||||||
if leveled {
|
if leveled {
|
||||||
return match content.materialize_level(&ctx, ctx.arena()) {
|
return match content.materialize_level(ctx, ctx.arena()) {
|
||||||
LevelStatus::Batch(batch, finality) => {
|
LevelStatus::Batch(batch, finality) => {
|
||||||
// SAFETY: the batch came from this input, so it carries the input's layout.
|
// SAFETY: the batch came from this input, so it carries the input's layout.
|
||||||
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) };
|
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) };
|
||||||
@@ -212,7 +212,7 @@ fn frame_memo<'e, 'l>(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
// The output layout is the content's, so the claim is the content's frame.
|
// The output layout is the content's, so the claim is the content's frame.
|
||||||
let result = content.serve(&ctx, slot);
|
let result = content.serve(ctx, slot);
|
||||||
let publishable = match &result {
|
let publishable = match &result {
|
||||||
GPoll::Final(served) => Some((served.record(), Finality::AllFinal)),
|
GPoll::Final(served) => Some((served.record(), Finality::AllFinal)),
|
||||||
GPoll::Partial(served) => Some((served.record(), Finality::Partial)),
|
GPoll::Partial(served) => Some((served.record(), Finality::Partial)),
|
||||||
@@ -246,7 +246,7 @@ fn monitor<'e, 'l>(
|
|||||||
if ctx.index() == 0 {
|
if ctx.index() == 0 {
|
||||||
*io.lock().unwrap() = Some(CtxSnapshot::capture(ctx));
|
*io.lock().unwrap() = Some(CtxSnapshot::capture(ctx));
|
||||||
}
|
}
|
||||||
content.serve(&ctx, slot)
|
content.serve(ctx, slot)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn serialize_monitor(io: &MonitorValue) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
|
fn serialize_monitor(io: &MonitorValue) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
|
||||||
@@ -262,7 +262,7 @@ mod tests {
|
|||||||
use core_types::context::{ContextImpl, EvalScope};
|
use core_types::context::{ContextImpl, EvalScope};
|
||||||
use core_types::node::Node;
|
use core_types::node::Node;
|
||||||
use core_types::record::LiftedSource;
|
use core_types::record::LiftedSource;
|
||||||
use core_types::registry::{EdgeHandle, ErasedRecordNode};
|
use core_types::registry::{SourceHandle, ErasedRecordNode};
|
||||||
use std::sync::atomic::{AtomicU32, Ordering};
|
use std::sync::atomic::{AtomicU32, Ordering};
|
||||||
|
|
||||||
fn lifted<T: Clone + Send + Sync + core_types::StaticTypeSized>(value: T) -> LiftedSource<T, impl for<'c> Fn(&ContextImpl<'c>) -> GPoll<T>>
|
fn lifted<T: Clone + Send + Sync + core_types::StaticTypeSized>(value: T) -> LiftedSource<T, impl for<'c> Fn(&ContextImpl<'c>) -> GPoll<T>>
|
||||||
@@ -303,7 +303,7 @@ mod tests {
|
|||||||
|
|
||||||
let layout = element_layout::<u32>();
|
let layout = element_layout::<u32>();
|
||||||
let monitor = MonitorNode::new(lifted::<u32>(11u32), &layout);
|
let monitor = MonitorNode::new(lifted::<u32>(11u32), &layout);
|
||||||
let handle = EdgeHandle::new_record::<u32>(Arc::new(monitor) as Arc<ErasedRecordNode>);
|
let handle = SourceHandle::new_record::<u32>(Arc::new(monitor) as Arc<ErasedRecordNode>);
|
||||||
assert!(handle.serialize().is_none(), "no snapshot before the first eval");
|
assert!(handle.serialize().is_none(), "no snapshot before the first eval");
|
||||||
|
|
||||||
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
|
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
|
||||||
@@ -331,7 +331,7 @@ mod tests {
|
|||||||
let source = core_types::value::LeveledValueSource::new(vec![10u32, 20, 30]);
|
let source = core_types::value::LeveledValueSource::new(vec![10u32, 20, 30]);
|
||||||
let layout = Node::<ContextImpl>::layout(&source).clone();
|
let layout = Node::<ContextImpl>::layout(&source).clone();
|
||||||
let monitor = MonitorNode::new(source, &layout);
|
let monitor = MonitorNode::new(source, &layout);
|
||||||
let handle = EdgeHandle::new_record::<u32>(Arc::new(monitor) as Arc<ErasedRecordNode>);
|
let handle = SourceHandle::new_record::<u32>(Arc::new(monitor) as Arc<ErasedRecordNode>);
|
||||||
|
|
||||||
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
|
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
|
||||||
let GPoll::Final(_) = core_types::record::serve_input(&edge, &ctx, &frames) else {
|
let GPoll::Final(_) = core_types::record::serve_input(&edge, &ctx, &frames) else {
|
||||||
@@ -475,8 +475,8 @@ mod tests {
|
|||||||
let ctx = ContextImpl::root(&scope);
|
let ctx = ContextImpl::root(&scope);
|
||||||
|
|
||||||
let layout = element_layout::<u32>();
|
let layout = element_layout::<u32>();
|
||||||
let edge = EdgeHandle::new_record::<u32>(Arc::new(counting()) as Arc<ErasedRecordNode>);
|
let edge = SourceHandle::new_record::<u32>(Arc::new(counting()) as Arc<ErasedRecordNode>);
|
||||||
let memoized = EdgeHandle::new_record::<u32>(Arc::new(MemoizeNode::new(edge.downcast_record::<u32>().unwrap(), &layout)) as Arc<ErasedRecordNode>);
|
let memoized = SourceHandle::new_record::<u32>(Arc::new(MemoizeNode::new(edge.downcast_record::<u32>().unwrap(), &layout)) as Arc<ErasedRecordNode>);
|
||||||
let stacked = MemoizeNode::new(memoized.downcast_record::<u32>().unwrap(), &layout);
|
let stacked = MemoizeNode::new(memoized.downcast_record::<u32>().unwrap(), &layout);
|
||||||
let stacked = core_types::record::RecordExtract::<u32, _>::new(stacked, &layout);
|
let stacked = core_types::record::RecordExtract::<u32, _>::new(stacked, &layout);
|
||||||
|
|
||||||
|
|||||||
@@ -171,8 +171,7 @@ fn extend_extent(base: ExtentIn<'_>, new: ExtentIn<'_>, level: LevelIn) -> GPoll
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The layer-path stamp: the flip-time replacement for the Merge
|
/// The layer-path stamp: writes the owning layer's document node path on each lane.
|
||||||
/// subnetwork's named attribute write.
|
|
||||||
#[node_macro::node(category("Test"))]
|
#[node_macro::node(category("Test"))]
|
||||||
fn stamp_layer_path<'e, T>(ctx: impl Ctx + ExtractArena<'e>, element: T, path: Vec<NodeId>) -> Result<(T, Attr<'e, EditorLayerPath>), Interrupt> {
|
fn stamp_layer_path<'e, T>(ctx: impl Ctx + ExtractArena<'e>, element: T, path: Vec<NodeId>) -> Result<(T, Attr<'e, EditorLayerPath>), Interrupt> {
|
||||||
let (parked, _) = ctx.arena().alloc(path).ok_or(GraphError {
|
let (parked, _) = ctx.arena().alloc(path).ok_or(GraphError {
|
||||||
@@ -2984,8 +2983,8 @@ mod tests {
|
|||||||
{
|
{
|
||||||
let scope = scope_fixture(&generations, &first_arena).with_persistent(&persistent);
|
let scope = scope_fixture(&generations, &first_arena).with_persistent(&persistent);
|
||||||
let ctx = ContextImpl::root(&scope);
|
let ctx = ContextImpl::root(&scope);
|
||||||
let mut first = frames.reborrow();
|
let first = frames.reborrow();
|
||||||
let GPoll::Final(_) = core_types::record::serve_input(&memo, &ctx, &mut first) else {
|
let GPoll::Final(_) = core_types::record::serve_input(&memo, &ctx, &first) else {
|
||||||
panic!("expected a final record");
|
panic!("expected a final record");
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -226,7 +226,7 @@ where
|
|||||||
}
|
}
|
||||||
let fill = park_paint(legacy.attribute::<Option<List<Graphic>>>(graphic_types::ATTR_FILL, source).cloned().flatten())?;
|
let fill = park_paint(legacy.attribute::<Option<List<Graphic>>>(graphic_types::ATTR_FILL, source).cloned().flatten())?;
|
||||||
let stroke = park_paint(legacy.attribute::<Option<List<Graphic>>>(graphic_types::ATTR_STROKE, source).cloned().flatten())?;
|
let stroke = park_paint(legacy.attribute::<Option<List<Graphic>>>(graphic_types::ATTR_STROKE, source).cloned().flatten())?;
|
||||||
let layer_path: Vec<NodeId> = legacy.attribute::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH, source).map(|path| path.clone()).unwrap_or_default();
|
let layer_path: Vec<NodeId> = legacy.attribute::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH, source).cloned().unwrap_or_default();
|
||||||
let layer_path = arena.alloc(layer_path).ok_or_else(exhausted)?.0;
|
let layer_path = arena.alloc(layer_path).ok_or_else(exhausted)?.0;
|
||||||
|
|
||||||
Ok((
|
Ok((
|
||||||
@@ -540,7 +540,7 @@ fn to_graphic_unit_extent(_content: core_types::extent::ValueIn<'_, ()>, _level:
|
|||||||
/// The transitional level bridge: the input's records as the legacy list an
|
/// The transitional level bridge: the input's records as the legacy list an
|
||||||
/// unconverted consumer expects, attributes copied through their erased
|
/// unconverted consumer expects, attributes copied through their erased
|
||||||
/// reads and content kept in its native form. Registered under the legacy
|
/// reads and content kept in its native form. Registered under the legacy
|
||||||
/// convert identifiers; the rows die with the last legacy consumer.
|
/// convert identifiers.
|
||||||
#[node_macro::node(category(""))]
|
#[node_macro::node(category(""))]
|
||||||
pub fn level_to_list<T: Clone + Send + Sync + CacheHash + dyn_any::StaticTypeSized>(
|
pub fn level_to_list<T: Clone + Send + Sync + CacheHash + dyn_any::StaticTypeSized>(
|
||||||
_: impl Ctx,
|
_: impl Ctx,
|
||||||
|
|||||||
@@ -551,9 +551,9 @@ mod tests {
|
|||||||
let entries = _flat_map_mod::flat_map_entries();
|
let entries = _flat_map_mod::flat_map_entries();
|
||||||
assert_eq!(entries.len(), 6, "one registry row per content implementation");
|
assert_eq!(entries.len(), 6, "one registry row per content implementation");
|
||||||
let content_types: Vec<core_types::Type> = entries.iter().map(|entry| entry.io.inputs[0].clone()).collect();
|
let content_types: Vec<core_types::Type> = entries.iter().map(|entry| entry.io.inputs[0].clone()).collect();
|
||||||
assert_eq!(content_types[0], core_types::registry::record_edge_type::<Graphic>());
|
assert_eq!(content_types[0], core_types::registry::record_source_type::<Graphic>());
|
||||||
assert_eq!(content_types[1], core_types::registry::record_edge_type::<Vector>());
|
assert_eq!(content_types[1], core_types::registry::record_source_type::<Vector>());
|
||||||
assert_eq!(content_types[5], core_types::registry::record_edge_type::<String>());
|
assert_eq!(content_types[5], core_types::registry::record_source_type::<String>());
|
||||||
// The subject and the output stay erased across rows.
|
// The subject and the output stay erased across rows.
|
||||||
assert_eq!(entries[0].io.inputs[1], entries[5].io.inputs[1]);
|
assert_eq!(entries[0].io.inputs[1], entries[5].io.inputs[1]);
|
||||||
assert_eq!(entries[0].io.return_value, entries[5].io.return_value);
|
assert_eq!(entries[0].io.return_value, entries[5].io.return_value);
|
||||||
@@ -885,8 +885,7 @@ mod tests {
|
|||||||
let GPoll::Final(value) = record::serve_input(&wrapped, &ctx.promoted(&head, 0), &scope) else {
|
let GPoll::Final(value) = record::serve_input(&wrapped, &ctx.promoted(&head, 0), &scope) else {
|
||||||
panic!("expected a final record");
|
panic!("expected a final record");
|
||||||
};
|
};
|
||||||
let group = unsafe { record::borrow_element::<Graphic>(wrap_out.rec(&value)) }.clone();
|
unsafe { record::borrow_element::<Graphic>(wrap_out.rec(&value)) }.clone()
|
||||||
group
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// One row holding the wrapped group flattens back to the lanes, the
|
// One row holding the wrapped group flattens back to the lanes, the
|
||||||
|
|||||||
@@ -1016,7 +1016,7 @@ mod graphene_test {
|
|||||||
use core_types::node::{BatchStatus, Node};
|
use core_types::node::{BatchStatus, Node};
|
||||||
use core_types::record::{Layout, LiftedSource, RecordValue, serve_input};
|
use core_types::record::{Layout, LiftedSource, RecordValue, serve_input};
|
||||||
use core_types::registry::{ErasedRecordNode, construct};
|
use core_types::registry::{ErasedRecordNode, construct};
|
||||||
use core_types::value::record_value_edge;
|
use core_types::value::record_value_source;
|
||||||
use std::mem::MaybeUninit;
|
use std::mem::MaybeUninit;
|
||||||
|
|
||||||
fn scope_fixture(arena: &Arena) -> EvalScope<'_> {
|
fn scope_fixture(arena: &Arena) -> EvalScope<'_> {
|
||||||
@@ -1111,7 +1111,7 @@ mod graphene_test {
|
|||||||
let ctx = ContextImpl::root(&scope);
|
let ctx = ContextImpl::root(&scope);
|
||||||
|
|
||||||
let entries = super::_logical_or_mod::logical_or_entries();
|
let entries = super::_logical_or_mod::logical_or_entries();
|
||||||
let mut wired = construct(&entries[0], vec![record_value_edge(true), record_value_edge(false)]).unwrap();
|
let mut wired = construct(&entries[0], vec![record_value_source(true), record_value_source(false)]).unwrap();
|
||||||
let layout = out_layout::<bool>();
|
let layout = out_layout::<bool>();
|
||||||
wired.set_layout(core_types::record::RecordLayout {
|
wired.set_layout(core_types::record::RecordLayout {
|
||||||
frame_bytes: layout.frame_bytes(),
|
frame_bytes: layout.frame_bytes(),
|
||||||
@@ -1148,16 +1148,16 @@ mod graphene_test {
|
|||||||
assert_eq!(entries.len(), 6);
|
assert_eq!(entries.len(), 6);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
entries[0].io.inputs,
|
entries[0].io.inputs,
|
||||||
vec![core_types::registry::record_edge_type::<f64>(), core_types::registry::record_edge_type::<f64>()]
|
vec![core_types::registry::record_source_type::<f64>(), core_types::registry::record_source_type::<f64>()]
|
||||||
);
|
);
|
||||||
assert_eq!(entries[0].io.return_value, core_types::registry::record_type::<f64>());
|
assert_eq!(entries[0].io.return_value, core_types::registry::record_type::<f64>());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
entries[3].io.inputs,
|
entries[3].io.inputs,
|
||||||
vec![core_types::registry::record_edge_type::<DVec2>(), core_types::registry::record_edge_type::<DVec2>()]
|
vec![core_types::registry::record_source_type::<DVec2>(), core_types::registry::record_source_type::<DVec2>()]
|
||||||
);
|
);
|
||||||
assert_eq!(entries[3].io.return_value, core_types::registry::record_type::<DVec2>());
|
assert_eq!(entries[3].io.return_value, core_types::registry::record_type::<DVec2>());
|
||||||
|
|
||||||
let mut wired = construct(&entries[0], vec![record_value_edge(1.5f64), record_value_edge(2.5f64)]).unwrap();
|
let mut wired = construct(&entries[0], vec![record_value_source(1.5f64), record_value_source(2.5f64)]).unwrap();
|
||||||
let layout = out_layout::<f64>();
|
let layout = out_layout::<f64>();
|
||||||
wired.set_layout(core_types::record::RecordLayout {
|
wired.set_layout(core_types::record::RecordLayout {
|
||||||
frame_bytes: layout.frame_bytes(),
|
frame_bytes: layout.frame_bytes(),
|
||||||
@@ -1179,7 +1179,7 @@ mod graphene_test {
|
|||||||
// Routing forwards the whole record, so the branch types need no rows.
|
// Routing forwards the whole record, so the branch types need no rows.
|
||||||
let entries = super::_switch_mod::switch_entries();
|
let entries = super::_switch_mod::switch_entries();
|
||||||
assert_eq!(entries.len(), 1);
|
assert_eq!(entries.len(), 1);
|
||||||
assert_eq!(entries[0].io.inputs[0], core_types::registry::record_edge_type::<bool>());
|
assert_eq!(entries[0].io.inputs[0], core_types::registry::record_source_type::<bool>());
|
||||||
assert!(matches!(&entries[0].io.return_value, core_types::Type::Record(element) if matches!(**element, core_types::Type::Generic(_))));
|
assert!(matches!(&entries[0].io.return_value, core_types::Type::Record(element) if matches!(**element, core_types::Type::Generic(_))));
|
||||||
assert_eq!(entries[0].io.inputs.len(), 3);
|
assert_eq!(entries[0].io.inputs.len(), 3);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ fn boolean_core<'e>(
|
|||||||
use core_types::lane::LaneSource;
|
use core_types::lane::LaneSource;
|
||||||
let fill = park_paint(result_vector_list.attr::<Fill>(0).filter(|paint| is_paint_present(paint)).cloned())?;
|
let fill = park_paint(result_vector_list.attr::<Fill>(0).filter(|paint| is_paint_present(paint)).cloned())?;
|
||||||
let stroke = park_paint(result_vector_list.attr::<Stroke>(0).filter(|paint| is_paint_present(paint)).cloned())?;
|
let stroke = park_paint(result_vector_list.attr::<Stroke>(0).filter(|paint| is_paint_present(paint)).cloned())?;
|
||||||
let layer_path: Vec<NodeId> = result_vector_list.attribute::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH, 0).map(|path| path.clone()).unwrap_or_default();
|
let layer_path: Vec<NodeId> = result_vector_list.attribute::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH, 0).cloned().unwrap_or_default();
|
||||||
let layer_path = arena.alloc(layer_path).ok_or_else(exhausted)?.0;
|
let layer_path = arena.alloc(layer_path).ok_or_else(exhausted)?.0;
|
||||||
// Snapshot the input layers so the renderer can recurse into them for
|
// Snapshot the input layers so the renderer can recurse into them for
|
||||||
// editor click-target preservation.
|
// editor click-target preservation.
|
||||||
|
|||||||
@@ -433,7 +433,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn qr_code_test() {
|
fn qr_code_test() {
|
||||||
let qr = qr_code(&(), (), "https://graphite.art".to_string(), false, 1., QRCodeErrorCorrectionLevel::Low, true);
|
let qr = qr_code(&(), (), "https://graphite.art".to_string(), false, 1., QRCodeErrorCorrectionLevel::Low, true);
|
||||||
assert!(qr.point_domain.ids().len() > 0);
|
assert!(!qr.point_domain.ids().is_empty());
|
||||||
assert!(qr.segment_domain.ids().len() > 0);
|
assert!(!qr.segment_domain.ids().is_empty());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -327,7 +327,6 @@ fn paint_table(paint: core_types::node::List<'_, Graphic<'_>>) -> List<Graphic<'
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Applies a fill style to the vector content, giving an appearance to the area within the interior of the geometry.
|
/// Applies a fill style to the vector content, giving an appearance to the area within the interior of the geometry.
|
||||||
/// The gradient transform fallback spans the lane's own bounds rather than the whole content's.
|
|
||||||
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector), properties("fill_properties"))]
|
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector), properties("fill_properties"))]
|
||||||
fn fill<'e>(
|
fn fill<'e>(
|
||||||
ctx: impl Ctx + ExtractArena<'e> + ExtractIndex + InjectIndex + Copy,
|
ctx: impl Ctx + ExtractArena<'e> + ExtractIndex + InjectIndex + Copy,
|
||||||
@@ -1578,7 +1577,7 @@ fn emit_legacy_lane<'e>(
|
|||||||
/// one group lane, lane 0's layer path stamped on the wrapper.
|
/// one group lane, lane 0's layer path stamped on the wrapper.
|
||||||
fn wrap_vector_level(content: core_types::node::List<'_, Vector>) -> List<Graphic<'_>> {
|
fn wrap_vector_level(content: core_types::node::List<'_, Vector>) -> List<Graphic<'_>> {
|
||||||
let item = content.as_group_item();
|
let item = content.as_group_item();
|
||||||
let layer_path: Vec<NodeId> = match content.len() > 0 {
|
let layer_path: Vec<NodeId> = match !content.is_empty() {
|
||||||
true => content.lane(0).attr::<EditorLayerPath>().to_vec(),
|
true => content.lane(0).attr::<EditorLayerPath>().to_vec(),
|
||||||
false => Vec::new(),
|
false => Vec::new(),
|
||||||
};
|
};
|
||||||
@@ -1767,8 +1766,6 @@ fn path_is_closed(
|
|||||||
.unwrap_or(false)
|
.unwrap_or(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Converts with the write-attribute family: the record form needs a lazy
|
|
||||||
// value input on a record node, which the macro does not accept yet, and it
|
|
||||||
/// Sets each anchor point's position to the value the mapped input produces, with the point's
|
/// Sets each anchor point's position to the value the mapped input produces, with the point's
|
||||||
/// index and current position provided via context.
|
/// index and current position provided via context.
|
||||||
#[node_macro::node(category("Vector"), path(graphene_core::vector), extent(map_points_extent))]
|
#[node_macro::node(category("Vector"), path(graphene_core::vector), extent(map_points_extent))]
|
||||||
|
|||||||
Reference in new issue
Block a user