Replace weapon pose jitter with native swings and timed slash trails

This commit is contained in:
2026-09-13 10:33:20 +03:00
parent 4ff0ed89b5
commit 28ce2a53e0
55 changed files with 1003 additions and 62 deletions
+2 -2
View File
@@ -15,7 +15,7 @@
«Размах» расширяет радиус до 4/5 блоков. Отмена атаки, стены, союзники, PvP, броня, щиты, криты и обычные чары учитываются. «Размах» расширяет радиус до 4/5 блоков. Отмена атаки, стены, союзники, PvP, броня, щиты, криты и обычные чары учитываются.
Смена оружия/слота, выход, смерть и смена измерения отменяют незавершённый замах. Смена оружия/слота, выход, смерть и смена измерения отменяют незавершённый замах.
Вместо частиц используется временная vanilla item-display с анимированной текстурой дуги, в том числе огненный вариант при «Заговоре огня». Вместо частиц используется временная vanilla item-display с анимированной текстурой дуги, в том числе огненный вариант при «Заговоре огня».
Положение оружия в руке проходит через шесть модельных кадров; геометрия попадания остаётся серверной. С версии 0.1.1 положение оружия не скачет между шестью моделями: используется штатный плавный взмах Minecraft со стабильным хватом. След удара — короткая сужающаяся дуга из четырёх кадров, синхронизированных с конкретным ударом.
Боевые перчатки: базовый урон 3, скорость 4 атаки/с, откат 5 тиков (0,25 с), небольшая область ±28° до 2,2 блока. Боевые перчатки: базовый урон 3, скорость 4 атаки/с, откат 5 тиков (0,25 с), небольшая область ±28° до 2,2 блока.
Серия: левый → правый → левый → правый → левый хук → правый апперкот → правый выпад. Серия: левый → правый → левый → правый → левый хук → правый апперкот → правый выпад.
@@ -34,7 +34,7 @@
Недостающие ресурсы и определения устанавливаются в общие каталоги AstraPlus до загрузки чар/сборки пака. Существующие пользовательские файлы сохраняются. Недостающие ресурсы и определения устанавливаются в общие каталоги AstraPlus до загрузки чар/сборки пака. Существующие пользовательские файлы сохраняются.
После установки JAR нужен перезапуск сервера и принятие обновлённого ресурспака. При отключённой автоматической сборке выполните `/astraplus build`. После установки JAR нужен перезапуск сервера и принятие обновлённого ресурспака. При отключённой автоматической сборке выполните `/astraplus build`.
Модели рук анимируются средствами ресурспака и сетевых пакетов; базовые движения рук самого ванильного персонажа сохраняются. Ванильный клиент использует `swing_animation`: STAB для прямых ударов/апперкота/выпада, WHACK для хука и твинблейда. Перчатки закреплены на кистях в третьем лице; смещение моделей отдельно от рук удалено. Произвольная скелетная анимация не используется. Изменения поз умеренные; точного воспроизведения анимаций Dungeons на ванильном скелете нет.
Авторы заимствованных моделей и звуков указаны в [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md), в JAR, ресурспаке и описании перчаток. Авторы заимствованных моделей и звуков указаны в [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md), в JAR, ресурспаке и описании перчаток.
Сборка: сначала `AstraPlus/gradlew build`, затем `gradlew build verificationJar` в AstraWeapons. Сборка: сначала `AstraPlus/gradlew build`, затем `gradlew build verificationJar` в AstraWeapons.
+1 -1
View File
@@ -3,7 +3,7 @@ plugins {
id("net.neoforged.moddev") version "2.0.146" id("net.neoforged.moddev") version "2.0.146"
} }
group = "online.astradev" group = "online.astradev"
version = "0.1.0" version = "0.1.1"
repositories { mavenCentral() } repositories { mavenCentral() }
dependencies { dependencies {
compileOnly(files(providers.gradleProperty("astraPlusJar").orElse("../AstraPlus/build/libs/AstraPlus-0.5.67.jar"))) compileOnly(files(providers.gradleProperty("astraPlusJar").orElse("../AstraPlus/build/libs/AstraPlus-0.5.67.jar")))
+18
View File
@@ -0,0 +1,18 @@
# Исправление анимаций 0.1.1
Исходная проблема подтверждена двумя пользовательскими записями: позы предметов менялись скачками поверх обычного взмаха, перчатки смещались отдельно от кистей, след твинблейда выглядел как широкий обруч.
Ванильный клиент сохранён. Покадровая подмена модели во время взмаха удалена. Используются штатные `swing_animation` Minecraft 26.2: прямые удары — STAB, хук и твинблейд — WHACK. Клиент интерполирует движение руки сам. Неактивная перчатка имеет однокадровый NONE; сервер отправляет взмах принятой руки после завершения локального клика, чтобы основной взмах не подавлял левый.
Все третьеличные преобразования наследуются от исходных моделей: оружие остаётся прикреплённым к кисти. Хват твинблейда в первом лице уменьшен и наклонён. След удара стал узким, с яркой кромкой, и проходит четыре кадра по возрасту конкретного удара. Новые ресурсы находятся в `v2`, поэтому обновляются без перезаписи пользовательских файлов.
Проверки:
- JUnit проверяет установку новых ресурсов, сохранение пользовательских правок, отсутствие отрыва моделей от рук через третьеличные смещения.
- Изолированный сервер проверяет серию, точный урон, откат, щиты, область твинблейда, тип и длительность штатного взмаха и восстановление реальных компонентов при перемещении в творческом инвентаре.
- Клиент без игровых модов AstraPlus/AstraWeapons отправляет реальные пакеты взмаха; записываются 360 последовательных кадров с частотой 20 кадров/с, от первого и третьего лица. Дополнительно проверяется исчезновение визуальной перчатки при переключении на твинблейд.
- `tools/encode-review.ps1` собирает четыре ракурса в один MP4: сверху перчатки, снизу твинблейд; слева первое лицо, справа третье.
Это доступные ванильному клиенту движения. Они не воспроизводят произвольную скелетную анимацию Minecraft Dungeons.
Результат выпуска 13.09.2026: 7 JUnit-тестов без ошибок; серверная проверка `build/verify-20260913-102920-88497e` — PASS. Клиент `build/weapons-capture-20260913-102945-3d1653` проверил 49 моделей, 23 звуковых файла и 360 последовательных кадров. Запись: `build/animation-review-0.1.1.mp4`.
@@ -49,28 +49,25 @@ public final class WeaponsCapture {
if(mc.gui.screen() instanceof DisconnectedScreen)throw new IllegalStateException("Disconnected during capture"); if(mc.gui.screen() instanceof DisconnectedScreen)throw new IllegalStateException("Disconnected during capture");
if(mc.player==null || mc.level==null || mc.gui.overlay()!=null)return; if(mc.player==null || mc.level==null || mc.gui.overlay()!=null)return;
mc.gui.toastManager().clear(); mc.gui.toastManager().clear();
if(stage>6) { if(stage>3) {
if(!audio.isDone())return; if(!audio.isDone())return;
long count; long count;
try(var files=Files.list(mc.gameDirectory.toPath().resolve("screenshots"))) {count=files.filter(f->f.getFileName().toString().startsWith("weapons-")).count();} try(var files=Files.list(mc.gameDirectory.toPath().resolve("screenshots"))) {count=files.filter(f->f.getFileName().toString().startsWith("weapons-")).count();}
if(count<21)return; if(count<360)return;
finish("PASS: "+models+" client item codecs/baked models, "+audio.join()+" original audio samples, 21 hand/area screenshots");return; finish("PASS: "+models+" client item codecs/baked models, "+audio.join()+" original audio samples, 360 consecutive frames of real swing packets, first/third-person");return;
} }
if(!Files.exists(server.resolve("capture-stage-"+stage+".txt")))return; if(!Files.exists(server.resolve("capture-stage-"+stage+".txt")))return;
++age; ++age;
if(age==35||age==55||age==75) { mc.options.setCameraType(stage%2==0 ? net.minecraft.client.CameraType.FIRST_PERSON : net.minecraft.client.CameraType.THIRD_PERSON_FRONT);
if(stage==6 && age>40) { if(stage==2 && age==20 && !mc.player.getOffhandItem().isEmpty()) throw new IllegalStateException("Ghost glove remains after switching to twinblade");
var displays=new com.google.gson.JsonArray(); if(age>=25 && age<=110 && (age-25)%(stage<2 ? 6 : 16)==0) {
for(var e:mc.level.entitiesForRendering()) if(e instanceof net.minecraft.world.entity.Display.ItemDisplay d) { // Same swing call as vanilla left-click-air: local prediction + ServerboundSwingPacket.
var state=d.itemRenderState(); mc.player.swing(net.minecraft.world.InteractionHand.MAIN_HAND);
if(state!=null) {var row=new com.google.gson.JsonObject();row.addProperty("model",String.valueOf(state.itemStack().get(net.minecraft.core.component.DataComponents.ITEM_MODEL)));row.addProperty("position",d.position().toString());row.addProperty("age",d.tickCount);displays.add(row);}
}
Files.writeString(mc.gameDirectory.toPath().resolve("slash-displays-"+age+".json"),displays.toString());
if(displays.isEmpty())throw new IllegalStateException("No textured slash received by client");
}
net.minecraft.client.Screenshot.grab(mc.gameDirectory,"weapons-"+stage+"-"+age+".png",mc.gameRenderer.mainRenderTarget(),1,ignored->{});
} }
if(age>=90) { Files.writeString(server.resolve("capture-ack-"+stage+".txt"),"done");stage++;age=0; } if(age>=20 && age<110) {
net.minecraft.client.Screenshot.grab(mc.gameDirectory,String.format("weapons-%d-%03d.png",stage,age-20),mc.gameRenderer.mainRenderTarget(),1,ignored->{});
}
if(age>=125) { Files.writeString(server.resolve("capture-ack-"+stage+".txt"),"done");stage++;age=0; }
} catch(Throwable error) { error.printStackTrace();finish("FAIL: "+error); } } catch(Throwable error) { error.printStackTrace();finish("FAIL: "+error); }
} }
private void finish(String result) { private void finish(String result) {
@@ -102,7 +102,7 @@ public final class GauntletCombat {
WeaponPresentation.animate(p,Combo.pose(step),Combo.left(step),config.gauntletCooldownTicks); WeaponPresentation.animate(p,Combo.pose(step),Combo.left(step),config.gauntletCooldownTicks);
sound(p,step == 6 ? "swing_kick" : step == 5 ? "swing_medium" : "swing_short",.7f); sound(p,step == 6 ? "swing_kick" : step == 5 ? "swing_medium" : "swing_short",.7f);
if (batch.hit) sound(p,step == 6 ? "hit_kick" : step == 5 ? "hit_medium" : "hit_light",.8f); if (batch.hit) sound(p,step == 6 ? "hit_kick" : step == 5 ? "hit_medium" : "hit_light",.8f);
p.swing(Combo.left(step) ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND,true); // WeaponPresentation sends the accepted hand after the local one-tick input swing.
} }
public static boolean attackAllowed(Player p,Entity t) { return BATCHES.get(p.getUUID()).accepted.contains(t.getId()); } public static boolean attackAllowed(Player p,Entity t) { return BATCHES.get(p.getUUID()).accepted.contains(t.getId()); }
public static boolean hurt(Player p,Entity t,DamageSource source,float damage) { public static boolean hurt(Player p,Entity t,DamageSource source,float damage) {
@@ -13,6 +13,11 @@ import online.astradev.weapons.resource.WeaponPresentation;
@Mixin(ServerGamePacketListenerImpl.class) @Mixin(ServerGamePacketListenerImpl.class)
public abstract class GauntletInventoryMixin { public abstract class GauntletInventoryMixin {
@Shadow public ServerPlayer player; @Shadow public ServerPlayer player;
@ModifyVariable(method="handleSetCreativeModeSlot",at=@At("HEAD"),argsOnly=true)
private ServerboundSetCreativeModeSlotPacket astraweapons$restore(ServerboundSetCreativeModeSlotPacket packet) {
var restored=WeaponPresentation.restorePresentation(packet.itemStack());
return restored==packet.itemStack() ? packet : new ServerboundSetCreativeModeSlotPacket(packet.slotNum(),restored);
}
// Each injection occurs AFTER vanilla's packet thread validation. // Each injection occurs AFTER vanilla's packet thread validation.
@Inject(method="handleContainerClick",at=@At(value="INVOKE",target="Lnet/minecraft/server/level/ServerPlayer;resetLastActionTime()V"),cancellable=true) @Inject(method="handleContainerClick",at=@At(value="INVOKE",target="Lnet/minecraft/server/level/ServerPlayer;resetLastActionTime()V"),cancellable=true)
private void astraweapons$slot(ServerboundContainerClickPacket p,CallbackInfo ci) { private void astraweapons$slot(ServerboundContainerClickPacket p,CallbackInfo ci) {
@@ -18,14 +18,17 @@ public abstract class TwinbladeSwingMixin {
@Shadow public ServerPlayer player; @Shadow public ServerPlayer player;
@Inject(method = "handleAnimate", at = @At(value = "INVOKE", @Inject(method = "handleAnimate", at = @At(value = "INVOKE",
target = "Lnet/minecraft/server/level/ServerPlayer;swing(Lnet/minecraft/world/InteractionHand;)V")) target = "Lnet/minecraft/server/level/ServerPlayer;swing(Lnet/minecraft/world/InteractionHand;)V"), cancellable=true)
private void astraplus$airSwing(ServerboundSwingPacket packet, CallbackInfo ci) { private void astraplus$airSwing(ServerboundSwingPacket packet, CallbackInfo ci) {
if (packet.getHand() != InteractionHand.MAIN_HAND || player.isSpectator() if (packet.getHand() != InteractionHand.MAIN_HAND || player.isSpectator()
|| (!TwinbladeCombat.holdsTwinblade(player) && !online.astradev.weapons.behavior.GauntletCombat.holds(player))) { return; } || (!TwinbladeCombat.holdsTwinblade(player) && !online.astradev.weapons.behavior.GauntletCombat.holds(player))) { return; }
// Mining/interacting with a block is not an air attack. Entity-hit packets already consume charge. // Mining/interacting with a block is not an air attack. Entity-hit packets already consume charge.
if (player.pick(player.blockInteractionRange(), 1, false).getType() == HitResult.Type.BLOCK) { return; } if (player.pick(player.blockInteractionRange(), 1, false).getType() == HitResult.Type.BLOCK) { return; }
// Run after packet thread validation, but before vanilla swing resets the attack charge. // Run after packet thread validation, but before vanilla swing resets the attack charge.
if (online.astradev.weapons.behavior.GauntletCombat.holds(player)) online.astradev.weapons.behavior.GauntletCombat.strike(player); if (online.astradev.weapons.behavior.GauntletCombat.holds(player)) {
online.astradev.weapons.behavior.GauntletCombat.strike(player);
ci.cancel(); // Do not broadcast an extra right-hand swing over the accepted combo hand.
}
else TwinbladeCombat.strike(player); else TwinbladeCombat.strike(player);
} }
} }
@@ -14,20 +14,25 @@ import org.joml.*;
public final class SlashDisplay extends Display.ItemDisplay { public final class SlashDisplay extends Display.ItemDisplay {
private static final List<SlashDisplay> ACTIVE = new ArrayList<>(); private static final List<SlashDisplay> ACTIVE = new ArrayList<>();
private final long expires; private final long expires;
private final long born;
private final boolean fiery;
private final ServerPlayer owner; private final ServerPlayer owner;
private SlashDisplay(ServerPlayer p,double reach,boolean fiery) { private SlashDisplay(ServerPlayer p,double reach,boolean fiery) {
super(EntityTypes.ITEM_DISPLAY,p.level()); owner=p; expires=p.level().getGameTime()+5; super(EntityTypes.ITEM_DISPLAY,p.level()); owner=p; born=p.level().getGameTime(); expires=born+4; this.fiery=fiery;
setNoGravity(true);setInvulnerable(true); setNoGravity(true);setInvulnerable(true);
setPos(p.getX(),p.getY()+1,p.getZ()); setPos(p.getX(),p.getY()+1.15,p.getZ());
// Vanilla ItemDisplayRenderer adds a 180-degree item rotation; compensate so +Z is the hit sector. // Vanilla ItemDisplayRenderer adds a 180-degree item rotation; compensate so +Z is the hit sector.
setYRot(p.getYRot()+180); setYRot(p.getYRot()+180);
var item=new ItemStack(Items.PAPER); frame(0);
item.set(DataComponents.ITEM_MODEL,Identifier.parse("astraweapons:slash"+(fiery?"_fire":"")));
getSlot(0).set(item);
((online.astradev.weapons.mixin.DisplayAccess)(Object)this).astraweapons$transform(new Transformation(new Vector3f(),new Quaternionf(),new Vector3f((float)reach*2),new Quaternionf())); ((online.astradev.weapons.mixin.DisplayAccess)(Object)this).astraweapons$transform(new Transformation(new Vector3f(),new Quaternionf(),new Vector3f((float)reach*2),new Quaternionf()));
((online.astradev.weapons.mixin.DisplayAccess)(Object)this).astraweapons$brightness(new net.minecraft.util.Brightness(15,15)); ((online.astradev.weapons.mixin.DisplayAccess)(Object)this).astraweapons$brightness(new net.minecraft.util.Brightness(15,15));
addTag("astraweapons:slash"); addTag("astraweapons:slash");
} }
private void frame(int frame) {
var item=new ItemStack(Items.PAPER);
item.set(DataComponents.ITEM_MODEL,Identifier.parse("astraweapons:v2/slash_"+(fiery?"fire_":"")+frame));
getSlot(0).set(item);
}
public static void spawn(ServerPlayer player,double reach,boolean fiery) { public static void spawn(ServerPlayer player,double reach,boolean fiery) {
var display=new SlashDisplay(player,reach,fiery); var display=new SlashDisplay(player,reach,fiery);
if(player.level().addFreshEntity(display)) ACTIVE.add(display); if(player.level().addFreshEntity(display)) ACTIVE.add(display);
@@ -37,6 +42,7 @@ public final class SlashDisplay extends Display.ItemDisplay {
if(display.isRemoved() || !display.owner.isAlive() || display.owner.level()!=display.level() || display.level().getGameTime()>=display.expires) { if(display.isRemoved() || !display.owner.isAlive() || display.owner.level()!=display.level() || display.level().getGameTime()>=display.expires) {
display.discard();return true; display.discard();return true;
} }
display.frame((int)(display.level().getGameTime()-display.born));
return false; return false;
}); });
} }
@@ -18,8 +18,9 @@ import online.astradev.weapons.behavior.TwinbladeCombat;
public final class WeaponPresentation { public final class WeaponPresentation {
private record Animation(ItemStack weapon, String pose, boolean left, long start, int ticks, Object level) {} private record Animation(ItemStack weapon, String pose, boolean left, long start, int ticks, Object level) {}
private static final Map<UUID,Animation> ANIMATIONS = new HashMap<>(); private static final Map<UUID,Animation> ANIMATIONS = new HashMap<>();
private static final Set<UUID> WEARING = new HashSet<>(); private record Presentation(String kind, int slot, ItemStack weapon) {}
private static final Identifier GHOST = Identifier.parse("astraweapons:gauntlet_offhand"); private static final Map<UUID,Presentation> PRESENTED = new HashMap<>();
private static final Set<UUID> SWING_SENT = new HashSet<>();
private WeaponPresentation() {} private WeaponPresentation() {}
public static boolean reserveOffhand(ServerPlayer p) { public static boolean reserveOffhand(ServerPlayer p) {
if (!GauntletCombat.holds(p)) return false; if (!GauntletCombat.holds(p)) return false;
@@ -44,29 +45,31 @@ public final class WeaponPresentation {
return true; return true;
} }
public static void animate(ServerPlayer p,String pose,boolean left,int ticks) { public static void animate(ServerPlayer p,String pose,boolean left,int ticks) {
SWING_SENT.remove(p.getUUID());
ANIMATIONS.put(p.getUUID(),new Animation(p.getMainHandItem(),pose,left,p.level().getGameTime(),ticks,p.level())); sync(p); ANIMATIONS.put(p.getUUID(),new Animation(p.getMainHandItem(),pose,left,p.level().getGameTime(),ticks,p.level())); sync(p);
} }
private static ItemStack visual(ServerPlayer p,ItemStack original,boolean offhand) { private static ItemStack visual(ServerPlayer p,ItemStack original,boolean offhand) {
boolean gloves = GauntletCombat.holds(p) && p.getOffhandItem().isEmpty() && !p.isSpectator() && p.isAlive(); boolean gloves = GauntletCombat.holds(p) && p.getOffhandItem().isEmpty() && !p.isSpectator() && p.isAlive();
var animation = ANIMATIONS.get(p.getUUID()); var animation = ANIMATIONS.get(p.getUUID());
boolean animating = animation != null && animation.weapon == p.getMainHandItem() && animation.level == p.level(); boolean animating = animation != null && animation.weapon == p.getMainHandItem() && animation.level == p.level();
if (offhand) { if (gloves) {
if (!gloves) return original; var copy = offhand ? new ItemStack(Items.PAPER) : original.copy();
var ghost = new ItemStack(Items.PAPER); boolean active = animating && animation.left == offhand;
ghost.set(DataComponents.ITEM_NAME,net.minecraft.network.chat.Component.literal("Левая боевая перчатка")); String pose = active ? animation.pose : "guard";
ghost.set(DataComponents.ITEM_MODEL,animating && animation.left ? frame(p,animation) : GHOST); copy.set(DataComponents.ITEM_MODEL,Identifier.parse("astraweapons:v2/"+pose));
return ghost; if (offhand) copy.set(DataComponents.ITEM_NAME,net.minecraft.network.chat.Component.literal("Левая боевая перчатка"));
var type = !active ? SwingAnimationType.NONE : pose.equals("hook") ? SwingAnimationType.WHACK : SwingAnimationType.STAB;
copy.set(DataComponents.SWING_ANIMATION,new net.minecraft.world.item.component.SwingAnimation(type,active ? Math.max(1,animation.ticks-1) : 1));
return copy;
} }
if (animating && (!gloves || !animation.left)) { if (!offhand && TwinbladeCombat.holdsTwinblade(p)) {
var copy = original.copy(); copy.set(DataComponents.ITEM_MODEL,frame(p,animation)); return copy; var copy=original.copy();
copy.set(DataComponents.ITEM_MODEL,Identifier.parse("astraweapons:v2/twinblade"));
copy.set(DataComponents.SWING_ANIMATION,new net.minecraft.world.item.component.SwingAnimation(SwingAnimationType.WHACK,9));
return copy;
} }
return original; return original;
} }
private static Identifier frame(ServerPlayer p,Animation animation) {
int elapsed = (int)(p.level().getGameTime()-animation.start);
int frame = Math.clamp(elapsed*6/Math.max(1,animation.ticks),0,5);
return Identifier.parse("astraweapons:animation/"+animation.pose+"_"+frame);
}
/** Used only by the outgoing packet mixin on the server thread. */ /** Used only by the outgoing packet mixin on the server thread. */
public static Packet<?> project(ServerPlayer viewer,Packet<?> packet) { public static Packet<?> project(ServerPlayer viewer,Packet<?> packet) {
if (packet instanceof ClientboundBundlePacket bundle) { if (packet instanceof ClientboundBundlePacket bundle) {
@@ -107,7 +110,16 @@ public final class WeaponPresentation {
} }
public static boolean ghost(ItemStack stack) { public static boolean ghost(ItemStack stack) {
var id=stack.get(DataComponents.ITEM_MODEL); var id=stack.get(DataComponents.ITEM_MODEL);
return id!=null && (id.equals(GHOST) || id.getNamespace().equals("astraweapons") && id.getPath().startsWith("animation/")); return id!=null && id.getNamespace().equals("astraweapons") && (id.getPath().startsWith("animation/") || stack.is(Items.PAPER) && id.getPath().startsWith("v2/"));
}
/** A creative inventory move sends the visible copy back; strip only our presentation fields. */
public static ItemStack restorePresentation(ItemStack stack) {
var model=stack.get(DataComponents.ITEM_MODEL);
String id=online.astradev.plus.content.PlusContent.id(stack);
boolean weapon=GauntletCombat.ID.equals(id) && stack.is(Items.IRON_SWORD)
|| TwinbladeCombat.ID.equals(id) && stack.is(Items.NETHERITE_SWORD);
if(!weapon || model==null || !model.getNamespace().equals("astraweapons") || !model.getPath().startsWith("v2/")) return stack;
var copy=stack.copy();copy.set(DataComponents.ITEM_MODEL,Identifier.parse(id));copy.set(DataComponents.SWING_ANIMATION,online.astradev.plus.AstraPlus.content().entry(id).stack(1).get(DataComponents.SWING_ANIMATION));return copy;
} }
public static void sync(ServerPlayer p) { public static void sync(ServerPlayer p) {
if (p.connection==null) return; if (p.connection==null) return;
@@ -121,18 +133,27 @@ public final class WeaponPresentation {
for(var p:server.getPlayerList().getPlayers()) { for(var p:server.getPlayerList().getPlayers()) {
online.add(p.getUUID()); online.add(p.getUUID());
boolean wearing=GauntletCombat.holds(p) && p.isAlive() && !p.isSpectator() && reserveOffhand(p); boolean wearing=GauntletCombat.holds(p) && p.isAlive() && !p.isSpectator() && reserveOffhand(p);
boolean changed=wearing ? WEARING.add(p.getUUID()) : WEARING.remove(p.getUUID()); String presented=wearing ? "gauntlets" : TwinbladeCombat.holdsTwinblade(p) ? "twinblade" : "none";
var presentation=new Presentation(presented,presented.equals("none") ? -1 : p.getInventory().getSelectedSlot(),presented.equals("none") ? ItemStack.EMPTY : p.getMainHandItem());
boolean changed=!presentation.equals(PRESENTED.put(p.getUUID(),presentation));
var animation=ANIMATIONS.get(p.getUUID()); var animation=ANIMATIONS.get(p.getUUID());
if(animation!=null) { if(animation!=null) {
if(!p.isAlive() || p.level()!=animation.level || p.getMainHandItem()!=animation.weapon || p.level().getGameTime()-animation.start>=animation.ticks) if(!p.isAlive() || p.level()!=animation.level || p.getMainHandItem()!=animation.weapon || p.level().getGameTime()-animation.start>=animation.ticks)
ANIMATIONS.remove(p.getUUID()); {
sync(p); ANIMATIONS.remove(p.getUUID()); SWING_SENT.remove(p.getUUID()); sync(p);
}
else if(GauntletCombat.holds(p) && p.level().getGameTime()-animation.start>=1 && SWING_SENT.add(p.getUUID())) {
// The local one-tick NONE swing has finished. Send the accepted hand once;
// vanilla now interpolates the arm and weapon together, without model-frame spam.
p.swinging=false; p.swingTime=-1;
p.swing(animation.left ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND,true);
}
} else if(changed) sync(p); } else if(changed) sync(p);
} }
WEARING.retainAll(online); ANIMATIONS.keySet().retainAll(online); PRESENTED.keySet().retainAll(online); ANIMATIONS.keySet().retainAll(online); SWING_SENT.retainAll(online);
} }
public static void close(MinecraftServer server) { public static void close(MinecraftServer server) {
ANIMATIONS.clear(); WEARING.clear(); ANIMATIONS.clear(); PRESENTED.clear(); SWING_SENT.clear();
// Projection naturally ends when the connection closes; no stored items need restoration. // Projection naturally ends when the connection closes; no stored items need restoration.
} }
} }
@@ -0,0 +1,24 @@
{
"hand_animation_on_swap": false,
"model": {
"type": "minecraft:select",
"property": "minecraft:display_context",
"cases": [
{
"when": [
"gui",
"ground",
"fixed"
],
"model": {
"type": "minecraft:model",
"model": "astraweapons:item/iron_gauntlet_2d"
}
}
],
"fallback": {
"type": "minecraft:model",
"model": "astraweapons:v2/guard"
}
}
}
@@ -0,0 +1,24 @@
{
"hand_animation_on_swap": false,
"model": {
"type": "minecraft:select",
"property": "minecraft:display_context",
"cases": [
{
"when": [
"gui",
"ground",
"fixed"
],
"model": {
"type": "minecraft:model",
"model": "astraweapons:item/iron_gauntlet_2d"
}
}
],
"fallback": {
"type": "minecraft:model",
"model": "astraweapons:v2/hook"
}
}
}
@@ -0,0 +1,24 @@
{
"hand_animation_on_swap": false,
"model": {
"type": "minecraft:select",
"property": "minecraft:display_context",
"cases": [
{
"when": [
"gui",
"ground",
"fixed"
],
"model": {
"type": "minecraft:model",
"model": "astraweapons:item/iron_gauntlet_2d"
}
}
],
"fallback": {
"type": "minecraft:model",
"model": "astraweapons:v2/jab"
}
}
}
@@ -0,0 +1,24 @@
{
"hand_animation_on_swap": false,
"model": {
"type": "minecraft:select",
"property": "minecraft:display_context",
"cases": [
{
"when": [
"gui",
"ground",
"fixed"
],
"model": {
"type": "minecraft:model",
"model": "astraweapons:item/iron_gauntlet_2d"
}
}
],
"fallback": {
"type": "minecraft:model",
"model": "astraweapons:v2/lunge"
}
}
}
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "astraweapons:v2/slash_0"
}
}
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "astraweapons:v2/slash_1"
}
}
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "astraweapons:v2/slash_2"
}
}
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "astraweapons:v2/slash_3"
}
}
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "astraweapons:v2/slash_fire_0"
}
}
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "astraweapons:v2/slash_fire_1"
}
}
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "astraweapons:v2/slash_fire_2"
}
}
@@ -0,0 +1,6 @@
{
"model": {
"type": "minecraft:model",
"model": "astraweapons:v2/slash_fire_3"
}
}
@@ -0,0 +1,24 @@
{
"hand_animation_on_swap": false,
"model": {
"type": "minecraft:select",
"property": "minecraft:display_context",
"cases": [
{
"when": [
"gui",
"ground",
"fixed"
],
"model": {
"type": "minecraft:model",
"model": "astraplus:internal/twinblade_gui"
}
}
],
"fallback": {
"type": "minecraft:model",
"model": "astraweapons:v2/twinblade"
}
}
}
@@ -0,0 +1,24 @@
{
"hand_animation_on_swap": false,
"model": {
"type": "minecraft:select",
"property": "minecraft:display_context",
"cases": [
{
"when": [
"gui",
"ground",
"fixed"
],
"model": {
"type": "minecraft:model",
"model": "astraweapons:item/iron_gauntlet_2d"
}
}
],
"fallback": {
"type": "minecraft:model",
"model": "astraweapons:v2/uppercut"
}
}
}
@@ -0,0 +1,39 @@
{
"parent": "astraweapons:item/iron_gauntlet_3d",
"display": {
"firstperson_righthand": {
"rotation": [
-24,
0,
-8
],
"translation": [
0.5,
5.0,
0
],
"scale": [
0.9,
0.9,
0.9
]
},
"firstperson_lefthand": {
"rotation": [
-24,
0,
8
],
"translation": [
-0.5,
5.0,
0
],
"scale": [
0.9,
0.9,
0.9
]
}
}
}
@@ -0,0 +1,39 @@
{
"parent": "astraweapons:item/iron_gauntlet_3d",
"display": {
"firstperson_righthand": {
"rotation": [
-24,
0,
4
],
"translation": [
0.5,
5.0,
0
],
"scale": [
0.9,
0.9,
0.9
]
},
"firstperson_lefthand": {
"rotation": [
-24,
0,
-4
],
"translation": [
-0.5,
5.0,
0
],
"scale": [
0.9,
0.9,
0.9
]
}
}
}
@@ -0,0 +1,39 @@
{
"parent": "astraweapons:item/iron_gauntlet_3d",
"display": {
"firstperson_righthand": {
"rotation": [
-24,
0,
-8
],
"translation": [
0.5,
5.0,
0
],
"scale": [
0.9,
0.9,
0.9
]
},
"firstperson_lefthand": {
"rotation": [
-24,
0,
8
],
"translation": [
-0.5,
5.0,
0
],
"scale": [
0.9,
0.9,
0.9
]
}
}
}
@@ -0,0 +1,39 @@
{
"parent": "astraweapons:item/iron_gauntlet_3d",
"display": {
"firstperson_righthand": {
"rotation": [
-24,
0,
-8
],
"translation": [
0.5,
5.0,
0
],
"scale": [
0.9,
0.9,
0.9
]
},
"firstperson_lefthand": {
"rotation": [
-24,
0,
8
],
"translation": [
-0.5,
5.0,
0
],
"scale": [
0.9,
0.9,
0.9
]
}
}
}
@@ -0,0 +1,43 @@
{
"textures": {
"slash": "astraweapons:item/v2/slash_0",
"particle": "astraweapons:item/v2/slash_0"
},
"elements": [
{
"from": [
0,
8,
0
],
"to": [
16,
8,
16
],
"shade": false,
"light_emission": 15,
"faces": {
"up": {
"texture": "#slash",
"uv": [
0,
0,
16,
16
]
},
"down": {
"texture": "#slash",
"uv": [
0,
0,
16,
16
],
"rotation": 180
}
}
}
]
}
@@ -0,0 +1,43 @@
{
"textures": {
"slash": "astraweapons:item/v2/slash_1",
"particle": "astraweapons:item/v2/slash_1"
},
"elements": [
{
"from": [
0,
8,
0
],
"to": [
16,
8,
16
],
"shade": false,
"light_emission": 15,
"faces": {
"up": {
"texture": "#slash",
"uv": [
0,
0,
16,
16
]
},
"down": {
"texture": "#slash",
"uv": [
0,
0,
16,
16
],
"rotation": 180
}
}
}
]
}
@@ -0,0 +1,43 @@
{
"textures": {
"slash": "astraweapons:item/v2/slash_2",
"particle": "astraweapons:item/v2/slash_2"
},
"elements": [
{
"from": [
0,
8,
0
],
"to": [
16,
8,
16
],
"shade": false,
"light_emission": 15,
"faces": {
"up": {
"texture": "#slash",
"uv": [
0,
0,
16,
16
]
},
"down": {
"texture": "#slash",
"uv": [
0,
0,
16,
16
],
"rotation": 180
}
}
}
]
}
@@ -0,0 +1,43 @@
{
"textures": {
"slash": "astraweapons:item/v2/slash_3",
"particle": "astraweapons:item/v2/slash_3"
},
"elements": [
{
"from": [
0,
8,
0
],
"to": [
16,
8,
16
],
"shade": false,
"light_emission": 15,
"faces": {
"up": {
"texture": "#slash",
"uv": [
0,
0,
16,
16
]
},
"down": {
"texture": "#slash",
"uv": [
0,
0,
16,
16
],
"rotation": 180
}
}
}
]
}
@@ -0,0 +1,43 @@
{
"textures": {
"slash": "astraweapons:item/v2/slash_fire_0",
"particle": "astraweapons:item/v2/slash_fire_0"
},
"elements": [
{
"from": [
0,
8,
0
],
"to": [
16,
8,
16
],
"shade": false,
"light_emission": 15,
"faces": {
"up": {
"texture": "#slash",
"uv": [
0,
0,
16,
16
]
},
"down": {
"texture": "#slash",
"uv": [
0,
0,
16,
16
],
"rotation": 180
}
}
}
]
}
@@ -0,0 +1,43 @@
{
"textures": {
"slash": "astraweapons:item/v2/slash_fire_1",
"particle": "astraweapons:item/v2/slash_fire_1"
},
"elements": [
{
"from": [
0,
8,
0
],
"to": [
16,
8,
16
],
"shade": false,
"light_emission": 15,
"faces": {
"up": {
"texture": "#slash",
"uv": [
0,
0,
16,
16
]
},
"down": {
"texture": "#slash",
"uv": [
0,
0,
16,
16
],
"rotation": 180
}
}
}
]
}
@@ -0,0 +1,43 @@
{
"textures": {
"slash": "astraweapons:item/v2/slash_fire_2",
"particle": "astraweapons:item/v2/slash_fire_2"
},
"elements": [
{
"from": [
0,
8,
0
],
"to": [
16,
8,
16
],
"shade": false,
"light_emission": 15,
"faces": {
"up": {
"texture": "#slash",
"uv": [
0,
0,
16,
16
]
},
"down": {
"texture": "#slash",
"uv": [
0,
0,
16,
16
],
"rotation": 180
}
}
}
]
}
@@ -0,0 +1,43 @@
{
"textures": {
"slash": "astraweapons:item/v2/slash_fire_3",
"particle": "astraweapons:item/v2/slash_fire_3"
},
"elements": [
{
"from": [
0,
8,
0
],
"to": [
16,
8,
16
],
"shade": false,
"light_emission": 15,
"faces": {
"up": {
"texture": "#slash",
"uv": [
0,
0,
16,
16
]
},
"down": {
"texture": "#slash",
"uv": [
0,
0,
16,
16
],
"rotation": 180
}
}
}
]
}
@@ -0,0 +1,39 @@
{
"parent": "astraplus:item/netherite_twinblade",
"display": {
"firstperson_righthand": {
"rotation": [
0,
-90,
55
],
"translation": [
1.1,
1.4,
0
],
"scale": [
1.85,
1.85,
0.68
]
},
"firstperson_lefthand": {
"rotation": [
0,
90,
-55
],
"translation": [
1.1,
1.4,
0
],
"scale": [
1.85,
1.85,
0.68
]
}
}
}
@@ -0,0 +1,39 @@
{
"parent": "astraweapons:item/iron_gauntlet_3d",
"display": {
"firstperson_righthand": {
"rotation": [
-36,
0,
-8
],
"translation": [
0.5,
5.0,
0
],
"scale": [
0.9,
0.9,
0.9
]
},
"firstperson_lefthand": {
"rotation": [
-36,
0,
8
],
"translation": [
-0.5,
5.0,
0
],
"scale": [
0.9,
0.9,
0.9
]
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 524 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 718 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 567 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 678 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 527 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 720 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 575 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 685 B

+36
View File
@@ -40,6 +40,20 @@ resources/assets/astraweapons/items/animation/uppercut_5.json
resources/assets/astraweapons/items/gauntlet_offhand.json resources/assets/astraweapons/items/gauntlet_offhand.json
resources/assets/astraweapons/items/slash.json resources/assets/astraweapons/items/slash.json
resources/assets/astraweapons/items/slash_fire.json resources/assets/astraweapons/items/slash_fire.json
resources/assets/astraweapons/items/v2/guard.json
resources/assets/astraweapons/items/v2/hook.json
resources/assets/astraweapons/items/v2/jab.json
resources/assets/astraweapons/items/v2/lunge.json
resources/assets/astraweapons/items/v2/slash_0.json
resources/assets/astraweapons/items/v2/slash_1.json
resources/assets/astraweapons/items/v2/slash_2.json
resources/assets/astraweapons/items/v2/slash_3.json
resources/assets/astraweapons/items/v2/slash_fire_0.json
resources/assets/astraweapons/items/v2/slash_fire_1.json
resources/assets/astraweapons/items/v2/slash_fire_2.json
resources/assets/astraweapons/items/v2/slash_fire_3.json
resources/assets/astraweapons/items/v2/twinblade.json
resources/assets/astraweapons/items/v2/uppercut.json
resources/assets/astraweapons/lang/en_us.json resources/assets/astraweapons/lang/en_us.json
resources/assets/astraweapons/lang/ru_ru.json resources/assets/astraweapons/lang/ru_ru.json
resources/assets/astraweapons/models/animation/hook_0.json resources/assets/astraweapons/models/animation/hook_0.json
@@ -76,6 +90,20 @@ resources/assets/astraweapons/models/effect/slash.json
resources/assets/astraweapons/models/effect/slash_fire.json resources/assets/astraweapons/models/effect/slash_fire.json
resources/assets/astraweapons/models/item/iron_gauntlet_2d.json resources/assets/astraweapons/models/item/iron_gauntlet_2d.json
resources/assets/astraweapons/models/item/iron_gauntlet_3d.json resources/assets/astraweapons/models/item/iron_gauntlet_3d.json
resources/assets/astraweapons/models/v2/guard.json
resources/assets/astraweapons/models/v2/hook.json
resources/assets/astraweapons/models/v2/jab.json
resources/assets/astraweapons/models/v2/lunge.json
resources/assets/astraweapons/models/v2/slash_0.json
resources/assets/astraweapons/models/v2/slash_1.json
resources/assets/astraweapons/models/v2/slash_2.json
resources/assets/astraweapons/models/v2/slash_3.json
resources/assets/astraweapons/models/v2/slash_fire_0.json
resources/assets/astraweapons/models/v2/slash_fire_1.json
resources/assets/astraweapons/models/v2/slash_fire_2.json
resources/assets/astraweapons/models/v2/slash_fire_3.json
resources/assets/astraweapons/models/v2/twinblade.json
resources/assets/astraweapons/models/v2/uppercut.json
resources/assets/astraweapons/sounds.json resources/assets/astraweapons/sounds.json
resources/assets/astraweapons/sounds/gauntlets/sfx_item_gauntletshitimpactkick-001_soundwave.ogg resources/assets/astraweapons/sounds/gauntlets/sfx_item_gauntletshitimpactkick-001_soundwave.ogg
resources/assets/astraweapons/sounds/gauntlets/sfx_item_gauntletshitimpactkick-002_soundwave.ogg resources/assets/astraweapons/sounds/gauntlets/sfx_item_gauntletshitimpactkick-002_soundwave.ogg
@@ -107,3 +135,11 @@ resources/assets/astraweapons/textures/item/slash.png
resources/assets/astraweapons/textures/item/slash.png.mcmeta resources/assets/astraweapons/textures/item/slash.png.mcmeta
resources/assets/astraweapons/textures/item/slash_fire.png resources/assets/astraweapons/textures/item/slash_fire.png
resources/assets/astraweapons/textures/item/slash_fire.png.mcmeta resources/assets/astraweapons/textures/item/slash_fire.png.mcmeta
resources/assets/astraweapons/textures/item/v2/slash_0.png
resources/assets/astraweapons/textures/item/v2/slash_1.png
resources/assets/astraweapons/textures/item/v2/slash_2.png
resources/assets/astraweapons/textures/item/v2/slash_3.png
resources/assets/astraweapons/textures/item/v2/slash_fire_0.png
resources/assets/astraweapons/textures/item/v2/slash_fire_1.png
resources/assets/astraweapons/textures/item/v2/slash_fire_2.png
resources/assets/astraweapons/textures/item/v2/slash_fire_3.png
@@ -28,6 +28,13 @@ class WeaponsResourcesTest {
assertTrue(Files.readString(assets.resolve("credits/THIRD_PARTY_NOTICES.md")).contains("joshieman")); assertTrue(Files.readString(assets.resolve("credits/THIRD_PARTY_NOTICES.md")).contains("joshieman"));
for(String pose:java.util.List.of("jab","hook","uppercut","lunge","twinblade")) for(int frame=0;frame<6;frame++) for(String pose:java.util.List.of("jab","hook","uppercut","lunge","twinblade")) for(int frame=0;frame<6;frame++)
assertTrue(Files.exists(assets.resolve("items/animation/"+pose+"_"+frame+".json"))); assertTrue(Files.exists(assets.resolve("items/animation/"+pose+"_"+frame+".json")));
for(String pose:java.util.List.of("guard","jab","hook","uppercut","lunge","twinblade")) {
var item=JsonParser.parseString(Files.readString(assets.resolve("items/v2/"+pose+".json"))).getAsJsonObject();
assertFalse(item.get("hand_animation_on_swap").getAsBoolean());
var display=JsonParser.parseString(Files.readString(assets.resolve("models/v2/"+pose+".json"))).getAsJsonObject().getAsJsonObject("display");
assertFalse(display.has("thirdperson_righthand"),"Pose must not detach model from vanilla arm");
assertFalse(display.has("thirdperson_lefthand"),"Pose must not detach model from vanilla arm");
}
assertFalse(Files.exists(root.resolve("astraplus/resources/assets/minecraft/items/iron_sword.json"))); assertFalse(Files.exists(root.resolve("astraplus/resources/assets/minecraft/items/iron_sword.json")));
} }
} }
@@ -31,22 +31,16 @@ final class CaptureFixture {
if(!ready || server.getPlayerList().getPlayers().isEmpty()) return; if(!ready || server.getPlayerList().getPlayers().isEmpty()) return;
ServerPlayer p=server.getPlayerList().getPlayers().getFirst(); ServerPlayer p=server.getPlayerList().getPlayers().getFirst();
if(stage<0 || Files.exists(Path.of("capture-ack-"+stage+".txt"))) { if(stage<0 || Files.exists(Path.of("capture-ack-"+stage+".txt"))) {
if(++stage>6) return; if(++stage>3) return;
age=0; age=0;
p.setGameMode(GameType.CREATIVE);p.setNoGravity(true);p.getInventory().clearContent(); p.setGameMode(GameType.CREATIVE);p.setNoGravity(true);p.getInventory().clearContent();
p.teleportTo(server.overworld(),100,65,100,java.util.Set.of(),0,15,true); p.teleportTo(server.overworld(),100,65,100,java.util.Set.of(),0,15,true);
p.setItemInHand(InteractionHand.MAIN_HAND,AstraPlus.content().entry(stage==6?TwinbladeCombat.ID:GauntletCombat.ID).stack(1)); p.setItemInHand(InteractionHand.MAIN_HAND,AstraPlus.content().entry(stage>=2?TwinbladeCombat.ID:GauntletCombat.ID).stack(1));
p.setItemInHand(InteractionHand.OFF_HAND,ItemStack.EMPTY); p.setItemInHand(InteractionHand.OFF_HAND,ItemStack.EMPTY);
Files.writeString(Path.of("capture-stage-"+stage+".txt"),"ready"); Files.writeString(Path.of("capture-stage-"+stage+".txt"),"ready");
} }
if(stage>6) return; if(stage>3) return;
++age; ++age;
if(age==20 && stage>0) {
String pose=stage==1||stage==2?"jab":stage==3?"hook":stage==4?"uppercut":stage==5?"lunge":"twinblade";
WeaponPresentation.animate(p,pose,stage==1||stage==3,80);
}
// Repeated flashes overlap one tick so screenshot cadence cannot land in a spawn/metadata gap.
if(stage==6 && age>=40 && age<80 && age%3==0) SlashDisplay.spawn(p,3,false);
} catch(Throwable error) { } catch(Throwable error) {
error.printStackTrace(); error.printStackTrace();
try { Files.writeString(Path.of("capture-failure.txt"),error.toString()); } catch(Exception ignored) {} try { Files.writeString(Path.of("capture-failure.txt"),error.toString()); } catch(Exception ignored) {}
@@ -44,6 +44,12 @@ final class GauntletVerification {
p.attack(front); p.attack(front);
check(Math.abs(front.getHealth()-(100-total))<.002,"combo step "+step+" exact damage: "+front.getHealth()); check(Math.abs(front.getHealth()-(100-total))<.002,"combo step "+step+" exact damage: "+front.getHealth());
check(side.getHealth()==100 && rear.getHealth()==100 && far.getHealth()==100,"small hit area excludes side/rear/far"); check(side.getHealth()==100 && rear.getHealth()==100 && far.getHealth()==100,"small hit area excludes side/rear/far");
var mainVisual=(ClientboundSetPlayerInventoryPacket)WeaponPresentation.project(p,new ClientboundSetPlayerInventoryPacket(p.getInventory().getSelectedSlot(),p.getMainHandItem()));
var offVisual=(ClientboundSetPlayerInventoryPacket)WeaponPresentation.project(p,new ClientboundSetPlayerInventoryPacket(40,ItemStack.EMPTY));
check(ItemStack.matches(WeaponPresentation.restorePresentation(mainVisual.contents()),p.getMainHandItem()),"creative movement restores real glove components");
var active=(Combo.left(step) ? offVisual : mainVisual).contents();
check(active.getSwingAnimation().type()==(step==4 ? SwingAnimationType.WHACK : SwingAnimationType.STAB),"accepted hand uses native interpolated swing "+step);
check(active.getSwingAnimation().duration()==4,"native swing finishes inside five-tick combo window");
float hp=front.getHealth();p.attack(front);GauntletCombat.strike(p); float hp=front.getHealth();p.attack(front);GauntletCombat.strike(p);
check(front.getHealth()==hp,"same tick click/swing cannot duplicate a hit"); check(front.getHealth()==hp,"same tick click/swing cannot duplicate a hit");
check(!WeaponPresentation.ghost(p.getMainHandItem()) && p.getOffhandItem().isEmpty(),"animated model only exists in packets"); check(!WeaponPresentation.ghost(p.getMainHandItem()) && p.getOffhandItem().isEmpty(),"animated model only exists in packets");
+1 -1
View File
@@ -28,7 +28,7 @@ def main():
band=max(0,1-abs(r-(.85+frame*.012))/.16) band=max(0,1-abs(r-(.85+frame*.012))/.16)
sweep=max(0,1-abs(angle-(-1.0+frame*.5))/2.25) sweep=max(0,1-abs(angle-(-1.0+frame*.5))/2.25)
# Use an opaque core: vanilla item cutout discards a translucent-only crescent. # Use an opaque core: vanilla item cutout discards a translucent-only crescent.
alpha=255 if band*sweep > .18+frame*.09 else 0 alpha=255 if band*sweep > .18+frame*.09 else 0
image.putpixel((x,y+frame*size),(255,184,79,alpha) if fiery else (222,208,255,alpha)) image.putpixel((x,y+frame*size),(255,184,79,alpha) if fiery else (222,208,255,alpha))
name='slash_fire' if fiery else 'slash' name='slash_fire' if fiery else 'slash'
(D/'textures/item').mkdir(parents=True,exist_ok=True) (D/'textures/item').mkdir(parents=True,exist_ok=True)
+64
View File
@@ -0,0 +1,64 @@
"""Stable hand models driven by vanilla swing animations, plus timed slash frames."""
from pathlib import Path
import json, math
from PIL import Image
ROOT = Path(__file__).resolve().parents[1] / 'src/main/resources'
D = ROOT / 'defaults/resources/assets/astraweapons'
def write(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, ensure_ascii=False, indent=2)+'\n', encoding='utf-8')
def model(name):
return {'type':'minecraft:model','model':name}
def hand_item(name, parent, gui, display):
write(D/f'models/v2/{name}.json', {'parent':parent, 'display':display})
write(D/f'items/v2/{name}.json', {'hand_animation_on_swap':False, 'model':{
'type':'minecraft:select','property':'minecraft:display_context',
'cases':[{'when':['gui','ground','fixed'],'model':model(gui)}],
'fallback':model(f'astraweapons:v2/{name}')}})
def main():
# No third-person pose offsets: the glove stays attached to the wrist while
# the vanilla STAB/WHACK animation moves the actual arm with frame interpolation.
base=json.loads((D/'models/item/iron_gauntlet_3d.json').read_text(encoding='utf-8'))
for pose, pitch, roll in [('guard',0,0),('jab',0,0),('hook',0,12),('uppercut',-12,0),('lunge',0,0)]:
display={}
for side,sign in [('righthand',1),('lefthand',-1)]:
src=base['display']['firstperson_'+side]
display['firstperson_'+side]={'rotation':[src['rotation'][0]+pitch,0,sign*(-8+roll)],
'translation':[sign*.5,5.0,0], 'scale':[.9,.9,.9]}
hand_item(pose,'astraweapons:item/iron_gauntlet_3d','astraweapons:item/iron_gauntlet_2d',display)
hand_item('twinblade','astraplus:item/netherite_twinblade','astraplus:internal/twinblade_gui',{
'firstperson_righthand':{'rotation':[0,-90,55],'translation':[1.1,1.4,0],'scale':[1.85,1.85,.68]},
'firstperson_lefthand':{'rotation':[0,90,-55],'translation':[1.1,1.4,0],'scale':[1.85,1.85,.68]}})
# Each transient display selects frames by its own age. No globally running
# animated texture, so every slash starts at the beginning of the same trail.
for fiery in (False, True):
for frame in range(4):
name=f'slash_{"fire_" if fiery else ""}{frame}'
size=192; im=Image.new('RGBA',(size,size))
lead=(-.9,-.15,.6,1.15)[frame]
for y in range(size):
for x in range(size):
dx=(x+.5-size/2)/(size/2);z=(y+.5-size/2)/(size/2)
r=math.hypot(dx,z);a=math.atan2(dx,z)
tail=lead-a
if z<=0 or not 0<tail<1.65:continue
width=.09*(1-tail/1.65)*(1-frame*.13)
outer=.87+frame*.02
if outer-width<r<outer:
core=(outer-r)<width*.4
rgb=((255,247,205) if core else (255,158,45)) if fiery else ((255,255,255) if core else (185,180,221))
im.putpixel((x,y),(*rgb,255))
path=D/f'textures/item/v2/{name}.png';path.parent.mkdir(parents=True,exist_ok=True);im.save(path)
write(D/f'models/v2/{name}.json',{'textures':{'slash':f'astraweapons:item/v2/{name}','particle':f'astraweapons:item/v2/{name}'},
'elements':[{'from':[0,8,0],'to':[16,8,16],'shade':False,'light_emission':15,'faces':{
'up':{'texture':'#slash','uv':[0,0,16,16]},'down':{'texture':'#slash','uv':[0,0,16,16],'rotation':180}}}]})
write(D/f'items/v2/{name}.json',{'model':model(f'astraweapons:v2/{name}')})
index=sorted(str(f.relative_to(ROOT/'defaults')).replace('\\','/') for f in (ROOT/'defaults').rglob('*') if f.is_file())
(ROOT/'weapons-index.txt').write_text('\n'.join(index)+'\n',encoding='utf-8')
if __name__=='__main__':main()
+1 -1
View File
@@ -11,7 +11,7 @@ $run = Join-Path $repo ('build/weapons-capture-' + (Get-Date -Format 'yyyyMMdd-H
$serverRun = Join-Path $run 'server' $serverRun = Join-Path $run 'server'
$clientRun = Join-Path $run 'client' $clientRun = Join-Path $run 'client'
New-Item -ItemType Directory -Path "$serverRun/mods", "$clientRun/resourcepacks" -Force | Out-Null New-Item -ItemType Directory -Path "$serverRun/mods", "$clientRun/resourcepacks" -Force | Out-Null
Copy-Item -LiteralPath $AstraPlusJar, "$repo/build/libs/AstraWeapons-0.1.0.jar", "$repo/build/libs/AstraWeapons-0.1.0-verification.jar" -Destination "$serverRun/mods" Copy-Item -LiteralPath $AstraPlusJar, "$repo/build/libs/AstraWeapons-0.1.1.jar", "$repo/build/libs/AstraWeapons-0.1.1-verification.jar" -Destination "$serverRun/mods"
New-Item -ItemType Directory -Path "$serverRun/astraplus" -Force | Out-Null New-Item -ItemType Directory -Path "$serverRun/astraplus" -Force | Out-Null
$serverRoot = (Resolve-Path -LiteralPath $ServerDirectory).Path.Replace('\','/') $serverRoot = (Resolve-Path -LiteralPath $ServerDirectory).Path.Replace('\','/')
$argsText = (@(foreach ($line in (Get-Content "$ServerDirectory/libraries/net/neoforged/neoforge/26.2.0.79/win_args.txt")) { $argsText = (@(foreach ($line in (Get-Content "$ServerDirectory/libraries/net/neoforged/neoforge/26.2.0.79/win_args.txt")) {
+14
View File
@@ -0,0 +1,14 @@
param(
[string]$CaptureDirectory = (Get-Content "$PSScriptRoot/../build/active-weapons-capture.txt"),
[string]$Ffmpeg = 'C:/Users/ScarPC/Documents/Plugins/PixelBanners/.codex-work/packs-smoke/plugins/ItemsAdder/storage/cache/ffmpeg/windows/ffmpeg.exe'
)
$ErrorActionPreference='Stop'
$repo=Split-Path $PSScriptRoot -Parent
$output=Join-Path $repo 'build/animation-review-0.1.1.mp4'
$ffargs=@('-hide_banner','-loglevel','error','-y')
foreach($stage in 0..3){$ffargs+=@('-framerate','20','-i',"$CaptureDirectory/client/screenshots/weapons-$stage-%03d.png")}
$filter='[0:v]scale=640:360[a];[1:v]scale=640:360[b];[2:v]scale=640:360[c];[3:v]scale=640:360[d];[a][b]hstack[top];[c][d]hstack[bottom];[top][bottom]vstack[v]'
$ffargs+=@('-filter_complex',$filter,'-map','[v]','-c:v','libx264','-crf','18','-pix_fmt','yuv420p','-movflags','+faststart',$output)
& $Ffmpeg @ffargs
if($LASTEXITCODE -ne 0){throw 'Review video encoding failed'}
Write-Output $output
+3 -3
View File
@@ -1,12 +1,12 @@
param([string]$ServerDirectory = 'C:/Users/ScarPC/Documents/NeoForge Server 26.2') param([string]$ServerDirectory = 'C:/Users/ScarPC/Documents/NeoForge Server 26.2', [switch]$IncludeAstraPlus)
$ErrorActionPreference='Stop' $ErrorActionPreference='Stop'
Add-Type -AssemblyName System.IO.Compression.FileSystem Add-Type -AssemblyName System.IO.Compression.FileSystem
$repo=Split-Path $PSScriptRoot -Parent $repo=Split-Path $PSScriptRoot -Parent
$mods=(Resolve-Path -LiteralPath (Join-Path $ServerDirectory 'mods')).Path $mods=(Resolve-Path -LiteralPath (Join-Path $ServerDirectory 'mods')).Path
$jobs=@( $jobs=@(
@{Id='astraplus';Jar=(Join-Path (Split-Path $repo -Parent) 'AstraPlus/build/libs/AstraPlus-0.5.67.jar')}, @{Id='astraweapons';Jar=(Join-Path $repo 'build/libs/AstraWeapons-0.1.1.jar')}
@{Id='astraweapons';Jar=(Join-Path $repo 'build/libs/AstraWeapons-0.1.0.jar')}
) )
if($IncludeAstraPlus){$jobs=@(@{Id='astraplus';Jar=(Join-Path (Split-Path $repo -Parent) 'AstraPlus/build/libs/AstraPlus-0.5.67.jar')})+$jobs}
function Get-ModIds([string]$Jar) { function Get-ModIds([string]$Jar) {
$zip=[IO.Compression.ZipFile]::OpenRead($Jar) $zip=[IO.Compression.ZipFile]::OpenRead($Jar)
try { try {
+1 -1
View File
@@ -8,7 +8,7 @@ $ErrorActionPreference = 'Stop'
$repo = Split-Path $PSScriptRoot -Parent $repo = Split-Path $PSScriptRoot -Parent
$run = Join-Path $repo ('build/verify-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + [guid]::NewGuid().ToString('N').Substring(0,6)) $run = Join-Path $repo ('build/verify-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + [guid]::NewGuid().ToString('N').Substring(0,6))
New-Item -ItemType Directory -Path "$run/mods", "$run/config" -Force | Out-Null New-Item -ItemType Directory -Path "$run/mods", "$run/config" -Force | Out-Null
Copy-Item -LiteralPath $AstraPlusJar,"$repo/build/libs/AstraWeapons-0.1.0.jar","$repo/build/libs/AstraWeapons-0.1.0-verification.jar" -Destination "$run/mods" Copy-Item -LiteralPath $AstraPlusJar,"$repo/build/libs/AstraWeapons-0.1.1.jar","$repo/build/libs/AstraWeapons-0.1.1-verification.jar" -Destination "$run/mods"
$serverRoot = (Resolve-Path -LiteralPath $ServerDirectory).Path.Replace('\','/') $serverRoot = (Resolve-Path -LiteralPath $ServerDirectory).Path.Replace('\','/')
$argsText = (@(foreach ($line in (Get-Content "$ServerDirectory/libraries/net/neoforged/neoforge/26.2.0.79/win_args.txt")) { $argsText = (@(foreach ($line in (Get-Content "$ServerDirectory/libraries/net/neoforged/neoforge/26.2.0.79/win_args.txt")) {
if ($line -eq '-DlibraryDirectory=libraries') { '"-DlibraryDirectory=' + $serverRoot + '/libraries"' } if ($line -eq '-DlibraryDirectory=libraries') { '"-DlibraryDirectory=' + $serverRoot + '/libraries"' }