1 USING: accessors alien.c-types arrays combinators destructors
2 http.client io io.encodings.ascii io.files io.files.temp kernel
3 locals math math.matrices math.parser math.vectors opengl
4 opengl.capabilities opengl.gl opengl.demo-support sequences
5 splitting vectors words specialized-arrays alien.data ;
6 QUALIFIED-WITH: alien.c-types c
7 SPECIALIZED-ARRAY: c:float
8 SPECIALIZED-ARRAY: c:uint
11 : numbers ( str -- seq )
12 " " split [ string>number ] map sift ;
14 : (parse-model) ( vs is -- vs is )
17 { [ dup length 5 = ] [ 3 head pick push ] }
18 { [ dup first 3 = ] [ rest over push ] }
23 : parse-model ( -- vs is )
24 100000 <vector> 100000 <vector> (parse-model) ;
26 : n ( vs triple -- n )
27 swap [ nth ] curry map
28 [ [ second ] [ first ] bi v- ] [ [ third ] [ first ] bi v- ] bi cross
31 : normal ( ns vs triple -- )
32 [ n ] keep [ rot [ v+ ] change-nth ] 2with each ;
34 : normals ( vs is -- ns )
35 [ [ length { 0.0 0.0 0.0 } <array> ] keep ] dip
36 [ [ 2dup ] dip normal ] each drop
39 : read-model ( stream -- model )
40 ascii [ parse-model ] with-file-reader
41 [ normals ] 2keep 3array ;
43 : model-path ( -- path ) "bun_zipper.ply" cache-file ;
45 CONSTANT: model-url "http://duriansoftware.com/joe/media/bun_zipper.ply"
47 : download-bunny ( -- path )
48 model-url model-path [ ?download-to ] keep ;
50 :: (draw-triangle) ( ns vs triple -- )
56 : draw-triangles ( ns vs is -- )
57 GL_TRIANGLES [ [ (draw-triangle) ] 2with each ] do-state ;
59 TUPLE: bunny-dlist list ;
60 TUPLE: bunny-buffers array element-array nv ni ;
62 : <bunny-dlist> ( model -- geom )
63 GL_COMPILE [ first3 draw-triangles ] make-dlist
66 : <bunny-buffers> ( model -- geom )
69 [ first concat ] [ second concat ] bi
70 append c:float >c-array underlying>>
71 GL_ARRAY_BUFFER swap GL_STATIC_DRAW <gl-buffer>
74 third concat c:uint >c-array underlying>>
75 GL_ELEMENT_ARRAY_BUFFER swap GL_STATIC_DRAW <gl-buffer>
79 } cleave bunny-buffers boa ;
81 GENERIC: bunny-geom ( geom -- )
82 GENERIC: draw-bunny ( geom draw -- )
84 M: bunny-dlist bunny-geom
87 M: bunny-buffers bunny-geom
88 dup [ array>> ] [ element-array>> ] bi [
89 { GL_VERTEX_ARRAY GL_NORMAL_ARRAY } [
90 GL_FLOAT 0 0 buffer-offset glNormalPointer
92 nv>> c:float heap-size * buffer-offset
93 [ 3 GL_FLOAT 0 ] dip glVertexPointer
96 GL_TRIANGLES swap GL_UNSIGNED_INT 0 buffer-offset glDrawElements
98 ] all-enabled-client-state
99 ] with-array-element-buffers ;
101 M: bunny-dlist dispose
102 list>> delete-dlist ;
104 M: bunny-buffers dispose
105 [ array>> ] [ element-array>> ] bi
106 delete-gl-buffer delete-gl-buffer ;
108 : <bunny-geom> ( model -- geom )
109 "1.5" { "GL_ARB_vertex_buffer_object" }
110 has-gl-version-or-extensions?
111 [ <bunny-buffers> ] [ <bunny-dlist> ] if ;