Merge branch 'master' into 1.16

This commit is contained in:
gnembon committed 2020-02-25 12:57:45 -04:00
commit 51ec01790b
10 files changed
+191 -53

No files matched your search

@@ -239,6 +239,7 @@ public class ScriptCommand
then(argument("call", StringArgumentType.word()).
suggests( (cc, bb) -> suggestMatching(suggestFunctionCalls(cc), bb)).
executes( (cc) -> CarpetServer.scriptServer.events.addEvent(
cc.getSource(),
StringArgumentType.getString(cc, "event"),
null,
StringArgumentType.getString(cc, "call")
@@ -249,6 +250,7 @@ public class ScriptCommand
then(argument("call", StringArgumentType.word()).
suggests( (cc, bb) -> suggestMatching(suggestFunctionCalls(cc), bb)).
executes( (cc) -> CarpetServer.scriptServer.events.addEvent(
cc.getSource(),
StringArgumentType.getString(cc, "event"),
StringArgumentType.getString(cc, "app"),
StringArgumentType.getString(cc, "call")
@@ -259,6 +261,7 @@ public class ScriptCommand
then(argument("call", StringArgumentType.greedyString()).
suggests( (cc, bb) -> suggestMatching(CarpetEventServer.Event.byName.get(StringArgumentType.getString(cc, "event")).handler.callList.stream().map(CarpetEventServer.Callback::toString), bb)).
executes( (cc) -> CarpetServer.scriptServer.events.removeEvent(
cc.getSource(),
StringArgumentType.getString(cc, "event"),
StringArgumentType.getString(cc, "call")
)?1:0))));
@@ -308,7 +311,7 @@ public class ScriptCommand
Messenger.m(source, "w Handlers for "+event.name+": ");
shownEvent = true;
}
Messenger.m(source, "w - "+c.function +(c.host==null?"":" (from "+c.host+")"));
Messenger.m(source, "w - "+c.function.getString() +(c.host==null?"":" (from "+c.host+")"));
}
}
return 1;
@@ -0,0 +1,10 @@
package carpet.fakes;
import net.minecraft.util.math.ChunkPos;
public interface ThreadedAnvilChunkStorageInterface
{
//boolean isChunkLoaded(ChunkPos chpos);
//void forceUnloadChunk(ChunkPos chpos);
void regenerateChunk(ChunkPos chpos);
}
@@ -22,6 +22,7 @@ import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec2f;
import net.minecraft.util.math.Vec3d;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@@ -197,15 +198,30 @@ public class EntityPlayerActionPack
public void onUpdate()
{
boolean used = false;
Map<ActionType, Boolean> actionAttempts = new HashMap<>();
actions.entrySet().removeIf((e) -> e.getValue().done);
for (Map.Entry<ActionType, Action> e : actions.entrySet())
{
Action action = e.getValue();
if (used && e.getKey() == ActionType.ATTACK)
continue;
if (action.tick(this, e.getKey()))
used = true;
// skipping attack if use was successful
if (!(actionAttempts.getOrDefault(ActionType.USE, false) && e.getKey() == ActionType.ATTACK))
{
Boolean actionStatus = action.tick(this, e.getKey());
if (actionStatus != null)
actionAttempts.put(e.getKey(), actionStatus);
}
// optionally retrying use after successful attack and unsuccessful use
if ( e.getKey() == ActionType.ATTACK
&& actionAttempts.getOrDefault(ActionType.ATTACK, false)
&& !actionAttempts.getOrDefault(ActionType.USE, true) )
{
// according to MinecraftClient.handleInputEvents
Action using = actions.get(ActionType.USE);
if (using != null) // this is always true - we know use worked, but just in case
{
using.retry(this, ActionType.USE);
}
}
}
if (forward != 0.0F)
{
@@ -316,7 +332,7 @@ public class EntityPlayerActionPack
player.resetLastAttackedTicks();
player.updateLastActionTime();
player.swingHand(Hand.MAIN_HAND);
break;
return true;
}
case BLOCK: {
EntityPlayerActionPack ap = ((ServerPlayerEntityInterface) player).getActionPack();
@@ -328,6 +344,7 @@ public class EntityPlayerActionPack
BlockHitResult blockHit = (BlockHitResult) hit;
BlockPos pos = blockHit.getBlockPos();
Direction side = blockHit.getSide();
// rather should be canNotMine
if (player.canMine(player.world, pos, player.interactionManager.getGameMode())) return false;
if (ap.currentBlock != null && player.world.getBlockState(ap.currentBlock).isAir())
{
@@ -335,10 +352,12 @@ public class EntityPlayerActionPack
return false;
}
BlockState state = player.world.getBlockState(pos);
boolean blockBroken = false;
if (player.interactionManager.getGameMode().isCreative())
{
player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, side, player.server.getWorldHeight());
ap.blockHitDelay = 5;
blockBroken = true;
}
else if (ap.currentBlock == null || !ap.currentBlock.equals(pos))
{
@@ -355,6 +374,8 @@ public class EntityPlayerActionPack
if (notAir && state.calcBlockBreakingDelta(player, player.world, pos) >= 1)
{
ap.currentBlock = null;
//instamine??
blockBroken = true;
}
else
{
@@ -369,13 +390,14 @@ public class EntityPlayerActionPack
{
player.interactionManager.processBlockBreakingAction(pos, PlayerActionC2SPacket.Action.STOP_DESTROY_BLOCK, side, player.server.getWorldHeight());
ap.currentBlock = null;
blockBroken = true;
}
player.world.setBlockBreakingInfo(-1, pos, (int) (ap.curBlockDamageMP * 10));
}
player.updateLastActionTime();
player.swingHand(Hand.MAIN_HAND);
break;
return blockBroken;
}
}
return false;
@@ -499,10 +521,10 @@ public class EntityPlayerActionPack
return new Action(-1, interval, offset);
}
boolean tick(EntityPlayerActionPack actionPack, ActionType type)
Boolean tick(EntityPlayerActionPack actionPack, ActionType type)
{
next--;
boolean cancel = false;
Boolean cancel = null;
if (next <= 0) {
if (!type.preventSpectator || !actionPack.player.isSpectator())
@@ -527,5 +549,20 @@ public class EntityPlayerActionPack
}
return cancel;
}
void retry(EntityPlayerActionPack actionPack, ActionType type)
{
//assuming action run but was unsuccesful that tick, but opportunity emerged to retry it, lets retry it.
if (!type.preventSpectator || !actionPack.player.isSpectator())
{
type.execute(actionPack.player, this);
}
count++;
if (count == limit)
{
type.stop(actionPack.player, null);
done = true;
}
}
}
}
@@ -1,8 +1,15 @@
package carpet.mixins;
import carpet.fakes.ThreadedAnvilChunkStorageInterface;
import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import it.unimi.dsi.fastutil.longs.LongSet;
import net.minecraft.server.world.ChunkHolder;
import net.minecraft.server.world.ChunkTaskPrioritySystem;
import net.minecraft.server.world.ServerLightingProvider;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.server.world.ThreadedAnvilChunkStorage;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.chunk.Chunk;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
@@ -11,15 +18,34 @@ import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import static carpet.script.CarpetEventServer.Event.CHUNK_GENERATED;
@Mixin(ThreadedAnvilChunkStorage.class)
public class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin
public abstract class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin implements ThreadedAnvilChunkStorageInterface
{
@Shadow @Final private ServerWorld world;
@Shadow @Final private LongSet loadedChunks;
@Shadow @Final private LongSet unloadedChunks;
@Shadow @Final private Long2ObjectLinkedOpenHashMap<ChunkHolder> currentChunkHolders;
@Shadow @Final private Long2ObjectLinkedOpenHashMap<ChunkHolder> field_18807;
@Shadow private boolean chunkHolderListDirty;
@Shadow protected abstract void method_20458(long l, ChunkHolder chunkHolder);
@Shadow @Final private Queue<Runnable> field_19343;
@Shadow @Final private ServerLightingProvider serverLightingProvider;
@Shadow @Final private ChunkTaskPrioritySystem chunkTaskPrioritySystem;
//in method_20617
//method_19534(Lnet/minecraft/server/world/ChunkHolder;Lnet/minecraft/world/chunk/Chunk;)Ljava/util/concurrent/CompletableFuture;
@Inject(method = "method_19534", at = @At(
@@ -32,4 +58,30 @@ public class ThreadedAnvilChunkStorage_scarpetChunkCreationMixin
if (CHUNK_GENERATED.isNeeded())
world.getServer().execute( () -> CHUNK_GENERATED.onChunkGenerated(world, chunk) );
}
@Override
public void regenerateChunk(ChunkPos chpos)
{
Long id = chpos.toLong();
if (loadedChunks.contains(id))
{
//unload chunk first
unloadedChunks.remove(id);
ChunkHolder chunkHolder = (ChunkHolder)currentChunkHolders.remove(id);
if (chunkHolder != null) {
field_18807.put(id, chunkHolder);
chunkHolderListDirty = true;
method_20458(id, chunkHolder);
}
Runnable runnable;
while((runnable = (Runnable) field_19343.poll()) != null) {
runnable.run();
}
}
ChunkHolder newHolder = new ChunkHolder(chpos, 0,serverLightingProvider, chunkTaskPrioritySystem, (ChunkHolder.PlayersWatchingChunkProvider) this);
this.currentChunkHolders.put(id, newHolder);
this.chunkHolderListDirty = true;
}
}
@@ -1,6 +1,7 @@
package carpet.script;
import carpet.CarpetServer;
import carpet.script.exception.InternalExpressionException;
import carpet.script.value.BlockValue;
import carpet.script.value.EntityValue;
import carpet.script.value.FunctionValue;
@@ -9,6 +10,7 @@ import carpet.script.value.NBTSerializableValue;
import carpet.script.value.NumericValue;
import carpet.script.value.StringValue;
import carpet.script.value.Value;
import carpet.utils.Messenger;
import net.minecraft.block.BlockState;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.entity.Entity;
@@ -126,27 +128,30 @@ public class CarpetEventServer
callList.removeIf(call -> !CarpetServer.scriptServer.runas(source, call.host, call.function, argv)); // this actually does the calls
}
}
public boolean addEventCall(String hostName, String funName, Function<ScriptHost, Boolean> verifier)
public boolean addEventCall(ServerCommandSource source, String hostName, String funName, Function<ScriptHost, Boolean> verifier)
{
ScriptHost host = CarpetServer.scriptServer.getHostByName(hostName);
if (host == null)
{
// impossible call to add
Messenger.m(source, "r Unknown app "+hostName);
return false;
}
if (!verifier.apply(host))
{
// host cannot use that event, its global event on player based app
Messenger.m(source, "r Global event can only be added to apps with global scope");
return false;
}
FunctionValue udf = host.getFunction(funName);
if (udf == null || udf.getArguments().size() != reqArgs)
{
// call won't match arguments
Messenger.m(source, "r Callback doesn't expect required number of arguments: "+reqArgs);
return false;
}
//all clear
//remove duplicates
removeEventCall(hostName, udf.getString());
callList.add(new Callback(hostName, udf));
return true;
@@ -567,38 +572,44 @@ public class CarpetEventServer
scheduledCalls.add(new ScheduledCall(context, function, args, due));
}
public boolean addEvent(String event, String host, String funName)
public boolean addEvent(ServerCommandSource source, String event, String host, String funName)
{
if (!Event.byName.containsKey(event))
{
return false;
}
Event ev = Event.byName.get(event);
return ev.handler.addEventCall(host, funName, h -> canAddEvent(ev, h));
boolean added = ev.handler.addEventCall(source, host, funName, h -> canAddEvent(ev, h));
if (added) Messenger.m(source, "gi Added " + funName + " to " + event);
return added;
}
public boolean addEventDirectly(String event, ScriptHost host, FunctionValue function)
{
Event ev = Event.byName.get(event);
// config can be analyzed after code is read, so this will always be player scope
//if (!canAddEvent(ev, host))
// throw new InternalExpressionException("Global event "+event+" can only be added to apps with global scope");
if (!canAddEvent(ev, host))
throw new InternalExpressionException("Global event "+event+" can only be added to apps with global scope");
return ev.handler.addEventCallDirect(host, function);
}
private boolean canAddEvent(Event event, ScriptHost host)
{
return !(event.globalOnly && host.perUser);
return !(event.globalOnly && (host.perUser || host.parent != null));
}
public boolean removeEvent(String event, String funName)
public boolean removeEvent(ServerCommandSource source, String event, String funName)
{
if (!Event.byName.containsKey(event))
{
Messenger.m(source, "r Unknown event: " + event);
return false;
}
Pair<String,String> call = decodeCallback(funName);
Event.byName.get(event).handler.removeEventCall(call.getLeft(), call.getRight());
// could verified if actually removed
Messenger.m(source, "gi Removed event: " + funName + " from "+event);
return true;
}
@@ -78,6 +78,7 @@ import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ChunkTicket;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.server.world.ThreadedAnvilChunkStorage;
import net.minecraft.sound.BlockSoundGroup;
import net.minecraft.sound.SoundCategory;
import net.minecraft.stat.Stat;
@@ -1672,6 +1673,18 @@ public class CarpetExpression
Value ret = result[0]; // preventing from lazy evaluating of the result in case a future completes later
return (_c, _t) -> ret;
});
/*this.expr.addLazyFunction("reset_chunk", -1, (c, t, lv) ->
{
CarpetContext cc = (CarpetContext)c;
BlockValue.LocatorResult locator = BlockValue.fromParams(cc, lv, 0);
ServerWorld world = cc.s.getWorld();
BlockPos pos = locator.block.getPos();
ThreadedAnvilChunkStorage
});*/
}
/**
@@ -7,6 +7,7 @@ import carpet.script.exception.ExpressionException;
import carpet.script.exception.InternalExpressionException;
import carpet.script.exception.InvalidCallbackException;
import carpet.script.value.FunctionValue;
import carpet.script.value.MapValue;
import carpet.script.value.NumericValue;
import carpet.script.value.StringValue;
import carpet.script.value.Value;
@@ -26,6 +27,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static java.lang.Math.max;
@@ -36,14 +38,23 @@ public class CarpetScriptHost extends ScriptHost
private Tag globalState;
private int saveTimeout;
public boolean persistenceRequired;
private CarpetScriptHost(CarpetScriptServer server, Module code, boolean perUser, ScriptHost parent)
{
super(code, perUser, parent);
this.saveTimeout = 0;
this.scriptServer = server;
if (parent == null && code != null)
persistenceRequired = true;
if (parent == null && code != null) // app, not a global host
{
persistenceRequired = false;
globalState = loadState();
}
else if (parent != null)
{
persistenceRequired = ((CarpetScriptHost)parent).persistenceRequired;
}
}
public static CarpetScriptHost create(CarpetScriptServer scriptServer, Module module, boolean perPlayer, ServerCommandSource source)
@@ -82,16 +93,39 @@ public class CarpetScriptHost extends ScriptHost
}
@Override
public void addUserDefinedFunction(Module module, String funName, FunctionValue function)
public void addUserDefinedFunction(Context ctx, Module module, String funName, FunctionValue function)
{
super.addUserDefinedFunction(module, funName, function);
super.addUserDefinedFunction(ctx, module, funName, function);
// mcarpet
if (funName.startsWith("__on_")) // here we can make a determination if we want to only accept events from main module.
if (funName.startsWith("__")) // potential fishy activity
{
if (funName.startsWith("__on_")) // here we can make a determination if we want to only accept events from main module.
{
// this is nasty, we have the host and function, yet we add it via names, but hey - works for now
String event = funName.replaceFirst("__on_", "");
if (CarpetEventServer.Event.byName.containsKey(event))
scriptServer.events.addEventDirectly(event, this, function);
}
else if (funName.equals("__config"))
{
addAppConfig(ctx, function);
}
}
}
private void addAppConfig(Context ctx, FunctionValue function)
{
try
{
CarpetContext cctx = (CarpetContext)ctx;
Value ret = callUDF(BlockPos.ORIGIN, cctx.s, function, Collections.emptyList());
if (!(ret instanceof MapValue)) return;
Map<Value, Value> config = ((MapValue) ret).getMap();
setPerPlayer(config.getOrDefault(new StringValue("scope"), new StringValue("player")).getString().equalsIgnoreCase("player"));
persistenceRequired = config.getOrDefault(new StringValue("stay_loaded"), Value.FALSE).getBoolean();
}
catch (NullPointerException | InvalidCallbackException ignored)
{
// this is nasty, we have the host and function, yet we add it via names, but hey - works for now
String event = funName.replaceFirst("__on_","");
if (CarpetEventServer.Event.byName.containsKey(event))
scriptServer.events.addEventDirectly(event, this, function);
}
}
@@ -164,7 +164,7 @@ public class CarpetScriptServer
modules.put(name, newHost);
if (!addConfig(source, name) && autoload)
if (autoload && !newHost.persistenceRequired)
{
removeScriptHost(source, name);
return false;
@@ -174,28 +174,6 @@ public class CarpetScriptServer
return true;
}
private boolean addConfig(ServerCommandSource source, String hostName)
{
CarpetScriptHost host = modules.get(hostName);
if (host == null || host.getFunction("__config") == null)
{
return false;
}
try
{
Value ret = host.callUDF(BlockPos.ORIGIN, source, host.getFunction("__config"), Collections.emptyList());
if (!(ret instanceof MapValue)) return false;
Map<Value, Value> config = ((MapValue) ret).getMap();
host.setPerPlayer(config.getOrDefault(new StringValue("scope"), new StringValue("player")).getString().equalsIgnoreCase("player"));
return config.getOrDefault(new StringValue("stay_loaded"), Value.FALSE).getBoolean();
}
catch (NullPointerException | InvalidCallbackException ignored)
{
}
return false;
}
private void addCommand(ServerCommandSource source, String hostName)
{
ScriptHost host = modules.get(hostName);
+1 -1
View File
@@ -680,7 +680,7 @@ public class Expression
FunctionValue result = new FunctionValue(expr, token, name, code, arguments, contextValues);
// do not store lambda definitions
if (!name.equals("_")) context.host.addUserDefinedFunction(module, name, result);
if (!name.equals("_")) context.host.addUserDefinedFunction(context, module, name, result);
return result;
}
+1 -1
View File
@@ -268,7 +268,7 @@ public abstract class ScriptHost
data.functionImports.remove(varName);
}
public void addUserDefinedFunction(Module module, String name, FunctionValue fun)
public void addUserDefinedFunction(Context ctx, Module module, String name, FunctionValue fun)
{
moduleData.get(module).globalFunctions.put(name, fun);
}