0
Fork 0
mirror of https://github.com/penpot/penpot.git synced 2025-01-21 06:02:32 -05:00

Merge pull request #5444 from penpot/ladybenko-9505-refactor-shapes

♻️ Refactor shapes and render code
This commit is contained in:
Alejandro 2024-12-11 07:10:18 +01:00 committed by GitHub
commit 777a4c8414
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 357 additions and 216 deletions

View file

@ -109,7 +109,7 @@ pub unsafe extern "C" fn set_shape_kind_circle() {
let state = unsafe { STATE.as_mut() }.expect("got an invalid state pointer");
if let Some(shape) = state.current_shape() {
shape.kind = Kind::Circle(math::Rect::new_empty());
shape.set_kind(Kind::Circle(math::Rect::new_empty()));
}
}
@ -118,7 +118,7 @@ pub unsafe extern "C" fn set_shape_kind_rect() {
let state = unsafe { STATE.as_mut() }.expect("got an invalid state pointer");
if let Some(shape) = state.current_shape() {
shape.kind = Kind::Rect(math::Rect::new_empty());
shape.set_kind(Kind::Rect(math::Rect::new_empty()));
}
}
@ -127,7 +127,7 @@ pub unsafe extern "C" fn set_shape_kind_path() {
let state = unsafe { STATE.as_mut() }.expect("got an invalid state pointer");
if let Some(shape) = state.current_shape() {
let p = Path::try_from(Vec::new()).unwrap();
shape.kind = Kind::Path(p);
shape.set_kind(Kind::Path(p));
}
}
@ -143,7 +143,7 @@ pub extern "C" fn set_shape_selrect(left: f32, top: f32, right: f32, bottom: f32
pub unsafe extern "C" fn set_shape_clip_content(clip_content: bool) {
let state = unsafe { STATE.as_mut() }.expect("got an invalid state pointer");
if let Some(shape) = state.current_shape() {
shape.clip_content = clip_content;
shape.set_clip(clip_content);
}
}
@ -151,7 +151,7 @@ pub unsafe extern "C" fn set_shape_clip_content(clip_content: bool) {
pub unsafe extern "C" fn set_shape_rotation(rotation: f32) {
let state = unsafe { STATE.as_mut() }.expect("got an invalid state pointer");
if let Some(shape) = state.current_shape() {
shape.rotation = rotation;
shape.set_rotation(rotation);
}
}
@ -159,12 +159,7 @@ pub unsafe extern "C" fn set_shape_rotation(rotation: f32) {
pub extern "C" fn set_shape_transform(a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) {
let state = unsafe { STATE.as_mut() }.expect("got an invalid state pointer");
if let Some(shape) = state.current_shape() {
shape.transform.a = a;
shape.transform.b = b;
shape.transform.c = c;
shape.transform.d = d;
shape.transform.e = e;
shape.transform.f = f;
shape.set_transform(a, b, c, d, e, f);
}
}
@ -173,7 +168,7 @@ pub extern "C" fn add_shape_child(a: u32, b: u32, c: u32, d: u32) {
let state = unsafe { STATE.as_mut() }.expect("got an invalid state pointer");
let id = uuid_from_u32_quartet(a, b, c, d);
if let Some(shape) = state.current_shape() {
shape.children.push(id);
shape.add_child(id);
}
}
@ -181,7 +176,7 @@ pub extern "C" fn add_shape_child(a: u32, b: u32, c: u32, d: u32) {
pub extern "C" fn clear_shape_children() {
let state = unsafe { STATE.as_mut() }.expect("got an invalid state pointer");
if let Some(shape) = state.current_shape() {
shape.children.clear();
shape.clear_children();
}
}
@ -307,7 +302,7 @@ pub extern "C" fn clear_shape_fills() {
pub extern "C" fn set_shape_blend_mode(mode: i32) {
let state = unsafe { STATE.as_mut() }.expect("got an invalid state pointer");
if let Some(shape) = state.current_shape() {
shape.set_blend_mode(shapes::BlendMode::from(mode));
shape.set_blend_mode(render::BlendMode::from(mode));
}
}
@ -315,7 +310,7 @@ pub extern "C" fn set_shape_blend_mode(mode: i32) {
pub extern "C" fn set_shape_opacity(opacity: f32) {
let state = unsafe { STATE.as_mut() }.expect("got an invalid state pointer");
if let Some(shape) = state.current_shape() {
shape.opacity = opacity;
shape.set_opacity(opacity);
}
}
@ -323,7 +318,7 @@ pub extern "C" fn set_shape_opacity(opacity: f32) {
pub extern "C" fn set_shape_hidden(hidden: bool) {
let state = unsafe { STATE.as_mut() }.expect("got an invalid state pointer");
if let Some(shape) = state.current_shape() {
shape.hidden = hidden;
shape.set_hidden(hidden);
}
}

View file

@ -1,55 +1,31 @@
use skia::gpu::{self, gl::FramebufferInfo, DirectContext};
use std::collections::HashMap;
use skia::Contains;
use skia_safe as skia;
use std::collections::HashMap;
use uuid::Uuid;
use crate::debug;
use crate::math::Rect;
use crate::shapes::{draw_image_in_container, Fill, Image, Kind, Shape};
use crate::math;
use crate::view::Viewbox;
struct GpuState {
pub context: DirectContext,
framebuffer_info: FramebufferInfo,
}
mod blend;
mod gpu_state;
mod images;
mod options;
impl GpuState {
fn new() -> Self {
let interface = skia::gpu::gl::Interface::new_native().unwrap();
let context = skia::gpu::direct_contexts::make_gl(interface, None).unwrap();
let framebuffer_info = {
let mut fboid: gl::types::GLint = 0;
unsafe { gl::GetIntegerv(gl::FRAMEBUFFER_BINDING, &mut fboid) };
use gpu_state::GpuState;
use options::RenderOptions;
FramebufferInfo {
fboid: fboid.try_into().unwrap(),
format: skia::gpu::gl::Format::RGBA8.into(),
protected: skia::gpu::Protected::No,
}
};
pub use blend::BlendMode;
pub use images::*;
GpuState {
context,
framebuffer_info,
}
}
/// Create a Skia surface that will be used for rendering.
fn create_target_surface(&mut self, width: i32, height: i32) -> skia::Surface {
let backend_render_target =
gpu::backend_render_targets::make_gl((width, height), 1, 8, self.framebuffer_info);
gpu::surfaces::wrap_backend_render_target(
&mut self.context,
&backend_render_target,
skia::gpu::SurfaceOrigin::BottomLeft,
skia::ColorType::RGBA8888,
None,
None,
)
.unwrap()
}
pub trait Renderable {
fn render(&self, surface: &mut skia::Surface, images: &ImageStore) -> Result<(), String>;
fn blend_mode(&self) -> BlendMode;
fn opacity(&self) -> f32;
fn bounds(&self) -> math::Rect;
fn hidden(&self) -> bool;
fn clip(&self) -> bool;
fn children_ids(&self) -> Vec<Uuid>;
}
pub(crate) struct CachedSurfaceImage {
@ -64,31 +40,6 @@ impl CachedSurfaceImage {
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
struct RenderOptions {
debug_flags: u32,
dpr: Option<f32>,
}
impl Default for RenderOptions {
fn default() -> Self {
Self {
debug_flags: 0x00,
dpr: None,
}
}
}
impl RenderOptions {
pub fn is_debug_visible(&self) -> bool {
self.debug_flags & debug::DEBUG_VISIBLE == debug::DEBUG_VISIBLE
}
pub fn dpr(&self) -> f32 {
self.dpr.unwrap_or(1.0)
}
}
pub(crate) struct RenderState {
gpu_state: GpuState,
pub final_surface: skia::Surface,
@ -97,7 +48,7 @@ pub(crate) struct RenderState {
pub cached_surface_image: Option<CachedSurfaceImage>,
options: RenderOptions,
pub viewbox: Viewbox,
images: HashMap<Uuid, Image>,
images: ImageStore,
}
impl RenderState {
@ -120,20 +71,16 @@ impl RenderState {
cached_surface_image: None,
options: RenderOptions::default(),
viewbox: Viewbox::new(width as f32, height as f32),
images: HashMap::with_capacity(2048),
images: ImageStore::new(),
}
}
pub fn add_image(&mut self, id: Uuid, image_data: &[u8]) -> Result<(), String> {
let image_data = skia::Data::new_copy(image_data);
let image = Image::from_encoded(image_data).ok_or("Error decoding image data")?;
self.images.insert(id, image);
Ok(())
self.images.add(id, image_data)
}
pub fn has_image(&mut self, id: &Uuid) -> bool {
self.images.contains_key(id)
self.images.contains(id)
}
pub fn set_debug_flags(&mut self, debug: u32) {
@ -197,39 +144,15 @@ impl RenderState {
.reset_matrix();
}
pub fn render_single_shape(&mut self, shape: &Shape) {
let mut transform = skia::Matrix::new_identity();
let (translate_x, translate_y) = shape.translation();
let (scale_x, scale_y) = shape.scale();
let (skew_x, skew_y) = shape.skew();
transform.set_all(
scale_x,
skew_x,
translate_x,
skew_y,
scale_y,
translate_y,
0.,
0.,
1.,
);
// Check transform-matrix code from common/src/app/common/geom/shapes/transforms.cljc
let center = shape.selrect.center();
let mut matrix = skia::Matrix::new_identity();
matrix.pre_translate(center);
matrix.pre_concat(&transform);
matrix.pre_translate(-center);
self.drawing_surface.canvas().concat(&matrix);
for fill in shape.fills().rev() {
self.render_fill(fill, shape.selrect, &shape.kind);
}
pub fn render_single_element(&mut self, element: &impl Renderable) {
element
.render(&mut self.drawing_surface, &self.images)
.unwrap();
let mut paint = skia::Paint::default();
paint.set_blend_mode(shape.blend_mode.into());
paint.set_alpha_f(shape.opacity);
paint.set_blend_mode(element.blend_mode().into());
paint.set_alpha_f(element.opacity());
self.drawing_surface.draw(
&mut self.final_surface.canvas(),
(0.0, 0.0),
@ -241,10 +164,10 @@ impl RenderState {
.clear(skia::Color::TRANSPARENT);
}
pub fn navigate(&mut self, shapes: &HashMap<Uuid, Shape>) -> Result<(), String> {
pub fn navigate(&mut self, tree: &HashMap<Uuid, impl Renderable>) -> Result<(), String> {
if let Some(cached_surface_image) = self.cached_surface_image.as_ref() {
if cached_surface_image.is_dirty(&self.viewbox) {
self.render_all(shapes, true);
self.render_all(tree, true);
} else {
self.render_all_from_cache()?;
}
@ -255,7 +178,7 @@ impl RenderState {
pub fn render_all(
&mut self,
shapes: &HashMap<Uuid, Shape>,
tree: &HashMap<Uuid, impl Renderable>,
generate_cached_surface_image: bool,
) {
self.reset_canvas();
@ -265,7 +188,7 @@ impl RenderState {
);
self.translate(self.viewbox.pan_x, self.viewbox.pan_y);
let is_complete = self.render_shape_tree(&Uuid::nil(), shapes);
let is_complete = self.render_shape_tree(&Uuid::nil(), tree);
if generate_cached_surface_image || self.cached_surface_image.is_none() {
self.cached_surface_image = Some(CachedSurfaceImage {
image: self.final_surface.image_snapshot(),
@ -281,38 +204,6 @@ impl RenderState {
self.flush();
}
fn render_fill(&mut self, fill: &Fill, selrect: Rect, kind: &Kind) {
match (fill, kind) {
(Fill::Image(image_fill), kind) => {
let image = self.images.get(&image_fill.id());
if let Some(image) = image {
draw_image_in_container(
&self.drawing_surface.canvas(),
&image,
image_fill.size(),
kind,
&fill.to_paint(&selrect),
);
}
}
(_, Kind::Rect(rect)) => {
self.drawing_surface
.canvas()
.draw_rect(rect, &fill.to_paint(&selrect));
}
(_, Kind::Circle(rect)) => {
self.drawing_surface
.canvas()
.draw_oval(rect, &fill.to_paint(&selrect));
}
(_, Kind::Path(path)) => {
self.drawing_surface
.canvas()
.draw_path(&path.to_skia_path(), &fill.to_paint(&selrect));
}
}
}
fn render_all_from_cache(&mut self) -> Result<(), String> {
self.reset_canvas();
@ -365,7 +256,7 @@ impl RenderState {
self.debug_surface.canvas().draw_rect(scaled_rect, &paint);
}
fn render_debug_shape(&mut self, shape: &Shape, intersected: bool) {
fn render_debug_element(&mut self, element: &impl Renderable, intersected: bool) {
let mut paint = skia::Paint::default();
paint.set_style(skia::PaintStyle::Stroke);
paint.set_color(if intersected {
@ -375,7 +266,7 @@ impl RenderState {
});
paint.set_stroke_width(1.);
let mut scaled_rect = shape.selrect.clone();
let mut scaled_rect = element.bounds();
let x = 100. + scaled_rect.x() * 0.2;
let y = 100. + scaled_rect.y() * 0.2;
let width = scaled_rect.width() * 0.2;
@ -397,18 +288,18 @@ impl RenderState {
}
// Returns a boolean indicating if the viewbox contains the rendered shapes
fn render_shape_tree(&mut self, id: &Uuid, shapes: &HashMap<Uuid, Shape>) -> bool {
let shape = shapes.get(&id).unwrap();
let mut is_complete = self.viewbox.area.contains(shape.selrect);
fn render_shape_tree(&mut self, root_id: &Uuid, tree: &HashMap<Uuid, impl Renderable>) -> bool {
let element = tree.get(&root_id).unwrap();
let mut is_complete = self.viewbox.area.contains(element.bounds());
if !id.is_nil() {
if !shape.selrect.intersects(self.viewbox.area) || shape.hidden {
self.render_debug_shape(shape, false);
if !root_id.is_nil() {
if !element.bounds().intersects(self.viewbox.area) || element.hidden() {
self.render_debug_element(element, false);
// TODO: This means that not all the shapes are renderer so we
// need to call a render_all on the zoom out.
return is_complete; // TODO return is_complete or return false??
} else {
self.render_debug_shape(shape, true);
self.render_debug_element(element, true);
}
}
@ -416,11 +307,11 @@ impl RenderState {
self.final_surface.canvas().save();
self.drawing_surface.canvas().save();
if !id.is_nil() {
self.render_single_shape(shape);
if shape.clip_content {
if !root_id.is_nil() {
self.render_single_element(element);
if element.clip() {
self.drawing_surface.canvas().clip_rect(
shape.selrect,
element.bounds(),
skia::ClipOp::Intersect,
true,
);
@ -428,13 +319,13 @@ impl RenderState {
}
// draw all the children shapes
let shape_ids = shape.children.iter();
for shape_id in shape_ids {
is_complete = self.render_shape_tree(shape_id, shapes) && is_complete;
for id in element.children_ids() {
is_complete = self.render_shape_tree(&id, tree) && is_complete;
}
self.final_surface.canvas().restore();
self.drawing_surface.canvas().restore();
return is_complete;
}
}

View file

@ -0,0 +1,45 @@
use skia_safe as skia;
use skia_safe::gpu::{self, gl::FramebufferInfo, DirectContext};
pub struct GpuState {
pub context: DirectContext,
framebuffer_info: FramebufferInfo,
}
impl GpuState {
pub fn new() -> Self {
let interface = gpu::gl::Interface::new_native().unwrap();
let context = gpu::direct_contexts::make_gl(interface, None).unwrap();
let framebuffer_info = {
let mut fboid: gl::types::GLint = 0;
unsafe { gl::GetIntegerv(gl::FRAMEBUFFER_BINDING, &mut fboid) };
FramebufferInfo {
fboid: fboid.try_into().unwrap(),
format: gpu::gl::Format::RGBA8.into(),
protected: gpu::Protected::No,
}
};
GpuState {
context,
framebuffer_info,
}
}
/// Create a Skia surface that will be used for rendering.
pub fn create_target_surface(&mut self, width: i32, height: i32) -> skia::Surface {
let backend_render_target =
gpu::backend_render_targets::make_gl((width, height), 1, 8, self.framebuffer_info);
gpu::surfaces::wrap_backend_render_target(
&mut self.context,
&backend_render_target,
gpu::SurfaceOrigin::BottomLeft,
skia::ColorType::RGBA8888,
None,
None,
)
.unwrap()
}
}

View file

@ -0,0 +1,33 @@
use skia_safe as skia;
use std::collections::HashMap;
use uuid::Uuid;
pub type Image = skia::Image;
pub struct ImageStore {
images: HashMap<Uuid, Image>,
}
impl ImageStore {
pub fn new() -> Self {
Self {
images: HashMap::with_capacity(2048),
}
}
pub fn add(&mut self, id: Uuid, image_data: &[u8]) -> Result<(), String> {
let image_data = skia::Data::new_copy(image_data);
let image = Image::from_encoded(image_data).ok_or("Error decoding image data")?;
self.images.insert(id, image);
Ok(())
}
pub fn contains(&mut self, id: &Uuid) -> bool {
self.images.contains_key(id)
}
pub fn get(&self, id: &Uuid) -> Option<&Image> {
self.images.get(id)
}
}

View file

@ -0,0 +1,26 @@
use crate::debug;
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct RenderOptions {
pub debug_flags: u32,
pub dpr: Option<f32>,
}
impl Default for RenderOptions {
fn default() -> Self {
Self {
debug_flags: 0x00,
dpr: None,
}
}
}
impl RenderOptions {
pub fn is_debug_visible(&self) -> bool {
self.debug_flags & debug::DEBUG_VISIBLE == debug::DEBUG_VISIBLE
}
pub fn dpr(&self) -> f32 {
self.dpr.unwrap_or(1.0)
}
}

View file

@ -2,13 +2,17 @@ use crate::math;
use skia_safe as skia;
use uuid::Uuid;
mod blend;
use crate::render::BlendMode;
mod fills;
mod images;
mod matrix;
mod paths;
pub use blend::*;
mod renderable;
pub use fills::*;
pub use images::*;
use matrix::*;
pub use paths::*;
#[derive(Debug, Clone, PartialEq)]
@ -20,43 +24,20 @@ pub enum Kind {
pub type Color = skia::Color;
#[derive(Debug, Clone, Copy)]
pub struct Matrix {
pub a: f32,
pub b: f32,
pub c: f32,
pub d: f32,
pub e: f32,
pub f: f32,
}
impl Matrix {
pub fn identity() -> Self {
Self {
a: 1.,
b: 0.,
c: 0.,
d: 1.,
e: 0.,
f: 0.,
}
}
}
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct Shape {
pub id: Uuid,
pub children: Vec<Uuid>,
pub kind: Kind,
pub selrect: math::Rect,
pub transform: Matrix,
pub rotation: f32,
pub clip_content: bool,
id: Uuid,
children: Vec<Uuid>,
kind: Kind,
selrect: math::Rect,
transform: Matrix,
rotation: f32,
clip_content: bool,
fills: Vec<Fill>,
pub blend_mode: BlendMode,
pub opacity: f32,
pub hidden: bool,
blend_mode: BlendMode,
opacity: f32,
hidden: bool,
}
impl Shape {
@ -89,16 +70,36 @@ impl Shape {
};
}
pub fn translation(&self) -> (f32, f32) {
(self.transform.e, self.transform.f)
pub fn set_kind(&mut self, kind: Kind) {
self.kind = kind;
}
pub fn scale(&self) -> (f32, f32) {
(self.transform.a, self.transform.d)
pub fn set_clip(&mut self, value: bool) {
self.clip_content = value;
}
pub fn skew(&self) -> (f32, f32) {
(self.transform.c, self.transform.b)
pub fn set_rotation(&mut self, angle: f32) {
self.rotation = angle;
}
pub fn set_transform(&mut self, a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) {
self.transform = Matrix::new(a, b, c, d, e, f);
}
pub fn set_opacity(&mut self, opacity: f32) {
self.opacity = opacity;
}
pub fn set_hidden(&mut self, value: bool) {
self.hidden = value;
}
pub fn add_child(&mut self, id: Uuid) {
self.children.push(id);
}
pub fn clear_children(&mut self) {
self.children.clear();
}
pub fn fills(&self) -> std::slice::Iter<Fill> {

View file

@ -0,0 +1,61 @@
use skia_safe as skia;
#[derive(Debug, Clone, Copy)]
pub struct Matrix {
pub a: f32,
pub b: f32,
pub c: f32,
pub d: f32,
pub e: f32,
pub f: f32,
}
impl Matrix {
pub fn new(a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) -> Self {
Self { a, b, c, d, e, f }
}
pub fn identity() -> Self {
Self {
a: 1.,
b: 0.,
c: 0.,
d: 1.,
e: 0.,
f: 0.,
}
}
pub fn to_skia_matrix(&self) -> skia::Matrix {
let mut res = skia::Matrix::new_identity();
let (translate_x, translate_y) = self.translation();
let (scale_x, scale_y) = self.scale();
let (skew_x, skew_y) = self.skew();
res.set_all(
scale_x,
skew_x,
translate_x,
skew_y,
scale_y,
translate_y,
0.,
0.,
1.,
);
res
}
fn translation(&self) -> (f32, f32) {
(self.e, self.f)
}
fn scale(&self) -> (f32, f32) {
(self.a, self.d)
}
fn skew(&self) -> (f32, f32) {
(self.c, self.b)
}
}

View file

@ -0,0 +1,89 @@
use skia_safe as skia;
use uuid::Uuid;
use super::{draw_image_in_container, Fill, Kind, Shape};
use crate::math::Rect;
use crate::render::{ImageStore, Renderable};
impl Renderable for Shape {
fn render(&self, surface: &mut skia_safe::Surface, images: &ImageStore) -> Result<(), String> {
let transform = self.transform.to_skia_matrix();
// Check transform-matrix code from common/src/app/common/geom/shapes/transforms.cljc
let center = self.selrect.center();
let mut matrix = skia::Matrix::new_identity();
matrix.pre_translate(center);
matrix.pre_concat(&transform);
matrix.pre_translate(-center);
surface.canvas().concat(&matrix);
for fill in self.fills().rev() {
render_fill(surface, images, fill, self.selrect, &self.kind);
}
let mut paint = skia::Paint::default();
paint.set_blend_mode(self.blend_mode.into());
paint.set_alpha_f(self.opacity);
Ok(())
}
fn blend_mode(&self) -> crate::render::BlendMode {
self.blend_mode
}
fn opacity(&self) -> f32 {
self.opacity
}
fn hidden(&self) -> bool {
self.hidden
}
fn bounds(&self) -> Rect {
self.selrect
}
fn clip(&self) -> bool {
self.clip_content
}
fn children_ids(&self) -> Vec<Uuid> {
self.children.clone()
}
}
fn render_fill(
surface: &mut skia::Surface,
images: &ImageStore,
fill: &Fill,
selrect: Rect,
kind: &Kind,
) {
match (fill, kind) {
(Fill::Image(image_fill), kind) => {
let image = images.get(&image_fill.id());
if let Some(image) = image {
draw_image_in_container(
surface.canvas(),
&image,
image_fill.size(),
kind,
&fill.to_paint(&selrect),
);
}
}
(_, Kind::Rect(rect)) => {
surface.canvas().draw_rect(rect, &fill.to_paint(&selrect));
}
(_, Kind::Circle(rect)) => {
surface.canvas().draw_oval(rect, &fill.to_paint(&selrect));
}
(_, Kind::Path(path)) => {
surface
.canvas()
.draw_path(&path.to_skia_path(), &fill.to_paint(&selrect));
}
}
}