3D: rendered images take every light's shadows and a Raster Settings dialog

- With Shadows on, every light with an intensity above 0 casts shadows on
  the solid and on the shadow plane in the image, black at 50%, with each
  light's Softness widening its edge; with Shadows off none does.
- Selection, Use Preview Bounds, Align, hit testing and snapping measure
  the shaded faces without rasterizing. Painted bounds hold the whole
  image, measured without rasterizing. Images are cached by their inputs.
- Expand Appearance and baking keep the rendered image; PDF export in a
  CMYK document writes it as raster effects are written.
- Render Settings gains Raster Settings... (resolution and background),
  built on the framework's parameter dialog; settings the selection holds
  differently open blank and are kept. The menu checks a choice only when
  every selected object has it.
- Tests for the clip matrix, coverage, depth order, the shading formula,
  limits, work bounds, edge values, masks and Revolve's objects-only rule.

Docs: docs/three-d.md, docs/mcp.md, effect params text.
This commit is contained in:
dotCooCoo committed 2026-11-30 09:40:13 -08:00
1 parent 1cb36511e9
commit 034c6fbd8d
19 files changed
+1576 -132

No files matched your search

+3 -3
View File
@@ -354,7 +354,7 @@ fn bake_object(d: &mut Document, n: &Node) -> Option<Node> {
if let Some(m) = crate::addons::halftone::halftone_art(d, n) {
return Some(bake_pieces(d, m));
}
if let Some(m) = crate::revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) {
if let Some(m) = crate::revolve_art_drawn_in(Some(d), n).or_else(|| crate::solid_art_drawn_in(Some(d), n)) {
let m = evaluate_container(Some(d), &m).unwrap_or(m);
return Some(bake_pieces(d, m));
}
@@ -871,7 +871,7 @@ pub type StrokeArt<'a> = &'a mut dyn FnMut(&mut Document, &PathData, FillRule, &
/// without transparency or effects of its own takes `n`'s place itself. Hidden fills, strokes and
/// effects are dropped. `None` for other kinds of objects.
pub fn expand_leaf(d: &mut Document, n: &Node, stroke_art: StrokeArt) -> Option<Node> {
if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) {
if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_drawn_in(Some(d), n)) {
let m = evaluate_container(Some(d), &m).unwrap_or(m);
return Some(bake_pieces(d, m));
}
@@ -963,7 +963,7 @@ pub fn bake_type_appearance(doc: Option<&Document>, n: &Node) -> Option<Node> {
/// [`bake_appearance`], or with `outline_strokes` false [`bake_type_appearance`].
fn bake_appearance_as(doc: Option<&Document>, n: &Node, outline_strokes: bool) -> Option<Node> {
if let Some(m) = crate::revolve_art_in(doc, n).or_else(|| crate::solid_art_in(doc, n)) {
if let Some(m) = crate::revolve_art_drawn_in(doc, n).or_else(|| crate::solid_art_drawn_in(doc, n)) {
return Some(m);
}
if !matches!(n.kind, NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. }) {
+1 -1
View File
@@ -241,7 +241,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
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; 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), 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 the shadows each casts on the solid, over the effect's shadow, and draws the shaded faces when the image can't be made; 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; 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), 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; 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(
+4 -3
View File
@@ -95,16 +95,17 @@ pub use reshape::{
has_transform_options, image_paint, instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape,
};
pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_drawn_in, revolve_art_in, revolve_options, validate_revolve,
validate_revolve_in,
};
pub use solids::rendered::rendered_warning;
pub use solids::rendered::{rendered_warning, three_d_bounds_art_in};
pub use solids::{
BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MATERIAL, MAX_GRAPHICS, MappedGraphic,
MeshGraphics, RENDER, RENDER_BACKGROUNDS, RENDER_MODES, RENDER_QUALITIES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, RenderSettings,
SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, graphic_bounds, graphic_frame,
graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, mesh_graphics_art, missing_symbol,
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, render_settings, rendered, renders_image, renders_wireframe, solid_art,
solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as,
solid_art_drawn_in, solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as,
three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in,
validate_three_d_params, view_options, with_graphic,
};
+36 -15
View File
@@ -10,7 +10,7 @@ use vectorcraft_three_d::{Edge, PlanarFace, Revolve, SolidFaces};
use crate::solids::wireframe::{WireFace, wireframe_params};
use crate::solids::{
Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds,
Build, Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds,
};
use crate::util::{flag, num, text};
use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params};
@@ -845,7 +845,7 @@ pub fn revolve_art(n: &Node) -> Option<Node> {
/// or in a group, revolve the art they show ([`resolve_for`]). `None` too when that art can't be
/// resolved.
pub fn revolve_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
art_reporting(doc, n, false, false, &mut None)
art_reporting(doc, n, false, Build::Vector, &mut None)
}
/// [`expand_revolve_art_in`] without a document.
@@ -854,10 +854,11 @@ pub(crate) fn expand_revolve_art(n: &Node) -> Option<Node> {
expand_revolve_art_in(None, n)
}
/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]). The shared
/// command and UI remain unchanged.
/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]): in
/// Render Settings › Rendered, the rendered image where it can be made. The shared command and UI
/// remain unchanged.
pub(crate) fn expand_revolve_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
art_reporting(doc, n, true, false, &mut None)
art_reporting(doc, n, true, Build::Draw, &mut None)
}
/// The surfaces [`revolve_art`] draws, as meshes ([`crate::three_d_meshes`]): with the effect on
@@ -1084,7 +1085,17 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::
Ok(out)
}
pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, check_only: bool, warning: &mut Option<String>) -> Option<Node> {
/// The art [`revolve_art_in`] builds, as it is drawn and exported: in Render Settings › Rendered,
/// the image of the lit surface where it can be made, in place of the shaded faces that
/// [`revolve_art_in`] keeps for bounds, hit testing and snapping.
pub fn revolve_art_drawn_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
art_reporting(doc, n, false, Build::Draw, &mut None)
}
/// [`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`.
pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, build: Build, warning: &mut Option<String>) -> Option<Node> {
let check_only = build == Build::Check;
if !has_revolve(n) {
return None;
}
@@ -1105,13 +1116,28 @@ pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, chec
let item = surface_item(&paints)?;
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
let p = merged_params(&fx.id, &fx.params);
// Rendered, the surface's image over its shadow; the shaded faces when it can't be made.
let image = crate::render_settings(&fx.id, &p).and_then(|settings| {
// Rendered, the surface's image, with the shadows of every light on the surface and on the
// shadow plane; the shaded faces when it can't be made, and for vector measurements.
let image = crate::render_settings(&fx.id, &p).filter(|_| build != Build::Vector).and_then(|settings| {
let result = if crate::mapped_graphics(&p).is_empty() && crate::solids::rendered::takes([item], false) {
let b = path.bounds()?;
let (paint, opacity, _) = paint_of(item);
surface_meshes(&path, rule, b, fx, rule_options(fx, rule), (&paint, opacity, 1.0), true).and_then(|meshes| {
crate::solids::rendered::art(doc, n.id, &crate::solids::rendered::lighting(&fx.id, &p), &meshes, settings, check_only)
let options = rule_options(fx, rule);
surface_meshes(&path, rule, b, fx, options, (&paint, opacity, 1.0), 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) => {
let mut caster = vectorcraft_three_d::ShadowCaster::new();
let faces = cast_surface(&mut caster, &path, b, options, None)?;
crate::solids::rendered::with_receiver(lighting, &caster, shadow, &[faces])
}
None => lighting,
};
if build == Build::Bounds {
crate::solids::rendered::bounds_art(doc, n.id, &lighting, &meshes, settings)
} else {
crate::solids::rendered::art(doc, n.id, &lighting, &meshes, settings, check_only)
}
})
} else {
Err(crate::solids::rendered::OPAQUE_ONLY.into())
@@ -1122,11 +1148,6 @@ pub(crate) fn art_reporting(doc: Option<&Document>, n: &Node, expand: bool, chec
return None;
}
if let Some(image) = image {
if let Some(b) = path.bounds()
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, rule_options(fx, rule), None).ok()?
{
children.push(Arc::new(shadow));
}
children.push(image);
} else if crate::solids::renders_wireframe(fx) {
// In wireframe mode the edges of the faces, with no shadow.
+64 -16
View File
@@ -2046,10 +2046,10 @@ fn art_for(
n: &Node,
fx: &Effect,
shapes: &[Profile],
check_only: bool,
build: Build,
warning: &mut Option<String>,
) -> Option<ShadowAndSurfaces> {
if check_only && !crate::renders_image(fx) {
if build == Build::Check && !crate::renders_image(fx) {
return Some((vec![], vec![]));
}
// In wireframe mode the effect draws the edges of the faces it builds, with no shadow.
@@ -2057,20 +2057,36 @@ fn art_for(
return Some((vec![], wireframe::wire_surfaces(n.id, fx, shapes)?));
}
let p = crate::merged_params(&fx.id, &fx.params);
// Rendered, the solids' image over the effect's shadow; the shaded faces when it can't be made.
if let Some(settings) = wireframe::render_settings(&fx.id, &p) {
// Rendered, the solids' image, with the shadows of every light on the solids and on the shadow
// plane; the shaded faces when it can't be made, and for vector measurements.
if build != Build::Vector
&& let Some(settings) = wireframe::render_settings(&fx.id, &p)
{
let image = if mapped_graphics(&p).is_empty() && rendered::takes(shapes.iter().flat_map(|s| &s.items), has_masks(shapes)) {
meshes_for(fx, shapes, &mut 0, MAX_MESH_TRIANGLES)
.and_then(|meshes| rendered::art(doc, n.id, &rendered::lighting(&fx.id, &p), &meshes, settings, check_only))
meshes_for(fx, shapes, &mut 0, MAX_MESH_TRIANGLES).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)) => {
let faces: Vec<std::ops::Range<usize>> = cast.iter().map(|c| c.2.clone()).collect();
rendered::with_receiver(lighting, &caster, shadow, &faces)
}
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)
}
})
} else {
Err(rendered::OPAQUE_ONLY.into())
};
let image = rendered::reported(image, warning);
if check_only {
if build == Build::Check {
return Some((vec![], vec![]));
}
if let Some(image) = image {
return Some((shadow_for(n.id, fx, shapes).ok()?, vec![image]));
return Some((vec![], vec![image]));
}
}
let cast = casts_shadow(&fx.id, &p);
@@ -2105,10 +2121,20 @@ pub(crate) fn shadow_for(id: NodeId, fx: &Effect, shapes: &[Profile]) -> Result<
/// When a member's opacity mask or blending mode applies to its solids ([`masked`]), it applies to
/// the part of the shadow they cast too ([`shadow::scoped_art`]).
fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<Cast<'a>>, String> {
cast_shadow_with(id, p, shapes, shadow::options(p))
}
/// [`cast_shadow`] with the shadow settings `settings` in place of those of `p`.
fn cast_shadow_with<'a>(
id: &str,
p: &Value,
shapes: &'a [Profile],
settings: Option<vectorcraft_three_d::Shadow>,
) -> Result<Option<Cast<'a>>, String> {
if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE {
return Ok(None);
}
let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) };
let (Some(settings), Some(b)) = (settings, union_bounds(shapes)) else { return Ok(None) };
let view = view_options(p);
let mut caster = vectorcraft_three_d::ShadowCaster::new();
// The faces each solid of visible art added, with its member's scopes and its ink (opacity
@@ -2837,16 +2863,38 @@ pub fn solid_art(n: &Node) -> Option<Node> {
/// or in a group, build from the art they show ([`resolve`]). `None` too when that art can't be
/// resolved.
pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
solid_art_reporting(doc, n, false, &mut None)
solid_art_reporting(doc, n, Build::Vector, &mut None)
}
pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, check_only: bool, warning: &mut Option<String>) -> Option<Node> {
/// The art [`solid_art_in`] builds, as it is drawn and exported: in Render Settings › Rendered, the
/// image of the lit solids where it can be made ([`rendered`]), in place of the shaded faces that
/// [`solid_art_in`] keeps for bounds, hit testing and snapping.
pub fn solid_art_drawn_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
solid_art_reporting(doc, n, Build::Draw, &mut None)
}
/// What a 3D effect's art is built for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Build {
/// The vector art: the shaded faces and the vector shadow, in every mode but wireframe. No
/// rendered image is made.
Vector,
/// Painted measurement art, with rendered images represented by their rectangles and no pixels.
Bounds,
/// Only whether the rendered image can be made, with the reason in the warning when it can't:
/// no art and no pixels.
Check,
/// The art drawn and exported: the rendered image where it can be made.
Draw,
}
pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, build: Build, warning: &mut Option<String>) -> Option<Node> {
if !has_solid(n) {
return None;
}
let n = &*resolve(doc, n, "").ok()?;
if is_container(n) {
return group_solid_art(doc, n, check_only, warning);
return group_solid_art(doc, n, build, warning);
}
let (path, rule) = profile(n)?;
let ctx = GeomContext::of(n);
@@ -2855,7 +2903,7 @@ pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, check_only:
let remaining: Vec<Effect>;
if let Some((index, fx)) = solid(&n.appearance.effects) {
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], check_only, warning)?;
let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }], build, 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);
@@ -2872,7 +2920,7 @@ pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, check_only:
if let Some((index, fx)) = solid(item.effects()) {
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(source.unwrap_or(item)));
let (shadow, surfaces) =
art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }], check_only, warning)?;
art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }], build, warning)?;
let later: Vec<Effect> = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect();
let with_later = |mut art: Arc<Node>| {
Arc::make_mut(&mut art).appearance.effects = later.clone();
@@ -2901,11 +2949,11 @@ pub(crate) fn solid_art_reporting(doc: Option<&Document>, n: &Node, check_only:
/// 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.
fn group_solid_art(doc: Option<&Document>, n: &Node, check_only: bool, warning: &mut Option<String>) -> Option<Node> {
fn group_solid_art(doc: Option<&Document>, n: &Node, build: Build, warning: &mut Option<String>) -> Option<Node> {
let (index, fx) = 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, fx, &shapes, check_only, warning)?;
let (shadow, surfaces) = art_for(doc, n, fx, &shapes, build, warning)?;
let children = shadow.into_iter().chain(surfaces).collect();
let remaining = past_effect(&n.appearance.effects, index);
let mut art = n.clone();
+304 -36
View File
@@ -34,13 +34,44 @@ pub fn rendered_warning(doc: &vectorcraft_doc::Document, n: &Node) -> Option<Str
}
let mut warning = None;
if crate::has_revolve(n) {
let _ = crate::revolve::art_reporting(Some(doc), n, false, true, &mut warning);
let _ = crate::revolve::art_reporting(Some(doc), n, false, super::Build::Check, &mut warning);
} else {
let _ = super::solid_art_reporting(Some(doc), n, true, &mut warning);
let _ = super::solid_art_reporting(Some(doc), n, super::Build::Check, &mut warning);
}
warning
}
/// The art of `n`'s 3D effect for painted bounds, with rendered images represented by their page
/// rectangles without pixels. Shaded fallback art and later effects keep their normal bounds.
/// This art is for measurement only; selection and snapping use the vector art instead.
pub fn three_d_bounds_art_in(doc: Option<&vectorcraft_doc::Document>, n: &Node) -> Option<Node> {
crate::revolve::art_reporting(doc, n, false, super::Build::Bounds, &mut None)
.or_else(|| super::solid_art_reporting(doc, n, super::Build::Bounds, &mut None))
}
/// 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.
pub(crate) fn bounds_art(
doc: Option<&vectorcraft_doc::Document>,
id: NodeId,
lighting: &Lighting,
meshes: &[SolidMesh],
settings: RenderSettings,
) -> Result<Option<Arc<Node>>, String> {
art(doc, id, lighting, meshes, settings, true)?;
let m = measure(meshes, lighting, settings, doc.map_or(72.0, |d| d.raster_ppi()), false, &Limits::default())?;
let object = ImageObject {
key: String::new(),
width: m.cols,
height: m.rows,
xf: Affine::new([m.rect.width() / f64::from(m.cols), 0.0, 0.0, m.rect.height() / f64::from(m.rows), m.rect.x0, m.rect.y0]),
link: None,
placement: Default::default(),
pixels: None,
};
Ok(Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object))))))
}
/// 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<Option<Arc<Node>>, String>, warning: &mut Option<String>) -> Option<Arc<Node>> {
@@ -58,10 +89,53 @@ pub(crate) fn reported(result: Result<Option<Arc<Node>>, String>, warning: &mut
pub struct Lighting {
/// The directional lights ([`vectorcraft_three_d::Revolve::active_lights`]).
pub lights: Vec<Light>,
/// Each light's shadow diffusion in points, in the same order as `lights`.
pub diffusion: Vec<f64>,
/// The ambient light, 0 to 2.
pub ambient: f64,
/// Shading on: off, the solids show their paint unlit, as the shaded faces do.
pub shade: bool,
/// Shadows on: each light that lights the art casts shadows on the solids and on
/// [`Lighting::receiver`]. Off, no light casts one.
pub shadows: bool,
/// The part of the shadow plane the shadows fall on, as four corners in mesh space (y up), in
/// order round it ([`receiver`]); `None` without one.
pub receiver: Option<[[f64; 3]; 4]>,
}
impl Lighting {
/// Does light `l` cast shadows in the image: Shading and Shadows are on and it lights the art?
fn casts(&self, l: &Light) -> bool {
self.shade && self.shadows && l.intensity > 0.0
}
}
/// The opacity of the black the shadow plane shows where a shadow falls, as the effect's vector
/// shadow paints it.
const PLANE_SHADOW: f32 = 0.5;
/// How far the shadow plane reaches past the shadows on it, as a share of the solids' largest size,
/// so a soft edge is not cut. VectorCraft's own value.
const PLANE_MARGIN: f64 = 0.05;
/// `lighting` with the part of the shadow plane the shadows of the faces in `faces` of `caster`
/// fall on, with settings `shadow`, for every light that casts one ([`Lighting::casts`]).
pub(crate) fn with_receiver(
mut lighting: Lighting,
caster: &vectorcraft_three_d::ShadowCaster,
shadow: vectorcraft_three_d::Shadow,
faces: &[std::ops::Range<usize>],
) -> Lighting {
let toward: Vec<[f64; 3]> = lighting.lights.iter().filter(|l| lighting.casts(l)).map(|l| l.direction()).collect();
lighting.diffusion = lighting
.lights
.iter()
.map(|l| caster.shadow_blur(vectorcraft_three_d::Shadow { softness: l.softness, ..shadow }, faces).unwrap_or(0.0))
.collect();
let softness = lighting.lights.iter().filter(|l| lighting.casts(l)).map(|l| l.softness).fold(0.0, f64::max);
let shadow = vectorcraft_three_d::Shadow { softness, ..shadow };
lighting.receiver = caster.receiver(shadow, faces, &toward, PLANE_MARGIN).map(|q| q.map(|[x, y, z]| [x, -y, z]));
lighting
}
/// A rendered image: `cols` × `rows` straight-alpha sRGB RGBA8 pixels covering `rect` on the page,
@@ -97,12 +171,13 @@ pub fn render(
limits: &Limits,
) -> Result<Rendered, String> {
let too_large = || TOO_LARGE.to_string();
let Measured { projection, rect, z, clip, cols, rows, samples: k, low } = measure(meshes, settings, doc_ppi, draft, limits)?;
let mut scene = scene(meshes, lighting, projection, z, clip, (cols * k, rows * k)).ok_or_else(too_large)?;
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)?;
scene.ssaa = k;
#[cfg(test)]
RASTERIZATIONS.with(|n| n.set(n.get() + 1));
if lighting.shade {
if scene.lights.iter().any(|l| l.shadow >= 0) {
try_shadow_maps(&mut scene, low, limits).map_err(|_| too_large())?;
}
let (mut image, _) = try_render_cpu(&scene, limits).map_err(|_| too_large())?;
@@ -138,14 +213,22 @@ struct Measured {
low: bool,
}
/// Measure the image and choose its samples without building a scene or producing pixels.
fn measure(meshes: &[SolidMesh], settings: RenderSettings, doc_ppi: f64, draft: bool, limits: &Limits) -> Result<Measured, String> {
/// Measure the image of `meshes` and the shadow plane `lighting` places, and choose its samples,
/// without building a scene or producing pixels.
fn measure(
meshes: &[SolidMesh],
lighting: &Lighting,
settings: RenderSettings,
doc_ppi: f64,
draft: bool,
limits: &Limits,
) -> Result<Measured, String> {
let too_large = || TOO_LARGE.to_string();
let projection = meshes.first().and_then(|m| m.projection).ok_or_else(too_large)?;
if meshes.iter().any(|m| m.projection != Some(projection)) {
return Err(too_large());
}
let (bounds, z) = extent(meshes, projection).ok_or_else(too_large)?;
let (bounds, z) = extent(meshes, receiver(lighting), projection).ok_or_else(too_large)?;
let cell = 72.0 / settings.resolution.unwrap_or(doc_ppi).clamp(1.0, 2400.0);
let (cols, rows) = ((bounds.width() / cell).ceil().max(1.0), (bounds.height() / cell).ceil().max(1.0));
let pixels = cols * rows;
@@ -164,15 +247,16 @@ fn measure(meshes: &[SolidMesh], settings: RenderSettings, doc_ppi: f64, draft:
}
/// Check scene limits without allocating raster or shadow depth buffers. The counts follow
/// craft-raster3d at 64383b5906b5a0a14fa4bea21dac379f2deae4bc: lib.rs:178-223,
/// 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 lie inside the clip volume and use opaque, visible materials and directional
/// lights only, 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.
/// Measured solids and the shadow plane lie inside the clip volume, the solids use opaque, visible
/// 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> {
let m = measure(meshes, settings, ppi, false, limits)?;
let s = scene(meshes, lighting, m.projection, m.z, m.clip, (m.cols * m.samples, m.rows * m.samples)).ok_or(TOO_LARGE)?;
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)?;
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());
@@ -206,7 +290,15 @@ fn check(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, pp
return Err(TOO_LARGE.into());
}
}
if s.lights.is_empty() || s.indices.is_empty() {
// Shadow maps are made only for the lights that cast shadows, from the triangles that cast them.
let casters: Vec<&[u32; 3]> = s
.indices
.as_chunks::<3>()
.0
.iter()
.filter(|t| s.materials.get(s.vertices[t[0] as usize].material as usize).is_some_and(|m| m.casts_shadows))
.collect();
if casters.is_empty() || s.lights.iter().all(|l| l.shadow < 0) {
return Ok(());
}
let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
@@ -218,10 +310,15 @@ fn check(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, pp
}
let center = [0, 1, 2].map(|k| (lo[k] + hi[k]) * 0.5);
let radius = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt() * 0.5 + 1.0;
let sizes = craft_raster3d::shadow_sizes(s.width, s.height, m.low, &vec![1; s.lights.len()]);
let kinds: Vec<u32> = s.lights.iter().map(|l| u32::from(l.shadow >= 0)).chain(std::iter::once(0)).collect();
let sizes = craft_raster3d::shadow_sizes(s.width, s.height, m.low, &kinds);
let maps = sizes.iter().flatten().count() as u64;
if maps.saturating_mul(casters.len() as u64) > limits.max_work {
return Err(TOO_LARGE.into());
}
let mut work = 0u64;
for (light, size) in s.lights.iter().zip(sizes) {
let Some(size) = size else { continue };
let (Some(size), true) = (size, light.shadow >= 0) else { continue };
let dir = light.dir.map(f64::from);
let eye = [0, 1, 2].map(|k| center[k] - dir[k] * radius * 2.0);
let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
@@ -236,7 +333,7 @@ fn check(meshes: &[SolidMesh], lighting: &Lighting, settings: RenderSettings, pp
]);
let view = [right, down].map(|row| [row[0] as f32, row[1] as f32, row[2] as f32, (-dot(row, eye)) as f32]);
let focal = (f64::from(size) * 0.5 / radius) as f32;
for tri in s.indices.as_chunks::<3>().0 {
for tri in &casters {
let points = [0, 1, 2].map(|k| {
let p = s.vertices[tri[k] as usize].pos;
[0, 1].map(|r| f64::from(transform(&view, p, r) * focal + size as f32 * 0.5))
@@ -268,12 +365,19 @@ fn bounding_work(points: [[f64; 2]; 3], size: [u32; 2]) -> u64 {
.product()
}
/// The page bounds the points of `meshes` project to, and the range of their depths. `None` with no
/// point, a point that isn't finite, or one at or behind the eye.
fn extent(meshes: &[SolidMesh], projection: MeshProjection) -> Option<(Rect, [f64; 2])> {
/// The corners of the shadow plane of `lighting`, in mesh space; none without one.
fn receiver(lighting: &Lighting) -> &[[f64; 3]] {
lighting.receiver.as_ref().map_or(&[], |q| q.as_slice())
}
/// 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
/// behind the eye.
fn extent(meshes: &[SolidMesh], plane: &[[f64; 3]], projection: MeshProjection) -> Option<(Rect, [f64; 2])> {
let mut bounds: Option<Rect> = None;
let mut z = [f64::INFINITY, f64::NEG_INFINITY];
for p in meshes.iter().flat_map(|m| &m.mesh.positions) {
meshes.iter().flat_map(|m| &m.mesh.positions).next()?;
for p in meshes.iter().flat_map(|m| &m.mesh.positions).chain(plane) {
if !p.iter().all(|v| v.is_finite()) || projection.eye.is_some_and(|e| p[2] >= e * NEAREST) {
return None;
}
@@ -312,8 +416,17 @@ fn clip(projection: MeshProjection, rect: Rect, z: [f64; 2]) -> Option<[[f32; 4]
/// The scene of `meshes` for an image `size` raster pixels with clip matrix `clip`: 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.
fn scene(meshes: &[SolidMesh], lighting: &Lighting, projection: MeshProjection, z: [f64; 2], clip: [[f32; 4]; 4], size: (u32, u32)) -> Option<Scene> {
/// 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<Scene> {
let eye = projection.eye.unwrap_or(z[1] + 1.0);
let mut vertices = vec![];
let mut opaque: Vec<[u32; 3]> = vec![];
@@ -357,15 +470,48 @@ fn scene(meshes: &[SolidMesh], lighting: &Lighting, projection: MeshProjection,
}
}
clear.sort_by(|a, b| a.1.total_cmp(&b.1));
// 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) {
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]];
let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
if len.is_finite() && len > 0.0 {
let material = materials.len() as u32;
materials.push(craft_raster3d::Material {
base: [0.0, 0.0, 0.0, 1.0],
opacity: PLANE_SHADOW,
double_sided: true,
shadows_only: true,
receives_shadows: true,
casts_shadows: false,
..Default::default()
});
let base = vertices.len() as u32;
for p in q {
vertices.push(Vertex {
pos: [p[0] as f32, -p[1] as f32, p[2] as f32],
normal: [(n[0] / len) as f32, (-n[1] / len) as f32, (n[2] / len) as f32],
uv: [0.0; 2],
tangent: [1.0, 0.0, 0.0, 1.0],
material,
});
}
plane = vec![[base, base + 1, base + 2], [base, base + 2, base + 3]];
}
}
// Later meshes paint over earlier ones in the shaded faces. Submit their opaque triangles
// first so the strict depth test keeps that paint when surfaces share a depth.
let opaque_count = (opaque.len() * 3) as u32;
let indices = opaque.into_iter().rev().flatten().chain(clear.into_iter().flat_map(|(t, _)| t)).collect();
let indices = opaque.into_iter().rev().flatten().chain(plane.into_iter().flatten()).chain(clear.into_iter().flat_map(|(t, _)| t)).collect();
let lights = lighting
.lights
.iter()
.enumerate()
.filter(|_| lighting.shade)
.map(|l| {
.map(|(i, l)| {
// The direction the light travels: away from it.
let [x, y, z] = l.direction().map(|v| -v);
let len = (x * x + y * y + z * z).sqrt();
@@ -379,9 +525,10 @@ fn scene(meshes: &[SolidMesh], lighting: &Lighting, projection: MeshProjection,
falloff: 0,
radius: 0.0,
falloff_distance: 0.0,
shadow: 0,
// With Shadows off no light casts one, on the solids or on a plane.
shadow: if lighting.casts(l) { 0 } else { -1 },
shadow_darkness: 1.0,
shadow_diffusion: l.softness as f32,
shadow_diffusion: lighting.diffusion.get(i).map_or(l.softness, |blur| blur * scale) as f32,
}
})
.collect();
@@ -417,12 +564,17 @@ fn scene(meshes: &[SolidMesh], lighting: &Lighting, projection: MeshProjection,
/// `image` as an image object of `id`'s art, holding its pixels as a PNG; `None` when it can't be
/// encoded.
pub fn image_node(id: NodeId, image: &Rendered) -> Option<Arc<Node>> {
Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(image_object(image)?)))))
}
/// `image` as an image object holding its pixels as a PNG; `None` when it can't be encoded.
fn image_object(image: &Rendered) -> Option<ImageObject> {
let raw = image::RgbaImage::from_raw(image.cols, image.rows, image.pixels.clone())?;
let mut png = vec![];
raw.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
let blob = ImageBlob::png(png);
let cell = image.rect.width() / f64::from(image.cols);
let object = ImageObject {
Some(ImageObject {
key: blob.content_key(),
width: image.cols,
height: image.rows,
@@ -430,8 +582,7 @@ pub fn image_node(id: NodeId, image: &Rendered) -> Option<Arc<Node>> {
link: None,
placement: Default::default(),
pixels: Some(Arc::new(blob)),
};
Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object)))))
})
}
/// The image a 3D effect with `settings` draws for object `id` from `meshes`, lit by `lighting`, with
@@ -456,7 +607,115 @@ pub(crate) fn art(
check(meshes, lighting, settings, ppi, &Limits::default())?;
return Ok(None);
}
image_node(id, &render(meshes, lighting, settings, ppi, false, &Limits::default())?).map(Some).ok_or_else(|| TOO_LARGE.into())
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
}
};
made.map(|object| Some(Arc::new(Node::new(id, NodeKind::Image(Box::new(object))))))
}
/// Most rendered images [`art`] keeps for reuse, and most PNG bytes they hold together. VectorCraft's
/// own values.
const KEPT_IMAGES: usize = 32;
const KEPT_BYTES: usize = 64 << 20;
/// What [`art`] made, newest last, under the key of what it was made from ([`image_key`]).
type Kept = Vec<(u128, Result<ImageObject, String>)>;
#[cfg(not(test))]
static KEPT: std::sync::Mutex<Kept> = std::sync::Mutex::new(Vec::new());
#[cfg(test)]
thread_local! {
/// Each test thread keeps its own images, so a test's count of rasterizations doesn't depend on
/// what other tests drew.
static KEPT: std::cell::RefCell<Kept> = const { std::cell::RefCell::new(Vec::new()) };
}
/// Run `f` on the kept images; `None` when they can't be reached.
fn with_kept<T>(f: impl FnOnce(&mut Kept) -> T) -> Option<T> {
#[cfg(not(test))]
{
KEPT.lock().ok().map(|mut kept| f(&mut kept))
}
#[cfg(test)]
{
KEPT.with(|kept| kept.try_borrow_mut().ok().map(|mut kept| f(&mut kept)))
}
}
/// The image kept under `key`, moved to the newest place.
fn cached(key: u128) -> Option<Result<ImageObject, String>> {
with_kept(|kept| {
let at = kept.iter().position(|(k, _)| *k == key)?;
let entry = kept.remove(at);
let made = entry.1.clone();
kept.push(entry);
Some(made)
})
.flatten()
}
/// Keep `made` under `key`, letting the oldest go past [`KEPT_IMAGES`] or [`KEPT_BYTES`].
fn keep(key: u128, made: &Result<ImageObject, String>) {
let bytes = |m: &Result<ImageObject, String>| m.as_ref().ok().and_then(|o| o.pixels.as_ref()).map_or(0, |b| b.bytes.len());
if bytes(made) > KEPT_BYTES {
return;
}
with_kept(|kept| {
kept.retain(|(k, _)| *k != key);
kept.push((key, made.clone()));
while kept.len() > KEPT_IMAGES || kept.iter().map(|(_, m)| bytes(m)).sum::<usize>() > KEPT_BYTES {
drop(kept.remove(0));
}
});
}
/// 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 {
use std::hash::{Hash, Hasher};
let half = |seed: u8| {
let mut h = std::collections::hash_map::DefaultHasher::new();
seed.hash(&mut h);
let mut f = |v: f64| v.to_bits().hash(&mut h);
for m in meshes {
let mesh = &m.mesh;
mesh.positions.iter().chain(&mesh.normals).flatten().for_each(|v| f(*v));
mesh.uvs.iter().flatten().for_each(|v| f(*v));
m.color.iter().for_each(|c| f(f64::from(*c)));
f(m.material.roughness());
f(m.material.metallic());
if let Some(p) = m.projection {
[p.origin.x, p.origin.y, p.eye.unwrap_or(f64::NAN)].into_iter().for_each(&mut f);
}
f(mesh.positions.len() as f64);
f(mesh.triangles.len() as f64);
}
for l in &lighting.lights {
[l.rotation, l.height, l.intensity, l.softness, f64::from(u8::from(l.behind))].into_iter().chain(l.color).for_each(&mut f);
}
lighting.receiver.iter().flatten().flatten().for_each(|v| f(*v));
lighting.diffusion.iter().for_each(|v| f(*v));
f(lighting.diffusion.len() as f64);
[lighting.ambient, f64::from(u8::from(lighting.shade)), f64::from(u8::from(lighting.shadows)), lighting.lights.len() as f64]
.into_iter()
.for_each(&mut f);
[settings.quality as f64, settings.resolution.unwrap_or(f64::NAN), f64::from(u8::from(settings.white)), ppi].into_iter().for_each(&mut f);
for m in meshes {
m.mesh.triangles.hash(&mut h);
}
h.finish()
};
(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
@@ -476,13 +735,22 @@ pub(crate) fn takes<'a>(items: impl IntoIterator<Item = &'a vectorcraft_doc::App
/// The lights a 3D effect with parameters `p` shades its faces with: Revolve's ([`crate::revolve_options`])
/// for Revolve, the other effects' ([`super::view_options`]) otherwise.
pub(crate) fn lighting(id: &str, p: &serde_json::Value) -> Lighting {
if id == crate::REVOLVE {
let (lights, ambient, shade) = if id == crate::REVOLVE {
let o = crate::revolve_options(p);
Lighting { lights: o.active_lights(), ambient: o.ambient, shade: o.shade }
(o.active_lights(), o.ambient, o.shade)
} else {
let v = super::view_options(p);
Lighting { lights: v.active_lights(), ambient: v.ambient, shade: v.shade }
}
(v.active_lights(), v.ambient, v.shade)
};
let lit = lights.iter().any(|l| l.intensity > 0.0);
let shadows = super::shadow::rendered_options(p, lit).is_some();
Lighting { lights, diffusion: vec![], ambient, shade, shadows, receiver: None }
}
/// The shadow settings a rendered image of a 3D effect with parameters `p` and lights `lighting`
/// draws its shadow plane with; `None` with Shadows off or no light lighting the art.
pub(crate) fn plane_settings(p: &serde_json::Value, lighting: &Lighting) -> Option<vectorcraft_three_d::Shadow> {
super::shadow::rendered_options(p, lighting.lights.iter().any(|l| l.intensity > 0.0))
}
#[cfg(test)]
+534 -25
View File
@@ -24,7 +24,7 @@ fn solid_square(id: &str, color: Color, params: Value) -> Node {
/// The art the canvas draws for `n`: Revolve's, else the other 3D effects'.
fn drawn(n: &Node) -> Node {
crate::revolve_art(n).or_else(|| super::super::solid_art(n)).unwrap_or_else(|| panic!("no art for {n:?}"))
crate::revolve_art_drawn_in(None, n).or_else(|| super::super::solid_art_drawn_in(None, n)).unwrap_or_else(|| panic!("no art for {n:?}"))
}
/// The image objects in `art`.
@@ -183,7 +183,7 @@ fn side_mapped_graphics_draw_the_shaded_faces_and_report_the_fallback() {
"graphics": [{"symbol": "Mark", "face": "side"}], "render": {"mode": "rendered"}
}),
);
let art = super::super::solid_art_in(Some(&doc), &n).unwrap();
let art = super::super::solid_art_drawn_in(Some(&doc), &n).unwrap();
assert!(images(&art).is_empty());
assert!(faces_bounds(&art).is_some());
let mut graphic_drawn = false;
@@ -219,9 +219,8 @@ fn ambient_200_percent_is_brighter_than_100_percent() {
}
}
/// The arms of an extruded U cast shadows across its recess under a light from the right.
#[test]
fn a_concave_solid_casts_a_shadow_on_itself() {
/// An extruded U under a light from the right, with Shadows `shadow`.
fn concave_u(shadow: bool) -> Node {
let mut path = BezPath::new();
path.move_to((100.0, 100.0));
for p in [(125.0, 100.0), (125.0, 175.0), (175.0, 175.0), (175.0, 100.0), (200.0, 100.0), (200.0, 200.0), (100.0, 200.0)] {
@@ -234,36 +233,45 @@ fn a_concave_solid_casts_a_shadow_on_itself() {
super::super::EXTRUDE,
&json!({
"depth": 80, "rotationX": -30, "rotationY": -30, "rotationZ": 0,
"lightRotation": 0, "lightHeight": 25, "lightIntensity": 100, "ambient": 10
"lightRotation": 0, "lightHeight": 25, "lightIntensity": 100, "ambient": 10, "shadow": shadow
}),
)
.unwrap(),
);
let (meshes, lighting) = scene_of(&n);
n
}
/// The most the solids' own shadows darken a pixel's linear red in the image of `n`, against the
/// same scene with no material casting shadows.
fn self_shadow_darkening(n: &Node) -> f32 {
let (meshes, lighting) = scene_of(n);
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)).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 mut unshadowed = shadowed.clone();
for material in &mut unshadowed.materials {
material.casts_shadows = false;
}
let limits = Limits::default();
let draw = |scene: &mut Scene| {
try_shadow_maps(scene, false, &limits).unwrap();
if scene.lights.iter().any(|l| l.shadow >= 0) {
try_shadow_maps(scene, false, &limits).unwrap();
}
try_render_cpu(scene, &limits).unwrap().0
};
let (shadowed, unshadowed) = (draw(&mut shadowed), draw(&mut unshadowed));
let (at, darkening) = shadowed
.data
.iter()
.zip(&unshadowed.data)
.enumerate()
.filter(|(_, (a, b))| a[3] == 1.0 && b[3] == 1.0)
.map(|(i, (a, b))| (i, b[0] - a[0]))
.max_by(|a, b| a.1.total_cmp(&b.1))
.unwrap();
assert!(darkening > 0.05, "pixel ({}, {}): shadow darkens linear red by {darkening}", at % 160, at / 160);
shadowed.data.iter().zip(&unshadowed.data).filter(|(a, b)| a[3] == 1.0 && b[3] == 1.0).map(|(a, b)| b[0] - a[0]).fold(0.0, f32::max)
}
/// With Shadows on, the arms of an extruded U cast shadows across its recess under a light from
/// the right; with Shadows off the solid casts none on itself.
#[test]
fn a_concave_solid_casts_a_shadow_on_itself() {
let on = self_shadow_darkening(&concave_u(true));
assert!(on > 0.05, "Shadows on: the solid's own shadow darkens linear red by {on}");
let off = self_shadow_darkening(&concave_u(false));
assert_eq!(off, 0.0, "Shadows off: the solid shadows itself by {off}");
}
/// Shading off, the surface shows its paint unlit, as the shaded faces do.
@@ -441,7 +449,7 @@ fn check_only_reports_rasterizer_limits_after_measure_succeeds() {
let n = solid_square(super::super::ROTATE, Color::BLACK, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "shade": false}));
let (meshes, lighting) = scene_of(&n);
let settings = RenderSettings { quality: 0, ..MEDIUM };
let measured = measure(&meshes, settings, 72.0, false, &Limits::default()).unwrap();
let measured = measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap();
let triangles = meshes.iter().map(|m| m.mesh.triangles.len() as u64).sum::<u64>();
let vertices = meshes.iter().map(|m| m.mesh.positions.len() as u64).sum::<u64>();
for limit in ["triangles", "vertices", "work"] {
@@ -451,7 +459,7 @@ fn check_only_reports_rasterizer_limits_after_measure_succeeds() {
"vertices" => limits.max_vertices = vertices - 1,
_ => limits.max_work = u64::from(measured.cols) * u64::from(measured.rows),
}
assert!(measure(&meshes, settings, 72.0, false, &limits).is_ok(), "{limit}: image fits");
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);
assert_eq!(checked.as_ref().map_err(String::as_str), Err(TOO_LARGE), "{limit}");
@@ -462,9 +470,11 @@ fn check_only_reports_rasterizer_limits_after_measure_succeeds() {
#[test]
fn check_only_counts_shadow_work_and_lights() {
let n = solid_square(super::super::ROTATE, Color::BLACK, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90}));
let n =
solid_square(super::super::ROTATE, Color::BLACK, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90, "shadow": true}));
let (meshes, lighting) = scene_of(&n);
assert!(!lighting.lights.is_empty());
assert!(lighting.shadows);
let settings = RenderSettings { quality: 0, ..MEDIUM };
for limit in ["lights", "shadow work"] {
let mut limits = Limits::default();
@@ -477,8 +487,13 @@ fn check_only_counts_shadow_work_and_lights() {
unlit.shade = false;
assert!(check(&meshes, &unlit, 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!(render(&meshes, &unshadowed, settings, 72.0, false, &limits).is_ok());
}
assert!(measure(&meshes, 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!(render(&meshes, &lighting, settings, 72.0, false, &limits), Err(TOO_LARGE.into()), "{limit}");
}
@@ -494,9 +509,503 @@ fn check_only_art_reports_overlapping_faces_past_the_work_limit() {
}
let meshes = vec![meshes[0].clone(); 200];
let settings = RenderSettings { quality: 0, ..MEDIUM };
assert!(measure(&meshes, settings, 72.0, false, &Limits::default()).is_ok());
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!(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.
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");
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();
let mut out = vec![];
for (x, y, p) in decoded.enumerate_pixels() {
let (px, py) = (x0 + (f64::from(x) + 0.5) * sx, y0 + (f64::from(y) + 0.5) * sy);
if p[3] > 16 && !solid.inflate(1.0, 1.0).contains(Point::new(px, py)) {
out.push((px.floor() as i64, py.floor() as i64));
}
}
out
}
/// A 100 pt square extruded face-on under two low lights, from the right and from the left, at
/// Intensity `right` and `left` (percent), with Shadows `shadow`, rendered.
fn two_lights(right: f64, left: f64, shadow: bool) -> Node {
solid_square(
super::super::EXTRUDE,
Color::rgb(0.7, 0.7, 0.7),
json!({
"depth": 40, "rotationX": 0, "rotationY": 0, "rotationZ": 0, "shadow": shadow,
"lights": [{"rotation": 0, "height": 30, "intensity": right}, {"rotation": 180, "height": 30, "intensity": left}],
"render": {"mode": "rendered", "quality": "low"}
}),
)
}
/// Rendered with Shadows on, each light casts its own shadow on the shadow plane: two lights from
/// opposite sides darken one region on each side of the solid. With Shadows off neither appears,
/// and a light at Intensity 0 casts none.
#[test]
fn every_light_casts_a_shadow_on_the_plane() {
let center = 150.0;
let sides = |cells: &[(i64, i64)]| {
let left = cells.iter().filter(|c| (c.0 as f64) < center).count();
(left, cells.len() - left)
};
let (left, right) = sides(&shadow_cells(&two_lights(100.0, 100.0, true)));
assert!(left > 50 && right > 50, "two lights: {left} shadow cells on the left, {right} on the right");
let (left, right) = sides(&shadow_cells(&two_lights(100.0, 0.0, true)));
assert!(left > 50, "the light from the right casts {left} cells to the left");
assert_eq!(right, 0, "the light at Intensity 0 casts {right} cells to the right");
let (left, right) = sides(&shadow_cells(&two_lights(0.0, 100.0, true)));
assert!(right > 50 && left == 0, "the light from the left alone: {left} left, {right} right");
assert_eq!(shadow_cells(&two_lights(100.0, 100.0, false)), vec![], "Shadows off");
}
/// 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.
#[test]
fn softness_widens_the_shadow_edge_on_the_plane() {
for (resolution, quality) in [(72.0, "low"), (144.0, "medium")] {
let transition = |softness| {
let n = solid_square(
super::super::EXTRUDE,
Color::rgb(0.7, 0.7, 0.7),
json!({
"depth": 40, "rotationX": 0, "rotationY": 0, "rotationZ": 0,
"shadow": true, "shadowDistance": 50, "lightHeight": 45, "lightRotation": 0,
"lightIntensity": 100, "lightSoftness": softness,
"render": {"mode": "rendered", "quality": quality, "resolution": resolution}
}),
);
let list = images(&drawn(&n));
assert_eq!(list.len(), 1);
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();
let y = ((150.0 - y0) / sy).floor() as u32;
assert!(y < decoded.height());
let alpha: Vec<u8> =
(0..decoded.width()).filter(|x| x0 + (f64::from(*x) + 0.5) * sx < 99.0).map(|x| decoded.get_pixel(x, y)[3]).collect();
assert!(alpha.contains(&0), "the plane includes an unshadowed region");
assert!(alpha.iter().any(|a| *a >= 120), "the plane includes a fully shadowed region");
alpha.iter().filter(|a| **a > 8 && **a < 120).count()
};
let (hard, soft) = (transition(0), transition(100));
assert!(soft > hard + (8.0 * resolution / 72.0) as usize, "{resolution} ppi, {quality}: {hard} hard transition pixels, {soft} soft");
}
}
/// Measuring the selection with Use Preview Bounds builds the vector art of a rendered 3D object
/// and makes no image; drawing it makes one.
#[test]
fn preview_bounds_do_not_rasterize() {
let mut doc = vectorcraft_doc::Document::new(400.0, 400.0);
let layer = doc.layers[0].id;
for (k, id) in FOUR.into_iter().enumerate() {
let mut n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered", "quality": "low"}}));
n.id = NodeId(100 + k as u64);
doc.insert(Some(layer), k, n).unwrap();
}
let ids: Vec<NodeId> = (0..4).map(|k| NodeId(100 + k)).collect();
let before = RASTERIZATIONS.with(|count| count.get());
assert!(crate::preview::bounds_of(&doc, &ids, true).is_some());
assert_eq!(RASTERIZATIONS.with(|count| count.get()), before, "measuring rasterizes");
for id in &ids {
assert_eq!(images(&drawn(doc.node(*id).unwrap())).len(), 1, "{id:?}");
}
assert_eq!(RASTERIZATIONS.with(|count| count.get()), before + 4, "drawing rasterizes once for each object");
}
/// Painted measurements include the image rectangle under opposite lights without rasterizing,
/// while 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);
for id in [super::super::EXTRUDE, crate::REVOLVE] {
let mut n = two_lights(100.0, 100.0, true);
n.appearance.effects[0].id = id.into();
let before = RASTERIZATIONS.with(|count| count.get());
let measured = crate::three_d_bounds_art_in(Some(&doc), &n).unwrap();
let bounds = measured.visual_bounds().unwrap();
let measured_images = images(&measured);
assert_eq!(measured_images.len(), 1, "{id}: measures the rendered image");
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");
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();
bare.appearance.effects[0].params["shadow"] = json!(false);
let bare = crate::three_d_bounds_art_in(Some(&doc), &bare).unwrap().visual_bounds().unwrap();
assert!(bounds.x0 < bare.x0 && bounds.x1 > bare.x1, "{id}: shadows extend on both sides");
let vector = crate::revolve_art_in(Some(&doc), &n).or_else(|| crate::solid_art_in(Some(&doc), &n)).unwrap();
assert!(images(&vector).is_empty(), "{id}: preview keeps vector art");
}
}
/// Drawing the same object again reuses its image; changing its geometry, its material, the
/// resolution or the document's raster resolution makes a new one.
#[test]
fn rendered_images_are_reused_until_an_input_changes() {
let count = || RASTERIZATIONS.with(|count| count.get());
let base = json!({"render": {"mode": "rendered", "quality": "low"}});
let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), base.clone());
let doc = |ppi: f64| {
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
d.raster_effects_ppi = ppi;
d
};
let draw = |d: &vectorcraft_doc::Document, n: &Node| images(&super::super::solid_art_drawn_in(Some(d), n).unwrap()).len();
let start = count();
assert_eq!(draw(&doc(72.0), &n), 1);
assert_eq!(count(), start + 1);
assert_eq!(draw(&doc(72.0), &n), 1);
assert_eq!(count(), start + 1, "a redraw rasterizes again");
let mut moved = Node::path(NodeId(1), square(130.0, 100.0, 100.0), Appearance::default());
moved.appearance = n.appearance.clone();
assert_eq!(draw(&doc(72.0), &moved), 1);
assert_eq!(count(), start + 2, "moving the object reuses the image");
let mut rough = n.clone();
rough.appearance.effects[0].params["material"] = json!({"roughness": 0.9});
assert_eq!(draw(&doc(72.0), &rough), 1);
assert_eq!(count(), start + 3, "a new roughness reuses the image");
let mut fine = n.clone();
fine.appearance.effects[0].params["render"] = json!({"mode": "rendered", "quality": "low", "resolution": 144});
assert_eq!(draw(&doc(72.0), &fine), 1);
assert_eq!(count(), start + 4, "a new resolution reuses the image");
assert_eq!(draw(&doc(150.0), &n), 1);
assert_eq!(count(), start + 5, "a new document resolution reuses the image");
}
/// A group whose 3D effect holds a member with a blending mode or an opacity mask draws the shaded
/// faces, which apply them; without either, the group draws the image.
#[test]
fn masked_or_blended_members_draw_the_shaded_faces() {
for id in [super::super::EXTRUDE, super::super::INFLATE, super::super::ROTATE] {
let group = |member: Node| {
let mut g = Node::group(NodeId(10), vec![std::sync::Arc::new(member)]);
g.appearance.effects.push(crate::new_effect(id, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap());
g
};
let member =
|| 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));
let art = drawn(&group(member()));
assert_eq!(images(&art).len(), 1, "{id}: plain member");
let mut blended = member();
blended.blend = vectorcraft_doc::color::BlendMode::Multiply;
let art = drawn(&group(blended));
assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: blended member");
let mut masked = member();
masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(member(), false)));
let art = drawn(&group(masked));
assert!(images(&art).is_empty() && faces_bounds(&art).is_some(), "{id}: masked member");
}
}
/// Revolve on a group, or on a fill or stroke, draws the shaded faces and reports why.
#[test]
fn revolve_on_a_group_or_a_paint_reports_objects_only() {
let doc = vectorcraft_doc::Document::new(400.0, 400.0);
let rendered = || crate::new_effect(crate::REVOLVE, &json!({"render": {"mode": "rendered", "quality": "low"}})).unwrap();
let member = || 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));
let mut group = Node::group(NodeId(10), vec![std::sync::Arc::new(member())]);
group.appearance.effects.push(rendered());
assert_eq!(crate::rendered_warning(&doc, &group).as_deref(), Some(OBJECTS_ONLY), "group");
assert!(images(&drawn(&group)).is_empty(), "group");
let mut fill = member();
fill.appearance.items[0].effects_mut().push(rendered());
assert_eq!(crate::rendered_warning(&doc, &fill).as_deref(), Some(OBJECTS_ONLY), "fill");
assert!(images(&drawn(&fill)).is_empty(), "fill");
assert_eq!(crate::rendered_warning(&doc, &solid_square(crate::REVOLVE, Color::BLACK, json!({"render": {"mode": "rendered"}}))), None);
}
/// Baking a rendered object's appearance, as an envelope with Distort Appearance does, keeps its
/// image, for Revolve and the other 3D effects.
#[test]
fn baked_appearance_keeps_the_rendered_image() {
for id in FOUR {
let n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"render": {"mode": "rendered", "quality": "low"}}));
let baked = crate::bake_appearance(None, &n).unwrap_or_else(|| panic!("{id}: nothing baked"));
assert_eq!(images(&baked).len(), 1, "{id}: the baked appearance has no image");
}
}
/// The page point the clip matrix `m` takes mesh point `p` to over image `rect`: the point goes
/// into the scene's frame (y down), through `m`, and from the image's normalized coordinates onto
/// the page.
fn clipped(m: [[f32; 4]; 4], rect: Rect, p: [f64; 3]) -> Point {
let v = [p[0], -p[1], p[2], 1.0];
let row = |r: usize| (0..4).map(|c| f64::from(m[r][c]) * v[c]).sum::<f64>();
let w = row(3);
let (x, y) = (row(0) / w, row(1) / w);
Point::new(rect.x0 + (x + 1.0) / 2.0 * rect.width(), rect.y0 + (1.0 - y) / 2.0 * rect.height())
}
/// The scene's clip matrix places every mesh point where the effect's projection draws it, within
/// 1e-3 pt, for each of the four effects without perspective and at 60 and 160 degrees.
#[test]
fn the_clip_matrix_places_every_mesh_point_where_the_projection_does() {
for id in FOUR {
for perspective in [0.0, 60.0, 160.0] {
let n = solid_square(id, Color::rgb(0.2, 0.5, 0.8), json!({"perspectiveAngle": perspective}));
let (meshes, lighting) = scene_of(&n);
let m = measure(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap_or_else(|e| panic!("{id} {perspective}: {e}"));
let mut worst = 0.0f64;
for p in meshes.iter().flat_map(|s| &s.mesh.positions) {
worst = worst.max(clipped(m.clip, m.rect, *p).distance(m.projection.project(*p)));
}
assert!(worst < 1e-3, "{id} at {perspective} degrees: a mesh point lands {worst} pt from its projected point");
}
}
}
/// A square facing the viewer covers every pixel more than one pixel inside its outline and none
/// more than one pixel outside it.
#[test]
fn the_image_covers_the_area_the_faces_cover() {
let n = solid_square(super::super::ROTATE, Color::rgb(0.2, 0.5, 0.8), json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0}));
let (meshes, lighting) = scene_of(&n);
let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap();
let face = faces_bounds(&super::super::solid_art_in(None, &n).unwrap()).unwrap();
let (mut inside, mut outside) = (0, 0);
for y in 0..image.rows {
for x in 0..image.cols {
let center = Point::new(image.rect.x0 + f64::from(x) + 0.5, image.rect.y0 + f64::from(y) + 0.5);
let a = pixel(&image, x, y)[3];
if face.inset(-1.0).contains(center) {
inside += 1;
assert_eq!(a, 255, "pixel {x}, {y} inside the face");
} else if !face.inset(1.0).contains(center) {
outside += 1;
assert_eq!(a, 0, "pixel {x}, {y} outside the face");
}
}
}
assert!(inside > 9000, "{inside} pixels inside");
assert!(outside + inside > 0);
}
/// The depth buffer decides which surface shows: with the mesh's triangles in reverse order, every
/// pixel inside the turned solid shows the same surface.
#[test]
fn the_nearer_surface_shows_whatever_order_the_triangles_come_in() {
let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({"rotationX": 40, "rotationY": 50, "rotationZ": 0, "shade": true}));
let (meshes, lighting) = scene_of(&n);
let mut reversed = meshes.clone();
for m in &mut reversed {
m.mesh.triangles.reverse();
}
let a = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap();
let b = render(&reversed, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap();
assert_eq!((a.cols, a.rows), (b.cols, b.rows));
let differ = a
.pixels
.chunks(4)
.zip(b.pixels.chunks(4))
.filter(|(p, q)| p[3] == 255 && q[3] == 255 && p.iter().zip(q.iter()).any(|(x, y)| x.abs_diff(*y) > 2))
.count();
let covered = a.pixels.chunks(4).filter(|p| p[3] == 255).count();
assert!(covered > 5000, "{covered}");
assert!(differ * 100 <= covered, "{differ} of {covered} covered pixels change with the triangle order");
}
/// Cook-Torrance with GGX, Smith-Schlick `k = (r + 1)² / 8` and Schlick's Fresnel, times N·L, for
/// linear base color `base`, `metallic` and `rough` along unit normal `n`, view `v` and light `l`.
fn cook_torrance(base: f64, metallic: f64, rough: f64, n: [f64; 3], v: [f64; 3], l: [f64; 3]) -> f64 {
let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
let h = [v[0] + l[0], v[1] + l[1], v[2] + l[2]];
let len = dot(h, h).sqrt();
let h = h.map(|c| c / len);
let (n_l, n_v, n_h, v_h) = (dot(n, l), dot(n, v), dot(n, h), dot(v, h));
let a2 = (rough * rough).powi(2);
let d = a2 / (std::f64::consts::PI * (n_h * n_h * (a2 - 1.0) + 1.0).powi(2));
let k = (rough + 1.0).powi(2) / 8.0;
let g = (n_v / (n_v * (1.0 - k) + k)) * (n_l / (n_l * (1.0 - k) + k));
let f0 = 0.04 * (1.0 - metallic) + base * metallic;
let f = f0 + (1.0 - f0) * (1.0 - v_h).powi(5);
let spec = d * g / (4.0 * n_v * n_l);
let kd = (1.0 - f) * (1.0 - metallic);
(kd * base / std::f64::consts::PI + f * spec) * n_l * std::f64::consts::PI
}
/// A face toward the viewer under one light at 45 degrees, Ambient 0, Roughness 0.5, Metallic 0
/// and 1: its center equals the Cook-Torrance formula times the light's color, within 1e-3 linear.
#[test]
fn a_lit_face_matches_the_shading_formula() {
for metallic in [0.0, 1.0] {
let n = solid_square(
super::super::ROTATE,
Color::rgb(0.5, 0.5, 0.5),
json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 45, "lightIntensity": 100, "ambient": 0,
"material": {"roughness": 0.5, "metallic": metallic}}),
);
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();
assert_eq!(scene.lights.len(), 1);
let light = &scene.lights[0];
let target = craft_raster3d::try_render(&scene, &Limits::default()).unwrap();
let got = target.color[(m.rows / 2 * m.cols + m.cols / 2) as usize];
let l = light.dir.map(|c| -f64::from(c));
let base = f64::from(srgb_to_linear(0.5));
let want = cook_torrance(base, metallic, 0.5, [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], l) * f64::from(light.color[0]);
assert!((f64::from(got[0]) - want).abs() < 1e-3, "metallic {metallic}: {} against {want}", got[0]);
assert_eq!(got[3], 1.0);
}
}
/// With the default light, Ambient 0, the default material and Softness 0, a face square to the
/// light has the color of the same shaded face within 3 levels.
#[test]
fn a_face_square_to_the_light_has_the_shaded_faces_color() {
let n = solid_square(
super::super::ROTATE,
Color::rgb(0.2, 0.5, 0.8),
json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90, "ambient": 0, "lightSoftness": 0}),
);
let mut face = None;
super::super::solid_art_in(None, &n).unwrap().walk(&mut |c| {
if c.path_data().is_some()
&& let Some(Paint::Solid { color, .. }) = c.appearance.items.iter().map(|i| i.paint()).find(|p| matches!(p, Paint::Solid { .. }))
{
face.get_or_insert(color.to_rgba8(1.0));
}
});
let face = face.unwrap();
let (meshes, lighting) = scene_of(&n);
let image = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).unwrap();
let center = pixel(&image, image.cols / 2, image.rows / 2);
for c in 0..3 {
assert!(center[c].abs_diff(face[c]) <= 3, "{center:?} against the shaded face's {face:?}");
}
}
/// The specular term of the shaded faces (the separable Smith visibility of glTF 2.0) and of the
/// rendered image (Smith-Schlick with `k = (r + 1)² / 8`) differ by at most 0.002 of the light over
/// Roughness 0.05 to 1 and light angles of 0 to 80 degrees from the normal, at a view along it.
#[test]
fn the_two_specular_terms_differ_within_a_bound() {
let mut worst = (0.0f64, 0.0, 0.0);
for r in (1..=20).map(|i| f64::from(i) * 0.05) {
for degrees in (0..=8).map(|i| f64::from(i) * 10.0) {
let t = degrees.to_radians();
let (n_l, n_v) = (t.cos(), 1.0);
let h_len = (2.0 + 2.0 * n_l).sqrt();
let n_h = (1.0 + n_l) / h_len;
let a2 = (r * r).powi(2);
let d = a2 / (std::f64::consts::PI * (n_h * n_h * (a2 - 1.0) + 1.0).powi(2));
let k = (r + 1.0).powi(2) / 8.0;
let schlick = (n_v / (n_v * (1.0 - k) + k)) * (n_l / (n_l * (1.0 - k) + k)) / (4.0 * n_v * n_l);
let one = |x: f64| x + (a2 + (1.0 - a2) * x * x).sqrt();
let separable = 1.0 / (one(n_l) * one(n_v));
// F0 0.04, the dielectric default, at the half vector.
let v_h = h_len / 2.0;
let f = 0.04 + 0.96 * (1.0 - v_h).powi(5);
let diff = (d * f * (schlick - separable) * n_l * std::f64::consts::PI).abs();
if diff > worst.0 {
worst = (diff, r, degrees);
}
}
}
println!("largest specular difference {:.4} at roughness {:.2}, {} degrees", worst.0, worst.1, worst.2);
assert!(worst.0 <= 0.002, "{worst:?}");
}
/// An image past the pixel limit at one sample a pixel draws the shaded faces and reports why; the
/// largest mesh the effects make fits the rasterizer's triangle limit.
#[test]
fn an_image_past_the_limits_draws_the_shaded_faces() {
assert!(super::super::MAX_MESH_TRIANGLES as u64 <= Limits::default().max_triangles);
let doc = vectorcraft_doc::Document::new(400.0, 400.0);
let mut n = Node::path(NodeId(1), square(0.0, 0.0, 3000.0), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0));
n.appearance
.effects
.push(crate::new_effect(super::super::EXTRUDE, &json!({"render": {"mode": "rendered", "quality": "low", "resolution": 2400}})).unwrap());
assert_eq!(crate::rendered_warning(&doc, &n).as_deref(), Some(TOO_LARGE));
let art = drawn(&n);
assert!(images(&art).is_empty() && faces_bounds(&art).is_some());
}
/// Rendering a 40 × 80 pt Extrude at 300 ppi, Medium (2 × 2 samples), fits a work limit of twice
/// the samples its triangles' bounding boxes cover plus one for each triangle, and a limit of half
/// those samples is refused.
#[test]
fn a_medium_render_stays_within_its_work_bound() {
let mut b = BezPath::new();
b.move_to((0.0, 0.0));
b.line_to((40.0, 0.0));
b.line_to((40.0, 80.0));
b.line_to((0.0, 80.0));
b.close_path();
let mut n = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0));
n.appearance.effects.push(crate::new_effect(super::super::EXTRUDE, &json!({"render": {"mode": "rendered", "resolution": 300}})).unwrap());
let (meshes, lighting) = scene_of(&n);
let settings = RenderSettings { quality: 1, resolution: Some(300.0), white: false };
let m = measure(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap();
assert_eq!(m.samples, 2);
let samples = u64::from(m.cols) * u64::from(m.rows) * 4;
// Each triangle's bounding box in raster samples, clipped to the raster.
let per_point = f64::from(m.cols * 2) / m.rect.width();
let mut boxes = 0u64;
let mut triangles = 0u64;
for s in &meshes {
for t in &s.mesh.triangles {
let at: Vec<Point> = t.iter().map(|&i| m.projection.project(s.mesh.positions[i as usize])).collect();
let span = |f: fn(&Point) -> f64, origin: f64, size: f64| {
let lo = at.iter().map(f).fold(f64::INFINITY, f64::min);
let hi = at.iter().map(f).fold(f64::NEG_INFINITY, f64::max);
(((hi - origin) * per_point).ceil().min(size) - ((lo - origin) * per_point).floor().max(0.0) + 1.0).max(0.0) as u64
};
boxes += span(|p| p.x, m.rect.x0, f64::from(m.cols * 2)) * span(|p| p.y, m.rect.y0, f64::from(m.rows * 2));
triangles += 1;
}
}
let mut limits = Limits::default();
limits.max_work = 2 * boxes + triangles;
assert!(render(&meshes, &lighting, settings, 72.0, false, &limits).is_ok(), "{samples} samples, {boxes} box samples, {triangles} triangles");
limits.max_work = boxes / 2;
assert_eq!(render(&meshes, &lighting, settings, 72.0, false, &limits), Err(TOO_LARGE.to_string()), "the work is counted");
println!("work bound: {samples} image samples, {boxes} box samples, {triangles} triangles");
}
/// Edge values: art with no area makes no image, a mesh with zero-area triangles renders, lights
/// with values that are not numbers are refused, resolutions 1 and 2400 render, and a solid behind
/// the eye at Perspective 160 is refused.
#[test]
fn edge_values_render_or_are_refused() {
let mut empty = Node::path(NodeId(1), PathData::from_bezpath(&BezPath::new()), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
empty.appearance.effects.push(crate::new_effect(super::super::EXTRUDE, &json!({"render": {"mode": "rendered"}})).unwrap());
assert!(super::super::solid_art_drawn_in(None, &empty).is_none_or(|a| images(&a).is_empty()));
let n = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({}));
let (mut meshes, mut lighting) = scene_of(&n);
let first = meshes[0].mesh.triangles[0];
meshes[0].mesh.triangles.push([first[0], first[0], first[1]]);
assert!(render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default()).is_ok(), "zero-area triangle");
for resolution in [1.0, 2400.0] {
let settings = RenderSettings { quality: 0, resolution: Some(resolution), white: false };
let image = render(&meshes, &lighting, settings, 72.0, false, &Limits::default()).unwrap();
assert!(image.cols >= 1 && image.rows >= 1, "{resolution} ppi");
}
lighting.lights[0].intensity = f64::NAN;
lighting.lights[0].rotation = f64::INFINITY;
let bad = render(&meshes, &lighting, MEDIUM, 72.0, false, &Limits::default());
assert!(matches!(bad.as_ref().map_err(String::as_str), Ok(_) | Err(TOO_LARGE)), "{bad:?}");
let behind = solid_square(super::super::EXTRUDE, Color::rgb(0.2, 0.5, 0.8), json!({"perspectiveAngle": 160}));
let (mut meshes, lighting) = scene_of(&behind);
let eye = meshes[0].projection.and_then(|p| p.eye).unwrap();
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()));
}
+14 -2
View File
@@ -25,12 +25,24 @@ pub(crate) fn options(p: &Value) -> Option<Shadow> {
let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied());
let intensity = first.map_or_else(|| num(p, "lightIntensity", 80.0), |l| l.intensity);
let lit = flag(p, "shade", true) && intensity > 0.0;
(lit && flag(p, "shadow", false)).then(|| Shadow {
(lit && flag(p, "shadow", false)).then(|| settings(p, first))
}
/// The shadow a rendered image of `p` draws, in which every light casts one: as [`options`], but on
/// when any light lights the art (`lit`), not only the first.
pub(crate) fn rendered_options(p: &Value, lit: bool) -> Option<Shadow> {
let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied());
(lit && flag(p, "shade", true) && flag(p, "shadow", false)).then(|| settings(p, first))
}
/// The plane settings of `p`, with the softness of light `first` (the single light's without one).
fn settings(p: &Value, first: Option<vectorcraft_three_d::Light>) -> Shadow {
Shadow {
position: ShadowPosition::parse(text(p, "shadowPosition", "behind")).unwrap_or_default(),
distance: num(p, "shadowDistance", 0.0) / 100.0,
bounds: num(p, "shadowBounds", 100.0) / 100.0,
softness: first.map_or_else(|| num(p, "lightSoftness", 0.0) / 100.0, |l| l.softness),
})
}
}
/// Check the shadow settings in `p`: an error for a value out of its range or of the wrong kind.
+1 -1
View File
@@ -356,7 +356,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, fx, &shapes, false, &mut None).unwrap();
let (drawn, _) = art_for(None, &n, fx, &shapes, Build::Vector, &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));
+134
View File
@@ -204,3 +204,137 @@ fn rendered_warning_is_in_effect_command_results() {
let plain = run(&mut s, "effect.setParams", json!({"index": 0, "item": null, "params": {"render": {"mode": "rendered", "quality": "low"}}}));
assert!(plain.get("warning").is_none());
}
/// The color space of each color image (not a soft mask) in PDF `bytes`, in order.
fn image_spaces(bytes: &[u8]) -> Vec<String> {
let text = String::from_utf8_lossy(bytes);
let mut out = vec![];
for (at, _) in text.match_indices("/Subtype/Image") {
let start = text[..at].rfind(" obj").unwrap_or(0);
let end = text[at..].find("stream").map_or(text.len(), |e| at + e);
let dict = &text[start..end];
let Some(cs) = dict.find("/ColorSpace") else { continue };
let name = dict[cs + "/ColorSpace".len()..].trim_start_matches(['[', ' ', '/']);
let space: String = name.chars().take_while(|c| c.is_ascii_alphanumeric()).collect();
if space != "DeviceGray" {
out.push(space);
}
}
out
}
/// In a CMYK document, PDF export writes a rendered 3D object as it writes a raster effect: one
/// image in the color space a drop shadow's image takes, kept in RGB by default and converted to
/// CMYK by Press Quality.
#[test]
fn a_rendered_3d_object_in_a_cmyk_pdf_is_written_as_raster_effects_are() {
let spaces = |effect: &str, params: Value, preset: Option<&str>| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300, "colorMode": "cmyk"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap();
run(&mut s, "paint.setStroke", json!({"none": true}));
run(&mut s, "paint.setFill", json!({"color": "#338ad6"}));
run(&mut s, "effect.apply", json!({"effect": effect, "item": null, "params": params}));
let v = s.execute("document.exportPdf", &preset.map_or(json!({}), |name| json!({"preset": name}))).unwrap();
image_spaces(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap())
};
let rendered = json!({"render": {"mode": "rendered", "quality": "low"}});
let shadow = json!({"x": 6.0, "y": 6.0, "blur": 3.0, "opacity": 75.0});
for preset in [None, Some("Press Quality")] {
let three_d = spaces("threeD.extrude", rendered.clone(), preset);
let dropped = spaces("stylize.dropShadow", shadow.clone(), preset);
assert_eq!(three_d.len(), 1, "{preset:?}: one image of the rendered object: {three_d:?}");
assert_eq!(dropped.len(), 1, "{preset:?}: {dropped:?}");
assert_eq!(three_d, dropped, "{preset:?}: the rendered image takes the drop shadow's color space");
}
assert_eq!(spaces("threeD.extrude", rendered, Some("Press Quality")), vec!["DeviceCMYK".to_string()]);
}
/// A selected 100 pt square filled blue with no stroke, rendered by Extrude at Low quality, and
/// `after` (effect, params) applied after it.
fn rendered_square(after: &[(&str, Value)]) -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap();
run(&mut s, "paint.setStroke", json!({"none": true}));
run(&mut s, "paint.setFill", json!({"color": "#338ad6"}));
run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": {"render": {"mode": "rendered", "quality": "low"}}}));
for (effect, params) in after {
run(&mut s, "effect.apply", json!({"effect": effect, "item": null, "params": params}));
}
s
}
/// The `/Width` of each color image (not a soft mask) in PDF `bytes`.
fn image_widths(bytes: &[u8]) -> Vec<u32> {
let text = String::from_utf8_lossy(bytes);
let mut out = vec![];
for (at, _) in text.match_indices("/Subtype/Image") {
let start = text[..at].rfind(" obj").unwrap_or(0);
let end = text[at..].find("stream").map_or(text.len(), |e| at + e);
let dict = &text[start..end];
if dict.contains("/DeviceGray") {
continue;
}
if let Some(w) = dict.find("/Width") {
out.push(dict[w + "/Width".len()..].trim_start().chars().take_while(char::is_ascii_digit).collect::<String>().parse().unwrap());
}
}
out
}
/// PDF and SVG export write one image for a rendered 3D object, and Expand Appearance leaves one
/// embedded image of the same size in pixels that covers the object.
#[test]
fn export_and_expand_write_one_image_of_a_rendered_3d_object() {
let mut s = rendered_square(&[]);
let pdf = s.execute("document.exportPdf", &json!({})).unwrap();
let widths = image_widths(&vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().unwrap()).unwrap());
assert_eq!(widths.len(), 1, "{widths:?}");
let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap();
let svg = String::from_utf8(vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).unwrap();
assert_eq!(svg.matches("<image").count(), 1, "{svg}");
run(&mut s, "effect.expandAppearance", json!({}));
let mut found = vec![];
for l in &s.doc().unwrap().doc.layers {
l.walk(&mut |n| {
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
found.push((**im).clone());
}
});
}
assert_eq!(found.len(), 1, "{found:?}");
let im = &found[0];
assert!(s.doc().unwrap().doc.images.contains_key(&im.key), "the image is embedded");
assert_eq!(im.width, widths[0], "the PDF's image and the expanded image have the same pixels");
let c = im.xf.as_coeffs();
let (x0, x1) = (c[4], c[4] + f64::from(im.width) * c[0]);
assert!(x0 <= 100.0 + 1e-6 && x1 >= 200.0 - 1e-6, "the image spans {x0} to {x1}");
}
/// The page bounds, in whole points, of the pixels the canvas covers in session `s`.
fn covered(s: &Session) -> (Vec<u8>, [u32; 4]) {
let img =
vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, vectorcraft_geom::Rect::new(0.0, 0.0, 300.0, 300.0), 1.0, false);
let mut b = [u32::MAX, u32::MAX, 0, 0];
for (i, p) in img.pixels.chunks(4).enumerate() {
if p[3] > 8 {
let (x, y) = (i as u32 % img.width, i as u32 / img.width);
b = [b[0].min(x), b[1].min(y), b[2].max(x), b[3].max(y)];
}
}
(img.pixels, b)
}
/// Effects after a rendered 3D effect apply to its image: Gaussian Blur spreads it past its edges,
/// Transform moves it, and Roughen leaves it as it is.
#[test]
fn effects_after_a_rendered_3d_effect_apply_to_its_image() {
let (plain, at) = covered(&rendered_square(&[]));
let (_, blurred) = covered(&rendered_square(&[("blur.gaussian", json!({"radius": 5.0}))]));
assert!(blurred[0] + 2 <= at[0] && blurred[2] >= at[2] + 2, "blurred {blurred:?} against {at:?}");
let (_, moved) = covered(&rendered_square(&[("distort.transform", json!({"moveH": 50.0}))]));
assert_eq!([moved[0], moved[2]], [at[0] + 50, at[2] + 50], "moved {moved:?} against {at:?}");
let (rough, _) = covered(&rendered_square(&[("distort.roughen", json!({"size": 5.0}))]));
assert!(rough == plain, "Roughen changes the rendered image");
}
+1 -1
View File
@@ -804,7 +804,7 @@ fn three_d_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Option<Rect>> {
return None;
}
let doc = Some(symbols.document());
let art = effects::revolve_art_in(doc, n).or_else(|| effects::solid_art_in(doc, n))?;
let art = effects::three_d_bounds_art_in(doc, n)?;
Some(three_d_art_bounds(symbols, &art))
}
+1 -1
View File
@@ -715,7 +715,7 @@ impl Renderer {
let art = match effects::crop_marks_art(a)
.or_else(|| crate::addons::halftone::art(doc, a))
.or_else(|| {
let art = effects::revolve_art_in(Some(doc), a).or_else(|| effects::solid_art_in(Some(doc), a));
let art = effects::revolve_art_drawn_in(Some(doc), a).or_else(|| effects::solid_art_drawn_in(Some(doc), a));
self.stats.three_d_built += usize::from(art.is_some());
three_d |= art.is_some();
art
+41
View File
@@ -9,6 +9,47 @@ use super::{DRAG_PIXEL_BUDGET, Drawn, PIXEL_BUDGET, drag_scale, filter_region, f
use crate::tests_fontchange::{fonts_steady, with_fonts_unchanged};
use crate::{RenderOptions, Rendered, Renderer};
/// Rasterize and culling include the complete rendered image under lights from opposite sides.
#[test]
fn rendered_three_d_painted_bounds_hold_both_shadows() {
let d = Document::new(400.0, 400.0);
for id in [vectorcraft_effects::EXTRUDE, vectorcraft_effects::REVOLVE] {
let mut n = Node::path(
vectorcraft_doc::NodeId(100),
shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
);
n.appearance.effects.push(
vectorcraft_effects::new_effect(
id,
&json!({
"depth": 40, "rotationX": 0, "rotationY": 0, "rotationZ": 0, "shadow": true,
"lights": [{"rotation": 0, "height": 30, "intensity": 100}, {"rotation": 180, "height": 30, "intensity": 100}],
"render": {"mode": "rendered", "quality": "low"}
}),
)
.unwrap(),
);
let rasterize = crate::drawn_bounds(&d, &n).unwrap();
let culling = crate::painted_bounds(&d, &n).unwrap();
let art = vectorcraft_effects::revolve_art_drawn_in(Some(&d), &n).or_else(|| vectorcraft_effects::solid_art_drawn_in(Some(&d), &n)).unwrap();
let mut images = 0;
art.walk(&mut |piece| {
if matches!(piece.kind, vectorcraft_doc::NodeKind::Image(_)) {
images += 1;
let image = piece.visual_bounds().unwrap();
for bounds in [rasterize, culling] {
assert!(
bounds.x0 <= image.x0 && bounds.y0 <= image.y0 && bounds.x1 >= image.x1 && bounds.y1 >= image.y1,
"{id}: {bounds:?} holds {image:?}"
);
}
}
});
assert_eq!(images, 1, "{id}: draws the rendered image");
}
}
/// The hash renderers compare to redraw art linked to swatches changes with a global swatch's
/// color and spot flag and with the Spot Colors option.
#[test]
+79 -7
View File
@@ -61,6 +61,13 @@ impl Default for Shadow {
}
impl Shadow {
/// The blur radius in points for a solid whose largest size is `size`.
fn blur(self, size: f64) -> f64 {
let s = self.sanitized();
let blur = (s.softness * size * (BLUR_NEAR + BLUR_PER_DISTANCE * s.distance)).min(MAX_SHADOW_BLUR);
if blur.is_finite() { blur } else { 0.0 }
}
fn sanitized(self) -> Self {
Self {
distance: finite(self.distance, 0.0, 0.0, 1.0),
@@ -149,6 +156,20 @@ impl ShadowPlane {
}
}
/// Where a shadow's plane lies ([`ShadowCaster::placement`]): its unit normal toward the object and
/// two unit axes along it, its level along the normal, the foot of the object's center on it, half
/// the side of the square it ends at, and the object's largest size.
#[derive(Clone, Copy, Debug)]
struct Placement {
n: V3,
u: V3,
w: V3,
level: f64,
foot: V3,
half: f64,
size: f64,
}
/// The faces of one object's solids, gathered to cast one shadow. The solids of one object share
/// their bounds and view, so they share a projection: the first solid's is kept. Each solid added
/// returns the range of its faces, so that the shadow of some of them can be drawn on the plane
@@ -261,6 +282,19 @@ impl ShadowCaster {
let p = self.projection?;
let light = p.light()?;
let s = shadow.sanitized();
let Placement { n, u, w, level, foot, half, size } = self.placement(s, faces)?;
let reach = n.dot(light);
if !reach.is_finite() || reach < MIN_LIGHT {
return None;
}
let blur = s.blur(size);
Some(ShadowPlane { projection: p, light, reach, n, u, w, level, foot, half, blur })
}
/// Where the plane of sanitized settings `s` lies for the faces in the ranges `faces`, whatever
/// lights it: `None` when there are none.
fn placement(&self, s: Shadow, faces: &[Range<usize>]) -> Option<Placement> {
let p = self.projection?;
let corners = || self.within(faces).flat_map(|face| face.contours.iter().flatten());
let first = *corners().next()?;
let (lo, hi) = corners()
@@ -274,17 +308,55 @@ impl ShadowCaster {
(r(V3(0.0, -1.0, 0.0)), r(V3(1.0, 0.0, 0.0)), r(V3(0.0, 0.0, 1.0)))
}
};
let reach = n.dot(light);
if !reach.is_finite() || reach < MIN_LIGHT {
return None;
}
// The plane: every corner at least `distance` × size in front of it.
let level = corners().map(|v| n.dot(*v)).fold(f64::INFINITY, f64::min) - s.distance * size;
let centre = V3((lo.0 + hi.0) / 2.0, (lo.1 + hi.1) / 2.0, (lo.2 + hi.2) / 2.0);
let foot = add(centre, scale(n, level - n.dot(centre)));
let blur = (s.softness * size * (BLUR_NEAR + BLUR_PER_DISTANCE * s.distance)).min(MAX_SHADOW_BLUR);
let blur = if blur.is_finite() { blur } else { 0.0 };
Some(ShadowPlane { projection: p, light, reach, n, u, w, level, foot, half: 2.0 * s.bounds * size, blur })
Some(Placement { n, u, w, level, foot, half: 2.0 * s.bounds * size, size })
}
/// The blur radius in points for `shadow` and the faces in the ranges `faces`, regardless of
/// the light direction; `None` when there are no faces.
pub fn shadow_blur(&self, shadow: Shadow, faces: &[Range<usize>]) -> Option<f64> {
Some(shadow.blur(self.placement(shadow.sanitized(), faces)?.size))
}
/// The rectangle of the plane `shadow` falls on that holds the shadows the faces in the ranges
/// `faces` cast toward each of the lights in `toward` (directions toward a light, in view space,
/// with y down), widened on each side by the blur radius plus `margin` times the faces' largest
/// size and cut where the plane ends: its four corners in view space, in order round it. Every light counts, not only the
/// first. `None` when there are no faces, when no light reaches the plane, or when no shadow falls
/// within it.
pub fn receiver(&self, shadow: Shadow, faces: &[Range<usize>], toward: &[[f64; 3]], margin: f64) -> Option<[[f64; 3]; 4]> {
let Placement { n, u, w, level, foot, half, size } = self.placement(shadow.sanitized(), faces)?;
let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
for t in toward {
let light = V3(t[0], t[1], t[2]).unit();
let reach = n.dot(light);
if !reach.is_finite() || reach < MIN_LIGHT {
continue;
}
for v in self.within(faces).flat_map(|face| face.contours.iter().flatten()) {
let d = add(*v, scale(light, -(n.dot(*v) - level) / reach)).sub(foot);
let q = [u.dot(d), w.dot(d)];
for k in 0..2 {
lo[k] = lo[k].min(q[k]);
hi[k] = hi[k].max(q[k]);
}
}
}
let m = shadow.blur(size) + if margin.is_finite() { margin.max(0.0) * size } else { 0.0 };
let [a0, b0] = [0, 1].map(|k| (lo[k] - m).clamp(-half, half));
let [a1, b1] = [0, 1].map(|k| (hi[k] + m).clamp(-half, half));
if !(a1 > a0 && b1 > b0) {
return None;
}
let at = |a: f64, b: f64| {
let p = add(foot, add(scale(u, a), scale(w, b)));
[p.0, p.1, p.2]
};
let corners = [at(a0, b0), at(a1, b0), at(a1, b1), at(a0, b1)];
corners.iter().flatten().all(|v| v.is_finite()).then_some(corners)
}
/// The shadow the faces in the ranges `faces` cast on `plane`, on the page, filled with the
+142
View File
@@ -1624,3 +1624,145 @@ fn rendered_warning_reaches_the_status_bar() {
super::set_render(&mut app, "rendered", Some("low"));
assert_eq!(app.ui.status, vectorcraft_effects::rendered::OPAQUE_ONLY);
}
/// The panel with the window's dialogs run and their held answers applied, as in the app's frame.
fn show_with_dialogs(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
app.ui_ctx = Some(ui.ctx().clone());
show(app, ui);
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| host.run(ui));
}
crate::dialogs::host::pump(app, ui.ctx());
}
/// Two squares with Extrude & Bevel, `a` with the default render settings and `b` rendered at
/// High quality, 150 ppi, on white, selected `b` first. Returns the app and their ids.
fn two_renders() -> (VectorcraftApp, u64, u64) {
let mut app = app();
let a = app.session.active().unwrap().selection.objects[0].0;
set_type(&mut app, "extrude").unwrap();
let b = app.run("shape.rectangle", json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap();
app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null})).unwrap();
let render = json!({"mode": "rendered", "quality": "high", "resolution": 150, "background": "white"});
app.run("effect.setParams", json!({"index": 0, "item": null, "params": {"render": render}})).unwrap();
app.run("select.set", json!({"ids": [b, a]})).unwrap();
assert_eq!(app.session.active().unwrap().selection.objects[0].0, b);
(app, a, b)
}
/// Object `id`'s 3D effect's render settings.
fn render_of(app: &VectorcraftApp, id: u64) -> Value {
app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0].params["render"].clone()
}
/// Render Settings lists Wireframe, Rendered, the three qualities and Raster Settings…. A mode or
/// quality the selected objects hold differently shows no check; choosing one sets it on every
/// object in one undo step, and choosing what every object already holds records none.
#[test]
fn render_settings_menu_shows_a_mixed_selection_unchecked() {
use craft::behavior::Mixed;
use crate::tests::panel_harness::Panel;
let (app, a, b) = two_renders();
let mut panel = Panel::new(app, show_with_dialogs);
panel.frame();
panel.click("Render Settings");
for name in ["Wireframe", "Rendered", "Low Quality", "Medium Quality", "High Quality", "Raster Settings…"] {
assert!(panel.shows(name), "the menu lists {name}");
}
for name in ["Wireframe", "Rendered", "High Quality"] {
assert_ne!(panel.toggled(name), Some(Mixed::Same(true)), "a mixed selection checks {name}");
}
let history = undo_len(&panel.app());
panel.click("High Quality");
assert_eq!(undo_len(&panel.app()), history + 1, "the choice is one undo step for the selection");
for id in [a, b] {
let render = render_of(&panel.app(), id);
assert_eq!((render["mode"].as_str(), render["quality"].as_str()), (Some("rendered"), Some("high")), "{id}");
}
panel.click("Render Settings");
assert_eq!(panel.toggled("Rendered"), Some(Mixed::Same(true)));
assert_eq!(panel.toggled("High Quality"), Some(Mixed::Same(true)));
panel.click("High Quality");
assert_eq!(undo_len(&panel.app()), history + 1, "choosing what every object holds records no undo step");
}
/// Raster Settings… opens blank on the settings the selected objects hold differently, and OK
/// leaves those as each object has them. OK sets the edited settings on every object in one undo
/// step, and records none when every object already holds them.
#[test]
fn raster_settings_sets_resolution_and_background() {
use craft::ui::dialog::dialog_id;
use craft::ui::patterns::form_dialogs::HostedParamDialog;
use crate::tests::panel_harness::Panel;
let (app, a, b) = two_renders();
let mut panel = Panel::new(app, show_with_dialogs);
panel.frame();
let (id, ctx) = (dialog_id(super::raster::KIND), panel.ctx().clone());
let is_open = |panel: &Panel| panel.app().dialogs().is_some_and(|d| d.with(|host| host.get_mut_by_id::<HostedParamDialog>(id).is_some()));
let set = |panel: &Panel, key: &str, value: Value| panel.app().dialogs().unwrap().with(|host| host.set_json_field(&ctx, id, key, value)).unwrap();
let ok = |panel: &mut Panel| {
panel.app().dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id));
panel.frame();
panel.frame();
};
let open = |panel: &mut Panel| {
panel.click("Render Settings");
panel.click("Raster Settings…");
panel.frame();
assert!(is_open(panel));
};
open(&mut panel);
for name in ["Use Document Raster Effects Resolution", "Transparent", "White"] {
assert!(panel.shows(name), "the dialog shows {name}");
}
// One object takes the document's resolution and the other 150 ppi: the switch is blank, the
// resolution field shows the one resolution given, and neither background is picked.
use craft::behavior::Mixed;
let switch = panel.toggled("Use Document Raster Effects Resolution");
assert!(!matches!(switch, Some(Mixed::Same(_))), "the switch shows {switch:?} for a mixed selection");
for name in ["Transparent", "White"] {
assert_ne!(panel.toggled(name), Some(Mixed::Same(true)), "{name} is shown picked for a mixed selection");
}
let role = craft::ui::contract::Role::SPIN_BUTTON;
assert_eq!(panel.value_role("Resolution (ppi)", role).as_deref(), Some("150"));
let history = undo_len(&panel.app());
let renders = |panel: &Panel| {
let app = panel.app();
(render_of(&app, a), render_of(&app, b))
};
let before = renders(&panel);
ok(&mut panel);
assert!(!is_open(&panel));
assert_eq!(undo_len(&panel.app()), history, "OK with every field blank changes nothing");
assert_eq!(renders(&panel), before);
open(&mut panel);
set(&panel, "background", json!("white"));
ok(&mut panel);
assert_eq!(undo_len(&panel.app()), history + 1, "OK is one undo step for the selection");
assert_eq!(render_of(&panel.app(), a).get("resolution"), None, "a blank resolution stays as the object has it");
assert_eq!(render_of(&panel.app(), b)["resolution"], 150);
for id in [a, b] {
assert_eq!(render_of(&panel.app(), id)["background"], "white", "{id}");
}
open(&mut panel);
set(&panel, "document", json!(false));
set(&panel, "resolution", json!(300));
ok(&mut panel);
assert_eq!(undo_len(&panel.app()), history + 2);
for id in [a, b] {
assert_eq!(render_of(&panel.app(), id)["resolution"].as_f64(), Some(300.0), "{id}");
}
open(&mut panel);
ok(&mut panel);
assert_eq!(undo_len(&panel.app()), history + 2, "OK with what every object holds records no undo step");
open(&mut panel);
set(&panel, "document", json!(true));
ok(&mut panel);
for id in [a, b] {
assert_eq!(render_of(&panel.app(), id)["resolution"], Value::Null, "{id}");
}
}
+50 -16
View File
@@ -33,6 +33,7 @@ use crate::dialogs::three_d_materials as materials;
pub(crate) mod handles;
pub(crate) use handles::FrameKey;
pub(crate) mod raster;
/// The panel's id (`window.panel`).
pub const ID: &str = "threeD";
@@ -359,7 +360,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
return;
};
if takes_render(&t.effect) {
render_settings(app, ui, &t);
render_settings(app, ui);
}
let (params, fields) = rows(app, &t);
let out = ParamRows::new(tl!("3D and Materials"), &params, Bind::given(fields.clone())).show(ui);
@@ -499,29 +500,62 @@ fn render_of(t: &Target) -> Map<String, Value> {
p.get(vectorcraft_effects::RENDER).and_then(Value::as_object).cloned().unwrap_or_default()
}
/// The Render Settings menu at the top of the panel: Wireframe, checked while the first selected
/// object's 3D effect draws the edges of its faces; Rendered, checked while it draws an image of
/// the lit solid; and the rendered image's Low, Medium and High quality. Choosing Wireframe or
/// Rendered turns that mode on or off, and choosing a quality renders at it ([`set_render`]), for
/// every selected object's 3D effect.
fn render_settings(app: &mut VectorcraftApp, ui: &mut Ui, t: &Target) {
let render = render_of(t);
let mode = render.get("mode").and_then(Value::as_str).unwrap_or("shaded");
let quality = render.get("quality").and_then(Value::as_str).unwrap_or("medium");
let rendered = mode == "rendered";
/// Render setting `key` in `render`, or the value it takes when it is left out.
fn render_value(render: &Map<String, Value>, key: &str) -> Value {
render.get(key).cloned().unwrap_or_else(|| match key {
"mode" => json!("shaded"),
"quality" => json!("medium"),
"background" => json!("transparent"),
_ => Value::Null,
})
}
/// The render settings of each selected object whose 3D effect takes them.
fn selected_renders(app: &VectorcraftApp) -> Vec<Map<String, Value>> {
let Some(st) = app.session.active() else { return vec![] };
st.selection.objects.iter().filter_map(|id| find(st.doc.node(*id)?)).filter(|t| takes_render(&t.effect)).map(|t| render_of(&t)).collect()
}
/// The value render setting `key` has in every one of `renders`; `None` when they hold it
/// differently, or with none.
fn shared_render(renders: &[Map<String, Value>], key: &str) -> Option<Value> {
let mut values = renders.iter().map(|r| render_value(r, key));
let first = values.next()?;
values.all(|v| v == first).then_some(first)
}
/// The Render Settings menu at the top of the panel: Wireframe, checked while every selected
/// object's 3D effect draws the edges of its faces; Rendered, checked while every one draws an
/// image of the lit solid; the rendered image's Low, Medium and High quality, checked while every
/// one renders at it; and Raster Settings… ([`raster`]). A setting the selected objects hold
/// differently shows no check. Choosing Wireframe or Rendered turns that mode on, or off when it
/// is checked, and choosing a quality renders at it ([`set_render`]), for every selected object's
/// 3D effect.
fn render_settings(app: &mut VectorcraftApp, ui: &mut Ui) {
let renders = selected_renders(app);
let (mode, quality) = (shared_render(&renders, "mode"), shared_render(&renders, "quality"));
let is = |v: &Option<Value>, s: &str| v.as_ref().and_then(Value::as_str) == Some(s);
let (wireframe, rendered) = (is(&mode, "wireframe"), is(&mode, "rendered"));
let opener = Button::new(tl!("Render Settings")).show(ui);
let entries = [
Entry::new(0usize, tl!("Wireframe")).checked(mode == "wireframe"),
Entry::new(0usize, tl!("Wireframe")).checked(wireframe),
Entry::new(1, tl!("Rendered")).checked(rendered),
Entry::new(2, tl!("Low Quality")).checked(rendered && quality == "low"),
Entry::new(3, tl!("Medium Quality")).checked(rendered && quality == "medium"),
Entry::new(4, tl!("High Quality")).checked(rendered && quality == "high"),
Entry::new(2, tl!("Low Quality")).checked(rendered && is(&quality, "low")),
Entry::new(3, tl!("Medium Quality")).checked(rendered && is(&quality, "medium")),
Entry::new(4, tl!("High Quality")).checked(rendered && is(&quality, "high")),
Entry::new(5, tl!("Raster Settings…")),
];
let picked = Menu::new(tl!("Render Settings")).values().opened_by(&opener, Trigger::Press).pick(ui, &entries).picked;
match picked {
Some(0) => set_render(app, if mode == "wireframe" { "shaded" } else { "wireframe" }, None),
Some(0) => set_render(app, if wireframe { "shaded" } else { "wireframe" }, None),
Some(1) => set_render(app, if rendered { "shaded" } else { "rendered" }, None),
Some(k @ 2..=4) => set_render(app, "rendered", vectorcraft_effects::RENDER_QUALITIES.get(k - 2).copied()),
Some(5) => {
finish(app);
if let Err(e) = raster::open(app) {
app.ui.status = e;
}
}
_ => {}
}
}
+151
View File
@@ -0,0 +1,151 @@
//! Render Settings › Raster Settings…: the resolution and background of the rendered image of each
//! selected object's 3D effect.
//!
//! Fields: `document` (Use Document Raster Effects Resolution), `resolution` (1 to 2400 ppi) and
//! `background` (`transparent` or `white`). A field the selected objects hold differently opens
//! blank, and OK leaves it as each object has it. OK runs one `effect.setParams` over the
//! selection, one undo step, which records none when every object already holds what it sets.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use serde_json::{Map, Value, json};
use super::{Live, finish, selected_renders, send, shared_render};
use crate::VectorcraftApp;
use crate::dialogs::host::open_held;
/// The dialog's key.
pub(crate) const KIND: &str = "threeDRasterSettings";
/// The message OK shows when Use Document Raster Effects Resolution is off and no resolution is
/// given.
const NO_RESOLUTION: &str = "Type a resolution from 1 to 2400 ppi";
/// Opens Raster Settings on the selected objects' render settings.
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<(), String> {
let renders = selected_renders(app);
if renders.is_empty() {
return Err("select an object with a 3D effect".into());
}
let ppi = app.session.active().map_or(72.0, |st| st.doc.raster_ppi());
let resolutions: Vec<Option<f64>> = renders.iter().map(|r| r.get("resolution").and_then(Value::as_f64)).collect();
let mut fields = DialogFields::new();
let document = if resolutions.iter().all(Option::is_none) {
Some(true)
} else if resolutions.iter().all(Option::is_some) {
Some(false)
} else {
None
};
match document {
Some(d) => fields.set("document", FieldValue::Bool(d)),
None => fields.set_mixed("document"),
}
let mut given = resolutions.iter().flatten();
let opening = match given.next() {
None => Some(ppi),
Some(first) if given.all(|r| r == first) => Some(*first),
Some(_) => None,
};
match opening {
Some(r) => fields.set("resolution", FieldValue::Number(r)),
None => fields.set_mixed("resolution"),
}
match shared_render(&renders, "background").as_ref().and_then(Value::as_str) {
Some(b) => fields.set("background", FieldValue::Text(b.into())),
None => fields.set_mixed("background"),
}
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let dialog = HostedParamDialog::new(&ctx, KIND, fields, |fields| dialog().values(Bind::bound(fields)));
let opened = Opened { document, resolution: opening };
open_held(app, dialog, move |app, answer| ok(app, answer, opened)).ok_or("no window")?;
Ok(())
}
/// The dialog over its rows.
fn dialog<'a>() -> ParamDialog<'a> {
let backgrounds = vec![("transparent".to_owned(), tl!("Transparent").into()), ("white".to_owned(), tl!("White").into())];
let params = vec![
Param::new("document", tl!("Use Document Raster Effects Resolution"), ParamKind::bool(true)),
Param::number("resolution", tl!("Resolution (ppi):"), 72.0, 1.0, 0).bounds(Some(1.0), Some(2400.0)).enabled_when("document", false),
Param::new("background", tl!("Background:"), ParamKind::radio(backgrounds, None)),
];
ParamDialog::new(KIND, tl!("Raster Settings"), params)
}
/// The values the dialog opened on; `None` for a field that opened blank.
#[derive(Clone, Copy, Debug)]
struct Opened {
document: Option<bool>,
resolution: Option<f64>,
}
/// The render settings the answer `f` sets, given the values the dialog opened on: a field left
/// blank sets nothing, and a resolution sets only when it was changed or the document's resolution
/// was switched off.
fn edited(f: &DialogFields, opened: Opened) -> Result<Map<String, Value>, String> {
let mut render = Map::new();
let resolution = f.number("resolution");
match f.bool("document") {
Some(true) => {
render.insert("resolution".into(), Value::Null);
}
// Every object already has its own resolution: a blank one leaves each as it is.
Some(false) if opened.document == Some(false) && resolution.is_none() => {}
Some(false) => {
render.insert("resolution".into(), json!(resolution.ok_or(NO_RESOLUTION)?));
}
None => {
if let Some(r) = resolution.filter(|r| Some(*r) != opened.resolution) {
render.insert("resolution".into(), json!(r));
}
}
}
if let Some(background) = f.text("background") {
render.insert("background".into(), json!(background));
}
Ok(render)
}
/// OK: sets the edited render settings on every selected object's 3D effect, one undo step.
fn ok(app: &mut VectorcraftApp, answer: &ParamResult, opened: Opened) -> Result<(), String> {
let render = edited(&answer.fields, opened)?;
if render.is_empty() {
return Ok(());
}
finish(app);
let mut changed = Map::new();
changed.insert(vectorcraft_effects::RENDER.into(), Value::Object(render));
send(app, changed, Live::Released);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn fields(set: &[(&str, FieldValue)]) -> DialogFields {
let mut f = DialogFields::new();
for (key, value) in set {
f.set(*key, value.clone());
}
f
}
/// With the document's resolution switched off and no resolution given, OK keeps the dialog
/// open with the reason; when every object already had its own resolutions, which differ, a
/// blank resolution keeps them and Background alone is set. With the switch blank, an unchanged
/// resolution sets nothing and a changed one sets it.
#[test]
fn ok_needs_a_resolution_and_keeps_blank_fields() {
let on = Opened { document: Some(true), resolution: Some(72.0) };
assert_eq!(edited(&fields(&[("document", FieldValue::Bool(false))]), on), Err(NO_RESOLUTION.to_string()));
let own = Opened { document: Some(false), resolution: None };
let kept = edited(&fields(&[("document", FieldValue::Bool(false)), ("background", FieldValue::Text("white".into()))]), own).unwrap();
assert_eq!(kept, Map::from_iter([("background".to_string(), json!("white"))]));
let mixed = Opened { document: None, resolution: Some(150.0) };
assert_eq!(edited(&fields(&[("resolution", FieldValue::Number(150.0))]), mixed), Ok(Map::new()));
let changed = edited(&fields(&[("resolution", FieldValue::Number(200.0))]), mixed).unwrap();
assert_eq!(changed.get("resolution").and_then(Value::as_f64), Some(200.0));
}
}
+2 -1
View File
@@ -6453,7 +6453,8 @@ Geometry effects after the 3D effect reshape the drawn edges. Expand as Wirefram
joins the edges, so with such an effect its paths can differ from the drawn ones. The mode is saved in the native file, SVG and PDF exports
draw the edges, and `effect.expandAppearance` keeps them as paths. Past 1,000,000 edges the source path is drawn, as
it is for a solid past its limits. In rendered mode the effect draws its solid as one image with a depth buffer, lit
by every light, with the shadows each light casts on the solid, over the effect's shadow. `render` then also takes
by every light. With `shadow` on, every light with an intensity above 0 casts shadows on the solid and on the
effect's shadow plane, drawn in the image; with it off, none does. `render` then also takes
`quality` (`"low"`, `"medium"` or `"high"`: 1, 2 × 2 or 3 × 3 samples a pixel, default `"medium"`, VectorCraft's own
values), `resolution` (`null` for Document Raster Effects Settings › Resolution, the default, or 1..2400 ppi) and
`background` (`"transparent"`, the default, or `"white"`). A quality whose samples would pass 16,777,216 pixels
+14 -4
View File
@@ -59,10 +59,20 @@ pages describe it.
page describes Render Settings customizing rendering quality. Choosing a quality also turns Rendered on, and each
choice is one undo step for every selected Extrude & Bevel, Revolve, Inflate and Rotate (`effect.setParams` with
`render`). The image is drawn with a depth buffer, so solids that pass through each other show where they meet;
every light lights it with its color and intensity, with the Roughness and Metallic of the material, and each
light casts shadows on the solid with shadow maps. The effect's shadow ([Shadows](#shadows)) is drawn behind the
image. Low takes one sample a pixel, Medium 2 × 2 and High 3 × 3 (VectorCraft's own values), at the effect's
`resolution` or, without one, at Document Raster Effects Settings › Resolution. A quality whose samples would pass
every light lights it with its color and intensity, with the Roughness and Metallic of the material. With
[Shadows](#shadows) on, every light with an Intensity above 0 casts shadows, on the solid itself and on the plane
the effect's Position, Distance and Shadow Bounds place, where they show in black at 50% (VectorCraft's own value);
the public
[Create 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-vector-artwork.html)
page describes the shadows of all the lights appearing in a full render, while the preview shows one. With Shadows
off, no light casts a shadow. Low takes one sample a pixel, Medium 2 × 2 and High 3 × 3 (VectorCraft's own
values), at the effect's `resolution` or, without one, at Document Raster Effects Settings › Resolution.
**Render Settings › Raster Settings…** sets Use Document Raster Effects Resolution, Resolution (1 to 2400 ppi) and
Background (Transparent or White) for every selected object in one undo step, as the Render 3D vector artwork page
describes Raster Settings changing the resolution and background. A setting the selected objects hold differently
opens blank and is left as each object has it; Rendered and the qualities show unchecked for such a selection.
The selection box, Use Preview Bounds, Align, hit testing and snapping measure the shaded faces, and the image is
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