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

feat: update nusamai dependencies and add support for LineString3D in geometry processing #35

Merged
merged 2 commits into from
Dec 2, 2024

Conversation

miseyu
Copy link
Collaborator

@miseyu miseyu commented Dec 2, 2024

Summary by CodeRabbit

  • New Features
    • Introduced add_linestring method for adding line strings to the GeometryCollector.
    • Added support for parsing MultiCurve and LineString geometries in the CityGmlReader.
  • Bug Fixes
    • Improved error handling in the XML parsing process for MultiCurve elements.
    • Enhanced checks for GLB format validity in the from_reader method.
  • Refactor
    • Simplified lifetime management in the Glb struct implementation.

@miseyu miseyu self-assigned this Dec 2, 2024
Copy link

coderabbitai bot commented Dec 2, 2024

Walkthrough

The pull request introduces several enhancements across multiple files. In geometry.rs, a new method add_linestring is added to the GeometryCollector struct, allowing the addition of line strings to its multilinestring field. In parser.rs, new methods for parsing MultiCurve and LineString elements are implemented, improving the XML parsing capabilities of the CityGmlReader. Lastly, in glb.rs, the Glb struct's implementation is refined with simplified lifetime management and enhanced error handling in the from_reader method.

Changes

File Change Summary
nusamai-citygml/src/geometry.rs - Added method pub fn add_linestring(&mut self, iter: impl IntoIterator<Item = [f64; 3]>) to GeometryCollector.
nusamai-citygml/src/parser.rs - Added methods: fn parse_multi_curve_prop(&mut self, ...), fn parse_multi_curve(&mut self), and fn parse_linestring(&mut self).
nusamai-gltf/src/glb.rs - Updated implementation block from impl<'a> Glb<'a> to impl Glb<'_>, simplifying lifetime handling.
- Enhanced from_reader method for error handling.

Possibly related PRs

Poem

🐰 In the land of lines and curves so bright,
A new method hops in, oh what a sight!
With add_linestring, our shapes grow wide,
As CityGmlReader takes us on a ride.
Parsing curves with joy, we dance and play,
In the world of geometry, we leap and sway! 🌈


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 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.

@miseyu miseyu changed the title feat(engine): update nusamai dependencies and add support for LineString3D in geometry processing feat: update nusamai dependencies and add support for LineString3D in geometry processing Dec 2, 2024
Copy link

@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: 2

🧹 Outside diff range and nitpick comments (2)
nusamai-citygml/src/geometry.rs (1)

152-159: Consider validating input coordinates in add_linestring

The add_linestring method does not perform validation on the input coordinates. Consider adding checks to ensure that the input iterator provides valid 3D points and handle any potential errors or inconsistencies.

If input validation is necessary, you can modify the method as follows:

pub fn add_linestring(&mut self, iter: impl IntoIterator<Item = [f64; 3]>) {
    for v in iter {
+       if !v.iter().all(|coord| coord.is_finite()) {
+           // Handle invalid coordinate
+           continue; // or return an error
+       }
        let vbits = [v[0].to_bits(), v[1].to_bits(), v[2].to_bits()];
        let (index, _) = self.vertices.insert_full(vbits);
        self.multilinestring.add_point(index as u32);
    }
    self.multilinestring.end_line();
}
nusamai-gltf/src/glb.rs (1)

Line range hint 57-73: Handle optional BIN chunk in GLB files

The from_reader method assumes that the BIN chunk is always present, which may not be the case for all GLB files. According to the GLB 2.0 specification, the BIN chunk is optional. Modify the method to handle cases where the BIN chunk is absent to improve compatibility.

Apply this diff to handle the optional BIN chunk:

// BIN chunk
- let bin_content_size = reader.read_u32::<LittleEndian>()?;
- reader.read_exact(&mut buf)?;
- if &buf[0..4] != b"BIN\x00" {
-     return Err(std::io::Error::new(
-         std::io::ErrorKind::InvalidData,
-         "Second chunk must be 'BIN'".to_string(),
-     ));
- }
- let mut bin_content = vec![0; bin_content_size as usize];
- reader.read_exact(&mut bin_content)?;
+ if let Ok(bin_content_size) = reader.read_u32::<LittleEndian>() {
+     reader.read_exact(&mut buf)?;
+     if &buf[0..4] != b"BIN\x00" {
+         return Err(std::io::Error::new(
+             std::io::ErrorKind::InvalidData,
+             "Expected 'BIN' in chunk type".to_string(),
+         ));
+     }
+     let mut bin_content = vec![0; bin_content_size as usize];
+     reader.read_exact(&mut bin_content)?;
+     return Ok(Self {
+         json: json_content.into(),
+         bin: Some(bin_content.into()),
+     });
+ } else {
+     return Ok(Self {
+         json: json_content.into(),
+         bin: None,
+     });
+ }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1864e75 and f3104d8.

