doodle / doodle.scm

  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
;; Doodle - Drawing and gaming made easy
;;
;; Copyright (c) 2012, Christian Kellermann
;; All rights reserved.

;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:

;;     Redistributions of source code must retain the above copyright
;;     notice, this list of conditions and the following disclaimer.
;;
;;     Redistributions in binary form must reproduce the above
;;     copyright notice, this list of conditions and the following
;;     disclaimer in the documentation and/or other materials provided
;;     with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
;; COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
;; OF THE POSSIBILITY OF SUCH DAMAGE.

(module doodle
        (*sprites*
         add-sprite!
         blit-image
         check-for-collisions
         circle
         clear-screen
         current-background
         doodle-width
         doodle-height
         draw-line
         define-resource
         filled-circle
         filled-rectangle
         font-color
         font-size
         make-sprite
         line-width
         new-doodle
         rectangle
         remove-sprite!
         run-event-loop
         save-screenshot
         set-font!
         show!
         solid-black
         solid-white
         text
         text-width
         update-sprite!
         world-changes
         world-inits
         world-ends)

(import chicken scheme)
(use (srfi 1 4 18) cairo data-structures extras sdl clojurian-syntax matchable)

(define font-color (make-parameter (list 0 0 0 1)))
(define font-size (make-parameter 12))

(define line-width (make-parameter 2.0))

(define current-background (make-parameter (list 0 0 0 1)))
(define solid-black (list 0 0 0 1))
(define solid-white (list 1 1 1 1))

(define *c* #f)
(define *c-surface* #f)
(define *s* #f)

(define doodle-width #f)
(define doodle-height #f)

(define (expect-procedure p)
  (unless (procedure? p)
    (error "This parameter can be set to procedures only, you gave it " p))
  p)

(define world-ends (make-parameter void expect-procedure))
(define world-changes (make-parameter void expect-procedure))
(define world-inits (make-parameter void expect-procedure))

(define-syntax set-color
  (syntax-rules ()
    ((_ color) (apply cairo-set-source-rgba `(,*c* ,@color)))))

(define (set-font! font size color)
  (font-color color)
  (font-size size)
  (cairo-select-font-face *c* font CAIRO_FONT_SLANT_NORMAL CAIRO_FONT_WEIGHT_NORMAL)
  (cairo-set-font-size *c* (font-size)))

(define (text-width text)
  (define ex (make-cairo-text-extents-type))
  (cairo-set-font-size *c* (font-size))
  (cairo-text-extents *c* text ex)
  (values (cairo-text-extents-width ex)
          (cairo-text-extents-height ex)))

(define (circle x y diameter color)
  (set-color color)
  (doto *c*
        (cairo-set-line-width (line-width))
        (cairo-arc x y (/ diameter 2) 0 (* 2 cairo-pi))
        (cairo-stroke)))

(define (filled-circle x y diameter color)
  (set-color color)
  (doto *c*
        (cairo-set-line-width (line-width))
        (cairo-arc x y (/ diameter 2) 0 (* 2 cairo-pi))
        (cairo-fill)))

(define (filled-rectangle x1 y1 width height color)
  (set-color color)
  (doto *c*
        (cairo-new-path)
        (cairo-set-line-width (line-width))
        (cairo-set-dash (make-f64vector 0) 0 0)
        (cairo-rectangle x1 y1 width height)
        (cairo-fill)
        (cairo-close-path)))

(define (rectangle x1 y1 width height color)
  (set-color color)
  (doto *c*
        (cairo-new-path)
        (cairo-set-line-width (line-width))
        (cairo-set-dash (make-f64vector 0) 0 0)
        (cairo-rectangle x1 y1 width height)
        (cairo-stroke)
        (cairo-close-path)))

(define (draw-line x1 y1 x2 y2
                   #!key
                   (width (line-width))
                   (color solid-white)
                   (style #:solid))
  (doto *c*
        (cairo-set-line-width width)
        (cairo-new-path)
        (cairo-move-to x1 y1))
  (set-color color)
  (case style
    ((#:solid)
     (cairo-set-dash *c* (make-f64vector 0) 0 0))
    ((#:dashed)
     (cairo-set-dash *c* (make-f64vector 1 5) 1 0))
    (else (error "unknown line style " style)))
  (doto *c*
        (cairo-line-to x2 y2)
        (cairo-stroke)))

(define (text x y text #!key (align #:left))
  (define (overall-height text)
    (let ((l (if (list? text) text (list text))))
      (fold (lambda (t s)
              (let-values (((w h) (text-width t)))
                          (+ s (* 1.5 h))))
            0
            l)))

  (define (draw-text x y text align)
    (let-values (((w h) (text-width text)))
                (let ((fx (case align
                            ((#:center) (- x (/ w 2)))
                            ((#:left) x)
                            ((#:right (- x w)))
                            (else x)))
                      (fy y))
                  (apply cairo-set-source-rgba `(,*c* ,@(font-color)))
                  (doto *c*
                        (cairo-move-to fx fy)
                        (cairo-set-font-size (font-size))
                        (cairo-show-text text))
                  h)))
  (if (list? text)
      (for-each (let ((y (if (eq? align #:center)
                             (- y (/ (overall-height text) 4))
                             y)))
                  (lambda (t)
                    (set! y (+ y (* 1.5 (draw-text x y t align))))))
                text)
      (draw-text x y text align)))

(define (save-screenshot filename)
  (cairo-surface-write-to-png *c-surface* filename))

(define (insert-image-as-background filename)
  (let* ((width (cairo-image-surface-get-width *c-surface*))
         (height (cairo-image-surface-get-height *c-surface*))
         (img (cairo-image-surface-create-from-png filename))
         (img-width (cairo-image-surface-get-width img))
         (img-height (cairo-image-surface-get-height img)))
    (doto *c*
          (cairo-set-source-rgba 0 0 0 1)
          (cairo-rectangle 0 0 width height)
          (cairo-fill)
          (cairo-stroke)
          (cairo-scale (/ width img-width) (/ height img-height))
          (cairo-set-source-surface img 0 0))
    (cairo-surface-destroy img)))

(define (sdl-colorspace->cairo bytes-per-pixel)
  (case (* 8 bytes-per-pixel)
    ((8) CAIRO_FORMAT_A8)
    ((24) CAIRO_FORMAT_RGB24)
    ((32) CAIRO_FORMAT_ARGB32)
    (else CAIRO_FORMAT_ARGB32)))

(define (new-doodle #!key
                    (width 680)
                    (height 460)
                    (title "Doodle")
                    (background solid-black)
                    (fullscreen #f))

  (sdl-init SDL_INIT_EVERYTHING)

  (set! *s* (sdl-set-video-mode width height 0 (+ SDL_HWSURFACE
                                                  SDL_HWPALETTE
                                                  SDL_DOUBLEBUF
                                                  (if fullscreen
                                                      SDL_FULLSCREEN
                                                      0))))

  (set! *c-surface* (cairo-image-surface-create-for-data
              (sdl-surface-pixels *s*)
              (sdl-colorspace->cairo (sdl-pixel-format-bytes-per-pixel
                                      (sdl-surface-pixel-format *s*)))
              width
              height
              (sdl-surface-pitch *s*)))

  (set! *c* (cairo-create *c-surface*))

  (set! doodle-width width)
  (set! doodle-height height)

  (sdl-wm-set-caption title title)

  (current-background background)

  (if (string? background)
      (insert-image-as-background background)
      (apply cairo-set-source-rgba `(,*c* ,@background)))

  (doto *c*
        (cairo-rectangle 0 0 width height)
        (cairo-fill)
        (cairo-stroke)
        (cairo-paint))

  (sdl-flip *s*))

(define (clear-screen #!optional (color (current-background)))
(let ((width (cairo-image-surface-get-width *c-surface*))
      (height (cairo-image-surface-get-height *c-surface*)))
  (if (list? color)
      (apply cairo-set-source-rgba `(,*c* ,@color))
      (insert-image-as-background color))
  (doto *c*
        (cairo-rectangle 0 0 width height)
        (cairo-fill)
        (cairo-stroke))))

(define (show!)
  (cairo-surface-flush *c-surface*)
  (sdl-flip *s*))


;; Collision detection

;; sprites are very crude rectangles atm consisting of a name, x, y,
;; width and height in pixels
(define-record sprite name x y width height)
(define *sprites* '())

(define-record-printer (sprite s p)
  (fprintf p "#,(sprite ~s ~s ~s ~s ~s)"
           (sprite-name s)
           (sprite-x s)
           (sprite-y s)
           (sprite-width s)
           (sprite-height s)))

(define (collides? s ss)
  (define (inside? x y s)
     (and (< (sprite-x s) x (+ (sprite-x s) (sprite-width s)))
          (< (sprite-y s) y (+ (sprite-y s) (sprite-height s)))))

  (define (sprite->points s)
    `((,(sprite-x s) ,(sprite-y s))
      (,(+ (sprite-x s) (sprite-width s)) ,(sprite-y s))
      (,(sprite-x s) ,(+ (sprite-height s) (sprite-y s)))
      (,(+ (sprite-x s) (sprite-width s)) ,(+ (sprite-y s) (sprite-height s)))))

  (define (overlap s1 s2)
    (or (any (lambda (xy)
               (inside? (first xy) (second xy) s1))
             (sprite->points s2))
        (any (lambda (xy)
               (inside? (first xy) (second xy) s2))
             (sprite->points s1))))

  (let ((cs (map (cut sprite-name <>)
                  (filter (lambda (s2)
                            (overlap s s2))
                          ss))))
    (and (not (null? cs)) cs)))

(define (check-for-collisions)
  (let loop ((s (map cdr *sprites*))
             (cols '()))
    (cond ((null? s) cols)
          ((collides? (car s) (remove (cut equal? (car s) <>) (map cdr  *sprites*)))
           => (lambda (o) (loop (cdr s) (cons (list (sprite-name (car s)) o) cols))))
          (else (loop (cdr s) cols)))))

(define (remove-sprite! s-name)
  (alist-delete! s-name *sprites* equal?))

(define (update-sprite! s)
  (set! *sprites* (alist-update! (sprite-name s) s *sprites*)))

(define add-sprite! update-sprite!)

;; blitting tiles in

(define *resources* '())

(define-record img-res name file surface w h x-offset y-offset scale-factor)
(define-record-printer (img-res i out)
  (fprintf out "#,(img-res ~a ~s ~ax~a px (~ax~a) x ~a"
           (img-res-name i)
           (img-res-file i)
           (img-res-w i)
           (img-res-h i)
           (img-res-x-offset i)
           (img-res-y-offset i)
           (img-res-scale-factor i)))


(define (define-resource name type file . data)
  (when (not (file-exists? file))
    (error "Resource does not exist " file))
  (match type
         ('#:image
          (let* ((s (cairo-image-surface-create-from-png file))
                 (w (cairo-image-surface-get-width s))
                 (h (cairo-image-surface-get-height s))
                 (offset? (and (not (null? data))
                              (>= (length data) 2)))
                 (x-off (if offset? (car data) 0))
                 (y-off (if offset? (cadr data) 0))
                 (scale-factor (and (= (length data) 3)
                                    (caddr data))))
            (set! *resources*
                  (alist-update! name (make-img-res name file s w h x-off y-off scale-factor)
                                *resources*))))
         ('#:tileset
          (when (or (null? data)
                    (not (= (length data) 2)))
                (error "Tileset needs tile-size and list of tiles but got " data))
          (let* ((ts (cairo-image-surface-create-from-png file))
                 (w (cairo-image-surface-get-width ts))
                 (h (cairo-image-surface-get-height ts))
                 (tile-size
                  (if (number? (car data))
                      (car data)
                      (error "Tile-set parameter needs to be a number")))
                 (tiles (if (list? (cadr data))
                            (cadr data)
                            (error "Second data parameter must be a list of tiles"))))
            (for-each
             (lambda (t)
               (if (and (list t)
                        (= (length t) 2))
                   (let* ((tile-name (car t))
                          (tile-number (cadr t))
                          (tile-x (modulo (* tile-number tile-size) w))
                          (tile-y (* tile-size (quotient (* tile-size tile-number) w)))
                          (tile-img
                           (cairo-surface-create-for-rectangle ts tile-x tile-y tile-size tile-size)))
                     (set! *resources*
                           (alist-update! (car t) (make-img-res tile-name file tile-img tile-size tile-size 0 0 #f)
                                          *resources*)))
                   (error "Malformed tile information entry " t)))
             tiles)))
         (else (error "Unkown resource type " type))))

(define (blit-image name x y #!key (rotation 0))
  (let ((img (alist-ref name *resources* equal?)))
    (unless img
      (error "No resource found with this name " name))
    (let* ((scale (img-res-scale-factor img))
           (scale (if scale scale 1))
           (h (img-res-h img))
           (w (img-res-w img))
           (t (/ (- 1 scale) 2))
           (x (+ x (* t w)
                 (img-res-x-offset img)))
           (y (+ y (* t h)
                 (img-res-y-offset img))))
      (cairo-save *c*)
      (if (zero? rotation)
              (cairo-translate *c* x y)
              (doto *c*
                    (cairo-translate (+ (/ w 2) x)
                                     (+ (/ h 2) y))
                    (cairo-rotate (* (/ cairo-pi 180) rotation))
                    (cairo-translate (- (/ w 2)) (- (/ h 2)))))
      (doto *c*
            (cairo-scale scale scale)
            (cairo-set-source-surface (img-res-surface img) 0 0)
            (cairo-mask-surface (img-res-surface img) 0 0)
            (cairo-restore)))))

;; Event stuff

(define (translate-mouse-event type event)
(let ((x (sdl-event-x event))
      (y (sdl-event-y event)))
  (if (equal? type SDL_MOUSEMOTION)
      (list 'mouse 'moved x y)
      (let ((b (sdl-event-button event)))
        (list 'mouse
              (if (equal? type SDL_MOUSEBUTTONDOWN)
                  'pressed 'released)
              x y b)))))

(define (translate-key-event type event)
  (let ((k (sdl-event-sym event)))
    (list 'key
     (if (equal? type SDL_KEYUP)
         'released 'pressed)
     (cond ((equal? k SDLK_UP)
            'up)
           ((equal? k SDLK_DOWN)
            'down)
           ((equal? k SDLK_LEFT)
            'left)
           ((equal? k SDLK_RIGHT)
            'right)
           ((integer->char k)
            => identity)
           (else 'unknown)))))

(define (translate-events event escape)
  (if (not event)
      #f
      (let ((t (sdl-event-type event)))
        (cond ((equal? t SDL_QUIT)
               (escape 'quit))
              ((equal? t SDL_VIDEOEXPOSE)
               '(redraw))
              ((or (equal? t SDL_MOUSEBUTTONUP)
                   (equal? t SDL_MOUSEBUTTONDOWN)
                   (equal? t SDL_MOUSEMOTION))
               (translate-mouse-event t event))
              ((or (equal? t SDL_KEYDOWN)
                   (equal? t SDL_KEYUP))
               (translate-key-event t event))
              (else (list 'unknown event))))))

(define (collect-events)
  (let pump ((events '()))
    (let ((event (make-sdl-event)))
      (if (sdl-poll-event! event)
          (pump (cons event events))
          (reverse events)))))

(define (event-handler #!optional minimum-wait)
  (lambda ()
    (let ((last (current-milliseconds)))
      (call-with-current-continuation
       (lambda (escape)
         (let loop ()
           (let* ((now (current-milliseconds))
                  (dt (min (/ 1 30) (/ (- now last)
                                       1000))))
             ((world-changes)
              (map (cut translate-events <> escape)
                   (collect-events))
              dt
              escape)
             (show!)
             (set! last now)
             (when (< dt minimum-wait)
               (thread-sleep! (- minimum-wait dt)))
             (loop)))))
      ((world-ends))
      (sdl-quit))))

(define (run-event-loop #!key
                        (run-in-background #f)
                        (minimum-wait 0))
  ((world-inits))
  (sdl-flip *s*)
  (if run-in-background
      (thread-start!
       (make-thread (event-handler minimum-wait) "doodle-event-loop"))
      (thread-join!
       (thread-start!
        (make-thread (event-handler minimum-wait) "doodle-event-loop"))))))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.