|
| 1 | +module Triangle exposing (main) |
| 2 | + |
| 3 | +{- |
| 4 | + Rotating triangle, that is a "hello world" of the WebGL |
| 5 | +-} |
| 6 | + |
| 7 | +import Browser |
| 8 | +import Browser.Events exposing (onAnimationFrameDelta) |
| 9 | +import Html exposing (Html) |
| 10 | +import Html.Attributes exposing (width, height, style) |
| 11 | +import WebGL exposing (Mesh, Shader) |
| 12 | +import Math.Matrix4 as Mat4 exposing (Mat4) |
| 13 | +import Math.Vector3 as Vec3 exposing (vec3, Vec3) |
| 14 | +import Json.Decode exposing (Value) |
| 15 | + |
| 16 | + |
| 17 | +main : Program Value Float Float |
| 18 | +main = |
| 19 | + Browser.element |
| 20 | + { init = \_ -> ( 0, Cmd.none ) |
| 21 | + , view = view |
| 22 | + , subscriptions = (\_ -> onAnimationFrameDelta Basics.identity) |
| 23 | + , update = (\elapsed currentTime -> ( elapsed + currentTime, Cmd.none )) |
| 24 | + } |
| 25 | + |
| 26 | + |
| 27 | +view : Float -> Html msg |
| 28 | +view t = |
| 29 | + WebGL.toHtml |
| 30 | + [ width 400 |
| 31 | + , height 400 |
| 32 | + , style "display" "block" |
| 33 | + ] |
| 34 | + [ WebGL.entity |
| 35 | + vertexShader |
| 36 | + fragmentShader |
| 37 | + mesh |
| 38 | + { perspective = perspective (t / 1000) } |
| 39 | + ] |
| 40 | + |
| 41 | + |
| 42 | +perspective : Float -> Mat4 |
| 43 | +perspective t = |
| 44 | + Mat4.mul |
| 45 | + (Mat4.makePerspective 45 1 0.01 100) |
| 46 | + (Mat4.makeLookAt (vec3 (4 * cos t) 0 (4 * sin t)) (vec3 0 0 0) (vec3 0 1 0)) |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | +-- Mesh |
| 51 | + |
| 52 | + |
| 53 | +type alias Vertex = |
| 54 | + { position : Vec3 |
| 55 | + , color : Vec3 |
| 56 | + } |
| 57 | + |
| 58 | + |
| 59 | +mesh : Mesh Vertex |
| 60 | +mesh = |
| 61 | + WebGL.triangles |
| 62 | + [ ( Vertex (vec3 0 0 0) (vec3 1 0 0) |
| 63 | + , Vertex (vec3 1 1 0) (vec3 0 1 0) |
| 64 | + , Vertex (vec3 1 -1 0) (vec3 0 0 1) |
| 65 | + ) |
| 66 | + ] |
| 67 | + |
| 68 | + |
| 69 | + |
| 70 | +-- Shaders |
| 71 | + |
| 72 | + |
| 73 | +type alias Uniforms = |
| 74 | + { perspective : Mat4 } |
| 75 | + |
| 76 | + |
| 77 | +vertexShader : Shader Vertex Uniforms { vcolor : Vec3 } |
| 78 | +vertexShader = |
| 79 | + [glsl| |
| 80 | +
|
| 81 | + attribute vec3 position; |
| 82 | + attribute vec3 color; |
| 83 | + uniform mat4 perspective; |
| 84 | + varying vec3 vcolor; |
| 85 | +
|
| 86 | + void main () { |
| 87 | + gl_Position = perspective * vec4(position, 1.0); |
| 88 | + vcolor = color; |
| 89 | + } |
| 90 | +
|
| 91 | + |] |
| 92 | + |
| 93 | + |
| 94 | +fragmentShader : Shader {} Uniforms { vcolor : Vec3 } |
| 95 | +fragmentShader = |
| 96 | + [glsl| |
| 97 | + #extension EXT_frag_depth : enable |
| 98 | + precision mediump float; |
| 99 | + varying vec3 vcolor; |
| 100 | +
|
| 101 | + void main () { |
| 102 | + gl_FragColor = vec4(vcolor, 1.0); |
| 103 | + } |
| 104 | +
|
| 105 | + |] |
0 commit comments