public
Created

Rakefile to generate a mruby mandelbrot example

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
# 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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.