diff options
| author | Arne Dußin | 2020-10-30 23:28:40 +0100 |
|---|---|---|
| committer | Arne Dußin | 2020-10-30 23:28:40 +0100 |
| commit | c5b16dd0511997331b8cc8c3647fff95effbe8ec (patch) | |
| tree | f9077567ee46d70e4988e66086e47d07192f6aa3 | |
| parent | 11faa70718c8304ac4e5b4a75e6aa1d573883955 (diff) | |
| download | graf_karto-c5b16dd0511997331b8cc8c3647fff95effbe8ec.tar.gz graf_karto-c5b16dd0511997331b8cc8c3647fff95effbe8ec.zip | |
Snap rooms to the grid
| -rw-r--r-- | src/math.rs | 18 | ||||
| -rw-r--r-- | src/tool/room_tool.rs | 12 |
2 files changed, 28 insertions, 2 deletions
diff --git a/src/math.rs b/src/math.rs index c4e7ac0..60a53e8 100644 --- a/src/math.rs +++ b/src/math.rs @@ -16,3 +16,21 @@ pub fn bounding_rect(pos1: Vector2, pos2: Vector2) -> Rectangle { height: max_y - min_y, } } + +/// Round a floating point number to the nearest step given by the step argument. For instance, if +/// the step is 0.5, then all numbers from 0.0 to 0.24999... will be 0., while all numbers from +/// 0.25 to 0.74999... will be 0.5 and so on. +pub fn round(num: f32, step: f32) -> f32 { + // Only positive steps will be accepted. + assert!(step > 0.); + + let lower_bound = ((num / step) as i32) as f32 * step; + let upper_bound = lower_bound + step; + + // Compare the distances and prefer the smaller. If they are the same, prefer the upper bound. + if (num - lower_bound) < (upper_bound - num) { + lower_bound + } else { + upper_bound + } +} diff --git a/src/tool/room_tool.rs b/src/tool/room_tool.rs index 8288c97..6a9ad55 100644 --- a/src/tool/room_tool.rs +++ b/src/tool/room_tool.rs @@ -29,7 +29,11 @@ impl Tool for RoomTool { let mouse_pos_m = transform.point_px_to_m(rl.get_mouse_position()); // Update the currently drawn rectangle, if it exists if let Some((_, ref mut pos2)) = &mut self.unfinished_rect { - *pos2 = mouse_pos_m; + let snapped_mouse_pos = Vector2::new( + math::round(mouse_pos_m.x, 0.5), + math::round(mouse_pos_m.y, 0.5), + ); + *pos2 = snapped_mouse_pos; } // Start or finish drawing the currently unfinished rectangle @@ -38,7 +42,11 @@ impl Tool for RoomTool { self.room_rects.push(math::bounding_rect(pos1, pos2)); self.unfinished_rect = None; } else { - self.unfinished_rect = Some((mouse_pos_m, mouse_pos_m)) + let snapped_mouse_pos = Vector2::new( + math::round(mouse_pos_m.x, 0.5), + math::round(mouse_pos_m.y, 0.5), + ); + self.unfinished_rect = Some((snapped_mouse_pos, snapped_mouse_pos)) } } |
