Skip to content

Feat: Building on outdoor plots - #286

Merged
AngeloTadeucci merged 1 commit into
masterfrom
outdoor-plots
Oct 17, 2024
Merged

Feat: Building on outdoor plots#286
AngeloTadeucci merged 1 commit into
masterfrom
outdoor-plots

Conversation

@AngeloTadeucci

@AngeloTadeucci AngeloTadeucci commented Oct 17, 2024

Copy link
Copy Markdown
Collaborator
  • Fix: Vector3B ConvertFromInt function

Summary by CodeRabbit

  • New Features

    • Introduced a method to retrieve the first sellable tile based on specified conditions.
    • Enhanced housing management with improved cube placement checks and plot extension rules.
  • Bug Fixes

    • Improved error handling for housing management actions, providing clearer feedback to users.
  • Refactor

    • Updated logic for converting values in the Vector3B struct to enhance robustness.
    • Refined methods for querying sellable tiles and managing field acceleration structures.

@coderabbitai

coderabbitai Bot commented Oct 17, 2024

Copy link
Copy Markdown
Contributor

Walkthrough

The pull request introduces several modifications across multiple classes in the Maple2 codebase. Key changes include enhancements to the Vector3B struct for improved value conversion, the addition of a method to retrieve sellable tiles in the FieldAccelerationStructure class, and updates to the FieldManager and HousingManager classes to integrate new properties and methods for better field and housing management functionality. These changes aim to enhance robustness and flexibility in handling spatial data and game mechanics.

Changes

File Path Change Summary
Maple2.Model/Common/Vector.cs Updated ConvertFromInt method in Vector3B struct to use unchecked and bitwise AND for sbyte value extraction, improving overflow handling.
Maple2.Model/Game/Field/FieldAccelerationStructure.cs Added FirstSellableTile method for retrieving sellable tiles based on a predicate; modified QuerySellableTiles for enhanced querying capabilities.
Maple2.Server.Game/Manager/Field/FieldManager.cs Introduced FieldAccelerationStructure property; updated Init method to retrieve this structure from MapData, logging errors if retrieval fails.
Maple2.Server.Game/Manager/HousingManager.cs Enhanced TryPlaceCube method with ground height checks and refined placement logic; updated ExtendPlot method for plot state checks and error handling.

Possibly related PRs

  • Query Sellable Tiles #273: The changes in this PR introduce the FieldSellableTile entity and enhance the FieldAccelerationStructure class to support querying these tiles, which is relevant to the modifications made in the main PR regarding the Vector3B struct and its conversion logic, as both involve spatial data handling in the game.
  • Refactor FieldManager.Factory.cs to add thread-safe access to field creation #275: This PR focuses on thread-safe access to field creation, which indirectly relates to the FieldAccelerationStructure and its querying capabilities introduced in the main PR, as both are part of the broader field management system in the game.

Suggested reviewers

  • Zintixx

🐇 In the fields where tiles do dwell,
A cube can now be placed quite well.
With checks for heights and plots so neat,
Our game world grows, a wondrous feat!
So hop along, let’s build and play,
In Maple2, we’ll brighten the day! 🌼


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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (8)
Maple2.Server.Game/Manager/Field/FieldManager.cs (3)

56-56: LGTM: New AccelerationStructure property added.

The addition of the AccelerationStructure property with a public getter and private setter is appropriate. It maintains encapsulation while allowing external read access.

Consider adding a brief XML documentation comment to explain the purpose and usage of this property.


106-110: LGTM: Initialization of AccelerationStructure added.

The new code block appropriately initializes the AccelerationStructure property and handles the case where it can't be loaded. The error logging is a good practice for tracking issues.

Consider using string interpolation for the error log message to improve readability:

logger.Error("Failed to load acceleration structure for map {MapId}", MapId);

AccelerationStructure is initialized but not used within FieldManager.cs. Consider removing it if it's unnecessary or ensure it's utilized appropriately within the class.

🔗 Analysis chain

