(OperatorSideEffect.ConsumeMedia(this.mediaCost))
val image2 = image.copy(stack = stack, opsConsumed = image.opsConsumed + result.opCount)
return OperationResult(image2, sideEffects, continuation, HexEvalSounds.NORMAL_EXECUTE)
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/castables/OperationAction.kt b/Common/src/main/java/at/petrak/hexcasting/api/casting/castables/OperationAction.kt
index 1e9a39f80f..11a0b9d5e1 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/castables/OperationAction.kt
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/castables/OperationAction.kt
@@ -10,15 +10,20 @@ import at.petrak.hexcasting.api.casting.mishaps.MishapInvalidOperatorArgs
import at.petrak.hexcasting.common.lib.hex.HexArithmetics
/**
- * Represents an Operator with the give pattern as its identifier, a special type of Action that calls a different function depending on the type of its arguments.
- * This exists so that addons can easily define their own overloads to patterns like addition, subtraction, etc.
+ * Represents an Operator with the give pattern as its identifier, a special type of Action that
+ * calls a different function depending on the type of its arguments. This exists so that addons can
+ * easily define their own overloads to patterns like addition, subtraction, etc.
*/
data class OperationAction(val pattern: HexPattern) : Action {
- override fun operate(env: CastingEnvironment, image: CastingImage, continuation: SpellContinuation): OperationResult {
+ override fun operate(
+ env: CastingEnvironment,
+ image: CastingImage,
+ continuation: SpellContinuation
+ ): OperationResult {
return try {
HexArithmetics.getEngine().run(pattern, env, image, continuation)
} catch (e: NoOperatorCandidatesException) {
throw MishapInvalidOperatorArgs(e.args)
}
}
-}
\ No newline at end of file
+}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/castables/SpecialHandler.java b/Common/src/main/java/at/petrak/hexcasting/api/casting/castables/SpecialHandler.java
index 14a64879e9..4181abb1ac 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/castables/SpecialHandler.java
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/castables/SpecialHandler.java
@@ -2,40 +2,41 @@
import at.petrak.hexcasting.api.casting.eval.CastingEnvironment;
import at.petrak.hexcasting.api.casting.math.HexPattern;
+
import net.minecraft.network.chat.Component;
+
import org.jetbrains.annotations.Nullable;
/**
* Special handling of a pattern. Before checking any of the normal angle-signature based patterns,
- * a given pattern is run by all of these special handlers patterns. If none of them return non-null,
- * then its signature is checked.
- *
- * In the base mod, this is used for number patterns and Bookkeeper's Gambit.
- *
- * There's a separation between the special handlers and their factories so we never have to use
- * {@link Action} instances on the client. We can have SpecialHandlers on the client though because they're just
- * wrappers.
+ * a given pattern is run by all of these special handlers patterns. If none of them return
+ * non-null, then its signature is checked.
+ *
+ *
In the base mod, this is used for number patterns and Bookkeeper's Gambit.
+ *
+ *
There's a separation between the special handlers and their factories so we never have to use
+ * {@link Action} instances on the client. We can have SpecialHandlers on the client though because
+ * they're just wrappers.
*/
public interface SpecialHandler {
/**
* Convert this to an action, for modification of the stack and state.
- *
- * This is called on the SERVER-SIDE ONLY.
+ *
+ *
This is called on the SERVER-SIDE ONLY.
*/
Action act();
- /**
- * Get the name of this handler.
- */
+ /** Get the name of this handler. */
Component getName();
/**
* Given a pattern, possibly make up the special handler from it.
- *
- * This is what goes in the registry! Think of it like BlockEntityType vs BlockEntity.
+ *
+ *
This is what goes in the registry! Think of it like BlockEntityType vs BlockEntity.
*/
@FunctionalInterface
public interface Factory {
- @Nullable T tryMatch(HexPattern pattern, CastingEnvironment env);
+ @Nullable
+ T tryMatch(HexPattern pattern, CastingEnvironment env);
}
}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/castables/SpellAction.kt b/Common/src/main/java/at/petrak/hexcasting/api/casting/castables/SpellAction.kt
index fcf17d08d0..34911d721b 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/castables/SpellAction.kt
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/castables/SpellAction.kt
@@ -20,22 +20,24 @@ interface SpellAction : Action {
fun awardsCastingStat(ctx: CastingEnvironment): Boolean = true
- fun execute(
- args: List,
- env: CastingEnvironment
- ): Result
+ fun execute(args: List, env: CastingEnvironment): Result
fun executeWithUserdata(
- args: List, env: CastingEnvironment, userData: CompoundTag
+ args: List,
+ env: CastingEnvironment,
+ userData: CompoundTag
): Result {
return this.execute(args, env)
}
- override fun operate(env: CastingEnvironment, image: CastingImage, continuation: SpellContinuation): OperationResult {
+ override fun operate(
+ env: CastingEnvironment,
+ image: CastingImage,
+ continuation: SpellContinuation
+ ): OperationResult {
val stack = image.stack.toMutableList()
- if (this.argc > stack.size)
- throw MishapNotEnoughArgs(this.argc, stack.size)
+ if (this.argc > stack.size) throw MishapNotEnoughArgs(this.argc, stack.size)
val args = stack.takeLast(this.argc)
for (_i in 0 until this.argc) stack.removeLast()
@@ -45,27 +47,29 @@ interface SpellAction : Action {
val sideEffects = mutableListOf()
- if (env.extractMedia(result.cost, true) > 0)
- throw MishapNotEnoughMedia(result.cost)
- if (result.cost > 0)
- sideEffects.add(OperatorSideEffect.ConsumeMedia(result.cost))
+ if (env.extractMedia(result.cost, true) > 0) throw MishapNotEnoughMedia(result.cost)
+ if (result.cost > 0) sideEffects.add(OperatorSideEffect.ConsumeMedia(result.cost))
sideEffects.add(
OperatorSideEffect.AttemptSpell(
- result.effect,
- this.hasCastingSound(env),
- this.awardsCastingStat(env)
- )
- )
+ result.effect, this.hasCastingSound(env), this.awardsCastingStat(env)))
- for (spray in result.particles)
- sideEffects.add(OperatorSideEffect.Particles(spray))
+ for (spray in result.particles) sideEffects.add(OperatorSideEffect.Particles(spray))
- val image2 = image.copy(stack = stack, opsConsumed = image.opsConsumed + result.opCount, userData = userDataMut)
+ val image2 =
+ image.copy(
+ stack = stack,
+ opsConsumed = image.opsConsumed + result.opCount,
+ userData = userDataMut)
val sound = if (this.hasCastingSound(env)) HexEvalSounds.SPELL else HexEvalSounds.MUTE
return OperationResult(image2, sideEffects, continuation, sound)
}
- data class Result(val effect: RenderedSpell, val cost: Long, val particles: List, val opCount: Long = 1)
+ data class Result(
+ val effect: RenderedSpell,
+ val cost: Long,
+ val particles: List,
+ val opCount: Long = 1
+ )
}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/circles/BlockEntityAbstractImpetus.java b/Common/src/main/java/at/petrak/hexcasting/api/casting/circles/BlockEntityAbstractImpetus.java
index ac8bf92d0d..a8e023512c 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/circles/BlockEntityAbstractImpetus.java
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/circles/BlockEntityAbstractImpetus.java
@@ -7,7 +7,9 @@
import at.petrak.hexcasting.api.utils.MediaHelper;
import at.petrak.hexcasting.common.items.magic.ItemCreativeUnlocker;
import at.petrak.hexcasting.common.lib.HexItems;
+
import com.mojang.datafixers.util.Pair;
+
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
@@ -28,6 +30,7 @@
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.phys.AABB;
+
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
@@ -36,39 +39,35 @@
/**
* Default impl for an impetus, not tecnically necessary but I'm exposing it for ease of use
- *
- * This does assume a great deal so you might have to re-implement a lot of this yourself if you
+ *
+ *
This does assume a great deal so you might have to re-implement a lot of this yourself if you
* wanna do something wild and new
*/
-public abstract class BlockEntityAbstractImpetus extends HexBlockEntity implements WorldlyContainer {
+public abstract class BlockEntityAbstractImpetus extends HexBlockEntity
+ implements WorldlyContainer {
private static final DecimalFormat DUST_AMOUNT = new DecimalFormat("###,###.##");
private static final long MAX_CAPACITY = 9_000_000_000_000_000_000L;
- public static final String
- TAG_EXECUTION_STATE = "executor",
- TAG_MEDIA = "media",
- TAG_ERROR_MSG = "errorMsg",
- TAG_ERROR_DISPLAY = "errorDisplay",
- TAG_PIGMENT = "pigment";
+ public static final String TAG_EXECUTION_STATE = "executor",
+ TAG_MEDIA = "media",
+ TAG_ERROR_MSG = "errorMsg",
+ TAG_ERROR_DISPLAY = "errorDisplay",
+ TAG_PIGMENT = "pigment";
// We might try to load the executor in loadModData when the level doesn't exist yet,
// so save the tag and load it lazy
@Nullable CompoundTag lazyExecutionState;
- @Nullable
- protected CircleExecutionState executionState;
+ @Nullable protected CircleExecutionState executionState;
protected long media = 0;
// these are null together
- @Nullable
- protected Component displayMsg = null;
- @Nullable
- protected ItemStack displayItem = null;
- @Nullable
- protected FrozenPigment pigment = null;
-
+ @Nullable protected Component displayMsg = null;
+ @Nullable protected ItemStack displayItem = null;
+ @Nullable protected FrozenPigment pigment = null;
- public BlockEntityAbstractImpetus(BlockEntityType> pType, BlockPos pWorldPosition, BlockState pBlockState) {
+ public BlockEntityAbstractImpetus(
+ BlockEntityType> pType, BlockPos pWorldPosition, BlockState pBlockState) {
super(pType, pWorldPosition, pBlockState);
}
@@ -104,16 +103,16 @@ public void postPrint(Component printDisplay) {
// Pull this out because we may need to call it both on startup and halfway thru
public void postNoExits(BlockPos pos) {
this.postDisplay(
- Component.translatable("hexcasting.tooltip.circle.no_exit",
- Component.literal(pos.toShortString()).withStyle(ChatFormatting.RED)),
- new ItemStack(Items.OAK_SIGN));
+ Component.translatable(
+ "hexcasting.tooltip.circle.no_exit",
+ Component.literal(pos.toShortString()).withStyle(ChatFormatting.RED)),
+ new ItemStack(Items.OAK_SIGN));
}
- //region execution
+ // region execution
public void tickExecution() {
- if (this.level == null)
- return;
+ if (this.level == null) return;
this.setChanged();
@@ -128,38 +127,35 @@ public void tickExecution() {
this.endExecution();
this.executionState = null;
} else
- this.level.scheduleTick(this.getBlockPos(), this.getBlockState().getBlock(), state.getTickSpeed());
+ this.level.scheduleTick(
+ this.getBlockPos(), this.getBlockState().getBlock(), state.getTickSpeed());
}
public void endExecution() {
- if (this.executionState == null)
- return;
+ if (this.executionState == null) return;
this.executionState.endExecution(this);
}
- /**
- * ONLY CALL THIS WHEN YOU KNOW THE WORLD EXISTS AND ON THE SERVER, lazy-loads it
- */
+ /** ONLY CALL THIS WHEN YOU KNOW THE WORLD EXISTS AND ON THE SERVER, lazy-loads it */
public @Nullable CircleExecutionState getExecutionState() {
if (this.level == null) {
- throw new IllegalStateException("didn't you read the doc comment, don't call this if the level is null");
+ throw new IllegalStateException(
+ "didn't you read the doc comment, don't call this if the level is null");
}
- if (this.executionState != null)
- return this.executionState;
+ if (this.executionState != null) return this.executionState;
if (this.lazyExecutionState != null)
- this.executionState = CircleExecutionState.load(this.lazyExecutionState, (ServerLevel) this.level);
+ this.executionState =
+ CircleExecutionState.load(this.lazyExecutionState, (ServerLevel) this.level);
return this.executionState;
}
public void startExecution(@Nullable ServerPlayer player) {
- if (this.level == null)
- return; // TODO: error here?
- if (this.level.isClientSide)
- return; // TODO: error here?
+ if (this.level == null) return; // TODO: error here?
+ if (this.level.isClientSide) return; // TODO: error here?
if (this.executionState != null) {
return;
@@ -168,13 +164,18 @@ public void startExecution(@Nullable ServerPlayer player) {
if (result.isErr()) {
var errPos = result.unwrapErr();
if (errPos == null) {
- ICircleComponent.sfx(this.getBlockPos(), this.getBlockState(), this.level, null, false);
+ ICircleComponent.sfx(
+ this.getBlockPos(), this.getBlockState(), this.level, null, false);
this.postNoExits(this.getBlockPos());
} else {
- ICircleComponent.sfx(errPos, this.level.getBlockState(errPos), this.level, null, false);
- this.postDisplay(Component.translatable("hexcasting.tooltip.circle.no_closure",
- Component.literal(errPos.toShortString()).withStyle(ChatFormatting.RED)),
- new ItemStack(Items.LEAD));
+ ICircleComponent.sfx(
+ errPos, this.level.getBlockState(errPos), this.level, null, false);
+ this.postDisplay(
+ Component.translatable(
+ "hexcasting.tooltip.circle.no_closure",
+ Component.literal(errPos.toShortString())
+ .withStyle(ChatFormatting.RED)),
+ new ItemStack(Items.LEAD));
}
return;
@@ -183,10 +184,13 @@ public void startExecution(@Nullable ServerPlayer player) {
this.clearDisplay();
var serverLevel = (ServerLevel) this.level;
- serverLevel.scheduleTick(this.getBlockPos(), this.getBlockState().getBlock(),
- this.executionState.getTickSpeed());
- serverLevel.setBlockAndUpdate(this.getBlockPos(),
- this.getBlockState().setValue(BlockCircleComponent.ENERGIZED, true));
+ serverLevel.scheduleTick(
+ this.getBlockPos(),
+ this.getBlockState().getBlock(),
+ this.executionState.getTickSpeed());
+ serverLevel.setBlockAndUpdate(
+ this.getBlockPos(),
+ this.getBlockState().setValue(BlockCircleComponent.ENERGIZED, true));
}
@Contract(pure = true)
@@ -222,9 +226,9 @@ protected static AABB getBounds(List poses) {
return new AABB(minX, minY, minZ, maxX + 1, maxY + 1, maxZ + 1);
}
- //endregion
+ // endregion
- //region media handling
+ // region media handling
public long getMedia() {
return this.media;
@@ -267,12 +271,10 @@ public long remainingMediaCapacity() {
return Math.max(0, MAX_CAPACITY - this.media);
}
- //endregion
-
+ // endregion
public FrozenPigment getPigment() {
- if (pigment != null)
- return pigment;
+ if (pigment != null) return pigment;
if (executionState != null && executionState.casterPigment != null)
return executionState.casterPigment;
return FrozenPigment.DEFAULT.get();
@@ -297,8 +299,7 @@ protected void saveModData(CompoundTag tag) {
this.displayItem.save(itemTag);
tag.put(TAG_ERROR_DISPLAY, itemTag);
}
- if (this.pigment != null)
- tag.put(TAG_PIGMENT, this.pigment.serializeToNBT());
+ if (this.pigment != null) tag.put(TAG_PIGMENT, this.pigment.serializeToNBT());
}
@Override
@@ -314,7 +315,8 @@ protected void loadModData(CompoundTag tag) {
this.media = tag.getLong(TAG_MEDIA);
}
- if (tag.contains(TAG_ERROR_MSG, Tag.TAG_STRING) && tag.contains(TAG_ERROR_DISPLAY, Tag.TAG_COMPOUND)) {
+ if (tag.contains(TAG_ERROR_MSG, Tag.TAG_STRING)
+ && tag.contains(TAG_ERROR_DISPLAY, Tag.TAG_COMPOUND)) {
var msg = Component.Serializer.fromJson(tag.getString(TAG_ERROR_MSG));
var display = ItemStack.of(tag.getCompound(TAG_ERROR_DISPLAY));
this.displayMsg = msg;
@@ -327,15 +329,24 @@ protected void loadModData(CompoundTag tag) {
this.pigment = FrozenPigment.fromNBT(tag.getCompound(TAG_PIGMENT));
}
- public void applyScryingLensOverlay(List> lines,
- BlockState state, BlockPos pos, Player observer, Level world, Direction hitFace) {
+ public void applyScryingLensOverlay(
+ List> lines,
+ BlockState state,
+ BlockPos pos,
+ Player observer,
+ Level world,
+ Direction hitFace) {
if (world.getBlockEntity(pos) instanceof BlockEntityAbstractImpetus beai) {
if (beai.getMedia() < 0) {
- lines.add(new Pair<>(new ItemStack(HexItems.AMETHYST_DUST), ItemCreativeUnlocker.infiniteMedia(world)));
+ lines.add(
+ new Pair<>(
+ new ItemStack(HexItems.AMETHYST_DUST),
+ ItemCreativeUnlocker.infiniteMedia(world)));
} else {
var dustCount = (float) beai.getMedia() / (float) MediaConstants.DUST_UNIT;
- var dustCmp = Component.translatable("hexcasting.tooltip.media",
- DUST_AMOUNT.format(dustCount));
+ var dustCmp =
+ Component.translatable(
+ "hexcasting.tooltip.media", DUST_AMOUNT.format(dustCount));
lines.add(new Pair<>(new ItemStack(HexItems.AMETHYST_DUST), dustCmp));
}
@@ -345,7 +356,7 @@ public void applyScryingLensOverlay(List> lines,
}
}
- //region music
+ // region music
protected int semitoneFromScale(int note) {
var blockBelow = this.level.getBlockState(this.getBlockPos().below());
@@ -357,9 +368,12 @@ protected int semitoneFromScale(int note) {
} else if (blockBelow.is(Blocks.PISTON) || blockBelow.is(Blocks.STICKY_PISTON)) {
scale = MIXOLYDIAN_SCALE;
} else if (blockBelow.is(Blocks.BLUE_WOOL)
- || blockBelow.is(Blocks.BLUE_CONCRETE) || blockBelow.is(Blocks.BLUE_CONCRETE_POWDER)
- || blockBelow.is(Blocks.BLUE_TERRACOTTA) || blockBelow.is(Blocks.BLUE_GLAZED_TERRACOTTA)
- || blockBelow.is(Blocks.BLUE_STAINED_GLASS) || blockBelow.is(Blocks.BLUE_STAINED_GLASS_PANE)) {
+ || blockBelow.is(Blocks.BLUE_CONCRETE)
+ || blockBelow.is(Blocks.BLUE_CONCRETE_POWDER)
+ || blockBelow.is(Blocks.BLUE_TERRACOTTA)
+ || blockBelow.is(Blocks.BLUE_GLAZED_TERRACOTTA)
+ || blockBelow.is(Blocks.BLUE_STAINED_GLASS)
+ || blockBelow.is(Blocks.BLUE_STAINED_GLASS_PANE)) {
scale = BLUES_SCALE;
} else if (blockBelow.is(Blocks.BONE_BLOCK)) {
scale = BAD_TIME;
@@ -380,9 +394,9 @@ protected int semitoneFromScale(int note) {
private static final int[] BAD_TIME = {0, 0, 12, 7, 6, 5, 3, 0, 3, 5};
private static final int[] SUSSY_BAKA = {5, 8, 10, 11, 10, 8, 5, 3, 7, 5};
- //endregion
+ // endregion
- //region item handler contract stuff
+ // region item handler contract stuff
private static final int[] SLOTS = {0};
@Override
@@ -454,5 +468,5 @@ public boolean canPlaceItem(int index, ItemStack stack) {
return mediamount > 0;
}
- //endregion
+ // endregion
}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/circles/CircleExecutionState.java b/Common/src/main/java/at/petrak/hexcasting/api/casting/circles/CircleExecutionState.java
index f95fa84f01..2b607b5e52 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/circles/CircleExecutionState.java
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/circles/CircleExecutionState.java
@@ -6,7 +6,9 @@
import at.petrak.hexcasting.api.misc.Result;
import at.petrak.hexcasting.api.pigment.FrozenPigment;
import at.petrak.hexcasting.api.utils.HexUtils;
+
import com.mojang.datafixers.util.Pair;
+
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
@@ -20,24 +22,22 @@
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.phys.AABB;
+
import org.jetbrains.annotations.Nullable;
import java.util.*;
-/**
- * See {@link BlockEntityAbstractImpetus}, this is what's stored in it
- */
+/** See {@link BlockEntityAbstractImpetus}, this is what's stored in it */
public class CircleExecutionState {
- public static final String
- TAG_IMPETUS_POS = "impetus_pos",
- TAG_IMPETUS_DIR = "impetus_dir",
- TAG_KNOWN_POSITIONS = "known_positions",
- TAG_REACHED_POSITIONS = "reached_positions",
- TAG_CURRENT_POS = "current_pos",
- TAG_ENTERED_FROM = "entered_from",
- TAG_IMAGE = "image",
- TAG_CASTER = "caster",
- TAG_PIGMENT = "pigment";
+ public static final String TAG_IMPETUS_POS = "impetus_pos",
+ TAG_IMPETUS_DIR = "impetus_dir",
+ TAG_KNOWN_POSITIONS = "known_positions",
+ TAG_REACHED_POSITIONS = "reached_positions",
+ TAG_CURRENT_POS = "current_pos",
+ TAG_ENTERED_FROM = "entered_from",
+ TAG_IMAGE = "image",
+ TAG_CASTER = "caster",
+ TAG_PIGMENT = "pigment";
public final BlockPos impetusPos;
public final Direction impetusDir;
@@ -52,10 +52,16 @@ public class CircleExecutionState {
public final AABB bounds;
-
- protected CircleExecutionState(BlockPos impetusPos, Direction impetusDir, Set knownPositions,
- List reachedPositions, BlockPos currentPos, Direction enteredFrom,
- CastingImage currentImage, @Nullable UUID caster, @Nullable FrozenPigment casterPigment) {
+ protected CircleExecutionState(
+ BlockPos impetusPos,
+ Direction impetusDir,
+ Set knownPositions,
+ List reachedPositions,
+ BlockPos currentPos,
+ Direction enteredFrom,
+ CastingImage currentImage,
+ @Nullable UUID caster,
+ @Nullable FrozenPigment casterPigment) {
this.impetusPos = impetusPos;
this.impetusDir = impetusDir;
this.knownPositions = knownPositions;
@@ -82,17 +88,19 @@ protected CircleExecutionState(BlockPos impetusPos, Direction impetusDir, Set createNew(BlockEntityAbstractImpetus impetus,
- @Nullable ServerPlayer caster) {
+ public static Result createNew(
+ BlockEntityAbstractImpetus impetus, @Nullable ServerPlayer caster) {
var level = (ServerLevel) impetus.getLevel();
- if (level == null)
- return new Result.Err<>(null);
+ if (level == null) return new Result.Err<>(null);
// Flood fill! Just like VCC all over again.
// this contains tentative positions and directions entered from
var todo = new Stack>();
- todo.add(Pair.of(impetus.getStartDirection(), impetus.getBlockPos().relative(impetus.getStartDirection())));
+ todo.add(
+ Pair.of(
+ impetus.getStartDirection(),
+ impetus.getBlockPos().relative(impetus.getStartDirection())));
var seenGoodPosSet = new HashSet();
var seenGoodPositions = new ArrayList();
@@ -122,7 +130,8 @@ protected CircleExecutionState(BlockPos impetusPos, Direction impetusDir, Set(null);
} else if (!seenGoodPosSet.contains(impetus.getBlockPos())) {
- // we can't enter from the side the directrix exits from, so this means we couldn't loop back.
+ // we can't enter from the side the directrix exits from, so this means we couldn't loop
+ // back.
// the last item we tried to examine will always be a terminal slate (b/c if it wasn't,
// then the *next* slate would be last qed)
return new Result.Err<>(seenGoodPositions.get(seenGoodPositions.size() - 1));
@@ -142,8 +151,16 @@ protected CircleExecutionState(BlockPos impetusPos, Direction impetusDir, Set(
- new CircleExecutionState(impetus.getBlockPos(), impetus.getStartDirection(), knownPositions,
- reachedPositions, start, impetus.getStartDirection(), new CastingImage(), casterUUID, colorizer));
+ new CircleExecutionState(
+ impetus.getBlockPos(),
+ impetus.getStartDirection(),
+ knownPositions,
+ reachedPositions,
+ start,
+ impetus.getStartDirection(),
+ new CastingImage(),
+ casterUUID,
+ colorizer));
}
public CompoundTag save() {
@@ -168,11 +185,9 @@ public CompoundTag save() {
out.putByte(TAG_ENTERED_FROM, (byte) this.enteredFrom.ordinal());
out.put(TAG_IMAGE, this.currentImage.serializeToNbt());
- if (this.caster != null)
- out.putUUID(TAG_CASTER, this.caster);
+ if (this.caster != null) out.putUUID(TAG_CASTER, this.caster);
- if (this.casterPigment != null)
- out.put(TAG_PIGMENT, this.casterPigment.serializeToNBT());
+ if (this.casterPigment != null) out.put(TAG_PIGMENT, this.casterPigment.serializeToNBT());
return out;
}
@@ -197,35 +212,45 @@ public static CircleExecutionState load(CompoundTag nbt, ServerLevel world) {
var image = CastingImage.loadFromNbt(nbt.getCompound(TAG_IMAGE), world);
UUID caster = null;
- if (nbt.hasUUID(TAG_CASTER))
- caster = nbt.getUUID(TAG_CASTER);
+ if (nbt.hasUUID(TAG_CASTER)) caster = nbt.getUUID(TAG_CASTER);
FrozenPigment pigment = null;
if (nbt.contains(TAG_PIGMENT, Tag.TAG_COMPOUND))
pigment = FrozenPigment.fromNBT(nbt.getCompound(TAG_PIGMENT));
- return new CircleExecutionState(startPos, startDir, knownPositions, reachedPositions, currentPos,
- enteredFrom, image, caster, pigment);
+ return new CircleExecutionState(
+ startPos,
+ startDir,
+ knownPositions,
+ reachedPositions,
+ currentPos,
+ enteredFrom,
+ image,
+ caster,
+ pigment);
}
/**
* Update this, also mutates the impetus.
- *
- * Returns whether to continue.
+ *
+ *
Returns whether to continue.
*/
public boolean tick(BlockEntityAbstractImpetus impetus) {
var world = (ServerLevel) impetus.getLevel();
- if (world == null)
- return true; // if the world is null, try again next tick.
+ if (world == null) return true; // if the world is null, try again next tick.
var env = new CircleCastEnv(world, this);
var executorBlockState = world.getBlockState(this.currentPos);
if (!(executorBlockState.getBlock() instanceof ICircleComponent executor)) {
// TODO: notification of the error?
- ICircleComponent.sfx(this.currentPos, executorBlockState, world,
- Objects.requireNonNull(env.getImpetus()), false);
+ ICircleComponent.sfx(
+ this.currentPos,
+ executorBlockState,
+ world,
+ Objects.requireNonNull(env.getImpetus()),
+ false);
return false;
}
@@ -234,11 +259,18 @@ public boolean tick(BlockEntityAbstractImpetus impetus) {
// Do the execution!
boolean halt = false;
- var ctrl = executor.acceptControlFlow(this.currentImage, env, this.enteredFrom, this.currentPos,
- executorBlockState, world);
+ var ctrl =
+ executor.acceptControlFlow(
+ this.currentImage,
+ env,
+ this.enteredFrom,
+ this.currentPos,
+ executorBlockState,
+ world);
if (env.getImpetus() == null)
- return false; //the impetus got removed during the cast and no longer exists in the world. stop casting
+ return false; // the impetus got removed during the cast and no longer exists in the
+ // world. stop casting
if (ctrl instanceof ICircleComponent.ControlFlow.Stop) {
// acceptControlFlow should have already posted the error
@@ -249,15 +281,22 @@ public boolean tick(BlockEntityAbstractImpetus impetus) {
for (var exit : cont.exits) {
var there = world.getBlockState(exit.getFirst());
if (there.getBlock() instanceof ICircleComponent cc
- && cc.canEnterFromDirection(exit.getSecond(), exit.getFirst(), there, world)) {
+ && cc.canEnterFromDirection(
+ exit.getSecond(), exit.getFirst(), there, world)) {
if (found != null) {
// oh no!
impetus.postDisplay(
- Component.translatable("hexcasting.tooltip.circle.many_exits",
- Component.literal(this.currentPos.toShortString()).withStyle(ChatFormatting.RED)),
- new ItemStack(Items.COMPASS));
- ICircleComponent.sfx(this.currentPos, executorBlockState, world,
- Objects.requireNonNull(env.getImpetus()), false);
+ Component.translatable(
+ "hexcasting.tooltip.circle.many_exits",
+ Component.literal(this.currentPos.toShortString())
+ .withStyle(ChatFormatting.RED)),
+ new ItemStack(Items.COMPASS));
+ ICircleComponent.sfx(
+ this.currentPos,
+ executorBlockState,
+ world,
+ Objects.requireNonNull(env.getImpetus()),
+ false);
halt = true;
break;
} else {
@@ -268,17 +307,27 @@ public boolean tick(BlockEntityAbstractImpetus impetus) {
if (found == null) {
// will never enter here if there were too many because found will have been set
- ICircleComponent.sfx(this.currentPos, executorBlockState, world,
- Objects.requireNonNull(env.getImpetus()), false);
+ ICircleComponent.sfx(
+ this.currentPos,
+ executorBlockState,
+ world,
+ Objects.requireNonNull(env.getImpetus()),
+ false);
impetus.postNoExits(this.currentPos);
halt = true;
} else {
// A single valid exit position has been found.
- ICircleComponent.sfx(this.currentPos, executorBlockState, world,
- Objects.requireNonNull(env.getImpetus()), true);
+ ICircleComponent.sfx(
+ this.currentPos,
+ executorBlockState,
+ world,
+ Objects.requireNonNull(env.getImpetus()),
+ true);
currentPos = found.getFirst();
enteredFrom = found.getSecond();
- currentImage = cont.update.withOverriddenUsedOps(0); // reset ops used after each slate finishes executing
+ currentImage =
+ cont.update.withOverriddenUsedOps(
+ 0); // reset ops used after each slate finishes executing
}
}
@@ -286,7 +335,8 @@ public boolean tick(BlockEntityAbstractImpetus impetus) {
}
/**
- * How many ticks should pass between activations, given the number of blocks encountered so far.
+ * How many ticks should pass between activations, given the number of blocks encountered so
+ * far.
*/
protected int getTickSpeed() {
return Math.max(2, 10 - (this.reachedPositions.size() - 1) / 3);
@@ -295,8 +345,7 @@ protected int getTickSpeed() {
public void endExecution(BlockEntityAbstractImpetus impetus) {
var world = (ServerLevel) impetus.getLevel();
- if (world == null)
- return; // TODO: error here?
+ if (world == null) return; // TODO: error here?
for (var pos : this.reachedPositions) {
var there = world.getBlockState(pos);
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/circles/ICircleComponent.java b/Common/src/main/java/at/petrak/hexcasting/api/casting/circles/ICircleComponent.java
index 66e06b4d0d..b1e1dadc43 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/circles/ICircleComponent.java
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/circles/ICircleComponent.java
@@ -10,7 +10,9 @@
import at.petrak.hexcasting.api.pigment.FrozenPigment;
import at.petrak.hexcasting.common.lib.HexItems;
import at.petrak.hexcasting.common.lib.HexSounds;
+
import com.mojang.datafixers.util.Pair;
+
import net.minecraft.Util;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
@@ -23,6 +25,7 @@
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.Vec3;
+
import org.jetbrains.annotations.Contract;
import java.util.EnumSet;
@@ -31,44 +34,51 @@
/**
* Implement this on a block to make circles interact with it.
- *
- * This is its own interface so you can have your blocks subclass something else, and to avoid enormous
- * files. The mod doesn't check for the interface on anything but blocks.
+ *
+ *
This is its own interface so you can have your blocks subclass something else, and to avoid
+ * enormous files. The mod doesn't check for the interface on anything but blocks.
*/
public interface ICircleComponent {
/**
* The heart of the interface! Functionally modify the casting environment.
- *
- * With the new update you can have the side effects happen inline. In fact, you have to have the side effects
- * happen inline.
- *
- * Also, return a list of directions that the control flow can exit this block in.
- * The circle environment will mishap if not exactly 1 of the returned directions can be accepted from.
+ *
+ *
With the new update you can have the side effects happen inline. In fact, you have to have
+ * the side effects happen inline.
+ *
+ *
Also, return a list of directions that the control flow can exit this block in. The circle
+ * environment will mishap if not exactly 1 of the returned directions can be accepted from.
*/
- ControlFlow acceptControlFlow(CastingImage imageIn, CircleCastEnv env, Direction enterDir, BlockPos pos,
- BlockState bs, ServerLevel world);
+ ControlFlow acceptControlFlow(
+ CastingImage imageIn,
+ CircleCastEnv env,
+ Direction enterDir,
+ BlockPos pos,
+ BlockState bs,
+ ServerLevel world);
/**
- * Can this component get transferred to from a block coming in from that direction, with the given normal?
+ * Can this component get transferred to from a block coming in from that direction, with the
+ * given normal?
*/
@Contract(pure = true)
- boolean canEnterFromDirection(Direction enterDir, BlockPos pos, BlockState bs, ServerLevel world);
+ boolean canEnterFromDirection(
+ Direction enterDir, BlockPos pos, BlockState bs, ServerLevel world);
/**
- * This determines the directions the control flow can exit from. It's called at the beginning of execution
- * to see if the circle actually forms a loop.
- *
- * For most blocks, this should be the same as returned from {@link ICircleComponent#acceptControlFlow}
- * Things like directrices might return otherwise. Whatever is returned when controlling flow must be a subset of
- * this set.
+ * This determines the directions the control flow can exit from. It's called at the
+ * beginning of execution to see if the circle actually forms a loop.
+ *
+ *
For most blocks, this should be the same as returned from {@link
+ * ICircleComponent#acceptControlFlow} Things like directrices might return otherwise. Whatever
+ * is returned when controlling flow must be a subset of this set.
*/
@Contract(pure = true)
EnumSet possibleExitDirections(BlockPos pos, BlockState bs, Level world);
/**
- * Given the current position and a direction, return a pair of the new position after a step
- * in that direction, along with the direction (this is a helper function for creating
- * {@link ICircleComponent.ControlFlow}s.
+ * Given the current position and a direction, return a pair of the new position after a step in
+ * that direction, along with the direction (this is a helper function for creating {@link
+ * ICircleComponent.ControlFlow}s.
*/
@Contract(pure = true)
default Pair exitPositionFromDirection(BlockPos pos, Direction dir) {
@@ -76,37 +86,43 @@ default Pair exitPositionFromDirection(BlockPos pos, Direct
}
/**
- * Start the {@link ICircleComponent} at the given position glowing. Returns the new state
- * of the given block.
- * // TODO: determine if this should just be in
- * {@link ICircleComponent#acceptControlFlow(CastingImage, CircleCastEnv, Direction, BlockPos, BlockState, ServerLevel)}.
+ * Start the {@link ICircleComponent} at the given position glowing. Returns the new state of
+ * the given block. // TODO: determine if this should just be in {@link
+ * ICircleComponent#acceptControlFlow(CastingImage, CircleCastEnv, Direction, BlockPos,
+ * BlockState, ServerLevel)}.
*/
BlockState startEnergized(BlockPos pos, BlockState bs, Level world);
- /**
- * Returns whether the {@link ICircleComponent} at the given position is energized.
- */
+ /** Returns whether the {@link ICircleComponent} at the given position is energized. */
boolean isEnergized(BlockPos pos, BlockState bs, Level world);
/**
- * End the {@link ICircleComponent} at the given position glowing. Returns the new state of
- * the given block.
+ * End the {@link ICircleComponent} at the given position glowing. Returns the new state of the
+ * given block.
*/
BlockState endEnergized(BlockPos pos, BlockState bs, Level world);
- static void sfx(BlockPos pos, BlockState bs, Level world, BlockEntityAbstractImpetus impetus, boolean success) {
+ static void sfx(
+ BlockPos pos,
+ BlockState bs,
+ Level world,
+ BlockEntityAbstractImpetus impetus,
+ boolean success) {
Vec3 vpos;
Vec3 vecOutDir;
FrozenPigment colorizer;
UUID activator = Util.NIL_UUID;
- if (impetus != null && impetus.getExecutionState() != null && impetus.getExecutionState().caster != null)
+ if (impetus != null
+ && impetus.getExecutionState() != null
+ && impetus.getExecutionState().caster != null)
activator = impetus.getExecutionState().caster;
if (impetus == null || impetus.getExecutionState() == null)
- colorizer = new FrozenPigment(new ItemStack(HexItems.DYE_PIGMENTS.get(DyeColor.RED)), activator);
- else
- colorizer = impetus.getPigment();
+ colorizer =
+ new FrozenPigment(
+ new ItemStack(HexItems.DYE_PIGMENTS.get(DyeColor.RED)), activator);
+ else colorizer = impetus.getPigment();
if (bs.getBlock() instanceof BlockCircleComponent bcc) {
var outDir = bcc.normalDir(pos, bs, world);
@@ -120,11 +136,20 @@ static void sfx(BlockPos pos, BlockState bs, Level world, BlockEntityAbstractImp
}
if (world instanceof ServerLevel serverLevel) {
- var spray = new ParticleSpray(vpos, vecOutDir.scale(success ? 1.0 : 1.5), success ? 0.1 : 0.5,
- Mth.PI / (success ? 4 : 2), success ? 30 : 100);
- spray.sprayParticles(serverLevel,
- success ? colorizer : new FrozenPigment(new ItemStack(HexItems.DYE_PIGMENTS.get(DyeColor.RED)),
- activator));
+ var spray =
+ new ParticleSpray(
+ vpos,
+ vecOutDir.scale(success ? 1.0 : 1.5),
+ success ? 0.1 : 0.5,
+ Mth.PI / (success ? 4 : 2),
+ success ? 30 : 100);
+ spray.sprayParticles(
+ serverLevel,
+ success
+ ? colorizer
+ : new FrozenPigment(
+ new ItemStack(HexItems.DYE_PIGMENTS.get(DyeColor.RED)),
+ activator));
}
var pitch = 1f;
@@ -142,12 +167,17 @@ static void sfx(BlockPos pos, BlockState bs, Level world, BlockEntityAbstractImp
world.playSound(null, vpos.x, vpos.y, vpos.z, sound, SoundSource.BLOCKS, 1f, pitch);
}
- /**
- * Helper function to "throw a mishap"
- */
- default void fakeThrowMishap(BlockPos pos, BlockState bs, CastingImage image, CircleCastEnv env, Mishap mishap) {
- Mishap.Context errorCtx = new Mishap.Context(null,
- bs.getBlock().getName().append(" (").append(Component.literal(pos.toShortString())).append(")"));
+ /** Helper function to "throw a mishap" */
+ default void fakeThrowMishap(
+ BlockPos pos, BlockState bs, CastingImage image, CircleCastEnv env, Mishap mishap) {
+ Mishap.Context errorCtx =
+ new Mishap.Context(
+ null,
+ bs.getBlock()
+ .getName()
+ .append(" (")
+ .append(Component.literal(pos.toShortString()))
+ .append(")"));
var sideEffect = new OperatorSideEffect.DoMishap(mishap, errorCtx);
var vm = new CastingVM(image, env);
sideEffect.performEffect(vm);
@@ -164,7 +194,6 @@ public Continue(CastingImage update, List> exits) {
}
}
- public static final class Stop extends ControlFlow {
- }
+ public static final class Stop extends ControlFlow {}
}
}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/CastResult.kt b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/CastResult.kt
index c0b4d4442d..33847c69d3 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/CastResult.kt
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/CastResult.kt
@@ -9,15 +9,15 @@ import at.petrak.hexcasting.api.casting.iota.Iota
/**
* The result of doing something to a cast harness.
*
- * Contains the iota that was executed to produce this CastResult,
- * the next thing to execute after this is finished, the modified state of the stack,
- * and side effects, as well as display information for the client.
+ * Contains the iota that was executed to produce this CastResult, the next thing to execute after
+ * this is finished, the modified state of the stack, and side effects, as well as display
+ * information for the client.
*/
data class CastResult(
- val cast: Iota,
- val continuation: SpellContinuation,
- val newData: CastingImage?,
- val sideEffects: List,
- val resolutionType: ResolvedPatternType,
- val sound: EvalSound,
+ val cast: Iota,
+ val continuation: SpellContinuation,
+ val newData: CastingImage?,
+ val sideEffects: List,
+ val resolutionType: ResolvedPatternType,
+ val sound: EvalSound,
)
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/CastingEnvironment.java b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/CastingEnvironment.java
index 6eaaf765ec..48325c9d82 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/CastingEnvironment.java
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/CastingEnvironment.java
@@ -1,5 +1,8 @@
package at.petrak.hexcasting.api.casting.eval;
+import static at.petrak.hexcasting.api.HexAPI.modLoc;
+import static at.petrak.hexcasting.api.casting.eval.CastingEnvironmentComponent.*;
+
import at.petrak.hexcasting.api.casting.ParticleSpray;
import at.petrak.hexcasting.api.casting.PatternShapeMatch;
import at.petrak.hexcasting.api.casting.eval.vm.CastingImage;
@@ -10,6 +13,7 @@
import at.petrak.hexcasting.api.mod.HexConfig;
import at.petrak.hexcasting.api.pigment.FrozenPigment;
import at.petrak.hexcasting.api.utils.HexUtils;
+
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
@@ -23,6 +27,7 @@
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.Vec3;
+
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -34,50 +39,50 @@
import java.util.function.Consumer;
import java.util.function.Predicate;
-import static at.petrak.hexcasting.api.HexAPI.modLoc;
-import static at.petrak.hexcasting.api.casting.eval.CastingEnvironmentComponent.*;
-
/**
* Environment within which hexes are cast.
- *
- * Stuff like "the player with a staff," "the player with a trinket," "spell circles,"
+ *
+ *
Stuff like "the player with a staff," "the player with a trinket," "spell circles,"
*/
public abstract class CastingEnvironment {
/**
* Stores all listeners that should be notified whenever a CastingEnvironment is initialised.
*/
- private static final List> createEventListeners = new ArrayList<>();
+ private static final List> createEventListeners =
+ new ArrayList<>();
- /**
- * Add a listener that will be called whenever a new CastingEnvironment is created.
- */
- public static void addCreateEventListener(BiConsumer listener) {
+ /** Add a listener that will be called whenever a new CastingEnvironment is created. */
+ public static void addCreateEventListener(
+ BiConsumer listener) {
createEventListeners.add(listener);
}
/**
* Add a listener that will be called whenever a new CastingEnvironment is created (legacy).
+ *
* @deprecated replaced by {@link #addCreateEventListener(BiConsumer)}
*/
@Deprecated(since = "0.11.0-pre-660")
public static void addCreateEventListener(Consumer listener) {
- createEventListeners.add((env, data) -> {listener.accept(env);});
+ createEventListeners.add(
+ (env, data) -> {
+ listener.accept(env);
+ });
}
private boolean createEventTriggered = false;
public final void triggerCreateEvent(CompoundTag userData) {
if (!createEventTriggered) {
- for (var listener : createEventListeners)
- listener.accept(this, userData);
+ for (var listener : createEventListeners) listener.accept(this, userData);
createEventTriggered = true;
}
}
-
protected final ServerLevel world;
- protected Map, @NotNull CastingEnvironmentComponent> componentMap = new HashMap<>();
+ protected Map, @NotNull CastingEnvironmentComponent>
+ componentMap = new HashMap<>();
private final List postExecutions = new ArrayList<>();
private final List postCasts = new ArrayList<>();
@@ -101,78 +106,73 @@ public int maxOpCount() {
/**
* Get the caster. Might be null!
- *
- * Implementations should NOT rely on this in general, use the methods on this class instead.
+ *
+ *
Implementations should NOT rely on this in general, use the methods on this class instead.
* This is mostly for spells (flight, etc)
+ *
* @deprecated as of build 0.11.1-7-pre-619 you are recommended to use {@link #getCastingEntity}
*/
- @Deprecated(since="0.11.1-7-pre-619")
+ @Deprecated(since = "0.11.1-7-pre-619")
@Nullable
public ServerPlayer getCaster() {
return getCastingEntity() instanceof ServerPlayer sp ? sp : null;
- };
+ }
+ ;
/**
* Gets the caster. Can be null if {@link #getCaster()} is also null
+ *
* @return the entity casting
*/
@Nullable
public abstract LivingEntity getCastingEntity();
- /**
- * Get an interface used to do mishaps
- */
+ /** Get an interface used to do mishaps */
public abstract MishapEnvironment getMishapEnvironment();
public void addExtension(@NotNull T extension) {
componentMap.put(extension.getKey(), extension);
- if (extension instanceof PostExecution postExecution)
- postExecutions.add(postExecution);
- if (extension instanceof PostCast postCast)
- postCasts.add(postCast);
+ if (extension instanceof PostExecution postExecution) postExecutions.add(postExecution);
+ if (extension instanceof PostCast postCast) postCasts.add(postCast);
if (extension instanceof ExtractMedia extractMedia)
if (extension instanceof ExtractMedia.Pre pre) {
preMediaExtract.add(pre);
} else if (extension instanceof ExtractMedia.Post post) {
postMediaExtract.add(post);
}
- if (extension instanceof IsVecInRange isVecInRange)
- isVecInRanges.add(isVecInRange);
+ if (extension instanceof IsVecInRange isVecInRange) isVecInRanges.add(isVecInRange);
if (extension instanceof HasEditPermissionsAt hasEditPermissionsAt)
hasEditPermissionsAts.add(hasEditPermissionsAt);
}
public void removeExtension(@NotNull CastingEnvironmentComponent.Key> key) {
var extension = componentMap.remove(key);
- if (extension == null)
- return;
+ if (extension == null) return;
- if (extension instanceof PostExecution postExecution)
- postExecutions.remove(postExecution);
- if (extension instanceof PostCast postCast)
- postCasts.remove(postCast);
+ if (extension instanceof PostExecution postExecution) postExecutions.remove(postExecution);
+ if (extension instanceof PostCast postCast) postCasts.remove(postCast);
if (extension instanceof ExtractMedia extractMedia)
if (extension instanceof ExtractMedia.Pre pre) {
preMediaExtract.remove(pre);
} else if (extension instanceof ExtractMedia.Post post) {
postMediaExtract.remove(post);
}
- if (extension instanceof IsVecInRange isVecInRange)
- isVecInRanges.remove(isVecInRange);
+ if (extension instanceof IsVecInRange isVecInRange) isVecInRanges.remove(isVecInRange);
if (extension instanceof HasEditPermissionsAt hasEditPermissionsAt)
hasEditPermissionsAts.remove(hasEditPermissionsAt);
}
@Nullable
@SuppressWarnings("unchecked")
- public T getExtension(@NotNull CastingEnvironmentComponent.Key key) {
+ public T getExtension(
+ @NotNull CastingEnvironmentComponent.Key key) {
return (T) componentMap.get(key);
}
/**
* If something about this ARE itself is invalid, mishap.
- *
- * This is used for stuff like requiring enlightenment and pattern denylists
+ *
+ *
This is used for stuff like requiring enlightenment and pattern denylists
*/
public void precheckAction(PatternShapeMatch match) throws Mishap {
// TODO: this doesn't let you select special handlers.
@@ -199,31 +199,26 @@ protected ResourceLocation actionKey(PatternShapeMatch match) {
return key;
}
- /**
- * Do whatever you like after a pattern is executed.
- */
+ /** Do whatever you like after a pattern is executed. */
public void postExecution(CastResult result) {
for (var postExecutionComponent : postExecutions)
postExecutionComponent.onPostExecution(result);
}
/**
- * Do things after the whole cast is finished (i.e. every pattern to be executed has been executed).
+ * Do things after the whole cast is finished (i.e. every pattern to be executed has been
+ * executed).
*/
public void postCast(CastingImage image) {
- for (var postCastComponent : postCasts)
- postCastComponent.onPostCast(image);
+ for (var postCastComponent : postCasts) postCastComponent.onPostCast(image);
}
public abstract Vec3 mishapSprayPos();
- /**
- * Return whether this env can cast great spells.
- */
+ /** Return whether this env can cast great spells. */
public boolean isEnlightened() {
var adv = this.world.getServer().getAdvancements().getAdvancement(modLoc("enlightenment"));
- if (adv == null)
- return false;
+ if (adv == null) return false;
var caster = this.getCastingEntity();
if (caster instanceof ServerPlayer player)
@@ -234,9 +229,9 @@ public boolean isEnlightened() {
/**
* Attempt to extract the given amount of media. Returns the amount of media left in the cost.
- *
- * If there was enough media found, it will return less or equal to zero; if there wasn't, it will be
- * positive.
+ *
+ *
If there was enough media found, it will return less or equal to zero; if there wasn't, it
+ * will be positive.
*/
public long extractMedia(long cost, boolean simulate) {
for (var extractMediaComponent : preMediaExtract)
@@ -249,16 +244,16 @@ public long extractMedia(long cost, boolean simulate) {
/**
* Attempt to extract the given amount of media. Returns the amount of media left in the cost.
- *
- * If there was enough media found, it will return less or equal to zero; if there wasn't, it will be
- * positive.
+ *
+ *
If there was enough media found, it will return less or equal to zero; if there wasn't, it
+ * will be positive.
*/
protected abstract long extractMediaEnvironment(long cost, boolean simulate);
/**
* Get if the vec is close enough, to the player or sentinel ...
- *
- * Doesn't take into account being out of the world.
+ *
+ *
Doesn't take into account being out of the world.
*/
public boolean isVecInRange(Vec3 vec) {
boolean isInRange = isVecInRangeEnvironment(vec);
@@ -269,29 +264,32 @@ public boolean isVecInRange(Vec3 vec) {
/**
* Get if the vec is close enough, to the player or sentinel ...
- *
- * Doesn't take into account being out of the world.
+ *
+ *
Doesn't take into account being out of the world.
*/
protected abstract boolean isVecInRangeEnvironment(Vec3 vec);
/**
- * Return whether the caster can edit blocks at the given permission (i.e. not adventure mode, etc.)
+ * Return whether the caster can edit blocks at the given permission (i.e. not adventure mode,
+ * etc.)
*/
public boolean hasEditPermissionsAt(BlockPos pos) {
boolean hasEditPermissionsAt = hasEditPermissionsAtEnvironment(pos);
for (var hasEditPermissionsAtComponent : hasEditPermissionsAts)
- hasEditPermissionsAt = hasEditPermissionsAtComponent.onHasEditPermissionsAt(pos, hasEditPermissionsAt);
+ hasEditPermissionsAt =
+ hasEditPermissionsAtComponent.onHasEditPermissionsAt(pos, hasEditPermissionsAt);
return hasEditPermissionsAt;
}
/**
- * Return whether the caster can edit blocks at the given permission (i.e. not adventure mode, etc.)
+ * Return whether the caster can edit blocks at the given permission (i.e. not adventure mode,
+ * etc.)
*/
protected abstract boolean hasEditPermissionsAtEnvironment(BlockPos pos);
public final boolean isVecInWorld(Vec3 vec) {
return this.world.isInWorldBounds(BlockPos.containing(vec))
- && this.world.getWorldBorder().isWithinBounds(vec.x, vec.z, 0.5);
+ && this.world.getWorldBorder().isWithinBounds(vec.x, vec.z, 0.5);
}
public final boolean isVecInAmbit(Vec3 vec) {
@@ -299,12 +297,11 @@ public final boolean isVecInAmbit(Vec3 vec) {
}
public final boolean isEntityInRange(Entity e) {
- return (e instanceof Player && HexConfig.server().trueNameHasAmbit()) || (this.isVecInWorld(e.position()) && this.isVecInRange(e.position()));
+ return (e instanceof Player && HexConfig.server().trueNameHasAmbit())
+ || (this.isVecInWorld(e.position()) && this.isVecInRange(e.position()));
}
- /**
- * Convenience function to throw if the vec is out of the caster's range or the world
- */
+ /** Convenience function to throw if the vec is out of the caster's range or the world */
public final void assertVecInRange(Vec3 vec) throws MishapBadLocation {
this.assertVecInWorld(vec);
if (!this.isVecInRange(vec)) {
@@ -326,9 +323,7 @@ public final boolean canEditBlockAt(BlockPos vec) {
return this.isVecInRange(Vec3.atCenterOf(vec)) && this.hasEditPermissionsAt(vec);
}
- /**
- * Convenience function to throw if the entity is out of the caster's range or the world
- */
+ /** Convenience function to throw if the entity is out of the caster's range or the world */
public final void assertEntityInRange(Entity e) throws MishapEntityTooFarAway {
if (e instanceof ServerPlayer && HexConfig.server().trueNameHasAmbit()) {
return;
@@ -341,9 +336,7 @@ public final void assertEntityInRange(Entity e) throws MishapEntityTooFarAway {
}
}
- /**
- * Convenience function to throw if the vec is out of the world (for GTP)
- */
+ /** Convenience function to throw if the vec is out of the world (for GTP) */
public final void assertVecInWorld(Vec3 vec) throws MishapBadLocation {
if (!this.isVecInWorld(vec)) {
throw new MishapBadLocation(vec, "out_of_world");
@@ -356,12 +349,11 @@ public InteractionHand getOtherHand() {
return HexUtils.otherHand(this.getCastingHand());
}
- /**
- * Get all the item stacks this env can use.
- */
+ /** Get all the item stacks this env can use. */
protected abstract List getUsableStacks(StackDiscoveryMode mode);
- protected List getUsableStacksForPlayer(StackDiscoveryMode mode, @Nullable InteractionHand castingHand, ServerPlayer caster) {
+ protected List getUsableStacksForPlayer(
+ StackDiscoveryMode mode, @Nullable InteractionHand castingHand, ServerPlayer caster) {
return switch (mode) {
case QUERY -> {
var out = new ArrayList();
@@ -383,12 +375,13 @@ protected List getUsableStacksForPlayer(StackDiscoveryMode mode, @Nul
}
}
- // If we're casting from the main hand, try to pick from the slot one to the right of the selected slot
+ // If we're casting from the main hand, try to pick from the slot one to the right
+ // of the selected slot
// Otherwise, scan the hotbar left to right
- var anchorSlot = castingHand != InteractionHand.OFF_HAND
- ? (caster.getInventory().selected + 1) % 9
- : 0;
-
+ var anchorSlot =
+ castingHand != InteractionHand.OFF_HAND
+ ? (caster.getInventory().selected + 1) % 9
+ : 0;
for (int delta = 0; delta < 9; delta++) {
var slot = (anchorSlot + delta) % 9;
@@ -424,28 +417,27 @@ protected List getUsableStacksForPlayer(StackDiscoveryMode mode, @Nul
}
/**
- * Get the primary/secondary item stacks this env can use (i.e. main hand and offhand for the player).
+ * Get the primary/secondary item stacks this env can use (i.e. main hand and offhand for the
+ * player).
*/
protected abstract List getPrimaryStacks();
- protected List getPrimaryStacksForPlayer(InteractionHand castingHand, ServerPlayer caster) {
+ protected List getPrimaryStacksForPlayer(
+ InteractionHand castingHand, ServerPlayer caster) {
var primaryItem = caster.getItemInHand(castingHand);
- if (primaryItem.isEmpty())
- primaryItem = ItemStack.EMPTY.copy();
+ if (primaryItem.isEmpty()) primaryItem = ItemStack.EMPTY.copy();
var secondaryItem = caster.getItemInHand(HexUtils.otherHand(castingHand));
- if (secondaryItem.isEmpty())
- secondaryItem = ItemStack.EMPTY.copy();
+ if (secondaryItem.isEmpty()) secondaryItem = ItemStack.EMPTY.copy();
- return List.of(new HeldItemInfo(secondaryItem, HexUtils.otherHand(castingHand)), new HeldItemInfo(primaryItem,
- castingHand));
+ return List.of(
+ new HeldItemInfo(secondaryItem, HexUtils.otherHand(castingHand)),
+ new HeldItemInfo(primaryItem, castingHand));
}
- /**
- * Return the slot from which to take blocks and items.
- */
+ /** Return the slot from which to take blocks and items. */
@Nullable
public ItemStack queryForMatchingStack(Predicate stackOk) {
var stacks = this.getUsableStacks(StackDiscoveryMode.QUERY);
@@ -468,9 +460,7 @@ public ItemStack component1() {
}
}
- /**
- * Return the slot from which to take blocks and items.
- */
+ /** Return the slot from which to take blocks and items. */
// TODO winfy: resolve the null here
public @Nullable HeldItemInfo getHeldItemToOperateOn(Predicate stackOk) {
var stacks = this.getPrimaryStacks();
@@ -483,17 +473,15 @@ public ItemStack component1() {
return null;
}
- /**
- * Whether to provide infinite items.
- */
+ /** Whether to provide infinite items. */
protected boolean isCreativeMode() {
return false;
}
/**
* Attempt to withdraw some number of items from stacks available.
- *
- * Return whether it was successful.
+ *
+ *
Return whether it was successful.
*/
public boolean withdrawItem(Predicate stackOk, int count, boolean actuallyRemove) {
if (this.isCreativeMode()) {
@@ -509,8 +497,7 @@ public boolean withdrawItem(Predicate stackOk, int count, boolean act
presentCount += stack.getCount();
matches.add(stack);
- if (presentCount >= count)
- break;
+ if (presentCount >= count) break;
}
}
if (presentCount < count) {
@@ -536,15 +523,20 @@ public boolean withdrawItem(Predicate stackOk, int count, boolean act
}
/**
- * Attempt to replace the first stack found which matches the predicate with the stack to replace with.
+ * Attempt to replace the first stack found which matches the predicate with the stack to
+ * replace with.
+ *
* @return whether it was successful.
*/
- public abstract boolean replaceItem(Predicate stackOk, ItemStack replaceWith, @Nullable InteractionHand hand);
+ public abstract boolean replaceItem(
+ Predicate stackOk, ItemStack replaceWith, @Nullable InteractionHand hand);
-
- public boolean replaceItemForPlayer(Predicate stackOk, ItemStack replaceWith, @Nullable InteractionHand hand, ServerPlayer caster) {
- if (caster == null)
- return false;
+ public boolean replaceItemForPlayer(
+ Predicate stackOk,
+ ItemStack replaceWith,
+ @Nullable InteractionHand hand,
+ ServerPlayer caster) {
+ if (caster == null) return false;
if (hand != null && stackOk.test(caster.getItemInHand(hand))) {
caster.setItemInHand(hand, replaceWith);
@@ -573,17 +565,11 @@ public boolean replaceItemForPlayer(Predicate stackOk, ItemStack repl
return false;
}
- /**
- * The order/mode stacks should be discovered in
- */
+ /** The order/mode stacks should be discovered in */
protected enum StackDiscoveryMode {
- /**
- * When finding items to pick (hotbar)
- */
+ /** When finding items to pick (hotbar) */
QUERY,
- /**
- * When extracting things
- */
+ /** When extracting things */
EXTRACTION,
}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/CastingEnvironmentComponent.java b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/CastingEnvironmentComponent.java
index 73f7775a44..0e66dd87cc 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/CastingEnvironmentComponent.java
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/CastingEnvironmentComponent.java
@@ -1,6 +1,7 @@
package at.petrak.hexcasting.api.casting.eval;
import at.petrak.hexcasting.api.casting.eval.vm.CastingImage;
+
import net.minecraft.core.BlockPos;
import net.minecraft.world.phys.Vec3;
@@ -10,50 +11,46 @@ public interface CastingEnvironmentComponent {
interface Key {}
interface PostExecution extends CastingEnvironmentComponent {
- /**
- * Do whatever you like after a pattern is executed.
- */
+ /** Do whatever you like after a pattern is executed. */
void onPostExecution(CastResult result);
}
interface PostCast extends CastingEnvironmentComponent {
/**
- * Do things after the whole cast is finished (i.e. every pattern to be executed has been executed).
+ * Do things after the whole cast is finished (i.e. every pattern to be executed has been
+ * executed).
*/
void onPostCast(CastingImage image);
}
interface ExtractMedia extends CastingEnvironmentComponent {
/**
- * Receives the cost that is being extracted, should return the
- * remaining cost after deducting whatever cost source this component
- * is responsible for (should be >= 0)
+ * Receives the cost that is being extracted, should return the remaining cost after
+ * deducting whatever cost source this component is responsible for (should be >= 0)
*/
long onExtractMedia(long cost, boolean simulate);
/**
- * ExtractMedia component that extracts media BEFORE the call to {@link CastingEnvironment#extractMediaEnvironment(long, boolean)}
+ * ExtractMedia component that extracts media BEFORE the call to {@link
+ * CastingEnvironment#extractMediaEnvironment(long, boolean)}
*/
interface Pre extends ExtractMedia {}
/**
- * ExtractMedia component that extracts media AFTER the call to {@link CastingEnvironment#extractMediaEnvironment(long, boolean)}
- * if the input is <= 0 you should also probably return 0 (since media cost was already paid off)
+ * ExtractMedia component that extracts media AFTER the call to {@link
+ * CastingEnvironment#extractMediaEnvironment(long, boolean)} if the input is <= 0 you
+ * should also probably return 0 (since media cost was already paid off)
*/
interface Post extends ExtractMedia {}
}
interface IsVecInRange extends CastingEnvironmentComponent {
- /**
- * Receives the vec, and the current return value, and returns the new return value.
- */
+ /** Receives the vec, and the current return value, and returns the new return value. */
boolean onIsVecInRange(Vec3 vec, boolean current);
}
interface HasEditPermissionsAt extends CastingEnvironmentComponent {
- /**
- * Receives the vec, and the current return value, and returns the new return value.
- */
+ /** Receives the vec, and the current return value, and returns the new return value. */
boolean onHasEditPermissionsAt(BlockPos pos, boolean current);
}
}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/ExecutionClientView.kt b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/ExecutionClientView.kt
index 3fcf1bf766..f875ccb384 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/ExecutionClientView.kt
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/ExecutionClientView.kt
@@ -2,9 +2,7 @@ package at.petrak.hexcasting.api.casting.eval
import net.minecraft.nbt.CompoundTag
-/**
- * Information sent back to the client
- */
+/** Information sent back to the client */
data class ExecutionClientView(
val isStackClear: Boolean,
val resolutionType: ResolvedPatternType,
@@ -14,4 +12,3 @@ data class ExecutionClientView(
val stackDescs: List,
val ravenmind: CompoundTag?,
)
-
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/MishapEnvironment.java b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/MishapEnvironment.java
index 5469914454..5008f2d0fa 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/MishapEnvironment.java
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/MishapEnvironment.java
@@ -5,17 +5,17 @@
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.Vec3;
+
import org.jetbrains.annotations.Nullable;
/**
* Kinda like {@link CastingEnvironment} but for executing mishaps.
- *
- * To avoid horrible O(mn) scope problems we offer a set of stock bad effects.
- * The player is exposed nullably if you like though.
+ *
+ *
To avoid horrible O(mn) scope problems we offer a set of stock bad effects. The player is
+ * exposed nullably if you like though.
*/
public abstract class MishapEnvironment {
- @Nullable
- protected final ServerPlayer caster;
+ @Nullable protected final ServerPlayer caster;
protected final ServerLevel world;
protected MishapEnvironment(ServerLevel world, @Nullable ServerPlayer caster) {
@@ -36,14 +36,16 @@ protected MishapEnvironment(ServerLevel world, @Nullable ServerPlayer caster) {
public abstract void blind(int ticks);
protected void yeetItem(ItemStack stack, Vec3 srcPos, Vec3 delta) {
- var entity = new ItemEntity(
- this.world,
- srcPos.x, srcPos.y, srcPos.z,
- stack,
- delta.x + (Math.random() - 0.5) * 0.1,
- delta.y + (Math.random() - 0.5) * 0.1,
- delta.z + (Math.random() - 0.5) * 0.1
- );
+ var entity =
+ new ItemEntity(
+ this.world,
+ srcPos.x,
+ srcPos.y,
+ srcPos.z,
+ stack,
+ delta.x + (Math.random() - 0.5) * 0.1,
+ delta.y + (Math.random() - 0.5) * 0.1,
+ delta.z + (Math.random() - 0.5) * 0.1);
entity.setPickUpDelay(40);
this.world.addWithUUID(entity);
}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/OperationResult.kt b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/OperationResult.kt
index 3a0f066fbc..bd60020295 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/OperationResult.kt
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/OperationResult.kt
@@ -5,9 +5,7 @@ import at.petrak.hexcasting.api.casting.eval.sideeffects.OperatorSideEffect
import at.petrak.hexcasting.api.casting.eval.vm.CastingImage
import at.petrak.hexcasting.api.casting.eval.vm.SpellContinuation
-/**
- * What happens when an operator is through?
- */
+/** What happens when an operator is through? */
data class OperationResult(
val newImage: CastingImage,
val sideEffects: List,
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/ResolvedPattern.kt b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/ResolvedPattern.kt
index 6108850727..077825701c 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/ResolvedPattern.kt
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/ResolvedPattern.kt
@@ -3,11 +3,14 @@ package at.petrak.hexcasting.api.casting.eval
import at.petrak.hexcasting.api.casting.math.HexCoord
import at.petrak.hexcasting.api.casting.math.HexPattern
import at.petrak.hexcasting.api.utils.NBTBuilder
-import net.minecraft.nbt.CompoundTag
import java.util.*
+import net.minecraft.nbt.CompoundTag
-
-data class ResolvedPattern(val pattern: HexPattern, val origin: HexCoord, var type: ResolvedPatternType) {
+data class ResolvedPattern(
+ val pattern: HexPattern,
+ val origin: HexCoord,
+ var type: ResolvedPatternType
+) {
fun serializeToNBT() = NBTBuilder {
"Pattern" %= pattern.serializeToNBT()
"OriginQ" %= origin.q
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/SpellCircleContext.kt b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/SpellCircleContext.kt
index 269d6465c4..d97d452d8a 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/SpellCircleContext.kt
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/SpellCircleContext.kt
@@ -5,10 +5,12 @@ import net.minecraft.core.BlockPos
import net.minecraft.nbt.CompoundTag
import net.minecraft.world.phys.AABB
-/**
- * Optional field on a [CastingEnvironment] for the spell circle
- */
-data class SpellCircleContext(val impetusPos: BlockPos, val aabb: AABB, val activatorAlwaysInRange: Boolean) {
+/** Optional field on a [CastingEnvironment] for the spell circle */
+data class SpellCircleContext(
+ val impetusPos: BlockPos,
+ val aabb: AABB,
+ val activatorAlwaysInRange: Boolean
+) {
fun serializeToNBT() = NBTBuilder {
TAG_IMPETUS_X %= impetusPos.x
TAG_IMPETUS_Y %= impetusPos.y
@@ -50,7 +52,8 @@ data class SpellCircleContext(val impetusPos: BlockPos, val aabb: AABB, val acti
val playerAIR = tag.getBoolean(TAG_PLAYER_ALWAYS_IN_RANGE)
- return SpellCircleContext(BlockPos(impX, impY, impZ), AABB(minX, minY, minZ, maxX, maxY, maxZ), playerAIR)
+ return SpellCircleContext(
+ BlockPos(impX, impY, impZ), AABB(minX, minY, minZ, maxX, maxY, maxZ), playerAIR)
}
}
}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/CircleCastEnv.java b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/CircleCastEnv.java
index d1d542780d..c24cd54309 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/CircleCastEnv.java
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/CircleCastEnv.java
@@ -1,5 +1,7 @@
package at.petrak.hexcasting.api.casting.eval.env;
+import static at.petrak.hexcasting.api.casting.eval.env.PlayerBasedCastEnv.SENTINEL_RADIUS;
+
import at.petrak.hexcasting.api.HexAPI;
import at.petrak.hexcasting.api.casting.ParticleSpray;
import at.petrak.hexcasting.api.casting.PatternShapeMatch;
@@ -13,6 +15,7 @@
import at.petrak.hexcasting.api.casting.mishaps.MishapDisallowedSpell;
import at.petrak.hexcasting.api.mod.HexConfig;
import at.petrak.hexcasting.api.pigment.FrozenPigment;
+
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
@@ -23,14 +26,13 @@
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.Vec3;
+
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
-import static at.petrak.hexcasting.api.casting.eval.env.PlayerBasedCastEnv.SENTINEL_RADIUS;
-
public class CircleCastEnv extends CastingEnvironment {
protected final CircleExecutionState execState;
@@ -96,7 +98,8 @@ public void postExecution(CastResult result) {
if (imp != null) {
for (var sideEffect : result.getSideEffects()) {
if (sideEffect instanceof OperatorSideEffect.DoMishap doMishap) {
- var msg = doMishap.getMishap().errorMessageWithName(this, doMishap.getErrorCtx());
+ var msg =
+ doMishap.getMishap().errorMessageWithName(this, doMishap.getErrorCtx());
if (msg != null) {
imp.postMishap(msg);
}
@@ -113,12 +116,10 @@ public Vec3 mishapSprayPos() {
@Override
public long extractMediaEnvironment(long cost, boolean simulate) {
var entity = this.getImpetus();
- if (entity == null)
- return cost;
+ if (entity == null) return cost;
var mediaAvailable = entity.getMedia();
- if (mediaAvailable < 0)
- return 0;
+ if (mediaAvailable < 0) return 0;
long mediaToTake = Math.min(cost, mediaAvailable);
cost -= mediaToTake;
@@ -133,16 +134,17 @@ public long extractMediaEnvironment(long cost, boolean simulate) {
public boolean isVecInRangeEnvironment(Vec3 vec) {
var caster = this.execState.getCaster(this.world);
if (caster != null) {
- if (vec.distanceToSqr(caster.position()) <= caster.getBbHeight() * caster.getBbHeight()) {
+ if (vec.distanceToSqr(caster.position())
+ <= caster.getBbHeight() * caster.getBbHeight()) {
return true;
}
var sentinel = HexAPI.instance().getSentinel(caster);
if (sentinel != null
- && sentinel.extendsRange()
- && caster.level().dimension() == sentinel.dimension()
- && vec.distanceToSqr(sentinel.position()) <= SENTINEL_RADIUS * SENTINEL_RADIUS + 0.00000000001
- ) {
+ && sentinel.extendsRange()
+ && caster.level().dimension() == sentinel.dimension()
+ && vec.distanceToSqr(sentinel.position())
+ <= SENTINEL_RADIUS * SENTINEL_RADIUS + 0.00000000001) {
return true;
}
}
@@ -153,7 +155,7 @@ public boolean isVecInRangeEnvironment(Vec3 vec) {
@Override
public boolean isEnlightened() {
// have unbound circles be enlightened.
- if(getCastingEntity() == null) return true;
+ if (getCastingEntity() == null) return true;
return super.isEnlightened();
}
@@ -170,8 +172,7 @@ public InteractionHand getCastingHand() {
@Override
// TODO: Could do something like get items in inventories adjacent to the circle?
protected List getUsableStacks(StackDiscoveryMode mode) {
- if (this.getCaster() != null)
- return getUsableStacksForPlayer(mode, null, this.getCaster());
+ if (this.getCaster() != null) return getUsableStacksForPlayer(mode, null, this.getCaster());
return new ArrayList<>();
}
@@ -185,7 +186,8 @@ protected List getPrimaryStacks() {
@Override
// TODO: Adjacent inv!
- public boolean replaceItem(Predicate stackOk, ItemStack replaceWith, @Nullable InteractionHand hand) {
+ public boolean replaceItem(
+ Predicate stackOk, ItemStack replaceWith, @Nullable InteractionHand hand) {
if (this.getCaster() != null)
return replaceItemForPlayer(stackOk, replaceWith, hand, this.getCaster());
return false;
@@ -194,16 +196,14 @@ public boolean replaceItem(Predicate stackOk, ItemStack replaceWith,
@Override
public FrozenPigment getPigment() {
var impetus = this.getImpetus();
- if (impetus == null)
- return FrozenPigment.DEFAULT.get();
+ if (impetus == null) return FrozenPigment.DEFAULT.get();
return impetus.getPigment();
}
@Override
public @Nullable FrozenPigment setPigment(@Nullable FrozenPigment pigment) {
var impetus = this.getImpetus();
- if (impetus == null)
- return null;
+ if (impetus == null) return null;
return impetus.setPigment(pigment);
}
@@ -215,8 +215,7 @@ public void produceParticles(ParticleSpray particles, FrozenPigment pigment) {
@Override
public void printMessage(Component message) {
var impetus = getImpetus();
- if (impetus == null)
- return;
+ if (impetus == null) return;
impetus.postPrint(message);
}
}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/CircleMishapEnv.java b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/CircleMishapEnv.java
index 407f0eb307..52db6d5f26 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/CircleMishapEnv.java
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/CircleMishapEnv.java
@@ -2,6 +2,7 @@
import at.petrak.hexcasting.api.casting.circles.CircleExecutionState;
import at.petrak.hexcasting.api.casting.eval.MishapEnvironment;
+
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.phys.Vec3;
@@ -14,32 +15,20 @@ protected CircleMishapEnv(ServerLevel world, CircleExecutionState execState) {
}
@Override
- public void yeetHeldItemsTowards(Vec3 targetPos) {
-
- }
+ public void yeetHeldItemsTowards(Vec3 targetPos) {}
@Override
- public void dropHeldItems() {
-
- }
+ public void dropHeldItems() {}
@Override
- public void drown() {
-
- }
+ public void drown() {}
@Override
- public void damage(float healthProportion) {
-
- }
+ public void damage(float healthProportion) {}
@Override
- public void removeXp(int amount) {
-
- }
+ public void removeXp(int amount) {}
@Override
- public void blind(int ticks) {
-
- }
+ public void blind(int ticks) {}
}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/PackagedItemCastEnv.java b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/PackagedItemCastEnv.java
index 43d0c67d28..bdd4f749f0 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/PackagedItemCastEnv.java
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/PackagedItemCastEnv.java
@@ -7,6 +7,7 @@
import at.petrak.hexcasting.common.lib.hex.HexEvalSounds;
import at.petrak.hexcasting.common.msgs.MsgNewSpiralPatternsS2C;
import at.petrak.hexcasting.xplat.IXplatAbstractions;
+
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
@@ -25,9 +26,9 @@ public void postExecution(CastResult result) {
super.postExecution(result);
if (result.component1() instanceof PatternIota patternIota) {
- var packet = new MsgNewSpiralPatternsS2C(
- this.caster.getUUID(), List.of(patternIota.getPattern()), 140
- );
+ var packet =
+ new MsgNewSpiralPatternsS2C(
+ this.caster.getUUID(), List.of(patternIota.getPattern()), 140);
IXplatAbstractions.INSTANCE.sendPacketToPlayer(this.caster, packet);
IXplatAbstractions.INSTANCE.sendPacketTracking(this.caster, packet);
}
@@ -38,13 +39,11 @@ public void postExecution(CastResult result) {
@Override
public long extractMediaEnvironment(long costLeft, boolean simulate) {
- if (this.caster.isCreative())
- return 0;
+ if (this.caster.isCreative()) return 0;
var casterStack = this.caster.getItemInHand(this.castingHand);
var casterHexHolder = IXplatAbstractions.INSTANCE.findHexHolder(casterStack);
- if (casterHexHolder == null)
- return costLeft;
+ if (casterHexHolder == null) return costLeft;
var canCastFromInv = casterHexHolder.canDrawMediaFromInventory();
var casterMediaHolder = IXplatAbstractions.INSTANCE.findMediaHolder(casterStack);
@@ -71,11 +70,9 @@ public InteractionHand getCastingHand() {
public FrozenPigment getPigment() {
var casterStack = this.caster.getItemInHand(this.castingHand);
var casterHexHolder = IXplatAbstractions.INSTANCE.findHexHolder(casterStack);
- if (casterHexHolder == null)
- return IXplatAbstractions.INSTANCE.getPigment(this.caster);
+ if (casterHexHolder == null) return IXplatAbstractions.INSTANCE.getPigment(this.caster);
var hexHolderPigment = casterHexHolder.getPigment();
- if (hexHolderPigment != null)
- return hexHolderPigment;
+ if (hexHolderPigment != null) return hexHolderPigment;
return IXplatAbstractions.INSTANCE.getPigment(this.caster);
}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/PlayerBasedCastEnv.java b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/PlayerBasedCastEnv.java
index 10ff3b052b..6b69163d8f 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/PlayerBasedCastEnv.java
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/PlayerBasedCastEnv.java
@@ -1,5 +1,7 @@
package at.petrak.hexcasting.api.casting.eval.env;
+import static at.petrak.hexcasting.api.HexAPI.modLoc;
+
import at.petrak.hexcasting.api.HexAPI;
import at.petrak.hexcasting.api.addldata.ADMediaHolder;
import at.petrak.hexcasting.api.advancements.HexAdvancementTriggers;
@@ -12,28 +14,25 @@
import at.petrak.hexcasting.api.mod.HexConfig;
import at.petrak.hexcasting.api.mod.HexStatistics;
import at.petrak.hexcasting.api.pigment.FrozenPigment;
-import at.petrak.hexcasting.api.utils.HexUtils;
import at.petrak.hexcasting.api.utils.MediaHelper;
import at.petrak.hexcasting.common.lib.HexDamageTypes;
import at.petrak.hexcasting.xplat.IXplatAbstractions;
+
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.util.Mth;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.LivingEntity;
-import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.GameType;
import net.minecraft.world.phys.Vec3;
+
import org.jetbrains.annotations.Nullable;
-import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
-import static at.petrak.hexcasting.api.HexAPI.modLoc;
-
public abstract class PlayerBasedCastEnv extends CastingEnvironment {
public static final double AMBIT_RADIUS = 32.0;
public static final double SENTINEL_RADIUS = 16.0;
@@ -79,7 +78,8 @@ protected List getPrimaryStacks() {
}
@Override
- public boolean replaceItem(Predicate stackOk, ItemStack replaceWith, @Nullable InteractionHand hand) {
+ public boolean replaceItem(
+ Predicate stackOk, ItemStack replaceWith, @Nullable InteractionHand hand) {
return replaceItemForPlayer(stackOk, replaceWith, hand, this.caster);
}
@@ -87,26 +87,27 @@ public boolean replaceItem(Predicate stackOk, ItemStack replaceWith,
public boolean isVecInRangeEnvironment(Vec3 vec) {
var sentinel = HexAPI.instance().getSentinel(this.caster);
if (sentinel != null
- && sentinel.extendsRange()
- && this.caster.level().dimension() == sentinel.dimension()
+ && sentinel.extendsRange()
+ && this.caster.level().dimension() == sentinel.dimension()
// adding 0.00000000001 to avoid machine precision errors at specific angles
- && vec.distanceToSqr(sentinel.position()) <= SENTINEL_RADIUS * SENTINEL_RADIUS + 0.00000000001
- ) {
+ && vec.distanceToSqr(sentinel.position())
+ <= SENTINEL_RADIUS * SENTINEL_RADIUS + 0.00000000001) {
return true;
}
- return vec.distanceToSqr(this.caster.position()) <= AMBIT_RADIUS * AMBIT_RADIUS + 0.00000000001;
+ return vec.distanceToSqr(this.caster.position())
+ <= AMBIT_RADIUS * AMBIT_RADIUS + 0.00000000001;
}
@Override
public boolean hasEditPermissionsAtEnvironment(BlockPos pos) {
- return this.caster.gameMode.getGameModeForPlayer() != GameType.ADVENTURE && this.world.mayInteract(this.caster, pos);
+ return this.caster.gameMode.getGameModeForPlayer() != GameType.ADVENTURE
+ && this.world.mayInteract(this.caster, pos);
}
- /**
- * Search the player's inventory for media ADs and use them.
- */
- protected long extractMediaFromInventory(long costLeft, boolean allowOvercast, boolean simulate) {
+ /** Search the player's inventory for media ADs and use them. */
+ protected long extractMediaFromInventory(
+ long costLeft, boolean allowOvercast, boolean simulate) {
List sources = MediaHelper.scanPlayerForMediaStuff(this.caster);
var startCost = costLeft;
@@ -123,14 +124,19 @@ protected long extractMediaFromInventory(long costLeft, boolean allowOvercast, b
double mediaToHealth = HexConfig.common().mediaToHealthRate();
double healthToRemove = Math.max(costLeft / mediaToHealth, 0.5);
if (simulate) {
- long simulatedRemovedMedia = Mth.ceil(Math.min(this.caster.getHealth(), healthToRemove) * mediaToHealth);
+ long simulatedRemovedMedia =
+ Mth.ceil(Math.min(this.caster.getHealth(), healthToRemove) * mediaToHealth);
costLeft -= simulatedRemovedMedia;
} else {
var mediaAbleToCastFromHP = this.caster.getHealth() * mediaToHealth;
- Mishap.trulyHurt(this.caster, this.caster.damageSources().source(HexDamageTypes.OVERCAST), (float) healthToRemove);
+ Mishap.trulyHurt(
+ this.caster,
+ this.caster.damageSources().source(HexDamageTypes.OVERCAST),
+ (float) healthToRemove);
- var actuallyTaken = Mth.ceil(mediaAbleToCastFromHP - (this.caster.getHealth() * mediaToHealth));
+ var actuallyTaken =
+ Mth.ceil(mediaAbleToCastFromHP - (this.caster.getHealth() * mediaToHealth));
HexAdvancementTriggers.OVERCAST_TRIGGER.trigger(this.caster, actuallyTaken);
this.caster.awardStat(HexStatistics.MEDIA_OVERCAST, actuallyTaken);
@@ -142,17 +148,15 @@ protected long extractMediaFromInventory(long costLeft, boolean allowOvercast, b
if (!simulate) {
this.caster.awardStat(HexStatistics.MEDIA_USED, (int) (startCost - costLeft));
HexAdvancementTriggers.SPEND_MEDIA_TRIGGER.trigger(
- this.caster,
- startCost - costLeft,
- costLeft < 0 ? -costLeft : 0
- );
+ this.caster, startCost - costLeft, costLeft < 0 ? -costLeft : 0);
}
return costLeft;
}
protected boolean canOvercast() {
- var adv = this.world.getServer().getAdvancements().getAdvancement(modLoc("y_u_no_cast_angy"));
+ var adv =
+ this.world.getServer().getAdvancements().getAdvancement(modLoc("y_u_no_cast_angy"));
var advs = this.caster.getAdvancements();
return advs.getOrStartProgress(adv).isDone();
}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/PlayerBasedMishapEnv.java b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/PlayerBasedMishapEnv.java
index 370ba5002a..81025a9534 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/PlayerBasedMishapEnv.java
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/PlayerBasedMishapEnv.java
@@ -3,6 +3,7 @@
import at.petrak.hexcasting.api.casting.eval.MishapEnvironment;
import at.petrak.hexcasting.api.casting.mishaps.Mishap;
import at.petrak.hexcasting.common.lib.HexDamageTypes;
+
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.effect.MobEffectInstance;
@@ -35,7 +36,10 @@ public void dropHeldItems() {
@Override
public void damage(float healthProportion) {
- Mishap.trulyHurt(this.caster, this.caster.damageSources().source(HexDamageTypes.OVERCAST), this.caster.getHealth() * healthProportion);
+ Mishap.trulyHurt(
+ this.caster,
+ this.caster.damageSources().source(HexDamageTypes.OVERCAST),
+ this.caster.getHealth() * healthProportion);
}
@Override
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/StaffCastEnv.java b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/StaffCastEnv.java
index 29e80d3817..091cf58f6f 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/StaffCastEnv.java
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/StaffCastEnv.java
@@ -13,7 +13,7 @@
import at.petrak.hexcasting.api.pigment.FrozenPigment;
import at.petrak.hexcasting.common.msgs.*;
import at.petrak.hexcasting.xplat.IXplatAbstractions;
-import net.minecraft.network.chat.Component;
+
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand;
@@ -29,7 +29,6 @@ public class StaffCastEnv extends PlayerBasedCastEnv {
private final Set castPatterns = new HashSet<>();
private int soundsPlayed = 0;
-
public StaffCastEnv(ServerPlayer caster, InteractionHand castingHand) {
super(caster, castingHand);
@@ -48,8 +47,8 @@ public void postExecution(CastResult result) {
var sound = result.getSound().sound();
if (soundsPlayed < 100 && sound != null) { // TODO: Make configurable
var soundPos = this.caster.position();
- this.world.playSound(null, soundPos.x, soundPos.y, soundPos.z,
- sound, SoundSource.PLAYERS, 1f, 1f);
+ this.world.playSound(
+ null, soundPos.x, soundPos.y, soundPos.z, sound, SoundSource.PLAYERS, 1f, 1f);
soundsPlayed++;
}
}
@@ -58,9 +57,9 @@ public void postExecution(CastResult result) {
public void postCast(CastingImage image) {
super.postCast(image);
- var packet = new MsgNewSpiralPatternsS2C(
- this.caster.getUUID(), castPatterns.stream().toList(), Integer.MAX_VALUE
- );
+ var packet =
+ new MsgNewSpiralPatternsS2C(
+ this.caster.getUUID(), castPatterns.stream().toList(), Integer.MAX_VALUE);
IXplatAbstractions.INSTANCE.sendPacketToPlayer(this.caster, packet);
IXplatAbstractions.INSTANCE.sendPacketTracking(this.caster, packet);
@@ -70,8 +69,7 @@ public void postCast(CastingImage image) {
@Override
public long extractMediaEnvironment(long cost, boolean simulate) {
- if (this.caster.isCreative())
- return 0;
+ if (this.caster.isCreative()) return 0;
var canOvercast = this.canOvercast();
return this.extractMediaFromInventory(cost, canOvercast, simulate);
@@ -98,8 +96,10 @@ public static void handleNewPatternOnServer(ServerPlayer sender, MsgNewSpellPatt
allPoints.addAll(pat.getPattern().positions(pat.getOrigin()));
}
var currentResolvedPattern = resolvedPatterns.get(resolvedPatterns.size() - 1);
- var currentSpellPoints = currentResolvedPattern.getPattern()
- .positions(currentResolvedPattern.getOrigin());
+ var currentSpellPoints =
+ currentResolvedPattern
+ .getPattern()
+ .positions(currentResolvedPattern.getOrigin());
if (currentSpellPoints.stream().anyMatch(allPoints::contains)) {
cheatedPatternOverlap = true;
}
@@ -113,29 +113,36 @@ public static void handleNewPatternOnServer(ServerPlayer sender, MsgNewSpellPatt
var vm = IXplatAbstractions.INSTANCE.getStaffcastVM(sender, msg.handUsed());
- // TODO: do we reset the number of evals run via the staff? because each new pat is a new tick.
+ // TODO: do we reset the number of evals run via the staff? because each new pat is a new
+ // tick.
- ExecutionClientView clientInfo = vm.queueExecuteAndWrapIota(new PatternIota(msg.pattern()), sender.serverLevel());
+ ExecutionClientView clientInfo =
+ vm.queueExecuteAndWrapIota(new PatternIota(msg.pattern()), sender.serverLevel());
if (clientInfo.isStackClear()) {
IXplatAbstractions.INSTANCE.setStaffcastImage(sender, null);
IXplatAbstractions.INSTANCE.setPatterns(sender, List.of());
} else {
- IXplatAbstractions.INSTANCE.setStaffcastImage(sender, vm.getImage().withOverriddenUsedOps(0));
+ IXplatAbstractions.INSTANCE.setStaffcastImage(
+ sender, vm.getImage().withOverriddenUsedOps(0));
if (!resolvedPatterns.isEmpty()) {
- resolvedPatterns.get(resolvedPatterns.size() - 1).setType(clientInfo.getResolutionType());
+ resolvedPatterns
+ .get(resolvedPatterns.size() - 1)
+ .setType(clientInfo.getResolutionType());
}
IXplatAbstractions.INSTANCE.setPatterns(sender, resolvedPatterns);
}
- IXplatAbstractions.INSTANCE.sendPacketToPlayer(sender,
- new MsgNewSpellPatternS2C(clientInfo, resolvedPatterns.size() - 1));
+ IXplatAbstractions.INSTANCE.sendPacketToPlayer(
+ sender, new MsgNewSpellPatternS2C(clientInfo, resolvedPatterns.size() - 1));
IMessage packet;
if (clientInfo.isStackClear()) {
packet = new MsgClearSpiralPatternsS2C(sender.getUUID());
} else {
- packet = new MsgNewSpiralPatternsS2C(sender.getUUID(), List.of(msg.pattern()), Integer.MAX_VALUE);
+ packet =
+ new MsgNewSpiralPatternsS2C(
+ sender.getUUID(), List.of(msg.pattern()), Integer.MAX_VALUE);
}
IXplatAbstractions.INSTANCE.sendPacketToPlayer(sender, packet);
IXplatAbstractions.INSTANCE.sendPacketTracking(sender, packet);
@@ -144,7 +151,8 @@ public static void handleNewPatternOnServer(ServerPlayer sender, MsgNewSpellPatt
// Somehow we lost spraying particles on each new pattern, so do it here
// this also nicely prevents particle spam on trinkets
new ParticleSpray(sender.position(), new Vec3(0.0, 1.5, 0.0), 0.4, Math.PI / 3, 30)
- .sprayParticles(sender.serverLevel(), IXplatAbstractions.INSTANCE.getPigment(sender));
+ .sprayParticles(
+ sender.serverLevel(), IXplatAbstractions.INSTANCE.getPigment(sender));
}
}
}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/package-info.java b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/package-info.java
index 036bb48b23..7818f29677 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/package-info.java
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/env/package-info.java
@@ -2,4 +2,4 @@
* Default impls for some casting and mishap envs for your convenience and also so i can impl
* BlockEntityAbstractImpetus in api guilt-free
*/
-package at.petrak.hexcasting.api.casting.eval.env;
\ No newline at end of file
+package at.petrak.hexcasting.api.casting.eval.env;
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/sideeffects/EvalSound.java b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/sideeffects/EvalSound.java
index f81a34eb3f..b66d2c6086 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/sideeffects/EvalSound.java
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/sideeffects/EvalSound.java
@@ -1,15 +1,15 @@
package at.petrak.hexcasting.api.casting.eval.sideeffects;
import net.minecraft.sounds.SoundEvent;
+
import org.jetbrains.annotations.Nullable;
/**
* The kind of sound that plays after a cast.
*
- * @param sound the actual sound file
- * @param priority the priority of this sound. the sound with the highest priority in a given cast will be
- * played.
- * shortcutMetacasting takes precedence over this.
+ * @param sound the actual sound file
+ * @param priority the priority of this sound. the sound with the highest priority in a given cast
+ * will be played. shortcutMetacasting takes precedence over this.
*/
public record EvalSound(@Nullable SoundEvent sound, int priority) {
public EvalSound greaterOf(EvalSound that) {
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/sideeffects/OperatorSideEffect.kt b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/sideeffects/OperatorSideEffect.kt
index 72226fe291..927e67dc17 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/sideeffects/OperatorSideEffect.kt
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/sideeffects/OperatorSideEffect.kt
@@ -13,26 +13,24 @@ import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.item.DyeColor
import net.minecraft.world.item.ItemStack
-/**
- * Things that happen after a spell is cast.
- */
+/** Things that happen after a spell is cast. */
sealed class OperatorSideEffect {
/** Return whether to cancel all further [OperatorSideEffect] */
abstract fun performEffect(harness: CastingVM)
data class RequiredEnlightenment(val awardStat: Boolean) : OperatorSideEffect() {
override fun performEffect(harness: CastingVM) {
- harness.env.castingEntity?.sendSystemMessage("hexcasting.message.cant_great_spell".asTranslatedComponent)
+ harness.env.castingEntity?.sendSystemMessage(
+ "hexcasting.message.cant_great_spell".asTranslatedComponent)
}
}
- /** Try to cast a spell */
+ /** Try to cast a spell */
data class AttemptSpell(
val spell: RenderedSpell,
val hasCastingSound: Boolean = true,
val awardStat: Boolean = true
- ) :
- OperatorSideEffect() {
+ ) : OperatorSideEffect() {
override fun performEffect(harness: CastingVM) {
this.spell.cast(harness.env, harness.image)?.let { harness.image = it }
if (awardStat)
@@ -49,7 +47,7 @@ sealed class OperatorSideEffect {
data class Particles(val spray: ParticleSpray) : OperatorSideEffect() {
override fun performEffect(harness: CastingVM) {
harness.env.produceParticles(this.spray, harness.env.pigment)
-// this.spray.sprayParticles(harness.env.world, harness.env.colorizer)
+ // this.spray.sprayParticles(harness.env.world, harness.env.colorizer)
}
}
@@ -60,13 +58,13 @@ sealed class OperatorSideEffect {
spray.sprayParticles(harness.env.world, color)
spray.sprayParticles(
harness.env.world,
- FrozenPigment(
- ItemStack(HexItems.DYE_PIGMENTS[DyeColor.RED]!!),
- Util.NIL_UUID
- )
- )
+ FrozenPigment(ItemStack(HexItems.DYE_PIGMENTS[DyeColor.RED]!!), Util.NIL_UUID))
- harness.image = harness.image.copy(stack = mishap.executeReturnStack(harness.env, errorCtx, harness.image.stack.toMutableList()))
+ harness.image =
+ harness.image.copy(
+ stack =
+ mishap.executeReturnStack(
+ harness.env, errorCtx, harness.image.stack.toMutableList()))
}
}
}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/CastingImage.kt b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/CastingImage.kt
index 3ffd771bcd..f0f93268e2 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/CastingImage.kt
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/CastingImage.kt
@@ -13,17 +13,14 @@ import net.minecraft.nbt.Tag
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.entity.Entity
-/**
- * The state of a casting VM, containing the stack and all
- */
-data class CastingImage private constructor(
+/** The state of a casting VM, containing the stack and all */
+data class CastingImage
+private constructor(
val stack: List,
-
val parenCount: Int,
val parenthesized: List,
val escapeNext: Boolean,
val opsConsumed: Long,
-
val userData: CompoundTag
) {
constructor() : this(listOf(), 0, listOf(), false, 0, CompoundTag())
@@ -35,9 +32,7 @@ data class CastingImage private constructor(
}
}
- /**
- * Returns an empty list if it's too complicated.
- */
+ /** Returns an empty list if it's too complicated. */
private fun Iterable.serializeToNBT(): CompoundTag {
val tag = CompoundTag()
@@ -52,24 +47,16 @@ data class CastingImage private constructor(
return tag
}
- /**
- * Return a copy of this with the given number of ops additionally exhausted
- */
+ /** Return a copy of this with the given number of ops additionally exhausted */
fun withUsedOps(count: Long) = this.copy(opsConsumed = this.opsConsumed + count)
- /**
- * Return a copy of this with 1 op used
- */
+ /** Return a copy of this with 1 op used */
fun withUsedOp() = this.withUsedOps(1)
- /**
- * Returns a copy of this with the [opsConsumed] replaced with [count].
- */
+ /** Returns a copy of this with the [opsConsumed] replaced with [count]. */
fun withOverriddenUsedOps(count: Long) = this.copy(opsConsumed = count)
- /**
- * Returns a copy of this with escape/paren-related fields cleared.
- */
+ /** Returns a copy of this with escape/paren-related fields cleared. */
fun withResetEscape() = this.copy(parenCount = 0, parenthesized = listOf(), escapeNext = false)
fun serializeToNbt() = NBTBuilder {
@@ -101,19 +88,24 @@ data class CastingImage private constructor(
stack.add(datum)
}
- val userData = if (tag.contains(TAG_USERDATA)) {
- tag.getCompound(TAG_USERDATA)
- } else {
- CompoundTag()
- }
+ val userData =
+ if (tag.contains(TAG_USERDATA)) {
+ tag.getCompound(TAG_USERDATA)
+ } else {
+ CompoundTag()
+ }
val parenthesized = mutableListOf()
val parenTag = tag.getCompound(TAG_PARENTHESIZED)
val parenIotasTag = parenTag.getList(TAG_IOTAS, Tag.TAG_COMPOUND)
val parenEscapedTag = parenTag.getByteArray(TAG_ESCAPED)
- for ((subtag, isEscapedByte) in parenIotasTag.zipWithDefault(parenEscapedTag) { _ -> 0 }) {
- parenthesized.add(ParenthesizedIota(IotaType.deserialize(subtag.downcast(CompoundTag.TYPE), world), isEscapedByte != 0.toByte()))
+ for ((subtag, isEscapedByte) in
+ parenIotasTag.zipWithDefault(parenEscapedTag) { _ -> 0 }) {
+ parenthesized.add(
+ ParenthesizedIota(
+ IotaType.deserialize(subtag.downcast(CompoundTag.TYPE), world),
+ isEscapedByte != 0.toByte()))
}
val parenCount = tag.getInt(TAG_PAREN_COUNT)
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/CastingVM.kt b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/CastingVM.kt
index 587500355b..ee64b92b1c 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/CastingVM.kt
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/CastingVM.kt
@@ -19,28 +19,28 @@ import net.minecraft.nbt.CompoundTag
import net.minecraft.server.level.ServerLevel
/**
- * The virtual machine! This is the glue that determines the next iteration of a [CastingImage], using a
- * [CastingEnvironment] to affect the world.
+ * The virtual machine! This is the glue that determines the next iteration of a [CastingImage],
+ * using a [CastingEnvironment] to affect the world.
*/
class CastingVM(var image: CastingImage, val env: CastingEnvironment) {
init {
env.triggerCreateEvent(image.userData)
}
- /**
- * Execute a single iota.
- */
- fun queueExecuteAndWrapIota(iota: Iota, world: ServerLevel): ExecutionClientView = queueExecuteAndWrapIotas(listOf(iota), world)
+ /** Execute a single iota. */
+ fun queueExecuteAndWrapIota(iota: Iota, world: ServerLevel): ExecutionClientView =
+ queueExecuteAndWrapIotas(listOf(iota), world)
/**
- * The main entrypoint to the VM. Given a list of iotas, execute them in sequence, and return whatever the client
- * needs to see.
+ * The main entrypoint to the VM. Given a list of iotas, execute them in sequence, and return
+ * whatever the client needs to see.
*
* Mutates this
*/
fun queueExecuteAndWrapIotas(iotas: List, world: ServerLevel): ExecutionClientView {
// Initialize the continuation stack to a single top-level eval for all iotas.
- var continuation = SpellContinuation.Done.pushFrame(FrameEvaluate(SpellList.LList(0, iotas), false))
+ var continuation =
+ SpellContinuation.Done.pushFrame(FrameEvaluate(SpellList.LList(0, iotas), false))
// Begin aggregating info
val info = TempControllerInfo(earlyExit = false)
var lastResolutionType = ResolvedPatternType.UNRESOLVED
@@ -48,21 +48,27 @@ class CastingVM(var image: CastingImage, val env: CastingEnvironment) {
// Take the top of the continuation stack...
val next = continuation.frame
// ...and execute it.
- // TODO there used to be error checking code here; I'm pretty sure any and all mishaps should already
+ // TODO there used to be error checking code here; I'm pretty sure any and all mishaps
+ // should already
// get caught and folded into CastResult by evaluate.
- val image2 = next.evaluate(continuation.next, world, this).let { result ->
- // if stack is unable to be serialized, have the result be an error
- if (result.newData != null && IotaType.isTooLargeToSerialize(result.newData.stack)) {
- result.copy(
- newData = null,
- sideEffects = listOf(OperatorSideEffect.DoMishap(MishapStackSize(), Mishap.Context(null, null))),
- resolutionType = ResolvedPatternType.ERRORED,
- sound = HexEvalSounds.MISHAP,
- )
- } else {
- result
+ val image2 =
+ next.evaluate(continuation.next, world, this).let { result ->
+ // if stack is unable to be serialized, have the result be an error
+ if (result.newData != null &&
+ IotaType.isTooLargeToSerialize(result.newData.stack)) {
+ result.copy(
+ newData = null,
+ sideEffects =
+ listOf(
+ OperatorSideEffect.DoMishap(
+ MishapStackSize(), Mishap.Context(null, null))),
+ resolutionType = ResolvedPatternType.ERRORED,
+ sound = HexEvalSounds.MISHAP,
+ )
+ } else {
+ result
+ }
}
- }
// Then write all pertinent data back to the harness for the next iteration.
if (image2.newData != null) {
@@ -76,27 +82,30 @@ class CastingVM(var image: CastingImage, val env: CastingEnvironment) {
performSideEffects(image2.sideEffects)
} catch (e: Exception) {
e.printStackTrace()
- performSideEffects(listOf(OperatorSideEffect.DoMishap(MishapInternalException(e), Mishap.Context(null, null))))
+ performSideEffects(
+ listOf(
+ OperatorSideEffect.DoMishap(
+ MishapInternalException(e), Mishap.Context(null, null))))
}
info.earlyExit = info.earlyExit || !lastResolutionType.success
}
if (continuation is SpellContinuation.NotDone) {
lastResolutionType =
- if (lastResolutionType.success) ResolvedPatternType.EVALUATED else ResolvedPatternType.ERRORED
+ if (lastResolutionType.success) ResolvedPatternType.EVALUATED
+ else ResolvedPatternType.ERRORED
}
val (stackDescs, ravenmind) = generateDescs()
- val isStackClear = image.stack.isEmpty() && image.parenCount == 0 && !image.escapeNext && ravenmind == null
+ val isStackClear =
+ image.stack.isEmpty() && image.parenCount == 0 && !image.escapeNext && ravenmind == null
this.env.postCast(image)
return ExecutionClientView(isStackClear, lastResolutionType, stackDescs, ravenmind)
}
- /**
- * this DOES NOT THROW THINGS
- */
+ /** this DOES NOT THROW THINGS */
@Throws()
fun executeInner(iota: Iota, world: ServerLevel, continuation: SpellContinuation): CastResult {
try {
@@ -104,7 +113,13 @@ class CastingVM(var image: CastingImage, val env: CastingEnvironment) {
// ALSO TODO need to add reader macro-style things
try {
this.handleParentheses(iota)?.let { (data, resolutionType) ->
- return@executeInner CastResult(iota, continuation, data, listOf(), resolutionType, HexEvalSounds.NORMAL_EXECUTE)
+ return@executeInner CastResult(
+ iota,
+ continuation,
+ data,
+ listOf(),
+ resolutionType,
+ HexEvalSounds.NORMAL_EXECUTE)
}
} catch (e: MishapTooManyCloseParens) {
// This is ridiculous and needs to be fixed
@@ -117,13 +132,9 @@ class CastingVM(var image: CastingImage, val env: CastingEnvironment) {
e,
Mishap.Context(
(iota as? PatternIota)?.pattern ?: HexPattern(HexDir.WEST),
- HexAPI.instance().getRawHookI18n(HexAPI.modLoc("close_paren"))
- )
- )
- ),
+ HexAPI.instance().getRawHookI18n(HexAPI.modLoc("close_paren"))))),
ResolvedPatternType.ERRORED,
- HexEvalSounds.MISHAP
- )
+ HexEvalSounds.MISHAP)
}
return iota.execute(this, world, continuation)
@@ -138,20 +149,13 @@ class CastingVM(var image: CastingImage, val env: CastingEnvironment) {
OperatorSideEffect.DoMishap(
MishapInternalException(exception),
Mishap.Context(
- (iota as? PatternIota)?.pattern ?: HexPattern(HexDir.WEST),
- null
- )
- )
- ),
+ (iota as? PatternIota)?.pattern ?: HexPattern(HexDir.WEST), null))),
ResolvedPatternType.ERRORED,
- HexEvalSounds.MISHAP
- )
+ HexEvalSounds.MISHAP)
}
}
- /**
- * Execute the side effects of a pattern, updating our aggregated info.
- */
+ /** Execute the side effects of a pattern, updating our aggregated info. */
fun performSideEffects(sideEffects: List) {
for (haskellProgrammersShakingandCryingRN in sideEffects) {
haskellProgrammersShakingandCryingRN.performEffect(this)
@@ -160,15 +164,16 @@ class CastingVM(var image: CastingImage, val env: CastingEnvironment) {
fun generateDescs(): Pair, CompoundTag?> {
val stackDescs = this.image.stack.map { IotaType.serialize(it) }
- val ravenmind = if (this.image.userData.contains(HexAPI.RAVENMIND_USERDATA)) {
- this.image.userData.getCompound(HexAPI.RAVENMIND_USERDATA)
- } else null
+ val ravenmind =
+ if (this.image.userData.contains(HexAPI.RAVENMIND_USERDATA)) {
+ this.image.userData.getCompound(HexAPI.RAVENMIND_USERDATA)
+ } else null
return Pair(stackDescs, ravenmind)
}
/**
- * Return a non-null value if we handled this in some sort of parenthesey way,
- * either escaping it onto the stack or changing the parenthese-handling state.
+ * Return a non-null value if we handled this in some sort of parenthesey way, either escaping
+ * it onto the stack or changing the parenthese-handling state.
*/
@Throws(MishapTooManyCloseParens::class)
private fun handleParentheses(iota: Iota): Pair? {
@@ -176,108 +181,111 @@ class CastingVM(var image: CastingImage, val env: CastingEnvironment) {
var displayDepth = this.image.parenCount
- val out = if (displayDepth > 0) {
- if (this.image.escapeNext) {
- val newParens = this.image.parenthesized.toMutableList()
- newParens.add(ParenthesizedIota(iota, true))
+ val out =
+ if (displayDepth > 0) {
+ if (this.image.escapeNext) {
+ val newParens = this.image.parenthesized.toMutableList()
+ newParens.add(ParenthesizedIota(iota, true))
+ this.image.copy(escapeNext = false, parenthesized = newParens) to
+ ResolvedPatternType.ESCAPED
+ } else {
+
+ when (sig) {
+ SpecialPatterns.CONSIDERATION.angles -> {
+ this.image.copy(
+ escapeNext = true,
+ ) to ResolvedPatternType.EVALUATED
+ }
+
+ SpecialPatterns.EVANITION.angles -> {
+ val newParens = this.image.parenthesized.toMutableList()
+ val last = newParens.removeLastOrNull()
+ val newParenCount =
+ this.image.parenCount +
+ if (last == null || last.escaped || last.iota !is PatternIota) 0
+ else
+ when (last.iota.pattern) {
+ SpecialPatterns.INTROSPECTION -> -1
+ SpecialPatterns.RETROSPECTION -> 1
+ else -> 0
+ }
+ this.image.copy(
+ parenthesized = newParens, parenCount = newParenCount) to
+ if (last == null) ResolvedPatternType.ERRORED
+ else ResolvedPatternType.UNDONE
+ }
+
+ SpecialPatterns.INTROSPECTION.angles -> {
+ // we have escaped the parens onto the stack; we just also record our
+ // count.
+ val newParens = this.image.parenthesized.toMutableList()
+ newParens.add(ParenthesizedIota(iota, false))
+ this.image.copy(
+ parenthesized = newParens,
+ parenCount = this.image.parenCount + 1) to
+ if (this.image.parenCount == 0) ResolvedPatternType.EVALUATED
+ else ResolvedPatternType.ESCAPED
+ }
+
+ SpecialPatterns.RETROSPECTION.angles -> {
+ val newParenCount = this.image.parenCount - 1
+ displayDepth--
+ if (newParenCount == 0) {
+ val newStack = this.image.stack.toMutableList()
+ newStack.add(
+ ListIota(this.image.parenthesized.toList().map { it.iota }))
+ this.image.copy(
+ stack = newStack,
+ parenCount = newParenCount,
+ parenthesized = listOf()) to ResolvedPatternType.EVALUATED
+ } else if (newParenCount < 0) {
+ throw MishapTooManyCloseParens()
+ } else {
+ // we have this situation: "(()"
+ // we need to add the close paren
+ val newParens = this.image.parenthesized.toMutableList()
+ newParens.add(ParenthesizedIota(iota, false))
+ this.image.copy(
+ parenCount = newParenCount, parenthesized = newParens) to
+ ResolvedPatternType.ESCAPED
+ }
+ }
+
+ else -> {
+ val newParens = this.image.parenthesized.toMutableList()
+ newParens.add(ParenthesizedIota(iota, false))
+ this.image.copy(parenthesized = newParens) to
+ ResolvedPatternType.ESCAPED
+ }
+ }
+ }
+ } else if (this.image.escapeNext) {
+ val newStack = this.image.stack.toMutableList()
+ newStack.add(iota)
this.image.copy(
+ stack = newStack,
escapeNext = false,
- parenthesized = newParens
) to ResolvedPatternType.ESCAPED
} else {
-
when (sig) {
SpecialPatterns.CONSIDERATION.angles -> {
- this.image.copy(
- escapeNext = true,
- ) to ResolvedPatternType.EVALUATED
- }
-
- SpecialPatterns.EVANITION.angles -> {
- val newParens = this.image.parenthesized.toMutableList()
- val last = newParens.removeLastOrNull()
- val newParenCount = this.image.parenCount + if (last == null || last.escaped || last.iota !is PatternIota) 0 else when (last.iota.pattern) {
- SpecialPatterns.INTROSPECTION -> -1
- SpecialPatterns.RETROSPECTION -> 1
- else -> 0
- }
- this.image.copy(parenthesized = newParens, parenCount = newParenCount) to if (last == null) ResolvedPatternType.ERRORED else ResolvedPatternType.UNDONE
+ this.image.copy(escapeNext = true) to ResolvedPatternType.EVALUATED
}
SpecialPatterns.INTROSPECTION.angles -> {
- // we have escaped the parens onto the stack; we just also record our count.
- val newParens = this.image.parenthesized.toMutableList()
- newParens.add(ParenthesizedIota(iota, false))
- this.image.copy(
- parenthesized = newParens,
- parenCount = this.image.parenCount + 1
- ) to if (this.image.parenCount == 0) ResolvedPatternType.EVALUATED else ResolvedPatternType.ESCAPED
+ this.image.copy(parenCount = this.image.parenCount + 1) to
+ ResolvedPatternType.EVALUATED
}
SpecialPatterns.RETROSPECTION.angles -> {
- val newParenCount = this.image.parenCount - 1
- displayDepth--
- if (newParenCount == 0) {
- val newStack = this.image.stack.toMutableList()
- newStack.add(ListIota(this.image.parenthesized.toList().map { it.iota }))
- this.image.copy(
- stack = newStack,
- parenCount = newParenCount,
- parenthesized = listOf()
- ) to ResolvedPatternType.EVALUATED
- } else if (newParenCount < 0) {
- throw MishapTooManyCloseParens()
- } else {
- // we have this situation: "(()"
- // we need to add the close paren
- val newParens = this.image.parenthesized.toMutableList()
- newParens.add(ParenthesizedIota(iota, false))
- this.image.copy(
- parenCount = newParenCount,
- parenthesized = newParens
- ) to ResolvedPatternType.ESCAPED
- }
+ throw MishapTooManyCloseParens()
}
else -> {
- val newParens = this.image.parenthesized.toMutableList()
- newParens.add(ParenthesizedIota(iota, false))
- this.image.copy(
- parenthesized = newParens
- ) to ResolvedPatternType.ESCAPED
+ null
}
}
}
- } else if (this.image.escapeNext) {
- val newStack = this.image.stack.toMutableList()
- newStack.add(iota)
- this.image.copy(
- stack = newStack,
- escapeNext = false,
- ) to ResolvedPatternType.ESCAPED
- } else {
- when (sig) {
- SpecialPatterns.CONSIDERATION.angles -> {
- this.image.copy(
- escapeNext = true
- ) to ResolvedPatternType.EVALUATED
- }
-
- SpecialPatterns.INTROSPECTION.angles -> {
- this.image.copy(
- parenCount = this.image.parenCount + 1
- ) to ResolvedPatternType.EVALUATED
- }
-
- SpecialPatterns.RETROSPECTION.angles -> {
- throw MishapTooManyCloseParens()
- }
-
- else -> {
- null
- }
- }
- }
// TODO: replace this once we can read things from the client
/*
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/ContinuationFrame.kt b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/ContinuationFrame.kt
index 8000ec09aa..d7b23e2364 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/ContinuationFrame.kt
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/ContinuationFrame.kt
@@ -12,38 +12,44 @@ import net.minecraft.server.level.ServerLevel
/**
* A single frame of evaluation during the execution of a spell.
*
- * Specifically, an evaluation will keep a stack of these frames.
- * An evaluation with no meta-eval will consist of a single [Evaluate(rest of the pats)] at all times.
- * When an Eval is invoked, we push Evaluate(pats) to the top of the stack.
+ * Specifically, an evaluation will keep a stack of these frames. An evaluation with no meta-eval
+ * will consist of a single [Evaluate(rest of the pats)] at all times. When an Eval is invoked, we
+ * push Evaluate(pats) to the top of the stack.
*
* Evaluation is performed by repeatedly popping the top-most (i.e. innermost) frame from the stack,
- * then evaluating that frame (and possibly allowing it to push other frames (e.g. if it's a Hermes)).
+ * then evaluating that frame (and possibly allowing it to push other frames (e.g. if it's a
+ * Hermes)).
*
* Once the stack of frames is empty, there are no more computations to run, so we're done.
- *
*/
interface ContinuationFrame {
/**
- * Step the evaluation forward once.
- * For Evaluate, this consumes one pattern; for ForEach this queues the next iteration of the outer loop.
+ * Step the evaluation forward once. For Evaluate, this consumes one pattern; for ForEach this
+ * queues the next iteration of the outer loop.
+ *
* @return the result of this pattern step
*/
- fun evaluate(continuation: SpellContinuation, level: ServerLevel, harness: CastingVM): CastResult
+ fun evaluate(
+ continuation: SpellContinuation,
+ level: ServerLevel,
+ harness: CastingVM
+ ): CastResult
/**
- * The OpHalt instruction wants us to "jump to" the END of the nearest meta-eval.
- * In other words, we should consume Evaluate frames until we hit a FinishEval or Thoth frame.
- * @return whether the break should stop here, alongside the new stack state (e.g. for finalizing a Thoth)
+ * The OpHalt instruction wants us to "jump to" the END of the nearest meta-eval. In other
+ * words, we should consume Evaluate frames until we hit a FinishEval or Thoth frame.
+ *
+ * @return whether the break should stop here, alongside the new stack state (e.g. for
+ * finalizing a Thoth)
*/
fun breakDownwards(stack: List): Pair>
- /**
- * Serializes this frame. Used for things like delays, where we pause execution.
- */
+ /** Serializes this frame. Used for things like delays, where we pause execution. */
fun serializeToNBT(): CompoundTag
/**
- * Return the number of iotas contained inside this frame, used for determining whether it is valid to serialise.
+ * Return the number of iotas contained inside this frame, used for determining whether it is
+ * valid to serialise.
*/
fun size(): Int
@@ -55,27 +61,30 @@ interface ContinuationFrame {
companion object {
/**
- * Takes a tag containing the ContinuationFrame.Type resourcelocation and the serialized continuation frame, and returns
- * the deserialized continuation frame.
+ * Takes a tag containing the ContinuationFrame.Type resourcelocation and the serialized
+ * continuation frame, and returns the deserialized continuation frame.
*/
@JvmStatic
fun fromNBT(tag: CompoundTag, world: ServerLevel): ContinuationFrame {
- val type = getTypeFromTag(tag) ?: return FrameEvaluate(SpellList.LList(0, listOf()), false)
+ val type =
+ getTypeFromTag(tag) ?: return FrameEvaluate(SpellList.LList(0, listOf()), false)
- return (tag.get(HexContinuationTypes.KEY_DATA) as? CompoundTag)?.let { type.deserializeFromNBT(it, world) }
- ?: FrameEvaluate(SpellList.LList(0, listOf()), false)
+ return (tag.get(HexContinuationTypes.KEY_DATA) as? CompoundTag)?.let {
+ type.deserializeFromNBT(it, world)
+ } ?: FrameEvaluate(SpellList.LList(0, listOf()), false)
}
- /**
- * Takes a continuation frame and serializes it along with its type.
- */
+ /** Takes a continuation frame and serializes it along with its type. */
@JvmStatic
fun toNBT(frame: ContinuationFrame): CompoundTag {
val type = frame.type
- val typeId = HexContinuationTypes.REGISTRY.getKey(type)
- ?: throw IllegalStateException(
- "Tried to serialize an unregistered continuation type. Continuation: " + frame
- + " ; Type" + type.javaClass.typeName)
+ val typeId =
+ HexContinuationTypes.REGISTRY.getKey(type)
+ ?: throw IllegalStateException(
+ "Tried to serialize an unregistered continuation type. Continuation: " +
+ frame +
+ " ; Type" +
+ type.javaClass.typeName)
val data = frame.serializeToNBT()
@@ -86,8 +95,8 @@ interface ContinuationFrame {
}
/**
- * This method attempts to find the type from the `type` key.
- * See [ContinuationFrame.serializeToNBT] for the storage format.
+ * This method attempts to find the type from the `type` key. See
+ * [ContinuationFrame.serializeToNBT] for the storage format.
*
* @return `null` if it cannot get the type.
*/
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/FrameEvaluate.kt b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/FrameEvaluate.kt
index 141148dfdc..a440349b0a 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/FrameEvaluate.kt
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/FrameEvaluate.kt
@@ -16,6 +16,7 @@ import net.minecraft.server.level.ServerLevel
/**
* A list of patterns to be evaluated in sequence.
+ *
* @property list the *remaining* list of patterns to be evaluated
* @property isMetacasting only for sound effects, if this is being cast from a hermes / iris
*/
@@ -31,10 +32,11 @@ data class FrameEvaluate(val list: SpellList, val isMetacasting: Boolean) : Cont
): CastResult {
// If there are patterns left...
return if (list.nonEmpty) {
- val newCont = if (list.cdr.nonEmpty) { // yay TCO
- // ...enqueue the evaluation of the rest of the patterns...
- continuation.pushFrame(FrameEvaluate(list.cdr, this.isMetacasting))
- } else continuation
+ val newCont =
+ if (list.cdr.nonEmpty) { // yay TCO
+ // ...enqueue the evaluation of the rest of the patterns...
+ continuation.pushFrame(FrameEvaluate(list.cdr, this.isMetacasting))
+ } else continuation
// ...before evaluating the first one in the list.
val update = harness.executeInner(list.car, level, newCont)
if (this.isMetacasting && update.sound != HexEvalSounds.MISHAP) {
@@ -44,7 +46,13 @@ data class FrameEvaluate(val list: SpellList, val isMetacasting: Boolean) : Cont
}
} else {
// If there are no patterns (e.g. empty Hermes), just return OK.
- CastResult(ListIota(list), continuation, null, listOf(), ResolvedPatternType.EVALUATED, HexEvalSounds.HERMES)
+ CastResult(
+ ListIota(list),
+ continuation,
+ null,
+ listOf(),
+ ResolvedPatternType.EVALUATED,
+ HexEvalSounds.HERMES)
}
}
@@ -59,16 +67,18 @@ data class FrameEvaluate(val list: SpellList, val isMetacasting: Boolean) : Cont
companion object {
@JvmField
- val TYPE: ContinuationFrame.Type = object : ContinuationFrame.Type {
- override fun deserializeFromNBT(tag: CompoundTag, world: ServerLevel): FrameEvaluate {
- return FrameEvaluate(
- HexIotaTypes.LIST.deserialize(
- tag.getList("patterns", Tag.TAG_COMPOUND),
- world
- )!!.list,
- tag.getBoolean("isMetacasting"))
+ val TYPE: ContinuationFrame.Type =
+ object : ContinuationFrame.Type {
+ override fun deserializeFromNBT(
+ tag: CompoundTag,
+ world: ServerLevel
+ ): FrameEvaluate {
+ return FrameEvaluate(
+ HexIotaTypes.LIST.deserialize(
+ tag.getList("patterns", Tag.TAG_COMPOUND), world)!!
+ .list,
+ tag.getBoolean("isMetacasting"))
+ }
}
-
- }
}
-}
\ No newline at end of file
+}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/FrameFinishEval.kt b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/FrameFinishEval.kt
index 72bbb8c80c..f181ab87e3 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/FrameFinishEval.kt
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/FrameFinishEval.kt
@@ -4,14 +4,13 @@ import at.petrak.hexcasting.api.casting.eval.CastResult
import at.petrak.hexcasting.api.casting.eval.ResolvedPatternType
import at.petrak.hexcasting.api.casting.iota.Iota
import at.petrak.hexcasting.api.casting.iota.NullIota
-import at.petrak.hexcasting.api.utils.NBTBuilder
import at.petrak.hexcasting.common.lib.hex.HexEvalSounds
import net.minecraft.nbt.CompoundTag
import net.minecraft.server.level.ServerLevel
/**
- * A stack marker representing the end of a Hermes evaluation,
- * so that we know when to stop removing frames during a Halt.
+ * A stack marker representing the end of a Hermes evaluation, so that we know when to stop removing
+ * frames during a Halt.
*/
object FrameFinishEval : ContinuationFrame {
// Don't do anything else to the stack, just finish the halt statement.
@@ -38,9 +37,10 @@ object FrameFinishEval : ContinuationFrame {
override fun size() = 0
@JvmField
- val TYPE: ContinuationFrame.Type = object : ContinuationFrame.Type {
- override fun deserializeFromNBT(tag: CompoundTag, world: ServerLevel) = FrameFinishEval
- }
+ val TYPE: ContinuationFrame.Type =
+ object : ContinuationFrame.Type {
+ override fun deserializeFromNBT(tag: CompoundTag, world: ServerLevel) = FrameFinishEval
+ }
override val type = TYPE
}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/FrameForEach.kt b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/FrameForEach.kt
index 0221c1f36d..c24270358f 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/FrameForEach.kt
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/FrameForEach.kt
@@ -16,9 +16,10 @@ import net.minecraft.nbt.Tag
import net.minecraft.server.level.ServerLevel
/**
- * A frame representing all the state for a Thoth evaluation.
- * Pushed by an OpForEach.
- * @property first whether the input stack state is the first one (since we don't want to save the base-stack before any changes are made)
+ * A frame representing all the state for a Thoth evaluation. Pushed by an OpForEach.
+ *
+ * @property first whether the input stack state is the first one (since we don't want to save the
+ * base-stack before any changes are made)
* @property data list of *remaining* datums to ForEach over
* @property code code to run per datum
* @property baseStack the stack state at Thoth entry
@@ -31,7 +32,10 @@ data class FrameForEach(
val acc: MutableList
) : ContinuationFrame {
- /** When halting, we add the stack state at halt to the stack accumulator, then return the original pre-Thoth stack, plus the accumulator. */
+ /**
+ * When halting, we add the stack state at halt to the stack accumulator, then return the
+ * original pre-Thoth stack, plus the accumulator.
+ */
override fun breakDownwards(stack: List): Pair> {
val newStack = baseStack?.toMutableList() ?: mutableListOf()
acc.addAll(stack)
@@ -46,28 +50,31 @@ data class FrameForEach(
harness: CastingVM
): CastResult {
// If this isn't the very first Thoth step (i.e. no Thoth computations run yet)...
- val stack = if (baseStack == null) {
- // init stack to the harness stack...
- harness.image.stack.toList()
- } else {
- // else save the stack to the accumulator and reuse the saved base stack.
- acc.addAll(harness.image.stack)
- baseStack
- }
+ val stack =
+ if (baseStack == null) {
+ // init stack to the harness stack...
+ harness.image.stack.toList()
+ } else {
+ // else save the stack to the accumulator and reuse the saved base stack.
+ acc.addAll(harness.image.stack)
+ baseStack
+ }
// If we still have data to process...
- val (stackTop, newImage, newCont) = if (data.nonEmpty) {
- // push the next datum to the top of the stack,
- val cont2 = continuation
- // put the next Thoth object back on the stack for the next Thoth cycle,
- .pushFrame(FrameForEach(data.cdr, code, stack, acc))
- // and prep the Thoth'd code block for evaluation.
- .pushFrame(FrameEvaluate(code, true))
- Triple(data.car, harness.image.withUsedOp(), cont2)
- } else {
- // Else, dump our final list onto the stack.
- Triple(ListIota(acc), harness.image, continuation)
- }
+ val (stackTop, newImage, newCont) =
+ if (data.nonEmpty) {
+ // push the next datum to the top of the stack,
+ val cont2 =
+ continuation
+ // put the next Thoth object back on the stack for the next Thoth cycle,
+ .pushFrame(FrameForEach(data.cdr, code, stack, acc))
+ // and prep the Thoth'd code block for evaluation.
+ .pushFrame(FrameEvaluate(code, true))
+ Triple(data.car, harness.image.withUsedOp(), cont2)
+ } else {
+ // Else, dump our final list onto the stack.
+ Triple(ListIota(acc), harness.image, continuation)
+ }
val tStack = stack.toMutableList()
tStack.add(stackTop)
return CastResult(
@@ -84,8 +91,7 @@ data class FrameForEach(
override fun serializeToNBT() = NBTBuilder {
"data" %= data.serializeToNBT()
"code" %= code.serializeToNBT()
- if (baseStack != null)
- "base" %= baseStack.serializeToNBT()
+ if (baseStack != null) "base" %= baseStack.serializeToNBT()
"accumulator" %= acc.serializeToNBT()
}
@@ -95,22 +101,30 @@ data class FrameForEach(
companion object {
@JvmField
- val TYPE: ContinuationFrame.Type = object : ContinuationFrame.Type {
- override fun deserializeFromNBT(tag: CompoundTag, world: ServerLevel): FrameForEach {
- return FrameForEach(
- HexIotaTypes.LIST.deserialize(tag.getList("data", Tag.TAG_COMPOUND), world)!!.list,
- HexIotaTypes.LIST.deserialize(tag.getList("code", Tag.TAG_COMPOUND), world)!!.list,
- if (tag.hasList("base", Tag.TAG_COMPOUND))
- HexIotaTypes.LIST.deserialize(tag.getList("base", Tag.TAG_COMPOUND), world)!!.list.toList()
- else
- null,
- HexIotaTypes.LIST.deserialize(
- tag.getList("accumulator", Tag.TAG_COMPOUND),
- world
- )!!.list.toMutableList()
- )
+ val TYPE: ContinuationFrame.Type =
+ object : ContinuationFrame.Type {
+ override fun deserializeFromNBT(
+ tag: CompoundTag,
+ world: ServerLevel
+ ): FrameForEach {
+ return FrameForEach(
+ HexIotaTypes.LIST.deserialize(
+ tag.getList("data", Tag.TAG_COMPOUND), world)!!
+ .list,
+ HexIotaTypes.LIST.deserialize(
+ tag.getList("code", Tag.TAG_COMPOUND), world)!!
+ .list,
+ if (tag.hasList("base", Tag.TAG_COMPOUND))
+ HexIotaTypes.LIST.deserialize(
+ tag.getList("base", Tag.TAG_COMPOUND), world)!!
+ .list
+ .toList()
+ else null,
+ HexIotaTypes.LIST.deserialize(
+ tag.getList("accumulator", Tag.TAG_COMPOUND), world)!!
+ .list
+ .toMutableList())
+ }
}
-
- }
}
}
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/FunctionalData.kt b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/FunctionalData.kt
index 49f3d149d0..e62340dadc 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/FunctionalData.kt
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/FunctionalData.kt
@@ -2,9 +2,7 @@ package at.petrak.hexcasting.api.casting.eval.vm
import at.petrak.hexcasting.api.casting.iota.Iota
-/**
- * A change to the data in a CastHarness after a pattern is drawn.
- */
+/** A change to the data in a CastHarness after a pattern is drawn. */
data class FunctionalData(
val stack: List,
val parenCount: Int,
@@ -12,4 +10,3 @@ data class FunctionalData(
val escapeNext: Boolean,
val ravenmind: Iota?
)
-
diff --git a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/SpellContinuation.kt b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/SpellContinuation.kt
index ec706c2858..96eb0b51b1 100644
--- a/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/SpellContinuation.kt
+++ b/Common/src/main/java/at/petrak/hexcasting/api/casting/eval/vm/SpellContinuation.kt
@@ -6,19 +6,17 @@ import net.minecraft.nbt.CompoundTag
import net.minecraft.nbt.Tag
import net.minecraft.server.level.ServerLevel
-/**
- * A continuation during the execution of a spell.
- */
+/** A continuation during the execution of a spell. */
sealed interface SpellContinuation {
object Done : SpellContinuation
- data class NotDone(val frame: ContinuationFrame, val next: SpellContinuation) : SpellContinuation
+ data class NotDone(val frame: ContinuationFrame, val next: SpellContinuation) :
+ SpellContinuation
fun pushFrame(frame: ContinuationFrame): SpellContinuation = NotDone(frame, this)
- fun serializeToNBT() = NBTBuilder {
- TAG_FRAME %= list(getNBTFrames())
- }
+ fun serializeToNBT() = NBTBuilder { TAG_FRAME %= list(getNBTFrames()) }
+
fun getNBTFrames(): List