I decided to make a Python version of the above SDL2 C++ example. Please help me write the equivalent code using GLFW3:
maxFPS = 5.0
def main():
# ...
running = True
while running:
startTicks = SDL_GetTicks()
# Drawing ...
# Limit the FPS to the max FPS
frameTicks = SDL_GetTicks() - startTicks
if 1000.0 / maxFPS > frameTicks:
SDL_Delay(int(1000.0 / maxFPS - frameTicks))
This is a complete SDL2 example that can be run:
main.py
import ctypes
import sys
from OpenGL.GL import *
from sdl2 import *
maxFPS = 5.0
window: SDL_Window = None
def fatalError(message):
print(message)
if window:
SDL_DestroyWindow(window)
SDL_Quit()
exit(-1)
def main():
if SDL_Init(SDL_INIT_VIDEO) < 0:
fatalError(SDL_GetError())
window = SDL_CreateWindow(
b"OpenGL, SDL2, Python",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
300, 300,
SDL_WINDOW_OPENGL)
if not window:
fatalError(SDL_GetError())
context = SDL_GL_CreateContext(window)
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1)
glClearColor(0.65, 0.6, 0.85, 1.0)
event = SDL_Event()
running = True
startTicks = 0.0
frameTicks = 0.0
while running:
while SDL_PollEvent(ctypes.byref(event)) != 0:
if event.type == SDL_QUIT:
running = False
startTicks = SDL_GetTicks()
glClear(GL_COLOR_BUFFER_BIT)
SDL_GL_SwapWindow(window)
# Limit the FPS to the max FPS
frameTicks = SDL_GetTicks() - startTicks
if 1000.0 / maxFPS > frameTicks:
SDL_Delay(int(1000.0 / maxFPS - frameTicks))
SDL_GL_DeleteContext(context)
SDL_DestroyWindow(window)
SDL_Quit()
return 0
if __name__ == "__main__":
sys.exit(main())
This is the window using GLFW3:
import ctypes
import sys
from OpenGL.GL import *
import glfw
maxFPS = 5.0
window = None
def fatalError(message):
print(message)
glfw.terminate()
exit(-1)
def main():
if not glfw.init():
fatalError("Failed to init GLFW")
window = glfw.create_window(
300, 300, "OpenGL, GLFW, Python", None, None)
if not window:
fatalError("Failed to create the GLFW window")
glfw.make_context_current(window)
glClearColor(0.65, 0.6, 0.85, 1.0)
while not glfw.window_should_close(window):
glfw.poll_events()
glClear(GL_COLOR_BUFFER_BIT)
glfw.swap_buffers(window)
glfw.terminate()
return 0
if __name__ == "__main__":
sys.exit(main())