Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 43 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,49 @@ Complete technical reference organized by modules:
- Physics (CollisionSystem, CollisionTypes)
- UI (UIElement, UIButton, UILabel, Layouts)

### Examples
- Space Invaders: Complete game analysis
### Examples (Game Samples)
Documentación de los juegos y demos incluidos en [PixelRoot32 Game Samples](https://github.com/Gperez88/PixelRoot32-Game-Samples):

| Ejemplo | Descripción | Motor / características |
|--------|-------------|---------------------------|
| **Pong** | Clásico con física y colisiones | PhysicsActor, Audio (PICO8) |
| **BrickBreaker** | Estilo Breakout, partículas | PhysicsActor, ParticleEmitter, Audio (GBC) |
| **Snake** | Juego en rejilla, pool de entidades | Entity pooling, rejilla discreta |
| **Space Invaders** | Shooter completo | 1bpp sprites, colisiones swept, música dinámica, starfield |
| **TicTacToe** | Turnos y IA simple | UI, lógica de tablero |
| **Metroidvania** | Plataformas 2D, tilemap multicapa | 4bpp sprites, TileMap4bpp, colisión tile-based, escaleras, optimizaciones ESP32 (sin cámara/scroll) |
| **CameraDemo** | Scroll horizontal y parallax | Camera2D, plataformas, capas |
| **SpritesDemo** | Formatos 2bpp y 4bpp | Sprite2bpp, Sprite4bpp, animación |
| **TileMapDemo** | Tilemaps 4bpp | TileMap4bpp, viewport culling |

### Herramientas e implementaciones del motor

**Herramientas usadas en los ejemplos:**

| Herramienta | Uso | Repositorio / notas |
|-------------|-----|----------------------|
| **PixelRoot32 Sprite Compiler** | Convierte PNG a datos 1bpp/2bpp/4bpp (C++ headers) | PixelRoot32 Sprite Compiler (Python) |
| **PixelRoot32 Tilemap Editor** | Edición visual de tilemaps, export a C++ | PixelRoot32 Tilemap Editor (opcional; algunos fondos se generan en código) |

**Implementaciones del motor en Game Samples:**

| Componente | ESP32 | Native (PC) |
|------------|--------|-------------|
| **Display** | TFT_eSPI (ST7789 240×240), buffer + DMA | SDL2, ventana 240×240 |
| **Input** | 5 botones digitales (InputConfig) | Teclado → scancodes |
| **Audio** | DAC interno o I2S (ESP32_DAC / ESP32_I2S) | SDL2 audio |
| **Sprites** | 1bpp (siempre), 2bpp/4bpp con `PIXELROOT32_ENABLE_*` | Igual |
| **Escenas** | Scene, SceneArena (arena opcional), MAX_ENTITIES configurable | Igual |

**Opciones de build relevantes** (en `platformio.ini` de Game Samples):

- `PIXELROOT32_ENABLE_2BPP_SPRITES` / `PIXELROOT32_ENABLE_4BPP_SPRITES`: sprites 2bpp y 4bpp.
- `PIXELROOT32_ENABLE_SCENE_ARENA`: asignación desde arena en escena (menos `new`/`delete`).
- `MAX_ENTITIES`, `MAX_LAYERS`: límites de entidades y capas de render.

### Tools
- Sprite Compiler: Installation, usage, and advanced features
- **Sprite Compiler**: Overview, instalación, guía de uso y características avanzadas (1bpp, 2bpp, 4bpp).
- **Tilemap Editor**: Edición visual de tilemaps y export a C++ (referencia en docs cuando esté habilitada).

### Resources
- Available Tools
Expand Down Expand Up @@ -177,9 +215,8 @@ PixelRoot32-Docs/
│ │ ├── game_development/ # Core game development
│ │ ├── advanced_graphics/ # Advanced graphics
│ │ └── optimization/ # Optimization guides
│ ├── reference/ # Reference documentation
│ ├── reference/ # Reference documentation (incl. Game Examples Guide)
│ ├── api_reference/ # Complete API reference
│ ├── examples/ # Game examples
│ ├── tools/ # Tool documentation
│ └── resources/ # Resources (FAQ, troubleshooting, etc.)
├── site/ # Generated HTML (git-ignored)
Expand All @@ -201,4 +238,4 @@ See individual source files for license details.

---

**Last updated:** January 23, 2026
**Last updated:** January 29, 2026
26 changes: 26 additions & 0 deletions docs/api_reference/core/engine.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,32 @@ void playMusic() {
}
```

## Optional: FPS overlay

When the engine is built with the preprocessor define **`PIXELROOT32_ENABLE_FPS_DISPLAY`**, an on-screen FPS counter is drawn each frame.

**Behavior:**

- A green text string `"FPS xxx"` is drawn in the top-right area (position from `Renderer::getWidth()` and a fixed Y offset).
- The value is derived from frame delta time (FPS = 1000 / deltaTime ms), clamped to 0–999.

**Performance:**

- The numeric value is recalculated and formatted only every **8 frames**; the cached string is drawn every frame to keep the overlay visible without extra per-frame cost (division and `snprintf` are done at most once every 8 frames).

**How to enable:**

In `platformio.ini`, add to your environment's `build_flags`:

```ini
build_flags =
-D PIXELROOT32_ENABLE_FPS_DISPLAY
```

No code changes are required; the overlay is drawn automatically after the scene in `Engine::draw()`. The implementation uses the private method `drawFpsOverlay(Renderer& r)`, which is only compiled when the define is set.

See also: [Performance Tuning - Profiling](../../manual/optimization/performance_tuning.md) and [Platforms and Drivers - Build flags](../../manual/optimization/platforms_and_drivers.md).

## Usage Example

```cpp
Expand Down
37 changes: 25 additions & 12 deletions docs/api_reference/core/scene.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Represents a game level or screen containing entities.

A `Scene` manages a collection of Entities and a CollisionSystem. It is responsible for updating and drawing all entities it contains. Scenes provide lifecycle hooks (`init()`, `update()`, `draw()`) to manage gameplay segments.

Scenes are the primary organizational unit in PixelRoot32, similar to levels or screens in other game engines. Each scene can contain up to `MAX_ENTITIES` (32) entities.
Scenes are the primary organizational unit in PixelRoot32, similar to levels or screens in other game engines. Each scene can contain up to `MAX_ENTITIES` (default 32; overridable via compiler flags) entities, and drawing uses up to `MAX_LAYERS` (default 3; overridable) render layers.

## Namespace

Expand Down Expand Up @@ -154,7 +154,7 @@ Adds an entity to the scene.

**Notes:**
- Entities are added to an internal queue
- Maximum of `MAX_ENTITIES` (32) entities per scene
- Maximum of `MAX_ENTITIES` (default 32; [overridable](#overriding-scene-limits-max_layers--max_entities)) entities per scene
- If the limit is reached, the entity may not be added (check return value if available)
- Entities are updated and drawn in the order they were added
- The entity's lifetime is managed by the scene (do not delete manually while in scene)
Expand Down Expand Up @@ -226,7 +226,7 @@ Queue of entities in the scene. Accessible to derived classes for custom entity
**Type:** `ArduinoQueue<Entity*>`

**Notes:**
- Maximum capacity: `MAX_ENTITIES` (32)
- Maximum capacity: `MAX_ENTITIES` (default 32; [overridable](#overriding-scene-limits-max_layers--max_entities))
- Direct access allows custom iteration or filtering
- Use with caution: modifying while iterating may cause issues

Expand All @@ -241,17 +241,30 @@ System to handle collisions between actors. Accessible to derived classes for cu
- Uses collision layers and masks for filtering
- Can be accessed for custom collision queries

## MAX_ENTITIES Constant
## Overriding scene limits (MAX_LAYERS / MAX_ENTITIES)

The maximum number of entities allowed per scene.
The engine defines default limits in `core/Scene.h`: **MAX_LAYERS** (default 3) and **MAX_ENTITIES** (default 32). These are guarded with `#ifndef`, so you can override them from your project without modifying the engine.

**Value:** `32`
!!! warning "ESP32 platform limitation"
The default of **3** for `MAX_LAYERS` is due to ESP32 platform constraints (memory and draw-loop cost). On native/PC you can safely use a higher value; on ESP32, increasing it may affect performance or memory.

**Notes:**
- Hard limit: cannot be changed without modifying engine code
- Includes all entity types: actors, UI elements, particles, etc.
- Plan your entity usage carefully
- Use object pooling to reuse entities instead of creating new ones
### Option A: Compiler flags (recommended)

In your project (e.g. in `platformio.ini`), add the defines to `build_flags` for the environment you use:

```ini
build_flags =
-DMAX_LAYERS=5
-DMAX_ENTITIES=64
```

The compiler defines `MAX_LAYERS` and `MAX_ENTITIES` before processing any `.cpp` file. Because `Scene.h` uses `#ifndef MAX_LAYERS` / `#ifndef MAX_ENTITIES`, it will not redefine them and your values will be used.

**Effect:**
- **MAX_LAYERS**: Number of render layers drawn in `Scene::draw()` (layer 0 = background, 1+ = sprite context). Increasing this allows more distinct draw layers (e.g. background, platforms, gameplay, foreground, UI).
- **MAX_ENTITIES**: On Arduino, the capacity of the scene entity queue when constructed with this value. On native (mock queue), the value is ignored (unbounded).

See also: [Platforms and Drivers - Scene limits](../../manual/optimization/platforms_and_drivers.md#scene-limits-max_layers--max_entities).

## Usage Example

Expand Down Expand Up @@ -305,7 +318,7 @@ public:

## Performance Considerations

- **Entity limit**: `MAX_ENTITIES = 32` is a hard limit; plan accordingly
- **Entity limit**: `MAX_ENTITIES` (default 32) can be overridden via [compiler flags](#overriding-scene-limits-max_layers--max_entities); plan accordingly
- **Add/Remove**: Frequent add/remove operations can be expensive; use object pooling
- **Update order**: Entities are updated in add order; consider order for dependencies
- **Collision checks**: CollisionSystem automatically handles actor collisions efficiently
Expand Down
4 changes: 2 additions & 2 deletions docs/api_reference/graphics/renderer.md
Original file line number Diff line number Diff line change
Expand Up @@ -537,8 +537,8 @@ void draw(Renderer& renderer) override {
- **Integer-only math**: All operations use integer arithmetic for ESP32 efficiency
- **Sprite storage**: Store sprite data in flash (const/constexpr) for best performance
- **Batch operations**: Group similar draw calls together
- **Tilemaps**: Use tilemaps for backgrounds instead of individual sprites
- **Viewport culling**: Only draw what's visible on screen
- **Tilemaps**: Dibuja un mapa de tiles completo. Implementa viewport culling automático y caché de paleta para máximo rendimiento.
- **Sprites 2bpp/4bpp**: Optimizado para ESP32 (IRAM + acceso de 16 bits).

## ESP32 Considerations

Expand Down
4 changes: 2 additions & 2 deletions docs/api_reference/graphics/sprite.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ static const MultiSprite PLAYER_MULTISPRITE = {

### Members

- `const uint8_t* data`: Packed 2bpp data
- `const uint16_t* data`: Datos empaquetados (4 píxeles por cada 8 bits, alineados a 16 bits)
- `const Color* palette`: Local palette (4 colors)
- `uint8_t width`: Sprite width
- `uint8_t height`: Sprite height
Expand All @@ -165,7 +165,7 @@ static const MultiSprite PLAYER_MULTISPRITE = {

### Members

- `const uint8_t* data`: Packed 4bpp data
- `const uint16_t* data`: Datos empaquetados (2 píxeles por cada 8 bits, alineados a 16 bits)
- `const Color* palette`: Local palette (16 colors)
- `uint8_t width`: Sprite width
- `uint8_t height`: Sprite height
Expand Down
Loading
Loading