norman784
05/25/2018, 12:20 PMimport cglew.glewExperimental
import cglew.glewInit
import cglew.GLEW_OK
import cglew.glClear
import cglfw.*
import kotlinx.cinterop.*
import platform.OpenGL3.*
fun main(args: Array<String>) {
glewExperimental = GL_TRUE.narrow()
if (glfwInit() == GL_FALSE) {
throw Error("Failed to initialize GLFW")
}
glfwWindowHint(GL_SAMPLES, 4)
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3)
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3)
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE)
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE)
val window = glfwCreateWindow(1024, 768, "GLLab", null, null) ?:
throw Error("Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.")
glfwMakeContextCurrent(window)
glewExperimental = GL_TRUE.narrow()
if (glewInit() != GLEW_OK) {
throw Error("Failed to initialize GLEW")
}
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE)
val vertexArrayId: Int = memScoped {
val resultVar: IntVarOf<Int> = alloc()
glGenVertexArrays(1, resultVar.ptr)
resultVar.value
}
glBindVertexArray(vertexArrayId)
checkError()
val vertexBufferData: FloatArray = floatArrayOf(
-1f, -1f, 0f,
1f, -1f, 0f,
0f, 1f, 0f
)
val vertexBuffer: Int = generateBuffer()
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer)
glBufferData(GL_ARRAY_BUFFER, (vertexBufferData.size * 4).signExtend(), vertexBufferData.toCValues(), GL_STATIC_DRAW)
checkError()
while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0) {
glClear(GL_COLOR_BUFFER_BIT)
glEnableVertexAttribArray(0)
checkError()
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer)
checkError()
glVertexAttribPointer(
0,
3,
GL_FLOAT,
GL_FALSE.narrow(),
0,
null
)
checkError()
platform.OpenGL.glDrawArrays(GL_TRIANGLES, 0, 3)
checkError()
glDisableVertexAttribArray(0)
checkError()
glfwSwapBuffers(window)
glfwPollEvents()
}
glfwTerminate()
}
fun generateBuffer(): Int = memScoped {
val bufferVar: IntVarOf<Int> = alloc()
glGenBuffers(1, bufferVar.ptr)
bufferVar.value
}
fun checkError() {
val error = glGetError()
if (error != 0) {
val errorString = when (error) {
GL_INVALID_ENUM -> "GL_INVALID_ENUM"
GL_INVALID_VALUE -> "GL_INVALID_VALUE"
GL_INVALID_OPERATION -> "GL_INVALID_OPERATION"
GL_INVALID_FRAMEBUFFER_OPERATION -> "GL_INVALID_FRAMEBUFFER_OPERATION"
GL_OUT_OF_MEMORY -> "GL_OUT_OF_MEMORY"
else -> "unknown"
}
throw Exception("GL error: 0x${error.toString(16)} ($errorString)")
}
}
cglew.def
headers = GL/glew.h
headerFilter = GL/*
compilerOpts.osx = -I/usr/include -I/usr/local/include
linkerOpts.osx = -L/usr/lib -L/usr/local/lib -lglew
linkerOpts.linux = -L/usr/lib/x86_64-linux-gnu -lglew
cglfw.def
headers = GLFW/glfw3.h
headerFilter = GLFW/*
compilerOpts.osx = -I/usr/include -I/usr/local/include
linkerOpts.osx = -L/usr/lib -L/usr/local/lib -lglfw
linkerOpts.linux = -L/usr/lib/x86_64-linux-gnu -lglfw