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 c5e7e8e298
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 6d29652ae7
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 a010e5fa96
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 9c8d6c4591
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 dcd1b0ca33
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 6813fb5129
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 6f67fbb51e
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 eb88c7b3aa
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 9fb428dd01
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 062e4dadc4
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 98fc49a978
Directory structure cleanup and organization overhaul
344 lines
No EOL
14 KiB
Python
344 lines
No EOL
14 KiB
Python
# Comprehensive UI Element Method Documentation
|
|
# This can be inserted into generate_api_docs_html.py in the method_docs dictionary
|
|
|
|
ui_method_docs = {
|
|
# Base Drawable methods (inherited by all UI elements)
|
|
'Drawable': {
|
|
'get_bounds': {
|
|
'signature': 'get_bounds()',
|
|
'description': 'Get the bounding rectangle of this drawable element.',
|
|
'returns': 'tuple: (x, y, width, height) representing the element\'s bounds',
|
|
'note': 'The bounds are in screen coordinates and account for current position and size.'
|
|
},
|
|
'move': {
|
|
'signature': 'move(dx, dy)',
|
|
'description': 'Move the element by a relative offset.',
|
|
'args': [
|
|
('dx', 'float', 'Horizontal offset in pixels'),
|
|
('dy', 'float', 'Vertical offset in pixels')
|
|
],
|
|
'note': 'This modifies the x and y position properties by the given amounts.'
|
|
},
|
|
'resize': {
|
|
'signature': 'resize(width, height)',
|
|
'description': 'Resize the element to new dimensions.',
|
|
'args': [
|
|
('width', 'float', 'New width in pixels'),
|
|
('height', 'float', 'New height in pixels')
|
|
],
|
|
'note': 'Behavior varies by element type. Some elements may ignore or constrain dimensions.'
|
|
}
|
|
},
|
|
|
|
# Caption-specific methods
|
|
'Caption': {
|
|
'get_bounds': {
|
|
'signature': 'get_bounds()',
|
|
'description': 'Get the bounding rectangle of the text.',
|
|
'returns': 'tuple: (x, y, width, height) based on text content and font size',
|
|
'note': 'Bounds are automatically calculated from the rendered text dimensions.'
|
|
},
|
|
'move': {
|
|
'signature': 'move(dx, dy)',
|
|
'description': 'Move the caption by a relative offset.',
|
|
'args': [
|
|
('dx', 'float', 'Horizontal offset in pixels'),
|
|
('dy', 'float', 'Vertical offset in pixels')
|
|
]
|
|
},
|
|
'resize': {
|
|
'signature': 'resize(width, height)',
|
|
'description': 'Set text wrapping bounds (limited support).',
|
|
'args': [
|
|
('width', 'float', 'Maximum width for text wrapping'),
|
|
('height', 'float', 'Currently unused')
|
|
],
|
|
'note': 'Full text wrapping is not yet implemented. This prepares for future multiline support.'
|
|
}
|
|
},
|
|
|
|
# Entity-specific methods
|
|
'Entity': {
|
|
'at': {
|
|
'signature': 'at(x, y)',
|
|
'description': 'Get the GridPointState at the specified grid coordinates relative to this entity.',
|
|
'args': [
|
|
('x', 'int', 'Grid x offset from entity position'),
|
|
('y', 'int', 'Grid y offset from entity position')
|
|
],
|
|
'returns': 'GridPointState: State of the grid point at the specified position',
|
|
'note': 'Requires entity to be associated with a grid. Raises ValueError if not.'
|
|
},
|
|
'die': {
|
|
'signature': 'die()',
|
|
'description': 'Remove this entity from its parent grid.',
|
|
'returns': 'None',
|
|
'note': 'The entity object remains valid but is no longer rendered or updated.'
|
|
},
|
|
'index': {
|
|
'signature': 'index()',
|
|
'description': 'Get the index of this entity in its grid\'s entity collection.',
|
|
'returns': 'int: Zero-based index in the parent grid\'s entity list',
|
|
'note': 'Raises RuntimeError if not associated with a grid, ValueError if not found.'
|
|
},
|
|
'get_bounds': {
|
|
'signature': 'get_bounds()',
|
|
'description': 'Get the bounding rectangle of the entity\'s sprite.',
|
|
'returns': 'tuple: (x, y, width, height) of the sprite bounds',
|
|
'note': 'Delegates to the internal sprite\'s get_bounds method.'
|
|
},
|
|
'move': {
|
|
'signature': 'move(dx, dy)',
|
|
'description': 'Move the entity by a relative offset in pixels.',
|
|
'args': [
|
|
('dx', 'float', 'Horizontal offset in pixels'),
|
|
('dy', 'float', 'Vertical offset in pixels')
|
|
],
|
|
'note': 'Updates both sprite position and entity grid position.'
|
|
},
|
|
'resize': {
|
|
'signature': 'resize(width, height)',
|
|
'description': 'Entities do not support direct resizing.',
|
|
'args': [
|
|
('width', 'float', 'Ignored'),
|
|
('height', 'float', 'Ignored')
|
|
],
|
|
'note': 'This method exists for interface compatibility but has no effect.'
|
|
}
|
|
},
|
|
|
|
# Frame-specific methods
|
|
'Frame': {
|
|
'get_bounds': {
|
|
'signature': 'get_bounds()',
|
|
'description': 'Get the bounding rectangle of the frame.',
|
|
'returns': 'tuple: (x, y, width, height) representing the frame bounds'
|
|
},
|
|
'move': {
|
|
'signature': 'move(dx, dy)',
|
|
'description': 'Move the frame and all its children by a relative offset.',
|
|
'args': [
|
|
('dx', 'float', 'Horizontal offset in pixels'),
|
|
('dy', 'float', 'Vertical offset in pixels')
|
|
],
|
|
'note': 'Child elements maintain their relative positions within the frame.'
|
|
},
|
|
'resize': {
|
|
'signature': 'resize(width, height)',
|
|
'description': 'Resize the frame to new dimensions.',
|
|
'args': [
|
|
('width', 'float', 'New width in pixels'),
|
|
('height', 'float', 'New height in pixels')
|
|
],
|
|
'note': 'Does not automatically resize children. Set clip_children=True to clip overflow.'
|
|
}
|
|
},
|
|
|
|
# Grid-specific methods
|
|
'Grid': {
|
|
'at': {
|
|
'signature': 'at(x, y) or at((x, y))',
|
|
'description': 'Get the GridPoint at the specified grid coordinates.',
|
|
'args': [
|
|
('x', 'int', 'Grid x coordinate (0-based)'),
|
|
('y', 'int', 'Grid y coordinate (0-based)')
|
|
],
|
|
'returns': 'GridPoint: The grid point at (x, y)',
|
|
'note': 'Raises IndexError if coordinates are out of range. Accepts either two arguments or a tuple.',
|
|
'example': 'point = grid.at(5, 3) # or grid.at((5, 3))'
|
|
},
|
|
'get_bounds': {
|
|
'signature': 'get_bounds()',
|
|
'description': 'Get the bounding rectangle of the entire grid.',
|
|
'returns': 'tuple: (x, y, width, height) of the grid\'s display area'
|
|
},
|
|
'move': {
|
|
'signature': 'move(dx, dy)',
|
|
'description': 'Move the grid display by a relative offset.',
|
|
'args': [
|
|
('dx', 'float', 'Horizontal offset in pixels'),
|
|
('dy', 'float', 'Vertical offset in pixels')
|
|
],
|
|
'note': 'Moves the entire grid viewport. Use center property to pan within the grid.'
|
|
},
|
|
'resize': {
|
|
'signature': 'resize(width, height)',
|
|
'description': 'Resize the grid\'s display viewport.',
|
|
'args': [
|
|
('width', 'float', 'New viewport width in pixels'),
|
|
('height', 'float', 'New viewport height in pixels')
|
|
],
|
|
'note': 'Changes the visible area, not the grid dimensions. Use zoom to scale content.'
|
|
}
|
|
},
|
|
|
|
# Sprite-specific methods
|
|
'Sprite': {
|
|
'get_bounds': {
|
|
'signature': 'get_bounds()',
|
|
'description': 'Get the bounding rectangle of the sprite.',
|
|
'returns': 'tuple: (x, y, width, height) based on texture size and scale',
|
|
'note': 'Bounds account for current scale. Returns (x, y, 0, 0) if no texture.'
|
|
},
|
|
'move': {
|
|
'signature': 'move(dx, dy)',
|
|
'description': 'Move the sprite by a relative offset.',
|
|
'args': [
|
|
('dx', 'float', 'Horizontal offset in pixels'),
|
|
('dy', 'float', 'Vertical offset in pixels')
|
|
]
|
|
},
|
|
'resize': {
|
|
'signature': 'resize(width, height)',
|
|
'description': 'Resize the sprite by adjusting its scale.',
|
|
'args': [
|
|
('width', 'float', 'Target width in pixels'),
|
|
('height', 'float', 'Target height in pixels')
|
|
],
|
|
'note': 'Calculates and applies uniform scale to best fit the target dimensions.'
|
|
}
|
|
},
|
|
|
|
# Collection methods (shared by EntityCollection and UICollection)
|
|
'EntityCollection': {
|
|
'append': {
|
|
'signature': 'append(entity)',
|
|
'description': 'Add an entity to the end of the collection.',
|
|
'args': [
|
|
('entity', 'Entity', 'The entity to add')
|
|
]
|
|
},
|
|
'remove': {
|
|
'signature': 'remove(entity)',
|
|
'description': 'Remove the first occurrence of an entity from the collection.',
|
|
'args': [
|
|
('entity', 'Entity', 'The entity to remove')
|
|
],
|
|
'note': 'Raises ValueError if entity is not found.'
|
|
},
|
|
'extend': {
|
|
'signature': 'extend(iterable)',
|
|
'description': 'Add multiple entities from an iterable.',
|
|
'args': [
|
|
('iterable', 'iterable', 'An iterable of Entity objects')
|
|
]
|
|
},
|
|
'count': {
|
|
'signature': 'count(entity)',
|
|
'description': 'Count occurrences of an entity in the collection.',
|
|
'args': [
|
|
('entity', 'Entity', 'The entity to count')
|
|
],
|
|
'returns': 'int: Number of times the entity appears'
|
|
},
|
|
'index': {
|
|
'signature': 'index(entity)',
|
|
'description': 'Find the index of the first occurrence of an entity.',
|
|
'args': [
|
|
('entity', 'Entity', 'The entity to find')
|
|
],
|
|
'returns': 'int: Zero-based index of the entity',
|
|
'note': 'Raises ValueError if entity is not found.'
|
|
}
|
|
},
|
|
|
|
'UICollection': {
|
|
'append': {
|
|
'signature': 'append(drawable)',
|
|
'description': 'Add a drawable element to the end of the collection.',
|
|
'args': [
|
|
('drawable', 'Drawable', 'Any UI element (Frame, Caption, Sprite, Grid)')
|
|
]
|
|
},
|
|
'remove': {
|
|
'signature': 'remove(drawable)',
|
|
'description': 'Remove the first occurrence of a drawable from the collection.',
|
|
'args': [
|
|
('drawable', 'Drawable', 'The drawable to remove')
|
|
],
|
|
'note': 'Raises ValueError if drawable is not found.'
|
|
},
|
|
'extend': {
|
|
'signature': 'extend(iterable)',
|
|
'description': 'Add multiple drawables from an iterable.',
|
|
'args': [
|
|
('iterable', 'iterable', 'An iterable of Drawable objects')
|
|
]
|
|
},
|
|
'count': {
|
|
'signature': 'count(drawable)',
|
|
'description': 'Count occurrences of a drawable in the collection.',
|
|
'args': [
|
|
('drawable', 'Drawable', 'The drawable to count')
|
|
],
|
|
'returns': 'int: Number of times the drawable appears'
|
|
},
|
|
'index': {
|
|
'signature': 'index(drawable)',
|
|
'description': 'Find the index of the first occurrence of a drawable.',
|
|
'args': [
|
|
('drawable', 'Drawable', 'The drawable to find')
|
|
],
|
|
'returns': 'int: Zero-based index of the drawable',
|
|
'note': 'Raises ValueError if drawable is not found.'
|
|
}
|
|
}
|
|
}
|
|
|
|
# Additional property documentation to complement the methods
|
|
ui_property_docs = {
|
|
'Drawable': {
|
|
'visible': 'bool: Whether this element is rendered (default: True)',
|
|
'opacity': 'float: Transparency level from 0.0 (invisible) to 1.0 (opaque)',
|
|
'z_index': 'int: Rendering order, higher values appear on top',
|
|
'name': 'str: Optional name for finding elements',
|
|
'x': 'float: Horizontal position in pixels',
|
|
'y': 'float: Vertical position in pixels',
|
|
'click': 'callable: Click event handler function'
|
|
},
|
|
'Caption': {
|
|
'text': 'str: The displayed text content',
|
|
'font': 'Font: Font used for rendering',
|
|
'fill_color': 'Color: Text color',
|
|
'outline_color': 'Color: Text outline color',
|
|
'outline': 'float: Outline thickness in pixels',
|
|
'w': 'float: Read-only computed width based on text',
|
|
'h': 'float: Read-only computed height based on text'
|
|
},
|
|
'Entity': {
|
|
'grid_x': 'float: X position in grid coordinates',
|
|
'grid_y': 'float: Y position in grid coordinates',
|
|
'sprite_index': 'int: Index of sprite in texture atlas',
|
|
'texture': 'Texture: Texture used for rendering',
|
|
'gridstate': 'list: Read-only list of GridPointState objects'
|
|
},
|
|
'Frame': {
|
|
'w': 'float: Width in pixels',
|
|
'h': 'float: Height in pixels',
|
|
'fill_color': 'Color: Background fill color',
|
|
'outline_color': 'Color: Border color',
|
|
'outline': 'float: Border thickness in pixels',
|
|
'children': 'UICollection: Child drawable elements',
|
|
'clip_children': 'bool: Whether to clip children to frame bounds'
|
|
},
|
|
'Grid': {
|
|
'grid_size': 'tuple: Read-only (width, height) in tiles',
|
|
'grid_x': 'int: Read-only width in tiles',
|
|
'grid_y': 'int: Read-only height in tiles',
|
|
'tile_width': 'int: Width of each tile in pixels',
|
|
'tile_height': 'int: Height of each tile in pixels',
|
|
'center': 'tuple: (x, y) center point for viewport',
|
|
'zoom': 'float: Scale factor for rendering',
|
|
'texture': 'Texture: Tile texture atlas',
|
|
'background_color': 'Color: Grid background color',
|
|
'entities': 'EntityCollection: Entities in this grid',
|
|
'points': 'list: 2D array of GridPoint objects'
|
|
},
|
|
'Sprite': {
|
|
'texture': 'Texture: The displayed texture',
|
|
'sprite_index': 'int: Index in texture atlas',
|
|
'scale': 'float: Scaling factor',
|
|
'w': 'float: Read-only computed width (texture width * scale)',
|
|
'h': 'float: Read-only computed height (texture height * scale)'
|
|
}
|
|
} |