diff --git a/Developer-Docs/Core-Components.md b/Developer-Docs/Core-Components.md new file mode 100644 index 000000000..499d1f621 --- /dev/null +++ b/Developer-Docs/Core-Components.md @@ -0,0 +1,260 @@ +# ProBuilder Core Components + +This document details the fundamental classes and data structures that form the foundation of ProBuilder's mesh representation and manipulation system. + +## ProBuilderMesh - The Central Component + +**Location**: `Runtime/Core/ProBuilderMesh.cs` + +`ProBuilderMesh` is the heart of ProBuilder, extending `MonoBehaviour` to provide a Unity component that manages all mesh data and operations. + +### Key Responsibilities: +- **Mesh Data Storage**: Maintains vertices, faces, edges, and UV coordinates +- **Unity Integration**: Bridges between ProBuilder's format and Unity's Mesh system +- **Serialization**: Handles saving/loading of mesh data +- **Mesh Compilation**: Converts internal format to Unity Mesh for rendering + +### Key Properties: +```csharp +// Core mesh elements +public Face[] faces // Array of face definitions +public Vector3[] positions // Vertex positions in local space +public SharedVertex[] sharedVertices // Vertex sharing information + +// Material and UV data +public Vector2[] textures0 // Primary UV coordinates +public Material[] materials // Per-face materials +public AutoUnwrapSettings[] unwrapParameters // UV generation settings +``` + +### Important Methods: +- `ToMesh()`: Compiles ProBuilder format to Unity Mesh +- `Refresh()`: Updates visual representation +- `GetVertices()`: Returns all vertex data as Vertex structs +- `SetVertices()`: Updates vertex data from Vertex array + +## Face - Polygon Definition + +**Location**: `Runtime/Core/Face.cs` + +Represents a polygonal face composed of triangles with associated material and UV settings. + +### Structure: +```csharp +public class Face +{ + int[] indexes; // Triangle indices (always triangulated) + int smoothingGroup; // For normal smoothing + AutoUnwrapSettings uv; // UV projection settings + Material material; // Face material + bool manualUV; // UV coordinate source +} +``` + +### Key Concepts: +- **Triangle Storage**: All faces are internally stored as triangles, even if originally quads +- **Smoothing Groups**: Faces sharing a smoothing group have averaged normals +- **UV Modes**: Faces can use automatic UV projection or manual coordinates +- **Material Assignment**: Each face can have its own material + +## Edge - Vertex Connection + +**Location**: `Runtime/Core/Edge.cs` + +A simple structure representing a connection between two vertices. + +### Structure: +```csharp +public struct Edge +{ + public int a, b; // Vertex indices + + public bool IsValid() // Checks if edge points to valid vertices + public static Edge Empty // Represents invalid edge (-1, -1) +} +``` + +### Usage: +- **Topology Queries**: Finding adjacent faces, edge loops +- **Selection Operations**: Edge-based selection and manipulation +- **Mesh Operations**: Extrusion, loop cuts, beveling + +## Vertex - Point Data + +**Location**: `Runtime/Core/Vertex.cs` + +Comprehensive vertex structure containing all per-vertex attributes. + +### Structure: +```csharp +public struct Vertex +{ + public Vector3 position; // 3D position + public Color color; // Vertex color + public Vector3 normal; // Surface normal + public Vector4 tangent; // Tangent vector (with handedness in w) + + // UV coordinates (up to 4 channels) + public Vector2 uv0, uv2; + public Vector4 uv3, uv4; +} +``` + +### Notes: +- **Complete Attribute Set**: Contains all data needed for rendering +- **UV Channels**: Supports multiple UV sets for advanced materials +- **Vertex Colors**: Per-vertex color information for special effects + +## Shared Vertex System + +**Location**: `Runtime/Core/SharedVertex.cs` + +ProBuilder's sophisticated system for managing vertex sharing and topology. + +### Concept: +``` +Geometric Vertices: [A, B, C, D, E, F] +Shared Groups: [[A,D], [B,E], [C,F]] +``` + +Multiple mesh vertices can reference the same geometric position while maintaining different attributes (normals, UVs, colors). + +### SharedVertex Structure: +```csharp +public sealed class SharedVertex : IEnumerable +{ + int[] m_Vertices; // Array of vertex indices sharing position +} +``` + +### Benefits: +- **Hard/Soft Edges**: Control over normal smoothing +- **UV Seams**: Different UV coordinates at same position +- **Efficient Operations**: Topology queries and modifications +- **Undo/Redo**: Preserves sharing relationships + +## WingedEdge - Topology Navigation + +**Location**: `Runtime/Core/WingedEdge.cs` + +Advanced data structure for efficient mesh topology navigation, based on the [Winged Edge](https://en.wikipedia.org/wiki/Winged_edge) data structure. + +### Structure: +```csharp +public sealed class WingedEdge +{ + public EdgeLookup edge; // The edge this wing represents + public Face face; // Connected face + public WingedEdge next; // Next edge in face + public WingedEdge previous; // Previous edge in face + public WingedEdge opposite; // Edge on adjacent face +} +``` + +### Usage: +- **Mesh Traversal**: Navigate between adjacent faces and edges +- **Topology Queries**: Find edge loops, face neighbors +- **Validation**: Check for manifold geometry +- **Complex Operations**: Boolean operations, subdivision + +### Algorithm Reference: +The implementation follows the classic Winged Edge data structure described in: +- [Winged Edge Wikipedia](https://en.wikipedia.org/wiki/Winged_edge) +- Original paper: "Winged edge polyhedron representation" by Bruce Baumgart (1975) + +## Material and UV Management + +### AutoUnwrapSettings +**Location**: `Runtime/Core/AutoUnwrapSettings.cs` + +Controls automatic UV coordinate generation for faces. + +```csharp +public struct AutoUnwrapSettings +{ + public bool useWorldSpace; // Use world vs local coordinates + public bool flipU, flipV; // UV flipping + public Vector2 scale; // UV scaling + public Vector2 offset; // UV offset + public float rotation; // UV rotation + public Anchor anchor; // Projection anchor point +} +``` + +### UV Projection Methods: +1. **Planar**: Project along face normal +2. **Box**: Six-sided projection +3. **Cylindrical**: Wrap around cylinder +4. **Spherical**: Spherical projection + +### Built-in Materials +**Location**: `Runtime/Core/BuiltinMaterials.cs` + +Manages default materials for different render pipelines: +- **Standard**: Built-in render pipeline +- **URP**: Universal Render Pipeline +- **HDRP**: High Definition Render Pipeline + +## Selection and Picking + +### SelectionPicker +**Location**: `Runtime/Core/SelectionPicker.cs` + +Handles 3D picking and selection of mesh elements using GPU-based selection. + +### Approach: +1. **Render to Texture**: Draw mesh with unique colors per element +2. **Mouse Query**: Sample color at mouse position +3. **Color Decode**: Convert color back to element index + +### Benefits: +- **Accurate Selection**: Pixel-perfect element picking +- **Performance**: GPU acceleration for complex meshes +- **Occlusion**: Automatically handles depth testing + +## Utility Classes + +### Math Utilities +**Location**: `Runtime/Core/Math.cs` + +Mathematical functions specific to mesh operations: +- **Plane/Ray intersections** +- **Point-in-polygon tests** +- **Distance calculations** +- **Geometric projections** + +### Mesh Utilities +**Location**: `Runtime/Core/MeshUtility.cs` + +Helper functions for mesh data manipulation: +- **Vertex welding and splitting** +- **Normal calculation** +- **Bounds computation** +- **Mesh validation** + +## Performance Considerations + +### Memory Management: +- **Object Pooling**: Reuse temporary collections +- **Lazy Evaluation**: Calculate expensive data on demand +- **Dirty Flags**: Track what needs recalculation + +### Optimization Patterns: +- **Batch Operations**: Process multiple elements together +- **Spatial Indexing**: Use KdTree for spatial queries +- **Cache Friendly**: Minimize object allocations in hot paths + +## Common Patterns + +### Mesh Modification Workflow: +1. **Begin Operation**: `mesh.ToMesh()` and `mesh.Refresh()` +2. **Modify Data**: Update vertices, faces, or topology +3. **Validate**: Check mesh integrity +4. **Commit**: `mesh.ToMesh()` and refresh display + +### Error Handling: +- **Validation**: Check for degenerate geometry +- **Graceful Degradation**: Fall back to simpler operations +- **User Feedback**: Provide actionable error messages + +This foundation enables all higher-level operations while maintaining data integrity and performance. \ No newline at end of file diff --git a/Developer-Docs/Editor-Tools.md b/Developer-Docs/Editor-Tools.md new file mode 100644 index 000000000..0012f1fbc --- /dev/null +++ b/Developer-Docs/Editor-Tools.md @@ -0,0 +1,401 @@ +# ProBuilder Editor Tools and Architecture + +This document covers the editor-specific components of ProBuilder, including the tool system, selection management, UI components, and integration with Unity's editor framework. + +## Editor Architecture Overview + +The ProBuilder editor is built around several key systems: + +1. **ProBuilderEditor**: Central controller and tool management +2. **Selection System**: Element selection and manipulation +3. **Tool System**: Unified tool interface and interaction +4. **Menu Actions**: Extensible action system +5. **UI Components**: Windows, overlays, and gizmos + +## ProBuilderEditor - Central Controller + +**Location**: `Editor/EditorCore/ProBuilderEditor.cs` + +The main editor class that coordinates all ProBuilder functionality. + +### Key Responsibilities: +- **Tool Management**: Activate/deactivate editing tools +- **Selection Coordination**: Manage mesh and element selection +- **Event Handling**: Process mouse/keyboard input +- **UI Updates**: Refresh editor windows and gizmos +- **Undo/Redo**: Integration with Unity's undo system + +### Core Architecture: +```csharp +public sealed class ProBuilderEditor : IDisposable +{ + // Events for external systems + public static event Action> selectionUpdated; + public static event Action selectModeChanged; + public static event Action> afterMeshModification; + + // Current edit state + public static SelectMode selectMode { get; set; } + public static bool enabled { get; } +} +``` + +### Tool State Management: +ProBuilder maintains several tool states: +- **Object Mode**: Select entire ProBuilder objects +- **Vertex Mode**: Select and manipulate individual vertices +- **Edge Mode**: Select and manipulate edges +- **Face Mode**: Select and manipulate faces + +## Selection System + +**Location**: `Editor/EditorCore/MeshSelection.cs` + +Manages selection of ProBuilder meshes and their elements. + +### Selection Data Structure: +```csharp +public static class MeshSelection +{ + // Currently selected ProBuilder objects + public static IEnumerable topInternal { get; } + + // Active mesh (primary selection) + public static ProBuilderMesh activeMesh { get; } + + // Element selections per mesh + public static ReadOnlyCollection elementSelection { get; } + + // Selection bounds for gizmo positioning + public static Bounds bounds { get; } +} +``` + +### Selection Types: +1. **Object Selection**: Entire ProBuilderMesh objects +2. **Element Selection**: Vertices, edges, or faces within meshes +3. **Mixed Selection**: Combination of objects and elements + +### Selection Persistence: +The system maintains selection state across: +- **Edit Mode Changes**: Preserve selection when switching tools +- **Scene Changes**: Restore selection after scene reload +- **Undo Operations**: Proper selection handling with undo/redo + +## Scene View Integration + +### EditorSceneViewPicker +**Location**: `Editor/EditorCore/EditorSceneViewPicker.cs` + +Handles mouse interaction and element picking in the Scene View. + +### Picking Algorithm: +1. **Ray Casting**: Cast ray from mouse position +2. **Mesh Intersection**: Find intersection with ProBuilder meshes +3. **Element Identification**: Determine which vertex/edge/face was hit +4. **Selection Update**: Modify selection based on input modifiers + +### Input Handling: +```csharp +// Mouse input processing +private void OnSceneGUI(SceneView sceneView) +{ + Event evt = Event.current; + + if (evt.type == EventType.MouseDown) + HandleMouseDown(evt); + else if (evt.type == EventType.MouseDrag) + HandleMouseDrag(evt); + else if (evt.type == EventType.MouseUp) + HandleMouseUp(evt); +} +``` + +### Rectangle Selection: +Supports drag-selection of multiple elements: +1. **Start Drag**: Record initial mouse position +2. **Track Drag**: Update selection rectangle +3. **Element Testing**: Test which elements fall within rectangle +4. **Complete Selection**: Apply final selection state + +## Tool System + +ProBuilder integrates with Unity's EditorTools system for unified tool handling. + +### Base Tool Classes: + +#### EditorTool Integration: +```csharp +public abstract class ProBuilderTool : EditorTool +{ + public abstract void OnToolGUI(EditorWindow window); + public virtual bool IsAvailable() => true; + public virtual void OnActivated() { } + public virtual void OnWillBeDeactivated() { } +} +``` + +### Manipulation Tools: + +#### Position Tool +**Location**: `Editor/EditorCore/PositionTool.cs` +- **Function**: Move vertices, edges, or faces +- **Handles**: Unity's position handles with ProBuilder integration +- **Constraints**: Grid snapping, axis locking + +#### Vertex Manipulation Tool +**Location**: `Editor/EditorCore/VertexManipulationTool.cs` +- **Function**: Direct vertex editing with visual feedback +- **Features**: Multi-selection, proportional editing +- **Visualization**: Custom gizmos for selected elements + +### Shape Tools: + +#### Draw Shape Tool +**Location**: `Editor/EditorCore/DrawShapeTool.cs` +- **Function**: Create new shapes by drawing in Scene View +- **Interaction**: Click-and-drag to define shape bounds +- **Preview**: Real-time preview of shape being created + +#### Poly Shape Tool +**Location**: `Editor/EditorCore/PolyShapeTool.cs` +- **Function**: Create custom polygonal shapes +- **Workflow**: Click to place vertices, close to finish +- **Features**: Bezier curves, hole creation + +## Gizmo and Handle System + +### EditorHandleDrawing +**Location**: `Editor/EditorCore/EditorHandleDrawing.cs` + +Provides custom drawing functions for ProBuilder's 3D handles and gizmos. + +### Handle Types: +1. **Vertex Handles**: Small spheres for vertex selection +2. **Edge Handles**: Lines with midpoint indicators +3. **Face Handles**: Filled polygons with normal indicators +4. **Center Handles**: Pivot points for transformations + +### Drawing Optimization: +- **Culling**: Skip drawing handles outside view frustum +- **LOD**: Reduce detail for distant elements +- **Batching**: Group similar handle types for efficient rendering + +### Custom Gizmos: +```csharp +public static void DrawVertexGizmos(ProBuilderMesh mesh, IEnumerable vertices) +{ + foreach(int vertex in vertices) + { + Vector3 worldPos = mesh.transform.TransformPoint(mesh.positions[vertex]); + + // Draw selection indicator + if (IsSelected(vertex)) + DrawSelectedVertexGizmo(worldPos); + else + DrawUnselectedVertexGizmo(worldPos); + } +} +``` + +## Menu Action System + +**Location**: `Editor/MenuActions/` + +ProBuilder uses an extensible action system for tools and operations. + +### MenuAction Base Class: +```csharp +[ProBuilderMenuAction] +public abstract class MenuAction +{ + public abstract ActionResult DoAction(); + public virtual bool enabled => true; + public virtual string tooltip => ""; + public abstract string menuTitle { get; } +} +``` + +### Action Categories: +1. **Geometry Actions**: Extrude, subdivide, merge +2. **Selection Actions**: Select loops, grow selection +3. **Material Actions**: Apply materials, UV operations +4. **Export Actions**: OBJ export, mesh conversion + +### Dynamic Menu Building: +Actions are automatically discovered and added to menus: +```csharp +// Attribute-based registration +[ProBuilderMenuAction] +public class ExtrudeFaces : MenuAction +{ + public override string menuTitle => "Extrude Faces"; + + public override ActionResult DoAction() + { + return MeshSelection.selectedFaceCount > 0 + ? ExtrudeSelectedFaces() + : ActionResult.UserCanceled; + } +} +``` + +## UI Components + +### ProBuilder Windows: + +#### Shape Tool Window +- **Purpose**: Configure shape parameters +- **Features**: Real-time preview, parameter validation +- **Integration**: Updates shapes as parameters change + +#### Material Palette +**Location**: `Editor/EditorCore/MaterialPalette.cs` +- **Purpose**: Quick material assignment +- **Features**: Drag-and-drop, material preview +- **Storage**: Persistent material collections + +#### UV Editor +**Location**: `Editor/EditorCore/UVEditor.cs` +- **Purpose**: Visual UV coordinate editing +- **Features**: 2D UV view, manual coordinate adjustment +- **Tools**: UV selection, transformation, stitching + +### Overlay System: +**Location**: `Editor/Overlays/` + +ProBuilder uses Unity's Overlay system for floating UI panels: +- **Tool Settings**: Context-sensitive tool parameters +- **Element Info**: Display counts and statistics +- **Quick Actions**: Common operations in floating panels + +## Preference System + +**Location**: `Editor/EditorCore/PreferencesInternal.cs` + +Manages user preferences and editor settings. + +### Preference Categories: +1. **Tool Behavior**: Default tool settings, interaction modes +2. **Visual Settings**: Gizmo colors, handle sizes +3. **Performance**: Culling distances, update frequencies +4. **Shortcuts**: Keyboard bindings for actions + +### Settings Storage: +```csharp +[UserSetting("Mesh Editing", "Handle Size")] +internal static Pref s_HandleSize = new Pref("mesh.handleSize", 2.5f); + +[UserSetting("General", "Show Scene Info")] +internal static Pref s_ShowSceneInfo = new Pref("editor.showSceneInfo", false); +``` + +## Performance Considerations + +### Update Optimization: +- **Dirty Flags**: Track what needs updating +- **Frame Budgeting**: Spread expensive operations across frames +- **Conditional Updates**: Only update visible elements + +### Memory Management: +- **Handle Pooling**: Reuse handle objects +- **Texture Caching**: Cache gizmo textures and materials +- **Selection Caching**: Cache selection bounds and counts + +### Scene View Optimization: +```csharp +// Example: Conditional gizmo drawing +if (ShouldDrawHandles()) +{ + // Only draw if handles are visible and relevant + DrawElementHandles(); +} +``` + +## Integration with Unity Systems + +### EditorTools Framework: +ProBuilder tools inherit from Unity's `EditorTool` base class: +```csharp +[EditorTool("ProBuilder/Position Tool")] +public class PositionTool : ProBuilderTool +{ + public override void OnToolGUI(EditorWindow window) + { + // Tool-specific GUI handling + } +} +``` + +### Undo System Integration: +All operations properly integrate with Unity's undo: +```csharp +public override ActionResult DoAction() +{ + Undo.RecordObjects(Selection.transforms, "Action Name"); + + // Perform operation + + ProBuilderEditor.Refresh(); + return ActionResult.Success; +} +``` + +### Scene View Integration: +Custom drawing and interaction in Scene View: +```csharp +[InitializeOnLoad] +public class SceneViewIntegration +{ + static SceneViewIntegration() + { + SceneView.duringSceneGui += OnSceneGUI; + } + + static void OnSceneGUI(SceneView sceneView) + { + // Custom scene view drawing and interaction + } +} +``` + +## Event System + +### Core Events: +```csharp +// Selection changes +ProBuilderEditor.selectionUpdated += OnSelectionChanged; + +// Tool mode changes +ProBuilderEditor.selectModeChanged += OnSelectModeChanged; + +// Mesh modifications +ProBuilderEditor.afterMeshModification += OnMeshModified; +``` + +### Event Flow: +1. **User Input** → Scene View handlers +2. **Selection Change** → Update UI and gizmos +3. **Tool Activation** → Configure tool-specific UI +4. **Mesh Modification** → Refresh displays and validate + +## Debugging and Diagnostics + +### Debug Tools: +**Location**: `Debug/` + +1. **Mesh Validation**: Check for topology errors +2. **Performance Profiling**: Measure operation times +3. **Selection Debugging**: Visualize selection state +4. **Handle Debugging**: Show handle bounds and interactions + +### Debug Visualization: +```csharp +#if PROBUILDER_DEBUG + // Visualize internal data structures + DebugDrawWingedEdges(mesh); + DebugDrawSharedVertices(mesh); +#endif +``` + +This editor architecture provides a robust foundation for 3D modeling tools while maintaining good performance and integration with Unity's editor systems. \ No newline at end of file diff --git a/Developer-Docs/Getting-Started.md b/Developer-Docs/Getting-Started.md new file mode 100644 index 000000000..19ce27174 --- /dev/null +++ b/Developer-Docs/Getting-Started.md @@ -0,0 +1,533 @@ +# Getting Started with ProBuilder Development + +This guide provides practical information for developers working on ProBuilder, covering common development scenarios, debugging techniques, and best practices. + +## Development Environment Setup + +### Prerequisites: +- **Unity 6000.0+**: ProBuilder requires Unity 6000.0 or later +- **Package Manager**: Development typically done through Package Manager workflow +- **Git Knowledge**: Understanding of Git for version control +- **C# Proficiency**: Strong C# skills for Unity development + +### Project Structure Understanding: +``` +com.unity.probuilder/ +├── Runtime/ # Game-ready code (no editor dependencies) +├── Editor/ # Editor-only code (UnityEditor namespace) +├── External/ # Third-party libraries +├── Tests/ # Unit and integration tests +├── Debug/ # Debug tools and utilities +└── Developer-Docs/ # This documentation +``` + +### Build and Test: +ProBuilder follows Unity's package development patterns: +- **Assembly Definitions**: Separate assemblies for Runtime, Editor, and External code +- **Unity Test Framework**: Unit tests in Tests/ directory +- **Package Validation**: Automated validation for package requirements + +## Common Development Scenarios + +### 1. Fixing a Bug + +#### Step 1: Identify the Component +Determine which part of the system is affected: + +**UI/Interaction Issues** → `Editor/EditorCore/` +- Selection not working: Check `MeshSelection.cs`, `EditorSceneViewPicker.cs` +- Tool problems: Look in specific tool classes (`PositionTool.cs`, etc.) +- Menu actions: Check `MenuActions/` directory + +**Mesh Operation Issues** → `Runtime/MeshOperations/` +- Extrusion problems: `ExtrudeElements.cs` +- Subdivision issues: `Subdivision.cs`, `ConnectElements.cs` +- Boolean operations: `External/CSG/` +- Triangulation: `Triangulation.cs`, `External/Poly2Tri/` + +**Core Data Issues** → `Runtime/Core/` +- Mesh corruption: `ProBuilderMesh.cs`, `MeshValidation.cs` +- Selection problems: `SharedVertex.cs`, `Face.cs` +- UV issues: `AutoUnwrapSettings.cs`, `UVEditing.cs` + +#### Step 2: Reproduce the Issue +Create minimal test case: +```csharp +[Test] +public void TestExtrudeFaceIssue() +{ + // Create simple test mesh + var mesh = ShapeGenerator.CreateShape(ShapeType.Cube); + var face = mesh.faces[0]; + + // Perform operation that should work + var result = mesh.Extrude(new[] { face }, ExtrudeMethod.FaceNormal, 1f); + + // Verify result + Assert.IsNotNull(result); + Assert.IsTrue(mesh.faces.Length > 6); // Should have more faces after extrude +} +``` + +#### Step 3: Debug and Fix +Use ProBuilder's debugging tools: +```csharp +// Enable verbose logging +Log.SetLogLevel(LogLevel.All); + +// Validate mesh state +if (!mesh.IsValid()) +{ + Debug.LogError("Mesh validation failed: " + mesh.GetValidationErrors()); +} + +// Check topology +var wingedEdges = WingedEdge.GetWingedEdges(mesh); +if (wingedEdges.Any(we => we.opposite == null)) +{ + Debug.LogWarning("Non-manifold edges detected"); +} +``` + +### 2. Adding a New Feature + +#### Step 1: Determine Scope +Choose appropriate layer for your feature: + +**New Mesh Operation** → `Runtime/MeshOperations/` +Example: Adding a new extrusion mode +```csharp +public static class ExtrudeElements +{ + public static Face[] ExtrudeWithTwist(ProBuilderMesh mesh, + IEnumerable faces, + float distance, + float twistAngle) + { + // Implementation here + } +} +``` + +**New Editor Tool** → `Editor/EditorCore/` +Example: Adding a measurement tool +```csharp +[EditorTool("ProBuilder/Measure Tool")] +public class MeasureTool : ProBuilderTool +{ + public override void OnToolGUI(EditorWindow window) + { + // Tool implementation + } +} +``` + +**New Menu Action** → `Editor/MenuActions/` +Example: Adding a new geometry operation +```csharp +[ProBuilderMenuAction] +public class CreateSpiral : MenuAction +{ + public override string menuTitle => "Create Spiral"; + + public override ActionResult DoAction() + { + // Action implementation + } +} +``` + +#### Step 2: Follow Established Patterns +Study existing similar features: +- **Extrusion patterns**: Look at `ExtrudeElements.cs` +- **Selection patterns**: Check `ElementSelection.cs` +- **UI patterns**: Examine existing tool implementations + +#### Step 3: Add Tests +Create comprehensive tests for new functionality: +```csharp +[TestFixture] +public class SpiralCreationTests +{ + [Test] + public void CreateSpiral_ValidParameters_CreatesValidMesh() + { + // Test implementation + } + + [Test] + public void CreateSpiral_InvalidParameters_HandlesGracefully() + { + // Error handling test + } +} +``` + +### 3. Performance Optimization + +#### Identify Bottlenecks: +Use Unity Profiler to find performance issues: +```csharp +// Add profiler markers to your code +using Unity.Profiling; + +static readonly ProfilerMarker s_ExtrudeFacesMarker = new ProfilerMarker("ExtrudeFaces"); + +public static Face[] Extrude(...) +{ + using (s_ExtrudeFacesMarker.Auto()) + { + // Your operation here + } +} +``` + +#### Common Optimization Areas: +1. **Excessive Memory Allocation**: Use object pooling +2. **Redundant Calculations**: Cache expensive computations +3. **Inefficient Algorithms**: Replace with faster alternatives +4. **Unnecessary Updates**: Use dirty flags and batch operations + +#### Example Optimization: +```csharp +// Before: Inefficient per-vertex normal calculation +foreach (var vertex in vertices) +{ + vertex.normal = CalculateVertexNormal(vertex); +} + +// After: Batch normal calculation +var normals = CalculateVertexNormals(vertices); +for (int i = 0; i < vertices.Length; i++) +{ + vertices[i].normal = normals[i]; +} +``` + +## Debugging Techniques + +### 1. Visual Debugging + +#### Gizmo Drawing: +```csharp +void OnDrawGizmos() +{ + if (Application.isPlaying && debugMesh != null) + { + // Draw vertex positions + Gizmos.color = Color.red; + foreach (var pos in debugMesh.positions) + { + Gizmos.DrawSphere(transform.TransformPoint(pos), 0.1f); + } + + // Draw face normals + Gizmos.color = Color.blue; + foreach (var face in debugMesh.faces) + { + var center = debugMesh.GetFaceCenter(face); + var normal = debugMesh.GetFaceNormal(face); + Gizmos.DrawRay(transform.TransformPoint(center), + transform.TransformDirection(normal)); + } + } +} +``` + +#### Scene View Debugging: +```csharp +[InitializeOnLoad] +public class ProBuilderDebugDraw +{ + static ProBuilderDebugDraw() + { + SceneView.duringSceneGui += OnSceneGUI; + } + + static void OnSceneGUI(SceneView sceneView) + { + // Custom debug visualization + foreach (var mesh in FindObjectsOfType()) + { + DrawMeshDebugInfo(mesh); + } + } +} +``` + +### 2. Logging and Validation + +#### Structured Logging: +```csharp +using UnityEngine.ProBuilder; + +// Use ProBuilder's logging system +Log.Info("Starting mesh operation with {0} faces", faces.Length); +Log.Warning("Non-manifold edge detected at {0}", edgePosition); +Log.Error("Mesh validation failed: {0}", validationError); +``` + +#### Mesh Validation: +```csharp +public static bool ValidateMeshOperation(ProBuilderMesh mesh, string operationName) +{ + var errors = new List(); + + // Check basic mesh integrity + if (mesh.faces == null || mesh.positions == null) + errors.Add("Null mesh data"); + + // Check face validity + foreach (var face in mesh.faces) + { + if (face.indexes.Any(i => i >= mesh.vertexCount)) + errors.Add($"Face index out of bounds: {face}"); + } + + // Check shared vertex consistency + if (!SharedVertex.AreConsistent(mesh.sharedVertices, mesh.vertexCount)) + errors.Add("Shared vertex inconsistency"); + + if (errors.Any()) + { + Log.Error($"{operationName} validation failed:\n{string.Join("\n", errors)}"); + return false; + } + + return true; +} +``` + +### 3. Unit Test Debugging + +#### Test-Driven Development: +```csharp +[TestFixture] +public class MeshOperationTests +{ + ProBuilderMesh testMesh; + + [SetUp] + public void Setup() + { + testMesh = ShapeGenerator.CreateShape(ShapeType.Cube); + } + + [Test] + public void ExtrudeFace_SingleFace_CreatesCorrectTopology() + { + var originalFaceCount = testMesh.faceCount; + var face = testMesh.faces[0]; + + var result = testMesh.Extrude(new[] { face }, ExtrudeMethod.FaceNormal, 1f); + + Assert.IsNotNull(result); + Assert.AreEqual(1, result.Length); + Assert.Greater(testMesh.faceCount, originalFaceCount); + + // Validate mesh integrity + Assert.IsTrue(ValidateMeshOperation(testMesh, "ExtrudeFace")); + } +} +``` + +## Best Practices + +### 1. Code Organization + +#### Follow Namespace Conventions: +```csharp +// Runtime code +namespace UnityEngine.ProBuilder +{ + // Core classes, mesh operations +} + +namespace UnityEngine.ProBuilder.MeshOperations +{ + // Specific mesh algorithms +} + +// Editor code +namespace UnityEditor.ProBuilder +{ + // Editor tools and UI +} +``` + +#### Use Proper Access Modifiers: +```csharp +// Public API - external users +public class ProBuilderMesh : MonoBehaviour + +// Internal API - within ProBuilder +internal static class InternalUtility + +// Private implementation details +private void UpdateSharedVertexLookup() +``` + +### 2. Error Handling + +#### Graceful Degradation: +```csharp +public static ActionResult SubdivideFaces(ProBuilderMesh mesh, Face[] faces) +{ + try + { + if (!ValidateInput(mesh, faces)) + return ActionResult.UserCanceled; + + var result = PerformSubdivision(mesh, faces); + + if (!ValidateMeshOperation(mesh, "Subdivide")) + { + Log.Warning("Subdivision produced invalid geometry, reverting"); + return ActionResult.Failure; + } + + return ActionResult.Success; + } + catch (Exception e) + { + Log.Error($"Subdivision failed: {e.Message}"); + return ActionResult.Failure; + } +} +``` + +#### User-Friendly Messages: +```csharp +public override ActionResult DoAction() +{ + if (MeshSelection.selectedFaceCount == 0) + return new ActionResult(ActionResult.Status.UserCanceled, + "No faces selected for extrusion"); + + if (MeshSelection.selectedFaceCount > 1000) + return new ActionResult(ActionResult.Status.UserCanceled, + "Too many faces selected (limit: 1000)"); +} +``` + +### 3. Performance Guidelines + +#### Memory Management: +```csharp +// Use object pooling for frequently allocated objects +private static readonly ObjectPool> s_IntListPool = + new ObjectPool>(() => new List(), + list => list.Clear()); + +public static void SomeOperation() +{ + var tempList = s_IntListPool.Get(); + try + { + // Use tempList + } + finally + { + s_IntListPool.Release(tempList); + } +} +``` + +#### Batch Operations: +```csharp +// Prefer batch operations over individual element processing +public static void SetVertexColors(ProBuilderMesh mesh, + IEnumerable vertices, + Color color) +{ + mesh.SetVertexColors(vertices.Select(i => new KeyValuePair(i, color))); + mesh.RefreshColors(); // Single refresh call +} +``` + +### 4. Integration Patterns + +#### Undo Integration: +```csharp +[ProBuilderMenuAction] +public class MyAction : MenuAction +{ + public override ActionResult DoAction() + { + var selectedMeshes = MeshSelection.topInternal.ToArray(); + + // Record state for undo + Undo.RecordObjects(selectedMeshes, menuTitle); + + // Perform operation + foreach (var mesh in selectedMeshes) + { + DoOperationOnMesh(mesh); + } + + // Refresh displays + ProBuilderEditor.Refresh(); + + return ActionResult.Success; + } +} +``` + +## Testing Strategies + +### 1. Unit Tests +Focus on individual algorithms and data structures: +```csharp +[Test] +public void SharedVertex_MergeVertices_MaintainsTopology() +{ + // Test shared vertex operations +} + +[Test] +public void Triangulation_ConvexPolygon_ProducesValidTriangles() +{ + // Test triangulation algorithms +} +``` + +### 2. Integration Tests +Test complete workflows: +```csharp +[UnityTest] +public IEnumerator CreateCube_ExtrudeFace_ProducesValidMesh() +{ + // Create mesh, perform operations, validate result + yield return null; +} +``` + +### 3. Performance Tests +Measure operation performance: +```csharp +[Test, Performance] +public void ExtrudeFaces_1000Faces_CompletesInReasonableTime() +{ + // Performance benchmarking +} +``` + +## Resources and References + +### Documentation: +- [Unity Editor Scripting](https://docs.unity3d.com/Manual/editor-EditorWindows.html) +- [Unity Package Development](https://docs.unity3d.com/Manual/CustomPackages.html) +- [Unity Test Framework](https://docs.unity3d.com/Packages/com.unity.test-framework@latest) + +### Algorithms: +- [Computational Geometry](https://en.wikipedia.org/wiki/Computational_geometry) +- [Mesh Processing](http://www.cs.cmu.edu/~kmcrane/Projects/ModelRepository/) +- [Real-Time Rendering](http://www.realtimerendering.com/) + +### Tools: +- **Unity Profiler**: Performance analysis +- **Unity Test Runner**: Automated testing +- **Git**: Version control integration +- **Visual Studio/Rider**: IDE with Unity support + +This guide should provide a solid foundation for ProBuilder development work. Remember to always validate your changes thoroughly and follow the established patterns and conventions. \ No newline at end of file diff --git a/Developer-Docs/Mesh-Operations.md b/Developer-Docs/Mesh-Operations.md new file mode 100644 index 000000000..09c619087 --- /dev/null +++ b/Developer-Docs/Mesh-Operations.md @@ -0,0 +1,330 @@ +# ProBuilder Mesh Operations + +This document covers the algorithms and techniques used in ProBuilder for mesh manipulation, including geometric operations, triangulation, and topology modifications. + +## Overview + +The `Runtime/MeshOperations/` directory contains the core algorithms that transform and manipulate ProBuilder meshes. These operations form the backbone of ProBuilder's modeling capabilities. + +## Triangulation System + +**Location**: `Runtime/MeshOperations/Triangulation.cs` + +ProBuilder uses the **Poly2Tri** library for robust polygon triangulation. + +### Algorithm: Delaunay Triangulation with Sweep Line + +**External Library**: [Poly2Tri](https://github.com/jhasse/poly2tri) (located in `External/Poly2Tri/`) + +**Algorithm Reference**: +- [Delaunay Triangulation](https://en.wikipedia.org/wiki/Delaunay_triangulation) +- [Sweep Line Algorithm](https://en.wikipedia.org/wiki/Fortune%27s_algorithm) + +### Key Methods: +```csharp +public static bool Triangulate(IList points, out List indexes) +public static bool TriangulateVertices(Vector3[] vertices, out List triangles) +public static bool SortAndTriangulate(IList points, out List indexes) +``` + +### Process: +1. **Project to 2D**: Find best-fit plane for 3D polygon +2. **Sort Points**: Order vertices counter-clockwise +3. **Triangulate**: Apply Delaunay triangulation +4. **Map Back**: Convert 2D indices back to 3D vertex indices + +### Differences from Standard Implementation: +- **Unity Integration**: Modified to work with Unity's coordinate system +- **Error Handling**: Enhanced fallbacks for degenerate cases +- **Performance**: Cached triangulation context for repeated operations + +## Extrusion Operations + +**Location**: `Runtime/MeshOperations/ExtrudeElements.cs` + +Implements face and edge extrusion with multiple strategies. + +### Face Extrusion Methods: + +#### 1. Individual Faces (`ExtrudeMethod.IndividualFaces`) +Each face is extruded along its own normal: +``` +Original Face → Duplicate Face → Connect Edges +``` + +#### 2. Face Normal (`ExtrudeMethod.FaceNormal`) +Faces are grouped and extruded along averaged normal: +``` +Face Group → Calculate Average Normal → Extrude as Group +``` + +#### 3. Vertex Normal (`ExtrudeMethod.VertexNormal`) +Extrusion follows vertex normals for smooth results: +``` +Per-Vertex → Use Vertex Normal → Smooth Extrusion +``` + +### Edge Extrusion: +```csharp +public static Edge[] Extrude(ProBuilderMesh mesh, IEnumerable edges, + float distance, bool extrudeAsGroup, bool enableManifoldExtrude) +``` + +### Algorithm Steps: +1. **Manifold Check**: Verify edges can be extruded safely +2. **Direction Calculation**: Determine extrusion direction per edge +3. **Vertex Duplication**: Create new vertices for extruded elements +4. **Face Creation**: Generate connecting faces between original and extruded elements +5. **Topology Update**: Update shared vertex information + +## Subdivision Algorithms + +**Location**: `Runtime/MeshOperations/Subdivision.cs` + +### Connect Elements Algorithm +ProBuilder's subdivision uses a "connect elements" approach: + +```csharp +public static Face[] Subdivide(ProBuilderMesh pb, IList faces) +{ + return ConnectElements.Connect(pb, faces); +} +``` + +### Process: +1. **Center Point Insertion**: Add vertex at center of each face +2. **Edge Midpoints**: Add vertices at edge midpoints +3. **Face Subdivision**: Split each face into smaller faces +4. **Connectivity**: Maintain proper topology relationships + +### Subdivision Pattern: +``` +Original Quad: Subdivided: ++-------+ +---+---+ +| | | \ | / | +| + | → +---+---+ +| | | / | \ | ++-------+ +---+---+ +``` + +## Boolean Operations (CSG) + +**Location**: `External/CSG/` + +ProBuilder implements **Constructive Solid Geometry** using a modified CSG algorithm. + +### Algorithm Reference: +- [CSG Wikipedia](https://en.wikipedia.org/wiki/Constructive_solid_geometry) +- Based on: "Merging BSP trees yields polyhedral Boolean operations" by Bruce Naylor (1990) + +### Operations Supported: +1. **Union**: Combine two meshes +2. **Subtraction**: Remove one mesh from another +3. **Intersection**: Keep only overlapping regions + +### CSG Process: +1. **BSP Tree Construction**: Build Binary Space Partitioning trees for each mesh +2. **Tree Operations**: Perform boolean operations on BSP trees +3. **Polygon Classification**: Classify polygons as inside/outside/on boundary +4. **Mesh Reconstruction**: Convert result back to ProBuilder mesh + +### Implementation Details: +```csharp +// Located in External/CSG/CSG.cs +public static Model Union(Model a, Model b) +public static Model Subtract(Model a, Model b) +public static Model Intersect(Model a, Model b) +``` + +### Differences from Standard CSG: +- **Robust Handling**: Enhanced error handling for edge cases +- **Unity Integration**: Works with ProBuilder's mesh format +- **Performance**: Optimized for interactive use + +## Surface Topology Operations + +**Location**: `Runtime/MeshOperations/SurfaceTopology.cs` + +Handles complex topology modifications and mesh validation. + +### Key Operations: +- **Manifold Detection**: Check if mesh is manifold (every edge shared by exactly 2 faces) +- **Edge Loop Detection**: Find continuous chains of connected edges +- **Hole Filling**: Close gaps in mesh topology +- **Vertex Welding**: Merge nearby vertices + +### Manifold Validation: +```csharp +public static bool IsManifold(ProBuilderMesh mesh) +{ + // Check each edge is shared by exactly 2 faces + // Verify no T-junctions or non-manifold vertices +} +``` + +## Element Selection Algorithms + +**Location**: `Runtime/MeshOperations/ElementSelection.cs` + +Implements intelligent selection algorithms for mesh elements. + +### Selection Methods: + +#### 1. Edge Loops +Selects continuous chains of connected edges: +``` +Start Edge → Find Connected Edges → Continue Until Loop Closes +``` + +#### 2. Face Loops +Selects rings of faces around topology: +``` +Start Face → Find Adjacent Faces → Follow Ring Pattern +``` + +#### 3. Connected Elements +Selects all elements connected to seed selection: +``` +Seed Selection → Flood Fill → Stop at Boundaries +``` + +### Algorithm: Flood Fill Selection +1. **Initialize Queue**: Add seed elements to queue +2. **Process Queue**: For each element, find neighbors +3. **Filter Neighbors**: Apply selection criteria +4. **Add to Result**: Include valid neighbors in selection +5. **Repeat**: Until queue is empty + +## UV Operations + +**Location**: `Runtime/MeshOperations/UV/` + +### Automatic UV Unwrapping + +#### Planar Projection: +Projects UV coordinates along a plane normal: +```csharp +Vector2 uv = new Vector2( + Vector3.Dot(worldPos, uAxis), + Vector3.Dot(worldPos, vAxis) +); +``` + +#### Box Projection: +Six-sided projection for complex shapes: +1. **Determine Primary Axis**: Find face normal's dominant direction +2. **Select Projection Plane**: Choose appropriate face of box +3. **Project Coordinates**: Apply planar projection on selected plane + +#### Cylindrical Projection: +```csharp +float angle = Mathf.Atan2(localPos.z, localPos.x); +float height = localPos.y; +Vector2 uv = new Vector2(angle / (2f * Mathf.PI), height); +``` + +### UV Stitching +**Location**: `Runtime/MeshOperations/UV/TextureStitching.cs` + +Algorithms for connecting UV islands: +1. **Edge Detection**: Find UV seam edges +2. **Island Identification**: Group connected UV vertices +3. **Stitching Strategy**: Determine how to connect islands +4. **UV Adjustment**: Modify coordinates to eliminate seams + +## Mesh Validation and Repair + +**Location**: `Runtime/MeshOperations/MeshValidation.cs` + +### Validation Checks: +1. **Degenerate Triangles**: Triangles with zero area +2. **Duplicate Vertices**: Vertices at same position +3. **Invalid Indices**: Face indices out of bounds +4. **Topology Consistency**: Proper edge/face relationships + +### Repair Operations: +```csharp +public static ActionResult EnsureMeshIsValid(ProBuilderMesh mesh) +{ + // Remove degenerate faces + // Merge duplicate vertices + // Fix invalid topology + // Recalculate normals +} +``` + +## Performance Optimizations + +### Spatial Data Structures + +#### KdTree (External Library) +**Location**: `External/KdTree/` + +Used for spatial queries and nearest neighbor searches: +- **Vertex Welding**: Find nearby vertices to merge +- **Collision Detection**: Fast intersection tests +- **Selection Queries**: Find elements in 3D regions + +**Algorithm Reference**: [k-d tree](https://en.wikipedia.org/wiki/K-d_tree) + +### Batch Operations +Many operations are optimized to process multiple elements: +```csharp +// Instead of processing one face at a time +foreach(Face face in selection) + ExtrudeFace(face); + +// Batch process for better performance +ExtrudeFaces(selection); +``` + +### Memory Management +- **Object Pooling**: Reuse temporary collections +- **Lazy Calculation**: Compute expensive data only when needed +- **Dirty Tracking**: Update only what changed + +## Algorithm Complexity + +### Common Operations: +- **Triangulation**: O(n log n) where n = vertices +- **CSG Boolean**: O(n²) worst case, O(n log n) average +- **Subdivision**: O(n) where n = faces +- **Extrusion**: O(n) where n = selected elements +- **Selection**: O(n) for flood fill, O(1) for direct selection + +## Error Handling Patterns + +### Graceful Degradation: +1. **Validate Input**: Check for valid mesh state +2. **Detect Problems**: Identify potential issues early +3. **Apply Fixes**: Use repair algorithms when possible +4. **Fallback**: Use simpler operations if complex ones fail +5. **User Feedback**: Provide clear error messages + +### Common Edge Cases: +- **Non-manifold geometry**: Handle T-junctions and boundary edges +- **Degenerate polygons**: Skip zero-area faces +- **Floating point precision**: Use epsilon comparisons +- **Memory constraints**: Limit operation complexity + +## Integration Points + +### Unity Mesh System: +Operations work with Unity's mesh format through `ProBuilderMesh.ToMesh()`: +```csharp +// ProBuilder Operation +mesh.ExtrudeFaces(selectedFaces); + +// Convert to Unity Mesh +mesh.ToMesh(); +mesh.Refresh(); +``` + +### Undo System: +All operations are designed to work with Unity's Undo system: +```csharp +Undo.RecordObject(mesh, "Extrude Faces"); +// Perform operation +``` + +This modular design allows for complex mesh operations while maintaining performance and reliability. \ No newline at end of file diff --git a/Developer-Docs/Overview.md b/Developer-Docs/Overview.md new file mode 100644 index 000000000..3dfbaacf7 --- /dev/null +++ b/Developer-Docs/Overview.md @@ -0,0 +1,117 @@ +# ProBuilder Developer Documentation - Overview + +## Introduction + +ProBuilder is Unity's 3D modeling and level design tool that allows users to build, edit, and texture custom geometry directly within the Unity Editor. This documentation provides developers with a comprehensive understanding of ProBuilder's architecture, core systems, and codebase organization. + +## High-Level Architecture + +ProBuilder follows a modular architecture organized into several key layers: + +### 1. Runtime Core (`Runtime/Core/`) +The foundational layer containing core data structures and utilities: +- **ProBuilderMesh**: The central component that manages all mesh data +- **Face, Edge, Vertex**: Fundamental geometric primitives +- **Shared Vertex System**: Manages vertex sharing and topology +- **Material and UV Management**: Handles texturing and material assignment + +### 2. Mesh Operations (`Runtime/MeshOperations/`) +High-level mesh manipulation algorithms: +- **Extrusion**: Face and edge extrusion operations +- **Subdivision**: Mesh refinement and tessellation +- **Boolean Operations**: CSG operations for combining meshes +- **Triangulation**: Polygon tessellation using external algorithms +- **Element Selection**: Tools for selecting mesh components + +### 3. Shape Generation (`Runtime/Shapes/`) +Procedural shape creation system: +- **ShapeGenerator**: Factory for creating primitive shapes +- **Parametric Shapes**: Configurable geometric primitives +- **Custom Shape Support**: Framework for user-defined shapes + +### 4. Editor Tools (`Editor/EditorCore/`) +Editor-specific functionality and UI: +- **ProBuilderEditor**: Main editor controller and tool management +- **Selection System**: Mesh element selection and manipulation +- **Gizmos and Handles**: 3D manipulation widgets +- **Tool Windows**: UV editor, material palette, etc. + +### 5. External Libraries (`External/`) +Third-party algorithms and utilities: +- **Poly2Tri**: Delaunay triangulation library +- **CSG**: Constructive Solid Geometry operations +- **KdTree**: Spatial data structure for performance + +## Core Data Flow + +``` +User Input → Editor Tools → ProBuilderMesh → Mesh Operations → Unity Mesh + ↑ ↓ + └─────────── Scene View Rendering ←──────────────────────────┘ +``` + +1. **User Input**: Mouse/keyboard interactions in the Scene View +2. **Editor Tools**: Translate input into mesh operations +3. **ProBuilderMesh**: Central data structure holding all mesh information +4. **Mesh Operations**: Algorithms that modify the ProBuilderMesh +5. **Unity Mesh**: Final compiled mesh for rendering + +## Key Design Principles + +### 1. Separation of Concerns +- **Runtime**: Core data structures and algorithms (game-ready) +- **Editor**: Tools and UI components (editor-only) +- **External**: Third-party libraries (isolated dependencies) + +### 2. Non-Destructive Editing +ProBuilder maintains its own mesh representation (`ProBuilderMesh`) separate from Unity's `Mesh` component, allowing for: +- Undo/Redo operations +- Preservation of topology information +- Complex mesh operations without data loss + +### 3. Element-Based Selection +The system operates on three levels of mesh elements: +- **Vertices**: Individual points in 3D space +- **Edges**: Connections between two vertices +- **Faces**: Polygonal surfaces defined by vertex loops + +### 4. Shared Vertex Management +ProBuilder uses a sophisticated shared vertex system where: +- Multiple mesh vertices can reference the same geometric position +- Allows for hard/soft edge control +- Enables complex topology operations + +## Package Structure + +``` +com.unity.probuilder/ +├── Runtime/ +│ ├── Core/ # Core data structures +│ ├── MeshOperations/ # Mesh manipulation algorithms +│ └── Shapes/ # Shape generation +├── Editor/ +│ ├── EditorCore/ # Core editor functionality +│ ├── MenuActions/ # Menu system and actions +│ └── Overlays/ # UI overlays and windows +├── External/ # Third-party libraries +├── Debug/ # Debug tools and utilities +└── Developer-Docs/ # This documentation +``` + +## Getting Started + +For developers looking to: + +- **Fix bugs**: Start with the relevant module (Core, MeshOperations, or Editor) +- **Add features**: Understand the data flow and identify the appropriate layer +- **Extend functionality**: Review the MenuActions and tool architecture +- **Optimize performance**: Focus on MeshOperations and External algorithms + +Continue reading the specific documentation sections for detailed information about each component. + +## Documentation Index + +1. [Core Components](Core-Components.md) - Deep dive into fundamental classes +2. [Mesh Operations](Mesh-Operations.md) - Algorithms and mesh manipulation +3. [Editor Tools](Editor-Tools.md) - Editor architecture and tools +4. [Getting Started](Getting-Started.md) - Practical development guide \ No newline at end of file diff --git a/Developer-Docs/README.md b/Developer-Docs/README.md new file mode 100644 index 000000000..38323b814 --- /dev/null +++ b/Developer-Docs/README.md @@ -0,0 +1,140 @@ +# ProBuilder Developer Documentation + +This folder contains comprehensive technical documentation for developers working on the ProBuilder codebase. The documentation covers architecture, algorithms, and practical development guidance. + +## Quick Start + +If you're new to ProBuilder development: + +1. **Start with [Overview.md](Overview.md)** - Get a high-level understanding of the system architecture +2. **Read [Getting-Started.md](Getting-Started.md)** - Learn practical development workflows +3. **Dive deeper** with the specific component documentation as needed + +## Documentation Structure + +### [Overview.md](Overview.md) +High-level architecture and system overview including: +- Core system layers (Runtime, Editor, External) +- Data flow and design principles +- Package structure and organization +- Key concepts and terminology + +### [Core-Components.md](Core-Components.md) +Deep dive into fundamental classes and data structures: +- **ProBuilderMesh** - Central mesh component +- **Face, Edge, Vertex** - Geometric primitives +- **Shared Vertex System** - Topology management +- **WingedEdge** - Advanced topology navigation +- **Material and UV systems** + +### [Mesh-Operations.md](Mesh-Operations.md) +Algorithms and techniques for mesh manipulation: +- **Triangulation** - Poly2Tri Delaunay triangulation +- **Extrusion** - Face and edge extrusion algorithms +- **Subdivision** - Connect elements algorithm +- **Boolean Operations** - CSG using BSP trees +- **UV Operations** - Automatic unwrapping and stitching + +### [Editor-Tools.md](Editor-Tools.md) +Editor architecture and tool system: +- **ProBuilderEditor** - Central controller +- **Selection System** - Element selection and management +- **Tool System** - Unity EditorTools integration +- **Scene View Integration** - 3D interaction and picking +- **UI Components** - Windows, overlays, and gizmos + +### [Getting-Started.md](Getting-Started.md) +Practical development guide covering: +- **Development scenarios** - Bug fixes, new features, optimization +- **Debugging techniques** - Visual debugging, logging, validation +- **Best practices** - Code organization, error handling, performance +- **Testing strategies** - Unit tests, integration tests, performance tests + +## Key External Libraries + +ProBuilder integrates several external libraries for specialized algorithms: + +### Poly2Tri (`External/Poly2Tri/`) +- **Purpose**: Robust polygon triangulation +- **Algorithm**: Delaunay triangulation using sweep line +- **Reference**: [Poly2Tri GitHub](https://github.com/jhasse/poly2tri) +- **Usage**: Converting polygonal faces to triangles for rendering + +### CSG (`External/CSG/`) +- **Purpose**: Constructive Solid Geometry operations +- **Algorithm**: BSP tree-based boolean operations +- **Reference**: [CSG Wikipedia](https://en.wikipedia.org/wiki/Constructive_solid_geometry) +- **Usage**: Union, subtraction, and intersection of meshes + +### KdTree (`External/KdTree/`) +- **Purpose**: Spatial data structure for performance +- **Algorithm**: k-dimensional tree for nearest neighbor queries +- **Reference**: [k-d tree Wikipedia](https://en.wikipedia.org/wiki/K-d_tree) +- **Usage**: Vertex welding, collision detection, spatial queries + +## Algorithm References + +The documentation includes links to external resources explaining the algorithms used: + +- **[Winged Edge Data Structure](https://en.wikipedia.org/wiki/Winged_edge)** - Topology navigation +- **[Delaunay Triangulation](https://en.wikipedia.org/wiki/Delaunay_triangulation)** - Robust polygon tessellation +- **[Fortune's Algorithm](https://en.wikipedia.org/wiki/Fortune%27s_algorithm)** - Sweep line triangulation +- **[BSP Trees](https://en.wikipedia.org/wiki/Binary_space_partitioning)** - Spatial partitioning for CSG + +## Development Workflow + +### For Bug Fixes: +1. Identify the affected component using [Getting-Started.md](Getting-Started.md) +2. Study the relevant algorithm documentation +3. Create a minimal reproduction case +4. Debug using the techniques described +5. Validate the fix with existing tests + +### For New Features: +1. Understand the architecture from [Overview.md](Overview.md) +2. Identify the appropriate layer for your feature +3. Study similar existing features for patterns +4. Implement following the established conventions +5. Add comprehensive tests and documentation + +### For Performance Issues: +1. Profile to identify bottlenecks +2. Check [Mesh-Operations.md](Mesh-Operations.md) for algorithm complexity +3. Apply optimization techniques from [Getting-Started.md](Getting-Started.md) +4. Validate performance improvements with benchmarks + +## Contributing Guidelines + +When working on ProBuilder: + +- **Follow Established Patterns** - Study existing code for conventions +- **Maintain Compatibility** - Consider runtime vs editor boundaries +- **Add Tests** - Especially for new algorithms and edge cases +- **Document Algorithms** - Include references for complex algorithms +- **Consider Performance** - Profile operations on large meshes +- **Validate Thoroughly** - Mesh operations must maintain topology integrity + +## Validation and Testing + +ProBuilder includes extensive validation systems: + +- **Mesh Validation** - Check topology integrity after operations +- **Unit Tests** - Algorithm correctness and edge case handling +- **Integration Tests** - Complete workflow validation +- **Performance Tests** - Ensure operations scale appropriately + +See [Getting-Started.md](Getting-Started.md) for detailed testing strategies. + +## Additional Resources + +### Unity Documentation: +- [Unity Editor Scripting](https://docs.unity3d.com/Manual/editor-EditorWindows.html) +- [Unity Package Development](https://docs.unity3d.com/Manual/CustomPackages.html) +- [Unity Test Framework](https://docs.unity3d.com/Packages/com.unity.test-framework@latest) + +### Computational Geometry: +- [Real-Time Rendering Book](http://www.realtimerendering.com/) +- [Computational Geometry Algorithms](https://en.wikipedia.org/wiki/Computational_geometry) +- [Mesh Processing Library](http://www.cs.cmu.edu/~kmcrane/Projects/ModelRepository/) + +This documentation is designed to help developers understand, maintain, and extend ProBuilder's capabilities while preserving its robustness and performance characteristics. \ No newline at end of file