Demo Example12

Demo 11 of 13 in category Nopper

Previous demo: poThumbs/Example11.jpgExample11
Next demo: poThumbs/Example13.jpgExample13
Example12.jpg
#
# OpenGL 4.0 with GLEW - Example 12
#
# @author  Norbert Nopper norbert@nopper.tv
# @version 1.0
#
# Homepage: https://github.com/McNopper/OpenGL
#
# Copyright Norbert Nopper
#
# Modified for Tcl3D by Paul Obermeier 2011/02/03
# See www.tcl3d.org for the Tcl3D extension.

package require Tk
package require tcl3d

# Font to be used in the Tk listbox.
set g_Demo(listFont) {-family {Courier} -size 10}

# Obtain the name of this script file.
set g_Demo(scriptDir) [file dirname [info script]]

# Window size.
set g_Demo(winWidth)  640
set g_Demo(winHeight) 480

# Projection matrix. 
set g_Demo(projection) [tcl3dVector GLfloat 16]

# Move the cube along the minus z axis for making it visible. Also rotated.
set g_Demo(modelView) [tcl3dVector GLfloat 16]

# The VAO for the vertices etc.
set g_Demo(vao) [tcl3dVector GLuint 1]

# The VBO for the vertices.
set g_Demo(vertices) [tcl3dVector GLuint 1]

# The VBO for the indices.
set g_Demo(indices) [tcl3dVector GLuint 1]

# The indices for the patch
set g_Demo(planeIndices) [tcl3dVectorFromArgs GLuint 0 1 3 2]

# The number of indices
set g_Demo(numberIndices) 4

set g_Demo(angle) 0.0

# A stop watch to get current time.
set g_Demo(stopWatch) [tcl3dNewSwatch]
tcl3dStartSwatch $g_Demo(stopWatch)
set g_Demo(lastTime) [tcl3dLookupSwatch $g_Demo(stopWatch)]

# Show errors occuring in the Togl callbacks.
proc bgerror { msg } {
    tk_messageBox -icon error -type ok -message "Error: $msg\n\n$::errorInfo"
    ExitProg
}

# Print info message into widget a the bottom of the window.
proc PrintInfo { msg } {
    if { [winfo exists .fr.info] } {
        .fr.info configure -text $msg
    }
}

proc Animate {} {
    global g_Demo

    .fr.toglwin postredisplay
    set g_Demo(animateId) [tcl3dAfterIdle Animate]
}

proc StartAnimation {} {
    global g_Demo

    if { ! [info exists g_Demo(animateId)] } {
        Animate
        tcl3dStartSwatch $g_Demo(stopWatch)
    }
}

proc StopAnimation {} {
    global g_Demo

    if { [info exists g_Demo(animateId)] } {
        after cancel $g_Demo(animateId)
        unset g_Demo(animateId)
        tcl3dStopSwatch $g_Demo(stopWatch)
    }
}

