Technical Requirements - treytomes/redstone_sim GitHub Wiki
- Programming Language: C# 10.0+
- Framework: .NET 9.0
- Graphics & I/O: OpenTK 4.x
- Testing Framework: xUnit 2.x
- Build System: .NET CLI / MSBuild
- Dependency Injection: Microsoft.Extensions.DependencyInjection
- Serialization: System.Text.Json
- Logging: Microsoft.Extensions.Logging
- Configuration: Microsoft.Extensions.Configuration
- Pattern: Model-View-ViewModel (MVVM) with Command pattern
- Structure: Modular, component-based design with clear separation of concerns
- Threading Model: Main thread for rendering, separate thread for simulation
- Simulation Core: Handles the logic and state of the redstone circuit
- Rendering Engine: Manages visualization using OpenTK
- Input Handler: Processes user input from keyboard/mouse
- UI Layer: Manages user interface elements and interactions
- Persistence Layer: Handles saving/loading circuits
-
Class:
GridSystem -
Responsibilities:
- Maintain the 2D grid structure
- Track component placement
- Handle coordinate transformations
- Support grid resizing operations
-
Key Methods:
PlaceComponent(Component component, Vector2i position)RemoveComponent(Vector2i position)GetComponentAt(Vector2i position)ResizeGrid(int width, int height)
-
Base Class:
RedstoneComponent(abstract) -
Derived Classes:
RedstoneWireRedstoneButtonRedstoneSwitchRedstoneTorchRedstoneRepeaterRedstoneTransistor
-
Interface:
IPowerableint PowerLevel { get; set; }void UpdatePowerState()bool CanReceivePowerFrom(Direction direction)bool CanProvidePowerTo(Direction direction)
-
Class:
SignalPropagator -
Responsibilities:
- Calculate signal paths
- Manage signal strength decay
- Handle update order
- Process component interactions
-
Key Methods:
PropagateSignals()CalculateUpdateOrder()UpdateComponentState(RedstoneComponent component)
-
Class:
SimulationController -
Responsibilities:
- Manage simulation tick rate
- Control simulation state (running, paused, step)
- Handle timing and synchronization
-
Key Methods:
Start()Pause()Step()SetSpeed(float ticksPerSecond)
-
Class:
RedstoneRenderer -
Responsibilities:
- Render grid and components
- Handle camera transformations
- Manage visual effects
-
Key Methods:
Initialize()Render(float deltaTime)UpdateViewport(int width, int height)
-
Class:
AssetManager -
Responsibilities:
- Load and manage textures
- Handle component visual states
- Provide sprite batching
-
Key Methods:
LoadTextures()GetComponentTexture(ComponentType type, PowerState state)UnloadAssets()
-
Class:
CameraController -
Responsibilities:
- Handle pan and zoom operations
- Convert between screen and world coordinates
- Manage view boundaries
-
Key Methods:
Pan(Vector2 delta)Zoom(float factor, Vector2 focusPoint)ScreenToWorld(Vector2 screenPos)WorldToScreen(Vector2 worldPos)
-
Class:
InputManager -
Responsibilities:
- Process keyboard and mouse input
- Map inputs to actions
- Handle input modes (build, select, etc.)
-
Key Methods:
ProcessInput()RegisterAction(InputType input, Action action)SetInputMode(InputMode mode)
-
Class:
ToolManager -
Responsibilities:
- Manage available tools (place, select, delete)
- Handle tool-specific input processing
- Coordinate tool state changes
-
Key Methods:
SelectTool(ToolType tool)ProcessToolInput(InputEvent input)CompleteToolAction()
-
Class:
UIManager -
Responsibilities:
- Manage UI elements
- Handle UI events
- Coordinate UI updates
-
Key Methods:
Initialize()ProcessUIEvents()UpdateUI()
-
Class:
ComponentPalette -
Responsibilities:
- Display available components
- Handle component selection
- Provide component information
-
Key Methods:
SelectComponent(ComponentType type)GetSelectedComponent()UpdatePaletteVisibility(bool visible)
-
Class:
AnalysisToolsPanel -
Responsibilities:
- Display signal tracing
- Show timing diagrams
- Present power statistics
-
Key Methods:
ShowSignalTrace(List<Vector2i> path)UpdateTimingDiagram(Dictionary<Vector2i, List<PowerState>> states)DisplayPowerStatistics(PowerStatistics stats)
-
Class:
CircuitPersistence -
Responsibilities:
- Serialize/deserialize circuit state
- Manage file operations
- Handle version compatibility
-
Key Methods:
SaveCircuit(string filename)LoadCircuit(string filename)ExportAsImage(string filename)
-
Class:
CircuitData -
Responsibilities:
- Define serializable circuit structure
- Track component metadata
- Store grid configuration
-
Properties:
Dictionary<Vector2i, ComponentData> ComponentsGridProperties GridConfigSimulationProperties SimConfig
- Target Frame Rate: 60+ FPS on standard hardware
-
Optimization Techniques:
- Sprite batching
- Frustum culling
- Level-of-detail rendering
- Hardware acceleration
- Target Update Rate: 20+ ticks per second with 1000+ components
-
Optimization Techniques:
- Spatial partitioning
- Dirty region tracking
- Lazy evaluation of inactive circuits
- Parallelized signal calculation where possible
- Maximum Memory Usage: <1GB for standard circuits
-
Techniques:
- Object pooling for frequently created/destroyed components
- Texture atlasing
- Efficient grid representation
- Framework: xUnit 2.x
- Coverage Target: 80%+ for core simulation logic
-
Key Test Areas:
- Component behavior
- Signal propagation
- Grid operations
- Serialization/deserialization
- Approach: Component interaction tests
-
Key Test Areas:
- Multi-component circuits
- Signal timing across components
- Save/load integrity
- Tools: Custom benchmarking harness
-
Metrics:
- FPS under various load conditions
- Simulation ticks per second
- Memory consumption
- Load/save times
- Approach: Automated UI tests + manual verification
-
Key Test Areas:
- Component placement
- Tool functionality
- Camera controls
- Develop basic component classes
- Create signal propagation system
- Build simulation tick controller
- Implement unit tests for core simulation logic
- Set up OpenTK rendering pipeline
- Implement camera system
- Create component visualization
- Develop input handling system
- Build basic tool functionality
- Add grid navigation controls
- Implement all basic components (wire, torch, button, etc.)
- Add transistor component with configurable logic
- Create component interaction rules
- Implement power level visualization
- Add component-specific unit tests
- Build component palette interface
- Implement selection and editing tools
- Create circuit analysis views
- Add simulation control panel
- Develop debug visualization options
- Implement circuit serialization
- Create save/load functionality
- Add circuit export capabilities
- Implement circuit sharing features
- Build file format validation
- Performance optimization
- Bug fixing
- UI refinement
- Documentation
- Final testing
- Rendering Approach: 2D sprite-based rendering using OpenTK's GL API
-
Shader Implementation:
- Basic vertex/fragment shaders for grid and components
- Special effects shaders for signal visualization
-
Window Management:
-
GameWindowsubclass for main application window - Event-driven rendering loop
- Vsync support
-
-
Mouse Input:
- Use OpenTK's
MouseMove,MouseDown,MouseUpevents - Implement click, drag, and scroll handling
- Use OpenTK's
-
Keyboard Input:
- Use OpenTK's keyboard events for shortcuts and controls
- Support for customizable key bindings
-
Storage: Sparse dictionary-based grid (
Dictionary<Vector2i, RedstoneComponent>) - Spatial Partitioning: Quad-tree for efficient spatial queries
- Chunk System: Optional chunking system for large circuits
RedstoneComponent (abstract)
├── WireComponent
├── SourceComponent (abstract)
│ ├── ButtonComponent
│ ├── SwitchComponent
│ └── TorchComponent
├── LogicComponent (abstract)
│ ├── RepeaterComponent
│ └── TransistorComponent
└── SpecialComponent (abstract)
└── ... (future components)
- Update Queue: Priority queue for component updates
- Dependency Graph: Directed graph for tracking signal dependencies
-
Propagation Algorithm:
- Identify changed power sources
- Build update graph
- Topologically sort components
- Process updates in order
- Format: Custom JSON-based format
-
Structure:
{ "version": "1.0", "metadata": { "name": "Example Circuit", "author": "User", "created": "2023-11-01T12:00:00Z" }, "grid": { "width": 100, "height": 100 }, "components": [ { "type": "wire", "position": { "x": 10, "y": 15 }, "properties": { } }, { "type": "repeater", "position": { "x": 11, "y": 15 }, "rotation": 1, "properties": { "delay": 2, "locked": false } } ], "powerStates": { "10,15": 0, "11,15": 0 } }
- Image Export: PNG with optional transparent background
- Circuit Sharing: Compressed binary format for efficient sharing
- UI rendering and updates
- Input processing
- OpenGL context operations
- Run simulation ticks at configured rate
- Process component updates
- Calculate signal propagation
- Thread-safe queue for cross-thread communication
- Double-buffered state for rendering
- Lock-free data structures where possible
- Custom exception types for simulation-specific errors
- Global exception handler for UI thread
- Graceful degradation for non-critical failures
- Structured logging using Microsoft.Extensions.Logging
- Log levels: Debug, Info, Warning, Error, Critical
- Log targets: Console, file, and in-application log viewer
-
OpenTK(4.x): Graphics and input handling -
Microsoft.Extensions.DependencyInjection: DI container -
Microsoft.Extensions.Logging: Logging infrastructure -
Microsoft.Extensions.Configuration: Configuration management -
System.Text.Json: JSON serialization -
xUnit(2.x): Testing framework -
Moq: Mocking library for testing -
BenchmarkDotNet: Performance testing
- Visual Studio 2022 or later / Visual Studio Code with C# extensions
- .NET 9.0 SDK
- Git for version control
- GitHub Actions for CI/CD
- Primary: Windows 10/11 (x64)
- Secondary: macOS, Linux (via .NET cross-platform capabilities)
-
Minimum Specifications:
- CPU: Dual-core 2.0 GHz or better
- RAM: 4 GB minimum, 8 GB recommended
- GPU: OpenGL 3.3+ compatible
- Storage: 100 MB for application, variable for circuit files
- Simulation tick rate consistency
- Rendering performance for large circuits
- Memory usage for component-dense areas
- Load/save times for large circuits
- Plugin architecture for future component types
- Event system for custom behaviors
- Scripting API for automation (future consideration)
- Follow Microsoft's C# coding conventions
- Use nullable reference types
- Implement proper XML documentation
- Follow SOLID principles
- Feature branching workflow
- Pull request reviews required
- Semantic versioning
- Automated CI/CD pipeline
- Unit tests required for all core simulation logic
- Integration tests for component interactions
- Performance tests for critical paths
- UI tests for main workflows
- API documentation generated from XML comments
- Architecture overview document
- User manual and tutorials
- Developer guidelines for contributions
This technical requirements document provides a comprehensive blueprint for implementing the 2D Redstone Circuit Simulator using C#, .NET 9.0, OpenTK, and xUnit. The modular architecture and clear separation of concerns will facilitate development across the implementation phases while ensuring the system meets all functional and performance requirements.