initial savefile generation of the newgame

This commit is contained in:
minjaesong
2021-09-29 12:38:08 +09:00
parent f4a4030260
commit 2891d0466e
21 changed files with 1456 additions and 83 deletions

Binary file not shown.

View File

@@ -14,7 +14,7 @@ object CommonResourcePool {
private val loadingList = Queue<ResourceLoadingDescriptor>()
private val pool = HashMap<String, Any>()
private val poolKillFun = HashMap<String, (() -> Unit)?>()
private val poolKillFun = HashMap<String, ((Any) -> Unit)?>()
//private val typesMap = HashMap<String, Class<*>>()
private var loadCounter = -1 // using counters so that the loading can be done on separate thread (gg if the asset requires GL context to be loaded)
val loaded: Boolean // see if there's a thing to load
@@ -77,7 +77,7 @@ object CommonResourcePool {
* - com.badlogic.gdx.graphics.g2d.TextureRegion
* - net.torvald.UnsafePtr
*/
fun addToLoadingList(identifier: String, loadFunction: () -> Any, destroyFunction: (() -> Unit)?) {
fun addToLoadingList(identifier: String, loadFunction: () -> Any, destroyFunction: ((Any) -> Unit)?) {
// check if resource is already there
if (!resourceExists(identifier)) {
loadingList.addFirst(ResourceLoadingDescriptor(identifier, loadFunction, destroyFunction))
@@ -128,7 +128,7 @@ object CommonResourcePool {
u is Texture -> u.dispose()
u is TextureRegion -> u.texture.dispose()
u is UnsafePtr -> u.destroy()
else -> poolKillFun[name]?.invoke()
else -> poolKillFun[name]?.invoke(u)
}
}
catch (e: Throwable) {
@@ -140,6 +140,6 @@ object CommonResourcePool {
private data class ResourceLoadingDescriptor(
val name: String,
val loadfun: () -> Any,
val killfun: (() -> Unit)? = null
val killfun: ((Any) -> Unit)? = null
)
}

View File

@@ -45,6 +45,8 @@ open class IngameInstance(val batch: SpriteBatch) : Screen {
lateinit var savegameArchive: VirtualDisk
internal set
var savegameNickname: String = "SplinesReticulated"
internal set
var screenZoom = 1.0f
val ZOOM_MAXIMUM = 4.0f

View File

@@ -126,6 +126,7 @@ open class GameWorld() : Disposable {
this.width = width
this.height = height
// preliminary spawn points
this.spawnX = width / 2
this.spawnY = 200

View File

@@ -32,19 +32,18 @@ import net.torvald.terrarum.modulebasegame.worldgenerator.RoguelikeRandomiser
import net.torvald.terrarum.modulebasegame.worldgenerator.Worldgen
import net.torvald.terrarum.modulebasegame.worldgenerator.WorldgenParams
import net.torvald.terrarum.realestate.LandUtil
import net.torvald.terrarum.serialise.Common
import net.torvald.terrarum.serialise.LoadSavegame
import net.torvald.terrarum.serialise.ReadActor
import net.torvald.terrarum.serialise.WriteMeta
import net.torvald.terrarum.serialise.*
import net.torvald.terrarum.tvda.VDUtil
import net.torvald.terrarum.tvda.VirtualDisk
import net.torvald.terrarum.ui.UICanvas
import net.torvald.terrarum.utils.RandomWordsName
import net.torvald.terrarum.weather.WeatherMixer
import net.torvald.terrarum.worlddrawer.BlocksDrawer
import net.torvald.terrarum.worlddrawer.FeaturesDrawer
import net.torvald.terrarum.worlddrawer.WorldCamera
import net.torvald.util.CircularArray
import org.khelekore.prtree.PRTree
import java.io.File
import java.util.concurrent.locks.ReentrantLock
import kotlin.math.roundToInt
@@ -231,7 +230,8 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
data class NewWorldParameters(
val width: Int,
val height: Int,
val worldGenSeed: Long
val worldGenSeed: Long,
val savegameName: String
// other worldgen options
) {
init {
@@ -278,7 +278,7 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
Terrarum.itemCodex.loadFromSave(codices.item)
Terrarum.apocryphas = HashMap(codices.apocryphas)
savegameNickname = codices.disk.getDiskNameString(Common.CHARSET)
}
}
@@ -293,6 +293,32 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
actorNowPlaying = getActorByID(Terrarum.PLAYER_REF_ID) as IngamePlayer
}
private fun postInitForNewGame() {
// go to spawn position
printdbg(this, "World Spawn position: (${world.spawnX}, ${world.spawnY})")
// setTheRealGamerFirstTime(PlayerBuilderSigrid())
setTheRealGamerFirstTime(PlayerBuilderTestSubject1())
// setTheRealGamerFirstTime(PlayerBuilderWerebeastTest())
savegameArchive = VDUtil.createNewDisk(
1L shl 60,
savegameNickname,
Common.CHARSET
)
actorNowPlaying!!.setPosition(
world.spawnX * TILE_SIZED,
world.spawnY * TILE_SIZED
)
// make initial savefile
// pause()
WriteSavegame.immediate(savegameArchive, File(App.defaultSaveDir, savegameNickname), this) {
// resume()
}
}
/**
* Init instance by creating new world
*/
@@ -324,6 +350,8 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
historicalFigureIDBucket = ArrayList<Int>()
savegameNickname = worldParams.savegameName
}
KeyToggler.forceSet(Input.Keys.Q, false)
@@ -333,17 +361,7 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
/** Load rest of the game with GL context */
fun postInit() {
if (actorNowPlaying == null) {
//setTheRealGamerFirstTime(PlayerBuilderSigrid())
setTheRealGamerFirstTime(PlayerBuilderTestSubject1())
// setTheRealGamerFirstTime(PlayerBuilderWerebeastTest())
savegameArchive = VDUtil.createNewDisk(
1L shl 60,
actorNowPlaying!!.actorValue.getAsString(AVKey.NAME) ?: "Player ${App.getTIME_T()}",
Common.CHARSET
)
}
actorNowPlaying!! // null check, just in case...
MegaRainGovernor // invoke MegaRain Governor
@@ -529,11 +547,7 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
if (!gameFullyLoaded) {
if (gameLoadMode == GameLoadMode.CREATE_NEW) {
// go to spawn position
actorNowPlaying?.setPosition(
world.spawnX * TILE_SIZED,
world.spawnY * TILE_SIZED
)
postInitForNewGame()
}
else if (gameLoadMode == GameLoadMode.LOAD_FROM) {
postInitForLoadFromSave(gameLoadInfoPayload as Codices)
@@ -541,7 +555,6 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
postInit()
gameFullyLoaded = true
}
@@ -1054,10 +1067,11 @@ open class TerrarumIngame(batch: SpriteBatch) : IngameInstance(batch) {
}
override fun pause() {
// TODO no pause when off-focus on desktop
paused = true
}
override fun resume() {
paused = false
}
override fun hide() {

View File

@@ -56,7 +56,7 @@ object Save : ConsoleCommand {
}
override fun printUsage() {
Echo("Usage: save <filename>")
Echo("Usage: save <new-savegame-name>")
}
}

View File

@@ -235,20 +235,20 @@ internal class UIStorageChest : UICanvas(
}
override fun doOpening(delta: Float) {
Terrarum.ingame?.paused = true
(Terrarum.ingame as? TerrarumIngame)?.setTooltipMessage(null)
INGAME.pause()
INGAME.setTooltipMessage(null)
}
override fun doClosing(delta: Float) {
Terrarum.ingame?.paused = false
(Terrarum.ingame as? TerrarumIngame)?.setTooltipMessage(null)
INGAME.resume()
INGAME.setTooltipMessage(null)
}
override fun endOpening(delta: Float) {
}
override fun endClosing(delta: Float) {
(Terrarum.ingame as? TerrarumIngame)?.setTooltipMessage(null) // required!
INGAME.setTooltipMessage(null) // required!
}

View File

@@ -34,7 +34,9 @@ object PlayerBuilderTestSubject1 {
p.reassembleSprite(p.sprite!!, p.spriteGlow)
p.setHitboxDimension(15, p.actorValue.getAsInt(AVKey.BASEHEIGHT) ?: ActorHumanoid.BASE_HEIGHT, 21, 0)
p.setPosition(3.0 * TILE_SIZE, 3.0 * TILE_SIZE)
// ingame must teleport the player to the spawn point
// see `TerrarumIngame.render`
// p.setPosition(3.0 * TILE_SIZE, 3.0 * TILE_SIZE)
PlayerBuilderSigrid.fillTestInventory(p.inventory)

View File

@@ -4,10 +4,7 @@ import com.badlogic.gdx.graphics.Camera
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import net.torvald.terrarum.App
import net.torvald.terrarum.Second
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.fillRect
import net.torvald.terrarum.*
import net.torvald.terrarum.langpack.Lang
import net.torvald.terrarum.ui.Toolkit
import net.torvald.terrarum.ui.UICanvas
@@ -51,7 +48,7 @@ class UICheatDetected : UICanvas() {
}
override fun doOpening(delta: Float) {
Terrarum.ingame?.paused = true
INGAME.pause()
}
override fun doClosing(delta: Float) {

View File

@@ -85,8 +85,13 @@ class UIInventoryEscMenu(val full: UIInventoryFull) : UICanvas() {
screen = 3; gameMenuButtons.deselect()
full.handler.lockToggle()
full.lockTransition()
// make backup of the old save
File(App.defaultSaveDir, INGAME.savegameNickname).copyTo(
File(App.defaultSaveDir, INGAME.savegameNickname+".1"), // don't use .bak as it's used by the savecracker
true
)
// save the game
WriteSavegame(INGAME.savegameArchive, File(App.defaultSaveDir, "${App.getTIME_T()}"), Terrarum.ingame!! as TerrarumIngame) {
WriteSavegame(INGAME.savegameArchive, File(App.defaultSaveDir, INGAME.savegameNickname), Terrarum.ingame!! as TerrarumIngame) {
// callback:
System.gc()
screen = 0

View File

@@ -275,20 +275,20 @@ class UIInventoryFull(
override fun doOpening(delta: Float) {
Terrarum.ingame?.paused = true
(Terrarum.ingame as? TerrarumIngame)?.setTooltipMessage(null)
INGAME.pause()
INGAME.setTooltipMessage(null)
}
override fun doClosing(delta: Float) {
Terrarum.ingame?.paused = false
(Terrarum.ingame as? TerrarumIngame)?.setTooltipMessage(null)
INGAME.resume()
INGAME.setTooltipMessage(null)
}
override fun endOpening(delta: Float) {
}
override fun endClosing(delta: Float) {
(Terrarum.ingame as? TerrarumIngame)?.setTooltipMessage(null) // required!
INGAME.setTooltipMessage(null) // required!
MinimapComposer.revalidateAll()
}

View File

@@ -374,7 +374,7 @@ class UIItemInventoryItemGrid(
// set tooltip accordingly
if (isCompactMode && it.item != null && it.mouseUp && !tooltipSet) {
(Terrarum.ingame as? TerrarumIngame)?.setTooltipMessage(
INGAME.setTooltipMessage(
if (INVEN_DEBUG_MODE) {
it.item?.name + " (${it.item?.originalID}${if (it.item?.originalID == it.item?.dynamicID) "" else "/${it.item?.dynamicID}"})"
}
@@ -387,7 +387,7 @@ class UIItemInventoryItemGrid(
}
if (!tooltipSet) {
(Terrarum.ingame as? TerrarumIngame)?.setTooltipMessage(null)
INGAME.setTooltipMessage(null)
}

View File

@@ -1,5 +1,6 @@
package net.torvald.terrarum.modulebasegame.ui
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.badlogic.gdx.graphics.*
import com.badlogic.gdx.graphics.g2d.SpriteBatch
@@ -10,6 +11,7 @@ import net.torvald.getKeycapConsole
import net.torvald.getKeycapPC
import net.torvald.terrarum.*
import net.torvald.terrarum.langpack.Lang
import net.torvald.terrarum.serialise.Common
import net.torvald.terrarum.serialise.LoadSavegame
import net.torvald.terrarum.serialise.ReadMeta
import net.torvald.terrarum.tvda.ByteArray64InputStream
@@ -27,6 +29,13 @@ import kotlin.math.roundToInt
*/
class UILoadDemoSavefiles : UICanvas() {
init {
CommonResourcePool.addToLoadingList("terrarum-defaultsavegamethumb") {
TextureRegion(Texture(Gdx.files.internal("assets/graphics/gui/savegame_thumb_placeholder.png")))
}
CommonResourcePool.loadAll()
}
override var width: Int
get() = App.scr.width
set(value) {}
@@ -277,7 +286,7 @@ class UIItemDemoSaveCells(
override val height: Int = HEIGHT
private lateinit var thumbPixmap: Pixmap
private lateinit var thumb: TextureRegion
private var thumb: TextureRegion? = null
private val grad = CommonResourcePool.getAsTexture("title_halfgrad")
private val meta = ReadMeta(disk)
@@ -309,7 +318,7 @@ class UIItemDemoSaveCells(
val thumbTex = Texture(thumbPixmap)
thumbTex.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear)
thumb = TextureRegion(thumbTex)
thumb.setRegion(0, (thumbTex.height - 2 * height) / 2, width * 2, height * 2)
thumb!!.setRegion(0, (thumbTex.height - 2 * height) / 2, width * 2, height * 2)
}
catch (e: NullPointerException) {
// use stock texture
@@ -335,7 +344,7 @@ class UIItemDemoSaveCells(
// draw thumbnail
batch.color = Color.WHITE
blendNormal(batch)
batch.draw(thumb, x, y + height, width.toFloat(), -height.toFloat())
batch.draw(thumb ?: CommonResourcePool.getAsTextureRegion("terrarum-defaultsavegamethumb"), x, y + height, width.toFloat(), -height.toFloat())
// draw gradient
blendMul(batch)
batch.draw(grad, x + width.toFloat(), y, -width.toFloat(), height.toFloat())
@@ -350,14 +359,14 @@ class UIItemDemoSaveCells(
// file size
App.fontSmallNumbers.draw(batch, "${disk.usedBytes.ushr(10)} KiB", x + 3f, y + height - 16f)
// savegame name
// App.fontGame.draw(batch, disk.getDiskNameString(Common.CHARSET), x + 3f, y + 1f)
App.fontGame.draw(batch, disk.getDiskNameString(Common.CHARSET), x + 3f, y + 1f)
super.render(batch, camera)
batch.color = Color.WHITE
}
override fun dispose() {
thumb.texture.dispose()
thumb?.texture?.dispose()
thumbPixmap.dispose()
}

View File

@@ -10,6 +10,7 @@ import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.modulebasegame.TerrarumIngame
import net.torvald.terrarum.modulebasegame.WorldgenLoadScreen
import net.torvald.terrarum.ui.UICanvas
import net.torvald.terrarum.utils.RandomWordsName
/**
* Created by minjaesong on 2018-12-08.
@@ -38,7 +39,7 @@ class UIProxyNewRandomGame : UICanvas() {
val ingame = TerrarumIngame(App.batch)
val worldParam = TerrarumIngame.NewWorldParameters(2880, 1350, HQRNG().nextLong())
val worldParam = TerrarumIngame.NewWorldParameters(2880, 1350, HQRNG().nextLong(), RandomWordsName(4))
// val worldParam = TerrarumIngame.NewWorldParameters(2880, 1350, 0x51621D)
// val worldParam = TerrarumIngame.NewWorldParameters(6030, 1800, HQRNG().nextLong()) // small

View File

@@ -2,6 +2,7 @@ package net.torvald.terrarum.modulebasegame.worldgenerator
import net.torvald.terrarum.App
import net.torvald.terrarum.App.printdbg
import net.torvald.terrarum.BlockCodex
import net.torvald.terrarum.gameworld.GameWorld
/**
@@ -30,7 +31,7 @@ object Worldgen {
for (i in jobs.indices) {
printdbg(this, "Worldgen: job #$i")
printdbg(this, "Worldgen: job #${i+1}")
val it = jobs[i]
@@ -38,6 +39,23 @@ object Worldgen {
it.theWork.getDone()
}
// determine spawn point
world.spawnX = 0
world.spawnY = 180
// go up?
if (BlockCodex[world.getTileFromTerrain(world.spawnX, world.spawnY)].isSolid) {
// go up!
while (BlockCodex[world.getTileFromTerrain(world.spawnX, world.spawnY)].isSolid) {
world.spawnY -= 1
}
}
else {
// go down!
while (!BlockCodex[world.getTileFromTerrain(world.spawnX, world.spawnY)].isSolid) {
world.spawnY += 1
}
}
printdbg(this, "Generation job finished")
}

View File

@@ -1,5 +1,6 @@
package net.torvald.terrarum.serialise
import com.badlogic.gdx.graphics.Pixmap
import net.torvald.gdx.graphics.PixmapIO2
import net.torvald.terrarum.*
import net.torvald.terrarum.console.Echo
@@ -13,7 +14,7 @@ import java.util.zip.GZIPOutputStream
/**
* Created by minjaesong on 2021-09-14.
*/
class GameSavingThread(val disk: VirtualDisk, val outFile: File, val ingame: TerrarumIngame, val callback: () -> Unit) : Runnable {
class GameSavingThread(val disk: VirtualDisk, val outFile: File, val ingame: TerrarumIngame, val hasThumbnail: Boolean, val callback: () -> Unit) : Runnable {
/**
* Will happily overwrite existing entry
@@ -29,8 +30,10 @@ class GameSavingThread(val disk: VirtualDisk, val outFile: File, val ingame: Ter
private val actorProgressMultiplier = 1f
override fun run() {
while (!IngameRenderer.fboRGBexportedLatch) {
Thread.sleep(1L)
if (hasThumbnail) {
while (!IngameRenderer.fboRGBexportedLatch) {
Thread.sleep(1L)
}
}
val actorsList = listOf(ingame.actorContainerActive, ingame.actorContainerInactive).flatMap { it.filter { WriteWorld.actorAcceptable(it) } }
@@ -58,12 +61,14 @@ class GameSavingThread(val disk: VirtualDisk, val outFile: File, val ingame: Ter
val meta = DiskEntry(-1, 0, creation_t, time_t, metaContent)
addFile(disk, meta)
if (hasThumbnail) {
PixmapIO2._writeTGA(gzout, IngameRenderer.fboRGBexport, true, true)
IngameRenderer.fboRGBexport.dispose()
PixmapIO2._writeTGA(gzout, IngameRenderer.fboRGBexport, true, true)
IngameRenderer.fboRGBexport.dispose()
val thumbContent = EntryFile(tgaout.toByteArray64())
val thumb = DiskEntry(-2, 0, creation_t, time_t, thumbContent)
addFile(disk, thumb)
val thumbContent = EntryFile(tgaout.toByteArray64())
val thumb = DiskEntry(-2, 0, creation_t, time_t, thumbContent)
addFile(disk, thumb)
}
WriteSavegame.saveProgress += 1f
@@ -157,7 +162,7 @@ class GameSavingThread(val disk: VirtualDisk, val outFile: File, val ingame: Ter
Echo ("${ccW}Game saved with size of $ccG${outFile.length()}$ccW bytes")
IngameRenderer.fboRGBexportedLatch = false
if (hasThumbnail) IngameRenderer.fboRGBexportedLatch = false
WriteSavegame.savingStatus = 255

View File

@@ -1,5 +1,6 @@
package net.torvald.terrarum.serialise
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Pixmap
import net.torvald.terrarum.*
import net.torvald.terrarum.App.printdbg
@@ -27,16 +28,6 @@ object WriteSavegame {
@Volatile var saveProgress = 0f
@Volatile var saveProgressMax = 1f
/**
* Will happily overwrite existing entry
*/
private fun addFile(disk: VirtualDisk, file: DiskEntry) {
disk.entries[file.entryID] = file
file.parentEntryID = 0
val dir = VDUtil.getAsDirectory(disk, 0)
if (!dir.contains(file.entryID)) dir.add(file.entryID)
}
operator fun invoke(disk: VirtualDisk, outFile: File, ingame: TerrarumIngame, callback: () -> Unit = {}) {
savingStatus = 0
@@ -57,9 +48,21 @@ object WriteSavegame {
}
IngameRenderer.fboRGBexportRequested = true
val savingThread = Thread(GameSavingThread(disk, outFile, ingame, callback), "TerrarumBasegameGameSaveThread")
val savingThread = Thread(GameSavingThread(disk, outFile, ingame, true, callback), "TerrarumBasegameGameSaveThread")
savingThread.start()
// it is caller's job to keep the game paused or keep a "save in progress" ui up
// use field 'savingStatus' to know when the saving is done
}
fun immediate(disk: VirtualDisk, outFile: File, ingame: TerrarumIngame, callback: () -> Unit = {}) {
savingStatus = 0
Echo("Immediate save fired")
val savingThread = Thread(GameSavingThread(disk, outFile, ingame, false, callback), "TerrarumBasegameGameSaveThread")
savingThread.start()
// it is caller's job to keep the game paused or keep a "save in progress" ui up
// use field 'savingStatus' to know when the saving is done
@@ -68,6 +71,7 @@ object WriteSavegame {
/**
* Load and setup the game for the first load.
*

View File

@@ -37,7 +37,6 @@ object VDUtil {
}
fun dumpToRealMachine(disk: VirtualDisk, outfile: File) {
if (!outfile.exists()) outfile.createNewFile()
outfile.writeBytes64(disk.serialize().array)
}

View File

@@ -127,7 +127,7 @@ class VirtualDisk(
var isReadOnly: Boolean
set(value) { extraInfoBytes[0] = (extraInfoBytes[0] and 0xFE.toByte()) or value.toBit() }
get() = capacity == 0L || (extraInfoBytes.size > 0 && extraInfoBytes[0].and(1) == 1.toByte())
fun getDiskNameString(charset: Charset) = String(diskName, charset)
fun getDiskNameString(charset: Charset) = diskName.toCanonicalString(charset)
val root: DiskEntry
get() = entries[0]!!

View File

@@ -10,7 +10,6 @@ import net.torvald.terrarum.console.Authenticator
import net.torvald.terrarum.console.CommandInterpreter
import net.torvald.terrarum.gameactors.AVKey
import net.torvald.terrarum.langpack.Lang
import net.torvald.terrarum.modulebasegame.TerrarumIngame
import net.torvald.util.CircularArray
@@ -208,7 +207,7 @@ class ConsoleWindow : UICanvas() {
}
override fun doOpening(delta: Float) {
Terrarum.ingame?.paused = true
Terrarum.ingame?.pause()
/*openingTimeCounter += delta
drawOffY = MovementInterpolator.fastPullOut(openingTimeCounter.toFloat() / openCloseTime.toFloat(),
-height.toFloat(), 0f
@@ -216,7 +215,7 @@ class ConsoleWindow : UICanvas() {
}
override fun doClosing(delta: Float) {
Terrarum.ingame?.paused = false
Terrarum.ingame?.resume()
/*openingTimeCounter += delta
drawOffY = MovementInterpolator.fastPullOut(openingTimeCounter.toFloat() / openCloseTime.toFloat(),
0f, -height.toFloat()
@@ -224,14 +223,14 @@ class ConsoleWindow : UICanvas() {
}
override fun endOpening(delta: Float) {
Terrarum.ingame?.paused = true
Terrarum.ingame?.pause()
drawOffY = 0f
openingTimeCounter = 0f
}
override fun endClosing(delta: Float) {
(Terrarum.ingame as? TerrarumIngame)?.setTooltipMessage(null)
Terrarum.ingame?.paused = false
Terrarum.ingame?.setTooltipMessage(null)
Terrarum.ingame?.resume()
drawOffY = -height.toFloat()
openingTimeCounter = 0f
}

File diff suppressed because it is too large Load Diff