proc Init {} {
    global g_Demo

    set plane [glusCreatePlane 1.0 1.0]

    # Load the source of the vertex shader.
    set vertexSource [tcl3dOglReadShaderFile [file join $g_Demo(scriptDir) "Vertex.vs"]]

    # Load the source of the control shader.
    set controlSource [tcl3dOglReadShaderFile [file join $g_Demo(scriptDir) "Control.tcs"]]

    # Load the source of the evaluation shader.
    set evaluationSource [tcl3dOglReadShaderFile [file join $g_Demo(scriptDir) "Evaluation.tes"]]

    # Load the source of the geometry shader.
    set geometrySource [tcl3dOglReadShaderFile [file join $g_Demo(scriptDir) "Geometry.gs"]]

    # Load the source of the fragment shader.
    set fragmentSource [tcl3dOglReadShaderFile [file join $g_Demo(scriptDir) "Fragment.fs"]]

    set g_Demo(program) [tcl3dOglBuildProgram $vertexSource $controlSource $evaluationSource \
                                              $geometrySource $fragmentSource]
    set program [dict get $g_Demo(program) program]

    glGenVertexArrays 1 $g_Demo(vao)
    glBindVertexArray [$g_Demo(vao) get 0]

    set g_Demo(projectionLocation) [glGetUniformLocation $program "projectionMatrix"]
    set g_Demo(modelViewLocation)  [glGetUniformLocation $program "modelViewMatrix"]
    set g_Demo(vertexLocation)     [glGetAttribLocation  $program "vertex"]

    glGenBuffers 1 $g_Demo(vertices)
    glBindBuffer GL_ARRAY_BUFFER [$g_Demo(vertices) get 0]
    set vertexVec [dict get $plane vertexVec]
    glBufferData GL_ARRAY_BUFFER \
                 [expr [dict get $plane numVertices]*4*[$vertexVec elemsize]] \
                 $vertexVec GL_STATIC_DRAW

    glGenBuffers 1 $g_Demo(indices)
    glBindBuffer GL_ELEMENT_ARRAY_BUFFER [$g_Demo(indices) get 0]
    glBufferData GL_ELEMENT_ARRAY_BUFFER [expr $g_Demo(numberIndices)*4] \
                 $g_Demo(planeIndices) GL_STATIC_DRAW

    glusDestroyShape $plane

    glUseProgram $program

    glBindBuffer GL_ARRAY_BUFFER [$g_Demo(vertices) get 0]

    glVertexAttribPointer $g_Demo(vertexLocation) 4 GL_FLOAT GL_FALSE 0 "NULL"

    glEnableVertexAttribArray $g_Demo(vertexLocation)
}

proc CreateCallback { toglwin } {
    glClearColor 0.0 0.0 0.0 0.0
    glClearDepth 1.0
    glEnable GL_DEPTH_TEST
    glEnable GL_CULL_FACE
}

proc ReshapeCallback { toglwin { w -1 } { h -1 } } {
    global g_Demo

    set w [$toglwin width]
    set h [$toglwin height]
    set g_Demo(winWidth)  $w
    set g_Demo(winHeight) $h

    glViewport 0 0 $w $h

    if { ! $g_Demo(haveNeededVersion) } {
        return
    }

    tcl3dPerspective 40.0 [expr double($w)/double($h)] 1.0 100.0 $g_Demo(projection)

    set projectionAsList [tcl3dVectorToList $g_Demo(projection) 16]
    glUniformMatrix4fv $g_Demo(projectionLocation) 1 GL_FALSE $projectionAsList
}

proc DisplayCallback { toglwin } {
    global g_Demo

    glClear [expr $::GL_COLOR_BUFFER_BIT | $::GL_DEPTH_BUFFER_BIT]

    if { ! $g_Demo(haveNeededVersion) } {
        $toglwin swapbuffer
        return
    }

    glPatchParameteri GL_PATCH_VERTICES 4
    glDrawElements GL_PATCHES $g_Demo(numberIndices) GL_UNSIGNED_INT "NULL"

    set model [tcl3dVector GLfloat 16]
    tcl3dMatfIdentity $model
    tcl3dMatfRotateY $g_Demo(angle) $model
    tcl3dLookAt 0.0 0.0 5.0 0.0 0.0 0.0 0.0 1.0 0.0 $g_Demo(modelView)
    tcl3dMatfMult $g_Demo(modelView) $model $g_Demo(modelView)
    $model delete

    set modelViewAsList [tcl3dVectorToList $g_Demo(modelView) 16]
    glUniformMatrix4fv $g_Demo(modelViewLocation) 1 GL_FALSE $modelViewAsList

    set curTime [tcl3dLookupSwatch $g_Demo(stopWatch)]
    set elapsedTime [expr $curTime - $g_Demo(lastTime)]
    set g_Demo(lastTime) $curTime
    set g_Demo(angle) [expr $g_Demo(angle) + 30.0 * $elapsedTime]

    $toglwin swapbuffer
}

