implement sprite pooling

This commit is contained in:
Jeremy Penner 2023-11-22 22:40:27 -05:00
parent c9e749ab61
commit 08f779ac4b
3 changed files with 40 additions and 6 deletions

View file

@ -6,24 +6,25 @@
(local iter (require :meta.iter))
(local state (require :state))
(local cache (require :cache))
(local pool (require :pool))
(local {: make-image : image : defsprite : sprite : dirty : with-bg-draw : with-image : with-collision} (require :sprite))
(local gfx playdate.graphics)
(local devmode false)
(local devmode true)
(local update (defmulti #$1))
(local children (defmulti #$2))
(local scene (defmulti #$1))
(fn destroy-all [type ctx] (cache.destroy type) (tset ctx type nil))
(fn destroy-key [type id ctx ?key] (cache.destroy type id) (tset (. ctx type) (or ?key id) nil))
(fn destroy-item [type id ctx ?index] (cache.destroy type id) (table.remove (. ctx type) (or ?index id)))
(update:defmethod :default #nil)
(children:defmethod :default (fn [val] (iter.ivalues val)))
(scene:defmethod :default #nil)
(fn destroy-all [type ctx] (cache.destroy type) (tset ctx type nil))
(fn destroy-key [type id ctx ?key] (cache.destroy type id) (tset (. ctx type) (or ?key id) nil))
(fn destroy-item [type id ctx ?index] (cache.destroy type id) (table.remove (. ctx type) (or ?index id)))
(fn descend [t k] (children (. t k) k t))
(fn do-to-children [keys f ?t]
@ -184,5 +185,6 @@
(gfx.sprite.update)
(playdate.timer.updateTimers)
(when (reload.check)
(pool.purge)
(cache.purge)
(dirty :background)))

23
src/pool.fnl Normal file
View file

@ -0,0 +1,23 @@
(local {: defmulti} (require :meta.multimethod))
(local tbl (require :meta.table))
(local Pool {
:create (defmulti #$1)
:clear (defmulti #$1)
:pools {}})
(Pool.clear:defmethod :default #nil)
(fn Pool.get [type]
(let [pool (. Pool.pools type)]
(if (and pool (. pool 1))
(table.remove pool)
(Pool.create type))))
(fn Pool.return [type val]
(Pool.clear type val)
(table.insert (tbl.ensure Pool.pools type) val))
(fn Pool.purge [] (set Pool.pools {}))
Pool

View file

@ -1,7 +1,16 @@
(local cache (require :cache))
(local pool (require :pool))
(import :CoreLibs/sprites)
(cache.register-asset :sprite #(doto (playdate.graphics.sprite.new) (: :add) (: :setUpdatesEnabled false)) #($1:remove))
(pool.create:defmethod :sprite #(doto (playdate.graphics.sprite.new) (: :setUpdatesEnabled false)))
(pool.clear:defmethod :sprite #(doto $2
(: :remove) (: :setImage nil) (: :setGroupMask 0) (: :setCollidesWithGroupsMask 0) (: :setIgnoresDrawOffset false)
(: :setCenter 0.5 0.5) (: :setVisible true) (: :setZIndex 0) (: :setTag 0)))
(cache.register-asset :sprite
#(doto (pool.get :sprite) (: :add))
#(pool.return :sprite $1))
(cache.register-asset :image #(playdate.graphics.image.new $1))
(cache.register-asset :imagetable #(playdate.graphics.imagetable.new $1))