📒 Files selected for processing (3)
  • nusamai-citygml/src/geometry.rs (1 hunks)
  • nusamai-citygml/src/parser.rs (11 hunks)
  • nusamai-gltf/src/glb.rs (1 hunks)
🔇 Additional comments (3)
nusamai-citygml/src/parser.rs (2)

729-730: ⚠️ Potential issue

Ensure proper handling of line_begin when parsing geometries

In the parse_geometry_prop method, when parsing a LineString, line_begin is initialized before the match statement. However, if the code path does not process a LineString or MultiCurve, line_begin may not be correctly used. Make sure that line_begin and line_end are appropriately handled for each geometry type to prevent incorrect geometry references.

Run the following script to check the usage of line_begin and ensure it's properly initialized and used:


1107-1124: ⚠️ Potential issue

Verify depth management in parse_linestring

The depth management in the parse_linestring method may not correctly handle all XML structures, potentially leading to incorrect parsing or premature termination. Ensure that the depth tracking accurately reflects the XML hierarchy and that the method can handle various nested elements properly.

Run the following script to test parse_linestring with different XML inputs:

If you need assistance in setting up tests or adjusting the implementation, please let me know.

nusamai-gltf/src/glb.rs (1)

20-20: Improve lifetime annotations by removing unnecessary elision

The change from impl<'a> Glb<'a> to impl Glb<'_> simplifies the lifetime annotations. Double-check that this change does not affect the lifetime requirements elsewhere in the codebase.

nusamai-citygml/src/parser.rs Outdated Show resolved Hide resolved
nusamai-citygml/src/parser.rs Outdated Show resolved Hide resolved
Copy link

@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: 0

🧹 Outside diff range and nitpick comments (4)
nusamai-citygml/src/parser.rs (4)

390-390: Consider addressing the FIXME comment.

The FIXME comment suggests incomplete implementation. Please document what needs to be fixed or remove the comment if it's no longer relevant.

Would you like me to help identify what needs to be fixed or open a GitHub issue to track this?


Line range hint 652-789: Consider refactoring geometry reference handling.

The code for handling geometry references is similar between polygon and line geometries. Consider extracting this common logic into a helper method to reduce duplication.

Example refactor:

fn add_geometry_ref(&mut self, 
    geomrefs: &mut GeometryRefs,
    geomtype: GeometryType,
    lod: u8,
    start: usize,
    end: usize,
    surface_id: Option<LocalId>,
    feature_id: Option<String>,
    feature_type: Option<String>) {
    
    if end - start > 0 {
        geomrefs.push(GeometryRef {
            ty: geomtype,
            lod,
            pos: start as u32,
            len: (end - start) as u32,
            id: surface_id,
            solid_ids: Vec::new(),
            feature_id,
            feature_type,
        });
    }
}

857-883: Improve error message clarity.

The error message "Unexpected element. Because only surface member" could be more descriptive.

-                            return Err(ParseError::SchemaViolation(
-                                "Unexpected element. Because only surface member".into(),
-                            ))
+                            return Err(ParseError::SchemaViolation(format!(
+                                "Unexpected element in MultiCurve: expected <curveMember> but found <{}>",
+                                String::from_utf8_lossy(start.name().as_ref())
+                            )))

1105-1165: Consider adding documentation for depth tracking.

The depth tracking logic could benefit from documentation explaining the expected XML structure and what each depth level represents.

Add documentation like:

/// Parses a LineString element with the following structure:
/// <LineString>           // depth = 1
///   <posList>           // depth = 2
///     <coordinates>     // depth = 3
///   </posList>
/// </LineString>
fn parse_linestring(&mut self) -> Result<(), ParseError> {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f3104d8 and e74090d.

📒 Files selected for processing (1)
  • nusamai-citygml/src/parser.rs (12 hunks)
🔇 Additional comments (3)
nusamai-citygml/src/parser.rs (3)

Line range hint 105-113: LGTM: Default implementation for ParseContext is well-structured.

The implementation provides appropriate defaults with a valid file URL and NoopResolver.


400-451: LGTM: Well-structured implementation of MultiCurve property parsing.

The implementation follows consistent patterns with other geometry parsing methods and includes proper error handling.


1291-1294: LGTM: Proper error handling for text unescaping.

The implementation now properly handles potential errors when unescaping text content.

@miseyu miseyu merged commit d424f63 into main Dec 2, 2024
1 check passed
@miseyu miseyu deleted the feature/modify-parser branch December 2, 2024 06:02
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.

1 participant