Rendering a Wavefront Obj file in Canvas3d

The Canvas3d provides 3d rendering to Tcl/Tk. But serious 3d work requires integrating externally produced models into one's application's visuals. The following is a route to read basic vertex data out of a Wavefront Obj file , and render that object on the canvas.

Note: This import routine only imports basic vertex and face data. Normals and textures are ignored.

###
# Title: opengl_render_obj_file
# Arguments: 
#   canvas - A canvas3d widget
#   tags - Tags to apply to the newly created object
#   filename - A path to a file in Wavefront Obj format
###
proc opengl_render_obj_file {canvas tags filename} {  
    set line_count 0
    set vertex_count 0
    set face_count 0
    set group {}
    set object {}
    
    foreach line [split $text \n] {
      switch [string range $line 0 1] {
        "g" {
          # Faces can be broken up into groups
          # We implement them as tags
          set group [lrange $line 1 end]
        }
        "o " {
          # Modes can be broken up into multiple objects
          # We implement them as tags
          set object [lrange $line 1 end]
        }
        "v " {
          set vertex_xyz([incr vertex_count]) [lrange $line 1 end]
        }
        "f " {
          set coords {}
          foreach point [lrange $line 1 end] {
            set vertex [lindex [split $point /] 0]
            lappend coords {*}$vertex_xyz($vertex)
          }
          $canvas create polygon ${coords} -tags [list {*}$tags {*}$group {*}$object]
        }
      }
    }
  }
}

AK - 2013-05-01 16:00:17

Other wiki pages of interest:

Also referencing wavefront.