diff --git a/src/main/java/org/ships/algorthum/blockfinder/BasicBlockFinder.java b/src/main/java/org/ships/algorthum/blockfinder/BasicBlockFinder.java index b4bd7471..028c5e59 100644 --- a/src/main/java/org/ships/algorthum/blockfinder/BasicBlockFinder.java +++ b/src/main/java/org/ships/algorthum/blockfinder/BasicBlockFinder.java @@ -12,28 +12,40 @@ public interface BasicBlockFinder extends Algorithm { - Ships5BlockFinder SHIPS_FIVE = new Ships5BlockFinder(); - Ships5AsyncBlockFinder SHIPS_FIVE_ASYNC = new Ships5AsyncBlockFinder(); - Ships6BlockFinder SHIPS_SIX = new Ships6BlockFinder(); - Ships6MultiAsyncBlockFinder SHIPS_SIX_RELEASE_ONE_MULTI_ASYNC = new Ships6MultiAsyncBlockFinder(); - Ships6SingleAsyncBlockFinder SHIPS_SIX_RELEASE_ONE_SINGLE_ASYNC = new Ships6SingleAsyncBlockFinder(); + @Deprecated(forRemoval = true) + Ships5BlockFinder SHIPS_FIVE = BlockFinders.SHIPS_FIVE_SYNCED; - @NotNull BasicBlockFinder init(); + @Deprecated(forRemoval = true) + Ships5AsyncBlockFinder SHIPS_FIVE_ASYNC = BlockFinders.SHIPS_FIVE_ASYNCED; + + @Deprecated(forRemoval = true) + Ships6BlockFinder SHIPS_SIX = BlockFinders.SHIPS_SIX_RELEASE_TWO_SYNCED; + + @Deprecated(forRemoval = true) + Ships6MultiAsyncBlockFinder SHIPS_SIX_RELEASE_ONE_MULTI_ASYNC = BlockFinders.SHIPS_SIX_RELEASE_ONE_ASYNC_MULTI_THREADED; + + @Deprecated(forRemoval = true) + Ships6SingleAsyncBlockFinder SHIPS_SIX_RELEASE_ONE_SINGLE_ASYNC = BlockFinders.SHIPS_SIX_RELEASE_ONE_ASYNC_SINGLE_THREADED; + + @NotNull + BasicBlockFinder init(); CompletableFuture getConnectedBlocksOvertime(@NotNull BlockPosition position, @NotNull OvertimeBlockFinderUpdate runAfterFullSearch); default CompletableFuture getConnectedBlocksOvertime(@NotNull BlockPosition position) { - return getConnectedBlocksOvertime(position, - (currentStructure, block) -> OvertimeBlockFinderUpdate.BlockFindControl.USE); + return this.getConnectedBlocksOvertime(position, + (currentStructure, block) -> OvertimeBlockFinderUpdate.BlockFindControl.USE); } int getBlockLimit(); - @NotNull BasicBlockFinder setBlockLimit(int limit); + @NotNull + BasicBlockFinder setBlockLimit(int limit); Optional getConnectedVessel(); - @NotNull BasicBlockFinder setConnectedVessel(@Nullable Vessel vessel); + @NotNull + BasicBlockFinder setConnectedVessel(@Nullable Vessel vessel); } diff --git a/src/main/java/org/ships/algorthum/blockfinder/BlockFinders.java b/src/main/java/org/ships/algorthum/blockfinder/BlockFinders.java new file mode 100644 index 00000000..857fe4e2 --- /dev/null +++ b/src/main/java/org/ships/algorthum/blockfinder/BlockFinders.java @@ -0,0 +1,38 @@ +package org.ships.algorthum.blockfinder; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.UnmodifiableView; + +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.LinkedTransferQueue; + +public final class BlockFinders { + + private static final Collection registered = new LinkedTransferQueue<>(); + + public static final Ships5BlockFinder SHIPS_FIVE_SYNCED = register(new Ships5BlockFinder()); + public static final Ships5AsyncBlockFinder SHIPS_FIVE_ASYNCED = register(new Ships5AsyncBlockFinder()); + + public static final Ships6BlockFinder SHIPS_SIX_RELEASE_TWO_SYNCED = register(new Ships6BlockFinder()); + + public static final Ships6MultiAsyncBlockFinder SHIPS_SIX_RELEASE_ONE_ASYNC_MULTI_THREADED = register(new Ships6MultiAsyncBlockFinder()); + + public static final Ships6SingleAsyncBlockFinder SHIPS_SIX_RELEASE_ONE_ASYNC_SINGLE_THREADED = register(new Ships6SingleAsyncBlockFinder()); + + private BlockFinders() { + throw new RuntimeException("Do not create"); + } + + public static T register(@NotNull T finder) { + registered.add(finder); + return finder; + } + + @UnmodifiableView + public static Collection getBlockFinders() { + return Collections.unmodifiableCollection(registered); + } + + +} diff --git a/src/main/java/org/ships/algorthum/blockfinder/FindAirOvertimeBlockFinderUpdate.java b/src/main/java/org/ships/algorthum/blockfinder/FindAirOvertimeBlockFinderUpdate.java index a74c7f72..ba5ae469 100644 --- a/src/main/java/org/ships/algorthum/blockfinder/FindAirOvertimeBlockFinderUpdate.java +++ b/src/main/java/org/ships/algorthum/blockfinder/FindAirOvertimeBlockFinderUpdate.java @@ -1,5 +1,6 @@ package org.ships.algorthum.blockfinder; +import org.core.vector.type.Vector3; import org.core.world.position.impl.BlockPosition; import org.jetbrains.annotations.NotNull; import org.ships.vessel.common.types.Vessel; @@ -16,7 +17,7 @@ public FindAirOvertimeBlockFinderUpdate(@NotNull Vessel vessel, @NotNull Overtim @Override public BlockFindControl onBlockFind(@NotNull PositionableShipsStructure currentStructure, - @NotNull BlockPosition block) { + @NotNull Vector3 block) { return this.update.onBlockFind(currentStructure, block); } } diff --git a/src/main/java/org/ships/algorthum/blockfinder/OvertimeBlockFinderUpdate.java b/src/main/java/org/ships/algorthum/blockfinder/OvertimeBlockFinderUpdate.java index fd65f0ed..ad06d8ce 100644 --- a/src/main/java/org/ships/algorthum/blockfinder/OvertimeBlockFinderUpdate.java +++ b/src/main/java/org/ships/algorthum/blockfinder/OvertimeBlockFinderUpdate.java @@ -1,6 +1,6 @@ package org.ships.algorthum.blockfinder; -import org.core.world.position.impl.BlockPosition; +import org.core.vector.type.Vector3; import org.jetbrains.annotations.NotNull; import org.ships.vessel.structure.PositionableShipsStructure; @@ -14,6 +14,7 @@ enum BlockFindControl { } - BlockFindControl onBlockFind(@NotNull PositionableShipsStructure currentStructure, @NotNull BlockPosition block); + BlockFindControl onBlockFind(@NotNull PositionableShipsStructure currentStructure, + @NotNull Vector3 blockPosition); } diff --git a/src/main/java/org/ships/algorthum/blockfinder/Ships5AsyncBlockFinder.java b/src/main/java/org/ships/algorthum/blockfinder/Ships5AsyncBlockFinder.java index 5f833596..6cce0e85 100644 --- a/src/main/java/org/ships/algorthum/blockfinder/Ships5AsyncBlockFinder.java +++ b/src/main/java/org/ships/algorthum/blockfinder/Ships5AsyncBlockFinder.java @@ -46,7 +46,7 @@ private void getNextBlock(@Nullable OvertimeBlockFinderUpdate event, OvertimeBlockFinderUpdate.BlockFindControl blockFind = null; if (bi.getCollide() == CollideType.MATERIAL) { if (event != null) { - blockFind = event.onBlockFind(this.shipsStructure, block); + blockFind = event.onBlockFind(this.shipsStructure, block.getPosition()); if (blockFind == OvertimeBlockFinderUpdate.BlockFindControl.IGNORE) { this.getNextBlock(event, block, directions); } diff --git a/src/main/java/org/ships/algorthum/blockfinder/Ships5BlockFinder.java b/src/main/java/org/ships/algorthum/blockfinder/Ships5BlockFinder.java index 2b0eaf0c..51df81bd 100644 --- a/src/main/java/org/ships/algorthum/blockfinder/Ships5BlockFinder.java +++ b/src/main/java/org/ships/algorthum/blockfinder/Ships5BlockFinder.java @@ -40,7 +40,7 @@ private void getNextBlock(OvertimeBlockFinderUpdate event, BlockPosition positio OvertimeBlockFinderUpdate.BlockFindControl blockFind = null; if (bi.getCollide() == CollideType.MATERIAL) { if (event != null) { - blockFind = event.onBlockFind(this.shipsStructure, block); + blockFind = event.onBlockFind(this.shipsStructure, block.getPosition()); if (blockFind == OvertimeBlockFinderUpdate.BlockFindControl.IGNORE) { this.getNextBlock(event, block, directions); } diff --git a/src/main/java/org/ships/algorthum/blockfinder/Ships6BlockFinder.java b/src/main/java/org/ships/algorthum/blockfinder/Ships6BlockFinder.java index f218ae8e..13493db8 100644 --- a/src/main/java/org/ships/algorthum/blockfinder/Ships6BlockFinder.java +++ b/src/main/java/org/ships/algorthum/blockfinder/Ships6BlockFinder.java @@ -1,9 +1,6 @@ package org.ships.algorthum.blockfinder; import org.core.TranslateCore; -import org.core.config.ConfigurationNode; -import org.core.config.ConfigurationStream; -import org.core.config.parser.Parser; import org.core.schedule.Scheduler; import org.core.schedule.unit.TimeUnit; import org.core.world.direction.Direction; @@ -16,16 +13,15 @@ import org.ships.config.blocks.instruction.BlockInstruction; import org.ships.config.blocks.instruction.CollideType; import org.ships.config.configuration.ShipsConfig; -import org.ships.config.node.DedicatedNode; -import org.ships.config.node.ObjectDedicatedNode; -import org.ships.config.node.RawDedicatedNode; import org.ships.plugin.ShipsPlugin; import org.ships.vessel.common.types.Vessel; import org.ships.vessel.structure.AbstractPositionableShipsStructure; import org.ships.vessel.structure.PositionableShipsStructure; -import java.io.File; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; @@ -107,8 +103,8 @@ private Overtime(SyncBlockPosition position, Scheduler scheduler = TranslateCore .getScheduleManager() .schedule() - .setDelay(stackDelay) - .setDelayUnit(stackDelayUnit) + .setDelay(this.stackDelay) + .setDelayUnit(this.stackDelayUnit) .setRunner((sch1) -> { if ((this.total.size() <= Ships6BlockFinder.this.limit) && (!this.ret.isEmpty())) { this.process = this.ret; @@ -117,8 +113,8 @@ private Overtime(SyncBlockPosition position, TranslateCore .getScheduleManager() .schedule() - .setDelay(stackDelay) - .setDelayUnit(stackDelayUnit) + .setDelay(this.stackDelay) + .setDelayUnit(this.stackDelayUnit) .setRunner(this.runnable) .setDisplayName("Ships 6 ASync Block Finder") .buildDelayed(ShipsPlugin.getPlugin()) @@ -134,14 +130,14 @@ private Overtime(SyncBlockPosition position, scheduler = TranslateCore .getScheduleManager() .schedule() - .setDelay(stackDelay) - .setDelayUnit(stackDelayUnit) + .setDelay(this.stackDelay) + .setDelayUnit(this.stackDelayUnit) .setRunner((scheduler2) -> { OvertimeSection section = new OvertimeSection(list, this.total); section.runnable.accept(scheduler2); section.ret.forEach(p -> { OvertimeBlockFinderUpdate.BlockFindControl blockFind = this.update.onBlockFind(this.pss, - p); + p.getPosition()); if (blockFind == OvertimeBlockFinderUpdate.BlockFindControl.IGNORE) { return; } @@ -177,7 +173,7 @@ private Overtime(SyncBlockPosition position, public CompletableFuture getConnectedBlocksOvertime(@NotNull BlockPosition position, @NotNull OvertimeBlockFinderUpdate runAfterFullSearch) { CompletableFuture future = new CompletableFuture<>(); - var configuration = ShipsPlugin.getPlugin().getConfig(); + ShipsConfig configuration = ShipsPlugin.getPlugin().getConfig(); Overtime overtime = new Overtime(position.toSyncPosition(), runAfterFullSearch, configuration, future); TranslateCore .getScheduleManager() diff --git a/src/main/java/org/ships/algorthum/blockfinder/Ships6MultiAsyncBlockFinder.java b/src/main/java/org/ships/algorthum/blockfinder/Ships6MultiAsyncBlockFinder.java index 7ae8b606..e0926f55 100644 --- a/src/main/java/org/ships/algorthum/blockfinder/Ships6MultiAsyncBlockFinder.java +++ b/src/main/java/org/ships/algorthum/blockfinder/Ships6MultiAsyncBlockFinder.java @@ -1,7 +1,6 @@ package org.ships.algorthum.blockfinder; import org.core.TranslateCore; -import org.core.config.ConfigurationNode; import org.core.schedule.unit.TimeUnit; import org.core.vector.type.Vector3; import org.core.world.direction.Direction; @@ -15,17 +14,19 @@ import org.ships.config.blocks.instruction.BlockInstruction; import org.ships.config.blocks.instruction.CollideType; import org.ships.config.configuration.ShipsConfig; -import org.ships.config.node.DedicatedNode; import org.ships.plugin.ShipsPlugin; import org.ships.vessel.common.types.Vessel; import org.ships.vessel.structure.AbstractPositionableShipsStructure; import org.ships.vessel.structure.PositionableShipsStructure; -import java.io.File; -import java.util.*; +import java.util.AbstractMap; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; import java.util.stream.Stream; public class Ships6MultiAsyncBlockFinder implements BasicBlockFinder { @@ -66,14 +67,16 @@ public CompletableFuture getConnectedBlocksOvertime( .setDelay(0) .setRunner((scheduler) -> { PositionableShipsStructure structure = new AbstractPositionableShipsStructure( - Position.toSync(position)); + position.toSyncPosition()); LinkedTransferQueue> toProcess = new LinkedTransferQueue<>(); Direction[] directions = Direction.withYDirections(FourFacingDirection.getFourFacingDirections()); - toProcess.add(new AbstractMap.SimpleImmutableEntry<>(Position.toASync(position), + toProcess.add(new AbstractMap.SimpleImmutableEntry<>(position.toAsyncPosition(), FourFacingDirection.NONE)); - while (!toProcess.isEmpty() && structure.getOriginalRelativePositionsToCenter().size() < limit - && !ShipsPlugin.getPlugin().isShuttingDown()) { - Collection> positions = structure.getOriginalRelativePositionsToCenter(); + while (!toProcess.isEmpty() && structure.size() < limit && !ShipsPlugin + .getPlugin() + .isShuttingDown()) { + Collection> positions = structure.getVectorsRelativeToLicence().collect( + Collectors.toList()); LinkedTransferQueue> next = new LinkedTransferQueue<>(); while (toProcess.hasWaitingConsumer()) { continue; @@ -112,11 +115,11 @@ public CompletableFuture getConnectedBlocksOvertime( } }); OvertimeBlockFinderUpdate.BlockFindControl blockFind = runAfterFullSearch.onBlockFind( - structure, posEntry.getKey()); + structure, posEntry.getKey().getPosition()); if (blockFind == OvertimeBlockFinderUpdate.BlockFindControl.IGNORE) { return; } - structure.addPositionRelativeToWorld(Position.toSync(posEntry.getKey())); + structure.addPositionRelativeToWorld(posEntry.getKey().toSyncPosition()); if (blockFind == OvertimeBlockFinderUpdate.BlockFindControl.USE_AND_FINISH) { shouldKill.set(true); TranslateCore diff --git a/src/main/java/org/ships/algorthum/blockfinder/Ships6SingleAsyncBlockFinder.java b/src/main/java/org/ships/algorthum/blockfinder/Ships6SingleAsyncBlockFinder.java index 79e74732..23802a96 100644 --- a/src/main/java/org/ships/algorthum/blockfinder/Ships6SingleAsyncBlockFinder.java +++ b/src/main/java/org/ships/algorthum/blockfinder/Ships6SingleAsyncBlockFinder.java @@ -1,30 +1,33 @@ package org.ships.algorthum.blockfinder; import org.core.TranslateCore; -import org.core.config.ConfigurationNode; import org.core.schedule.unit.TimeUnit; +import org.core.utils.Bounds; import org.core.vector.type.Vector3; +import org.core.world.chunk.AsyncChunk; import org.core.world.direction.Direction; import org.core.world.direction.FourFacingDirection; +import org.core.world.position.block.details.BlockDetails; import org.core.world.position.impl.BlockPosition; -import org.core.world.position.impl.async.ASyncBlockPosition; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.ships.config.blocks.BlockList; import org.ships.config.blocks.instruction.BlockInstruction; import org.ships.config.blocks.instruction.CollideType; import org.ships.config.configuration.ShipsConfig; -import org.ships.config.node.DedicatedNode; import org.ships.plugin.ShipsPlugin; import org.ships.vessel.common.types.Vessel; import org.ships.vessel.structure.AbstractPositionableShipsStructure; import org.ships.vessel.structure.PositionableShipsStructure; -import java.io.File; -import java.util.*; +import java.util.AbstractMap; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; import java.util.stream.Stream; public class Ships6SingleAsyncBlockFinder implements BasicBlockFinder { @@ -56,6 +59,13 @@ public String getName() { public CompletableFuture getConnectedBlocksOvertime(@NotNull BlockPosition position, @NotNull OvertimeBlockFinderUpdate runAfterFullSearch) { CompletableFuture future = new CompletableFuture<>(); + Vector3 originalChunkPos = position.getChunkPosition(); + Map> asyncChunks = position + .getWorld() + .getChunkExtents() + .filter(chunk -> chunk.getChunkPosition().distanceSquared(originalChunkPos) <= 2) + .map(chunk -> chunk.createAsync()) + .collect(Collectors.toMap(c -> c, c -> c.getBounds())); int limit = this.limit; TranslateCore .getScheduleManager() @@ -66,17 +76,20 @@ public CompletableFuture getConnectedBlocksOvertime( .setRunner((scheduler) -> { PositionableShipsStructure structure = new AbstractPositionableShipsStructure( position.toSyncPosition()); - LinkedTransferQueue> toProcess = new LinkedTransferQueue<>(); + LinkedTransferQueue, Direction>> toProcess = new LinkedTransferQueue<>(); Direction[] directions = Direction.withYDirections(FourFacingDirection.getFourFacingDirections()); - toProcess.add(Map.entry(position.toAsyncPosition(), FourFacingDirection.NONE)); - while (!toProcess.isEmpty() && structure.getOriginalRelativePositionsToCenter().size() < limit - && !ShipsPlugin.getPlugin().isShuttingDown()) { - Collection> positions = structure.getOriginalRelativePositionsToCenter(); - LinkedTransferQueue> next = new LinkedTransferQueue<>(); + toProcess.add(Map.entry(position.getPosition(), FourFacingDirection.NONE)); + while (!toProcess.isEmpty() && structure.size() < limit && !ShipsPlugin + .getPlugin() + .isShuttingDown()) { + Collection> positions = structure + .getVectorsRelativeToWorld() + .collect(Collectors.toList()); + LinkedTransferQueue, Direction>> next = new LinkedTransferQueue<>(); while (toProcess.hasWaitingConsumer()) { continue; } - final Collection> finalToProcess = toProcess; + final Collection, Direction>> finalToProcess = toProcess; AtomicBoolean shouldKill = new AtomicBoolean(); toProcess.forEach(posEntry -> { if (ShipsPlugin.getPlugin().isShuttingDown()) { @@ -90,22 +103,30 @@ public CompletableFuture getConnectedBlocksOvertime( if (shouldKill.get()) { return; } - ASyncBlockPosition block = posEntry.getKey().getRelative(direction); - Vector3 vector = block.getPosition().minus(position.getPosition()); - BlockInstruction bi = this.list.getBlockInstruction(block.getBlockType()); + Vector3 blockPosition = posEntry + .getKey() + .plus(direction.getAsVector()); + if (blockPosition.equals(Vector3.valueOf(149, 64, 166))) { + System.out.println("Found"); + } + BlockDetails blockDetails = asyncChunks + .entrySet() + .stream() + .filter(entry -> entry.getValue().containsWithoutMax(blockPosition)) + .map(entry -> entry.getKey().getDetails(blockPosition)) + .findFirst() + .orElseThrow(() -> new RuntimeException( + "Cannot find " + blockPosition + " in loaded chunks")); + BlockInstruction bi = this.list.getBlockInstruction(blockDetails.getType()); if (bi.getCollide() == CollideType.MATERIAL) { - if (positions.contains(vector) || finalToProcess + if (positions.contains(blockPosition) || finalToProcess .stream() - .anyMatch(entry -> entry.getKey().equals(block))) { + .anyMatch(entry -> entry.getKey().equals(blockPosition))) { return; } - if (next - .stream() - .noneMatch(b -> b - .getKey() - .getPosition() - .equals(block.getPosition()))) { - next.add(new AbstractMap.SimpleImmutableEntry<>(block, direction)); + if (next.stream().noneMatch(b -> b.getKey().equals(blockPosition))) { + next.add(new AbstractMap.SimpleImmutableEntry<>(blockPosition, + direction)); } } }); @@ -114,7 +135,10 @@ public CompletableFuture getConnectedBlocksOvertime( if (blockFind == OvertimeBlockFinderUpdate.BlockFindControl.IGNORE) { return; } - structure.addPositionRelativeToWorld(posEntry.getKey().toSyncPosition()); + + Vector3 vector = posEntry.getKey().minus(structure.getPosition().getPosition()); + structure.addVectorRelativeToLicence(vector); + if (blockFind == OvertimeBlockFinderUpdate.BlockFindControl.USE_AND_FINISH) { shouldKill.set(true); TranslateCore diff --git a/src/main/java/org/ships/algorthum/movement/Movements.java b/src/main/java/org/ships/algorthum/movement/Movements.java new file mode 100644 index 00000000..f6ed15ed --- /dev/null +++ b/src/main/java/org/ships/algorthum/movement/Movements.java @@ -0,0 +1,31 @@ +package org.ships.algorthum.movement; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.UnmodifiableView; + +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.LinkedTransferQueue; + +public final class Movements { + + private static final Collection registered = new LinkedTransferQueue<>(); + + public static final Ships5Movement SHIPS_5 = register(new Ships5Movement()); + public static final Ships6Movement SHIPS_6 = register(new Ships6Movement()); + + private Movements() { + throw new RuntimeException("Do not create"); + } + + public static T register(@NotNull T movement) { + registered.add(movement); + return movement; + } + + @UnmodifiableView + public static Collection getMovements() { + return Collections.unmodifiableCollection(registered); + } + +} diff --git a/src/main/java/org/ships/algorthum/movement/Ships6Movement.java b/src/main/java/org/ships/algorthum/movement/Ships6Movement.java index 3c7c4641..483b98cf 100644 --- a/src/main/java/org/ships/algorthum/movement/Ships6Movement.java +++ b/src/main/java/org/ships/algorthum/movement/Ships6Movement.java @@ -2,30 +2,22 @@ import net.kyori.adventure.text.Component; import org.core.TranslateCore; -import org.core.config.ConfigurationNode; -import org.core.config.ConfigurationStream; -import org.core.config.parser.Parser; import org.core.schedule.Scheduler; import org.core.schedule.unit.TimeUnit; -import org.core.world.position.block.details.data.keyed.TileEntityKeyedData; -import org.jetbrains.annotations.NotNull; -import org.ships.config.messages.AdventureMessageConfig; -import org.ships.config.node.DedicatedNode; -import org.ships.config.node.ObjectDedicatedNode; -import org.ships.config.node.RawDedicatedNode; +import org.core.world.position.block.BlockTypes; +import org.ships.config.configuration.ShipsConfig; +import org.ships.config.messages.Messages; import org.ships.event.vessel.move.VesselMoveEvent; import org.ships.exceptions.move.MoveException; -import org.ships.movement.MovementContext; -import org.ships.movement.MovingBlock; -import org.ships.movement.MovingBlockSet; -import org.ships.movement.Result; +import org.ships.movement.*; import org.ships.movement.instruction.actions.PostMovement; import org.ships.plugin.ShipsPlugin; import org.ships.vessel.common.flag.MovingFlag; import org.ships.vessel.common.types.Vessel; -import java.io.File; -import java.util.*; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; import java.util.function.Consumer; import java.util.stream.Stream; @@ -83,7 +75,6 @@ private static final class SetBlocks implements Consumer { private final int current; private final int totalBlocks; - private SetBlocks(int current, int totalBlocks, MovementContext context, List blocks) { this.toProcess = blocks; this.context = context; @@ -98,7 +89,7 @@ public void accept(Scheduler scheduler) { final int finalIndex = index; this.context.getAdventureBossBar().ifPresent(bar -> { int currentBlock = this.current + finalIndex; - float progress = (float) currentBlock / totalBlocks; + float progress = (float) currentBlock / this.totalBlocks; progress = Math.max(progress, 0); progress = Math.min(progress, 1); bar.progress(progress); @@ -112,13 +103,22 @@ public void accept(Scheduler scheduler) { @Override public Result move(Vessel vessel, MovementContext context) throws MoveException { - var config = ShipsPlugin.getPlugin().getConfig(); + ShipsConfig config = ShipsPlugin.getPlugin().getConfig(); int stackLimit = config.getDefaultMovementStackLimit(); TimeUnit stackDelayUnit = config.getDefaultMovementStackDelayUnit(); int stackDelay = config.getDefaultMovementStackDelay(); context.getAdventureBossBar().ifPresent(b -> b.progress(0)); - List blocks = context.getMovingStructure().order(MovingBlockSet.ORDER_ON_PRIORITY); + List blocks = new LinkedList<>(context.getMovingStructure()); + if (!blocks.isEmpty()) { + var action = blocks.get(0).getAction(); + vessel + .getStructure() + .getAir() + .forEach(pos -> blocks.add( + new SetMovingBlock(pos, action, BlockTypes.AIR.getDefaultBlockDetails()))); + } + blocks.sort(MovingBlockSet.ORDER_ON_PRIORITY); List> blocksToProcess = new LinkedList<>(); List currentlyAdding = new LinkedList<>(); context.getAdventureBossBar().ifPresent(bar -> bar.name(Component.text("Movement: optimising "))); @@ -193,7 +193,7 @@ public Result move(Vessel vessel, MovementContext context) throws MoveException placedBlocks = placedBlocks + blocks2.size(); } if (scheduler == null) { - throw new MoveException(context, AdventureMessageConfig.ERROR_FAILED_IN_MOVEMENT, vessel); + throw new MoveException(context, Messages.ERROR_FAILED_IN_MOVEMENT, vessel); } scheduler.run(); diff --git a/src/main/java/org/ships/commands/argument/arguments/identifiable/ShipIdentifiableArgument.java b/src/main/java/org/ships/commands/argument/arguments/identifiable/ShipIdentifiableArgument.java index 7681dfda..3c358775 100644 --- a/src/main/java/org/ships/commands/argument/arguments/identifiable/ShipIdentifiableArgument.java +++ b/src/main/java/org/ships/commands/argument/arguments/identifiable/ShipIdentifiableArgument.java @@ -6,27 +6,29 @@ import org.core.command.argument.context.CommandContext; import org.core.utils.Identifiable; import org.core.utils.lamda.tri.TriPredicate; -import org.ships.plugin.ShipsPlugin; import java.io.IOException; import java.util.List; import java.util.Optional; +import java.util.function.Supplier; import java.util.stream.Collectors; +import java.util.stream.Stream; public class ShipIdentifiableArgument implements CommandArgument { private final String id; - private final Class type; + private final Supplier> all; private final TriPredicate, ? super T> predicate; - public ShipIdentifiableArgument(String id, Class type) { - this(id, type, (c, a, v) -> true); + public ShipIdentifiableArgument(String id, Supplier> all) { + this(id, all, (c, a, v) -> true); } - public ShipIdentifiableArgument(String id, Class type, - TriPredicate, ? super T> predicate) { + public ShipIdentifiableArgument(String id, + Supplier> all, + TriPredicate, ? super T> predicate) { this.id = id; - this.type = type; + this.all = all; this.predicate = predicate; } @@ -36,13 +38,11 @@ public String getId() { } @Override - public CommandArgumentResult parse(CommandContext context, CommandArgumentContext argument) throws - IOException { + public CommandArgumentResult parse(CommandContext context, CommandArgumentContext argument) + throws IOException { String arg = context.getCommand()[argument.getFirstArgument()]; - Optional opValue = ShipsPlugin - .getPlugin() - .getAll(this.type) - .parallelStream() + Optional opValue = this.all + .get() .filter(i -> i.getId().equalsIgnoreCase(arg)) .filter(v -> this.predicate.apply(context, argument, v)) .findAny(); @@ -55,10 +55,8 @@ public CommandArgumentResult parse(CommandContext context, CommandArgumentCon @Override public List suggest(CommandContext context, CommandArgumentContext argument) { String arg = context.getCommand()[argument.getFirstArgument()]; - return ShipsPlugin - .getPlugin() - .getAll(this.type) - .parallelStream() + return this.all + .get() .filter(i -> i.getId().startsWith(arg.toLowerCase()) || i.getName().startsWith(arg.toLowerCase())) .filter(v -> this.predicate.apply(context, argument, v)) .map(Identifiable::getId) diff --git a/src/main/java/org/ships/commands/argument/arguments/identifiable/crew/CrewPermissionArgument.java b/src/main/java/org/ships/commands/argument/arguments/identifiable/crew/CrewPermissionArgument.java index f55d839e..696598c1 100644 --- a/src/main/java/org/ships/commands/argument/arguments/identifiable/crew/CrewPermissionArgument.java +++ b/src/main/java/org/ships/commands/argument/arguments/identifiable/crew/CrewPermissionArgument.java @@ -5,16 +5,15 @@ import org.core.utils.lamda.tri.TriPredicate; import org.ships.commands.argument.arguments.identifiable.ShipIdentifiableArgument; import org.ships.permissions.vessel.CrewPermission; +import org.ships.permissions.vessel.CrewPermissions; public class CrewPermissionArgument extends ShipIdentifiableArgument { - public CrewPermissionArgument(String id, Class type) { - super(id, type); + public CrewPermissionArgument(String id) { + super(id, () -> CrewPermissions.permissions().stream()); } public CrewPermissionArgument(String id, - Class type, - TriPredicate, ? super CrewPermission> predicate) { - super(id, type, predicate); + TriPredicate, ? super CrewPermission> predicate) { + super(id, () -> CrewPermissions.permissions().stream(), predicate); } } diff --git a/src/main/java/org/ships/commands/argument/blockinfo/ShipsBlockInfoArgumentCommand.java b/src/main/java/org/ships/commands/argument/blockinfo/ShipsBlockInfoArgumentCommand.java index dfc55a30..1c5d6f02 100644 --- a/src/main/java/org/ships/commands/argument/blockinfo/ShipsBlockInfoArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/blockinfo/ShipsBlockInfoArgumentCommand.java @@ -1,9 +1,8 @@ package org.ships.commands.argument.blockinfo; -import org.array.utils.ArrayUtils; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.core.TranslateCore; -import org.core.adventureText.AText; -import org.core.adventureText.format.NamedTextColours; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.CommandArgumentResult; @@ -17,7 +16,6 @@ import org.core.exceptions.NotEnoughArguments; import org.core.permission.Permission; import org.core.source.command.CommandSource; -import org.core.source.viewer.CommandViewer; import org.core.utils.Identifiable; import org.core.world.WorldExtent; import org.core.world.position.block.BlockType; @@ -47,7 +45,7 @@ public CommandArgumentResult parse(CommandContext context, if (!(context.getSource() instanceof LivePlayer)) { return CommandArgumentResult.from(argument, 0, null); } - Optional opBlockType = ((LivePlayer)context.getSource()).getBlockLookingAt(); + Optional opBlockType = ((LivePlayer) context.getSource()).getBlockLookingAt(); return CommandArgumentResult.from(argument, 0, opBlockType.map(Position::getBlockType).orElse(null)); } }); @@ -72,38 +70,41 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou CommandSource viewer = commandContext.getSource(); BlockType bt = commandContext.getArgument(this, BLOCK_TYPE); if (bt == null) { - viewer.sendMessage(AText.ofPlain("BlockType id isn't valid").withColour(NamedTextColours.RED)); + viewer.sendMessage(Component.text("BlockType id isn't valid").color(NamedTextColor.RED)); return false; } - viewer.sendMessage(AText.ofPlain("--[" + bt.getName() + "]--")); + viewer.sendMessage(Component.text("--[" + bt.getName() + "]--")); BlockDetails details = bt.getDefaultBlockDetails(); - viewer.sendMessage(AText.ofPlain("---[ID]---")); - viewer.sendMessage(AText.ofPlain(" |- ID: " + details.getType().getId())); - viewer.sendMessage(AText.ofPlain(" |- BlockList-CollideType: " + ShipsPlugin + viewer.sendMessage(Component.text("---[ID]---")); + viewer.sendMessage(Component.text(" |- ID: " + details.getType().getId())); + viewer.sendMessage(Component.text(" |- BlockList-CollideType: " + ShipsPlugin .getPlugin() .getBlockList() .getBlockInstruction(details.getType()) .getCollide() .name())); - viewer.sendMessage(AText.ofPlain("---[Keyed Data]---")); + viewer.sendMessage(Component.text("---[Keyed Data]---")); for (Map.Entry>> dataClass : KeyedData.getDefaultKeys().entrySet()) { if (details.getUnspecified(dataClass.getValue()).isPresent()) { - viewer.sendMessage(AText.ofPlain(" |- " + dataClass.getKey())); + viewer.sendMessage(Component.text(" |- " + dataClass.getKey())); } } if (details.getDirectionalData().isPresent()) { - viewer.sendMessage(AText.ofPlain(" |- Directional")); + viewer.sendMessage(Component.text(" |- Directional")); } - viewer.sendMessage(AText.ofPlain("---[Priority]---")); - WorldExtent world = TranslateCore.getServer().getWorlds().iterator().next(); + viewer.sendMessage(Component.text("---[Priority]---")); + WorldExtent world = TranslateCore.getServer().getWorldExtents().findFirst().orElseThrow(() -> new RuntimeException("Minecraft server should always have a world loaded")); BlockPriority priority = new SetMovingBlock(world.getPosition(0, 0, 0), world.getPosition(0, 0, 0), details).getBlockPriority(); - viewer.sendMessage(AText.ofPlain(" |- ID: " + priority.getId())); - viewer.sendMessage(AText.ofPlain(" |- Value: " + priority.getPriorityNumber())); - viewer.sendMessage(AText.ofPlain("---[Like]---")); - String like = ArrayUtils.toString("\n |- ", Identifiable::getName, - bt.getLike().parallelStream().limit(5).collect(Collectors.toList())); - viewer.sendMessage(AText.ofPlain("\n |- " + like)); + viewer.sendMessage(Component.text(" |- ID: " + priority.getId())); + viewer.sendMessage(Component.text(" |- Value: " + priority.getPriorityNumber())); + viewer.sendMessage(Component.text("---[Like]---")); + String like = bt + .getAlike() + .limit(5) + .map(Identifiable::getName) + .collect(Collectors.joining("\n |- ")); + viewer.sendMessage(Component.text("\n |- " + like)); return true; } } diff --git a/src/main/java/org/ships/commands/argument/blocklist/ShipsBlockListViewArgumentCommand.java b/src/main/java/org/ships/commands/argument/blocklist/ShipsBlockListViewArgumentCommand.java index 46d9f0fd..6034985c 100644 --- a/src/main/java/org/ships/commands/argument/blocklist/ShipsBlockListViewArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/blocklist/ShipsBlockListViewArgumentCommand.java @@ -1,7 +1,7 @@ package org.ships.commands.argument.blocklist; -import org.core.adventureText.AText; -import org.core.adventureText.format.NamedTextColours; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; @@ -10,7 +10,6 @@ import org.core.exceptions.NotEnoughArguments; import org.core.permission.Permission; import org.core.source.command.CommandSource; -import org.core.source.viewer.CommandViewer; import org.ships.config.blocks.instruction.BlockInstruction; import org.ships.config.blocks.instruction.CollideType; import org.ships.permissions.Permissions; @@ -43,7 +42,7 @@ public boolean hasPermission(CommandSource source) { if (source instanceof LivePlayer) { return ((LivePlayer) source).hasPermission(this.getPermissionNode().get()); } - return source instanceof CommandViewer; + return true; } @Override @@ -57,12 +56,12 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou for (BlockInstruction bi : bl) { values.replace(bi.getCollide(), values.get(bi.getCollide()) + 1); } - values.forEach((c, a) -> viewer.sendMessage(AText - .ofPlain(c.name() + ": ") - .withColour(NamedTextColours.AQUA) - .append(AText - .ofPlain(a.toString()) - .withColour(NamedTextColours.YELLOW)))); + values.forEach((c, a) -> viewer.sendMessage(Component + .text(c.name() + ": ") + .color(NamedTextColor.AQUA) + .append(Component + .text(a.toString()) + .color(NamedTextColor.YELLOW)))); return true; } } diff --git a/src/main/java/org/ships/commands/argument/blocklist/ShipsBlockListViewBlockArgumentCommand.java b/src/main/java/org/ships/commands/argument/blocklist/ShipsBlockListViewBlockArgumentCommand.java index 3e413547..2776f80d 100644 --- a/src/main/java/org/ships/commands/argument/blocklist/ShipsBlockListViewBlockArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/blocklist/ShipsBlockListViewBlockArgumentCommand.java @@ -12,7 +12,6 @@ import org.core.permission.Permission; import org.core.source.Messageable; import org.core.source.command.CommandSource; -import org.core.source.viewer.CommandViewer; import org.core.world.position.block.BlockType; import org.ships.config.blocks.instruction.BlockInstruction; import org.ships.permissions.Permissions; @@ -46,9 +45,6 @@ public Optional getPermissionNode() { @Override public boolean run(CommandContext commandContext, String... args) throws NotEnoughArguments { - if (!(commandContext.getSource() instanceof CommandViewer)) { - return false; - } Messageable viewer = commandContext.getSource(); BlockType type = commandContext.getArgument(this, SHIP_BLOCK_TYPE_ARGUMENT); BlockInstruction bi = ShipsPlugin.getPlugin().getBlockList().getBlockInstruction(type); @@ -70,6 +66,6 @@ public boolean hasPermission(CommandSource source) { if (source instanceof LivePlayer) { return ((LivePlayer) source).hasPermission(this.getPermissionNode().get()); } - return source instanceof CommandViewer; + return true; } } diff --git a/src/main/java/org/ships/commands/argument/blocklist/set/ShipsBlockListSetBlockLimitArgumentCommand.java b/src/main/java/org/ships/commands/argument/blocklist/set/ShipsBlockListSetBlockLimitArgumentCommand.java index 42012946..c7450af1 100644 --- a/src/main/java/org/ships/commands/argument/blocklist/set/ShipsBlockListSetBlockLimitArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/blocklist/set/ShipsBlockListSetBlockLimitArgumentCommand.java @@ -1,7 +1,7 @@ package org.ships.commands.argument.blocklist.set; -import org.core.adventureText.AText; -import org.core.adventureText.format.NamedTextColours; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.id.BlockTypesArgument; @@ -10,7 +10,6 @@ import org.core.command.argument.context.CommandContext; import org.core.exceptions.NotEnoughArguments; import org.core.permission.Permission; -import org.core.source.viewer.CommandViewer; import org.core.world.position.block.BlockType; import org.ships.config.blocks.DefaultBlockList; import org.ships.config.blocks.instruction.ModifiableBlockInstruction; @@ -32,8 +31,9 @@ public class ShipsBlockListSetBlockLimitArgumentCommand implements ArgumentComma @Override public List> getArguments() { return Arrays.asList(new ExactArgument(SHIP_BLOCK_LIST_ARGUMENT), new ExactArgument(SHIP_SET_ARGUMENT), - new ExactArgument(SHIP_BLOCK_LIMIT_ARGUMENT), new IntegerArgument(SHIP_LIMIT_VALUE_ARGUMENT), - new BlockTypesArgument(SHIP_BLOCK_TYPE_ARGUMENT)); + new ExactArgument(SHIP_BLOCK_LIMIT_ARGUMENT), + new IntegerArgument(SHIP_LIMIT_VALUE_ARGUMENT), + new BlockTypesArgument(SHIP_BLOCK_TYPE_ARGUMENT)); } @Override @@ -56,13 +56,13 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou .stream() .filter(bi -> blocks.stream().anyMatch(b -> bi.getType().equals(b))) .filter(bi -> bi instanceof ModifiableBlockInstruction) - .forEach(bi -> blocklist.replaceBlockInstruction(((ModifiableBlockInstruction)bi).setBlockLimit(limit))); + .forEach(bi -> blocklist.replaceBlockInstruction( + ((ModifiableBlockInstruction) bi).setBlockLimit(limit))); blocklist.saveChanges(); - if (commandContext.getSource() instanceof CommandViewer) { - ((CommandViewer) commandContext.getSource()).sendMessage(AText.ofPlain(blocks.size() + " have been set to" + - " have a block limit of " + limit).withColour(NamedTextColours.AQUA)); - - } + Component text = Component + .text(blocks.size() + " have been set to have a block limit of " + limit) + .color(NamedTextColor.AQUA); + commandContext.getSource().sendMessage(text); return true; } } diff --git a/src/main/java/org/ships/commands/argument/blocklist/set/ShipsBlockListSetCollideTypeArgumentCommand.java b/src/main/java/org/ships/commands/argument/blocklist/set/ShipsBlockListSetCollideTypeArgumentCommand.java index ed43050e..517f75ef 100644 --- a/src/main/java/org/ships/commands/argument/blocklist/set/ShipsBlockListSetCollideTypeArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/blocklist/set/ShipsBlockListSetCollideTypeArgumentCommand.java @@ -1,7 +1,7 @@ package org.ships.commands.argument.blocklist.set; -import org.core.adventureText.AText; -import org.core.adventureText.format.NamedTextColours; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.id.BlockTypesArgument; @@ -10,7 +10,6 @@ import org.core.command.argument.context.CommandContext; import org.core.exceptions.NotEnoughArguments; import org.core.permission.Permission; -import org.core.source.viewer.CommandViewer; import org.core.world.position.block.BlockType; import org.ships.config.blocks.DefaultBlockList; import org.ships.config.blocks.instruction.CollideType; @@ -61,13 +60,12 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou .forEach(bi -> blocklist.replaceBlockInstruction( ((ModifiableBlockInstruction) bi).setCollide(collideType))); blocklist.saveChanges(); - if (commandContext.getSource() instanceof CommandViewer) { - ((CommandViewer) commandContext.getSource()).sendMessage(AText - .ofPlain(blocks.size() - + " have been set to " - + collideType.name()) - .withColour(NamedTextColours.AQUA)); - } + + Component text = Component + .text(blocks.size() + " have been set to " + collideType.name()) + .color(NamedTextColor.AQUA); + commandContext.getSource().sendMessage(text); + return true; } } diff --git a/src/main/java/org/ships/commands/argument/config/shiptype/ShipTypeSetSingleConfigArgument.java b/src/main/java/org/ships/commands/argument/config/shiptype/ShipTypeSetSingleConfigArgument.java index 6172bd26..62f54d9b 100644 --- a/src/main/java/org/ships/commands/argument/config/shiptype/ShipTypeSetSingleConfigArgument.java +++ b/src/main/java/org/ships/commands/argument/config/shiptype/ShipTypeSetSingleConfigArgument.java @@ -1,7 +1,7 @@ package org.ships.commands.argument.config.shiptype; -import org.core.adventureText.AText; -import org.core.adventureText.format.NamedTextColours; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; @@ -15,6 +15,7 @@ import org.ships.commands.argument.arguments.identifiable.shiptype.ShipTypeSingleValueArgument; import org.ships.permissions.Permissions; import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import java.util.Arrays; import java.util.List; @@ -32,7 +33,7 @@ public class ShipTypeSetSingleConfigArgument implements ArgumentCommand { public List> getArguments() { return Arrays.asList(new ExactArgument(COMMAND_NAME, false, "config"), new ExactArgument("set"), new ExactArgument(CONFIG_TYPE, false, "shiptype"), - new ShipIdentifiableArgument<>(SHIP_TYPE, ShipType.class), + new ShipIdentifiableArgument<>(SHIP_TYPE, () -> ShipTypes.shipTypes().stream()), new ShipTypeSingleKeyArgument(CONFIG_KEY), new ShipTypeSingleValueArgument<>(CONFIG_VALUE, (c, a) -> c.getArgument( this, @@ -61,7 +62,7 @@ private boolean runGeneric(CommandContext commandContext, String... args) th ConfigurationStream.ConfigurationFile file = type.getFile(); file.set(parser, value); file.save(); - AText text = AText.ofPlain("Value has been set").withColour(NamedTextColours.AQUA); + Component text = Component.text("Value has been set").color(NamedTextColor.AQUA); commandContext.getSource().sendMessage(text); return true; } diff --git a/src/main/java/org/ships/commands/argument/config/shiptype/ShipTypeViewSingleConfigArgument.java b/src/main/java/org/ships/commands/argument/config/shiptype/ShipTypeViewSingleConfigArgument.java index 7798f6d0..665902d0 100644 --- a/src/main/java/org/ships/commands/argument/config/shiptype/ShipTypeViewSingleConfigArgument.java +++ b/src/main/java/org/ships/commands/argument/config/shiptype/ShipTypeViewSingleConfigArgument.java @@ -14,6 +14,7 @@ import org.ships.commands.argument.arguments.identifiable.shiptype.ShipTypeSingleKeyArgument; import org.ships.permissions.Permissions; import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import java.util.Arrays; import java.util.List; @@ -30,7 +31,7 @@ public class ShipTypeViewSingleConfigArgument implements ArgumentCommand { public List> getArguments() { return Arrays.asList(new ExactArgument(COMMAND_NAME, false, "config"), new ExactArgument("view"), new ExactArgument(CONFIG_TYPE, false, "shiptype"), - new ShipIdentifiableArgument<>(SHIP_TYPE, ShipType.class), + new ShipIdentifiableArgument<>(SHIP_TYPE, () -> ShipTypes.shipTypes().stream()), new ShipTypeSingleKeyArgument(CONFIG_KEY)); } diff --git a/src/main/java/org/ships/commands/argument/create/CreateShipCommand.java b/src/main/java/org/ships/commands/argument/create/CreateShipCommand.java index 07a00d30..a8dd4166 100644 --- a/src/main/java/org/ships/commands/argument/create/CreateShipCommand.java +++ b/src/main/java/org/ships/commands/argument/create/CreateShipCommand.java @@ -32,8 +32,10 @@ import org.ships.plugin.ShipsPlugin; import org.ships.vessel.common.finder.IdVesselFinder; import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import org.ships.vessel.common.types.Vessel; import org.ships.vessel.sign.LicenceSign; +import org.ships.vessel.sign.ShipsSigns; import java.io.IOException; import java.util.Arrays; @@ -45,7 +47,9 @@ public class CreateShipCommand implements ArgumentCommand { private static final ShipIdentifiableArgument> SHIP_TYPE = new ShipIdentifiableArgument<>("ship_type", - (Class>) (Object) ShipType.class); + () -> ShipTypes + .shipTypes() + .stream()); private static final ShipsStructureArgument STRUCTURE = new ShipsStructureArgument("structure"); private static final StringArgument NAME = new StringArgument("name"); @@ -81,7 +85,8 @@ public CommandArgumentResult parse(CommandContext context, CommandArgumentCon @Override public List> getArguments() { - return Arrays.asList(new ExactArgument("create"), X, Y, Z, WORLD, STRUCTURE, SHIP_TYPE, NAME); + return Arrays.asList(new ExactArgument("create"), this.X, this.Y, this.Z, this.WORLD, STRUCTURE, SHIP_TYPE, + NAME); } @Override @@ -96,10 +101,10 @@ public Optional getPermissionNode() { @Override public boolean run(CommandContext commandContext, String... args) throws NotEnoughArguments { - Integer x = commandContext.getArgument(this, X); - Integer y = commandContext.getArgument(this, Y); - Integer z = commandContext.getArgument(this, Z); - WorldExtent world = commandContext.getArgument(this, WORLD); + Integer x = commandContext.getArgument(this, this.X); + Integer y = commandContext.getArgument(this, this.Y); + Integer z = commandContext.getArgument(this, this.Z); + WorldExtent world = commandContext.getArgument(this, this.WORLD); ShipType shipType = commandContext.getArgument(this, SHIP_TYPE); Structure structure = commandContext.getArgument(this, STRUCTURE); String name = commandContext.getArgument(this, NAME); @@ -167,10 +172,7 @@ private Map.Entry findLicence(Structure structure, continue; } LiveSignTileEntity ste = (LiveSignTileEntity) opTile.get(); - LicenceSign licence = ShipsPlugin - .getPlugin() - .get(LicenceSign.class) - .orElseThrow(() -> new RuntimeException("Could not find licence sign in register.")); + LicenceSign licence = ShipsSigns.LICENCE; if (licence.isSign(ste)) { return Map.entry(ste, licence.getSide(ste).map(SignSide::isFront).orElse(false)); } diff --git a/src/main/java/org/ships/commands/argument/help/ShipsHelpArgumentCommand.java b/src/main/java/org/ships/commands/argument/help/ShipsHelpArgumentCommand.java index e69eb34e..96e91358 100644 --- a/src/main/java/org/ships/commands/argument/help/ShipsHelpArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/help/ShipsHelpArgumentCommand.java @@ -1,7 +1,7 @@ package org.ships.commands.argument.help; -import org.core.adventureText.AText; -import org.core.adventureText.format.NamedTextColours; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; @@ -10,7 +10,6 @@ import org.core.exceptions.NotEnoughArguments; import org.core.permission.Permission; import org.core.source.command.CommandSource; -import org.core.source.viewer.CommandViewer; import org.ships.commands.argument.ShipsArgumentCommand; import java.util.*; @@ -78,15 +77,13 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou for (ArgumentCommand cmd : commands) { List> arguments = cmd.getArguments(); if (arguments.isEmpty()) { - viewer.sendMessage(AText.ofPlain(cmd.getDescription()).withColour(NamedTextColours.YELLOW)); + viewer.sendMessage(Component.text(cmd.getDescription()).color(NamedTextColor.YELLOW)); continue; } - viewer.sendMessage(AText - .ofPlain(arguments.get(0).getUsage() + ":") - .withColour(NamedTextColours.AQUA) - .append(AText - .ofPlain(cmd.getDescription()) - .withColour(NamedTextColours.YELLOW))); + viewer.sendMessage(Component.text(arguments.get(0).getUsage() + ":") + .color(NamedTextColor.AQUA) + .append(Component.text(cmd.getDescription()) + .color(NamedTextColor.YELLOW))); } return true; } diff --git a/src/main/java/org/ships/commands/argument/info/ShipsInfoArgumentCommand.java b/src/main/java/org/ships/commands/argument/info/ShipsInfoArgumentCommand.java index edcbc37d..14d4d31f 100644 --- a/src/main/java/org/ships/commands/argument/info/ShipsInfoArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/info/ShipsInfoArgumentCommand.java @@ -1,8 +1,8 @@ package org.ships.commands.argument.info; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.core.TranslateCore; -import org.core.adventureText.AText; -import org.core.adventureText.format.NamedTextColours; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; @@ -12,16 +12,15 @@ import org.core.permission.Permission; import org.core.platform.PlatformDetails; import org.core.source.command.CommandSource; -import org.core.source.viewer.CommandViewer; import org.ships.permissions.Permissions; import org.ships.plugin.ShipsPlugin; import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; public class ShipsInfoArgumentCommand implements ArgumentCommand { @@ -48,50 +47,48 @@ public Optional getPermissionNode() { @Override public boolean run(CommandContext commandContext, String... args) throws NotEnoughArguments { CommandSource viewer = commandContext.getSource(); - Collection> shipTypes = ShipsPlugin.getPlugin().getAllShipTypes(); - viewer.sendMessage(AText.ofPlain("----[Ships]----").withColour(NamedTextColours.YELLOW)); - viewer.sendMessage(AText - .ofPlain("Ships Version: ") - .withColour(NamedTextColours.AQUA) - .append(AText - .ofPlain(ShipsPlugin.getPlugin().getPluginVersion().asString()) - .withColour(NamedTextColours.GOLD))); - viewer.sendMessage(AText - .ofPlain("Ships " + ShipsPlugin.PRERELEASE_TAG + " Version: ") - .withColour(NamedTextColours.AQUA) - .append(AText - .ofPlain(ShipsPlugin.PRERELEASE_VERSION + "") - .withColour(NamedTextColours.GOLD))); + Collection> shipTypes = ShipTypes.shipTypes(); + viewer.sendMessage(Component.text("----[Ships]----").color(NamedTextColor.YELLOW)); + viewer.sendMessage(Component + .text("Ships Version: ") + .color(NamedTextColor.AQUA) + .append(Component + .text(ShipsPlugin.getPlugin().getPluginVersion().asString()) + .color(NamedTextColor.GOLD))); + viewer.sendMessage(Component + .text("Ships " + ShipsPlugin.PRERELEASE_TAG + " Version: ") + .color(NamedTextColor.AQUA) + .append(Component + .text(ShipsPlugin.PRERELEASE_VERSION + "") + .color(NamedTextColor.GOLD))); viewer.sendMessage(this.readVersion(TranslateCore.getPlatform().getDetails())); viewer.sendMessage(this.readVersion(TranslateCore.getPlatform().getTranslateCoreDetails())); viewer.sendMessage(this.readVersion(TranslateCore.getPlatform().getImplementationDetails())); - viewer.sendMessage(AText - .ofPlain("Vessel Types: ") - .withColour(NamedTextColours.AQUA) - .append(AText.ofPlain(shipTypes.size() + "").withColour(NamedTextColours.GOLD))); + viewer.sendMessage(Component + .text("Vessel Types: ") + .color(NamedTextColor.AQUA) + .append(Component.text(shipTypes.size() + "").color(NamedTextColor.GOLD))); if (commandContext.getArgument(this, SHIP_TYPE_ARGUMENT) != null) { - List typeText = shipTypes - .stream() - .map(s -> AText.ofPlain(s.getDisplayName()).withColour(NamedTextColours.GOLD)) - .collect(Collectors.toList()); - AText text = null; + Component text = null; for (ShipType shipType : shipTypes) { - AText displayName = AText.ofPlain(shipType.getDisplayName()).withColour(NamedTextColours.GOLD); + Component displayName = Component.text(shipType.getDisplayName()).color(NamedTextColor.GOLD); if (text == null) { text = displayName; continue; } - text = text.append(AText.ofPlain(" | ").withColour(NamedTextColours.GREEN)).append(displayName); + text = text.append(Component.text(" | ").color(NamedTextColor.GREEN)).append(displayName); + } + if (text != null) { + viewer.sendMessage(text); } - viewer.sendMessage(text); } return true; } - private AText readVersion(PlatformDetails details) { - return AText - .ofPlain(details.getName() + ": ") - .withColour(NamedTextColours.AQUA) - .append(AText.ofPlain(details.getVersion().asString()).withColour(NamedTextColours.GOLD)); + private Component readVersion(PlatformDetails details) { + return Component + .text(details.getName() + ": ") + .color(NamedTextColor.AQUA) + .append(Component.text(details.getVersion().asString()).color(NamedTextColor.GOLD)); } } diff --git a/src/main/java/org/ships/commands/argument/ship/check/ShipsShipCheckArgumentCommand.java b/src/main/java/org/ships/commands/argument/ship/check/ShipsShipCheckArgumentCommand.java index 088417cc..cf2d5e17 100644 --- a/src/main/java/org/ships/commands/argument/ship/check/ShipsShipCheckArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/ship/check/ShipsShipCheckArgumentCommand.java @@ -1,6 +1,6 @@ package org.ships.commands.argument.ship.check; -import org.core.adventureText.AText; +import net.kyori.adventure.text.Component; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; @@ -72,7 +72,7 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou CommandSource source = commandContext.getSource(); Vessel vessel = commandContext.getArgument(this, SHIP_ID_ARGUMENT); if (vessel instanceof Fallable) { - source.sendMessage(AText.ofPlain("Will Fall: " + ((Fallable)vessel).shouldFall())); + source.sendMessage(Component.text("Will Fall: " + ((Fallable) vessel).shouldFall())); } if (!(vessel instanceof VesselRequirement)) { return true; @@ -80,8 +80,7 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou VesselRequirement rVessel = (VesselRequirement) vessel; MovingBlockSet set = rVessel .getStructure() - .getSyncedPositionsRelativeToWorld() - .stream() + .getPositionsRelativeToWorld() .map(block -> new SetMovingBlock(block, block)) .collect(Collectors.toCollection(MovingBlockSet::new)); @@ -91,10 +90,10 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou try { rVessel.checkRequirements(context); - source.sendMessage(AText.ofPlain("Meets Requirements: true")); + source.sendMessage(Component.text("Meets Requirements: true")); } catch (MoveException e) { - source.sendMessage(AText.ofPlain("Meets Requirements: false")); - source.sendMessage(e.getErrorMessageText()); + source.sendMessage(Component.text("Meets Requirements: false")); + source.sendMessage(e.getErrorMessage()); } return true; diff --git a/src/main/java/org/ships/commands/argument/ship/crew/ShipAddCrewArgumentCommand.java b/src/main/java/org/ships/commands/argument/ship/crew/ShipAddCrewArgumentCommand.java index bcccdc9a..faa46e44 100644 --- a/src/main/java/org/ships/commands/argument/ship/crew/ShipAddCrewArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/ship/crew/ShipAddCrewArgumentCommand.java @@ -1,7 +1,7 @@ package org.ships.commands.argument.ship.crew; -import org.core.adventureText.AText; -import org.core.adventureText.format.NamedTextColours; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; @@ -12,9 +12,9 @@ import org.core.entity.living.human.player.User; import org.core.exceptions.NotEnoughArguments; import org.core.permission.Permission; -import org.core.source.viewer.CommandViewer; import org.ships.commands.argument.arguments.ShipIdArgument; import org.ships.commands.argument.arguments.identifiable.ShipIdentifiableArgument; +import org.ships.commands.argument.arguments.identifiable.crew.CrewPermissionArgument; import org.ships.permissions.Permissions; import org.ships.permissions.vessel.CrewPermission; import org.ships.vessel.common.assits.CrewStoredVessel; @@ -43,7 +43,7 @@ public List> getArguments() { return vessel instanceof CrewStoredVessel; }, v -> "Vessel does not accept crew"), new ExactArgument(this.SHIP_CREW_ARGUMENT), new ExactArgument(this.SHIP_VIEW_ARGUMENT), - new ShipIdentifiableArgument<>(this.SHIP_CREW_PERMISSION_ARGUMENT, CrewPermission.class), + new CrewPermissionArgument(this.SHIP_CREW_PERMISSION_ARGUMENT), new RemainingArgument<>(this.SHIP_PLAYERS_ARGUMENT, new UserArgument(this.SHIP_PLAYERS_ARGUMENT))); } @@ -75,10 +75,8 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou map.put(user.getUniqueId(), permission); } }); - if (commandContext.getSource() instanceof CommandViewer) { - ((CommandViewer) commandContext.getSource()).sendMessage( - AText.ofPlain("Added crew member(s)").withColour(NamedTextColours.AQUA)); - } + Component text = Component.text("Added crew members(s)").color(NamedTextColor.AQUA); + commandContext.getSource().sendMessage(text); return true; } } diff --git a/src/main/java/org/ships/commands/argument/ship/crew/ShipRemoveCrewArgumentCommand.java b/src/main/java/org/ships/commands/argument/ship/crew/ShipRemoveCrewArgumentCommand.java index ceeed5b2..5c23a828 100644 --- a/src/main/java/org/ships/commands/argument/ship/crew/ShipRemoveCrewArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/ship/crew/ShipRemoveCrewArgumentCommand.java @@ -1,7 +1,7 @@ package org.ships.commands.argument.ship.crew; -import org.core.adventureText.AText; -import org.core.adventureText.format.NamedTextColours; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; @@ -12,7 +12,6 @@ import org.core.entity.living.human.player.User; import org.core.exceptions.NotEnoughArguments; import org.core.permission.Permission; -import org.core.source.viewer.CommandViewer; import org.ships.commands.argument.arguments.ShipIdArgument; import org.ships.permissions.Permissions; import org.ships.permissions.vessel.CrewPermission; @@ -34,7 +33,9 @@ public List> getArguments() { new ShipIdArgument<>(this.SHIP_ID_ARGUMENT, (source, vessel) -> { if (source instanceof LivePlayer && vessel instanceof CrewStoredVessel) { User player = (User) source; - return ((CrewStoredVessel)vessel).getPermission(player.getUniqueId()).canCommand(); + return ((CrewStoredVessel) vessel) + .getPermission(player.getUniqueId()) + .canCommand(); } return vessel instanceof CrewStoredVessel; }, v -> "Vessel does not accept crew"), new ExactArgument(this.SHIP_CREW_ARGUMENT), @@ -59,10 +60,9 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou Map map = vessel.getCrew(); List users = commandContext.getArgument(this, this.SHIP_PLAYERS_ARGUMENT); users.forEach(user -> map.remove(user.getUniqueId())); - if (commandContext.getSource() instanceof CommandViewer) { - ((CommandViewer) commandContext.getSource()).sendMessage( - AText.ofPlain("Removed crew member(s)").withColour(NamedTextColours.AQUA)); - } + + Component text = Component.text("Removed crew member(s)").color(NamedTextColor.AQUA); + commandContext.getSource().sendMessage(text); return true; } } diff --git a/src/main/java/org/ships/commands/argument/ship/crew/ShipViewCrewArgumentCommand.java b/src/main/java/org/ships/commands/argument/ship/crew/ShipViewCrewArgumentCommand.java index eeeabb81..fbfca8dd 100644 --- a/src/main/java/org/ships/commands/argument/ship/crew/ShipViewCrewArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/ship/crew/ShipViewCrewArgumentCommand.java @@ -1,7 +1,7 @@ package org.ships.commands.argument.ship.crew; +import net.kyori.adventure.text.Component; import org.core.TranslateCore; -import org.core.adventureText.AText; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; @@ -13,10 +13,10 @@ import org.core.exceptions.NotEnoughArguments; import org.core.permission.Permission; import org.core.source.command.CommandSource; -import org.core.source.viewer.CommandViewer; import org.core.utils.Else; import org.ships.commands.argument.arguments.ShipIdArgument; import org.ships.commands.argument.arguments.identifiable.ShipIdentifiableArgument; +import org.ships.commands.argument.arguments.identifiable.crew.CrewPermissionArgument; import org.ships.permissions.vessel.CrewPermission; import org.ships.vessel.common.assits.CrewStoredVessel; @@ -36,14 +36,15 @@ public List> getArguments() { new ShipIdArgument<>(this.SHIP_ID_ARGUMENT, (source, vessel) -> { if (source instanceof LivePlayer && vessel instanceof CrewStoredVessel) { User player = (User) source; - return ((CrewStoredVessel)vessel).getPermission(player.getUniqueId()).canCommand(); + return ((CrewStoredVessel) vessel) + .getPermission(player.getUniqueId()) + .canCommand(); } return vessel instanceof CrewStoredVessel; }, v -> "Vessel does not accept crew"), new ExactArgument(this.SHIP_CREW_ARGUMENT), new ExactArgument(this.SHIP_VIEW_ARGUMENT), new OptionalArgument<>( new RemainingArgument<>(this.SHIP_CREW_PERMISSION_ARGUMENT, - new ShipIdentifiableArgument<>(this.SHIP_CREW_PERMISSION_ARGUMENT, - CrewPermission.class)), + new CrewPermissionArgument(this.SHIP_CREW_PERMISSION_ARGUMENT)), Collections.emptyList())); } @@ -70,7 +71,7 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou } permissionsToShow.forEach(crewPermission -> { - viewer.sendMessage(AText.ofPlain(crewPermission.getName())); + viewer.sendMessage(Component.text(crewPermission.getName())); vessel .getCrew(crewPermission) .stream() @@ -80,7 +81,7 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou .filter(Optional::isPresent) .map(Optional::get) - .forEach(user -> viewer.sendMessage(AText.ofPlain("- " + user.getName()))); + .forEach(user -> viewer.sendMessage(Component.text("- " + user.getName()))); }); return true; } diff --git a/src/main/java/org/ships/commands/argument/ship/data/block/special/percent/ShipsDataSetSpecialBlockPercentCommand.java b/src/main/java/org/ships/commands/argument/ship/data/block/special/percent/ShipsDataSetSpecialBlockPercentCommand.java index 5b4d8a23..791d7c6d 100644 --- a/src/main/java/org/ships/commands/argument/ship/data/block/special/percent/ShipsDataSetSpecialBlockPercentCommand.java +++ b/src/main/java/org/ships/commands/argument/ship/data/block/special/percent/ShipsDataSetSpecialBlockPercentCommand.java @@ -1,7 +1,7 @@ package org.ships.commands.argument.ship.data.block.special.percent; -import org.core.adventureText.AText; -import org.core.adventureText.format.NamedTextColours; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; import org.core.command.argument.arguments.operation.OptionalArgument; @@ -45,7 +45,7 @@ protected boolean apply(CommandContext context, Vessel vessel, String[] argument if (!(vessel instanceof VesselRequirement)) { return false; } - VesselRequirement requirementVessel = (VesselRequirement)vessel; + VesselRequirement requirementVessel = (VesselRequirement) vessel; Optional opRequirement = requirementVessel.getRequirement( SpecialBlocksRequirement.class); if (opRequirement.isEmpty()) { @@ -57,14 +57,12 @@ protected boolean apply(CommandContext context, Vessel vessel, String[] argument if (value > 100) { context .getSource() - .sendMessage(AText.ofPlain("Percent cannot be above 100%").withColour(NamedTextColours.RED)); + .sendMessage(Component.text("Percent cannot be above 100%").color(NamedTextColor.RED)); return false; } if (value < 0) { - context - .getSource() - .sendMessage(AText.ofPlain("Percent cannot be below 0%").withColour(NamedTextColours.RED)); + context.getSource().sendMessage(Component.text("Percent cannot be below 0%").color(NamedTextColor.RED)); return false; } diff --git a/src/main/java/org/ships/commands/argument/ship/data/speed/max/ShipsDataSetMaxSpeedCommand.java b/src/main/java/org/ships/commands/argument/ship/data/speed/max/ShipsDataSetMaxSpeedCommand.java index 8fde9ecb..f6bbdf55 100644 --- a/src/main/java/org/ships/commands/argument/ship/data/speed/max/ShipsDataSetMaxSpeedCommand.java +++ b/src/main/java/org/ships/commands/argument/ship/data/speed/max/ShipsDataSetMaxSpeedCommand.java @@ -1,6 +1,6 @@ package org.ships.commands.argument.ship.data.speed.max; -import org.core.adventureText.AText; +import net.kyori.adventure.text.Component; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; import org.core.command.argument.arguments.operation.OptionalArgument; @@ -35,7 +35,7 @@ protected boolean apply(CommandContext context, Vessel vessel, String[] argument int displayValue = Objects.requireNonNullElseGet(value, () -> vessel.getType().getDefaultMaxSpeed()); context .getSource() - .sendMessage(AText.ofPlain( + .sendMessage(Component.text( "Updated " + Else.throwOr(NoLicencePresent.class, vessel::getName, "Unknown") + " max speed to " + displayValue)); diff --git a/src/main/java/org/ships/commands/argument/ship/eot/ShipsShipEOTEnableArgumentCommand.java b/src/main/java/org/ships/commands/argument/ship/eot/ShipsShipEOTEnableArgumentCommand.java index ef52bfe5..b39f864e 100644 --- a/src/main/java/org/ships/commands/argument/ship/eot/ShipsShipEOTEnableArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/ship/eot/ShipsShipEOTEnableArgumentCommand.java @@ -1,6 +1,6 @@ package org.ships.commands.argument.ship.eot; -import org.core.adventureText.AText; +import net.kyori.adventure.text.Component; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; @@ -10,20 +10,20 @@ import org.core.exceptions.NotEnoughArguments; import org.core.permission.Permission; import org.core.source.command.CommandSource; -import org.core.source.viewer.CommandViewer; import org.core.world.position.block.entity.LiveTileEntity; -import org.core.world.position.impl.sync.SyncBlockPosition; +import org.core.world.position.block.entity.sign.LiveSignTileEntity; import org.ships.commands.argument.arguments.ShipIdArgument; import org.ships.movement.autopilot.scheduler.EOTExecutor; import org.ships.permissions.Permissions; -import org.ships.plugin.ShipsPlugin; import org.ships.vessel.common.types.Vessel; import org.ships.vessel.sign.EOTSign; +import org.ships.vessel.sign.ShipsSigns; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; public class ShipsShipEOTEnableArgumentCommand implements ArgumentCommand { @@ -55,32 +55,37 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou CommandSource source = commandContext.getSource(); Vessel vessel = commandContext.getArgument(this, this.SHIP_ID_ARGUMENT); boolean enabled = commandContext.getArgument(this, this.SHIP_BOOLEAN_ARGUMENT); - EOTSign sign = ShipsPlugin.getPlugin().get(EOTSign.class).get(); + EOTSign signFunctions = ShipsSigns.EOT; if (!enabled) { - sign.getScheduler(vessel).forEach(s -> { + signFunctions.getScheduler(vessel).forEach(s -> { EOTExecutor exe = (EOTExecutor) s.getRunner(); - exe.getSign().ifPresent(liveSignTileEntity -> { - liveSignTileEntity.setTextAt(1, AText.ofPlain("Ahead")); - liveSignTileEntity.setTextAt(2, AText.ofPlain("{Stop}")); + var sign = exe.getSign(); + sign.ifPresent(liveSignTileEntity -> { + var side = signFunctions.getSide(liveSignTileEntity).orElseThrow(); + side.setLineAt(1, Component.text("Ahead")); + side.setLineAt(2, Component.text("{Stop}")); }); s.cancel(); }); return true; } - Collection eotSigns = vessel.getStructure().getAll(sign); + Collection eotSigns = vessel + .getStructure() + .getRelativeToWorld(signFunctions) + .collect(Collectors.toList()); if (eotSigns.size() == 1) { if (!(source instanceof LivePlayer)) { - (source).sendMessage(AText.ofPlain("Can only enable eot as a player")); + (source).sendMessage(Component.text("Can only enable eot as a player")); return false; } LivePlayer player = (LivePlayer) source; - LiveTileEntity lste = eotSigns.stream().findAny().get().getTileEntity().get(); - sign.onSecondClick(player, lste.getPosition()); + LiveTileEntity lste = eotSigns.stream().findAny().get(); + signFunctions.onSecondClick(player, lste.getPosition()); return true; - } else if (source instanceof CommandViewer) { - ((CommandViewer) source).sendMessage(AText.ofPlain("Found more then one EOT sign, unable to enable.")); } + Component text = Component.text("Found more then one EOT sign, unable to enable."); + source.sendMessage(text); return false; } } diff --git a/src/main/java/org/ships/commands/argument/ship/info/ShipsShipInfoArgumentCommand.java b/src/main/java/org/ships/commands/argument/ship/info/ShipsShipInfoArgumentCommand.java index 2ba2d592..8a284b8b 100644 --- a/src/main/java/org/ships/commands/argument/ship/info/ShipsShipInfoArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/ship/info/ShipsShipInfoArgumentCommand.java @@ -16,6 +16,8 @@ import org.ships.commands.argument.arguments.ShipIdArgument; import org.ships.config.messages.AdventureMessageConfig; import org.ships.config.messages.Message; +import org.ships.config.messages.Messages; +import org.ships.config.messages.adapter.MessageAdapters; import org.ships.exceptions.NoLicencePresent; import org.ships.permissions.vessel.CrewPermission; import org.ships.plugin.ShipsPlugin; @@ -72,45 +74,45 @@ private static String flagToString(Function, String> t public static void displayInfo(Messageable viewer, Vessel vessel) { AdventureMessageConfig messages = ShipsPlugin.getPlugin().getAdventureMessageConfig(); - Component infoName = AdventureMessageConfig.INFO_NAME + Component infoName = Messages.INFO_NAME .parseMessage(messages) .replaceText(TextReplacementConfig .builder() - .match("%" + Message.VESSEL_NAME.adapterText() + "%") + .match("%" + MessageAdapters.VESSEL_NAME.adapterText() + "%") .replacement(Else.throwOr(NoLicencePresent.class, vessel::getName, "Unknown")) .build()); if (vessel instanceof IdentifiableShip) { IdentifiableShip ship = (IdentifiableShip)vessel; - Component infoId = AdventureMessageConfig.INFO_ID + Component infoId = Messages.INFO_ID .parseMessage(messages) .replaceText(TextReplacementConfig .builder() - .match("%" + Message.VESSEL_ID.adapterText() + "%") + .match("%" + MessageAdapters.VESSEL_ID.adapterText() + "%") .replacement(Else.throwOr(NoLicencePresent.class, ship::getId, "Unknown")) .build()); viewer.sendMessage(infoId); } - Component maxSpeed = AdventureMessageConfig.INFO_MAX_SPEED + Component maxSpeed = Messages.INFO_MAX_SPEED .parseMessage(messages) .replaceText(TextReplacementConfig .builder() - .match("%" + Message.VESSEL_SPEED.adapterText() + "%") + .match("%" + MessageAdapters.VESSEL_SPEED.adapterText() + "%") .replacement(vessel.getMaxSpeed() + "") .build()); - Component altitudeSpeed = AdventureMessageConfig.INFO_ALTITUDE_SPEED + Component altitudeSpeed = Messages.INFO_ALTITUDE_SPEED .parseMessage(messages) .replaceText(TextReplacementConfig .builder() - .match("%" + Message.VESSEL_SPEED.adapterText() + "%") + .match("%" + MessageAdapters.VESSEL_SPEED.adapterText() + "%") .replacement(vessel.getAltitudeSpeed() + "") .build()); - Component size = AdventureMessageConfig.INFO_SIZE + Component size = Messages.INFO_SIZE .parseMessage(messages) .replaceText(TextReplacementConfig .builder() - .match("%" + Message.STRUCTURE_SIZE.adapterText() + "%") + .match("%" + MessageAdapters.STRUCTURE_SIZE.adapterText() + "%") .replacement( - vessel.getStructure().getOriginalRelativePositionsToCenter().size() + "") + vessel.getStructure().size() + "") .build()); viewer.sendMessage(infoName); @@ -126,15 +128,15 @@ public static void displayInfo(Messageable viewer, Vessel vessel) { .text(perm.getId()) .replaceText(TextReplacementConfig .builder() - .match("%" + Message.CREW_NAME.adapterText() + "%") + .match("%" + MessageAdapters.CREW_NAME.adapterText() + "%") .replacement(perm.getName()) .build()); - Component permission = AdventureMessageConfig.INFO_DEFAULT_PERMISSION + Component permission = Messages.INFO_DEFAULT_PERMISSION .parseMessage(messages) .replaceText(TextReplacementConfig .builder() - .match("%" + Message.CREW_ID.adapterText() + "%") + .match("%" + MessageAdapters.CREW_ID.adapterText() + "%") .replacement(replacementPermissionName) .build()); viewer.sendMessage(permission); @@ -142,16 +144,16 @@ public static void displayInfo(Messageable viewer, Vessel vessel) { if (vessel instanceof ShipsVessel) { @NotNull Map info = ((ShipsVessel) vessel).getExtraInformation(); info.forEach((key, value) -> { - Component built = AdventureMessageConfig.INFO_VESSEL_INFO + Component built = Messages.INFO_VESSEL_INFO .parseMessage(messages) .replaceText(TextReplacementConfig .builder() - .match("%" + Message.VESSEL_INFO_KEY.adapterText() + "%") + .match("%" + MessageAdapters.VESSEL_INFO_KEY.adapterText() + "%") .replacement(key) .build()) .replaceText(TextReplacementConfig .builder() - .match("%" + Message.VESSEL_INFO_VALUE.adapterText() + "%") + .match("%" + MessageAdapters.VESSEL_INFO_VALUE.adapterText() + "%") .replacement(value) .build()); viewer.sendMessage(built); @@ -170,25 +172,25 @@ public static void displayInfo(Messageable viewer, Vessel vessel) { .map(vf -> flagToString(Identifiable::getName, vf)) .collect(Collectors.joining("\n - ")); - Component text = AdventureMessageConfig.INFO_FLAG + Component text = Messages.INFO_FLAG .parseMessage(messages) .replaceText(TextReplacementConfig .builder() - .match("%" + Message.VESSEL_FLAG_ID.adapterText() + "%") + .match("%" + MessageAdapters.VESSEL_FLAG_ID.adapterText() + "%") .replacement(flagIds) .build()) .replaceText(TextReplacementConfig .builder() - .match("%" + Message.VESSEL_FLAG_NAME.adapterText() + "%") + .match("%" + MessageAdapters.VESSEL_FLAG_NAME.adapterText() + "%") .replacement(flagNames) .build()); viewer.sendMessage(text); } - viewer.sendMessage(AdventureMessageConfig.INFO_ENTITIES_LINE.parseMessage(messages)); + viewer.sendMessage(Messages.INFO_ENTITIES_LINE.parseMessage(messages)); vessel.getEntitiesOvertime(e -> true).thenAccept(collection -> collection.forEach(entity -> { - Component entitiesText = AdventureMessageConfig.INFO_ENTITIES_LIST.parseMessage(messages); - entitiesText = AdventureMessageConfig.INFO_ENTITIES_LIST.processMessage(entitiesText, entity); + Component entitiesText = Messages.INFO_ENTITIES_LIST.parseMessage(messages); + entitiesText = Messages.INFO_ENTITIES_LIST.processMessage(entitiesText, entity); viewer.sendMessage(entitiesText); })); } diff --git a/src/main/java/org/ships/commands/argument/ship/structure/ShipStructureSaveCommand.java b/src/main/java/org/ships/commands/argument/ship/structure/ShipStructureSaveCommand.java index 394b09b9..edb373b8 100644 --- a/src/main/java/org/ships/commands/argument/ship/structure/ShipStructureSaveCommand.java +++ b/src/main/java/org/ships/commands/argument/ship/structure/ShipStructureSaveCommand.java @@ -1,7 +1,7 @@ package org.ships.commands.argument.ship.structure; +import net.kyori.adventure.text.Component; import org.core.TranslateCore; -import org.core.adventureText.AText; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; @@ -11,7 +11,6 @@ import org.core.exceptions.NotEnoughArguments; import org.core.permission.Permission; import org.core.source.command.CommandSource; -import org.core.source.viewer.CommandViewer; import org.core.utils.Bounds; import org.core.world.structure.Structure; import org.core.world.structure.StructureBuilder; @@ -56,7 +55,7 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou File file = new File(ShipsPlugin.getPlugin().getConfigFolder(), "Structure/" + ShipsPlugin.getPlugin().getPluginId() + "/" + id + ".structure"); if (file.exists()) { - commandContext.getSource().sendMessage(AText.ofPlain("Cannot replace another structure file")); + commandContext.getSource().sendMessage(Component.text("Cannot replace another structure file")); return false; } @@ -65,7 +64,7 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou try { file.createNewFile(); } catch (IOException e) { - commandContext.getSource().sendMessage(AText.ofPlain("Error when creating file: " + e.getMessage())); + commandContext.getSource().sendMessage(Component.text("Error when creating file: " + e.getMessage())); e.printStackTrace(); return false; @@ -79,7 +78,7 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou if (bounds.getIntMax().equals(bounds.getIntMin())) { commandContext .getSource() - .sendMessage(AText.ofPlain( + .sendMessage(Component.text( "Size of ship is invalid. Manually updating the ship structure should fix this by sneaking and clicking the [ships] sign")); return false; @@ -95,10 +94,10 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou CommandSource viewer = commandContext.getSource(); try { structure.serialize(file); - viewer.sendMessage(AText.ofPlain("Saved")); + viewer.sendMessage(Component.text("Saved")); } catch (IOException e) { - viewer.sendMessage(AText.ofPlain("Error saving: " + e.getMessage())); + viewer.sendMessage(Component.text("Error saving: " + e.getMessage())); e.printStackTrace(); } return true; diff --git a/src/main/java/org/ships/commands/argument/ship/teleport/ShipsShipTeleportToArgument.java b/src/main/java/org/ships/commands/argument/ship/teleport/ShipsShipTeleportToArgument.java index e2285c21..c57455a9 100644 --- a/src/main/java/org/ships/commands/argument/ship/teleport/ShipsShipTeleportToArgument.java +++ b/src/main/java/org/ships/commands/argument/ship/teleport/ShipsShipTeleportToArgument.java @@ -1,7 +1,7 @@ package org.ships.commands.argument.ship.teleport; -import org.core.adventureText.AText; -import org.core.adventureText.format.NamedTextColours; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; @@ -12,7 +12,6 @@ import org.core.exceptions.NotEnoughArguments; import org.core.permission.Permission; import org.core.source.command.CommandSource; -import org.core.source.viewer.CommandViewer; import org.core.world.position.impl.ExactPosition; import org.ships.commands.argument.arguments.ShipIdArgument; import org.ships.commands.argument.arguments.ShipTeleportLocationArgument; @@ -37,7 +36,9 @@ public List> getArguments() { new ShipIdArgument<>(this.SHIP_ID_ARGUMENT, (source, vessel) -> { if (source instanceof LivePlayer && vessel instanceof CrewStoredVessel) { User player = (User) source; - return ((CrewStoredVessel)vessel).getPermission(player.getUniqueId()).canCommand(); + return ((CrewStoredVessel) vessel) + .getPermission(player.getUniqueId()) + .canCommand(); } return vessel instanceof TeleportToVessel; }, v -> "Ship is not teleport capable"), new ExactArgument(this.SHIP_TELEPORT_ARGUMENT), @@ -63,7 +64,7 @@ public Optional getPermissionNode() { public boolean run(CommandContext commandContext, String... args) throws NotEnoughArguments { CommandSource source = commandContext.getSource(); if (!(source instanceof LivePlayer)) { - source.sendMessage(AText.ofPlain("Teleport requires to be ran as a player")); + source.sendMessage(Component.text("Teleport requires to be ran as a player")); return false; } LivePlayer player = (LivePlayer) source; @@ -71,7 +72,7 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou String telPos = commandContext.getArgument(this, this.SHIP_LOCATION); ExactPosition position = tVessel.getTeleportPositions().get(telPos); if (position == null) { - player.sendMessage(AText.ofPlain("Unknown part of ship").withColour(NamedTextColours.RED)); + player.sendMessage(Component.text("Unknown part of ship").color(NamedTextColor.RED)); return false; } player.setPosition(position); diff --git a/src/main/java/org/ships/commands/argument/ship/track/ShipsShipTrackArgumentCommand.java b/src/main/java/org/ships/commands/argument/ship/track/ShipsShipTrackArgumentCommand.java index 4cc689fa..ea96ff9d 100644 --- a/src/main/java/org/ships/commands/argument/ship/track/ShipsShipTrackArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/ship/track/ShipsShipTrackArgumentCommand.java @@ -23,6 +23,7 @@ import java.util.Arrays; import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; public class ShipsShipTrackArgumentCommand implements ArgumentCommand { @@ -55,21 +56,19 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou return true; } LivePlayer player = (LivePlayer)source; - vessel + var blocks = vessel .getStructure() - .getSyncedPositionsRelativeToWorld() - .forEach(bp -> bp.setBlock(BlockTypes.OBSIDIAN.getDefaultBlockDetails(), (LivePlayer) source)); + .getPositionsRelativeToWorld().collect(Collectors.toList()); + blocks.forEach(bp -> bp.setBlock(BlockTypes.OBSIDIAN.getDefaultBlockDetails(), (LivePlayer) source)); TranslateCore .getScheduleManager() .schedule() .setDisplayName("ShipsTrack:" + Else.throwOr(NoLicencePresent.class, vessel::getName, "Unknown")) .setDelay(10) .setDelayUnit(TimeUnit.SECONDS) - .setRunner((sch) -> vessel - .getStructure() - .getSyncedPositionsRelativeToWorld() + .setRunner((sch) -> blocks .forEach(bp -> bp.resetBlock(player))) - .build(ShipsPlugin.getPlugin()) + .buildDelayed(ShipsPlugin.getPlugin()) .run(); return true; } diff --git a/src/main/java/org/ships/commands/argument/ship/unlock/ShipsShipUnlockArgumentCommand.java b/src/main/java/org/ships/commands/argument/ship/unlock/ShipsShipUnlockArgumentCommand.java index 8b5e3e6e..cc55aee6 100644 --- a/src/main/java/org/ships/commands/argument/ship/unlock/ShipsShipUnlockArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/ship/unlock/ShipsShipUnlockArgumentCommand.java @@ -1,6 +1,6 @@ package org.ships.commands.argument.ship.unlock; -import org.core.adventureText.AText; +import net.kyori.adventure.text.Component; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; @@ -8,7 +8,6 @@ import org.core.exceptions.NotEnoughArguments; import org.core.permission.Permission; import org.core.source.command.CommandSource; -import org.core.source.viewer.CommandViewer; import org.ships.commands.argument.arguments.ShipIdArgument; import org.ships.plugin.ShipsPlugin; import org.ships.vessel.common.types.Vessel; @@ -47,16 +46,13 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou Vessel vessel = commandContext.getArgument(this, this.SHIP_ID_ARGUMENT); Collection locks = ShipsPlugin.getPlugin().getLockedSignManager().getLockedSigns(vessel); if (locks.isEmpty()) { - if (source instanceof CommandViewer) { - ((CommandViewer) source).sendMessage(AText.ofPlain("No locks could be found")); - } + source.sendMessage(Component.text("No locks could be found")); return true; } boolean successful = ShipsPlugin.getPlugin().getLockedSignManager().unlockAll(locks); - if (source instanceof CommandViewer) { - ((CommandViewer) source).sendMessage(AText.ofPlain( - (successful ? "Cleared " : "Failed to clear") + " all (" + locks.size() + ") locked signs: ")); - } + source.sendMessage(Component.text( + (successful ? "Cleared " : "Failed to clear") + " all (" + locks.size() + ") locked signs: ")); + return true; } } diff --git a/src/main/java/org/ships/commands/argument/type/ShipsCreateShipTypeArgument.java b/src/main/java/org/ships/commands/argument/type/ShipsCreateShipTypeArgument.java index de11bbc8..c84c7946 100644 --- a/src/main/java/org/ships/commands/argument/type/ShipsCreateShipTypeArgument.java +++ b/src/main/java/org/ships/commands/argument/type/ShipsCreateShipTypeArgument.java @@ -1,7 +1,7 @@ package org.ships.commands.argument.type; +import net.kyori.adventure.text.Component; import org.core.TranslateCore; -import org.core.adventureText.AText; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; @@ -11,11 +11,11 @@ import org.core.exceptions.NotEnoughArguments; import org.core.permission.Permission; import org.core.source.command.CommandSource; -import org.core.source.viewer.CommandViewer; import org.ships.commands.argument.arguments.identifiable.ShipIdentifiableArgument; import org.ships.permissions.Permissions; import org.ships.plugin.ShipsPlugin; import org.ships.vessel.common.assits.shiptype.CloneableShipType; +import org.ships.vessel.common.types.ShipTypes; import java.io.File; import java.io.IOException; @@ -33,11 +33,9 @@ public class ShipsCreateShipTypeArgument implements ArgumentCommand { @Override public List> getArguments() { - return Arrays.asList( - new ExactArgument(SHIP_TYPE), - new ExactArgument(CREATE), - new ShipIdentifiableArgument<>(CLONEABLE_SHIP_TYPE, CloneableShipType.class), - new RemainingArgument<>(NEW_SHIP_TYPE_NAME, new StringArgument(NEW_SHIP_TYPE_NAME))); + return Arrays.asList(new ExactArgument(SHIP_TYPE), new ExactArgument(CREATE), + new ShipIdentifiableArgument<>(CLONEABLE_SHIP_TYPE, ShipTypes::cloneableShipTypes), + new RemainingArgument<>(NEW_SHIP_TYPE_NAME, new StringArgument(NEW_SHIP_TYPE_NAME))); } @Override @@ -54,47 +52,30 @@ public Optional getPermissionNode() { public boolean run(CommandContext commandContext, String... args) throws NotEnoughArguments { CommandSource source = commandContext.getSource(); CloneableShipType type = ((CloneableShipType) commandContext.getArgument(this, - CLONEABLE_SHIP_TYPE)).getOriginType(); + CLONEABLE_SHIP_TYPE)).getOriginType(); List names = commandContext.getArgument(this, NEW_SHIP_TYPE_NAME); names.forEach(name -> { - File file = new File(ShipsPlugin - .getPlugin() - .getConfigFolder(), - "Configuration/ShipType/Custom/" - + type - .getId() - .replace(":", ".") - + "/" - + name - + "." - + TranslateCore - .getPlatform() - .getConfigFormat() - .getFileType()[0]); - file = TranslateCore.createConfigurationFile(file, TranslateCore.getPlatform().getConfigFormat()).getFile(); + File file = new File(ShipsPlugin.getPlugin().getConfigFolder(), + "Configuration/ShipType/Custom/" + type.getId().replace(":", ".") + "/" + name + "." + + TranslateCore.getPlatform().getConfigFormat().getFileType()[0]); + file = TranslateCore.getConfigManager().read(file, TranslateCore.getPlatform().getConfigFormat()).getFile(); if (file.exists()) { - if (source instanceof CommandViewer) { - ((CommandViewer) source).sendMessage( - AText.ofPlain("Custom ShipType " + name + " has already been " + - "created")); - } + (source).sendMessage(Component.text("Custom ShipType " + name + " has already been created")); + return; } try { file.getParentFile().mkdirs(); Files.copy(type.getFile().getFile().toPath(), file.toPath()); } catch (IOException e) { - if (source instanceof CommandViewer) { - ((CommandViewer) source).sendMessage( - AText.ofPlain(name + " failed to created file. " + e.getMessage())); - } + + source.sendMessage(Component.text(name + " failed to created file. " + e.getMessage())); + e.printStackTrace(); } CloneableShipType newType = type.cloneWithName(file, name); - ShipsPlugin.getPlugin().register(newType); - if (source instanceof CommandViewer) { - ((CommandViewer) source).sendMessage(AText.ofPlain(name + " created. ")); - } + ShipTypes.registerType(newType); + source.sendMessage(Component.text(name + " created.")); }); return true; diff --git a/src/main/java/org/ships/commands/argument/type/ShipsDeleteShipTypeArgument.java b/src/main/java/org/ships/commands/argument/type/ShipsDeleteShipTypeArgument.java index 644d5498..59c3bc4a 100644 --- a/src/main/java/org/ships/commands/argument/type/ShipsDeleteShipTypeArgument.java +++ b/src/main/java/org/ships/commands/argument/type/ShipsDeleteShipTypeArgument.java @@ -1,6 +1,6 @@ package org.ships.commands.argument.type; -import org.core.adventureText.AText; +import net.kyori.adventure.text.Component; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; @@ -9,12 +9,12 @@ import org.core.exceptions.NotEnoughArguments; import org.core.permission.Permission; import org.core.source.command.CommandSource; -import org.core.source.viewer.CommandViewer; import org.ships.commands.argument.arguments.identifiable.ShipIdentifiableArgument; import org.ships.permissions.Permissions; import org.ships.plugin.ShipsPlugin; import org.ships.vessel.common.assits.SwitchableVessel; import org.ships.vessel.common.assits.shiptype.CloneableShipType; +import org.ships.vessel.common.types.ShipTypes; import java.io.IOException; import java.nio.file.Files; @@ -33,8 +33,11 @@ public class ShipsDeleteShipTypeArgument implements ArgumentCommand { @Override public List> getArguments() { return Arrays.asList(new ExactArgument(SHIP_TYPE), new ExactArgument(DELETE), - new RemainingArgument<>(CUSTOM_SHIP_TYPE, new ShipIdentifiableArgument<>(CUSTOM_SHIP_TYPE, - CloneableShipType.class, (c, a, t) -> !t.getOriginType().equals(t)))); + new RemainingArgument<>(CUSTOM_SHIP_TYPE, new ShipIdentifiableArgument<>(CUSTOM_SHIP_TYPE, + ShipTypes::cloneableShipTypes, + (c, a, t) -> !t + .getOriginType() + .equals(t)))); } @Override @@ -69,26 +72,27 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou } }).count(); if (count != vessels.size()) { - if (source instanceof CommandViewer) { - ((CommandViewer) source).sendMessage( - AText.ofPlain("Could not delete. Could not convert all vessels " + - "into " + type.getOriginType().getId() + ". Did convert " + count)); - } + source.sendMessage(Component.text( + "Could not delete. Could not convert all vessels into " + type.getOriginType().getId() + + ". Did convert " + count)); + return; } try { Files.delete(type.getFile().getFile().toPath()); } catch (IOException e) { - if (source instanceof CommandViewer) { - ((CommandViewer) source).sendMessage(AText.ofPlain("Could not delete. " + e.getMessage())); - } + + source.sendMessage(Component.text("Could not delete. " + e.getMessage())); + throw new IllegalStateException(e); } - ShipsPlugin.getPlugin().unregister(type); - if (source instanceof CommandViewer) { - ((CommandViewer) source).sendMessage(AText.ofPlain("Deleted " + type.getDisplayName() + " deleted. " + - "All " + count + " ships are now " + type.getOriginType().getDisplayName())); - } + ShipTypes.unregisterType(type); + + source.sendMessage(Component.text( + "Deleted " + type.getDisplayName() + " deleted. All " + count + " ships are now " + type + .getOriginType() + .getDisplayName())); + }); return true; } diff --git a/src/main/java/org/ships/commands/argument/type/ShipsViewShipTypeArgument.java b/src/main/java/org/ships/commands/argument/type/ShipsViewShipTypeArgument.java index af3cb6be..16ce554b 100644 --- a/src/main/java/org/ships/commands/argument/type/ShipsViewShipTypeArgument.java +++ b/src/main/java/org/ships/commands/argument/type/ShipsViewShipTypeArgument.java @@ -1,6 +1,6 @@ package org.ships.commands.argument.type; -import org.core.adventureText.AText; +import net.kyori.adventure.text.Component; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; @@ -8,9 +8,9 @@ import org.core.exceptions.NotEnoughArguments; import org.core.permission.Permission; import org.core.source.command.CommandSource; -import org.core.source.viewer.CommandViewer; import org.ships.plugin.ShipsPlugin; import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import java.util.Arrays; import java.util.Collection; @@ -40,8 +40,8 @@ public Optional getPermissionNode() { @Override public boolean run(CommandContext commandContext, String... args) throws NotEnoughArguments { CommandSource viewer = commandContext.getSource(); - Collection> types = ShipsPlugin.getPlugin().getAllShipTypes(); - types.forEach(st -> viewer.sendMessage(AText.ofPlain(" - " + st.getDisplayName()))); + Collection> types = ShipTypes.shipTypes(); + types.forEach(st -> viewer.sendMessage(Component.text(" - " + st.getDisplayName()))); return true; } } diff --git a/src/main/java/org/ships/commands/argument/type/flag/ModifyShipTypeFlagArgument.java b/src/main/java/org/ships/commands/argument/type/flag/ModifyShipTypeFlagArgument.java index 181e671b..d70b8970 100644 --- a/src/main/java/org/ships/commands/argument/type/flag/ModifyShipTypeFlagArgument.java +++ b/src/main/java/org/ships/commands/argument/type/flag/ModifyShipTypeFlagArgument.java @@ -14,6 +14,7 @@ import org.ships.permissions.Permissions; import org.ships.vessel.common.flag.VesselFlag; import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import java.util.Arrays; import java.util.List; @@ -25,7 +26,9 @@ public class ModifyShipTypeFlagArgument implements ArgumentCommand { private final ExactArgument FLAG_KEY = new ExactArgument("flag key", false, "flag"); private final ExactArgument MODIFY_KEY = new ExactArgument("modify"); private final ShipIdentifiableArgument> VESSEL_TYPE = new ShipIdentifiableArgument<>("shiptype", - (Class>) (Object) ShipType.class, + () -> ShipTypes + .shipTypes() + .stream(), (c, a, v) -> !v .getFlags() .isEmpty()); diff --git a/src/main/java/org/ships/commands/argument/type/flag/ViewShipTypeFlagArgument.java b/src/main/java/org/ships/commands/argument/type/flag/ViewShipTypeFlagArgument.java index e317168a..55f34def 100644 --- a/src/main/java/org/ships/commands/argument/type/flag/ViewShipTypeFlagArgument.java +++ b/src/main/java/org/ships/commands/argument/type/flag/ViewShipTypeFlagArgument.java @@ -1,18 +1,19 @@ package org.ships.commands.argument.type.flag; -import org.core.adventureText.AText; +import net.kyori.adventure.text.Component; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; import org.core.command.argument.context.CommandContext; import org.core.exceptions.NotEnoughArguments; import org.core.permission.Permission; +import org.core.source.Messageable; import org.core.source.command.CommandSource; -import org.core.source.viewer.CommandViewer; import org.ships.commands.argument.arguments.identifiable.ShipIdentifiableArgument; import org.ships.permissions.Permissions; import org.ships.vessel.common.flag.VesselFlag; import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import java.util.Arrays; import java.util.List; @@ -24,16 +25,16 @@ public class ViewShipTypeFlagArgument implements ArgumentCommand { private final ExactArgument FLAG_KEY_ARGUMENT = new ExactArgument("flag key", false, "flag"); private final ExactArgument VIEW_KEY = new ExactArgument("view"); private final ShipIdentifiableArgument> SHIP_TYPE = new ShipIdentifiableArgument<>("shiptype", - (Class>) (Object) ShipType.class, (c, a, v) -> !v.getFlags().isEmpty()); + () -> ShipTypes + .shipTypes() + .stream(), + (c, a, v) -> !v + .getFlags() + .isEmpty()); @Override public List> getArguments() { - return Arrays.asList( - this.SHIP_TYPE_KEY_ARGUMENT, - this.FLAG_KEY_ARGUMENT, - this.VIEW_KEY, - this.SHIP_TYPE - ); + return Arrays.asList(this.SHIP_TYPE_KEY_ARGUMENT, this.FLAG_KEY_ARGUMENT, this.VIEW_KEY, this.SHIP_TYPE); } @Override @@ -46,25 +47,17 @@ public Optional getPermissionNode() { return Optional.of(Permissions.CMD_SHIPTYPE_VIEW_FLAG); } - @Override - public boolean hasPermission(CommandSource source) { - if (!(source instanceof CommandViewer)) { - return false; - } - return ArgumentCommand.super.hasPermission(source); - } - @Override public boolean run(CommandContext commandContext, String... args) throws NotEnoughArguments { ShipType type = commandContext.getArgument(this, this.SHIP_TYPE); - CommandViewer viewer = (CommandViewer) commandContext.getSource(); - type.getFlags().forEach(vf -> this.sendMessage(viewer, vf)); + CommandSource source = commandContext.getSource(); + type.getFlags().forEach(vf -> this.sendMessage(source, vf)); return true; } - private void sendMessage(CommandViewer viewer, VesselFlag flag) { - viewer.sendMessage( - AText.ofPlain(flag.getId() + ": " + flag.getValue().map(f -> flag.getParser().unparse(f)).orElse(""))); + private void sendMessage(Messageable source, VesselFlag flag) { + source.sendMessage( + Component.text(flag.getId() + ": " + flag.getValue().map(f -> flag.getParser().unparse(f)).orElse(""))); } } diff --git a/src/main/java/org/ships/commands/argument/type/modify/read/ReadFuelTypeArgumentCommand.java b/src/main/java/org/ships/commands/argument/type/modify/read/ReadFuelTypeArgumentCommand.java index 3961fa4a..9ac519b4 100644 --- a/src/main/java/org/ships/commands/argument/type/modify/read/ReadFuelTypeArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/type/modify/read/ReadFuelTypeArgumentCommand.java @@ -1,6 +1,6 @@ package org.ships.commands.argument.type.modify.read; -import org.core.adventureText.AText; +import net.kyori.adventure.text.Component; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; @@ -9,13 +9,15 @@ import org.core.inventory.item.ItemType; import org.core.permission.Permission; import org.core.source.command.CommandSource; -import org.core.source.viewer.CommandViewer; import org.core.utils.Identifiable; import org.ships.commands.argument.arguments.identifiable.ShipIdentifiableArgument; import org.ships.permissions.Permissions; import org.ships.vessel.common.assits.FuelSlot; import org.ships.vessel.common.assits.shiptype.FuelledShipType; import org.ships.vessel.common.requirement.FuelRequirement; +import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; +import org.ships.vessel.sign.ShipsSigns; import java.util.Collection; import java.util.List; @@ -27,7 +29,11 @@ public class ReadFuelTypeArgumentCommand implements ArgumentCommand { private final ExactArgument type = new ExactArgument("shiptype"); private final ExactArgument modify = new ExactArgument("modify"); private final ShipIdentifiableArgument> shipType = new ShipIdentifiableArgument<>( - "shiptype value", (Class>) (Object) FuelledShipType.class, (c, a, t) -> true); + "shiptype value", () -> ShipTypes + .shipTypes() + .stream() + .filter(t -> t instanceof FuelledShipType) + .map(t -> (FuelledShipType) t), (c, a, t) -> true); private final ExactArgument get = new ExactArgument("get"); private final ExactArgument fuel = new ExactArgument("fuel"); @@ -55,15 +61,14 @@ public boolean run(CommandContext commandContext, String... args) throws NotEnou FuelSlot fuelSlot = fuelRequirement.getFuelSlot(); int take = fuelRequirement.getConsumption(); - if (commandContext.getSource() instanceof CommandViewer) { - CommandSource viewer = commandContext.getSource(); - viewer.sendMessage(AText.ofPlain("Consumption: " + take)); - viewer.sendMessage(AText.ofPlain("Slot: " + fuelSlot.name())); - viewer.sendMessage(AText.ofPlain("Fuel Types: " + fuelTypes - .parallelStream() - .map(Identifiable::getName) - .collect(Collectors.joining(", ")))); - } + CommandSource viewer = commandContext.getSource(); + viewer.sendMessage(Component.text("Consumption: " + take)); + viewer.sendMessage(Component.text("Slot: " + fuelSlot.name())); + viewer.sendMessage(Component.text("Fuel Types: " + fuelTypes + .parallelStream() + .map(Identifiable::getName) + .collect(Collectors.joining(", ")))); + return true; } } diff --git a/src/main/java/org/ships/commands/argument/type/modify/read/ReadSizeTypeArgumentCommand.java b/src/main/java/org/ships/commands/argument/type/modify/read/ReadSizeTypeArgumentCommand.java index 08fafafe..317c5087 100644 --- a/src/main/java/org/ships/commands/argument/type/modify/read/ReadSizeTypeArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/type/modify/read/ReadSizeTypeArgumentCommand.java @@ -1,6 +1,6 @@ package org.ships.commands.argument.type.modify.read; -import org.core.adventureText.AText; +import net.kyori.adventure.text.Component; import org.core.command.argument.ArgumentCommand; import org.core.command.argument.CommandArgument; import org.core.command.argument.arguments.operation.ExactArgument; @@ -11,6 +11,7 @@ import org.ships.commands.argument.arguments.identifiable.ShipIdentifiableArgument; import org.ships.permissions.Permissions; import org.ships.vessel.common.assits.shiptype.SizedShipType; +import org.ships.vessel.common.types.ShipTypes; import java.util.List; import java.util.Optional; @@ -20,7 +21,11 @@ public class ReadSizeTypeArgumentCommand implements ArgumentCommand { private final ExactArgument type = new ExactArgument("shiptype"); private final ExactArgument modify = new ExactArgument("modify"); private final ShipIdentifiableArgument> shipType = new ShipIdentifiableArgument<>("shiptype value", - (Class>) (Object) SizedShipType.class, + () -> ShipTypes + .shipTypes() + .stream() + .filter(t -> t instanceof SizedShipType) + .map(t -> (SizedShipType) t), (c, a, t) -> true); private final ExactArgument get = new ExactArgument("get"); private final ExactArgument size = new ExactArgument("size"); @@ -44,11 +49,11 @@ public Optional getPermissionNode() { @Override public boolean run(CommandContext commandContext, String... args) throws NotEnoughArguments { SizedShipType shipType = commandContext.getArgument(this, this.shipType); - int minSize = shipType.getMinSize(); - String maxSize = shipType.getMaxSize().stream().map(Object::toString).findAny().orElse("unspecified"); + int minSize = shipType.getMinimumSize(); + String maxSize = shipType.getMaximumSize().stream().boxed().map(Object::toString).findAny().orElse("unspecified"); CommandSource viewer = commandContext.getSource(); - viewer.sendMessage(AText.ofPlain("Minimum size: " + minSize)); - viewer.sendMessage(AText.ofPlain("Maximum size: " + maxSize)); + viewer.sendMessage(Component.text("Minimum size: " + minSize)); + viewer.sendMessage(Component.text("Maximum size: " + maxSize)); return true; } diff --git a/src/main/java/org/ships/commands/argument/type/modify/read/ReadSpecialBlocksTypeArgumentCommand.java b/src/main/java/org/ships/commands/argument/type/modify/read/ReadSpecialBlocksTypeArgumentCommand.java index b86db6bc..e8654aca 100644 --- a/src/main/java/org/ships/commands/argument/type/modify/read/ReadSpecialBlocksTypeArgumentCommand.java +++ b/src/main/java/org/ships/commands/argument/type/modify/read/ReadSpecialBlocksTypeArgumentCommand.java @@ -13,6 +13,7 @@ import org.ships.permissions.Permissions; import org.ships.vessel.common.assits.shiptype.SpecialBlocksShipType; import org.ships.vessel.common.requirement.SpecialBlocksRequirement; +import org.ships.vessel.common.types.ShipTypes; import java.util.Collection; import java.util.List; @@ -24,8 +25,11 @@ public class ReadSpecialBlocksTypeArgumentCommand implements ArgumentCommand { private final ExactArgument type = new ExactArgument("shiptype"); private final ExactArgument modify = new ExactArgument("modify"); private final ShipIdentifiableArgument> shipType = new ShipIdentifiableArgument<>( - "shiptype value", (Class>) (Object) SpecialBlocksShipType.class, - (c, a, t) -> true); + "shiptype value", () -> ShipTypes + .shipTypes() + .stream() + .filter(t -> t instanceof SpecialBlocksShipType) + .map(t -> (SpecialBlocksShipType) t), (c, a, t) -> true); private final ExactArgument get = new ExactArgument("get"); private final ExactArgument specialBlocks = new ExactArgument("blocks"); diff --git a/src/main/java/org/ships/config/blocks/DefaultBlockList.java b/src/main/java/org/ships/config/blocks/DefaultBlockList.java index 213e7334..8f023bb6 100644 --- a/src/main/java/org/ships/config/blocks/DefaultBlockList.java +++ b/src/main/java/org/ships/config/blocks/DefaultBlockList.java @@ -8,14 +8,13 @@ import org.core.world.position.block.BlockTypes; import org.core.world.position.block.blocktypes.post.BlockTypes1V13; import org.core.world.position.block.grouptype.BlockGroups; -import org.core.world.position.block.grouptype.versions.BlockGroups1V13; -import org.core.world.position.block.grouptype.versions.CommonBlockGroups; import org.ships.config.blocks.instruction.BlockInstruction; import org.ships.config.blocks.instruction.CollideType; import org.ships.config.blocks.instruction.ModifiableBlockInstruction; import org.ships.config.blocks.instruction.MoveIntoBlockInstruction; import org.ships.config.parsers.ShipsParsers; import org.ships.plugin.ShipsPlugin; +import org.ships.vessel.common.types.ShipTypes; import java.io.File; import java.util.*; @@ -32,7 +31,7 @@ public DefaultBlockList() { ConfigurationFormat format = TranslateCore.getPlatform().getConfigFormat(); File file = new File(ShipsPlugin.getPlugin().getConfigFolder(), "Configuration/BlockList." + format.getFileType()[0]); - this.file = TranslateCore.createConfigurationFile(file, format); + this.file = TranslateCore.getConfigManager().read(file, format); if (!this.file.getFile().exists()) { this.recreateFile(); this.reloadBlockList(); @@ -52,9 +51,8 @@ public Collection getBlockList() { } Collection blockInstructions = new LinkedTransferQueue<>(this.blocks); blockInstructions.addAll(this.blocks); - Collection moveIn = ShipsPlugin - .getPlugin() - .getAllShipTypes() + Collection moveIn = ShipTypes + .shipTypes() .parallelStream() .flatMap(type -> Stream.of(type.getIgnoredTypes())) .map(MoveIntoBlockInstruction::new) @@ -68,16 +66,14 @@ public synchronized Collection reloadBlockList() { this.file.reload(); this.blocks.clear(); - Set moveInTypes = ShipsPlugin - .getPlugin() - .getAllShipTypes() + Set moveInTypes = ShipTypes + .shipTypes() .parallelStream() .flatMap(type -> Stream.of(type.getIgnoredTypes())) .collect(Collectors.toSet()); - Collection mBlocks = TranslateCore.getPlatform().getBlockTypes(); - mBlocks.forEach(bt -> { + TranslateCore.getPlatform().getAllBlockTypes().forEach(bt -> { Optional opBlock = BlockList.getBlockInstruction(DefaultBlockList.this, bt); if (opBlock.isPresent()) { this.blocks.add(opBlock.get()); @@ -100,7 +96,7 @@ public BlockList replaceBlockInstruction(BlockInstruction blockInstruction) { .orElseThrow(() -> new IllegalArgumentException( "Could not find Block instruction for " + blockInstruction.getType().getName())); if (bi instanceof ModifiableBlockInstruction) { - ModifiableBlockInstruction mbi = (ModifiableBlockInstruction)bi; + ModifiableBlockInstruction mbi = (ModifiableBlockInstruction) bi; mbi.setCollide(blockInstruction.getCollide()); mbi.setBlockLimit( blockInstruction.getBlockLimit().isPresent() ? blockInstruction.getBlockLimit().getAsInt() : null); @@ -126,9 +122,8 @@ public ConfigurationStream.ConfigurationFile getFile() { @Override public synchronized void recreateFile() { - Set ignoreBlocks = ShipsPlugin - .getPlugin() - .getAllShipTypes() + Set ignoreBlocks = ShipTypes + .shipTypes() .parallelStream() .flatMap(type -> Stream.of(type.getIgnoredTypes())) .collect(Collectors.toSet()); @@ -137,37 +132,82 @@ public synchronized void recreateFile() { ConfigurationStream.ConfigurationFile file = this.getFile(); Collection completedBefore = new HashSet<>(); //TODO -> FIX getLike - BlockTypes.OAK_SIGN - .getLike() + BlockGroups.SIGNS + .get() + .getBlocks() .forEach(w -> this.addToConfig(w, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - BlockTypes.OAK_WALL_SIGN - .getLike() + BlockGroups.ANVIL + .get() + .getBlocks() .forEach(w -> this.addToConfig(w, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - BlockTypes.PURPUR_BLOCK - .getLike() - .forEach(w -> this.addToConfig(w, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - BlockTypes.ANVIL - .getLike() - .forEach(w -> this.addToConfig(w, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - BlockTypes.BLACK_GLAZED_TERRACOTTA - .getLike() - .forEach(w -> this.addToConfig(w, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(CommonBlockGroups.SHULKER_BOX.getGrouped()) + BlockGroups.SHULKER_BOXES + .get() + .getBlocks() + .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); + BlockGroups.FENCES + .get() + .getBlocks() + .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); + BlockGroups.FENCE_GATES + .get() + .getBlocks() + .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); + BlockGroups.DOORS + .get() + .getBlocks() .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(CommonBlockGroups.FENCE.getGrouped()) + BlockGroups.LOGS + .get() + .getBlocks() .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(CommonBlockGroups.FENCE_GATE.getGrouped()) + BlockGroups.PLANKS + .get() + .getBlocks() .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(CommonBlockGroups.DOOR.getGrouped()) + BlockGroups.BANNERS + .get() + .getBlocks() .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(CommonBlockGroups.PISTON.getGrouped()) + BlockGroups.CARPET + .get() + .getBlocks() + .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); + BlockGroups.WOOL + .get() + .getBlocks() .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); + BlockGroups.BUTTONS + .get() + .getBlocks() + .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); + BlockGroups.BEDS + .get() + .getBlocks() + .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); + BlockGroups.STAIRS + .get() + .getBlocks() + .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); + BlockGroups.SLABS + .get() + .getBlocks() + .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); + BlockGroups.PRESSURE_PLATES + .get() + .getBlocks() + .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); + BlockGroups.TRAPDOOR + .get() + .getBlocks() + .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); + BlockGroups.SAPLINGS + .get() + .getBlocks() + .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); + + this.addToConfig(BlockTypes.PISTON, CollideType.MATERIAL, completedBefore, ignoreBlocks); + this.addToConfig(BlockTypes.STICKY_PISTON, CollideType.MATERIAL, completedBefore, ignoreBlocks); this.addToConfig(BlockTypes.JUKEBOX, CollideType.MATERIAL, completedBefore, ignoreBlocks); this.addToConfig(BlockTypes.LEVER, CollideType.MATERIAL, completedBefore, ignoreBlocks); this.addToConfig(BlockTypes.LADDER, CollideType.MATERIAL, completedBefore, ignoreBlocks); @@ -203,74 +243,14 @@ public synchronized void recreateFile() { this.addToConfig(BlockTypes.OBSERVER, CollideType.MATERIAL, completedBefore, ignoreBlocks); this.addToConfig(BlockTypes.REDSTONE_WIRE, CollideType.MATERIAL, completedBefore, ignoreBlocks); this.addToConfig(BlockTypes.CAULDRON, CollideType.MATERIAL, completedBefore, ignoreBlocks); + this.addToConfig(BlockTypes1V13.REPEATER, CollideType.MATERIAL, completedBefore, ignoreBlocks); + this.addToConfig(BlockTypes1V13.COMPARATOR, CollideType.MATERIAL, completedBefore, ignoreBlocks); + this.addToConfig(BlockTypes.CAVE_AIR, CollideType.IGNORE, completedBefore, ignoreBlocks); this.addToConfig(BlockTypes.TALL_GRASS, CollideType.IGNORE, completedBefore, ignoreBlocks); - this.addToConfig(BlockTypes.REDSTONE_WIRE, CollideType.IGNORE, completedBefore, ignoreBlocks); - - Stream - .of(BlockGroups1V13.LOG.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(BlockGroups1V13.WOOD_PLANKS.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(BlockGroups1V13.BANNER.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(BlockGroups1V13.CARPET.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(BlockGroups1V13.WOOL.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(BlockGroups1V13.BUTTON.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(BlockGroups1V13.BED.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(BlockGroups1V13.CONCRETE.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(BlockGroups1V13.CONCRETE_POWDER.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(BlockGroups1V13.SLAB.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(BlockGroups1V13.STAIRS.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(BlockGroups1V13.POTTED_SAPLING.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(BlockGroups1V13.TORCH.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(BlockGroups1V13.STAINED_GLASS.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(BlockGroups1V13.STAINED_GLASS_PANE.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(BlockGroups1V13.TERRACOTTA.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(BlockGroups1V13.PRESSURE_PLATE.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - Stream - .of(BlockGroups1V13.TRAP_DOOR.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.MATERIAL, completedBefore, ignoreBlocks)); - - - Stream - .of(BlockGroups1V13.SAPLING.getGrouped()) - .forEach(t -> this.addToConfig(t, CollideType.IGNORE, completedBefore, ignoreBlocks)); this.addToConfig(BlockTypes1V13.DANDELION, CollideType.IGNORE, completedBefore, ignoreBlocks); this.addToConfig(BlockTypes1V13.KELP, CollideType.IGNORE, completedBefore, ignoreBlocks); - this.addToConfig(BlockTypes1V13.REPEATER, CollideType.MATERIAL, completedBefore, ignoreBlocks); - this.addToConfig(BlockTypes1V13.COMPARATOR, CollideType.MATERIAL, completedBefore, ignoreBlocks); this.addToConfig(BlockTypes.CAVE_AIR, CollideType.IGNORE, completedBefore, ignoreBlocks); this.addToConfig(BlockTypes.TALL_GRASS, CollideType.IGNORE, completedBefore, ignoreBlocks); this.addToConfig(BlockTypes.TALL_SEAGRASS, CollideType.IGNORE, completedBefore, ignoreBlocks); @@ -278,7 +258,7 @@ public synchronized void recreateFile() { TranslateCore .getPlatform() - .getBlockTypes() + .getAllBlockTypes() .forEach(bt -> this.addToConfig(bt, CollideType.DETECT_COLLIDE, completedBefore, ignoreBlocks)); file.save(); } @@ -290,7 +270,7 @@ private void addToConfig(BlockType type, if (current.stream().anyMatch(c -> c.equals(type))) { return; } - String[] idSplit = type.getId().split(":"); + String[] idSplit = type.getId().split(":"); this.file.set(new ConfigurationNode("BlockList", idSplit[0], idSplit[1]), ShipsParsers.NODE_TO_BLOCK_INSTRUCTION, new ModifiableBlockInstruction(type).setCollide(collide)); current.add(type); diff --git a/src/main/java/org/ships/config/configuration/LegacyShipsConfig.java b/src/main/java/org/ships/config/configuration/LegacyShipsConfig.java index d7c8cca3..a877a453 100644 --- a/src/main/java/org/ships/config/configuration/LegacyShipsConfig.java +++ b/src/main/java/org/ships/config/configuration/LegacyShipsConfig.java @@ -36,7 +36,7 @@ public class LegacyShipsConfig implements Config { public LegacyShipsConfig() { File file = new File(ShipsPlugin.getPlugin().getConfigFolder(), "Configuration/Config.yml"); - this.configuration = TranslateCore.createConfigurationFile(file, ConfigurationFormat.FORMAT_YAML); + this.configuration = TranslateCore.getConfigManager().read(file, ConfigurationFormat.FORMAT_YAML); } @Override diff --git a/src/main/java/org/ships/config/configuration/ShipsConfig.java b/src/main/java/org/ships/config/configuration/ShipsConfig.java index a2be1720..45f8d92b 100644 --- a/src/main/java/org/ships/config/configuration/ShipsConfig.java +++ b/src/main/java/org/ships/config/configuration/ShipsConfig.java @@ -8,6 +8,7 @@ import org.core.schedule.unit.TimeUnit; import org.core.world.WorldExtent; import org.ships.algorthum.blockfinder.BasicBlockFinder; +import org.ships.algorthum.blockfinder.BlockFinders; import org.ships.algorthum.movement.BasicMovement; import org.ships.config.Config; import org.ships.config.node.CollectionDedicatedNode; @@ -135,7 +136,7 @@ public class ShipsConfig implements Config.KnownNodes { public ShipsConfig() { File file = new File(ShipsPlugin.getPlugin().getConfigFolder(), "Configuration/Config." + TranslateCore.getPlatform().getConfigFormat().getFileType()[0]); - this.file = TranslateCore.createConfigurationFile(file, TranslateCore.getPlatform().getConfigFormat()); + this.file = TranslateCore.getConfigManager().read(file, TranslateCore.getPlatform().getConfigFormat()); boolean modified = false; if (!this.file.getFile().exists()) { this.recreateFile(); @@ -310,7 +311,7 @@ public Optional getDefaultLoginCommand() { public BasicBlockFinder getDefaultFinder() { return this.file - .parse(this.ADVANCED_BLOCKFINDER.getNode(), BasicBlockFinder.SHIPS_SIX_RELEASE_ONE_SINGLE_ASYNC) + .parse(this.ADVANCED_BLOCKFINDER.getNode(), BlockFinders.SHIPS_SIX_RELEASE_ONE_ASYNC_SINGLE_THREADED) .init(); } diff --git a/src/main/java/org/ships/config/messages/Message.java b/src/main/java/org/ships/config/messages/Message.java index aff304d3..e7867cd9 100644 --- a/src/main/java/org/ships/config/messages/Message.java +++ b/src/main/java/org/ships/config/messages/Message.java @@ -1,8 +1,6 @@ package org.ships.config.messages; import net.kyori.adventure.text.Component; -import org.core.adventureText.AText; -import org.core.adventureText.adventure.AdventureText; import org.core.config.ConfigurationNode; import org.core.config.parser.StringParser; import org.core.entity.Entity; @@ -167,65 +165,35 @@ public interface Message { String[] getPath(); - @Deprecated(forRemoval = true) - default AText getDefault() { - return new AdventureText(getDefaultMessage()); - } - Component getDefaultMessage(); Collection> getCategories(); default Collection> getAdapters() { - List> adapters = this + return this .getCategories() .parallelStream() .flatMap(MessageAdapters::getAdaptersFor) .distinct() .map(adapter -> (MessageAdapter) adapter) - .collect(Collectors.toList()); - return new LinkedTransferQueue<>(adapters); + .collect(Collectors.toCollection(LinkedTransferQueue::new)); } - @Deprecated(forRemoval = true) - default AText process(@NotNull AText text, R obj) { - return new AdventureText(processMessage(text.asComponent(), obj)); - } Component processMessage(@NotNull Component text, R obj); - @Deprecated(forRemoval = true) - default AText process(R obj) { - return this.process(this.parse(), obj); - } - default Component processMessage(R obj) { return this.processMessage(this.parseMessage(), obj); } - @Deprecated(forRemoval = true) - default ConfigurationNode.KnownParser.SingleKnown getKnownPath() { - return new ConfigurationNode.KnownParser.SingleKnown<>(StringParser.STRING_TO_TEXT, this.getPath()); - } - default ConfigurationNode.KnownParser.SingleKnown getConfigNode() { return new ConfigurationNode.KnownParser.SingleKnown<>(StringParser.STRING_TO_COMPONENT, this.getPath()); } - @Deprecated(forRemoval = true) - default AText parse(AdventureMessageConfig config) { - return config.getFile().parse(this.getKnownPath()).orElse(this.getDefault()); - } - default Component parseMessage(AdventureMessageConfig config) { return config.getFile().parse(this.getConfigNode()).orElse(this.getDefaultMessage()); } - @Deprecated(forRemoval = true) - default AText parse() { - return this.parse(ShipsPlugin.getPlugin().getAdventureMessageConfig()); - } - default Component parseMessage() { return this.parseMessage(ShipsPlugin.getPlugin().getAdventureMessageConfig()); } diff --git a/src/main/java/org/ships/config/messages/adapter/MessageAdapter.java b/src/main/java/org/ships/config/messages/adapter/MessageAdapter.java index 638f8778..c14032f5 100644 --- a/src/main/java/org/ships/config/messages/adapter/MessageAdapter.java +++ b/src/main/java/org/ships/config/messages/adapter/MessageAdapter.java @@ -2,8 +2,6 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextReplacementConfig; -import org.core.adventureText.AText; -import org.core.adventureText.adventure.AdventureText; import org.core.utils.ComponentUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.UnmodifiableView; @@ -24,19 +22,8 @@ public interface MessageAdapter { @NotNull Collection> categories(); - @Deprecated(forRemoval = true) - default AText process(@NotNull T obj) { - return new AdventureText(processMessage(obj)); - } - @NotNull Component processMessage(@NotNull T obj); - @Deprecated(forRemoval = true) - default AText process(@NotNull T obj, @NotNull AText message) { - AText mapped = this.process(obj); - return message.withAllAsIgnoreCase(this.adapterTextFormat(), mapped); - } - default @NotNull Component processMessage(@NotNull T obj, @NotNull Component message) { Component component = this.processMessage(obj); return message.replaceText(TextReplacementConfig @@ -54,11 +41,6 @@ default boolean containsAdapter(@NotNull String plain) { return plain.toLowerCase().contains(this.adapterTextFormat().toLowerCase()); } - @Deprecated(forRemoval = true) - default boolean containsAdapter(AText text) { - return text.containsIgnoreCase(this.adapterTextFormat()); - } - default boolean containsAdapter(@NotNull Component component) { return ComponentUtils.toPlain(component).contains(this.adapterTextFormat()); } diff --git a/src/main/java/org/ships/config/messages/adapter/block/BlockTypeIdAdapter.java b/src/main/java/org/ships/config/messages/adapter/block/BlockTypeIdAdapter.java index 93fbff53..92360310 100644 --- a/src/main/java/org/ships/config/messages/adapter/block/BlockTypeIdAdapter.java +++ b/src/main/java/org/ships/config/messages/adapter/block/BlockTypeIdAdapter.java @@ -10,7 +10,6 @@ import org.ships.config.messages.adapter.category.AdapterCategory; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -28,12 +27,7 @@ public Class adaptingType() { @Override public Set examples() { - return TranslateCore - .getPlatform() - .getBlockTypes() - .stream() - .map(Identifiable::getId) - .collect(Collectors.toSet()); + return TranslateCore.getPlatform().getAllBlockTypes().map(Identifiable::getId).collect(Collectors.toSet()); } @Override diff --git a/src/main/java/org/ships/config/messages/adapter/block/BlockTypeNameAdapter.java b/src/main/java/org/ships/config/messages/adapter/block/BlockTypeNameAdapter.java index f03c7dd5..c7f78146 100644 --- a/src/main/java/org/ships/config/messages/adapter/block/BlockTypeNameAdapter.java +++ b/src/main/java/org/ships/config/messages/adapter/block/BlockTypeNameAdapter.java @@ -27,12 +27,7 @@ public Class adaptingType() { @Override public Set examples() { - return TranslateCore - .getPlatform() - .getBlockTypes() - .stream() - .map(Identifiable::getName) - .collect(Collectors.toSet()); + return TranslateCore.getPlatform().getAllBlockTypes().map(Identifiable::getName).collect(Collectors.toSet()); } @Override diff --git a/src/main/java/org/ships/config/messages/adapter/block/group/BlockGroupAdapter.java b/src/main/java/org/ships/config/messages/adapter/block/group/BlockGroupAdapter.java index 057c3794..07e4b325 100644 --- a/src/main/java/org/ships/config/messages/adapter/block/group/BlockGroupAdapter.java +++ b/src/main/java/org/ships/config/messages/adapter/block/group/BlockGroupAdapter.java @@ -51,15 +51,16 @@ public Component processMessage(@NotNull Collection obj) { if (obj.isEmpty()) { return Component.empty(); } - var blockTypes = new ArrayList<>(obj); + List blockTypes = new ArrayList<>(obj); BlockType blockType = obj.iterator().next(); List potentialBlockGroups = blockType - .getGroups() - .parallelStream() - .filter(blockGroup -> obj.parallelStream().anyMatch(type -> type.getGroups().contains(blockGroup))) + .getBlockGroups() + .filter(blockGroup -> obj + .parallelStream() + .anyMatch(type -> type.getBlockGroups().anyMatch(group -> group.equals(blockGroup)))) .collect(Collectors.toList()); - var blockGroups = getValidBlockGroups(blockTypes, potentialBlockGroups); + Collection blockGroups = this.getValidBlockGroups(blockTypes, potentialBlockGroups); if (blockTypes.isEmpty() && blockGroups.size() == 1) { return this.toString.apply(blockGroups.iterator().next()); @@ -75,8 +76,7 @@ public Component processMessage(@NotNull Collection obj) { private Collection getValidBlockGroups(Collection types, Collection groups) { Optional allMatchGroup = groups .parallelStream() - .filter(group -> group.getGrouped().length == types.size()) - .filter(group -> Stream.of(group.getGrouped()).allMatch(types::contains)) + .filter(group -> group.getBlocks().allMatch(types::contains)) .findAny(); if (allMatchGroup.isPresent()) { types.clear(); @@ -85,13 +85,14 @@ private Collection getValidBlockGroups(Collection types, List allMatchGroups = groups .parallelStream() - .filter(group -> Arrays.stream(group.getGrouped()).allMatch(types::contains)) - .sorted(Comparator.comparing(group -> group.getGrouped().length)) + .filter(group -> group.getBlocks().allMatch(types::contains)) + .sorted(Comparator.comparing(group -> group.getBlocks().count())) .collect(Collectors.toList()); Collection ret = new ArrayList<>(); for (BlockGroup group : allMatchGroups) { - if (Stream.of(group.getGrouped()).allMatch(types::contains)) { - types.removeAll(Arrays.asList(group.getGrouped())); + List blockTypes = group.getBlocks().collect(Collectors.toList()); + if (new HashSet<>(blockTypes).containsAll(types)) { + types.removeAll(blockTypes); ret.add(group); } } diff --git a/src/main/java/org/ships/config/messages/adapter/config/ConfigAdapter.java b/src/main/java/org/ships/config/messages/adapter/config/ConfigAdapter.java index 4335c346..ab9f9ac3 100644 --- a/src/main/java/org/ships/config/messages/adapter/config/ConfigAdapter.java +++ b/src/main/java/org/ships/config/messages/adapter/config/ConfigAdapter.java @@ -2,8 +2,6 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextReplacementConfig; -import org.core.adventureText.AText; -import org.core.adventureText.adventure.AdventureText; import org.jetbrains.annotations.NotNull; import org.ships.config.configuration.ShipsConfig; import org.ships.config.messages.adapter.MessageAdapter; @@ -13,28 +11,13 @@ public interface ConfigAdapter extends MessageAdapter { - @Deprecated(forRemoval = true) - default AText process(@NotNull ShipsConfig config) { - return new AdventureText(processMessage(config)); - } Component processMessage(@NotNull ShipsConfig config); - @Deprecated - default AText process() { - return this.process(ShipsPlugin.getPlugin().getConfig()); - } - default Component processMessage() { return this.processMessage(ShipsPlugin.getPlugin().getConfig()); } - @Deprecated(forRemoval = true) - default AText process(@NotNull ShipsConfig config, @NotNull AText message) { - AText mapped = this.process(config); - return message.withAllAs(this.adapterTextFormat(), mapped); - } - default Component processMessage(@NotNull ShipsConfig config, @NotNull Component message) { Component mapped = this.processMessage(config); return message.replaceText(TextReplacementConfig @@ -44,12 +27,6 @@ default Component processMessage(@NotNull ShipsConfig config, @NotNull Component .build()); } - @Deprecated(forRemoval = true) - default AText process(@NotNull AText message) { - AText mapped = this.process(); - return message.withAllAs(this.adapterTextFormat(), mapped); - } - default Component processMessage(@NotNull Component message) { Component mapped = this.processMessage(); return message.replaceText(TextReplacementConfig diff --git a/src/main/java/org/ships/config/messages/adapter/entity/EntityNameAdapter.java b/src/main/java/org/ships/config/messages/adapter/entity/EntityNameAdapter.java index 4f412169..76eb69c6 100644 --- a/src/main/java/org/ships/config/messages/adapter/entity/EntityNameAdapter.java +++ b/src/main/java/org/ships/config/messages/adapter/entity/EntityNameAdapter.java @@ -31,7 +31,7 @@ public Class adaptingType() { @Override public Set examples() { - Collection collection = TranslateCore.getServer().getOnlinePlayers(); + Collection collection = TranslateCore.getServer().getLivePlayers().collect(Collectors.toList()); if (collection.isEmpty()) { return Collections.singleton("Creeper"); } diff --git a/src/main/java/org/ships/config/messages/adapter/misc/CollectionSingleAdapter.java b/src/main/java/org/ships/config/messages/adapter/misc/CollectionSingleAdapter.java index 131d353d..6f2d3ede 100644 --- a/src/main/java/org/ships/config/messages/adapter/misc/CollectionSingleAdapter.java +++ b/src/main/java/org/ships/config/messages/adapter/misc/CollectionSingleAdapter.java @@ -4,7 +4,6 @@ import net.kyori.adventure.text.TextReplacementConfig; import net.kyori.adventure.text.format.NamedTextColor; import org.core.TranslateCore; -import org.core.adventureText.AText; import org.core.utils.ComponentUtils; import org.jetbrains.annotations.NotNull; import org.ships.config.messages.adapter.MessageAdapter; @@ -201,12 +200,6 @@ public boolean containsAdapter(String plain) { return this.adapters.parallelStream().anyMatch(ma -> ma.containsAdapter(adapterText)); } - @Override - @Deprecated - public boolean containsAdapter(AText text) { - return this.containsAdapter(text.toPlain()); - } - @Override public boolean containsAdapter(@NotNull Component component) { return MessageAdapter.super.containsAdapter(component); diff --git a/src/main/java/org/ships/config/messages/adapter/misc/MapToAdapter.java b/src/main/java/org/ships/config/messages/adapter/misc/MapToAdapter.java index f640b689..2052b6c0 100644 --- a/src/main/java/org/ships/config/messages/adapter/misc/MapToAdapter.java +++ b/src/main/java/org/ships/config/messages/adapter/misc/MapToAdapter.java @@ -6,15 +6,14 @@ import org.ships.config.messages.adapter.category.AdapterCategory; import java.util.Collection; -import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; public class MapToAdapter implements MessageAdapter { - private MessageAdapter adapter; - private Function to; - private Class adapterType; + private final MessageAdapter adapter; + private final Function to; + private final Class adapterType; public MapToAdapter(Class type, MessageAdapter adapter, Function to) { this.to = to; @@ -39,7 +38,11 @@ public Collection examples() { @Override public Collection> categories() { - return this.adapter.categories().parallelStream().map(t -> t.map(this.adapterType)).collect(Collectors.toList()); + return this.adapter + .categories() + .parallelStream() + .map(t -> t.map(this.adapterType)) + .collect(Collectors.toList()); } @Override diff --git a/src/main/java/org/ships/config/messages/adapter/structure/StructureChunkSizeAdapter.java b/src/main/java/org/ships/config/messages/adapter/structure/StructureChunkSizeAdapter.java index d519afcf..cba5573a 100644 --- a/src/main/java/org/ships/config/messages/adapter/structure/StructureChunkSizeAdapter.java +++ b/src/main/java/org/ships/config/messages/adapter/structure/StructureChunkSizeAdapter.java @@ -36,6 +36,6 @@ public Collection> categories() { @Override public Component processMessage(@NotNull PositionableShipsStructure obj) { - return Component.text(obj.getChunks().size() + ""); + return Component.text(obj.getLoadedChunks().count() + ""); } } diff --git a/src/main/java/org/ships/config/messages/adapter/structure/StructureSizeAdapter.java b/src/main/java/org/ships/config/messages/adapter/structure/StructureSizeAdapter.java index 129b037e..9c251ebe 100644 --- a/src/main/java/org/ships/config/messages/adapter/structure/StructureSizeAdapter.java +++ b/src/main/java/org/ships/config/messages/adapter/structure/StructureSizeAdapter.java @@ -36,6 +36,6 @@ public Collection> categories() { @Override public Component processMessage(@NotNull PositionableShipsStructure obj) { - return Component.text((obj.getOriginalRelativePositionsToCenter().size() + 1) + ""); + return Component.text((obj.size() + 1) + ""); } } diff --git a/src/main/java/org/ships/config/messages/messages/bar/BlockFinderBarMessage.java b/src/main/java/org/ships/config/messages/messages/bar/BlockFinderBarMessage.java index e03aad93..3297dabf 100644 --- a/src/main/java/org/ships/config/messages/messages/bar/BlockFinderBarMessage.java +++ b/src/main/java/org/ships/config/messages/messages/bar/BlockFinderBarMessage.java @@ -21,8 +21,8 @@ public String[] getPath() { @Override public Component getDefaultMessage() { - return Component.text( - Message.STRUCTURE_SIZE.adapterTextFormat() + " / " + Message.CONFIG_TRACK_LIMIT.adapterTextFormat()); + return Component.text(MessageAdapters.STRUCTURE_SIZE.adapterTextFormat() + " / " + + MessageAdapters.CONFIG_TRACK_LIMIT.adapterTextFormat()); } @Override diff --git a/src/main/java/org/ships/config/messages/messages/error/ErrorAlreadyMovingMessage.java b/src/main/java/org/ships/config/messages/messages/error/ErrorAlreadyMovingMessage.java index 9db24f35..427f7b1f 100644 --- a/src/main/java/org/ships/config/messages/messages/error/ErrorAlreadyMovingMessage.java +++ b/src/main/java/org/ships/config/messages/messages/error/ErrorAlreadyMovingMessage.java @@ -22,7 +22,7 @@ public String[] getPath() { @Override public Component getDefaultMessage() { return Component.text( - Message.VESSEL_ID.adapterTextFormat() + " is already moving. Please wait for it to finish"); + MessageAdapters.VESSEL_ID.adapterTextFormat() + " is already moving. Please wait for it to finish"); } @Override diff --git a/src/main/java/org/ships/config/messages/messages/error/ErrorBlockInWayMessage.java b/src/main/java/org/ships/config/messages/messages/error/ErrorBlockInWayMessage.java index 7239179c..b1f35b30 100644 --- a/src/main/java/org/ships/config/messages/messages/error/ErrorBlockInWayMessage.java +++ b/src/main/java/org/ships/config/messages/messages/error/ErrorBlockInWayMessage.java @@ -21,10 +21,10 @@ public class ErrorBlockInWayMessage implements Message>> { private static final MappedAdapter, BlockType> BLOCK_TYPE_NAME = new MappedAdapter<>(BlockType.class, - Message.BLOCK_TYPE_NAME, + MessageAdapters.BLOCK_TYPE_NAME, Position::getBlockType); private static final MappedAdapter, BlockType> BLOCK_TYPE_ID = new MappedAdapter<>(BlockType.class, - Message.BLOCK_TYPE_ID, + MessageAdapters.BLOCK_TYPE_ID, Position::getBlockType); @Override @@ -35,7 +35,7 @@ public String[] getPath() { @Override public Component getDefaultMessage() { return Component.text( - Message.VESSEL_ID.adapterTextFormat() + " cannot move due to " + Message.BLOCK_NAMES.adapterTextFormat() + MessageAdapters.VESSEL_ID.adapterTextFormat() + " cannot move due to " + MessageAdapters.BLOCK_NAMES.adapterTextFormat() + " in way"); } diff --git a/src/main/java/org/ships/config/messages/messages/error/ErrorCannotCreateOntopMessage.java b/src/main/java/org/ships/config/messages/messages/error/ErrorCannotCreateOntopMessage.java index 96c9e6d8..6733084c 100644 --- a/src/main/java/org/ships/config/messages/messages/error/ErrorCannotCreateOntopMessage.java +++ b/src/main/java/org/ships/config/messages/messages/error/ErrorCannotCreateOntopMessage.java @@ -23,7 +23,7 @@ public String[] getPath() { @Override public Component getDefaultMessage() { return Component - .text("Cannot create your ship on top of " + Message.VESSEL_NAME.adapterTextFormat()) + .text("Cannot create your ship on top of " + MessageAdapters.VESSEL_NAME.adapterTextFormat()) .color(NamedTextColor.RED); } diff --git a/src/main/java/org/ships/config/messages/messages/error/ErrorFailedToFindNamedBlockMessage.java b/src/main/java/org/ships/config/messages/messages/error/ErrorFailedToFindNamedBlockMessage.java index 46fe281f..a1a0a999 100644 --- a/src/main/java/org/ships/config/messages/messages/error/ErrorFailedToFindNamedBlockMessage.java +++ b/src/main/java/org/ships/config/messages/messages/error/ErrorFailedToFindNamedBlockMessage.java @@ -36,7 +36,7 @@ public Collection> getCategories() { @Override public Collection> getAdapters() { Collection> adapters = new HashSet<>(Message.super.getAdapters()); - adapters.add(Message.NAMED_BLOCK_NAME); + adapters.add(MessageAdapters.NAMED_BLOCK_NAME); return adapters; } @@ -54,7 +54,7 @@ public Component processMessage(@NotNull Component text, NamedBlockMessageData o for (MessageAdapter adapter : blockTypeAdapters) { text = adapter.processMessage(obj.getType(), text); } - text = Message.NAMED_BLOCK_NAME.processMessage(obj.getNamedBlock(), text); + text = MessageAdapters.NAMED_BLOCK_NAME.processMessage(obj.getNamedBlock(), text); return text; } } diff --git a/src/main/java/org/ships/config/messages/messages/error/ErrorInvalidShipNameMessage.java b/src/main/java/org/ships/config/messages/messages/error/ErrorInvalidShipNameMessage.java index b95c8f6c..ea691136 100644 --- a/src/main/java/org/ships/config/messages/messages/error/ErrorInvalidShipNameMessage.java +++ b/src/main/java/org/ships/config/messages/messages/error/ErrorInvalidShipNameMessage.java @@ -4,6 +4,7 @@ import org.jetbrains.annotations.NotNull; import org.ships.config.messages.Message; import org.ships.config.messages.adapter.MessageAdapter; +import org.ships.config.messages.adapter.MessageAdapters; import org.ships.config.messages.adapter.category.AdapterCategory; import java.util.Collection; @@ -18,7 +19,7 @@ public String[] getPath() { @Override public Component getDefaultMessage() { - return Component.text("The name of '" + Message.INVALID_NAME.adapterTextFormat() + "' has already been taken"); + return Component.text("The name of '" + MessageAdapters.INVALID_NAME.adapterTextFormat() + "' has already been taken"); } @Override @@ -28,11 +29,11 @@ public Collection> getCategories() { @Override public Collection> getAdapters() { - return List.of(Message.INVALID_NAME); + return List.of(MessageAdapters.INVALID_NAME); } @Override public Component processMessage(@NotNull Component text, String obj) { - return Message.INVALID_NAME.processMessage(obj, text); + return MessageAdapters.INVALID_NAME.processMessage(obj, text); } } diff --git a/src/main/java/org/ships/config/messages/messages/error/ErrorInvalidShipTypeMessage.java b/src/main/java/org/ships/config/messages/messages/error/ErrorInvalidShipTypeMessage.java index daf53c26..6aae02a7 100644 --- a/src/main/java/org/ships/config/messages/messages/error/ErrorInvalidShipTypeMessage.java +++ b/src/main/java/org/ships/config/messages/messages/error/ErrorInvalidShipTypeMessage.java @@ -4,6 +4,7 @@ import org.jetbrains.annotations.NotNull; import org.ships.config.messages.Message; import org.ships.config.messages.adapter.MessageAdapter; +import org.ships.config.messages.adapter.MessageAdapters; import org.ships.config.messages.adapter.category.AdapterCategory; import java.util.Collection; @@ -18,7 +19,7 @@ public String[] getPath() { @Override public Component getDefaultMessage() { - return Component.text("Invalid Shiptype of '" + Message.INVALID_NAME.adapterTextFormat() + "'"); + return Component.text("Invalid Shiptype of '" + MessageAdapters.INVALID_NAME.adapterTextFormat() + "'"); } @Override @@ -28,11 +29,11 @@ public Collection> getCategories() { @Override public Collection> getAdapters() { - return List.of(Message.INVALID_NAME); + return List.of(MessageAdapters.INVALID_NAME); } @Override public Component processMessage(@NotNull Component text, String obj) { - return Message.INVALID_NAME.processMessage(obj, text); + return MessageAdapters.INVALID_NAME.processMessage(obj, text); } } diff --git a/src/main/java/org/ships/config/messages/messages/error/ErrorNotEnoughFuelMessage.java b/src/main/java/org/ships/config/messages/messages/error/ErrorNotEnoughFuelMessage.java index 68f4eed9..657cdfd0 100644 --- a/src/main/java/org/ships/config/messages/messages/error/ErrorNotEnoughFuelMessage.java +++ b/src/main/java/org/ships/config/messages/messages/error/ErrorNotEnoughFuelMessage.java @@ -31,9 +31,9 @@ public String[] getPath() { @Override public Component getDefaultMessage() { - return Component.text( - "Not enough fuel, you need " + Message.FUEL_LEFT_REQUIREMENT.adapterTextFormat() + " more of either " - + new CollectionAdapter<>(Message.ITEM_NAME).adapterTextFormat()); + return Component.text("Not enough fuel, you need " + MessageAdapters.FUEL_LEFT_REQUIREMENT.adapterTextFormat() + + " more of either " + new CollectionAdapter<>( + MessageAdapters.ITEM_NAME).adapterTextFormat()); } @Override @@ -55,8 +55,9 @@ public Component processMessage(@NotNull Component text, FuelRequirementMessageD int toTakeAmount = obj.getToTakeAmount(); Collection fuelTypes = obj.getFuelTypes(); - List> vesselAdapters = MessageAdapters.getAdaptersFor(AdapterCategories.VESSEL).collect( - Collectors.toList()); + List> vesselAdapters = MessageAdapters + .getAdaptersFor(AdapterCategories.VESSEL) + .collect(Collectors.toList()); List> itemTypeAdapters = MessageAdapters .getAdaptersFor(AdapterCategories.ITEM_TYPE) .map(CollectionAdapter::new) diff --git a/src/main/java/org/ships/config/messages/messages/error/ErrorOversizedMessage.java b/src/main/java/org/ships/config/messages/messages/error/ErrorOversizedMessage.java index 9c745e4e..d9cc7ccf 100644 --- a/src/main/java/org/ships/config/messages/messages/error/ErrorOversizedMessage.java +++ b/src/main/java/org/ships/config/messages/messages/error/ErrorOversizedMessage.java @@ -25,7 +25,7 @@ public String[] getPath() { @Override public Component getDefaultMessage() { return Component.text( - Message.VESSEL_ID.adapterTextFormat() + " is over the max size of " + OVERSIZED_BY.adapterTextFormat()); + MessageAdapters.VESSEL_ID.adapterTextFormat() + " is over the max size of " + OVERSIZED_BY.adapterTextFormat()); } @Override diff --git a/src/main/java/org/ships/config/messages/messages/error/ErrorPermissionMissMatchMessage.java b/src/main/java/org/ships/config/messages/messages/error/ErrorPermissionMissMatchMessage.java index 81c20257..640d207a 100644 --- a/src/main/java/org/ships/config/messages/messages/error/ErrorPermissionMissMatchMessage.java +++ b/src/main/java/org/ships/config/messages/messages/error/ErrorPermissionMissMatchMessage.java @@ -24,7 +24,7 @@ public String[] getPath() { @Override public Component getDefaultMessage() { return Component - .text("Missing permission of " + Message.PERMISSION_NODE.adapterTextFormat()) + .text("Missing permission of " + MessageAdapters.PERMISSION_NODE.adapterTextFormat()) .color(NamedTextColor.RED); } diff --git a/src/main/java/org/ships/config/messages/messages/error/ErrorSpecialBlockPercentNotEnough.java b/src/main/java/org/ships/config/messages/messages/error/ErrorSpecialBlockPercentNotEnough.java index c47d28c5..c1c4e9c1 100644 --- a/src/main/java/org/ships/config/messages/messages/error/ErrorSpecialBlockPercentNotEnough.java +++ b/src/main/java/org/ships/config/messages/messages/error/ErrorSpecialBlockPercentNotEnough.java @@ -29,8 +29,8 @@ public String[] getPath() { @Override public Component getDefaultMessage() { - return Component.text("You have " + Message.PERCENT_FOUND.adapterTextFormat() + "% of one of " - + Message.BLOCK_NAMES.adapterTextFormat() + ". You require more"); + return Component.text("You have " + MessageAdapters.PERCENT_FOUND.adapterTextFormat() + "% of one of " + + MessageAdapters.BLOCK_NAMES.adapterTextFormat() + ". You require more"); } @Override @@ -41,15 +41,16 @@ public Collection> getCategories() { @Override public Collection> getAdapters() { Collection> collection = new HashSet<>(Message.super.getAdapters()); - collection.add(Message.PERCENT_FOUND); - collection.add(Message.TOTAL_FOUND_BLOCKS); + collection.add(MessageAdapters.PERCENT_FOUND); + collection.add(MessageAdapters.TOTAL_FOUND_BLOCKS); return collection; } @Override public Component processMessage(@NotNull Component text, RequirementPercentMessageData obj) { - List> vesselAdapters = MessageAdapters.getAdaptersFor(AdapterCategories.VESSEL).collect( - Collectors.toList()); + List> vesselAdapters = MessageAdapters + .getAdaptersFor(AdapterCategories.VESSEL) + .collect(Collectors.toList()); List>> blockGroupsAdapters = MessageAdapters .getAdaptersFor(AdapterCategories.BLOCK_GROUP) .collect(Collectors.toList()); @@ -59,7 +60,7 @@ public Component processMessage(@NotNull Component text, RequirementPercentMessa } if (obj.getVessel() instanceof VesselRequirement) { - VesselRequirement shipVessel = (VesselRequirement)obj.getVessel(); + VesselRequirement shipVessel = (VesselRequirement) obj.getVessel(); Optional opRequirement = shipVessel.getRequirement( SpecialBlocksRequirement.class); if (opRequirement.isPresent()) { @@ -69,8 +70,8 @@ public Component processMessage(@NotNull Component text, RequirementPercentMessa } } - text = Message.PERCENT_FOUND.processMessage(obj.getPercentageMet(), text); - text = Message.TOTAL_FOUND_BLOCKS.processMessage(obj.getBlocksMeetingRequirements(), text); + text = MessageAdapters.PERCENT_FOUND.processMessage(obj.getPercentageMet(), text); + text = MessageAdapters.TOTAL_FOUND_BLOCKS.processMessage(obj.getBlocksMeetingRequirements(), text); return text; } diff --git a/src/main/java/org/ships/config/messages/messages/error/ErrorTooManyOfBlockMessage.java b/src/main/java/org/ships/config/messages/messages/error/ErrorTooManyOfBlockMessage.java index 96356519..c01fec37 100644 --- a/src/main/java/org/ships/config/messages/messages/error/ErrorTooManyOfBlockMessage.java +++ b/src/main/java/org/ships/config/messages/messages/error/ErrorTooManyOfBlockMessage.java @@ -25,7 +25,7 @@ public String[] getPath() { @Override public Component getDefaultMessage() { return Component - .text("Too many of " + Message.BLOCK_TYPE_NAME.adapterTextFormat() + " found") + .text("Too many of " + MessageAdapters.BLOCK_TYPE_NAME.adapterTextFormat() + " found") .color(NamedTextColor.RED); } diff --git a/src/main/java/org/ships/config/messages/messages/error/ErrorUndersizedMessage.java b/src/main/java/org/ships/config/messages/messages/error/ErrorUndersizedMessage.java index 7c0ef208..b2dff8ca 100644 --- a/src/main/java/org/ships/config/messages/messages/error/ErrorUndersizedMessage.java +++ b/src/main/java/org/ships/config/messages/messages/error/ErrorUndersizedMessage.java @@ -7,7 +7,6 @@ import org.ships.config.messages.adapter.MessageAdapters; import org.ships.config.messages.adapter.category.AdapterCategories; import org.ships.config.messages.adapter.category.AdapterCategory; -import org.ships.config.messages.adapter.config.ConfigAdapter; import org.ships.config.messages.adapter.specific.number.NumberAdapter; import org.ships.vessel.common.types.Vessel; @@ -25,7 +24,7 @@ public String[] getPath() { @Override public Component getDefaultMessage() { - return Component.text(Message.VESSEL_ID.adapterTextFormat() + " is under the min size of " + return Component.text(MessageAdapters.VESSEL_ID.adapterTextFormat() + " is under the min size of " + UNDERSIZED_BY.adapterTextFormat()); } @@ -43,8 +42,9 @@ public Collection> getAdapters() { @Override public Component processMessage(@NotNull Component text, Map.Entry obj) { - List> vesselAdapters = MessageAdapters.getAdaptersFor(AdapterCategories.VESSEL).collect( - Collectors.toList()); + List> vesselAdapters = MessageAdapters + .getAdaptersFor(AdapterCategories.VESSEL) + .collect(Collectors.toList()); for (MessageAdapter adapter : vesselAdapters) { text = adapter.processMessage(obj.getKey(), text); } diff --git a/src/main/java/org/ships/config/messages/messages/error/ErrorVesselStillLoadingMessage.java b/src/main/java/org/ships/config/messages/messages/error/ErrorVesselStillLoadingMessage.java index 85fd0ef2..be88fdb3 100644 --- a/src/main/java/org/ships/config/messages/messages/error/ErrorVesselStillLoadingMessage.java +++ b/src/main/java/org/ships/config/messages/messages/error/ErrorVesselStillLoadingMessage.java @@ -23,7 +23,7 @@ public String[] getPath() { @Override public Component getDefaultMessage() { return Component - .text(Message.VESSEL_NAME.adapterTextFormat() + .text(MessageAdapters.VESSEL_NAME.adapterTextFormat() + " is loading. All movement controls are locked until it is loaded") .color(NamedTextColor.RED); } diff --git a/src/main/java/org/ships/config/messages/messages/info/InfoAltitudeSpeedMessage.java b/src/main/java/org/ships/config/messages/messages/info/InfoAltitudeSpeedMessage.java index deb75302..d00870f3 100644 --- a/src/main/java/org/ships/config/messages/messages/info/InfoAltitudeSpeedMessage.java +++ b/src/main/java/org/ships/config/messages/messages/info/InfoAltitudeSpeedMessage.java @@ -25,7 +25,7 @@ public Component getDefaultMessage() { return Component .text("Max Altitude Speed: ") .color(NamedTextColor.AQUA) - .append(Component.text("%" + Message.VESSEL_SPEED.adapterText() + "%").color(NamedTextColor.GOLD)); + .append(Component.text("%" + MessageAdapters.VESSEL_SPEED.adapterText() + "%").color(NamedTextColor.GOLD)); } @Override diff --git a/src/main/java/org/ships/config/messages/messages/info/InfoDefaultPermissionMessage.java b/src/main/java/org/ships/config/messages/messages/info/InfoDefaultPermissionMessage.java index 05a1a9ed..143225c2 100644 --- a/src/main/java/org/ships/config/messages/messages/info/InfoDefaultPermissionMessage.java +++ b/src/main/java/org/ships/config/messages/messages/info/InfoDefaultPermissionMessage.java @@ -25,7 +25,7 @@ public Component getDefaultMessage() { return Component .text("Default Permission: ") .color(NamedTextColor.AQUA) - .append(Component.text("%" + Message.CREW_ID.adapterText() + "%").color(NamedTextColor.GOLD)); + .append(Component.text("%" + MessageAdapters.CREW_ID.adapterText() + "%").color(NamedTextColor.GOLD)); } @Override diff --git a/src/main/java/org/ships/config/messages/messages/info/InfoEntitiesListMessage.java b/src/main/java/org/ships/config/messages/messages/info/InfoEntitiesListMessage.java index ea7a169d..810421c2 100644 --- a/src/main/java/org/ships/config/messages/messages/info/InfoEntitiesListMessage.java +++ b/src/main/java/org/ships/config/messages/messages/info/InfoEntitiesListMessage.java @@ -22,7 +22,7 @@ public String[] getPath() { @Override public Component getDefaultMessage() { - return Component.text(Message.ENTITY_NAME.adapterTextFormat()).color(NamedTextColor.GOLD); + return Component.text(MessageAdapters.ENTITY_NAME.adapterTextFormat()).color(NamedTextColor.GOLD); } @Override diff --git a/src/main/java/org/ships/config/messages/messages/info/InfoFlagMessage.java b/src/main/java/org/ships/config/messages/messages/info/InfoFlagMessage.java index 4526b0a9..387f27a3 100644 --- a/src/main/java/org/ships/config/messages/messages/info/InfoFlagMessage.java +++ b/src/main/java/org/ships/config/messages/messages/info/InfoFlagMessage.java @@ -25,7 +25,7 @@ public Component getDefaultMessage() { return Component .text("Flags: ") .color(NamedTextColor.AQUA) - .append(Component.text(Message.VESSEL_FLAG_ID.adapterTextFormat()).color(NamedTextColor.GOLD)); + .append(Component.text(MessageAdapters.VESSEL_FLAG_ID.adapterTextFormat()).color(NamedTextColor.GOLD)); } @Override diff --git a/src/main/java/org/ships/config/messages/messages/info/InfoIdMessage.java b/src/main/java/org/ships/config/messages/messages/info/InfoIdMessage.java index f219aa64..889ca11e 100644 --- a/src/main/java/org/ships/config/messages/messages/info/InfoIdMessage.java +++ b/src/main/java/org/ships/config/messages/messages/info/InfoIdMessage.java @@ -25,7 +25,7 @@ public Component getDefaultMessage() { return Component .text("Id: ") .color(NamedTextColor.AQUA) - .append(Component.text("%" + Message.VESSEL_ID.adapterText() + "%").color(NamedTextColor.GOLD)); + .append(Component.text("%" + MessageAdapters.VESSEL_ID.adapterText() + "%").color(NamedTextColor.GOLD)); } @Override diff --git a/src/main/java/org/ships/config/messages/messages/info/InfoMaxSpeedMessage.java b/src/main/java/org/ships/config/messages/messages/info/InfoMaxSpeedMessage.java index b9c89635..3397c364 100644 --- a/src/main/java/org/ships/config/messages/messages/info/InfoMaxSpeedMessage.java +++ b/src/main/java/org/ships/config/messages/messages/info/InfoMaxSpeedMessage.java @@ -25,7 +25,7 @@ public Component getDefaultMessage() { return Component .text("Max Speed: ") .color(NamedTextColor.AQUA) - .append(Component.text("%" + Message.VESSEL_SPEED.adapterText() + "%").color(NamedTextColor.GOLD)); + .append(Component.text("%" + MessageAdapters.VESSEL_SPEED.adapterText() + "%").color(NamedTextColor.GOLD)); } @Override diff --git a/src/main/java/org/ships/config/messages/messages/info/InfoNameMessage.java b/src/main/java/org/ships/config/messages/messages/info/InfoNameMessage.java index 59d1fa25..2fb8a423 100644 --- a/src/main/java/org/ships/config/messages/messages/info/InfoNameMessage.java +++ b/src/main/java/org/ships/config/messages/messages/info/InfoNameMessage.java @@ -24,7 +24,9 @@ public Component getDefaultMessage() { return Component .text("Name: ") .color(NamedTextColor.AQUA) - .append(Component.text("%" + Message.VESSEL_NAME.adapterText() + "%").color(NamedTextColor.GOLD)); + .append(Component + .text("%" + MessageAdapters.VESSEL_NAME.adapterText() + "%") + .color(NamedTextColor.GOLD)); } @Override @@ -50,7 +52,7 @@ public Component processMessage(@NotNull Component text, Vessel obj) { @Deprecated(forRemoval = true) public Set> getExactAdapters() { - return Collections.singleton(Message.VESSEL_NAME); + return Collections.singleton(MessageAdapters.VESSEL_NAME); } } diff --git a/src/main/java/org/ships/config/messages/messages/info/InfoPlayerSpawnedOnShipMessage.java b/src/main/java/org/ships/config/messages/messages/info/InfoPlayerSpawnedOnShipMessage.java index 201b4e32..37de4b76 100644 --- a/src/main/java/org/ships/config/messages/messages/info/InfoPlayerSpawnedOnShipMessage.java +++ b/src/main/java/org/ships/config/messages/messages/info/InfoPlayerSpawnedOnShipMessage.java @@ -22,7 +22,7 @@ public String[] getPath() { @Override public Component getDefaultMessage() { - return Component.text("You have spawned on " + Message.VESSEL_NAME.adapterTextFormat()); + return Component.text("You have spawned on " + MessageAdapters.VESSEL_NAME.adapterTextFormat()); } @Override diff --git a/src/main/java/org/ships/config/messages/messages/info/InfoSizeMessage.java b/src/main/java/org/ships/config/messages/messages/info/InfoSizeMessage.java index f5b846b4..e19f75f0 100644 --- a/src/main/java/org/ships/config/messages/messages/info/InfoSizeMessage.java +++ b/src/main/java/org/ships/config/messages/messages/info/InfoSizeMessage.java @@ -25,7 +25,9 @@ public Component getDefaultMessage() { return Component .text("Current Size: ") .color(NamedTextColor.AQUA) - .append(Component.text("%" + Message.STRUCTURE_SIZE.adapterText() + "%").color(NamedTextColor.GOLD)); + .append(Component + .text("%" + MessageAdapters.STRUCTURE_SIZE.adapterText() + "%") + .color(NamedTextColor.GOLD)); } @Override diff --git a/src/main/java/org/ships/config/messages/messages/info/InfoVesselInfoMessage.java b/src/main/java/org/ships/config/messages/messages/info/InfoVesselInfoMessage.java index e09db36f..ca9ca169 100644 --- a/src/main/java/org/ships/config/messages/messages/info/InfoVesselInfoMessage.java +++ b/src/main/java/org/ships/config/messages/messages/info/InfoVesselInfoMessage.java @@ -23,9 +23,11 @@ public String[] getPath() { @Override public Component getDefaultMessage() { return Component - .text("%" + Message.VESSEL_INFO_KEY.adapterText() + "%: ") + .text("%" + MessageAdapters.VESSEL_INFO_KEY.adapterText() + "%: ") .color(NamedTextColor.AQUA) - .append(Component.text("%" + Message.VESSEL_INFO_VALUE.adapterText() + "%").color(NamedTextColor.GOLD)); + .append(Component + .text("%" + MessageAdapters.VESSEL_INFO_VALUE.adapterText() + "%") + .color(NamedTextColor.GOLD)); } @Override @@ -35,7 +37,9 @@ public Collection> getCategories() { @Override public Component processMessage(@NotNull Component text, Map.Entry obj) { - List>> infoAdapters = MessageAdapters.getAdaptersFor(AdapterCategories.VESSEL_INFO).collect(Collectors.toList()); + List>> infoAdapters = MessageAdapters + .getAdaptersFor(AdapterCategories.VESSEL_INFO) + .collect(Collectors.toList()); for (MessageAdapter> adapter : infoAdapters) { text = adapter.processMessage(obj, text); } diff --git a/src/main/java/org/ships/config/parsers/identify/StringToBlockFinder.java b/src/main/java/org/ships/config/parsers/identify/StringToBlockFinder.java index 94b7175c..3a448628 100644 --- a/src/main/java/org/ships/config/parsers/identify/StringToBlockFinder.java +++ b/src/main/java/org/ships/config/parsers/identify/StringToBlockFinder.java @@ -1,10 +1,11 @@ package org.ships.config.parsers.identify; import org.ships.algorthum.blockfinder.BasicBlockFinder; +import org.ships.algorthum.blockfinder.BlockFinders; public class StringToBlockFinder extends StringToIdentifiable { public StringToBlockFinder() { - super(BasicBlockFinder.class); + super(() -> BlockFinders.getBlockFinders().stream()); } } diff --git a/src/main/java/org/ships/config/parsers/identify/StringToCrewPermission.java b/src/main/java/org/ships/config/parsers/identify/StringToCrewPermission.java index 8edebe88..ff950229 100644 --- a/src/main/java/org/ships/config/parsers/identify/StringToCrewPermission.java +++ b/src/main/java/org/ships/config/parsers/identify/StringToCrewPermission.java @@ -1,10 +1,11 @@ package org.ships.config.parsers.identify; import org.ships.permissions.vessel.CrewPermission; +import org.ships.permissions.vessel.CrewPermissions; public class StringToCrewPermission extends StringToIdentifiable { public StringToCrewPermission() { - super(CrewPermission.class); + super(() -> CrewPermissions.permissions().stream()); } } diff --git a/src/main/java/org/ships/config/parsers/identify/StringToIdentifiable.java b/src/main/java/org/ships/config/parsers/identify/StringToIdentifiable.java index 382c711d..bea13a54 100644 --- a/src/main/java/org/ships/config/parsers/identify/StringToIdentifiable.java +++ b/src/main/java/org/ships/config/parsers/identify/StringToIdentifiable.java @@ -2,24 +2,24 @@ import org.core.config.parser.StringParser; import org.core.utils.Identifiable; -import org.ships.plugin.ShipsPlugin; -import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.function.Supplier; import java.util.stream.Collectors; +import java.util.stream.Stream; public class StringToIdentifiable implements StringParser.Suggestible { - protected final Class class1; + protected final Supplier> all; - public StringToIdentifiable(Class class1) { - this.class1 = class1; + public StringToIdentifiable(Supplier> class1) { + this.all = class1; } @Override public Optional parse(String original) { - return ShipsPlugin.getPlugin().getAll(this.class1).stream().filter(t -> t.getId().equals(original)).findAny(); + return this.all.get().filter(t -> t.getId().equals(original)).findAny(); } @Override @@ -38,6 +38,6 @@ public List getSuggestions(String peek) { @Override public List getSuggestions() { - return new ArrayList<>(ShipsPlugin.getPlugin().getAll(this.class1)); + return this.all.get().collect(Collectors.toList()); } } diff --git a/src/main/java/org/ships/config/parsers/identify/StringToMovement.java b/src/main/java/org/ships/config/parsers/identify/StringToMovement.java index 18d70a9e..e4936e3f 100644 --- a/src/main/java/org/ships/config/parsers/identify/StringToMovement.java +++ b/src/main/java/org/ships/config/parsers/identify/StringToMovement.java @@ -1,10 +1,11 @@ package org.ships.config.parsers.identify; import org.ships.algorthum.movement.BasicMovement; +import org.ships.algorthum.movement.Movements; public class StringToMovement extends StringToIdentifiable { public StringToMovement() { - super(BasicMovement.class); + super(() -> Movements.getMovements().stream()); } } diff --git a/src/main/java/org/ships/config/parsers/identify/StringToShipTypeParser.java b/src/main/java/org/ships/config/parsers/identify/StringToShipTypeParser.java index 03be4c21..300307fa 100644 --- a/src/main/java/org/ships/config/parsers/identify/StringToShipTypeParser.java +++ b/src/main/java/org/ships/config/parsers/identify/StringToShipTypeParser.java @@ -3,6 +3,7 @@ import org.ships.plugin.ShipsPlugin; import org.ships.vessel.common.assits.shiptype.CloneableShipType; import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import java.util.Collection; import java.util.List; @@ -12,20 +13,19 @@ public class StringToShipTypeParser extends StringToIdentifiable> { public StringToShipTypeParser() { - super((Class>) (Object) ShipType.class); + super(() -> ShipTypes.shipTypes().stream()); } public static class StringToHostCloneableShipTypeParser extends StringToIdentifiable> { public StringToHostCloneableShipTypeParser() { - super((Class>) (Object) CloneableShipType.class); + super(ShipTypes::cloneableShipTypes); } @Override public Optional> parse(String original) { - Collection> shipTypes = ShipsPlugin.getPlugin().getAllCloneableShipTypes(); - return shipTypes - .stream() + return ShipTypes + .cloneableShipTypes() .filter(s -> s.getOriginType().equals(s)) .filter(s -> s.getId().equals(original)) .findAny(); @@ -33,8 +33,7 @@ public Optional> parse(String original) { @Override public List> getSuggestions() { - Collection> shipTypes = ShipsPlugin.getPlugin().getAllCloneableShipTypes(); - return shipTypes.stream().filter(s -> s.getOriginType().equals(s)).collect(Collectors.toList()); + return ShipTypes.cloneableShipTypes().filter(s -> s.getOriginType().equals(s)).collect(Collectors.toList()); } } } diff --git a/src/main/java/org/ships/event/listener/CoreEventListener.java b/src/main/java/org/ships/event/listener/CoreEventListener.java index c86c8858..4f71d1a1 100644 --- a/src/main/java/org/ships/event/listener/CoreEventListener.java +++ b/src/main/java/org/ships/event/listener/CoreEventListener.java @@ -45,6 +45,7 @@ import org.ships.config.blocks.instruction.CollideType; import org.ships.config.configuration.ShipsConfig; import org.ships.config.messages.AdventureMessageConfig; +import org.ships.config.messages.Messages; import org.ships.event.vessel.create.VesselCreateEvent; import org.ships.exceptions.NoLicencePresent; import org.ships.exceptions.load.LoadVesselException; @@ -60,10 +61,12 @@ import org.ships.vessel.common.flag.MovingFlag; import org.ships.vessel.common.flag.PlayerStatesFlag; import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import org.ships.vessel.common.types.Vessel; import org.ships.vessel.common.types.typical.ShipsVessel; import org.ships.vessel.sign.LicenceSign; import org.ships.vessel.sign.ShipsSign; +import org.ships.vessel.sign.ShipsSigns; import org.ships.vessel.structure.PositionableShipsStructure; import java.io.File; @@ -227,10 +230,10 @@ public void onPlayerInteractWithBlock(EntityInteractEvent.WithBlock.AsPlayer eve if (collideType != CollideType.MATERIAL) { return; } - ShipsPlugin.getPlugin().getAll(ShipsSign.class).stream().filter(s -> s.isSign(lste)).forEach(s -> { + ShipsSigns.signs().stream().filter(s -> s.isSign(lste)).forEach(s -> { if (ShipsPlugin.getPlugin().getLockedSignManager().isLocked(position)) { LivePlayer player = event.getEntity(); - Component text = AdventureMessageConfig.ERROR_SHIPS_SIGN_IS_MOVING.parseMessage(); + Component text = Messages.ERROR_SHIPS_SIGN_IS_MOVING.parseMessage(); player.sendMessage(text); return; } @@ -262,9 +265,8 @@ public void onSignChangeEvent(SignChangeEvent.ByPlayer event) { if (opFirstLine.isEmpty()) { return; } - ShipsSign sign = ShipsPlugin - .getPlugin() - .getAll(ShipsSign.class) + ShipsSign sign = ShipsSigns + .signs() .stream() .filter(s -> s.isSign(event.getChangingSide().getLines())) .findFirst() @@ -290,14 +292,13 @@ public void onSignChangeEvent(SignChangeEvent.ByPlayer event) { return; } String typeText = ComponentUtils.toPlain(opTypeText.get()); - Optional> opType = ShipsPlugin - .getPlugin() - .getAllShipTypes() + Optional> opType = ShipTypes + .shipTypes() .stream() .filter(t -> typeText.equalsIgnoreCase(t.getDisplayName())) .findAny(); if (opType.isEmpty()) { - event.getEntity().sendMessage(AdventureMessageConfig.ERROR_INVALID_SHIP_TYPE.processMessage(typeText)); + event.getEntity().sendMessage(Messages.ERROR_INVALID_SHIP_TYPE.processMessage(typeText)); event.setCancelled(true); return; } @@ -305,8 +306,8 @@ public void onSignChangeEvent(SignChangeEvent.ByPlayer event) { if (!(event.getEntity().hasPermission(type.getMakePermission()) || event .getEntity() .hasPermission(Permissions.SHIP_REMOVE_OTHER))) { - Component text = AdventureMessageConfig.ERROR_PERMISSION_MISS_MATCH.processMessage( - AdventureMessageConfig.ERROR_PERMISSION_MISS_MATCH.parseMessage( + Component text = Messages.ERROR_PERMISSION_MISS_MATCH.processMessage( + Messages.ERROR_PERMISSION_MISS_MATCH.parseMessage( ShipsPlugin.getPlugin().getAdventureMessageConfig()), new AbstractMap.SimpleImmutableEntry<>(event.getEntity(), type.getMakePermission().getPermissionValue())); @@ -322,7 +323,7 @@ public void onSignChangeEvent(SignChangeEvent.ByPlayer event) { } String name = ComponentUtils.toPlain(opName.get()); IdVesselFinder.load("ships:" + type.getName().toLowerCase() + "." + name.toLowerCase()); - event.getEntity().sendMessage(AdventureMessageConfig.ERROR_INVALID_SHIP_NAME.processMessage(name)); + event.getEntity().sendMessage(Messages.ERROR_INVALID_SHIP_NAME.processMessage(name)); event.setCancelled(true); return; } catch (LoadVesselException ignored) { @@ -332,9 +333,7 @@ public void onSignChangeEvent(SignChangeEvent.ByPlayer event) { for (Direction direction : FourFacingDirection.getFourFacingDirections()) { SyncBlockPosition position = event.getPosition().getRelative(direction); Vessel vessel = VesselBlockFinder.findCached(position); - event - .getEntity() - .sendMessage(AdventureMessageConfig.ERROR_CANNOT_CREATE_ONTOP.processMessage(vessel)); + event.getEntity().sendMessage(Messages.ERROR_CANNOT_CREATE_ONTOP.processMessage(vessel)); event.setCancelled(true); return; } @@ -358,9 +357,8 @@ public void onSignChangeEvent(SignChangeEvent.ByPlayer event) { if ((finalBar.progress() * 100) > trackSize) { return; } - Component text = AdventureMessageConfig.BAR_BLOCK_FINDER_ON_FIND.processMessage( - currentStructure); - int blockAmount = (currentStructure.getOriginalRelativePositionsToCenter().size() + 1); + Component text = Messages.BAR_BLOCK_FINDER_ON_FIND.processMessage(currentStructure); + int blockAmount = (currentStructure.size() + 1); float progress = (trackSize / (float) Math.max(trackSize, blockAmount)); finalBar.name(text); finalBar.progress(progress); @@ -378,9 +376,6 @@ public void onSignChangeEvent(SignChangeEvent.ByPlayer event) { ((TeleportToVessel) vessel).setTeleportPosition(bp); } vessel.setStructure(structure); - if (vessel instanceof WaterType) { - return structure.fillAir().thenApply(str -> vessel); - } return CompletableFuture.completedFuture(vessel); }).thenAccept(vessel -> { if (vessel instanceof CrewStoredVessel) { @@ -424,10 +419,7 @@ public void onBlockExplode(ExplosionEvent.Post event) { if (!config.isPreventingExplosions()) { return; } - LicenceSign licenceSign = ShipsPlugin - .getPlugin() - .get(LicenceSign.class) - .orElseThrow(() -> new RuntimeException("Could not " + "find licence sign? is it registered?")); + LicenceSign licenceSign = ShipsSigns.LICENCE; Optional opLicenceSignSnapshot = event .getExplosion() .getBlocks() @@ -471,7 +463,7 @@ public void onBlockExplode(ExplosionEvent.Post event) { .setDisplayName("restoring blocks") .setDelay(1) .setDelayUnit(TimeUnit.MINECRAFT_TICKS) - .build(ShipsPlugin.getPlugin()) + .buildDelayed(ShipsPlugin.getPlugin()) .run(); } } @@ -483,11 +475,7 @@ public void onBlockBreak(BlockChangeEvent.Break.Pre event) { } ShipsConfig config = ShipsPlugin.getPlugin().getConfig(); BlockDetails beforeDetails = event.getBeforeState(); - LicenceSign licenceSign = ShipsPlugin - .getPlugin() - .get(LicenceSign.class) - .orElseThrow(() -> new IllegalStateException( - "Licence sign could not be found from register. Something is really wrong.")); + LicenceSign licenceSign = ShipsSigns.LICENCE; Collection list = new ArrayList<>(Arrays.asList(FourFacingDirection.getFourFacingDirections())); list.add(FourFacingDirection.NONE); SyncBlockPosition position = event.getPosition(); diff --git a/src/main/java/org/ships/exceptions/load/WrappedFileLoadVesselException.java b/src/main/java/org/ships/exceptions/load/WrappedFileLoadVesselException.java index 79575eb9..bb93ad3c 100644 --- a/src/main/java/org/ships/exceptions/load/WrappedFileLoadVesselException.java +++ b/src/main/java/org/ships/exceptions/load/WrappedFileLoadVesselException.java @@ -1,5 +1,7 @@ package org.ships.exceptions.load; +import org.ships.plugin.ShipsPlugin; + import java.io.File; import java.io.PrintStream; import java.io.PrintWriter; @@ -15,19 +17,19 @@ public WrappedFileLoadVesselException(File file, Throwable throwable) { @Override public void printStackTrace() { - System.err.println("An error occurred in file: " + this.getFile().getPath()); + ShipsPlugin.getPlugin().getLogger().error("An error occurred in file: " + this.getFile().getPath()); this.throwable.printStackTrace(); } @Override public void printStackTrace(PrintStream stream) { - System.err.println("An error occurred in file: " + this.getFile().getPath()); + ShipsPlugin.getPlugin().getLogger().error("An error occurred in file: " + this.getFile().getPath()); this.throwable.printStackTrace(stream); } @Override public void printStackTrace(PrintWriter writer) { - System.err.println("An error occurred in file: " + this.getFile().getPath()); + ShipsPlugin.getPlugin().getLogger().error("An error occurred in file: " + this.getFile().getPath()); this.throwable.printStackTrace(writer); } } diff --git a/src/main/java/org/ships/exceptions/move/MoveException.java b/src/main/java/org/ships/exceptions/move/MoveException.java index 1ffa4402..9e3af5f3 100644 --- a/src/main/java/org/ships/exceptions/move/MoveException.java +++ b/src/main/java/org/ships/exceptions/move/MoveException.java @@ -1,8 +1,6 @@ package org.ships.exceptions.move; import net.kyori.adventure.text.Component; -import org.core.adventureText.AText; -import org.core.adventureText.adventure.AdventureText; import org.core.utils.ComponentUtils; import org.jetbrains.annotations.NotNull; import org.ships.config.messages.Message; @@ -32,11 +30,6 @@ public MoveException(@NotNull MovementContext context, this.data = data; } - @Deprecated(forRemoval = true) - public @NotNull AText getErrorMessageText() { - return new AdventureText(this.errorMessage); - } - public @NotNull Component getErrorMessage() { return this.errorMessage; } diff --git a/src/main/java/org/ships/movement/BlockPriorities.java b/src/main/java/org/ships/movement/BlockPriorities.java new file mode 100644 index 00000000..4b03ba42 --- /dev/null +++ b/src/main/java/org/ships/movement/BlockPriorities.java @@ -0,0 +1,31 @@ +package org.ships.movement; + +import org.jetbrains.annotations.NotNull; + +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.LinkedTransferQueue; + +public final class BlockPriorities { + + private static final Collection registered = new LinkedTransferQueue<>(); + + public static final BlockPriority ATTACHED = register(new PackagedBlockPriority("attached", 5)); + public static final BlockPriority DIRECTIONAL = register(new PackagedBlockPriority("directional", 10)); + public static final BlockPriority NORMAL = register(new PackagedBlockPriority("normal", 100)); + public static final BlockPriority AIR = register(new PackagedBlockPriority("air", 200)); + + private BlockPriorities() { + throw new RuntimeException("Do not create"); + } + + public static T register(@NotNull T blockPriority) { + registered.add(blockPriority); + return blockPriority; + } + + public static Collection priorities() { + return Collections.unmodifiableCollection(registered); + } + +} diff --git a/src/main/java/org/ships/movement/BlockPriority.java b/src/main/java/org/ships/movement/BlockPriority.java index 00e8e377..fa8e9038 100644 --- a/src/main/java/org/ships/movement/BlockPriority.java +++ b/src/main/java/org/ships/movement/BlockPriority.java @@ -4,10 +4,17 @@ public interface BlockPriority extends Identifiable { - BlockPriority ATTACHED = new PackagedBlockPriority("attached", 5); - BlockPriority DIRECTIONAL = new PackagedBlockPriority("directional", 10); - BlockPriority NORMAL = new PackagedBlockPriority("normal", 100); - BlockPriority AIR = new PackagedBlockPriority("air", 200); + @Deprecated(forRemoval = true) + BlockPriority ATTACHED = BlockPriorities.ATTACHED; + + @Deprecated(forRemoval = true) + BlockPriority DIRECTIONAL = BlockPriorities.DIRECTIONAL; + + @Deprecated(forRemoval = true) + BlockPriority NORMAL = BlockPriorities.NORMAL; + + @Deprecated(forRemoval = true) + BlockPriority AIR = BlockPriorities.AIR; int getPriorityNumber(); diff --git a/src/main/java/org/ships/movement/MovementContext.java b/src/main/java/org/ships/movement/MovementContext.java index 0aca67e9..2cda7352 100644 --- a/src/main/java/org/ships/movement/MovementContext.java +++ b/src/main/java/org/ships/movement/MovementContext.java @@ -6,8 +6,8 @@ import org.core.entity.Entity; import org.core.entity.EntitySnapshot; import org.core.entity.LiveEntity; +import org.core.entity.living.human.player.LivePlayer; import org.core.utils.BarUtils; -import org.core.world.boss.ServerBossBar; import org.core.world.direction.FourFacingDirection; import org.core.world.position.block.BlockType; import org.core.world.position.impl.BlockPosition; @@ -18,7 +18,7 @@ import org.ships.config.blocks.BlockList; import org.ships.config.blocks.instruction.BlockInstruction; import org.ships.config.blocks.instruction.CollideType; -import org.ships.config.messages.AdventureMessageConfig; +import org.ships.config.messages.Messages; import org.ships.config.messages.messages.error.data.CollideDetectedMessageData; import org.ships.event.vessel.move.VesselMoveEvent; import org.ships.exceptions.move.MoveException; @@ -31,13 +31,14 @@ import org.ships.vessel.common.assits.VesselRequirement; import org.ships.vessel.common.flag.MovingFlag; import org.ships.vessel.common.types.Vessel; -import org.ships.vessel.sign.LicenceSign; +import org.ships.vessel.sign.ShipsSigns; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.stream.Collectors; +import java.util.stream.Stream; public class MovementContext { @@ -54,11 +55,6 @@ public Optional getClicked() { return this.details.getClickedBlock(); } - @Deprecated(forRemoval = true) - public Optional getBossBar() { - return this.details.getBossBar(); - } - public Optional getAdventureBossBar() { return this.details.getAdventureBossBar(); } @@ -120,21 +116,23 @@ public CompletableFuture move(Vessel vessel, boolean updateStructure) thro this.isVesselMoving(vessel); vessel.set(MovingFlag.class, this); Consumer> consumer = entities -> { - try { - this.movePostEntity(vessel); - } catch (Throwable e) { - this - .getAdventureBossBar() - .ifPresent(bar -> BarUtils.getPlayers(bar).forEach(player -> player.hideBossBar(bar))); - vessel.set(new MovingFlag()); - entities.forEach(entity -> entity.setGravity(true)); - this.getException().accept(this, e); - - if (e instanceof MoveException) { - return; + TranslateCore.getScheduleManager().schedule().setAsync(false).setRunner(sch -> { + try { + this.movePostEntity(vessel); + } catch (Throwable e) { + this + .getAdventureBossBar() + .ifPresent(bar -> BarUtils.getPlayers(bar).forEach(player -> player.hideBossBar(bar))); + vessel.set(new MovingFlag()); + entities.forEach(entity -> entity.setGravity(true)); + this.getException().accept(this, e); + + if (e instanceof MoveException) { + return; + } + e.printStackTrace(); } - e.printStackTrace(); - } + }).setDisplayName("Back to sync").buildDelayed(ShipsPlugin.getPlugin()).run(); }; if (updateStructure) { return vessel @@ -152,7 +150,7 @@ private void movePostEntity(Vessel vessel) throws Exception { }); if (ShipsPlugin.getPlugin().getPreventMovementManager().isMovementPrevented()) { - throw new MoveException(this, AdventureMessageConfig.ERROR_PREVENT_MOVEMENT, vessel); + throw new MoveException(this, Messages.ERROR_PREVENT_MOVEMENT, vessel); } if (this.isPreMoveEventCancelled(vessel)) { @@ -163,7 +161,7 @@ private void movePostEntity(Vessel vessel) throws Exception { bossBar.progress(0.25f); }); if (vessel instanceof SignBasedVessel) { - this.isLicenceSignValid((SignBasedVessel)vessel); + this.isLicenceSignValid((SignBasedVessel) vessel); } this.getAdventureBossBar().ifPresent(bossBar -> { bossBar.name(Component.text("Checking requirements: Vessel specific")); @@ -210,11 +208,18 @@ private void processRequirements(VesselRequirement vessel) throws MoveException } private void isClearFromColliding(@NotNull Vessel vessel) throws MoveException { + var player = vessel + .getPosition() + .getWorld() + .getLiveEntities() + .filter(e -> e instanceof LivePlayer) + .map(e -> (LivePlayer) e) + .findAny() + .orElseThrow(); Set collided = this.getMovingStructure().stream().filter(mb -> { SyncBlockPosition after = mb.getAfterPosition(); - if (this.getMovingStructure().stream().anyMatch(mb1 -> { - return after.equals(mb1.getBeforePosition()); - })) { + + if (this.getMovingStructure().stream().anyMatch(mb1 -> after.equals(mb1.getBeforePosition()))) { return false; } for (BlockType type : vessel.getType().getIgnoredTypes()) { @@ -224,7 +229,10 @@ private void isClearFromColliding(@NotNull Vessel vessel) throws MoveException { } BlockList list = ShipsPlugin.getPlugin().getBlockList(); BlockInstruction bi = list.getBlockInstruction(after.getBlockType()); - return bi.getCollide() != CollideType.IGNORE; + if (bi.getCollide() == CollideType.IGNORE) { + return false; + } + return true; }).map(MovingBlock::getAfterPosition).collect(Collectors.toSet()); if (collided.isEmpty()) { return; @@ -233,9 +241,9 @@ private void isClearFromColliding(@NotNull Vessel vessel) throws MoveException { VesselMoveEvent.CollideDetected collideEvent = new VesselMoveEvent.CollideDetected(vessel, this, collided); TranslateCore.getPlatform().callEvent(collideEvent); - throw new MoveException(this, AdventureMessageConfig.ERROR_COLLIDE_DETECTED, - new CollideDetectedMessageData(vessel, - collided.parallelStream().collect(Collectors.toSet()))); + throw new MoveException(this, Messages.ERROR_COLLIDE_DETECTED, new CollideDetectedMessageData(vessel, collided + .parallelStream() + .collect(Collectors.toSet()))); } private void isRequirementsValid(VesselRequirement vessel) throws MoveException { @@ -243,16 +251,11 @@ private void isRequirementsValid(VesselRequirement vessel) throws MoveException } private void isLicenceSignValid(Vessel vessel) throws MoveException { - Optional opLicence = this - .getMovingStructure() - .get(ShipsPlugin - .getPlugin() - .get(LicenceSign.class) - .orElseThrow(() -> new RuntimeException("Could not find licence sign class"))); + Optional opLicence = this.getMovingStructure().get(ShipsSigns.LICENCE); if (opLicence.isPresent()) { return; } - throw new MoveException(this, AdventureMessageConfig.ERROR_FAILED_TO_FIND_LICENCE_SIGN, vessel.getStructure()); + throw new MoveException(this, Messages.ERROR_FAILED_TO_FIND_LICENCE_SIGN, vessel.getStructure()); } private boolean isPreMoveEventCancelled(Vessel vessel) { @@ -292,9 +295,8 @@ private void saveEntity(@NotNull Vessel vessel, @NotNull Entity enti Optional mBlock = this.getMovingStructure().getBefore(opAttached.get()); if (mBlock.isEmpty()) { SyncBlockPosition position = snapshot.getPosition().toBlockPosition(); - Collection positions = vessel.getStructure().getSyncedPositionsRelativeToWorld(); + Stream positions = vessel.getStructure().getPositionsRelativeToWorld(); Optional opDown = positions - .stream() .filter(f -> position.isInLineOfSight(f.getPosition(), FourFacingDirection.DOWN)) .findAny(); if (opDown.isEmpty()) { @@ -307,7 +309,7 @@ private void saveEntity(@NotNull Vessel vessel, @NotNull Entity enti } this.entities.put(snapshot, mBlock.get()); this.getAdventureBossBar().ifPresent(bossBar -> { - float progress = this.entities.size() / (float)totalSize; + float progress = this.entities.size() / (float) totalSize; progress = progress / 100; bossBar.name(Component.text("Collecting entities: " + this.entities.size())); @@ -320,13 +322,13 @@ private void isVesselMoving(Vessel vessel) throws MoveException { if (opMoving.isEmpty()) { return; } - throw new MoveException(this, AdventureMessageConfig.ERROR_ALREADY_MOVING, vessel); + throw new MoveException(this, Messages.ERROR_ALREADY_MOVING, vessel); } private void isVesselLoading(Vessel vessel) throws MoveException { if (!vessel.isLoading()) { return; } - throw new MoveException(this, AdventureMessageConfig.ERROR_VESSEL_STILL_LOADING, vessel); + throw new MoveException(this, Messages.ERROR_VESSEL_STILL_LOADING, vessel); } } diff --git a/src/main/java/org/ships/movement/MovingBlock.java b/src/main/java/org/ships/movement/MovingBlock.java index fbbce111..1e59905b 100644 --- a/src/main/java/org/ships/movement/MovingBlock.java +++ b/src/main/java/org/ships/movement/MovingBlock.java @@ -9,6 +9,7 @@ import org.core.world.position.impl.BlockPosition; import org.core.world.position.impl.sync.SyncBlockPosition; import org.jetbrains.annotations.NotNull; +import org.ships.movement.action.MovementAction; import java.util.Optional; @@ -20,12 +21,17 @@ public interface MovingBlock { SyncBlockPosition getAfterPosition(); + @Deprecated(forRemoval = true) MovingBlock setAfterPosition(SyncBlockPosition position); BlockDetails getStoredBlockData(); MovingBlock setStoredBlockData(BlockDetails blockDetails); + MovementAction getAction(); + + MovingBlock setAction(@NotNull MovementAction action); + BlockPriority getBlockPriority(); default MovingBlock removeBeforePosition(SyncBlockPosition pos) { @@ -35,7 +41,7 @@ default MovingBlock removeBeforePosition(SyncBlockPosition pos) { } if (opLive.get() instanceof ContainerTileEntity) { ContainerTileEntity cte = (ContainerTileEntity) opLive.get(); - cte.getInventory().getSlots().forEach(s -> s.setItem(null)); + cte.getInventory().getItemSlots().forEach(s -> s.setItem(null)); } return this; } diff --git a/src/main/java/org/ships/movement/Result.java b/src/main/java/org/ships/movement/Result.java index 4e2ec83b..321fdb1e 100644 --- a/src/main/java/org/ships/movement/Result.java +++ b/src/main/java/org/ships/movement/Result.java @@ -17,7 +17,7 @@ import org.ships.vessel.common.flag.FlightPathFlag; import org.ships.vessel.common.flag.SuccessfulMoveFlag; import org.ships.vessel.common.types.Vessel; -import org.ships.vessel.sign.LicenceSign; +import org.ships.vessel.sign.ShipsSigns; import org.ships.vessel.structure.PositionableShipsStructure; import java.util.ArrayList; @@ -48,8 +48,7 @@ public interface Run { .getWhoClicked() .flatMap(uuid -> TranslateCore .getServer() - .getOnlinePlayers() - .parallelStream() + .getLivePlayers() .filter(p -> p.getUniqueId().equals(uuid)) .findAny()) .orElse(null); @@ -60,7 +59,7 @@ public interface Run { .setDelayUnit(unit) .setDisplayName("Repeating display name") .setRunner(new EOTExecutor(v, player)) - .build(ShipsPlugin.getPlugin()) + .buildDelayed(ShipsPlugin.getPlugin()) .run(); }; @@ -76,7 +75,7 @@ public interface Run { .setDelayUnit(TimeUnit.SECONDS) .setDisplayName("Repeating autopilot") .setRunner(new AutopilotExecutor(v)) - .build(ShipsPlugin.getPlugin()) + .buildDelayed(ShipsPlugin.getPlugin()) .run(); }; @@ -100,7 +99,7 @@ public interface Run { Vector3 position2 = after.toExactPosition().getPosition(); position = position2.plus(position); if (!entity.setPosition(position)) { - System.err.println("Teleport failed. Likely due to a plugin cancelling"); + ShipsPlugin.getPlugin().getLogger().error("Teleport failed. Likely due to a plugin cancelling"); } entity.setYaw(yaw); entity.setRoll(roll); @@ -116,14 +115,7 @@ public interface Run { }; Run COMMON_SET_POSITION_OF_LICENCE_SIGN = (v, c) -> { - Optional opSign = c - .getMovingStructure() - .getOriginal() - .get(ShipsPlugin - .getPlugin() - .get(LicenceSign.class) - .orElseThrow( - () -> new RuntimeException("Cannot find licence sign, is it registered"))); + Optional opSign = c.getMovingStructure().getOriginal().get(ShipsSigns.LICENCE); if (opSign.isEmpty()) { return; } diff --git a/src/main/java/org/ships/movement/SetMovingBlock.java b/src/main/java/org/ships/movement/SetMovingBlock.java index 50aad21f..f3ec8630 100644 --- a/src/main/java/org/ships/movement/SetMovingBlock.java +++ b/src/main/java/org/ships/movement/SetMovingBlock.java @@ -1,23 +1,38 @@ package org.ships.movement; +import org.core.vector.type.Vector3; +import org.core.world.WorldExtent; import org.core.world.position.block.BlockTypes; import org.core.world.position.block.details.BlockDetails; import org.core.world.position.block.details.data.keyed.KeyedData; import org.core.world.position.impl.sync.SyncBlockPosition; +import org.jetbrains.annotations.NotNull; +import org.ships.movement.action.MovementAction; public class SetMovingBlock implements MovingBlock { protected SyncBlockPosition before; - protected SyncBlockPosition after; protected BlockDetails detail; + private MovementAction action; + + public SetMovingBlock(SyncBlockPosition before, MovementAction action) { + this(before, action, before.getBlockDetails()); + } + + public SetMovingBlock(SyncBlockPosition before, MovementAction action, BlockDetails details) { + this.before = before; + this.action = action; + this.detail = details; + } public SetMovingBlock(SyncBlockPosition before, SyncBlockPosition after) { this(before, after, before.getBlockDetails()); } + @Deprecated public SetMovingBlock(SyncBlockPosition before, SyncBlockPosition after, BlockDetails details) { this.before = before; - this.after = after; + this.action = MovementAction.plus(after.getPosition().minus(before.getPosition())); this.detail = details; } @@ -26,11 +41,6 @@ public SyncBlockPosition getBeforePosition() { return this.before; } - @Override - public SyncBlockPosition getAfterPosition() { - return this.after; - } - @Override public MovingBlock setBeforePosition(SyncBlockPosition position) { this.before = position; @@ -38,8 +48,16 @@ public MovingBlock setBeforePosition(SyncBlockPosition position) { } @Override + public SyncBlockPosition getAfterPosition() { + WorldExtent world = this.before.getWorld(); + Vector3 newPos = this.action.move(this.before.getPosition()); + return (SyncBlockPosition) world.getPosition(newPos); + } + + @Override + @Deprecated(forRemoval = true) public MovingBlock setAfterPosition(SyncBlockPosition position) { - this.after = position; + this.action = MovementAction.plus(position.getPosition().minus(this.before.getPosition())); return this; } @@ -54,15 +72,26 @@ public MovingBlock setStoredBlockData(BlockDetails blockDetails) { return this; } + @Override + public MovementAction getAction() { + return this.action; + } + + @Override + public MovingBlock setAction(@NotNull MovementAction action) { + this.action = action; + return this; + } + @Override public BlockPriority getBlockPriority() { if ((this.detail.getType().equals(BlockTypes.AIR))) { - return BlockPriority.AIR; + return BlockPriorities.AIR; } else if (this.detail.get(KeyedData.ATTACHABLE).isPresent()) { - return BlockPriority.ATTACHED; + return BlockPriorities.ATTACHED; } else if (this.detail.getDirectionalData().isPresent()) { - return BlockPriority.DIRECTIONAL; + return BlockPriorities.DIRECTIONAL; } - return BlockPriority.NORMAL; + return BlockPriorities.NORMAL; } } diff --git a/src/main/java/org/ships/movement/action/FixedAction.java b/src/main/java/org/ships/movement/action/FixedAction.java new file mode 100644 index 00000000..e476ad43 --- /dev/null +++ b/src/main/java/org/ships/movement/action/FixedAction.java @@ -0,0 +1,20 @@ +package org.ships.movement.action; + +import org.core.vector.type.Vector3; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Supplier; + +class FixedAction implements MovementAction { + + private final @NotNull Supplier> vector; + + public FixedAction(@NotNull Supplier> vector) { + this.vector = vector; + } + + @Override + public Vector3 move(@NotNull Vector3 position) { + return position.plus(this.vector.get()); + } +} diff --git a/src/main/java/org/ships/movement/action/MovementAction.java b/src/main/java/org/ships/movement/action/MovementAction.java new file mode 100644 index 00000000..006cf32d --- /dev/null +++ b/src/main/java/org/ships/movement/action/MovementAction.java @@ -0,0 +1,28 @@ +package org.ships.movement.action; + +import org.core.vector.type.Vector3; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Supplier; + +public interface MovementAction { + + Vector3 move(@NotNull Vector3 position); + + static MovementAction rotateClockwise(Supplier> rotateAround) { + return new RotateClockwiseAction(rotateAround); + } + + static MovementAction rotateAntiClockwise(Supplier> rotateAround) { + return new RotateAntiClockwiseAction(rotateAround); + } + + static MovementAction plus(Supplier> plus) { + return new FixedAction(plus); + } + + static MovementAction plus(Vector3 plus) { + return plus(() -> plus); + } + +} diff --git a/src/main/java/org/ships/movement/action/RotateAntiClockwiseAction.java b/src/main/java/org/ships/movement/action/RotateAntiClockwiseAction.java new file mode 100644 index 00000000..f2909830 --- /dev/null +++ b/src/main/java/org/ships/movement/action/RotateAntiClockwiseAction.java @@ -0,0 +1,28 @@ +package org.ships.movement.action; + +import org.core.vector.type.Vector3; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Supplier; + +class RotateAntiClockwiseAction implements MovementAction { + + private final Supplier> rotateAround; + + public RotateAntiClockwiseAction(Supplier> supplier) { + this.rotateAround = supplier; + } + + @Override + public Vector3 move(@NotNull Vector3 position) { + Vector3 around = rotateAround.get(); + + int symmetry = around.getX(); + int shift = symmetry - around.getZ(); + + int z = position.getZ() - (position.getZ() - symmetry) * 2 - shift; + int y = position.getY(); + int x = position.getX() - shift; + return Vector3.valueOf(z, y, x); + } +} diff --git a/src/main/java/org/ships/movement/action/RotateClockwiseAction.java b/src/main/java/org/ships/movement/action/RotateClockwiseAction.java new file mode 100644 index 00000000..0bb1ba58 --- /dev/null +++ b/src/main/java/org/ships/movement/action/RotateClockwiseAction.java @@ -0,0 +1,28 @@ +package org.ships.movement.action; + +import org.core.vector.type.Vector3; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Supplier; + +class RotateClockwiseAction implements MovementAction { + + private final Supplier> rotateAround; + + public RotateClockwiseAction(Supplier> supplier) { + this.rotateAround = supplier; + } + + @Override + public Vector3 move(@NotNull Vector3 position) { + Vector3 around = rotateAround.get(); + + int symmetry = around.getX(); + int shift = symmetry - around.getZ(); + + int x = position.getX() - (position.getX() - symmetry) * 2 - shift; + int y = position.getY(); + int z = position.getZ() + shift; + return Vector3.valueOf(z, y, x); + } +} diff --git a/src/main/java/org/ships/movement/autopilot/path/FlightPathBuilder.java b/src/main/java/org/ships/movement/autopilot/path/FlightPathBuilder.java index a502c65e..b444171f 100644 --- a/src/main/java/org/ships/movement/autopilot/path/FlightPathBuilder.java +++ b/src/main/java/org/ships/movement/autopilot/path/FlightPathBuilder.java @@ -77,7 +77,7 @@ public FlightPathBuilder ofAutopilot(@NotNull BlockPosition vesselPosition, this.addCheckpoint(new FlightCheckpoint(world.getPosition(to.getX(), travelHeight, to.getZ()))); } if (travelHeight != to.getY()) { - this.addCheckpoint(new FlightCheckpoint(Position.toBlock(world.getPosition(to)))); + this.addCheckpoint(new FlightCheckpoint(world.getPosition(to).toBlockPosition())); } this.asExact = false; this.name = "Autopilot"; diff --git a/src/main/java/org/ships/movement/autopilot/scheduler/EOTExecutor.java b/src/main/java/org/ships/movement/autopilot/scheduler/EOTExecutor.java index 3b031749..21f70d43 100644 --- a/src/main/java/org/ships/movement/autopilot/scheduler/EOTExecutor.java +++ b/src/main/java/org/ships/movement/autopilot/scheduler/EOTExecutor.java @@ -6,7 +6,6 @@ import org.core.entity.LiveEntity; import org.core.schedule.Scheduler; import org.core.source.Messageable; -import org.core.source.viewer.CommandViewer; import org.core.vector.type.Vector3; import org.core.world.position.block.details.data.DirectionalData; import org.core.world.position.block.entity.LiveTileEntity; @@ -20,6 +19,7 @@ import org.ships.vessel.common.flag.EotFlag; import org.ships.vessel.common.types.Vessel; import org.ships.vessel.sign.EOTSign; +import org.ships.vessel.sign.ShipsSigns; import java.util.Optional; import java.util.function.Consumer; @@ -38,11 +38,6 @@ public EOTExecutor(@NotNull Vessel vessel, @Nullable Messageable player) { return this.vessel; } - @Deprecated(forRemoval = true) - public @NotNull Optional getPlayer() { - return getMessenger().filter(t -> t instanceof CommandViewer).map(t -> (CommandViewer) t); - } - public @NotNull Optional getMessenger() { return Optional.ofNullable(this.player); } @@ -76,10 +71,7 @@ public void accept(Scheduler scheduler) { } LiveSignTileEntity liveSignTileEntity = opLiveSignTileEntity.get(); - EOTSign signTools = ShipsPlugin - .getPlugin() - .get(EOTSign.class) - .orElseThrow(() -> new RuntimeException("EOT sign could not be found")); + EOTSign signTools = ShipsSigns.EOT; if (!signTools.isSign(liveSignTileEntity)) { scheduler.cancel(); return; diff --git a/src/main/java/org/ships/movement/autopilot/scheduler/FallExecutor.java b/src/main/java/org/ships/movement/autopilot/scheduler/FallExecutor.java index c5881a62..fbcac06c 100644 --- a/src/main/java/org/ships/movement/autopilot/scheduler/FallExecutor.java +++ b/src/main/java/org/ships/movement/autopilot/scheduler/FallExecutor.java @@ -9,7 +9,7 @@ import org.core.utils.time.TimeRange; import org.jetbrains.annotations.NotNull; import org.ships.config.configuration.ShipsConfig; -import org.ships.config.messages.AdventureMessageConfig; +import org.ships.config.messages.Messages; import org.ships.exceptions.move.MoveException; import org.ships.movement.MovementContext; import org.ships.movement.instruction.details.MovementDetailsBuilder; @@ -70,20 +70,20 @@ public void accept(Scheduler scheduler) { builder.setPostMovementEvents(vessel -> vessel.set(new CooldownFlag( new TimeRange(config.getFallingDelayUnit().toTicks(config.getFallingDelay()))))); BiConsumer exception = (context, exc) -> { - context.getAdventureBossBar().ifPresent(bar -> { - BarUtils.getPlayers(bar).forEach(user -> user.hideBossBar(bar)); - }); - v.getEntities().forEach(e -> e.setGravity(true)); + context + .getAdventureBossBar() + .ifPresent(bar -> BarUtils.getPlayers(bar).forEach(user -> user.hideBossBar(bar))); + v.getLiveEntities(t -> true).forEach(e -> e.setGravity(true)); if (!(exc instanceof MoveException)) { return; } - MoveException e = (MoveException)exc; + MoveException e = (MoveException) exc; context .getAdventureBossBar() .ifPresent(bar -> BarUtils.getPlayers(bar).forEach(user -> user.hideBossBar(bar))); - if (!e.getDisplayMessage().equals(AdventureMessageConfig.ERROR_COLLIDE_DETECTED)) { + if (!e.getDisplayMessage().equals(Messages.ERROR_COLLIDE_DETECTED)) { return; } if (v instanceof FileBasedVessel) { diff --git a/src/main/java/org/ships/movement/instruction/MovementInstructionBuilder.java b/src/main/java/org/ships/movement/instruction/MovementInstructionBuilder.java index 93255b8e..4dbbb11f 100644 --- a/src/main/java/org/ships/movement/instruction/MovementInstructionBuilder.java +++ b/src/main/java/org/ships/movement/instruction/MovementInstructionBuilder.java @@ -2,7 +2,6 @@ import org.core.vector.type.Vector3; import org.core.world.position.impl.BlockPosition; -import org.core.world.position.impl.Position; import org.core.world.position.impl.sync.SyncBlockPosition; import org.jetbrains.annotations.NotNull; import org.ships.algorthum.movement.BasicMovement; @@ -14,6 +13,7 @@ import org.ships.plugin.ShipsPlugin; import org.ships.vessel.structure.PositionableShipsStructure; +import java.util.Comparator; import java.util.function.Function; import java.util.stream.Collectors; @@ -37,7 +37,7 @@ public MovementInstructionBuilder setMovingBlocks(MovingBlockSet movingBlocks) { public MovementInstructionBuilder setTeleportToMovementBlocks(PositionableShipsStructure structure, BlockPosition position) { - SyncBlockPosition syncedBlock = Position.toSync(position); + SyncBlockPosition syncedBlock = position.toSyncPosition(); return this.setMovementBlocks(structure, block -> { Vector3 relative = block.getPosition().minus(structure.getPosition().getPosition()); SyncBlockPosition newType = syncedBlock.getRelative(relative); @@ -78,10 +78,10 @@ public MovementInstructionBuilder setRotateRightAroundPosition(PositionableShips public MovementInstructionBuilder setMovementBlocks(PositionableShipsStructure structure, Function function) { this.movingBlocks = structure - .getSyncedPositionsRelativeToWorld() - .stream() + .getPositionsRelativeToWorld() .map(function) .collect(Collectors.toCollection(MovingBlockSet::new)); + return this; } diff --git a/src/main/java/org/ships/movement/instruction/details/MovementDetails.java b/src/main/java/org/ships/movement/instruction/details/MovementDetails.java index 574999b5..2586b9de 100644 --- a/src/main/java/org/ships/movement/instruction/details/MovementDetails.java +++ b/src/main/java/org/ships/movement/instruction/details/MovementDetails.java @@ -2,7 +2,6 @@ import net.kyori.adventure.bossbar.BossBar; import org.core.TranslateCore; -import org.core.world.boss.ServerBossBar; import org.core.world.position.impl.BlockPosition; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -48,11 +47,6 @@ public Optional getClickedBlock() { return Optional.ofNullable(this.clickedBlock); } - @Deprecated(forRemoval = true) - public Optional getBossBar() { - return getAdventureBossBar().map(TranslateCore::createBossBar); - } - public Optional getAdventureBossBar() { return Optional.ofNullable(this.bossBar); } diff --git a/src/main/java/org/ships/movement/instruction/details/MovementDetailsBuilder.java b/src/main/java/org/ships/movement/instruction/details/MovementDetailsBuilder.java index dc918111..35d75116 100644 --- a/src/main/java/org/ships/movement/instruction/details/MovementDetailsBuilder.java +++ b/src/main/java/org/ships/movement/instruction/details/MovementDetailsBuilder.java @@ -2,7 +2,6 @@ import net.kyori.adventure.bossbar.BossBar; import org.core.TranslateCore; -import org.core.world.boss.ServerBossBar; import org.core.world.position.impl.BlockPosition; import org.jetbrains.annotations.NotNull; import org.ships.movement.MovementContext; @@ -48,16 +47,6 @@ public MovementDetailsBuilder setClickedBlock(BlockPosition clickedBlock) { return this; } - @Deprecated(forRemoval = true) - public ServerBossBar getBossBar() { - return TranslateCore.createBossBar(getAdventureBossBar()); - } - - @Deprecated(forRemoval = true) - public MovementDetailsBuilder setBossBar(ServerBossBar bossBar) { - return setAdventureBossBar(bossBar.bossBar()); - } - public BossBar getAdventureBossBar() { return this.bossBar; } diff --git a/src/main/java/org/ships/movement/instruction/details/SimpleMovementException.java b/src/main/java/org/ships/movement/instruction/details/SimpleMovementException.java index d6fa9198..d4e7b009 100644 --- a/src/main/java/org/ships/movement/instruction/details/SimpleMovementException.java +++ b/src/main/java/org/ships/movement/instruction/details/SimpleMovementException.java @@ -1,8 +1,8 @@ package org.ships.movement.instruction.details; import org.core.entity.LiveEntity; +import org.core.entity.living.human.player.LivePlayer; import org.core.source.Messageable; -import org.core.world.boss.ServerBossBar; import org.ships.exceptions.move.MoveException; import org.ships.movement.MovementContext; @@ -34,12 +34,18 @@ public void accept(MovementContext context, Throwable throwable) { .map(snapshot -> snapshot.getCreatedFrom().get()) .collect(Collectors.toSet()); entities.forEach(entity -> entity.setGravity(true)); - context.getBossBar().ifPresent(ServerBossBar::deregisterPlayers); + context.getAdventureBossBar().ifPresent(bossBar -> { + entities + .stream() + .filter(entity -> entity instanceof LivePlayer) + .map(entity -> (LivePlayer) entity) + .forEach(player -> player.hideBossBar(bossBar)); + }); if (!(throwable instanceof MoveException)) { throwable.printStackTrace(); return; } MoveException e = (MoveException) throwable; - this.messageReceivers.forEach(viewer -> viewer.sendMessage(e.getErrorMessageText())); + this.messageReceivers.forEach(viewer -> viewer.sendMessage(e.getErrorMessage())); } } diff --git a/src/main/java/org/ships/permissions/vessel/CrewPermission.java b/src/main/java/org/ships/permissions/vessel/CrewPermission.java index 8b5a4055..bdd6bc3a 100644 --- a/src/main/java/org/ships/permissions/vessel/CrewPermission.java +++ b/src/main/java/org/ships/permissions/vessel/CrewPermission.java @@ -4,18 +4,9 @@ public interface CrewPermission extends Identifiable { - CrewPermission CAPTAIN = new AbstractCrewPermission("ships.captain", "Captain") - .setCanMove(true) - .setCommand(true) - .setRemove(true); - CrewPermission CREW_MEMBER = new AbstractCrewPermission("ships.member", "Crew") - .setCanMove(true) - .setCommand(false) - .setRemove(false); - CrewPermission DEFAULT = new AbstractCrewPermission("ships.default", "Default") - .setCanMove(false) - .setCommand(false) - .setRemove(false); + CrewPermission CAPTAIN = CrewPermissions.CAPTAIN; + CrewPermission CREW_MEMBER = CrewPermissions.CREW_MEMBER; + CrewPermission DEFAULT = CrewPermissions.DEFAULT; boolean canMove(); diff --git a/src/main/java/org/ships/permissions/vessel/CrewPermissions.java b/src/main/java/org/ships/permissions/vessel/CrewPermissions.java new file mode 100644 index 00000000..12a0a511 --- /dev/null +++ b/src/main/java/org/ships/permissions/vessel/CrewPermissions.java @@ -0,0 +1,37 @@ +package org.ships.permissions.vessel; + +import org.jetbrains.annotations.UnmodifiableView; + +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.LinkedTransferQueue; + +public final class CrewPermissions { + + private static final Collection registered = new LinkedTransferQueue<>(); + + public static final CrewPermission CAPTAIN = register( + new AbstractCrewPermission("ships.captain", "Captain").setCanMove(true).setCommand(true).setRemove(true)); + + public static final CrewPermission CREW_MEMBER = register( + new AbstractCrewPermission("ships.member", "Crew").setCanMove(true).setCommand(false).setRemove(false)); + + public static final CrewPermission DEFAULT = register(new AbstractCrewPermission("ships.default", "Default") + .setCanMove(false) + .setCommand(false) + .setRemove(false)); + + private CrewPermissions() { + } + + public static CrewPermission register(CrewPermission permission) { + registered.add(permission); + return permission; + } + + @UnmodifiableView + public static Collection permissions() { + return Collections.unmodifiableCollection(registered); + } + +} diff --git a/src/main/java/org/ships/plugin/ShipsPlugin.java b/src/main/java/org/ships/plugin/ShipsPlugin.java index 1a4ea37f..6ea308a9 100644 --- a/src/main/java/org/ships/plugin/ShipsPlugin.java +++ b/src/main/java/org/ships/plugin/ShipsPlugin.java @@ -4,7 +4,6 @@ import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextColor; -import net.kyori.adventure.util.RGBLike; import org.core.TranslateCore; import org.core.command.CommandRegister; import org.core.logger.Logger; @@ -17,11 +16,8 @@ import org.core.platform.update.result.SuccessfulResult; import org.core.schedule.Scheduler; import org.core.source.command.ConsoleSource; -import org.core.utils.Identifiable; import org.core.world.structure.StructureFileBuilder; import org.jetbrains.annotations.NotNull; -import org.ships.algorthum.blockfinder.BasicBlockFinder; -import org.ships.algorthum.movement.BasicMovement; import org.ships.commands.argument.ShipsArgumentCommand; import org.ships.config.blocks.DefaultBlockList; import org.ships.config.configuration.LegacyShipsConfig; @@ -30,21 +26,19 @@ import org.ships.config.messages.AdventureMessageConfig; import org.ships.event.listener.CoreEventListener; import org.ships.exceptions.load.FileLoadVesselException; -import org.ships.movement.BlockPriority; import org.ships.movement.PreventMovementManager; import org.ships.movement.autopilot.path.FlightPathManager; import org.ships.movement.autopilot.scheduler.FallExecutor; -import org.ships.permissions.vessel.CrewPermission; import org.ships.vessel.common.assits.shiptype.CloneableShipType; import org.ships.vessel.common.flag.PlayerStatesFlag; -import org.ships.vessel.common.flag.VesselFlag; +import org.ships.vessel.common.flag.VesselFlags; import org.ships.vessel.common.loader.shipsvessel.ShipsFileLoader; import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import org.ships.vessel.common.types.Vessel; import org.ships.vessel.common.types.typical.AbstractShipType; +import org.ships.vessel.converts.ShipsConverters; import org.ships.vessel.converts.vessel.VesselConverter; -import org.ships.vessel.converts.vessel.shipsfive.Ships5VesselConverter; -import org.ships.vessel.sign.*; import org.ships.vessel.sign.lock.LockedSignManager; import java.io.File; @@ -55,11 +49,9 @@ public class ShipsPlugin implements CorePlugin { - public static final double PRERELEASE_VERSION = 16.4; + public static final double PRERELEASE_VERSION = 17; public static final String PRERELEASE_TAG = "Beta"; private static ShipsPlugin plugin; - private final Map> vesselFlags = new HashMap<>(); - private final Collection identifiables = new HashSet<>(); private final LockedSignManager lockedSignManager = new LockedSignManager(); private final Collection vessels = new LinkedHashSet<>(); private final FlightPathManager flightPaths = new FlightPathManager(); @@ -74,7 +66,6 @@ public class ShipsPlugin implements CorePlugin { public ShipsPlugin() { plugin = this; - TranslateCore.getPlatform().setDeveloperCommandsEnabled(true); } public @NotNull LockedSignManager getLockedSignManager() { @@ -128,7 +119,7 @@ public AdventureMessageConfig getAdventureMessageConfig() { } public void initShipType() { - for (ShipType type : this.getAllShipTypes()) { + for (ShipType type : ShipTypes.shipTypes()) { if (!(type instanceof AbstractShipType)) { continue; } @@ -138,17 +129,17 @@ public void initShipType() { public void loadCustomShipType() { File folder = new File(this.getConfigFolder(), "Configuration/ShipType/Custom"); - for (CloneableShipType type : this.getAllCloneableShipTypes()) { + for (CloneableShipType type : ShipTypes.cloneableShipTypes().collect(Collectors.toList())) { File folderType = new File(folder, type.getId().replace(":", ".") + "/"); File[] files = folderType.listFiles(); if (files == null) { if (!folderType.exists() && !folderType.mkdirs()) { - System.err.println("Could not create folder at '" + folderType.getPath() + "'"); + this.logger.error("Could not create folder at '" + folderType.getPath() + "'"); } continue; } for (File file : files) { - this.identifiables.add(type.cloneWithName(file)); + ShipTypes.registerType(type.cloneWithName(file)); } } } @@ -165,7 +156,7 @@ public void loadVessels() { } public void loadConverts() { - this.getAll(VesselConverter.class).forEach(c -> { + ShipsConverters.converters().forEach(c -> { File folder = c.getFolder(); File[] files = folder.listFiles(); if (files == null) { @@ -175,7 +166,7 @@ public void loadConverts() { try { this.registerVessel(c.convert(f)); } catch (IOException e) { - System.err.println("Error converting vessel with " + c.getId() + " at: " + f.getPath()); + this.logger.error("Error converting vessel with " + c.getId() + " at: " + f.getPath()); e.printStackTrace(); } }); @@ -183,35 +174,7 @@ public void loadConverts() { } private void init() { - this.identifiables.add(BasicMovement.SHIPS_FIVE); - this.identifiables.add(BasicMovement.SHIPS_SIX); - - this.identifiables.add(BasicBlockFinder.SHIPS_FIVE); - this.identifiables.add(BasicBlockFinder.SHIPS_FIVE_ASYNC); - this.identifiables.add(BasicBlockFinder.SHIPS_SIX); - this.identifiables.add(BasicBlockFinder.SHIPS_SIX_RELEASE_ONE_MULTI_ASYNC); - this.identifiables.add(BasicBlockFinder.SHIPS_SIX_RELEASE_ONE_SINGLE_ASYNC); - this.identifiables.add(BlockPriority.AIR); - this.identifiables.add(BlockPriority.DIRECTIONAL); - this.identifiables.add(BlockPriority.ATTACHED); - this.identifiables.add(BlockPriority.NORMAL); - this.identifiables.add(new Ships5VesselConverter()); - this.identifiables.add(new LicenceSign()); - this.identifiables.add(new AltitudeSign()); - this.identifiables.add(new WheelSign()); - this.identifiables.add(new MoveSign()); - this.identifiables.add(new EOTSign()); - this.register(CrewPermission.CAPTAIN, CrewPermission.CREW_MEMBER, CrewPermission.DEFAULT); - this.vesselFlags.put("ships:player_states", new PlayerStatesFlag.Builder()); - } - - private void init2() { - this.identifiables.add(ShipType.OVERPOWERED_SHIP); - this.identifiables.add(ShipType.AIRSHIP); - this.identifiables.add(ShipType.WATERSHIP); - this.identifiables.add(ShipType.SUBMARINE); - this.identifiables.add(ShipType.MARSSHIP); - this.identifiables.add(ShipType.PLANE); + VesselFlags.registerBuilder("ships:player_states", new PlayerStatesFlag.Builder()); } public ShipsConfig getConfig() { @@ -235,10 +198,15 @@ public void getLoadedMessages() { } public void loadVesselTypeFlagData() { - this.getAll(AbstractShipType.class).forEach(vt -> { - vt.initFlags(); - vt.save(); - }); + ShipTypes + .shipTypes() + .stream() + .filter(t -> t instanceof AbstractShipType) + .map(t -> (AbstractShipType) t) + .forEach(vt -> { + vt.initFlags(); + vt.save(); + }); } public DebugFile getDebugFile() { @@ -253,30 +221,6 @@ public Collection getVessels() { return this.vessels; } - public Collection getAll(Class class1) { - return this.identifiables - .parallelStream() - .filter(class1::isInstance) - .map(t -> (T) t) - .collect(Collectors.toSet()); - } - - public Collection> getAllShipTypes() { - return (Collection>) (Object) this.getAll(ShipType.class); - } - - public @NotNull Collection> getAllCloneableShipTypes() { - return (Collection>) (Object) this.getAll(CloneableShipType.class); - } - - public Optional get(@NotNull Class class1) { - return this.identifiables.stream().filter(class1::isInstance).map(t -> (T) t).findAny(); - } - - public @NotNull Map> getVesselFlags() { - return this.vesselFlags; - } - public void registerVessel(@NotNull Vessel vessel) { this.vessels.add(vessel); } @@ -285,28 +229,6 @@ public void unregisterVessel(@NotNull Vessel vessel) { this.vessels.remove(vessel); } - @Deprecated - public void register() { - throw new RuntimeException("Must specify a Identifiable to register"); - } - - public void register(Identifiable... identifiables) { - this.identifiables.addAll(Arrays.asList(identifiables)); - } - - @Deprecated - public void unregister() { - throw new RuntimeException("Must specify an Identifiable to unregister"); - } - - public void unregister(Identifiable... identifiables) { - Arrays.asList(identifiables).forEach(this.identifiables::remove); - } - - public void register(@NotNull String id, @NotNull VesselFlag.Builder flag) { - this.vesselFlags.put(id, flag); - } - @Override public @NotNull String getPluginName() { return "Ships"; @@ -330,7 +252,6 @@ public void onCoreReady() { Scheduler fallScheduler = FallExecutor.createScheduler(); fallScheduler.run(); } - this.init2(); } @Override @@ -364,7 +285,7 @@ public void onCoreFinishedInit() { if (fullVersionName.equals(currentVersionName)) { return; } - var console = TranslateCore.getConsole(); + ConsoleSource console = TranslateCore.getConsole(); console.sendMessage(Component .text("An update can be downloaded for Ships") .color(NamedTextColor.GREEN)); @@ -427,7 +348,7 @@ public void onRegisterCommands(@NotNull CommandRegister register) { @Override public void onShutdown() { - shutdown = true; + this.shutdown = true; } public @NotNull Logger getLogger() { diff --git a/src/main/java/org/ships/vessel/common/assits/UnderWaterType.java b/src/main/java/org/ships/vessel/common/assits/UnderWaterType.java index e61eae51..6f69ae23 100644 --- a/src/main/java/org/ships/vessel/common/assits/UnderWaterType.java +++ b/src/main/java/org/ships/vessel/common/assits/UnderWaterType.java @@ -9,6 +9,7 @@ import java.util.Collection; import java.util.HashSet; +import java.util.stream.Collectors; public interface UnderWaterType extends WaterType { @@ -17,7 +18,7 @@ default boolean isSubmerged() { Direction[] directions = FourFacingDirection.getFourFacingDirections(); int height = pss.getYSize(); Collection values = new HashSet<>(); - for (SyncBlockPosition position : pss.getSyncedPositionsRelativeToWorld()) { + for (SyncBlockPosition position : pss.getPositionsRelativeToWorld().collect(Collectors.toList())) { if (values.contains(position.getY())) { continue; } diff --git a/src/main/java/org/ships/vessel/common/finder/IdVesselFinder.java b/src/main/java/org/ships/vessel/common/finder/IdVesselFinder.java index d6e3edbd..9a0c380f 100644 --- a/src/main/java/org/ships/vessel/common/finder/IdVesselFinder.java +++ b/src/main/java/org/ships/vessel/common/finder/IdVesselFinder.java @@ -5,7 +5,11 @@ import org.ships.vessel.common.assits.IdentifiableShip; import org.ships.vessel.common.types.Vessel; -public class IdVesselFinder { +public final class IdVesselFinder { + + private IdVesselFinder() { + throw new RuntimeException("Do not create"); + } public static Vessel load(String id) throws LoadVesselException { return ShipsPlugin.getPlugin().getVessels().stream().filter(v -> v instanceof IdentifiableShip).filter(v -> { diff --git a/src/main/java/org/ships/vessel/common/finder/ShipsSignVesselFinder.java b/src/main/java/org/ships/vessel/common/finder/ShipsSignVesselFinder.java index 9fe19052..5a666883 100644 --- a/src/main/java/org/ships/vessel/common/finder/ShipsSignVesselFinder.java +++ b/src/main/java/org/ships/vessel/common/finder/ShipsSignVesselFinder.java @@ -6,8 +6,10 @@ import org.ships.exceptions.load.LoadVesselException; import org.ships.plugin.ShipsPlugin; import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import org.ships.vessel.common.types.Vessel; import org.ships.vessel.sign.LicenceSign; +import org.ships.vessel.sign.ShipsSigns; import java.util.Optional; @@ -18,10 +20,7 @@ private ShipsSignVesselFinder() { } public static Vessel find(SignTileEntity signTileEntity) throws LoadVesselException { - LicenceSign ls = ShipsPlugin - .getPlugin() - .get(LicenceSign.class) - .orElseThrow(() -> new RuntimeException("Could not find licence sign. is it registered?")); + LicenceSign ls = ShipsSigns.LICENCE; if (!ls.isSign(signTileEntity)) { throw new LoadVesselException("Unable to read sign"); @@ -34,9 +33,8 @@ public static Vessel find(SignTileEntity signTileEntity) throws LoadVesselExcept String typeS = ComponentUtils.toPlain( signSide.getLineAt(1).orElseThrow(() -> new RuntimeException("Could not read line 2"))); - Optional> opType = ShipsPlugin - .getPlugin() - .getAllShipTypes() + Optional> opType = ShipTypes + .shipTypes() .stream() .filter(st -> st.getDisplayName().equalsIgnoreCase(typeS)) .findAny(); diff --git a/src/main/java/org/ships/vessel/common/finder/VesselBlockFinder.java b/src/main/java/org/ships/vessel/common/finder/VesselBlockFinder.java index 051103c3..47d4db13 100644 --- a/src/main/java/org/ships/vessel/common/finder/VesselBlockFinder.java +++ b/src/main/java/org/ships/vessel/common/finder/VesselBlockFinder.java @@ -36,10 +36,7 @@ private static Optional findCachedVessel(@NotNull Position posi .filter(v -> v.getStructure().getBounds().contains(position.getPosition())) .filter(v -> { PositionableShipsStructure pss = v.getStructure(); - Collection collection = pss.getAsyncedPositionsRelativeToWorld(); - return collection - .parallelStream() - .map(Position::getPosition) + return pss.getVectorsRelativeToWorld() .anyMatch(p -> p.equals(position.getPosition())); }) .findAny(); @@ -50,7 +47,7 @@ public static CompletableFuture>> findOvertime(BlockPosition position, - BiConsumer consumer) { + BiConsumer> consumer) { Optional opVessel = findCachedVessel(position); if (opVessel.isPresent()) { Map.Entry<@NotNull PositionableShipsStructure, Optional> ret = Map.entry( @@ -69,9 +66,8 @@ public static CompletableFuture { - consumer.accept(currentStructure, block); - Vector3 pos = block.getPosition(); + .getConnectedBlocksOvertime(position, (currentStructure, pos) -> { + consumer.accept(currentStructure, pos); Vessel vessel = map.get(pos); if (vessel == null) { return OvertimeBlockFinderUpdate.BlockFindControl.USE; diff --git a/src/main/java/org/ships/vessel/common/flag/AltitudeLockFlag.java b/src/main/java/org/ships/vessel/common/flag/AltitudeLockFlag.java index 006625cb..41bda5b6 100644 --- a/src/main/java/org/ships/vessel/common/flag/AltitudeLockFlag.java +++ b/src/main/java/org/ships/vessel/common/flag/AltitudeLockFlag.java @@ -47,6 +47,11 @@ public String getName() { return "Altitude Lock"; } + @Override + public VesselFlag clone() { + return VesselFlag.super.clone(); + } + public static class Builder extends VesselFlag.Builder { @Override diff --git a/src/main/java/org/ships/vessel/common/flag/CooldownFlag.java b/src/main/java/org/ships/vessel/common/flag/CooldownFlag.java index 4f48e704..fc74970d 100644 --- a/src/main/java/org/ships/vessel/common/flag/CooldownFlag.java +++ b/src/main/java/org/ships/vessel/common/flag/CooldownFlag.java @@ -48,6 +48,11 @@ public Builder toBuilder() { return new Builder(); } + @Override + public CooldownFlag clone() { + return (CooldownFlag) VesselFlag.super.clone(); + } + public static class Builder extends VesselFlag.Builder { @Override diff --git a/src/main/java/org/ships/vessel/common/flag/EotFlag.java b/src/main/java/org/ships/vessel/common/flag/EotFlag.java index d673a36c..3b26841f 100644 --- a/src/main/java/org/ships/vessel/common/flag/EotFlag.java +++ b/src/main/java/org/ships/vessel/common/flag/EotFlag.java @@ -55,6 +55,11 @@ public String getName() { return "E.O.T"; } + @Override + public EotFlag clone() { + return (EotFlag) VesselFlag.super.clone(); + } + public static class Builder extends VesselFlag.Builder, EotFlag> { @Override diff --git a/src/main/java/org/ships/vessel/common/flag/FlightPathFlag.java b/src/main/java/org/ships/vessel/common/flag/FlightPathFlag.java index 2bf5ff90..7e603319 100644 --- a/src/main/java/org/ships/vessel/common/flag/FlightPathFlag.java +++ b/src/main/java/org/ships/vessel/common/flag/FlightPathFlag.java @@ -66,4 +66,9 @@ public String getId() { public String getName() { return "Flight Path"; } + + @Override + public FlightPathFlag clone() { + return (FlightPathFlag) VesselFlag.super.clone(); + } } diff --git a/src/main/java/org/ships/vessel/common/flag/MovingFlag.java b/src/main/java/org/ships/vessel/common/flag/MovingFlag.java index 713454d4..e9a00c99 100644 --- a/src/main/java/org/ships/vessel/common/flag/MovingFlag.java +++ b/src/main/java/org/ships/vessel/common/flag/MovingFlag.java @@ -64,4 +64,9 @@ public String getId() { public String getName() { return "Is Moving"; } + + @Override + public MovingFlag clone() { + return (MovingFlag) VesselFlag.super.clone(); + } } diff --git a/src/main/java/org/ships/vessel/common/flag/PlayerStatesFlag.java b/src/main/java/org/ships/vessel/common/flag/PlayerStatesFlag.java index ca341038..5ceed79e 100644 --- a/src/main/java/org/ships/vessel/common/flag/PlayerStatesFlag.java +++ b/src/main/java/org/ships/vessel/common/flag/PlayerStatesFlag.java @@ -13,6 +13,14 @@ public class PlayerStatesFlag implements VesselFlag.Serializable>> { + public static class Builder extends VesselFlag.Builder>, PlayerStatesFlag> { + + @Override + protected PlayerStatesFlag buildEmpty() { + return new PlayerStatesFlag(); + } + } + private Map> playerStates = new HashMap<>(); @Override @@ -25,6 +33,7 @@ public String getName() { return "Player States"; } + @SuppressWarnings("OptionalContainsCollection") @Override public Optional>> getValue() { return Optional.of(this.playerStates); @@ -39,6 +48,7 @@ public void setValue(Map> value) { public StringParser>> getParser() { return new StringParser<>() { + @SuppressWarnings("OptionalContainsCollection") @Override public Optional>> parse(String original) { Map> map = new HashMap<>(); @@ -94,15 +104,16 @@ public Serializable>> deserialize(String idWithValue) @Override public boolean isDeserializable(String idWithValue) { - Optional>> opMap = this.getParser().parse(idWithValue); + @SuppressWarnings("OptionalContainsCollection") Optional>> opMap = this + .getParser() + .parse(idWithValue); return opMap.filter(uuidVector3Map -> !uuidVector3Map.isEmpty()).isPresent(); } - public static class Builder extends VesselFlag.Builder>, PlayerStatesFlag> { - - @Override - protected PlayerStatesFlag buildEmpty() { - return new PlayerStatesFlag(); - } + @Override + public PlayerStatesFlag clone() { + PlayerStatesFlag flag = new PlayerStatesFlag(); + flag.setValue(new HashMap<>(this.playerStates)); + return flag; } } diff --git a/src/main/java/org/ships/vessel/common/flag/SuccessfulMoveFlag.java b/src/main/java/org/ships/vessel/common/flag/SuccessfulMoveFlag.java index 6f053a0a..56077fd3 100644 --- a/src/main/java/org/ships/vessel/common/flag/SuccessfulMoveFlag.java +++ b/src/main/java/org/ships/vessel/common/flag/SuccessfulMoveFlag.java @@ -39,6 +39,11 @@ public String getName() { return "Has successfully moved"; } + @Override + public SuccessfulMoveFlag clone() { + return (SuccessfulMoveFlag) VesselFlag.super.clone(); + } + public static class Builder extends VesselFlag.Builder { @Override diff --git a/src/main/java/org/ships/vessel/common/flag/VesselFlag.java b/src/main/java/org/ships/vessel/common/flag/VesselFlag.java index b6324e0b..5c36d59c 100644 --- a/src/main/java/org/ships/vessel/common/flag/VesselFlag.java +++ b/src/main/java/org/ships/vessel/common/flag/VesselFlag.java @@ -5,7 +5,7 @@ import java.util.Optional; -public interface VesselFlag extends Identifiable { +public interface VesselFlag extends Identifiable, Cloneable { abstract class Builder> { @@ -41,4 +41,12 @@ interface Serializable extends VesselFlag { StringParser getParser(); VesselFlag.Builder> toBuilder(); + + default VesselFlag clone() { + Optional opValueString = this.getValue().map(value -> this.getParser().unparse(value)); + if (opValueString.isEmpty()) { + return this.toBuilder().buildEmpty(); + } + return this.toBuilder().build(opValueString.get()); + } } diff --git a/src/main/java/org/ships/vessel/common/flag/VesselFlags.java b/src/main/java/org/ships/vessel/common/flag/VesselFlags.java new file mode 100644 index 00000000..f3e10663 --- /dev/null +++ b/src/main/java/org/ships/vessel/common/flag/VesselFlags.java @@ -0,0 +1,50 @@ +package org.ships.vessel.common.flag; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.UnmodifiableView; + +import java.util.*; +import java.util.concurrent.LinkedTransferQueue; + +public final class VesselFlags { + + private static final Map> flagsBuilders = new HashMap<>(); + private static final Collection> flags = new LinkedTransferQueue<>(); + + public static final AltitudeLockFlag ALTITUDE_LOCK = registerDefault(new AltitudeLockFlag()); + public static final CooldownFlag COOLDOWN = registerDefault(new CooldownFlag()); + public static final EotFlag EOT = registerDefault(new EotFlag.Builder().buildEmpty()); + public static final FlightPathFlag FLIGHT_PATH = registerDefault(new FlightPathFlag()); + public static final MovingFlag MOVING = registerDefault(new MovingFlag()); + public static final SuccessfulMoveFlag SUCCESSFUL_MOVE = registerDefault(new SuccessfulMoveFlag()); + + private VesselFlags() { + throw new RuntimeException("Do not create"); + } + + public static > Optional getDefault(Class clazz) { + return flags.stream().filter(clazz::isInstance).findFirst().map(flag -> (F) flag); + } + + public static > @NotNull F registerDefault(F flag) { + if (getDefault(flag.getClass()).isPresent()) { + throw new IllegalArgumentException("Flag already has a default"); + } + flags.add(flag); + return flag; + } + + public static > @NotNull B registerBuilder(String id, @NotNull B flag) { + if (flagsBuilders.containsKey(id)) { + throw new IllegalArgumentException("Id of '" + id + "' is already registered"); + } + flagsBuilders.put(id, flag); + return flag; + } + + @UnmodifiableView + public static Map> builders() { + return Collections.unmodifiableMap(flagsBuilders); + } + +} diff --git a/src/main/java/org/ships/vessel/common/loader/ShipsBlockFinder.java b/src/main/java/org/ships/vessel/common/loader/ShipsBlockFinder.java index c8748b6f..02a00a59 100644 --- a/src/main/java/org/ships/vessel/common/loader/ShipsBlockFinder.java +++ b/src/main/java/org/ships/vessel/common/loader/ShipsBlockFinder.java @@ -23,8 +23,7 @@ public ShipsBlockFinder(BlockPosition position) { public Vessel load() throws LoadVesselException { Optional opVessel = ShipsPlugin.getPlugin().getVessels().stream().filter(v -> { PositionableShipsStructure pss = v.getStructure(); - Collection collection = pss.getAsyncedPositionsRelativeToWorld(); - return collection.stream().anyMatch(p -> p.getPosition().equals(this.position.getPosition())); + return pss.getVectorsRelativeToWorld().anyMatch(p -> p.equals(this.position.getPosition())); }).findAny(); if (opVessel.isPresent()) { return opVessel.get(); diff --git a/src/main/java/org/ships/vessel/common/loader/ShipsLicenceSignFinder.java b/src/main/java/org/ships/vessel/common/loader/ShipsLicenceSignFinder.java index 0cb7bac8..7aaeb03b 100644 --- a/src/main/java/org/ships/vessel/common/loader/ShipsLicenceSignFinder.java +++ b/src/main/java/org/ships/vessel/common/loader/ShipsLicenceSignFinder.java @@ -1,15 +1,19 @@ package org.ships.vessel.common.loader; +import org.core.utils.ComponentUtils; import org.core.world.position.block.entity.LiveTileEntity; import org.core.world.position.block.entity.sign.LiveSignTileEntity; +import org.core.world.position.block.entity.sign.SignSide; import org.core.world.position.block.entity.sign.SignTileEntity; import org.core.world.position.impl.sync.SyncPosition; import org.ships.exceptions.load.LoadVesselException; import org.ships.plugin.ShipsPlugin; import org.ships.vessel.common.finder.IdVesselFinder; import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import org.ships.vessel.common.types.Vessel; import org.ships.vessel.sign.LicenceSign; +import org.ships.vessel.sign.ShipsSigns; import java.io.IOException; import java.util.Optional; @@ -36,24 +40,24 @@ public ShipsLicenceSignFinder(SignTileEntity ste) { @Override public Vessel load() throws LoadVesselException { - LicenceSign ls = ShipsPlugin - .getPlugin() - .get(LicenceSign.class) - .orElseThrow(() -> new RuntimeException("Could not find licence sign. is it registered?")); + LicenceSign ls = ShipsSigns.LICENCE; if (!ls.isSign(this.ste)) { throw new LoadVesselException("Unable to read sign"); } - String typeS = this.ste.getTextAt(1).orElseThrow(() -> new RuntimeException("You broke logic")).toPlain(); - Optional> opType = ShipsPlugin - .getPlugin() - .getAllShipTypes() + SignSide side = ls.getSide(this.ste).orElseThrow(() -> new RuntimeException("You broke logic")); + String typeS = side + .getLineAt(1) + .map(ComponentUtils::toPlain) + .orElseThrow(() -> new RuntimeException("You broke logic")); + Optional> opType = ShipTypes + .shipTypes() .stream() .filter(st -> st.getDisplayName().equalsIgnoreCase(typeS)) .findAny(); if (opType.isEmpty()) { throw new LoadVesselException("Unable to find shiptype of " + typeS); } - String name = this.ste.getTextAt(2).get().toPlain().toLowerCase(); + String name = side.getLineAt(2).map(ComponentUtils::toPlain).orElseThrow().toLowerCase(); String id = "ships:" + opType.get().getName().toLowerCase() + "." + name; return IdVesselFinder.load(id); } diff --git a/src/main/java/org/ships/vessel/common/loader/ShipsOvertimeBlockFinder.java b/src/main/java/org/ships/vessel/common/loader/ShipsOvertimeBlockFinder.java index 3b958ebf..9d1676ca 100644 --- a/src/main/java/org/ships/vessel/common/loader/ShipsOvertimeBlockFinder.java +++ b/src/main/java/org/ships/vessel/common/loader/ShipsOvertimeBlockFinder.java @@ -69,7 +69,7 @@ public CompletableFuture loadOvertime(Consumer future = new CompletableFuture<>(); ShipsPlugin.getPlugin().getVessels().forEach(v -> { PositionableShipsStructure pss = v.getStructure(); - Collection collection = pss.getAsyncedPositionsRelativeToWorld(); + List> collection = pss.getVectorsRelativeToWorld().collect(Collectors.toList()); TranslateCore .getScheduleManager() .schedule() @@ -78,7 +78,7 @@ public CompletableFuture loadOvertime(Consumer { - if (collection.parallelStream().anyMatch(p -> p.equals(this.position))) { + if (collection.parallelStream().anyMatch(p -> p.equals(this.position.getPosition()))) { future.complete(v); } }) @@ -92,7 +92,7 @@ public CompletableFuture loadOvertime(Consumer { Optional, Vessel>> opFirst = vessels .parallelStream() - .filter(e -> e.getKey().equals(block.getPosition())) + .filter(e -> e.getKey().equals(block)) .findFirst(); if (opFirst.isPresent()) { passed.setValue(opFirst.get().getValue()); @@ -110,6 +110,6 @@ public CompletableFuture loadOvertime(Consumer consumer, Consumer exceptionRunner) { - loadOvertime(exceptionRunner).thenAccept(consumer); + this.loadOvertime(exceptionRunner).thenAccept(consumer); } } diff --git a/src/main/java/org/ships/vessel/common/loader/ShipsOvertimeUpdateBlockLoader.java b/src/main/java/org/ships/vessel/common/loader/ShipsOvertimeUpdateBlockLoader.java index 09316a50..fa9cd4ab 100644 --- a/src/main/java/org/ships/vessel/common/loader/ShipsOvertimeUpdateBlockLoader.java +++ b/src/main/java/org/ships/vessel/common/loader/ShipsOvertimeUpdateBlockLoader.java @@ -1,5 +1,6 @@ package org.ships.vessel.common.loader; +import org.core.vector.type.Vector3; import org.core.world.position.block.entity.LiveTileEntity; import org.core.world.position.block.entity.sign.SignTileEntity; import org.core.world.position.impl.BlockPosition; @@ -16,6 +17,7 @@ import org.ships.vessel.common.finder.ShipsSignVesselFinder; import org.ships.vessel.common.types.Vessel; import org.ships.vessel.sign.LicenceSign; +import org.ships.vessel.sign.ShipsSigns; import org.ships.vessel.structure.AbstractPositionableShipsStructure; import org.ships.vessel.structure.PositionableShipsStructure; @@ -36,7 +38,7 @@ public ShipsOvertimeUpdateBlockLoader(@NotNull SyncBlockPosition position, boole protected abstract void onStructureUpdate(Vessel vessel); protected abstract OvertimeBlockFinderUpdate.BlockFindControl onBlockFind(PositionableShipsStructure currentStructure, - BlockPosition block); + Vector3 block); protected abstract void onExceptionThrown(LoadVesselException e); @@ -46,14 +48,9 @@ public CompletableFuture> loadOvertime() { Optional opVessel = vessels .parallelStream() .filter(vessel -> vessel.getPosition().getWorld().equals(this.original.getWorld())) - .filter(v -> { - Collection positions = v - .getStructure() - .getPositionsRelativeTo(Position.toASync(this.original)); - return positions - .parallelStream() - .anyMatch(position -> position.getPosition().equals(this.original.getPosition())); - }) + .filter(v -> v + .getStructure() + .getVectorsRelativeTo(this.original.getPosition()).anyMatch(position -> position.equals(this.original.getPosition()))) .findAny(); if (opVessel.isEmpty()) { this.onExceptionThrown( @@ -67,21 +64,16 @@ public CompletableFuture> loadOvertime() { BasicBlockFinder finder = ShipsPlugin.getPlugin().getConfig().getDefaultFinder(); - CompletableFuture> opVesselFuture = finder - .getConnectedBlocksOvertime(this.original, ShipsOvertimeUpdateBlockLoader.this::onBlockFind) + return finder + .getConnectedBlocksOvertime(this.original, this::onBlockFind) .thenApply(structure -> { - LicenceSign ls = ShipsPlugin - .getPlugin() - .get(LicenceSign.class) - .orElseThrow(() -> new IllegalStateException("Could" + " not get licence")); - Optional opBlock = structure.getAll(SignTileEntity.class).stream().filter(b -> { - SignTileEntity lste = (SignTileEntity) b - .getTileEntity() - .orElseThrow(() -> new IllegalStateException("Could not get tile entity")); - return ls.isSign(lste); - }).findAny(); + LicenceSign ls = ShipsSigns.LICENCE; + Optional opBlock = structure + .getRelativeToWorld(ls) + .findAny() + .map(LiveTileEntity::getPosition); if (opBlock.isEmpty()) { - ShipsOvertimeUpdateBlockLoader.this.onExceptionThrown( + this.onExceptionThrown( new UnableToFindLicenceSign(structure, "Failed to find licence sign")); return Optional.empty(); } @@ -97,20 +89,12 @@ public CompletableFuture> loadOvertime() { Vessel vessel = ShipsSignVesselFinder.find((SignTileEntity) tileEntity); vessel.setStructure(structure2); - ShipsOvertimeUpdateBlockLoader.this.onStructureUpdate(vessel); + this.onStructureUpdate(vessel); return Optional.of(vessel); } catch (LoadVesselException e) { - ShipsOvertimeUpdateBlockLoader.this.onExceptionThrown(e); + this.onExceptionThrown(e); return Optional.empty(); } }); - return opVesselFuture.thenCompose(opVessel -> { - if (opVessel.isPresent()) { - if (opVessel.get() instanceof WaterType) { - return opVessel.get().getStructure().fillAir().thenApply(pss -> opVessel); - } - } - return CompletableFuture.completedFuture(opVessel); - }); } } diff --git a/src/main/java/org/ships/vessel/common/loader/ShipsUpdateBlockLoader.java b/src/main/java/org/ships/vessel/common/loader/ShipsUpdateBlockLoader.java index deafb040..0182da07 100644 --- a/src/main/java/org/ships/vessel/common/loader/ShipsUpdateBlockLoader.java +++ b/src/main/java/org/ships/vessel/common/loader/ShipsUpdateBlockLoader.java @@ -1,6 +1,6 @@ package org.ships.vessel.common.loader; -import org.core.world.position.block.entity.sign.SignTileEntity; +import org.core.world.position.block.entity.sign.LiveSignTileEntity; import org.core.world.position.impl.sync.SyncBlockPosition; import org.ships.algorthum.blockfinder.OvertimeBlockFinderUpdate; import org.ships.exceptions.load.LoadVesselException; @@ -10,6 +10,7 @@ import org.ships.vessel.common.finder.ShipsSignVesselFinder; import org.ships.vessel.common.types.Vessel; import org.ships.vessel.sign.LicenceSign; +import org.ships.vessel.sign.ShipsSigns; import org.ships.vessel.structure.AbstractPositionableShipsStructure; import org.ships.vessel.structure.PositionableShipsStructure; @@ -42,40 +43,24 @@ public CompletableFuture> loadOvertime(Consumer { - if (opVessel.isPresent() && opVessel.get() instanceof WaterType) { - return opVessel.get().getStructure().fillAir().thenApply(structure -> opVessel); - } - return CompletableFuture.completedFuture(opVessel); - }); + return opVesselFuture; } @Deprecated(forRemoval = true) public void loadOvertime(Consumer consumer, Consumer ex) { - loadOvertime(ex).thenAccept(opVessel -> opVessel.ifPresent(consumer::accept)); + this.loadOvertime(ex).thenAccept(opVessel -> opVessel.ifPresent(consumer::accept)); } private Vessel load(PositionableShipsStructure blocks) throws LoadVesselException { - LicenceSign ls = ShipsPlugin - .getPlugin() - .get(LicenceSign.class) - .orElseThrow(() -> new IllegalStateException("Could not fince licence sign")); - Optional opBlock = blocks.getAll(SignTileEntity.class).stream().filter(b -> { - SignTileEntity lste = (SignTileEntity) b - .getTileEntity() - .orElseThrow(() -> new IllegalStateException("Could not get tile entity")); - return ls.isSign(lste); - }).findAny(); + LicenceSign ls = ShipsSigns.LICENCE; + Optional opBlock = blocks.getRelativeToWorld(ls).findAny(); if (opBlock.isEmpty()) { throw new UnableToFindLicenceSign(blocks, "Failed to find licence sign"); } - SyncBlockPosition block = opBlock.get(); - Vessel vessel = ShipsSignVesselFinder.find((SignTileEntity) opBlock - .get() - .getTileEntity() - .orElseThrow(() -> new IllegalStateException("Could not get tile entity"))); - PositionableShipsStructure apss = new AbstractPositionableShipsStructure(block); - blocks.getSyncedPositionsRelativeToWorld().forEach(apss::addPositionRelativeToWorld); + LiveSignTileEntity block = opBlock.get(); + Vessel vessel = ShipsSignVesselFinder.find(opBlock.get()); + PositionableShipsStructure apss = new AbstractPositionableShipsStructure(block.getPosition()); + blocks.getPositionsRelativeToWorld().forEach(apss::addPositionRelativeToWorld); vessel.setStructure(apss); return vessel; } diff --git a/src/main/java/org/ships/vessel/common/loader/shipsvessel/ShipsFileLoader.java b/src/main/java/org/ships/vessel/common/loader/shipsvessel/ShipsFileLoader.java index e8204b54..683b5274 100644 --- a/src/main/java/org/ships/vessel/common/loader/shipsvessel/ShipsFileLoader.java +++ b/src/main/java/org/ships/vessel/common/loader/shipsvessel/ShipsFileLoader.java @@ -1,18 +1,20 @@ package org.ships.vessel.common.loader.shipsvessel; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.array.utils.ArrayUtils; import org.core.TranslateCore; -import org.core.adventureText.AText; -import org.core.adventureText.format.NamedTextColours; import org.core.config.ConfigurationNode; import org.core.config.ConfigurationStream; import org.core.config.parser.Parser; import org.core.schedule.unit.TimeUnit; +import org.core.utils.ComponentUtils; import org.core.utils.Else; import org.core.vector.type.Vector3; import org.core.world.WorldExtent; import org.core.world.position.block.entity.LiveTileEntity; import org.core.world.position.block.entity.sign.LiveSignTileEntity; +import org.core.world.position.block.entity.sign.SignSide; import org.core.world.position.impl.BlockPosition; import org.core.world.position.impl.sync.SyncBlockPosition; import org.ships.config.parsers.ShipsParsers; @@ -22,15 +24,19 @@ import org.ships.exceptions.load.LoadVesselException; import org.ships.exceptions.load.WrappedFileLoadVesselException; import org.ships.permissions.vessel.CrewPermission; +import org.ships.permissions.vessel.CrewPermissions; import org.ships.plugin.ShipsPlugin; import org.ships.vessel.common.assits.TeleportToVessel; import org.ships.vessel.common.flag.VesselFlag; +import org.ships.vessel.common.flag.VesselFlags; import org.ships.vessel.common.loader.ShipsLoader; import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import org.ships.vessel.common.types.Vessel; import org.ships.vessel.common.types.typical.AbstractShipsVessel; import org.ships.vessel.common.types.typical.ShipsVessel; import org.ships.vessel.sign.LicenceSign; +import org.ships.vessel.sign.ShipsSigns; import org.ships.vessel.structure.PositionableShipsStructure; import java.io.File; @@ -65,9 +71,8 @@ public class ShipsFileLoader implements ShipsLoader { public static final ConfigurationNode.KnownParser.CollectionKnown> META_STRUCTURE = new ConfigurationNode.KnownParser.CollectionKnown<>( Parser.STRING_TO_VECTOR3INT, "Meta", "Location", "Structure"); public static final ConfigurationNode.GroupKnown> META_FLAGS = new ConfigurationNode.GroupKnown<>( - () -> ShipsPlugin - .getPlugin() - .getVesselFlags() + () -> VesselFlags + .builders() .entrySet() .stream() .collect( @@ -99,10 +104,10 @@ public CompletableFuture load(BlockPosition position Collection> structureList) { if (structureList.isEmpty()) { - return ship.updateStructure().thenApply(structure -> { + return this.ship.updateStructure().thenApply(structure -> { TranslateCore .getConsole() - .sendMessage(AText.ofPlain( + .sendMessage(Component.text( Else.throwOr(NoLicencePresent.class, StructureLoad.this.ship::getId, "Unknown") + " has loaded.")); return structure; @@ -113,8 +118,8 @@ public CompletableFuture load(BlockPosition position this.ship.setLoading(false); TranslateCore .getConsole() - .sendMessage( - AText.ofPlain(Else.throwOr(NoLicencePresent.class, this.ship::getId, "") + " has loaded.")); + .sendMessage(Component.text( + Else.throwOr(NoLicencePresent.class, this.ship::getId, "") + " has loaded.")); return CompletableFuture.completedFuture(pss); } @@ -128,7 +133,7 @@ public ShipsFileLoader(File file) { public void save(AbstractShipsVessel vessel) { try { - saveToFile(vessel); + this.saveToFile(vessel); } catch (Throwable e) { e.printStackTrace(); } @@ -180,7 +185,7 @@ public void saveToFile(AbstractShipsVessel vessel) { uuidList.forEach((key, value) -> file.set( new ConfigurationNode.KnownParser.CollectionKnown<>(Parser.STRING_TO_STRING_PARSER, "Meta", "Permission", key.getId()), value)); - file.set(META_STRUCTURE, vessel.getStructure().getRelativePositionsToCenter()); + file.set(META_STRUCTURE, vessel.getStructure().getVectorsRelativeToLicence().collect(Collectors.toList())); Set> flags = vessel .getFlags() .stream() @@ -214,11 +219,7 @@ public ShipsVessel load() throws LoadVesselException { throw new FileLoadVesselException(this.file, "Unknown Z value"); } SyncBlockPosition position = opWorld.get().getPosition(opX.get(), opY.get(), opZ.get()); - LicenceSign sign = ShipsPlugin - .getPlugin() - .get(LicenceSign.class) - .orElseThrow(() -> new IllegalStateException( - "Could not get licence sign from register. Something is really wrong")); + LicenceSign sign = ShipsSigns.LICENCE; Optional opTile = position.getTileEntity(); if (!(opTile.isPresent() && opTile.get() instanceof LiveSignTileEntity)) { throw new FileLoadVesselException(this.file, "LicenceSign is not at location " + position.getX() + "," @@ -230,13 +231,20 @@ public ShipsVessel load() throws LoadVesselException { + position.getY() + "," + position.getZ() + "," + position.getWorld().getName() + ": Error V2"); } - Optional opShipTypeS = lste.getTextAt(1); + SignSide signSide = sign + .getSide(lste) + .orElseThrow(() -> new FileLoadVesselException(this.file, + "LicenceSign is not at location " + position.getX() + "," + + position.getY() + "," + position.getZ() + "," + + position.getWorld().getName() + ": Error V4")); + + Optional opShipTypeS = signSide.getLineAt(1); if (opShipTypeS.isEmpty()) { throw new FileLoadVesselException(this.file, "LicenceSign is not at location " + position.getX() + "," + position.getY() + "," + position.getZ() + "," + position.getWorld().getName() + ": Error V3"); } - String shipTypeS = opShipTypeS.get().toPlain(); - Collection> types = ShipsPlugin.getPlugin().getAllShipTypes(); + String shipTypeS = ComponentUtils.toPlain(opShipTypeS.get()); + Collection> types = ShipTypes.shipTypes(); Optional> opShipType = types .parallelStream() .filter(s -> s.getDisplayName().equalsIgnoreCase(shipTypeS)) @@ -245,11 +253,11 @@ public ShipsVessel load() throws LoadVesselException { throw new FileLoadVesselException(this.file, "Unknown ShipType"); } ShipType type = opShipType.get(); - Vessel vessel = type.createNewVessel(lste); + Vessel vessel = type.createNewVessel(signSide, lste.getPosition()); if (!(vessel instanceof ShipsVessel)) { throw new FileLoadVesselException(this.file, "ShipType requires to be ShipsVessel"); } - ShipsVessel ship = (ShipsVessel)vessel; + ShipsVessel ship = (ShipsVessel) vessel; file.getInteger(SPEED_ALTITUDE).ifPresent(ship::setAltitudeSpeed); file.getInteger(SPEED_MAX).ifPresent(ship::setMaxSpeed); @@ -283,9 +291,8 @@ public ShipsVessel load() throws LoadVesselException { .build(ShipsPlugin.getPlugin()) .run(); - ShipsPlugin - .getPlugin() - .getAll(CrewPermission.class) + CrewPermissions + .permissions() .forEach(p -> file .parseCollection(new ConfigurationNode("Meta", "Permission", p.getId()), Parser.STRING_TO_UNIQUE_ID, new ArrayList<>()) @@ -317,7 +324,7 @@ public static File getVesselDataFolder() { public static Set loadAll(Consumer function) { Set set = new HashSet<>(); - Collection> types = ShipsPlugin.getPlugin().getAllShipTypes(); + Collection> types = ShipTypes.shipTypes(); types.forEach(st -> { try { File vesselDataFolder = getVesselDataFolder(); @@ -336,25 +343,24 @@ public static Set loadAll(Consumer fun } catch (LoadVesselException e) { TranslateCore .getConsole() - .sendMessage(AText - .ofPlain("Failed to load " + file.getAbsolutePath() + ":") - .withColour(NamedTextColours.RED)); + .sendMessage(Component + .text("Failed to load " + file.getAbsolutePath() + ":") + .color(NamedTextColor.RED)); function.accept(e); } catch (Throwable e) { TranslateCore .getConsole() - .sendMessage(AText - .ofPlain("Failed to load " + file.getAbsolutePath() + ":") - .withColour(NamedTextColours.RED)); + .sendMessage(Component + .text("Failed to load " + file.getAbsolutePath() + ":") + .color(NamedTextColor.RED)); e.printStackTrace(); } } } catch (Throwable e) { TranslateCore .getConsole() - .sendMessage(AText - .ofPlain("Could not load any ships of " + st.getId()) - .withColour(NamedTextColours.RED)); + .sendMessage( + Component.text("Could not load any ships of " + st.getId()).color(NamedTextColor.RED)); e.printStackTrace(); } }); diff --git a/src/main/java/org/ships/vessel/common/requirement/FuelRequirement.java b/src/main/java/org/ships/vessel/common/requirement/FuelRequirement.java index be7944c1..1eba5c25 100644 --- a/src/main/java/org/ships/vessel/common/requirement/FuelRequirement.java +++ b/src/main/java/org/ships/vessel/common/requirement/FuelRequirement.java @@ -9,7 +9,7 @@ import org.core.world.position.block.entity.container.furnace.FurnaceTileEntity; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.ships.config.messages.AdventureMessageConfig; +import org.ships.config.messages.Messages; import org.ships.config.messages.messages.error.data.FuelRequirementMessageData; import org.ships.exceptions.move.MoveException; import org.ships.movement.MovementContext; @@ -99,16 +99,6 @@ public boolean useOnStrict() { return false; } - private Stream getInventories(MovementContext context) { - return context - .getMovingStructure() - .stream() - .map(movingBlock -> (movingBlock.getStoredBlockData()).get(KeyedData.TILED_ENTITY)) - .filter(Optional::isPresent) - .filter(opTileEntity -> opTileEntity.get() instanceof FurnaceTileEntity) - .map(opTileEntity -> ((FurnaceTileEntity) opTileEntity.get()).getInventory()); - } - @Override public void onCheckRequirement(@NotNull MovementContext context, @NotNull Vessel vessel) throws MoveException { Collection fuelTypes = this.getFuelTypes(); @@ -126,12 +116,12 @@ public void onCheckRequirement(@NotNull MovementContext context, @NotNull Vessel .map(opItem -> opItem.get().getQuantity()) .collect(Collectors.toCollection(TreeSet::new)); if (fuelSlots.isEmpty()) { - throw new MoveException(context, AdventureMessageConfig.ERROR_NOT_ENOUGH_FUEL, + throw new MoveException(context, Messages.ERROR_NOT_ENOUGH_FUEL, new FuelRequirementMessageData(vessel, fuelTypes, 0)); } int slot = fuelSlots.last(); if (slot < toTakeAmount) { - throw new MoveException(context, AdventureMessageConfig.ERROR_NOT_ENOUGH_FUEL, + throw new MoveException(context, Messages.ERROR_NOT_ENOUGH_FUEL, new FuelRequirementMessageData(vessel, fuelTypes, fuelSlots.last())); } } @@ -196,18 +186,6 @@ public void onProcessRequirement(@NotNull MovementContext context, @NotNull Vess return new FuelRequirement(this.parent, this.slot, this.takeAmount, this.fuelTypes); } - public @NotNull FuelRequirement createCopyWithSlot(@Nullable FuelSlot slot) { - return new FuelRequirement(this.parent, slot, this.takeAmount, this.fuelTypes); - } - - public @NotNull FuelRequirement createCopyWithConsumption(@Nullable Integer amount) { - return new FuelRequirement(this.parent, this.slot, amount, this.fuelTypes); - } - - public @NotNull FuelRequirement createCopyWithFuel(Collection items) { - return new FuelRequirement(this.parent, this.slot, this.takeAmount, items); - } - @Override public Optional getParent() { return Optional.ofNullable(this.parent); @@ -230,6 +208,28 @@ public void serialize(@NotNull ConfigurationStream stream, boolean withParentDat this.serializeInstance(stream); } + private Stream getInventories(MovementContext context) { + return context + .getMovingStructure() + .stream() + .map(movingBlock -> (movingBlock.getStoredBlockData()).get(KeyedData.TILED_ENTITY)) + .filter(Optional::isPresent) + .filter(opTileEntity -> opTileEntity.get() instanceof FurnaceTileEntity) + .map(opTileEntity -> ((FurnaceTileEntity) opTileEntity.get()).getInventory()); + } + + public @NotNull FuelRequirement createCopyWithSlot(@Nullable FuelSlot slot) { + return new FuelRequirement(this.parent, slot, this.takeAmount, this.fuelTypes); + } + + public @NotNull FuelRequirement createCopyWithConsumption(@Nullable Integer amount) { + return new FuelRequirement(this.parent, this.slot, amount, this.fuelTypes); + } + + public @NotNull FuelRequirement createCopyWithFuel(Collection items) { + return new FuelRequirement(this.parent, this.slot, this.takeAmount, items); + } + private void serializeInstance(@NotNull ConfigurationStream stream) { this.getSpecifiedFuelSlot().ifPresent(slot -> stream.set(AbstractShipType.FUEL_SLOT, slot)); this.getSpecifiedConsumption().ifPresent(take -> stream.set(AbstractShipType.FUEL_CONSUMPTION, take)); diff --git a/src/main/java/org/ships/vessel/common/requirement/MaxSizeRequirement.java b/src/main/java/org/ships/vessel/common/requirement/MaxSizeRequirement.java index 9d2dff50..55473da1 100644 --- a/src/main/java/org/ships/vessel/common/requirement/MaxSizeRequirement.java +++ b/src/main/java/org/ships/vessel/common/requirement/MaxSizeRequirement.java @@ -6,6 +6,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.ships.config.messages.AdventureMessageConfig; +import org.ships.config.messages.Messages; import org.ships.exceptions.move.MoveException; import org.ships.movement.MovementContext; import org.ships.vessel.common.types.Vessel; @@ -61,7 +62,7 @@ public void onCheckRequirement(@NotNull MovementContext context, @NotNull Vessel return; } if (opMaxSize.getAsInt() < size) { - throw new MoveException(context, AdventureMessageConfig.ERROR_OVERSIZED, + throw new MoveException(context, Messages.ERROR_OVERSIZED, new AbstractMap.SimpleEntry<>(vessel, size - opMaxSize.getAsInt())); } } diff --git a/src/main/java/org/ships/vessel/common/requirement/MinSizeRequirement.java b/src/main/java/org/ships/vessel/common/requirement/MinSizeRequirement.java index 17fd2d26..4f06ceba 100644 --- a/src/main/java/org/ships/vessel/common/requirement/MinSizeRequirement.java +++ b/src/main/java/org/ships/vessel/common/requirement/MinSizeRequirement.java @@ -6,6 +6,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.ships.config.messages.AdventureMessageConfig; +import org.ships.config.messages.Messages; import org.ships.exceptions.move.MoveException; import org.ships.movement.MovementContext; import org.ships.vessel.common.types.Vessel; @@ -51,7 +52,7 @@ public void onCheckRequirement(@NotNull MovementContext context, @NotNull Vessel int minSize = this.getMinimumSize(); if (minSize > shipSize) { - throw new MoveException(context, AdventureMessageConfig.ERROR_UNDERSIZED, + throw new MoveException(context, Messages.ERROR_UNDERSIZED, new AbstractMap.SimpleImmutableEntry<>(vessel, minSize - shipSize)); } } diff --git a/src/main/java/org/ships/vessel/common/requirement/SpecialBlockRequirement.java b/src/main/java/org/ships/vessel/common/requirement/SpecialBlockRequirement.java index da8ef096..9a353bf9 100644 --- a/src/main/java/org/ships/vessel/common/requirement/SpecialBlockRequirement.java +++ b/src/main/java/org/ships/vessel/common/requirement/SpecialBlockRequirement.java @@ -7,6 +7,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.ships.config.messages.AdventureMessageConfig; +import org.ships.config.messages.Messages; import org.ships.config.messages.messages.error.data.NamedBlockMessageData; import org.ships.exceptions.move.MoveException; import org.ships.movement.MovementContext; @@ -100,7 +101,7 @@ public void onCheckRequirement(@NotNull MovementContext context, @NotNull Vessel .map(moving -> moving.getStoredBlockData().getType().equals(requiredType)) .count(); if (found < amount) { - throw new MoveException(context, AdventureMessageConfig.ERROR_FAILED_TO_FIND_NAMED_BLOCK, + throw new MoveException(context, Messages.ERROR_FAILED_TO_FIND_NAMED_BLOCK, new NamedBlockMessageData() .setVessel(vessel) .setType(requiredType) diff --git a/src/main/java/org/ships/vessel/common/requirement/SpecialBlocksRequirement.java b/src/main/java/org/ships/vessel/common/requirement/SpecialBlocksRequirement.java index e10e3682..d8de26fa 100644 --- a/src/main/java/org/ships/vessel/common/requirement/SpecialBlocksRequirement.java +++ b/src/main/java/org/ships/vessel/common/requirement/SpecialBlocksRequirement.java @@ -6,6 +6,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.ships.config.messages.AdventureMessageConfig; +import org.ships.config.messages.Messages; import org.ships.config.messages.messages.error.data.RequirementPercentMessageData; import org.ships.exceptions.move.MoveException; import org.ships.movement.MovementContext; @@ -99,13 +100,13 @@ public void onCheckRequirement(@NotNull MovementContext context, @NotNull Vessel .filter(block -> specialBlocks.contains(block.getType())) .count(); if (blocksFound == 0) { - throw new MoveException(context, AdventureMessageConfig.ERROR_SPECIAL_BLOCK_PERCENT_NOT_ENOUGH, + throw new MoveException(context, Messages.ERROR_SPECIAL_BLOCK_PERCENT_NOT_ENOUGH, new RequirementPercentMessageData(vessel, 0, 0)); } double totalPercent = (blocksFound * 100.0) / context.getMovingStructure().size(); if (totalPercent < percentageRequired) { - throw new MoveException(context, AdventureMessageConfig.ERROR_SPECIAL_BLOCK_PERCENT_NOT_ENOUGH, + throw new MoveException(context, Messages.ERROR_SPECIAL_BLOCK_PERCENT_NOT_ENOUGH, new RequirementPercentMessageData(vessel, totalPercent, (int) blocksFound)); } } diff --git a/src/main/java/org/ships/vessel/common/types/ShipType.java b/src/main/java/org/ships/vessel/common/types/ShipType.java index 69e910e3..62184118 100644 --- a/src/main/java/org/ships/vessel/common/types/ShipType.java +++ b/src/main/java/org/ships/vessel/common/types/ShipType.java @@ -23,12 +23,22 @@ public interface ShipType extends Identifiable { @Deprecated(forRemoval = true) - OPShipType OVERPOWERED_SHIP = new OPShipType(); - MarsshipType MARSSHIP = new MarsshipType(); - AirshipType AIRSHIP = new AirshipType(); - WaterShipType WATERSHIP = new WaterShipType(); - SubmarineType SUBMARINE = new SubmarineType(); - PlaneType PLANE = new PlaneType(); + OPShipType OVERPOWERED_SHIP = ShipTypes.OVERPOWERED_SHIP; + + @Deprecated + MarsshipType MARSSHIP = ShipTypes.MARSSHIP; + + @Deprecated(forRemoval = true) + AirshipType AIRSHIP = ShipTypes.AIRSHIP; + + @Deprecated(forRemoval = true) + WaterShipType WATERSHIP = ShipTypes.WATERSHIP; + + @Deprecated(forRemoval = true) + SubmarineType SUBMARINE = ShipTypes.SUBMARINE; + + @Deprecated(forRemoval = true) + PlaneType PLANE = ShipTypes.PLANE; @NotNull String getDisplayName(); @@ -52,11 +62,6 @@ public interface ShipType extends Identifiable { @NotNull CorePermission getMakePermission(); - @Deprecated(forRemoval = true) - default T createNewVessel(@NotNull LiveSignTileEntity position) { - return this.createNewVessel(position.getSide(true), position.getPosition()); - } - default @NotNull Optional getFlag(@NotNull Class class1) { return this.getFlags().stream().filter(class1::isInstance).map(f -> (E) f).findAny(); } diff --git a/src/main/java/org/ships/vessel/common/types/ShipTypes.java b/src/main/java/org/ships/vessel/common/types/ShipTypes.java new file mode 100644 index 00000000..1038a89a --- /dev/null +++ b/src/main/java/org/ships/vessel/common/types/ShipTypes.java @@ -0,0 +1,62 @@ +package org.ships.vessel.common.types; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.UnmodifiableView; +import org.ships.vessel.common.assits.shiptype.CloneableShipType; +import org.ships.vessel.common.types.typical.airship.AirshipType; +import org.ships.vessel.common.types.typical.marsship.MarsshipType; +import org.ships.vessel.common.types.typical.opship.OPShipType; +import org.ships.vessel.common.types.typical.plane.PlaneType; +import org.ships.vessel.common.types.typical.submarine.SubmarineType; +import org.ships.vessel.common.types.typical.watership.WaterShipType; + +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.LinkedTransferQueue; +import java.util.stream.Stream; + +public final class ShipTypes { + + private static final @NotNull Collection> registered = new LinkedTransferQueue<>(); + + public static final PlaneType PLANE = register(new PlaneType()); + public static final SubmarineType SUBMARINE = register(new SubmarineType()); + public static final AirshipType AIRSHIP = register(new AirshipType()); + public static final WaterShipType WATERSHIP = register(new WaterShipType()); + public static final MarsshipType MARSSHIP = register(new MarsshipType()); + public static final OPShipType OVERPOWERED_SHIP = register(new OPShipType()); + + private ShipTypes() { + throw new RuntimeException("Do not generate"); + } + + + private static > T register(@NotNull T shipType) { + registered.add(shipType); + return shipType; + } + + public static void unregisterType(@NotNull ShipType type) { + registered.remove(type); + } + + public static void registerType(@NotNull ShipType shipType) { + if (registered.stream().anyMatch(type -> type.getId().equals(shipType.getId()))) { + throw new IllegalArgumentException( + "ShipType with the id of '" + shipType.getId() + "' is already registered"); + } + registered.add(shipType); + } + + @UnmodifiableView + public static Collection> shipTypes() { + return Collections.unmodifiableCollection(registered); + } + + public static Stream> cloneableShipTypes() { + return shipTypes() + .stream() + .filter(shipType -> shipType instanceof CloneableShipType) + .map(shipType -> (CloneableShipType) shipType); + } +} diff --git a/src/main/java/org/ships/vessel/common/types/Vessel.java b/src/main/java/org/ships/vessel/common/types/Vessel.java index 701691ee..1bc0e184 100644 --- a/src/main/java/org/ships/vessel/common/types/Vessel.java +++ b/src/main/java/org/ships/vessel/common/types/Vessel.java @@ -6,14 +6,15 @@ import org.core.vector.type.Vector2; import org.core.vector.type.Vector3; import org.core.world.Extent; +import org.core.world.WorldExtent; +import org.core.world.chunk.AsyncChunk; +import org.core.world.chunk.Chunk; import org.core.world.direction.Direction; import org.core.world.direction.FourFacingDirection; import org.core.world.position.Positionable; -import org.core.world.position.block.BlockType; import org.core.world.position.block.BlockTypes; import org.core.world.position.impl.BlockPosition; import org.core.world.position.impl.Position; -import org.core.world.position.impl.async.ASyncBlockPosition; import org.core.world.position.impl.sync.SyncBlockPosition; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -25,43 +26,51 @@ import java.util.*; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; +import java.util.stream.Stream; public interface Vessel extends Positionable { - @NotNull String getName() throws NoLicencePresent; + @NotNull + String getName() throws NoLicencePresent; - @NotNull PositionableShipsStructure getStructure(); + @NotNull + PositionableShipsStructure getStructure(); void setStructure(@NotNull PositionableShipsStructure pss); CompletableFuture updateStructure(OvertimeBlockFinderUpdate finder); default CompletableFuture updateStructure() { - return updateStructure((currentStructure, block) -> OvertimeBlockFinderUpdate.BlockFindControl.USE); + return this.updateStructure((currentStructure, block) -> OvertimeBlockFinderUpdate.BlockFindControl.USE); } - @NotNull ShipType getType(); + @NotNull + ShipType getType(); > @NotNull Optional get(@NotNull Class clazz); @NotNull Vessel set(@NotNull Class> flag, T value); - @NotNull Vessel set(@NotNull VesselFlag flag); + @NotNull + Vessel set(@NotNull VesselFlag flag); int getMaxSpeed(); - @NotNull Vessel setMaxSpeed(@Nullable Integer speed); + @NotNull + Vessel setMaxSpeed(@Nullable Integer speed); boolean isMaxSpeedSpecified(); int getAltitudeSpeed(); - @NotNull Vessel setAltitudeSpeed(@Nullable Integer speed); + @NotNull + Vessel setAltitudeSpeed(@Nullable Integer speed); boolean isAltitudeSpeedSpecified(); @@ -92,44 +101,37 @@ default > Optional getValue(Class flagClass) { return this.get(flagClass).flatMap(VesselFlag::getValue); } + @Deprecated(forRemoval = true) default Collection getEntities() { return this.getEntities(e -> true); } + @Deprecated(forRemoval = true) default Collection getEntities(Class clazz) { return (Collection) this.getEntities(clazz::isInstance); } + @Deprecated(forRemoval = true) default Collection getEntities(Predicate check) { + return this.getLiveEntities(check).collect(Collectors.toSet()); + } + + default Stream getLiveEntities(Predicate check) { Bounds bounds = this.getStructure().getBounds(); bounds.add(1, Integer.MAX_VALUE, 1); bounds.add(-1, -1, -1); - Set entities = new HashSet<>(); - this.getStructure().getChunks().stream().map(Extent::getEntities).forEach(entities::addAll); - entities = entities.stream().filter(e -> { + Collection> blocks = this + .getStructure() + .getVectorsRelativeToWorld() + .collect(Collectors.toList()); + return this.getStructure().getLoadedChunks().flatMap(Extent::getLiveEntities).filter(e -> { Optional opTo = e.getAttachedTo(); return opTo.filter(syncBlockPosition -> bounds.contains(syncBlockPosition.getPosition())).isPresent(); - }).collect(Collectors.toSet()); - Collection blocks = this.getStructure().getAsyncedPositionsRelativeToWorld(); - return entities.stream().filter(check).filter(e -> { + }).filter(check).filter(e -> { Optional opBlock = e.getAttachedTo(); //noinspection SuspiciousMethodCalls return opBlock.filter(blocks::contains).isPresent(); - }).collect(Collectors.toSet()); - - } - - @Deprecated(forRemoval = true) - default void getEntitiesAsynced(Predicate predicate, - Consumer> output) { - this.getEntitiesAsynced(predicate, output, Throwable::printStackTrace); - } - - @Deprecated(forRemoval = true) - default void getEntitiesAsynced(Predicate predicate, - Consumer> output, - Consumer onException) { - this.getEntitiesOvertime(predicate, onException).thenAccept(output); + }); } default CompletableFuture> getEntitiesOvertime(Predicate predicate) { @@ -144,17 +146,12 @@ default CompletableFuture> getEntitiesOvertime(Predicate< bounds.add(-1, -1, -1); bounds.add(1, 5, 1); - Map> entityPositions = chunks - .stream() - .flatMap(c -> c.getEntities().stream()) - .collect(Collectors.toMap(e -> e, e -> e + return chunks + .flatMap(Extent::getLiveEntities) + .map(entity -> Map.entry(entity, entity .getAttachedTo() .map(Position::getPosition) - .orElseGet(() -> e.getPosition().toBlockPosition().getPosition()))); - - return entityPositions - .entrySet() - .parallelStream() + .orElseGet(() -> entity.getPosition().toBlockPosition().getPosition()))) .filter(entry -> bounds.contains(entry.getValue())) .map(Map.Entry::getKey) .filter(predicate) @@ -174,38 +171,73 @@ default void rotateClockwiseAround(@NotNull BlockPosition location, @NotNull Mov this.rotateLeftAround(location, details); } + @Deprecated(forRemoval = true) default Optional getWaterLevel(Function function, Collection collection) { - Map, Integer> height = new HashMap<>(); - int lowest = Integer.MIN_VALUE; + if (collection.isEmpty()) { + return Optional.empty(); + } + WorldExtent world = function.apply(collection.iterator().next()).getWorld(); + List> positions = collection + .stream() + .map(function) + .map(Position::getPosition) + .collect(Collectors.toList()); + + OptionalInt result = this.getWaterLevel(world, positions); + if (result.isEmpty()) { + return Optional.empty(); + } + return Optional.of(result.getAsInt()); + } + + default OptionalInt getWaterLevel(WorldExtent extent, Collection> collection) { + List asyncChunks = extent + .getChunkExtents() + .filter(chunk -> collection.stream().anyMatch(vec -> chunk.getBounds().containsWithoutMax(vec))) + .map(Chunk::createAsync) + .collect(Collectors.toList()); Direction[] directions = FourFacingDirection.getFourFacingDirections(); - for (T value : collection) { - BlockPosition position = function.apply(value); - for (Direction direction : directions) { - BlockType type = position.getRelative(direction).getBlockType(); - if (!type.equals(BlockTypes.WATER)) { - continue; - } - Vector2 vector = Vector2.valueOf(position.getX() + direction.getAsVector().getX(), - position.getZ() + direction.getAsVector().getZ()); - if (!height.containsKey(vector)) { - height.put(vector, position.getY()); - continue; - } - if (height.getOrDefault(vector, lowest) < position.getY()) { - height.replace(vector, position.getY()); - } + Map, Integer> waterLevels = collection + .stream() + .flatMap(vec -> Stream.of(directions).map(direction -> vec.plus(direction.getAsVector()))) + .map(vec -> asyncChunks + .stream() + .filter(chunk -> chunk.getBounds().containsWithoutMax(vec)) + .findAny() + .map(chunk -> Map.entry(vec, chunk.getDetails(vec).getType())) + .filter(entry -> entry.getValue().equals(BlockTypes.WATER)) + .map(Map.Entry::getKey)) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.toMap(vec -> vec, Vector3::getY)); + + Map, Integer> filteredWaterLevels = new ConcurrentHashMap<>(); + for (Map.Entry, Integer> entry : waterLevels.entrySet()) { + Vector2 as2dVector = Vector2.valueOf(entry.getKey().getX(), entry.getKey().getZ()); + Integer currentWaterLevel = filteredWaterLevels.get(as2dVector); + if (currentWaterLevel == null) { + filteredWaterLevels.put(as2dVector, entry.getValue()); + continue; + } + if (entry.getValue() > currentWaterLevel) { + filteredWaterLevels.replace(as2dVector, entry.getValue()); } } - if (height.isEmpty()) { - return Optional.empty(); + if (filteredWaterLevels.isEmpty()) { + return OptionalInt.empty(); } - return Optional.of(MathUtils.getMostCommonNumber(height.values())); + return OptionalInt.of(MathUtils.getMostCommonNumber(filteredWaterLevels.values())); } default Optional getWaterLevel() { PositionableShipsStructure pss = this.getStructure(); - return this.getWaterLevel(p -> p, pss.getAsyncedPositionsRelativeToWorld()); + OptionalInt result = this.getWaterLevel(this.getPosition().getWorld(), + pss.getVectorsRelativeToWorld().collect(Collectors.toList())); + if (result.isEmpty()) { + return Optional.empty(); + } + return Optional.of(result.getAsInt()); } } diff --git a/src/main/java/org/ships/vessel/common/types/typical/AbstractShipsVessel.java b/src/main/java/org/ships/vessel/common/types/typical/AbstractShipsVessel.java index 9abf477e..64caf230 100644 --- a/src/main/java/org/ships/vessel/common/types/typical/AbstractShipsVessel.java +++ b/src/main/java/org/ships/vessel/common/types/typical/AbstractShipsVessel.java @@ -32,11 +32,14 @@ import org.ships.vessel.common.assits.shiptype.SizedShipType; import org.ships.vessel.common.flag.MovingFlag; import org.ships.vessel.common.flag.VesselFlag; +import org.ships.vessel.common.flag.VesselFlags; import org.ships.vessel.common.loader.shipsvessel.ShipsFileLoader; import org.ships.vessel.common.requirement.Requirement; import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import org.ships.vessel.common.types.Vessel; import org.ships.vessel.sign.LicenceSign; +import org.ships.vessel.sign.ShipsSigns; import org.ships.vessel.structure.AbstractPositionableShipsStructure; import org.ships.vessel.structure.PositionableShipsStructure; @@ -60,17 +63,6 @@ public abstract class AbstractShipsVessel implements ShipsVessel { protected boolean isLoading = true; protected String cachedName; - @Deprecated(forRemoval = true) - public AbstractShipsVessel(@NotNull LiveTileEntity licence, @NotNull ShipType type) - throws NoLicencePresent { - this((LiveSignTileEntity) licence, ShipsPlugin - .getPlugin() - .get(LicenceSign.class) - .flatMap(lic -> lic.getSide((SignTileEntity) licence)) - .orElseThrow(() -> new IllegalStateException("Invalid license sign")) - .isFront(), type); - } - public AbstractShipsVessel(@SuppressWarnings("TypeMayBeWeakened") @NotNull LiveSignTileEntity licence, boolean isFrontOfSign, @NotNull ShipType type) { @@ -86,25 +78,13 @@ public AbstractShipsVessel(@SuppressWarnings("TypeMayBeWeakened") @NotNull LiveS } } - @Deprecated(forRemoval = true) - public AbstractShipsVessel(@NotNull SignTileEntity ste, - @NotNull SyncBlockPosition position, - @NotNull ShipType type) { - this(ShipsPlugin - .getPlugin() - .get(LicenceSign.class) - .flatMap(licence -> licence.getSide(ste)) - .orElseThrow(() -> new IllegalStateException("Not valid sign")), position, type); - } - public AbstractShipsVessel(SignSide signSide, SyncBlockPosition position, ShipType type) { this.isFrontOfSign = signSide.isFront(); this.positionableShipsStructure = new AbstractPositionableShipsStructure(position); - this.file = new File(ShipsPlugin.getPlugin().getConfigFolder(), "VesselData/" + ShipsPlugin - .getPlugin() - .getAllShipTypes() + this.file = new File(ShipsPlugin.getPlugin().getConfigFolder(), "VesselData/" + ShipTypes + .shipTypes() .stream() .filter(t -> signSide .getLineAt(1) @@ -125,10 +105,9 @@ public AbstractShipsVessel(SignSide signSide, } private void init(ShipType type) { - ConfigurationStream.ConfigurationFile configuration = TranslateCore.createConfigurationFile(this.file, - TranslateCore - .getPlatform() - .getConfigFormat()); + ConfigurationStream.ConfigurationFile configuration = TranslateCore + .getConfigManager() + .read(this.file, TranslateCore.getPlatform().getConfigFormat()); this.file = configuration.getFile(); this.type = type; @@ -191,44 +170,14 @@ public CompletableFuture updateStructure(OvertimeBlo .setConnectedVessel(this) .getConnectedBlocksOvertime(this.getPosition(), update) .thenApplyAsync(updatedStructure -> { - Set> updatedBlocks = updatedStructure - .getAsyncedPositionsRelativeToWorld() - .parallelStream() - .filter(position -> !position.getBlockType().equals(BlockTypes.AIR)) - .map(Position::getPosition) - .collect(Collectors.toSet()); - PositionableShipsStructure currentStructure = this.getStructure(); - boolean sameStructure = currentStructure - .getAsyncedPositionsRelativeToWorld() - .parallelStream() - .filter(position -> !position.getBlockType().equals(BlockTypes.AIR)) - .map(Position::getPosition) - .allMatch(updatedBlocks::contains); - if (sameStructure) { - currentStructure.setPosition(updatedStructure.getPosition()); - } - return Map.entry(currentStructure, sameStructure); + boolean sameStructure = currentStructure.matchStructure(updatedStructure); + return Map.entry(updatedStructure, sameStructure); }) .thenCompose(entry -> { PositionableShipsStructure updated = entry.getKey(); - if (entry.getValue()) { - return CompletableFuture.completedFuture(entry); - } - if (AbstractShipsVessel.this instanceof WaterType) { - CompletableFuture filled = updated.fillAir(); - return filled.thenApply(structure -> Map.entry(structure, entry.getValue())); - } - return CompletableFuture.completedFuture(entry); - }) - .thenCompose(entry -> { - PositionableShipsStructure updated = entry.getKey(); - if (entry.getValue()) { - return CompletableFuture.completedFuture(updated); - } - this.setStructure(updated); - if (AbstractShipsVessel.this instanceof WaterType) { - return updated.fillAir(); + if (!entry.getValue()) { + this.setStructure(updated); } return CompletableFuture.completedFuture(updated); }); @@ -248,7 +197,7 @@ public CompletableFuture updateStructure(OvertimeBlo public @NotNull Vessel set(@NotNull Class> flag, T value) { Optional> opFlag = this.getFlags().stream().filter(flag::isInstance).findFirst(); if (opFlag.isEmpty()) { - Optional> opNewFlag = ShipsPlugin.getPlugin().get(flag); + Optional> opNewFlag = VesselFlags.getDefault(flag); if (opNewFlag.isEmpty()) { Component error = Component.text( "Class of '" + flag.getName() + "' is not registered in ShipsPlugin.Failed to set for '" @@ -256,7 +205,7 @@ public CompletableFuture updateStructure(OvertimeBlo TranslateCore.getConsole().sendMessage(error); return this; } - VesselFlag vFlag = opNewFlag.get(); + VesselFlag vFlag = opNewFlag.get().clone(); vFlag.setValue(value); this.flags.add(vFlag); return this; diff --git a/src/main/java/org/ships/vessel/common/types/typical/ShipsVessel.java b/src/main/java/org/ships/vessel/common/types/typical/ShipsVessel.java index 25653e32..68a108c4 100644 --- a/src/main/java/org/ships/vessel/common/types/typical/ShipsVessel.java +++ b/src/main/java/org/ships/vessel/common/types/typical/ShipsVessel.java @@ -1,9 +1,10 @@ package org.ships.vessel.common.types.typical; -import org.core.adventureText.AText; +import net.kyori.adventure.text.Component; import org.core.vector.type.Vector3; import org.core.world.position.block.entity.LiveTileEntity; import org.core.world.position.block.entity.sign.LiveSignTileEntity; +import org.core.world.position.block.entity.sign.SignSide; import org.core.world.position.impl.BlockPosition; import org.jetbrains.annotations.NotNull; import org.ships.exceptions.NoLicencePresent; @@ -16,6 +17,8 @@ import org.ships.vessel.common.assits.*; import org.ships.vessel.common.flag.VesselFlag; import org.ships.vessel.sign.LicenceSign; +import org.ships.vessel.sign.ShipsSign; +import org.ships.vessel.sign.ShipsSigns; import java.io.File; import java.util.Collection; @@ -42,11 +45,8 @@ public interface ShipsVessel if (!(tile instanceof LiveSignTileEntity)) { throw new NoLicencePresent(this); } - LiveSignTileEntity sign = (LiveSignTileEntity)tile; - LicenceSign licenceSign = ShipsPlugin - .getPlugin() - .get(LicenceSign.class) - .orElseThrow(() -> new IllegalStateException("Could not get licence sign builder")); + LiveSignTileEntity sign = (LiveSignTileEntity) tile; + LicenceSign licenceSign = ShipsSigns.LICENCE; if (!licenceSign.isSign(sign)) { throw new NoLicencePresent(this); } @@ -55,7 +55,11 @@ public interface ShipsVessel @Override default @NotNull ShipsVessel setName(@NotNull String name) throws NoLicencePresent { - this.getSign().setTextAt(2, AText.ofPlain(name)); + LiveSignTileEntity sign = this.getSign(); + SignSide side = ShipsSigns.LICENCE + .getSide(sign) + .orElseThrow(() -> new RuntimeException("No licence sign found")); + side.setLineAt(2, Component.text(name)); File file = this.getFile(); String[] ext = file.getName().split(Pattern.quote(".")); file.renameTo(new File(file.getParentFile(), name + "." + ext[ext.length - 1])); diff --git a/src/main/java/org/ships/vessel/common/types/typical/airship/Airship.java b/src/main/java/org/ships/vessel/common/types/typical/airship/Airship.java index 89e6ba74..eb14a0ee 100644 --- a/src/main/java/org/ships/vessel/common/types/typical/airship/Airship.java +++ b/src/main/java/org/ships/vessel/common/types/typical/airship/Airship.java @@ -42,20 +42,6 @@ public class Airship extends AbstractShipsVessel implements AirType, FallableReq private final Collection> requirements = new HashSet<>(); - @SuppressWarnings("removal") - @Deprecated(forRemoval = true) - public Airship(ShipType type, LiveTileEntity licence) throws NoLicencePresent { - super(licence, type); - this.initRequirements(); - } - - @SuppressWarnings("removal") - @Deprecated(forRemoval = true) - public Airship(ShipType type, SignTileEntity ste, SyncBlockPosition position) { - super(ste, position, type); - this.initRequirements(); - } - public Airship(@NotNull LiveSignTileEntity licence, boolean isFrontOfSign, @NotNull ShipType type) { diff --git a/src/main/java/org/ships/vessel/common/types/typical/airship/AirshipType.java b/src/main/java/org/ships/vessel/common/types/typical/airship/AirshipType.java index dd07927d..ceb77d8e 100644 --- a/src/main/java/org/ships/vessel/common/types/typical/airship/AirshipType.java +++ b/src/main/java/org/ships/vessel/common/types/typical/airship/AirshipType.java @@ -1,16 +1,16 @@ package org.ships.vessel.common.types.typical.airship; -import org.array.utils.ArrayUtils; import org.core.TranslateCore; import org.core.config.ConfigurationStream; import org.core.inventory.item.ItemTypes; import org.core.inventory.item.type.post.ItemTypes1V13; import org.core.permission.CorePermission; import org.core.platform.plugin.Plugin; +import org.core.utils.Identifiable; import org.core.world.position.block.BlockType; import org.core.world.position.block.BlockTypes; import org.core.world.position.block.entity.sign.SignSide; -import org.core.world.position.block.grouptype.versions.BlockGroups1V13; +import org.core.world.position.block.grouptype.BlockGroups; import org.core.world.position.impl.sync.SyncBlockPosition; import org.jetbrains.annotations.NotNull; import org.ships.permissions.Permissions; @@ -21,12 +21,15 @@ import org.ships.vessel.common.assits.shiptype.SizedShipType; import org.ships.vessel.common.assits.shiptype.SpecialBlocksShipType; import org.ships.vessel.common.requirement.*; -import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import org.ships.vessel.common.types.typical.AbstractShipType; import java.io.File; import java.util.Collection; +import java.util.Comparator; import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; public class AirshipType extends AbstractShipType implements CloneableShipType, SpecialBlocksShipType, FuelledShipType, @@ -51,7 +54,7 @@ public AirshipType() { public AirshipType(String displayName, File file) { this(ShipsPlugin.getPlugin(), displayName, - TranslateCore.createConfigurationFile(file, TranslateCore.getPlatform().getConfigFormat()), + TranslateCore.getConfigManager().read(file, TranslateCore.getPlatform().getConfigFormat()), BlockTypes.AIR); } @@ -99,17 +102,21 @@ public AirshipType cloneWithName(File file, String name) { @Override public AirshipType getOriginType() { - return ShipType.AIRSHIP; + return ShipTypes.AIRSHIP; } @Override protected void createDefault(ConfigurationStream.@NotNull ConfigurationFile file) { this.file.set(BURNER_BLOCK, true); this.file.set(SPECIAL_BLOCK_PERCENT, 60.0f); - this.file.set(SPECIAL_BLOCK_TYPE, ArrayUtils.ofSet(BlockGroups1V13.WOOL.getGrouped())); + this.file.set(SPECIAL_BLOCK_TYPE, BlockGroups.WOOL + .get() + .getBlocks() + .sorted(Comparator.comparing(Identifiable::getId)) + .collect(Collectors.toList())); this.file.set(FUEL_CONSUMPTION, 1); this.file.set(FUEL_SLOT, FuelSlot.BOTTOM); - this.file.set(FUEL_TYPES, ArrayUtils.ofSet(ItemTypes.COAL.get(), ItemTypes1V13.CHARCOAL.get())); + this.file.set(FUEL_TYPES, Set.of(ItemTypes.COAL.get(), ItemTypes1V13.CHARCOAL.get())); this.file.set(MAX_SPEED, 10); this.file.set(ALTITUDE_SPEED, 5); } diff --git a/src/main/java/org/ships/vessel/common/types/typical/marsship/Marsship.java b/src/main/java/org/ships/vessel/common/types/typical/marsship/Marsship.java index 37bba923..c73f3f61 100644 --- a/src/main/java/org/ships/vessel/common/types/typical/marsship/Marsship.java +++ b/src/main/java/org/ships/vessel/common/types/typical/marsship/Marsship.java @@ -1,18 +1,14 @@ package org.ships.vessel.common.types.typical.marsship; -import org.array.utils.ArrayUtils; import org.core.config.ConfigurationNode; import org.core.config.ConfigurationStream; import org.core.config.parser.Parser; import org.core.world.position.block.BlockType; -import org.core.world.position.block.entity.LiveTileEntity; import org.core.world.position.block.entity.sign.LiveSignTileEntity; import org.core.world.position.block.entity.sign.SignSide; -import org.core.world.position.block.entity.sign.SignTileEntity; import org.core.world.position.impl.sync.SyncBlockPosition; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.ships.exceptions.NoLicencePresent; import org.ships.vessel.common.assits.AirType; import org.ships.vessel.common.assits.VesselRequirement; import org.ships.vessel.common.requirement.MaxSizeRequirement; @@ -24,6 +20,7 @@ import org.ships.vessel.common.types.typical.AbstractShipsVessel; import java.util.*; +import java.util.stream.Collectors; public class Marsship extends AbstractShipsVessel implements AirType, VesselRequirement { @@ -46,18 +43,6 @@ public Marsship(SignSide signSide, SyncBlockPosition position, ShipType type, LiveTileEntity licence) throws NoLicencePresent { - super(licence, type); - this.initRequirements(); - } - - @Deprecated(forRemoval = true) - public Marsship(ShipType type, SignTileEntity ste, SyncBlockPosition position) { - super(ste, position, type); - this.initRequirements(); - } - public MaxSizeRequirement getMaxBlocksRequirement() { return this .getRequirement(MaxSizeRequirement.class) @@ -101,6 +86,12 @@ public Collection> getRequirements() { return Collections.unmodifiableCollection(this.requirements); } + @Override + public void setRequirement(@NotNull Requirement updated) { + this.getRequirement(updated.getClass()).ifPresent(this.requirements::remove); + this.requirements.add(updated); + } + public boolean isSpecialBlocksSpecified() { return this.getSpecialBlocksRequirement().isBlocksSpecified(); } @@ -139,8 +130,11 @@ public boolean isMinSizeSpecified() { @Override public @NotNull Map getExtraInformation() { Map map = new HashMap<>(); - map.put("Special Block", - ArrayUtils.toString(", ", Parser.STRING_TO_BLOCK_TYPE::unparse, this.getSpecialBlocks())); + map.put("Special Block", this + .getSpecialBlocks() + .stream() + .map(Parser.STRING_TO_BLOCK_TYPE::unparse) + .collect(Collectors.joining(", "))); map.put("Required Percent", this.getSpecialBlocksPercent() + ""); return map; } @@ -166,10 +160,4 @@ public boolean isMinSizeSpecified() { return this; } - @Override - public void setRequirement(@NotNull Requirement updated) { - this.getRequirement(updated.getClass()).ifPresent(this.requirements::remove); - this.requirements.add(updated); - } - } diff --git a/src/main/java/org/ships/vessel/common/types/typical/marsship/MarsshipType.java b/src/main/java/org/ships/vessel/common/types/typical/marsship/MarsshipType.java index da208d3b..dfcb3d1d 100644 --- a/src/main/java/org/ships/vessel/common/types/typical/marsship/MarsshipType.java +++ b/src/main/java/org/ships/vessel/common/types/typical/marsship/MarsshipType.java @@ -20,6 +20,7 @@ import org.ships.vessel.common.requirement.Requirement; import org.ships.vessel.common.requirement.SpecialBlocksRequirement; import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import org.ships.vessel.common.types.typical.AbstractShipType; import java.io.File; @@ -54,7 +55,7 @@ public MarsshipType() { public MarsshipType(String name, File file) { this(ShipsPlugin.getPlugin(), name, - TranslateCore.createConfigurationFile(file, TranslateCore.getPlatform().getConfigFormat()), BlockTypes.AIR, + TranslateCore.getConfigManager().read(file, TranslateCore.getPlatform().getConfigFormat()), BlockTypes.AIR, BlockTypes.WATER); } @@ -97,7 +98,7 @@ public MarsshipType cloneWithName(File file, String name) { @Override public MarsshipType getOriginType() { - return ShipType.MARSSHIP; + return ShipTypes.MARSSHIP; } @Override diff --git a/src/main/java/org/ships/vessel/common/types/typical/opship/OPShip.java b/src/main/java/org/ships/vessel/common/types/typical/opship/OPShip.java index 3b762abd..3ea3a845 100644 --- a/src/main/java/org/ships/vessel/common/types/typical/opship/OPShip.java +++ b/src/main/java/org/ships/vessel/common/types/typical/opship/OPShip.java @@ -2,13 +2,10 @@ import org.core.config.ConfigurationNode; import org.core.config.ConfigurationStream; -import org.core.world.position.block.entity.LiveTileEntity; import org.core.world.position.block.entity.sign.LiveSignTileEntity; import org.core.world.position.block.entity.sign.SignSide; -import org.core.world.position.block.entity.sign.SignTileEntity; import org.core.world.position.impl.sync.SyncBlockPosition; import org.jetbrains.annotations.NotNull; -import org.ships.exceptions.NoLicencePresent; import org.ships.vessel.common.assits.AirType; import org.ships.vessel.common.types.ShipType; import org.ships.vessel.common.types.typical.AbstractShipsVessel; @@ -16,19 +13,8 @@ import java.util.HashMap; import java.util.Map; -@Deprecated(forRemoval = true) public class OPShip extends AbstractShipsVessel implements AirType { - @Deprecated(forRemoval = true) - public OPShip(LiveTileEntity licence, ShipType origin) throws NoLicencePresent { - super(licence, origin); - } - - @Deprecated(forRemoval = true) - public OPShip(SignTileEntity ste, SyncBlockPosition position, ShipType origin) { - super(ste, position, origin); - } - public OPShip(@NotNull LiveSignTileEntity licence, boolean isFrontOfSign, @NotNull ShipType type) { diff --git a/src/main/java/org/ships/vessel/common/types/typical/opship/OPShipType.java b/src/main/java/org/ships/vessel/common/types/typical/opship/OPShipType.java index 76d57e91..d1263d16 100644 --- a/src/main/java/org/ships/vessel/common/types/typical/opship/OPShipType.java +++ b/src/main/java/org/ships/vessel/common/types/typical/opship/OPShipType.java @@ -18,7 +18,6 @@ import java.util.Collection; import java.util.Collections; -@Deprecated(forRemoval = true) public class OPShipType extends AbstractShipType { public OPShipType() { @@ -31,7 +30,7 @@ public OPShipType() { public OPShipType(String name, File file) { this(ShipsPlugin.getPlugin(), name, - TranslateCore.createConfigurationFile(file, TranslateCore.getPlatform().getConfigFormat()), + TranslateCore.getConfigManager().read(file, TranslateCore.getPlatform().getConfigFormat()), BlockTypes.AIR); } diff --git a/src/main/java/org/ships/vessel/common/types/typical/plane/Plane.java b/src/main/java/org/ships/vessel/common/types/typical/plane/Plane.java index 30aee86f..576c5275 100644 --- a/src/main/java/org/ships/vessel/common/types/typical/plane/Plane.java +++ b/src/main/java/org/ships/vessel/common/types/typical/plane/Plane.java @@ -10,18 +10,15 @@ import org.core.inventory.parts.Slot; import org.core.world.position.block.details.BlockSnapshot; import org.core.world.position.block.details.data.keyed.KeyedData; -import org.core.world.position.block.entity.LiveTileEntity; import org.core.world.position.block.entity.TileEntity; import org.core.world.position.block.entity.TileEntitySnapshot; import org.core.world.position.block.entity.container.furnace.FurnaceTileEntity; import org.core.world.position.block.entity.container.furnace.FurnaceTileEntitySnapshot; import org.core.world.position.block.entity.sign.LiveSignTileEntity; import org.core.world.position.block.entity.sign.SignSide; -import org.core.world.position.block.entity.sign.SignTileEntity; import org.core.world.position.impl.sync.SyncBlockPosition; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.ships.exceptions.NoLicencePresent; import org.ships.vessel.common.assits.AirType; import org.ships.vessel.common.assits.Fallable; import org.ships.vessel.common.assits.FuelSlot; @@ -48,18 +45,6 @@ public class Plane extends AbstractShipsVessel implements AirType, VesselRequire private final Collection> requirements = new HashSet<>(); - @Deprecated(forRemoval = true) - public Plane(LiveTileEntity licence, ShipType type) throws NoLicencePresent { - super(licence, type); - this.initRequirements(); - } - - @Deprecated(forRemoval = true) - public Plane(SignTileEntity ste, SyncBlockPosition position, ShipType type) { - super(ste, position, type); - this.initRequirements(); - } - public Plane(@NotNull LiveSignTileEntity licence, boolean isFrontOfSign, @NotNull ShipType type) { @@ -159,7 +144,7 @@ public boolean shouldFall() { return false; } Collection furnaceInventories = new HashSet<>(); - for (SyncBlockPosition loc : this.getStructure().getSyncedPositionsRelativeToWorld()) { + for (SyncBlockPosition loc : this.getStructure().getPositionsRelativeToWorld().collect(Collectors.toList())) { BlockSnapshot snapshot = loc.getBlockDetails(); Optional> opTiled = snapshot.get(KeyedData.TILED_ENTITY); if (opTiled.isPresent()) { diff --git a/src/main/java/org/ships/vessel/common/types/typical/plane/PlaneType.java b/src/main/java/org/ships/vessel/common/types/typical/plane/PlaneType.java index b352bbea..dd72dbcd 100644 --- a/src/main/java/org/ships/vessel/common/types/typical/plane/PlaneType.java +++ b/src/main/java/org/ships/vessel/common/types/typical/plane/PlaneType.java @@ -42,7 +42,7 @@ public PlaneType() { public PlaneType(String name, File file) { this(ShipsPlugin.getPlugin(), name, - TranslateCore.createConfigurationFile(file, TranslateCore.getPlatform().getConfigFormat()), + TranslateCore.getConfigManager().read(file, TranslateCore.getPlatform().getConfigFormat()), BlockTypes.AIR); } diff --git a/src/main/java/org/ships/vessel/common/types/typical/submarine/Submarine.java b/src/main/java/org/ships/vessel/common/types/typical/submarine/Submarine.java index 0628490d..ec302d28 100644 --- a/src/main/java/org/ships/vessel/common/types/typical/submarine/Submarine.java +++ b/src/main/java/org/ships/vessel/common/types/typical/submarine/Submarine.java @@ -40,18 +40,6 @@ public class Submarine extends AbstractShipsVessel implements UnderWaterType, Ve Parser.STRING_TO_ITEM_TYPE, "Block", "Fuel", "Types"); private final Collection> requirements = new HashSet<>(); - @Deprecated(forRemoval = true) - public Submarine(ShipType type, LiveTileEntity licence) throws NoLicencePresent { - super(licence, type); - this.initRequirements(); - } - - @Deprecated(forRemoval = true) - public Submarine(ShipType type, SignTileEntity ste, SyncBlockPosition position) { - super(ste, position, type); - this.initRequirements(); - } - public Submarine(@NotNull LiveSignTileEntity licence, boolean isFrontOfSign, @NotNull ShipType type) { diff --git a/src/main/java/org/ships/vessel/common/types/typical/watership/WaterShip.java b/src/main/java/org/ships/vessel/common/types/typical/watership/WaterShip.java index c5e9536b..95fa1c78 100644 --- a/src/main/java/org/ships/vessel/common/types/typical/watership/WaterShip.java +++ b/src/main/java/org/ships/vessel/common/types/typical/watership/WaterShip.java @@ -8,14 +8,11 @@ import org.core.world.direction.FourFacingDirection; import org.core.world.position.block.BlockType; import org.core.world.position.block.BlockTypes; -import org.core.world.position.block.entity.LiveTileEntity; import org.core.world.position.block.entity.sign.LiveSignTileEntity; import org.core.world.position.block.entity.sign.SignSide; -import org.core.world.position.block.entity.sign.SignTileEntity; import org.core.world.position.impl.sync.SyncBlockPosition; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.ships.exceptions.NoLicencePresent; import org.ships.vessel.common.assits.Fallable; import org.ships.vessel.common.assits.FileBasedVessel; import org.ships.vessel.common.assits.VesselRequirement; @@ -31,6 +28,7 @@ import org.ships.vessel.common.types.typical.AbstractShipsVessel; import java.util.*; +import java.util.stream.Collectors; public class WaterShip extends AbstractShipsVessel implements WaterType, Fallable, VesselRequirement { @@ -41,20 +39,6 @@ public class WaterShip extends AbstractShipsVessel implements WaterType, Fallabl private final Collection> requirements = new HashSet<>(); - @Deprecated(forRemoval = true) - public WaterShip(ShipType type, LiveTileEntity licence) throws NoLicencePresent { - super(licence, type); - this.flags.add(new AltitudeLockFlag(true)); - this.initRequirements(); - } - - @Deprecated(forRemoval = true) - public WaterShip(ShipType type, SignTileEntity ste, SyncBlockPosition position) { - super(ste, position, type); - this.flags.add(new AltitudeLockFlag(true)); - this.initRequirements(); - } - public WaterShip(@NotNull LiveSignTileEntity licence, boolean isFrontOfSign, @NotNull ShipType type) { @@ -188,7 +172,10 @@ public boolean isMinSizeSpecified() { public boolean shouldFall() { int specialBlockCount = 0; boolean inWater = false; - for (SyncBlockPosition blockPosition : this.getStructure().getSyncedPositionsRelativeToWorld()) { + for (SyncBlockPosition blockPosition : this + .getStructure() + .getPositionsRelativeToWorld() + .collect(Collectors.toList())) { if (this.getSpecialBlocks().stream().anyMatch(b -> b.equals(blockPosition.getBlockType()))) { specialBlockCount++; } @@ -201,10 +188,7 @@ public boolean shouldFall() { if (!inWater) { return true; } - float specialBlockPercent = ((specialBlockCount * 100.0f) / this - .getStructure() - .getOriginalRelativePositionsToCenter() - .size()); + float specialBlockPercent = ((specialBlockCount * 100.0f) / this.getStructure().size()); return (!(this.getSpecialBlockPercent() == 0) || !(specialBlockPercent <= this.getSpecialBlockPercent())); } } diff --git a/src/main/java/org/ships/vessel/common/types/typical/watership/WaterShipType.java b/src/main/java/org/ships/vessel/common/types/typical/watership/WaterShipType.java index e1742c77..f1df460e 100644 --- a/src/main/java/org/ships/vessel/common/types/typical/watership/WaterShipType.java +++ b/src/main/java/org/ships/vessel/common/types/typical/watership/WaterShipType.java @@ -1,14 +1,14 @@ package org.ships.vessel.common.types.typical.watership; -import org.array.utils.ArrayUtils; import org.core.TranslateCore; import org.core.config.ConfigurationStream; import org.core.permission.CorePermission; import org.core.platform.plugin.Plugin; +import org.core.utils.Identifiable; import org.core.world.position.block.BlockType; import org.core.world.position.block.BlockTypes; import org.core.world.position.block.entity.sign.SignSide; -import org.core.world.position.block.grouptype.versions.BlockGroups1V13; +import org.core.world.position.block.grouptype.BlockGroups; import org.core.world.position.impl.sync.SyncBlockPosition; import org.jetbrains.annotations.NotNull; import org.ships.permissions.Permissions; @@ -19,28 +19,27 @@ import org.ships.vessel.common.requirement.MinSizeRequirement; import org.ships.vessel.common.requirement.Requirement; import org.ships.vessel.common.requirement.SpecialBlocksRequirement; -import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import org.ships.vessel.common.types.typical.AbstractShipType; import java.io.File; import java.util.Collection; +import java.util.Comparator; import java.util.List; +import java.util.stream.Collectors; public class WaterShipType extends AbstractShipType implements CloneableShipType, SpecialBlocksShipType { public static final String NAME = "Ship"; + private final int minSize; private CorePermission moveOwnPermission = Permissions.WATERSHIP_MOVE_OWN; private CorePermission moveOtherPermission = Permissions.WATERSHIP_MOVE_OTHER; private CorePermission makePermission = Permissions.WATERSHIP_MAKE; - - private SpecialBlocksRequirement specialBlocksRequirement; private MinSizeRequirement minSizeRequirement; private MaxSizeRequirement maxSizeRequirement; - private Integer maxSize; - private int minSize; public WaterShipType() { this(NAME, new File(ShipsPlugin.getPlugin().getConfigFolder(), @@ -61,7 +60,7 @@ public WaterShipType(@NotNull Plugin plugin, @NotNull ConfigurationStream.ConfigurationFile file, BlockType... types) { super(plugin, displayName, file, types); - file.getInteger(MaxSizeRequirement.MAX_SIZE).ifPresent(v -> maxSize = v); + file.getInteger(MaxSizeRequirement.MAX_SIZE).ifPresent(v -> this.maxSize = v); this.minSize = file.getInteger(MinSizeRequirement.MIN_SIZE, 0); if (!(plugin.equals(ShipsPlugin.getPlugin()) && displayName.equals(NAME))) { String pluginId = plugin.getPluginId(); @@ -103,7 +102,11 @@ protected void createDefault(@NotNull ConfigurationStream.ConfigurationFile file this.file.set(MAX_SPEED, 10); this.file.set(ALTITUDE_SPEED, 5); this.file.set(SPECIAL_BLOCK_PERCENT, 25); - this.file.set(SPECIAL_BLOCK_TYPE, ArrayUtils.ofSet(BlockGroups1V13.WOOL.getGrouped())); + this.file.set(SPECIAL_BLOCK_TYPE, BlockGroups.WOOL + .get() + .getBlocks() + .sorted(Comparator.comparing(Identifiable::getId)) + .collect(Collectors.toList())); } @Override @@ -128,7 +131,7 @@ public CloneableShipType cloneWithName(@NotNull File file, @NotNull S @Override public CloneableShipType getOriginType() { - return ShipType.WATERSHIP; + return ShipTypes.WATERSHIP; } @Override diff --git a/src/main/java/org/ships/vessel/converts/ShipsConverters.java b/src/main/java/org/ships/vessel/converts/ShipsConverters.java new file mode 100644 index 00000000..c7eae882 --- /dev/null +++ b/src/main/java/org/ships/vessel/converts/ShipsConverters.java @@ -0,0 +1,30 @@ +package org.ships.vessel.converts; + +import org.jetbrains.annotations.UnmodifiableView; +import org.ships.vessel.converts.vessel.shipsfive.Ships5VesselConverter; + +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.LinkedTransferQueue; + +public final class ShipsConverters { + + private static final Collection> registered = new LinkedTransferQueue<>(); + + public static Ships5VesselConverter SHIPS_FIVE_CONVERTER = register(new Ships5VesselConverter()); + + private ShipsConverters() { + throw new RuntimeException("Do not create"); + } + + public static > C register(C converter){ + registered.add(converter); + return converter; + } + + @UnmodifiableView + public static Collection> converters(){ + return Collections.unmodifiableCollection(registered); + } + +} diff --git a/src/main/java/org/ships/vessel/converts/vessel/shipsfive/Ships5VesselConverter.java b/src/main/java/org/ships/vessel/converts/vessel/shipsfive/Ships5VesselConverter.java index eb6f5e11..fded75ae 100644 --- a/src/main/java/org/ships/vessel/converts/vessel/shipsfive/Ships5VesselConverter.java +++ b/src/main/java/org/ships/vessel/converts/vessel/shipsfive/Ships5VesselConverter.java @@ -12,9 +12,12 @@ import org.ships.permissions.vessel.CrewPermission; import org.ships.plugin.ShipsPlugin; import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import org.ships.vessel.common.types.typical.ShipsVessel; import org.ships.vessel.common.types.typical.airship.Airship; import org.ships.vessel.converts.vessel.VesselConverter; +import org.ships.vessel.sign.LicenceSign; +import org.ships.vessel.sign.ShipsSigns; import java.io.File; import java.io.IOException; @@ -61,11 +64,14 @@ public class Ships5VesselConverter implements VesselConverter { if (!(lte instanceof LiveSignTileEntity)) { throw new IOException("Unable to locate licence sign"); } - LiveSignTileEntity lste = (LiveSignTileEntity)lte; + LiveSignTileEntity lste = (LiveSignTileEntity) lte; + var side = ShipsSigns.LICENCE + .getSide(lste) + .orElseThrow(() -> new IOException("Unable to read side of licence sign")); ShipsVessel vessel; switch (type) { case "Airship": - vessel = ShipType.AIRSHIP.createNewVessel(lste); + vessel = ShipTypes.AIRSHIP.createNewVessel(side, lste.getPosition()); if (consumption != null) { ((Airship) vessel).setFuelConsumption(consumption); } diff --git a/src/main/java/org/ships/vessel/sign/AltitudeSign.java b/src/main/java/org/ships/vessel/sign/AltitudeSign.java index 297b2c5c..efeb3ffe 100644 --- a/src/main/java/org/ships/vessel/sign/AltitudeSign.java +++ b/src/main/java/org/ships/vessel/sign/AltitudeSign.java @@ -37,6 +37,7 @@ import java.util.List; import java.util.Optional; import java.util.function.BiConsumer; +import java.util.stream.Collectors; public class AltitudeSign implements ShipsSign { @@ -53,7 +54,7 @@ public class AltitudeSign implements ShipsSign { @Override public boolean isSign(List lines) { - return lines.size() >= 1 && ComponentUtils + return !lines.isEmpty() && ComponentUtils .toPlain(lines.get(0)) .equalsIgnoreCase(ComponentUtils.toPlain(SIGN.get(0))); } @@ -96,7 +97,7 @@ public boolean onPrimaryClick(@NotNull LivePlayer player, @NotNull SyncBlockPosi player.sendMessage(Component.text("could not find the licence sign").color(NamedTextColor.RED)); entry .getKey() - .getSyncedPositionsRelativeToWorld() + .getPositionsRelativeToWorld() .forEach(bp -> bp.setBlock(BlockTypes.BEDROCK.getDefaultBlockDetails(), player)); TranslateCore .getScheduleManager() @@ -106,7 +107,7 @@ public boolean onPrimaryClick(@NotNull LivePlayer player, @NotNull SyncBlockPosi .setDelayUnit(TimeUnit.SECONDS) .setRunner((sch) -> entry .getKey() - .getSyncedPositionsRelativeToWorld() + .getPositionsRelativeToWorld() .forEach(bp -> bp.resetBlock(player))) .buildDelayed(ShipsPlugin.getPlugin()) .run(); @@ -169,7 +170,7 @@ public boolean onSecondClick(@NotNull LivePlayer player, @NotNull SyncBlockPosit ShipsPlugin.getPlugin().getLockedSignManager().lock(position); VesselBlockFinder.findOvertime(position, (currentStructure, block) -> { - int foundBlocks = currentStructure.getOriginalRelativePositionsToCenter().size() + 1; + int foundBlocks = currentStructure.size() + 1; int newTotal = Math.max(blockLimit, foundBlocks); if (finalBar != null) { finalBar.name(Component.text(foundBlocks + "/" + newTotal)); @@ -184,7 +185,10 @@ public boolean onSecondClick(@NotNull LivePlayer player, @NotNull SyncBlockPosit entry.getValue().get()); return; } - Collection foundStructure = entry.getKey().getSyncedPositionsRelativeToWorld(); + Collection foundStructure = entry + .getKey() + .getPositionsRelativeToWorld() + .collect(Collectors.toList()); foundStructure.forEach(bp -> bp.setBlock(BlockTypes.BEDROCK.getDefaultBlockDetails(), player)); TranslateCore .getScheduleManager() diff --git a/src/main/java/org/ships/vessel/sign/LicenceSign.java b/src/main/java/org/ships/vessel/sign/LicenceSign.java index de3e616d..0860214f 100644 --- a/src/main/java/org/ships/vessel/sign/LicenceSign.java +++ b/src/main/java/org/ships/vessel/sign/LicenceSign.java @@ -1,21 +1,20 @@ package org.ships.vessel.sign; +import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import org.core.TranslateCore; -import org.core.adventureText.AText; -import org.core.adventureText.format.NamedTextColours; import org.core.config.ConfigurationStream; import org.core.entity.living.human.player.LivePlayer; import org.core.schedule.unit.TimeUnit; +import org.core.utils.BarUtils; import org.core.utils.ComponentUtils; -import org.core.world.boss.ServerBossBar; +import org.core.vector.type.Vector3; import org.core.world.position.block.BlockTypes; import org.core.world.position.block.entity.LiveTileEntity; import org.core.world.position.block.entity.sign.LiveSignTileEntity; import org.core.world.position.block.entity.sign.SignSide; import org.core.world.position.block.entity.sign.SignTileEntity; -import org.core.world.position.impl.BlockPosition; import org.core.world.position.impl.sync.SyncBlockPosition; import org.core.world.position.impl.sync.SyncPosition; import org.jetbrains.annotations.NotNull; @@ -30,6 +29,7 @@ import org.ships.vessel.common.finder.ShipsSignVesselFinder; import org.ships.vessel.common.loader.shipsvessel.ShipsFileLoader; import org.ships.vessel.common.types.ShipType; +import org.ships.vessel.common.types.ShipTypes; import org.ships.vessel.common.types.Vessel; import org.ships.vessel.common.types.typical.ShipsVessel; import org.ships.vessel.structure.PositionableShipsStructure; @@ -43,24 +43,24 @@ public class LicenceSign implements ShipsSign { - private static class VesselStructureUpdate implements OvertimeBlockFinderUpdate { + private final static class VesselStructureUpdate implements OvertimeBlockFinderUpdate { - private final @Nullable ServerBossBar finalBar; + private final @Nullable BossBar finalBar; private final int totalBlockCount; - private VesselStructureUpdate(int totalBlockCount, @Nullable ServerBossBar bossBar) { + private VesselStructureUpdate(int totalBlockCount, @Nullable BossBar bossBar) { this.finalBar = bossBar; this.totalBlockCount = totalBlockCount; } @Override public OvertimeBlockFinderUpdate.BlockFindControl onBlockFind(@NotNull PositionableShipsStructure currentStructure, - @NotNull BlockPosition block) { + @NotNull Vector3 block) { if (this.finalBar != null) { - int blockCount = currentStructure.getOriginalRelativePositionsToCenter().size() + 1; - this.finalBar.setTitle(AText.ofPlain(blockCount + "/" + this.totalBlockCount)); + float blockCount = currentStructure.size() + 1; + this.finalBar.name(Component.text(blockCount + "/" + this.totalBlockCount)); try { - this.finalBar.setValue(blockCount, this.totalBlockCount); + this.finalBar.progress(this.totalBlockCount / blockCount); } catch (IllegalArgumentException ignore) { } @@ -83,22 +83,20 @@ public Optional getShip(SignTileEntity entity) { @Override public boolean isSign(List lines) { - return lines.size() >= 1 && ComponentUtils.toPlain(lines.get(0)).equalsIgnoreCase("[Ships]"); + return !lines.isEmpty() && "[Ships]".equalsIgnoreCase(ComponentUtils.toPlain(lines.get(0))); } @Override public void changeInto(@NotNull SignSide sign) throws IOException { List lines = sign.getLines(); - Optional> opType = ShipsPlugin - .getPlugin() - .getAllShipTypes() + Optional> opType = ShipTypes + .shipTypes() .stream() .filter(t -> ComponentUtils.toPlain(lines.get(1)).equalsIgnoreCase(t.getDisplayName())) .findFirst(); if (opType.isEmpty()) { - throw new IOException("Unknown Ship Type: Ship Types: " + ShipsPlugin - .getPlugin() - .getAllShipTypes() + throw new IOException("Unknown Ship Type: Ship Types: " + ShipTypes + .shipTypes() .stream() .map(ShipType::getDisplayName) .collect(Collectors.joining(", "))); @@ -136,7 +134,8 @@ public boolean onPrimaryClick(@NotNull LivePlayer player, @NotNull SyncBlockPosi } catch (UnableToFindLicenceSign e1) { Collection foundStructure = e1 .getFoundStructure() - .getSyncedPositionsRelativeToWorld(); + .getPositionsRelativeToWorld() + .collect(Collectors.toList()); foundStructure.forEach(bp -> bp.setBlock(BlockTypes.BEDROCK.getDefaultBlockDetails(), player)); TranslateCore .getScheduleManager() @@ -149,53 +148,52 @@ public boolean onPrimaryClick(@NotNull LivePlayer player, @NotNull SyncBlockPosi return true; } catch (IOException e) { Optional opTile = position.getTileEntity(); - if (opTile.isPresent()) { - if (opTile.get() instanceof LiveSignTileEntity) { - SignTileEntity lste = (SignTileEntity) opTile.get(); - String type = lste.getTextAt(1).map(AText::toPlain).orElse(""); - String name = lste.getTextAt(2).map(AText::toPlain).orElse(""); - Optional> opType = ShipsPlugin - .getPlugin() - .getAllShipTypes() - .stream() - .filter(t -> t.getDisplayName().equalsIgnoreCase(type)) - .findAny(); - if (opType.isEmpty()) { - player.sendMessage(AText - .ofPlain("Could not find ShipType with display name of " + type) - .withColour(NamedTextColours.RED)); - return false; - } - File file = new File(TranslateCore.getPlatform().getPlatformConfigFolder(), - "VesselData/" + opType.get().getId().replaceAll(":", ".") + "/" + name + "." - + TranslateCore.getPlatform().getConfigFormat().getFileType()[0]); - if (!file.exists()) { - player.sendMessage(AText - .ofPlain("Could not find the file associated with the ship") - .withColour(NamedTextColours.RED)); - return false; - } - ConfigurationStream.ConfigurationFile config = TranslateCore.createConfigurationFile(file, - TranslateCore - .getPlatform() - .getConfigFormat()); - config.set(ShipsFileLoader.META_LOCATION_X, position.getX()); - config.set(ShipsFileLoader.META_LOCATION_Y, position.getY()); - config.set(ShipsFileLoader.META_LOCATION_Z, position.getZ()); - config.set(ShipsFileLoader.META_LOCATION_WORLD, position.getWorld()); - config.save(); - try { - ShipsVessel vessel = new ShipsFileLoader(file).load(); - ShipsPlugin.getPlugin().registerVessel(vessel); - player.sendMessage(AText.ofPlain("Ship has resynced")); - } catch (LoadVesselException loadVesselException) { - player.sendMessage(AText.ofPlain(loadVesselException.getReason())); - return false; - } - return true; - } + Optional opSide = opTile + .filter(lte -> lte instanceof LiveSignTileEntity) + .flatMap(lste -> this.getSide((SignTileEntity) lste)); + if (opSide.isEmpty()) { + player.sendMessage(Component.text(e.getMessage()).color(NamedTextColor.RED)); + return true; + } + SignSide side = opSide.get(); + + String type = side.getLineAt(1).map(ComponentUtils::toPlain).orElse(""); + String name = side.getLineAt(2).map(ComponentUtils::toPlain).orElse(""); + Optional> opType = ShipTypes + .shipTypes() + .stream() + .filter(t -> t.getDisplayName().equalsIgnoreCase(type)) + .findAny(); + if (opType.isEmpty()) { + player.sendMessage(Component + .text("Could not find ShipType with display name of " + type) + .color(NamedTextColor.RED)); + return false; + } + File file = new File(TranslateCore.getPlatform().getPlatformConfigFolder(), + "VesselData/" + opType.get().getId().replaceAll(":", ".") + "/" + name + "." + + TranslateCore.getPlatform().getConfigFormat().getFileType()[0]); + if (!file.exists()) { + player.sendMessage( + Component.text("Could not find the file associated with the ship").color(NamedTextColor.RED)); + return false; + } + ConfigurationStream.ConfigurationFile config = TranslateCore + .getConfigManager() + .read(file, TranslateCore.getPlatform().getConfigFormat()); + config.set(ShipsFileLoader.META_LOCATION_X, position.getX()); + config.set(ShipsFileLoader.META_LOCATION_Y, position.getY()); + config.set(ShipsFileLoader.META_LOCATION_Z, position.getZ()); + config.set(ShipsFileLoader.META_LOCATION_WORLD, position.getWorld()); + config.save(); + try { + ShipsVessel vessel = new ShipsFileLoader(file).load(); + ShipsPlugin.getPlugin().registerVessel(vessel); + player.sendMessage(Component.text("Ship has resynced")); + } catch (LoadVesselException loadVesselException) { + player.sendMessage(ComponentUtils.fromPlain(loadVesselException.getReason())); + return false; } - player.sendMessage(AText.ofPlain(e.getMessage()).withColour(NamedTextColours.RED)); return true; } } @@ -218,20 +216,21 @@ private void displayInfo(@NotNull LivePlayer player, @NotNull SyncPosition { - int originalSize = structure.getOriginalRelativePositionsToCenter().size(); + int originalSize = structure.size(); s.save(); - player.sendMessage(AText.ofPlain( - "Vessel structure has updated by " + (structure.getOriginalRelativePositionsToCenter().size() - - originalSize))); + player.sendMessage( + Component.text("Vessel structure has updated by " + (structure.size() - originalSize))); if (finalBar != null) { - finalBar.deregisterPlayers(); + BarUtils.getPlayers(finalBar).forEach(play -> play.hideBossBar(finalBar)); } }); } diff --git a/src/main/java/org/ships/vessel/sign/MoveSign.java b/src/main/java/org/ships/vessel/sign/MoveSign.java index 20ab80ed..44c79294 100644 --- a/src/main/java/org/ships/vessel/sign/MoveSign.java +++ b/src/main/java/org/ships/vessel/sign/MoveSign.java @@ -30,6 +30,7 @@ import java.util.Collection; import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; import java.util.stream.IntStream; public class MoveSign implements ShipsSign { @@ -42,7 +43,7 @@ public List getSignText() { @Override public boolean isSign(List lines) { - return lines.size() >= 1 && ComponentUtils + return !lines.isEmpty() && ComponentUtils .toPlain(lines.get(0)) .equalsIgnoreCase(ComponentUtils.toPlain(this.getSignText().get(0))); } @@ -62,7 +63,7 @@ public boolean onPrimaryClick(@NotNull LivePlayer player, @NotNull SyncBlockPosi if (!(lte instanceof LiveSignTileEntity)) { return false; } - LiveSignTileEntity lste = (LiveSignTileEntity)lte; + LiveSignTileEntity lste = (LiveSignTileEntity) lte; String defaultSpeed = ShipsPlugin.getPlugin().getConfig().getDefaultMoveSpeed() + ""; String name = this .getSide(lste) @@ -89,7 +90,10 @@ public boolean onPrimaryClick(@NotNull LivePlayer player, @NotNull SyncBlockPosi } player.sendMessage(Component.text("Could not find [Ships] sign").color(NamedTextColor.RED)); ShipsPlugin.getPlugin().getLockedSignManager().unlock(position); - Collection positions = entry.getKey().getSyncedPositionsRelativeToWorld(); + Collection positions = entry + .getKey() + .getPositionsRelativeToWorld() + .collect(Collectors.toList()); positions.forEach(bp -> bp.setBlock(BlockTypes.BEDROCK.getDefaultBlockDetails(), player)); TranslateCore .getScheduleManager() @@ -169,8 +173,13 @@ private void onVesselMove(Messageable player, ShipsPlugin.getPlugin().getLockedSignManager().unlock(position); player.sendMessage( Component.text("Speed error: Your ship cannot move that fast").color(NamedTextColor.RED)); - if (builder.getBossBar() != null) { - builder.getBossBar().deregisterPlayers(); + if (builder.getAdventureBossBar() != null) { + position + .getWorld() + .getLiveEntities() + .filter(p -> p instanceof LivePlayer) + .map(p -> (LivePlayer) p) + .forEach(p -> p.hideBossBar(builder.getAdventureBossBar())); } return; } @@ -181,14 +190,19 @@ private void onVesselMove(Messageable player, .text("Unknown error: " + position.getBlockType().getId() + " is not " + "directional") .color(NamedTextColor.RED)); - if (builder.getBossBar() != null) { - builder.getBossBar().deregisterPlayers(); + if (builder.getAdventureBossBar() != null) { + position + .getWorld() + .getLiveEntities() + .filter(p -> p instanceof LivePlayer) + .map(p -> (LivePlayer) p) + .forEach(p -> p.hideBossBar(builder.getAdventureBossBar())); } return; } Direction originalDirection = opDirectional.get().getDirection(); if (originalDirection instanceof SixteenFacingDirection) { - SixteenFacingDirection sixteenFacingDir = (SixteenFacingDirection)originalDirection; + SixteenFacingDirection sixteenFacingDir = (SixteenFacingDirection) originalDirection; originalDirection = sixteenFacingDir.normal(); } Vector3 direction = originalDirection.getOpposite().getAsVector().multiply(speed); diff --git a/src/main/java/org/ships/vessel/sign/ShipsSign.java b/src/main/java/org/ships/vessel/sign/ShipsSign.java index 4bd4d09b..6a4c8e8d 100644 --- a/src/main/java/org/ships/vessel/sign/ShipsSign.java +++ b/src/main/java/org/ships/vessel/sign/ShipsSign.java @@ -23,7 +23,7 @@ public interface ShipsSign extends Identifiable { boolean onSecondClick(@NotNull LivePlayer player, @NotNull SyncBlockPosition position); default boolean isSign(@NotNull SignTileEntity entity) { - return getSide(entity).isPresent(); + return this.getSide(entity).isPresent(); } default Optional getSide(SignTileEntity entity) { diff --git a/src/main/java/org/ships/vessel/sign/ShipsSigns.java b/src/main/java/org/ships/vessel/sign/ShipsSigns.java new file mode 100644 index 00000000..b44f4fc8 --- /dev/null +++ b/src/main/java/org/ships/vessel/sign/ShipsSigns.java @@ -0,0 +1,35 @@ +package org.ships.vessel.sign; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.UnmodifiableView; + +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.LinkedTransferQueue; + +public final class ShipsSigns { + + private static final @NotNull Collection registered = new LinkedTransferQueue<>(); + + public static final AltitudeSign ALTITUDE = register(new AltitudeSign()); + public static final EOTSign EOT = register(new EOTSign()); + public static final LicenceSign LICENCE = register(new LicenceSign()); + public static final WheelSign WHEEL = register(new WheelSign()); + public static final MoveSign MOVE = register(new MoveSign()); + + private ShipsSigns() { + throw new RuntimeException("Do not create"); + } + + + private static T register(@NotNull T shipType) { + registered.add(shipType); + return shipType; + } + + @UnmodifiableView + public static Collection signs() { + return Collections.unmodifiableCollection(registered); + } + +} diff --git a/src/main/java/org/ships/vessel/sign/SignUtil.java b/src/main/java/org/ships/vessel/sign/SignUtil.java index afed3113..805105aa 100644 --- a/src/main/java/org/ships/vessel/sign/SignUtil.java +++ b/src/main/java/org/ships/vessel/sign/SignUtil.java @@ -9,14 +9,14 @@ import org.core.entity.living.human.player.LivePlayer; import org.core.schedule.unit.TimeUnit; import org.core.utils.BarUtils; +import org.core.vector.type.Vector3; import org.core.world.position.block.BlockTypes; -import org.core.world.position.impl.BlockPosition; import org.core.world.position.impl.Position; import org.core.world.position.impl.sync.SyncBlockPosition; import org.jetbrains.annotations.Nullable; import org.ships.algorthum.blockfinder.OvertimeBlockFinderUpdate; import org.ships.config.configuration.ShipsConfig; -import org.ships.config.messages.AdventureMessageConfig; +import org.ships.config.messages.Messages; import org.ships.exceptions.load.LoadVesselException; import org.ships.exceptions.load.UnableToFindLicenceSign; import org.ships.exceptions.move.MoveException; @@ -33,6 +33,8 @@ import java.util.Map; import java.util.Optional; import java.util.function.BiConsumer; +import java.util.function.Supplier; +import java.util.stream.Stream; public interface SignUtil { @@ -62,12 +64,12 @@ protected void onStructureUpdate(Vessel vessel) { @Override protected OvertimeBlockFinderUpdate.BlockFindControl onBlockFind(PositionableShipsStructure currentStructure, - BlockPosition block) { + Vector3 block) { var bossBar = this.context.getAdventureBossBar(); if (bossBar == null) { return OvertimeBlockFinderUpdate.BlockFindControl.USE; } - int foundBlocks = currentStructure.getOriginalRelativePositionsToCenter().size() + 1; + int foundBlocks = currentStructure.size() + 1; int trackLimit = Math.max(foundBlocks, this.trackLimit); float progress = foundBlocks / (float) trackLimit; progress = progress / 100; @@ -83,26 +85,26 @@ protected void onExceptionThrown(LoadVesselException e) { if (bar != null) { BarUtils.getPlayers(bar).forEach(player -> player.hideBossBar(bar)); } - if (!(e instanceof UnableToFindLicenceSign)) { + if (e instanceof UnableToFindLicenceSign) { this.player.sendMessage(Component.text(e.getReason()).color(NamedTextColor.RED)); + UnableToFindLicenceSign e1 = (UnableToFindLicenceSign) e; + this.showPlayer(() -> e1 + .getFoundStructure() + .getPositionsRelativeToWorld()); return; } - UnableToFindLicenceSign e1 = (UnableToFindLicenceSign) e; - this.player.sendMessage(Component.text(e1.getReason()).color(NamedTextColor.RED)); - e1 - .getFoundStructure() - .getSyncedPositionsRelativeToWorld() - .forEach(bp -> bp.setBlock(BlockTypes.BEDROCK.getDefaultBlockDetails(), this.player)); + this.player.sendMessage(Component.text(e.getReason()).color(NamedTextColor.RED)); + } + + private void showPlayer(Supplier> toShow) { + toShow.get().forEach(bp -> bp.setBlock(BlockTypes.BEDROCK.getDefaultBlockDetails(), this.player)); TranslateCore .getScheduleManager() .schedule() .setDelay(5) .setDisplayName("bedrock reset") .setDelayUnit(TimeUnit.SECONDS) - .setRunner((sch) -> e1 - .getFoundStructure() - .getSyncedPositionsRelativeToWorld() - .forEach(bp -> bp.resetBlock(this.player))) + .setRunner((sch) -> toShow.get().forEach(bp -> bp.resetBlock(this.player))) .buildDelayed(ShipsPlugin.getPlugin()) .run(); } @@ -137,7 +139,7 @@ private static boolean checkCrewVessel(Vessel vessel, return false; } - Component permissionMessage = AdventureMessageConfig.ERROR_PERMISSION_MISS_MATCH.processMessage( + Component permissionMessage = Messages.ERROR_PERMISSION_MISS_MATCH.processMessage( Map.entry(player, stored.getType().getMoveOtherPermission().getPermissionValue())); player.sendMessage(permissionMessage); ShipsPlugin.getPlugin().getLockedSignManager().unlock(position); @@ -165,7 +167,7 @@ static void postMovementReady(MovementDetailsBuilder details, } ShipsPlugin.getPlugin().getLockedSignManager().unlock(position); if (exc instanceof MoveException) { - MoveException e = (MoveException)exc; + MoveException e = (MoveException) exc; player.sendMessage(e.getErrorMessage()); } context @@ -200,9 +202,8 @@ static void onMovement(SyncBlockPosition sign, LivePlayer player, MovementReady .filter(vessel -> vessel.getStructure().getBounds().contains(sign.getPosition())) .filter(vessel -> vessel .getStructure() - .getAsyncedPositionsRelativeToWorld() - .parallelStream() - .anyMatch(pos -> pos.getPosition().equals(sign.getPosition()))) + .getVectorsRelativeToWorld() + .anyMatch(pos -> pos.equals(sign.getPosition()))) .findAny(); if (opVessel.isPresent()) { new OnOvertimeAutoUpdate(sign, builder, player, movement, diff --git a/src/main/java/org/ships/vessel/sign/WheelSign.java b/src/main/java/org/ships/vessel/sign/WheelSign.java index 959738bc..be620ae7 100644 --- a/src/main/java/org/ships/vessel/sign/WheelSign.java +++ b/src/main/java/org/ships/vessel/sign/WheelSign.java @@ -21,7 +21,7 @@ public class WheelSign implements ShipsSign { @Override public boolean isSign(List lines) { - return lines.size() >= 1 && ComponentUtils + return !lines.isEmpty() && ComponentUtils .toPlain(lines.get(0)) .equalsIgnoreCase(ComponentUtils.toPlain(SIGN.get(0))); diff --git a/src/main/java/org/ships/vessel/structure/AbstractPositionableShipsStructure.java b/src/main/java/org/ships/vessel/structure/AbstractPositionableShipsStructure.java index df61203e..60af44d5 100644 --- a/src/main/java/org/ships/vessel/structure/AbstractPositionableShipsStructure.java +++ b/src/main/java/org/ships/vessel/structure/AbstractPositionableShipsStructure.java @@ -1,24 +1,27 @@ package org.ships.vessel.structure; -import org.core.TranslateCore; import org.core.exceptions.DirectionNotSupported; -import org.core.schedule.unit.TimeUnit; import org.core.utils.Bounds; +import org.core.vector.RangeVectorSpliterator; import org.core.vector.type.Vector3; import org.core.world.WorldExtent; import org.core.world.direction.Direction; import org.core.world.direction.FourFacingDirection; import org.core.world.position.block.BlockTypes; +import org.core.world.position.block.entity.LiveTileEntity; +import org.core.world.position.block.entity.sign.LiveSignTileEntity; import org.core.world.position.impl.BlockPosition; import org.core.world.position.impl.Position; import org.core.world.position.impl.sync.SyncBlockPosition; +import org.core.world.position.impl.sync.SyncPosition; import org.jetbrains.annotations.NotNull; -import org.ships.plugin.ShipsPlugin; +import org.ships.vessel.sign.ShipsSign; import java.util.*; -import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedTransferQueue; import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; public class AbstractPositionableShipsStructure implements PositionableShipsStructure { @@ -27,6 +30,7 @@ public class AbstractPositionableShipsStructure implements PositionableShipsStru private final Collection> outsideEast = new LinkedTransferQueue<>(); private final Collection> outsideSouth = new LinkedTransferQueue<>(); private final Collection> outsideWest = new LinkedTransferQueue<>(); + private final Collection> tileEntityVectors = new LinkedTransferQueue<>(); private SyncBlockPosition position; private Bounds cachedBounds; @@ -36,6 +40,7 @@ public AbstractPositionableShipsStructure(SyncBlockPosition position) { this.position = position; } + public boolean isEmpty() { if (!this.vectors.isEmpty()) { return false; @@ -60,73 +65,47 @@ public SyncBlockPosition getPosition() { @Override public PositionableShipsStructure setPosition(@NotNull SyncBlockPosition pos) { this.position = pos; + this.cachedBounds = null; return this; } @Override - public Collection> getOutsidePositionsRelativeToCenter(@NotNull FourFacingDirection direction) { + public Stream> getOutsideVectorsRelativeToLicence(@NotNull FourFacingDirection direction) { if (direction.equals(FourFacingDirection.EAST)) { - return Collections.unmodifiableCollection(this.outsideEast); + return this.outsideEast.stream(); } if (direction.equals(FourFacingDirection.WEST)) { - return Collections.unmodifiableCollection(this.outsideWest); + return this.outsideWest.stream(); } if (direction.equals(FourFacingDirection.NORTH)) { - return Collections.unmodifiableCollection(this.outsideNorth); + return this.outsideNorth.stream(); } if (direction.equals(FourFacingDirection.SOUTH)) { - return Collections.unmodifiableCollection(this.outsideSouth); + return this.outsideSouth.stream(); } throw new RuntimeException("Unknown direction of " + direction.getName()); } @Override - public CompletableFuture fillAir() { - CompletableFuture future = new CompletableFuture<>(); - Bounds bounds = this.getBounds(); - Vector3 max = bounds.getIntMax(); - Vector3 min = bounds.getIntMin(); - WorldExtent world = this.getPosition().getWorld(); - TranslateCore - .getScheduleManager() - .schedule() - .setDisplayName("Air getter") - .setDelay(0) - .setDelayUnit(TimeUnit.MINECRAFT_TICKS) - .setAsync(true) - .setRunner((scheduler -> { - for (int x = min.getX(); x < max.getX(); x++) { - for (int y = min.getY(); y < max.getY(); y++) { - for (int z = min.getZ(); z < max.getZ(); z++) { - BlockPosition position = world.getAsyncPosition(x, y, z); - if (position.getBlockType().equals(BlockTypes.AIR)) { - this.addPositionRelativeToWorld(position); - } - } - } - } - TranslateCore - .getScheduleManager() - .schedule() - .setDisplayName("from air getter") - .setDelay(0) - .setDelayUnit(TimeUnit.MINECRAFT_TICKS) - .setRunner((s) -> future.complete(this)) - .buildDelayed(ShipsPlugin.getPlugin()) - .run(); - })) - .buildDelayed(ShipsPlugin.getPlugin()) - .run(); - return future; + public Stream getAir() { + Spliterator> split = new RangeVectorSpliterator(this.getBounds()); + WorldExtent world = this.position.getWorld(); + return StreamSupport + .stream(split, false) + .map(pos -> (SyncBlockPosition) world.getPosition(pos)) + .filter(pos -> pos.getBlockType().equals(BlockTypes.AIR)); } @Override - public Collection> getOutsidePositionsRelativeToCenter() { - Collection> vectors = new HashSet<>(this.getOriginalRelativeVectorsToCenter()); - if (vectors.stream().noneMatch(v -> v.equals(Vector3.valueOf(0, 0, 0)))) { - vectors.add(Vector3.valueOf(0, 0, 0)); - } - return vectors; + public Stream> getOutsideVectorsRelativeToLicence() { + Stream> east = this.outsideEast.stream(); + Stream> west = this.outsideWest.stream(); + Stream> north = this.outsideNorth.stream(); + Stream> south = this.outsideSouth.stream(); + Stream> result = Stream.concat(east, west); + result = Stream.concat(north, result); + result = Stream.concat(south, result); + return result.distinct(); } @Override @@ -134,21 +113,19 @@ public Bounds getBounds() { if (this.cachedBounds != null) { return this.cachedBounds; } - Set> positions = this - .getOutsidePositionsRelativeToWorld() - .parallelStream() - .collect(Collectors.toSet()); - if (positions.isEmpty()) { + Iterator> positions = this.getOutsideVectorsRelativeToWorld().iterator(); + if (!positions.hasNext()) { throw new IllegalStateException("No structure found"); } - Vector3 randomVector = positions.iterator().next(); + Vector3 randomVector = positions.next(); int minX = randomVector.getX(); int minY = randomVector.getY(); int minZ = randomVector.getZ(); int maxX = minX; int maxY = minY; int maxZ = minZ; - for (Vector3 vector : positions) { + while (positions.hasNext()) { + Vector3 vector = positions.next(); if (minX <= vector.getX()) { minX = vector.getX(); } @@ -172,21 +149,13 @@ public Bounds getBounds() { } @Override - public Collection> getOriginalRelativeVectorsToWorld() { - return this - .getOriginalRelativeVectorsToCenter() - .parallelStream() - .map(vector -> this.position.getPosition().plus(vector)) - .collect(Collectors.toList()); + public Stream> getVectorsRelativeTo(@NotNull Vector3 vector) { + Stream> stream = this.vectors.stream().map(vector::plus); + return Stream.concat(Stream.of(vector), stream); } @Override - public Collection> getOriginalRelativeVectorsToCenter() { - return this.vectors; - } - - @Override - public boolean addPositionRelativeToCenter(Vector3 add) { + public boolean addVectorRelativeToLicence(Vector3 add) { if (this.vectors.parallelStream().anyMatch(v -> v.equals(add))) { return false; } @@ -281,12 +250,15 @@ public void copyFrom(@NotNull PositionableShipsStructure structure) { this.outsideWest.addAll(abstractStructure.outsideWest); return; } - structure.getOriginalRelativeVectorsToWorld().parallelStream().forEach(this::addPositionRelativeToWorld); + structure.getVectorsRelativeToWorld().parallel().forEach(this::addPositionRelativeToWorld); } @Override public boolean matchRelativeToCenter(PositionableShipsStructure structure) { - return this.getRelativePositionsToCenter().equals(structure.getRelativePositionsToCenter()); + if (!(structure instanceof AbstractPositionableShipsStructure)) { + throw new IllegalArgumentException("Structure must be a AbstractPositionableShipsStructure"); + } + return this.vectors.equals(((AbstractPositionableShipsStructure) structure).vectors); } @Override @@ -299,13 +271,78 @@ public boolean matchRelativeToCenter(PositionableShipsStructure structure) { @Override public PositionableShipsStructure setRawPositionsRelativeToCenter(Collection> collection) { this.clear(); - collection.forEach(this::addPositionRelativeToCenter); + collection.forEach(this::addVectorRelativeToLicence); return this; } - private void addPositionRelativeToWorld(@NotNull Vector3 position) { + @Override + public boolean addPositionRelativeToWorld(@NotNull BlockPosition position) { + if (position instanceof SyncBlockPosition) { + SyncPosition syncedPosition = (SyncPosition) position; + Optional opTileEntityData = syncedPosition.getTileEntity(); + if (opTileEntityData.isPresent()) { + Vector3 original = this.getPosition().getPosition(); + Vector3 resultPosition = position.getPosition().minus(original); + this.tileEntityVectors.add(resultPosition); + } + } + + return this.addPositionRelativeToWorld(position.getPosition()); + } + + @Override + public boolean removePositionRelativeToWorld(BlockPosition position) { + Vector3 original = this.getPosition().getPosition(); + Vector3 resultPosition = position.getPosition().minus(original); + this.tileEntityVectors.remove(resultPosition); + return this.removePositionRelativeToCenter(resultPosition); + } + + @Override + public int size() { + return this.vectors.size(); + } + + @Override + public Stream getRelativeToWorld(@NotNull Class class1) { + Stream cachedTileEntities = this.tileEntityVectors + .stream() + .map(vector -> this.position.getRelative(vector).getTileEntity()) + .filter(Optional::isPresent) + .map(Optional::get) + .filter(class1::isInstance) + .map(lte -> (L) lte); + + Stream allTileEntities = this + .getPositionsRelativeToWorld() + .map(SyncPosition::getTileEntity) + .filter(Optional::isPresent) + .map(Optional::get) + .peek(lte -> this.tileEntityVectors.add( + lte.getPosition().getPosition().minus(this.position.getPosition()))) + .filter(class1::isInstance) + .map(lte -> (L) lte); + return Stream.concat(cachedTileEntities, allTileEntities).distinct(); + + } + + @Override + public Stream getRelativeToWorld(@NotNull ShipsSign sign) { + return this.getRelativeToWorld(LiveSignTileEntity.class).filter(sign::isSign); + } + + @Override + public boolean matchStructure(@NotNull PositionableShipsStructure updatedStructure) { + if(!(updatedStructure instanceof AbstractPositionableShipsStructure)){ + throw new IllegalArgumentException("Match structure must be run on a AbstractPositionableShipsStructure"); + } + AbstractPositionableShipsStructure arg = (AbstractPositionableShipsStructure) updatedStructure; + return arg.vectors.equals(this.vectors); + } + + private boolean addPositionRelativeToWorld(@NotNull Vector3 position) { Vector3 original = this.getPosition().getPosition(); - this.addPositionRelativeToCenter(position.minus(original)); + return this.addVectorRelativeToLicence(position.minus(original)); } private static Optional getNextInLine(Position pos, diff --git a/src/main/java/org/ships/vessel/structure/PositionableShipsStructure.java b/src/main/java/org/ships/vessel/structure/PositionableShipsStructure.java index 4c0531ed..60cfbd8c 100644 --- a/src/main/java/org/ships/vessel/structure/PositionableShipsStructure.java +++ b/src/main/java/org/ships/vessel/structure/PositionableShipsStructure.java @@ -6,100 +6,68 @@ import org.core.world.WorldExtent; import org.core.world.direction.FourFacingDirection; import org.core.world.position.Positionable; -import org.core.world.position.block.BlockType; -import org.core.world.position.block.entity.TileEntity; +import org.core.world.position.block.entity.LiveTileEntity; import org.core.world.position.block.entity.sign.LiveSignTileEntity; -import org.core.world.position.block.entity.sign.SignTileEntity; import org.core.world.position.impl.BlockPosition; import org.core.world.position.impl.Position; -import org.core.world.position.impl.async.ASyncBlockPosition; import org.core.world.position.impl.sync.SyncBlockPosition; import org.jetbrains.annotations.NotNull; import org.ships.vessel.sign.ShipsSign; -import java.util.Arrays; import java.util.Collection; -import java.util.HashSet; -import java.util.Set; +import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import java.util.concurrent.LinkedTransferQueue; -import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; +import java.util.stream.Stream; public interface PositionableShipsStructure extends Positionable { PositionableShipsStructure setPosition(@NotNull SyncBlockPosition pos); - Collection> getOutsidePositionsRelativeToCenter(FourFacingDirection direction); + Stream> getOutsideVectorsRelativeToLicence(@NotNull FourFacingDirection direction); - @Deprecated(forRemoval = true) - default Collection> getOutsideBlocks(@NotNull FourFacingDirection direction) { - return this.getOutsidePositionsRelativeToCenter(direction); - } - - @Deprecated(forRemoval = true) - default void addAir(Consumer onComplete) { - fillAir().thenAccept(onComplete); - } + Stream getAir(); - CompletableFuture fillAir(); - - default Collection> getOutsidePositionsRelativeToCenter() { - return Arrays - .stream(FourFacingDirection.getFourFacingDirections()) - .flatMap(direction -> this.getOutsideBlocks((FourFacingDirection) direction).stream()) - .collect(Collectors.toSet()); - } + Stream> getOutsideVectorsRelativeToLicence(); - default Collection> getOutsidePositionsRelativeToWorld() { + default Stream> getOutsideVectorsRelativeToWorld() { Vector3 position = this.getPosition().getPosition(); - return this - .getOutsidePositionsRelativeToCenter() - .parallelStream() - .map(position::plus) - .collect(Collectors.toSet()); - } - - @Deprecated(forRemoval = true) - default Collection> getOutsideBlocks() { - return this.getOutsidePositionsRelativeToCenter(); + return this.getOutsideVectorsRelativeToLicence().map(position::plus); } Bounds getBounds(); - default Collection> getRelativePositionsToCenter() { - Collection> originalPositions = new HashSet<>(this.getOriginalRelativePositionsToCenter()); - originalPositions.add(Vector3.valueOf(0, 0, 0)); - return originalPositions; - } + Stream> getVectorsRelativeTo(@NotNull Vector3 vector); - @Deprecated(forRemoval = true) - default Collection> getRelativePositions() { - return this.getRelativePositionsToCenter(); + default Stream> getVectorsRelativeToWorld() { + return this.getVectorsRelativeTo(this.getPosition().getPosition()); } - @Deprecated(forRemoval = true) - default Collection> getOriginalRelativePositionsToCenter() { - return getOriginalRelativeVectorsToCenter(); + default Stream> getVectorsRelativeToLicence() { + return this.getVectorsRelativeTo(Vector3.valueOf(0, 0, 0)); } - Collection> getOriginalRelativeVectorsToWorld(); + default Stream getPositionsRelativeToPosition(@NotNull BlockPosition pos, + @NotNull Function, BlockPos> toPos) { + return this.getVectorsRelativeTo(pos.getPosition()).map(toPos); + } - Collection> getOriginalRelativeVectorsToCenter(); + default Stream getPositionsRelativeToPosition(@NotNull BlockPosition pos) { + WorldExtent world = pos.getWorld(); + return this.getPositionsRelativeToPosition(pos, vector -> (SyncBlockPosition) world.getPosition(vector)); + } - @Deprecated(forRemoval = true) - default Collection> getOriginalRelativePositions() { - return this.getOriginalRelativePositionsToCenter(); + default Stream getPositionsRelativeToWorld() { + return getPositionsRelativeToPosition(this.getPosition()); } - @Deprecated(forRemoval = true) - default boolean addPosition(Vector3 add) { - return this.addPositionRelativeToCenter(add); + default Stream getPositionsRelativeToLicence() { + return getPositionsRelativeToPosition(this.getPosition().getWorld().getPosition(0, 0, 0)); } - boolean addPositionRelativeToCenter(Vector3 add); + boolean addVectorRelativeToLicence(Vector3 add); boolean removePositionRelativeToCenter(Vector3 remove); @@ -107,16 +75,11 @@ default boolean addPosition(Vector3 add) { boolean matchRelativeToCenter(PositionableShipsStructure structure); - @Deprecated(forRemoval = true) - default boolean removePosition(Vector3 remove) { - return this.removePositionRelativeToCenter(remove); - } - PositionableShipsStructure clear(); @Deprecated default PositionableShipsStructure setRaw(Collection> collection) { - return setRawPositionsRelativeToCenter(collection); + return this.setRawPositionsRelativeToCenter(collection); } PositionableShipsStructure setRawPositionsRelativeToCenter(Collection> collection); @@ -136,7 +99,7 @@ default int getZSize() { default int getSpecificSize(Function, Integer> function) { Integer min = null; Integer max = null; - for (Vector3 vector : this.getRelativePositions()) { + for (Vector3 vector : this.getVectorsRelativeToLicence().collect(Collectors.toList())) { int value = function.apply(vector); if (min == null && max == null) { max = value; @@ -156,133 +119,45 @@ default int getSpecificSize(Function, Integer> function return max - min; } - default Collection getPositionsRelativeTo(Positionable positionable) { - return this.getPositionsRelativeTo(positionable.getPosition()); + default Stream> getChunkPositions() { + return this.getPositionsRelativeToPosition(this.getPosition()).parallel().map(Position::getChunkPosition); } - default Collection getPositionsRelativeTo(T position) { - return this - .getRelativePositions() - .stream() - .map(vector -> (T) position.getRelative(vector)) - .collect(Collectors.toCollection(LinkedTransferQueue::new)); + default Stream getLoadedChunks() { + WorldExtent world = this.getPosition().getWorld(); + return this.getChunkPositions().map(world::getChunk).filter(Optional::isPresent).map(Optional::get); } - default Set getChunks() { - Collection> positions = this - .getAsyncedPositionsRelativeToWorld() - .parallelStream() - .map(Position::getChunkPosition) - .collect(Collectors.toSet()); + default Stream loadChunks() { WorldExtent world = this.getPosition().getWorld(); - return positions.stream().map(world::loadChunk).collect(Collectors.toSet()); + return this.getChunkPositions().map(world::loadChunk); } - default CompletableFuture> getChunksAsynced() { - Collection> positions = this - .getAsyncedPositionsRelativeToWorld() - .parallelStream() - .map(Position::getChunkPosition) - .collect(Collectors.toSet()); + default CompletableFuture> getChunksAsynced() { WorldExtent world = this.getPosition().getWorld(); - Set> chunkAsync = positions - .stream() + CompletableFuture[] futures = this + .getPositionsRelativeToWorld() + .map(Position::getChunkPosition) .map(world::loadChunkAsynced) - .collect(Collectors.toSet()); - return CompletableFuture - .allOf(chunkAsync.toArray(new CompletableFuture[0])) - .thenApply(v -> chunkAsync.parallelStream().map(f -> { - try { - return f.get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException("This should be impossible", e); - } - }).collect(Collectors.toSet())); - } - - @Deprecated(forRemoval = true) - default boolean addPosition(BlockPosition position) { - Vector3 original = this.getPosition().getPosition(); - Vector3 next = position.getPosition(); - return this.addPosition(next.minus(original)); - } - - default boolean addPositionRelativeToWorld(BlockPosition position) { - Vector3 original = this.getPosition().getPosition(); - Vector3 next = position.getPosition(); - return this.addPosition(next.minus(original)); - } - - @Deprecated(forRemoval = true) - default boolean removePosition(BlockPosition position) { - Vector3 original = this.getPosition().getPosition(); - Vector3 next = position.getPosition(); - return this.removePosition(next.minus(original)); - } - - default boolean removePositionRelativeToWorld(BlockPosition position) { - Vector3 original = this.getPosition().getPosition(); - Vector3 next = position.getPosition(); - return this.removePosition(next.minus(original)); - } - - default

Collection getAllLike(Function toPos, - Function function) { - return this.getPositions(toPos).stream().map(function).collect(Collectors.toUnmodifiableSet()); - } - - default Collection getAll(BlockType type, - Function function) { - return this - .getPositions(function) - .stream() - .filter(p -> p.getBlockType().equals(type)) - .collect(Collectors.toUnmodifiableSet()); - } - - default Collection getAll(Class class1) { - return this - .getPositionsRelativeTo(this) - .stream() - .filter(p -> p.getTileEntity().isPresent()) - .filter(p -> class1.isInstance(p.getTileEntity().get())) - .collect(Collectors.toUnmodifiableSet()); + .toArray(CompletableFuture[]::new); + return CompletableFuture.allOf(futures).thenApply(v -> Stream.of(futures).parallel().map(f -> { + try { + return f.get(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException("This should be impossible", e); + } + })); } - default Collection getAll(ShipsSign sign) { - return this - .getSyncedPositions() - .stream() - .filter(b -> b.getTileEntity().isPresent()) - .filter(b -> b.getTileEntity().get() instanceof LiveSignTileEntity) - .filter(b -> sign.isSign((SignTileEntity) b.getTileEntity().get())) - .collect(Collectors.toUnmodifiableSet()); - } + boolean addPositionRelativeToWorld(BlockPosition position); - @Deprecated(forRemoval = true) - default Collection getSyncedPositions() { - return this.getPositionsRelativeTo(this.getPosition()); - } + boolean removePositionRelativeToWorld(BlockPosition position); - default Collection getSyncedPositionsRelativeToWorld() { - return this.getPositionsRelativeTo(this.getPosition()); - } + int size(); - @Deprecated(forRemoval = true) - default Collection getAsyncedPositions() { - return this.getPositions(Position::toASync); - } + Stream getRelativeToWorld(@NotNull Class class1); - default Collection getAsyncedPositionsRelativeToWorld() { - return this.getPositions(Position::toASync); - } - - @Deprecated(forRemoval = true) - default Collection getPositions(Function function) { - return this.getPositionsRelativeTo(function.apply(this.getPosition())); - } + Stream getRelativeToWorld(@NotNull ShipsSign sign); - default Collection getPositionsRelativeTo(Function function) { - return this.getPositionsRelativeTo(function.apply(this.getPosition())); - } + boolean matchStructure(@NotNull PositionableShipsStructure updatedStructure); }