From bc9896d327a6963c6224037a4aa9d496d5c0dd76 Mon Sep 17 00:00:00 2001 From: DBotThePony Date: Sat, 9 Sep 2023 11:34:24 +0700 Subject: [PATCH] Make Starbound class be singleton again --- .../kotlin/ru/dbotthepony/kstarbound/Main.kt | 27 +++++++------- .../ru/dbotthepony/kstarbound/Starbound.kt | 36 +++++++------------ .../kstarbound/client/StarboundClient.kt | 4 +-- .../kstarbound/client/gl/GLStateTracker.kt | 7 ++-- .../kstarbound/client/render/TileRenderer.kt | 5 +-- .../ru/dbotthepony/kstarbound/lua/LuaState.kt | 4 +-- .../dbotthepony/kstarbound/util/SBPattern.kt | 2 +- .../ru/dbotthepony/kstarbound/util/Utils.kt | 5 ++- 8 files changed, 40 insertions(+), 50 deletions(-) diff --git a/src/main/kotlin/ru/dbotthepony/kstarbound/Main.kt b/src/main/kotlin/ru/dbotthepony/kstarbound/Main.kt index ccf71e29..ee2cc812 100644 --- a/src/main/kotlin/ru/dbotthepony/kstarbound/Main.kt +++ b/src/main/kotlin/ru/dbotthepony/kstarbound/Main.kt @@ -26,7 +26,6 @@ import java.util.zip.Inflater private val LOGGER = LogManager.getLogger() fun main() { - val starbound = Starbound() LOGGER.info("Running LWJGL ${Version.getVersion()}") //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("world.world")) - val client = StarboundClient(starbound) + val client = StarboundClient() //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()!!) { val f = File("J:\\Steam\\steamapps\\workshop\\content\\211820\\$folder\\contents.pak") @@ -49,17 +48,17 @@ fun main() { //Starbound.addPakPath(File("packed.pak")) - starbound.initializeGame { finished, replaceStatus, status -> + Starbound.initializeGame { finished, replaceStatus, status -> client.putDebugLog(status, replaceStatus) } client.onTermination { - starbound.terminateLoading = true + Starbound.terminateLoading = true } val ent = PlayerEntity(client.world!!) - starbound.onInitialize { + Starbound.onInitialize { var find = 0L var set = 0L var parse = 0L @@ -94,7 +93,7 @@ fun main() { if (cell == null) { IChunkCell.skip(reader) } 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"] - val item = starbound.items.values.random() + val item = Starbound.items.values.random() val rand = java.util.Random() client.world!!.physics.gravity = Vector2d.ZERO @@ -124,9 +123,9 @@ fun main() { // println(Starbound.statusEffects["firecharge"]) - starbound.pathStack.push("/animations/dust4") - val def = starbound.gson.fromJson(starbound.locate("/animations/dust4/dust4.animation").reader(), AnimationDefinition::class.java) - starbound.pathStack.pop() + Starbound.pathStack.push("/animations/dust4") + val def = Starbound.gson.fromJson(Starbound.locate("/animations/dust4/dust4.animation").reader(), AnimationDefinition::class.java) + Starbound.pathStack.pop() val animator = Animator(client.world!!, def) @@ -134,7 +133,7 @@ fun main() { // 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")) quest.init() 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) @@ -234,7 +233,7 @@ fun main() { } while (client.renderFrame()) { - starbound.pollCallbacks() + Starbound.pollCallbacks() //ent.think(client.frameRenderTime) //client.camera.pos.x = ent.position.x.toFloat() diff --git a/src/main/kotlin/ru/dbotthepony/kstarbound/Starbound.kt b/src/main/kotlin/ru/dbotthepony/kstarbound/Starbound.kt index 997026f1..d5cccebe 100644 --- a/src/main/kotlin/ru/dbotthepony/kstarbound/Starbound.kt +++ b/src/main/kotlin/ru/dbotthepony/kstarbound/Starbound.kt @@ -95,10 +95,14 @@ import kotlin.NoSuchElementException import kotlin.collections.ArrayList import kotlin.random.Random -class Starbound : ISBFileLocator { +object Starbound : ISBFileLocator { + val strings: Interner = Interner.newWeakInterner() + + private val polyfill by lazy { loadInternalScript("polyfill") } + private val logger = LogManager.getLogger() - val pathStack = PathStack(STRINGS) + val pathStack = PathStack(strings) private val _tiles = ObjectRegistry("tiles", TileDefinition::materialName, TileDefinition::materialId) val tiles = _tiles.view @@ -162,9 +166,9 @@ class Starbound : ISBFileLocator { setFieldNamingPolicy(FieldNamingPolicy.IDENTITY) setPrettyPrinting() - registerTypeAdapter(InternedStringAdapter(STRINGS)) + registerTypeAdapter(InternedStringAdapter(strings)) - InternedJsonElementAdapter(STRINGS).also { + InternedJsonElementAdapter(strings).also { registerTypeAdapter(it) registerTypeAdapter(it.arrays) registerTypeAdapter(it.objects) @@ -176,7 +180,7 @@ class Starbound : ISBFileLocator { registerTypeAdapterFactory(JsonImplementationTypeFactory) // ImmutableList, ImmutableSet, ImmutableMap - registerTypeAdapterFactory(ImmutableCollectionAdapterFactory(STRINGS)) + registerTypeAdapterFactory(ImmutableCollectionAdapterFactory(strings)) // ArrayList registerTypeAdapterFactory(ArrayListAdapterFactory) @@ -185,10 +189,10 @@ class Starbound : ISBFileLocator { registerTypeAdapterFactory(EnumAdapter.Companion) // @JsonBuilder - registerTypeAdapterFactory(BuilderAdapter.Factory(STRINGS)) + registerTypeAdapterFactory(BuilderAdapter.Factory(strings)) // @JsonFactory - registerTypeAdapterFactory(FactoryAdapter.Factory(STRINGS)) + registerTypeAdapterFactory(FactoryAdapter.Factory(strings)) // Either<> registerTypeAdapterFactory(EitherTypeAdapter) @@ -216,7 +220,7 @@ class Starbound : ISBFileLocator { registerTypeAdapterFactory(Json2Function.Companion) // Общее - registerTypeAdapterFactory(ThingDescription.Factory(STRINGS)) + registerTypeAdapterFactory(ThingDescription.Factory(strings)) registerTypeAdapter(EnumAdapter(DamageType::class, default = DamageType.NORMAL)) @@ -230,7 +234,7 @@ class Starbound : ISBFileLocator { registerTypeAdapter(ItemStack.Adapter(this@Starbound)) - registerTypeAdapterFactory(ItemReference.Factory(STRINGS)) + registerTypeAdapterFactory(ItemReference.Factory(strings)) registerTypeAdapterFactory(TreasurePoolDefinition.Companion) registerTypeAdapterFactory(with(RegistryReferenceFactory()) { @@ -1168,20 +1172,6 @@ class Starbound : ISBFileLocator { } } } - - companion object { - /** - * Глобальный [Interner] для [String] - * - * Так как нет смысла иметь множество [Interner]'ов для [String], - * а так же в силу его поточной безопасности, - * данный [Interner] доступен глобально - */ - @JvmField - val STRINGS: Interner = Interner.newWeakInterner() - - private val polyfill by lazy { loadInternalScript("polyfill") } - } } private class StringInterner(private val segmentBits: Int) : Interner, Hash.Strategy { diff --git a/src/main/kotlin/ru/dbotthepony/kstarbound/client/StarboundClient.kt b/src/main/kotlin/ru/dbotthepony/kstarbound/client/StarboundClient.kt index 32793d52..43c6579e 100644 --- a/src/main/kotlin/ru/dbotthepony/kstarbound/client/StarboundClient.kt +++ b/src/main/kotlin/ru/dbotthepony/kstarbound/client/StarboundClient.kt @@ -40,7 +40,7 @@ import java.util.concurrent.locks.LockSupport import kotlin.collections.ArrayList import kotlin.math.roundToInt -class StarboundClient(val starbound: Starbound) : Closeable { +class StarboundClient : Closeable { val time = PausableTimeSource(JVMTimeSource.INSTANCE) val window: Long val camera = Camera(this) @@ -354,7 +354,7 @@ class StarboundClient(val starbound: Starbound) : Closeable { updateViewportParams() val layers = LayeredRenderer() - if (frameRenderTime != 0.0 && starbound.initialized) + if (frameRenderTime != 0.0 && Starbound.initialized) world.think(frameRenderTime) gl.clearColor = RGBAColor.SLATE_GRAY diff --git a/src/main/kotlin/ru/dbotthepony/kstarbound/client/gl/GLStateTracker.kt b/src/main/kotlin/ru/dbotthepony/kstarbound/client/gl/GLStateTracker.kt index 36f06827..2e229843 100644 --- a/src/main/kotlin/ru/dbotthepony/kstarbound/client/gl/GLStateTracker.kt +++ b/src/main/kotlin/ru/dbotthepony/kstarbound/client/gl/GLStateTracker.kt @@ -6,6 +6,7 @@ import org.apache.logging.log4j.LogManager import org.lwjgl.opengl.GL import org.lwjgl.opengl.GL46.* import org.lwjgl.opengl.GLCapabilities +import ru.dbotthepony.kstarbound.Starbound import ru.dbotthepony.kstarbound.client.StarboundClient import ru.dbotthepony.kstarbound.client.freetype.FreeType import ru.dbotthepony.kstarbound.client.freetype.InvalidArgumentException @@ -441,7 +442,7 @@ class GLStateTracker(val client: StarboundClient) { .build() 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.textureMagFilter = GL_NEAREST } @@ -454,11 +455,11 @@ class GLStateTracker(val client: StarboundClient) { return named2DTextures0.get(path) { named2DTextures1.get(it) { - if (!client.starbound.exists(it)) { + if (!Starbound.exists(it)) { LOGGER.error("Texture {} is missing! Falling back to {}", it, missingTexturePath) missingTexture } else { - newTexture(it).upload(client.starbound.imageData(it)).generateMips().also { + newTexture(it).upload(Starbound.imageData(it)).generateMips().also { it.textureMinFilter = GL_NEAREST it.textureMagFilter = GL_NEAREST } diff --git a/src/main/kotlin/ru/dbotthepony/kstarbound/client/render/TileRenderer.kt b/src/main/kotlin/ru/dbotthepony/kstarbound/client/render/TileRenderer.kt index 002f99e2..c5583e1d 100644 --- a/src/main/kotlin/ru/dbotthepony/kstarbound/client/render/TileRenderer.kt +++ b/src/main/kotlin/ru/dbotthepony/kstarbound/client/render/TileRenderer.kt @@ -3,6 +3,7 @@ package ru.dbotthepony.kstarbound.client.render import org.apache.logging.log4j.LogManager import org.lwjgl.opengl.GL46.* import ru.dbotthepony.kstarbound.PIXELS_IN_STARBOUND_UNITf +import ru.dbotthepony.kstarbound.Starbound import ru.dbotthepony.kstarbound.client.StarboundClient import ru.dbotthepony.kstarbound.client.gl.* import ru.dbotthepony.kstarbound.client.gl.shader.GLTileProgram @@ -31,14 +32,14 @@ class TileRenderers(val client: StarboundClient) { fun getMaterialRenderer(defName: String): TileRenderer { return matCache.computeIfAbsent(defName) { - val def = client.starbound.tiles[defName] // TODO: Пустой рендерер + val def = Starbound.tiles[defName] // TODO: Пустой рендерер return@computeIfAbsent TileRenderer(this, def!!.value) } } fun getModifierRenderer(defName: String): TileRenderer { return modCache.computeIfAbsent(defName) { - val def = client.starbound.tileModifiers[defName] // TODO: Пустой рендерер + val def = Starbound.tileModifiers[defName] // TODO: Пустой рендерер return@computeIfAbsent TileRenderer(this, def!!.value) } } diff --git a/src/main/kotlin/ru/dbotthepony/kstarbound/lua/LuaState.kt b/src/main/kotlin/ru/dbotthepony/kstarbound/lua/LuaState.kt index 6bed052b..3e6f0cb3 100644 --- a/src/main/kotlin/ru/dbotthepony/kstarbound/lua/LuaState.kt +++ b/src/main/kotlin/ru/dbotthepony/kstarbound/lua/LuaState.kt @@ -32,8 +32,8 @@ import java.nio.ByteOrder import kotlin.system.exitProcess @Suppress("unused") -class LuaState private constructor(private val pointer: Pointer, val stringInterner: Interner = Starbound.STRINGS) : Closeable { - constructor(stringInterner: Interner = Starbound.STRINGS) : this(LuaJNR.INSTANCE.luaL_newstate() ?: throw OutOfMemoryError("Unable to allocate new LuaState"), stringInterner) { +class LuaState private constructor(private val pointer: Pointer, val stringInterner: Interner = Starbound.strings) : Closeable { + constructor(stringInterner: Interner = Starbound.strings) : this(LuaJNR.INSTANCE.luaL_newstate() ?: throw OutOfMemoryError("Unable to allocate new LuaState"), stringInterner) { val pointer = this.pointer val panic = ClosureManager.getInstance().newClosure( { diff --git a/src/main/kotlin/ru/dbotthepony/kstarbound/util/SBPattern.kt b/src/main/kotlin/ru/dbotthepony/kstarbound/util/SBPattern.kt index bc4f721d..1a2e2bb9 100644 --- a/src/main/kotlin/ru/dbotthepony/kstarbound/util/SBPattern.kt +++ b/src/main/kotlin/ru/dbotthepony/kstarbound/util/SBPattern.kt @@ -166,7 +166,7 @@ class SBPattern private constructor( 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 } } diff --git a/src/main/kotlin/ru/dbotthepony/kstarbound/util/Utils.kt b/src/main/kotlin/ru/dbotthepony/kstarbound/util/Utils.kt index 90bef9f2..4dad612a 100644 --- a/src/main/kotlin/ru/dbotthepony/kstarbound/util/Utils.kt +++ b/src/main/kotlin/ru/dbotthepony/kstarbound/util/Utils.kt @@ -10,14 +10,13 @@ import ru.dbotthepony.kstarbound.Starbound import java.util.* import java.util.function.Consumer import java.util.stream.Stream -import kotlin.collections.ArrayList fun String.sbIntern(): String { - return Starbound.STRINGS.intern(this) + return Starbound.strings.intern(this) } fun String.sbIntern2(): String { - return Starbound.STRINGS.intern(this.intern()) + return Starbound.strings.intern(this.intern()) } fun traverseJsonPath(path: String?, element: JsonElement?): JsonElement? {