Search code examples
pythonsimulationframe-ratepyglet

Pyglet application framerate appears to speed up each time it is restarted


I am working on a basic simulation in pyglet, which I need to re-run and visualise multiple times. The simulation adjusts the focus "f" of a lens until it reaches the desired location (see gif here https://i.sstatic.net/NTDOC.jpg). I have put an instance of the simulation inside a for loop along with a pyglet.app.run() loop running inside it also, so that it can be reset and run for 10 episodes.

num_episodes=10
for i in range(num_episodes):
    update_rate=1/59
    simulation=PivotPointSimulation()
    pyglet.clock.schedule_interval(update, update_rate)
    pyglet.app.run()

I need to make an instance of the "simulation" so that the draw and update methods can be called by pyglet.app.run(). By making a new instance each loop, I can also reset the variables when the simulation starts again. I terminate the simulation when the focus "f" of the lens reaches the desired position with pyglet.app.exit().

The problem is each time the for loop iterates, the framerate of my pyglet application speeds up (see gif for example https://i.sstatic.net/NTDOC.jpg). I have checked if the update_rate is changing and it is staying the same. Peculiarly enough, when I use spyders stop button to stop the code, and run the simulation again with "play" the framerate of the simulation also gets faster and faster each time I hit stop and play.

I am wondering if there is a way to properly terminate an app, so that each time it runs again it is reset fully? I am unsure if pyglet.app.exit() is resetting everything properly. But I am not sure how the app is speeding up, since pyglet.clock.schedule_interval(update, update_rate) should update at a constant update rate.

I have tried playing around with Vsync settings (setting from false to true) and it hasn't helped. I have also tried using pyglet.clock.set_fps_limit(60) to no avail. So I am not sure what is going on here.

Has anyone encountered this problem before?


Solution

  • Every time you call pyglet.clock.schedule_interval(update, update_rate), it adds the callback to be called at the rate.

    So at the end of your loop of 10, you have the same callback scheduled ten times.

    One way to prevent this is to unschedule the function before so that it isn't scheduled a second time:

    num_episodes=10
    for i in range(num_episodes):
        update_rate=1/59
        simulation=PivotPointSimulation()
        pyglet.clock.unschedule(update)   
        pyglet.clock.schedule_interval(update, update_rate)
        pyglet.app.run()