on bce304a help sign in
137 lines 2.2 kB history raw
1-- elm install elm-explorations/linear-algebra
2-- elm install elm-explorations/webgl
5import Browser
6import Browser.Events as E
7import Html exposing (Html)
8import Html.Attributes exposing (width, height, style)
9import Math.Matrix4 as Mat4 exposing (Mat4)
10import Math.Vector3 as Vec3 exposing (Vec3, vec3)
11import WebGL
15-- MAIN
18main =
19 Browser.element
20 { init = init
21 , view = view
22 , update = update
23 , subscriptions = subscriptions
24 }
28-- MODEL
31type alias Model =
32 Float
35init : () -> (Model, Cmd Msg)
36init () =
37 ( 0, Cmd.none )
41-- UPDATE
44type Msg
45 = TimeDelta Float
48update : Msg -> Model -> (Model, Cmd Msg)
49update msg currentTime =
50 case msg of
51 TimeDelta delta ->
52 ( delta + currentTime, Cmd.none )
56-- SUBSCRIPTIONS
59subscriptions : Model -> Sub Msg
60subscriptions _ =
61 E.onAnimationFrameDelta TimeDelta
65-- VIEW
68view : Model -> Html msg
69view t =
70 WebGL.toHtml
71 [ width 400, height 400, style "display" "block"
72 ]
73 [ WebGL.entity vertexShader fragmentShader mesh { perspective = perspective (t / 1000) }
74 ]
77perspective : Float -> Mat4
78perspective t =
79 Mat4.mul
80 (Mat4.makePerspective 45 1 0.01 100)
81 (Mat4.makeLookAt (vec3 (4 * cos t) 0 (4 * sin t)) (vec3 0 0 0) (vec3 0 1 0))
85-- MESH
88type alias Vertex =
89 { position : Vec3
90 , color : Vec3
91 }
94mesh : WebGL.Mesh Vertex
95mesh =
96 WebGL.triangles
97 [ ( Vertex (vec3 0 0 0) (vec3 1 0 0)
98 , Vertex (vec3 1 1 0) (vec3 0 1 0)
99 , Vertex (vec3 1 -1 0) (vec3 0 0 1)
100 )
101 ]
105-- SHADERS
108type alias Uniforms =
109 { perspective : Mat4
110 }
113vertexShader : WebGL.Shader Vertex Uniforms { vcolor : Vec3 }
114vertexShader =
115 [glsl|
116 attribute vec3 position;
117 attribute vec3 color;
118 uniform mat4 perspective;
119 varying vec3 vcolor;
121 void main () {
122 gl_Position = perspective * vec4(position, 1.0);
123 vcolor = color;
124 }
125 |]
128fragmentShader : WebGL.Shader {} Uniforms { vcolor : Vec3 }
129fragmentShader =
130 [glsl|
131 precision mediump float;
132 varying vec3 vcolor;
134 void main () {
135 gl_FragColor = vec4(vcolor, 1.0);
136 }
137 |]