All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.ru.casperix.opengl.renderer.texture.GLTexture2DArray.kt Maven / Gradle / Ivy

package ru.casperix.opengl.renderer.texture

import ru.casperix.opengl.core.*
import ru.casperix.opengl.renderer.texture.GLTexture.Companion.asGLMagFilter
import ru.casperix.opengl.renderer.texture.GLTexture.Companion.asGLMinFilter
import ru.casperix.opengl.renderer.texture.GLTexture.Companion.asGLWrap
import ru.casperix.renderer.material.Texture2DArray
import ru.casperix.renderer.pixel_map.PixelMap

class GLTexture2DArray(val texture: Texture2DArray) : GLTexture {
    val handle = glGenTexture()

//	constructor(colorProvider: ColorCube) : this(colorProvider.minX, colorProvider.maxX, colorProvider.minY, colorProvider.maxY, colorProvider.minZ, colorProvider.maxZ)

    class PixelMap3D(val bytes: UByteArray, val width: Int, val height: Int, val depth: Int)

    init {
        glBindTexture(GL_TEXTURE_2D_ARRAY, handle)
        texture.config.apply {
            glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, asGLWrap(uWrap))
            glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, asGLWrap(vWrap))
            glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_R, asGLWrap(wWrap))
            glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, asGLMinFilter(minFilter, useMipMap))
            glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, asGLMagFilter(magFilter, useMipMap))
        }
        texture.apply {
            val bytes = toMap3D(maps)
            loadData(bytes, maps.size)
        }
        if (texture.config.useMipMap) {
            glGenerateMipmap(GL_TEXTURE_2D_ARRAY)
        }
        glBindTexture(GL_TEXTURE_2D_ARRAY, 0)
    }


    private fun toMap3D(maps: List): PixelMap3D {
        if (maps.isEmpty()) return PixelMap3D(UByteArray(0), 0, 0, 0)

        val map = maps.first()

        val size = map.bytes.data.size
        val output = UByteArray(size * maps.size)

        maps.forEachIndexed { index, pixelMap ->
            if (pixelMap.bytes.data.size != size) {
                throw Exception("Don't support not equal size pixel-map")
            }
            pixelMap.bytes.data.copyInto(output, index * size)
        }

        return PixelMap3D(output, map.width, map.height, maps.size)
    }

    override fun dispose() {
        glDeleteTexture(handle)
    }

    private fun loadData(map: PixelMap3D, layerAmount: Int) {
        glTexImage3D(
            GL_TEXTURE_2D_ARRAY,
            0,
            GL_RGBA,
            map.width,
            map.height,
            layerAmount,
            0,
            GL_RGBA,
            GL_UNSIGNED_BYTE,
            map.bytes.toByteArray()
        )
    }

    override fun bind(channel: Int) {
        glActiveTexture(GL_TEXTURE0 + channel)
        glBindTexture(GL_TEXTURE_2D_ARRAY, handle)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy