Make Starbound class be singleton again

This commit is contained in:
DBotThePony 2023-09-09 11:34:24 +07:00
parent 528a2e6c59
commit bc9896d327
Signed by: DBot
GPG Key ID: DCC23B5715498507
8 changed files with 40 additions and 50 deletions

View File

@ -26,7 +26,6 @@ import java.util.zip.Inflater
private val LOGGER = LogManager.getLogger() private val LOGGER = LogManager.getLogger()
fun main() { fun main() {
val starbound = Starbound()
LOGGER.info("Running LWJGL ${Version.getVersion()}") LOGGER.info("Running LWJGL ${Version.getVersion()}")
//Thread.sleep(6_000L) //Thread.sleep(6_000L)
@ -34,10 +33,10 @@ fun main() {
val db = BTreeDB(File("F:\\SteamLibrary\\steamapps\\common\\Starbound - Unstable\\storage\\universe\\389760395_938904237_-238610574_5.world")) val db = BTreeDB(File("F:\\SteamLibrary\\steamapps\\common\\Starbound - Unstable\\storage\\universe\\389760395_938904237_-238610574_5.world"))
//val db = BTreeDB(File("world.world")) //val db = BTreeDB(File("world.world"))
val client = StarboundClient(starbound) val client = StarboundClient()
//Starbound.addFilePath(File("./unpacked_assets/")) //Starbound.addFilePath(File("./unpacked_assets/"))
starbound.addPakPath(File("J:\\Steam\\steamapps\\common\\Starbound\\assets\\packed.pak")) Starbound.addPakPath(File("J:\\Steam\\steamapps\\common\\Starbound\\assets\\packed.pak"))
/*for (folder in File("J:\\Steam\\steamapps\\workshop\\content\\211820").list()!!) { /*for (folder in File("J:\\Steam\\steamapps\\workshop\\content\\211820").list()!!) {
val f = File("J:\\Steam\\steamapps\\workshop\\content\\211820\\$folder\\contents.pak") val f = File("J:\\Steam\\steamapps\\workshop\\content\\211820\\$folder\\contents.pak")
@ -49,17 +48,17 @@ fun main() {
//Starbound.addPakPath(File("packed.pak")) //Starbound.addPakPath(File("packed.pak"))
starbound.initializeGame { finished, replaceStatus, status -> Starbound.initializeGame { finished, replaceStatus, status ->
client.putDebugLog(status, replaceStatus) client.putDebugLog(status, replaceStatus)
} }
client.onTermination { client.onTermination {
starbound.terminateLoading = true Starbound.terminateLoading = true
} }
val ent = PlayerEntity(client.world!!) val ent = PlayerEntity(client.world!!)
starbound.onInitialize { Starbound.onInitialize {
var find = 0L var find = 0L
var set = 0L var set = 0L
var parse = 0L var parse = 0L
@ -94,7 +93,7 @@ fun main() {
if (cell == null) { if (cell == null) {
IChunkCell.skip(reader) IChunkCell.skip(reader)
} else { } else {
cell.read(starbound.tilesByID::get, starbound.tileModifiersByID::get, starbound.liquidByID::get, reader) cell.read(Starbound.tilesByID::get, Starbound.tileModifiersByID::get, Starbound.liquidByID::get, reader)
} }
} }
} }
@ -108,7 +107,7 @@ fun main() {
//client.world!!.parallax = Starbound.parallaxAccess["garden"] //client.world!!.parallax = Starbound.parallaxAccess["garden"]
val item = starbound.items.values.random() val item = Starbound.items.values.random()
val rand = java.util.Random() val rand = java.util.Random()
client.world!!.physics.gravity = Vector2d.ZERO client.world!!.physics.gravity = Vector2d.ZERO
@ -124,9 +123,9 @@ fun main() {
// println(Starbound.statusEffects["firecharge"]) // println(Starbound.statusEffects["firecharge"])
starbound.pathStack.push("/animations/dust4") Starbound.pathStack.push("/animations/dust4")
val def = starbound.gson.fromJson(starbound.locate("/animations/dust4/dust4.animation").reader(), AnimationDefinition::class.java) val def = Starbound.gson.fromJson(Starbound.locate("/animations/dust4/dust4.animation").reader(), AnimationDefinition::class.java)
starbound.pathStack.pop() Starbound.pathStack.pop()
val animator = Animator(client.world!!, def) val animator = Animator(client.world!!, def)
@ -134,7 +133,7 @@ fun main() {
// animator.render(client.gl.matrixStack) // animator.render(client.gl.matrixStack)
//} //}
val avatar = Avatar(starbound, UUID.randomUUID()) val avatar = Avatar(Starbound, UUID.randomUUID())
val quest = QuestInstance(avatar, descriptor = QuestDescriptor("floran_mission1")) val quest = QuestInstance(avatar, descriptor = QuestDescriptor("floran_mission1"))
quest.init() quest.init()
quest.start() quest.start()
@ -148,7 +147,7 @@ fun main() {
} }
} }
println(starbound.treasurePools["motherpoptopTreasure"]!!.value.evaluate(Random(), 2.0)) println(Starbound.treasurePools["motherpoptopTreasure"]!!.value.evaluate(Random(), 2.0))
} }
//ent.position += Vector2d(y = 14.0, x = -10.0) //ent.position += Vector2d(y = 14.0, x = -10.0)
@ -234,7 +233,7 @@ fun main() {
} }
while (client.renderFrame()) { while (client.renderFrame()) {
starbound.pollCallbacks() Starbound.pollCallbacks()
//ent.think(client.frameRenderTime) //ent.think(client.frameRenderTime)
//client.camera.pos.x = ent.position.x.toFloat() //client.camera.pos.x = ent.position.x.toFloat()

View File

@ -95,10 +95,14 @@ import kotlin.NoSuchElementException
import kotlin.collections.ArrayList import kotlin.collections.ArrayList
import kotlin.random.Random import kotlin.random.Random
class Starbound : ISBFileLocator { object Starbound : ISBFileLocator {
val strings: Interner<String> = Interner.newWeakInterner()
private val polyfill by lazy { loadInternalScript("polyfill") }
private val logger = LogManager.getLogger() private val logger = LogManager.getLogger()
val pathStack = PathStack(STRINGS) val pathStack = PathStack(strings)
private val _tiles = ObjectRegistry("tiles", TileDefinition::materialName, TileDefinition::materialId) private val _tiles = ObjectRegistry("tiles", TileDefinition::materialName, TileDefinition::materialId)
val tiles = _tiles.view val tiles = _tiles.view
@ -162,9 +166,9 @@ class Starbound : ISBFileLocator {
setFieldNamingPolicy(FieldNamingPolicy.IDENTITY) setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
setPrettyPrinting() setPrettyPrinting()
registerTypeAdapter(InternedStringAdapter(STRINGS)) registerTypeAdapter(InternedStringAdapter(strings))
InternedJsonElementAdapter(STRINGS).also { InternedJsonElementAdapter(strings).also {
registerTypeAdapter(it) registerTypeAdapter(it)
registerTypeAdapter(it.arrays) registerTypeAdapter(it.arrays)
registerTypeAdapter(it.objects) registerTypeAdapter(it.objects)
@ -176,7 +180,7 @@ class Starbound : ISBFileLocator {
registerTypeAdapterFactory(JsonImplementationTypeFactory) registerTypeAdapterFactory(JsonImplementationTypeFactory)
// ImmutableList, ImmutableSet, ImmutableMap // ImmutableList, ImmutableSet, ImmutableMap
registerTypeAdapterFactory(ImmutableCollectionAdapterFactory(STRINGS)) registerTypeAdapterFactory(ImmutableCollectionAdapterFactory(strings))
// ArrayList // ArrayList
registerTypeAdapterFactory(ArrayListAdapterFactory) registerTypeAdapterFactory(ArrayListAdapterFactory)
@ -185,10 +189,10 @@ class Starbound : ISBFileLocator {
registerTypeAdapterFactory(EnumAdapter.Companion) registerTypeAdapterFactory(EnumAdapter.Companion)
// @JsonBuilder // @JsonBuilder
registerTypeAdapterFactory(BuilderAdapter.Factory(STRINGS)) registerTypeAdapterFactory(BuilderAdapter.Factory(strings))
// @JsonFactory // @JsonFactory
registerTypeAdapterFactory(FactoryAdapter.Factory(STRINGS)) registerTypeAdapterFactory(FactoryAdapter.Factory(strings))
// Either<> // Either<>
registerTypeAdapterFactory(EitherTypeAdapter) registerTypeAdapterFactory(EitherTypeAdapter)
@ -216,7 +220,7 @@ class Starbound : ISBFileLocator {
registerTypeAdapterFactory(Json2Function.Companion) registerTypeAdapterFactory(Json2Function.Companion)
// Общее // Общее
registerTypeAdapterFactory(ThingDescription.Factory(STRINGS)) registerTypeAdapterFactory(ThingDescription.Factory(strings))
registerTypeAdapter(EnumAdapter(DamageType::class, default = DamageType.NORMAL)) registerTypeAdapter(EnumAdapter(DamageType::class, default = DamageType.NORMAL))
@ -230,7 +234,7 @@ class Starbound : ISBFileLocator {
registerTypeAdapter(ItemStack.Adapter(this@Starbound)) registerTypeAdapter(ItemStack.Adapter(this@Starbound))
registerTypeAdapterFactory(ItemReference.Factory(STRINGS)) registerTypeAdapterFactory(ItemReference.Factory(strings))
registerTypeAdapterFactory(TreasurePoolDefinition.Companion) registerTypeAdapterFactory(TreasurePoolDefinition.Companion)
registerTypeAdapterFactory(with(RegistryReferenceFactory()) { registerTypeAdapterFactory(with(RegistryReferenceFactory()) {
@ -1168,20 +1172,6 @@ class Starbound : ISBFileLocator {
} }
} }
} }
companion object {
/**
* Глобальный [Interner] для [String]
*
* Так как нет смысла иметь множество [Interner]'ов для [String],
* а так же в силу его поточной безопасности,
* данный [Interner] доступен глобально
*/
@JvmField
val STRINGS: Interner<String> = Interner.newWeakInterner()
private val polyfill by lazy { loadInternalScript("polyfill") }
}
} }
private class StringInterner(private val segmentBits: Int) : Interner<String>, Hash.Strategy<Any> { private class StringInterner(private val segmentBits: Int) : Interner<String>, Hash.Strategy<Any> {

View File

@ -40,7 +40,7 @@ import java.util.concurrent.locks.LockSupport
import kotlin.collections.ArrayList import kotlin.collections.ArrayList
import kotlin.math.roundToInt import kotlin.math.roundToInt
class StarboundClient(val starbound: Starbound) : Closeable { class StarboundClient : Closeable {
val time = PausableTimeSource(JVMTimeSource.INSTANCE) val time = PausableTimeSource(JVMTimeSource.INSTANCE)
val window: Long val window: Long
val camera = Camera(this) val camera = Camera(this)
@ -354,7 +354,7 @@ class StarboundClient(val starbound: Starbound) : Closeable {
updateViewportParams() updateViewportParams()
val layers = LayeredRenderer() val layers = LayeredRenderer()
if (frameRenderTime != 0.0 && starbound.initialized) if (frameRenderTime != 0.0 && Starbound.initialized)
world.think(frameRenderTime) world.think(frameRenderTime)
gl.clearColor = RGBAColor.SLATE_GRAY gl.clearColor = RGBAColor.SLATE_GRAY

View File

@ -6,6 +6,7 @@ import org.apache.logging.log4j.LogManager
import org.lwjgl.opengl.GL import org.lwjgl.opengl.GL
import org.lwjgl.opengl.GL46.* import org.lwjgl.opengl.GL46.*
import org.lwjgl.opengl.GLCapabilities import org.lwjgl.opengl.GLCapabilities
import ru.dbotthepony.kstarbound.Starbound
import ru.dbotthepony.kstarbound.client.StarboundClient import ru.dbotthepony.kstarbound.client.StarboundClient
import ru.dbotthepony.kstarbound.client.freetype.FreeType import ru.dbotthepony.kstarbound.client.freetype.FreeType
import ru.dbotthepony.kstarbound.client.freetype.InvalidArgumentException import ru.dbotthepony.kstarbound.client.freetype.InvalidArgumentException
@ -441,7 +442,7 @@ class GLStateTracker(val client: StarboundClient) {
.build() .build()
private val missingTexture: GLTexture2D by lazy { private val missingTexture: GLTexture2D by lazy {
newTexture(missingTexturePath).upload(client.starbound.readDirect(missingTexturePath), GL_RGBA, GL_RGBA).generateMips().also { newTexture(missingTexturePath).upload(Starbound.readDirect(missingTexturePath), GL_RGBA, GL_RGBA).generateMips().also {
it.textureMinFilter = GL_NEAREST it.textureMinFilter = GL_NEAREST
it.textureMagFilter = GL_NEAREST it.textureMagFilter = GL_NEAREST
} }
@ -454,11 +455,11 @@ class GLStateTracker(val client: StarboundClient) {
return named2DTextures0.get(path) { return named2DTextures0.get(path) {
named2DTextures1.get(it) { named2DTextures1.get(it) {
if (!client.starbound.exists(it)) { if (!Starbound.exists(it)) {
LOGGER.error("Texture {} is missing! Falling back to {}", it, missingTexturePath) LOGGER.error("Texture {} is missing! Falling back to {}", it, missingTexturePath)
missingTexture missingTexture
} else { } else {
newTexture(it).upload(client.starbound.imageData(it)).generateMips().also { newTexture(it).upload(Starbound.imageData(it)).generateMips().also {
it.textureMinFilter = GL_NEAREST it.textureMinFilter = GL_NEAREST
it.textureMagFilter = GL_NEAREST it.textureMagFilter = GL_NEAREST
} }

View File

@ -3,6 +3,7 @@ package ru.dbotthepony.kstarbound.client.render
import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.LogManager
import org.lwjgl.opengl.GL46.* import org.lwjgl.opengl.GL46.*
import ru.dbotthepony.kstarbound.PIXELS_IN_STARBOUND_UNITf import ru.dbotthepony.kstarbound.PIXELS_IN_STARBOUND_UNITf
import ru.dbotthepony.kstarbound.Starbound
import ru.dbotthepony.kstarbound.client.StarboundClient import ru.dbotthepony.kstarbound.client.StarboundClient
import ru.dbotthepony.kstarbound.client.gl.* import ru.dbotthepony.kstarbound.client.gl.*
import ru.dbotthepony.kstarbound.client.gl.shader.GLTileProgram import ru.dbotthepony.kstarbound.client.gl.shader.GLTileProgram
@ -31,14 +32,14 @@ class TileRenderers(val client: StarboundClient) {
fun getMaterialRenderer(defName: String): TileRenderer { fun getMaterialRenderer(defName: String): TileRenderer {
return matCache.computeIfAbsent(defName) { return matCache.computeIfAbsent(defName) {
val def = client.starbound.tiles[defName] // TODO: Пустой рендерер val def = Starbound.tiles[defName] // TODO: Пустой рендерер
return@computeIfAbsent TileRenderer(this, def!!.value) return@computeIfAbsent TileRenderer(this, def!!.value)
} }
} }
fun getModifierRenderer(defName: String): TileRenderer { fun getModifierRenderer(defName: String): TileRenderer {
return modCache.computeIfAbsent(defName) { return modCache.computeIfAbsent(defName) {
val def = client.starbound.tileModifiers[defName] // TODO: Пустой рендерер val def = Starbound.tileModifiers[defName] // TODO: Пустой рендерер
return@computeIfAbsent TileRenderer(this, def!!.value) return@computeIfAbsent TileRenderer(this, def!!.value)
} }
} }

View File

@ -32,8 +32,8 @@ import java.nio.ByteOrder
import kotlin.system.exitProcess import kotlin.system.exitProcess
@Suppress("unused") @Suppress("unused")
class LuaState private constructor(private val pointer: Pointer, val stringInterner: Interner<String> = Starbound.STRINGS) : Closeable { class LuaState private constructor(private val pointer: Pointer, val stringInterner: Interner<String> = Starbound.strings) : Closeable {
constructor(stringInterner: Interner<String> = Starbound.STRINGS) : this(LuaJNR.INSTANCE.luaL_newstate() ?: throw OutOfMemoryError("Unable to allocate new LuaState"), stringInterner) { constructor(stringInterner: Interner<String> = Starbound.strings) : this(LuaJNR.INSTANCE.luaL_newstate() ?: throw OutOfMemoryError("Unable to allocate new LuaState"), stringInterner) {
val pointer = this.pointer val pointer = this.pointer
val panic = ClosureManager.getInstance().newClosure( val panic = ClosureManager.getInstance().newClosure(
{ {

View File

@ -166,7 +166,7 @@ class SBPattern private constructor(
throw IllegalArgumentException("Malformed pattern string: $raw") throw IllegalArgumentException("Malformed pattern string: $raw")
} }
pieces.add(Piece(name = Starbound.STRINGS.intern(raw.substring(open + 1, closing)))) pieces.add(Piece(name = Starbound.strings.intern(raw.substring(open + 1, closing))))
i = closing + 1 i = closing + 1
} }
} }

View File

@ -10,14 +10,13 @@ import ru.dbotthepony.kstarbound.Starbound
import java.util.* import java.util.*
import java.util.function.Consumer import java.util.function.Consumer
import java.util.stream.Stream import java.util.stream.Stream
import kotlin.collections.ArrayList
fun String.sbIntern(): String { fun String.sbIntern(): String {
return Starbound.STRINGS.intern(this) return Starbound.strings.intern(this)
} }
fun String.sbIntern2(): String { fun String.sbIntern2(): String {
return Starbound.STRINGS.intern(this.intern()) return Starbound.strings.intern(this.intern())
} }
fun traverseJsonPath(path: String?, element: JsonElement?): JsonElement? { fun traverseJsonPath(path: String?, element: JsonElement?): JsonElement? {