line_clipping/lib.rs
1#![no_std]
2//! A rust crate to implement several line clipping algorithms. See the
3//! [documentation](https://docs.rs/line_clipping) for more information. The choice of algorithms is
4//! based on the following article which contains a good summary of the options:
5//!
6//! Matthes D, Drakopoulos V. [Line Clipping in 2D: Overview, Techniques and
7//! Algorithms](https://pmc.ncbi.nlm.nih.gov/articles/PMC9605407/). J Imaging. 2022 Oct
8//! 17;8(10):286. doi: 10.3390/jimaging8100286. PMID: 36286380; PMCID: PMC9605407.
9//!
10//! Supports:
11//!
12//! - [x] Cohen-Sutherland
13//!
14//! TODO
15//!
16//! - [ ] Cyrus-Beck
17//! - [ ] Liang-Barsky
18//! - [ ] Nicholl-Lee-Nicholl
19//! - [ ] More comprehensive testing
20//!
21//! # Installation
22//!
23//! ```shell
24//! cargo add line-clipping
25//! ```
26//!
27//! # Usage
28//!
29//! ```rust
30//! use line_clipping::cohen_sutherland::clip_line;
31//! use line_clipping::{LineSegment, Point, Window};
32//!
33//! let line = clip_line(
34//! LineSegment::new(Point::new(0.0, 0.0), Point::new(10.0, 10.0)),
35//! Window::new(1.0, 9.0, 1.0, 9.0),
36//! );
37//! ```
38//!
39//! # License
40//!
41//! Copyright (c) 2024 Josh McKinney
42//!
43//! This project is licensed under either of
44//!
45//! - MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
46//! - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
47//!
48//! at your option.
49//!
50//! # Contribution
51//!
52//! Contributions are welcome! Please open an issue or submit a pull request.
53//!
54//! Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in
55//! the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without
56//! any additional terms or conditions.
57pub mod cohen_sutherland;
58
59/// A point in 2D space.
60#[derive(Debug, Clone, Copy, PartialEq)]
61pub struct Point {
62 pub x: f64,
63 pub y: f64,
64}
65
66impl Point {
67 /// Creates a new point.
68 pub fn new(x: f64, y: f64) -> Self {
69 Point { x, y }
70 }
71}
72
73/// A line segment in 2D space.
74#[derive(Debug, Clone, Copy, PartialEq)]
75pub struct LineSegment {
76 pub p1: Point,
77 pub p2: Point,
78}
79
80impl LineSegment {
81 /// Creates a new line segment.
82 pub fn new(p1: Point, p2: Point) -> Self {
83 LineSegment { p1, p2 }
84 }
85}
86
87/// A rectangular region to clip lines against.
88#[derive(Debug, Clone, Copy)]
89pub struct Window {
90 pub x_min: f64,
91 pub x_max: f64,
92 pub y_min: f64,
93 pub y_max: f64,
94}
95
96impl Window {
97 /// Creates a new window.
98 pub fn new(x_min: f64, x_max: f64, y_min: f64, y_max: f64) -> Self {
99 Window {
100 x_min,
101 x_max,
102 y_min,
103 y_max,
104 }
105 }
106}