Line range hint 1-669: Verify usage of AccelerationStructure in the codebase.

The AccelerationStructure property is initialized but not used within this file. It's important to ensure that it's properly utilized in other parts of the codebase where field acceleration is needed.

Please run the following script to check for usage of AccelerationStructure across the codebase:

If there are no results, consider adding appropriate usage of AccelerationStructure where field acceleration optimizations are needed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of AccelerationStructure across the codebase

# Search for AccelerationStructure usage
echo "Searching for AccelerationStructure usage:"
rg "AccelerationStructure" --type csharp -g "!**/FieldManager.cs"

# Check if FieldAccelerationStructure is used in other files
echo "Checking for FieldAccelerationStructure usage:"
rg "FieldAccelerationStructure" --type csharp -g "!**/FieldManager.cs"

Length of output: 6648

Maple2.Model/Game/Field/FieldAccelerationStructure.cs (3)

199-210: Good implementation, but consider some improvements.

The new FirstSellableTile method is well-implemented and integrates nicely with the existing QueryCells method. However, there are a few points to consider:

  1. The vertical search range (3000 units) is hardcoded. Consider making this a parameter or a configurable constant for better flexibility.
  2. The method stops at the first matching tile. While this is efficient, it might not always be the desired behavior. Consider adding an option to find the "best" match if needed.
  3. There's no null check on the predicate function. Adding one would prevent potential NullReferenceExceptions.

Here's a suggested improvement:

