Metadata-Version: 2.2
Name: ecs-cub
Version: 0.1.11
Summary: An Entity Component System (ECS) package for Python with a C++26 core.
Author-Email: chaz <bright.lid5647@fastmail.com>
Requires-Python: >=3.15
Requires-Dist: fond>=0.3.19
Description-Content-Type: text/markdown

# ecs-cub

A high-performance Entity Component System with a C++26 core and native CPython 3.15 bindings.

> ⚠️ Research project — not production ready. We're exploring, not shipping.

---

## Features

- **Registry** — one native Python object owns entities, systems, queries, tags, groups, signals, and pub/sub
- **Entities** — lightweight integer IDs with freelist reuse and optional generation-checked `Entity` handles
- **Components** — any Python object, indexed by its exact type
- **Queries** — reusable query signatures, exclusion filters (`Exclude(Dead)`), and `NOT_ANY(A, B, C)` NOR semantics
- **Systems** — push model (ECS calls your `update()`) or pull model (you ask for results when you want them); opt out of entity IDs when you don't need them
- **Tags** — unique 1:1 string → entity mapping, O(1) lookup
- **Groups** — 1:many grouping, entities can belong to multiple groups simultaneously
- **Events** — signals (1:1 handler) and pub/sub (1:many subscribers); internal lifecycle events auto-published for entity/component changes
- **Resources** — native exact-type storage owned by the registry, plus explicitly process-wide resources
- **Deferred kills** — `kill_entity()` is deferred by default to prevent iterator invalidation during system updates
- **Marker components** — filter by presence without passing the component into results, saving allocations per entity

---

## Performance

- **65MB** memory for 1,000,000 entities
- O(1) entity creation, component add/remove, tag and group lookups
- 32-bit bitmask signatures for fast system matching
- Sparse sets for component storage

Resource storage has a focused benchmark comparing the native registry, the historical Python resource API, and a direct
dictionary. It rotates measurement order, checks stored identities before timing, and reports median nanoseconds across
exact-type stores containing 1, 32, and 128 resources.

```bash
mask benchmark-resources
mask benchmark-resources 100000 5  # iterations, rounds
```

Use `python benchmarks/resource_storage.py --help` for custom store sizes and warmup counts. The benchmark is descriptive;
it does not impose performance thresholds on CI.

For CPython 3.15 sampling profiles of the Python workload around the native resource implementation:

```bash
mask profile-resources                 # mixed workload for 15 seconds
mask profile-resources lookup 30       # lookup-only workload for 30 seconds
mask profile-resources mutation 30
mask profile-resources bulk 30
```

The profiling command uses CPU-mode sampling at 5 kHz with opcode and native-frame markers. It writes an uncompressed
binary profile and replays it as both `/tmp/ecs-cub-resources-<workload>.html` and
`/tmp/ecs-cub-resources-<workload>-heatmap/index.html`. The flamegraph is useful for call-stack-heavy workloads such as
`mixed`; the opcode heatmap gives a clearer view of tight loops such as `bulk`. The profiler's native markers are opaque
boundaries rather than symbolized C++ stacks. Sampling them on macOS requires `sudo`; the workload itself is available
without elevated privileges through `python -m benchmarks.profile_resources --help`.

Use Instruments Time Profiler when the C++ implementation itself is the target:

```bash
mask profile-resources-native bulk 30
```

This writes a uniquely named `.trace` under `/tmp` and prints both its path and the command to open it. The extension
contains native symbols, so Time Profiler can attribute samples inside the resource operations; optimization and inlining
may still merge small functions into their callers.

---

## Features

### Entities

```python
from ecs_cub import Health, Inventory, Position, Velocity, registry

# Lightweight integer IDs
entity_id = registry.create_entity(Position(0, 0), Velocity(1, 0))

# Or a generation-checked wrapper that cannot alias a recycled entity ID
player = registry.create_entity_obj(Position(0, 0), Health(100))
player.tag("player")
player.add_component(Inventory())
player.kill()
```

IDs are reused via a freelist (LIFO). Max 1,048,576 entities by default, configurable at compile time.

---

### Components

```python
from fond import struct

@struct(slots=True)
class Position:
    x: float
    y: float
```

Components are identified by their exact Python type. They can be ordinary classes, slotted dataclasses, Fond `Struct`
records, or any other Python object; no ECS base class or metaclass is required.

---

### Queries

```python
from ecs_cub import Exclude, Position, Velocity, registry

query = registry.create_query(Position, Velocity)
for entity_id, (pos, vel) in registry.get_components(query):
    pos.x += vel.dx

# Exclusion — entities with Position but NOT Dead
query = registry.create_query(Position, Exclude(Dead))
```

---

### Systems

Two patterns, pick what fits:

```python
from ecs_cub import Position, SystemBase, Velocity, registry

# Push model — ECS calls update() for you
class MovementSystem(SystemBase):
    required_components = (Position, Velocity)

    def update(self, results, dt):
        for entity_id, (pos, vel) in results:
            pos.x += vel.dx * dt

registry.world_update(dt=1 / 60)

# Pull model — you ask for results when you want them
sys_idx = registry.register_system(Position, Velocity)
results = registry.get_system_results(sys_idx)
```

Skip entity IDs when you don't need them:

