summaryrefslogtreecommitdiff
path: root/catbird/node-2d.scm
blob: 6e9c197ffa6e8b3e0884b7add88b1d5a50ea309b (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
;;; Catbird Game Engine
;;; Copyright © 2022 David Thompson <davet@gnu.org>
;;;
;;; 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.

;;; Commentary:
;;
;; 2D game nodes.
;;
;;; Code:
(define-module (catbird node-2d)
  #:use-module (catbird asset)
  #:use-module (catbird camera)
  #:use-module (catbird cached-slots)
  #:use-module (catbird mixins)
  #:use-module (catbird node)
  #:use-module (catbird observer)
  #:use-module (chickadee)
  #:use-module (chickadee math)
  #:use-module (chickadee math bezier)
  #:use-module (chickadee math easings)
  #:use-module (chickadee math matrix)
  #:use-module (chickadee math rect)
  #:use-module (chickadee math vector)
  #:use-module (chickadee graphics 9-patch)
  #:use-module (chickadee graphics blend)
  #:use-module (chickadee graphics color)
  #:use-module (chickadee graphics engine)
  #:use-module (chickadee graphics framebuffer)
  #:use-module (chickadee graphics particles)
  #:use-module ((chickadee graphics path) #:prefix path:)
  #:use-module (chickadee graphics sprite)
  #:use-module (chickadee graphics text)
  #:use-module (chickadee graphics texture)
  #:use-module (chickadee graphics tile-map)
  #:use-module (chickadee graphics viewport)
  #:use-module (chickadee scripting)
  #:use-module (ice-9 match)
  #:use-module (oop goops)
  #:use-module (rnrs base)
  #:export (<node-2d>
            aggregate-bounding-box
            align-bottom
            align-left
            align-right
            align-top
            center
            center-in-parent
            center-horizontal
            center-horizontal-in-parent
            center-vertical
            center-vertical-in-parent
            default-height
            default-width
            expire-local-matrix
            fit-to-children
            follow-bezier-path
            local-bounding-box
            local-height
            local-matrix
            local-origin-x
            local-origin-y
            local-width
            local-x
            local-y
            move-by
            move-to
            on-child-resize
            origin
            origin-x
            origin-y
            place-above
            place-at
            place-at-x
            place-at-y
            place-below
            place-left
            place-right
            position-x
            position-y
            rotate-by
            rotate-to
            rotation
            scale
            scale-by
            scale-to
            scale-x
            scale-y
            shear
            shear-x
            shear-y
            teleport
            world-bounding-box
            world-matrix
            world->local

            <sprite>
            texture
            source-rect
            blend-mode
            tint

            <atlas-sprite>
            atlas
            index

            <animation>
            frames
            frame-duration

            <animated-sprite>
            animations
            frame-duration
            current-animation
            start-time
            change-animation

            <9-patch>
            top-margin
            bottom-margin
            left-margin
            right-margin

            <sprite-batch>
            batch

            <canvas>
            painter

            <label>
            font
            text
            color
            align
            vertical-align

            <tile-map>
            tile-map
            layers

            <particles>
            particles)
  #:re-export (height
               position
               width))

