Command Palette

Search for a command to run...

Назад к скиллам
скилл № 34453

ecs-pattern

Use when the user asks about ECS, entity component system design, archetype storage, chunk iteration, sparse sets, structural changes, ECS scheduling, Bevy…

БесплатноБез исполняемых скриптов
j4flmaoот j4flmao★ 47 звёзд на GitHub

Установить ecs-pattern в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Об этом скилле

Entity Component System (ECS) — Deep Engineering Guide

Purpose

ECS is the dominant data-oriented architecture for modern game engines (Unity Entities/DOTS, Bevy, Unreal Mass, Overwatch's engine, flecs, EnTT — used in Minecraft Bedrock). It replaces scattered OOP objects with contiguous arrays of plain data so tens of thousands of entities update at 60 FPS on cache-limited CPUs.

Agent Protocol

Trigger

"ecs pattern", "archetype storage", "chunk iteration", "ecs scheduling", "bevy ecs", "entt", "flecs", "unity dots architecture".

Input Context

  • ECS library/engine and version
  • Entity counts, component churn, thread count
  • Profiler data if tuning

Output Artifact

ECS design or code with memory-layout reasoning. No file unless requested.

Response Format

Library: {EnTT | flecs | Bevy | Unity Entities | custom}
Layout: {archetypes / chunk size}
Systems: {order, read/write sets}
Code: {snippet}

1. Why ECS Exists: The Performance Rationale

1.1 The OOP Cache Problem

A classic OOP hierarchy:

class GameObject {
public:
    virtual void Update() = 0;
    glm::vec3 m_Position;
    float m_Health;
    std::vector<GameObject*> m_Children;
};

class Enemy : public GameObject {
public:
    void Update() override;
private:
    std::string m_Name;
    float m_Speed;
};

Each Enemy is heap-allocated individually. The pointer-chasing heap layout scatters m_Position across DRAM. Iterating 10,000 enemies typically costs at least one cache miss per object, and the CPU spends most of the loop waiting on memory.

Impact: once the working set exceeds cache, pointer-chasing iteration is typically an order of magnitude or more slower than streaming over contiguous arrays — measure your own case with a microbenchmark and hardware counters (cache misses) before and after.

1.2 The Data-Oriented Answer

OOP layout (heap):          [Enemy0][Enemy1][Enemy2] --- scattered pages ---
Data layout (SoA):          Position[].x = {2.1, 9.4, 5.0, ...}
                            Position[].y = {0.0, 3.3, 8.2, ...}
                            Health[]     = {100, 42, 7, ...}

1.3 The Three Pillars

Term Definition Example
Entity A lightweight opaque ID (integer). No data, no behavior. Entity(42) is just uint32_t 42
Component A plain-data struct (POD, no virtuals, no methods beyond trivial accessors) struct Position { float x, y, z; }
System Pure logic that reads/writes components for every matched entity MovementSystem does pos += vel * dt

1.4 Why This is Faster — Cache Lines

A cache line is 64 bytes on x86 and most ARM cores (128 bytes on Apple silicon). With SoA, a Position array of float3 (12 bytes) packs five positions per line, and the Velocity array streams in parallel; every byte fetched is used and the hardware prefetcher sees a linear pattern. With scattered objects, each entity costs at least one line fetch, mostly filled with cold fields.

%%{init: {"theme": "default", "flowchart": {"useMaxWidth": true}}}%%
flowchart TD
    subgraph RAM ["DRAM: Component Arrays (SoA)"]
        A["Position[0..N]  (contiguous)"]
        B["Velocity[0..N]  (contiguous)"]
        C["Health[0..N]  (contiguous)"]
    end
    subgraph CORE ["CPU L1/L2 Cache"]
        D["Cache Line: 64B"]
        E["prefetch next line"]
    end
    F["Movement System"] -->|"iterates pos[i]+=vel[i]"| A
    F --> B
    F -->|"next element already in cache"| D
    D --> E

2. Storage Models

2.1 Naïve: Dictionary-of-Component-Arrays (AoS-friendly)

The simplest ECS stores each component type in one flat array, where array index == entity ID:

struct PositionArray { std::vector<Vec3> data; };      // data[entity] = position
struct HealthArray   { std::vector<float> data; };      // data[entity] = health
  • Pros: minimal implementation, easy to reason about.
  • Cons: index collisions when entities are destroyed (holes), stale IDs trigger undefined behavior, and unused components occupy memory slots.

2.2 Sparse Set

The canonical solution to sparse entity IDs. Two parallel arrays:

template<typename T>
class SparseSet {
    std::vector<T>        dense;    // component payload, packed
    std::vector<uint32_t> sparse;   // entity index -> index into dense
    std::vector<Entity>   entities; // dense index -> entity
public:
    void add(Entity e, T comp) {
        if (e.id >= sparse.size()) sparse.resize(e.id + 1);
        sparse[e.id] = static_cast<uint32_t>(dense.size());
        dense.push_back(std::move(comp));
        entities.push_back(e);
    }
    void remove(Entity e) {
        const uint32_t idx = sparse[e.id];
        const Entity last = entities.back();
        dense[idx] = std::move(dense.back());     // swap-remove keeps dense packed
        entities[idx] = last;
        sparse[last.id] = idx;
        dense.pop_back();
        entities.pop_back();
Полный SKILL.md на GitHub

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

  • references/archetype-storage-deep-dive.md
  • references/bevy-ecs-patterns.md
  • references/ecs-architecture.md
  • references/ecs-netcode.md
  • references/entt-and-flecs.md
  • references/merged-ecs-architecture.md
  • references/system-scheduling-pipelines.md
  • references/unity-dots-in-practice.md

FAQ

Что делает скилл ecs-pattern?

Use when the user asks about ECS, entity component system design, archetype storage, chunk iteration, sparse sets, structural changes, ECS scheduling, Bevy ECS, EnTT or flecs. Produces ECS storage, query and scheduling design with trade-offs. Not for Unity Entities and Burst API details (use unity-csharp).

Как установить скилл ecs-pattern?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл ecs-pattern запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить ecs-pattern с