```python
class DecaySystem(SystemBase):
    required_components = (Health,)
    include_entity_id = False  # Skips Py_INCREF per entity — faster
```

---

### Tags & Groups

```python
# Tags — 1:1 unique mapping
registry.tag_entity(entity_id, "player")
player_id = registry.get_entity_by_tag("player")

# Groups — 1:many, entities can belong to multiple groups
registry.group_entity(entity_id, "enemies")
registry.group_entity(entity_id, "bosses")  # same entity, two groups
enemies = registry.get_entities_by_group("enemies")
```

---

### Events & Pub/Sub

```python
# Signals — 1:1 handler
registry.connect("player_died", on_player_death)
registry.fire("player_died", player_id)

# Pub/Sub — 1:many subscribers
registry.subscribe("damage_dealt", log_damage)
registry.subscribe("damage_dealt", update_ui)
registry.publish("damage_dealt", entity_id, amount)
```

Internal lifecycle events are auto-published on `_entity:created`, `_entity:killed`, `_component:added`, and `_component:removed`.

`Registry()` returns the same canonical object as `registry`; ecs-cub does not create a second hidden world. The historical
free functions remain compatibility aliases to these bound methods.

---

### Resources

Resources are indexed by their exact Python type in a bounded native open-addressing store. Registry-local and
process-global storage each accept at most `MAX_RESOURCES` (128) exact types. `find_resource()` is the direct required
path and raises `KeyError` when a resource is absent; `get_resource()` is the optional path and returns `None`.

```python
from fond import struct

from ecs_cub.api import find_resource, set_resource


@struct(slots=True)
class FrameClock:
    delta_time: float = 0.0


clock = FrameClock(delta_time=0.016)
set_resource(clock)

dt = find_resource(FrameClock).delta_time
```

There is one resource slot per exact type, so setting another `FrameClock` replaces the existing value without consuming
another capacity slot. Passing a class instead of an instance default-constructs it with no arguments.

Process-wide resources survive `clear_database()` for things like input state or configuration:

```python
from ecs_cub.api import find_global_resource, set_global_resource


@struct(slots=True)
class InputState:
    jump: bool = False


set_global_resource(InputState)
input_state = find_global_resource(InputState)
```

---

### Deferred Kills

```python
registry.kill_entity(entity_id)                  # Deferred — safe during system iteration
registry.kill_entity(entity_id, immediate=True)  # Immediate — use outside systems
```

---

## Installation

```bash
uv sync
mask clean_and_build
```

Requires Python 3.15+ and a C++26 compiler.

## Native C++ build

The public C++ API lives under `src/ecs_cub/include` and is consumed as, for example,
`#include <ecs_cub/registry.hpp>`. CMake consumers that add this repository as a subdirectory can link the
`ecs_cub::ecs_cub` target.

An installed package exposes the same native paths through Python:

```python
import ecs_cub

ecs_cub.get_include()      # Public C++ include directories
ecs_cub.get_libs()         # Built Python extension files
ecs_cub.get_cmake_dir()    # Directory containing EcsCubTarget.cmake
```

The CLI prints shell-friendly equivalents:

```bash
ecs-cub includes           # -I/path/to/ecs_cub/include
ecs-cub includes --path-only
ecs-cub libs               # One built extension path per line
ecs-cub cmake-dir
```

To consume an installed wheel from CMake:

```cmake
execute_process(
    COMMAND "${Python_EXECUTABLE}" -c "import ecs_cub; print(ecs_cub.get_cmake_dir())"
    OUTPUT_VARIABLE ECS_CUB_CMAKE_DIR
    OUTPUT_STRIP_TRAILING_WHITESPACE
    COMMAND_ERROR_IS_FATAL ANY
)
include("${ECS_CUB_CMAKE_DIR}/EcsCubTarget.cmake")
target_link_libraries(app PRIVATE ecs_cub::ecs_cub)
```

For a standalone Clang build against the sibling Fond checkout:

```bash
cmake -S . -B build-cmake \
    -DCMAKE_CXX_COMPILER=clang++
cmake --build build-cmake --parallel
ctest --test-dir build-cmake --output-on-failure
```

Set `FOND_ROOT` when Fond is somewhere other than `../fond`. The CMake-built Python extension is written to
`<build>/python/ecs_cub/api`; pass `-DECS_CUB_BUILD_PYTHON_MODULE=OFF` when only the native library is needed. Wheel builds
place their extension behind the same `ecs_cub.api` front door.

Enable diagnostic logging and strict Python callback errors with
`-DECS_CUB_DEBUG_MODE=ON -DECS_CUB_VERBOSE_LOGGING=ON -DECS_CUB_STRICT=ON`. The equivalent wheel workflow is
`mask debug_build`.

The native shutdown latch can be polled without running application logic inside a signal handler:

```python
import signal

from ecs_cub.api import install_shutdown_signal, restore_shutdown_signal, shutdown_requested


install_shutdown_signal(signal.SIGTERM)
try:
    while not shutdown_requested():
        run_frame()
finally:
    restore_shutdown_signal(signal.SIGTERM)
```

`consume_shutdown_request()` atomically reads and clears the latch. `signal_shutdown` is also compatible with
`signal.signal()` when Python-managed signal dispatch is preferred.
