Skip to content

Instantly share code, notes, and snippets.

@moschlar
Created December 11, 2011 12:50
Show Gist options
  • Save moschlar/1460439 to your computer and use it in GitHub Desktop.
Save moschlar/1460439 to your computer and use it in GitHub Desktop.
Travelling Salesman Problem visualized with pyopengl
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 09.12.2011
@author: moschlar
'''
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from sa import *
from tsp import *
def init():
# Color for filling
glClearColor (0.0, 0.0, 0.0, 0.0)
#glShadeModel (GL_SMOOTH)
#glEnable(GL_LIGHTING)
#glEnable(GL_LIGHT0)
# Store z coordinates and don't redraw if unnecessary
glEnable(GL_DEPTH_TEST)
def display():
# Calculate state
cities = [(1,2),(4,3),(4,4),(6,6),(7,1),(2,9)]
tour = [0,1,2,3,4,5]
# State-machine
# Clear viewport color information and depth information
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity ()
# glScaled(2, 2, 2) # ZOOOOOOM
# Draw cities
glPointSize(10)
glColor3d (0.0, 0.0, 1.0)
glBegin(GL_POINTS)
for x,y in cities:
print x,y
glVertex2d(float(x)/10,float(y)/10)
#glVertex2d(0, 0.1)
#glVertex2d(0.1, 0.1)
glEnd()
# Draw route
glLineWidth(2)
glColor3d (1.0, 0.0, 0.0)
glBegin(GL_LINE_LOOP)
for city in tour:
x,y = cities[city]
glVertex2d(float(x)/10,float(y)/10)
glEnd()
glBegin(GL_LINES)
glVertex2d(0, 0.1)
glVertex2d(0.1, 0.1)
glEnd()
#glRotated(0.1,1,1,1)
#glColor3d(0.0, 1.0, 1.0)
#glBegin(GL_QUADS)
#glNormal3d(0,0,1)
#glVertex3d(-0.1,-0.1,0)
#glNormal3d(0,0,1)
#glVertex3d(-0.1,+0.1,0)
#glNormal3d(0,0,1)
#glVertex3d(+0.1,+0.1,0)
#glNormal3d(0,0,1)
#glVertex3d(+0.1,-0.1,0)
#glEnd()
# Redraw by swapping buffers
glutSwapBuffers()
# Re-call display()
# glutPostRedisplay()
def reshape (w, h):
glViewport (0, 0, w, h)
# Set matrix mode for projection
glMatrixMode (GL_PROJECTION)
# Put identity on projection stack
glLoadIdentity ()
# Define coordinate system
# left right bottom top near far
glOrtho (0.0, 1.0, 0.0, 1.0, -10.0, 10.0)
# Set matrix mode for
glMatrixMode (GL_MODELVIEW)
if __name__ == '__main__':
# GLUT boiler plate
glutInit()
# Double buffered, Colors
glutInitDisplayMode (GLUT_DOUBLE| GLUT_RGB)
glutInitWindowSize (500, 500)
glutInitWindowPosition (100, 100)
glutCreateWindow ('simulated annealing')
init ()
glutDisplayFunc(display)
glutReshapeFunc(reshape)
glutMainLoop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment