Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

7.9 KB
Raw Blame
"""Component resolvers for compiled systems (AotComponents.generated.hpp/.cpp).

A compiled system calls the engine zero times, so everything it reads has to be
in memory before the call. `AotHost.hpp` asks the caller for one `ComponentAt`
per component — "supplied by the layer that knows its TYPE" — and this is that
layer: the same reflection the bindings come from, turned into a table from the
NAME a manifest uses to the pointer a Registry has.

Two artifacts on purpose. The definitions need every component's header, and a
consumer that included them would pay for the whole engine to ask where one
component is; the declaration needs only `AotHost.hpp` and a forward-declared
Registry.

Resolved once per query and called per entity, not looked up per entity: a
strcmp chain inside the row loop would be paid on exactly the path AOT exists
to make cheap.

The second table answers the other question a query asks — WHO has the
component — because a host that cannot ask it has to offer every entity as a
candidate, and then a system's cost is the size of the world rather than the
size of what it matches.
"""

from typing import List

from ..data import Component, Enum

_BANNER = [
    '// Auto-generated by EHT (aot_components) — DO NOT EDIT.',
    '// The type half of the AOT contract: a manifest names a component, and a',
    '// compiled system needs the bytes. Regenerate with `pnpm eht`.',
]


class AotComponentsGenerator:
    """Generates the name -> ComponentAt table a native host dispatches through."""

    def __init__(self, components: List[Component], enums: List[Enum]):
        self.components = components
        self.enums = enums

    def _sorted(self) -> List[Component]:
        return sorted(self.components, key=lambda c: c.name)

    def _full(self, comp: Component) -> str:
        return f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name

    @staticmethod
    def _include_path(comp: Component) -> str:
        hp = comp.header_path.replace('\\', '/')
        # The parser may hand back an absolute path, and the include has to be
        # the one a compiler's -I resolves — which is rooted at src/.
        if hp.startswith('src/'):
            return hp[len('src/'):]
        if '/src/' in hp:
            return hp[hp.rindex('/src/') + len('/src/'):]
        return hp

    def generate_header(self) -> str:
        return '\n'.join(_BANNER + [
            '#pragma once',
            '',
            '#include "esengine/aot/AotHost.hpp"',
            '',
            'namespace esengine::ecs { class Registry; }',
            '',
            'namespace esengine::aot {',
            '',
            '/**',
            ' * Where a named ENGINE component lives, for this registry.',
            ' *',
            ' * `tryGet`, never `getOrEmplace`: a resolver that created the component',
            ' * would give one to every entity the query walked, and a row is kept only',
            ' * when every component resolves — the absence IS the filter.',
            ' *',
            ' * No lazily-derived field is refreshed, because the interpreted side does',
            ' * not refresh one either and it is the oracle. A component whose fields are',
            ' * stale until a method runs cannot be read by a compiled system at all, and',
            ' * that is a subset question rather than a resolver one.',
            ' *',
            ' * An unknown name yields an EMPTY resolver: a project component lives in the',
            ' * script pool and is not this table\'s to answer for. Call it and it throws,',
            ' * so a caller must ask `isEngineComponent` first.',
            ' */',
            'ComponentAt engineComponentAt(ecs::Registry& registry, const char* name);',
            '',
            '/**',
            ' * WHO has that component, for a caller narrowing a query to its shortest',
            ' * column.',
            ' *',
            ' * The resolver above answers per entity and can only be asked about one',
            ' * that is already a candidate; this is where candidates come FROM. A host',
            ' * without it must offer every entity, and then what a compiled system',
            ' * costs is the size of the world instead of the size of what it matches.',
            ' *',
            ' * An empty span means nobody has it — a query that matches nothing. The',
            ' * empty FUNCTION means this table does not answer for the name, which is',
            ' * a different answer and the caller must not narrow on it.',
            ' */',
            'CandidatesOf engineComponentCandidates(ecs::Registry& registry, const char* name);',
            '',
            '/** Whether this table answers for that name, without building a resolver. */',
            'bool isEngineComponent(const char* name);',
            '',
            '}  // namespace esengine::aot',
            '',
        ])

    def generate_source(self) -> str:
        components = self._sorted()
        lines = list(_BANNER)
        lines += [
            '#include "esengine/aot/AotComponents.generated.hpp"',
            '',
            '#include <cstdint>',
            '#include <cstring>',
            '#include <span>',
            '',
            '#include "esengine/ecs/Entity.hpp"',
            '#include "esengine/ecs/Registry.hpp"',
        ]
        seen = set()
        for comp in components:
            hp = self._include_path(comp)
            if hp and hp not in seen:
                seen.add(hp)
                lines.append(f'#include "{hp}"')
        lines += [
            '',
            'namespace esengine::aot {',
            'namespace {',
            '',
            '/**',
            ' * The dense column of a pool, as raw ids.',
            ' *',
            ' * `Entity` is a four-byte struct whose only member is that id, and',
            ' * Types.hpp static_asserts the size for exactly this — a dense array of',
            ' * them IS an array of ids. Copying it per frame would put the cost back',
            ' * where narrowing took it from.',
            ' */',
            'Candidates denseAsIds(std::span<const Entity> dense) {',
            '    static_assert(sizeof(Entity) == sizeof(std::uint32_t),',
            '                  "a dense entity array is only an id array while these agree");',
            '    return std::span<const std::uint32_t>(',
            '        reinterpret_cast<const std::uint32_t*>(dense.data()), dense.size());',
            '}',
            '',
            '}  // namespace',
            '',
            'ComponentAt engineComponentAt(ecs::Registry& registry, const char* name) {',
        ]
        for comp in components:
            full = self._full(comp)
            lines.append(f'    if (std::strcmp(name, "{comp.name}") == 0) {{')
            lines.append('        return [&registry](std::uint32_t raw) -> void* {')
            lines.append(f'            return registry.tryGet<{full}>(Entity::fromRaw(raw));')
            lines.append('        };')
            lines.append('    }')
        lines += [
            '    return {};',
            '}',
            '',
            'CandidatesOf engineComponentCandidates(ecs::Registry& registry, const char* name) {',
        ]
        for comp in components:
            full = self._full(comp)
            lines.append(f'    if (std::strcmp(name, "{comp.name}") == 0) {{')
            lines.append('        return [&registry]() -> Candidates {')
            lines.append(f'            return denseAsIds(registry.entitiesWith<{full}>());')
            lines.append('        };')
            lines.append('    }')
        lines += [
            '    return {};',
            '}',
            '',
            'bool isEngineComponent(const char* name) {',
        ]
        for comp in components:
            lines.append(f'    if (std::strcmp(name, "{comp.name}") == 0) return true;')
        lines += [
            '    return false;',
            '}',
            '',
            '}  // namespace esengine::aot',
            '',
        ]
        return '\n'.join(lines)