proc Cleanup {} {
    global g_Demo

    if { [info exists g_Demo(vertices)] } {
        glDeleteBuffers 1 [$g_Demo(vertices) get 0]
        $g_Demo(vertices) delete
    }

    if { [info exists g_Demo(indices)] } {
        glDeleteBuffers 1 [$g_Demo(indices) get 0]
        $g_Demo(indices) delete
    }

    if { [info exists g_Demo(vao)] } {
        glDeleteVertexArrays 1 [$g_Demo(vao) get 0]
        $g_Demo(vao) delete
    }

    if { [info exists g_Demo(program)] } {
        tcl3dOglDestroyProgram $g_Demo(program)
    }

    tcl3dDeleteSwatch $g_Demo(stopWatch)

    # Unset all global variables. 
    # Needed when running the demo in the Tcl3D presentation framework.
    foreach var [info globals g_*] {
        uplevel #0 unset $var
    }
}

# Put all exit related code here.
proc ExitProg {} {
    exit
}

# Create the OpenGL window and some Tk helper widgets.
proc CreateWindow {} {
    global g_Demo

    frame .fr
    pack .fr -expand 1 -fill both

    # Create a Togl window with an OpenGL core profile using version 3.3.
    # Reshape and Display callbacks are configured later after knowing if
    # the needed OpenGL profile version is available.
    togl .fr.toglwin -width $g_Demo(winWidth) -height $g_Demo(winHeight) \
                     -double true -depth true -alpha true \
                     -createcommand CreateCallback \
                     -coreprofile true -major 4 -minor 0

    set g_Demo(haveNeededVersion) true
    set numRows 2
    set haveGL4 [tcl3dOglHaveVersion 4]
    if { ! $haveGL4 } {
        set msgStr [format \
            "Demo needs core profile 4.0. Only have GL version %s" \
            [tcl3dOglGetVersion]]
        set g_Demo(haveNeededVersion) false
        incr numRows
    } else {
        set profile [tcl3dOglGetProfile .fr.toglwin]
        if { [dict get $profile "coreprofile"] != true } {
            set msgStr [format \
                "Demo needs core profile 4.0. Only have compatibility profile %d.%d" \
                [dict get $profile "major"] \
                [dict get $profile "minor"]]
            incr numRows
        }
    }
    if { $g_Demo(haveNeededVersion) } {
        # If OpenGL 4.0 or higher is available, initialize the buffers.
        Init
    }

    # Now attach the Reshape and Display callbacks to the Togl window.
    .fr.toglwin configure \
        -reshapecommand ReshapeCallback \
        -displaycommand DisplayCallback

    listbox .fr.usage -font $g_Demo(listFont) -height $numRows
    label .fr.info
    grid .fr.toglwin -row 0 -column 0 -sticky news
    grid .fr.usage   -row 1 -column 0 -sticky news
    grid .fr.info    -row 2 -column 0 -sticky news
    grid rowconfigure .fr 0 -weight 1
    grid columnconfigure .fr 0 -weight 1
    wm title . "Tcl3D demo: Nopper's core profile tutorials (Example 12 - Simple tessellation)"

    # Watch for Esc key and Quit messages
    wm protocol . WM_DELETE_WINDOW "ExitProg"
    bind . <Key-Escape> "ExitProg"

    bind .fr.toglwin <1> "StartAnimation"
    bind .fr.toglwin <2> "StopAnimation"
    bind .fr.toglwin <3> "StopAnimation"
    bind .fr.toglwin <Control-Button-1> "StopAnimation" 

    .fr.usage insert end "Key-Escape Exit"
    .fr.usage insert end "Mouse-L|MR Start|Stop animation"
    if { [info exists msgStr] } {
        .fr.usage insert end $msgStr
        .fr.usage itemconfigure end -background red
    } else {
        .fr.usage configure -state disabled
    }
}

CreateWindow
ReshapeCallback .fr.toglwin

PrintInfo [tcl3dOglGetInfoString]

if { [file tail [info script]] eq [file tail $::argv0] } {
    # If started directly from tclsh or wish, then start animation.
    update
    StartAnimation
}

Top of page