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.

feat(eht): generate native QuickJS bindings from the same reflection source

yhhe7f880f635df
diff --git a/tools/eht/__main__.py b/tools/eht/__main__.py
index fc4bb9f24..2762ebb56 100644
--- a/tools/eht/__main__.py
+++ b/tools/eht/__main__.py
@@ -8,7 +8,7 @@ from .parser import CppParser
from .abi import compute_abi_hash
from .generators import (
EmbindGenerator, TypeScriptGenerator, MetadataGenerator,
- PtrLayoutGenerator, EditorAPIGenerator,
+ PtrLayoutGenerator, EditorAPIGenerator, NativeBindingsGenerator,
)
@@ -23,6 +23,15 @@ def main() -> int:
parser.add_argument('--ts-output', type=Path, default=Path('sdk'),
help='Output directory for TypeScript')
parser.add_argument('--verbose', '-v', action='store_true')
+ # Opt-in native (QuickJS) bindings. Off by default so the standard EHT run and
+ # its committed *.generated.* files are unchanged; a native build passes this
+ # to emit NativeBindings.generated.cpp into its build tree from the same source.
+ parser.add_argument('--native-output', type=Path, default=None,
+ help='Also emit native QuickJS bindings to this .cpp path')
+ parser.add_argument('--native-components', type=str, default=None,
+ help='Comma-separated component names to emit (default: all)')
+ parser.add_argument('--native-shim', type=str, default='esn_shim.hpp',
+ help='Shim header the generated native TU includes')
args = parser.parse_args()
print("EHT - ESEngine Header Tool")
@@ -85,6 +94,19 @@ def main() -> int:
)
embind_path.write_text(embind_gen.generate(), encoding='utf-8')
+ # ── Native QuickJS Bindings (opt-in) ──
+ if args.native_output is not None:
+ only = None
+ if args.native_components:
+ only = {n.strip() for n in args.native_components.split(',') if n.strip()}
+ args.native_output.parent.mkdir(parents=True, exist_ok=True)
+ print(f"Generating: {args.native_output}")
+ native_gen = NativeBindingsGenerator(
+ cpp_parser.components, cpp_parser.enums,
+ shim_header=args.native_shim, only=only,
+ )
+ args.native_output.write_text(native_gen.generate(), encoding='utf-8')
+
# Resolve the TS source directory robustly. Callers historically pass either
# the package root (`sdk`) or the source dir (`sdk/src`); detect which by
# looking for the `ecs/` subfolder. Previously a `sdk/src` argument made every
diff --git a/tools/eht/generators/__init__.py b/tools/eht/generators/__init__.py
index bf7444247..77632f646 100644
--- a/tools/eht/generators/__init__.py
+++ b/tools/eht/generators/__init__.py
@@ -5,8 +5,9 @@ from .typescript import TypeScriptGenerator
from .metadata import MetadataGenerator
from .ptr_layout import PtrLayoutGenerator
from .editor_api import EditorAPIGenerator
+from .native_bindings import NativeBindingsGenerator
__all__ = [
'EmbindGenerator', 'TypeScriptGenerator', 'MetadataGenerator',
- 'PtrLayoutGenerator', 'EditorAPIGenerator',
+ 'PtrLayoutGenerator', 'EditorAPIGenerator', 'NativeBindingsGenerator',
]
diff --git a/tools/eht/generators/native_bindings.py b/tools/eht/generators/native_bindings.py
new file mode 100644
index 000000000..1374eedac
--- /dev/null
+++ b/tools/eht/generators/native_bindings.py
@@ -0,0 +1,87 @@
+"""Native (QuickJS) binding generator — the native sibling of the embind generator.
+
+Emits, per ES_COMPONENT, a QuickJS-callable ``es_set_<Component>(entityId, obj)``
+that writes the reflected scalar / vec / bool / enum fields, plus an
+``esn_register()`` that installs them as script globals. It consumes the SAME
+parsed reflection (data.Component) as EmbindGenerator, so the web (embind) and
+native (QuickJS) binding surfaces are generated from one source and cannot drift.
+
+Opt-in: only emitted when ``python -m eht --native-output PATH`` is given, so the
+default EHT run (and the committed *.generated.* files it produces) is unchanged.
+The generated TU relies on a host-provided shim header (default ``esn_shim.hpp``)
+for the ``esn_*`` readers, the entity lookup, and the component includes.
+"""
+
+from typing import List
+from ..data import Component, Enum
+from ..type_system import TypeSystem
+
+# Numeric primitives written straight through (via a double), by cleaned type.
+_FLOAT = {'f32', 'f64', 'float', 'double'}
+_INT = {'i8', 'i16', 'i32', 'i64', 'u8', 'u16', 'u32', 'u64',
+ 'int', 'int8_t', 'int16_t', 'int32_t', 'int64_t',
+ 'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t', 'size_t', 'char'}
+# glm vector arities the reader marshals (float lanes). quat/uvec2 skipped:
+# quaternion storage order is fragile to hand-write, uvec2 is unsigned.
+_GLM_ARITY = {'glm::vec2': 2, 'glm::vec3': 3, 'glm::vec4': 4}
+
+
+class NativeBindingsGenerator:
+ def __init__(self, components: List[Component], enums: List[Enum],
+ shim_header: str = 'esn_shim.hpp', only=None):
+ # ``only`` (a set of component names) narrows the emitted surface so a host
+ # that includes only some component headers still compiles; None = all.
+ self.components = [c for c in components if only is None or c.name in only]
+ self.enums = enums
+ self.types = TypeSystem(enums)
+ self.shim_header = shim_header
+
+ def _field(self, prop) -> str:
+ t = prop.cpp_type
+ n = prop.name
+ ct = self.types.clean_type(t)
+ if ct in _GLM_ARITY:
+ return f' esn_getvec(ctx, o, "{n}", &c.{n}.x, {_GLM_ARITY[ct]});'
+ if ct == 'bool':
+ return f' {{ int _b; if (esn_getbool(ctx, o, "{n}", &_b)) c.{n} = _b != 0; }}'
+ if self.types.is_enum(t) or ct in _INT:
+ return (f' {{ double _v; if (esn_getnum(ctx, o, "{n}", &_v)) '
+ f'c.{n} = static_cast<decltype(c.{n})>(static_cast<long long>(_v)); }}')
+ if ct in _FLOAT:
+ return (f' {{ double _v; if (esn_getnum(ctx, o, "{n}", &_v)) '
+ f'c.{n} = static_cast<decltype(c.{n})>(_v); }}')
+ return f' // skip {n}: {t} (handle / entity / vector / struct — needs a resource-aware binding)'
+
+ def _component(self, comp: Component) -> List[str]:
+ full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
+ out = [f'static JSValue es_set_{comp.name}(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {{',
+ ' if (argc < 2) return JS_UNDEFINED;',
+ ' esengine::Entity e = esn_entity(ctx, argv[0]);',
+ f' auto& c = esn_reg().getOrEmplace<{full}>(e);',
+ ' JSValueConst o = argv[1];',
+ ' (void)c; (void)o;']
+ for prop in comp.properties:
+ out.append(self._field(prop))
+ out.append(' return JS_UNDEFINED;')
+ out.append('}')
+ out.append('')
+ return out
+
+ def generate(self) -> str:
+ lines = [
+ '// Auto-generated by EHT (native_bindings) — DO NOT EDIT.',
+ '// Native QuickJS sibling of WebBindings.generated.cpp — one reflection source.',
+ f'#include "{self.shim_header}"',
+ '',
+ ]
+ components = sorted(self.components, key=lambda c: c.name)
+ for comp in components:
+ lines.extend(self._component(comp))
+ lines.append('void esn_register(JSContext* ctx, JSValue global) {')
+ for comp in components:
+ fn = f'es_set_{comp.name}'
+ lines.append(f' JS_SetPropertyStr(ctx, global, "{fn}", '
+ f'JS_NewCFunction(ctx, {fn}, "{fn}", 2));')
+ lines.append('}')
+ lines.append('')
+ return '\n'.join(lines)