summaryrefslogtreecommitdiff
path: root/starling/node-2d.scm
blob: f439ebe161bf36e3dabd8b42184b6cd798dc8a77 (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
;;; Starling Game Engine
;;; Copyright © 2018, 2019 David Thompson <davet@gnu.org>
;;;
;;; This program is free software: you can redistribute it and/or
;;; modify it under the terms of the GNU General Public License as
;;; published by the Free Software Foundation, either version 3 of the
;;; License, or (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;;; General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with Starling.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:
;;
;; 2D game nodes.
;;
;;; Code:

(define-module (starling node-2d)
  #: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 color)
  #:use-module (chickadee graphics engine)
  #:use-module (chickadee graphics font)
  #:use-module (chickadee graphics framebuffer)
  #:use-module (chickadee graphics particles)
  #:use-module (chickadee graphics path)
  #:use-module (chickadee graphics sprite)
  #: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)
  #:use-module (starling asset)
  #:use-module (starling node)
  #:use-module (starling scene)
  #:use-module (starling system)
  #:export (<camera-2d>
            target
            offset
            position
            resolution
            viewport
            point-within-camera-viewport?
            window-space->camera-space

            <canvas>
            cameras
            first-camera

            <scene-2d>

            <node-2d>
            origin
            origin-x
            origin-y
            position
            position-x
            position-y
            rotation
            scale
            scale-x
            scale-y
            skew
            skew-x
            skew-y
            local-matrix
            world-matrix
            width
            height
            bounding-box
            on-child-resize
            dirty!
            move-by
            move-to
            teleport
            rotate-by
            rotate-to
            scale-by
            scale-to
            follow-bezier-path
            pick

            <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

            <sprite-batch>
            batch

            <path>
            painter

            <label>
            font
            text

            <tile-map>
            tile-map
            layers

            <particles>
            particles))


;;;
;;; 2D Camera
;;;

;; Cameras define a view into the scene.  They are attached to a 2D
;; node and follow it around.

(define (default-resolution)
  (call-with-values current-window-size
    (lambda (width height)
      (vec2 width height))))

(define (default-viewport)
  (call-with-values current-window-size
    (lambda (width height)
     (make-viewport 0 0 width height))))

(define-class <camera-2d> ()
  (target #:accessor target #:init-form #f #:init-keyword #:target)
  (offset #:accessor offset #:init-form (vec2 0.0 0.0) #:init-keyword #:offset)
  (position #:getter position #:init-form (vec2 0.0 0.0))
  (resolution #:getter resolution #:init-keyword #:resolution
              #:init-thunk default-resolution)
  (viewport #:getter viewport #:init-keyword #:viewport
            #:init-thunk default-viewport)
  (projection-matrix #:accessor projection-matrix)
  ;; Combined projection/view matrix
  (view-matrix #:getter view-matrix #:init-form (make-identity-matrix4)))

(define-method (initialize (camera <camera-2d>) initargs)
  (next-method)
  ;; Initialize orthographic projection matrix based on the resolution
  ;; of the camera.
  (let ((r (resolution camera)))
    (set! (projection-matrix camera)
      (orthographic-projection 0 (vec2-x r) (vec2-y r) 0 0 1))))

;; This method can be overridden by subclasses to create custom camera
;; movement.
(define-method (follow-target (camera <camera-2d>))
  (let ((p (position camera))
        (m (view-matrix camera))
        (w (world-matrix (target camera))))
    (set-vec2! p (matrix4-x w) (matrix4-y w))
    (vec2-mult! p -1.0)
    (vec2-add! p (offset camera))
    (matrix4-translate! m (position camera))
    (matrix4-mult! m m (projection-matrix camera))))

(define-syntax-rule (with-camera camera body ...)
  (begin
    (when (target camera)
      (follow-target camera))
    (with-graphics-state ((g:viewport (viewport camera)))
      (with-projection (if (target camera)
                           (view-matrix camera)
                           (projection-matrix camera))
        body ...))))

(define-method (point-within-camera-viewport? (camera <camera-2d>) p)
  (let* ((vp (viewport camera))
         (x (viewport-x vp))
         (y (viewport-y vp))
         (w (viewport-width vp))
         (h (viewport-height vp))
         (px (vec2-x p))
         (py (vec2-y p)))
    (and (>= px x)
         (< px (+ x w))
         (>= py y)
         (< py (+ y h)))))

(define-method (window-space->camera-space (camera <camera-2d>) p)
  ;; To translate a coordinate in window space to camera space, we
  ;; do the following:
  ;;
  ;; - transform p into viewport space by subtracting the viewport
  ;; position
  ;;
  ;; - transform the result of the previous step into camera space by
  ;; multiplying by the ratio of the viewport size / camera resolution
  ;;
  ;; - finally, translate the result of the previous step to the
  ;; correct position relative to the camera's current location by
  ;; adding the camera position
  (let* ((vp (viewport camera))
         (r (resolution camera))
         (pos (position camera)))
    (vec2 (+ (* (- (vec2-x p) (viewport-x vp))
                (/ (vec2-x r) (viewport-width vp)))
             (vec2-x pos))
          (+ (* (- (vec2-y p) (viewport-y vp))
                (/ (vec2-y r) (viewport-height vp)))
             (vec2-y pos)))))


;;;
;;; 2D Canvas
;;;

;; The canvas is the root of a 2D scene.  It handles rendering one or
;; more cameras.

(define-class <canvas> (<node>)
  (cameras #:accessor cameras #:init-form (list (make <camera-2d>))
           #:init-keyword #:cameras))

(define-method (render-tree (canvas <canvas>) alpha)
  (render canvas alpha)
  ;; Draw scene from the viewpoint of each camera.
  (for-each (lambda (camera)
              (with-camera camera
                 (for-each-child (lambda (child)
                                   (render-tree child alpha))
                                 canvas)))
            (cameras canvas)))

(define-method (first-camera (canvas <canvas>))
  (match (cameras canvas)
    ((camera . _) camera)
    (() #f)))

(define-method (pick (canvas <canvas>) p)
  (let camera-loop ((cams (cameras canvas)))
    (match cams
      (() #f)
      ((camera . rest)
       (if (point-within-camera-viewport? camera p)
           (let ((p* (window-space->camera-space camera p)))
             (let loop ((kids (reverse (children canvas))))
               (match kids
                 (() #f)
                 ((child . rest)
                  (or (pick child p*)
                      (loop rest))))))
           (camera-loop rest))))))


;;;
;;; 2D Scene
;;;

(define-class <scene-2d> (<scene> <canvas>))


;;;
;;; 2D Game Node
;;;

(define-class <node-2d> (<node>)
  ;; Transformation components: origin, position, rotation, scale, and
  ;; skew.
  (origin #:accessor origin #:init-form (vec2 0.0 0.0) #:init-keyword #:origin
          #:watch? #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)
                          (dirty! 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)
                          (dirty! node)))
  (position #:accessor position #:init-form (vec2 0.0 0.0)
            #:init-keyword #:position #:watch? #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)
                            (dirty! 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)
                            (dirty! node)))
  (rotation #:accessor rotation #:init-form 0.0 #:init-keyword #:rotation
            #:watch? #t)
  (scale #:accessor scale #:init-form (vec2 1.0 1.0) #:init-keyword #:scale
         #:watch? #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)
                         (dirty! 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)
                         (dirty! node)))
  (skew #:accessor skew #:init-form (vec2 0.0 0.0) #:init-keyword #:skew
        #:watch? #t)
  (skew-x #:accessor skew-x #:allocation #:virtual
          #:slot-ref (lambda (node) (vec2-x (skew node)))
          #:slot-set! (lambda (node x)
                        (set-vec2-x! (skew node) x)
                        (dirty! node)))
  (skew-y #:accessor skew-y #:allocation #:virtual
          #:slot-ref (lambda (node) (vec2-y (skew node)))
          #:slot-set! (lambda (node y)
                        (set-vec2-y! (skew node) y)
                        (dirty! 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))
  ;; Lazily computed transformation matrices.
  (local-matrix #:getter local-matrix #:init-form (make-identity-matrix4))
  (world-matrix #:getter world-matrix #:init-form (make-identity-matrix4))
  (dirty-matrix? #:accessor dirty-matrix? #:init-form #t)
  ;; Bounding box for render culling, mouse selection, etc.
  (width #:accessor width #:init-keyword #:width #:init-form 0.0 #:watch? #t)
  (height #:accessor height #:init-keyword #:height #:init-form 0.0 #:watch? #t)
  (bounding-box #:getter bounding-box #:init-form (make-rect 0.0 0.0 0.0 0.0))
  (dirty-bounding-box? #:accessor dirty-bounding-box? #:init-form #t))

(define-method (dirty! (node <node-2d>))
  (set! (dirty-matrix? node) #t)
  (set! (dirty-bounding-box? node) #t))

(define-method (refresh-matrices (node <node-2d>))
  (let ((local (local-matrix node))
        (world (world-matrix node)))
    (matrix4-2d-transform! local
                           #:origin (origin node)
                           #:position (render-position node)
                           #:rotation (rotation node)
                           #:scale (scale node)
                           #:skew (skew node))
    ;; Compute world matrix by multiplying by the parent node's
    ;; matrix, if there is a 2D parent node, that is.
    (if (and (parent node) (is-a? (parent node) <node-2d>))
        (matrix4-mult! world local (world-matrix (parent node)))
        (begin
          (matrix4-identity! world)
          (matrix4-mult! world world local)))))

(define-method (on-child-resize (node <node-2d>) child)
  #t)

;; TODO: Take rotation and skew into consideration.
(define-method (refresh-bounding-box (node <node-2d>))
  (let ((bb (bounding-box node))
        (p (position node))
        (o (origin node))
        (s (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 (* (width node) (vec2-x s)))
    (set-rect-height! bb (* (height node) (vec2-y s)))
    (set! (dirty-bounding-box? node) #f)))

(define-method (on-change (node <node-2d>) slot old new)
  (case slot
    ((origin position rotation scale skew)
     (set! (dirty-bounding-box? node) #t)
     (dirty! node))
    ((width height)
     (let ((np (parent node)))
       (when (is-a? np <node-2d>)
         (on-child-resize (parent node) node)))
     (set! (dirty-bounding-box? node) #t))))

;; Animation helpers

(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)
  (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)
  (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)
  (refresh-matrices 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)
                         (dirty! node))
                       #:ease linear))
              path)))

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

(define-method (pick (node <node-2d>) p)
  (let ((bb (bounding-box node)))
    (let loop ((kids (reverse (children node))))
      (match kids
        (()
         (and (rect-contains-vec2? bb p)
              node))
        ((child . rest)
         (let ((o (origin node)))
           (or (pick child (vec2- p (position node)))
               (loop rest))))))))

;; Events

(define-method (update-tree (node <node-2d>) dt)
  (vec2-copy! (position node) (last-position node))
  (when (dirty-bounding-box? node)
    (refresh-bounding-box node))
  (next-method))

(define-method (render-tree (node <node-2d>) alpha)
  (when (visible? node)
    ;; Compute the linearly interpolated rendering position, in the case
    ;; that node has moved since the last update.
    (let ((p (position node))
          (lp (last-position node))
          (rp (render-position node))
          (beta (- 1.0 alpha)))
      (unless (and (vec2= rp p) (vec2= lp p))
        (set-vec2-x! rp (+ (* (vec2-x p) alpha) (* (vec2-x lp) beta)))
        (set-vec2-y! rp (+ (* (vec2-y p) alpha) (* (vec2-y lp) beta)))
        (set! (dirty-matrix? node) #t)))
    ;; Recompute dirty matrices.
    (when (dirty-matrix? node)
      (refresh-matrices node)
      (set! (dirty-matrix? node) #f)
      ;; If the parent is dirty, all the children need to be marked as
      ;; dirty, too.
      (for-each-child (lambda (child)
                        (when (is-a? child <node-2d>)
                          (set! (dirty-matrix? child) #t)))
                      node)))
  (next-method))

(define-method (activate (node <node-2d>))
  (set! (dirty-matrix? node) #t)
  ;; Set the initial last position to the same as the initial position
  ;; to avoid a brief flash where the node appears at (0, 0).
  (vec2-copy! (position node) (last-position node))
  (next-method))


;;;
;;; Sprite
;;;

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

(define-method (refresh-sprite-size (sprite <sprite>))
  (let ((t (texture sprite)))
    (set! (width sprite) (texture-width t))
    (set! (height sprite) (texture-height t))))

(define-method (on-asset-reload (sprite <sprite>) slot-name asset)
  (case slot-name
    ((texture)
     (refresh-sprite-size sprite))))

(define-method (on-change (sprite <sprite>) slot-name old new)
  (case slot-name
    ((texture)
     (refresh-sprite-size sprite))
    (else
     (next-method))))

(define-method (on-boot (sprite <sprite>))
  (refresh-sprite-size sprite))

(define-method (render (sprite <sprite>) alpha)
  (let* ((tex (texture sprite))
         (rect (texture-gl-rect tex))
         (batch (batch sprite))
         (tint (tint sprite))
         (matrix (world-matrix sprite)))
    (if batch
        (sprite-batch-add* batch rect matrix
                           #:tint tint
                           #:texture-region tex)
        (draw-sprite* tex rect matrix
                      #:tint tint
                      #:texcoords (texture-gl-tex-rect tex)))))

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

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

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

(define-method (on-boot (sprite <atlas-sprite>))
  (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)))


;;;
;;; 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 '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 <path> (<node-2d>)
  (painter #:accessor painter #:init-keyword #:painter #:watch? #t)
  (canvas #:accessor canvas #:init-thunk make-empty-canvas))

(define-method (initialize (path <path>) args)
  (next-method)
  (set-canvas-painter! (canvas path) (painter path)))

(define-method (on-change (path <path>) slot-name old new)
  (pk 'change slot-name old new)
  (when (eq? slot-name 'painter)
    (set-canvas-painter! (canvas path) new)))

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


;;;
;;; Label
;;;

(define-class <label> (<node-2d>)
  (font #:accessor font #:init-keyword #:font #:init-thunk default-font
        #:asset? #t #:watch? #t)
  (text #:accessor text #:init-form "" #:init-keyword #:text #:watch? #t)
  (align #:accessor align #:init-value 'left #:init-keyword #:align #:watch? #t)
  (vertical-align #:accessor vertical-align #:init-value 'bottom
                  #:init-keyword #:vertical-align #:watch? #t))

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

(define-method (refresh-label-size (label <label>))
  (let ((f (font label))
        (t (text label)))
    (set! (width label) (font-line-width f t))
    (set! (height label) (font-line-height f))))

(define-method (on-boot (label <label>))
  (refresh-label-size label)
  (realign label))

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

(define-method (on-change (label <label>) slot-name old new)
  (case slot-name
    ;; TODO: Minor performance improvement: Realignment is not
    ;; necessary when changing the text of a left-aligned label.
    ((font text)
     (refresh-label-size label)
     (realign label))
    ((align vertical-align)
     (realign label))
    (else
     (next-method))))

(define-method (render (label <label>) alpha)
  (draw-text* (font label) (text 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 (initialize (node <tile-map>) initargs)
  (next-method))

(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 (on-boot (particles <particles>))
  ;; Default bounding box size.
  (when (zero? (width particles))
    (set! (width particles) 32.0))
  (when (zero? (height particles))
    (set! (height 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)))