Compare commits

..
Author SHA1 Message Date
Dennis KobertandClaude Fable 5.1 8b1d6bd938 WIP: single-lane gather shortcut, borrowed layouts for stacks, lock-free glue lookups
A gathered input whose producer has a depth-0 layout serves at most one
lane per context, so a first group of one lane skips the per-group extent
probes; a short grouped fill falls back per lane. GRAPHENE_NO_RAGGED_CHECK
skips the probes for measurement. A stack adopts its sides borrowing the
source node's layout instead of cloning it into an Arc per lane. The
promotion and deep-clone glue maps read under an RwLock with Fx hashing.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-19 11:27:31 +00:00
Dennis KobertandClaude Fable 5.1 d5a5f35595 WIP: demo artworks render again with stacks; ragged levels fall back per lane
Stacks only replace an extend when every transitive consumer forwards or
renders lanes; lane-inspecting nodes keep the plain extend. Boolean flatten,
assign colors and the graphic flatten walkers treat a stack lane's runs as
inline lanes. A gathered input that comes back short serves what it got, a
short grouped gather and a ragged repeat fall back to per-lane evaluation,
and stack_graphics reports its own extent. Debug tracing for past-end
signals and refused stacks is env-gated.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-19 10:19:51 +00:00
Dennis Kobert ee0918e1de WIP: geometry cell on the vector, shared click targets, transparent stacks in metadata 2026-09-18 23:10:28 +00:00
Dennis Kobert d650ea3c8c WIP: segmented stacks, vector by reference, lent carriers 2026-09-18 19:51:21 +00:00
Dennis Kobert ea7acc749a WIP: batch gathers, level-pushing flips, and shared inputs end to end 2026-09-18 14:29:19 +00:00
Dennis KobertandClaude Fable 5.1 43be58e003 WIP: dispatch-based batch protocol with lane maps and a lane view; serve contexts rebuilt per lane
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-17 19:47:03 +00:00
Dennis KobertandClaude Fable 5.1 aaff28f63a WIP: batch forwarding through boundaries, routes and memos; batched carrier subjects; per-kernel batch tally
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-17 18:15:28 +00:00
Dennis KobertandClaude Fable 5.1 7a206a973f WIP: index memo table, region growth, zoom-invariant render key, Fx hashers, batch tally per consumer
Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-17 15:10:27 +00:00
Dennis Kobert 851cf43f2a Add the brick-waves artwork used to reproduce the index-level collapse 2026-09-17 12:55:34 +02:00
Dennis Kobert e735051005 Narrow read_index's declared index levels in the preprocessor (WIP, renders wrong) 2026-09-17 12:28:30 +02:00
Keavon Chambers 9720e4e4fd Relicense Graphite under the dual MIT/Apache-2.0 license (#4208)
Relicense under dual MIT/Apache-2.0
2026-09-16 10:48:14 +02:00
Keavon Chambers fa03494f04 Remove a couple of old frontend comments 2026-09-16 10:48:13 +02:00
Keavon Chambers f342f6fa08 Extend open paths from endpoints with the Freehand tool and skip hidden layers in path edits (#4508) 2026-09-16 10:48:12 +02:00
Keavon Chambers 5d7ae25c87 Revert #1594 and #1623 so the Freehand tool no longer extends existing paths 2026-09-16 10:48:11 +02:00
Keavon Chambers b4af039c14 Give each Pen tool segment its own history step and keep drawing across undo/redo (#4507) 2026-09-16 10:48:09 +02:00
Keavon Chambers fc850de7f3 Revert #1587 and #1597 so the Pen tool no longer handles per-segment history 2026-09-16 10:48:08 +02:00
Timon 74b9162a9f Desktop: Port the pointer shake event detection for direct input routing (#4506)
Desktop: Port shake detection for direct input routing
2026-09-16 10:48:07 +02:00
Timon b234cdfb21 Desktop: Mirror direct viewport input to the UI (#4502)
Desktop: Mirror direct-routed input to the UI
2026-09-16 10:48:06 +02:00
Timon 4a080571a2 Desktop: Make input routing aware of floating menus (#4498)
* Desktop: Make input routing aware of floating menus

* Desktop: Route mouse input like pen input

* Desktop: Model pointer input routing as a state machine
2026-09-16 10:48:05 +02:00
Timon 16f8d6d634 Desktop: Restructure UI input handling (#4500) 2026-09-16 10:48:03 +02:00
Keavon Chambers 37e19eabe3 Pin cargo-binstall and cargo-about and cross-reference all tool version pins (#4505)
* Pin cargo-binstall and cargo-about and cross-reference all tool version pins

* Pin the cargo-binstall GitHub Action to its release tag

* Use a version floor for cargo-about and drop the Nix sync notices
2026-09-16 10:48:02 +02:00
Daniel Z. 1eb215ee0e Fix dev environment configurations with devcontainer, vscode, and cargo-about (#4372)
Some minor fixes to issues I ran into using devcontainer on this project
with vscode.

- Add `esbenp.prettier-vscode` to the recommended extensions list as
it's already used in `.vscode/settings.json`
- Install `wasm32-unknown-unknown` Rust target in devcontainer
- Add cargo-binstall and pin cargo-about version in devcontainer
- Remove `no-clearly-defined = true` from `about.toml`:
  - cargo-about 0.9.1 fails to run if `no-clearly-defined` is present
- cargo-about 0.8.0 already [removed
support](https://github.com/EmbarkStudios/cargo-about/blob/main/CHANGELOG.md#080---2025-09-05)
for clearlydefined.io, so the argument is a no-op
2026-09-16 10:48:01 +02:00
Timon 65f1ed71ca Desktop: Fix node graph grid dot transparency (#4504) 2026-09-16 10:47:59 +02:00
Timon 6109c13f25 Add 'Scale with Viewport' option to the Brush tool (#4485) 2026-09-16 10:47:58 +02:00
Timon 84b95608d0 Fix Brush tool drawing into nested layers (#4487) 2026-09-16 10:47:57 +02:00
Timon 2cd6f10299 Desktop: Improve Mac signing and notarization 2026-09-16 10:47:55 +02:00
Timon ce95bc3ec0 Desktop: Update CEF to 151 (#4490) 2026-09-16 10:47:54 +02:00
Timon e304c1d879 Update Nix flake (#4489) 2026-09-16 10:47:53 +02:00
Timon e4df7e6416 Add the CODEOWNERS file (#4477)
Introduce `CODEOWNERS` file
2026-09-16 10:47:52 +02:00
Keavon Chambers 45863723c6 Add a thanks banner to the donation page's flow 2026-09-16 10:47:51 +02:00
Keavon Chambers accc54bb24 Revamp the website's donation page 2026-09-16 10:47:49 +02:00
Keavon Chambers df70f56188 Update the roadmap on the website 2026-09-16 10:47:48 +02:00
Keavon Chambers e9dfe08996 Bump the Graphite release series to alpha 5, intended as retroactively backdated to the start of 2026 2026-09-16 10:47:47 +02:00
Timon 0ca3625252 Improve fix for corrupted font resource loading in older documents (#4482) 2026-09-16 10:47:45 +02:00
Timon ada0914959 Move file filter creation from frontend to editor (#4351) 2026-09-16 10:47:44 +02:00
James Lindsay 79949226ae Frontend type constraints (#4334) 2026-09-16 10:47:36 +02:00
Timon 0c7fc3214f Add the 'Basic Brush' node and replace the legacy Brush tool implementation with it (#4469) 2026-09-16 10:47:35 +02:00
Timon ae2307b9b0 Add caching infrastructure for the GPU brush nodes (#4468) 2026-09-16 10:47:33 +02:00
Timon 83e031f0d2 Introduce the new brush stroke data types (#4467) 2026-09-16 10:47:23 +02:00
Timon f9bdac7fd2 Improve texture caching by allowing weak refs and more formats (#4447) 2026-09-16 01:15:29 +02:00
Timon 9b9ea5741d Fix Vello-related GPU out-of-memory issues (#4446) 2026-09-16 01:15:28 +02:00
Timon 678c22644f Support input from drawing tablets on web (#4445) 2026-09-16 01:15:27 +02:00
Timon b82d9de927 Add time since pointerdown to input event handling (#4443) 2026-09-16 01:15:25 +02:00
Timon 8ae2df47fb Desktop: Support input from drawing tablets (#4354) 2026-09-16 01:15:24 +02:00
Keavon Chambers 71fdf3746a Fix corrupted font resource loading in older documents 2026-09-16 01:15:22 +02:00
Keavon Chambers 8d2645e20c Make Data panel scalars selectable inline, denoise float display, and standardize breadcrumb string truncation (#4470) 2026-09-16 01:15:21 +02:00
Keavon Chambers 704af633b7 Reintroduce improved logic for mesh interior region fill determination (#4464) 2026-09-16 01:15:20 +02:00
Keavon Chambers d5bb1396ec Delete the vestigial region domain, reverting to naive logic for mesh region fill determination (#4463) 2026-09-16 01:15:18 +02:00
Dennis Kobert 9bfbc20d87 Fix the remaining clippy warnings across the workspace 2026-09-16 01:15:16 +02:00
Keavon Chambers 45d6f1bd39 Delete the dead StrokeId and FillId attributes from the Vector segment and region domains (#4461) 2026-09-16 01:15:15 +02:00
Keavon Chambers 38c6685e7f Auto-recover stuck npm installs blocked on files locked by zombie processes (#4460) 2026-09-16 01:15:09 +02:00
Keavon Chambers cca178384e Dedupe code for BezPath emission, epsilon constants, and Polynomial internals (#4459) 2026-09-16 01:15:07 +02:00
Keavon Chambers 5fb67897de Clean up the Vector struct implementations by privatizing and deleting unused APIs (#4458) 2026-09-16 01:15:06 +02:00
Keavon Chambers 9fbd44d21d Port all remaining Subpath producers to BezPath and delete the legacy subpath module (#4457) 2026-09-16 01:15:05 +02:00
Keavon Chambers 89617462b6 Collapse ClickTargetType to a single multi-contour BezPath variant (#4456) 2026-09-16 01:15:03 +02:00
Keavon Chambers 26f4c655a1 Replace the legacy Bezier struct with kurbo::PathSeg throughout (#4455) 2026-09-16 01:15:02 +02:00
Keavon Chambers bf0f3510df Remove remnant dead code across the Subpath, Vector, and editor geometry API surfaces (#4454) 2026-09-16 01:15:00 +02:00
Keavon Chambers 9dfb5bd733 Add the "Type Assertion" node catalog category (#4452) 2026-09-16 01:14:59 +02:00
Keavon Chambers 9cca3f0e1e Fix color and gradient list paints not rendering as stacks (#4439) 2026-09-16 01:14:58 +02:00
Keavon Chambers 4a22f23d43 Fix the blend mode formulas for the Overlay, whole-color, and alpha-only modes (#4449) 2026-09-16 01:14:57 +02:00
Keavon Chambers 950c3afbb5 Move the color blending helpers down beside Color and BlendMode in no-std-types (#4448) 2026-09-16 01:14:56 +02:00
Keavon Chambers 2a86112a93 Replace the IntoPaint trait with direct Graphic-typed node inputs (#4442) 2026-09-16 01:14:49 +02:00
Keavon Chambers a41fdb3d75 Split 'To Graphic' and 'Wrap Graphic' into the 'As Graphic' type assertion and 'Into Group' reducer nodes (#4441) 2026-09-15 16:46:03 +02:00
Keavon ChambersandDennis Kobert f09eb73c08 Rename the Graphic enum wrapper variants with a "List" suffix (#4434)
Only the list-holding variant takes the suffix here: the record model already carries the rank-0 leaves upstream adds in #4437.

Co-authored-by: Dennis Kobert <[email protected]>
2026-09-15 15:08:26 +02:00
Keavon ChambersandDennis Kobert a41b362fe2 Adopt the cascading "appearance" attribute in place of Vector::stroke and the "fill"/"paint" attributes (#4433)
Reimplemented on the record model in place of upstream d117c3eace.

Co-authored-by: Dennis Kobert <[email protected]>
2026-09-15 14:49:57 +02:00
Dennis Kobert 28e5d1bdc9 Let vector modifier nodes operate on graphic content by recursing into groups 2026-09-15 14:40:47 +02:00
Dennis Kobert 64adde1ced Add a generic map over a graphic's leaves, reaching every depth 2026-09-15 14:40:43 +02:00
Keavon Chambers d7f35259c9 Make the 'Boolean Operation' node ignore raster, color, and gradient content (#4430)
Stop the Boolean Operation flattener fabricating operands from non-path content
2026-09-15 14:40:39 +02:00
Keavon Chambers 1c88592fa4 Fix clipping masks, click targets, and bounds when rendering Vector[] and flattened graphic wrappers (#4429)
* Honor clipping masks when rendering Vector[] lists, not just Graphic[] groups

* Keep per-layer click targets when a Vector[] round-trips through a Graphic[] wrapper

* Skip the rebuild and the merged-layers snapshot when flattening a lone anonymous graphic wrapper

* Fix a group's bounds excluding its raster children and stretching to the origin

* Fix SVG clipping masks landing in the wrong space when sibling layers differ in transform
2026-09-15 14:40:35 +02:00
Keavon Chambers ae1ff71f45 Fix style controls corrupting stack nodes like Transform that can't host blending or paint nodes (#4428)
* Stop chain node insertion from stranding a node on layers without a chain

* Gate the Layers panel blending controls on whether the layer can host them

* Gate the fill and stroke setters on whether the layer can host paint nodes

* Make the tool options fill and stroke controls treat layers that cannot take paint as unselected

* Remove the unused first_selected_stroke_weight helper
2026-09-15 14:40:31 +02:00
Keavon Chambers 0e0687c8cb Make the 'Index Points' node index within each vector element instead of across the whole list (#4427) 2026-09-15 14:40:26 +02:00
Keavon Chambers 29540adc8f New node: 'Gradient to Colors' for unwrapping a gradient ramp into its colors (#4425)
* New node: 'Gradient to Colors' for unwrapping a gradient ramp into its colors

* Update 'Gradient Midpoints' wording
2026-09-15 14:40:23 +02:00
Keavon Chambers 1356139559 New nodes: 'Gradient Reverse', 'Gradient Shift', and 'Gradient Stretch' nodes for rearranging a ramp's stops (#4424)
* New nodes: 'Gradient Reverse', 'Gradient Shift', and 'Gradient Stretch' nodes for rearranging a ramp's stops

* Clip a lone out-of-range stop into the bake, and correct the docs that still promised edge-held stops
2026-09-15 14:40:18 +02:00
Keavon Chambers 35e77de9fe Fix read-only widget appearance and focus, and keep ColorInput picks surviving a layout diff (#4423) 2026-09-15 14:40:13 +02:00
Keavon Chambers ca615fd6fc Rename the 'Sample Gradient' node to 'Evaluate Gradient' (#4422)
* Rename the 'Sample Gradient' node to 'Evaluate Gradient'

* Let the Evaluate Gradient node's position reach the out-of-range values its spread modes handle
2026-09-15 14:40:09 +02:00
Keavon Chambers ed738b8e5c Drop CSS vendor prefixes and compat workarounds now obsolete in modern browsers (#4421) 2026-09-15 14:40:04 +02:00
Keavon Chambers d2d372d875 Clean up CSS color opacity application to theme colors (#4420) 2026-09-15 14:40:00 +02:00
Keavon Chambers da3ffa1721 Fix Vello rendering incompatibility with its gradients using premultiplied alpha instead of SVG's straight (#4419)
* Upgrade Vello to a git main revision that honors the brush's interpolation alpha space

* Interpolate Vello gradients with straight alpha, matching the SVG renderer

* Draw the gradient picker strip and fill swatches as SVG so transparency previews with straight alpha

* Keep gradient stop handles opaque so a transparent stop's RGB stays visible

* Paint a stopless gradient's picker strip and swatch black rather than transparent
2026-09-15 14:39:56 +02:00
Keavon Chambers 9181a62e99 Add a gradient interpolation attribute with Stepped, Linear (existing), and Smooth modes (#4418)
* Delete dead code function

* Add a Gradient Interpolation axis with Stepped, Linear, and Smooth paths through the stops

* Keep the gradient interpolation attached when dragging stops in the picker

* Give the gradient popover's dropdowns the same tooltips as their row labels

* Order the gradient popover with Intrp. above Space

* Hold gradient stops in place when the cyclic flag is toggled

* Fix wrong Smooth gradient colors around stops sitting on the ramp boundaries

* Consolidate gradient settings plumbing and fix bugs

* Bundle whole-ramp gradient settings into GradientSettings across the editor plumbing

* Name the Smooth gradient interpolation's spline type in its tooltip

* Linearize the gamma hex stop colors recovered from imported Graphite SVGs

* Code review

* Aim the Smooth bake's seam subdivision at the copied boundary color

* Add GradientEvaluator to build gradient sampling state once per loop instead of per sample

* Correct the gradient evaluator's documented setup cost to O(n log n)
2026-09-15 14:39:52 +02:00
Keavon Chambers c00eb21a7f Add a "Cyclic" gradient option that closes the ramp into a seamless loop (#4416)
* Add a Cyclic gradient attribute that wraps the stop list through the 1|0 boundary back to the first stop

* Show the wrap segment's midpoint diamond in the color picker spectrum strip when cyclic

* Keep the wrap midpoint diamond tracking the pointer by a wrapped strip width when dragged past the ends

* Give the Gradient tool's viewport overlay the same cyclic wrap midpoint diamond and drag behavior

* Correct the docs claiming the final stop's midpoint is always ignored now that cyclic uses it

* Move the gradient cyclic toggle onto the Ends row as a Link icon checkbox

* Update labels

* Register GradientHueDirection with the Data panel so its attribute column renders

* Reword wrap segment to wrapped interval and stray segment usages to interval

* Clean up comments

* Fix the color picker write-back losing default position elision and the blend path guessing the cyclic flag
2026-09-15 14:39:48 +02:00
Keavon Chambers be42a0aada Add the "Perceptual" and "Classic" families of gradient spaces with OkLab as the new default (#4415)
* Add an OkLab gradient interpolation space and make it the new default

* Fix the Properties panel fill row resetting the gradient interpolation space to the default

* Add OkLch, Lab, LCh, and HSL gradient interpolation spaces

* Add a hue direction attribute and picker choice for polar gradient interpolation spaces

* Add an HSV gradient interpolation space

* Rename the sRGB Linear and sRGB Gamma gradient spaces to RGB Linear and RGB Gamma

* Divide the gradient interpolation dropdown between absolute and relative color spaces

* Rename the OkLch gradient interpolation space to OkLCh for channel-notation capitalization

* Shorten the color picker popover's hue direction row label to Arc

* Call the Gradient Interpolation node's parameter Space and extend the picker tooltip title to match

* Rename the gradient interpolation attribute and type family to gradient space

* Rename the gradient tool's gradient space transform to gradient to viewport transform

* Add serde aliases and a node replacement covering the gradient space renames

* Give the gradient space choices artist-facing labels and reorder the dropdown sections

* Add a Gradient Hue Direction node and its attribute read node

* Say interpolate instead of blend for gradient stop color traversal in docs and tooltips

* Label the polar perceptual gradient spaces as Perceptual Hue and group the dropdown sections by geometry

* Add a migration alias covering the gradient space attribute reader rename

* Carry the gradient hue direction attribute through boolean operations

* Register GradientHueDirection wire types in the node registry
2026-09-15 14:39:44 +02:00
Keavon Chambers 11436cfc80 Make gradient evaluation follow the ramp's interpolation space attribute (#4414) 2026-09-15 14:39:40 +02:00
Keavon Chambers a43b3eaa00 Give whole-expanse gradient layers a transform cage based on the gradient line (#4413) 2026-09-15 14:39:36 +02:00
Keavon Chambers a1dfe52b70 Add a gradient interpolation space attribute with sRGB Gamma (existing) and sRGB Linear (new) (#4412)
* Build dropdown menu entries from choice type metadata

* Add a gradient interpolation color space attribute, blending stops in linear light by default

* Add a Space interpolation dropdown to the color picker popover

* Stamp legacy gradient ramps with their implicit gamma interpolation during deserialization

* Resolve color-interpolation from SVG style blocks and fix cascade order among repeated declarations
2026-09-15 14:39:32 +02:00
Keavon Chambers 65ba494b14 Fix node shaking causing an offset from the pointer for the rest of the drag (#4411) 2026-09-15 14:39:28 +02:00
Keavon Chambers e54b348166 Add a Clear gradient spread that cuts off to transparency beyond the ends (#4410) 2026-09-15 14:39:24 +02:00
Keavon Chambers fb6a0f9460 Bind the Gradient tool's spread to the gradient value's ramp instead of a Gradient Spread node (#4409) 2026-09-15 14:39:20 +02:00
Keavon Chambers 93a1b1f456 Build radio widget entries from choice type metadata so variants display their icons (#4408)
* Build radio widget entries from choice type metadata so variants display their icons

* Route the node properties enum radio through the shared choice type entry builder
2026-09-15 14:39:16 +02:00
Keavon Chambers 8a93b47788 Let the Fill and Gradient tools paint blank layers with whole-expanse colors and gradients (#4407)
* Let the Gradient and Fill tools paint blank layers with whole-expanse gradients and colors

* Make it work on layers with un-fed Transform nodes

* Show the Fill tool's hover pattern over the whole expanse of layers painted by a color chain

* Let the Fill and Gradient tools replace one another's whole-expanse paint on a selected layer

* Keep a shared paint node alive when a tool takes over a layer, and share the paint value lookup

* Stop a chain node from being shifted twice when a node is inserted in front of it
2026-09-15 14:39:08 +02:00
Keavon Chambers b9a8065eb8 Rename gradient type to gradient form (#4405)
* Rename gradient type to gradient form

* Update the demo art for the gradient form rename

* Say form not type in the Gradient Form node's doc comment
2026-09-15 14:39:04 +02:00
Keavon Chambers d5e31c23bb Rename spread method to gradient spread so it matches the other gradient attribute names (#4404)
* Rename spread method to gradient spread so it matches the other gradient attribute names

* Keep the legacy gradient struct's spread method field name matching its on-disk key
2026-09-15 14:38:59 +02:00
Keavon Chambers 8d4f1346a1 Move the gradient-focused nodes from the Color category to a new Gradient category (#4403) 2026-09-15 14:38:53 +02:00
Keavon Chambers 26d67eb48b Move the gradient spread method into GradientRamp and the color picker popover (#4402)
* Add a spread method field to GradientRamp, carried at runtime as the gradient item's attribute

* Retire the Fill node's spread method input, folding its value into the gradient ramps on document upgrade

* Add an Ends spread method radio to the color picker popover, replacing the Gradient tool's control bar radio

* Update the demo art
2026-09-15 14:38:48 +02:00
Keavon Chambers 2196d308a7 Ban the null literal via ESLint and replace existing usages with undefined or truthiness checks (#4401) 2026-09-15 14:38:44 +02:00
Keavon Chambers 57c01ed413 Wrap serialized gradient stops in a new GradientRamp struct and unify FillChoice (#4400)
* Introduce the GradientRamp exchange struct as the serialized TaggedValue::Gradient payload

* Unify FillChoice and FillChoiceUI into one enum generic over color format, carrying GradientRamp stops

* Rename the TaggedValue::Gradient variant to GradientRamp to match its payload

* Move the Color variant into the tagged_value macro list since its stored and wire forms match
2026-09-15 14:38:39 +02:00
Keavon Chambers a0df7c2513 Add a drill-in button beside Data panel gradient preview widgets (#4398) 2026-09-15 14:38:34 +02:00
Keavon Chambers f6b4ce71e6 Rework Gradient into a newtype of List<Color> with optional position and midpoint attributes (#4397)
* Rework Gradient into a newtype of List<Color> with optional position and midpoint attributes

* Fix Vello stopless-gradient fallback coverage, empty legacy gradient tables, the node docs gradient swatch, NaN position elision, and wired setter input overwrites
2026-09-15 14:38:29 +02:00
Keavon Chambers 8504564f5d Remove custom (de)serializers from the DashPattern and BoxCorners TaggedValue variants (#4394)
Replace the DashPattern and BoxCorners custom serde impls with storage-shaped Vec<f64> TaggedValue payloads
2026-09-15 14:38:23 +02:00
Keavon Chambers bf217169f6 Replace raw node input indices with compile-time parameter symbols (#4387)
* Remove the dead InputAccessor traits and the uncallable test helper built on them

* Replace raw node input indices with macro-generated parameter symbols across the editor

* Audit dynamic input index usage, converting to parameter symbols and named input position constants

* Abstract the remaining input index plumbing behind ParameterRef APIs and accessors

* Build SetInputValue messages as struct literals to keep message enums impl-free

* Delete the typed parameter markers in favor of explicit-output test introspection

* Wire the interpolation control path input per chain node type

* Return no input when a parameter symbol is read against the wrong node's parameter view
2026-09-15 14:38:16 +02:00
Keavon Chambers 5af465ce36 Fix the math parser's implicit multiplication precedence and other regressions from the rewrite (#4383)
* Fix parsing regressions, make parsing 2.5x faster than the old pest parser, and clean up the math-parser rewrite

* Fix review findings: whitespace-juxtaposed numbers, mixed real/complex logic, correctly rounded literals, unified NaN truthiness, and gcd/lcm range checks
2026-09-15 14:38:05 +02:00
urisinger 860174c08e Move the math expression parser from Pest to Chumsky and add more features (#2685)
Rewrite the math-parser library using a chumsky-based lexer and parser, adding functions, comparisons, logic, and conditionals
2026-09-15 14:38:00 +02:00
Keavon Chambers c4da22f4a4 Add a Connect Cells option to the 'Grid' node (#4374)
Add a Connect Cells option to the Grid node
2026-09-15 14:37:53 +02:00
Keavon Chambers 804831a1ca Box big enum variants to satisfy Clippy's lint warnings (#4292)
* Box the `value` field of `NodeGraphMessage::SetInputValue`

* Box the `ExecutionResponse` variant of `NodeGraphUpdate`

* Box the `Layer` variant of `NodeTypeClickTargets`

* Box the `Scope` variant of `ParsedValueSource`
2026-09-15 14:37:48 +02:00
Keavon Chambers 76f0956c2c Deduplicate the network interface query helpers and collapse TransientMetadata into TransientCache (#4382)
* Route the remaining view queries through the logging query helper

* Name the cache readers by their loading contract and stop cloning the owned nodes per collision check

* Deduplicate the port center, output count, and upstream connector helpers and drop dead accessors

* Collapse the TransientMetadata enum into the Option inside TransientCache

* Extract the shared history snapshot install from undo and redo
2026-09-15 14:37:43 +02:00
Keavon Chambers 84bdc593ae Fix wrong-input disconnects, ghost wire caches, and partial import removal in the network interface (#4381)
* Remove commented-out code and fix stale names and doc comments

* Validate that the pinned node order only references existing nodes

* Abort remove_import before any mutation when the import's wires cannot be resolved

* Purge the deleted nodes' cached wire paths in delete_nodes

* Disconnect a deleted node's inputs by position so hidden inputs cannot mask a later exposed wire

* Gather the delete_nodes layer sweep only when deleting children needs it
2026-09-15 14:37:38 +02:00
Keavon Chambers 3d3ed7ab01 Move session state out of the network interface caches and replace the selection hijacks with explicit parameters (#4379)
* Move drag offsets out of the stack dependents cache into dedicated drag session state

* Replace the move_layer_to_stack selection hijack with a seeded stack dependents load

* Move text measurement into a neutral utility module out of the overlays layer

* Deduplicate the document bounds queries and name the artboard clip input index

* Replace the remove_references_from_network selection hijack with an explicit shift set

* Extract shared import and export wire disconnection used by the expose handlers

* Extract the shared epilogue of the import and export removal operations

* Move the post node lookup into the network interface to fix the layering inversion

* Clear drag offsets when the stack dependents cache unloads so programmatic shifts cannot replay them

* Use the thread-local text context for text measurement instead of a process-global mutex

* Resolve the post node lookup within the network being edited instead of the document root
2026-09-15 14:37:33 +02:00
Keavon Chambers f045b87daf Make the network interface's queries take &self instead of &mut self (#4378)
* Back the outward wires cache with an interior-mutability cell readable through &self

* Convert the remaining network-level caches to interior-mutability TransientCache cells

* Move the owned nodes cache out of persistent layer metadata into a transient cell

* Flatten the transient node type enum into a layer width cell with &self loading

* Back the per-node click targets cache with a TransientCache cell

* Unify the per-input and per-export wire caches into one connector-keyed map

* Flip the click target, position, and stack dependent load chains to &self

* Flip the bounding box, import export position, and port load chains to &self

* Flip the wire geometry and resolved type query families to &self

* Flip the hit testing and frontend click target surface to &self

* Flip the frontend assembly, clipboard copy, and chain validation queries to &self

* Load stack dependents before filtering layer-owned nodes out of a selected-nodes shift
2026-09-15 14:37:28 +02:00
Keavon Chambers 7ec885e7c7 Replace NodeTemplate's parallel node and metadata trees with a single flat recursive shape (#4377)
* Unify NodeTemplate into a single flat recursive shape with from_parts/into_parts as the storage split points

* Unify the three sole-dependent traversals onto one is_sole_dependent kernel

* Scan network exports for resource values when collecting used resources
2026-09-15 14:37:22 +02:00
Keavon Chambers 343969561e Introduce the NetworkView read cursor with typed errors and convert the network queries onto it (#4376)
* Introduce a NetworkView cursor with typed errors and convert the primitive queries to it

* Convert the composite name, selection, and eligibility queries onto NetworkView
2026-09-15 14:37:17 +02:00
Keavon Chambers 4e1426eb67 Make double-clicking a text layer begin editing in shallow select mode, not just deep select mode (#4373) 2026-09-15 14:37:12 +02:00
Keavon Chambers c616bd2238 Break apart the enormous network_interface.rs into submodules (#4371)
Split the network interface monolith into submodules with no behavior change
2026-09-15 14:37:06 +02:00
Keavon Chambers faa20bd041 Add additional tests to the network interface (#4370)
* Add a network interface invariant validator and characterization tests as a refactor safety net

* Characterize stack, chain, layer move, signature edit, and preview behaviors in tests

* Sweep network interface invariants after every message in editor tests
2026-09-15 14:36:58 +02:00
Keavon Chambers 3aad7ee8ae Fix assorted node graph correctness bugs and replace network interface panics with logged errors (#4364)
* Deselect deleted layer children by pruning the expanded deletion set from the selection

* Rebuild the document structure on redo to match undo

* Check for cycles in set_input before applying layout side effects rather than reverting after

* Correct the swapped old/new exposure binding names in set_input

* Reload the document structure when an import or export is appended into the first two slots

* Treat toggling preview on a disconnected export as a preview with nothing to restore

* Replace panics on malformed networks with logged errors in the network interface

* Make is_artboard an identity check independent of scene connectivity

* Stop serializing the selection undo and redo history into saved documents

* Run the set_input cycle check before the node-to-node disconnect so a rejected wire swap leaves the graph unchanged
2026-09-15 14:36:50 +02:00
Keavon Chambers fdadd9cc0d Improve number fields/labels in the UI to filter out floating point noise and truncate at correct precision (#4363)
* Improve the displayed precision of float number labels

* Show actual tiny values in high-precision number fields
2026-09-15 14:36:42 +02:00
Keavon Chambers 77f7e654e8 Make the 'Angle Between' node report the signed angle and fix its zero-vector output (#4362) 2026-09-15 14:36:33 +02:00
Keavon Chambers dfec7c9e4b New nodes: 'Sign', 'Distance', 'Cross Product', and 'Lerp' (#4361) 2026-09-15 14:36:28 +02:00
Keavon Chambers 7aec563210 Add Vec2 support to the scalar math operator nodes (#4360)
* Add Vec2 support to the scalar math operator nodes

* Support the scalar-with-Vec2 operand order in the Exponent, Root, Logarithm, Min, Max, and Clamp nodes

* Detect an f32 base of e in the Logarithm node despite inexact widening to f64
2026-09-15 14:36:18 +02:00
Keavon Chambers 7add2adea6 Fix the 'Divide' node dividing partially-zero Vec2 denominators and the 'Logarithm' node misdetecting base e (#4359) 2026-09-15 14:36:09 +02:00
Timon 4c911f6aa0 Desktop: Stop compiling the editor into the wasm wrapper (#4348)
* Make wasm wrapper not depend on editor on native

* Introduce pkg-native

* Fix tests

* Fix fmt

* Correct span and make cargo fmt work inside editor_commands block

* Review

* Fix lint
2026-09-15 14:35:57 +02:00
Keavon Chambers 4f49c000e8 Rename the nodes 'Length' -> 'Magnitude', 'Flatten Path' -> 'Combine Paths', 'Vec2 Value' -> 'Combine Vec2', and add a new 'Vec2 Value' node (#4349)
* Rename the node 'Length' -> 'Magnitude'

* Rename the node 'Flatten Path' -> 'Combine Paths'

* Replace the node 'Vec2 Value' with 'Combine Vec2' and add a new 'Vec2 Value' that's actually a vec2

* Update demo artwork
2026-09-15 14:35:48 +02:00
Keavon Chambers 9556904aed New nodes: 'Voronoi Cells', 'Tesselate', and 'Relax Points' (#4345) 2026-09-15 14:35:37 +02:00
Keavon ChambersandDennis Kobert 20eb5ccb8a New nodes: Sum, Average, Minimum, Maximum, Any, All (#4344)
Co-authored-by: Dennis Kobert <[email protected]>
2026-09-15 14:35:27 +02:00
Keavon ChambersandDennis Kobert 04d6c0d5cf Convert the node catalog to rank-polymorphic kernels, materialize stored values as ranked wires, and display wire rank in the graph
Co-authored-by:    Dennis Kobert <[email protected]>
2026-09-15 14:35:20 +02:00
Keavon Chambers 83cfd0225a Reshape the node catalog: rename the list access nodes, split Text to Vector, reinstate Upload Texture as a proto node, and delete the vestigial debug nodes 2026-09-15 14:35:15 +02:00
Keavon Chambers 194c3d0a72 Split Fill's optional transform into a has-transform toggle and add the DashPattern and BoxCorners value types 2026-09-15 14:35:10 +02:00
Keavon Chambers 8e233d3229 Add Graphic::None and store paint choices as plain color, gradient, and no-paint values 2026-09-15 14:35:04 +02:00
Keavon Chambers 9dd1e2bdf9 Rename GradientStops to Gradient and the legacy Gradient/Fill structs to LegacyGradient/LegacyFill 2026-09-15 14:34:59 +02:00
Dennis Kobert 149e1fc4e0 Carry eight dropped columns through flatten_graphic 2026-09-15 14:34:54 +02:00
Dennis Kobert d1f7db77ed Carry four dropped columns through the flatten path kernels 2026-09-15 14:34:49 +02:00
Dennis Kobert 4993a5f6d3 Give VectorRow a top lane and thread it through the walk recursion 2026-09-15 14:34:46 +02:00
Dennis Kobert 8918c43b08 Carry the boolean operation kernels through lane 0 map_element 2026-09-15 14:34:40 +02:00
Dennis Kobert d218e408fd Build a gathered subject's copy plan on collapse and reject an empty carry 2026-09-15 14:34:35 +02:00
Dennis Kobert d4dc2e9e6b Adopt map_element in the mirror kernels 2026-09-15 14:34:30 +02:00
Dennis Kobert c3755b3eb7 Adopt map_element in the assign colors kernels and drop the dead carried_lane_attrs helper 2026-09-15 14:34:25 +02:00
Dennis Kobert d04e94f549 Add a map_element primitive to Lane and teach the node macro to emit it 2026-09-15 14:34:20 +02:00
Dennis Kobert 362b54dafa Box the largest message and update payloads 2026-09-15 14:34:16 +02:00
Dennis Kobert 5356a9fe7e Sort key mappings and node positions by key 2026-09-15 14:34:10 +02:00
Dennis Kobert 71c15802d0 Drop redundant conversions, assertions and struct updates 2026-09-15 14:34:06 +02:00
Dennis Kobert c1704df0b3 Elide the arena lifetimes that the signatures do not need 2026-09-15 14:34:02 +02:00
Dennis Kobert 44f46c12b5 Name the crate cluster tuple as a type alias 2026-09-15 14:33:58 +02:00
Dennis Kobert 5e2398be74 Explain why the selective color and spline loops index by range 2026-09-15 14:33:54 +02:00
Dennis Kobert de93fa40fb Collapse nested conditionals into let-chains and match guards 2026-09-15 14:33:50 +02:00
Dennis Kobert 3bdec5d005 Fold attribute names through monitors and skip coercing name inputs 2026-09-15 14:33:45 +02:00
Dennis Kobert e6bbfe2ea1 Read a node's eval tail off its record work instead of a class label 2026-09-15 14:33:41 +02:00
Dennis Kobert 0a4e03beb9 Quantify a flip node's output bound over the lifetime it is served at 2026-09-15 14:33:36 +02:00
Dennis Kobert 2157ce700c Measure a node's level delta from its deepest layout source 2026-09-15 14:33:32 +02:00
Dennis Kobert 7fb55cf59f Name the shapes the record lowering refuses 2026-09-15 14:33:27 +02:00
Dennis Kobert 652c1c0e1b Row a reading input's element generic instead of erasing it 2026-09-15 14:33:20 +02:00
Dennis Kobert 781aef5f2e Name a type's live spelling beside its static one 2026-09-15 14:32:52 +02:00
Dennis KobertandClaude Fable 5 0a4288eca6 Read a named attribute at each value type it can hold
One read node per value type, mirroring master's read family. A name
means one value type, so there is no coercion between them: master's
number read silently widened integers, and these refuse instead, which
is the same rule the write side already enforces.

Each takes any record wire through the opaque reading input and serves
the name's own default where the attribute is absent, so the value
carries the declared type either way.

The gradient enums join the value-type rows now that a family exists to
read them at.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:36:00 +00:00
Dennis KobertandClaude Fable 5 5baeb8fd46 Accept any record wire on an input read only for its attributes
An element generic declared on a reading input, absent from the output
and from every other input, has nowhere to go and nothing to be: the
node reads its declared attributes and never the element. That is an
attr-to-element map, so it accepts any upstream record wire.

The blessing is inferred rather than marked, since the signature already
says it. The two substrate pieces were both in place: the element rides
as the byte-carried token, so the registry takes one generic row instead
of a row per element type, and the reads resolve against the input's own
layout as they always have. Only the passthrough rule stood in the way,
in the three places that enforced it.

A generic the output carries, or one on an input with no reads, is
unchanged and still owes an implementations list.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:15:40 +00:00
Dennis KobertandClaude Fable 5 f04d439b33 Name the attribute read for the type it reads
The read is a number read, not a read of whatever the name holds: our
model has no coercion, so a name written at another value type is a graph
error rather than a conversion. The name says so.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 11:35:38 +00:00
Dennis KobertandClaude Fable 5 6e22d6a412 Serve a declared name's census default on an absent read
An absent read of a name the census declares now serves that name's own
default rather than its value type's, which is the rule for a declared
name. The census stages it exactly as it fills any absent field, as the
declared default's bytes, so the read reuses the census's own mechanism
instead of a second one; the compiler takes them when the name folds and
`set_layout` installs them beside the offset.

A name the census does not declare keeps the value type's default, which
is that case's own rule. One name carries one value type, checked when
the name folds, so the row's value type and width agree with the read's.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 11:13:41 +00:00
Dennis KobertandClaude Fable 5 5eb80721dd Resolve a named read's offset when the graph compiles
The fold already holds the name and the read input's finished layout, so
the offset falls out there rather than at construction: `RecordLayout`
carries the resolved numbers and `set_layout` copies them into the read
slots. Constructors are untouched, and census-marker reads keep their
current installation.

A read meets the value type the name was written at, so a disagreement
between a read here and a write upstream is the same graph error as two
writes disagreeing; the one-name-one-type check now spans reads and
writes together. An absent attribute stays absent and the read serves
the forced default rather than reporting it.

`read_attribute` is the catalog's get half, typed and never `Option` at
the kernel boundary, with the name declared exactly as the write side
declares it.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 10:50:08 +00:00
Dennis KobertandClaude Fable 5 fc94487d0b Keep the name placeholder out of the kernel entirely
A name input declares where a placeholder's name is wired and nothing
more. The name is spent resolving the layout when the graph compiles, so
the kernel neither declares it nor is passed it; the return type's
`Named<X, V>` is the only tie between the write slot and the folded name.

The wire is untouched: the input keeps its declared position and crosses
as constant text, so a document's input order is unchanged. The
placeholder stays a concrete token, so it adds no generic for the node
to carry and none to go unconstrained.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 10:20:22 +00:00
Dennis KobertandClaude Fable 5 37c0d0852d Carry the new layout fields through the hand-built fixtures
The record fixtures spell their metas and resolved layouts out in full,
so the name-from-input fields reach them as empty. `named_value!`'s
example moves to `ignore`: its `for T` arm implements a core-types trait
on the value type, which only core-types itself may do.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 09:43:52 +00:00
Dennis KobertandClaude Fable 5 9b92edc0e9 Write an attribute under a name the graph supplies
`Named<X>` in parameter position declares where a placeholder's name is
wired, and the macro gives that input constant text; `Attr<Named<X, V>>`
in the return writes under it. The kernel is handed the bare placeholder,
since the name is spent resolving the layout and a folded offset is all
the write needs, so the hot path matches a marker node's exactly.

A name-generic write names its value type through the wired generic,
which only an implementations row resolves, so those nodes emit their
layout meta per row rather than sharing one across rows.

`write_attribute` is the catalog's set half, restoring the identifier
master's documents carry with its input positions. Its name input is a
constant, so those documents resolve without migration, and the reset
marker that stood in for the missing node retires with it.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 09:26:17 +00:00
Dennis KobertandClaude Fable 5 348e9022a6 Fold attribute names out of their constant inputs when the graph compiles
`compute_layouts` resolves every name-from-input write against the text
its name input carries, so a folded meta is indistinguishable from a
marker node's and the layout holds a `&'static str` from there on. That
leaves nowhere for a name to be computed, which is the whole of the
rule: a name input that is not a constant is refused right here, per
node, with the path the editor pins its diagnostic to.

One name carries one value type, checked across the census and the
names a node folds together, so no graph can declare one field at two
widths. `compute_layouts` returns those refusals rather than panicking.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 08:51:05 +00:00
Dennis KobertandClaude Fable 5 0001cdf04d Carry a name-generic attribute's value type as its own row
An attribute's name and its value type separate: `AttrValue` declares
everything `Attribute` does except the name and its name-specific
default, and `Named<X, V>` pairs one with a name the graph supplies.
The value type stays concrete in the signature while the name varies
per instance, so a computed name has nowhere to come from.

`LayoutMeta` gains the name-from-input variant the fold consumes: a
`FieldWrite` template with every facet minted from the concrete type
and only the name left as a placeholder, plus the input position the
name's constant sits at. `fold_name` resolves one, preferring the
census row's descriptor where the name is declared so a known name
keeps its census default. `RecordLayout` carries the folded names so
`set_layout` can resolve offsets without a marker's `NAME`.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 08:41:53 +00:00
Dennis Kobert c2845def11 Take rasterize's data input on the materialized leveled form 2026-09-08 20:19:18 +00:00
Dennis Kobert b8bd9499fc Pin the async source materialized input shape 2026-09-08 20:19:18 +00:00
Dennis Kobert e92ced1e4a Cross an async source's materialized input as an owned snapshot 2026-09-08 20:19:18 +00:00
Dennis Kobert e322d8957d Lift the run to owned legacy list bridge into core-types 2026-09-08 20:19:12 +00:00
Dennis Kobert 296185b7fc Register a record-io source whose generic sits on an implementations secondary 2026-09-08 15:23:33 +00:00
176 changed files with 13982 additions and 7192 deletions

No files matched your search

+9 -1
View File
@@ -1,6 +1,14 @@
# Keep `--cfg=web_sys_unstable_apis` here so the wasm wrapper crates build with the same web-sys API signatures (e.g. `put_image_data`/`get_image_data` taking `i32` rather than `f64`) on both native and the wasm target.
[target.'cfg(not(target_family = "wasm"))']
rustflags = ["--cfg=web_sys_unstable_apis"]
# Frame pointers keep the native build profileable: the record model puts ~1KB frames on the stack and
# recurses past a hundred of them, so a sampling profiler copying a fixed slice of stack unwinds a frame
# or two and reports every sample as its own root. This must live here rather than under `[build]`, which
# Cargo ignores whenever any `target.*` section matches.
# A build id is what a profiler matches a recorded module against when it goes looking for symbols;
# the linker here does not emit one on its own, and without it an imported profile is all addresses.
# It has to be the `uuid` style: perf stores a 20 byte id, and the other styles here produce 32 bytes,
# which perf truncates and the profiler then reads as a mismatch against the file it was told to use.
rustflags = ["--cfg=web_sys_unstable_apis", "-C", "force-frame-pointers=yes", "-C", "link-arg=-Wl,--build-id=uuid"]
[target.'cfg(target_family = "wasm")']
rustflags = [
Generated
+6 -1
View File
@@ -2143,12 +2143,17 @@ dependencies = [
"dyn-any",
"glam",
"graphene-hash",
"graphic-nodes",
"graphic-types",
"log",
"math-nodes",
"node-macro",
"rand",
"raster-types",
"repeat-nodes",
"serde",
"tsify",
"vector-types",
"wasm-bindgen",
]
@@ -2229,9 +2234,9 @@ dependencies = [
"core-types",
"dyn-any",
"glam",
"graphene-core",
"graphic-types",
"node-macro",
"rand",
"raster-types",
"serde",
"vector-types",
+146
View File
@@ -0,0 +1,146 @@
# Index-level narrowing: investigation state
Branch `brick-wave-investigation`. Why `~/Downloads/brick-waves.graphite` gets no caching around its
palette lookup, what we changed, and where it still breaks.
## The original problem
`read_index` takes its *Loop Level* as a runtime input, so its signature can only declare
`ExtractIndices` → `ContextFeature::ExtractIndex(u8::MAX)` → `IndexLevels::all()`.
A saturated mask is absorbing in both places it is consumed:
- `nullify_index_levels` (`core-types/src/context.rs:283`) early-returns on `is_all()`, so nothing is
nullified
- `IndexLevels::lifted` (`context.rs:253`) has `u32::MAX => self`, so propagation never narrows it
- `ContextModification::contains` therefore always succeeds, so `we_introduce_new_deps` is false and
**no cache boundary is ever inserted anywhere in the cone**
In `brick-waves` the whole palette chain (`StringValue → split → item_at_index → join → split →
item_at_index → join → hex_to_color`) sits under this, and re-derives per lane: 36864 evaluations
where 96 would do.
## What we built (all in the preprocessor, none of it node-specific in the compiler)
`node-graph/preprocessor/src/lib.rs`:
1. `restore_declared_context_features` — re-declares `extract`/`inject`/`index_levels` from the
registry. A document serializes `extract`/`inject` (so it can carry a declaration from an older
build) and `index_levels` is `#[serde(skip)]`, so the field was only ever trustworthy by accident.
2. `determine_index_reads` — when `loop_level` is a literal, narrows `index_levels` to
`{loop_level + 1}` (the kernel reads `nth(loop_level + 1)`).
3. `expand_network` — carries the wrapper's declaration onto the substituted proto node. Needed
because a substitution replaces `implementation` with a template network, and the declaration
would otherwise stay on the wrapper that `flatten` dissolves.
**Verified neutral**: with narrowing disabled (`LEVEL_MODE=off`) the render is byte-identical to
baseline (`md5 87fd5f79b006`). So 1 and 3 are sound on their own.
## What narrowing achieves, and how it breaks
Masks stop being saturated: precise `{1,2,3,4,6,7}` appear, boundaries go 82 → 109.
`read_index` itself is **correct** under narrowing — verified at runtime, not inferred:
| mode | chain seen | value | distinct chains |
|---|---|---|---|
| `LEVEL_MODE=only0` | `[0, 0, N, 0]` depth 4 | `nth(2) = N` | 36864 |
| narrowed | `[0, 0, N]` depth 3 | `nth(2) = N` | **96** |
Both return the full range 0..95. Nullification strips only the trailing zeroed level and the read
still lands on `N`. That is the 384× win we were after.
But `hex_to_color` receives **1 distinct hex string instead of 63**, and the render collapses from 65
colors to 3. So the correct values are lost *downstream* of `read_index`, in the string chain.
## Ruled out
- **Off-by-one in the declared level.** Declaring 2, 3, or 4 for the `loop_level=1` reader gives
byte-identical broken output. The mask *value* is irrelevant; only its non-saturation matters.
- **Keeping level 0 as well.** No change.
- **`InjectIndex` falsely discharging the requirement.** `ContextFeature::InjectIndex → INDEX` exists
(`context.rs:534`) but the macro never emits it (`parsing.rs:1041`), so `inject` never contains
`INDEX`. `new_deps &= !inject` never clears it and `we_supply_existing_deps` never fires for it.
The feature is never falsely discharged — only the *level* arithmetic discharges.
- **A node overstating `pushed_levels`.** `PROBE_LEVELS` dumps every lift. The only requirement
deaths are legitimate lane-drives (`ItemAtIndex` on `list`, `Fill` on its color inputs, …). The two
`Repeat`s consume exactly the two levels `read_index` declares: `{0,1,2} → {0,1} → {0}`. The
boundary mask follows correctly from the declarations.
- **The split/item/join level arithmetic alone.** See the repro below — it does not collapse.
Narrowing only the `loop_level=0` reader (`LEVEL_MODE=only0`) is byte-identical to baseline and adds
4 boundaries, but measures the same as `off` (10s vs 10s over 8 repeats, debug). No partial win to
bank; the payoff needs the outer-loop reader.
## Minimal reproduction (does NOT yet reproduce)
`proto::test::nested_index_lookup_boundary_levels` in `graph-craft/src/proto.rs`, with helpers
`nested_index_lookup_network` and `index_level_boundaries`.
Builds `split → item_at_index → join` twice against two resolved-level `read_index` nodes, plus two
more level-consuming hops standing in for the `Repeat`s. Masks come out `0, 2, 1, 0, 1, 0` — every
boundary keeps a level its subtree reads. **No collapse.**
It is committed as a *characterization* test, not a correctness assertion: an earlier assertion
("a boundary requiring INDEX must retain some level") passed for the wrong reason, because the real
failure is mask `{0}` above content that varies over deeper levels, not an empty mask. That invariant
can't be written until the intended semantics are settled.
## Leading hypothesis
The missing ingredient is the real `Repeat`. `string_join` only *consumes* a level; `Repeat` also
**injects an index at runtime**. That asymmetry is where the model's two jobs diverge:
`ContextModification` computes a cache key *and* rewrites the chain the subtree receives. "A `Repeat`
supplies this level, so the requirement vanishes above it" is sound for the **key** — nothing above
the `Repeat` varies over it — but the subtree below still evaluates against whatever chain survives.
`repeat-nodes` is not a `graph-craft` dependency, so a repro including it belongs in
`interpreted-executor`, asserting on evaluated values rather than masks.
## Env gates (all inert when unset)
| var | where | effect |
|---|---|---|
| `LEVEL_MODE=off` | preprocessor | disable narrowing → byte-identical to baseline |
| `LEVEL_MODE=only0` / `only1` | preprocessor | narrow only that `loop_level` |
| `LEVEL_BUMP=N` | preprocessor | add N to declared level for `loop_level >= 1` |
| `PROBE_LEVELS` | `proto.rs` | dump every `lifted` call that changes a mask |
| `PROBE_READ_INDEX` | `gcore/src/context.rs` | dump each newly seen chain + value |
| `PROBE_HEX` | `math/src/lib.rs` | dump distinct `hex_to_color` inputs |
**Narrowing is ON by default, so the tree renders wrong.** Use `LEVEL_MODE=only0` for a correct run.
Remove the probes and the `LEVEL_MODE`/`LEVEL_BUMP` block before this is fit to merge.
## Artwork
Committed under `test-artwork/`:
- `brick-waves-v3.graphite` — the migrated working copy. **Every measurement in this document used
this file**; it is the one known to reproduce.
- `brick-waves.graphite` — the original as saved from the editor. Kept so nothing is lost, but it
**does not load on this branch**:
```
GraphError { identifier: "graphic_nodes::graphic::ToGraphicNode", error: "No implementations found" }
```
It predates the rebase, so it needs a migration that does not exist here yet. Use the v3 copy.
## Repro commands
```sh
cargo build -p graphene-cli
ART=test-artwork/brick-waves-v3.graphite
# correct vs broken
LEVEL_MODE=only0 ./target/debug/graphene-cli export $ART -o ok.svg # 65 colors
./target/debug/graphene-cli export $ART -o bad.svg # 3 colors
grep -o 'fill="#[0-9a-f]*"' bad.svg | sort -u | wc -l
# where distinctness is lost
PROBE_READ_INDEX=1 ./target/debug/graphene-cli export $ART -o p.svg # read_index: correct, 96 values
PROBE_HEX=1 ./target/debug/graphene-cli export $ART -o h.svg # hex_to_color: 1 input, should be 63
# compile-time masks (note: -o /dev/null short-circuits evaluation, use a real file)
./target/debug/graphene-cli compile -p $ART | grep -o "index_levels: IndexLevels([0-9]*)" | sort | uniq -c
```
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":fLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::list::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false}],[1789832635968548900,{"inputs":[{"Node":{"node_id":1924303400883620400,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.9822506,"green":0.20507872,"blue":0.012983031,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.25,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[9.4105020317595,0.0,0.0,9.4105020317595,-5.928761491996683,27Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::list::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[183952488591282082,{"inputs":[{"Node":{"node_id":17965270694495451178,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,-6.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_noLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"raster_nodes::gradient_map::GradientMapNode"}},"visible":true,"skip_deduplication":false}],[4388711862172196665,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"U32":0},"exposed":false}},{"Value":{"tagged_value":{"F64":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"F64":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"U32":3},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"F64":0.5},"exposed":false}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"F64":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_value":{"CellularReturnType":"CellValue"},"exposed":false}},{"Value":{"tagged_value":{"F64":1.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::NoisePatternNode"}},"visible":true,"skip_deduplication":false}],[6565638614909771142,{"inputs":[{"Node":{"node_id":7Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"F64":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":1}},{"Import":{"import_type":{"Concrete":{"name":"f64"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"glam::f64::dvec2::DVec2"}},"import_index":4}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::artboard::Artboard>"}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Node":{"node_id":6,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":2}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":3}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":4}},{"Import":{"import_type":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":1,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":7,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementaLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"outLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<graphic_types::graphic::Graphic>"}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::list::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"F64":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"F64":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"F64":4000.0},"exposed":false}},{"Value":{"tagged_value":{"F64":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"core_types::vector::SplineNode"}},"visible":true,"skip_deduplication":false}],[7828034197076821310,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":3}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl<'_>"}},"implementation":{"ProtoNode":{"name":"math_nodes::AsU32Node"}},"visible":true,"skip_deduplication":false}],[11731553664207576737,{"inputs":[{"Node":{"node_id":14514477720912258595,"output_index":0}},{"Value":{"tagged_value":{"F64":48.900000000000006},"exposed":false}},{"Node":{"node_id":7828034197076821310,"output_index":0}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"namLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":6559102076450693000,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::list::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0]]},"regions":{"add":[],"remove":[],"segment_range":[],"fill":[]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"PrLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]],"stroke":[[1,0],[2,0],[3,0],[4,0],[5,0]]},"regions":{"add":[0],"remove":[],"segment_range":[[0,{"start":1,"end":5}]],"fill":[[0,0]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Concrete":{"name":"core_types::list::List<vector_types::vector::vector_types::Vector>"}},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::list::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::StampLayerPathNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphene_core::list::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[76,{"inputs":[{"Node":{"node_id":77,"output_index":0}},{"Node":{"node_id":16164610528699022118,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core_types::context::ContextImpl"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Node":{"node_id":2,"output_index":0}}],"call_argumenLine truncated
+4 -8
View File
@@ -493,15 +493,11 @@ mod test {
if let FrontendMessage::UpdateLayout {
layout_target: LayoutTarget::DialogColumn1,
diff,
} = response
} = response && let DiffUpdate::Layout(sub_layout) = &diff[0].new_value
&& let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0]
&& let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget
{
if let DiffUpdate::Layout(sub_layout) = &diff[0].new_value {
if let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0] {
if let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget {
print_problem_to_terminal_on_failure(value);
}
}
}
print_problem_to_terminal_on_failure(value);
}
}
}
@@ -8,7 +8,5 @@ pub enum EventMessage {
CanvasTransformed,
ToolAbort,
SelectionChanged,
/// The document graph's nodes or wires changed, so state derived from the selection's chains may be stale
GraphChanged,
WorkingColorChanged,
}
@@ -247,20 +247,9 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
let mut vectors = Vec::new();
let mut resources = Vec::new();
for item in items {
// Pasted templates skip document migration, so stored types normalize here
match item {
ClipboardItem::Layer(mut entry) => {
for (_, template) in &mut entry.nodes {
template.normalize_stored_types();
}
layers.push(entry);
}
ClipboardItem::Nodes(mut nodes) => {
for (_, template) in &mut nodes {
template.normalize_stored_types();
}
node_groups.push(nodes);
}
ClipboardItem::Layer(entry) => layers.push(entry),
ClipboardItem::Nodes(nodes) => node_groups.push(nodes),
ClipboardItem::Vector(vector) => vectors.push(vector),
ClipboardItem::Resource(resource) => resources.push(resource),
}
@@ -465,7 +465,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
];
let (mut key_up, mut key_down, mut key_up_no_repeat, mut key_down_no_repeat, mut double_click, mut wheel_scroll, mut pointer_move, mut pointer_shake) = mappings;
let sort = |list: &mut KeyMappingEntries| list.0.sort_by(|a, b| b.modifiers.count_ones().cmp(&a.modifiers.count_ones()));
let sort = |list: &mut KeyMappingEntries| list.0.sort_by_key(|entry| std::cmp::Reverse(entry.modifiers.count_ones()));
// Sort the sublists of `key_up`, `key_down`, `key_up_no_repeat`, and `key_down_no_repeat`
for list in [&mut key_up, &mut key_down, &mut key_up_no_repeat, &mut key_down_no_repeat] {
for sublist in list {
@@ -12,7 +12,7 @@ use graphene_std::blending::BlendMode;
use graphene_std::color::SRGBA8;
use graphene_std::extract_xy::XY;
use graphene_std::gradient::Gradient;
use graphene_std::list::{Item, List, NodeIdPath};
use graphene_std::list::{Item, List};
use graphene_std::math::float_noise::round_away_float_noise;
use graphene_std::raster::{
CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, LuminanceCalculation, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute, SelectiveColorChoice,
@@ -22,14 +22,13 @@ use graphene_std::text::TextAlign;
use graphene_std::text_nodes::StringCapitalization;
use graphene_std::transform::{ReferencePoint, ScaleType};
use graphene_std::vector::misc::{
ArcType, BezierHandles, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns,
SpiralType,
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType,
};
use graphene_std::vector::style::{
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector};
use graphene_std::{Appearance, Artboard, Color, Cover, Coverage, Graphic};
use graphene_std::{Artboard, Color, Graphic};
use std::any::Any;
use std::sync::Arc;
@@ -196,15 +195,16 @@ macro_rules! generate_layout_downcast {
}
// TODO: We simply try all these types sequentially. Find a better strategy.
fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'static>, data: &mut LayoutData) -> Option<Vec<LayoutGroup>> {
// `NodeIdPath` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a
// `List<NodeId>` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a
// `List` where each item's NodeId resolves against the prefix made up of the items above it.
if let Some(path) = introspected_data.downcast_ref::<NodeIdPath>() {
return Some(table_node_id_path_layout_with_breadcrumb(&path.0, data));
}
// The path's bare list form, introspected off a leveled wire.
if let Some(list) = introspected_data.downcast_ref::<List<NodeId>>() {
return Some(table_node_id_path_layout_with_breadcrumb(list, data));
}
// The path's plain value form, produced by `path_of_subgraph` on leveled wires.
if let Some(path) = introspected_data.downcast_ref::<Vec<NodeId>>() {
let list: List<NodeId> = path.iter().copied().map(graphene_std::list::Item::new_from_element).collect();
return Some(table_node_id_path_layout_with_breadcrumb(&list, data));
}
generate_layout_downcast!(introspected_data, data, [
List<Artboard>,
List<Graphic>,
@@ -234,6 +234,7 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
List<StrokeJoin>,
List<StrokeAlign>,
List<StrokeCap>,
List<PaintOrder>,
List<MergeByDistanceAlgorithm>,
List<ExtrudeJoiningAlgorithm>,
List<PointSpacingType>,
@@ -280,15 +281,14 @@ fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'st
DAffine2,
BlendMode,
GradientForm,
GradientSpread,
GradientSpace,
GradientHueDirection,
GradientInterpolation,
GradientSpread,
DashPattern,
BoxCorners,
StrokeJoin,
StrokeAlign,
StrokeCap,
PaintOrder,
MergeByDistanceAlgorithm,
ExtrudeJoiningAlgorithm,
PointSpacingType,
@@ -497,15 +497,6 @@ impl TableItemLayout for Artboard<'_> {
}
}
impl TableItemLayout for graphene_std::brush::Stroke {
fn type_name() -> &'static str {
"Stroke"
}
fn identifier(&self) -> String {
format!("Stroke ({} {})", self.len(), if self.len() == 1 { "sample" } else { "samples" })
}
}
impl TableItemLayout for DashPattern {
fn type_name() -> &'static str {
"DashPattern"
@@ -526,45 +517,6 @@ impl TableItemLayout for DashPattern {
}
}
impl TableItemLayout for Appearance {
fn type_name() -> &'static str {
"Appearance"
}
fn identifier(&self) -> String {
"Appearance".to_string()
}
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.value_page(data)
}
// Label the spreadsheet's element button with the inner list's identifier, like Artboard
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
self.0.value_widgets(target, data)
}
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.0.layout_with_breadcrumb(data)
}
}
impl TableItemLayout for Coverage {
fn type_name() -> &'static str {
"Coverage"
}
fn identifier(&self) -> String {
"Coverage".to_string()
}
// The wrapping row already contributes the breadcrumb; the inner item supplies the next level
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.value_page(data)
}
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
self.0.value_widgets(target, data)
}
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.0.layout_with_breadcrumb(data)
}
}
impl TableItemLayout for BoxCorners {
fn type_name() -> &'static str {
"BoxCorners"
@@ -585,35 +537,23 @@ impl TableItemLayout for BoxCorners {
}
}
impl TableItemLayout for graphene_std::core_types::none::None {
fn type_name() -> &'static str {
"None"
}
fn identifier(&self) -> String {
"None".to_string()
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
label("None")
}
}
impl TableItemLayout for Graphic<'_> {
fn type_name() -> &'static str {
"Graphic"
}
fn identifier(&self) -> String {
// Our leaf variants hold the bare element, so they report the element's own identifier
match self {
Self::None => "None".to_string(),
Self::Stroke(_) => "Brush Stroke".to_string(),
Self::GraphicList(list) => list.identifier(),
Self::Vector(vector) => vector.identifier(),
Self::RasterCPU(raster) => raster.identifier(),
Self::RasterGPU(raster) => raster.identifier(),
Self::Color(color) => color.identifier(),
Self::Gradient(gradient) => gradient.identifier(),
Self::Text(text) => text.identifier(),
Self::Stroke(stroke) => stroke.identifier(),
Self::StrokeList(list) => list.identifier(),
Self::Vector(list) => list.identifier(),
Self::RasterCPU(list) => list.identifier(),
Self::RasterGPU(list) => list.identifier(),
Self::Color(list) => list.identifier(),
Self::Gradient(list) => list.identifier(),
Self::Text(list) => list.identifier(),
Self::Group(_) => "Group".to_string(),
Self::Segmented(_) => "Stack".to_string(),
}
}
// Don't put a breadcrumb for Graphic
@@ -622,16 +562,17 @@ impl TableItemLayout for Graphic<'_> {
}
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
match self {
Self::None => label("None"),
Self::Stroke(_) => label("Brush Stroke"),
Self::GraphicList(list) => list.layout_with_breadcrumb(data),
Self::Vector(vector) => vector.layout_with_breadcrumb(data),
Self::RasterCPU(raster) => raster.layout_with_breadcrumb(data),
Self::RasterGPU(raster) => raster.layout_with_breadcrumb(data),
Self::Color(color) => color.layout_with_breadcrumb(data),
Self::Gradient(gradient) => gradient.layout_with_breadcrumb(data),
Self::Text(text) => text.layout_with_breadcrumb(data),
Self::Stroke(stroke) => stroke.layout_with_breadcrumb(data),
Self::StrokeList(list) => list.layout_with_breadcrumb(data),
Self::Vector(list) => list.layout_with_breadcrumb(data),
Self::RasterCPU(list) => list.layout_with_breadcrumb(data),
Self::RasterGPU(list) => list.layout_with_breadcrumb(data),
Self::Color(list) => list.layout_with_breadcrumb(data),
Self::Gradient(list) => list.layout_with_breadcrumb(data),
Self::Text(list) => list.layout_with_breadcrumb(data),
Self::Group(_) => Vec::new(),
Self::Segmented(_) => Vec::new(),
}
}
}
@@ -662,6 +603,27 @@ impl TableItemLayout for Vector {
let mut table_rows = Vec::new();
match data.vector_table_tab {
VectorTableTab::Points => {
table_rows.push(column_headings(&["", "position"]));
table_rows.extend(self.point_domain.iter().map(|(id, position)| {
let position = DVec2::new(round_away_float_noise(position.x), round_away_float_noise(position.y));
vec![
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
TextLabel::new(format!("{position}")).narrow(true).widget_instance(),
]
}));
}
VectorTableTab::Segments => {
table_rows.push(column_headings(&["", "start_index", "end_index", "handles"]));
table_rows.extend(self.segment_domain.iter().map(|(id, start, end, handles)| {
vec![
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
TextLabel::new(format!("{start}")).narrow(true).widget_instance(),
TextLabel::new(format!("{end}")).narrow(true).widget_instance(),
TextLabel::new(format!("{handles:?}")).narrow(true).widget_instance(),
]
}));
}
VectorTableTab::Handles => {
table_rows.push(column_headings(&["", "colinear_manipulators[0]", "colinear_manipulators[1]"]));
table_rows.extend(self.colinear_manipulators.iter().enumerate().map(|(index, [a, b])| {
@@ -672,31 +634,6 @@ impl TableItemLayout for Vector {
]
}));
}
VectorTableTab::Points => {
table_rows.push(column_headings(&["", "position"]));
table_rows.extend(self.point_domain.iter().map(|(id, position)| {
vec![
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
TextLabel::new(format_dvec2(position)).narrow(true).widget_instance(),
]
}));
}
VectorTableTab::Segments => {
table_rows.push(column_headings(&["", "start_point", "end_point", "handles"]));
table_rows.extend(self.segment_domain.iter().map(|(id, start, end, handles)| {
let handles = match handles {
BezierHandles::Linear => "Linear".to_string(),
BezierHandles::Quadratic { handle } => format!("Quadratic — {}", format_dvec2(handle)),
BezierHandles::Cubic { handle_start, handle_end } => format!("Cubic — start: {}, end: {}", format_dvec2(handle_start), format_dvec2(handle_end)),
};
vec![
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
TextLabel::new(format!("Point {start}")).narrow(true).widget_instance(),
TextLabel::new(format!("Point {end}")).narrow(true).widget_instance(),
TextLabel::new(handles).narrow(true).widget_instance(),
]
}));
}
}
vec![LayoutGroup::row(table_tabs), LayoutGroup::table(table_rows, false)]
@@ -1016,7 +953,6 @@ macro_rules! impl_table_item_layout_for_choice_enum {
}
impl_table_item_layout_for_choice_enum!(
BlendMode,
Cover,
GradientForm,
GradientSpread,
GradientSpace,
@@ -1025,6 +961,7 @@ impl_table_item_layout_for_choice_enum!(
StrokeJoin,
StrokeAlign,
StrokeCap,
PaintOrder,
MergeByDistanceAlgorithm,
ExtrudeJoiningAlgorithm,
PointSpacingType,
@@ -1228,9 +1165,6 @@ macro_rules! known_item_types {
Raster<GPU>,
Graphic,
Artboard,
Appearance,
Coverage,
Cover,
DashPattern,
BoxCorners,
BlendMode,
@@ -1242,6 +1176,7 @@ macro_rules! known_item_types {
StrokeJoin,
StrokeAlign,
StrokeCap,
PaintOrder,
MergeByDistanceAlgorithm,
ExtrudeJoiningAlgorithm,
PointSpacingType,
@@ -1289,10 +1224,6 @@ fn display_value_override(any: &dyn Any) -> Option<String> {
/// element-column rendering and attribute-column rendering. Returns `None` for unrecognized
/// types so the caller can fall back to a debug-formatted [`TextLabel`].
fn dispatch_value_widgets(any: &dyn Any, target: PathStep, data: &LayoutData) -> Option<Vec<WidgetInstance>> {
// `NodeIdPath` (e.g. the `editor:layer_path` attribute) drills into its inner path list, matching `drilldown_attribute_layout`.
if let Some(path) = any.downcast_ref::<NodeIdPath>() {
return Some(path.0.value_widgets(target, data));
}
macro_rules! check {
( $($ty:ty),* $(,)? ) => {
$(
@@ -1346,13 +1277,13 @@ fn table_node_id_path_layout_with_breadcrumb(path: &List<NodeId>, data: &mut Lay
}
/// Type-dispatched recursion into an attribute value for the Data panel breadcrumb navigation.
/// Mirrors [`dispatch_value_widget`] but routes to [`TableItemLayout::layout_with_breadcrumb`].
/// Mirrors [`dispatch_value_widgets`] but routes to [`TableItemLayout::layout_with_breadcrumb`].
/// Returns `None` for unrecognized types.
fn drilldown_attribute_layout(any: &dyn Any, data: &mut LayoutData) -> Option<Vec<LayoutGroup>> {
// `NodeIdPath` is interpreted as a path (e.g. the `editor:layer_path` attribute), so each item's NodeId value
// resolves against the prefix made up of preceding items. Handled before the generic blanket impl.
if let Some(path) = any.downcast_ref::<NodeIdPath>() {
return Some(table_node_id_path_layout_with_breadcrumb(&path.0, data));
// `List<NodeId>` is interpreted as a path (e.g. the `editor:layer_path` attribute), so each item's NodeId value
// resolves against the prefix made up of preceding items. Handled before the generic `List<T>` blanket impl.
if let Some(path) = any.downcast_ref::<List<NodeId>>() {
return Some(table_node_id_path_layout_with_breadcrumb(path, data));
}
// The path's plain value form, the layer-path marker's owned shape.
if let Some(path) = any.downcast_ref::<Vec<NodeId>>() {
@@ -11,9 +11,8 @@ use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::prelude::*;
use glam::{DAffine2, IVec2};
use graph_craft::document::NodeId;
use graphene_std::Appearance;
use graphene_std::Color;
use graphene_std::Graphic;
use graphene_std::list::List;
use graphene_std::raster::BlendMode;
use graphene_std::raster::Image;
use graphene_std::transform::Footprint;
@@ -245,14 +244,10 @@ pub enum DocumentMessage {
vector_data: HashMap<NodeId, Arc<Vector>>,
},
// `Message` is only serialized at `editor_wrapper.rs`, and only inputs from JS pass through it.
// `UpdateFillAttributes`/`UpdateStrokeAttributes` are produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so they never reach that serialization point.
// `UpdateAppearanceAttributes` is produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so it never reaches that serialization point.
#[serde(skip)]
UpdateFillAttributes {
fill_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
},
#[serde(skip)]
UpdateStrokeAttributes {
stroke_attributes: HashMap<NodeId, Arc<List<Graphic<'static>>>>,
UpdateAppearanceAttributes {
appearance_attributes: HashMap<NodeId, Arc<Appearance>>,
},
Undo,
UngroupSelectedLayers,
@@ -35,7 +35,7 @@ use crate::node_graph_executor::NodeGraphExecutor;
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::application_io::wgpu_available;
use graph_craft::concrete;
use graph_craft::descriptor;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput, NodeNetwork, OldNodeNetwork};
use graphene_std::Cover;
@@ -1518,13 +1518,19 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
.collect();
self.network_interface.update_vector_data(layer_vector_data);
}
DocumentMessage::UpdateFillAttributes { fill_attributes } => {
let layer_fill_attributes = self.layer_keyed(fill_attributes);
self.network_interface.update_fill_attributes(layer_fill_attributes);
}
DocumentMessage::UpdateStrokeAttributes { stroke_attributes } => {
let layer_stroke_attributes = self.layer_keyed(stroke_attributes);
self.network_interface.update_stroke_attributes(layer_stroke_attributes);
DocumentMessage::UpdateAppearanceAttributes { appearance_attributes } => {
// Convert NodeId keys to LayerNodeIdentifier keys, filtering to only layers
let layer_appearance_attributes = appearance_attributes
.into_iter()
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id))
.filter_map(|(node_id, attrs)| {
self.network_interface.is_layer(&node_id, &[]).then(|| {
let layer = LayerNodeIdentifier::new(node_id, &self.network_interface);
(layer, attrs)
})
})
.collect();
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
}
DocumentMessage::Undo => {
if self.network_interface.transaction_status() != TransactionStatus::Finished {
@@ -1800,15 +1806,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
impl DocumentMessageHandler {
/// Rekeys a per-node attribute snapshot by layer, dropping nodes that are not layers.
fn layer_keyed<T>(&self, attributes: HashMap<NodeId, T>) -> HashMap<LayerNodeIdentifier, T> {
attributes
.into_iter()
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id))
.filter_map(|(node_id, attrs)| self.network_interface.is_layer(&node_id, &[]).then(|| (LayerNodeIdentifier::new(node_id, &self.network_interface), attrs)))
.collect()
}
/// Build a document handler from a `.gdd` working copy.
pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, name: String, path: Option<std::path::PathBuf>) -> Self {
let mut document = Self {
@@ -1904,8 +1901,8 @@ impl DocumentMessageHandler {
layer_click_targets.is_some_and(|targets| {
targets.iter().all(|target| match target.target_type() {
ClickTargetType::Path(path) => {
let mut path = path.clone();
ClickTargetType::Path(_) | ClickTargetType::Instance { .. } => {
let mut path = target.path_in_layer().map(|path| path.into_owned()).unwrap_or_default();
path.apply_affine(Affine::new(layer_transform.to_cols_array()));
bezpath_is_inside_bezpath(&path, &viewport_polygon, None, None)
}
@@ -2767,7 +2764,7 @@ impl DocumentMessageHandler {
}
let solidify_stroke_definition = document_node_definitions::resolve_proto_node_type(graphene_std::vector::solidify_stroke::IDENTIFIER).expect("Solidify Stroke node should exist");
let item_at_index_definition = document_node_definitions::resolve_proto_node_type(graphene_std::graphic::index_elements::IDENTIFIER).expect("Item at Index node should exist");
let item_at_index_definition = document_node_definitions::resolve_proto_node_type(graphene_std::list::item_at_index::IDENTIFIER).expect("Item at Index node should exist");
let mut resulting_layers: Vec<NodeId> = Vec::new();
@@ -2777,14 +2774,13 @@ impl DocumentMessageHandler {
continue;
}
let metadata = self.network_interface.document_metadata();
let fill_paint = metadata.layer_fill_attributes.get(&layer);
let stroke_paint = metadata.layer_stroke_attributes.get(&layer);
let appearance = self.network_interface.document_metadata().layer_appearance_attributes.get(&layer);
let has_fill = fill_paint.is_some_and(|paint| paint.element(0).is_some_and(|graphic| !graphic.is_guaranteed_fully_transparent()));
let has_fill = appearance.is_some_and(|appearance| appearance.has_painted_cover(Cover::Fill));
// A visible stroke needs both renderable geometry (non-zero weight) and paint that draws something
let has_stroke = stroke_paint.is_some_and(|paint| {
graphene_std::renderer::stroke_params(paint).has_renderable_stroke() && paint.element(0).is_some_and(|graphic| !graphic.is_guaranteed_fully_transparent())
let has_stroke = appearance.is_some_and(|appearance| {
appearance.first_coverage_of(Cover::Stroke).is_some_and(|coverage| coverage.stroke_params().has_renderable_stroke())
&& appearance.first_paint_of(Cover::Stroke).is_some_and(|paint| !paint.is_fully_transparent())
});
// No stroke means there's nothing to solidify. Fill-only layers are already in the desired form, so skip.
@@ -3804,7 +3800,7 @@ impl DocumentMessageHandler {
/// Create a network interface with a single export
fn default_document_network_interface() -> NodeNetworkInterface {
let mut network_interface = NodeNetworkInterface::default();
network_interface.add_export(TaggedValue::TypeDefault(graph_craft::descriptor!(graphene_std::list::List<graphene_std::Artboard>)), -1, "", &[]);
network_interface.add_export(TaggedValue::TypeDefault(descriptor!(graphene_std::list::List<graphene_std::Artboard>)), -1, "", &[]);
network_interface
}
@@ -3836,8 +3832,8 @@ fn quad_to_kurbo(quad: Quad) -> BezPath {
fn click_targets_to_kurbo<'a>(click_targets: impl Iterator<Item = &'a ClickTarget>, transform: DAffine2) -> BezPath {
let segments = click_targets
.filter_map(|target| if let ClickTargetType::Path(path) = target.target_type() { Some(path.segments()) } else { None })
.flatten()
.filter_map(|target| target.path_in_layer().map(|path| path.into_owned()))
.flat_map(|path| path.segments().collect::<Vec<_>>())
.map(|bezier| Affine::new(transform.to_cols_array()) * bezier);
BezPath::from_path_segments(segments)
}
@@ -4109,10 +4105,11 @@ mod document_message_handler_tests {
async fn get_layer_by_bounds(editor: &mut EditorTestUtils, min_x: f64, min_y: f64) -> Option<LayerNodeIdentifier> {
let document = editor.active_document();
for layer in document.metadata().all_layers() {
if let Some(bbox) = document.metadata().bounding_box_viewport(layer) {
if (bbox[0].x - min_x).abs() < 1. && (bbox[0].y - min_y).abs() < 1. {
return Some(layer);
}
if let Some(bbox) = document.metadata().bounding_box_viewport(layer)
&& (bbox[0].x - min_x).abs() < 1.
&& (bbox[0].y - min_y).abs() < 1.
{
return Some(layer);
}
}
None
@@ -4167,9 +4164,8 @@ mod document_message_handler_tests {
.await;
// The operation completed without crashing
// Verifying application still functions by performing another operation
// Verifying application still functions by performing another operation, which panics if the folder move left the editor broken
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
assert!(true, "Application didn't crash after folder move operation");
}
// Merging nodes whose output isn't wired downstream produces an encapsulating subnetwork with no exports.
@@ -4339,24 +4335,24 @@ mod document_message_handler_tests {
let instrumented = editor.eval_graph().await.unwrap();
// The emptiness guards keep these assertions honest: a wrong `Output` type on `grab_all_input` yields no records at all, which would otherwise pass without checking anything
// An empty stack base is never served: `Extend` maps no lane onto it, so the monitor records nothing rather than an empty list.
// A base that wrongly carried a phantom element would therefore show up as a recorded row, which this catches.
// The `news` guard below is what keeps both assertions honest, since a wrong `Output` type empties every record.
let base_lengths: Vec<usize> = instrumented
.grab_all_input::<graphene_std::graphic::extend::BaseInput, graphene_std::list::List<graphene_std::Graphic>>(&editor.runtime)
.grab_all_input::<graphene_std::list::extend::BaseInput, graphene_std::list::List<graphene_std::Graphic>>(&editor.runtime)
.map(|base| base.len())
.collect();
assert!(!base_lengths.is_empty(), "Instrumentation should have recorded at least one stack base");
assert!(base_lengths.iter().all(|&len| len == 0), "Every stack base should be empty, found lengths {base_lengths:?}");
let news: Vec<graphene_std::list::List<graphene_std::Graphic>> = instrumented
.grab_all_input::<graphene_std::graphic::extend::NewInput, graphene_std::list::List<graphene_std::Graphic>>(&editor.runtime)
.grab_all_input::<graphene_std::list::extend::NewInput, graphene_std::list::List<graphene_std::Graphic>>(&editor.runtime)
.collect();
assert!(!news.is_empty(), "Instrumentation should have recorded at least one stacked element list");
let phantom_count = news
.iter()
.flat_map(|new| new.iter_element_values())
// Our no-content graphic is an empty list rather than master's dedicated None variant
.filter(|graphic| graphic.is_empty())
.filter(|graphic| matches!(graphic, graphene_std::Graphic::None))
.count();
assert_eq!(phantom_count, 0, "No stacked element should be a phantom empty graphic");
assert_eq!(phantom_count, 0, "No stacked element should be a phantom None graphic");
}
}
@@ -91,7 +91,7 @@ pub enum GraphOperationMessage {
color: Option<Color>,
stroke: Stroke,
},
StrokeOrderSet {
StrokePaintOrderSet {
layer: LayerNodeIdentifier,
paint_order: PaintOrder,
},
@@ -1,17 +1,18 @@
use super::transform_utils;
use super::utility_types::{ModifyInputsContext, set_stroke_paint_order};
use super::utility_types::ModifyInputsContext;
use crate::consts::{LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP};
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{BLEND_PATH_INPUT_INDEX, DefinitionIdentifier, resolve_proto_node_type};
use crate::messages::portfolio::document::node_graph::document_node_definitions::{BLEND_PATH_INPUT_INDEX, resolve_proto_node_type};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, OutputConnector};
use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::concrete;
use graph_craft::descriptor;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::list::List;
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{Gradient, GradientForm, GradientSettings, GradientSpace, GradientSpread, GradientStop, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
@@ -132,15 +133,12 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
modify_inputs.stroke_set(color, stroke);
}
}
GraphOperationMessage::StrokeOrderSet { layer, paint_order } => {
let stroke_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
let Some(stroke_node_id) = ModifyInputsContext::locate_node_in_layer_chain(&stroke_reference, layer, network_interface) else {
return;
};
if set_stroke_paint_order(network_interface, &[], stroke_node_id, paint_order) {
GraphOperationMessage::StrokePaintOrderSet { layer, paint_order } => {
if let Some(stroke_node_id) = crate::messages::tool::common_functionality::graph_modification_utils::get_stroke_id(layer, network_interface)
&& super::utility_types::set_stroke_paint_order(network_interface, &[], stroke_node_id, paint_order)
{
responses.add(PropertiesPanelMessage::Refresh);
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SendGraph);
}
}
GraphOperationMessage::TransformChange {
@@ -252,7 +250,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
}
// Set the bottom input of the artboard back to artboard
let bottom_input = NodeInput::type_default(graph_craft::descriptor!(graphene_std::list::List<Artboard>), true);
let bottom_input = NodeInput::type_default(descriptor!(List<Artboard>), true);
network_interface.set_input(&InputConnector::primary_input(artboard_layer.to_node()), bottom_input, &[]);
} else {
// We have some non layers (e.g. just a rectangle node). We disconnect the bottom input and connect it to the left input.
@@ -260,7 +258,7 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
network_interface.set_input(&InputConnector::layer_secondary_input(artboard_layer.to_node()), primary_input, &[]);
// Set the bottom input of the artboard back to artboard
let bottom_input = NodeInput::type_default(graph_craft::descriptor!(graphene_std::list::List<Artboard>), true);
let bottom_input = NodeInput::type_default(descriptor!(List<Artboard>), true);
network_interface.set_input(&InputConnector::primary_input(artboard_layer.to_node()), bottom_input, &[]);
}
}
@@ -1071,81 +1069,6 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
mod tests {
use super::*;
#[tokio::test]
async fn stroke_order_set_reorders_the_fill_and_stroke_nodes() {
use crate::messages::tool::common_functionality::graph_modification_utils::get_stroke_paint_order;
use crate::test_utils::test_prelude::*;
use graphene_std::vector::style::PaintOrder;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
let document = editor.active_document();
let layer = document.metadata().all_layers().next().unwrap();
let paint_order = get_stroke_paint_order(layer, &document.network_interface);
assert_eq!(paint_order, PaintOrder::StrokeAbove, "a fresh shape should stroke above its fill");
editor
.handle_message(GraphOperationMessage::StrokeOrderSet {
layer,
paint_order: PaintOrder::StrokeBelow,
})
.await;
let paint_order = get_stroke_paint_order(layer, &editor.active_document().network_interface);
assert_eq!(paint_order, PaintOrder::StrokeBelow, "the rewrite should move the stroke downstream of the fill");
editor
.handle_message(GraphOperationMessage::StrokeOrderSet {
layer,
paint_order: PaintOrder::StrokeAbove,
})
.await;
let paint_order = get_stroke_paint_order(layer, &editor.active_document().network_interface);
assert_eq!(paint_order, PaintOrder::StrokeAbove, "the rewrite should move the stroke back upstream of the fill");
}
#[tokio::test]
async fn a_node_inserted_between_the_fill_and_stroke_makes_the_order_swap_inapplicable() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::tool::common_functionality::graph_modification_utils::stroke_paint_order_applicable;
use crate::test_utils::test_prelude::*;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
let layer = editor.active_document().metadata().all_layers().next().unwrap();
assert!(
stroke_paint_order_applicable(layer, &editor.active_document().network_interface),
"a fresh shape's adjacent Fill and Stroke pair should be swappable"
);
let stroke_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
let stroke_node_id = ModifyInputsContext::locate_node_in_layer_chain(&stroke_reference, layer, &editor.active_document().network_interface).unwrap();
let node_template = Box::new(resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER).unwrap().default_node_template());
let passthrough_node_id = NodeId::new();
editor
.handle_message(NodeGraphMessage::InsertNode {
node_id: passthrough_node_id,
node_template,
})
.await;
editor
.handle_message(NodeGraphMessage::InsertNodeBetween {
node_id: passthrough_node_id,
input_connector: InputConnector::node_at_index(stroke_node_id, 0),
insert_node_input_index: 0,
})
.await;
assert!(
!stroke_paint_order_applicable(layer, &editor.active_document().network_interface),
"a node between the pair should gray the order radio out"
);
}
#[test]
fn color_interpolation_resolves_per_gradient_with_inheritance_and_style_priority() {
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" color-interpolation="linearRGB">
@@ -3,7 +3,7 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions:
ARTBOARD_DIMENSIONS_INPUT_INDEX, ARTBOARD_LOCATION_INPUT_INDEX, DefinitionIdentifier, resolve_document_node_type, resolve_network_node_type, resolve_proto_node_type,
};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface};
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{
ReplaceablePaintChain, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, replaceable_paint_chain,
@@ -414,7 +414,7 @@ impl<'a> ModifyInputsContext<'a> {
// TODO: Allow the 'Path' node to operate on `List` data by utilizing the reference (index or ID?) for each item.
if node_definition.identifier == "Path" {
let layer_input_type = self.network_interface.input_type(&InputConnector::layer_secondary_input(output_layer.to_node()), &[]);
if layer_input_type.compiled_element_name().as_deref() == Some("Graphic") {
if layer_input_type.compiled_nested_type() == Some(&concrete!(List<Graphic>)) {
let Some(combine_paths_definition) = resolve_proto_node_type(graphene_std::vector_nodes::combine_paths::IDENTIFIER) else {
log::error!("Combine Paths does not exist in ModifyInputsContext::existing_node_id");
return None;
@@ -431,8 +431,7 @@ impl<'a> ModifyInputsContext<'a> {
}
pub fn fill_color_set(&mut self, color: Option<Color>) {
let existing_fill_node_id = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, false);
let Some(fill_node_id) = existing_fill_node_id.or_else(|| self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true)) else {
let Some(fill_node_id) = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
return;
};
let input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::PaintInput);
@@ -447,8 +446,7 @@ impl<'a> ModifyInputsContext<'a> {
}
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_form: GradientForm, settings: GradientSettings, transform: DAffine2) {
let existing_fill_node_id = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, false);
let Some(fill_node_id) = existing_fill_node_id.or_else(|| self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true)) else {
let Some(fill_node_id) = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true) else {
return;
};
let backup_input_connector = InputConnector::node(fill_node_id, graphene_std::vector::fill::BackupGradientInput);
@@ -646,7 +644,7 @@ impl<'a> ModifyInputsContext<'a> {
.nodes
.get(&node_id)
.and_then(|node| node.input(graphene_std::math_nodes::gradient_positions::PositionsInput));
if !current_input.is_some_and(|input| input.as_value().is_some()) {
if current_input.is_none_or(|input| input.as_value().is_none()) {
return;
}
@@ -670,7 +668,7 @@ impl<'a> ModifyInputsContext<'a> {
.nodes
.get(&node_id)
.and_then(|node| node.input(graphene_std::math_nodes::gradient_midpoints::MidpointsInput));
if !current_input.is_some_and(|input| input.as_value().is_some()) {
if current_input.is_none_or(|input| input.as_value().is_none()) {
return;
}
@@ -859,9 +857,6 @@ impl<'a> ModifyInputsContext<'a> {
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeJoin(stroke.join), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::MiterLimitInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
// Our stroke node keeps a paint order input rather than encoding the order by Fill/Stroke node adjacency, and master's `Stroke` no longer carries one to copy
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintOrder(Default::default()), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashPatternInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
@@ -999,15 +994,62 @@ impl<'a> ModifyInputsContext<'a> {
}
}
/// Sets the Stroke node's paint order input, which decides whether the stroke paints above or below the fill.
/// The wires feeding off a node's primary output.
fn primary_output_consumers(network_interface: &mut NodeNetworkInterface, network_path: &[NodeId], node_id: NodeId) -> Vec<InputConnector> {
network_interface
.outward_wires(network_path)
.and_then(|wires| wires.get(&OutputConnector::node(node_id, 0)).cloned())
.unwrap_or_default()
}
/// The fill wired directly to the stroke on either side, and whether the stroke currently paints above it.
/// The downstream node of the pair appends its cover last, so it paints on top.
pub fn adjacent_fill_of_stroke(network_interface: &mut NodeNetworkInterface, network_path: &[NodeId], stroke_node_id: NodeId) -> Option<(NodeId, bool)> {
let fill_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER);
let is_fill = |network_interface: &NodeNetworkInterface, node_id: &NodeId| network_interface.reference(node_id, network_path) == Some(fill_reference.clone());
let stroke_primary_source = match network_interface.input_from_connector(&InputConnector::node_at_index(stroke_node_id, 0), network_path) {
Some(NodeInput::Node { node_id, output_index: 0, .. }) => Some(*node_id),
_ => None,
};
if let Some(source) = stroke_primary_source.filter(|source| is_fill(network_interface, source)) {
return Some((source, true));
}
let consumers = primary_output_consumers(network_interface, network_path, stroke_node_id);
let fill_consumer = consumers.iter().find_map(|connector| match connector {
InputConnector::Node { node_id, input_index: 0 } if is_fill(network_interface, node_id) => Some(*node_id),
_ => None,
});
fill_consumer.map(|fill_node_id| (fill_node_id, false))
}
/// Swaps a chain's directly adjacent Stroke and Fill nodes when their order disagrees with the requested
/// paint order: both nodes append their cover, so the downstream one of the pair paints on top, following
/// the painter's algorithm. Without a fill wired directly to the stroke, nothing changes.
/// Returns whether the graph changed.
pub fn set_stroke_paint_order(network_interface: &mut NodeNetworkInterface, network_path: &[NodeId], stroke_node_id: NodeId, paint_order: PaintOrder) -> bool {
let connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintOrderInput);
if let Some(NodeInput::Value { tagged_value, .. }) = network_interface.input_from_connector(&connector, network_path)
&& **tagged_value == TaggedValue::PaintOrder(paint_order)
{
let Some((fill_node_id, currently_above)) = adjacent_fill_of_stroke(network_interface, network_path, stroke_node_id) else {
return false;
};
if (paint_order == PaintOrder::StrokeAbove) == currently_above {
return false;
}
network_interface.set_input(&connector, NodeInput::value(TaggedValue::PaintOrder(paint_order), false), network_path);
let (upstream, downstream) = if currently_above { (fill_node_id, stroke_node_id) } else { (stroke_node_id, fill_node_id) };
let Some(upstream_source) = network_interface.input_from_connector(&InputConnector::node_at_index(upstream, 0), network_path).cloned() else {
return false;
};
let downstream_consumers = primary_output_consumers(network_interface, network_path, downstream);
network_interface.set_input(&InputConnector::node_at_index(downstream, 0), upstream_source, network_path);
network_interface.set_input(&InputConnector::node_at_index(upstream, 0), NodeInput::node(downstream, 0), network_path);
for consumer in &downstream_consumers {
if matches!(consumer, InputConnector::Node { node_id, .. } if *node_id == upstream || *node_id == downstream) {
continue;
}
network_interface.set_input(consumer, NodeInput::node(upstream, 0), network_path);
}
true
}
@@ -13,8 +13,7 @@ use glam::DVec2;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::value::*;
use graph_craft::document::*;
use graph_craft::concrete;
use graph_craft::descriptor;
use graph_craft::{concrete, descriptor};
use graphene_std::extract_xy::XY;
use graphene_std::list::List;
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType, RedGreenBlueAlpha};
@@ -156,11 +155,12 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
// Primary (bottom) input type coercion
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 0)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::to_graphic::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, -3)),
implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, -2)),
..Default::default()
},
// Collection of the content into the layer's group; the wrap keeps the content level's element type for the legacy boundary
// Collection of the content into the layer's group; the group keeps
// the content level's element type for the legacy boundary.
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 1)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER),
@@ -171,7 +171,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
NodeTemplate {
inputs: vec![NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::path_of_subgraph::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, 1)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, 0)),
..Default::default()
},
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
@@ -193,8 +193,8 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
NodeTemplate {
call_argument: generic!(T),
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(4), 0)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -3)),
implementation: NodeTemplateImplementation::ProtoNode(list::extend::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)),
..Default::default()
},
]
@@ -262,14 +262,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(concrete!(List<Artboard>))), 0),
NodeInput::node(NodeId(3), 0),
],
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(list::extend::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
..Default::default()
},
// Content coercion into a graphic level, evaluated within the artboard's footprint
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 1)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::to_graphic::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-35, -3)),
..Default::default()
},
@@ -558,7 +558,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
// 5: Map
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphic::map::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(list::map::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(4), 0), NodeInput::node(NodeId(3), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, 0)),
..Default::default()
@@ -837,17 +837,17 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
// Node 1: extract_element at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::extract_element::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(list::item_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
..Default::default()
},
// Node 2: omit_element at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::F64(0.), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::omit_element::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(list::remove_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
..Default::default()
},
@@ -918,7 +918,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default()
}),
inputs: vec![
NodeInput::type_default(descriptor!(Vector), true),
NodeInput::type_default(descriptor!(List<Vector>), true),
NodeInput::value(TaggedValue::VectorModification(Default::default()), false),
],
input_metadata: vec![("Content", "TODO").into(), ("Modification", "TODO").into()],
@@ -1716,7 +1716,7 @@ mod test_type_constraints {
use crate::messages::portfolio::document::node_graph::utility_types::InputTypeConstraint;
use crate::messages::portfolio::document::utility_types::network_interface::{NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation};
use crate::test_utils::test_prelude::*;
use core_types::{Ctx, list::Item};
use core_types::Ctx;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::{Type, concrete, generic};
use node_macro;
@@ -1736,7 +1736,7 @@ mod test_type_constraints {
}
#[node_macro::node(category(""))]
fn test_node_accept_f32_f64_dvec2<T: std::any::Any>(_: impl Ctx, #[implementations(f32, f64, DVec2)] a: Item<T>, _b: Item<bool>) -> Item<T> {
fn test_node_accept_f32_f64_dvec2<T: std::any::Any>(_: impl Ctx, #[implementations(f32, f64, DVec2)] a: T, _b: bool) -> T {
a
}
@@ -1750,7 +1750,7 @@ mod test_type_constraints {
}
#[node_macro::node(category(""))]
fn test_node_accept_f32_f64_string<T: std::any::Any>(_: impl Ctx, #[implementations(f32, f64, String)] a: Item<T>, _b: Item<bool>) -> Item<T> {
fn test_node_accept_f32_f64_string<T: std::any::Any>(_: impl Ctx, #[implementations(f32, f64, String)] a: T, _b: bool) -> T {
a
}
@@ -73,7 +73,6 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
inputs,
call_argument: input_type.clone(),
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
// Context features are resolved from the registry at compile time, not persisted on the node
context_features: ContextDependencies::default(),
// TODO: Store information for input overrides in the node macro
input_metadata: fields
@@ -157,6 +157,7 @@ pub enum NodeGraphMessage {
SetInputValue {
node_id: NodeId,
input_index: usize,
// Boxed to keep the whole editor message tree small; `TaggedValue` alone is 568 bytes
value: Box<TaggedValue>,
},
SetInput {
@@ -1734,7 +1734,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
responses.add(NodeGraphMessage::UpdateLayerPanel);
responses.add(DocumentMessage::DocumentStructureChanged);
responses.add(PropertiesPanelMessage::Refresh);
responses.add(EventMessage::GraphChanged);
if breadcrumb_network_path == selection_network_path && graph_view_overlay_open {
let nodes = self.collect_nodes(network_interface, breadcrumb_network_path);
self.frontend_nodes = nodes.iter().map(|node| node.id).collect();
@@ -1758,6 +1757,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
NodeGraphMessage::SetInputValue { node_id, input_index, value } => {
use graphene_std::vector::generator_nodes::*;
let value = *value;
let reference = network_interface.reference(&node_id, selection_network_path);
let is_text_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER));
let is_stroke_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER));
@@ -1769,7 +1769,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
.any(|id| *r == DefinitionIdentifier::ProtoNode(id))
});
let input = NodeInput::value(*value, false);
let input = NodeInput::value(value, false);
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node_at_index(node_id, input_index),
input,
@@ -57,7 +57,7 @@ fn optionally_update_value_at_index<T>(value: impl Fn(&T) -> Option<TaggedValue>
Some(value) => NodeGraphMessage::SetInputValue {
node_id,
input_index,
value: value.into(),
value: Box::new(value),
}
.into(),
None => Message::NoOp,
@@ -228,24 +228,6 @@ pub(crate) fn property_from_type(
let default_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
// A type with no widget can only be supplied through the graph, labeled with a placeholder row
let unsupported_widgets = |default_info: ParameterWidgetsInfo, type_label: String| {
let is_exposed = default_info.is_exposed();
let mut widgets = start_widgets(&default_info);
if !is_exposed {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextLabel::new("-")
.tooltip_label(type_label)
.tooltip_description("This data can only be supplied through the node graph because no widget exists for its type.")
.widget_instance(),
]);
}
vec![LayoutGroup::from(widgets)]
};
let mut extra_widgets = vec![];
let widgets = match ty {
Type::Concrete(concrete_type) => {
@@ -277,17 +259,22 @@ pub(crate) fn property_from_type(
// ===============
// PRIMITIVE TYPES
// ===============
Some(x) if id_is::<f64>(x) || id_is::<f32>(x) => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if id_is::<u32>(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::from(u32::MAX))).into(),
Some(x) if id_is::<u64>(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
Some(x) if id_is::<String>(x) => text_widget(default_info).into(),
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", "", None, false),
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
// A leveled f64 arrives peeled to its element, so only a genuinely list-typed input reaches this arm
Some(x) if id_is::<List<f64>>(x) => array_of_number_widget(default_info, TextInput::default()).into(),
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if x == TypeId::of::<f64>() || x == TypeId::of::<f32>() => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if x == TypeId::of::<u32>() => number_widget(default_info, bounded(number_input.int(), 0., f64::from(u32::MAX))).into(),
Some(x) if x == TypeId::of::<u64>() => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(),
Some(x) if x == TypeId::of::<bool>() => bool_widget(default_info, CheckboxInput::default()).into(),
Some(x) if x == TypeId::of::<String>() => text_widget(default_info).into(),
Some(x) if x == TypeId::of::<DVec2>() => vec2_widget(default_info, "X", "Y", "", None, false),
Some(x) if x == TypeId::of::<DAffine2>() => transform_widget(default_info, &mut extra_widgets),
// ==========
// LIST TYPES
// ==========
Some(x) if x == TypeId::of::<List<f64>>() => array_of_number_widget(default_info, TextInput::default()).into(),
Some(x) if x == TypeId::of::<List<Color>>() => color_widget(default_info, ColorInput::default().allow_none(true)),
Some(x) if x == TypeId::of::<List<Gradient>>() => color_widget(default_info, ColorInput::default().allow_none(false)),
// Leveled wires type by their element; each element keeps its list form's widget.
Some(x) if x == TypeId::of::<Color>() => color_widget(default_info, ColorInput::default().allow_none(true)),
Some(x) if x == TypeId::of::<Gradient>() => color_widget(default_info, ColorInput::default().allow_none(false)),
// ============
// STRUCT TYPES
// ============
@@ -323,6 +310,7 @@ pub(crate) fn property_from_type(
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).property_row(),
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).property_row(),
Some(x) if id_is::<PaintOrder>(x) => enum_choice::<PaintOrder>().for_socket(default_info).property_row(),
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).property_row(),
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).property_row(),
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).property_row(),
@@ -338,7 +326,22 @@ pub(crate) fn property_from_type(
// =====
// OTHER
// =====
_ => return Err(unsupported_widgets(default_info, concrete_type.to_string())),
_ => {
let is_exposed = default_info.is_exposed();
let mut widgets = start_widgets(&default_info);
if !is_exposed {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextLabel::new("-")
.tooltip_label(concrete_type.to_string())
.tooltip_description("This data can only be supplied through the node graph because no widget exists for its type.")
.widget_instance(),
]);
}
return Err(vec![widgets.into()]);
}
}
}
}
@@ -837,7 +840,7 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
NodeGraphMessage::SetInputValue {
node_id,
input_index: graphene_std::text::text::FontInput::INDEX,
value: TaggedValue::Resource(resource_id).into(),
value: Box::new(TaggedValue::Resource(resource_id)),
}
.into(),
]),
@@ -1393,7 +1396,7 @@ fn build_shared_spectrum_section(node_id: NodeId, context: &mut NodePropertiesCo
NodeGraphMessage::SetInputValue {
node_id,
input_index,
value: TaggedValue::F32(percent.clamp(0., 100.) as f32).into(),
value: Box::new(TaggedValue::F32(percent.clamp(0., 100.) as f32)),
}
.into()
}
@@ -1549,7 +1552,7 @@ fn spectrum_slider_row(
NodeGraphMessage::SetInputValue {
node_id,
input_index,
value: TaggedValue::F32(position_to_value(new_position).clamp(value_min, value_max) as f32).into(),
value: Box::new(TaggedValue::F32(position_to_value(new_position).clamp(value_min, value_max) as f32)),
}
.into()
})
@@ -2081,13 +2084,13 @@ pub(crate) fn string_capitalization_properties(node_id: NodeId, context: &mut No
NodeGraphMessage::SetInputValue {
node_id,
input_index: UseJoinerInput::INDEX,
value: TaggedValue::Bool(true).into(),
value: Box::new(TaggedValue::Bool(true)),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: JoinerInput::INDEX,
value: TaggedValue::String(value.clone()).into(),
value: Box::new(TaggedValue::String(value.clone())),
}
.into(),
]),
@@ -2142,13 +2145,13 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
NodeGraphMessage::SetInputValue {
node_id,
input_index: IndividualCornerRadiiInput::INDEX,
value: TaggedValue::Bool(false).into(),
value: Box::new(TaggedValue::Bool(false)),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: CornerRadiusInput::INDEX,
value: TaggedValue::BoxCorners(vec![uniform_val]).into(),
value: Box::new(TaggedValue::BoxCorners(vec![uniform_val])),
}
.into(),
]),
@@ -2161,13 +2164,13 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
NodeGraphMessage::SetInputValue {
node_id,
input_index: IndividualCornerRadiiInput::INDEX,
value: TaggedValue::Bool(true).into(),
value: Box::new(TaggedValue::Bool(true)),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: CornerRadiusInput::INDEX,
value: TaggedValue::BoxCorners(corner_values.to_vec()).into(),
value: Box::new(TaggedValue::BoxCorners(corner_values.to_vec())),
}
.into(),
]),
@@ -2479,7 +2482,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
NodeGraphMessage::SetInputValue {
node_id,
input_index: BackupColorInput::INDEX,
value: TaggedValue::Color(color).into(),
value: Box::new(TaggedValue::Color(color)),
}
.into(),
);
@@ -2492,13 +2495,13 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
NodeGraphMessage::SetInputValue {
node_id,
input_index: PaintInput::INDEX,
value: TaggedValue::GradientRamp(ramp.clone()).into(),
value: Box::new(TaggedValue::GradientRamp(ramp.clone())),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: BackupGradientInput::INDEX,
value: TaggedValue::GradientRamp(ramp).into(),
value: Box::new(TaggedValue::GradientRamp(ramp)),
}
.into(),
]),
@@ -2574,13 +2577,13 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
NodeGraphMessage::SetInputValue {
node_id,
input_index: HasTransformInput::INDEX,
value: TaggedValue::Bool(true).into(),
value: Box::new(TaggedValue::Bool(true)),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: TransformInput::INDEX,
value: TaggedValue::DAffine2(new_transform).into(),
value: Box::new(TaggedValue::DAffine2(new_transform)),
}
.into(),
]),
@@ -2647,8 +2650,6 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
ParameterWidgetsInfo::new(node_id, MiterLimitInput, true, context),
NumberInput::default().min(0.).disabled(miter_limit_disabled),
);
// Our stroke node keeps a paint order input rather than encoding the order by Fill/Stroke node adjacency
let paint_order = enum_choice::<PaintOrder>().for_socket(ParameterWidgetsInfo::new(node_id, PaintOrderInput, true, context)).property_row();
let disabled_number_input = NumberInput::default().unit(" px").disabled(has_dash_lengths);
let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput, true, context), TextInput::default().centered(true));
let number_input = disabled_number_input;
@@ -2661,7 +2662,6 @@ pub fn stroke_properties(node_id: NodeId, context: &mut NodePropertiesContext) -
cap,
join,
LayoutGroup::row(miter_limit),
paint_order,
LayoutGroup::row(dash_lengths),
LayoutGroup::row(dash_offset),
]
@@ -1012,6 +1012,11 @@ impl OverlayContextInternal {
self.manipulator_anchor(transform.transform_point2(point.position), false, None);
}
ClickTargetType::Path(bezpath) => combined.extend(bezpath.elements().iter().copied()),
ClickTargetType::Instance { path, transform } => {
let mut placed = (**path).clone();
placed.apply_affine(Affine::new(transform.to_cols_array()));
combined.extend(placed.elements().iter().copied());
}
}
}
@@ -972,6 +972,11 @@ impl OverlayContext {
self.manipulator_anchor(transform.transform_point2(point.position), false, None);
}
ClickTargetType::Path(bezpath) => combined.extend(bezpath.elements().iter().copied()),
ClickTargetType::Instance { path, transform } => {
let mut placed = (**path).clone();
placed.apply_affine(Affine::new(transform.to_cols_array()));
combined.extend(placed.elements().iter().copied());
}
});
if !combined.is_empty() {
@@ -741,7 +741,7 @@ async fn none_fill_survives_document_reopen() {
.handle_message(NodeGraphMessage::SetInputValue {
node_id: fill_node_id,
input_index: graphene_std::vector::fill::PaintInput::INDEX,
value: graph_craft::document::value::TaggedValue::no_paint().into(),
value: Box::new(graph_craft::document::value::TaggedValue::no_paint()),
})
.await;
assert!(fill_paint_value(editor.active_document()).is_no_paint(), "the None pick should store as no_paint");
@@ -24,7 +24,9 @@ pub fn load_demo(file_name: &str) -> DocumentMessageHandler {
#[test]
#[ignore = "dev tool: set DEMO_OUT and run explicitly"]
fn migrate_demo_artwork_into_demo_out() {
use crate::messages::portfolio::document_migration::{document_migration_reset_node_definition, document_migration_string_preprocessing, document_migration_upgrades};
use crate::messages::portfolio::document_migration::{
document_migration_reset_layer_definitions, document_migration_reset_node_definition, document_migration_string_preprocessing, document_migration_upgrades,
};
let out_dir = std::env::var("DEMO_OUT").expect("set DEMO_OUT to the output directory");
for entry in std::fs::read_dir("../demo-artwork").unwrap() {
let path = entry.unwrap().path();
@@ -34,8 +36,9 @@ fn migrate_demo_artwork_into_demo_out() {
let content = std::fs::read_to_string(&path).unwrap();
let content = document_migration_string_preprocessing(content);
let reset = document_migration_reset_node_definition(&content);
let reset_layers = document_migration_reset_layer_definitions(&content);
let mut document = DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {}: {e:?}", path.display()));
document_migration_upgrades(&mut document, reset);
document_migration_upgrades(&mut document, reset, reset_layers);
let out = format!("{out_dir}/{}", path.file_name().unwrap().to_string_lossy());
std::fs::write(out, document.serialize_document()).unwrap();
}
@@ -6,8 +6,7 @@ use crate::messages::portfolio::document::utility_types::network_interface::Flow
use crate::messages::tool::common_functionality::graph_modification_utils;
use glam::{DAffine2, DVec2};
use graph_craft::document::NodeId;
use graphene_std::Graphic;
use graphene_std::list::List;
use graphene_std::Appearance;
use graphene_std::math::quad::Quad;
use graphene_std::transform::Footprint;
use graphene_std::vector::Vector;
@@ -41,12 +40,9 @@ pub struct DocumentMetadata {
/// Vector data keyed by layer ID, used as fallback when no Path node exists.
/// This provides accurate SegmentIds for layers without explicit Path nodes.
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Vector>>,
/// Per-layer `ATTR_FILL` attribute, exposed so message handlers can read paint
/// information that lives on the list.
pub layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>,
/// Per-layer `ATTR_STROKE` attribute, exposed so message handlers can read
/// stroke paint information that lives on the list.
pub layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>,
/// Per-layer resolved appearance snapshot, exposed so message handlers can
/// read the paint and stroke parameters that live on the coverage rows.
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
/// Transform from document space to viewport space.
pub document_to_viewport: DAffine2,
}
@@ -193,8 +189,8 @@ impl DocumentMetadata {
self.visual_targets(layer)?
.iter()
.filter_map(|click_target| match click_target.target_type() {
ClickTargetType::Path(path) => {
let mut transformed = path.clone();
ClickTargetType::Path(_) | ClickTargetType::Instance { .. } => {
let mut transformed = click_target.path_in_layer().map(|path| path.into_owned()).unwrap_or_default();
transformed.apply_affine(Affine::new(transform.to_cols_array()));
let control_box = transformed.control_box();
@@ -236,8 +232,11 @@ impl DocumentMetadata {
/// bounds for non-vector layers (groups, raster, text, color, gradient).
pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
if let Some(vector) = self.layer_vector_data.get(&layer) {
// The stroke geometry rides the stroke paint list's own attribute columns, the carrier that replaced the deleted `Vector::stroke`.
let stroke = self.layer_stroke_attributes.get(&layer).map(|paint| graphene_std::renderer::stroke_params(paint));
let stroke = self
.layer_appearance_attributes
.get(&layer)
.and_then(|appearance| appearance.first_coverage_of(graphene_std::Cover::Stroke))
.map(graphene_std::Coverage::stroke_params);
if let Some(bounds) = vector.stroke_inclusive_bounding_box_with_transform(self.transform_to_document(layer), stroke.as_ref()) {
return Some(bounds);
}
@@ -255,11 +254,8 @@ impl DocumentMetadata {
self.all_layers().filter_map(|layer| self.bounding_box_viewport(layer)).reduce(Quad::combine_bounds)
}
pub fn layer_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &BezPath> {
self.visual_targets(layer).unwrap_or(&[]).iter().filter_map(|target| match target.target_type() {
ClickTargetType::Path(path) => Some(path),
ClickTargetType::FreePoint(_) => None,
})
pub fn layer_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = std::borrow::Cow<'_, BezPath>> {
self.visual_targets(layer).unwrap_or(&[]).iter().filter_map(|target| target.path_in_layer())
}
pub fn layer_with_free_points_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &ClickTargetType> {
@@ -40,9 +40,6 @@ use graph_craft::Type;
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
use graphene_std::Graphic;
use graphene_std::list::List;
use graphene_std::ContextDependencies;
use graphene_std::math::quad::Quad;
use graphene_std::transform::Footprint;
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint};
@@ -228,7 +228,7 @@ impl NodeNetworkInterface {
})
.collect::<Vec<(NodeId, i32)>>();
node_ids_with_position.sort_unstable_by(|a, b| a.1.cmp(&b.1));
node_ids_with_position.sort_unstable_by_key(|entry| entry.1);
Some(node_ids_with_position.into_iter().map(|(node_id, _)| node_id).collect::<Vec<_>>())
}
@@ -650,7 +650,6 @@ impl NodeNetworkInterface {
node.call_argument = call_argument;
}
/// Lightweight version of `set_input` for bulk import operations.
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
/// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and
@@ -74,14 +74,9 @@ impl TypeSource {
}
}
/// The element type, so semantic type checks can be rank-agnostic.
pub fn compiled_element_type(&self) -> Option<&Type> {
self.compiled_nested_type()
}
/// The identifier name of [`Self::compiled_element_type`].
/// The element type's identifier name, so semantic type checks can be rank-agnostic.
pub fn compiled_element_name(&self) -> Option<String> {
Some(self.compiled_element_type()?.identifier_name())
Some(self.compiled_nested_type()?.identifier_name())
}
pub fn compiled_nested_type(&self) -> Option<&Type> {
@@ -188,13 +183,13 @@ impl NodeNetworkInterface {
}
let chain_type = self.input_type(&secondary_input, network_path);
match chain_type.compiled_element_type() {
match chain_type.compiled_nested_type() {
Some(element) => {
let Some(implementations) = NODE_REGISTRY.get(node) else {
log::error!("Proto node {node:?} not found in the node registry, in layer_chain_hosts_node");
return false;
};
implementations.iter().map(|entry| &entry.io).any(|node_io| node_io.inputs.first().is_some_and(|content| content.nested_type() == element))
implementations.iter().any(|entry| entry.io.inputs.first().is_some_and(|content| content.nested_type() == element))
}
None => !matches!(chain_type, TypeSource::Invalid),
}
@@ -186,13 +186,8 @@ impl NodeNetworkInterface {
self.document_metadata.layer_vector_data = new_layer_vector_data;
}
/// Update the per-layer `ATTR_FILL` snapshot.
pub fn update_fill_attributes(&mut self, new_layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>) {
self.document_metadata.layer_fill_attributes = new_layer_fill_attributes;
}
/// Update the per-layer `ATTR_STROKE` snapshot.
pub fn update_stroke_attributes(&mut self, new_layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic<'static>>>>) {
self.document_metadata.layer_stroke_attributes = new_layer_stroke_attributes;
/// Update the per-layer resolved appearance snapshot.
pub fn update_appearance_attributes(&mut self, new_layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<graphene_std::Appearance>>) {
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
}
}
@@ -2,6 +2,7 @@ use super::*;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::concrete;
use graphene_std::Context;
use graphene_std::ContextDependencies;
// PartialEq required by message handlers
/// All persistent editor and Graphene data for a node, unified into a single flat shape.
@@ -217,13 +218,6 @@ impl NodeTemplate {
}
}
}
/// Normalizes the stored types at every nesting level via [`DocumentNode::normalize_stored_types`], round-tripping through the split halves to reuse its logic.
pub fn normalize_stored_types(&mut self) {
let (mut document_node, persistent_node_metadata) = std::mem::take(self).into_parts();
document_node.normalize_stored_types();
*self = NodeTemplate::from_parts(document_node, persistent_node_metadata);
}
}
impl NodeTemplateImplementation {
@@ -1,19 +1,19 @@
// TODO: Eventually remove this document upgrade code
// This file contains lots of hacky code for upgrading old documents to the new format
use crate::messages::portfolio::document::graph_operation::utility_types::set_stroke_paint_order;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_network_node_type, resolve_proto_node_type};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeTemplate, NodeTemplateImplementation, OutputConnector};
use crate::messages::prelude::DocumentMessageHandler;
use glam::{DVec2, IVec2};
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
use graph_craft::descriptor;
use graph_craft::document::DocumentNode;
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
use graph_craft::{Type, concrete, descriptor};
use graphene_std::Color;
use graphene_std::ParameterRef;
use graphene_std::ProtoNodeIdentifier;
use graphene_std::list::List;
use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::transform::ScaleType;
use graphene_std::uuid::NodeId;
@@ -132,8 +132,12 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
],
},
NodeReplacement {
node: graphene_std::graphic::extend::IDENTIFIER,
aliases: &["graphene_core::graphic::graphic::ExtendNode", "graphene_core::graphic::ExtendNode"],
node: graphene_std::list::extend::IDENTIFIER,
aliases: &[
"graphene_core::graphic::graphic::ExtendNode",
"graphene_core::graphic::ExtendNode",
"graphic_nodes::graphic::ExtendNode",
],
},
NodeReplacement {
node: graphene_std::graphic::flatten_graphic::IDENTIFIER,
@@ -148,21 +152,35 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
aliases: &["graphene_core::graphic::FlattenVectorNode", "graphene_core::graphic_element::FlattenVectorNode"],
},
NodeReplacement {
node: graphene_std::graphic::index_elements::IDENTIFIER,
node: graphene_std::list::item_at_index::IDENTIFIER,
aliases: &[
"graphene_core::graphic_element::IndexNode",
"graphene_core::graphic::IndexNode",
"graphene_core::graphic::IndexElementsNode",
"graphic_nodes::graphic::IndexElementsNode",
"graphic_nodes::graphic::ExtractElementNode",
"graphic_nodes::graphic::ItemAtIndexNode",
],
},
NodeReplacement {
node: graphene_std::graphic::omit_element::IDENTIFIER,
aliases: &["graphic_nodes::graphic::OmitElementNode"],
node: graphene_std::graphic::read_gradient_spread_attribute::IDENTIFIER,
aliases: &["graphic_nodes::graphic::ReadAttributeSpreadMethodNode", "graphic_nodes::graphic::ReadSpreadMethodAttributeNode"],
},
NodeReplacement {
node: graphene_std::graphic::legacy_layer_extend::IDENTIFIER,
node: graphene_std::graphic::read_gradient_space_attribute::IDENTIFIER,
aliases: &[
"graphic_nodes::graphic::ReadAttributeGradientInterpolationNode",
"graphic_nodes::graphic::ReadGradientInterpolationAttributeNode",
],
},
NodeReplacement {
node: graphene_std::list::remove_at_index::IDENTIFIER,
aliases: &["graphic_nodes::graphic::OmitElementNode", "graphic_nodes::graphic::RemoveAtIndexNode"],
},
// The legacy layer extend no longer exists as a node; the aliases still land on its identifier so the
// subgraph rebuild below recognizes and replaces the networks that carried it.
NodeReplacement {
node: ProtoNodeIdentifier::new("graphic_nodes::graphic::LegacyLayerExtendNode"),
aliases: &[
"graphene_core::graphic_element::LayerNode",
"graphene_core::graphic_types::LayerNode",
@@ -847,9 +865,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::context::read_index::IDENTIFIER,
aliases: &["graphene_core::vector::InstanceIndexNode", "core_types::vector::InstanceIndexNode"],
},
// The string map folded into the general Map, and its reader into the vararg readers.
NodeReplacement {
node: graphene_std::graphic::map::IDENTIFIER,
aliases: &["graphene_core::vector::InstanceMapNode"],
node: graphene_std::list::map::IDENTIFIER,
aliases: &["graphene_core::vector::InstanceMapNode", "text_nodes::MapStringNode", "graphic_nodes::graphic::MapNode"],
},
NodeReplacement {
node: graphene_std::context::read_position::IDENTIFIER,
@@ -859,6 +878,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::context::read_vector::IDENTIFIER,
aliases: &["graphene_core::vector::InstanceVectorNode"],
},
NodeReplacement {
node: graphene_std::context::read_string::IDENTIFIER,
aliases: &["text_nodes::ReadStringNode"],
},
NodeReplacement {
node: graphene_std::repeat::repeat::IDENTIFIER,
aliases: &["graphene_core::vector::InstanceRepeatNode", "core_types::vector::InstanceRepeatNode"],
@@ -1050,16 +1073,24 @@ pub fn document_migration_reset_node_definition(document_serialized_content: &st
return true;
}
// Every Merge layer network is built from the two nodes that became "As Graphic" and "Into Group", so their definitions
// are reset to pick up the current plumbing instead of the alias migration meant for standalone copies of those nodes.
if into_group_aliases().any(|alias| document_serialized_content.contains(alias)) {
return true;
}
false
}
/// Whether the layer networks built from the coercion nodes that became "As Graphic" and "Into Group" need their definitions reset.
///
/// A document still naming either node by an alias stores the pre-split plumbing, which the alias migration alone would mangle:
/// it maps both names onto the reducer, leaving a reducer where the layer wants the assertion. Resetting those two layer
/// definitions installs the current plumbing instead. This stays narrower than a full
/// [`document_migration_reset_node_definition`], whose one-shot input reorderings would re-apply to documents already carrying them.
pub fn document_migration_reset_layer_definitions(document_serialized_content: &str) -> bool {
into_group_aliases().any(|alias| document_serialized_content.contains(alias))
}
/// The layer networks whose definitions [`document_migration_reset_layer_definitions`] resets.
fn is_coercion_layer_definition(reference: &DefinitionIdentifier) -> bool {
matches!(reference, DefinitionIdentifier::Network(name) if name == "Merge" || name == "Artboard")
}
pub fn document_migration_replace_resources_referenced_by_hash(document_serialized_content: String) -> (String, HashMap<ResourceHash, ResourceId>) {
fn collect_resources_referenced_by_hash(s: &str) -> HashMap<ResourceHash, Vec<Range<usize>>> {
let mut out: HashMap<ResourceHash, Vec<Range<usize>>> = HashMap::new();
@@ -1131,9 +1162,8 @@ pub fn document_migration_replace_resources_referenced_by_hash(document_serializ
(out, hash_to_id)
}
pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) {
pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool, reset_layer_definitions: bool) {
document.network_interface.migrate_path_modify_node();
document.network_interface.document_network_mut().normalize_stored_types();
let network = document.network_interface.document_network().clone();
@@ -1164,7 +1194,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
// The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present.
// Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths.
// This must run as a pre-pass before the recursive iteration below: replacing the outer Transform's network impl orphans its child paths, and the recursive iteration would log errors for those stale paths.
let transform_layers: Vec<(NodeId, Vec<NodeId>, usize)> = document
.network_interface
.document_network()
@@ -1231,7 +1261,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
// The "Image" wrapper network was replaced with the `image` proto node directly. Convert old `Network("Image")` instances to the proto node, forwarding the embedded image data so the `image` pass in `migrate_node` below turns it into a resource.
// Pre-pass for the same reason as the Brush and Transform migrations above: replacing the outer Image's network impl orphans its child paths.
// Pre-pass for the same reason as the Transform migration above: replacing the outer Image's network impl orphans its child paths.
let image_layers: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
@@ -1275,7 +1305,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
.map(|(node_id, node, path)| (*node_id, node.clone(), path))
.collect::<Vec<(NodeId, graph_craft::document::DocumentNode, Vec<NodeId>)>>();
for (node_id, node, network_path) in &nodes {
migrate_node(node_id, node, network_path, document, reset_node_definitions_on_open);
migrate_node(node_id, node, network_path, document, reset_node_definitions_on_open, reset_layer_definitions);
}
// The old geometry-producing "Text" node was split into the current "Text" (`String[]`) -> converter pair, which reuses the same proto
@@ -1393,12 +1423,21 @@ fn fold_gradient_spread_into_ramp_input(input: &NodeInput, gradient_spread: Grad
}
}
fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId], document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) -> Option<()> {
fn migrate_node(
node_id: &NodeId,
node: &DocumentNode,
network_path: &[NodeId],
document: &mut DocumentMessageHandler,
reset_node_definitions_on_open: bool,
reset_layer_definitions: bool,
) -> Option<()> {
// Must run before the reset block below: a node referencing a removed catalog entry would otherwise abort
// `migrate_node` via the `?` on `resolve_document_node_type`, preventing subsequent migration blocks from running.
migrate_removed_catalog_definitions(node_id, node, network_path, document);
if reset_node_definitions_on_open && let Some(reference) = document.network_interface.reference(node_id, network_path) {
if let Some(reference) = document.network_interface.reference(node_id, network_path)
&& (reset_node_definitions_on_open || (reset_layer_definitions && is_coercion_layer_definition(&reference)))
{
let node_definition = resolve_document_node_type(&reference)?;
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
@@ -1739,19 +1778,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 7;
}
// Master retired the stroke paint order input, encoding the order as coverage list position instead. Ours keeps the
// input and carries it LAST, so a master-era stroke node arrives one input short and is padded with the default order.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 9 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
for (index, input) in old_inputs.into_iter().enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 9), NodeInput::value(TaggedValue::PaintOrder(Default::default()), false), network_path);
}
// Fill split its `Option<DAffine2>` placement into a `_has_transform` bool immediately before the `_transform` matrix. The modern
// shape is also 7 inputs, so this era is identified by its `_spread_method` input at 5 or its optional transform at 6.
let is_pre_transform_split_fill = inputs_count == 7
@@ -1823,13 +1849,12 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 7;
}
// Upgrade Stroke node to reorder parameters and add "Align" and "Paint Order" (#2644)
// Upgrade Stroke node to reorder parameters and add "Align" (#2644), landing on the shape without the retired "Paint Order" input
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 8 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
let align_input = NodeInput::value(TaggedValue::StrokeAlign(StrokeAlign::Center), false);
let paint_order_input = NodeInput::value(TaggedValue::PaintOrder(PaintOrder::StrokeAbove), false);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
@@ -1838,15 +1863,54 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 4), old_inputs[5].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 5), old_inputs[6].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 6), old_inputs[7].clone(), network_path);
// Our stroke node keeps the paint order input, so the dash pair lands at 8 and 9
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 7), paint_order_input, network_path);
let dash_input = migrate_dash_input(&old_inputs[3]).unwrap_or_else(|| old_inputs[3].clone());
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 8), dash_input, network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 9), old_inputs[4].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 7), dash_input, network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 8), old_inputs[4].clone(), network_path);
inputs_count = 10;
inputs_count = 9;
}
// The Stroke node's "Paint Order" input was retired in favor of the relative order of the Fill and Stroke
// nodes in the chain, so the stored value becomes a topology rewrite that reorders the two nodes.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 10 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
// A wired paint order input cannot be evaluated statically, so it degrades to the default and leaves its source disconnected
let paint_order = match old_inputs.get(7).and_then(|input| input.as_value()) {
Some(&TaggedValue::PaintOrder(value)) => value,
_ => PaintOrder::StrokeAbove,
};
for (index, input) in old_inputs.iter().enumerate().take(7) {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
}
// A document old enough to still carry "Paint Order" also predates `DashPattern`, and the standalone dash
// conversion below reads the pre-migration node, where index 7 is still the paint order
let dash_input = migrate_dash_input(&old_inputs[8]).unwrap_or_else(|| old_inputs[8].clone());
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 7), dash_input, network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 8), old_inputs[9].clone(), network_path);
inputs_count = 9;
set_stroke_paint_order(&mut document.network_interface, network_path, *node_id, paint_order);
}
// The String Split node gained a unit primary so its level stands on its own rather than inheriting its
// subject's rank, which shifts its three original inputs one slot later
if reference == DefinitionIdentifier::ProtoNode(graphene_std::text_nodes::string_split::IDENTIFIER) && inputs_count == 3 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
for (index, input) in old_inputs.iter().enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index + 1), input.clone(), network_path);
}
inputs_count = 4;
}
// TODO: Eventually remove this document upgrade code
// A legacy "no color" on a plain color connector (`TaggedValue::no_paint()` restored by the deserializer) becomes a color,
// since only paint connectors keep the no-paint choice
{
@@ -1889,28 +1953,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
.set_input(&InputConnector::node(*node_id, graphene_std::vector::stroke::DashPatternInput), migrated, network_path);
}
// The stored no-paint sentinel was the `List<Graphic>` type default before the paint connectors ranked down to `Item<Graphic>`.
// This must run before the stale-List-default cleanup below, which would otherwise adopt the definition's default paint.
{
let legacy_no_paint = TaggedValue::TypeDefault(descriptor!(List<graphene_std::Graphic>));
let paint_parameters: &[ParameterRef] = &[graphene_std::vector::fill::PaintInput.into(), graphene_std::vector::stroke::PaintInput.into()];
for parameter in paint_parameters {
if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) {
continue;
}
let Some(NodeInput::Value { tagged_value, exposed }) = node.inputs.get(parameter.input_index) else {
continue;
};
if **tagged_value == legacy_no_paint {
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, parameter.input_index),
NodeInput::value(TaggedValue::no_paint(), *exposed),
network_path,
);
}
}
}
// The corner radius became the `BoxCorners` value type; convert any already-shaped rectangle that still stores a legacy corner input
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)
&& let Some(corner_input) = node.input(graphene_std::vector::generator_nodes::rectangle::CornerRadiusInput)
@@ -2711,7 +2753,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 0),
NodeInput::type_default(descriptor!(graphene_std::vector::Vector), true),
NodeInput::type_default(descriptor!(graphene_std::list::List<graphene_std::vector::Vector>), true),
network_path,
);
@@ -2761,7 +2803,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
.input_from_connector(&InputConnector::node_at_index(*node_id, index), network_path)
.is_some_and(|stored_input| match stored_input {
NodeInput::Value { tagged_value, .. } => match &**tagged_value {
// Our type defaults name their type rather than carrying a structural rank, so a list-carrying wire is recognized by its name.
TaggedValue::TypeDefault(stored_type) if stored_type.name.contains("list::List<") && !tagged_value.is_no_paint() => {
!matches!(definition_input, NodeInput::Value { tagged_value, .. } if matches!(&**tagged_value, TaggedValue::TypeDefault(definition_type) if definition_type == stored_type))
}
@@ -2900,15 +2941,11 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
if let Some(DefinitionIdentifier::Network(name)) = document.network_interface.reference(node_id, network_path)
&& name == "Upload Texture"
{
// Our `upload_texture` node belongs to the optional wgpu-executor crate rather than to platform_application_io, so the conversion only exists in a GPU build.
#[cfg(feature = "gpu")]
{
let mut node_template = resolve_proto_node_type(wgpu_executor::texture_conversion::upload_texture::IDENTIFIER)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
if let Some(content) = old_inputs.first() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), content.clone(), network_path);
}
let mut node_template = resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::IDENTIFIER)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
if let Some(content) = old_inputs.first() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), content.clone(), network_path);
}
}
@@ -2923,8 +2960,16 @@ mod tests {
#[test]
fn removed_definition_swap_targets_resolve() {
assert!(resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER).is_some());
#[cfg(feature = "gpu")]
assert!(resolve_proto_node_type(wgpu_executor::texture_conversion::upload_texture::IDENTIFIER).is_some());
assert!(resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::IDENTIFIER).is_some());
}
#[test]
fn a_written_attribute_no_longer_resets_the_layer_definitions() {
// The node resolves natively again, so a document carrying it keeps
// its own layer internals instead of rebuilding them.
assert!(!document_migration_reset_node_definition(
r#"{"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}}}"#
));
}
// Migrating a Merge network's coercion nodes by alias would leave a reducer in the primary slot, so every alias must reset instead
@@ -2934,10 +2979,15 @@ mod tests {
assert!(!aliases.is_empty(), "the reset is driven by these aliases, so losing them all would disable it unnoticed");
for alias in aliases {
let document = format!(r#""implementation":{{"ProtoNode":"{alias}"}}"#);
assert!(
document_migration_reset_node_definition(&format!(r#""implementation":{{"ProtoNode":"{alias}"}}"#)),
document_migration_reset_layer_definitions(&document),
"a document referencing `{alias}` should reset its layer definitions"
);
assert!(
!document_migration_reset_node_definition(&document),
"`{alias}` alone must not reset every definition, which would re-apply the one-shot input reorderings"
);
}
}
@@ -2985,7 +3035,7 @@ mod tests {
);
document.network_interface.set_input(&InputConnector::node_at_index(consumer_id, 0), NodeInput::node(text_id, 0), &[]);
document_migration_upgrades(&mut document, false);
document_migration_upgrades(&mut document, false, false);
let network = document.network_interface.document_network();
let text_node = network.nodes.get(&text_id).expect("the upgraded text node should keep its ID");
@@ -3028,15 +3078,6 @@ mod tests {
}
}
#[test]
fn a_written_attribute_no_longer_resets_the_layer_definitions() {
// The node resolves natively again, so a document carrying it keeps
// its own layer internals instead of rebuilding them.
assert!(!document_migration_reset_node_definition(
r#"{"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}}}"#
));
}
#[test]
fn test_no_duplicate_node_replacements() {
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
@@ -52,7 +52,7 @@ pub enum PortfolioMessage {
reopened: bool,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
gdd: Option<document_format::GddV1>,
gdd: Option<Box<document_format::GddV1>>,
},
DestroyAllDocuments,
EditorPreferences,
@@ -305,7 +305,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// Document was closed before its working copy finished mounting.
return;
};
document.set_storage(gdd);
document.set_storage(gdd.map(|gdd| *gdd));
if !reopened {
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
document.retire_storage_interaction();
@@ -853,6 +853,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
} => {
// Upgrade the document being opened to use fresh copies of all nodes
let reset_node_definitions_on_open = reset_node_definitions_on_open || document_migration_reset_node_definition(&document_serialized_content);
// Reinstall just the layer networks whose coercion nodes were split into "As Graphic" and "Into Group"
let reset_layer_definitions = document_migration_reset_layer_definitions(&document_serialized_content);
// Upgrade the document being opened with string replacements on the original JSON
let document_serialized_content = document_migration_string_preprocessing(document_serialized_content);
// Upgrade resources from being referend by hash to beeing referened by ID
@@ -903,7 +905,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
};
// Upgrade the document's nodes to be compatible with the latest version
document_migration_upgrades(&mut document, reset_node_definitions_on_open);
document_migration_upgrades(&mut document, reset_node_definitions_on_open, reset_layer_definitions);
// Load the document's embedded resources into the resource storage
std::mem::take(&mut document.resources.embedded).into_iter().for_each(|(hash, resource)| {
@@ -1939,7 +1941,7 @@ impl PortfolioMessageHandler {
Message::Portfolio(PortfolioMessage::DocumentStorageMounted {
document_id,
reopened,
gdd: Some(gdd),
gdd: Some(Box::new(gdd)),
})
};
future.into()
@@ -125,9 +125,6 @@ pub struct DrawingToolState {
pub miter_limit: Option<f64>,
/// Paint order from the selection. `None` = mixed.
pub paint_order: Option<PaintOrder>,
/// Whether any selected layer has a lone adjacent Fill/Stroke pair for the paint order to swap.
/// Stays true with an empty selection, where the radio still sets the default for new shapes.
pub paint_order_applicable: bool,
/// Dash lengths from the selection. `None` = mixed.
pub dash_lengths: Option<Vec<f64>>,
/// Dash offset from the selection. `None` = mixed.
@@ -153,7 +150,6 @@ impl DrawingToolState {
stroke_join: Some(StrokeJoin::default()),
miter_limit: Some(4.),
paint_order: Some(PaintOrder::default()),
paint_order_applicable: true,
dash_lengths: Some(Vec::new()),
dash_offset: Some(0.),
last_synced_selection: Vec::new(),
@@ -192,14 +188,12 @@ impl DrawingToolState {
transform: glam::DAffine2::IDENTITY,
};
responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke });
}
/// Queues the paint order rewrite for a freshly created `layer`. The order is the relative position of the
/// Stroke and Fill nodes in the chain, so this must run after both the stroke and fill have been applied.
pub fn apply_stroke_order_to_new_layer(&self, layer: LayerNodeIdentifier, responses: &mut VecDeque<Message>) {
let paint_order = self.paint_order.unwrap_or_default();
if paint_order != PaintOrder::default() {
responses.add(GraphOperationMessage::StrokeOrderSet { layer, paint_order });
// The paint order is the chain order of the Fill and Stroke nodes, so a below choice reorders the new pair
if self.paint_order.unwrap_or_default() == graphene_std::vector::style::PaintOrder::StrokeBelow {
responses.add(GraphOperationMessage::StrokePaintOrderSet {
layer,
paint_order: graphene_std::vector::style::PaintOrder::StrokeBelow,
});
}
}
}
@@ -316,23 +310,12 @@ pub fn sync_drawing_state(drawing: &mut DrawingToolState, natural_fill_enabled:
/// Reads the stroke proto-node inputs (align, cap, join, miter limit, paint order, dash lengths, dash offset) across the selection and updates
/// the matching fields on `drawing`. Each field becomes `None` (mixed) when selected strokes disagree. With no selection, fields are left as-is.
fn sync_stroke_options(drawing: &mut DrawingToolState, document: &DocumentMessageHandler) -> bool {
let layers = graph_modification_utils::paintable_selected_layers(document);
// The order radio only swaps a layer's lone adjacent Fill/Stroke pair, so it grays out when no selected
// layer has one; with nothing selected it still sets the default order for new shapes
let paint_order_applicable = layers.is_empty() || layers.iter().any(|&layer| graph_modification_utils::stroke_paint_order_applicable(layer, &document.network_interface));
let mut applicability_changed = false;
if drawing.paint_order_applicable != paint_order_applicable {
drawing.paint_order_applicable = paint_order_applicable;
applicability_changed = true;
}
let strokes: Vec<_> = layers
let strokes: Vec<_> = graph_modification_utils::paintable_selected_layers(document)
.into_iter()
.filter_map(|layer| graph_modification_utils::get_stroke_options(layer, &document.network_interface))
.collect();
if strokes.is_empty() {
return applicability_changed;
return false;
}
fn unanimous<T: PartialEq + Clone>(values: impl IntoIterator<Item = T>) -> Option<T> {
@@ -349,7 +332,7 @@ fn sync_stroke_options(drawing: &mut DrawingToolState, document: &DocumentMessag
let new_dash_lengths = unanimous(strokes.iter().map(|s| &s.dash_lengths)).cloned();
let new_dash_offset = unanimous(strokes.iter().map(|s| s.dash_offset));
let mut changed = applicability_changed;
let mut changed = false;
if drawing.stroke_align != new_align {
drawing.stroke_align = new_align;
@@ -68,6 +68,8 @@ impl SpiralTurns {
self.handle_state == SpiralTurnsState::Dragging
}
// Records one snapshot of the spiral's parameters; grouping them would only move the same fields into a struct
#[allow(clippy::too_many_arguments)]
pub fn store_initial_parameters(
&mut self,
layer: LayerNodeIdentifier,
@@ -4,12 +4,12 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeNetworkInterface, NodeTemplate, OutputConnector};
use crate::messages::prelude::*;
use glam::{DAffine2, DVec2};
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, NodeId, NodeInput};
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_std::Color;
use graphene_std::raster::BlendMode;
use graphene_std::raster_types::Image;
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::misc::ManipulatorPointId;
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
@@ -682,9 +682,22 @@ pub fn get_stroke_options(layer: LayerNodeIdentifier, network_interface: &NodeNe
Some(TaggedValue::F64(value)) => *value,
_ => 4.,
};
let paint_order = match parameters.value(stroke::PaintOrderInput) {
Some(TaggedValue::PaintOrder(value)) => *value,
_ => PaintOrder::default(),
// The paint order is the chain order of the Fill and Stroke nodes: the downstream one of an adjacent pair paints on top
let paint_order = {
let stroke_node_id = get_stroke_id(layer, network_interface);
let primary_source = |node_id: Option<NodeId>| {
node_id.and_then(|node_id| match network_interface.input_from_connector(&InputConnector::node_at_index(node_id, 0), &[]) {
Some(NodeInput::Node { node_id, output_index: 0, .. }) => Some(*node_id),
_ => None,
})
};
if primary_source(stroke_node_id).is_some_and(|source| Some(source) == get_fill_id(layer, network_interface)) {
PaintOrder::StrokeAbove
} else if primary_source(get_fill_id(layer, network_interface)).is_some_and(|source| Some(source) == stroke_node_id) {
PaintOrder::StrokeBelow
} else {
PaintOrder::default()
}
};
let dash_lengths = match parameters.value(stroke::DashPatternInput) {
Some(TaggedValue::DashPattern(lengths)) => lengths.clone(),
@@ -711,19 +724,6 @@ pub fn get_stroke_id(layer: LayerNodeIdentifier, network_interface: &NodeNetwork
NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER))
}
/// Whether the paint order can act on the layer: it rides the Stroke node's paint order input, so any layer with a Stroke node qualifies.
pub fn stroke_paint_order_applicable(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> bool {
get_stroke_id(layer, network_interface).is_some()
}
/// The paint order of a layer's stroke, read from the Stroke node's paint order input rather than from the chain topology.
pub fn get_stroke_paint_order(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> PaintOrder {
match NodeGraphLayer::new(layer, network_interface).parameter_value(graphene_std::vector::stroke::PaintOrderInput) {
Some(TaggedValue::PaintOrder(paint_order)) => *paint_order,
_ => PaintOrder::default(),
}
}
/// Writes the weight back to every selected non-artboard layer's stroke. Layers with an existing stroke just have their
/// `WeightInput` updated; layers without one get a fresh stroke node added (defaulting to a black stroke with the new
/// weight) only when the new weight is nonzero, so changing back to 0 doesn't keep adding empty strokes.
@@ -1111,7 +1111,9 @@ impl<'a> NodeGraphLayer<'a> {
pub fn is_raster_layer(layer: LayerNodeIdentifier, network_interface: &mut NodeNetworkInterface) -> bool {
let layer_input_type = network_interface.input_type(&InputConnector::layer_secondary_input(layer.to_node()), &[]);
matches!(layer_input_type.compiled_element_name().as_deref(), Some("Raster<CPU>" | "Raster<GPU>"))
// A leveled wire is typed by its element; depth rides the layout.
let compiled = layer_input_type.compiled_nested_type();
compiled == Some(&concrete!(Raster<CPU>)) || compiled == Some(&concrete!(Raster<GPU>))
}
}
@@ -88,11 +88,8 @@ impl ShapeType {
}
pub fn tooltip_description(&self) -> String {
(match self {
// TODO: Add descriptions to all the shape tools
_ => "",
})
.into()
// TODO: Add descriptions to all the shape tools
String::new()
}
pub fn icon_name(&self) -> String {
@@ -677,7 +677,6 @@ mod tests {
down: [10., 15.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
left: [-12., -15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
right: [12., 15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
..Default::default()
};
let source = Rect::from_square(DVec2::new(0.3, 0.4), 2.);
let snap_results = &mut SnapResults::default();
@@ -734,7 +734,7 @@ pub fn get_layer_snap_points(layer: LayerNodeIdentifier, snap_data: &SnapData, p
if !snap_data.ignore_bounds(layer) {
let to_document = document.metadata().transform_to_document(layer);
for bezpath in document.metadata().layer_outline(layer) {
bezpath_anchor_snap_points(layer, bezpath, snap_data, points, to_document);
bezpath_anchor_snap_points(layer, &bezpath, snap_data, points, to_document);
}
}
@@ -64,9 +64,7 @@ where
if has_dash {
rows.push(LayoutGroup::row(dash_offset_row(drawing.dash_offset, to_message.clone())));
}
// An inapplicable order (no Fill/Stroke pair to reorder) grays out and highlights no entry, since the synced value is only a fallback
let paint_order = drawing.paint_order.filter(|_| drawing.paint_order_applicable);
rows.push(LayoutGroup::row(enum_radio_row::<PaintOrder, _>("Order", paint_order, !drawing.paint_order_applicable, {
rows.push(LayoutGroup::row(enum_radio_row::<PaintOrder, _>("Order", drawing.paint_order, false, {
let to_message = to_message.clone();
move |value| to_message(StrokeOptionsUpdate::PaintOrder(value))
})));
@@ -200,11 +198,9 @@ pub fn apply_miter_limit(drawing: &mut DrawingToolState, limit: f64, document: &
pub fn apply_paint_order(drawing: &mut DrawingToolState, order: PaintOrder, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
drawing.paint_order = Some(order);
// A mixed selection only grays the radio out when no layer can take the swap, so skip the ones that can't
for layer in graph_modification_utils::paintable_selected_layers(document) {
if graph_modification_utils::stroke_paint_order_applicable(layer, &document.network_interface) {
responses.add(GraphOperationMessage::StrokeOrderSet { layer, paint_order: order });
}
// The paint order is the chain order of the Fill and Stroke nodes, so applying it reorders the pair
for layer in document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface) {
responses.add(GraphOperationMessage::StrokePaintOrderSet { layer, paint_order: order });
}
}
@@ -11,7 +11,9 @@ use crate::messages::tool::common_functionality::transformation_cage::SelectedEd
use crate::messages::tool::tool_messages::path_tool::PathOverlayMode;
use crate::messages::tool::utility_types::ToolType;
use glam::{DAffine2, DVec2};
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graphene_std::list::List;
use graphene_std::renderer::Quad;
use graphene_std::vector::algorithms::bezpath_algorithms::pathseg_compute_lookup_table;
use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point};
@@ -543,7 +545,7 @@ pub fn make_path_editable_is_allowed(network_interface: &mut NodeNetworkInterfac
let node_id = NodeGraphLayer::new(first_layer, network_interface).horizontal_layer_flow().nth(1)?;
let output_type = network_interface.output_type(&OutputConnector::primary_output(node_id), &[]);
if output_type.compiled_element_name().as_deref() != Some("Vector") {
if output_type.compiled_nested_type() != Some(&concrete!(List<Vector>)) {
return None;
}
@@ -582,7 +582,7 @@ mod test_artboard {
Err(e) => panic!("Failed to evaluate graph: {e}"),
};
let mut artboards = List::new();
for list in instrumented.grab_all_input::<graphene_std::graphic::extend::NewInput, List<Artboard>>(&editor.runtime) {
for list in instrumented.grab_all_input_level::<graphene_std::list::extend::NewInput, Artboard>(&editor.runtime) {
for index in 0..list.len() {
if let Some(item) = list.clone_item(index) {
artboards.push(item);
@@ -347,7 +347,7 @@ impl BrushToolData {
.document_network()
.nodes
.get(&strokes_node_id)
.and_then(|node| node.inputs.get(brush_strokes::StrokesInput::INDEX))
.and_then(|node| node.inputs.get(brush_strokes::StrokeInput::INDEX))
.and_then(|input| input.as_value())
.and_then(|value| if let TaggedValue::Strokes(strokes) = value { Some(strokes.clone()) } else { None });
match strokes {
@@ -410,7 +410,7 @@ impl BrushToolData {
strokes.push(self.stroke.clone());
responses.add(NodeGraphMessage::SetInputValue {
node_id: stroke_node_id,
input_index: brush_strokes::StrokesInput::INDEX,
input_index: brush_strokes::StrokeInput::INDEX,
value: TaggedValue::Strokes(strokes).into(),
});
}
@@ -264,7 +264,6 @@ fn whole_expanse_rect(layer: LayerNodeIdentifier, document: &DocumentMessageHand
mod test_fill {
pub use crate::test_utils::test_prelude::*;
use graphene_std::color::SRGBA8;
use graphene_std::list::List;
use graphene_std::vector::fill;
/// The monitored fill wire carries `Color`; the `Graphic` conversion sits downstream of the monitor.
@@ -275,7 +274,7 @@ mod test_fill {
};
instrumented
.grab_all_input::<fill::PaintInput, List<Color>>(&editor.runtime)
.grab_all_input_level::<fill::PaintInput, Color>(&editor.runtime)
.flat_map(|list| list.iter_element_values().cloned().collect::<Vec<_>>())
.collect()
}
@@ -218,7 +218,6 @@ impl ToolTransition for FreehandTool {
overlay_provider: Some(|context: OverlayContext| FreehandToolMessage::Overlays { context }.into()),
tool_abort: Some(FreehandToolMessage::Abort.into()),
selection_changed: Some(FreehandToolMessage::SelectionChanged.into()),
graph_changed: Some(FreehandToolMessage::SelectionChanged.into()),
working_color_changed: Some(FreehandToolMessage::WorkingColorChanged.into()),
..Default::default()
}
@@ -309,9 +308,8 @@ impl Fsm for FreehandToolFsmState {
let nodes = vec![(NodeId(0), node)];
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, parent, responses);
tool_options.drawing.fill.apply_fill(layer, responses);
tool_options.drawing.apply_stroke_to_new_layer(layer, responses);
tool_options.drawing.apply_stroke_order_to_new_layer(layer, responses);
tool_options.drawing.fill.apply_fill(layer, responses);
tool_data.layer = Some(layer);
tool_data.new_layer_viewport_start = Some(input.mouse.position);
@@ -2249,7 +2249,7 @@ mod test_gradient {
.handle_message(NodeGraphMessage::SetInputValue {
node_id: gradient_node_id,
input_index: 1,
value: TaggedValue::GradientRamp(GradientRamp::from(Gradient::new([
value: Box::new(TaggedValue::GradientRamp(GradientRamp::from(Gradient::new([
GradientStop {
position: 0.,
midpoint: 0.5,
@@ -2260,8 +2260,7 @@ mod test_gradient {
midpoint: 0.5,
color: Color::BLUE,
},
])))
.into(),
])))),
})
.await;
@@ -2313,7 +2312,7 @@ mod test_gradient {
.handle_message(NodeGraphMessage::SetInputValue {
node_id: gradient_node_id,
input_index: 1,
value: TaggedValue::GradientRamp(GradientRamp::from(Gradient::new([
value: Box::new(TaggedValue::GradientRamp(GradientRamp::from(Gradient::new([
GradientStop {
position: 0.,
midpoint: 0.5,
@@ -2324,8 +2323,7 @@ mod test_gradient {
midpoint: 0.5,
color: Color::BLUE,
},
])))
.into(),
])))),
})
.await;
@@ -3039,7 +3037,7 @@ mod test_gradient {
.handle_message(NodeGraphMessage::SetInputValue {
node_id: gradient_value_id,
input_index: 1,
value: TaggedValue::GradientRamp(GradientRamp::from(Gradient::new([
value: Box::new(TaggedValue::GradientRamp(GradientRamp::from(Gradient::new([
GradientStop {
position: 0.,
midpoint: 0.5,
@@ -3050,8 +3048,7 @@ mod test_gradient {
midpoint: 0.5,
color: Color::BLUE,
},
])))
.into(),
])))),
})
.await;
@@ -315,7 +315,6 @@ impl ToolTransition for PenTool {
EventToMessageMap {
tool_abort: Some(PenToolMessage::Abort.into()),
selection_changed: Some(PenToolMessage::SelectionChanged.into()),
graph_changed: Some(PenToolMessage::SelectionChanged.into()),
working_color_changed: Some(PenToolMessage::WorkingColorChanged.into()),
overlay_provider: Some(|context| PenToolMessage::Overlays { context }.into()),
..Default::default()
@@ -1361,9 +1360,8 @@ impl PenToolData {
let parent = document.new_layer_bounding_artboard(input, viewport);
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, parent, responses);
self.current_layer = Some(layer);
tool_options.drawing.fill.apply_fill(layer, responses);
tool_options.drawing.apply_stroke_to_new_layer(layer, responses);
tool_options.drawing.apply_stroke_order_to_new_layer(layer, responses);
tool_options.drawing.fill.apply_fill(layer, responses);
self.prior_segment = None;
self.prior_segments = None;
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] });
@@ -448,7 +448,6 @@ impl ToolTransition for SelectTool {
EventToMessageMap {
tool_abort: Some(SelectToolMessage::Abort.into()),
selection_changed: Some(SelectToolMessage::SelectionChanged.into()),
graph_changed: Some(SelectToolMessage::SelectionChanged.into()),
working_color_changed: Some(SelectToolMessage::WorkingColorChanged.into()),
overlay_provider: Some(|context| SelectToolMessage::Overlays { context }.into()),
..Default::default()
@@ -710,7 +710,6 @@ impl ToolTransition for ShapeTool {
overlay_provider: Some(|context| ShapeToolMessage::Overlays { context }.into()),
tool_abort: Some(ShapeToolMessage::Abort.into()),
selection_changed: Some(ShapeToolMessage::SelectionChanged.into()),
graph_changed: Some(ShapeToolMessage::SelectionChanged.into()),
working_color_changed: Some(ShapeToolMessage::WorkingColorChanged.into()),
..Default::default()
}
@@ -1130,9 +1129,8 @@ impl Fsm for ShapeToolFsmState {
skip_rerender: false,
});
tool_options.drawing.fill.apply_fill(layer, defered_responses);
tool_options.drawing.apply_stroke_to_new_layer(layer, defered_responses);
tool_options.drawing.apply_stroke_order_to_new_layer(layer, defered_responses);
tool_options.drawing.fill.apply_fill(layer, defered_responses);
}
ShapeType::Arrow => {
let viewport_drag_start = tool_data.data.viewport_drag_start(document);
@@ -1145,9 +1143,8 @@ impl Fsm for ShapeToolFsmState {
tool_data.line_data.weight = tool_options.drawing.effective_line_weight();
tool_data.line_data.editing_layer = Some(layer);
tool_options.drawing.fill.apply_fill(layer, defered_responses);
tool_options.drawing.apply_stroke_to_new_layer(layer, defered_responses);
tool_options.drawing.apply_stroke_order_to_new_layer(layer, defered_responses);
tool_options.drawing.fill.apply_fill(layer, defered_responses);
}
ShapeType::Line => {
let viewport_drag_start = tool_data.data.viewport_drag_start(document);
@@ -233,7 +233,6 @@ impl ToolTransition for SplineTool {
canvas_transformed: Some(SplineToolMessage::CanvasTransformed.into()),
tool_abort: Some(SplineToolMessage::Abort.into()),
selection_changed: Some(SplineToolMessage::SelectionChanged.into()),
graph_changed: Some(SplineToolMessage::SelectionChanged.into()),
working_color_changed: Some(SplineToolMessage::WorkingColorChanged.into()),
}
}
@@ -409,9 +408,8 @@ impl Fsm for SplineToolFsmState {
let nodes = vec![(NodeId(1), path_node), (NodeId(0), spline_node)];
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, parent, responses);
tool_options.drawing.fill.apply_fill(layer, responses);
tool_options.drawing.apply_stroke_to_new_layer(layer, responses);
tool_options.drawing.apply_stroke_order_to_new_layer(layer, responses);
tool_options.drawing.fill.apply_fill(layer, responses);
tool_data.current_layer = Some(layer);
tool_data.new_layer_viewport_start = Some(viewport_vec);
@@ -117,7 +117,7 @@ fn create_text_widgets(tool: &TextTool, font_catalog: &FontCatalog, document: &D
NodeGraphMessage::SetInputValue {
node_id,
input_index: graphene_std::text::text::FontInput::INDEX,
value: TaggedValue::Resource(resource_id).into(),
value: Box::new(TaggedValue::Resource(resource_id)),
}
.into(),
]),
@@ -337,7 +337,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
responses.add(NodeGraphMessage::SetInputValue {
node_id,
input_index: graphene_std::text::text::SizeInput::INDEX,
value: TaggedValue::F64(font_size).into(),
value: Box::new(TaggedValue::F64(font_size)),
});
}
}
@@ -352,7 +352,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
responses.add(NodeGraphMessage::SetInputValue {
node_id,
input_index: graphene_std::text::text::AlignInput::INDEX,
value: TaggedValue::TextAlign(align).into(),
value: Box::new(TaggedValue::TextAlign(align)),
});
}
}
@@ -403,7 +403,6 @@ impl ToolTransition for TextTool {
EventToMessageMap {
canvas_transformed: None,
selection_changed: Some(TextToolMessage::SelectionChanged.into()),
graph_changed: None,
tool_abort: Some(TextToolMessage::Abort.into()),
working_color_changed: Some(TextToolMessage::WorkingColorChanged.into()),
overlay_provider: Some(|context| TextToolMessage::Overlays { context }.into()),
@@ -156,9 +156,6 @@ impl DocumentToolData {
pub struct EventToMessageMap {
pub canvas_transformed: Option<ToolMessage>,
pub selection_changed: Option<ToolMessage>,
/// Tools whose control bar mirrors the selection's node chains map this to the same message as
/// `selection_changed`, so a graph edit re-syncs the widgets the same way reselecting would.
pub graph_changed: Option<ToolMessage>,
pub tool_abort: Option<ToolMessage>,
pub working_color_changed: Option<ToolMessage>,
pub overlay_provider: Option<OverlayProvider>,
@@ -181,7 +178,6 @@ pub trait ToolTransition {
subscribe_message(event_to_tool_map.canvas_transformed, EventMessage::CanvasTransformed);
subscribe_message(event_to_tool_map.tool_abort, EventMessage::ToolAbort);
subscribe_message(event_to_tool_map.selection_changed, EventMessage::SelectionChanged);
subscribe_message(event_to_tool_map.graph_changed, EventMessage::GraphChanged);
subscribe_message(event_to_tool_map.working_color_changed, EventMessage::WorkingColorChanged);
if let Some(overlay_provider) = event_to_tool_map.overlay_provider {
responses.add(OverlaysMessage::AddProvider { provider: overlay_provider });
@@ -202,7 +198,6 @@ pub trait ToolTransition {
unsubscribe_message(event_to_tool_map.canvas_transformed, EventMessage::CanvasTransformed);
unsubscribe_message(event_to_tool_map.tool_abort, EventMessage::ToolAbort);
unsubscribe_message(event_to_tool_map.selection_changed, EventMessage::SelectionChanged);
unsubscribe_message(event_to_tool_map.graph_changed, EventMessage::GraphChanged);
unsubscribe_message(event_to_tool_map.working_color_changed, EventMessage::WorkingColorChanged);
if let Some(overlay_provider) = event_to_tool_map.overlay_provider {
responses.add(OverlaysMessage::RemoveProvider { provider: overlay_provider });
+20 -10
View File
@@ -712,8 +712,7 @@ impl NodeGraphExecutor {
text_frames,
clip_targets,
vector_data,
fill_attributes,
stroke_attributes,
appearance_attributes,
backgrounds: _,
} = render_output.metadata;
@@ -728,8 +727,7 @@ impl NodeGraphExecutor {
responses.add(DocumentMessage::UpdateTextFrames { text_frames });
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
responses.add(DocumentMessage::UpdateVectorData { vector_data });
responses.add(DocumentMessage::UpdateFillAttributes { fill_attributes });
responses.add(DocumentMessage::UpdateStrokeAttributes { stroke_attributes });
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
responses.add(DocumentMessage::RenderScrollbars);
responses.add(DocumentMessage::RenderRulers);
responses.add(OverlaysMessage::Draw);
@@ -917,7 +915,7 @@ mod test {
use crate::test_utils::test_prelude::{self, NodeGraphLayer};
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::NodeNetwork;
use graphene_std::NodeParameter;
use graphene_std::{NodeInputDecleration, NodeParameter};
use test_prelude::LayerNodeIdentifier;
/// Stores all of the monitor nodes that have been attached to a graph
@@ -980,15 +978,28 @@ mod test {
instrumented
}
/// Pulls a concrete output type out of what the monitor introspects as.
/// Our monitor stores only the context snapshot, so `introspect` recreates the value itself rather than an `IORecord`.
/// Our monitor introspects as the recorded value itself, not as an `IORecord` wrapper.
fn downcast_record<Output: Send + Sync + Clone + 'static>(dynamic: Arc<dyn std::any::Any + Send + Sync>) -> Option<Output> {
dynamic.downcast_ref::<Output>().cloned()
}
/// Grab all of the values of a LEVELED input, which introspects as its
/// whole legacy list rather than as one element. `T` is the introspected
/// element type, which differs from the declared one where a conversion
/// sits downstream of the monitor.
pub fn grab_all_input_level<'a, Input: NodeInputDecleration + 'a, T: Send + Sync + Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = List<T>> + 'a {
self.protonodes_by_name
.get(&Input::identifier())
.map_or([].as_slice(), |x| x.as_slice())
.iter()
.filter_map(|inputs| inputs.get(Input::INDEX))
.filter_map(|input_monitor_node| runtime.executor.introspect(input_monitor_node).ok())
.filter_map(|dynamic| dynamic.downcast_ref::<List<T>>().cloned())
}
/// Grab all of the values of the input every time it occurs in the graph, downcast to the recorded `Output` type.
/// A record whose type does not match `Output` is skipped, so a wrong `Output` yields an empty iterator rather than an error.
pub fn grab_all_input<'a, Input: NodeParameter + 'a, Output: Send + Sync + Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = Output> + 'a {
pub fn grab_all_input<'a, Input: NodeInputDecleration + 'a, Output: Send + Sync + Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = Output> + 'a {
self.protonodes_by_name
.get(&Input::identifier())
.map_or([].as_slice(), |x| x.as_slice())
@@ -1006,8 +1017,7 @@ mod test {
Self::downcast_record::<Output>(dynamic)
}
/// Grabs a ranked input's recorded value as its bare element `Element`.
/// `introspect` serves a rank-0 input as its element, so no cell unwrapping is needed here.
/// Grabs a ranked input's recorded value as its bare element; our monitor serves a rank-0 input as the element itself.
pub fn grab_ranked_input<Input: NodeParameter, Element: Send + Sync + Clone + 'static>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<Element> {
self.grab_protonode_input::<Input, Element>(path, runtime)
}
+11 -2
View File
@@ -5,7 +5,7 @@ use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{NodeId, NodeNetwork};
use graph_craft::graphene_compiler::Compiler;
use graph_craft::graphene_compiler::{CompileError, Compiler};
use graph_craft::proto::GraphErrors;
use graphene_std::application_io::{ApplicationIo, ExportFormat, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig, Texture};
use graphene_std::bounds::RenderBoundingBox;
@@ -441,7 +441,12 @@ impl NodeRuntime {
let c = Compiler {};
let proto_network = match c.compile_single(scoped_network, &interpreted_executor::node_registry::NODE_REGISTRY) {
Ok(network) => network,
Err(e) => return Err((ResolvedDocumentNodeTypesDelta::default(), e)),
// Errors pinned to nodes (the attribute-name fold) show in the graph like type errors do
Err(CompileError::Graph(errors)) => {
self.node_graph_errors.clone_from(&errors);
return Err((ResolvedDocumentNodeTypesDelta::default(), format!("{errors:?}")));
}
Err(error) => return Err((ResolvedDocumentNodeTypesDelta::default(), error.to_string())),
};
self.monitor_nodes = proto_network
.nodes
@@ -499,6 +504,10 @@ impl NodeRuntime {
let result = self.executor.introspect_with(monitor_node_path, |layout, batch, _arena| {
use graphene_std::core_types::record::{Group, GroupItem, RunView};
let type_id = layout.element.type_id;
// A bare constant (a value input under a test monitor) has no run to read: only a level's records adopt as one
if layout.element.content_hash.is_none() {
return Some(());
}
// Graphic run: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::Text` content)
if type_id == std::any::TypeId::of::<Graphic>() {
if update_thumbnails {
+2 -3
View File
@@ -17,7 +17,6 @@ mod editor_commands {
use editor::messages::clipboard::utility_types::ClipboardContentRaw;
use editor::messages::input_mapper::utility_types::keyboard::ModifierKeys;
use editor::messages::input_mapper::utility_types::pointer::{EditorPointerState, ScrollDelta};
use editor::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport;
use editor::messages::portfolio::utility_types::PanelGroupId;
@@ -589,11 +588,11 @@ mod editor_commands {
}
/// Creates a new document node in the node graph
fn create_node(node_type: String, x: i32, y: i32) -> Message {
fn create_node(node_type: Any, x: i32, y: i32) -> Message {
let id = NodeId::new();
NodeGraphMessage::CreateNodeFromContextMenu {
node_id: Some(id),
node_type: DefinitionIdentifier::from_serialized(&node_type),
node_type: node_type.cast(),
xy: Some((x / 24, y / 24)),
add_transaction: true,
}
+96 -10
View File
@@ -4,6 +4,7 @@ extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2::Span;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{DeriveInput, GenericParam, Lifetime, TypeParamBound, parse_macro_input};
@@ -40,25 +41,110 @@ pub fn system_desc_derive(input: TokenStream) -> TokenStream {
let struct_name = &ast.ident;
let generics = &ast.generics;
let static_params = generic_arguments(generics, "'static");
// A container's type parameter maps through its own projection, so `List<Graphic<'e>>`
// erases and relifts its contents. A value type whose parameter carries trait bounds
// cannot: the projected type need not satisfy them, so it passes through instead, and
// the `'static` bound keeps it borrow-free. `#[dyn_any_derive(project)]` picks the first.
let projects = ast
.attrs
.iter()
.any(|attr| attr.path().is_ident("dyn_any_derive") && attr.parse_args::<syn::Ident>().is_ok_and(|arg| arg == "project"));
let dyn_params = generic_arguments(generics, "'dyn_any");
let static_params = match projects {
true => projected_arguments(generics, "'static", |ident| quote! { <#ident as dyn_any::StaticTypeSized>::Static }),
false => projected_arguments(generics, "'static", |ident| quote! { #ident }),
};
let live_params = match projects {
true => projected_arguments(generics, "'dyn_any_live", |ident| quote! { <#ident as dyn_any::Relift>::Live<'dyn_any_live> }),
false => projected_arguments(generics, "'dyn_any_live", |ident| quote! { #ident }),
};
let self_params = projected_arguments(generics, "'static", |ident| quote! { #ident });
// The declared bounds come along, since the impl restates the struct's own parameters.
let bounded = |bound: TypeParamBound| -> Vec<TokenStream2> {
generics
.params
.iter()
.filter_map(|param| match param {
GenericParam::Type(t) => {
let mut t = t.clone();
t.bounds.push(bound.clone());
Some(quote! { #t })
}
GenericParam::Const(c) => Some(quote! { #c }),
GenericParam::Lifetime(_) => None,
})
.collect()
};
let static_bound: TypeParamBound = match projects {
true => syn::parse_quote!(dyn_any::StaticTypeSized),
false => TypeParamBound::Lifetime(Lifetime::new("'static", Span::call_site())),
};
let relift_bound: TypeParamBound = match projects {
true => syn::parse_quote!(dyn_any::Relift),
false => TypeParamBound::Lifetime(Lifetime::new("'static", Span::call_site())),
};
let static_bounds = bounded(static_bound);
let relift_bounds = bounded(relift_bound);
// A projected parameter must still satisfy what the struct declared of it, which only
// the author can promise: `Image<P: Pixel>` needs `P::Static: Pixel` to name its own
// static form. The relift side quantifies over the lifetime the associated type takes.
let declared_bounds = |project: &dyn Fn(&syn::Ident) -> TokenStream2| -> Vec<TokenStream2> {
generics
.params
.iter()
.filter_map(|param| match param {
GenericParam::Type(t) if projects && !t.bounds.is_empty() => {
let projected = project(&t.ident);
let bounds = &t.bounds;
Some(quote! { #projected: #bounds })
}
_ => None,
})
.collect()
};
let static_where = declared_bounds(&|ident| quote! { <#ident as dyn_any::StaticTypeSized>::Static });
let relift_where = declared_bounds(&|ident| quote! { <#ident as dyn_any::Relift>::Live<'dyn_any_live> });
let relift_where = (!relift_where.is_empty()).then(|| quote! { where for<'dyn_any_live> #(#relift_where),* });
let impl_params = generics.params.iter().map(|param| match param {
GenericParam::Type(t) => {
let mut t = t.clone();
t.bounds.push(TypeParamBound::Lifetime(Lifetime::new("'static", Span::call_site())));
quote! {#t}
}
param => quote! {#param},
});
quote! {
unsafe impl<'dyn_any, #(#impl_params,)*> dyn_any::StaticType for #struct_name <#(#dyn_params,)*> {
unsafe impl<'dyn_any, #(#static_bounds,)*> dyn_any::StaticType for #struct_name <#(#dyn_params,)*>
where #(#static_where,)*
{
type Static = #struct_name <#(#static_params,)*>;
}
unsafe impl<#(#relift_bounds,)*> dyn_any::Relift for #struct_name <#(#self_params,)*>
#relift_where
{
type Live<'dyn_any_live> = #struct_name <#(#live_params,)*>;
}
}
.into()
}
/// The struct's generic arguments with lifetimes replaced and type parameters put
/// through `project`, so a container's argument can be mapped rather than passed on.
fn projected_arguments(generics: &syn::Generics, replacement: &str, project: impl Fn(&syn::Ident) -> TokenStream2) -> Vec<TokenStream2> {
generics
.params
.iter()
.map(|param| match param {
GenericParam::Lifetime(_) => {
let lifetime = Lifetime::new(replacement, Span::call_site());
quote! {#lifetime}
}
GenericParam::Type(t) => project(&t.ident),
GenericParam::Const(c) => {
let ident = &c.ident;
quote! {#ident}
}
})
.collect()
}
/// The struct's generic parameters as argument tokens: bare idents for type
/// and const parameters (bounds are illegal in argument position), the
/// replacement for lifetimes.
+12
View File
@@ -142,6 +142,18 @@ where
{
type Static = <T as StaticType>::Static;
}
/// The inverse of [`StaticType`]: the `'static` spelling of a type re-stated at a
/// live lifetime. Where `StaticType` erases borrows so a value can be keyed and
/// stored, `Relift` names the borrowing form again so code holding the borrow can
/// be typed. A type without lifetimes relifts to itself.
///
/// # Safety
/// `Live<'a>` must be `Self` with every lifetime replaced by `'a`, so the two
/// spellings differ in nothing but the borrows they claim.
pub unsafe trait Relift {
type Live<'a>;
}
pub unsafe trait StaticTypeClone {
type Static: 'static + Clone;
fn type_id(&self) -> core::any::TypeId {
+3 -39
View File
@@ -136,17 +136,6 @@ impl DocumentNode {
self.input(parameter)?.as_value()
}
/// Normalizes this node's stored types (call argument, `Import` input types, `TypeDefault` value payloads, and any nested network) to their structural form.
/// Applied once at ingestion (document migration and clipboard paste) so no name-encoded ranked type enters a live document.
pub fn normalize_stored_types(&mut self) {
for input in &mut self.inputs {
normalize_input_stored_type(input);
}
if let Some(network) = self.implementation.get_network_mut() {
network.normalize_stored_types();
}
}
/// Locate the input that is a [`NodeInput::Import`] at index `offset` and replace it with a [`NodeInput::Node`].
pub fn populate_first_network_input(&mut self, node_id: NodeId, output_index: usize, offset: usize, source: impl Iterator<Item = Source>, skip: usize) {
let (index, _) = self
@@ -194,6 +183,8 @@ impl DocumentNode {
skip_deduplication: self.skip_deduplication,
context_features: self.context_features,
lane_invariant_inputs: 0,
footprint_free_inputs: 0,
input_index_levels: Vec::new(),
resolved: Default::default(),
}
}
@@ -265,7 +256,7 @@ impl NodeInput {
Self::Value { tagged_value, exposed }
}
/// Constructs a `NodeInput::Value` whose tagged value is `TaggedValue::TypeDefault(ty)`, recording only the
/// Constructs a `NodeInput::Value` whose tagged value is `TaggedValue::TypeDefault(td)`, recording only the
/// type so the runtime materializes its default rather than baking a placeholder value into the saved document.
pub fn type_default(td: core_types::TypeDescriptor, exposed: bool) -> Self {
Self::value(TaggedValue::TypeDefault(td), exposed)
@@ -300,7 +291,6 @@ impl NodeInput {
match self {
NodeInput::Node { .. } => unreachable!("ty() called on NodeInput::Node"),
NodeInput::Value { tagged_value, .. } => tagged_value.ty(),
// Stored import types are normalized to their structural form once at document migration
NodeInput::Import { import_type, .. } => import_type.clone(),
NodeInput::Inline(_) => panic!("ty() called on NodeInput::Inline"),
NodeInput::Scope(_) => panic!("ty() called on NodeInput::Scope"),
@@ -754,33 +744,7 @@ impl ScopeChain<'_> {
}
/// Functions for compiling the network
/// Normalizes the ranked types an input can store: an `Import`'s type or a value's `TypeDefault` payload.
fn normalize_input_stored_type(input: &mut NodeInput) {
match input {
NodeInput::Import { .. } => {}
NodeInput::Value { tagged_value, .. } => {
if let TaggedValue::TypeDefault(ty) = &**tagged_value {
let normalized = ty.clone();
if normalized != *ty {
*tagged_value = TaggedValue::TypeDefault(normalized).into();
}
}
}
_ => {}
}
}
impl NodeNetwork {
/// Normalizes every stored type in the network (exports and each node's types) to the structural form, recursively.
pub fn normalize_stored_types(&mut self) {
for export in &mut self.exports {
normalize_input_stored_type(export);
}
for node in self.nodes.values_mut() {
node.normalize_stored_types();
}
}
/// Replace all references in the graph of a node ID with a new node ID defined by the function `f`.
pub fn map_ids(&mut self, f: impl Fn(NodeId) -> NodeId + Copy) {
self.exports.iter_mut().for_each(|output| {
+151 -267
View File
@@ -6,7 +6,7 @@ use brush_nodes::{BrushCache, Stroke};
use core_types::color::SRGBA8;
use core_types::context::Context;
use core_types::gpoll::GPoll;
use core_types::list::{Item, List};
use core_types::list::List;
use core_types::registry::SourceHandle;
use core_types::transform::Footprint;
use core_types::uuid::NodeId;
@@ -33,38 +33,15 @@ use vector::VectorModification;
pub struct TaggedValueTypeError;
/// Item-cell element types routed through [`TaggedValue::TypeDefault`] instead of another dedicated variant, stored as the concrete `Item<T>` wire type.
/// List of types routed through [`TaggedValue::TypeDefault`] instead of another dedicated variant.
/// Consumed by [`TaggedValue::from_type`] (which creates `TypeDefault` values) and [`TaggedValue::to_dynany`]/[`TaggedValue::to_any`] (which unwrap them into real default values).
macro_rules! for_each_item_type_default {
($action:ident) => {
$action!(Vector);
$action!(f64);
$action!(Raster<CPU>);
$action!(Graphic);
$action!(Color);
$action!(Gradient);
$action!(Artboard);
$action!(String);
};
}
/// List element types routed through [`TaggedValue::TypeDefault`], stored as the structural [`Type::List`] form.
/// `List<f64>` is absent because it stores as `TaggedValue::F64Array`.
macro_rules! for_each_list_type_default {
($action:ident) => {
$action!(Graphic);
$action!(Artboard);
$action!(Raster<CPU>);
$action!(Vector);
$action!(String);
$action!(Color);
$action!(Gradient);
};
}
/// Unranked types routed through [`TaggedValue::TypeDefault`], stored as their concrete type.
macro_rules! for_each_bare_type_default {
macro_rules! for_each_type_default {
($action:ident) => {
$action!(List<Graphic>);
$action!(List<Artboard>);
$action!(List<Raster<CPU>>);
$action!(List<Vector>);
$action!(List<String>);
$action!(DocumentNode);
$action!(Resource);
};
@@ -82,22 +59,28 @@ macro_rules! tagged_value {
// ===============
None,
/// Stores a type, from which its `Default::default()` value can be obtained, rather than storing an actual type's value.
/// Example: `TaggedValue::TypeDefault(concrete!(String))` stores the type `String` but no specific string value.
/// (Old documents stored a bare `TypeDescriptor` payload, routed to this shape by `deserialize_tagged_value_with_legacy_migration`.)
/// Example: `TaggedValue::TypeDefault(descriptor!(String))` stores the type `String` but no specific string value.
TypeDefault(TypeDescriptor),
/// Stored compactly as a `Vec<f64>`, materializes as `List<f64>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
#[serde(deserialize_with = "core_types::misc::migrate_to_f64_array")] // TODO: Eventually remove this document upgrade code
#[serde(alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4")]
F64Array(Vec<f64>),
/// Stored compactly as a `Vec<f64>` of dash lengths, materializes as an `Item<DashPattern>` at runtime via `to_dynany`/`to_any`.
/// Stored compactly as a `Vec<f64>` of dash lengths, materializes as a `DashPattern` at runtime via `to_dynany`/`to_any`.
DashPattern(Vec<f64>),
/// Stored compactly as a `Vec<f64>` of corner values, materializes as an `Item<BoxCorners>` at runtime via `to_dynany`/`to_any`.
/// Stored compactly as a `Vec<f64>` of corner values, materializes as a `BoxCorners` at runtime via `to_dynany`/`to_any`.
BoxCorners(Vec<f64>),
/// Stored as the `GradientRamp` exchange struct (nested `{ stops: { color, position?, midpoint? } }`), materializing as an `Item<Gradient>` at runtime. Aliases recover legacy on-disk shapes.
/// A plain, always-present color. Aliases recover legacy on-disk shapes; a legacy `null` payload (the old "no color")
/// is routed to [`TaggedValue::no_paint`] by `deserialize_tagged_value_with_legacy_migration`.
#[serde(deserialize_with = "core_types::misc::migrate_to_color")] // TODO: Eventually remove this document upgrade code
#[serde(alias = "ColorTable", alias = "OptionalColor", alias = "ColorNotInTable")]
Color(Color),
/// Stored as the `GradientRamp` exchange struct (nested `{ stops: { color, position?, midpoint? } }`), materializes as a single-row `List<Gradient>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
/// (Old documents stored flat stops, a tuple list, or the ancient full `Gradient` struct under the legacy `"Gradient"` tag, all routed by `deserialize_tagged_value_with_legacy_migration`.)
#[serde(alias = "Gradient", alias = "GradientTable", alias = "GradientPositions", alias = "Gradient")]
#[serde(alias = "Gradient", alias = "GradientTable", alias = "GradientPositions", alias = "GradientStops")]
GradientRamp(GradientRamp),
/// The tablet-capture strokes the Brush tool records, materialized as `List<Stroke>` at runtime.
Strokes(Vec<Stroke>),
/// The GPU brush node's render cache, carried as node data rather than user-visible content.
BrushCache(BrushCache),
// =======================
// AUTO-GENERATED VARIANTS
@@ -108,10 +91,10 @@ macro_rules! tagged_value {
// =======================
#[serde(skip)]
RenderOutput(RenderOutput),
/// Path to the consumer of a `NodeInput::Reflection(DocumentNodePath)`, in the `Vec<NodeId>` form our node catalog consumes.
/// Path to the consumer of a `NodeInput::Reflection(DocumentNodePath)`. Materializes a `List<NodeId>` at runtime via `to_dynany`/`to_any` during graph flattening.
#[serde(skip)]
NodeIdPath(Vec<NodeId>),
/// The `DocumentNode` value carried by an `Extract` proto node, populated at flatten time by `resolve_extract_nodes`. The on-disk placeholder uses `TypeDefault(concrete!(DocumentNode))`.
/// The `DocumentNode` value carried by an `Extract` proto node, populated at flatten time by `resolve_extract_nodes`. The on-disk placeholder uses `TypeDefault(descriptor!(DocumentNode))`.
#[serde(skip)]
DocumentNode(DocumentNode),
/// Carried by context nullification proto nodes constructed at proto node compilation time in `insert_context_nullification_nodes`.
@@ -140,6 +123,7 @@ macro_rules! tagged_value {
Self::F64Array(values) => values.cache_hash(state),
Self::DashPattern(lengths) => lengths.cache_hash(state),
Self::BoxCorners(values) => values.cache_hash(state),
Self::Color(color) => color.cache_hash(state),
Self::GradientRamp(ramp) => ramp.cache_hash(state),
Self::Strokes(strokes) => strokes.cache_hash(state),
Self::BrushCache(cache) => cache.cache_hash(state),
@@ -174,32 +158,26 @@ macro_rules! tagged_value {
if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Box::new(<$type_default>::default()); }
};
}
macro_rules! check_list {
($element:ty) => {
if name == core_types::normalize_type_name(std::any::type_name::<List<$element>>()) { return Box::new(List::<$element>::default()); }
};
}
for_each_list_type_default!(check_list);
for_each_item_type_default!(check);
for_each_bare_type_default!(check);
Self::from_type_or_none(&Type::Concrete(td.clone())).to_dynany()
for_each_type_default!(check);
Self::from_type_or_none(&Type::Concrete(td)).to_dynany()
}
Self::F64Array(values) => {
let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect();
Box::new(list)
}
Self::DashPattern(lengths) => Box::new(Item::new_from_element(DashPattern::from(lengths))),
Self::BoxCorners(values) => Box::new(Item::new_from_element(BoxCorners::from(values))),
Self::GradientRamp(ramp) => Box::new(Item::<Gradient>::from(ramp)),
Self::DashPattern(lengths) => Box::new(DashPattern::from(lengths)),
Self::BoxCorners(values) => Box::new(BoxCorners::from(values)),
Self::Color(color) => Box::new(List::<Color>::new_from_element(color)),
Self::GradientRamp(ramp) => Box::new(List::new_from_item(core_types::list::Item::<Gradient>::from(ramp))),
Self::Strokes(strokes) => {
let list: List<Stroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
Box::new(list)
}
Self::BrushCache(cache) => Box::new(Item::new_from_element(cache)),
Self::BrushCache(cache) => Box::new(cache),
// =======================
// AUTO-GENERATED VARIANTS
// =======================
$( Self::$identifier(x) => Box::new(Item::new_from_element(x)), )*
$( Self::$identifier(x) => Box::new(x), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
@@ -208,7 +186,7 @@ macro_rules! tagged_value {
Self::DocumentNode(node) => Box::new(node),
Self::ContextModification(modification) => Box::new(modification),
Self::EditorApi(x) => Box::new(x),
Self::ResourceHash(x) => Box::new(Item::new_from_element(x)),
Self::ResourceHash(x) => Box::new(x),
}
}
@@ -227,32 +205,26 @@ macro_rules! tagged_value {
if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Arc::new(<$type_default>::default()); }
};
}
macro_rules! check_list {
($element:ty) => {
if name == core_types::normalize_type_name(std::any::type_name::<List<$element>>()) { return Arc::new(List::<$element>::default()); }
};
}
for_each_list_type_default!(check_list);
for_each_item_type_default!(check);
for_each_bare_type_default!(check);
Self::from_type_or_none(&Type::Concrete(td.clone())).to_any()
for_each_type_default!(check);
Self::from_type_or_none(&Type::Concrete(td)).to_any()
}
Self::F64Array(values) => {
let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect();
Arc::new(list)
}
Self::DashPattern(lengths) => Arc::new(Item::new_from_element(DashPattern::from(lengths))),
Self::BoxCorners(values) => Arc::new(Item::new_from_element(BoxCorners::from(values))),
Self::GradientRamp(ramp) => Arc::new(Item::<Gradient>::from(ramp)),
Self::DashPattern(lengths) => Arc::new(DashPattern::from(lengths)),
Self::BoxCorners(values) => Arc::new(BoxCorners::from(values)),
Self::Color(color) => Arc::new(List::<Color>::new_from_element(color)),
Self::GradientRamp(ramp) => Arc::new(List::new_from_item(core_types::list::Item::<Gradient>::from(ramp))),
Self::Strokes(strokes) => {
let list: List<Stroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
Arc::new(list)
}
Self::BrushCache(cache) => Arc::new(Item::new_from_element(cache)),
Self::BrushCache(cache) => Arc::new(cache),
// =======================
// AUTO-GENERATED VARIANTS
// =======================
$( Self::$identifier(x) => Arc::new(Item::new_from_element(x)), )*
$( Self::$identifier(x) => Arc::new(x), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
@@ -265,7 +237,7 @@ macro_rules! tagged_value {
}
}
/// Creates the wire [`Type`] of the value inside the tagged value, with ranked types in their structural form.
/// Creates a core_types::Type::Concrete(TypeDescriptor { .. }) with the type of the value inside the tagged value
pub fn ty(&self) -> Type {
match self {
// ===============
@@ -284,11 +256,11 @@ macro_rules! tagged_value {
Type::Concrete(td.clone())
}
Self::F64Array(_) => concrete!(f64),
Self::DashPattern(_) => concrete!(DashPattern),
Self::BoxCorners(_) => concrete!(BoxCorners),
Self::Color(_) => concrete!(Color),
Self::GradientRamp(_) => concrete!(Gradient),
Self::Strokes(_) => concrete!(Stroke),
Self::DashPattern(_) => concrete!(DashPattern),
Self::BoxCorners(_) => concrete!(BoxCorners),
Self::BrushCache(_) => concrete!(BrushCache),
// =======================
// AUTO-GENERATED VARIANTS
@@ -336,11 +308,11 @@ macro_rules! tagged_value {
None
}
Self::F64Array(_) => leveled::<f64>(),
Self::DashPattern(_) => scalar::<DashPattern>(),
Self::BoxCorners(_) => scalar::<BoxCorners>(),
Self::Color(_) => leveled::<Color>(),
Self::GradientRamp(_) => leveled::<Gradient>(),
Self::Strokes(_) => leveled::<Stroke>(),
Self::DashPattern(_) => scalar::<DashPattern>(),
Self::BoxCorners(_) => scalar::<BoxCorners>(),
Self::BrushCache(_) => scalar::<BrushCache>(),
$( Self::$identifier(_) => scalar::<$ty>(), )*
Self::RenderOutput(_) => scalar::<RenderOutput>(),
@@ -382,12 +354,11 @@ macro_rules! tagged_value {
Self::from_type_or_none(&Type::Concrete(td)).to_edge()
}
Self::F64Array(values) => Ok(leveled_record_value_source(values)),
Self::DashPattern(lengths) => Ok(record_value_source(DashPattern::from(lengths))),
Self::BoxCorners(values) => Ok(record_value_source(BoxCorners::from(values))),
Self::Color(color) => Ok(leveled_record_value_source(vec![color])),
Self::GradientRamp(ramp) => Ok(leveled_record_value_source(vec![Gradient::from(ramp)])),
Self::Strokes(strokes) => Ok(leveled_record_value_source(strokes)),
Self::DashPattern(lengths) => Ok(record_value_source(DashPattern(lengths.into_iter().map(core_types::list::Item::new_from_element).collect()))),
Self::BoxCorners(values) => Ok(record_value_source(BoxCorners(values.into_iter().map(core_types::list::Item::new_from_element).collect()))),
Self::BrushCache(cache) => Ok(record_value_source(cache)),
// =======================
// AUTO-GENERATED VARIANTS
// =======================
@@ -401,6 +372,7 @@ macro_rules! tagged_value {
Self::ContextModification(modification) => Ok(record_value_source(modification)),
Self::EditorApi(x) => Ok(record_value_source(x)),
Self::ResourceHash(x) => Ok(record_value_source(x)),
Self::BrushCache(cache) => Ok(record_value_source(cache)),
}
}
@@ -445,22 +417,17 @@ macro_rules! tagged_value {
x if x == TypeId::of::<Vec<f64>>() => Ok(TaggedValue::F64Array(*downcast(input).unwrap())),
x if x == TypeId::of::<List<f64>>() => Ok(TaggedValue::F64Array(downcast::<List<f64>>(input).unwrap().iter_element_values().copied().collect())),
x if x == TypeId::of::<DashPattern>() => Ok(TaggedValue::DashPattern(downcast::<DashPattern>(input).unwrap().0.iter_element_values().copied().collect())),
x if x == TypeId::of::<Item<DashPattern>>() => Ok(TaggedValue::DashPattern(downcast::<Item<DashPattern>>(input).unwrap().into_element().0.iter_element_values().copied().collect())),
x if x == TypeId::of::<BoxCorners>() => Ok(TaggedValue::BoxCorners(downcast::<BoxCorners>(input).unwrap().0.iter_element_values().copied().collect())),
x if x == TypeId::of::<Item<BoxCorners>>() => Ok(TaggedValue::BoxCorners(downcast::<Item<BoxCorners>>(input).unwrap().into_element().0.iter_element_values().copied().collect())),
x if x == TypeId::of::<Gradient>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(*downcast::<Gradient>(input).unwrap()))),
x if x == TypeId::of::<Item<Gradient>>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(&*downcast::<Item<Gradient>>(input).unwrap()))),
x if x == TypeId::of::<List<Stroke>>() => Ok(TaggedValue::Strokes(downcast::<List<Stroke>>(input).unwrap().into_iter().map(Item::into_element).collect())),
x if x == TypeId::of::<Item<BrushCache>>() => Ok(TaggedValue::BrushCache(downcast::<Item<BrushCache>>(input).unwrap().into_element())),
x if x == TypeId::of::<BrushCache>() => Ok(TaggedValue::BrushCache(*downcast(input).unwrap())),
// =======================
// AUTO-GENERATED VARIANTS
// =======================
$( x if x == TypeId::of::<$ty>() => Ok(TaggedValue::$identifier(*downcast(input).unwrap())), )*
$( x if x == TypeId::of::<Item<$ty>>() => Ok(TaggedValue::$identifier(downcast::<Item<$ty>>(input).unwrap().into_element())), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
x if x == TypeId::of::<Item<RenderOutput>>() => Ok(TaggedValue::RenderOutput(downcast::<Item<RenderOutput>>(input).unwrap().into_element())),
x if x == TypeId::of::<RenderOutput>() => Ok(TaggedValue::RenderOutput(*downcast(input).unwrap())),
_ => Err(format!("Cannot convert {:?} to TaggedValue", DynAny::type_name(input.as_ref()))),
}
@@ -479,32 +446,28 @@ macro_rules! tagged_value {
x if x == TypeId::of::<Vec<f64>>() => Ok(TaggedValue::F64Array(input.downcast_ref::<Vec<f64>>().unwrap().clone())),
x if x == TypeId::of::<List<f64>>() => Ok(TaggedValue::F64Array(input.downcast_ref::<List<f64>>().unwrap().iter_element_values().copied().collect())),
x if x == TypeId::of::<DashPattern>() => Ok(TaggedValue::DashPattern(input.downcast_ref::<DashPattern>().unwrap().0.iter_element_values().copied().collect())),
x if x == TypeId::of::<Item<DashPattern>>() => Ok(TaggedValue::DashPattern(input.downcast_ref::<Item<DashPattern>>().unwrap().element().0.iter_element_values().copied().collect())),
x if x == TypeId::of::<BoxCorners>() => Ok(TaggedValue::BoxCorners(input.downcast_ref::<BoxCorners>().unwrap().0.iter_element_values().copied().collect())),
x if x == TypeId::of::<Item<BoxCorners>>() => Ok(TaggedValue::BoxCorners(input.downcast_ref::<Item<BoxCorners>>().unwrap().element().0.iter_element_values().copied().collect())),
x if x == TypeId::of::<Gradient>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(input.downcast_ref::<Gradient>().unwrap()))),
x if x == TypeId::of::<Item<Gradient>>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(input.downcast_ref::<Item<Gradient>>().unwrap()))),
x if x == TypeId::of::<List<Stroke>>() => Ok(TaggedValue::Strokes(input.downcast_ref::<List<Stroke>>().unwrap().iter_element_values().cloned().collect())),
x if x == TypeId::of::<Item<BrushCache>>() => Ok(TaggedValue::BrushCache(input.downcast_ref::<Item<BrushCache>>().unwrap().element().clone())),
x if x == TypeId::of::<BrushCache>() => Ok(TaggedValue::BrushCache(input.downcast_ref::<BrushCache>().unwrap().clone())),
// =======================
// AUTO-GENERATED VARIANTS
// =======================
$( x if x == TypeId::of::<$ty>() => Ok(TaggedValue::$identifier(<$ty as Clone>::clone(input.downcast_ref().unwrap()))), )*
$( x if x == TypeId::of::<Item<$ty>>() => Ok(TaggedValue::$identifier(Item::<$ty>::clone(input.downcast_ref().unwrap()).into_element())), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
x if x == TypeId::of::<Item<RenderOutput>>() => Ok(TaggedValue::RenderOutput(Item::<RenderOutput>::clone(input.downcast_ref().unwrap()).into_element())),
x if x == TypeId::of::<RenderOutput>() => Ok(TaggedValue::RenderOutput(RenderOutput::clone(input.downcast_ref().unwrap()))),
_ => Err(format!("Cannot convert {:?} to TaggedValue", std::any::type_name_of_val(input))),
}
}
/// Returns a TaggedValue from the type, where that value is its type's `Default::default()`.
/// Dispatches by name for concrete types and structurally by element for ranked types, where the name
/// field is what round-trips through serde so it works even for types deserialized from disk.
/// Dispatches by the type's name (the field that round-trips through serde) so it works for both
/// freshly constructed types and types deserialized from disk where the runtime `TypeId` is unavailable.
pub fn from_type(input: &Type) -> Option<Self> {
match input {
Type::Generic(_) => None,
Type::Record(inner) => Self::from_type(inner),
Type::Concrete(concrete_type) => {
let name = concrete_type.name.as_ref();
// Tries using the default for the tagged value type. If it not implemented, then uses the default used in document_node_types. If it is not used there, then TaggedValue::None is returned.
@@ -514,14 +477,8 @@ macro_rules! tagged_value {
if name == core_types::normalize_type_name(std::any::type_name::<List<Gradient>>()) { return Some(TaggedValue::GradientRamp(GradientRamp::default())) }
$( if name == core_types::normalize_type_name(std::any::type_name::<$ty>()) { return Some(TaggedValue::$identifier(Default::default())) } )*
if name == core_types::normalize_type_name(std::any::type_name::<List<f64>>()) { return Some(TaggedValue::F64Array(Vec::new())) }
if name == core_types::normalize_type_name(std::any::type_name::<List<Stroke>>()) { return Some(TaggedValue::Strokes(Vec::new())) }
// The manual variants are not in the generated `$ty` list, so their defaults are named here
if name == core_types::normalize_type_name(std::any::type_name::<BoxCorners>()) { return Some(TaggedValue::BoxCorners(Vec::new())) }
if name == core_types::normalize_type_name(std::any::type_name::<DashPattern>()) { return Some(TaggedValue::DashPattern(Vec::new())) }
if name == core_types::normalize_type_name(std::any::type_name::<List<BoxCorners>>()) { return Some(TaggedValue::BoxCorners(Vec::new())) }
if name == core_types::normalize_type_name(std::any::type_name::<List<DashPattern>>()) { return Some(TaggedValue::DashPattern(Vec::new())) }
if name == core_types::normalize_type_name(std::any::type_name::<BrushCache>()) { return Some(TaggedValue::BrushCache(Default::default())) }
if name == core_types::normalize_type_name(std::any::type_name::<GradientRamp>()) { return Some(TaggedValue::GradientRamp(GradientRamp::default())) }
if name == core_types::normalize_type_name(std::any::type_name::<BoxCorners>()) { return Some(TaggedValue::BoxCorners(Vec::new())) }
// Leveled inputs type by their element; each element name maps to the
// same tagged default as its legacy list form.
if name == core_types::normalize_type_name(std::any::type_name::<Color>()) { return Some(TaggedValue::Color(Color::default())) }
@@ -534,38 +491,14 @@ macro_rules! tagged_value {
// Types whose `TaggedValue` variant has been removed. They route through `TypeDefault` instead, with `to_dynany`/`to_any` constructing the actual default at execution time.
macro_rules! check {
($type_default:ty) => {
if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Some(TaggedValue::TypeDefault(core_types::descriptor!($type_default))); }
if name == core_types::normalize_type_name(std::any::type_name::<$type_default>()) { return Some(TaggedValue::TypeDefault(concrete_type.clone())); }
};
}
for_each_bare_type_default!(check);
macro_rules! check_list {
($element:ty) => {
if name == core_types::normalize_type_name(std::any::type_name::<List<$element>>()) { return Some(TaggedValue::TypeDefault(core_types::descriptor!(List<$element>))); }
};
}
for_each_list_type_default!(check_list);
for_each_type_default!(check);
None
}
Type::Fn(_, output) => TaggedValue::from_type(output),
Type::Future(output) => TaggedValue::from_type(output),
// One wire kind: a record input types by its element, so the element's own
// dedicated variant is used where there is one and the structural type otherwise.
Type::Record(element) => TaggedValue::from_type(element).or_else(|| {
if **element == concrete!(f64) {
return Some(TaggedValue::F64Array(Vec::new()));
}
if **element == concrete!(Stroke) {
return Some(TaggedValue::Strokes(Vec::new()));
}
macro_rules! check {
($type_default:ty) => {
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(core_types::descriptor!($type_default))); }
};
}
for_each_item_type_default!(check);
for_each_list_type_default!(check);
None
})
}
}
@@ -579,13 +512,14 @@ macro_rules! tagged_value {
// MANUAL VARIANTS
// ===============
Self::None => "()".to_string(),
Self::TypeDefault(td) => format!("TypeDefault({td})"),
Self::TypeDefault(td) => format!("TypeDefault({})", td.name),
Self::F64Array(values) => format!("F64Array({values:?})"),
Self::DashPattern(lengths) => format!("DashPattern({lengths:?})"),
Self::BoxCorners(values) => format!("BoxCorners({values:?})"),
Self::Color(color) => format!("Color({color:?})"),
Self::GradientRamp(ramp) => format!("GradientRamp({ramp:?})"),
Self::Strokes(strokes) => format!("Strokes({strokes:?})"),
Self::BrushCache(cache) => format!("{cache:?}"),
Self::BrushCache(cache) => format!("BrushCache({cache:?})"),
// =======================
// AUTO-GENERATED VARIANTS
// =======================
@@ -639,11 +573,6 @@ tagged_value! {
DVec2(DVec2),
#[serde(alias = "Affine2")]
DAffine2(DAffine2),
/// A plain, always-present color. Aliases recover legacy on-disk shapes; a legacy `null` payload (the old "no color")
/// is routed to [`TaggedValue::no_paint`] by `deserialize_tagged_value_with_legacy_migration`.
#[serde(deserialize_with = "core_types::misc::migrate_to_color")] // TODO: Eventually remove this document upgrade code
#[serde(alias = "ColorTable", alias = "OptionalColor", alias = "ColorNotInTable")]
Color(Color),
Font(Font),
Footprint(Footprint),
VectorModification(Box<VectorModification>),
@@ -685,6 +614,7 @@ tagged_value! {
#[serde(alias = "LineJoin")]
StrokeJoin(vector::style::StrokeJoin),
StrokeAlign(vector::style::StrokeAlign),
PaintOrder(vector::style::PaintOrder),
#[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code
GradientForm(vector::style::GradientForm),
#[serde(alias = "GradientSpreadMethod")] // TODO: Eventually remove this document upgrade code
@@ -698,9 +628,8 @@ tagged_value! {
TextAlign(text_nodes::TextAlign),
ScaleType(core_types::transform::ScaleType),
// Legacy
PaintOrder(vector::style::PaintOrder), // TODO: Eventually remove this document upgrade code
#[serde(alias = "Fill")]
LegacyFill(graphic_types::migrations::legacy::LegacyFill), // TODO: Eventually remove this document upgrade code
LegacyFill(graphic_types::migrations::legacy::LegacyFill),
}
impl TaggedValue {
@@ -818,13 +747,14 @@ impl TaggedValue {
() if ty == TypeId::of::<u32>() => FromStr::from_str(string).map(TaggedValue::U32).ok()?,
() if ty == TypeId::of::<DVec2>() => to_dvec2(string).map(TaggedValue::DVec2)?,
() if ty == TypeId::of::<bool>() => FromStr::from_str(string).map(TaggedValue::Bool).ok()?,
// `Color` (not in a `List`) is still currently needed by `BlackAndWhiteNode` and `ColorOverlayNode` GPU `shader_node(PerPixelAdjust)` variants
() if ty == TypeId::of::<Color>() => to_color(string).map(TaggedValue::Color)?,
// The Fill/Stroke paint wires carry `Graphic` or `Gradient` elements, so a paint default parses through the element recursion as a color or gradient literal
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
// A rank-1 paint wire names its list type, so it parses the same literal as its element does
() if ty == TypeId::of::<List<Graphic>>() => to_color(string).map(TaggedValue::Color)?,
() if ty == TypeId::of::<List<Color>>() => to_color(string).map(TaggedValue::Color)?,
// The Fill and Stroke nodes' paint connectors default to `List<Graphic>`, their first registered implementation row
() if ty == TypeId::of::<List<Graphic>>() => to_color(string).map(TaggedValue::Color)?,
() if ty == TypeId::of::<List<Gradient>>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
// A paint default also parses against the bare element forms, as a color or gradient literal
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
@@ -845,14 +775,14 @@ impl TaggedValue {
}
}
/// The stored form of a paint input's red-slash "no paint" choice: the `Item<Graphic>` type default, materializing as a `Graphic::None` paint.
/// The stored form of a paint input's red-slash "no paint" choice: the `List<Graphic>` type default, materializing as an empty paint list.
pub fn no_paint() -> Self {
TaggedValue::TypeDefault(core_types::descriptor!(Graphic))
TaggedValue::TypeDefault(descriptor!(List<Graphic>))
}
/// Whether this is the `Item<Graphic>` type default created by [`Self::no_paint`] (and by disconnecting a paint wire).
/// Whether this is the `List<Graphic>` type default created by [`Self::no_paint`] (and by disconnecting a paint wire).
pub fn is_no_paint(&self) -> bool {
matches!(self, TaggedValue::TypeDefault(td) if *td == core_types::descriptor!(Graphic))
matches!(self, TaggedValue::TypeDefault(td) if *td == descriptor!(List<Graphic>))
}
}
@@ -860,17 +790,16 @@ impl TaggedValue {
///
/// Routes legacy variant names into modern variants, in typed Rust. Each legacy name is also matched against the historical `#[serde(alias = "...")]` spellings the deleted variant accepted, so old-shape inner payloads are caught:
///
/// - `Graphic` (or alias `GraphicGroup`/`Group`) → `TaggedValue::TypeDefault(core_types::descriptor!(List<Graphic>))`
/// - `Artboard` (or alias `ArtboardGroup`) → `TaggedValue::TypeDefault(core_types::descriptor!(List<Artboard>))`
/// - `BrushCache` → `TaggedValue::None` (purely runtime cache; no payload to preserve)
/// - `Graphic` (or alias `GraphicGroup`/`Group`) → `TaggedValue::TypeDefault(descriptor!(List<Graphic>))`
/// - `Artboard` (or alias `ArtboardGroup`) → `TaggedValue::TypeDefault(descriptor!(List<Artboard>))`
/// - `Raster` (or alias `ImageFrame`/`RasterData`/`Image`):
/// - non-empty (the legacy `image` proto's input 1, where the inner `Raster<CPU>` serializes as the embedded `Image<Color>`) → `TaggedValue::ImageData(<inner Image<Color>>)`
/// - empty → `TaggedValue::TypeDefault(core_types::descriptor!(List<Raster<CPU>>))`
/// - empty → `TaggedValue::TypeDefault(descriptor!(List<Raster<CPU>>))`
/// - `Vector` (or alias `VectorData`):
/// - non-empty → `TaggedValue::VectorModification(<built from first element>)` (the document_migration's Path pass disambiguates this between SVG-import legacy and a discardable modern baked value via the input's `exposed` flag)
/// - empty → `TaggedValue::TypeDefault(core_types::descriptor!(List<Vector>))`
/// - empty → `TaggedValue::TypeDefault(descriptor!(List<Vector>))`
/// - `FillChoice` → `TaggedValue::Color` (solid), `TaggedValue::GradientRamp` (gradient), or `TaggedValue::no_paint()` (none)
/// - `Gradient` (or alias `GradientTable`/`GradientPositions`/`Gradient`) → `TaggedValue::LegacyGradient` (ancient full struct) or `TaggedValue::GradientRamp` (ramp and legacy stops shapes, unwrapped from the legacy table form)
/// - `TypeDefault` with the old bare-`TypeDescriptor` payload → the same variant wrapping a `Type` (name-encoded `List` normalized to structural)
///
/// All other tags (including ones with the modern shape) fall through to the standard derived `Deserialize` for `TaggedValue`.
// TODO: Eventually remove this document upgrade code
@@ -884,8 +813,9 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
&& let Some((tag, content)) = map.iter().next()
{
match tag.as_str() {
"Graphic" | "GraphicGroup" | "Group" => return Ok(MemoHash::new(TaggedValue::TypeDefault(core_types::descriptor!(List<Graphic>)))),
"Artboard" | "ArtboardGroup" => return Ok(MemoHash::new(TaggedValue::TypeDefault(core_types::descriptor!(List<Artboard>)))),
"BrushCache" => return Ok(MemoHash::new(TaggedValue::None)),
"Graphic" | "GraphicGroup" | "Group" => return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor!(List<Graphic>)))),
"Artboard" | "ArtboardGroup" => return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor!(List<Artboard>)))),
"Raster" | "ImageFrame" | "RasterData" | "Image" => {
let first_element = content
.as_object()
@@ -896,7 +826,7 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
let image: Image<Color> = serde_json::from_value(image_value.clone()).map_err(serde::de::Error::custom)?;
return Ok(MemoHash::new(TaggedValue::ImageData(image)));
}
return Ok(MemoHash::new(TaggedValue::TypeDefault(core_types::descriptor!(List<Raster<CPU>>))));
return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor!(List<Raster<CPU>>))));
}
"Vector" | "VectorData" => {
let vector = graphic_types::migrations::migrate_to_optional_vector(content.clone()).map_err(serde::de::Error::custom)?;
@@ -904,41 +834,7 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
let modification = Box::new(VectorModification::create_from_vector(&vector));
return Ok(MemoHash::new(TaggedValue::VectorModification(modification)));
}
return Ok(MemoHash::new(TaggedValue::TypeDefault(core_types::descriptor!(List<Vector>))));
}
// Documents written against the structural rank model store the payload as a `Type`
// (`{"List": {"Concrete": {..}}}`). Our one wire kind reduces that to the element it names,
// keeping the `List<..>` spelling for a rank-1 wire so the existing name lookups still match.
"TypeDefault" if content.as_object().is_some_and(|c| c.contains_key("Concrete") || c.contains_key("Item") || c.contains_key("List")) => {
fn structural_type_name(value: &serde_json::Value) -> Option<String> {
let object = value.as_object()?;
if let Some(concrete) = object.get("Concrete") {
return Some(concrete.as_object()?.get("name")?.as_str()?.to_string());
}
if let Some(item) = object.get("Item") {
return structural_type_name(item);
}
if let Some(list) = object.get("List") {
return Some(format!("core_types::list::List<{}>", structural_type_name(list)?));
}
object.get("Generic")?.as_str().map(str::to_string)
}
let Some(name) = structural_type_name(&content) else {
return Err(serde::de::Error::custom("a structural TypeDefault payload named no type"));
};
let descriptor = TypeDescriptor {
id: None,
name: std::borrow::Cow::Owned(name),
alias: None,
size: 0,
align: 0,
};
return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor)));
}
// The `TypeDefault` payload is a bare `TypeDescriptor`: our one wire kind needs no structural rank in it
"TypeDefault" if content.as_object().is_some_and(|c| c.contains_key("name")) => {
let descriptor: TypeDescriptor = serde_json::from_value(content.clone()).map_err(serde::de::Error::custom)?;
return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor)));
return Ok(MemoHash::new(TaggedValue::TypeDefault(descriptor!(List<Vector>))));
}
// The `Color` tag used to carry `Option<Color>`, where a `null` payload (or an empty legacy color table) was the red-slash "no paint" choice
"Color" | "ColorTable" | "OptionalColor" | "ColorNotInTable"
@@ -967,7 +863,7 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize
}
// The gradient tags carried several shapes over time, disambiguated here: the ancient full struct (`start`/`end` keys) becomes `LegacyGradient`,
// while the current ramp, the flat stops struct, the old tuple list, and the legacy one-element table wrapper all parse as the ramp value directly
"Gradient" | "GradientTable" | "GradientPositions" | "Gradient" => {
"Gradient" | "GradientTable" | "GradientPositions" | "GradientStops" => {
let table_element = content
.as_object()
.and_then(|c| c.get("element").or_else(|| c.get("instance")).or_else(|| c.get("instances")))
@@ -1077,18 +973,18 @@ impl CacheHash for RenderOutput {
#[cfg(test)]
mod typedefault_dispatch {
use super::*;
use core_types::{concrete, item, list};
use core_types::descriptor;
/// Round-trips every type in the type-default lists through `TaggedValue::TypeDefault → to_dynany / to_any` and asserts the resulting concrete type matches the stored type.
/// Round-trips every type listed in [`for_each_type_default`] through `TaggedValue::TypeDefault → to_dynany / to_any` and asserts the resulting concrete type matches the descriptor.
///
/// This guards against the only way to break the recursion invariant in the unwrap functions: someone hand-rolling a `TypeDefault`-yielding case in `from_type` (or the macro's expansion in one of the unwrap sites silently failing to match a name). If it fails, the message points at the specific type and the structural reason.
#[test]
fn typedefault_dispatch_terminates() {
macro_rules! check {
($type_default:ty, $stored:expr) => {{
let ty: TypeDescriptor = $stored;
($type_default:ty) => {{
let descriptor = descriptor!($type_default);
let expected_type_id = std::any::TypeId::of::<$type_default>();
let dyn_value = TaggedValue::TypeDefault(ty.clone()).to_dynany();
let dyn_value = TaggedValue::TypeDefault(descriptor.clone()).to_dynany();
assert_eq!(
DynAny::type_id(&*dyn_value),
expected_type_id,
@@ -1096,7 +992,7 @@ mod typedefault_dispatch {
core_types::normalize_type_name(std::any::type_name::<$type_default>()),
);
let arc_value = TaggedValue::TypeDefault(ty).to_any();
let arc_value = TaggedValue::TypeDefault(descriptor).to_any();
assert_eq!(
(*arc_value).type_id(),
expected_type_id,
@@ -1105,19 +1001,66 @@ mod typedefault_dispatch {
);
}};
}
// One wire kind: a type default names its type, so the item and list lists both check their list form.
macro_rules! check_list {
($element:ty) => {
check!(List<$element>, core_types::descriptor!(List<$element>));
};
for_each_type_default!(check);
}
}
#[cfg(test)]
mod leveled_edges {
use super::*;
use core_types::descriptor;
use core_types::registry::record_source_type;
#[test]
fn list_variants_produce_leveled_edges_typed_by_element() {
let edge = TaggedValue::F64Array(vec![1., 2., 3.]).to_edge().unwrap();
assert_eq!(edge.ty(), &record_source_type::<f64>());
assert_eq!(edge.layout().depth, 1);
let edge = TaggedValue::Color(Color::default()).to_edge().unwrap();
assert_eq!(edge.ty(), &record_source_type::<Color>());
assert_eq!(edge.layout().depth, 1);
let edge = TaggedValue::TypeDefault(descriptor!(List<Graphic>)).to_edge().unwrap();
assert_eq!(edge.ty(), &record_source_type::<Graphic>());
assert_eq!(edge.layout().depth, 1);
}
#[test]
fn scalar_variants_keep_their_rank_zero_edges() {
let edge = TaggedValue::Bool(true).to_edge().unwrap();
assert_eq!(edge.ty(), &record_source_type::<bool>());
assert_eq!(edge.layout().depth, 0);
}
#[test]
fn the_value_layout_matches_the_edge_layout() {
for value in [
TaggedValue::F64Array(vec![1.]),
TaggedValue::Bool(true),
TaggedValue::TypeDefault(descriptor!(List<Vector>)),
TaggedValue::GradientRamp(Default::default()),
] {
let layout = value.value_layout().unwrap();
let edge = value.to_edge().unwrap();
assert_eq!(&layout, edge.layout());
}
macro_rules! check_bare {
($type_default:ty) => {
check!($type_default, core_types::descriptor!($type_default));
};
}
for_each_list_type_default!(check_list);
for_each_bare_type_default!(check_bare);
}
}
#[cfg(test)]
mod record_defaults {
use super::*;
use core_types::registry::record_source_type;
// The registry can present a record row first (wasm registration order),
// so primitive defaults must parse through the record wrapping.
#[test]
fn primitive_defaults_parse_through_record_wires() {
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("5", &record_source_type::<u32>()), Some(TaggedValue::U32(5)));
assert_eq!(TaggedValue::from_primitive_string("true", &record_source_type::<bool>()), Some(TaggedValue::Bool(true)));
}
}
@@ -1125,8 +1068,8 @@ mod typedefault_dispatch {
mod paint_default_parsing {
use super::*;
/// A Fill/Stroke paint wire carries `Graphic` elements, so its `Color::BLACK` default must parse through the
/// element recursion into a `Color` for a fresh Fill node's paint to resolve.
/// A Fill/Stroke paint wire carries `Graphic` elements, so its `Color::BLACK` default must parse
/// into a `Color` for a fresh Fill node's paint to resolve.
#[test]
fn paint_wire_parses_color_default_through_its_element() {
let black = Some(TaggedValue::Color(Color::BLACK));
@@ -1138,7 +1081,7 @@ mod paint_default_parsing {
assert_eq!(
TaggedValue::from_primitive_string("Color::BLACK", &concrete!(Graphic)),
black,
"an `Item<Graphic>` paint wire should resolve its color default"
"a bare `Graphic` paint element should resolve its color default"
);
}
@@ -1255,62 +1198,3 @@ mod gradient_shape_migration {
);
}
}
#[cfg(test)]
mod leveled_edges {
use super::*;
use core_types::descriptor;
use core_types::registry::record_source_type;
#[test]
fn list_variants_produce_leveled_edges_typed_by_element() {
let edge = TaggedValue::F64Array(vec![1., 2., 3.]).to_edge().unwrap();
assert_eq!(edge.ty(), &record_source_type::<f64>());
assert_eq!(edge.layout().depth, 1);
let edge = TaggedValue::Color(Color::default()).to_edge().unwrap();
assert_eq!(edge.ty(), &record_source_type::<Color>());
assert_eq!(edge.layout().depth, 1);
let edge = TaggedValue::TypeDefault(descriptor!(List<Graphic>)).to_edge().unwrap();
assert_eq!(edge.ty(), &record_source_type::<Graphic>());
assert_eq!(edge.layout().depth, 1);
}
#[test]
fn scalar_variants_keep_their_rank_zero_edges() {
let edge = TaggedValue::Bool(true).to_edge().unwrap();
assert_eq!(edge.ty(), &record_source_type::<bool>());
assert_eq!(edge.layout().depth, 0);
}
#[test]
fn the_value_layout_matches_the_edge_layout() {
for value in [
TaggedValue::F64Array(vec![1.]),
TaggedValue::Bool(true),
TaggedValue::TypeDefault(descriptor!(List<Vector>)),
TaggedValue::GradientRamp(Default::default()),
] {
let layout = value.value_layout().unwrap();
let edge = value.to_edge().unwrap();
assert_eq!(&layout, edge.layout());
}
}
}
#[cfg(test)]
mod record_defaults {
use super::*;
use core_types::registry::record_source_type;
// The registry can present a record row first (wasm registration order),
// so primitive defaults must parse through the record wrapping.
#[test]
fn primitive_defaults_parse_through_record_wires() {
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("5", &record_source_type::<u32>()), Some(TaggedValue::U32(5)));
assert_eq!(TaggedValue::from_primitive_string("true", &record_source_type::<bool>()), Some(TaggedValue::Bool(true)));
}
}
@@ -1,11 +1,42 @@
use crate::document::NodeNetwork;
use crate::proto::{ProtoNetwork, Registry};
use crate::proto::{GraphErrors, ProtoNetwork, Registry};
use std::error::Error;
/// Why a network failed to compile: a structural message, or errors the
/// editor can pin to their nodes in the graph.
#[derive(Debug, Clone, PartialEq)]
pub enum CompileError {
Message(String),
Graph(GraphErrors),
}
impl std::fmt::Display for CompileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CompileError::Message(message) => write!(f, "{message}"),
CompileError::Graph(errors) => write!(f, "{errors:?}"),
}
}
}
impl Error for CompileError {}
impl From<String> for CompileError {
fn from(message: String) -> Self {
CompileError::Message(message)
}
}
impl From<CompileError> for String {
fn from(error: CompileError) -> Self {
error.to_string()
}
}
pub struct Compiler {}
impl Compiler {
pub fn compile<'r>(&self, mut network: NodeNetwork, registry: &'r Registry) -> impl Iterator<Item = Result<ProtoNetwork, String>> + 'r {
pub fn compile<'r>(&self, mut network: NodeNetwork, registry: &'r Registry) -> impl Iterator<Item = Result<ProtoNetwork, CompileError>> + 'r {
network.resolve_scope_inputs();
network.generate_node_paths(&[]);
let node_ids = network.nodes.keys().copied().collect::<Vec<_>>();
@@ -20,17 +51,15 @@ impl Compiler {
proto_networks.map(move |mut proto_network| {
proto_network.insert_context_nullification_nodes()?;
let _ = proto_network.resolve_types(registry);
proto_network
.compute_layouts()
.map_err(|errors| errors.iter().map(|error| format!("{:?}", error.error)).collect::<Vec<_>>().join("\n"))?;
proto_network.compute_layouts().map_err(CompileError::Graph)?;
proto_network.generate_stable_node_ids();
Ok(proto_network)
})
}
pub fn compile_single(&self, network: NodeNetwork, registry: &Registry) -> Result<ProtoNetwork, String> {
pub fn compile_single(&self, network: NodeNetwork, registry: &Registry) -> Result<ProtoNetwork, CompileError> {
assert_eq!(network.exports.len(), 1, "Graph with multiple outputs not yet handled");
let Some(proto_network) = self.compile(network, registry).next() else {
return Err("Failed to convert graph into proto graph".to_string());
return Err(CompileError::Message("Failed to convert graph into proto graph".to_string()));
};
proto_network
}
+1 -1
View File
@@ -3,7 +3,7 @@ extern crate log;
#[macro_use]
extern crate core_types;
pub use core_types::{ProtoNodeIdentifier, Type, TypeDescriptor, concrete, descriptor, generic, item, list};
pub use core_types::{ProtoNodeIdentifier, Type, TypeDescriptor, concrete, descriptor, generic};
pub mod application_io;
pub mod document;
+286 -51
View File
@@ -156,6 +156,12 @@ pub struct ProtoNode {
/// position 32 and above never set a bit, so they read as varying.
#[serde(skip)]
pub(crate) lane_invariant_inputs: u32,
/// Bit `i` marks input `i` as never reading the footprint.
#[serde(skip)]
pub(crate) footprint_free_inputs: u32,
/// The index levels each input's branch reads, by input position.
#[serde(skip)]
pub(crate) input_index_levels: Vec<core_types::context::IndexLevels>,
#[serde(skip)]
pub(crate) resolved: Resolved,
}
@@ -170,6 +176,8 @@ impl Default for ProtoNode {
skip_deduplication: false,
context_features: Default::default(),
lane_invariant_inputs: 0,
footprint_free_inputs: 0,
input_index_levels: Vec::new(),
resolved: Default::default(),
}
}
@@ -212,6 +220,8 @@ impl ProtoNode {
skip_deduplication: false,
context_features: Default::default(),
lane_invariant_inputs: 0,
footprint_free_inputs: 0,
input_index_levels: Vec::new(),
resolved: Default::default(),
}
}
@@ -338,7 +348,9 @@ impl ProtoNetwork {
pub fn resolve_types(&mut self, registry: &Registry) -> Result<(), String> {
self.reorder_ids()?;
let stack_safe = stack_safe_extends(&self.nodes);
for index in 0..self.nodes.len() {
let mut swapped = None;
let resolved = {
let node = &self.nodes[index].1;
match &node.construction_args {
@@ -363,8 +375,10 @@ impl ProtoNetwork {
ConstructionArgs::Inline(inline) => vec![inline.ty.clone()],
ConstructionArgs::Value(_) => unreachable!(),
};
let impls = registry.get(&node.identifier).ok_or_else(|| format!("no implementations for {}", node.identifier.as_str()))?;
let identifier = specialized_identifier(node, &inputs, registry, stack_safe.contains(&self.nodes[index].0)).unwrap_or_else(|| node.identifier.clone());
let impls = registry.get(&identifier).ok_or_else(|| format!("no implementations for {}", identifier.as_str()))?;
let (io, entry) = resolve_entry(node, &inputs, impls).map_err(|errors| format!("{errors:?}"))?;
swapped = (identifier != node.identifier).then_some(identifier);
Resolved {
io: Some(io),
layout_meta: entry.layout_meta.clone(),
@@ -374,6 +388,9 @@ impl ProtoNetwork {
}
};
self.nodes[index].1.resolved = resolved;
if let Some(identifier) = swapped {
self.nodes[index].1.identifier = identifier;
}
}
Ok(())
}
@@ -383,6 +400,17 @@ impl ProtoNetwork {
let mut errors = GraphErrors::new();
for index in 0..self.nodes.len() {
let lane_invariant = self.nodes[index].1.lane_invariant_inputs;
let footprint_free = self.nodes[index].1.footprint_free_inputs;
let input_levels = self.nodes[index].1.input_index_levels.clone();
// A depth-0 producer serves at most one lane per context.
let single_lane = match &self.nodes[index].1.construction_args {
ConstructionArgs::Nodes(inputs) => inputs
.iter()
.enumerate()
.filter(|(position, input)| *position < 32 && self.nodes[input.0 as usize].1.resolved.layout.as_ref().is_some_and(|resolved| resolved.layout.depth == 0))
.fold(0u32, |mask, (position, _)| mask | (1 << position)),
_ => 0,
};
let layout = {
let node = &self.nodes[index].1;
match &node.construction_args {
@@ -390,6 +418,9 @@ impl ProtoNetwork {
frame_bytes: layout.frame_bytes(),
plan: Vec::new(),
lane_invariant,
footprint_free,
single_lane,
input_levels: input_levels.clone(),
named_writes: Vec::new(),
named_reads: Vec::new(),
named_read_defaults: Vec::new(),
@@ -406,6 +437,9 @@ impl ProtoNetwork {
errors.extend(read_type_conflicts(node, meta, &input_layouts));
meta.sources.iter().all(|&source| input_layouts[source as usize].is_some()).then(|| core_types::record::RecordLayout {
lane_invariant,
footprint_free,
single_lane,
input_levels,
..meta.resolve(&input_layouts)
})
}),
@@ -424,6 +458,27 @@ impl ProtoNetwork {
errors.is_empty().then_some(()).ok_or(errors)
}
/// The constant a node serves, seen through the wrappers that pass a value
/// on unchanged (the editor's monitors, memo and nullification nodes, and
/// passthroughs); a node that computes its value names itself instead.
fn constant_behind(&self, id: NodeId) -> Result<&MemoHash<TaggedValue>, &str> {
let transparent = [
graphene_core::memo::monitor::IDENTIFIER,
graphene_core::memo::memoize::IDENTIFIER,
graphene_core::memo::frame_memo::IDENTIFIER,
graphene_core::context_modification::context_modification::IDENTIFIER,
graphene_core::ops::passthrough::IDENTIFIER,
];
let mut node = &self.nodes[id.0 as usize].1;
loop {
match &node.construction_args {
ConstructionArgs::Value(value) => return Ok(value),
ConstructionArgs::Nodes(items) if transparent.contains(&node.identifier) && !items.is_empty() => node = &self.nodes[items[0].0 as usize].1,
_ => return Err(node.identifier.as_str()),
}
}
}
/// Resolves every name-from-input write against the constant its name
/// input carries, leaving each node's meta indistinguishable from a marker
/// node's. A name input that is not a constant is refused here, which is
@@ -449,18 +504,17 @@ impl ProtoNetwork {
.collect();
let names: Vec<Result<&'static str, GraphErrorType>> = sources
.iter()
.map(
|&(name_input, _)| match inputs.get(name_input as usize).map(|input| &self.nodes[input.0 as usize].1.construction_args) {
Some(ConstructionArgs::Value(value)) => match &**value {
value::TaggedValue::String(name) => Ok(core_types::attribute::intern_name(name)),
other => Err(GraphErrorType::AttributeName(format!("an attribute name must be text, but input {} is {}", name_input + 1, other.ty()))),
},
_ => Err(GraphErrorType::AttributeName(format!(
"input {} must be a constant, since attribute names resolve when the graph compiles rather than when it runs",
name_input + 1
))),
.map(|&(name_input, _)| match inputs.get(name_input as usize).map(|input| self.constant_behind(*input)) {
Some(Ok(value)) => match &**value {
value::TaggedValue::String(name) => Ok(core_types::attribute::intern_name(name)),
other => Err(GraphErrorType::AttributeName(format!("an attribute name must be text, but input {} is {}", name_input + 1, other.ty()))),
},
)
Some(Err(computed_by)) => Err(GraphErrorType::AttributeName(format!(
"input {} must be a constant, since attribute names resolve when the graph compiles rather than when it runs, but it is computed by {computed_by}",
name_input + 1
))),
None => Err(GraphErrorType::AttributeName(format!("input {} must be a constant, but the node has no such input", name_input + 1))),
})
.collect();
let node = &self.nodes[index].1;
let mut folded: Vec<(&'static str, std::any::TypeId)> = Vec::new();
@@ -594,16 +648,16 @@ impl ProtoNetwork {
nullification_node_id
}
/// The node's declared dependencies and per-input pushed levels, both read
/// The node's declared dependencies and per-input pushed and driven levels, all read
/// from the registry since they follow the node's signature. A node with no
/// registry entry declares nothing and pushes nothing.
fn registry_dependencies(&self, node_index: usize) -> (ContextDependencies, Vec<u8>) {
fn registry_dependencies(&self, node_index: usize) -> (ContextDependencies, Vec<(u8, u8)>) {
let identifier = &self.nodes[node_index].1.identifier;
let metadata = core_types::registry::NODE_METADATA.lock().unwrap();
match metadata.get(identifier) {
Some(entry) => (
ContextDependencies::from(entry.context_features.as_slice()),
entry.fields.iter().map(|field| field.pushed_levels).collect(),
entry.fields.iter().map(|field| (field.pushed_levels, field.driven_levels)).collect(),
),
None => (ContextDependencies::default(), Vec::new()),
}
@@ -614,7 +668,7 @@ impl ProtoNetwork {
let mut combined_deps = ContextModification::default();
let node_index = id.0 as usize;
let (registry_deps, pushed_levels) = self.registry_dependencies(node_index);
let (registry_deps, input_levels) = self.registry_dependencies(node_index);
let (extract, inject, own_deps) = {
let carried = &self.nodes[node_index].1.context_features;
// A code-built wrapper node declares dependencies its signature cannot
@@ -652,6 +706,8 @@ impl ProtoNetwork {
// Compute the dependencies for each branch and combine all of them
let mut lane_invariant_inputs = 0u32;
let mut footprint_free_inputs = 0u32;
let mut input_index_levels = Vec::with_capacity(inputs.len());
for (input, &node) in inputs.iter().enumerate() {
let branch = self.find_context_dependencies(node);
@@ -659,13 +715,33 @@ impl ProtoNetwork {
if !reads_innermost && input < 32 {
lane_invariant_inputs |= 1 << input;
}
if !branch.0.features.contains(core_types::context::ContextFeatures::FOOTPRINT) && input < 32 {
footprint_free_inputs |= 1 << input;
}
input_index_levels.push(match branch.0.features.contains(core_types::context::ContextFeatures::INDEX) {
true => branch.0.index_levels,
false => core_types::context::IndexLevels::default(),
});
let mut lifted = branch.0.clone();
lifted.index_levels = lifted.index_levels.lifted(0, pushed_levels.get(input).copied().unwrap_or(0));
let (pushed, driven) = input_levels.get(input).copied().unwrap_or((0, 0));
lifted.index_levels = lifted.index_levels.lifted(driven, pushed);
if std::env::var_os("PROBE_LEVELS").is_some() && branch.0.index_levels != lifted.index_levels {
eprintln!(
"PROBE lift: {} input {input} pushed {pushed} driven {driven}: {:?} -> {:?}{}",
self.nodes[node_index].1.identifier.as_str(),
branch.0.index_levels,
lifted.index_levels,
if lifted.index_levels.is_empty() { " <-- REQUIREMENT DIES" } else { "" }
);
}
combined_deps |= &lifted;
branch_dependencies.push(branch);
}
self.nodes[node_index].1.lane_invariant_inputs = lane_invariant_inputs;
self.nodes[node_index].1.footprint_free_inputs = footprint_free_inputs;
self.nodes[node_index].1.input_index_levels = input_index_levels;
let mut new_deps = combined_deps.clone();
// Remove requirements which this node provides
@@ -960,31 +1036,7 @@ pub struct TypingContext {
lookup: Cow<'static, Registry>,
inferred: HashMap<NodeId, NodeIOTypes>,
constructor: HashMap<NodeId, NodeConstructor>,
promotions: HashMap<NodeId, Vec<(usize, Promotion)>>,
}
/// A rank adapter which type resolution marks for insertion between a wire and a connector whose ranks differ,
/// carrying the element type the adapter is registered under.
#[derive(Debug, Clone, PartialEq)]
pub enum Promotion {
/// Raises an `Item<X>` wire onto a `List<X>` connector as a one-element list.
ItemToList(Type),
/// Bundles a whole `List<X>` wire into one opaque `Item<Bundle<X>>` cell.
Bundle(Type),
/// Unbundles an `Item<Bundle<X>>` wire back into the whole `List<X>`.
Unbundle(Type),
}
impl Promotion {
/// The registry identifier of the adapter node monomorphized for this promotion's element type.
pub fn adapter_identifier(&self) -> ProtoNodeIdentifier {
let (adapter_name, element) = match self {
Self::ItemToList(element) => ("graphene_core::ops::ItemToListNode", element),
Self::Bundle(element) => ("graphene_core::ops::BundleNode", element),
Self::Unbundle(element) => ("graphene_core::ops::UnbundleNode", element),
};
ProtoNodeIdentifier::with_owned_string(format!("{adapter_name}<{}>", element.identifier_name()))
}
stack_safe: HashSet<NodeId>,
}
impl TypingContext {
@@ -1004,6 +1056,7 @@ impl TypingContext {
/// and store them in the `inferred` field. The proto network has to be topologically sorted
/// and contain fully resolved stable node ids.
pub fn update(&mut self, network: &mut ProtoNetwork) -> Result<(), GraphErrors> {
self.stack_safe = stack_safe_extends(&network.nodes);
for (id, node) in &network.nodes {
self.infer(*id, node)?;
}
@@ -1013,16 +1066,9 @@ impl TypingContext {
pub fn remove_inference(&mut self, node_id: NodeId) -> Option<NodeIOTypes> {
self.constructor.remove(&node_id);
self.promotions.remove(&node_id);
self.inferred.remove(&node_id)
}
/// Returns the input positions of a node which type resolution marked for rank promotion, with each position's adapter.
pub fn promotions(&self, node_id: NodeId) -> Option<&Vec<(usize, Promotion)>> {
self.promotions.get(&node_id)
}
/// Returns the node constructor for a given node id.
pub fn constructor(&self, node_id: NodeId) -> Option<NodeConstructor> {
self.constructor.get(&node_id).copied()
@@ -1062,7 +1108,8 @@ impl TypingContext {
};
// Get the node input type from the proto node declaration
let impls = self.lookup.get(&node.identifier).ok_or_else(|| vec![GraphError::new(node, GraphErrorType::NoImplementations)])?;
let identifier = specialized_identifier(node, &inputs, &self.lookup, self.stack_safe.contains(&node_id)).unwrap_or_else(|| node.identifier.clone());
let impls = self.lookup.get(&identifier).ok_or_else(|| vec![GraphError::new(node, GraphErrorType::NoImplementations)])?;
let (node_io, entry) = resolve_entry(node, &inputs, impls)?;
if std::env::var("GRAPHENE_TYPE_DEBUG").is_ok() {
eprintln!("type {} {} -> {}", node_id, node.identifier, node_io.ty());
@@ -1073,8 +1120,85 @@ impl TypingContext {
}
}
/// The extend nodes every consumer accepts in stacked form. A stack lane
/// renders inline but reads as one lane, so only consumers that forward or
/// render lanes may see it; a wrapper forwards the question to its consumers.
fn stack_safe_extends(nodes: &[(NodeId, ProtoNode)]) -> HashSet<NodeId> {
const EXTEND: &str = "graphene_core::list::ExtendNode";
const FORWARDING: &[&str] = &[
"graphene_core::memo::MonitorNode",
"graphene_core::memo::MemoizeNode",
"graphene_core::memo::FrameMemoNode",
"graphene_core::context_modification::ContextModificationNode",
"graphene_core::ops::IntoNode<Graphic>",
"graphic_nodes::graphic::AsGraphicNode",
"graphic_nodes::graphic::StampLayerPathNode",
"graphic_nodes::graphic::WriteAttributeNode",
"graphic_nodes::artboard::TranslateFootprintNode",
"transform_nodes::transform_nodes::TransformNode",
"blending_nodes::OpacityNode",
"blending_nodes::BlendModeNode",
"blending_nodes::ClippingMaskNode",
"graphene_std::render_cache::RenderOutputCacheNode",
];
const ACCEPTING: &[&str] = &[
EXTEND,
"graphic_nodes::graphic::StackGraphicsNode",
"graphic_nodes::graphic::IntoGroupNode",
"graphic_nodes::artboard::CreateArtboardNode",
"graphene_std::render_node::RenderIntermediateNode",
"graphene_std::render_node::RenderNode",
"graphene_std::render_node::CreateContextNode",
"graphene_std::render_background::RenderBackgroundNode",
"graphene_std::render_pixel_preview::RenderPixelPreviewNode",
];
let index: HashMap<NodeId, usize> = nodes.iter().enumerate().map(|(position, (id, _))| (*id, position)).collect();
let mut consumers: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
for (id, node) in nodes {
if let ConstructionArgs::Nodes(inputs) = &node.construction_args {
for input in inputs {
consumers.entry(*input).or_default().push(*id);
}
}
}
fn accepted(id: NodeId, nodes: &[(NodeId, ProtoNode)], index: &HashMap<NodeId, usize>, consumers: &HashMap<NodeId, Vec<NodeId>>, depth: usize) -> bool {
// The network output renders; a runaway chain is refused.
let Some(list) = consumers.get(&id) else { return true };
depth < 64
&& list.iter().all(|consumer| {
let name = index.get(consumer).map_or("", |&position| nodes[position].1.identifier.as_str());
let accepts = ACCEPTING.contains(&name) || (FORWARDING.contains(&name) && accepted(*consumer, nodes, index, consumers, depth + 1));
if !accepts && std::env::var_os("GRAPHENE_STACK_DEBUG").is_some() {
eprintln!("stack refused> {id} consumed by {name}");
}
accepts
})
}
nodes
.iter()
.filter(|(id, node)| node.identifier.as_str() == EXTEND && accepted(*id, nodes, &index, &consumers, 0))
.map(|(id, _)| *id)
.collect()
}
/// Selects the single registry entry matching the node's resolved input types,
/// substituting generics. Stateless and stable-id-free.
/// An extend over graphic levels resolves to the stacking node, which holds both
/// sides by reference: the stacking entry accepting the inputs is the test.
fn specialized_identifier(node: &ProtoNode, inputs: &[Type], registry: &Registry, stack_safe: bool) -> Option<ProtoNodeIdentifier> {
const EXTEND: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graphene_core::list::ExtendNode");
const STACK: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graphic_nodes::graphic::StackGraphicsNode");
if node.identifier != EXTEND || !stack_safe {
return None;
}
if std::env::var_os("GRAPHENE_NO_STACK").is_some() {
return None;
}
let impls = registry.get(&STACK)?;
resolve_entry(node, inputs, impls).ok()?;
Some(STACK)
}
fn resolve_entry<'a>(node: &ProtoNode, inputs: &[Type], impls: &'a [RegistryEntry]) -> Result<(NodeIOTypes, &'a RegistryEntry), GraphErrors> {
let call_argument = &node.call_argument;
let candidates: Vec<(NodeIOTypes, &RegistryEntry)> = impls.iter().map(|entry| (entry.io.clone(), entry)).collect();
@@ -1349,7 +1473,7 @@ mod test {
// If this assert fails: These NodeIds seem to be changing when you modify TaggedValue, just update them.
assert_eq!(
ids,
vec![NodeId(12331852515109999872), NodeId(5084548161767585362), NodeId(14635346976242256925), NodeId(16015195863711239715)]
vec![NodeId(9617677014563055585), NodeId(3306304180790283913), NodeId(4482673701109291121), NodeId(1535890178157254933)]
);
}
@@ -1395,6 +1519,117 @@ mod test {
assert!(nullification_filters(&network).is_empty(), "equal branch source sets need no filter");
}
/// A nested lookup shaped like the palette chain in `brick-waves`: a constant string split
/// twice, each split indexed by a `read_index` whose *Loop Level* the preprocessor resolved
/// to a concrete level. Every inserted boundary must keep the levels its subtree reads, or
/// the lookup collapses to one cached result.
fn nested_index_lookup_network() -> ProtoNetwork {
let read_index = |level: u8| ProtoNode {
identifier: graphene_core::context::read_index::IDENTIFIER,
call_argument: concrete!(Context),
construction_args: ConstructionArgs::Nodes(vec![NodeId(0), NodeId(0)]),
context_features: ContextDependencies::new(core_types::context::ContextFeatures::INDEX, core_types::context::ContextFeatures::empty())
.with_index_levels(core_types::context::IndexLevels::empty().with_level(level)),
..Default::default()
};
let split = |source: NodeId| ProtoNode {
identifier: text_nodes::string_split::IDENTIFIER,
call_argument: concrete!(Context),
construction_args: ConstructionArgs::Nodes(vec![NodeId(0), source, NodeId(0), NodeId(0)]),
..Default::default()
};
let item_at_index = |list: NodeId, index: NodeId| ProtoNode {
identifier: graphene_core::list::item_at_index::IDENTIFIER,
call_argument: concrete!(Context),
construction_args: ConstructionArgs::Nodes(vec![list, index]),
..Default::default()
};
// A materialized list input drives its own level 0 and shifts nothing above it.
let join = |strings: NodeId| ProtoNode {
identifier: text_nodes::string_join::IDENTIFIER,
call_argument: concrete!(Context),
construction_args: ConstructionArgs::Nodes(vec![strings, NodeId(0), NodeId(0)]),
..Default::default()
};
ProtoNetwork {
inputs: vec![],
output: NodeId(10),
nodes: [
(
NodeId(0),
ProtoNode {
identifier: ProtoNodeIdentifier::new("core_types::value::ClonedNode"),
call_argument: concrete!(Context),
construction_args: ConstructionArgs::Value(value::TaggedValue::String("a,b\nc,d".to_string()).into()),
..Default::default()
},
),
// The outer loop selects a row, the inner loop a field within it.
(NodeId(1), read_index(2)),
(NodeId(2), read_index(1)),
(NodeId(3), split(NodeId(0))),
(NodeId(4), item_at_index(NodeId(3), NodeId(1))),
(NodeId(5), join(NodeId(4))),
(NodeId(6), split(NodeId(5))),
(NodeId(7), item_at_index(NodeId(6), NodeId(2))),
(NodeId(8), join(NodeId(7))),
// Two more driven hops above the lookup; neither shifts a reader's level.
(NodeId(9), join(NodeId(8))),
(NodeId(10), join(NodeId(9))),
]
.into_iter()
.collect(),
..Default::default()
}
}
/// Pins the masks a resolved-level lookup produces: every boundary keeps each level its
/// subtree reads, unshifted across the materialized hops, so the readers' levels reach the
/// boundaries above the lookup intact.
#[test]
fn nested_index_lookup_boundary_levels() {
let mut network = nested_index_lookup_network();
network.insert_context_nullification_nodes().expect("Error when calling 'insert_context_nullification_nodes'");
let levels: Vec<_> = index_level_boundaries(&network).into_iter().map(|(wrapped, _, levels)| (wrapped, levels)).collect();
assert_eq!(
levels,
vec![
("text_nodes::StringSplitNode".to_string(), IndexLevels::empty().with_level(0)),
("text_nodes::StringJoinNode".to_string(), IndexLevels::empty().with_level(2)),
("text_nodes::StringSplitNode".to_string(), IndexLevels::empty().with_level(0).with_level(2)),
("core_types::vector::ReadIndexNode".to_string(), IndexLevels::empty().with_level(1)),
]
);
}
/// Each inserted context modification, as (wrapped node, required features, retained levels).
fn index_level_boundaries(network: &ProtoNetwork) -> Vec<(String, core_types::context::ContextFeatures, core_types::context::IndexLevels)> {
let node = |id: NodeId| &network.nodes[id.0 as usize].1;
network
.nodes
.iter()
.filter(|(_, candidate)| candidate.identifier.as_str() == graphene_core::context_modification::context_modification::IDENTIFIER.as_str())
.map(|(_, candidate)| {
let ConstructionArgs::Nodes(args) = &candidate.construction_args else {
panic!("filter args must be nodes")
};
let ConstructionArgs::Nodes(memoized) = &node(args[0]).construction_args else {
panic!("filter memoize args must be nodes")
};
let ConstructionArgs::Value(value) = &node(args[1]).construction_args else {
panic!("filter payload must be a value")
};
let value::TaggedValue::ContextModification(modification) = &**value else {
panic!("filter payload must be a context modification")
};
(node(memoized[0]).identifier.as_str().to_string(), modification.features, modification.index_levels)
})
.collect()
}
fn find_node<'a>(network: &'a ProtoNetwork, name: &str) -> (NodeId, &'a ProtoNode) {
network
.nodes
+29 -5
View File
@@ -114,6 +114,11 @@ enum Command {
/// Animation duration in seconds for GIF (takes precedence over --frames)
#[clap(long)]
duration: Option<f64>,
/// Render this many times in a row, reporting each run. Compiling the graph and building the
/// executor happen once, so the later runs time the evaluation rather than the setup around it.
#[clap(long, default_value = "1")]
repeat: u32,
},
ListNodeIdentifiers,
@@ -236,6 +241,7 @@ fn main() -> Result<(), Box<dyn Error>> {
fps,
frames,
duration,
repeat,
..
} => {
// Spawn thread to poll GPU device
@@ -257,11 +263,29 @@ fn main() -> Result<(), Box<dyn Error>> {
}
// Perform export based on file type
if file_type == export::FileType::Gif {
let animation = export::AnimationParams::new(fps, frames, duration);
export::export_gif(&executor, wgpu_executor_ref.clone(), output, scale, (width, height), animation, &completion_receiver)?;
} else {
export::export_document(&executor, wgpu_executor_ref.clone(), output, file_type, scale, (width, height), transparent, &completion_receiver)?;
for run in 1..=repeat.max(1) {
// Each run starts from a flushed region, so it evaluates the graph rather than
// reading back the memos the run before it published
executor.flush_persistent();
let started = std::time::Instant::now();
if file_type == export::FileType::Gif {
let animation = export::AnimationParams::new(fps, frames, duration);
export::export_gif(&executor, wgpu_executor_ref.clone(), output.clone(), scale, (width, height), animation, &completion_receiver)?;
} else {
export::export_document(
&executor,
wgpu_executor_ref.clone(),
output.clone(),
file_type,
scale,
(width, height),
transparent,
&completion_receiver,
)?;
}
if repeat > 1 {
println!("run {run}/{repeat}: {:?}", started.elapsed());
}
}
}
_ => unreachable!("All other commands should be handled before this match statement is run"),
@@ -0,0 +1,115 @@
use core_types::transform::Footprint;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::graphene_compiler::Executor;
use graph_craft::util::{compile, load_network};
use graphene_std::application_io::{EditorApi, RenderConfig};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope;
use std::time::Instant;
fn main() {
let path = std::env::args().nth(1).expect("path to a .graphite document");
let document = std::fs::read_to_string(&path).expect("readable document");
let network = load_network(&document);
let editor_api = std::sync::Arc::new(EditorApi::default());
let mut network = wrap_network_in_scope(network, editor_api);
preprocessor::Preprocessor::new().preprocess(&mut network, &|_| None).expect("preprocess");
let proto = compile(network, &interpreted_executor::node_registry::NODE_REGISTRY);
let executor = DynamicExecutor::new(proto).expect("executor");
let viewport = |transform: DAffine2| Footprint {
transform,
resolution: UVec2::new(1024, 1024),
..Footprint::default()
};
let config = |transform: DAffine2| RenderConfig {
viewport: viewport(transform),
..RenderConfig::default()
};
let base = config(DAffine2::IDENTITY);
let panned = config(DAffine2::from_translation(DVec2::new(100., 50.)));
let zoomed = config(DAffine2::from_scale(DVec2::splat(2.)));
let steps = [
("cold", base),
("warm (same view)", base),
("pan", panned),
("pan again", panned),
("zoom", zoomed),
("zoom again", zoomed),
("back to base", base),
("zoom", zoomed),
];
// PROBE_COLD_REPEATS=N re-runs the base view N times behind a flush, so a
// profile of this process is dominated by cold frames rather than by loading.
if let Some(repeats) = std::env::var("PROBE_COLD_REPEATS").ok().and_then(|n| n.parse::<usize>().ok()) {
let first = Executor::execute(&&executor, base).expect("execute");
println!("{:>18}: digest={}", "cold", digest(&first));
for _ in 0..repeats {
executor.flush_persistent();
let started = Instant::now();
core_types::record::take_render_nanos();
let result = Executor::execute(&&executor, base).expect("execute");
let elapsed = started.elapsed();
let render = std::time::Duration::from_nanos(core_types::record::take_render_nanos());
println!("{:>18}: {:>10.3?} eval {:>10.3?} render {:>10.3?} digest={}", "cold (flushed)", elapsed, elapsed.saturating_sub(render), render, digest(&result));
#[cfg(debug_assertions)]
if std::env::var_os("GRAPHENE_BATCH_DEBUG").is_some() {
let mut rows = core_types::record::take_batch_tally();
rows.sort_by_key(|(_, (_, _, lanes))| std::cmp::Reverse(*lanes));
let (mut m, mut u, mut l) = (0, 0, 0);
for (name, (batched, unbatched, lanes)) in &rows {
m += batched;
u += unbatched;
l += lanes;
println!(" tally {batched:>7} batched {unbatched:>7} unbatched {lanes:>9} lanes {name}");
}
println!(" tally {m:>7} batched {u:>7} unbatched {l:>9} lanes TOTAL");
let mut kernels = core_types::record::take_kernel_tally();
kernels.sort_by_key(|(_, (calls, _))| std::cmp::Reverse(*calls));
for ((kernel, how), (calls, lanes)) in &kernels {
println!(" kernel {calls:>8} calls {lanes:>9} lanes {kernel:<28} {how}");
}
if std::env::var_os("GRAPHENE_ARENA_DEBUG").is_some() {
core_types::arena::Arena::dump_tally();
}
}
}
return;
}
for (name, config) in steps {
let started = Instant::now();
let result = Executor::execute(&&executor, config).expect("execute");
let elapsed = started.elapsed();
println!("{name:>18}: {:>10.3?} digest={}", elapsed, digest(&result));
}
}
/// A stable digest of a frame's output, so two frames can be compared for identical results.
fn digest<T: std::fmt::Debug>(value: &T) -> String {
use std::hash::{Hash, Hasher};
let text = format!("{value:?}");
// Pattern ids are fresh uuids per render, so hex runs of twelve or more are masked before hashing.
let mut masked = String::with_capacity(text.len());
let mut run = String::new();
for c in text.chars().chain(std::iter::once(' ')) {
if c.is_ascii_hexdigit() {
run.push(c);
continue;
}
if run.len() >= 12 {
masked.push('#');
} else {
masked.push_str(&run);
}
run.clear();
masked.push(c);
}
let text = masked;
if text.len() < 400 {
eprintln!(" result: {text}");
}
let mut hasher = std::hash::DefaultHasher::new();
text.hash(&mut hasher);
format!("{:016x} ({} bytes)", hasher.finish(), text.len())
}
@@ -14,16 +14,17 @@ use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::sync::{Arc, Mutex, PoisonError};
const ARENA_CAPACITY: usize = 1 << 27;
const ARENA_CAPACITY: usize = 1 << 28;
const PERSISTENT_CAPACITY: usize = 1 << 26;
/// The largest region a frame can grow the persistent region to.
const PERSISTENT_CAPACITY_MAX: usize = 1 << 30;
/// The heap the persistent region's parked payloads may own before a flush.
/// Occupancy cannot stand in for it: a park costs one pointer in the region
/// and owns its content outside it, so the two diverge by orders of magnitude.
#[cfg(not(target_family = "wasm"))]
const PERSISTENT_HEAP_BUDGET: usize = 1 << 29;
#[cfg(target_family = "wasm")]
const PERSISTENT_HEAP_BUDGET: usize = 1 << 28;
@@ -47,6 +48,19 @@ fn assert_deep_element_glue() {
}
}
/// The evaluation arena size, overridable for experiments with `GRAPHENE_ARENA_MB`.
fn arena_capacity() -> usize {
std::env::var("GRAPHENE_ARENA_MB").ok().and_then(|mb| mb.parse::<usize>().ok()).map_or(ARENA_CAPACITY, |mb| mb << 20)
}
/// The persistent region size, overridable for experiments with `GRAPHENE_PERSISTENT_MB`.
fn persistent_capacity() -> usize {
std::env::var("GRAPHENE_PERSISTENT_MB")
.ok()
.and_then(|mb| mb.parse::<usize>().ok())
.map_or(PERSISTENT_CAPACITY, |mb| mb << 20)
}
fn new_arena(capacity: usize) -> Arena {
Arena::new(capacity).unwrap_or_else(|| {
log::error!("arena generations exhausted; continuing without frame caching");
@@ -86,8 +100,8 @@ impl Default for DynamicExecutor {
tree: Default::default(),
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
orphaned_nodes: HashSet::new(),
arena: Mutex::new(new_arena(ARENA_CAPACITY)),
persistent: Mutex::new(new_arena(PERSISTENT_CAPACITY)),
arena: Mutex::new(new_arena(arena_capacity())),
persistent: Mutex::new(new_arena(persistent_capacity())),
frames: Mutex::new(core_types::record::FrameArena::new()),
runtime: noop_runtime(),
live_sources: Vec::new(),
@@ -125,8 +139,8 @@ impl DynamicExecutor {
output,
typing_context,
orphaned_nodes: HashSet::new(),
arena: Mutex::new(new_arena(ARENA_CAPACITY)),
persistent: Mutex::new(new_arena(PERSISTENT_CAPACITY)),
arena: Mutex::new(new_arena(arena_capacity())),
persistent: Mutex::new(new_arena(persistent_capacity())),
frames: Mutex::new(core_types::record::FrameArena::new()),
runtime,
live_sources: sources,
@@ -253,6 +267,13 @@ impl DynamicExecutor {
result.ok_or(IntrospectError::NoData)
}
/// Drops the persistent region, so every memo has to republish on the next evaluation.
/// An evaluation that follows this one does the work a first evaluation would, which is what
/// a measurement of the graph itself wants rather than the memo hits of a repeat.
pub fn flush_persistent(&self) {
self.persistent.lock().unwrap_or_else(PoisonError::into_inner).reset();
}
pub fn input_type(&self) -> Option<Type> {
self.typing_context.type_of(self.output).map(|node_io| node_io.call_argument.clone())
}
@@ -290,8 +311,27 @@ where
// re-promote: on a refusal, which leaves no room for the next promote,
// and ahead of one where either the region itself or the heap its
// parked payloads own is close to full.
if persistent.exhausted() || over_budget(persistent.occupancy(), persistent.capacity()) || over_budget(persistent.retained_heap(), PERSISTENT_HEAP_BUDGET) {
persistent.reset();
let heap_bound = over_budget(persistent.retained_heap(), PERSISTENT_HEAP_BUDGET);
if persistent.exhausted() || over_budget(persistent.occupancy(), persistent.capacity()) || heap_bound {
// A region its frames outgrow is replaced by one sized to twice what
// they published, so the steady state fits without a flush per frame;
// the heap the payloads own stays the bound that only a flush relieves.
let wanted = (persistent.occupancy() * 2).min(PERSISTENT_CAPACITY_MAX);
match !heap_bound && wanted > persistent.capacity() {
true => *persistent = new_arena(wanted),
false => {
persistent.reset();
}
}
}
if std::env::var_os("PROBE_REGION").is_some() {
eprintln!(
"PROBE region capacity={} occupancy={} retained_heap={} exhausted={}",
persistent.capacity(),
persistent.occupancy(),
persistent.retained_heap(),
persistent.exhausted()
);
}
let mut buffer = self.frames.lock().unwrap_or_else(PoisonError::into_inner);
buffer.reserve(self.tree.stack_need());
@@ -881,6 +921,29 @@ mod test {
);
}
/// The editor's monitors and the compiler's memo and nullification nodes
/// pass a constant on unchanged, so a name reaches the fold through them.
#[test]
fn a_constant_name_folds_through_a_monitor() {
let mut network = ProtoNetwork {
stack_need: 0,
inputs: vec![],
output: NodeId(4),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
(NodeId(1), string_value("novel:count")),
(NodeId(2), proto_node("graphene_core::memo::MonitorNode", vec![NodeId(1)])),
(NodeId(3), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(2.5).into()), vec![])),
(NodeId(4), proto_node("graphic_nodes::graphic::WriteAttributeNode", vec![NodeId(0), NodeId(2), NodeId(3)])),
],
};
network.resolve_types(&node_registry::NODE_REGISTRY).unwrap();
network.compute_layouts().expect("a monitored constant still folds");
let executor = DynamicExecutor::new(network).unwrap();
let layout = executor.tree().get(NodeId(4)).unwrap().layout().clone();
assert!(layout.offset_of("novel:count", 0).is_some(), "the folded name names a field of the output layout");
}
#[test]
fn a_runtime_attribute_name_is_refused_when_the_graph_compiles() {
// The outer node's name comes off another node rather than sitting on
@@ -922,33 +985,6 @@ mod test {
);
}
#[test]
fn the_clone_node_clones_the_element_out_of_its_record_wire() {
let network = ProtoNetwork {
stack_need: 0,
inputs: vec![],
output: NodeId(1),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![7.]).into()), vec![])),
(NodeId(1), proto_node("graphene_core::debug::CloneNode", vec![NodeId(0)])),
],
};
let executor = build_executor(network);
let arena = Arena::new(1 << 20).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
let handle = executor.tree().get(NodeId(1)).unwrap();
let layout = handle.layout().clone();
let edge = handle.duplicate().downcast_record::<f64>().unwrap();
let frames = core_types::record::test_frames(executor.tree().stack_need());
let GPoll::Final(value) = core_types::record::serve_input(&edge, &ctx, &frames) else {
panic!("the flipped clone must evaluate over record wires, got a non-final poll");
};
assert_eq!(unsafe { core_types::record::read_element::<f64>(layout.rec(&value)) }, 7.);
}
#[test]
fn the_palette_folds_its_record_wire_to_a_color_level() {
let raster_list = TaggedValue::from_type(&core_types::concrete!(graphene_std::list::List<graphene_std::raster_types::Raster<graphene_std::raster_types::CPU>>)).unwrap();
@@ -1,71 +1,21 @@
use glam::{DAffine2, DVec2, IVec2};
use graphene_std::list::List;
#[cfg(feature = "gpu")]
use graphene_std::raster::GPU;
#[cfg(feature = "gpu")]
use graphene_std::SourceId;
use graphene_std::raster::{CPU, Raster};
use graphene_std::registry::{ConstructionError, NodeIOTypes, RegistryEntry, SourceHandle};
#[cfg(feature = "gpu")]
use graphene_std::runtime::RuntimeHandle;
use graphene_std::vector::Vector;
use graphene_std::gradient::Gradient;
use graphene_std::brush::Stroke;
use graphene_std::{Color, Context, Graphic, ProtoNodeIdentifier, concrete};
use node_registry_macros::{convert_node, into_node};
use graphene_std::{Context, ProtoNodeIdentifier, concrete};
use node_registry_macros::convert_node;
use std::collections::HashMap;
#[cfg(feature = "gpu")]
use wgpu_executor::WgpuExecutorHandle;
fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
let mut node_types: Vec<(ProtoNodeIdentifier, RegistryEntry)> = vec![
// ==========
// INTO NODES
// ==========
into_node!(from: List<Graphic>, to: List<Graphic>),
into_node!(from: List<Raster<CPU>>, to: List<Raster<CPU>>),
#[cfg(feature = "gpu")]
into_node!(from: List<Raster<GPU>>, to: List<Raster<GPU>>),
convert_node!(from: List<Vector>, to: List<Graphic>),
convert_node!(from: List<Color>, to: List<Graphic>),
convert_node!(from: List<Gradient>, to: List<Graphic>),
convert_node!(from: List<String>, to: List<Graphic>),
convert_node!(from: List<Stroke>, to: List<Graphic>),
convert_node!(from: Vector, to: Graphic),
convert_node!(from: Color, to: Graphic),
convert_node!(from: Gradient, to: Graphic),
convert_node!(from: String, to: Graphic),
convert_node!(from: Stroke, to: Graphic),
convert_node!(from: Raster<CPU>, to: Graphic),
convert_node!(from: List<Raster<CPU>>, to: List<Graphic>),
#[cfg(feature = "gpu")]
convert_node!(from: List<Raster<GPU>>, to: List<Graphic>),
// into_node!(from: List<Raster<CPU>>, to: List<Raster<SRGBA8>>),
// =============
// CONVERT NODES
// =============
convert_node!(from: DVec2, to: DVec2),
convert_node!(from: List<Vector>, to: List<Vector>),
convert_node!(from: DVec2, to: List<Vector>),
convert_node!(from: String, to: String),
convert_node!(from: bool, to: String),
convert_node!(from: &'static str, to: String),
convert_node!(from: DVec2, to: String),
convert_node!(from: IVec2, to: String),
convert_node!(from: DAffine2, to: String),
#[cfg(feature = "gpu")]
convert_node!(from: List<Raster<CPU>>, to: List<Raster<CPU>>, converter: WgpuExecutorHandle),
#[cfg(feature = "gpu")]
convert_node!(from: List<Raster<CPU>>, to: List<Raster<GPU>>, converter: WgpuExecutorHandle),
#[cfg(feature = "gpu")]
convert_node!(from: List<Raster<GPU>>, to: List<Raster<GPU>>, converter: WgpuExecutorHandle),
#[cfg(feature = "gpu")]
convert_node!(from: List<Raster<GPU>>, to: List<Raster<CPU>>, converter: WgpuExecutorHandle, async),
// =============
// MONITOR NODES
// =============
// ==========
// MEMO NODES
// ==========
];
// The transform's value-typed rows, served by `transform_value` under the
// leveled transform's identifier.
@@ -115,6 +65,12 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
.into_iter()
.map(|entry| (graphene_std::graphic::mirror::IDENTIFIER.clone(), entry)),
);
// The gradient over a graphic level's color leaves, served under the colors to gradient identifier.
node_types.extend(
graphene_std::graphic::colors_to_gradient_graphic_entries()
.into_iter()
.map(|entry| (graphene_std::graphic::colors_to_gradient::IDENTIFIER.clone(), entry)),
);
// The morph's plain vector rows, served under its identifier.
node_types.extend(
graphene_std::vector::morph_vector_entries()
@@ -128,34 +84,11 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
.into_iter()
.map(|entry| (ProtoNodeIdentifier::new("graphene_core::ops::IntoNode<Graphic>"), entry)),
);
// The typed-level collapse rows of To Graphic, served under its identifier.
// The unit row of As Graphic: an unconnected content input renders as nothing.
node_types.extend(
graphene_std::graphic::to_graphic_typed_entries()
graphene_std::graphic::as_graphic_unit_entries()
.into_iter()
.map(|entry| (graphene_std::graphic::to_graphic::IDENTIFIER.clone(), entry)),
);
// The unit row of To Graphic: an unconnected content input renders as nothing.
node_types.extend(
graphene_std::graphic::to_graphic_unit_entries()
.into_iter()
.map(|entry| (graphene_std::graphic::to_graphic::IDENTIFIER.clone(), entry)),
);
// The transitional level bridge: a leveled input materializes into the legacy
// list an unconverted consumer expects. The rows are keyed under the legacy
// convert identifiers and die with the last legacy consumer.
node_types.extend(
graphene_std::graphic::level_to_list_entries()
.into_iter()
.zip([
"List<Graphic>",
"List<Vector>",
"List<Raster<CPU>>",
"List<Raster<GPU>>",
"List<Color>",
"List<Gradient>",
"List<String>",
])
.map(|(entry, target)| (ProtoNodeIdentifier::with_owned_string(format!("graphene_core::ops::ConvertNode<{target}>")), entry)),
.map(|entry| (graphene_std::graphic::as_graphic::IDENTIFIER.clone(), entry)),
);
// =============
// CONVERT NODES
@@ -203,12 +136,10 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
// This might be caused by the stringify! macro
let mut new_name = id.as_str().replace('\n', " ");
// Remove struct generics for all nodes except the adapter identifiers, whose element suffix distinguishes their rows
let element_suffixed_adapter = new_name.starts_with("input_adapter<")
|| new_name.starts_with("graphene_core::ops::ItemToListNode<")
|| new_name.starts_with("graphene_core::ops::BundleNode<")
|| new_name.starts_with("graphene_core::ops::UnbundleNode<");
if !element_suffixed_adapter && let Some((path, _generics)) = new_name.split_once("<") {
// Remove struct generics for all nodes except for the IntoNode and ConvertNode
if !(new_name.contains("IntoNode") || new_name.contains("ConvertNode"))
&& let Some((path, _generics)) = new_name.split_once("<")
{
new_name = path.to_string();
}
@@ -222,33 +153,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
pub static NODE_REGISTRY: once_cell::sync::Lazy<HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>> = once_cell::sync::Lazy::new(node_registry);
mod node_registry_macros {
macro_rules! into_node {
(from: $from:ty, to: $to:ty) => {
(
ProtoNodeIdentifier::new(concat!["graphene_core::ops::IntoNode<", stringify!($to), ">"]),
RegistryEntry {
layout_meta: Some(core_types::record::LayoutMeta::retype(core_types::record::element_write::<$to>())),
io: NodeIOTypes::new(
concrete!(Context),
core_types::registry::record_type::<$to>(),
vec![core_types::registry::record_source_type::<$from>()],
),
constructor: |inputs| {
if inputs.len() != 1 {
return Err(ConstructionError::Arity { expected: 1, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
let handle = inputs.next().unwrap();
let layout = handle.layout().clone();
let node = graphene_std::ops::IntoNode::<$to, _, $from>::new(handle.downcast_record::<$from>()?, &layout);
Ok(SourceHandle::new_record::<$to>(
std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>
))
},
},
)
};
}
macro_rules! convert_node {
(from: $from:ty, to: numbers) => {{
let x: Vec<(ProtoNodeIdentifier, RegistryEntry)> = vec![
@@ -368,7 +272,6 @@ mod node_registry_macros {
}
pub(crate) use convert_node;
pub(crate) use into_node;
}
#[cfg(test)]
+2 -2
View File
@@ -1,8 +1,8 @@
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
use graph_craft::generic;
use graph_craft::{concrete, item};
use graphene_std::Context;
use graphene_std::ContextFeatures;
use graphene_std::uuid::NodeId;
@@ -29,7 +29,7 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::import(core_types::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate_leveled::IDENTIFIER),
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate::IDENTIFIER),
context_features: graphene_std::ContextDependencies::new(ContextFeatures::VARARGS, ContextFeatures::INDEX),
..Default::default()
},
@@ -1,5 +1,5 @@
use core_types::transform::Footprint;
use dyn_any::{DynAny, StaticType, StaticTypeSized};
use dyn_any::DynAny;
use glam::DVec2;
use graphene_hash::CacheHash;
use std::fmt::Debug;
@@ -107,6 +107,8 @@ impl GetEditorPreferences for DummyPreferences {
}
}
#[derive(dyn_any::DynAny)]
#[dyn_any_derive(project)]
pub struct EditorApi<Io> {
/// Gives access to APIs like resources.
pub application_io: Option<Arc<Io>>,
@@ -156,7 +158,3 @@ impl<T> Debug for EditorApi<T> {
f.debug_struct("EditorApi").finish()
}
}
unsafe impl<T: StaticTypeSized> StaticType for EditorApi<T> {
type Static = EditorApi<T::Static>;
}
+51 -5
View File
@@ -32,7 +32,7 @@ pub struct Arena {
/// while a mistyped sharer, a sharer naming another destination, and a
/// sharer whose destination has since flushed are all refused. Cleared by
/// [`Arena::reset`], so a forwarding holds for one generation.
forwarded: Mutex<HashMap<usize, (usize, TypeId, u64)>>,
forwarded: Mutex<HashMap<usize, (usize, TypeId, u64), std::hash::BuildHasherDefault<graphene_hash::FxHasher64>>>,
}
impl std::fmt::Debug for Arena {
@@ -113,7 +113,17 @@ pub unsafe fn reset_generation_counter() -> bool {
impl Arena {
pub fn new(capacity: usize) -> Option<Self> {
let generation = next_generation()?;
let buf = (0..capacity).map(|_| UnsafeCell::new(MaybeUninit::uninit())).collect();
// The backbone is handed out uninitialized, so it is reserved rather than written: building
// it element by element would touch every byte of the region before an evaluation uses any
// of it. `UnsafeCell<MaybeUninit<u8>>` has no validity requirement, so the spare capacity
// is already a legal value of it.
let buf = {
let mut buf: Vec<UnsafeCell<MaybeUninit<u8>>> = Vec::with_capacity(capacity);
// SAFETY: the allocation covers `capacity` elements and the element type is valid
// in any bit pattern, including uninitialized.
unsafe { buf.set_len(capacity) };
buf.into_boxed_slice()
};
LIVE_ARENAS.fetch_add(1, Ordering::Release);
Some(Self {
generation: AtomicU64::new(generation),
@@ -122,7 +132,7 @@ impl Arena {
drops: Mutex::new(Vec::new()),
exhausted: AtomicBool::new(false),
retained_heap: AtomicUsize::new(0),
forwarded: Mutex::new(HashMap::new()),
forwarded: Mutex::new(HashMap::default()),
})
}
@@ -137,7 +147,7 @@ impl Arena {
drops: Mutex::new(Vec::new()),
exhausted: AtomicBool::new(false),
retained_heap: AtomicUsize::new(0),
forwarded: Mutex::new(HashMap::new()),
forwarded: Mutex::new(HashMap::default()),
}
}
@@ -199,7 +209,8 @@ impl Arena {
static COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let count = COUNT.fetch_add(1, Ordering::Relaxed);
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");
Self::dump_tally();
} else if count.is_multiple_of(20000) {
eprintln!("arena> {count} allocations, offset {}, this {size} bytes", self.offset.load(Ordering::Relaxed));
}
@@ -216,6 +227,20 @@ impl Arena {
self.alloc_sized(value, 0)
}
/// Prints the per-type allocation tally gathered under `GRAPHENE_ARENA_DEBUG`.
#[cfg(debug_assertions)]
pub fn dump_tally() {
ARENA_TALLY.with(|tally| {
let mut rows: Vec<(String, usize)> = tally.borrow().iter().map(|(name, count)| (name.clone(), *count)).collect();
rows.sort_by_key(|(_, count)| std::cmp::Reverse(*count));
let total: usize = rows.iter().map(|(_, count)| count).sum();
eprintln!("arena tally> {total} allocations across {} types", rows.len());
for (name, count) in rows.iter().take(20) {
eprintln!("arena tally> {count:>10} {name}");
}
});
}
/// [`Arena::alloc`] with the park glue's estimate of the heap `value` owns,
/// which the region's own occupancy cannot see.
pub fn alloc_sized<T: Send + Sync>(&self, value: T, retained: usize) -> Option<(&T, ArenaWeak<T>)> {
@@ -236,6 +261,8 @@ impl Arena {
}
fn alloc_stamped<T: Send + Sync>(&self, value: T, retained: usize, type_of: Option<TypeId>) -> Option<(&T, ArenaWeak<T>)> {
#[cfg(debug_assertions)]
arena_tally(core::any::type_name::<T>());
let offset = self.reserve(size_of::<T>(), align_of::<T>())?;
// Built before the write so an unencodable offset drops `value` here
// rather than stranding it in the arena without drop glue.
@@ -346,6 +373,8 @@ impl Arena {
}
pub fn alloc_slice_copy<T: Copy + Send + Sync>(&self, src: &[T]) -> Option<&[T]> {
#[cfg(debug_assertions)]
arena_tally(core::any::type_name::<&[T]>());
let buf = self.alloc_scratch::<T>(src.len())?;
for (slot, &value) in buf.iter_mut().zip(src) {
slot.write(value);
@@ -358,6 +387,8 @@ impl Arena {
// restrict themselves to `Copy` payloads (leak, not UB, otherwise).
#[allow(clippy::mut_from_ref)]
pub fn alloc_scratch<T: Send + Sync>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
#[cfg(debug_assertions)]
arena_tally("<scratch>");
let size = size_of::<T>().checked_mul(len)?;
let offset = self.reserve(size, align_of::<T>())?;
// SAFETY: `reserve` returned `offset`, so it is within the backbone.
@@ -868,3 +899,18 @@ mod tests {
assert_eq!(DROPS.load(Ordering::Relaxed), 2);
}
}
#[cfg(debug_assertions)]
thread_local! {
static ARENA_TALLY: std::cell::RefCell<std::collections::HashMap<String, usize>> = std::cell::RefCell::new(std::collections::HashMap::new());
}
/// Counts one arena allocation against its type, for the `GRAPHENE_ARENA_DEBUG` breakdown.
#[cfg(debug_assertions)]
fn arena_tally(name: &str) {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if !*ON.get_or_init(|| std::env::var_os("GRAPHENE_ARENA_DEBUG").is_some()) {
return;
}
ARENA_TALLY.with(|tally| *tally.borrow_mut().entry(name.to_string()).or_default() += 1);
}
@@ -257,7 +257,7 @@ macro_rules! wire_value {
impl $crate::attribute::WireValue for $value {
type Row = $value;
fn park<'e>(self, _: &'e $crate::arena::Arena) -> ::core::option::Option<$value> {
fn park(self, _: &$crate::arena::Arena) -> ::core::option::Option<$value> {
::core::option::Option::Some(self)
}
}
@@ -699,6 +699,12 @@ attribute! {
/// glyph origin so it survives 'Index Elements' filtering. The Text tool reads this to
/// position its drag cage.
pub EditorTextFrame("editor:text_frame"): DAffine2;
/// Gradient stop's position from 0 to 1 along the gradient, on the `List<Color>` inside a `Gradient`.
/// When the attribute is absent, stops distribute evenly across the 0 to 1 range.
pub Position("position"): f64;
/// Gradient stop's midpoint, a factor from 0 to 1 across the distance to the next stop,
/// on the `List<Color>` inside a `Gradient`. The final stop's midpoint is ignored.
pub Midpoint("midpoint"): f64 = 0.5;
/// Byte offset where a regex match begins ('Regex Find All' and 'Regex Capture' text nodes).
pub Start("start"): u64;
/// Byte offset where a regex match ends ('Regex Find All' and 'Regex Capture' text nodes).
@@ -727,6 +733,14 @@ attribute! {
pub MaxHeight("max_height"): Option<f64>;
/// Text item's faux-italic letter tilt angle in degrees.
pub LetterTilt("letter_tilt"): f64;
/// Brush stroke item's color its strokes are painted with.
pub BrushColor("color"): crate::Color;
/// Brush stroke item's tip diameter in document-space units.
pub Diameter("diameter"): f64 = 40.;
/// Brush stroke item's edge hardness from `0.` (softest) to `1.` (hardest).
pub Hardness("hardness"): f64;
/// Brush stroke item's per-pass paint coverage from `0.` to `1.`.
pub Flow("flow"): f64 = 1.;
}
#[cfg(test)]
+127 -28
View File
@@ -249,6 +249,11 @@ impl IndexLevels {
/// deeper than that node's. A supplied level leaves no requirement behind;
/// the rest renumber by the depth difference. An all-levels mask stays
/// saturated, since its reader's level is not known at compile time.
/// The mask after level 0 splits in two: both halves keep level 0's bit and every outer level moves up one.
pub const fn split_innermost(self) -> Self {
Self((self.0 << 1) | (self.0 & 1))
}
pub const fn lifted(self, supplied: u8, delta: u8) -> Self {
match self.0 {
u32::MAX => self,
@@ -283,7 +288,21 @@ pub fn nullify_index_levels<'s>(head: IndexLink<'s>, levels: IndexLevels, arena:
if levels.is_all() {
return Some(head);
}
let indices: Vec<u64> = core::iter::successors(Some(&head), |link| link.outer).map(|link| link.index).collect();
// A chain is a handful of levels deep and this runs on every nullified serve, so the walk
// lands in a local buffer rather than a fresh allocation. `IndexLevels` only distinguishes
// the first `u32::BITS` levels, and a chain past that is masked wholesale by `contains_level`.
const MAX_LEVELS: usize = u32::BITS as usize;
let mut buffer = [0_u64; MAX_LEVELS];
let mut count = 0;
for link in core::iter::successors(Some(&head), |link| link.outer) {
if count == MAX_LEVELS {
break;
}
buffer[count] = link.index;
count += 1;
}
let indices = &buffer[..count];
let masked = |level: usize| match levels.contains_level(level) {
true => indices[level],
false => 0,
@@ -309,6 +328,12 @@ impl core::ops::BitOrAssign for IndexLevels {
}
}
impl core::ops::BitAndAssign for IndexLevels {
fn bitand_assign(&mut self, other: Self) {
self.0 &= other.0;
}
}
impl graphene_hash::CacheHash for IndexLevels {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
core::hash::Hash::hash(self, state);
@@ -693,7 +718,7 @@ impl ExtractFootprint for () {
// ==============
pub type Context<'a> = ContextImpl<'a>;
type DynRef<'a> = &'a (dyn Any + Send + Sync);
pub type DynRef<'a> = &'a (dyn Any + Send + Sync);
pub trait DynHash {
fn dyn_hash(&self, state: &mut dyn Hasher);
@@ -809,6 +834,10 @@ impl<'a> std::fmt::Debug for VarArgLink<'a> {
}
}
/// The scope hash a boundary last nullified and the hash that came out; the strip set is fixed per boundary, so the pair is a memo of one evaluation.
#[derive(Debug, Default)]
pub struct NullifiedHash(std::sync::Mutex<(u64, u64)>);
#[derive(Clone, Copy, Debug)]
pub struct EvalScope<'a> {
real_time: Option<f64>,
@@ -861,6 +890,30 @@ impl<'a> EvalScope<'a> {
scope
}
/// [`EvalScope::nullified`] remembering the last scope it nullified: a boundary serves every lane of an evaluation from one scope, so the filtered hash is computed once per scope rather than per lane.
pub fn nullified_through(&self, keep: ContextFeatures, retain: Option<&[SourceId]>, remembered: &NullifiedHash) -> EvalScope<'a> {
let mut scope = EvalScope {
real_time: self.real_time.filter(|_| keep.contains(ContextFeatures::REAL_TIME)),
animation_time: self.animation_time.filter(|_| keep.contains(ContextFeatures::ANIMATION_TIME)),
pointer_position: self.pointer_position.filter(|_| keep.contains(ContextFeatures::POINTER_POSITION)),
..*self
};
if !scope_hash_cache_enabled() {
scope.hash = scope.compute_hash(|source| retain.is_none_or(|retain| retain.contains(source)));
return scope;
}
let mut last = remembered.0.lock().unwrap();
scope.hash = match *last {
(input, output) if input == self.hash => output,
_ => {
let output = scope.compute_hash(|source| retain.is_none_or(|retain| retain.contains(source)));
*last = (self.hash, output);
output
}
};
scope
}
pub fn nullified(&self, keep: ContextFeatures, retain: Option<&[SourceId]>) -> EvalScope<'a> {
let mut scope = EvalScope {
real_time: self.real_time.filter(|_| keep.contains(ContextFeatures::REAL_TIME)),
@@ -879,7 +932,7 @@ impl<'a> EvalScope<'a> {
}
fn compute_hash(&self, keep_source: impl Fn(&SourceId) -> bool) -> u64 {
let mut hasher = std::hash::DefaultHasher::new();
let mut hasher = graphene_hash::FxHasher64::new();
self.real_time.map(f64::to_bits).hash(&mut hasher);
self.animation_time.map(f64::to_bits).hash(&mut hasher);
self.pointer_position.map(|position| (position.x.to_bits(), position.y.to_bits())).hash(&mut hasher);
@@ -895,6 +948,23 @@ impl<'a> EvalScope<'a> {
self.generations.iter().find(|(candidate, _)| *candidate == source).map(|(_, generation)| *generation)
}
/// The scope's own contribution to a cache key.
pub fn hash(&self) -> u64 {
self.hash
}
pub fn real_time(&self) -> Option<f64> {
self.real_time
}
pub fn animation_time(&self) -> Option<f64> {
self.animation_time
}
pub fn pointer_position(&self) -> Option<DVec2> {
self.pointer_position
}
pub fn generations(&self) -> &'a [(SourceId, u64)] {
self.generations
}
@@ -927,7 +997,7 @@ impl BorrowArena for ContextImpl<'_> {
}
pub trait CtxFamily {
type Ctx<'s>: Ctx + DeriveCtx<Family = Self>;
type Ctx<'s>: Ctx + DeriveCtx<Family = Self> + InjectIndex + Copy + crate::dispatch::AsDispatch<'s>;
}
pub type Derived<'s, C> = <<C as DeriveCtx>::Family as CtxFamily>::Ctx<'s>;
@@ -1201,6 +1271,15 @@ impl<'a> ContextImpl<'a> {
pub fn index_head(&self) -> IndexLink<'a> {
self.index
}
pub fn footprint_ref(&self) -> Option<&'a Footprint> {
self.footprint
}
pub fn varargs_ref(&self) -> Option<&'a VarArgLink<'a>> {
self.varargs
}
pub fn position_ref(&self) -> Option<&'a PositionLink<'a>> {
self.position
}
pub fn with_footprint<'s>(&self, footprint: &'s Footprint) -> ContextImpl<'s>
where
@@ -1322,37 +1401,52 @@ impl ExtractPosition for ContextImpl<'_> {
self.position.map(|head| std::iter::successors(Some(head), |link| link.outer).map(|link| link.position))
}
}
impl ExtractVarArgs for ContextImpl<'_> {
fn vararg(&self, index: usize) -> Result<DynRef<'_>, VarArgsResult> {
let mut link = self.varargs.ok_or(VarArgsResult::NoVarArgs)?;
let mut remaining = index;
loop {
match link.args.get(remaining) {
Some(arg) => return Ok(arg as DynRef<'_>),
None => {
remaining -= link.args.len();
link = link.outer.ok_or(VarArgsResult::IndexOutOfBounds)?;
}
/// The vararg at `index` along a chain of links.
pub fn vararg_at<'a>(head: Option<&'a VarArgLink<'a>>, index: usize) -> Result<DynRef<'a>, VarArgsResult> {
let mut link = head.ok_or(VarArgsResult::NoVarArgs)?;
let mut remaining = index;
loop {
match link.args.get(remaining) {
Some(arg) => return Ok(arg as DynRef<'a>),
None => {
remaining -= link.args.len();
link = link.outer.ok_or(VarArgsResult::IndexOutOfBounds)?;
}
}
}
}
/// The number of varargs along a chain of links.
pub fn varargs_len(head: Option<&VarArgLink<'_>>) -> Result<usize, VarArgsResult> {
let head = head.ok_or(VarArgsResult::NoVarArgs)?;
Ok(std::iter::successors(Some(head), |link| link.outer).map(|link| link.args.len()).sum())
}
/// Hashes every vararg along a chain of links, then their count.
pub fn hash_vararg_chain(head: Option<&VarArgLink<'_>>, hasher: &mut dyn Hasher) {
let mut count = 0u64;
let mut link = head;
while let Some(current) = link {
for arg in current.args.iter() {
arg.dyn_hash(&mut *hasher);
count += 1;
}
link = current.outer;
}
count.hash(&mut &mut *hasher);
}
impl ExtractVarArgs for ContextImpl<'_> {
fn vararg(&self, index: usize) -> Result<DynRef<'_>, VarArgsResult> {
vararg_at(self.varargs, index)
}
fn varargs_len(&self) -> Result<usize, VarArgsResult> {
let head = self.varargs.ok_or(VarArgsResult::NoVarArgs)?;
Ok(std::iter::successors(Some(head), |link| link.outer).map(|link| link.args.len()).sum())
varargs_len(self.varargs)
}
fn hash_varargs(&self, hasher: &mut dyn Hasher) {
let mut count = 0u64;
let mut link = self.varargs;
while let Some(current) = link {
for arg in current.args.iter() {
arg.dyn_hash(&mut *hasher);
count += 1;
}
link = current.outer;
}
count.hash(&mut &mut *hasher);
hash_vararg_chain(self.varargs, hasher)
}
}
impl<'a> ExtractArena for ContextImpl<'a> {
@@ -1459,7 +1553,7 @@ mod context_impl_tests {
use crate::graphene_hash::CacheHash;
fn hash_of(ctx: &ContextImpl) -> u64 {
let mut hasher = std::hash::DefaultHasher::new();
let mut hasher = graphene_hash::FxHasher64::new();
ctx.cache_hash(&mut hasher);
hasher.finish()
}
@@ -1783,3 +1877,8 @@ mod context_impl_tests {
assert_eq!(*value, 41);
}
}
fn scope_hash_cache_enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("SCOPE_HASH_CACHE").is_none_or(|v| v != "off"))
}
@@ -0,0 +1,611 @@
//! Batch evaluation over a flat lane range without building a context per
//! lane: a [`LaneMap`] decomposes a global lane into index levels, and a
//! [`Lane`] answers the context traits from the map and the batch's fixed
//! part on demand.
use crate::arena::Arena;
use crate::context::{
ContextFeatures, ContextImpl, Ctx, EvalScope, ExtractAnimationTime, ExtractArena, ExtractFootprint, ExtractIndices, ExtractPointerPosition, ExtractPosition, ExtractRealTime, ExtractVarArgs,
IndexLevels, IndexLink, InjectIndex, PositionLink, VarArgLink, VarArgsResult,
};
use crate::transform::Footprint;
use glam::DVec2;
use std::hash::{Hash, Hasher};
/// The levels a map can split a lane into; deeper nesting stays on the outer chain.
pub const MAX_LEVELS: usize = 8;
/// How a global lane decomposes into index levels, innermost first: level
/// `i` runs over `extents[i]` values with the product of the levels below
/// it as its stride. A reversed level counts down, as Repeat's `reverse`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct LaneMap {
extents: [u64; MAX_LEVELS],
depth: u8,
reversed: u8,
}
impl LaneMap {
/// One level of `extent` lanes: the flat view of a level.
pub fn flat(extent: u64) -> Self {
let mut extents = [1; MAX_LEVELS];
extents[0] = extent;
Self { extents, depth: 1, reversed: 0 }
}
/// A flat view whose extent is unknown: a range over it is what the caller
/// asked for, and refinement leaves the copy count open too.
pub fn open() -> Self {
Self::flat(u64::MAX)
}
pub fn depth(&self) -> usize {
self.depth as usize
}
/// The number of lanes the map spans.
pub fn total(&self) -> u64 {
self.extents[..self.depth()].iter().product()
}
/// Splits level 0 into `inner` lanes per copy: the map reads `[inner, copies, ..]`
/// afterwards. `None` where level 0 is not a whole number of copies or the
/// map is full.
pub fn refined(&self, inner: u64, reverse: bool) -> Option<Self> {
// A reversed flat level has no well-defined split, so it refuses.
let open = self.extents[0] == u64::MAX;
if inner == 0 || self.depth() == MAX_LEVELS || (!open && self.extents[0] % inner != 0) || self.reversed & 1 == 1 {
return None;
}
let mut map = *self;
map.extents.copy_within(1..self.depth(), 2);
map.extents[0] = inner;
map.extents[1] = match open {
true => u64::MAX,
false => self.extents[0] / inner,
};
map.depth += 1;
// The copies take the flag; the new inner level counts up.
map.reversed = (self.reversed << 1) | (u8::from(reverse) << 1);
Some(map)
}
/// Level `level`'s index at `lane`.
/// An empty level has no lane, so every index under it reads as 0.
pub fn level(&self, lane: u64, level: usize) -> u64 {
let mut rest = lane;
for extent in &self.extents[..level] {
rest = rest.checked_div(*extent).unwrap_or(0);
}
let Some(index) = rest.checked_rem(self.extents[level]) else {
return 0;
};
match self.reversed >> level & 1 {
1 => self.extents[level] - 1 - index,
_ => index,
}
}
}
/// What every lane of a batch shares: the evaluation scope, the features a
/// context carries by reference, and the index chain above the map.
#[derive(Clone, Copy)]
pub struct Fixed<'a> {
scope: &'a EvalScope<'a>,
footprint: Option<&'a Footprint>,
varargs: Option<&'a VarArgLink<'a>>,
position: Option<&'a PositionLink<'a>>,
outer: Option<&'a IndexLink<'a>>,
}
/// A batch: the fixed part, the map, the lanes asked for, and which levels
/// survive nullification. Structure nodes refine the map; boundaries narrow
/// the retained levels; kernels loop [`Lane`]s over the range.
#[derive(Clone)]
pub struct Dispatch<'a> {
fixed: Fixed<'a>,
map: LaneMap,
retained: IndexLevels,
range: std::ops::Range<u64>,
}
impl<'a> Dispatch<'a> {
/// A dispatch over `range` of the level `ctx` addresses at its lane: the
/// context's own lane becomes the map's level 0.
pub fn new(ctx: &ContextImpl<'a>, map: LaneMap, range: std::ops::Range<u64>) -> Self {
let head = ctx.index_head();
Self {
fixed: Fixed {
scope: ctx.scope(),
footprint: ctx.footprint_ref(),
varargs: ctx.varargs_ref(),
position: ctx.position_ref(),
outer: head.outer,
},
map,
retained: IndexLevels::all(),
range,
}
}
pub fn map(&self) -> &LaneMap {
&self.map
}
pub fn range(&self) -> std::ops::Range<u64> {
self.range.clone()
}
pub fn retained(&self) -> IndexLevels {
self.retained
}
/// The same lanes with level 0 split into `inner` lanes per copy.
pub fn refined(&self, inner: u64, reverse: bool) -> Option<Self> {
Some(Self {
map: self.map.refined(inner, reverse)?,
retained: self.retained.split_innermost(),
..self.clone()
})
}
/// The same lanes with only `keep`'s levels readable.
pub fn nullified(&self, keep: IndexLevels) -> Self {
let mut retained = self.retained;
retained &= keep;
Self { retained, ..self.clone() }
}
pub fn lane(&self, lane: u64) -> Lane<'_> {
Lane { dispatch: self, lane }
}
}
/// The bridge between a kernel's context type and the batch: a context
/// yields the dispatch over a range of the level it addresses, and rebuilds
/// itself at any lane of a dispatch.
pub trait AsDispatch<'e>: Sized {
fn dispatch(&self, map: LaneMap, range: std::ops::Range<u64>) -> Dispatch<'e>;
/// The context at `lane`, or `None` when the arena cannot hold its chain.
fn at_lane(dispatch: &Dispatch<'e>, lane: u64) -> Option<Self>;
}
impl<'e> AsDispatch<'e> for ContextImpl<'e> {
fn dispatch(&self, map: LaneMap, range: std::ops::Range<u64>) -> Dispatch<'e> {
Dispatch::new(self, map, range)
}
fn at_lane(dispatch: &Dispatch<'e>, lane: u64) -> Option<Self> {
dispatch.serve_at(lane)
}
}
impl<'e> Dispatch<'e> {
pub fn scope(&self) -> &'e EvalScope<'e> {
self.fixed.scope
}
/// The same lanes under another scope, as a boundary narrows the scope.
pub fn with_scope<'s>(&self, scope: &'s EvalScope<'s>) -> Dispatch<'s>
where
'e: 's,
{
Dispatch {
fixed: Fixed {
scope,
footprint: self.fixed.footprint,
varargs: self.fixed.varargs,
position: self.fixed.position,
outer: self.fixed.outer,
},
map: self.map,
retained: self.retained,
range: self.range.clone(),
}
}
/// The same lanes carrying only the features in `keep`.
pub fn keeping(&self, keep: ContextFeatures) -> Self {
Dispatch {
fixed: Fixed {
footprint: self.fixed.footprint.filter(|_| keep.contains(ContextFeatures::FOOTPRINT)),
varargs: self.fixed.varargs.filter(|_| keep.contains(ContextFeatures::VARARGS)),
position: self.fixed.position.filter(|_| keep.contains(ContextFeatures::POSITION)),
..self.fixed
},
..self.clone()
}
}
/// The key every lane of the dispatch shares: the context with the map's
/// levels zeroed, which is what a memo keys a published level on.
pub fn key(&self) -> u64 {
let mut outer_only = IndexLevels::empty();
for level in self.map.depth()..32 {
outer_only = outer_only.with_level(level as u8);
}
crate::registry::cache_key(&self.nullified(outer_only).lane(0))
}
/// The serve-side context at `lane`, its canonical chain built in the
/// scope's arena so it lives as long as the dispatch does.
pub fn serve_at(&self, lane: u64) -> Option<ContextImpl<'e>> {
let view = self.lane(lane);
// A chain is a handful of levels, so it lands in a stack buffer; deeper
// chains spill to a heap buffer rather than to a limit.
let mut buffer = [0u64; 16];
let mut spill = Vec::new();
let mut count = 0;
for level in view.canonical() {
match count < buffer.len() {
true => buffer[count] = level,
false => spill.push(level),
}
count += 1;
}
let levels = |index: usize| match index < buffer.len() {
true => buffer[index],
false => spill[index - buffer.len()],
};
let arena = self.fixed.scope.arena();
let mut outer: Option<&'e IndexLink<'e>> = None;
for index in (1..count).rev() {
outer = Some(arena.alloc(IndexLink { index: levels(index), outer })?.0);
}
let mut base = ContextImpl::root(self.fixed.scope);
if let Some(footprint) = self.fixed.footprint {
base = base.with_footprint(footprint);
}
if let Some(varargs) = self.fixed.varargs {
base = base.with_varargs(varargs);
}
if let Some(position) = self.fixed.position {
base = base.with_position(position);
}
Some(match outer {
Some(outer) => base.promoted(outer, levels(0)),
None => base.replaced(levels(0)),
})
}
}
impl LaneMap {
/// Whether level 0's extent is still open.
pub fn is_open(&self) -> bool {
self.extents[0] == u64::MAX
}
/// The map with level 0 sized to `extent` where it was open.
pub fn sized(&self, extent: u64) -> Self {
let mut map = *self;
if map.is_open() {
map.extents[0] = extent;
}
map
}
/// The map with level 0 replaced by `extent`: a node whose own lane count
/// differs from an input's hands that input the map it serves under.
pub fn resized(&self, extent: u64) -> Self {
let mut map = *self;
map.extents[0] = extent;
map
}
/// Level `level`'s extent, `u64::MAX` where open.
pub fn extent(&self, level: usize) -> u64 {
self.extents[level]
}
/// Whether level `level` counts down.
pub fn is_reversed(&self, level: usize) -> bool {
self.reversed >> level & 1 == 1
}
/// Whether every level has a known extent, so `total` is the domain.
pub fn is_finite(&self) -> bool {
self.extents[..self.depth()].iter().all(|extent| *extent != u64::MAX)
}
/// The lane whose levels read as `levels(i)`: the inverse of `level`.
pub fn flat_index(&self, levels: impl Fn(usize) -> u64) -> u64 {
let mut lane = 0;
let mut stride = 1;
for level in 0..self.depth() {
let mut index = levels(level);
if self.reversed >> level & 1 == 1 {
index = self.extents[level] - 1 - index;
}
lane += index * stride;
stride = stride.saturating_mul(self.extents[level]);
}
lane
}
}
impl<'e> Dispatch<'e> {
/// The same dispatch over another range of the same map.
pub fn over(&self, range: std::ops::Range<u64>) -> Self {
Self { range, ..self.clone() }
}
/// The same dispatch with level 0 sized where it was open.
pub fn sized(&self, extent: u64) -> Self {
Self {
map: self.map.sized(extent),
..self.clone()
}
}
/// The same dispatch with level 0 replaced by `extent`.
pub fn resized(&self, extent: u64) -> Self {
Self {
map: self.map.resized(extent),
..self.clone()
}
}
/// The same lanes with every index level retained again: a gathered level
/// is a fresh level, so nothing about it is nullified yet.
pub fn retaining_all(&self) -> Self {
Self {
retained: IndexLevels::all(),
..self.clone()
}
}
/// The same lanes under another footprint.
pub fn with_footprint<'s>(&self, footprint: &'s Footprint) -> Dispatch<'s>
where
'e: 's,
{
Dispatch {
fixed: Fixed {
scope: self.fixed.scope,
footprint: Some(footprint),
varargs: self.fixed.varargs,
position: self.fixed.position,
outer: self.fixed.outer,
},
map: self.map,
retained: self.retained,
range: self.range.clone(),
}
}
}
/// One lane of a dispatch, answering the context traits from the map.
#[derive(Clone, Copy)]
pub struct Lane<'a> {
dispatch: &'a Dispatch<'a>,
lane: u64,
}
impl<'a> Lane<'a> {
fn depth(&self) -> usize {
self.dispatch.map.depth()
}
/// The chain value at `level`, zero where nullification cleared it.
pub fn level(&self, level: usize) -> u64 {
if !self.dispatch.retained.contains_level(level) {
return 0;
}
let depth = self.depth();
match level < depth {
true => self.dispatch.map.level(self.lane, level),
false => std::iter::successors(self.dispatch.fixed.outer, |link| link.outer).nth(level - depth).map_or(0, |link| link.index),
}
}
fn chain_len(&self) -> usize {
self.depth() + std::iter::successors(self.dispatch.fixed.outer, |link| link.outer).count()
}
/// The chain as nullification canonicalizes it: trailing zeroed levels
/// carry no information and are dropped, keeping at least one level.
fn canonical(&self) -> impl Iterator<Item = u64> + '_ {
let len = (0..self.chain_len()).rev().find(|&level| self.level(level) != 0).map_or(1, |level| level + 1);
(0..len).map(move |level| self.level(level))
}
/// Runs `body` with the serve-side context this lane stands for, its chain
/// built on the stack for the call.
pub fn with_serve<R>(&self, body: impl FnOnce(&ContextImpl<'_>) -> R) -> R {
let mut levels: Vec<u64> = self.canonical().collect();
levels.reverse();
let fixed = &self.dispatch.fixed;
let mut base = ContextImpl::root(fixed.scope);
if let Some(footprint) = fixed.footprint {
base = base.with_footprint(footprint);
}
if let Some(varargs) = fixed.varargs {
base = base.with_varargs(varargs);
}
if let Some(position) = fixed.position {
base = base.with_position(position);
}
// The canonical chain replaces the whole chain, outer part included.
descend(&levels, None, &base, body)
}
}
/// Builds `levels` (outermost first) as stack-linked chain links and hands
/// the innermost to `body` through the base context.
fn descend<R>(levels: &[u64], outer: Option<&IndexLink<'_>>, base: &ContextImpl<'_>, body: impl FnOnce(&ContextImpl<'_>) -> R) -> R {
match levels.split_last() {
None => body(base),
Some((&innermost, rest)) if rest.is_empty() => match outer {
Some(outer) => body(&base.promoted(outer, innermost)),
None => body(&base.replaced(innermost)),
},
Some((_, _)) => {
let (&outermost, inner) = levels.split_first().expect("non-empty");
let link = IndexLink { index: outermost, outer };
descend(inner, Some(&link), base, body)
}
}
}
impl Ctx for Lane<'_> {}
impl InjectIndex for Lane<'_> {
fn set_index(&mut self, index: u64) {
self.lane = index;
}
}
impl ExtractIndices for Lane<'_> {
fn try_index(&self) -> Option<impl Iterator<Item = usize>> {
Some(self.canonical().map(|level| level as usize))
}
}
impl ExtractFootprint for Lane<'_> {
fn try_footprint(&self) -> Option<&Footprint> {
self.dispatch.fixed.footprint
}
}
impl ExtractRealTime for Lane<'_> {
fn try_real_time(&self) -> Option<f64> {
self.dispatch.fixed.scope.real_time()
}
}
impl ExtractAnimationTime for Lane<'_> {
fn try_animation_time(&self) -> Option<f64> {
self.dispatch.fixed.scope.animation_time()
}
}
impl ExtractPointerPosition for Lane<'_> {
fn try_pointer_position(&self) -> Option<DVec2> {
self.dispatch.fixed.scope.pointer_position()
}
}
impl ExtractPosition for Lane<'_> {
fn try_position(&self) -> Option<impl Iterator<Item = DVec2>> {
self.dispatch.fixed.position.map(|head| std::iter::successors(Some(head), |link| link.outer).map(|link| link.position))
}
}
impl ExtractVarArgs for Lane<'_> {
fn vararg(&self, index: usize) -> Result<crate::context::DynRef<'_>, VarArgsResult> {
crate::context::vararg_at(self.dispatch.fixed.varargs, index)
}
fn varargs_len(&self) -> Result<usize, VarArgsResult> {
crate::context::varargs_len(self.dispatch.fixed.varargs)
}
fn hash_varargs(&self, hasher: &mut dyn Hasher) {
crate::context::hash_vararg_chain(self.dispatch.fixed.varargs, hasher)
}
}
impl<'a> ExtractArena for Lane<'a> {
type ArenaRef = &'a Arena;
fn arena(&self) -> &'a Arena {
self.dispatch.fixed.scope.arena()
}
}
/// The same hash as the serve-side context this lane stands for.
impl graphene_hash::CacheHash for Lane<'_> {
fn cache_hash<H: Hasher>(&self, state: &mut H) {
match self.dispatch.fixed.footprint {
Some(footprint) => {
1u8.hash(state);
footprint.cache_hash(state);
}
None => 0u8.hash(state),
}
let mut count = 0u64;
for level in self.canonical() {
level.hash(state);
count += 1;
}
count.hash(state);
count = 0;
let mut position = self.dispatch.fixed.position;
while let Some(link) = position {
link.position.x.to_bits().hash(state);
link.position.y.to_bits().hash(state);
count += 1;
position = link.outer;
}
count.hash(state);
self.hash_varargs(state);
self.dispatch.fixed.scope.hash().hash(state);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::context::{ContextImpl, nullify_index_levels};
use crate::registry::cache_key;
fn keep(levels: &[u8]) -> IndexLevels {
levels.iter().fold(IndexLevels::empty(), |mask, &level| mask.with_level(level))
}
/// The serve side: the chain a Repeat of `copies` over a body of `inner`
/// lanes builds for one lane, nullified to `keep`.
fn served_key(root: &ContextImpl<'_>, scope: &EvalScope<'_>, arena: &Arena, inner: u64, lane: u64, reverse: bool, copies: u64, keep: IndexLevels) -> u64 {
let (copy, within) = (lane / inner, lane % inner);
let copy = match reverse {
true => copies - 1 - copy,
false => copy,
};
let mut frame = IndexLink { index: 0, outer: None };
let served = root.push_level(&mut frame, copy, within);
let chain = nullify_index_levels(served.index_head(), keep, arena).unwrap();
cache_key(&served.nullified(ContextFeatures::all(), chain, scope))
}
#[test]
fn a_lane_keys_like_the_serve_chain_it_stands_for() {
let arena = Arena::new(1 << 12).unwrap();
let generations = [];
let scope = EvalScope::new(Some(0.5), None, None, &generations, &arena);
let root = ContextImpl::root(&scope);
let (inner, copies) = (4u64, 3u64);
for reverse in [false, true] {
for keep in [keep(&[0, 1]), keep(&[1]), keep(&[0])] {
let dispatch = Dispatch::new(&root, LaneMap::flat(inner * copies).refined(inner, reverse).unwrap(), 0..inner * copies).nullified(keep);
for lane in 0..inner * copies {
let expected = served_key(&root, &scope, &arena, inner, lane, reverse, copies, keep);
assert_eq!(cache_key(&dispatch.lane(lane)), expected, "lane {lane} reverse {reverse} keep {keep:?}");
let via_serve = dispatch.lane(lane).with_serve(|ctx| cache_key(ctx));
assert_eq!(via_serve, expected, "with_serve for lane {lane} reverse {reverse} keep {keep:?}");
}
}
}
}
#[test]
fn serve_at_builds_the_refined_chain() {
let arena = Arena::new(1 << 12).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let root = ContextImpl::root(&scope);
let dispatch = Dispatch::new(&root, LaneMap::open(), 0..6).sized(6).refined(3, false).unwrap();
for (lane, expected) in [(0u64, vec![0usize]), (1, vec![1]), (4, vec![1, 1]), (5, vec![2, 1])] {
let served = dispatch.serve_at(lane).unwrap();
let chain: Vec<usize> = served.try_index().unwrap().collect();
assert_eq!(chain, expected, "lane {lane}");
assert_eq!(served.try_index().unwrap().nth(1).unwrap_or(0), (lane / 3) as usize, "copy of lane {lane}");
}
}
#[test]
fn a_map_decomposes_and_reverses() {
let map = LaneMap::flat(12).refined(4, true).unwrap();
assert_eq!(map.depth(), 2);
assert_eq!(map.total(), 12);
assert_eq!((map.level(5, 0), map.level(5, 1)), (1, 1), "lane 5 is inner 1 of copy 1, reversed among 3 copies");
assert_eq!(map.level(11, 1), 0, "the last lane is the last copy, which reversal makes copy 0");
assert!(LaneMap::flat(10).refined(4, false).is_none(), "a level is a whole number of copies");
}
}
@@ -29,11 +29,18 @@ impl GraphError {
}
pub fn traced(mut self, input_index: usize) -> Self {
// The past-end signal ends a drain rather than reporting a fault, so nobody reads where it
// came from, and every level of every lane would otherwise grow a trace nobody looks at
if self.kind == ErrorKind::PastEnd {
return self;
}
self.trace.push(input_index);
self
}
pub fn past_end() -> Self {
#[cfg(debug_assertions)]
trace_past_end("past_end()", 0, 0);
Self {
kind: ErrorKind::PastEnd,
trace: Vec::new(),
@@ -120,6 +127,8 @@ impl<T> GPoll<T> {
boxed.1.trace.push(input);
GPoll::Fallback(boxed)
}
// The past-end signal ends a drain rather than reporting a fault, so its trace is never read
GPoll::Error(error) if error.kind == ErrorKind::PastEnd => GPoll::Error(error),
GPoll::Error(mut e) => {
e.trace.push(input);
GPoll::Error(e)
@@ -288,3 +297,25 @@ mod tests {
assert!(matches!(GPoll::<u32>::from(interrupt), GPoll::Error(e) if e.kind == "boom"));
}
}
/// Debug trace of a past-end signal ending a level at its first lane, under
/// `GRAPHENE_PASTEND_TRACE`: the site and the node frames of the backtrace.
#[cfg(debug_assertions)]
pub fn trace_past_end(site: &str, lane: usize, start: u64) {
static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
static COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
if !*ENABLED.get_or_init(|| std::env::var_os("GRAPHENE_PASTEND_TRACE").is_some()) {
return;
}
if COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= 40 {
return;
}
let backtrace = std::backtrace::Backtrace::force_capture().to_string();
let frames: Vec<&str> = backtrace
.lines()
.filter(|line| line.contains("_nodes::") || line.contains("gcore::") || line.contains("graphic_nodes") || line.contains("core_types::record"))
.map(|line| line.trim().split("core_types::registry::SharedSource").next().unwrap_or(line).trim_end_matches(['<', ':']))
.take(12)
.collect();
eprintln!("pastend> {site} lane {lane} start {start}\n{}", frames.join("\n"));
}
+3 -4
View File
@@ -5,6 +5,7 @@ pub mod attribute;
pub mod bounds;
pub mod consts;
pub mod context;
pub mod dispatch;
pub mod extent;
pub mod gpoll;
pub mod lane;
@@ -13,7 +14,6 @@ pub mod math;
pub mod memo;
pub mod misc;
pub mod node;
pub mod none;
pub mod ops;
pub mod record;
pub mod registry;
@@ -32,9 +32,8 @@ pub use dyn_any::{StaticTypeSized, WasmNotSend, WasmNotSync};
pub use graphene_hash;
pub use graphene_hash::CacheHash;
pub use list::{
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_TEXT_FRAME, ATTR_END, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC,
ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION,
ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TRANSFORM, ATTR_TYPE,
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_TEXT_FRAME, ATTR_END, ATTR_FONT_SIZE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT,
ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TRANSFORM, ATTR_TYPE,
};
pub use memo::MemoHash;
pub use no_std_types::AsU32;
+19 -181
View File
@@ -1,8 +1,7 @@
use crate::attribute::Attribute as _;
use crate::bounds::{BoundingBox, RenderBoundingBox};
use crate::transform::ApplyTransform;
use crate::uuid::NodeId;
use dyn_any::{DynAny, StaticType, StaticTypeSized};
use dyn_any::StaticType;
use glam::DAffine2;
use graphene_hash::CacheHash;
use std::fmt::Debug;
@@ -23,6 +22,8 @@ pub const ATTR_OPACITY_FILL: &str = crate::attribute::OpacityFill::NAME;
pub const ATTR_CLIPPING_MASK: &str = crate::attribute::ClippingMask::NAME;
pub const ATTR_EDITOR_LAYER_PATH: &str = crate::attribute::EditorLayerPath::NAME;
pub const ATTR_EDITOR_TEXT_FRAME: &str = crate::attribute::EditorTextFrame::NAME;
pub const ATTR_POSITION: &str = crate::attribute::Position::NAME;
pub const ATTR_MIDPOINT: &str = crate::attribute::Midpoint::NAME;
pub const ATTR_START: &str = crate::attribute::Start::NAME;
pub const ATTR_END: &str = crate::attribute::End::NAME;
pub const ATTR_NAME: &str = crate::attribute::Name::NAME;
@@ -37,84 +38,10 @@ pub const ATTR_LETTER_SPACING: &str = crate::attribute::LetterSpacing::NAME;
pub const ATTR_MAX_WIDTH: &str = crate::attribute::MaxWidth::NAME;
pub const ATTR_MAX_HEIGHT: &str = crate::attribute::MaxHeight::NAME;
pub const ATTR_LETTER_TILT: &str = crate::attribute::LetterTilt::NAME;
// Name aliases for markers declared below core-types, so code here and in
// sibling crates can spell the name without depending on the owning crate.
// The marker, and with it the value type and the default, lives in the crate
// named beside each name; these are the string only.
// vector-types (gradient and stroke coverage):
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
pub const ATTR_GRADIENT_HUE_DIRECTION: &str = "gradient_hue_direction";
pub const ATTR_GRADIENT_INTERPOLATION: &str = "gradient_interpolation";
pub const ATTR_GRADIENT_CYCLIC: &str = "gradient_cyclic";
pub const ATTR_POSITION: &str = "position";
pub const ATTR_MIDPOINT: &str = "midpoint";
pub const ATTR_WEIGHT: &str = "weight";
pub const ATTR_DASH_OFFSET: &str = "dash_offset";
pub const ATTR_CAP: &str = "cap";
pub const ATTR_JOIN: &str = "join";
pub const ATTR_JOIN_MITER_LIMIT: &str = "join_miter_limit";
pub const ATTR_ALIGN: &str = "align";
// graphic-types (paint):
pub const ATTR_APPEARANCE: &str = "appearance";
pub const ATTR_PAINT: &str = "paint";
// vector-types (stroke coverage, value type is not `Copy` so it has no marker yet):
pub const ATTR_DASH_PATTERN: &str = "dash_pattern";
// brush-types (per-stroke styling):
pub const ATTR_COLOR: &str = "color";
pub const ATTR_DIAMETER: &str = "diameter";
pub const ATTR_HARDNESS: &str = "hardness";
pub const ATTR_FLOW: &str = "flow";
// =====================
// TYPE: NodeIdPath
// =====================
/// A single path of `NodeId`s locating a node (or its owning layer) within the nested document graph.
/// Wraps a `List<NodeId>` so it flows as one rank-0 value (`Item<NodeIdPath>`) rather than a rank-1
/// `List<NodeId>` that the element-wise machinery would wrongly zip over per ID.
#[derive(Default, Debug, Clone, PartialEq, CacheHash, DynAny)]
pub struct NodeIdPath(pub List<NodeId>);
impl From<Vec<NodeId>> for NodeIdPath {
fn from(ids: Vec<NodeId>) -> Self {
Self(ids.into_iter().map(Item::new_from_element).collect())
}
}
// ================
// TYPE: Bundle
// ================
/// A whole `List<T>` treated as one rank-0 value (`Item<Bundle<T>>`) rather than a rank-1 `List<T>`.
/// Bundling a collection lets it pass through a connector that selects or carries the entire collection as one opaque
/// cell (such as a Switch branch), instead of the element-wise machinery zipping over it per element.
#[derive(Clone, Debug, PartialEq)]
pub struct Bundle<T>(pub List<T>);
impl<T> Default for Bundle<T> {
fn default() -> Self {
Self(List::default())
}
}
impl<T: CacheHash> CacheHash for Bundle<T> {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.0.cache_hash(state);
}
}
impl<T> From<List<T>> for Bundle<T> {
fn from(list: List<T>) -> Self {
Self(list)
}
}
unsafe impl<T: StaticTypeSized> StaticType for Bundle<T> {
type Static = Bundle<T::Static>;
}
pub const ATTR_COLOR: &str = crate::attribute::BrushColor::NAME;
pub const ATTR_DIAMETER: &str = crate::attribute::Diameter::NAME;
pub const ATTR_HARDNESS: &str = crate::attribute::Hardness::NAME;
pub const ATTR_FLOW: &str = crate::attribute::Flow::NAME;
// ===========================
// Implicit attribute defaults
@@ -160,13 +87,6 @@ pub trait AnyAttributeValue: std::any::Any + Send + Sync {
/// Returns a debug-formatted string representation of this value.
fn display_string(&self) -> String;
/// Hashes this value into the given hasher (object-safe wrapper around `CacheHash`).
fn cache_hash_dyn(&self, state: &mut dyn core::hash::Hasher);
/// Compares this value to another for value-by-value equality (object-safe wrapper around `PartialEq`).
/// Returns `false` if the underlying types differ.
fn eq_dyn(&self, other: &dyn AnyAttributeValue) -> bool;
/// Wraps this scalar value into a new attribute, preceded by `preceding_defaults` implicit defaults for `key`.
fn into_attribute(self: Box<Self>, key: &str, preceding_defaults: usize) -> Box<dyn AnyAttribute>;
}
@@ -203,17 +123,6 @@ impl<T: Clone + Send + Sync + Default + Sized + Debug + PartialEq + CacheHash +
format!("{:?}", self)
}
/// Hashes this value into the given hasher (object-safe wrapper around `CacheHash`).
fn cache_hash_dyn(&self, state: &mut dyn core::hash::Hasher) {
self.cache_hash(&mut DynHasher(state));
}
/// Compares this value to another for value-by-value equality (object-safe wrapper around `PartialEq`).
/// Returns `false` if the underlying types differ.
fn eq_dyn(&self, other: &dyn AnyAttributeValue) -> bool {
other.as_any().downcast_ref::<Self>().is_some_and(|other| self == other)
}
/// Wraps this scalar value into a new attribute, preceded by `preceding_defaults` implicit defaults for `key`.
fn into_attribute(self: Box<Self>, key: &str, preceding_defaults: usize) -> Box<dyn AnyAttribute> {
let mut attribute: Box<dyn AnyAttribute> = Box::new(Attribute::<T>(Vec::with_capacity(preceding_defaults + 1)));
@@ -481,7 +390,8 @@ unsafe impl StaticType for AttributeDyn {
// ==================
/// Type-erased single attribute value, used as a node graph parameter type.
/// Lets a node accept a value of any valid concrete type via the auto-inserted input adapter conversion without monomorphizing over the value type.
/// Lets a node accept a value of any concrete type via the auto-inserted `Convert<AttributeValueDyn, ()>`
/// without monomorphizing over the value type.
pub struct AttributeValueDyn(pub Box<dyn AnyAttributeValue>);
impl Clone for AttributeValueDyn {
@@ -622,17 +532,6 @@ impl Debug for ItemAttributeValues {
}
}
impl PartialEq for ItemAttributeValues {
fn eq(&self, other: &Self) -> bool {
self.0.len() == other.0.len()
&& self
.0
.iter()
.zip(&other.0)
.all(|((self_key, self_value), (other_key, other_value))| self_key == other_key && self_value.eq_dyn(other_value.as_ref()))
}
}
impl ItemAttributeValues {
/// Creates an empty set of attributes.
pub fn new() -> Self {
@@ -713,11 +612,6 @@ impl ItemAttributeValues {
self.0.iter().find_map(|(existing_key, value)| if existing_key == key { Some((**value).as_any()) } else { None })
}
/// Returns an iterator over key and type-erased value pairs of all stored attributes, in insertion order.
pub fn iter_any(&self) -> impl Iterator<Item = (&str, &dyn std::any::Any)> {
self.0.iter().map(|(key, value)| (key.as_str(), (**value).as_any()))
}
/// Returns a debug-formatted string representation of the attribute value for the given key, if it exists.
/// The `overrides` function can provide custom formatting for specific type.
pub fn display_value(&self, key: &str, overrides: fn(&dyn std::any::Any) -> Option<String>) -> Option<String> {
@@ -996,7 +890,10 @@ impl Attributes {
/// Elements are stored contiguously in a `Vec<T>`, while attributes live in an internal
/// [`Attributes`] store that keeps one attribute per attribute key. Items are accessed by
/// index through element/attribute accessor methods, or consumed as owned [`Item`]s via iteration.
#[derive(Clone, Debug)]
// The list carries its lifetime only through T, so its parameter projects: substituting
// T's static form substitutes the list's and keeps the layout identical.
#[derive(Clone, Debug, dyn_any::DynAny)]
#[dyn_any_derive(project)]
pub struct List<T> {
element: Vec<T>,
attributes: Attributes,
@@ -1309,12 +1206,6 @@ impl<T> ApplyTransform for List<T> {
}
}
// SAFETY: the list carries its lifetime only through T, so substituting T's
// static form substitutes the list's and keeps the layout identical.
unsafe impl<T: StaticTypeSized> StaticType for List<T> {
type Static = List<T::Static>;
}
impl<T> FromIterator<Item<T>> for List<T> {
/// Collects an iterator of [`Item`]s into a [`List`], pre-allocating based on the iterator's size hint.
fn from_iter<I: IntoIterator<Item = Item<T>>>(iter: I) -> Self {
@@ -1337,40 +1228,23 @@ impl<T> FromIterator<Item<T>> for List<T> {
/// An owned item containing an element of type `T` and a set of type-erased scalar attributes.
///
/// Used to build individual items before pushing them into a [`List`], or when consuming items out of a list via [`IntoIterator`].
#[derive(Clone, Debug, PartialEq)]
// As for `List`, the item's lifetime rides its element alone, so the parameter projects.
#[derive(Clone, Debug, dyn_any::DynAny)]
#[dyn_any_derive(project)]
pub struct Item<T> {
element: T,
attributes: ItemAttributeValues,
}
impl<T: BoundingBox> BoundingBox for Item<T> {
/// Computes the element's bounding box, composing the item's transform attribute with the given transform.
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM);
self.element().bounding_box(transform * item_transform, include_stroke)
}
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM);
self.element().thumbnail_bounding_box(transform * item_transform, include_stroke)
}
}
impl<T: Default> Default for Item<T> {
fn default() -> Self {
Self::new_from_element(T::default())
}
}
impl<T: CacheHash> CacheHash for Item<T> {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.element.cache_hash(state);
// Hash every attribute (key + value) so attribute changes invalidate downstream caches, mirroring `List`
for (key, attribute) in &self.attributes.0 {
std::hash::Hash::hash(key.as_str(), state);
attribute.cache_hash_dyn(state);
}
impl<T: PartialEq> PartialEq for Item<T> {
fn eq(&self, other: &Self) -> bool {
self.element == other.element
}
}
@@ -1462,42 +1336,6 @@ impl<T> Item<T> {
}
}
impl<T> From<T> for Item<T> {
fn from(element: T) -> Self {
Self::new_from_element(element)
}
}
impl<T> From<Item<T>> for List<T> {
fn from(item: Item<T>) -> Self {
Self::new_from_item(item)
}
}
impl<T> From<T> for List<T> {
fn from(element: T) -> Self {
Self::new_from_element(element)
}
}
impl<T> ApplyTransform for Item<T> {
/// Right-multiplies the modification into the item's transform attribute.
fn apply_transform(&mut self, modification: &DAffine2) {
let transform = self.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM);
*transform *= *modification;
}
/// Left-multiplies the modification into the item's transform attribute.
fn left_apply_transform(&mut self, modification: &DAffine2) {
let transform = self.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM);
*transform = *modification * *transform;
}
}
unsafe impl<T: StaticTypeSized> StaticType for Item<T> {
type Static = Item<T::Static>;
}
// ===========
// ItemIter<T>
// ===========
+137 -63
View File
@@ -3,7 +3,7 @@ use crate::gpoll::{Extent, Finality, GPoll, GraphError, Interrupt, Level};
use std::cell::Cell;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::ops::{Deref, Range};
use std::ops::Deref;
#[derive(Debug)]
pub enum BatchStatus<'a> {
@@ -62,6 +62,12 @@ impl<'a> RecordBatch<'a> {
}
}
/// No lanes of `layout`: nothing is read, so no frames are needed.
pub fn empty(layout: &'a crate::record::Layout) -> Self {
// SAFETY: zero lanes read no frame.
unsafe { Self::new(std::ptr::NonNull::<u8>::dangling().as_ptr(), 0, layout) }
}
pub fn len(&self) -> usize {
self.len
}
@@ -78,6 +84,19 @@ impl<'a> RecordBatch<'a> {
self.frames
}
/// The lanes in `range` as a view of their own, which is these frames at an offset rather
/// than a copy of them. `None` where the range leaves the batch.
pub fn slice(&self, range: std::ops::Range<usize>) -> Option<RecordBatch<'a>> {
(range.start <= range.end && range.end <= self.len).then(|| RecordBatch {
// SAFETY: in-bounds by the check above, at the stride the constructor established.
frames: unsafe { self.frames.add(range.start * self.stride) },
stride: self.stride,
len: range.end - range.start,
layout: self.layout,
_lifetime: PhantomData,
})
}
pub fn get(&self, lane: usize) -> RecordLane<'a> {
assert!(lane < self.len, "lane {lane} out of bounds for a batch of {}", self.len);
RecordLane {
@@ -108,11 +127,27 @@ impl<'a> RecordBatchMut<'a> {
/// Minted only by a [`crate::record::SlotRun`] finishing its served lanes,
/// which serve in ascending order with no gaps, so the initialized prefix is
/// a fact rather than a contract.
#[track_caller]
pub(crate) fn new(scratch: &'a mut [MaybeUninit<u64>], len: usize, layout: &'a crate::record::Layout) -> Self {
debug_assert!(len.checked_mul(layout.lane_stride()).is_some_and(|need| need <= scratch.len() * 8));
#[cfg(debug_assertions)]
if layout.element.parked {
let stride = layout.lane_stride();
for lane in 0..len {
// SAFETY: the lane is within the capacity checked above.
let header = unsafe { scratch.as_ptr().cast::<u8>().add(lane * stride).cast::<usize>().read() };
assert!(header != 0, "batch lane {lane} of {len} has no parked element (stride {stride}, {} fields at {}", layout.fields.len(), std::panic::Location::caller());
}
}
Self { scratch, len, layout }
}
/// A batch over lanes the caller imaged itself: `len` complete records of
/// `layout`, packed at its stride from the start of `scratch`.
pub fn filled(scratch: &'a mut [MaybeUninit<u64>], len: usize, layout: &'a crate::record::Layout) -> Self {
Self::new(scratch, len, layout)
}
pub fn len(&self) -> usize {
self.len
}
@@ -188,20 +223,48 @@ impl<'a> RecordLane<'a> {
/// One lane of a materialized level, element-typed. In a kernel's element
/// position the output frame is copied from this lane.
///
/// The subject is substitutable: [`map_element`](Self::map_element) keeps the
/// lane's whole record and swaps what it is a record *of*, so a node that
/// rewrites its element still carries every column it never mentions. `Attr`
/// members of the kernel's return tuple remain overrides layered on top.
#[derive(Debug)]
pub struct Lane<'a, T> {
lane: RecordLane<'a>,
_element: PhantomData<T>,
/// `Some` once the subject was replaced; the carried record's own element
/// is then ignored in favour of this value.
subject: Option<T>,
}
// A view regardless of `T`: copying a lane copies no record.
impl<T> Clone for Lane<'_, T> {
// A lane that carries no substitute is still a pure view: copying it copies no
// record. One holding a replaced subject owns it, so it clones with the value.
impl<T: Clone> Clone for Lane<'_, T> {
fn clone(&self) -> Self {
*self
Self {
lane: self.lane,
subject: self.subject.clone(),
}
}
}
impl<T> Copy for Lane<'_, T> {}
impl<T: Copy> Copy for Lane<'_, T> {}
impl<'a, T> Lane<'a, T> {
/// The same source lane with a different subject. The record's columns are
/// carried unchanged; only the element becomes `element`.
pub fn map_element<U>(self, element: U) -> Lane<'a, U> {
Lane {
lane: self.lane,
subject: Some(element),
}
}
/// The substituted subject, or `None` where this lane still stands for its
/// source record's own element.
pub fn into_element(self) -> Option<T> {
self.subject
}
}
impl<'a, T> Deref for Lane<'a, T> {
type Target = RecordLane<'a>;
@@ -272,11 +335,27 @@ impl<'a, T> List<'a, T> {
unsafe { crate::record::borrow_element::<T>(self.batch.get(index).rec()) }
}
/// The element at `index` borrowed for the arena's lifetime rather than the batch's.
/// A parked element is a pointer in the frame to a payload the arena owns, so the
/// payload outlives the frame that named it and a kernel may hand out slices of it.
/// Panics where `T` is written inline, whose bytes live in the frame and die with it.
pub fn element_arena<'arena>(&self, index: usize, arena: &'arena crate::arena::Arena) -> &'arena T {
assert!(
crate::record::element_parked::<T>(),
"`{}` is written inline, so its bytes live in the frame rather than the arena",
std::any::type_name::<T>()
);
let _ = arena;
// SAFETY: `List::new` established that `T` is the batch's element type, and a
// parked element's payload is arena-resident, so it lives for `'arena`.
unsafe { crate::record::borrow_element::<T>(self.batch.get(index).rec()) }
}
/// Lane `index`'s record, for attribute reads beside the element.
pub fn lane(&self, index: usize) -> Lane<'a, T> {
Lane {
lane: self.batch.get(index),
_element: PhantomData,
subject: None,
}
}
@@ -323,7 +402,7 @@ pub trait Node<Input> {
/// takes exactly its own frame out of the caller's free space.
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll<crate::record::Served<'e>>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>;
Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>;
/// The count of items at one absolute nesting level (innermost `0`). The
/// leveled primitive a structure node overrides to report a pushed level's
@@ -331,7 +410,7 @@ pub trait Node<Input> {
/// `GPoll` status axis.
fn extent_at<'e>(&self, _input: &Input, _level: u8, _frames: &crate::record::Frames<'e>) -> GPoll<Extent>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
GPoll::Final(Extent::Exactly(1))
}
@@ -341,7 +420,7 @@ pub trait Node<Input> {
/// domain's flat count. Consumers query this; nodes only write `extent_at`.
fn extent<'e>(&self, input: &Input, at: Level, frames: &crate::record::Frames<'e>) -> GPoll<Extent>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
let product =
|range: core::ops::Range<u8>, frames: &crate::record::Frames<'e>| range.fold(GPoll::Final(Extent::Exactly(1)), |acc, level| Extent::mul(acc, self.extent_at(input, level, frames)));
@@ -375,17 +454,19 @@ pub trait Node<Input> {
/// Installs this node's resolved record layout; a no-op unless it produces records.
fn set_layout(&mut self, _layout: crate::record::RecordLayout) {}
/// Batched evaluation of `range` into caller-provided frame storage of
/// Batched evaluation of the dispatch's range into caller-provided frame storage of
/// `range.len() * layout.lane_stride()` bytes; see [`BatchStatus`]. The
/// default advertises no support and drivers fall back to per-lane serves
/// with copy-out ([`crate::record::fill_frames`]); overrides exist to beat
/// that loop (resident lanes, direct fills, fewer erased calls), never for
/// correctness.
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a>
fn eval_batch<'a, 'e, 'r>(&'a self, dispatch: crate::dispatch::Dispatch<'e>, scratch: Option<&'r mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'r>
where
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
'a: 'r,
'e: 'r,
Input: crate::dispatch::AsDispatch<'e> + InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
let _ = (input, range, scratch, frames);
let _ = (dispatch, scratch, frames);
BatchStatus::Unbatched
}
}
@@ -396,14 +477,14 @@ where
{
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll<crate::record::Served<'e>>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).serve(input, slot)
}
fn extent_at<'e>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'e>) -> GPoll<Extent>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).extent_at(input, level, frames)
}
@@ -416,11 +497,13 @@ where
(**self).layout()
}
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a>
fn eval_batch<'a, 'e, 'r>(&'a self, dispatch: crate::dispatch::Dispatch<'e>, scratch: Option<&'r mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'r>
where
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
'a: 'r,
'e: 'r,
Input: crate::dispatch::AsDispatch<'e> + InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).eval_batch(input, range, scratch, frames)
(**self).eval_batch(dispatch, scratch, frames)
}
}
@@ -430,14 +513,14 @@ where
{
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll<crate::record::Served<'e>>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).serve(input, slot)
}
fn extent_at<'e>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'e>) -> GPoll<Extent>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).extent_at(input, level, frames)
}
@@ -450,11 +533,13 @@ where
(**self).layout()
}
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a>
fn eval_batch<'a, 'e, 'r>(&'a self, dispatch: crate::dispatch::Dispatch<'e>, scratch: Option<&'r mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'r>
where
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
'a: 'r,
'e: 'r,
Input: crate::dispatch::AsDispatch<'e> + InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).eval_batch(input, range, scratch, frames)
(**self).eval_batch(dispatch, scratch, frames)
}
}
@@ -464,14 +549,14 @@ where
{
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> GPoll<crate::record::Served<'e>>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).serve(input, slot)
}
fn extent_at<'e>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'e>) -> GPoll<Extent>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).extent_at(input, level, frames)
}
@@ -484,11 +569,13 @@ where
(**self).layout()
}
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'a>
fn eval_batch<'a, 'e, 'r>(&'a self, dispatch: crate::dispatch::Dispatch<'e>, scratch: Option<&'r mut [MaybeUninit<u64>]>, frames: &crate::record::Frames<'e>) -> BatchStatus<'r>
where
Input: InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
'a: 'r,
'e: 'r,
Input: crate::dispatch::AsDispatch<'e> + InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
(**self).eval_batch(input, range, scratch, frames)
(**self).eval_batch(dispatch, scratch, frames)
}
}
@@ -524,7 +611,7 @@ impl StatusCell {
#[inline(always)]
pub fn eval_input<'e, Input, N: Node<Input> + ?Sized>(&self, input_index: usize, node: &N, input: &Input, frames: &crate::record::Frames<'e>) -> Result<crate::record::RecordValue<'e>, Interrupt>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
let slot = frames.claim(node.layout());
match node.serve(input, slot) {
@@ -542,7 +629,10 @@ impl StatusCell {
}
GPoll::Pending => Err(Interrupt::Pending),
GPoll::Error(mut error) => {
error.trace.push(input_index);
// A drain's past-end signal carries no trace; see `GraphError::traced`
if error.kind != crate::gpoll::ErrorKind::PastEnd {
error.trace.push(input_index);
}
Err(Interrupt::Error(error))
}
}
@@ -617,7 +707,7 @@ impl<'a, 'f, N> LazyInput<'a, 'f, N> {
pub fn extent<'e, Input>(&self, ctx: &Input, at: Level) -> GPoll<Extent>
where
N: Node<Input>,
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
'f: 'e,
{
self.node.extent(ctx, at, self.frames)
@@ -627,59 +717,43 @@ impl<'a, 'f, N> LazyInput<'a, 'f, N> {
#[cfg(test)]
mod tests {
use super::*;
use crate::arena::Arena;
use crate::context::ExtractArena;
use crate::context::{ContextImpl, EvalScope, ExtractIndices};
use crate::dispatch::{AsDispatch, LaneMap};
use crate::record::{LiftedSource, serve_input};
#[derive(Clone, Copy)]
struct TestInput<'a> {
index: u64,
arena: &'a Arena,
}
impl InjectIndex for TestInput<'_> {
fn set_index(&mut self, index: u64) {
self.index = index;
}
}
impl<'a> ExtractArena for TestInput<'a> {
type ArenaRef = &'a Arena;
fn arena(&self) -> &'a Arena {
self.arena
}
}
fn double<'a>() -> LiftedSource<u64, impl Fn(&TestInput<'a>) -> GPoll<u64>> {
LiftedSource::new(|input: &TestInput<'a>| GPoll::Final(input.index * 2))
fn double() -> LiftedSource<u64, impl for<'c> Fn(&ContextImpl<'c>) -> GPoll<u64>> {
LiftedSource::new(|input: &ContextImpl<'_>| GPoll::Final(input.innermost_index() * 2))
}
#[test]
fn the_default_advertises_no_batch_support() {
let frames = crate::record::test_frames(1 << 16);
let arena = Arena::new(1024).unwrap();
let input = TestInput { index: 0, arena: &arena };
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let input = ContextImpl::root(&scope);
let mut scratch = [const { MaybeUninit::uninit() }; 4];
let node = double();
assert!(matches!(node.eval_batch(&input, 2..6, Some(&mut scratch), &frames), BatchStatus::Unbatched));
assert!(matches!(node.eval_batch(&input, 2..6, None, &frames), BatchStatus::Unbatched));
assert!(matches!(node.eval_batch(input.dispatch(LaneMap::open(), 2..6), Some(&mut scratch), &frames), BatchStatus::Unbatched));
assert!(matches!(node.eval_batch(input.dispatch(LaneMap::open(), 2..6), None, &frames), BatchStatus::Unbatched));
}
#[test]
fn trait_is_object_safe_across_erased_edges() {
let arena = Arena::new(1024).unwrap();
let input = TestInput { index: 21, arena: &arena };
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let input = ContextImpl::root(&scope).replaced(21);
let node = double();
let layout = Node::<TestInput>::layout(&node).clone();
let erased: Box<dyn Node<TestInput>> = Box::new(node);
let layout = Node::<ContextImpl<'_>>::layout(&node).clone();
let erased: Box<dyn for<'c> Node<ContextImpl<'c>>> = Box::new(node);
let frames = crate::record::test_frames(1 << 12);
let GPoll::Final(value) = serve_input(&*erased, &input, &frames) else {
panic!("the erased edge must serve a final record");
};
// SAFETY: the record was served at `layout`, whose element is the output.
assert_eq!(unsafe { crate::record::read_element::<u64>(layout.rec(&value)) }, 42);
assert!(matches!(erased.eval_batch(&input, 0..2, None, &frames), BatchStatus::Unbatched));
assert!(matches!(erased.eval_batch(input.dispatch(LaneMap::open(), 0..2), None, &frames), BatchStatus::Unbatched));
}
}
@@ -1,9 +0,0 @@
use dyn_any::DynAny;
use graphene_hash::CacheHash;
/// An artist's declaration that there is no content here, distinct from the `()` type's "nothing was wired".
/// Visually represented as a red slash over a white background. Akin to the CSS `none` keyword.
///
/// Because its name matches the Rust prelude's `Option::None` variant, we always reference this as `none::None`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, CacheHash, DynAny)]
pub struct None;
+10 -1
View File
@@ -31,7 +31,16 @@ macro_rules! impl_convert_to_string {
)*
};
}
impl_convert_to_string!(f32, u32, u64, i32, i64, bool, DVec2, DAffine2, String, IVec2, i8, u8, u16, i16, u128, i128, usize, isize);
impl_convert_to_string!(f32, i8, u8, i16, u16, i32, u32, i64, u64, i128, u128, isize, usize, bool, String, DVec2, IVec2, DAffine2);
/// Owns a borrowed element, so a node lending slices of an arena-parked string can still
/// feed a consumer that wants the string itself.
impl Convert<String, ()> for &str {
#[inline]
fn convert(self, _: Footprint, _converter: ()) -> String {
self.to_string()
}
}
// Denoised so 0.1 + 0.2 reaches the string as "0.3" rather than "0.30000000000000004"
impl Convert<String, ()> for f64 {
@@ -112,6 +112,7 @@ impl<'e> Frames<'e> {
frame,
free: self.reborrow(),
filled_fields: false,
carried_empty: false,
}
}
@@ -182,4 +183,48 @@ mod tests {
}
assert!(addresses.windows(2).all(|pair| pair[0] == pair[1]), "each claim reuses the same region");
}
#[test]
#[should_panic(expected = "carried an empty plan and filled nothing")]
fn carrying_an_empty_plan_and_filling_nothing_refuses_to_close() {
// The shape that served uninitialized bytes before this guard existed: a
// layout that DECLARES a field, a carry whose plan turned out empty, and
// nothing else to fill it. The field would otherwise be the prior frame's
// bytes, which for a reference field is an uninitialized read.
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")]);
let mut frame_arena = FrameArena::new();
frame_arena.reserve(1 << 10);
let frames = frame_arena.frames();
let scope = frames.scope();
let mut claim = scope.claim(&layout);
let value = crate::record::access::RecordValue::zeroed();
let src = layout.rec(&value);
// SAFETY: an empty plan reads nothing from `src`; closing afterwards is
// what the guard refuses.
unsafe { claim.carry(src, &[]) };
// SAFETY: the assertion fires before anything reads the unfilled field.
let _ = unsafe { claim.finish() };
}
#[test]
fn an_empty_carry_whose_fields_are_written_closes_normally() {
// The control that pins what the guard actually tracks: the same empty
// carry, but the declared field is then written. Closing must succeed, so
// the guard is about a field left unfilled rather than about the carry.
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[f64_field("opacity")]);
let offset = layout.fields.first().expect("the fixture declares one field").offset;
let mut frame_arena = FrameArena::new();
frame_arena.reserve(1 << 10);
let frames = frame_arena.frames();
let scope = frames.scope();
let mut claim = scope.claim(&layout);
let value = crate::record::access::RecordValue::zeroed();
let src = layout.rec(&value);
// SAFETY: an empty plan reads nothing from `src`.
unsafe { claim.carry(src, &[]) };
// SAFETY: `offset` is this layout's own resolved offset for an f64 field.
unsafe { claim.attr_at(offset, 0.5_f64) };
// SAFETY: the write above filled the declared field.
let _ = unsafe { claim.finish() };
}
}
@@ -4,6 +4,7 @@ use super::access::{Rec, RecordValue, read_element};
use super::frames::Frames;
use super::layout::Layout;
use super::serve::{FrameClaim, Served, serve_input};
use crate::dispatch::{AsDispatch, Dispatch, LaneMap};
use crate::gpoll::GPoll;
use crate::node::Node;
@@ -15,32 +16,154 @@ use crate::node::Node;
pub trait DerivedRecordInput<'derived, C> {
fn eval_derived(&self, cell: &crate::node::StatusCell, input_index: usize, ctx: &C, frames: &Frames<'derived>) -> Result<RecordValue<'derived>, crate::gpoll::Interrupt>;
fn extent_at_derived(&self, ctx: &C, level: u8, frames: &Frames<'derived>) -> GPoll<crate::gpoll::Extent>;
fn eval_batch_derived<'a, 'r>(&'a self, dispatch: Dispatch<'derived>, scratch: Option<&'r mut [std::mem::MaybeUninit<u64>]>, frames: &Frames<'derived>) -> crate::node::BatchStatus<'r>
where
'a: 'r,
'derived: 'r,
C: AsDispatch<'derived> + crate::context::InjectIndex + Copy;
fn serve_derived<'l>(&self, ctx: &C, slot: crate::record::FrameClaim<'derived, 'l>) -> GPoll<crate::record::Served<'derived>>;
}
impl<'derived, C, N> DerivedRecordInput<'derived, C> for N
where
N: Node<C>,
C: crate::context::ExtractArena<ArenaRef = &'derived crate::arena::Arena>,
C: crate::dispatch::AsDispatch<'derived> + crate::context::ExtractArena<ArenaRef = &'derived crate::arena::Arena>,
{
fn eval_derived(&self, cell: &crate::node::StatusCell, input_index: usize, ctx: &C, frames: &Frames<'derived>) -> Result<RecordValue<'derived>, crate::gpoll::Interrupt> {
cell.eval_input(input_index, self, ctx, frames)
}
fn extent_at_derived(&self, ctx: &C, level: u8, frames: &Frames<'derived>) -> GPoll<crate::gpoll::Extent> {
self.extent_at(ctx, level, frames)
}
fn eval_batch_derived<'a, 'r>(&'a self, dispatch: Dispatch<'derived>, scratch: Option<&'r mut [std::mem::MaybeUninit<u64>]>, frames: &Frames<'derived>) -> crate::node::BatchStatus<'r>
where
'a: 'r,
'derived: 'r,
C: AsDispatch<'derived> + crate::context::InjectIndex + Copy,
{
self.eval_batch(dispatch, scratch, frames)
}
fn serve_derived<'l>(&self, ctx: &C, slot: crate::record::FrameClaim<'derived, 'l>) -> GPoll<crate::record::Served<'derived>> {
self.serve(ctx, slot)
}
}
/// Evaluates `node`'s batch at a derived context and hands the lanes back
/// through the caller's scratch: a batch borrowed at the derived lifetime
/// cannot outlive it, so a lent run is copied in and a filled scratch is
/// re-minted. The node is asked without scratch first, as the driver asks;
/// an unbatched answer hands the scratch to `unbatched`, the caller's own
/// lane loop, so a boundary keeps its hoisted loop where nothing lends.
pub fn forward_batch<'a, 'derived, C, N>(
node: &N,
ctx: &C,
range: std::ops::Range<u64>,
scratch: Option<&'a mut [std::mem::MaybeUninit<u64>]>,
frames: &Frames<'derived>,
layout: &'a Layout,
unbatched: impl FnOnce(&'a mut [std::mem::MaybeUninit<u64>]) -> crate::node::BatchStatus<'a>,
) -> crate::node::BatchStatus<'a>
where
N: DerivedRecordInput<'derived, C>,
C: AsDispatch<'derived> + crate::context::InjectIndex + Copy,
{
forward_dispatch(node, &ctx.dispatch(LaneMap::open(), range), scratch, frames, layout, unbatched)
}
/// [`forward_batch`] over a dispatch the caller already derived.
pub fn forward_dispatch<'a, 'derived, C, N>(
node: &N,
dispatch: &Dispatch<'derived>,
scratch: Option<&'a mut [std::mem::MaybeUninit<u64>]>,
frames: &Frames<'derived>,
layout: &'a Layout,
unbatched: impl FnOnce(&'a mut [std::mem::MaybeUninit<u64>]) -> crate::node::BatchStatus<'a>,
) -> crate::node::BatchStatus<'a>
where
N: DerivedRecordInput<'derived, C>,
C: AsDispatch<'derived> + crate::context::InjectIndex + Copy,
{
use crate::node::BatchStatus;
let range = dispatch.range();
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
return BatchStatus::InvalidRange;
};
let stride = layout.lane_stride();
let wants_fill = match node.eval_batch_derived(dispatch.clone(), None, frames) {
BatchStatus::Lent(batch, finality, hint) => {
let Some(scratch) = scratch else {
return BatchStatus::NeedBuffer;
};
if scratch.len() * 8 < len * stride {
return BatchStatus::InvalidRange;
}
let lanes = batch.len().min(len);
let base: *mut u8 = scratch.as_mut_ptr().cast();
for lane in 0..lanes {
// SAFETY: the lent lanes are live records of this layout, and the
// scratch holds `len` lanes at the layout's stride.
unsafe { std::ptr::copy_nonoverlapping(batch.get(lane).rec().ptr(), base.add(lane * stride), layout.size) };
}
// Lanes `0..lanes` were imaged above as records of this layout.
return BatchStatus::Filled(crate::node::RecordBatchMut::new(scratch, lanes, layout), finality, hint);
}
BatchStatus::NeedBuffer => true,
// The caller's own lane loop takes the scratch instead.
BatchStatus::Unbatched => {
return match scratch {
Some(scratch) => unbatched(scratch),
None => BatchStatus::NeedBuffer,
};
}
BatchStatus::Pending => return BatchStatus::Pending,
BatchStatus::Error(error) => return BatchStatus::Error(error),
BatchStatus::InvalidRange => return BatchStatus::InvalidRange,
BatchStatus::Filled(..) => return BatchStatus::Error(crate::gpoll::GraphError::new("a batch filled scratch it was not given")),
};
debug_assert!(wants_fill);
let Some(scratch) = scratch else {
return BatchStatus::NeedBuffer;
};
if scratch.len() * 8 < len * stride {
return BatchStatus::InvalidRange;
}
let filled = match node.eval_batch_derived(dispatch.clone(), Some(&mut *scratch), frames) {
BatchStatus::Filled(filled, finality, hint) => Ok((filled.len(), finality, hint)),
// A node that lends only once given scratch is served lane by lane instead.
BatchStatus::Lent(..) | BatchStatus::Unbatched | BatchStatus::NeedBuffer => Err(BatchStatus::Unbatched),
BatchStatus::Pending => Err(BatchStatus::Pending),
BatchStatus::Error(error) => Err(BatchStatus::Error(error)),
BatchStatus::InvalidRange => Err(BatchStatus::InvalidRange),
};
match filled {
// The node filled lanes `0..lanes` of this scratch as records of its layout, which is `layout`.
Ok((lanes, finality, hint)) => BatchStatus::Filled(crate::node::RecordBatchMut::new(scratch, lanes, layout), finality, hint),
Err(status) => status,
}
}
/// Fills caller scratch with one frame per lane of `range`: the input serves
/// into the lane's own region of the slab, and the lane's own frame space is
/// free again at the next lane, so the frame peak stays at one lane's need and
/// every lane's bytes are distinct.
pub fn fill_frames<'a, 'e, C, N>(node: &'a N, input: &C, range: std::ops::Range<u64>, scratch: Option<&'a mut [std::mem::MaybeUninit<u64>]>, frames: &Frames<'e>) -> crate::node::BatchStatus<'a>
/// the scratch grows only with the lanes.
pub fn fill_frames<'a, 'e, 'r, C, N>(node: &'a N, input: &C, range: std::ops::Range<u64>, scratch: Option<&'r mut [std::mem::MaybeUninit<u64>]>, frames: &Frames<'e>) -> crate::node::BatchStatus<'r>
where
C: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
'a: 'r,
C: AsDispatch<'e> + crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
N: Node<C>,
{
fill_dispatch::<C, N>(node, &input.dispatch(LaneMap::open(), range), scratch, frames)
}
/// [`fill_frames`] over a dispatch: each lane's context is rebuilt from it.
pub fn fill_dispatch<'a, 'e, 'r, C, N>(node: &'a N, dispatch: &Dispatch<'e>, scratch: Option<&'r mut [std::mem::MaybeUninit<u64>]>, frames: &Frames<'e>) -> crate::node::BatchStatus<'r>
where
'a: 'r,
C: AsDispatch<'e> + crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
N: Node<C>,
{
use crate::node::BatchStatus;
let range = dispatch.range();
let Some(scratch) = scratch else {
return BatchStatus::NeedBuffer;
};
@@ -50,11 +173,15 @@ where
let Some(mut run) = frames.run(scratch, len, node.layout()) else {
return BatchStatus::InvalidRange;
};
let mut local = *input;
let mut finality = crate::gpoll::Finality::AllFinal;
let mut hint = crate::gpoll::Extent::AtLeast(range.end as usize);
for lane in 0..len {
local.set_index(range.start + lane as u64);
let Some(local) = C::at_lane(dispatch, range.start + lane as u64) else {
return BatchStatus::Error(crate::gpoll::GraphError {
kind: crate::gpoll::ErrorKind::ArenaExhausted,
trace: Vec::new(),
});
};
let lane_frames = frames.scope();
let slot = run.slot(lane, &lane_frames);
let served = match node.serve(&local, slot) {
@@ -68,6 +195,8 @@ where
// A lane past a lower-bound level ends the data: the fill comes
// back short and the hint turns exact.
GPoll::Error(error) if error.kind == crate::gpoll::ErrorKind::PastEnd => {
#[cfg(debug_assertions)]
crate::gpoll::trace_past_end("fill_dispatch", lane, range.start);
hint = crate::gpoll::Extent::Exactly(range.start as usize + lane);
break;
}
@@ -81,12 +210,37 @@ where
/// The driver a consumer runs on a record input: a resident batch returns with
/// no allocation, a node's own batch impl gets `n * frame_bytes` of arena
/// scratch, and an unbatched input falls back to the [`fill_frames`] loop.
pub fn materialize_batch<'a, 'e, C, N>(node: &'a N, input: &'a C, range: std::ops::Range<u64>, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> crate::node::BatchStatus<'a>
pub fn materialize_batch<'a, 'e, 'r, C, N>(node: &'a N, input: &'a C, range: std::ops::Range<u64>, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> crate::node::BatchStatus<'r>
where
C: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
'a: 'r,
'e: 'r,
C: AsDispatch<'e> + crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
N: Node<C>,
{
let dispatch = input.dispatch(LaneMap::open(), range);
materialize_owned::<C, N>(node, dispatch, arena, frames)
}
/// [`materialize_batch`] over a dispatch the caller already derived.
pub fn materialize_dispatch<'a, 'e, 'r, C, N>(node: &'a N, dispatch: &Dispatch<'e>, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> crate::node::BatchStatus<'r>
where
'a: 'r,
'e: 'r,
C: AsDispatch<'e> + crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
N: Node<C>,
{
materialize_owned::<C, N>(node, dispatch.clone(), arena, frames)
}
fn materialize_owned<'a, 'e, 'r, C, N>(node: &'a N, dispatch: Dispatch<'e>, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> crate::node::BatchStatus<'r>
where
'a: 'r,
'e: 'r,
C: AsDispatch<'e> + crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
N: Node<C>,
{
use crate::node::BatchStatus;
let range = dispatch.range();
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
return BatchStatus::InvalidRange;
};
@@ -100,13 +254,40 @@ where
trace: Vec::new(),
})
};
match node.eval_batch(input, range.clone(), None, frames) {
let status = node.eval_batch(dispatch.clone(), None, frames);
#[cfg(debug_assertions)]
{
let consumer = BATCH_CONSUMER.with(|consumer| consumer.get());
let name = match consumer.is_empty() {
true => core::any::type_name::<N>(),
false => consumer,
};
let batched = !matches!(status, BatchStatus::Unbatched);
crate::record::input::tally_batch(name, batched, len);
}
match status {
BatchStatus::Unbatched => match arena.alloc_scratch::<u64>(words) {
Some(scratch) => fill_frames(node, input, range, Some(scratch), frames),
// Which node type declines a batch, so a lane loop has a name in the tally.
#[cfg(debug_assertions)]
Some(scratch) => {
let name = core::any::type_name::<N>();
let short = name.split('<').next().unwrap_or(name).rsplit("::").next().unwrap_or(name);
note_kernel_batch(Box::leak(short.to_string().into_boxed_str()), "unbatched fill", len);
fill_dispatch::<C, N>(node, &dispatch, Some(scratch), frames)
}
#[cfg(not(debug_assertions))]
Some(scratch) => fill_dispatch::<C, N>(node, &dispatch, Some(scratch), frames),
None => exhausted(),
},
BatchStatus::NeedBuffer => match arena.alloc_scratch::<u64>(words) {
Some(scratch) => node.eval_batch(input, range, Some(scratch), frames),
// A node that declines once given scratch is served lane by lane instead.
Some(scratch) => match node.eval_batch(dispatch.clone(), Some(scratch), frames) {
BatchStatus::Unbatched => match arena.alloc_scratch::<u64>(words) {
Some(scratch) => fill_dispatch::<C, N>(node, &dispatch, Some(scratch), frames),
None => exhausted(),
},
status => status,
},
None => exhausted(),
},
status => status,
@@ -124,9 +305,11 @@ pub enum LevelStatus<'a> {
/// fills once, a lower bound drains by guess-and-double until a short fill,
/// each reply's hint seeding the next guess. The boundary consumers' driver;
/// reducers inline the same protocol with their span offsets.
pub fn materialize_level<'a, 'e, C, N>(node: &'a N, input: &'a C, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> LevelStatus<'a>
pub fn materialize_level<'a, 'e, 'r, C, N>(node: &'a N, input: &'a C, arena: &'a crate::arena::Arena, frames: &Frames<'e>) -> LevelStatus<'r>
where
C: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
'a: 'r,
'e: 'r,
C: AsDispatch<'e> + crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
N: Node<C>,
{
use crate::gpoll::{Extent, GraphError, Level};
@@ -194,7 +377,7 @@ impl<'a, 'e, N> RecordInput<'a, 'e, N> {
pub fn serve<'l, C>(&self, ctx: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
where
N: Node<C>,
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
self.node.serve(ctx, slot)
}
@@ -204,7 +387,7 @@ impl<'a, 'e, N> RecordInput<'a, 'e, N> {
pub fn materialize_level<'b, C>(&'b self, ctx: &'b C, arena: &'b crate::arena::Arena) -> LevelStatus<'b>
where
N: Node<C>,
C: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
C: AsDispatch<'e> + crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
materialize_level(self.node, ctx, arena, self.frames)
}
@@ -384,7 +567,7 @@ impl<'a, 'e, N> RecordLazyInput<'a, 'e, N> {
}
/// See [`RecordLazyInput::inner_extent`].
fn inner_extent_of<B, N>(node: &N, ctx: &B, copy: u64, levels: u8, input_index: usize, frames: &Frames<'_>) -> Result<u64, crate::gpoll::Interrupt>
pub fn inner_extent_of<B, N>(node: &N, ctx: &B, copy: u64, levels: u8, input_index: usize, frames: &Frames<'_>) -> Result<u64, crate::gpoll::Interrupt>
where
B: crate::context::DeriveCtx,
N: for<'d> DerivedRecordInput<'d, crate::context::Derived<'d, B>>,
@@ -512,7 +695,7 @@ impl<El: Clone + 'static, N> RecordExtract<El, N> {
pub fn eval<'e, C>(&self, input: &C, frames: &Frames<'e>) -> GPoll<El>
where
N: Node<C>,
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
// The element copies out by value, so the input's claim dies with
// the scope.
@@ -522,3 +705,119 @@ impl<El: Clone + 'static, N> RecordExtract<El, N> {
serve_input(&self.edge, input, &scope).map(|value| unsafe { read_element::<El>(self.layout.rec(&value)) })
}
}
/// Records whether a materialized input answered with a batch, for the `GRAPHENE_BATCH_DEBUG`
/// report on which nodes still drive the per-lane fill.
#[cfg(debug_assertions)]
pub fn tally_batch(name: &str, batched: bool, lanes: usize) {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
if !*ON.get_or_init(|| std::env::var_os("GRAPHENE_BATCH_DEBUG").is_some()) {
return;
}
TALLY.with(|tally| {
let mut tally = tally.borrow_mut();
let entry = tally.entry(short_name(name)).or_insert((0, 0, 0));
match batched {
true => entry.0 += 1,
false => entry.1 += 1,
}
entry.2 += lanes;
});
// Reporting on drop is awkward from a thread local, so the report is printed on demand
TALLY.with(|tally| {
let tally = tally.borrow();
let total: usize = tally.values().map(|(batched, unbatched, _)| batched + unbatched).sum();
if !total.is_multiple_of(20000) || std::env::var_os("GRAPHENE_BATCH_DEBUG_PERIODIC").is_none() {
return;
}
let mut rows: Vec<_> = tally.iter().map(|(name, counts)| (name.clone(), *counts)).collect();
rows.sort_by_key(|(_, (_, unbatched, _))| std::cmp::Reverse(*unbatched));
eprintln!("batch tally> after {total} materializations:");
for (name, (batched, unbatched, lanes)) in rows.iter().take(12) {
eprintln!("batch tally> batched={batched:<8} UNBATCHED={unbatched:<8} lanes={lanes:<10} {name}");
}
});
}
/// The node's own name out of the fully qualified generic soup.
#[cfg(debug_assertions)]
fn short_name(name: &str) -> String {
let head = name.split('<').next().unwrap_or(name);
head.rsplit("::").take(2).collect::<Vec<_>>().into_iter().rev().collect::<Vec<_>>().join("::")
}
#[cfg(debug_assertions)]
thread_local! {
static BATCH_CONSUMER: std::cell::Cell<&'static str> = const { std::cell::Cell::new("") };
static TALLY: std::cell::RefCell<std::collections::HashMap<String, (usize, usize, usize)>> = std::cell::RefCell::new(std::collections::HashMap::new());
}
/// Names the kernel input about to materialize, so the `GRAPHENE_BATCH_DEBUG` tally is keyed by consumer rather than by the erased source.
#[cfg(debug_assertions)]
pub fn note_batch_consumer(name: &'static str) {
BATCH_CONSUMER.with(|consumer| consumer.set(name));
}
/// Drains the tally: per consumer input, (batched, unbatched, lanes).
#[cfg(debug_assertions)]
pub fn take_batch_tally() -> Vec<(String, (usize, usize, usize))> {
TALLY.with(|tally| tally.borrow_mut().drain().collect())
}
#[cfg(debug_assertions)]
thread_local! {
static KERNELS: std::cell::RefCell<std::collections::HashMap<(&'static str, &'static str), (usize, usize)>> = std::cell::RefCell::new(std::collections::HashMap::new());
}
/// Records one batch entry of a kernel: `how` names the path taken (hand,
/// hoisted, eager-forward, unbatched, or a hand batch's own outcome).
#[cfg(debug_assertions)]
pub fn note_kernel_batch(kernel: &'static str, how: &'static str, lanes: usize) {
// GRAPHENE_BATCH_TRACE=kernel:arm:lanes prints one backtrace for the first matching call.
thread_local! { static TRACED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; }
if !TRACED.with(|traced| traced.get()) {
static SPEC: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
if let Some(spec) = SPEC.get_or_init(|| std::env::var("GRAPHENE_BATCH_TRACE").ok()) {
let mut parts = spec.split(':');
let hit = parts.next() == Some(kernel) && parts.next() == Some(how) && parts.next().and_then(|n| n.parse::<usize>().ok()) == Some(lanes);
if hit {
TRACED.with(|traced| traced.set(true));
eprintln!("BATCH TRACE {kernel} {how} {lanes}:\n{}", std::backtrace::Backtrace::force_capture());
}
}
}
KERNELS.with(|kernels| {
let mut kernels = kernels.borrow_mut();
let entry = kernels.entry((kernel, how)).or_insert((0, 0));
entry.0 += 1;
entry.1 += lanes;
});
}
/// Drains the kernel tally: per (kernel, path), (calls, lanes).
#[cfg(debug_assertions)]
pub fn take_kernel_tally() -> Vec<((&'static str, &'static str), (usize, usize))> {
KERNELS.with(|kernels| kernels.borrow_mut().drain().collect())
}
/// Time spent inside the render node building output, so a frame timing can
/// be split into evaluation and rendering.
static RENDER_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
pub fn note_render_nanos(nanos: u64) {
RENDER_NANOS.fetch_add(nanos, std::sync::atomic::Ordering::Relaxed);
}
/// Drains the render time accumulated since the last drain.
pub fn take_render_nanos() -> u64 {
RENDER_NANOS.swap(0, std::sync::atomic::Ordering::Relaxed)
}
/// Whether grouped gathers and repeats verify their groups are rectangular
/// before batching; `GRAPHENE_NO_RAGGED_CHECK` skips the probes for measurement.
pub fn ragged_checks_enabled() -> bool {
static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ENABLED.get_or_init(|| std::env::var_os("GRAPHENE_NO_RAGGED_CHECK").is_none())
}
@@ -366,6 +366,16 @@ pub struct RecordLayout {
/// over input positions. Empty is the safe default: an uninstalled layout
/// rebinds every input per lane.
pub lane_invariant: u32,
/// Inputs whose branch never reads the footprint, as a bitmask over input
/// positions. Empty is the safe default: an uninstalled layout treats
/// every input as footprint-dependent.
pub footprint_free: u32,
/// Inputs whose branch serves at most one lane per context (a depth-0
/// producer), as a bitmask over input positions. Empty is the safe default.
pub single_lane: u32,
/// The index levels each input's branch reads, by input position; a
/// missing entry reads as every level.
pub input_levels: Vec<crate::context::IndexLevels>,
/// The names the fold gave this node's name-from-input writes, in the
/// order the signature declares its placeholders. A marker-only node
/// leaves it empty; `set_layout` resolves its offsets through these
@@ -478,6 +488,18 @@ pub struct LayoutMeta {
/// The materialized subject a reducer folds, as `(input, levels)`. The fold
/// consumes the whole subject input, so only the node's own levels remain.
pub folded: Option<(u8, u8)>,
/// Whether [`sources`](Self::sources)`[0]` is a GATHERED subject, whose
/// per-lane layout is this output's base.
///
/// Carried explicitly because it cannot be inferred from `sources` and
/// `level_delta`. A gathered subject that also collapses the level
/// (`level_delta < 0`) still has a well-defined copy plan: the gathered
/// lane's layout IS the base being copied into. A LAZY folding subject looks
/// identical from the outside - un-materialized, so it also sits in
/// `sources` with a negative delta - but copying its fields down is exactly
/// what the plan must not do. Keying on "sources is non-empty" would
/// conflate the two and reintroduce the defect in the other direction.
pub gathered: bool,
}
/// The attributes a node reads from one input, recorded on [`LayoutMeta`] for
@@ -513,6 +535,8 @@ impl LayoutMeta {
removes: Vec::new(),
level_delta: 0,
folded: None,
// A retype keeps input 0's level, so its plan is already unconditional.
gathered: false,
}
}
@@ -545,7 +569,9 @@ impl LayoutMeta {
let layout = self.fold(inputs);
let frame_bytes = layout.frame_bytes();
let plan = match self.sources.first() {
Some(&source) if self.level_delta >= 0 => {
// A gathered subject copies from the lane it gathered, whose layout is
// this output's base, so its plan holds however the level moves.
Some(&source) if self.level_delta >= 0 || self.gathered => {
let from = inputs[source as usize].expect("layout resolve source input has no layout");
let carry_element = matches!(self.element, ElementSpec::Carried);
let removes: Vec<(&str, u8)> = self.removes.clone();
@@ -587,6 +613,9 @@ impl LayoutMeta {
frame_bytes,
plan,
lane_invariant: 0,
footprint_free: 0,
single_lane: 0,
input_levels: Vec::new(),
named_writes: self.folded_names.clone(),
named_reads,
named_read_defaults,
@@ -23,7 +23,14 @@ mod testkit;
pub use access::{Rec, RecordValue, apply_plan, borrow_element, erase_static, read_at, read_at_defaulting, read_element, token_only, write_element, write_element_sized, write_field};
pub use frames::{FrameArena, FrameScope, Frames};
pub use input::{DerivedLazyInput, DerivedRecordInput, ElementInput, ElementLazyInput, LevelStatus, RecordExtract, RecordInput, RecordLazyInput, fill_frames, materialize_batch, materialize_level};
pub use input::{
DerivedLazyInput, DerivedRecordInput, ElementInput, ElementLazyInput, LevelStatus, RecordExtract, RecordInput, RecordLazyInput, fill_dispatch, fill_frames, forward_batch, forward_dispatch,
inner_extent_of, materialize_batch, materialize_dispatch, materialize_level,
};
#[cfg(debug_assertions)]
pub use input::{note_batch_consumer, note_kernel_batch, take_batch_tally, take_kernel_tally};
pub use input::ragged_checks_enabled;
pub use input::{note_render_nanos, take_render_nanos};
pub use layout::{
ElToken, ElementSpec, ElementWrite, ElementWritePick, ElementWritePickHashed, ElementWritePickPlain, FieldDesc, FieldOffset, FieldWrite, InputReads, Layout, LayoutMeta, NamedRead, NamedWrite,
RecordLayout, copy_plan, element_dims, element_parked, element_write, element_write_hashed, empty_layout,
@@ -31,6 +38,6 @@ pub use layout::{
pub use owned::{OwnedRecord, deepen_field_value, has_deep_element_glue, register_deep_element_clone, register_deep_field_value, replay_field_value};
pub use promote::{Promotion, assert_promoted, register_element_promote, register_field_promote, register_retained_heap};
pub use route::{RecordSource, SourcePlan};
pub use run::{Group, GroupItem, RunBuilder, RunColumn, RunView};
pub use serve::{FrameClaim, MaterializedSpan, Served, SlotRun, serve_input};
pub use testkit::{LiftedSource, ServedRecord, capture, test_frames};
pub use run::{Child, Group, GroupItem, LayoutRef, RunBuilder, RunColumn, RunView, Segmented, run_to_owned_list};
pub use serve::{FrameClaim, LaneSpan, MaterializedSpan, Served, SlotRun, serve_input};
pub use testkit::{LiftedSource, ServedRecord, capture, fixtures as test_fixtures, test_frames};
@@ -17,7 +17,7 @@ pub(in crate::record) struct DeepElementGlue {
pub(in crate::record) repark: unsafe fn(&(dyn std::any::Any + Send + Sync), *mut u8, &crate::arena::Arena) -> Option<()>,
}
static DEEP_ELEMENT_CLONES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, DeepElementGlue>>> = std::sync::LazyLock::new(Default::default);
static DEEP_ELEMENT_CLONES: std::sync::LazyLock<std::sync::RwLock<std::collections::HashMap<std::any::TypeId, DeepElementGlue, std::hash::BuildHasherDefault<graphene_hash::FxHasher64>>>> = std::sync::LazyLock::new(Default::default);
/// Registers the deep copy-out and re-park pair for elements of `T`. Called
/// at startup from the crate that owns the type.
@@ -25,18 +25,18 @@ pub fn register_deep_element_clone<T: dyn_any::StaticTypeSized>(
clone_out: unsafe fn(*const u8) -> Box<dyn std::any::Any + Send + Sync>,
repark: unsafe fn(&(dyn std::any::Any + Send + Sync), *mut u8, &crate::arena::Arena) -> Option<()>,
) {
DEEP_ELEMENT_CLONES.lock().unwrap().insert(std::any::TypeId::of::<T::Static>(), DeepElementGlue { clone_out, repark });
DEEP_ELEMENT_CLONES.write().unwrap().insert(std::any::TypeId::of::<T::Static>(), DeepElementGlue { clone_out, repark });
}
pub(in crate::record) fn deep_element_glue(type_id: std::any::TypeId) -> Option<DeepElementGlue> {
DEEP_ELEMENT_CLONES.lock().unwrap().get(&type_id).copied()
DEEP_ELEMENT_CLONES.read().unwrap().get(&type_id).copied()
}
/// Whether elements of a type registered deep glue. The shallow clone path is
/// only sound for types that did not need to, so a host that drives the
/// registration itself checks the types it owes before it evaluates anything.
pub fn has_deep_element_glue(type_id: std::any::TypeId) -> bool {
DEEP_ELEMENT_CLONES.lock().unwrap().contains_key(&type_id)
DEEP_ELEMENT_CLONES.read().unwrap().contains_key(&type_id)
}
/// Deep-copy overrides for field values whose content borrows the
@@ -53,16 +53,16 @@ pub(in crate::record) struct DeepFieldGlue {
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::RwLock<std::collections::HashMap<std::any::TypeId, DeepFieldGlue, std::hash::BuildHasherDefault<graphene_hash::FxHasher64>>>> = std::sync::LazyLock::new(Default::default);
/// Registers the deep copy-out and replay pair for field values of `T`.
/// Called at startup from the crate that owns the type.
pub fn register_deep_field_value<T: 'static>(copy_out: fn(&dyn crate::list::AnyAttributeValue) -> 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.write().unwrap().insert(std::any::TypeId::of::<T>(), DeepFieldGlue { copy_out, replay });
}
pub(in crate::record) fn deep_field_glue(type_id: std::any::TypeId) -> Option<DeepFieldGlue> {
DEEP_FIELD_VALUES.lock().unwrap().get(&type_id).copied()
DEEP_FIELD_VALUES.read().unwrap().get(&type_id).copied()
}
/// The copy-out half over an erased field value: the owned form a value takes
@@ -155,17 +155,17 @@ pub unsafe fn assert_promoted(layout: &Layout, ptr: *const u8, promotion: &Promo
/// region and copies only the rest.
type ElementPromote = unsafe fn(*const u8, *mut u8, &Promotion<'_>) -> Option<()>;
static ELEMENT_PROMOTES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, ElementPromote>>> = std::sync::LazyLock::new(Default::default);
static ELEMENT_PROMOTES: std::sync::LazyLock<std::sync::RwLock<std::collections::HashMap<std::any::TypeId, ElementPromote, std::hash::BuildHasherDefault<graphene_hash::FxHasher64>>>> = std::sync::LazyLock::new(Default::default);
/// Registers the promote for elements of `T`. Called at startup from the crate
/// that owns the type. The promote must leave no reference the promotion calls
/// evaluation-lived.
pub fn register_element_promote<T: dyn_any::StaticTypeSized>(promote: ElementPromote) {
ELEMENT_PROMOTES.lock().unwrap().insert(std::any::TypeId::of::<T::Static>(), promote);
ELEMENT_PROMOTES.write().unwrap().insert(std::any::TypeId::of::<T::Static>(), promote);
}
fn element_promote_glue(type_id: std::any::TypeId) -> Option<ElementPromote> {
ELEMENT_PROMOTES.lock().unwrap().get(&type_id).copied()
ELEMENT_PROMOTES.read().unwrap().get(&type_id).copied()
}
/// The deep field glue's third half, opt-in beside [`register_deep_field_value`]'s
@@ -186,17 +186,17 @@ fn element_promote_glue(type_id: std::any::TypeId) -> Option<ElementPromote> {
/// dies with the evaluation is copied or moved.
type FieldPromote = unsafe fn(*const u8, *mut u8, &Promotion<'_>) -> Option<()>;
static FIELD_PROMOTES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, FieldPromote>>> = std::sync::LazyLock::new(Default::default);
static FIELD_PROMOTES: std::sync::LazyLock<std::sync::RwLock<std::collections::HashMap<std::any::TypeId, FieldPromote, std::hash::BuildHasherDefault<graphene_hash::FxHasher64>>>> = std::sync::LazyLock::new(Default::default);
/// Registers the promote for fields stored as `T`. Called at startup from the
/// crate that owns the type. The promote must leave no reference the promotion
/// calls evaluation-lived.
pub fn register_field_promote<T: 'static>(promote: FieldPromote) {
FIELD_PROMOTES.lock().unwrap().insert(std::any::TypeId::of::<T>(), promote);
FIELD_PROMOTES.write().unwrap().insert(std::any::TypeId::of::<T>(), promote);
}
fn field_promote_glue(type_id: std::any::TypeId) -> Option<FieldPromote> {
FIELD_PROMOTES.lock().unwrap().get(&type_id).copied()
FIELD_PROMOTES.read().unwrap().get(&type_id).copied()
}
/// The park glue's heap estimate for values of a type, keyed as the deep glue
@@ -204,17 +204,17 @@ fn field_promote_glue(type_id: std::any::TypeId) -> Option<FieldPromote> {
/// without walking it.
type RetainedMeasure = fn(&(dyn std::any::Any + Send + Sync)) -> usize;
static RETAINED_MEASURES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, RetainedMeasure>>> = std::sync::LazyLock::new(Default::default);
static RETAINED_MEASURES: std::sync::LazyLock<std::sync::RwLock<std::collections::HashMap<std::any::TypeId, RetainedMeasure, std::hash::BuildHasherDefault<graphene_hash::FxHasher64>>>> = std::sync::LazyLock::new(Default::default);
/// Registers the retained-heap estimate for values of `T`. Called at startup
/// from the crate that owns the type. The estimate is a hint: an unregistered
/// type contributes 0, so a region's counter is a lower bound.
pub fn register_retained_heap<T: dyn_any::StaticTypeSized>(measure: RetainedMeasure) {
RETAINED_MEASURES.lock().unwrap().insert(std::any::TypeId::of::<T::Static>(), measure);
RETAINED_MEASURES.write().unwrap().insert(std::any::TypeId::of::<T::Static>(), measure);
}
pub(in crate::record) fn retained_measure(type_id: std::any::TypeId) -> Option<RetainedMeasure> {
RETAINED_MEASURES.lock().unwrap().get(&type_id).copied()
RETAINED_MEASURES.read().unwrap().get(&type_id).copied()
}
impl MaterializedSpan {
@@ -92,7 +92,7 @@ where
{
fn serve<'e, 'l>(&self, input: &C, mut slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
where
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
// The source's frame is claimed beyond this one and dies with the
// claim; the translated union record stays.
@@ -127,11 +127,60 @@ where
fn extent_at<'x>(&self, input: &C, level: u8, frames: &Frames<'x>) -> GPoll<crate::gpoll::Extent>
where
C: crate::context::ExtractArena<ArenaRef = &'x crate::arena::Arena>,
C: crate::dispatch::AsDispatch<'x> + crate::context::ExtractArena<ArenaRef = &'x crate::arena::Arena>,
{
self.edge.extent_at(input, level, frames)
}
/// A batch through the route: an identity route forwards the request
/// untouched, and a translating route materializes the source's lanes at
/// the source layout and translates each into the caller's scratch, so a
/// batch survives the layout seam instead of restarting lane by lane.
fn eval_batch<'a, 'x, 'r>(&'a self, dispatch: crate::dispatch::Dispatch<'x>, scratch: Option<&'r mut [std::mem::MaybeUninit<u64>]>, frames: &Frames<'x>) -> crate::node::BatchStatus<'r>
where
'a: 'r,
'x: 'r,
C: crate::dispatch::AsDispatch<'x> + crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'x crate::arena::Arena>,
{
use crate::node::BatchStatus;
let range = dispatch.range();
let Some(plan) = &self.plan else {
#[cfg(debug_assertions)]
super::input::note_kernel_batch("route", "identity", range.end.saturating_sub(range.start) as usize);
return self.edge.eval_batch(dispatch, scratch, frames);
};
#[cfg(debug_assertions)]
super::input::note_kernel_batch("route", "translate", range.end.saturating_sub(range.start) as usize);
let Some(scratch) = scratch else {
return BatchStatus::NeedBuffer;
};
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
return BatchStatus::InvalidRange;
};
let stride = self.union.lane_stride();
if scratch.len() * 8 < len * stride {
return BatchStatus::InvalidRange;
}
let (source, finality, hint) = match super::input::materialize_dispatch::<C, _>(&self.edge, &dispatch, dispatch.scope().arena(), frames) {
BatchStatus::Lent(batch, finality, hint) => (batch, finality, hint),
BatchStatus::Filled(batch, finality, hint) => (batch.into_shared(), finality, hint),
BatchStatus::Pending => return BatchStatus::Pending,
BatchStatus::Error(error) => return BatchStatus::Error(error),
BatchStatus::Unbatched => return BatchStatus::Unbatched,
BatchStatus::NeedBuffer => return BatchStatus::NeedBuffer,
BatchStatus::InvalidRange => return BatchStatus::InvalidRange,
};
let lanes = source.len().min(len);
let base: *mut u8 = scratch.as_mut_ptr().cast();
for lane in 0..lanes {
// SAFETY: the source lane is a record of the plan's source layout,
// and the scratch holds `len` union lanes at the union stride,
// disjoint from the source's storage.
unsafe { plan.translate(source.get(lane).rec(), base.add(lane * stride)) };
}
// Lanes `0..lanes` were translated above as records of the union layout.
BatchStatus::Filled(crate::node::RecordBatchMut::new(scratch, lanes, &self.union), finality, hint)
}
fn layout(&self) -> &Layout {
&self.union
}
@@ -155,12 +155,33 @@ impl<'e> RunBuilder<'e> {
unsafe { (info.write_stored)(value, self.frames.add(lane * self.layout.lane_stride() + offset), self.arena) }
}
/// Copies a source lane's fields onto an already pushed lane through `plan`.
/// The columns move as bytes rather than through a read-write round trip, so a
/// parked payload carries as its arena reference and stays valid for the
/// evaluation, exactly as a lane's own carry does.
///
/// # Safety
/// `src` must be a live record of `plan`'s source layout, `plan` must target
/// this builder's layout, and `src` must not overlap the frames.
pub unsafe fn carry(&mut self, lane: usize, src: crate::record::Rec<'_>, plan: &[(usize, usize, usize)]) {
assert!(lane < self.pushed, "a carry lands on a pushed lane");
// SAFETY: the lane is below `pushed`, so its frame is within the allocation.
let dst = unsafe { self.frames.add(lane * self.layout.lane_stride()) };
// SAFETY: the caller's contract.
unsafe { crate::record::apply_plan(src, dst, plan) };
}
/// The layout the finished run carries, for computing a carry plan into it.
pub fn layout(&self) -> &Layout {
&self.layout
}
/// The finished run. Panics unless every lane was pushed, since an
/// unwritten parked element slot must never become readable.
pub fn finish(self) -> GroupItem<'e> {
assert_eq!(self.pushed, self.len, "every lane pushes before the run finishes");
GroupItem {
layout: self.layout,
layout: LayoutRef::Shared(std::sync::Arc::new(self.layout)),
storage: ItemStorage::Resident(self.frames.cast_const()),
len: self.len,
_arena: std::marker::PhantomData,
@@ -168,6 +189,53 @@ impl<'e> RunBuilder<'e> {
}
}
/// A run's layout by reference: borrowed from the node that owns it for the
/// evaluation, or shared once copied out. Every lane of a run reads through
/// one layout, so a run costs no layout clone.
#[derive(Clone, Debug)]
pub enum LayoutRef<'e> {
Borrowed(&'e Layout),
Shared(std::sync::Arc<Layout>),
}
impl LayoutRef<'_> {
pub fn copy_out(&self) -> LayoutRef<'static> {
LayoutRef::Shared(match self {
LayoutRef::Borrowed(layout) => std::sync::Arc::new((*layout).clone()),
LayoutRef::Shared(layout) => layout.clone(),
})
}
/// The same layout at the persistent region's lifetime. A node's layout
/// outlives every persistent generation: the region resets when the graph
/// recompiles, before any node is dropped.
fn persistent<'p>(&self) -> LayoutRef<'p> {
match self {
// SAFETY: as documented above; the borrow names storage the graph keeps
// for as long as the persistent region can hold a run over it.
LayoutRef::Borrowed(layout) => LayoutRef::Borrowed(unsafe { &*std::ptr::from_ref::<Layout>(layout) }),
LayoutRef::Shared(layout) => LayoutRef::Shared(layout.clone()),
}
}
}
impl std::ops::Deref for LayoutRef<'_> {
type Target = Layout;
fn deref(&self) -> &Layout {
match self {
LayoutRef::Borrowed(layout) => layout,
LayoutRef::Shared(layout) => layout,
}
}
}
impl PartialEq for LayoutRef<'_> {
fn eq(&self, other: &Self) -> bool {
std::ptr::eq(&**self, &**other) || **self == **other
}
}
/// `len` records stored in the arena at `layout`'s stride. The layout is
/// owned by the value and identifies the run's element type. A resident item
/// borrows the serving arena at `'e`, so it cannot outlive the evaluation. An
@@ -177,7 +245,7 @@ impl<'e> RunBuilder<'e> {
/// so the lifetime instantiation is the resident/owned distinction.
#[derive(Clone, Debug)]
pub struct GroupItem<'e> {
layout: Layout,
layout: LayoutRef<'e>,
storage: ItemStorage,
len: usize,
_arena: std::marker::PhantomData<&'e ()>,
@@ -213,13 +281,29 @@ unsafe impl Send for GroupItem<'_> {}
unsafe impl Sync for GroupItem<'_> {}
impl<'e> GroupItem<'e> {
/// As [`Self::adopt`], borrowing the batch's layout instead of cloning it.
///
/// # Safety
/// The batch must read through a layout the compiled graph owns for as
/// long as `arena` can hold the run (a node's own layout, as a materialized
/// input's batch does; see [`LayoutRef::persistent`]), never a run's
/// shared layout that dies with the run.
pub unsafe fn adopt_borrowing(batch: crate::node::RecordBatch<'_>, arena: &'e crate::arena::Arena) -> Option<Self> {
// SAFETY: the caller's contract on the layout's storage.
let layout = LayoutRef::Borrowed(unsafe { &*std::ptr::from_ref::<Layout>(batch.layout()) });
Self::adopt_with(batch, layout, arena)
}
/// Copies the batch's lanes into the arena and clones its layout.
/// Returns `None` when the arena is exhausted. Parked regions must carry
/// the content glue, so equality and hashing never fall back to pointer
/// bytes. A copied lane's parked payloads re-park into `arena`, so the
/// adopted run names nothing the source arena's reset frees.
pub fn adopt(batch: crate::node::RecordBatch<'_>, arena: &'e crate::arena::Arena) -> Option<Self> {
let layout = batch.layout().clone();
Self::adopt_with(batch, LayoutRef::Shared(std::sync::Arc::new(batch.layout().clone())), arena)
}
fn adopt_with(batch: crate::node::RecordBatch<'_>, layout: LayoutRef<'e>, arena: &'e crate::arena::Arena) -> Option<Self> {
assert_element_glue(&layout);
for field in &layout.fields {
assert!(field.repark.is_none() || field.content_hash.is_some(), "a parked field adopts only with content glue");
@@ -309,7 +393,7 @@ impl<'e> GroupItem<'e> {
/// spans only the window it lends the batch for, which is sound exactly when
/// `'e` is bounded to that window.
pub unsafe fn from_resident(batch: crate::node::RecordBatch<'e>) -> Self {
let layout = batch.layout().clone();
let layout = LayoutRef::Borrowed(batch.layout());
assert_element_glue(&layout);
for field in &layout.fields {
assert!(field.repark.is_none() || field.content_hash.is_some(), "a parked field adopts only with content glue");
@@ -322,6 +406,16 @@ impl<'e> GroupItem<'e> {
}
}
/// A run of no lanes at this run's layout.
pub fn empty_like(&self) -> GroupItem<'e> {
Self {
layout: self.layout.clone(),
storage: ItemStorage::Resident(std::ptr::NonNull::<u64>::dangling().as_ptr().cast_const().cast()),
len: 0,
_arena: std::marker::PhantomData,
}
}
/// A batch view over the stored records. Panics on an owned item, which
/// must [`Self::replay`] first.
pub fn lanes(&self) -> crate::node::RecordBatch<'_> {
@@ -336,7 +430,7 @@ impl<'e> GroupItem<'e> {
pub fn copy_out(&self) -> GroupItem<'static> {
if let ItemStorage::Owned(_) = &self.storage {
return GroupItem {
layout: self.layout.clone(),
layout: self.layout.copy_out(),
storage: self.storage.clone(),
len: self.len,
_arena: std::marker::PhantomData,
@@ -380,7 +474,7 @@ impl<'e> GroupItem<'e> {
})
.collect();
GroupItem {
layout: self.layout.clone(),
layout: self.layout.copy_out(),
storage: ItemStorage::Owned(std::sync::Arc::new(OwnedLanes { bytes, elements, fields })),
len: self.len,
_arena: std::marker::PhantomData,
@@ -426,7 +520,7 @@ impl<'e> GroupItem<'e> {
}
}
Some(GroupItem {
layout: self.layout.clone(),
layout: self.layout.copy_out(),
storage: ItemStorage::Resident(frames.cast_const()),
len: self.len,
_arena: std::marker::PhantomData,
@@ -445,7 +539,7 @@ impl<'e> GroupItem<'e> {
let persistent = promotion.persistent();
if self.len == 0 || persistent.contains(frames) {
return Some(GroupItem {
layout: self.layout.clone(),
layout: self.layout.persistent(),
storage: ItemStorage::Resident(frames),
len: self.len,
_arena: std::marker::PhantomData,
@@ -462,7 +556,7 @@ impl<'e> GroupItem<'e> {
unsafe { promote_record(&self.layout, dst.add(lane * stride), promotion) }?;
}
Some(GroupItem {
layout: self.layout.clone(),
layout: self.layout.persistent(),
storage: ItemStorage::Resident(dst.cast_const()),
len: self.len,
_arena: std::marker::PhantomData,
@@ -480,6 +574,25 @@ impl<'e> GroupItem<'e> {
}
}
/// One typed run as an owned legacy list, elements cloned and every attribute
/// copied through its erased read. The owned result outlives the evaluation the
/// run was materialized in, so an async source can carry it across its await.
pub fn run_to_owned_list<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(item: &GroupItem) -> Option<crate::list::List<T>> {
let lanes = item.typed_lanes::<T>()?;
let mut list = crate::list::List::new();
for lane in 0..lanes.len() {
list.push(crate::list::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, crate::list::AttributeValueDyn(value));
}
}
Some(list)
}
/// A run read at its element type. Record fields hold each marker's value
/// verbatim, so lane reads are plain typed reads at a hoisted offset.
pub struct RunView<'a, T> {
@@ -1016,3 +1129,227 @@ mod tests {
item.copy_out().lanes();
}
}
/// A level as an immutable pointer structure: two children and the cached
/// lane count. Stacking two levels allocates one node and copies nothing;
/// lanes read in order by walking the children, so a stack nested on the
/// right iterates as a list.
#[derive(Clone, Debug)]
pub struct Segmented<'e> {
left: Child<'e>,
right: Child<'e>,
len: usize,
}
/// One side of a [`Segmented`] node: a run of lanes, a node resident in the
/// arena, or an owned node copied out of it.
#[derive(Clone, Debug)]
pub enum Child<'e> {
Leaf(GroupItem<'e>),
Resident(&'e Segmented<'e>),
Owned(std::sync::Arc<Segmented<'static>>),
}
impl<'e> Child<'e> {
pub fn len(&self) -> usize {
match self {
Child::Leaf(item) => item.len(),
Child::Resident(node) => node.len,
Child::Owned(node) => node.len,
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl<'e> Segmented<'e> {
pub fn new(left: Child<'e>, right: Child<'e>) -> Self {
let len = left.len() + right.len();
Self { left, right, len }
}
/// A right-nested stack over `runs` in order, parking one node per run
/// beyond the first pair. `None` for no runs or an exhausted arena.
pub fn from_runs(runs: Vec<GroupItem<'e>>, arena: &'e crate::arena::Arena) -> Option<Self> {
let mut runs = runs.into_iter().rev();
let last = runs.next()?;
let mut node = Segmented::new(Child::Leaf(last.empty_like()), Child::Leaf(last));
for run in runs {
node = Segmented::new(Child::Leaf(run), node.park(arena)?);
}
Some(node)
}
/// The node parked in `arena`, as a child for the next stack.
pub fn park(self, arena: &'e crate::arena::Arena) -> Option<Child<'e>> {
Some(Child::Resident(arena.alloc(self)?.0))
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// The runs in lane order. A right-nested stack walks with one pending
/// child; a left-nested one pushes its path.
pub fn runs(&self) -> Runs<'e> {
Runs {
stack: vec![self.right.clone(), self.left.clone()],
}
}
/// The lane's run and its offset within it.
pub fn locate(&self, lane: usize) -> Option<(GroupItem<'e>, usize)> {
let mut node = NodeRef::Resident(self);
let mut lane = lane;
loop {
let (left, right) = node.children();
let child = match lane < left.len() {
true => left,
false => {
lane -= left.len();
right
}
};
match child {
Child::Leaf(item) => return (lane < item.len()).then(|| (item.clone(), lane)),
Child::Resident(next) => node = NodeRef::Resident(next),
Child::Owned(next) => node = NodeRef::Owned(next.clone()),
}
}
}
pub fn copy_out(&self) -> Segmented<'static> {
Segmented {
left: self.left.copy_out(),
right: self.right.copy_out(),
len: self.len,
}
}
pub fn replay<'a>(&self, arena: &'a crate::arena::Arena) -> Option<Segmented<'a>> {
Some(Segmented {
left: self.left.replay(arena)?,
right: self.right.replay(arena)?,
len: self.len,
})
}
pub fn to_persistent<'p>(&self, promotion: &Promotion<'p>) -> Option<Segmented<'p>> {
Some(Segmented {
left: self.left.to_persistent(promotion)?,
right: self.right.to_persistent(promotion)?,
len: self.len,
})
}
}
impl<'e> Child<'e> {
fn copy_out(&self) -> Child<'static> {
match self {
Child::Leaf(item) => Child::Leaf(item.copy_out()),
Child::Resident(node) => Child::Owned(std::sync::Arc::new(node.copy_out())),
Child::Owned(node) => Child::Owned(node.clone()),
}
}
fn replay<'a>(&self, arena: &'a crate::arena::Arena) -> Option<Child<'a>> {
Some(match self {
Child::Leaf(item) => Child::Leaf(item.replay(arena)?),
Child::Resident(node) => node.replay(arena)?.park(arena)?,
Child::Owned(node) => node.replay(arena)?.park(arena)?,
})
}
fn to_persistent<'p>(&self, promotion: &Promotion<'p>) -> Option<Child<'p>> {
let persistent = promotion.persistent();
Some(match self {
Child::Leaf(item) => Child::Leaf(item.to_persistent(promotion)?),
Child::Resident(node) => {
let ptr = std::ptr::from_ref::<Segmented<'_>>(node).cast::<u8>();
if persistent.contains(ptr) {
// SAFETY: the node already lives in the persistent region, so the
// reference is valid for that region's lifetime.
Child::Resident(unsafe { &*ptr.cast::<Segmented<'p>>() })
} else {
node.to_persistent(promotion)?.park(persistent)?
}
}
Child::Owned(node) => node.to_persistent(promotion)?.park(persistent)?,
})
}
}
/// A node by reference or by owned handle while walking.
#[derive(Clone)]
enum NodeRef<'a, 'e> {
Resident(&'a Segmented<'e>),
Owned(std::sync::Arc<Segmented<'static>>),
}
impl<'a, 'e> NodeRef<'a, 'e> {
fn children(&self) -> (Child<'e>, Child<'e>) {
match self {
NodeRef::Resident(node) => (node.left.clone(), node.right.clone()),
NodeRef::Owned(node) => (relabel_child(&node.left), relabel_child(&node.right)),
}
}
}
/// An owned node's children are owned or owned-leaf, so they carry no borrow
/// and read at any lifetime.
fn relabel_child<'e>(child: &Child<'static>) -> Child<'e> {
match child {
Child::Leaf(item) => Child::Leaf(item.clone()),
Child::Owned(node) => Child::Owned(node.clone()),
Child::Resident(node) => Child::Resident(node),
}
}
/// The runs of a [`Segmented`] in lane order.
pub struct Runs<'e> {
stack: Vec<Child<'e>>,
}
impl<'e> Iterator for Runs<'e> {
type Item = GroupItem<'e>;
fn next(&mut self) -> Option<GroupItem<'e>> {
loop {
match self.stack.pop()? {
Child::Leaf(item) => return Some(item),
Child::Resident(node) => {
self.stack.push(node.right.clone());
self.stack.push(node.left.clone());
}
Child::Owned(node) => {
self.stack.push(relabel_child(&node.right));
self.stack.push(relabel_child(&node.left));
}
}
}
}
}
impl PartialEq for Segmented<'_> {
fn eq(&self, other: &Self) -> bool {
self.len == other.len && self.runs().flat_map(|run| (0..run.len()).map(move |lane| (run.clone(), lane))).zip(other.runs().flat_map(|run| (0..run.len()).map(move |lane| (run.clone(), lane)))).all(|((a, i), (b, j))| {
// SAFETY: both lanes image records of their run's layout.
a.layout() == b.layout() && unsafe { record_content_eq(a.layout(), a.lanes().get(i).rec().ptr(), b.lanes().get(j).rec().ptr()) }
})
}
}
impl graphene_hash::CacheHash for Segmented<'_> {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
state.write_usize(self.len);
for run in self.runs() {
run.cache_hash(state);
}
}
}
@@ -47,6 +47,7 @@ impl<'a> SlotRun<'a> {
frame: (self.layout.frame_bytes() != 0).then_some(frame),
free: frames.reborrow(),
filled_fields: false,
carried_empty: false,
}
}
@@ -86,6 +87,11 @@ pub struct FrameClaim<'e, 'l> {
/// Set by the writes that fill the declared fields, so the safe closers can
/// refuse a field-bearing frame that was never filled.
pub(in crate::record) filled_fields: bool,
/// Set where a carry ran against an EMPTY plan, which fills nothing. Kept
/// apart from `filled_fields` because "carried nothing" and "never carried"
/// are different mistakes: the first is a wiring defect the closers can
/// prove, the second is the ordinary shape of a fresh record.
pub(in crate::record) carried_empty: bool,
}
impl<'e, 'l> FrameClaim<'e, 'l> {
@@ -124,7 +130,33 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
/// serving the source through [`Self::frames`] establishes it.
pub unsafe fn carry(&mut self, src: Rec<'_>, plan: &[(usize, usize, usize)]) {
unsafe { apply_plan(src, self.dst(), plan) };
self.filled_fields = true;
// An empty plan copied nothing, so it must not satisfy the closers'
// "carried or wrote its fields" guard: the frame still holds whatever
// bytes the previous claim left, and a declared field read out of them
// is an uninitialized read rather than a missing value. Recorded rather
// than ignored so the closers can tell "carried nothing" apart from
// "never carried", which are not the same mistake.
match plan.is_empty() {
true => self.carried_empty = true,
false => self.filled_fields = true,
}
}
/// Copies the source record's element bytes into the frame, for a gathered
/// lane whose subject [`map_element`](crate::node::Lane::map_element) never
/// replaced. Carrying the element is not a field write, so it leaves
/// `filled_fields` alone.
///
/// # Safety
/// As [`Self::carry`]: `src` must be a live record of the gather's source
/// layout and must not overlap this frame. The element slots agree because
/// an unsubstituted `Lane<T>` can only come from a level whose element is
/// already `T`.
pub unsafe fn carry_element(&mut self, src: Rec<'_>) {
let size = self.layout.element.size;
if size > 0 {
unsafe { apply_plan(src, self.dst(), &[(0, 0, size)]) };
}
}
/// Writes a field at its wiring-resolved offset.
@@ -190,6 +222,17 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
/// The frame must hold a complete record of the layout, written through
/// the carry, element, and field writes.
pub unsafe fn finish(mut self) -> RecordValue<'e> {
// A frame that CARRIED, but through an empty plan, and then filled
// nothing else: its declared fields hold the previous claim's bytes, and
// a reference field read out of them is an uninitialized read. This is
// narrower than [`Self::lift`]'s guard on purpose - a frame that never
// carried at all may legitimately serve fields the census staged as
// declared defaults, so only an empty carry is evidence of the defect.
assert!(
!(self.carried_empty && !self.filled_fields && !self.layout.fields.is_empty()),
"a layout with {} fields carried an empty plan and filled nothing: its fields would be the prior frame's bytes",
self.layout.fields.len()
);
match self.frame {
Some(frame) => RecordValue::spilled(unsafe { Rec::new(frame.cast_const()) }),
// SAFETY: the inline record is the value's own bytes.
@@ -197,6 +240,42 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
}
}
/// Serves an element the arena already parks, writing that park's pointer
/// rather than allocating a second copy of the same value. A constant whose
/// park outlives every lane of an evaluation costs one allocation per
/// generation this way instead of one per serve.
///
/// The frame representation is the one [`crate::record::write_element`]
/// produces for a parked element, so a consumer cannot tell the two apart;
/// the difference is only that the arena's drop glue was registered once,
/// when `parked` was allocated.
pub fn lift_served_parked<T: Send + Sync + dyn_any::StaticTypeSized>(mut self, parked: &'e T, arena: &'e crate::arena::Arena) -> GPoll<Served<'e>> {
self.check_element::<T>();
assert!(
crate::record::element_parked::<T>(),
"`lift_served_parked` serves a parked element; `{}` is written inline",
std::any::type_name::<T>()
);
assert!(
self.layout.fields.is_empty() || self.filled_fields,
"a layout with {} fields must carry or write them before lifting",
self.layout.fields.len()
);
let frame_bytes = self.layout.frame_bytes();
let dst = self.dst();
// SAFETY: the element check pinned `T` and its slot holds `&T` for a
// parked element, and the frame is this layout's fresh claim.
unsafe { dst.cast::<&T>().write(parked) };
let value = match frame_bytes {
// SAFETY: the frame was just written with the whole record.
0 => unsafe { (&raw mut self.inline).cast::<RecordValue<'e>>().read() },
// SAFETY: as above, for a spilled frame.
_ => RecordValue::spilled(unsafe { Rec::new(dst.cast_const()) }),
};
let _ = arena;
GPoll::Final(Served { value })
}
/// [`Self::lift`] with the proof-bearing return for [`Node::serve`].
pub fn lift_served<T: Send + Sync + dyn_any::StaticTypeSized>(self, poll: GPoll<T>, arena: &'e crate::arena::Arena) -> GPoll<Served<'e>> {
self.lift(poll, arena).map(|value| Served { value })
@@ -291,6 +370,99 @@ impl MaterializedSpan {
}
}
/// A level published one lane at a time, for content served per lane under a
/// level whose extent the publisher never learns: chunk `k` holds lanes
/// `2^k - 1 ..= 2^(k+1) - 2`, so a lane's chunk is `(lane + 1).ilog2()`, a
/// reserved slab never moves, and the level costs at most twice its lanes.
pub struct LaneSpan {
generation: u64,
/// Chunk base addresses, 0 while unreserved; live exactly while the generation is.
chunks: Vec<usize>,
/// Per lane: 0 unpublished, 1 final, 2 partial.
states: Vec<u8>,
}
impl std::fmt::Debug for LaneSpan {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LaneSpan").field("lanes", &self.states.len()).finish()
}
}
impl LaneSpan {
pub fn new(arena: &crate::arena::Arena) -> Self {
Self {
generation: arena.generation(),
chunks: Vec::new(),
states: Vec::new(),
}
}
/// Whether the span still resolves against `arena`; a flush ends it.
pub fn is_live(&self, arena: &crate::arena::Arena) -> bool {
self.generation == arena.generation()
}
fn place(lane: usize) -> (usize, usize) {
let chunk = (lane + 1).ilog2() as usize;
(chunk, lane + 1 - (1 << chunk))
}
/// Lane `lane`'s record and finality, or `None` while it is unpublished or
/// once the generation moved on.
pub fn lane(&self, arena: &crate::arena::Arena, lane: usize, layout: &Layout) -> Option<(*const u8, crate::gpoll::Finality)> {
self.is_live(arena).then_some(())?;
let finality = match self.states.get(lane).copied().unwrap_or(0) {
1 => crate::gpoll::Finality::AllFinal,
2 => crate::gpoll::Finality::Partial,
_ => return None,
};
let (chunk, slot) = Self::place(lane);
let base = self.chunks.get(chunk).copied().filter(|base| *base != 0)? as *const u8;
// SAFETY: the state marks the slot published within the chunk's
// reservation, at the layout it was published under, and the generation
// check proved the region still holds it.
Some((unsafe { base.add(slot * layout.lane_stride()) }, finality))
}
/// Publishes lane `lane` as a copy of `src`. `None` where the region refused
/// the reservation or the promote, which leaves the lane unpublished.
///
/// # Safety
/// `src` must be a live record of `layout`.
pub unsafe fn publish(&mut self, lane: usize, src: *const u8, layout: &Layout, promotion: &crate::record::Promotion<'_>, finality: crate::gpoll::Finality) -> Option<()> {
let persistent = promotion.persistent();
self.is_live(persistent).then_some(())?;
let stride = layout.lane_stride();
let (chunk, slot) = Self::place(lane);
if self.chunks.len() <= chunk {
self.chunks.resize(chunk + 1, 0);
}
if self.chunks[chunk] == 0 {
let slab = persistent.alloc_scratch::<u64>(((1usize << chunk) * stride).div_ceil(8))?;
self.chunks[chunk] = slab.as_mut_ptr() as usize;
}
// SAFETY: the caller's contract on `src`, into this lane's own slot of
// the chunk reserved above at the layout's stride.
let dst = unsafe { (self.chunks[chunk] as *mut u8).add(slot * stride) };
unsafe { std::ptr::copy_nonoverlapping(src, dst, layout.size) };
// SAFETY: the copy images a record of this layout.
unsafe { crate::record::promote::promote_record(layout, dst, promotion) }?;
#[cfg(debug_assertions)]
// SAFETY: the lane was imaged and promoted above.
unsafe {
crate::record::promote::assert_promoted(layout, dst.cast_const(), promotion)
};
if self.states.len() <= lane {
self.states.resize(lane + 1, 0);
}
self.states[lane] = match finality {
crate::gpoll::Finality::AllFinal => 1,
crate::gpoll::Finality::Partial => 2,
};
Some(())
}
}
/// The proof a record was served through a frame claim: mintable only by the
/// claim's closing methods, so holding one means the record is of the
/// claimed layout.
@@ -316,7 +488,7 @@ impl<'e> Served<'e> {
pub fn serve_input<'e, C, N>(node: &N, input: &C, frames: &Frames<'e>) -> GPoll<RecordValue<'e>>
where
N: Node<C> + ?Sized,
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
let slot = frames.claim(node.layout());
node.serve(input, slot).map(Served::value)
@@ -386,4 +558,30 @@ mod tests {
let claim = shorten(frames.claim(&layout));
assert_eq!(claim.layout, &layout);
}
#[test]
fn a_lane_span_publishes_out_of_order_and_dies_with_its_generation() {
let transient = crate::arena::Arena::new(4096).unwrap();
let mut persistent = crate::arena::Arena::new(1 << 14).unwrap();
let layout = Layout::default().with_writes(1, crate::record::layout::element_write::<f64>(), &[crate::record::test_support::f64_field("opacity")]);
let mut buffer = vec![0u64; layout.frame_bytes().div_ceil(8)];
let base = buffer.as_mut_ptr().cast::<u8>();
let bounds = (base as usize, buffer.len() * 8);
let promotion = crate::record::Promotion::new(&transient, bounds, &persistent);
let mut span = LaneSpan::new(&persistent);
for lane in [5usize, 0, 2] {
unsafe { base.cast::<f64>().write(lane as f64) };
unsafe { span.publish(lane, base.cast_const(), &layout, &promotion, crate::gpoll::Finality::AllFinal) }.unwrap();
}
assert!(span.lane(&persistent, 1, &layout).is_none(), "an unpublished lane is a miss");
assert!(span.lane(&persistent, 9, &layout).is_none(), "a lane past every published one is a miss");
for lane in [0usize, 2, 5] {
let (ptr, finality) = span.lane(&persistent, lane, &layout).unwrap();
assert_eq!(unsafe { ptr.cast::<f64>().read() }, lane as f64, "lane {lane}");
assert_eq!(finality, crate::gpoll::Finality::AllFinal);
}
persistent.reset();
assert!(!span.is_live(&persistent));
assert!(span.lane(&persistent, 0, &layout).is_none(), "a flush ends the span");
}
}
@@ -77,7 +77,7 @@ impl ServedRecord {
pub fn capture<'e, C, N>(node: &N, ctx: &C, frames: &Frames<'e>) -> GPoll<ServedRecord>
where
N: Node<C> + ?Sized,
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
let scope = frames.scope();
let layout = node.layout().clone();
@@ -119,7 +119,7 @@ where
{
fn serve<'e, 'l>(&self, input: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
where
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
slot.lift_served((self.kernel)(input), input.arena())
}
@@ -146,7 +146,7 @@ mod tests {
impl<C> Node<C> for Fixture {
fn serve<'e, 'l>(&self, input: &C, mut slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
where
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
let offset = self.layout.offset_of(Transform::NAME, 0).expect("the fixture's layout carries the transform");
if slot.element(String::from("parked"), crate::context::ExtractArena::arena(input)).is_none() {
@@ -180,3 +180,336 @@ mod tests {
assert_eq!(served.attr::<Transform>(), DAffine2::from_translation(DVec2::new(3., 4.)));
}
}
/// The node-test fixtures: hand-wired record sources and layout installers,
/// so a node crate's tests drive a generated node without the compiler pass.
pub mod fixtures {
use super::super::frames::Frames;
use super::super::layout::{FieldWrite, Layout, LayoutMeta, RecordLayout, element_write};
use super::super::serve::{FrameClaim, Served};
use super::test_frames;
use crate::SourceId;
use crate::arena::Arena;
use crate::attribute::{Attribute, Opacity, Transform};
use crate::context::{ContextImpl, EvalScope, ExtractArena, ExtractIndex, ExtractIndices};
use crate::gpoll::{Extent, GPoll};
use crate::node::Node;
use crate::value::ValueSource;
use glam::DAffine2;
/// A one-record source with fixed `f64` fields, optionally served partial.
pub struct RecordSourceNode<E> {
pub layout: Layout,
pub element: E,
pub fields: Vec<(&'static str, f64)>,
pub partial: bool,
}
impl<C, E: Copy + Send + Sync + dyn_any::StaticTypeSized + 'static> Node<C> for RecordSourceNode<E> {
fn serve<'e, 'l>(&self, input: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
where
C: ExtractArena<ArenaRef = &'e Arena>,
{
let mut frame = slot;
let arena = ExtractArena::arena(input);
if frame.element(self.element, arena).is_none() {
return GPoll::arena_exhausted();
}
for (name, field) in &self.fields {
write_field_at(&mut frame, &self.layout, name, 0, *field);
}
// SAFETY: the writes above complete the record of this layout.
let served = unsafe { frame.finish_served() };
match self.partial {
true => GPoll::Partial(served),
false => GPoll::Final(served),
}
}
fn layout(&self) -> &Layout {
&self.layout
}
}
/// A level of `f64` lanes, each optionally carrying one fixed field.
pub struct LeveledSourceNode {
pub layout: Layout,
pub elements: Vec<f64>,
pub field: Option<(&'static str, f64)>,
}
impl<C: ExtractIndex> Node<C> for LeveledSourceNode {
fn serve<'e, 'l>(&self, input: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
where
C: ExtractArena<ArenaRef = &'e Arena>,
{
let element = self.elements[input.innermost_index() as usize % self.elements.len()];
let mut frame = slot;
let arena = ExtractArena::arena(input);
if frame.element(element, arena).is_none() {
return GPoll::arena_exhausted();
}
if let Some((name, value)) = self.field {
write_field_at(&mut frame, &self.layout, name, 0, value);
}
// SAFETY: the writes above complete the record of this layout.
GPoll::Final(unsafe { frame.finish_served() })
}
fn extent_at<'x>(&self, _input: &C, _level: u8, _frames: &Frames<'x>) -> GPoll<Extent>
where
C: ExtractArena<ArenaRef = &'x Arena>,
{
GPoll::Final(Extent::Exactly(self.elements.len()))
}
fn layout(&self) -> &Layout {
&self.layout
}
}
/// A level of `f64` lanes each carrying a transform.
pub struct LeveledTransformSource {
pub layout: Layout,
pub rows: Vec<(f64, DAffine2)>,
}
impl<C: ExtractIndex> Node<C> for LeveledTransformSource {
fn serve<'e, 'l>(&self, input: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
where
C: ExtractArena<ArenaRef = &'e Arena>,
{
let (element, transform) = self.rows[input.innermost_index() as usize % self.rows.len()];
let mut frame = slot;
let arena = ExtractArena::arena(input);
if frame.element(element, arena).is_none() {
return GPoll::arena_exhausted();
}
write_attr_at::<Transform>(&mut frame, &self.layout, transform);
// SAFETY: the writes above complete the record of this layout.
GPoll::Final(unsafe { frame.finish_served() })
}
fn extent_at<'x>(&self, _input: &C, _level: u8, _frames: &Frames<'x>) -> GPoll<Extent>
where
C: ExtractArena<ArenaRef = &'x Arena>,
{
GPoll::Final(Extent::Exactly(self.rows.len()))
}
fn layout(&self) -> &Layout {
&self.layout
}
}
/// Serves lanes carrying both a Transform no gather kernel declares and an
/// Opacity one does, so a carried column can be told apart from a written one.
pub struct LeveledCarriedSource {
pub layout: Layout,
pub rows: Vec<(f64, DAffine2, f64)>,
}
impl<C: ExtractIndex> Node<C> for LeveledCarriedSource {
fn serve<'e, 'l>(&self, input: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
where
C: ExtractArena<ArenaRef = &'e Arena>,
{
let (element, transform, opacity) = self.rows[input.innermost_index() as usize % self.rows.len()];
let mut frame = slot;
let arena = ExtractArena::arena(input);
if frame.element(element, arena).is_none() {
return GPoll::arena_exhausted();
}
write_attr_at::<Transform>(&mut frame, &self.layout, transform);
write_attr_at::<Opacity>(&mut frame, &self.layout, opacity);
// SAFETY: the writes above complete the record of this layout.
GPoll::Final(unsafe { frame.finish_served() })
}
fn extent_at<'x>(&self, _input: &C, _level: u8, _frames: &Frames<'x>) -> GPoll<Extent>
where
C: ExtractArena<ArenaRef = &'x Arena>,
{
GPoll::Final(Extent::Exactly(self.rows.len()))
}
fn layout(&self) -> &Layout {
&self.layout
}
}
/// A leveled source that keeps its count to itself: the extent is a lower
/// bound and lanes past the data answer the past-end signal.
pub struct DrainSourceNode {
pub layout: Layout,
pub count: usize,
}
impl<C: ExtractIndex> Node<C> for DrainSourceNode {
fn serve<'e, 'l>(&self, input: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
where
C: ExtractArena<ArenaRef = &'e Arena>,
{
let lane = input.innermost_index();
if lane >= self.count as u64 {
return GPoll::past_end();
}
let mut frame = slot;
let arena = ExtractArena::arena(input);
if frame.element(lane as f64, arena).is_none() {
return GPoll::arena_exhausted();
}
// SAFETY: the writes above complete the record of this layout.
GPoll::Final(unsafe { frame.finish_served() })
}
fn extent_at<'x>(&self, _input: &C, _level: u8, _frames: &Frames<'x>) -> GPoll<Extent>
where
C: ExtractArena<ArenaRef = &'x Arena>,
{
GPoll::Final(Extent::AtLeast(0))
}
fn layout(&self) -> &Layout {
&self.layout
}
}
/// Depth-0 content varying per copy: serves the enclosing (pushed) level's
/// index, which sits one link above the content's own innermost lane.
pub struct IndexSourceNode {
pub layout: Layout,
}
impl<C: ExtractIndex + ExtractIndices> Node<C> for IndexSourceNode {
fn serve<'e, 'l>(&self, input: &C, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>
where
C: ExtractArena<ArenaRef = &'e Arena>,
{
let element = input.try_index().and_then(|mut indices| indices.nth(1)).unwrap_or(0) as f64;
let mut frame = slot;
let arena = ExtractArena::arena(input);
if frame.element(element, arena).is_none() {
return GPoll::arena_exhausted();
}
// SAFETY: the writes above complete the record of this layout.
GPoll::Final(unsafe { frame.finish_served() })
}
fn layout(&self) -> &Layout {
&self.layout
}
}
/// Writes a field at the layout's resolved offset, the wiring-proven pairing
/// a generated node performs.
pub fn write_field_at<T: Copy + 'static>(frame: &mut FrameClaim<'_, '_>, layout: &Layout, name: &str, level: u8, value: T) {
let field = layout
.fields
.iter()
.find(|field| field.name == name && field.level == level)
.expect("the layout carries the written field");
assert_eq!(field.type_id, std::any::TypeId::of::<T>(), "the field was declared at this value type");
// SAFETY: the offset is this layout's own, at the field's declared type.
unsafe { frame.attr_at(field.offset, value) };
}
/// [`write_field_at`] for a census marker at level 0.
pub fn write_attr_at<A: Attribute>(frame: &mut FrameClaim<'_, '_>, layout: &Layout, value: A::Value<'static>)
where
A::Value<'static>: Copy + 'static,
{
write_field_at(frame, layout, A::NAME, 0, value);
}
pub fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
EvalScope::new(Some(0.5), None, None, generations, arena)
}
fn f64_fields(names: &[&'static str]) -> Vec<FieldWrite> {
names
.iter()
.map(|name| FieldWrite {
name,
level: 0,
size: 8,
align: 8,
type_id: std::any::TypeId::of::<f64>(),
read_erased: <Opacity as Attribute>::read_erased,
repark: None,
content_hash: None,
content_eq: None,
})
.collect()
}
/// A depth-0 `f64` record layout carrying the named `f64` fields.
pub fn f64_layout(names: &[&'static str]) -> Layout {
Layout::default().with_writes(0, element_write::<f64>(), &f64_fields(names))
}
/// A one-level `f64` layout carrying the named `f64` fields.
pub fn leveled_f64_layout(names: &[&'static str]) -> Layout {
Layout::default().with_writes(1, element_write::<f64>(), &f64_fields(names))
}
/// Frame space sized for the layouts, with a floor for small fixtures.
pub fn frames_for(layouts: &[&Layout]) -> Frames<'static> {
test_frames(layouts.iter().map(|layout| layout.frame_bytes()).sum::<usize>().max(1 << 12))
}
/// Installs the layout the compiler pass would resolve for `node` over the
/// given input layouts. The fixtures wire constants into every eager input,
/// which the pass records as lane-invariant.
pub fn install<N: Node<ContextImpl<'static>>>(mut node: N, meta: LayoutMeta, inputs: &[Option<&Layout>]) -> N {
let resolved = RecordLayout {
named_writes: Vec::new(),
named_reads: Vec::new(),
named_read_defaults: Vec::new(),
lane_invariant: u32::MAX,
footprint_free: u32::MAX,
single_lane: 0,
input_levels: Vec::new(),
..meta.resolve(inputs)
};
<N as Node<ContextImpl<'static>>>::set_layout(&mut node, resolved);
node
}
/// Installs a flipped node's output layout directly.
pub fn install_flip<N: Node<ContextImpl<'static>>>(mut node: N, layout: &Layout) -> N {
let bundle = RecordLayout {
named_writes: Vec::new(),
named_reads: Vec::new(),
named_read_defaults: Vec::new(),
frame_bytes: layout.frame_bytes(),
plan: Vec::new(),
layout: layout.clone(),
lane_invariant: u32::MAX,
footprint_free: u32::MAX,
single_lane: 0,
input_levels: Vec::new(),
};
<N as Node<ContextImpl<'static>>>::set_layout(&mut node, bundle);
node
}
/// A constant as a value source with its layout.
pub fn lifted_value<T: Clone + Send + Sync + dyn_any::StaticTypeSized + 'static>(value: T) -> (ValueSource<T>, Layout)
where
T::Static: Clone + Send + Sync,
{
let lift = ValueSource::new(value);
let layout = Node::<ContextImpl>::layout(&lift).clone();
(lift, layout)
}
pub fn bare_source(layout: &Layout, element: f64) -> RecordSourceNode<f64> {
RecordSourceNode {
layout: layout.clone(),
element,
fields: vec![],
partial: false,
}
}
}
@@ -31,6 +31,8 @@ pub struct FieldMetadata {
pub description: &'static str,
/// Index levels the node pushes when evaluating this input.
pub pushed_levels: u8,
/// Index levels of this input the node iterates itself when materializing it; they are the input's own lanes, never the caller's.
pub driven_levels: u8,
pub hidden: bool,
pub exposed: bool,
pub widget_override: RegistryWidgetOverride,
@@ -104,6 +106,14 @@ pub fn cache_key<C: CacheHash + ?Sized>(ctx: &C) -> u64 {
hasher.finish()
}
/// The lane-normalized cache key and arena generation of one evaluation, so a
/// node can keep per-evaluation scratch across its lanes.
pub fn eval_key<'e, C: CacheHash + crate::context::InjectIndex + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena> + Copy>(ctx: &C) -> (u64, u64) {
let mut keyed = *ctx;
keyed.set_index(0);
(cache_key(&keyed), ctx.arena().generation())
}
#[derive(Debug, PartialEq)]
pub enum ConstructionError {
Arity { expected: usize, got: usize },
@@ -157,7 +167,7 @@ where
{
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> crate::gpoll::GPoll<crate::record::Served<'e>>
where
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
Input: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
// SAFETY: `own` keeps the payload alive for `self`'s lifetime and Arc
// payloads are address stable.
@@ -166,7 +176,7 @@ where
fn extent_at<'x>(&self, input: &Input, level: u8, frames: &crate::record::Frames<'x>) -> crate::gpoll::GPoll<crate::gpoll::Extent>
where
Input: crate::context::ExtractArena<ArenaRef = &'x crate::arena::Arena>,
Input: crate::dispatch::AsDispatch<'x> + crate::context::ExtractArena<ArenaRef = &'x crate::arena::Arena>,
{
// SAFETY: as in serve.
unsafe { self.ptr.as_ref() }.extent_at(input, level, frames)
@@ -182,18 +192,19 @@ where
unsafe { self.ptr.as_ref() }.layout()
}
fn eval_batch<'a, 'x>(
fn eval_batch<'a, 'x, 'r>(
&'a self,
input: &'a Input,
range: std::ops::Range<u64>,
scratch: Option<&'a mut [std::mem::MaybeUninit<u64>]>,
dispatch: crate::dispatch::Dispatch<'x>,
scratch: Option<&'r mut [std::mem::MaybeUninit<u64>]>,
frames: &crate::record::Frames<'x>,
) -> crate::node::BatchStatus<'a>
) -> crate::node::BatchStatus<'r>
where
Input: crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'x crate::arena::Arena>,
'a: 'r,
'x: 'r,
Input: crate::dispatch::AsDispatch<'x> + crate::context::InjectIndex + Copy + crate::context::ExtractArena<ArenaRef = &'x crate::arena::Arena>,
{
// SAFETY: as in serve.
unsafe { self.ptr.as_ref() }.eval_batch(input, range, scratch, frames)
unsafe { self.ptr.as_ref() }.eval_batch(dispatch, scratch, frames)
}
}
@@ -1,6 +1,6 @@
// Raster types moved to raster-types crate
use crate::Color;
use crate::list::{Item, List};
use crate::list::List;
pub trait RenderComplexity {
fn render_complexity(&self) -> usize {
@@ -8,12 +8,6 @@ pub trait RenderComplexity {
}
}
impl<T: RenderComplexity> RenderComplexity for Item<T> {
fn render_complexity(&self) -> usize {
self.element().render_complexity()
}
}
impl<T: RenderComplexity> RenderComplexity for List<T> {
fn render_complexity(&self) -> usize {
self.iter_element_values().map(|element| element.render_complexity()).fold(0, usize::saturating_add)
@@ -278,6 +278,9 @@ mod tests {
plan: Vec::new(),
layout: layout.clone(),
lane_invariant: u32::MAX,
footprint_free: u32::MAX,
single_lane: 0,
input_levels: Vec::new(),
named_writes: Vec::new(),
named_reads: Vec::new(),
named_read_defaults: Vec::new(),
+6 -120
View File
@@ -61,48 +61,8 @@ macro_rules! generic {
($type:ty) => {{ $crate::Type::Generic($crate::Cow::Borrowed(stringify!($type))) }};
}
/// Constructs the [`Type`] of an `Item` holding the given element type, e.g. `item!(f64)` is the type of an `Item<f64>`.
/// The two-argument form tags the element descriptor with an alias, preserving the source spelling for widget dispatch.
#[macro_export]
macro_rules! item {
(Item<$inner:ty>) => {
$crate::Type::Item(Box::new($crate::item!($inner)))
};
($element:ty) => {
$crate::Type::Item(Box::new($crate::concrete!($element)))
};
($element:ty, $alias:ty) => {
$crate::Type::Item(Box::new($crate::concrete!($element, $alias)))
};
}
/// Constructs the [`Type`] of a `List` holding the given element type, e.g. `list!(f64)` is the type of a `List<f64>`.
#[macro_export]
macro_rules! list {
(List<$inner:ty>) => {
$crate::Type::List(Box::new($crate::list!($inner)))
};
($element:ty) => {
$crate::Type::List(Box::new($crate::concrete!($element)))
};
}
// The `List<...>`/`Item<...>` rules must appear before the generic `$type:ty` rules, and in each macro that sees the literal tokens,
// because a type captured as `ty` becomes opaque to any inner macro's ranked pattern
#[macro_export]
macro_rules! future {
(List<$inner:ty>) => {
$crate::Type::Future(Box::new($crate::list!($inner)))
};
(List<$inner:ty>, $name:ty) => {
$crate::Type::Future(Box::new($crate::list!($inner)))
};
(Item<$inner:ty>) => {
$crate::Type::Future(Box::new($crate::item!($inner)))
};
(Item<$inner:ty>, $name:ty) => {
$crate::Type::Future(Box::new($crate::item!($inner, $name)))
};
($type:ty) => {{ $crate::Type::Future(Box::new(concrete!($type))) }};
($type:ty, $name:ty) => {
$crate::Type::Future(Box::new(concrete!($type, $name)))
@@ -111,27 +71,9 @@ macro_rules! future {
#[macro_export]
macro_rules! fn_type_fut {
(List<$inner:ty>) => {
$crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::Type::Future(Box::new($crate::list!($inner)))))
};
(Item<$inner:ty>) => {
$crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::Type::Future(Box::new($crate::item!($inner)))))
};
($type:ty) => {
$crate::Type::Fn(Box::new(concrete!(())), Box::new(future!($type)))
};
($in_type:ty, List<$inner:ty>, alias: $outname:ty) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::list!($inner)))))
};
($in_type:ty, List<$inner:ty>) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::list!($inner)))))
};
($in_type:ty, Item<$inner:ty>, alias: $outname:ty) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::item!($inner, $inner)))))
};
($in_type:ty, Item<$inner:ty>) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::item!($inner)))))
};
($in_type:ty, $type:ty, alias: $outname:ty) => {
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(future!($type, $outname)))
};
@@ -280,8 +222,7 @@ impl PartialEq for TypeDescriptor {
/// Graph runtime type information used for type inference.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, PartialEq, Eq, Hash, graphene_hash::CacheHash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "PascalCase"))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Type {
/// A wrapper for some type variable used within the inference system. Resolved at inference time and replaced with a concrete type.
Generic(Cow<'static, str>),
@@ -295,41 +236,6 @@ pub enum Type {
Record(Box<Type>),
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Type {
/// Documents written against the structural rank model store `Item` and `List` wire types.
/// Our one wire kind has neither, so an `Item` reduces to the element it wraps and a `List`
/// becomes the concrete `List<..>` type it names.
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(serde::Deserialize)]
enum Stored {
Generic(Cow<'static, str>),
Concrete(TypeDescriptor),
Fn(Box<Type>, Box<Type>),
Future(Box<Type>),
Record(Box<Type>),
Item(Box<Type>),
List(Box<Type>),
}
Ok(match Stored::deserialize(deserializer)? {
Stored::Generic(name) => Type::Generic(name),
Stored::Concrete(descriptor) => Type::Concrete(descriptor),
Stored::Fn(input, output) => Type::Fn(input, output),
Stored::Future(inner) => Type::Future(inner),
Stored::Record(inner) => Type::Record(inner),
Stored::Item(element) => *element,
Stored::List(element) => Type::Concrete(TypeDescriptor {
id: None,
name: Cow::Owned(format!("core_types::list::List<{}>", element.identifier_name())),
alias: None,
size: 0,
align: 0,
}),
})
}
}
impl Default for Type {
fn default() -> Self {
concrete!(())
@@ -469,13 +375,12 @@ pub fn make_type_user_readable(ty: &str) -> String {
.replace("UVec2", "Vec2")
.replace("&str", "String");
rewrite_ranked_type_wrappers(&ty)
rewrite_list_as_array_brackets(&ty)
}
/// Rewrites `List<T>` and the whole-collection `Bundle<T>` as `T[]`, and unwraps `Item<T>` to `T`, so ranked wires read as their element type.
/// Handles nesting (e.g. `List<List<Vector>>` becomes `Vector[][]`).
/// Respects word boundaries so unrelated identifiers that happen to end in `List` or `Item` are not affected.
fn rewrite_ranked_type_wrappers(input: &str) -> String {
/// Rewrites `List<T>` as `T[]`. Handles nesting (e.g. `List<List<Vector>>` becomes `Vector[][]`).
/// Respects word boundaries so unrelated identifiers that happen to end in `List` are not affected.
fn rewrite_list_as_array_brackets(input: &str) -> String {
let bytes = input.as_bytes();
let mut result = String::with_capacity(input.len());
let mut i = 0;
@@ -486,31 +391,12 @@ fn rewrite_ranked_type_wrappers(input: &str) -> String {
let inner_start = i + b"List<".len();
if let Some(close) = find_matching_angle_bracket(bytes, inner_start) {
let inner = &input[inner_start..close];
result.push_str(&rewrite_ranked_type_wrappers(inner));
result.push_str(&rewrite_list_as_array_brackets(inner));
result.push_str("[]");
i = close + 1;
continue;
}
}
if at_word_boundary && bytes[i..].starts_with(b"Bundle<") {
let inner_start = i + b"Bundle<".len();
if let Some(close) = find_matching_angle_bracket(bytes, inner_start) {
let inner = &input[inner_start..close];
result.push_str(&rewrite_ranked_type_wrappers(inner));
result.push_str("[]");
i = close + 1;
continue;
}
}
if at_word_boundary && bytes[i..].starts_with(b"Item<") {
let inner_start = i + b"Item<".len();
if let Some(close) = find_matching_angle_bracket(bytes, inner_start) {
let inner = &input[inner_start..close];
result.push_str(&rewrite_ranked_type_wrappers(inner));
i = close + 1;
continue;
}
}
if bytes[i].is_ascii() {
result.push(bytes[i] as char);
i += 1;
+24 -5
View File
@@ -2,6 +2,10 @@
/// input per evaluation.
pub struct ValueSource<T> {
value: T,
/// The park this constant already holds in the serving arena. A value wire is
/// read once per lane, so re-parking the constant each time is what made a wide
/// level's arena cost scale with its lane count rather than with its data.
parked: crate::arena::ArenaCell<T>,
layout: crate::record::Layout,
}
@@ -12,6 +16,7 @@ where
pub fn new(value: T) -> Self {
Self {
value,
parked: crate::arena::ArenaCell::new(),
layout: crate::record::Layout::default().with_writes(0, crate::record::element_write::<T>(), &[]),
}
}
@@ -19,13 +24,27 @@ where
impl<C, T> crate::node::Node<C> for ValueSource<T>
where
T: Clone + Send + Sync + dyn_any::StaticTypeSized,
T: Clone + Send + Sync + dyn_any::StaticTypeSized + 'static,
{
fn serve<'e, 'l>(&self, input: &C, slot: crate::record::FrameClaim<'e, 'l>) -> crate::gpoll::GPoll<crate::record::Served<'e>>
where
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
slot.lift_served(crate::gpoll::GPoll::Final(self.value.clone()), input.arena())
let arena = input.arena();
// An element the arena does not park has no pointer to share, so it takes the plain write
if !crate::record::element_parked::<T>() {
return slot.lift_served(crate::gpoll::GPoll::Final(self.value.clone()), arena);
}
if let Some(parked) = self.parked.load(arena) {
return slot.lift_served_parked(parked, arena);
}
let Some((parked, weak)) = arena.alloc(self.value.clone()) else {
return crate::gpoll::GPoll::arena_exhausted();
};
self.parked.store(weak);
slot.lift_served_parked(parked, arena)
}
fn layout(&self) -> &crate::record::Layout {
@@ -67,7 +86,7 @@ where
{
fn serve<'e, 'l>(&self, input: &C, slot: crate::record::FrameClaim<'e, 'l>) -> crate::gpoll::GPoll<crate::record::Served<'e>>
where
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
C: crate::dispatch::AsDispatch<'e> + crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
{
let Some(value) = self.values.get(input.innermost_index() as usize) else {
return crate::gpoll::GPoll::error("value level addressed past its items");
@@ -77,7 +96,7 @@ where
fn extent_at<'x>(&self, _input: &C, level: u8, _frames: &crate::record::Frames<'x>) -> crate::gpoll::GPoll<crate::gpoll::Extent>
where
C: crate::context::ExtractArena<ArenaRef = &'x crate::arena::Arena>,
C: crate::dispatch::AsDispatch<'x> + crate::context::ExtractArena<ArenaRef = &'x crate::arena::Arena>,
{
match level {
0 => crate::gpoll::GPoll::Final(crate::gpoll::Extent::Exactly(self.values.len())),
Loaded 100 of 176 files, more files were not shown because too many files have changed in this diff. Show more