1 ! (c)2009 Joe Groff bsd license
2 USING: accessors timers alien.c-types calendar classes.struct
3 continuations destructors fry kernel math math.order memory
4 namespaces sequences system ui ui.gadgets.worlds vm
5 vocabs.loader arrays locals ;
9 { tick-interval-nanos integer read-only }
19 GENERIC: tick* ( delegate -- )
20 GENERIC: draw* ( tick-slice delegate -- )
24 TUPLE: game-loop-error-state error game-loop ;
26 : ?ui-error ( error -- )
27 ui-running? [ ui-error ] [ rethrow ] if ;
29 : game-loop-error ( error game-loop -- )
30 [ nip stop-loop ] [ \ game-loop-error-state boa ?ui-error ] 2bi ;
32 : fps ( fps -- nanos )
33 [ 1,000,000,000 ] dip /i ; inline
37 : last-tick-percent-offset ( loop -- float )
38 [ draw-timer>> iteration-start-nanos>> nano-count swap - ]
39 [ tick-interval-nanos>> ] bi /f 1.0 min ;
41 GENERIC# record-benchmarking 1 ( loop quot -- )
43 M: object record-benchmarking
49 [ last-tick-percent-offset ] [ draw-delegate>> ] bi
51 ] record-benchmarking ;
54 [ tick-delegate>> tick* ] record-benchmarking ;
56 : increment-tick ( loop -- )
62 :: when-running ( loop quot -- )
65 dup running?>> quot [ drop ] if
70 : tick-iteration ( loop -- )
71 [ [ tick ] [ increment-tick ] bi ] when-running ;
73 : frame-iteration ( loop -- )
74 [ redraw ] when-running ;
76 : start-loop ( loop -- )
80 [ '[ _ tick-iteration ] f ]
81 [ tick-interval-nanos>> nanoseconds ] bi <timer> >>tick-timer
83 dup '[ _ frame-iteration ] f 1 milliseconds <timer> >>draw-timer
85 [ tick-timer>> ] [ draw-timer>> ] bi [ start-timer ] bi@ ;
87 : stop-loop ( loop -- )
89 [ tick-timer>> ] [ draw-timer>> ] bi [ stop-timer ] bi@ ;
91 : <game-loop*> ( tick-interval-nanos tick-delegate draw-delegate -- loop )
92 f 0 0 f f f game-loop boa ;
94 : <game-loop> ( tick-interval-nanos delegate -- loop )
95 dup <game-loop*> ; inline
100 { "game.loop" "prettyprint" } "game.loop.prettyprint" require-when
101 { "game.loop" "tools.memory" } "game.loop.benchmark" require-when