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.

32.7 KB
Raw Blame
"""Editor API generator — string-dispatched component CRUD and property access.

Generates EditorAPI.generated.cpp with:
- Component name listing and JSON schema export
- String-dispatched add/remove/has component
- String-dispatched property get/set by component+field path
"""

import hashlib
from typing import List, Set
from ..data import Component, Enum, HIERARCHY_COMPONENTS, WRITE_HOOKS
from ..type_system import TypeSystem
from ..field_utils import get_sub_components, get_editor_type, is_color_field


def compute_schema_hash(components: List[Component]) -> str:
    """Stable sha256 over (component, field, type, annotations), truncated."""
    h = hashlib.sha256()
    for comp in sorted(components, key=lambda c: (c.namespace or '', c.name)):
        h.update(f'{comp.namespace or ""}::{comp.name}|'.encode('utf-8'))
        for prop in comp.properties:
            annotations = ','.join(sorted(prop.annotations.keys())) if prop.annotations else ''
            h.update(f'{prop.name}:{prop.cpp_type}:{annotations};'.encode('utf-8'))
        h.update(b'\n')
    return h.hexdigest()[:16]


# Components whose non-scalar field changes require a runtime-side
# invalidation flag to be flipped so the owning system re-runs its load
# path on the next tick. Expressed as raw C++ appended after the field
# assignment in editor_setString. When a proper ES_PROPERTY(invalidates=)
# annotation exists this table should go away.
_STRING_SET_SIDE_EFFECTS = {
    'SpineAnimation': 'c.needsReload = true;',
}


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

    def generate(self) -> str:
        lines = self._gen_header()
        lines.extend(self._gen_component_names())
        lines.extend(self._gen_component_schema())
        lines.extend(self._gen_add_remove_has())
        lines.extend(self._gen_get_components())
        lines.extend(self._gen_set_float())
        lines.extend(self._gen_get_float())
        lines.extend(self._gen_set_int())
        lines.extend(self._gen_get_int())
        lines.extend(self._gen_set_bool())
        lines.extend(self._gen_get_bool())
        lines.extend(self._gen_set_string())
        lines.extend(self._gen_get_string())
        lines.extend(self._gen_embind())
        lines.append('')
        return '\n'.join(lines)

    def _gen_header(self) -> List[str]:
        schema_hash = compute_schema_hash(self.components)
        lines = [
            '/**',
            ' * @file    EditorAPI.generated.cpp',
            ' * @brief   Auto-generated editor API with string-dispatched component access',
            ' * @details Generated by EHT - DO NOT EDIT',
            f' * @schema_hash  {schema_hash}',
            ' */',
            '',
            f'#define ES_EDITOR_API_SCHEMA_HASH "{schema_hash}"',
            '',
            '#include <emscripten/bind.h>',
            '#include <string>',
            '#include <vector>',
            '#include "../ecs/Registry.hpp"',
        ]

        headers: Set[str] = set()
        for comp in self.components:
            if comp.header_path and 'src/esengine/' in comp.header_path:
                rel = '../' + comp.header_path.replace('\\', '/').split('src/esengine/')[-1]
                headers.add(f'#include "{rel}"')
        # Enums too: one declared away from any component is registered by
        # its C++ type all the same, and without this the TU cannot name it.
        for enum in self.enums:
            if enum.header_path and 'src/esengine/' in enum.header_path:
                rel = '../' + enum.header_path.replace('\\', '/').split('src/esengine/')[-1]
                headers.add(f'#include "{rel}"')
        lines.extend(sorted(headers))

        lines.extend([
            '#include "../ecs/TransformSystem.hpp"',
            '#include <glm/gtc/quaternion.hpp>',
            '',
            'using namespace esengine;',
            'using namespace esengine::ecs;',
            '',
            'namespace {',
            '',
            '// Euler (degrees) ↔ Quaternion conversion helpers',
            'inline glm::vec3 quatToEulerDeg(const glm::quat& q) {',
            '    return glm::degrees(glm::eulerAngles(q));',
            '}',
            'inline glm::quat eulerDegToQuat(const glm::vec3& deg) {',
            '    return glm::quat(glm::radians(deg));',
            '}',
            '',
        ])
        return lines

    def _gen_component_names(self) -> List[str]:
        lines = [
            '// ── Component Name List ──',
            '',
            'std::vector<std::string> editor_getComponentNames() {',
            '    return {',
        ]
        for comp in self.components:
            if comp.properties:
                lines.append(f'        "{comp.name}",')
        lines.extend([
            '    };',
            '}',
            '',
        ])
        return lines

    def _gen_component_schema(self) -> List[str]:
        """Generate JSON schema for each component's editable fields."""
        lines = [
            '// ── Component Schema (JSON) ──',
            '',
            'std::string editor_getComponentSchema(const std::string& name) {',
        ]

        first = True
        for comp in self.components:
            if not comp.properties:
                continue

            cond = 'if' if first else '} else if'
            first = False
            lines.append(f'    {cond} (name == "{comp.name}") {{')
            lines.append(f'        return R"JSON([')

            fields = self._get_all_fields(comp)
            for i, (key, editor_type, group, enum_values) in enumerate(fields):
                comma = ',' if i < len(fields) - 1 else ''
                if enum_values:
                    vals_json = '","'.join(enum_values)
                    lines.append(
                        f'  {{"key":"{key}","type":"{editor_type}","group":"{group}","values":["{vals_json}"]}}{comma}'
                    )
                else:
                    lines.append(
                        f'  {{"key":"{key}","type":"{editor_type}","group":"{group}"}}{comma}'
                    )

            lines.append(f'        ])JSON";')

        if not first:
            lines.append('    }')
        lines.extend([
            '    return "[]";',
            '}',
            '',
        ])
        return lines

    def _is_readonly(self, prop) -> bool:
        return 'readonly' in prop.annotations

    def _write_hook(self, comp: Component) -> List[str]:
        """What a successful set on this component has to announce, if anything.

        Emitted once per branch rather than per field: every field that reaches a
        setter is writable (readonly ones are filtered out above), so reaching the
        end of the chain already means a real write happened.
        """
        hook = WRITE_HOOKS.get(comp.name)
        return [f'        {hook}'] if hook else []

    def _get_all_fields(self, comp: Component) -> list:
        """Get all editable fields as (key, editor_type, group, enum_values) tuples."""
        fields = []
        for prop in comp.properties:
            if self._is_readonly(prop):
                continue

            editor_type = get_editor_type(prop, self.types)
            if editor_type == 'skip':
                continue

            t = self.types.clean_type(prop.cpp_type)
            subs = get_sub_components(prop, self.types)
            enum_values = self.types.get_enum_values(t) if editor_type == 'enum' else []

            if is_color_field(prop, self.types):
                for ch in ['r', 'g', 'b', 'a']:
                    fields.append((f'{prop.name}.{ch}', 'color', comp.name, []))
            elif t == 'glm::quat':
                # Quaternion: expose as Euler angles X/Y/Z (degrees) in editor
                fields.append((f'{prop.name}.x', 'float', comp.name, []))
                fields.append((f'{prop.name}.y', 'float', comp.name, []))
                fields.append((f'{prop.name}.z', 'float', comp.name, []))
            elif len(subs) == 1 and subs[0][0] == '':
                fields.append((prop.name, editor_type, comp.name, enum_values))
            else:
                sub_type = 'int' if t == 'glm::uvec2' else 'float'
                for label, _ in subs:
                    fields.append((f'{prop.name}.{label}', sub_type, comp.name, []))

        return fields

    def _gen_add_remove_has(self) -> List[str]:
        lines = [
            '// ── Add / Remove / Has Component ──',
            '',
            'bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {',
            '    auto entity = static_cast<Entity>(e);',
            '    if (!reg.valid(entity)) return false;',
        ]

        first = True
        for comp in self.components:
            if not comp.properties:
                continue
            full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
            cond = 'if' if first else '} else if'
            first = False
            lines.append(f'    {cond} (name == "{comp.name}") {{')
            if comp.name in HIERARCHY_COMPONENTS:
                # A bare Parent names no one, and TransformSystem skips anything that
                # has one — the link is made by naming a parent, not by adding this.
                lines.append(f'        return false;')
            elif WRITE_HOOKS.get(comp.name):
                # Structural, and still a composition input: a Transform added
                # under a parent is at the origin until something composes it.
                hook = WRITE_HOOKS[comp.name]
                lines.append(f'        if (!reg.has<{full}>(entity)) {{ reg.emplace<{full}>(entity); {hook} }}')
                lines.append(f'        return true;')
            else:
                lines.append(f'        if (!reg.has<{full}>(entity)) reg.emplace<{full}>(entity);')
                lines.append(f'        return true;')

        if not first:
            lines.append('    }')
        lines.extend([
            '    return false;',
            '}',
            '',
            'bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {',
            '    auto entity = static_cast<Entity>(e);',
            '    if (!reg.valid(entity)) return false;',
        ])

        first = True
        for comp in self.components:
            if not comp.properties:
                continue
            full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
            cond = 'if' if first else '} else if'
            first = False
            lines.append(f'    {cond} (name == "{comp.name}") {{')
            if comp.name == 'Parent':
                lines.append(f'        if (reg.has<{full}>(entity)) {{ esengine::ecs::setParent(reg, entity, INVALID_ENTITY); return true; }}')
            elif comp.name == 'Children':
                lines.append(f'        if (reg.has<{full}>(entity)) {{')
                lines.append(f'            const auto kids = reg.get<{full}>(entity).entities;')
                lines.append(f'            for (auto child : kids) esengine::ecs::setParent(reg, child, INVALID_ENTITY);')
                lines.append(f'            return true;')
                lines.append(f'        }}')
            else:
                lines.append(f'        if (reg.has<{full}>(entity)) {{ reg.remove<{full}>(entity); return true; }}')

        if not first:
            lines.append('    }')
        lines.extend([
            '    return false;',
            '}',
            '',
            'bool editor_hasComponent(Registry& reg, u32 e, const std::string& name) {',
            '    auto entity = static_cast<Entity>(e);',
            '    if (!reg.valid(entity)) return false;',
        ])

        for comp in self.components:
            if not comp.properties:
                continue
            full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
            lines.append(f'    if (name == "{comp.name}") return reg.has<{full}>(entity);')

        lines.extend([
            '    return false;',
            '}',
            '',
        ])
        return lines

    def _gen_get_components(self) -> List[str]:
        """Generate function to get list of component names on an entity."""
        lines = [
            '// ── Get Components on Entity ──',
            '',
            'std::vector<std::string> editor_getComponents(Registry& reg, u32 e) {',
            '    auto entity = static_cast<Entity>(e);',
            '    std::vector<std::string> result;',
            '    if (!reg.valid(entity)) return result;',
        ]

        for comp in self.components:
            if not comp.properties:
                continue
            full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
            lines.append(f'    if (reg.has<{full}>(entity)) result.push_back("{comp.name}");')

        lines.extend([
            '    return result;',
            '}',
            '',
        ])
        return lines

    def _collect_float_fields(self, comp: Component) -> list:
        """Collect (key, cpp_path) for all float-settable fields, skipping readonly."""
        float_fields = []
        for prop in comp.properties:
            if self._is_readonly(prop):
                continue
            editor_type = get_editor_type(prop, self.types)
            if editor_type == 'skip':
                continue
            t = self.types.clean_type(prop.cpp_type)

            if t == 'glm::quat':
                # Quaternion: handled separately via euler conversion
                continue
            else:
                subs = get_sub_components(prop, self.types)
                if len(subs) == 1 and subs[0][0] == '':
                    if editor_type == 'float':
                        float_fields.append((prop.name, prop.name))
                elif t != 'glm::uvec2':
                    for label, member in subs:
                        float_fields.append((f'{prop.name}.{label}', f'{prop.name}.{member}'))
        return float_fields

    def _collect_quat_fields(self, comp: Component) -> list:
        """Collect quat property names that should be exposed as euler X/Y/Z."""
        return [p.name for p in comp.properties
                if not self._is_readonly(p) and self.types.clean_type(p.cpp_type) == 'glm::quat']

    def _gen_set_float(self) -> List[str]:
        lines = [
            '// ── Set Float Property ──',
            '',
            'bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::string& field, f32 value) {',
            '    auto entity = static_cast<Entity>(e);',
            '    if (!reg.valid(entity)) return false;',
        ]

        first_comp = True
        for comp in self.components:
            if not comp.properties:
                continue
            full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
            float_fields = self._collect_float_fields(comp)
            quat_fields = self._collect_quat_fields(comp)
            if not float_fields and not quat_fields:
                continue

            cond = 'if' if first_comp else '} else if'
            first_comp = False
            lines.append(f'    {cond} (comp == "{comp.name}") {{')
            lines.append(f'        if (!reg.has<{full}>(entity)) return false;')
            # patch: an editor's write is stamped, so whatever reads changes (the renderer) sees it.
            lines.append(f'        auto& c = reg.patch<{full}>(entity);')

            idx = 0
            for key, cpp_path in float_fields:
                prefix = 'if' if idx == 0 else 'else if'
                lines.append(f'        {prefix} (field == "{key}") {{ c.{cpp_path} = value; }}')
                idx += 1

            # Quaternion fields: set euler angle then convert to quaternion
            for qname in quat_fields:
                for axis in ['x', 'y', 'z']:
                    prefix = 'if' if idx == 0 else 'else if'
                    lines.append(f'        {prefix} (field == "{qname}.{axis}") {{')
                    lines.append(f'            auto euler = quatToEulerDeg(c.{qname});')
                    lines.append(f'            euler.{axis} = value;')
                    lines.append(f'            c.{qname} = eulerDegToQuat(euler);')
                    lines.append(f'        }}')
                    idx += 1

            lines.append('        else { return false; }')
            lines.extend(self._write_hook(comp))
            lines.append('        return true;')

        if not first_comp:
            lines.append('    }')
        lines.extend([
            '    return false;',
            '}',
            '',
        ])
        return lines

    def _gen_get_float(self) -> List[str]:
        lines = [
            '// ── Get Float Property ──',
            '',
            'f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::string& field) {',
            '    auto entity = static_cast<Entity>(e);',
            '    if (!reg.valid(entity)) return 0.0f;',
        ]

        first_comp = True
        for comp in self.components:
            if not comp.properties:
                continue
            full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
            float_fields = self._collect_float_fields(comp)
            quat_fields = self._collect_quat_fields(comp)
            if not float_fields and not quat_fields:
                continue

            cond = 'if' if first_comp else '} else if'
            first_comp = False
            lines.append(f'    {cond} (comp == "{comp.name}") {{')
            lines.append(f'        if (!reg.has<{full}>(entity)) return 0.0f;')
            lines.append(f'        const auto& c = reg.get<{full}>(entity);')

            idx = 0
            for key, cpp_path in float_fields:
                prefix = 'if' if idx == 0 else 'else if'
                lines.append(f'        {prefix} (field == "{key}") {{ return c.{cpp_path}; }}')
                idx += 1

            # Quaternion fields: convert to euler and return axis
            for qname in quat_fields:
                for axis in ['x', 'y', 'z']:
                    prefix = 'if' if idx == 0 else 'else if'
                    lines.append(f'        {prefix} (field == "{qname}.{axis}") {{ return quatToEulerDeg(c.{qname}).{axis}; }}')
                    idx += 1


        if not first_comp:
            lines.append('    }')
        lines.extend([
            '    return 0.0f;',
            '}',
            '',
        ])
        return lines

    def _gen_set_int(self) -> List[str]:
        lines = [
            '// ── Set Int Property ──',
            '',
            'bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::string& field, i32 value) {',
            '    auto entity = static_cast<Entity>(e);',
            '    if (!reg.valid(entity)) return false;',
        ]

        first_comp = True
        for comp in self.components:
            if not comp.properties:
                continue
            full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name

            int_fields = []
            for prop in comp.properties:
                if self._is_readonly(prop):
                    continue
                editor_type = get_editor_type(prop, self.types)
                t = self.types.clean_type(prop.cpp_type)
                if editor_type in ('int', 'enum'):
                    int_fields.append((prop.name, prop.name, t))
                elif editor_type == 'entity' and not self.types.is_vector(t):
                    int_fields.append((prop.name, prop.name, t))
                elif editor_type == 'asset' and not self.types.is_vector(t):
                    # Asset refs round-trip as i32 only when the backing type fits
                    # into an int (resource::*Handle or raw u32 for material).
                    # String-backed asset fields (e.g. spine paths) are excluded —
                    # they need a setString path instead.
                    if self.types.is_handle(t) or self.types.is_primitive(t):
                        int_fields.append((prop.name, prop.name, t))

            if not int_fields:
                continue

            cond = 'if' if first_comp else '} else if'
            first_comp = False
            lines.append(f'    {cond} (comp == "{comp.name}") {{')

            if comp.name == 'Parent':
                lines.append('        if (field != "entity") return false;')
                lines.append('        esengine::ecs::setParent(reg, entity, static_cast<Entity>(value));')
                lines.append('        return true;')
                continue

            lines.append(f'        if (!reg.has<{full}>(entity)) return false;')
            # patch: an editor's write is stamped, so whatever reads changes (the renderer) sees it.
            lines.append(f'        auto& c = reg.patch<{full}>(entity);')

            for i, (key, cpp_path, cpp_type) in enumerate(int_fields):
                prefix = 'if' if i == 0 else 'else if'
                if self.types.is_enum(cpp_type):
                    lines.append(f'        {prefix} (field == "{key}") {{ c.{cpp_path} = static_cast<{cpp_type}>(value); }}')
                elif self.types.is_handle(cpp_type):
                    lines.append(f'        {prefix} (field == "{key}") {{ c.{cpp_path} = {cpp_type}(static_cast<u32>(value)); }}')
                elif self.types.is_entity(cpp_type):
                    lines.append(f'        {prefix} (field == "{key}") {{ c.{cpp_path} = static_cast<Entity>(value); }}')
                else:
                    lines.append(f'        {prefix} (field == "{key}") {{ c.{cpp_path} = static_cast<{cpp_type}>(value); }}')

            lines.append('        else { return false; }')
            lines.extend(self._write_hook(comp))
            lines.append('        return true;')

        if not first_comp:
            lines.append('    }')
        lines.extend([
            '    return false;',
            '}',
            '',
        ])
        return lines

    def _gen_get_int(self) -> List[str]:
        lines = [
            '// ── Get Int Property ──',
            '',
            'i32 editor_getInt(Registry& reg, u32 e, const std::string& comp, const std::string& field) {',
            '    auto entity = static_cast<Entity>(e);',
            '    if (!reg.valid(entity)) return 0;',
        ]

        first_comp = True
        for comp in self.components:
            if not comp.properties:
                continue
            full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name

            int_fields = []
            for prop in comp.properties:
                if self._is_readonly(prop):
                    continue
                editor_type = get_editor_type(prop, self.types)
                t = self.types.clean_type(prop.cpp_type)
                if editor_type in ('int', 'enum'):
                    int_fields.append((prop.name, prop.name, t))
                elif editor_type == 'entity' and not self.types.is_vector(t):
                    int_fields.append((prop.name, prop.name, t))
                elif editor_type == 'asset' and not self.types.is_vector(t):
                    if self.types.is_handle(t) or self.types.is_primitive(t):
                        int_fields.append((prop.name, prop.name, t))

            if not int_fields:
                continue

            cond = 'if' if first_comp else '} else if'
            first_comp = False
            lines.append(f'    {cond} (comp == "{comp.name}") {{')
            lines.append(f'        if (!reg.has<{full}>(entity)) return 0;')
            lines.append(f'        const auto& c = reg.get<{full}>(entity);')

            for i, (key, cpp_path, cpp_type) in enumerate(int_fields):
                prefix = 'if' if i == 0 else 'else if'
                if self.types.is_entity(cpp_type):
                    lines.append(f'        {prefix} (field == "{key}") {{ return static_cast<i32>(static_cast<u32>(c.{cpp_path})); }}')
                elif self.types.is_handle(cpp_type):
                    # Handle<T> has no implicit int cast; unpack via .id().
                    lines.append(f'        {prefix} (field == "{key}") {{ return static_cast<i32>(c.{cpp_path}.id()); }}')
                else:
                    lines.append(f'        {prefix} (field == "{key}") {{ return static_cast<i32>(c.{cpp_path}); }}')

        if not first_comp:
            lines.append('    }')
        lines.extend([
            '    return 0;',
            '}',
            '',
        ])
        return lines

    def _gen_set_bool(self) -> List[str]:
        lines = [
            '// ── Set Bool Property ──',
            '',
            'bool editor_setBool(Registry& reg, u32 e, const std::string& comp, const std::string& field, bool value) {',
            '    auto entity = static_cast<Entity>(e);',
            '    if (!reg.valid(entity)) return false;',
        ]

        first_comp = True
        for comp in self.components:
            if not comp.properties:
                continue
            full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name

            bool_fields = [(p.name, p.name) for p in comp.properties
                           if get_editor_type(p, self.types) == 'bool' and not self._is_readonly(p)]

            if not bool_fields:
                continue

            cond = 'if' if first_comp else '} else if'
            first_comp = False
            lines.append(f'    {cond} (comp == "{comp.name}") {{')
            lines.append(f'        if (!reg.has<{full}>(entity)) return false;')
            # patch: an editor's write is stamped, so whatever reads changes (the renderer) sees it.
            lines.append(f'        auto& c = reg.patch<{full}>(entity);')

            for i, (key, cpp_path) in enumerate(bool_fields):
                prefix = 'if' if i == 0 else 'else if'
                lines.append(f'        {prefix} (field == "{key}") {{ c.{cpp_path} = value; }}')

            lines.append('        else { return false; }')
            lines.extend(self._write_hook(comp))
            lines.append('        return true;')

        if not first_comp:
            lines.append('    }')
        lines.extend([
            '    return false;',
            '}',
            '',
        ])
        return lines

    def _gen_get_bool(self) -> List[str]:
        lines = [
            '// ── Get Bool Property ──',
            '',
            'bool editor_getBool(Registry& reg, u32 e, const std::string& comp, const std::string& field) {',
            '    auto entity = static_cast<Entity>(e);',
            '    if (!reg.valid(entity)) return false;',
        ]

        first_comp = True
        for comp in self.components:
            if not comp.properties:
                continue
            full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name

            bool_fields = [(p.name, p.name) for p in comp.properties
                           if get_editor_type(p, self.types) == 'bool' and not self._is_readonly(p)]

            if not bool_fields:
                continue

            cond = 'if' if first_comp else '} else if'
            first_comp = False
            lines.append(f'    {cond} (comp == "{comp.name}") {{')
            lines.append(f'        if (!reg.has<{full}>(entity)) return false;')
            lines.append(f'        const auto& c = reg.get<{full}>(entity);')

            for i, (key, cpp_path) in enumerate(bool_fields):
                prefix = 'if' if i == 0 else 'else if'
                lines.append(f'        {prefix} (field == "{key}") {{ return c.{cpp_path}; }}')

        if not first_comp:
            lines.append('    }')
        lines.extend([
            '    return false;',
            '}',
            '',
        ])
        return lines

    def _collect_string_fields(self, comp: Component) -> list:
        string_fields = []
        for prop in comp.properties:
            if self._is_readonly(prop):
                continue
            editor_type = get_editor_type(prop, self.types)
            if editor_type == 'skip':
                continue
            t = self.types.clean_type(prop.cpp_type)
            if t == 'std::string':
                string_fields.append((prop.name, prop.name))
        return string_fields

    def _gen_set_string(self) -> List[str]:
        lines = [
            '// ── Set String Property ──',
            '',
            'bool editor_setString(Registry& reg, u32 e, const std::string& comp, const std::string& field, const std::string& value) {',
            '    auto entity = static_cast<Entity>(e);',
            '    if (!reg.valid(entity)) return false;',
        ]

        first_comp = True
        for comp in self.components:
            if not comp.properties:
                continue
            full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
            string_fields = self._collect_string_fields(comp)
            if not string_fields:
                continue

            cond = 'if' if first_comp else '} else if'
            first_comp = False
            lines.append(f'    {cond} (comp == "{comp.name}") {{')
            lines.append(f'        if (!reg.has<{full}>(entity)) return false;')
            # patch: an editor's write is stamped, so whatever reads changes (the renderer) sees it.
            lines.append(f'        auto& c = reg.patch<{full}>(entity);')

            for i, (key, cpp_path) in enumerate(string_fields):
                prefix = 'if' if i == 0 else 'else if'
                lines.append(f'        {prefix} (field == "{key}") {{ c.{cpp_path} = value; }}')

            lines.append('        else { return false; }')
            side_effect = _STRING_SET_SIDE_EFFECTS.get(comp.name)
            if side_effect:
                lines.append(f'        {side_effect}')
            lines.extend(self._write_hook(comp))
            lines.append('        return true;')

        if not first_comp:
            lines.append('    }')
        lines.extend([
            '    return false;',
            '}',
            '',
        ])
        return lines

    def _gen_get_string(self) -> List[str]:
        lines = [
            '// ── Get String Property ──',
            '',
            'std::string editor_getString(Registry& reg, u32 e, const std::string& comp, const std::string& field) {',
            '    auto entity = static_cast<Entity>(e);',
            '    if (!reg.valid(entity)) return std::string{};',
        ]

        first_comp = True
        for comp in self.components:
            if not comp.properties:
                continue
            full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
            string_fields = self._collect_string_fields(comp)
            if not string_fields:
                continue

            cond = 'if' if first_comp else '} else if'
            first_comp = False
            lines.append(f'    {cond} (comp == "{comp.name}") {{')
            lines.append(f'        if (!reg.has<{full}>(entity)) return std::string{{}};')
            lines.append(f'        const auto& c = reg.get<{full}>(entity);')

            for i, (key, cpp_path) in enumerate(string_fields):
                prefix = 'if' if i == 0 else 'else if'
                lines.append(f'        {prefix} (field == "{key}") {{ return c.{cpp_path}; }}')

        if not first_comp:
            lines.append('    }')
        lines.extend([
            '    return std::string{};',
            '}',
            '',
        ])
        return lines

    def _gen_embind(self) -> List[str]:
        return [
            '}  // anonymous namespace',
            '',
            '// ── Embind Registration ──',
            '',
            'EMSCRIPTEN_BINDINGS(esengine_editor_api) {',
            '    emscripten::function("editor_getComponentNames", &editor_getComponentNames);',
            '    emscripten::function("editor_getComponentSchema", &editor_getComponentSchema);',
            '',
            '    emscripten::function("editor_addComponent", &editor_addComponent);',
            '    emscripten::function("editor_removeComponent", &editor_removeComponent);',
            '    emscripten::function("editor_hasComponent", &editor_hasComponent);',
            '    emscripten::function("editor_getComponents", &editor_getComponents);',
            '',
            '    emscripten::function("editor_setFloat", &editor_setFloat);',
            '    emscripten::function("editor_getFloat", &editor_getFloat);',
            '    emscripten::function("editor_setInt", &editor_setInt);',
            '    emscripten::function("editor_getInt", &editor_getInt);',
            '    emscripten::function("editor_setBool", &editor_setBool);',
            '    emscripten::function("editor_getBool", &editor_getBool);',
            '    emscripten::function("editor_setString", &editor_setString);',
            '    emscripten::function("editor_getString", &editor_getString);',
            '',
            '    emscripten::register_vector<std::string>("VectorString");',
            '}',
        ]