Skip to content

Instantly share code, notes, and snippets.

@mattetti
Created October 8, 2012 01:19
Show Gist options
  • Save mattetti/3850240 to your computer and use it in GitHub Desktop.
Save mattetti/3850240 to your computer and use it in GitHub Desktop.
Rakefile to generate a mruby mandelbrot example
# Change the path to match the path to your machine.
$mrb_path = File.expand_path("~/src/mruby")
$mrbc = File.join($mrb_path,"/bin/mrbc")
task :default do
# dumps the Ruby file to disk
File.open("mandelbrot.rb", "w"){|f| f << mandelbrot_ruby_code }
# creates the .c file containing mandelbrot char array for the bytecode
`#{$mrbc} -Bmandelbrot_bytecode ./mandelbrot.rb`
example_file = wrapper_code(File.read("./mandelbrot.c"))
File.open("example.c", 'w'){|f| f << example_file}
cmd = "gcc -I#{$mrb_path}/src -I#{$mrb_path}/include -c example.c -o example.o"
cmd2 = "gcc -o ./example example.o #{$mrb_path}/lib/libmruby.a"
`#{cmd}`
`#{cmd2}`
print "compiled\n"
print "executing\n"
print "You can now run 10 mandelbrots by running ./example\n"
end
def wrapper_code(insert=nil)
code = <<-EOF
#include "mruby.h"
#include "mruby/irep.h"
#include "mruby/proc.h"
#{insert}
int
main(void)
{
/* new interpreter instance */
mrb_state *mrb;
mrb = mrb_open();
/* read and execute compiled symbols */
int n = mrb_read_irep(mrb, mandelbrot_bytecode);
mrb_run(mrb, mrb_proc_new(mrb, mrb->irep[n]), mrb_top_self(mrb));
mrb_close(mrb);
return 0;
}
EOF
end
def mandelbrot_ruby_code
code = <<-EOF
BAILOUT = 16
MAX_ITERATIONS = 1000
class Mandelbrot
def initialize
(-39...39).each do |y|
puts
(-39...39).each do |x|
i = iterate(x/40.0,y/40.0)
print (i == 0) ? "*" : " "
end
end
end
def iterate(x,y)
cr = y-0.5
ci = x
zi = 0.0
zr = 0.0
i = 0
while true
i += 1
temp = zr * zi
zr2 = zr * zr
zi2 = zi * zi
zr = zr2 - zi2 + cr
zi = temp + temp + ci
return i if (zi2 + zr2 > BAILOUT)
return 0 if (i > MAX_ITERATIONS)
end
end
end
5.times do
Mandelbrot.new
end
EOF
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment