Skip to content
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

Implement monotone polygons triangulation #10

Open
wants to merge 11 commits into
base: main
Choose a base branch
from

Conversation

Czaki
Copy link
Contributor

@Czaki Czaki commented Jan 30, 2025

Next steep for sweeping line triangulation

Summary by CodeRabbit

  • New Features

    • Introduced advanced geometry support that processes y-monotone polygons and performs reliable triangulation.
    • Enhanced triangle representations to ensure consistent vertex ordering.
  • Tests

    • Added a comprehensive test suite covering various polygon configurations and triangulation scenarios.

@Czaki Czaki added this to the 0.1.0 milestone Jan 30, 2025
Copy link
Contributor

coderabbitai bot commented Jan 30, 2025

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This PR introduces a new monotone polygon module and its triangulation functionality into the project. It adds a suite of tests using the rstest framework for validating both simple and parameterized cases. New structures and methods for creating and processing y-monotone polygons are defined, including a stack-based triangulation algorithm. Additionally, new triangle representation types are added to better manage geometry and provide a clear construction of triangles with correctly ordered vertices.

Changes

File(s) Change Summary
crates/bermuda/tests/test_monotone_polygon.rs Added a new test suite with functions test_monotone_polygon_simple and parameterized test_monotone_polygon using rstest to verify monotone polygon construction and triangulation.
crates/triangulation/src/lib.rs
crates/triangulation/src/monotone_polygon.rs
New public module monotone_polygon introduced. Defined MonotonePolygon struct, its constructors, and methods (including finished) along with triangulation functions (triangulate_monotone_polygon, build_triangles_opposite_edge, build_triangles_current_edge) and a Side enum.
crates/triangulation/src/point.rs Added new structures Triangle and PointTriangle with constructors ensuring proper vertex ordering and enhanced documentation.

Sequence Diagram(s)

sequenceDiagram
    participant TS as Test Suite
    participant MP as MonotonePolygon
    participant TA as Triangulation Algorithm

    TS->>MP: Construct polygon (new_top, add vertices)
    TS->>TA: Call triangulate_monotone_polygon(MP)
    TA->>MP: Process left/right chains using stack
    TA-->>TS: Return vector of PointTriangles
Loading

Possibly related PRs

Poem

I'm a rabbit, hopping with delight,
Coding shapes from morning to night.
Monotone polygons twist and turn,
Triangles now form, oh how they burn!
With every carrot crunch and joyful leap,
I celebrate these changes in bounds so deep!
🥕🐰


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@Czaki Czaki marked this pull request as draft January 30, 2025 23:30
@@ -271,6 +272,23 @@ impl Ord for Segment {
}

#[derive(Debug, Clone)]
/// A structure representing a triangle using three indices of its vertices.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Love the documentation. 😄

@Czaki
Copy link
Contributor Author

Czaki commented Feb 4, 2025

I will update doc strings tomorrow.

@Czaki Czaki marked this pull request as ready for review February 5, 2025 20:51
@Czaki
Copy link
Contributor Author

Czaki commented Feb 5, 2025

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Feb 5, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (5)
crates/triangulation/src/monotone_polygon.rs (2)

88-117: Guard against empty stack before popping
In build_triangles_opposite_edge, there's a direct call to stack.pop_back().unwrap(), which will panic if the stack is empty. While your logic might guarantee non-empty usage, it may be safer to add a debug assertion or an early return to handle unexpected cases.


239-245: Handle possible empty bottom unwrap
points.push((polygon.bottom.unwrap(), Side::TopOrBottom)); here relies on bottom being set. Ensure that callers check polygon.finished() or otherwise guarantee a valid bottom before calling triangulate_monotone_polygon.

Would you like me to add logic that returns an error if bottom is unset?

crates/bermuda/tests/test_monotone_polygon.rs (2)

6-22: Validate orientation assumptions in test_monotone_polygon_simple
Your test confirms the number of triangles and exact vertex arrangement. Consider adding a quick orientation check (e.g., ensuring the triangle is counterclockwise) or a small doc comment indicating that the expected triangle order depends on your reordering logic in PointTriangle.


24-67: Provide additional edge-case tests
These parameterized tests look comprehensive. You might add a test for nearly collinear points or a degenerate polygon to confirm the triangulation logic’s behavior in edge cases.

crates/triangulation/src/point.rs (1)

