McRogueFace/src/PyTimer.h

90 lines
4.4 KiB
C
Raw Normal View History

Squashed commit of 53 Commits: [alpha_streamline_2] * Field of View, Pathing courtesy of libtcod * python-tcod emulation at `mcrfpy.libtcod` - partial implementation * documentation, tutorial drafts: in middling to good shape ┌────────────┬────────────────────┬───────────┬────────────┬───────────────┬────────────────┬────────────────┬─────────────┐ │ Date │ Models │ Input │ Output │ Cache Create │ Cache Read │ Total Tokens │ Cost (USD) │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-05 │ - opus-4 │ 13,630 │ 159,500 │ 3,854,900 │ 84,185,034 │ 88,213,064 │ $210.72 │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-06 │ - opus-4 │ 5,814 │ 113,190 │ 4,242,407 │ 150,191,183 │ 154,552,594 │ $313.41 │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-07 │ - opus-4 │ 7,244 │ 104,599 │ 3,894,453 │ 81,781,179 │ 85,787,475 │ $184.46 │ │ │ - sonnet-4 │ │ │ │ │ │ │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-08 │ - opus-4 │ 50,312 │ 158,599 │ 5,021,189 │ 60,028,561 │ 65,258,661 │ $167.05 │ │ │ - sonnet-4 │ │ │ │ │ │ │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-09 │ - opus-4 │ 6,311 │ 109,653 │ 4,171,140 │ 80,092,875 │ 84,379,979 │ $193.09 │ │ │ - sonnet-4 │ │ │ │ │ │ │ └────────────┴────────────────────┴───────────┴────────────┴───────────────┴────────────────┴────────────────┴─────────────┘ 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> Author: John McCardle <mccardle.john@gmail.com> Draft tutorials Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP with FOV, A* pathfinding, and GUI text widget completions - Mark TCOD Integration Sprint as complete - Document FOV system with perspective rendering implementation - Update UIEntity pathfinding status to complete with A* and caching - Add comprehensive achievement entry for July 10 work - Reflect current engine capabilities accurately The engine now has all core roguelike mechanics: - Field of View with per-entity visibility - Pathfinding (both Dijkstra and A*) - Text input for in-game consoles - Performance optimizations throughout Author: John McCardle <mccardle.john@gmail.com> feat(engine): implement perspective FOV, pathfinding, and GUI text widgets Major Engine Enhancements: - Complete FOV (Field of View) system with perspective rendering - UIGrid.perspective property for entity-based visibility - Three-layer overlay colors (unexplored, explored, visible) - Per-entity visibility state tracking - Perfect knowledge updates only for explored areas - Advanced Pathfinding Integration - A* pathfinding implementation in UIGrid - Entity.path_to() method for direct pathfinding - Dijkstra maps for multi-target pathfinding - Path caching for performance optimization - GUI Text Input Widgets - TextInputWidget class with cursor, selection, scrolling - Improved widget with proper text rendering and input handling - Example showcase of multiple text input fields - Foundation for in-game console and chat systems - Performance & Architecture Improvements - PyTexture copy operations optimized - GameEngine update cycle refined - UIEntity property handling enhanced - UITestScene modernized Test Suite: - Interactive visibility demos showing FOV in action - Pathfinding comparison (A* vs Dijkstra) - Debug utilities for visibility and empty path handling - Sizzle reel demo combining pathfinding and vision - Multiple text input test scenarios This commit brings McRogueFace closer to a complete roguelike engine with essential features like line-of-sight, intelligent pathfinding, and interactive text input capabilities. Author: John McCardle <mccardle.john@gmail.com> feat(demos): enhance interactive pathfinding demos with entity.path_to() - dijkstra_interactive_enhanced.py: Animation along paths with smooth movement - M key to start movement animation - P to pause/resume - R to reset positions - Visual path gradient for better clarity - pathfinding_showcase.py: Advanced multi-entity behaviors - Chase mode: enemies pursue player - Flee mode: enemies avoid player - Patrol mode: entities follow waypoints - WASD player movement - Dijkstra distance field visualization (D key) - Larger dungeon map with multiple rooms - Both demos use new entity.path_to() method - Smooth interpolated movement animations - Real-time pathfinding recalculation - Comprehensive test coverage These demos showcase the power of integrated pathfinding for game AI. Author: John McCardle <mccardle.john@gmail.com> feat(entity): implement path_to() method for entity pathfinding - Add path_to(target_x, target_y) method to UIEntity class - Uses existing Dijkstra pathfinding implementation from UIGrid - Returns list of (x, y) coordinate tuples for complete path - Supports both positional and keyword argument formats - Proper error handling for out-of-bounds and no-grid scenarios - Comprehensive test suite covering normal and edge cases Part of TCOD integration sprint - gives entities immediate pathfinding capabilities. Author: John McCardle <mccardle.john@gmail.com> docs: update roadmap with Dijkstra pathfinding progress - Mark UIGrid TCOD Integration as completed - Document critical PyArg bug fix achievement - Update UIEntity Pathfinding to 50% complete - Add detailed progress notes for July 9 sprint work Author: John McCardle <mccardle.john@gmail.com> feat(tcod): complete Dijkstra pathfinding implementation with critical PyArg fix - Add complete Dijkstra pathfinding to UIGrid class - compute_dijkstra(), get_dijkstra_distance(), get_dijkstra_path() - Full TCODMap and TCODDijkstra integration - Proper memory management in constructors/destructors - Create mcrfpy.libtcod submodule with Python bindings - dijkstra_compute(), dijkstra_get_distance(), dijkstra_get_path() - line() function for drawing corridors - Foundation for future FOV and pathfinding algorithms - Fix critical PyArg bug in UIGridPoint color setter - PyObject_to_sfColor() now handles both Color objects and tuples - Prevents "SystemError: new style getargs format but argument is not a tuple" - Proper error handling and exception propagation - Add comprehensive test suite - test_dijkstra_simple.py validates all pathfinding operations - dijkstra_test.py for headless testing with screenshots - dijkstra_interactive.py for full user interaction demos - Consolidate and clean up test files - Removed 6 duplicate/broken demo attempts - Two clean versions: headless test + interactive demo Part of TCOD integration sprint for RoguelikeDev Tutorial Event. Author: John McCardle <mccardle.john@gmail.com> Roguelike Tutorial Planning + Prep Author: John McCardle <mccardle.john@gmail.com> feat(docs): complete markdown API documentation export - Created comprehensive markdown documentation matching HTML completeness - Documented all 75 functions, 20 classes, 56 methods, and 20 automation methods - Zero ellipsis instances - complete coverage with no missing documentation - Added proper markdown formatting with code blocks and navigation - Included full parameter documentation, return values, and examples Key features: - 23KB GitHub-compatible markdown documentation - 47 argument sections with detailed parameters - 35 return value specifications - 23 code examples with syntax highlighting - 38 explanatory notes and 10 exception specifications - Full table of contents with anchor links - Professional markdown formatting Both export formats now available: - HTML: docs/api_reference_complete.html (54KB, rich styling) - Markdown: docs/API_REFERENCE_COMPLETE.md (23KB, GitHub-compatible) Author: John McCardle <mccardle.john@gmail.com> feat(docs): complete API documentation with zero missing methods - Eliminated ALL ellipsis instances (0 remaining) - Documented 40 functions with complete signatures and examples - Documented 21 classes with full method and property documentation - Added 56 method descriptions with detailed parameters and return values - Included 15 complete property specifications - Added 24 code examples and 38 explanatory notes - Comprehensive coverage of all collection methods, system classes, and functions Key highlights: - EntityCollection/UICollection: Complete method docs (append, remove, extend, count, index) - Animation: Full property and method documentation with examples - Color: All manipulation methods (from_hex, to_hex, lerp) with examples - Vector: Complete mathematical operations (magnitude, normalize, dot, distance_to, angle, copy) - Scene: All management methods including register_keyboard - Timer: Complete control methods (pause, resume, cancel, restart) - Window: All management methods (get, center, screenshot) - System functions: Complete audio, scene, UI, and system function documentation Author: John McCardle <mccardle.john@gmail.com> feat(docs): create professional HTML API documentation - Fixed all formatting issues from original HTML output - Added comprehensive constructor documentation for all classes - Enhanced visual design with modern styling and typography - Fixed literal newline display and markdown link conversion - Added proper semantic HTML structure and navigation - Includes detailed documentation for Entity, collections, and system types Author: John McCardle <mccardle.john@gmail.com> feat: complete API reference generator and finish Phase 7 documentation Implemented comprehensive API documentation generator that: - Introspects live mcrfpy module for accurate documentation - Generates organized Markdown reference (docs/API_REFERENCE.md) - Categorizes classes and functions by type - Includes full automation module documentation - Provides summary statistics Results: - 20 classes documented - 19 module functions documented - 20 automation methods documented - 100% coverage of public API - Clean, readable Markdown output Phase 7 Summary: - Completed 4/5 tasks (1 cancelled as architecturally inappropriate) - All documentation tasks successful - Type stubs, docstrings, and API reference all complete Author: John McCardle <mccardle.john@gmail.com> docs: cancel PyPI wheel task and add future vision for Python extension architecture Task #70 Analysis: - Discovered fundamental incompatibility with PyPI distribution - McRogueFace embeds CPython rather than being loaded by it - Traditional wheels expect to extend existing Python interpreter - Current architecture is application-with-embedded-Python Decisions: - Cancelled PyPI wheel preparation as out of scope for Alpha - Cleaned up attempted packaging files (pyproject.toml, setup.py, etc.) - Identified better distribution methods (installers, package managers) Added Future Vision: - Comprehensive plan for pure Python extension architecture - Would allow true "pip install mcrogueface" experience - Requires major refactoring to invert control flow - Python would drive main loop with C++ performance extensions - Unscheduled but documented as long-term possibility This clarifies the architectural boundaries and sets realistic expectations for distribution methods while preserving the vision of what McRogueFace could become with significant rework. Author: John McCardle <mccardle.john@gmail.com> feat: generate comprehensive .pyi type stubs for IDE support (#108) Created complete type stub files for the mcrfpy module to enable: - Full IntelliSense/autocomplete in IDEs - Static type checking with mypy/pyright - Better documentation tooltips - Parameter hints and return types Implementation details: - Manually crafted stubs for accuracy (15KB, 533 lines) - Complete coverage: 19 classes, 112 functions/methods - Proper type annotations using typing module - @overload decorators for multiple signatures - Type aliases for common patterns (UIElement union) - Preserved all docstrings for IDE help - Automation module fully typed - PEP 561 compliant with py.typed marker Testing: - Validated Python syntax with ast.parse() - Verified all expected classes and functions - Confirmed type annotations are well-formed - Checked docstring preservation (80 docstrings) Usage: - VS Code: Add stubs/ to python.analysis.extraPaths - PyCharm: Mark stubs/ directory as Sources Root - Other IDEs will auto-detect .pyi files This significantly improves the developer experience when using McRogueFace as a Python game engine. Author: John McCardle <mccardle.john@gmail.com> docs: add comprehensive parameter documentation to all API methods (#86) Enhanced documentation for the mcrfpy module with: - Detailed docstrings for all API methods - Type hints in documentation (name: type format) - Return type specifications - Exception documentation where applicable - Usage examples for complex methods - Module-level documentation with overview and example code Specific improvements: - Audio API: Added parameter types and return values - Scene API: Documented transition types and error conditions - Timer API: Clarified handler signature and runtime parameter - UI Search: Added wildcard pattern examples for findAll() - Metrics API: Documented all dictionary keys returned Also fixed method signatures: - Changed METH_VARARGS to METH_NOARGS for parameterless methods - Ensures proper Python calling conventions Test coverage included - all documentation is accessible via Python's __doc__ attributes and shows correctly formatted information. Author: John McCardle <mccardle.john@gmail.com> docs: mark issue #85 as completed in Phase 7 Author: John McCardle <mccardle.john@gmail.com> docs: replace all 'docstring' placeholders with comprehensive documentation (#85) Added proper Python docstrings for all UI component classes: UIFrame: - Container element that can hold child drawables - Documents position, size, colors, outline, and clip_children - Includes constructor signature with all parameters UICaption: - Text display element with font and styling - Documents text content, position, font, colors, outline - Notes that w/h are computed from text content UISprite: - Texture/sprite display element - Documents position, texture, sprite_index, scale - Notes that w/h are computed from texture and scale UIGrid: - Tile-based grid for game worlds - Documents grid dimensions, tile size, texture atlas - Includes entities collection and background_color All docstrings follow consistent format: - Constructor signature with defaults - Brief description - Args section with types and defaults - Attributes section with all properties This completes Phase 7 task #85 for documentation improvements. Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP with PyArgHelpers infrastructure completion Author: John McCardle <mccardle.john@gmail.com> refactor: implement PyArgHelpers for standardized Python argument parsing This major refactoring standardizes how position, size, and other arguments are parsed across all UI components. PyArgHelpers provides consistent handling for various argument patterns: - Position as (x, y) tuple or separate x, y args - Size as (w, h) tuple or separate width, height args - Grid position and size with proper validation - Color parsing with PyColorObject support Changes across UI components: - UICaption: Migrated to PyArgHelpers, improved resize() for future multiline support - UIFrame: Uses standardized position parsing - UISprite: Consistent position handling - UIGrid: Grid-specific position/size helpers - UIEntity: Unified argument parsing Also includes: - Improved error messages for type mismatches (int or float accepted) - Reduced code duplication across constructors - Better handling of keyword/positional argument conflicts - Maintains backward compatibility with existing API This addresses the inconsistent argument handling patterns discovered during the inheritance hierarchy work and prepares for Phase 7 documentation. Author: John McCardle <mccardle.john@gmail.com> feat(Python): establish proper inheritance hierarchy for UI types All UIDrawable-derived Python types now properly inherit from the Drawable base class in Python, matching the C++ inheritance structure. Changes: - Add Py_TPFLAGS_BASETYPE to PyDrawableType to allow inheritance - Set tp_base = &mcrfpydef::PyDrawableType for all UI types - Add PyDrawable.h include to UI type headers - Rename _Drawable to Drawable and update error message This enables proper Python inheritance: Frame, Caption, Sprite, Grid, and Entity all inherit from Drawable, allowing shared functionality and isinstance() checks. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UISprite) - Update UISprite to use base class position instead of sprite position - Synchronize sprite position with base class position for rendering - Implement onPositionChanged() for position synchronization - Update all UISprite methods to use base position consistently - Add comprehensive test coverage for UISprite position handling This is part 3 of moving position to the base class. UIGrid is the final class that needs to be updated. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UICaption) - Update UICaption to use base class position instead of text position - Synchronize text position with base class position for rendering - Add onPositionChanged() virtual method for position synchronization - Update all UICaption methods to use base position consistently - Add comprehensive test coverage for UICaption position handling This is part 2 of moving position to the base class. UISprite and UIGrid will be updated in subsequent commits. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UIFrame) - Add position member to UIDrawable base class - Add common position getters/setters (x, y, pos) to base class - Update UIFrame to use base class position instead of box position - Synchronize box position with base class position for rendering - Update all UIFrame methods to use base position consistently - Add comprehensive test coverage for UIFrame position handling This is part 1 of moving position to the base class. Other derived classes (UICaption, UISprite, UIGrid) will be updated in subsequent commits. Author: John McCardle <mccardle.john@gmail.com> refactor: remove UIEntity collision_pos field - Remove redundant collision_pos field from UIEntity - Update position getters/setters to use integer-cast position when needed - Remove all collision_pos synchronization code - Simplify entity position handling to use single float position field - Add comprehensive test coverage proving functionality is preserved This removes technical debt and simplifies the codebase without changing API behavior. Author: John McCardle <mccardle.john@gmail.com> feat: add PyArgHelpers infrastructure for standardized argument parsing - Create PyArgHelpers.h with parsing functions for position, size, grid coordinates, and color - Support tuple-based vector arguments with conflict detection - Provide consistent error messages and validation - Add comprehensive test coverage for infrastructure This sets the foundation for standardizing all Python API constructors. Author: John McCardle <mccardle.john@gmail.com> docs: mark Phase 6 (Rendering Revolution) as complete Phase 6 is now complete with all core rendering features implemented: Completed Features: - Grid background colors (#50) - customizable backgrounds with animation - RenderTexture overhaul (#6) - UIFrame clipping with opt-in architecture - Viewport-based rendering (#8) - three scaling modes with coordinate transform Strategic Decisions: - UIGrid already has optimal RenderTexture implementation for its viewport needs - UICaption/UISprite clipping deemed unnecessary (no children to clip) - Effects/Shader/Particle systems deferred to post-Phase 7 for focused delivery The rendering foundation is now solid and ready for Phase 7: Documentation & Distribution. Author: John McCardle <mccardle.john@gmail.com> feat(viewport): complete viewport-based rendering system (#8) Implements a comprehensive viewport system that allows fixed game resolution with flexible window scaling, addressing the primary wishes for issues #34, #49, and #8. Key Features: - Fixed game resolution independent of window size (window.game_resolution property) - Three scaling modes accessible via window.scaling_mode: - "center": 1:1 pixels, viewport centered in window - "stretch": viewport fills window, ignores aspect ratio - "fit": maintains aspect ratio with black bars - Automatic window-to-game coordinate transformation for mouse input - Full Python API integration with PyWindow properties Technical Implementation: - GameEngine::ViewportMode enum with Center, Stretch, Fit modes - SFML View system for efficient GPU-based viewport scaling - updateViewport() recalculates on window resize or mode change - windowToGameCoords() transforms mouse coordinates correctly - PyScene mouse input automatically uses transformed coordinates Tests: - test_viewport_simple.py: Basic API functionality - test_viewport_visual.py: Visual verification with screenshots - test_viewport_scaling.py: Interactive mode switching and resizing This completes the viewport-based rendering task and provides the foundation for resolution-independent game development as requested for Crypt of Sokoban. Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP for Phase 6 progress - Marked Phase 6 as IN PROGRESS - Updated RenderTexture overhaul (#6) as PARTIALLY COMPLETE - Marked Grid background colors (#50) as COMPLETED - Added technical notes from implementation experience - Identified viewport rendering (#8) as next priority Author: John McCardle <mccardle.john@gmail.com> feat(rendering): implement RenderTexture base infrastructure and UIFrame clipping (#6) - Added RenderTexture support to UIDrawable base class - std::unique_ptr<sf::RenderTexture> for opt-in rendering - Dirty flag system for optimization - enableRenderTexture() and markDirty() methods - Implemented clip_children property for UIFrame - Python-accessible boolean property - Automatic RenderTexture creation when enabled - Proper coordinate transformation for nested frames - Updated UIFrame::render() for clipping support - Renders to RenderTexture when clip_children=true - Handles nested clipping correctly - Only re-renders when dirty flag is set - Added comprehensive dirty flag propagation - All property setters mark frame as dirty - Size changes recreate RenderTexture - Animation system integration - Created tests for clipping functionality - Basic clipping test with visual verification - Advanced nested clipping test - Dynamic resize handling test This is Phase 1 of the RenderTexture overhaul, providing the foundation for advanced rendering effects like blur, glow, and viewport rendering. Author: John McCardle <mccardle.john@gmail.com> docs: create RenderTexture overhaul design document - Comprehensive design for Issue #6 implementation - Opt-in architecture to maintain backward compatibility - Phased implementation plan with clear milestones - Performance considerations and risk mitigation - API design for clipping and future effects Also includes Grid background color test Author: John McCardle <mccardle.john@gmail.com> feat(Grid): add customizable background_color property (#50) - Added sf::Color background_color member with default dark gray - Python property getter/setter for background_color - Animation support for individual color components (r/g/b/a) - Replaces hardcoded clear color in render method - Test demonstrates color changes and property access Closes #50 Author: John McCardle <mccardle.john@gmail.com> docs: update roadmap for Phase 6 preparation - Mark Phase 5 (Window/Scene Architecture) as complete - Update issue statuses (#34, #61, #1, #105 completed) - Add Phase 6 implementation strategy for RenderTexture overhaul - Archive Phase 5 test files to .archive/ - Identify quick wins and technical approach for rendering work Author: John McCardle <mccardle.john@gmail.com> feat(Phase 5): Complete Window/Scene Architecture - Window singleton with properties (resolution, fullscreen, vsync, title) - OOP Scene support with lifecycle methods (on_enter, on_exit, on_keypress, update) - Window resize events trigger scene.on_resize callbacks - Scene transitions (fade, slide_left/right/up/down) with smooth animations - Full integration of Python Scene objects with C++ engine All Phase 5 tasks (#34, #1, #61, #105) completed successfully. Author: John McCardle <mccardle.john@gmail.com> research: SFML 3.0 migration analysis - Analyzed SFML 3.0 breaking changes (event system, scoped enums, C++17) - Assessed migration impact on McRogueFace (40+ files affected) - Evaluated timing relative to mcrfpy.sfml module plans - Recommended deferring migration until after mcrfpy.sfml implementation - Created SFML_3_MIGRATION_RESEARCH.md with comprehensive strategy Author: John McCardle <mccardle.john@gmail.com> research: SFML exposure options analysis (#14) - Analyzed current SFML 2.6.1 usage throughout codebase - Evaluated python-sfml (abandoned, only supports SFML 2.3.2) - Recommended direct integration as mcrfpy.sfml module - Created comprehensive SFML_EXPOSURE_RESEARCH.md with implementation plan - Identified opportunity to provide modern SFML 2.6+ Python bindings Author: John McCardle <mccardle.john@gmail.com> feat: add basic profiling/metrics system (#104) - Add ProfilingMetrics struct to track performance data - Track frame time (current and 60-frame rolling average) - Calculate FPS from average frame time - Count draw calls, UI elements, and visible elements per frame - Track total runtime and current frame number - PyScene counts elements during render - Expose metrics via mcrfpy.getMetrics() returning dict This provides basic performance monitoring capabilities for identifying bottlenecks and optimizing rendering performance. Author: John McCardle <mccardle.john@gmail.com> fix: improve click handling with proper z-order and coordinate transforms - UIFrame: Fix coordinate transformation (subtract parent pos, not add) - UIFrame: Check children in reverse order (highest z-index first) - UIFrame: Skip invisible elements entirely - PyScene: Sort elements by z-index before checking clicks - PyScene: Stop at first element that handles the click - UIGrid: Implement entity click detection with grid coordinate transform - UIGrid: Check entities in reverse order, return sprite as target Click events now correctly respect z-order (top elements get priority), handle coordinate transforms for nested frames, and support clicking on grid entities. Elements without click handlers are transparent to clicks, allowing elements below to receive them. Note: Click testing requires non-headless mode due to PyScene limitation. feat: implement name system for finding UI elements (#39/40/41) - Add 'name' property to UIDrawable base class - All UI elements (Frame, Caption, Sprite, Grid, Entity) support .name - Entity delegates name to its sprite member - Add find(name, scene=None) function for exact match search - Add findAll(pattern, scene=None) with wildcard support (* matches any sequence) - Both functions search recursively through Frame children and Grid entities - Comprehensive test coverage for all functionality This provides a simple way to find UI elements by name in Python scripts, supporting both exact matches and wildcard patterns. Author: John McCardle <mccardle.john@gmail.com> fix: prevent segfault when closing window via X button - Add cleanup() method to GameEngine to clear Python references before destruction - Clear timers and McRFPy_API references in proper order - Call cleanup() at end of run loop and in destructor - Ensure cleanup is only called once per GameEngine instance Also includes: - Fix audio ::stop() calls (already in place, OpenAL warning is benign) - Add Caption support for x, y keywords (e.g. Caption("text", x=5, y=10)) - Refactor UIDrawable_methods.h into UIBase.h for better organization - Move UIEntity-specific implementations to UIEntityPyMethods.h Author: John McCardle <mccardle.john@gmail.com> feat: stabilize test suite and add UIDrawable methods - Add visible, opacity properties to all UI classes (#87, #88) - Add get_bounds(), move(), resize() methods to UIDrawable (#89, #98) - Create UIDrawable_methods.h with template implementations - Fix test termination issues - all tests now exit properly - Fix test_sprite_texture_swap.py click handler signature - Fix test_drawable_base.py segfault in headless mode - Convert audio objects to pointers for cleanup (OpenAL warning persists) - Remove debug print statements from UICaption - Special handling for UIEntity to delegate drawable methods to sprite All test files are now "airtight" - they complete successfully, terminate on their own, and handle edge cases properly. Author: John McCardle <mccardle.john@gmail.com> docs: add Phase 1-3 completion summary - Document all completed tasks across three phases - Show before/after API improvements - Highlight technical achievements - Outline next steps for Phase 4-7 Author: John McCardle <mccardle.john@gmail.com> feat: implement mcrfpy.Timer object with pause/resume/cancel capabilities closes #103 - Created PyTimer.h/cpp with object-oriented timer interface - Enhanced PyTimerCallable with pause/resume state tracking - Added timer control methods: pause(), resume(), cancel(), restart() - Added timer properties: interval, remaining, paused, active, callback - Fixed timing logic to prevent rapid catch-up after resume - Timer objects automatically register with game engine - Added comprehensive test demonstrating all functionality Author: John McCardle <mccardle.john@gmail.com> feat(Color): add helper methods from_hex, to_hex, lerp closes #94 - Add Color.from_hex(hex_string) class method for creating colors from hex - Support formats: #RRGGBB, RRGGBB, #RRGGBBAA, RRGGBBAA - Add color.to_hex() to convert Color to hex string - Add color.lerp(other, t) for smooth color interpolation - Comprehensive test coverage for all methods Author: John McCardle <mccardle.john@gmail.com> fix: properly configure UTF-8 encoding for Python stdio - Use PyConfig to set stdio_encoding="UTF-8" during initialization - Set stdio_errors="surrogateescape" for robust handling - Configure in both init_python() and init_python_with_config() - Cleaner solution than wrapping streams after initialization - Fixes UnicodeEncodeError when printing unicode characters Author: John McCardle <mccardle.john@gmail.com> feat(Vector): implement arithmetic operations closes #93 - Add PyNumberMethods with add, subtract, multiply, divide, negate, absolute - Add rich comparison for equality/inequality checks - Add boolean check (zero vector is False) - Implement vector methods: magnitude(), normalize(), dot(), distance_to(), angle(), copy() - Fix UIDrawable::get_click() segfault when click_callable is null - Comprehensive test coverage for all arithmetic operations Author: John McCardle <mccardle.john@gmail.com> feat: Complete position argument standardization for all UI classes - Frame and Sprite now support pos keyword override - Entity now accepts x,y arguments (was pos-only before) - All UI classes now consistently support: - (x, y) positional - ((x, y)) tuple - x=x, y=y keywords - pos=(x,y) keyword - pos=Vector keyword - Improves API consistency and flexibility Author: John McCardle <mccardle.john@gmail.com> feat: Standardize position arguments across all UI classes - Create PyPositionHelper for consistent position parsing - Grid.at() now accepts (x,y), ((x,y)), x=x, y=y, pos=(x,y) - Caption now accepts x,y args in addition to pos - Grid init fully supports keyword arguments - Maintain backward compatibility for all formats - Consistent error messages across classes Author: John McCardle <mccardle.john@gmail.com> feat: Add Entity.die() method for lifecycle management closes #30 - Remove entity from its grid's entity list - Clear grid reference after removal - Safe to call multiple times (no-op if not on grid) - Works with shared_ptr entity management Author: John McCardle <mccardle.john@gmail.com> perf: Skip out-of-bounds entities during Grid rendering closes #52 - Add visibility bounds check in entity render loop - Skip entities outside view with 1 cell margin - Improves performance for large grids with many entities - Bounds check considers zoom and pan settings Author: John McCardle <mccardle.john@gmail.com> verify: Sprite texture swapping functionality closes #19 - Texture property getter/setter already implemented - Position/scale preservation during swap confirmed - Type validation for texture assignment working - Tests verify functionality is complete Author: John McCardle <mccardle.john@gmail.com> feat: Grid size tuple support closes #90 - Add grid_size keyword parameter to Grid.__init__ - Accept tuple or list of two integers - Override grid_x/grid_y if grid_size provided - Maintain backward compatibility - Add comprehensive test coverage Author: John McCardle <mccardle.john@gmail.com> feat: Phase 1 - safe constructors and _Drawable foundation Closes #7 - Make all UI class constructors safe: - Added safe default constructors for UISprite, UIGrid, UIEntity, UICaption - Initialize all members to predictable values - Made Python init functions accept no arguments - Added x,y properties to UIEntity Closes #71 - Create _Drawable Python base class: - Created PyDrawable.h/cpp with base type (not yet inherited by UI types) - Registered in module initialization Closes #87 - Add visible property: - Added bool visible=true to UIDrawable base class - All render methods check visibility before drawing Closes #88 - Add opacity property: - Added float opacity=1.0 to UIDrawable base class - UICaption and UISprite apply opacity to alpha channel Closes #89 - Add get_bounds() method: - Virtual method returns sf::FloatRect(x,y,w,h) - Implemented in Frame, Caption, Sprite, Grid Closes #98 - Add move() and resize() methods: - move(dx,dy) for relative movement - resize(w,h) for absolute sizing - Caption resize is no-op (size controlled by font) Author: John McCardle <mccardle.john@gmail.com> docs: comprehensive alpha_streamline_2 plan and strategic vision - Add 7-phase development plan for alpha_streamline_2 branch - Define architectural dependencies and critical path - Identify new issues needed (Timer objects, event system, etc.) - Add strategic vision document with 3 transformative directions - Timeline: 10-12 weeks to solid Beta foundation Author: John McCardle <mccardle.john@gmail.com> feat(Grid): flexible at() method arguments - Support tuple argument: grid.at((x, y)) - Support keyword arguments: grid.at(x=5, y=3) - Support pos keyword: grid.at(pos=(2, 8)) - Maintain backward compatibility with grid.at(x, y) - Add comprehensive error handling for invalid arguments Improves API ergonomics and Python-like flexibility
2025-07-09 22:41:15 -04:00
#pragma once
#include "Common.h"
#include "Python.h"
#include <memory>
#include <string>
Squashed commit of the following: [alpha_presentable] Author: John McCardle <mccardle.john@gmail.com> Co-Authored-By: Claude <noreply@anthropic.com> commit dc47f2474c7b2642d368f9772894aed857527807 the UIEntity rant commit 673ca8e1b089ea670257fc04ae1a676ed95a40ed I forget when these tests were written, but I want them in the squash merge commit 70c71565c684fa96e222179271ecb13a156d80ad Fix UI object segfault by switching from managed to manual weakref management The UI types (Frame, Caption, Sprite, Grid, Entity) were using Py_TPFLAGS_MANAGED_WEAKREF while also trying to manually create weakrefs for the PythonObjectCache. This is fundamentally incompatible - when Python manages weakrefs internally, PyWeakref_NewRef() cannot access the weakref list properly, causing segfaults. Changed all UI types to use manual weakref management (like PyTimer): - Restored weakreflist field in all UI type structures - Removed Py_TPFLAGS_MANAGED_WEAKREF from all UI type flags - Added tp_weaklistoffset for all UI types in module initialization - Initialize weakreflist=NULL in tp_new and init methods - Call PyObject_ClearWeakRefs() in dealloc functions This allows the PythonObjectCache to continue working correctly, maintaining Python object identity for C++ objects across the boundary. Fixes segfault when creating UI objects (e.g., Caption, Grid) that was preventing tutorial scripts from running. This is the bulk of the required behavior for Issue #126. that issure isn't ready for closure yet; several other sub-issues left. closes #110 mention issue #109 - resolves some __init__ related nuisances commit 3dce3ec539ae99e32d869007bf3f49d03e4e2f89 Refactor timer system for cleaner architecture and enhanced functionality Major improvements to the timer system: - Unified all timer logic in the Timer class (C++) - Removed PyTimerCallable subclass, now using PyCallable directly - Timer objects are now passed to callbacks as first argument - Added 'once' parameter for one-shot timers that auto-stop - Implemented proper PythonObjectCache integration with weakref support API enhancements: - New callback signature: callback(timer, runtime) instead of just (runtime) - Timer objects expose: name, interval, remaining, paused, active, once properties - Methods: pause(), resume(), cancel(), restart() - Comprehensive documentation with examples - Enhanced repr showing timer state (active/paused/once/remaining time) This cleanup follows the UIEntity/PyUIEntity pattern and makes the timer system more Pythonic while maintaining backward compatibility through the legacy setTimer/delTimer API. closes #121 commit 145834cfc31b8dabc4cb3591b9cb4ed99fc8b964 Implement Python object cache to preserve derived types in collections Add a global cache system that maintains weak references to Python objects, ensuring that derived Python classes maintain their identity when stored in and retrieved from C++ collections. Key changes: - Add PythonObjectCache singleton with serial number system - Each cacheable object (UIDrawable, UIEntity, Timer, Animation) gets unique ID - Cache stores weak references to prevent circular reference memory leaks - Update all UI type definitions to support weak references (Py_TPFLAGS_MANAGED_WEAKREF) - Enable subclassing for all UI types (Py_TPFLAGS_BASETYPE) - Collections check cache before creating new Python wrappers - Register objects in cache during __init__ methods - Clean up cache entries in C++ destructors This ensures that Python code like: ```python class MyFrame(mcrfpy.Frame): def __init__(self): super().__init__() self.custom_data = "preserved" frame = MyFrame() scene.ui.append(frame) retrieved = scene.ui[0] # Same MyFrame instance with custom_data intact ``` Works correctly, with retrieved maintaining the derived type and custom attributes. Closes #112 commit c5e7e8e29835a69f4c50f3c99fd3123012635a9a Update test demos for new Python API and entity system - Update all text input demos to use new Entity constructor signature - Fix pathfinding showcase to work with new entity position handling - Remove entity_waypoints tracking in favor of simplified movement - Delete obsolete exhaustive_api_demo.py (superseded by newer demos) - Adjust entity creation calls to match Entity((x, y), texture, sprite_index) pattern commit 6d29652ae7418745dc24066532454167d447df89 Update animation demo suite with crash fixes and improvements - Add warnings about AnimationManager segfault bug in sizzle_reel_final.py - Create sizzle_reel_final_fixed.py that works around the crash by hiding objects instead of removing them - Increase font sizes for better visibility in demos - Extend demo durations for better showcase of animations - Remove debug prints from animation_sizzle_reel_working.py - Minor cleanup and improvements to all animation demos commit a010e5fa968feaba620dcf2eda44fb9514512151 Update game scripts for new Python API - Convert entity position access from tuple to x/y properties - Update caption size property to font_size - Fix grid boundary checks to use grid_size instead of exceptions - Clean up demo timer on menu exit to prevent callbacks These changes adapt the game scripts to work with the new standardized Python API constructors and property names. commit 9c8d6c459109be883cb8070b8ef83c60bfc1a970 Fix click event z-order handling in PyScene Changed click detection to properly respect z-index by: - Sorting ui_elements in-place when needed (same as render order) - Using reverse iterators to check highest z-index elements first - This ensures top-most elements receive clicks before lower ones commit dcd1b0ca33d46639023221f4d7d52000b947dbdf Add roguelike tutorial implementation files Implement Parts 0-2 of the classic roguelike tutorial adapted for McRogueFace: - Part 0: Basic grid setup and tile rendering - Part 1: Drawing '@' symbol and basic movement - Part 1b: Variant with sprite-based player - Part 2: Entity system and NPC implementation with three movement variants: - part_2.py: Standard implementation - part_2-naive.py: Naive movement approach - part_2-onemovequeued.py: Queued movement system Includes tutorial assets: - tutorial2.png: Tileset for dungeon tiles - tutorial_hero.png: Player sprite sheet commit 6813fb5129738cca2d79c80304834523561ba7fb Standardize Python API constructors and remove PyArgHelpers - Remove PyArgHelpers.h and all macro-based argument parsing - Convert all UI class constructors to use PyArg_ParseTupleAndKeywords - Standardize constructor signatures across UICaption, UIEntity, UIFrame, UIGrid, and UISprite - Replace PYARGHELPER_SINGLE/MULTI macros with explicit argument parsing - Improve error messages and argument validation - Maintain backward compatibility with existing Python code This change improves code maintainability and consistency across the Python API. commit 6f67fbb51efaf70e52fba8c939298dcdff50450a Fix animation callback crashes from iterator invalidation (#119) Resolved segfaults caused by creating new animations from within animation callbacks. The issue was iterator invalidation in AnimationManager::update() when callbacks modified the active animations vector. Changes: - Add deferred animation queue to AnimationManager - New animations created during update are queued and added after - Set isUpdating flag to track when in update loop - Properly handle Animation destructor during callback execution - Add clearCallback() method for safe cleanup scenarios This fixes the "free(): invalid pointer" and "malloc(): unaligned fastbin chunk detected" errors that occurred with rapid animation creation in callbacks. commit eb88c7b3aab3da519db7569106c34f3510b6e963 Add animation completion callbacks (#119) Implement callbacks that fire when animations complete, enabling direct causality between animation end and game state changes. This eliminates race conditions from parallel timer workarounds. - Add optional callback parameter to Animation constructor - Callbacks execute synchronously when animation completes - Proper Python reference counting with GIL safety - Callbacks receive (anim, target) parameters (currently None) - Exception handling prevents crashes from Python errors Example usage: ```python def on_complete(anim, target): player_moving = False anim = mcrfpy.Animation("x", 300.0, 1.0, "easeOut", callback=on_complete) anim.start(player) ``` closes #119 commit 9fb428dd0176a4d7cfad09deb7509d8aa5562868 Update ROADMAP with GitHub issue numbers (#111-#125) Added issue numbers from GitHub tracker to roadmap items: - #111: Grid Click Events Broken in Headless - #112: Object Splitting Bug (Python type preservation) - #113: Batch Operations for Grid - #114: CellView API - #115: SpatialHash Implementation - #116: Dirty Flag System - #117: Memory Pool for Entities - #118: Scene as Drawable - #119: Animation Completion Callbacks - #120: Animation Property Locking - #121: Timer Object System - #122: Parent-Child UI System - #123: Grid Subgrid System - #124: Grid Point Animation - #125: GitHub Issues Automation Also updated existing references: - #101/#110: Constructor standardization - #109: Vector class indexing Note: Tutorial-specific items and Python-implementable features (input queue, collision reservation) are not tracked as engine issues. commit 062e4dadc42833bf5a3559e5d7c4ceb4abb7e9c0 Fix animation segfaults with RAII weak_ptr implementation Resolved two critical segmentation faults in AnimationManager: 1. Race condition when creating multiple animations in timer callbacks 2. Exit crash when animations outlive their target objects Changes: - Replace raw pointers with std::weak_ptr for automatic target invalidation - Add Animation::complete() to jump animations to final value - Add Animation::hasValidTarget() to check if target still exists - Update AnimationManager to auto-remove invalid animations - Add AnimationManager::clear() call to GameEngine::cleanup() - Update Python bindings to pass shared_ptr instead of raw pointers This ensures animations can never reference destroyed objects, following proper RAII principles. Tested with sizzle_reel_final.py and stress tests creating/destroying hundreds of animated objects. commit 98fc49a978ec792ee6096f40fd4e19841b8ec6a3 Directory structure cleanup and organization overhaul
2025-07-15 21:30:49 -04:00
class Timer;
Squashed commit of 53 Commits: [alpha_streamline_2] * Field of View, Pathing courtesy of libtcod * python-tcod emulation at `mcrfpy.libtcod` - partial implementation * documentation, tutorial drafts: in middling to good shape ┌────────────┬────────────────────┬───────────┬────────────┬───────────────┬────────────────┬────────────────┬─────────────┐ │ Date │ Models │ Input │ Output │ Cache Create │ Cache Read │ Total Tokens │ Cost (USD) │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-05 │ - opus-4 │ 13,630 │ 159,500 │ 3,854,900 │ 84,185,034 │ 88,213,064 │ $210.72 │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-06 │ - opus-4 │ 5,814 │ 113,190 │ 4,242,407 │ 150,191,183 │ 154,552,594 │ $313.41 │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-07 │ - opus-4 │ 7,244 │ 104,599 │ 3,894,453 │ 81,781,179 │ 85,787,475 │ $184.46 │ │ │ - sonnet-4 │ │ │ │ │ │ │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-08 │ - opus-4 │ 50,312 │ 158,599 │ 5,021,189 │ 60,028,561 │ 65,258,661 │ $167.05 │ │ │ - sonnet-4 │ │ │ │ │ │ │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-09 │ - opus-4 │ 6,311 │ 109,653 │ 4,171,140 │ 80,092,875 │ 84,379,979 │ $193.09 │ │ │ - sonnet-4 │ │ │ │ │ │ │ └────────────┴────────────────────┴───────────┴────────────┴───────────────┴────────────────┴────────────────┴─────────────┘ 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> Author: John McCardle <mccardle.john@gmail.com> Draft tutorials Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP with FOV, A* pathfinding, and GUI text widget completions - Mark TCOD Integration Sprint as complete - Document FOV system with perspective rendering implementation - Update UIEntity pathfinding status to complete with A* and caching - Add comprehensive achievement entry for July 10 work - Reflect current engine capabilities accurately The engine now has all core roguelike mechanics: - Field of View with per-entity visibility - Pathfinding (both Dijkstra and A*) - Text input for in-game consoles - Performance optimizations throughout Author: John McCardle <mccardle.john@gmail.com> feat(engine): implement perspective FOV, pathfinding, and GUI text widgets Major Engine Enhancements: - Complete FOV (Field of View) system with perspective rendering - UIGrid.perspective property for entity-based visibility - Three-layer overlay colors (unexplored, explored, visible) - Per-entity visibility state tracking - Perfect knowledge updates only for explored areas - Advanced Pathfinding Integration - A* pathfinding implementation in UIGrid - Entity.path_to() method for direct pathfinding - Dijkstra maps for multi-target pathfinding - Path caching for performance optimization - GUI Text Input Widgets - TextInputWidget class with cursor, selection, scrolling - Improved widget with proper text rendering and input handling - Example showcase of multiple text input fields - Foundation for in-game console and chat systems - Performance & Architecture Improvements - PyTexture copy operations optimized - GameEngine update cycle refined - UIEntity property handling enhanced - UITestScene modernized Test Suite: - Interactive visibility demos showing FOV in action - Pathfinding comparison (A* vs Dijkstra) - Debug utilities for visibility and empty path handling - Sizzle reel demo combining pathfinding and vision - Multiple text input test scenarios This commit brings McRogueFace closer to a complete roguelike engine with essential features like line-of-sight, intelligent pathfinding, and interactive text input capabilities. Author: John McCardle <mccardle.john@gmail.com> feat(demos): enhance interactive pathfinding demos with entity.path_to() - dijkstra_interactive_enhanced.py: Animation along paths with smooth movement - M key to start movement animation - P to pause/resume - R to reset positions - Visual path gradient for better clarity - pathfinding_showcase.py: Advanced multi-entity behaviors - Chase mode: enemies pursue player - Flee mode: enemies avoid player - Patrol mode: entities follow waypoints - WASD player movement - Dijkstra distance field visualization (D key) - Larger dungeon map with multiple rooms - Both demos use new entity.path_to() method - Smooth interpolated movement animations - Real-time pathfinding recalculation - Comprehensive test coverage These demos showcase the power of integrated pathfinding for game AI. Author: John McCardle <mccardle.john@gmail.com> feat(entity): implement path_to() method for entity pathfinding - Add path_to(target_x, target_y) method to UIEntity class - Uses existing Dijkstra pathfinding implementation from UIGrid - Returns list of (x, y) coordinate tuples for complete path - Supports both positional and keyword argument formats - Proper error handling for out-of-bounds and no-grid scenarios - Comprehensive test suite covering normal and edge cases Part of TCOD integration sprint - gives entities immediate pathfinding capabilities. Author: John McCardle <mccardle.john@gmail.com> docs: update roadmap with Dijkstra pathfinding progress - Mark UIGrid TCOD Integration as completed - Document critical PyArg bug fix achievement - Update UIEntity Pathfinding to 50% complete - Add detailed progress notes for July 9 sprint work Author: John McCardle <mccardle.john@gmail.com> feat(tcod): complete Dijkstra pathfinding implementation with critical PyArg fix - Add complete Dijkstra pathfinding to UIGrid class - compute_dijkstra(), get_dijkstra_distance(), get_dijkstra_path() - Full TCODMap and TCODDijkstra integration - Proper memory management in constructors/destructors - Create mcrfpy.libtcod submodule with Python bindings - dijkstra_compute(), dijkstra_get_distance(), dijkstra_get_path() - line() function for drawing corridors - Foundation for future FOV and pathfinding algorithms - Fix critical PyArg bug in UIGridPoint color setter - PyObject_to_sfColor() now handles both Color objects and tuples - Prevents "SystemError: new style getargs format but argument is not a tuple" - Proper error handling and exception propagation - Add comprehensive test suite - test_dijkstra_simple.py validates all pathfinding operations - dijkstra_test.py for headless testing with screenshots - dijkstra_interactive.py for full user interaction demos - Consolidate and clean up test files - Removed 6 duplicate/broken demo attempts - Two clean versions: headless test + interactive demo Part of TCOD integration sprint for RoguelikeDev Tutorial Event. Author: John McCardle <mccardle.john@gmail.com> Roguelike Tutorial Planning + Prep Author: John McCardle <mccardle.john@gmail.com> feat(docs): complete markdown API documentation export - Created comprehensive markdown documentation matching HTML completeness - Documented all 75 functions, 20 classes, 56 methods, and 20 automation methods - Zero ellipsis instances - complete coverage with no missing documentation - Added proper markdown formatting with code blocks and navigation - Included full parameter documentation, return values, and examples Key features: - 23KB GitHub-compatible markdown documentation - 47 argument sections with detailed parameters - 35 return value specifications - 23 code examples with syntax highlighting - 38 explanatory notes and 10 exception specifications - Full table of contents with anchor links - Professional markdown formatting Both export formats now available: - HTML: docs/api_reference_complete.html (54KB, rich styling) - Markdown: docs/API_REFERENCE_COMPLETE.md (23KB, GitHub-compatible) Author: John McCardle <mccardle.john@gmail.com> feat(docs): complete API documentation with zero missing methods - Eliminated ALL ellipsis instances (0 remaining) - Documented 40 functions with complete signatures and examples - Documented 21 classes with full method and property documentation - Added 56 method descriptions with detailed parameters and return values - Included 15 complete property specifications - Added 24 code examples and 38 explanatory notes - Comprehensive coverage of all collection methods, system classes, and functions Key highlights: - EntityCollection/UICollection: Complete method docs (append, remove, extend, count, index) - Animation: Full property and method documentation with examples - Color: All manipulation methods (from_hex, to_hex, lerp) with examples - Vector: Complete mathematical operations (magnitude, normalize, dot, distance_to, angle, copy) - Scene: All management methods including register_keyboard - Timer: Complete control methods (pause, resume, cancel, restart) - Window: All management methods (get, center, screenshot) - System functions: Complete audio, scene, UI, and system function documentation Author: John McCardle <mccardle.john@gmail.com> feat(docs): create professional HTML API documentation - Fixed all formatting issues from original HTML output - Added comprehensive constructor documentation for all classes - Enhanced visual design with modern styling and typography - Fixed literal newline display and markdown link conversion - Added proper semantic HTML structure and navigation - Includes detailed documentation for Entity, collections, and system types Author: John McCardle <mccardle.john@gmail.com> feat: complete API reference generator and finish Phase 7 documentation Implemented comprehensive API documentation generator that: - Introspects live mcrfpy module for accurate documentation - Generates organized Markdown reference (docs/API_REFERENCE.md) - Categorizes classes and functions by type - Includes full automation module documentation - Provides summary statistics Results: - 20 classes documented - 19 module functions documented - 20 automation methods documented - 100% coverage of public API - Clean, readable Markdown output Phase 7 Summary: - Completed 4/5 tasks (1 cancelled as architecturally inappropriate) - All documentation tasks successful - Type stubs, docstrings, and API reference all complete Author: John McCardle <mccardle.john@gmail.com> docs: cancel PyPI wheel task and add future vision for Python extension architecture Task #70 Analysis: - Discovered fundamental incompatibility with PyPI distribution - McRogueFace embeds CPython rather than being loaded by it - Traditional wheels expect to extend existing Python interpreter - Current architecture is application-with-embedded-Python Decisions: - Cancelled PyPI wheel preparation as out of scope for Alpha - Cleaned up attempted packaging files (pyproject.toml, setup.py, etc.) - Identified better distribution methods (installers, package managers) Added Future Vision: - Comprehensive plan for pure Python extension architecture - Would allow true "pip install mcrogueface" experience - Requires major refactoring to invert control flow - Python would drive main loop with C++ performance extensions - Unscheduled but documented as long-term possibility This clarifies the architectural boundaries and sets realistic expectations for distribution methods while preserving the vision of what McRogueFace could become with significant rework. Author: John McCardle <mccardle.john@gmail.com> feat: generate comprehensive .pyi type stubs for IDE support (#108) Created complete type stub files for the mcrfpy module to enable: - Full IntelliSense/autocomplete in IDEs - Static type checking with mypy/pyright - Better documentation tooltips - Parameter hints and return types Implementation details: - Manually crafted stubs for accuracy (15KB, 533 lines) - Complete coverage: 19 classes, 112 functions/methods - Proper type annotations using typing module - @overload decorators for multiple signatures - Type aliases for common patterns (UIElement union) - Preserved all docstrings for IDE help - Automation module fully typed - PEP 561 compliant with py.typed marker Testing: - Validated Python syntax with ast.parse() - Verified all expected classes and functions - Confirmed type annotations are well-formed - Checked docstring preservation (80 docstrings) Usage: - VS Code: Add stubs/ to python.analysis.extraPaths - PyCharm: Mark stubs/ directory as Sources Root - Other IDEs will auto-detect .pyi files This significantly improves the developer experience when using McRogueFace as a Python game engine. Author: John McCardle <mccardle.john@gmail.com> docs: add comprehensive parameter documentation to all API methods (#86) Enhanced documentation for the mcrfpy module with: - Detailed docstrings for all API methods - Type hints in documentation (name: type format) - Return type specifications - Exception documentation where applicable - Usage examples for complex methods - Module-level documentation with overview and example code Specific improvements: - Audio API: Added parameter types and return values - Scene API: Documented transition types and error conditions - Timer API: Clarified handler signature and runtime parameter - UI Search: Added wildcard pattern examples for findAll() - Metrics API: Documented all dictionary keys returned Also fixed method signatures: - Changed METH_VARARGS to METH_NOARGS for parameterless methods - Ensures proper Python calling conventions Test coverage included - all documentation is accessible via Python's __doc__ attributes and shows correctly formatted information. Author: John McCardle <mccardle.john@gmail.com> docs: mark issue #85 as completed in Phase 7 Author: John McCardle <mccardle.john@gmail.com> docs: replace all 'docstring' placeholders with comprehensive documentation (#85) Added proper Python docstrings for all UI component classes: UIFrame: - Container element that can hold child drawables - Documents position, size, colors, outline, and clip_children - Includes constructor signature with all parameters UICaption: - Text display element with font and styling - Documents text content, position, font, colors, outline - Notes that w/h are computed from text content UISprite: - Texture/sprite display element - Documents position, texture, sprite_index, scale - Notes that w/h are computed from texture and scale UIGrid: - Tile-based grid for game worlds - Documents grid dimensions, tile size, texture atlas - Includes entities collection and background_color All docstrings follow consistent format: - Constructor signature with defaults - Brief description - Args section with types and defaults - Attributes section with all properties This completes Phase 7 task #85 for documentation improvements. Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP with PyArgHelpers infrastructure completion Author: John McCardle <mccardle.john@gmail.com> refactor: implement PyArgHelpers for standardized Python argument parsing This major refactoring standardizes how position, size, and other arguments are parsed across all UI components. PyArgHelpers provides consistent handling for various argument patterns: - Position as (x, y) tuple or separate x, y args - Size as (w, h) tuple or separate width, height args - Grid position and size with proper validation - Color parsing with PyColorObject support Changes across UI components: - UICaption: Migrated to PyArgHelpers, improved resize() for future multiline support - UIFrame: Uses standardized position parsing - UISprite: Consistent position handling - UIGrid: Grid-specific position/size helpers - UIEntity: Unified argument parsing Also includes: - Improved error messages for type mismatches (int or float accepted) - Reduced code duplication across constructors - Better handling of keyword/positional argument conflicts - Maintains backward compatibility with existing API This addresses the inconsistent argument handling patterns discovered during the inheritance hierarchy work and prepares for Phase 7 documentation. Author: John McCardle <mccardle.john@gmail.com> feat(Python): establish proper inheritance hierarchy for UI types All UIDrawable-derived Python types now properly inherit from the Drawable base class in Python, matching the C++ inheritance structure. Changes: - Add Py_TPFLAGS_BASETYPE to PyDrawableType to allow inheritance - Set tp_base = &mcrfpydef::PyDrawableType for all UI types - Add PyDrawable.h include to UI type headers - Rename _Drawable to Drawable and update error message This enables proper Python inheritance: Frame, Caption, Sprite, Grid, and Entity all inherit from Drawable, allowing shared functionality and isinstance() checks. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UISprite) - Update UISprite to use base class position instead of sprite position - Synchronize sprite position with base class position for rendering - Implement onPositionChanged() for position synchronization - Update all UISprite methods to use base position consistently - Add comprehensive test coverage for UISprite position handling This is part 3 of moving position to the base class. UIGrid is the final class that needs to be updated. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UICaption) - Update UICaption to use base class position instead of text position - Synchronize text position with base class position for rendering - Add onPositionChanged() virtual method for position synchronization - Update all UICaption methods to use base position consistently - Add comprehensive test coverage for UICaption position handling This is part 2 of moving position to the base class. UISprite and UIGrid will be updated in subsequent commits. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UIFrame) - Add position member to UIDrawable base class - Add common position getters/setters (x, y, pos) to base class - Update UIFrame to use base class position instead of box position - Synchronize box position with base class position for rendering - Update all UIFrame methods to use base position consistently - Add comprehensive test coverage for UIFrame position handling This is part 1 of moving position to the base class. Other derived classes (UICaption, UISprite, UIGrid) will be updated in subsequent commits. Author: John McCardle <mccardle.john@gmail.com> refactor: remove UIEntity collision_pos field - Remove redundant collision_pos field from UIEntity - Update position getters/setters to use integer-cast position when needed - Remove all collision_pos synchronization code - Simplify entity position handling to use single float position field - Add comprehensive test coverage proving functionality is preserved This removes technical debt and simplifies the codebase without changing API behavior. Author: John McCardle <mccardle.john@gmail.com> feat: add PyArgHelpers infrastructure for standardized argument parsing - Create PyArgHelpers.h with parsing functions for position, size, grid coordinates, and color - Support tuple-based vector arguments with conflict detection - Provide consistent error messages and validation - Add comprehensive test coverage for infrastructure This sets the foundation for standardizing all Python API constructors. Author: John McCardle <mccardle.john@gmail.com> docs: mark Phase 6 (Rendering Revolution) as complete Phase 6 is now complete with all core rendering features implemented: Completed Features: - Grid background colors (#50) - customizable backgrounds with animation - RenderTexture overhaul (#6) - UIFrame clipping with opt-in architecture - Viewport-based rendering (#8) - three scaling modes with coordinate transform Strategic Decisions: - UIGrid already has optimal RenderTexture implementation for its viewport needs - UICaption/UISprite clipping deemed unnecessary (no children to clip) - Effects/Shader/Particle systems deferred to post-Phase 7 for focused delivery The rendering foundation is now solid and ready for Phase 7: Documentation & Distribution. Author: John McCardle <mccardle.john@gmail.com> feat(viewport): complete viewport-based rendering system (#8) Implements a comprehensive viewport system that allows fixed game resolution with flexible window scaling, addressing the primary wishes for issues #34, #49, and #8. Key Features: - Fixed game resolution independent of window size (window.game_resolution property) - Three scaling modes accessible via window.scaling_mode: - "center": 1:1 pixels, viewport centered in window - "stretch": viewport fills window, ignores aspect ratio - "fit": maintains aspect ratio with black bars - Automatic window-to-game coordinate transformation for mouse input - Full Python API integration with PyWindow properties Technical Implementation: - GameEngine::ViewportMode enum with Center, Stretch, Fit modes - SFML View system for efficient GPU-based viewport scaling - updateViewport() recalculates on window resize or mode change - windowToGameCoords() transforms mouse coordinates correctly - PyScene mouse input automatically uses transformed coordinates Tests: - test_viewport_simple.py: Basic API functionality - test_viewport_visual.py: Visual verification with screenshots - test_viewport_scaling.py: Interactive mode switching and resizing This completes the viewport-based rendering task and provides the foundation for resolution-independent game development as requested for Crypt of Sokoban. Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP for Phase 6 progress - Marked Phase 6 as IN PROGRESS - Updated RenderTexture overhaul (#6) as PARTIALLY COMPLETE - Marked Grid background colors (#50) as COMPLETED - Added technical notes from implementation experience - Identified viewport rendering (#8) as next priority Author: John McCardle <mccardle.john@gmail.com> feat(rendering): implement RenderTexture base infrastructure and UIFrame clipping (#6) - Added RenderTexture support to UIDrawable base class - std::unique_ptr<sf::RenderTexture> for opt-in rendering - Dirty flag system for optimization - enableRenderTexture() and markDirty() methods - Implemented clip_children property for UIFrame - Python-accessible boolean property - Automatic RenderTexture creation when enabled - Proper coordinate transformation for nested frames - Updated UIFrame::render() for clipping support - Renders to RenderTexture when clip_children=true - Handles nested clipping correctly - Only re-renders when dirty flag is set - Added comprehensive dirty flag propagation - All property setters mark frame as dirty - Size changes recreate RenderTexture - Animation system integration - Created tests for clipping functionality - Basic clipping test with visual verification - Advanced nested clipping test - Dynamic resize handling test This is Phase 1 of the RenderTexture overhaul, providing the foundation for advanced rendering effects like blur, glow, and viewport rendering. Author: John McCardle <mccardle.john@gmail.com> docs: create RenderTexture overhaul design document - Comprehensive design for Issue #6 implementation - Opt-in architecture to maintain backward compatibility - Phased implementation plan with clear milestones - Performance considerations and risk mitigation - API design for clipping and future effects Also includes Grid background color test Author: John McCardle <mccardle.john@gmail.com> feat(Grid): add customizable background_color property (#50) - Added sf::Color background_color member with default dark gray - Python property getter/setter for background_color - Animation support for individual color components (r/g/b/a) - Replaces hardcoded clear color in render method - Test demonstrates color changes and property access Closes #50 Author: John McCardle <mccardle.john@gmail.com> docs: update roadmap for Phase 6 preparation - Mark Phase 5 (Window/Scene Architecture) as complete - Update issue statuses (#34, #61, #1, #105 completed) - Add Phase 6 implementation strategy for RenderTexture overhaul - Archive Phase 5 test files to .archive/ - Identify quick wins and technical approach for rendering work Author: John McCardle <mccardle.john@gmail.com> feat(Phase 5): Complete Window/Scene Architecture - Window singleton with properties (resolution, fullscreen, vsync, title) - OOP Scene support with lifecycle methods (on_enter, on_exit, on_keypress, update) - Window resize events trigger scene.on_resize callbacks - Scene transitions (fade, slide_left/right/up/down) with smooth animations - Full integration of Python Scene objects with C++ engine All Phase 5 tasks (#34, #1, #61, #105) completed successfully. Author: John McCardle <mccardle.john@gmail.com> research: SFML 3.0 migration analysis - Analyzed SFML 3.0 breaking changes (event system, scoped enums, C++17) - Assessed migration impact on McRogueFace (40+ files affected) - Evaluated timing relative to mcrfpy.sfml module plans - Recommended deferring migration until after mcrfpy.sfml implementation - Created SFML_3_MIGRATION_RESEARCH.md with comprehensive strategy Author: John McCardle <mccardle.john@gmail.com> research: SFML exposure options analysis (#14) - Analyzed current SFML 2.6.1 usage throughout codebase - Evaluated python-sfml (abandoned, only supports SFML 2.3.2) - Recommended direct integration as mcrfpy.sfml module - Created comprehensive SFML_EXPOSURE_RESEARCH.md with implementation plan - Identified opportunity to provide modern SFML 2.6+ Python bindings Author: John McCardle <mccardle.john@gmail.com> feat: add basic profiling/metrics system (#104) - Add ProfilingMetrics struct to track performance data - Track frame time (current and 60-frame rolling average) - Calculate FPS from average frame time - Count draw calls, UI elements, and visible elements per frame - Track total runtime and current frame number - PyScene counts elements during render - Expose metrics via mcrfpy.getMetrics() returning dict This provides basic performance monitoring capabilities for identifying bottlenecks and optimizing rendering performance. Author: John McCardle <mccardle.john@gmail.com> fix: improve click handling with proper z-order and coordinate transforms - UIFrame: Fix coordinate transformation (subtract parent pos, not add) - UIFrame: Check children in reverse order (highest z-index first) - UIFrame: Skip invisible elements entirely - PyScene: Sort elements by z-index before checking clicks - PyScene: Stop at first element that handles the click - UIGrid: Implement entity click detection with grid coordinate transform - UIGrid: Check entities in reverse order, return sprite as target Click events now correctly respect z-order (top elements get priority), handle coordinate transforms for nested frames, and support clicking on grid entities. Elements without click handlers are transparent to clicks, allowing elements below to receive them. Note: Click testing requires non-headless mode due to PyScene limitation. feat: implement name system for finding UI elements (#39/40/41) - Add 'name' property to UIDrawable base class - All UI elements (Frame, Caption, Sprite, Grid, Entity) support .name - Entity delegates name to its sprite member - Add find(name, scene=None) function for exact match search - Add findAll(pattern, scene=None) with wildcard support (* matches any sequence) - Both functions search recursively through Frame children and Grid entities - Comprehensive test coverage for all functionality This provides a simple way to find UI elements by name in Python scripts, supporting both exact matches and wildcard patterns. Author: John McCardle <mccardle.john@gmail.com> fix: prevent segfault when closing window via X button - Add cleanup() method to GameEngine to clear Python references before destruction - Clear timers and McRFPy_API references in proper order - Call cleanup() at end of run loop and in destructor - Ensure cleanup is only called once per GameEngine instance Also includes: - Fix audio ::stop() calls (already in place, OpenAL warning is benign) - Add Caption support for x, y keywords (e.g. Caption("text", x=5, y=10)) - Refactor UIDrawable_methods.h into UIBase.h for better organization - Move UIEntity-specific implementations to UIEntityPyMethods.h Author: John McCardle <mccardle.john@gmail.com> feat: stabilize test suite and add UIDrawable methods - Add visible, opacity properties to all UI classes (#87, #88) - Add get_bounds(), move(), resize() methods to UIDrawable (#89, #98) - Create UIDrawable_methods.h with template implementations - Fix test termination issues - all tests now exit properly - Fix test_sprite_texture_swap.py click handler signature - Fix test_drawable_base.py segfault in headless mode - Convert audio objects to pointers for cleanup (OpenAL warning persists) - Remove debug print statements from UICaption - Special handling for UIEntity to delegate drawable methods to sprite All test files are now "airtight" - they complete successfully, terminate on their own, and handle edge cases properly. Author: John McCardle <mccardle.john@gmail.com> docs: add Phase 1-3 completion summary - Document all completed tasks across three phases - Show before/after API improvements - Highlight technical achievements - Outline next steps for Phase 4-7 Author: John McCardle <mccardle.john@gmail.com> feat: implement mcrfpy.Timer object with pause/resume/cancel capabilities closes #103 - Created PyTimer.h/cpp with object-oriented timer interface - Enhanced PyTimerCallable with pause/resume state tracking - Added timer control methods: pause(), resume(), cancel(), restart() - Added timer properties: interval, remaining, paused, active, callback - Fixed timing logic to prevent rapid catch-up after resume - Timer objects automatically register with game engine - Added comprehensive test demonstrating all functionality Author: John McCardle <mccardle.john@gmail.com> feat(Color): add helper methods from_hex, to_hex, lerp closes #94 - Add Color.from_hex(hex_string) class method for creating colors from hex - Support formats: #RRGGBB, RRGGBB, #RRGGBBAA, RRGGBBAA - Add color.to_hex() to convert Color to hex string - Add color.lerp(other, t) for smooth color interpolation - Comprehensive test coverage for all methods Author: John McCardle <mccardle.john@gmail.com> fix: properly configure UTF-8 encoding for Python stdio - Use PyConfig to set stdio_encoding="UTF-8" during initialization - Set stdio_errors="surrogateescape" for robust handling - Configure in both init_python() and init_python_with_config() - Cleaner solution than wrapping streams after initialization - Fixes UnicodeEncodeError when printing unicode characters Author: John McCardle <mccardle.john@gmail.com> feat(Vector): implement arithmetic operations closes #93 - Add PyNumberMethods with add, subtract, multiply, divide, negate, absolute - Add rich comparison for equality/inequality checks - Add boolean check (zero vector is False) - Implement vector methods: magnitude(), normalize(), dot(), distance_to(), angle(), copy() - Fix UIDrawable::get_click() segfault when click_callable is null - Comprehensive test coverage for all arithmetic operations Author: John McCardle <mccardle.john@gmail.com> feat: Complete position argument standardization for all UI classes - Frame and Sprite now support pos keyword override - Entity now accepts x,y arguments (was pos-only before) - All UI classes now consistently support: - (x, y) positional - ((x, y)) tuple - x=x, y=y keywords - pos=(x,y) keyword - pos=Vector keyword - Improves API consistency and flexibility Author: John McCardle <mccardle.john@gmail.com> feat: Standardize position arguments across all UI classes - Create PyPositionHelper for consistent position parsing - Grid.at() now accepts (x,y), ((x,y)), x=x, y=y, pos=(x,y) - Caption now accepts x,y args in addition to pos - Grid init fully supports keyword arguments - Maintain backward compatibility for all formats - Consistent error messages across classes Author: John McCardle <mccardle.john@gmail.com> feat: Add Entity.die() method for lifecycle management closes #30 - Remove entity from its grid's entity list - Clear grid reference after removal - Safe to call multiple times (no-op if not on grid) - Works with shared_ptr entity management Author: John McCardle <mccardle.john@gmail.com> perf: Skip out-of-bounds entities during Grid rendering closes #52 - Add visibility bounds check in entity render loop - Skip entities outside view with 1 cell margin - Improves performance for large grids with many entities - Bounds check considers zoom and pan settings Author: John McCardle <mccardle.john@gmail.com> verify: Sprite texture swapping functionality closes #19 - Texture property getter/setter already implemented - Position/scale preservation during swap confirmed - Type validation for texture assignment working - Tests verify functionality is complete Author: John McCardle <mccardle.john@gmail.com> feat: Grid size tuple support closes #90 - Add grid_size keyword parameter to Grid.__init__ - Accept tuple or list of two integers - Override grid_x/grid_y if grid_size provided - Maintain backward compatibility - Add comprehensive test coverage Author: John McCardle <mccardle.john@gmail.com> feat: Phase 1 - safe constructors and _Drawable foundation Closes #7 - Make all UI class constructors safe: - Added safe default constructors for UISprite, UIGrid, UIEntity, UICaption - Initialize all members to predictable values - Made Python init functions accept no arguments - Added x,y properties to UIEntity Closes #71 - Create _Drawable Python base class: - Created PyDrawable.h/cpp with base type (not yet inherited by UI types) - Registered in module initialization Closes #87 - Add visible property: - Added bool visible=true to UIDrawable base class - All render methods check visibility before drawing Closes #88 - Add opacity property: - Added float opacity=1.0 to UIDrawable base class - UICaption and UISprite apply opacity to alpha channel Closes #89 - Add get_bounds() method: - Virtual method returns sf::FloatRect(x,y,w,h) - Implemented in Frame, Caption, Sprite, Grid Closes #98 - Add move() and resize() methods: - move(dx,dy) for relative movement - resize(w,h) for absolute sizing - Caption resize is no-op (size controlled by font) Author: John McCardle <mccardle.john@gmail.com> docs: comprehensive alpha_streamline_2 plan and strategic vision - Add 7-phase development plan for alpha_streamline_2 branch - Define architectural dependencies and critical path - Identify new issues needed (Timer objects, event system, etc.) - Add strategic vision document with 3 transformative directions - Timeline: 10-12 weeks to solid Beta foundation Author: John McCardle <mccardle.john@gmail.com> feat(Grid): flexible at() method arguments - Support tuple argument: grid.at((x, y)) - Support keyword arguments: grid.at(x=5, y=3) - Support pos keyword: grid.at(pos=(2, 8)) - Maintain backward compatibility with grid.at(x, y) - Add comprehensive error handling for invalid arguments Improves API ergonomics and Python-like flexibility
2025-07-09 22:41:15 -04:00
typedef struct {
PyObject_HEAD
Squashed commit of the following: [alpha_presentable] Author: John McCardle <mccardle.john@gmail.com> Co-Authored-By: Claude <noreply@anthropic.com> commit dc47f2474c7b2642d368f9772894aed857527807 the UIEntity rant commit 673ca8e1b089ea670257fc04ae1a676ed95a40ed I forget when these tests were written, but I want them in the squash merge commit 70c71565c684fa96e222179271ecb13a156d80ad Fix UI object segfault by switching from managed to manual weakref management The UI types (Frame, Caption, Sprite, Grid, Entity) were using Py_TPFLAGS_MANAGED_WEAKREF while also trying to manually create weakrefs for the PythonObjectCache. This is fundamentally incompatible - when Python manages weakrefs internally, PyWeakref_NewRef() cannot access the weakref list properly, causing segfaults. Changed all UI types to use manual weakref management (like PyTimer): - Restored weakreflist field in all UI type structures - Removed Py_TPFLAGS_MANAGED_WEAKREF from all UI type flags - Added tp_weaklistoffset for all UI types in module initialization - Initialize weakreflist=NULL in tp_new and init methods - Call PyObject_ClearWeakRefs() in dealloc functions This allows the PythonObjectCache to continue working correctly, maintaining Python object identity for C++ objects across the boundary. Fixes segfault when creating UI objects (e.g., Caption, Grid) that was preventing tutorial scripts from running. This is the bulk of the required behavior for Issue #126. that issure isn't ready for closure yet; several other sub-issues left. closes #110 mention issue #109 - resolves some __init__ related nuisances commit 3dce3ec539ae99e32d869007bf3f49d03e4e2f89 Refactor timer system for cleaner architecture and enhanced functionality Major improvements to the timer system: - Unified all timer logic in the Timer class (C++) - Removed PyTimerCallable subclass, now using PyCallable directly - Timer objects are now passed to callbacks as first argument - Added 'once' parameter for one-shot timers that auto-stop - Implemented proper PythonObjectCache integration with weakref support API enhancements: - New callback signature: callback(timer, runtime) instead of just (runtime) - Timer objects expose: name, interval, remaining, paused, active, once properties - Methods: pause(), resume(), cancel(), restart() - Comprehensive documentation with examples - Enhanced repr showing timer state (active/paused/once/remaining time) This cleanup follows the UIEntity/PyUIEntity pattern and makes the timer system more Pythonic while maintaining backward compatibility through the legacy setTimer/delTimer API. closes #121 commit 145834cfc31b8dabc4cb3591b9cb4ed99fc8b964 Implement Python object cache to preserve derived types in collections Add a global cache system that maintains weak references to Python objects, ensuring that derived Python classes maintain their identity when stored in and retrieved from C++ collections. Key changes: - Add PythonObjectCache singleton with serial number system - Each cacheable object (UIDrawable, UIEntity, Timer, Animation) gets unique ID - Cache stores weak references to prevent circular reference memory leaks - Update all UI type definitions to support weak references (Py_TPFLAGS_MANAGED_WEAKREF) - Enable subclassing for all UI types (Py_TPFLAGS_BASETYPE) - Collections check cache before creating new Python wrappers - Register objects in cache during __init__ methods - Clean up cache entries in C++ destructors This ensures that Python code like: ```python class MyFrame(mcrfpy.Frame): def __init__(self): super().__init__() self.custom_data = "preserved" frame = MyFrame() scene.ui.append(frame) retrieved = scene.ui[0] # Same MyFrame instance with custom_data intact ``` Works correctly, with retrieved maintaining the derived type and custom attributes. Closes #112 commit c5e7e8e29835a69f4c50f3c99fd3123012635a9a Update test demos for new Python API and entity system - Update all text input demos to use new Entity constructor signature - Fix pathfinding showcase to work with new entity position handling - Remove entity_waypoints tracking in favor of simplified movement - Delete obsolete exhaustive_api_demo.py (superseded by newer demos) - Adjust entity creation calls to match Entity((x, y), texture, sprite_index) pattern commit 6d29652ae7418745dc24066532454167d447df89 Update animation demo suite with crash fixes and improvements - Add warnings about AnimationManager segfault bug in sizzle_reel_final.py - Create sizzle_reel_final_fixed.py that works around the crash by hiding objects instead of removing them - Increase font sizes for better visibility in demos - Extend demo durations for better showcase of animations - Remove debug prints from animation_sizzle_reel_working.py - Minor cleanup and improvements to all animation demos commit a010e5fa968feaba620dcf2eda44fb9514512151 Update game scripts for new Python API - Convert entity position access from tuple to x/y properties - Update caption size property to font_size - Fix grid boundary checks to use grid_size instead of exceptions - Clean up demo timer on menu exit to prevent callbacks These changes adapt the game scripts to work with the new standardized Python API constructors and property names. commit 9c8d6c459109be883cb8070b8ef83c60bfc1a970 Fix click event z-order handling in PyScene Changed click detection to properly respect z-index by: - Sorting ui_elements in-place when needed (same as render order) - Using reverse iterators to check highest z-index elements first - This ensures top-most elements receive clicks before lower ones commit dcd1b0ca33d46639023221f4d7d52000b947dbdf Add roguelike tutorial implementation files Implement Parts 0-2 of the classic roguelike tutorial adapted for McRogueFace: - Part 0: Basic grid setup and tile rendering - Part 1: Drawing '@' symbol and basic movement - Part 1b: Variant with sprite-based player - Part 2: Entity system and NPC implementation with three movement variants: - part_2.py: Standard implementation - part_2-naive.py: Naive movement approach - part_2-onemovequeued.py: Queued movement system Includes tutorial assets: - tutorial2.png: Tileset for dungeon tiles - tutorial_hero.png: Player sprite sheet commit 6813fb5129738cca2d79c80304834523561ba7fb Standardize Python API constructors and remove PyArgHelpers - Remove PyArgHelpers.h and all macro-based argument parsing - Convert all UI class constructors to use PyArg_ParseTupleAndKeywords - Standardize constructor signatures across UICaption, UIEntity, UIFrame, UIGrid, and UISprite - Replace PYARGHELPER_SINGLE/MULTI macros with explicit argument parsing - Improve error messages and argument validation - Maintain backward compatibility with existing Python code This change improves code maintainability and consistency across the Python API. commit 6f67fbb51efaf70e52fba8c939298dcdff50450a Fix animation callback crashes from iterator invalidation (#119) Resolved segfaults caused by creating new animations from within animation callbacks. The issue was iterator invalidation in AnimationManager::update() when callbacks modified the active animations vector. Changes: - Add deferred animation queue to AnimationManager - New animations created during update are queued and added after - Set isUpdating flag to track when in update loop - Properly handle Animation destructor during callback execution - Add clearCallback() method for safe cleanup scenarios This fixes the "free(): invalid pointer" and "malloc(): unaligned fastbin chunk detected" errors that occurred with rapid animation creation in callbacks. commit eb88c7b3aab3da519db7569106c34f3510b6e963 Add animation completion callbacks (#119) Implement callbacks that fire when animations complete, enabling direct causality between animation end and game state changes. This eliminates race conditions from parallel timer workarounds. - Add optional callback parameter to Animation constructor - Callbacks execute synchronously when animation completes - Proper Python reference counting with GIL safety - Callbacks receive (anim, target) parameters (currently None) - Exception handling prevents crashes from Python errors Example usage: ```python def on_complete(anim, target): player_moving = False anim = mcrfpy.Animation("x", 300.0, 1.0, "easeOut", callback=on_complete) anim.start(player) ``` closes #119 commit 9fb428dd0176a4d7cfad09deb7509d8aa5562868 Update ROADMAP with GitHub issue numbers (#111-#125) Added issue numbers from GitHub tracker to roadmap items: - #111: Grid Click Events Broken in Headless - #112: Object Splitting Bug (Python type preservation) - #113: Batch Operations for Grid - #114: CellView API - #115: SpatialHash Implementation - #116: Dirty Flag System - #117: Memory Pool for Entities - #118: Scene as Drawable - #119: Animation Completion Callbacks - #120: Animation Property Locking - #121: Timer Object System - #122: Parent-Child UI System - #123: Grid Subgrid System - #124: Grid Point Animation - #125: GitHub Issues Automation Also updated existing references: - #101/#110: Constructor standardization - #109: Vector class indexing Note: Tutorial-specific items and Python-implementable features (input queue, collision reservation) are not tracked as engine issues. commit 062e4dadc42833bf5a3559e5d7c4ceb4abb7e9c0 Fix animation segfaults with RAII weak_ptr implementation Resolved two critical segmentation faults in AnimationManager: 1. Race condition when creating multiple animations in timer callbacks 2. Exit crash when animations outlive their target objects Changes: - Replace raw pointers with std::weak_ptr for automatic target invalidation - Add Animation::complete() to jump animations to final value - Add Animation::hasValidTarget() to check if target still exists - Update AnimationManager to auto-remove invalid animations - Add AnimationManager::clear() call to GameEngine::cleanup() - Update Python bindings to pass shared_ptr instead of raw pointers This ensures animations can never reference destroyed objects, following proper RAII principles. Tested with sizzle_reel_final.py and stress tests creating/destroying hundreds of animated objects. commit 98fc49a978ec792ee6096f40fd4e19841b8ec6a3 Directory structure cleanup and organization overhaul
2025-07-15 21:30:49 -04:00
std::shared_ptr<Timer> data;
Squashed commit of 53 Commits: [alpha_streamline_2] * Field of View, Pathing courtesy of libtcod * python-tcod emulation at `mcrfpy.libtcod` - partial implementation * documentation, tutorial drafts: in middling to good shape ┌────────────┬────────────────────┬───────────┬────────────┬───────────────┬────────────────┬────────────────┬─────────────┐ │ Date │ Models │ Input │ Output │ Cache Create │ Cache Read │ Total Tokens │ Cost (USD) │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-05 │ - opus-4 │ 13,630 │ 159,500 │ 3,854,900 │ 84,185,034 │ 88,213,064 │ $210.72 │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-06 │ - opus-4 │ 5,814 │ 113,190 │ 4,242,407 │ 150,191,183 │ 154,552,594 │ $313.41 │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-07 │ - opus-4 │ 7,244 │ 104,599 │ 3,894,453 │ 81,781,179 │ 85,787,475 │ $184.46 │ │ │ - sonnet-4 │ │ │ │ │ │ │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-08 │ - opus-4 │ 50,312 │ 158,599 │ 5,021,189 │ 60,028,561 │ 65,258,661 │ $167.05 │ │ │ - sonnet-4 │ │ │ │ │ │ │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-09 │ - opus-4 │ 6,311 │ 109,653 │ 4,171,140 │ 80,092,875 │ 84,379,979 │ $193.09 │ │ │ - sonnet-4 │ │ │ │ │ │ │ └────────────┴────────────────────┴───────────┴────────────┴───────────────┴────────────────┴────────────────┴─────────────┘ 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> Author: John McCardle <mccardle.john@gmail.com> Draft tutorials Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP with FOV, A* pathfinding, and GUI text widget completions - Mark TCOD Integration Sprint as complete - Document FOV system with perspective rendering implementation - Update UIEntity pathfinding status to complete with A* and caching - Add comprehensive achievement entry for July 10 work - Reflect current engine capabilities accurately The engine now has all core roguelike mechanics: - Field of View with per-entity visibility - Pathfinding (both Dijkstra and A*) - Text input for in-game consoles - Performance optimizations throughout Author: John McCardle <mccardle.john@gmail.com> feat(engine): implement perspective FOV, pathfinding, and GUI text widgets Major Engine Enhancements: - Complete FOV (Field of View) system with perspective rendering - UIGrid.perspective property for entity-based visibility - Three-layer overlay colors (unexplored, explored, visible) - Per-entity visibility state tracking - Perfect knowledge updates only for explored areas - Advanced Pathfinding Integration - A* pathfinding implementation in UIGrid - Entity.path_to() method for direct pathfinding - Dijkstra maps for multi-target pathfinding - Path caching for performance optimization - GUI Text Input Widgets - TextInputWidget class with cursor, selection, scrolling - Improved widget with proper text rendering and input handling - Example showcase of multiple text input fields - Foundation for in-game console and chat systems - Performance & Architecture Improvements - PyTexture copy operations optimized - GameEngine update cycle refined - UIEntity property handling enhanced - UITestScene modernized Test Suite: - Interactive visibility demos showing FOV in action - Pathfinding comparison (A* vs Dijkstra) - Debug utilities for visibility and empty path handling - Sizzle reel demo combining pathfinding and vision - Multiple text input test scenarios This commit brings McRogueFace closer to a complete roguelike engine with essential features like line-of-sight, intelligent pathfinding, and interactive text input capabilities. Author: John McCardle <mccardle.john@gmail.com> feat(demos): enhance interactive pathfinding demos with entity.path_to() - dijkstra_interactive_enhanced.py: Animation along paths with smooth movement - M key to start movement animation - P to pause/resume - R to reset positions - Visual path gradient for better clarity - pathfinding_showcase.py: Advanced multi-entity behaviors - Chase mode: enemies pursue player - Flee mode: enemies avoid player - Patrol mode: entities follow waypoints - WASD player movement - Dijkstra distance field visualization (D key) - Larger dungeon map with multiple rooms - Both demos use new entity.path_to() method - Smooth interpolated movement animations - Real-time pathfinding recalculation - Comprehensive test coverage These demos showcase the power of integrated pathfinding for game AI. Author: John McCardle <mccardle.john@gmail.com> feat(entity): implement path_to() method for entity pathfinding - Add path_to(target_x, target_y) method to UIEntity class - Uses existing Dijkstra pathfinding implementation from UIGrid - Returns list of (x, y) coordinate tuples for complete path - Supports both positional and keyword argument formats - Proper error handling for out-of-bounds and no-grid scenarios - Comprehensive test suite covering normal and edge cases Part of TCOD integration sprint - gives entities immediate pathfinding capabilities. Author: John McCardle <mccardle.john@gmail.com> docs: update roadmap with Dijkstra pathfinding progress - Mark UIGrid TCOD Integration as completed - Document critical PyArg bug fix achievement - Update UIEntity Pathfinding to 50% complete - Add detailed progress notes for July 9 sprint work Author: John McCardle <mccardle.john@gmail.com> feat(tcod): complete Dijkstra pathfinding implementation with critical PyArg fix - Add complete Dijkstra pathfinding to UIGrid class - compute_dijkstra(), get_dijkstra_distance(), get_dijkstra_path() - Full TCODMap and TCODDijkstra integration - Proper memory management in constructors/destructors - Create mcrfpy.libtcod submodule with Python bindings - dijkstra_compute(), dijkstra_get_distance(), dijkstra_get_path() - line() function for drawing corridors - Foundation for future FOV and pathfinding algorithms - Fix critical PyArg bug in UIGridPoint color setter - PyObject_to_sfColor() now handles both Color objects and tuples - Prevents "SystemError: new style getargs format but argument is not a tuple" - Proper error handling and exception propagation - Add comprehensive test suite - test_dijkstra_simple.py validates all pathfinding operations - dijkstra_test.py for headless testing with screenshots - dijkstra_interactive.py for full user interaction demos - Consolidate and clean up test files - Removed 6 duplicate/broken demo attempts - Two clean versions: headless test + interactive demo Part of TCOD integration sprint for RoguelikeDev Tutorial Event. Author: John McCardle <mccardle.john@gmail.com> Roguelike Tutorial Planning + Prep Author: John McCardle <mccardle.john@gmail.com> feat(docs): complete markdown API documentation export - Created comprehensive markdown documentation matching HTML completeness - Documented all 75 functions, 20 classes, 56 methods, and 20 automation methods - Zero ellipsis instances - complete coverage with no missing documentation - Added proper markdown formatting with code blocks and navigation - Included full parameter documentation, return values, and examples Key features: - 23KB GitHub-compatible markdown documentation - 47 argument sections with detailed parameters - 35 return value specifications - 23 code examples with syntax highlighting - 38 explanatory notes and 10 exception specifications - Full table of contents with anchor links - Professional markdown formatting Both export formats now available: - HTML: docs/api_reference_complete.html (54KB, rich styling) - Markdown: docs/API_REFERENCE_COMPLETE.md (23KB, GitHub-compatible) Author: John McCardle <mccardle.john@gmail.com> feat(docs): complete API documentation with zero missing methods - Eliminated ALL ellipsis instances (0 remaining) - Documented 40 functions with complete signatures and examples - Documented 21 classes with full method and property documentation - Added 56 method descriptions with detailed parameters and return values - Included 15 complete property specifications - Added 24 code examples and 38 explanatory notes - Comprehensive coverage of all collection methods, system classes, and functions Key highlights: - EntityCollection/UICollection: Complete method docs (append, remove, extend, count, index) - Animation: Full property and method documentation with examples - Color: All manipulation methods (from_hex, to_hex, lerp) with examples - Vector: Complete mathematical operations (magnitude, normalize, dot, distance_to, angle, copy) - Scene: All management methods including register_keyboard - Timer: Complete control methods (pause, resume, cancel, restart) - Window: All management methods (get, center, screenshot) - System functions: Complete audio, scene, UI, and system function documentation Author: John McCardle <mccardle.john@gmail.com> feat(docs): create professional HTML API documentation - Fixed all formatting issues from original HTML output - Added comprehensive constructor documentation for all classes - Enhanced visual design with modern styling and typography - Fixed literal newline display and markdown link conversion - Added proper semantic HTML structure and navigation - Includes detailed documentation for Entity, collections, and system types Author: John McCardle <mccardle.john@gmail.com> feat: complete API reference generator and finish Phase 7 documentation Implemented comprehensive API documentation generator that: - Introspects live mcrfpy module for accurate documentation - Generates organized Markdown reference (docs/API_REFERENCE.md) - Categorizes classes and functions by type - Includes full automation module documentation - Provides summary statistics Results: - 20 classes documented - 19 module functions documented - 20 automation methods documented - 100% coverage of public API - Clean, readable Markdown output Phase 7 Summary: - Completed 4/5 tasks (1 cancelled as architecturally inappropriate) - All documentation tasks successful - Type stubs, docstrings, and API reference all complete Author: John McCardle <mccardle.john@gmail.com> docs: cancel PyPI wheel task and add future vision for Python extension architecture Task #70 Analysis: - Discovered fundamental incompatibility with PyPI distribution - McRogueFace embeds CPython rather than being loaded by it - Traditional wheels expect to extend existing Python interpreter - Current architecture is application-with-embedded-Python Decisions: - Cancelled PyPI wheel preparation as out of scope for Alpha - Cleaned up attempted packaging files (pyproject.toml, setup.py, etc.) - Identified better distribution methods (installers, package managers) Added Future Vision: - Comprehensive plan for pure Python extension architecture - Would allow true "pip install mcrogueface" experience - Requires major refactoring to invert control flow - Python would drive main loop with C++ performance extensions - Unscheduled but documented as long-term possibility This clarifies the architectural boundaries and sets realistic expectations for distribution methods while preserving the vision of what McRogueFace could become with significant rework. Author: John McCardle <mccardle.john@gmail.com> feat: generate comprehensive .pyi type stubs for IDE support (#108) Created complete type stub files for the mcrfpy module to enable: - Full IntelliSense/autocomplete in IDEs - Static type checking with mypy/pyright - Better documentation tooltips - Parameter hints and return types Implementation details: - Manually crafted stubs for accuracy (15KB, 533 lines) - Complete coverage: 19 classes, 112 functions/methods - Proper type annotations using typing module - @overload decorators for multiple signatures - Type aliases for common patterns (UIElement union) - Preserved all docstrings for IDE help - Automation module fully typed - PEP 561 compliant with py.typed marker Testing: - Validated Python syntax with ast.parse() - Verified all expected classes and functions - Confirmed type annotations are well-formed - Checked docstring preservation (80 docstrings) Usage: - VS Code: Add stubs/ to python.analysis.extraPaths - PyCharm: Mark stubs/ directory as Sources Root - Other IDEs will auto-detect .pyi files This significantly improves the developer experience when using McRogueFace as a Python game engine. Author: John McCardle <mccardle.john@gmail.com> docs: add comprehensive parameter documentation to all API methods (#86) Enhanced documentation for the mcrfpy module with: - Detailed docstrings for all API methods - Type hints in documentation (name: type format) - Return type specifications - Exception documentation where applicable - Usage examples for complex methods - Module-level documentation with overview and example code Specific improvements: - Audio API: Added parameter types and return values - Scene API: Documented transition types and error conditions - Timer API: Clarified handler signature and runtime parameter - UI Search: Added wildcard pattern examples for findAll() - Metrics API: Documented all dictionary keys returned Also fixed method signatures: - Changed METH_VARARGS to METH_NOARGS for parameterless methods - Ensures proper Python calling conventions Test coverage included - all documentation is accessible via Python's __doc__ attributes and shows correctly formatted information. Author: John McCardle <mccardle.john@gmail.com> docs: mark issue #85 as completed in Phase 7 Author: John McCardle <mccardle.john@gmail.com> docs: replace all 'docstring' placeholders with comprehensive documentation (#85) Added proper Python docstrings for all UI component classes: UIFrame: - Container element that can hold child drawables - Documents position, size, colors, outline, and clip_children - Includes constructor signature with all parameters UICaption: - Text display element with font and styling - Documents text content, position, font, colors, outline - Notes that w/h are computed from text content UISprite: - Texture/sprite display element - Documents position, texture, sprite_index, scale - Notes that w/h are computed from texture and scale UIGrid: - Tile-based grid for game worlds - Documents grid dimensions, tile size, texture atlas - Includes entities collection and background_color All docstrings follow consistent format: - Constructor signature with defaults - Brief description - Args section with types and defaults - Attributes section with all properties This completes Phase 7 task #85 for documentation improvements. Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP with PyArgHelpers infrastructure completion Author: John McCardle <mccardle.john@gmail.com> refactor: implement PyArgHelpers for standardized Python argument parsing This major refactoring standardizes how position, size, and other arguments are parsed across all UI components. PyArgHelpers provides consistent handling for various argument patterns: - Position as (x, y) tuple or separate x, y args - Size as (w, h) tuple or separate width, height args - Grid position and size with proper validation - Color parsing with PyColorObject support Changes across UI components: - UICaption: Migrated to PyArgHelpers, improved resize() for future multiline support - UIFrame: Uses standardized position parsing - UISprite: Consistent position handling - UIGrid: Grid-specific position/size helpers - UIEntity: Unified argument parsing Also includes: - Improved error messages for type mismatches (int or float accepted) - Reduced code duplication across constructors - Better handling of keyword/positional argument conflicts - Maintains backward compatibility with existing API This addresses the inconsistent argument handling patterns discovered during the inheritance hierarchy work and prepares for Phase 7 documentation. Author: John McCardle <mccardle.john@gmail.com> feat(Python): establish proper inheritance hierarchy for UI types All UIDrawable-derived Python types now properly inherit from the Drawable base class in Python, matching the C++ inheritance structure. Changes: - Add Py_TPFLAGS_BASETYPE to PyDrawableType to allow inheritance - Set tp_base = &mcrfpydef::PyDrawableType for all UI types - Add PyDrawable.h include to UI type headers - Rename _Drawable to Drawable and update error message This enables proper Python inheritance: Frame, Caption, Sprite, Grid, and Entity all inherit from Drawable, allowing shared functionality and isinstance() checks. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UISprite) - Update UISprite to use base class position instead of sprite position - Synchronize sprite position with base class position for rendering - Implement onPositionChanged() for position synchronization - Update all UISprite methods to use base position consistently - Add comprehensive test coverage for UISprite position handling This is part 3 of moving position to the base class. UIGrid is the final class that needs to be updated. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UICaption) - Update UICaption to use base class position instead of text position - Synchronize text position with base class position for rendering - Add onPositionChanged() virtual method for position synchronization - Update all UICaption methods to use base position consistently - Add comprehensive test coverage for UICaption position handling This is part 2 of moving position to the base class. UISprite and UIGrid will be updated in subsequent commits. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UIFrame) - Add position member to UIDrawable base class - Add common position getters/setters (x, y, pos) to base class - Update UIFrame to use base class position instead of box position - Synchronize box position with base class position for rendering - Update all UIFrame methods to use base position consistently - Add comprehensive test coverage for UIFrame position handling This is part 1 of moving position to the base class. Other derived classes (UICaption, UISprite, UIGrid) will be updated in subsequent commits. Author: John McCardle <mccardle.john@gmail.com> refactor: remove UIEntity collision_pos field - Remove redundant collision_pos field from UIEntity - Update position getters/setters to use integer-cast position when needed - Remove all collision_pos synchronization code - Simplify entity position handling to use single float position field - Add comprehensive test coverage proving functionality is preserved This removes technical debt and simplifies the codebase without changing API behavior. Author: John McCardle <mccardle.john@gmail.com> feat: add PyArgHelpers infrastructure for standardized argument parsing - Create PyArgHelpers.h with parsing functions for position, size, grid coordinates, and color - Support tuple-based vector arguments with conflict detection - Provide consistent error messages and validation - Add comprehensive test coverage for infrastructure This sets the foundation for standardizing all Python API constructors. Author: John McCardle <mccardle.john@gmail.com> docs: mark Phase 6 (Rendering Revolution) as complete Phase 6 is now complete with all core rendering features implemented: Completed Features: - Grid background colors (#50) - customizable backgrounds with animation - RenderTexture overhaul (#6) - UIFrame clipping with opt-in architecture - Viewport-based rendering (#8) - three scaling modes with coordinate transform Strategic Decisions: - UIGrid already has optimal RenderTexture implementation for its viewport needs - UICaption/UISprite clipping deemed unnecessary (no children to clip) - Effects/Shader/Particle systems deferred to post-Phase 7 for focused delivery The rendering foundation is now solid and ready for Phase 7: Documentation & Distribution. Author: John McCardle <mccardle.john@gmail.com> feat(viewport): complete viewport-based rendering system (#8) Implements a comprehensive viewport system that allows fixed game resolution with flexible window scaling, addressing the primary wishes for issues #34, #49, and #8. Key Features: - Fixed game resolution independent of window size (window.game_resolution property) - Three scaling modes accessible via window.scaling_mode: - "center": 1:1 pixels, viewport centered in window - "stretch": viewport fills window, ignores aspect ratio - "fit": maintains aspect ratio with black bars - Automatic window-to-game coordinate transformation for mouse input - Full Python API integration with PyWindow properties Technical Implementation: - GameEngine::ViewportMode enum with Center, Stretch, Fit modes - SFML View system for efficient GPU-based viewport scaling - updateViewport() recalculates on window resize or mode change - windowToGameCoords() transforms mouse coordinates correctly - PyScene mouse input automatically uses transformed coordinates Tests: - test_viewport_simple.py: Basic API functionality - test_viewport_visual.py: Visual verification with screenshots - test_viewport_scaling.py: Interactive mode switching and resizing This completes the viewport-based rendering task and provides the foundation for resolution-independent game development as requested for Crypt of Sokoban. Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP for Phase 6 progress - Marked Phase 6 as IN PROGRESS - Updated RenderTexture overhaul (#6) as PARTIALLY COMPLETE - Marked Grid background colors (#50) as COMPLETED - Added technical notes from implementation experience - Identified viewport rendering (#8) as next priority Author: John McCardle <mccardle.john@gmail.com> feat(rendering): implement RenderTexture base infrastructure and UIFrame clipping (#6) - Added RenderTexture support to UIDrawable base class - std::unique_ptr<sf::RenderTexture> for opt-in rendering - Dirty flag system for optimization - enableRenderTexture() and markDirty() methods - Implemented clip_children property for UIFrame - Python-accessible boolean property - Automatic RenderTexture creation when enabled - Proper coordinate transformation for nested frames - Updated UIFrame::render() for clipping support - Renders to RenderTexture when clip_children=true - Handles nested clipping correctly - Only re-renders when dirty flag is set - Added comprehensive dirty flag propagation - All property setters mark frame as dirty - Size changes recreate RenderTexture - Animation system integration - Created tests for clipping functionality - Basic clipping test with visual verification - Advanced nested clipping test - Dynamic resize handling test This is Phase 1 of the RenderTexture overhaul, providing the foundation for advanced rendering effects like blur, glow, and viewport rendering. Author: John McCardle <mccardle.john@gmail.com> docs: create RenderTexture overhaul design document - Comprehensive design for Issue #6 implementation - Opt-in architecture to maintain backward compatibility - Phased implementation plan with clear milestones - Performance considerations and risk mitigation - API design for clipping and future effects Also includes Grid background color test Author: John McCardle <mccardle.john@gmail.com> feat(Grid): add customizable background_color property (#50) - Added sf::Color background_color member with default dark gray - Python property getter/setter for background_color - Animation support for individual color components (r/g/b/a) - Replaces hardcoded clear color in render method - Test demonstrates color changes and property access Closes #50 Author: John McCardle <mccardle.john@gmail.com> docs: update roadmap for Phase 6 preparation - Mark Phase 5 (Window/Scene Architecture) as complete - Update issue statuses (#34, #61, #1, #105 completed) - Add Phase 6 implementation strategy for RenderTexture overhaul - Archive Phase 5 test files to .archive/ - Identify quick wins and technical approach for rendering work Author: John McCardle <mccardle.john@gmail.com> feat(Phase 5): Complete Window/Scene Architecture - Window singleton with properties (resolution, fullscreen, vsync, title) - OOP Scene support with lifecycle methods (on_enter, on_exit, on_keypress, update) - Window resize events trigger scene.on_resize callbacks - Scene transitions (fade, slide_left/right/up/down) with smooth animations - Full integration of Python Scene objects with C++ engine All Phase 5 tasks (#34, #1, #61, #105) completed successfully. Author: John McCardle <mccardle.john@gmail.com> research: SFML 3.0 migration analysis - Analyzed SFML 3.0 breaking changes (event system, scoped enums, C++17) - Assessed migration impact on McRogueFace (40+ files affected) - Evaluated timing relative to mcrfpy.sfml module plans - Recommended deferring migration until after mcrfpy.sfml implementation - Created SFML_3_MIGRATION_RESEARCH.md with comprehensive strategy Author: John McCardle <mccardle.john@gmail.com> research: SFML exposure options analysis (#14) - Analyzed current SFML 2.6.1 usage throughout codebase - Evaluated python-sfml (abandoned, only supports SFML 2.3.2) - Recommended direct integration as mcrfpy.sfml module - Created comprehensive SFML_EXPOSURE_RESEARCH.md with implementation plan - Identified opportunity to provide modern SFML 2.6+ Python bindings Author: John McCardle <mccardle.john@gmail.com> feat: add basic profiling/metrics system (#104) - Add ProfilingMetrics struct to track performance data - Track frame time (current and 60-frame rolling average) - Calculate FPS from average frame time - Count draw calls, UI elements, and visible elements per frame - Track total runtime and current frame number - PyScene counts elements during render - Expose metrics via mcrfpy.getMetrics() returning dict This provides basic performance monitoring capabilities for identifying bottlenecks and optimizing rendering performance. Author: John McCardle <mccardle.john@gmail.com> fix: improve click handling with proper z-order and coordinate transforms - UIFrame: Fix coordinate transformation (subtract parent pos, not add) - UIFrame: Check children in reverse order (highest z-index first) - UIFrame: Skip invisible elements entirely - PyScene: Sort elements by z-index before checking clicks - PyScene: Stop at first element that handles the click - UIGrid: Implement entity click detection with grid coordinate transform - UIGrid: Check entities in reverse order, return sprite as target Click events now correctly respect z-order (top elements get priority), handle coordinate transforms for nested frames, and support clicking on grid entities. Elements without click handlers are transparent to clicks, allowing elements below to receive them. Note: Click testing requires non-headless mode due to PyScene limitation. feat: implement name system for finding UI elements (#39/40/41) - Add 'name' property to UIDrawable base class - All UI elements (Frame, Caption, Sprite, Grid, Entity) support .name - Entity delegates name to its sprite member - Add find(name, scene=None) function for exact match search - Add findAll(pattern, scene=None) with wildcard support (* matches any sequence) - Both functions search recursively through Frame children and Grid entities - Comprehensive test coverage for all functionality This provides a simple way to find UI elements by name in Python scripts, supporting both exact matches and wildcard patterns. Author: John McCardle <mccardle.john@gmail.com> fix: prevent segfault when closing window via X button - Add cleanup() method to GameEngine to clear Python references before destruction - Clear timers and McRFPy_API references in proper order - Call cleanup() at end of run loop and in destructor - Ensure cleanup is only called once per GameEngine instance Also includes: - Fix audio ::stop() calls (already in place, OpenAL warning is benign) - Add Caption support for x, y keywords (e.g. Caption("text", x=5, y=10)) - Refactor UIDrawable_methods.h into UIBase.h for better organization - Move UIEntity-specific implementations to UIEntityPyMethods.h Author: John McCardle <mccardle.john@gmail.com> feat: stabilize test suite and add UIDrawable methods - Add visible, opacity properties to all UI classes (#87, #88) - Add get_bounds(), move(), resize() methods to UIDrawable (#89, #98) - Create UIDrawable_methods.h with template implementations - Fix test termination issues - all tests now exit properly - Fix test_sprite_texture_swap.py click handler signature - Fix test_drawable_base.py segfault in headless mode - Convert audio objects to pointers for cleanup (OpenAL warning persists) - Remove debug print statements from UICaption - Special handling for UIEntity to delegate drawable methods to sprite All test files are now "airtight" - they complete successfully, terminate on their own, and handle edge cases properly. Author: John McCardle <mccardle.john@gmail.com> docs: add Phase 1-3 completion summary - Document all completed tasks across three phases - Show before/after API improvements - Highlight technical achievements - Outline next steps for Phase 4-7 Author: John McCardle <mccardle.john@gmail.com> feat: implement mcrfpy.Timer object with pause/resume/cancel capabilities closes #103 - Created PyTimer.h/cpp with object-oriented timer interface - Enhanced PyTimerCallable with pause/resume state tracking - Added timer control methods: pause(), resume(), cancel(), restart() - Added timer properties: interval, remaining, paused, active, callback - Fixed timing logic to prevent rapid catch-up after resume - Timer objects automatically register with game engine - Added comprehensive test demonstrating all functionality Author: John McCardle <mccardle.john@gmail.com> feat(Color): add helper methods from_hex, to_hex, lerp closes #94 - Add Color.from_hex(hex_string) class method for creating colors from hex - Support formats: #RRGGBB, RRGGBB, #RRGGBBAA, RRGGBBAA - Add color.to_hex() to convert Color to hex string - Add color.lerp(other, t) for smooth color interpolation - Comprehensive test coverage for all methods Author: John McCardle <mccardle.john@gmail.com> fix: properly configure UTF-8 encoding for Python stdio - Use PyConfig to set stdio_encoding="UTF-8" during initialization - Set stdio_errors="surrogateescape" for robust handling - Configure in both init_python() and init_python_with_config() - Cleaner solution than wrapping streams after initialization - Fixes UnicodeEncodeError when printing unicode characters Author: John McCardle <mccardle.john@gmail.com> feat(Vector): implement arithmetic operations closes #93 - Add PyNumberMethods with add, subtract, multiply, divide, negate, absolute - Add rich comparison for equality/inequality checks - Add boolean check (zero vector is False) - Implement vector methods: magnitude(), normalize(), dot(), distance_to(), angle(), copy() - Fix UIDrawable::get_click() segfault when click_callable is null - Comprehensive test coverage for all arithmetic operations Author: John McCardle <mccardle.john@gmail.com> feat: Complete position argument standardization for all UI classes - Frame and Sprite now support pos keyword override - Entity now accepts x,y arguments (was pos-only before) - All UI classes now consistently support: - (x, y) positional - ((x, y)) tuple - x=x, y=y keywords - pos=(x,y) keyword - pos=Vector keyword - Improves API consistency and flexibility Author: John McCardle <mccardle.john@gmail.com> feat: Standardize position arguments across all UI classes - Create PyPositionHelper for consistent position parsing - Grid.at() now accepts (x,y), ((x,y)), x=x, y=y, pos=(x,y) - Caption now accepts x,y args in addition to pos - Grid init fully supports keyword arguments - Maintain backward compatibility for all formats - Consistent error messages across classes Author: John McCardle <mccardle.john@gmail.com> feat: Add Entity.die() method for lifecycle management closes #30 - Remove entity from its grid's entity list - Clear grid reference after removal - Safe to call multiple times (no-op if not on grid) - Works with shared_ptr entity management Author: John McCardle <mccardle.john@gmail.com> perf: Skip out-of-bounds entities during Grid rendering closes #52 - Add visibility bounds check in entity render loop - Skip entities outside view with 1 cell margin - Improves performance for large grids with many entities - Bounds check considers zoom and pan settings Author: John McCardle <mccardle.john@gmail.com> verify: Sprite texture swapping functionality closes #19 - Texture property getter/setter already implemented - Position/scale preservation during swap confirmed - Type validation for texture assignment working - Tests verify functionality is complete Author: John McCardle <mccardle.john@gmail.com> feat: Grid size tuple support closes #90 - Add grid_size keyword parameter to Grid.__init__ - Accept tuple or list of two integers - Override grid_x/grid_y if grid_size provided - Maintain backward compatibility - Add comprehensive test coverage Author: John McCardle <mccardle.john@gmail.com> feat: Phase 1 - safe constructors and _Drawable foundation Closes #7 - Make all UI class constructors safe: - Added safe default constructors for UISprite, UIGrid, UIEntity, UICaption - Initialize all members to predictable values - Made Python init functions accept no arguments - Added x,y properties to UIEntity Closes #71 - Create _Drawable Python base class: - Created PyDrawable.h/cpp with base type (not yet inherited by UI types) - Registered in module initialization Closes #87 - Add visible property: - Added bool visible=true to UIDrawable base class - All render methods check visibility before drawing Closes #88 - Add opacity property: - Added float opacity=1.0 to UIDrawable base class - UICaption and UISprite apply opacity to alpha channel Closes #89 - Add get_bounds() method: - Virtual method returns sf::FloatRect(x,y,w,h) - Implemented in Frame, Caption, Sprite, Grid Closes #98 - Add move() and resize() methods: - move(dx,dy) for relative movement - resize(w,h) for absolute sizing - Caption resize is no-op (size controlled by font) Author: John McCardle <mccardle.john@gmail.com> docs: comprehensive alpha_streamline_2 plan and strategic vision - Add 7-phase development plan for alpha_streamline_2 branch - Define architectural dependencies and critical path - Identify new issues needed (Timer objects, event system, etc.) - Add strategic vision document with 3 transformative directions - Timeline: 10-12 weeks to solid Beta foundation Author: John McCardle <mccardle.john@gmail.com> feat(Grid): flexible at() method arguments - Support tuple argument: grid.at((x, y)) - Support keyword arguments: grid.at(x=5, y=3) - Support pos keyword: grid.at(pos=(2, 8)) - Maintain backward compatibility with grid.at(x, y) - Add comprehensive error handling for invalid arguments Improves API ergonomics and Python-like flexibility
2025-07-09 22:41:15 -04:00
std::string name;
Squashed commit of the following: [alpha_presentable] Author: John McCardle <mccardle.john@gmail.com> Co-Authored-By: Claude <noreply@anthropic.com> commit dc47f2474c7b2642d368f9772894aed857527807 the UIEntity rant commit 673ca8e1b089ea670257fc04ae1a676ed95a40ed I forget when these tests were written, but I want them in the squash merge commit 70c71565c684fa96e222179271ecb13a156d80ad Fix UI object segfault by switching from managed to manual weakref management The UI types (Frame, Caption, Sprite, Grid, Entity) were using Py_TPFLAGS_MANAGED_WEAKREF while also trying to manually create weakrefs for the PythonObjectCache. This is fundamentally incompatible - when Python manages weakrefs internally, PyWeakref_NewRef() cannot access the weakref list properly, causing segfaults. Changed all UI types to use manual weakref management (like PyTimer): - Restored weakreflist field in all UI type structures - Removed Py_TPFLAGS_MANAGED_WEAKREF from all UI type flags - Added tp_weaklistoffset for all UI types in module initialization - Initialize weakreflist=NULL in tp_new and init methods - Call PyObject_ClearWeakRefs() in dealloc functions This allows the PythonObjectCache to continue working correctly, maintaining Python object identity for C++ objects across the boundary. Fixes segfault when creating UI objects (e.g., Caption, Grid) that was preventing tutorial scripts from running. This is the bulk of the required behavior for Issue #126. that issure isn't ready for closure yet; several other sub-issues left. closes #110 mention issue #109 - resolves some __init__ related nuisances commit 3dce3ec539ae99e32d869007bf3f49d03e4e2f89 Refactor timer system for cleaner architecture and enhanced functionality Major improvements to the timer system: - Unified all timer logic in the Timer class (C++) - Removed PyTimerCallable subclass, now using PyCallable directly - Timer objects are now passed to callbacks as first argument - Added 'once' parameter for one-shot timers that auto-stop - Implemented proper PythonObjectCache integration with weakref support API enhancements: - New callback signature: callback(timer, runtime) instead of just (runtime) - Timer objects expose: name, interval, remaining, paused, active, once properties - Methods: pause(), resume(), cancel(), restart() - Comprehensive documentation with examples - Enhanced repr showing timer state (active/paused/once/remaining time) This cleanup follows the UIEntity/PyUIEntity pattern and makes the timer system more Pythonic while maintaining backward compatibility through the legacy setTimer/delTimer API. closes #121 commit 145834cfc31b8dabc4cb3591b9cb4ed99fc8b964 Implement Python object cache to preserve derived types in collections Add a global cache system that maintains weak references to Python objects, ensuring that derived Python classes maintain their identity when stored in and retrieved from C++ collections. Key changes: - Add PythonObjectCache singleton with serial number system - Each cacheable object (UIDrawable, UIEntity, Timer, Animation) gets unique ID - Cache stores weak references to prevent circular reference memory leaks - Update all UI type definitions to support weak references (Py_TPFLAGS_MANAGED_WEAKREF) - Enable subclassing for all UI types (Py_TPFLAGS_BASETYPE) - Collections check cache before creating new Python wrappers - Register objects in cache during __init__ methods - Clean up cache entries in C++ destructors This ensures that Python code like: ```python class MyFrame(mcrfpy.Frame): def __init__(self): super().__init__() self.custom_data = "preserved" frame = MyFrame() scene.ui.append(frame) retrieved = scene.ui[0] # Same MyFrame instance with custom_data intact ``` Works correctly, with retrieved maintaining the derived type and custom attributes. Closes #112 commit c5e7e8e29835a69f4c50f3c99fd3123012635a9a Update test demos for new Python API and entity system - Update all text input demos to use new Entity constructor signature - Fix pathfinding showcase to work with new entity position handling - Remove entity_waypoints tracking in favor of simplified movement - Delete obsolete exhaustive_api_demo.py (superseded by newer demos) - Adjust entity creation calls to match Entity((x, y), texture, sprite_index) pattern commit 6d29652ae7418745dc24066532454167d447df89 Update animation demo suite with crash fixes and improvements - Add warnings about AnimationManager segfault bug in sizzle_reel_final.py - Create sizzle_reel_final_fixed.py that works around the crash by hiding objects instead of removing them - Increase font sizes for better visibility in demos - Extend demo durations for better showcase of animations - Remove debug prints from animation_sizzle_reel_working.py - Minor cleanup and improvements to all animation demos commit a010e5fa968feaba620dcf2eda44fb9514512151 Update game scripts for new Python API - Convert entity position access from tuple to x/y properties - Update caption size property to font_size - Fix grid boundary checks to use grid_size instead of exceptions - Clean up demo timer on menu exit to prevent callbacks These changes adapt the game scripts to work with the new standardized Python API constructors and property names. commit 9c8d6c459109be883cb8070b8ef83c60bfc1a970 Fix click event z-order handling in PyScene Changed click detection to properly respect z-index by: - Sorting ui_elements in-place when needed (same as render order) - Using reverse iterators to check highest z-index elements first - This ensures top-most elements receive clicks before lower ones commit dcd1b0ca33d46639023221f4d7d52000b947dbdf Add roguelike tutorial implementation files Implement Parts 0-2 of the classic roguelike tutorial adapted for McRogueFace: - Part 0: Basic grid setup and tile rendering - Part 1: Drawing '@' symbol and basic movement - Part 1b: Variant with sprite-based player - Part 2: Entity system and NPC implementation with three movement variants: - part_2.py: Standard implementation - part_2-naive.py: Naive movement approach - part_2-onemovequeued.py: Queued movement system Includes tutorial assets: - tutorial2.png: Tileset for dungeon tiles - tutorial_hero.png: Player sprite sheet commit 6813fb5129738cca2d79c80304834523561ba7fb Standardize Python API constructors and remove PyArgHelpers - Remove PyArgHelpers.h and all macro-based argument parsing - Convert all UI class constructors to use PyArg_ParseTupleAndKeywords - Standardize constructor signatures across UICaption, UIEntity, UIFrame, UIGrid, and UISprite - Replace PYARGHELPER_SINGLE/MULTI macros with explicit argument parsing - Improve error messages and argument validation - Maintain backward compatibility with existing Python code This change improves code maintainability and consistency across the Python API. commit 6f67fbb51efaf70e52fba8c939298dcdff50450a Fix animation callback crashes from iterator invalidation (#119) Resolved segfaults caused by creating new animations from within animation callbacks. The issue was iterator invalidation in AnimationManager::update() when callbacks modified the active animations vector. Changes: - Add deferred animation queue to AnimationManager - New animations created during update are queued and added after - Set isUpdating flag to track when in update loop - Properly handle Animation destructor during callback execution - Add clearCallback() method for safe cleanup scenarios This fixes the "free(): invalid pointer" and "malloc(): unaligned fastbin chunk detected" errors that occurred with rapid animation creation in callbacks. commit eb88c7b3aab3da519db7569106c34f3510b6e963 Add animation completion callbacks (#119) Implement callbacks that fire when animations complete, enabling direct causality between animation end and game state changes. This eliminates race conditions from parallel timer workarounds. - Add optional callback parameter to Animation constructor - Callbacks execute synchronously when animation completes - Proper Python reference counting with GIL safety - Callbacks receive (anim, target) parameters (currently None) - Exception handling prevents crashes from Python errors Example usage: ```python def on_complete(anim, target): player_moving = False anim = mcrfpy.Animation("x", 300.0, 1.0, "easeOut", callback=on_complete) anim.start(player) ``` closes #119 commit 9fb428dd0176a4d7cfad09deb7509d8aa5562868 Update ROADMAP with GitHub issue numbers (#111-#125) Added issue numbers from GitHub tracker to roadmap items: - #111: Grid Click Events Broken in Headless - #112: Object Splitting Bug (Python type preservation) - #113: Batch Operations for Grid - #114: CellView API - #115: SpatialHash Implementation - #116: Dirty Flag System - #117: Memory Pool for Entities - #118: Scene as Drawable - #119: Animation Completion Callbacks - #120: Animation Property Locking - #121: Timer Object System - #122: Parent-Child UI System - #123: Grid Subgrid System - #124: Grid Point Animation - #125: GitHub Issues Automation Also updated existing references: - #101/#110: Constructor standardization - #109: Vector class indexing Note: Tutorial-specific items and Python-implementable features (input queue, collision reservation) are not tracked as engine issues. commit 062e4dadc42833bf5a3559e5d7c4ceb4abb7e9c0 Fix animation segfaults with RAII weak_ptr implementation Resolved two critical segmentation faults in AnimationManager: 1. Race condition when creating multiple animations in timer callbacks 2. Exit crash when animations outlive their target objects Changes: - Replace raw pointers with std::weak_ptr for automatic target invalidation - Add Animation::complete() to jump animations to final value - Add Animation::hasValidTarget() to check if target still exists - Update AnimationManager to auto-remove invalid animations - Add AnimationManager::clear() call to GameEngine::cleanup() - Update Python bindings to pass shared_ptr instead of raw pointers This ensures animations can never reference destroyed objects, following proper RAII principles. Tested with sizzle_reel_final.py and stress tests creating/destroying hundreds of animated objects. commit 98fc49a978ec792ee6096f40fd4e19841b8ec6a3 Directory structure cleanup and organization overhaul
2025-07-15 21:30:49 -04:00
PyObject* weakreflist; // Weak reference support
Squashed commit of 53 Commits: [alpha_streamline_2] * Field of View, Pathing courtesy of libtcod * python-tcod emulation at `mcrfpy.libtcod` - partial implementation * documentation, tutorial drafts: in middling to good shape ┌────────────┬────────────────────┬───────────┬────────────┬───────────────┬────────────────┬────────────────┬─────────────┐ │ Date │ Models │ Input │ Output │ Cache Create │ Cache Read │ Total Tokens │ Cost (USD) │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-05 │ - opus-4 │ 13,630 │ 159,500 │ 3,854,900 │ 84,185,034 │ 88,213,064 │ $210.72 │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-06 │ - opus-4 │ 5,814 │ 113,190 │ 4,242,407 │ 150,191,183 │ 154,552,594 │ $313.41 │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-07 │ - opus-4 │ 7,244 │ 104,599 │ 3,894,453 │ 81,781,179 │ 85,787,475 │ $184.46 │ │ │ - sonnet-4 │ │ │ │ │ │ │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-08 │ - opus-4 │ 50,312 │ 158,599 │ 5,021,189 │ 60,028,561 │ 65,258,661 │ $167.05 │ │ │ - sonnet-4 │ │ │ │ │ │ │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-09 │ - opus-4 │ 6,311 │ 109,653 │ 4,171,140 │ 80,092,875 │ 84,379,979 │ $193.09 │ │ │ - sonnet-4 │ │ │ │ │ │ │ └────────────┴────────────────────┴───────────┴────────────┴───────────────┴────────────────┴────────────────┴─────────────┘ 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> Author: John McCardle <mccardle.john@gmail.com> Draft tutorials Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP with FOV, A* pathfinding, and GUI text widget completions - Mark TCOD Integration Sprint as complete - Document FOV system with perspective rendering implementation - Update UIEntity pathfinding status to complete with A* and caching - Add comprehensive achievement entry for July 10 work - Reflect current engine capabilities accurately The engine now has all core roguelike mechanics: - Field of View with per-entity visibility - Pathfinding (both Dijkstra and A*) - Text input for in-game consoles - Performance optimizations throughout Author: John McCardle <mccardle.john@gmail.com> feat(engine): implement perspective FOV, pathfinding, and GUI text widgets Major Engine Enhancements: - Complete FOV (Field of View) system with perspective rendering - UIGrid.perspective property for entity-based visibility - Three-layer overlay colors (unexplored, explored, visible) - Per-entity visibility state tracking - Perfect knowledge updates only for explored areas - Advanced Pathfinding Integration - A* pathfinding implementation in UIGrid - Entity.path_to() method for direct pathfinding - Dijkstra maps for multi-target pathfinding - Path caching for performance optimization - GUI Text Input Widgets - TextInputWidget class with cursor, selection, scrolling - Improved widget with proper text rendering and input handling - Example showcase of multiple text input fields - Foundation for in-game console and chat systems - Performance & Architecture Improvements - PyTexture copy operations optimized - GameEngine update cycle refined - UIEntity property handling enhanced - UITestScene modernized Test Suite: - Interactive visibility demos showing FOV in action - Pathfinding comparison (A* vs Dijkstra) - Debug utilities for visibility and empty path handling - Sizzle reel demo combining pathfinding and vision - Multiple text input test scenarios This commit brings McRogueFace closer to a complete roguelike engine with essential features like line-of-sight, intelligent pathfinding, and interactive text input capabilities. Author: John McCardle <mccardle.john@gmail.com> feat(demos): enhance interactive pathfinding demos with entity.path_to() - dijkstra_interactive_enhanced.py: Animation along paths with smooth movement - M key to start movement animation - P to pause/resume - R to reset positions - Visual path gradient for better clarity - pathfinding_showcase.py: Advanced multi-entity behaviors - Chase mode: enemies pursue player - Flee mode: enemies avoid player - Patrol mode: entities follow waypoints - WASD player movement - Dijkstra distance field visualization (D key) - Larger dungeon map with multiple rooms - Both demos use new entity.path_to() method - Smooth interpolated movement animations - Real-time pathfinding recalculation - Comprehensive test coverage These demos showcase the power of integrated pathfinding for game AI. Author: John McCardle <mccardle.john@gmail.com> feat(entity): implement path_to() method for entity pathfinding - Add path_to(target_x, target_y) method to UIEntity class - Uses existing Dijkstra pathfinding implementation from UIGrid - Returns list of (x, y) coordinate tuples for complete path - Supports both positional and keyword argument formats - Proper error handling for out-of-bounds and no-grid scenarios - Comprehensive test suite covering normal and edge cases Part of TCOD integration sprint - gives entities immediate pathfinding capabilities. Author: John McCardle <mccardle.john@gmail.com> docs: update roadmap with Dijkstra pathfinding progress - Mark UIGrid TCOD Integration as completed - Document critical PyArg bug fix achievement - Update UIEntity Pathfinding to 50% complete - Add detailed progress notes for July 9 sprint work Author: John McCardle <mccardle.john@gmail.com> feat(tcod): complete Dijkstra pathfinding implementation with critical PyArg fix - Add complete Dijkstra pathfinding to UIGrid class - compute_dijkstra(), get_dijkstra_distance(), get_dijkstra_path() - Full TCODMap and TCODDijkstra integration - Proper memory management in constructors/destructors - Create mcrfpy.libtcod submodule with Python bindings - dijkstra_compute(), dijkstra_get_distance(), dijkstra_get_path() - line() function for drawing corridors - Foundation for future FOV and pathfinding algorithms - Fix critical PyArg bug in UIGridPoint color setter - PyObject_to_sfColor() now handles both Color objects and tuples - Prevents "SystemError: new style getargs format but argument is not a tuple" - Proper error handling and exception propagation - Add comprehensive test suite - test_dijkstra_simple.py validates all pathfinding operations - dijkstra_test.py for headless testing with screenshots - dijkstra_interactive.py for full user interaction demos - Consolidate and clean up test files - Removed 6 duplicate/broken demo attempts - Two clean versions: headless test + interactive demo Part of TCOD integration sprint for RoguelikeDev Tutorial Event. Author: John McCardle <mccardle.john@gmail.com> Roguelike Tutorial Planning + Prep Author: John McCardle <mccardle.john@gmail.com> feat(docs): complete markdown API documentation export - Created comprehensive markdown documentation matching HTML completeness - Documented all 75 functions, 20 classes, 56 methods, and 20 automation methods - Zero ellipsis instances - complete coverage with no missing documentation - Added proper markdown formatting with code blocks and navigation - Included full parameter documentation, return values, and examples Key features: - 23KB GitHub-compatible markdown documentation - 47 argument sections with detailed parameters - 35 return value specifications - 23 code examples with syntax highlighting - 38 explanatory notes and 10 exception specifications - Full table of contents with anchor links - Professional markdown formatting Both export formats now available: - HTML: docs/api_reference_complete.html (54KB, rich styling) - Markdown: docs/API_REFERENCE_COMPLETE.md (23KB, GitHub-compatible) Author: John McCardle <mccardle.john@gmail.com> feat(docs): complete API documentation with zero missing methods - Eliminated ALL ellipsis instances (0 remaining) - Documented 40 functions with complete signatures and examples - Documented 21 classes with full method and property documentation - Added 56 method descriptions with detailed parameters and return values - Included 15 complete property specifications - Added 24 code examples and 38 explanatory notes - Comprehensive coverage of all collection methods, system classes, and functions Key highlights: - EntityCollection/UICollection: Complete method docs (append, remove, extend, count, index) - Animation: Full property and method documentation with examples - Color: All manipulation methods (from_hex, to_hex, lerp) with examples - Vector: Complete mathematical operations (magnitude, normalize, dot, distance_to, angle, copy) - Scene: All management methods including register_keyboard - Timer: Complete control methods (pause, resume, cancel, restart) - Window: All management methods (get, center, screenshot) - System functions: Complete audio, scene, UI, and system function documentation Author: John McCardle <mccardle.john@gmail.com> feat(docs): create professional HTML API documentation - Fixed all formatting issues from original HTML output - Added comprehensive constructor documentation for all classes - Enhanced visual design with modern styling and typography - Fixed literal newline display and markdown link conversion - Added proper semantic HTML structure and navigation - Includes detailed documentation for Entity, collections, and system types Author: John McCardle <mccardle.john@gmail.com> feat: complete API reference generator and finish Phase 7 documentation Implemented comprehensive API documentation generator that: - Introspects live mcrfpy module for accurate documentation - Generates organized Markdown reference (docs/API_REFERENCE.md) - Categorizes classes and functions by type - Includes full automation module documentation - Provides summary statistics Results: - 20 classes documented - 19 module functions documented - 20 automation methods documented - 100% coverage of public API - Clean, readable Markdown output Phase 7 Summary: - Completed 4/5 tasks (1 cancelled as architecturally inappropriate) - All documentation tasks successful - Type stubs, docstrings, and API reference all complete Author: John McCardle <mccardle.john@gmail.com> docs: cancel PyPI wheel task and add future vision for Python extension architecture Task #70 Analysis: - Discovered fundamental incompatibility with PyPI distribution - McRogueFace embeds CPython rather than being loaded by it - Traditional wheels expect to extend existing Python interpreter - Current architecture is application-with-embedded-Python Decisions: - Cancelled PyPI wheel preparation as out of scope for Alpha - Cleaned up attempted packaging files (pyproject.toml, setup.py, etc.) - Identified better distribution methods (installers, package managers) Added Future Vision: - Comprehensive plan for pure Python extension architecture - Would allow true "pip install mcrogueface" experience - Requires major refactoring to invert control flow - Python would drive main loop with C++ performance extensions - Unscheduled but documented as long-term possibility This clarifies the architectural boundaries and sets realistic expectations for distribution methods while preserving the vision of what McRogueFace could become with significant rework. Author: John McCardle <mccardle.john@gmail.com> feat: generate comprehensive .pyi type stubs for IDE support (#108) Created complete type stub files for the mcrfpy module to enable: - Full IntelliSense/autocomplete in IDEs - Static type checking with mypy/pyright - Better documentation tooltips - Parameter hints and return types Implementation details: - Manually crafted stubs for accuracy (15KB, 533 lines) - Complete coverage: 19 classes, 112 functions/methods - Proper type annotations using typing module - @overload decorators for multiple signatures - Type aliases for common patterns (UIElement union) - Preserved all docstrings for IDE help - Automation module fully typed - PEP 561 compliant with py.typed marker Testing: - Validated Python syntax with ast.parse() - Verified all expected classes and functions - Confirmed type annotations are well-formed - Checked docstring preservation (80 docstrings) Usage: - VS Code: Add stubs/ to python.analysis.extraPaths - PyCharm: Mark stubs/ directory as Sources Root - Other IDEs will auto-detect .pyi files This significantly improves the developer experience when using McRogueFace as a Python game engine. Author: John McCardle <mccardle.john@gmail.com> docs: add comprehensive parameter documentation to all API methods (#86) Enhanced documentation for the mcrfpy module with: - Detailed docstrings for all API methods - Type hints in documentation (name: type format) - Return type specifications - Exception documentation where applicable - Usage examples for complex methods - Module-level documentation with overview and example code Specific improvements: - Audio API: Added parameter types and return values - Scene API: Documented transition types and error conditions - Timer API: Clarified handler signature and runtime parameter - UI Search: Added wildcard pattern examples for findAll() - Metrics API: Documented all dictionary keys returned Also fixed method signatures: - Changed METH_VARARGS to METH_NOARGS for parameterless methods - Ensures proper Python calling conventions Test coverage included - all documentation is accessible via Python's __doc__ attributes and shows correctly formatted information. Author: John McCardle <mccardle.john@gmail.com> docs: mark issue #85 as completed in Phase 7 Author: John McCardle <mccardle.john@gmail.com> docs: replace all 'docstring' placeholders with comprehensive documentation (#85) Added proper Python docstrings for all UI component classes: UIFrame: - Container element that can hold child drawables - Documents position, size, colors, outline, and clip_children - Includes constructor signature with all parameters UICaption: - Text display element with font and styling - Documents text content, position, font, colors, outline - Notes that w/h are computed from text content UISprite: - Texture/sprite display element - Documents position, texture, sprite_index, scale - Notes that w/h are computed from texture and scale UIGrid: - Tile-based grid for game worlds - Documents grid dimensions, tile size, texture atlas - Includes entities collection and background_color All docstrings follow consistent format: - Constructor signature with defaults - Brief description - Args section with types and defaults - Attributes section with all properties This completes Phase 7 task #85 for documentation improvements. Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP with PyArgHelpers infrastructure completion Author: John McCardle <mccardle.john@gmail.com> refactor: implement PyArgHelpers for standardized Python argument parsing This major refactoring standardizes how position, size, and other arguments are parsed across all UI components. PyArgHelpers provides consistent handling for various argument patterns: - Position as (x, y) tuple or separate x, y args - Size as (w, h) tuple or separate width, height args - Grid position and size with proper validation - Color parsing with PyColorObject support Changes across UI components: - UICaption: Migrated to PyArgHelpers, improved resize() for future multiline support - UIFrame: Uses standardized position parsing - UISprite: Consistent position handling - UIGrid: Grid-specific position/size helpers - UIEntity: Unified argument parsing Also includes: - Improved error messages for type mismatches (int or float accepted) - Reduced code duplication across constructors - Better handling of keyword/positional argument conflicts - Maintains backward compatibility with existing API This addresses the inconsistent argument handling patterns discovered during the inheritance hierarchy work and prepares for Phase 7 documentation. Author: John McCardle <mccardle.john@gmail.com> feat(Python): establish proper inheritance hierarchy for UI types All UIDrawable-derived Python types now properly inherit from the Drawable base class in Python, matching the C++ inheritance structure. Changes: - Add Py_TPFLAGS_BASETYPE to PyDrawableType to allow inheritance - Set tp_base = &mcrfpydef::PyDrawableType for all UI types - Add PyDrawable.h include to UI type headers - Rename _Drawable to Drawable and update error message This enables proper Python inheritance: Frame, Caption, Sprite, Grid, and Entity all inherit from Drawable, allowing shared functionality and isinstance() checks. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UISprite) - Update UISprite to use base class position instead of sprite position - Synchronize sprite position with base class position for rendering - Implement onPositionChanged() for position synchronization - Update all UISprite methods to use base position consistently - Add comprehensive test coverage for UISprite position handling This is part 3 of moving position to the base class. UIGrid is the final class that needs to be updated. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UICaption) - Update UICaption to use base class position instead of text position - Synchronize text position with base class position for rendering - Add onPositionChanged() virtual method for position synchronization - Update all UICaption methods to use base position consistently - Add comprehensive test coverage for UICaption position handling This is part 2 of moving position to the base class. UISprite and UIGrid will be updated in subsequent commits. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UIFrame) - Add position member to UIDrawable base class - Add common position getters/setters (x, y, pos) to base class - Update UIFrame to use base class position instead of box position - Synchronize box position with base class position for rendering - Update all UIFrame methods to use base position consistently - Add comprehensive test coverage for UIFrame position handling This is part 1 of moving position to the base class. Other derived classes (UICaption, UISprite, UIGrid) will be updated in subsequent commits. Author: John McCardle <mccardle.john@gmail.com> refactor: remove UIEntity collision_pos field - Remove redundant collision_pos field from UIEntity - Update position getters/setters to use integer-cast position when needed - Remove all collision_pos synchronization code - Simplify entity position handling to use single float position field - Add comprehensive test coverage proving functionality is preserved This removes technical debt and simplifies the codebase without changing API behavior. Author: John McCardle <mccardle.john@gmail.com> feat: add PyArgHelpers infrastructure for standardized argument parsing - Create PyArgHelpers.h with parsing functions for position, size, grid coordinates, and color - Support tuple-based vector arguments with conflict detection - Provide consistent error messages and validation - Add comprehensive test coverage for infrastructure This sets the foundation for standardizing all Python API constructors. Author: John McCardle <mccardle.john@gmail.com> docs: mark Phase 6 (Rendering Revolution) as complete Phase 6 is now complete with all core rendering features implemented: Completed Features: - Grid background colors (#50) - customizable backgrounds with animation - RenderTexture overhaul (#6) - UIFrame clipping with opt-in architecture - Viewport-based rendering (#8) - three scaling modes with coordinate transform Strategic Decisions: - UIGrid already has optimal RenderTexture implementation for its viewport needs - UICaption/UISprite clipping deemed unnecessary (no children to clip) - Effects/Shader/Particle systems deferred to post-Phase 7 for focused delivery The rendering foundation is now solid and ready for Phase 7: Documentation & Distribution. Author: John McCardle <mccardle.john@gmail.com> feat(viewport): complete viewport-based rendering system (#8) Implements a comprehensive viewport system that allows fixed game resolution with flexible window scaling, addressing the primary wishes for issues #34, #49, and #8. Key Features: - Fixed game resolution independent of window size (window.game_resolution property) - Three scaling modes accessible via window.scaling_mode: - "center": 1:1 pixels, viewport centered in window - "stretch": viewport fills window, ignores aspect ratio - "fit": maintains aspect ratio with black bars - Automatic window-to-game coordinate transformation for mouse input - Full Python API integration with PyWindow properties Technical Implementation: - GameEngine::ViewportMode enum with Center, Stretch, Fit modes - SFML View system for efficient GPU-based viewport scaling - updateViewport() recalculates on window resize or mode change - windowToGameCoords() transforms mouse coordinates correctly - PyScene mouse input automatically uses transformed coordinates Tests: - test_viewport_simple.py: Basic API functionality - test_viewport_visual.py: Visual verification with screenshots - test_viewport_scaling.py: Interactive mode switching and resizing This completes the viewport-based rendering task and provides the foundation for resolution-independent game development as requested for Crypt of Sokoban. Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP for Phase 6 progress - Marked Phase 6 as IN PROGRESS - Updated RenderTexture overhaul (#6) as PARTIALLY COMPLETE - Marked Grid background colors (#50) as COMPLETED - Added technical notes from implementation experience - Identified viewport rendering (#8) as next priority Author: John McCardle <mccardle.john@gmail.com> feat(rendering): implement RenderTexture base infrastructure and UIFrame clipping (#6) - Added RenderTexture support to UIDrawable base class - std::unique_ptr<sf::RenderTexture> for opt-in rendering - Dirty flag system for optimization - enableRenderTexture() and markDirty() methods - Implemented clip_children property for UIFrame - Python-accessible boolean property - Automatic RenderTexture creation when enabled - Proper coordinate transformation for nested frames - Updated UIFrame::render() for clipping support - Renders to RenderTexture when clip_children=true - Handles nested clipping correctly - Only re-renders when dirty flag is set - Added comprehensive dirty flag propagation - All property setters mark frame as dirty - Size changes recreate RenderTexture - Animation system integration - Created tests for clipping functionality - Basic clipping test with visual verification - Advanced nested clipping test - Dynamic resize handling test This is Phase 1 of the RenderTexture overhaul, providing the foundation for advanced rendering effects like blur, glow, and viewport rendering. Author: John McCardle <mccardle.john@gmail.com> docs: create RenderTexture overhaul design document - Comprehensive design for Issue #6 implementation - Opt-in architecture to maintain backward compatibility - Phased implementation plan with clear milestones - Performance considerations and risk mitigation - API design for clipping and future effects Also includes Grid background color test Author: John McCardle <mccardle.john@gmail.com> feat(Grid): add customizable background_color property (#50) - Added sf::Color background_color member with default dark gray - Python property getter/setter for background_color - Animation support for individual color components (r/g/b/a) - Replaces hardcoded clear color in render method - Test demonstrates color changes and property access Closes #50 Author: John McCardle <mccardle.john@gmail.com> docs: update roadmap for Phase 6 preparation - Mark Phase 5 (Window/Scene Architecture) as complete - Update issue statuses (#34, #61, #1, #105 completed) - Add Phase 6 implementation strategy for RenderTexture overhaul - Archive Phase 5 test files to .archive/ - Identify quick wins and technical approach for rendering work Author: John McCardle <mccardle.john@gmail.com> feat(Phase 5): Complete Window/Scene Architecture - Window singleton with properties (resolution, fullscreen, vsync, title) - OOP Scene support with lifecycle methods (on_enter, on_exit, on_keypress, update) - Window resize events trigger scene.on_resize callbacks - Scene transitions (fade, slide_left/right/up/down) with smooth animations - Full integration of Python Scene objects with C++ engine All Phase 5 tasks (#34, #1, #61, #105) completed successfully. Author: John McCardle <mccardle.john@gmail.com> research: SFML 3.0 migration analysis - Analyzed SFML 3.0 breaking changes (event system, scoped enums, C++17) - Assessed migration impact on McRogueFace (40+ files affected) - Evaluated timing relative to mcrfpy.sfml module plans - Recommended deferring migration until after mcrfpy.sfml implementation - Created SFML_3_MIGRATION_RESEARCH.md with comprehensive strategy Author: John McCardle <mccardle.john@gmail.com> research: SFML exposure options analysis (#14) - Analyzed current SFML 2.6.1 usage throughout codebase - Evaluated python-sfml (abandoned, only supports SFML 2.3.2) - Recommended direct integration as mcrfpy.sfml module - Created comprehensive SFML_EXPOSURE_RESEARCH.md with implementation plan - Identified opportunity to provide modern SFML 2.6+ Python bindings Author: John McCardle <mccardle.john@gmail.com> feat: add basic profiling/metrics system (#104) - Add ProfilingMetrics struct to track performance data - Track frame time (current and 60-frame rolling average) - Calculate FPS from average frame time - Count draw calls, UI elements, and visible elements per frame - Track total runtime and current frame number - PyScene counts elements during render - Expose metrics via mcrfpy.getMetrics() returning dict This provides basic performance monitoring capabilities for identifying bottlenecks and optimizing rendering performance. Author: John McCardle <mccardle.john@gmail.com> fix: improve click handling with proper z-order and coordinate transforms - UIFrame: Fix coordinate transformation (subtract parent pos, not add) - UIFrame: Check children in reverse order (highest z-index first) - UIFrame: Skip invisible elements entirely - PyScene: Sort elements by z-index before checking clicks - PyScene: Stop at first element that handles the click - UIGrid: Implement entity click detection with grid coordinate transform - UIGrid: Check entities in reverse order, return sprite as target Click events now correctly respect z-order (top elements get priority), handle coordinate transforms for nested frames, and support clicking on grid entities. Elements without click handlers are transparent to clicks, allowing elements below to receive them. Note: Click testing requires non-headless mode due to PyScene limitation. feat: implement name system for finding UI elements (#39/40/41) - Add 'name' property to UIDrawable base class - All UI elements (Frame, Caption, Sprite, Grid, Entity) support .name - Entity delegates name to its sprite member - Add find(name, scene=None) function for exact match search - Add findAll(pattern, scene=None) with wildcard support (* matches any sequence) - Both functions search recursively through Frame children and Grid entities - Comprehensive test coverage for all functionality This provides a simple way to find UI elements by name in Python scripts, supporting both exact matches and wildcard patterns. Author: John McCardle <mccardle.john@gmail.com> fix: prevent segfault when closing window via X button - Add cleanup() method to GameEngine to clear Python references before destruction - Clear timers and McRFPy_API references in proper order - Call cleanup() at end of run loop and in destructor - Ensure cleanup is only called once per GameEngine instance Also includes: - Fix audio ::stop() calls (already in place, OpenAL warning is benign) - Add Caption support for x, y keywords (e.g. Caption("text", x=5, y=10)) - Refactor UIDrawable_methods.h into UIBase.h for better organization - Move UIEntity-specific implementations to UIEntityPyMethods.h Author: John McCardle <mccardle.john@gmail.com> feat: stabilize test suite and add UIDrawable methods - Add visible, opacity properties to all UI classes (#87, #88) - Add get_bounds(), move(), resize() methods to UIDrawable (#89, #98) - Create UIDrawable_methods.h with template implementations - Fix test termination issues - all tests now exit properly - Fix test_sprite_texture_swap.py click handler signature - Fix test_drawable_base.py segfault in headless mode - Convert audio objects to pointers for cleanup (OpenAL warning persists) - Remove debug print statements from UICaption - Special handling for UIEntity to delegate drawable methods to sprite All test files are now "airtight" - they complete successfully, terminate on their own, and handle edge cases properly. Author: John McCardle <mccardle.john@gmail.com> docs: add Phase 1-3 completion summary - Document all completed tasks across three phases - Show before/after API improvements - Highlight technical achievements - Outline next steps for Phase 4-7 Author: John McCardle <mccardle.john@gmail.com> feat: implement mcrfpy.Timer object with pause/resume/cancel capabilities closes #103 - Created PyTimer.h/cpp with object-oriented timer interface - Enhanced PyTimerCallable with pause/resume state tracking - Added timer control methods: pause(), resume(), cancel(), restart() - Added timer properties: interval, remaining, paused, active, callback - Fixed timing logic to prevent rapid catch-up after resume - Timer objects automatically register with game engine - Added comprehensive test demonstrating all functionality Author: John McCardle <mccardle.john@gmail.com> feat(Color): add helper methods from_hex, to_hex, lerp closes #94 - Add Color.from_hex(hex_string) class method for creating colors from hex - Support formats: #RRGGBB, RRGGBB, #RRGGBBAA, RRGGBBAA - Add color.to_hex() to convert Color to hex string - Add color.lerp(other, t) for smooth color interpolation - Comprehensive test coverage for all methods Author: John McCardle <mccardle.john@gmail.com> fix: properly configure UTF-8 encoding for Python stdio - Use PyConfig to set stdio_encoding="UTF-8" during initialization - Set stdio_errors="surrogateescape" for robust handling - Configure in both init_python() and init_python_with_config() - Cleaner solution than wrapping streams after initialization - Fixes UnicodeEncodeError when printing unicode characters Author: John McCardle <mccardle.john@gmail.com> feat(Vector): implement arithmetic operations closes #93 - Add PyNumberMethods with add, subtract, multiply, divide, negate, absolute - Add rich comparison for equality/inequality checks - Add boolean check (zero vector is False) - Implement vector methods: magnitude(), normalize(), dot(), distance_to(), angle(), copy() - Fix UIDrawable::get_click() segfault when click_callable is null - Comprehensive test coverage for all arithmetic operations Author: John McCardle <mccardle.john@gmail.com> feat: Complete position argument standardization for all UI classes - Frame and Sprite now support pos keyword override - Entity now accepts x,y arguments (was pos-only before) - All UI classes now consistently support: - (x, y) positional - ((x, y)) tuple - x=x, y=y keywords - pos=(x,y) keyword - pos=Vector keyword - Improves API consistency and flexibility Author: John McCardle <mccardle.john@gmail.com> feat: Standardize position arguments across all UI classes - Create PyPositionHelper for consistent position parsing - Grid.at() now accepts (x,y), ((x,y)), x=x, y=y, pos=(x,y) - Caption now accepts x,y args in addition to pos - Grid init fully supports keyword arguments - Maintain backward compatibility for all formats - Consistent error messages across classes Author: John McCardle <mccardle.john@gmail.com> feat: Add Entity.die() method for lifecycle management closes #30 - Remove entity from its grid's entity list - Clear grid reference after removal - Safe to call multiple times (no-op if not on grid) - Works with shared_ptr entity management Author: John McCardle <mccardle.john@gmail.com> perf: Skip out-of-bounds entities during Grid rendering closes #52 - Add visibility bounds check in entity render loop - Skip entities outside view with 1 cell margin - Improves performance for large grids with many entities - Bounds check considers zoom and pan settings Author: John McCardle <mccardle.john@gmail.com> verify: Sprite texture swapping functionality closes #19 - Texture property getter/setter already implemented - Position/scale preservation during swap confirmed - Type validation for texture assignment working - Tests verify functionality is complete Author: John McCardle <mccardle.john@gmail.com> feat: Grid size tuple support closes #90 - Add grid_size keyword parameter to Grid.__init__ - Accept tuple or list of two integers - Override grid_x/grid_y if grid_size provided - Maintain backward compatibility - Add comprehensive test coverage Author: John McCardle <mccardle.john@gmail.com> feat: Phase 1 - safe constructors and _Drawable foundation Closes #7 - Make all UI class constructors safe: - Added safe default constructors for UISprite, UIGrid, UIEntity, UICaption - Initialize all members to predictable values - Made Python init functions accept no arguments - Added x,y properties to UIEntity Closes #71 - Create _Drawable Python base class: - Created PyDrawable.h/cpp with base type (not yet inherited by UI types) - Registered in module initialization Closes #87 - Add visible property: - Added bool visible=true to UIDrawable base class - All render methods check visibility before drawing Closes #88 - Add opacity property: - Added float opacity=1.0 to UIDrawable base class - UICaption and UISprite apply opacity to alpha channel Closes #89 - Add get_bounds() method: - Virtual method returns sf::FloatRect(x,y,w,h) - Implemented in Frame, Caption, Sprite, Grid Closes #98 - Add move() and resize() methods: - move(dx,dy) for relative movement - resize(w,h) for absolute sizing - Caption resize is no-op (size controlled by font) Author: John McCardle <mccardle.john@gmail.com> docs: comprehensive alpha_streamline_2 plan and strategic vision - Add 7-phase development plan for alpha_streamline_2 branch - Define architectural dependencies and critical path - Identify new issues needed (Timer objects, event system, etc.) - Add strategic vision document with 3 transformative directions - Timeline: 10-12 weeks to solid Beta foundation Author: John McCardle <mccardle.john@gmail.com> feat(Grid): flexible at() method arguments - Support tuple argument: grid.at((x, y)) - Support keyword arguments: grid.at(x=5, y=3) - Support pos keyword: grid.at(pos=(2, 8)) - Maintain backward compatibility with grid.at(x, y) - Add comprehensive error handling for invalid arguments Improves API ergonomics and Python-like flexibility
2025-07-09 22:41:15 -04:00
} PyTimerObject;
class PyTimer
{
public:
// Python type methods
static PyObject* repr(PyObject* self);
static int init(PyTimerObject* self, PyObject* args, PyObject* kwds);
static PyObject* pynew(PyTypeObject* type, PyObject* args=NULL, PyObject* kwds=NULL);
static void dealloc(PyTimerObject* self);
// Timer control methods
static PyObject* pause(PyTimerObject* self, PyObject* Py_UNUSED(ignored));
static PyObject* resume(PyTimerObject* self, PyObject* Py_UNUSED(ignored));
static PyObject* cancel(PyTimerObject* self, PyObject* Py_UNUSED(ignored));
static PyObject* restart(PyTimerObject* self, PyObject* Py_UNUSED(ignored));
// Timer property getters
Squashed commit of the following: [alpha_presentable] Author: John McCardle <mccardle.john@gmail.com> Co-Authored-By: Claude <noreply@anthropic.com> commit dc47f2474c7b2642d368f9772894aed857527807 the UIEntity rant commit 673ca8e1b089ea670257fc04ae1a676ed95a40ed I forget when these tests were written, but I want them in the squash merge commit 70c71565c684fa96e222179271ecb13a156d80ad Fix UI object segfault by switching from managed to manual weakref management The UI types (Frame, Caption, Sprite, Grid, Entity) were using Py_TPFLAGS_MANAGED_WEAKREF while also trying to manually create weakrefs for the PythonObjectCache. This is fundamentally incompatible - when Python manages weakrefs internally, PyWeakref_NewRef() cannot access the weakref list properly, causing segfaults. Changed all UI types to use manual weakref management (like PyTimer): - Restored weakreflist field in all UI type structures - Removed Py_TPFLAGS_MANAGED_WEAKREF from all UI type flags - Added tp_weaklistoffset for all UI types in module initialization - Initialize weakreflist=NULL in tp_new and init methods - Call PyObject_ClearWeakRefs() in dealloc functions This allows the PythonObjectCache to continue working correctly, maintaining Python object identity for C++ objects across the boundary. Fixes segfault when creating UI objects (e.g., Caption, Grid) that was preventing tutorial scripts from running. This is the bulk of the required behavior for Issue #126. that issure isn't ready for closure yet; several other sub-issues left. closes #110 mention issue #109 - resolves some __init__ related nuisances commit 3dce3ec539ae99e32d869007bf3f49d03e4e2f89 Refactor timer system for cleaner architecture and enhanced functionality Major improvements to the timer system: - Unified all timer logic in the Timer class (C++) - Removed PyTimerCallable subclass, now using PyCallable directly - Timer objects are now passed to callbacks as first argument - Added 'once' parameter for one-shot timers that auto-stop - Implemented proper PythonObjectCache integration with weakref support API enhancements: - New callback signature: callback(timer, runtime) instead of just (runtime) - Timer objects expose: name, interval, remaining, paused, active, once properties - Methods: pause(), resume(), cancel(), restart() - Comprehensive documentation with examples - Enhanced repr showing timer state (active/paused/once/remaining time) This cleanup follows the UIEntity/PyUIEntity pattern and makes the timer system more Pythonic while maintaining backward compatibility through the legacy setTimer/delTimer API. closes #121 commit 145834cfc31b8dabc4cb3591b9cb4ed99fc8b964 Implement Python object cache to preserve derived types in collections Add a global cache system that maintains weak references to Python objects, ensuring that derived Python classes maintain their identity when stored in and retrieved from C++ collections. Key changes: - Add PythonObjectCache singleton with serial number system - Each cacheable object (UIDrawable, UIEntity, Timer, Animation) gets unique ID - Cache stores weak references to prevent circular reference memory leaks - Update all UI type definitions to support weak references (Py_TPFLAGS_MANAGED_WEAKREF) - Enable subclassing for all UI types (Py_TPFLAGS_BASETYPE) - Collections check cache before creating new Python wrappers - Register objects in cache during __init__ methods - Clean up cache entries in C++ destructors This ensures that Python code like: ```python class MyFrame(mcrfpy.Frame): def __init__(self): super().__init__() self.custom_data = "preserved" frame = MyFrame() scene.ui.append(frame) retrieved = scene.ui[0] # Same MyFrame instance with custom_data intact ``` Works correctly, with retrieved maintaining the derived type and custom attributes. Closes #112 commit c5e7e8e29835a69f4c50f3c99fd3123012635a9a Update test demos for new Python API and entity system - Update all text input demos to use new Entity constructor signature - Fix pathfinding showcase to work with new entity position handling - Remove entity_waypoints tracking in favor of simplified movement - Delete obsolete exhaustive_api_demo.py (superseded by newer demos) - Adjust entity creation calls to match Entity((x, y), texture, sprite_index) pattern commit 6d29652ae7418745dc24066532454167d447df89 Update animation demo suite with crash fixes and improvements - Add warnings about AnimationManager segfault bug in sizzle_reel_final.py - Create sizzle_reel_final_fixed.py that works around the crash by hiding objects instead of removing them - Increase font sizes for better visibility in demos - Extend demo durations for better showcase of animations - Remove debug prints from animation_sizzle_reel_working.py - Minor cleanup and improvements to all animation demos commit a010e5fa968feaba620dcf2eda44fb9514512151 Update game scripts for new Python API - Convert entity position access from tuple to x/y properties - Update caption size property to font_size - Fix grid boundary checks to use grid_size instead of exceptions - Clean up demo timer on menu exit to prevent callbacks These changes adapt the game scripts to work with the new standardized Python API constructors and property names. commit 9c8d6c459109be883cb8070b8ef83c60bfc1a970 Fix click event z-order handling in PyScene Changed click detection to properly respect z-index by: - Sorting ui_elements in-place when needed (same as render order) - Using reverse iterators to check highest z-index elements first - This ensures top-most elements receive clicks before lower ones commit dcd1b0ca33d46639023221f4d7d52000b947dbdf Add roguelike tutorial implementation files Implement Parts 0-2 of the classic roguelike tutorial adapted for McRogueFace: - Part 0: Basic grid setup and tile rendering - Part 1: Drawing '@' symbol and basic movement - Part 1b: Variant with sprite-based player - Part 2: Entity system and NPC implementation with three movement variants: - part_2.py: Standard implementation - part_2-naive.py: Naive movement approach - part_2-onemovequeued.py: Queued movement system Includes tutorial assets: - tutorial2.png: Tileset for dungeon tiles - tutorial_hero.png: Player sprite sheet commit 6813fb5129738cca2d79c80304834523561ba7fb Standardize Python API constructors and remove PyArgHelpers - Remove PyArgHelpers.h and all macro-based argument parsing - Convert all UI class constructors to use PyArg_ParseTupleAndKeywords - Standardize constructor signatures across UICaption, UIEntity, UIFrame, UIGrid, and UISprite - Replace PYARGHELPER_SINGLE/MULTI macros with explicit argument parsing - Improve error messages and argument validation - Maintain backward compatibility with existing Python code This change improves code maintainability and consistency across the Python API. commit 6f67fbb51efaf70e52fba8c939298dcdff50450a Fix animation callback crashes from iterator invalidation (#119) Resolved segfaults caused by creating new animations from within animation callbacks. The issue was iterator invalidation in AnimationManager::update() when callbacks modified the active animations vector. Changes: - Add deferred animation queue to AnimationManager - New animations created during update are queued and added after - Set isUpdating flag to track when in update loop - Properly handle Animation destructor during callback execution - Add clearCallback() method for safe cleanup scenarios This fixes the "free(): invalid pointer" and "malloc(): unaligned fastbin chunk detected" errors that occurred with rapid animation creation in callbacks. commit eb88c7b3aab3da519db7569106c34f3510b6e963 Add animation completion callbacks (#119) Implement callbacks that fire when animations complete, enabling direct causality between animation end and game state changes. This eliminates race conditions from parallel timer workarounds. - Add optional callback parameter to Animation constructor - Callbacks execute synchronously when animation completes - Proper Python reference counting with GIL safety - Callbacks receive (anim, target) parameters (currently None) - Exception handling prevents crashes from Python errors Example usage: ```python def on_complete(anim, target): player_moving = False anim = mcrfpy.Animation("x", 300.0, 1.0, "easeOut", callback=on_complete) anim.start(player) ``` closes #119 commit 9fb428dd0176a4d7cfad09deb7509d8aa5562868 Update ROADMAP with GitHub issue numbers (#111-#125) Added issue numbers from GitHub tracker to roadmap items: - #111: Grid Click Events Broken in Headless - #112: Object Splitting Bug (Python type preservation) - #113: Batch Operations for Grid - #114: CellView API - #115: SpatialHash Implementation - #116: Dirty Flag System - #117: Memory Pool for Entities - #118: Scene as Drawable - #119: Animation Completion Callbacks - #120: Animation Property Locking - #121: Timer Object System - #122: Parent-Child UI System - #123: Grid Subgrid System - #124: Grid Point Animation - #125: GitHub Issues Automation Also updated existing references: - #101/#110: Constructor standardization - #109: Vector class indexing Note: Tutorial-specific items and Python-implementable features (input queue, collision reservation) are not tracked as engine issues. commit 062e4dadc42833bf5a3559e5d7c4ceb4abb7e9c0 Fix animation segfaults with RAII weak_ptr implementation Resolved two critical segmentation faults in AnimationManager: 1. Race condition when creating multiple animations in timer callbacks 2. Exit crash when animations outlive their target objects Changes: - Replace raw pointers with std::weak_ptr for automatic target invalidation - Add Animation::complete() to jump animations to final value - Add Animation::hasValidTarget() to check if target still exists - Update AnimationManager to auto-remove invalid animations - Add AnimationManager::clear() call to GameEngine::cleanup() - Update Python bindings to pass shared_ptr instead of raw pointers This ensures animations can never reference destroyed objects, following proper RAII principles. Tested with sizzle_reel_final.py and stress tests creating/destroying hundreds of animated objects. commit 98fc49a978ec792ee6096f40fd4e19841b8ec6a3 Directory structure cleanup and organization overhaul
2025-07-15 21:30:49 -04:00
static PyObject* get_name(PyTimerObject* self, void* closure);
Squashed commit of 53 Commits: [alpha_streamline_2] * Field of View, Pathing courtesy of libtcod * python-tcod emulation at `mcrfpy.libtcod` - partial implementation * documentation, tutorial drafts: in middling to good shape ┌────────────┬────────────────────┬───────────┬────────────┬───────────────┬────────────────┬────────────────┬─────────────┐ │ Date │ Models │ Input │ Output │ Cache Create │ Cache Read │ Total Tokens │ Cost (USD) │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-05 │ - opus-4 │ 13,630 │ 159,500 │ 3,854,900 │ 84,185,034 │ 88,213,064 │ $210.72 │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-06 │ - opus-4 │ 5,814 │ 113,190 │ 4,242,407 │ 150,191,183 │ 154,552,594 │ $313.41 │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-07 │ - opus-4 │ 7,244 │ 104,599 │ 3,894,453 │ 81,781,179 │ 85,787,475 │ $184.46 │ │ │ - sonnet-4 │ │ │ │ │ │ │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-08 │ - opus-4 │ 50,312 │ 158,599 │ 5,021,189 │ 60,028,561 │ 65,258,661 │ $167.05 │ │ │ - sonnet-4 │ │ │ │ │ │ │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-09 │ - opus-4 │ 6,311 │ 109,653 │ 4,171,140 │ 80,092,875 │ 84,379,979 │ $193.09 │ │ │ - sonnet-4 │ │ │ │ │ │ │ └────────────┴────────────────────┴───────────┴────────────┴───────────────┴────────────────┴────────────────┴─────────────┘ 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> Author: John McCardle <mccardle.john@gmail.com> Draft tutorials Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP with FOV, A* pathfinding, and GUI text widget completions - Mark TCOD Integration Sprint as complete - Document FOV system with perspective rendering implementation - Update UIEntity pathfinding status to complete with A* and caching - Add comprehensive achievement entry for July 10 work - Reflect current engine capabilities accurately The engine now has all core roguelike mechanics: - Field of View with per-entity visibility - Pathfinding (both Dijkstra and A*) - Text input for in-game consoles - Performance optimizations throughout Author: John McCardle <mccardle.john@gmail.com> feat(engine): implement perspective FOV, pathfinding, and GUI text widgets Major Engine Enhancements: - Complete FOV (Field of View) system with perspective rendering - UIGrid.perspective property for entity-based visibility - Three-layer overlay colors (unexplored, explored, visible) - Per-entity visibility state tracking - Perfect knowledge updates only for explored areas - Advanced Pathfinding Integration - A* pathfinding implementation in UIGrid - Entity.path_to() method for direct pathfinding - Dijkstra maps for multi-target pathfinding - Path caching for performance optimization - GUI Text Input Widgets - TextInputWidget class with cursor, selection, scrolling - Improved widget with proper text rendering and input handling - Example showcase of multiple text input fields - Foundation for in-game console and chat systems - Performance & Architecture Improvements - PyTexture copy operations optimized - GameEngine update cycle refined - UIEntity property handling enhanced - UITestScene modernized Test Suite: - Interactive visibility demos showing FOV in action - Pathfinding comparison (A* vs Dijkstra) - Debug utilities for visibility and empty path handling - Sizzle reel demo combining pathfinding and vision - Multiple text input test scenarios This commit brings McRogueFace closer to a complete roguelike engine with essential features like line-of-sight, intelligent pathfinding, and interactive text input capabilities. Author: John McCardle <mccardle.john@gmail.com> feat(demos): enhance interactive pathfinding demos with entity.path_to() - dijkstra_interactive_enhanced.py: Animation along paths with smooth movement - M key to start movement animation - P to pause/resume - R to reset positions - Visual path gradient for better clarity - pathfinding_showcase.py: Advanced multi-entity behaviors - Chase mode: enemies pursue player - Flee mode: enemies avoid player - Patrol mode: entities follow waypoints - WASD player movement - Dijkstra distance field visualization (D key) - Larger dungeon map with multiple rooms - Both demos use new entity.path_to() method - Smooth interpolated movement animations - Real-time pathfinding recalculation - Comprehensive test coverage These demos showcase the power of integrated pathfinding for game AI. Author: John McCardle <mccardle.john@gmail.com> feat(entity): implement path_to() method for entity pathfinding - Add path_to(target_x, target_y) method to UIEntity class - Uses existing Dijkstra pathfinding implementation from UIGrid - Returns list of (x, y) coordinate tuples for complete path - Supports both positional and keyword argument formats - Proper error handling for out-of-bounds and no-grid scenarios - Comprehensive test suite covering normal and edge cases Part of TCOD integration sprint - gives entities immediate pathfinding capabilities. Author: John McCardle <mccardle.john@gmail.com> docs: update roadmap with Dijkstra pathfinding progress - Mark UIGrid TCOD Integration as completed - Document critical PyArg bug fix achievement - Update UIEntity Pathfinding to 50% complete - Add detailed progress notes for July 9 sprint work Author: John McCardle <mccardle.john@gmail.com> feat(tcod): complete Dijkstra pathfinding implementation with critical PyArg fix - Add complete Dijkstra pathfinding to UIGrid class - compute_dijkstra(), get_dijkstra_distance(), get_dijkstra_path() - Full TCODMap and TCODDijkstra integration - Proper memory management in constructors/destructors - Create mcrfpy.libtcod submodule with Python bindings - dijkstra_compute(), dijkstra_get_distance(), dijkstra_get_path() - line() function for drawing corridors - Foundation for future FOV and pathfinding algorithms - Fix critical PyArg bug in UIGridPoint color setter - PyObject_to_sfColor() now handles both Color objects and tuples - Prevents "SystemError: new style getargs format but argument is not a tuple" - Proper error handling and exception propagation - Add comprehensive test suite - test_dijkstra_simple.py validates all pathfinding operations - dijkstra_test.py for headless testing with screenshots - dijkstra_interactive.py for full user interaction demos - Consolidate and clean up test files - Removed 6 duplicate/broken demo attempts - Two clean versions: headless test + interactive demo Part of TCOD integration sprint for RoguelikeDev Tutorial Event. Author: John McCardle <mccardle.john@gmail.com> Roguelike Tutorial Planning + Prep Author: John McCardle <mccardle.john@gmail.com> feat(docs): complete markdown API documentation export - Created comprehensive markdown documentation matching HTML completeness - Documented all 75 functions, 20 classes, 56 methods, and 20 automation methods - Zero ellipsis instances - complete coverage with no missing documentation - Added proper markdown formatting with code blocks and navigation - Included full parameter documentation, return values, and examples Key features: - 23KB GitHub-compatible markdown documentation - 47 argument sections with detailed parameters - 35 return value specifications - 23 code examples with syntax highlighting - 38 explanatory notes and 10 exception specifications - Full table of contents with anchor links - Professional markdown formatting Both export formats now available: - HTML: docs/api_reference_complete.html (54KB, rich styling) - Markdown: docs/API_REFERENCE_COMPLETE.md (23KB, GitHub-compatible) Author: John McCardle <mccardle.john@gmail.com> feat(docs): complete API documentation with zero missing methods - Eliminated ALL ellipsis instances (0 remaining) - Documented 40 functions with complete signatures and examples - Documented 21 classes with full method and property documentation - Added 56 method descriptions with detailed parameters and return values - Included 15 complete property specifications - Added 24 code examples and 38 explanatory notes - Comprehensive coverage of all collection methods, system classes, and functions Key highlights: - EntityCollection/UICollection: Complete method docs (append, remove, extend, count, index) - Animation: Full property and method documentation with examples - Color: All manipulation methods (from_hex, to_hex, lerp) with examples - Vector: Complete mathematical operations (magnitude, normalize, dot, distance_to, angle, copy) - Scene: All management methods including register_keyboard - Timer: Complete control methods (pause, resume, cancel, restart) - Window: All management methods (get, center, screenshot) - System functions: Complete audio, scene, UI, and system function documentation Author: John McCardle <mccardle.john@gmail.com> feat(docs): create professional HTML API documentation - Fixed all formatting issues from original HTML output - Added comprehensive constructor documentation for all classes - Enhanced visual design with modern styling and typography - Fixed literal newline display and markdown link conversion - Added proper semantic HTML structure and navigation - Includes detailed documentation for Entity, collections, and system types Author: John McCardle <mccardle.john@gmail.com> feat: complete API reference generator and finish Phase 7 documentation Implemented comprehensive API documentation generator that: - Introspects live mcrfpy module for accurate documentation - Generates organized Markdown reference (docs/API_REFERENCE.md) - Categorizes classes and functions by type - Includes full automation module documentation - Provides summary statistics Results: - 20 classes documented - 19 module functions documented - 20 automation methods documented - 100% coverage of public API - Clean, readable Markdown output Phase 7 Summary: - Completed 4/5 tasks (1 cancelled as architecturally inappropriate) - All documentation tasks successful - Type stubs, docstrings, and API reference all complete Author: John McCardle <mccardle.john@gmail.com> docs: cancel PyPI wheel task and add future vision for Python extension architecture Task #70 Analysis: - Discovered fundamental incompatibility with PyPI distribution - McRogueFace embeds CPython rather than being loaded by it - Traditional wheels expect to extend existing Python interpreter - Current architecture is application-with-embedded-Python Decisions: - Cancelled PyPI wheel preparation as out of scope for Alpha - Cleaned up attempted packaging files (pyproject.toml, setup.py, etc.) - Identified better distribution methods (installers, package managers) Added Future Vision: - Comprehensive plan for pure Python extension architecture - Would allow true "pip install mcrogueface" experience - Requires major refactoring to invert control flow - Python would drive main loop with C++ performance extensions - Unscheduled but documented as long-term possibility This clarifies the architectural boundaries and sets realistic expectations for distribution methods while preserving the vision of what McRogueFace could become with significant rework. Author: John McCardle <mccardle.john@gmail.com> feat: generate comprehensive .pyi type stubs for IDE support (#108) Created complete type stub files for the mcrfpy module to enable: - Full IntelliSense/autocomplete in IDEs - Static type checking with mypy/pyright - Better documentation tooltips - Parameter hints and return types Implementation details: - Manually crafted stubs for accuracy (15KB, 533 lines) - Complete coverage: 19 classes, 112 functions/methods - Proper type annotations using typing module - @overload decorators for multiple signatures - Type aliases for common patterns (UIElement union) - Preserved all docstrings for IDE help - Automation module fully typed - PEP 561 compliant with py.typed marker Testing: - Validated Python syntax with ast.parse() - Verified all expected classes and functions - Confirmed type annotations are well-formed - Checked docstring preservation (80 docstrings) Usage: - VS Code: Add stubs/ to python.analysis.extraPaths - PyCharm: Mark stubs/ directory as Sources Root - Other IDEs will auto-detect .pyi files This significantly improves the developer experience when using McRogueFace as a Python game engine. Author: John McCardle <mccardle.john@gmail.com> docs: add comprehensive parameter documentation to all API methods (#86) Enhanced documentation for the mcrfpy module with: - Detailed docstrings for all API methods - Type hints in documentation (name: type format) - Return type specifications - Exception documentation where applicable - Usage examples for complex methods - Module-level documentation with overview and example code Specific improvements: - Audio API: Added parameter types and return values - Scene API: Documented transition types and error conditions - Timer API: Clarified handler signature and runtime parameter - UI Search: Added wildcard pattern examples for findAll() - Metrics API: Documented all dictionary keys returned Also fixed method signatures: - Changed METH_VARARGS to METH_NOARGS for parameterless methods - Ensures proper Python calling conventions Test coverage included - all documentation is accessible via Python's __doc__ attributes and shows correctly formatted information. Author: John McCardle <mccardle.john@gmail.com> docs: mark issue #85 as completed in Phase 7 Author: John McCardle <mccardle.john@gmail.com> docs: replace all 'docstring' placeholders with comprehensive documentation (#85) Added proper Python docstrings for all UI component classes: UIFrame: - Container element that can hold child drawables - Documents position, size, colors, outline, and clip_children - Includes constructor signature with all parameters UICaption: - Text display element with font and styling - Documents text content, position, font, colors, outline - Notes that w/h are computed from text content UISprite: - Texture/sprite display element - Documents position, texture, sprite_index, scale - Notes that w/h are computed from texture and scale UIGrid: - Tile-based grid for game worlds - Documents grid dimensions, tile size, texture atlas - Includes entities collection and background_color All docstrings follow consistent format: - Constructor signature with defaults - Brief description - Args section with types and defaults - Attributes section with all properties This completes Phase 7 task #85 for documentation improvements. Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP with PyArgHelpers infrastructure completion Author: John McCardle <mccardle.john@gmail.com> refactor: implement PyArgHelpers for standardized Python argument parsing This major refactoring standardizes how position, size, and other arguments are parsed across all UI components. PyArgHelpers provides consistent handling for various argument patterns: - Position as (x, y) tuple or separate x, y args - Size as (w, h) tuple or separate width, height args - Grid position and size with proper validation - Color parsing with PyColorObject support Changes across UI components: - UICaption: Migrated to PyArgHelpers, improved resize() for future multiline support - UIFrame: Uses standardized position parsing - UISprite: Consistent position handling - UIGrid: Grid-specific position/size helpers - UIEntity: Unified argument parsing Also includes: - Improved error messages for type mismatches (int or float accepted) - Reduced code duplication across constructors - Better handling of keyword/positional argument conflicts - Maintains backward compatibility with existing API This addresses the inconsistent argument handling patterns discovered during the inheritance hierarchy work and prepares for Phase 7 documentation. Author: John McCardle <mccardle.john@gmail.com> feat(Python): establish proper inheritance hierarchy for UI types All UIDrawable-derived Python types now properly inherit from the Drawable base class in Python, matching the C++ inheritance structure. Changes: - Add Py_TPFLAGS_BASETYPE to PyDrawableType to allow inheritance - Set tp_base = &mcrfpydef::PyDrawableType for all UI types - Add PyDrawable.h include to UI type headers - Rename _Drawable to Drawable and update error message This enables proper Python inheritance: Frame, Caption, Sprite, Grid, and Entity all inherit from Drawable, allowing shared functionality and isinstance() checks. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UISprite) - Update UISprite to use base class position instead of sprite position - Synchronize sprite position with base class position for rendering - Implement onPositionChanged() for position synchronization - Update all UISprite methods to use base position consistently - Add comprehensive test coverage for UISprite position handling This is part 3 of moving position to the base class. UIGrid is the final class that needs to be updated. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UICaption) - Update UICaption to use base class position instead of text position - Synchronize text position with base class position for rendering - Add onPositionChanged() virtual method for position synchronization - Update all UICaption methods to use base position consistently - Add comprehensive test coverage for UICaption position handling This is part 2 of moving position to the base class. UISprite and UIGrid will be updated in subsequent commits. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UIFrame) - Add position member to UIDrawable base class - Add common position getters/setters (x, y, pos) to base class - Update UIFrame to use base class position instead of box position - Synchronize box position with base class position for rendering - Update all UIFrame methods to use base position consistently - Add comprehensive test coverage for UIFrame position handling This is part 1 of moving position to the base class. Other derived classes (UICaption, UISprite, UIGrid) will be updated in subsequent commits. Author: John McCardle <mccardle.john@gmail.com> refactor: remove UIEntity collision_pos field - Remove redundant collision_pos field from UIEntity - Update position getters/setters to use integer-cast position when needed - Remove all collision_pos synchronization code - Simplify entity position handling to use single float position field - Add comprehensive test coverage proving functionality is preserved This removes technical debt and simplifies the codebase without changing API behavior. Author: John McCardle <mccardle.john@gmail.com> feat: add PyArgHelpers infrastructure for standardized argument parsing - Create PyArgHelpers.h with parsing functions for position, size, grid coordinates, and color - Support tuple-based vector arguments with conflict detection - Provide consistent error messages and validation - Add comprehensive test coverage for infrastructure This sets the foundation for standardizing all Python API constructors. Author: John McCardle <mccardle.john@gmail.com> docs: mark Phase 6 (Rendering Revolution) as complete Phase 6 is now complete with all core rendering features implemented: Completed Features: - Grid background colors (#50) - customizable backgrounds with animation - RenderTexture overhaul (#6) - UIFrame clipping with opt-in architecture - Viewport-based rendering (#8) - three scaling modes with coordinate transform Strategic Decisions: - UIGrid already has optimal RenderTexture implementation for its viewport needs - UICaption/UISprite clipping deemed unnecessary (no children to clip) - Effects/Shader/Particle systems deferred to post-Phase 7 for focused delivery The rendering foundation is now solid and ready for Phase 7: Documentation & Distribution. Author: John McCardle <mccardle.john@gmail.com> feat(viewport): complete viewport-based rendering system (#8) Implements a comprehensive viewport system that allows fixed game resolution with flexible window scaling, addressing the primary wishes for issues #34, #49, and #8. Key Features: - Fixed game resolution independent of window size (window.game_resolution property) - Three scaling modes accessible via window.scaling_mode: - "center": 1:1 pixels, viewport centered in window - "stretch": viewport fills window, ignores aspect ratio - "fit": maintains aspect ratio with black bars - Automatic window-to-game coordinate transformation for mouse input - Full Python API integration with PyWindow properties Technical Implementation: - GameEngine::ViewportMode enum with Center, Stretch, Fit modes - SFML View system for efficient GPU-based viewport scaling - updateViewport() recalculates on window resize or mode change - windowToGameCoords() transforms mouse coordinates correctly - PyScene mouse input automatically uses transformed coordinates Tests: - test_viewport_simple.py: Basic API functionality - test_viewport_visual.py: Visual verification with screenshots - test_viewport_scaling.py: Interactive mode switching and resizing This completes the viewport-based rendering task and provides the foundation for resolution-independent game development as requested for Crypt of Sokoban. Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP for Phase 6 progress - Marked Phase 6 as IN PROGRESS - Updated RenderTexture overhaul (#6) as PARTIALLY COMPLETE - Marked Grid background colors (#50) as COMPLETED - Added technical notes from implementation experience - Identified viewport rendering (#8) as next priority Author: John McCardle <mccardle.john@gmail.com> feat(rendering): implement RenderTexture base infrastructure and UIFrame clipping (#6) - Added RenderTexture support to UIDrawable base class - std::unique_ptr<sf::RenderTexture> for opt-in rendering - Dirty flag system for optimization - enableRenderTexture() and markDirty() methods - Implemented clip_children property for UIFrame - Python-accessible boolean property - Automatic RenderTexture creation when enabled - Proper coordinate transformation for nested frames - Updated UIFrame::render() for clipping support - Renders to RenderTexture when clip_children=true - Handles nested clipping correctly - Only re-renders when dirty flag is set - Added comprehensive dirty flag propagation - All property setters mark frame as dirty - Size changes recreate RenderTexture - Animation system integration - Created tests for clipping functionality - Basic clipping test with visual verification - Advanced nested clipping test - Dynamic resize handling test This is Phase 1 of the RenderTexture overhaul, providing the foundation for advanced rendering effects like blur, glow, and viewport rendering. Author: John McCardle <mccardle.john@gmail.com> docs: create RenderTexture overhaul design document - Comprehensive design for Issue #6 implementation - Opt-in architecture to maintain backward compatibility - Phased implementation plan with clear milestones - Performance considerations and risk mitigation - API design for clipping and future effects Also includes Grid background color test Author: John McCardle <mccardle.john@gmail.com> feat(Grid): add customizable background_color property (#50) - Added sf::Color background_color member with default dark gray - Python property getter/setter for background_color - Animation support for individual color components (r/g/b/a) - Replaces hardcoded clear color in render method - Test demonstrates color changes and property access Closes #50 Author: John McCardle <mccardle.john@gmail.com> docs: update roadmap for Phase 6 preparation - Mark Phase 5 (Window/Scene Architecture) as complete - Update issue statuses (#34, #61, #1, #105 completed) - Add Phase 6 implementation strategy for RenderTexture overhaul - Archive Phase 5 test files to .archive/ - Identify quick wins and technical approach for rendering work Author: John McCardle <mccardle.john@gmail.com> feat(Phase 5): Complete Window/Scene Architecture - Window singleton with properties (resolution, fullscreen, vsync, title) - OOP Scene support with lifecycle methods (on_enter, on_exit, on_keypress, update) - Window resize events trigger scene.on_resize callbacks - Scene transitions (fade, slide_left/right/up/down) with smooth animations - Full integration of Python Scene objects with C++ engine All Phase 5 tasks (#34, #1, #61, #105) completed successfully. Author: John McCardle <mccardle.john@gmail.com> research: SFML 3.0 migration analysis - Analyzed SFML 3.0 breaking changes (event system, scoped enums, C++17) - Assessed migration impact on McRogueFace (40+ files affected) - Evaluated timing relative to mcrfpy.sfml module plans - Recommended deferring migration until after mcrfpy.sfml implementation - Created SFML_3_MIGRATION_RESEARCH.md with comprehensive strategy Author: John McCardle <mccardle.john@gmail.com> research: SFML exposure options analysis (#14) - Analyzed current SFML 2.6.1 usage throughout codebase - Evaluated python-sfml (abandoned, only supports SFML 2.3.2) - Recommended direct integration as mcrfpy.sfml module - Created comprehensive SFML_EXPOSURE_RESEARCH.md with implementation plan - Identified opportunity to provide modern SFML 2.6+ Python bindings Author: John McCardle <mccardle.john@gmail.com> feat: add basic profiling/metrics system (#104) - Add ProfilingMetrics struct to track performance data - Track frame time (current and 60-frame rolling average) - Calculate FPS from average frame time - Count draw calls, UI elements, and visible elements per frame - Track total runtime and current frame number - PyScene counts elements during render - Expose metrics via mcrfpy.getMetrics() returning dict This provides basic performance monitoring capabilities for identifying bottlenecks and optimizing rendering performance. Author: John McCardle <mccardle.john@gmail.com> fix: improve click handling with proper z-order and coordinate transforms - UIFrame: Fix coordinate transformation (subtract parent pos, not add) - UIFrame: Check children in reverse order (highest z-index first) - UIFrame: Skip invisible elements entirely - PyScene: Sort elements by z-index before checking clicks - PyScene: Stop at first element that handles the click - UIGrid: Implement entity click detection with grid coordinate transform - UIGrid: Check entities in reverse order, return sprite as target Click events now correctly respect z-order (top elements get priority), handle coordinate transforms for nested frames, and support clicking on grid entities. Elements without click handlers are transparent to clicks, allowing elements below to receive them. Note: Click testing requires non-headless mode due to PyScene limitation. feat: implement name system for finding UI elements (#39/40/41) - Add 'name' property to UIDrawable base class - All UI elements (Frame, Caption, Sprite, Grid, Entity) support .name - Entity delegates name to its sprite member - Add find(name, scene=None) function for exact match search - Add findAll(pattern, scene=None) with wildcard support (* matches any sequence) - Both functions search recursively through Frame children and Grid entities - Comprehensive test coverage for all functionality This provides a simple way to find UI elements by name in Python scripts, supporting both exact matches and wildcard patterns. Author: John McCardle <mccardle.john@gmail.com> fix: prevent segfault when closing window via X button - Add cleanup() method to GameEngine to clear Python references before destruction - Clear timers and McRFPy_API references in proper order - Call cleanup() at end of run loop and in destructor - Ensure cleanup is only called once per GameEngine instance Also includes: - Fix audio ::stop() calls (already in place, OpenAL warning is benign) - Add Caption support for x, y keywords (e.g. Caption("text", x=5, y=10)) - Refactor UIDrawable_methods.h into UIBase.h for better organization - Move UIEntity-specific implementations to UIEntityPyMethods.h Author: John McCardle <mccardle.john@gmail.com> feat: stabilize test suite and add UIDrawable methods - Add visible, opacity properties to all UI classes (#87, #88) - Add get_bounds(), move(), resize() methods to UIDrawable (#89, #98) - Create UIDrawable_methods.h with template implementations - Fix test termination issues - all tests now exit properly - Fix test_sprite_texture_swap.py click handler signature - Fix test_drawable_base.py segfault in headless mode - Convert audio objects to pointers for cleanup (OpenAL warning persists) - Remove debug print statements from UICaption - Special handling for UIEntity to delegate drawable methods to sprite All test files are now "airtight" - they complete successfully, terminate on their own, and handle edge cases properly. Author: John McCardle <mccardle.john@gmail.com> docs: add Phase 1-3 completion summary - Document all completed tasks across three phases - Show before/after API improvements - Highlight technical achievements - Outline next steps for Phase 4-7 Author: John McCardle <mccardle.john@gmail.com> feat: implement mcrfpy.Timer object with pause/resume/cancel capabilities closes #103 - Created PyTimer.h/cpp with object-oriented timer interface - Enhanced PyTimerCallable with pause/resume state tracking - Added timer control methods: pause(), resume(), cancel(), restart() - Added timer properties: interval, remaining, paused, active, callback - Fixed timing logic to prevent rapid catch-up after resume - Timer objects automatically register with game engine - Added comprehensive test demonstrating all functionality Author: John McCardle <mccardle.john@gmail.com> feat(Color): add helper methods from_hex, to_hex, lerp closes #94 - Add Color.from_hex(hex_string) class method for creating colors from hex - Support formats: #RRGGBB, RRGGBB, #RRGGBBAA, RRGGBBAA - Add color.to_hex() to convert Color to hex string - Add color.lerp(other, t) for smooth color interpolation - Comprehensive test coverage for all methods Author: John McCardle <mccardle.john@gmail.com> fix: properly configure UTF-8 encoding for Python stdio - Use PyConfig to set stdio_encoding="UTF-8" during initialization - Set stdio_errors="surrogateescape" for robust handling - Configure in both init_python() and init_python_with_config() - Cleaner solution than wrapping streams after initialization - Fixes UnicodeEncodeError when printing unicode characters Author: John McCardle <mccardle.john@gmail.com> feat(Vector): implement arithmetic operations closes #93 - Add PyNumberMethods with add, subtract, multiply, divide, negate, absolute - Add rich comparison for equality/inequality checks - Add boolean check (zero vector is False) - Implement vector methods: magnitude(), normalize(), dot(), distance_to(), angle(), copy() - Fix UIDrawable::get_click() segfault when click_callable is null - Comprehensive test coverage for all arithmetic operations Author: John McCardle <mccardle.john@gmail.com> feat: Complete position argument standardization for all UI classes - Frame and Sprite now support pos keyword override - Entity now accepts x,y arguments (was pos-only before) - All UI classes now consistently support: - (x, y) positional - ((x, y)) tuple - x=x, y=y keywords - pos=(x,y) keyword - pos=Vector keyword - Improves API consistency and flexibility Author: John McCardle <mccardle.john@gmail.com> feat: Standardize position arguments across all UI classes - Create PyPositionHelper for consistent position parsing - Grid.at() now accepts (x,y), ((x,y)), x=x, y=y, pos=(x,y) - Caption now accepts x,y args in addition to pos - Grid init fully supports keyword arguments - Maintain backward compatibility for all formats - Consistent error messages across classes Author: John McCardle <mccardle.john@gmail.com> feat: Add Entity.die() method for lifecycle management closes #30 - Remove entity from its grid's entity list - Clear grid reference after removal - Safe to call multiple times (no-op if not on grid) - Works with shared_ptr entity management Author: John McCardle <mccardle.john@gmail.com> perf: Skip out-of-bounds entities during Grid rendering closes #52 - Add visibility bounds check in entity render loop - Skip entities outside view with 1 cell margin - Improves performance for large grids with many entities - Bounds check considers zoom and pan settings Author: John McCardle <mccardle.john@gmail.com> verify: Sprite texture swapping functionality closes #19 - Texture property getter/setter already implemented - Position/scale preservation during swap confirmed - Type validation for texture assignment working - Tests verify functionality is complete Author: John McCardle <mccardle.john@gmail.com> feat: Grid size tuple support closes #90 - Add grid_size keyword parameter to Grid.__init__ - Accept tuple or list of two integers - Override grid_x/grid_y if grid_size provided - Maintain backward compatibility - Add comprehensive test coverage Author: John McCardle <mccardle.john@gmail.com> feat: Phase 1 - safe constructors and _Drawable foundation Closes #7 - Make all UI class constructors safe: - Added safe default constructors for UISprite, UIGrid, UIEntity, UICaption - Initialize all members to predictable values - Made Python init functions accept no arguments - Added x,y properties to UIEntity Closes #71 - Create _Drawable Python base class: - Created PyDrawable.h/cpp with base type (not yet inherited by UI types) - Registered in module initialization Closes #87 - Add visible property: - Added bool visible=true to UIDrawable base class - All render methods check visibility before drawing Closes #88 - Add opacity property: - Added float opacity=1.0 to UIDrawable base class - UICaption and UISprite apply opacity to alpha channel Closes #89 - Add get_bounds() method: - Virtual method returns sf::FloatRect(x,y,w,h) - Implemented in Frame, Caption, Sprite, Grid Closes #98 - Add move() and resize() methods: - move(dx,dy) for relative movement - resize(w,h) for absolute sizing - Caption resize is no-op (size controlled by font) Author: John McCardle <mccardle.john@gmail.com> docs: comprehensive alpha_streamline_2 plan and strategic vision - Add 7-phase development plan for alpha_streamline_2 branch - Define architectural dependencies and critical path - Identify new issues needed (Timer objects, event system, etc.) - Add strategic vision document with 3 transformative directions - Timeline: 10-12 weeks to solid Beta foundation Author: John McCardle <mccardle.john@gmail.com> feat(Grid): flexible at() method arguments - Support tuple argument: grid.at((x, y)) - Support keyword arguments: grid.at(x=5, y=3) - Support pos keyword: grid.at(pos=(2, 8)) - Maintain backward compatibility with grid.at(x, y) - Add comprehensive error handling for invalid arguments Improves API ergonomics and Python-like flexibility
2025-07-09 22:41:15 -04:00
static PyObject* get_interval(PyTimerObject* self, void* closure);
static int set_interval(PyTimerObject* self, PyObject* value, void* closure);
static PyObject* get_remaining(PyTimerObject* self, void* closure);
static PyObject* get_paused(PyTimerObject* self, void* closure);
static PyObject* get_active(PyTimerObject* self, void* closure);
static PyObject* get_callback(PyTimerObject* self, void* closure);
static int set_callback(PyTimerObject* self, PyObject* value, void* closure);
Squashed commit of the following: [alpha_presentable] Author: John McCardle <mccardle.john@gmail.com> Co-Authored-By: Claude <noreply@anthropic.com> commit dc47f2474c7b2642d368f9772894aed857527807 the UIEntity rant commit 673ca8e1b089ea670257fc04ae1a676ed95a40ed I forget when these tests were written, but I want them in the squash merge commit 70c71565c684fa96e222179271ecb13a156d80ad Fix UI object segfault by switching from managed to manual weakref management The UI types (Frame, Caption, Sprite, Grid, Entity) were using Py_TPFLAGS_MANAGED_WEAKREF while also trying to manually create weakrefs for the PythonObjectCache. This is fundamentally incompatible - when Python manages weakrefs internally, PyWeakref_NewRef() cannot access the weakref list properly, causing segfaults. Changed all UI types to use manual weakref management (like PyTimer): - Restored weakreflist field in all UI type structures - Removed Py_TPFLAGS_MANAGED_WEAKREF from all UI type flags - Added tp_weaklistoffset for all UI types in module initialization - Initialize weakreflist=NULL in tp_new and init methods - Call PyObject_ClearWeakRefs() in dealloc functions This allows the PythonObjectCache to continue working correctly, maintaining Python object identity for C++ objects across the boundary. Fixes segfault when creating UI objects (e.g., Caption, Grid) that was preventing tutorial scripts from running. This is the bulk of the required behavior for Issue #126. that issure isn't ready for closure yet; several other sub-issues left. closes #110 mention issue #109 - resolves some __init__ related nuisances commit 3dce3ec539ae99e32d869007bf3f49d03e4e2f89 Refactor timer system for cleaner architecture and enhanced functionality Major improvements to the timer system: - Unified all timer logic in the Timer class (C++) - Removed PyTimerCallable subclass, now using PyCallable directly - Timer objects are now passed to callbacks as first argument - Added 'once' parameter for one-shot timers that auto-stop - Implemented proper PythonObjectCache integration with weakref support API enhancements: - New callback signature: callback(timer, runtime) instead of just (runtime) - Timer objects expose: name, interval, remaining, paused, active, once properties - Methods: pause(), resume(), cancel(), restart() - Comprehensive documentation with examples - Enhanced repr showing timer state (active/paused/once/remaining time) This cleanup follows the UIEntity/PyUIEntity pattern and makes the timer system more Pythonic while maintaining backward compatibility through the legacy setTimer/delTimer API. closes #121 commit 145834cfc31b8dabc4cb3591b9cb4ed99fc8b964 Implement Python object cache to preserve derived types in collections Add a global cache system that maintains weak references to Python objects, ensuring that derived Python classes maintain their identity when stored in and retrieved from C++ collections. Key changes: - Add PythonObjectCache singleton with serial number system - Each cacheable object (UIDrawable, UIEntity, Timer, Animation) gets unique ID - Cache stores weak references to prevent circular reference memory leaks - Update all UI type definitions to support weak references (Py_TPFLAGS_MANAGED_WEAKREF) - Enable subclassing for all UI types (Py_TPFLAGS_BASETYPE) - Collections check cache before creating new Python wrappers - Register objects in cache during __init__ methods - Clean up cache entries in C++ destructors This ensures that Python code like: ```python class MyFrame(mcrfpy.Frame): def __init__(self): super().__init__() self.custom_data = "preserved" frame = MyFrame() scene.ui.append(frame) retrieved = scene.ui[0] # Same MyFrame instance with custom_data intact ``` Works correctly, with retrieved maintaining the derived type and custom attributes. Closes #112 commit c5e7e8e29835a69f4c50f3c99fd3123012635a9a Update test demos for new Python API and entity system - Update all text input demos to use new Entity constructor signature - Fix pathfinding showcase to work with new entity position handling - Remove entity_waypoints tracking in favor of simplified movement - Delete obsolete exhaustive_api_demo.py (superseded by newer demos) - Adjust entity creation calls to match Entity((x, y), texture, sprite_index) pattern commit 6d29652ae7418745dc24066532454167d447df89 Update animation demo suite with crash fixes and improvements - Add warnings about AnimationManager segfault bug in sizzle_reel_final.py - Create sizzle_reel_final_fixed.py that works around the crash by hiding objects instead of removing them - Increase font sizes for better visibility in demos - Extend demo durations for better showcase of animations - Remove debug prints from animation_sizzle_reel_working.py - Minor cleanup and improvements to all animation demos commit a010e5fa968feaba620dcf2eda44fb9514512151 Update game scripts for new Python API - Convert entity position access from tuple to x/y properties - Update caption size property to font_size - Fix grid boundary checks to use grid_size instead of exceptions - Clean up demo timer on menu exit to prevent callbacks These changes adapt the game scripts to work with the new standardized Python API constructors and property names. commit 9c8d6c459109be883cb8070b8ef83c60bfc1a970 Fix click event z-order handling in PyScene Changed click detection to properly respect z-index by: - Sorting ui_elements in-place when needed (same as render order) - Using reverse iterators to check highest z-index elements first - This ensures top-most elements receive clicks before lower ones commit dcd1b0ca33d46639023221f4d7d52000b947dbdf Add roguelike tutorial implementation files Implement Parts 0-2 of the classic roguelike tutorial adapted for McRogueFace: - Part 0: Basic grid setup and tile rendering - Part 1: Drawing '@' symbol and basic movement - Part 1b: Variant with sprite-based player - Part 2: Entity system and NPC implementation with three movement variants: - part_2.py: Standard implementation - part_2-naive.py: Naive movement approach - part_2-onemovequeued.py: Queued movement system Includes tutorial assets: - tutorial2.png: Tileset for dungeon tiles - tutorial_hero.png: Player sprite sheet commit 6813fb5129738cca2d79c80304834523561ba7fb Standardize Python API constructors and remove PyArgHelpers - Remove PyArgHelpers.h and all macro-based argument parsing - Convert all UI class constructors to use PyArg_ParseTupleAndKeywords - Standardize constructor signatures across UICaption, UIEntity, UIFrame, UIGrid, and UISprite - Replace PYARGHELPER_SINGLE/MULTI macros with explicit argument parsing - Improve error messages and argument validation - Maintain backward compatibility with existing Python code This change improves code maintainability and consistency across the Python API. commit 6f67fbb51efaf70e52fba8c939298dcdff50450a Fix animation callback crashes from iterator invalidation (#119) Resolved segfaults caused by creating new animations from within animation callbacks. The issue was iterator invalidation in AnimationManager::update() when callbacks modified the active animations vector. Changes: - Add deferred animation queue to AnimationManager - New animations created during update are queued and added after - Set isUpdating flag to track when in update loop - Properly handle Animation destructor during callback execution - Add clearCallback() method for safe cleanup scenarios This fixes the "free(): invalid pointer" and "malloc(): unaligned fastbin chunk detected" errors that occurred with rapid animation creation in callbacks. commit eb88c7b3aab3da519db7569106c34f3510b6e963 Add animation completion callbacks (#119) Implement callbacks that fire when animations complete, enabling direct causality between animation end and game state changes. This eliminates race conditions from parallel timer workarounds. - Add optional callback parameter to Animation constructor - Callbacks execute synchronously when animation completes - Proper Python reference counting with GIL safety - Callbacks receive (anim, target) parameters (currently None) - Exception handling prevents crashes from Python errors Example usage: ```python def on_complete(anim, target): player_moving = False anim = mcrfpy.Animation("x", 300.0, 1.0, "easeOut", callback=on_complete) anim.start(player) ``` closes #119 commit 9fb428dd0176a4d7cfad09deb7509d8aa5562868 Update ROADMAP with GitHub issue numbers (#111-#125) Added issue numbers from GitHub tracker to roadmap items: - #111: Grid Click Events Broken in Headless - #112: Object Splitting Bug (Python type preservation) - #113: Batch Operations for Grid - #114: CellView API - #115: SpatialHash Implementation - #116: Dirty Flag System - #117: Memory Pool for Entities - #118: Scene as Drawable - #119: Animation Completion Callbacks - #120: Animation Property Locking - #121: Timer Object System - #122: Parent-Child UI System - #123: Grid Subgrid System - #124: Grid Point Animation - #125: GitHub Issues Automation Also updated existing references: - #101/#110: Constructor standardization - #109: Vector class indexing Note: Tutorial-specific items and Python-implementable features (input queue, collision reservation) are not tracked as engine issues. commit 062e4dadc42833bf5a3559e5d7c4ceb4abb7e9c0 Fix animation segfaults with RAII weak_ptr implementation Resolved two critical segmentation faults in AnimationManager: 1. Race condition when creating multiple animations in timer callbacks 2. Exit crash when animations outlive their target objects Changes: - Replace raw pointers with std::weak_ptr for automatic target invalidation - Add Animation::complete() to jump animations to final value - Add Animation::hasValidTarget() to check if target still exists - Update AnimationManager to auto-remove invalid animations - Add AnimationManager::clear() call to GameEngine::cleanup() - Update Python bindings to pass shared_ptr instead of raw pointers This ensures animations can never reference destroyed objects, following proper RAII principles. Tested with sizzle_reel_final.py and stress tests creating/destroying hundreds of animated objects. commit 98fc49a978ec792ee6096f40fd4e19841b8ec6a3 Directory structure cleanup and organization overhaul
2025-07-15 21:30:49 -04:00
static PyObject* get_once(PyTimerObject* self, void* closure);
static int set_once(PyTimerObject* self, PyObject* value, void* closure);
Squashed commit of 53 Commits: [alpha_streamline_2] * Field of View, Pathing courtesy of libtcod * python-tcod emulation at `mcrfpy.libtcod` - partial implementation * documentation, tutorial drafts: in middling to good shape ┌────────────┬────────────────────┬───────────┬────────────┬───────────────┬────────────────┬────────────────┬─────────────┐ │ Date │ Models │ Input │ Output │ Cache Create │ Cache Read │ Total Tokens │ Cost (USD) │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-05 │ - opus-4 │ 13,630 │ 159,500 │ 3,854,900 │ 84,185,034 │ 88,213,064 │ $210.72 │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-06 │ - opus-4 │ 5,814 │ 113,190 │ 4,242,407 │ 150,191,183 │ 154,552,594 │ $313.41 │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-07 │ - opus-4 │ 7,244 │ 104,599 │ 3,894,453 │ 81,781,179 │ 85,787,475 │ $184.46 │ │ │ - sonnet-4 │ │ │ │ │ │ │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-08 │ - opus-4 │ 50,312 │ 158,599 │ 5,021,189 │ 60,028,561 │ 65,258,661 │ $167.05 │ │ │ - sonnet-4 │ │ │ │ │ │ │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-09 │ - opus-4 │ 6,311 │ 109,653 │ 4,171,140 │ 80,092,875 │ 84,379,979 │ $193.09 │ │ │ - sonnet-4 │ │ │ │ │ │ │ └────────────┴────────────────────┴───────────┴────────────┴───────────────┴────────────────┴────────────────┴─────────────┘ 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> Author: John McCardle <mccardle.john@gmail.com> Draft tutorials Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP with FOV, A* pathfinding, and GUI text widget completions - Mark TCOD Integration Sprint as complete - Document FOV system with perspective rendering implementation - Update UIEntity pathfinding status to complete with A* and caching - Add comprehensive achievement entry for July 10 work - Reflect current engine capabilities accurately The engine now has all core roguelike mechanics: - Field of View with per-entity visibility - Pathfinding (both Dijkstra and A*) - Text input for in-game consoles - Performance optimizations throughout Author: John McCardle <mccardle.john@gmail.com> feat(engine): implement perspective FOV, pathfinding, and GUI text widgets Major Engine Enhancements: - Complete FOV (Field of View) system with perspective rendering - UIGrid.perspective property for entity-based visibility - Three-layer overlay colors (unexplored, explored, visible) - Per-entity visibility state tracking - Perfect knowledge updates only for explored areas - Advanced Pathfinding Integration - A* pathfinding implementation in UIGrid - Entity.path_to() method for direct pathfinding - Dijkstra maps for multi-target pathfinding - Path caching for performance optimization - GUI Text Input Widgets - TextInputWidget class with cursor, selection, scrolling - Improved widget with proper text rendering and input handling - Example showcase of multiple text input fields - Foundation for in-game console and chat systems - Performance & Architecture Improvements - PyTexture copy operations optimized - GameEngine update cycle refined - UIEntity property handling enhanced - UITestScene modernized Test Suite: - Interactive visibility demos showing FOV in action - Pathfinding comparison (A* vs Dijkstra) - Debug utilities for visibility and empty path handling - Sizzle reel demo combining pathfinding and vision - Multiple text input test scenarios This commit brings McRogueFace closer to a complete roguelike engine with essential features like line-of-sight, intelligent pathfinding, and interactive text input capabilities. Author: John McCardle <mccardle.john@gmail.com> feat(demos): enhance interactive pathfinding demos with entity.path_to() - dijkstra_interactive_enhanced.py: Animation along paths with smooth movement - M key to start movement animation - P to pause/resume - R to reset positions - Visual path gradient for better clarity - pathfinding_showcase.py: Advanced multi-entity behaviors - Chase mode: enemies pursue player - Flee mode: enemies avoid player - Patrol mode: entities follow waypoints - WASD player movement - Dijkstra distance field visualization (D key) - Larger dungeon map with multiple rooms - Both demos use new entity.path_to() method - Smooth interpolated movement animations - Real-time pathfinding recalculation - Comprehensive test coverage These demos showcase the power of integrated pathfinding for game AI. Author: John McCardle <mccardle.john@gmail.com> feat(entity): implement path_to() method for entity pathfinding - Add path_to(target_x, target_y) method to UIEntity class - Uses existing Dijkstra pathfinding implementation from UIGrid - Returns list of (x, y) coordinate tuples for complete path - Supports both positional and keyword argument formats - Proper error handling for out-of-bounds and no-grid scenarios - Comprehensive test suite covering normal and edge cases Part of TCOD integration sprint - gives entities immediate pathfinding capabilities. Author: John McCardle <mccardle.john@gmail.com> docs: update roadmap with Dijkstra pathfinding progress - Mark UIGrid TCOD Integration as completed - Document critical PyArg bug fix achievement - Update UIEntity Pathfinding to 50% complete - Add detailed progress notes for July 9 sprint work Author: John McCardle <mccardle.john@gmail.com> feat(tcod): complete Dijkstra pathfinding implementation with critical PyArg fix - Add complete Dijkstra pathfinding to UIGrid class - compute_dijkstra(), get_dijkstra_distance(), get_dijkstra_path() - Full TCODMap and TCODDijkstra integration - Proper memory management in constructors/destructors - Create mcrfpy.libtcod submodule with Python bindings - dijkstra_compute(), dijkstra_get_distance(), dijkstra_get_path() - line() function for drawing corridors - Foundation for future FOV and pathfinding algorithms - Fix critical PyArg bug in UIGridPoint color setter - PyObject_to_sfColor() now handles both Color objects and tuples - Prevents "SystemError: new style getargs format but argument is not a tuple" - Proper error handling and exception propagation - Add comprehensive test suite - test_dijkstra_simple.py validates all pathfinding operations - dijkstra_test.py for headless testing with screenshots - dijkstra_interactive.py for full user interaction demos - Consolidate and clean up test files - Removed 6 duplicate/broken demo attempts - Two clean versions: headless test + interactive demo Part of TCOD integration sprint for RoguelikeDev Tutorial Event. Author: John McCardle <mccardle.john@gmail.com> Roguelike Tutorial Planning + Prep Author: John McCardle <mccardle.john@gmail.com> feat(docs): complete markdown API documentation export - Created comprehensive markdown documentation matching HTML completeness - Documented all 75 functions, 20 classes, 56 methods, and 20 automation methods - Zero ellipsis instances - complete coverage with no missing documentation - Added proper markdown formatting with code blocks and navigation - Included full parameter documentation, return values, and examples Key features: - 23KB GitHub-compatible markdown documentation - 47 argument sections with detailed parameters - 35 return value specifications - 23 code examples with syntax highlighting - 38 explanatory notes and 10 exception specifications - Full table of contents with anchor links - Professional markdown formatting Both export formats now available: - HTML: docs/api_reference_complete.html (54KB, rich styling) - Markdown: docs/API_REFERENCE_COMPLETE.md (23KB, GitHub-compatible) Author: John McCardle <mccardle.john@gmail.com> feat(docs): complete API documentation with zero missing methods - Eliminated ALL ellipsis instances (0 remaining) - Documented 40 functions with complete signatures and examples - Documented 21 classes with full method and property documentation - Added 56 method descriptions with detailed parameters and return values - Included 15 complete property specifications - Added 24 code examples and 38 explanatory notes - Comprehensive coverage of all collection methods, system classes, and functions Key highlights: - EntityCollection/UICollection: Complete method docs (append, remove, extend, count, index) - Animation: Full property and method documentation with examples - Color: All manipulation methods (from_hex, to_hex, lerp) with examples - Vector: Complete mathematical operations (magnitude, normalize, dot, distance_to, angle, copy) - Scene: All management methods including register_keyboard - Timer: Complete control methods (pause, resume, cancel, restart) - Window: All management methods (get, center, screenshot) - System functions: Complete audio, scene, UI, and system function documentation Author: John McCardle <mccardle.john@gmail.com> feat(docs): create professional HTML API documentation - Fixed all formatting issues from original HTML output - Added comprehensive constructor documentation for all classes - Enhanced visual design with modern styling and typography - Fixed literal newline display and markdown link conversion - Added proper semantic HTML structure and navigation - Includes detailed documentation for Entity, collections, and system types Author: John McCardle <mccardle.john@gmail.com> feat: complete API reference generator and finish Phase 7 documentation Implemented comprehensive API documentation generator that: - Introspects live mcrfpy module for accurate documentation - Generates organized Markdown reference (docs/API_REFERENCE.md) - Categorizes classes and functions by type - Includes full automation module documentation - Provides summary statistics Results: - 20 classes documented - 19 module functions documented - 20 automation methods documented - 100% coverage of public API - Clean, readable Markdown output Phase 7 Summary: - Completed 4/5 tasks (1 cancelled as architecturally inappropriate) - All documentation tasks successful - Type stubs, docstrings, and API reference all complete Author: John McCardle <mccardle.john@gmail.com> docs: cancel PyPI wheel task and add future vision for Python extension architecture Task #70 Analysis: - Discovered fundamental incompatibility with PyPI distribution - McRogueFace embeds CPython rather than being loaded by it - Traditional wheels expect to extend existing Python interpreter - Current architecture is application-with-embedded-Python Decisions: - Cancelled PyPI wheel preparation as out of scope for Alpha - Cleaned up attempted packaging files (pyproject.toml, setup.py, etc.) - Identified better distribution methods (installers, package managers) Added Future Vision: - Comprehensive plan for pure Python extension architecture - Would allow true "pip install mcrogueface" experience - Requires major refactoring to invert control flow - Python would drive main loop with C++ performance extensions - Unscheduled but documented as long-term possibility This clarifies the architectural boundaries and sets realistic expectations for distribution methods while preserving the vision of what McRogueFace could become with significant rework. Author: John McCardle <mccardle.john@gmail.com> feat: generate comprehensive .pyi type stubs for IDE support (#108) Created complete type stub files for the mcrfpy module to enable: - Full IntelliSense/autocomplete in IDEs - Static type checking with mypy/pyright - Better documentation tooltips - Parameter hints and return types Implementation details: - Manually crafted stubs for accuracy (15KB, 533 lines) - Complete coverage: 19 classes, 112 functions/methods - Proper type annotations using typing module - @overload decorators for multiple signatures - Type aliases for common patterns (UIElement union) - Preserved all docstrings for IDE help - Automation module fully typed - PEP 561 compliant with py.typed marker Testing: - Validated Python syntax with ast.parse() - Verified all expected classes and functions - Confirmed type annotations are well-formed - Checked docstring preservation (80 docstrings) Usage: - VS Code: Add stubs/ to python.analysis.extraPaths - PyCharm: Mark stubs/ directory as Sources Root - Other IDEs will auto-detect .pyi files This significantly improves the developer experience when using McRogueFace as a Python game engine. Author: John McCardle <mccardle.john@gmail.com> docs: add comprehensive parameter documentation to all API methods (#86) Enhanced documentation for the mcrfpy module with: - Detailed docstrings for all API methods - Type hints in documentation (name: type format) - Return type specifications - Exception documentation where applicable - Usage examples for complex methods - Module-level documentation with overview and example code Specific improvements: - Audio API: Added parameter types and return values - Scene API: Documented transition types and error conditions - Timer API: Clarified handler signature and runtime parameter - UI Search: Added wildcard pattern examples for findAll() - Metrics API: Documented all dictionary keys returned Also fixed method signatures: - Changed METH_VARARGS to METH_NOARGS for parameterless methods - Ensures proper Python calling conventions Test coverage included - all documentation is accessible via Python's __doc__ attributes and shows correctly formatted information. Author: John McCardle <mccardle.john@gmail.com> docs: mark issue #85 as completed in Phase 7 Author: John McCardle <mccardle.john@gmail.com> docs: replace all 'docstring' placeholders with comprehensive documentation (#85) Added proper Python docstrings for all UI component classes: UIFrame: - Container element that can hold child drawables - Documents position, size, colors, outline, and clip_children - Includes constructor signature with all parameters UICaption: - Text display element with font and styling - Documents text content, position, font, colors, outline - Notes that w/h are computed from text content UISprite: - Texture/sprite display element - Documents position, texture, sprite_index, scale - Notes that w/h are computed from texture and scale UIGrid: - Tile-based grid for game worlds - Documents grid dimensions, tile size, texture atlas - Includes entities collection and background_color All docstrings follow consistent format: - Constructor signature with defaults - Brief description - Args section with types and defaults - Attributes section with all properties This completes Phase 7 task #85 for documentation improvements. Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP with PyArgHelpers infrastructure completion Author: John McCardle <mccardle.john@gmail.com> refactor: implement PyArgHelpers for standardized Python argument parsing This major refactoring standardizes how position, size, and other arguments are parsed across all UI components. PyArgHelpers provides consistent handling for various argument patterns: - Position as (x, y) tuple or separate x, y args - Size as (w, h) tuple or separate width, height args - Grid position and size with proper validation - Color parsing with PyColorObject support Changes across UI components: - UICaption: Migrated to PyArgHelpers, improved resize() for future multiline support - UIFrame: Uses standardized position parsing - UISprite: Consistent position handling - UIGrid: Grid-specific position/size helpers - UIEntity: Unified argument parsing Also includes: - Improved error messages for type mismatches (int or float accepted) - Reduced code duplication across constructors - Better handling of keyword/positional argument conflicts - Maintains backward compatibility with existing API This addresses the inconsistent argument handling patterns discovered during the inheritance hierarchy work and prepares for Phase 7 documentation. Author: John McCardle <mccardle.john@gmail.com> feat(Python): establish proper inheritance hierarchy for UI types All UIDrawable-derived Python types now properly inherit from the Drawable base class in Python, matching the C++ inheritance structure. Changes: - Add Py_TPFLAGS_BASETYPE to PyDrawableType to allow inheritance - Set tp_base = &mcrfpydef::PyDrawableType for all UI types - Add PyDrawable.h include to UI type headers - Rename _Drawable to Drawable and update error message This enables proper Python inheritance: Frame, Caption, Sprite, Grid, and Entity all inherit from Drawable, allowing shared functionality and isinstance() checks. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UISprite) - Update UISprite to use base class position instead of sprite position - Synchronize sprite position with base class position for rendering - Implement onPositionChanged() for position synchronization - Update all UISprite methods to use base position consistently - Add comprehensive test coverage for UISprite position handling This is part 3 of moving position to the base class. UIGrid is the final class that needs to be updated. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UICaption) - Update UICaption to use base class position instead of text position - Synchronize text position with base class position for rendering - Add onPositionChanged() virtual method for position synchronization - Update all UICaption methods to use base position consistently - Add comprehensive test coverage for UICaption position handling This is part 2 of moving position to the base class. UISprite and UIGrid will be updated in subsequent commits. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UIFrame) - Add position member to UIDrawable base class - Add common position getters/setters (x, y, pos) to base class - Update UIFrame to use base class position instead of box position - Synchronize box position with base class position for rendering - Update all UIFrame methods to use base position consistently - Add comprehensive test coverage for UIFrame position handling This is part 1 of moving position to the base class. Other derived classes (UICaption, UISprite, UIGrid) will be updated in subsequent commits. Author: John McCardle <mccardle.john@gmail.com> refactor: remove UIEntity collision_pos field - Remove redundant collision_pos field from UIEntity - Update position getters/setters to use integer-cast position when needed - Remove all collision_pos synchronization code - Simplify entity position handling to use single float position field - Add comprehensive test coverage proving functionality is preserved This removes technical debt and simplifies the codebase without changing API behavior. Author: John McCardle <mccardle.john@gmail.com> feat: add PyArgHelpers infrastructure for standardized argument parsing - Create PyArgHelpers.h with parsing functions for position, size, grid coordinates, and color - Support tuple-based vector arguments with conflict detection - Provide consistent error messages and validation - Add comprehensive test coverage for infrastructure This sets the foundation for standardizing all Python API constructors. Author: John McCardle <mccardle.john@gmail.com> docs: mark Phase 6 (Rendering Revolution) as complete Phase 6 is now complete with all core rendering features implemented: Completed Features: - Grid background colors (#50) - customizable backgrounds with animation - RenderTexture overhaul (#6) - UIFrame clipping with opt-in architecture - Viewport-based rendering (#8) - three scaling modes with coordinate transform Strategic Decisions: - UIGrid already has optimal RenderTexture implementation for its viewport needs - UICaption/UISprite clipping deemed unnecessary (no children to clip) - Effects/Shader/Particle systems deferred to post-Phase 7 for focused delivery The rendering foundation is now solid and ready for Phase 7: Documentation & Distribution. Author: John McCardle <mccardle.john@gmail.com> feat(viewport): complete viewport-based rendering system (#8) Implements a comprehensive viewport system that allows fixed game resolution with flexible window scaling, addressing the primary wishes for issues #34, #49, and #8. Key Features: - Fixed game resolution independent of window size (window.game_resolution property) - Three scaling modes accessible via window.scaling_mode: - "center": 1:1 pixels, viewport centered in window - "stretch": viewport fills window, ignores aspect ratio - "fit": maintains aspect ratio with black bars - Automatic window-to-game coordinate transformation for mouse input - Full Python API integration with PyWindow properties Technical Implementation: - GameEngine::ViewportMode enum with Center, Stretch, Fit modes - SFML View system for efficient GPU-based viewport scaling - updateViewport() recalculates on window resize or mode change - windowToGameCoords() transforms mouse coordinates correctly - PyScene mouse input automatically uses transformed coordinates Tests: - test_viewport_simple.py: Basic API functionality - test_viewport_visual.py: Visual verification with screenshots - test_viewport_scaling.py: Interactive mode switching and resizing This completes the viewport-based rendering task and provides the foundation for resolution-independent game development as requested for Crypt of Sokoban. Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP for Phase 6 progress - Marked Phase 6 as IN PROGRESS - Updated RenderTexture overhaul (#6) as PARTIALLY COMPLETE - Marked Grid background colors (#50) as COMPLETED - Added technical notes from implementation experience - Identified viewport rendering (#8) as next priority Author: John McCardle <mccardle.john@gmail.com> feat(rendering): implement RenderTexture base infrastructure and UIFrame clipping (#6) - Added RenderTexture support to UIDrawable base class - std::unique_ptr<sf::RenderTexture> for opt-in rendering - Dirty flag system for optimization - enableRenderTexture() and markDirty() methods - Implemented clip_children property for UIFrame - Python-accessible boolean property - Automatic RenderTexture creation when enabled - Proper coordinate transformation for nested frames - Updated UIFrame::render() for clipping support - Renders to RenderTexture when clip_children=true - Handles nested clipping correctly - Only re-renders when dirty flag is set - Added comprehensive dirty flag propagation - All property setters mark frame as dirty - Size changes recreate RenderTexture - Animation system integration - Created tests for clipping functionality - Basic clipping test with visual verification - Advanced nested clipping test - Dynamic resize handling test This is Phase 1 of the RenderTexture overhaul, providing the foundation for advanced rendering effects like blur, glow, and viewport rendering. Author: John McCardle <mccardle.john@gmail.com> docs: create RenderTexture overhaul design document - Comprehensive design for Issue #6 implementation - Opt-in architecture to maintain backward compatibility - Phased implementation plan with clear milestones - Performance considerations and risk mitigation - API design for clipping and future effects Also includes Grid background color test Author: John McCardle <mccardle.john@gmail.com> feat(Grid): add customizable background_color property (#50) - Added sf::Color background_color member with default dark gray - Python property getter/setter for background_color - Animation support for individual color components (r/g/b/a) - Replaces hardcoded clear color in render method - Test demonstrates color changes and property access Closes #50 Author: John McCardle <mccardle.john@gmail.com> docs: update roadmap for Phase 6 preparation - Mark Phase 5 (Window/Scene Architecture) as complete - Update issue statuses (#34, #61, #1, #105 completed) - Add Phase 6 implementation strategy for RenderTexture overhaul - Archive Phase 5 test files to .archive/ - Identify quick wins and technical approach for rendering work Author: John McCardle <mccardle.john@gmail.com> feat(Phase 5): Complete Window/Scene Architecture - Window singleton with properties (resolution, fullscreen, vsync, title) - OOP Scene support with lifecycle methods (on_enter, on_exit, on_keypress, update) - Window resize events trigger scene.on_resize callbacks - Scene transitions (fade, slide_left/right/up/down) with smooth animations - Full integration of Python Scene objects with C++ engine All Phase 5 tasks (#34, #1, #61, #105) completed successfully. Author: John McCardle <mccardle.john@gmail.com> research: SFML 3.0 migration analysis - Analyzed SFML 3.0 breaking changes (event system, scoped enums, C++17) - Assessed migration impact on McRogueFace (40+ files affected) - Evaluated timing relative to mcrfpy.sfml module plans - Recommended deferring migration until after mcrfpy.sfml implementation - Created SFML_3_MIGRATION_RESEARCH.md with comprehensive strategy Author: John McCardle <mccardle.john@gmail.com> research: SFML exposure options analysis (#14) - Analyzed current SFML 2.6.1 usage throughout codebase - Evaluated python-sfml (abandoned, only supports SFML 2.3.2) - Recommended direct integration as mcrfpy.sfml module - Created comprehensive SFML_EXPOSURE_RESEARCH.md with implementation plan - Identified opportunity to provide modern SFML 2.6+ Python bindings Author: John McCardle <mccardle.john@gmail.com> feat: add basic profiling/metrics system (#104) - Add ProfilingMetrics struct to track performance data - Track frame time (current and 60-frame rolling average) - Calculate FPS from average frame time - Count draw calls, UI elements, and visible elements per frame - Track total runtime and current frame number - PyScene counts elements during render - Expose metrics via mcrfpy.getMetrics() returning dict This provides basic performance monitoring capabilities for identifying bottlenecks and optimizing rendering performance. Author: John McCardle <mccardle.john@gmail.com> fix: improve click handling with proper z-order and coordinate transforms - UIFrame: Fix coordinate transformation (subtract parent pos, not add) - UIFrame: Check children in reverse order (highest z-index first) - UIFrame: Skip invisible elements entirely - PyScene: Sort elements by z-index before checking clicks - PyScene: Stop at first element that handles the click - UIGrid: Implement entity click detection with grid coordinate transform - UIGrid: Check entities in reverse order, return sprite as target Click events now correctly respect z-order (top elements get priority), handle coordinate transforms for nested frames, and support clicking on grid entities. Elements without click handlers are transparent to clicks, allowing elements below to receive them. Note: Click testing requires non-headless mode due to PyScene limitation. feat: implement name system for finding UI elements (#39/40/41) - Add 'name' property to UIDrawable base class - All UI elements (Frame, Caption, Sprite, Grid, Entity) support .name - Entity delegates name to its sprite member - Add find(name, scene=None) function for exact match search - Add findAll(pattern, scene=None) with wildcard support (* matches any sequence) - Both functions search recursively through Frame children and Grid entities - Comprehensive test coverage for all functionality This provides a simple way to find UI elements by name in Python scripts, supporting both exact matches and wildcard patterns. Author: John McCardle <mccardle.john@gmail.com> fix: prevent segfault when closing window via X button - Add cleanup() method to GameEngine to clear Python references before destruction - Clear timers and McRFPy_API references in proper order - Call cleanup() at end of run loop and in destructor - Ensure cleanup is only called once per GameEngine instance Also includes: - Fix audio ::stop() calls (already in place, OpenAL warning is benign) - Add Caption support for x, y keywords (e.g. Caption("text", x=5, y=10)) - Refactor UIDrawable_methods.h into UIBase.h for better organization - Move UIEntity-specific implementations to UIEntityPyMethods.h Author: John McCardle <mccardle.john@gmail.com> feat: stabilize test suite and add UIDrawable methods - Add visible, opacity properties to all UI classes (#87, #88) - Add get_bounds(), move(), resize() methods to UIDrawable (#89, #98) - Create UIDrawable_methods.h with template implementations - Fix test termination issues - all tests now exit properly - Fix test_sprite_texture_swap.py click handler signature - Fix test_drawable_base.py segfault in headless mode - Convert audio objects to pointers for cleanup (OpenAL warning persists) - Remove debug print statements from UICaption - Special handling for UIEntity to delegate drawable methods to sprite All test files are now "airtight" - they complete successfully, terminate on their own, and handle edge cases properly. Author: John McCardle <mccardle.john@gmail.com> docs: add Phase 1-3 completion summary - Document all completed tasks across three phases - Show before/after API improvements - Highlight technical achievements - Outline next steps for Phase 4-7 Author: John McCardle <mccardle.john@gmail.com> feat: implement mcrfpy.Timer object with pause/resume/cancel capabilities closes #103 - Created PyTimer.h/cpp with object-oriented timer interface - Enhanced PyTimerCallable with pause/resume state tracking - Added timer control methods: pause(), resume(), cancel(), restart() - Added timer properties: interval, remaining, paused, active, callback - Fixed timing logic to prevent rapid catch-up after resume - Timer objects automatically register with game engine - Added comprehensive test demonstrating all functionality Author: John McCardle <mccardle.john@gmail.com> feat(Color): add helper methods from_hex, to_hex, lerp closes #94 - Add Color.from_hex(hex_string) class method for creating colors from hex - Support formats: #RRGGBB, RRGGBB, #RRGGBBAA, RRGGBBAA - Add color.to_hex() to convert Color to hex string - Add color.lerp(other, t) for smooth color interpolation - Comprehensive test coverage for all methods Author: John McCardle <mccardle.john@gmail.com> fix: properly configure UTF-8 encoding for Python stdio - Use PyConfig to set stdio_encoding="UTF-8" during initialization - Set stdio_errors="surrogateescape" for robust handling - Configure in both init_python() and init_python_with_config() - Cleaner solution than wrapping streams after initialization - Fixes UnicodeEncodeError when printing unicode characters Author: John McCardle <mccardle.john@gmail.com> feat(Vector): implement arithmetic operations closes #93 - Add PyNumberMethods with add, subtract, multiply, divide, negate, absolute - Add rich comparison for equality/inequality checks - Add boolean check (zero vector is False) - Implement vector methods: magnitude(), normalize(), dot(), distance_to(), angle(), copy() - Fix UIDrawable::get_click() segfault when click_callable is null - Comprehensive test coverage for all arithmetic operations Author: John McCardle <mccardle.john@gmail.com> feat: Complete position argument standardization for all UI classes - Frame and Sprite now support pos keyword override - Entity now accepts x,y arguments (was pos-only before) - All UI classes now consistently support: - (x, y) positional - ((x, y)) tuple - x=x, y=y keywords - pos=(x,y) keyword - pos=Vector keyword - Improves API consistency and flexibility Author: John McCardle <mccardle.john@gmail.com> feat: Standardize position arguments across all UI classes - Create PyPositionHelper for consistent position parsing - Grid.at() now accepts (x,y), ((x,y)), x=x, y=y, pos=(x,y) - Caption now accepts x,y args in addition to pos - Grid init fully supports keyword arguments - Maintain backward compatibility for all formats - Consistent error messages across classes Author: John McCardle <mccardle.john@gmail.com> feat: Add Entity.die() method for lifecycle management closes #30 - Remove entity from its grid's entity list - Clear grid reference after removal - Safe to call multiple times (no-op if not on grid) - Works with shared_ptr entity management Author: John McCardle <mccardle.john@gmail.com> perf: Skip out-of-bounds entities during Grid rendering closes #52 - Add visibility bounds check in entity render loop - Skip entities outside view with 1 cell margin - Improves performance for large grids with many entities - Bounds check considers zoom and pan settings Author: John McCardle <mccardle.john@gmail.com> verify: Sprite texture swapping functionality closes #19 - Texture property getter/setter already implemented - Position/scale preservation during swap confirmed - Type validation for texture assignment working - Tests verify functionality is complete Author: John McCardle <mccardle.john@gmail.com> feat: Grid size tuple support closes #90 - Add grid_size keyword parameter to Grid.__init__ - Accept tuple or list of two integers - Override grid_x/grid_y if grid_size provided - Maintain backward compatibility - Add comprehensive test coverage Author: John McCardle <mccardle.john@gmail.com> feat: Phase 1 - safe constructors and _Drawable foundation Closes #7 - Make all UI class constructors safe: - Added safe default constructors for UISprite, UIGrid, UIEntity, UICaption - Initialize all members to predictable values - Made Python init functions accept no arguments - Added x,y properties to UIEntity Closes #71 - Create _Drawable Python base class: - Created PyDrawable.h/cpp with base type (not yet inherited by UI types) - Registered in module initialization Closes #87 - Add visible property: - Added bool visible=true to UIDrawable base class - All render methods check visibility before drawing Closes #88 - Add opacity property: - Added float opacity=1.0 to UIDrawable base class - UICaption and UISprite apply opacity to alpha channel Closes #89 - Add get_bounds() method: - Virtual method returns sf::FloatRect(x,y,w,h) - Implemented in Frame, Caption, Sprite, Grid Closes #98 - Add move() and resize() methods: - move(dx,dy) for relative movement - resize(w,h) for absolute sizing - Caption resize is no-op (size controlled by font) Author: John McCardle <mccardle.john@gmail.com> docs: comprehensive alpha_streamline_2 plan and strategic vision - Add 7-phase development plan for alpha_streamline_2 branch - Define architectural dependencies and critical path - Identify new issues needed (Timer objects, event system, etc.) - Add strategic vision document with 3 transformative directions - Timeline: 10-12 weeks to solid Beta foundation Author: John McCardle <mccardle.john@gmail.com> feat(Grid): flexible at() method arguments - Support tuple argument: grid.at((x, y)) - Support keyword arguments: grid.at(x=5, y=3) - Support pos keyword: grid.at(pos=(2, 8)) - Maintain backward compatibility with grid.at(x, y) - Add comprehensive error handling for invalid arguments Improves API ergonomics and Python-like flexibility
2025-07-09 22:41:15 -04:00
static PyGetSetDef getsetters[];
static PyMethodDef methods[];
};
namespace mcrfpydef {
static PyTypeObject PyTimerType = {
.ob_base = {.ob_base = {.ob_refcnt = 1, .ob_type = NULL}, .ob_size = 0},
.tp_name = "mcrfpy.Timer",
.tp_basicsize = sizeof(PyTimerObject),
.tp_itemsize = 0,
.tp_dealloc = (destructor)PyTimer::dealloc,
.tp_repr = PyTimer::repr,
.tp_flags = Py_TPFLAGS_DEFAULT,
Squashed commit of the following: [alpha_presentable] Author: John McCardle <mccardle.john@gmail.com> Co-Authored-By: Claude <noreply@anthropic.com> commit dc47f2474c7b2642d368f9772894aed857527807 the UIEntity rant commit 673ca8e1b089ea670257fc04ae1a676ed95a40ed I forget when these tests were written, but I want them in the squash merge commit 70c71565c684fa96e222179271ecb13a156d80ad Fix UI object segfault by switching from managed to manual weakref management The UI types (Frame, Caption, Sprite, Grid, Entity) were using Py_TPFLAGS_MANAGED_WEAKREF while also trying to manually create weakrefs for the PythonObjectCache. This is fundamentally incompatible - when Python manages weakrefs internally, PyWeakref_NewRef() cannot access the weakref list properly, causing segfaults. Changed all UI types to use manual weakref management (like PyTimer): - Restored weakreflist field in all UI type structures - Removed Py_TPFLAGS_MANAGED_WEAKREF from all UI type flags - Added tp_weaklistoffset for all UI types in module initialization - Initialize weakreflist=NULL in tp_new and init methods - Call PyObject_ClearWeakRefs() in dealloc functions This allows the PythonObjectCache to continue working correctly, maintaining Python object identity for C++ objects across the boundary. Fixes segfault when creating UI objects (e.g., Caption, Grid) that was preventing tutorial scripts from running. This is the bulk of the required behavior for Issue #126. that issure isn't ready for closure yet; several other sub-issues left. closes #110 mention issue #109 - resolves some __init__ related nuisances commit 3dce3ec539ae99e32d869007bf3f49d03e4e2f89 Refactor timer system for cleaner architecture and enhanced functionality Major improvements to the timer system: - Unified all timer logic in the Timer class (C++) - Removed PyTimerCallable subclass, now using PyCallable directly - Timer objects are now passed to callbacks as first argument - Added 'once' parameter for one-shot timers that auto-stop - Implemented proper PythonObjectCache integration with weakref support API enhancements: - New callback signature: callback(timer, runtime) instead of just (runtime) - Timer objects expose: name, interval, remaining, paused, active, once properties - Methods: pause(), resume(), cancel(), restart() - Comprehensive documentation with examples - Enhanced repr showing timer state (active/paused/once/remaining time) This cleanup follows the UIEntity/PyUIEntity pattern and makes the timer system more Pythonic while maintaining backward compatibility through the legacy setTimer/delTimer API. closes #121 commit 145834cfc31b8dabc4cb3591b9cb4ed99fc8b964 Implement Python object cache to preserve derived types in collections Add a global cache system that maintains weak references to Python objects, ensuring that derived Python classes maintain their identity when stored in and retrieved from C++ collections. Key changes: - Add PythonObjectCache singleton with serial number system - Each cacheable object (UIDrawable, UIEntity, Timer, Animation) gets unique ID - Cache stores weak references to prevent circular reference memory leaks - Update all UI type definitions to support weak references (Py_TPFLAGS_MANAGED_WEAKREF) - Enable subclassing for all UI types (Py_TPFLAGS_BASETYPE) - Collections check cache before creating new Python wrappers - Register objects in cache during __init__ methods - Clean up cache entries in C++ destructors This ensures that Python code like: ```python class MyFrame(mcrfpy.Frame): def __init__(self): super().__init__() self.custom_data = "preserved" frame = MyFrame() scene.ui.append(frame) retrieved = scene.ui[0] # Same MyFrame instance with custom_data intact ``` Works correctly, with retrieved maintaining the derived type and custom attributes. Closes #112 commit c5e7e8e29835a69f4c50f3c99fd3123012635a9a Update test demos for new Python API and entity system - Update all text input demos to use new Entity constructor signature - Fix pathfinding showcase to work with new entity position handling - Remove entity_waypoints tracking in favor of simplified movement - Delete obsolete exhaustive_api_demo.py (superseded by newer demos) - Adjust entity creation calls to match Entity((x, y), texture, sprite_index) pattern commit 6d29652ae7418745dc24066532454167d447df89 Update animation demo suite with crash fixes and improvements - Add warnings about AnimationManager segfault bug in sizzle_reel_final.py - Create sizzle_reel_final_fixed.py that works around the crash by hiding objects instead of removing them - Increase font sizes for better visibility in demos - Extend demo durations for better showcase of animations - Remove debug prints from animation_sizzle_reel_working.py - Minor cleanup and improvements to all animation demos commit a010e5fa968feaba620dcf2eda44fb9514512151 Update game scripts for new Python API - Convert entity position access from tuple to x/y properties - Update caption size property to font_size - Fix grid boundary checks to use grid_size instead of exceptions - Clean up demo timer on menu exit to prevent callbacks These changes adapt the game scripts to work with the new standardized Python API constructors and property names. commit 9c8d6c459109be883cb8070b8ef83c60bfc1a970 Fix click event z-order handling in PyScene Changed click detection to properly respect z-index by: - Sorting ui_elements in-place when needed (same as render order) - Using reverse iterators to check highest z-index elements first - This ensures top-most elements receive clicks before lower ones commit dcd1b0ca33d46639023221f4d7d52000b947dbdf Add roguelike tutorial implementation files Implement Parts 0-2 of the classic roguelike tutorial adapted for McRogueFace: - Part 0: Basic grid setup and tile rendering - Part 1: Drawing '@' symbol and basic movement - Part 1b: Variant with sprite-based player - Part 2: Entity system and NPC implementation with three movement variants: - part_2.py: Standard implementation - part_2-naive.py: Naive movement approach - part_2-onemovequeued.py: Queued movement system Includes tutorial assets: - tutorial2.png: Tileset for dungeon tiles - tutorial_hero.png: Player sprite sheet commit 6813fb5129738cca2d79c80304834523561ba7fb Standardize Python API constructors and remove PyArgHelpers - Remove PyArgHelpers.h and all macro-based argument parsing - Convert all UI class constructors to use PyArg_ParseTupleAndKeywords - Standardize constructor signatures across UICaption, UIEntity, UIFrame, UIGrid, and UISprite - Replace PYARGHELPER_SINGLE/MULTI macros with explicit argument parsing - Improve error messages and argument validation - Maintain backward compatibility with existing Python code This change improves code maintainability and consistency across the Python API. commit 6f67fbb51efaf70e52fba8c939298dcdff50450a Fix animation callback crashes from iterator invalidation (#119) Resolved segfaults caused by creating new animations from within animation callbacks. The issue was iterator invalidation in AnimationManager::update() when callbacks modified the active animations vector. Changes: - Add deferred animation queue to AnimationManager - New animations created during update are queued and added after - Set isUpdating flag to track when in update loop - Properly handle Animation destructor during callback execution - Add clearCallback() method for safe cleanup scenarios This fixes the "free(): invalid pointer" and "malloc(): unaligned fastbin chunk detected" errors that occurred with rapid animation creation in callbacks. commit eb88c7b3aab3da519db7569106c34f3510b6e963 Add animation completion callbacks (#119) Implement callbacks that fire when animations complete, enabling direct causality between animation end and game state changes. This eliminates race conditions from parallel timer workarounds. - Add optional callback parameter to Animation constructor - Callbacks execute synchronously when animation completes - Proper Python reference counting with GIL safety - Callbacks receive (anim, target) parameters (currently None) - Exception handling prevents crashes from Python errors Example usage: ```python def on_complete(anim, target): player_moving = False anim = mcrfpy.Animation("x", 300.0, 1.0, "easeOut", callback=on_complete) anim.start(player) ``` closes #119 commit 9fb428dd0176a4d7cfad09deb7509d8aa5562868 Update ROADMAP with GitHub issue numbers (#111-#125) Added issue numbers from GitHub tracker to roadmap items: - #111: Grid Click Events Broken in Headless - #112: Object Splitting Bug (Python type preservation) - #113: Batch Operations for Grid - #114: CellView API - #115: SpatialHash Implementation - #116: Dirty Flag System - #117: Memory Pool for Entities - #118: Scene as Drawable - #119: Animation Completion Callbacks - #120: Animation Property Locking - #121: Timer Object System - #122: Parent-Child UI System - #123: Grid Subgrid System - #124: Grid Point Animation - #125: GitHub Issues Automation Also updated existing references: - #101/#110: Constructor standardization - #109: Vector class indexing Note: Tutorial-specific items and Python-implementable features (input queue, collision reservation) are not tracked as engine issues. commit 062e4dadc42833bf5a3559e5d7c4ceb4abb7e9c0 Fix animation segfaults with RAII weak_ptr implementation Resolved two critical segmentation faults in AnimationManager: 1. Race condition when creating multiple animations in timer callbacks 2. Exit crash when animations outlive their target objects Changes: - Replace raw pointers with std::weak_ptr for automatic target invalidation - Add Animation::complete() to jump animations to final value - Add Animation::hasValidTarget() to check if target still exists - Update AnimationManager to auto-remove invalid animations - Add AnimationManager::clear() call to GameEngine::cleanup() - Update Python bindings to pass shared_ptr instead of raw pointers This ensures animations can never reference destroyed objects, following proper RAII principles. Tested with sizzle_reel_final.py and stress tests creating/destroying hundreds of animated objects. commit 98fc49a978ec792ee6096f40fd4e19841b8ec6a3 Directory structure cleanup and organization overhaul
2025-07-15 21:30:49 -04:00
.tp_doc = PyDoc_STR("Timer(name, callback, interval, once=False)\n\n"
"Create a timer that calls a function at regular intervals.\n\n"
"Args:\n"
" name (str): Unique identifier for the timer\n"
" callback (callable): Function to call - receives (timer, runtime) args\n"
" interval (int): Time between calls in milliseconds\n"
" once (bool): If True, timer stops after first call. Default: False\n\n"
"Attributes:\n"
" interval (int): Time between calls in milliseconds\n"
" remaining (int): Time until next call in milliseconds (read-only)\n"
" paused (bool): Whether timer is paused (read-only)\n"
" active (bool): Whether timer is active and not paused (read-only)\n"
" callback (callable): The callback function\n"
" once (bool): Whether timer stops after firing once\n\n"
"Methods:\n"
" pause(): Pause the timer, preserving time remaining\n"
" resume(): Resume a paused timer\n"
" cancel(): Stop and remove the timer\n"
" restart(): Reset timer to start from beginning\n\n"
"Example:\n"
" def on_timer(timer, runtime):\n"
" print(f'Timer {timer} fired at {runtime}ms')\n"
" if runtime > 5000:\n"
" timer.cancel()\n"
" \n"
" timer = mcrfpy.Timer('my_timer', on_timer, 1000)\n"
" timer.pause() # Pause timer\n"
" timer.resume() # Resume timer\n"
" timer.once = True # Make it one-shot"),
Squashed commit of 53 Commits: [alpha_streamline_2] * Field of View, Pathing courtesy of libtcod * python-tcod emulation at `mcrfpy.libtcod` - partial implementation * documentation, tutorial drafts: in middling to good shape ┌────────────┬────────────────────┬───────────┬────────────┬───────────────┬────────────────┬────────────────┬─────────────┐ │ Date │ Models │ Input │ Output │ Cache Create │ Cache Read │ Total Tokens │ Cost (USD) │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-05 │ - opus-4 │ 13,630 │ 159,500 │ 3,854,900 │ 84,185,034 │ 88,213,064 │ $210.72 │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-06 │ - opus-4 │ 5,814 │ 113,190 │ 4,242,407 │ 150,191,183 │ 154,552,594 │ $313.41 │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-07 │ - opus-4 │ 7,244 │ 104,599 │ 3,894,453 │ 81,781,179 │ 85,787,475 │ $184.46 │ │ │ - sonnet-4 │ │ │ │ │ │ │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-08 │ - opus-4 │ 50,312 │ 158,599 │ 5,021,189 │ 60,028,561 │ 65,258,661 │ $167.05 │ │ │ - sonnet-4 │ │ │ │ │ │ │ ├────────────┼────────────────────┼───────────┼────────────┼───────────────┼────────────────┼────────────────┼─────────────┤ │ 2025-07-09 │ - opus-4 │ 6,311 │ 109,653 │ 4,171,140 │ 80,092,875 │ 84,379,979 │ $193.09 │ │ │ - sonnet-4 │ │ │ │ │ │ │ └────────────┴────────────────────┴───────────┴────────────┴───────────────┴────────────────┴────────────────┴─────────────┘ 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> Author: John McCardle <mccardle.john@gmail.com> Draft tutorials Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP with FOV, A* pathfinding, and GUI text widget completions - Mark TCOD Integration Sprint as complete - Document FOV system with perspective rendering implementation - Update UIEntity pathfinding status to complete with A* and caching - Add comprehensive achievement entry for July 10 work - Reflect current engine capabilities accurately The engine now has all core roguelike mechanics: - Field of View with per-entity visibility - Pathfinding (both Dijkstra and A*) - Text input for in-game consoles - Performance optimizations throughout Author: John McCardle <mccardle.john@gmail.com> feat(engine): implement perspective FOV, pathfinding, and GUI text widgets Major Engine Enhancements: - Complete FOV (Field of View) system with perspective rendering - UIGrid.perspective property for entity-based visibility - Three-layer overlay colors (unexplored, explored, visible) - Per-entity visibility state tracking - Perfect knowledge updates only for explored areas - Advanced Pathfinding Integration - A* pathfinding implementation in UIGrid - Entity.path_to() method for direct pathfinding - Dijkstra maps for multi-target pathfinding - Path caching for performance optimization - GUI Text Input Widgets - TextInputWidget class with cursor, selection, scrolling - Improved widget with proper text rendering and input handling - Example showcase of multiple text input fields - Foundation for in-game console and chat systems - Performance & Architecture Improvements - PyTexture copy operations optimized - GameEngine update cycle refined - UIEntity property handling enhanced - UITestScene modernized Test Suite: - Interactive visibility demos showing FOV in action - Pathfinding comparison (A* vs Dijkstra) - Debug utilities for visibility and empty path handling - Sizzle reel demo combining pathfinding and vision - Multiple text input test scenarios This commit brings McRogueFace closer to a complete roguelike engine with essential features like line-of-sight, intelligent pathfinding, and interactive text input capabilities. Author: John McCardle <mccardle.john@gmail.com> feat(demos): enhance interactive pathfinding demos with entity.path_to() - dijkstra_interactive_enhanced.py: Animation along paths with smooth movement - M key to start movement animation - P to pause/resume - R to reset positions - Visual path gradient for better clarity - pathfinding_showcase.py: Advanced multi-entity behaviors - Chase mode: enemies pursue player - Flee mode: enemies avoid player - Patrol mode: entities follow waypoints - WASD player movement - Dijkstra distance field visualization (D key) - Larger dungeon map with multiple rooms - Both demos use new entity.path_to() method - Smooth interpolated movement animations - Real-time pathfinding recalculation - Comprehensive test coverage These demos showcase the power of integrated pathfinding for game AI. Author: John McCardle <mccardle.john@gmail.com> feat(entity): implement path_to() method for entity pathfinding - Add path_to(target_x, target_y) method to UIEntity class - Uses existing Dijkstra pathfinding implementation from UIGrid - Returns list of (x, y) coordinate tuples for complete path - Supports both positional and keyword argument formats - Proper error handling for out-of-bounds and no-grid scenarios - Comprehensive test suite covering normal and edge cases Part of TCOD integration sprint - gives entities immediate pathfinding capabilities. Author: John McCardle <mccardle.john@gmail.com> docs: update roadmap with Dijkstra pathfinding progress - Mark UIGrid TCOD Integration as completed - Document critical PyArg bug fix achievement - Update UIEntity Pathfinding to 50% complete - Add detailed progress notes for July 9 sprint work Author: John McCardle <mccardle.john@gmail.com> feat(tcod): complete Dijkstra pathfinding implementation with critical PyArg fix - Add complete Dijkstra pathfinding to UIGrid class - compute_dijkstra(), get_dijkstra_distance(), get_dijkstra_path() - Full TCODMap and TCODDijkstra integration - Proper memory management in constructors/destructors - Create mcrfpy.libtcod submodule with Python bindings - dijkstra_compute(), dijkstra_get_distance(), dijkstra_get_path() - line() function for drawing corridors - Foundation for future FOV and pathfinding algorithms - Fix critical PyArg bug in UIGridPoint color setter - PyObject_to_sfColor() now handles both Color objects and tuples - Prevents "SystemError: new style getargs format but argument is not a tuple" - Proper error handling and exception propagation - Add comprehensive test suite - test_dijkstra_simple.py validates all pathfinding operations - dijkstra_test.py for headless testing with screenshots - dijkstra_interactive.py for full user interaction demos - Consolidate and clean up test files - Removed 6 duplicate/broken demo attempts - Two clean versions: headless test + interactive demo Part of TCOD integration sprint for RoguelikeDev Tutorial Event. Author: John McCardle <mccardle.john@gmail.com> Roguelike Tutorial Planning + Prep Author: John McCardle <mccardle.john@gmail.com> feat(docs): complete markdown API documentation export - Created comprehensive markdown documentation matching HTML completeness - Documented all 75 functions, 20 classes, 56 methods, and 20 automation methods - Zero ellipsis instances - complete coverage with no missing documentation - Added proper markdown formatting with code blocks and navigation - Included full parameter documentation, return values, and examples Key features: - 23KB GitHub-compatible markdown documentation - 47 argument sections with detailed parameters - 35 return value specifications - 23 code examples with syntax highlighting - 38 explanatory notes and 10 exception specifications - Full table of contents with anchor links - Professional markdown formatting Both export formats now available: - HTML: docs/api_reference_complete.html (54KB, rich styling) - Markdown: docs/API_REFERENCE_COMPLETE.md (23KB, GitHub-compatible) Author: John McCardle <mccardle.john@gmail.com> feat(docs): complete API documentation with zero missing methods - Eliminated ALL ellipsis instances (0 remaining) - Documented 40 functions with complete signatures and examples - Documented 21 classes with full method and property documentation - Added 56 method descriptions with detailed parameters and return values - Included 15 complete property specifications - Added 24 code examples and 38 explanatory notes - Comprehensive coverage of all collection methods, system classes, and functions Key highlights: - EntityCollection/UICollection: Complete method docs (append, remove, extend, count, index) - Animation: Full property and method documentation with examples - Color: All manipulation methods (from_hex, to_hex, lerp) with examples - Vector: Complete mathematical operations (magnitude, normalize, dot, distance_to, angle, copy) - Scene: All management methods including register_keyboard - Timer: Complete control methods (pause, resume, cancel, restart) - Window: All management methods (get, center, screenshot) - System functions: Complete audio, scene, UI, and system function documentation Author: John McCardle <mccardle.john@gmail.com> feat(docs): create professional HTML API documentation - Fixed all formatting issues from original HTML output - Added comprehensive constructor documentation for all classes - Enhanced visual design with modern styling and typography - Fixed literal newline display and markdown link conversion - Added proper semantic HTML structure and navigation - Includes detailed documentation for Entity, collections, and system types Author: John McCardle <mccardle.john@gmail.com> feat: complete API reference generator and finish Phase 7 documentation Implemented comprehensive API documentation generator that: - Introspects live mcrfpy module for accurate documentation - Generates organized Markdown reference (docs/API_REFERENCE.md) - Categorizes classes and functions by type - Includes full automation module documentation - Provides summary statistics Results: - 20 classes documented - 19 module functions documented - 20 automation methods documented - 100% coverage of public API - Clean, readable Markdown output Phase 7 Summary: - Completed 4/5 tasks (1 cancelled as architecturally inappropriate) - All documentation tasks successful - Type stubs, docstrings, and API reference all complete Author: John McCardle <mccardle.john@gmail.com> docs: cancel PyPI wheel task and add future vision for Python extension architecture Task #70 Analysis: - Discovered fundamental incompatibility with PyPI distribution - McRogueFace embeds CPython rather than being loaded by it - Traditional wheels expect to extend existing Python interpreter - Current architecture is application-with-embedded-Python Decisions: - Cancelled PyPI wheel preparation as out of scope for Alpha - Cleaned up attempted packaging files (pyproject.toml, setup.py, etc.) - Identified better distribution methods (installers, package managers) Added Future Vision: - Comprehensive plan for pure Python extension architecture - Would allow true "pip install mcrogueface" experience - Requires major refactoring to invert control flow - Python would drive main loop with C++ performance extensions - Unscheduled but documented as long-term possibility This clarifies the architectural boundaries and sets realistic expectations for distribution methods while preserving the vision of what McRogueFace could become with significant rework. Author: John McCardle <mccardle.john@gmail.com> feat: generate comprehensive .pyi type stubs for IDE support (#108) Created complete type stub files for the mcrfpy module to enable: - Full IntelliSense/autocomplete in IDEs - Static type checking with mypy/pyright - Better documentation tooltips - Parameter hints and return types Implementation details: - Manually crafted stubs for accuracy (15KB, 533 lines) - Complete coverage: 19 classes, 112 functions/methods - Proper type annotations using typing module - @overload decorators for multiple signatures - Type aliases for common patterns (UIElement union) - Preserved all docstrings for IDE help - Automation module fully typed - PEP 561 compliant with py.typed marker Testing: - Validated Python syntax with ast.parse() - Verified all expected classes and functions - Confirmed type annotations are well-formed - Checked docstring preservation (80 docstrings) Usage: - VS Code: Add stubs/ to python.analysis.extraPaths - PyCharm: Mark stubs/ directory as Sources Root - Other IDEs will auto-detect .pyi files This significantly improves the developer experience when using McRogueFace as a Python game engine. Author: John McCardle <mccardle.john@gmail.com> docs: add comprehensive parameter documentation to all API methods (#86) Enhanced documentation for the mcrfpy module with: - Detailed docstrings for all API methods - Type hints in documentation (name: type format) - Return type specifications - Exception documentation where applicable - Usage examples for complex methods - Module-level documentation with overview and example code Specific improvements: - Audio API: Added parameter types and return values - Scene API: Documented transition types and error conditions - Timer API: Clarified handler signature and runtime parameter - UI Search: Added wildcard pattern examples for findAll() - Metrics API: Documented all dictionary keys returned Also fixed method signatures: - Changed METH_VARARGS to METH_NOARGS for parameterless methods - Ensures proper Python calling conventions Test coverage included - all documentation is accessible via Python's __doc__ attributes and shows correctly formatted information. Author: John McCardle <mccardle.john@gmail.com> docs: mark issue #85 as completed in Phase 7 Author: John McCardle <mccardle.john@gmail.com> docs: replace all 'docstring' placeholders with comprehensive documentation (#85) Added proper Python docstrings for all UI component classes: UIFrame: - Container element that can hold child drawables - Documents position, size, colors, outline, and clip_children - Includes constructor signature with all parameters UICaption: - Text display element with font and styling - Documents text content, position, font, colors, outline - Notes that w/h are computed from text content UISprite: - Texture/sprite display element - Documents position, texture, sprite_index, scale - Notes that w/h are computed from texture and scale UIGrid: - Tile-based grid for game worlds - Documents grid dimensions, tile size, texture atlas - Includes entities collection and background_color All docstrings follow consistent format: - Constructor signature with defaults - Brief description - Args section with types and defaults - Attributes section with all properties This completes Phase 7 task #85 for documentation improvements. Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP with PyArgHelpers infrastructure completion Author: John McCardle <mccardle.john@gmail.com> refactor: implement PyArgHelpers for standardized Python argument parsing This major refactoring standardizes how position, size, and other arguments are parsed across all UI components. PyArgHelpers provides consistent handling for various argument patterns: - Position as (x, y) tuple or separate x, y args - Size as (w, h) tuple or separate width, height args - Grid position and size with proper validation - Color parsing with PyColorObject support Changes across UI components: - UICaption: Migrated to PyArgHelpers, improved resize() for future multiline support - UIFrame: Uses standardized position parsing - UISprite: Consistent position handling - UIGrid: Grid-specific position/size helpers - UIEntity: Unified argument parsing Also includes: - Improved error messages for type mismatches (int or float accepted) - Reduced code duplication across constructors - Better handling of keyword/positional argument conflicts - Maintains backward compatibility with existing API This addresses the inconsistent argument handling patterns discovered during the inheritance hierarchy work and prepares for Phase 7 documentation. Author: John McCardle <mccardle.john@gmail.com> feat(Python): establish proper inheritance hierarchy for UI types All UIDrawable-derived Python types now properly inherit from the Drawable base class in Python, matching the C++ inheritance structure. Changes: - Add Py_TPFLAGS_BASETYPE to PyDrawableType to allow inheritance - Set tp_base = &mcrfpydef::PyDrawableType for all UI types - Add PyDrawable.h include to UI type headers - Rename _Drawable to Drawable and update error message This enables proper Python inheritance: Frame, Caption, Sprite, Grid, and Entity all inherit from Drawable, allowing shared functionality and isinstance() checks. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UISprite) - Update UISprite to use base class position instead of sprite position - Synchronize sprite position with base class position for rendering - Implement onPositionChanged() for position synchronization - Update all UISprite methods to use base position consistently - Add comprehensive test coverage for UISprite position handling This is part 3 of moving position to the base class. UIGrid is the final class that needs to be updated. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UICaption) - Update UICaption to use base class position instead of text position - Synchronize text position with base class position for rendering - Add onPositionChanged() virtual method for position synchronization - Update all UICaption methods to use base position consistently - Add comprehensive test coverage for UICaption position handling This is part 2 of moving position to the base class. UISprite and UIGrid will be updated in subsequent commits. Author: John McCardle <mccardle.john@gmail.com> refactor: move position property to UIDrawable base class (UIFrame) - Add position member to UIDrawable base class - Add common position getters/setters (x, y, pos) to base class - Update UIFrame to use base class position instead of box position - Synchronize box position with base class position for rendering - Update all UIFrame methods to use base position consistently - Add comprehensive test coverage for UIFrame position handling This is part 1 of moving position to the base class. Other derived classes (UICaption, UISprite, UIGrid) will be updated in subsequent commits. Author: John McCardle <mccardle.john@gmail.com> refactor: remove UIEntity collision_pos field - Remove redundant collision_pos field from UIEntity - Update position getters/setters to use integer-cast position when needed - Remove all collision_pos synchronization code - Simplify entity position handling to use single float position field - Add comprehensive test coverage proving functionality is preserved This removes technical debt and simplifies the codebase without changing API behavior. Author: John McCardle <mccardle.john@gmail.com> feat: add PyArgHelpers infrastructure for standardized argument parsing - Create PyArgHelpers.h with parsing functions for position, size, grid coordinates, and color - Support tuple-based vector arguments with conflict detection - Provide consistent error messages and validation - Add comprehensive test coverage for infrastructure This sets the foundation for standardizing all Python API constructors. Author: John McCardle <mccardle.john@gmail.com> docs: mark Phase 6 (Rendering Revolution) as complete Phase 6 is now complete with all core rendering features implemented: Completed Features: - Grid background colors (#50) - customizable backgrounds with animation - RenderTexture overhaul (#6) - UIFrame clipping with opt-in architecture - Viewport-based rendering (#8) - three scaling modes with coordinate transform Strategic Decisions: - UIGrid already has optimal RenderTexture implementation for its viewport needs - UICaption/UISprite clipping deemed unnecessary (no children to clip) - Effects/Shader/Particle systems deferred to post-Phase 7 for focused delivery The rendering foundation is now solid and ready for Phase 7: Documentation & Distribution. Author: John McCardle <mccardle.john@gmail.com> feat(viewport): complete viewport-based rendering system (#8) Implements a comprehensive viewport system that allows fixed game resolution with flexible window scaling, addressing the primary wishes for issues #34, #49, and #8. Key Features: - Fixed game resolution independent of window size (window.game_resolution property) - Three scaling modes accessible via window.scaling_mode: - "center": 1:1 pixels, viewport centered in window - "stretch": viewport fills window, ignores aspect ratio - "fit": maintains aspect ratio with black bars - Automatic window-to-game coordinate transformation for mouse input - Full Python API integration with PyWindow properties Technical Implementation: - GameEngine::ViewportMode enum with Center, Stretch, Fit modes - SFML View system for efficient GPU-based viewport scaling - updateViewport() recalculates on window resize or mode change - windowToGameCoords() transforms mouse coordinates correctly - PyScene mouse input automatically uses transformed coordinates Tests: - test_viewport_simple.py: Basic API functionality - test_viewport_visual.py: Visual verification with screenshots - test_viewport_scaling.py: Interactive mode switching and resizing This completes the viewport-based rendering task and provides the foundation for resolution-independent game development as requested for Crypt of Sokoban. Author: John McCardle <mccardle.john@gmail.com> docs: update ROADMAP for Phase 6 progress - Marked Phase 6 as IN PROGRESS - Updated RenderTexture overhaul (#6) as PARTIALLY COMPLETE - Marked Grid background colors (#50) as COMPLETED - Added technical notes from implementation experience - Identified viewport rendering (#8) as next priority Author: John McCardle <mccardle.john@gmail.com> feat(rendering): implement RenderTexture base infrastructure and UIFrame clipping (#6) - Added RenderTexture support to UIDrawable base class - std::unique_ptr<sf::RenderTexture> for opt-in rendering - Dirty flag system for optimization - enableRenderTexture() and markDirty() methods - Implemented clip_children property for UIFrame - Python-accessible boolean property - Automatic RenderTexture creation when enabled - Proper coordinate transformation for nested frames - Updated UIFrame::render() for clipping support - Renders to RenderTexture when clip_children=true - Handles nested clipping correctly - Only re-renders when dirty flag is set - Added comprehensive dirty flag propagation - All property setters mark frame as dirty - Size changes recreate RenderTexture - Animation system integration - Created tests for clipping functionality - Basic clipping test with visual verification - Advanced nested clipping test - Dynamic resize handling test This is Phase 1 of the RenderTexture overhaul, providing the foundation for advanced rendering effects like blur, glow, and viewport rendering. Author: John McCardle <mccardle.john@gmail.com> docs: create RenderTexture overhaul design document - Comprehensive design for Issue #6 implementation - Opt-in architecture to maintain backward compatibility - Phased implementation plan with clear milestones - Performance considerations and risk mitigation - API design for clipping and future effects Also includes Grid background color test Author: John McCardle <mccardle.john@gmail.com> feat(Grid): add customizable background_color property (#50) - Added sf::Color background_color member with default dark gray - Python property getter/setter for background_color - Animation support for individual color components (r/g/b/a) - Replaces hardcoded clear color in render method - Test demonstrates color changes and property access Closes #50 Author: John McCardle <mccardle.john@gmail.com> docs: update roadmap for Phase 6 preparation - Mark Phase 5 (Window/Scene Architecture) as complete - Update issue statuses (#34, #61, #1, #105 completed) - Add Phase 6 implementation strategy for RenderTexture overhaul - Archive Phase 5 test files to .archive/ - Identify quick wins and technical approach for rendering work Author: John McCardle <mccardle.john@gmail.com> feat(Phase 5): Complete Window/Scene Architecture - Window singleton with properties (resolution, fullscreen, vsync, title) - OOP Scene support with lifecycle methods (on_enter, on_exit, on_keypress, update) - Window resize events trigger scene.on_resize callbacks - Scene transitions (fade, slide_left/right/up/down) with smooth animations - Full integration of Python Scene objects with C++ engine All Phase 5 tasks (#34, #1, #61, #105) completed successfully. Author: John McCardle <mccardle.john@gmail.com> research: SFML 3.0 migration analysis - Analyzed SFML 3.0 breaking changes (event system, scoped enums, C++17) - Assessed migration impact on McRogueFace (40+ files affected) - Evaluated timing relative to mcrfpy.sfml module plans - Recommended deferring migration until after mcrfpy.sfml implementation - Created SFML_3_MIGRATION_RESEARCH.md with comprehensive strategy Author: John McCardle <mccardle.john@gmail.com> research: SFML exposure options analysis (#14) - Analyzed current SFML 2.6.1 usage throughout codebase - Evaluated python-sfml (abandoned, only supports SFML 2.3.2) - Recommended direct integration as mcrfpy.sfml module - Created comprehensive SFML_EXPOSURE_RESEARCH.md with implementation plan - Identified opportunity to provide modern SFML 2.6+ Python bindings Author: John McCardle <mccardle.john@gmail.com> feat: add basic profiling/metrics system (#104) - Add ProfilingMetrics struct to track performance data - Track frame time (current and 60-frame rolling average) - Calculate FPS from average frame time - Count draw calls, UI elements, and visible elements per frame - Track total runtime and current frame number - PyScene counts elements during render - Expose metrics via mcrfpy.getMetrics() returning dict This provides basic performance monitoring capabilities for identifying bottlenecks and optimizing rendering performance. Author: John McCardle <mccardle.john@gmail.com> fix: improve click handling with proper z-order and coordinate transforms - UIFrame: Fix coordinate transformation (subtract parent pos, not add) - UIFrame: Check children in reverse order (highest z-index first) - UIFrame: Skip invisible elements entirely - PyScene: Sort elements by z-index before checking clicks - PyScene: Stop at first element that handles the click - UIGrid: Implement entity click detection with grid coordinate transform - UIGrid: Check entities in reverse order, return sprite as target Click events now correctly respect z-order (top elements get priority), handle coordinate transforms for nested frames, and support clicking on grid entities. Elements without click handlers are transparent to clicks, allowing elements below to receive them. Note: Click testing requires non-headless mode due to PyScene limitation. feat: implement name system for finding UI elements (#39/40/41) - Add 'name' property to UIDrawable base class - All UI elements (Frame, Caption, Sprite, Grid, Entity) support .name - Entity delegates name to its sprite member - Add find(name, scene=None) function for exact match search - Add findAll(pattern, scene=None) with wildcard support (* matches any sequence) - Both functions search recursively through Frame children and Grid entities - Comprehensive test coverage for all functionality This provides a simple way to find UI elements by name in Python scripts, supporting both exact matches and wildcard patterns. Author: John McCardle <mccardle.john@gmail.com> fix: prevent segfault when closing window via X button - Add cleanup() method to GameEngine to clear Python references before destruction - Clear timers and McRFPy_API references in proper order - Call cleanup() at end of run loop and in destructor - Ensure cleanup is only called once per GameEngine instance Also includes: - Fix audio ::stop() calls (already in place, OpenAL warning is benign) - Add Caption support for x, y keywords (e.g. Caption("text", x=5, y=10)) - Refactor UIDrawable_methods.h into UIBase.h for better organization - Move UIEntity-specific implementations to UIEntityPyMethods.h Author: John McCardle <mccardle.john@gmail.com> feat: stabilize test suite and add UIDrawable methods - Add visible, opacity properties to all UI classes (#87, #88) - Add get_bounds(), move(), resize() methods to UIDrawable (#89, #98) - Create UIDrawable_methods.h with template implementations - Fix test termination issues - all tests now exit properly - Fix test_sprite_texture_swap.py click handler signature - Fix test_drawable_base.py segfault in headless mode - Convert audio objects to pointers for cleanup (OpenAL warning persists) - Remove debug print statements from UICaption - Special handling for UIEntity to delegate drawable methods to sprite All test files are now "airtight" - they complete successfully, terminate on their own, and handle edge cases properly. Author: John McCardle <mccardle.john@gmail.com> docs: add Phase 1-3 completion summary - Document all completed tasks across three phases - Show before/after API improvements - Highlight technical achievements - Outline next steps for Phase 4-7 Author: John McCardle <mccardle.john@gmail.com> feat: implement mcrfpy.Timer object with pause/resume/cancel capabilities closes #103 - Created PyTimer.h/cpp with object-oriented timer interface - Enhanced PyTimerCallable with pause/resume state tracking - Added timer control methods: pause(), resume(), cancel(), restart() - Added timer properties: interval, remaining, paused, active, callback - Fixed timing logic to prevent rapid catch-up after resume - Timer objects automatically register with game engine - Added comprehensive test demonstrating all functionality Author: John McCardle <mccardle.john@gmail.com> feat(Color): add helper methods from_hex, to_hex, lerp closes #94 - Add Color.from_hex(hex_string) class method for creating colors from hex - Support formats: #RRGGBB, RRGGBB, #RRGGBBAA, RRGGBBAA - Add color.to_hex() to convert Color to hex string - Add color.lerp(other, t) for smooth color interpolation - Comprehensive test coverage for all methods Author: John McCardle <mccardle.john@gmail.com> fix: properly configure UTF-8 encoding for Python stdio - Use PyConfig to set stdio_encoding="UTF-8" during initialization - Set stdio_errors="surrogateescape" for robust handling - Configure in both init_python() and init_python_with_config() - Cleaner solution than wrapping streams after initialization - Fixes UnicodeEncodeError when printing unicode characters Author: John McCardle <mccardle.john@gmail.com> feat(Vector): implement arithmetic operations closes #93 - Add PyNumberMethods with add, subtract, multiply, divide, negate, absolute - Add rich comparison for equality/inequality checks - Add boolean check (zero vector is False) - Implement vector methods: magnitude(), normalize(), dot(), distance_to(), angle(), copy() - Fix UIDrawable::get_click() segfault when click_callable is null - Comprehensive test coverage for all arithmetic operations Author: John McCardle <mccardle.john@gmail.com> feat: Complete position argument standardization for all UI classes - Frame and Sprite now support pos keyword override - Entity now accepts x,y arguments (was pos-only before) - All UI classes now consistently support: - (x, y) positional - ((x, y)) tuple - x=x, y=y keywords - pos=(x,y) keyword - pos=Vector keyword - Improves API consistency and flexibility Author: John McCardle <mccardle.john@gmail.com> feat: Standardize position arguments across all UI classes - Create PyPositionHelper for consistent position parsing - Grid.at() now accepts (x,y), ((x,y)), x=x, y=y, pos=(x,y) - Caption now accepts x,y args in addition to pos - Grid init fully supports keyword arguments - Maintain backward compatibility for all formats - Consistent error messages across classes Author: John McCardle <mccardle.john@gmail.com> feat: Add Entity.die() method for lifecycle management closes #30 - Remove entity from its grid's entity list - Clear grid reference after removal - Safe to call multiple times (no-op if not on grid) - Works with shared_ptr entity management Author: John McCardle <mccardle.john@gmail.com> perf: Skip out-of-bounds entities during Grid rendering closes #52 - Add visibility bounds check in entity render loop - Skip entities outside view with 1 cell margin - Improves performance for large grids with many entities - Bounds check considers zoom and pan settings Author: John McCardle <mccardle.john@gmail.com> verify: Sprite texture swapping functionality closes #19 - Texture property getter/setter already implemented - Position/scale preservation during swap confirmed - Type validation for texture assignment working - Tests verify functionality is complete Author: John McCardle <mccardle.john@gmail.com> feat: Grid size tuple support closes #90 - Add grid_size keyword parameter to Grid.__init__ - Accept tuple or list of two integers - Override grid_x/grid_y if grid_size provided - Maintain backward compatibility - Add comprehensive test coverage Author: John McCardle <mccardle.john@gmail.com> feat: Phase 1 - safe constructors and _Drawable foundation Closes #7 - Make all UI class constructors safe: - Added safe default constructors for UISprite, UIGrid, UIEntity, UICaption - Initialize all members to predictable values - Made Python init functions accept no arguments - Added x,y properties to UIEntity Closes #71 - Create _Drawable Python base class: - Created PyDrawable.h/cpp with base type (not yet inherited by UI types) - Registered in module initialization Closes #87 - Add visible property: - Added bool visible=true to UIDrawable base class - All render methods check visibility before drawing Closes #88 - Add opacity property: - Added float opacity=1.0 to UIDrawable base class - UICaption and UISprite apply opacity to alpha channel Closes #89 - Add get_bounds() method: - Virtual method returns sf::FloatRect(x,y,w,h) - Implemented in Frame, Caption, Sprite, Grid Closes #98 - Add move() and resize() methods: - move(dx,dy) for relative movement - resize(w,h) for absolute sizing - Caption resize is no-op (size controlled by font) Author: John McCardle <mccardle.john@gmail.com> docs: comprehensive alpha_streamline_2 plan and strategic vision - Add 7-phase development plan for alpha_streamline_2 branch - Define architectural dependencies and critical path - Identify new issues needed (Timer objects, event system, etc.) - Add strategic vision document with 3 transformative directions - Timeline: 10-12 weeks to solid Beta foundation Author: John McCardle <mccardle.john@gmail.com> feat(Grid): flexible at() method arguments - Support tuple argument: grid.at((x, y)) - Support keyword arguments: grid.at(x=5, y=3) - Support pos keyword: grid.at(pos=(2, 8)) - Maintain backward compatibility with grid.at(x, y) - Add comprehensive error handling for invalid arguments Improves API ergonomics and Python-like flexibility
2025-07-09 22:41:15 -04:00
.tp_methods = PyTimer::methods,
.tp_getset = PyTimer::getsetters,
.tp_init = (initproc)PyTimer::init,
.tp_new = PyTimer::pynew,
};
}