Author SHA1 Message Date
Claude 6a8a7ead04 feat(client): keep the lead pipper through radar loss
Follows the ship matched to the selected radar contact (true position and
velocity) and extrapolates the last contact when no ship is loaded, so
notching or the radar speed gate no longer removes the pipper.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YVREx3uo7nz1FEhzveWTUh
2026-11-11 12:20:48 +01:00
Claude 9e7aae5773 feat(client): gun pipper with ground impact point and radar lead marker
Draws where the shells of the first light autocannon come down and, for the
selected radar target, a lead pipper. Uses the same ballistics as Warium's
LACFireScript (muzzle speed, barrels, drag 0.99, gravity 0.05).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YVREx3uo7nz1FEhzveWTUh
2026-11-11 12:02:47 +01:00
richard 1e659816b8 Merge pull request 'feat(flight): enhance flight model with transonic drag and vortex lift features' (#1) from transsonic_stuff into master
Reviewed-on: #1
2026-10-30 10:05:43 +00:00
richard 44a5f7f9bc feat(flight): enhance flight model with transonic drag and vortex lift features 2026-10-28 23:14:37 +01:00
20 changed files with 1049 additions and 26 deletions

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@ mapping_version=2023.09.03-1.20.1
mod_id=improved_aerodynamics mod_id=improved_aerodynamics
mod_name=VS: Improved Aerodynamics mod_name=VS: Improved Aerodynamics
mod_license=MIT mod_license=MIT
mod_version=0.2.0 mod_version=0.3.0
mod_group_id=dev.lumareth.improvedaerodynamics mod_group_id=dev.lumareth.improvedaerodynamics
mod_authors=Lumareth mod_authors=Lumareth
mod_description=Valkyrien Skies addon that keeps terrain streaming ahead of fast ships and smooths out Warium flight physics, with an optional flight model with real stalls and auto trim. mod_description=Valkyrien Skies addon that keeps terrain streaming ahead of fast ships and smooths out Warium flight physics, with an optional flight model with real stalls and auto trim.
@@ -92,6 +92,37 @@ public final class Config {
"with lift, so this only costs speed. Wings use Warium's 1.0, which also stands in for fuselage drag") "with lift, so this only costs speed. Wings use Warium's 1.0, which also stands in for fuselage drag")
.defineInRange("stabilizerDrag", 0.2D, 0.0D, 2.0D); .defineInRange("stabilizerDrag", 0.2D, 0.0D, 2.0D);
public static final ForgeConfigSpec.BooleanValue TRANSONIC_DRAG = BUILDER
.comment("Improved flight model: zero-lift drag rises steeply around the speed of sound, so craft can no longer",
"cruise supersonic without a lot of thrust or a clean shape. Induced and stall drag are not affected")
.define("transonicDrag", true);
public static final ForgeConfigSpec.DoubleValue SPEED_OF_SOUND = BUILDER
.comment("Improved flight model: speed of sound in blocks per second, Mach 1 for the transonic drag")
.defineInRange("speedOfSound", 100.0D, 10.0D, 1000.0D);
public static final ForgeConfigSpec.DoubleValue TRANSONIC_PEAK_DRAG = BUILDER
.comment("Improved flight model: multiplier for zero-lift drag at its peak, at Mach 1.05")
.defineInRange("transonicPeakDrag", 4.0D, 1.0D, 20.0D);
public static final ForgeConfigSpec.DoubleValue SUPERSONIC_DRAG = BUILDER
.comment("Improved flight model: multiplier for zero-lift drag once fully supersonic, from Mach 1.3")
.defineInRange("supersonicDrag", 2.0D, 1.0D, 20.0D);
public static final ForgeConfigSpec.BooleanValue VORTEX_LIFT = BUILDER
.comment("Improved flight model: wings with a low aspect ratio (delta wings) stall later and get extra lift at",
"high angles of attack from leading-edge vortices. Wings with an aspect ratio of 3 or more are not affected")
.define("vortexLift", true);
public static final ForgeConfigSpec.DoubleValue VORTEX_STALL_BONUS = BUILDER
.comment("Improved flight model: extra stall angle of the lowest aspect ratio wings (1 or less) as a fraction of",
"the normal stall angle, 1.0 doubles it, for example from 16 to 32 degrees")
.defineInRange("vortexStallBonus", 1.0D, 0.0D, 3.0D);
public static final ForgeConfigSpec.DoubleValue VORTEX_LIFT_STRENGTH = BUILDER
.comment("Improved flight model: multiplier for the extra lift the vortices make at high angles of attack")
.defineInRange("vortexLiftStrength", 1.0D, 0.0D, 3.0D);
public static final ForgeConfigSpec.DoubleValue TRIM_AUTHORITY = BUILDER public static final ForgeConfigSpec.DoubleValue TRIM_AUTHORITY = BUILDER
.comment("Auto trim: largest pitch input (fraction of full deflection) the trim may hold") .comment("Auto trim: largest pitch input (fraction of full deflection) the trim may hold")
.defineInRange("trimAuthority", 0.5D, 0.0D, 1.0D); .defineInRange("trimAuthority", 0.5D, 0.0D, 1.0D);
@@ -8,6 +8,7 @@ import com.mojang.brigadier.tree.LiteralCommandNode;
import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands; import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.common.ForgeConfigSpec; import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.event.RegisterCommandsEvent; import net.minecraftforge.event.RegisterCommandsEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.eventbus.api.SubscribeEvent;
@@ -17,6 +18,7 @@ import java.util.List;
/** /**
* /improvedaerodynamics (or /aero) to read and change the most important server config values in game. * /improvedaerodynamics (or /aero) to read and change the most important server config values in game.
* {@code /aero} lists them, {@code /aero <option>} shows one, {@code /aero <option> <value>} sets and saves it. * {@code /aero} lists them, {@code /aero <option>} shows one, {@code /aero <option> <value>} sets and saves it.
* Needs operator rights, except for the owner of a singleplayer world, who may use them without cheats.
* All of them are read live, so changes apply immediately. * All of them are read live, so changes apply immediately.
*/ */
public final class ConfigCommands { public final class ConfigCommands {
@@ -32,6 +34,13 @@ public final class ConfigCommands {
new Option<>("lift_scale", Config.LIFT_SCALE, DoubleArgumentType.doubleArg(), Double.class), new Option<>("lift_scale", Config.LIFT_SCALE, DoubleArgumentType.doubleArg(), Double.class),
new Option<>("stall_angle_scale", Config.STALL_ANGLE_SCALE, DoubleArgumentType.doubleArg(), Double.class), new Option<>("stall_angle_scale", Config.STALL_ANGLE_SCALE, DoubleArgumentType.doubleArg(), Double.class),
new Option<>("stabilizer_drag", Config.STABILIZER_DRAG, DoubleArgumentType.doubleArg(), Double.class), new Option<>("stabilizer_drag", Config.STABILIZER_DRAG, DoubleArgumentType.doubleArg(), Double.class),
new Option<>("transonic_drag", Config.TRANSONIC_DRAG, BoolArgumentType.bool(), Boolean.class),
new Option<>("speed_of_sound", Config.SPEED_OF_SOUND, DoubleArgumentType.doubleArg(), Double.class),
new Option<>("transonic_peak_drag", Config.TRANSONIC_PEAK_DRAG, DoubleArgumentType.doubleArg(), Double.class),
new Option<>("supersonic_drag", Config.SUPERSONIC_DRAG, DoubleArgumentType.doubleArg(), Double.class),
new Option<>("vortex_lift", Config.VORTEX_LIFT, BoolArgumentType.bool(), Boolean.class),
new Option<>("vortex_stall_bonus", Config.VORTEX_STALL_BONUS, DoubleArgumentType.doubleArg(), Double.class),
new Option<>("vortex_lift_strength", Config.VORTEX_LIFT_STRENGTH, DoubleArgumentType.doubleArg(), Double.class),
new Option<>("trim_authority", Config.TRIM_AUTHORITY, DoubleArgumentType.doubleArg(), Double.class), new Option<>("trim_authority", Config.TRIM_AUTHORITY, DoubleArgumentType.doubleArg(), Double.class),
new Option<>("trim_min_speed", Config.TRIM_MIN_SPEED, DoubleArgumentType.doubleArg(), Double.class), new Option<>("trim_min_speed", Config.TRIM_MIN_SPEED, DoubleArgumentType.doubleArg(), Double.class),
new Option<>("air_placeholder", Config.ENABLE_AIR_PLACEHOLDER, BoolArgumentType.bool(), Boolean.class), new Option<>("air_placeholder", Config.ENABLE_AIR_PLACEHOLDER, BoolArgumentType.bool(), Boolean.class),
@@ -40,17 +49,26 @@ public final class ConfigCommands {
private ConfigCommands() { private ConfigCommands() {
} }
/** Operators, and the owner of a singleplayer world even when cheats are off. */
private static boolean mayUse(CommandSourceStack source) {
if (source.hasPermission(2)) {
return true;
}
return source.getEntity() instanceof ServerPlayer player
&& source.getServer().isSingleplayerOwner(player.getGameProfile());
}
@SubscribeEvent @SubscribeEvent
public static void onRegisterCommands(RegisterCommandsEvent event) { public static void onRegisterCommands(RegisterCommandsEvent event) {
LiteralArgumentBuilder<CommandSourceStack> root = Commands.literal("improvedaerodynamics") LiteralArgumentBuilder<CommandSourceStack> root = Commands.literal("improvedaerodynamics")
.requires(source -> source.hasPermission(2)) .requires(ConfigCommands::mayUse)
.executes(context -> list(context.getSource())); .executes(context -> list(context.getSource()));
for (Option<?> option : OPTIONS) { for (Option<?> option : OPTIONS) {
root.then(optionNode(option)); root.then(optionNode(option));
} }
LiteralCommandNode<CommandSourceStack> node = event.getDispatcher().register(root); LiteralCommandNode<CommandSourceStack> node = event.getDispatcher().register(root);
event.getDispatcher().register(Commands.literal("aero") event.getDispatcher().register(Commands.literal("aero")
.requires(source -> source.hasPermission(2)) .requires(ConfigCommands::mayUse)
.executes(context -> list(context.getSource())) .executes(context -> list(context.getSource()))
.redirect(node)); .redirect(node));
} }
@@ -1,6 +1,7 @@
package dev.lumareth.improvedAerodynamics; package dev.lumareth.improvedAerodynamics;
import com.mojang.logging.LogUtils; import com.mojang.logging.LogUtils;
import dev.lumareth.improvedAerodynamics.client.pipper.PipperConfig;
import dev.lumareth.improvedAerodynamics.flight.PhysicsBridge; import dev.lumareth.improvedAerodynamics.flight.PhysicsBridge;
import dev.lumareth.improvedAerodynamics.network.Network; import dev.lumareth.improvedAerodynamics.network.Network;
import dev.lumareth.improvedAerodynamics.terrain.LookaheadLoader; import dev.lumareth.improvedAerodynamics.terrain.LookaheadLoader;
@@ -21,6 +22,7 @@ public class ImprovedAerodynamics {
MinecraftForge.EVENT_BUS.register(PhysicsBridge.class); MinecraftForge.EVENT_BUS.register(PhysicsBridge.class);
MinecraftForge.EVENT_BUS.register(ConfigCommands.class); MinecraftForge.EVENT_BUS.register(ConfigCommands.class);
ModLoadingContext.get().registerConfig(ModConfig.Type.SERVER, Config.SPEC); ModLoadingContext.get().registerConfig(ModConfig.Type.SERVER, Config.SPEC);
ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, PipperConfig.SPEC);
Network.register(); Network.register();
} }
} }
@@ -0,0 +1,147 @@
package dev.lumareth.improvedAerodynamics.client.pipper;
/**
* Flight of a Warium shell, which is a vanilla arrow: every tick it moves by its velocity, the velocity is then scaled
* by the drag and gravity is subtracted. That is linear in the launch velocity, so the position after n ticks is
* <pre>M + D(n) * v0 - (0, G(n), 0)</pre>
* with D(n) the sum of the drag factors and G(n) the drop gravity causes on its own. Both are tabulated once, which
* makes both the impact point and the lead solution cheap enough to run every frame.
* <p>
* Plain doubles and no Minecraft classes, so it can be tested on its own. Units are blocks and ticks.
*/
public final class Ballistics {
public static final int MAX_TICKS = 400;
private final double[] d = new double[MAX_TICKS + 1];
private final double[] g = new double[MAX_TICKS + 1];
public Ballistics(double drag, double gravity) {
double y = 0.0;
double vy = 0.0;
double sum = 0.0;
double factor = 1.0;
for (int n = 1; n <= MAX_TICKS; n++) {
y += vy;
vy = vy * drag - gravity;
sum += factor;
factor *= drag;
d[n] = sum;
g[n] = -y;
}
}
/** Sum of the drag factors after n ticks, n may be fractional. */
public double d(double n) {
return interpolate(d, n);
}
/** Drop in blocks after n ticks, n may be fractional. */
public double g(double n) {
return interpolate(g, n);
}
private static double interpolate(double[] table, double n) {
if (n <= 0.0) {
return 0.0;
}
if (n >= MAX_TICKS) {
return table[MAX_TICKS];
}
int i = (int) n;
double f = n - i;
return table[i] + (table[i + 1] - table[i]) * f;
}
/** Height of the terrain a shell would hit at a column. */
public interface Ground {
double heightAt(double x, double z);
}
/**
* Where a shell fired from the muzzle with the given world velocity (blocks per tick, already including the
* speed of the shooter if shells inherit it) comes down. Returns the impact point as {x, y, z} or null if it
* stays in the air for the whole table.
*/
public double[] impact(double mx, double my, double mz, double vx, double vy, double vz, Ground ground) {
double px = mx;
double py = my;
double pz = mz;
for (int n = 1; n <= MAX_TICKS; n++) {
double nx = mx + d[n] * vx;
double ny = my + d[n] * vy - g[n];
double nz = mz + d[n] * vz;
double floor = ground.heightAt(nx, nz);
if (ny <= floor) {
// Linear crossing inside this step
double before = py - ground.heightAt(px, pz);
double after = ny - floor;
double f = before - after > 1.0E-9 ? Math.min(1.0, Math.max(0.0, before / (before - after))) : 1.0;
return new double[] {px + (nx - px) * f, py + (ny - py) * f, pz + (nz - pz) * f};
}
px = nx;
py = ny;
pz = nz;
}
return null;
}
/** Result of {@link #lead}: aim direction, time of flight in ticks and the range to the target's current position. */
public record Lead(double dirX, double dirY, double dirZ, double ticks, double range) {
}
/**
* Aim direction that makes a shell meet a moving target.
*
* @param speed muzzle speed in blocks per tick
* @param t* target position now
* @param tv* target velocity in blocks per tick
* @param sv* velocity the shell inherits from the shooter in blocks per tick, zero if it does not
* @return the solution or null if the shell cannot reach the target within the table
*/
public Lead lead(double mx, double my, double mz, double speed, double tx, double ty, double tz,
double tvx, double tvy, double tvz, double svx, double svy, double svz) {
double range = Math.sqrt(sq(tx - mx) + sq(ty - my) + sq(tz - mz));
double previousN = 0.0;
for (int n = 1; n <= MAX_TICKS; n++) {
double f = miss(n, mx, my, mz, speed, tx, ty, tz, tvx, tvy, tvz, svx, svy, svz);
if (f <= 0.0) {
double lo = previousN;
double hi = n;
for (int i = 0; i < 30; i++) {
double mid = 0.5 * (lo + hi);
if (miss(mid, mx, my, mz, speed, tx, ty, tz, tvx, tvy, tvz, svx, svy, svz) > 0.0) {
lo = mid;
} else {
hi = mid;
}
}
double t = 0.5 * (lo + hi);
double dn = d(t);
double rx = tx + tvx * t - mx - dn * svx;
double ry = ty + tvy * t - my - dn * svy + g(t);
double rz = tz + tvz * t - mz - dn * svz;
double length = Math.sqrt(rx * rx + ry * ry + rz * rz);
if (length < 1.0E-6) {
return null;
}
return new Lead(rx / length, ry / length, rz / length, t, range);
}
previousN = n;
}
return null;
}
/** Distance the shell can still cover short of where the target will be, positive means it has not got there yet. */
private double miss(double n, double mx, double my, double mz, double speed, double tx, double ty, double tz,
double tvx, double tvy, double tvz, double svx, double svy, double svz) {
double dn = d(n);
double rx = tx + tvx * n - mx - dn * svx;
double ry = ty + tvy * n - my - dn * svy + g(n);
double rz = tz + tvz * n - mz - dn * svz;
return Math.sqrt(rx * rx + ry * ry + rz * rz) - speed * dn;
}
private static double sq(double v) {
return v * v;
}
}
@@ -0,0 +1,155 @@
package dev.lumareth.improvedAerodynamics.client.pipper;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.DirectionProperty;
import net.minecraft.world.level.block.state.properties.Property;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ChunkStatus;
import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.registries.ForgeRegistries;
import org.joml.primitives.AABBic;
import java.util.ArrayList;
import java.util.List;
/**
* Finds the light autocannon of a ship and works out what it will shoot, the same way Warium's LACFireScript does:
* barrel count, muzzle, aim direction and muzzle speed.
*/
final class GunFinder {
private static final ResourceLocation LIGHT_AUTOCANNON = new ResourceLocation("crusty_chunks", "light_autocannon");
private static final TagKey<Block> BARREL = TagKey.create(Registries.BLOCK, new ResourceLocation("crusty_chunks", "acbarrel"));
private static final TagKey<Block> PASSTHROUGH = TagKey.create(Registries.BLOCK, new ResourceLocation("crusty_chunks", "barrelpassthrough"));
private static final int RESCAN_TICKS = 100;
private static final int MAX_GUNS = 16;
/** Muzzle and direction in ship space and the speed of the shell in blocks per tick. */
record Shot(double mx, double my, double mz, double dx, double dy, double dz, double speed) {
}
private long shipId = Long.MIN_VALUE;
private long lastScan = Long.MIN_VALUE;
private final List<BlockPos> guns = new ArrayList<>();
/** The gun closest to the seat, or null if the ship has none loaded. */
Shot find(ClientLevel level, long shipId, AABBic aabb, BlockPos seat) {
if (shipId != this.shipId || level.getGameTime() - lastScan >= RESCAN_TICKS || level.getGameTime() < lastScan) {
this.shipId = shipId;
lastScan = level.getGameTime();
scan(level, aabb);
}
BlockPos best = null;
double bestDistance = Double.MAX_VALUE;
for (BlockPos pos : guns) {
double distance = pos.distSqr(seat);
if (distance < bestDistance) {
bestDistance = distance;
best = pos;
}
}
return best == null ? null : shotOf(level, best);
}
private void scan(ClientLevel level, AABBic aabb) {
guns.clear();
Block gun = ForgeRegistries.BLOCKS.getValue(LIGHT_AUTOCANNON);
if (gun == null || aabb == null) {
return;
}
BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
for (int cx = aabb.minX() >> 4; cx <= aabb.maxX() >> 4; cx++) {
for (int cz = aabb.minZ() >> 4; cz <= aabb.maxZ() >> 4; cz++) {
ChunkAccess chunk = level.getChunk(cx, cz, ChunkStatus.FULL, false);
if (chunk == null) {
continue;
}
LevelChunkSection[] sections = chunk.getSections();
for (int i = 0; i < sections.length; i++) {
LevelChunkSection section = sections[i];
if (section.hasOnlyAir() || !section.maybeHas(state -> state.is(gun))) {
continue;
}
int baseY = level.getSectionYFromSectionIndex(i) << 4;
for (int x = 0; x < 16; x++) {
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
if (section.getBlockState(x, y, z).is(gun) && guns.size() < MAX_GUNS) {
guns.add(pos.set((cx << 4) + x, baseY + y, (cz << 4) + z).immutable());
}
}
}
}
}
}
}
}
private static Shot shotOf(ClientLevel level, BlockPos gun) {
BlockState state = level.getBlockState(gun);
Property<?> property = state.getBlock().getStateDefinition().getProperty("facing");
if (!(property instanceof DirectionProperty facingProperty)) {
return null;
}
Direction facing = state.getValue(facingProperty);
int fx = facing.getStepX();
int fy = facing.getStepY();
int fz = facing.getStepZ();
// Barrels, counted like Warium does: up to five more behind the first one
double barrels = 1.0;
for (int i = 0; i < 5 && level.getBlockState(gun.offset(fx * (int) (1 + barrels), fy * (int) (1 + barrels), fz * (int) (1 + barrels))).is(BARREL); i++) {
barrels++;
}
// Muzzle: past the barrels, skipping through blocks the shell passes
double position = barrels;
for (int i = 0; i < 10; i++) {
BlockState at = level.getBlockState(gun.offset(fx * (int) (1 + position), fy * (int) (1 + position), fz * (int) (1 + position)));
if ((!at.isAir() && !at.canOcclude()) || at.is(PASSTHROUGH)) {
position++;
} else {
break;
}
}
double mx = gun.getX() + fx * (1.5 + position) + 0.5;
double my = gun.getY() + fy * (1.5 + position) + 0.5;
double mz = gun.getZ() + fz * (1.5 + position) + 0.5;
// Aim, from the tags of the gun itself
double aimX = 0.0;
double aimY = 0.0;
double aimZ = 0.0;
BlockEntity entity = level.getBlockEntity(gun);
double gx = entity == null ? 0.0 : entity.getPersistentData().getDouble("X");
double gz = entity == null ? 0.0 : entity.getPersistentData().getDouble("Z");
double gpitch = entity == null ? 0.0 : entity.getPersistentData().getDouble("Pitch");
if (1.0 > Math.abs(fx - gx) || 1.0 > Math.abs(fz - gz)) {
aimY = gpitch;
aimX = gx + fx;
aimZ = gz + fz;
}
if (aimX * aimZ == 0.0) {
aimX = fx;
aimZ = fz;
}
double length = Math.sqrt(aimX * aimX + aimY * aimY + aimZ * aimZ);
if (length < 1.0E-6) {
return null;
}
double speed = PipperConfig.MUZZLE_SPEED_OVERRIDE.get();
if (speed <= 0.0) {
double multiplier = ModList.get().isLoaded("ritchiesprojectilelib") ? 2.0 : 1.0;
speed = (5.0 + barrels / 1.5) * multiplier;
}
return new Shot(mx, my, mz, aimX / length, aimY / length, aimZ / length, speed);
}
}
@@ -0,0 +1,251 @@
package dev.lumareth.improvedAerodynamics.client.pipper;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.BufferUploader;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.Tesselator;
import com.mojang.blaze3d.vertex.VertexFormat;
import dev.lumareth.improvedAerodynamics.ImprovedAerodynamics;
import net.minecraft.client.Camera;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.core.BlockPos;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.RenderLevelStageEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.common.Mod;
import org.joml.Matrix4f;
import org.joml.Vector3d;
import org.joml.Vector3f;
import org.valkyrienskies.core.api.ships.ClientShip;
import org.valkyrienskies.core.api.ships.Ship;
import org.valkyrienskies.mod.common.VSGameUtilsKt;
/**
* Draws two markers for the first light autocannon of the aircraft you sit in:
* an orange ring where its shells come down on the ground, and, for the radar target selected on the seat, a green
* ring you put on the target to hit it (the lead pipper): green from the radar, cyan while following the ship itself,
* yellow while only extrapolating a lost contact. Both come from the same ballistics Warium's shells follow.
*/
@Mod.EventBusSubscriber(modid = ImprovedAerodynamics.MOD_ID, value = Dist.CLIENT)
public final class GunPipperRenderer {
private static final int IMPACT_COLOR = 0xFFFF9020;
private static final int LEAD_COLOR = 0xFF40FF60;
private static final int VISUAL_COLOR = 0xFF40E8FF;
private static final int COAST_COLOR = 0xFFFFE040;
private static final float DISTANCE = 2.0F;
private static final GunFinder FINDER = new GunFinder();
private static final TargetTrack TRACK = new TargetTrack();
private static Ballistics ballistics;
private static double ballisticsDrag = Double.NaN;
private static double ballisticsGravity = Double.NaN;
private GunPipperRenderer() {
}
@SubscribeEvent
public static void onRenderLevel(RenderLevelStageEvent event) {
if (event.getStage() != RenderLevelStageEvent.Stage.AFTER_PARTICLES || !PipperConfig.SPEC.isLoaded()
|| !PipperConfig.ENABLED.get() || !ModList.get().isLoaded("valkyrien_warium")) {
return;
}
Minecraft minecraft = Minecraft.getInstance();
ClientLevel level = minecraft.level;
if (level == null || minecraft.player == null) {
return;
}
Entity seat = WariumSeat.seatOf(minecraft.player);
if (seat == null) {
TRACK.reset();
return;
}
BlockPos seatPos = BlockPos.containing(seat.getX(), seat.getY(), seat.getZ());
Ship ship = VSGameUtilsKt.getLoadedShipManagingPos(level, seatPos);
if (ship == null) {
return;
}
GunFinder.Shot shot = FINDER.find(level, ship.getId(), ship.getShipAABB(), seatPos);
if (shot == null) {
return;
}
org.joml.Matrix4dc shipToWorld = ship instanceof ClientShip clientShip
? clientShip.getRenderTransform().getShipToWorld() : ship.getShipToWorld();
Vector3d muzzle = shipToWorld.transformPosition(new Vector3d(shot.mx(), shot.my(), shot.mz()));
Vector3d direction = shipToWorld.transformDirection(new Vector3d(shot.dx(), shot.dy(), shot.dz())).normalize();
double inherit = PipperConfig.INHERIT_SHIP_VELOCITY.get() ? 1.0 / 20.0 : 0.0;
org.joml.Vector3dc velocity = ship.getVelocity();
double svx = velocity.x() * inherit;
double svy = velocity.y() * inherit;
double svz = velocity.z() * inherit;
Ballistics table = table();
Camera camera = event.getCamera();
Matrix4f matrix = event.getPoseStack().last().pose();
BufferBuilder builder = Tesselator.getInstance().getBuilder();
RenderSystem.disableDepthTest();
RenderSystem.enableBlend();
RenderSystem.defaultBlendFunc();
RenderSystem.disableCull();
RenderSystem.setShader(GameRenderer::getPositionColorShader);
builder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);
boolean drawn = false;
if (PipperConfig.SHOW_IMPACT.get()) {
double[] impact = table.impact(muzzle.x, muzzle.y, muzzle.z,
direction.x * shot.speed() + svx, direction.y * shot.speed() + svy, direction.z * shot.speed() + svz,
(x, z) -> level.getHeight(Heightmap.Types.MOTION_BLOCKING, Mth.floor(x), Mth.floor(z)));
if (impact != null) {
drawn |= marker(builder, matrix, camera, impact[0], impact[1], impact[2], IMPACT_COLOR, false);
}
}
if (PipperConfig.SHOW_LEAD.get()) {
drawn |= lead(builder, matrix, camera, level, seat, seatPos, ship.getId(), table, muzzle, shot.speed(), svx, svy, svz);
} else {
TRACK.reset();
}
if (drawn) {
BufferUploader.drawWithShader(builder.end());
} else {
builder.end().release();
}
RenderSystem.enableCull();
RenderSystem.enableDepthTest();
RenderSystem.disableBlend();
}
private static boolean lead(BufferBuilder builder, Matrix4f matrix, Camera camera, ClientLevel level, Entity seat, BlockPos seatPos,
long ownShipId, Ballistics table, Vector3d muzzle, double speed, double svx, double svy, double svz) {
int selected = WariumSeat.selectedTarget(seat);
double[] radar = selected > 0 ? radarPosition(level, seatPos, selected) : null;
TargetTrack.Fix fix = TRACK.resolve(level, ownShipId, selected, radar, level.getGameTime(),
PipperConfig.VISUAL_TRACK.get(), PipperConfig.COAST_SECONDS.get());
if (fix == null) {
return false;
}
Ballistics.Lead lead = table.lead(muzzle.x, muzzle.y, muzzle.z, speed, fix.x(), fix.y(), fix.z(),
fix.vx(), fix.vy(), fix.vz(), svx, svy, svz);
if (lead == null) {
return false;
}
int color = switch (fix.source()) {
case RADAR -> LEAD_COLOR;
case VISUAL -> VISUAL_COLOR;
case COAST -> COAST_COLOR;
};
return marker(builder, matrix, camera,
muzzle.x + lead.dirX() * lead.range(), muzzle.y + lead.dirY() * lead.range(), muzzle.z + lead.dirZ() * lead.range(),
color, true);
}
/** Position the node reports for a target index, or null if it reports none. */
private static double[] radarPosition(ClientLevel level, BlockPos seatPos, int selected) {
BlockEntity seatEntity = level.getBlockEntity(seatPos);
if (seatEntity == null) {
return null;
}
var seatData = seatEntity.getPersistentData();
BlockEntity node = level.getBlockEntity(BlockPos.containing(seatData.getDouble("ControlX"), seatData.getDouble("ControlY"), seatData.getDouble("ControlZ")));
if (node == null) {
return null;
}
var data = node.getPersistentData();
// Warium builds these keys from a double, so they read TargetX1.0, TargetY1.0 and so on
double tx = data.getDouble("TargetX" + (double) selected);
double ty = data.getDouble("TargetY" + (double) selected);
double tz = data.getDouble("TargetZ" + (double) selected);
if (tx == 0.0 && ty == 0.0 && tz == 0.0) {
return null;
}
return new double[] {tx, ty, tz};
}
private static Ballistics table() {
double drag = PipperConfig.DRAG.get();
double gravity = PipperConfig.GRAVITY.get();
if (ballistics == null || drag != ballisticsDrag || gravity != ballisticsGravity) {
ballistics = new Ballistics(drag, gravity);
ballisticsDrag = drag;
ballisticsGravity = gravity;
}
return ballistics;
}
/** A ring on the screen in the direction of a world point, with ticks on it for the lead pipper. */
private static boolean marker(BufferBuilder builder, Matrix4f matrix, Camera camera, double x, double y, double z, int color, boolean ticks) {
Vec3 cameraPosition = camera.getPosition();
Vector3f toPoint = new Vector3f((float) (x - cameraPosition.x), (float) (y - cameraPosition.y), (float) (z - cameraPosition.z));
if (toPoint.lengthSquared() < 1.0E-6F) {
return false;
}
toPoint.normalize();
if (toPoint.dot(camera.getLookVector()) <= 0.05F) {
return false;
}
Vector3f center = new Vector3f(toPoint).mul(DISTANCE);
Vector3f left = new Vector3f(camera.getLeftVector());
Vector3f up = new Vector3f(camera.getUpVector());
float radius = (float) (PipperConfig.MARKER_SIZE.get() * DISTANCE);
float thickness = radius * 0.12F;
ring(builder, matrix, center, left, up, radius, thickness, color);
quad(builder, matrix, center, left, up, thickness * 1.6F, thickness * 1.6F, color);
if (ticks) {
for (int i = 0; i < 4; i++) {
double angle = i * Math.PI / 2.0;
float cx = (float) Math.cos(angle);
float cy = (float) Math.sin(angle);
Vector3f tickCenter = new Vector3f(center)
.fma(cx * radius * 1.45F, left).fma(cy * radius * 1.45F, up);
float halfX = Math.abs(cx) > 0.5F ? radius * 0.35F : thickness;
float halfY = Math.abs(cy) > 0.5F ? radius * 0.35F : thickness;
quad(builder, matrix, tickCenter, left, up, halfX, halfY, color);
}
}
return true;
}
private static void ring(BufferBuilder builder, Matrix4f matrix, Vector3f center, Vector3f left, Vector3f up, float radius, float thickness, int color) {
final int segments = 32;
float inner = radius - thickness;
float outer = radius + thickness;
for (int i = 0; i < segments; i++) {
double a0 = i * 2.0 * Math.PI / segments;
double a1 = (i + 1) * 2.0 * Math.PI / segments;
vertex(builder, matrix, center, left, up, (float) Math.cos(a0) * inner, (float) Math.sin(a0) * inner, color);
vertex(builder, matrix, center, left, up, (float) Math.cos(a0) * outer, (float) Math.sin(a0) * outer, color);
vertex(builder, matrix, center, left, up, (float) Math.cos(a1) * outer, (float) Math.sin(a1) * outer, color);
vertex(builder, matrix, center, left, up, (float) Math.cos(a1) * inner, (float) Math.sin(a1) * inner, color);
}
}
private static void quad(BufferBuilder builder, Matrix4f matrix, Vector3f center, Vector3f left, Vector3f up, float halfX, float halfY, int color) {
vertex(builder, matrix, center, left, up, -halfX, -halfY, color);
vertex(builder, matrix, center, left, up, halfX, -halfY, color);
vertex(builder, matrix, center, left, up, halfX, halfY, color);
vertex(builder, matrix, center, left, up, -halfX, halfY, color);
}
private static void vertex(BufferBuilder builder, Matrix4f matrix, Vector3f center, Vector3f left, Vector3f up, float a, float b, int color) {
// The left vector points to the left of the screen, so a positive offset along it is drawn to the left
float vx = center.x - left.x * a + up.x * b;
float vy = center.y - left.y * a + up.y * b;
float vz = center.z - left.z * a + up.z * b;
builder.vertex(matrix, vx, vy, vz)
.color(color >> 16 & 255, color >> 8 & 255, color & 255, color >>> 24)
.endVertex();
}
}
@@ -0,0 +1,53 @@
package dev.lumareth.improvedAerodynamics.client.pipper;
import net.minecraftforge.common.ForgeConfigSpec;
/** Client side settings of the gun pipper. Lives in improved_aerodynamics-client.toml. */
public final class PipperConfig {
public static final ForgeConfigSpec SPEC;
public static final ForgeConfigSpec.BooleanValue ENABLED;
public static final ForgeConfigSpec.BooleanValue SHOW_IMPACT;
public static final ForgeConfigSpec.BooleanValue SHOW_LEAD;
public static final ForgeConfigSpec.BooleanValue INHERIT_SHIP_VELOCITY;
public static final ForgeConfigSpec.BooleanValue VISUAL_TRACK;
public static final ForgeConfigSpec.DoubleValue COAST_SECONDS;
public static final ForgeConfigSpec.DoubleValue MUZZLE_SPEED_OVERRIDE;
public static final ForgeConfigSpec.DoubleValue GRAVITY;
public static final ForgeConfigSpec.DoubleValue DRAG;
public static final ForgeConfigSpec.DoubleValue MARKER_SIZE;
static {
ForgeConfigSpec.Builder builder = new ForgeConfigSpec.Builder();
builder.comment("Gun pipper for Warium light autocannons, drawn while seated in a Warium seat").push("pipper");
ENABLED = builder.comment("Master switch")
.define("enabled", true);
SHOW_IMPACT = builder.comment("Show where the shells of the gun come down on the ground (orange ring)")
.define("showImpact", true);
SHOW_LEAD = builder.comment("Show the lead pipper for the radar target you selected (green ring)")
.define("showLead", true);
VISUAL_TRACK = builder.comment("Follow the selected target's ship itself once the radar has shown it, so the lead pipper keeps working when",
"the radar loses it (notching, speed gate, ground clutter). Only while the ship is loaded, which is within render distance",
"(cyan ring)")
.define("visualTrack", true);
COAST_SECONDS = builder.comment("Seconds a lost radar contact is extrapolated from its last position and velocity when its ship is not loaded",
"(yellow ring), 0 turns it off")
.defineInRange("coastSeconds", 8.0, 0.0, 60.0);
INHERIT_SHIP_VELOCITY = builder.comment("Add the speed of your aircraft to the shells. Warium does not do this itself, only turn it",
"on if a test shows your shells keep the speed of the jet (fire level at full speed, then hovering)")
.define("inheritShipVelocity", false);
MUZZLE_SPEED_OVERRIDE = builder.comment("Muzzle speed in blocks per tick, 0 works it out from the barrel length like Warium does")
.defineInRange("muzzleSpeedOverride", 0.0, 0.0, 100.0);
GRAVITY = builder.comment("Gravity of the shells in blocks per tick squared")
.defineInRange("gravity", 0.05, 0.0, 1.0);
DRAG = builder.comment("Speed the shells keep each tick, 0.99 is a vanilla arrow")
.defineInRange("drag", 0.99, 0.5, 1.0);
MARKER_SIZE = builder.comment("Radius of the markers on screen")
.defineInRange("markerSize", 0.03, 0.005, 0.2);
builder.pop();
SPEC = builder.build();
}
private PipperConfig() {
}
}
@@ -0,0 +1,131 @@
package dev.lumareth.improvedAerodynamics.client.pipper;
import net.minecraft.client.multiplayer.ClientLevel;
import org.joml.Vector3d;
import org.joml.primitives.AABBdc;
import org.valkyrienskies.core.api.ships.ClientShip;
import org.valkyrienskies.mod.common.VSGameUtilsKt;
/**
* The target the lead pipper aims at. The radar is only the way in: its contact is matched to the closest loaded ship
* and from then on that ship is followed directly, with its true position and velocity, so the pipper survives the
* radar losing the contact (notching, the speed gate, ground clutter). Without a loaded ship, which happens beyond
* render distance, the last radar position is extrapolated for a limited time.
* <p>
* The selected index is no help for this: the radar rebuilds its list, so after a loss the index can point at another
* contact or at an empty slot.
*/
final class TargetTrack {
/** A radar position this close to a ship is taken to be that ship. */
private static final double SNAP_BLOCKS = 80.0;
/** A fresh radar position this far from the followed ship means the player moved on to another target. */
private static final double REBIND_BLOCKS = 250.0;
private static final long NONE = Long.MIN_VALUE;
enum Source {
RADAR, VISUAL, COAST
}
/** Position in blocks, velocity in blocks per tick. */
record Fix(double x, double y, double z, double vx, double vy, double vz, Source source) {
}
private final TargetTracker radar = new TargetTracker();
private int index = -1;
private long boundId = NONE;
void reset() {
radar.reset();
index = -1;
boundId = NONE;
}
/**
* @param radarPosition the position the node reports for the selected index, or null if it reports none
*/
Fix resolve(ClientLevel level, long ownShipId, int selected, double[] radarPosition, long tick,
boolean visualTrack, double coastSeconds) {
if (selected <= 0) {
reset();
return null;
}
if (selected != index) {
reset();
index = selected;
}
if (radarPosition != null) {
radar.update(selected, radarPosition[0], radarPosition[1], radarPosition[2], tick);
}
if (visualTrack) {
ClientShip bound = boundId == NONE ? null : shipById(level, boundId);
if (radarPosition != null && radar.age(tick) <= 1) {
// Fresh contact: pick the ship it belongs to, or let go of the old one if the player switched
if (bound == null || distance(center(bound), radarPosition) > REBIND_BLOCKS) {
bound = nearest(level, ownShipId, radarPosition);
boundId = bound == null ? NONE : bound.getId();
}
}
if (bound != null) {
Vector3d center = center(bound);
var velocity = bound.getVelocity();
return new Fix(center.x, center.y, center.z, velocity.x() / 20.0, velocity.y() / 20.0, velocity.z() / 20.0, Source.VISUAL);
}
boundId = NONE;
}
if (!radar.hasPosition()) {
return null;
}
long age = radar.age(tick);
if (age > TargetTracker.STALE_TICKS) {
if (coastSeconds <= 0.0 || !radar.hasVelocity() || age > coastSeconds * 20.0) {
return null;
}
double[] p = radar.predicted(tick);
return new Fix(p[0], p[1], p[2], radar.vx(), radar.vy(), radar.vz(), Source.COAST);
}
double[] p = radar.predicted(tick);
// A contact is only extrapolated up to the age of its last update
return new Fix(p[0], p[1], p[2], radar.vx(), radar.vy(), radar.vz(), Source.RADAR);
}
private static ClientShip shipById(ClientLevel level, long id) {
for (ClientShip ship : VSGameUtilsKt.getShipObjectWorld(level).getLoadedShips()) {
if (ship.getId() == id) {
return ship;
}
}
return null;
}
private static ClientShip nearest(ClientLevel level, long ownShipId, double[] position) {
ClientShip best = null;
double bestDistance = SNAP_BLOCKS;
for (ClientShip ship : VSGameUtilsKt.getShipObjectWorld(level).getLoadedShips()) {
if (ship.getId() == ownShipId) {
continue;
}
double distance = distance(center(ship), position);
if (distance < bestDistance) {
bestDistance = distance;
best = ship;
}
}
return best;
}
/** The same point Warium's radar reports: the center of the world bounding box. */
private static Vector3d center(ClientShip ship) {
AABBdc box = ship.getWorldAABB();
return box.center(new Vector3d());
}
private static double distance(Vector3d a, double[] b) {
return Math.sqrt(sq(a.x - b[0]) + sq(a.y - b[1]) + sq(a.z - b[2]));
}
private static double sq(double v) {
return v * v;
}
}
@@ -0,0 +1,113 @@
package dev.lumareth.improvedAerodynamics.client.pipper;
/**
* Target velocity from the radar. The node only stores positions, and they change when the radar updates, which is
* not every tick. So the velocity is the change between two distinct positions divided by the ticks between them,
* smoothed. When the radar stops updating the last velocity is kept so the track can be extrapolated.
*/
final class TargetTracker {
/** Ticks without a new position after which the contact counts as lost and is only extrapolated. */
static final long STALE_TICKS = 40;
private static final double SMOOTHING = 0.5;
private static final double JUMP_BLOCKS_PER_TICK = 15.0;
private int index = -1;
private double px;
private double py;
private double pz;
private long sampleTick;
private double vx;
private double vy;
private double vz;
private boolean hasVelocity;
void update(int selected, double x, double y, double z, long tick) {
if (selected != index || tick < sampleTick) {
index = selected;
px = x;
py = y;
pz = z;
sampleTick = tick;
hasVelocity = false;
vx = 0.0;
vy = 0.0;
vz = 0.0;
return;
}
if (x != px || y != py || z != pz) {
long dt = Math.max(1L, tick - sampleTick);
double nx = (x - px) / dt;
double ny = (y - py) / dt;
double nz = (z - pz) / dt;
if (Math.sqrt(nx * nx + ny * ny + nz * nz) > JUMP_BLOCKS_PER_TICK) {
// Teleport or a different contact reusing the slot
hasVelocity = false;
} else if (hasVelocity) {
vx += (nx - vx) * SMOOTHING;
vy += (ny - vy) * SMOOTHING;
vz += (nz - vz) * SMOOTHING;
} else {
vx = nx;
vy = ny;
vz = nz;
hasVelocity = true;
}
px = x;
py = y;
pz = z;
sampleTick = tick;
}
}
void reset() {
index = -1;
hasVelocity = false;
vx = 0.0;
vy = 0.0;
vz = 0.0;
}
boolean hasPosition() {
return index >= 0;
}
/** Ticks since the radar last gave a new position. */
long age(long tick) {
return tick - sampleTick;
}
/** The last radar position moved on by the velocity over the time since. */
double[] predicted(long tick) {
long dt = Math.max(0L, tick - sampleTick);
return new double[] {px + vx * dt, py + vy * dt, pz + vz * dt};
}
double lastX() {
return px;
}
double lastY() {
return py;
}
double lastZ() {
return pz;
}
/** Velocity in blocks per tick, zero when unknown. */
double vx() {
return vx;
}
double vy() {
return vy;
}
double vz() {
return vz;
}
boolean hasVelocity() {
return hasVelocity;
}
}
@@ -0,0 +1,20 @@
package dev.lumareth.improvedAerodynamics.client.pipper;
import net.mcreator.valkyrienwarium.entity.SeatEntityEntity;
import net.minecraft.world.entity.Entity;
/** Everything that touches Warium VS classes, so nothing else loads them when Warium is missing. */
final class WariumSeat {
private WariumSeat() {
}
static Entity seatOf(Entity rider) {
Entity root = rider.getRootVehicle();
return root instanceof SeatEntityEntity ? root : null;
}
/** Index of the radar target selected on the seat, 1 based, 0 for none. */
static int selectedTarget(Entity seat) {
return seat.getEntityData().get(SeatEntityEntity.DATA_SelectedTarget);
}
}
@@ -205,10 +205,7 @@ public final class AeroState implements PhysicsBridge.Publishable {
private void evaluate(Frame frame, Vector3dc centerOfMass, double[] v, double[] w, boolean improved, boolean commit, Wrench out) { private void evaluate(Frame frame, Vector3dc centerOfMass, double[] v, double[] w, boolean improved, boolean commit, Wrench out) {
out.clear(); out.clear();
double weight = clock.weight(); double weight = clock.weight();
double liftConstant = ImprovedAero.LIFT_CONSTANT; ImprovedAero.Tuning tuning = improved ? ImprovedAero.Tuning.read() : null;
double stallAngleScale = Config.STALL_ANGLE_SCALE.get();
double liftScale = Config.LIFT_SCALE.get();
double thinDrag = Config.STABILIZER_DRAG.get();
double[] r = new double[3]; double[] r = new double[3];
if (commit) { if (commit) {
wingStalled = false; wingStalled = false;
@@ -227,7 +224,7 @@ public final class AeroState implements PhysicsBridge.Publishable {
double input = s.type().controllable ? input(s, node, state, 0.0) : 0.0; double input = s.type().controllable ? input(s, node, state, 0.0) : 0.0;
if (improved) { if (improved) {
boolean nowStalled = ImprovedAero.evaluate(s, v, w, r, input, weight, liftConstant, liftScale, stallAngleScale, thinDrag, stalled[i], out); boolean nowStalled = ImprovedAero.evaluate(s, v, w, r, input, weight, tuning, stalled[i], out);
if (commit) { if (commit) {
stalled[i] = nowStalled; stalled[i] = nowStalled;
wingStalled |= nowStalled && s.type() == SurfaceType.WING; wingStalled |= nowStalled && s.type() == SurfaceType.WING;
@@ -242,7 +239,7 @@ public final class AeroState implements PhysicsBridge.Publishable {
probe.clear(); probe.clear();
double base = 0.0; double base = 0.0;
if (improved) { if (improved) {
ImprovedAero.evaluate(s, v, w, r, input, weight, liftConstant, liftScale, stallAngleScale, thinDrag, stalled[i], probe); ImprovedAero.evaluate(s, v, w, r, input, weight, tuning, stalled[i], probe);
} else { } else {
WariumAero.evaluate(s, v, w, r, input, weight, probe); WariumAero.evaluate(s, v, w, r, input, weight, probe);
} }
@@ -250,7 +247,7 @@ public final class AeroState implements PhysicsBridge.Publishable {
probe.clear(); probe.clear();
double nudged = input(s, node, state, delta); double nudged = input(s, node, state, delta);
if (improved) { if (improved) {
ImprovedAero.evaluate(s, v, w, r, nudged, weight, liftConstant, liftScale, stallAngleScale, thinDrag, stalled[i], probe); ImprovedAero.evaluate(s, v, w, r, nudged, weight, tuning, stalled[i], probe);
} else { } else {
WariumAero.evaluate(s, v, w, r, nudged, weight, probe); WariumAero.evaluate(s, v, w, r, nudged, weight, probe);
} }
@@ -13,16 +13,17 @@ package dev.lumareth.improvedAerodynamics.flight;
* @param node BlockPos.asLong of the Vehicle Control Node the surface listens to, {@link #NO_NODE} if none * @param node BlockPos.asLong of the Vehicle Control Node the surface listens to, {@link #NO_NODE} if none
* @param brakeInput air brakes only: Warium's input value, they ignore smoothing and trim * @param brakeInput air brakes only: Warium's input value, they ignore smoothing and trim
* @param aspectRatio span squared over area of the wing the block belongs to, 0 if not known yet * @param aspectRatio span squared over area of the wing the block belongs to, 0 if not known yet
* @param wingGroup whether the wing the block belongs to contains WING blocks, not only control surfaces or stabilizers
*/ */
public record AeroSurface(long key, SurfaceType type, boolean slab, double x, double y, double z, int facingX, int facingZ, public record AeroSurface(long key, SurfaceType type, boolean slab, double x, double y, double z, int facingX, int facingZ,
double pressure, double fluidFactor, double speedMultiplier, double pressure, double fluidFactor, double speedMultiplier,
long node, ControlAxis axis1, double multiplier1, ControlAxis axis2, double multiplier2, long node, ControlAxis axis1, double multiplier1, ControlAxis axis2, double multiplier2,
double brakeInput, double aspectRatio) { double brakeInput, double aspectRatio, boolean wingGroup) {
public static final long NO_NODE = Long.MIN_VALUE; public static final long NO_NODE = Long.MIN_VALUE;
AeroSurface withAspectRatio(double aspectRatio) { AeroSurface withWingShape(double aspectRatio, boolean wingGroup) {
return new AeroSurface(key, type, slab, x, y, z, facingX, facingZ, pressure, fluidFactor, speedMultiplier, return new AeroSurface(key, type, slab, x, y, z, facingX, facingZ, pressure, fluidFactor, speedMultiplier,
node, axis1, multiplier1, axis2, multiplier2, brakeInput, aspectRatio); node, axis1, multiplier1, axis2, multiplier2, brakeInput, aspectRatio, wingGroup);
} }
/** Warium's "Direction.getClockWise(Axis.Y)" of the facing, the span direction of a horizontal surface. */ /** Warium's "Direction.getClockWise(Axis.Y)" of the facing, the span direction of a horizontal surface. */
@@ -1,5 +1,7 @@
package dev.lumareth.improvedAerodynamics.flight; package dev.lumareth.improvedAerodynamics.flight;
import dev.lumareth.improvedAerodynamics.Config;
/** /**
* Flight model based on each surface's angle of attack, used instead of {@link WariumAero} when enabled. * Flight model based on each surface's angle of attack, used instead of {@link WariumAero} when enabled.
* <p> * <p>
@@ -41,6 +43,18 @@ final class ImprovedAero {
*/ */
static final double LIFT_CONSTANT = 160.0 / (REFERENCE_SPEED * LIFT_SLOPE * REFERENCE_ANGLE); static final double LIFT_CONSTANT = 160.0 / (REFERENCE_SPEED * LIFT_SLOPE * REFERENCE_ANGLE);
/** The config values the model reads, taken once per evaluation. */
record Tuning(double liftScale, double stallAngleScale, double thinDrag,
boolean transonic, double speedOfSound, double transonicPeakDrag, double supersonicDrag,
boolean vortex, double vortexStallBonus, double vortexLiftStrength) {
static Tuning read() {
return new Tuning(Config.LIFT_SCALE.get(), Config.STALL_ANGLE_SCALE.get(), Config.STABILIZER_DRAG.get(),
Config.TRANSONIC_DRAG.get(), Config.SPEED_OF_SOUND.get(), Config.TRANSONIC_PEAK_DRAG.get(),
Config.SUPERSONIC_DRAG.get(),
Config.VORTEX_LIFT.get(), Config.VORTEX_STALL_BONUS.get(), Config.VORTEX_LIFT_STRENGTH.get());
}
}
/** /**
* Adds the surface's forces to out. * Adds the surface's forces to out.
* *
@@ -49,12 +63,10 @@ final class ImprovedAero {
* @param r block center relative to the center of mass, ship axes * @param r block center relative to the center of mass, ship axes
* @param input control input of the surface, -1 to 1 * @param input control input of the surface, -1 to 1
* @param stalled whether the surface was stalled in the previous substep * @param stalled whether the surface was stalled in the previous substep
* @param liftScale multiplier for the lift only, not the drag
* @param thinDrag parasitic drag coefficient of stabilizers and vertical wings
* @return whether the surface is stalled now * @return whether the surface is stalled now
*/ */
static boolean evaluate(AeroSurface s, double[] v, double[] w, double[] r, double input, double weight, static boolean evaluate(AeroSurface s, double[] v, double[] w, double[] r, double input, double weight,
double liftConstant, double liftScale, double stallAngleScale, double thinDrag, boolean stalled, Wrench out) { Tuning tuning, boolean stalled, Wrench out) {
// Airflow at the block: ship velocity plus w x r // Airflow at the block: ship velocity plus w x r
double vx = v[0] + w[1] * r[2] - w[2] * r[1]; double vx = v[0] + w[1] * r[2] - w[2] * r[1];
double vy = v[1] + w[2] * r[0] - w[0] * r[2]; double vy = v[1] + w[2] * r[0] - w[0] * r[2];
@@ -71,8 +83,13 @@ final class ImprovedAero {
return false; return false;
} }
// Warium's own per-block drag, lower for thin surfaces since they stabilize with lift, not drag // Warium's own per-block drag, lower for thin surfaces since they stabilize with lift, not drag. Shock waves
double parasitic = -localSpeed * (s.type().thin ? thinDrag : s.type().parasiticDrag) * p / m; // multiply it near the speed of sound; this is the only zero-lift drag a craft has, induced and stall drag
// below are not affected
double shockDrag = tuning.transonic()
? TransonicDrag.multiplier(localSpeed / tuning.speedOfSound(), tuning.transonicPeakDrag(), tuning.supersonicDrag())
: 1.0;
double parasitic = -localSpeed * (s.type().thin ? tuning.thinDrag() : s.type().parasiticDrag) * shockDrag * p / m;
out.addForce(r, vx * parasitic, vy * parasitic, vz * parasitic); out.addForce(r, vx * parasitic, vy * parasitic, vz * parasitic);
// Chord c along the facing, normal n up for horizontal surfaces and to the side for vertical ones // Chord c along the facing, normal n up for horizontal surfaces and to the side for vertical ones
@@ -99,7 +116,13 @@ final class ImprovedAero {
} }
alpha = Math.max(-Math.PI / 2.0, Math.min(Math.PI / 2.0, alpha)); alpha = Math.max(-Math.PI / 2.0, Math.min(Math.PI / 2.0, alpha));
double critical = Math.toRadians(s.slab() ? SurfaceType.SLAB_STALL_ANGLE : s.type().stallAngle) * stallAngleScale; // Low aspect ratio wings keep their flow attached longer thanks to leading-edge vortices. Control surfaces
// in a wing's group stall with the wing instead of before it
double vortexFactor = tuning.vortex() && (s.type() == SurfaceType.WING || s.wingGroup() && s.type().controllable)
? VortexLift.factor(s.aspectRatio()) : 0.0;
double baseStall = s.slab() ? SurfaceType.SLAB_STALL_ANGLE
: s.wingGroup() && s.type().controllable ? SurfaceType.WING.stallAngle : s.type().stallAngle;
double critical = Math.toRadians(baseStall) * (1.0 + tuning.vortexStallBonus() * vortexFactor) * tuning.stallAngleScale();
double absAlpha = Math.abs(alpha); double absAlpha = Math.abs(alpha);
// Flips only where both blends agree, so the hysteresis never makes the force jump // Flips only where both blends agree, so the hysteresis never makes the force jump
if (!stalled && absAlpha > critical + STALL_BLEND) { if (!stalled && absAlpha > critical + STALL_BLEND) {
@@ -115,11 +138,14 @@ final class ImprovedAero {
double slope = aspectRatio > 0.0 ? 2.0 * Math.PI / (1.0 + 2.0 / aspectRatio) : LIFT_SLOPE; double slope = aspectRatio > 0.0 ? 2.0 * Math.PI / (1.0 + 2.0 / aspectRatio) : LIFT_SLOPE;
double inducedDrag = aspectRatio > 0.0 ? 1.0 / (Math.PI * EFFICIENCY * aspectRatio) : INDUCED_DRAG; double inducedDrag = aspectRatio > 0.0 ? 1.0 / (Math.PI * EFFICIENCY * aspectRatio) : INDUCED_DRAG;
double attachedLift = slope * alpha; double attachedLift = slope * alpha;
if (s.type() == SurfaceType.WING) {
attachedLift += VortexLift.liftCoefficient(alpha, vortexFactor, tuning.vortexLiftStrength());
}
double lift = attached * attachedLift + (1.0 - attached) * SEPARATED_LIFT * Math.sin(2.0 * alpha); double lift = attached * attachedLift + (1.0 - attached) * SEPARATED_LIFT * Math.sin(2.0 * alpha);
double drag = attached * inducedDrag * attachedLift * attachedLift double drag = attached * inducedDrag * attachedLift * attachedLift
+ (1.0 - attached) * SEPARATED_DRAG * Math.sin(alpha) * Math.sin(alpha); + (1.0 - attached) * SEPARATED_DRAG * Math.sin(alpha) * Math.sin(alpha);
double q = liftConstant * p * fd * planeSpeedSq; double q = LIFT_CONSTANT * p * fd * planeSpeedSq;
// Lift is perpendicular to the airflow in the chord/normal plane, on the side of n // Lift is perpendicular to the airflow in the chord/normal plane, on the side of n
double side = u < 0.0 ? -1.0 : 1.0; double side = u < 0.0 ? -1.0 : 1.0;
double lx = (Math.abs(u) * nx - side * vn * cx) / planeSpeed; double lx = (Math.abs(u) * nx - side * vn * cx) / planeSpeed;
@@ -129,13 +155,13 @@ final class ImprovedAero {
double dx = -(u * cx + vn * nx) / planeSpeed; double dx = -(u * cx + vn * nx) / planeSpeed;
double dy = -(vn * ny) / planeSpeed; double dy = -(vn * ny) / planeSpeed;
double dz = -(u * cz + vn * nz) / planeSpeed; double dz = -(u * cz + vn * nz) / planeSpeed;
double liftForce = q * lift * liftScale; double liftForce = q * lift * tuning.liftScale();
double dragForce = q * drag / m; double dragForce = q * drag / m;
out.addForce(r, lx * liftForce + dx * dragForce, ly * liftForce + dy * dragForce, lz * liftForce + dz * dragForce); out.addForce(r, lx * liftForce + dx * dragForce, ly * liftForce + dy * dragForce, lz * liftForce + dz * dragForce);
return stalled; return stalled;
} }
private static double smoothstep(double edge0, double edge1, double x) { static double smoothstep(double edge0, double edge1, double x) {
double t = Math.max(0.0, Math.min(1.0, (x - edge0) / (edge1 - edge0))); double t = Math.max(0.0, Math.min(1.0, (x - edge0) / (edge1 - edge0)));
return t * t * (3.0 - 2.0 * t); return t * t * (3.0 - 2.0 * t);
} }
@@ -0,0 +1,33 @@
package dev.lumareth.improvedAerodynamics.flight;
/**
* Rise of zero-lift drag around the speed of sound: shock waves build up from Mach 0.8, drag peaks at Mach 1.05 and
* settles to a lower, still high, level once the flow is fully supersonic from Mach 1.3.
*/
final class TransonicDrag {
private static final double DRAG_RISE_START = 0.80;
private static final double PEAK = 1.05;
private static final double SUPERSONIC_START = 1.30;
private TransonicDrag() {
}
/**
* @param mach airspeed divided by the speed of sound
* @param peakDrag multiplier at the peak
* @param supersonicDrag multiplier once fully supersonic
* @return factor for parasitic drag, 1 in subsonic flight
*/
static double multiplier(double mach, double peakDrag, double supersonicDrag) {
if (mach <= DRAG_RISE_START) {
return 1.0;
}
if (mach < PEAK) {
return 1.0 + (peakDrag - 1.0) * ImprovedAero.smoothstep(DRAG_RISE_START, PEAK, mach);
}
if (mach < SUPERSONIC_START) {
return peakDrag + (supersonicDrag - peakDrag) * ImprovedAero.smoothstep(PEAK, SUPERSONIC_START, mach);
}
return supersonicDrag;
}
}
@@ -0,0 +1,29 @@
package dev.lumareth.improvedAerodynamics.flight;
/**
* Leading-edge vortices of low aspect ratio (delta) wings: the sharp edge rolls the flow up into a vortex that keeps
* the wing lifting far beyond the angle where a straight wing stalls.
*/
final class VortexLift {
// Polhamus' leading-edge suction analogy constant, about pi for a sharp edge
private static final double VORTEX_CONSTANT = Math.PI;
private static final double FULL_VORTEX_ASPECT_RATIO = 1.0;
private static final double NO_VORTEX_ASPECT_RATIO = 3.0;
private VortexLift() {
}
/** How much of the vortex effect a wing gets: 1 at aspect ratio 1 or less, 0 at 3 or more, 0 if its shape is unknown. */
static double factor(double aspectRatio) {
if (aspectRatio <= 0.0) {
return 0.0;
}
return 1.0 - ImprovedAero.smoothstep(FULL_VORTEX_ASPECT_RATIO, NO_VORTEX_ASPECT_RATIO, aspectRatio);
}
/** Lift coefficient added by the vortex, odd in the angle of attack like the normal lift. */
static double liftCoefficient(double alpha, double factor, double strength) {
double sin = Math.sin(alpha);
return strength * factor * VORTEX_CONSTANT * sin * Math.abs(sin) * Math.cos(alpha);
}
}
@@ -97,7 +97,7 @@ public final class WariumCapture {
return new AeroSurface(pos.asLong(), type, slab, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, return new AeroSurface(pos.asLong(), type, slab, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5,
facing.getStepX(), facing.getStepZ(), pressure, fluidFactor(level), speedMultiplier, facing.getStepX(), facing.getStepZ(), pressure, fluidFactor(level), speedMultiplier,
node, ControlAxis.of(key), ControlAxis.multiplier(key), ControlAxis.of(key2), ControlAxis.multiplier(key2), node, ControlAxis.of(key), ControlAxis.multiplier(key), ControlAxis.of(key2), ControlAxis.multiplier(key2),
brakeInput, 0.0); brakeInput, 0.0, false);
} }
/** Registers a node's inputs once per tick, and saves its trim to it now and then so it survives reloading. */ /** Registers a node's inputs once per tick, and saves its trim to it now and then so it survives reloading. */
@@ -61,6 +61,7 @@ final class WingShape {
int[] count = new int[n]; int[] count = new int[n];
int[] minSpan = new int[n]; int[] minSpan = new int[n];
int[] maxSpan = new int[n]; int[] maxSpan = new int[n];
boolean[] hasWing = new boolean[n];
java.util.Arrays.fill(minSpan, Integer.MAX_VALUE); java.util.Arrays.fill(minSpan, Integer.MAX_VALUE);
java.util.Arrays.fill(maxSpan, Integer.MIN_VALUE); java.util.Arrays.fill(maxSpan, Integer.MIN_VALUE);
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
@@ -70,6 +71,7 @@ final class WingShape {
int root = find(parent, i); int root = find(parent, i);
int span = all[i].type().vertical ? cell[i * 3 + 1] : cell[i * 3] * Math.abs(all[i].rightX()) + cell[i * 3 + 2] * Math.abs(all[i].rightZ()); int span = all[i].type().vertical ? cell[i * 3 + 1] : cell[i * 3] * Math.abs(all[i].rightX()) + cell[i * 3 + 2] * Math.abs(all[i].rightZ());
count[root]++; count[root]++;
hasWing[root] |= all[i].type() == SurfaceType.WING;
minSpan[root] = Math.min(minSpan[root], span); minSpan[root] = Math.min(minSpan[root], span);
maxSpan[root] = Math.max(maxSpan[root], span); maxSpan[root] = Math.max(maxSpan[root], span);
} }
@@ -80,7 +82,7 @@ final class WingShape {
int root = find(parent, i); int root = find(parent, i);
double span = maxSpan[root] - minSpan[root] + 1; double span = maxSpan[root] - minSpan[root] + 1;
double aspectRatio = span * span / count[root]; double aspectRatio = span * span / count[root];
all[i] = all[i].withAspectRatio(Math.max(MIN_ASPECT_RATIO, Math.min(MAX_ASPECT_RATIO, aspectRatio))); all[i] = all[i].withWingShape(Math.max(MIN_ASPECT_RATIO, Math.min(MAX_ASPECT_RATIO, aspectRatio)), hasWing[root]);
} }
return all; return all;
} }
@@ -5,5 +5,12 @@
"message.improved_aerodynamics.auto_trim.off": "Automatische Trimmung aus", "message.improved_aerodynamics.auto_trim.off": "Automatische Trimmung aus",
"message.improved_aerodynamics.auto_trim.unavailable": "Automatische Trimmung an, sie braucht aber physicsRateAerodynamics in der Serverkonfiguration", "message.improved_aerodynamics.auto_trim.unavailable": "Automatische Trimmung an, sie braucht aber physicsRateAerodynamics in der Serverkonfiguration",
"message.improved_aerodynamics.auto_trim.no_seat": "Setz dich in einen Warium-Steuersitz, um die automatische Trimmung zu nutzen", "message.improved_aerodynamics.auto_trim.no_seat": "Setz dich in einen Warium-Steuersitz, um die automatische Trimmung zu nutzen",
"message.improved_aerodynamics.auto_trim.no_node": "Dieser Sitz ist mit keinem Vehicle Control Node verbunden" "message.improved_aerodynamics.auto_trim.no_node": "Dieser Sitz ist mit keinem Vehicle Control Node verbunden",
"config.improved_aerodynamics.transonicDrag": "Transsonischer Widerstand: Der Nullauftriebswiderstand steigt um die Schallgeschwindigkeit stark an (verbessertes Flugmodell)",
"config.improved_aerodynamics.speedOfSound": "Schallgeschwindigkeit in Blöcken pro Sekunde, Mach 1 für den transsonischen Widerstand",
"config.improved_aerodynamics.transonicPeakDrag": "Multiplikator für den Nullauftriebswiderstand an seinem Höchstwert bei Mach 1,05",
"config.improved_aerodynamics.supersonicDrag": "Multiplikator für den Nullauftriebswiderstand bei vollem Überschall, ab Mach 1,3",
"config.improved_aerodynamics.vortexLift": "Wirbelauftrieb: Flügel mit kleiner Streckung (Deltaflügel) überziehen später und liefern bei großen Anstellwinkeln mehr Auftrieb (verbessertes Flugmodell)",
"config.improved_aerodynamics.vortexStallBonus": "Zusätzlicher Überziehwinkel der Flügel mit der kleinsten Streckung, als Anteil des normalen Überziehwinkels",
"config.improved_aerodynamics.vortexLiftStrength": "Multiplikator für den zusätzlichen Auftrieb der Vorderkantenwirbel"
} }
@@ -5,5 +5,12 @@
"message.improved_aerodynamics.auto_trim.off": "Auto trim off", "message.improved_aerodynamics.auto_trim.off": "Auto trim off",
"message.improved_aerodynamics.auto_trim.unavailable": "Auto trim on, but it needs physicsRateAerodynamics enabled in the server config", "message.improved_aerodynamics.auto_trim.unavailable": "Auto trim on, but it needs physicsRateAerodynamics enabled in the server config",
"message.improved_aerodynamics.auto_trim.no_seat": "Sit in a Warium control seat to use auto trim", "message.improved_aerodynamics.auto_trim.no_seat": "Sit in a Warium control seat to use auto trim",
"message.improved_aerodynamics.auto_trim.no_node": "This seat is not linked to a vehicle control node" "message.improved_aerodynamics.auto_trim.no_node": "This seat is not linked to a vehicle control node",
"config.improved_aerodynamics.transonicDrag": "Transonic drag: zero-lift drag rises steeply around the speed of sound (improved flight model)",
"config.improved_aerodynamics.speedOfSound": "Speed of sound in blocks per second, Mach 1 for the transonic drag",
"config.improved_aerodynamics.transonicPeakDrag": "Zero-lift drag multiplier at its peak, Mach 1.05",
"config.improved_aerodynamics.supersonicDrag": "Zero-lift drag multiplier once fully supersonic, from Mach 1.3",
"config.improved_aerodynamics.vortexLift": "Vortex lift: low aspect ratio (delta) wings stall later and lift more at high angles of attack (improved flight model)",
"config.improved_aerodynamics.vortexStallBonus": "Extra stall angle of the lowest aspect ratio wings, as a fraction of the normal stall angle",
"config.improved_aerodynamics.vortexLiftStrength": "Multiplier for the extra lift the leading-edge vortices make"
} }