 
 CONSTANT: size 200
 
-: delta ( -- n ) epsilon sqrt ; inline
+: delta ( -- n ) epsilon sqrt ; inline no-compile
 
 TUPLE: ray { orig double-4 read-only } { dir double-4 read-only } ;
 

! Factor port of the raytracer benchmark from
! http://www.ffconsultancy.com/free/ray_tracer/languages.html

USING: arrays accessors io io.files io.files.temp
io.encodings.binary kernel math math.constants math.functions
math.vectors math.vectors.simd math.vectors.simd.cords math.parser
make sequences sequences.private words hints classes.struct ;
QUALIFIED-WITH: alien.c-types c
IN: benchmark.raytracer-simd

! parameters


    ] [
        [ sray-intersect lambda>> 1/0. = ] keep swap
        [ ray-g neg ] [ drop 0.0 ] if
    ] if ; inline no-compile

: create-center ( c r d -- c2 )
    [ 3.0 12.0 sqrt / * ] dip n*v v+ ; inline no-compile

DEFER: create ( level c r -- scene )

: create-step ( level c r d -- scene )
    over [ create-center ] dip 2.0 / [ 1 - ] 2dip create ;

CONSTANT: create-offsets
    {
        double-4{ -1.0 1.0 -1.0 0.0 }
        double-4{ 1.0 1.0 -1.0 0.0 }
        double-4{ -1.0 1.0 1.0 0.0 }
        double-4{ 1.0 1.0 1.0 0.0 }
    }

: create-bound ( c r -- sphere ) 3.0 * <sphere> ;

: create-group ( level c r -- scene )
    2dup create-bound [
        2dup <sphere> ,
        create-offsets [ create-step , ] with with with each
    ] make-group ;

: create ( level c r -- scene )
    pick 1 = [ <sphere> nip ] [ create-group ] if ;

: ss-point ( dx dy -- point )
    [ oversampling /f ] bi@ 0.0 0.0 double-4-boa ; inline no-compile

: ray-pixel ( scene point -- ray-grid )
    [ 0.0 ] 2dip
    oversampling iota [
        oversampling iota [
            ss-point v+ normalize
            double-4{ 0.0 0.0 -4.0 0.0 } swap <ray>
            swap cast-ray +
        ] with with with each
    ] with with each ; inline no-compile

: ray-trace ( scene -- grid )
    size iota <reversed> [
        size iota [
            [ size 0.5 * - ] bi@ swap size
            0.0 double-4-boa ray-pixel
        ] with with map
    ] with map ;

: pgm-header ( w h -- )
    "P5\n" % swap # " " % # "\n255\n" % ;

: pgm-pixel ( n -- ) 255 * 0.5 + >fixnum , ;

: run ( -- string )
    levels double-4{ 0.0 -1.0 0.0 0.0 } 1.0 create ray-trace [