(define (refresh-local-matrix node local)
  (matrix4-2d-transform! local
                         #:origin (origin node)
                         #:position (position node)
                         #:rotation (rotation node)
                         #:scale (scale node)
                         #:shear (shear node))
  local)

(define (refresh-world-matrix node world)
  (let ((p (parent node))
        (local (local-matrix node)))
    ;; If the parent isn't a 2D node, then we consider this to be a
    ;; root node, which means the world matrix is the same as the
    ;; local matrix.
    (if (is-a? p <node-2d>)
        (matrix4-mult! world local (world-matrix p))
        (matrix4-copy! local world))
    world))

(define (refresh-inverse-world-matrix node inverse)
  (matrix4-inverse! (world-matrix node) inverse)
  inverse)

(define (refresh-local-bounding-box node bb)
  (let ((p (position node))
        (o (origin node))
        (r (rotation node))
        (k (shear node))
        (s (size node)))
    (if (and (= r 0.0)
             (= (vec2-x k) 0.0)
             (= (vec2-y k) 0.0))
        ;; Fast path: Node is axis-aligned and bounding box
        ;; calculation is easy peasy.
        (let ((z (scale node)))
          (set-rect-x! bb (- (vec2-x p) (vec2-x o)))
          (set-rect-y! bb (- (vec2-y p) (vec2-y o)))
          (set-rect-width! bb (* (rect-width s) (vec2-x z)))
          (set-rect-height! bb (* (rect-height s) (vec2-y z))))
        ;; Slow path: Node is rotated, sheared, or both.
        (let* ((m (local-matrix node))
               (x0 0.0)
               (y0 0.0)
               (x1 (rect-width s))
               (y1 (rect-height s))
               (x2 (matrix4-transform-x m x0 y0))
               (y2 (matrix4-transform-y m x0 y0))
               (x3 (matrix4-transform-x m x1 y0))
               (y3 (matrix4-transform-y m x1 y0))
               (x4 (matrix4-transform-x m x1 y1))
               (y4 (matrix4-transform-y m x1 y1))
               (x5 (matrix4-transform-x m x0 y1))
               (y5 (matrix4-transform-y m x0 y1))
               (xmin (min x2 x3 x4 x5))
               (ymin (min y2 y3 y4 y5))
               (xmax (max x2 x3 x4 x5))
               (ymax (max y2 y3 y4 y5)))
          (set-rect-x! bb xmin)
          (set-rect-y! bb ymin)
          (set-rect-width! bb (- xmax xmin))
          (set-rect-height! bb (- ymax ymin))))
    bb))

(define (refresh-world-bounding-box node bb)
  (let* ((m (world-matrix node))
         (s (size node))
         (x0 0.0)
         (y0 0.0)
         (x1 (rect-width s))
         (y1 (rect-height s))
         (x2 (matrix4-transform-x m x0 y0))
         (y2 (matrix4-transform-y m x0 y0))
         (x3 (matrix4-transform-x m x1 y0))
         (y3 (matrix4-transform-y m x1 y0))
         (x4 (matrix4-transform-x m x1 y1))
         (y4 (matrix4-transform-y m x1 y1))
         (x5 (matrix4-transform-x m x0 y1))
         (y5 (matrix4-transform-y m x0 y1))
         (xmin (min x2 x3 x4 x5))
         (ymin (min y2 y3 y4 y5))
         (xmax (max x2 x3 x4 x5))
         (ymax (max y2 y3 y4 y5)))
    (set-rect-x! bb xmin)
    (set-rect-y! bb ymin)
    (set-rect-width! bb (- xmax xmin))
    (set-rect-height! bb (- ymax ymin))
    bb))

(define (refresh-aggregate-bounding-box node bb)
  ;; If the node has no children then the aggregate bounding box is
  ;; the same as the world bounding box.
  (rect-copy! (world-bounding-box node) bb)
  (for-each-child (lambda (child)
                    (rect-union! bb (aggregate-bounding-box child)))
                  node)
  bb)

(define-class <node-2d> (<node> <movable-2d> <cacheable>)
  ;; Translation of the origin.  By default, the origin is at the
  ;; bottom left corner of a node.
  (origin #:accessor origin #:init-form (vec2 0.0 0.0) #:init-keyword #:origin
          #:observe? #t)
  (origin-x #:accessor origin-x #:allocation #:virtual
            #:slot-ref (lambda (node) (vec2-x (origin node)))
            #:slot-set! (lambda (node x)
                          (set-vec2-x! (origin node) x)
                          (expire-local-matrix node)))
  (origin-y #:accessor origin-y #:allocation #:virtual
            #:slot-ref (lambda (node) (vec2-y (origin node)))
            #:slot-set! (lambda (node y)
                          (set-vec2-y! (origin node) y)
                          (expire-local-matrix node)))
  ;; Translation
  (position #:accessor position #:init-keyword #:position
            #:init-form (vec2 0.0 0.0) #:observe? #t)
  (position-x #:accessor position-x #:allocation #:virtual
              #:slot-ref (lambda (node) (vec2-x (position node)))
              #:slot-set! (lambda (node x)
                            (set-vec2-x! (position node) x)
                            (expire-local-matrix node)))
  (position-y #:accessor position-y #:allocation #:virtual
              #:slot-ref (lambda (node) (vec2-y (position node)))
              #:slot-set! (lambda (node y)
                            (set-vec2-y! (position node) y)
                            (expire-local-matrix node)))
  ;; Rotation around the Z-axis.
  (rotation #:accessor rotation #:init-form 0.0 #:init-keyword #:rotation
            #:observe? #t)
  ;; Scaling
  (scale #:accessor scale #:init-form (vec2 1.0 1.0) #:init-keyword #:scale
         #:observe? #t)
  (scale-x #:accessor scale-x #:allocation #:virtual
           #:slot-ref (lambda (node) (vec2-x (scale node)))
           #:slot-set! (lambda (node x)
                         (set-vec2-x! (scale node) x)
                         (expire-local-matrix node)))
  (scale-y #:accessor scale-y #:allocation #:virtual
           #:slot-ref (lambda (node) (vec2-y (scale node)))
           #:slot-set! (lambda (node y)
                         (set-vec2-y! (scale node) y)
                         (expire-local-matrix node)))
  ;; Shearing
  (shear #:accessor shear #:init-form (vec2 0.0 0.0) #:init-keyword #:shear
        #:observe? #t)
  (shear-x #:accessor shear-x #:allocation #:virtual
          #:slot-ref (lambda (node) (vec2-x (shear node)))
          #:slot-set! (lambda (node x)
                        (set-vec2-x! (shear node) x)
                        (expire-local-matrix node)))
  (shear-y #:accessor shear-y #:allocation #:virtual
          #:slot-ref (lambda (node) (vec2-y (shear node)))
          #:slot-set! (lambda (node y)
                        (set-vec2-y! (shear node) y)
                        (expire-local-matrix node)))
  ;; Some extra position vectors for defeating "temporal aliasing"
  ;; when rendering.
  (last-position #:getter last-position #:init-form (vec2 0.0 0.0))
  (render-position #:getter render-position #:init-form (vec2 0.0 0.0))
  ;; Transformation matrices:
  ;;
  ;; The local matrix incorporates the node-specific translation,
  ;; rotation, scale, and shear factors.
  (local-matrix #:getter local-matrix #:init-thunk make-identity-matrix4
                #:cached? #t #:refresh refresh-local-matrix)
  ;; The world matrix is defined by the multiplication of the parent's
  ;; world matrix with the local matrix.
  (world-matrix #:getter world-matrix #:init-thunk make-identity-matrix4
                #:cached? #t #:refresh refresh-world-matrix)
  ;; The inverse world matrix is useful for translating world
  ;; coordinates into local coordinates.  Using this matrix it is
  ;; possible to detect if the mouse is over a rotated and sheared
  ;; node, for example.
  (inverse-world-matrix #:getter inverse-world-matrix
                        #:init-form (make-identity-matrix4)
                        #:cached? #t #:refresh refresh-inverse-world-matrix)
  ;; Node dimensions.  Stored as a rectangle for convenience, so it
  ;; can be used as a bounding box that doesn't take any
  ;; transformation matrix into consideration.
  (size #:getter size #:init-thunk make-null-rect)
  (width #:accessor width
         #:observe? #t
         #:allocation #:virtual
         #:slot-ref (lambda (node) (rect-width (size node)))
         #:slot-set! (lambda (node w)
                       (set-rect-width! (size node) w)
                       (expire-local-bounding-box node)))
  (height #:accessor height
          #:observe? #t
          #:allocation #:virtual
          #:slot-ref (lambda (node) (rect-height (size node)))
          #:slot-set! (lambda (node h)
                        (set-rect-height! (size node) h)
                        (expire-local-bounding-box node)))
  ;; The local bounding box is the combination of the node's
  ;; dimensions with the local transformation matrix.
  (local-bounding-box #:getter local-bounding-box #:init-thunk make-null-rect
                      #:cached? #t #:refresh refresh-local-bounding-box)
  ;; The world bounding box is the combination of the node's
  ;; dimensions with the world transformation matrix.
  (world-bounding-box #:getter world-bounding-box #:init-thunk make-null-rect
                      #:cached? #t #:refresh refresh-world-bounding-box)
  ;; The aggregate bounding box is the union of the node's world
  ;; bounding boxes and the aggregate bounding boxes of all its
  ;; children.  This bounding box is used to quickly determine if a
  ;; point in world space might be within any node in a tree.  This
  ;; bounding box can be used for render culling, mouse selection, and
  ;; render clipping.
  (aggregate-bounding-box #:getter aggregate-bounding-box
                          #:init-thunk make-null-rect #:cached? #t
                          #:refresh refresh-aggregate-bounding-box))

(define-method (initialize (node <node-2d>) args)
  (next-method)
  ;; If scale is specified as a scalar value, convert it to a vector
  ;; that applies identical scaling to both axes.
  (let ((s (scale node)))
    (when (number? s)
      (slot-set! node 'scale (vec2 s s))))
  ;; If caller doesn't specify a custom width and height, let the node
  ;; pick a reasonable default size.
  (let ((r (size node)))
    (set-rect-width! r (or (get-keyword #:width args)
                           (default-width node)))
    (set-rect-height! r (or (get-keyword #:height args)
                            (default-height node))))
  ;; Build an initial bounding box.
  (vec2-copy! (position node) (render-position node))
  ;; Set the initial last position to the same as the initial position
  ;; to avoid a brief flash where the node appears at (0, 0).
  (remember-position node))

(define (expire-local-matrix node)
  (expire-slot! node 'local-matrix)
  (expire-world-matrix node)
  (expire-local-bounding-box node))

(define (expire-world-matrix node)
  (unless (slot-expired? node 'world-matrix)
    (expire-slot! node 'world-matrix)
    (expire-slot! node 'inverse-world-matrix)
    (for-each-child (lambda (child)
                      (expire-world-matrix child)
                      (expire-world-bounding-box child))
                    node)))

(define (expire-local-bounding-box node)
  (expire-slot! node 'local-bounding-box)
  (expire-world-bounding-box node))

(define (expire-world-bounding-box node)
  (expire-slot! node 'world-bounding-box)
  (expire-aggregate-bounding-box node))

(define (expire-aggregate-bounding-box node)
  (unless (slot-expired? node 'aggregate-bounding-box)
    (expire-slot! node 'aggregate-bounding-box)
    (let ((p (parent node)))
      (when (is-a? p <node-2d>)
        (expire-aggregate-bounding-box p)))))


;;;
;;; Bounding boxes
;;;

(define-method (default-width (node <node-2d>)) 0.0)

(define-method (default-height (node <node-2d>)) 0.0)

(define-method (local-x (node <node-2d>))
  (rect-x (local-bounding-box node)))

(define-method (local-y (node <node-2d>))
  (rect-y (local-bounding-box node)))

(define-method (local-width (node <node-2d>))
  (rect-width (local-bounding-box node)))

(define-method (local-height (node <node-2d>))
  (rect-height (local-bounding-box node)))

(define-method (local-origin-x (node <node-2d>))
  (matrix4-transform-x (local-matrix node) 0.0 0.0))

(define-method (local-origin-y (node <node-2d>))
  (matrix4-transform-y (local-matrix node) 0.0 0.0))

(define-method (on-child-resize node child)
  #t)

(define-method (on-change (node <node-2d>) slot old new)
  (case slot
    ((origin position rotation scale shear)
     (expire-local-matrix node)))
  (next-method))

(define-method (resize (node <node-2d>) w h)
  ;; No-op if the size is the same.
  (unless (and (= (width node) w)
               (= (height node) h))
    (set! (width node) w)
    (set! (height node) h)
    (expire-local-bounding-box node)
    (on-child-resize (parent node) node)))

(define-method (resize (node <node-2d>))
  (resize node (default-width node) (default-height node)))


;;;
;;; Animation
;;;

(define-method (remember-position (node <node-2d>))
  (vec2-copy! (position node) (last-position node)))

(define-method (remember-position/recursive (node <node-2d>))
  (remember-position node)
  (for-each-child remember-position/recursive node))

(define-method (move-to (node <node-2d>) x y)
  (set! (position-x node) x)
  (set! (position-y node) y))

(define-method (move-to (node <node-2d>) x y duration ease)
  (let ((p (position node)))
    (move-by node (- x (vec2-x p)) (- y (vec2-y p)) duration ease)))

(define-method (move-to (node <node-2d>) x y duration)
  (move-to node x y duration smoothstep))

(define-method (move-by (node <node-2d>) dx dy)
  ;; No-op if the node wouldn't be moved at all.
  (unless (and (= dx 0.0) (= dy 0.0))
    (let ((p (position node)))
      (move-to node (+ (vec2-x p) dx) (+ (vec2-y p) dy)))))

(define-method (move-by (node <node-2d>) dx dy duration ease)
  ;; No-op if the node wouldn't be moved at all.
  (unless (and (= dx 0.0) (= dy 0.0))
    (let* ((p (position node))
           (start-x (vec2-x p))
           (start-y (vec2-y p)))
      (tween duration 0.0 1.0
             (lambda (n)
               (move-to node
                        (+ start-x (* dx n))
                        (+ start-y (* dy n))))
             #:ease ease))))

(define-method (move-by (node <node-2d>) dx dy duration)
  (move-by node dx dy duration smoothstep))

(define-method (teleport (node <node-2d>) x y)
  ;; When teleporting, we want to avoid position interpolation and odd
  ;; looking camera jumps.
  ;;
  ;; Interpolation is avoided by setting all 3 position vectors to the
  ;; same values.  This prevents a visual artifact where the player
  ;; sees 1 frame where the node is somewhere in between its former
  ;; position and the new position.
  ;;
  ;; The camera jump problem occurs when a camera has a node as its
  ;; tracking target and that node teleports. Normally, the camera's
  ;; view matrix is updated before any nodes are rendered, and thus
  ;; *before* the node can recompute its world matrix based on the new
  ;; position.  This creates 1 frame where the camera is improperly
  ;; positioned at the target's old location.  This 1 frame lag is not
  ;; an issue during normal movement, but when teleporting it causes a
  ;; noticably unsmooth blip.  Forcing the matrices to be recomputed
  ;; immediately solves this issue.
  (set-vec2! (position node) x y)
  (set-vec2! (last-position node) x y)
  (set-vec2! (render-position node) x y)
  (expire-local-matrix node))

(define-method (rotate-to (node <node-2d>) theta)
  (set! (rotation node) theta))

(define-method (rotate-to (node <node-2d>) theta duration ease)
  (tween duration (rotation node) theta
         (lambda (r)
           (rotate-to node r))
         #:ease ease))

(define-method (rotate-to (node <node-2d>) theta duration)
  (rotate-to node theta duration smoothstep))

(define-method (rotate-by (node <node-2d>) dtheta)
  (rotate-to node (+ (rotation node) dtheta)))

(define-method (rotate-by (node <node-2d>) dtheta duration ease)
  (rotate-to node (+ (rotation node) dtheta) duration ease))

(define-method (rotate-by (node <node-2d>) dtheta duration)
  (rotate-by node dtheta duration smoothstep))

(define-method (scale-to (node <node-2d>) sx sy)
  (set! (scale-x node) sx)
  (set! (scale-y node) sy))

(define-method (scale-to (node <node-2d>) s)
  (scale-to node s s))

(define-method (scale-to (node <node-2d>) sx sy duration ease)
  (scale-by node (- sx (scale-x node)) (- sy (scale-y node)) duration ease))

(define-method (scale-to (node <node-2d>) sx sy duration)
  (scale-to node sx sy duration smoothstep))

(define-method (scale-by (node <node-2d>) dsx dsy)
  (scale-to node (+ (scale-x node) dsx) (+ (scale-y node) dsy)))

(define-method (scale-by (node <node-2d>) ds)
  (scale-by node ds ds))

(define-method (scale-by (node <node-2d>) dsx dsy duration ease)
  (let ((start-x (scale-x node))
        (start-y (scale-y node)))
    (tween duration 0.0 1.0
           (lambda (n)
             (scale-to node
                       (+ start-x (* dsx n))
                       (+ start-y (* dsy n))))
           #:ease ease)))

(define-method (scale-by (node <node-2d>) dsx dsy duration)
  (scale-by node dsx dsy duration smoothstep))

(define-method (scale-by (node <node-2d>) ds duration (ease <procedure>))
  (scale-by node ds ds duration ease))

(define-method (follow-bezier-path (node <node-2d>) path duration forward?)
  (let ((p (position node))
        (path (if forward? path (reverse path))))
    (for-each (lambda (bezier)
                (tween duration
                       (if forward? 0.0 1.0)
                       (if forward? 1.0 0.0)
                       (lambda (t)
                         (bezier-curve-point-at! p bezier t)
                         (expire-local-matrix node))
                       #:ease linear))
              path)))

(define-method (follow-bezier-path (node <node-2d>) path duration)
  (follow-bezier-path node path duration #t))

(define-method (world->local (node <node-2d>) p)
  (matrix4-transform-vec2 (inverse-world-matrix node) p))

(define-method (pick (node <node-2d>) p)
  (let loop ((kids (reverse (children node))))
    (match kids
      (()
       ;; Multiply the cursor position by the inverse world matrix to
       ;; translate world coordinates into node-local coordinates.
       (let* ((p* (world->local node p))
              (x (vec2-x p*))
              (y (vec2-y p*)))
         (and (>= x 0.0)
              (< x (width node))
              (>= y 0.0)
              (< y (height node))
              node)))
      ((child . rest)
       (let ((o (origin node)))
         (or (pick child p)
             (loop rest)))))))


;;;
;;; Updating/rendering
;;;

(define-method (update/around (node <node-2d>) dt)
  (unless (paused? node)
    (remember-position node))
  (next-method))

(define-method (pause (node <node-2d>))
  ;; We need to set the last position of all objects in the tree to
  ;; their current position, otherwise any moving objects will
  ;; experience this weird jitter while paused because the last
  ;; position will never be updated during the duration of the pause
  ;; event.
  (next-method)
  (remember-position/recursive node))

(define-method (tree-in-view? (node <node-2d>))
  (rect-intersects? (aggregate-bounding-box node)
                    (view-bounding-box (current-camera))))

(define-method (in-view? (node <node-2d>))
  (rect-intersects? (world-bounding-box node)
                    (view-bounding-box (current-camera))))

(define-method (render/around (node <node-2d>) alpha)
  ;; Compute the linearly interpolated rendering position, in the case
  ;; that node has moved since the last update.
  (when (visible? node)
    (let ((p (position node))
          (lp (last-position node))
          (rp (render-position node)))
      (unless (and (vec2= rp p) (vec2= lp p))
        (let ((beta (- 1.0 alpha)))
          (set-vec2-x! rp (+ (* (vec2-x p) alpha) (* (vec2-x lp) beta)))
          (set-vec2-y! rp (+ (* (vec2-y p) alpha) (* (vec2-y lp) beta)))
          (expire-local-matrix node))))
    (next-method)))


;;;
;;; Placement and alignment
;;;

(define (place-at-x node x)
  "Adjust position of NODE so that its left edge is at X on the x-axis."
  (set! (position-x node)
        (+ x (- (local-origin-x node) (local-x node)))))

(define (place-at-y node y)
  "Adjust position of NODE so that its bottom edge is at Y on the
y-axis."
  (set! (position-y node)
        (+ y (- (local-origin-y node) (local-y node)))))

(define (place-at node x y)
  "Adjust position of NODE so that its bottom-left corner is at (X, Y)."
  (place-at-x node x)
  (place-at-y node y))

;; Relative placement and alignment of nodes is done under the
;; assumption that the nodes are in the same local coordinate space.
;; If this is not the case, the results will be garbage.

(define* (place-right a b #:key (padding 0.0))
  "Adjust B's x position coordinate so that it is PADDING distance to
the right of A."
  (set! (position-x b)
        (+ (local-x a) (local-width a) padding
           (- (local-origin-x b) (local-x b)))))

(define* (place-left a b #:key (padding 0.0))
  "Adjust B's x position coordinate so that it is PADDING distance to
the left of A."
  (set! (position-x b)
        (- (local-x a) (local-width b) padding
           (- (local-x b) (local-origin-x b)))))

(define* (place-above a b #:key (padding 0.0))
  "Adjust B's y position coordinate so that it is PADDING distance above
A."
  (set! (position-y b)
        (+ (local-y a) (local-height a) padding
           (- (local-origin-y b) (local-y b)))))

(define* (place-below a b #:key (padding 0.0))
  "Adjust B's y position coordinate so that it is PADDING distance below
A."
  (set! (position-y b)
        (- (local-y a) (local-height b) padding
           (- (local-y b) (local-origin-y b)))))

(define (align-right a b)
  "Align the right side of B with the right side of A."
  (set! (position-x b)
        (+ (local-x a) (local-width a)
           (- (local-origin-x b) (local-x b)))))

(define (align-left a b)
  "Align the left side of B with the left side of A."
  (set! (position-x b)
        (- (local-x a)
           (- (local-x b) (local-origin-x b)))))

(define (align-top a b)
  "Align the top of B with the top of A."
  (set! (position-y b)
        (+ (local-y a) (local-height a)
           (- (local-origin-y b) (local-y b)))))

(define (align-bottom a b)
  "Align the bottom of B with the bottom of A."
  (set! (position-y b)
        (- (local-y a)
           (- (local-y b) (local-origin-y b)))))

(define (center-horizontal a b)
  "Move the x position of A so that it is centered with B."
  (set! (position-x b)
        (+ (local-x a)
           (/ (- (local-width a) (local-width b)) 2.0)
           (- (local-x b) (local-origin-x b)))))

(define (center-vertical a b)
  "Move the y position of A so that it is centered with B."
  (set! (position-y b)
        (+ (local-y a)
           (/ (- (local-height a) (local-height b)) 2.0)
           (- (local-y b) (local-origin-y b)))))

(define (center a b)
  "Center B within A."
  (center-horizontal a b)
  (center-vertical a b))

(define (center-horizontal-in-parent node)
  "Center x position of NODE within its parent."
  (set! (position-x node)
        (+ (/ (- (width (parent node)) (local-width node)) 2.0)
           (- (local-origin-x node) (local-x node)))))

(define (center-vertical-in-parent node)
  "Center y position of NODE within its parent."
  (set! (position-y node)
        (+ (/ (- (height (parent node)) (local-height node)) 2.0)
           (- (local-origin-y node) (local-y node)))))

(define (center-in-parent node)
  "Center NODE within its parent."
  (center-horizontal-in-parent node)
  (center-vertical-in-parent node))


;;;
;;; Sizing
;;;

(define* (fit-to-children node #:optional (padding 0.0))
  "Resize NODE to fit the current size of its visible children, with
PADDING on all sides."
  (let ((bb (make-null-rect)))
    ;; Compute bounding box of all children.
    (for-each-child (lambda (child)
                      (when (visible? child)
                        (rect-union! bb (local-bounding-box child))))
                    node)
    ;; Adjust all children so that there is the desired padding.
    (let ((dx (- padding (rect-x bb)))
          (dy (- padding (rect-y bb))))
      (for-each-child (lambda (child)
                        (when (visible? child)
                          (move-by child dx dy)))
                      node))
    ;; Finally, resize ourselves.
    (let ((w (+ (rect-width bb) (* padding 2.0)))
          (h (+ (rect-height bb) (* padding 2.0))))
      (resize node w h))))


;;;
;;; Sprite
;;;

(define-class <sprite> (<node-2d>)
  (texture #:accessor texture #:init-keyword #:texture #:asset? #t
           #:observe? #t)
  (tint #:accessor tint #:init-keyword #:tint #:init-form white)
  (blend-mode #:accessor blend-mode #:init-keyword #:blend-mode
              #:init-form blend:alpha))

(define-method (default-width (sprite <sprite>))
  (let ((t (texture sprite)))
    (if t (texture-width t) 0.0)))

(define-method (default-height (sprite <sprite>))
  (let ((t (texture sprite)))
    (if t (texture-height t) 0.0)))

(define-method (on-change (sprite <sprite>) slot-name old new)
  (case slot-name
    ((texture)
     (let ((new (artifact (->asset new))))
       (resize sprite
               (texture-width new)
               (texture-height new)))))
  (next-method))

(define-method (render (sprite <sprite>) alpha)
  (let ((t (texture sprite)))
    (with-graphics-state ((g:blend-mode (blend-mode sprite)))
      (draw-sprite* t (size sprite) (world-matrix sprite)
                    #:tint (tint sprite)
                    #:texcoords (texture-gl-tex-rect t)))))


;;;
;;; Texture Atlas Sprite
;;;

(define-class <atlas-sprite> (<sprite>)
  (atlas #:accessor atlas #:init-keyword #:atlas #:asset? #t #:observe? #t)
  (index #:accessor index #:init-keyword #:index #:init-value 0 #:observe? #t))

(define-method (sync-texture (sprite <atlas-sprite>))
  (let ((t (texture-atlas-ref (atlas sprite) (index sprite))))
    (set! (texture sprite) t)))

(define-method (initialize (sprite <atlas-sprite>) initargs)
  (next-method)
  (sync-texture sprite))

(define-method (on-change (sprite <atlas-sprite>) slot-name old new)
  (case slot-name
    ((atlas index)
     (sync-texture sprite))
    (else
     (next-method))))


;;;
;;; Animated Sprite
;;;

(define-class <animation> ()
  (frames #:getter frames #:init-keyword #:frames)
  (frame-duration #:getter frame-duration #:init-keyword #:frame-duration
                  #:init-form 250))

(define-class <animated-sprite> (<atlas-sprite>)
  (atlas #:accessor atlas #:init-keyword #:atlas #:asset? #t)
  (animations #:accessor animations #:init-keyword #:animations)
  (current-animation #:accessor current-animation
                     #:init-keyword #:default-animation
                     #:init-form 'default)
  (start-time #:accessor start-time #:init-form 0))

(define-method (on-enter (sprite <animated-sprite>))
  (update sprite 0))

(define-method (update (sprite <animated-sprite>) dt)
  (let* ((anim (assq-ref (animations sprite) (current-animation sprite)))
         (frame-duration (frame-duration anim))
         (frames (frames anim))
         (anim-duration (* frame-duration (vector-length frames)))
         (time (mod (- (elapsed-time) (start-time sprite)) anim-duration))
         (frame (vector-ref frames (inexact->exact
                                    (floor (/ time frame-duration))))))
    (when (not (= frame (index sprite)))
      (set! (index sprite) frame))))

(define-method (change-animation (sprite <animated-sprite>) name)
  (set! (current-animation sprite) name)
  (set! (start-time sprite) (elapsed-time)))


;;;
;;; 9-Patch
;;;

(define-class <9-patch> (<node-2d>)
  (texture #:accessor texture #:init-keyword #:texture #:asset? #t)
  (left-margin #:accessor left-margin #:init-keyword #:left)
  (right-margin #:accessor right-margin #:init-keyword #:right)
  (bottom-margin #:accessor bottom-margin #:init-keyword #:bottom)
  (top-margin #:accessor top-margin #:init-keyword #:top)
  (mode #:accessor mode #:init-keyword #:mode #:init-value 'stretch)
  (blend-mode #:accessor blend-mode #:init-keyword #:blend-mode
              #:init-value blend:alpha)
  (tint #:accessor tint #:init-keyword #:tint #:init-value white)
  (render-rect #:getter render-rect #:init-form (make-rect 0.0 0.0 0.0 0.0)))

(define-method (initialize (9-patch <9-patch>) initargs)
  (let ((default-margin (get-keyword #:margin initargs 0.0)))
    (slot-set! 9-patch 'left-margin default-margin)
    (slot-set! 9-patch 'right-margin default-margin)
    (slot-set! 9-patch 'bottom-margin default-margin)
    (slot-set! 9-patch 'top-margin default-margin))
  (next-method)
  (set-rect-width! (render-rect 9-patch) (width 9-patch))
  (set-rect-height! (render-rect 9-patch) (height 9-patch)))

(define-method (on-change (9-patch <9-patch>) slot-name old new)
  (case slot-name
    ((width)
     (set-rect-width! (render-rect 9-patch) new))
    ((height)
     (set-rect-height! (render-rect 9-patch) new)))
  (next-method))

(define-method (render (9-patch <9-patch>) alpha)
  (draw-9-patch* (texture 9-patch)
                 (render-rect 9-patch)
                 (world-matrix 9-patch)
                 #:top-margin (top-margin 9-patch)
                 #:bottom-margin (bottom-margin 9-patch)
                 #:left-margin (left-margin 9-patch)
                 #:right-margin (right-margin 9-patch)
                 #:mode (mode 9-patch)
                 #:blend-mode (blend-mode 9-patch)
                 #:tint (tint 9-patch)))


;;;
;;; Sprite Batch
;;;

(define-class <sprite-batch> (<node-2d>)
  (batch #:accessor batch #:init-keyword #:batch)
  (blend-mode #:accessor blend-mode
              #:init-keyword #:blend-mode
              #:init-form blend:alpha)
  (clear-after-draw? #:accessor clear-after-draw?
                     #:init-keyword #:clear-after-draw?
                     #:init-form #t)
  (batch-matrix #:accessor batch-matrix #:init-thunk make-identity-matrix4))

(define-method (render (sprite-batch <sprite-batch>) alpha)
  (let ((batch (batch sprite-batch)))
    (draw-sprite-batch* batch (batch-matrix sprite-batch)
                        #:blend-mode (blend-mode sprite-batch))
    (when (clear-after-draw? sprite-batch)
      (sprite-batch-clear! batch))))


;;;
;;; Vector Path
;;;

(define-class <canvas> (<node-2d>)
  (painter #:accessor painter #:init-keyword #:painter #:init-value #f
           #:observe? #t)
  (canvas #:accessor canvas #:init-thunk path:make-empty-canvas))

(define-method (on-enter (c <canvas>))
  (refresh-painter c))

;; Width and height of canvas nodes default to the size of their
;; initial painter, or 0 if there isn't one.
(define-method (default-width (c <canvas>))
  (let ((p (painter c)))
    (if p (rect-width (path:painter-bounding-box p)) 0.0)))

(define-method (default-height (c <canvas>))
  (let ((p (painter c)))
    (if p (rect-height (path:painter-bounding-box p)) 0.0)))

(define-method (refresh-painter (c <canvas>))
  (define (close? x y)
    (<= (abs (- x y)) 0.01))
  (let* ((p (painter c)))
    (when p
      ;; Scale the original painter within the vector path rendering
      ;; system so that it fills the canvas nodes bounding box.
      (let* ((bb (path:painter-bounding-box p))
             (pw (rect-width bb))
             (ph (rect-height bb))
             (w (width c))
             (h (height c))
             (p* (if (and (close? w pw) (close? h ph))
                     p ; width/height the same
                     ;; Scale by the factor that makes the painter's
                     ;; size stretch/shrink to occupy the entire
                     ;; bounding box.
                     (path:scale (vec2 (/ w pw) (/ h ph)) p))))
        (path:set-canvas-painter! (canvas c) p*)))))

(define-method ((setter canvas) (c <canvas>))
  (next-method)
  (path:set-canvas-painter! (canvas c) (painter c)))

(define-method (on-change (c <canvas>) slot-name old new)
  (case slot-name
    ((painter width height)
     (refresh-painter c)))
  (next-method))

(define-method (render (c <canvas>) alpha)
  (path:draw-canvas* (canvas c) (world-matrix c)))


;;;
;;; Label
;;;

(define-class <label> (<node-2d>)
  (font #:accessor font #:init-keyword #:font #:init-thunk default-font
        #:asset? #t #:observe? #t)
  (text #:accessor text #:init-value "" #:init-keyword #:text #:observe? #t)
  (compositor #:accessor compositor #:init-thunk make-compositor)
  (page #:accessor page #:init-thunk make-page)
  (typeset #:accessor typeset #:init-value typeset-lrtb)
  (align #:accessor align #:init-value 'left #:init-keyword #:align #:observe? #t)
  (vertical-align #:accessor vertical-align #:init-value 'bottom
                  #:init-keyword #:vertical-align #:observe? #t)
  (color #:accessor color #:init-keyword #:color #:init-value white #:observe? #t))

(define-method (initialize (label <label>) initargs)
  (next-method)
  (refresh-label label)
  (realign label))

(define-method (realign (label <label>))
  (set! (origin-x label)
        (case (align label)
          ((left) 0.0)
          ((right) (width label))
          ((center) (/ (width label) 2.0))))
  (set! (origin-y label)
        (case (vertical-align label)
          ((bottom) 0.0)
          ((top) (height label))
          ((center) (+ (/ (height label) 2.0) (font-descent (font label)))))))

(define-method (refresh-label (label <label>))
  (let ((c (compositor label))
        (p (page label)))
    (compositor-reset! c)
    ((typeset label) c (font label) (text label) (color label))
    (page-reset! p)
    (page-write! p c)
    (let ((bb (page-bounding-box p)))
      (resize label (rect-width bb) (rect-height bb)))
    (realign label)))

(define-method (on-asset-reload (label <label>) slot-name asset)
  (case slot-name
    ((font)
     (refresh-label label))))

(define-method (on-change (label <label>) slot-name old new)
  (case slot-name
    ((font text)
     (refresh-label label)
     (unless (eq? (align label) 'left)
       (realign label)))
    ((color)
     (refresh-label label))
    ((align vertical-align)
     (realign label))
    (else
     (next-method))))

(define-method (render (label <label>) alpha)
  (draw-page (page label) (world-matrix label)))


;;;
;;; Tiled Map
;;;

(define-class <tile-map> (<node-2d>)
  (tile-map #:accessor tile-map #:init-keyword #:map #:asset? #t)
  (layers #:accessor layers #:init-keyword #:layers #:init-form #f))

(define-method (render (node <tile-map>) alpha)
  (let ((m (tile-map node)))
    (draw-tile-map* m (world-matrix node) (tile-map-rect m)
                    #:layers (layers node))))


;;;
;;; Particles
;;;

(define-class <particles> (<node-2d>)
  (particles #:accessor particles #:init-keyword #:particles))

(define-method (default-width (particles <particles>))
  32.0)

(define-method (default-height (particles <particles>))
  32.0)

(define-method (update (node <particles>) dt)
  (update-particles (particles node)))

(define-method (render (node <particles>) alpha)
  (draw-particles* (particles node) (world-matrix node)))