commonMain.ru.casperix.opengl.renderer.ShaderCompiler.kt Maven / Gradle / Ivy
package ru.casperix.opengl.renderer
import ru.casperix.opengl.core.*
import ru.casperix.opengl.core.misc.GLErrorPrinter
import ru.casperix.opengl.core.misc.ShaderErrorParser
object ShaderCompiler {
fun compile(vertexShaderSource: String, fragmentShaderSource: String): GLuint {
val vertexShader = compile(vertexShaderSource, GL_VERTEX_SHADER)
val fragmentShader = compile(fragmentShaderSource, GL_FRAGMENT_SHADER)
val shaderProgram = glCreateProgram()
glAttachShader(shaderProgram, vertexShader)
glAttachShader(shaderProgram, fragmentShader)
glLinkProgram(shaderProgram)
val programSuccess = glGetProgrami(shaderProgram, GL_LINK_STATUS)
if (programSuccess != 1) {
throw Error("Invalid program")
}
glUseProgram(shaderProgram)
glDeleteShader(vertexShader)
glDeleteShader(fragmentShader)
GLErrorPrinter.throwIfExist()
return shaderProgram
}
private fun compile(shaderSource: String, type: GLenum): GLuint {
val vertexShader = glCreateShader(type)
glShaderSource(vertexShader, shaderSource)
glCompileShader(vertexShader)
val vertexShaderSuccess = glGetShaderi(vertexShader, GL_COMPILE_STATUS)
if (vertexShaderSuccess != 1) {
println(ShaderErrorParser.get(shaderSource, vertexShader))
throw Error("Invalid shader:\n\n$shaderSource")
}
return vertexShader
}
}