1use std::sync::Arc;
2
3use cranpose_ui::text::{AnnotatedString, TextStyle, drawn_text_style};
4use cranpose_ui_graphics::{
5 ArcGeometry, BlendMode, Brush, Color, ColorFilter, CornerRadii, DrawPrimitive, GraphicsLayer,
6 ImageBitmap, ImageSampling, LineGeometry, Point, Rect, RoundedCornerShape, ShadowPrimitive,
7 Stroke, TextPrimitive, Trapezoid, arc_band, inflate_rect,
8};
9
10use crate::{
11 graph::quad_bounds,
12 layer_transform::{
13 apply_layer_affine_to_point, apply_layer_affine_to_rect, apply_layer_to_quad,
14 apply_layer_to_rect, layer_uniform_scale,
15 },
16 style_shared::{
17 ResolvedBrush, apply_layer_to_brush, apply_layer_to_color, compose_color_filters,
18 resolve_layer_brush, scale_corner_radii,
19 },
20};
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum PrimitiveClipSpace {
25 Local,
27 LayerTransformed,
29}
30
31pub struct ShapeDrawParams {
33 pub rect: Rect,
35 pub local_rect: Rect,
37 pub quad: [[f32; 2]; 4],
39 pub brush: ResolvedBrush,
43 pub shape: Option<RoundedCornerShape>,
45 pub stroke: Option<Stroke>,
50 pub arc: Option<ArcGeometry>,
53 pub line: Option<LineGeometry>,
56 pub trapezoid: Option<Trapezoid>,
60 pub clip: Option<Rect>,
62 pub blend_mode: BlendMode,
64 pub motion_context_animated: bool,
67}
68
69fn stroked_draw_rect(
70 local_rect: Rect,
71 stroke: Option<Stroke>,
72 layer_bounds: Rect,
73 layer: &GraphicsLayer,
74) -> Option<(Rect, Option<Stroke>)> {
75 let draw_rect = local_rect.translate(layer_bounds.x, layer_bounds.y);
76 let Some(stroke) = stroke else {
77 return Some((draw_rect, None));
78 };
79 if !stroke.is_visible() {
80 return None;
81 }
82 let outset = stroke.half_width();
83 Some((
84 inflate_rect(draw_rect, outset),
85 Some(stroke.scaled(layer_uniform_scale(layer))),
86 ))
87}
88
89pub struct ImageDrawParams {
91 pub rect: Rect,
93 pub local_rect: Rect,
95 pub quad: [[f32; 2]; 4],
97 pub image: ImageBitmap,
99 pub alpha: f32,
101 pub color_filter: Option<ColorFilter>,
103 pub sampling: ImageSampling,
105 pub clip: Option<Rect>,
107 pub src_rect: Option<Rect>,
109 pub blend_mode: BlendMode,
111 pub motion_context_animated: bool,
114}
115
116pub struct TextDrawParams {
123 pub rect: Rect,
126 pub text: AnnotatedString,
128 pub layout: cranpose_text::TextLayout,
130 pub color: Color,
132 pub text_style: Arc<TextStyle>,
134 pub style_hash: u64,
136 pub font_size: f32,
138 pub scale: f32,
140 pub clip: Option<Rect>,
142}
143
144pub trait DrawPrimitiveSink {
146 fn push_shape(&mut self, params: ShapeDrawParams);
148
149 fn push_image(&mut self, params: ImageDrawParams);
151
152 fn push_shadow(
154 &mut self,
155 shadow_primitive: &ShadowPrimitive,
156 layer_bounds: Rect,
157 layer: &GraphicsLayer,
158 clip: Option<Rect>,
159 );
160
161 fn push_text(&mut self, params: TextDrawParams) {
165 let _ = params;
166 }
167}
168
169pub fn draw_shape_params_for_primitive(
171 primitive: &DrawPrimitive,
172 layer_bounds: Rect,
173 layer: &GraphicsLayer,
174 clip: Option<Rect>,
175 blend_mode: BlendMode,
176) -> Option<ShapeDrawParams> {
177 struct SingleShapeSink {
178 shape: Option<ShapeDrawParams>,
179 }
180
181 impl DrawPrimitiveSink for SingleShapeSink {
182 fn push_shape(&mut self, params: ShapeDrawParams) {
183 if self.shape.is_none() {
184 self.shape = Some(params);
185 }
186 }
187
188 fn push_image(&mut self, _params: ImageDrawParams) {}
189
190 fn push_shadow(
191 &mut self,
192 _shadow_primitive: &ShadowPrimitive,
193 _layer_bounds: Rect,
194 _layer: &GraphicsLayer,
195 _clip: Option<Rect>,
196 ) {
197 }
198 }
199
200 let mut sink = SingleShapeSink { shape: None };
201 emit_draw_primitive(
202 primitive,
203 layer_bounds,
204 layer,
205 clip,
206 &mut sink,
207 Some(blend_mode),
208 false,
209 );
210 sink.shape
211}
212
213pub fn resolve_clip(parent_clip: Option<Rect>, requested_clip: Option<Rect>) -> Option<Rect> {
218 match (parent_clip, requested_clip) {
219 (Some(parent), Some(current)) => Some(parent.intersect(current).unwrap_or(Rect::EMPTY)),
220 (Some(parent), None) => Some(parent),
221 (None, Some(current)) => Some(current),
222 (None, None) => None,
223 }
224}
225
226pub fn resolve_primitive_clip(
230 local_clip: Option<Rect>,
231 layer_bounds: Rect,
232 layer: &GraphicsLayer,
233 parent_clip: Option<Rect>,
234 clip_space: PrimitiveClipSpace,
235) -> Option<Rect> {
236 let Some(local_clip) = local_clip else {
237 return parent_clip;
238 };
239 let clip_rect = Rect {
240 x: layer_bounds.x + local_clip.x,
241 y: layer_bounds.y + local_clip.y,
242 width: local_clip.width,
243 height: local_clip.height,
244 };
245 let requested_clip = match clip_space {
246 PrimitiveClipSpace::Local => clip_rect,
247 PrimitiveClipSpace::LayerTransformed => apply_layer_to_rect(clip_rect, layer_bounds, layer),
248 };
249 resolve_clip(parent_clip, Some(requested_clip))
250}
251
252struct ShapePlacement<'a> {
255 layer_bounds: Rect,
256 layer: &'a GraphicsLayer,
257 clip: Option<Rect>,
258 blend_mode: BlendMode,
259 motion_context_animated: bool,
260}
261
262#[derive(Clone, Copy)]
264enum ShapeGeometry {
265 Rect,
266 Rounded(RoundedCornerShape),
267 Arc(ArcGeometry),
268 Line(LineGeometry),
269 Trapezoid(Trapezoid),
270}
271
272impl ShapePlacement<'_> {
273 fn fill(
277 &self,
278 draw_rect: Rect,
279 brush: &Brush,
280 geometry: ShapeGeometry,
281 stroke: Option<Stroke>,
282 ) -> ShapeDrawParams {
283 let quad = apply_layer_to_quad(draw_rect, self.layer_bounds, self.layer);
284 let mut params = ShapeDrawParams {
285 rect: quad_bounds(quad),
286 local_rect: apply_layer_affine_to_rect(draw_rect, self.layer_bounds, self.layer),
287 quad,
288 brush: resolve_layer_brush(brush, self.layer),
289 shape: None,
290 stroke,
291 arc: None,
292 line: None,
293 trapezoid: None,
294 clip: self.clip,
295 blend_mode: self.blend_mode,
296 motion_context_animated: self.motion_context_animated,
297 };
298 match geometry {
299 ShapeGeometry::Rect => {}
300 ShapeGeometry::Rounded(shape) => params.shape = Some(shape),
301 ShapeGeometry::Arc(arc) => params.arc = Some(arc),
302 ShapeGeometry::Line(line) => params.line = Some(line),
303 ShapeGeometry::Trapezoid(trapezoid) => params.trapezoid = Some(trapezoid),
304 }
305 params
306 }
307
308 fn translate(&self, rect: Rect) -> Rect {
309 rect.translate(self.layer_bounds.x, self.layer_bounds.y)
310 }
311
312 fn place(&self, point: Point) -> Point {
313 apply_layer_affine_to_point(
314 Point::new(point.x + self.layer_bounds.x, point.y + self.layer_bounds.y),
315 self.layer_bounds,
316 self.layer,
317 )
318 }
319}
320
321fn rect_shape_params(
322 local_rect: Rect,
323 brush: &Brush,
324 stroke: Option<Stroke>,
325 placement: &ShapePlacement,
326) -> Option<ShapeDrawParams> {
327 let (draw_rect, stroke) =
328 stroked_draw_rect(local_rect, stroke, placement.layer_bounds, placement.layer)?;
329 Some(placement.fill(draw_rect, brush, ShapeGeometry::Rect, stroke))
330}
331
332fn round_rect_shape_params(
333 local_rect: Rect,
334 brush: &Brush,
335 radii: CornerRadii,
336 stroke: Option<Stroke>,
337 placement: &ShapePlacement,
338) -> Option<ShapeDrawParams> {
339 let (draw_rect, stroke) =
340 stroked_draw_rect(local_rect, stroke, placement.layer_bounds, placement.layer)?;
341 let radii = scale_corner_radii(radii, layer_uniform_scale(placement.layer));
342 let shape = ShapeGeometry::Rounded(RoundedCornerShape::with_radii(radii));
343 Some(placement.fill(draw_rect, brush, shape, stroke))
344}
345
346fn arc_shape_params(
348 local_rect: Rect,
349 brush: &Brush,
350 arc: ArcGeometry,
351 placement: &ShapePlacement,
352) -> Option<ShapeDrawParams> {
353 if arc.is_degenerate() {
354 return None;
355 }
356 let scale = layer_uniform_scale(placement.layer);
357 let arc = ShapeGeometry::Arc(arc.scaled_about(placement.place(arc.center), scale));
358 Some(placement.fill(placement.translate(local_rect), brush, arc, None))
359}
360
361fn line_shape_params(
364 brush: &Brush,
365 start: Point,
366 end: Point,
367 stroke: Stroke,
368 placement: &ShapePlacement,
369) -> Option<ShapeDrawParams> {
370 let line = LineGeometry::new(start, end, stroke);
371 if line.is_degenerate() {
372 return None;
373 }
374 let scale = layer_uniform_scale(placement.layer);
375 let draw_rect = placement.translate(line.bounds());
376 let line =
377 ShapeGeometry::Line(line.placed(placement.place(start), placement.place(end), scale));
378 Some(placement.fill(draw_rect, brush, line, None))
379}
380
381fn trapezoid_shape_params(
384 brush_rect: Rect,
385 brush: &Brush,
386 trapezoid: Trapezoid,
387 placement: &ShapePlacement,
388) -> Option<ShapeDrawParams> {
389 if trapezoid.right <= trapezoid.left {
390 return None;
391 }
392 let place = |x: f32, y: f32| placement.place(Point::new(x, y));
393 let [top_left, top_right, bottom_left, bottom_right] = [
394 place(trapezoid.left, trapezoid.top[0]),
395 place(trapezoid.right, trapezoid.top[1]),
396 place(trapezoid.left, trapezoid.bottom[0]),
397 place(trapezoid.right, trapezoid.bottom[1]),
398 ];
399 let placed = ShapeGeometry::Trapezoid(Trapezoid {
400 left: top_left.x,
401 right: top_right.x,
402 top: [top_left.y, top_right.y],
403 bottom: [bottom_left.y, bottom_right.y],
404 ..trapezoid
405 });
406 Some(placement.fill(placement.translate(brush_rect), brush, placed, None))
407}
408
409pub fn emit_draw_primitive<S: DrawPrimitiveSink>(
414 primitive: &DrawPrimitive,
415 layer_bounds: Rect,
416 layer: &GraphicsLayer,
417 clip: Option<Rect>,
418 sink: &mut S,
419 blend_mode: Option<BlendMode>,
420 motion_context_animated: bool,
421) {
422 let placement = ShapePlacement {
423 layer_bounds,
424 layer,
425 clip,
426 blend_mode: blend_mode.unwrap_or(BlendMode::SrcOver),
427 motion_context_animated,
428 };
429 match primitive {
430 DrawPrimitive::Content | DrawPrimitive::Group(_) => {}
431 DrawPrimitive::Blend {
432 primitive,
433 blend_mode: nested,
434 } => emit_draw_primitive(
435 primitive,
436 layer_bounds,
437 layer,
438 clip,
439 sink,
440 blend_mode.or(Some(*nested)),
441 motion_context_animated,
442 ),
443 DrawPrimitive::Rect {
444 rect,
445 brush,
446 stroke,
447 } => {
448 if let Some(params) = rect_shape_params(*rect, brush, *stroke, &placement) {
449 sink.push_shape(params);
450 }
451 }
452 DrawPrimitive::RoundRect {
453 rect,
454 brush,
455 radii,
456 stroke,
457 } => {
458 if let Some(params) = round_rect_shape_params(*rect, brush, *radii, *stroke, &placement)
459 {
460 sink.push_shape(params);
461 }
462 }
463 DrawPrimitive::Arc {
464 rect,
465 brush,
466 center,
467 radius,
468 start_angle,
469 sweep_angle,
470 stroke,
471 inner_radius,
472 } => {
473 let (band_inner, band_outer, cap) = arc_band(*radius, *inner_radius, *stroke);
474 let arc = ArcGeometry::new(
475 *center,
476 band_inner,
477 band_outer,
478 *start_angle,
479 *sweep_angle,
480 cap,
481 );
482 if let Some(params) = arc_shape_params(*rect, brush, arc, &placement) {
483 sink.push_shape(params);
484 }
485 }
486 DrawPrimitive::Line {
487 brush,
488 start,
489 end,
490 stroke,
491 ..
492 } => {
493 if let Some(params) = line_shape_params(brush, *start, *end, *stroke, &placement) {
494 sink.push_shape(params);
495 }
496 }
497 DrawPrimitive::Trapezoid {
498 rect,
499 brush,
500 trapezoid,
501 } => {
502 if let Some(params) = trapezoid_shape_params(*rect, brush, *trapezoid, &placement) {
503 sink.push_shape(params);
504 }
505 }
506 DrawPrimitive::Image {
507 rect: local_rect,
508 image,
509 alpha,
510 color_filter,
511 sampling,
512 src_rect,
513 } => {
514 let draw_rect = local_rect.translate(layer_bounds.x, layer_bounds.y);
515 let local_rect = apply_layer_affine_to_rect(draw_rect, layer_bounds, layer);
516 let quad = apply_layer_to_quad(draw_rect, layer_bounds, layer);
517 sink.push_image(ImageDrawParams {
518 rect: quad_bounds(quad),
519 local_rect,
520 quad,
521 image: image.clone(),
522 alpha: (alpha * layer.alpha).clamp(0.0, 1.0),
523 color_filter: compose_color_filters(
524 color_filter.as_ref(),
525 layer.color_filter.as_ref(),
526 ),
527 sampling: *sampling,
528 clip,
529 src_rect: *src_rect,
530 blend_mode: blend_mode.unwrap_or(BlendMode::SrcOver),
531 motion_context_animated,
532 });
533 }
534 DrawPrimitive::Text(text) => {
535 if let Some(params) = text_draw_params((**text).clone(), layer_bounds, layer, clip) {
536 sink.push_text(params);
537 }
538 }
539 DrawPrimitive::Shadow(shadow_primitive) => {
540 sink.push_shadow(shadow_primitive, layer_bounds, layer, clip);
541 }
542 }
543}
544
545fn text_draw_params(
546 text: TextPrimitive,
547 layer_bounds: Rect,
548 layer: &GraphicsLayer,
549 clip: Option<Rect>,
550) -> Option<TextDrawParams> {
551 if text.text.is_empty() {
552 return None;
553 }
554 let layout = cranpose_text::TextLayout::clone(
556 &*text
557 .layout
558 .as_ref()?
559 .downcast::<cranpose_text::TextLayout>()?,
560 );
561 let draw_rect = text.rect.translate(layer_bounds.x, layer_bounds.y);
562 let rect = apply_layer_to_rect(draw_rect, layer_bounds, layer);
563 if !(rect.width > 0.0 && rect.height > 0.0) {
564 return None;
565 }
566 let scale = layer_uniform_scale(layer);
567 if !scale.is_finite() || scale <= 0.0 {
568 return None;
569 }
570 let (mut text_style, mut style_hash) = drawn_text_style(&text.style);
571 let color = match text.brush {
574 Brush::Solid(color) => apply_layer_to_color(color, layer),
575 gradient => {
576 let gradient = apply_layer_to_brush(gradient, layer);
577 let first = gradient
578 .colors()
579 .first()
580 .copied()
581 .unwrap_or(Color::TRANSPARENT);
582 let style = Arc::make_mut(&mut text_style);
583 style.span_style.brush = Some(gradient);
584 style_hash = style.render_hash();
585 first
586 }
587 };
588 if !text_style
589 .span_style
590 .brush
591 .as_ref()
592 .map_or(color.3 > 0.0, Brush::paints)
593 {
594 return None;
595 }
596
597 Some(TextDrawParams {
598 rect,
599 text: cranpose_ui::text::shared_plain_annotated_string(text.text.as_ref()),
600 layout,
601 color,
602 text_style,
603 style_hash,
604 font_size: text.style.resolved_font_size(),
605 scale,
606 clip,
607 })
608}
609
610#[cfg(test)]
611#[path = "tests/primitive_emit_tests.rs"]
612mod tests;