forked from Shirakumo/trial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
toolkit.lisp
1433 lines (1260 loc) · 51.4 KB
/
toolkit.lisp
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
(in-package #:org.shirakumo.fraf.trial)
(defvar *native-array-element-types*
(remove T (remove-duplicates
(mapcar #'upgraded-array-element-type
(append '(fixnum short-float single-float double-float long-float)
(loop for i from 1 to 64 collect `(signed-byte ,i))
(loop for i from 1 to 64 collect `(unsigned-byte ,i))
'(base-char extended-char character)))
:test #'equal)))
(defmacro define-global (name value)
`(eval-when (:compile-toplevel :load-toplevel :execute)
#+sbcl (sb-ext:defglobal ,name ,value)
#-sbcl (defvar ,name ,value)
(setf ,name ,value)))
(define-global +app-vendor+ "shirakumo")
(define-global +app-system+ "trial")
(define-global +main+ NIL)
(defconstant F-PI (float PI 0f0))
(defconstant F-2PI (float (* 2 PI) 0f0))
(defconstant F-PI/2 (float (* 0.5 PI) 0f0))
(defun git-repo-commit (dir)
(flet ((file (path)
(pathname-utils:merge-pathnames* path dir))
(trim (string)
(string-trim '(#\Return #\Linefeed #\Space) string)))
(when (probe-file (file ".git/HEAD"))
(let* ((head (trim (alexandria:read-file-into-string (file ".git/HEAD"))))
(path (subseq head (1+ (or (position #\Space head) -1)))))
(cond ((probe-file (file (merge-pathnames path ".git/")))
(trim (alexandria:read-file-into-string (file (merge-pathnames path ".git/")))))
((probe-file (file ".git/packed-refs"))
(with-open-file (stream (file ".git/packed-refs"))
(loop for line = (read-line stream NIL NIL)
while line
do (when (search path line :start2 40)
(return (subseq line 0 (position #\Space line))))))))))))
(defun self ()
#-nx (first (uiop:raw-command-line-arguments))
#+nx (make-pathname :device "rom" :name "sbcl" :directory '(:absolute)))
(let ((asdf-cache (make-hash-table :test 'equal)))
(defun system-cache (system)
(or (gethash (string-downcase system) asdf-cache)
(setf (gethash (string-downcase system) asdf-cache)
#+asdf
(cons (asdf:component-version (asdf:find-system system))
(asdf:system-source-directory system))
#-asdf
(cons NIL NIL))))
(defun system-source-directory (system)
(cdr (system-cache system)))
(defun (setf system-source-directory) (dir system)
(setf (cdr (system-cache system)) dir))
(defun system-version (system)
(car (system-cache system)))
(defun (setf system-version) (version system)
(setf (car (system-cache system)) version)))
(defun checksum (file)
(with-output-to-string (out)
(loop for o across (sha3:sha3-digest-file file :output-bit-length 224)
do (format out "~2,'0X" o))))
(defmethod version ((_ (eql :app)))
(let ((commit (git-repo-commit (system-source-directory +app-system+))))
(format NIL "~a~@[-~a~]"
(system-version +app-system+)
(when commit (subseq commit 0 7)))))
(defmethod version ((_ (eql :trial)))
(let ((commit (git-repo-commit (system-source-directory :trial))))
(format NIL "~a~@[-~a~]"
(system-version :trial)
(when commit (subseq commit 0 7)))))
(defmethod version ((_ (eql :binary)))
(let ((self (self)))
(if (and self (uiop:file-exists-p self) (not (uiop:featurep :nx)))
(checksum self)
"?")))
(defun data-root (&optional (app +app-system+))
(if (deploy:deployed-p)
(deploy:runtime-directory)
(system-source-directory app)))
(defgeneric coerce-object (object type &key))
(defmethod coerce-object (object type &key)
(coerce object type))
(defmethod coerce-object :around (object type &key)
(if (eql (type-of object) type)
object
(call-next-method)))
(defgeneric finalize (object))
(defmethod finalize :before ((object standard-object))
(v:debug :trial "Finalizing ~a" object))
(defmethod finalize (object)
object)
(defun round-to (base number)
(* base (ceiling number base)))
(defun gl-property (name)
(handler-case (gl:get* name)
(error (err) (declare (ignore err))
:unavailable)))
(defmethod apply-class-changes ((class standard-class)))
(defmethod apply-class-changes :before ((class standard-class))
(dolist (super (c2mop:class-direct-superclasses class))
(unless (c2mop:class-finalized-p super)
(c2mop:finalize-inheritance super))))
(defmethod apply-class-changes :after ((class standard-class))
(make-instances-obsolete class)
(dolist (sub (c2mop:class-direct-subclasses class))
(apply-class-changes sub)))
(define-global +current-time-units-per-second+ NIL)
(declaim (inline current-time))
(defun current-time ()
(declare (optimize speed (safety 0)))
(multiple-value-bind (s ms) (org.shirakumo.precise-time:get-monotonic-time)
(let* ((s (logand s (1- (expt 2 62))))
(ms (logand ms (1- (expt 2 62)))))
(declare (type (unsigned-byte 62) s ms))
(let ((inv (or +current-time-units-per-second+
(setf +current-time-units-per-second+
(coerce (/ org.shirakumo.precise-time:MONOTONIC-TIME-UNITS-PER-SECOND) 'double-float)))))
(declare (type double-float inv))
(+ s (* ms inv))))))
(defmacro undefmethod (name &rest args)
(flet ((lambda-keyword-p (symbol)
(find symbol lambda-list-keywords)))
(destructuring-bind (qualifiers args) (loop for thing = (pop args)
until (listp thing)
collect thing into qualifiers
finally (return (list qualifiers thing)))
`(let ((method (find-method
#',name
',qualifiers
(mapcar #'find-class
',(loop for arg in args
until (lambda-keyword-p arg)
collect (if (listp arg) (second arg) T)))
NIL)))
(if method
(remove-method #',name method)
NIL)))))
(defmacro define-unbound-reader (class method &body default)
(destructuring-bind (method slot) (enlist method method)
`(defmethod ,method ((,class ,class))
(cond ((slot-boundp ,class ',slot)
(slot-value ,class ',slot))
(T
,@default)))))
(defun class-default-initargs (class-ish)
(let ((class (etypecase class-ish
(symbol (find-class class-ish))
(standard-class class-ish))))
(unless (c2mop:class-finalized-p class)
(c2mop:finalize-inheritance class))
(c2mop:class-default-initargs class)))
(defmethod copy-instance ((instance standard-object) &key deep)
(let ((copy (allocate-instance (class-of instance))))
(loop for slot in (c2mop:class-slots (class-of instance))
for name = (c2mop:slot-definition-name slot)
for value = (slot-value instance name)
do (setf (slot-value copy name) (if deep (copy-instance value) value)))
copy))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun kw (thing)
(intern (string-upcase thing) "KEYWORD"))
(defun mksym (package &rest parts)
(let ((*print-case* (readtable-case *readtable*)))
(intern (format NIL "~{~a~}" parts) package))))
(defun %lispify-name (name)
(with-output-to-string (out)
(loop with dash = T
for char across name
do (cond ((or #+sbcl (sb-unicode:whitespace-p char)
#-sbcl (find char '(#\Space #\Tab #\Linefeed #\Return))
(find char "-_,'`\"#;"))
(unless dash
(setf dash T)
(write-char #\- out)))
(T
(write-char (char-upcase char) out)
(setf dash NIL))))))
(defun lispify-name (name &optional (package "KEYWORD"))
(etypecase name
(integer name)
(symbol name)
(cons (cons (lispify-name (car name) package)
(lispify-name (cdr name) package)))
(string (intern (%lispify-name name) package))))
(defun enlist (item &rest items)
(if (listp item) item (list* item items)))
(defun unlist (item)
(if (listp item) (first item) item))
(defun unquote (item)
(if (and (listp item) (eql 'quote (first item))) (second item) item))
(defun remf* (list &rest keys)
(loop for (k v) on list by #'cddr
for x = (member k keys)
unless x collect k
unless x collect v))
(defmacro popf (list key)
(let ((value (gensym "VALUE"))
(ksym (gensym "KEY")))
`(let* ((,ksym ,key)
(,value (getf ,list ,ksym)))
(remf ,list ,ksym)
,value)))
(defun getf* (key list &key (test #'eql) default)
(loop for (k v) on list by #'cddr
do (when (funcall test key k) (return v))
finally (return default)))
(defun remove-all (elements sequence &rest args)
(apply #'remove-if (lambda (e) (member e elements)) sequence args))
(defun f32-vec (&rest args)
(let ((array (make-array (length args) :element-type 'single-float)))
(map-into array #'float args)))
(defun u32-vec (&rest args)
(let ((array (make-array (length args) :element-type '(unsigned-byte 32))))
(map-into array #'truncate args)))
(defun i32-vec (&rest args)
(let ((array (make-array (length args) :element-type '(signed-byte 32))))
(map-into array #'truncate args)))
(defmacro xor (a &rest options)
(cond ((null options) a)
(T
(let ((found (gensym "FOUND")))
`(let ((,found NIL))
(block NIL
,@(loop for option in (list* a options)
collect `(when ,option
(if ,found
(return NIL)
(setf ,found T))))
,found))))))
(defun one-of (thing &rest options)
(find thing options))
(define-compiler-macro one-of (thing &rest options)
(let ((thingg (gensym "THING")))
`(let ((,thingg ,thing))
(or ,@(loop for option in options
collect `(eql ,thingg ,option))))))
(defun input-source (&optional (stream *query-io*))
(with-output-to-string (out)
(loop for in = (read-line stream NIL NIL)
while (and in (string/= in "EOF"))
do (write-string in out))))
(defun input-value (&optional (stream *query-io*))
(multiple-value-list (eval (read stream))))
(defun input-literal (&optional (stream *query-io*))
(read stream))
(defmacro define-accessor-wrapper-methods (name &body wrappers)
`(progn ,@(loop with value = (gensym "VALUE")
for (type resolution) in wrappers
collect `(defmethod ,name ((,type ,type))
(,name ,resolution))
collect `(defmethod (setf ,name) (,value (,type ,type))
(setf (,name ,resolution) ,value)))))
(defmacro define-accessor-delegate-methods (name &body wrappers)
`(progn ,@(loop with value = (gensym "VALUE")
for (resolution type) in wrappers
collect `(defmethod ,name ((,type ,type))
(,resolution ,type))
collect `(defmethod (setf ,name) (,value (,type ,type))
(setf (,resolution ,type) ,value)))))
(defmacro with-retry-restart ((name report &rest report-args) &body body)
(let ((tag (gensym "RETRY-TAG"))
(return (gensym "RETURN"))
(stream (gensym "STREAM")))
`(block ,return
(tagbody
,tag (restart-case
(return-from ,return
(progn ,@body))
(,name ()
:report (lambda (,stream) (format ,stream ,report ,@report-args))
(go ,tag)))))))
(defmacro with-new-value-restart ((place &optional (input 'input-value))
(name report &rest report-args) &body body)
(let ((tag (gensym "RETRY-TAG"))
(return (gensym "RETURN"))
(stream (gensym "STREAM"))
(value (gensym "VALUE")))
`(block ,return
(tagbody
,tag (restart-case
(return-from ,return
(progn ,@body))
(,name (,value)
:report (lambda (,stream) (format ,stream ,report ,@report-args))
:interactive ,input
(setf ,place ,value)
(go ,tag)))))))
(defmacro with-unwind-protection (cleanup &body body)
`(unwind-protect
(progn ,@body)
,cleanup))
(defmacro with-cleanup-on-failure (cleanup-form &body body)
(let ((success (gensym "SUCCESS")))
`(let ((,success NIL))
(unwind-protect
(multiple-value-prog1
(progn
,@body)
(setf ,success T))
(unless ,success
,cleanup-form)))))
(defun constantly-restart (restart &rest values)
(lambda (&rest args)
(declare (ignore args))
(apply #'invoke-restart restart values)))
(defmacro with-accessors* (accessors instance &body body)
`(with-accessors ,(loop for accessor in accessors
collect (enlist accessor accessor))
,instance
,@body))
(defmacro with-accessor-values (bindings instance &body body)
`(let ,(loop for binding in bindings
for (var acc) = (enlist binding binding)
collect `(,var (,acc ,instance)))
,@body))
(defun acquire-lock-with-starvation-test (lock &key (warn-time 10) timeout)
(assert (or (null timeout) (< warn-time timeout)))
(flet ((do-warn () (v:warn :trial.core "Failed to acquire ~a for ~s seconds. Possible starvation!"
lock warn-time)))
#+sbcl (or (sb-thread:grab-mutex lock :timeout warn-time)
(do-warn)
(if timeout
(sb-thread:grab-mutex lock :timeout (- timeout warn-time))
(sb-thread:grab-mutex lock)))
#-sbcl (loop with start = (get-universal-time)
for time = (- (get-universal-time) start)
thereis (bt:acquire-lock lock NIL)
do (when (and warn-time (< warn-time time))
(setf warn-time NIL)
(do-warn))
(when (and timeout (< timeout time))
(return NIL))
(bt:thread-yield))))
(defmacro with-trial-io-syntax ((&optional (package '*package*)) &body body)
(let ((pkg (gensym "PACKAGE")))
`(let ((,pkg (etypecase ,package
((or string symbol) (find-package ,package))
(package ,package))))
(with-standard-io-syntax
(let ((*package* ,pkg)
(*print-case* :downcase)
(*print-readably* NIL))
,@body)))))
(defun parse-sexps (input)
(with-trial-io-syntax ()
(etypecase input
(string
(loop with i = 0
collect (multiple-value-bind (data next) (read-from-string input NIL #1='#:EOF :start i)
(setf i next)
(if (eql data #1#)
(loop-finish)
data))))
(stream
(loop for value = (read input NIL #1#)
until (eq value #1#)
collect value)))))
(defun envvar-directory (var)
(let ((var (uiop:getenv var)))
(when (and var (string/= "" var))
(pathname-utils:parse-native-namestring var :as :directory :junk-allowed T))))
(defun tempdir ()
(or #+windows (or (envvar-directory "TEMP") #p"~/AppData/Local/Temp/")
#+darwin (envvar-directory "TMPDIR")
#+linux (envvar-directory "XDG_RUNTIME_DIR")
#+nx (make-pathname :device "tmp" :directory '(:absolute))
#p"/tmp/"))
(defun tempfile (&key (id (format NIL "trial-~a-~a" (get-universal-time) (random 1000)))
(type "tmp"))
(make-pathname :name id
:type type
:defaults (tempdir)))
(defmacro with-tempfile ((path &rest args) &body body)
`(let ((,path (tempfile ,@args)))
(unwind-protect
(progn ,@body)
(when (probe-file ,path)
(delete-file ,path)))))
(defun make-uuid (&optional (id NIL id-p))
(let ((val (random #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
(id (cond (id-p id)
(+main+ (sxhash (username +main+))))))
(format NIL "~8,'0x-~4,'0x-~4,'0x-~4,'0x-~12,'0x"
(ldb (byte 32 0) (or id val))
(ldb (byte 16 32) val)
(ldb (byte 16 48) val)
(ldb (byte 16 64) val)
(ldb (byte 48 80) val))))
(defun file-out-of-date-p (path default)
(let ((path (probe-file path))
(default (probe-file default)))
(when default
(or (null path)
(< (file-write-date path) (file-write-date default))))))
(defun logfile ()
(let ((log (or (uiop:getenv "TRIAL_LOGFILE") "")))
(pathname-utils:merge-pathnames*
(if (string= "" log)
"trial.log"
(pathname-utils:parse-native-namestring log))
(or #+nx (tempdir) (uiop:argv0) (user-homedir-pathname)))))
(defun config-directory (&rest app-path)
(apply #'pathname-utils:subdirectory
(or (envvar-directory "TRIAL_CONFIG_HOME")
#+windows
(or (envvar-directory "AppData")
(pathname-utils:subdirectory (user-homedir-pathname) "AppData" "Roaming"))
#+nx
(make-pathname :device "save" :directory '(:absolute))
(or (envvar-directory "XDG_CONFIG_HOME")
(pathname-utils:subdirectory (user-homedir-pathname) ".config")))
(or app-path (list +app-vendor+ +app-system+))))
(defun standalone-logging-handler ()
(when (deploy:deployed-p)
(handler-case
(when (logfile)
(ignore-errors (delete-file (logfile)))
(v:define-pipe ()
(v:file-faucet :file (logfile))))
(error (e)
(v:error :trial "Failed to set up standalone logging handler: ~a" e)
(setf (v:repl-level) :trace)))
(v:info :trial "Running on ~a, ~a ~a, ~a ~a"
(machine-instance) (machine-type) (machine-version)
(software-type) (software-version))))
(defun make-thread (name func)
(v:debug :trial "Spinning up thread: ~a" name)
(bt:make-thread (lambda ()
(handler-bind ((error #'standalone-error-handler))
(funcall func)))
:name name
:initial-bindings `((*standard-output* . ,*standard-output*)
(*error-output* . ,*error-output*)
(*trace-output* . ,*trace-output*)
(*standard-input* . ,*standard-input*)
(*query-io* . ,*query-io*)
(*debug-io* . ,*debug-io*)
(*context* . ,*context*)
(*package* . ,*package*))))
(defmacro with-thread ((name) &body body)
`(make-thread ,name (lambda () ,@body)))
(defun wait-for-thread-exit (thread &key (timeout 1) (interval 0.1))
(loop for i from 0
while (bt:thread-alive-p thread)
do (sleep interval)
(when (= i (/ timeout interval))
(restart-case
(error 'thread-did-not-exit :thread thread :timeout (* i interval))
(continue ()
:report "Continue waiting.")
(debug ()
:report "Try to interrupt the thread with a break."
(bt:interrupt-thread thread (lambda () (break))))
(abort ()
:report "Kill the thread and exit, risking corrupting the image."
(bt:destroy-thread thread)
(return))))))
(defmacro with-thread-exit ((thread &key (timeout 1) (interval 0.1)) &body body)
(let ((thread-g (gensym "THREAD")))
`(let ((,thread-g ,thread))
(when (and ,thread-g (bt:thread-alive-p ,thread-g))
,@body
(wait-for-thread-exit ,thread-g :timeout ,timeout :interval ,interval)))))
(defmacro with-error-logging ((&optional (category :trial) (message "") &rest args) &body body)
(let ((category-g (gensym "CATEGORY")))
`(let ((,category-g ,category))
(handler-bind ((error (lambda (err)
(v:severe ,category-g "~@[~@? ~]~a" ,message ,@args err)
(v:debug ,category-g err))))
,@body))))
(defmacro with-ignored-errors-on-release ((&optional (category :trial) (message "") &rest args) &body body)
(declare (ignorable category message args))
#+trial-release
`(ignore-errors
(with-error-logging (,category ,message ,@args)
,@body))
#-trial-release
`(with-simple-restart (continue "Ignore the error and continue.")
,@body))
(defmacro with-timing-report ((level category &optional (format "Operation took ~fs run-time ~fs real-time") &rest args) &body body)
(let ((run (gensym "RUNTIME"))
(real (gensym "REALTIME")))
`(let ((,run (get-internal-run-time))
(,real (get-internal-real-time)))
(unwind-protect
(progn ,@body)
(v:log ,(kw level) ,category ,format ,@args
(/ (- (get-internal-run-time) ,run) INTERNAL-TIME-UNITS-PER-SECOND)
(/ (- (get-internal-real-time) ,real) INTERNAL-TIME-UNITS-PER-SECOND))))))
(defun format-timestring (&key (timestamp (get-universal-time)) (as :datetime))
(multiple-value-bind (s m h dd mm yy) (decode-universal-time timestamp)
(ecase as
(:filename (format NIL "~4,'0d-~2,'0d-~2,'0d ~2,'0d-~2,'0d-~2,'0d" yy mm dd h m s))
(:datetime (format NIL "~4,'0d-~2,'0d-~2,'0d ~2,'0d:~2,'0d:~2,'0d" yy mm dd h m s))
(:date (format NIL "~4,'0d-~2,'0d-~2,'0d" yy mm dd))
(:time (format NIL "~2,'0d:~2,'0d:~2,'0d" h m s))
(:clock (format NIL "~2,'0d:~2,'0d" h m)))))
(defgeneric descriptor (object))
(defmethod descriptor (object)
(format NIL "~a@~4,'0x" (type-of object)
#-sbcl (sxhash object)
#+sbcl (sb-kernel:get-lisp-obj-address object)))
(defmethod descriptor ((number number))
(format NIL "~a" number))
(defmethod descriptor ((string string))
(format NIL "~s" string))
(defun simplify (array &optional (element-type (array-element-type array)))
(if (and (typep array 'simple-array)
(equal element-type (array-element-type array)))
array
(make-array (length array)
:element-type element-type
:initial-contents array)))
(defun ensure-instance (object type &rest initargs)
(cond ((null object)
(apply #'make-instance type initargs))
((eql (type-of object) type)
(apply #'reinitialize-instance object initargs))
(T
(apply #'change-class object type initargs))))
(defun ensure-class (class-ish)
(etypecase class-ish
(symbol (find-class class-ish))
(standard-class class-ish)
(standard-object (class-of class-ish))))
(defun type-prototype (type)
(case type
(character #\Nul)
(complex #c(0 0))
(cons '(NIL . NIL))
(float 0.0)
(function #'identity)
(hash-table (load-time-value (make-hash-table)))
(integer 0)
(null NIL)
(package #.*package*)
(pathname #p"")
(random-state (load-time-value (make-random-state)))
(readtable (load-time-value (copy-readtable)))
(stream (load-time-value (make-broadcast-stream)))
(string "string")
(symbol 'symbol)
(vector #(vector))
(T (let ((class (find-class type)))
(unless (c2mop:class-finalized-p class)
(c2mop:finalize-inheritance class))
(c2mop:class-prototype class)))))
(defun list-eql-specializers (function &rest args)
(delete-duplicates
(loop for method in (c2mop:generic-function-methods function)
for spec = (loop for arg in args
collect (nth arg (c2mop:method-specializers method)))
when (loop for arg in spec
thereis (typep arg 'c2mop:eql-specializer))
collect (loop for arg in spec
collect (if (typep arg 'c2mop:eql-specializer) (c2mop:eql-specializer-object arg) arg)))))
(defun maybe-finalize-inheritance (class)
(let ((class (etypecase class
(class class)
(symbol (find-class class)))))
(unless (c2mop:class-finalized-p class)
(c2mop:finalize-inheritance class))
class))
(defun list-subclasses (class)
(let ((sub (c2mop:class-direct-subclasses (ensure-class class))))
(loop for class in sub
nconc (list* class (list-subclasses class)))))
(defun list-leaf-classes (root)
(let ((sub (c2mop:class-direct-subclasses (ensure-class root))))
(if sub
(remove-duplicates
(loop for class in sub
nconc (list-leaf-classes class)))
(list (ensure-class root)))))
(defmacro with-slots-bound ((instance class) &body body)
(let ((slots (loop for slot in (c2mop:class-direct-slots
(let ((class (ensure-class class)))
(c2mop:finalize-inheritance class)
class))
for name = (c2mop:slot-definition-name slot)
collect name)))
`(with-slots ,slots ,instance
(declare (ignorable ,@slots))
,@body)))
(defmacro with-all-slots-bound ((instance class) &body body)
(let ((slots (loop for slot in (c2mop:class-slots
(let ((class (ensure-class class)))
(c2mop:finalize-inheritance class)
class))
for name = (c2mop:slot-definition-name slot)
collect name)))
`(with-slots ,slots ,instance
(declare (ignorable ,@slots))
,@body)))
(defmethod find-slot ((name symbol) (class class))
(unless (c2mop:class-finalized-p class)
(c2mop:finalize-inheritance class))
(find name (c2mop:class-slots class)))
(defmethod find-slot (name (object standard-object))
(find-slot name (class-of object)))
(defmethod construct-delegate-object-type (delegate base &rest args)
(apply #'make-instance delegate args))
(defmacro define-constant-fold-function (name (arg) &body body)
(let ((whole (gensym "WHOLE"))
(env (gensym "ENV"))
(thunk (mksym (symbol-package name) "%" name)))
`(progn
(defun ,thunk (,arg)
,@body)
(setf (fdefinition ',name) #',thunk)
(define-compiler-macro ,name (&whole ,whole &environment ,env ,arg)
(if (constantp ,arg ,env)
`(load-time-value (,',thunk ,,arg))
,whole)))))
(defgeneric clone (thing &key &allow-other-keys))
(defgeneric <- (target source)
(:method-combination progn :most-specific-last))
(defgeneric initargs (thing)
(:method-combination append :most-specific-last))
(defmethod initargs append (thing) ())
(defmethod clone (thing &key) thing)
(defmethod <- progn (a b))
(defmethod clone ((vec vec2) &key) (vcopy vec))
(defmethod <- progn ((target vec2) (source vec2)) (v<- target source))
(defmethod clone ((vec vec3) &key) (vcopy vec))
(defmethod <- progn ((target vec3) (source vec3)) (v<- target source))
(defmethod clone ((vec vec4) &key) (vcopy vec))
(defmethod <- progn ((target vec4) (source vec4)) (v<- target source))
(defmethod clone ((mat mat2) &key) (mcopy mat))
(defmethod <- progn ((target mat2) (source mat2)) (m<- target source))
(defmethod clone ((mat mat3) &key) (mcopy mat))
(defmethod <- progn ((target mat3) (source mat3)) (m<- target source))
(defmethod clone ((mat mat4) &key) (mcopy mat))
(defmethod <- progn ((target mat4) (source mat4)) (m<- target source))
(defmethod clone ((mat matn) &key) (mcopy mat))
(defmethod <- progn ((target matn) (source matn)) (m<- target source))
(defmethod clone ((quat quat) &key) (qcopy quat))
(defmethod <- progn ((target quat) (source quat)) (q<- target source))
(defmethod clone ((cons cons) &key)
(cons (clone (car cons)) (clone (cdr cons))))
(defmethod clone ((array array) &key)
(if (array-has-fill-pointer-p array)
(make-array (array-dimensions array)
:element-type (array-element-type array)
:adjustable (adjustable-array-p array)
:fill-pointer (fill-pointer array)
:initial-contents array)
(make-array (array-dimensions array)
:element-type (array-element-type array)
:adjustable (adjustable-array-p array)
:initial-contents array)))
(defmethod clone ((object standard-object) &rest initargs)
(<- (apply #'make-instance (class-of object) initargs) object))
(defmacro define-transfer (class &body properties)
`(defmethod <- progn ((target ,class) (source ,class))
,@(loop for property in properties
collect (if (and (listp property) (eql :eval (first property)))
`(progn ,@(rest property))
(destructuring-bind (target-accessor &optional (source-accessor target-accessor) (key 'identity)) (enlist property)
`(setf (,target-accessor target) (,key (,source-accessor source))))))
target))
(defmethod location ((vec vec2)) vec)
(defmethod location ((vec vec3)) vec)
(defmethod location ((mat mat3))
(with-fast-matref (m mat)
(vec (m 0 2) (m 1 2))))
(defmethod location ((mat mat4))
(with-fast-matref (m mat)
(vec (m 0 3) (m 1 3) (m 2 3))))
(defmethod orientation ((mat mat4))
(qfrom-mat mat))
(defmethod global-location ((vec vec2) &optional (target (vec3)))
(let ((vec (vec (vx vec) (vy vec) 0 0)))
(declare (dynamic-extent vec))
(n*m (model-matrix) vec)
(vsetf target (vx vec) (vy vec) (vz vec))))
(defmethod global-location ((vec vec3) &optional (target (vec3)))
(let ((vec (vec (vx vec) (vy vec) (vz vec) 0)))
(declare (dynamic-extent vec))
(n*m (model-matrix) vec)
(vsetf target (vx vec) (vy vec) (vz vec))))
(defmethod global-location ((tf transform) &optional (target (vec3)))
(let ((vec (vec (location tf) 0)))
(declare (dynamic-extent vec))
(n*m (model-matrix) vec)
(vsetf target (vx vec) (vy vec) (vz vec))))
(defmethod global-orientation ((quat quat) &optional (target (quat)))
(q<- target quat)
(let ((q (qfrom-mat (model-matrix))))
(declare (dynamic-extent q))
(!q* target q target)))
(defmethod global-orientation ((tf transform) &optional (target (quat)))
(q<- target (orientation tf))
(let ((q (qfrom-mat (model-matrix))))
(declare (dynamic-extent q))
(!q* target q target)))
(defun initarg-slot (class initarg)
(let ((class (etypecase class
(class class)
(symbol (find-class class)))))
(find (list initarg) (c2mop:class-slots class)
:key #'c2mop:slot-definition-initargs
:test #'subsetp)))
(defun initarg-slot-value (instance initarg)
(slot-value instance (c2mop:slot-definition-name (initarg-slot (class-of instance) initarg))))
(defun minimize (sequence test &key (key #'identity))
(etypecase sequence
(vector (when (< 0 (length sequence))
(loop with minimal = (aref sequence 0)
for i from 1 below (length sequence)
for current = (aref sequence i)
do (when (funcall test
(funcall key current)
(funcall key minimal))
(setf minimal current))
finally (return minimal))))
(list (when sequence
(loop with minimal = (car sequence)
for current in (rest sequence)
do (when (funcall test
(funcall key current)
(funcall key minimal))
(setf minimal current))
finally (return minimal))))))
(defun format-with-line-numbers (text &optional out)
(etypecase out
(null
(with-output-to-string (out)
(format-with-line-numbers text out)))
((eql T)
(format-with-line-numbers text *standard-output*))
(stream
(with-input-from-string (in text)
(loop for i from 1
for line = (read-line in NIL)
while line
do (format out "~3d " i)
(write-line line out))))))
(defun generate-name (&optional indicator)
(loop for name = (format NIL "~a-~d" (or indicator "ENTITY") (incf *gensym-counter*))
while (find-symbol name *package*)
finally (return (intern name *package*))))
(declaim (inline clamp))
(defun clamp (low mid high)
(max low (min mid high)))
(declaim (inline deadzone))
(defun deadzone (min thing)
(if (< (abs thing) min) 0.0 thing))
(declaim (inline lpf))
(defun lpf (factor cur target)
(+ (* (- 1.0 factor) target) (* cur factor)))
(declaim (inline lerp))
(defun lerp (from to n)
(etypecase from
(real (+ (* from (- 1.0 n)) (* to n)))
(vec (vlerp from to n))))
(declaim (inline lerp-dt))
(defun lerp-dt (from to dt rem)
;; REM: remaining time to get to TO.
(declare (optimize speed))
(let* ((l (- (/ (float rem 0f0)
(float (log 1/100 2) 0f0))))
(n (- 1 (expt 2 (- (/ (float dt 0f0) l))))))
(declare (type single-float n l))
(lerp from to n)))
(declaim (inline deg->rad rad->deg))
(defun deg->rad (deg)
(* deg PI 1/180))
(defun rad->deg (rad)
(* rad 180 (/ PI)))
(defun db (db)
(expt 10 (* 0.05 db)))
(defun angle-midpoint (a b)
(when (< b a) (rotatef a b))
(when (< PI (- b a)) (decf b F-2PI))
(mod (/ (+ b a) 2) F-2PI))
(defun angle-distance (a b)
(let ((da (mod (- b a) F-2PI)))
(- (mod (* 2 da) F-2PI) da)))
(defun clamp-angle (min a max)
(flet ((normalize-180 (a)
(- (mod (+ a F-PI) F-2PI) F-PI)))
(let* ((a (mod a F-2PI))
(n-min (normalize-180 (- min a)))
(n-max (normalize-180 (- max a))))
(cond ((and (<= n-min 0) (<= 0 n-max))
a)
((< (abs n-min) (abs n-max))
min)
(T
max)))))
(defun lerp-angle (a b x)
(let ((d (- b a)))
(cond ((< (+ F-PI) d) (incf a F-2PI))
((< d (- F-PI)) (decf a F-2PI)))
(+ a (* (- b a) x))))
#-3d-math-u32
(progn
(declaim (inline uvarr2 uvarr3 uvarr4 uvec2 uvec3 uvec4))
(defun uvarr2 (a) (ivarr2 a))
(defun uvarr3 (a) (ivarr3 a))
(defun uvarr4 (a) (ivarr4 a))
(defun uvec2 (&rest args) (apply #'ivec2 args))
(defun uvec3 (&rest args) (apply #'ivec3 args))
(defun uvec4 (&rest args) (apply #'ivec4 args)))
(defparameter *c-chars* "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_[]")
(defun symbol->c-name (symbol &optional out)
(flet ((frob (out)
(loop for c across (symbol-name symbol)
do (cond ((char= c #\-)
(write-char #\_ out))
((find c *c-chars*)
(write-char (char-downcase c) out))
(T (write-char #\_ out))))))
(if out
(frob out)
(with-output-to-string (out)
(frob out)))))
(defun c-name->symbol (name &optional (package *package*))
(intern
(with-output-to-string (out)
(loop for c across name
do (cond ((char= c #\_)
(write-char #\- out))
(T
(write-char (char-upcase c) out)))))
package))
(defun gl-vendor ()
(let ((vendor (gl:get-string :vendor)))
(cond ((search "Intel" vendor) :intel)
((search "NVIDIA" vendor) :nvidia)
((search "ATI" vendor) :amd)
((search "AMD" vendor) :amd)
(T :unknown))))
(defun check-texture-size (width height)
(let ((max (gl:get* :max-texture-size)))
(when (< max (max width height))
(error "Hardware cannot support a texture of size ~ax~a, max is ~a."
width height max))))
(defmacro define-enum-check (name &body cases)
(let* ((*print-case* (readtable-case *readtable*))
(list (mksym *package* "*" name "-" '#:list "*"))
(func (mksym *package* '#:check "-" name))
(funcp (mksym *package* name '#:-p)))
`(progn (defparameter ,list '(,@cases))
(defun ,func (enum)
(unless (member enum ,list)
(error "~a is not a valid ~a. Needs to be one of the following:~%~a"
enum ',name ,list)))
(defun ,funcp (enum)
(member enum ,list)))))
(define-enum-check texture-target
:texture-1d :texture-2d :texture-3d
:texture-1d-array :texture-2d-array
:texture-cube-map :texture-cube-map-array
:texture-2d-multisample :texture-2d-multisample-array)
(define-enum-check texture-mag-filter
:nearest :linear)
(define-enum-check texture-min-filter
:nearest :linear :nearest-mipmap-nearest :nearest-mipmap-linear