Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
DragonBonesModuleEntry.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
32// KEEPALIVE keeps these exported through the emscripten link; natively the
33// attribute has no meaning and the header does not exist.
34#ifdef __EMSCRIPTEN__
35#include <emscripten.h>
36#else
37#define EMSCRIPTEN_KEEPALIVE
38#endif
39
40#include <algorithm>
41#include <cstring>
42#include <string>
43#include <vector>
44
48
49namespace {
50
51using dragonBones::Armature;
52using dragonBones::DragonBonesData;
53using dragonBones::EsArmatureProxy;
54using dragonBones::EsFactory;
55using dragonBones::EsSlot;
56using dragonBones::EsTextureAtlasData;
57
59struct LoadedSkeleton {
60 DragonBonesData* data = nullptr;
61 EsTextureAtlasData* atlas = nullptr;
62 std::string name;
63};
64
65struct LiveInstance {
66 Armature* armature = nullptr;
67 int skeletonHandle = -1;
70 float tint[4] = {1.0f, 1.0f, 1.0f, 1.0f};
71};
72
73struct Context {
76
80
81 std::string lastError;
82
83 Armature* armatureOf(int id) {
84 auto* live = instances.find(id);
85 return live ? live->armature : nullptr;
86 }
87};
88
89Context g_ctx;
90
92std::string skeletonName(int handle) { return "es_db_" + std::to_string(handle); }
93
100void extractBatches(int instanceId) {
101 g_ctx.batches.reset();
102 auto* live = g_ctx.instances.find(instanceId);
103 if (!live || !live->armature) return;
104
105 es::skeletal::BatchCollector collector(g_ctx.batches);
106 for (auto* slot : live->armature->getSlots()) {
107 static_cast<EsSlot*>(slot)->emit(collector, live->tint);
108 }
109}
110
111} // namespace
112
113extern "C" {
114
115// =============================================================================
116// Resources
117// =============================================================================
118
120int db_loadSkeleton(uintptr_t skeletonPtr, int skeletonLen, uintptr_t atlasPtr, int atlasLen) {
121 g_ctx.lastError.clear();
122 if (skeletonPtr == 0 || skeletonLen <= 0 || atlasPtr == 0 || atlasLen <= 0) {
123 g_ctx.lastError = "empty skeleton or atlas data";
124 return -1;
125 }
126
127 // Both arrive as bytes and both parsers want a C string, so they are copied
128 // rather than cast: the caller's buffer carries no terminator.
129 const std::string skeletonText(reinterpret_cast<const char*>(skeletonPtr),
130 static_cast<std::size_t>(skeletonLen));
131 const std::string atlasText(reinterpret_cast<const char*>(atlasPtr), static_cast<std::size_t>(atlasLen));
132
133 const int handle = g_ctx.skeletons.add(LoadedSkeleton{});
134 auto* held = g_ctx.skeletons.find(handle);
135 held->name = skeletonName(handle);
136
137 auto& factory = EsFactory::instance();
138 held->data = factory.parseDragonBonesData(skeletonText.c_str(), held->name, 1.0f);
139 if (held->data == nullptr) {
140 g_ctx.lastError = "skeleton data could not be parsed";
141 g_ctx.skeletons.erase(handle);
142 return -1;
143 }
144
145 held->atlas = static_cast<EsTextureAtlasData*>(
146 factory.parseTextureAtlasData(atlasText.c_str(), nullptr, held->name, 1.0f));
147 if (held->atlas == nullptr) {
148 g_ctx.lastError = "texture atlas data could not be parsed";
149 factory.removeDragonBonesData(held->name);
150 g_ctx.skeletons.erase(handle);
151 return -1;
152 }
153 return handle;
154}
155
157const char* db_getLastError() { return g_ctx.strings.publish(g_ctx.lastError.c_str()); }
158
160void db_unloadSkeleton(int handle) {
161 auto* held = g_ctx.skeletons.find(handle);
162 if (!held) return;
163
164 // Instances hold this data; they go first, or their next update reads freed memory.
165 g_ctx.instances.eraseIf([handle](LiveInstance& live) {
166 if (live.skeletonHandle != handle) return false;
167 if (live.armature) live.armature->dispose();
168 return true;
169 });
170
171 auto& factory = EsFactory::instance();
172 factory.removeTextureAtlasData(held->name);
173 factory.removeDragonBonesData(held->name);
174 g_ctx.skeletons.erase(handle);
175}
176
179const char* db_getArmatures(int handle) {
180 auto* held = g_ctx.skeletons.find(handle);
181 if (!held || !held->data) return g_ctx.strings.publish("[]");
182 const auto& names = held->data->armatureNames;
183 return g_ctx.strings.publishArray(static_cast<int>(names.size()),
184 [&names](int i) { return names[static_cast<std::size_t>(i)].c_str(); });
185}
186
189const char* db_getAtlasImageName(int handle) {
190 auto* held = g_ctx.skeletons.find(handle);
191 return g_ctx.strings.publish(held && held->atlas ? held->atlas->imagePath.c_str() : "");
192}
193
195void db_setAtlasTexture(int handle, uint32_t textureId) {
196 auto* held = g_ctx.skeletons.find(handle);
197 if (!held || !held->atlas) return;
198 held->atlas->setTexture(textureId);
199
200 // Slots rebuild their geometry only when DragonBones thinks the display
201 // changed, and binding a texture is not something it watches. Without this an
202 // instance created before the upload finished would stay empty forever — and
203 // the upload finishing last is the normal order, not the unusual one.
204 g_ctx.instances.eraseIf([handle](LiveInstance& live) {
205 if (live.skeletonHandle == handle && live.armature) live.armature->invalidUpdate("", true);
206 return false;
207 });
208}
209
210// =============================================================================
211// Instances
212// =============================================================================
213
215int db_createInstance(int skeletonHandle, const char* armatureName) {
216 auto* held = g_ctx.skeletons.find(skeletonHandle);
217 if (!held) {
218 g_ctx.lastError = "no such skeleton";
219 return -1;
220 }
221 auto* armature = EsFactory::instance().buildArmature(armatureName ? armatureName : "", held->name);
222 if (armature == nullptr) {
223 g_ctx.lastError = "no such armature in this skeleton";
224 return -1;
225 }
226 return g_ctx.instances.add(LiveInstance{armature, skeletonHandle});
227}
228
230void db_destroyInstance(int instanceId) {
231 auto* live = g_ctx.instances.find(instanceId);
232 if (!live) return;
233 if (live->armature) live->armature->dispose();
234 g_ctx.instances.erase(instanceId);
235}
236
237// =============================================================================
238// Animation
239// =============================================================================
240
243int db_playAnimation(int instanceId, const char* name, int playTimes) {
244 auto* armature = g_ctx.armatureOf(instanceId);
245 if (!armature) return 0;
246 return armature->getAnimation()->play(name ? name : "", playTimes) != nullptr ? 1 : 0;
247}
248
251int db_fadeInAnimation(int instanceId, const char* name, float fadeSeconds, int playTimes) {
252 auto* armature = g_ctx.armatureOf(instanceId);
253 if (!armature) return 0;
254 return armature->getAnimation()->fadeIn(name ? name : "", fadeSeconds, playTimes) != nullptr ? 1 : 0;
255}
256
258void db_stopAnimation(int instanceId, const char* name) {
259 auto* armature = g_ctx.armatureOf(instanceId);
260 if (armature) armature->getAnimation()->stop(name ? name : "");
261}
262
264void db_setTimeScale(int instanceId, float scale) {
265 auto* armature = g_ctx.armatureOf(instanceId);
266 if (armature) armature->getAnimation()->timeScale = scale;
267}
268
272void db_setColor(int instanceId, float r, float g, float b, float a) {
273 auto* live = g_ctx.instances.find(instanceId);
274 if (!live) return;
275 live->tint[0] = r;
276 live->tint[1] = g;
277 live->tint[2] = b;
278 live->tint[3] = a;
279}
280
282void db_update(int instanceId, float dt) {
283 auto* armature = g_ctx.armatureOf(instanceId);
284 if (!armature) return;
285 g_ctx.events.clear();
286 // Return what the LAST advance retired before this one retires more. The
287 // runtime object is the only thing that empties that buffer, and an armature
288 // fills it whenever an animation state finishes or is faded out — so nothing
289 // else here can be what frees them.
291 armature->advanceTime(dt);
292}
293
295const char* db_getAnimations(int instanceId) {
296 auto* armature = g_ctx.armatureOf(instanceId);
297 if (!armature) return g_ctx.strings.publish("[]");
298 const auto& names = armature->getAnimation()->getAnimationNames();
299 return g_ctx.strings.publishArray(static_cast<int>(names.size()),
300 [&names](int i) { return names[static_cast<std::size_t>(i)].c_str(); });
301}
302
305const char* db_getBones(int instanceId) {
306 auto* armature = g_ctx.armatureOf(instanceId);
307 if (!armature) return g_ctx.strings.publish("[]");
308 const auto& bones = armature->getBones();
309 return g_ctx.strings.publishArray(static_cast<int>(bones.size()),
310 [&bones](int i) { return bones[static_cast<std::size_t>(i)]->getName().c_str(); });
311}
312
320int db_getBonePoses(int instanceId, uintptr_t outPtr, int capacity) {
321 auto* armature = g_ctx.armatureOf(instanceId);
322 if (!armature) return 0;
323 const auto& bones = armature->getBones();
324 float* out = reinterpret_cast<float*>(outPtr);
325 const int n = std::min(static_cast<int>(bones.size()), capacity);
326 for (int i = 0; i < n; ++i) {
327 dragonBones::Bone* bone = bones[static_cast<std::size_t>(i)];
328 bone->updateGlobalTransform();
329 int parent = -1;
330 if (const dragonBones::Bone* p = bone->getParent()) {
331 for (int j = 0; j < i; ++j) {
332 if (bones[static_cast<std::size_t>(j)] == p) { parent = j; break; }
333 }
334 }
335 constexpr float kRadToDeg = 57.29577951308232f;
336 float* at = out + i * 5;
337 at[0] = static_cast<float>(parent);
338 at[1] = bone->global.x;
339 at[2] = -bone->global.y;
340 at[3] = -bone->global.rotation * kRadToDeg;
341 at[4] = bone->getBoneData()->length;
342 }
343 return n;
344}
345
346// =============================================================================
347// Geometry readback
348// =============================================================================
349
350// Posing happens HERE, not in update: one batch list serves every instance, so it
351// has to belong to whichever one is being read right now. Extracting in update
352// instead leaves it holding the last instance updated — and every getter below
353// would then answer for that one however carefully it was asked about another.
355int db_getMeshBatchCount(int instanceId) {
356 extractBatches(instanceId);
357 return static_cast<int>(g_ctx.batches.size());
358}
359
361int db_getMeshBatchVertexCount(int instanceId, int batchIndex) {
362 (void)instanceId;
363 if (batchIndex < 0 || batchIndex >= static_cast<int>(g_ctx.batches.size())) return 0;
364 return static_cast<int>(g_ctx.batches[batchIndex].vertices.size() / es::skeletal::VERTEX_FLOATS);
365}
366
368int db_getMeshBatchIndexCount(int instanceId, int batchIndex) {
369 (void)instanceId;
370 if (batchIndex < 0 || batchIndex >= static_cast<int>(g_ctx.batches.size())) return 0;
371 return static_cast<int>(g_ctx.batches[batchIndex].indices.size());
372}
373
375void db_getMeshBatchData(int instanceId, int batchIndex, uintptr_t outVerticesPtr, uintptr_t outIndicesPtr,
376 uintptr_t outTextureIdPtr, uintptr_t outBlendModePtr) {
377 (void)instanceId;
378 if (batchIndex < 0 || batchIndex >= static_cast<int>(g_ctx.batches.size())) return;
379
380 const es::skeletal::MeshBatch& batch = g_ctx.batches[batchIndex];
381 std::memcpy(reinterpret_cast<float*>(outVerticesPtr), batch.vertices.data(),
382 batch.vertices.size() * sizeof(float));
383 std::memcpy(reinterpret_cast<uint16_t*>(outIndicesPtr), batch.indices.data(),
384 batch.indices.size() * sizeof(uint16_t));
385 *reinterpret_cast<uint32_t*>(outTextureIdPtr) = batch.texture;
386 *reinterpret_cast<int32_t*>(outBlendModePtr) = batch.blendMode;
387}
388
390void db_getBounds(int instanceId, uintptr_t outXPtr, uintptr_t outYPtr, uintptr_t outWPtr, uintptr_t outHPtr) {
391 // Derived from the posed batches rather than asked of the runtime: DragonBones
392 // reports an armature's authored bounds, which is not where it currently is.
393 extractBatches(instanceId);
394 float minX = 0.0f, minY = 0.0f, maxX = 0.0f, maxY = 0.0f;
395 bool any = false;
396 for (const auto& batch : g_ctx.batches) {
397 for (std::size_t i = 0; i < batch.vertices.size(); i += es::skeletal::VERTEX_FLOATS) {
398 const float x = batch.vertices[i];
399 const float y = batch.vertices[i + 1];
400 if (!any) {
401 minX = maxX = x;
402 minY = maxY = y;
403 any = true;
404 continue;
405 }
406 minX = x < minX ? x : minX;
407 maxX = x > maxX ? x : maxX;
408 minY = y < minY ? y : minY;
409 maxY = y > maxY ? y : maxY;
410 }
411 }
412 *reinterpret_cast<float*>(outXPtr) = minX;
413 *reinterpret_cast<float*>(outYPtr) = minY;
414 *reinterpret_cast<float*>(outWPtr) = maxX - minX;
415 *reinterpret_cast<float*>(outHPtr) = maxY - minY;
416}
417
420int db_runtimeVersion() { return 5; }
421
422} // extern "C"
The host types DragonBones requires, implemented for a module that renders nothing itself and only ha...
The DragonBones module's exported ABI, declared apart from its bodies.
void db_stopAnimation(int instanceId, const char *name)
int db_getBonePoses(int instanceId, uintptr_t outPtr, int capacity)
void db_update(int instanceId, float dt)
void db_setColor(int instanceId, float r, float g, float b, float a)
int db_runtimeVersion()
5 — the DragonBones data format this runtime reads, for the SDK's version gate.
const char * db_getArmatures(int handle)
["armatureA","armatureB"] — a DragonBones file names more than one.
void db_setTimeScale(int instanceId, float scale)
int db_getMeshBatchCount(int instanceId)
void db_unloadSkeleton(int handle)
int db_getMeshBatchVertexCount(int instanceId, int batchIndex)
const char * db_getAtlasImageName(int handle)
The image this file's atlas expects, so the caller knows what to upload.
int db_loadSkeleton(uintptr_t skeletonPtr, int skeletonLen, uintptr_t atlasPtr, int atlasLen)
const char * db_getBones(int instanceId)
int db_getMeshBatchIndexCount(int instanceId, int batchIndex)
int db_createInstance(int skeletonHandle, const char *armatureName)
#define EMSCRIPTEN_KEEPALIVE
const char * db_getAnimations(int instanceId)
void db_getMeshBatchData(int instanceId, int batchIndex, uintptr_t outVerticesPtr, uintptr_t outIndicesPtr, uintptr_t outTextureIdPtr, uintptr_t outBlendModePtr)
int db_playAnimation(int instanceId, const char *name, int playTimes)
playTimes: -1 keeps what the data says, 0 loops, n plays n times.
void db_destroyInstance(int instanceId)
void db_setAtlasTexture(int handle, uint32_t textureId)
void db_getBounds(int instanceId, uintptr_t outXPtr, uintptr_t outYPtr, uintptr_t outWPtr, uintptr_t outHPtr)
int db_fadeInAnimation(int instanceId, const char *name, float fadeSeconds, int playTimes)
Where Spine would set a mix duration: DragonBones fades at the moment of play.
const char * db_getLastError()
PhysicsContext g_ctx
What every 2D skeletal-animation side module needs, none of which is about any particular one.
static EsFactory & instance()
Armature * buildArmature(const std::string &armatureName, const std::string &dragonBonesName)
Build an armature by name; null when this data holds no such armature.
void advanceTime(float passedTime)
std::size_t size() const
const T * data() const
constexpr int VERTEX_FLOATS
Interleaved x,y,u,v,r,g,b,a per vertex — the layout the SDK reads back.
One draw's worth of geometry.
Buffer< std::uint16_t > indices