diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index a05aa8810..79ea852fb 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -116,6 +116,9 @@ jobs: # Horizon's Azure app for Microsoft sign-in (docs/microsoft-account.md): a repository # variable, not a secret. Unset, the launcher says sign-in is not configured. HORIZON_MSA_CLIENT_ID: ${{ vars.HORIZON_MSA_CLIENT_ID }} + # The mod browser's CurseForge source (docs/mod-browser.md#curseforge): a repository secret. Unset, the + # launcher searches Modrinth only. + HORIZON_CURSEFORGE_API_KEY: ${{ secrets.HORIZON_CURSEFORGE_API_KEY }} # The release's version and tag, built in (launcher/src/backend.rs VERSION and own_tag: the tag says which # line it is on, docs/versioning.md); a launcher branch's build keeps Cargo.toml's. HORIZON_LAUNCHER_VERSION: ${{ (github.event_name != 'push' || github.ref == 'refs/heads/main') && needs.decide.outputs.version || '' }} diff --git a/crates/horizon-client/examples/particle_providers_probe.rs b/crates/horizon-client/examples/particle_providers_probe.rs index 989895c07..8b8bd1e0d 100644 --- a/crates/horizon-client/examples/particle_providers_probe.rs +++ b/crates/horizon-client/examples/particle_providers_probe.rs @@ -112,21 +112,26 @@ fn state(s: &ParticleSnapshot) -> String { } out } -fn world(assets: &Assets, facts: &BlockFacts, floor: bool) -> Result { +fn world(assets: &Assets, facts: &BlockFacts, floor: bool, water: bool) -> Result { let mut world = World::new(facts.air, 0); - let stone = assets - .registry - .default_state("minecraft:stone") - .ok_or("missing stone")?; + let state = |name: &str| assets.registry.default_state(name).ok_or("missing block"); + let (stone, still) = (state("minecraft:stone")?, state("minecraft:water")?); for cz in -3..=2 { for cx in -3..=2 { world .chunks .insert((cx, cz), Arc::new(Chunk::empty(cx, cz))); - if floor { - for z in 0..16 { - for x in 0..16 { - world.set(cx * 16 + x, 63, cz * 16 + z, stone)?; + for z in 0..16 { + for x in 0..16 { + let (x, z) = (cx * 16 + x, cz * 16 + z); + if floor { + world.set(x, 63, z, stone)?; + } + // The oracle's water: still sources from y 64 to 67. + if water { + for y in 64..=67 { + world.set(x, y, z, still)?; + } } } } @@ -142,8 +147,10 @@ fn main() -> Result<()> { let facts = BlockFacts::load(root, assets.registry)?; let collision = collisions::load(root, assets.registry)?; let worlds = [ - world(&assets, &facts, false)?, - world(&assets, &facts, true)?, + world(&assets, &facts, false, false)?, + world(&assets, &facts, true, false)?, + world(&assets, &facts, false, true)?, + world(&assets, &facts, true, true)?, ]; let mut engine = ParticleEngine::new(root, &HashMap::new()); for (ty, item) in [ @@ -174,7 +181,8 @@ fn main() -> Result<()> { engine.requested = Some(Vec::new()); engine.sounds.clear(); let level = ParticleLevel { - world: &worlds[usize::from(case["floor"].as_bool() == Some(true))], + world: &worlds[usize::from(case["floor"].as_bool() == Some(true)) + + 2 * usize::from(case["water"].as_bool() == Some(true))], facts: &facts, collision: &collision, player: None, diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index b391c0cbf..ce34df510 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -61,6 +61,8 @@ enum Animate { Fire, /// An active sculk sensor. SculkSensor, + /// Potent sulfur that is not dry. + PotentSulfur, } fn step(facing: &str) -> [i32; 3] { match facing { @@ -128,6 +130,9 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { } } "respawn_anchor" if prop("charges").is_some_and(|c| c != "0") => Animate::RespawnAnchor, + "potent_sulfur" if prop("potent_sulfur_state").is_some_and(|s| s != "dry") => { + Animate::PotentSulfur + } "bubble_column" => Animate::BubbleColumn { drag: prop("drag").as_deref() == Some("true"), }, @@ -819,6 +824,26 @@ fn block_animate_tick( } } } + Animate::PotentSulfur => { + // PotentSulfurBlock.animateTick: under a water source, two + // bubbles and, one time in ten, the noxious gas. + let above = ctx.facts.get(ctx.state([pos[0], pos[1] + 1, pos[2]])); + if above.fluid == Fluid::Water && above.fluid_level == 8 && !above.fluid_falling { + for _ in 0..2 { + let r = engine.random(); + let p = [ + fx + f64::from(r.next_float()), + fy + 1.0 + f64::from(r.next_float()), + fz + f64::from(r.next_float()), + ]; + add(engine, T::SulfurBubbles, p, [0.0; 3]); + } + if next_int(engine.random(), 10) == 0 { + let name = "minecraft:block.potent_sulfur.noxious_gas"; + sound(engine, name, [fx, fy, fz], 1.0, 1.0); + } + } + } Animate::Mycelium => { let r = engine.random(); if next_int(r, 10) == 0 { diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 62bdc041f..f101f53cd 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -2,7 +2,7 @@ //! small mixer standing in for OpenAL: one channel per source with its gain, //! pitch, linear distance attenuation (`AL_LINEAR_DISTANCE`, reference 0, //! rolloff 1), looping, relative flag and source state, Ogg/Vorbis decoding -//! (streams on a worker thread) and stereo panning. +//! (streams on a worker thread) and OpenAL Soft's stereo panning. use crate::Result; use crate::sound_engine::{ Attenuation, Backend, Bound, ChannelId, InstanceId, PlayResult, SoundEngine, SoundInstance, @@ -45,6 +45,7 @@ struct Mixer { channels: HashMap, listener: [f64; 3], listener_yaw: f32, + listener_pitch: f32, limiter_peak: f32, } /// A sound the player could have heard (`SoundEventListener.onPlaySound`): @@ -157,6 +158,9 @@ pub struct Audio { /// Positional sounds played since the last drain, kept while the world /// is open to the network so guests hear them too. pub capture: Option>, + /// How many times each positional sound played (the control socket's `status`), + /// with or without an audio device. + pub heard: std::collections::BTreeMap, } fn decode(path: &Path) -> Option<(Vec, u32)> { use symphonia::core::{ @@ -331,6 +335,32 @@ impl Backend for MixerBackend { .unwrap_or(true) } } +/// OpenAL Soft's stereo gains `[left, right]` for a mono source in a +/// direction given in listener space (right, up, forward; any length). +/// Vanilla's context (`Library.createAttributes`: HRTF off) on a stereo +/// output renders pairwise: front azimuths are stretched by 1.5 +/// (`ScaleAzimuthFront`, so 60 degrees off-centre pans fully) and the +/// direction is decoded by the first-order stereo decoder, 0.5 W, 0.5 Y and +/// 0.0957 X in this scaling. A centred source gets 0.596 on each side, one +/// behind 0.404, one above or below 0.5, one at the source's own position +/// is panned to the front. Matches OpenAL Soft 1.25.2 (LWJGL 3.4.3, the +/// pinned client's) rendered through `ALC_SOFT_loopback` within 1e-5. +fn stereo_gains(right: f32, up: f32, forward: f32) -> [f32; 2] { + let length = (right * right + up * up + forward * forward).sqrt(); + if length <= f32::EPSILON { + return stereo_gains(0.0, 0.0, 1.0); + } + let elevation = (up / length).clamp(-1.0, 1.0).asin(); + let mut azimuth = right.atan2(forward); + if azimuth.abs() < std::f32::consts::FRAC_PI_2 { + azimuth = (azimuth.abs() * 1.5) + .min(std::f32::consts::FRAC_PI_2) + .copysign(azimuth); + } + let side = azimuth.sin() * elevation.cos(); + let front = azimuth.cos() * elevation.cos() * 0.095_660_8; + [0.5 - 0.5 * side + front, 0.5 + 0.5 * side + front] +} /// The gain OpenAL applies for distance (`AL_LINEAR_DISTANCE` with reference /// distance 0 and rolloff 1: the distance clamps to the max distance). fn distance_gain(linear: Option, distance: f32) -> f32 { @@ -345,9 +375,30 @@ fn distance_gain(linear: Option, distance: f32) -> f32 { fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { data.fill(0.0); let listener = mixer.listener; - let yaw = mixer.listener_yaw.to_radians(); + // The camera's forward and up vectors (`Camera.forwardVector`/`upVector`) + // and OpenAL's right = forward x up. + let (yaw, pitch) = ( + f64::from(mixer.listener_yaw.to_radians()), + f64::from(mixer.listener_pitch.to_radians()), + ); + let forward = [ + -yaw.sin() * pitch.cos(), + -pitch.sin(), + yaw.cos() * pitch.cos(), + ]; + let up = [ + -yaw.sin() * pitch.sin(), + pitch.cos(), + yaw.cos() * pitch.sin(), + ]; + let right = [ + forward[1] * up[2] - forward[2] * up[1], + forward[2] * up[0] - forward[0] * up[2], + forward[0] * up[1] - forward[1] * up[0], + ]; + let dot = |a: [f64; 3], b: [f64; 3]| (a[0] * b[0] + a[1] * b[1] + a[2] * b[2]) as f32; // Gains and pans per source for this buffer. - let mut voices: Vec<(ChannelId, f32, f32, f64)> = Vec::new(); + let mut voices: Vec<(ChannelId, [f32; 3], f64)> = Vec::new(); for (id, c) in &mixer.channels { let Some((_, source_rate)) = &c.samples else { continue; @@ -366,19 +417,17 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { }; let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32; let gain = c.gain.clamp(0.0, 1.0) * distance_gain(c.linear, distance); - // The listener's right vector for a Minecraft yaw. - let side = if c.relative { - (d[0] as f32) / distance.max(0.001) + // Relative sources are already in OpenAL's listener space (-Z ahead). + let [left, right] = if c.relative { + stereo_gains(d[0] as f32, d[1] as f32, -d[2] as f32) } else { - (-(yaw.cos()) as f64 * d[0] - (yaw.sin()) as f64 * d[2]) as f32 / distance.max(0.001) - }; - let pan = side.clamp(-1.0, 1.0); - let left = gain * (1.0 - pan.max(0.0) * 0.6); - let right = gain * (1.0 + pan.min(0.0) * 0.6); + stereo_gains(dot(d, right), dot(d, up), dot(d, forward)) + } + .map(|pan| gain * pan); let step = f64::from(*source_rate) / f64::from(rate) * f64::from(c.pitch.max(0.0)); - voices.push((*id, left, right, step)); + voices.push((*id, [left, right, gain], step)); } - for (id, left, right, step) in voices { + for (id, [left, right, gain], step) in voices { let Some(c) = mixer.channels.get_mut(&id) else { continue; }; @@ -402,16 +451,19 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { frame[0] += s * left; frame[1] += s * right; } else { - frame[0] += s * (left + right) / 2.0; + // A mono output has no panning: the source's own gain. + frame[0] += s * gain; } c.position += step; } } // Limit the whole buffer together, preserving waveform and stereo balance - // instead of flattening each overloaded sample; release over 50 ms. + // instead of flattening each overloaded sample; release over 200 ms + // (OpenAL Soft's output limiter, `ALC_OUTPUT_LIMITER_SOFT`, releases + // over 0.2 s). let peak = data.iter().fold(1.0f32, |peak, s| peak.max(s.abs())); mixer.limiter_peak = mixer.limiter_peak.max(peak); - let release = (-1.0 / (0.05 * rate as f32)).exp(); + let release = (-1.0 / (0.2 * rate as f32)).exp(); for frame in data.chunks_mut(channels) { let gain = mixer.limiter_peak.recip(); for s in frame { @@ -542,6 +594,7 @@ impl Audio { random: LegacyRandom::new(crate::sound_engine::unique_seed()), source_override: None, capture: None, + heard: Default::default(), } } #[cfg(not(feature = "audio"))] @@ -591,13 +644,15 @@ impl Audio { backend: &mut self.backend, } } - /// `SoundManager.updateSource`: the camera position and yaw. - pub fn set_listener(&mut self, position: [f64; 3], yaw: f32) { + /// `SoundManager.updateSource`: the camera position and rotation + /// (`Listener.setTransform` takes its forward and up vectors). + pub fn set_listener(&mut self, position: [f64; 3], yaw: f32, pitch: f32) { self.listener = position; self.listener_yaw = yaw; if let Ok(mut m) = self.backend.mixer.lock() { m.listener = position; m.listener_yaw = yaw; + m.listener_pitch = pitch; } } /// Sync the volume options, refreshing the categories that changed @@ -682,6 +737,9 @@ impl Audio { if let (Some(capture), Some(at)) = (self.capture.as_mut(), at) { capture.push((event.to_owned(), at, volume, pitch)); } + if at.is_some() { + *self.heard.entry(event.to_owned()).or_default() += 1; + } self.sync_volumes(); let event = crate::sound_events::normalize(event); let source = self @@ -908,8 +966,9 @@ mod tests { } let mut data = [0.0; 16]; mix(&mut m, &mut data, 2, 48_000); + // West of a listener facing south: fully on the right. for (frame, sample) in data.as_chunks::<2>().0.iter().zip(wave) { - assert!((frame[0] - sample * 0.4).abs() < 1e-6, "{frame:?}"); + assert!(frame[0].abs() < 1e-6, "{frame:?}"); assert!((frame[1] - sample).abs() < 1e-6, "{frame:?}"); } assert!(data.iter().all(|s| s.abs() <= 1.0)); @@ -920,9 +979,10 @@ mod tests { let mut m = Mixer::default(); m.channels .insert(1, channel(vec![0.25; 2], None, [0.0; 3], true)); + let quiet = 0.25 * stereo_gains(0.0, 0.0, 1.0)[0]; let mut data = [0.0; 16]; mix(&mut m, &mut data, 2, 48_000); - assert_eq!(data, [0.25; 16]); + assert_eq!(data, [quiet; 16]); for id in 2..=5 { m.channels @@ -935,7 +995,7 @@ mod tests { mix(&mut m, &mut recovery, 2, 48_000); assert!(recovery[0] > 0.0 && recovery[0] < 0.1); assert!(recovery.windows(2).all(|w| w[1] >= w[0])); - assert_eq!(*recovery.last().unwrap(), 0.25); + assert_eq!(*recovery.last().unwrap(), quiet); } #[test] @@ -953,4 +1013,60 @@ mod tests { let first = data[0] + data[1]; assert!(first > 1.4 && first < 3.1, "{first}"); } + + #[test] + fn stereo_panning_matches_openal_soft() { + // OpenAL Soft 1.25.2 (LWJGL 3.4.3's macOS build), stereo loopback + // device with vanilla's attributes, 1 kHz sine 4 blocks away. + let cases = [ + ((0.0, 0.0, 1.0), [0.5957, 0.5957]), + ((-1.0, 0.0, 0.0), [1.0, 0.0]), + ((1.0, 0.0, 0.0), [0.0, 1.0]), + ((0.0, 0.0, -1.0), [0.4043, 0.4043]), + ((0.0, 1.0, 0.0), [0.5, 0.5]), + ((0.0, -1.0, 0.0), [0.5, 0.5]), + ((-1.0, 0.0, 1.0), [0.9985, 0.0747]), + ((-1.0, 0.0, -1.0), [0.7859, 0.0788]), + ((0.0, 0.0, 0.0), [0.5957, 0.5957]), + ]; + for ((right, up, forward), expected) in cases { + let gains = stereo_gains(right, up, forward); + for (g, e) in gains.into_iter().zip(expected) { + assert!((g - e).abs() < 1e-4, "{right} {up} {forward}: {gains:?}"); + } + } + } + + #[test] + fn panning_follows_the_camera_rotation() { + let gains = |yaw: f32, pitch: f32, at: [f32; 3]| { + let mut m = Mixer { + listener_yaw: yaw, + listener_pitch: pitch, + ..Mixer::default() + }; + m.channels.insert(1, channel(vec![1.0; 4], None, at, true)); + let mut data = [0.0; 2]; + mix(&mut m, &mut data, 2, 48_000); + data + }; + let close = + |a: [f32; 2], b: [f32; 2]| (a[0] - b[0]).abs() < 1e-4 && (a[1] - b[1]).abs() < 1e-4; + // Facing south (yaw 0), east is on the left; facing north, on the right. + assert!(close(gains(0.0, 0.0, [1.0, 0.0, 0.0]), [1.0, 0.0])); + assert!(close(gains(180.0, 0.0, [1.0, 0.0, 0.0]), [0.0, 1.0])); + // Looking straight down, a source below is ahead and one south is above. + assert!(close(gains(0.0, 90.0, [0.0, -1.0, 0.0]), [0.5957, 0.5957])); + assert!(close(gains(0.0, 90.0, [0.0, 0.0, 1.0]), [0.5, 0.5])); + } + + #[test] + fn a_mono_output_plays_sources_unpanned() { + let mut m = Mixer::default(); + m.channels + .insert(1, channel(vec![0.5; 4], None, [0.0, 0.0, -3.0], true)); + let mut data = [0.0; 2]; + mix(&mut m, &mut data, 1, 48_000); + assert_eq!(data, [0.5; 2]); + } } diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index a52f25ce7..67f5d6027 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -15,8 +15,9 @@ use horizon_world::{ entity_obstruction::EntityIdentity, fluid::{FluidKind, FluidState}, liquid_collision::LiquidCollisionWorld, + piston_shape::PistonCollisionWorld, powder_snow_collision::{PowderSnowEntity, PowderSnowWorld}, - registry::{BlockRegistry, BlockTableFile}, + registry::{BlockRegistry, BlockStateId, BlockTableFile}, world_movement::{ CollisionCheckRequest, EntityMovementWorld, MovementRequest, no_world_collision, resolve_world_movement, @@ -259,8 +260,30 @@ impl DynamicSupportWorld for SceneCollisions<'_, '_> { fn shulker_is_closed(&mut self, _: [i32; 3]) -> io::Result> { Ok(None) } - fn moving_piston_shape(&mut self, _: [i32; 3]) -> io::Result> { - Ok(None) + /// `MovingPistonBlock.getCollisionShape`: the block entity's moving shape + /// (`PistonMovingBlockEntity.getCollisionShape`), outside any push. + fn moving_piston_shape(&mut self, p: [i32; 3]) -> io::Result> { + let Some(&(_, piston)) = self.world.moving_pistons.iter().find(|(q, _)| *q == p) else { + return Ok(None); + }; + let binding = self.binding; + let Some(pistons) = binding.pistons() else { + return Ok(None); + }; + pistons + .collision_shape(self, p, piston, None) + .map(Some) + .map_err(io::Error::other) + } +} +impl PistonCollisionWorld for SceneCollisions<'_, '_> { + type Error = io::Error; + /// `BlockState.getCollisionShape(level, pos)` of the moved state. + fn collision_shape(&mut self, state: BlockStateId, p: [i32; 3]) -> io::Result { + let binding = self.binding; + binding + .collision_shape(self, state, p) + .map_err(io::Error::other) } } impl DynamicCollisionWorld for SceneCollisions<'_, '_> { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a25e8fdeb..2df6aa9b0 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -34,6 +34,7 @@ mod crossbow; mod debug_keys; mod decorated_pot; mod dedicated; +mod deflect; mod dispense_fixture; mod dispenser; mod dragon; @@ -89,6 +90,7 @@ mod mob_gear; mod mods; mod mount_menu; mod mounts; +mod moving_pistons; mod music; mod names; mod natural_spawning; @@ -1236,7 +1238,9 @@ struct Game<'a> { /// swap just before an attack keeps them, with the new item's enchantments /// (attribute swapping). attack_item: Option>, - last_hurt_by_player: HashSet, + /// Mobs a player hurt (`LivingEntity.lastHurtByPlayer`), with the guest + /// it was by connection (None: the host). + last_hurt_by_player: HashMap>, /// Mobs whose death (`LivingEntity.die`) has been handled. died: HashSet, /// Client-ticked block-entity animation state (`game/block_entity_anims.rs`). @@ -2420,8 +2424,21 @@ impl Game<'_> { b.run_block_events(level, ticks); b.tick_block_entities(level, ticks); }); + self.sync_moving_pistons(); self.process_level_events() } + /// Copies the moving-piston block entities into the world, where the + /// collision queries and the renderer read them. + fn sync_moving_pistons(&mut self) { + let pistons = &mut self.world.moving_pistons; + pistons.clear(); + pistons.extend( + self.block_ticks + .moving_pistons + .iter() + .map(|(p, piston)| ([p.x, p.y, p.z], piston.shape_state())), + ); + } /// `ServerLevel.tick`'s scheduled block then fluid ticks, one at a time: /// the side effects of each (a shrieker summoning a warden, drops, game /// events) happen before the next tick runs, as they do inline in vanilla. @@ -6575,6 +6592,7 @@ impl Game<'_> { vertex.color = horizon_client::hud_layout::multiply(vertex.color, tint); } } + self.moving_piston_geometry(camera, alpha, &mut out); self.tnt_geometry(camera, alpha, &mut out); self.painting_geometry(camera, &mut out); self.frame_geometry(camera, &mut out); @@ -6586,6 +6604,7 @@ impl Game<'_> { self.leash_geometry(camera, alpha, &mut out); self.trident_geometry(camera, alpha, &mut out); self.rocket_geometry(camera, alpha, &mut out); + self.thrown_potion_geometry(camera, alpha, &mut out); // Particles (ParticleEngine.extract): camera-facing quads. let world = &self.world; self.particles.render( @@ -6829,6 +6848,10 @@ impl Game<'_> { self.break_painting(i, true); return true; } + // A ghast's fireball or a wind charge in front: turned back. + if self.attack_redirectable() { + return true; + } let hand_damage = 1.0 + self .held() @@ -6937,7 +6960,8 @@ impl Game<'_> { (actual * 0.5) as u32, ); } - self.last_hurt_by_player.insert(self.mobs[index].id); + self.last_hurt_by_player + .insert(self.mobs[index].id, self.lan_acting); let sound = if crit { "minecraft:entity.player.attack.crit" } else if scale > 0.9 { @@ -9404,7 +9428,7 @@ impl Game<'_> { ), }; self.audio - .set_listener([camera.x, camera.y, camera.z], view_yaw); + .set_listener([camera.x, camera.y, camera.z], view_yaw, view_pitch); let block = [ camera.x.floor() as i32, camera.y.floor() as i32, @@ -11323,7 +11347,7 @@ impl<'a> Game<'a> { raiding: Default::default(), attack_ticks: 100, attack_item: None, - last_hurt_by_player: HashSet::new(), + last_hurt_by_player: HashMap::new(), died: HashSet::new(), be_anims: { let mut anims = horizon_client::block_entity_anim::BlockEntityAnims::default(); diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index da3851d9a..70ae082aa 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -25,6 +25,9 @@ pub(super) struct CombatTracker { pub(super) last_hurt_mob: Option<(u32, i64)>, /// The mob whose projectile is hitting the player now. pub(super) projectile_owner: Option, + /// The projectile hitting the player now is another player's that + /// `ServerPlayer.canHarmPlayer` refuses (the `pvp` rule, an ally). + pub(super) refuse_player_hit: bool, /// The mob exploding now (`ServerExplosion.source`): its team's friendly /// fire decides whom the blast may hurt. pub(super) explosion_source: Option, diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 6c69904ac..d79f69d3c 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -912,6 +912,7 @@ impl Game<'_> { status["pending_uploads"] = self.pending_uploads.len().into(); status["destroying"] = json!(destroying); status["physical_keys"] = json!(physical_keys); + status["heard"] = json!(self.audio.heard); // Boats, minecarts, armor stands, item frames and paintings. status["objects"] = json!(self.objects_status()); // Primed TNT, falling blocks, projectiles, tridents and end crystals. diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 218d9e85c..78efc708d 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -3,6 +3,7 @@ //! breeding, conversions, drops), projectiles, player interactions //! (feeding, shearing, milking, spawn eggs, throwing) and rendering. use super::{Dim, Game, view_vector}; +use horizon_assets::item_model::DisplayContext; use horizon_client::{ Result, arrows::EntityHit, @@ -622,7 +623,8 @@ impl Game<'_> { } /// LivingEntity.die / dropAllDeathLoot. fn mob_died(&mut self, m: &Mob) { - let by_player = self.last_hurt_by_player.remove(&m.id) || m.ai.last_hurt_by_player > 0; + let killer = self.last_hurt_by_player.remove(&m.id); + let by_player = killer.is_some() || m.ai.last_hurt_by_player > 0; let mut dying = m.clone(); // LivingEntity.die: the death is heard, and a sculk catalyst nearby // takes the experience (before the loot is dropped). @@ -636,11 +638,22 @@ impl Game<'_> { } }); if by_player { - self.stats.add("killed", &m.kind.id, 1); - self.stats.custom("mob_kills", 1); - self.score_player_killed(super::commands::Target::Mob(m.id)); - let view = self.mob_entity(m); - self.trigger_entity("minecraft:player_killed_entity", "entity", &view); + // A guest's kill is theirs: their statistics, scores and + // advancements (LivingEntity.die credits lastHurtByPlayer). + let guest = killer.flatten().filter(|_| self.lan_acting.is_none()); + let credited = guest.is_some_and(|conn| { + let Some(mut host) = self.lan.take() else { + return false; + }; + let done = self + .as_guest(&mut host, conn, |g| g.credit_kill(m)) + .is_some(); + self.lan = Some(host); + done + }); + if !credited { + self.credit_kill(m); + } } self.score_entity_removed(m.id); self.raider_died(m, by_player); @@ -675,6 +688,15 @@ impl Game<'_> { } } } + /// The killer's side of a mob's death: `ServerPlayer.awardKillScore`'s + /// statistics and scores, and the `player_killed_entity` trigger. + fn credit_kill(&mut self, m: &Mob) { + self.stats.add("killed", &m.kind.id, 1); + self.stats.custom("mob_kills", 1); + self.score_player_killed(super::commands::Target::Mob(m.id)); + let view = self.mob_entity(m); + self.trigger_entity("minecraft:player_killed_entity", "entity", &view); + } /// `dropAllDeathLoot` through `mobs::drops`: the entity loot table from the /// world's random sequence, equipment by drop chance, species extras and /// the experience orbs, spawned in order. @@ -1393,7 +1415,8 @@ impl Game<'_> { from: [f64; 3], damage_type: &str, ) -> bool { - if self.creative { + // ServerPlayer.canHarmPlayer refused another player's projectile. + if self.creative || self.combat.refuse_player_hit { return false; } let projectile = self @@ -1631,14 +1654,30 @@ impl Game<'_> { w: &w, targets: targets_guests, }; + let guest_entities = self.lan_guest_entities(); projectiles.retain_mut(|p| { let mob_shot = !matches!(p.owner, Some(Who::Player)); - let (keep, hit) = match (p.arrow.is_some(), mob_shot) { + // A player's arrows, snowballs and eggs meet every player; a + // guest's flies from that guest (Projectile.getOwner), not + // from the host, until it has left them. + let pvp = !mob_shot && super::lan_pvp::meets_players(&p.kind); + let shooter = p + .guest + .filter(|_| pvp) + .and_then(|c| guest_entities.iter().find(|(g, _)| *g == c)) + .map(|&(_, id)| Who::Mob(id)); + if shooter.is_some() { + p.owner = shooter; + } + let (keep, hit) = match (p.arrow.is_some(), mob_shot || pvp) { (true, false) => horizon_client::arrows::tick(p, &scene, &arrow_targets), (true, true) => horizon_client::arrows::tick(p, &scene, &arrow_targets_guests), (false, false) => p.tick(&pw), (false, true) => p.tick(&pw_guests), }; + if shooter.is_some() { + p.owner = Some(Who::Player); + } if let Some(a) = p.arrow.as_mut() { arrow_events.extend(a.events.drain(..).map(|e| (p.position, e))); } @@ -1690,6 +1729,11 @@ impl Game<'_> { } self.creatures.projectiles.append(&mut projectiles); for (p, hit) in hits { + // A player's arrow on another player lands as the victim's hurt. + if let Some(victim) = self.projectile_pvp_victim(&p, hit) { + self.projectile_hits_player(&p, hit, victim)?; + continue; + } // A guest's projectile lands as theirs: a pearl takes them, what // it hurts answers to them. One hitting the host (`Who::Player` // here) stays the host's hit. @@ -1973,7 +2017,7 @@ impl Game<'_> { .find(|m| m.id == id) .is_some_and(|m| m.damage(amount, source)); if p.owner == Some(Who::Player) { - self.last_hurt_by_player.insert(id); + self.last_hurt_by_player.insert(id, self.lan_acting); } hurt } @@ -2098,15 +2142,21 @@ impl Game<'_> { } }, Hit::Block { pos, face, .. } => { + // SmallFireball.onHitBlock: a mob's only with mobGriefing; + // BaseFireBlock.getState placed with updates (the fire + // ticks, ages and goes out where it can't stay). let fire = [pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]]; - if self - .res - .facts() - .is_air(self.world.block(fire[0], fire[1], fire[2])) - && let Some(state) = - self.pack.assets.registry.default_state("minecraft:fire") + let mob = matches!(p.owner, Some(Who::Mob(_))); + if (!mob || self.ui.rules.bool("mob_griefing")) + && self + .res + .facts() + .is_air(self.world.block(fire[0], fire[1], fire[2])) { - self.world.set(fire[0], fire[1], fire[2], state)?; + let at = BlockPos::new(fire[0], fire[1], fire[2]); + let state = + self.with_level(|b, level, ticks| b.fire_state_for(level, ticks, at)); + self.level_set(fire, state)?; } } Hit::None => {} @@ -3058,6 +3108,14 @@ impl Game<'_> { } continue; } + if let Some(stack) = a.potion_item() { + let owner = super::item_draw::owner_at(at, 0.0, "minecraft:splash_potion"); + let state = self.resolve_item(&stack, DisplayContext::Ground, Some(&owner), 0); + let pose = glam::Mat4::from_translation(c) + * glam::Mat4::from_quat(self.camera_orientation()); + self.submit_item_world(&state, pose, packed, out); + continue; + } let Some(name) = a.item_sprite() else { continue; }; diff --git a/crates/horizon-client/src/game/deflect.rs b/crates/horizon-client/src/game/deflect.rs new file mode 100644 index 000000000..a08de87b3 --- /dev/null +++ b/crates/horizon-client/src/game/deflect.rs @@ -0,0 +1,155 @@ +//! A player's blow at a ghast's fireball or a wind charge +//! (`#minecraft:redirectable_projectile`): `Player.attack` turns it with +//! `ProjectileDeflection.AIM_DEFLECT` instead of hurting anything. It flies on +//! along the player's view and is the player's now (`Projectile.deflect` +//! sets the owner), so a ghast it meets dies of it (`Ghast.isReflectedFireball`). +use super::{Game, ray_box, view_vector}; +use horizon_client::{ + mobs::Who, + projectiles::{Projectile, ProjectileKind}, +}; +use horizon_core::geometry::{Aabb, Vec3}; + +/// `AbstractHurtingProjectile.getPickRadius`: the crosshair finds it a block +/// round its box. +const PICK_RADIUS: f64 = 1.0; + +/// `#minecraft:redirectable_projectile`: a ghast's fireball and both wind charges. +pub(super) fn redirectable(p: &Projectile) -> bool { + !p.stuck + && matches!( + p.kind, + ProjectileKind::LargeFireball { .. } + | ProjectileKind::WindCharge + | ProjectileKind::BreezeWindCharge + ) +} + +/// Its box for the crosshair: the entity's (a fireball 1 x 1, a wind charge +/// 0.3125, from its feet up) grown by the pick radius. +fn pick_box(p: &Projectile) -> Aabb { + let size = match p.kind { + ProjectileKind::LargeFireball { .. } => 1.0, + _ => 0.3125, + }; + let half = size / 2.0 + PICK_RADIUS; + Aabb::new( + Vec3::new( + p.position.x - half, + p.position.y - PICK_RADIUS, + p.position.z - half, + ), + Vec3::new( + p.position.x + half, + p.position.y + size + PICK_RADIUS, + p.position.z + half, + ), + ) +} + +impl Game<'_> { + /// The redirectable projectile under the crosshair within the attack + /// reach, and how far along the view it is. + pub(super) fn redirectable_hit(&self) -> Option<(usize, f64)> { + let eye = self.eye_position()?; + let dir = view_vector(self.yaw, self.pitch); + let reach: f64 = if self.creative { 5.0 } else { 3.0 }; + self.creatures + .projectiles + .iter() + .enumerate() + .filter(|(_, p)| redirectable(p)) + .filter_map(|(i, p)| ray_box(eye, dir, reach, pick_box(p)).map(|t| (i, t))) + .min_by(|a, b| a.1.total_cmp(&b.1)) + } + + /// `Player.attack` on a redirectable projectile nearer than any mob or + /// block in view: `AIM_DEFLECT` (its movement the unit view vector), the + /// player its owner, its acceleration power back to 0.1 + /// (`onDeflection` by an attack), and the no-damage sound. True when a + /// projectile was turned. + pub(super) fn attack_redirectable(&mut self) -> bool { + let Some((i, t)) = self.redirectable_hit() else { + return false; + }; + if self.mob_hit().is_some_and(|(_, d)| d < t) { + return false; + } + if let (Some(hit), Some(eye)) = (self.pick(), self.eye_position()) { + let d = (0..3) + .map(|a| (hit.point[a] - eye[a]).powi(2)) + .sum::() + .sqrt(); + if d < t { + return false; + } + } + self.deflect(i); + true + } + + /// `Player.canInteractWithEntity(box, 3.0)` as the server checks an + /// attack packet: the projectile's box within the reach plus 3 of the eyes. + pub(super) fn within_interaction_range(&self, i: usize) -> bool { + let (Some(eye), Some(p)) = (self.eye_position(), self.creatures.projectiles.get(i)) else { + return false; + }; + let b = pick_box(p); + let (lo, hi) = (b.min_position(), b.max_position()); + let (lo, hi) = ( + [lo.x + PICK_RADIUS, lo.y + PICK_RADIUS, lo.z + PICK_RADIUS], + [hi.x - PICK_RADIUS, hi.y - PICK_RADIUS, hi.z - PICK_RADIUS], + ); + let d2: f64 = (0..3) + .map(|a| (eye[a] - eye[a].clamp(lo[a], hi[a])).powi(2)) + .sum(); + let range = if self.creative { 5.0 } else { 3.0 } + 3.0; + d2 < range * range + } + + /// `Projectile.deflect(AIM_DEFLECT, player, player, true)`. + pub(super) fn deflect(&mut self, i: usize) { + let dir = view_vector(self.yaw, self.pitch); + let guest = self.lan_acting; + let p = &mut self.creatures.projectiles[i]; + p.velocity = Vec3::new(dir[0], dir[1], dir[2]); + p.yaw = dir[0].atan2(dir[2]).to_degrees() as f32; + p.pitch = dir[1].atan2(dir[0].hypot(dir[2])).to_degrees() as f32; + p.owner = Some(Who::Player); + // On a server, the guest who struck it (their projectile now). + p.guest = guest; + // Not into the one who turned it on its way out. + p.left_owner = false; + self.reset_attack_strength(); + self.swing_arm(); + let from = self + .player + .as_ref() + .map(|p| [p.position.x, p.position.y, p.position.z]); + self.audio + .play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_ghast_fireballs_and_wind_charges_are_redirectable() { + let at = Vec3::new(0.0, 64.0, 0.0); + let large = Projectile::fireball( + ProjectileKind::LargeFireball { power: 1 }, + at, + None, + [1.0, 0.0, 0.0], + ); + let small = Projectile::fireball(ProjectileKind::SmallFireball, at, None, [1.0, 0.0, 0.0]); + assert!(redirectable(&large)); + assert!(!redirectable(&small)); + // The pick box: a block round the fireball's 1 x 1 box. + let b = pick_box(&large); + assert_eq!(b.min_position().x, -1.5); + assert_eq!(b.max_position().y, 66.0); + } +} diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index db3f523bc..b4e358d50 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -317,7 +317,11 @@ impl Game<'_> { .cloned() } /// The same block with other properties (`withProperty`). - fn with_props(&self, state: BlockStateId, props: &[(&str, &str)]) -> Option { + pub(super) fn with_props( + &self, + state: BlockStateId, + props: &[(&str, &str)], + ) -> Option { let mut s = self.pack.assets.registry.state(state)?.clone(); for (k, v) in props { s.properties.insert((*k).to_owned(), (*v).to_owned()); diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 55babd9af..5cf67f586 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -226,6 +226,102 @@ impl Game<'_> { } /// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT); /// the player takes `damage_type`. + /// `ServerExplosion.hurtEntities` for the player: damage scaled by + /// distance and exposure, through a raised shield (`hurtServer` blocks + /// explosions like any attack from where the blast is), then the push + /// (less with explosion knockback resistance; none for spectators or a + /// creative player flying). + pub(super) fn explosion_hurt_player( + &mut self, + center: [f64; 3], + radius: f32, + damage_type: &str, + exploding: Option, + ) { + let diameter = f64::from(radius * 2.0); + // Blast protection: `EXPLOSION_KNOCKBACK_RESISTANCE` (0.15 per level and + // piece, so two Blast Protection IV pieces cancel it). + let resistance = self + .player + .as_mut() + .and_then(|p| p.attribute("minecraft:explosion_knockback_resistance").ok()) + .unwrap_or(0.0); + let Some(p) = self.player.as_ref() else { + return; + }; + let feet = [p.position.x, p.position.y, p.position.z]; + let dist = ((feet[0] - center[0]).powi(2) + + (feet[1] - center[1]).powi(2) + + (feet[2] - center[2]).powi(2)) + .sqrt() + / diameter; + if dist > 1.0 || p.health.dead_or_dying() { + return; + } + let w = f64::from(p.dimensions.width) / 2.0; + let h = f64::from(p.dimensions.height); + let eye = [ + feet[0], + feet[1] + f64::from(p.dimensions.eye_height), + feet[2], + ]; + let exposure = self.seen_percent( + center, + [feet[0] - w, feet[1], feet[2] - w], + [feet[0] + w, feet[1] + h, feet[2] + w], + ); + let pow = (1.0 - dist) * f64::from(exposure); + let amount = ((pow * pow + pow) / 2.0 * 7.0 * diameter + 1.0) as f32; + let d = [eye[0] - center[0], eye[1] - center[1], eye[2] - center[2]]; + let l = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + let dir = if l < 1.0e-4 { + [0.0; 3] + } else { + [d[0] / l, d[1] / l, d[2] / l] + }; + let power = pow * (1.0 - resistance); + // `source.doTeamsAllowDamage(entity)`. + let hurtable = exploding.is_none_or(|id| { + horizon_client::scoreboard::teams_allow_damage(self.mob_team(id), self.player_team()) + }); + let blocking = self.player_blocking(Some(center), damage_type, false); + let raised = blocking.is_some(); + let (creative, spectator) = (self.creative, self.spectator()); + let flying = self.player.as_ref().is_some_and(|p| p.flying); + let mut outcome = horizon_client::health::BlockOutcome::default(); + if let Some(p) = self.player.as_mut() + && let Some(id) = self.motion.health.damage.id(damage_type) + { + // Creative players are invulnerable to explosions. + if !creative + && !spectator + && hurtable + && let Ok(o) = p.hurt_blocking( + &self.motion.health, + self.world.health_rules, + id, + amount, + blocking, + ) + { + outcome = o; + } + if !spectator && !(creative && flying) { + p.velocity = Vec3::new( + p.velocity.x + dir[0] * power, + p.velocity.y + dir[1] * power, + p.velocity.z + dir[2] * power, + ); + } + } + if outcome.hurt && !creative { + self.hurt_armor(amount); + } + if raised { + self.after_block(outcome, amount, None, false); + } + } + fn explosion_hurt_entities(&mut self, center: [f64; 3], radius: f32, damage_type: &str) { if radius < 1.0e-5 { return; @@ -261,57 +357,23 @@ impl Game<'_> { horizon_client::scoreboard::teams_allow_damage(g.mob_team(id), victim) }) }; - let player_hurtable = teams_allow(self, self.player_team()); - // Player. - if let Some(p) = self.player.as_ref() { - let feet = [p.position.x, p.position.y, p.position.z]; - let dist = distance(feet) / diameter; - if dist <= 1.0 && !p.health.dead_or_dying() { - let w = f64::from(p.dimensions.width) / 2.0; - let h = f64::from(p.dimensions.height); - let eye = [ - feet[0], - feet[1] + f64::from(p.dimensions.eye_height), - feet[2], - ]; - let exposure = self.seen_percent( - center, - [feet[0] - w, feet[1], feet[2] - w], - [feet[0] + w, feet[1] + h, feet[2] + w], - ); - let amount = damage(dist, exposure); - let dir = direction(eye); - let mut hurt = false; - let creative = self.creative; - if let Some(p) = self.player.as_mut() - && let Some(id) = self.motion.health.damage.id(damage_type) - { - // Creative players are invulnerable to explosions. - if !creative && player_hurtable { - hurt = p - .hurt(&self.motion.health, self.world.health_rules, id, amount) - .unwrap_or(false); - } - // Blast protection: `EXPLOSION_KNOCKBACK_RESISTANCE` (0.15 per - // level and piece, so two Blast Protection IV pieces cancel it). - let resistance = p - .attribute("minecraft:explosion_knockback_resistance") - .unwrap_or(0.0); - let power = (1.0 - dist) * f64::from(exposure) * (1.0 - resistance); - // `hitPlayers` skips creative players who are flying: the - // client gets no knockback in the explode packet. - if !(creative && p.flying) { - p.velocity = Vec3::new( - p.velocity.x + dir[0] * power, - p.velocity.y + dir[1] * power, - p.velocity.z + dir[2] * power, - ); - } - } - if hurt && !self.creative { - self.hurt_armor(amount); - } + // The player, then every other player in the level (LAN guests), + // each swapped in as the player. + self.explosion_hurt_player(center, radius, damage_type, exploding); + if let Some(mut host) = self.lan.take() { + let guests: Vec = host + .hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) + .map(|g| g.conn) + .collect(); + for conn in guests { + self.guest_hit_by(&mut host, conn, |g| { + g.explosion_hurt_player(center, radius, damage_type, exploding); + }); } + self.lan = Some(host); } // Mobs. let mut mobs = std::mem::take(&mut self.mobs); diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index 84cea5a5c..a7218ff3c 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -156,6 +156,7 @@ impl Game<'_> { || before(self.dragon_hit().map(|h| h.1)) || before(self.mob_hit().map(|h| h.1)) || before(self.guest_hit().map(|h| h.1)) + || before(self.redirectable_hit().map(|h| h.1)) } /// `LocalPlayer.isHandsBusy`: paddling a boat. fn hands_busy(&self) -> bool { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 1c38f9542..b261e8ad2 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -64,6 +64,12 @@ pub(super) struct GuestPlay { xp_delay: u32, /// What last killed the guest outright (`/kill`): the death message's key. death_cause: Option, + /// The equipment modifiers on the guest's attributes (`apply_equipment`) + /// and the armour and main hand they were put on for: the hub's player + /// is a `ServerPlayer` too, whose worn armour counts + /// (`LivingEntity.collectEquipmentChanges`). + modifiers: Vec<(String, String)>, + equipped: Option>>, } /// A guest's command waiting for the hub (`LanHost::commands`). @@ -130,6 +136,8 @@ pub(super) struct GuestSwap { swings: u32, /// How many projectiles there were: those added since are the guest's. projectiles: usize, + /// The host's equipment modifiers. + modifiers: Vec<(String, String)>, } impl GuestPlay { @@ -193,7 +201,8 @@ impl Game<'_> { return None; } let i = host.hub.guests.iter().position(|g| g.conn == conn)?; - if host.hub.guests[i].motion.is_none() { + let fresh = host.hub.guests[i].motion.is_none(); + if fresh { let p = Vec3::new( host.hub.guests[i].position[0], host.hub.guests[i].position[1], @@ -207,6 +216,10 @@ impl Game<'_> { } } let mut play = host.play.remove(&conn).unwrap_or_default(); + if fresh { + // A new body (joined, respawned, changed level): nothing on it yet. + play.equipped = None; + } let g = &mut host.hub.guests[i]; // The guest's body. let Some(mut motion) = g.motion.take() else { @@ -310,6 +323,17 @@ impl Game<'_> { let packets = std::mem::take(&mut self.guest_packets); let swings = self.swings_started; let projectiles = self.creatures.projectiles.len(); + let modifiers = std::mem::replace( + &mut self.applied_modifiers, + std::mem::take(&mut play.modifiers), + ); + // Its worn armour on its attributes, when it changed. + let mut equipped: Vec> = self.armor.to_vec(); + equipped.push(self.inventory.get(self.selected).cloned().flatten()); + if play.equipped.as_ref() != Some(&equipped) { + self.apply_equipment(); + play.equipped = Some(equipped); + } Some(GuestSwap { conn, i, @@ -355,6 +379,7 @@ impl Game<'_> { packets, swings, projectiles, + modifiers, }) } @@ -406,7 +431,9 @@ impl Game<'_> { packets, swings, projectiles, + modifiers, } = swap; + play.modifiers = std::mem::replace(&mut self.applied_modifiers, modifiers); // What the guest shot is theirs (Projectile.setOwner). for p in self.creatures.projectiles.iter_mut().skip(projectiles) { if p.owner == Some(horizon_client::mobs::Who::Player) && p.guest.is_none() { @@ -805,6 +832,8 @@ impl Game<'_> { ], }; let hand = if p.hand == 1 { Hand::Off } else { Hand::Main }; + let logged = self.world.block_log.as_ref().map_or(0, Vec::len); + let heard = self.audio.capture.as_ref().map_or(0, Vec::len); let swung = self.as_guest(host, conn, |g| { g.forced_hit = Some(hit); g.guest_use = Some(GuestUse::OnBlock(hand)); @@ -815,6 +844,7 @@ impl Game<'_> { g.swings_started != swings }); self.lan_swing_back(host, conn, swung); + self.guest_use_sounds(host, conn, logged, heard); // The client predicted a result: correct it with what really is. for pos in [ p.pos, @@ -1127,6 +1157,22 @@ impl Game<'_> { } return; } + // A ghast's fireball or a wind charge: turned along the guest's own + // view (ServerGamePacketListenerImpl.handleInteract, then + // Player.attack's AIM_DEFLECT). + if let Some(i) = self + .creatures + .projectiles + .iter() + .position(|p| p.id != 0 && p.id as i32 == id && super::deflect::redirectable(p)) + { + self.as_guest(host, conn, |g| { + if g.within_interaction_range(i) { + g.deflect(i); + } + }); + return; + } let (old_yaw, old_pitch) = (host.hub.guests[gi].yaw, host.hub.guests[gi].pitch); if self.look_at_entity(host, gi, id).is_none() { return; @@ -1962,6 +2008,33 @@ impl Game<'_> { } } + /// `level.playSound(player, ...)` of a guest's use it predicted (`remote::hand_operated` + /// blocks only, as the guest decides): the others hear it now, the guest already did. + fn guest_use_sounds(&mut self, host: &mut LanHost, conn: u32, logged: usize, heard: usize) { + let changed: Vec<(i32, i32, i32)> = self + .world + .block_log + .as_ref() + .map_or(&[][..], |log| log.get(logged..).unwrap_or(&[])) + .to_vec(); + let facts = self.res.facts(); + if changed.is_empty() + || !changed.iter().all(|&(x, y, z)| { + super::remote::hand_operated(&facts.get(self.world.block(x, y, z)).name) + }) + { + return; + } + let Some(capture) = self.audio.capture.as_mut() else { + return; + }; + let sounds: Vec<_> = capture.drain(heard.min(capture.len())..).collect(); + for (name, at, volume, pitch) in sounds { + let source = horizon_client::settings::sound_source(&name) as i32; + host.hub.sound(&name, at, volume, pitch, source, Some(conn)); + } + } + /// Positional sounds and level events of the tick, for the guests. pub(super) fn lan_broadcast_effects(&mut self, host: &mut LanHost) { let sounds = self.audio.capture.take().unwrap_or_default(); diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index a7347ab2a..d2c643088 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -3,9 +3,26 @@ //! is worked out as the attacker (weapon, attack strength, critical hit, //! enchantments, a mace's smash) and lands on the victim like any player //! attack (blocking, armour, knockback), when the `pvp` game rule allows it -//! (`ServerPlayer.canHarmPlayer`, `isPvpAllowed`). +//! (`ServerPlayer.canHarmPlayer`, `isPvpAllowed`). A player's arrow on +//! another player lands the same way. use super::{Game, lan::LanHost, lan_mobs::guest_bounds, ray_box, view_vector}; +use horizon_client::{ + Result, + mobs::Who, + projectiles::{Hit, Projectile, ProjectileKind}, +}; + +/// The player projectiles that meet other players: arrows (their hurt), and +/// snowballs and eggs, which break on them (`Player.hurtServer` takes no 0 +/// damage). Pearls, potions and wind charges fly past players as before. +pub(super) fn meets_players(kind: &ProjectileKind) -> bool { + matches!( + kind, + ProjectileKind::Arrow { .. } | ProjectileKind::Snowball | ProjectileKind::Egg + ) +} + /// Who a player's attack lands on. #[derive(Clone, Copy)] pub(super) enum Victim { @@ -105,6 +122,89 @@ impl Game<'_> { }) } + /// The guests by connection, with their entity ids. + pub(super) fn lan_guest_entities(&self) -> Vec<(u32, u32)> { + self.lan.as_ref().map_or_else(Vec::new, |host| { + host.hub + .guests + .iter() + .map(|g| (g.conn, g.entity_id as u32)) + .collect() + }) + } + + /// The player a player's projectile hit, when it hit one: the host for a + /// guest's shot, or a guest. + pub(super) fn projectile_pvp_victim(&self, p: &Projectile, hit: Hit) -> Option { + if p.owner != Some(Who::Player) || !meets_players(&p.kind) { + return None; + } + let Hit::Entity { who, .. } = hit else { + return None; + }; + match who { + Who::Player => p.guest.map(|_| Victim::Host), + Who::Mob(id) => self + .lan + .as_ref()? + .hub + .guests + .iter() + .find(|g| g.entity_id as u32 == id) + .map(|g| Victim::Guest(g.conn)), + } + } + + /// A player's projectile on a player: the hit runs as the victim, whose + /// hurt refuses it when the `pvp` game rule or their teams forbid it + /// (`ServerPlayer.canHarmPlayer`; `AbstractArrow.onHitEntity` then turns + /// the arrow back). + pub(super) fn projectile_hits_player( + &mut self, + p: &Projectile, + hit: Hit, + victim: Victim, + ) -> Result<()> { + let Hit::Entity { at, .. } = hit else { + return Ok(()); + }; + let Some(mut host) = self.lan.take() else { + return self.projectile_hit(p, hit); + }; + let team_of = |game: &Self, name: &str| game.score.board.players_team(name).cloned(); + let attacker = match p.guest { + Some(conn) => host.hub.guest(conn).and_then(|g| team_of(self, &g.name)), + None => self.player_team().cloned(), + }; + let target = match victim { + Victim::Host => self.player_team().cloned(), + Victim::Guest(conn) => host.hub.guest(conn).and_then(|g| team_of(self, &g.name)), + }; + let refused = !(self.ui.rules.bool("pvp") + && horizon_client::scoreboard::teams_allow_damage(target.as_ref(), attacker.as_ref())); + let on_player = Hit::Entity { + who: Who::Player, + at, + }; + let result = match victim { + Victim::Host => { + self.lan = Some(host); + self.combat.refuse_player_hit = refused; + let r = self.projectile_hit(p, on_player); + self.combat.refuse_player_hit = false; + return r; + } + Victim::Guest(conn) => self.guest_hit_by(&mut host, conn, |g| { + g.combat.refuse_player_hit = refused; + let r = g.projectile_hit(p, on_player); + g.combat.refuse_player_hit = false; + r + }), + }; + self.lan = Some(host); + result.unwrap_or(Ok(())) + } + /// The hit landing on the victim with its extra knockback, then the /// attacker's attack sound. Whether the victim was hurt. pub(super) fn pvp_land(&mut self, host: &mut LanHost, victim: Victim, s: &Strike) -> bool { diff --git a/crates/horizon-client/src/game/moving_pistons.rs b/crates/horizon-client/src/game/moving_pistons.rs new file mode 100644 index 000000000..17247850e --- /dev/null +++ b/crates/horizon-client/src/game/moving_pistons.rs @@ -0,0 +1,110 @@ +//! `PistonHeadRenderer`: while a piston moves them, blocks are +//! `minecraft:moving_piston` block entities (drawn as nothing by the chunk +//! mesher); this draws each moved block at its interpolated offset. +use super::Game; +use horizon_client::mesher::Vertex; +use horizon_world::{piston_shape::MovingPistonState, registry::BlockStateId}; + +impl Game<'_> { + /// `PistonHeadRenderer.extractRenderState` and `submit`. + pub(super) fn moving_piston_geometry( + &self, + camera: glam::DVec3, + alpha: f64, + out: &mut Vec, + ) { + let partial = alpha as f32; + for &(p, piston) in &self.world.moving_pistons { + let Some((block, base)) = self.moving_piston_blocks(piston, partial) else { + continue; + }; + let step = piston.movement_direction().normal(); + let from = horizon_core::position::BlockPos::new( + p[0] - step[0], + p[1] - step[1], + p[2] - step[2], + ); + let offset = piston.interpolated_offset(partial); + let light = self.world.light(p[0], p[1], p[2]); + let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); + let corner = glam::DVec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2])); + let moved = corner + glam::Vec3::from_array(offset).as_dvec3(); + self.moving_block_vertices(block, from, moved - camera, packed, out); + if let Some(base) = base { + let at = horizon_core::position::BlockPos::new(p[0], p[1], p[2]); + self.moving_block_vertices(base, at, corner - camera, packed, out); + } + } + } + /// The moved block and, for a retracting piston, its extended base. + fn moving_piston_blocks( + &self, + piston: MovingPistonState, + partial: f32, + ) -> Option<(BlockStateId, Option)> { + let facts = self.res.facts(); + if facts.is_air(piston.moved_state) { + return None; + } + let progress = piston.interpolated_progress(partial); + let name = &*facts.get(piston.moved_state).name; + // Vanilla tests `progress <= 4.0`: a moving head is always drawn so. + if name == "minecraft:piston_head" { + let short = if progress <= 0.5 { "true" } else { "false" }; + return Some(( + self.with_props(piston.moved_state, &[("short", short)])?, + None, + )); + } + if piston.source && !piston.extending { + let registry = &self.pack.assets.registry; + let facing = registry + .state(piston.moved_state)? + .properties + .get("facing")? + .clone(); + let kind = if name == "minecraft:sticky_piston" { + "sticky" + } else { + "normal" + }; + let short = if progress >= 0.5 { "true" } else { "false" }; + let head = self.with_props( + registry.default_state("minecraft:piston_head")?, + &[("type", kind), ("facing", &facing), ("short", short)], + )?; + let base = self.with_props(piston.moved_state, &[("extended", "true")])?; + return Some((head, Some(base))); + } + Some((piston.moved_state, None)) + } + /// One `MovingBlockRenderState`: the baked model at `at` (camera-relative), + /// seeded by its block position and tinted like a falling block. + fn moving_block_vertices( + &self, + state: BlockStateId, + seed: horizon_core::position::BlockPos, + at: glam::DVec3, + light: u32, + out: &mut Vec, + ) { + let tint = self + .particle_sprite(state, [seed.x, seed.y, seed.z]) + .map(|(_, tint)| tint); + let start = out.len(); + self.block_model_vertices( + state, + horizon_core::random::position_seed(seed), + glam::Mat4::from_translation(at.as_vec3()), + light, + false, + out, + ); + if let Some(tint) = tint { + let tint = horizon_client::mobs::render::abgr(tint); + for vertex in &mut out[start..] { + vertex.color = horizon_client::hud_layout::multiply(vertex.color, tint); + } + } + } +} diff --git a/crates/horizon-client/src/game/piglins.rs b/crates/horizon-client/src/game/piglins.rs index 9df5311aa..6280959d8 100644 --- a/crates/horizon-client/src/game/piglins.rs +++ b/crates/horizon-client/src/game/piglins.rs @@ -6,7 +6,7 @@ use horizon_client::{ items::ItemStack, mobs::{Species, Who, piglin::ADMIRE}, }; -use horizon_core::random::RandomSource; +use horizon_core::{geometry::Vec3, random::RandomSource}; impl Game<'_> { fn piglin_loved(&self, item: &str) -> bool { @@ -132,12 +132,29 @@ impl Game<'_> { } else { vec![ItemStack::new(&item, 1)] }; - // BehaviorUtils.throwItem toward the nearest visible player, else nearby. - let target = self + // BehaviorUtils.throwItem toward the nearest visible player + // (NEAREST_VISIBLE_PLAYER: within 16, alive, no spectators; the + // guests count as much as the host), else nearby. + let at = m.position; + let host = self .player .as_ref() - .filter(|p| p.position.distance_squared(m.position) < 256.0) - .map(|p| [p.position.x, p.position.y + 1.0, p.position.z]); + .filter(|p| !p.health.dead_or_dying() && !self.spectator()) + .map(|p| [p.position.x, p.position.y, p.position.z]); + let guests = self.lan.iter().flat_map(|h| { + h.hub + .guests + .iter() + .filter(|g| h.hub.here(g) && g.loaded && !g.dead && !g.spectator()) + .map(|g| g.position) + }); + let d = |p: &[f64; 3]| at.distance_squared(Vec3::new(p[0], p[1], p[2])); + let target = host + .into_iter() + .chain(guests) + .filter(|p| d(p) < 256.0) + .min_by(|a, b| d(a).total_cmp(&d(b))) + .map(|p| [p[0], p[1] + 1.0, p[2]]); for stack in items { let to = target.unwrap_or_else(|| { let r = &mut self.world.random; diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 52ab5060a..72c8fe885 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -2,13 +2,16 @@ //! `Consumable`), throwing splash/lingering potions (`ThrownSplashPotion`), //! filling glass bottles (`BottleItem`), the per-tick effect application, //! effect attribute modifiers and the HUD effect icons (`Hud.extractEffects`). -use super::{Game, Screen}; +use super::{Game, Screen, item_draw::owner_at}; +use horizon_assets::item_model::DisplayContext; use horizon_client::{ + block_entity_render::vertex_light, brewing, effects::{EffectAction, EffectInstance, PlayerEffects}, hud::HudBatch, hud_layout, hud_overlays, inventory_effects, items::ItemStack, + mesher::Vertex, }; use horizon_core::{geometry::Vec3, random::RandomSource}; @@ -16,6 +19,8 @@ use horizon_core::{geometry::Vec3, random::RandomSource}; #[derive(Clone, Debug)] pub(super) struct ThrownPotion { stack: ItemStack, + /// The position before the last tick, for drawing between ticks. + previous: Vec3, position: Vec3, velocity: Vec3, age: u32, @@ -43,6 +48,7 @@ impl Game<'_> { pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) { self.potions.thrown.push(ThrownPotion { stack, + previous: position, position, velocity, age: 0, @@ -411,6 +417,7 @@ impl Game<'_> { let mut landed = Vec::new(); thrown.retain_mut(|t| { t.age += 1; + t.previous = t.position; let next = Vec3::new( t.position.x + t.velocity.x, t.position.y + t.velocity.y, @@ -461,33 +468,56 @@ impl Game<'_> { ); t.age < 1200 && t.position.y > -128.0 }); - // ThrownItemRenderer stand-in: a short-lived sprite of the potion at its position. - for t in &thrown { - let sprite = match &*t.stack.item { - "minecraft:lingering_potion" => "item/lingering_potion", - "minecraft:experience_bottle" => "item/experience_bottle", - _ => "item/splash_potion", - }; - let mut fixed = horizon_core::random::LegacyRandom::new(0); - let mut p = horizon_client::particles::Particle::terrain( - &mut fixed, - [t.position.x, t.position.y, t.position.z], - [0.0; 3], - sprite.into(), - 0xFFFFFF, - ); - p.velocity = [0.0; 3]; - p.gravity = 0.0; - p.lifetime = 2; - p.size = 0.25; - p.uv = [0.0, 0.0, 1.0, 1.0]; - self.particles.push(p); - } self.potions.thrown = thrown; for (stack, at) in landed { self.splash(&stack, at); } } + /// `ThrownItemRenderer` for thrown splash and lingering potions and + /// experience bottles: the item (GROUND) facing the camera at scale 1, + /// lit at the light probe (the eye, 0.85 of the 0.25 height). + pub(super) fn thrown_potion_geometry( + &self, + camera: glam::DVec3, + alpha: f64, + out: &mut Vec, + ) { + let orientation = glam::Mat4::from_quat(self.camera_orientation()); + for t in &self.potions.thrown { + let previous = glam::DVec3::new(t.previous.x, t.previous.y, t.previous.z); + let position = glam::DVec3::new(t.position.x, t.position.y, t.position.z); + // ThrowableProjectile.shouldRenderAtSqrDistance: hidden for its + // first two ticks within 3.5 blocks (not in the thrower's face). + if t.age < 2 && position.distance_squared(camera) < 12.25 { + continue; + } + if !self.standing_entity_in_view( + camera, + super::entity_culling::at(t.previous), + super::entity_culling::at(t.position), + alpha, + 0.25, + 0.25, + 64.0, + 0.0, + ) { + continue; + } + let p = previous.lerp(position, alpha); + let owner = owner_at(p.to_array(), 0.0, &t.stack.item); + let state = self.resolve_item(&t.stack, DisplayContext::Ground, Some(&owner), 0); + if state.is_empty() { + continue; + } + let pose = glam::Mat4::from_translation((p - camera).as_vec3()) * orientation; + let light = self.world.light( + p.x.floor() as i32, + (p.y + 0.2125).floor() as i32, + p.z.floor() as i32, + ); + self.submit_item_world(&state, pose, vertex_light(light), out); + } + } /// A splash potion's effects on the player in place, by their distance. fn splash_on_player( &mut self, diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index f7346199a..da98c52cf 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3275,7 +3275,11 @@ impl Game<'_> { .and_then(|h| self.res.items().get(&h.item)) .is_some_and(|i| i.block.is_some()); if let Some(hit) = self.pick() { - let reacts = hand == Hand::Main && self.remote_block_reacts(&hit, held.as_ref()); + let (reacts, changes) = if hand == Hand::Main { + self.remote_block_reacts(&hit, held.as_ref()) + } else { + (false, DryUse::default()) + }; let seq = self.next_sequence(); let cursor = [ (hit.point[0] - f64::from(hit.pos[0])) as f32, @@ -3301,6 +3305,9 @@ impl Game<'_> { r.use_target = Some(hit.pos); r.placing = Some((target, ticks)); } + if reacts { + self.predict_use(&changes, seq); + } if held_block { self.with_hand(hand, Game::swing_arm); return true; @@ -3310,15 +3317,61 @@ impl Game<'_> { false } + /// MultiPlayerGameMode.useItemOn inside startPrediction: the blocks the + /// use changed on this client's level at once, each kept as predicted + /// under the use's sequence until the server acknowledges it (a use the + /// server refused goes back). Only the blocks a hand opens or flips: a + /// wooden or copper door, trapdoor or fence gate, a lever or a button; + /// whatever else the use changes waits for the server. + fn predict_use(&mut self, (changes, sounds): &DryUse, seq: i32) { + let facts = self.res.facts(); + let predicted = |state: BlockStateId| hand_operated(&facts.get(state).name); + if changes.is_empty() + || !changes + .iter() + .all(|(p, s)| predicted(*s) && predicted(self.world.block(p.x, p.y, p.z))) + { + return; + } + for &(p, state) in changes { + let pos = [p.x, p.y, p.z]; + let before = self.world.block(p.x, p.y, p.z); + // BlockStatePredictionHandler.retainKnownServerState. + if let Some(r) = self.remote.as_mut() { + r.predictions + .entry(pos) + .and_modify(|e| e.0 = seq) + .or_insert((seq, before.0 as i32)); + } + self.set_block(pos, state.0 as i32); + } + // `level.playSound(player, ...)`: the clicker hears it from its own use; the + // server sends it to the others only. + for (pos, sound, volume, pitch) in sounds { + let at = [ + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 0.5, + f64::from(pos.z) + 0.5, + ]; + let name = if sound.contains(':') { + sound.to_string() + } else { + format!("minecraft:{sound}") + }; + self.audio.play(&name, Some(at), *volume, *pitch); + } + } + /// Whether the block hit takes a main-hand right click with `held` /// (`BlockState.useItemOn`, then `useWithoutItem`): a door, a button, a - /// container. Vanilla's client runs it on its own level first; this runs - /// it on a copy that keeps no change. - fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> bool { + /// container, and the blocks it changed. Vanilla's client runs it on its + /// own level first; this runs it on a copy, and `predict_use` keeps the + /// changes it predicts. + fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> (bool, DryUse) { // Player.isSecondaryUseActive with something in either hand. let hands_full = self.stack_in(self.selected).is_some() || self.offhand.is_some(); if self.keys.contains(&KeyCode::ShiftLeft) && hands_full { - return false; + return (false, DryUse::default()); } use horizon_core::geometry::Direction; let face = match hit.face { @@ -3333,8 +3386,10 @@ impl Game<'_> { world: &self.world, changed: HashMap::new(), random: horizon_core::random::LegacyRandom::new(0), + sounds: Vec::new(), }; - self.res + let reacts = self + .res .behaviours() .use_item_on( &mut level, @@ -3345,7 +3400,8 @@ impl Game<'_> { self.use_context(), held.map(|s| &*s.item), ) - .consumes_action() + .consumes_action(); + (reacts, (level.changed.into_iter().collect(), level.sounds)) } /// MultiPlayerGameMode.useItem for `hand`, if it holds something: whether @@ -3367,6 +3423,16 @@ impl Game<'_> { // MultiPlayerGameMode.useItem runs the use here too: food starts // being eaten (Consumable.startConsuming). self.with_hand(hand, |g| g.start_eating(&info)); + // BowItem.use: startUsingItem here too (with an arrow, or in creative), so that letting + // go sends RELEASE_USE_ITEM (Minecraft.handleKeybinds) and the server shoots. + if &*held.item == "minecraft:bow" { + self.with_hand(hand, |g| { + if g.using.is_none() && (g.creative || g.projectile_slot("minecraft:bow").is_some()) + { + g.using = Some((g.held_slot(), 0)); + } + }); + } item_has_use(&info) } @@ -3382,14 +3448,20 @@ impl Game<'_> { } self.remote_use_item(Hand::Off); } - /// `LivingEntity.updatingUsingItem` for a consumable on a server client: the - /// eating animation and its crumbs. The server eats it and sends the - /// stack, the hunger and the sounds. + /// `LivingEntity.updatingUsingItem` on a server client: a drawn bow, and a + /// consumable's eating animation and its crumbs. The server eats it and + /// sends the stack, the hunger and the sounds. fn remote_tick_using(&mut self) { let Some((slot, ticks)) = self.using else { return; }; let stack = self.stack_in(slot).cloned(); + // A drawn bow: held until the button lets go (or another slot is picked). + if stack.as_ref().is_some_and(|s| &*s.item == "minecraft:bow") { + self.using = (slot == self.selected || slot == super::shield::OFFHAND_SLOT) + .then_some((slot, ticks + 1)); + return; + } let consumable = stack .as_ref() .and_then(|s| self.res.items().get(&s.item)) @@ -3499,7 +3571,18 @@ impl Game<'_> { return true; } let mut instant = false; - if let Some((i, distance)) = self.mob_hit() + // A ghast's fireball or a wind charge nearer than any mob: the + // server turns it (game/deflect.rs). + if let Some((i, distance)) = self.redirectable_hit() + && self.mob_hit().is_none_or(|(_, d)| distance <= d) + && self.before_block(distance) + && self.creatures.projectiles[i].id != 0 + { + self.send(S::Attack(play::Attack { + id: self.creatures.projectiles[i].id as i32, + })); + self.reset_attack_strength(); + } else if let Some((i, distance)) = self.mob_hit() && self.before_block(distance) { self.send(S::Attack(play::Attack { @@ -4247,9 +4330,45 @@ struct DryLevel<'w> { world: &'w horizon_client::world::World, changed: HashMap, random: horizon_core::random::LegacyRandom, + /// The sounds the use plays (a door's creak). + sounds: Vec, +} + +type DrySound = ( + horizon_core::position::BlockPos, + std::sync::Arc, + f32, + f32, +); +/// What a use on the dry level changed, and the sounds it played. +type DryUse = ( + Vec<(horizon_core::position::BlockPos, BlockStateId)>, + Vec, +); + +/// The blocks a guest's hand flips that its use predicts (and hears at once): a wooden or +/// copper door, trapdoor or fence gate, a lever or a button. An iron door or trapdoor has +/// no hand use. +pub(super) fn hand_operated(name: &str) -> bool { + let name = name.trim_start_matches("minecraft:"); + ((name.ends_with("_door") || name.ends_with("_trapdoor")) && !name.starts_with("iron_")) + || name.ends_with("_fence_gate") + || name.ends_with("_button") + || name == "lever" } impl horizon_world::level::LevelAccess for DryLevel<'_> { + fn emit(&mut self, event: horizon_world::level::LevelEvent) { + if let horizon_world::level::LevelEvent::Sound { + pos, + sound, + volume, + pitch, + } = event + { + self.sounds.push((pos, sound, volume, pitch)); + } + } fn block_state(&self, pos: horizon_core::position::BlockPos) -> BlockStateId { self.changed .get(&pos) diff --git a/crates/horizon-client/src/game/sculk_fixture.rs b/crates/horizon-client/src/game/sculk_fixture.rs index 890e571b8..d71cd5431 100644 --- a/crates/horizon-client/src/game/sculk_fixture.rs +++ b/crates/horizon-client/src/game/sculk_fixture.rs @@ -665,7 +665,7 @@ impl Game<'_> { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { m.damage(amount, horizon_client::mobs::Damage::player(at)); } - self.last_hurt_by_player.insert(id); + self.last_hurt_by_player.insert(id, self.lan_acting); } "set" => { let n = |i: usize| words[i].parse::().unwrap_or(0); diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs index 355b5b877..72e6ee0e8 100644 --- a/crates/horizon-client/src/game/wind.rs +++ b/crates/horizon-client/src/game/wind.rs @@ -131,7 +131,7 @@ impl Game<'_> { m.damage(1.0, source); } if p.owner == Some(Who::Player) { - self.last_hurt_by_player.insert(id); + self.last_hurt_by_player.insert(id, self.lan_acting); } } } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index c8155984c..28bcadeed 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1623,13 +1623,18 @@ impl Mob { if !self.alive() || self.removed || self.invulnerable_flag { return false; } - if source.is_fire() && (self.kind.flags.fire_immune) { + // Ghast.isReflectedFireball: a fireball a player turned back is + // no fire to it, and kills it (Ghast.hurtServer: 1000 damage). + let reflected = &*self.kind.id == "minecraft:ghast" + && source.kind == DamageKind::Fireball + && source.attacker == Some(Who::Player); + if source.is_fire() && (self.kind.flags.fire_immune) && !reflected { return false; } if !ai::accepts_damage(self, &source, amount) { return false; } - let mut amount = amount; + let mut amount = if reflected { 1000.0 } else { amount }; if source.kind == DamageKind::FallingBlock && !species::body_slot(self.species()) && self.extra.head.is_some() diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 34276ddda..ae4aa91a6 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -1240,10 +1240,10 @@ pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 { 0.0 }; } - // AbstractNautilus and Creaking.getWalkTargetValue: everywhere alike. + // AbstractNautilus, Axolotl and Creaking.getWalkTargetValue: everywhere alike. if matches!( m.species(), - Species::Nautilus | Species::ZombieNautilus | Species::Creaking + Species::Nautilus | Species::ZombieNautilus | Species::Axolotl | Species::Creaking ) { return 0.0; } @@ -1406,6 +1406,12 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { if super::creaking::is_creaking(m) { m.voice("entity.creaking.attack", cx.events); } + // Axolotl.playAttackSound: playSound(AXOLOTL_ATTACK, 1.0, 1.0). + if m.species() == Species::Axolotl { + let at = [m.position.x, m.position.y, m.position.z]; + cx.events + .push(MobEvent::Sound("entity.axolotl.attack", at, 1.0, 1.0)); + } let _ = Fluid::None; } /// Mob.ate (sheep regrow wool, babies grow). diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index 702e3740d..6afacb53a 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -46,6 +46,9 @@ pub fn register(m: &mut Mob) { }; m.ai.look.kind = super::control::LookKind::SmoothSwimming(20.0); m.ai.nav.kind = NavKind::Amphibious; + // `Axolotl()`: water costs nothing, so swim targets in water pass + // DefaultRandomPos's malus check. + m.set_malus(super::path::PathType::Water, 0.0); super::animal_brain::init(m, i64::from(m.id)); } S::Tadpole => { diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index b25915085..7bdaea785 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -2152,6 +2152,68 @@ mod tests { assert!(player.position.y < 84.0); } + /// `MovingPistonBlock.getCollisionShape`: a block halfway through a push + /// up is solid at its moving position, so a player lands on it. + #[test] + fn a_player_lands_on_a_block_a_piston_is_moving() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let mut scene = World::test_scene(&assets, &render, 1).unwrap(); + let registry = assets.registry; + let moving = registry.default_state("minecraft:moving_piston").unwrap(); + let stone = registry.default_state("minecraft:stone").unwrap(); + scene.set(20, 4, 20, moving).unwrap(); + scene.moving_pistons.push(( + [20, 4, 20], + horizon_world::piston_shape::MovingPistonState { + moved_state: stone, + direction: horizon_core::geometry::Direction::Up, + extending: true, + source: false, + progress: 0.5, + previous_progress: 0.0, + }, + )); + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 6.0, 20.5)).unwrap(); + for _ in 0..30 { + MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + } + .controlled_simulation_tick(Default::default()) + .unwrap(); + } + assert!(player.ground.on_ground); + assert_eq!(player.position.y, 4.5); + // Once the block entity is gone, the moving_piston block has no shape. + scene.moving_pistons.clear(); + for _ in 0..10 { + MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + } + .controlled_simulation_tick(Default::default()) + .unwrap(); + } + assert_eq!(player.position.y, 4.0); + } + #[test] fn spectator_scroll_speed_controls_horizontal_and_vertical_flight() { let root = Path::new(env!("CARGO_MANIFEST_DIR")) diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 29bf5b030..55a7a5120 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -73,6 +73,7 @@ particle_types! { Splash = "splash", Rain = "rain", Bubble = "bubble", + SulfurBubbles = "sulfur_bubbles", BubblePop = "bubble_pop", BubbleColumnUp = "bubble_column_up", CurrentDown = "current_down", @@ -352,6 +353,14 @@ enum Behaviour { }, WaterDrop, Bubble, + /// `SulfurBubbleParticle`: rises three blocks through still water, + /// growing to 0.15. + SulfurBubble { + y_start: f64, + y_end: f64, + size_start: f32, + y_prev: f64, + }, BubblePop, BubbleColumnUp, CurrentDown { @@ -1099,6 +1108,11 @@ impl ParticleLevel<'_> { }; (s.fluid, height) } + /// The fluid at a block and whether it is a source (`FluidState.isSource`). + fn fluid_source(&self, b: [i32; 3]) -> (Fluid, bool) { + let s = self.facts.get(self.world.block(b[0], b[1], b[2])); + (s.fluid, s.fluid_level == 8 && !s.fluid_falling) + } /// `getCollisionShape(...).max(Y, x, z)` for cached shapes. fn collision_top(&self, b: [i32; 3], fx: f64, fz: f64) -> f64 { let state = self.world.block(b[0], b[1], b[2]); @@ -1933,6 +1947,27 @@ impl ParticleEngine { } q } + T::SulfurBubbles => { + let mut q = Particle::at(r, ty, p); + q.gravity = -0.04; + q.friction = 0.85; + q.set_size(0.02, 0.02); + q.velocity[0] = + v[0] * f64::from(0.2f32) + f64::from((r.next_float() * 2.0 - 1.0) * 0.02); + // The provider passes `yAux` as `za`, so the Z speed comes from Y. + q.velocity[2] = + v[1] * f64::from(0.2f32) + f64::from((r.next_float() * 2.0 - 1.0) * 0.02); + let size_start = 0.02 + 0.02 * r.next_float(); + q.size = size_start; + q.lifetime = i32::MAX; + q.behaviour = Behaviour::SulfurBubble { + y_start: p[1], + y_end: p[1] + 4.0 - 1.0, + size_start, + y_prev: p[1], + }; + q + } T::BubblePop => { let mut q = Particle::at(r, ty, p); q.lifetime = 4; @@ -3172,6 +3207,40 @@ impl ParticleEngine { p.removed = true; } } + Behaviour::SulfurBubble { + y_start, + y_end, + size_start, + y_prev, + } => { + p.base_tick(level); + let (fluid, source) = level.fluid_source(ParticleLevel::block_at(p.position)); + if !p.removed && !(fluid == Fluid::Water && source) { + p.removed = true; + } + if !p.removed && p.position[1] >= y_end { + p.removed = true; + } + if !p.removed && p.position[1] <= y_prev { + p.removed = true; + } + // randomHorizontalWiggling, then a second, horizontal move. + let wiggle = |r: &mut LegacyRandom| { + let f = r.next_float() * 0.003; + f64::from(if r.next_boolean() { f } else { -f }) * 0.5 + }; + p.velocity[0] += wiggle(&mut p.random); + p.velocity[2] += wiggle(&mut p.random); + p.move_by(level, [p.velocity[0], 0.0, p.velocity[2]]); + let progress = ((p.position[1] - y_start) / (y_end - y_start)) as f32; + p.size = size_start + progress * (0.15 - size_start); + p.behaviour = Behaviour::SulfurBubble { + y_start, + y_end, + size_start, + y_prev: p.position[1], + }; + } Behaviour::BubbleColumnUp => { p.base_tick(level); if !p.removed && level.fluid(ParticleLevel::block_at(p.position)).0 != Fluid::Water diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index cc44e7511..093482a08 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -689,6 +689,19 @@ impl Projectile { } damage as f32 } + /// The item a thrown potion is drawn as (`ThrownItemRenderer`): the + /// splash potion `Witch.performRangedAttack` makes for the effect. + pub fn potion_item(&self) -> Option { + let ProjectileKind::Potion { effect, .. } = self.kind else { + return None; + }; + let potion = match effect { + "minecraft:instant_health" => "minecraft:healing", + "minecraft:instant_damage" => "minecraft:harming", + other => other, + }; + Some(crate::items::ItemStack::new("minecraft:splash_potion", 1).with_potion(potion)) + } /// The item sprite drawn for thrown projectiles (ThrownItemRenderer). pub fn item_sprite(&self) -> Option<&'static str> { Some(match self.kind { diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 34b945626..1fadacf57 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -48,7 +48,10 @@ pub fn sound_source(event: &str) -> usize { "zombified_piglin", "wither_skeleton", ]; - if e.starts_with("music_disc.") { + if e == "block.potent_sulfur.noxious_gas" { + // PotentSulfurBlock.animateTick, its only caller, plays it as AMBIENT. + index("ambient") + } else if e.starts_with("music_disc.") { index("record") } else if e.starts_with("music.") { index("music") diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index 4a80a7fcd..3b2920ade 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -93,6 +93,9 @@ pub struct World { pub light_log: Option>, /// The villager POIs of each section (`PoiManager`'s sections). pub pois: crate::poi_sections::PoiSections, + /// The moving-piston block entities of the level, by position, copied + /// from the block ticks after each tick: collision and rendering read them. + pub moving_pistons: Vec<([i32; 3], horizon_world::piston_shape::MovingPistonState)>, } /// ServerLevel weather state (advanceWeatherCycle). #[derive(Clone, Copy, Debug, Default)] @@ -178,6 +181,7 @@ impl World { weather: Weather::default(), block_log: None, light_log: None, + moving_pistons: Vec::new(), pois: Default::default(), } } diff --git a/crates/horizon-world/src/block_collision.rs b/crates/horizon-world/src/block_collision.rs index b84db5def..3770a1a0f 100644 --- a/crates/horizon-world/src/block_collision.rs +++ b/crates/horizon-world/src/block_collision.rs @@ -6,6 +6,7 @@ use crate::{ collision_context::CollisionContext, dynamic_support::{DynamicSupport, DynamicSupportError, DynamicSupportWorld}, liquid_collision::{LiquidCollision, LiquidCollisionWorld}, + piston_shape::PistonBlockBindings, powder_snow_collision::{PowderSnowWorld, powder_snow_collision_shape}, registry::{BlockRegistry, BlockStateId}, }; @@ -79,6 +80,9 @@ pub struct BlockCollisionRegistry<'r> { dynamic: HashMap, contextual: HashMap, scan_flags: Vec, + /// Piston and piston-head states for moving-piston collision; None in + /// registries without pistons. + pistons: Option>, } enum ContextualRule { Scaffolding(ScaffoldingCollision), @@ -122,16 +126,22 @@ impl<'r> BlockCollisionRegistry<'r> { } } } + let pistons = PistonBlockBindings::new(cached.registry()).ok(); Ok(Self { cached, dynamic, contextual, scan_flags, + pistons, }) } pub fn registry(&self) -> &'r BlockRegistry { self.cached.registry() } + /// The piston states behind `PistonMovingBlockEntity.getCollisionShape`. + pub fn pistons(&self) -> Option<&PistonBlockBindings<'r>> { + self.pistons.as_ref() + } pub fn cached_shapes(&self) -> &CachedCollisionRegistry<'r> { &self.cached } diff --git a/crates/horizon-world/src/level/pistons.rs b/crates/horizon-world/src/level/pistons.rs index fa5b7989c..648d6d543 100644 --- a/crates/horizon-world/src/level/pistons.rs +++ b/crates/horizon-world/src/level/pistons.rs @@ -31,6 +31,17 @@ pub struct MovingPiston { pub id: u64, } impl MovingPiston { + /// What collision and rendering need from this block entity. + pub fn shape_state(&self) -> crate::piston_shape::MovingPistonState { + crate::piston_shape::MovingPistonState { + moved_state: self.moved_state, + direction: self.direction, + extending: self.extending, + source: self.source, + progress: self.progress, + previous_progress: self.progress_o, + } + } pub fn movement_direction(&self) -> Direction { if self.extending { self.direction diff --git a/docs/mod-browser.md b/docs/mod-browser.md new file mode 100644 index 000000000..115877075 --- /dev/null +++ b/docs/mod-browser.md @@ -0,0 +1,89 @@ +# The launcher's mod browser + +Search Modrinth (and CurseForge, once the launcher has a key) for packs Horizon loads, see how well each one runs, +and install it with its checksum checked. This is item 16 of the roadmap and issue #577. The code is in +`launcher/src/browser.rs` and `launcher/src/browser/`. + +## What it offers + +Only what Horizon actually loads is offered. Java mod jars (Fabric, NeoForge, Forge) don't run in Horizon +([mods.md](mods.md), [research/java-mod-compat.md](research/java-mod-compat.md)), so they are never searched. +Horizon `.hmod` mods aren't on Modrinth or CurseForge yet (Modrinth has no `horizon` loader). + +| Kind | Goes to | How well it runs | +|---|---|---| +| Resource packs | `resourcepacks/` beside `options.txt` | **Works** when made for 26.3 ([resource-packs.md](resource-packs.md) lists what Horizon reads). Older packs are **Partly**: they load with vanilla's compatibility warning | +| Shader packs (Iris, OptiFine) | `shaderpacks/` | **Partly**: translated to WGSL, the full-screen passes draw and the world and shadow passes don't yet ([shader-packs.md](shader-packs.md)). Packs for other loaders (Canvas, core-shader packs) **don't run** and can't be installed | +| Modpacks (`.mrpack`, CurseForge zip) | the Modpacks page's import | **Partly**: Horizon runs the mods it can port, from the player's own downloads ([modpacks.md](modpacks.md)) | + +By default a search shows only what runs: resource packs made for 26.3, shader packs for Iris or OptiFine, and every +modpack. **Show everything** lists the rest of the kind too, each marked with how well it runs; what doesn't run is +never offered for install. + +## Checks on every download + +- The file must come from Modrinth's or CurseForge's file servers (`cdn.modrinth.com`, `edge.forgecdn.net`, + `mediafilez.forgecdn.net`), over HTTPS. +- Its name must be one plain file name (no folders, `..`, hidden names or reserved characters). +- It is written as `..part`, hashed as it arrives, and renamed into place only when its size and checksum match + what the source lists: SHA-512 on Modrinth, SHA-1 on CurseForge (the strongest hash CurseForge publishes). Anything + else removes the part file and installs nothing. +- A file whose source lists no checksum is refused. + +## The Mods page + +The launcher's **Mods** page has the three kinds as tabs, a search field (Enter searches), **Show everything** and, +once CurseForge is set up, a Modrinth / CurseForge switch. Each result is an index row: its summary, author, +downloads, source and licence, how well it runs (and why), **Page** (the project's page on its source) and +**Install** (**Import** for a modpack). Installed packs are listed above the results with their version, source, +file and the checksum they were checked against, with **Update to …** when a newer version runs and **Remove** +(asked twice). + +## Installing, updating, removing + +`mod-browser.json` beside `options.txt` lists every file the browser installed: its source, project, version, file +and the checksum it was checked against. The browser replaces or removes only the files it lists; a file of the +same name the player put there is never overwritten. + +- **Install** picks the newest version that runs, then its required dependencies, checked before any download: a + dependency that isn't a pack Horizon loads (a Java mod) stops the install. Dependencies go in first. A resource + pack still has to be turned on in the game's Resource Packs screen, and a shader pack in Video Settings > Shader + Packs, as in vanilla and Iris. +- **Update** installs the newer version and removes the old file. +- **Remove** deletes the file and its entry. Packs installed as dependencies stay. +- **A modpack** is downloaded (checked the same way) into `ports/downloads/` and imported on the Modpacks page, + which says what of it Horizon runs and ports it. + +From a terminal (or an agent): + +```sh +horizon-launcher mods search faithful # --kind resource|shader|modpack, --everything, --source +horizon-launcher mods install faithful-32x # id or slug; a modpack is imported +horizon-launcher mods list # --json +horizon-launcher mods update [faithful-32x] [--check] +horizon-launcher mods remove faithful-32x +``` + +## Sources + +**Modrinth.** The public API (`api.modrinth.com/v2`) needs no key. The launcher names itself in its user agent, as +Modrinth asks. + +### CurseForge + +CurseForge's API (`api.curseforge.com/v1`) needs an API key from its developer console. Ludovic approved CurseForge +for the browser on 2026-10-21; the key is his (agents never sign up for him). Until a key exists the CurseForge source +is off and the browser searches Modrinth only. + +To turn it on: + +1. Ludovic gets a key at (sign in, API keys). CurseForge's terms for a launcher + that ships the key apply: the key is built into the binary, so anyone with the binary can read it. +2. He stores it in the 1Password **Agents** vault as an item `CurseForge API`, field `credential`. +3. It goes into the repository secret `HORIZON_CURSEFORGE_API_KEY` + (`~/fleet/op read "op://Agents/CurseForge API/credential" | gh secret set HORIZON_CURSEFORGE_API_KEY`). + The launcher workflow passes it to the build, which builds it in (`option_env!`). + +At run time `HORIZON_CURSEFORGE_API_KEY` in the environment overrides the built-in key; empty means none. A file +whose author allows downloads from CurseForge's own site only (no `downloadUrl` in the API) is shown but can't be +installed. diff --git a/docs/mods.md b/docs/mods.md index 346ce0783..9a643198e 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -17,7 +17,8 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | Runtime | `crates/horizon-mods` | wasmtime 36 LTS, component model | | Authoring tool | `crates/cargo-horizon-mod` | `cargo horizon-mod new / build / run` | | In the game | `crates/horizon-client/src/game/mods.rs`, Options > Mods | client mods | -| Launcher mod browser, signing, server mods, registries | this page, [Roadmap](#roadmap) | planned | +| Launcher mod browser (Modrinth, CurseForge with a key) | [mod-browser.md](mod-browser.md) | resource packs, shader packs, modpacks | +| `.hmod` index, signing, server mods, registries | this page, [Roadmap](#roadmap) | planned | ## Design goals diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index b48a90543..0e866fe19 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -2685,6 +2685,7 @@ dependencies = [ "serde", "serde_json", "sha1", + "sha2 0.10.9", "tar", "ureq", "winresource", diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index d6225cb96..1097d5675 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -14,6 +14,8 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" # Checks the client jar and the version file found in other launchers' folders (sources.rs). sha1 = "0.10" +# The mod browser checks Modrinth's SHA-512 before a pack reaches the game folder (browser/download.rs). +sha2 = "0.10" pulldown-cmark = { version = "0.12", default-features = false } flate2 = "1" tar = { version = "0.4", default-features = false } diff --git a/launcher/README.md b/launcher/README.md index d6168dbb4..74054ea55 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -24,6 +24,12 @@ The opening, then Play ([clip](docs/opening.webm)): preparation reuses checksum-verified game jars and libraries from the current or another installed Horizon version, so the original Minecraft install is only required when no valid imported copy exists. +- **Mods**: search Modrinth (and CurseForge once the launcher has its API key) for resource + packs, Iris/OptiFine shader packs and modpacks, each marked Works, Partly or Doesn't run in + Horizon; Java mod jars are never offered. Install puts a pack and what it needs in + `resourcepacks/` or `shaderpacks/` only after its SHA-512 (SHA-1 on CurseForge) matches, and a + modpack goes to the Modpacks page; installed packs show their source and checksum, with Update + and Remove ([docs/mod-browser.md](../docs/mod-browser.md)). - **Modpacks**: import a Java modpack (a Modrinth `.mrpack`, a CurseForge zip, or a Prism, MultiMC or CurseForge instance folder) and see its coverage report: per mod, ported, partial, not yet or not needed, with the reason ([docs/modpacks.md](../docs/modpacks.md)). **Port** @@ -139,6 +145,11 @@ The same binary is a command-line tool; without a subcommand it opens the window horizon-launcher modpack port [--from ] [--version ] get the jars and carry them over horizon-launcher modpack play [--version ] play it as its own profile horizon-launcher modpack remove + horizon-launcher mods [list] what the mod browser installed (docs/mod-browser.md) + horizon-launcher mods search [--kind resource|shader|modpack] [--everything] [--source modrinth|curseforge] + horizon-launcher mods install checksum checked, with what it needs; a modpack is imported + horizon-launcher mods update [] [--check] + horizon-launcher mods remove horizon-launcher servers [list] the servers hosted from the launcher, and whether they run horizon-launcher servers create [--name N] [--seed S | --copy-world DIR] [--mode M] [--difficulty D] [--max-players N] [--open] [--check-accounts] [--player NAME]... --accept-eula diff --git a/launcher/src/browser.rs b/launcher/src/browser.rs new file mode 100644 index 000000000..49ec1e696 --- /dev/null +++ b/launcher/src/browser.rs @@ -0,0 +1,315 @@ +//! The mod browser's sources: search Modrinth (and CurseForge, once a key exists) for what +//! Horizon loads, say how well each result runs, and download a file only after its checksum +//! matches (docs/mod-browser.md). +//! +//! Only what Horizon actually loads is offered: resource packs (`resourcepacks/`), Java shader +//! packs (`shaderpacks/`, Iris and OptiFine) and modpacks (imported and ported on the Modpacks +//! page). Java mod jars don't run in Horizon (docs/mods.md), so they are never searched. +pub mod curseforge; +pub mod download; +pub mod installed; +pub mod modrinth; + +use serde::{Deserialize, Serialize}; + +/// The Minecraft version Horizon plays. A version port updates it with the other `"26.3"` sites +/// (docs/version-ports.md). +pub const GAME: &str = "26.3"; + +/// What a project is, as far as Horizon is concerned. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Kind { + ResourcePack, + ShaderPack, + Modpack, +} + +impl Kind { + pub const ALL: [Kind; 3] = [Kind::ResourcePack, Kind::ShaderPack, Kind::Modpack]; + + pub fn label(self) -> &'static str { + match self { + Kind::ResourcePack => "Resource packs", + Kind::ShaderPack => "Shader packs", + Kind::Modpack => "Modpacks", + } + } + + /// The folder beside `options.txt` the file goes in; a modpack is imported instead. + pub fn folder(self) -> Option<&'static str> { + match self { + Kind::ResourcePack => Some("resourcepacks"), + Kind::ShaderPack => Some("shaderpacks"), + Kind::Modpack => None, + } + } +} + +/// Where a project comes from. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum SourceId { + Modrinth, + CurseForge, +} + +impl SourceId { + pub fn label(self) -> &'static str { + match self { + SourceId::Modrinth => "Modrinth", + SourceId::CurseForge => "CurseForge", + } + } +} + +/// How well a project runs in Horizon. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Support { + /// Made for the version Horizon plays, and Horizon reads everything it uses. + Works, + /// It loads, with the limit said. + Partial(String), + /// It can't run in Horizon: never offered for install. + No(String), +} + +impl Support { + pub fn installable(&self) -> bool { + !matches!(self, Support::No(_)) + } + + pub fn label(&self) -> &'static str { + match self { + Support::Works => "Works", + Support::Partial(_) => "Partly", + Support::No(_) => "Doesn't run", + } + } + + pub fn reason(&self) -> Option<&str> { + match self { + Support::Works => None, + Support::Partial(r) | Support::No(r) => Some(r), + } + } +} + +/// A search result or a looked-up project. +#[derive(Clone, Debug, PartialEq)] +pub struct Project { + pub source: SourceId, + pub id: String, + pub slug: String, + pub title: String, + pub summary: String, + pub author: String, + pub downloads: u64, + /// The project's page on its source, for the player to read before installing. + pub page: String, + pub icon: Option, + pub license: String, + pub kind: Kind, + /// The Minecraft versions its files list, and the loaders (`iris`, `optifine`, `minecraft`...). + pub game_versions: Vec, + pub loaders: Vec, +} + +impl Project { + pub fn support(&self) -> Support { + support(self.kind, &self.game_versions, &self.loaders) + } +} + +/// One downloadable file of a version, with the checksums its source publishes. +#[derive(Clone, Debug, PartialEq)] +pub struct FileRef { + pub url: String, + pub name: String, + pub size: u64, + pub sha512: Option, + pub sha1: Option, + pub primary: bool, +} + +impl FileRef { + /// The strongest checksum the source gives: what the download is checked against. + pub fn checksum(&self) -> Option<(&'static str, &str)> { + match (&self.sha512, &self.sha1) { + (Some(h), _) => Some(("SHA-512", h)), + (None, Some(h)) => Some(("SHA-1", h)), + (None, None) => None, + } + } +} + +/// A version of a project: its files and what it needs. +#[derive(Clone, Debug, PartialEq)] +pub struct Version { + pub id: String, + pub number: String, + pub published: String, + pub game_versions: Vec, + pub loaders: Vec, + pub files: Vec, + /// Required dependencies, as project ids on the same source. + pub required: Vec, + /// Why this version can't be downloaded from here (CurseForge authors can forbid it). + pub blocked: Option, +} + +impl Version { + /// The file to install: the primary one, else the first. + pub fn file(&self) -> Option<&FileRef> { + self.files + .iter() + .find(|f| f.primary) + .or_else(|| self.files.first()) + } +} + +/// A search. +#[derive(Clone, Debug, PartialEq)] +pub struct Query { + pub text: String, + pub kind: Kind, + /// Off: only what runs (made for [`GAME`], Iris or OptiFine shaders). On: everything of the + /// kind, each result marked with how well it runs. + pub everything: bool, + pub offset: usize, + pub limit: usize, +} + +impl Query { + pub fn new(text: &str, kind: Kind) -> Self { + Self { + text: text.trim().to_owned(), + kind, + everything: false, + offset: 0, + limit: 20, + } + } +} + +/// A place projects come from. +pub trait Source: Send + Sync { + fn id(&self) -> SourceId; + fn search(&self, query: &Query) -> Result, String>; + fn project(&self, id: &str) -> Result; + /// Versions, newest first. + fn versions(&self, project: &Project) -> Result, String>; + /// Downloads one of its files into `folder`, checked ([`download::fetch`]). + fn fetch( + &self, + file: &FileRef, + folder: &std::path::Path, + progress: &dyn Fn(f32), + ) -> Result { + download::fetch(file, folder, progress) + } +} + +/// The sources this launcher can use: Modrinth always, CurseForge when it has an API key. +pub fn sources() -> Vec> { + let mut all: Vec> = vec![Box::new(modrinth::Modrinth)]; + if let Some(cf) = curseforge::CurseForge::from_env() { + all.push(Box::new(cf)); + } + all +} + +/// The source of that id, when this launcher can use it. +pub fn source(id: SourceId) -> Option> { + sources().into_iter().find(|s| s.id() == id) +} + +/// The loaders a Java shader pack may name that Horizon translates. +const SHADER_LOADERS: [&str; 2] = ["iris", "optifine"]; + +/// How well a project of `kind` made for `game_versions` and `loaders` runs in Horizon. +pub fn support(kind: Kind, game_versions: &[String], loaders: &[String]) -> Support { + match kind { + Kind::ResourcePack => { + if game_versions.iter().any(|v| v == GAME) { + Support::Works + } else if let Some(newest) = newest_release(game_versions) { + Support::Partial(format!( + "Made for {newest}: it loads with vanilla's compatibility warning, and \ + what changed since may look wrong." + )) + } else { + Support::Partial("Lists no Minecraft version.".into()) + } + } + Kind::ShaderPack => { + if loaders.iter().any(|l| SHADER_LOADERS.contains(&l.as_str())) { + Support::Partial( + "Java shader packs are translated: their full-screen passes draw, the world \ + and shadow passes don't yet (BSL and Complementary tested)." + .into(), + ) + } else { + let named = loaders.first().map(String::as_str).unwrap_or("unknown"); + Support::No(format!( + "A shader pack for {named}: Horizon runs Iris and OptiFine packs only." + )) + } + } + Kind::Modpack => Support::Partial( + "Imported on the Modpacks page: Horizon runs the mods it can port, from your own \ + downloads." + .into(), + ), + } +} + +/// The newest plain release (`1.21.4`, `26.2`) in a list of Minecraft versions. +fn newest_release(versions: &[String]) -> Option<&str> { + versions + .iter() + .filter(|v| { + v.split('.') + .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) + }) + .max_by_key(|v| { + v.split('.') + .map(|p| p.parse::().unwrap_or(0)) + .collect::>() + }) + .map(String::as_str) +} + +/// The version to install: the newest one that runs, or with `everything` the newest at all. +/// `versions` is newest first, as [`Source::versions`] gives them. +pub fn pick(kind: Kind, versions: &[Version], everything: bool) -> Option<&Version> { + let mut usable = versions + .iter() + .filter(|v| v.blocked.is_none() && v.file().is_some()); + let runs = |v: &&Version| match support(kind, &v.game_versions, &v.loaders) { + Support::Works => true, + // A modpack's version is for its own Minecraft; any shader pack Horizon translates. + Support::Partial(_) => kind != Kind::ResourcePack, + Support::No(_) => false, + }; + if let Some(v) = usable.clone().find(runs) { + return Some(v); + } + usable.find(|v| everything && support(kind, &v.game_versions, &v.loaders).installable()) +} + +/// A file name from a source, kept only when it is one plain name: no folders, no `..`, no +/// hidden file, nothing a file system would read as something else. +pub fn safe_name(name: &str) -> Option<&str> { + let ok = !name.is_empty() + && name.len() <= 200 + && !name.starts_with('.') + && !name.ends_with(['.', ' ']) + && name.chars().all(|c| { + !c.is_control() && !matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') + }); + ok.then_some(name) +} + +#[cfg(test)] +mod tests; diff --git a/launcher/src/browser/curseforge.rs b/launcher/src/browser/curseforge.rs new file mode 100644 index 000000000..347cf0d40 --- /dev/null +++ b/launcher/src/browser/curseforge.rs @@ -0,0 +1,237 @@ +//! CurseForge's API (api.curseforge.com/v1). It needs a key from CurseForge's developer console, +//! so this source stays off until one is given (docs/mod-browser.md#curseforge): +//! `HORIZON_CURSEFORGE_API_KEY` in the environment, else the same variable when the launcher was +//! built (the release workflow passes the repository secret). Files carry SHA-1 and MD5; the +//! download is checked against the SHA-1. +use super::{modrinth::encode, FileRef, Kind, Project, Query, Source, SourceId, Version, GAME}; +use serde_json::Value; + +const API: &str = "https://api.curseforge.com/v1"; +/// Minecraft's game id on CurseForge. +const MINECRAFT: u64 = 432; +/// `HashAlgo` in CurseForge's schema. +const SHA1: u64 = 1; +/// `FileRelationType::RequiredDependency`. +const REQUIRED: u64 = 3; + +pub struct CurseForge { + key: String, +} + +/// CurseForge's class id for a kind. +fn class(kind: Kind) -> u64 { + match kind { + Kind::ResourcePack => 12, + Kind::ShaderPack => 6552, + Kind::Modpack => 4471, + } +} + +fn kind_of(class_id: u64) -> Option { + Kind::ALL.into_iter().find(|k| class(*k) == class_id) +} + +/// The key: the environment's, else the one built in. Empty counts as none. +pub(super) fn key(runtime: Option, built: Option<&str>) -> Option { + runtime + .or_else(|| built.map(str::to_owned)) + .map(|k| k.trim().to_owned()) + .filter(|k| !k.is_empty()) +} + +impl CurseForge { + /// The source, when a key exists; else None and CurseForge isn't offered. + pub fn from_env() -> Option { + key( + std::env::var("HORIZON_CURSEFORGE_API_KEY").ok(), + option_env!("HORIZON_CURSEFORGE_API_KEY"), + ) + .map(|key| Self { key }) + } + + fn get(&self, url: &str) -> Result { + let response = super::download::agent() + .get(url) + .set("x-api-key", &self.key) + .set("Accept", "application/json") + .call() + .map_err(|e| match e { + ureq::Error::Status(403, _) => "CurseForge refused the launcher's API key.".into(), + ureq::Error::Status(code, _) => format!("CurseForge answered {code}."), + ureq::Error::Transport(t) => format!("No connection to CurseForge: {t}"), + })?; + response + .into_json() + .map_err(|e| format!("CurseForge's answer wasn't readable: {e}")) + } +} + +pub(super) fn search_url(query: &Query) -> String { + let mut url = format!( + "{API}/mods/search?gameId={MINECRAFT}&classId={}&sortField=2&sortOrder=desc&index={}&pageSize={}", + class(query.kind), + query.offset, + query.limit.clamp(1, 50), + ); + if !query.everything && query.kind == Kind::ResourcePack { + url.push_str(&format!("&gameVersion={GAME}")); + } + if !query.text.is_empty() { + url.push_str("&searchFilter="); + url.push_str(&encode(&query.text)); + } + url +} + +/// CurseForge mixes Minecraft versions and loader names (`Iris`, `OptiFine`, `NeoForge`) in one +/// list: digits first is a version, the rest are loaders, in lowercase as Modrinth names them. +fn split_versions(list: &Value) -> (Vec, Vec) { + let mut versions = Vec::new(); + let mut loaders = Vec::new(); + for v in list + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + { + if v.starts_with(|c: char| c.is_ascii_digit()) { + versions.push(v.to_owned()); + } else { + loaders.push(v.to_ascii_lowercase()); + } + } + versions.sort(); + versions.dedup(); + loaders.sort(); + loaders.dedup(); + (versions, loaders) +} + +pub(super) fn parse_mod(m: &Value) -> Option { + let kind = kind_of(m["classId"].as_u64()?)?; + let latest = Value::Array( + m["latestFilesIndexes"] + .as_array() + .into_iter() + .flatten() + .filter_map(|i| i["gameVersion"].as_str()) + .map(|v| Value::String(v.to_owned())) + .collect(), + ); + let (game_versions, mut loaders) = split_versions(&latest); + // A shader pack's files name its loader; the index often doesn't. + if kind == Kind::ShaderPack && loaders.is_empty() { + let (_, own) = split_versions(&Value::Array( + m["latestFiles"] + .as_array() + .into_iter() + .flatten() + .flat_map(|f| f["gameVersions"].as_array().cloned().unwrap_or_default()) + .collect(), + )); + loaders = own; + } + Some(Project { + source: SourceId::CurseForge, + id: m["id"].as_u64()?.to_string(), + slug: m["slug"].as_str().unwrap_or_default().to_owned(), + title: m["name"].as_str().unwrap_or_default().to_owned(), + summary: m["summary"].as_str().unwrap_or_default().to_owned(), + author: m["authors"][0]["name"] + .as_str() + .unwrap_or_default() + .to_owned(), + downloads: m["downloadCount"].as_f64().unwrap_or(0.) as u64, + page: m["links"]["websiteUrl"] + .as_str() + .unwrap_or_default() + .to_owned(), + icon: m["logo"]["thumbnailUrl"].as_str().map(str::to_owned), + // CurseForge's API doesn't say; the project page does. + license: String::new(), + kind, + game_versions, + loaders, + }) +} + +pub(super) fn parse_file(f: &Value) -> Option { + let (game_versions, loaders) = split_versions(&f["gameVersions"]); + let name = f["fileName"].as_str()?.to_owned(); + let sha1 = f["hashes"] + .as_array() + .into_iter() + .flatten() + .find(|h| h["algo"].as_u64() == Some(SHA1)) + .and_then(|h| h["value"].as_str()) + .map(str::to_ascii_lowercase); + let url = f["downloadUrl"].as_str().filter(|u| !u.is_empty()); + let files = url + .map(|url| { + vec![FileRef { + url: url.to_owned(), + name: name.clone(), + size: f["fileLength"].as_u64().unwrap_or(0), + sha512: None, + sha1, + primary: true, + }] + }) + .unwrap_or_default(); + Some(Version { + id: f["id"].as_u64()?.to_string(), + number: f["displayName"].as_str().unwrap_or(&name).to_owned(), + published: f["fileDate"].as_str().unwrap_or_default().to_owned(), + game_versions, + loaders, + files, + required: f["dependencies"] + .as_array() + .into_iter() + .flatten() + .filter(|d| d["relationType"].as_u64() == Some(REQUIRED)) + .filter_map(|d| d["modId"].as_u64().map(|id| id.to_string())) + .collect(), + blocked: url + .is_none() + .then(|| "Its author allows downloads from CurseForge's own site only.".to_owned()), + }) +} + +impl Source for CurseForge { + fn id(&self) -> SourceId { + SourceId::CurseForge + } + + fn search(&self, query: &Query) -> Result, String> { + let found = self.get(&search_url(query))?; + Ok(found["data"] + .as_array() + .into_iter() + .flatten() + .filter_map(parse_mod) + .collect()) + } + + fn project(&self, id: &str) -> Result { + let m = self.get(&format!("{API}/mods/{}", encode(id)))?; + parse_mod(&m["data"]) + .ok_or_else(|| format!("CurseForge: {id} is not a pack Horizon loads.")) + } + + fn versions(&self, project: &Project) -> Result, String> { + let found = self.get(&format!( + "{API}/mods/{}/files?pageSize=50", + encode(&project.id) + ))?; + let mut all: Vec = found["data"] + .as_array() + .into_iter() + .flatten() + .filter(|f| f["isAvailable"].as_bool() != Some(false)) + .filter_map(parse_file) + .collect(); + all.sort_by(|a, b| b.published.cmp(&a.published)); + Ok(all) + } +} diff --git a/launcher/src/browser/download.rs b/launcher/src/browser/download.rs new file mode 100644 index 000000000..66199fd07 --- /dev/null +++ b/launcher/src/browser/download.rs @@ -0,0 +1,144 @@ +//! Downloads that reach the game folder only when their checksum matches the source's. +use super::{safe_name, FileRef}; +use sha1::Sha1; +use sha2::{Digest, Sha512}; +use std::fs; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; + +/// Hosts a file may come from: Modrinth's and CurseForge's file servers. +const HOSTS: [&str; 3] = [ + "https://cdn.modrinth.com/", + "https://edge.forgecdn.net/", + "https://mediafilez.forgecdn.net/", +]; +/// Bigger than any pack these sources serve (Modrinth caps uploads at 500 MiB). +const MAX: u64 = 1 << 30; + +/// The HTTP agent the sources share. Modrinth asks for a user agent that names the project. +pub(super) fn agent() -> ureq::Agent { + ureq::AgentBuilder::new() + .user_agent(&format!( + "ludovic111/horizon horizon-launcher/{} (github.com/ludovic111/horizon)", + crate::backend::VERSION + )) + .timeout_connect(std::time::Duration::from_secs(15)) + .timeout_read(std::time::Duration::from_secs(60)) + .build() +} + +/// Why a file can't be downloaded at all, before any byte is read. +pub fn refuse(file: &FileRef) -> Option { + if !HOSTS.iter().any(|h| file.url.starts_with(h)) { + return Some(format!( + "{} isn't on Modrinth's or CurseForge's file servers.", + file.url + )); + } + if safe_name(&file.name).is_none() { + return Some(format!("{:?} isn't a plain file name.", file.name)); + } + if file.checksum().is_none() { + return Some("Its source gives no checksum, so it can't be checked.".into()); + } + if file.size > MAX { + return Some("It is larger than any pack should be.".into()); + } + None +} + +/// Hashes as they are written: the strongest one the file lists. +enum Hasher { + Sha512(Sha512), + Sha1(Sha1), +} + +impl Hasher { + fn for_file(file: &FileRef) -> Self { + if file.sha512.is_some() { + Hasher::Sha512(Sha512::new()) + } else { + Hasher::Sha1(Sha1::new()) + } + } + fn update(&mut self, bytes: &[u8]) { + match self { + Hasher::Sha512(h) => h.update(bytes), + Hasher::Sha1(h) => h.update(bytes), + } + } + fn hex(self) -> String { + let bytes: Vec = match self { + Hasher::Sha512(h) => h.finalize().to_vec(), + Hasher::Sha1(h) => h.finalize().to_vec(), + }; + bytes.iter().map(|b| format!("{b:02x}")).collect() + } +} + +/// Copies `reader` into `/`, hashing on the way, and keeps it only when the +/// size and checksum match: until then it is `..part`, removed on any failure. +/// `progress` gets the fraction done. +pub fn save( + file: &FileRef, + mut reader: impl Read, + folder: &Path, + progress: &dyn Fn(f32), +) -> Result { + if let Some(why) = refuse(file) { + return Err(why); + } + let (algo, want) = file.checksum().expect("refuse checks for one"); + fs::create_dir_all(folder).map_err(|e| format!("{}: {e}", folder.display()))?; + let target = folder.join(&file.name); + let part = folder.join(format!(".{}.part", file.name)); + let result = (|| { + let mut out = fs::File::create(&part).map_err(|e| format!("{}: {e}", part.display()))?; + let mut hasher = Hasher::for_file(file); + let (mut done, mut buf) = (0u64, vec![0u8; 1 << 16]); + loop { + let n = reader + .read(&mut buf) + .map_err(|e| format!("Download interrupted: {e}"))?; + if n == 0 { + break; + } + done += n as u64; + if done > MAX || (file.size > 0 && done > file.size) { + return Err("The download is larger than its source says.".to_string()); + } + hasher.update(&buf[..n]); + out.write_all(&buf[..n]).map_err(|e| e.to_string())?; + progress(done as f32 / file.size.max(1) as f32); + } + if file.size > 0 && done != file.size { + return Err(format!("Got {done} bytes of {}.", file.size)); + } + let got = hasher.hex(); + if !got.eq_ignore_ascii_case(want) { + return Err(format!( + "The {algo} checksum doesn't match: the file isn't the one its source lists. \ + Nothing was installed." + )); + } + out.sync_all().map_err(|e| e.to_string())?; + drop(out); + fs::rename(&part, &target).map_err(|e| format!("{}: {e}", target.display())) + })(); + if result.is_err() { + let _ = fs::remove_file(&part); + } + result.map(|()| target) +} + +/// Downloads `file` into `folder`, checked as [`save`] does. +pub fn fetch(file: &FileRef, folder: &Path, progress: &dyn Fn(f32)) -> Result { + if let Some(why) = refuse(file) { + return Err(why); + } + let response = agent().get(&file.url).call().map_err(|e| match e { + ureq::Error::Status(code, _) => format!("{} answered {code}.", file.url), + ureq::Error::Transport(t) => format!("No connection: {t}"), + })?; + save(file, response.into_reader(), folder, progress) +} diff --git a/launcher/src/browser/installed.rs b/launcher/src/browser/installed.rs new file mode 100644 index 000000000..d1aac1af5 --- /dev/null +++ b/launcher/src/browser/installed.rs @@ -0,0 +1,260 @@ +//! What the browser installed into the game folder, and installing, updating and removing it. +//! +//! `mod-browser.json` beside `options.txt` lists each file the browser put in `resourcepacks/` +//! or `shaderpacks/`: where it came from, its version and its checksum. Files the player put +//! there themselves are never touched: the browser only replaces or removes what it lists. +use super::{pick, safe_name, Kind, Project, Source, SourceId, Support, Version}; +use serde::{Deserialize, Serialize}; +use std::fs; +use std::path::{Path, PathBuf}; + +const MANIFEST: &str = "mod-browser.json"; +/// How deep required dependencies are followed. +const MAX_DEPTH: usize = 4; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Entry { + pub source: SourceId, + pub project: String, + pub slug: String, + pub title: String, + pub kind: Kind, + pub version: String, + pub number: String, + /// Relative to the game folder: `resourcepacks/`. + pub file: String, + /// The checksum the download was checked against: `SHA-512:`. + pub checksum: String, + pub page: String, + /// Installed because another pack needs it. + #[serde(default)] + pub dependency: bool, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct Installed { + pub entries: Vec, +} + +impl Installed { + pub fn load(home: &Path) -> Self { + fs::read_to_string(home.join(MANIFEST)) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default() + } + + pub fn save(&self, home: &Path) -> Result<(), String> { + let path = home.join(MANIFEST); + let part = home.join(format!(".{MANIFEST}.part")); + let text = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?; + fs::create_dir_all(home).map_err(|e| format!("{}: {e}", home.display()))?; + fs::write(&part, text).map_err(|e| format!("{}: {e}", part.display()))?; + fs::rename(&part, &path).map_err(|e| format!("{}: {e}", path.display())) + } + + pub fn find(&self, source: SourceId, project: &str) -> Option<&Entry> { + self.entries + .iter() + .find(|e| e.source == source && e.project == project) + } + + /// By project id or slug, as the CLI takes them. + pub fn lookup(&self, name: &str) -> Option<&Entry> { + self.entries + .iter() + .find(|e| e.project == name || e.slug == name) + } +} + +/// One file to install: the project, the version chosen and why it was pulled in. +#[derive(Clone, Debug)] +pub struct Step { + pub project: Project, + pub version: Version, + pub dependency: bool, +} + +/// What installing `project` takes, dependencies first, checked before any byte is downloaded: +/// every file runs in Horizon and has a version to install. +pub fn plan(source: &dyn Source, project: &Project, everything: bool) -> Result, String> { + if project.kind.folder().is_none() { + return Err(format!( + "{} is a modpack: it is imported on the Modpacks page.", + project.title + )); + } + let mut steps = Vec::new(); + add(source, project.clone(), everything, false, 0, &mut steps)?; + Ok(steps) +} + +fn add( + source: &dyn Source, + project: Project, + everything: bool, + dependency: bool, + depth: usize, + steps: &mut Vec, +) -> Result<(), String> { + if steps.iter().any(|s| s.project.id == project.id) { + return Ok(()); + } + if depth > MAX_DEPTH { + return Err(format!("{}'s dependencies go too deep.", project.title)); + } + if let Support::No(why) = project.support() { + return Err(format!("{} doesn't run in Horizon: {why}", project.title)); + } + let versions = source.versions(&project)?; + let Some(version) = pick(project.kind, &versions, everything).cloned() else { + return Err(match versions.iter().find_map(|v| v.blocked.clone()) { + Some(why) => format!("{} can't be installed from here: {why}", project.title), + None => format!("{} has no version Horizon runs.", project.title), + }); + }; + for id in &version.required { + let needed = source.project(id).map_err(|_| { + format!( + "{} needs {id} on {}, which isn't a pack Horizon loads (a Java mod?).", + project.title, + source.id().label() + ) + })?; + if needed.kind.folder().is_none() { + return Err(format!( + "{} needs the modpack {}.", + project.title, needed.title + )); + } + add(source, needed, everything, true, depth + 1, steps)?; + } + steps.push(Step { + project, + version, + dependency, + }); + Ok(()) +} + +/// Installs `project` (and what it needs) into the game folder `home`. A project already +/// installed is updated to the version chosen. `progress` gets a line per file and the fraction. +pub fn install( + source: &dyn Source, + project: &Project, + everything: bool, + home: &Path, + progress: &dyn Fn(&str, f32), +) -> Result, String> { + let steps = plan(source, project, everything)?; + let mut installed = Installed::load(home); + let mut done = Vec::new(); + for step in steps { + let p = &step.project; + let old = installed.find(p.source, &p.id).cloned(); + if old.as_ref().is_some_and(|o| o.version == step.version.id) { + done.push(old.expect("checked")); + continue; + } + let file = step + .version + .file() + .expect("pick keeps versions with a file"); + let folder_name = p.kind.folder().expect("plan keeps folder kinds"); + let name = safe_name(&file.name) + .ok_or_else(|| format!("{:?} isn't a plain file name.", file.name))?; + let relative = format!("{folder_name}/{name}"); + let owner = installed.entries.iter().find(|e| e.file == relative); + let ours = owner.is_some_and(|e| e.source == p.source && e.project == p.id); + if home.join(&relative).exists() && !ours { + return Err(match owner { + Some(e) => format!( + "{relative} belongs to {}, installed from the browser.", + e.title + ), + None => format!( + "{relative} is already there and wasn't installed by the browser: move it \ + away first, or keep it." + ), + }); + } + let line = format!("{} {}", p.title, step.version.number); + let path = source.fetch(file, &home.join(folder_name), &|f| progress(&line, f))?; + let (algo, hash) = file.checksum().expect("fetch checks for one"); + if let Some(old) = &old { + if old.file != relative { + let _ = fs::remove_file(home.join(&old.file)); + } + } + let entry = Entry { + source: p.source, + project: p.id.clone(), + slug: p.slug.clone(), + title: p.title.clone(), + kind: p.kind, + version: step.version.id.clone(), + number: step.version.number.clone(), + file: relative, + checksum: format!("{algo}:{hash}"), + page: p.page.clone(), + // Asked for by the player once: it stays theirs. + dependency: step.dependency && old.as_ref().is_none_or(|o| o.dependency), + }; + debug_assert!(path.ends_with(name)); + installed + .entries + .retain(|e| !(e.source == p.source && e.project == p.id)); + installed.entries.push(entry.clone()); + installed.save(home)?; + done.push(entry); + } + Ok(done) +} + +/// Removes what the browser installed for `name` (a project id or slug): its file and its entry. +pub fn remove(home: &Path, name: &str) -> Result { + let mut installed = Installed::load(home); + let entry = installed + .lookup(name) + .cloned() + .ok_or_else(|| format!("{name} wasn't installed by the browser."))?; + match fs::remove_file(home.join(&entry.file)) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(format!("{}: {e}", entry.file)), + } + installed + .entries + .retain(|e| !(e.source == entry.source && e.project == entry.project)); + installed.save(home)?; + Ok(entry) +} + +/// The newer version `entry` can be updated to, if any. +pub fn update_for(source: &dyn Source, entry: &Entry) -> Result, String> { + let project = source.project(&entry.project)?; + let versions = source.versions(&project)?; + Ok(pick(project.kind, &versions, true) + .filter(|v| v.id != entry.version) + .cloned()) +} + +/// Downloads a modpack's file, checked, into `folder` (kept there: the import reads it). +pub fn fetch_modpack( + source: &dyn Source, + project: &Project, + folder: &Path, + progress: &dyn Fn(f32), +) -> Result { + if project.kind != Kind::Modpack { + return Err(format!("{} isn't a modpack.", project.title)); + } + let versions = source.versions(project)?; + let version = pick(Kind::Modpack, &versions, true) + .ok_or_else(|| format!("{} has no file to download.", project.title))?; + let file = version.file().expect("pick keeps versions with a file"); + source.fetch(file, folder, progress) +} + +#[cfg(test)] +mod tests; diff --git a/launcher/src/browser/installed/tests.rs b/launcher/src/browser/installed/tests.rs new file mode 100644 index 000000000..33dc525ab --- /dev/null +++ b/launcher/src/browser/installed/tests.rs @@ -0,0 +1,252 @@ +use super::*; +use crate::browser::{download, FileRef, Query, GAME}; +use sha2::Digest; +use std::collections::HashMap; +use std::sync::Mutex; + +/// A source in memory: projects, their versions, and the bytes each file URL serves. +#[derive(Default)] +struct Fake { + projects: HashMap, + versions: Mutex>>, + bytes: Mutex>>, +} + +impl Source for Fake { + fn id(&self) -> SourceId { + SourceId::Modrinth + } + fn search(&self, _: &Query) -> Result, String> { + Ok(self.projects.values().cloned().collect()) + } + fn project(&self, id: &str) -> Result { + self.projects + .get(id) + .cloned() + .ok_or_else(|| "not a pack".into()) + } + fn versions(&self, p: &Project) -> Result, String> { + Ok(self + .versions + .lock() + .unwrap() + .get(&p.id) + .cloned() + .unwrap_or_default()) + } + fn fetch( + &self, + file: &FileRef, + folder: &Path, + progress: &dyn Fn(f32), + ) -> Result { + let body = self + .bytes + .lock() + .unwrap() + .get(&file.url) + .cloned() + .unwrap_or_default(); + download::save(file, &body[..], folder, progress) + } +} + +fn project(id: &str, kind: Kind) -> Project { + Project { + source: SourceId::Modrinth, + id: id.into(), + slug: format!("{id}-slug"), + title: format!("Pack {id}"), + summary: String::new(), + author: String::new(), + downloads: 0, + page: format!("https://modrinth.com/resourcepack/{id}-slug"), + icon: None, + license: "MIT".into(), + kind, + game_versions: vec![GAME.into()], + loaders: vec![if kind == Kind::ShaderPack { + "iris" + } else { + "minecraft" + } + .into()], + } +} + +impl Fake { + fn add(&mut self, p: Project) { + self.projects.insert(p.id.clone(), p); + } + /// A new newest version of `id`, its file serving `body`; `tamper` serves other bytes. + fn release(&self, id: &str, number: &str, needs: &[&str], body: &[u8], tamper: bool) { + let url = format!("https://cdn.modrinth.com/data/{id}/versions/{number}/{id}-{number}.zip"); + let file = FileRef { + url: url.clone(), + name: format!("{id}-{number}.zip"), + size: body.len() as u64, + sha512: Some( + sha2::Sha512::digest(body) + .iter() + .map(|b| format!("{b:02x}")) + .collect(), + ), + sha1: None, + primary: true, + }; + let version = Version { + id: format!("{id}@{number}"), + number: number.into(), + published: number.into(), + game_versions: vec![GAME.into()], + loaders: self.projects[id].loaders.clone(), + files: vec![file], + required: needs.iter().map(|s| s.to_string()).collect(), + blocked: None, + }; + let mut served = body.to_vec(); + if tamper { + served[0] ^= 1; + } + self.bytes.lock().unwrap().insert(url, served); + let mut versions = self.versions.lock().unwrap(); + versions.entry(id.into()).or_default().insert(0, version); + } +} + +fn home(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("horizon-installed-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + +const NONE: &dyn Fn(&str, f32) = &|_, _| {}; + +#[test] +fn installs_with_dependencies_then_updates_and_removes() { + let home = home("cycle"); + let mut fake = Fake::default(); + fake.add(project("base", Kind::ResourcePack)); + fake.add(project("addon", Kind::ResourcePack)); + fake.release("base", "1", &[], b"base pack", false); + fake.release("addon", "1", &["base"], b"addon pack", false); + let addon = fake.project("addon").unwrap(); + + let done = install(&fake, &addon, false, &home, NONE).unwrap(); + let files: Vec<&str> = done.iter().map(|e| e.file.as_str()).collect(); + assert_eq!( + files, + ["resourcepacks/base-1.zip", "resourcepacks/addon-1.zip"] + ); + assert!(done[0].dependency && !done[1].dependency); + assert!(done[1].checksum.starts_with("SHA-512:")); + assert_eq!( + fs::read(home.join("resourcepacks/addon-1.zip")).unwrap(), + b"addon pack" + ); + assert_eq!(Installed::load(&home).entries.len(), 2); + + // Installing again with nothing new downloads nothing. + fs::remove_file(home.join("resourcepacks/base-1.zip")).unwrap(); + install(&fake, &addon, false, &home, NONE).unwrap(); + assert!(!home.join("resourcepacks/base-1.zip").exists()); + + // An update replaces the old file. + fake.release("addon", "2", &["base"], b"addon pack v2", false); + let entry = Installed::load(&home).lookup("addon").cloned().unwrap(); + assert_eq!(update_for(&fake, &entry).unwrap().unwrap().number, "2"); + install(&fake, &addon, false, &home, NONE).unwrap(); + assert!(!home.join("resourcepacks/addon-1.zip").exists()); + assert_eq!( + fs::read(home.join("resourcepacks/addon-2.zip")).unwrap(), + b"addon pack v2" + ); + let entry = Installed::load(&home) + .lookup("addon-slug") + .cloned() + .unwrap(); + assert_eq!(entry.number, "2"); + assert!(update_for(&fake, &entry).unwrap().is_none()); + + let removed = remove(&home, "addon").unwrap(); + assert_eq!(removed.project, "addon"); + assert!(!home.join("resourcepacks/addon-2.zip").exists()); + assert!(remove(&home, "addon").is_err()); + assert_eq!(Installed::load(&home).entries.len(), 1); + fs::remove_dir_all(&home).unwrap(); +} + +#[test] +fn nothing_is_installed_when_a_check_fails() { + let home = home("refuse"); + let mut fake = Fake::default(); + fake.add(project("good", Kind::ResourcePack)); + fake.add(project("bad", Kind::ResourcePack)); + fake.add(project("needs-mod", Kind::ResourcePack)); + fake.release("good", "1", &[], b"good", false); + fake.release("bad", "1", &[], b"tampered", true); + fake.release("needs-mod", "1", &["sodium"], b"x", false); + + let e = install(&fake, &fake.project("bad").unwrap(), false, &home, NONE).unwrap_err(); + assert!(e.contains("checksum doesn't match"), "{e}"); + let e = install( + &fake, + &fake.project("needs-mod").unwrap(), + false, + &home, + NONE, + ) + .unwrap_err(); + assert!(e.contains("needs sodium"), "{e}"); + assert!( + !home.join("resourcepacks").exists() + || fs::read_dir(home.join("resourcepacks")).unwrap().count() == 0 + ); + assert!(Installed::load(&home).entries.is_empty()); + + // The player's own file of the same name is never replaced. + fs::create_dir_all(home.join("resourcepacks")).unwrap(); + fs::write(home.join("resourcepacks/good-1.zip"), b"mine").unwrap(); + let e = install(&fake, &fake.project("good").unwrap(), false, &home, NONE).unwrap_err(); + assert!(e.contains("wasn't installed by the browser"), "{e}"); + assert_eq!( + fs::read(home.join("resourcepacks/good-1.zip")).unwrap(), + b"mine" + ); + assert!(remove(&home, "good").is_err()); + assert!(home.join("resourcepacks/good-1.zip").exists()); + + // What doesn't run is refused before anything is asked for. + let mut canvas = project("canvas", Kind::ShaderPack); + canvas.loaders = vec!["canvas".into()]; + fake.add(canvas.clone()); + assert!(install(&fake, &canvas, true, &home, NONE) + .unwrap_err() + .contains("doesn't run")); + let pack = project("pack", Kind::Modpack); + assert!(plan(&fake, &pack, false) + .unwrap_err() + .contains("Modpacks page")); + fs::remove_dir_all(&home).unwrap(); +} + +#[test] +fn shader_packs_go_to_their_folder_and_modpacks_download_checked() { + let home = home("kinds"); + let mut fake = Fake::default(); + fake.add(project("bsl", Kind::ShaderPack)); + fake.release("bsl", "10", &[], b"shaders", false); + install(&fake, &fake.project("bsl").unwrap(), false, &home, NONE).unwrap(); + assert!(home.join("shaderpacks/bsl-10.zip").is_file()); + + fake.add(project("atm", Kind::Modpack)); + fake.release("atm", "1", &[], b"mrpack", false); + let downloads = home.join("downloads"); + let path = fetch_modpack(&fake, &fake.project("atm").unwrap(), &downloads, &|_| {}).unwrap(); + assert_eq!(fs::read(path).unwrap(), b"mrpack"); + fake.release("atm", "2", &[], b"mrpack 2", true); + assert!(fetch_modpack(&fake, &fake.project("atm").unwrap(), &downloads, &|_| {}).is_err()); + assert!(!downloads.join("atm-2.zip").exists()); + fs::remove_dir_all(&home).unwrap(); +} diff --git a/launcher/src/browser/modrinth.rs b/launcher/src/browser/modrinth.rs new file mode 100644 index 000000000..e7e39628a --- /dev/null +++ b/launcher/src/browser/modrinth.rs @@ -0,0 +1,214 @@ +//! Modrinth's public API (api.modrinth.com/v2): no key, files with SHA-512 and SHA-1. +use super::{FileRef, Kind, Project, Query, Source, SourceId, Version, GAME}; +use serde_json::Value; + +const API: &str = "https://api.modrinth.com/v2"; +const SITE: &str = "https://modrinth.com"; + +pub struct Modrinth; + +/// Modrinth's project type for a kind. +fn project_type(kind: Kind) -> &'static str { + match kind { + Kind::ResourcePack => "resourcepack", + Kind::ShaderPack => "shader", + Kind::Modpack => "modpack", + } +} + +fn kind_of(project_type: &str) -> Option { + Kind::ALL + .into_iter() + .find(|k| self::project_type(*k) == project_type) +} + +/// The search's facets (AND of ORs): the kind, and unless `everything` what runs. +pub(super) fn facets(query: &Query) -> String { + let mut all = vec![vec![format!("project_type:{}", project_type(query.kind))]]; + if !query.everything { + match query.kind { + Kind::ResourcePack => all.push(vec![format!("versions:{GAME}")]), + Kind::ShaderPack => { + all.push(vec!["categories:iris".into(), "categories:optifine".into()]) + } + Kind::Modpack => {} + } + } + serde_json::to_string(&all).unwrap_or_default() +} + +pub(super) fn search_url(query: &Query) -> String { + let mut url = format!( + "{API}/search?facets={}&index={}&offset={}&limit={}", + encode(&facets(query)), + if query.text.is_empty() { + "downloads" + } else { + "relevance" + }, + query.offset, + query.limit.clamp(1, 100), + ); + if !query.text.is_empty() { + url.push_str("&query="); + url.push_str(&encode(&query.text)); + } + url +} + +fn strings(v: &Value) -> Vec { + v.as_array() + .into_iter() + .flatten() + .filter_map(|s| s.as_str().map(str::to_owned)) + .collect() +} + +fn text(v: &Value) -> String { + v.as_str().unwrap_or_default().to_owned() +} + +/// A search hit. Its `categories` hold the loaders too; `versions` its Minecraft versions. +pub(super) fn parse_hit(hit: &Value) -> Option { + let kind = kind_of(hit["project_type"].as_str()?)?; + let slug = text(&hit["slug"]); + Some(Project { + source: SourceId::Modrinth, + id: hit["project_id"].as_str()?.to_owned(), + page: format!("{SITE}/{}/{slug}", project_type(kind)), + slug, + title: text(&hit["title"]), + summary: text(&hit["description"]), + author: text(&hit["author"]), + downloads: hit["downloads"].as_u64().unwrap_or(0), + icon: hit["icon_url"] + .as_str() + .filter(|u| !u.is_empty()) + .map(str::to_owned), + license: text(&hit["license"]), + kind, + game_versions: strings(&hit["versions"]), + loaders: strings(&hit["categories"]), + }) +} + +/// `GET /project/{id}`: the fields differ from a search hit's. +pub(super) fn parse_project(p: &Value) -> Option { + let kind = kind_of(p["project_type"].as_str()?)?; + let slug = text(&p["slug"]); + Some(Project { + source: SourceId::Modrinth, + id: p["id"].as_str()?.to_owned(), + page: format!("{SITE}/{}/{slug}", project_type(kind)), + slug, + title: text(&p["title"]), + summary: text(&p["description"]), + author: String::new(), + downloads: p["downloads"].as_u64().unwrap_or(0), + icon: p["icon_url"] + .as_str() + .filter(|u| !u.is_empty()) + .map(str::to_owned), + license: text(&p["license"]["id"]), + kind, + game_versions: strings(&p["game_versions"]), + loaders: strings(&p["loaders"]), + }) +} + +pub(super) fn parse_version(v: &Value) -> Option { + let files = v["files"] + .as_array()? + .iter() + .filter_map(|f| { + Some(FileRef { + url: f["url"].as_str()?.to_owned(), + name: f["filename"].as_str()?.to_owned(), + size: f["size"].as_u64().unwrap_or(0), + sha512: f["hashes"]["sha512"].as_str().map(str::to_ascii_lowercase), + sha1: f["hashes"]["sha1"].as_str().map(str::to_ascii_lowercase), + primary: f["primary"].as_bool().unwrap_or(false), + }) + }) + .collect(); + let required = v["dependencies"] + .as_array() + .into_iter() + .flatten() + .filter(|d| d["dependency_type"] == "required") + .filter_map(|d| d["project_id"].as_str().map(str::to_owned)) + .collect(); + Some(Version { + id: v["id"].as_str()?.to_owned(), + number: text(&v["version_number"]), + published: text(&v["date_published"]), + game_versions: strings(&v["game_versions"]), + loaders: strings(&v["loaders"]), + files, + required, + blocked: None, + }) +} + +impl Source for Modrinth { + fn id(&self) -> SourceId { + SourceId::Modrinth + } + + fn search(&self, query: &Query) -> Result, String> { + let found = get(&search_url(query))?; + Ok(found["hits"] + .as_array() + .into_iter() + .flatten() + .filter_map(parse_hit) + .collect()) + } + + fn project(&self, id: &str) -> Result { + let p = get(&format!("{API}/project/{}", encode(id)))?; + parse_project(&p).ok_or_else(|| format!("Modrinth: {id} is not a pack Horizon loads.")) + } + + fn versions(&self, project: &Project) -> Result, String> { + let found = get(&format!("{API}/project/{}/version", encode(&project.id)))?; + let mut all: Vec = found + .as_array() + .into_iter() + .flatten() + .filter(|v| v["status"].as_str().is_none_or(|s| s == "listed")) + .filter_map(parse_version) + .collect(); + // Modrinth lists newest first already; ISO dates sort as text. + all.sort_by(|a, b| b.published.cmp(&a.published)); + Ok(all) + } +} + +fn get(url: &str) -> Result { + let response = super::download::agent() + .get(url) + .call() + .map_err(|e| match e { + ureq::Error::Status(429, _) => { + "Modrinth asks to slow down: try again in a minute.".into() + } + ureq::Error::Status(code, _) => format!("Modrinth answered {code}."), + ureq::Error::Transport(t) => format!("No connection to Modrinth: {t}"), + })?; + response + .into_json() + .map_err(|e| format!("Modrinth's answer wasn't readable: {e}")) +} + +/// Percent-encoding for a query value or a path segment. +pub(super) fn encode(s: &str) -> String { + s.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + (b as char).to_string() + } + _ => format!("%{b:02X}"), + }) + .collect() +} diff --git a/launcher/src/browser/tests.rs b/launcher/src/browser/tests.rs new file mode 100644 index 000000000..ced342d13 --- /dev/null +++ b/launcher/src/browser/tests.rs @@ -0,0 +1,355 @@ +use super::*; +use serde_json::json; +use sha2::Digest; + +fn v(list: &[&str]) -> Vec { + list.iter().map(|s| s.to_string()).collect() +} + +fn version(id: &str, games: &[&str], loaders: &[&str]) -> Version { + Version { + id: id.into(), + number: id.into(), + published: String::new(), + game_versions: v(games), + loaders: v(loaders), + files: vec![FileRef { + url: format!("https://cdn.modrinth.com/data/x/versions/{id}/{id}.zip"), + name: format!("{id}.zip"), + size: 3, + sha512: Some("ab".into()), + sha1: None, + primary: true, + }], + required: Vec::new(), + blocked: None, + } +} + +#[test] +fn support_by_kind() { + assert_eq!( + support( + Kind::ResourcePack, + &v(&["1.21.4", GAME]), + &v(&["minecraft"]) + ), + Support::Works + ); + let old = support( + Kind::ResourcePack, + &v(&["1.20.1", "1.21.10", "1.21.9", "26.4-snapshot-1"]), + &[], + ); + assert_eq!(old.label(), "Partly"); + assert!( + old.reason().unwrap().starts_with("Made for 1.21.10:"), + "{old:?}" + ); + assert!(support(Kind::ShaderPack, &[], &v(&["iris"])).installable()); + assert!(support(Kind::ShaderPack, &[], &v(&["optifine"])).installable()); + let canvas = support(Kind::ShaderPack, &[], &v(&["canvas"])); + assert!(!canvas.installable()); + assert!(canvas.reason().unwrap().contains("canvas")); + assert!(!support(Kind::ShaderPack, &[], &[]).installable()); + assert!(support(Kind::Modpack, &v(&["1.21.1"]), &v(&["neoforge"])).installable()); +} + +#[test] +fn picks_the_newest_version_that_runs() { + let versions = [ + version("snapshot", &["26.4-snapshot-5"], &["minecraft"]), + version("now", &["26.2", GAME], &["minecraft"]), + version("old", &["1.21.1"], &["minecraft"]), + ]; + assert_eq!( + pick(Kind::ResourcePack, &versions, false).unwrap().id, + "now" + ); + let old = [version("old", &["1.21.1"], &["minecraft"])]; + assert!(pick(Kind::ResourcePack, &old, false).is_none()); + assert_eq!(pick(Kind::ResourcePack, &old, true).unwrap().id, "old"); + + let shaders = [ + version("canvas", &[GAME], &["canvas"]), + version("iris", &["1.21.1"], &["iris"]), + ]; + assert_eq!(pick(Kind::ShaderPack, &shaders, false).unwrap().id, "iris"); + let only_canvas = [version("canvas", &[GAME], &["canvas"])]; + assert!(pick(Kind::ShaderPack, &only_canvas, true).is_none()); + + let mut blocked = version("blocked", &[GAME], &["minecraft"]); + blocked.blocked = Some("no".into()); + let mut empty = version("empty", &[GAME], &["minecraft"]); + empty.files.clear(); + assert!(pick(Kind::ResourcePack, &[blocked, empty], true).is_none()); +} + +#[test] +fn file_names_must_be_plain() { + for good in [ + "Faithful 32x.zip", + "FreshAnimations_v1.11.1_26.1+.zip", + "BSL_v10.zip", + ] { + assert_eq!(safe_name(good), Some(good)); + } + for bad in [ + "", + "../x.zip", + "a/b.zip", + "a\\b.zip", + ".hidden.zip", + "c:x.zip", + "x.zip.", + "x\n.zip", + ] { + assert_eq!(safe_name(bad), None, "{bad:?}"); + } +} + +#[test] +fn modrinth_search_asks_for_what_runs() { + let q = Query::new(" faithful ", Kind::ResourcePack); + assert_eq!(q.text, "faithful"); + assert_eq!( + modrinth::facets(&q), + r#"[["project_type:resourcepack"],["versions:26.3"]]"# + ); + let url = modrinth::search_url(&q); + assert!(url.starts_with("https://api.modrinth.com/v2/search?facets=%5B%5B%22project_type")); + assert!( + url.contains("&index=relevance&") && url.ends_with("&query=faithful"), + "{url}" + ); + let shaders = Query::new("", Kind::ShaderPack); + assert_eq!( + modrinth::facets(&shaders), + r#"[["project_type:shader"],["categories:iris","categories:optifine"]]"# + ); + assert!(modrinth::search_url(&shaders).contains("&index=downloads&")); + let everything = Query { + everything: true, + ..Query::new("", Kind::ResourcePack) + }; + assert_eq!( + modrinth::facets(&everything), + r#"[["project_type:resourcepack"]]"# + ); + assert_eq!( + modrinth::facets(&Query::new("", Kind::Modpack)), + r#"[["project_type:modpack"]]"# + ); +} + +#[test] +fn modrinth_answers() { + let hit = json!({ + "project_id": "50dA9Sha", "project_type": "resourcepack", "slug": "fresh-animations", + "title": "Fresh Animations", "description": "Animated entities.", "author": "FreshLX", + "downloads": 51404735, "icon_url": "https://cdn.modrinth.com/data/50dA9Sha/icon.webp", + "license": "LicenseRef-See-Terms", "versions": ["1.21.11", "26.3"], + "categories": ["16x", "minecraft"] + }); + let p = modrinth::parse_hit(&hit).unwrap(); + assert_eq!(p.id, "50dA9Sha"); + assert_eq!(p.kind, Kind::ResourcePack); + assert_eq!(p.page, "https://modrinth.com/resourcepack/fresh-animations"); + assert_eq!(p.support(), Support::Works); + assert_eq!(p.downloads, 51404735); + // A Java mod is never a result. + let jar = json!({"project_id": "AANobbMI", "project_type": "mod", "slug": "sodium"}); + assert!(modrinth::parse_hit(&jar).is_none()); + + let project = json!({ + "id": "HVnmMxH1", "project_type": "shader", "slug": "complementary-reimagined", + "title": "Complementary Shaders - Reimagined", "description": "d", + "license": {"id": "LicenseRef-Complementary", "name": ""}, + "game_versions": ["1.21.1"], "loaders": ["iris", "optifine"] + }); + let p = modrinth::parse_project(&project).unwrap(); + assert_eq!(p.kind, Kind::ShaderPack); + assert_eq!(p.license, "LicenseRef-Complementary"); + assert_eq!( + p.page, + "https://modrinth.com/shader/complementary-reimagined" + ); + assert!(p.support().installable()); + + let version = json!({ + "id": "tvGVYMD4", "version_number": "1.11.1", "date_published": "2026-10-20T02:23:13Z", + "game_versions": ["26.2", "26.3"], "loaders": ["minecraft"], + "dependencies": [ + {"project_id": "need", "dependency_type": "required"}, + {"project_id": "maybe", "dependency_type": "optional"}, + {"version_id": "x", "project_id": null, "dependency_type": "required"} + ], + "files": [ + {"hashes": {"sha512": "AB12", "sha1": "cd34"}, "url": "https://cdn.modrinth.com/data/a/b.zip", + "filename": "b.zip", "primary": false, "size": 10}, + {"hashes": {"sha512": "ef56", "sha1": "0789"}, "url": "https://cdn.modrinth.com/data/a/c.zip", + "filename": "c.zip", "primary": true, "size": 20} + ] + }); + let ver = modrinth::parse_version(&version).unwrap(); + assert_eq!(ver.required, ["need"]); + assert_eq!(ver.files[0].sha512.as_deref(), Some("ab12")); + let file = ver.file().unwrap(); + assert_eq!(file.name, "c.zip"); + assert_eq!(file.checksum(), Some(("SHA-512", "ef56"))); +} + +#[test] +fn curseforge_stays_off_without_a_key() { + assert_eq!(curseforge::key(None, None), None); + assert_eq!(curseforge::key(Some(" ".into()), None), None); + assert_eq!(curseforge::key(None, Some("")), None); + assert_eq!( + curseforge::key(None, Some("built")).as_deref(), + Some("built") + ); + assert_eq!( + curseforge::key(Some("env ".into()), Some("built")).as_deref(), + Some("env") + ); +} + +#[test] +fn curseforge_answers() { + let q = Query::new("bsl", Kind::ShaderPack); + let url = curseforge::search_url(&q); + assert!(url.contains("gameId=432&classId=6552&"), "{url}"); + assert!( + !url.contains("gameVersion=") && url.ends_with("&searchFilter=bsl"), + "{url}" + ); + assert!( + curseforge::search_url(&Query::new("", Kind::ResourcePack)).contains("&gameVersion=26.3") + ); + + let m = json!({ + "id": 228756, "classId": 6552, "slug": "bsl-shaders", "name": "BSL Shaders", + "summary": "s", "authors": [{"name": "CaptTatsu"}], "downloadCount": 1.5e7, + "links": {"websiteUrl": "https://www.curseforge.com/minecraft/shaders/bsl-shaders"}, + "logo": {"thumbnailUrl": "https://media.forgecdn.net/avatars/thumbnails/x.png"}, + "latestFilesIndexes": [{"gameVersion": "1.21.1"}], + "latestFiles": [{"gameVersions": ["1.21.1", "Iris", "OptiFine"]}] + }); + let p = curseforge::parse_mod(&m).unwrap(); + assert_eq!( + (p.source, p.id.as_str(), p.kind), + (SourceId::CurseForge, "228756", Kind::ShaderPack) + ); + assert_eq!(p.loaders, ["iris", "optifine"]); + assert_eq!(p.author, "CaptTatsu"); + assert!(p.support().installable()); + assert!(curseforge::parse_mod(&json!({"id": 1, "classId": 6})).is_none()); + + let file = json!({ + "id": 5000, "displayName": "BSL v10", "fileName": "BSL_v10.zip", "fileLength": 300, + "fileDate": "2026-01-01T00:00:00Z", "downloadUrl": "https://edge.forgecdn.net/files/5/0/BSL_v10.zip", + "gameVersions": ["1.21.1", "Iris"], + "hashes": [{"value": "D41D8CD9", "algo": 2}, {"value": "DA39A3EE", "algo": 1}], + "dependencies": [{"modId": 7, "relationType": 3}, {"modId": 8, "relationType": 2}] + }); + let ver = curseforge::parse_file(&file).unwrap(); + assert_eq!(ver.required, ["7"]); + assert_eq!(ver.loaders, ["iris"]); + assert_eq!(ver.file().unwrap().checksum(), Some(("SHA-1", "da39a3ee"))); + assert!(ver.blocked.is_none()); + let mut closed = file.clone(); + closed["downloadUrl"] = serde_json::Value::Null; + let ver = curseforge::parse_file(&closed).unwrap(); + assert!(ver.files.is_empty() && ver.blocked.is_some()); +} + +fn scratch(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("horizon-browser-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + dir +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +fn file_for(body: &[u8], sha512: bool) -> FileRef { + FileRef { + url: "https://cdn.modrinth.com/data/a/versions/b/pack.zip".into(), + name: "pack.zip".into(), + size: body.len() as u64, + sha512: sha512.then(|| hex(&sha2::Sha512::digest(body))), + sha1: (!sha512).then(|| hex(&sha1::Sha1::digest(body))), + primary: true, + } +} + +#[test] +fn a_download_is_kept_only_when_its_checksum_matches() { + let dir = scratch("save"); + let body = b"a resource pack"; + for strong in [true, false] { + let file = file_for(body, strong); + let path = download::save(&file, &body[..], &dir, &|_| {}).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), body); + std::fs::remove_file(path).unwrap(); + } + // Another file than the one listed: refused, and nothing is left behind. + let file = file_for(body, true); + let other = b"a resource paCk"; + let e = download::save(&file, &other[..], &dir, &|_| {}).unwrap_err(); + assert!(e.contains("SHA-512 checksum doesn't match"), "{e}"); + let short = download::save(&file, &body[..4], &dir, &|_| {}).unwrap_err(); + assert!(short.starts_with("Got 4 bytes"), "{short}"); + let long = download::save(&file, &b"a resource pack and more"[..], &dir, &|_| {}).unwrap_err(); + assert!(long.contains("larger"), "{long}"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn downloads_refused_before_any_byte() { + let body = b"x"; + let mut file = file_for(body, true); + file.url = "https://example.com/pack.zip".into(); + assert!(download::refuse(&file).unwrap().contains("file servers")); + let mut file = file_for(body, true); + file.url = "http://cdn.modrinth.com/data/a/pack.zip".into(); + assert!(download::refuse(&file).is_some()); + let mut file = file_for(body, true); + file.name = "../../options.txt".into(); + assert!(download::refuse(&file).unwrap().contains("plain file name")); + let mut file = file_for(body, true); + file.sha512 = None; + assert!(download::refuse(&file).unwrap().contains("no checksum")); + let mut file = file_for(body, false); + file.url = "https://edge.forgecdn.net/files/1/2/pack.zip".into(); + assert_eq!(download::refuse(&file), None); +} + +/// Against the real Modrinth: `cargo test --lib browser::tests::live -- --ignored`. +#[test] +#[ignore = "needs the network"] +fn live_modrinth_search_pick_and_download() { + let source = modrinth::Modrinth; + for kind in Kind::ALL { + let found = source.search(&Query::new("", kind)).unwrap(); + assert!(!found.is_empty(), "{kind:?}"); + assert!(found + .iter() + .all(|p| p.kind == kind && p.support().installable())); + } + let packs = source + .search(&Query::new("fresh animations", Kind::ResourcePack)) + .unwrap(); + let p = packs.iter().find(|p| p.slug == "fresh-animations").unwrap(); + assert_eq!(p.support(), Support::Works); + let versions = source.versions(p).unwrap(); + let chosen = pick(p.kind, &versions, false).unwrap(); + assert!(chosen.game_versions.iter().any(|g| g == GAME)); + let dir = scratch("live"); + let path = download::fetch(chosen.file().unwrap(), &dir, &|_| {}).unwrap(); + assert!(path.is_file()); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(source.project(&p.id).unwrap().slug, p.slug); +} diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index a43529db0..6dcb4b975 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -155,6 +155,68 @@ enum ModpackCmd { Remove { pack: String }, } +#[derive(Subcommand)] +enum ModsCmd { + /// What the browser installed (the default) + List, + /// Search for packs Horizon loads + Search { + text: Vec, + #[arg(long, value_enum, default_value_t = KindArg::Resource)] + kind: KindArg, + /// Also what was made for other versions or runs only partly, each marked + #[arg(long)] + everything: bool, + #[arg(long, value_enum, default_value_t = SourceArg::Modrinth)] + source: SourceArg, + }, + /// Install a pack and what it needs, by its id or slug (checksums checked); a modpack is + /// imported on the Modpacks page + Install { + project: String, + /// Allow a version made for another Minecraft version + #[arg(long)] + everything: bool, + #[arg(long, value_enum, default_value_t = SourceArg::Modrinth)] + source: SourceArg, + }, + /// Update what the browser installed (or one pack) + Update { + project: Option, + /// Only say what is newer + #[arg(long)] + check: bool, + }, + /// Remove a pack the browser installed + Remove { project: String }, +} + +#[derive(Clone, Copy, clap::ValueEnum)] +enum KindArg { + Resource, + Shader, + Modpack, +} + +#[derive(Clone, Copy, clap::ValueEnum)] +enum SourceArg { + Modrinth, + Curseforge, +} + +impl SourceArg { + fn get(self) -> Result, String> { + use horizon_launcher::browser::{self, SourceId}; + let id = match self { + SourceArg::Modrinth => SourceId::Modrinth, + SourceArg::Curseforge => SourceId::CurseForge, + }; + browser::source(id).ok_or_else(|| { + "CurseForge needs an API key: HORIZON_CURSEFORGE_API_KEY (docs/mod-browser.md).".into() + }) + } +} + #[derive(Subcommand)] enum Cmd { /// List Horizon releases, or the installed versions @@ -257,6 +319,12 @@ enum Cmd { #[command(subcommand)] action: Option, }, + /// The mod browser: resource packs, shader packs and modpacks from Modrinth (and CurseForge + /// with a key), each file checked against its checksum (docs/mod-browser.md) + Mods { + #[command(subcommand)] + action: Option, + }, /// Servers hosted with horizon-server (the Servers page): list them, create one, or run any /// horizon-server command on one Servers { @@ -523,6 +591,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { } } Cmd::Modpack { action } => modpack(action.unwrap_or(ModpackCmd::List), as_json)?, + Cmd::Mods { action } => mods(action.unwrap_or(ModsCmd::List), as_json)?, Cmd::Servers { action } => servers(action.unwrap_or(ServersCmd::List), as_json)?, Cmd::Mcp => unreachable!(), } @@ -821,6 +890,148 @@ fn servers(action: ServersCmd, as_json: bool) -> Result<(), String> { Ok(()) } +fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> { + use horizon_launcher::browser::{installed, Kind, Query}; + use horizon_launcher::modpacks; + let home = backend::game_home(); + let entry_json = |e: &installed::Entry| serde_json::to_value(e).unwrap_or_default(); + let line = |label: &str, f: f32| progress(label.to_string())(f); + match action { + ModsCmd::List => { + let list = installed::Installed::load(&home).entries; + if as_json { + json(list.iter().map(entry_json).collect()); + } else if list.is_empty() { + println!( + "Nothing installed from the browser yet: horizon-launcher mods search " + ); + } + for e in list.iter().filter(|_| !as_json) { + println!( + "{} {} ({}, {})\n {} {}", + e.title, + e.number, + e.source.label(), + e.slug, + e.file, + e.checksum + ); + } + } + ModsCmd::Search { + text, + kind, + everything, + source, + } => { + let kind = match kind { + KindArg::Resource => Kind::ResourcePack, + KindArg::Shader => Kind::ShaderPack, + KindArg::Modpack => Kind::Modpack, + }; + let query = Query { + everything, + ..Query::new(&text.join(" "), kind) + }; + let found = source.get()?.search(&query)?; + if as_json { + json(found.iter().map(|p| { + let support = p.support(); + serde_json::json!({ + "id": p.id, "slug": p.slug, "title": p.title, "summary": p.summary, + "author": p.author, "downloads": p.downloads, "page": p.page, + "license": p.license, "support": support.label(), "reason": support.reason(), + }) + }).collect()); + } else { + for p in &found { + let support = p.support(); + println!( + "{} ({}) {} · {} downloads\n {}", + p.title, + p.slug, + support.label(), + p.downloads, + p.summary + ); + if let Some(why) = support.reason() { + println!(" {why}"); + } + } + } + } + ModsCmd::Install { + project, + everything, + source, + } => { + let source = source.get()?; + let p = source.project(&project)?; + if p.kind == Kind::Modpack { + let folder = modpacks::ports_dir().join("downloads"); + let file = + installed::fetch_modpack(&*source, &p, &folder, &progress(p.title.clone()))?; + let log = &|line: String| eprintln!("{line}"); + let pack = modpacks::import(&file, log)?; + println!( + "Imported {} ({}): horizon-launcher modpack port {}", + pack.title(), + pack.summary(), + pack.slug + ); + return Ok(()); + } + let done = installed::install(&*source, &p, everything, &home, &line)?; + if as_json { + json(done.iter().map(entry_json).collect()); + } + for e in done.iter().filter(|_| !as_json) { + println!("{} {}: {} ({})", e.title, e.number, e.file, e.checksum); + } + } + ModsCmd::Update { project, check } => { + let list = installed::Installed::load(&home).entries; + let chosen: Vec<_> = list + .iter() + .filter(|e| { + project + .as_deref() + .is_none_or(|n| e.project == n || e.slug == n) + }) + .collect(); + if chosen.is_empty() { + return Err(match project { + Some(n) => format!("{n} wasn't installed by the browser."), + None => "Nothing installed from the browser yet.".into(), + }); + } + for e in chosen { + let Some(source) = horizon_launcher::browser::source(e.source) else { + println!("{}: {} isn't available here.", e.title, e.source.label()); + continue; + }; + match installed::update_for(&*source, e)? { + None => println!("{} {}: up to date.", e.title, e.number), + Some(v) if check => { + println!("{} {}: {} is available.", e.title, e.number, v.number) + } + Some(_) => { + let p = source.project(&e.project)?; + for done in installed::install(&*source, &p, true, &home, &line)? { + println!("{} {}: {}", done.title, done.number, done.file); + } + } + } + } + } + ModsCmd::Remove { project } => { + let e = installed::remove(&home, &project)?; + println!("Removed {} ({}).", e.title, e.file); + } + } + Ok(()) +} + fn modpack(action: ModpackCmd, as_json: bool) -> Result<(), String> { use horizon_launcher::modpacks::{self, Imported}; use horizon_port_pack::report::Status; diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs index 99445abf3..98228b5fc 100644 --- a/launcher/src/lib.rs +++ b/launcher/src/lib.rs @@ -1,6 +1,7 @@ //! The launcher's core, shared by the GUI, the CLI and the MCP server. pub mod account; pub mod backend; +pub mod browser; pub mod desktop; pub mod heads; pub mod modpacks; diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 3b2d0f32b..41bce0489 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -8,6 +8,7 @@ mod internet; mod markdown; mod mcp; mod modpacks_page; +mod mods_page; mod perf; mod scrollbar; mod servers_page; @@ -35,6 +36,7 @@ use theme::Theme; enum Page { Play, Versions, + Mods, Modpacks, Servers, Notes, @@ -42,9 +44,10 @@ enum Page { } impl Page { - const ALL: [(Page, &'static str); 6] = [ + const ALL: [(Page, &'static str); 7] = [ (Page::Play, "Play"), (Page::Versions, "Versions"), + (Page::Mods, "Mods"), (Page::Modpacks, "Modpacks"), (Page::Servers, "Servers"), (Page::Notes, "Patch notes"), @@ -181,6 +184,8 @@ struct Launcher { pack_error: Option, /// The game starting now plays this pack's profile (its work folder). starting_pack: Option, + /// The Mods page: the browser's search, installs and updates (`mods_page.rs`). + mods: mods_page::Mods, } impl Launcher { @@ -291,6 +296,7 @@ impl Launcher { pack_log: VecDeque::new(), pack_error: None, starting_pack: None, + mods: mods_page::Mods::new(cx), }; if this.bench.is_some() { this.perf.keep_local_log(false); @@ -595,6 +601,7 @@ impl Launcher { } } changed |= self.servers_tick(); + changed |= self.mods_tick(); if let Some(sign_in) = &self.sign_in { let state = sign_in.state(); let changed_state = format!("{state:?}") != format!("{:?}", self.sign_in_state); @@ -2687,10 +2694,12 @@ impl Render for Launcher { self.perf.frame(); self.servers.note_focus(window); self.friend_focused = self.friend_focus.is_focused(window); + self.mods.note_focus(window); self.args_focused = self.args_focus.is_focused(window); let content = match self.page { Page::Play => self.play_page(cx), Page::Versions => self.versions_page(cx), + Page::Mods => self.mods_page(cx), Page::Modpacks => self.modpacks_page(cx), Page::Servers => self.servers_page(cx), Page::Notes => self.notes_page(cx), diff --git a/launcher/src/mods_page.rs b/launcher/src/mods_page.rs new file mode 100644 index 000000000..25a825c93 --- /dev/null +++ b/launcher/src/mods_page.rs @@ -0,0 +1,675 @@ +//! The Mods page: search Modrinth (and CurseForge with a key) for resource packs, shader packs +//! and modpacks Horizon loads, see where each comes from and how well it runs, install it with +//! its checksum checked, and update or remove what was installed (`horizon_launcher::browser`). +use super::servers_page::{type_key, Key}; +use super::*; +use horizon_launcher::browser::{ + self, curseforge::CurseForge, installed, Kind as PackKind, Project, Query, SourceId, Support, +}; +use horizon_launcher::modpacks; +use std::collections::HashMap; + +const KINDS: [(PackKind, &str); 3] = [ + (PackKind::ResourcePack, "Resource packs"), + (PackKind::ShaderPack, "Shader packs"), + (PackKind::Modpack, "Modpacks"), +]; +const SOURCES: [(SourceId, &str); 2] = [ + (SourceId::Modrinth, "Modrinth"), + (SourceId::CurseForge, "CurseForge"), +]; +const PAGE: usize = 20; + +pub(super) enum Event { + /// A search's answer, for the search it was (stale answers are dropped) at that offset. + Found(u64, usize, Result, String>), + Progress(String, f32), + Done(Result, bool), + Updates(HashMap<(SourceId, String), String>), +} + +pub(super) struct Mods { + kind: PackKind, + source: SourceId, + curseforge: bool, + text: String, + focus: FocusHandle, + pub(super) focused: bool, + everything: bool, + /// Which search is the current one; answers for older ones are dropped. + search: u64, + searching: bool, + searched: bool, + results: Vec, + more: bool, + error: Option, + installed: Vec, + loaded: bool, + /// The project being installed, and the line and fraction of its download. + busy: Option<(String, String, f32)>, + message: Option>, + updates: HashMap<(SourceId, String), String>, + confirm_remove: Option, + tx: Sender, + rx: Receiver, +} + +impl Mods { + pub(super) fn new(cx: &mut App) -> Self { + let (tx, rx) = channel(); + Self { + kind: PackKind::ResourcePack, + source: SourceId::Modrinth, + curseforge: CurseForge::from_env().is_some(), + text: String::new(), + focus: cx.focus_handle().tab_index(0).tab_stop(true), + focused: false, + everything: false, + search: 0, + searching: false, + searched: false, + results: Vec::new(), + more: false, + error: None, + installed: Vec::new(), + loaded: false, + busy: None, + message: None, + updates: HashMap::new(), + confirm_remove: None, + tx, + rx, + } + } + + pub(super) fn note_focus(&mut self, window: &Window) { + self.focused = self.focus.is_focused(window); + } + + fn entry(&self, p: &Project) -> Option<&installed::Entry> { + self.installed + .iter() + .find(|e| e.source == p.source && e.project == p.id) + } +} + +/// `51404735` → `51.4M`. +fn count(n: u64) -> String { + match n { + 0..1_000 => n.to_string(), + 1_000..1_000_000 => format!("{:.1}k", n as f64 / 1e3), + _ => format!("{:.1}M", n as f64 / 1e6), + } +} + +/// A checksum as the page shows it: the algorithm and the first and last hex digits. +fn short_sum(checksum: &str) -> String { + let (algo, hex) = checksum.split_once(':').unwrap_or(("", checksum)); + if hex.len() <= 20 { + return checksum.to_string(); + } + format!("{algo} {}…{}", &hex[..12], &hex[hex.len() - 8..]) +} + +impl Launcher { + /// Called with the launcher's other work: what the background sent. + pub(super) fn mods_tick(&mut self) -> bool { + let mut changed = false; + while let Ok(event) = self.mods.rx.try_recv() { + changed = true; + let m = &mut self.mods; + match event { + Event::Found(search, offset, result) if search == m.search => { + m.searching = false; + m.searched = true; + match result { + Ok(found) => { + m.more = found.len() == PAGE; + m.results.truncate(offset); + m.results.extend(found); + m.error = None; + } + Err(e) => m.error = Some(e), + } + } + Event::Found(..) => {} + Event::Progress(line, f) => { + if let Some(busy) = &mut m.busy { + busy.1 = line; + busy.2 = f; + } + } + Event::Done(result, modpack) => { + m.busy = None; + m.message = Some(result); + m.installed = installed::Installed::load(&backend::game_home()).entries; + if modpack { + // The Modpacks page reads its list again. + self.packs_loaded = None; + } + } + Event::Updates(found) => m.updates = found, + } + } + changed + } + + fn mods_search(&mut self, offset: usize) { + let m = &mut self.mods; + m.search += 1; + m.searching = true; + if offset == 0 { + m.results.clear(); + m.more = false; + } + let query = Query { + everything: m.everything, + offset, + limit: PAGE, + ..Query::new(&m.text, m.kind) + }; + let (tx, search, source) = (m.tx.clone(), m.search, m.source); + std::thread::spawn(move || { + let result = browser::source(source) + .ok_or_else(|| format!("{} isn't set up.", source.label())) + .and_then(|s| s.search(&query)); + let _ = tx.send(Event::Found(search, offset, result)); + }); + } + + /// Looks for newer versions of what the browser installed. + fn mods_check_updates(&mut self) { + let entries = self.mods.installed.clone(); + if entries.is_empty() { + return; + } + let tx = self.mods.tx.clone(); + std::thread::spawn(move || { + let mut found = HashMap::new(); + for e in entries { + let Some(source) = browser::source(e.source) else { + continue; + }; + if let Ok(Some(v)) = installed::update_for(&*source, &e) { + found.insert((e.source, e.project.clone()), v.number); + } + } + let _ = tx.send(Event::Updates(found)); + }); + } + + /// Installs (or updates) a project on a thread: a pack into its folder, a modpack into + /// Modpacks. `known` is the project when the page has it; else it is asked for first. + fn mods_install(&mut self, source: SourceId, id: String, known: Option) { + if self.mods.busy.is_some() { + return; + } + self.mods.message = None; + self.mods.busy = Some((id.clone(), format!("Asking {}…", source.label()), 0.)); + self.mods.updates.remove(&(source, id.clone())); + let (tx, everything) = (self.mods.tx.clone(), self.mods.everything); + std::thread::spawn(move || { + let last = std::cell::Cell::new(-1); + let progress = |line: &str, f: f32| { + let pct = (f * 100.) as i32; + if last.replace(pct) != pct { + let _ = tx.send(Event::Progress(line.to_string(), f)); + } + }; + let mut modpack = false; + let result = browser::source(source) + .ok_or_else(|| format!("{} isn't set up.", source.label())) + .and_then(|source| { + let p = match known { + Some(p) => p, + None => source.project(&id)?, + }; + modpack = p.kind == PackKind::Modpack; + if modpack { + let folder = modpacks::ports_dir().join("downloads"); + let file = installed::fetch_modpack(&*source, &p, &folder, &|f| { + progress(&p.title, f) + })?; + let log = |line: String| progress(&line, 1.); + let pack = modpacks::import(&file, &log)?; + return Ok(format!( + "{} is imported: open it on the Modpacks page to port it.", + pack.title() + )); + } + let home = backend::game_home(); + let done = installed::install(&*source, &p, everything, &home, &progress)?; + let names: Vec = done + .iter() + .map(|e| format!("{} {}", e.title, e.number)) + .collect(); + let turn_on = match p.kind { + PackKind::ShaderPack => "Video Settings > Shader Packs", + _ => "Options > Resource Packs", + }; + Ok(format!( + "Installed {}, checksums checked. Turn it on in the game: {turn_on}.", + names.join(", ") + )) + }); + let _ = tx.send(Event::Done(result, modpack)); + }); + } + + fn mods_field(&mut self, cx: &mut Context) -> Stateful
{ + let t = self.theme; + let m = &self.mods; + let focused = m.focused; + let shown: String = { + let chars: Vec = m.text.chars().collect(); + chars[chars.len().saturating_sub(40)..].iter().collect() + }; + div() + .id("mods-search") + .track_focus(&m.focus) + .flex() + .items_center() + .w(px(320.)) + .h(px(theme::FIELD)) + .px(px(12.)) + .overflow_hidden() + .rounded(px(theme::RADIUS)) + .border_1() + .border_color(if focused { t.accent } else { t.rule }) + .bg(t.surface) + .text_size(px(theme::UI.px)) + .cursor_text() + .child(if m.text.is_empty() && !focused { + div().text_color(t.muted).child("Search, then Enter") + } else { + div().text_color(t.ink).child(shown) + }) + .when(focused, |d| { + d.child(div().flex_none().w(px(1.)).h(px(16.)).bg(t.ink)) + }) + .on_click(cx.listener(|this, _: &ClickEvent, window, cx| { + window.focus(&this.mods.focus); + cx.notify(); + })) + .on_key_down(cx.listener(|this, ev: &KeyDownEvent, window, cx| { + let k = &ev.keystroke; + let command = k.modifiers.control || k.modifiers.platform; + match type_key( + &mut this.mods.text, + false, + &k.key, + k.key_char.as_deref(), + command, + ) { + Key::Enter => this.mods_search(0), + Key::Escape => window.blur(), + Key::Paste => { + if let Some(text) = cx.read_from_clipboard().and_then(|c| c.text()) { + let line = text.lines().next().unwrap_or_default().trim().to_string(); + this.mods.text.push_str(&line); + } + } + Key::Edited => {} + Key::Pass => return, + } + if let Some((at, _)) = this.mods.text.char_indices().nth(100) { + this.mods.text.truncate(at); + } + cx.stop_propagation(); + cx.notify(); + })) + } + + pub(super) fn mods_page(&mut self, cx: &mut Context) -> Div { + let t = self.theme; + if !self.mods.loaded { + self.mods.loaded = true; + self.mods.installed = installed::Installed::load(&backend::game_home()).entries; + self.mods_check_updates(); + self.mods_search(0); + } + let header = page_header( + "Mods", + "Resource packs, shader packs and modpacks that Horizon loads. Each file is checked \ + against its source's checksum before it reaches your game folder.", + &t, + ); + let this = cx.entity().downgrade(); + let kinds = segments("mods-kind", &KINDS, self.mods.kind, &t, { + let this = this.clone(); + move |kind, _, cx| { + let _ = this.update(cx, |this, cx| { + if this.mods.kind != kind { + this.mods.kind = kind; + this.mods_search(0); + } + cx.notify(); + }); + } + }); + let everything = self.mods.everything; + let toggle = div() + .id("mods-everything") + .flex() + .items_center() + .gap(px(8.)) + .cursor_pointer() + .child(switch("mods-everything-switch", everything, &t)) + .child( + text(theme::LABEL) + .text_color(t.ink_soft) + .child("Show everything"), + ) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.mods.everything = !this.mods.everything; + this.mods_search(0); + cx.notify(); + })); + let source_note = if self.mods.curseforge { + segments("mods-source", &SOURCES, self.mods.source, &t, { + let this = this.clone(); + move |source, _, cx| { + let _ = this.update(cx, |this, cx| { + if this.mods.source != source { + this.mods.source = source; + this.mods_search(0); + } + cx.notify(); + }); + } + }) + .into_any_element() + } else { + text(theme::CAPTION) + .text_color(t.muted) + .child("From Modrinth. CurseForge comes once the launcher has its API key.") + .into_any_element() + }; + let controls = div() + .flex() + .flex_col() + .gap(px(12.)) + .child( + div() + .flex() + .flex_wrap() + .items_center() + .gap(px(12.)) + .child(kinds) + .child(self.mods_field(cx)) + .child(toggle), + ) + .child(source_note); + let mut page = div() + .flex() + .flex_col() + .gap(px(32.)) + .child(header) + .child(controls); + if let Some((_, line, f)) = &self.mods.busy { + page = page.child( + plate(&t) + .flex() + .flex_col() + .gap(px(8.)) + .p(px(16.)) + .child(caps("Installing").text_color(t.accent)) + .child( + text(theme::CAPTION) + .font_family(theme::MONO) + .text_color(t.ink_soft) + .truncate() + .child(format!("{line} {:.0}%", f * 100.)), + ), + ); + } + match &self.mods.message { + Some(Ok(done)) => { + page = page.child( + plate(&t) + .p(px(16.)) + .text_size(px(theme::UI.px)) + .text_color(t.ink) + .child(done.clone()), + ) + } + Some(Err(e)) => page = page.child(notice(e.clone(), &t)), + None => {} + } + if let Some(list) = self.mods_installed_list(cx) { + page = page.child(list); + } + page.child(self.mods_results(cx)) + } + + fn mods_installed_list(&self, cx: &mut Context) -> Option
{ + let t = self.theme; + let kind = self.mods.kind; + let entries: Vec<&installed::Entry> = self + .mods + .installed + .iter() + .filter(|e| e.kind == kind) + .collect(); + if entries.is_empty() { + return None; + } + let busy = self.mods.busy.is_some(); + let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, e) in entries.into_iter().enumerate() { + let key = (e.source, e.project.clone()); + let mut right = div().flex().items_center().gap(px(8.)); + if let Some(number) = self.mods.updates.get(&key) { + let mut update = button( + SharedString::from(format!("mods-update-{}", e.project)), + format!("Update to {number}"), + Kind::Secondary, + &t, + ); + if busy { + update = disabled(update); + } else { + let (source, id) = key.clone(); + update = update.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.mods_install(source, id.clone(), None); + cx.notify(); + })); + } + right = right.child(update); + } + let confirming = self.mods.confirm_remove.as_deref() == Some(e.project.as_str()); + let id = e.project.clone(); + let remove = button( + SharedString::from(format!("mods-remove-{}", e.project)), + if confirming { + "Remove for good" + } else { + "Remove" + }, + if confirming { + Kind::Secondary + } else { + Kind::Ghost + }, + &t, + ) + .when(confirming, |b| b.text_color(t.danger)) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + if this.mods.confirm_remove.as_ref() == Some(&id) { + let home = backend::game_home(); + this.mods.message = Some( + installed::remove(&home, &id).map(|e| format!("Removed {}.", e.title)), + ); + this.mods.installed = installed::Installed::load(&home).entries; + this.mods.confirm_remove = None; + } else { + this.mods.confirm_remove = Some(id.clone()); + } + cx.notify(); + })); + right = right.child(remove); + let detail = div() + .flex() + .flex_col() + .child(format!( + "{} · from {}{} · {}", + e.number, + e.source.label(), + if e.dependency { + ", needed by another pack" + } else { + "" + }, + e.file + )) + .child( + div() + .font_family(theme::MONO) + .child(format!("checked: {}", short_sum(&e.checksum))), + ); + list = list.child(index_row( + i + 1, + e.title.clone(), + Some(detail.into_any_element()), + Some(right.into_any_element()), + &t, + )); + } + Some( + div() + .flex() + .flex_col() + .gap(px(12.)) + .child(caps("Installed").text_color(t.muted)) + .child(list), + ) + } + + fn mods_results(&self, cx: &mut Context) -> Div { + let t = self.theme; + let m = &self.mods; + if let Some(e) = &m.error { + return div().child(notice(e.clone(), &t)); + } + if m.results.is_empty() { + let line = if m.searching || !m.searched { + "Searching…" + } else if m.everything { + "Nothing found." + } else { + "Nothing found that runs in Horizon. Show everything lists the rest." + }; + return centered(line, &t); + } + let busy = m.busy.as_ref().map(|b| b.0.as_str()); + let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, p) in m.results.iter().enumerate() { + let support = p.support(); + let color = match support { + Support::Works => t.success, + Support::Partial(_) => t.accent, + Support::No(_) => t.muted, + }; + let mut right = div() + .flex() + .items_center() + .gap(px(8.)) + .child(caps(support.label()).flex_none().text_color(color)); + let page_url = p.page.clone(); + if !page_url.is_empty() { + right = right.child( + button( + SharedString::from(format!("mods-page-{}", p.id)), + "Page", + Kind::Ghost, + &t, + ) + .on_click(move |_, _, cx| cx.open_url(&page_url)), + ); + } + if busy == Some(p.id.as_str()) { + right = right.child(caps("Installing").text_color(t.accent)); + } else if m.entry(p).is_some() { + right = right.child(caps("Installed").text_color(t.muted)); + } else if support.installable() { + let label = if p.kind == PackKind::Modpack { + "Import" + } else { + "Install" + }; + let mut install = button( + SharedString::from(format!("mods-install-{}", p.id)), + label, + Kind::Secondary, + &t, + ); + if busy.is_some() { + install = disabled(install); + } else { + let p = p.clone(); + install = install.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.mods_install(p.source, p.id.clone(), Some(p.clone())); + cx.notify(); + })); + } + right = right.child(install); + } + let mut by = Vec::new(); + if !p.author.is_empty() { + by.push(format!("by {}", p.author)); + } + by.push(format!("{} downloads", count(p.downloads))); + by.push(format!("from {}", p.source.label())); + if !p.license.is_empty() { + by.push(p.license.clone()); + } + let detail = div() + .flex() + .flex_col() + .child(div().truncate().child(p.summary.clone())) + .child(by.join(" · ")) + .children( + support + .reason() + .map(|r| div().text_color(t.ink_soft).child(r.to_string())), + ); + list = list.child(index_row( + i + 1, + p.title.clone(), + Some(detail.into_any_element()), + Some(right.into_any_element()), + &t, + )); + } + let mut out = div().flex().flex_col().child(list); + if m.more { + let mut more = button("mods-more", "More", Kind::Ghost, &t); + if m.searching { + more = disabled(more); + } else { + let offset = m.results.len(); + more = more.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.mods_search(offset); + cx.notify(); + })); + } + out = out.child(div().flex().pt(px(16.)).child(more)); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn counts_and_checksums_read_short() { + assert_eq!(count(999), "999"); + assert_eq!(count(1_500), "1.5k"); + assert_eq!(count(51_404_735), "51.4M"); + let sum = format!("SHA-512:{}", "ab".repeat(64)); + assert_eq!(short_sum(&sum), "SHA-512 abababababab…abababab"); + assert_eq!(short_sum("SHA-1:abcd"), "SHA-1:abcd"); + } +} diff --git a/launcher/src/servers_page.rs b/launcher/src/servers_page.rs index 625b6ffab..b1338f1aa 100644 --- a/launcher/src/servers_page.rs +++ b/launcher/src/servers_page.rs @@ -291,7 +291,7 @@ fn bytes(n: u64) -> String { /// A backup's date and kind from its name (`2026-10-19_11-28-57-manual.zip`, UTC), for people. /// What a key did in a one-line field. #[derive(Debug, PartialEq)] -enum Key { +pub(super) enum Key { Enter, Escape, /// Command/Ctrl-V: the caller pastes the clipboard's first line. @@ -303,7 +303,7 @@ enum Key { /// Types `key` into `text`. A `selected` suggestion is replaced by what's typed or pasted, and /// cleared by Backspace. -fn type_key( +pub(super) fn type_key( text: &mut String, selected: bool, key: &str, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaParticleProvidersOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaParticleProvidersOracle.java index f060351b3..85fb5ecd9 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaParticleProvidersOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaParticleProvidersOracle.java @@ -48,8 +48,9 @@ import org.jspecify.annotations.Nullable; /** Builds each particle through its real registered ParticleProvider (the real * ParticleResources, sprite sets bound to stand-in sprites named after the * vanilla particles/*.json textures) in a stand-in ClientLevel (air, an - * optional stone floor at y 63, no fluids), then ticks it and records its - * state, the particles and sounds it asks the level for, tick by tick. + * optional stone floor at y 63, optionally still water from y 64 to 67), + * then ticks it and records its state, the particles and sounds it asks the + * level for, tick by tick. * * Each vanilla Particle owns a RandomSource.create() random seeded from the * clock; its seed is recovered after construction (the SEED_UNIQUIFIER value @@ -67,13 +68,18 @@ public final class VanillaParticleProvidersOracle { static T make(Class type) throws Exception { return type.cast(allocate.invoke(unsafe, type)); } static final class Level0 extends ClientLevel { - boolean floor; + boolean floor, water; List events; Level0() { super(null, null, null, null, 0, 0, null, false, 0L, 0); } + // Water: still water sources from y 64 to 67 (above the floor, below the open air). + boolean wet(BlockPos p) { return water && p.getY() >= 64 && p.getY() <= 67; } @Override public BlockState getBlockState(BlockPos p) { + if (wet(p)) return Blocks.WATER.defaultBlockState(); return floor && p.getY() == 63 ? Blocks.STONE.defaultBlockState() : Blocks.AIR.defaultBlockState(); } - @Override public FluidState getFluidState(BlockPos p) { return Fluids.EMPTY.defaultFluidState(); } + @Override public FluidState getFluidState(BlockPos p) { + return wet(p) ? Fluids.WATER.getSource(false) : Fluids.EMPTY.defaultFluidState(); + } @Override public @Nullable BlockGetter getChunkForCollisions(int x, int z) { return this; } @Override public boolean hasChunkAt(BlockPos p) { return false; } @Override public void addParticle(ParticleOptions o, double x, double y, double z, double xd, double yd, double zd) { @@ -258,6 +264,7 @@ public final class VanillaParticleProvidersOracle { long seed = c.get("seed").getAsLong(); RandomSource random = null; level.floor = c.get("floor").getAsBoolean(); + level.water = c.has("water") && c.get("water").getAsBoolean(); level.events.clear(); var p = c.getAsJsonArray("pos"); var v = c.getAsJsonArray("vel"); Particle particle = null; diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 40c081a5a..38bf2a68c 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -20,6 +20,10 @@ address. The script then checks, from both sides, what a guest's game used to ge drowning and the void (then respawns); - pvp: the guest and the host hit each other with a sword; with the pvp game rule off, or on one team without friendly fire, nothing; +- kills: a pig the guest kills counts in the guest's killed statistic, not the host's (#484); + + +- arrows: the guest and the host shoot each other with a bow; with the pvp game rule off, nothing (#484); - respawn: a player killed is drawn dead by the other side, and alive again once it respawns (the respawned player is a new entity to the others); the host dies, and on the server thread the guest too; @@ -52,6 +56,9 @@ address. The script then checks, from both sides, what a guest's game used to ge its crafting grid and gathers a stack with a double click; the server has each. - sleep: at night the guest lies down in its own bed (not the host); alone it stays night, it gets up with Escape, and once the host sleeps too the night ends and both wake. +- predict: with the host frozen, the oak door the guest opens opens on the guest's screen at once (its + prediction) and creaks there at once, stays open once the server answers, and each side hears + it once; an iron door stays shut (#869). - push: a cow standing in the guest pushes it just clear of the cow (the guest's own client pushes it, as in vanilla), not ever faster across the ground. - eat: holding right click with bread, the guest's own screen plays the eating (the item in use @@ -64,6 +71,17 @@ address. The script then checks, from both sides, what a guest's game used to ge guest as the host has them (kind, place, rotation, what they hold or wear, the variant). - projectiles: primed TNT (one falling), an end crystal and an arrow that lands reach the guest where the host has them; a falling block lands on both sides. +- fireball: a fire charge a dispenser shoots onto stone lights a fire both sides see, and the fire + goes out on its own within a minute (it ticks: FireBlock.tick on a floor that doesn't burn) + + +- blast: primed TNT going off beside a guest in survival hurts the guest and pushes it away + (ServerExplosion.hurtEntities takes every player); facing it behind a raised shield, the + guest takes nothing. + + +- worn: iron armour the guest puts on in its inventory protects it: a 10-damage blow takes 6 + (armour 15, LivingEntity.getDamageAfterArmorAbsorb), and the full 10 without it. - plates: a stone pressure plate the guest steps on is pressed on both sides, and comes up once the guest steps off (#848). - swings: each side sees the other's arm swing while it mines a block, and the guest sees its own @@ -94,6 +112,7 @@ macOS both games render offscreen. Games started here have no audio (HORIZON_NO_ """ import argparse import json +import math import os import re import shutil @@ -114,7 +133,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight'] class Game: @@ -623,12 +642,76 @@ def check_pvp(host, guest, out): host('command', command='team remove parity_allies') assert hits['guest hits host'][1] < hits['guest hits host'][0], f'the guest did not hurt the host: {hits}' assert hits['host hits guest'][1] < hits['host hits guest'][0], f'the host did not hurt the guest: {hits}' - assert hits['pvp off'][1] == hits['pvp off'][0], f'pvp off still hurts: {hits}' + # Natural regeneration may heal the victim meanwhile. + assert hits['pvp off'][1] >= hits['pvp off'][0], f'pvp off still hurts: {hits}' for name in ('guest hits teammate', 'host hits teammate'): assert hits[name][1] == hits[name][0], f'friendly fire off still hurts ({name}): {hits}' return hits +def check_kills(host, guest, out): + # A mob the guest kills is the guest's kill (#484): LivingEntity.die credits lastHurtByPlayer, so the + # killed statistic (and its scoreboard criterion) counts for the guest, not the host. + host('command', command='scoreboard objectives add parity_kills minecraft.killed:minecraft.pig') + for g in (host, guest): + g('command', command='gamemode survival') + guest('command', command='item replace entity @s weapon.mainhand with minecraft:iron_sword') + face_each_other(host, guest) + hx, hy, hz = pos_of(host) + try: + # Between the two, in front of the guest, with one health left. + host('command', command=f'summon minecraft:pig {hx + 1.5:.2f} {hy:.2f} {hz:.2f} {{NoAI:1b,Health:1.0f}}') + guest.wait(30) + guest.raw('look-at', f'{hx + 1.5:.2f}', f'{hy + 0.5:.2f}', f'{hz:.2f}') + guest.wait(10) + guest.raw('attack') + guest.wait(20) + host('command', command=f'scoreboard players get {GUEST_NAME} parity_kills') + host('command', command=f'scoreboard players get {host.player} parity_kills') + host.wait(10) + chat = host.raw('messages', 10)['chat'] + guest.shot(out, 'kills') + finally: + host('command', command='kill @e[type=minecraft:pig]') + host('command', command='scoreboard objectives remove parity_kills') + assert any(f'{GUEST_NAME} has 1 [parity_kills]' in line for line in chat), f"the guest's kill is not theirs: {chat}" + assert not any(f'{host.player} has 1 [parity_kills]' in line for line in chat), f"the host got the guest's kill: {chat}" + return chat + + +def check_arrows(host, guest, out): + # A player's arrow on another player (#484): AbstractArrow.onHitEntity, refused by + # ServerPlayer.canHarmPlayer with the pvp game rule off (the arrow turns back). + for g in (host, guest): + g('command', command='gamemode survival') + g('command', command='clear @s') + g('command', command='item replace entity @s weapon.mainhand with minecraft:bow') + g('command', command='give @s minecraft:arrow 16') + hits = {} + try: + for name, rule, shooter in (('guest shoots host', 'true', guest), ('host shoots guest', 'true', host), + ('pvp off', 'false', guest)): + host('command', command=f'gamerule pvp {rule}') + for g in (host, guest): + g('command', command='effect give @s minecraft:instant_health 1 5') + face_each_other(host, guest) + shooter.wait(20) + victim = (lambda: host('state')['player']['health']) if shooter is guest else (lambda: remote(guest)['health']) + before = victim() + shooter.raw('use-item', '--hold', 1.3) # a full draw (BowItem: 20 ticks) + shooter.wait(20) + hits[name] = (before, victim()) + shooter.shot(out, 'arrows-' + name.replace(' ', '-')) + finally: + host('command', command='gamerule pvp true') + for g in (host, guest): + g('command', command='clear @s') + assert hits['guest shoots host'][1] < hits['guest shoots host'][0], f"the guest's arrow did not hurt the host: {hits}" + assert hits['host shoots guest'][1] < hits['host shoots guest'][0], f"the host's arrow did not hurt the guest: {hits}" + assert hits['pvp off'][1] >= hits['pvp off'][0], f'pvp off, an arrow still hurts: {hits}' + return hits + + def dead_players(game, want, ticks=60): """The other players `game`'s client draws dead, once that is `want` (empty or not) or after `ticks`.""" for _ in range(ticks // 5): @@ -1271,6 +1354,50 @@ def check_sleep(host, guest, out): assert lying['host'] and lying['guest'], f'a sleeping player is drawn standing: {detail}' assert not lying['after'], f'a player up again is still drawn lying: {detail}' return detail +def check_predict(host, guest, out): + # MultiPlayerGameMode.useItemOn under startPrediction (#869): the guest's door opens on its own screen + # at once, with the host (the server) frozen, and the server's answer later agrees; an iron door + # (no hand use) stays shut on both sides. + guest('command', command='gamemode survival') + guest('command', command='clear @s') + x, y, z = (int(v // 1) for v in pos_of(guest)) + wood, iron = (x - 1, y, z + 2), (x + 1, y, z + 2) + for (bx, by, bz), kind in ((wood, 'oak_door'), (iron, 'iron_door')): + for half, dy in (('lower', 0), ('upper', 1)): + host('command', command=f'setblock {bx} {by + dy} {bz} minecraft:{kind}[facing=north,hinge=right,half={half}]') + guest.wait(20) + state = lambda game, at: game.raw('block', *at)['state'] + seen = {} + creaks = lambda game: sum(n for s, n in game('status')['heard'].items() if 'door' in s) + heard = {'guest': creaks(guest), 'host': creaks(host)} + os.kill(host.pid, signal.SIGSTOP) + try: + guest.raw('interact', *wood) + seen['guest_frozen'] = (state(guest, wood), state(guest, (wood[0], wood[1] + 1, wood[2]))) + # level.playSound(player, ...): the clicker hears its own door at once. + seen['guest_heard_frozen'] = creaks(guest) - heard['guest'] + guest.raw('interact', *iron) + seen['guest_iron_frozen'] = state(guest, iron) + finally: + os.kill(host.pid, signal.SIGCONT) + guest.wait(20) + seen['guest_after'] = state(guest, wood) + seen['host_after'] = state(host, wood) + seen['iron_after'] = (state(guest, iron), state(host, iron)) + # ... and not a second time from the server; the host hears it once. + seen['heard_after'] = {'guest': creaks(guest) - heard['guest'], 'host': creaks(host) - heard['host']} + guest.shot(out, 'predict') + for (bx, by, bz) in (wood, iron): + host('command', command=f'fill {bx} {by} {bz} {bx} {by + 1} {bz} minecraft:air') + assert all('open=true' in s for s in seen['guest_frozen']), f'the door waited for the server: {seen}' + assert 'open=true' in seen['guest_after'] and 'open=true' in seen['host_after'], f'the door did not stay open: {seen}' + assert 'open=false' in seen['guest_iron_frozen'], f'the guest opened an iron door by hand: {seen}' + assert all('open=false' in s for s in seen['iron_after']), f'an iron door opened: {seen}' + assert seen['guest_heard_frozen'] == 1 and seen['heard_after'] == {'guest': 1, 'host': 1}, \ + f'the door is not heard once on each side: {seen}' + return seen + + def check_push(host, guest, out): guest('command', command='gamemode survival') x, y, z = (int(v // 1) + 0.5 for v in pos_of(guest)) @@ -1600,6 +1727,56 @@ def check_projectiles(host, guest, out): return f'{len(theirs)} identical, fuses (host, guest) {fuses}' +def check_blast(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + host('command', command='gamemode creative') + x, y, z = (int(v // 1) for v in pos_of(host)) + gx, gz = x + 6, z + floor = f'fill {gx - 6} {y - 1} {gz - 4} {gx + 6} {y - 1} {gz + 4} minecraft:bedrock' + detail = {} + try: + for shielded in (False, True): + if remote(guest)['health'] <= 0: + guest.raw('respawn') + guest.wait(40) + host('command', command=floor) + host('command', command=f'fill {gx - 6} {y} {gz - 4} {gx + 6} {y + 3} {gz + 4} minecraft:air') + guest('command', command=f'tp @s {gx + 0.5} {y} {gz + 0.5}') + guest('command', command='effect give @s minecraft:instant_health 1 5') + guest.wait(30) + hold = None + if shielded: + guest('command', command='item replace entity @s weapon.offhand with minecraft:shield') + guest.wait(5) + guest.raw('look-at', gx + 5.5, y + 0.5, gz + 0.5) + hold = threading.Thread(target=guest.raw, args=('use-item', '--hold', 2.5)) + hold.start() + time.sleep(0.5) + before = remote(guest)['health'] + at = pos_of(guest) + # Five blocks off: a blast that hurts without killing (about 14 at full exposure). + host('command', command=f'summon minecraft:tnt {gx + 5.5} {y} {gz + 0.5} {{fuse:10s}}') + # The guest's own controller is busy holding the shield up: the host waits. + host.wait(14) + after = remote(guest)['health'] + moved = pos_of(guest) + if hold: + hold.join() + guest.shot(out, f'blast-{"shield" if shielded else "open"}') + detail['shield' if shielded else 'open'] = { + 'before': before, 'after': after, 'pushed': round(at[0] - moved[0], 2)} + finally: + host('command', command='gamemode survival') + guest('command', command='clear @s') + host('command', command=floor) + open_, shield = detail['open'], detail['shield'] + assert open_['after'] < open_['before'], f'the blast never hurt the guest: {detail}' + assert open_['pushed'] > 0, f'the blast never pushed the guest away: {detail}' + assert shield['after'] >= shield['before'], f'the shield did not stop the blast: {detail}' + return detail + + def light_differences(host, guest, lo, hi): """Positions of the box loaded on both sides, and those whose sky or block light differ.""" h, g = host.raw('light', *lo, *hi), guest.raw('light', *lo, *hi) @@ -1757,6 +1934,203 @@ def check_light(host, guest, out): return results +def check_fireball(host, guest, out): + x, y, z = (int(v // 1) for v in pos_of(host)) + fx, fz = x + 4, z + # A stone floor, a dispenser facing down three blocks over it, a fire charge in it, powered. + host('command', command=f'fill {fx - 2} {y - 1} {fz - 2} {fx + 2} {y - 1} {fz + 2} minecraft:stone') + host('command', command=f'fill {fx - 2} {y} {fz - 2} {fx + 2} {y + 4} {fz + 2} minecraft:air') + host('command', command=f'setblock {fx} {y + 3} {fz} minecraft:dispenser[facing=down]') + host('command', command=f'item replace block {fx} {y + 3} {fz} container.0 with minecraft:fire_charge') + seen, gone = {}, None + try: + host('command', command=f'setblock {fx} {y + 4} {fz} minecraft:redstone_block') + host.wait(10) + seen = {'host': host.raw('block', fx, y, fz).get('block'), + 'guest': guest.raw('block', fx, y, fz).get('block')} + # FireBlock.tick every 30-39 ticks ages it by one a third of the time; past age 3 it goes. + for waited in range(40, 1240, 40): + host.wait(40) + if host.raw('block', fx, y, fz).get('block') == 'minecraft:air': + gone = waited + break + guest.wait(5) + seen['guest_after'] = guest.raw('block', fx, y, fz).get('block') + finally: + host('command', command=f'fill {fx - 2} {y} {fz - 2} {fx + 2} {y + 4} {fz + 2} minecraft:air') + assert seen.get('host') == 'minecraft:fire' and seen.get('guest') == 'minecraft:fire', \ + f'no fire where the fire charge landed: {seen}' + assert gone is not None, f'the fire on stone never went out (1200 ticks): {seen}' + assert seen['guest_after'] == 'minecraft:air', f'the guest still sees the fire: {seen}' + return {'out_after_ticks': gone, **seen} + + +def check_deflect(host, guest, out): + """The host punches a ghast's fireball back: it flies along the host's view and kills the ghast + (Player.attack: AIM_DEFLECT on #redirectable_projectile; Ghast.isReflectedFireball). The ghast is caged + (a window toward the host); the game runs at 4 ticks a second, and once the fireball is within 4.5 blocks + the host looks at the ghast and clicks.""" + if SERVER_THREAD: + # The fireball's position and the host's hurts are read from the host's own level. + return 'skipped (in-frame only)' + x, y, z = (int(v // 1) for v in pos_of(host)) + guest('command', command='gamemode creative') + host('command', command='gamemode survival') + host('command', command='difficulty normal') + gx, gz = x, z + 30 + gy = y + 20 + host('command', command=f'fill {gx - 3} {gy - 1} {gz - 3} {gx + 24} {gy - 1} {gz + 3} minecraft:glass') + host('command', command=f'fill {gx - 3} {gy} {gz - 3} {gx + 24} {gy + 8} {gz + 3} minecraft:air') + host('command', command=f'tp @s {gx + 0.5} {gy} {gz + 0.5} -90 0') + host.wait(20) + host.raw('hurtlog') + # The ghast in a glass cage it can't drift out of, a 3 x 3 window toward the host. + host('command', command=f'fill {gx + 13} {gy} {gz - 3} {gx + 19} {gy + 6} {gz + 3} minecraft:glass hollow') + host('command', command=f'fill {gx + 13} {gy + 2} {gz - 1} {gx + 13} {gy + 4} {gz + 1} minecraft:air') + host('command', command=f'summon minecraft:ghast {gx + 16.5} {gy + 1} {gz + 0.5}') + eye = (gx + 0.5, gy + 1.62, gz + 0.5) + host('command', command='tick rate 4') + turned, near, ghast, hurt = None, None, None, [] + try: + deadline = time.monotonic() + 120 + while time.monotonic() < deadline: + balls = [q for q in host.raw('status')['projectiles'] if q['kind'] == 'LargeFireball'] + near = min((math.dist(q['position'], eye) for q in balls), default=None) + if near is not None and near < 4.5: + g = [m['pos'] for m in host.raw('mobs', 60).get('near', []) if m['kind'].endswith('ghast')][0] + host.raw('look-at', f'{g[0]:.2f}', f'{g[1] + 2:.2f}', f'{g[2]:.2f}') + host.raw('mouse', 'left', 'down') + host.raw('mouse', 'left', 'up') + turned = near + break + host('command', command='tick rate 20') + host.wait(60) + ghast = [m for m in host.raw('mobs', 60).get('near', []) if m['kind'].endswith('ghast') and m['health'] > 0] + hurt = [h for pl in host.raw('hurtlog')['players'] if pl['name'] == 'host' for h in pl['hurts'] + if 'fireball' in h['source'] or 'explosion' in h['source']] + finally: + host('command', command='tick rate 20') + host('command', command='kill @e[type=minecraft:ghast]') + host('command', command=f'fill {gx - 3} {gy - 1} {gz - 3} {gx + 24} {gy + 8} {gz + 3} minecraft:air') + guest('command', command='gamemode survival') + assert turned is not None, f'no fireball came within 4.5 blocks (nearest {near})' + assert not hurt, f'the host was hit: {hurt}' + assert not ghast, f'the ghast lived: the fireball was not turned back ({ghast})' + return {'struck_at': round(turned, 2)} + + +def check_barter(host, guest, out): + """The guest, in gold boots, drops a gold ingot to a piglin: the piglin stays calm, takes it, and throws its + barter toward the nearest player, the guest (PiglinAi.throwItemsTowardPlayer: NEAREST_VISIBLE_PLAYER), who + picks it up. The host is nearby on the other side, so a barter thrown at the host misses the guest. A glass + corridor (the hollow box) keeps the piglin between them.""" + x, y, z = (int(v // 1) for v in pos_of(host)) + cz = z + 4 + host('command', command='gamemode creative') + guest('command', command='gamemode survival') + guest('command', command='clear @s') + guest('command', command='effect give @s minecraft:instant_health 1 5') + host('command', command=f'fill {x + 1} {y - 1} {cz - 1} {x + 8} {y + 2} {cz + 1} minecraft:glass hollow') + host('command', command=f'fill {x + 2} {y - 1} {cz} {x + 7} {y - 1} {cz} minecraft:stone') + host('command', command=f'tp @s {x - 0.5} {y} {cz + 0.5} -90 0') + guest('command', command=f'tp @s {x + 7.3} {y} {cz + 0.5} 90 30') + guest('command', command='item replace entity @s armor.feet with minecraft:golden_boots') + guest('command', command='give @s minecraft:gold_ingot 1') + host('command', command=f'summon minecraft:piglin {x + 4.5} {y} {cz + 0.5} {{IsImmuneToZombification:1b}}') + guest.wait(20) + before = remote(guest)['health'] + kept = dict(guest('inventory')['counts']) + try: + guest.raw('select', 'minecraft:gold_ingot') + guest.raw('key', 'q', 'tap') + bought, trace = {}, [] + for _ in range(20): + guest.wait(20) + trace.append([(e['type'].split(':')[-1], round(e['pos'][0] - x, 1), round(e['pos'][2] - cz, 1)) + for e in host.raw('entities', 24)['entities'] if e['type'] in ('minecraft:item', 'minecraft:piglin')]) + counts = guest('inventory')['counts'] + bought = {k: n - kept.get(k, 0) for k, n in counts.items() + if k not in ('minecraft:gold_ingot', 'minecraft:golden_boots') and n > kept.get(k, 0)} + if bought: + guest.wait(40) + break + counts = guest('inventory')['counts'] + bought = {k: n - kept.get(k, 0) for k, n in counts.items() + if k not in ('minecraft:gold_ingot', 'minecraft:golden_boots') and n > kept.get(k, 0)} + piglins = [m for m in host.raw('mobs', 20).get('near', []) if m['kind'].split(':')[-1] == 'piglin'] + health = remote(guest)['health'] + finally: + host('command', command=f'kill @e[type=minecraft:piglin,x={x},y={y - 2},z={cz - 2},dx=10,dy=6,dz=4]') + # What lies on the floor, on the host's side of the piglin's start and on the guest's. + floor = [host('command', command=f'kill @e[type=minecraft:item,x={x0},y={y - 2},z={cz - 3},dx={dx},dy=6,dz=6]') + ['chat'][0] for x0, dx in ((x - 2, 6.5), (x + 4.5, 6))] + host('command', command=f'fill {x + 1} {y - 1} {cz - 1} {x + 8} {y + 2} {cz + 1} minecraft:air') + host('command', command=f'fill {x - 8} {y - 1} {z - 8} {x + 8} {y - 1} {z + 8} minecraft:stone') + guest('command', command='clear @s') + host('command', command='gamemode survival') + assert piglins, 'the piglin is gone' + assert health >= before, f'the piglin hurt the guest in gold boots: {before} -> {health}' + assert bought, f'no barter reached the guest (on the floor, host side then guest side: {floor}; items and the piglin, every second: {trace})' + return {'bought': bought, 'floor': floor} + + +def check_worn(host, guest, out): + pieces = ['iron_helmet', 'iron_chestplate', 'iron_leggings', 'iron_boots'] + guest('command', command='gamemode survival') + taken = {} + try: + for worn in (False, True): + guest('command', command='clear @s') + if remote(guest)['health'] <= 0: + guest.raw('respawn') + guest.wait(40) + if worn: + for piece in pieces: + guest('command', command=f'give @s minecraft:{piece}') + guest.wait(10) + # Shift-clicked from the hotbar onto the body in the inventory menu (the hub moves them). + guest.raw('key', 'e', 'tap') + guest.raw('wait-for', 'screen', 'inventory') + for piece in pieces: + guest.raw('click-slot', hotbar_slot(guest, f'minecraft:{piece}'), 'shift') + guest.wait(2) + guest.raw('key', 'esc', 'tap') + guest.wait(5) + guest('command', command='effect give @s minecraft:instant_health 1 5') + guest.wait(30) + before = remote(guest)['health'] + if not SERVER_THREAD: + host.raw('hurtlog') + # A mob's blow (no attacker: no difficulty scaling); armour counts against it. + guest('command', command='damage @s 10 minecraft:mob_attack') + if SERVER_THREAD: + # The server's hurt log isn't on a control socket here: the health the guest is + # sent, read as soon as it drops (natural regeneration heals it again after). + health = before + for _ in range(40): + guest.wait(1) + health = remote(guest)['health'] + if health < before: + break + taken['worn' if worn else 'bare'] = [round(before - health, 2)] + continue + guest.wait(10) + log = [h for p in host.raw('hurtlog')['players'] if p['name'] == GUEST_NAME for h in p['hurts']] + taken['worn' if worn else 'bare'] = [(h['amount'], h['armor'], round(h['taken'], 2)) for h in log] + finally: + guest('command', command='clear @s') + guest('command', command='effect give @s minecraft:instant_health 1 5') + if SERVER_THREAD: + # Natural regeneration may heal up to a point before the health arrives. + assert len(taken['bare']) == 1 and 9.0 <= taken['bare'][0] <= 10.0, f'10 damage on no armour: {taken}' + assert len(taken['worn']) == 1 and 5.0 <= taken['worn'][0] <= 6.0, \ + f'10 damage through iron armour (15) should take 6: {taken}' + return taken + assert taken['bare'] == [(10.0, 0.0, 10.0)], f'10 damage on no armour: {taken}' + assert taken['worn'] == [(10.0, 15.0, 6.0)], f'10 damage through iron armour (15) should take 6: {taken}' + return taken + + CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, @@ -1769,10 +2143,10 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls, 'effects': check_effects, 'portals': check_portals, 'distance': check_distance, 'clicks': check_clicks, 'sleep': check_sleep, 'push': check_push, 'eat': check_eat, 'eating': check_eating, - 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, + 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth, 'flight': check_flight} + 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict} def run(ctl, out, resources, checks): @@ -1781,7 +2155,7 @@ def run(ctl, out, resources, checks): host.d.env['HORIZON_SERVER_THREAD'] = '1' results = {} try: - host('launch', wait=False, offscreen=sys.platform == 'darwin') + host.pid = host('launch', wait=False, offscreen=sys.platform == 'darwin')['pid'] # Guests' commands need the world's Allow Commands as well as the LAN's (#372): a creative # world has them; everyone plays in survival. host.raw('open', 'Lan', 5, 'creative') diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 6eda7583e..01ed4680f 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -268,6 +268,13 @@ def scenarios(): ('witch', 176), ('vindicator', 177), ('zombie', 178)]: add(f'{species}_deep_water', 160, ['fill -4 -64 -4 4 -61 4 minecraft:water', f'mob minecraft:{species} 0.5 -62 0.5 0 {seed} persistent']) + # Axolotls (#64): idle swimming, hunting a cod, and playing dead after hits, in a pool sunk into + # the ground so no water flows out of it (the probe doesn't tick fluids). + POOL = 'fill -5 -63 -5 5 -61 5 minecraft:water' + add('axolotl_hunting', 45, [POOL, 'player 12.5 -60 0.5', 'mob minecraft:axolotl 0.5 -62 0.5 0 12 persistent', + 'mob minecraft:cod 2.5 -62 0.5 0 13 persistent noai']) + add('axolotl_play_dead', 300, [POOL, 'player 12.5 -60 0.5', 'mob minecraft:axolotl 0.5 -62 0.5 0 28 persistent'] + + [f'hurt {t} 0' for t in range(4, 160, 12)]) return s diff --git a/tools/test_particle_providers_parity.py b/tools/test_particle_providers_parity.py index afd283359..2fdd510d9 100644 --- a/tools/test_particle_providers_parity.py +++ b/tools/test_particle_providers_parity.py @@ -35,7 +35,7 @@ spore_blossom_air totem_of_undying underwater vault_connection warped_spore whit sweep_attack glow wax_on wax_off electric_spark scrape squid_ink glow_squid_ink item_slime item_snowball item_cobweb sulfur_cube_goo firefly trial_spawner_detection trial_spawner_detection_ominous trial_omen raid_omen ominous_spawning spit fishing dust_plume red_poplar_leaves orange_poplar_leaves yellow_poplar_leaves pause_mob_growth -reset_mob_growth""".split() +reset_mob_growth sulfur_bubbles""".split() def options(kind, rng): @@ -78,6 +78,12 @@ def cases(rng): for vel in velocities: yield dict(type=kind, options=options(kind, rng), pos=pos, vel=vel, floor=floor, seed=rng.randrange(-2**63, 2**63), ticks=80) + # In still water (sources from y 64 to 67): the bubbles rise until they leave it. + for kind in ['sulfur_bubbles', 'bubble', 'bubble_column_up']: + for (pos, floor) in [([0.3125, 64.046875, -0.40625], True), ([-5.75, 66.59375, 3.125], False)]: + for vel in velocities: + yield dict(type=kind, options={}, pos=pos, vel=vel, floor=floor, water=True, + seed=rng.randrange(-2**63, 2**63), ticks=80) def make_cases(build): @@ -215,10 +221,10 @@ def main(): client_jar_sha256=lab.digest(jars['client'], 'sha256'), matched_output_lines=matched, output_sha256=lab.digest(build / 'rust.txt', 'sha256'), libm_tolerated_lines=tolerance, scope=('Real ParticleResources providers for every type Horizon implements, ticked in an air level with an optional ' - 'stone floor: construction (provider, level, SpellParticle and particle-local random draws), per-tick ' + 'stone floor and, for the bubbles, still water: construction (provider, level, SpellParticle and particle-local random draws), per-tick ' 'position, previous position, motion, age, lifetime, removal, onGround, quad size at partial 0 and 0.5, ' 'colour, alpha, roll, sprite, UVs and light at partial 0.5 (unloaded chunk), and the particles and sounds ' - 'requested from the level. Fluids, block light, render layers/facing and the ParticleEngine group limits ' + 'requested from the level. Flowing fluids, block light, render layers/facing and the ParticleEngine group limits ' 'are not exercised.'))) print(f'{units:,} particle cases match the pinned client ({matched:,} output lines, {tolerance} within ' f'the libm tolerance): {report}', flush=True)