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

commonMain.ru.casperix.opengl.renderer.TextureProvider.kt Maven / Gradle / Ivy

There is a newer version: 1.3.0
Show newest version
package ru.casperix.opengl.renderer

import ru.casperix.math.collection.LRUCache
import ru.casperix.opengl.renderer.texture.GLTexture
import ru.casperix.opengl.renderer.texture.GLTexture2D
import ru.casperix.opengl.renderer.texture.GLTexture2DArray
import ru.casperix.opengl.renderer.texture.GLTextureCube
import ru.casperix.renderer.material.Texture
import ru.casperix.renderer.material.Texture2D
import ru.casperix.renderer.material.Texture2DArray
import ru.casperix.renderer.material.TextureCube

class TextureProvider {
    private val smallTextureCache = LRUCache(1024, false)
    private val mediumTextureCache = LRUCache(256, false)
    private val largeTextureCache = LRUCache(64, false)
    private val otherTextureCache = LRUCache(32, false)

    private fun getTextureCache(texture: Texture): LRUCache {
        return if (texture is Texture2D) {
            val volume = texture.map.dimension.volume()
            if (volume <= 16384) {
                smallTextureCache
            } else if (volume <= 65536) {
                mediumTextureCache
            } else {
                largeTextureCache
            }
        } else {
            otherTextureCache
        }
    }

    fun getTexture(texture: Texture): GLTexture {
        val cache = getTextureCache(texture)
        return cache.getOrPut(texture) {
            createTexture(texture)
        }.apply {
            cache.removeOldest()?.dispose()
        }
    }

    private fun createTexture(texture: Texture) = when (texture) {
        is Texture2D -> GLTexture2D(texture)
        is Texture2DArray -> GLTexture2DArray(texture)
        is TextureCube -> GLTextureCube(texture)
        else -> throw Exception("Unsupported texture type: ${texture::class.simpleName}")
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy