class MagicCloud::Spriter

Incapsulates sprite maker for any Shape, able to draw itself.

Constants

CANVAS_SIZE

Attributes

canvas[R]
cur_x[R]
cur_y[R]
row_height[R]

Public Instance Methods

make_sprites!(shapes) click to toggle source
# File lib/magic_cloud/spriter.rb, line 12
def make_sprites!(shapes)
  start = Time.now
  
  Debug.logger.info 'Starting sprites creation'
  
  restart_canvas!
  
  shapes.each do |shape|
    make_sprite(shape)
  end

  Debug.logger.info 'Sprites ready: %i sec, %i canvases' %
    [Time.now - start, Debug.stats[:canvases]]
end

Private Instance Methods

ensure_position(rect) click to toggle source

ensure this rect can be drawn at current position or shift position of it can't

# File lib/magic_cloud/spriter.rb, line 64
def ensure_position(rect)
  # no place in current row -> go to next row
  if cur_x + rect.width > canvas.width
    @cur_x = 0
    @cur_y += row_height
    @row_height = 0
  end

  # no place in current canvas -> restart canvas
  restart_canvas! if cur_y + rect.height > canvas.height
end
make_sprite(shape) click to toggle source
# File lib/magic_cloud/spriter.rb, line 31
def make_sprite(shape)
  rect = shape.measure(canvas)
  ensure_position(rect)

  shape.draw(canvas, color: 'red', x: cur_x, y: cur_y)
  shape.sprite =
    pixels_to_sprite(
      canvas.pixels(cur_x, cur_y, rect.width, rect.height),
      rect
    )
      
  shift_position(rect)

  Debug.logger.debug 'Sprite for %p ready: %i×%i' %
    [shape, shape.sprite.width, shape.sprite.height]
end
pixels_to_sprite(pixels, rect) click to toggle source
# File lib/magic_cloud/spriter.rb, line 76
def pixels_to_sprite(pixels, rect)
  sprite = Sprite.new(rect.width, rect.height)

  (0...rect.height).each do |y|
    (0...rect.width).each do |x|
      # each 4-th byte of RGBA - 1 or 0
      bit = pixels[(y * rect.width + x) * 4]
      sprite.put(x, y, bit.zero? ? 0 : 1)
    end
  end

  sprite
end
restart_canvas!() click to toggle source
# File lib/magic_cloud/spriter.rb, line 50
def restart_canvas!
  Debug.stats[:canvases] += 1
  @canvas = Canvas.new(*CANVAS_SIZE)
  @cur_x, @cur_y, @row_height = 0, 0, 0
end
shift_position(rect) click to toggle source

go to next free position after this rect was drawn

# File lib/magic_cloud/spriter.rb, line 57
def shift_position(rect)
  @cur_x += rect.width
  @row_height = [row_height, rect.height].max
end