1 USING: accessors alien.c-types arrays combinators destructors http.client
2 io io.encodings.ascii io.files kernel math math.matrices math.parser
3 math.vectors opengl opengl.capabilities opengl.gl sequences sequences.lib
4 splitting vectors words ;
7 : numbers ( str -- seq )
8 " " split [ string>number ] map sift ;
10 : (parse-model) ( vs is -- vs is )
13 { [ dup length 5 = ] [ 3 head pick push ] }
14 { [ dup first 3 = ] [ rest over push ] }
19 : parse-model ( -- vs is )
20 100000 <vector> 100000 <vector> (parse-model) ;
22 : n ( vs triple -- n )
23 swap [ nth ] curry map
24 dup third over first v- >r dup second swap first v- r> cross
27 : normal ( ns vs triple -- )
28 [ n ] keep [ rot [ v+ ] change-nth ] each-with2 ;
30 : normals ( vs is -- ns )
31 over length { 0.0 0.0 0.0 } <array> -rot
32 [ >r 2dup r> normal ] each drop
35 : read-model ( stream -- model )
36 ascii [ parse-model ] with-file-reader
37 [ normals ] 2keep 3array ;
39 : model-path ( -- path ) "bun_zipper.ply" temp-file ;
41 : model-url ( -- url ) "http://factorcode.org/bun_zipper.ply" ;
43 : maybe-download ( -- path )
44 model-path dup exists? [
45 "Downloading bunny from " write
46 model-url dup print flush
50 : (draw-triangle) ( ns vs triple -- )
51 [ dup roll nth gl-normal swap nth gl-vertex ] each-with2 ;
53 : draw-triangles ( ns vs is -- )
54 GL_TRIANGLES [ [ (draw-triangle) ] each-with2 ] do-state ;
56 TUPLE: bunny-dlist list ;
57 TUPLE: bunny-buffers array element-array nv ni ;
59 : <bunny-dlist> ( model -- geom )
60 GL_COMPILE [ first3 draw-triangles ] make-dlist
63 : <bunny-buffers> ( model -- geom )
66 [ first concat ] [ second concat ] bi
68 GL_ARRAY_BUFFER swap GL_STATIC_DRAW <gl-buffer>
71 third concat >c-uint-array
72 GL_ELEMENT_ARRAY_BUFFER swap GL_STATIC_DRAW <gl-buffer>
76 } cleave bunny-buffers boa ;
78 GENERIC: bunny-geom ( geom -- )
79 GENERIC: draw-bunny ( geom draw -- )
81 M: bunny-dlist bunny-geom
82 bunny-dlist-list glCallList ;
84 M: bunny-buffers bunny-geom
85 dup { array>> element-array>> } get-slots [
86 { GL_VERTEX_ARRAY GL_NORMAL_ARRAY } [
87 GL_FLOAT 0 0 buffer-offset glNormalPointer
89 nv>> "float" heap-size * buffer-offset
90 3 GL_FLOAT 0 roll glVertexPointer
93 GL_TRIANGLES swap GL_UNSIGNED_INT 0 buffer-offset glDrawElements
95 ] all-enabled-client-state
96 ] with-array-element-buffers ;
98 M: bunny-dlist dispose
101 M: bunny-buffers dispose
102 { array>> element-array>> } get-slots
103 delete-gl-buffer delete-gl-buffer ;
105 : <bunny-geom> ( model -- geom )
106 "1.5" { "GL_ARB_vertex_buffer_object" }
107 has-gl-version-or-extensions?
108 [ <bunny-buffers> ] [ <bunny-dlist> ] if ;