373-373: Retain note about floating-point precision
The updated distance doc is concise, but floating-point operations can be tricky. Consider explicitly mentioning possible floating imprecision or referencing the orientation approach used elsewhere in your docs.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6405677 and 13a8540.

📒 Files selected for processing (4)
  • crates/bermuda/tests/test_monotone_polygon.rs (1 hunks)
  • crates/triangulation/src/lib.rs (1 hunks)
  • crates/triangulation/src/monotone_polygon.rs (1 hunks)
  • crates/triangulation/src/point.rs (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • crates/triangulation/src/lib.rs
🔇 Additional comments (3)
crates/triangulation/src/monotone_polygon.rs (2)

64-71: Consider verifying chain completeness in finished()
Currently, finished() only checks for the presence of a bottom vertex. If your logic requires non-empty left and right chains as well, consider also verifying that self.left and self.right are populated.


213-221: Double-check comparison logic in line 214
The condition if polygon.left[left_index] < polygon.right[right_index] { points.push((polygon.right[right_index], Side::Right)); } else { ... } may look reversed for a top-down approach (usually you'd push the smaller point first). If it's intentional, please clarify in a comment to avoid confusion.

crates/triangulation/src/point.rs (1)

274-295: Ensure no off-by-one or index misuse in Triangle
The Triangle struct references vertices by indices. If these indices come from outside user code or a large vertex list, consider validating them to avoid out-of-bounds issues.

Comment on lines 303 to 364
#[derive(Debug, Clone, PartialEq, Eq)]
/// A structure representing a triangle using three [`Point`] as its vertices.
///
/// # Fields
/// * `p1` - The first vertex of the triangle.
/// * `p2` - The second vertex of the triangle.
/// * `p3` - The third vertex of the triangle.
///
/// # Examples
/// ```
/// use triangulation::point::{Point, PointTriangle};
///
/// let p1 = Point::new(0.0, 0.0);
/// let p2 = Point::new(1.0, 0.0);
/// let p3 = Point::new(0.0, 1.0);
///
/// let triangle = PointTriangle::new(p1, p2, p3);
/// assert_eq!(triangle.p1, p1);
/// assert_eq!(triangle.p2, p2);
/// assert_eq!(triangle.p3, p3);
/// ```
pub struct PointTriangle {
pub p1: Point,
pub p2: Point,
pub p3: Point,
}

impl PointTriangle {
/// Creates a new `PointTriangle`.
///
/// The vertices of the triangle are reordered such that the triangle has a counterclockwise orientation.
///
/// # Arguments
/// * `p1` - The first vertex of the triangle.
/// * `p2` - The second vertex of the triangle.
/// * `p3` - The third vertex of the triangle.
///
/// # Returns
/// A `PointTriangle` instance with reordered vertices, if needed, to ensure counterclockwise orientation.
///
/// # Examples
/// ```
/// use triangulation::point::{Point, PointTriangle};
///
/// let p1 = Point::new(0.0, 0.0);
/// let p2 = Point::new(1.0, 0.0);
/// let p3 = Point::new(0.0, 1.0);
///
/// let triangle = PointTriangle::new(p1, p2, p3);
/// assert_eq!(triangle.p1, p1);
/// assert_eq!(triangle.p2, p2);
/// assert_eq!(triangle.p3, p3);
/// ```
pub fn new(p1: Point, p2: Point, p3: Point) -> Self {
let orientation = (p2.x - p1.x) * (p3.y - p1.y) - (p2.y - p1.y) * (p3.x - p1.x);
if orientation < 0.0 {
Self { p1: p3, p2, p3: p1 }
} else {
Self { p1, p2, p3 }
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Handle collinearity in PointTriangle::new
When orientation is zero, the triangle remains in its original order. If strictly counterclockwise ordering is a requirement, consider clarifying how collinear points should be handled (e.g., reorder or treat as invalid).

Copy link
Contributor

@willingc willingc left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall, this looks good. Made a few suggestions and will review monotone polygon closer tomorrow.

crates/triangulation/src/lib.rs Show resolved Hide resolved
crates/triangulation/src/point.rs Outdated Show resolved Hide resolved
crates/triangulation/src/point.rs Show resolved Hide resolved
crates/triangulation/src/point.rs Show resolved Hide resolved
crates/triangulation/src/point.rs Show resolved Hide resolved
Copy link
Contributor

@willingc willingc left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thanks @Czaki. 📐

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants