Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
AotHost.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
27#pragma once
28
29#include <cstddef>
30#include <cstdint>
31#include <functional>
32#include <optional>
33#include <span>
34#include <utility>
35#include <vector>
36
37#include "estella_abi.h"
38
39namespace esengine::aot {
40
42using SystemFn = void (*)(es_addr_t);
43
49using ComponentAt = std::function<void*(std::uint32_t)>;
50
58using Candidates = std::optional<std::span<const std::uint32_t>>;
59
61using CandidatesOf = std::function<Candidates()>;
62
70struct WorldStamp {
71 double at = 0.0;
72 bool known = false;
73
75 bool operator==(const WorldStamp& o) const { return known && o.known && at == o.at; }
76};
77
79struct QuerySpec {
80 std::vector<ComponentAt> comps;
86 std::vector<CandidatesOf> sources;
87};
88
96inline Candidates narrowest(const QuerySpec& spec) {
97 Candidates best;
98 for (const CandidatesOf& source : spec.sources) {
99 if (!source) continue;
100 const Candidates got = source();
101 if (!got) continue;
102 if (!best || got->size() < best->size()) best = got;
103 }
104 return best;
105}
106
112inline bool narrows(std::span<const QuerySpec> queries) {
113 for (const QuerySpec& q : queries) {
114 if (!narrowest(q)) return false;
115 }
116 return true;
117}
118
119struct BoundSystem;
120using ResourceLookup = std::function<void*(const char*)>;
121
127public:
128 explicit CallArena(std::uint32_t cmdCap = 256) : cmds_(cmdCap) {}
129
131 std::uint32_t commandCapacity() const { return static_cast<std::uint32_t>(cmds_.size()); }
132
140 std::uint32_t candidatesWalked() const { return walked_; }
141
144 std::uint32_t rowsPacked() const { return packed_; }
145
146private:
147 friend std::span<const EsCmd> run(SystemFn, std::span<const std::uint32_t>,
148 std::span<const QuerySpec>, std::span<void* const>,
150 friend std::span<const EsCmd> runBound(const BoundSystem&, std::span<const std::uint32_t>,
151 const ResourceLookup&, CallArena&, WorldStamp, bool*);
152 std::vector<es_addr_t> rows_;
153 std::vector<EsQueryRows> queries_;
154 std::vector<es_addr_t> resources_;
155 std::vector<void*> resourcePointers_;
156 std::vector<std::size_t> starts_;
157 std::vector<std::uint32_t> counts_;
158 std::vector<EsCmd> cmds_;
159 std::uint32_t count_ = 0;
160 std::uint32_t walked_ = 0;
161 std::uint32_t packed_ = 0;
165 WorldStamp packedAt_;
166 std::vector<std::span<const std::uint32_t>> from_;
168 std::vector<std::span<const std::uint32_t>> lists_;
169 std::vector<std::span<const std::uint32_t>> columns_;
170 EsSysCtx ctx_{};
171};
172
181inline std::span<const EsCmd> run(SystemFn fn,
182 std::span<const std::uint32_t> fallback,
183 std::span<const QuerySpec> queries,
184 std::span<void* const> resources,
185 CallArena& arena,
186 WorldStamp world = {}) {
187 // Its own column where a query has one, everybody where it has none. A freed
188 // slot in a script column reads as an entity nothing resolves for, so the
189 // completeness check below drops it like any other miss.
190 arena.walked_ = 0;
191 arena.lists_.assign(queries.size(), {});
192 arena.columns_.clear();
193 // A query that cannot say who it matches cannot say whether that changed, so
194 // falling back to the caller's list also gives up the row table.
195 bool narrowedEvery = !queries.empty();
196 for (std::size_t q = 0; q < queries.size(); ++q) {
197 Candidates best;
198 for (const CandidatesOf& source : queries[q].sources) {
199 if (!source) continue;
200 const Candidates got = source();
201 if (!got) continue;
202 arena.columns_.push_back(*got);
203 if (!best || got->size() < best->size()) best = got;
204 }
205 if (!best) narrowedEvery = false;
206 arena.lists_[q] = best ? *best : fallback;
207 arena.walked_ += static_cast<std::uint32_t>(arena.lists_[q].size());
208 }
209
210 bool reuse = narrowedEvery && (world == arena.packedAt_)
211 && arena.from_.size() == arena.columns_.size();
212 for (std::size_t c = 0; reuse && c < arena.columns_.size(); ++c) {
213 if (arena.columns_[c].data() != arena.from_[c].data()
214 || arena.columns_[c].size() != arena.from_[c].size()) {
215 reuse = false;
216 }
217 }
218
219 arena.packed_ = 0;
220 if (!reuse) {
221 arena.rows_.clear();
222 arena.queries_.assign(queries.size(), EsQueryRows{});
223 // Offsets first, addresses after: one vector holding every query's rows
224 // moves under the first query's pointer as the second grows, and the ctx
225 // has to point at something that will still be there during the call.
226 auto& starts = arena.starts_;
227 auto& counts = arena.counts_;
228 starts.resize(queries.size());
229 counts.assign(queries.size(), 0);
230 for (std::size_t q = 0; q < queries.size(); ++q) {
231 starts[q] = arena.rows_.size();
232 const auto& comps = queries[q].comps;
233 for (std::uint32_t e : arena.lists_[q]) {
234 const std::size_t mark = arena.rows_.size();
235 arena.rows_.push_back(static_cast<es_addr_t>(e));
236 bool complete = true;
237 for (const auto& at : comps) {
238 void* p = at(e);
239 if (p == nullptr) { complete = false; break; }
240 arena.rows_.push_back(reinterpret_cast<es_addr_t>(p));
241 }
242 if (complete) ++counts[q];
243 else arena.rows_.resize(mark);
244 }
245 arena.packed_ += counts[q];
246 }
247 for (std::size_t q = 0; q < queries.size(); ++q) {
248 arena.queries_[q].rows = reinterpret_cast<es_addr_t>(arena.rows_.data() + starts[q]);
249 arena.queries_[q].count = counts[q];
250 }
251 // Only a table that narrowed EVERY query can be offered again; an
252 // unknown stamp is recorded as unknown and never matches.
253 arena.packedAt_ = narrowedEvery ? world : WorldStamp{};
254 arena.from_ = arena.columns_;
255 }
256
257 arena.resources_.assign(resources.size(), es_addr_t{});
258 for (std::size_t r = 0; r < resources.size(); ++r) {
259 arena.resources_[r] = reinterpret_cast<es_addr_t>(resources[r]);
260 }
261
262 arena.count_ = 0;
263 arena.ctx_.queries = reinterpret_cast<es_addr_t>(arena.queries_.data());
264 arena.ctx_.resources = reinterpret_cast<es_addr_t>(arena.resources_.data());
265 arena.ctx_.cmdBuf = reinterpret_cast<es_addr_t>(arena.cmds_.data());
266 arena.ctx_.cmdCap = arena.commandCapacity();
267 arena.ctx_.cmdCount = reinterpret_cast<es_addr_t>(&arena.count_);
268 arena.ctx_.events = 0;
269
270 fn(reinterpret_cast<es_addr_t>(&arena.ctx_));
271
272 return std::span<const EsCmd>(arena.cmds_.data(), arena.count_);
273}
274
281struct RowSpan {
282 const std::uint32_t* sparse = nullptr;
283 std::uint32_t sparseCount = 0;
284 unsigned char* rows = nullptr;
285 std::uint32_t stride = 0;
288 std::uint32_t indexMask = 0;
296 const std::uint32_t* owners = nullptr;
299 std::uint32_t ownerCount = 0;
300};
301
304inline constexpr std::uint32_t NO_OWNER = 0xFFFFFFFFu;
305
307inline void* rowAt(const RowSpan& span, std::uint32_t entity) {
308 const std::uint32_t at = entity & span.indexMask;
309 if (at >= span.sparseCount) return nullptr;
310 const std::uint32_t slot = span.sparse[at];
311 if (slot == 0u) return nullptr;
312 return span.rows + static_cast<std::size_t>(slot - 1u) * span.stride;
313}
314
316inline ComponentAt fromRows(const RowSpan& span) {
317 return [span](std::uint32_t entity) -> void* { return rowAt(span, entity); };
318}
319
327inline ComponentAt fromMovingRows(const RowSpan* slot) {
328 return [slot](std::uint32_t entity) -> void* {
329 return slot == nullptr ? nullptr : rowAt(*slot, entity);
330 };
331}
332
339 return [slot]() -> Candidates {
340 if (slot == nullptr || slot->owners == nullptr) return std::nullopt;
341 return std::span<const std::uint32_t>(slot->owners, slot->ownerCount);
342 };
343}
344
350using ComponentLookup = std::function<ComponentAt(const char*)>;
351
358using CandidateLookup = std::function<CandidatesOf(const char*)>;
359
366 SystemFn fn = nullptr;
367 std::vector<QuerySpec> queries;
368 std::vector<const char*> resourceNames;
369};
370
376inline BoundSystem bind(const EsSystemDecl& decl,
377 const ComponentLookup& components,
378 const ResourceLookup& resources,
379 const CandidateLookup& candidates = {}) {
380 BoundSystem out;
381 out.queries.resize(decl.queryCount);
382 for (std::uint32_t q = 0; q < decl.queryCount; ++q) {
383 const EsQueryDecl& qd = decl.queries[q];
384 for (std::uint32_t c = 0; c < qd.count; ++c) {
385 ComponentAt at = components(qd.comps[c]);
386 if (!at) return {};
387 out.queries[q].comps.push_back(std::move(at));
388 // A column that cannot say leaves a falsy entry rather than none, so
389 // `sources` stays index-for-index with `comps` and a reader of one
390 // is a reader of the other.
391 out.queries[q].sources.push_back(candidates ? candidates(qd.comps[c]) : CandidatesOf{});
392 }
393 }
394 for (std::uint32_t r = 0; r < decl.resourceCount; ++r) {
395 if (resources(decl.resources[r]) == nullptr) return {};
396 out.resourceNames.push_back(decl.resources[r]);
397 }
398 out.fn = decl.fn;
399 return out;
400}
401
404inline std::span<const EsCmd> runBound(const BoundSystem& bound,
405 std::span<const std::uint32_t> fallback,
406 const ResourceLookup& resources,
407 CallArena& arena,
408 WorldStamp world = {}, bool* runnable = nullptr) {
409 if (runnable) *runnable = false;
410 if (bound.fn == nullptr) return {};
411 auto& addresses = arena.resourcePointers_;
412 addresses.clear();
413 addresses.reserve(bound.resourceNames.size());
414 for (const char* name : bound.resourceNames) {
415 void* address = resources(name);
416 if (address == nullptr) return {};
417 addresses.push_back(address);
418 }
419 if (runnable) *runnable = true;
420 return run(bound.fn, fallback, bound.queries, addresses, arena, world);
421}
422
428inline std::uint64_t abiHash(std::uint64_t contract) {
429 return contract ^ (0x9e3779b97f4a7c15ULL * sizeof(es_addr_t));
430}
431
432} // namespace esengine::aot
std::uint32_t rowsPacked() const
Definition AotHost.hpp:144
CallArena(std::uint32_t cmdCap=256)
Definition AotHost.hpp:128
friend std::span< const EsCmd > run(SystemFn, std::span< const std::uint32_t >, std::span< const QuerySpec >, std::span< void *const >, CallArena &, WorldStamp)
Definition AotHost.hpp:181
friend std::span< const EsCmd > runBound(const BoundSystem &, std::span< const std::uint32_t >, const ResourceLookup &, CallArena &, WorldStamp, bool *)
Definition AotHost.hpp:404
std::uint32_t commandCapacity() const
Definition AotHost.hpp:131
std::uint32_t candidatesWalked() const
Definition AotHost.hpp:140
struct EsQueryRows EsQueryRows
uintptr_t es_addr_t
Definition estella_abi.h:31
void(*)(es_addr_t) SystemFn
Definition AotHost.hpp:42
ComponentAt fromRows(const RowSpan &span)
Definition AotHost.hpp:316
std::function< CandidatesOf(const char *)> CandidateLookup
Definition AotHost.hpp:358
void * rowAt(const RowSpan &span, std::uint32_t entity)
Definition AotHost.hpp:307
ComponentAt fromMovingRows(const RowSpan *slot)
Definition AotHost.hpp:327
constexpr std::uint32_t NO_OWNER
Definition AotHost.hpp:304
bool narrows(std::span< const QuerySpec > queries)
Definition AotHost.hpp:112
CandidatesOf fromMovingOwners(const RowSpan *slot)
Definition AotHost.hpp:338
std::function< void *(const char *)> ResourceLookup
Definition AotHost.hpp:120
std::span< const EsCmd > runBound(const BoundSystem &bound, std::span< const std::uint32_t > fallback, const ResourceLookup &resources, CallArena &arena, WorldStamp world={}, bool *runnable=nullptr)
Definition AotHost.hpp:404
std::function< Candidates()> CandidatesOf
Definition AotHost.hpp:61
Candidates narrowest(const QuerySpec &spec)
Definition AotHost.hpp:96
std::optional< std::span< const std::uint32_t > > Candidates
Definition AotHost.hpp:58
std::function< ComponentAt(const char *)> ComponentLookup
Definition AotHost.hpp:350
std::function< void *(std::uint32_t)> ComponentAt
Definition AotHost.hpp:49
std::uint64_t abiHash(std::uint64_t contract)
Definition AotHost.hpp:428
std::span< const EsCmd > run(SystemFn fn, std::span< const std::uint32_t > fallback, std::span< const QuerySpec > queries, std::span< void *const > resources, CallArena &arena, WorldStamp world={})
Definition AotHost.hpp:181
BoundSystem bind(const EsSystemDecl &decl, const ComponentLookup &components, const ResourceLookup &resources, const CandidateLookup &candidates={})
Definition AotHost.hpp:376
const char *const * comps
Definition estella_abi.h:94
uint32_t count
Definition estella_abi.h:96
es_addr_t events
Definition estella_abi.h:72
es_addr_t cmdCap
Definition estella_abi.h:70
es_addr_t resources
Definition estella_abi.h:68
es_addr_t cmdBuf
Definition estella_abi.h:69
es_addr_t cmdCount
Definition estella_abi.h:71
es_addr_t queries
Definition estella_abi.h:67
void(* fn)(es_addr_t)
uint32_t resourceCount
const char *const * resources
const EsQueryDecl * queries
uint32_t queryCount
std::vector< const char * > resourceNames
Definition AotHost.hpp:368
std::vector< QuerySpec > queries
Definition AotHost.hpp:367
std::vector< ComponentAt > comps
Definition AotHost.hpp:80
std::vector< CandidatesOf > sources
Definition AotHost.hpp:86
std::uint32_t ownerCount
Definition AotHost.hpp:299
const std::uint32_t * sparse
Definition AotHost.hpp:282
const std::uint32_t * owners
Definition AotHost.hpp:296
std::uint32_t indexMask
Definition AotHost.hpp:288
unsigned char * rows
Definition AotHost.hpp:284
std::uint32_t sparseCount
Definition AotHost.hpp:283
std::uint32_t stride
Definition AotHost.hpp:285
bool operator==(const WorldStamp &o) const
Definition AotHost.hpp:75