diff --git a/crates/horizon-client/examples/tab_list_fixture.rs b/crates/horizon-client/examples/tab_list_fixture.rs new file mode 100644 index 000000000..b28ab6e41 --- /dev/null +++ b/crates/horizon-client/examples/tab_list_fixture.rs @@ -0,0 +1,172 @@ +//! Headless transport for the player list parity gate: builds each case's +//! scoreboard (teams, `list` objective, scores), listed players, header and +//! footer, replays its frames through `horizon_client::tab_list` and writes +//! the draw calls in vanilla's GuiGraphicsExtractor terms (text as styled +//! runs, faces as skin blits). +#![forbid(unsafe_code)] +use horizon_client::{ + component, + hud::HudAtlas, + lang, + scoreboard::{NumberFormat, RenderType, Scoreboard}, + tab_list::{self, TabDraw, TabInputs, TabList, TabPlayer}, + text::Text, +}; +use serde_json::{Value, json}; +use std::{ + fs, + io::{BufWriter, Write}, + path::PathBuf, +}; +type Result = std::result::Result>; + +fn text(v: &Value) -> Option { + (!v.is_null()).then(|| component::to_text(v, &mut |_| Text::empty())) +} +fn format(v: &Value) -> Option { + match v["type"].as_str()? { + "blank" => Some(NumberFormat::Blank), + "styled" => Some(NumberFormat::Styled(v["style"].clone())), + "fixed" => Some(NumberFormat::Fixed(v["value"].clone())), + _ => None, + } +} +fn runs(t: &Text) -> Value { + let mut out: Vec<(String, Value)> = Vec::new(); + for (c, s) in t.chars() { + let key = json!([ + s.color.map_or(-1, i64::from), + s.is_bold(), + s.is_italic(), + s.underlined == Some(true), + s.strikethrough == Some(true), + s.obfuscated == Some(true) + ]); + match out.last_mut() { + Some((run, k)) if *k == key => run.push(c), + _ => out.push((c.to_string(), key)), + } + } + out.into_iter().map(|(r, k)| json!([r, k])).collect() +} + +fn main() -> Result<()> { + let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); + let [root, inputs, output] = args.as_slice() else { + return Err("usage: tab_list_fixture RESOURCES INPUTS OUTPUT".into()); + }; + let atlas = HudAtlas::build(root)?; + lang::set(lang::Language::load(&[root], "en_us")); + let font = &atlas.font; + let mut out = BufWriter::new(fs::File::create(output)?); + for line in fs::read_to_string(inputs)? + .lines() + .filter(|l| !l.is_empty()) + { + let c: Value = serde_json::from_str(line)?; + let mut board = Scoreboard::default(); + for t in c["teams"].as_array().into_iter().flatten() { + let name = t["name"].as_str().unwrap_or(""); + let team = board.add_team(name); + team.color = t["color"].as_str().map(str::to_owned); + team.prefix = t["prefix"].clone(); + team.suffix = t["suffix"].clone(); + for m in t["members"].as_array().into_iter().flatten() { + board.add_to_team(m.as_str().unwrap_or(""), name); + } + } + let objective_name = c["objective"]["name"].as_str().map(str::to_owned); + if let Some(name) = &objective_name { + let hearts = c["objective"]["renderType"] == "hearts"; + board.add_objective( + name, + "dummy", + Value::String("x".into()), + if hearts { + RenderType::Hearts + } else { + RenderType::Integer + }, + false, + format(&c["objective"]["numberFormat"]), + ); + } + let mut players = Vec::new(); + let mut upside = Vec::new(); + for p in c["players"].as_array().into_iter().flatten() { + let uuid = + u128::from_str_radix(&p["uuid"].as_str().unwrap_or("0").replace('-', ""), 16)?; + let name = p["name"].as_str().unwrap_or("").to_owned(); + if p["inLevel"].as_bool().unwrap_or(false) && (name == "Dinnerbone" || name == "Grumm") + { + upside.push(uuid); + } + let mut player = TabPlayer::new(uuid, name); + player.game_mode = p["gameMode"].as_i64().unwrap_or(0) as i32; + player.latency = p["latency"].as_i64().unwrap_or(0) as i32; + player.display_name = (!p["displayName"].is_null()).then(|| p["displayName"].clone()); + player.list_order = p["listOrder"].as_i64().unwrap_or(0) as i32; + player.show_hat = p["showHat"].as_bool().unwrap_or(true); + players.push(player); + } + let mut list = TabList::default(); + list.header = text(&c["header"]); + list.footer = text(&c["footer"]); + let background = tab_list::row_background( + c["backgroundForChatOnly"].as_bool().unwrap_or(true), + c["opacity"].as_f64().unwrap_or(0.5), + ); + let mut frames = Vec::new(); + for f in c["frames"].as_array().into_iter().flatten() { + if let Some(obj) = &objective_name { + for (holder, v) in f["scores"].as_object().into_iter().flatten() { + let s = board.score_mut(holder, obj); + s.value = v["value"].as_i64().unwrap_or(0) as i32; + s.number_format = format(&v["format"]); + } + for r in f["reset"].as_array().into_iter().flatten() { + board.reset_one(r.as_str().unwrap_or(""), obj); + } + } + let visible = f["visible"].as_bool().unwrap_or(false); + list.set_visible(visible); + let mut draws = Vec::new(); + if visible { + let up = |id: u128| upside.contains(&id); + let inputs = TabInputs { + players: &players, + board: &board, + objective: objective_name.as_deref().and_then(|n| board.objective(n)), + screen_width: c["width"].as_i64().unwrap_or(0) as i32, + online_mode: c["onlineMode"].as_bool().unwrap_or(false), + gui_ticks: f["tick"].as_i64().unwrap_or(0), + background, + upside_down: &up, + }; + for d in list.layout(&inputs, font) { + match d { + TabDraw::Fill { x0, y0, x1, y1, color } => draws.push( + json!({"type": "fill", "x0": x0, "y0": y0, "x1": x1, "y1": y1, "color": color as i32}), + ), + TabDraw::Sprite { sprite, x, y, w, h } => { + draws.push(json!({"type": "sprite", "sprite": sprite, "x": x, "y": y, "w": w, "h": h})) + } + TabDraw::Text { text, x, y, color } => draws.push( + json!({"type": "text", "runs": runs(&text), "x": x, "y": y, "color": color as i32, "shadow": true}), + ), + TabDraw::Face { skin, x, y, size, hat, flip } => { + let (v, h) = if flip { (16.0, -8.0) } else { (8.0, 8.0) }; + for u in [8.0, 40.0].into_iter().take(if hat { 2 } else { 1 }) { + let a = [x as f64, y as f64, u, v, size as f64, size as f64, 8.0, h, 64.0, 64.0]; + draws.push(json!({"type": "blit", "texture": skin, "args": a, "color": -1})); + } + } + } + } + } + frames.push(Value::Array(draws)); + } + writeln!(out, "{}", json!({ "frames": frames }))?; + } + Ok(()) +} diff --git a/crates/horizon-client/src/border.wgsl b/crates/horizon-client/src/border.wgsl new file mode 100644 index 000000000..7eb6bb9aa --- /dev/null +++ b/crates/horizon-client/src/border.wgsl @@ -0,0 +1,32 @@ +// The world border wall (core/world_border): camera-relative wall quads +// moved by the model offset, the forcefield texture scrolled by the texture +// offset and modulated by the status colour and fade. +struct Globals { + view_proj: mat4x4, +} +struct Border { + color: vec4, + // xyz: model offset, w: texture translation (u and v) + offset: vec4, +} +@group(0) @binding(0) var globals: Globals; +@group(0) @binding(1) var forcefield: texture_2d; +@group(0) @binding(2) var forcefield_sampler: sampler; +@group(0) @binding(3) var border: Border; +struct Out { + @builtin(position) clip: vec4, + @location(0) uv: vec2, +} +@vertex fn vs_border(@location(0) position: vec3, @location(1) uv: vec2) -> Out { + var out: Out; + out.clip = globals.view_proj * vec4(position + border.offset.xyz, 1.0); + out.uv = uv + vec2(border.offset.w); + return out; +} +@fragment fn fs_border(in: Out) -> @location(0) vec4 { + let color = textureSample(forcefield, forcefield_sampler, in.uv); + if color.a == 0.0 { + discard; + } + return color * border.color; +} diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs index a69e3f030..70a01927d 100644 --- a/crates/horizon-client/src/font.rs +++ b/crates/horizon-client/src/font.rs @@ -451,48 +451,55 @@ impl Font { .sum::() .ceil() } - /// StringSplitter.splitLines: wrap at the last space that fits (or - /// mid-word when none does); `\n` always breaks. Styles are kept. + /// Wrapped lines, as `split_lines` but never empty (one empty line for + /// empty text). pub fn split(&self, t: &Text, max_width: f32) -> Vec { + let mut lines = self.split_lines(t, max_width); + if lines.is_empty() { + lines.push(Text::empty()); + } + lines + } + /// `StringSplitter.splitLines` (`Font.split`): `\n` always breaks; a line + /// overflowing `max_width` breaks at its last space (dropped), or before + /// the overflowing character when it has none; the first character of + /// width always fits. Styles are kept; empty text gives no lines. + pub fn split_lines(&self, t: &Text, max_width: f32) -> Vec { let chars: Vec<(char, Style)> = t.chars().map(|(c, s)| (c, s.clone())).collect(); + let max_width = max_width.max(1.0); let mut lines = Vec::new(); let mut start = 0; - while start < chars.len() { - let mut width = 0.0; - let mut end = chars.len(); - let mut next = chars.len(); + let mut force_new_line = false; + loop { + let mut width = 0.0f32; + let mut had_width = false; let mut last_space = None; + let mut split = None; for (i, (c, style)) in chars.iter().enumerate().skip(start) { if *c == '\n' { - end = i; - next = i + 1; + split = Some(i); break; } if *c == ' ' { last_space = Some(i); } - width += self.advance(*c, style); - if width > max_width { - match last_space { - Some(s) if s > start => { - end = s; - next = s + 1; - } - _ => { - end = i.max(start + 1); - next = end; - } - } + let w = self.advance(*c, style); + width += w; + if had_width && width > max_width { + split = Some(last_space.unwrap_or(i)); break; } + had_width |= w != 0.0; } - lines.push(t.slice(start, end)); - start = next; - if start == chars.len() && chars.last().is_some_and(|c| c.0 == '\n') { - lines.push(Text::empty()); - } + let Some(at) = split else { break }; + let tail = chars[at].0; + force_new_line = tail == '\n'; + lines.push(t.slice(start, at)); + start = at + usize::from(tail == '\n' || tail == ' '); } - if lines.is_empty() { + if start < chars.len() { + lines.push(t.slice(start, chars.len())); + } else if force_new_line { lines.push(Text::empty()); } lines diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 21e3400cb..047fec3fd 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -509,6 +509,8 @@ pub struct Resources { names: Names, /// clouds.png: (width, height, filled cells). clouds: (u32, u32, Vec), + /// misc/forcefield.png: (width, height, RGBA) for the world border wall. + forcefield: (u32, u32, Vec), context: Arc, threads: usize, player_arm: Option, @@ -751,6 +753,9 @@ struct Game<'a> { exec: commands::execute::ExecState, rand_sequences: horizon_client::random_sequences::RandomSequences, border: horizon_client::worldborder::WorldBorder, + /// `WorldBorderRenderer` and its render state. + border_renderer: horizon_client::border_render::BorderRenderer, + border_state: horizon_client::border_render::BorderRenderState, subtitles: subtitle_hud::SubtitleState, adv: advancements::AdvState, stats_ui: stats_screen::StatsUi, @@ -7041,6 +7046,9 @@ impl Game<'_> { (c & 255) as f32 / 255.0, ] }; + let border = (!title) + .then(|| self.border_draw(camera.to_array(), alpha as f32)) + .flatten(); let frame = Frame { camera, yaw, @@ -7078,6 +7086,7 @@ impl Game<'_> { celestial: &celestial, hand: &hand, screen: &screen, + border, game_time: self.world.game_time as f32, ticks: self.ticks, darkness: self.darkness_lighting(alpha as f32), @@ -7086,6 +7095,39 @@ impl Game<'_> { }; self.renderer.as_mut().ok_or("renderer")?.render(&frame) } + /// `LevelExtractor` / `LevelRenderer`: the world border wall this frame. + fn border_draw( + &mut self, + camera: [f64; 3], + partial: f32, + ) -> Option { + use horizon_client::border_render::{self, BorderRenderer}; + let distance = f64::from(self.streaming.radius * 16); + border_render::extract( + &self.border, + partial, + camera, + distance, + &mut self.border_state, + ); + // Camera.depthFar, as the renderer's far plane. + let depth_far = (distance as f32 * 4.0).max(1024.0); + if !self + .border_renderer + .prepare(&self.border_state, camera, distance, depth_far) + { + return None; + } + let millis = self.started.elapsed().as_millis() as i64; + Some(horizon_client::gfx::BorderDraw { + vertices: self.border_renderer.vertices, + rebuilt: self.border_renderer.take_rebuilt(), + transforms: self + .border_renderer + .transforms(&self.border_state, camera, millis), + sides: BorderRenderer::sides(&self.border_state, camera, distance), + }) + } /// A key press while a world is open (keyboard or control socket). fn key_pressed(&mut self, key: KeyCode) -> Result<()> { if self.remote.is_some() && self.remote_key(key)? { @@ -7318,6 +7360,7 @@ impl ApplicationHandler for Game<'_> { self.res.atlas.width, self.res.atlas.height, ), + (&self.res.forcefield.2, self.res.forcefield.0), )) { Ok(r) => self.renderer = Some(r), Err(e) => { @@ -7932,6 +7975,12 @@ pub fn run() -> Result<()> { ) }) .unwrap_or((1, 1, vec![false])), + forcefield: horizon_client::hud::decode( + &root.join("assets/minecraft/textures/misc/forcefield.png"), + ) + .ok() + .filter(|(w, h, _)| w == h && w.is_power_of_two()) + .unwrap_or((1, 1, vec![0; 4])), mob_types: MobTypes::load(&root)? .types .into_iter() @@ -8137,6 +8186,8 @@ pub fn run() -> Result<()> { exec: Default::default(), rand_sequences: Default::default(), border: Default::default(), + border_renderer: Default::default(), + border_state: Default::default(), subtitles: Default::default(), adv: Default::default(), stats_ui: Default::default(), diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 9654d9ca3..822133a8e 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -76,6 +76,8 @@ pub struct Frame<'a> { pub hand: &'a [Vertex], /// Full-screen camera effects drawn over the world and hand, under the HUD. pub screen: &'a [crate::screen_effects::ScreenQuad], + /// The world border wall, when near enough to be drawn. + pub border: Option, pub game_time: f32, pub ticks: u64, /// The darkness effect on the lightmap: the brightness it takes off the @@ -86,6 +88,22 @@ pub struct Frame<'a> { /// Torch flicker added to the block light factor of 1.4. pub block_flicker: f32, } +/// One frame of the world border wall (`WorldBorderRenderer.render`). +#[derive(Clone, Debug)] +pub struct BorderDraw { + /// The cached wall buffer; uploaded only when `rebuilt`. + pub vertices: [crate::border_render::BorderVertex; 16], + pub rebuilt: bool, + pub transforms: crate::border_render::BorderTransforms, + /// Walls to draw (indices of four-vertex quads), nearest first. + pub sides: Vec, +} +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +struct BorderUniform { + color: [f32; 4], + offset: [f32; 4], +} pub struct Renderer { instance: wgpu::Instance, surface: wgpu::Surface<'static>, @@ -102,6 +120,11 @@ pub struct Renderer { additive_pipeline: wgpu::RenderPipeline, celestial_pipeline: wgpu::RenderPipeline, celestial_buffer: wgpu::Buffer, + /// `RenderPipelines.WORLD_BORDER` and its buffers. + border_pipeline: wgpu::RenderPipeline, + border_group: wgpu::BindGroup, + border_uniform: wgpu::Buffer, + border_vertices: wgpu::Buffer, /// Screen effects: alpha-blended and vignette (`dst * (1 - src)`) pipelines. screen_pipelines: [wgpu::RenderPipeline; 2], screen_buffer: wgpu::Buffer, @@ -190,6 +213,7 @@ impl Renderer { layers: u32, animations: &[SpriteAnimation], hud_atlas: (&[u8], u32, u32), + forcefield: (&[u8], u32), ) -> Result { let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); @@ -764,6 +788,175 @@ impl Renderer { multiview_mask: None, cache: None, }); + // WorldBorderRenderer: misc/forcefield.png as a MipmappedTexture + // (repeat, linear minification with mipmaps, nearest magnification). + let (forcefield_pixels, forcefield_size) = forcefield; + let (forcefield_mips, forcefield_levels) = mip_chain(forcefield_pixels, forcefield_size, 1); + let forcefield_texture = device.create_texture_with_data( + &queue, + &wgpu::TextureDescriptor { + label: Some("Forcefield"), + size: wgpu::Extent3d { + width: forcefield_size, + height: forcefield_size, + depth_or_array_layers: 1, + }, + mip_level_count: forcefield_levels, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }, + wgpu::util::TextureDataOrder::LayerMajor, + &forcefield_mips, + ); + let forcefield_view = forcefield_texture.create_view(&Default::default()); + let forcefield_sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Forcefield"), + address_mode_u: wgpu::AddressMode::Repeat, + address_mode_v: wgpu::AddressMode::Repeat, + min_filter: wgpu::FilterMode::Linear, + mag_filter: wgpu::FilterMode::Nearest, + mipmap_filter: wgpu::MipmapFilterMode::Linear, + ..Default::default() + }); + let border_uniform = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("World border"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let border_vertices = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("World border vertices"), + size: 16 * std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let border_bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("World border bindings"), + entries: &[ + entry( + 0, + vf, + wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + ), + entry( + 1, + vf, + wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + ), + entry( + 2, + vf, + wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + ), + entry( + 3, + vf, + wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + ), + ], + }); + let border_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("World border resources"), + layout: &border_bindings, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: globals.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&forcefield_view), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::Sampler(&forcefield_sampler), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: border_uniform.as_entire_binding(), + }, + ], + }); + let border_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("World border layout"), + bind_group_layouts: &[Some(&border_bindings)], + ..Default::default() + }); + let border_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Horizon world border"), + source: wgpu::ShaderSource::Wgsl(include_str!("border.wgsl").into()), + }); + let border_attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2]; + // RenderPipelines.WORLD_BORDER: BlendFunction.OVERLAY, no culling, + // depth writes with a polygon offset of 3 towards the camera. + let border_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("World border"), + layout: Some(&border_layout), + vertex: wgpu::VertexState { + module: &border_shader, + entry_point: Some("vs_border"), + compilation_options: Default::default(), + buffers: &[Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &border_attributes, + })], + }, + primitive: wgpu::PrimitiveState { + cull_mode: None, + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::LessEqual), + stencil: Default::default(), + bias: wgpu::DepthBiasState { + constant: -3, + slope_scale: -3.0, + clamp: 0.0, + }, + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &border_shader, + entry_point: Some("fs_border"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: config.format.remove_srgb_suffix(), + blend: Some(wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::SrcAlpha, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::Zero, + operation: wgpu::BlendOperation::Add, + }, + }), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }); let screen_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("Horizon screen effects"), source: wgpu::ShaderSource::Wgsl(include_str!("screen.wgsl").into()), @@ -855,6 +1048,10 @@ impl Renderer { additive_pipeline, celestial_pipeline, celestial_buffer, + border_pipeline, + border_group, + border_uniform, + border_vertices, screen_pipelines, screen_buffer, screen_capacity, @@ -1421,6 +1618,27 @@ impl Renderer { self.index_quads = (entity_quads + additive_quads + hand_quads).next_power_of_two(); self.indices = Self::quad_indices(&self.device, self.index_quads); } + if let Some(b) = &frame.border { + if b.rebuilt { + self.queue.write_buffer( + &self.border_vertices, + 0, + bytemuck::cast_slice(&b.vertices), + ); + } + let t = &b.transforms; + let uniform = BorderUniform { + color: t.color, + offset: [ + t.model_offset[0], + t.model_offset[1], + t.model_offset[2], + t.texture_offset, + ], + }; + self.queue + .write_buffer(&self.border_uniform, 0, bytemuck::bytes_of(&uniform)); + } let view_target = surface_frame .texture .create_view(&wgpu::TextureViewDescriptor { @@ -1537,6 +1755,18 @@ impl Renderer { i as u32..i as u32 + 1, ); } + // LevelRenderer: the world border after translucent terrain and weather. + if let Some(b) = frame.border.as_ref().filter(|_| !frame.title) { + pass.set_pipeline(&self.border_pipeline); + pass.set_bind_group(0, &self.border_group, &[]); + pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.set_vertex_buffer(0, self.border_vertices.slice(..)); + for &side in &b.sides { + let first = side as u32 * 6; + pass.draw_indexed(first..first + 6, 0, 0..1); + } + pass.set_bind_group(0, &self.group, &[]); + } } if hand_quads > 0 { let attachments = [Some(wgpu::RenderPassColorAttachment { diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index eecbef52f..8d91133eb 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -98,6 +98,7 @@ pub mod stopwatches; pub mod streaming; pub mod structure_blocks; pub mod subtitles; +pub mod tab_list; pub mod testgen; pub mod text; pub mod title; diff --git a/crates/horizon-client/src/tab_list.rs b/crates/horizon-client/src/tab_list.rs new file mode 100644 index 000000000..1f936fcac --- /dev/null +++ b/crates/horizon-client/src/tab_list.rs @@ -0,0 +1,703 @@ +//! The player list shown while the player-list key is held +//! (`PlayerTabOverlay`, `Hud.extractTabList`): listed players sorted by list +//! order, spectators last, team and name; columns of at most 20 rows; heads, +//! names (team prefix and colour, italic spectators), ping bars and the +//! `list` objective (integer scores in their number format, or hearts that +//! blink when they change); the header and footer. Laid out as draw calls so +//! the parity fixture can compare them with the vanilla client. +use crate::{ + font::Font, + java_text::float_to_string, + scoreboard::{Comp, NumberFormat, Objective, RenderType, Scoreboard, comp_text}, + text::Text, +}; +use std::{cmp::Ordering, collections::HashMap}; + +/// `GameType.SPECTATOR` id. +pub const SPECTATOR: i32 = 3; +/// `PlayerTabOverlay.MAX_ROWS_PER_COL`. +pub const MAX_ROWS_PER_COL: i32 = 20; + +/// One `PlayerInfo` the list can show. +#[derive(Clone, Debug, PartialEq)] +pub struct TabPlayer { + pub uuid: u128, + /// `GameProfile.name`: the score holder and team member name. + pub name: String, + /// `GameType` id (0 survival, 1 creative, 2 adventure, 3 spectator). + pub game_mode: i32, + /// Milliseconds; negative when unknown. + pub latency: i32, + /// `tabListDisplayName` as a component (its root style matters: a + /// spectator's name is made italic at the root). + pub display_name: Option, + pub list_order: i32, + pub show_hat: bool, + /// Skin texture path, e.g. `entity/player/wide/steve`. + pub skin: String, +} +impl TabPlayer { + /// A player with the default skin for their UUID. + pub fn new(uuid: u128, name: impl Into) -> Self { + Self { + uuid, + name: name.into(), + game_mode: 0, + latency: 0, + display_name: None, + list_order: 0, + show_hat: true, + skin: default_skin(uuid).to_owned(), + } + } +} + +/// `DefaultPlayerSkin.get(UUID)`: the default skin by `UUID.hashCode`. +pub fn default_skin(uuid: u128) -> &'static str { + const SKINS: [&str; 18] = [ + "entity/player/slim/alex", + "entity/player/slim/ari", + "entity/player/slim/efe", + "entity/player/slim/kai", + "entity/player/slim/makena", + "entity/player/slim/noor", + "entity/player/slim/steve", + "entity/player/slim/sunny", + "entity/player/slim/zuri", + "entity/player/wide/alex", + "entity/player/wide/ari", + "entity/player/wide/efe", + "entity/player/wide/kai", + "entity/player/wide/makena", + "entity/player/wide/noor", + "entity/player/wide/steve", + "entity/player/wide/sunny", + "entity/player/wide/zuri", + ]; + let hilo = ((uuid >> 64) as u64) ^ (uuid as u64); + let hash = ((hilo >> 32) as i32) ^ (hilo as i32); + SKINS[hash.rem_euclid(SKINS.len() as i32) as usize] +} + +/// One `GuiGraphicsExtractor` call of the list. +#[derive(Clone, Debug, PartialEq)] +pub enum TabDraw { + /// `fill(x0, y0, x1, y1, argb)`. + Fill { + x0: i32, + y0: i32, + x1: i32, + y1: i32, + color: u32, + }, + /// `text(font, text, x, y, argb)` with its drop shadow. + Text { + text: Text, + x: i32, + y: i32, + color: u32, + }, + /// `blitSprite(sprite, x, y, w, h)`. + Sprite { + sprite: &'static str, + x: i32, + y: i32, + w: i32, + h: i32, + }, + /// `PlayerFaceExtractor.extractRenderState`: the skin's face (and hat + /// layer), upside down for Dinnerbone and Grumm. + Face { + skin: String, + x: i32, + y: i32, + size: i32, + hat: bool, + flip: bool, + }, +} + +/// `Hud.extractTabList`: whether the list shows. A single-player world +/// shows it only with another listed player or a `list` objective. +pub fn visible(key_down: bool, local_server: bool, listed: usize, objective: bool) -> bool { + key_down && !(local_server && listed <= 1 && !objective) +} + +/// `Options.getBackgroundColor(553648127)`: the row background. +pub fn row_background(background_for_chat_only: bool, text_background_opacity: f64) -> u32 { + if background_for_chat_only { + 0x20FF_FFFF + } else { + ((text_background_opacity as f32 * 255.0).floor() as i32 as u32 & 0xFF) << 24 + } +} + +/// `String.compareTo`: UTF-16 code unit order. +fn compare_utf16(a: &str, b: &str) -> Ordering { + a.encode_utf16().cmp(b.encode_utf16()) +} +/// `String.compareToIgnoreCase` (per code point: upper then lower case). +fn compare_ignore_case(a: &str, b: &str) -> Ordering { + fn simple(c: char, upper: bool) -> char { + let mut it: Box> = if upper { + Box::new(c.to_uppercase()) + } else { + Box::new(c.to_lowercase()) + }; + match (it.next(), it.next()) { + (Some(m), None) => m, + _ => c, + } + } + let (mut x, mut y) = (a.chars(), b.chars()); + loop { + match (x.next(), y.next()) { + (Some(c1), Some(c2)) => { + if c1 != c2 { + let (u1, u2) = (simple(c1, true), simple(c2, true)); + if u1 != u2 { + let (l1, l2) = (simple(u1, false), simple(u2, false)); + if l1 != l2 { + return l1.cmp(&l2); + } + } + } + } + (None, None) => return Ordering::Equal, + (None, Some(_)) => return Ordering::Less, + (Some(_), None) => return Ordering::Greater, + } + } +} + +/// `PlayerTabOverlay.getPlayerInfos`: `PLAYER_COMPARATOR` order (higher +/// list order first, spectators last, team name, profile name ignoring +/// case), at most 80 players. +pub fn sorted_players<'a>(players: &'a [TabPlayer], board: &Scoreboard) -> Vec<&'a TabPlayer> { + let team = |p: &TabPlayer| { + board + .players_team(&p.name) + .map_or("", |t| t.name.as_str()) + .to_owned() + }; + let mut out: Vec<&TabPlayer> = players.iter().collect(); + out.sort_by(|a, b| { + a.list_order + .wrapping_neg() + .cmp(&b.list_order.wrapping_neg()) + .then_with(|| (a.game_mode == SPECTATOR).cmp(&(b.game_mode == SPECTATOR))) + .then_with(|| compare_utf16(&team(a), &team(b))) + .then_with(|| compare_ignore_case(&a.name, &b.name)) + }); + out.truncate(80); + out +} + +/// `MutableComponent.withStyle(ITALIC)` on a component's root. +fn italic_root(c: &Comp) -> Comp { + use serde_json::Value; + match c { + Value::Object(o) => { + let mut o = o.clone(); + o.insert("italic".into(), Value::Bool(true)); + Value::Object(o) + } + // A list is its first element with the rest as its siblings. + Value::Array(list) if !list.is_empty() => { + let mut list = list.clone(); + list[0] = italic_root(&list[0]); + Value::Array(list) + } + Value::Array(_) => serde_json::json!({"text": "", "italic": true}), + other => { + let text = match other { + Value::String(s) => s.clone(), + Value::Null => String::new(), + v => v.to_string(), + }; + serde_json::json!({"text": text, "italic": true}) + } + } +} + +/// `PlayerTabOverlay.getNameForDisplay`. +pub fn name_for_display(p: &TabPlayer, board: &Scoreboard) -> Text { + let spectator = p.game_mode == SPECTATOR; + let name = match &p.display_name { + Some(d) if spectator => return comp_text(&italic_root(d)), + Some(d) => return comp_text(d), + None => match board.players_team(&p.name) { + Some(team) => team.formatted_name(Text::literal(p.name.clone())), + None => Text::literal(p.name.clone()), + }, + }; + if spectator { name.italic() } else { name } +} + +/// `PlayerTabOverlay.extractPingIcon`'s sprite. +pub fn ping_sprite(latency: i32) -> &'static str { + match latency { + i32::MIN..=-1 => "icon/ping_unknown", + 0..150 => "icon/ping_5", + 150..300 => "icon/ping_4", + 300..600 => "icon/ping_3", + 600..1000 => "icon/ping_2", + _ => "icon/ping_1", + } +} + +/// `PlayerTabOverlay.HealthState`: the hearts of one player. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct HealthState { + last_value: i32, + displayed_value: i32, + last_update_tick: i64, + blink_until_tick: i64, +} +impl HealthState { + fn new(value: i32) -> Self { + Self { + last_value: value, + displayed_value: value, + last_update_tick: 0, + blink_until_tick: 0, + } + } + fn update(&mut self, value: i32, tick: i64) { + if value != self.last_value { + let duration = if value < self.last_value { 20 } else { 10 }; + self.blink_until_tick = tick + duration; + self.last_value = value; + self.last_update_tick = tick; + } + if tick - self.last_update_tick > 20 { + self.displayed_value = value; + } + } + fn is_blinking(&self, tick: i64) -> bool { + self.blink_until_tick > tick && (self.blink_until_tick - tick) % 6 >= 3 + } +} + +/// What the list is drawn from this frame. +pub struct TabInputs<'a> { + /// The listed players (`getListedOnlinePlayers`), in any order. + pub players: &'a [TabPlayer], + pub board: &'a Scoreboard, + /// The objective in the `list` display slot. + pub objective: Option<&'a Objective>, + pub screen_width: i32, + /// `ClientPacketListener.onlineMode`: heads are shown. + pub online_mode: bool, + /// `Hud.getGuiTicks`. + pub gui_ticks: i64, + /// [`row_background`]. + pub background: u32, + /// The player is in the level with an upside-down name + /// (`AvatarRenderer.isPlayerUpsideDown`). + pub upside_down: &'a dyn Fn(u128) -> bool, +} + +/// `PlayerTabOverlay`: the header, footer, visibility and heart states. +#[derive(Clone, Debug, Default)] +pub struct TabList { + pub header: Option, + pub footer: Option, + visible: bool, + health: HashMap, +} +struct Entry { + name: Text, + score: i32, + formatted: Option, + score_width: i32, +} +impl TabList { + /// `setVisible`: showing or hiding forgets the heart states. + pub fn set_visible(&mut self, visible: bool) { + if self.visible != visible { + self.health.clear(); + self.visible = visible; + } + } + pub fn is_visible(&self) -> bool { + self.visible + } + /// `reset`. + pub fn reset(&mut self) { + self.header = None; + self.footer = None; + } + /// `extractRenderState`. + pub fn layout(&mut self, i: &TabInputs, font: &Font) -> Vec { + let width = |t: &Text| font.width_text(t) as i32; + let players = sorted_players(i.players, i.board); + let spacer = font.width(" ") as i32; + let mut max_name = 0; + let mut max_score = 0; + let mut entries = Vec::with_capacity(players.len()); + for p in &players { + let name = name_for_display(p, i.board).resolve_legacy(); + max_name = max_name.max(width(&name)); + let mut entry = Entry { + name, + score: 0, + formatted: None, + score_width: 0, + }; + if let Some(objective) = i.objective { + let info = i.board.score(&p.name, &objective.name); + if let Some(s) = info { + entry.score = s.value; + } + if objective.render_type != RenderType::Hearts { + if let Some(s) = info { + let default = + objective.format_or_default(NumberFormat::player_list_default()); + let text = s + .number_format + .as_ref() + .unwrap_or(&default) + .format(s.value) + .resolve_legacy(); + entry.score_width = width(&text); + entry.formatted = Some(text); + } + let w = if entry.score_width > 0 { + spacer + entry.score_width + } else { + 0 + }; + max_score = max_score.max(w); + } + } + entries.push(entry); + } + if !self.health.is_empty() { + self.health + .retain(|id, _| players.iter().any(|p| p.uuid == *id)); + } + let slots = players.len() as i32; + let mut rows = slots; + let mut cols = 1; + while rows > MAX_ROWS_PER_COL { + cols += 1; + rows = (slots + cols - 1) / cols; + } + let show_head = i.online_mode; + let width_for_score = match i.objective { + Some(o) if o.render_type == RenderType::Hearts => 90, + Some(_) => max_score, + None => 0, + }; + let sw = i.screen_width; + let head = if show_head { 9 } else { 0 }; + let slot_width = (cols * (head + max_name + width_for_score + 13)).min(sw - 50) / cols; + let xxo = sw / 2 - (slot_width * cols + (cols - 1) * 5) / 2; + let mut yyo = 10; + let mut max_line = slot_width * cols + (cols - 1) * 5; + let split = |t: &Option| { + t.as_ref() + .map(|t| font.split_lines(&t.resolve_legacy(), (sw - 50) as f32)) + }; + let header = split(&self.header); + let footer = split(&self.footer); + for line in header.iter().chain(footer.iter()).flatten() { + max_line = max_line.max(width(line)); + } + let mut out = Vec::new(); + let band = |y0: i32, y1: i32| TabDraw::Fill { + x0: sw / 2 - max_line / 2 - 1, + y0, + x1: sw / 2 + max_line / 2 + 1, + y1, + color: 0x8000_0000, + }; + if let Some(lines) = &header { + out.push(band(yyo - 1, yyo + lines.len() as i32 * 9)); + for line in lines { + let w = width(line); + out.push(TabDraw::Text { + text: line.clone(), + x: sw / 2 - w / 2, + y: yyo, + color: 0xFFFF_FFFF, + }); + yyo += 9; + } + yyo += 1; + } + out.push(band(yyo - 1, yyo + rows * 9)); + for (n, (p, entry)) in players.iter().zip(&entries).enumerate() { + let n = n as i32; + let (col, row) = (n / rows, n % rows); + let mut xo = xxo + col * slot_width + col * 5; + let yo = yyo + row * 9; + out.push(TabDraw::Fill { + x0: xo, + y0: yo, + x1: xo + slot_width, + y1: yo + 8, + color: i.background, + }); + if show_head { + out.push(TabDraw::Face { + skin: p.skin.clone(), + x: xo, + y: yo, + size: 8, + hat: p.show_hat, + flip: (i.upside_down)(p.uuid), + }); + xo += 9; + } + let spectator = p.game_mode == SPECTATOR; + out.push(TabDraw::Text { + text: entry.name.clone(), + x: xo, + y: yo, + color: if spectator { 0x90FF_FFFF } else { 0xFFFF_FFFF }, + }); + if let Some(objective) = i.objective.filter(|_| !spectator) { + let left = xo + max_name + 1; + let right = left + width_for_score; + if right - left > 5 { + if objective.render_type == RenderType::Hearts { + self.hearts( + yo, + left, + right, + p.uuid, + entry.score, + i.gui_ticks, + font, + &mut out, + ); + } else if let Some(text) = &entry.formatted { + out.push(TabDraw::Text { + text: text.clone(), + x: right - entry.score_width, + y: yo, + color: 0xFFFF_FFFF, + }); + } + } + } + out.push(TabDraw::Sprite { + sprite: ping_sprite(p.latency), + x: xo - head + slot_width - 11, + y: yo, + w: 10, + h: 8, + }); + } + if let Some(lines) = &footer { + yyo += rows * 9 + 1; + out.push(band(yyo - 1, yyo + lines.len() as i32 * 9)); + for line in lines { + let w = width(line); + out.push(TabDraw::Text { + text: line.clone(), + x: sw / 2 - w / 2, + y: yyo, + color: 0xFFFF_FFFF, + }); + yyo += 9; + } + } + out + } + /// `extractTablistHearts`. + #[allow(clippy::too_many_arguments)] + fn hearts( + &mut self, + yo: i32, + left: i32, + right: i32, + id: u128, + score: i32, + tick: i64, + font: &Font, + out: &mut Vec, + ) { + let health = self + .health + .entry(id) + .or_insert_with(|| HealthState::new(score)); + health.update(score, tick); + let displayed = health.displayed_value; + let blink = health.is_blinking(tick); + // Mth.positiveCeilDiv. + let full_hearts = -((-score.max(displayed)).div_euclid(2)); + let to_render = score.max(displayed.max(20)) / 2; + if full_hearts <= 0 { + return; + } + let per_heart = ((right - left - 4) as f32 / to_render as f32) + .min(9.0) + .floor() as i32; + if per_heart <= 3 { + let pct = (score as f32 / 20.0).clamp(0.0, 1.0); + let color = (((1.0 - pct) * 255.0) as i32) << 16 | ((pct * 255.0) as i32) << 8; + let hearts = score as f32 / 2.0; + let hp = Text::translate( + "multiplayer.player.list.hp", + &[Text::literal(float_to_string(hearts))], + ); + let text = if right - font.width_text(&hp) as i32 >= left { + hp + } else { + Text::literal(float_to_string(hearts)) + }; + let w = font.width_text(&text) as i32; + out.push(TabDraw::Text { + text, + x: (right + left - w) / 2, + y: yo, + color: color as u32 | 0xFF00_0000, + }); + return; + } + let container = if blink { + "hud/heart/container_blinking" + } else { + "hud/heart/container" + }; + let heart = |sprite: &'static str, n: i32| TabDraw::Sprite { + sprite, + x: left + n * per_heart, + y: yo, + w: 9, + h: 9, + }; + for n in full_hearts..to_render { + out.push(heart(container, n)); + } + for n in 0..full_hearts { + out.push(heart(container, n)); + if blink { + if n * 2 + 1 < displayed { + out.push(heart("hud/heart/full_blinking", n)); + } + if n * 2 + 1 == displayed { + out.push(heart("hud/heart/half_blinking", n)); + } + } + if n * 2 + 1 < score { + out.push(heart( + if n >= 10 { + "hud/heart/absorbing_full_blinking" + } else { + "hud/heart/full" + }, + n, + )); + } + if n * 2 + 1 == score { + out.push(heart( + if n >= 10 { + "hud/heart/absorbing_half_blinking" + } else { + "hud/heart/half" + }, + n, + )); + } + } + } +} + +/// Draws the list with the HUD batch (faces from the shared atlas). +pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, draws: &[TabDraw]) { + let rgba = |argb: u32| { + let [a, r, g, b] = argb.to_be_bytes(); + crate::hud::rgba(r, g, b, a) + }; + for d in draws { + match d { + TabDraw::Fill { + x0, + y0, + x1, + y1, + color, + } => { + let (xa, xb) = (*x0.min(x1), *x0.max(x1)); + let (ya, yb) = (*y0.min(y1), *y0.max(y1)); + batch.fill( + atlas, + xa as f32, + ya as f32, + (xb - xa) as f32, + (yb - ya) as f32, + rgba(*color), + ); + } + TabDraw::Text { text, x, y, color } => { + batch.text_styled(atlas, text, *x as f32, *y as f32, rgba(*color), true); + } + TabDraw::Sprite { sprite, x, y, w, h } => { + if let Some(r) = atlas.sprites.get(&format!("gui/sprites/{sprite}")).copied() { + batch.rect_uv(*x as f32, *y as f32, *w as f32, *h as f32, r, u32::MAX); + } + } + TabDraw::Face { + skin, + x, + y, + size, + hat, + flip, + } => { + let Some(r) = atlas.sprites.get(skin.as_str()).copied() else { + continue; + }; + // blit(u, v, size, size, 8, ±8, 64, 64): the face then the hat layer. + let layer = |u: f32| { + let mut t = r; + let (du, dv) = (r.u1 - r.u0, r.v1 - r.v0); + t.u0 = r.u0 + du * u / 64.0; + t.u1 = t.u0 + du * 8.0 / 64.0; + let (v0, v1) = if *flip { (16.0, 8.0) } else { (8.0, 16.0) }; + t.v0 = r.v0 + dv * v0 / 64.0; + t.v1 = r.v0 + dv * v1 / 64.0; + t + }; + let s = *size as f32; + batch.rect_uv(*x as f32, *y as f32, s, s, layer(8.0), u32::MAX); + if *hat { + batch.rect_uv(*x as f32, *y as f32, s, s, layer(40.0), u32::MAX); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn order_ping_and_skins() { + let board = Scoreboard::default(); + let mut a = TabPlayer::new(1, "bob"); + let mut b = TabPlayer::new(2, "Alice"); + let c = TabPlayer::new(3, "carl"); + a.game_mode = SPECTATOR; + b.list_order = -1; + let players = [a, b, c]; + let names: Vec<_> = sorted_players(&players, &board) + .iter() + .map(|p| p.name.as_str()) + .collect(); + assert_eq!(names, ["carl", "bob", "Alice"]); + assert_eq!(ping_sprite(-1), "icon/ping_unknown"); + assert_eq!(ping_sprite(149), "icon/ping_5"); + assert_eq!(ping_sprite(1000), "icon/ping_1"); + // UUID.hashCode of 0 is 0: the first default skin. + assert_eq!(default_skin(0), "entity/player/slim/alex"); + assert!(!visible(true, true, 1, false)); + assert!(visible(true, true, 1, true)); + assert!(visible(true, false, 1, false)); + } +} diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index 434a9f339..1fc16f421 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -220,6 +220,69 @@ impl Text { } out } + /// `StringDecomposer.iterateFormatted` on every span: legacy `§` codes + /// inside the span contents restyle what follows them (colour codes + /// clear the decorations, `§r` returns to the span's own style) and are + /// not drawn. + pub fn resolve_legacy(&self) -> Text { + if !self.spans.iter().any(|s| s.text.contains('§')) { + return self.clone(); + } + let mut out = Text::default(); + for span in &self.spans { + let mut style = span.style.clone(); + let mut current = String::new(); + let mut chars = span.text.chars(); + while let Some(c) = chars.next() { + if c != '§' { + current.push(c); + continue; + } + let Some(code) = chars.next() else { break }; + let code = code.to_ascii_lowercase(); + let next = if let Some(c) = COLORS.iter().find(|c| c.0 == code) { + // Style.applyLegacyFormat: a colour clears the decorations. + Style { + color: Some(c.2), + bold: Some(false), + italic: Some(false), + underlined: Some(false), + strikethrough: Some(false), + obfuscated: Some(false), + ..style.clone() + } + } else { + let mut s = style.clone(); + match code { + 'k' => s.obfuscated = Some(true), + 'l' => s.bold = Some(true), + 'm' => s.strikethrough = Some(true), + 'n' => s.underlined = Some(true), + 'o' => s.italic = Some(true), + 'r' => s = span.style.clone(), + _ => {} + } + s + }; + if next != style { + if !current.is_empty() { + out.spans.push(Span { + text: std::mem::take(&mut current), + style: style.clone(), + }); + } + style = next; + } + } + if !current.is_empty() { + out.spans.push(Span { + text: current, + style, + }); + } + } + out + } /// Characters with their effective styles. pub fn chars(&self) -> impl Iterator { self.spans diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 6025b1e63..096b944a4 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -582,6 +582,192 @@ packet!( } ); packet!(TabList { header: Tag => Nbt, footer: Tag => Nbt }); +packet!( + /// ClientboundSetBorderCenterPacket. + SetBorderCenter { x: f64 => Double, z: f64 => Double } +); +packet!( + /// ClientboundSetBorderLerpSizePacket. + SetBorderLerpSize { old_size: f64 => Double, new_size: f64 => Double, lerp_time: i64 => VarLong } +); +packet!( + /// ClientboundSetBorderSizePacket. + SetBorderSize { size: f64 => Double } +); +packet!( + /// ClientboundSetBorderWarningDelayPacket (ticks). + SetBorderWarningDelay { delay: i32 => VarInt } +); +packet!( + /// ClientboundSetBorderWarningDistancePacket. + SetBorderWarningDistance { blocks: i32 => VarInt } +); +packet!( + /// ClientboundSetDisplayObjectivePacket: `DisplaySlot` id (0 list, + /// 1 sidebar, 2 below name, 3.. team sidebars) and the objective ("" clears). + SetDisplayObjective { slot: i32 => VarInt, objective: String => Str } +); +packet!( + /// ClientboundResetScorePacket: one objective, or all of them when absent. + ResetScore { owner: String => Str, objective: Option => Opt } +); +/// `NumberFormatTypes.STREAM_CODEC`, by `number_format_type` registry id. +#[derive(Clone, Debug, PartialEq)] +pub enum NumberFormat { + /// 0: `minecraft:blank`. + Blank, + /// 1: `minecraft:styled`, a style compound. + Styled(Tag), + /// 2: `minecraft:fixed`, a component. + Fixed(Tag), +} +impl Codec for NumberFormat { + fn read(r: &mut Reader) -> Result { + Ok(match r.varint()? { + 0 => NumberFormat::Blank, + 1 => NumberFormat::Styled(r.nbt()?), + 2 => NumberFormat::Fixed(r.nbt()?), + other => return Err(crate::Error::new(format!("unknown number format {other}"))), + }) + } + fn write(v: &Self, w: &mut Writer) { + match v { + NumberFormat::Blank => w.varint(0), + NumberFormat::Styled(t) => { + w.varint(1); + w.nbt(t); + } + NumberFormat::Fixed(t) => { + w.varint(2); + w.nbt(t); + } + } + } +} +packet!( + /// ClientboundSetScorePacket. + SetScore { + owner: String => Str, + objective: String => Str, + score: i32 => VarInt, + display: Option => Opt, + number_format: Option => Opt, + } +); +/// ClientboundSetObjectivePacket: method 0 adds, 1 removes, 2 changes; +/// adds and changes carry the display name, render type (0 integer, +/// 1 hearts) and number format. +#[derive(Clone, Debug, PartialEq)] +pub struct SetObjective { + pub name: String, + pub method: i8, + pub display: Option<(Tag, i32, Option)>, +} +impl Codec for SetObjective { + fn read(r: &mut Reader) -> Result { + let name = r.string(32767)?; + let method = r.i8()?; + let display = if method == 0 || method == 2 { + Some((r.nbt()?, r.varint()?, >::read(r)?)) + } else { + None + }; + Ok(Self { + name, + method, + display, + }) + } + fn write(v: &Self, w: &mut Writer) { + w.string(&v.name); + w.i8(v.method); + if v.method == 0 || v.method == 2 { + let (name, render, format) = v.display.clone().unwrap_or((Tag::End, 0, None)); + w.nbt(&name); + w.varint(render); + >::write(&format, w); + } + } +} +/// `ClientboundSetPlayerTeamPacket.Parameters`. +#[derive(Clone, Debug, PartialEq)] +pub struct TeamParameters { + pub display_name: Tag, + pub prefix: Tag, + pub suffix: Tag, + /// `Team.Visibility` id. + pub name_tag_visibility: i32, + /// `Team.CollisionRule` id. + pub collision_rule: i32, + /// `TeamColor` id (0 black .. 15 white), absent for no colour. + pub color: Option, + /// 1: friendly fire, 2: see friendly invisibles. + pub options: i8, +} +/// ClientboundSetPlayerTeamPacket: method 0 adds (parameters and players), +/// 1 removes, 2 changes (parameters), 3 joins and 4 leaves (players). +#[derive(Clone, Debug, PartialEq)] +pub struct SetPlayerTeam { + pub name: String, + pub method: i8, + pub parameters: Option, + pub players: Vec, +} +impl Codec for SetPlayerTeam { + fn read(r: &mut Reader) -> Result { + let name = r.string(32767)?; + let method = r.i8()?; + let parameters = if method == 0 || method == 2 { + Some(TeamParameters { + display_name: r.nbt()?, + prefix: r.nbt()?, + suffix: r.nbt()?, + name_tag_visibility: r.varint()?, + collision_rule: r.varint()?, + color: >::read(r)?, + options: r.i8()?, + }) + } else { + None + }; + let players = if matches!(method, 0 | 3 | 4) { + >::read(r)? + } else { + Vec::new() + }; + Ok(Self { + name, + method, + parameters, + players, + }) + } + fn write(v: &Self, w: &mut Writer) { + w.string(&v.name); + w.i8(v.method); + if v.method == 0 || v.method == 2 { + let p = v.parameters.clone().unwrap_or(TeamParameters { + display_name: Tag::End, + prefix: Tag::End, + suffix: Tag::End, + name_tag_visibility: 0, + collision_rule: 0, + color: None, + options: 0, + }); + w.nbt(&p.display_name); + w.nbt(&p.prefix); + w.nbt(&p.suffix); + w.varint(p.name_tag_visibility); + w.varint(p.collision_rule); + >::write(&p.color, w); + w.i8(p.options); + } + if matches!(v.method, 0 | 3 | 4) { + >::write(&v.players, w); + } + } +} packet!(ServerData { motd: Tag => Nbt, icon: Option> => Opt }); packet!( /// ClientboundUpdateMobEffectPacket; flags: 1 ambient, 2 visible, 4 icon, 8 blend. @@ -746,23 +932,33 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { PlayerRotation(PlayerRotation) = PLAYER_ROTATION, RemoveEntities(RemoveEntities) = REMOVE_ENTITIES, RemoveMobEffect(RemoveMobEffect) = REMOVE_MOB_EFFECT, + ResetScore(ResetScore) = RESET_SCORE, ResourcePackPush(ResourcePackPush) = RESOURCE_PACK_PUSH, Respawn(Respawn) = RESPAWN, RotateHead(RotateHead) = ROTATE_HEAD, SectionBlocksUpdate(SectionBlocksUpdate) = SECTION_BLOCKS_UPDATE, ServerData(ServerData) = SERVER_DATA, SetActionBarText(Text) = SET_ACTION_BAR_TEXT, + SetBorderCenter(SetBorderCenter) = SET_BORDER_CENTER, + SetBorderLerpSize(SetBorderLerpSize) = SET_BORDER_LERP_SIZE, + SetBorderSize(SetBorderSize) = SET_BORDER_SIZE, + SetBorderWarningDelay(SetBorderWarningDelay) = SET_BORDER_WARNING_DELAY, + SetBorderWarningDistance(SetBorderWarningDistance) = SET_BORDER_WARNING_DISTANCE, SetChunkCacheCenter(SetChunkCacheCenter) = SET_CHUNK_CACHE_CENTER, SetChunkCacheRadius(Distance) = SET_CHUNK_CACHE_RADIUS, SetCursorItem(SetCursorItem) = SET_CURSOR_ITEM, SetDefaultSpawnPosition(SetDefaultSpawnPosition) = SET_DEFAULT_SPAWN_POSITION, + SetDisplayObjective(SetDisplayObjective) = SET_DISPLAY_OBJECTIVE, SetEntityData(SetEntityData) = SET_ENTITY_DATA, SetEntityMotion(SetEntityMotion) = SET_ENTITY_MOTION, SetEquipment(SetEquipment) = SET_EQUIPMENT, SetExperience(SetExperience) = SET_EXPERIENCE, SetHealth(SetHealth) = SET_HEALTH, SetHeldSlot(SetHeldSlot) = SET_HELD_SLOT, + SetObjective(SetObjective) = SET_OBJECTIVE, SetPlayerInventory(SetPlayerInventory) = SET_PLAYER_INVENTORY, + SetPlayerTeam(SetPlayerTeam) = SET_PLAYER_TEAM, + SetScore(SetScore) = SET_SCORE, SetSimulationDistance(Distance) = SET_SIMULATION_DISTANCE, SetSubtitleText(Text) = SET_SUBTITLE_TEXT, SetTime(SetTime) = SET_TIME, @@ -948,6 +1144,63 @@ mod tests { fn clientbound_round_trips() { let packets = vec![ Clientbound::BundleDelimiter(Empty), + Clientbound::SetBorderCenter(SetBorderCenter { x: 1.5, z: -2.0 }), + Clientbound::SetBorderLerpSize(SetBorderLerpSize { + old_size: 10.0, + new_size: 200.0, + lerp_time: 1200, + }), + Clientbound::SetBorderSize(SetBorderSize { size: 30.0 }), + Clientbound::SetBorderWarningDelay(SetBorderWarningDelay { delay: 300 }), + Clientbound::SetBorderWarningDistance(SetBorderWarningDistance { blocks: 5 }), + Clientbound::SetDisplayObjective(SetDisplayObjective { + slot: 0, + objective: "kills".into(), + }), + Clientbound::ResetScore(ResetScore { + owner: "Steve".into(), + objective: Some("kills".into()), + }), + Clientbound::SetScore(SetScore { + owner: "Steve".into(), + objective: "kills".into(), + score: -3, + display: Some(Tag::String("S".into())), + number_format: Some(NumberFormat::Styled(Tag::compound([( + "color", + Tag::String("red".into()), + )]))), + }), + Clientbound::SetObjective(SetObjective { + name: "kills".into(), + method: 0, + display: Some((Tag::String("Kills".into()), 1, Some(NumberFormat::Blank))), + }), + Clientbound::SetObjective(SetObjective { + name: "kills".into(), + method: 1, + display: None, + }), + Clientbound::SetPlayerTeam(SetPlayerTeam { + name: "red".into(), + method: 0, + parameters: Some(TeamParameters { + display_name: Tag::String("Red".into()), + prefix: Tag::String("[R] ".into()), + suffix: Tag::String("".into()), + name_tag_visibility: 0, + collision_rule: 0, + color: Some(12), + options: 3, + }), + players: vec!["Steve".into(), "Alex".into()], + }), + Clientbound::SetPlayerTeam(SetPlayerTeam { + name: "red".into(), + method: 4, + parameters: None, + players: vec!["Alex".into()], + }), Clientbound::AddEntity(AddEntity { id: 5, uuid: 9, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTabListOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTabListOracle.java new file mode 100644 index 000000000..006928728 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTabListOracle.java @@ -0,0 +1,283 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import com.mojang.authlib.GameProfile; +import com.mojang.renderpearl.api.pipeline.RenderPipeline; +import com.mojang.serialization.JsonOps; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.Minecraft; +import net.minecraft.client.OptionInstance; +import net.minecraft.client.Options; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.Hud; +import net.minecraft.client.gui.components.PlayerTabOverlay; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.client.multiplayer.PlayerInfo; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.client.player.RemotePlayer; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.ComponentSerialization; +import net.minecraft.network.chat.Style; +import net.minecraft.network.chat.numbers.BlankFormat; +import net.minecraft.network.chat.numbers.FixedFormat; +import net.minecraft.network.chat.numbers.NumberFormat; +import net.minecraft.network.chat.numbers.StyledFormat; +import net.minecraft.resources.Identifier; +import net.minecraft.util.FormattedCharSequence; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.GameType; +import net.minecraft.world.scores.Objective; +import net.minecraft.world.scores.ScoreHolder; +import net.minecraft.world.scores.Scoreboard; +import net.minecraft.world.scores.TeamColor; +import net.minecraft.world.scores.criteria.ObjectiveCriteria; + +/** + * Original oracle for the player list: runs vanilla's own + * PlayerTabOverlay.extractRenderState frame after frame on a stand-in client + * (Unsafe-allocated Minecraft, connection with the case's listed PlayerInfos + * and online mode, level with the case's players, real Scoreboard with the + * case's teams, list objective and scores, options and Hud ticks) and + * records every fill, text (as styled runs), sprite and face blit. + * Visibility changes clear the heart states as setVisible does (without + * the narration). + * + * Input lines: case JSON. Output lines: {case, frames:[[draws]...]} or {case, error}. + */ +public final class VanillaTabListOracle { + static Object unsafe; + static Method allocate; + static JsonArray draws; + static int width; + static Scoreboard board; + + @SuppressWarnings("unchecked") + static T alloc(Class type) throws Exception { + return (T) allocate.invoke(unsafe, type); + } + + static Field field(Class type, String name) throws NoSuchFieldException { + for (Class k = type; k != null; k = k.getSuperclass()) { + try { + Field f = k.getDeclaredField(name); + f.setAccessible(true); + return f; + } catch (NoSuchFieldException e) { + } + } + throw new NoSuchFieldException(name + " on " + type); + } + + static void put(Object target, Class owner, String name, Object value) throws Exception { + Field f = field(owner, name); + boolean isStatic = Modifier.isStatic(f.getModifiers()); + long offset = isStatic + ? (long) unsafe.getClass().getMethod("staticFieldOffset", Field.class).invoke(unsafe, f) + : (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, f); + Object base = isStatic ? unsafe.getClass().getMethod("staticFieldBase", Field.class).invoke(unsafe, f) : target; + Class t = f.getType(); + String setter = t == int.class ? "putInt" : t == boolean.class ? "putBoolean" : t == float.class ? "putFloat" + : t == long.class ? "putLong" : t == double.class ? "putDouble" : "putObject"; + Class param = t.isPrimitive() ? t : Object.class; + unsafe.getClass().getMethod(setter, Object.class, long.class, param).invoke(unsafe, base, offset, value); + } + + static Object get(Object target, Class owner, String name) throws Exception { + return field(owner, name).get(target); + } + + static Component component(JsonElement e) { + return ComponentSerialization.CODEC.parse(JsonOps.INSTANCE, e).getOrThrow(); + } + + static NumberFormat format(JsonElement e) { + if (e == null || e.isJsonNull()) return null; + var o = e.getAsJsonObject(); + return switch (o.get("type").getAsString()) { + case "blank" -> BlankFormat.INSTANCE; + case "styled" -> new StyledFormat(Style.Serializer.CODEC.parse(JsonOps.INSTANCE, o.get("style")).getOrThrow()); + case "fixed" -> new FixedFormat(component(o.get("value"))); + default -> throw new IllegalArgumentException(o.toString()); + }; + } + + /** Records GuiGraphicsExtractor calls. */ + public static final class Capture extends GuiGraphicsExtractor { + private Capture() { super(null, null, 0, 0); } + @Override public int guiWidth() { return width; } + @Override public void nextStratum() { } + @Override public void fill(RenderPipeline p, int x0, int y0, int x1, int y1, int color) { + var o = new JsonObject(); + o.addProperty("type", "fill"); + o.addProperty("x0", x0); o.addProperty("y0", y0); o.addProperty("x1", x1); o.addProperty("y1", y1); + o.addProperty("color", color); + draws.add(o); + } + @Override public void blitSprite(RenderPipeline p, Identifier id, int x, int y, int w, int h, int color) { + var o = new JsonObject(); + o.addProperty("type", "sprite"); + o.addProperty("sprite", id.getPath()); + o.addProperty("x", x); o.addProperty("y", y); o.addProperty("w", w); o.addProperty("h", h); + draws.add(o); + } + @Override public void blit(RenderPipeline p, Identifier texture, int x, int y, float u, float v, int w, int h, int sw, int sh, int tw, int th, int color) { + var o = new JsonObject(); + o.addProperty("type", "blit"); + String path = texture.getPath(); + if (path.startsWith("textures/")) path = path.substring(9); + if (path.endsWith(".png")) path = path.substring(0, path.length() - 4); + o.addProperty("texture", path); + var a = new JsonArray(); + for (float n : new float[] {x, y, u, v, w, h, sw, sh, tw, th}) a.add(n); + o.add("args", a); + o.addProperty("color", color); + draws.add(o); + } + @Override public void text(Font font, FormattedCharSequence str, int x, int y, int color, boolean shadow) { + var o = new JsonObject(); + o.addProperty("type", "text"); + var runs = new JsonArray(); + str.accept((index, style, cp) -> { + var key = new JsonArray(); + key.add(style.getColor() == null ? -1 : style.getColor().getValue()); + key.add(style.isBold()); key.add(style.isItalic()); key.add(style.isUnderlined()); + key.add(style.isStrikethrough()); key.add(style.isObfuscated()); + var last = runs.isEmpty() ? null : runs.get(runs.size() - 1).getAsJsonArray(); + if (last != null && last.get(1).equals(key)) { + last.set(0, new JsonPrimitive(last.get(0).getAsString() + new String(Character.toChars(cp)))); + } else { + var run = new JsonArray(); + run.add(new String(Character.toChars(cp))); + run.add(key); + runs.add(run); + } + return true; + }); + o.add("runs", runs); + o.addProperty("x", x); o.addProperty("y", y); o.addProperty("color", color); o.addProperty("shadow", shadow); + draws.add(o); + } + } + + public static void main(String[] args) throws Exception { + ParityData.init(); + var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + unsafe = unsafeField.get(null); + allocate = unsafe.getClass().getMethod("allocateInstance", Class.class); + Font font = ParityFont.create(ParityFont.resources()); + var gson = new Gson(); + var out = new StringBuilder(); + for (String line : Files.readAllLines(Path.of(args[0]))) { + if (line.isBlank()) continue; + JsonObject c = JsonParser.parseString(line).getAsJsonObject(); + var result = new JsonObject(); + result.add("case", c); + try { + width = c.get("width").getAsInt(); + board = new Scoreboard(); + for (var t : c.getAsJsonArray("teams")) { + var o = t.getAsJsonObject(); + var team = board.addPlayerTeam(o.get("name").getAsString()); + if (!o.get("color").isJsonNull()) team.setColor(Optional.of(TeamColor.byName(o.get("color").getAsString()))); + team.setPlayerPrefix(component(o.get("prefix"))); + team.setPlayerSuffix(component(o.get("suffix"))); + for (var m : o.getAsJsonArray("members")) board.addPlayerToTeam(m.getAsString(), team); + } + Objective objective = null; + if (!c.get("objective").isJsonNull()) { + var o = c.getAsJsonObject("objective"); + var type = o.get("renderType").getAsString().equals("hearts") ? ObjectiveCriteria.RenderType.HEARTS : ObjectiveCriteria.RenderType.INTEGER; + objective = board.addObjective(o.get("name").getAsString(), ObjectiveCriteria.DUMMY, Component.literal("x"), type, false, format(o.get("numberFormat"))); + } + var mc = alloc(Minecraft.class); + put(null, Minecraft.class, "instance", mc); + var level = alloc(ClientLevel.class); + var levelPlayers = new ArrayList(); + put(level, ClientLevel.class, "players", levelPlayers); + put(mc, Minecraft.class, "level", level); + put(mc, Minecraft.class, "font", font); + var options = alloc(Options.class); + var chatOnly = alloc(OptionInstance.class); + put(chatOnly, OptionInstance.class, "value", c.get("backgroundForChatOnly").getAsBoolean()); + put(options, Options.class, "backgroundForChatOnly", chatOnly); + var opacity = alloc(OptionInstance.class); + put(opacity, OptionInstance.class, "value", c.get("opacity").getAsDouble()); + put(options, Options.class, "textBackgroundOpacity", opacity); + put(mc, Minecraft.class, "options", options); + var connection = alloc(ClientPacketListener.class); + put(connection, ClientPacketListener.class, "scoreboard", board); + put(level, ClientLevel.class, "connection", connection); + put(connection, ClientPacketListener.class, "onlineMode", c.get("onlineMode").getAsBoolean()); + var listed = new LinkedHashSet(); + put(connection, ClientPacketListener.class, "listedPlayers", listed); + var player = alloc(LocalPlayer.class); + put(player, LocalPlayer.class, "connection", connection); + put(mc, Minecraft.class, "player", player); + for (var p : c.getAsJsonArray("players")) { + var o = p.getAsJsonObject(); + var uuid = UUID.fromString(o.get("uuid").getAsString()); + var profile = new GameProfile(uuid, o.get("name").getAsString()); + var info = new PlayerInfo(profile, false); + put(info, PlayerInfo.class, "gameMode", GameType.byId(o.get("gameMode").getAsInt())); + put(info, PlayerInfo.class, "latency", o.get("latency").getAsInt()); + if (!o.get("displayName").isJsonNull()) info.setTabListDisplayName(component(o.get("displayName"))); + info.setTabListOrder(o.get("listOrder").getAsInt()); + info.setShowHat(o.get("showHat").getAsBoolean()); + var skin = net.minecraft.client.resources.DefaultPlayerSkin.get(uuid); + put(info, PlayerInfo.class, "skinLookup", (java.util.function.Supplier) () -> skin); + listed.add(info); + if (o.get("inLevel").getAsBoolean()) { + var entity = alloc(RemotePlayer.class); + put(entity, Player.class, "gameProfile", profile); + put(entity, net.minecraft.world.entity.Entity.class, "uuid", uuid); + levelPlayers.add(entity); + } + } + var hud = alloc(Hud.class); + put(hud, Hud.class, "minecraft", mc); + var overlay = new PlayerTabOverlay(mc, hud); + if (!c.get("header").isJsonNull()) overlay.setHeader(component(c.get("header"))); + if (!c.get("footer").isJsonNull()) overlay.setFooter(component(c.get("footer"))); + @SuppressWarnings("unchecked") + var health = (Map) get(overlay, PlayerTabOverlay.class, "healthStates"); + var capture = alloc(Capture.class); + var frames = new JsonArray(); + for (var f : c.getAsJsonArray("frames")) { + var o = f.getAsJsonObject(); + if (objective != null) { + for (var s : o.getAsJsonObject("scores").entrySet()) { + var v = s.getValue().getAsJsonObject(); + var access = board.getOrCreatePlayerScore(ScoreHolder.forNameOnly(s.getKey()), objective); + access.set(v.get("value").getAsInt()); + access.numberFormatOverride(format(v.get("format"))); + } + for (var r : o.getAsJsonArray("reset")) board.resetSinglePlayerScore(ScoreHolder.forNameOnly(r.getAsString()), objective); + } + put(hud, Hud.class, "tickCount", o.get("tick").getAsInt()); + boolean visible = o.get("visible").getAsBoolean(); + if ((boolean) get(overlay, PlayerTabOverlay.class, "visible") != visible) { + health.clear(); + put(overlay, PlayerTabOverlay.class, "visible", visible); + } + draws = new JsonArray(); + if (visible) overlay.extractRenderState(capture, width, board, objective); + frames.add(draws); + } + result.add("frames", frames); + } catch (Throwable error) { + var cause = error instanceof InvocationTargetException && error.getCause() != null ? error.getCause() : error; + var sw = new java.io.StringWriter(); + cause.printStackTrace(new java.io.PrintWriter(sw)); + result.addProperty("error", sw.toString().lines().limit(10).reduce("", (x, y) -> x + y + " | ")); + } + out.append(gson.toJson(result)).append('\n'); + } + Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8); + } +} diff --git a/tools/test_tab_list_parity.py b/tools/test_tab_list_parity.py new file mode 100644 index 000000000..2bcbcc121 --- /dev/null +++ b/tools/test_tab_list_parity.py @@ -0,0 +1,184 @@ +#!/usr/bin/env python3 +"""Compare the player list (tab list) with the vanilla 26.3 client. + +The Java oracle (VanillaTabListOracle) runs vanilla's own +PlayerTabOverlay.extractRenderState, frame after frame, on a stand-in client +whose connection lists the case's players (game mode, latency, display name, +list order, hat layer, online mode for heads), whose level holds some of +them (upside-down Dinnerbone and Grumm) and whose real Scoreboard has the +case's teams (colour, prefix, suffix), `list` objective (integer or hearts, +number formats) and scores, with the header, footer, row background option +and Hud ticks. It records every fill, text (as styled runs), sprite and +face blit. `examples/tab_list_fixture` lays out the same frames with +`horizon_client::tab_list`; the ordered call lists must agree. + + test_tab_list_parity.py [--count N] [--detail N] +""" +import argparse +import json +import os +import random +import subprocess +import sys +import uuid + +try: + from . import lab, test_rust_parity as base, test_model_baking_parity as baking +except ImportError: + import lab, test_rust_parity as base, test_model_baking_parity as baking + +PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' +COLORS = ['black', 'dark_blue', 'dark_green', 'dark_aqua', 'dark_red', 'dark_purple', 'gold', 'gray', 'dark_gray', + 'blue', 'green', 'aqua', 'red', 'light_purple', 'yellow', 'white'] +WORDS = ['Welcome', 'to', 'the', 'server', 'Horizon', 'players', 'online', 'mc.example.net', 'Have', 'fun!', + 'Supercalifragilisticexpialidocious', 'a', 'é', 'Ünïcödé', '§aGreen', '§lBold', '[VIP]', '1234567890'] +NAMES = ['Steve', 'Alex', 'Notch', 'jeb_', 'Dinnerbone', 'Grumm', 'xX_Pro_Xx', 'a', 'Zed', 'zebra', 'Émile', 'ÆON', + 'bob', 'Carl', '_under', '123', 'MMMMMMMMMMMMMMMM', 'iiiiiiii', 'Wide_W', 'ßtraße', 'Ⅻ', 'Mix3d_Case'] + + +def component(rng, words=3, depth=0): + text = ' '.join(rng.choice(WORDS) for _ in range(words)) + kind = rng.random() + if kind < 0.3: + return text + c = {'text': text} + if rng.random() < 0.5: + c['color'] = rng.choice(COLORS + ['#12ABEF']) + for flag in ('bold', 'italic', 'underlined', 'strikethrough', 'obfuscated'): + if rng.random() < 0.15: + c[flag] = rng.random() < 0.8 + if depth < 2 and rng.random() < 0.4: + c['extra'] = [component(rng, rng.randint(1, 3), depth + 1) for _ in range(rng.randint(1, 2))] + if rng.random() < 0.08: + c = {'translate': 'multiplayer.player.list.hp', 'with': [text], 'color': rng.choice(COLORS)} + return c + + +def number_format(rng): + kind = rng.random() + if kind < 0.4: + return None + if kind < 0.55: + return {'type': 'blank'} + if kind < 0.85: + style = {'color': rng.choice(COLORS)} + if rng.random() < 0.4: + style['bold'] = True + return {'type': 'styled', 'style': style} + return {'type': 'fixed', 'value': component(rng, 1)} + + +def cases(count): + rng = random.Random(0x544142) + out = [] + for n in range(count): + size = rng.choice([1, 1, 2, 3, 5, 8, 12, 19, 20, 21, 25, 40, 41, 60, 79, 80, 85, 100]) + names = [] + while len(names) < size: + name = rng.choice(NAMES) if rng.random() < 0.5 else ''.join( + rng.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_') for _ in range(rng.randint(1, 16))) + if name.lower() not in {x.lower() for x in names}: + names.append(name) + players = [] + for name in names: + players.append({ + 'uuid': str(uuid.UUID(int=rng.getrandbits(128))), 'name': name, + 'gameMode': rng.choice([0, 0, 0, 1, 2, 3]), + 'latency': rng.choice([-1, 0, 1, 149, 150, 299, 300, 599, 600, 999, 1000, 5000, rng.randint(0, 2000)]), + 'displayName': component(rng, rng.randint(1, 2)) if rng.random() < 0.2 else None, + 'listOrder': rng.choice([0, 0, 0, 1, -1, 5, 2147483647, -2147483648]), + 'showHat': rng.random() < 0.8, 'inLevel': rng.random() < 0.5, + }) + teams = [] + for t in range(rng.choice([0, 0, 1, 2, 4])): + members = [p['name'] for p in players if rng.random() < 0.3] + teams.append({'name': rng.choice(['red', 'Blue', 'team' + str(t), 'ä', 'z', 'A']) + str(t), + 'color': rng.choice([None] + COLORS), + 'prefix': rng.choice(['', '[R] ', {'text': '★ ', 'color': 'gold', 'bold': True}, component(rng, 1)]), + 'suffix': rng.choice(['', ' ✔', {'text': ' (afk)', 'italic': True}]), 'members': members}) + objective = None + if rng.random() < 0.7: + objective = {'name': 'obj', 'renderType': rng.choice(['integer', 'hearts', 'hearts']), 'numberFormat': number_format(rng)} + frames = [] + tick = rng.randint(0, 100000) + values = {} + for f in range(rng.randint(1, 6)): + scores = {} + for p in players: + if objective and (f == 0 and rng.random() < 0.85 or rng.random() < 0.3): + v = rng.choice([0, 1, 2, 7, 19, 20, 21, 40, 99, 100, -3, 1234567, rng.randint(-50, 300)]) + if p['name'] in values and rng.random() < 0.5: + v = values[p['name']] + rng.choice([-3, -1, 1, 2, 10]) + values[p['name']] = v + scores[p['name']] = {'value': v, 'format': number_format(rng) if rng.random() < 0.2 else None} + reset = [p['name'] for p in players if objective and rng.random() < 0.03] + for r in reset: + values.pop(r, None) + tick += rng.choice([1, 1, 2, 3, 5, 10, 21, 40]) + frames.append({'tick': tick, 'visible': rng.random() < 0.85, 'scores': scores, 'reset': reset}) + header = footer = None + if rng.random() < 0.6: + header = rng.choice([component(rng, rng.randint(1, 30)), 'Line one\nLine two', '\n', 'trailing\n', ' two spaces ', + {'text': 'Header', 'extra': ['\n', component(rng, 12)]}]) + if rng.random() < 0.5: + footer = rng.choice([component(rng, rng.randint(1, 30)), 'Footer', 'x\n\ny']) + out.append({'width': rng.choice([427, 320, 480, 640, 961, 160, 90, 300]), 'onlineMode': rng.random() < 0.7, + 'backgroundForChatOnly': rng.random() < 0.8, 'opacity': rng.choice([0.5, 0.0, 1.0, 0.37]), + 'header': header, 'footer': footer, 'teams': teams, 'objective': objective, 'players': players, + 'frames': frames}) + return out + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--count', type=int, default=700) + parser.add_argument('--detail', type=int, default=3) + args = parser.parse_args() + lock, jars, _ = base.verify_artifacts() + libraries = baking.client_libraries() + build = lab.LOCAL / 'rust-tab-list-parity'; build.mkdir(parents=True, exist_ok=True) + resources = lab.LOCAL / 'horizon-client' / '26.3' + chosen = cases(args.count) + inputs = build / 'inputs.jsonl'; inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen)) + classes = build / 'classes'; classes.mkdir(exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['client'], *libraries])) + + def run(command, name): + with (build / (name + '.log')).open('w') as log: + result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT) + if result.returncode: + print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed') + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes, + *(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaTabListOracle'))], 'compile-java') + run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTabListOracle', + inputs, build / 'vanilla.jsonl'], 'vanilla') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'tab_list_fixture', '--', + resources, inputs, build / 'rust.jsonl'], 'rust') + vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()] + rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()] + assert len(vanilla) == len(rust) + errors, bad, frames, calls = [], [], 0, 0 + for v, r in zip(vanilla, rust): + if 'error' in v: + errors.append(v['error']); continue + for i, (a, b) in enumerate(zip(v['frames'], r['frames'])): + frames += 1 + calls += len(a) + if a != b: + first = next((k for k, (x, y) in enumerate(zip(a, b)) if x != y), min(len(a), len(b))) + bad.append((v['case'], i, first, a[first:first + 2], b[first:first + 2], len(a), len(b))) + break + for e in sorted(set(errors))[:5]: + print('ORACLE ERROR', e) + for case, i, k, a, b, la, lb in bad[:args.detail]: + print('MISMATCH', json.dumps(case)[:3000]) + print(f' frame {i}, call {k} ({la} vanilla, {lb} Horizon calls)\n vanilla {a}\n horizon {b}') + print(f'{len(vanilla) - len(bad) - len(errors)}/{len(vanilla)} player lists match ({frames} frames, {calls} calls); ' + f'{len(errors)} oracle errors') + if bad or errors: + sys.exit(1) + print('tab list parity ok') + + +if __name__ == '__main__': + main()