diff --git a/src/main/kotlin/ru/dbotthepony/kstarbound/Starbound.kt b/src/main/kotlin/ru/dbotthepony/kstarbound/Starbound.kt index 70d68420..15e21682 100644 --- a/src/main/kotlin/ru/dbotthepony/kstarbound/Starbound.kt +++ b/src/main/kotlin/ru/dbotthepony/kstarbound/Starbound.kt @@ -372,15 +372,9 @@ class Starbound : ISBFileLocator { val (width, height) = imageSize(args.getString()) with(args.lua) { - pushTable(hashSize = 2) + pushTable(arraySize = 2) val table = stackTop - setTableValue("width", width) - setTableValue("height", height) - - setTableValue("x", width) - setTableValue("y", height) - push(1) push(width) setTableValue(table) @@ -398,6 +392,33 @@ class Starbound : ISBFileLocator { TODO() } + state.setTableFunction("nonEmptyRegion", this) { args -> + val (x, y, z, w) = imageData(args.getString()).nonEmptyRegion + + with(args.lua) { + pushTable(arraySize = 4) + val table = stackTop + + push(1) + push(x) + setTableValue(table) + + push(2) + push(y) + setTableValue(table) + + push(3) + push(z) + setTableValue(table) + + push(4) + push(w) + setTableValue(table) + } + + 1 + } + state.pop() state.load(polyfill, "@starbound.jar!/scripts/polyfill.lua") diff --git a/src/main/kotlin/ru/dbotthepony/kstarbound/io/ImageData.kt b/src/main/kotlin/ru/dbotthepony/kstarbound/io/ImageData.kt index 91ea81f8..d0b94b14 100644 --- a/src/main/kotlin/ru/dbotthepony/kstarbound/io/ImageData.kt +++ b/src/main/kotlin/ru/dbotthepony/kstarbound/io/ImageData.kt @@ -4,6 +4,7 @@ import org.lwjgl.stb.STBImage import org.lwjgl.system.MemoryUtil.memAddress import ru.dbotthepony.kvector.vector.ndouble.Vector2d import ru.dbotthepony.kvector.vector.nint.Vector2i +import ru.dbotthepony.kvector.vector.nint.Vector4i import java.lang.ref.Cleaner import java.nio.ByteBuffer @@ -51,4 +52,38 @@ class ImageData(val data: ByteBuffer, val width: Int, val height: Int, val amoun else -> throw IllegalStateException("Can not check world space taken by image with $amountOfChannels color channels") } } + + val nonEmptyRegion by lazy { + if (amountOfChannels == 4) { + var x0 = 0 + var y0 = 0 + + search@for (y in 0 until height) { + for (x in 0 until width) { + if (this[x, y] and 0x000000FF != 0x0) { + x0 = x + y0 = y + break@search + } + } + } + + var x1 = x0 + var y1 = y0 + + search@for (y in height - 1 downTo y0) { + for (x in width - 1 downTo x0) { + if (this[x, y] and 0x000000FF != 0x0) { + x1 = x + y1 = y + break@search + } + } + } + + return@lazy Vector4i(x0, y0, x1, y1) + } + + Vector4i(0, 0, width, height) + } }