]> git.jsancho.org Git - gacela.git/blob - src/video.scm
Using guile-figl
[gacela.git] / src / video.scm
1 ;;; Gacela, a GNU Guile extension for fast games development
2 ;;; Copyright (C) 2009 by Javier Sancho Fernandez <jsf at jsancho dot org>
3 ;;;
4 ;;; This program is free software: you can redistribute it and/or modify
5 ;;; it under the terms of the GNU General Public License as published by
6 ;;; the Free Software Foundation, either version 3 of the License, or
7 ;;; (at your option) any later version.
8 ;;;
9 ;;; This program is distributed in the hope that it will be useful,
10 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
11 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 ;;; GNU General Public License for more details.
13 ;;;
14 ;;; You should have received a copy of the GNU General Public License
15 ;;; along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17
18 (define-module (gacela video)
19   #:use-module (gacela sdl)
20 ;  #:use-module (gacela gl)
21   #:use-module (figl gl)
22   #:use-module (figl glx)
23   #:use-module (figl glu)
24   #:use-module (gacela ftgl)
25   #:use-module (gacela math)
26   #:use-module (gacela utils)
27   #:use-module (ice-9 optargs)
28   #:use-module (ice-9 receive)
29   #:use-module (srfi srfi-9)
30   #:use-module (system foreign)
31   #:export (init-video
32             get-screen-height
33             get-screen-width
34             get-screen-bpp
35             set-screen-bpp!
36             resize-screen
37             quit-video
38             clear-screen
39             flip-screen
40             set-screen-title!
41             get-screen-title
42             set-2d-mode
43             set-3d-mode
44             3d-mode?
45             get-frames-per-second
46             set-frames-per-second!
47             get-fullscreen
48             set-fullscreen!
49             init-frame-time
50             get-frame-time
51             delay-frame
52             get-current-color
53             set-current-color
54             with-color
55             with-textures
56             draw
57             load-texture
58             load-texture-without-cache
59             get-texture-properties
60             draw-texture
61             draw-line
62             draw-quad
63             draw-rectangle
64             draw-square
65             draw-cube
66             translate
67             rotate
68             to-origin
69             add-light
70             set-camera
71             camera-look
72             load-font
73             load-font-without-texture
74             render-text)
75   #:re-export (with-gl-push-matrix))
76
77
78
79 ;;; Screen
80
81 (define screen #f)
82 (define flags 0)
83
84 (define* (init-video width height bpp #:key (mode '2d) (title "") (fps 20) (fullscreen 'off))
85   (SDL_Init SDL_INIT_VIDEO)
86   (let ((info (SDL_GetVideoInfo)))
87     (SDL_GL_SetAttribute SDL_GL_DOUBLEBUFFER 1)
88     (set! flags (+ SDL_OPENGL SDL_GL_DOUBLEBUFFER SDL_HWPALETTE SDL_RESIZABLE
89                    (if (= (assoc-ref info 'hw_available) 0) SDL_SWSURFACE SDL_HWSURFACE)
90                    (if (= (assoc-ref info 'blit_hw) 0) 0 SDL_HWACCEL)
91                    (if (eq? fullscreen 'on) SDL_FULLSCREEN 0)))
92     (set! screen (SDL_SetVideoMode width height bpp flags))
93     (set-screen-title! title)
94     (set-frames-per-second! fps)
95     (set-fullscreen! fullscreen #f)
96     (init-gl)
97     (if (eq? mode '3d) (set-3d-mode) (set-2d-mode))))
98
99 (define (get-screen-height)
100   (surface-h screen))
101
102 (define (get-screen-width)
103   (surface-w screen))
104
105 (define (get-screen-bpp)
106   (* (surface-format-BytesPerPixel screen) 8))
107
108 (define (set-screen-bpp! bpp)
109   (cond (screen
110          (set! screen (SDL_SetVideoMode (get-screen-width) (get-screen-height) (get-screen-bpp) flags)))))
111
112 (define (resize-screen width height)
113   (cond (screen
114          (set! screen (SDL_SetVideoMode width height (get-screen-bpp) flags))
115          (resize-screen-GL width height))))
116
117 (define (quit-video)
118   (cond (screen
119          (SDL_FreeSurface screen)
120          (set! screen #f)
121          (SDL_Quit))))
122
123 (define (clear-screen)
124   (gl-clear (clear-buffer-mask color-buffer depth-buffer)))
125
126 (define (flip-screen)
127   (SDL_GL_SwapBuffers))
128
129
130 (define screen-title "")
131
132 (define (set-screen-title! title)
133   (set! screen-title title)
134   (SDL_WM_SetCaption title ""))
135
136 (define (get-screen-title)
137   screen-title)
138
139
140 (define mode '2d)
141
142 (define (set-2d-mode)
143   (set! mode '2d)
144   (gl-disable (enable-cap depth-test))
145   (resize-screen-GL (get-screen-width) (get-screen-height)))
146
147 (define (set-3d-mode)
148   (set! mode '3d)
149   (set-gl-clear-depth 1)
150   (gl-enable (enable-cap depth-test))
151   (set-gl-depth-function (depth-function lequal))
152   (resize-screen-GL (get-screen-width) (get-screen-height)))
153
154 (define (3d-mode?)
155   (eq? mode '3d))
156
157
158 (define fullscreen 'off)
159
160 (define* (set-fullscreen! fs #:optional (toggle #t))
161   (cond ((or (and (eq? fullscreen 'on) (eq? fs 'off))
162              (and (eq? fullscreen 'off) (eq? fs 'on)))
163          (set! fullscreen fs)
164          (cond (toggle
165                 (SDL_WM_ToggleFullScreen screen))))))
166
167 (define (get-fullscreen)
168   fullscreen)
169
170
171 (define (init-gl)
172   (set-gl-shade-model (shading-model smooth))
173   (set-gl-clear-color 0 0 0 0)
174   (gl-enable (enable-cap blend))
175   (set-gl-blend-function (blending-factor-dest src-alpha) (blending-factor-dest one-minus-src-alpha))
176   (set-gl-hint (hint-target perspective-correction-hint) (hint-mode nicest)))
177
178 (define (resize-screen-GL width height)
179   (gl-viewport 0 0 width height)
180   (set-gl-matrix-mode (matrix-mode projection))
181   (gl-load-identity)
182   (cond ((3d-mode?)
183          (let ((ratio (if (= height 0) width (/ width height))))
184            (glu-perspective 45 ratio 0.1 100)))
185         (else
186          (let* ((w (/ width 2)) (h (/ height 2)))
187            (gl-ortho (- w) w (- h) h 0 1))))
188   (set-gl-matrix-mode (matrix-mode modelview))
189   (gl-load-identity))
190
191
192 ;;; Frames per second
193
194 (define time 0)
195 (define frames-per-second 20)
196 (define time-per-frame 50)   ;in ms
197
198 (define (get-frames-per-second)
199   frames-per-second)
200
201 (define (set-frames-per-second! fps)
202   (set! frames-per-second fps)
203   (set! time-per-frame (/ 1000.0 fps)))
204
205 (define (init-frame-time)
206   (set! time (SDL_GetTicks)))
207
208 (define (get-frame-time)
209   time)
210
211 (define (delay-frame)
212   (let ((frame-time (- (SDL_GetTicks) time)))
213     (cond ((< frame-time time-per-frame)
214            (SDL_Delay (- time-per-frame frame-time))))))
215
216
217 ;;; Textures
218
219 (define-record-type <texture>
220   (texture id width height)
221   texture?
222   (id texture-id)
223   (width texture-width set-texture-width)
224   (height texture-height set-texture-height))
225
226 (define-macro (with-textures . code)
227   `(let ((result #f))
228      (gl-enable (oes-framebuffer-object texture-2d))
229      (set! result (begin ,@code))
230      (gl-disable (oes-framebuffer-object texture-2d))
231      result))
232
233 (define (load-image filename)
234   (let ((image (IMG_Load filename)))
235     (cond (image
236            (SDL_DisplayFormatAlpha image)))))
237   
238 (define (load-image-for-texture filename)
239   (let ((image (load-image filename)))
240     (cond (image
241            (let* ((width (surface-w image)) (height (surface-h image))
242                   (power-2 (nearest-power-of-two (min width height)))
243                   (resized-image #f))
244              (cond ((and (= width power-2) (= height power-2)) (values image width height))
245                    (else (set! resized-image (resize-surface image power-2 power-2))
246                          (if resized-image (values resized-image width height))))))
247           (else
248            (values #f 0 0)))))
249
250 (define (resize-surface surface width height)
251   (let ((old-width (surface-w surface)) (old-height (surface-h surface)))
252     (cond ((and (= width old-width) (= height old-height)) surface)
253           (else (let ((zoomx (/ (+ width 0.5) old-width)) (zoomy (/ (+ height 0.5) old-height)))
254                (zoomSurface surface zoomx zoomy 0))))))
255
256 (define* (load-texture-without-cache filename #:key (min-filter (texture-min-filter linear)) (mag-filter (texture-mag-filter linear)))
257   (with-textures
258    (receive
259     (image real-w real-h) (load-image-for-texture filename)
260     (cond (image
261            (let ((width (surface-w image)) (height (surface-h image))
262                  (byteorder (if (= SDL_BYTEORDER SDL_LIL_ENDIAN)
263                                 (if (= (surface-format-BytesPerPixel image) 3) (ext-bgra bgr-ext) (ext-bgra bgra-ext))
264                                 (if (= (surface-format-BytesPerPixel image) 3) (pixel-format rgb) (pixel-format rgba))))
265                  (texture-id (gl-generate-texture))
266                  (image-pointer (make-pointer
267                                  (if (> (surface-pixels image) 0)
268                                      (surface-pixels image)
269                                      (+ ($expt 2 32) (surface-pixels image))))))
270
271              (gl-bind-texture (oes-framebuffer-object texture-2d) texture-id)
272              (set-gl-texture-image (oes-framebuffer-object texture-2d) 0 4 0 byteorder (data-type unsigned-byte) image-pointer width height)
273              (set-gl-texture-parameter (oes-framebuffer-object texture-2d) (texture-parameter-name texture-min-filter) min-filter)
274              (set-gl-texture-parameter (oes-framebuffer-object texture-2d) (texture-parameter-name texture-mag-filter) mag-filter)
275              (texture texture-id real-w real-h)))))))
276
277 (define load-texture (use-cache-with load-texture-without-cache))
278
279       
280 ;;; Drawing
281
282 (define current-color '(1 1 1 1))
283
284 (define (get-current-color)
285   current-color)
286
287 (define* (set-current-color red green blue #:optional (alpha 1))
288   (set! current-color (list red green blue alpha))
289   (gl-color red green blue alpha))
290
291 (define-macro (with-color color . code)
292   `(cond (,color
293           (let ((original-color (get-current-color))
294                 (result #f))
295             (apply set-current-color ,color)
296             (set! result (begin ,@code))
297             (apply set-current-color original-color)
298             result))
299          (else (begin ,@code))))
300
301 (define (draw . vertexes)
302   (gl-begin
303    (let ((number-of-points (length vertexes)))
304      (cond ((= number-of-points 2) (begin-mode lines))
305            ((= number-of-points 3) (begin-mode triangles))
306            ((= number-of-points 4) (begin-mode quads))
307            ((> number-of-points 4) (begin-mode polygon))))
308    (draw-vertexes vertexes)))
309
310 (define (draw-vertexes vertexes)
311   (cond ((not (null? vertexes))
312          (apply draw-vertex (if (list? (caar vertexes)) (car vertexes) (list (car vertexes))))
313          (draw-vertexes (cdr vertexes)))))
314
315 (define* (draw-vertex vertex #:key texture-coord)
316   (cond (texture-coord (apply gl-texture-coordinates texture-coord)))
317   (apply gl-vertex vertex))
318
319 (define* (draw-texture texture #:key (zoom 1) (sprite '((0 0) (1 1))))
320   (cond (texture
321          (let ((width (texture-width texture))
322                (height (texture-height texture)))
323            (draw-rectangle (* zoom width (- (caadr sprite) (caar sprite)))
324                            (* zoom height (- (cadadr sprite) (cadar sprite)))
325                            #:texture texture
326                            #:texture-coord sprite)))))
327
328 (define* (draw-line length)
329   (let ((l (/ length 2)))
330     (draw (list 0 l) (list 0 (- l)))))
331
332 (define (draw-circle radius)
333   (gl-begin
334    (begin-mode polygon)
335    (do ((i 0 (1+ i)))
336        ((>= i 360))
337      (let ((a (degrees-to-radians i)))
338        (draw-vertex (list (* radius (cos a)) (* radius (sin a))))))))
339
340 (define* (draw-quad v1 v2 v3 v4 #:key texture (texture-coord '((0 0) (1 1))))
341   (cond (texture
342          (with-textures
343           (gl-bind-texture (oes-framebuffer-object texture-2d) (texture-id texture))
344           (draw (list v1 #:texture-coord (car texture-coord))
345                 (list v2 #:texture-coord (list (caadr texture-coord) (cadar texture-coord)))
346                 (list v3 #:texture-coord (cadr texture-coord))
347                 (list v4 #:texture-coord (list (caar texture-coord) (cadadr texture-coord))))))
348         (else
349          (draw v1 v2 v3 v4))))
350
351 (define* (draw-rectangle width height #:key texture texture-coord)
352   (let ((w (/ width 2)) (h (/ height 2)))
353     (draw-quad (list (- w) h 0)
354                (list w h 0)
355                (list w (- h) 0)
356                (list (- w) (- h) 0)
357                #:texture texture
358                #:texture-coord texture-coord)))
359
360 (define* (draw-square size #:key texture)
361   (draw-rectangle size size #:texture texture))
362
363 (define* (draw-cube #:key (size 1)
364                    texture texture-1 texture-2 texture-3 texture-4 texture-5 texture-6
365                    color-1 color-2 color-3 color-4 color-5 color-6)
366   (let ((-size (- size)))
367     (with-textures
368      (gl-normal 0 0 1)
369      (with-color color-1 (draw-quad (list -size size size) (list size size size) (list size -size size) (list -size -size size) #:texture (or texture-1 texture)))
370      (gl-normal 0 0 -1)
371      (with-color color-2 (draw-quad (list -size -size -size) (list size -size -size) (list size size -size) (list -size size -size) #:texture (or texture-2 texture)))
372      (gl-normal 0 1 0)
373      (with-color color-3 (draw-quad (list size size size) (list -size size size) (list -size size -size) (list size size -size) #:texture (or texture-3 texture)))
374      (gl-normal 0 -1 0)
375      (with-color color-4 (draw-quad (list -size -size size) (list size -size size) (list size -size -size) (list -size -size -size) #:texture (or texture-4 texture)))
376      (gl-normal 1 0 0)
377      (with-color color-5 (draw-quad (list size -size -size) (list size -size size) (list size size size) (list size size -size) #:texture (or texture-5 texture)))
378      (gl-normal -1 0 0)
379      (with-color color-6 (draw-quad (list -size -size size) (list -size -size -size) (list -size size -size) (list -size size size) #:texture (or texture-6 texture))))))
380
381 (define* (gtranslate x y #:optional (z 0))
382   (gl-translate x y z))
383
384 (define (grotate . rot)
385   (cond ((3d-mode?)
386          (apply 3d-rotate rot))
387         (else
388          (2d-rotate (car (last-pair rot))))))
389
390 (define (3d-rotate xrot yrot zrot)
391   (gl-rotate xrot 1 0 0)
392   (gl-rotate yrot 0 1 0)
393   (gl-rotate zrot 0 0 1))
394
395 (define (2d-rotate rot)
396   (gl-rotate rot 0 0 1))
397
398 (define (to-origin)
399   (gl-load-identity)
400   (cond ((3d-mode?) (camera-look))))
401
402
403 ;;; Lights
404
405 ;; (define* (add-light #:key light position ambient (id GL_LIGHT1) (turn-on t))
406 ;;   (init-lighting)
407 ;;   (and light (glLightfv id GL_DIFFUSE (car light) (cadr light) (caddr light) (cadddr light)))
408 ;;   (and light position (glLightfv GL_POSITION (car position) (cadr position) (caddr position) (cadddr position)))
409 ;;   (and ambient (glLightfv id GL_AMBIENT (car ambient) (cadr ambient) (caddr ambient) (cadddr ambient)))
410 ;;   (and turn-on (gl-enable id))
411 ;;   id)
412
413
414 ;;; Camera
415
416 (define camera-eye '(0 0 0))
417 (define camera-center '(0 0 -100))
418 (define camera-up '(0 1 0))
419
420 (define* (set-camera #:key eye center up)
421   (cond (eye (set! camera-eye eye)))
422   (cond (center (set! camera-center center)))
423   (cond (up (set! camera-up up))))
424
425 (define (camera-look)
426   (apply glu-look-at (append camera-eye camera-center camera-up)))
427
428
429 ;;; Text and fonts
430
431 (define* (load-font-without-cache font-file #:key (size 40) (encoding ft_encoding_unicode))
432   (let ((font (ftglCreateTextureFont font-file size)))
433     (ftglSetFontFaceSize font size 72)
434     (ftglSetFontCharMap font encoding)
435     font))
436
437 (define load-font (use-cache-with load-font-without-cache))
438
439 (define* (render-text text font #:key (size #f))
440   (cond (size
441          (cond ((not (= (ftglGetFontFaceSize font) size))
442                 (ftglSetFontFaceSize font size 72))))
443         ((not (= (ftglGetFontFaceSize font) (font-size font)))
444          (ftglSetFontFaceSize font (font-size font) 72)))
445   (ftglRenderFont font text FTGL_RENDER_ALL))
446
447
448 ;;; Meshes
449
450 (define mesh-type
451   (make-record-type "mesh" 
452                     '(draw translate turn rotate color inner-properties inner-property properties properties-set! property property-set!)
453                     (lambda (record port)
454                       (format port "#<mesh: ~a" (mesh-inner-property record 'type))
455                       (for-each (lambda (x) (format port " ~a" x))
456                                 (mesh-properties record))
457                       (display ">" port))))
458
459 (define mesh? (record-predicate mesh-type))
460
461 (define (make-mesh type proc)
462   (apply
463    (record-constructor mesh-type)
464    (let ((px 0) (py 0) (pz 0)
465          (ax 0) (ay 0) (az 0)
466          (rx 0) (ry 0) (rz 0)
467          (color #f)
468          (properties '()))
469      (let ((inner-properties
470             (lambda ()
471               `((type . ,type) (color . ,color)
472                 (x . ,px) (y . ,py) (z . ,pz)
473                 (ax . ,ax) (ay . ,ay) (az . ,az)
474                 (rx . ,rx) (ry . ,ry) (rz . ,rz)))))
475        (list
476         (lambda ()
477           "draw"
478           (with-gl-push-matrix
479            (grotate ax ay az)
480            (gtranslate px py pz)
481            (grotate rx ry rz)
482            (with-color color (proc properties))))
483         (lambda (x y z)
484           "translate"
485           (set! px (+ px x))
486           (set! py (+ py y))
487           (set! pz (+ pz z)))
488         (lambda (x y z)
489           "turn"
490           (set! ax (+ ax x))
491           (set! ay (+ ay y))
492           (set! az (+ az z)))
493         (lambda (x y z)
494           "rotate"
495           (set! rx (+ rx x))
496           (set! ry (+ ry y))
497           (set! rz (+ rz z)))
498         (lambda (c)
499           "color"
500           (set! color c))
501         (lambda ()
502           "inner-properties"
503           (inner-properties))
504         (lambda (prop-name)
505           "inner-property"
506           (assoc-ref (inner-properties) prop-name))
507         (lambda ()
508           "properties"
509           properties)
510         (lambda (new-properties)
511           "properties-set!"
512           (set! properties new-properties))
513         (lambda (prop-name)
514           "property"
515           (assoc-ref properties prop-name))
516         (lambda (prop-name value)
517           "property-set!"
518           (set! properties (assoc-set! properties prop-name value))))))))
519
520 (define (mesh-draw mesh)
521   (((record-accessor mesh-type 'draw) mesh)))
522
523 (define (mesh-inner-properties mesh)
524   (((record-accessor mesh-type 'inner-properties) mesh)))
525
526 (define (mesh-inner-property mesh prop-name)
527   (((record-accessor mesh-type 'inner-property) mesh) prop-name))
528
529 (define (mesh-properties mesh)
530   (((record-accessor mesh-type 'properties) mesh)))
531
532 (define (mesh-properties-set! mesh new-properties)
533   (((record-accessor mesh-type 'properties-set!) mesh) new-properties))
534
535 (define (mesh-property mesh prop-name)
536   (((record-accessor mesh-type 'property) mesh) prop-name))
537
538 (define (mesh-property-set! mesh prop-name value)
539   (((record-accessor mesh-type 'property-set!) mesh) prop-name value))
540
541 (define* (translate mesh x y #:optional (z 0))
542   (((record-accessor mesh-type 'translate) mesh) x y z)
543   mesh)
544
545 (define (turn mesh . params)
546   (apply ((record-accessor mesh-type 'turn) mesh)
547          (if (>= (length params) 3)
548              params
549              (list 0 0 (car params))))
550   mesh)
551
552 (define (rotate mesh . params)
553   (apply ((record-accessor mesh-type 'rotate) mesh)
554          (if (>= (length params) 3)
555              params
556              (list 0 0 (car params))))
557   mesh)
558
559 (define (color mesh c)
560   (((record-accessor mesh-type 'color) mesh) c)
561   mesh)
562
563
564 ;;; Advanced meshes
565
566 (define (mesh-join . meshes)
567   (make-mesh
568    'joined-meshes
569    (lambda (props)
570      (for-each (lambda (m) (with-gl-push-matrix (mesh-draw m))) meshes))))
571
572
573 ;;; Primitives
574
575 (define-macro (primitive header . body)
576   (let* ((type (car header))
577          (args (cdr header))
578          (list-args (names-arguments args)))
579     `(lambda* ,args
580        (let ((m (make-mesh
581                  ',type
582                  (lambda (props)
583                    (apply (lambda* ,(cons #:key list-args) ,@body)
584                           (list
585                            ,@(let get-params ((l list-args))
586                                (cond ((null? l) '())
587                                      (else
588                                       (cons (symbol->keyword (car l))
589                                             (cons `(assoc-ref props ',(car l))
590                                                   (get-params (cdr l)))))))))))))
591          (mesh-properties-set! m (list ,@(map (lambda (a) `(cons ',a ,a)) list-args)))
592          m))))
593
594 (define-macro (define-primitive header . body)
595   `(define ,(car header) (primitive ,header ,@body)))
596
597
598 ;;; Primitives definition
599
600 (define-primitive (square size #:key texture)
601   (draw-square size #:texture texture))
602
603 (define-primitive (rectangle width height #:key texture texture-coord)
604   (draw-rectangle width height #:texture texture #:texture-coord texture-coord))
605
606 (define-primitive (circle radius)
607   (draw-circle radius))
608
609 (define-primitive (picture filename #:key (min-filter (texture-min-filter linear)) (mag-filter (texture-mag-filter linear)) (zoom 1) (sprite '((0 0) (1 1))))
610   (draw-texture (load-texture filename #:min-filter min-filter #:mag-filter mag-filter) #:zoom zoom #:sprite sprite))
611
612
613 (module-map (lambda (sym var)
614               (if (not (eq? sym '%module-public-interface))
615                   (module-export! (current-module) (list sym))))
616             (current-module))