-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
comp_spine_model.cpp
1535 lines (1278 loc) · 64.4 KB
/
comp_spine_model.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 The Defold Foundation
// Licensed under the Defold License version 1.0 (the "License"); you may not use
// this file except in compliance with the License.
//
// You may obtain a copy of the License, together with FAQs at
// https://www.defold.com/license
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#include "comp_spine_model.h"
#include "res_spine_scene.h"
extern "C" {
#include <spine/AnimationState.h>
#include <spine/Attachment.h>
#include <spine/Bone.h>
#include <spine/MeshAttachment.h>
#include <spine/RegionAttachment.h>
#include <spine/Skeleton.h>
#include <spine/SkeletonBounds.h>
#include <spine/SkeletonClipping.h>
#include <spine/Slot.h>
#include <spine/extension.h>
} // extern C
#include <string.h> // memset
#include <dmsdk/script.h>
#include <dmsdk/dlib/array.h>
#include <dmsdk/dlib/log.h>
#include <dmsdk/dlib/math.h>
#include <dmsdk/dlib/vmath.h>
#include <dmsdk/dlib/intersection.h>
#include <dmsdk/dlib/object_pool.h>
#include <dmsdk/dlib/profile.h>
#include <dmsdk/gameobject/component.h>
#include <dmsdk/gamesys/property.h>
#include <dmsdk/gamesys/resources/res_textureset.h>
#include <dmsdk/resource/resource.hpp>
#include <gameobject/gameobject_ddf.h>
#include <common/vertices.h>
#define _USE_MATH_DEFINES
#include <math.h> // M_PI
DM_PROPERTY_GROUP(rmtp_Spine, "Spine");
DM_PROPERTY_U32(rmtp_SpineBones, 0, FrameReset, "# spine bones", &rmtp_Spine);
DM_PROPERTY_U32(rmtp_SpineComponents, 0, FrameReset, "# spine components", &rmtp_Spine);
namespace dmSpine
{
using namespace dmVMath;
static const dmhash_t PROP_SKIN = dmHashString64("skin");
static const dmhash_t PROP_ANIMATION = dmHashString64("animation");
static const dmhash_t PROP_CURSOR = dmHashString64("cursor");
static const dmhash_t PROP_PLAYBACK_RATE = dmHashString64("playback_rate");
static const dmhash_t PROP_MATERIAL = dmHashString64("material");
static const dmhash_t MATERIAL_EXT_HASH = dmHashString64("materialc");
static const uint32_t INVALID_ANIMATION_INDEX = 0xFFFFFFFF;
static void ResourceReloadedCallback(const dmResource::ResourceReloadedParams* params);
static void DestroyComponent(struct SpineModelWorld* world, uint32_t index);
struct SpineModelWorld
{
dmObjectPool<SpineModelComponent*> m_Components;
dmArray<dmRender::RenderObject> m_RenderObjects;
dmArray<dmSpine::SpineModelBounds> m_BoundingBoxes;
dmGraphics::HVertexDeclaration m_VertexDeclaration;
dmGraphics::HVertexBuffer m_VertexBuffer;
dmArray<dmSpine::SpineVertex> m_VertexBufferData;
dmArray<SpineDrawDesc> m_DrawDescBuffer;
dmResource::HFactory m_Factory;
spSkeletonClipping* m_SkeletonClipper;
};
struct SpineModelContext
{
SpineModelContext()
{
memset(this, 0, sizeof(*this));
}
dmResource::HFactory m_Factory;
dmRender::HRenderContext m_RenderContext;
dmGraphics::HContext m_GraphicsContext;
uint32_t m_MaxSpineModelCount;
};
dmGameObject::CreateResult CompSpineModelNewWorld(const dmGameObject::ComponentNewWorldParams& params)
{
SpineModelContext* context = (SpineModelContext*)params.m_Context;
//dmRender::HRenderContext render_context = context->m_RenderContext;
SpineModelWorld* world = new SpineModelWorld();
world->m_Factory = context->m_Factory;
uint32_t comp_count = dmMath::Min(params.m_MaxComponentInstances, context->m_MaxSpineModelCount);
world->m_Components.SetCapacity(comp_count);
world->m_RenderObjects.SetCapacity(comp_count);
world->m_BoundingBoxes.SetCapacity(comp_count);
world->m_BoundingBoxes.SetSize(comp_count);
dmGraphics::HVertexStreamDeclaration stream_declaration = dmGraphics::NewVertexStreamDeclaration(context->m_GraphicsContext);
dmGraphics::AddVertexStream(stream_declaration, "position", 3, dmGraphics::TYPE_FLOAT, false);
dmGraphics::AddVertexStream(stream_declaration, "texcoord0", 2, dmGraphics::TYPE_FLOAT, true);
dmGraphics::AddVertexStream(stream_declaration, "color", 4, dmGraphics::TYPE_FLOAT, true);
dmGraphics::AddVertexStream(stream_declaration, "page_index", 1, dmGraphics::TYPE_FLOAT, false);
world->m_VertexDeclaration = dmGraphics::NewVertexDeclaration(context->m_GraphicsContext, stream_declaration);
world->m_VertexBuffer = dmGraphics::NewVertexBuffer(context->m_GraphicsContext, 0, 0x0, dmGraphics::BUFFER_USAGE_DYNAMIC_DRAW);
dmGraphics::DeleteVertexStreamDeclaration(stream_declaration);
*params.m_World = world;
dmResource::RegisterResourceReloadedCallback(context->m_Factory, ResourceReloadedCallback, world);
world->m_SkeletonClipper = spSkeletonClipping_create();
return dmGameObject::CREATE_RESULT_OK;
}
dmGameObject::CreateResult CompSpineModelDeleteWorld(const dmGameObject::ComponentDeleteWorldParams& params)
{
SpineModelWorld* world = (SpineModelWorld*)params.m_World;
dmGraphics::DeleteVertexDeclaration(world->m_VertexDeclaration);
dmGraphics::DeleteVertexBuffer(world->m_VertexBuffer);
dmResource::UnregisterResourceReloadedCallback(((SpineModelContext*)params.m_Context)->m_Factory, ResourceReloadedCallback, world);
spSkeletonClipping_dispose(world->m_SkeletonClipper);
delete world;
return dmGameObject::CREATE_RESULT_OK;
}
static inline dmRender::HMaterial GetMaterial(const SpineModelComponent* component) {
return component->m_Material ? component->m_Material : component->m_Resource->m_Material->m_Material;
}
static void ReHash(SpineModelComponent* component)
{
// material, texture set, blend mode and render constants
HashState32 state;
bool reverse = false;
SpineModelResource* resource = component->m_Resource;
dmGameSystemDDF::SpineModelDesc* ddf = resource->m_Ddf;
dmRender::HMaterial material = GetMaterial(component);
dmGameSystem::TextureSetResource* texture_set = resource->m_SpineScene->m_TextureSet;
dmHashInit32(&state, reverse);
dmHashUpdateBuffer32(&state, &material, sizeof(material));
dmHashUpdateBuffer32(&state, &texture_set, sizeof(texture_set));
dmHashUpdateBuffer32(&state, &ddf->m_BlendMode, sizeof(ddf->m_BlendMode));
if (component->m_RenderConstants)
dmGameSystem::HashRenderConstants(component->m_RenderConstants, &state);
component->m_MixedHash = dmHashFinal32(&state);
component->m_ReHash = 0;
}
static void SetTransformFromBone(dmGameObject::HInstance instance, const dmTransform::Transform& parent, const spBone* bone)
{
float radians = spBone_getWorldRotationX((spBone*)bone) * M_PI / 180.0f;
float sx = spBone_getWorldScaleX((spBone*)bone);
float sy = spBone_getWorldScaleY((spBone*)bone);
dmTransform::Transform local = dmTransform::Transform( dmVMath::Vector3(bone->worldX, bone->worldY, 0),
dmVMath::Quat::rotationZ(radians),
dmVMath::Vector3(sx, sy, 1));
dmTransform::Transform transform = dmTransform::Mul(parent, local);
dmGameObject::SetPosition(instance, Point3(transform.GetTranslation()));
dmGameObject::SetRotation(instance, transform.GetRotation());
dmGameObject::SetScale(instance, transform.GetScale());
}
static bool CreateGOBone(SpineModelComponent* component, dmGameObject::HCollection collection, dmGameObject::HInstance goparent, spBone* parent, spBone* bone, int indent)
{
dmGameObject::HInstance bone_instance = dmGameObject::New(collection, 0x0);
if (!bone_instance)
{
dmLogError("Failed to create bone game object");
return false;
}
dmGameObject::SetBone(bone_instance, true); // flag it as a bone instance
dmGameObject::SetParent(bone_instance, goparent);
uint32_t index = dmGameObject::AcquireInstanceIndex(collection);
if (index == dmGameObject::INVALID_INSTANCE_POOL_INDEX)
{
dmLogError("Failed to acquire instance index for bone game object");
return false;
}
dmhash_t id = dmGameObject::ConstructInstanceId(index);
dmGameObject::AssignInstanceIndex(index, bone_instance);
dmGameObject::Result result = dmGameObject::SetIdentifier(collection, bone_instance, id);
if (dmGameObject::RESULT_OK != result)
{
dmLogError("Failed to set identifier for bone game object");
return false;
}
SetTransformFromBone(bone_instance, component->m_Transform, bone);
dmhash_t name_hash = dmHashString64(bone->data->name);
component->m_BoneNameToNodeInstanceIndex.Put(name_hash, component->m_BoneInstances.Size());
component->m_BoneInstances.Push(bone_instance);
component->m_Bones.Push(bone);
// Create the children
for (int n = 0; n < bone->childrenCount; ++n)
{
// Since I haven't figured out how to update the local transforms, we do it in world space
// However, that means all bones are parented to the top game object
if (!CreateGOBone(component, collection, component->m_Instance, bone, bone->children[n], indent + 2))
//if (!CreateGOBone(component, collection, bone_instance, bone, bone->children[n], indent + 2))
return false;
}
return true;
}
static bool CreateGOBones(SpineModelWorld* world, SpineModelComponent* component)
{
//dmGameObject::HCollection collection = dmGameObject::GetCollection(component->m_Instance);
SpineModelResource* spine_model = component->m_Resource;
//SpineSceneResource* spine_scene = spine_model->m_SpineScene;
spSkeleton* skeleton = component->m_SkeletonInstance;
component->m_Bones.SetCapacity(skeleton->bonesCount);
component->m_BoneInstances.SetCapacity(skeleton->bonesCount);
component->m_BoneNameToNodeInstanceIndex.SetCapacity((skeleton->bonesCount+1)/2, skeleton->bonesCount);
if (!CreateGOBone(component, dmGameObject::GetCollection(component->m_Instance), component->m_Instance, 0, skeleton->root, 0))
{
dmLogError("Failed to create bones");
dmGameObject::DeleteBones(component->m_Instance); // iterates recursively and deletes the ones marked as a bone
component->m_BoneInstances.SetSize(0);
return false;
}
return true;
}
static inline SpineModelComponent* GetComponentFromIndex(SpineModelWorld* world, int index)
{
return world->m_Components.Get(index);
}
static void* CompSpineModelGetComponent(const dmGameObject::ComponentGetParams& params)
{
SpineModelWorld* world = (SpineModelWorld*)params.m_World;
uint32_t index = (uint32_t) params.m_UserData;
return GetComponentFromIndex(world, index);
}
static inline uint32_t FindAnimationIndex(SpineModelComponent* component, dmhash_t animation)
{
SpineModelResource* spine_model = component->m_Resource;
SpineSceneResource* spine_scene = spine_model->m_SpineScene;
uint32_t* index = spine_scene->m_AnimationNameToIndex.Get(animation);
return index ? *index : INVALID_ANIMATION_INDEX;
}
static inline bool IsLooping(dmGameObject::Playback playback)
{
return playback == dmGameObject::PLAYBACK_LOOP_BACKWARD ||
playback == dmGameObject::PLAYBACK_LOOP_FORWARD ||
playback == dmGameObject::PLAYBACK_LOOP_PINGPONG;
}
static inline bool IsReverse(dmGameObject::Playback playback)
{
return playback == dmGameObject::PLAYBACK_LOOP_BACKWARD ||
playback == dmGameObject::PLAYBACK_ONCE_BACKWARD;
}
static inline bool IsPingPong(dmGameObject::Playback playback)
{
return playback == dmGameObject::PLAYBACK_LOOP_PINGPONG ||
playback == dmGameObject::PLAYBACK_ONCE_PINGPONG;
}
static SpineAnimationTrack* GetTrackFromIndex(SpineModelComponent* component, int track_index)
{
if (track_index < 0 || track_index >= component->m_AnimationTracks.Size())
return nullptr;
return &component->m_AnimationTracks[track_index];
}
static void ClearCompletionCallback(SpineAnimationTrack* track)
{
if (track->m_CallbackInfo)
{
dmScript::DestroyCallback(track->m_CallbackInfo);
track->m_CallbackInfo = 0x0;
}
}
static bool PlayAnimation(SpineModelComponent* component, dmhash_t animation_id, dmGameObject::Playback playback,
float blend_duration, float offset, float playback_rate, int track_index)
{
uint32_t index = FindAnimationIndex(component, animation_id);
if (index == INVALID_ANIMATION_INDEX)
{
dmLogError("No animation '%s' found", dmHashReverseSafe64(animation_id));
return false;
}
SpineModelResource* spine_model = component->m_Resource;
SpineSceneResource* spine_scene = spine_model->m_SpineScene;
int loop = IsLooping(playback);
if (index >= spine_scene->m_Skeleton->animationsCount)
{
dmLogError("No animation index %u is too large. Number of animations are %u", index, spine_scene->m_Skeleton->animationsCount);
return false;
}
spAnimation* animation = spine_scene->m_Skeleton->animations[index];
if (track_index < 0)
{
dmLogError("Invalid track index %d", track_index);
return false;
}
if (track_index >= component->m_AnimationTracks.Capacity())
{
component->m_AnimationTracks.SetCapacity(track_index + 4);
}
while (track_index >= component->m_AnimationTracks.Size())
{
SpineAnimationTrack track;
track.m_AnimationInstance = nullptr;
track.m_CallbackInfo = 0x0;
component->m_AnimationTracks.Push(track);
}
SpineAnimationTrack& track = component->m_AnimationTracks[track_index];
ClearCompletionCallback(&track);
track.m_AnimationId = animation_id;
track.m_AnimationInstance = spAnimationState_setAnimation(component->m_AnimationStateInstance, track_index, animation, loop);
track.m_Playback = playback;
track.m_AnimationInstance->timeScale = playback_rate;
track.m_AnimationInstance->reverse = IsReverse(playback);
track.m_AnimationInstance->mixDuration = blend_duration;
track.m_AnimationInstance->trackTime = dmMath::Clamp(offset, track.m_AnimationInstance->animationStart, track.m_AnimationInstance->animationEnd);
track.m_CallbackInfo = 0x0;
dmMessage::ResetURL(&track.m_Listener);
return true;
}
static void CancelTrackAnimation(SpineModelComponent* component, int32_t track_index)
{
SpineAnimationTrack* track = GetTrackFromIndex(component, track_index);
if (!track || !track->m_AnimationInstance)
return;
spAnimationState_clearTrack(component->m_AnimationStateInstance, track->m_AnimationInstance->trackIndex);
ClearCompletionCallback(track);
track->m_AnimationInstance = nullptr;
}
static void CancelAllAnimations(SpineModelComponent* component)
{
for (int32_t i = 0; i < component->m_AnimationTracks.Size(); i++) {
CancelTrackAnimation(component, i);
}
}
static bool GetSender(SpineModelComponent* component, dmMessage::URL* out_sender)
{
dmMessage::URL sender;
sender.m_Socket = dmGameObject::GetMessageSocket(dmGameObject::GetCollection(component->m_Instance));
if (dmMessage::IsSocketValid(sender.m_Socket))
{
dmGameObject::Result go_result = dmGameObject::GetComponentId(component->m_Instance, component->m_ComponentIndex, &sender.m_Fragment);
if (go_result == dmGameObject::RESULT_OK)
{
sender.m_Path = dmGameObject::GetIdentifier(component->m_Instance);
*out_sender = sender;
return true;
}
}
return false;
}
static void SendAnimationDone(SpineModelComponent* component, const spAnimationState* state, const spTrackEntry* entry, const spEvent* event)
{
SpineAnimationTrack& track = component->m_AnimationTracks[entry->trackIndex];
dmMessage::URL sender;
dmMessage::URL receiver = track.m_Listener;
if (!GetSender(component, &sender))
{
dmLogError("Could not send animation_done to listener because of incomplete component.");
return;
}
dmGameSystemDDF::SpineAnimationDone message;
message.m_AnimationId = dmHashString64(entry->animation->name);
message.m_Playback = track.m_Playback;
message.m_Track = entry->trackIndex + 1;
if (track.m_CallbackInfo)
{
uint32_t id = track.m_CallbackId;
RunTrackCallback(track.m_CallbackInfo, dmGameSystemDDF::SpineAnimationDone::m_DDFDescriptor, (const char*)&message, &sender);
// If, in a Lua callback, the user calls spine.play_anim(),
// it will destroy the current callback and create a new one (if specified).
// Therefore, we need to check whether we are going to remove the same callback
// that we are running. If not, it has already been removed.
if (id == track.m_CallbackId)
{
ClearCompletionCallback(&track);
}
}
else
{
dmGameObject::Result result = dmGameObject::PostDDF(&message, &sender, &receiver, 0, true);
if (result != dmGameObject::RESULT_OK)
{
dmLogError("Could not send animation_done to listener: %d", result);
}
}
}
static void SendSpineEvent(SpineModelComponent* component, const spAnimationState* state, const spTrackEntry* entry, const spEvent* event)
{
SpineAnimationTrack& track = component->m_AnimationTracks[entry->trackIndex];
dmMessage::URL sender;
dmMessage::URL receiver = track.m_Listener;
if (!GetSender(component, &sender))
{
dmLogError("Could not send animation_done to listener because of incomplete component.");
return;
}
if (!dmMessage::IsSocketValid(receiver.m_Socket))
{
receiver = sender;
receiver.m_Fragment = 0;
}
dmGameSystemDDF::SpineEvent message;
message.m_AnimationId = dmHashString64(entry->animation->name);
message.m_EventId = dmHashString64(event->data->name);
message.m_BlendWeight = 0.0f;//keyframe_event->m_BlendWeight;
message.m_T = event->time;
message.m_Integer = event->intValue;
message.m_Float = event->floatValue;
message.m_String = dmHashString64(event->stringValue?event->stringValue:"");
message.m_Node.m_Ref = 0;
message.m_Node.m_ContextTableRef = 0;
message.m_Track = entry->trackIndex + 1;
if (track.m_CallbackInfo)
{
RunTrackCallback(track.m_CallbackInfo, dmGameSystemDDF::SpineEvent::m_DDFDescriptor, (const char*)&message, &sender);
}
else
{
dmGameObject::Result result = dmGameObject::PostDDF(&message, &sender, &receiver, 0, false);
if (result != dmGameObject::RESULT_OK)
{
dmLogError("Could not send animation event '%s' from animation '%s' to listener: %d", entry->animation->name, event->data->name, result);
}
}
}
static void SpineEventListener(spAnimationState* state, spEventType type, spTrackEntry* entry, spEvent* event)
{
SpineModelComponent* component = (SpineModelComponent*)state->userData;
// Events are explained here: http://esotericsoftware.com/spine-api-reference#AnimationStateListener
switch (type)
{
// case SP_ANIMATION_START:
// {
// printf("Animation %s started on track %i\n", entry->animation->name, entry->trackIndex);
// break;
// }
// case SP_ANIMATION_INTERRUPT:
// {
// printf("Animation %s interrupted on track %i\n", entry->animation->name, entry->trackIndex);
// break;
// }
// case SP_ANIMATION_END:
// {
// printf("Animation %s ended on track %i\n", entry->animation->name, entry->trackIndex);
// break;
// }
case SP_ANIMATION_COMPLETE:
{
if (entry->mixingTo != 0)
{
// While mixing, the previous animation completed.
// The problem is that the track is already owned by the new animation, and we
// cannot call the previous callback (as we haven't stored it)
return;
}
SpineAnimationTrack& track = component->m_AnimationTracks[entry->trackIndex];
// Should we look at the looping state?
if (!IsLooping(track.m_Playback))
{
// We only send the event if it's not looping (same behavior as before)
SendAnimationDone(component, state, entry, event);
}
if (IsPingPong(track.m_Playback))
{
track.m_AnimationInstance->reverse = !track.m_AnimationInstance->reverse;
}
break;
}
case SP_ANIMATION_DISPOSE:
{
SpineAnimationTrack* track = GetTrackFromIndex(component, entry->trackIndex);
if (track && track->m_AnimationInstance == entry)
{
ClearCompletionCallback(track);
track->m_AnimationInstance = nullptr;
}
break;
}
case SP_ANIMATION_EVENT:
SendSpineEvent(component, state, entry, event);
break;
default:
break;
}
}
dmGameObject::CreateResult CompSpineModelCreate(const dmGameObject::ComponentCreateParams& params)
{
SpineModelWorld* world = (SpineModelWorld*)params.m_World;
if (world->m_Components.Full())
{
dmLogError("Spine Model could not be created since the buffer is full (%d).", world->m_Components.Capacity());
return dmGameObject::CREATE_RESULT_UNKNOWN_ERROR;
}
SpineModelResource* spine_model = (SpineModelResource*)params.m_Resource;
SpineSceneResource* spine_scene = spine_model->m_SpineScene;
uint32_t index = world->m_Components.Alloc();
SpineModelComponent* component = new SpineModelComponent;
memset(component, 0, sizeof(SpineModelComponent));
world->m_Components.Set(index, component);
component->m_Instance = params.m_Instance;
component->m_Transform = dmTransform::Transform(Vector3(params.m_Position), params.m_Rotation, params.m_Scale);
component->m_Resource = (SpineModelResource*)params.m_Resource;
component->m_ComponentIndex = params.m_ComponentIndex;
component->m_Enabled = 1;
component->m_World = Matrix4::identity();
component->m_DoRender = 0;
component->m_RenderConstants = 0;
component->m_SkeletonInstance = spSkeleton_create(spine_scene->m_Skeleton);
if (!component->m_SkeletonInstance)
{
dmLogError("Failed to create skeleton instance");
DestroyComponent(world, index);
return dmGameObject::CREATE_RESULT_UNKNOWN_ERROR;
}
if (0 == spSkeleton_setSkinByName(component->m_SkeletonInstance, component->m_Resource->m_Ddf->m_Skin))
{
spSkeleton_setSkin(component->m_SkeletonInstance, spine_scene->m_Skeleton->defaultSkin);
}
spSkeleton_setSlotsToSetupPose(component->m_SkeletonInstance);
component->m_AnimationStateInstance = spAnimationState_create(spine_scene->m_AnimationStateData);
if (!component->m_AnimationStateInstance)
{
dmLogError("Failed to create animation state instance");
DestroyComponent(world, index);
return dmGameObject::CREATE_RESULT_UNKNOWN_ERROR;
}
component->m_AnimationStateInstance->userData = component;
component->m_AnimationStateInstance->listener = SpineEventListener;
component->m_AnimationTracks.SetCapacity(8);
spSkeleton_setToSetupPose(component->m_SkeletonInstance);
spSkeleton_updateWorldTransform(component->m_SkeletonInstance, SP_PHYSICS_UPDATE);
// Create GO<->bone representation
// We need to make sure that bone GOs are created before we start the default animation.
if (spine_model->m_CreateGoBones)
{
if (!CreateGOBones(world, component))
{
dmLogError("Failed to create game objects for bones in spine model. Consider increasing collection max instances (collection.max_instances).");
DestroyComponent(world, index);
return dmGameObject::CREATE_RESULT_UNKNOWN_ERROR;
}
}
dmhash_t animation_id = dmHashString64(component->m_Resource->m_Ddf->m_DefaultAnimation);
PlayAnimation(component, animation_id, dmGameObject::PLAYBACK_LOOP_FORWARD, 0.0f,
component->m_Resource->m_Ddf->m_Offset, component->m_Resource->m_Ddf->m_PlaybackRate, 0);
// TODO: Is the default playmode specified anywhere?
component->m_ReHash = 1;
*params.m_UserData = (uintptr_t)index;
return dmGameObject::CREATE_RESULT_OK;
}
static void DestroyComponent(SpineModelWorld* world, uint32_t index)
{
SpineModelComponent* component = world->m_Components.Get(index);
dmGameObject::DeleteBones(component->m_Instance);
// If we're going to use memset, then we should explicitly clear pose and instance arrays.
component->m_BoneInstances.SetCapacity(0);
component->m_AnimationTracks.SetCapacity(0);
if (component->m_Material)
{
dmResource::Release(world->m_Factory, (void*)component->m_Material);
}
if (component->m_RenderConstants)
{
dmGameSystem::DestroyRenderConstants(component->m_RenderConstants);
}
if (component->m_AnimationStateInstance)
spAnimationState_dispose(component->m_AnimationStateInstance);
if (component->m_SkeletonInstance)
spSkeleton_dispose(component->m_SkeletonInstance);
delete component;
world->m_Components.Free(index, true);
}
dmGameObject::CreateResult CompSpineModelDestroy(const dmGameObject::ComponentDestroyParams& params)
{
//SpineModelContext* ctx = (SpineModelContext*)params.m_Context;
SpineModelWorld* world = (SpineModelWorld*)params.m_World;
uint32_t index = *params.m_UserData;
DestroyComponent(world, index);
return dmGameObject::CREATE_RESULT_OK;
}
static void UpdateBones(SpineModelComponent* component)
{
if (component->m_BoneInstances.Empty())
return;
uint32_t size = component->m_Bones.Size();
dmArray<dmTransform::Transform> transforms;
transforms.SetCapacity(size);
transforms.SetSize(size);
DM_PROPERTY_ADD_U32(rmtp_SpineBones, size);
for (uint32_t n = 0; n < size; ++n)
{
spBone* bone = component->m_Bones[n];
dmGameObject::HInstance bone_instance = component->m_BoneInstances[n];
SetTransformFromBone(bone_instance, component->m_Transform, bone);
}
}
dmGameObject::CreateResult CompSpineModelAddToUpdate(const dmGameObject::ComponentAddToUpdateParams& params)
{
SpineModelWorld* world = (SpineModelWorld*)params.m_World;
uint32_t index = (uint32_t)*params.m_UserData;
SpineModelComponent* component = GetComponentFromIndex(world, index);
component->m_AddedToUpdate = true;
return dmGameObject::CREATE_RESULT_OK;
}
static void ApplyIKTargets(SpineModelComponent* component)
{
uint32_t count = component->m_IKTargetPositions.Size();
for (uint32_t i = 0; i < count; ++i)
{
const IKTarget& target = component->m_IKTargetPositions[i];
dmVMath::Vector3 model_pos = (dmVMath::Vector3)dmTransform::Apply(dmTransform::Inv(dmTransform::Mul(dmGameObject::GetWorldTransform(component->m_Instance), component->m_Transform)), target.m_Position);
target.m_Constraint->target->x = model_pos.getX();
target.m_Constraint->target->y = model_pos.getY();
}
component->m_IKTargetPositions.SetSize(0);
count = component->m_IKTargets.Size();
for (uint32_t i = 0; i < count; ++i)
{
const IKTarget& target = component->m_IKTargets[i];
dmVMath::Vector3 model_pos = (dmVMath::Vector3)dmTransform::Apply(dmTransform::Inv(dmTransform::Mul(dmGameObject::GetWorldTransform(component->m_Instance), component->m_Transform)),
dmGameObject::GetWorldPosition(target.m_Target));
target.m_Constraint->target->x = model_pos.getX();
target.m_Constraint->target->y = model_pos.getY();
}
}
dmGameObject::UpdateResult CompSpineModelUpdate(const dmGameObject::ComponentsUpdateParams& params, dmGameObject::ComponentsUpdateResult& update_result)
{
SpineModelWorld* world = (SpineModelWorld*)params.m_World;
float dt = params.m_UpdateContext->m_DT;
dmArray<SpineModelComponent*>& components = world->m_Components.GetRawObjects();
const uint32_t count = components.Size();
DM_PROPERTY_ADD_U32(rmtp_SpineComponents, count);
uint32_t num_active = 0;
for (uint32_t i = 0; i < count; ++i)
{
SpineModelComponent& component = *components[i];
component.m_DoRender = 0;
if (!component.m_SkeletonInstance || !component.m_AnimationStateInstance)
{
component.m_Enabled = false;
}
if (!component.m_Enabled || !component.m_AddedToUpdate)
continue;
const Matrix4& go_world = dmGameObject::GetWorldMatrix(component.m_Instance);
const Matrix4 local = dmTransform::ToMatrix4(component.m_Transform);
// if (dmGameObject::ScaleAlongZ(component.m_Instance))
// {
// component.m_World = go_world * local;
// }
// else
{
component.m_World = dmTransform::MulNoScaleZ(go_world, local);
}
++num_active;
// docs: http://esotericsoftware.com/spine-runtime-skeletons
spAnimationState_update(component.m_AnimationStateInstance, dt);
spAnimationState_apply(component.m_AnimationStateInstance, component.m_SkeletonInstance);
ApplyIKTargets(&component);
spSkeleton_update(component.m_SkeletonInstance, dt);
spSkeleton_updateWorldTransform(component.m_SkeletonInstance, SP_PHYSICS_UPDATE);
// Update the game world objects
UpdateBones(&component);
if (component.m_ReHash || (component.m_RenderConstants && dmGameSystem::AreRenderConstantsUpdated(component.m_RenderConstants)))
{
ReHash(&component);
}
component.m_DoRender = 1;
}
// Since we've moved the child game objects (bones), we need to sync back the transforms
update_result.m_TransformsUpdated = num_active > 0;
return dmGameObject::UPDATE_RESULT_OK;
}
static inline dmGameSystemDDF::SpineModelDesc::BlendMode SpineBlendModeToRenderBlendMode(spBlendMode sp_blend_mode)
{
switch(sp_blend_mode)
{
case SP_BLEND_MODE_NORMAL:
return dmGameSystemDDF::SpineModelDesc::BLEND_MODE_ALPHA;
case SP_BLEND_MODE_ADDITIVE:
return dmGameSystemDDF::SpineModelDesc::BLEND_MODE_ADD;
case SP_BLEND_MODE_MULTIPLY:
return dmGameSystemDDF::SpineModelDesc::BLEND_MODE_MULT;
case SP_BLEND_MODE_SCREEN:
return dmGameSystemDDF::SpineModelDesc::BLEND_MODE_SCREEN;
default:break;
}
return dmGameSystemDDF::SpineModelDesc::BLEND_MODE_ALPHA;
}
static void FillRenderObject(SpineModelWorld* world,
dmRender::HRenderContext render_context,
dmRender::RenderObject& ro,
dmGameSystem::HComponentRenderConstants constants,
dmGraphics::HTexture texture,
dmRender::HMaterial material,
dmGameSystemDDF::SpineModelDesc::BlendMode blend_mode,
uint32_t vertex_start,
uint32_t vertex_count)
{
ro.Init();
ro.m_VertexDeclaration = world->m_VertexDeclaration;
ro.m_VertexBuffer = world->m_VertexBuffer;
ro.m_PrimitiveType = dmGraphics::PRIMITIVE_TRIANGLES;
ro.m_VertexStart = vertex_start;
ro.m_VertexCount = vertex_count;
ro.m_Textures[0] = texture;
ro.m_Material = material;
if (constants)
{
dmGameSystem::EnableRenderObjectConstants(&ro, constants);
}
ro.m_SetBlendFactors = 1;
switch (blend_mode)
{
case dmGameSystemDDF::SpineModelDesc::BLEND_MODE_ALPHA:
ro.m_SourceBlendFactor = dmGraphics::BLEND_FACTOR_ONE;
ro.m_DestinationBlendFactor = dmGraphics::BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
break;
case dmGameSystemDDF::SpineModelDesc::BLEND_MODE_ADD:
ro.m_SourceBlendFactor = dmGraphics::BLEND_FACTOR_ONE;
ro.m_DestinationBlendFactor = dmGraphics::BLEND_FACTOR_ONE;
break;
case dmGameSystemDDF::SpineModelDesc::BLEND_MODE_MULT:
ro.m_SourceBlendFactor = dmGraphics::BLEND_FACTOR_DST_COLOR;
ro.m_DestinationBlendFactor = dmGraphics::BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
break;
case dmGameSystemDDF::SpineModelDesc::BLEND_MODE_SCREEN:
ro.m_SourceBlendFactor = dmGraphics::BLEND_FACTOR_ONE_MINUS_DST_COLOR;
ro.m_DestinationBlendFactor = dmGraphics::BLEND_FACTOR_ONE;
break;
default:
dmLogError("Unknown blend mode: %d\n", blend_mode);
assert(0);
break;
}
dmRender::AddToRender(render_context, &ro);
}
static void RenderBatch(SpineModelWorld* world, dmRender::HRenderContext render_context, dmRender::RenderListEntry *buf, uint32_t* begin, uint32_t* end)
{
//DM_PROFILE(SpineModel, "RenderBatch");
dmArray<SpineModelComponent*>& components = world->m_Components.GetRawObjects();
uint32_t component_index = (uint32_t)buf[*begin].m_UserData;
const SpineModelComponent* first = (const SpineModelComponent*) components[component_index];
const SpineModelResource* resource = first->m_Resource;
dmGameSystemDDF::SpineModelDesc::BlendMode blend_mode = resource->m_Ddf->m_BlendMode;
bool use_inherit_blend = blend_mode == dmGameSystemDDF::SpineModelDesc::BLEND_MODE_INHERIT;
uint32_t vertex_start = world->m_VertexBufferData.Size();
uint32_t vertex_count = 0;
uint32_t draw_desc_buffer_count = 0;
// This is a temporary scratch buffer just used for this batch call, so we make sure to reset it.
world->m_DrawDescBuffer.SetSize(0);
for (uint32_t *i = begin; i != end; ++i)
{
component_index = (uint32_t)buf[*i].m_UserData;
const SpineModelComponent* component = (const SpineModelComponent*) components[component_index];
vertex_count += dmSpine::CalcVertexBufferSize(component->m_SkeletonInstance, world->m_SkeletonClipper, 0);
if (use_inherit_blend)
{
draw_desc_buffer_count += dmSpine::CalcDrawDescCount(component->m_SkeletonInstance);
}
}
if (draw_desc_buffer_count && draw_desc_buffer_count > world->m_DrawDescBuffer.Capacity())
{
world->m_DrawDescBuffer.SetCapacity(draw_desc_buffer_count);
}
if (vertex_count > world->m_VertexBufferData.Capacity())
{
world->m_VertexBufferData.SetCapacity(vertex_count);
}
vertex_count = 0;
for (uint32_t *i = begin; i != end; ++i)
{
component_index = (uint32_t)buf[*i].m_UserData;
const SpineModelComponent* component = (const SpineModelComponent*) components[component_index];
vertex_count += dmSpine::GenerateVertexData(world->m_VertexBufferData, component->m_SkeletonInstance, world->m_SkeletonClipper, component->m_World, use_inherit_blend ? &world->m_DrawDescBuffer : 0);
}
dmGraphics::HTexture texture = resource->m_SpineScene->m_TextureSet->m_Texture->m_Texture; // spine - texture set resource - texture resource - texture
dmRender::HMaterial material = GetMaterial(first);
if (use_inherit_blend)
{
uint32_t draw_desc_count = world->m_DrawDescBuffer.Size();
if (draw_desc_count > 0)
{
dmArray<SpineDrawDesc> scratch_draw_descs;
MergeDrawDescs(world->m_DrawDescBuffer, scratch_draw_descs);
uint32_t merged_size = scratch_draw_descs.Size();
uint32_t ro_count_begin = world->m_RenderObjects.Size();
world->m_RenderObjects.SetSize(world->m_RenderObjects.Size() + merged_size);
for (int i = 0; i < merged_size; ++i)
{
dmRender::RenderObject& ro = world->m_RenderObjects[ro_count_begin + i];
FillRenderObject(world, render_context, ro, first->m_RenderConstants, texture, material,
SpineBlendModeToRenderBlendMode((spBlendMode) scratch_draw_descs[i].m_BlendMode),
scratch_draw_descs[i].m_VertexStart,
scratch_draw_descs[i].m_VertexCount);
}
}
}
else
{
uint32_t ro_index = world->m_RenderObjects.Size();
world->m_RenderObjects.SetSize(ro_index + 1);
dmRender::RenderObject& ro = world->m_RenderObjects[ro_index];
FillRenderObject(world, render_context, ro, first->m_RenderConstants, texture, material, blend_mode, vertex_start, vertex_count);
}
}
static void RenderListFrustumCulling(dmRender::RenderListVisibilityParams const ¶ms)
{
DM_PROFILE("SpineModel");
SpineModelWorld* world = (SpineModelWorld*)params.m_UserData;
dmArray<SpineModelComponent*>& components = world->m_Components.GetRawObjects();
const dmIntersection::Frustum frustum = *params.m_Frustum;
uint32_t num_entries = params.m_NumEntries;
for (uint32_t i = 0; i < num_entries; ++i)
{
dmRender::RenderListEntry* entry = ¶ms.m_Entries[i];
int component_index = entry->m_UserData;
SpineModelComponent* component_p = components[component_index];
const SpineModelBounds& bounds = world->m_BoundingBoxes[component_index];
// get center of bounding box in local coords
float center_x = (bounds.maxX + bounds.minX)/2;
float center_y = (bounds.maxY + bounds.minY)/2;
dmVMath::Point3 center_local(center_x, center_y, 0);
dmVMath::Point3 corner_local(bounds.maxX, bounds.maxY, 0);
// transform to world coords
dmVMath::Vector4 center_world = component_p->m_World * center_local;
dmVMath::Vector4 corner_world = component_p->m_World * corner_local;
float radius = Vectormath::Aos::length(corner_world - center_world);
bool intersect = dmIntersection::TestFrustumSphere(frustum, center_world, radius);
entry->m_Visibility = intersect ? dmRender::VISIBILITY_FULL : dmRender::VISIBILITY_NONE;
}
}
static void RenderListDispatch(dmRender::RenderListDispatchParams const ¶ms)
{
SpineModelWorld *world = (SpineModelWorld *) params.m_UserData;
switch (params.m_Operation)
{
case dmRender::RENDER_LIST_OPERATION_BEGIN:
{
dmGraphics::SetVertexBufferData(world->m_VertexBuffer, 0, 0, dmGraphics::BUFFER_USAGE_DYNAMIC_DRAW);
world->m_RenderObjects.SetSize(0);
world->m_VertexBufferData.SetSize(0);
break;
}
case dmRender::RENDER_LIST_OPERATION_BATCH:
{