Skip to content

Commit

Permalink
fix: Don't pass world in CopyToInstances, we can get it from the enti…
Browse files Browse the repository at this point in the history
…ty in decodeComponentsTo
  • Loading branch information
0ffz committed Oct 28, 2024
1 parent 364b694 commit 33e9b48
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@ package com.mineinabyss.geary.prefabs.configuration.components

import com.mineinabyss.geary.datatypes.Component
import com.mineinabyss.geary.datatypes.Entity
import com.mineinabyss.geary.modules.Geary
import com.mineinabyss.geary.serialization.SerializableComponents
import com.mineinabyss.geary.serialization.serializers.SerializedComponents
import com.mineinabyss.geary.serialization.setAllPersisting
import kotlinx.serialization.Contextual
import kotlinx.serialization.Polymorphic
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
Expand All @@ -23,31 +21,20 @@ import kotlinx.serialization.Serializable
data class CopyToInstances(
private val temporary: SerializedComponents? = null,
private val persisting: SerializedComponents? = null,
private val world: @Contextual Geary,
) {
@Serializable
private data class DeepCopy(
val temporary: List<@Polymorphic Component>?,
val persisting: List<@Polymorphic Component>?
val persisting: List<@Polymorphic Component>?,
)

val formats get() = world.getAddon(SerializableComponents).formats
fun decodeComponentsTo(entity: Entity) {
val binaryFormat = entity.world.getAddon(SerializableComponents).formats.binaryFormat

// This is the safest and cleanest way to deep-copy, even if a little performance intense.
private val serializedComponents by lazy {
formats.binaryFormat.encodeToByteArray(
DeepCopy.serializer(),
DeepCopy(temporary, persisting)
)
}
// This is the safest and cleanest way to deep-copy, even if a little performance intense.
val encoded = binaryFormat.encodeToByteArray(DeepCopy.serializer(), DeepCopy(temporary, persisting))
val (instance, persist) = binaryFormat.decodeFromByteArray(DeepCopy.serializer(), encoded)

private fun getDeepCopied() = formats.binaryFormat.decodeFromByteArray(
DeepCopy.serializer(), serializedComponents
)

fun decodeComponentsTo(entity: Entity) {
val (instance, persist) = getDeepCopied()
//order of addition specifies that persisting components should override all
if (instance != null) {
entity.setAll(instance, override = false)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ class CopyToInstancesTest : GearyTest() {
CopyToInstances(
temporary = listOf(42),
persisting = listOf("Hello world"),
world = world,
)
)
addRelation<NoInherit, CopyToInstances>()
Expand Down

0 comments on commit 33e9b48

Please sign in to comment.