feat: Implement FOV enum and layer draw_fov for #114 and #113

Phase 1 - FOV Enum System:
- Create PyFOV.h/cpp with mcrfpy.FOV IntEnum (BASIC, DIAMOND, SHADOW, etc.)
- Add mcrfpy.default_fov module property initialized to FOV.BASIC
- Add grid.fov and grid.fov_radius properties for per-grid defaults
- Remove deprecated module-level FOV_* constants (breaking change)

Phase 2 - Layer Operations:
- Implement ColorLayer.fill_rect(pos, size, color) for rectangle fills
- Implement TileLayer.fill_rect(pos, size, index) for tile rectangle fills
- Implement ColorLayer.draw_fov(source, radius, fov, visible, discovered, unknown)
  to paint FOV-based visibility on color layers using parent grid's TCOD map

The FOV enum uses Python's IntEnum for type safety while maintaining
backward compatibility with integer values. Tests updated to use new API.

Addresses #114 (FOV enum), #113 (layer operations)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
John McCardle 2025-12-01 15:18:10 -05:00
commit 018e73590f
11 changed files with 1061 additions and 407 deletions

View file

@ -2,6 +2,7 @@
#include "UIGrid.h"
#include "PyColor.h"
#include "PyTexture.h"
#include "PyFOV.h"
#include <sstream>
// =============================================================================
@ -11,47 +12,96 @@
GridLayer::GridLayer(GridLayerType type, int z_index, int grid_x, int grid_y, UIGrid* parent)
: type(type), z_index(z_index), grid_x(grid_x), grid_y(grid_y),
parent_grid(parent), visible(true),
dirty(true), texture_initialized(false),
chunks_x(0), chunks_y(0),
cached_cell_width(0), cached_cell_height(0)
{}
void GridLayer::markDirty() {
dirty = true;
{
initChunks();
}
void GridLayer::ensureTextureSize(int cell_width, int cell_height) {
// Check if we need to resize/create the texture
unsigned int required_width = grid_x * cell_width;
unsigned int required_height = grid_y * cell_height;
void GridLayer::initChunks() {
// Calculate chunk dimensions
chunks_x = (grid_x + CHUNK_SIZE - 1) / CHUNK_SIZE;
chunks_y = (grid_y + CHUNK_SIZE - 1) / CHUNK_SIZE;
int total_chunks = chunks_x * chunks_y;
// Maximum texture size limit (prevent excessive memory usage)
const unsigned int MAX_TEXTURE_SIZE = 4096;
if (required_width > MAX_TEXTURE_SIZE) required_width = MAX_TEXTURE_SIZE;
if (required_height > MAX_TEXTURE_SIZE) required_height = MAX_TEXTURE_SIZE;
// Initialize per-chunk tracking
chunk_dirty.assign(total_chunks, true); // All chunks start dirty
chunk_texture_initialized.assign(total_chunks, false);
chunk_textures.clear();
chunk_textures.reserve(total_chunks);
for (int i = 0; i < total_chunks; ++i) {
chunk_textures.push_back(std::make_unique<sf::RenderTexture>());
}
}
// Skip if already properly sized
if (texture_initialized &&
cached_texture.getSize().x == required_width &&
cached_texture.getSize().y == required_height &&
void GridLayer::markDirty() {
// Mark ALL chunks as dirty
std::fill(chunk_dirty.begin(), chunk_dirty.end(), true);
}
void GridLayer::markDirty(int cell_x, int cell_y) {
// Mark only the specific chunk containing this cell
if (cell_x < 0 || cell_x >= grid_x || cell_y < 0 || cell_y >= grid_y) return;
int chunk_idx = getChunkIndex(cell_x, cell_y);
if (chunk_idx >= 0 && chunk_idx < static_cast<int>(chunk_dirty.size())) {
chunk_dirty[chunk_idx] = true;
}
}
int GridLayer::getChunkIndex(int cell_x, int cell_y) const {
int cx = cell_x / CHUNK_SIZE;
int cy = cell_y / CHUNK_SIZE;
return cy * chunks_x + cx;
}
void GridLayer::getChunkCoords(int cell_x, int cell_y, int& chunk_x, int& chunk_y) const {
chunk_x = cell_x / CHUNK_SIZE;
chunk_y = cell_y / CHUNK_SIZE;
}
void GridLayer::getChunkBounds(int chunk_x, int chunk_y, int& start_x, int& start_y, int& end_x, int& end_y) const {
start_x = chunk_x * CHUNK_SIZE;
start_y = chunk_y * CHUNK_SIZE;
end_x = std::min(start_x + CHUNK_SIZE, grid_x);
end_y = std::min(start_y + CHUNK_SIZE, grid_y);
}
void GridLayer::ensureChunkTexture(int chunk_idx, int cell_width, int cell_height) {
if (chunk_idx < 0 || chunk_idx >= static_cast<int>(chunk_textures.size())) return;
if (!chunk_textures[chunk_idx]) return;
// Calculate chunk dimensions in cells
int cx = chunk_idx % chunks_x;
int cy = chunk_idx / chunks_x;
int start_x, start_y, end_x, end_y;
getChunkBounds(cx, cy, start_x, start_y, end_x, end_y);
int chunk_width_cells = end_x - start_x;
int chunk_height_cells = end_y - start_y;
unsigned int required_width = chunk_width_cells * cell_width;
unsigned int required_height = chunk_height_cells * cell_height;
// Check if texture needs (re)creation
if (chunk_texture_initialized[chunk_idx] &&
chunk_textures[chunk_idx]->getSize().x == required_width &&
chunk_textures[chunk_idx]->getSize().y == required_height &&
cached_cell_width == cell_width &&
cached_cell_height == cell_height) {
return; // Already properly sized
}
// Create the texture for this chunk
if (!chunk_textures[chunk_idx]->create(required_width, required_height)) {
chunk_texture_initialized[chunk_idx] = false;
return;
}
// Create or resize the texture (SFML uses .create() not .resize())
if (!cached_texture.create(required_width, required_height)) {
// Creation failed - texture will remain uninitialized
texture_initialized = false;
return;
}
chunk_texture_initialized[chunk_idx] = true;
chunk_dirty[chunk_idx] = true; // Force re-render after resize
cached_cell_width = cell_width;
cached_cell_height = cell_height;
texture_initialized = true;
dirty = true; // Force re-render after resize
// Setup the sprite to use the texture
cached_sprite.setTexture(cached_texture.getTexture());
}
// =============================================================================
@ -73,7 +123,76 @@ const sf::Color& ColorLayer::at(int x, int y) const {
void ColorLayer::fill(const sf::Color& color) {
std::fill(colors.begin(), colors.end(), color);
markDirty(); // #148 - Mark for re-render
markDirty(); // Mark ALL chunks for re-render
}
void ColorLayer::fillRect(int x, int y, int width, int height, const sf::Color& color) {
// Clamp to valid bounds
int x1 = std::max(0, x);
int y1 = std::max(0, y);
int x2 = std::min(grid_x, x + width);
int y2 = std::min(grid_y, y + height);
// Fill the rectangle
for (int fy = y1; fy < y2; ++fy) {
for (int fx = x1; fx < x2; ++fx) {
colors[fy * grid_x + fx] = color;
}
}
// Mark affected chunks dirty
int chunk_x1 = x1 / CHUNK_SIZE;
int chunk_y1 = y1 / CHUNK_SIZE;
int chunk_x2 = (x2 - 1) / CHUNK_SIZE;
int chunk_y2 = (y2 - 1) / CHUNK_SIZE;
for (int cy = chunk_y1; cy <= chunk_y2; ++cy) {
for (int cx = chunk_x1; cx <= chunk_x2; ++cx) {
int idx = cy * chunks_x + cx;
if (idx >= 0 && idx < static_cast<int>(chunk_dirty.size())) {
chunk_dirty[idx] = true;
}
}
}
}
void ColorLayer::drawFOV(int source_x, int source_y, int radius,
TCOD_fov_algorithm_t algorithm,
const sf::Color& visible_color,
const sf::Color& discovered_color,
const sf::Color& unknown_color) {
// Need parent grid for TCOD map access
if (!parent_grid) {
return; // Cannot compute FOV without parent grid
}
// Import UIGrid here to avoid circular dependency in header
// parent_grid is already a UIGrid*, we can use its tcod_map directly
// But we need to forward declare access to it...
// Compute FOV on the parent grid
parent_grid->computeFOV(source_x, source_y, radius, true, algorithm);
// Paint cells based on visibility
for (int cy = 0; cy < grid_y; ++cy) {
for (int cx = 0; cx < grid_x; ++cx) {
// Check if in FOV (visible right now)
if (parent_grid->isInFOV(cx, cy)) {
colors[cy * grid_x + cx] = visible_color;
}
// Check if previously discovered (current color != unknown)
else if (colors[cy * grid_x + cx] != unknown_color) {
colors[cy * grid_x + cx] = discovered_color;
}
// Otherwise leave as unknown (or set to unknown if first time)
else {
colors[cy * grid_x + cx] = unknown_color;
}
}
}
// Mark entire layer dirty
markDirty();
}
void ColorLayer::resize(int new_grid_x, int new_grid_y) {
@ -92,36 +211,53 @@ void ColorLayer::resize(int new_grid_x, int new_grid_y) {
grid_x = new_grid_x;
grid_y = new_grid_y;
// #148 - Invalidate cached texture (will be resized on next render)
texture_initialized = false;
markDirty();
// Reinitialize chunks for new dimensions
initChunks();
}
// #148 - Render all cells to cached texture (called when dirty)
void ColorLayer::renderToTexture(int cell_width, int cell_height) {
ensureTextureSize(cell_width, cell_height);
if (!texture_initialized) return;
// Render a single chunk to its cached texture
void ColorLayer::renderChunkToTexture(int chunk_x, int chunk_y, int cell_width, int cell_height) {
int chunk_idx = chunk_y * chunks_x + chunk_x;
if (chunk_idx < 0 || chunk_idx >= static_cast<int>(chunk_textures.size())) return;
if (!chunk_textures[chunk_idx]) return;
cached_texture.clear(sf::Color::Transparent);
ensureChunkTexture(chunk_idx, cell_width, cell_height);
if (!chunk_texture_initialized[chunk_idx]) return;
// Get chunk bounds
int start_x, start_y, end_x, end_y;
getChunkBounds(chunk_x, chunk_y, start_x, start_y, end_x, end_y);
chunk_textures[chunk_idx]->clear(sf::Color::Transparent);
sf::RectangleShape rect;
rect.setSize(sf::Vector2f(cell_width, cell_height));
rect.setOutlineThickness(0);
// Render all cells to cached texture (no zoom - 1:1 pixel mapping)
for (int x = 0; x < grid_x; ++x) {
for (int y = 0; y < grid_y; ++y) {
// Render only cells within this chunk (local coordinates in texture)
for (int x = start_x; x < end_x; ++x) {
for (int y = start_y; y < end_y; ++y) {
const sf::Color& color = at(x, y);
if (color.a == 0) continue; // Skip fully transparent
rect.setPosition(sf::Vector2f(x * cell_width, y * cell_height));
// Position relative to chunk origin
rect.setPosition(sf::Vector2f((x - start_x) * cell_width, (y - start_y) * cell_height));
rect.setFillColor(color);
cached_texture.draw(rect);
chunk_textures[chunk_idx]->draw(rect);
}
}
cached_texture.display();
dirty = false;
chunk_textures[chunk_idx]->display();
chunk_dirty[chunk_idx] = false;
}
// Legacy: render all chunks (used by fill, resize, etc.)
void ColorLayer::renderToTexture(int cell_width, int cell_height) {
for (int cy = 0; cy < chunks_y; ++cy) {
for (int cx = 0; cx < chunks_x; ++cx) {
renderChunkToTexture(cx, cy, cell_width, cell_height);
}
}
}
void ColorLayer::render(sf::RenderTarget& target,
@ -130,61 +266,67 @@ void ColorLayer::render(sf::RenderTarget& target,
float zoom, int cell_width, int cell_height) {
if (!visible) return;
// #148 - Use cached texture rendering
// Re-render to texture only if dirty
if (dirty || !texture_initialized) {
renderToTexture(cell_width, cell_height);
}
// Calculate visible chunk range
int chunk_left = std::max(0, left_edge / CHUNK_SIZE);
int chunk_top = std::max(0, top_edge / CHUNK_SIZE);
int chunk_right = std::min(chunks_x - 1, (x_limit + CHUNK_SIZE - 1) / CHUNK_SIZE);
int chunk_bottom = std::min(chunks_y - 1, (y_limit + CHUNK_SIZE - 1) / CHUNK_SIZE);
if (!texture_initialized) {
// Fallback to direct rendering if texture creation failed
sf::RectangleShape rect;
rect.setSize(sf::Vector2f(cell_width * zoom, cell_height * zoom));
rect.setOutlineThickness(0);
// Iterate only over visible chunks
for (int cy = chunk_top; cy <= chunk_bottom; ++cy) {
for (int cx = chunk_left; cx <= chunk_right; ++cx) {
int chunk_idx = cy * chunks_x + cx;
for (int x = (left_edge - 1 >= 0 ? left_edge - 1 : 0); x < x_limit; ++x) {
for (int y = (top_edge - 1 >= 0 ? top_edge - 1 : 0); y < y_limit; ++y) {
if (x < 0 || x >= grid_x || y < 0 || y >= grid_y) continue;
const sf::Color& color = at(x, y);
if (color.a == 0) continue;
auto pixel_pos = sf::Vector2f(
(x * cell_width - left_spritepixels) * zoom,
(y * cell_height - top_spritepixels) * zoom
);
rect.setPosition(pixel_pos);
rect.setFillColor(color);
target.draw(rect);
// Re-render chunk only if dirty AND visible
if (chunk_dirty[chunk_idx] || !chunk_texture_initialized[chunk_idx]) {
renderChunkToTexture(cx, cy, cell_width, cell_height);
}
if (!chunk_texture_initialized[chunk_idx]) {
// Fallback: direct rendering for this chunk
int start_x, start_y, end_x, end_y;
getChunkBounds(cx, cy, start_x, start_y, end_x, end_y);
sf::RectangleShape rect;
rect.setSize(sf::Vector2f(cell_width * zoom, cell_height * zoom));
rect.setOutlineThickness(0);
for (int x = start_x; x < end_x; ++x) {
for (int y = start_y; y < end_y; ++y) {
const sf::Color& color = at(x, y);
if (color.a == 0) continue;
auto pixel_pos = sf::Vector2f(
(x * cell_width - left_spritepixels) * zoom,
(y * cell_height - top_spritepixels) * zoom
);
rect.setPosition(pixel_pos);
rect.setFillColor(color);
target.draw(rect);
}
}
continue;
}
// Blit this chunk's texture to target
int start_x, start_y, end_x, end_y;
getChunkBounds(cx, cy, start_x, start_y, end_x, end_y);
// Chunk position in world pixel coordinates
float chunk_world_x = start_x * cell_width;
float chunk_world_y = start_y * cell_height;
// Position in target (accounting for viewport offset and zoom)
float dest_x = (chunk_world_x - left_spritepixels) * zoom;
float dest_y = (chunk_world_y - top_spritepixels) * zoom;
sf::Sprite chunk_sprite(chunk_textures[chunk_idx]->getTexture());
chunk_sprite.setPosition(sf::Vector2f(dest_x, dest_y));
chunk_sprite.setScale(sf::Vector2f(zoom, zoom));
target.draw(chunk_sprite);
}
return;
}
// Blit visible portion of cached texture with zoom applied
// Calculate source rectangle (unzoomed pixel coordinates in cached texture)
int src_left = std::max(0, (int)left_spritepixels);
int src_top = std::max(0, (int)top_spritepixels);
int src_width = std::min((int)cached_texture.getSize().x - src_left,
(int)((x_limit - left_edge + 2) * cell_width));
int src_height = std::min((int)cached_texture.getSize().y - src_top,
(int)((y_limit - top_edge + 2) * cell_height));
if (src_width <= 0 || src_height <= 0) return;
// Set texture rect for visible portion
cached_sprite.setTextureRect(sf::IntRect({src_left, src_top}, {src_width, src_height}));
// Position in target (offset for partial cell visibility)
float dest_x = (src_left - left_spritepixels) * zoom;
float dest_y = (src_top - top_spritepixels) * zoom;
cached_sprite.setPosition(sf::Vector2f(dest_x, dest_y));
// Apply zoom via scale
cached_sprite.setScale(sf::Vector2f(zoom, zoom));
target.draw(cached_sprite);
}
// =============================================================================
@ -208,7 +350,37 @@ int TileLayer::at(int x, int y) const {
void TileLayer::fill(int tile_index) {
std::fill(tiles.begin(), tiles.end(), tile_index);
markDirty(); // #148 - Mark for re-render
markDirty(); // Mark ALL chunks for re-render
}
void TileLayer::fillRect(int x, int y, int width, int height, int tile_index) {
// Clamp to valid bounds
int x1 = std::max(0, x);
int y1 = std::max(0, y);
int x2 = std::min(grid_x, x + width);
int y2 = std::min(grid_y, y + height);
// Fill the rectangle
for (int fy = y1; fy < y2; ++fy) {
for (int fx = x1; fx < x2; ++fx) {
tiles[fy * grid_x + fx] = tile_index;
}
}
// Mark affected chunks dirty
int chunk_x1 = x1 / CHUNK_SIZE;
int chunk_y1 = y1 / CHUNK_SIZE;
int chunk_x2 = (x2 - 1) / CHUNK_SIZE;
int chunk_y2 = (y2 - 1) / CHUNK_SIZE;
for (int cy = chunk_y1; cy <= chunk_y2; ++cy) {
for (int cx = chunk_x1; cx <= chunk_x2; ++cx) {
int idx = cy * chunks_x + cx;
if (idx >= 0 && idx < static_cast<int>(chunk_dirty.size())) {
chunk_dirty[idx] = true;
}
}
}
}
void TileLayer::resize(int new_grid_x, int new_grid_y) {
@ -227,32 +399,51 @@ void TileLayer::resize(int new_grid_x, int new_grid_y) {
grid_x = new_grid_x;
grid_y = new_grid_y;
// #148 - Invalidate cached texture (will be resized on next render)
texture_initialized = false;
markDirty();
// Reinitialize chunks for new dimensions
initChunks();
}
// #148 - Render all cells to cached texture (called when dirty)
void TileLayer::renderToTexture(int cell_width, int cell_height) {
ensureTextureSize(cell_width, cell_height);
if (!texture_initialized || !texture) return;
// Render a single chunk to its cached texture
void TileLayer::renderChunkToTexture(int chunk_x, int chunk_y, int cell_width, int cell_height) {
if (!texture) return;
cached_texture.clear(sf::Color::Transparent);
int chunk_idx = chunk_y * chunks_x + chunk_x;
if (chunk_idx < 0 || chunk_idx >= static_cast<int>(chunk_textures.size())) return;
if (!chunk_textures[chunk_idx]) return;
// Render all tiles to cached texture (no zoom - 1:1 pixel mapping)
for (int x = 0; x < grid_x; ++x) {
for (int y = 0; y < grid_y; ++y) {
ensureChunkTexture(chunk_idx, cell_width, cell_height);
if (!chunk_texture_initialized[chunk_idx]) return;
// Get chunk bounds
int start_x, start_y, end_x, end_y;
getChunkBounds(chunk_x, chunk_y, start_x, start_y, end_x, end_y);
chunk_textures[chunk_idx]->clear(sf::Color::Transparent);
// Render only tiles within this chunk (local coordinates in texture)
for (int x = start_x; x < end_x; ++x) {
for (int y = start_y; y < end_y; ++y) {
int tile_index = at(x, y);
if (tile_index < 0) continue; // No tile
auto pixel_pos = sf::Vector2f(x * cell_width, y * cell_height);
// Position relative to chunk origin
auto pixel_pos = sf::Vector2f((x - start_x) * cell_width, (y - start_y) * cell_height);
sf::Sprite sprite = texture->sprite(tile_index, pixel_pos, sf::Vector2f(1.0f, 1.0f));
cached_texture.draw(sprite);
chunk_textures[chunk_idx]->draw(sprite);
}
}
cached_texture.display();
dirty = false;
chunk_textures[chunk_idx]->display();
chunk_dirty[chunk_idx] = false;
}
// Legacy: render all chunks (used by fill, resize, etc.)
void TileLayer::renderToTexture(int cell_width, int cell_height) {
for (int cy = 0; cy < chunks_y; ++cy) {
for (int cx = 0; cx < chunks_x; ++cx) {
renderChunkToTexture(cx, cy, cell_width, cell_height);
}
}
}
void TileLayer::render(sf::RenderTarget& target,
@ -261,56 +452,62 @@ void TileLayer::render(sf::RenderTarget& target,
float zoom, int cell_width, int cell_height) {
if (!visible || !texture) return;
// #148 - Use cached texture rendering
// Re-render to texture only if dirty
if (dirty || !texture_initialized) {
renderToTexture(cell_width, cell_height);
}
// Calculate visible chunk range
int chunk_left = std::max(0, left_edge / CHUNK_SIZE);
int chunk_top = std::max(0, top_edge / CHUNK_SIZE);
int chunk_right = std::min(chunks_x - 1, (x_limit + CHUNK_SIZE - 1) / CHUNK_SIZE);
int chunk_bottom = std::min(chunks_y - 1, (y_limit + CHUNK_SIZE - 1) / CHUNK_SIZE);
if (!texture_initialized) {
// Fallback to direct rendering if texture creation failed
for (int x = (left_edge - 1 >= 0 ? left_edge - 1 : 0); x < x_limit; ++x) {
for (int y = (top_edge - 1 >= 0 ? top_edge - 1 : 0); y < y_limit; ++y) {
if (x < 0 || x >= grid_x || y < 0 || y >= grid_y) continue;
// Iterate only over visible chunks
for (int cy = chunk_top; cy <= chunk_bottom; ++cy) {
for (int cx = chunk_left; cx <= chunk_right; ++cx) {
int chunk_idx = cy * chunks_x + cx;
int tile_index = at(x, y);
if (tile_index < 0) continue;
auto pixel_pos = sf::Vector2f(
(x * cell_width - left_spritepixels) * zoom,
(y * cell_height - top_spritepixels) * zoom
);
sf::Sprite sprite = texture->sprite(tile_index, pixel_pos, sf::Vector2f(zoom, zoom));
target.draw(sprite);
// Re-render chunk only if dirty AND visible
if (chunk_dirty[chunk_idx] || !chunk_texture_initialized[chunk_idx]) {
renderChunkToTexture(cx, cy, cell_width, cell_height);
}
if (!chunk_texture_initialized[chunk_idx]) {
// Fallback: direct rendering for this chunk
int start_x, start_y, end_x, end_y;
getChunkBounds(cx, cy, start_x, start_y, end_x, end_y);
for (int x = start_x; x < end_x; ++x) {
for (int y = start_y; y < end_y; ++y) {
int tile_index = at(x, y);
if (tile_index < 0) continue;
auto pixel_pos = sf::Vector2f(
(x * cell_width - left_spritepixels) * zoom,
(y * cell_height - top_spritepixels) * zoom
);
sf::Sprite sprite = texture->sprite(tile_index, pixel_pos, sf::Vector2f(zoom, zoom));
target.draw(sprite);
}
}
continue;
}
// Blit this chunk's texture to target
int start_x, start_y, end_x, end_y;
getChunkBounds(cx, cy, start_x, start_y, end_x, end_y);
// Chunk position in world pixel coordinates
float chunk_world_x = start_x * cell_width;
float chunk_world_y = start_y * cell_height;
// Position in target (accounting for viewport offset and zoom)
float dest_x = (chunk_world_x - left_spritepixels) * zoom;
float dest_y = (chunk_world_y - top_spritepixels) * zoom;
sf::Sprite chunk_sprite(chunk_textures[chunk_idx]->getTexture());
chunk_sprite.setPosition(sf::Vector2f(dest_x, dest_y));
chunk_sprite.setScale(sf::Vector2f(zoom, zoom));
target.draw(chunk_sprite);
}
return;
}
// Blit visible portion of cached texture with zoom applied
// Calculate source rectangle (unzoomed pixel coordinates in cached texture)
int src_left = std::max(0, (int)left_spritepixels);
int src_top = std::max(0, (int)top_spritepixels);
int src_width = std::min((int)cached_texture.getSize().x - src_left,
(int)((x_limit - left_edge + 2) * cell_width));
int src_height = std::min((int)cached_texture.getSize().y - src_top,
(int)((y_limit - top_edge + 2) * cell_height));
if (src_width <= 0 || src_height <= 0) return;
// Set texture rect for visible portion
cached_sprite.setTextureRect(sf::IntRect({src_left, src_top}, {src_width, src_height}));
// Position in target (offset for partial cell visibility)
float dest_x = (src_left - left_spritepixels) * zoom;
float dest_y = (src_top - top_spritepixels) * zoom;
cached_sprite.setPosition(sf::Vector2f(dest_x, dest_y));
// Apply zoom via scale
cached_sprite.setScale(sf::Vector2f(zoom, zoom));
target.draw(cached_sprite);
}
// =============================================================================
@ -324,6 +521,24 @@ PyMethodDef PyGridLayerAPI::ColorLayer_methods[] = {
"set(x, y, color)\n\nSet the color at cell position (x, y)."},
{"fill", (PyCFunction)PyGridLayerAPI::ColorLayer_fill, METH_VARARGS,
"fill(color)\n\nFill the entire layer with the specified color."},
{"fill_rect", (PyCFunction)PyGridLayerAPI::ColorLayer_fill_rect, METH_VARARGS | METH_KEYWORDS,
"fill_rect(pos, size, color)\n\n"
"Fill a rectangular region with a color.\n\n"
"Args:\n"
" pos (tuple): Top-left corner as (x, y)\n"
" size (tuple): Dimensions as (width, height)\n"
" color: Color object or (r, g, b[, a]) tuple"},
{"draw_fov", (PyCFunction)PyGridLayerAPI::ColorLayer_draw_fov, METH_VARARGS | METH_KEYWORDS,
"draw_fov(source, radius=None, fov=None, visible=None, discovered=None, unknown=None)\n\n"
"Paint cells based on field-of-view visibility from source position.\n\n"
"Args:\n"
" source (tuple): FOV origin as (x, y)\n"
" radius (int): FOV radius. Default: grid's fov_radius\n"
" fov (FOV): FOV algorithm. Default: grid's fov setting\n"
" visible (Color): Color for currently visible cells\n"
" discovered (Color): Color for previously seen cells\n"
" unknown (Color): Color for never-seen cells\n\n"
"Note: Layer must be attached to a grid for FOV calculation."},
{NULL}
};
@ -442,7 +657,7 @@ PyObject* PyGridLayerAPI::ColorLayer_set(PyColorLayerObject* self, PyObject* arg
Py_DECREF(color_type);
self->data->at(x, y) = color;
self->data->markDirty(); // #148 - Mark for re-render
self->data->markDirty(x, y); // Mark only the affected chunk
Py_RETURN_NONE;
}
@ -486,6 +701,170 @@ PyObject* PyGridLayerAPI::ColorLayer_fill(PyColorLayerObject* self, PyObject* ar
Py_RETURN_NONE;
}
PyObject* PyGridLayerAPI::ColorLayer_fill_rect(PyColorLayerObject* self, PyObject* args, PyObject* kwds) {
static const char* kwlist[] = {"pos", "size", "color", NULL};
PyObject* pos_obj;
PyObject* size_obj;
PyObject* color_obj;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOO", const_cast<char**>(kwlist),
&pos_obj, &size_obj, &color_obj)) {
return NULL;
}
if (!self->data) {
PyErr_SetString(PyExc_RuntimeError, "Layer has no data");
return NULL;
}
// Parse pos
int x, y;
if (PyTuple_Check(pos_obj) && PyTuple_Size(pos_obj) == 2) {
x = PyLong_AsLong(PyTuple_GetItem(pos_obj, 0));
y = PyLong_AsLong(PyTuple_GetItem(pos_obj, 1));
if (PyErr_Occurred()) return NULL;
} else {
PyErr_SetString(PyExc_TypeError, "pos must be a (x, y) tuple");
return NULL;
}
// Parse size
int width, height;
if (PyTuple_Check(size_obj) && PyTuple_Size(size_obj) == 2) {
width = PyLong_AsLong(PyTuple_GetItem(size_obj, 0));
height = PyLong_AsLong(PyTuple_GetItem(size_obj, 1));
if (PyErr_Occurred()) return NULL;
} else {
PyErr_SetString(PyExc_TypeError, "size must be a (width, height) tuple");
return NULL;
}
// Parse color
sf::Color color;
auto* mcrfpy_module = PyImport_ImportModule("mcrfpy");
if (!mcrfpy_module) return NULL;
auto* color_type = PyObject_GetAttrString(mcrfpy_module, "Color");
Py_DECREF(mcrfpy_module);
if (!color_type) return NULL;
if (PyObject_IsInstance(color_obj, color_type)) {
color = ((PyColorObject*)color_obj)->data;
} else if (PyTuple_Check(color_obj)) {
int r, g, b, a = 255;
if (!PyArg_ParseTuple(color_obj, "iii|i", &r, &g, &b, &a)) {
Py_DECREF(color_type);
return NULL;
}
color = sf::Color(r, g, b, a);
} else {
Py_DECREF(color_type);
PyErr_SetString(PyExc_TypeError, "color must be a Color object or (r, g, b[, a]) tuple");
return NULL;
}
Py_DECREF(color_type);
self->data->fillRect(x, y, width, height, color);
Py_RETURN_NONE;
}
PyObject* PyGridLayerAPI::ColorLayer_draw_fov(PyColorLayerObject* self, PyObject* args, PyObject* kwds) {
static const char* kwlist[] = {"source", "radius", "fov", "visible", "discovered", "unknown", NULL};
PyObject* source_obj;
int radius = -1; // -1 means use grid's default
PyObject* fov_obj = Py_None;
PyObject* visible_obj = nullptr;
PyObject* discovered_obj = nullptr;
PyObject* unknown_obj = nullptr;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|iOOOO", const_cast<char**>(kwlist),
&source_obj, &radius, &fov_obj, &visible_obj, &discovered_obj, &unknown_obj)) {
return NULL;
}
if (!self->data) {
PyErr_SetString(PyExc_RuntimeError, "Layer has no data");
return NULL;
}
if (!self->grid) {
PyErr_SetString(PyExc_RuntimeError, "Layer is not attached to a grid");
return NULL;
}
// Parse source position
int source_x, source_y;
if (PyTuple_Check(source_obj) && PyTuple_Size(source_obj) == 2) {
source_x = PyLong_AsLong(PyTuple_GetItem(source_obj, 0));
source_y = PyLong_AsLong(PyTuple_GetItem(source_obj, 1));
if (PyErr_Occurred()) return NULL;
} else {
PyErr_SetString(PyExc_TypeError, "source must be a (x, y) tuple");
return NULL;
}
// Get radius from grid if not specified
if (radius < 0) {
radius = self->grid->fov_radius;
}
// Get FOV algorithm
TCOD_fov_algorithm_t algorithm;
bool was_none = false;
if (!PyFOV::from_arg(fov_obj, &algorithm, &was_none)) {
return NULL;
}
if (was_none) {
algorithm = self->grid->fov_algorithm;
}
// Helper lambda to parse color
auto parse_color = [](PyObject* obj, sf::Color& out, const sf::Color& default_val, const char* name) -> bool {
if (!obj || obj == Py_None) {
out = default_val;
return true;
}
auto* mcrfpy_module = PyImport_ImportModule("mcrfpy");
if (!mcrfpy_module) return false;
auto* color_type = PyObject_GetAttrString(mcrfpy_module, "Color");
Py_DECREF(mcrfpy_module);
if (!color_type) return false;
if (PyObject_IsInstance(obj, color_type)) {
out = ((PyColorObject*)obj)->data;
Py_DECREF(color_type);
return true;
} else if (PyTuple_Check(obj)) {
int r, g, b, a = 255;
if (!PyArg_ParseTuple(obj, "iii|i", &r, &g, &b, &a)) {
Py_DECREF(color_type);
return false;
}
out = sf::Color(r, g, b, a);
Py_DECREF(color_type);
return true;
}
Py_DECREF(color_type);
PyErr_Format(PyExc_TypeError, "%s must be a Color object or (r, g, b[, a]) tuple", name);
return false;
};
// Default colors for FOV visualization
sf::Color visible_color(255, 255, 200, 64); // Light yellow tint
sf::Color discovered_color(128, 128, 128, 128); // Gray
sf::Color unknown_color(0, 0, 0, 255); // Black
if (!parse_color(visible_obj, visible_color, visible_color, "visible")) return NULL;
if (!parse_color(discovered_obj, discovered_color, discovered_color, "discovered")) return NULL;
if (!parse_color(unknown_obj, unknown_color, unknown_color, "unknown")) return NULL;
self->data->drawFOV(source_x, source_y, radius, algorithm, visible_color, discovered_color, unknown_color);
Py_RETURN_NONE;
}
PyObject* PyGridLayerAPI::ColorLayer_get_z_index(PyColorLayerObject* self, void* closure) {
if (!self->data) {
PyErr_SetString(PyExc_RuntimeError, "Layer has no data");
@ -556,6 +935,13 @@ PyMethodDef PyGridLayerAPI::TileLayer_methods[] = {
"set(x, y, index)\n\nSet the tile index at cell position (x, y). Use -1 for no tile."},
{"fill", (PyCFunction)PyGridLayerAPI::TileLayer_fill, METH_VARARGS,
"fill(index)\n\nFill the entire layer with the specified tile index."},
{"fill_rect", (PyCFunction)PyGridLayerAPI::TileLayer_fill_rect, METH_VARARGS | METH_KEYWORDS,
"fill_rect(pos, size, index)\n\n"
"Fill a rectangular region with a tile index.\n\n"
"Args:\n"
" pos (tuple): Top-left corner as (x, y)\n"
" size (tuple): Dimensions as (width, height)\n"
" index (int): Tile index to fill with (-1 for no tile)"},
{NULL}
};
@ -661,7 +1047,7 @@ PyObject* PyGridLayerAPI::TileLayer_set(PyTileLayerObject* self, PyObject* args)
}
self->data->at(x, y) = index;
self->data->markDirty(); // #148 - Mark for re-render
self->data->markDirty(x, y); // Mark only the affected chunk
Py_RETURN_NONE;
}
@ -680,6 +1066,48 @@ PyObject* PyGridLayerAPI::TileLayer_fill(PyTileLayerObject* self, PyObject* args
Py_RETURN_NONE;
}
PyObject* PyGridLayerAPI::TileLayer_fill_rect(PyTileLayerObject* self, PyObject* args, PyObject* kwds) {
static const char* kwlist[] = {"pos", "size", "index", NULL};
PyObject* pos_obj;
PyObject* size_obj;
int tile_index;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOi", const_cast<char**>(kwlist),
&pos_obj, &size_obj, &tile_index)) {
return NULL;
}
if (!self->data) {
PyErr_SetString(PyExc_RuntimeError, "Layer has no data");
return NULL;
}
// Parse pos
int x, y;
if (PyTuple_Check(pos_obj) && PyTuple_Size(pos_obj) == 2) {
x = PyLong_AsLong(PyTuple_GetItem(pos_obj, 0));
y = PyLong_AsLong(PyTuple_GetItem(pos_obj, 1));
if (PyErr_Occurred()) return NULL;
} else {
PyErr_SetString(PyExc_TypeError, "pos must be a (x, y) tuple");
return NULL;
}
// Parse size
int width, height;
if (PyTuple_Check(size_obj) && PyTuple_Size(size_obj) == 2) {
width = PyLong_AsLong(PyTuple_GetItem(size_obj, 0));
height = PyLong_AsLong(PyTuple_GetItem(size_obj, 1));
if (PyErr_Occurred()) return NULL;
} else {
PyErr_SetString(PyExc_TypeError, "size must be a (width, height) tuple");
return NULL;
}
self->data->fillRect(x, y, width, height, tile_index);
Py_RETURN_NONE;
}
PyObject* PyGridLayerAPI::TileLayer_get_z_index(PyTileLayerObject* self, void* closure) {
if (!self->data) {
PyErr_SetString(PyExc_RuntimeError, "Layer has no data");
@ -749,7 +1177,7 @@ int PyGridLayerAPI::TileLayer_set_texture(PyTileLayerObject* self, PyObject* val
if (value == Py_None) {
self->data->texture.reset();
self->data->markDirty(); // #148 - Mark for re-render
self->data->markDirty(); // Mark ALL chunks for re-render (texture change affects all)
return 0;
}
@ -768,7 +1196,7 @@ int PyGridLayerAPI::TileLayer_set_texture(PyTileLayerObject* self, PyObject* val
Py_DECREF(texture_type);
self->data->texture = ((PyTextureObject*)value)->data;
self->data->markDirty(); // #148 - Mark for re-render
self->data->markDirty(); // Mark ALL chunks for re-render (texture change affects all)
return 0;
}

View file

@ -3,6 +3,7 @@
#include "Python.h"
#include "structmember.h"
#include <SFML/Graphics.hpp>
#include <libtcod.h>
#include <memory>
#include <vector>
#include <string>
@ -23,6 +24,9 @@ enum class GridLayerType {
// Abstract base class for grid layers
class GridLayer {
public:
// Chunk size for per-chunk dirty tracking (matches GridChunk::CHUNK_SIZE)
static constexpr int CHUNK_SIZE = 64;
GridLayerType type;
std::string name; // #150 - Layer name for GridPoint property access
int z_index; // Negative = below entities, >= 0 = above entities
@ -30,33 +34,53 @@ public:
UIGrid* parent_grid; // Parent grid reference
bool visible; // Visibility flag
// #148 - Dirty flag and RenderTexture caching
bool dirty; // True if layer needs re-render
sf::RenderTexture cached_texture; // Cached layer content
sf::Sprite cached_sprite; // Sprite for blitting cached texture
bool texture_initialized; // True if RenderTexture has been created
int cached_cell_width, cached_cell_height; // Cell size used for cached texture
// Chunk dimensions
int chunks_x, chunks_y;
// Per-chunk dirty flags and RenderTextures
std::vector<bool> chunk_dirty; // One flag per chunk
std::vector<std::unique_ptr<sf::RenderTexture>> chunk_textures; // One texture per chunk
std::vector<bool> chunk_texture_initialized; // Track which textures are created
int cached_cell_width, cached_cell_height; // Cell size used for cached textures
GridLayer(GridLayerType type, int z_index, int grid_x, int grid_y, UIGrid* parent);
virtual ~GridLayer() = default;
// Mark layer as needing re-render
// Mark entire layer as needing re-render
void markDirty();
// Ensure cached texture is properly sized for current grid dimensions
void ensureTextureSize(int cell_width, int cell_height);
// Mark specific cell's chunk as dirty
void markDirty(int cell_x, int cell_y);
// Render the layer content to the cached texture (called when dirty)
// Get chunk index for a cell
int getChunkIndex(int cell_x, int cell_y) const;
// Get chunk coordinates for a cell
void getChunkCoords(int cell_x, int cell_y, int& chunk_x, int& chunk_y) const;
// Get cell bounds for a chunk
void getChunkBounds(int chunk_x, int chunk_y, int& start_x, int& start_y, int& end_x, int& end_y) const;
// Ensure a specific chunk's texture is properly sized
void ensureChunkTexture(int chunk_idx, int cell_width, int cell_height);
// Initialize chunk tracking arrays
void initChunks();
// Render a specific chunk to its cached texture (called when chunk is dirty)
virtual void renderChunkToTexture(int chunk_x, int chunk_y, int cell_width, int cell_height) = 0;
// Render the layer content to the cached texture (legacy - marks all dirty)
virtual void renderToTexture(int cell_width, int cell_height) = 0;
// Render the layer to a RenderTarget with the given transformation parameters
// Uses cached texture if available, only re-renders when dirty
// Uses cached chunk textures, only re-renders visible dirty chunks
virtual void render(sf::RenderTarget& target,
float left_spritepixels, float top_spritepixels,
int left_edge, int top_edge, int x_limit, int y_limit,
float zoom, int cell_width, int cell_height) = 0;
// Resize the layer (reallocates storage)
// Resize the layer (reallocates storage and reinitializes chunks)
virtual void resize(int new_grid_x, int new_grid_y) = 0;
};
@ -74,7 +98,21 @@ public:
// Fill entire layer with a color
void fill(const sf::Color& color);
// #148 - Render all content to cached texture
// Fill a rectangular region with a color (#113)
void fillRect(int x, int y, int width, int height, const sf::Color& color);
// Draw FOV-based visibility (#113)
// Paints cells based on current FOV state from parent grid
void drawFOV(int source_x, int source_y, int radius,
TCOD_fov_algorithm_t algorithm,
const sf::Color& visible,
const sf::Color& discovered,
const sf::Color& unknown);
// Render a specific chunk to its texture (called when chunk is dirty AND visible)
void renderChunkToTexture(int chunk_x, int chunk_y, int cell_width, int cell_height) override;
// #148 - Render all content to cached texture (legacy - calls renderChunkToTexture for all)
void renderToTexture(int cell_width, int cell_height) override;
void render(sf::RenderTarget& target,
@ -101,7 +139,13 @@ public:
// Fill entire layer with a tile index
void fill(int tile_index);
// #148 - Render all content to cached texture
// Fill a rectangular region with a tile index (#113)
void fillRect(int x, int y, int width, int height, int tile_index);
// Render a specific chunk to its texture (called when chunk is dirty AND visible)
void renderChunkToTexture(int chunk_x, int chunk_y, int cell_width, int cell_height) override;
// #148 - Render all content to cached texture (legacy - calls renderChunkToTexture for all)
void renderToTexture(int cell_width, int cell_height) override;
void render(sf::RenderTarget& target,
@ -139,6 +183,8 @@ public:
static PyObject* ColorLayer_at(PyColorLayerObject* self, PyObject* args);
static PyObject* ColorLayer_set(PyColorLayerObject* self, PyObject* args);
static PyObject* ColorLayer_fill(PyColorLayerObject* self, PyObject* args);
static PyObject* ColorLayer_fill_rect(PyColorLayerObject* self, PyObject* args, PyObject* kwds);
static PyObject* ColorLayer_draw_fov(PyColorLayerObject* self, PyObject* args, PyObject* kwds);
static PyObject* ColorLayer_get_z_index(PyColorLayerObject* self, void* closure);
static int ColorLayer_set_z_index(PyColorLayerObject* self, PyObject* value, void* closure);
static PyObject* ColorLayer_get_visible(PyColorLayerObject* self, void* closure);
@ -151,6 +197,7 @@ public:
static PyObject* TileLayer_at(PyTileLayerObject* self, PyObject* args);
static PyObject* TileLayer_set(PyTileLayerObject* self, PyObject* args);
static PyObject* TileLayer_fill(PyTileLayerObject* self, PyObject* args);
static PyObject* TileLayer_fill_rect(PyTileLayerObject* self, PyObject* args, PyObject* kwds);
static PyObject* TileLayer_get_z_index(PyTileLayerObject* self, void* closure);
static int TileLayer_set_z_index(PyTileLayerObject* self, PyObject* value, void* closure);
static PyObject* TileLayer_get_visible(PyTileLayerObject* self, void* closure);

View file

@ -8,6 +8,7 @@
#include "PyTimer.h"
#include "PyWindow.h"
#include "PySceneObject.h"
#include "PyFOV.h"
#include "GameEngine.h"
#include "ImGuiConsole.h"
#include "BenchmarkLogger.h"
@ -366,20 +367,28 @@ PyObject* PyInit_mcrfpy()
PyModule_AddObject(m, "default_font", Py_None);
PyModule_AddObject(m, "default_texture", Py_None);
// Add TCOD FOV algorithm constants
PyModule_AddIntConstant(m, "FOV_BASIC", FOV_BASIC);
PyModule_AddIntConstant(m, "FOV_DIAMOND", FOV_DIAMOND);
PyModule_AddIntConstant(m, "FOV_SHADOW", FOV_SHADOW);
PyModule_AddIntConstant(m, "FOV_PERMISSIVE_0", FOV_PERMISSIVE_0);
PyModule_AddIntConstant(m, "FOV_PERMISSIVE_1", FOV_PERMISSIVE_1);
PyModule_AddIntConstant(m, "FOV_PERMISSIVE_2", FOV_PERMISSIVE_2);
PyModule_AddIntConstant(m, "FOV_PERMISSIVE_3", FOV_PERMISSIVE_3);
PyModule_AddIntConstant(m, "FOV_PERMISSIVE_4", FOV_PERMISSIVE_4);
PyModule_AddIntConstant(m, "FOV_PERMISSIVE_5", FOV_PERMISSIVE_5);
PyModule_AddIntConstant(m, "FOV_PERMISSIVE_6", FOV_PERMISSIVE_6);
PyModule_AddIntConstant(m, "FOV_PERMISSIVE_7", FOV_PERMISSIVE_7);
PyModule_AddIntConstant(m, "FOV_PERMISSIVE_8", FOV_PERMISSIVE_8);
PyModule_AddIntConstant(m, "FOV_RESTRICTIVE", FOV_RESTRICTIVE);
// Add FOV enum class (uses Python's IntEnum) (#114)
PyObject* fov_class = PyFOV::create_enum_class(m);
if (!fov_class) {
// If enum creation fails, continue without it (non-fatal)
PyErr_Clear();
}
// Add default_fov module property - defaults to FOV.BASIC
// New grids copy this value at creation time
if (fov_class) {
PyObject* default_fov = PyObject_GetAttrString(fov_class, "BASIC");
if (default_fov) {
PyModule_AddObject(m, "default_fov", default_fov);
} else {
PyErr_Clear();
// Fallback to integer
PyModule_AddIntConstant(m, "default_fov", FOV_BASIC);
}
} else {
// Fallback to integer if enum failed
PyModule_AddIntConstant(m, "default_fov", FOV_BASIC);
}
// Add automation submodule
PyObject* automation_module = McRFPy_Automation::init_automation_module();

View file

@ -185,38 +185,19 @@ static PyObject* McRFPy_Libtcod::dijkstra_path_to(PyObject* self, PyObject* args
return path_list;
}
// Add FOV algorithm constants to module
static PyObject* McRFPy_Libtcod::add_fov_constants(PyObject* module) {
// FOV algorithms
PyModule_AddIntConstant(module, "FOV_BASIC", FOV_BASIC);
PyModule_AddIntConstant(module, "FOV_DIAMOND", FOV_DIAMOND);
PyModule_AddIntConstant(module, "FOV_SHADOW", FOV_SHADOW);
PyModule_AddIntConstant(module, "FOV_PERMISSIVE_0", FOV_PERMISSIVE_0);
PyModule_AddIntConstant(module, "FOV_PERMISSIVE_1", FOV_PERMISSIVE_1);
PyModule_AddIntConstant(module, "FOV_PERMISSIVE_2", FOV_PERMISSIVE_2);
PyModule_AddIntConstant(module, "FOV_PERMISSIVE_3", FOV_PERMISSIVE_3);
PyModule_AddIntConstant(module, "FOV_PERMISSIVE_4", FOV_PERMISSIVE_4);
PyModule_AddIntConstant(module, "FOV_PERMISSIVE_5", FOV_PERMISSIVE_5);
PyModule_AddIntConstant(module, "FOV_PERMISSIVE_6", FOV_PERMISSIVE_6);
PyModule_AddIntConstant(module, "FOV_PERMISSIVE_7", FOV_PERMISSIVE_7);
PyModule_AddIntConstant(module, "FOV_PERMISSIVE_8", FOV_PERMISSIVE_8);
PyModule_AddIntConstant(module, "FOV_RESTRICTIVE", FOV_RESTRICTIVE);
PyModule_AddIntConstant(module, "FOV_SYMMETRIC_SHADOWCAST", FOV_SYMMETRIC_SHADOWCAST);
return module;
}
// FOV algorithm constants removed - use mcrfpy.FOV enum instead (#114)
// Method definitions
static PyMethodDef libtcodMethods[] = {
{"compute_fov", McRFPy_Libtcod::compute_fov, METH_VARARGS,
"compute_fov(grid, x, y, radius, light_walls=True, algorithm=FOV_BASIC)\n\n"
{"compute_fov", McRFPy_Libtcod::compute_fov, METH_VARARGS,
"compute_fov(grid, x, y, radius, light_walls=True, algorithm=mcrfpy.FOV.BASIC)\n\n"
"Compute field of view from a position.\n\n"
"Args:\n"
" grid: Grid object to compute FOV on\n"
" x, y: Origin position\n"
" radius: Maximum sight radius\n"
" light_walls: Whether walls are lit when in FOV\n"
" algorithm: FOV algorithm to use (FOV_BASIC, FOV_SHADOW, etc.)\n\n"
" algorithm: FOV algorithm (mcrfpy.FOV.BASIC, mcrfpy.FOV.SHADOW, etc.)\n\n"
"Returns:\n"
" List of (x, y) tuples for visible cells"},
@ -293,13 +274,13 @@ static PyModuleDef libtcodModule = {
"TCOD-compatible algorithms for field of view, pathfinding, and line drawing.\n\n"
"This module provides access to TCOD's algorithms integrated with McRogueFace grids.\n"
"Unlike the original TCOD, these functions work directly with Grid objects.\n\n"
"FOV Algorithms:\n"
" FOV_BASIC - Basic circular FOV\n"
" FOV_SHADOW - Shadow casting (recommended)\n"
" FOV_DIAMOND - Diamond-shaped FOV\n"
" FOV_PERMISSIVE_0 through FOV_PERMISSIVE_8 - Permissive variants\n"
" FOV_RESTRICTIVE - Most restrictive FOV\n"
" FOV_SYMMETRIC_SHADOWCAST - Symmetric shadow casting\n\n"
"FOV Algorithms (use mcrfpy.FOV enum):\n"
" mcrfpy.FOV.BASIC - Basic circular FOV\n"
" mcrfpy.FOV.SHADOW - Shadow casting (recommended)\n"
" mcrfpy.FOV.DIAMOND - Diamond-shaped FOV\n"
" mcrfpy.FOV.PERMISSIVE_0 through PERMISSIVE_8 - Permissive variants\n"
" mcrfpy.FOV.RESTRICTIVE - Most restrictive FOV\n"
" mcrfpy.FOV.SYMMETRIC_SHADOWCAST - Symmetric shadow casting\n\n"
"Example:\n"
" import mcrfpy\n"
" from mcrfpy import libtcod\n\n"
@ -317,8 +298,7 @@ PyObject* McRFPy_Libtcod::init_libtcod_module() {
return NULL;
}
// Add FOV algorithm constants
add_fov_constants(m);
// FOV algorithm constants now provided by mcrfpy.FOV enum (#114)
return m;
}

View file

@ -18,10 +18,7 @@ namespace McRFPy_Libtcod
// Line algorithms
static PyObject* line(PyObject* self, PyObject* args);
static PyObject* line_iter(PyObject* self, PyObject* args);
// FOV algorithm constants
static PyObject* add_fov_constants(PyObject* module);
// Module initialization
PyObject* init_libtcod_module();
}

148
src/PyFOV.cpp Normal file
View file

@ -0,0 +1,148 @@
#include "PyFOV.h"
#include "McRFPy_API.h"
// Static storage for cached enum class reference
PyObject* PyFOV::fov_enum_class = nullptr;
PyObject* PyFOV::create_enum_class(PyObject* module) {
// Import IntEnum from enum module
PyObject* enum_module = PyImport_ImportModule("enum");
if (!enum_module) {
return NULL;
}
PyObject* int_enum = PyObject_GetAttrString(enum_module, "IntEnum");
Py_DECREF(enum_module);
if (!int_enum) {
return NULL;
}
// Create dict of enum members
PyObject* members = PyDict_New();
if (!members) {
Py_DECREF(int_enum);
return NULL;
}
// Add all FOV algorithm members
struct {
const char* name;
int value;
} fov_members[] = {
{"BASIC", FOV_BASIC},
{"DIAMOND", FOV_DIAMOND},
{"SHADOW", FOV_SHADOW},
{"PERMISSIVE_0", FOV_PERMISSIVE_0},
{"PERMISSIVE_1", FOV_PERMISSIVE_1},
{"PERMISSIVE_2", FOV_PERMISSIVE_2},
{"PERMISSIVE_3", FOV_PERMISSIVE_3},
{"PERMISSIVE_4", FOV_PERMISSIVE_4},
{"PERMISSIVE_5", FOV_PERMISSIVE_5},
{"PERMISSIVE_6", FOV_PERMISSIVE_6},
{"PERMISSIVE_7", FOV_PERMISSIVE_7},
{"PERMISSIVE_8", FOV_PERMISSIVE_8},
{"RESTRICTIVE", FOV_RESTRICTIVE},
{"SYMMETRIC_SHADOWCAST", FOV_SYMMETRIC_SHADOWCAST},
};
for (const auto& m : fov_members) {
PyObject* value = PyLong_FromLong(m.value);
if (!value) {
Py_DECREF(members);
Py_DECREF(int_enum);
return NULL;
}
if (PyDict_SetItemString(members, m.name, value) < 0) {
Py_DECREF(value);
Py_DECREF(members);
Py_DECREF(int_enum);
return NULL;
}
Py_DECREF(value);
}
// Call IntEnum("FOV", members) to create the enum class
PyObject* name = PyUnicode_FromString("FOV");
if (!name) {
Py_DECREF(members);
Py_DECREF(int_enum);
return NULL;
}
// IntEnum(name, members) using functional API
PyObject* args = PyTuple_Pack(2, name, members);
Py_DECREF(name);
Py_DECREF(members);
if (!args) {
Py_DECREF(int_enum);
return NULL;
}
PyObject* fov_class = PyObject_Call(int_enum, args, NULL);
Py_DECREF(args);
Py_DECREF(int_enum);
if (!fov_class) {
return NULL;
}
// Cache the reference for fast type checking
fov_enum_class = fov_class;
Py_INCREF(fov_enum_class);
// Add to module
if (PyModule_AddObject(module, "FOV", fov_class) < 0) {
Py_DECREF(fov_class);
fov_enum_class = nullptr;
return NULL;
}
return fov_class;
}
int PyFOV::from_arg(PyObject* arg, TCOD_fov_algorithm_t* out_algo, bool* was_none) {
if (was_none) *was_none = false;
// Accept None -> caller should use default
if (arg == Py_None) {
if (was_none) *was_none = true;
*out_algo = FOV_BASIC;
return 1;
}
// Accept FOV enum member (check if it's an instance of our enum)
if (fov_enum_class && PyObject_IsInstance(arg, fov_enum_class)) {
// IntEnum members have a 'value' attribute
PyObject* value = PyObject_GetAttrString(arg, "value");
if (!value) {
return 0;
}
long val = PyLong_AsLong(value);
Py_DECREF(value);
if (val == -1 && PyErr_Occurred()) {
return 0;
}
*out_algo = (TCOD_fov_algorithm_t)val;
return 1;
}
// Accept int (for backwards compatibility)
if (PyLong_Check(arg)) {
long val = PyLong_AsLong(arg);
if (val == -1 && PyErr_Occurred()) {
return 0;
}
if (val < 0 || val >= NB_FOV_ALGORITHMS) {
PyErr_Format(PyExc_ValueError,
"Invalid FOV algorithm value: %ld. Must be 0-%d or use mcrfpy.FOV enum.",
val, NB_FOV_ALGORITHMS - 1);
return 0;
}
*out_algo = (TCOD_fov_algorithm_t)val;
return 1;
}
PyErr_SetString(PyExc_TypeError,
"FOV algorithm must be mcrfpy.FOV enum member, int, or None");
return 0;
}

22
src/PyFOV.h Normal file
View file

@ -0,0 +1,22 @@
#pragma once
#include "Common.h"
#include "Python.h"
#include <libtcod.h>
// Module-level FOV enum class (created at runtime using Python's IntEnum)
// Stored as a module attribute: mcrfpy.FOV
class PyFOV {
public:
// Create the FOV enum class and add to module
// Returns the enum class (new reference), or NULL on error
static PyObject* create_enum_class(PyObject* module);
// Helper to extract algorithm from Python arg (accepts FOV enum, int, or None)
// Returns 1 on success, 0 on error (with exception set)
// If arg is None, sets *out_algo to the default (FOV_BASIC) and sets *was_none to true
static int from_arg(PyObject* arg, TCOD_fov_algorithm_t* out_algo, bool* was_none = nullptr);
// Cached reference to the FOV enum class for fast type checking
static PyObject* fov_enum_class;
};

View file

@ -4,6 +4,7 @@
#include "PythonObjectCache.h"
#include "UIEntity.h"
#include "Profiler.h"
#include "PyFOV.h"
#include <algorithm>
#include <cmath> // #142 - for std::floor
#include <cstring> // #150 - for strcmp
@ -12,7 +13,8 @@
UIGrid::UIGrid()
: grid_x(0), grid_y(0), zoom(1.0f), center_x(0.0f), center_y(0.0f), ptex(nullptr),
fill_color(8, 8, 8, 255), tcod_map(nullptr), tcod_dijkstra(nullptr), tcod_path(nullptr),
perspective_enabled(false), use_chunks(false) // Default to omniscient view
perspective_enabled(false), fov_algorithm(FOV_BASIC), fov_radius(10),
use_chunks(false) // Default to omniscient view
{
// Initialize entities list
entities = std::make_shared<std::list<std::shared_ptr<UIEntity>>>();
@ -43,7 +45,7 @@ UIGrid::UIGrid(int gx, int gy, std::shared_ptr<PyTexture> _ptex, sf::Vector2f _x
zoom(1.0f),
ptex(_ptex),
fill_color(8, 8, 8, 255), tcod_map(nullptr), tcod_dijkstra(nullptr), tcod_path(nullptr),
perspective_enabled(false),
perspective_enabled(false), fov_algorithm(FOV_BASIC), fov_radius(10),
use_chunks(gx > CHUNK_THRESHOLD || gy > CHUNK_THRESHOLD) // #123 - Use chunks for large grids
{
// Use texture dimensions if available, otherwise use defaults
@ -1275,6 +1277,62 @@ int UIGrid::set_perspective_enabled(PyUIGridObject* self, PyObject* value, void*
return 0;
}
// #114 - FOV algorithm property
PyObject* UIGrid::get_fov(PyUIGridObject* self, void* closure)
{
// Return the FOV enum member for the current algorithm
if (PyFOV::fov_enum_class) {
// Get the enum member by value
PyObject* value = PyLong_FromLong(self->data->fov_algorithm);
if (!value) return NULL;
// Call FOV(value) to get the enum member
PyObject* args = PyTuple_Pack(1, value);
Py_DECREF(value);
if (!args) return NULL;
PyObject* result = PyObject_Call(PyFOV::fov_enum_class, args, NULL);
Py_DECREF(args);
return result;
}
// Fallback to integer
return PyLong_FromLong(self->data->fov_algorithm);
}
int UIGrid::set_fov(PyUIGridObject* self, PyObject* value, void* closure)
{
TCOD_fov_algorithm_t algo;
if (!PyFOV::from_arg(value, &algo, nullptr)) {
return -1;
}
self->data->fov_algorithm = algo;
return 0;
}
// #114 - FOV radius property
PyObject* UIGrid::get_fov_radius(PyUIGridObject* self, void* closure)
{
return PyLong_FromLong(self->data->fov_radius);
}
int UIGrid::set_fov_radius(PyUIGridObject* self, PyObject* value, void* closure)
{
if (!PyLong_Check(value)) {
PyErr_SetString(PyExc_TypeError, "fov_radius must be an integer");
return -1;
}
long radius = PyLong_AsLong(value);
if (radius == -1 && PyErr_Occurred()) {
return -1;
}
if (radius < 0) {
PyErr_SetString(PyExc_ValueError, "fov_radius must be non-negative");
return -1;
}
self->data->fov_radius = (int)radius;
return 0;
}
// Python API implementations for TCOD functionality
PyObject* UIGrid::py_compute_fov(PyUIGridObject* self, PyObject* args, PyObject* kwds)
{
@ -1836,6 +1894,11 @@ PyGetSetDef UIGrid::getsetters[] = {
{"perspective_enabled", (getter)UIGrid::get_perspective_enabled, (setter)UIGrid::set_perspective_enabled,
"Whether to use perspective-based FOV rendering. When True with no valid entity, "
"all cells appear undiscovered.", NULL},
{"fov", (getter)UIGrid::get_fov, (setter)UIGrid::set_fov,
"FOV algorithm for this grid (mcrfpy.FOV enum). "
"Used by entity.updateVisibility() and layer methods when fov=None.", NULL},
{"fov_radius", (getter)UIGrid::get_fov_radius, (setter)UIGrid::set_fov_radius,
"Default FOV radius for this grid. Used when radius not specified.", NULL},
{"z_index", (getter)UIDrawable::get_int, (setter)UIDrawable::set_int,
MCRF_PROPERTY(z_index,
"Z-order for rendering (lower values rendered first). "

View file

@ -112,6 +112,10 @@ public:
std::weak_ptr<UIEntity> perspective_entity; // Weak reference to perspective entity
bool perspective_enabled; // Whether to use perspective rendering
// #114 - FOV algorithm and radius for this grid
TCOD_fov_algorithm_t fov_algorithm; // Default FOV algorithm (from mcrfpy.default_fov)
int fov_radius; // Default FOV radius
// #142 - Grid cell mouse events
std::unique_ptr<PyClickCallable> on_cell_enter_callable;
std::unique_ptr<PyClickCallable> on_cell_exit_callable;
@ -149,6 +153,10 @@ public:
static int set_perspective(PyUIGridObject* self, PyObject* value, void* closure);
static PyObject* get_perspective_enabled(PyUIGridObject* self, void* closure);
static int set_perspective_enabled(PyUIGridObject* self, PyObject* value, void* closure);
static PyObject* get_fov(PyUIGridObject* self, void* closure);
static int set_fov(PyUIGridObject* self, PyObject* value, void* closure);
static PyObject* get_fov_radius(PyUIGridObject* self, void* closure);
static int set_fov_radius(PyUIGridObject* self, PyObject* value, void* closure);
static PyObject* py_at(PyUIGridObject* self, PyObject* args, PyObject* kwds);
static PyObject* py_compute_fov(PyUIGridObject* self, PyObject* args, PyObject* kwds);
static PyObject* py_is_in_fov(PyUIGridObject* self, PyObject* args);