refactoring the call order of the renderers' init code invocation

This commit is contained in:
minjaesong
2019-06-25 22:24:22 +09:00
parent d2e886aec2
commit ed58e72724
29 changed files with 283 additions and 195 deletions

1
.gitignore vendored
View File

@@ -6,6 +6,7 @@ build/*
# Java native errors
hs_err_pid*
replay_pid*
# OS files
Thumbs.db

View File

@@ -15,7 +15,9 @@ object UnsafeHelper {
unsafe = unsafeConstructor.newInstance()
}
/**
* A factory method to allocate a memory of given size and return its starting address as a pointer.
*/
fun allocate(size: Long): UnsafePtr {
val ptr = unsafe.allocateMemory(size)
return UnsafePtr(ptr, size)
@@ -34,7 +36,7 @@ class UnsafePtr(val ptr: Long, val allocSize: Long) {
UnsafeHelper.unsafe.freeMemory(ptr)
println("[UnsafePtr] Destroying pointer $this; called from:")
Thread.currentThread().stackTrace.forEach { println("[UnsafePtr] $it") }
Thread.currentThread().stackTrace.forEach { println(it) }
destroyed = true
}

View File

@@ -28,10 +28,9 @@ import net.torvald.terrarum.gamecontroller.KeyToggler;
import net.torvald.terrarum.gameworld.GameWorld;
import net.torvald.terrarum.imagefont.TinyAlphNum;
import net.torvald.terrarum.modulebasegame.Ingame;
import net.torvald.terrarum.modulebasegame.IngameRenderer;
import net.torvald.terrarum.utils.JsonFetcher;
import net.torvald.terrarum.utils.JsonWriter;
import net.torvald.terrarum.worlddrawer.BlocksDrawer;
import net.torvald.terrarum.worlddrawer.LightmapRenderer;
import net.torvald.terrarumsansbitmap.gdx.GameFontBase;
import net.torvald.terrarumsansbitmap.gdx.TextureRegionPack;
import net.torvald.util.ArrayListMap;
@@ -614,9 +613,7 @@ public class AppLoader implements ApplicationListener {
ModMgr.INSTANCE.invoke(); // invoke Module Manager
AppLoader.resourcePool.loadAll();
printdbg(this, "all modules loaded successfully");
BlocksDrawer.INSTANCE.getWorld(); // will initialize the BlocksDrawer by calling dummy method
LightmapRenderer.INSTANCE.hdr(0f);
IngameRenderer.initialise();
}

View File

@@ -8,7 +8,6 @@ import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.glutils.FrameBuffer
import com.badlogic.gdx.graphics.glutils.ShaderProgram
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.badlogic.gdx.utils.Disposable
import com.badlogic.gdx.utils.GdxRuntimeException
@@ -180,14 +179,6 @@ object Terrarum : Screen, Disposable {
const val NAME = AppLoader.GAME_NAME
lateinit var shaderBlur: ShaderProgram
lateinit var shaderBayer: ShaderProgram
lateinit var shaderSkyboxFill: ShaderProgram
lateinit var shaderBlendGlow: ShaderProgram
lateinit var shaderRGBOnly: ShaderProgram
lateinit var shaderAtoGrey: ShaderProgram
lateinit var testTexture: Texture
@@ -334,59 +325,6 @@ object Terrarum : Screen, Disposable {
shapeRender = ShapeRenderer()
shaderBlur = AppLoader.loadShader("assets/blur.vert", "assets/blur.frag")
if (getConfigBoolean("fxdither")) {
shaderBayer = AppLoader.loadShader("assets/4096.vert", "assets/4096_bayer.frag")
shaderBayer.begin()
shaderBayer.setUniformf("rcount", 64f)
shaderBayer.setUniformf("gcount", 64f)
shaderBayer.setUniformf("bcount", 64f)
shaderBayer.end()
shaderSkyboxFill = AppLoader.loadShader("assets/4096.vert", "assets/4096_bayer_skyboxfill.frag")
shaderSkyboxFill.begin()
shaderSkyboxFill.setUniformf("rcount", 64f)
shaderSkyboxFill.setUniformf("gcount", 64f)
shaderSkyboxFill.setUniformf("bcount", 64f)
shaderSkyboxFill.end()
}
else {
shaderBayer = AppLoader.loadShader("assets/4096.vert", "assets/passthrurgb.frag")
shaderSkyboxFill = AppLoader.loadShader("assets/4096.vert", "assets/skyboxfill.frag")
}
shaderBlendGlow = AppLoader.loadShader("assets/blendGlow.vert", "assets/blendGlow.frag")
shaderRGBOnly = AppLoader.loadShader("assets/4096.vert", "assets/rgbonly.frag")
shaderAtoGrey = AppLoader.loadShader("assets/4096.vert", "assets/aonly.frag")
if (!shaderBlendGlow.isCompiled) {
Gdx.app.log("shaderBlendGlow", shaderBlendGlow.log)
System.exit(1)
}
if (getConfigBoolean("fxdither")) {
if (!shaderBayer.isCompiled) {
Gdx.app.log("shaderBayer", shaderBayer.log)
System.exit(1)
}
if (!shaderSkyboxFill.isCompiled) {
Gdx.app.log("shaderSkyboxFill", shaderSkyboxFill.log)
System.exit(1)
}
}
AppLoader.GAME_LOCALE = getConfigString("language")
printdbg(this, "locale = ${AppLoader.GAME_LOCALE}")
@@ -428,11 +366,6 @@ object Terrarum : Screen, Disposable {
/** Don't call this! Call AppLoader.dispose() */
override fun dispose() {
//dispose any other resources used in this level
shaderBayer.dispose()
shaderSkyboxFill.dispose()
shaderBlur.dispose()
shaderBlendGlow.dispose()
ingame?.dispose()
}

View File

@@ -14,9 +14,9 @@ import com.jme3.math.FastMath
import net.torvald.random.HQRNG
import net.torvald.terrarum.AppLoader.printdbg
import net.torvald.terrarum.blockproperties.BlockCodex
import net.torvald.terrarum.gameactors.AVKey
import net.torvald.terrarum.gameactors.Actor
import net.torvald.terrarum.gameactors.*
import net.torvald.terrarum.gameactors.ai.ActorAI
import net.torvald.terrarum.gameworld.GameWorld
import net.torvald.terrarum.gameworld.fmod
import net.torvald.terrarum.langpack.Lang
import net.torvald.terrarum.modulebasegame.Ingame
@@ -107,7 +107,7 @@ class TitleScreen(val batch: SpriteBatch) : Screen {
//println("${actor.hitbox.canonicalX}, ${actor.hitbox.canonicalY}")
}
}
private lateinit var cameraPlayer: HumanoidNPC
private lateinit var cameraPlayer: ActorWithBody
private val gradWhiteTop = Color(0xf8f8f8ff.toInt())
private val gradWhiteBottom = Color(0xd8d8d8ff.toInt())
@@ -132,7 +132,7 @@ class TitleScreen(val batch: SpriteBatch) : Screen {
printdbg(this, "Demo world gen complete")
// set time to summer
demoWorld.time.addTime(WorldTime.DAY_LENGTH * 32)
demoWorld.worldTime.addTime(WorldTime.DAY_LENGTH * 32)
// construct camera nodes
val nodeCount = 100
@@ -146,23 +146,12 @@ class TitleScreen(val batch: SpriteBatch) : Screen {
}
cameraPlayer = object : HumanoidNPC(cameraAI, born = 0, usePhysics = false) {
init {
setHitboxDimension(2, 2, 0, 0)
hitbox.setPosition(
HQRNG().nextInt(demoWorld.width) * CreateTileAtlas.TILE_SIZE.toDouble(),
0.0 // Y pos: placeholder; camera AI will take it over
)
isNoClip = true
}
}
cameraPlayer = CameraPlayer(demoWorld, cameraAI)
demoWorld.time.timeDelta = 150
demoWorld.worldTime.timeDelta = 150
//LightmapRenderer.setWorld(demoWorld)
//BlocksDrawer.world = demoWorld
//FeaturesDrawer.world = demoWorld
IngameRenderer.setWorld(demoWorld)
uiMenu = UIRemoCon(UITitleRemoConYaml())//UITitleRemoConRoot()
@@ -254,7 +243,10 @@ class TitleScreen(val batch: SpriteBatch) : Screen {
if (!demoWorld.disposed) { // FIXME q&d hack to circumvent the dangling pointer issue #26
IngameRenderer.invoke(gamePaused = false, world = demoWorld, uisToDraw = uiContainer)
IngameRenderer.invoke(gamePaused = false, uisToDraw = uiContainer)
}
else {
System.err.println("[TitleScreen] demoworld is already destroyed")
}
@@ -375,4 +367,56 @@ class TitleScreen(val batch: SpriteBatch) : Screen {
return true
}
}
private class CameraPlayer(val demoWorld: GameWorld, override val ai: ActorAI) : ActorWithBody(RenderOrder.FRONT), AIControlled {
override val hitbox = Hitbox(0.0, 0.0, 2.0, 2.0)
init {
hitbox.setPosition(
HQRNG().nextInt(demoWorld.width) * CreateTileAtlas.TILE_SIZE.toDouble(),
0.0 // Y pos: placeholder; camera AI will take it over
)
}
override fun drawBody(batch: SpriteBatch) { }
override fun drawGlow(batch: SpriteBatch) { }
override fun update(delta: Float) {
}
override fun onActorValueChange(key: String, value: Any?) { }
override fun dispose() { }
override fun run() { TODO("not implemented") }
override fun moveLeft(amount: Float) {
TODO("not implemented")
}
override fun moveRight(amount: Float) {
TODO("not implemented")
}
override fun moveUp(amount: Float) {
TODO("not implemented")
}
override fun moveDown(amount: Float) {
TODO("not implemented")
}
override fun moveJump(amount: Float) {
TODO("not implemented")
}
override fun moveTo(bearing: Double) {
TODO("not implemented")
}
override fun moveTo(toX: Double, toY: Double) {
TODO("not implemented")
}
}
}

View File

@@ -95,7 +95,7 @@ object BlockPropUtil {
return when (type) {
1 -> getTorchFlicker(baseLum)
2 -> (Terrarum.ingame!!.world).globalLight.cpy().mul(LightmapRenderer.DIV_FLOAT) // current global light
3 -> WeatherMixer.getGlobalLightOfTime(WorldTime.DAY_LENGTH / 2).cpy().mul(LightmapRenderer.DIV_FLOAT) // daylight at noon
3 -> WeatherMixer.getGlobalLightOfTime(Terrarum.ingame!!.world, WorldTime.DAY_LENGTH / 2).cpy().mul(LightmapRenderer.DIV_FLOAT) // daylight at noon
4 -> getSlowBreath(baseLum)
5 -> getPulsate(baseLum)
else -> baseLum

View File

@@ -142,7 +142,7 @@ open class BlockLayer(val width: Int, val height: Int) : Disposable {
printdbg(this, "BlockLayer successfully freed")
}
internal fun getPtr() = ptr.ptr
internal fun getPtr() = ptr
companion object {
@Transient val BYTES_PER_BLOCK = 2L

View File

@@ -37,14 +37,14 @@ open class GameWorld : Disposable {
val width: Int
val height: Int
val creationTime: Long
var lastPlayTime: Long
open val creationTime: Long
open var lastPlayTime: Long
internal set // there's a case of save-and-continue-playing
var totalPlayTime: Int
open var totalPlayTime: Int
internal set
/** Used to calculate play time */
val loadTime: Long = System.currentTimeMillis() / 1000L
open val loadTime: Long = System.currentTimeMillis() / 1000L
//layers
@TEMzPayload("WALL", TEMzPayload.TWELVE_BITS_LITTLE)
@@ -57,9 +57,9 @@ open class GameWorld : Disposable {
//val layerFluidPressure: MapLayerHalfFloat // (milibar - 1000)
/** Tilewise spawn point */
var spawnX: Int
open var spawnX: Int
/** Tilewise spawn point */
var spawnY: Int
open var spawnY: Int
@TEMzPayload("WdMG", TEMzPayload.INT48_FLOAT_PAIR)
val wallDamages: HashMap<BlockAddress, Float>
@@ -84,18 +84,22 @@ open class GameWorld : Disposable {
//public World physWorld = new World( new Vec2(0, -Terrarum.game.gravitationalAccel) );
//physics
/** Meter per second squared. Currently only the downward gravity is supported. No reverse gravity :p */
var gravitation: Vector2 = Vector2(0.0, 9.80665)
open var gravitation: Vector2 = Vector2(0.0, 9.80665)
/** 0.0..1.0+ */
var globalLight = Cvec(0f, 0f, 0f, 0f)
var averageTemperature = 288f // 15 deg celsius; simulates global warming
open var globalLight = Cvec(0f, 0f, 0f, 0f)
open var averageTemperature = 288f // 15 deg celsius; simulates global warming
var generatorSeed: Long = 0
open var generatorSeed: Long = 0
internal set
var disposed = false
private set
/** time in (preferably) seconds */
open var TIME_T: Long = 0L
open var dayLength: Int = 86400
constructor(worldIndex: Int, width: Int, height: Int, creationTIME_T: Long, lastPlayTIME_T: Long, totalPlayTime: Int) {
if (width <= 0 || height <= 0) throw IllegalArgumentException("Non-positive width/height: ($width, $height)")

View File

@@ -101,7 +101,7 @@ class BuildingMaker(batch: SpriteBatch) : IngameInstance(batch) {
}
// set time to summer
gameWorld.time.addTime(WorldTime.DAY_LENGTH * 32)
gameWorld.worldTime.addTime(WorldTime.DAY_LENGTH * 32)
world = gameWorld
}
@@ -278,7 +278,7 @@ class BuildingMaker(batch: SpriteBatch) : IngameInstance(batch) {
private val essentialOverlays = ArrayList<ActorWithBody>()
init {
gameWorld.time.setTimeOfToday(WorldTime.HOUR_SEC * 10)
gameWorld.worldTime.setTimeOfToday(WorldTime.HOUR_SEC * 10)
gameWorld.globalLight = Cvec(.8f, .8f, .8f, .8f)
essentialOverlays.add(blockPointingCursor)
@@ -308,6 +308,7 @@ class BuildingMaker(batch: SpriteBatch) : IngameInstance(batch) {
uiPalette.setPosition(200, 100)
IngameRenderer.setWorld(gameWorld)
LightmapRenderer.fireRecalculateEvent()
}
@@ -392,7 +393,7 @@ class BuildingMaker(batch: SpriteBatch) : IngameInstance(batch) {
private fun renderGame() {
_testMarkerDrawCalls = 0L
IngameRenderer.invoke(false, world as GameWorldExtension, actorsRenderOverlay = if (showSelection) actorsRenderOverlay + essentialOverlays else essentialOverlays, uisToDraw = uiContainer)
IngameRenderer.invoke(false, actorsRenderOverlay = if (showSelection) actorsRenderOverlay + essentialOverlays else essentialOverlays, uisToDraw = uiContainer)
AppLoader.setDebugTime("Test.MarkerDrawCalls", _testMarkerDrawCalls)
}
@@ -597,25 +598,25 @@ class YamlCommandExit : YamlInvokable {
class YamlCommandSetTimeMorning : YamlInvokable {
override fun invoke(args: Array<Any>) {
(args[0] as BuildingMaker).gameWorld.time.setTimeOfToday(WorldTime.parseTime("7h00"))
(args[0] as BuildingMaker).gameWorld.worldTime.setTimeOfToday(WorldTime.parseTime("7h00"))
}
}
class YamlCommandSetTimeNoon : YamlInvokable {
override fun invoke(args: Array<Any>) {
(args[0] as BuildingMaker).gameWorld.time.setTimeOfToday(WorldTime.parseTime("12h30"))
(args[0] as BuildingMaker).gameWorld.worldTime.setTimeOfToday(WorldTime.parseTime("12h30"))
}
}
class YamlCommandSetTimeDusk : YamlInvokable {
override fun invoke(args: Array<Any>) {
(args[0] as BuildingMaker).gameWorld.time.setTimeOfToday(WorldTime.parseTime("18h40"))
(args[0] as BuildingMaker).gameWorld.worldTime.setTimeOfToday(WorldTime.parseTime("18h40"))
}
}
class YamlCommandSetTimeNight : YamlInvokable {
override fun invoke(args: Array<Any>) {
(args[0] as BuildingMaker).gameWorld.time.setTimeOfToday(WorldTime.parseTime("0h30"))
(args[0] as BuildingMaker).gameWorld.worldTime.setTimeOfToday(WorldTime.parseTime("0h30"))
}
}

View File

@@ -174,9 +174,7 @@ open class Ingame(batch: SpriteBatch) : IngameInstance(batch) {
GameLoadMode.LOAD_FROM -> enter(gameLoadInfoPayload as GameSaveData)
}
//LightmapRenderer.world = this.world
//BlocksDrawer.world = this.world
FeaturesDrawer.world = this.world
IngameRenderer.setWorld(gameworld)
super.show() // gameInitialised = true
@@ -556,7 +554,6 @@ open class Ingame(batch: SpriteBatch) : IngameInstance(batch) {
IngameRenderer.invoke(
paused,
world as GameWorldExtension,
visibleActorsRenderBehind,
visibleActorsRenderMiddle,
visibleActorsRenderMidTop,

View File

@@ -5,15 +5,17 @@ import com.badlogic.gdx.Input
import com.badlogic.gdx.graphics.*
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.glutils.FrameBuffer
import com.badlogic.gdx.graphics.glutils.ShaderProgram
import com.badlogic.gdx.utils.Disposable
import com.badlogic.gdx.utils.ScreenUtils
import net.torvald.gdx.graphics.PixmapIO2
import net.torvald.terrarum.*
import net.torvald.terrarum.AppLoader.printdbg
import net.torvald.terrarum.gameactors.ActorWithBody
import net.torvald.terrarum.gamecontroller.KeyToggler
import net.torvald.terrarum.gameworld.GameWorld
import net.torvald.terrarum.gameworld.fmod
import net.torvald.terrarum.modulebasegame.gameactors.ParticleBase
import net.torvald.terrarum.modulebasegame.gameworld.GameWorldExtension
import net.torvald.terrarum.modulebasegame.weather.WeatherMixer
import net.torvald.terrarum.ui.UICanvas
import net.torvald.terrarum.worlddrawer.*
@@ -41,12 +43,13 @@ object IngameRenderer : Disposable {
// you must have lightMixed FBO; otherwise you'll be reading from unbaked FBO and it freaks out GPU
private val shaderBlur = Terrarum.shaderBlur
private val shaderSkyboxFill = Terrarum.shaderSkyboxFill
private val shaderBlendGlow = Terrarum.shaderBlendGlow
private val shaderRGBOnly = Terrarum.shaderRGBOnly
private val shaderAtoGrey = Terrarum.shaderAtoGrey
private val shaderPassthru = SpriteBatch.createDefaultShader()
val shaderBlur: ShaderProgram
val shaderBayer: ShaderProgram
val shaderSkyboxFill: ShaderProgram
val shaderBlendGlow: ShaderProgram
val shaderRGBOnly: ShaderProgram
val shaderAtoGrey: ShaderProgram
val shaderPassthru = SpriteBatch.createDefaultShader()
private val width = Terrarum.WIDTH
private val height = Terrarum.HEIGHT
@@ -63,10 +66,6 @@ object IngameRenderer : Disposable {
private var debugMode = 0
init {
AppLoader.disposableSingletonsPool.add(this)
}
var renderingActorsCount = 0
private set
var renderingUIsCount = 0
@@ -74,9 +73,112 @@ object IngameRenderer : Disposable {
//var renderingParticleCount = 0
// private set
var world: GameWorld = GameWorld.makeNullWorld()
private set // the grammar "IngameRenderer.world = gameWorld" seemes mundane and this function needs special care!
// these codes will run regardless of the invocation of the "initialise()" function
// the "initialise()" function will also be called
init {
shaderBlur = AppLoader.loadShader("assets/blur.vert", "assets/blur.frag")
if (AppLoader.getConfigBoolean("fxdither")) {
shaderBayer = AppLoader.loadShader("assets/4096.vert", "assets/4096_bayer.frag")
shaderBayer.begin()
shaderBayer.setUniformf("rcount", 64f)
shaderBayer.setUniformf("gcount", 64f)
shaderBayer.setUniformf("bcount", 64f)
shaderBayer.end()
shaderSkyboxFill = AppLoader.loadShader("assets/4096.vert", "assets/4096_bayer_skyboxfill.frag")
shaderSkyboxFill.begin()
shaderSkyboxFill.setUniformf("rcount", 64f)
shaderSkyboxFill.setUniformf("gcount", 64f)
shaderSkyboxFill.setUniformf("bcount", 64f)
shaderSkyboxFill.end()
}
else {
shaderBayer = AppLoader.loadShader("assets/4096.vert", "assets/passthrurgb.frag")
shaderSkyboxFill = AppLoader.loadShader("assets/4096.vert", "assets/skyboxfill.frag")
}
shaderBlendGlow = AppLoader.loadShader("assets/blendGlow.vert", "assets/blendGlow.frag")
shaderRGBOnly = AppLoader.loadShader("assets/4096.vert", "assets/rgbonly.frag")
shaderAtoGrey = AppLoader.loadShader("assets/4096.vert", "assets/aonly.frag")
if (!shaderBlendGlow.isCompiled) {
Gdx.app.log("shaderBlendGlow", shaderBlendGlow.log)
System.exit(1)
}
if (AppLoader.getConfigBoolean("fxdither")) {
if (!shaderBayer.isCompiled) {
Gdx.app.log("shaderBayer", shaderBayer.log)
System.exit(1)
}
if (!shaderSkyboxFill.isCompiled) {
Gdx.app.log("shaderSkyboxFill", shaderSkyboxFill.log)
System.exit(1)
}
}
initialise()
}
/** Whether or not "initialise()" method had been called */
private var initialisedExternally = false
/** To make it more convenient to be initialised by the Java code, and for the times when the order of the call
* actually matter */
@JvmStatic fun initialise() {
if (!initialisedExternally) {
AppLoader.disposableSingletonsPool.add(this)
// also initialise these sinigletons
BlocksDrawer
LightmapRenderer
initialisedExternally = true
}
}
/**
* Your game/a scene that renders the world must call this method at least once!
*
* For example:
* - When the main scene that renders the world is first created
* - When the game make transition to the new world (advancing to the next level/entering or exiting the room)
*/
fun setWorld(world: GameWorld) {
try {
if (this.world != world) {
printdbg(this, "World change detected -- " +
"old world: ${this.world.hashCode()}, " +
"new world: ${world.hashCode()}")
// change worlds from internal methods
LightmapRenderer.internalSetWorld(world)
BlocksDrawer.world = world
FeaturesDrawer.world = world
}
}
catch (e: UninitializedPropertyAccessException) {
// new init, do nothing
}
finally {
this.world = world
}
}
operator fun invoke(
gamePaused: Boolean,
world: GameWorldExtension,
actorsRenderBehind : List<ActorWithBody>? = null,
actorsRenderMiddle : List<ActorWithBody>? = null,
actorsRenderMidTop : List<ActorWithBody>? = null,
@@ -100,15 +202,11 @@ object IngameRenderer : Disposable {
uiListToDraw = uisToDraw
}
init()
invokeInit()
batch.color = Color.WHITE
BlocksDrawer.world = world
LightmapRenderer.setWorld(world)
FeaturesDrawer.world = world
this.player = player
@@ -480,7 +578,7 @@ object IngameRenderer : Disposable {
}
private fun init() {
private fun invokeInit() {
if (!initDone) {
batch = SpriteBatch()
camera = OrthographicCamera(widthf, heightf)
@@ -639,6 +737,14 @@ object IngameRenderer : Disposable {
WeatherMixer.dispose()
batch.dispose()
shaderBlur.dispose()
shaderBayer.dispose()
shaderSkyboxFill.dispose()
shaderBlendGlow.dispose()
shaderRGBOnly.dispose()
shaderAtoGrey.dispose()
shaderPassthru.dispose()
}
private fun worldCamToRenderPos(): Pair<Float, Float> {

View File

@@ -11,7 +11,7 @@ import net.torvald.terrarum.modulebasegame.gameworld.GameWorldExtension
internal object GetTime : ConsoleCommand {
override fun execute(args: Array<String>) {
val worldTime = (Terrarum.ingame!!.world as GameWorldExtension).time
val worldTime = (Terrarum.ingame!!.world as GameWorldExtension).worldTime
Echo(worldTime.getFormattedTime())
}

View File

@@ -17,10 +17,10 @@ internal object SetTime : ConsoleCommand {
if (args.size == 2) {
val timeToSet = WorldTime.parseTime(args[1])
world.time.setTimeOfToday(timeToSet)
world.worldTime.setTimeOfToday(timeToSet)
Echo("Set time to ${world.time.todaySeconds} " +
"(${world.time.hours}h${formatMin(world.time.minutes)})")
Echo("Set time to ${world.worldTime.todaySeconds} " +
"(${world.worldTime.hours}h${formatMin(world.worldTime.minutes)})")
}
else {
printUsage()

View File

@@ -17,11 +17,11 @@ internal object SetTimeDelta : ConsoleCommand {
if (args.size == 2) {
world.time.timeDelta = args[1].toInt()
if (world.time.timeDelta == 0)
world.worldTime.timeDelta = args[1].toInt()
if (world.worldTime.timeDelta == 0)
Echo("時間よ止まれ!ザ・ワルド!!")
else
Echo("Set time delta to ${world.time.timeDelta}")
Echo("Set time delta to ${world.worldTime.timeDelta}")
}
else {
printUsage()

View File

@@ -12,7 +12,6 @@ import net.torvald.terrarum.gameworld.GameWorld
import net.torvald.terrarum.itemproperties.ItemCodex
import net.torvald.terrarum.itemproperties.Material
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.modulebasegame.gameworld.time_t
import net.torvald.terrarum.modulebasegame.ui.UIInventoryFull
import net.torvald.terrarum.realestate.LandUtil
import net.torvald.terrarum.worlddrawer.LightmapRenderer
@@ -31,8 +30,8 @@ import java.util.*
* Created by minjaesong on 2016-10-24.
*/
open class ActorHumanoid(
birth: time_t,
death: time_t? = null,
birth: Long,
death: Long? = null,
usePhysics: Boolean = true
) : ActorWBMovable(RenderOrder.MIDDLE, usePhysics = usePhysics), Controllable, Pocketed, Factionable, Luminous, LandHolder, HistoricalFigure {

View File

@@ -6,7 +6,6 @@ import net.torvald.terrarum.gameactors.AVKey
import net.torvald.terrarum.gameactors.ai.ActorAI
import net.torvald.terrarum.gameitem.GameItem
import net.torvald.terrarum.itemproperties.Material
import net.torvald.terrarum.modulebasegame.gameworld.time_t
/**
* @param ai AI class. Use LuaAIWrapper for Lua script
@@ -15,7 +14,7 @@ import net.torvald.terrarum.modulebasegame.gameworld.time_t
*/
open class HumanoidNPC(
override val ai: ActorAI, // it's there for written-in-Kotlin, "hard-wired" AIs
born: time_t,
born: Long,
usePhysics: Boolean = true
//forceAssignRefID: Int? = null
) : ActorHumanoid(born, usePhysics = usePhysics), AIControlled, CanBeAnItem {

View File

@@ -2,7 +2,6 @@ package net.torvald.terrarum.modulebasegame.gameactors
import net.torvald.spriteanimation.HasAssembledSprite
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.modulebasegame.gameworld.time_t
/**
@@ -14,7 +13,7 @@ import net.torvald.terrarum.modulebasegame.gameworld.time_t
class IngamePlayer(
override var animDescPath: String,
override var animDescPathGlow: String? = null,
born: time_t
born: Long
) : ActorHumanoid(born), HasAssembledSprite {
/**

View File

@@ -13,7 +13,7 @@ object PlayerBuilder {
operator fun invoke(): Actor {
val world = (Terrarum.ingame!! as Ingame).gameworld
val p: Actor = IngamePlayer("lol", "lol_glow", world.time.TIME_T)
val p: Actor = IngamePlayer("lol", "lol_glow", world.worldTime.TIME_T)
InjectCreatureRaw(p.actorValue, "basegame", "CreatureHuman.json")
// attach sprite

View File

@@ -6,15 +6,24 @@ import net.torvald.terrarum.serialise.ReadLayerDataZip
/**
* Created by minjaesong on 2018-07-03.
*/
class GameWorldExtension: GameWorld {
class GameWorldExtension : GameWorld {
constructor(worldIndex: Int, width: Int, height: Int, creationTIME_T: Long, lastPlayTIME_T: Long, totalPlayTime: Int) : super(worldIndex, width, height, creationTIME_T, lastPlayTIME_T, totalPlayTime)
internal constructor(worldIndex: Int, layerData: ReadLayerDataZip.LayerData, creationTIME_T: Long, lastPlayTIME_T: Long, totalPlayTime: Int) : super(worldIndex, layerData, creationTIME_T, lastPlayTIME_T, totalPlayTime)
val time: WorldTime
/** Extended world time */
val worldTime: WorldTime
val economy = GameEconomy()
override var TIME_T: Long
get() = worldTime.TIME_T
set(value) { worldTime.TIME_T = value }
override var dayLength: Int
get() = WorldTime.DAY_LENGTH
set(value) { throw UnsupportedOperationException() }
// delegated properties //
/*val layerWall: MapLayer; get() = baseworld.layerWall
val layerTerrain: MapLayer; get() = baseworld.layerTerrain
@@ -35,14 +44,14 @@ class GameWorldExtension: GameWorld {
val damageDataArray: ByteArray; get() = baseworld.damageDataArray*/
init {
time = WorldTime( // Year EPOCH (125), Month 1, Day 1 is implied
worldTime = WorldTime( // Year EPOCH (125), Month 1, Day 1 is implied
7 * WorldTime.HOUR_SEC +
30L * WorldTime.MINUTE_SEC
)
}
fun updateWorldTime(delta: Float) {
time.update(delta)
worldTime.update(delta)
}
}

View File

@@ -3,8 +3,6 @@ package net.torvald.terrarum.modulebasegame.gameworld
import net.torvald.terrarum.gameworld.fmod
typealias time_t = Long
/**
* Please also see:
* https://en.wikipedia.org/wiki/World_Calendar
@@ -56,8 +54,9 @@ typealias time_t = Long
* Created by minjaesong on 2016-01-24.
*/
class WorldTime(initTime: Long = 0L) {
/** It is not recommended to directly modify the TIME_T. Use provided methods instead. */
var TIME_T = 0L // Epoch: Year 125 Spring 1st, 0h00:00 (Mondag) // 125-01-01
private set
init {
TIME_T = initTime

View File

@@ -38,7 +38,7 @@ class UITierOneWatch(private val player: ActorHumanoid?) : UICanvas() {
//get() = if (ELon) lcdLitColELon else lcdLitColELoff
private val worldTime: WorldTime
get() = (Terrarum.ingame!!.world as GameWorldExtension).time
get() = (Terrarum.ingame!!.world as GameWorldExtension).worldTime
override fun updateUI(delta: Float) {

View File

@@ -6,20 +6,17 @@ import com.badlogic.gdx.graphics.Camera
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Texture
import net.torvald.colourutil.CIELuvUtil
import net.torvald.gdx.graphics.Cvec
import net.torvald.random.HQRNG
import net.torvald.terrarum.GdxColorMap
import net.torvald.terrarum.ModMgr
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.*
import net.torvald.terrarum.gameactors.ActorWithBody
import net.torvald.terrarum.gamecontroller.KeyToggler
import net.torvald.terrarum.gdxSetBlendNormal
import net.torvald.terrarum.gameworld.GameWorld
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.modulebasegame.IngameRenderer
import net.torvald.terrarum.modulebasegame.RNGConsumer
import net.torvald.terrarum.modulebasegame.gameactors.ParticleMegaRain
import net.torvald.terrarum.modulebasegame.gameworld.GameWorldExtension
import net.torvald.terrarum.modulebasegame.gameworld.WorldTime
import net.torvald.terrarum.modulebasegame.worldgenerator.WorldGenerator
import net.torvald.terrarum.utils.JsonFetcher
import net.torvald.terrarum.worlddrawer.CreateTileAtlas
@@ -124,16 +121,16 @@ internal object WeatherMixer : RNGConsumer {
/**
* Sub-portion of IngameRenderer. You are not supposed to directly deal with this.
*/
internal fun render(camera: Camera, world: GameWorldExtension) {
internal fun render(camera: Camera, world: GameWorld) {
val parallaxZeroPos = (world.height / 3) * 0.75f // just an arb multiplier (266.66666 -> 200)
// we will not care for nextSkybox for now
val timeNow = world.time.todaySeconds
val timeNow = world.TIME_T.toInt() % world.dayLength
val skyboxColourMap = currentWeather.skyboxGradColourMap
// calculate global light
val globalLight = getGradientColour(skyboxColourMap, 2, timeNow)
val globalLight = getGradientColour(world, skyboxColourMap, 2, timeNow)
globalLightNow.set(globalLight)
@@ -152,20 +149,20 @@ internal object WeatherMixer : RNGConsumer {
// draw skybox to provided graphics instance
val topCol = getGradientColour(skyboxColourMap, 0, timeNow)
val bottomCol = getGradientColour(skyboxColourMap, 1, timeNow)
val topCol = getGradientColour(world, skyboxColourMap, 0, timeNow)
val bottomCol = getGradientColour(world, skyboxColourMap, 1, timeNow)
//Terrarum.textureWhiteSquare.bind(0)
gdxSetBlendNormal()
Terrarum.shaderSkyboxFill.begin()
Terrarum.shaderSkyboxFill.setUniformMatrix("u_projTrans", camera.combined)
Terrarum.shaderSkyboxFill.setUniformf("topColor", topCol.r, topCol.g, topCol.b)
Terrarum.shaderSkyboxFill.setUniformf("bottomColor", bottomCol.r, bottomCol.g, bottomCol.b)
Terrarum.shaderSkyboxFill.setUniformf("parallax", parallax.coerceIn(-1f, 1f))
Terrarum.shaderSkyboxFill.setUniformf("parallax_size", 1f/3f)
Terrarum.fullscreenQuad.render(Terrarum.shaderSkyboxFill, GL20.GL_TRIANGLES)
Terrarum.shaderSkyboxFill.end()
IngameRenderer.shaderSkyboxFill.begin()
IngameRenderer.shaderSkyboxFill.setUniformMatrix("u_projTrans", camera.combined)
IngameRenderer.shaderSkyboxFill.setUniformf("topColor", topCol.r, topCol.g, topCol.b)
IngameRenderer.shaderSkyboxFill.setUniformf("bottomColor", bottomCol.r, bottomCol.g, bottomCol.b)
IngameRenderer.shaderSkyboxFill.setUniformf("parallax", parallax.coerceIn(-1f, 1f))
IngameRenderer.shaderSkyboxFill.setUniformf("parallax_size", 1f/3f)
AppLoader.fullscreenQuad.render(IngameRenderer.shaderSkyboxFill, GL20.GL_TRIANGLES)
IngameRenderer.shaderSkyboxFill.end()
Gdx.gl.glActiveTexture(GL20.GL_TEXTURE0) // so that batch that comes next will bind any tex to it
@@ -179,11 +176,11 @@ internal object WeatherMixer : RNGConsumer {
/**
* Get a GL of specific time
*/
fun getGlobalLightOfTime(timeInSec: Int): Cvec =
getGradientColour(currentWeather.skyboxGradColourMap, 2, timeInSec)
fun getGlobalLightOfTime(world: GameWorld, timeInSec: Int): Cvec =
getGradientColour(world, currentWeather.skyboxGradColourMap, 2, timeInSec)
fun getGradientColour(colorMap: GdxColorMap, row: Int, timeInSec: Int): Cvec {
val dataPointDistance = WorldTime.DAY_LENGTH / colorMap.width
fun getGradientColour(world: GameWorld, colorMap: GdxColorMap, row: Int, timeInSec: Int): Cvec {
val dataPointDistance = world.dayLength / colorMap.width
val phaseThis: Int = timeInSec / dataPointDistance // x-coord in gradmap
val phaseNext: Int = (phaseThis + 1) % colorMap.width

View File

@@ -23,7 +23,7 @@ class WorldInformationProvider(globals: Globals) {
companion object {
fun getWorldTimeInLuaFormat() : LuaTable {
val t = LuaTable()
val time = if (Terrarum.ingame != null) (Terrarum.ingame!!.world as GameWorldExtension).time else WorldTime()
val time = if (Terrarum.ingame != null) (Terrarum.ingame!!.world as GameWorldExtension).worldTime else WorldTime()
// int Terrarum World Time format
t["hour"] = time.hours
@@ -42,7 +42,7 @@ class WorldInformationProvider(globals: Globals) {
/** evaluate single C date format */
fun String.evalAsDate(): String {
val time = if (Terrarum.ingame != null) (Terrarum.ingame!!.world as GameWorldExtension).time else WorldTime()
val time = if (Terrarum.ingame != null) (Terrarum.ingame!!.world as GameWorldExtension).worldTime else WorldTime()
return when (this) {
"%a" -> time.getDayNameShort()
"%A" -> time.getDayNameFull()

View File

@@ -101,7 +101,7 @@ object WriteWorldInfo {
metaOut.write(Terrarum.PLAYER_REF_ID.toLittle())
// ingame time_t
metaOut.write((world as GameWorldExtension).time.TIME_T.toLittle())
metaOut.write((world as GameWorldExtension).worldTime.TIME_T.toLittle())
// creation time (real world time)
metaOut.write(world.creationTime.toULittle48())

View File

@@ -178,8 +178,8 @@ class BasicDebugInfoWindow : UICanvas() {
//printLineColumn(batch, 2, 2, "Env colour temp $ccG" + FeaturesDrawer.colTemp)
if (world != null) {
printLineColumn(batch, 2, 5, "Time $ccG${world2!!.time.todaySeconds.toString().padStart(5, '0')}" +
" (${world2!!.time.getFormattedTime()})")
printLineColumn(batch, 2, 5, "Time $ccG${world2!!.worldTime.todaySeconds.toString().padStart(5, '0')}" +
" (${world2!!.worldTime.getFormattedTime()})")
}
if (player != null) {

View File

@@ -31,7 +31,7 @@ import kotlin.math.roundToInt
*/
internal object BlocksDrawer {
var world: GameWorld = GameWorld.makeNullWorld()
internal var world: GameWorld = GameWorld.makeNullWorld()
private val TILE_SIZE = CreateTileAtlas.TILE_SIZE
private val TILE_SIZEF = CreateTileAtlas.TILE_SIZE.toFloat()
@@ -189,7 +189,7 @@ internal object BlocksDrawer {
internal fun renderData() {
try {
drawTIME_T = (world as GameWorldExtension).time.TIME_T - (WorldTime.DAY_LENGTH * 15) // offset by -15 days
drawTIME_T = (world as GameWorldExtension).worldTime.TIME_T - (WorldTime.DAY_LENGTH * 15) // offset by -15 days
val seasonalMonth = (drawTIME_T.div(WorldTime.DAY_LENGTH) fmod WorldTime.YEAR_DAYS.toLong()).toInt() / WorldTime.MONTH_LENGTH + 1
tilesTerrain = weatherTerrains[seasonalMonth - 1]

View File

@@ -16,7 +16,7 @@ import net.torvald.terrarum.worlddrawer.CreateTileAtlas.TILE_SIZE
* Created by minjaesong on 2015-12-31.
*/
object FeaturesDrawer {
lateinit var world: GameWorld
internal var world: GameWorld = GameWorld.makeNullWorld()
//const val TILE_SIZE = CreateTileAtlas.TILE_SIZE

View File

@@ -39,11 +39,12 @@ object LightmapRenderer {
private const val TILE_SIZE = CreateTileAtlas.TILE_SIZE
private var world: GameWorld = GameWorld.makeNullWorld()
private lateinit var lightCalcShader: ShaderProgram
//private val SHADER_LIGHTING = AppLoader.getConfigBoolean("gpulightcalc")
/** do not call this yourself! Let your game renderer handle this! */
fun setWorld(world: GameWorld) {
internal fun internalSetWorld(world: GameWorld) {
try {
if (this.world != world) {
printdbg(this, "World change detected -- old world: ${this.world.hashCode()}, new world: ${world.hashCode()}")
@@ -213,9 +214,9 @@ object LightmapRenderer {
}
catch (e: NullPointerException) {
System.err.println("[LightmapRendererNew.fireRecalculateEvent] Attempted to refer destroyed unsafe array " +
"(world size: ${world.layerTerrain.width} x ${world.layerTerrain.height}; " +
"ptr: 0x${world.layerTerrain.getPtr().toString(16)})")
return
"(${world.layerTerrain.getPtr()})")
e.printStackTrace()
return // something's wrong but we'll ignore it like a trustful AK
}
if (world.worldIndex == -1) return

View File

@@ -3,7 +3,7 @@ package net.torvald.terrarum.worlddrawer
import com.jme3.math.FastMath
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.floorInt
import net.torvald.terrarum.gameactors.ActorWBMovable
import net.torvald.terrarum.gameactors.ActorWithBody
import net.torvald.terrarum.gameworld.GameWorld
import org.dyn4j.geometry.Vector2
@@ -36,7 +36,7 @@ object WorldCamera {
private val nullVec = Vector2(0.0, 0.0)
fun update(world: GameWorld, player: ActorWBMovable?) {
fun update(world: GameWorld, player: ActorWithBody?) {
if (player == null) return
width = FastMath.ceil(Terrarum.WIDTH / (Terrarum.ingame?.screenZoom ?: 1f)) // div, not mul
@@ -46,7 +46,7 @@ object WorldCamera {
// some hacky equation to position player at the dead centre
// implementing the "lag behind" camera the right way
val pVecSum = player.externalV + (player.controllerV ?: nullVec)
val pVecSum = Vector2(0.0, 0.0)//player.externalV + (player.controllerV ?: nullVec)
x = ((player.hitbox.centeredX - pVecSum.x).toFloat() - (width / 2)).floorInt() // X only: ROUNDWORLD implementation