Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to get started with OpenTK using IronPython

📅 2013-Jun-07 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

OpenTK is a .Net library that provides a wrapper to OpenGL, OpenCL and OpenAL. Here are the first steps to get started using it with IronPython:

  1. Download and install OpenTK. The .Net assembly files of OpenTK can be found in its **OpenTK.0* directory.

  2. Create an empty IronPython solution in Visual Studio.

  3. Place OpenTK.dll in the directory of the Python source file.

  4. Paste the source code given below into the Python source file.

  5. Run. You should see a colored triangle. Press ESC to quit.

# IronPython example program to demonstrate OpenTK
#
# Steps:
# 1. Create an empty IronPython project in Visual Studio
# 2. Place OpenTK.dll in the directory of the Python source file
# 3. Paste this source code into the Python source file
# 4. Run. You should see a colored triangle. Press ESC to quit.
#
# Copyright (c) 2013 Ashwin Nanjappa
# Released under the MIT License
 
import clr
import math

clr.AddReferenceToFile("OpenTK.dll")
import OpenTK as TK
import OpenTK.Graphics.OpenGL as OGL
import OpenTK.Input as TKInput

class Game(TK.GameWindow):

    def __init__(self):
        self.VSync = TK.VSyncMode.On
        self.base = super(Game, self)

    def OnLoad(self, e):
        self.base.OnLoad(e)
        OGL.GL.ClearColor(1, 1, 1, 0.0)

    def OnResize(self, e):
        self.base.OnResize(e)
        OGL.GL.Viewport(self.ClientRectangle.X, self.ClientRectangle.Y, self.ClientRectangle.Width, self.ClientRectangle.Height)
        projection = TK.Matrix4.CreatePerspectiveFieldOfView(math.pi / 4, self.Width / self.Height, 1.0, 64.0)
        OGL.GL.MatrixMode(OGL.MatrixMode.Projection)
        OGL.GL.LoadMatrix(projection)

    def OnUpdateFrame(self, e):
        self.base.OnUpdateFrame(e)
        if self.Keyboard[TKInput.Key.Escape]:
            self.Exit()

    def OnRenderFrame(self, e):
            self.base.OnRenderFrame(e)
            OGL.GL.Clear(OGL.ClearBufferMask.ColorBufferBit)
            modelview = TK.Matrix4.LookAt(TK.Vector3.Zero, TK.Vector3.UnitZ, TK.Vector3.UnitY)
            OGL.GL.MatrixMode(OGL.MatrixMode.Modelview)
            OGL.GL.LoadMatrix(modelview)

            OGL.GL.Begin(OGL.BeginMode.Triangles)
            OGL.GL.Color3(1.0, 1.0, 0.0)
            OGL.GL.Vertex3(-1.0, -1.0, 4.0)
            OGL.GL.Color3(1.0, 0.0, 0.0)
            OGL.GL.Vertex3(1.0, -1.0, 4.0)
            OGL.GL.Color3(0.2, 0.9, 1.0)
            OGL.GL.Vertex3(0.0, 1.0, 4.0)
            OGL.GL.End()

            self.SwapBuffers()

def main():
    game = Game()
    game.Run(30)

if "__main__" == __name__:
    main()

Tried with: OpenTK 1.0, IronPython 2.7.3, Visual Studio Express 2012 and Windows 7 x64