The following tip can be interesting if you have many runnable programs in the same project and want to apply extensions or behaviors to all of them.
I have over a hundred OPENRNDR programs in the same clone of openrndr-template
. Most had repeated code to
- take Screenshots by pressing the space key.
- quit by pressing ESC (something I inherited from Processing).
- be able to record video when something visually interesting happens, but not always, otherwise I’ll fill my disk with video files.
The following trick shows how to move these behaviors to a common file, so all programs have them. It involves adding a class to your openrndr-template
which extends ApplicationPreload
. For example, create the following file
openrndr-template/src/main/kotlin/org/openrndr/Preload.kt
with this content:
package org.openrndr
import org.openrndr.extensions.Screenshots
import org.openrndr.ffmpeg.ScreenRecorder
class Preload : ApplicationPreload() {
// change default window size
// override fun onConfiguration(configuration: Configuration) {
// configuration.width = 1200
// configuration.height = 600
// }
override fun onProgramSetup(program: Program) {
// 1. Add video recording
val screenRecorder = ScreenRecorder().apply {
outputToVideo = false
}
program.extend(screenRecorder)
// 2. Add screenshots (space key by default)
program.extend(Screenshots())
program.keyboard.keyDown.listen {
when {
// 3. Quit with ESC key
it.key == KEY_ESCAPE -> program.application.exit()
// Use a key to toggle video output
it.name == "v" -> {
screenRecorder.outputToVideo = !screenRecorder.outputToVideo
println("ScreenRecorder: ${if (screenRecorder.outputToVideo) "ON" else "OFF"}")
}
}
}
}
}
After adding that file I searched and deleted any uses of the Screenshots, ScreenRecorder and the ESC key quitting in my programs.
To make it work we added the outputToVideo
property the ScreenRecorder
class so it is now possible to turn video recording on and off during program execution. In the class above it is set to false by default, so no video is produced until you press the v
key. Also notice how pressing it toggles the state, allowing you to export multiple takes to the same video file.
If you come up with interesting / unique uses for the ApplicationPreload
let us know below