Skip to content

Instantly share code, notes, and snippets.

@Mon-Ouie
Created August 30, 2011 10:29
Show Gist options
  • Save Mon-Ouie/1180616 to your computer and use it in GitHub Desktop.
Save Mon-Ouie/1180616 to your computer and use it in GitHub Desktop.
require 'ray'
class Life
Width = 1920
Height = 1080
Size = Ray::Vector2[Width, Height]
def initialize
@image = Ray::Image.new Size
@buffer = Ray::Image.new Size
setup_image(@image)
@image_sprite = Ray::Sprite.new(@image)
@buffer_sprite = Ray::Sprite.new(@buffer)
@image_target = Ray::ImageTarget.new(@image)
@buffer_target = Ray::ImageTarget.new(@buffer)
setup_target(@image_target)
setup_target(@buffer_target)
end
def update
@buffer_target.draw @image_sprite
swap
end
def sprite
@image_sprite
end
private
def swap
@buffer_target.update
@image, @buffer = @buffer, @image
@image_sprite, @buffer_sprite = @buffer_sprite, @image_sprite
@image_target, @buffer_target = @buffer_target, @image_target
end
def setup_image(image)
image.map! { rand(2).zero? ? Ray::Color.black : Ray::Color.white }
end
def setup_target(target)
target.shader.compile(:frag => StringIO.new(<<eof))
#version 130
const float width = 1.0 / #{Width.to_f};
const float height = 1.0 / #{Height.to_f};
uniform sampler2D in_Texture;
in vec2 var_TexCoord;
out vec4 out_FragColor;
bool is_alive(vec2 pos) {
return texture(in_Texture, var_TexCoord + pos) == vec4(0, 0, 0, 1);
}
int count_neighbours() {
int count = 0;
if (is_alive(vec2(-width, +height))) count += 1;
if (is_alive(vec2(-width, -height))) count += 1;
if (is_alive(vec2(+width, +height))) count += 1;
if (is_alive(vec2(+width, -height))) count += 1;
if (is_alive(vec2(+width, 0))) count += 1;
if (is_alive(vec2(-width, 0))) count += 1;
if (is_alive(vec2(0, +height))) count += 1;
if (is_alive(vec2(0, -height))) count += 1;
return count;
}
void main() {
int count = count_neighbours();
if (is_alive(vec2(0, 0))) {
if (count == 2 || count == 3)
out_FragColor = vec4(0, 0, 0, 1);
else
out_FragColor = vec4(1, 1, 1, 1);
}
else if (count == 3)
out_FragColor = vec4(0, 0, 0, 1);
else
out_FragColor = vec4(1, 1, 1, 1);
}
eof
end
end
Ray.game "The game of life", :size => Life::Size do
register { add_hook :quit, method(:exit!) }
scene :life do
self.frames_per_second = nil
window.view = Ray::View.new(Life::Size / 2, Life::Size)
@life = Life.new
always do
@life.update
end
render do |win|
win.draw @life.sprite
end
end
scenes << :life
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment