# accpersp.tcl
#
# An example of the OpenGL red book modified to work with Tcl3D.
# The original C sources are Copyright (c) 1993-2003, Silicon Graphics, Inc.
# The Tcl3D sources are Copyright (c) 2005-2022, Paul Obermeier.
# See file LICENSE for complete license information.
#
# Use the accumulation buffer to do full-scene antialiasing
# on a scene with perspective projection, using the special
# routines accFrustum() and accPerspective().

package require tcl3d

source [file join [file dirname [info script]] "jitter.tclinc"]

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

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

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

# The first 6 arguments are identical to the glFrustum() call.
#  
# pixdx and pixdy are anti-alias jitter in pixels. 
# Set both equal to 0.0 for no anti-alias jitter.
# eyedx and eyedy are depth-of field jitter in pixels. 
# Set both equal to 0.0 for no depth of field effects.
#
# focus is distance from eye to plane in focus. 
# focus must be greater than, but not equal to 0.0.
#
# Note that accFrustum() calls glTranslatef().  You will 
# probably want to insure that your ModelView matrix has been 
# initialized to identity before calling accFrustum().
#
proc accFrustum { left right bottom top near far \
                  pixdx pixdy eyedx eyedy focus } {

    set viewport [tcl3dOglGetViewport]

    set xwsize [expr $right - $left]
    set ywsize [expr $top - $bottom]

    set dx [expr -($pixdx*$xwsize/double([lindex $viewport 2]) + \
                   $eyedx*$near/$focus)]
    set dy [expr -($pixdy*$ywsize/double([lindex $viewport 3]) + \
                   $eyedy*$near/$focus)]

    glMatrixMode GL_PROJECTION
    glLoadIdentity
    glFrustum [expr $left + $dx] [expr $right + $dx] \
              [expr $bottom + $dy] [expr $top + $dy] $near $far
    glMatrixMode GL_MODELVIEW
    glLoadIdentity
    glTranslatef [expr -1.0 * $eyedx] [expr -1.0 * $eyedy] 0.0
}

# The first 4 arguments are identical to the gluPerspective() call.
# pixdx and pixdy are anti-alias jitter in pixels. 
# Set both equal to 0.0 for no anti-alias jitter.
# eyedx and eyedy are depth-of field jitter in pixels. 
# Set both equal to 0.0 for no depth of field effects.
#
# focus is distance from eye to plane in focus. 
# focus must be greater than, but not equal to 0.0.
#
# Note that accPerspective() calls accFrustum().
#
proc accPerspective { fovy aspect near far pixdx pixdy \
                      eyedx eyedy focus } {

    set PI_ 3.14159265358979323846
    set fov2 [expr (($fovy*$PI_) / 180.0) / 2.0]

    set top    [expr $near / (cos($fov2) / sin($fov2))]
    set bottom [expr -1 * $top]

    set right [expr $top * $aspect]
    set left  [expr -1 * $right]

    accFrustum $left $right $bottom $top $near $far \
               $pixdx $pixdy $eyedx $eyedy $focus
}

# Initialize lighting and other values.
#
proc CreateCallback { toglwin } {
    set mat_ambient    { 1.0 1.0  1.0 1.0 }
    set mat_specular   { 1.0 1.0  1.0 1.0 }
    set light_position { 0.0 0.0 10.0 1.0 }
    set lm_ambient     { 0.2 0.2  0.2 1.0 }

    glMaterialfv GL_FRONT GL_AMBIENT $mat_ambient
    glMaterialfv GL_FRONT GL_SPECULAR $mat_specular
    glMaterialf GL_FRONT GL_SHININESS 50.0
    glLightfv GL_LIGHT0 GL_POSITION $light_position
    glLightModelfv GL_LIGHT_MODEL_AMBIENT $lm_ambient

    glEnable GL_LIGHTING
    glEnable GL_LIGHT0
    glEnable GL_DEPTH_TEST
    glShadeModel GL_FLAT

    glClearColor 0.0 0.0 0.0 0.0
    glClearAccum 0.0 0.0 0.0 0.0
}

proc displayObjects {} {
   set torus_diffuse  { 0.7 0.7 0.0 1.0 }
   set cube_diffuse   { 0.0 0.7 0.7 1.0 }
   set sphere_diffuse { 0.7 0.0 0.7 1.0 }
   set octa_diffuse   { 0.7 0.4 0.4 1.0 }
    
   glPushMatrix
   glTranslatef 0.0 0.0 -5.0 
   glRotatef 30.0 1.0 0.0 0.0

   glPushMatrix
   glTranslatef -0.80 0.35 0.0 
   glRotatef 100.0 1.0 0.0 0.0
   glMaterialfv GL_FRONT GL_DIFFUSE $torus_diffuse
   glutSolidTorus 0.275 0.85 16 16
   glPopMatrix

   glPushMatrix
   glTranslatef -0.75 -0.50 0.0 
   glRotatef 45.0 0.0 0.0 1.0
   glRotatef 45.0 1.0 0.0 0.0
   glMaterialfv GL_FRONT GL_DIFFUSE $cube_diffuse
   glutSolidCube 1.5
   glPopMatrix

   glPushMatrix
   glTranslatef 0.75 0.60 0.0 
   glRotatef 30.0 1.0 0.0 0.0
   glMaterialfv GL_FRONT GL_DIFFUSE $sphere_diffuse
   glutSolidSphere 1.0 16 16
   glPopMatrix

   glPushMatrix
   glTranslatef 0.70 -0.90 0.25
   glMaterialfv GL_FRONT GL_DIFFUSE $octa_diffuse
   glutSolidOctahedron
   glPopMatrix

   glPopMatrix
}

proc DisplayCallback { toglwin } {
    set ACSIZE 8

    # Viewport command is not really needed, but has been inserted for
    # Mac OSX. Presentation framework (Tk) does not send a reshape event,
    # when switching from one demo to another.
    glViewport 0 0 [$toglwin width] [$toglwin height]

    set viewport [tcl3dOglGetViewport]

    glClear GL_ACCUM_BUFFER_BIT
    for { set jitter 0 } { $jitter < $ACSIZE } { incr jitter } {
        glClear [expr $::GL_COLOR_BUFFER_BIT | $::GL_DEPTH_BUFFER_BIT]
        set jitPnt [lindex $::j($ACSIZE) $jitter]
        accPerspective 50.0 \
                       double([lindex $viewport 2])/double([lindex $viewport 3]) \
                       1.0 15.0 \
                       [lindex $jitPnt 0] \
                       [lindex $jitPnt 1] \
                       0.0 0.0 1.0
        displayObjects
        glAccum GL_ACCUM [expr 1.0 / $ACSIZE]
    }
    glAccum GL_RETURN 1.0
    glFlush
    $toglwin swapbuffers
}


proc ReshapeCallback { toglwin { w -1 } { h -1 } } {
    set w [$toglwin width]
    set h [$toglwin height]

    glViewport 0 0 $w $h
}

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

# Create a Togl window using an accumulation buffer.
# Reshape and Display callbacks are configured later after knowing if
# the needed accumulation buffer is available.
set retVal [catch { togl .fr.toglwin \
    -width 400 -height 400 \
    -double true -accum true -depth true \
    -createcommand CreateCallback } errMsg]
if { $retVal != 0 } {
    tk_messageBox -icon error -type ok -title "Missing Togl feature" \
                  -message "Demo needs accumulation buffer: $errMsg"
    proc ::Cleanup {} {}
    exit 1
    return
}

.fr.toglwin configure \
    -reshapecommand ReshapeCallback \
    -displaycommand DisplayCallback 

listbox .fr.usage -font $::listFont -height 1
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: OpenGL Red Book example accpersp"

bind . <Key-Escape> "exit"

.fr.usage insert end "Key-Escape Exit"
.fr.usage configure -state disabled

PrintInfo [tcl3dOglGetInfoString]
