From f033a17bd04e8934ec25e1583c086f9e03588ee0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 14:27:44 -0800 Subject: [PATCH] 3D and Materials: rendered 3D draws see-through and blended solid colors in their opacity and blending mode Render Settings > Rendered drew the shaded faces instead of the image whenever a solid's fill or stroke was below 100% opacity or in a blending mode other than Normal. Such a solid now draws its own image in that opacity and blending mode, lit and shadowed as in the single image, in the order of the fills and strokes; with Shadows on, the shadow plane draws first, one image for each run of solids in the same opacity and blending mode. An effect on one fill or stroke draws its shadow plane behind the object's other fills and strokes, and with background white one white rectangle goes behind its images. A solid at 0% opacity draws nothing, casts no shadow and is left out of the image's size and of the rendered mesh budget. The images share the pixel and work limits; past 16 images the shaded faces are drawn. Revolve on a group still draws its shaded faces when a member's surface is see-through or blended, now with its own warning. Gradients, patterns, mapped graphics and masked members keep the shaded faces. --- crates/effects/src/catalog.rs | 2 +- crates/effects/src/revolve.rs | 136 ++++-- crates/effects/src/solids.rs | 78 ++-- crates/effects/src/solids/rendered.rs | 318 ++++++++++++--- crates/effects/src/solids/rendered/tests.rs | 431 ++++++++++++++++++-- crates/effects/src/solids/tests_mesh.rs | 12 +- crates/effects/src/solids/tests_shadow.rs | 3 +- docs/mcp.md | 21 +- docs/target-app-parity.md | 2 +- docs/three-d.md | 23 +- 10 files changed, 848 insertions(+), 178 deletions(-) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 7a6663b603..00c0043a78 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -241,7 +241,7 @@ pub fn effect_catalog() -> Vec { REVOLVE, "Revolve…", &["Effect", "3D and Materials"], - "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own; rendered draws the solid as one image with a depth buffer, lit by every light; with shadow on, every light with an intensity above 0 casts shadows on the solid and on the shadow plane in the image, and with it off none does; it draws the shaded faces when the image can't be made or a later geometry effect reshapes paths but leaves images unchanged; quality: low|medium|high (medium; 1, 2 x 2 or 3 x 3 samples a pixel, VectorCraft's own), resolution: null or ppi 1..2400 (null: Document Raster Effects Settings), background: transparent|white (transparent); any other key or value is an error)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", + "{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; in the shaded faces the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it; with render mode rendered, every light with an intensity above 0 casts shadows in the image), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), material: object ({roughness: 1, metallic: 0}; the 3D and Materials panel's Materials › Properties: roughness: 0..1 (1; lower values give a smaller, brighter highlight), metallic: 0..1 (0; higher values tint the reflected light with the paint and darken the diffuse light); a key left out keeps its default, and any other key or value is an error; the default draws as before), render: object ({mode: shaded}; mode: shaded|wireframe|rendered, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own; rendered draws the solid as one image with a depth buffer, lit by every light; with shadow on, every light with an intensity above 0 casts shadows on the solid and on the shadow plane in the image, and with it off none does; it draws the shaded faces when the image can't be made, for a gradient, pattern or graphics, or when a later geometry effect reshapes paths but leaves images unchanged; a solid below 100% opacity or in a blending mode other than Normal draws its own image in that opacity and blending mode (Revolve on a group draws the shaded faces instead); quality: low|medium|high (medium; 1, 2 x 2 or 3 x 3 samples a pixel, VectorCraft's own), resolution: null or ppi 1..2400 (null: Document Raster Effects Settings), background: transparent|white (transparent); any other key or value is an error)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.", json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"material":{"roughness":1.0,"metallic":0.0},"render":{"mode":"shaded"}}), ), g( diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 8d4e448162..72f8504201 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -873,8 +873,8 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul let ctx = GeomContext::of(n); let mut keep = |out: &mut Vec, path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result<(), String> { let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; - let (paint, opacity, _) = paint_of(item); - surface_meshes(path, rule, b, fx, fx_options(fx), (&paint, opacity, 1.0), true)? + let (paint, opacity, blend) = paint_of(item); + surface_meshes(path, rule, b, fx, fx_options(fx), (&paint, opacity, 1.0, blend), true)? .into_iter() .try_for_each(|m| crate::solids::keep_mesh(out, total, m, limit)) }; @@ -908,20 +908,21 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul /// ([`crate::MeshGraphics`]), the points the canvas places the graphics by /// ([`crate::solids::graphics::surface_parts`]), after a mesh of the rest (the end caps and the cut /// sides). As on the canvas, the graphics take `opacity`, and `member` applies to the side and its -/// graphics together. Otherwise the surface is one plain mesh. +/// graphics together. Otherwise the surface is one plain mesh. Every mesh carries the paint's +/// blending mode `blend`. fn surface_meshes( path: &PathData, rule: FillRule, b: Rect, fx: &Effect, options: Revolve, - (paint, opacity, member): (&Paint, f32, f32), + (paint, opacity, member, blend): (&Paint, f32, f32, vectorcraft_doc::color::BlendMode), graphics: bool, ) -> Result, String> { let material = crate::solids::material::of(&fx.id, &merged_params(&fx.id, &fx.params)); let projection = Some(vectorcraft_three_d::revolve_mesh_projection(b, options)); surface_meshes_of(path, rule, b, fx, options, (paint, opacity, member), graphics) - .map(|meshes| meshes.into_iter().map(|m| crate::SolidMesh { material, projection, ..m }).collect()) + .map(|meshes| meshes.into_iter().map(|m| crate::SolidMesh { material, projection, blend, ..m }).collect()) } /// [`surface_meshes`] in the default material. @@ -1072,13 +1073,14 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result Result, String> { // The graphics go on the side of the member with the longest profile, as the canvas draws them. let longest = if options.map_surface { graphics_member(shapes, b, options) } else { None }; let mut out = vec![]; for (k, s) in shapes.iter().enumerate() { let Some(item) = surface_item(&s.items) else { continue }; - let (paint, opacity, _) = paint_of(item); - for mesh in surface_meshes(&s.path, s.rule, b, fx, options, (&paint, opacity, s.opacity), longest == Some(k))? { + let (paint, opacity, blend) = paint_of(item); + if rendered && !crate::solids::shadow::casts(opacity * s.opacity) { + continue; + } + for mesh in surface_meshes(&s.path, s.rule, b, fx, options, (&paint, opacity, s.opacity, blend), longest == Some(k))? { crate::solids::keep_mesh(&mut out, total, mesh, limit)?; } } @@ -1108,7 +1114,9 @@ pub fn revolve_art_drawn_in(doc: Option<&Document>, n: &Node) -> Option { } /// [`revolve_art_in`], or with `expand` Revolve's Expand Appearance art, built for `build`, with -/// the reason a rendered image can't be made kept in `warning`. +/// the reason a rendered image can't be made kept in `warning`. Item effects separate the shadow +/// plane behind every fill and stroke; opaque Normal object effects keep one image with shadows. +/// Check, Bounds and Draw use the same layer plan. pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, build: Build, warning: &mut Option) -> Option { let check_only = build == Build::Check; if !has_revolve(n) { @@ -1140,11 +1148,12 @@ pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, buil let item = surface_item(&paints)?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); let later = n.appearance.effects.get(index + 1..).unwrap_or_default(); - let image = surface_image(ImageFor { doc, id: n.id, build }, fx, later, &path, rule, item, warning); + let image = surface_image(ImageFor { doc, id: n.id, build, apart: false }, fx, later, &path, rule, item, warning); if check_only { return None; } - if let Some(image) = image { + if let Some((behind, image)) = image { + children.extend(behind); children.push(image); } else if crate::solids::renders_wireframe(fx) { // In wireframe mode the edges of the faces, with no shadow. @@ -1180,14 +1189,20 @@ pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, buil } let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original)); // Rendered, this fill's or stroke's surface as an image, under the effects after its - // Revolve, with the shadows in the image. + // Revolve, with the shadows on the surface in the image; the shadow plane's images go + // behind every item's art, as the shaded faces' shadow does. let later = item.effects().get(index + 1..).unwrap_or_default(); - let image = surface_image(ImageFor { doc, id: n.id, build }, fx, later, &p, rule, item, warning); + let image = surface_image(ImageFor { doc, id: n.id, build, apart: true }, fx, later, &p, rule, item, warning); if check_only { continue; } - if let Some(mut image) = image { - Arc::make_mut(&mut image).appearance.effects = later.iter().filter(|e| !is_revolve(&e.id)).cloned().collect(); + if let Some((behind, mut image)) = image { + let effects: Vec = later.iter().filter(|e| !is_revolve(&e.id)).cloned().collect(); + for mut plane in behind { + Arc::make_mut(&mut plane).appearance.effects = effects.clone(); + shadows.push(plane); + } + Arc::make_mut(&mut image).appearance.effects = effects; children.push(image); continue; } @@ -1223,18 +1238,22 @@ pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, buil } /// What a rendered image is made for: the object `id` it is art of, the document `doc` whose raster -/// effects resolution it takes, and the art `build` it goes in. +/// effects resolution it takes, the art `build` it goes in, and whether an item effect needs its +/// shadow plane `apart` from its surface in every build. #[derive(Clone, Copy)] struct ImageFor<'a> { doc: Option<&'a Document>, id: NodeId, build: Build, + apart: bool, } /// The rendered image of Revolve `fx` for `to`, swept from `path` (filled under `rule`) about its /// own bounds and painted with `item`; `later` are the effects after `fx`. `None` when `fx` draws no /// image or `to.build` takes none, and when the image can't be made, with the reason in `warning`: -/// the caller then draws the shaded faces. +/// the caller then draws the shaded faces. The image comes in two parts: the shadow plane's images, +/// for the caller to draw behind every fill and stroke ([`crate::solids::rendered::art_apart`]), +/// and the rest when `to.apart` is true. Otherwise opaque Normal solids share one image with shadows. fn surface_image( to: ImageFor, fx: &Effect, @@ -1243,21 +1262,17 @@ fn surface_image( rule: FillRule, item: &AppearanceItem, warning: &mut Option, -) -> Option> { +) -> Option<(Vec>, Arc)> { let p = merged_params(&fx.id, &fx.params); let settings = crate::render_settings(&fx.id, &p).filter(|_| to.build != Build::Vector)?; - let paint = item.paint(); - let opacity = item.opacity(); + let (paint, opacity, blend) = paint_of(item); let result = if crate::solids::rendered::reshapes_paths_only(later) { Err(crate::solids::rendered::PATHS_ONLY.into()) - } else if !crate::mapped_graphics(&p).is_empty() - || !crate::solids::rendered::takes([item], false) - || crate::solids::mesh_color(paint, opacity)[3] != 1.0 - { + } else if !crate::mapped_graphics(&p).is_empty() || !crate::solids::rendered::takes([item], false) { Err(crate::solids::rendered::OPAQUE_ONLY.into()) } else if let Some(b) = path.bounds() { let options = rule_options(fx, rule); - surface_meshes(path, rule, b, fx, options, (paint, opacity, 1.0), true).and_then(|meshes| { + surface_meshes(path, rule, b, fx, options, (&paint, opacity, 1.0, blend), true).and_then(|meshes| { let lighting = crate::solids::rendered::lighting(&fx.id, &p); let lighting = match crate::solids::rendered::plane_settings(&p, &lighting).filter(|_| crate::solids::shadow::casts(opacity)) { Some(shadow) => { @@ -1267,7 +1282,10 @@ fn surface_image( } None => lighting, }; - image_for(to, &lighting, &meshes, settings) + if to.build == Build::Draw { + return crate::solids::rendered::art_apart(to.doc, to.id, &lighting, &meshes, settings, to.apart).map(Some); + } + image_for(to, &lighting, &meshes, settings).map(|image| image.map(|image| (vec![], image))) }) } else { Err("Revolve requires a shape with at least two anchors".into()) @@ -1277,8 +1295,10 @@ fn surface_image( /// [`surface_image`] of the members `shapes` of a group, every member swept about the axis of `b` /// with `options` into one image, as the shaded faces draw them in one order. The shaded faces are -/// drawn instead when a member's surface is not an opaque solid color in Normal blending, or when a -/// member, or a group it is in, has an opacity below 100%, a blending mode or an opacity mask. +/// drawn instead when a member's surface is not a solid color ([`crate::solids::rendered::OPAQUE_ONLY`]), +/// when a member or a group it is in has a blending mode or an opacity mask (the same message), and +/// when a member's surface is below 100% opacity or in a blending mode other than Normal, the +/// member's own opacity included ([`crate::solids::rendered::GROUP_OPAQUE_ONLY`]). fn members_image( to: ImageFor, fx: &Effect, @@ -1296,14 +1316,17 @@ fn members_image( Err("Revolve requires a group holding a shape with a fill or stroke".into()) } else if crate::solids::rendered::reshapes_paths_only(later) { Err(crate::solids::rendered::PATHS_ONLY.into()) - } else if crate::mapped_graphics(&p).is_empty() - && crate::solids::rendered::takes(surfaces, crate::solids::profiles_have_masks(profiles)) - && shapes.iter().all(|s| { - let Some(item) = surface_item(&s.items) else { return true }; - crate::solids::mesh_color(item.paint(), item.opacity() * s.opacity)[3] == 1.0 - }) - { - members_meshes(fx, shapes, b, options, &mut 0, crate::solids::MAX_MESH_TRIANGLES).and_then(|meshes| { + } else if !crate::mapped_graphics(&p).is_empty() || !crate::solids::rendered::takes(surfaces, crate::solids::profiles_have_masks(profiles)) { + Err(crate::solids::rendered::OPAQUE_ONLY.into()) + } else if !shapes.iter().all(|s| { + let Some(item) = surface_item(&s.items) else { return true }; + let (paint, opacity, blend) = paint_of(item); + !crate::solids::shadow::casts(opacity * s.opacity) + || (crate::solids::mesh_color(&paint, opacity * s.opacity)[3] == 1.0 && blend == vectorcraft_doc::color::BlendMode::Normal) + }) { + Err(crate::solids::rendered::GROUP_OPAQUE_ONLY.into()) + } else { + members_meshes(fx, shapes, b, options, &mut 0, crate::solids::MAX_MESH_TRIANGLES, true).and_then(|meshes| { let lighting = crate::solids::rendered::lighting(&fx.id, &p); let lighting = match crate::solids::rendered::plane_settings(&p, &lighting) { Some(shadow) => { @@ -1321,14 +1344,13 @@ fn members_image( }; image_for(to, &lighting, &meshes, settings) }) - } else { - Err(crate::solids::rendered::OPAQUE_ONLY.into()) }; crate::solids::rendered::reported(result, warning) } /// The rendered image of `meshes` lit by `lighting` for `to`: for [`Build::Bounds`] its rectangle -/// without pixels, for [`Build::Check`] only the check of its limits. +/// without pixels, for [`Build::Check`] only the check of its limits. Every build uses `to.apart` +/// to choose whether an item effect's shadow plane is separate. fn image_for( to: ImageFor, lighting: &crate::solids::rendered::Lighting, @@ -1336,9 +1358,9 @@ fn image_for( settings: crate::solids::wireframe::RenderSettings, ) -> Result>, String> { if to.build == Build::Bounds { - crate::solids::rendered::bounds_art(to.doc, to.id, lighting, meshes, settings) + crate::solids::rendered::bounds_art(to.doc, to.id, lighting, meshes, settings, to.apart) } else { - crate::solids::rendered::art(to.doc, to.id, lighting, meshes, settings, to.build == Build::Check) + crate::solids::rendered::art(to.doc, to.id, lighting, meshes, settings, to.apart, to.build == Build::Check) } } @@ -1462,6 +1484,7 @@ pub(crate) fn overlaps(a: Rect, b: Rect) -> bool { /// [`art`] of group or layer `n`: every member swept about one axis on the bounds of all of them, /// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when /// the effect is only on the group's own fills or strokes or when its members can't be revolved. +/// Rendered opaque Normal members share one image with their shadows in every build. fn group_art(doc: Option<&Document>, n: &Node, expand: bool, build: Build, warning: &mut Option) -> Option { let check_only = build == Build::Check; let index = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id))?; @@ -1489,7 +1512,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool, build: Build, warni // Rendered, one image of every member's surface, with the shadows of every light on the // surfaces and on the shadow plane; the shaded faces when it can't be made. let later = n.appearance.effects.get(index + 1..).unwrap_or_default(); - let image = members_image(ImageFor { doc, id: n.id, build }, fx, later, &shapes, b, options, warning); + let image = members_image(ImageFor { doc, id: n.id, build, apart: false }, fx, later, &shapes, b, options, warning); if check_only { return None; } @@ -1712,6 +1735,33 @@ mod tests { crate::new_effect(REVOLVE, &json!({})).unwrap() } #[test] + fn zero_opacity_members_do_not_spend_the_rendered_mesh_budget() { + let visible = profile_node(); + let mut invisible = profile_node(); + invisible.id = NodeId(2); + invisible.opacity = 0.0; + let mut group = Node::group(NodeId(10), vec![Arc::new(visible), Arc::new(invisible)]); + let fx = crate::new_effect(REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap(); + let shapes = members(&group, "Revolve").unwrap(); + let b = union_bounds(&shapes).unwrap(); + let options = shared_options(&shapes, fx_options(&fx)).unwrap(); + let exported = members_meshes(&fx, &shapes, b, options, &mut 0, usize::MAX, false).unwrap(); + assert_eq!(exported.len(), 2); + let limit = exported[0].mesh.triangles.len(); + assert!(members_meshes(&fx, &shapes, b, options, &mut 0, limit, false).is_err()); + let mut total = 0; + let rendered = members_meshes(&fx, &shapes, b, options, &mut total, limit, true).unwrap(); + assert_eq!(rendered.len(), 1); + assert_eq!(total, limit); + assert_eq!(rendered[0].projection, exported[0].projection); + group.appearance.effects.push(fx); + assert_eq!(crate::rendered_warning(&Document::new(400.0, 400.0), &group), None); + let art = revolve_art_drawn_in(None, &group).unwrap(); + let mut images = 0; + art.walk(&mut |n| images += usize::from(matches!(n.kind, NodeKind::Image(_)))); + assert!(images > 0); + } + #[test] fn seam_strokes_stay_within_half_a_stroke_width_of_each_face() { use kurbo::Shape; for shade in [false, true] { diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 5fca519b94..8865de9cee 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -2072,13 +2072,15 @@ type ShadowAndSurfaces = (Vec>, Vec>); /// blending mode, and those of a group it is in, apply to the surfaces of the members it holds /// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it /// off), cast from the faces the solids drawn kept ([`cast_built`]), to be drawn behind every -/// surface of the object, and the surfaces. +/// surface of the object, and the surfaces. Rendered opaque Normal solids keep their shadows in +/// one image unless `apart` separates an item effect's plane, with the same plan in every build. fn art_for( doc: Option<&Document>, n: &Node, effects: &[Effect], shapes: &[Profile], build: Build, + apart: bool, warning: &mut Option, ) -> Option { let (fx, later) = effects.split_first()?; @@ -2098,7 +2100,7 @@ fn art_for( let image = if rendered::reshapes_paths_only(later) { Err(rendered::PATHS_ONLY.into()) } else if mapped_graphics(&p).is_empty() && rendered::takes(drawn_items(&fx.id, shapes), has_masks(shapes)) { - meshes_for(fx, shapes, &mut 0, MAX_MESH_TRIANGLES).and_then(|meshes| { + meshes_for(fx, shapes, &mut 0, MAX_MESH_TRIANGLES, true).and_then(|meshes| { let lighting = rendered::lighting(&fx.id, &p); let lighting = match cast_shadow_with(&fx.id, &p, shapes, rendered::plane_settings(&p, &lighting))? { Some((caster, shadow, cast)) => { @@ -2107,10 +2109,10 @@ fn art_for( } None => lighting, }; - if build == Build::Bounds { - rendered::bounds_art(doc, n.id, &lighting, &meshes, settings) - } else { - rendered::art(doc, n.id, &lighting, &meshes, settings, build == Build::Check) + match build { + Build::Bounds => rendered::bounds_art(doc, n.id, &lighting, &meshes, settings, apart).map(|art| art.map(|art| (vec![], art))), + Build::Draw => rendered::art_apart(doc, n.id, &lighting, &meshes, settings, apart).map(Some), + _ => rendered::art(doc, n.id, &lighting, &meshes, settings, apart, true).map(|art| art.map(|art| (vec![], art))), } }) } else { @@ -2120,8 +2122,9 @@ fn art_for( if build == Build::Check { return Some((vec![], vec![])); } - if let Some(image) = image { - return Some((vec![], vec![image])); + // The shadow plane's images go behind every surface, as the shaded faces' shadow does. + if let Some((plane, image)) = image { + return Some((plane, vec![image])); } } let cast = casts_shadow(&fx.id, &p); @@ -2923,6 +2926,9 @@ pub(crate) enum Build { Draw, } +/// Build the object's 3D art or report its rendered fallback. Object and group effects combine +/// opaque Normal solids with their shadows; item effects keep the plane behind every fill and stroke. +/// Check, Bounds and Draw use the same layer plan. pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, build: Build, warning: &mut Option) -> Option { if !has_solid(n) { return None; @@ -2938,8 +2944,15 @@ pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, build: Build let remaining: Vec; if let Some((index, _)) = solid(&n.appearance.effects) { let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); - let (shadow, surfaces) = - art_for(doc, n, &n.appearance.effects[index..], &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], build, warning)?; + let (shadow, surfaces) = art_for( + doc, + n, + &n.appearance.effects[index..], + &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], + build, + false, + warning, + )?; children.extend(shadow.into_iter().chain(surfaces)); // Later geometry effects act on the projected art as a whole. remaining = past_effect(&n.appearance.effects, index); @@ -2961,6 +2974,7 @@ pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, build: Build &item.effects()[index..], &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }], build, + true, warning, )?; let later: Vec = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect(); @@ -2990,12 +3004,13 @@ pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, build: Build /// [`solid_art`] of group or layer `n`: its object-level 3D effect on its members together. The /// geometry effects before it reshape the members, those after it bend the result as a whole; the /// group's own fills and strokes are not drawn. `None` when the effect is only on one of the -/// group's own fills or strokes, or when its members can't become solids. +/// group's own fills or strokes, or when its members can't become solids. Rendered opaque Normal +/// members share one image with their shadows in every build. fn group_solid_art(doc: Option<&Document>, n: &Node, build: Build, warning: &mut Option) -> Option { let (index, _) = solid(&n.appearance.effects)?; let mut shapes = members(n, "").ok()?; reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); - let (shadow, surfaces) = art_for(doc, n, &n.appearance.effects[index..], &shapes, build, warning)?; + let (shadow, surfaces) = art_for(doc, n, &n.appearance.effects[index..], &shapes, build, false, warning)?; let children = shadow.into_iter().chain(surfaces).collect(); let remaining = past_effect(&n.appearance.effects, index); let mut art = n.clone(); @@ -3307,12 +3322,15 @@ pub struct SolidMesh { /// The projection that takes the mesh's points to where the effect draws them on the page; /// `None` when it is not known. pub projection: Option, + /// The blending mode of the fill or stroke the solid is painted with. + pub blend: BlendMode, } impl SolidMesh { - /// A mesh painted `color`, with no graphics, in the default material, with no projection. + /// A mesh painted `color` in Normal blending, with no graphics, in the default material, with no + /// projection. pub fn plain(mesh: Mesh, color: [f32; 4]) -> Self { - Self { mesh, color, graphics: None, material: vectorcraft_three_d::Material::DEFAULT, projection: None } + Self { mesh, color, graphics: None, material: vectorcraft_three_d::Material::DEFAULT, projection: None, blend: BlendMode::Normal } } } @@ -3408,8 +3426,9 @@ pub(crate) fn keep_mesh(out: &mut Vec, total: &mut usize, mesh: Solid /// The solids effect `fx` builds from `shapes`, as [`art_for`] draws them, as meshes: Rotate turns /// every fill and stroke; Extrude & Bevel and Inflate build one from each shape's top fill and one /// from the outline of each stroke. A stroke whose solid is past the limits is left out. Each mesh -/// is counted against `limit` ([`keep_mesh`]) before the next is built. -fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) -> Result, String> { +/// is counted against `limit` ([`keep_mesh`]) before the next is built. With `rendered`, +/// zero-opacity solids add no meshes or triangles to the budget; the shared bounds stay the same. +fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize, rendered: bool) -> Result, String> { let label = crate::effect_info(&fx.id).map_or("This effect", |e| e.label.trim_end_matches('…')); let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?; let p = crate::merged_params(&fx.id, &fx.params); @@ -3417,17 +3436,20 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) let material = material::of(&fx.id, &p); let mut out = vec![]; // A solid's parts with and without graphics count together against the limit. - let mut keep = |out: &mut Vec, (mesh, projection): (Mesh, _), (paint, opacity): (&Paint, f32), bounds: Rect| { + let mut keep = |out: &mut Vec, (mesh, projection): (Mesh, _), (paint, opacity, blend): (&Paint, f32, BlendMode), bounds: Rect| { + if rendered && !shadow::casts(opacity) { + return Ok(()); + } split_graphics(&fx.id, &p, bounds, mesh, (mesh_color(paint, opacity), opacity)) .into_iter() - .try_for_each(|part| keep_mesh(out, total, SolidMesh { material, projection, ..part }, limit)) + .try_for_each(|part| keep_mesh(out, total, SolidMesh { material, projection, blend, ..part }, limit)) }; if is_plane(&fx.id) { for s in shapes { for item in &s.items { - let (paint, opacity, _) = paint_of(item, s.opacity); + let (paint, opacity, blend) = paint_of(item, s.opacity); let (area, rule) = region(&s.path, s.rule, item); - keep(&mut out, vectorcraft_three_d::plane_meshed(&area, rule, b, view)?, (&paint, opacity), b)?; + keep(&mut out, vectorcraft_three_d::plane_meshed(&area, rule, b, view)?, (&paint, opacity, blend), b)?; } } return Ok(out); @@ -3463,8 +3485,8 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) } match solid.mesh() { Ok(mesh) => { - let (paint, opacity, _) = paint_of(item, *member); - keep(&mut out, (mesh, solid.projection()), (&paint, opacity), bounds)?; + let (paint, opacity, blend) = paint_of(item, *member); + keep(&mut out, (mesh, solid.projection()), (&paint, opacity, blend), bounds)?; } Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {} Err(e) => return Err(e), @@ -3527,21 +3549,27 @@ fn meshes_within(doc: Option<&Document>, n: &Node, total: &mut usize, limit: usi let label = crate::effect_info(&fx.id).map_or("This effect", |e| e.label.trim_end_matches('…')); let mut shapes = members(n, label)?; reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes); - meshes_for(fx, &shapes, total, limit)? + meshes_for(fx, &shapes, total, limit, false)? } else { let (path, rule) = object_profile(n, label)?; let ctx = GeomContext::of(n); let (sources, paints) = solid_paint_sources(n); if let Some((index, fx)) = solid(&n.appearance.effects) { let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx); - meshes_for(fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], total, limit)? + meshes_for(fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], total, limit, false)? } else { let path = geometry(&path, &n.appearance.effects, &ctx); let mut out = vec![]; for (source, item) in sources.into_iter().zip(&paints) { if let Some((index, fx)) = solid(item.effects()) { let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(source.unwrap_or(item))); - out.extend(meshes_for(fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }], total, limit)?); + out.extend(meshes_for( + fx, + &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }], + total, + limit, + false, + )?); } } out diff --git a/crates/effects/src/solids/rendered.rs b/crates/effects/src/solids/rendered.rs index a21ccbbba2..890d5176da 100644 --- a/crates/effects/src/solids/rendered.rs +++ b/crates/effects/src/solids/rendered.rs @@ -7,7 +7,8 @@ use std::io::Cursor; use std::sync::Arc; use craft_raster3d::{Limits, Scene, Vertex, srgb_to_linear, try_encode, try_render_cpu, try_shadow_maps}; -use vectorcraft_doc::{ImageBlob, ImageObject, Node, NodeId, NodeKind}; +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, ImageBlob, ImageObject, Node, NodeId, NodeKind}; use vectorcraft_geom::{Affine, Rect}; use vectorcraft_three_d::{Light, MeshProjection}; @@ -18,9 +19,13 @@ use super::wireframe::RenderSettings; /// shaded faces. pub const TOO_LARGE: &str = "The 3D render is too large; showing the shaded faces instead"; -/// The message for a solid painted with something other than an opaque solid color in Normal -/// blending, or with graphics; the effect then draws its shaded faces. -pub const OPAQUE_ONLY: &str = "The 3D render shows opaque solid colors only; showing the shaded faces instead"; +/// The message for a solid painted with something other than a solid color, one with graphics, and +/// one under a group member's opacity mask or blending mode; the effect then draws its shaded faces. +pub const OPAQUE_ONLY: &str = "The 3D render shows solid colors only; showing the shaded faces instead"; + +/// The message for Revolve on a group with a member painted below 100% opacity or in a blending +/// mode other than Normal; the effect then draws its shaded faces. +pub const GROUP_OPAQUE_ONLY: &str = "Revolve on a group renders opaque members in Normal blending only; showing the shaded faces instead"; /// The message for a later geometry effect that reshapes paths but leaves images unchanged. pub const PATHS_ONLY: &str = "A later effect reshapes the 3D object's paths; showing the shaded faces instead"; @@ -60,15 +65,21 @@ pub fn three_d_bounds_art_in(doc: Option<&vectorcraft_doc::Document>, n: &Node) } /// The image rectangle for painted measurements, with the same eligibility and scene limits as -/// the rendered image, without rasterizing or adding an image to the cache. +/// the rendered image, using `apart` to separate an item effect's plane in every build, without +/// rasterizing or adding an image to the cache. pub(crate) fn bounds_art( doc: Option<&vectorcraft_doc::Document>, id: NodeId, lighting: &Lighting, meshes: &[SolidMesh], settings: RenderSettings, + apart: bool, ) -> Result>, String> { - art(doc, id, lighting, meshes, settings, true)?; + art(doc, id, lighting, meshes, settings, apart, true)?; + // Without drawn solids there is no image or white background to measure. + if layers(meshes, lighting, apart).is_empty() { + return Ok(Some(Arc::new(Node::group(id, vec![])))); + } let m = measure(meshes, lighting, settings, doc.map_or(72.0, |d| d.raster_ppi()), false, &Limits::default())?; let object = ImageObject { key: String::new(), @@ -84,7 +95,7 @@ pub(crate) fn bounds_art( /// The rendered image of `result`, or `None` after a successful check. An error keeps its message /// in `warning` when no earlier reason is there; the caller then draws its shaded faces. -pub(crate) fn reported(result: Result>, String>, warning: &mut Option) -> Option> { +pub(crate) fn reported(result: Result, String>, warning: &mut Option) -> Option { match result { Ok(image) => image, Err(message) => { @@ -179,11 +190,25 @@ pub fn render( doc_ppi: f64, draft: bool, limits: &Limits, +) -> Result { + render_layer(meshes, lighting, Layer::All, settings, doc_ppi, draft, limits) +} + +/// [`render`] of what `layer` draws. Every layer of the same meshes and lighting covers the same +/// page rectangle, and the measured projection and dimensions build its scene. +fn render_layer( + meshes: &[SolidMesh], + lighting: &Lighting, + layer: Layer, + settings: RenderSettings, + doc_ppi: f64, + draft: bool, + limits: &Limits, ) -> Result { let too_large = || TOO_LARGE.to_string(); - let Measured { projection, rect, z, clip, cols, rows, samples: k, low } = measure(meshes, lighting, settings, doc_ppi, draft, limits)?; - let scale = f64::from(cols * k) / rect.width(); - let mut scene = scene(meshes, lighting, projection, z, clip, (cols * k, rows * k), scale).ok_or_else(too_large)?; + let m = measure(meshes, lighting, settings, doc_ppi, draft, limits)?; + let mut scene = scene(meshes, lighting, layer, &m).ok_or_else(too_large)?; + let Measured { rect, cols, rows, samples: k, low, .. } = m; scene.ssaa = k; #[cfg(test)] RASTERIZATIONS.with(|n| n.set(n.get() + 1)); @@ -260,13 +285,14 @@ fn measure( /// craft-raster3d at 2680a3b3fe464c7afa3d260b33a828fa94e12f6d: lib.rs:178-223, /// scene.rs:242-278,325-328, raster.rs:245-281,307-385,740-747 and /// shadow.rs:109-135,262-276,316-356,413-449,500-515,533-538,576-657. -/// Measured solids and the shadow plane lie inside the clip volume, the solids use opaque, visible +/// Measured solids and the shadow plane lie inside the clip volume, the solids use opaque /// materials, the plane's two triangles hold no texture and the lights are directional, so each -/// source triangle contributes one bounding box, without clipping or an alpha-discard search. Raster and shadow work have separate budgets, as in the renderer. -fn check(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, ppi: f64, limits: &Limits) -> Result<(), String> { +/// drawn source triangle contributes one bounding box, without clipping or an alpha-discard search; +/// a triangle `layer` does not draw adds no raster work. Raster and shadow work have separate +/// budgets, as in the renderer. The scene takes its projection and raster dimensions from the measurement. +fn check(meshes: &[SolidMesh], lighting: &Lighting, layer: Layer, settings: RenderSettings, ppi: f64, limits: &Limits) -> Result<(), String> { let m = measure(meshes, lighting, settings, ppi, false, limits)?; - let size = (m.cols * m.samples, m.rows * m.samples); - let s = scene(meshes, lighting, m.projection, m.z, m.clip, size, f64::from(size.0) / m.rect.width()).ok_or(TOO_LARGE)?; + let s = scene(meshes, lighting, layer, &m).ok_or(TOO_LARGE)?; limits.check(s.width, s.height).map_err(|_| TOO_LARGE)?; if s.indices.len() as u64 / 3 > limits.max_triangles || s.vertices.len() as u64 > limits.max_vertices || s.lights.len() > limits.max_lights { return Err(TOO_LARGE.into()); @@ -274,7 +300,8 @@ fn check(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, pp let transform = |matrix: &[[f32; 4]], p: [f32; 3], row: usize| matrix[row][0] * p[0] + matrix[row][1] * p[1] + matrix[row][2] * p[2] + matrix[row][3]; let mut work = 0u64; - for tri in s.indices.as_chunks::<3>().0 { + let drawn = |t: &[u32; 3]| s.materials.get(s.vertices[t[0] as usize].material as usize).is_some_and(|m| m.visible); + for tri in s.indices.as_chunks::<3>().0.iter().filter(|t| drawn(t)) { let mut points = [[0.0; 2]; 3]; for (point, &i) in points.iter_mut().zip(tri) { let p = s.vertices[i as usize].pos; @@ -381,13 +408,17 @@ fn receiver(lighting: &Lighting) -> &[[f64; 3]] { } /// The page bounds the points of `meshes` and the shadow plane's corners `plane` project to, and -/// the range of their depths. `None` with no mesh point, a point that isn't finite, or one at or +/// the range of their depths. Solids at 0% opacity, which draw nothing and cast no shadow, are left +/// out unless every solid is. `None` with no mesh point, a point that isn't finite, or one at or /// behind the eye. fn extent(meshes: &[SolidMesh], plane: &[[f64; 3]], projection: MeshProjection) -> Option<(Rect, [f64; 2])> { let mut bounds: Option = None; let mut z = [f64::INFINITY, f64::NEG_INFINITY]; - meshes.iter().flat_map(|m| &m.mesh.positions).next()?; - for p in meshes.iter().flat_map(|m| &m.mesh.positions).chain(plane) { + let drawn = |m: &&SolidMesh| super::shadow::casts(m.color[3]); + let any = meshes.iter().any(|m| drawn(&m)); + let points = || meshes.iter().filter(|m| !any || drawn(m)).flat_map(|m| &m.mesh.positions); + points().next()?; + for p in points().chain(plane) { if !p.iter().all(|v| v.is_finite()) || projection.eye.is_some_and(|e| p[2] >= e * NEAREST) { return None; } @@ -429,27 +460,33 @@ fn clip(projection: MeshProjection, rect: Rect, z: [f64; 2]) -> Option<[[f32; 4] m.iter().flatten().all(|v| v.is_finite()).then_some(m) } -/// The scene of `meshes` for an image `size` raster pixels with clip matrix `clip`: every triangle in world +/// The scene of `meshes` with the projection, clip matrix and raster dimensions in `measured`: every triangle in world /// space (mesh space with y down, as the page is), opaque ones first, then /// those of see-through solids from back to front; one material for each mesh; one parallel light, -/// casting shadows, for each of `lighting`'s lights. `scale` is raster pixels per point, including -/// the samples per image pixel. -fn scene( - meshes: &[SolidMesh], - lighting: &Lighting, - projection: MeshProjection, - z: [f64; 2], - clip: [[f32; 4]; 4], - size: (u32, u32), - scale: f64, -) -> Option { +/// casting shadows, for each of `lighting`'s lights. Shadow diffusion scales to the measured raster +/// pixels per point, including the samples per image pixel. With a `layer` other than [`Layer::All`] only the solid or the +/// shadow plane it names is drawn, opaque, and only the solids that cast in that layer cast +/// shadows; the other casting solids stay in the scene unseen. Zero-opacity solids add no triangles. +fn scene(meshes: &[SolidMesh], lighting: &Lighting, layer: Layer, measured: &Measured) -> Option { + let Measured { projection, z, clip, .. } = *measured; + let size = (measured.cols * measured.samples, measured.rows * measured.samples); + let scale = f64::from(size.0) / measured.rect.width(); let eye = projection.eye.unwrap_or(z[1] + 1.0); let mut vertices = vec![]; let mut opaque: Vec<[u32; 3]> = vec![]; let mut clear: Vec<([u32; 3], f64)> = vec![]; let mut materials = vec![]; + let shadows = lighting.lights.iter().any(|l| lighting.casts(l)); for (index, m) in meshes.iter().enumerate() { let [r, g, b, alpha] = m.color.map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.0 }); + let casts = super::shadow::casts(m.color[3]); + let (visible, casts, alpha) = match layer { + Layer::All | Layer::Solids => (casts, casts, alpha), + Layer::Solid(k) => (index == k, casts, 1.0), + Layer::Plane(start, end) => (false, casts && (start..end).contains(&index), 1.0), + }; + let casts = casts && shadows; + let skipped = !visible && !casts; materials.push(craft_raster3d::Material { base: [srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b), 1.0], metallic: m.material.metallic() as f32, @@ -457,9 +494,14 @@ fn scene( opacity: alpha, double_sided: true, unlit: !lighting.shade, - casts_shadows: true, + casts_shadows: casts, + visible, ..Default::default() }); + // A solid this image neither draws nor shadows with adds no triangles. + if skipped { + continue; + } let base = vertices.len() as u32; let mesh = &m.mesh; for (i, p) in mesh.positions.iter().enumerate() { @@ -489,7 +531,7 @@ fn scene( // The shadow plane: drawn only where a shadow falls on it, black at the vector shadow's // opacity, behind every surface, so first in the see-through range. let mut plane = vec![]; - if let Some(q) = lighting.receiver.filter(|_| lighting.shade && lighting.shadows) { + if let Some(q) = lighting.receiver.filter(|_| shadows) { let edge = |a: [f64; 3], b: [f64; 3]| [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; let (e1, e2) = (edge(q[0], q[1]), edge(q[0], q[3])); let n = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]; @@ -503,6 +545,9 @@ fn scene( shadows_only: true, receives_shadows: true, casts_shadows: false, + // In a solid's own image the plane stays in the scene unseen, so the shadow maps + // cover what they cover in the other images. + visible: !matches!(layer, Layer::Solid(_) | Layer::Solids), ..Default::default() }); let base = vertices.len() as u32; @@ -604,38 +649,190 @@ fn image_object(image: &Rendered) -> Option { } /// The image a 3D effect with `settings` draws for object `id` from `meshes`, lit by `lighting`, with -/// the raster effects resolution of `doc` (72 ppi without one). An error when it can't be made: the -/// effect then draws its shaded faces. With `check_only`, validate the colors and scene limits -/// without producing pixels, returning `Ok(None)` when it fits. +/// the raster effects resolution of `doc` (72 ppi without one): one image when every drawn solid is +/// opaque and in Normal blending and `apart` does not separate an item effect's plane. Otherwise a +/// group holds the images [`layers`] lists, each in its solid's opacity and blending mode, sharing +/// the pixel and work limits. An error when it can't be made, or when it would take more than [`MAX_LAYERS`] images: the effect then draws its +/// shaded faces. With `check_only`, validate the colors and scene limits without producing pixels, +/// returning `Ok(None)` when it fits. pub(crate) fn art( doc: Option<&vectorcraft_doc::Document>, id: NodeId, lighting: &Lighting, meshes: &[SolidMesh], settings: RenderSettings, + apart: bool, check_only: bool, ) -> Result>, String> { - // Mapped graphics and see-through solids keep their shaded faces, which draw the graphics and - // apply a solid's opacity once to the whole surface. - if meshes.iter().any(|m| m.graphics.is_some() || m.color[3].is_nan() || m.color[3] < 1.0) { + let Some(Parts { behind, front }) = parts(doc, id, lighting, meshes, settings, apart, check_only)? else { return Ok(None) }; + if behind.is_empty() && front.len() == 1 && front.iter().all(|n| matches!(n.kind, NodeKind::Image(_)) && n.opacity == 1.0) { + return Ok(front.into_iter().next()); + } + Ok(Some(Arc::new(Node::group(id, behind.into_iter().chain(front).collect())))) +} + +/// [`art`] in two parts: the shadow plane's images behind every other fill and stroke when `apart` +/// is true, and the solids' images at the affected paint's position. A white background starts the +/// front part, followed by the plane images and solids. With `apart` false, the plane stays in front +/// with the solids, combined in one image for opaque Normal solids. +pub(crate) fn art_apart( + doc: Option<&vectorcraft_doc::Document>, + id: NodeId, + lighting: &Lighting, + meshes: &[SolidMesh], + settings: RenderSettings, + apart: bool, +) -> Result<(Vec>, Arc), String> { + let Parts { behind, mut front } = parts(doc, id, lighting, meshes, settings, apart, false)?.unwrap_or_default(); + let front = if front.len() == 1 { front.remove(0) } else { Arc::new(Node::group(id, front)) }; + Ok((behind, front)) +} + +/// The art behind the object's other paints and the art at the affected paint's position. +/// A white background and all images over it stay in the front part. +#[derive(Default)] +struct Parts { + behind: Vec>, + front: Vec>, +} + +/// The images [`art`] draws, in two parts ([`art_apart`]); `None` with `check_only` once the colors +/// and scene limits are checked with the same `apart` layer plan as drawing. A white rectangle +/// starts the front part, followed by plane images and solids; otherwise `apart` puts plane images +/// behind the object's other paints. +fn parts( + doc: Option<&vectorcraft_doc::Document>, + id: NodeId, + lighting: &Lighting, + meshes: &[SolidMesh], + settings: RenderSettings, + apart: bool, + check_only: bool, +) -> Result, String> { + // Mapped graphics keep their shaded faces, which draw the graphics. + if meshes.iter().any(|m| m.graphics.is_some() || m.color[3].is_nan()) { return Err(OPAQUE_ONLY.into()); } let ppi = doc.map_or(72.0, |d| d.raster_ppi()); + let layers = layers(meshes, lighting, apart); + // Without drawn solids there is no image or white background to size. + if layers.is_empty() { + return Ok((!check_only).then(Parts::default)); + } + if layers.len() > MAX_LAYERS { + return Err(TOO_LARGE.into()); + } + let limits = shared_limits(&Limits::default(), layers.len()); + let one = layers.first().is_some_and(|(layer, _)| *layer == Layer::All); + // The white background behind several images is measured as the images are. + let white = if settings.white && !one { Some(measure(meshes, lighting, settings, ppi, false, &Limits::default())?) } else { None }; if check_only { - check(meshes, lighting, settings, ppi, &Limits::default())?; + for (layer, _) in &layers { + check(meshes, lighting, *layer, settings, ppi, &limits)?; + } return Ok(None); } - let key = image_key(meshes, lighting, settings, ppi); - let made = match cached(key) { - Some(made) => made, - None => { - let made = render(meshes, lighting, settings, ppi, false, &Limits::default()) - .and_then(|image| image_object(&image).ok_or_else(|| TOO_LARGE.to_string())); - keep(key, &made); - made + // Images drawn one over another keep their background clear; a white one goes once, behind + // them all, at the object's or the item's own place. + let each = RenderSettings { white: settings.white && one, ..settings }; + let mut out = Parts::default(); + if let Some(m) = white { + let white = Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0); + out.front.push(Arc::new(Node::path(id, vectorcraft_geom::shapes::rectangle(m.rect), white))); + } + for (layer, ink) in &layers { + let key = image_key(meshes, lighting, each, ppi, (*layer, layers.len())); + let made = match cached(key) { + Some(made) => made, + None => { + let made = render_layer(meshes, lighting, *layer, each, ppi, false, &limits) + .and_then(|image| image_object(&image).ok_or_else(|| TOO_LARGE.to_string())); + keep(key, &made); + made + } + }; + let mut node = Node::new(id, NodeKind::Image(Box::new(made?))); + node.opacity = ink.0; + node.blend = ink.1; + let into = if apart && !settings.white && matches!(layer, Layer::Plane(..)) { &mut out.behind } else { &mut out.front }; + into.push(Arc::new(node)); + } + Ok(Some(out)) +} + +/// What one image of a 3D object draws. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum Layer { + /// Every solid and the shadow plane: the one image of solids that are all opaque and in Normal + /// blending, including the shadow plane unless an item effect needs it apart. + All, + /// Every solid, without the shadow plane: the image of solids that are all opaque and in + /// Normal blending, with a shadow plane drawn behind them. + Solids, + /// Only solid `k`, lit and shadowed as in [`Layer::All`]; the other solids cast their shadows + /// on it without being drawn. + Solid(usize), + /// Only the shadow plane, with the shadows the solids in `start..end` cast on it. + Plane(usize, usize), +} + +/// Most images one 3D object draws. VectorCraft's own value. +const MAX_LAYERS: usize = 16; + +/// A solid's opacity and blending mode ([`SolidMesh::color`], [`SolidMesh::blend`]). +type Ink = (f32, vectorcraft_doc::color::BlendMode); + +/// The ink of mesh `m`. +fn ink(m: &SolidMesh) -> Ink { + (m.color[3], m.blend) +} + +/// The images that draw `meshes` lit by `lighting`, back to front, each in its own ink. When all +/// drawn solids are opaque Normal, one image includes the plane unless `apart` separates it for an +/// item effect. Otherwise the plane comes first, one image per run of solids in the same ink, then +/// each solid in mesh order. With `apart` and a plane, opaque Normal solids use [`Layer::Solids`]. +/// A solid at 0% opacity draws nothing, casts no shadow and does not split the image. +fn layers(meshes: &[SolidMesh], lighting: &Lighting, apart: bool) -> Vec<(Layer, Ink)> { + use vectorcraft_doc::color::BlendMode; + let plane = lighting.receiver.is_some() && lighting.shade && lighting.shadows; + let drawn: Vec<&SolidMesh> = meshes.iter().filter(|m| super::shadow::casts(m.color[3])).collect(); + if drawn.is_empty() { + return vec![]; + } + let opaque = drawn.iter().all(|m| m.color[3] >= 1.0 && m.blend == BlendMode::Normal); + if opaque && !(apart && plane) { + return vec![(Layer::All, (1.0, BlendMode::Normal))]; + } + let mut out = vec![]; + if plane { + let casting: Vec = (0..meshes.len()).filter(|&k| super::shadow::casts(meshes[k].color[3])).collect(); + let mut run: Option<(usize, usize, Ink)> = None; + for k in casting { + match run { + Some((start, _, run_ink)) if run_ink == ink(&meshes[k]) => run = Some((start, k + 1, run_ink)), + _ => { + out.extend(run.map(|(start, end, run_ink)| (Layer::Plane(start, end), run_ink))); + run = Some((k, k + 1, ink(&meshes[k]))); + } + } } - }; - made.map(|object| Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object)))))) + out.extend(run.map(|(start, end, run_ink)| (Layer::Plane(start, end), run_ink))); + } + if opaque { + out.push((Layer::Solids, (1.0, BlendMode::Normal))); + return out; + } + out.extend((0..meshes.len()).filter(|&k| super::shadow::casts(meshes[k].color[3])).map(|k| (Layer::Solid(k), ink(&meshes[k])))); + out +} + +/// `limits` shared by `count` images: each takes its part of the pixels and the work. +fn shared_limits(limits: &Limits, count: usize) -> Limits { + let count = count.max(1) as u64; + let mut shared = *limits; + shared.max_pixels /= count; + shared.max_work /= count; + shared } /// Most rendered images [`art`] keeps for reuse, and most PNG bytes they hold together. VectorCraft's @@ -697,13 +894,15 @@ fn keep(key: u128, made: &Result) { /// A 128-bit hash of everything a rendered image is made from: every mesh's points, normals, /// texture coordinates, triangles, color, material and projection, the lights, ambient light, -/// shading, shadows and shadow plane, the render settings and the resolution. Moving, turning or -/// reshaping the object, or changing any setting, changes it; panning and redrawing do not. -fn image_key(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, ppi: f64) -> u128 { +/// shading, shadows and shadow plane, the render settings and the resolution, and the layer the image +/// draws with the number of images the object draws (`layer`). Moving, turning or reshaping the +/// object, or changing any setting, changes it; panning and redrawing do not. +fn image_key(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, ppi: f64, layer: (Layer, usize)) -> u128 { use std::hash::{Hash, Hasher}; let half = |seed: u8| { let mut h = std::collections::hash_map::DefaultHasher::new(); seed.hash(&mut h); + layer.hash(&mut h); let mut f = |v: f64| v.to_bits().hash(&mut h); for m in meshes { let mesh = &m.mesh; @@ -736,17 +935,16 @@ fn image_key(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings (u128::from(half(1)) << 64) | u128::from(half(2)) } -/// Can the solids of `items` be drawn as a rendered image: is each painted with a solid color (or -/// nothing) in Normal blending, with no member's opacity mask or blending mode applying to them -/// (`masked`)? Otherwise the effect draws its shaded faces, which keep gradients, patterns, mapped -/// graphics, masks and blending. +/// Can the solids of `items` be drawn as rendered images: is each painted with a solid color (or +/// nothing), at any opacity and in any blending mode, with no member's opacity mask or blending +/// mode applying to them (`masked`)? Otherwise the effect draws its shaded faces, which keep +/// gradients, patterns, mapped graphics and masks. pub(crate) fn takes<'a>(items: impl IntoIterator, masked: bool) -> bool { use vectorcraft_doc::AppearanceItem; - use vectorcraft_doc::color::Paint; !masked && items.into_iter().all(|i| match i { - AppearanceItem::Fill(f) => matches!(f.paint, Paint::Solid { .. } | Paint::None) && f.blend == Default::default(), - AppearanceItem::Stroke(s) => matches!(s.paint, Paint::Solid { .. } | Paint::None) && s.blend == Default::default(), + AppearanceItem::Fill(f) => matches!(f.paint, Paint::Solid { .. } | Paint::None), + AppearanceItem::Stroke(s) => matches!(s.paint, Paint::Solid { .. } | Paint::None), }) } diff --git a/crates/effects/src/solids/rendered/tests.rs b/crates/effects/src/solids/rendered/tests.rs index 59633f835f..0eb6446646 100644 --- a/crates/effects/src/solids/rendered/tests.rs +++ b/crates/effects/src/solids/rendered/tests.rs @@ -333,7 +333,8 @@ fn self_shadow_darkening(n: &Node) -> f32 { assert_eq!(meshes.len(), 1, "the caster and receiver belong to the same solid"); let projection = meshes[0].projection.unwrap(); let (rect, z) = extent(&meshes, &[], projection).unwrap(); - let mut shadowed = scene(&meshes, &lighting, projection, z, clip(projection, rect, z).unwrap(), (160, 160), 160.0 / rect.width()).unwrap(); + let measured = Measured { projection, rect, z, clip: clip(projection, rect, z).unwrap(), cols: 160, rows: 160, samples: 1, low: false }; + let mut shadowed = scene(&meshes, &lighting, Layer::All, &measured).unwrap(); let mut unshadowed = shadowed.clone(); for material in &mut unshadowed.materials { material.casts_shadows = false; @@ -478,10 +479,10 @@ fn depths_close_to_a_near_eye_keep_a_clip_matrix() { assert!(clip(projection, rect, [0.0, 100.0]).is_none()); } -/// A solid painted with a gradient, in a blending mode other than Normal or with an opacity below -/// 100% draws its shaded faces, which keep that paint: the image shows opaque solid colors only. +/// A solid painted with a gradient draws its shaded faces, which keep that paint: the image shows +/// solid colors only. #[test] -fn gradients_and_blending_draw_the_shaded_faces() { +fn gradients_draw_the_shaded_faces() { use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; for id in FOUR { let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered"}})); @@ -491,21 +492,280 @@ fn gradients_and_blending_draw_the_shaded_faces() { )))); let art = drawn(&n); assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: gradient"); - let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered"}})); - if let vectorcraft_doc::AppearanceItem::Fill(f) = &mut n.appearance.items[0] { - f.blend = vectorcraft_doc::color::BlendMode::Multiply; - } - let art = drawn(&n); - assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: blending"); - let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered"}})); - if let vectorcraft_doc::AppearanceItem::Fill(f) = &mut n.appearance.items[0] { - f.opacity = 0.5; - } - let art = drawn(&n); - assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: opacity"); } } +/// `n` with its fill at `opacity` in blending mode `blend`. +fn inked(mut n: Node, opacity: f32, blend: vectorcraft_doc::color::BlendMode) -> Node { + if let vectorcraft_doc::AppearanceItem::Fill(f) = &mut n.appearance.items[0] { + f.opacity = opacity; + f.blend = blend; + } + n +} + +/// The image nodes in `art`, in drawing order, with their opacity and blending mode. +fn image_nodes(art: &Node) -> Vec<(vectorcraft_doc::ImageObject, f32, vectorcraft_doc::color::BlendMode)> { + let mut out = vec![]; + art.walk(&mut |c| { + if let NodeKind::Image(i) = &c.kind { + out.push(((**i).clone(), c.opacity, c.blend)); + } + }); + out +} + +/// The straight-alpha RGBA8 pixels of image object `i`. +fn decoded(i: &vectorcraft_doc::ImageObject) -> Vec { + let bytes = &i.pixels.as_ref().expect("the image holds its pixels").bytes; + image::load_from_memory(bytes).expect("a PNG").to_rgba8().into_raw() +} + +/// A solid painted below 100% opacity or in a blending mode other than Normal draws its rendered +/// image in that opacity and blending mode, as the shaded faces draw the solid's surface, with the +/// pixels the opaque solid's image has; nothing reports a fallback. +#[test] +fn see_through_and_blended_solids_draw_their_image_in_that_ink() { + use vectorcraft_doc::color::BlendMode; + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in FOUR { + let opaque = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered", "quality": "low"}})); + let plain = image_nodes(&drawn(&opaque)); + assert_eq!(plain.len(), 1, "{id}: opaque"); + for (opacity, blend) in [(0.5, BlendMode::Normal), (1.0, BlendMode::Multiply), (0.25, BlendMode::Screen)] { + let n = inked(opaque.clone(), opacity, blend); + assert_eq!(crate::rendered_warning(&doc, &n), None, "{id}: {opacity} {blend:?}"); + let art = drawn(&n); + assert!(faces_bounds(&art).is_none(), "{id}: {opacity} {blend:?} draws no shaded faces"); + let drawn = image_nodes(&art); + assert_eq!(drawn.len(), 1, "{id}: {opacity} {blend:?}"); + assert_eq!((drawn[0].1, drawn[0].2), (opacity, blend), "{id}: the image takes the fill's ink"); + assert_eq!(image_rect(&drawn[0].0), image_rect(&plain[0].0), "{id}: {opacity} {blend:?}"); + assert_eq!(decoded(&drawn[0].0), decoded(&plain[0].0), "{id}: {opacity} {blend:?} keeps the opaque solid's pixels"); + } + } +} + +/// With Shadows on, an opaque Normal object shares one image with its shadow plane. A see-through +/// solid draws a separate plane image behind its own, both in its ink. Their pixels match the +/// combined opaque image where each shows. At one sample a pixel the solid's image is opaque or +/// clear, and the plane's image holds only black. +#[test] +fn a_see_through_solid_draws_its_shadow_plane_behind_it() { + use vectorcraft_doc::color::BlendMode; + let opaque = two_lights(100.0, 0.0, true); + let plain = image_nodes(&drawn(&opaque)); + assert_eq!(plain.len(), 1, "the opaque solid and plane share one image"); + assert!(plain.iter().all(|(_, o, b)| *o == 1.0 && *b == BlendMode::Normal)); + let layered = image_nodes(&drawn(&inked(opaque.clone(), 0.5, BlendMode::Normal))); + assert_eq!(layered.len(), 2, "the plane, then the solid"); + assert!(layered.iter().all(|(_, o, b)| *o == 0.5 && *b == BlendMode::Normal)); + assert!(layered.iter().chain(&plain).all(|(i, ..)| image_rect(i) == image_rect(&plain[0].0)), "every image covers the same rectangle"); + let (plane, solid) = (decoded(&layered[0].0), decoded(&layered[1].0)); + let whole = decoded(&plain[0].0); + let alpha = |p: &[u8], i: usize| p[4 * i + 3]; + let (mut shadow, mut covered) = (0, 0); + for i in 0..solid.len() / 4 { + match alpha(&solid, i) { + 255 => { + assert_eq!(solid[4 * i..4 * i + 4], whole[4 * i..4 * i + 4], "pixel {i}: the solid covers the plane"); + covered += 1; + } + 0 => { + assert_eq!(plane[4 * i..4 * i + 4], whole[4 * i..4 * i + 4], "pixel {i}: the plane shows outside the solid"); + shadow += usize::from(alpha(&plane, i) > 0); + } + a => panic!("pixel {i}: alpha {a} at one sample a pixel"), + } + assert!(alpha(&plane, i) == 0 || plane[4 * i..4 * i + 3] == [0, 0, 0], "pixel {i}: the plane's image holds only black"); + } + assert!(shadow > 0 && covered > 0, "{shadow} shadow pixels, {covered} solid pixels"); +} + +/// With a fill and a stroke, each drawn on its own once either is see-through, in the order of the +/// appearance, each in its own ink; a fill at 0% opacity draws nothing and its stroke still draws. +#[test] +fn each_solid_draws_on_its_own_in_its_ink() { + use vectorcraft_doc::color::BlendMode; + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in [super::super::EXTRUDE, super::super::ROTATE] { + let params = json!({"render": {"mode": "rendered", "quality": "low"}}); + let mut n = Node::path( + NodeId(1), + square(100.0, 100.0, 100.0), + Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::solid(Color::BLACK), 8.0), + ); + n.appearance.effects.push(crate::new_effect(id, ¶ms).unwrap()); + assert_eq!(image_nodes(&drawn(&n)).len(), 1, "{id}: opaque fill and stroke share one image"); + // Appearance::basic holds the fill, then the stroke. + let mut faint = n.clone(); + if let vectorcraft_doc::AppearanceItem::Stroke(s) = &mut faint.appearance.items[1] { + s.opacity = 0.5; + } + assert_eq!(crate::rendered_warning(&doc, &faint), None, "{id}"); + let inks: Vec<(f32, BlendMode)> = image_nodes(&drawn(&faint)).into_iter().map(|(_, o, b)| (o, b)).collect(); + assert_eq!(inks, [(1.0, BlendMode::Normal), (0.5, BlendMode::Normal)], "{id}: one image for each solid, in the appearance's order"); + let mut gone = n.clone(); + if let vectorcraft_doc::AppearanceItem::Fill(f) = &mut gone.appearance.items[0] { + f.opacity = 0.0; + } + let inks: Vec<(f32, BlendMode)> = image_nodes(&drawn(&gone)).into_iter().map(|(_, o, b)| (o, b)).collect(); + assert_eq!(inks, [(1.0, BlendMode::Normal)], "{id}: a fill at 0% draws nothing"); + } +} + +/// An overlapping fill at 0% opacity does not split or change the image of an opaque fill and stroke. +#[test] +fn a_zero_opacity_solid_does_not_split_opaque_solids() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + let mut n = Node::path( + NodeId(1), + square(100.0, 100.0, 100.0), + Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::solid(Color::BLACK), 8.0), + ); + n.appearance + .effects + .push(crate::new_effect(super::super::ROTATE, &json!({"shadow": true, "render": {"mode": "rendered", "quality": "low"}})).unwrap()); + let plain = images(&drawn(&n)); + assert_eq!(plain.len(), 1); + let mut clear = n.appearance.items[0].clone(); + if let vectorcraft_doc::AppearanceItem::Fill(f) = &mut clear { + f.opacity = 0.0; + f.paint = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + } + n.appearance.items.push(clear); + assert_eq!(crate::rendered_warning(&doc, &n), None); + let with_clear = images(&drawn(&n)); + assert_eq!(with_clear.len(), 1, "the zero-opacity fill does not split the image"); + assert_eq!(image_rect(&with_clear[0]), image_rect(&plain[0])); + assert_eq!(decoded(&with_clear[0]), decoded(&plain[0]), "the zero-opacity fill neither draws nor casts a shadow"); +} + +/// With `background: white`, a see-through object draws one white rectangle behind all its images, +/// which keep their background clear, so a later solid's image does not hide an earlier one. +#[test] +fn a_white_background_goes_once_behind_every_image() { + let params = json!({"render": {"mode": "rendered", "quality": "low", "background": "white"}}); + let mut n = Node::path( + NodeId(1), + square(100.0, 100.0, 100.0), + Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::solid(Color::BLACK), 8.0), + ); + n.appearance.effects.push(crate::new_effect(super::super::EXTRUDE, ¶ms).unwrap()); + if let vectorcraft_doc::AppearanceItem::Fill(f) = &mut n.appearance.items[0] { + f.opacity = 0.5; + } + let art = drawn(&n); + let layers = image_nodes(&art); + assert_eq!(layers.len(), 2, "the fill's image, then the stroke's"); + let mut paths = vec![]; + art.walk(&mut |c| { + if let Some(b) = c.path_data().and_then(PathData::bounds) { + paths.push((b, c.appearance.fill().map(|f| f.paint.clone()))); + } + }); + assert_eq!(paths, [(image_rect(&layers[0].0), Some(Paint::solid(Color::WHITE)))], "one white rectangle under the images"); + for (i, (image, ..)) in layers.iter().enumerate() { + assert!(decoded(image).chunks(4).any(|p| p[3] == 0), "image {i} keeps a clear background"); + } +} + +/// A rendered 3D effect on a stroke with Shadows on draws its shadow plane behind the fill under it, +/// as the shaded faces draw that shadow behind every fill and stroke, whether the stroke is opaque +/// or see-through. +#[test] +fn a_rendered_effect_on_a_stroke_draws_its_shadow_plane_behind_the_fill() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in [crate::REVOLVE, super::super::EXTRUDE] { + for opacity in [1.0, 0.5] { + let mut n = Node::path( + NodeId(11), + square(100.0, 100.0, 100.0), + Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::solid(Color::BLACK), 4.0), + ); + let fx = crate::new_effect(id, &json!({"shadow": true, "render": {"mode": "rendered", "quality": "low"}})).unwrap(); + if let vectorcraft_doc::AppearanceItem::Stroke(s) = &mut n.appearance.items[1] { + s.opacity = opacity; + } + n.appearance.items[1].effects_mut().push(fx); + assert_eq!(crate::rendered_warning(&doc, &n), None, "{id}: {opacity}"); + let art = drawn(&n); + let kinds: Vec = art.children().unwrap().iter().map(|c| matches!(c.kind, NodeKind::Image(_))).collect(); + assert_eq!(kinds, [true, false, true], "{id}: {opacity}: the plane's image, the fill, then the stroke's image"); + } + } +} + +/// A member at 0% opacity, which draws nothing, does not widen the image of the members that draw. +#[test] +fn a_solid_at_zero_opacity_does_not_widen_the_image() { + let member = |id: u64, x: f64, opacity: f32| { + let mut m = Node::path(NodeId(id), square(x, 100.0, 100.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); + if let vectorcraft_doc::AppearanceItem::Fill(f) = &mut m.appearance.items[0] { + f.opacity = opacity; + } + Arc::new(m) + }; + let params = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "render": {"mode": "rendered", "quality": "low"}}); + let width = |far: f32| { + let mut g = Node::group(NodeId(10), vec![member(1, 100.0, 1.0), member(2, 1000.0, far)]); + g.appearance.effects.push(crate::new_effect(super::super::ROTATE, ¶ms).unwrap()); + let found = images(&drawn(&g)); + assert!(!found.is_empty(), "{far}"); + image_rect(&found[0]).width() + }; + assert!(width(1.0) > 900.0, "both members draw: {}", width(1.0)); + assert!(width(0.0) < 200.0, "the member at 0% is left out: {}", width(0.0)); +} + +/// With `background: white`, a large drawn solid still exceeds the image's pixel limit. +#[test] +fn a_white_background_is_checked_when_a_large_solid_draws() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + let params = json!({"render": {"mode": "rendered", "quality": "low", "background": "white", "resolution": 2400}}); + let mut n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), params); + n.kind = Node::path(NodeId(1), square(0.0, 0.0, 2000.0), Appearance::default()).kind; + assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(TOO_LARGE)); + assert!(images(&drawn(&n)).is_empty()); +} + +/// Solids that all draw nothing measure nothing: painted bounds take no image rectangle. +#[test] +fn solids_at_zero_opacity_measure_nothing() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in [super::super::EXTRUDE, crate::REVOLVE] { + for background in ["transparent", "white"] { + let n = inked( + solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered", "background": background}})), + 0.0, + Default::default(), + ); + assert_eq!(crate::rendered_warning(&doc, &n), None, "{id}: {background}"); + let measured = crate::three_d_bounds_art_in(Some(&doc), &n).unwrap(); + assert!(images(&measured).is_empty() && faces_bounds(&measured).is_none(), "{id}: {background}: {measured:?}"); + let art = drawn(&n); + assert!(image_nodes(&art).is_empty() && faces_bounds(&art).is_none(), "{id}: {background}: {art:?}"); + } + } +} + +/// The images of a see-through object share the pixel limit: a quality that fits one image takes +/// fewer samples once the solid and its shadow plane each draw one, and past the limit at one sample +/// a pixel the shaded faces are drawn. +#[test] +fn layered_images_share_the_pixel_limit() { + let lighting = Lighting { lights: vec![], diffusion: vec![], ambient: 1.0, shade: true, shadows: false, receiver: None }; + let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({})); + let (meshes, _) = scene_of(&n); + let m = measure(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let pixels = u64::from(m.cols * m.rows); + let mut limits = Limits::default(); + limits.max_pixels = pixels * 4; + assert_eq!(measure(&meshes, &lighting, MEDIUM, 72.0, false, &limits).unwrap().samples, 2); + assert_eq!(measure(&meshes, &lighting, MEDIUM, 72.0, false, &shared_limits(&limits, 2)).unwrap().samples, 1); + assert!(measure(&meshes, &lighting, MEDIUM, 72.0, false, &shared_limits(&limits, 5)).is_err()); +} + /// A loaded file whose `render` breaks the rules draws the shaded faces. #[test] fn an_invalid_loaded_render_draws_shaded() { @@ -564,7 +824,7 @@ fn check_only_reports_rasterizer_limits_after_measure_succeeds() { } assert!(measure(&meshes, &lighting, settings, 72.0, false, &limits).is_ok(), "{limit}: image fits"); let before = RASTERIZATIONS.with(|count| count.get()); - let checked = check(&meshes, &lighting, settings, 72.0, &limits); + let checked = check(&meshes, &lighting, Layer::All, settings, 72.0, &limits); assert_eq!(checked.as_ref().map_err(String::as_str), Err(TOO_LARGE), "{limit}"); assert_eq!(RASTERIZATIONS.with(|count| count.get()), before, "{limit}: check rasterizes"); assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &limits).map(|_| ()), checked, "{limit}"); @@ -588,16 +848,16 @@ fn check_only_counts_shadow_work_and_lights() { limits.max_work = 30_000; let mut unlit = lighting.clone(); unlit.shade = false; - assert!(check(&meshes, &unlit, settings, 72.0, &limits).is_ok()); + assert!(check(&meshes, &unlit, Layer::All, settings, 72.0, &limits).is_ok()); assert!(render(&meshes, &unlit, settings, 72.0, false, &limits).is_ok()); // With Shadows off, no shadow map is made, so the same limit fits. let mut unshadowed = lighting.clone(); unshadowed.shadows = false; - assert!(check(&meshes, &unshadowed, settings, 72.0, &limits).is_ok()); + assert!(check(&meshes, &unshadowed, Layer::All, settings, 72.0, &limits).is_ok()); assert!(render(&meshes, &unshadowed, settings, 72.0, false, &limits).is_ok()); } assert!(measure(&meshes, &lighting, settings, 72.0, false, &limits).is_ok()); - assert_eq!(check(&meshes, &lighting, settings, 72.0, &limits), Err(TOO_LARGE.into()), "{limit}"); + assert_eq!(check(&meshes, &lighting, Layer::All, settings, 72.0, &limits), Err(TOO_LARGE.into()), "{limit}"); assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &limits), Err(TOO_LARGE.into()), "{limit}"); } } @@ -614,20 +874,21 @@ fn check_only_art_reports_overlapping_faces_past_the_work_limit() { let settings = RenderSettings { quality: 0, ..MEDIUM }; assert!(measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).is_ok()); let before = RASTERIZATIONS.with(|count| count.get()); - assert_eq!(art(None, NodeId(1), &lighting, &meshes, settings, true).map(|_| ()), Err(TOO_LARGE.into())); + assert_eq!(art(None, NodeId(1), &lighting, &meshes, settings, false, true).map(|_| ()), Err(TOO_LARGE.into())); assert_eq!(RASTERIZATIONS.with(|count| count.get()), before); assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &Limits::default()), Err(TOO_LARGE.into())); } /// The page cells (1 pt squares, by their top-left corner) where the rendered image of `n` shows /// a shadow: covered past alpha 16 outside the bounds of `n`'s shaded faces without a shadow. +/// The opaque object keeps its solid and shadows in one image. fn shadow_cells(n: &Node) -> Vec<(i64, i64)> { let mut bare = n.clone(); bare.appearance.effects[0].params["shadow"] = json!(false); bare.appearance.effects[0].params["render"] = json!({"mode": "shaded"}); let solid = faces_bounds(&drawn(&bare)).unwrap(); let list = images(&drawn(n)); - assert_eq!(list.len(), 1, "one image"); + assert_eq!(list.len(), 1, "the opaque solid and its shadows share one image"); let i = &list[0]; let decoded = image::load_from_memory(&i.pixels.as_ref().unwrap().bytes).unwrap().to_rgba8(); let [sx, _, _, sy, x0, y0] = i.xf.as_coeffs(); @@ -676,7 +937,7 @@ fn every_light_casts_a_shadow_on_the_plane() { } /// Full Softness widens the shadow's transition on the plane by several image pixels at both -/// resolutions, including when the image uses multiple samples per pixel. +/// resolutions in the opaque object's combined image, including with multiple samples per pixel. #[test] fn softness_widens_the_shadow_edge_on_the_plane() { for (resolution, quality) in [(72.0, "low"), (144.0, "medium")] { @@ -692,7 +953,7 @@ fn softness_widens_the_shadow_edge_on_the_plane() { }), ); let list = images(&drawn(&n)); - assert_eq!(list.len(), 1); + assert_eq!(list.len(), 1, "the opaque solid and its shadows share one image"); let image = &list[0]; let decoded = image::load_from_memory(&image.pixels.as_ref().unwrap().bytes).unwrap().to_rgba8(); let [sx, _, _, sy, x0, y0] = image.xf.as_coeffs(); @@ -731,7 +992,7 @@ fn preview_bounds_do_not_rasterize() { } /// Painted measurements include the image rectangle under opposite lights without rasterizing, -/// while preview measurements keep the vector art. +/// while drawing uses one image for the opaque Normal object and preview measurements keep the vector art. #[test] fn painted_bounds_include_every_lights_shadow_without_rasterizing() { let doc = vectorcraft_doc::Document::new(400.0, 400.0); @@ -746,7 +1007,7 @@ fn painted_bounds_include_every_lights_shadow_without_rasterizing() { assert!(measured_images[0].pixels.is_none(), "{id}: no pixels for measurement"); assert_eq!(RASTERIZATIONS.with(|count| count.get()), before, "{id}: measuring rasterizes"); let drawn_images = images(&drawn(&n)); - assert_eq!(drawn_images.len(), 1, "{id}: draws the rendered image"); + assert_eq!(drawn_images.len(), 1, "{id}: draws the solid and its shadows in one image"); let image = Node::new(n.id, NodeKind::Image(Box::new(drawn_images[0].clone()))).visual_bounds().unwrap(); assert!(bounds.x0 <= image.x0 && bounds.y0 <= image.y0 && bounds.x1 >= image.x1 && bounds.y1 >= image.y1, "{id}: {bounds:?} holds {image:?}"); let mut bare = n.clone(); @@ -858,9 +1119,17 @@ fn revolve_on_a_group_with_a_see_through_member_draws_the_shaded_faces() { member.opacity = 0.5; let mut group = Node::group(NodeId(10), vec![std::sync::Arc::new(member)]); group.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap()); - assert_eq!(crate::rendered_warning(&doc, &group).as_deref(), Some(OPAQUE_ONLY), "member at 50%"); + assert_eq!(crate::rendered_warning(&doc, &group).as_deref(), Some(GROUP_OPAQUE_ONLY), "member at 50%"); let art = drawn(&group); assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "member at 50%"); + let mut fill = Node::path(NodeId(11), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0)); + if let vectorcraft_doc::AppearanceItem::Fill(f) = &mut fill.appearance.items[0] { + f.blend = vectorcraft_doc::color::BlendMode::Multiply; + } + let mut group = Node::group(NodeId(10), vec![std::sync::Arc::new(fill)]); + group.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap()); + assert_eq!(crate::rendered_warning(&doc, &group).as_deref(), Some(GROUP_OPAQUE_ONLY), "a member's fill in Multiply"); + assert!(images(&drawn(&group)).is_empty(), "a member's fill in Multiply"); } /// A member with no surface paint does not prevent the group's Revolve from rendering. @@ -967,8 +1236,10 @@ fn revolve_on_a_fill_or_a_stroke_draws_its_image() { if let AppearanceItem::Fill(f) = &mut faint.appearance.items[i] { f.opacity = 0.5; } - assert_eq!(crate::rendered_warning(&doc, &faint).as_deref(), Some(OPAQUE_ONLY), "fill at 50%"); - assert!(images(&drawn(&faint)).is_empty(), "fill at 50%"); + assert_eq!(crate::rendered_warning(&doc, &faint), None, "fill at 50%"); + let faint_art = crate::revolve_art_drawn_in(Some(&doc), &faint).unwrap(); + let inks: Vec = image_nodes(&faint_art).into_iter().map(|(_, o, _)| o).collect(); + assert_eq!(inks, [0.5], "fill at 50% draws its image at 50%"); assert_eq!(crate::rendered_warning(&doc, &solid_square(crate::REVOLVE, Color::BLACK, json!({"render": {"mode": "rendered"}}))), None); } @@ -1104,7 +1375,7 @@ fn a_lit_face_matches_the_shading_formula() { let (meshes, lighting) = scene_of(&n); let settings = RenderSettings { quality: 0, ..MEDIUM }; let m = measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap(); - let scene = scene(&meshes, &lighting, m.projection, m.z, m.clip, (m.cols, m.rows), f64::from(m.cols) / m.rect.width()).unwrap(); + let scene = scene(&meshes, &lighting, Layer::All, &m).unwrap(); assert_eq!(scene.lights.len(), 1); let light = &scene.lights[0]; let target = craft_raster3d::try_render(&scene, &Limits::default()).unwrap(); @@ -1259,3 +1530,103 @@ fn edge_values_render_or_are_refused() { meshes[0].mesh.positions[0][2] = eye * 2.0; assert_eq!(render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()), Err(TOO_LARGE.to_string())); } + +/// A rendered effect on a stroke with `background: white` keeps its white rectangle, and with +/// Shadows on its shadow plane, at the stroke's place above the fill, whether its image is one or +/// several. +#[test] +fn a_strokes_white_background_stays_above_the_fill() { + let doc = vectorcraft_doc::Document::new(400.0, 400.0); + for id in [super::super::EXTRUDE, crate::REVOLVE] { + for (opacity, shadow) in [(1.0, true), (0.5, false)] { + let mut n = Node::path( + NodeId(11), + square(100.0, 100.0, 100.0), + Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::solid(Color::BLACK), 4.0), + ); + if let vectorcraft_doc::AppearanceItem::Stroke(s) = &mut n.appearance.items[1] { + s.opacity = opacity; + } + let fx = + crate::new_effect(id, &json!({"shadow": shadow, "render": {"mode": "rendered", "quality": "low", "background": "white"}})).unwrap(); + n.appearance.items[1].effects_mut().push(fx); + assert_eq!(crate::rendered_warning(&doc, &n), None, "{id}: {opacity}"); + let art = drawn(&n); + let children = art.children().unwrap(); + assert_eq!(children.len(), 2, "{id}: {opacity}: fill then stroke art"); + assert!(children[0].path_data().is_some()); + assert!(images(&children[0]).is_empty()); + assert!(children[0].appearance.items.iter().any(|i| i.paint().color() == Some(Color::rgb(0.2, 0.5, 0.8)))); + let stroke = children[1].children().unwrap(); + assert!(stroke[0].path_data().is_some()); + assert!(stroke[0].appearance.items.iter().any(|i| i.paint().color() == Some(Color::WHITE))); + assert!(stroke[1..].iter().all(|c| matches!(c.kind, NodeKind::Image(_)))); + assert_eq!(stroke.len(), if shadow { 3 } else { 2 }); + } + } +} + +/// A solid's own image, and the shadow plane's, hold the other solids only while a light casts a +/// shadow: with Shadows off, Shading off or every light at Intensity 0 they add no vertices. +#[test] +fn invisible_meshes_need_a_casting_light() { + let mut n = Node::path(NodeId(1), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::WHITE), 4.0)); + if let vectorcraft_doc::AppearanceItem::Fill(f) = &mut n.appearance.items[0] { + f.opacity = 0.5; + } + n.appearance.effects.push(crate::new_effect(super::super::EXTRUDE, &json!({"shadow": true})).unwrap()); + let (meshes, lit) = scene_of(&n); + assert_eq!(meshes.len(), 2); + for mode in 0..4 { + let mut lighting = lit.clone(); + match mode { + 0 => lighting.shadows = false, + 1 => lighting.shade = false, + 2 => lighting.lights.iter_mut().for_each(|l| l.intensity = 0.0), + _ => {} + } + let measured = measure(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap(); + let solid = scene(&meshes, &lighting, Layer::Solid(0), &measured).unwrap(); + let plane = scene(&meshes, &lighting, Layer::Plane(0, meshes.len()), &measured).unwrap(); + let count = if mode == 3 { meshes.iter().map(|m| m.mesh.positions.len()).sum() } else { meshes[0].mesh.positions.len() }; + assert_eq!(solid.vertices.len(), count); + if mode < 3 { + assert!(plane.vertices.is_empty()); + assert!(plane.indices.is_empty()); + } else { + assert!(lighting.lights.iter().any(|l| lighting.casts(l))); + assert_eq!(plane.vertices.len(), count); + } + } +} + +/// A member at 0% opacity counts against the mesh budget of a 3D export but not of the rendered +/// image, which keeps the drawn member's projection. +#[test] +fn zero_opacity_solids_do_not_spend_the_rendered_mesh_budget() { + use super::super::{Profile, members, meshes_for}; + for id in [super::super::EXTRUDE, super::super::INFLATE, super::super::ROTATE] { + let member = |key, x, opacity| { + let mut n = Node::path(NodeId(key), square(x, 100.0, 30.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + n.opacity = opacity; + Arc::new(n) + }; + let mut group = Node::group(NodeId(10), vec![member(1, 100.0, 1.0), member(2, 160.0, 0.0)]); + let fx = crate::new_effect(id, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap(); + let shapes: Vec = members(&group, "3D").unwrap(); + let exported = meshes_for(&fx, &shapes, &mut 0, usize::MAX, false).unwrap(); + assert_eq!(exported.len(), 2); + let limit = exported[0].mesh.triangles.len(); + assert!(meshes_for(&fx, &shapes, &mut 0, limit, false).is_err()); + let mut total = 0; + let rendered = meshes_for(&fx, &shapes, &mut total, limit, true).unwrap(); + assert_eq!(rendered.len(), 1); + assert_eq!(total, limit); + assert_eq!(rendered[0].projection, exported[0].projection); + let lighting = lighting(id, &crate::merged_params(id, &fx.params)); + assert!(!images(&art(None, group.id, &lighting, &rendered, MEDIUM, false, false).unwrap().unwrap()).is_empty()); + group.appearance.effects.push(fx); + assert_eq!(crate::rendered_warning(&vectorcraft_doc::Document::new(400.0, 400.0), &group), None); + assert!(!images(&drawn(&group)).is_empty()); + } +} diff --git a/crates/effects/src/solids/tests_mesh.rs b/crates/effects/src/solids/tests_mesh.rs index b7ecb75384..8bcebf8eee 100644 --- a/crates/effects/src/solids/tests_mesh.rs +++ b/crates/effects/src/solids/tests_mesh.rs @@ -54,9 +54,9 @@ fn the_meshes_of_one_object_share_one_triangle_budget() { let shapes = [Profile { path: profile(&n).unwrap().0, rule: FillRule::NonZero, items: solid_paints(&n), opacity: 1.0, scopes: vec![] }]; let Some(effect) = n.appearance.effects.first() else { panic!("no effect") }; let mut total = 0; - assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES).is_ok()); + assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES, false).is_ok()); let mut total = MAX_MESH_TRIANGLES - first + 1; - assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES).is_err_and(|e| e.contains("too complex"))); + assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES, false).is_err_and(|e| e.contains("too complex"))); } /// A mesh past the budget stops the export before the solids after it are built. @@ -69,7 +69,7 @@ fn the_solids_after_a_mesh_past_the_budget_are_not_built() { let Some(effect) = n.appearance.effects.first() else { panic!("no effect") }; let mut total = MAX_MESH_TRIANGLES - first + 1; SOLIDS_BUILT.with(|b| b.set(0)); - assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES).is_err_and(|e| e.contains("too complex"))); + assert!(meshes_for(effect, &shapes, &mut total, MAX_MESH_TRIANGLES, false).is_err_and(|e| e.contains("too complex"))); assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get), 1, "the stroke's solid is never built"); } @@ -312,7 +312,7 @@ fn one_build_exports_the_meshes_built_apart() { for nodes in &sets { let shapes = shapes_of(nodes); let (mut once, mut apart) = (0, 0); - let built = meshes_for(&effect, &shapes, &mut once, MAX_MESH_TRIANGLES).unwrap_or_else(|e| panic!("{id} {params}: {e}")); + let built = meshes_for(&effect, &shapes, &mut once, MAX_MESH_TRIANGLES, false).unwrap_or_else(|e| panic!("{id} {params}: {e}")); let reference = meshes_built_apart(&effect, &shapes, &mut apart, MAX_MESH_TRIANGLES).unwrap(); assert!(!reference.is_empty()); assert_eq!(mesh_bits(&built), mesh_bits(&reference), "{id} {params}"); @@ -320,7 +320,7 @@ fn one_build_exports_the_meshes_built_apart() { // Past the budget, at the same mesh, with the same count. let limit = once - 1; let (mut once, mut apart) = (0, 0); - let built = meshes_for(&effect, &shapes, &mut once, limit); + let built = meshes_for(&effect, &shapes, &mut once, limit, false); assert!(built.is_err(), "{id} {params}"); assert_eq!(built.err(), meshes_built_apart(&effect, &shapes, &mut apart, limit).err(), "{id} {params}"); assert_eq!(once, apart, "{id} {params}"); @@ -349,7 +349,7 @@ fn a_stroke_past_the_limits_is_left_out_of_the_export() { let shapes = shapes_of(&[&n]); // The fill's mesh alone has more triangles than an export takes. let (mut once, mut apart) = (0, 0); - let built = meshes_for(&effect, &shapes, &mut once, usize::MAX).unwrap_or_else(|e| panic!("{id}: {e}")); + let built = meshes_for(&effect, &shapes, &mut once, usize::MAX, false).unwrap_or_else(|e| panic!("{id}: {e}")); assert_eq!(built.len(), 1, "{id}: the fill's mesh alone"); assert!(close(built[0].color, [0.8, 0.2, 0.1, 1.0]), "{id}"); let reference = meshes_built_apart(&effect, &shapes, &mut apart, usize::MAX).unwrap(); diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs index 8170a3bfa7..9c58e12df7 100644 --- a/crates/effects/src/solids/tests_shadow.rs +++ b/crates/effects/src/solids/tests_shadow.rs @@ -344,6 +344,7 @@ fn a_shadowed_3d_object_builds_each_solid_once() { /// The shadow of the faces Extrude & Bevel, Inflate and Rotate kept when they drew their solids, /// to the bit: the shadow [`cast_shadow`] casts from solids built for the shadow alone. +/// Object-level art keeps the default combined render plan. #[test] fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it() { for id in [EXTRUDE, INFLATE, ROTATE] { @@ -356,7 +357,7 @@ fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it() let (path, rule) = profile(&n).unwrap(); vec![Profile { path, rule, items: solid_paint_sources(&n).1, opacity: 1.0, scopes: vec![] }] }; - let (drawn, _) = art_for(None, &n, std::slice::from_ref(fx), &shapes, Build::Vector, &mut None).unwrap(); + let (drawn, _) = art_for(None, &n, std::slice::from_ref(fx), &shapes, Build::Vector, false, &mut None).unwrap(); let p = crate::merged_params(&fx.id, &fx.params); let (caster, settings, cast) = cast_shadow(&fx.id, &p, &shapes).unwrap().unwrap(); let alone = shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes)); diff --git a/docs/mcp.md b/docs/mcp.md index 8ba81f20ad..7c2f2868e5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7641,12 +7641,23 @@ values), `resolution` (`null` for Document Raster Effects Settings › Resolutio `background` (`"transparent"`, the default, or `"white"`). A quality whose samples would pass 16,777,216 pixels takes fewer, and an image past that limit at one sample a pixel draws the shaded faces. The shaded faces are also drawn for a scene past the renderer's limits on triangles, vertices, lights or work, for a mesh point at or behind -the eye, for solids painted with a gradient, a pattern, graphics, an -opacity below 100% or a blending mode other than Normal, and for a later geometry effect that reshapes paths but -leaves images unchanged. Extrude & Bevel and Inflate check the top fill and the strokes they build solids from; Rotate +the eye, for solids painted with a gradient, a pattern or graphics, for a group member whose opacity mask or blending +mode applies to its solid, and for a later geometry effect that reshapes paths but leaves images unchanged. A solid +painted below 100% opacity or in a blending mode other than Normal draws its own image in that opacity and blending +mode. An object or group whose solids are all opaque in Normal blending draws one image with its shadows. When any +solid is see-through or blended, each solid draws an image of its own, in the order of the fills and strokes, lit and +shadowed as in the one image, and with `shadow` on the shadow plane draws first, in an image for each run of solids in +the same opacity and blending mode. An effect on one fill or stroke with `shadow` on always draws the shadow plane in +images of its own, behind every fill and stroke of the object unless the background is white. A solid at 0% opacity draws nothing, casts no shadow, +and is left out of the image's mesh budget, size and choice between one image and several. The images share the +16,777,216-pixel limit and the renderer's work limit, past 16 images (VectorCraft's own value) the shaded faces are +drawn, and with `background: "white"` one white rectangle goes behind them all. On one fill or stroke, the rectangle +stays at that paint's position, followed by the plane images and solids' images. Extrude & Bevel and Inflate check the +top fill and the strokes they build solids from; Rotate checks every fill and stroke, since it draws a plane for each. Revolve on a group draws every member's surface in one -image and checks each member's surface fill or stroke; Revolve on a fill or stroke draws that fill's or stroke's -surface as an image under the effects after it. The status bar and +image and checks each member's surface fill or stroke; a visible member's surface below 100% opacity, its own opacity +included, or in a blending mode other than Normal draws the shaded faces. Revolve on a fill or stroke draws that +fill's or stroke's surface as an image under the effects after it. The status bar and the command result's `warning` field report when the shaded faces are drawn instead. A `render` that is not an object, another key, another value, and `render` on Extrude & Bevel (Classic), Revolve (Classic) or Rotate (Classic) are refused before the document changes. In wireframe mode the graphics' art is not checked against the graphics diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4f0ae8fc24..a632196fbd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -742,7 +742,7 @@ since 2026-10-01. - 3D and Materials › Object › Bevel › Reset: the button next to Extrude & Bevel's Bevel heading, in the options dialog and the panel, sets Bevel Shape, Width, Height, Repeat, Space, Bevel Inside and Bevel both sides back to their defaults and leaves the other settings as they are, as one undo step in the panel; it is unavailable while every bevel setting is at its default ([three-d.md](three-d.md#extrude--bevel)); `crates/ui-egui/src/dialogs/revolve/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Quick Actions › Expand as Wireframes (#6354): `effect.expandAsWireframes` replaces each selected 3D object with a group of 0.5 pt black stroked paths, the edges of the faces its effect draws, each edge once and joined end to end, curves kept, in one undo step ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs`, `crates/engine/src/cmd/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Render Settings › Wireframe: `render: {mode: "wireframe"}` on Extrude & Bevel, Revolve, Inflate and Rotate draws the live effect as the edges of its faces, 0.5 pt black strokes with no shadow, in every output and in Expand Appearance ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. -- 3D and Materials › Render Settings › Rendered: `render: {mode: "rendered"}` with `quality`, `resolution` and `background` draws the solid of Extrude & Bevel, Revolve, Inflate and Rotate as one depth-buffered image lit by every light (Revolve on a group draws every member's surface in one image, and Revolve on a fill or stroke draws that surface's own image), with shadow maps while Shading and Shadows are both on; solids painted with a gradient, a pattern, graphics, an opacity below 100% or a blending mode other than Normal, a later geometry effect that reshapes paths only, and an image past the renderer's limits draw the shaded faces instead, with a warning ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/rendered/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. +- 3D and Materials › Render Settings › Rendered: `render: {mode: "rendered"}` with `quality`, `resolution` and `background` draws the solid of Extrude & Bevel, Revolve, Inflate and Rotate as one depth-buffered image lit by every light (Revolve on a group draws every member's surface in one image, and Revolve on a fill or stroke draws that surface's own image), with shadow maps while Shading and Shadows are both on; a solid below 100% opacity or in a blending mode other than Normal draws its own image in that opacity and blending mode, after the shadow plane's images, except in Revolve on a group; solids painted with a gradient, a pattern or graphics, a later geometry effect that reshapes paths only, and an image past the renderer's limits draw the shaded faces instead, with a warning ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/rendered/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Materials › Properties: Roughness and Metallic sliders set `material: {roughness, metallic}` on Extrude & Bevel, Revolve, Inflate and Rotate; with Shading on and outside Wireframe mode, any material other than the default (1 and 0) is shaded with craft-pbr's glTF 2.0 metallic-roughness BRDF, its highlight screened over each face; in every mode glTF exports write both factors, and USD exports write roughness and write metallic only when it is not the default 0 ([three-d.md](three-d.md#material-properties)); `crates/three-d/src/material.rs`, `crates/effects/src/solids/tests_material.rs`, `crates/engine/src/cmd/fileio/mesh3d/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D and Materials › Export 3D Object: the panel's button adds the selected objects that have a 3D effect to Asset Export as 3D assets (`assets.add3D`), one undo step and none when each is an asset already, selects their assets and shows the Asset Export panel ([three-d.md](three-d.md#3d-and-materials-panel)); `panels::three_d::tests::{export_3d_object_adds_the_selected_3d_objects_to_asset_export, export_3d_object_leaves_out_a_3d_object_inside_another}` cover it. Scores and hours unchanged. - 3D effects on clipping groups, blends and symbol instances (#6140, #5725): every 3D type builds from the art the object shows (the art inside the clipping path, the blend's keys and steps, the symbol's art where the instance places it), alone or in a group, on the canvas, in exports, Object › Rasterize and `assets.add3D`; an image is refused with a pointer to Object › Image Trace › Make. `crates/effects/src/solids/tests_sources.rs`, `crates/engine/src/cmd/effectcmd/three_d_source_tests.rs` and `fx::tests::a_symbol_instance_a_blend_and_a_clipping_group_draw_their_solids` cover it. Scores and estimates unchanged. diff --git a/docs/three-d.md b/docs/three-d.md index ca4ab76973..38d9fc1cc4 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -79,12 +79,23 @@ pages describe it. made only when the object is drawn, then reused until an input to it changes. A quality whose samples would pass 16,777,216 pixels takes fewer; past that limit at one sample a pixel, or when the solid can't be placed in one image, the effect draws its shaded faces. The image keeps transparency where no surface is, or is white with - `background: white`. The image shows opaque solid colors only: a solid painted with a gradient or a pattern, one - with graphics, a paint with an opacity below 100% or in a blending mode other than Normal, a painted group member - whose own opacity or the opacity of a nested group holding it is below 100%, and a group member whose opacity mask or blending mode - applies to its solid draw the shaded faces, as does a later geometry effect that reshapes paths but leaves images - unchanged. Revolve on a group draws every member's surface in one image, and Revolve on a fill or stroke draws an - image of that fill's or stroke's surface under the effects after it. The mode + `background: white`. The image shows solid colors only: a solid painted with a gradient or a pattern, one with + graphics, and a group member whose opacity mask or blending mode applies to its solid draw the shaded faces, as does + a later geometry effect that reshapes paths but leaves images unchanged. A solid painted below 100% opacity or in a + blending mode other than Normal, a group member's own opacity and that of a nested group holding it included, draws + its image in that opacity and blending mode, as the shaded faces draw its surface. An object or group whose solids + are all opaque in Normal blending draws one image with its shadows. When any solid is see-through or blended, each + solid draws an image of its own, in the order of the fills and strokes, lit and shadowed as in the one image, and + with Shadows on the shadow plane draws first, in an image for each run of solids in the same opacity and blending + mode, as the shaded faces draw the shadow. An effect on one fill or stroke with Shadows on always draws the shadow + plane in images of its own, behind every fill and stroke of the object unless the background is white. A solid at 0% opacity draws nothing, casts + no shadow, and is left out of the image's mesh budget, size and choice between one image and several. These images share + the 16,777,216-pixel limit, and past 16 images (VectorCraft's own value) the effect draws its shaded faces. With + `background: white` and more than one image, one white rectangle goes behind them all. On one fill or stroke, + the rectangle stays at that paint's position, followed by the plane images and solids' images. Revolve on a group draws + every visible member's surface in one image, and draws the shaded faces when a visible member's surface is below 100% opacity or in + a blending mode other than Normal. Revolve on a fill or stroke draws an image of that fill's or stroke's surface + under the effects after it. The mode is saved with the effect. The status bar and the command result's `warning` field report when the shaded faces are drawn instead. The lighting follows the same lights as the shaded faces but in linear light, so lit areas differ from the shaded faces' colors. Ambient Light keeps its full range from 0 to 200%;