Repository navigation
Expand file tree
/
Copy pathsprite_sync_test.go
More file actions
2020 lines (1889 loc) · 71.6 KB
/
Copy pathsprite_sync_test.go
File metadata and controls
2020 lines (1889 loc) · 71.6 KB
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 (c) 2021 The XGo Authors (xgo.dev). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
package spx
import (
"fmt"
"math"
"reflect"
"slices"
"strings"
"sync/atomic"
"testing"
"github.com/goplus/spbase/mathf"
"github.com/goplus/spx/v4/internal/core/collision"
"github.com/goplus/spx/v4/internal/engine"
"github.com/goplus/spx/v4/internal/engine/coroutine"
"github.com/goplus/spx/v4/internal/engine/wrap"
pkgengine "github.com/goplus/spx/v4/pkg/spx/pkg/engine"
)
// Batch submission and transform validation.
func TestFlushSyncBufferOnlySubmitsChanges(t *testing.T) {
game, mgr := setupSyncBufferCapture(t)
game.flushSyncBuffer()
if len(mgr.batches) != 0 {
t.Fatalf("empty buffer submitted %d batches, want 0", len(mgr.batches))
}
game.syncBuffer.AddTransform(1, engine.SpriteTransform{Position: mathf.NewVec2(2, 3), Rotation: 4, Scale: mathf.NewVec2(5, 6), RenderOffset: mathf.NewVec2(7, 8), Visible: true})
game.flushSyncBuffer()
if len(mgr.batches) != 1 {
t.Fatalf("updated buffer submitted %d batches, want 1", len(mgr.batches))
}
game.syncBuffer.Clear()
game.syncBuffer.AddDelete(1)
game.flushSyncBuffer()
if len(mgr.batches) != 2 {
t.Fatalf("delete buffer submitted %d total batches, want 2", len(mgr.batches))
}
}
func TestFlushSyncBufferDoesNotSubmitSerializationFailure(t *testing.T) {
game, mgr := setupSyncBufferCapture(t)
invalidID := int64(1<<24 + 1)
game.syncBuffer.AddTransform(invalidID, engine.SpriteTransform{})
requireSyncPanic(t, game.flushSyncBuffer, "invalid sprite ID", "legacy float32 batch encoding")
if len(mgr.batches) != 0 {
t.Fatalf("serialization failure submitted %d batches, want 0", len(mgr.batches))
}
}
func TestProxyTransformQueryAndBatchMatch(t *testing.T) {
spy := setupSpyPenMgr(t)
sprite := newPenTestSprite()
configurePenRenderOffsetSprite(sprite)
sprite.spriteState.isVisible = true
sprite.transform().direction = 45
sprite.transform().rotationStyle = Normal
sprite.syncProxyForQuery()
if got, want := spy.spriteMgr.position, mathf.NewVec2(50, 60); got != want {
t.Fatalf("query position = %v, want %v", got, want)
}
if got, want := spy.spriteMgr.rotation, engine.DegToRad(-45); got != want {
t.Fatalf("query rotation = %v, want %v", got, want)
}
if got, want := spy.spriteMgr.scale, mathf.NewVec2(1, 1); got != want {
t.Fatalf("query scale = %v, want %v", got, want)
}
if got, want := spy.spriteMgr.renderOffset, mathf.NewVec2(37, -24); got != want {
t.Fatalf("query offset = %v, want %v", got, want)
}
if !spy.spriteMgr.visible {
t.Fatal("query transform hid a visible sprite")
}
buffer := engine.NewSpriteSyncBuffer(1)
sprite.collectProxyUpdate(buffer)
if buffer.UpdateCount() != 0 {
t.Fatal("batch repeated an already synchronized transform")
}
sprite.markProxyDirty()
sprite.collectProxyUpdate(buffer)
want := []float32{1, 0, 101, 50, 60, float32(spy.spriteMgr.rotation), 1, 1, 37, -24, 1}
if got := buffer.Serialize(); !slices.Equal(got, want) {
t.Fatalf("batch transform = %v, want %v", got, want)
}
}
func TestProxyRebuildAndDestroySubmitOnlyPendingTransforms(t *testing.T) {
var game Game
game.scene.init()
mgr := setupCloneSpriteMgr(t)
sprite := newCloneAwakeOrderSprite(&game, "Sprite")
buffer := engine.NewSpriteSyncBuffer(1)
collect := func(want int) {
t.Helper()
buffer.Clear()
sprite.prepareProxyUpdate()
update := sprite.collectProxyUpdate(buffer)
if got := buffer.UpdateCount(); got != want {
t.Fatalf("collected %d transforms, want %d", got, want)
}
engine.SyncBatchUpdateSprites(buffer.Serialize())
commitProxyChange(update)
}
collect(0)
sprite.initRuntimeProxy()
collect(1)
collect(0)
oldProxy := sprite.runtimeState.proxy
if oldProxy.CallbackAlive == nil || !oldProxy.CallbackAlive() {
t.Fatal("initialized proxy rejected callbacks for its live sprite")
}
sprite.initRuntimeProxy()
if sprite.runtimeState.proxy == oldProxy {
t.Fatal("rebuild reused the old proxy")
}
collect(1)
collect(0)
sprite.Show()
sprite.destroy()
if oldProxy.CallbackAlive() || sprite.runtimeState.proxy.CallbackAlive() {
t.Fatal("proxy accepted callbacks after logical sprite destruction")
}
operations := len(mgr.recordedOperations())
sprite.syncProxyForQuery()
collect(0)
if got := len(mgr.recordedOperations()); got != operations {
t.Fatalf("destroyed sprite made %d proxy calls", got-operations)
}
}
func TestNonFiniteHeadingDoesNotExitFrame(t *testing.T) {
for _, value := range []float64{math.NaN(), math.Inf(1), math.Inf(-1)} {
t.Run(fmt.Sprint(value), func(t *testing.T) {
currentScheduler, game, _ := setupFrameSyncGame(t)
sprite := addFrameSyncSprite(game, 1, "heading")
sprite.SetHeading(45)
previous := pkgengine.ExtMgr
ext := &inputFrameFailureExtMgr{}
pkgengine.ExtMgr = ext
t.Cleanup(func() { pkgengine.ExtMgr = previous })
sprite.SetHeading(value)
func() {
defer engine.CheckPanic()
runFrameSyncGame(currentScheduler, game)
}()
if sprite.Heading() != 45 || len(ext.exits) != 0 || len(ext.messages) != 0 {
t.Fatalf("invalid heading changed frame: heading=%v exits=%v errors=%v", sprite.Heading(), ext.exits, ext.messages)
}
})
}
}
func TestProxyQueryAndBatchRejectInvalidTransformsWithoutAcknowledging(t *testing.T) {
for _, mode := range []string{"query", "batch"} {
for _, field := range []string{"x", "rotation"} {
t.Run(mode+"/"+field, func(t *testing.T) {
sprite, mgr := setupPositionSyncSprite(t)
sprite.SetXpos(42)
if field == "x" {
sprite.SetXpos(math.MaxFloat64)
} else {
// Bypass the public setter to exercise the internal-state guard.
sprite.transform().direction = math.NaN()
}
pending := sprite.transform().pendingPosition
requireSyncPanic(t, func() {
if mode == "query" {
sprite.syncProxyForQuery()
} else {
sprite.g.flushSpriteProxyChanges(sprite.g.scene.items)
}
}, "sprite 1", field+"=")
if mgr.submissions != 0 || sprite.transform().pendingPosition != pending ||
sprite.spriteState.proxySyncVersion == sprite.spriteState.dirtyVersion {
t.Fatal("invalid transform was submitted or acknowledged")
}
sprite.SetHeading(45)
sprite.SetXpos(80)
sprite.g.flushSpriteProxyChanges(sprite.g.scene.items)
if mgr.submissions != 1 || sprite.spriteState.proxySyncVersion != sprite.spriteState.dirtyVersion {
t.Fatal("corrected transform did not commit")
}
})
}
}
}
func setupSyncBufferCapture(t *testing.T) (*Game, *captureFlushSpriteMgr) {
t.Helper()
mgr := setupCaptureFlushSpriteMgr(t)
return &Game{syncBuffer: engine.NewSpriteSyncBuffer(1)}, mgr
}
// Physics position pulls and explicit axis writes.
func TestPullPhysicsPositionsFiltersAndKeepsIDOrder(t *testing.T) {
mgr := setupPullPositionSpriteMgr(t)
mgr.positions = []float32{11, 12, 31, 32}
first := newPullPhysicsSprite(1, KinematicPhysics, 1, 2)
noPhysics := newPullPhysicsSprite(2, NoPhysics, 2, 3)
missing := newPullPhysicsSprite(4, DynamicPhysics, 4, 5)
missing.runtimeState.proxy = nil
last := newPullPhysicsSprite(3, DynamicPhysics, 3, 4)
game := &Game{syncBuffer: engine.NewSpriteSyncBuffer(4)}
game.scene.items = []Shape{first, noPhysics, struct{}{}, missing, last}
game.pullPhysicsPositions()
if mgr.calls != 1 || !slices.Equal(mgr.ids, []int64{1, 3}) {
t.Fatalf("position query calls=%d ids=%v, want one query for [1 3]", mgr.calls, mgr.ids)
}
for _, tt := range []struct {
sprite *SpriteImpl
x, y float64
version uint64
}{
{first, 11, 12, 1},
{noPhysics, 2, 3, 0},
{missing, 4, 5, 0},
{last, 31, 32, 1},
} {
x, y := tt.sprite.transform().getXY()
if x != tt.x || y != tt.y || tt.sprite.spriteState.visualVersion != tt.version {
t.Errorf("sprite position=(%v,%v) visual version=%d, want (%v,%v) version %d", x, y, tt.sprite.spriteState.visualVersion, tt.x, tt.y, tt.version)
}
if tt.sprite.spriteState.dirtyVersion != 0 {
t.Errorf("physics pull dirtied proxy: %+v", tt.sprite.spriteState)
}
}
game.pullPhysicsPositions()
if first.spriteState.visualVersion != 1 || last.spriteState.visualVersion != 1 {
t.Fatal("unchanged position incremented visual version")
}
mgr.positions = []float32{13, 14, float32(math.NaN()), 40}
game.pullPhysicsPositions()
if x, y := last.transform().getXY(); x != 31 || y != 32 || last.spriteState.visualVersion != 1 {
t.Fatalf("missing sentinel changed last sprite to (%v,%v), version %d", x, y, last.spriteState.visualVersion)
}
if x, y := first.transform().getXY(); x != 13 || y != 14 || first.spriteState.visualVersion != 2 {
t.Fatalf("valid result not applied to first sprite: (%v,%v), version %d", x, y, first.spriteState.visualVersion)
}
game.scene.items = []Shape{noPhysics, struct{}{}, missing}
game.pullPhysicsPositions()
if mgr.calls != 3 {
t.Fatalf("empty physics pull made an engine query: %d total calls, want 3", mgr.calls)
}
}
func TestPullPhysicsPositionsReentrant(t *testing.T) {
setupPullPositionSpriteMgr(t)
game := &Game{syncBuffer: engine.NewSpriteSyncBuffer(2)}
first := newPullPhysicsSprite(1, DynamicPhysics, 0, 0)
second := newPullPhysicsSprite(2, DynamicPhysics, 0, 0)
nested := newPullPhysicsSprite(3, DynamicPhysics, 0, 0)
game.scene.items = []Shape{first, second}
mgr := &reentrantPullPositionMgr{game: game, nested: nested}
pkgengine.SpriteMgr = mgr
game.pullPhysicsPositions()
if mgr.calls != 2 {
t.Fatalf("position queries = %d, want 2", mgr.calls)
}
for _, tt := range []struct {
sprite *SpriteImpl
x, y float64
}{{first, 10, 11}, {second, 20, 21}, {nested, 30, 31}} {
if x, y := tt.sprite.transform().getXY(); x != tt.x || y != tt.y {
t.Errorf("position = (%v, %v), want (%v, %v)", x, y, tt.x, tt.y)
}
}
if game.physicsPull.busy.Load() || len(game.physicsPull.sprites) != 0 || game.physicsPull.sprites[:cap(game.physicsPull.sprites)][0] != nil {
t.Fatal("position pull retained a sprite")
}
}
func TestPullPhysicsPositionsConcurrent(t *testing.T) {
setupPullPositionSpriteMgr(t)
game := &Game{syncBuffer: engine.NewSpriteSyncBuffer(1)}
sprite := newPullPhysicsSprite(1, DynamicPhysics, 0, 0)
game.scene.items = []Shape{sprite}
mgr := &concurrentPullPositionMgr{started: make(chan struct{}), release: make(chan struct{})}
pkgengine.SpriteMgr = mgr
done := make(chan struct{})
go func() {
defer close(done)
game.pullPhysicsPositions()
}()
<-mgr.started
game.pullPhysicsPositions()
close(mgr.release)
<-done
if mgr.calls.Load() != 2 {
t.Fatalf("position queries = %d, want 2", mgr.calls.Load())
}
if x, y := sprite.transform().getXY(); x != 10 || y != 11 {
t.Fatalf("position = (%v, %v), want (10, 11)", x, y)
}
}
func BenchmarkPullPhysicsPositions(b *testing.B) {
setupImmediateEngineCalls(b)
previous := pkgengine.SpriteMgr
mgr := &pullPositionSpriteMgr{positions: make([]float32, 600)}
pkgengine.SpriteMgr = mgr
b.Cleanup(func() { pkgengine.SpriteMgr = previous })
for _, scenario := range []struct {
name string
active int
}{{"none", 0}, {"one", 1}, {"all", 300}} {
b.Run(scenario.name, func(b *testing.B) {
game := &Game{syncBuffer: engine.NewSpriteSyncBuffer(300)}
for i := range 300 {
mode := NoPhysics
if i < scenario.active {
mode = DynamicPhysics
}
game.scene.items = append(game.scene.items, newPullPhysicsSprite(int64(i+1), mode, 0, 0))
}
game.pullPhysicsPositions()
b.ReportAllocs()
b.ResetTimer()
for range b.N {
game.pullPhysicsPositions()
}
})
}
}
func TestApplyPhysicsPositionsStopsAtShortResponse(t *testing.T) {
sprites := []*SpriteImpl{
newPhysicsPositionTestSprite(1, 2),
newPhysicsPositionTestSprite(3, 4),
}
applyPhysicsPositions(sprites, []float32{11, 12, 31})
if x, y := sprites[0].transform().getXY(); x != 11 || y != 12 {
t.Fatalf("first sprite position=(%v,%v), want (11,12)", x, y)
}
if x, y := sprites[1].transform().getXY(); x != 3 || y != 4 {
t.Fatalf("short response changed second sprite to (%v,%v)", x, y)
}
}
func TestMergeEnginePositionInvalidatesVisualsOnlyWhenChanged(t *testing.T) {
sprite := newPhysicsPositionTestSprite(1, 2)
sprite.mergeEnginePosition(1, 2)
if sprite.spriteState.visualVersion != 0 {
t.Fatalf("unchanged position visual version = %d, want 0", sprite.spriteState.visualVersion)
}
sprite.mergeEnginePosition(3, 4)
if sprite.spriteState.visualVersion != 1 {
t.Fatalf("changed position visual version = %d, want 1", sprite.spriteState.visualVersion)
}
if sprite.spriteState.dirtyVersion != 0 {
t.Fatalf("physics writeback dirtied proxy state: DirtyVersion=%d", sprite.spriteState.dirtyVersion)
}
if x, y := sprite.transform().getXY(); x != 3 || y != 4 {
t.Fatalf("physics position = (%v, %v), want (3, 4)", x, y)
}
sprite.mergeEnginePosition(3, 4)
if sprite.spriteState.visualVersion != 1 {
t.Fatalf("repeated position visual version = %d, want 1", sprite.spriteState.visualVersion)
}
}
func TestProxyCallbacksIgnoreMissingAndDestroyedSprites(t *testing.T) {
destroyed := &SpriteImpl{}
destroyed.markDestroyed()
for _, sprite := range []*SpriteImpl{{}, destroyed} {
sprite.handleAnimationFinished()
sprite.handleAnimationLooped()
if sprite.runtimeState.proxy != nil {
t.Fatal("stale callback created a proxy")
}
}
sprite := &SpriteImpl{}
sprite.runtimeState.proxy = &engine.Sprite{}
sprite.ensureProxyInitialized()
for _, state := range []string{"missing", "replaced", "destroyed"} {
t.Run(state, func(t *testing.T) {
sprite := newPhysicsPositionTestSprite(10, 20)
proxy := &engine.Sprite{}
sprite.runtimeState.proxy = proxy
switch state {
case "missing":
sprite.runtimeState.proxy = nil
case "replaced":
sprite.runtimeState.proxy = &engine.Sprite{}
case "destroyed":
sprite.markDestroyed()
}
pending := positionVersions{x: 1, y: 2}
sprite.transform().pendingPosition = pending
sprite.mirrorPosition(proxy, mathf.NewVec2(30, 40), engine.PositionXY)
requirePosition(t, sprite, 10, 20)
if sprite.transform().pendingPosition != pending {
t.Fatal("stale position callback acknowledged pending writes")
}
})
}
}
func TestPhysicsPullPreservesExplicitPositionAxes(t *testing.T) {
for _, tt := range []struct {
name string
write func(*SpriteImpl)
x, y float64
}{
{"set x", func(s *SpriteImpl) { s.SetXpos(42) }, 42, 200},
{"set same x", func(s *SpriteImpl) { s.SetXpos(10) }, 10, 200},
{"set y", func(s *SpriteImpl) { s.SetYpos(42) }, 100, 42},
{"set same y", func(s *SpriteImpl) { s.SetYpos(20) }, 100, 20},
{"change x", func(s *SpriteImpl) { s.ChangeXpos(3) }, 13, 200},
{"change y", func(s *SpriteImpl) { s.ChangeYpos(3) }, 100, 23},
{"set xy", func(s *SpriteImpl) { s.SetXYpos(42, 43) }, 42, 43},
{"set same xy", func(s *SpriteImpl) { s.SetXYpos(10, 20) }, 10, 20},
{"change xy", func(s *SpriteImpl) { s.ChangeXYpos(3, 4) }, 13, 24},
{"move", func(s *SpriteImpl) { s.transform().direction = 0; s.Move__0(5) }, 10, 25},
{"hide", func(s *SpriteImpl) { s.Hide() }, 100, 200},
} {
t.Run(tt.name, func(t *testing.T) {
sprite, _ := setupPositionSyncSprite(t)
tt.write(sprite)
sprite.mergeEnginePosition(100, 200)
requirePosition(t, sprite, tt.x, tt.y)
})
}
}
func TestDirectProxyAxisWritesPreserveOtherPendingAxis(t *testing.T) {
for _, tt := range []struct {
name string
write func(*engine.Sprite)
axis engine.PositionAxes
want mathf.Vec2
}{
{"set x", func(p *engine.Sprite) { p.SetPosX(42) }, engine.PositionX, mathf.NewVec2(42, 99)},
{"add x", func(p *engine.Sprite) { p.AddPosX(3) }, engine.PositionX, mathf.NewVec2(13, 99)},
{"set same x", func(p *engine.Sprite) { p.SetPosX(10) }, engine.PositionX, mathf.NewVec2(10, 99)},
{"add zero x", func(p *engine.Sprite) { p.AddPosX(0) }, engine.PositionX, mathf.NewVec2(10, 99)},
{"set y", func(p *engine.Sprite) { p.SetPosY(42) }, engine.PositionY, mathf.NewVec2(99, 42)},
{"add y", func(p *engine.Sprite) { p.AddPosY(3) }, engine.PositionY, mathf.NewVec2(99, 23)},
{"set same y", func(p *engine.Sprite) { p.SetPosY(20) }, engine.PositionY, mathf.NewVec2(99, 20)},
{"add zero y", func(p *engine.Sprite) { p.AddPosY(0) }, engine.PositionY, mathf.NewVec2(99, 20)},
} {
t.Run(tt.name, func(t *testing.T) {
sprite, mgr := setupPositionSyncSprite(t)
if tt.axis == engine.PositionX {
sprite.SetYpos(99)
} else {
sprite.SetXpos(99)
}
tt.write(sprite.runtimeState.proxy)
requirePosition(t, sprite, tt.want.X, tt.want.Y)
sprite.g.flushSpriteProxyChanges(sprite.g.scene.items)
if mgr.position != tt.want {
t.Fatalf("submitted position = %v, want %v", mgr.position, tt.want)
}
sprite.mergeEnginePosition(200, 300)
requirePosition(t, sprite, 200, 300)
})
}
}
type pullPositionSpriteMgr struct {
wrap.SpriteMgrImpl
calls int
ids []int64
positions []float32
}
func (m *pullPositionSpriteMgr) BatchRetrievePositions(ids []int64, out []float32) bool {
m.calls++
m.ids = append(m.ids[:0], ids...)
copy(out, m.positions)
return true
}
type reentrantPullPositionMgr struct {
wrap.SpriteMgrImpl
game *Game
nested *SpriteImpl
calls int
}
func (m *reentrantPullPositionMgr) BatchRetrievePositions(ids []int64, out []float32) bool {
m.calls++
if m.calls == 1 {
items := m.game.scene.items
m.game.scene.items = []Shape{m.nested}
m.game.pullPhysicsPositions()
m.game.scene.items = items
}
for i, id := range ids {
out[i*2], out[i*2+1] = float32(id*10), float32(id*10+1)
}
return true
}
type concurrentPullPositionMgr struct {
wrap.SpriteMgrImpl
started chan struct{}
release chan struct{}
calls atomic.Int32
}
func (m *concurrentPullPositionMgr) BatchRetrievePositions(ids []int64, out []float32) bool {
if m.calls.Add(1) == 1 {
close(m.started)
<-m.release
}
out[0], out[1] = float32(ids[0]*10), float32(ids[0]*10+1)
return true
}
func setupPullPositionSpriteMgr(t *testing.T) *pullPositionSpriteMgr {
t.Helper()
setupImmediateEngineCalls(t)
original := pkgengine.SpriteMgr
mgr := &pullPositionSpriteMgr{}
pkgengine.SpriteMgr = mgr
t.Cleanup(func() { pkgengine.SpriteMgr = original })
return mgr
}
func newPullPhysicsSprite(id int64, mode PhysicsMode, x, y float64) *SpriteImpl {
sprite := newPhysicsPositionTestSprite(x, y)
sprite.runtimeState.proxy = &engine.Sprite{}
sprite.runtimeState.proxy.Id = id
sprite.components.physics = &physicsComponent{sprite: sprite, physicsMode: mode}
return sprite
}
func newPhysicsPositionTestSprite(x, y float64) *SpriteImpl {
sprite := &SpriteImpl{}
sprite.components.transform = &transformComponent{
sprite: sprite,
x: x,
y: y,
}
return sprite
}
// Touch dispatch ordering, filtering, and retry.
func TestDispatchTouchEventsFiltersPairs(t *testing.T) {
game := newTouchDispatchGame(t)
source := newTouchDispatchSprite(game, "source")
target := newTouchDispatchSprite(game, "target")
hidden := newTouchDispatchSprite(game, "hidden")
hidden.spriteState.isVisible = false
dying := newTouchDispatchSprite(game, "dying")
dying.spriteState.isDying = true
noHandler := newTouchDispatchSprite(game, "no-handler")
var nilSprite *SpriteImpl
typedNil := &engine.Sprite{Target: nilSprite}
wrongType := &engine.Sprite{Target: "not a sprite"}
emptyTarget := &engine.Sprite{}
src, dst := source.runtimeState.proxy, target.runtimeState.proxy
var calls []Sprite
for _, sprite := range []*touchEventSprite{source, target, hidden, dying} {
sprite.addTouchStartHandler(func(other Sprite) { calls = append(calls, other) })
}
for _, tt := range []struct {
name string
src, dst *engine.Sprite
touch bool
}{
{"valid", src, dst, true},
{"nil source", nil, dst, false},
{"nil destination", src, nil, false},
{"both proxies nil", nil, nil, false},
{"wrong source type", wrongType, dst, false},
{"wrong destination type", src, wrongType, false},
{"both types wrong", wrongType, wrongType, false},
{"nil source target", emptyTarget, dst, false},
{"nil destination target", src, emptyTarget, false},
{"typed nil source and invalid destination", typedNil, wrongType, false},
{"invalid source and typed nil destination", wrongType, typedNil, false},
{"hidden source and invalid destination", hidden.runtimeState.proxy, wrongType, false},
{"hidden source", hidden.runtimeState.proxy, dst, false},
{"hidden destination", src, hidden.runtimeState.proxy, false},
{"dying source", dying.runtimeState.proxy, dst, false},
{"dying destination", src, dying.runtimeState.proxy, false},
{"hidden source short circuits typed nil destination", hidden.runtimeState.proxy, typedNil, false},
{"dying source short circuits typed nil destination", dying.runtimeState.proxy, typedNil, false},
{"no source handler", noHandler.runtimeState.proxy, dst, false},
} {
t.Run(tt.name, func(t *testing.T) {
calls = nil
game.triggerEvents = []engine.TriggerEvent{{Src: tt.src, Dst: tt.dst}, {Src: src, Dst: dst}}
game.dispatchTouchEvents()
want := []Sprite{target} // Processing must continue after a skipped pair.
if tt.touch {
want = append(want, target)
}
if !slices.Equal(calls, want) {
t.Fatalf("touches = %v, want %v", calls, want)
}
if len(game.triggerEvents) != 0 || game.triggerEvents[:1][0] != (engine.TriggerEvent{}) {
t.Fatal("normal dispatch retained a trigger pair")
}
})
}
}
func TestDispatchTouchEventsIgnoresDraggedTargetOnly(t *testing.T) {
game := newTouchDispatchGame(t)
source := newTouchDispatchSprite(game, "source")
target := newTouchDispatchSprite(game, "target")
game.inputMgr.drag.target = &target.SpriteImpl
game.inputMgr.drag.active = true
var calls []string
for _, sprite := range []*touchEventSprite{source, target} {
sprite.addTouchStartHandler(func(other Sprite) {
calls = append(calls, sprite.name+":"+spriteOf(other).name)
})
}
game.triggerEvents = []engine.TriggerEvent{
{Src: source.runtimeState.proxy, Dst: target.runtimeState.proxy},
{Src: target.runtimeState.proxy, Dst: source.runtimeState.proxy},
}
game.dispatchTouchEvents()
if want := []string{"target:source"}; !slices.Equal(calls, want) {
t.Fatalf("touches = %v, want %v", calls, want)
}
}
func TestDispatchTouchEventsRequiresShapeGeometry(t *testing.T) {
for _, byShape := range []bool{false, true} {
for _, missing := range []string{"neither", "source", "target"} {
t.Run(fmt.Sprintf("byShape=%v/%s", byShape, missing), func(t *testing.T) {
game := newTouchDispatchGame(t)
game.touchByShape = byShape
source := newTouchDispatchSprite(game, "source")
target := newTouchDispatchSprite(game, "target")
for _, sprite := range []*touchEventSprite{source, target} {
sprite.components.physics = &physicsComponent{
sprite: &sprite.SpriteImpl, triggerCollider: colliderConfig{Type: collision.ColliderRect},
}
}
calls := 0
source.addTouchStartHandler(func(Sprite) { calls++ })
game.triggerEvents = []engine.TriggerEvent{{Src: source.runtimeState.proxy, Dst: target.runtimeState.proxy}}
// Geometry may disappear after the native event was queued.
if missing == "source" {
source.physics().triggerCollider.Type = collision.ColliderNone
} else if missing == "target" {
target.physics().triggerCollider.Type = collision.ColliderNone
}
game.dispatchTouchEvents()
want := 1
if byShape && missing != "neither" {
want = 0
}
if calls != want || len(game.triggerEvents) != 0 {
t.Fatalf("callbacks = %d, want %d; queued events = %d", calls, want, len(game.triggerEvents))
}
})
}
}
}
func TestDispatchTouchEventsOrderAndBufferReuse(t *testing.T) {
game := newTouchDispatchGame(t)
first := newTouchDispatchSprite(game, "first")
second := newTouchDispatchSprite(game, "second")
last := newTouchDispatchSprite(game, "last")
var calls []string
for _, sprite := range []*touchEventSprite{first, second, last} {
sprite.addTouchStartHandler(func(other Sprite) {
calls = append(calls, sprite.name+":"+spriteOf(other).name)
})
}
firstPair := engine.TriggerEvent{Src: first.runtimeState.proxy, Dst: second.runtimeState.proxy}
backing := make([]engine.TriggerEvent, 4)
backing[0] = firstPair
backing[1] = engine.TriggerEvent{Src: second.runtimeState.proxy, Dst: last.runtimeState.proxy}
backing[2] = engine.TriggerEvent{Src: first.runtimeState.proxy, Dst: last.runtimeState.proxy}
backing[3] = firstPair // Capacity beyond the active batch is not cleared.
game.triggerEvents = backing[:3]
game.dispatchTouchEvents()
if want := []string{"first:second", "second:last", "first:last"}; !slices.Equal(calls, want) {
t.Fatalf("touch order = %v, want %v", calls, want)
}
if len(game.triggerEvents) != 0 || cap(game.triggerEvents) != len(backing) || &game.triggerEvents[:1][0] != &backing[0] {
t.Fatal("dispatch did not retain the empty reusable buffer")
}
for _, pair := range backing[:3] {
if pair != (engine.TriggerEvent{}) {
t.Fatal("dispatch retained a processed pair")
}
}
if backing[3] != firstPair {
t.Fatal("dispatch cleared beyond the active batch")
}
game.triggerEvents = append(game.triggerEvents, firstPair)
game.dispatchTouchEvents()
if len(calls) != 4 || calls[3] != "first:second" || backing[0] != (engine.TriggerEvent{}) {
t.Fatal("reused buffer did not dispatch and clear its next batch")
}
game.dispatchTouchEvents()
if len(calls) != 4 {
t.Fatal("empty dispatch repeated a touch")
}
}
func TestDispatchTouchEventsRechecksTouchability(t *testing.T) {
for _, dying := range []bool{false, true} {
t.Run(fmt.Sprintf("dying=%v", dying), func(t *testing.T) {
game := newTouchDispatchGame(t)
source := newTouchDispatchSprite(game, "source")
target := newTouchDispatchSprite(game, "target")
last := newTouchDispatchSprite(game, "last")
var calls []Sprite
source.addTouchStartHandler(func(other Sprite) {
calls = append(calls, other)
if dying {
target.spriteState.isDying = true
} else {
target.spriteState.isVisible = false
}
})
target.addTouchStartHandler(func(Sprite) { t.Error("untouchable source fired a callback") })
src, dst := source.runtimeState.proxy, target.runtimeState.proxy
game.triggerEvents = []engine.TriggerEvent{
{Src: src, Dst: dst},
{Src: dst, Dst: src},
{Src: src, Dst: dst},
{Src: src, Dst: last.runtimeState.proxy},
}
game.dispatchTouchEvents()
if want := []Sprite{target, last}; !slices.Equal(calls, want) {
t.Fatalf("touches = %v, want target then last", calls)
}
})
}
}
func TestDispatchTouchEventsPanicRetainsBatch(t *testing.T) {
for _, name := range []string{"callback", "typed nil source", "typed nil destination", "typed nil source before hidden destination"} {
t.Run(name, func(t *testing.T) {
game := newTouchDispatchGame(t)
source := newTouchDispatchSprite(game, "source")
target := newTouchDispatchSprite(game, "target")
panicking := newTouchDispatchSprite(game, "panicking")
hidden := newTouchDispatchSprite(game, "hidden")
hidden.spriteState.isVisible = false
var nilSprite *SpriteImpl
typedNil := &engine.Sprite{Target: nilSprite}
calls := 0
source.addTouchStartHandler(func(Sprite) { calls++ })
panicValue := new(int)
panicking.addTouchStartHandler(func(Sprite) { panic(panicValue) })
src, dst := source.runtimeState.proxy, target.runtimeState.proxy
pair := engine.TriggerEvent{Src: panicking.runtimeState.proxy, Dst: dst}
switch name {
case "typed nil source":
pair.Src = typedNil
case "typed nil destination":
pair.Src, pair.Dst = src, typedNil
case "typed nil source before hidden destination":
pair.Src, pair.Dst = typedNil, hidden.runtimeState.proxy
}
game.triggerEvents = []engine.TriggerEvent{{Src: src, Dst: dst}, pair, {Src: src, Dst: dst}}
before := slices.Clone(game.triggerEvents)
backing := &game.triggerEvents[0]
defer func() {
value := recover()
if value == nil || name == "callback" && value != panicValue {
t.Fatalf("panic = %v, want the original panic", value)
}
if calls != 1 {
t.Fatalf("completed touches = %d, want only the first pair", calls)
}
if !slices.Equal(game.triggerEvents, before) || &game.triggerEvents[0] != backing {
t.Fatal("panic cleared or replaced the uncompleted batch")
}
}()
game.dispatchTouchEvents()
})
}
}
func newTouchDispatchGame(t *testing.T) *Game {
t.Helper()
previous := scheduler
scheduler = nil
t.Cleanup(func() { scheduler = previous })
game := new(Game)
game.bindScriptEvents()
return game
}
func newTouchDispatchSprite(game *Game, name string) *touchEventSprite {
sprite := newTouchEventSprite(game, name)
sprite.spriteState.isVisible = true
sprite.runtimeState.proxy = &engine.Sprite{Target: &sprite.SpriteImpl, MirrorPosition: sprite.mirrorPosition}
return sprite
}
// Proxy commit, reentrant writes, and deletion retry.
func TestPositionSyncRequiresSuccessfulSubmission(t *testing.T) {
for _, mode := range []string{"query", "batch", "serialization"} {
t.Run(mode, func(t *testing.T) {
sprite, mgr := setupPositionSyncSprite(t)
sync := sprite.syncProxyForQuery
if mode != "query" {
sync = func() { sprite.g.flushSpriteProxyChanges(sprite.g.scene.items) }
}
sprite.SetXpos(42)
mgr.position = mathf.NewVec2(100, 200)
sprite.mergeEnginePosition(100, 200)
wantPanic := "position sync failed"
if mode == "serialization" {
sprite.runtimeState.proxy.Id = 1<<24 + 1
wantPanic = "invalid sprite ID"
} else {
mgr.fail = true
}
requireSyncPanic(t, sync, wantPanic)
if sprite.spriteState.proxySyncVersion == sprite.spriteState.dirtyVersion {
t.Fatal("failed sync consumed dirty state")
}
mgr.position = mathf.NewVec2(300, 400)
sprite.mergeEnginePosition(300, 400)
requirePosition(t, sprite, 42, 400)
mgr.fail = false
sprite.runtimeState.proxy.Id = 1
sync()
if mgr.submissions != 1 || mgr.position != mathf.NewVec2(42, 400) {
t.Fatalf("submitted %d positions, latest %v", mgr.submissions, mgr.position)
}
if sprite.spriteState.proxySyncVersion != sprite.spriteState.dirtyVersion {
t.Fatal("successful sync left dirty state")
}
sprite.mergeEnginePosition(500, 600)
requirePosition(t, sprite, 500, 600)
})
}
}
func TestPositionSyncPreservesLaterWrites(t *testing.T) {
for _, mode := range []string{"query", "batch"} {
for _, test := range []struct {
name string
write func(*SpriteImpl)
x, y float64
}{
{"hide", (*SpriteImpl).Hide, 100, 200},
{"set same x", func(s *SpriteImpl) { s.SetXpos(42) }, 42, 200},
{"set x", func(s *SpriteImpl) { s.SetXpos(84) }, 84, 200},
{"set y", func(s *SpriteImpl) { s.SetYpos(43) }, 100, 43},
} {
t.Run(mode+"/"+test.name, func(t *testing.T) {
sprite, mgr := setupPositionSyncSprite(t)
sync := sprite.syncProxyForQuery
if mode == "batch" {
sync = func() { sprite.g.flushSpriteProxyChanges(sprite.g.scene.items) }
}
sprite.SetXpos(42)
mgr.onSubmit = func() { test.write(sprite) }
sync()
mgr.position = mathf.NewVec2(100, 200)
sprite.mergeEnginePosition(100, 200)
requirePosition(t, sprite, test.x, test.y)
if sprite.spriteState.proxySyncVersion == sprite.spriteState.dirtyVersion {
t.Fatal("older submission acknowledged a newer write")
}
mgr.onSubmit = nil
sync()
if mgr.position != mathf.NewVec2(test.x, test.y) {
t.Fatalf("next submission = %v, want (%v, %v)", mgr.position, test.x, test.y)
}
sprite.mergeEnginePosition(300, 400)
requirePosition(t, sprite, 300, 400)
})
}
}
}
func TestProxyCollectionIncludesCallbackWrites(t *testing.T) {
for _, test := range []struct {
name string
write func(*SpriteImpl)
x float64
}{
{"hide", (*SpriteImpl).Hide, 42},
{"nested query", func(s *SpriteImpl) {
s.SetXpos(84)
s.syncProxyForQuery()
}, 84},
{"direct position", func(s *SpriteImpl) {
s.runtimeState.proxy.SetPosition(mathf.NewVec2(84, 20))
}, 84},
} {
t.Run(test.name, func(t *testing.T) {
sprite, mgr := setupPositionSyncSprite(t)
textures := &textureFramesSpriteMgr{positionSyncSpriteMgr: mgr}
pkgengine.SpriteMgr = textures
sprite.SetXpos(42)
game := sprite.g
later := &newCloneAwakeOrderSprite(game, "costume").SpriteImpl
later.currentCostume().path = "sprites/costume.png"
later.runtimeState.isCostumeDirty = true
later.runtimeState.isLayerDirty = false
later.runtimeState.proxy = &engine.Sprite{Target: later, MirrorPosition: later.mirrorPosition}
const id = pkgengine.Object(9001)
pkgengine.InitSpriteInstance(id, later.runtimeState.proxy, nil)
registry := pkgengine.Sprites()
previous, existed := registry[id]
t.Cleanup(func() {
if existed {
registry[id] = previous
} else {
delete(registry, id)
}
})
registry[id] = &framesChangedSprite{
ISpriter: later.runtimeState.proxy,
changed: func() { test.write(sprite) },
}
game.scene.add(later)
game.flushSpriteProxyChanges(game.scene.items)
if textures.callbacks != 1 || mgr.position != mathf.NewVec2(test.x, 20) {
t.Fatalf("texture callbacks=%d, submitted position=%v, want (%v, 20)", textures.callbacks, mgr.position, test.x)
}
requirePosition(t, sprite, test.x, 20)
if sprite.spriteState.proxySyncVersion != sprite.spriteState.dirtyVersion {
t.Fatal("callback changes were not included in the final submission")
}
mgr.position = mathf.NewVec2(100, 200)
sprite.mergeEnginePosition(100, 200)
requirePosition(t, sprite, 100, 200)
sprite.markProxyDirty()
game.flushSpriteProxyChanges(game.scene.items)
if mgr.position != mathf.NewVec2(100, 200) {
t.Fatalf("next update reset physics position to %v, want (100, 200)", mgr.position)
}
})
}
}
func TestProxyCommitRetriesPositionAndDeletionAfterFailure(t *testing.T) {
for _, failure := range []string{"serialization", "bridge"} {
t.Run(failure, func(t *testing.T) {
sprite, mgr := setupPositionSyncSprite(t)
game := sprite.g
mgr.fail = failure == "bridge"
sprite.SetXpos(42)
invalid := &newCloneAwakeOrderSprite(game, "invalid").SpriteImpl
invalid.runtimeState.isCostumeDirty = false
invalid.runtimeState.proxy = &engine.Sprite{Target: invalid, MirrorPosition: invalid.mirrorPosition}
invalid.runtimeState.proxy.Id = 2
if failure == "serialization" {
// A finite Go coordinate can overflow the float32 batch protocol.
invalid.SetXpos(math.MaxFloat64)
} else {
invalid.SetXpos(80)
}
game.scene.add(invalid)
destroyed := &SpriteImpl{}
proxy := &engine.Sprite{}
proxy.Id = 3
destroyed.runtimeState.proxy = proxy
game.scene.add(destroyed)
game.scene.removeShape(destroyed)
game.scene.removeShape(destroyed)
wantPanic := []string{"position sync failed"}
if failure == "serialization" {
wantPanic = []string{"sprite 2 transform x=", "finite after float32 conversion"}