Skip to content

Refactor ViewportPosition from u32 (UVec2) to f64 (DVec2) #345

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Aug 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions editor/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ thiserror = "1.0.24"
serde = { version = "1.0", features = ["derive"] }
graphite-proc-macros = { path = "../proc-macros" }
glam = { version="0.17", features = ["serde"] }
rand_chacha = "0.3.1"
spin = "0.9.2"

[dependencies.graphene]
path = "../graphene"
Expand Down
10 changes: 5 additions & 5 deletions editor/src/communication/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,11 @@ mod test {
}));

editor.select_primary_color(Color::RED);
editor.draw_rect(100, 200, 300, 400);
editor.draw_rect(100., 200., 300., 400.);
editor.select_primary_color(Color::BLUE);
editor.draw_shape(10, 1200, 1300, 400);
editor.draw_shape(10., 1200., 1300., 400.);
editor.select_primary_color(Color::GREEN);
editor.draw_ellipse(104, 1200, 1300, 400);
editor.draw_ellipse(104., 1200., 1300., 400.);

editor
}
Expand Down Expand Up @@ -278,7 +278,7 @@ mod test {
editor.handle_message(DocumentMessage::SelectLayers(vec![vec![rect_id], vec![ellipse_id]])).unwrap();
editor.handle_message(DocumentsMessage::CopySelectedLayers).unwrap();
editor.handle_message(DocumentMessage::DeleteSelectedLayers).unwrap();
editor.draw_rect(0, 800, 12, 200);
editor.draw_rect(0., 800., 12., 200.);
editor.handle_message(DocumentsMessage::PasteLayers { path: vec![], insert_index: -1 }).unwrap();
editor.handle_message(DocumentsMessage::PasteLayers { path: vec![], insert_index: -1 }).unwrap();

Expand All @@ -303,7 +303,7 @@ mod test {
/// - create rect, shape and ellipse
/// - select ellipse and rect
/// - move them down and back up again
fn move_seletion() {
fn move_selection() {
init_logger();
let mut editor = create_editor_with_three_layers();

Expand Down
22 changes: 12 additions & 10 deletions editor/src/communication/mod.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

pub mod dispatcher;
pub mod message;
use crate::message_prelude::*;
pub use dispatcher::*;
use rand_chacha::{
rand_core::{RngCore, SeedableRng},
ChaCha20Rng,
};
use spin::Mutex;

pub use crate::input::InputPreprocessor;
use std::collections::VecDeque;

pub type ActionList = Vec<Vec<MessageDiscriminant>>;

static RNG: Mutex<Option<ChaCha20Rng>> = Mutex::new(None);

// TODO: Add Send + Sync requirement
// Use something like rw locks for synchronization
pub trait MessageHandlerData {}
Expand All @@ -25,12 +29,10 @@ where
fn actions(&self) -> ActionList;
}

pub fn generate_hash<'a>(messages: impl IntoIterator<Item = &'a Message>, ipp: &InputPreprocessor, document_hash: u64) -> u64 {
let mut s = DefaultHasher::new();
document_hash.hash(&mut s);
ipp.hash(&mut s);
for message in messages {
message.pseudo_hash().hash(&mut s);
pub fn generate_uuid() -> u64 {
let mut lock = RNG.lock();
if lock.is_none() {
*lock = Some(ChaCha20Rng::seed_from_u64(0));
}
s.finish()
lock.as_mut().map(ChaCha20Rng::next_u64).unwrap()
}
4 changes: 2 additions & 2 deletions editor/src/document/document_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ impl DocumentMessageHandler {
}

/// Returns a list of `LayerPanelEntry`s intended for display purposes. These don't contain
/// any actual data, but ratfolderch as visibility and names of the layers.
/// any actual data, but rather attributes such as visibility and names of the layers.
pub fn layer_panel(&mut self, path: &[LayerId]) -> Result<Vec<LayerPanelEntry>, EditorError> {
let folder = self.document.folder(path)?;
let paths: Vec<Vec<LayerId>> = folder.layer_ids.iter().map(|id| [path, &[*id]].concat()).collect();
Expand Down Expand Up @@ -284,7 +284,7 @@ impl MessageHandler<DocumentMessage, &InputPreprocessor> for DocumentMessageHand
}
CommitTransaction => self.document_backup = None,
ExportDocument => {
let bbox = self.document.visible_layers_bounding_box().unwrap_or([DVec2::ZERO, ipp.viewport_size.as_f64()]);
let bbox = self.document.visible_layers_bounding_box().unwrap_or([DVec2::ZERO, ipp.viewport_size]);
let size = bbox[1] - bbox[0];
let name = match self.name.ends_with(FILE_SAVE_SUFFIX) {
true => self.name.clone().replace(FILE_SAVE_SUFFIX, FILE_EXPORT_SUFFIX),
Expand Down
19 changes: 9 additions & 10 deletions editor/src/document/movement_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pub enum MovementMessage {
ZoomCanvasToFitAll,
}

#[derive(Debug, Clone, Hash, Default, PartialEq)]
#[derive(Debug, Clone, Default, PartialEq)]
pub struct MovementMessageHandler {
translating: bool,
rotating: bool,
Expand All @@ -43,7 +43,7 @@ pub struct MovementMessageHandler {

impl MovementMessageHandler {
fn create_document_transform_from_layerdata(&self, layerdata: &LayerData, viewport_size: &ViewportPosition, responses: &mut VecDeque<Message>) {
let half_viewport = viewport_size.as_f64() / 2.;
let half_viewport = *viewport_size / 2.;
let scaled_half_viewport = half_viewport / layerdata.scale;
responses.push_back(
DocumentOperation::SetLayerTransform {
Expand All @@ -64,7 +64,6 @@ impl MessageHandler<MovementMessage, (&mut LayerData, &Document, &InputPreproces
self.translating = true;
self.mouse_pos = ipp.mouse.position;
}

RotateCanvasBegin { snap } => {
self.rotating = true;
self.snapping = snap;
Expand All @@ -86,17 +85,17 @@ impl MessageHandler<MovementMessage, (&mut LayerData, &Document, &InputPreproces
}
MouseMove => {
if self.translating {
let delta = ipp.mouse.position.as_f64() - self.mouse_pos.as_f64();
let delta = ipp.mouse.position - self.mouse_pos;
let transformed_delta = document.root.transform.inverse().transform_vector2(delta);

layerdata.translation += transformed_delta;
self.create_document_transform_from_layerdata(layerdata, &ipp.viewport_size, responses);
}
if self.rotating {
let half_viewport = ipp.viewport_size.as_f64() / 2.;
let half_viewport = ipp.viewport_size / 2.;
let rotation = {
let start_vec = self.mouse_pos.as_f64() - half_viewport;
let end_vec = ipp.mouse.position.as_f64() - half_viewport;
let start_vec = self.mouse_pos - half_viewport;
let end_vec = ipp.mouse.position - half_viewport;
start_vec.angle_between(end_vec)
};

Expand Down Expand Up @@ -140,8 +139,8 @@ impl MessageHandler<MovementMessage, (&mut LayerData, &Document, &InputPreproces
}
WheelCanvasZoom => {
let scroll = ipp.mouse.scroll_delta.scroll_delta();
let mouse = ipp.mouse.position.as_f64();
let viewport_size = ipp.viewport_size.as_f64();
let mouse = ipp.mouse.position;
let viewport_size = ipp.viewport_size;
let mut zoom_factor = 1. + scroll.abs() * VIEWPORT_ZOOM_WHEEL_RATE;
if ipp.mouse.scroll_delta.y > 0 {
zoom_factor = 1. / zoom_factor
Expand Down Expand Up @@ -177,7 +176,7 @@ impl MessageHandler<MovementMessage, (&mut LayerData, &Document, &InputPreproces
let pos1 = document.root.transform.inverse().transform_point2(pos1);
let pos2 = document.root.transform.inverse().transform_point2(pos2);
let v1 = document.root.transform.inverse().transform_point2(DVec2::ZERO);
let v2 = document.root.transform.inverse().transform_point2(ipp.viewport_size.as_f64());
let v2 = document.root.transform.inverse().transform_point2(ipp.viewport_size);

let center = v1.lerp(v2, 0.5) - pos1.lerp(pos2, 0.5);
let size = (pos2 - pos1) / (v2 - v1);
Expand Down
6 changes: 3 additions & 3 deletions editor/src/input/input_preprocessor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ bitflags! {
}
}

#[derive(Debug, Default, Hash)]
#[derive(Debug, Default)]
pub struct InputPreprocessor {
pub keyboard: KeyStates,
pub mouse: MouseState,
Expand Down Expand Up @@ -81,7 +81,7 @@ impl MessageHandler<InputPreprocessorMessage, ()> for InputPreprocessor {
responses.push_back(
graphene::Operation::TransformLayer {
path: vec![],
transform: glam::DAffine2::from_translation((size.as_f64() - self.viewport_size.as_f64()) / 2.).to_cols_array(),
transform: glam::DAffine2::from_translation((size - self.viewport_size) / 2.).to_cols_array(),
}
.into(),
);
Expand Down Expand Up @@ -141,7 +141,7 @@ mod test {
#[test]
fn process_action_mouse_move_handle_modifier_keys() {
let mut input_preprocessor = InputPreprocessor::default();
let message = InputPreprocessorMessage::MouseMove((4, 809).into(), ModifierKeys::ALT);
let message = InputPreprocessorMessage::MouseMove((4., 809.).into(), ModifierKeys::ALT);
let mut responses = VecDeque::new();

input_preprocessor.process_action(message, (), &mut responses);
Expand Down
13 changes: 7 additions & 6 deletions editor/src/input/mouse.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use bitflags::bitflags;
use glam::DVec2;

// origin is top left
pub type ViewportPosition = glam::UVec2;
// Origin is top left
pub type ViewportPosition = DVec2;

#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Hash)]
pub struct ScrollDelta {
Expand All @@ -23,25 +23,26 @@ impl ScrollDelta {
}
}

#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Hash)]
#[derive(Debug, Copy, Clone, Default, PartialEq)]
pub struct MouseState {
pub position: ViewportPosition,
pub mouse_keys: MouseKeys,
pub scroll_delta: ScrollDelta,
}

impl MouseState {
pub fn new() -> MouseState {
pub fn new() -> Self {
Self::default()
}

pub fn from_pos(x: u32, y: u32) -> MouseState {
MouseState {
pub fn from_pos(x: f64, y: f64) -> Self {
Self {
position: (x, y).into(),
mouse_keys: MouseKeys::default(),
scroll_delta: ScrollDelta::default(),
}
}

pub fn from_u8_pos(keys: u8, position: ViewportPosition) -> Self {
let mouse_keys = MouseKeys::from_bits(keys).expect("invalid modifier keys");
Self {
Expand Down
2 changes: 1 addition & 1 deletion editor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ impl Editor {
}

pub mod message_prelude {
pub use crate::communication::generate_hash;
pub use crate::communication::generate_uuid;
pub use crate::communication::message::{AsMessage, Message, MessageDiscriminant};
pub use crate::communication::{ActionList, MessageHandler};
pub use crate::document::{DocumentMessage, DocumentMessageDiscriminant};
Expand Down
Loading