diff --git a/res/graphics/sky_colour.png b/res/graphics/sky_colour.png index 9c5574f32..240210244 100644 Binary files a/res/graphics/sky_colour.png and b/res/graphics/sky_colour.png differ diff --git a/res/graphics/sprites/test_player.png b/res/graphics/sprites/test_player.png index 99a21e8e1..d9a1c32de 100644 Binary files a/res/graphics/sprites/test_player.png and b/res/graphics/sprites/test_player.png differ diff --git a/res/graphics/terrain/terrain.png b/res/graphics/terrain/terrain.png index d4a10ca52..e847fef6a 100644 Binary files a/res/graphics/terrain/terrain.png and b/res/graphics/terrain/terrain.png differ diff --git a/src/com/Torvald/JsonWriter.kt b/src/com/Torvald/JsonWriter.kt index 52563b523..c32f970a0 100644 --- a/src/com/Torvald/JsonWriter.kt +++ b/src/com/Torvald/JsonWriter.kt @@ -12,6 +12,12 @@ import java.io.IOException */ object JsonWriter { + /** + * Serialise a class to the file as JSON, using Google GSON. + * + * @param c: a class + * @param path: path to write a file + */ @Throws(IOException::class) fun writeToFile(c: Any, path: String) { val classElem = Gson().toJsonTree(c) @@ -21,6 +27,12 @@ object JsonWriter { writer.close() } + /** + * Serialise JsonObject to the file as JSON, using Google GSON. + * + * @param jsonObject + * @param path: path to write a file + */ @Throws(IOException::class) fun writeToFile(jsonObject: JsonObject, path: String) { val writer = FileWriter(path) diff --git a/src/com/Torvald/Point/Point2f.java b/src/com/Torvald/Point/Point2f.java deleted file mode 100644 index ad29004b0..000000000 --- a/src/com/Torvald/Point/Point2f.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.Torvald.Point; - -/** - * Created by minjaesong on 16-01-15. - */ -public class Point2f { - - private float x; - private float y; - - public Point2f(float x, float y) { - this.x = x; - this.y = y; - } - - public void set(float x, float y) { - this.x = x; - this.y = y; - } - - public float getX() { - return x; - } - - public float getY() { - return y; - } -} diff --git a/src/com/Torvald/Point/Point2f.kt b/src/com/Torvald/Point/Point2f.kt new file mode 100644 index 000000000..da5fb376c --- /dev/null +++ b/src/com/Torvald/Point/Point2f.kt @@ -0,0 +1,22 @@ +package com.Torvald.Point + +/** + * Created by minjaesong on 16-01-15. + */ +class Point2f(x: Float, y: Float) { + + var x: Float = 0.toFloat() + private set + var y: Float = 0.toFloat() + private set + + init { + this.x = x + this.y = y + } + + operator fun set(x: Float, y: Float) { + this.x = x + this.y = y + } +} diff --git a/src/com/Torvald/Terrarum/Actors/Hitbox.java b/src/com/Torvald/Terrarum/Actors/Hitbox.java deleted file mode 100644 index 6729accf4..000000000 --- a/src/com/Torvald/Terrarum/Actors/Hitbox.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.Torvald.Terrarum.Actors; - -import com.Torvald.Point.Point2f; - -/** - * Created by minjaesong on 16-01-15. - */ -public class Hitbox { - - private Point2f hitboxStart; - private Point2f hitboxEnd; - private float width; - private float height; - - public Hitbox(float x1, float y1, float width, float height) { - hitboxStart = new Point2f(x1, y1); - hitboxEnd = new Point2f(x1 + width, y1 + height); - this.width = width; - this.height = height; - } - - public Point2f getHitboxStart() { - return hitboxStart; - } - - public Point2f getHitboxEnd() { - return hitboxEnd; - } - - public float getWidth() { - return width; - } - - public float getHeight() { - return height; - } - - /** - * Returns bottom-centered point of hitbox. - * @return pointX - */ - public float getPointedX() { - return hitboxStart.getX() + (width / 2); - } - - /** - * Returns bottom-centered point of hitbox. - * @return pointY - */ - public float getPointedY() { - return hitboxEnd.getY(); - } - - /** - * Set to the point top left - * @param x1 - * @param y1 - * @param width - * @param height - */ - public void set(float x1, float y1, float width, float height) { - hitboxStart = new Point2f(x1, y1); - hitboxEnd = new Point2f(x1 + width, y1 + height); - this.width = width; - this.height = height; - } - - public void setPosition(float x1, float y1) { - hitboxStart = new Point2f(x1, y1); - hitboxEnd = new Point2f(x1 + width, y1 + height); - } - - public void setPositionX(float x) { - setPosition(x, getPosY()); - } - - public void setPositionY(float y) { - setPosition(getPosX(), y); - } - - public void setPositionFromPoint(float x1, float y1) { - hitboxStart = new Point2f(x1 - (width / 2), y1 - height); - hitboxEnd = new Point2f(hitboxStart.getX() + width, hitboxStart.getY() + height); - } - - public void setPositionXFromPoint(float x) { - setPositionFromPoint(x, getPointedY()); - } - - public void setPositionYFromPoint(float y) { - setPositionFromPoint(getPointedX(), y); - } - - public void translatePosX(float d) { - setPositionX(getPosX() + d); - } - - public void translatePosY(float d) { - setPositionY(getPosY() + d); - } - - public void setDimension(float w, float h) { - width = w; - height = h; - } - - /** - * Returns x value of start point - * @return top-left point posX - */ - public float getPosX() { - return hitboxStart.getX(); - } - - /** - * Returns y value of start point - * @return top-left point posY - */ - public float getPosY() { - return hitboxStart.getY(); - } - - public float getCenteredX() { - return (hitboxStart.getX() + hitboxEnd.getX()) * 0.5f; - } - - public float getCenteredY() { - return (hitboxStart.getY() + hitboxEnd.getY()) * 0.5f; - } -} diff --git a/src/com/Torvald/Terrarum/Actors/Hitbox.kt b/src/com/Torvald/Terrarum/Actors/Hitbox.kt new file mode 100644 index 000000000..8631ac807 --- /dev/null +++ b/src/com/Torvald/Terrarum/Actors/Hitbox.kt @@ -0,0 +1,115 @@ +package com.Torvald.Terrarum.Actors + +import com.Torvald.Point.Point2f + +/** + * Created by minjaesong on 16-01-15. + */ +class Hitbox(x1: Float, y1: Float, width: Float, height: Float) { + + var hitboxStart: Point2f + private set + var hitboxEnd: Point2f + private set + var width: Float = 0.toFloat() + private set + var height: Float = 0.toFloat() + private set + + init { + hitboxStart = Point2f(x1, y1) + hitboxEnd = Point2f(x1 + width, y1 + height) + this.width = width + this.height = height + } + + /** + * Returns bottom-centered point of hitbox. + * @return pointX + */ + val pointedX: Float + get() = hitboxStart.x + width / 2 + + /** + * Returns bottom-centered point of hitbox. + * @return pointY + */ + val pointedY: Float + get() = hitboxEnd.y + + /** + * Set to the point top left + * @param x1 + * * + * @param y1 + * * + * @param width + * * + * @param height + */ + operator fun set(x1: Float, y1: Float, width: Float, height: Float) { + hitboxStart = Point2f(x1, y1) + hitboxEnd = Point2f(x1 + width, y1 + height) + this.width = width + this.height = height + } + + fun setPosition(x1: Float, y1: Float) { + hitboxStart = Point2f(x1, y1) + hitboxEnd = Point2f(x1 + width, y1 + height) + } + + fun setPositionX(x: Float) { + setPosition(x, posY) + } + + fun setPositionY(y: Float) { + setPosition(posX, y) + } + + fun setPositionFromPoint(x1: Float, y1: Float) { + hitboxStart = Point2f(x1 - width / 2, y1 - height) + hitboxEnd = Point2f(hitboxStart.x + width, hitboxStart.y + height) + } + + fun setPositionXFromPoint(x: Float) { + setPositionFromPoint(x, pointedY) + } + + fun setPositionYFromPoint(y: Float) { + setPositionFromPoint(pointedX, y) + } + + fun translatePosX(d: Float) { + setPositionX(posX + d) + } + + fun translatePosY(d: Float) { + setPositionY(posY + d) + } + + fun setDimension(w: Float, h: Float) { + width = w + height = h + } + + /** + * Returns x value of start point + * @return top-left point posX + */ + val posX: Float + get() = hitboxStart.x + + /** + * Returns y value of start point + * @return top-left point posY + */ + val posY: Float + get() = hitboxStart.y + + val centeredX: Float + get() = (hitboxStart.x + hitboxEnd.x) * 0.5f + + val centeredY: Float + get() = (hitboxStart.y + hitboxEnd.y) * 0.5f +} diff --git a/src/com/Torvald/Terrarum/Actors/PFSigrid.kt b/src/com/Torvald/Terrarum/Actors/PFSigrid.kt index 5c363f051..282d86c57 100644 --- a/src/com/Torvald/Terrarum/Actors/PFSigrid.kt +++ b/src/com/Torvald/Terrarum/Actors/PFSigrid.kt @@ -26,7 +26,6 @@ object PFSigrid { p.sprite!!.setDelay(200) p.sprite!!.setRowsAndFrames(1, 1) p.sprite!!.setAsVisible() - p.sprite!!.composeSprite() p.spriteGlow = SpriteAnimation() p.spriteGlow!!.setDimension(28, 51) @@ -34,7 +33,6 @@ object PFSigrid { p.spriteGlow!!.setDelay(200) p.spriteGlow!!.setRowsAndFrames(1, 1) p.spriteGlow!!.setAsVisible() - p.spriteGlow!!.composeSprite() p.actorValue = ActorValue() p.actorValue.set("scale", 1.0f) diff --git a/src/com/Torvald/Terrarum/Actors/PhysTestBall.kt b/src/com/Torvald/Terrarum/Actors/PhysTestBall.kt index d4c009258..17c808645 100644 --- a/src/com/Torvald/Terrarum/Actors/PhysTestBall.kt +++ b/src/com/Torvald/Terrarum/Actors/PhysTestBall.kt @@ -17,9 +17,9 @@ class PhysTestBall : ActorWithBody { override fun drawBody(gc: GameContainer, g: Graphics) { g.color = Color.orange g.fillOval( - hitbox!!.getPosX(), - hitbox!!.getPosY(), - hitbox!!.getWidth(), - hitbox!!.getHeight()) + hitbox!!.posX, + hitbox!!.posY, + hitbox!!.width, + hitbox!!.height) } } \ No newline at end of file diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/CatStdout.java b/src/com/Torvald/Terrarum/ConsoleCommand/CatStdout.java deleted file mode 100644 index 418348a68..000000000 --- a/src/com/Torvald/Terrarum/ConsoleCommand/CatStdout.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.Torvald.Terrarum.ConsoleCommand; - -import java.io.IOException; -import java.nio.file.FileSystems; -import java.nio.file.Files; - -/** - * Created by minjaesong on 16-02-10. - */ -public class CatStdout implements ConsoleCommand { - @Override - public void execute(String[] args) { - - Echo echo = new Echo(); - - if (args.length == 1) { - printUsage(); - return; - } - - try { - Files.lines(FileSystems.getDefault().getPath(args[1])).forEach(echo::execute); - } - catch (IOException e) { - echo.execute("CatStdout: could not read file -- IOException"); - } - - } - - @Override - public void printUsage() { - new Echo().execute("usage: cat 'path/to/text/file"); - } -} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/CatStdout.kt b/src/com/Torvald/Terrarum/ConsoleCommand/CatStdout.kt new file mode 100644 index 000000000..6ee8e12c7 --- /dev/null +++ b/src/com/Torvald/Terrarum/ConsoleCommand/CatStdout.kt @@ -0,0 +1,32 @@ +package com.Torvald.Terrarum.ConsoleCommand + +import java.io.IOException +import java.nio.file.FileSystems +import java.nio.file.Files + +/** + * Created by minjaesong on 16-02-10. + */ +class CatStdout : ConsoleCommand { + override fun execute(args: Array) { + + val echo = Echo() + + if (args.size == 1) { + printUsage() + return + } + + try { + Files.lines(FileSystems.getDefault().getPath(args[1])).forEach({ echo.execute(it) }) + } + catch (e: IOException) { + echo.execute("CatStdout: could not read file -- IOException") + } + + } + + override fun printUsage() { + Echo().execute("usage: cat 'path/to/text/file") + } +} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/Echo.java b/src/com/Torvald/Terrarum/ConsoleCommand/Echo.java deleted file mode 100644 index d90cabb7f..000000000 --- a/src/com/Torvald/Terrarum/ConsoleCommand/Echo.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.Torvald.Terrarum.ConsoleCommand; - -import com.Torvald.Terrarum.Terrarum; -import com.Torvald.Terrarum.UserInterface.ConsoleWindow; - -import java.util.Arrays; - -/** - * Created by minjaesong on 16-01-16. - */ -class Echo implements ConsoleCommand { - @Override - public void execute(String[] args) { - String[] argsWoHeader = new String[args.length - 1]; - for (int i = 0; i < argsWoHeader.length; i++) - argsWoHeader[i] = args[i + 1]; - - Arrays.asList(argsWoHeader).forEach( - ((ConsoleWindow) Terrarum.game.consoleHandler.getUI())::sendMessage - ); - } - - public void execute(String single_line) { - ((ConsoleWindow) Terrarum.game.consoleHandler.getUI()) - .sendMessage(single_line); - } - - @Override - public void printUsage() { - - } -} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/Echo.kt b/src/com/Torvald/Terrarum/ConsoleCommand/Echo.kt new file mode 100644 index 000000000..5b5d39b8f --- /dev/null +++ b/src/com/Torvald/Terrarum/ConsoleCommand/Echo.kt @@ -0,0 +1,26 @@ +package com.Torvald.Terrarum.ConsoleCommand + +import com.Torvald.Terrarum.Terrarum +import com.Torvald.Terrarum.UserInterface.ConsoleWindow + +import java.util.Arrays + +/** + * Created by minjaesong on 16-01-16. + */ +internal class Echo : ConsoleCommand { + override fun execute(args: Array) { + val argsWoHeader = Array(args.size - 1, {it -> args[it + 1]}) + + argsWoHeader.forEach( + { (Terrarum.game.consoleHandler.UI as ConsoleWindow).sendMessage(it) }) + } + + fun execute(single_line: String) { + (Terrarum.game.consoleHandler.UI as ConsoleWindow).sendMessage(single_line) + } + + override fun printUsage() { + + } +} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/ExportAV.java b/src/com/Torvald/Terrarum/ConsoleCommand/ExportAV.java deleted file mode 100644 index d625c5cb5..000000000 --- a/src/com/Torvald/Terrarum/ConsoleCommand/ExportAV.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.Torvald.Terrarum.ConsoleCommand; - -import com.Torvald.JsonWriter; -import com.Torvald.Terrarum.Terrarum; - -import java.io.IOException; - -/** - * Created by minjaesong on 16-02-10. - */ -public class ExportAV implements ConsoleCommand { - @Override - public void execute(String[] args) { - if (args.length == 2) { - try { - JsonWriter.INSTANCE.writeToFile(Terrarum.game.player.getActorValue() - , Terrarum.defaultDir + "/Exports/" + args[1] + ".json" - ); - - new Echo().execute("ExportAV: exported to " + args[1] + ".json"); - } - catch (IOException e) { - new Echo().execute("ExportAV: IOException raised."); - e.printStackTrace(); - } - } - else { - printUsage(); - } - } - - @Override - public void printUsage() { - Echo echo = new Echo(); - echo.execute("Export ActorValue as JSON format."); - echo.execute("Usage: exportav (id) filename-without-extension"); - echo.execute("blank ID for player"); - } -} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/ExportAV.kt b/src/com/Torvald/Terrarum/ConsoleCommand/ExportAV.kt new file mode 100644 index 000000000..c37fe6828 --- /dev/null +++ b/src/com/Torvald/Terrarum/ConsoleCommand/ExportAV.kt @@ -0,0 +1,38 @@ +package com.Torvald.Terrarum.ConsoleCommand + +import com.Torvald.JsonWriter +import com.Torvald.Terrarum.Terrarum + +import java.io.IOException + +/** + * Created by minjaesong on 16-02-10. + */ +class ExportAV : ConsoleCommand { + override fun execute(args: Array) { + if (args.size == 2) { + try { + JsonWriter.writeToFile( + Terrarum.game.player.getActorValue(), + Terrarum.defaultDir + "/Exports/" + args[1] + ".json") + + Echo().execute("ExportAV: exported to " + args[1] + ".json") + } + catch (e: IOException) { + Echo().execute("ExportAV: IOException raised.") + e.printStackTrace() + } + + } + else { + printUsage() + } + } + + override fun printUsage() { + val echo = Echo() + echo.execute("Export ActorValue as JSON format.") + echo.execute("Usage: exportav (id) filename-without-extension") + echo.execute("blank ID for player") + } +} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/ExportMap.java b/src/com/Torvald/Terrarum/ConsoleCommand/ExportMap.kt similarity index 51% rename from src/com/Torvald/Terrarum/ConsoleCommand/ExportMap.java rename to src/com/Torvald/Terrarum/ConsoleCommand/ExportMap.kt index 5df05bf63..79d84cbb2 100644 --- a/src/com/Torvald/Terrarum/ConsoleCommand/ExportMap.java +++ b/src/com/Torvald/Terrarum/ConsoleCommand/ExportMap.kt @@ -1,3 +1,151 @@ +package com.Torvald.Terrarum.ConsoleCommand + +import com.Torvald.ColourUtil.Col4096 +import com.Torvald.RasterWriter +import com.Torvald.Terrarum.Terrarum + +import javax.imageio.ImageIO +import java.awt.* +import java.awt.color.ColorSpace +import java.awt.image.* +import java.io.* +import java.util.Hashtable + +/** + * Created by minjaesong on 16-01-17. + */ +class ExportMap : ConsoleCommand { + + //private var mapData: ByteArray? = null + // private var mapDataPointer = 0 + + private val colorTable = Hashtable() + + override fun execute(args: Array) { + if (args.size == 2) { + buildColorTable() + + var mapData = ByteArray(Terrarum.game.map.width * Terrarum.game.map.height * 3) + var mapDataPointer = 0 + + for (tile in Terrarum.game.map.layerTerrain) { + val colArray = (colorTable as java.util.Map) + .getOrDefault(tile, Col4096(0xFFF)).toByteArray() + + for (i in 0..2) { + mapData[mapDataPointer + i] = colArray[i] + } + + mapDataPointer += 3 + } + + val dir = Terrarum.defaultDir + "/Exports/" + val dirAsFile = File(dir) + if (!dirAsFile.exists()) { + dirAsFile.mkdir() + } + + try { + RasterWriter.writePNG_RGB( + Terrarum.game.map.width, Terrarum.game.map.height, mapData, dir + args[1] + ".png") + Echo().execute("ExportMap: exported to " + args[1] + ".png") + + } + catch (e: IOException) { + Echo().execute("ExportMap: IOException raised.") + e.printStackTrace() + } + + // mapData = null + // mapDataPointer = 0 + + // Free up some memory + System.gc() + } + else { + printUsage() + } + } + + override fun printUsage() { + val echo = Echo() + echo.execute("Usage: export ") + echo.execute("Exports current map into visible image.") + echo.execute("The image can be found at %adddata%/Terrarum/Exports") + } + + private fun buildColorTable() { + colorTable.put(AIR, Col4096(0xCEF)) + colorTable.put(STONE, Col4096(0x887)) + colorTable.put(DIRT, Col4096(0x763)) + colorTable.put(GRASS, Col4096(0x251)) + + colorTable.put(COPPER, Col4096(0x6A8)) + colorTable.put(IRON, Col4096(0xC75)) + colorTable.put(GOLD, Col4096(0xCB6)) + colorTable.put(ILMENITE, Col4096(0x8AB)) + colorTable.put(AURICHALCUM, Col4096(0xD92)) + colorTable.put(SILVER, Col4096(0xDDD)) + + colorTable.put(DIAMOND, Col4096(0x9CE)) + colorTable.put(RUBY, Col4096(0xB10)) + colorTable.put(EMERALD, Col4096(0x0B1)) + colorTable.put(SAPPHIRE, Col4096(0x01B)) + colorTable.put(TOPAZ, Col4096(0xC70)) + colorTable.put(AMETHYST, Col4096(0x70C)) + + colorTable.put(WATER, Col4096(0x038)) + colorTable.put(LAVA, Col4096(0xF50)) + + colorTable.put(SAND, Col4096(0xDCA)) + colorTable.put(GRAVEL, Col4096(0x664)) + + colorTable.put(ICE_NATURAL, Col4096(0x9AB)) + colorTable.put(ICE_MAGICAL, Col4096(0x7AC)) + colorTable.put(ICE_FRAGILE, Col4096(0x6AF)) + colorTable.put(SNOW, Col4096(0xCDE)) + + + } + + companion object { + + private val AIR: Byte = 0 + + private val STONE: Byte = 1 + private val DIRT: Byte = 2 + private val GRASS: Byte = 3 + + private val SAND: Byte = 13 + private val GRAVEL: Byte = 14 + + private val COPPER: Byte = 15 + private val IRON: Byte = 16 + private val GOLD: Byte = 17 + private val SILVER: Byte = 18 + private val ILMENITE: Byte = 19 + private val AURICHALCUM: Byte = 20 + + private val DIAMOND: Byte = 25 + private val RUBY: Byte = 21 + private val EMERALD: Byte = 22 + private val SAPPHIRE: Byte = 23 + private val TOPAZ: Byte = 24 + private val AMETHYST: Byte = 26 + + private val SNOW: Byte = 27 + private val ICE_FRAGILE: Byte = 28 + private val ICE_NATURAL: Byte = 29 + private val ICE_MAGICAL: Byte = 30 + + private val WATER = 239.toByte() + private val LAVA = 255.toByte() + } + +} + + +/* package com.Torvald.Terrarum.ConsoleCommand; import com.Torvald.ColourUtil.Col4096; @@ -144,3 +292,5 @@ public class ExportMap implements ConsoleCommand { } } + + */ \ No newline at end of file diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/ForceGC.java b/src/com/Torvald/Terrarum/ConsoleCommand/ForceGC.java deleted file mode 100644 index 4b0121491..000000000 --- a/src/com/Torvald/Terrarum/ConsoleCommand/ForceGC.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.Torvald.Terrarum.ConsoleCommand; - -/** - * Created by minjaesong on 16-01-18. - */ -public class ForceGC implements ConsoleCommand { - @Override - public void execute(String[] args) { - System.gc(); - new Echo().execute("Invoked System.gc"); - } - - @Override - public void printUsage() { - new Echo().execute("Invoke garbage collection of JVM."); - } -} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/ForceGC.kt b/src/com/Torvald/Terrarum/ConsoleCommand/ForceGC.kt new file mode 100644 index 000000000..b3d41afc6 --- /dev/null +++ b/src/com/Torvald/Terrarum/ConsoleCommand/ForceGC.kt @@ -0,0 +1,15 @@ +package com.Torvald.Terrarum.ConsoleCommand + +/** + * Created by minjaesong on 16-01-18. + */ +class ForceGC : ConsoleCommand { + override fun execute(args: Array) { + System.gc() + Echo().execute("Invoked System.gc") + } + + override fun printUsage() { + Echo().execute("Invoke garbage collection of JVM.") + } +} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/GetAV.java b/src/com/Torvald/Terrarum/ConsoleCommand/GetAV.java deleted file mode 100644 index 6902b8feb..000000000 --- a/src/com/Torvald/Terrarum/ConsoleCommand/GetAV.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.Torvald.Terrarum.ConsoleCommand; - -import com.Torvald.Terrarum.Actors.ActorValue; -import com.Torvald.Terrarum.Game; -import com.Torvald.Terrarum.Terrarum; - -import java.util.Iterator; -import java.util.Set; - -/** - * Created by minjaesong on 16-01-19. - */ -public class GetAV implements ConsoleCommand { - @Override - public void execute(String[] args) { - Echo echo = new Echo(); - - try { - if (args.length == 1) { - // print all actorvalue of player - ActorValue av = Terrarum.game.player.getActorValue(); - Set keyset = av.getKeySet(); - - keyset.forEach( - elem -> echo.execute(elem + " = " + av.get((String) elem)) - ); - - } - else if (args.length != 3 && args.length != 2) { - printUsage(); - } - else if (args.length == 2) { - echo.execute("player." + args[1] + " = " - + Terrarum.game.player.getActorValue().get(args[1]) - + " (" - + Terrarum.game.player.getActorValue().get(args[1]).getClass() - .getSimpleName() - + ")" - ); - } - else if (args.length == 3) { - - } - } - catch (NullPointerException e) { - if (args.length == 2) { - echo.execute(args[1] + ": actor value does not exist."); - } - else if (args.length == 3) { - echo.execute(args[2] + ": actor value does not exist."); - } - else { - throw new NullPointerException(); - } - } - } - - @Override - public void printUsage() { - Echo echo = new Echo(); - echo.execute("Get desired actor value of specific target."); - echo.execute("Usage: getav (id) "); - echo.execute("blank ID for player"); - } -} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/GetAV.kt b/src/com/Torvald/Terrarum/ConsoleCommand/GetAV.kt new file mode 100644 index 000000000..51d96e7f1 --- /dev/null +++ b/src/com/Torvald/Terrarum/ConsoleCommand/GetAV.kt @@ -0,0 +1,57 @@ +package com.Torvald.Terrarum.ConsoleCommand + +import com.Torvald.Terrarum.Actors.ActorValue +import com.Torvald.Terrarum.Game +import com.Torvald.Terrarum.Terrarum + +/** + * Created by minjaesong on 16-01-19. + */ +class GetAV : ConsoleCommand { + override fun execute(args: Array) { + val echo = Echo() + + try { + if (args.size == 1) { + // print all actorvalue of player + val av = Terrarum.game.player.getActorValue() + val keyset = av.keySet + + keyset.forEach { elem -> echo.execute("$elem = ${av[elem as String]}") } + + } + else if (args.size != 3 && args.size != 2) { + printUsage() + } + else if (args.size == 2) { + echo.execute("player." + args[1] + " = " + + Terrarum.game.player.getActorValue()[args[1]] + + " (" + + Terrarum.game.player.getActorValue()[args[1]]!!.javaClass.simpleName + + ")") + } + else if (args.size == 3) { + + } + } + catch (e: NullPointerException) { + if (args.size == 2) { + echo.execute(args[1] + ": actor value does not exist.") + } + else if (args.size == 3) { + echo.execute(args[2] + ": actor value does not exist.") + } + else { + throw NullPointerException() + } + } + + } + + override fun printUsage() { + val echo = Echo() + echo.execute("Get desired actor value of specific target.") + echo.execute("Usage: getav (id) ") + echo.execute("blank ID for player") + } +} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/GetFactioning.java b/src/com/Torvald/Terrarum/ConsoleCommand/GetFactioning.java deleted file mode 100644 index e58532f85..000000000 --- a/src/com/Torvald/Terrarum/ConsoleCommand/GetFactioning.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.Torvald.Terrarum.ConsoleCommand; - -import com.Torvald.Terrarum.Actors.Faction.Faction; -import com.Torvald.Terrarum.LangPack.Lang; -import com.Torvald.Terrarum.Terrarum; - -import java.util.HashSet; - -/** - * Created by minjaesong on 16-02-17. - */ -public class GetFactioning implements ConsoleCommand { - - private final String PRINT_INDENTATION = " --> "; - - @Override - public void execute(String[] args) { - Echo echo = new Echo(); - - if (args.length == 1) { // get all factioning data of player - HashSet factionSet = Terrarum.game.player.getFaction(); - - if (factionSet == null) { - echo.execute("The actor has null faction set."); - return; - } - - int count = factionSet.size(); - echo.execute(String.valueOf(count) + Lang.pluralise(" faction", count) + " assigned."); - - for (Faction faction : factionSet) { - echo.execute("Faction \"" + faction.getFactionName() + "\""); - echo.execute(" Amicable"); - faction.getFactionAmicable().forEach( - s -> echo.execute(PRINT_INDENTATION + s) - ); - - echo.execute(" Explicit neutral"); - faction.getFactionNeutral().forEach( - s -> echo.execute(PRINT_INDENTATION + s) - ); - - echo.execute(" Hostile"); - faction.getFactionHostile().forEach( - s -> echo.execute(PRINT_INDENTATION + s) - ); - - echo.execute(" Fearful"); - faction.getFactionFearful().forEach( - s -> echo.execute(PRINT_INDENTATION + s) - ); - } - } - } - - @Override - public void printUsage() { - - } -} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/GetFactioning.kt b/src/com/Torvald/Terrarum/ConsoleCommand/GetFactioning.kt new file mode 100644 index 000000000..7a2a7fd18 --- /dev/null +++ b/src/com/Torvald/Terrarum/ConsoleCommand/GetFactioning.kt @@ -0,0 +1,51 @@ +package com.Torvald.Terrarum.ConsoleCommand + +import com.Torvald.Terrarum.Actors.Faction.Faction +import com.Torvald.Terrarum.LangPack.Lang +import com.Torvald.Terrarum.Terrarum + +import java.util.HashSet + +/** + * Created by minjaesong on 16-02-17. + */ +class GetFactioning : ConsoleCommand { + + private val PRINT_INDENTATION = " --> " + + override fun execute(args: Array) { + val echo = Echo() + + if (args.size == 1) { + // get all factioning data of player + val factionSet = Terrarum.game.player.faction + + if (factionSet == null) { + echo.execute("The actor has null faction set.") + return + } + + val count = factionSet.size + echo.execute(count.toString() + Lang.pluralise(" faction", count) + " assigned.") + + for (faction in factionSet) { + echo.execute("Faction \"" + faction.factionName + "\"") + echo.execute(" Amicable") + faction.factionAmicable.forEach { s -> echo.execute(PRINT_INDENTATION + s) } + + echo.execute(" Explicit neutral") + faction.factionNeutral.forEach { s -> echo.execute(PRINT_INDENTATION + s) } + + echo.execute(" Hostile") + faction.factionHostile.forEach { s -> echo.execute(PRINT_INDENTATION + s) } + + echo.execute(" Fearful") + faction.factionFearful.forEach { s -> echo.execute(PRINT_INDENTATION + s) } + } + } + } + + override fun printUsage() { + + } +} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/GetLocale.java b/src/com/Torvald/Terrarum/ConsoleCommand/GetLocale.java deleted file mode 100644 index bd1696c9d..000000000 --- a/src/com/Torvald/Terrarum/ConsoleCommand/GetLocale.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.Torvald.Terrarum.ConsoleCommand; - -import com.Torvald.Terrarum.LangPack.Lang; -import com.Torvald.Terrarum.Terrarum; - -/** - * Created by minjaesong on 16-01-22. - */ -public class GetLocale implements ConsoleCommand { - @Override - public void execute(String[] args) { - new Echo().execute( - "Locale: " - + Lang.get("LANGUAGE_THIS") - + " (" - + Lang.get("LANGUAGE_EN") - + ")" - ); - } - - @Override - public void printUsage() { - Echo echo = new Echo(); - echo.execute("Usage: getlocale"); - echo.execute("Get name of locale currently using."); - } -} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/GetLocale.kt b/src/com/Torvald/Terrarum/ConsoleCommand/GetLocale.kt new file mode 100644 index 000000000..eb3f8b908 --- /dev/null +++ b/src/com/Torvald/Terrarum/ConsoleCommand/GetLocale.kt @@ -0,0 +1,24 @@ +package com.Torvald.Terrarum.ConsoleCommand + +import com.Torvald.Terrarum.LangPack.Lang +import com.Torvald.Terrarum.Terrarum + +/** + * Created by minjaesong on 16-01-22. + */ +class GetLocale : ConsoleCommand { + override fun execute(args: Array) { + Echo().execute( + "Locale: " + + Lang.get("LANGUAGE_THIS") + + " (" + + Lang.get("LANGUAGE_EN") + + ")") + } + + override fun printUsage() { + val echo = Echo() + echo.execute("Usage: getlocale") + echo.execute("Get name of locale currently using.") + } +} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/GsonTest.java b/src/com/Torvald/Terrarum/ConsoleCommand/GsonTest.java deleted file mode 100644 index 2d23740d9..000000000 --- a/src/com/Torvald/Terrarum/ConsoleCommand/GsonTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.Torvald.Terrarum.ConsoleCommand; - -import com.Torvald.Terrarum.Terrarum; -import com.google.gson.Gson; -import com.google.gson.JsonElement; - -import java.io.BufferedWriter; -import java.io.FileWriter; -import java.io.IOException; - -/** - * Created by minjaesong on 16-02-10. - */ -public class GsonTest implements ConsoleCommand { - @Override - public void execute(String[] args) { - if (args.length == 2) { - JsonElement avelem = new Gson().toJsonTree(Terrarum.game.player); - - String jsonString = avelem.toString(); - - BufferedWriter bufferedWriter; - FileWriter writer; - try { - writer = new FileWriter(Terrarum.defaultDir + "/Exports/" + args[1] + ".json"); - bufferedWriter = new BufferedWriter(writer); - - bufferedWriter.write(jsonString); - bufferedWriter.close(); - - new Echo().execute("GsonTest: exported to " + args[1] + ".json"); - } - catch (IOException e) { - new Echo().execute("GsonTest: IOException raised."); - e.printStackTrace(); - } - } - else { - printUsage(); - } - } - - @Override - public void printUsage() { - Echo echo = new Echo(); - echo.execute("Usage: gsontest filename-without-extension"); - } -} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/GsonTest.kt b/src/com/Torvald/Terrarum/ConsoleCommand/GsonTest.kt new file mode 100644 index 000000000..13ed6898f --- /dev/null +++ b/src/com/Torvald/Terrarum/ConsoleCommand/GsonTest.kt @@ -0,0 +1,47 @@ +package com.Torvald.Terrarum.ConsoleCommand + +import com.Torvald.Terrarum.Terrarum +import com.google.gson.Gson +import com.google.gson.JsonElement + +import java.io.BufferedWriter +import java.io.FileWriter +import java.io.IOException + +/** + * Created by minjaesong on 16-02-10. + */ +class GsonTest : ConsoleCommand { + override fun execute(args: Array) { + if (args.size == 2) { + val avelem = Gson().toJsonTree(Terrarum.game.player) + + val jsonString = avelem.toString() + + val bufferedWriter: BufferedWriter + val writer: FileWriter + try { + writer = FileWriter(Terrarum.defaultDir + "/Exports/" + args[1] + ".json") + bufferedWriter = BufferedWriter(writer) + + bufferedWriter.write(jsonString) + bufferedWriter.close() + + Echo().execute("GsonTest: exported to " + args[1] + ".json") + } + catch (e: IOException) { + Echo().execute("GsonTest: IOException raised.") + e.printStackTrace() + } + + } + else { + printUsage() + } + } + + override fun printUsage() { + val echo = Echo() + echo.execute("Usage: gsontest filename-without-extension") + } +} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/Help.kt b/src/com/Torvald/Terrarum/ConsoleCommand/Help.kt index 9f5f2d015..e042e38bc 100644 --- a/src/com/Torvald/Terrarum/ConsoleCommand/Help.kt +++ b/src/com/Torvald/Terrarum/ConsoleCommand/Help.kt @@ -15,6 +15,6 @@ class Help : ConsoleCommand { } override fun printUsage() { - Echo().execute("Prints some utility functions assigned to runction row of the keyboard.") + Echo().execute("Prints some utility functions assigned to function row of the keyboard.") } } \ No newline at end of file diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/QuitApp.java b/src/com/Torvald/Terrarum/ConsoleCommand/QuitApp.java deleted file mode 100644 index 11f25ef60..000000000 --- a/src/com/Torvald/Terrarum/ConsoleCommand/QuitApp.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.Torvald.Terrarum.ConsoleCommand; - -/** - * Created by minjaesong on 16-01-15. - */ -public class QuitApp implements ConsoleCommand { - - @Override - public void execute(String[] args) { - System.exit(1); - } - - @Override - public void printUsage() { - - } -} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/QuitApp.kt b/src/com/Torvald/Terrarum/ConsoleCommand/QuitApp.kt new file mode 100644 index 000000000..ae1fe3013 --- /dev/null +++ b/src/com/Torvald/Terrarum/ConsoleCommand/QuitApp.kt @@ -0,0 +1,15 @@ +package com.Torvald.Terrarum.ConsoleCommand + +/** + * Created by minjaesong on 16-01-15. + */ +class QuitApp : ConsoleCommand { + + override fun execute(args: Array) { + System.exit(1) + } + + override fun printUsage() { + + } +} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/SetAV.java b/src/com/Torvald/Terrarum/ConsoleCommand/SetAV.java deleted file mode 100644 index a73f5f2e4..000000000 --- a/src/com/Torvald/Terrarum/ConsoleCommand/SetAV.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.Torvald.Terrarum.ConsoleCommand; - -import com.Torvald.Terrarum.Game; -import com.Torvald.Terrarum.Terrarum; - -/** - * Created by minjaesong on 16-01-15. - */ -class SetAV implements ConsoleCommand { - - @Override - public void printUsage() { - Echo echo = new Echo(); - echo.execute("Set actor value of specific target to desired value."); - echo.execute("Usage: setav (id) "); - echo.execute("blank ID for player"); - } - - @Override - public void execute(String[] args) { - Echo echo = new Echo(); - - // setav - if (args.length != 4 && args.length != 3) { - printUsage(); - } - else if (args.length == 3) { - Object val; - - try { - val = new Integer(args[2]); // try for integer - } - catch (NumberFormatException e) { - - try { - val = new Float(args[2]); // try for float - } - catch (NumberFormatException ee) { - if (args[2].equalsIgnoreCase("__true")) { - val = new Boolean(true); - } - else if (args[2].equalsIgnoreCase("__false")) { - val = new Boolean(false); - } - else { - val = new String(args[2]); // string if not number - } - } - } - - Terrarum.game.player.getActorValue().set(args[1], val); - echo.execute("Set " + args[1] + " to " + val); - } - else if (args.length == 4) { - - } - - } -} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/SetAV.kt b/src/com/Torvald/Terrarum/ConsoleCommand/SetAV.kt new file mode 100644 index 000000000..c542405ca --- /dev/null +++ b/src/com/Torvald/Terrarum/ConsoleCommand/SetAV.kt @@ -0,0 +1,61 @@ +package com.Torvald.Terrarum.ConsoleCommand + +import com.Torvald.Terrarum.Game +import com.Torvald.Terrarum.Terrarum + +/** + * Created by minjaesong on 16-01-15. + */ +internal class SetAV : ConsoleCommand { + + override fun printUsage() { + val echo = Echo() + echo.execute("Set actor value of specific target to desired value.") + echo.execute("Usage: setav (id) ") + echo.execute("blank ID for player") + echo.execute("Contaminated (float -> string) actor value will crash the game,") + echo.execute(" so make it sure before you issue the command.") + echo.execute("Use '__true' and '__false' for boolean value.") + } + + override fun execute(args: Array) { + val echo = Echo() + + // setav + if (args.size != 4 && args.size != 3) { + printUsage() + } + else if (args.size == 3) { + val `val`: Any + + try { + `val` = Integer(args[2]) // try for integer + } + catch (e: NumberFormatException) { + + try { + `val` = args[2].toFloat() // try for float + } + catch (ee: NumberFormatException) { + if (args[2].equals("__true", ignoreCase = true)) { + `val` = true + } + else if (args[2].equals("__false", ignoreCase = true)) { + `val` = false + } + else { + `val` = args[2] // string if not number + } + } + + } + + Terrarum.game.player.getActorValue()[args[1]] = `val` + echo.execute("Set " + args[1] + " to " + `val`) + } + else if (args.size == 4) { + + } + + } +} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/SetBulletin.java b/src/com/Torvald/Terrarum/ConsoleCommand/SetBulletin.java deleted file mode 100644 index b4368a6be..000000000 --- a/src/com/Torvald/Terrarum/ConsoleCommand/SetBulletin.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.Torvald.Terrarum.ConsoleCommand; - -import com.Torvald.Terrarum.LangPack.Lang; -import com.Torvald.Terrarum.Terrarum; -import com.Torvald.Terrarum.UserInterface.Notification; - -/** - * Created by minjaesong on 16-01-23. - */ -public class SetBulletin implements ConsoleCommand { - @Override - public void execute(String[] args) { - String[] testMsg = { - //Lang.get("ERROR_SAVE_CORRUPTED") - //, Lang.get("MENU_LABEL_CONTINUE_QUESTION") - "Bulletin test “Hello, world!”", - "世界一みんなの人気者 それは彼女のこと アシュリー 달이 차오른다 가자" - }; - send(testMsg); - } - - @Override - public void printUsage() { - - } - - /** - * Actually send notifinator - * @param message real message - */ - public void send(String[] message) { - Terrarum.game.sendNotification(message); - System.out.println("sent notifinator"); - } -} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/SetBulletin.kt b/src/com/Torvald/Terrarum/ConsoleCommand/SetBulletin.kt new file mode 100644 index 000000000..a78054b6a --- /dev/null +++ b/src/com/Torvald/Terrarum/ConsoleCommand/SetBulletin.kt @@ -0,0 +1,31 @@ +package com.Torvald.Terrarum.ConsoleCommand + +import com.Torvald.Terrarum.LangPack.Lang +import com.Torvald.Terrarum.Terrarum +import com.Torvald.Terrarum.UserInterface.Notification + +/** + * Created by minjaesong on 16-01-23. + */ +class SetBulletin : ConsoleCommand { + override fun execute(args: Array) { + val testMsg = arrayOf( + Lang["ERROR_SAVE_CORRUPTED"], + Lang["MENU_LABEL_CONTINUE_QUESTION"] + ) + send(testMsg) + } + + override fun printUsage() { + + } + + /** + * Actually send notifinator + * @param message real message + */ + fun send(message: Array) { + Terrarum.game.sendNotification(message) + println("sent notifinator") + } +} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/SetLocale.java b/src/com/Torvald/Terrarum/ConsoleCommand/SetLocale.java deleted file mode 100644 index 7c2b7220f..000000000 --- a/src/com/Torvald/Terrarum/ConsoleCommand/SetLocale.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.Torvald.Terrarum.ConsoleCommand; - -import com.Torvald.ImageFont.GameFontBase; -import com.Torvald.Terrarum.LangPack.Lang; -import com.Torvald.Terrarum.Terrarum; -import org.apache.commons.csv.CSVRecord; -import org.newdawn.slick.SlickException; - -import java.io.IOException; - -/** - * Created by minjaesong on 16-01-25. - */ -public class SetLocale implements ConsoleCommand { - @Override - public void execute(String[] args) { - if (args.length == 2) { - String prevLocale = Terrarum.Companion.getGameLocale(); - Terrarum.Companion.setGameLocale(args[1]); - try { - new Lang(); - new Echo().execute("Set locale to '" + Terrarum.Companion.getGameLocale() + "'."); - } - catch (IOException e) { - new Echo().execute("could not read lang file."); - Terrarum.Companion.setGameLocale(prevLocale); - } - } - else if (args.length == 1) { - Echo echo = new Echo(); - echo.execute("Locales:"); - - CSVRecord record = Lang.getRecord("LANGUAGE_ID"); - record.forEach(field -> echo.execute("] " + field)); - } - else { - printUsage(); - } - } - - @Override - public void printUsage() { - new Echo().execute("Usage: setlocale [locale]"); - } -} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/SetLocale.kt b/src/com/Torvald/Terrarum/ConsoleCommand/SetLocale.kt new file mode 100644 index 000000000..08acbe7e2 --- /dev/null +++ b/src/com/Torvald/Terrarum/ConsoleCommand/SetLocale.kt @@ -0,0 +1,43 @@ +package com.Torvald.Terrarum.ConsoleCommand + +import com.Torvald.ImageFont.GameFontBase +import com.Torvald.Terrarum.LangPack.Lang +import com.Torvald.Terrarum.Terrarum +import org.apache.commons.csv.CSVRecord +import org.newdawn.slick.SlickException + +import java.io.IOException + +/** + * Created by minjaesong on 16-01-25. + */ +class SetLocale : ConsoleCommand { + override fun execute(args: Array) { + if (args.size == 2) { + val prevLocale = Terrarum.gameLocale + Terrarum.gameLocale = args[1] + try { + Echo().execute("Set locale to '" + Terrarum.gameLocale + "'.") + } + catch (e: IOException) { + Echo().execute("could not read lang file.") + Terrarum.gameLocale = prevLocale + } + + } + else if (args.size == 1) { + val echo = Echo() + echo.execute("Locales:") + + val record = Lang.getRecord("LANGUAGE_ID") + record.forEach { field -> echo.execute("] " + field) } + } + else { + printUsage() + } + } + + override fun printUsage() { + Echo().execute("Usage: setlocale [locale]") + } +} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/SpawnPhysTestBall.java b/src/com/Torvald/Terrarum/ConsoleCommand/SpawnPhysTestBall.java deleted file mode 100644 index d40b136c0..000000000 --- a/src/com/Torvald/Terrarum/ConsoleCommand/SpawnPhysTestBall.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.Torvald.Terrarum.ConsoleCommand; - -import com.Torvald.Terrarum.Actors.Actor; -import com.Torvald.Terrarum.Actors.ActorWithBody; -import com.Torvald.Terrarum.Actors.PhysTestBall; -import com.Torvald.Terrarum.MapDrawer.MapCamera; -import com.Torvald.Terrarum.Terrarum; - -/** - * Created by minjaesong on 16-03-05. - */ -public class SpawnPhysTestBall implements ConsoleCommand { - @Override - public void execute(String[] args) throws Exception { - if (args.length == 2) { - int mouseX = Terrarum.appgc.getInput().getMouseX(); - int mouseY = Terrarum.appgc.getInput().getMouseY(); - - float elasticity = new Float(args[1]); - - ActorWithBody ball = new PhysTestBall(); - ball.setPosition(mouseX + MapCamera.getCameraX() - , mouseY + MapCamera.getCameraY()); - ball.setElasticity(elasticity); - - Terrarum.game.addActor(ball); - } - else { - printUsage(); - } - } - - @Override - public void printUsage() { - new Echo().execute("usage: spawnball [elasticity]"); - } -} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/SpawnPhysTestBall.kt b/src/com/Torvald/Terrarum/ConsoleCommand/SpawnPhysTestBall.kt new file mode 100644 index 000000000..b9669748a --- /dev/null +++ b/src/com/Torvald/Terrarum/ConsoleCommand/SpawnPhysTestBall.kt @@ -0,0 +1,38 @@ +package com.Torvald.Terrarum.ConsoleCommand + +import com.Torvald.Terrarum.Actors.Actor +import com.Torvald.Terrarum.Actors.ActorWithBody +import com.Torvald.Terrarum.Actors.PhysTestBall +import com.Torvald.Terrarum.MapDrawer.MapCamera +import com.Torvald.Terrarum.Terrarum + +/** + * Created by minjaesong on 16-03-05. + */ +class SpawnPhysTestBall : ConsoleCommand { + @Throws(Exception::class) + override fun execute(args: Array) { + if (args.size == 2) { + val mouseX = Terrarum.appgc.input.mouseX + val mouseY = Terrarum.appgc.input.mouseY + + val elasticity = args[1].toFloat() + + val ball = PhysTestBall() + ball.setPosition( + (mouseX + MapCamera.cameraX).toFloat(), + (mouseY + MapCamera.cameraY).toFloat() + ) + ball.elasticity = elasticity + + Terrarum.game.addActor(ball) + } + else { + printUsage() + } + } + + override fun printUsage() { + Echo().execute("usage: spawnball [elasticity]") + } +} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/TeleportPlayer.java b/src/com/Torvald/Terrarum/ConsoleCommand/TeleportPlayer.java deleted file mode 100644 index cc4e8ccce..000000000 --- a/src/com/Torvald/Terrarum/ConsoleCommand/TeleportPlayer.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.Torvald.Terrarum.ConsoleCommand; - -import com.Torvald.Terrarum.Game; -import com.Torvald.Terrarum.MapDrawer.MapDrawer; -import com.Torvald.Terrarum.Terrarum; - -/** - * Created by minjaesong on 16-01-24. - */ -public class TeleportPlayer implements ConsoleCommand { - - @Override - public void execute(String[] args) { - if (args.length != 3) { - printUsage(); - } - else { - - int x, y; - try { - x = new Integer((args[1])) * MapDrawer.getTILE_SIZE() + (MapDrawer.getTILE_SIZE() / 2); - y = new Integer((args[2])) * MapDrawer.getTILE_SIZE() + (MapDrawer.getTILE_SIZE() / 2); - } - catch (NumberFormatException e) { - new Echo().execute("Wrong number input."); - return; - } - - Terrarum.game.player.setPosition(x, y); - } - } - - @Override - public void printUsage() { - new Echo().execute("Usage: teleport [x-tile] [y-tile]"); - } -} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/TeleportPlayer.kt b/src/com/Torvald/Terrarum/ConsoleCommand/TeleportPlayer.kt new file mode 100644 index 000000000..d244eee5c --- /dev/null +++ b/src/com/Torvald/Terrarum/ConsoleCommand/TeleportPlayer.kt @@ -0,0 +1,36 @@ +package com.Torvald.Terrarum.ConsoleCommand + +import com.Torvald.Terrarum.Game +import com.Torvald.Terrarum.MapDrawer.MapDrawer +import com.Torvald.Terrarum.Terrarum + +/** + * Created by minjaesong on 16-01-24. + */ +class TeleportPlayer : ConsoleCommand { + + override fun execute(args: Array) { + if (args.size != 3) { + printUsage() + } + else { + + val x: Int + val y: Int + try { + x = args[1].toInt() * MapDrawer.TILE_SIZE + MapDrawer.TILE_SIZE / 2 + y = args[2].toInt() * MapDrawer.TILE_SIZE + MapDrawer.TILE_SIZE / 2 + } + catch (e: NumberFormatException) { + Echo().execute("Wrong number input.") + return + } + + Terrarum.game.player.setPosition(x.toFloat(), y.toFloat()) + } + } + + override fun printUsage() { + Echo().execute("Usage: teleport [x-tile] [y-tile]") + } +} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/ToggleNoClip.java b/src/com/Torvald/Terrarum/ConsoleCommand/ToggleNoClip.java deleted file mode 100644 index 4d6efb387..000000000 --- a/src/com/Torvald/Terrarum/ConsoleCommand/ToggleNoClip.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.Torvald.Terrarum.ConsoleCommand; - -import com.Torvald.Terrarum.Game; -import com.Torvald.Terrarum.Terrarum; - -/** - * Created by minjaesong on 16-01-19. - */ -public class ToggleNoClip implements ConsoleCommand { - @Override - public void execute(String[] args) { - boolean status = Terrarum.game.player.isNoClip(); - - Terrarum.game.player.setNoClip(!status); - new Echo().execute("Set no-clip status to " + String.valueOf(!status)); - } - - @Override - public void printUsage() { - new Echo().execute("toggle no-clip status of player"); - } -} diff --git a/src/com/Torvald/Terrarum/ConsoleCommand/ToggleNoClip.kt b/src/com/Torvald/Terrarum/ConsoleCommand/ToggleNoClip.kt new file mode 100644 index 000000000..24dc5fb44 --- /dev/null +++ b/src/com/Torvald/Terrarum/ConsoleCommand/ToggleNoClip.kt @@ -0,0 +1,20 @@ +package com.Torvald.Terrarum.ConsoleCommand + +import com.Torvald.Terrarum.Game +import com.Torvald.Terrarum.Terrarum + +/** + * Created by minjaesong on 16-01-19. + */ +class ToggleNoClip : ConsoleCommand { + override fun execute(args: Array) { + val status = Terrarum.game.player.isNoClip() + + Terrarum.game.player.setNoClip(!status) + Echo().execute("Set no-clip status to " + (!status).toString()) + } + + override fun printUsage() { + Echo().execute("toggle no-clip status of player") + } +} diff --git a/src/com/Torvald/Terrarum/Game b/src/com/Torvald/Terrarum/Game deleted file mode 100644 index 34aec2639..000000000 --- a/src/com/Torvald/Terrarum/Game +++ /dev/null @@ -1,403 +0,0 @@ -package com.Torvald.Terrarum; - -import com.Torvald.Rand.HQRNG; -import com.Torvald.Terrarum.Actors.*; -import com.Torvald.Terrarum.ConsoleCommand.Authenticator; -import com.Torvald.Terrarum.ConsoleCommand.CommandDict; -import com.Torvald.Terrarum.GameControl.GameController; -import com.Torvald.Terrarum.GameControl.KeyMap; -import com.Torvald.Terrarum.GameMap.GameMap; -import com.Torvald.Terrarum.GameMap.WorldTime; -import com.Torvald.Terrarum.MapDrawer.LightmapRenderer; -import com.Torvald.Terrarum.MapDrawer.MapCamera; -import com.Torvald.Terrarum.MapDrawer.MapDrawer; -import com.Torvald.Terrarum.MapGenerator.MapGenerator; -import com.Torvald.Terrarum.MapGenerator.RoguelikeRandomiser; -import com.Torvald.Terrarum.TileProperties.TilePropCodex; -import com.Torvald.Terrarum.TileStat.TileStat; -import com.Torvald.Terrarum.UserInterface.*; -import com.jme3.math.FastMath; -import org.lwjgl.opengl.ARBShaderObjects; -import org.lwjgl.opengl.GL11; -import org.newdawn.slick.*; -import org.newdawn.slick.Graphics; -import org.newdawn.slick.fills.GradientFill; -import org.newdawn.slick.geom.Rectangle; -import org.newdawn.slick.state.BasicGameState; -import org.newdawn.slick.state.StateBasedGame; -import shader.Shader; - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.InputStreamReader; -import java.lang.management.ManagementFactory; -import java.util.HashSet; - -/** - * Created by minjaesong on 15-12-30. - */ -public class Game extends BasicGameState { - - public static long memInUse; - public static long totalVMMem; - int game_mode = 0; - - public GameMap map; - - public HashSet actorContainer = new HashSet<>(); - public HashSet uiContainer = new HashSet<>(); - - public UIHandler consoleHandler; - public UIHandler debugWindow; - public UIHandler notifinator; - - Player player; - - private Image GRADIENT_IMAGE; - private Rectangle skyBox; - - public float screenZoom = 1.0f; - public final float ZOOM_MAX = 2.0f; - public final float ZOOM_MIN = 0.25f; - - private Shader shader12BitCol; - private Shader shaderBlurH; - private Shader shaderBlurV; - - public static Authenticator auth = new Authenticator(); - - public Game() throws SlickException { } - - - private boolean useShader; - private int shaderProgram = 0; - - - private final int ENV_COLTEMP_SUNRISE = 2500; - private final int ENV_SUNLIGHT_DELTA = MapDrawer.getENV_COLTEMP_NOON() - ENV_COLTEMP_SUNRISE; - - - @Override - public void init(GameContainer gameContainer, StateBasedGame stateBasedGame) throws - SlickException { - new GameController(); - KeyMap.build(); - GameController.setKeyMap(new KeyMap()); - - - shader12BitCol = Shader.makeShader("./res/4096.vrt", "./res/4096.frg"); - shaderBlurH = Shader.makeShader("./res/blurH.vrt", "./res/blur.frg"); - shaderBlurV = Shader.makeShader("./res/blurV.vrt", "./res/blur.frg"); - - - GRADIENT_IMAGE = new Image("res/graphics/sky_colour.png"); - skyBox = new Rectangle(0, 0, Terrarum.WIDTH, Terrarum.HEIGHT); - - new WorldTime(); - new TilePropCodex(); - // new ItemPropCodex() -- This is kotlin object and already initialised. - - map = new GameMap(8192, 2048); - map.setGravitation(9.8f); - - MapGenerator.attachMap(map); - MapGenerator.setSeed(0x51621D2); - //MapGenerator.setSeed(new HQRNG().nextLong()); - MapGenerator.generateMap(); - - RoguelikeRandomiser.setSeed(0x540198); - //RoguelikeRandomiser.setSeed(new HQRNG().nextLong()); - - - new CommandDict(); - - // add new player and put it to actorContainer - //player = new Player(); - player = PFSigrid.build(); - //player.setNoClip(true); - actorContainer.add(player); - - consoleHandler = new UIHandler(new ConsoleWindow()); - consoleHandler.setPosition(0, 0); - - debugWindow = new UIHandler(new BasicDebugInfoWindow()); - debugWindow.setPosition(0, 0); - - notifinator = new UIHandler(new Notification()); - notifinator.setPosition( - (Terrarum.WIDTH - notifinator.getUI().getWidth()) - / 2 - , Terrarum.HEIGHT - notifinator.getUI().getHeight() - ); - notifinator.setVisibility(true); - } - - public Player getPlayer() { - return player; - } - - @Override - public void update(GameContainer gc, StateBasedGame sbg, int delta_t) { - setAppTitle(); - - // GL at after_sunrise-noon_before_sunset - //map.setGlobalLight(); - - GameController.processInput(gc.getInput()); - - TileStat.update(); - - MapDrawer.update(gc, delta_t); - MapCamera.update(gc, delta_t); - - actorContainer.forEach(actor -> actor.update(gc, delta_t)); - actorContainer.forEach( - actor -> { - if (actor instanceof Visible) { - ((Visible) actor).updateBodySprite(gc, delta_t); - } - if (actor instanceof Glowing) { - ((Glowing) actor).updateGlowSprite(gc, delta_t); - } - } - ); - - uiContainer.forEach(ui -> ui.update(gc, delta_t)); - - notifinator.update(gc, delta_t); - - Terrarum.appgc.setVSync(Terrarum.appgc.getFPS() >= Terrarum.VSYNC_TRIGGER_THRESHOLD); - } - - private void setAppTitle() { - Runtime runtime = Runtime.getRuntime(); - memInUse = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() >> 20; - totalVMMem = runtime.maxMemory() >> 20; - - Terrarum.appgc.setTitle( - "Simple Slick Game — FPS: " - + Terrarum.appgc.getFPS() + " (" - + String.valueOf(Terrarum.TARGET_INTERNAL_FPS) - + ") — " - + String.valueOf(memInUse) + "M / " - + String.valueOf(totalVMMem) + "M" - ); - } - - @Override - public void render(GameContainer gc, StateBasedGame sbg, Graphics g) { - - drawSkybox(g); - - // compensate for zoom. UIs have to be treated specially! (see UIHandler) - g.translate( - -MapCamera.getCameraX() * screenZoom - , -MapCamera.getCameraY() * screenZoom - ); - - MapCamera.renderBehind(gc, g); - - actorContainer.forEach( - actor -> { if (actor instanceof Visible) ((Visible) actor).drawBody(gc, g); } - ); - actorContainer.forEach( - actor -> { if (actor instanceof Glowing) ((Glowing) actor).drawGlow(gc, g); } - ); - - LightmapRenderer.renderLightMap(); - - MapCamera.renderFront(gc, g); - MapDrawer.render(gc, g); - - setBlendModeMul(); - MapDrawer.drawEnvOverlay(g); - LightmapRenderer.draw(g); - setBlendModeNormal(); - - uiContainer.forEach(ui -> ui.render(gc, g)); - debugWindow.render(gc, g); - consoleHandler.render(gc, g); - notifinator.render(gc, g); - } - - public boolean addActor(Actor e) { - return actorContainer.add(e); - } - - public boolean removeActor(Actor e) { - return actorContainer.remove(e); - } - - private Color[] getGradientColour(int timeSec) { - Color[] colourTable = new Color[2]; - - int gradMapWidth = GRADIENT_IMAGE.getWidth(); - int phase = Math.round((timeSec / WorldTime.DAY_LENGTH) * gradMapWidth); - - //update in every INTERNAL_FRAME frames - colourTable[0] = GRADIENT_IMAGE.getColor(phase, 0); - colourTable[1] = GRADIENT_IMAGE.getColor(phase, 1); - - return colourTable; - } - - public void keyPressed(int key, char c) { - GameController.keyPressed(key, c); - } - - public void keyReleased(int key, char c) { - GameController.keyReleased(key, c); - } - - public void mouseMoved(int oldx, int oldy, int newx, int newy) { - GameController.mouseMoved(oldx, oldy, newx, newy); - } - - public void mouseDragged(int oldx, int oldy, int newx, int newy) { - GameController.mouseDragged(oldx, oldy, newx, newy); - } - - public void mousePressed(int button, int x, int y) { - GameController.mousePressed(button, x, y); - } - - public void mouseReleased(int button, int x, int y) { - GameController.mouseReleased(button, x, y); - } - - public void mouseWheelMoved(int change) { - GameController.mouseWheelMoved(change); - } - - public void controllerButtonPressed(int controller, int button) { - GameController.controllerButtonPressed(controller, button); - } - - public void controllerButtonReleased(int controller, int button) { - GameController.controllerButtonReleased(controller, button); - } - - @Override - public int getID() { - return Terrarum.SCENE_ID_GAME; - } - - private void drawSkybox(Graphics g) { - Color[] colourTable = getGradientColour(Terrarum.game.map.getWorldTime().elapsedSeconds()); - GradientFill skyColourFill = new GradientFill(0, 0, colourTable[0], 0, Terrarum.HEIGHT, colourTable[1]); - g.fill(skyBox, skyColourFill); - } - - private void setBlendModeMul() { - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_DST_COLOR, GL11.GL_ONE_MINUS_SRC_ALPHA); - } - - private void setBlendModeNormal() { - GL11.glDisable(GL11.GL_BLEND); - Terrarum.appgc.getGraphics().setDrawMode(Graphics.MODE_NORMAL); - } - - public void sendNotification(String[] msg) { - ((Notification) notifinator.getUI()).sendNotification(msg); - } - - private int createShader(String filename, int shaderType) throws Exception { - int shader = 0; - try { - shader = ARBShaderObjects.glCreateShaderObjectARB(shaderType); - - if(shader == 0) - return 0; - - ARBShaderObjects.glShaderSourceARB(shader, readFileAsString(filename)); - ARBShaderObjects.glCompileShaderARB(shader); - - if (ARBShaderObjects.glGetObjectParameteriARB(shader, ARBShaderObjects.GL_OBJECT_COMPILE_STATUS_ARB) == GL11.GL_FALSE) - throw new RuntimeException("Error creating shader: " + getLogInfo(shader)); - - return shader; - } - catch(Exception exc) { - ARBShaderObjects.glDeleteObjectARB(shader); - throw exc; - } - } - - private static String getLogInfo(int obj) { - return ARBShaderObjects.glGetInfoLogARB(obj, ARBShaderObjects.glGetObjectParameteriARB(obj, ARBShaderObjects.GL_OBJECT_INFO_LOG_LENGTH_ARB)); - } - - private String readFileAsString(String filename) throws Exception { - StringBuilder source = new StringBuilder(); - - FileInputStream in = new FileInputStream(filename); - - Exception exception = null; - - BufferedReader reader; - try{ - reader = new BufferedReader(new InputStreamReader(in,"UTF-8")); - - Exception innerExc= null; - try { - String line; - while((line = reader.readLine()) != null) - source.append(line).append('\n'); - } - catch(Exception exc) { - exception = exc; - } - finally { - try { - reader.close(); - } - catch(Exception exc) { - if(innerExc == null) - innerExc = exc; - else - exc.printStackTrace(); - } - } - - if(innerExc != null) - throw innerExc; - } - catch(Exception exc) { - exception = exc; - } - finally { - try { - in.close(); - } - catch(Exception exc) { - if(exception == null) - exception = exc; - else - exc.printStackTrace(); - } - - if(exception != null) - throw exception; - } - - return source.toString(); - } - - public long getMemInUse() { - return memInUse; - } - - public long getTotalVMMem() { - return totalVMMem; - } - - private int getSunlightColtemp() { - int half_today = WorldTime.DAY_LENGTH / 2; - int timeToday = WorldTime.elapsedSeconds(); - float sunAlt = (timeToday < half_today) ? - timeToday / half_today * FastMath.PI - : 0f; - return Math.round(ENV_COLTEMP_SUNRISE + (ENV_SUNLIGHT_DELTA * FastMath.sin(sunAlt))); - } -} diff --git a/src/com/Torvald/Terrarum/Game.kt b/src/com/Torvald/Terrarum/Game.kt index 2466e9246..3d5c3e631 100644 --- a/src/com/Torvald/Terrarum/Game.kt +++ b/src/com/Torvald/Terrarum/Game.kt @@ -185,7 +185,7 @@ constructor() : BasicGameState() { // compensate for zoom. UIs have to be treated specially! (see UIHandler) g.translate( - -MapCamera.getCameraX() * screenZoom, -MapCamera.getCameraY() * screenZoom) + -MapCamera.cameraX * screenZoom, -MapCamera.cameraY * screenZoom) MapCamera.renderBehind(gc, g) @@ -305,7 +305,5 @@ constructor() : BasicGameState() { /** * extension function for org.newdawn.slick.Color */ - fun Color.getRGB24(): Int = (this.redByte shl 16) or - (this.greenByte shl 8) or - (this.blueByte) + fun Color.getRGB24(): Int = (this.redByte shl 16) or (this.greenByte shl 8) or (this.blueByte) } diff --git a/src/com/Torvald/Terrarum/GameControl/GameController.kt b/src/com/Torvald/Terrarum/GameControl/GameController.kt index 05dca0526..b3e44d330 100644 --- a/src/com/Torvald/Terrarum/GameControl/GameController.kt +++ b/src/com/Torvald/Terrarum/GameControl/GameController.kt @@ -16,8 +16,8 @@ import org.newdawn.slick.Input object GameController { fun processInput(input: Input) { - val mouseTileX = ((MapCamera.getCameraX() + input.mouseX / Terrarum.game.screenZoom) / MapDrawer.TILE_SIZE).toInt() - val mouseTileY = ((MapCamera.getCameraY() + input.mouseY / Terrarum.game.screenZoom) / MapDrawer.TILE_SIZE).toInt() + val mouseTileX = ((MapCamera.cameraX + input.mouseX / Terrarum.game.screenZoom) / MapDrawer.TILE_SIZE).toInt() + val mouseTileY = ((MapCamera.cameraY + input.mouseY / Terrarum.game.screenZoom) / MapDrawer.TILE_SIZE).toInt() KeyToggler.update(input) diff --git a/src/com/Torvald/Terrarum/GameMap/GameMap.java b/src/com/Torvald/Terrarum/GameMap/GameMap.java deleted file mode 100644 index 7125ff7ce..000000000 --- a/src/com/Torvald/Terrarum/GameMap/GameMap.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * MapLoader version 1.2 - * Release date 2013-05-20 - * Copyright 2013 SKYHi14 - * - * The program is distributed in GNU GPL Licence version 3. - * See http://www.gnu.org/licenses/gpl.html for information. - */ - -package com.Torvald.Terrarum.GameMap; - -import org.newdawn.slick.SlickException; - -public class GameMap { - - //layers - private volatile MapLayer layerWall; - private volatile MapLayer layerTerrain; - private volatile MapLayer layerWire; - private volatile PairedMapLayer wallDamage; - private volatile PairedMapLayer terrainDamage; - - //properties - private int width; - private int height; - private int spawnX; - private int spawnY; - - public static transient final int WALL = 0; - public static transient final int TERRAIN = 1; - public static transient final int WIRE = 2; - - //public World physWorld = new World( new Vec2(0, -TerrarumMain.game.gravitationalAccel) ); - //physics - private float gravitation; - private int globalLight; - private WorldTime worldTime; - - public static transient final int TILES_SUPPORTED = MapLayer.RANGE * PairedMapLayer.RANGE; - public static transient final byte BITS = 1; // 1 for Byte, 2 for Char, 4 for Int, 8 for Long - public static transient final byte LAYERS = 4; // terrain, wall (terrainDamage + wallDamage), wire - - /** - * @param width - * @param height - * @throws SlickException - */ - public GameMap(int width, int height) throws SlickException { - this.width = width; - this.height = height; - this.spawnX = width / 2; - this.spawnY = 200; - - layerTerrain = new MapLayer(width, height); - layerWall = new MapLayer(width, height); - layerWire = new MapLayer(width, height); - terrainDamage = new PairedMapLayer(width, height); - wallDamage = new PairedMapLayer(width, height); - - globalLight = (char) 0; - worldTime = new WorldTime(); - } - - public void setGravitation(float g) { - gravitation = g; - } - - /** - * Get 2d array data of terrain - * - * @return byte[][] terrain layer - */ - public byte[][] getTerrainArray() { - return layerTerrain.data; - } - - /** - * Get 2d array data of wall - * - * @return byte[][] wall layer - */ - public byte[][] getWallArray() { - return layerWall.data; - } - - /** - * Get 2d array data of wire - * - * @return byte[][] wire layer - */ - public byte[][] getWireArray() { - return layerWire.data; - } - - /** - * Get paired array data of damage codes. - * Format: 0baaaabbbb, aaaa for x = 0, 2, 4, ..., bbbb for x = 1, 3, 5, ... - * @return byte[][] damage code pair - */ - public byte[][] getDamageDataArray() { - return terrainDamage.dataPair; - } - - /** - * Get MapLayer object of terrain - * - * @return MapLayer terrain layer - */ - public MapLayer getLayerTerrain() { - return layerTerrain; - } - - public MapLayer getLayerWall() { - return layerWall; - } - - public MapLayer getLayerWire() { - return layerWire; - } - - public PairedMapLayer getTerrainDamage() { - return terrainDamage; - } - - public PairedMapLayer getWallDamage() { - return wallDamage; - } - - public int getTileFromWall(int x, int y) { - return layerWall.getTile(x, y) * PairedMapLayer.RANGE + getWallDamage(x, y); - } - - public int getTileFromTerrain(int x, int y) { - return layerTerrain.getTile(x, y) * PairedMapLayer.RANGE + getTerrainDamage(x, y); - } - - public int getTileFromWire(int x, int y) { - return layerWire.getTile(x, y); - } - - public int getWallDamage(int x, int y) { - return wallDamage.getData(x, y); - } - - public int getTerrainDamage(int x, int y) { - return terrainDamage.getData(x, y); - } - - /** - * Set the tile of wall as specified, with damage value of zero. - * @param x - * @param y - * @param combinedTilenum (tilenum * 16) + damage - */ - public void setTileWall(int x, int y, int combinedTilenum) { - setTileWall(x, y - , (byte) (combinedTilenum / PairedMapLayer.RANGE) - , combinedTilenum % PairedMapLayer.RANGE); - } - - /** - * Set the tile of wall as specified, with damage value of zero. - * @param x - * @param y - * @param combinedTilenum (tilenum * 16) + damage - */ - public void setTileTerrain(int x, int y, int combinedTilenum) { - setTileTerrain(x, y - , (byte) (combinedTilenum / PairedMapLayer.RANGE) - , combinedTilenum % PairedMapLayer.RANGE); - } - - public void setTileWall(int x, int y, byte tile, int damage) { - layerWall.setTile(x, y, tile); - wallDamage.setData(x, y, damage); - } - - public void setTileTerrain(int x, int y, byte tile, int damage) { - layerTerrain.setTile(x, y, tile); - terrainDamage.setData(x, y, damage); - } - - public void setTileWire(int x, int y, byte tile) { - layerWire.data[y][x] = tile; - } - - public int getTileFrom(int mode, int x, int y) { - if (mode == TERRAIN) { return getTileFromTerrain(x, y); } - else if (mode == WALL) { return getTileFromWall(x, y); } - else if (mode == WIRE) { return getTileFromWire(x, y); } - else throw new IllegalArgumentException("illegal mode input: " + String.valueOf(mode)); - } - - public void overwriteLayerWall(MapLayer layerData) { - layerWall = layerData; - } - - public void overwriteLayerTerrain(MapLayer layerData) { - layerTerrain = layerData; - } - - private int uint8ToInt32(byte x) { - int ret; - if ((x & 0b1000_0000) != 0) { - ret = x & 0b1111_1111; - } else { - ret = x; - } - return ret; - } - - public float getGravitation() { - return gravitation; - } - - public int getGlobalLight() { - return globalLight; - } - - public void setGlobalLight(int globalLight) { - this.globalLight = globalLight; - } - - public WorldTime getWorldTime() { - return worldTime; - } - - public void updateWorldTime(int delta) { - worldTime.update(delta); - } - - public int getWidth() { - return width; - } - - public int getHeight() { - return height; - } - - public int getSpawnX() { - return spawnX; - } - - public int getSpawnY() { - return spawnY; - } -} \ No newline at end of file diff --git a/src/com/Torvald/Terrarum/GameMap/GameMap.kt b/src/com/Torvald/Terrarum/GameMap/GameMap.kt new file mode 100644 index 000000000..44a529569 --- /dev/null +++ b/src/com/Torvald/Terrarum/GameMap/GameMap.kt @@ -0,0 +1,178 @@ +/* + * MapLoader version 1.2 + * Release date 2013-05-20 + * Copyright 2013 SKYHi14 + * + * The program is distributed in GNU GPL Licence version 3. + * See http://www.gnu.org/licenses/gpl.html for information. + */ + +package com.Torvald.Terrarum.GameMap + +import org.newdawn.slick.SlickException + +class GameMap +/** + * @param width + * * + * @param height + * * + * @throws SlickException + */ +@Throws(SlickException::class) +constructor(//properties + val width: Int, val height: Int) { + + //layers + val layerWall: MapLayer + /** + * Get MapLayer object of terrain + + * @return MapLayer terrain layer + */ + val layerTerrain: MapLayer + val layerWire: MapLayer + val wallDamage: PairedMapLayer + val terrainDamage: PairedMapLayer + val spawnX: Int + val spawnY: Int + + //public World physWorld = new World( new Vec2(0, -TerrarumMain.game.gravitationalAccel) ); + //physics + var gravitation: Float = 0.toFloat() + var globalLight: Int = 0 + val worldTime: WorldTime + + init { + this.spawnX = width / 2 + this.spawnY = 200 + + layerTerrain = MapLayer(width, height) + layerWall = MapLayer(width, height) + layerWire = MapLayer(width, height) + terrainDamage = PairedMapLayer(width, height) + wallDamage = PairedMapLayer(width, height) + + globalLight = 0.toChar().toInt() + worldTime = WorldTime() + } + + /** + * Get 2d array data of terrain + + * @return byte[][] terrain layer + */ + val terrainArray: Array + get() = layerTerrain.data + + /** + * Get 2d array data of wall + + * @return byte[][] wall layer + */ + val wallArray: Array + get() = layerWall.data + + /** + * Get 2d array data of wire + + * @return byte[][] wire layer + */ + val wireArray: Array + get() = layerWire.data + + /** + * Get paired array data of damage codes. + * Format: 0baaaabbbb, aaaa for x = 0, 2, 4, ..., bbbb for x = 1, 3, 5, ... + * @return byte[][] damage code pair + */ + val damageDataArray: Array + get() = terrainDamage.dataPair + + fun getTileFromWall(x: Int, y: Int): Int { + return layerWall.getTile(x, y) * PairedMapLayer.RANGE + getWallDamage(x, y) + } + + fun getTileFromTerrain(x: Int, y: Int): Int { + return layerTerrain.getTile(x, y) * PairedMapLayer.RANGE + getTerrainDamage(x, y) + } + + fun getTileFromWire(x: Int, y: Int): Int { + return layerWire.getTile(x, y) + } + + fun getWallDamage(x: Int, y: Int): Int { + return wallDamage.getData(x, y) + } + + fun getTerrainDamage(x: Int, y: Int): Int { + return terrainDamage.getData(x, y) + } + + /** + * Set the tile of wall as specified, with damage value of zero. + * @param x + * * + * @param y + * * + * @param combinedTilenum (tilenum * 16) + damage + */ + fun setTileWall(x: Int, y: Int, combinedTilenum: Int) { + setTileWall(x, y, (combinedTilenum / PairedMapLayer.RANGE).toByte(), combinedTilenum % PairedMapLayer.RANGE) + } + + /** + * Set the tile of wall as specified, with damage value of zero. + * @param x + * * + * @param y + * * + * @param combinedTilenum (tilenum * 16) + damage + */ + fun setTileTerrain(x: Int, y: Int, combinedTilenum: Int) { + setTileTerrain(x, y, (combinedTilenum / PairedMapLayer.RANGE).toByte(), combinedTilenum % PairedMapLayer.RANGE) + } + + fun setTileWall(x: Int, y: Int, tile: Byte, damage: Int) { + layerWall.setTile(x, y, tile) + wallDamage.setData(x, y, damage) + } + + fun setTileTerrain(x: Int, y: Int, tile: Byte, damage: Int) { + layerTerrain.setTile(x, y, tile) + terrainDamage.setData(x, y, damage) + } + + fun setTileWire(x: Int, y: Int, tile: Byte) { + layerWire.data[y][x] = tile + } + + fun getTileFrom(mode: Int, x: Int, y: Int): Int { + if (mode == TERRAIN) { + return getTileFromTerrain(x, y) + } + else if (mode == WALL) { + return getTileFromWall(x, y) + } + else if (mode == WIRE) { + return getTileFromWire(x, y) + } + else + throw IllegalArgumentException("illegal mode input: " + mode.toString()) + } + + fun updateWorldTime(delta: Int) { + worldTime.update(delta) + } + + companion object { + + @Transient val WALL = 0 + @Transient val TERRAIN = 1 + @Transient val WIRE = 2 + + @Transient val TILES_SUPPORTED = MapLayer.RANGE * PairedMapLayer.RANGE + @Transient val BITS: Byte = 1 // 1 for Byte, 2 for Char, 4 for Int, 8 for Long + @Transient val LAYERS: Byte = 4 // terrain, wall (terrainDamage + wallDamage), wire + } +} \ No newline at end of file diff --git a/src/com/Torvald/Terrarum/GameMap/MapLayer.java b/src/com/Torvald/Terrarum/GameMap/MapLayer.java deleted file mode 100644 index 203abc6ac..000000000 --- a/src/com/Torvald/Terrarum/GameMap/MapLayer.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.Torvald.Terrarum.GameMap; - -import java.io.Serializable; -import java.util.Iterator; -import java.util.Spliterator; -import java.util.function.Consumer; - -/** - * Created by minjaesong on 16-01-17. - */ -public class MapLayer implements Iterable { - - byte[][] data; - - public int width; - public int height; - - public static transient final int RANGE = 256; - - public MapLayer(int width, int height) { - this.width = width; - this.height = height; - - data = new byte[height][width]; - - for (int i = 0; i < height; i++) { - for (int j = 0; j < width; j++) { - data[i][j] = 0; - } - } - } - - /** - * Returns an iterator over elements of type {@code T}. - * - * @return an Iterator. - */ - @Override - public Iterator iterator() { - return new Iterator() { - - private int iteratorCount = 0; - - @Override - public boolean hasNext() { - return iteratorCount < width * height; - } - - @Override - public Byte next() { - int y = iteratorCount / width; - int x = iteratorCount % width; - // advance counter - iteratorCount += 1; - - return data[y][x]; - } - }; - } - - /** - * Performs the given action for each element of the {@code Iterable} - * until all elements have been processed or the action throws an - * exception. Unless otherwise specified by the implementing class, - * actions are performed in the order of iteration (if an iteration order - * is specified). Exceptions thrown by the action are relayed to the - * caller. - * - * @param action The action to be performed for each element - * @throws NullPointerException if the specified action is null - * @implSpec

The default implementation behaves as if: - *

{@code
-     *     for (T t : this)
-     *         action.accept(t);
-     * }
- * @since 1.8 - */ - @Override - public void forEach(Consumer action) { - for (Byte b : this) { - action.accept(b); - } - } - - /** - * Creates a {@link java.util.Spliterator} over the elements described by this - * {@code Iterable}. - * - * @return a {@code Spliterator} over the elements described by this - * {@code Iterable}. - * @implSpec The default implementation creates an - * early-binding - * spliterator from the iterable's {@code Iterator}. The spliterator - * inherits the fail-fast properties of the iterable's iterator. - * @implNote The default implementation should usually be overridden. The - * spliterator returned by the default implementation has poor splitting - * capabilities, is unsized, and does not report any spliterator - * characteristics. Implementing classes can nearly always provide a - * better implementation. - * @since 1.8 - */ - @Override - public Spliterator spliterator() { - throw new UnsupportedOperationException(); - } - - int getTile(int x, int y) { - return uint8ToInt32(data[y][x]); - } - - void setTile(int x, int y, byte tile) { - data[y][x] = tile; - } - - private int uint8ToInt32(byte x) { - int ret; - if ((x & 0b1000_0000) != 0) { - ret = (x & 0b0111_1111) | (x & 0b1000_0000); - } - else { - ret = x; - } - return ret; - } -} - diff --git a/src/com/Torvald/Terrarum/GameMap/MapLayer.kt b/src/com/Torvald/Terrarum/GameMap/MapLayer.kt new file mode 100644 index 000000000..2c89c3942 --- /dev/null +++ b/src/com/Torvald/Terrarum/GameMap/MapLayer.kt @@ -0,0 +1,58 @@ +package com.Torvald.Terrarum.GameMap + +import java.io.Serializable +import java.util.Spliterator +import java.util.function.Consumer + +/** + * Created by minjaesong on 16-01-17. + */ +class MapLayer(var width: Int, var height: Int) : Iterable { + + internal var data: Array + + init { + data = Array(height) { ByteArray(width) } + } + + /** + * Returns an iterator over elements of type `T`. + + * @return an Iterator. + */ + override fun iterator(): Iterator { + return object : Iterator { + + private var iteratorCount = 0 + + override fun hasNext(): Boolean { + return iteratorCount < width * height + } + + override fun next(): Byte { + val y = iteratorCount / width + val x = iteratorCount % width + // advance counter + iteratorCount += 1 + + return data[y][x] + } + } + } + + internal fun getTile(x: Int, y: Int): Int { + return uint8ToInt32(data[y][x]) + } + + internal fun setTile(x: Int, y: Int, tile: Byte) { + data[y][x] = tile + } + + private fun uint8ToInt32(x: Byte): Int = java.lang.Byte.toUnsignedInt(x) + + companion object { + + @Transient @JvmStatic val RANGE = 256 + } +} + diff --git a/src/com/Torvald/Terrarum/GameMap/MapPoint.java b/src/com/Torvald/Terrarum/GameMap/MapPoint.java deleted file mode 100644 index 8b1a134dd..000000000 --- a/src/com/Torvald/Terrarum/GameMap/MapPoint.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.Torvald.Terrarum.GameMap; - -import com.Torvald.Point.Point2f; - -import java.io.Serializable; - - -public class MapPoint { - private Point2f startPoint; - private Point2f endPoint; - - public MapPoint(){ - - } - - public MapPoint(Point2f p1, Point2f p2){ - setPoint(p1, p2); - } - - public MapPoint(int x1, int y1, int x2, int y2){ - setPoint(x1, y1, x2, y2); - } - - public void setPoint(Point2f p1, Point2f p2){ - startPoint = p1; - endPoint = p2; - } - - public void setPoint(int x1, int y1, int x2, int y2){ - startPoint = new Point2f(x1, y1); - endPoint = new Point2f(x2, y2); - } - - public Point2f getStartPoint(){ - return startPoint; - } - - public Point2f getEndPoint(){ - return endPoint; - } -} diff --git a/src/com/Torvald/Terrarum/GameMap/MapPoint.kt b/src/com/Torvald/Terrarum/GameMap/MapPoint.kt new file mode 100644 index 000000000..a449e2370 --- /dev/null +++ b/src/com/Torvald/Terrarum/GameMap/MapPoint.kt @@ -0,0 +1,35 @@ +package com.Torvald.Terrarum.GameMap + +import com.Torvald.Point.Point2f + +import java.io.Serializable + + +class MapPoint { + var startPoint: Point2f? = null + private set + var endPoint: Point2f? = null + private set + + constructor() { + + } + + constructor(p1: Point2f, p2: Point2f) { + setPoint(p1, p2) + } + + constructor(x1: Int, y1: Int, x2: Int, y2: Int) { + setPoint(x1, y1, x2, y2) + } + + fun setPoint(p1: Point2f, p2: Point2f) { + startPoint = p1 + endPoint = p2 + } + + fun setPoint(x1: Int, y1: Int, x2: Int, y2: Int) { + startPoint = Point2f(x1.toFloat(), y1.toFloat()) + endPoint = Point2f(x2.toFloat(), y2.toFloat()) + } +} diff --git a/src/com/Torvald/Terrarum/GameMap/PairedMapLayer.java b/src/com/Torvald/Terrarum/GameMap/PairedMapLayer.java deleted file mode 100644 index 23e003d45..000000000 --- a/src/com/Torvald/Terrarum/GameMap/PairedMapLayer.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.Torvald.Terrarum.GameMap; - -import java.io.Serializable; -import java.util.Iterator; -import java.util.Spliterator; -import java.util.function.Consumer; - -/** - * Created by minjaesong on 16-02-15. - */ -public class PairedMapLayer implements Iterable { - - /** - * 0b_xxxx_yyyy, x for lower index, y for higher index - * - * e.g. - * - * 0110 1101 is interpreted as - * 6 for tile 0, 13 for tile 1. - */ - byte[][] dataPair; - - public int width; - public int height; - - public static transient final int RANGE = 16; - - public PairedMapLayer(int width, int height) { - this.width = width / 2; - this.height = height; - - dataPair = new byte[height][width / 2]; - - for (int i = 0; i < height; i++) { - for (int j = 0; j < width / 2; j++) { - dataPair[i][j] = 0; - } - } - } - - /** - * Returns an iterator over elements of type {@code T}. - * Note: this iterator will return combined damage, that is 0bxxxx_yyyy as whole. - * - * @return an Iterator. - */ - @Override - public Iterator iterator() { - return new Iterator() { - - private int iteratorCount = 0; - - @Override - public boolean hasNext() { - return iteratorCount < width * height; - } - - @Override - public Byte next() { - int y = iteratorCount / width; - int x = iteratorCount % width; - // advance counter - iteratorCount += 1; - - return dataPair[y][x]; - } - }; - } - - /** - * Performs the given action for each element of the {@code Iterable} - * until all elements have been processed or the action throws an - * exception. Unless otherwise specified by the implementing class, - * actions are performed in the order of iteration (if an iteration order - * is specified). Exceptions thrown by the action are relayed to the - * caller. - * - * Note: this iterator will return combined damage, that is 0bxxxx_yyyy as whole. - * - * @param action The action to be performed for each element - * @throws NullPointerException if the specified action is null - * @implSpec

The default implementation behaves as if: - *

{@code
-     *     for (T t : this)
-     *         action.accept(t);
-     * }
- * @since 1.8 - */ - @Override - public void forEach(Consumer action) { - for (Byte b : this) { - action.accept(b); - } - } - - /** - * Creates a {@link Spliterator} over the elements described by this - * {@code Iterable}. - * - * @return a {@code Spliterator} over the elements described by this - * {@code Iterable}. - * @implSpec The default implementation creates an - * early-binding - * spliterator from the iterable's {@code Iterator}. The spliterator - * inherits the fail-fast properties of the iterable's iterator. - * @implNote The default implementation should usually be overridden. The - * spliterator returned by the default implementation has poor splitting - * capabilities, is unsized, and does not report any spliterator - * characteristics. Implementing classes can nearly always provide a - * better implementation. - * @since 1.8 - */ - @Override - public Spliterator spliterator() { - throw new UnsupportedOperationException(); - } - - int getData(int x, int y) { - if ((x & 0x1) == 0) - // higher four bits for i = 0, 2, 4, ... - return (dataPair[y][x / 2] & 0xF0) >>> 4; - else - // lower four bits for i = 1, 3, 5, ... - return dataPair[y][x / 2] & 0x0F; - } - - void setData(int x, int y, int data) { - if (data < 0 || data >= 16) throw new IllegalArgumentException("[PairedMapLayer] " + data + ": invalid data value."); - if ((x & 0x1) == 0) - // higher four bits for i = 0, 2, 4, ... - dataPair[y][x / 2] = (byte) (dataPair[y][x / 2] & 0x0F | (data & 0xF) << 4); - else - // lower four bits for i = 1, 3, 5, ... - dataPair[y][x / 2] = (byte) (dataPair[y][x / 2] & 0xF0 | (data & 0xF)); - } -} diff --git a/src/com/Torvald/Terrarum/GameMap/PairedMapLayer.kt b/src/com/Torvald/Terrarum/GameMap/PairedMapLayer.kt new file mode 100644 index 000000000..a4fd75fa0 --- /dev/null +++ b/src/com/Torvald/Terrarum/GameMap/PairedMapLayer.kt @@ -0,0 +1,82 @@ +package com.Torvald.Terrarum.GameMap + +import java.io.Serializable +import java.util.Spliterator +import java.util.function.Consumer + +/** + * Created by minjaesong on 16-02-15. + */ +class PairedMapLayer(width: Int, var height: Int) : Iterable { + + /** + * 0b_xxxx_yyyy, x for lower index, y for higher index + + * e.g. + + * 0110 1101 is interpreted as + * 6 for tile 0, 13 for tile 1. + */ + internal var dataPair: Array + + var width: Int = 0 + + init { + this.width = width / 2 + + dataPair = Array(height) { ByteArray(width / 2) } + } + + /** + * Returns an iterator over elements of type `T`. + * Note: this iterator will return combined damage, that is 0bxxxx_yyyy as whole. + + * @return an Iterator. + */ + override fun iterator(): Iterator { + return object : Iterator { + + private var iteratorCount = 0 + + override fun hasNext(): Boolean { + return iteratorCount < width * height + } + + override fun next(): Byte { + val y = iteratorCount / width + val x = iteratorCount % width + // advance counter + iteratorCount += 1 + + return dataPair[y][x] + } + } + } + + internal fun getData(x: Int, y: Int): Int { + if (x and 0x1 == 0) + // higher four bits for i = 0, 2, 4, ... + return (java.lang.Byte.toUnsignedInt(dataPair[y][x / 2]) and 0xF0) ushr 4 + else + // lower four bits for i = 1, 3, 5, ... + return java.lang.Byte.toUnsignedInt(dataPair[y][x / 2]) and 0x0F + } + + internal fun setData(x: Int, y: Int, data: Int) { + if (data < 0 || data >= 16) throw IllegalArgumentException("[PairedMapLayer] $data: invalid data value.") + if (x and 0x1 == 0) + // higher four bits for i = 0, 2, 4, ... + dataPair[y][x / 2] = + (java.lang.Byte.toUnsignedInt(dataPair[y][x / 2]) and 0x0F + or (data and 0xF shl 4)).toByte() + else + // lower four bits for i = 1, 3, 5, ... + dataPair[y][x / 2] = (java.lang.Byte.toUnsignedInt(dataPair[y][x / 2]) and 0xF0 + or (data and 0xF)).toByte() + } + + companion object { + + @Transient val RANGE = 16 + } +} diff --git a/src/com/Torvald/Terrarum/LangPack/Lang.java b/src/com/Torvald/Terrarum/LangPack/Lang.java deleted file mode 100644 index 442671266..000000000 --- a/src/com/Torvald/Terrarum/LangPack/Lang.java +++ /dev/null @@ -1,179 +0,0 @@ -package com.Torvald.Terrarum.LangPack; - -import com.Torvald.CSVFetcher; -import com.Torvald.ImageFont.GameFontWhite; -import com.Torvald.Terrarum.Terrarum; -import org.apache.commons.csv.CSVRecord; -import org.newdawn.slick.SlickException; - -import java.io.*; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Hashtable; -import java.util.List; -import java.util.Properties; - -/** - * Created by minjaesong on 16-01-22. - */ -public class Lang { - - private static final String CSV_COLUMN_FIRST = "STRING_ID"; - /** - * Get record by its STRING_ID - */ - private static Hashtable lang; - private static final String FALLBACK_LANG_CODE = "enUS"; - - private static final int HANGUL_SYL_START = 0xAC00; - - private static final String PATH_TO_CSV = "./res/locales/"; - private static final String CSV_MAIN = "polyglot.csv"; - private static final String NAMESET_PREFIX = "nameset_"; - - private static final int[] HANGUL_POST_INDEX_ALPH = { // 0: 는, 가, ... 1: 은, 이, ... - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - private static final int[] HANGUL_POST_RO_INDEX_ALPH = { // 0: 로 1: 으로 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - - private static String[] ENGLISH_WORD_NORMAL_PLURAL = { - "photo" - }; - - private static String[] FRENCH_WORD_NORMAL_PLURAL = { - "bal" - , "banal" - , "fatal" - , "final" - }; - - public Lang() throws IOException { - lang = new Hashtable<>(); - - List langPackCSV = CSVFetcher.INSTANCE.readCSV(PATH_TO_CSV + CSV_MAIN); - - File file = new File(PATH_TO_CSV); - FilenameFilter filter = new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.contains(".csv") && !name.contains(CSV_MAIN) && !name.contains(NAMESET_PREFIX); - } - }; - for (String csvfilename : file.list(filter)) { - List csv = CSVFetcher.INSTANCE.readCSV(PATH_TO_CSV + csvfilename); - csv.forEach(langPackCSV::add); - } - - // Fill lang table - langPackCSV.forEach(this::appendToLangByStringID); - - - Arrays.sort(ENGLISH_WORD_NORMAL_PLURAL); - Arrays.sort(FRENCH_WORD_NORMAL_PLURAL); - - try { ((GameFontWhite)Terrarum.gameFontWhite).reloadUnihan(); } - catch (SlickException e) {} - } - - private void appendToLangByStringID(CSVRecord record) { - lang.put(record.get(CSV_COLUMN_FIRST), record); - } - - public static CSVRecord getRecord(String key) { - CSVRecord record = lang.get(key); - if (record == null) { - System.out.println("[Lang] No such record."); - throw new NullPointerException(); - } - return record; - } - - public static String get(String key) { - String value = null; - try { value = lang.get(key).get(Terrarum.Companion.getGameLocale()); } - catch (IllegalArgumentException e) { value = key; } - return value; - } - - public static String pluraliseLang(String key, int count) { - return (count > 1) ? get(key + "_PLURAL") : get(key); - } - - public static String pluralise(String word, int count) { - if (count < 2) return word; - - switch (Terrarum.Companion.getGameLocale()) { - case ("fr"): - if (Arrays.binarySearch(FRENCH_WORD_NORMAL_PLURAL, word) >= 0) { - return word + "s"; - } - if (word.endsWith("al") || word.endsWith("au") || word.endsWith("eu") || word - .endsWith("eau")) { - return word.substring(0, word.length() - 2) + "ux"; - } - else if (word.endsWith("ail")) { - return word.substring(0, word.length() - 3) + "ux"; - } - else { - return word + "s"; - } - case ("en"): default: - if (Arrays.binarySearch(ENGLISH_WORD_NORMAL_PLURAL, word) >= 0) { - return word + "s"; - } - else if (word.endsWith("f")) { // f -> ves - return word.substring(0, word.length() - 2) + "ves"; - } - else if (word.endsWith("o") || word.endsWith("z")) { // o -> oes - return word + "es"; - } - else { - return word + "s"; - } - } - } - - public static String postEunNeun(String word) { - char lastChar = getLastChar(word); - - if (isHangul(lastChar)) { - int index = lastChar - HANGUL_SYL_START; - return (index % 28 == 0) ? word + "는" : word + "은"; - } - else if ((lastChar >= 'A' && lastChar <= 'Z') - || (lastChar >= 'a' && lastChar <= 'z')) { - int index = (lastChar - 0x41) % 0x20; - return (HANGUL_POST_INDEX_ALPH[index] == 0) ? word + "는" : word + "은"; - } - else { - return "은(는)"; - } - } - - public static String postIiGa(String word) { - char lastChar = getLastChar(word); - - if (isHangul(lastChar)) { - int index = lastChar - HANGUL_SYL_START; - return (index % 28 == 0) ? word + "가" : word + "이"; - } - else if ((lastChar >= 'A' && lastChar <= 'Z') - || (lastChar >= 'a' && lastChar <= 'z')) { - int index = (lastChar - 0x41) % 0x20; - return (HANGUL_POST_INDEX_ALPH[index] == 0) ? word + "가" : word + "이"; - } - else { - return "이(가)"; - } - } - - private static boolean isHangul(char c) { - return (c >= 0xAC00 && c <= 0xD7A3); - } - - private static char getLastChar(String s) { - return s.charAt(s.length() - 1); - } -} diff --git a/src/com/Torvald/Terrarum/LangPack/Lang.kt b/src/com/Torvald/Terrarum/LangPack/Lang.kt new file mode 100644 index 000000000..965d925b6 --- /dev/null +++ b/src/com/Torvald/Terrarum/LangPack/Lang.kt @@ -0,0 +1,190 @@ +package com.Torvald.Terrarum.LangPack + +import com.Torvald.CSVFetcher +import com.Torvald.ImageFont.GameFontWhite +import com.Torvald.Terrarum.Terrarum +import org.apache.commons.csv.CSVRecord +import org.newdawn.slick.SlickException + +import java.io.* +import java.util.* + +/** + * Created by minjaesong on 16-01-22. + */ +object Lang { + + private val CSV_COLUMN_FIRST = "STRING_ID" + /** + * Get record by its STRING_ID + */ + private var lang: HashMap + private val FALLBACK_LANG_CODE = "enUS" + + private val HANGUL_SYL_START = 0xAC00 + + private val PATH_TO_CSV = "./res/locales/" + private val CSV_MAIN = "polyglot.csv" + private val NAMESET_PREFIX = "nameset_" + + private val HANGUL_POST_INDEX_ALPH = intArrayOf(// 0: 는, 가, ... 1: 은, 이, ... + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + private val HANGUL_POST_RO_INDEX_ALPH = intArrayOf(// 0: 로 1: 으로 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + + private val ENGLISH_WORD_NORMAL_PLURAL = arrayOf("photo") + + private val FRENCH_WORD_NORMAL_PLURAL = arrayOf("bal", "banal", "fatal", "final") + + init { + lang = HashMap() + + // read polyglot.csv first and use this list as a pivot + var langPackCSV: List = CSVFetcher.readCSV(PATH_TO_CSV + CSV_MAIN) + + // append CSV records to the main langpack + val file = File(PATH_TO_CSV) + val filter = FilenameFilter { dir, name -> name.contains(".csv") && !name.contains(NAMESET_PREFIX) } + for (csvfilename in file.list(filter)) { + val csv = CSVFetcher.readCSV(PATH_TO_CSV + csvfilename) + //csv.forEach({ langPackCSV. }) + csv.forEach { it -> lang.put(it.get(CSV_COLUMN_FIRST), it) } + } + + // lang.put(record.get(CSV_COLUMN_FIRST), record) + + // Fill lang table + // langPackCSV.forEach({ this.appendToLangByStringID(it) }) + + + Arrays.sort(ENGLISH_WORD_NORMAL_PLURAL) + Arrays.sort(FRENCH_WORD_NORMAL_PLURAL) + + try { + (Terrarum.gameFontWhite as GameFontWhite).reloadUnihan() + } + catch (e: SlickException) { + } + + } + + fun getRecord(key: String): CSVRecord { + val record = lang[key] + if (record == null) { + println("[Lang] No such record: $key") + throw NullPointerException() + } + return record + } + + operator fun get(key: String): String { + var value: String + try { + value = lang[key]!!.get(Terrarum.gameLocale) + } + catch (e: IllegalArgumentException) { + value = key + } + + return value + } + + fun pluraliseLang(key: String, count: Int): String { + return if (count > 1) get(key + "_PLURAL") else get(key) + } + + fun pluralise(word: String, count: Int): String { + if (count < 2) return word + + when (Terrarum.gameLocale) { + "fr" -> { + if (Arrays.binarySearch(FRENCH_WORD_NORMAL_PLURAL, word) >= 0) { + return word + "s" + } + if (word.endsWith("al") || word.endsWith("au") || word.endsWith("eu") || word.endsWith("eau")) { + return word.substring(0, word.length - 2) + "ux" + } + else if (word.endsWith("ail")) { + return word.substring(0, word.length - 3) + "ux" + } + else { + return word + "s" + } + } + "en" -> { + if (Arrays.binarySearch(ENGLISH_WORD_NORMAL_PLURAL, word) >= 0) { + return word + "s" + } + else if (word.endsWith("f")) { + // f -> ves + return word.substring(0, word.length - 2) + "ves" + } + else if (word.endsWith("o") || word.endsWith("z")) { + // o -> oes + return word + "es" + } + else { + return word + "s" + } + } + else -> { + if (Arrays.binarySearch(ENGLISH_WORD_NORMAL_PLURAL, word) >= 0) { + return word + "s" + } + else if (word.endsWith("f")) { + return word.substring(0, word.length - 2) + "ves" + } + else if (word.endsWith("o") || word.endsWith("z")) { + return word + "es" + } + else { + return word + "s" + } + } + } + } + + fun postEunNeun(word: String): String { + val lastChar = getLastChar(word) + + if (isHangul(lastChar)) { + val index = lastChar.toInt() - HANGUL_SYL_START + return if (index % 28 == 0) word + "는" else word + "은" + } + else if (lastChar >= 'A' && lastChar <= 'Z' || lastChar >= 'a' && lastChar <= 'z') { + val index = (lastChar.toInt() - 0x41) % 0x20 + return if (HANGUL_POST_INDEX_ALPH[index] == 0) word + "는" else word + "은" + } + else { + return "은(는)" + } + } + + fun postIiGa(word: String): String { + val lastChar = getLastChar(word) + + if (isHangul(lastChar)) { + val index = lastChar.toInt() - HANGUL_SYL_START + return if (index % 28 == 0) word + "가" else word + "이" + } + else if (lastChar >= 'A' && lastChar <= 'Z' || lastChar >= 'a' && lastChar <= 'z') { + val index = (lastChar.toInt() - 0x41) % 0x20 + return if (HANGUL_POST_INDEX_ALPH[index] == 0) word + "가" else word + "이" + } + else { + return "이(가)" + } + } + + private fun isHangul(c: Char): Boolean { + return c.toInt() >= 0xAC00 && c.toInt() <= 0xD7A3 + } + + private fun getLastChar(s: String): Char { + return s[s.length - 1] + } + + private fun appendToLangByStringID(record: CSVRecord) { + lang.put(record.get(CSV_COLUMN_FIRST), record) + } +} diff --git a/src/com/Torvald/Terrarum/MapDrawer/LightmapRenderer.kt b/src/com/Torvald/Terrarum/MapDrawer/LightmapRenderer.kt index 01c1771b3..b27de7e43 100644 --- a/src/com/Torvald/Terrarum/MapDrawer/LightmapRenderer.kt +++ b/src/com/Torvald/Terrarum/MapDrawer/LightmapRenderer.kt @@ -96,11 +96,11 @@ object LightmapRenderer { } - val for_y_start = div16(MapCamera.getCameraY()) - 1 // fix for premature lightmap rendering - val for_x_start = div16(MapCamera.getCameraX()) - 1 // on topmost/leftmost side + val for_x_start = div16(MapCamera.cameraX) - 1 // fix for premature lightmap rendering + val for_y_start = div16(MapCamera.cameraY) - 1 // on topmost/leftmost side - val for_y_end = clampHTile(for_y_start + div16(MapCamera.getRenderHeight()) + 2) + 1 // same fix as above val for_x_end = clampWTile(for_x_start + div16(MapCamera.getRenderWidth()) + 2) + 1 + val for_y_end = clampHTile(for_y_start + div16(MapCamera.getRenderHeight()) + 2) + 1 // same fix as above /** * Updating order: diff --git a/src/com/Torvald/Terrarum/MapDrawer/MapCamera.kt b/src/com/Torvald/Terrarum/MapDrawer/MapCamera.kt index aa43771e9..88282bf13 100644 --- a/src/com/Torvald/Terrarum/MapDrawer/MapCamera.kt +++ b/src/com/Torvald/Terrarum/MapDrawer/MapCamera.kt @@ -19,8 +19,10 @@ import java.util.* object MapCamera { private val map: GameMap = Terrarum.game.map; - internal var cameraX = 0 - internal var cameraY = 0 + var cameraX = 0 + private set + var cameraY = 0 + private set private val TSIZE = MapDrawer.TILE_SIZE @@ -122,6 +124,7 @@ object MapCamera { , TileNameCode.ORE_ILMENITE , TileNameCode.ORE_AURICHALCUM + , TileNameCode.WATER , TileNameCode.WATER_1 , TileNameCode.WATER_2 , TileNameCode.WATER_3 @@ -153,7 +156,6 @@ object MapCamera { , TileNameCode.LAVA_13 , TileNameCode.LAVA_14 , TileNameCode.LAVA_15 - , TileNameCode.LAVA ) /** @@ -444,18 +446,9 @@ object MapCamera { } } - @JvmStatic - fun div16(x: Int): Int { - return x and 0x7FFFFFFF shr 4 - } - - fun mod16(x: Int): Int { - return x and 15 - } - - fun quantise16(x: Int): Int { - return x and 0xFFFFFFF0.toInt() - } + fun div16(x: Int): Int = x and 0x7FFFFFFF shr 4 + fun mod16(x: Int): Int = x and 15 + fun quantise16(x: Int): Int = x and 0xFFFFFFF0.toInt() fun clampW(x: Int): Int { if (x < 0) { @@ -477,7 +470,6 @@ object MapCamera { } } - @JvmStatic fun clampWTile(x: Int): Int { if (x < 0) { return 0 @@ -488,7 +480,6 @@ object MapCamera { } } - @JvmStatic fun clampHTile(x: Int): Int { if (x < 0) { return 0 @@ -499,55 +490,21 @@ object MapCamera { } } - @JvmStatic - fun getRenderWidth(): Int { - return renderWidth - } + fun getRenderWidth(): Int = renderWidth + fun getRenderHeight(): Int = renderHeight - @JvmStatic - fun getRenderHeight(): Int { - return renderHeight - } + fun getRenderStartX(): Int = div16(cameraX) + fun getRenderStartY(): Int = div16(cameraY) - @JvmStatic - fun getRenderStartX(): Int { - return div16(cameraX) - } + fun getRenderEndX(): Int = clampWTile(getRenderStartX() + div16(renderWidth) + 2) + fun getRenderEndY(): Int = clampHTile(getRenderStartY() + div16(renderHeight) + 2) - @JvmStatic - fun getRenderStartY(): Int { - return div16(cameraY) - } + private fun isConnectSelf(b: Int): Boolean = TILES_CONNECT_SELF.contains(b) + private fun isConnectMutual(b: Int): Boolean = TILES_CONNECT_MUTUAL.contains(b) + private fun isWallSticker(b: Int): Boolean = TILES_WALL_STICKER.contains(b) + private fun isPlatform(b: Int): Boolean = TILES_WALL_STICKER_CONNECT_SELF.contains(b) - @JvmStatic - fun getRenderEndX(): Int { - return clampWTile(getRenderStartX() + div16(renderWidth) + 2) - } - - @JvmStatic - fun getRenderEndY(): Int { - return clampHTile(getRenderStartY() + div16(renderHeight) + 2) - } - - private fun isConnectSelf(b: Int): Boolean { - return Arrays.asList(*TILES_CONNECT_SELF).contains(b) - } - - private fun isConnectMutual(b: Int): Boolean { - return Arrays.asList(*TILES_CONNECT_MUTUAL).contains(b) - } - - private fun isWallSticker(b: Int): Boolean { - return Arrays.asList(*TILES_WALL_STICKER).contains(b) - } - - private fun isPlatform(b: Int): Boolean { - return Arrays.asList(*TILES_WALL_STICKER_CONNECT_SELF).contains(b) - } - - private fun isBlendMul(b: Int): Boolean { - return Arrays.asList(*TILES_BLEND_MUL).contains(b) - } + private fun isBlendMul(b: Int): Boolean = TILES_BLEND_MUL.contains(b) private fun setBlendModeMul() { GL11.glEnable(GL11.GL_BLEND) @@ -558,14 +515,4 @@ object MapCamera { GL11.glDisable(GL11.GL_BLEND) Terrarum.appgc.graphics.setDrawMode(Graphics.MODE_NORMAL) } - - @JvmStatic - fun getCameraX(): Int { - return cameraX - } - - @JvmStatic - fun getCameraY(): Int { - return cameraY - } } \ No newline at end of file diff --git a/src/com/Torvald/Terrarum/MapDrawer/MapDrawer.kt b/src/com/Torvald/Terrarum/MapDrawer/MapDrawer.kt index 878c680cb..475fd26dc 100644 --- a/src/com/Torvald/Terrarum/MapDrawer/MapDrawer.kt +++ b/src/com/Torvald/Terrarum/MapDrawer/MapDrawer.kt @@ -54,7 +54,12 @@ object MapDrawer { g.color = getColourFromMap(colTemp) //g.color = getColourFromMap(3022) - g.fillRect(MapCamera.getCameraX() * zoom, MapCamera.getCameraY() * zoom, Terrarum.WIDTH * if (zoom < 1) 1f / zoom else zoom, Terrarum.HEIGHT * if (zoom < 1) 1f / zoom else zoom) + g.fillRect( + MapCamera.cameraX * zoom, + MapCamera.cameraY * zoom, + Terrarum.WIDTH * if (zoom < 1) 1f / zoom else zoom, + Terrarum.HEIGHT * if (zoom < 1) 1f / zoom else zoom + ) } /** diff --git a/src/com/Torvald/Terrarum/Terrarum b/src/com/Torvald/Terrarum/Terrarum deleted file mode 100644 index 45be528a9..000000000 --- a/src/com/Torvald/Terrarum/Terrarum +++ /dev/null @@ -1,305 +0,0 @@ -package com.Torvald.Terrarum; - -import java.io.File; -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.Torvald.ImageFont.GameFontWhite; -import com.Torvald.JsonFetcher; -import com.Torvald.JsonWriter; -import com.Torvald.Terrarum.LangPack.Lang; -import com.google.gson.JsonObject; -import org.lwjgl.input.Controllers; -import org.newdawn.slick.*; -import org.newdawn.slick.state.StateBasedGame; - -/** - * Created by minjaesong on 15-12-30. - */ -public class Terrarum extends StateBasedGame { - - /** - * To be used with physics simulator - */ - public static final int TARGET_FPS = 50; - - /** - * To be used with render, to achieve smooth frame drawing - * - * TARGET_INTERNAL_FPS > TARGET_FPS for smooth frame drawing - * - * Must choose a value so that (1000 / VAL) is still integer - */ - public static final int TARGET_INTERNAL_FPS = 100; - - public static AppGameContainer appgc; - - public static final int WIDTH = 1060; - public static final int HEIGHT = 742; // IMAX ratio - public static boolean VSYNC = true; - public static final int VSYNC_TRIGGER_THRESHOLD = 56; - - public static Game game; - public static GameConfig gameConfig; - - public static String OSName; - public static String OSVersion; - public static String OperationSystem; - public static String defaultDir; - public static String defaultSaveDir; - - public static String gameLocale = ""; // locale override - - public static Font gameFontWhite; - - public static final int SCENE_ID_HOME = 1; - public static final int SCENE_ID_GAME = 3; - - public static boolean hasController = false; - public static final float CONTROLLER_DEADZONE = 0.1f; - - private static String configDir; - - public Terrarum(String gamename) throws SlickException { - super(gamename); - - gameConfig = new GameConfig(); - - getDefaultDirectory(); - createDirs(); - - boolean readFromDisk = readConfigJson(); - if (!readFromDisk) readConfigJson(); - - // get locale from config - gameLocale = gameConfig.getAsString("language"); - - // if game locale were not set, use system locale - if (gameLocale.length() < 4) - gameLocale = getSysLang(); - - System.out.println("[Terrarum] Locale: " + gameLocale); - } - - @Override - public void initStatesList(GameContainer gc) throws SlickException { - gameFontWhite = new GameFontWhite(); - - try { new Lang(); } - catch (IOException e) { e.printStackTrace(); } - - hasController = (gc.getInput().getControllerCount() > 0); - if (hasController) { - for (int c = 0; c < Controllers.getController(0).getAxisCount(); c++) { - Controllers.getController(0).setDeadZone(c, CONTROLLER_DEADZONE); - } - } - - appgc.getInput().enableKeyRepeat(); - - game = new Game(); - addState(game); - } - - public static void main(String[] args) - { - try - { - appgc = new AppGameContainer(new Terrarum("Terrarum")); - appgc.setDisplayMode(WIDTH, HEIGHT, false); - - appgc.setTargetFrameRate(TARGET_INTERNAL_FPS); - appgc.setVSync(VSYNC); - appgc.setMaximumLogicUpdateInterval(1000 / TARGET_INTERNAL_FPS); - appgc.setMinimumLogicUpdateInterval(1000 / TARGET_INTERNAL_FPS - 1); - - appgc.setShowFPS(false); - appgc.setUpdateOnlyWhenVisible(false); - - appgc.start(); - } - catch (SlickException ex) - { - Logger.getLogger(Terrarum.class.getName()).log(Level.SEVERE, null, ex); - } - } - - private static void getDefaultDirectory(){ - OSName = System.getProperty("os.name"); - OSVersion = System.getProperty("os.version"); - - String OS = System.getProperty("os.name").toUpperCase(); - if (OS.contains("WIN")){ - OperationSystem = "WINDOWS"; - defaultDir = System.getenv("APPDATA") + "/Terrarum"; - } - else if (OS.contains("OS X")){ - OperationSystem = "OSX"; - defaultDir = System.getProperty("user.home") + "/Library/Application " - + "Support" + "/Terrarum"; - } - else if (OS.contains("NUX") || OS.contains("NIX")){ - OperationSystem = "LINUX"; - defaultDir = System.getProperty("user.home") + "/.terrarum"; - } - else if (OS.contains("SUNOS")){ - OperationSystem = "SOLARIS"; - defaultDir = System.getProperty("user.home") + "/.terrarum"; - } - else{ - OperationSystem = "UNKNOWN"; - defaultDir = System.getProperty("user.home") + "/.terrarum"; - } - - defaultSaveDir = defaultDir + "/Saves"; - configDir = defaultDir + "/config.json"; - } - - private static void createDirs(){ - File[] dirs = { - new File(defaultSaveDir), - }; - - for (File d : dirs){ - if (!d.exists()){ - d.mkdirs(); - } - } - } - - private static void createConfigJson() throws IOException { - File configFile = new File(configDir); - - if (!configFile.exists() || configFile.length() == 0) { - JsonWriter.writeToFile(DefaultConfig.fetch(), configDir); - } - } - - private static boolean readConfigJson() { - try { - // read from disk and build config from it - JsonObject jsonObject = JsonFetcher.readJson(configDir); - - // make config - jsonObject.entrySet().forEach( - entry -> gameConfig.set(entry.getKey(), entry.getValue()) - ); - - return true; - } - catch (IOException e) { - // write default config to game dir. Call this method again to read config from it. - try { - createConfigJson(); - } - catch (IOException e1) { - e.printStackTrace(); - } - - return false; - } - } - - public static String getSysLang() { - String lan = System.getProperty("user.language"); - String country = System.getProperty("user.country"); - - // exception handling - if (lan.equals("en")) country = "US"; - else if (lan.equals("fr")) country = "FR"; - else if (lan.equals("de")) country = "DE"; - else if (lan.equals("ko")) country = "KR"; - - return lan + country; - } - - - /** - * Return config from config set. If the config does not exist, default value will be returned. - * @param key - * @return Config from config set or default config if it does not exist. - * @throws NullPointerException if the specified config simply does not exist. - */ - public static int getConfigInt(String key) { - int cfg = 0; - try { - cfg = gameConfig.getAsInt(key); - } - catch (NullPointerException e) { - try { - cfg = DefaultConfig.fetch().get(key).getAsInt(); - } - catch (NullPointerException e1) { - e.printStackTrace(); - } - } - return cfg; - } - - /** - * Return config from config set. If the config does not exist, default value will be returned. - * @param key - * @return Config from config set or default config if it does not exist. - * @throws NullPointerException if the specified config simply does not exist. - */ - public static float getConfigFloat(String key) { - float cfg = 0; - try { - cfg = gameConfig.getAsFloat(key); - } - catch (NullPointerException e) { - try { - cfg = DefaultConfig.fetch().get(key).getAsFloat(); - } - catch (NullPointerException e1) { - e.printStackTrace(); - } - } - return cfg; - } - - /** - * Return config from config set. If the config does not exist, default value will be returned. - * @param key - * @return Config from config set or default config if it does not exist. - * @throws NullPointerException if the specified config simply does not exist. - */ - public static String getConfigString(String key) { - String cfg = ""; - try { - cfg = gameConfig.getAsString(key); - } - catch (NullPointerException e) { - try { - cfg = DefaultConfig.fetch().get(key).getAsString(); - } - catch (NullPointerException e1) { - e.printStackTrace(); - } - } - return cfg; - } - - /** - * Return config from config set. If the config does not exist, default value will be returned. - * @param key - * @return Config from config set or default config if it does not exist. - * @throws NullPointerException if the specified config simply does not exist. - */ - public static boolean getConfigBoolean(String key) { - boolean cfg = false; - try { - cfg = gameConfig.getAsBoolean(key); - } - catch (NullPointerException e) { - try { - cfg = DefaultConfig.fetch().get(key).getAsBoolean(); - } - catch (NullPointerException e1) { - e.printStackTrace(); - } - } - return cfg; - } -} diff --git a/src/com/Torvald/Terrarum/Terrarum.kt b/src/com/Torvald/Terrarum/Terrarum.kt index 36bde460e..2466ecb8b 100644 --- a/src/com/Torvald/Terrarum/Terrarum.kt +++ b/src/com/Torvald/Terrarum/Terrarum.kt @@ -46,13 +46,6 @@ constructor(gamename: String) : StateBasedGame(gamename) { override fun initStatesList(gc: GameContainer) { gameFontWhite = GameFontWhite() - try { - Lang() - } - catch (e: IOException) { - e.printStackTrace() - } - hasController = gc.input.controllerCount > 0 if (hasController) { for (c in 0..Controllers.getController(0).axisCount - 1) { diff --git a/src/com/Torvald/Terrarum/TileProperties/tileprop.csv b/src/com/Torvald/Terrarum/TileProperties/tileprop.csv index 221d2f08e..2d29ad39b 100644 --- a/src/com/Torvald/Terrarum/TileProperties/tileprop.csv +++ b/src/com/Torvald/Terrarum/TileProperties/tileprop.csv @@ -41,7 +41,7 @@ "10"; "2";"TILE_PLATFORM_EBONY" ; "394758"; "1"; "N/A"; "0"; "0"; "0"; "0"; "0"; "10"; "2"; "0";"16" "10"; "3";"TILE_PLATFORM_BIRCH" ; "394758"; "1"; "N/A"; "0"; "0"; "0"; "0"; "0"; "10"; "3"; "0";"16" "10"; "4";"TILE_PLATFORM_BLOODROSE" ; "394758"; "1"; "N/A"; "0"; "0"; "0"; "0"; "0"; "10"; "4"; "0";"16" - "11"; "0";"TILE_TORCH" ; "0"; "0"; "N/A"; "0"; "0"; "0"; "0";"16750673"; "11"; "0"; "0";"16" + "11"; "0";"TILE_TORCH" ; "0"; "0"; "N/A"; "0"; "0"; "0"; "0";"15304000"; "11"; "0"; "0";"16" "11"; "1";"TILE_TORCH_FROST" ; "0"; "0"; "N/A"; "0"; "0"; "0"; "0"; "5143807"; "11"; "1"; "0";"16" "12"; "0";"TILE_TORCH" ; "394758"; "0"; "N/A"; "0"; "0"; "0"; "0"; "0"; "11"; "0"; "0";"16" "12"; "1";"TILE_TORCH_FROST" ; "394758"; "0"; "N/A"; "0"; "0"; "0"; "0"; "0"; "11"; "1"; "0";"16" @@ -83,6 +83,7 @@ "15"; "3";"TILE_SANDSTONE_DESERT" ;"2105376"; "25";"1900"; "0"; "0"; "1"; "1"; "0"; "15"; "3"; "0";"16" "15"; "4";"TILE_SANDSTONE_BLACK" ;"2105376"; "25";"1900"; "0"; "0"; "1"; "1"; "0"; "15"; "4"; "0";"16" "15"; "5";"TILE_SANDSTONE_BLACK" ;"2105376"; "25";"1900"; "0"; "0"; "1"; "1"; "0"; "15"; "5"; "0";"16" + "16"; "0";"TILE_LANTERN_IRON_REGULAR"; "0"; "0"; "N/A"; "0"; "0"; "0"; "0";"16769944"; "16"; "0"; "0";"16" "254"; "0";"TILE_WATER" ;"1708813"; "100";"1000"; "1"; "12"; "0"; "0"; "0"; "N/A"; "N/A"; "0";"16" "254"; "1";"TILE_WATER" ;"1708813"; "100";"1000"; "1"; "12"; "0"; "0"; "0"; "N/A"; "N/A"; "0";"16" "254"; "2";"TILE_WATER" ;"1708813"; "100";"1000"; "1"; "12"; "0"; "0"; "0"; "N/A"; "N/A"; "0";"16" diff --git a/src/com/Torvald/Terrarum/UserInterface/BasicDebugInfoWindow.kt b/src/com/Torvald/Terrarum/UserInterface/BasicDebugInfoWindow.kt index d988e62e6..95d275285 100644 --- a/src/com/Torvald/Terrarum/UserInterface/BasicDebugInfoWindow.kt +++ b/src/com/Torvald/Terrarum/UserInterface/BasicDebugInfoWindow.kt @@ -137,14 +137,14 @@ class BasicDebugInfoWindow : UICanvas { // Hitbox val zoom = Terrarum.game.screenZoom g.setColor(Color(0x007f00)) - g.drawRect(hitbox.getHitboxStart().getX() * zoom - MapCamera.cameraX * zoom - , hitbox.getHitboxStart().getY() * zoom - MapCamera.cameraY * zoom - , hitbox.getWidth() * zoom - , hitbox.getHeight() * zoom) + g.drawRect(hitbox.hitboxStart.x * zoom - MapCamera.cameraX * zoom + , hitbox.hitboxStart.y * zoom - MapCamera.cameraY * zoom + , hitbox.width * zoom + , hitbox.height * zoom) // ...and its point g.fillRect( - (hitbox.getPointedX() - 1) * zoom - MapCamera.cameraX * zoom - , (hitbox.getPointedY() - 1) * zoom - MapCamera.cameraY * zoom + (hitbox.pointedX - 1) * zoom - MapCamera.cameraX * zoom + , (hitbox.pointedY - 1) * zoom - MapCamera.cameraY * zoom , 3f, 3f) g.drawString( Lang.get("DEV_COLOUR_LEGEND_GREEN") + " : hitbox", (Terrarum.WIDTH - 200).toFloat() @@ -152,14 +152,14 @@ class BasicDebugInfoWindow : UICanvas { // Next hitbox g.setColor(Color.blue) - g.drawRect(nextHitbox!!.getHitboxStart().getX() * zoom - MapCamera.cameraX * zoom - , nextHitbox.getHitboxStart().getY() * zoom - MapCamera.cameraY * zoom - , nextHitbox.getWidth() * zoom - , nextHitbox.getHeight() * zoom) + g.drawRect(nextHitbox!!.hitboxStart.x * zoom - MapCamera.cameraX * zoom + , nextHitbox.hitboxStart.y * zoom - MapCamera.cameraY * zoom + , nextHitbox.width * zoom + , nextHitbox.height * zoom) // ...and its point g.fillRect( - (nextHitbox.getPointedX() - 1) * zoom - MapCamera.cameraX * zoom - , (nextHitbox.getPointedY() - 1) * zoom - MapCamera.cameraY * zoom + (nextHitbox.pointedX - 1) * zoom - MapCamera.cameraX * zoom + , (nextHitbox.pointedY - 1) * zoom - MapCamera.cameraY * zoom , 3f, 3f) g.drawString( Lang.get("DEV_COLOUR_LEGEND_BLUE") + " : nextHitbox", (Terrarum.WIDTH - 200).toFloat() diff --git a/src/com/Torvald/Terrarum/UserInterface/UIHandler.kt b/src/com/Torvald/Terrarum/UserInterface/UIHandler.kt index d8eba8b2a..c01488b03 100644 --- a/src/com/Torvald/Terrarum/UserInterface/UIHandler.kt +++ b/src/com/Torvald/Terrarum/UserInterface/UIHandler.kt @@ -96,7 +96,10 @@ constructor(val UI: UICanvas) { UIGraphicInstance.font = Terrarum.gameFontWhite UI.render(gc, UIGraphicInstance) - gameGraphicInstance.drawImage(UIDrawnCanvas, posX + MapCamera.getCameraX() * Terrarum.game.screenZoom, posY + MapCamera.getCameraY() * Terrarum.game.screenZoom)// compensate for screenZoom AND camera translation + gameGraphicInstance.drawImage(UIDrawnCanvas, + posX + MapCamera.cameraX * Terrarum.game.screenZoom, + posY + MapCamera.cameraY * Terrarum.game.screenZoom + )// compensate for screenZoom AND camera translation // (see Game.render -> g.translate()) } } diff --git a/src/com/Torvald/spriteAnimation/SpriteAnimation.java b/src/com/Torvald/spriteAnimation/SpriteAnimation.java deleted file mode 100644 index b5080d7ec..000000000 --- a/src/com/Torvald/spriteAnimation/SpriteAnimation.java +++ /dev/null @@ -1,281 +0,0 @@ - -/* Original code author: Sean Laurvick - * This code is based on the original author's code written in Lua. - */ - -package com.Torvald.spriteAnimation; - -import com.Torvald.Terrarum.Game; -import com.Torvald.Terrarum.Terrarum; -import com.jme3.math.FastMath; -import org.newdawn.slick.Graphics; -import org.newdawn.slick.Image; -import org.newdawn.slick.SlickException; -import org.newdawn.slick.SpriteSheet; - -public class SpriteAnimation { - - private SpriteSheet spriteImage; - private Image[][] sprites; - private int height; - private int width; - private int currentFrame = 1; - private int currentRow = 1; - private int nFrames; - private int nRows; - private int delay = 200; - private int delta = 0; - private boolean looping = true; - private boolean animationRunning = true; - private boolean flipHorizontal = false; - private boolean flipVertical = false; - private boolean visible = false; - - private int offsetX = 0; - private int offsetY = 0; - - private float prevScale = 1f; - private Image currentImage; - - public SpriteAnimation() throws SlickException{ - - } - - /** - * Sets spritesheet. - * MUST be called AFTER setDimension. - * @param imagePath path to the sprite sheet image. - * @throws SlickException - */ - public void setSpriteImage(String imagePath) throws SlickException { - spriteImage = new SpriteSheet(imagePath, this.width, this.height); - } - - /** - * Sets animation delay. Will default to 200 if not called. - * @param delay in milliseconds - */ - public void setDelay(int delay) { - this.delay = delay; - } - - /** - * Sets sprite dimension. This is necessary. - * @param w - * @param h - */ - public void setDimension(int w, int h) { - width = w; - height = h; - } - - /** - * Sets sheet rows and animation frames. Will default to - * 1, 1 (still image of top left from the sheet) if not called. - * @param rows - * @param frames - */ - public void setRowsAndFrames(int rows, int frames) { - nRows = rows; - nFrames = frames; - } - - /** - * Compose (load from spritesheet) as attributes defined. - * If attributes were not defined, will throw exception of - * SlickException or ArraySizeException. - * @throws SlickException - */ - public void composeSprite() throws SlickException { - this.sprites = new Image[this.nRows][this.nFrames]; - - for (int i=0; i= ( this.delay ) ){ - //if set to not loop, keep the frame at the last frame - if ( this.currentFrame == this.nFrames && !(this.looping) ){ - this.currentFrame = this.nFrames - 1; - } - - //advance one frame, then reset delta counter - this.currentFrame = (this.currentFrame % this.nFrames) + 1; - this.delta = 0; - } - } - } - - /** - * Render to specific coordinates. Will assume bottom-center point as image position. - * Will round to integer. - * @param g - * @param posX bottom-center point - * @param posY bottom-center point - * @param scale - */ - public void render(Graphics g, float posX, float posY, float scale){ - scale *= Terrarum.game.getScreenZoom(); - - // Null checking - if (currentImage == null) { - currentImage = getScaledSprite(scale); - } - - if (visible) { - // re-scale image if scale has been changed - if (prevScale != scale) { - currentImage = getScaledSprite(scale); - prevScale = scale; - } - - Image flippedImage = currentImage.getFlippedCopy(flipHorizontal, flipVertical); - - flippedImage.startUse(); - flippedImage.drawEmbedded( - Math.round(posX * Terrarum.game.getScreenZoom()) - , Math.round(posY * Terrarum.game.getScreenZoom()) - , FastMath.floor(width * scale) - , FastMath.floor(height * scale) - ); - flippedImage.endUse(); - } - } - - public void render(Graphics g, float posX, float posY){ - render(g, posX, posY, 1); - } - - public void switchSprite(int newRow){ - currentRow = newRow; - - //if beyond the frame index then reset - if (currentFrame > nFrames){ - reset(); - } - } - - public void switchSprite(int newRow, int newMax){ - if (newMax > 0){ - nFrames = newMax; - } - - currentRow = newRow; - - //if beyond the frame index then reset - if (currentFrame > nFrames){ - reset(); - } - } - - public void switchSpriteDelay(int newDelay){ - if (newDelay > 0){ - delay = newDelay; - } - } - - public void switchSprite(int newRow, int newMax, int newDelay){ - if (newMax > 0){ - nFrames = newMax; - } - - if (newDelay > 0){ - delay = newDelay; - } - - currentRow = newRow; - - //if beyond the frame index then reset - if (currentFrame > nFrames){ - reset(); - } - } - - public void reset(){ - currentFrame = 1; - } - - public void start(){ //starts the animation - animationRunning = true; - } - - public void start(int selectFrame){ //starts the animation - animationRunning = true; - - //optional: seleft the frame no which to start the animation - currentFrame = selectFrame; - } - - public void stop(){ - animationRunning = false; - } - - public void stop(int selectFrame){ - animationRunning = false; - - currentFrame = selectFrame; - } - - public void flip(boolean horizontal, boolean vertical){ - flipHorizontal = horizontal; - flipVertical = vertical; - } - - public boolean flippedHorizontal() { - return flipHorizontal; - } - - public boolean flippedVertical() { - return flipVertical; - } - - public int getWidth(){ - return width; - } - - public int getHeight(){ - return height; - } - - private Image getScaledSprite(float scale) { - Image selectedImage = sprites[currentRow - 1][currentFrame - 1]; - - // resample - /*float nearestResampleScale = (scale > 1) ? Math.round(scale) : 1; - float linearResampleScale = scale / nearestResampleScale; - - // scale 1.8 -> resample in 2(nearest), then resample in 0.9(linear) - // scale by nearestResampleScale (2, 3, ...) - selectedImage.setFilter(Image.FILTER_NEAREST); - Image selImgNearestScaled = selectedImage.getScaledCopy(nearestResampleScale); - // scale by linearResampleScale (.x) - Image selImgLinearScaled; - if (scale % 1 > 0) { - selImgNearestScaled.setFilter(Image.FILTER_LINEAR); - selImgLinearScaled = selImgNearestScaled.getScaledCopy(linearResampleScale); - return selImgLinearScaled; - } - else { - return selImgNearestScaled; - }*/ - selectedImage.setFilter(Image.FILTER_NEAREST); - return selectedImage.getScaledCopy(scale); - } -} diff --git a/src/com/Torvald/spriteAnimation/SpriteAnimation.kt b/src/com/Torvald/spriteAnimation/SpriteAnimation.kt new file mode 100644 index 000000000..a8347eac7 --- /dev/null +++ b/src/com/Torvald/spriteAnimation/SpriteAnimation.kt @@ -0,0 +1,261 @@ +/* Original code author: Sean Laurvick + * This code is based on the original author's code written in Lua. + */ + +package com.Torvald.spriteAnimation + +import com.Torvald.Terrarum.Game +import com.Torvald.Terrarum.Terrarum +import com.jme3.math.FastMath +import org.newdawn.slick.Graphics +import org.newdawn.slick.Image +import org.newdawn.slick.SlickException +import org.newdawn.slick.SpriteSheet + +class SpriteAnimation @Throws(SlickException::class) +constructor() { + + private var spriteImage: SpriteSheet? = null + var height: Int = 0 + private set + var width: Int = 0 + private set + private var currentFrame = 1 + private var currentRow = 1 + private var nFrames: Int = 0 + private var nRows: Int = 0 + private var delay = 200 + private var delta = 0 + private val looping = true + private var animationRunning = true + private var flipHorizontal = false + private var flipVertical = false + private var visible = false + + private val offsetX = 0 + private val offsetY = 0 + + private var prevScale = 1f + private var currentImage: Image? = null + + /** + * Sets spritesheet. + * MUST be called AFTER setDimension. + * @param imagePath path to the sprite sheet image. + * * + * @throws SlickException + */ + @Throws(SlickException::class) + fun setSpriteImage(imagePath: String) { + spriteImage = SpriteSheet(imagePath, this.width, this.height) + } + + /** + * Sets animation delay. Will default to 200 if not called. + * @param delay in milliseconds + */ + fun setDelay(delay: Int) { + this.delay = delay + } + + /** + * Sets sprite dimension. This is necessary. + * @param w + * * + * @param h + */ + fun setDimension(w: Int, h: Int) { + width = w + height = h + } + + /** + * Sets sheet rows and animation frames. Will default to + * 1, 1 (still image of top left from the sheet) if not called. + * @param rows + * * + * @param frames + */ + fun setRowsAndFrames(rows: Int, frames: Int) { + nRows = rows + nFrames = frames + } + + fun setAsVisible() { + visible = true + } + + fun setAsInvisible() { + visible = false + } + + fun update(delta: Int) { + if (animationRunning) { + //skip this if animation is stopped + this.delta += delta + + //check if it's time to advance the frame + if (this.delta >= this.delay) { + //if set to not loop, keep the frame at the last frame + if (this.currentFrame == this.nFrames && !this.looping) { + this.currentFrame = this.nFrames - 1 + } + + //advance one frame, then reset delta counter + this.currentFrame = this.currentFrame % this.nFrames + 1 + this.delta = 0 + } + } + } + + /** + * Render to specific coordinates. Will assume bottom-center point as image position. + * Will round to integer. + * @param g + * * + * @param posX bottom-center point + * * + * @param posY bottom-center point + * * + * @param scale + */ + @JvmOverloads fun render(g: Graphics, posX: Float, posY: Float, scale: Float = 1f) { + var scale = scale + scale *= Terrarum.game.screenZoom + + // Null checking + if (currentImage == null) { + currentImage = getScaledSprite(scale) + } + + if (visible) { + // re-scale image if scale has been changed + if (prevScale != scale) { + currentImage = getScaledSprite(scale) + prevScale = scale + } + + val flippedImage = currentImage!!.getFlippedCopy(flipHorizontal, flipVertical) + + flippedImage.startUse() + flippedImage.drawEmbedded( + Math.round(posX * Terrarum.game.screenZoom).toFloat(), + Math.round(posY * Terrarum.game.screenZoom).toFloat(), + FastMath.floor(width * scale).toFloat(), + FastMath.floor(height * scale).toFloat() + ) + flippedImage.endUse() + } + } + + fun switchSprite(newRow: Int) { + currentRow = newRow + + //if beyond the frame index then reset + if (currentFrame > nFrames) { + reset() + } + } + + fun switchSprite(newRow: Int, newMax: Int) { + if (newMax > 0) { + nFrames = newMax + } + + currentRow = newRow + + //if beyond the frame index then reset + if (currentFrame > nFrames) { + reset() + } + } + + fun switchSpriteDelay(newDelay: Int) { + if (newDelay > 0) { + delay = newDelay + } + } + + fun switchSprite(newRow: Int, newMax: Int, newDelay: Int) { + if (newMax > 0) { + nFrames = newMax + } + + if (newDelay > 0) { + delay = newDelay + } + + currentRow = newRow + + //if beyond the frame index then reset + if (currentFrame > nFrames) { + reset() + } + } + + fun reset() { + currentFrame = 1 + } + + fun start() { + //starts the animation + animationRunning = true + } + + fun start(selectFrame: Int) { + //starts the animation + animationRunning = true + + //optional: seleft the frame no which to start the animation + currentFrame = selectFrame + } + + fun stop() { + animationRunning = false + } + + fun stop(selectFrame: Int) { + animationRunning = false + + currentFrame = selectFrame + } + + fun flip(horizontal: Boolean, vertical: Boolean) { + flipHorizontal = horizontal + flipVertical = vertical + } + + fun flippedHorizontal(): Boolean { + return flipHorizontal + } + + fun flippedVertical(): Boolean { + return flipVertical + } + + private fun getScaledSprite(scale: Float): Image { + val selectedImage = spriteImage!!.getSprite(currentFrame - 1, currentRow - 1) + //Image selectedImage = sprites[currentRow - 1][currentFrame - 1]; + + // resample + /*float nearestResampleScale = (scale > 1) ? Math.round(scale) : 1; + float linearResampleScale = scale / nearestResampleScale; + + // scale 1.8 -> resample in 2(nearest), then resample in 0.9(linear) + // scale by nearestResampleScale (2, 3, ...) + selectedImage.setFilter(Image.FILTER_NEAREST); + Image selImgNearestScaled = selectedImage.getScaledCopy(nearestResampleScale); + // scale by linearResampleScale (.x) + Image selImgLinearScaled; + if (scale % 1 > 0) { + selImgNearestScaled.setFilter(Image.FILTER_LINEAR); + selImgLinearScaled = selImgNearestScaled.getScaledCopy(linearResampleScale); + return selImgLinearScaled; + } + else { + return selImgNearestScaled; + }*/ + selectedImage.filter = Image.FILTER_NEAREST + return selectedImage.getScaledCopy(scale) + } +}