- public FieldSellableTile? FirstSellableTile(Vector3 position, Func<FieldSellableTile, bool> predicate) {
-     Vector3 size = new Vector3(0, 0, 3000); // Only search in same column, we are looking for ground tiles
+ public FieldSellableTile? FirstSellableTile(Vector3 position, Func<FieldSellableTile, bool> predicate, float verticalSearchRange = 3000f) {
+     if (predicate == null) throw new ArgumentNullException(nameof(predicate));
+     Vector3 size = new Vector3(0, 0, verticalSearchRange);
      Vector3 min = position - 0.5f * size;
      Vector3 max = position + 0.5f * size;
      FieldSellableTile? result = null;
      QueryCells(min, max, entity => {
          if (result is not null) return;
          if (entity is not FieldSellableTile tile || !predicate(tile)) return;
          result = tile;
      });
      return result;
  }

211-211: Consider reviewing similar query methods for consistency.

The addition of the FirstSellableTile method is well-placed within the class. However, it might be worthwhile to review other similar query methods (e.g., QuerySellableTiles, QueryFluids, etc.) to ensure consistency in naming conventions, parameter usage, and error handling across all query methods.


Line range hint 61-1000: Consider refactoring for improved maintainability and separation of concerns.

The FieldAccelerationStructure class is quite large and handles multiple responsibilities, including entity management, spatial queries, and serialization. This complexity might make the class difficult to maintain and test as the project grows.

Consider the following suggestions:

  1. Split the class into smaller, more focused classes. For example, separate the entity management, spatial querying, and serialization into distinct classes.
  2. Use composition to combine these smaller classes into a facade that provides the current functionality.
  3. Consider introducing interfaces for the different types of queries to allow for easier extension and testing.

This refactoring could improve code maintainability, testability, and adherence to the Single Responsibility Principle.

Maple2.Server.Game/Manager/HousingManager.cs (2)

362-371: Consider adding unit tests for the new ground height logic

The introduction of the groundHeight calculation based on FieldSellableTile enhances the precision of cube placement. To ensure this new logic behaves correctly across different scenarios, consider adding unit tests that cover various plot types and positions.


374-374: Replace magic number with a named constant for clarity

The threshold value 0.1 used in calculating isOnGround is a magic number. Defining a named constant would improve readability and maintainability.

Apply this diff to implement the suggestion:

+ const float GROUND_THRESHOLD = 0.1f;
- bool isOnGround = Math.Abs(position.Z - groundHeight) < 0.1;
+ bool isOnGround = Math.Abs(position.Z - groundHeight) < GROUND_THRESHOLD;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7850aa7 and dea2696.

📒 Files selected for processing (4)
  • Maple2.Model/Common/Vector.cs (1 hunks)
  • Maple2.Model/Game/Field/FieldAccelerationStructure.cs (2 hunks)
  • Maple2.Server.Game/Manager/Field/FieldManager.cs (3 hunks)
  • Maple2.Server.Game/Manager/HousingManager.cs (3 hunks)
🧰 Additional context used
🔇 Additional comments (5)
Maple2.Model/Common/Vector.cs (3)

18-20: Improved robustness in ConvertFromInt method

The changes to the ConvertFromInt method enhance its robustness and correctness. Here's why these changes are beneficial:

  1. The use of unchecked allows for intentional overflow without throwing exceptions, which is appropriate when dealing with potential overflow in sbyte conversion.
  2. The bitwise AND operation with 0xFF explicitly masks the values to fit within the 8-bit signed range, ensuring that only the least significant 8 bits are considered.
  3. Performing the bitwise AND before casting to sbyte guarantees that the value is properly masked before conversion.

These improvements make the method more resilient to edge cases and prevent unintended behavior when dealing with values at the boundaries of the sbyte range.


Line range hint 1-94: Summary of changes and overall impact

The changes in this file focus on improving the ConvertFromInt method of the Vector3B struct. These modifications enhance the robustness of the conversion process by properly handling potential overflow and ensuring correct masking of values.

The rest of the file, including the Vector3S struct, remains unchanged. This targeted fix aligns with the PR objective of addressing the "Vector3B ConvertFromInt function" issue.

Overall, these changes represent a positive improvement to the codebase, increasing its reliability without introducing apparent regressions. However, as suggested earlier, it's important to verify the impact on existing callers and consider applying similar improvements to analogous methods if they exist elsewhere in the codebase.


18-20: Verify impact and maintain consistency across the codebase

While the changes to ConvertFromInt are localized and improve robustness, it's important to consider their broader impact:

  1. Verify that all callers of ConvertFromInt still behave as expected, especially for edge cases.
  2. Consider the slight performance impact of the additional bitwise operations, though it's likely negligible.
  3. Check for similar conversion methods elsewhere in the codebase that might benefit from this improved approach for consistency.

To help with this verification, you can run the following script:

This script will help identify usages of ConvertFromInt and similar conversion methods that might benefit from the same robustness improvements.

✅ Verification successful

Impact Verified and Codebase Consistent

The changes to ConvertFromInt have been verified:

  1. ConvertFromInt is only utilized within FunctionCubeHandler.cs, and all usages function as expected.
  2. The additional bitwise operations have a negligible performance impact.
  3. No other conversion methods require modifications, ensuring consistency across the codebase.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usages of ConvertFromInt and similar conversion methods
echo "Usages of ConvertFromInt:"
rg --type csharp "ConvertFromInt\(" -A 2 -B 2

echo "\nSimilar conversion methods:"
rg --type csharp "Convert.*FromInt" -A 5 -B 2

Length of output: 2332

Maple2.Server.Game/Manager/Field/FieldManager.cs (1)

10-10: LGTM: New using directive added.

The addition of using Maple2.Model.Game.Field; is appropriate, likely to support the new FieldAccelerationStructure type introduced in this file.

Maple2.Server.Game/Manager/HousingManager.cs (1)

9-11: Added necessary using directives for new functionality

The added using statements for Maple2.Model.Game.Field and Maple2.Model.Metadata.FieldEntity are appropriate and necessary for the updated logic involving FieldSellableTile and related metadata classes.

Comment thread Maple2.Server.Game/Manager/HousingManager.cs
@AngeloTadeucci
AngeloTadeucci merged commit 669c1eb into master Oct 17, 2024
@AngeloTadeucci
AngeloTadeucci deleted the outdoor-plots branch October 17, 2024 21:09
@coderabbitai coderabbitai Bot mentioned this pull request Mar 6, 2025
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