aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/TextureManager.kt
diff options
context:
space:
mode:
authorJames Barnett <noreply@jamesbarnett.xyz>2020-12-29 20:13:01 +0000
committerJames Barnett <noreply@jamesbarnett.xyz>2020-12-29 20:13:01 +0000
commitad192fe7068081ed88f8616581bf450d601e99b1 (patch)
treee3cda400065c051ee628dbeb85709f778c90311e /src/main/kotlin/TextureManager.kt
parente816c727624056b91c5ef5152c3121a7f8497c5b (diff)
downloadkotlin-raycaster-ad192fe7068081ed88f8616581bf450d601e99b1.tar.xz
kotlin-raycaster-ad192fe7068081ed88f8616581bf450d601e99b1.zip
Add textures
Diffstat (limited to 'src/main/kotlin/TextureManager.kt')
-rw-r--r--src/main/kotlin/TextureManager.kt49
1 files changed, 49 insertions, 0 deletions
diff --git a/src/main/kotlin/TextureManager.kt b/src/main/kotlin/TextureManager.kt
new file mode 100644
index 0000000..58005e9
--- /dev/null
+++ b/src/main/kotlin/TextureManager.kt
@@ -0,0 +1,49 @@
+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.first { it.id == id }
+ }
+
+ fun loadTextures() {
+ textures = document.getElementsByClassName("texture-definition").asList()
+ .map { it as HTMLImageElement }
+ .map {
+ val id = it.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))
+ }
+
+ console.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
+ }
+} \ No newline at end of file