Class: RGame::Engine::Pool

Inherits:
Object
  • Object
show all
Defined in:
lib/rgame/engine/pool.rb

Overview

A reuse-don't-allocate pool for many short-lived, homogeneous objects — bullets, particles, transient enemies. Acquired objects come from a free list (or the factory when the list is empty) so steady-state spawning allocates nothing. Pure logic; no graphics.

pool = Engine::Pool.new { Bullet.new }
b = pool.acquire        # recycled or freshly built
pool.each { |b| b.update(dt) }
pool.reclaim_if(&:dead?) # sweep dead → free list, once per frame

The factory builds a blank object; callers re-initialise it after acquire.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&factory) ⇒ Pool

Returns a new instance of Pool.



17
18
19
20
21
# File 'lib/rgame/engine/pool.rb', line 17

def initialize(&factory)
  @factory = factory
  @free = []
  @active = []
end

Instance Attribute Details

#activeObject (readonly)

Returns the value of attribute active.



23
24
25
# File 'lib/rgame/engine/pool.rb', line 23

def active
  @active
end

Instance Method Details

#acquireObject



25
26
27
28
29
# File 'lib/rgame/engine/pool.rb', line 25

def acquire
  obj = @free.empty? ? @factory.call : @free.pop
  @active.push(obj)
  obj
end

#eachObject



31
# File 'lib/rgame/engine/pool.rb', line 31

def each(&) = @active.each(&)

#empty?Boolean

No live (acquired, not-yet-reclaimed) objects.

Returns:

  • (Boolean)


36
# File 'lib/rgame/engine/pool.rb', line 36

def empty? = @active.empty?

#reclaim_ifObject

Deferred removal: sweep the active list once, moving every object for which the block returns true onto the free list. Safe to call after iterating with each — never mutate the active list mid-iteration; mark objects dead during the frame and reclaim them here.



42
43
44
45
46
47
48
# File 'lib/rgame/engine/pool.rb', line 42

def reclaim_if
  @active.reject! do |obj|
    dead = yield(obj)
    @free.push(obj) if dead
    dead
  end
end

#sizeObject



33
# File 'lib/rgame/engine/pool.rb', line 33

def size = @active.size