aboutsummaryrefslogtreecommitdiffhomepage
path: root/wheelwork.lisp
blob: 42dd830cd0f6e4772e0b7e5d64358a87c60627a3 (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
;;;; wheelwork.lisp

(in-package #:wheelwork)

(defvar *application* nil
  "current application")

(defclass/std unit ()
  ((cached-model :a)
   (container :with :a)
   (width height :with :std 1.0)
   (rotation x y :with :std 0.0)
   (opacity :std 1.0 :doc "0.0 indicates it will not be rendred.")))

(defmethod (setf closer-mop:slot-value-using-class) :after
    (newval class (unit unit) slot)
  (when (member (closer-mop:slot-definition-name slot)
                '(scale-y scale-x rotation tx ty))
    (setf (cached-model unit) nil)))

(defclass/std container ()
  ((units :with :a))
  (:documentation "Just a list of units. Made into a class so that transformation affine transformations methods can be specialzied on whole groups of units"))

(defun add-unit (container unit)
  "Adds a unit to the end of a container (thus affecting render
order). Makes sure to remove the unit from its current container if necessary."
  (when (unit-container unit)
    (remove-unit unit))
  (setf (container-units container)
        (nconc (container-units container)
               (list unit)))
  unit)

(defun remove-unit (unit)
  "Removes a unit from its container. Returns T if the unit actually was removed."
  (when (unit-container unit)
    (setf
     (container-units (unit-container unit)) (delete unit (container-units (unit-container units)))
     (unit-container unit) nil)
    t))
          
(defclass/std application (container)
  ((title :with :std "Wheelwork App")
   (asset-root :ri :std #P"./" :doc "Directory under which assets are stored.")
   (asset-classifiers
    :std '(("png" texture))
    :doc "ALIST of (EXT CLASS). EXT is a string, file estension. CLASS is a symbol, class name.")
   (assets :with :a :std (make-hash-table :test 'equal)
           :doc "maps asset names to asset instances.")
   (scale :with :a :std 1.0)
   (width height :with :std 800)
   (projection :with :a :doc "The projection matrix for the scene. Orthographic by default.")
   (window :with :a)
   (refocus-on-mousedown-p :std t)
   (focus last-motion-target :with :a)
   (frame-wait :std (/ 1000 30) :doc "Frames Per Second" :a)))

(defun can-set-projection-p (app)
  (and (slot-boundp app 'width)
       (slot-boundp app 'height)
       (slot-boundp app 'scale)))

(defun set-projection (app)
  (when (can-set-projection-p app)
    (with-slots (projection scale width height) app 
      ;; set projection matrix
      (setf projection (mat:mortho 0.0 (/ width scale) 0 (/ height scale) -1.0 1.0)))))

(defmethod initialize-instance :after ((app application) &key)
  (set-projection app))

(defmethod (setf closer-mop:slot-value-using-class) :after
    (new-value class (app application) slot)
  (when (member (closer-mop:slot-definition-name slot)
                '(scale width height))
    (set-projection app)))

(defgeneric boot (app)
  (:documentation "Specialized for each subclass of
  APPLICATION. Responsble for setting the app up once the system
  resoruces are avaialble.")
  (:method ((app application)) nil))

(defgeneric cleanup (thing)
  (:documentation "Clean up applications, textures, and so on.")
  (:method ((any t)) nil))

(defmethod cleanup ((app application))
  (loop for asset being the hash-value of (application-assets app)
        do (cleanup asset))
  (call-next-method))

(defmethod cleanup ((container container))
  (dolist (u (container-units container))
    (cleanup u)))

(defun start (app &key (x :centered) (y :centered))
  (sdl2:with-init (:everything)
    (sdl2:with-window (window
                       :flags '(:shown :opengl)
                       :title (application-title app)
                       :w (application-width app)
                       :h (application-height app)
                       :x x :y y)
      (setf (application-window app) window)
      (sdl2:with-gl-context (ctx window)
        (sdl2:gl-make-current window ctx)
        (gl:viewport 0 0 (application-width app) (application-height app))
        (let ((*application* app)) 
          (unwind-protect
               (progn 
                 (boot app)
                 (eventloop app))
            (cleanup app)))))))

(defvar *frame-time* nil
  "Bound and available once per frame. The result of GET-UNIVERSAL-TIME.")

(defgeneric render (thing))
(defmethod render ((app application))
  (gl:clear-color 0.0 0.0 0.0 1.0)
  (gl:clear :depth-buffer-bit :color-buffer-bit)
  (dolist (thing (container-units app))
    (render thing))
  (sdl2:gl-swap-window (application-window app)))

(defun eventloop (app)
  (let ((next-frame-time
          (get-universal-time))
        (*frame-time*
          (get-universal-time))) 
    (sdl2:with-event-loop (:method :poll)
      (:idle ()
             (when (<= next-frame-time (setf *frame-time* (get-universal-time)))
               (setf next-frame-time (+ *frame-time* (frame-wait app)))
               (render app)))
      (:quit () t))))

(defgeneric translate-by (thing dx dy))
(defgeneric rotate-by (thing radians))
(defgeneric scale-by (thing sx sy))
(defgeneric pixel-width (thing))
(defgeneric (setf pixel-width) (newval thing))
(defgeneric pixel-height (thing))
(defgeneric (setf pixel-height) (newval thing))

(defgeneric visible-pixel-at-p (object x y)
  (:documentation "returns T if the visible pixel at screen
  coordintaes x and y belogns to object. Used for event handling."))

(defgeneric model-matrix (thing)
  (:documentation "Returns the model matrix"))


(defmethod model-matrix ((u unit))
  (or (cached-model u)
      (setf (cached-model u)
            (let ((m (mat:meye 4)))
              (mat:nmtranslate m (vec:vec (unit-x u) (unit-y u) 0.0))

              (mat:nmtranslate m (vec:v* 0.5 (vec:vec (unit-width u) (unit-height u) 0.0)))
              (mat:nmrotate  m vec:+vz+ (unit-rotation u))
              (mat:nmtranslate m (vec:v* -0.5 (vec:vec (unit-width u) (unit-height u) 0.0)))
              
              (mat:nmscale m (vec:vec (unit-width u) (unit-height u) 1.0))
              m))))

(defgeneric ensure-loaded (asset)
  (:documentation "Ensures that the asset is loaded into memory and ready for use. Returns the asset."))

(defclass/std asset ()
  ((path :with :ri :std (error "An asset requires a path"))
   (loadedp :with :a)))

(defmethod cleanup :around ((asset asset))
  (when (asset-loadedp asset)
    (call-next-method))
  (setf (asset-loadedp asset) nil))

(defmethod ensure-loaded :around ((thing asset))
  (unless (asset-loadedp thing) 
    (call-next-method)
    (setf (asset-loadedp thing) t))
  thing) 

(defclass/std texture (asset)
  ((width height id mipmap :with :r)
   (internal-format image-format :ri :with :std :rgba)
   (wrap-s wrap-t :ri :with :std :repeat)
   (min-filter mag-filter :ri :with :std :nearest)))

(defmethod cleanup ((texture texture))
  (gl:delete-texture (texture-id texture)))

(defmethod ensure-loaded ((texture texture))
  (with-slots
        (width height id wrap-s wrap-t min-filter mag-filter internal-format image-format)
      texture 
    (pngload:with-png-in-static-vector (png (asset-path texture) :flip-y t)
      (setf width (pngload:width png)
            height (pngload:height png)
            id (gl:gen-texture))
      (gl:bind-texture :texture-2d id)
      (gl:tex-parameter :texture-2d :texture-wrap-s wrap-s)
      (gl:tex-parameter :texture-2d :texture-wrap-t wrap-t)
      (gl:tex-parameter :texture-2d :texture-min-filter min-filter)
      (gl:tex-parameter :texture-2d :texture-min-filter mag-filter)
      (gl:tex-image-2d :texture-2d
                       0
                       internal-format
                       width
                       height
                       0
                       image-format
                       :unsigned-byte
                       (pngload:data png)))))

(defclass/std bitmap (unit)
  ((texture :ri :std (error "A bitmap requires a texture."))
   (vao shader :with :r :static)))

(defmethod cleanup ((bitmap bitmap))
  (with-slots (vao shader) bitmap
    (when vao
      (gl:delete-vertex-arrays (list vao)))
    (when shader
      (gl:delete-program shader))
    (setf vao nil
          shader nil)))

(defun shader-by-type (type)
  (case type
    (:vertex :vertex-shader)
    (:geometry :geometry-shader)
    (:fragment :fragment-shader)))

(defun gl-shader (type stage)
  (let ((shader (gl:create-shader type)))
    (gl:shader-source shader (varjo:glsl-code stage))
    (gl:compile-shader shader)
    (unless (gl:get-shader shader :compile-status)
      (error "failed to compile ~a shader:~%~a~%"
             type (gl:get-shader-info-log shader)))
    shader))

(defun create-shader (&rest sources)
  (let* ((stages
          (varjo:rolling-translate
           (mapcar (lambda (source)
                     (destructuring-bind (type inputs uniforms code) source
                       (varjo:make-stage type inputs uniforms '(:330) code)))
                   sources)))
         (shaders
          (loop
             :for stage :in stages
             :for source :in sources
             :collect (gl-shader (shader-by-type (car source))
                                 stage)))
         
         (program (gl:create-program)))
    (dolist (shader shaders) (gl:attach-shader program shader))
    (gl:link-program program)
    (unless (gl:get-program program :link-status)
      (error "failed to link program: ~%~a~%"
             (gl:get-program-info-log program)))
    (dolist (shader shaders)
      (gl:detach-shader program shader)
      (gl:delete-shader shader))
    program))


(defun gl-array (type &rest contents)
  (let ((array (gl:alloc-gl-array type (length contents))))
    (dotimes (i (length contents) array)
      (setf (gl:glaref array i) (elt contents i)))))

(defmacro with-gl-array ((var type &rest contents) &body body)
  `(let ((,var (gl-array ,type ,@contents))) 
     (unwind-protect (progn ,@body)
       (gl:free-gl-array ,var))))


(define-symbol-macro +float-size+
    (cffi:foreign-type-size :float))

(defmethod initialize-instance :after ((bitmap bitmap) &key)
  (with-slots (vao shader width height texture) bitmap
    (setf texture (ensure-loaded texture)
          height (texture-height texture)
          width (texture-width texture))
    (unless shader
      (setf shader
            (create-shader
             '(:vertex
               ((vert :vec2))
               ((transform :mat4))
               ((values
                 (* transform (vari:vec4 vert 0.0 1.0))
                 vert))) ;color
             '(:fragment
               ((tc :vec2))
               ((tex :sampler-2d))
               ((vari:texture tex tc)))))
      (gl:program-uniformi
       shader
       (gl:get-uniform-location shader "TEX")
       0))
    (unless vao
      (setf vao (gl:gen-vertex-array))
      (gl:bind-vertex-array vao)
      (let ((vbo (gl:gen-buffer)))
        (with-gl-array (verts :float
                              0.0 1.0
                              1.0 0.0
                              0.0 0.0
                              
                              0.0 1.0
                              1.0 1.0
                              1.0 0.0)
          (gl:bind-buffer :array-buffer vbo)
          (gl:buffer-data :array-buffer :static-draw verts)))
      (gl:enable-vertex-attrib-array 0)
      (gl:vertex-attrib-pointer 0 2 :float 0 (* +float-size+ 2) 0)
      (gl:bind-buffer :array-buffer 0)
      (gl:bind-vertex-array 0))))

(defmethod render ((bitmap bitmap))
  (with-slots (texture vao shader) bitmap
    (gl:active-texture 0)
    (gl:bind-texture :texture-2d (texture-id texture))
    (gl:use-program shader)
    (gl:program-uniform-matrix-4fv
     shader
     (gl:get-uniform-location shader "TRANSFORM")
     (mat:marr (mat:m* (application-projection *application*) (model-matrix bitmap))))
    (gl:bind-vertex-array vao)    
    (gl:draw-arrays :triangles 0 6)
    (gl:bind-vertex-array 0)))


(defun asset-class-for (asset-id &optional (app *application*))
  "Given an asset-id (see GET-ASSET), retrieve the symbol name of a
the class that will be used to instantiate the asset object. That
class should be a subclass of ASSET.  Additional clases can be added
to the application's ASSET-CLASSIFIERS association list."
  (second (assoc (pathname-type asset-id) (asset-classifiers app) :test #'string-equal)))

(defun get-asset (asset-id &optional (app *application*))
  "ASSET-ID is a pathname namestring relative to the application's
ASSET-ROOT. GET-ASSET retrieves an already-available asset from the
application's ASSETS table, or, if not available, loads the asset from
disk."
  (or (gethash asset-id (application-assets app))
      (setf (gethash asset-id (application-assets app))
            (ensure-loaded
             (make-instance (asset-class-for asset-id)
                            :path (uiop:merge-pathnames* asset-id (asset-root app)))))))

;; (defun get-focus (&optional (app *application*))
;;   (or (application-focus app)
;;       (display-root app)))

;; (defun get-projection (&optional (app *application*))
;;   (application-projection app))

;; (defun application-width (&optional (app *application*))
;;   (multiple-value-bind (w h) (sdl2:get-window-size (application-window app))
;;     (declare (ignore h))
;;     w))

;; (defun application-height (&optional (app *application*))
;;   (multiple-value-bind (w h) (sdl2:get-window-size (application-window app))
;;     (declare (ignore w))
;;     h))


;; (defclass/std event-handler ()
;;   ((event-type handler-function :ri)))

;; (defclass/std listener ()
;;   ((keydown keyup mousedown mouseup mousemove mousewheel focus blur perframe
;;             :r :with :type event-handler)
;;    (keydown-table
;;     keyup-table
;;     mousedown-table
;;     mouseup-table
;;     mousemove-table
;;     mousewheel-table
;;     focus-table
;;     blur-table
;;     perframe-table
;;     :static
;;     :std (make-hash-table)
;;     :doc "Keyed by DISPLAY-UNIT instance, holds an EVENT-HANDLER if handler is defined for unit."))
;;   (:documentation "Event handlers per object. The static hash tables
;;   are keyed by UNIT and hold Event-Handler instances."))