aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/TextureManager.kt
blob: 41da09520681e6c5f83e88e2e88c98628af170f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import kotlinx.browser.document
import org.khronos.webgl.get
import org.w3c.dom.CanvasRenderingContext2D
import org.w3c.dom.HTMLCanvasElement
import org.w3c.dom.HTMLImageElement
import org.w3c.dom.asList

class TextureManager {

  private lateinit var textures: List<Texture>

  fun getTexture(id: Int): Texture {
    return textures.find { it.id == id } ?: textures.first()
  }

  fun loadTextures(set: String) {
    textures = document.getElementsByClassName("texture-definition").asList()
      .map { it as HTMLImageElement }
      .filter { it.getAttribute("data-set") == set }
      .map {
        val id = it.getAttribute("data-texture-id")!!.toInt()
        val width = it.getAttribute("data-width")?.toInt() ?: 64
        val height = it.getAttribute("data-height")?.toInt() ?: 64
        Texture(id, width, height, parseImage(it, width, height))
      }

    Logger.log("Loaded ${textures.size} texture(s)")
  }

  private fun parseImage(image: HTMLImageElement, imageWidth: Int, imageHeight: Int): List<String> {
    val canvas = (document.createElement("canvas") as HTMLCanvasElement)
      .apply {
        width = imageWidth
        height = imageHeight
      }

    // Draw image to canvas and read back out to get RGBA data
    val imageData = with(canvas.getContext("2d") as CanvasRenderingContext2D) {
      drawImage(image, 0.0, 0.0, imageWidth.toDouble(), imageHeight.toDouble())
      getImageData(0.0, 0.0, imageWidth.toDouble(), imageHeight.toDouble()).data
    }

    val cssColourPixelList = mutableListOf<String>()
    for (i in 0 until imageData.length step 4) {
      cssColourPixelList.add("rgb(${imageData[i]},${imageData[i+1]},${imageData[i+2]}")
    }

    return cssColourPixelList
  }
}