1 ! Copyright (C) 2009 Joe Groff.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors timers alien.c-types calendar classes.struct
4 continuations destructors fry kernel math math.order memory
5 namespaces sequences system ui ui.gadgets.worlds vm
6 vocabs.loader arrays locals ;
10 { tick-interval-nanos integer read-only }
20 GENERIC: tick* ( delegate -- )
21 GENERIC: draw* ( tick-slice delegate -- )
25 TUPLE: game-loop-error-state error game-loop ;
27 : ?ui-error ( error -- )
28 ui-running? [ ui-error ] [ rethrow ] if ;
30 : game-loop-error ( error game-loop -- )
31 [ nip stop-loop ] [ \ game-loop-error-state boa ?ui-error ] 2bi ;
33 : fps ( fps -- nanos )
34 [ 1,000,000,000 ] dip /i ; inline
38 : last-tick-percent-offset ( loop -- float )
39 [ draw-timer>> iteration-start-nanos>> nano-count swap - ]
40 [ tick-interval-nanos>> ] bi /f 1.0 min ;
42 GENERIC#: record-benchmarking 1 ( loop quot -- )
44 M: object record-benchmarking
50 [ last-tick-percent-offset ] [ draw-delegate>> ] bi
52 ] record-benchmarking ;
55 [ tick-delegate>> tick* ] record-benchmarking ;
57 : increment-tick ( loop -- )
63 :: when-running ( loop quot -- )
66 dup running?>> quot [ drop ] if
71 : tick-iteration ( loop -- )
72 [ [ tick ] [ increment-tick ] bi ] when-running ;
74 : frame-iteration ( loop -- )
75 [ redraw ] when-running ;
77 : start-loop ( loop -- )
81 [ '[ _ tick-iteration ] f ]
82 [ tick-interval-nanos>> nanoseconds ] bi <timer> >>tick-timer
84 dup '[ _ frame-iteration ] f 1 milliseconds <timer> >>draw-timer
86 [ tick-timer>> ] [ draw-timer>> ] bi [ start-timer ] bi@ ;
88 : stop-loop ( loop -- )
90 [ tick-timer>> ] [ draw-timer>> ] bi [ stop-timer ] bi@ ;
92 : <game-loop*> ( tick-interval-nanos tick-delegate draw-delegate -- loop )
93 f 0 0 f f f game-loop boa ;
95 : <game-loop> ( tick-interval-nanos delegate -- loop )
96 dup <game-loop*> ; inline
101 { "game.loop" "prettyprint" } "game.loop.prettyprint" require-when
102 { "game.loop" "tools.memory" } "game.loop.benchmark" require-when