Add vanilla font metrics with unifont fallback, languages, styled text and a Brigadier command core
Font: bitmap glyph ascent/oversampling, unihex glyphs rasterized on demand into a reserved atlas region, bold/italic/underline/strikethrough and StringSplitter wrapping. Languages layer lang/<code>.json over en_us. The command module ports Brigadier parsing, suggestions and smart usage with the vanilla argument types and the 26.3 command tree; game rules use the 26.3 registry names and saved-data file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Generated
+1
@@ -686,6 +686,7 @@ dependencies = [
|
||||
"horizon-assets",
|
||||
"horizon-core",
|
||||
"horizon-world",
|
||||
"miniz_oxide 0.8.9",
|
||||
"png",
|
||||
"pollster",
|
||||
"serde_json",
|
||||
|
||||
@@ -20,3 +20,4 @@ png = "0.18"
|
||||
serde_json = { version = "1.0.151", features = ["raw_value"] }
|
||||
cpal = "0.16"
|
||||
symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] }
|
||||
miniz_oxide = "0.8"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,639 @@
|
||||
//! A port of Brigadier (the command library vanilla uses): a string reader,
|
||||
//! literal/argument node trees with redirects, parsing that tries every
|
||||
//! relevant child and keeps the best result, completion suggestions, smart
|
||||
//! usage text and the vanilla error messages. Argument types live in
|
||||
//! [`args`]; the vanilla command tree in [`vanilla`].
|
||||
pub mod args;
|
||||
pub mod vanilla;
|
||||
|
||||
use crate::text::Text;
|
||||
pub use args::{Arg, ArgType, Registries};
|
||||
|
||||
/// A command error (CommandSyntaxException): the message and, for parse
|
||||
/// errors, the input and cursor it occurred at.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct CommandError {
|
||||
pub message: Text,
|
||||
pub input: Option<String>,
|
||||
pub cursor: usize,
|
||||
/// BuiltInExceptions.literalIncorrect (summarised specially by the chat UI).
|
||||
pub literal_incorrect: bool,
|
||||
}
|
||||
impl CommandError {
|
||||
pub fn new(message: Text) -> Self {
|
||||
Self { message, input: None, cursor: 0, literal_incorrect: false }
|
||||
}
|
||||
pub fn tr(key: &str, args: &[&dyn std::fmt::Display]) -> Self {
|
||||
Self::new(Text::tr(key, args))
|
||||
}
|
||||
pub fn at(message: Text, reader: &Reader) -> Self {
|
||||
Self { message, input: Some(reader.string.to_owned()), cursor: reader.cursor, literal_incorrect: false }
|
||||
}
|
||||
pub fn tr_at(key: &str, args: &[&dyn std::fmt::Display], reader: &Reader) -> Self {
|
||||
Self::at(Text::tr(key, args), reader)
|
||||
}
|
||||
/// CommandSyntaxException.getContext: up to ten characters before the
|
||||
/// cursor followed by "<--[HERE]".
|
||||
pub fn context(&self) -> Option<String> {
|
||||
let input = self.input.as_ref()?;
|
||||
let cursor = self.cursor.min(input.len());
|
||||
let start = input.floor_char_boundary(cursor.saturating_sub(10));
|
||||
let mut out = String::new();
|
||||
if cursor > 10 {
|
||||
out.push_str("...");
|
||||
}
|
||||
out.push_str(&input[start..cursor]);
|
||||
out.push_str("<--[HERE]");
|
||||
Some(out)
|
||||
}
|
||||
/// The message as shown by command suggestions ("... at position N: ...").
|
||||
pub fn with_context(&self) -> Text {
|
||||
match self.context() {
|
||||
Some(context) => Text::translate("command.context.parse_error", &[self.message.clone(), Text::literal(self.cursor.to_string()), Text::literal(context)]),
|
||||
None => self.message.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub type CmdResult<T> = Result<T, CommandError>;
|
||||
|
||||
/// Brigadier StringReader over a command line (byte cursor on char boundaries).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Reader<'a> {
|
||||
pub string: &'a str,
|
||||
pub cursor: usize,
|
||||
}
|
||||
impl<'a> Reader<'a> {
|
||||
pub fn new(string: &'a str) -> Self {
|
||||
Self { string, cursor: 0 }
|
||||
}
|
||||
pub fn can_read(&self) -> bool {
|
||||
self.cursor < self.string.len()
|
||||
}
|
||||
pub fn can_read_n(&self, n: usize) -> bool {
|
||||
self.string[self.cursor..].chars().take(n).count() == n
|
||||
}
|
||||
pub fn peek(&self) -> char {
|
||||
self.string[self.cursor..].chars().next().unwrap_or('\0')
|
||||
}
|
||||
pub fn peek_at(&self, offset: usize) -> char {
|
||||
self.string[self.cursor..].chars().nth(offset).unwrap_or('\0')
|
||||
}
|
||||
pub fn skip(&mut self) {
|
||||
self.cursor += self.peek().len_utf8();
|
||||
}
|
||||
pub fn read(&mut self) -> char {
|
||||
let c = self.peek();
|
||||
self.skip();
|
||||
c
|
||||
}
|
||||
pub fn remaining(&self) -> &'a str {
|
||||
&self.string[self.cursor..]
|
||||
}
|
||||
pub fn skip_whitespace(&mut self) {
|
||||
while self.can_read() && self.peek().is_whitespace() {
|
||||
self.skip();
|
||||
}
|
||||
}
|
||||
pub fn is_allowed_number(c: char) -> bool {
|
||||
c.is_ascii_digit() || c == '.' || c == '-'
|
||||
}
|
||||
pub fn is_allowed_in_unquoted(c: char) -> bool {
|
||||
c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '+')
|
||||
}
|
||||
fn read_number_text(&mut self) -> &'a str {
|
||||
let start = self.cursor;
|
||||
while self.can_read() && Self::is_allowed_number(self.peek()) {
|
||||
self.skip();
|
||||
}
|
||||
&self.string[start..self.cursor]
|
||||
}
|
||||
fn number<T: std::str::FromStr>(&mut self, kind: &str) -> CmdResult<T> {
|
||||
let start = self.cursor;
|
||||
let text = self.read_number_text();
|
||||
if text.is_empty() {
|
||||
return Err(CommandError::tr_at(&format!("parsing.{kind}.expected"), &[], self));
|
||||
}
|
||||
// Java's parsers reject a trailing '.'-less exponent etc. the same way.
|
||||
match text.parse::<T>() {
|
||||
Ok(v) if !(kind == "int" || kind == "long") || !text.contains('.') => Ok(v),
|
||||
_ => {
|
||||
self.cursor = start;
|
||||
Err(CommandError::tr_at(&format!("parsing.{kind}.invalid"), &[&text], self))
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn read_int(&mut self) -> CmdResult<i32> {
|
||||
self.number("int")
|
||||
}
|
||||
pub fn read_long(&mut self) -> CmdResult<i64> {
|
||||
self.number("long")
|
||||
}
|
||||
pub fn read_double(&mut self) -> CmdResult<f64> {
|
||||
self.number("double")
|
||||
}
|
||||
pub fn read_float(&mut self) -> CmdResult<f32> {
|
||||
self.number("float")
|
||||
}
|
||||
pub fn read_unquoted_string(&mut self) -> &'a str {
|
||||
let start = self.cursor;
|
||||
while self.can_read() && Self::is_allowed_in_unquoted(self.peek()) {
|
||||
self.skip();
|
||||
}
|
||||
&self.string[start..self.cursor]
|
||||
}
|
||||
pub fn read_string_until(&mut self, terminator: char) -> CmdResult<String> {
|
||||
let mut out = String::new();
|
||||
let mut escaped = false;
|
||||
while self.can_read() {
|
||||
let c = self.read();
|
||||
if escaped {
|
||||
if c == terminator || c == '\\' {
|
||||
out.push(c);
|
||||
escaped = false;
|
||||
} else {
|
||||
self.cursor -= c.len_utf8();
|
||||
return Err(CommandError::tr_at("parsing.quote.escape", &[&c], self));
|
||||
}
|
||||
} else if c == '\\' {
|
||||
escaped = true;
|
||||
} else if c == terminator {
|
||||
return Ok(out);
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
Err(CommandError::tr_at("parsing.quote.expected.end", &[], self))
|
||||
}
|
||||
pub fn read_quoted_string(&mut self) -> CmdResult<String> {
|
||||
if !self.can_read() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let next = self.peek();
|
||||
if next != '"' && next != '\'' {
|
||||
return Err(CommandError::tr_at("parsing.quote.expected.start", &[], self));
|
||||
}
|
||||
self.skip();
|
||||
self.read_string_until(next)
|
||||
}
|
||||
pub fn read_string(&mut self) -> CmdResult<String> {
|
||||
if !self.can_read() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let next = self.peek();
|
||||
if next == '"' || next == '\'' {
|
||||
self.skip();
|
||||
return self.read_string_until(next);
|
||||
}
|
||||
Ok(self.read_unquoted_string().to_owned())
|
||||
}
|
||||
pub fn read_boolean(&mut self) -> CmdResult<bool> {
|
||||
let start = self.cursor;
|
||||
let value = self.read_string()?;
|
||||
if value.is_empty() {
|
||||
return Err(CommandError::tr_at("parsing.bool.expected", &[], self));
|
||||
}
|
||||
match value.as_str() {
|
||||
"true" => Ok(true),
|
||||
"false" => Ok(false),
|
||||
_ => {
|
||||
self.cursor = start;
|
||||
Err(CommandError::tr_at("parsing.bool.invalid", &[&value], self))
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn expect(&mut self, c: char) -> CmdResult<()> {
|
||||
if !self.can_read() || self.peek() != c {
|
||||
return Err(CommandError::tr_at("parsing.expected", &[&c], self));
|
||||
}
|
||||
self.skip();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub type Range = (usize, usize);
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum NodeKind {
|
||||
Root,
|
||||
Literal(String),
|
||||
Argument { name: String, ty: ArgType },
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Node {
|
||||
pub kind: NodeKind,
|
||||
pub children: Vec<usize>,
|
||||
/// The command id run when parsing ends here.
|
||||
pub command: Option<&'static str>,
|
||||
pub redirect: Option<usize>,
|
||||
/// Required permission level (0 everyone, 2 game masters, 4 owners).
|
||||
pub permission: u8,
|
||||
}
|
||||
impl Node {
|
||||
pub fn name(&self) -> &str {
|
||||
match &self.kind {
|
||||
NodeKind::Root => "",
|
||||
NodeKind::Literal(l) => l,
|
||||
NodeKind::Argument { name, .. } => name,
|
||||
}
|
||||
}
|
||||
/// CommandNode.getUsageText.
|
||||
pub fn usage_text(&self) -> String {
|
||||
match &self.kind {
|
||||
NodeKind::Root => String::new(),
|
||||
NodeKind::Literal(l) => l.clone(),
|
||||
NodeKind::Argument { name, .. } => format!("<{name}>"),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ParsedArg {
|
||||
pub name: String,
|
||||
pub value: Arg,
|
||||
pub range: Range,
|
||||
}
|
||||
/// CommandContextBuilder: the nodes and arguments parsed so far.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Context {
|
||||
pub root: usize,
|
||||
pub nodes: Vec<(usize, Range)>,
|
||||
pub args: Vec<ParsedArg>,
|
||||
pub command: Option<&'static str>,
|
||||
pub range: Range,
|
||||
pub child: Option<Box<Context>>,
|
||||
/// Literal words parsed so far (mode keywords such as `masked`).
|
||||
pub literals: Vec<String>,
|
||||
}
|
||||
impl Context {
|
||||
fn new(root: usize, start: usize) -> Self {
|
||||
Self { root, nodes: Vec::new(), args: Vec::new(), command: None, range: (start, start), child: None, literals: Vec::new() }
|
||||
}
|
||||
/// Whether the literal `word` was parsed (in this context).
|
||||
pub fn has(&self, word: &str) -> bool {
|
||||
self.literals.iter().any(|l| l == word)
|
||||
}
|
||||
fn with_node(&mut self, node: usize, range: Range) {
|
||||
self.nodes.push((node, range));
|
||||
self.range = (self.range.0.min(range.0), self.range.1.max(range.1));
|
||||
}
|
||||
pub fn last_child(&self) -> &Context {
|
||||
let mut c = self;
|
||||
while let Some(child) = &c.child {
|
||||
c = child;
|
||||
}
|
||||
c
|
||||
}
|
||||
pub fn get(&self, name: &str) -> Option<&Arg> {
|
||||
self.args.iter().rev().find(|a| a.name == name).map(|a| &a.value)
|
||||
}
|
||||
/// CommandContextBuilder.findSuggestionContext: the node whose children
|
||||
/// complete the text at `cursor`, and where that text starts.
|
||||
pub fn suggestion_context(&self, cursor: usize) -> (usize, usize, &Context) {
|
||||
if self.range.1 < cursor {
|
||||
if let Some(child) = &self.child {
|
||||
return child.suggestion_context(cursor);
|
||||
}
|
||||
if let Some((node, range)) = self.nodes.last() {
|
||||
return (*node, range.1 + 1, self);
|
||||
}
|
||||
return (self.root, self.range.0, self);
|
||||
}
|
||||
let mut prev = self.root;
|
||||
for (node, range) in &self.nodes {
|
||||
if range.0 <= cursor && cursor <= range.1 {
|
||||
return (prev, range.0, self);
|
||||
}
|
||||
prev = *node;
|
||||
}
|
||||
(prev, self.range.0, self)
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ParseResults {
|
||||
pub context: Context,
|
||||
pub input: String,
|
||||
pub cursor: usize,
|
||||
pub errors: Vec<(usize, CommandError)>,
|
||||
}
|
||||
impl ParseResults {
|
||||
pub fn can_read(&self) -> bool {
|
||||
self.cursor < self.input.len()
|
||||
}
|
||||
/// Commands.getParseException.
|
||||
pub fn error(&self) -> Option<CommandError> {
|
||||
if !self.can_read() {
|
||||
return None;
|
||||
}
|
||||
if self.errors.len() == 1 {
|
||||
return Some(self.errors[0].1.clone());
|
||||
}
|
||||
let reader = Reader { string: &self.input, cursor: self.cursor };
|
||||
Some(if self.context.range.0 == self.context.range.1 {
|
||||
CommandError::tr_at("command.unknown.command", &[], &reader)
|
||||
} else {
|
||||
CommandError::tr_at("command.unknown.argument", &[], &reader)
|
||||
})
|
||||
}
|
||||
/// The executable context and command id, or the vanilla error.
|
||||
pub fn executable(&self) -> CmdResult<(&Context, &'static str)> {
|
||||
if let Some(e) = self.error() {
|
||||
return Err(e);
|
||||
}
|
||||
let last = self.context.last_child();
|
||||
match last.command {
|
||||
Some(id) => Ok((last, id)),
|
||||
None => Err(CommandError::tr_at("command.unknown.command", &[], &Reader { string: &self.input, cursor: self.cursor })),
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A completion: replace `range` of the input with `text`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Suggestion {
|
||||
pub range: Range,
|
||||
pub text: String,
|
||||
pub tooltip: Option<String>,
|
||||
}
|
||||
impl Suggestion {
|
||||
/// Suggestion.apply.
|
||||
pub fn apply(&self, input: &str) -> String {
|
||||
let (s, e) = (self.range.0.min(input.len()), self.range.1.min(input.len()));
|
||||
format!("{}{}{}", &input[..s], self.text, &input[e..])
|
||||
}
|
||||
}
|
||||
/// SuggestionsBuilder: suggestions for the text from `start` to the cursor.
|
||||
pub struct SuggestionsBuilder<'a> {
|
||||
pub input: &'a str,
|
||||
pub start: usize,
|
||||
pub out: Vec<Suggestion>,
|
||||
}
|
||||
impl<'a> SuggestionsBuilder<'a> {
|
||||
pub fn new(input: &'a str, start: usize) -> Self {
|
||||
Self { input, start: start.min(input.len()), out: Vec::new() }
|
||||
}
|
||||
pub fn remaining(&self) -> &'a str {
|
||||
&self.input[self.start..]
|
||||
}
|
||||
pub fn remaining_lower(&self) -> String {
|
||||
self.remaining().to_lowercase()
|
||||
}
|
||||
pub fn suggest(&mut self, text: impl Into<String>) {
|
||||
let text = text.into();
|
||||
if text != self.remaining() {
|
||||
self.out.push(Suggestion { range: (self.start, self.input.len()), text, tooltip: None });
|
||||
}
|
||||
}
|
||||
pub fn suggest_tooltip(&mut self, text: impl Into<String>, tooltip: impl Into<String>) {
|
||||
let text = text.into();
|
||||
if text != self.remaining() {
|
||||
self.out.push(Suggestion { range: (self.start, self.input.len()), text, tooltip: Some(tooltip.into()) });
|
||||
}
|
||||
}
|
||||
pub fn offset(&self, start: usize) -> SuggestionsBuilder<'a> {
|
||||
SuggestionsBuilder::new(self.input, start)
|
||||
}
|
||||
/// SharedSuggestionProvider.suggest: candidates starting with the remaining text.
|
||||
pub fn suggest_matching<'b>(&mut self, candidates: impl IntoIterator<Item = &'b str>) {
|
||||
let lower = self.remaining_lower();
|
||||
for c in candidates {
|
||||
if c.to_lowercase().starts_with(&lower) {
|
||||
self.suggest(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Suggestions.create: merged, expanded to a common range and sorted case-insensitively.
|
||||
pub fn merge_suggestions(input: &str, list: Vec<Suggestion>) -> (Range, Vec<Suggestion>) {
|
||||
if list.is_empty() {
|
||||
return ((0, 0), Vec::new());
|
||||
}
|
||||
let start = list.iter().map(|s| s.range.0).min().unwrap_or(0);
|
||||
let end = list.iter().map(|s| s.range.1).max().unwrap_or(0);
|
||||
let mut out: Vec<Suggestion> = Vec::new();
|
||||
for s in list {
|
||||
// Suggestion.expand: pad the text with the input around it.
|
||||
let text = format!("{}{}{}", &input[start..s.range.0], s.text, &input[s.range.1..end]);
|
||||
let expanded = Suggestion { range: (start, end), text, tooltip: s.tooltip };
|
||||
if !out.iter().any(|o| o.text == expanded.text) {
|
||||
out.push(expanded);
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.text.to_lowercase().cmp(&b.text.to_lowercase()));
|
||||
((start, end), out)
|
||||
}
|
||||
|
||||
/// The command tree (CommandDispatcher). Node 0 is the root.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Dispatcher {
|
||||
pub nodes: Vec<Node>,
|
||||
}
|
||||
impl Default for Dispatcher {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
impl Dispatcher {
|
||||
pub fn new() -> Self {
|
||||
Self { nodes: vec![Node { kind: NodeKind::Root, children: Vec::new(), command: None, redirect: None, permission: 0 }] }
|
||||
}
|
||||
fn add(&mut self, parent: usize, kind: NodeKind) -> usize {
|
||||
let name = match &kind {
|
||||
NodeKind::Literal(l) => l.clone(),
|
||||
NodeKind::Argument { name, .. } => name.clone(),
|
||||
NodeKind::Root => String::new(),
|
||||
};
|
||||
// CommandNode.addChild merges same-named children.
|
||||
if let Some(&existing) = self.nodes[parent].children.iter().find(|&&c| self.nodes[c].name() == name) {
|
||||
return existing;
|
||||
}
|
||||
let permission = self.nodes[parent].permission;
|
||||
self.nodes.push(Node { kind, children: Vec::new(), command: None, redirect: None, permission });
|
||||
let id = self.nodes.len() - 1;
|
||||
self.nodes[parent].children.push(id);
|
||||
id
|
||||
}
|
||||
pub fn literal(&mut self, parent: usize, name: &str) -> usize {
|
||||
self.add(parent, NodeKind::Literal(name.to_owned()))
|
||||
}
|
||||
pub fn argument(&mut self, parent: usize, name: &str, ty: ArgType) -> usize {
|
||||
self.add(parent, NodeKind::Argument { name: name.to_owned(), ty })
|
||||
}
|
||||
pub fn executes(&mut self, node: usize, command: &'static str) -> usize {
|
||||
self.nodes[node].command = Some(command);
|
||||
node
|
||||
}
|
||||
pub fn redirect(&mut self, node: usize, target: usize) -> usize {
|
||||
self.nodes[node].redirect = Some(target);
|
||||
node
|
||||
}
|
||||
pub fn requires(&mut self, node: usize, level: u8) -> usize {
|
||||
self.nodes[node].permission = level;
|
||||
node
|
||||
}
|
||||
/// A root literal by name.
|
||||
pub fn find(&self, name: &str) -> Option<usize> {
|
||||
self.nodes[0].children.iter().copied().find(|&c| self.nodes[c].name() == name)
|
||||
}
|
||||
fn relevant(&self, node: usize, reader: &Reader) -> Vec<usize> {
|
||||
let children = &self.nodes[node].children;
|
||||
let literals: Vec<usize> = children.iter().copied().filter(|&c| matches!(self.nodes[c].kind, NodeKind::Literal(_))).collect();
|
||||
let arguments: Vec<usize> = children.iter().copied().filter(|&c| matches!(self.nodes[c].kind, NodeKind::Argument { .. })).collect();
|
||||
if literals.is_empty() {
|
||||
return arguments;
|
||||
}
|
||||
let rest = reader.remaining();
|
||||
let word = rest.split(' ').next().unwrap_or("");
|
||||
match literals.iter().find(|&&l| self.nodes[l].name() == word) {
|
||||
Some(&l) => vec![l],
|
||||
None => arguments,
|
||||
}
|
||||
}
|
||||
fn parse_node(&self, node: usize, reader: &mut Reader, context: &mut Context, reg: &Registries) -> CmdResult<()> {
|
||||
let start = reader.cursor;
|
||||
match &self.nodes[node].kind {
|
||||
NodeKind::Root => Ok(()),
|
||||
NodeKind::Literal(literal) => {
|
||||
if reader.remaining().starts_with(literal.as_str()) {
|
||||
let end = start + literal.len();
|
||||
reader.cursor = end;
|
||||
if !reader.can_read() || reader.peek() == ' ' {
|
||||
context.with_node(node, (start, end));
|
||||
context.literals.push(literal.clone());
|
||||
return Ok(());
|
||||
}
|
||||
reader.cursor = start;
|
||||
}
|
||||
let mut e = CommandError::tr_at("argument.literal.incorrect", &[literal], reader);
|
||||
e.literal_incorrect = true;
|
||||
Err(e)
|
||||
}
|
||||
NodeKind::Argument { name, ty } => {
|
||||
let value = ty.parse(reader, reg)?;
|
||||
let range = (start, reader.cursor);
|
||||
context.args.push(ParsedArg { name: name.clone(), value, range });
|
||||
context.with_node(node, range);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
fn parse_nodes(&self, node: usize, input: &str, cursor: usize, so_far: &Context, reg: &Registries, level: u8) -> ParseResults {
|
||||
let mut errors = Vec::new();
|
||||
let mut potentials: Vec<ParseResults> = Vec::new();
|
||||
let original = Reader { string: input, cursor };
|
||||
for child in self.relevant(node, &original) {
|
||||
if self.nodes[child].permission > level {
|
||||
continue;
|
||||
}
|
||||
let mut context = so_far.clone();
|
||||
let mut reader = original.clone();
|
||||
let parsed = self.parse_node(child, &mut reader, &mut context, reg).and_then(|()| {
|
||||
if reader.can_read() && reader.peek() != ' ' {
|
||||
Err(CommandError::tr_at("command.expected.separator", &[], &reader))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
});
|
||||
if let Err(e) = parsed {
|
||||
errors.push((child, e));
|
||||
continue;
|
||||
}
|
||||
context.command = self.nodes[child].command;
|
||||
let redirect = self.nodes[child].redirect;
|
||||
if reader.can_read_n(if redirect.is_none() { 2 } else { 1 }) {
|
||||
reader.skip();
|
||||
if let Some(target) = redirect {
|
||||
let child_context = Context::new(target, reader.cursor);
|
||||
let parse = self.parse_nodes(target, input, reader.cursor, &child_context, reg, level);
|
||||
context.child = Some(Box::new(parse.context));
|
||||
return ParseResults { context, input: input.to_owned(), cursor: parse.cursor, errors: parse.errors };
|
||||
}
|
||||
potentials.push(self.parse_nodes(child, input, reader.cursor, &context, reg, level));
|
||||
} else {
|
||||
potentials.push(ParseResults { context, input: input.to_owned(), cursor: reader.cursor, errors: Vec::new() });
|
||||
}
|
||||
}
|
||||
if !potentials.is_empty() {
|
||||
// Prefer fully read input, then results without errors (stable sort).
|
||||
potentials.sort_by_key(|p| (p.can_read(), !p.errors.is_empty()));
|
||||
return potentials.swap_remove(0);
|
||||
}
|
||||
ParseResults { context: so_far.clone(), input: input.to_owned(), cursor, errors }
|
||||
}
|
||||
/// CommandDispatcher.parse from the start of `input` (no leading slash).
|
||||
pub fn parse(&self, input: &str, reg: &Registries) -> ParseResults {
|
||||
self.parse_at(input, 0, reg)
|
||||
}
|
||||
/// Parse starting at byte `start` (after a leading '/').
|
||||
pub fn parse_at(&self, input: &str, start: usize, reg: &Registries) -> ParseResults {
|
||||
let context = Context::new(0, start);
|
||||
self.parse_nodes(0, input, start, &context, reg, reg.permission)
|
||||
}
|
||||
/// CommandDispatcher.getCompletionSuggestions at `cursor`.
|
||||
pub fn suggestions(&self, parse: &ParseResults, cursor: usize, reg: &Registries) -> (Range, Vec<Suggestion>) {
|
||||
let (parent, start, context) = parse.context.suggestion_context(cursor);
|
||||
let start = start.min(cursor);
|
||||
let truncated = &parse.input[..cursor.min(parse.input.len())];
|
||||
let mut all = Vec::new();
|
||||
for &child in &self.nodes[parent].children {
|
||||
if self.nodes[child].permission > reg.permission {
|
||||
continue;
|
||||
}
|
||||
let mut builder = SuggestionsBuilder::new(truncated, start);
|
||||
match &self.nodes[child].kind {
|
||||
NodeKind::Literal(l) => {
|
||||
if l.to_lowercase().starts_with(&builder.remaining_lower()) {
|
||||
builder.suggest(l.clone());
|
||||
}
|
||||
}
|
||||
NodeKind::Argument { ty, name } => ty.suggest(&mut builder, reg, context, name),
|
||||
NodeKind::Root => {}
|
||||
}
|
||||
all.extend(builder.out);
|
||||
}
|
||||
merge_suggestions(truncated, all)
|
||||
}
|
||||
fn smart_usage_of(&self, node: usize, optional: bool, deep: bool, level: u8) -> Option<String> {
|
||||
let n = &self.nodes[node];
|
||||
if n.permission > level {
|
||||
return None;
|
||||
}
|
||||
let this = if optional { format!("[{}]", n.usage_text()) } else { n.usage_text() };
|
||||
let child_optional = n.command.is_some();
|
||||
let (open, close) = if child_optional { ("[", "]") } else { ("(", ")") };
|
||||
if !deep {
|
||||
if let Some(r) = n.redirect {
|
||||
let target = if r == 0 { "...".to_owned() } else { format!("-> {}", self.nodes[r].usage_text()) };
|
||||
return Some(format!("{this} {target}"));
|
||||
}
|
||||
let children: Vec<usize> = n.children.iter().copied().filter(|&c| self.nodes[c].permission <= level).collect();
|
||||
if children.len() == 1 {
|
||||
if let Some(usage) = self.smart_usage_of(children[0], child_optional, child_optional, level) {
|
||||
return Some(format!("{this} {usage}"));
|
||||
}
|
||||
} else if children.len() > 1 {
|
||||
let mut child_usage: Vec<String> = Vec::new();
|
||||
for &c in &children {
|
||||
if let Some(u) = self.smart_usage_of(c, child_optional, true, level)
|
||||
&& !child_usage.contains(&u)
|
||||
{
|
||||
child_usage.push(u);
|
||||
}
|
||||
}
|
||||
if child_usage.len() == 1 {
|
||||
let usage = &child_usage[0];
|
||||
return Some(format!("{this} {}", if child_optional { format!("[{usage}]") } else { usage.clone() }));
|
||||
}
|
||||
if child_usage.len() > 1 {
|
||||
let alternatives: Vec<String> = children.iter().map(|&c| self.nodes[c].usage_text()).collect();
|
||||
return Some(format!("{this} {open}{}{close}", alternatives.join("|")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(this)
|
||||
}
|
||||
/// CommandDispatcher.getSmartUsage: one line per child of `node`.
|
||||
pub fn smart_usage(&self, node: usize, level: u8) -> Vec<(usize, String)> {
|
||||
let optional = self.nodes[node].command.is_some();
|
||||
self.nodes[node].children.iter().filter_map(|&c| self.smart_usage_of(c, optional, false, level).map(|u| (c, u))).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,139 @@
|
||||
use super::{args::*, vanilla, *};
|
||||
|
||||
fn reg() -> Registries {
|
||||
let mut r = Registries { permission: 4, ..Registries::default() };
|
||||
r.items = vec!["minecraft:diamond".into(), "minecraft:diamond_sword".into(), "minecraft:stone".into()];
|
||||
r.blocks.insert("minecraft:stone".into(), vec![]);
|
||||
r.blocks.insert(
|
||||
"minecraft:oak_stairs".into(),
|
||||
vec![("facing".into(), vec!["north".into(), "south".into()]), ("half".into(), vec!["top".into(), "bottom".into()])],
|
||||
);
|
||||
r.summonable = vec!["minecraft:pig".into(), "minecraft:zombie".into()];
|
||||
r.entity_types = vec!["minecraft:pig".into(), "minecraft:player".into(), "minecraft:zombie".into()];
|
||||
r.players = vec!["Player".into()];
|
||||
r.dimensions = vec!["minecraft:overworld".into()];
|
||||
r.time_markers = vec!["minecraft:day".into(), "minecraft:noon".into()];
|
||||
r
|
||||
}
|
||||
fn run(input: &str) -> CmdResult<(String, Vec<String>)> {
|
||||
let reg = reg();
|
||||
let parse = vanilla::dispatcher().parse(input, ®);
|
||||
let (ctx, id) = parse.executable()?;
|
||||
Ok((id.to_owned(), ctx.args.iter().map(|a| a.name.clone()).collect()))
|
||||
}
|
||||
fn suggestions(input: &str) -> Vec<String> {
|
||||
let reg = reg();
|
||||
let d = vanilla::dispatcher();
|
||||
let parse = d.parse(input, ®);
|
||||
d.suggestions(&parse, input.len(), ®).1.into_iter().map(|s| s.text).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reader_matches_brigadier() {
|
||||
let mut r = Reader::new("12 -3.5 abc \"q\\\"x\" true");
|
||||
assert_eq!(r.read_int().unwrap(), 12);
|
||||
r.skip();
|
||||
assert_eq!(r.read_double().unwrap(), -3.5);
|
||||
r.skip();
|
||||
assert_eq!(r.read_unquoted_string(), "abc");
|
||||
r.skip();
|
||||
assert_eq!(r.read_string().unwrap(), "q\"x");
|
||||
r.skip();
|
||||
assert!(r.read_boolean().unwrap());
|
||||
let e = Reader::new("1.5").read_int().unwrap_err();
|
||||
assert_eq!(e.message.plain(), "parsing.int.invalid");
|
||||
assert_eq!(e.context().unwrap(), "<--[HERE]");
|
||||
}
|
||||
#[test]
|
||||
fn parses_vanilla_commands() {
|
||||
assert_eq!(run("gamemode creative").unwrap().0, "gamemode");
|
||||
assert_eq!(run("gamemode creative @s").unwrap().1, ["gamemode", "target"]);
|
||||
assert_eq!(run("give @s minecraft:diamond 64").unwrap().1, ["targets", "item", "count"]);
|
||||
assert_eq!(run("tp 1 2 3").unwrap().0, "teleport.location");
|
||||
assert_eq!(run("tp Player").unwrap().0, "teleport.destination");
|
||||
assert_eq!(run("tp @s ~ ~10 ~").unwrap().0, "teleport.targets.location");
|
||||
assert_eq!(run("teleport @e[type=pig,limit=2] ^ ^ ^5 90 0").unwrap().0, "teleport.targets.location");
|
||||
assert_eq!(run("time set 1000").unwrap().0, "time.set");
|
||||
assert_eq!(run("time set 1d").unwrap().0, "time.set");
|
||||
assert_eq!(run("time set day").unwrap().0, "time.set.marker");
|
||||
assert_eq!(run("time query gametime").unwrap().0, "time.query.gametime");
|
||||
assert_eq!(run("weather rain 10s").unwrap().0, "weather");
|
||||
assert_eq!(run("xp add @s 5 levels").unwrap().0, "experience");
|
||||
assert_eq!(run("gamerule keep_inventory true").unwrap().0, "gamerule");
|
||||
assert_eq!(run("gamerule minecraft:random_tick_speed 10").unwrap().0, "gamerule");
|
||||
assert_eq!(run("fill ~ ~ ~ ~1 ~1 ~1 stone hollow").unwrap().0, "fill");
|
||||
assert_eq!(run("fill 0 0 0 1 1 1 minecraft:oak_stairs[facing=north] replace stone").unwrap().0, "fill");
|
||||
assert_eq!(run("clone 0 0 0 1 1 1 5 5 5 masked move").unwrap().0, "clone");
|
||||
assert_eq!(run("setblock ~ ~1 ~ oak_stairs[half=top] keep").unwrap().0, "setblock");
|
||||
assert_eq!(run("summon zombie ~ ~ ~ {NoAI:1b}").unwrap().0, "summon");
|
||||
assert_eq!(run("difficulty hard").unwrap().0, "difficulty");
|
||||
assert_eq!(run("say hello @p").unwrap().0, "say");
|
||||
let reg = reg();
|
||||
let parse = vanilla::dispatcher().parse("clone 0 0 0 1 1 1 5 5 5 strict filtered stone force", ®);
|
||||
let (ctx, _) = parse.executable().unwrap();
|
||||
assert!(ctx.has("strict") && ctx.has("filtered") && ctx.has("force") && !ctx.has("move"));
|
||||
}
|
||||
#[test]
|
||||
fn vanilla_error_messages() {
|
||||
let e = run("foo").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "command.unknown.command");
|
||||
assert_eq!(e.cursor, 0);
|
||||
let e = run("gamemode").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "command.unknown.command");
|
||||
let e = run("gamemode creatve").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.gamemode.invalid");
|
||||
assert_eq!(e.cursor, 9);
|
||||
let e = run("give @s minecraft:dirt").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.item.id.invalid");
|
||||
let e = run("give @s diamond 0").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.integer.low");
|
||||
let e = run("gamemode creative @e").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.player.entities");
|
||||
let e = run("setblock 1 2").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.pos3d.incomplete");
|
||||
let e = run("setblock 1 2 3 oak_stairs[facing=up]").unwrap_err();
|
||||
assert_eq!(e.message.plain(), "argument.block.property.invalid");
|
||||
}
|
||||
#[test]
|
||||
fn suggestions_like_vanilla() {
|
||||
let root = suggestions("");
|
||||
assert!(root.contains(&"gamemode".to_owned()) && root.contains(&"tp".to_owned()));
|
||||
assert_eq!(suggestions("game"), ["gamemode", "gamerule"]);
|
||||
assert_eq!(suggestions("gamemode "), ["adventure", "creative", "spectator", "survival"]);
|
||||
assert_eq!(suggestions("gamemode c"), ["creative"]);
|
||||
assert_eq!(suggestions("give @s dia"), ["minecraft:diamond", "minecraft:diamond_sword"]);
|
||||
// Underscore-separated parts match too (SharedSuggestionProvider.matchesSubStr).
|
||||
assert_eq!(suggestions("give @s sword"), ["minecraft:diamond_sword"]);
|
||||
assert_eq!(suggestions("kill @"), ["@a", "@e", "@n", "@p", "@r", "@s"]);
|
||||
assert_eq!(suggestions("kill @e"), ["["]);
|
||||
assert_eq!(suggestions("kill @e[ty"), ["type="]);
|
||||
assert!(suggestions("kill @e[type=").contains(&"minecraft:zombie".to_owned()));
|
||||
assert_eq!(suggestions("kill @e[type=pig"), [",", "]"]);
|
||||
assert_eq!(suggestions("setblock 0 0 0 oak_stairs[fa"), ["facing="]);
|
||||
assert_eq!(suggestions("setblock 0 0 0 oak_stairs[facing=n"), ["north"]);
|
||||
assert_eq!(suggestions("tp "), ["@a", "@e", "@n", "@p", "@r", "@s", "Player", "~", "~ ~", "~ ~ ~"]);
|
||||
assert_eq!(suggestions("time set 5"), ["d", "s", "t"]);
|
||||
assert!(suggestions("time set ").contains(&"minecraft:day".to_owned()));
|
||||
}
|
||||
#[test]
|
||||
fn smart_usage_matches_brigadier() {
|
||||
let d = vanilla::dispatcher();
|
||||
let usage = |name: &str| d.smart_usage(0, 4).into_iter().find(|(n, _)| d.nodes[*n].name() == name).unwrap().1;
|
||||
assert_eq!(usage("gamemode"), "gamemode <gamemode> [<target>]");
|
||||
assert_eq!(usage("give"), "give <targets> <item> [<count>]");
|
||||
assert_eq!(usage("kill"), "kill [<targets>]");
|
||||
assert_eq!(usage("weather"), "weather (clear|rain|thunder)");
|
||||
assert_eq!(usage("tp"), "tp -> teleport");
|
||||
assert_eq!(usage("difficulty"), "difficulty [peaceful|easy|normal|hard]");
|
||||
}
|
||||
#[test]
|
||||
fn local_coordinates_follow_view() {
|
||||
// Facing south (yaw 0) moves +Z.
|
||||
let p = Coordinates::Local([0.0, 0.0, 2.0]).position([0.0, 64.0, 0.0], [0.0, 0.0]);
|
||||
assert!((p[2] - 2.0).abs() < 1e-6 && p[0].abs() < 1e-6);
|
||||
// ^1 (left) while facing south is +X.
|
||||
let p = Coordinates::Local([1.0, 0.0, 0.0]).position([0.0, 64.0, 0.0], [0.0, 0.0]);
|
||||
assert!((p[0] - 1.0).abs() < 1e-6, "{p:?}");
|
||||
let w = Coordinates::World([Coord { relative: true, value: 1.0 }, Coord { relative: false, value: 5.0 }, Coord { relative: true, value: 0.0 }]);
|
||||
assert_eq!(w.position([10.0, 64.0, 3.0], [0.0, 0.0]), [11.0, 5.0, 3.0]);
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
//! The vanilla command tree (Commands.java registrations) for the commands
|
||||
//! Horizon implements. Leaves carry command ids that the game executes;
|
||||
//! mode keywords are read back from the parsed literals.
|
||||
use super::{
|
||||
Dispatcher,
|
||||
args::{ArgType, GameMode, Resource, integer},
|
||||
};
|
||||
use crate::gamerules::{RULES, Value};
|
||||
|
||||
/// Permission levels (Commands.LEVEL_*).
|
||||
pub const ALL: u8 = 0;
|
||||
pub const GAMEMASTERS: u8 = 2;
|
||||
|
||||
const PLAYERS: ArgType = ArgType::Entity { single: false, players: true };
|
||||
const PLAYER: ArgType = ArgType::Entity { single: true, players: true };
|
||||
const ENTITIES: ArgType = ArgType::Entity { single: false, players: false };
|
||||
const ENTITY: ArgType = ArgType::Entity { single: true, players: false };
|
||||
|
||||
pub const DIFFICULTIES: [&str; 4] = ["peaceful", "easy", "normal", "hard"];
|
||||
|
||||
pub fn build() -> Dispatcher {
|
||||
let mut d = Dispatcher::new();
|
||||
let root = 0;
|
||||
|
||||
// help [<command>]
|
||||
let help = d.literal(root, "help");
|
||||
d.executes(help, "help");
|
||||
let c = d.argument(help, "command", ArgType::Greedy);
|
||||
d.executes(c, "help");
|
||||
|
||||
// gamemode <gamemode> [<target>]
|
||||
let gm = d.literal(root, "gamemode");
|
||||
d.requires(gm, GAMEMASTERS);
|
||||
let mode = d.argument(gm, "gamemode", ArgType::GameMode);
|
||||
d.executes(mode, "gamemode");
|
||||
let t = d.argument(mode, "target", PLAYERS);
|
||||
d.executes(t, "gamemode");
|
||||
|
||||
let dgm = d.literal(root, "defaultgamemode");
|
||||
d.requires(dgm, GAMEMASTERS);
|
||||
let mode = d.argument(dgm, "gamemode", ArgType::GameMode);
|
||||
d.executes(mode, "defaultgamemode");
|
||||
|
||||
// give <targets> <item> [<count>]
|
||||
let give = d.literal(root, "give");
|
||||
d.requires(give, GAMEMASTERS);
|
||||
let targets = d.argument(give, "targets", PLAYERS);
|
||||
let item = d.argument(targets, "item", ArgType::Item);
|
||||
d.executes(item, "give");
|
||||
let count = d.argument(item, "count", integer(1));
|
||||
d.executes(count, "give");
|
||||
|
||||
// teleport / tp
|
||||
let tp = d.literal(root, "teleport");
|
||||
d.requires(tp, GAMEMASTERS);
|
||||
let loc = d.argument(tp, "location", ArgType::Vec3 { center: true });
|
||||
d.executes(loc, "teleport.location");
|
||||
let dest = d.argument(tp, "destination", ENTITY);
|
||||
d.executes(dest, "teleport.destination");
|
||||
let targets = d.argument(tp, "targets", ENTITIES);
|
||||
let loc = d.argument(targets, "location", ArgType::Vec3 { center: true });
|
||||
d.executes(loc, "teleport.targets.location");
|
||||
let rot = d.argument(loc, "rotation", ArgType::Rotation);
|
||||
d.executes(rot, "teleport.targets.location");
|
||||
let facing = d.literal(loc, "facing");
|
||||
let fe = d.literal(facing, "entity");
|
||||
let fent = d.argument(fe, "facingEntity", ENTITY);
|
||||
d.executes(fent, "teleport.targets.location");
|
||||
let anchor = d.argument(fent, "facingAnchor", ArgType::Anchor);
|
||||
d.executes(anchor, "teleport.targets.location");
|
||||
let floc = d.argument(facing, "facingLocation", ArgType::Vec3 { center: true });
|
||||
d.executes(floc, "teleport.targets.location");
|
||||
let dest = d.argument(targets, "destination", ENTITY);
|
||||
d.executes(dest, "teleport.targets.destination");
|
||||
let alias = d.literal(root, "tp");
|
||||
d.requires(alias, GAMEMASTERS);
|
||||
d.redirect(alias, tp);
|
||||
|
||||
// time: clock nodes for the dimension's default clock, plus `of <clock>`.
|
||||
let time = d.literal(root, "time");
|
||||
d.requires(time, GAMEMASTERS);
|
||||
clock_nodes(&mut d, time);
|
||||
let query = d.literal(time, "query");
|
||||
let gt = d.literal(query, "gametime");
|
||||
d.executes(gt, "time.query.gametime");
|
||||
let of = d.literal(time, "of");
|
||||
let clock = d.argument(of, "clock", ArgType::Resource(Resource::Clock));
|
||||
clock_nodes(&mut d, clock);
|
||||
|
||||
// weather (clear|rain|thunder) [<duration>]
|
||||
let weather = d.literal(root, "weather");
|
||||
d.requires(weather, GAMEMASTERS);
|
||||
for kind in ["clear", "rain", "thunder"] {
|
||||
let k = d.literal(weather, kind);
|
||||
d.executes(k, "weather");
|
||||
let dur = d.argument(k, "duration", ArgType::Time { min: 1 });
|
||||
d.executes(dur, "weather");
|
||||
}
|
||||
|
||||
// kill [<targets>]
|
||||
let kill = d.literal(root, "kill");
|
||||
d.requires(kill, GAMEMASTERS);
|
||||
d.executes(kill, "kill");
|
||||
let t = d.argument(kill, "targets", ENTITIES);
|
||||
d.executes(t, "kill");
|
||||
|
||||
// summon <entity> [<pos>] [<nbt>]
|
||||
let summon = d.literal(root, "summon");
|
||||
d.requires(summon, GAMEMASTERS);
|
||||
let e = d.argument(summon, "entity", ArgType::Resource(Resource::EntityType));
|
||||
d.executes(e, "summon");
|
||||
let pos = d.argument(e, "pos", ArgType::Vec3 { center: true });
|
||||
d.executes(pos, "summon");
|
||||
let nbt = d.argument(pos, "nbt", ArgType::Nbt);
|
||||
d.executes(nbt, "summon");
|
||||
|
||||
// setblock <pos> <block> [destroy|keep|replace|strict]
|
||||
let sb = d.literal(root, "setblock");
|
||||
d.requires(sb, GAMEMASTERS);
|
||||
let pos = d.argument(sb, "pos", ArgType::BlockPos);
|
||||
let block = d.argument(pos, "block", ArgType::BlockState);
|
||||
d.executes(block, "setblock");
|
||||
for m in ["destroy", "keep", "replace", "strict"] {
|
||||
let l = d.literal(block, m);
|
||||
d.executes(l, "setblock");
|
||||
}
|
||||
|
||||
// fill <from> <to> <block> [modes]
|
||||
let fill = d.literal(root, "fill");
|
||||
d.requires(fill, GAMEMASTERS);
|
||||
let from = d.argument(fill, "from", ArgType::BlockPos);
|
||||
let to = d.argument(from, "to", ArgType::BlockPos);
|
||||
let block = d.argument(to, "block", ArgType::BlockState);
|
||||
fill_modes(&mut d, block);
|
||||
let replace = d.literal(block, "replace");
|
||||
d.executes(replace, "fill");
|
||||
let filter = d.argument(replace, "filter", ArgType::BlockPredicate);
|
||||
fill_modes(&mut d, filter);
|
||||
let keep = d.literal(block, "keep");
|
||||
d.executes(keep, "fill");
|
||||
|
||||
// clone [from <dim>] <begin> <end> [to <dim>] <destination> [strict] [mask] [mode]
|
||||
let clone = d.literal(root, "clone");
|
||||
d.requires(clone, GAMEMASTERS);
|
||||
clone_begin(&mut d, clone);
|
||||
let from = d.literal(clone, "from");
|
||||
let dim = d.argument(from, "sourceDimension", ArgType::Dimension);
|
||||
clone_begin(&mut d, dim);
|
||||
|
||||
// experience / xp
|
||||
let xp = d.literal(root, "experience");
|
||||
d.requires(xp, GAMEMASTERS);
|
||||
for (op, min) in [("add", i32::MIN), ("set", 0)] {
|
||||
let o = d.literal(xp, op);
|
||||
let t = d.argument(o, "target", PLAYERS);
|
||||
let amount = d.argument(t, "amount", integer(min));
|
||||
d.executes(amount, "experience");
|
||||
for unit in ["points", "levels"] {
|
||||
let u = d.literal(amount, unit);
|
||||
d.executes(u, "experience");
|
||||
}
|
||||
}
|
||||
let q = d.literal(xp, "query");
|
||||
let t = d.argument(q, "target", PLAYER);
|
||||
for unit in ["points", "levels"] {
|
||||
let u = d.literal(t, unit);
|
||||
d.executes(u, "experience");
|
||||
}
|
||||
let alias = d.literal(root, "xp");
|
||||
d.requires(alias, GAMEMASTERS);
|
||||
d.redirect(alias, xp);
|
||||
|
||||
// gamerule <rule> [<value>] (short and namespaced names)
|
||||
let gr = d.literal(root, "gamerule");
|
||||
d.requires(gr, GAMEMASTERS);
|
||||
for rule in RULES {
|
||||
for name in [rule.name.to_owned(), format!("minecraft:{}", rule.name)] {
|
||||
let r = d.literal(gr, &name);
|
||||
d.executes(r, "gamerule");
|
||||
let ty = match rule.default {
|
||||
Value::Bool(_) => ArgType::Bool,
|
||||
Value::Int(_) => ArgType::Integer { min: rule.min, max: rule.max },
|
||||
};
|
||||
let v = d.argument(r, "value", ty);
|
||||
d.executes(v, "gamerule");
|
||||
}
|
||||
}
|
||||
|
||||
// difficulty [<difficulty>]
|
||||
let diff = d.literal(root, "difficulty");
|
||||
d.executes(diff, "difficulty");
|
||||
for name in DIFFICULTIES {
|
||||
let l = d.literal(diff, name);
|
||||
d.requires(l, GAMEMASTERS);
|
||||
d.executes(l, "difficulty");
|
||||
}
|
||||
|
||||
let seed = d.literal(root, "seed");
|
||||
d.executes(seed, "seed");
|
||||
|
||||
// spawnpoint [<targets>] [<pos>] [<rotation>]
|
||||
let sp = d.literal(root, "spawnpoint");
|
||||
d.requires(sp, GAMEMASTERS);
|
||||
d.executes(sp, "spawnpoint");
|
||||
let t = d.argument(sp, "targets", PLAYERS);
|
||||
d.executes(t, "spawnpoint");
|
||||
let pos = d.argument(t, "pos", ArgType::BlockPos);
|
||||
d.executes(pos, "spawnpoint");
|
||||
let rot = d.argument(pos, "rotation", ArgType::Rotation);
|
||||
d.executes(rot, "spawnpoint");
|
||||
|
||||
// setworldspawn [<pos>] [<rotation>]
|
||||
let ws = d.literal(root, "setworldspawn");
|
||||
d.requires(ws, GAMEMASTERS);
|
||||
d.executes(ws, "setworldspawn");
|
||||
let pos = d.argument(ws, "pos", ArgType::BlockPos);
|
||||
d.executes(pos, "setworldspawn");
|
||||
let rot = d.argument(pos, "rotation", ArgType::Rotation);
|
||||
d.executes(rot, "setworldspawn");
|
||||
|
||||
// clear [<targets>] [<item>] [<maxCount>]
|
||||
let clear = d.literal(root, "clear");
|
||||
d.requires(clear, GAMEMASTERS);
|
||||
d.executes(clear, "clear");
|
||||
let t = d.argument(clear, "targets", PLAYERS);
|
||||
d.executes(t, "clear");
|
||||
let item = d.argument(t, "item", ArgType::ItemPredicate);
|
||||
d.executes(item, "clear");
|
||||
let max = d.argument(item, "maxCount", integer(0));
|
||||
d.executes(max, "clear");
|
||||
|
||||
// locate (structure|biome) <...>
|
||||
let locate = d.literal(root, "locate");
|
||||
d.requires(locate, GAMEMASTERS);
|
||||
let s = d.literal(locate, "structure");
|
||||
let a = d.argument(s, "structure", ArgType::Resource(Resource::Structure));
|
||||
d.executes(a, "locate.structure");
|
||||
let b = d.literal(locate, "biome");
|
||||
let a = d.argument(b, "biome", ArgType::Resource(Resource::Biome));
|
||||
d.executes(a, "locate.biome");
|
||||
|
||||
// say / me / msg / list
|
||||
let say = d.literal(root, "say");
|
||||
d.requires(say, GAMEMASTERS);
|
||||
let m = d.argument(say, "message", ArgType::Message);
|
||||
d.executes(m, "say");
|
||||
let me = d.literal(root, "me");
|
||||
let m = d.argument(me, "action", ArgType::Message);
|
||||
d.executes(m, "me");
|
||||
let msg = d.literal(root, "msg");
|
||||
let t = d.argument(msg, "targets", PLAYERS);
|
||||
let m = d.argument(t, "message", ArgType::Message);
|
||||
d.executes(m, "msg");
|
||||
for alias in ["tell", "w"] {
|
||||
let a = d.literal(root, alias);
|
||||
d.redirect(a, msg);
|
||||
}
|
||||
let list = d.literal(root, "list");
|
||||
d.executes(list, "list");
|
||||
let uuids = d.literal(list, "uuids");
|
||||
d.executes(uuids, "list");
|
||||
|
||||
d
|
||||
}
|
||||
|
||||
/// TimeCommand.addClockNodes.
|
||||
fn clock_nodes(d: &mut Dispatcher, node: usize) {
|
||||
let set = d.literal(node, "set");
|
||||
let t = d.argument(set, "time", ArgType::Time { min: 0 });
|
||||
d.executes(t, "time.set");
|
||||
let marker = d.argument(set, "timemarker", ArgType::Id("time_markers"));
|
||||
d.executes(marker, "time.set.marker");
|
||||
let add = d.literal(node, "add");
|
||||
let t = d.argument(add, "time", ArgType::Time { min: i32::MIN });
|
||||
d.executes(t, "time.add");
|
||||
let pause = d.literal(node, "pause");
|
||||
d.executes(pause, "time.pause");
|
||||
let resume = d.literal(node, "resume");
|
||||
d.executes(resume, "time.resume");
|
||||
let rate = d.literal(node, "rate");
|
||||
let r = d.argument(rate, "rate", ArgType::Float { min: 1.0e-5, max: 1000.0 });
|
||||
d.executes(r, "time.rate");
|
||||
let query = d.literal(node, "query");
|
||||
let time = d.literal(query, "time");
|
||||
d.executes(time, "time.query.time");
|
||||
let tl = d.argument(query, "timeline", ArgType::Resource(Resource::Timeline));
|
||||
d.executes(tl, "time.query.timeline");
|
||||
let rep = d.literal(tl, "repetition");
|
||||
d.executes(rep, "time.query.repetition");
|
||||
}
|
||||
/// FillCommand.wrapWithMode.
|
||||
fn fill_modes(d: &mut Dispatcher, node: usize) {
|
||||
d.executes(node, "fill");
|
||||
for m in ["outline", "hollow", "destroy", "strict"] {
|
||||
let l = d.literal(node, m);
|
||||
d.executes(l, "fill");
|
||||
}
|
||||
}
|
||||
fn clone_begin(d: &mut Dispatcher, node: usize) {
|
||||
let begin = d.argument(node, "begin", ArgType::BlockPos);
|
||||
let end = d.argument(begin, "end", ArgType::BlockPos);
|
||||
clone_destination(d, end);
|
||||
let to = d.literal(end, "to");
|
||||
let dim = d.argument(to, "targetDimension", ArgType::Dimension);
|
||||
clone_destination(d, dim);
|
||||
}
|
||||
fn clone_destination(d: &mut Dispatcher, node: usize) {
|
||||
let dest = d.argument(node, "destination", ArgType::BlockPos);
|
||||
clone_mask(d, dest);
|
||||
let strict = d.literal(dest, "strict");
|
||||
clone_mask(d, strict);
|
||||
}
|
||||
fn clone_mask(d: &mut Dispatcher, node: usize) {
|
||||
d.executes(node, "clone");
|
||||
for m in ["replace", "masked"] {
|
||||
let l = d.literal(node, m);
|
||||
clone_mode(d, l);
|
||||
}
|
||||
let filtered = d.literal(node, "filtered");
|
||||
let filter = d.argument(filtered, "filter", ArgType::BlockPredicate);
|
||||
clone_mode(d, filter);
|
||||
}
|
||||
fn clone_mode(d: &mut Dispatcher, node: usize) {
|
||||
d.executes(node, "clone");
|
||||
for m in ["force", "move", "normal"] {
|
||||
let l = d.literal(node, m);
|
||||
d.executes(l, "clone");
|
||||
}
|
||||
}
|
||||
/// Game mode names for selector `gamemode=` and the argument.
|
||||
pub fn game_modes() -> [&'static str; 4] {
|
||||
GameMode::ALL.map(GameMode::name)
|
||||
}
|
||||
/// The shared vanilla tree.
|
||||
pub fn dispatcher() -> &'static Dispatcher {
|
||||
static TREE: std::sync::OnceLock<Dispatcher> = std::sync::OnceLock::new();
|
||||
TREE.get_or_init(build)
|
||||
}
|
||||
#[allow(unused)]
|
||||
const _: (u8, u8) = (ALL, GAMEMASTERS);
|
||||
@@ -0,0 +1,455 @@
|
||||
//! The default font (FontSet over `font/default.json`): space and bitmap
|
||||
//! providers from the shared atlas, the unihex (GNU Unifont) fallback whose
|
||||
//! glyphs are rasterized on demand into a reserved atlas region, vanilla
|
||||
//! glyph metrics (ascent, oversampling, advances, bold/shadow offsets),
|
||||
//! styled drawing and StringSplitter-style line wrapping.
|
||||
use crate::{
|
||||
hud::Rect,
|
||||
text::{Style, Text},
|
||||
zip::Zip,
|
||||
};
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
collections::HashMap,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
/// A glyph ready to draw: atlas UVs and its box relative to the pen
|
||||
/// position (GlyphBitmap left/top/right/bottom), in GUI pixels.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Glyph {
|
||||
pub rect: Option<Rect>,
|
||||
pub left: f32,
|
||||
pub top: f32,
|
||||
pub right: f32,
|
||||
pub bottom: f32,
|
||||
pub advance: f32,
|
||||
/// Shadow and bold offset (1 for bitmap glyphs, 0.5 for unihex).
|
||||
pub offset: f32,
|
||||
}
|
||||
/// Pixels to copy into the shared atlas before the next HUD draw.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Patch {
|
||||
pub x: u32,
|
||||
pub y: u32,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub rgba: Vec<u8>,
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
struct HexGlyph {
|
||||
/// Rows left-aligned in 32 bits.
|
||||
rows: [u32; 16],
|
||||
left: u32,
|
||||
right: u32,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct HexProvider {
|
||||
glyphs: HashMap<u32, HexGlyph>,
|
||||
}
|
||||
struct Cache {
|
||||
glyphs: HashMap<char, Glyph>,
|
||||
cursor: (u32, u32),
|
||||
pending: Vec<Patch>,
|
||||
hex: Option<Vec<HexProvider>>,
|
||||
}
|
||||
pub struct Font {
|
||||
bitmap: HashMap<char, Glyph>,
|
||||
space: HashMap<char, f32>,
|
||||
missing: Glyph,
|
||||
white: Rect,
|
||||
root: PathBuf,
|
||||
/// Atlas size and the reserved dynamic region (y, height).
|
||||
atlas: (u32, u32),
|
||||
region: (u32, u32),
|
||||
cache: RefCell<Cache>,
|
||||
/// "Force Unicode Font": skip the bitmap providers (font/uniform.json).
|
||||
pub uniform: bool,
|
||||
/// "Japanese Glyph Variants": enable providers filtered on `jp`.
|
||||
pub japanese: bool,
|
||||
}
|
||||
fn parse_hex_digit(b: u8) -> Option<u32> {
|
||||
(b as char).to_digit(16)
|
||||
}
|
||||
/// UnihexProvider.readFromStream over one `.hex` file.
|
||||
fn parse_hex(text: &[u8], out: &mut HashMap<u32, HexGlyph>) {
|
||||
for line in text.split(|b| *b == b'\n') {
|
||||
let line = line.strip_suffix(b"\r").unwrap_or(line);
|
||||
let Some(colon) = line.iter().position(|b| *b == b':') else { continue };
|
||||
let (code, data) = (&line[..colon], &line[colon + 1..]);
|
||||
if !(4..=6).contains(&code.len()) {
|
||||
continue;
|
||||
}
|
||||
let Some(codepoint) = code.iter().try_fold(0u32, |a, b| parse_hex_digit(*b).map(|d| a << 4 | d)) else { continue };
|
||||
let digits_per_row = match data.len() {
|
||||
32 => 2,
|
||||
64 => 4,
|
||||
96 => 6,
|
||||
128 => 8,
|
||||
_ => continue,
|
||||
};
|
||||
let bit_width = digits_per_row as u32 * 4;
|
||||
let mut rows = [0u32; 16];
|
||||
let mut mask = 0u32;
|
||||
let mut ok = true;
|
||||
for (r, row) in rows.iter_mut().enumerate() {
|
||||
let chunk = &data[r * digits_per_row..(r + 1) * digits_per_row];
|
||||
match chunk.iter().try_fold(0u32, |a, b| parse_hex_digit(*b).map(|d| a << 4 | d)) {
|
||||
Some(v) => {
|
||||
*row = v << (32 - bit_width);
|
||||
mask |= *row;
|
||||
}
|
||||
None => ok = false,
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
continue;
|
||||
}
|
||||
// LineData.calculateWidth.
|
||||
let (left, right) = if mask == 0 { (0, bit_width) } else { (mask.leading_zeros(), 31 - mask.trailing_zeros()) };
|
||||
out.insert(codepoint, HexGlyph { rows, left, right });
|
||||
}
|
||||
}
|
||||
fn read_json(root: &Path, path: &str) -> Option<serde_json::Value> {
|
||||
serde_json::from_slice(&std::fs::read(root.join(path)).ok()?).ok()
|
||||
}
|
||||
fn resource_path(id: &str, folder: &str, ext: &str) -> String {
|
||||
let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id));
|
||||
format!("assets/{ns}/{folder}/{}{ext}", path.trim_end_matches(ext))
|
||||
}
|
||||
/// Providers of a font definition with references expanded, in order, with
|
||||
/// their `filter` objects.
|
||||
fn providers(root: &Path, id: &str, depth: u32, out: &mut Vec<serde_json::Value>) {
|
||||
if depth > 8 {
|
||||
return;
|
||||
}
|
||||
let Some(def) = read_json(root, &resource_path(id, "font", ".json")) else { return };
|
||||
for p in def["providers"].as_array().into_iter().flatten() {
|
||||
if p["type"] == "reference" {
|
||||
let mut nested = Vec::new();
|
||||
providers(root, p["id"].as_str().unwrap_or(""), depth + 1, &mut nested);
|
||||
for mut n in nested {
|
||||
// A reference's filter applies to everything it includes.
|
||||
if let Some(f) = p["filter"].as_object() {
|
||||
let merged = n["filter"].as_object().cloned().unwrap_or_default().into_iter().chain(f.clone()).collect();
|
||||
n["filter"] = serde_json::Value::Object(merged);
|
||||
}
|
||||
out.push(n);
|
||||
}
|
||||
} else {
|
||||
out.push(p.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Font {
|
||||
/// Build from the atlas holding the bitmap font sheets. `pixels` is the
|
||||
/// RGBA atlas (for glyph widths) and `region` the reserved rows.
|
||||
pub fn load(root: &Path, sprites: &HashMap<String, Rect>, pixels: &[u8], atlas: (u32, u32), region: (u32, u32), white: Rect) -> Self {
|
||||
let mut bitmap = HashMap::new();
|
||||
let mut space = HashMap::new();
|
||||
let mut all = Vec::new();
|
||||
providers(root, "minecraft:default", 0, &mut all);
|
||||
for provider in &all {
|
||||
match provider["type"].as_str() {
|
||||
Some("space") => {
|
||||
for (k, v) in provider["advances"].as_object().into_iter().flatten() {
|
||||
if let (Some(c), Some(a)) = (k.chars().next(), v.as_f64()) {
|
||||
space.entry(c).or_insert(a as f32);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("bitmap") => {
|
||||
// Only non-uniform bitmap sheets exist in the default font.
|
||||
let file = provider["file"].as_str().unwrap_or("");
|
||||
let name = file.trim_start_matches("minecraft:").trim_end_matches(".png");
|
||||
let name = format!("{}", name);
|
||||
let Some(rect) = sprites.get(&name).copied() else { continue };
|
||||
let rows: Vec<Vec<char>> = provider["chars"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|r| r.as_str().map(|s| s.chars().collect()))
|
||||
.collect();
|
||||
if rows.is_empty() || rows[0].is_empty() {
|
||||
continue;
|
||||
}
|
||||
let cell_w = rect.w / rows[0].len() as u32;
|
||||
let cell_h = rect.h / rows.len() as u32;
|
||||
let height = provider["height"].as_f64().unwrap_or(8.0) as f32;
|
||||
let ascent = provider["ascent"].as_f64().unwrap_or(7.0) as f32;
|
||||
let scale = height / cell_h as f32;
|
||||
let (ax, ay) = ((rect.u0 * atlas.0 as f32).round() as u32, (rect.v0 * atlas.1 as f32).round() as u32);
|
||||
for (r, row) in rows.iter().enumerate() {
|
||||
for (c, ch) in row.iter().enumerate() {
|
||||
if *ch == '\0' || bitmap.contains_key(ch) {
|
||||
continue;
|
||||
}
|
||||
let (cx, cy) = (ax + c as u32 * cell_w, ay + r as u32 * cell_h);
|
||||
// BitmapProvider.getActualGlyphWidth.
|
||||
let mut used = 0;
|
||||
for x in (0..cell_w).rev() {
|
||||
if (0..cell_h).any(|y| pixels.get((((cy + y) * atlas.0 + cx + x) * 4 + 3) as usize).is_some_and(|a| *a != 0)) {
|
||||
used = x + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
let top = 7.0 - ascent;
|
||||
bitmap.insert(
|
||||
*ch,
|
||||
Glyph {
|
||||
rect: Some(Rect {
|
||||
u0: cx as f32 / atlas.0 as f32,
|
||||
v0: cy as f32 / atlas.1 as f32,
|
||||
u1: (cx + cell_w) as f32 / atlas.0 as f32,
|
||||
v1: (cy + cell_h) as f32 / atlas.1 as f32,
|
||||
w: cell_w,
|
||||
h: cell_h,
|
||||
}),
|
||||
left: 0.0,
|
||||
top,
|
||||
right: cell_w as f32 * scale,
|
||||
bottom: top + cell_h as f32 * scale,
|
||||
advance: (0.5 + used as f32 * scale).floor() + 1.0,
|
||||
offset: 1.0,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let missing = Glyph { rect: None, left: 0.0, top: 0.0, right: 5.0, bottom: 8.0, advance: 6.0, offset: 1.0 };
|
||||
Self {
|
||||
bitmap,
|
||||
space,
|
||||
missing,
|
||||
white,
|
||||
root: root.to_owned(),
|
||||
atlas,
|
||||
region,
|
||||
cache: RefCell::new(Cache { glyphs: HashMap::new(), cursor: (0, 0), pending: Vec::new(), hex: None }),
|
||||
uniform: false,
|
||||
japanese: false,
|
||||
}
|
||||
}
|
||||
fn load_hex(&self) -> Vec<HexProvider> {
|
||||
let mut all = Vec::new();
|
||||
providers(&self.root, "minecraft:default", 0, &mut all);
|
||||
let mut out = Vec::new();
|
||||
for p in all.iter().filter(|p| p["type"] == "unihex") {
|
||||
if let Some(filter) = p["filter"].as_object() {
|
||||
let pass = filter.iter().all(|(k, v)| match k.as_str() {
|
||||
"jp" => v.as_bool() == Some(self.japanese),
|
||||
"uniform" => v.as_bool() == Some(self.uniform),
|
||||
_ => true,
|
||||
});
|
||||
if !pass {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let Some(file) = p["hex_file"].as_str() else { continue };
|
||||
let path = self.root.join(resource_path(file, "", "").replace("//", "/"));
|
||||
let Ok(zip) = Zip::open(&path) else { continue };
|
||||
let mut provider = HexProvider::default();
|
||||
let names: Vec<String> = zip.names().filter(|n| n.ends_with(".hex")).map(str::to_owned).collect();
|
||||
for name in names {
|
||||
if let Ok(bytes) = zip.read(&name) {
|
||||
parse_hex(&bytes, &mut provider.glyphs);
|
||||
}
|
||||
}
|
||||
for o in p["size_overrides"].as_array().into_iter().flatten() {
|
||||
let from = o["from"].as_str().and_then(|s| s.chars().next()).map_or(0, u32::from);
|
||||
let to = o["to"].as_str().and_then(|s| s.chars().next()).map_or(0, u32::from);
|
||||
let (left, right) = (o["left"].as_u64().unwrap_or(0) as u32, o["right"].as_u64().unwrap_or(15) as u32);
|
||||
for c in from..=to {
|
||||
if let Some(g) = provider.glyphs.get_mut(&c) {
|
||||
g.left = left;
|
||||
g.right = right;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(provider);
|
||||
}
|
||||
out
|
||||
}
|
||||
/// Forget rasterized fallback glyphs (after changing font options).
|
||||
pub fn reset_cache(&self) {
|
||||
let mut cache = self.cache.borrow_mut();
|
||||
cache.glyphs.clear();
|
||||
cache.cursor = (0, 0);
|
||||
cache.hex = None;
|
||||
}
|
||||
/// The glyph for a character (FontSet.getGlyph).
|
||||
pub fn glyph(&self, c: char) -> Glyph {
|
||||
if let Some(a) = self.space.get(&c) {
|
||||
return Glyph { rect: None, left: 0.0, top: 0.0, right: 0.0, bottom: 0.0, advance: *a, offset: 1.0 };
|
||||
}
|
||||
if !self.uniform
|
||||
&& let Some(g) = self.bitmap.get(&c)
|
||||
{
|
||||
return *g;
|
||||
}
|
||||
if let Some(g) = self.cache.borrow().glyphs.get(&c) {
|
||||
return *g;
|
||||
}
|
||||
let mut cache = self.cache.borrow_mut();
|
||||
if cache.hex.is_none() {
|
||||
cache.hex = Some(self.load_hex());
|
||||
}
|
||||
let hex = cache.hex.as_ref().and_then(|providers| providers.iter().find_map(|p| p.glyphs.get(&u32::from(c)).copied()));
|
||||
let glyph = match hex {
|
||||
Some(h) => self.rasterize(&mut cache, h).unwrap_or(self.missing),
|
||||
None => self.missing,
|
||||
};
|
||||
cache.glyphs.insert(c, glyph);
|
||||
glyph
|
||||
}
|
||||
fn rasterize(&self, cache: &mut Cache, h: HexGlyph) -> Option<Glyph> {
|
||||
let width = h.right.saturating_sub(h.left) + 1;
|
||||
let (mut x, mut y) = cache.cursor;
|
||||
if x + width + 1 > self.atlas.0 {
|
||||
x = 0;
|
||||
y += 17;
|
||||
}
|
||||
if y + 16 > self.region.1 {
|
||||
return None;
|
||||
}
|
||||
let mut rgba = Vec::with_capacity((width * 16 * 4) as usize);
|
||||
for row in h.rows {
|
||||
for bit in h.left..=h.right {
|
||||
let set = bit < 32 && (row >> (31 - bit)) & 1 != 0;
|
||||
rgba.extend(if set { [255; 4] } else { [0; 4] });
|
||||
}
|
||||
}
|
||||
let (ax, ay) = (x, self.region.0 + y);
|
||||
cache.pending.push(Patch { x: ax, y: ay, width, height: 16, rgba });
|
||||
cache.cursor = (x + width + 1, y);
|
||||
Some(Glyph {
|
||||
rect: Some(Rect {
|
||||
u0: ax as f32 / self.atlas.0 as f32,
|
||||
v0: ay as f32 / self.atlas.1 as f32,
|
||||
u1: (ax + width) as f32 / self.atlas.0 as f32,
|
||||
v1: (ay + 16) as f32 / self.atlas.1 as f32,
|
||||
w: width,
|
||||
h: 16,
|
||||
}),
|
||||
left: 0.0,
|
||||
top: 0.0,
|
||||
right: width as f32 / 2.0,
|
||||
bottom: 8.0,
|
||||
advance: (width / 2 + 1) as f32,
|
||||
offset: 0.5,
|
||||
})
|
||||
}
|
||||
/// Atlas pixels rasterized since the last call.
|
||||
pub fn take_patches(&self) -> Vec<Patch> {
|
||||
std::mem::take(&mut self.cache.borrow_mut().pending)
|
||||
}
|
||||
pub fn advance(&self, c: char, style: &Style) -> f32 {
|
||||
let g = self.glyph(c);
|
||||
g.advance + if style.is_bold() { g.offset } else { 0.0 }
|
||||
}
|
||||
/// Font.width of plain text (legacy codes are formatting, not glyphs).
|
||||
pub fn width(&self, s: &str) -> f32 {
|
||||
if s.contains('§') {
|
||||
return self.width_text(&Text::legacy(s));
|
||||
}
|
||||
s.chars().map(|c| self.glyph(c).advance).sum::<f32>().ceil()
|
||||
}
|
||||
pub fn width_text(&self, t: &Text) -> f32 {
|
||||
t.chars().map(|(c, s)| self.advance(c, s)).sum::<f32>().ceil()
|
||||
}
|
||||
/// StringSplitter.splitLines: wrap at the last space that fits (or
|
||||
/// mid-word when none does); `\n` always breaks. Styles are kept.
|
||||
pub fn split(&self, t: &Text, max_width: f32) -> Vec<Text> {
|
||||
let chars: Vec<(char, Style)> = t.chars().map(|(c, s)| (c, s.clone())).collect();
|
||||
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 last_space = None;
|
||||
for (i, (c, style)) in chars.iter().enumerate().skip(start) {
|
||||
if *c == '\n' {
|
||||
end = i;
|
||||
next = i + 1;
|
||||
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;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
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());
|
||||
}
|
||||
}
|
||||
if lines.is_empty() {
|
||||
lines.push(Text::empty());
|
||||
}
|
||||
lines
|
||||
}
|
||||
/// Characters of `s` that fit in `width` (Font.plainSubstrByWidth).
|
||||
pub fn fit(&self, s: &str, width: f32) -> usize {
|
||||
let mut w = 0.0;
|
||||
for (i, c) in s.chars().enumerate() {
|
||||
w += self.glyph(c).advance;
|
||||
if w > width {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
s.chars().count()
|
||||
}
|
||||
/// Characters of `s` that fit in `width`, measured from the end.
|
||||
pub fn fit_reverse(&self, s: &str, width: f32) -> usize {
|
||||
let mut w = 0.0;
|
||||
for (i, c) in s.chars().rev().enumerate() {
|
||||
w += self.glyph(c).advance;
|
||||
if w > width {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
s.chars().count()
|
||||
}
|
||||
pub fn white(&self) -> Rect {
|
||||
self.white
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn unihex_rows_and_widths() {
|
||||
let mut out = HashMap::new();
|
||||
// 'A' from unifont (8 wide) and a 16-wide glyph with an empty left column.
|
||||
let wide = format!("4E00:{}7FFE{}\n", "0000".repeat(4), "0000".repeat(11));
|
||||
parse_hex(b"0041:0000000018242442427E424242420000\n", &mut out);
|
||||
parse_hex(wide.as_bytes(), &mut out);
|
||||
let a = out[&0x41];
|
||||
assert_eq!((a.left, a.right), (1, 6));
|
||||
assert_eq!(a.rows[4], 0x18 << 24);
|
||||
let yi = out[&0x4E00];
|
||||
assert_eq!((yi.left, yi.right), (1, 14));
|
||||
// Unparseable lines are skipped.
|
||||
parse_hex(b"zz:00\n", &mut out);
|
||||
assert_eq!(out.len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
//! Game rules (26.3 `GameRules`): the registered rules with their category,
|
||||
//! type, default and bounds, a value map, and persistence in the world's
|
||||
//! `data/minecraft/game_rules.dat` saved-data file.
|
||||
use horizon_world::{
|
||||
DATA_VERSION,
|
||||
compression::Compression,
|
||||
nbt::{self, Limits, NamedTag, Tag},
|
||||
};
|
||||
use std::{collections::BTreeMap, fs, path::Path};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Value {
|
||||
Bool(bool),
|
||||
Int(i32),
|
||||
}
|
||||
impl std::fmt::Display for Value {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Value::Bool(b) => write!(f, "{b}"),
|
||||
Value::Int(i) => write!(f, "{i}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub struct Rule {
|
||||
pub name: &'static str,
|
||||
pub category: &'static str,
|
||||
pub default: Value,
|
||||
pub min: i32,
|
||||
pub max: i32,
|
||||
}
|
||||
const fn b(name: &'static str, category: &'static str, default: bool) -> Rule {
|
||||
Rule { name, category, default: Value::Bool(default), min: 0, max: 0 }
|
||||
}
|
||||
const fn i(name: &'static str, category: &'static str, default: i32, min: i32, max: i32) -> Rule {
|
||||
Rule { name, category, default: Value::Int(default), min, max }
|
||||
}
|
||||
/// Every rule available without experimental features, in registration order.
|
||||
pub const RULES: &[Rule] = &[
|
||||
b("advance_time", "updates", true),
|
||||
b("advance_weather", "updates", true),
|
||||
b("allow_entering_nether_using_portals", "misc", true),
|
||||
b("block_drops", "drops", true),
|
||||
b("block_explosion_drop_decay", "drops", true),
|
||||
b("command_blocks_work", "misc", true),
|
||||
b("command_block_output", "chat", true),
|
||||
b("drowning_damage", "player", true),
|
||||
b("elytra_movement_check", "player", true),
|
||||
b("ender_pearls_vanish_on_death", "player", true),
|
||||
b("entity_drops", "drops", true),
|
||||
b("fall_damage", "player", true),
|
||||
b("fire_damage", "player", true),
|
||||
i("fire_spread_radius_around_player", "updates", 128, -1, i32::MAX),
|
||||
b("forgive_dead_players", "mobs", true),
|
||||
b("freeze_damage", "player", true),
|
||||
b("global_sound_events", "misc", true),
|
||||
b("immediate_respawn", "player", false),
|
||||
b("keep_inventory", "player", false),
|
||||
b("lava_source_conversion", "updates", false),
|
||||
b("limited_crafting", "player", false),
|
||||
b("locator_bar", "player", true),
|
||||
b("log_admin_commands", "chat", true),
|
||||
i("max_block_modifications", "misc", 32768, 1, i32::MAX),
|
||||
i("max_command_forks", "misc", 65536, 0, i32::MAX),
|
||||
i("max_command_sequence_length", "misc", 65536, 0, i32::MAX),
|
||||
i("max_entity_cramming", "mobs", 24, 0, i32::MAX),
|
||||
i("max_snow_accumulation_height", "updates", 1, 0, 8),
|
||||
b("mob_drops", "drops", true),
|
||||
b("mob_explosion_drop_decay", "drops", true),
|
||||
b("mob_griefing", "mobs", true),
|
||||
b("natural_health_regeneration", "player", true),
|
||||
b("player_movement_check", "player", true),
|
||||
i("players_nether_portal_creative_delay", "player", 0, 0, i32::MAX),
|
||||
i("players_nether_portal_default_delay", "player", 80, 0, i32::MAX),
|
||||
i("players_sleeping_percentage", "player", 100, 0, i32::MAX),
|
||||
b("projectiles_can_break_blocks", "drops", true),
|
||||
b("pvp", "player", true),
|
||||
b("raids", "mobs", true),
|
||||
i("random_tick_speed", "updates", 3, 0, i32::MAX),
|
||||
b("reduced_debug_info", "misc", false),
|
||||
i("respawn_radius", "player", 10, 0, i32::MAX),
|
||||
b("send_command_feedback", "chat", true),
|
||||
b("show_advancement_messages", "chat", true),
|
||||
b("show_death_messages", "chat", true),
|
||||
b("spawner_blocks_work", "misc", true),
|
||||
b("spawn_mobs", "spawning", true),
|
||||
b("spawn_monsters", "spawning", true),
|
||||
b("spawn_patrols", "spawning", true),
|
||||
b("spawn_phantoms", "spawning", true),
|
||||
b("spawn_wandering_traders", "spawning", true),
|
||||
b("spawn_wardens", "spawning", true),
|
||||
b("spectators_generate_chunks", "player", true),
|
||||
b("spread_vines", "updates", true),
|
||||
b("tnt_explodes", "misc", true),
|
||||
b("tnt_explosion_drop_decay", "drops", false),
|
||||
b("universal_anger", "mobs", false),
|
||||
b("water_source_conversion", "updates", true),
|
||||
];
|
||||
pub fn rule(name: &str) -> Option<&'static Rule> {
|
||||
let name = name.strip_prefix("minecraft:").unwrap_or(name);
|
||||
RULES.iter().find(|r| r.name == name)
|
||||
}
|
||||
|
||||
/// Current values (defaults unless set).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct GameRules {
|
||||
values: BTreeMap<&'static str, Value>,
|
||||
}
|
||||
impl GameRules {
|
||||
pub fn get(&self, name: &str) -> Option<Value> {
|
||||
let r = rule(name)?;
|
||||
Some(self.values.get(r.name).copied().unwrap_or(r.default))
|
||||
}
|
||||
pub fn bool(&self, name: &str) -> bool {
|
||||
matches!(self.get(name), Some(Value::Bool(true)))
|
||||
}
|
||||
pub fn int(&self, name: &str) -> i32 {
|
||||
match self.get(name) {
|
||||
Some(Value::Int(v)) => v,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
/// Set a rule; false if the name or value type is wrong.
|
||||
pub fn set(&mut self, name: &str, value: Value) -> bool {
|
||||
let Some(r) = rule(name) else { return false };
|
||||
let ok = match (r.default, value) {
|
||||
(Value::Bool(_), Value::Bool(_)) => true,
|
||||
(Value::Int(_), Value::Int(v)) => (r.min..=r.max).contains(&v),
|
||||
_ => false,
|
||||
};
|
||||
if ok && value == r.default {
|
||||
self.values.remove(r.name);
|
||||
} else if ok {
|
||||
self.values.insert(r.name, value);
|
||||
}
|
||||
ok
|
||||
}
|
||||
/// GameRuleMap codec: `{data: {"minecraft:<rule>": value...}, DataVersion}`.
|
||||
pub fn to_nbt(&self) -> NamedTag {
|
||||
let data: Vec<(horizon_world::nbt::JavaString, Tag)> = RULES
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let v = self.values.get(r.name).copied().unwrap_or(r.default);
|
||||
let tag = match v {
|
||||
Value::Bool(b) => Tag::Byte(i8::from(b)),
|
||||
Value::Int(i) => Tag::Int(i),
|
||||
};
|
||||
(horizon_world::nbt::JavaString::from(format!("minecraft:{}", r.name).as_str()), tag)
|
||||
})
|
||||
.collect();
|
||||
NamedTag { name: "".into(), tag: Tag::compound([("data", Tag::compound(data)), ("DataVersion", Tag::Int(DATA_VERSION))]) }
|
||||
}
|
||||
pub fn from_nbt(root: &Tag) -> Self {
|
||||
let mut rules = Self::default();
|
||||
let Some(data) = root.get("data") else { return rules };
|
||||
for r in RULES {
|
||||
let key = format!("minecraft:{}", r.name);
|
||||
let value = data.get(&key).or_else(|| data.get(r.name));
|
||||
match (r.default, value) {
|
||||
(Value::Bool(_), Some(Tag::Byte(v))) => {
|
||||
rules.set(r.name, Value::Bool(*v != 0));
|
||||
}
|
||||
(Value::Int(_), Some(Tag::Int(v))) => {
|
||||
rules.set(r.name, Value::Int(*v));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
rules
|
||||
}
|
||||
pub fn load(world: &Path) -> Self {
|
||||
let Ok(bytes) = fs::read(world.join("data/minecraft/game_rules.dat")) else { return Self::default() };
|
||||
let Ok(raw) = Compression::Gzip.decode(&bytes, 16 << 20) else { return Self::default() };
|
||||
match nbt::read_named(&raw, Limits::default()) {
|
||||
Ok((root, _)) => Self::from_nbt(&root.tag),
|
||||
Err(_) => Self::default(),
|
||||
}
|
||||
}
|
||||
pub fn save(&self, world: &Path) -> crate::Result<()> {
|
||||
let dir = world.join("data/minecraft");
|
||||
fs::create_dir_all(&dir)?;
|
||||
let bytes = nbt::write_named(&self.to_nbt(), Limits::default()).map_err(|e| e.to_string())?;
|
||||
fs::write(dir.join("game_rules.dat"), Compression::Gzip.encode(&bytes)?)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn defaults_bounds_and_round_trip() {
|
||||
let mut rules = GameRules::default();
|
||||
assert!(rules.bool("advance_time"));
|
||||
assert_eq!(rules.int("random_tick_speed"), 3);
|
||||
assert!(!rules.set("random_tick_speed", Value::Bool(true)));
|
||||
assert!(!rules.set("max_snow_accumulation_height", Value::Int(9)));
|
||||
assert!(rules.set("keep_inventory", Value::Bool(true)));
|
||||
assert!(rules.set("minecraft:random_tick_speed", Value::Int(10)));
|
||||
let back = GameRules::from_nbt(&rules.to_nbt().tag);
|
||||
assert_eq!(back, rules);
|
||||
assert!(back.bool("keep_inventory"));
|
||||
let dir = std::env::temp_dir().join(format!("horizon-gamerules-{}", std::process::id()));
|
||||
rules.save(&dir).unwrap();
|
||||
assert_eq!(GameRules::load(&dir), rules);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -488,7 +488,8 @@ impl Renderer {
|
||||
atlas_pixels,
|
||||
);
|
||||
let atlas_view = atlas.create_view(&Default::default());
|
||||
let hud = HudRenderer::new(&device, config.format.remove_srgb_suffix(), &atlas_view)?;
|
||||
let mut hud = HudRenderer::new(&device, config.format.remove_srgb_suffix(), &atlas_view)?;
|
||||
hud.atlas_texture = Some(atlas.clone());
|
||||
let entity_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Horizon entities"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("entity.wgsl").into()),
|
||||
|
||||
@@ -18,19 +18,17 @@ pub struct Rect {
|
||||
pub w: u32,
|
||||
pub h: u32,
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
struct Glyph {
|
||||
rect: Rect,
|
||||
advance: f32,
|
||||
}
|
||||
pub struct HudAtlas {
|
||||
pub pixels: Vec<u8>,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub sprites: HashMap<String, Rect>,
|
||||
glyphs: HashMap<char, Glyph>,
|
||||
/// The default font (bitmap sheets in this atlas, unifont rasterized on demand).
|
||||
pub font: crate::font::Font,
|
||||
white: Rect,
|
||||
}
|
||||
/// Atlas rows reserved for glyphs rasterized at run time.
|
||||
pub const GLYPH_ROWS: u32 = 512;
|
||||
pub fn decode(path: &Path) -> Result<(u32, u32, Vec<u8>)> {
|
||||
let mut decoder = png::Decoder::new(std::io::BufReader::new(fs::File::open(path)?));
|
||||
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
|
||||
@@ -129,7 +127,8 @@ impl HudAtlas {
|
||||
x += w + 1;
|
||||
row = row.max(*h);
|
||||
}
|
||||
let height = (y + row + 1).next_power_of_two();
|
||||
let glyph_region = y + row + 1;
|
||||
let height = (glyph_region + GLYPH_ROWS).next_power_of_two();
|
||||
let mut pixels = vec![0u8; (width * height * 4) as usize];
|
||||
let mut sprites = HashMap::new();
|
||||
for ((name, w, h, data), (px, py)) in images.iter().zip(placements) {
|
||||
@@ -151,91 +150,15 @@ impl HudAtlas {
|
||||
);
|
||||
}
|
||||
let white = sprites["horizon/white"];
|
||||
let mut atlas = Self {
|
||||
let font = crate::font::Font::load(root, &sprites, &pixels, (width, height), (glyph_region, height - glyph_region), white);
|
||||
Ok(Self {
|
||||
pixels,
|
||||
width,
|
||||
height,
|
||||
sprites,
|
||||
glyphs: HashMap::new(),
|
||||
font,
|
||||
white,
|
||||
};
|
||||
atlas.load_font(root)?;
|
||||
Ok(atlas)
|
||||
}
|
||||
fn load_font(&mut self, root: &Path) -> Result<()> {
|
||||
let text = fs::read_to_string(root.join("assets/minecraft/font/include/default.json"))?;
|
||||
let value: serde_json::Value = serde_json::from_str(&text)?;
|
||||
for provider in value["providers"].as_array().into_iter().flatten() {
|
||||
if provider["type"] != "bitmap" {
|
||||
continue;
|
||||
}
|
||||
let file = provider["file"].as_str().unwrap_or("");
|
||||
let name = file
|
||||
.trim_start_matches("minecraft:")
|
||||
.trim_end_matches(".png")
|
||||
.to_owned();
|
||||
let Some(rect) = self.sprites.get(&name).copied() else {
|
||||
continue;
|
||||
};
|
||||
let rows: Vec<Vec<char>> = provider["chars"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|r| r.as_str().map(|s| s.chars().collect()))
|
||||
.collect();
|
||||
if rows.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let columns = rows[0].len() as u32;
|
||||
let cell_w = rect.w / columns;
|
||||
let cell_h = rect.h / rows.len() as u32;
|
||||
let height = provider["height"].as_f64().unwrap_or(8.0) as f32;
|
||||
let scale = height / cell_h as f32;
|
||||
let (ax, ay) = (
|
||||
(rect.u0 * self.width as f32) as u32,
|
||||
(rect.v0 * self.height as f32) as u32,
|
||||
);
|
||||
for (r, row) in rows.iter().enumerate() {
|
||||
for (c, ch) in row.iter().enumerate() {
|
||||
if *ch == '\0' || self.glyphs.contains_key(ch) {
|
||||
continue;
|
||||
}
|
||||
let (cx, cy) = (ax + c as u32 * cell_w, ay + r as u32 * cell_h);
|
||||
// Glyph width: rightmost column containing an opaque pixel.
|
||||
let mut used = 0;
|
||||
for x in (0..cell_w).rev() {
|
||||
if (0..cell_h).any(|y| {
|
||||
self.pixels[(((cy + y) * self.width + cx + x) * 4 + 3) as usize] != 0
|
||||
}) {
|
||||
used = x + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.glyphs.insert(
|
||||
*ch,
|
||||
Glyph {
|
||||
rect: Rect {
|
||||
u0: cx as f32 / self.width as f32,
|
||||
v0: cy as f32 / self.height as f32,
|
||||
u1: (cx + cell_w) as f32 / self.width as f32,
|
||||
v1: (cy + cell_h) as f32 / self.height as f32,
|
||||
w: cell_w,
|
||||
h: cell_h,
|
||||
},
|
||||
advance: (used as f32 * scale + 0.5).floor() + 1.0,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.glyphs.insert(
|
||||
' ',
|
||||
Glyph {
|
||||
rect: self.white,
|
||||
advance: 4.0,
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
#[repr(C)]
|
||||
@@ -253,6 +176,8 @@ pub struct HudBatch {
|
||||
pub scale: f32,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
/// Glyph pixels to upload into the atlas before drawing.
|
||||
pub patches: Vec<crate::font::Patch>,
|
||||
}
|
||||
pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> u32 {
|
||||
u32::from(a) << 24 | u32::from(b) << 16 | u32::from(g) << 8 | u32::from(r)
|
||||
@@ -271,6 +196,7 @@ impl HudBatch {
|
||||
scale: scale as f32,
|
||||
width: (window[0] as f32 / scale as f32).ceil(),
|
||||
height: (window[1] as f32 / scale as f32).ceil(),
|
||||
patches: Vec::new(),
|
||||
}
|
||||
}
|
||||
pub fn quad(&mut self, p: [[f32; 2]; 4], uv: [[f32; 2]; 4], color: u32) {
|
||||
@@ -317,26 +243,77 @@ impl HudBatch {
|
||||
self.rect_uv(x, y, w, h, r, color);
|
||||
}
|
||||
pub fn text_width(atlas: &HudAtlas, text: &str) -> f32 {
|
||||
text.chars()
|
||||
.map(|c| atlas.glyphs.get(&c).map_or(6.0, |g| g.advance))
|
||||
.sum()
|
||||
atlas.font.width(text)
|
||||
}
|
||||
/// Draw plain text (legacy `§` codes are honoured); returns the advance.
|
||||
pub fn text(&mut self, atlas: &HudAtlas, text: &str, x: f32, y: f32, color: u32, shadow: bool) -> f32 {
|
||||
if shadow {
|
||||
let c = color.to_le_bytes();
|
||||
let dark = rgba(c[0] / 4, c[1] / 4, c[2] / 4, c[3]);
|
||||
self.text(atlas, text, x + 1.0, y + 1.0, dark, false);
|
||||
}
|
||||
let t = if text.contains('§') { crate::text::Text::legacy(text) } else { crate::text::Text::literal(text) };
|
||||
self.text_styled(atlas, &t, x, y, color, shadow)
|
||||
}
|
||||
/// Font.drawInternal: styled glyphs, shadows first, with bold, italic,
|
||||
/// underline and strikethrough. `color` is the default colour and alpha.
|
||||
pub fn text_styled(&mut self, atlas: &HudAtlas, text: &crate::text::Text, x: f32, y: f32, color: u32, shadow: bool) -> f32 {
|
||||
let font = &atlas.font;
|
||||
let alpha = (color >> 24) as u8;
|
||||
let mut glyphs = Vec::new();
|
||||
let mut cursor = x;
|
||||
for ch in text.chars() {
|
||||
let Some(g) = atlas.glyphs.get(&ch).copied() else {
|
||||
cursor += 6.0;
|
||||
continue;
|
||||
};
|
||||
if ch != ' ' {
|
||||
self.rect_uv(cursor, y, 8.0, 8.0, g.rect, color);
|
||||
for (i, (ch, style)) in text.chars().enumerate() {
|
||||
let g = font.glyph(ch);
|
||||
let c = style.color.map_or(color, |rgb| rgba((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8, alpha));
|
||||
let bold = style.is_bold();
|
||||
let advance = g.advance + if bold { g.offset } else { 0.0 };
|
||||
glyphs.push((cursor, g, c, bold, style.is_italic(), style.underlined == Some(true), style.strikethrough == Some(true), i == 0, advance));
|
||||
cursor += advance;
|
||||
}
|
||||
self.patches.extend(font.take_patches());
|
||||
let white = font.white();
|
||||
let passes: &[bool] = if shadow { &[true, false] } else { &[false] };
|
||||
for &is_shadow in passes {
|
||||
for &(gx, g, c, bold, italic, underline, strike, first, advance) in &glyphs {
|
||||
let (dx, col) = if is_shadow {
|
||||
let b = c.to_le_bytes();
|
||||
(g.offset, rgba((f32::from(b[0]) * 0.25) as u8, (f32::from(b[1]) * 0.25) as u8, (f32::from(b[2]) * 0.25) as u8, b[3]))
|
||||
} else {
|
||||
(0.0, c)
|
||||
};
|
||||
let (px, py) = (gx + dx, y + dx);
|
||||
let shear = |v: f32| if italic { 1.0 - 0.25 * v } else { 0.0 };
|
||||
let thick = if bold { 0.1 } else { 0.0 };
|
||||
let draw = |batch: &mut Self, ox: f32| match g.rect {
|
||||
Some(r) => {
|
||||
let (x0, x1, y0, y1) = (px + ox + g.left, px + ox + g.right, py + g.top, py + g.bottom);
|
||||
batch.quad(
|
||||
[
|
||||
[x0 + shear(g.top) - thick, y0 - thick],
|
||||
[x1 + shear(g.top) + thick, y0 - thick],
|
||||
[x1 + shear(g.bottom) + thick, y1 + thick],
|
||||
[x0 + shear(g.bottom) - thick, y1 + thick],
|
||||
],
|
||||
[[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]],
|
||||
col,
|
||||
);
|
||||
}
|
||||
None if g.right > 0.0 => {
|
||||
// SpecialGlyphs.MISSING: a 5x8 outline.
|
||||
let (bx, by) = (px + ox, py);
|
||||
for (fx, fy, fw, fh) in [(0.0, 0.0, 5.0, 1.0), (0.0, 7.0, 5.0, 1.0), (0.0, 1.0, 1.0, 6.0), (4.0, 1.0, 1.0, 6.0)] {
|
||||
batch.rect_uv(bx + fx, by + fy, fw, fh, white, col);
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
};
|
||||
draw(self, 0.0);
|
||||
if bold {
|
||||
draw(self, g.offset);
|
||||
}
|
||||
let x0 = if first { px - 1.0 } else { px };
|
||||
if strike {
|
||||
self.rect_uv(x0, py + 3.5, px + advance - x0, 1.0, white, col);
|
||||
}
|
||||
if underline {
|
||||
self.rect_uv(x0, py + 8.0, px + advance - x0, 1.0, white, col);
|
||||
}
|
||||
}
|
||||
cursor += g.advance;
|
||||
}
|
||||
cursor - x
|
||||
}
|
||||
@@ -347,6 +324,8 @@ struct HudUniform {
|
||||
size: [f32; 4],
|
||||
}
|
||||
pub struct HudRenderer {
|
||||
/// The shared atlas texture, for run-time glyph uploads.
|
||||
pub atlas_texture: Option<wgpu::Texture>,
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
group: wgpu::BindGroup,
|
||||
uniform: wgpu::Buffer,
|
||||
@@ -465,6 +444,7 @@ impl HudRenderer {
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
Ok(Self {
|
||||
atlas_texture: None,
|
||||
pipeline,
|
||||
group,
|
||||
uniform,
|
||||
@@ -481,6 +461,16 @@ impl HudRenderer {
|
||||
batch: &HudBatch,
|
||||
size: [u32; 2],
|
||||
) {
|
||||
if let Some(texture) = &self.atlas_texture {
|
||||
for p in &batch.patches {
|
||||
queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d { x: p.x, y: p.y, z: 0 }, aspect: wgpu::TextureAspect::All },
|
||||
&p.rgba,
|
||||
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(p.width * 4), rows_per_image: None },
|
||||
wgpu::Extent3d { width: p.width, height: p.height, depth_or_array_layers: 1 },
|
||||
);
|
||||
}
|
||||
}
|
||||
if batch.vertices.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
//! Languages (ClientLanguage / LanguageManager): `lang/<code>.json` from the
|
||||
//! resource root and enabled packs layered over `en_us`, the language list
|
||||
//! from `pack.mcmeta` `language` sections, and a process-wide current
|
||||
//! language used by every screen.
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
path::Path,
|
||||
sync::{Arc, RwLock},
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LanguageInfo {
|
||||
pub code: String,
|
||||
pub name: String,
|
||||
pub region: String,
|
||||
pub bidirectional: bool,
|
||||
}
|
||||
impl LanguageInfo {
|
||||
/// LanguageInfo.toComponent: "Name (Region)".
|
||||
pub fn label(&self) -> String {
|
||||
format!("{} ({})", self.name, self.region)
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct Language {
|
||||
pub code: String,
|
||||
map: HashMap<String, String>,
|
||||
}
|
||||
pub const DEFAULT: &str = "en_us";
|
||||
|
||||
static CURRENT: RwLock<Option<Arc<Language>>> = RwLock::new(None);
|
||||
|
||||
/// A source of resource files: the prepared root plus packs, highest priority last.
|
||||
pub trait ResourceSource {
|
||||
fn read(&self, path: &str) -> Option<Vec<u8>>;
|
||||
}
|
||||
impl ResourceSource for Path {
|
||||
fn read(&self, path: &str) -> Option<Vec<u8>> {
|
||||
std::fs::read(self.join(path)).ok()
|
||||
}
|
||||
}
|
||||
|
||||
impl Language {
|
||||
pub fn from_map(code: &str, map: HashMap<String, String>) -> Self {
|
||||
Self { code: code.to_owned(), map }
|
||||
}
|
||||
/// ClientLanguage.loadFrom: en_us first, then the selected language, each
|
||||
/// from every source in priority order (later sources override).
|
||||
pub fn load(sources: &[&dyn ResourceSource], code: &str) -> Self {
|
||||
let mut map = HashMap::new();
|
||||
let mut codes = vec![DEFAULT];
|
||||
if code != DEFAULT {
|
||||
codes.push(code);
|
||||
}
|
||||
for c in codes {
|
||||
for source in sources {
|
||||
let Some(bytes) = source.read(&format!("assets/minecraft/lang/{c}.json")) else { continue };
|
||||
if let Ok(entries) = serde_json::from_slice::<HashMap<String, String>>(&bytes) {
|
||||
map.extend(entries);
|
||||
}
|
||||
}
|
||||
}
|
||||
Self { code: code.to_owned(), map }
|
||||
}
|
||||
pub fn get(&self, key: &str) -> Option<&str> {
|
||||
self.map.get(key).map(String::as_str)
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.map.len()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.map.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Languages declared by `pack.mcmeta` files (the vanilla asset root first).
|
||||
pub fn available(sources: &[&dyn ResourceSource]) -> Vec<LanguageInfo> {
|
||||
let mut found: BTreeMap<String, LanguageInfo> = BTreeMap::new();
|
||||
found.insert(
|
||||
DEFAULT.into(),
|
||||
LanguageInfo { code: DEFAULT.into(), name: "English".into(), region: "US".into(), bidirectional: false },
|
||||
);
|
||||
for source in sources {
|
||||
for path in ["assets/pack.mcmeta", "pack.mcmeta"] {
|
||||
let Some(bytes) = source.read(path) else { continue };
|
||||
let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes) else { continue };
|
||||
for (code, info) in value["language"].as_object().into_iter().flatten() {
|
||||
// Only languages whose file exists somewhere are selectable.
|
||||
let file = format!("assets/minecraft/lang/{code}.json");
|
||||
if code != DEFAULT && !sources.iter().any(|s| s.read(&file).is_some()) {
|
||||
continue;
|
||||
}
|
||||
found.insert(
|
||||
code.clone(),
|
||||
LanguageInfo {
|
||||
code: code.clone(),
|
||||
name: info["name"].as_str().unwrap_or(code).to_owned(),
|
||||
region: info["region"].as_str().unwrap_or("").to_owned(),
|
||||
bidirectional: info["bidirectional"].as_bool().unwrap_or(false),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
found.into_values().collect()
|
||||
}
|
||||
|
||||
pub fn set(language: Language) {
|
||||
*CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(language));
|
||||
}
|
||||
pub fn current() -> Option<Arc<Language>> {
|
||||
CURRENT.read().unwrap_or_else(|e| e.into_inner()).clone()
|
||||
}
|
||||
pub fn code() -> String {
|
||||
current().map_or_else(|| DEFAULT.to_owned(), |l| l.code.clone())
|
||||
}
|
||||
/// Language.getOrDefault: the translation, or the key itself.
|
||||
pub fn get(key: &str) -> String {
|
||||
current().and_then(|l| l.get(key).map(str::to_owned)).unwrap_or_else(|| key.to_owned())
|
||||
}
|
||||
/// The translation, or `fallback` when the key is missing.
|
||||
pub fn get_or(key: &str, fallback: &str) -> String {
|
||||
current().and_then(|l| l.get(key).map(str::to_owned)).unwrap_or_else(|| fallback.to_owned())
|
||||
}
|
||||
pub fn has(key: &str) -> bool {
|
||||
current().is_some_and(|l| l.get(key).is_some())
|
||||
}
|
||||
/// I18n.get with plain string arguments.
|
||||
pub fn tr(key: &str, args: &[&dyn std::fmt::Display]) -> String {
|
||||
crate::text::Text::tr(key, args).plain()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
struct Mem(HashMap<String, Vec<u8>>);
|
||||
impl ResourceSource for Mem {
|
||||
fn read(&self, path: &str) -> Option<Vec<u8>> {
|
||||
self.0.get(path).cloned()
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn layers_selected_language_over_english() {
|
||||
let base = Mem(HashMap::from([
|
||||
("assets/minecraft/lang/en_us.json".into(), br#"{"a":"Apple","b":"Banana"}"#.to_vec()),
|
||||
("assets/minecraft/lang/fr_fr.json".into(), br#"{"a":"Pomme"}"#.to_vec()),
|
||||
("assets/pack.mcmeta".into(), r#"{"language":{"fr_fr":{"name":"Français","region":"France"},"de_de":{"name":"Deutsch","region":"Deutschland"}}}"#.as_bytes().to_vec()),
|
||||
]));
|
||||
let pack = Mem(HashMap::from([("assets/minecraft/lang/fr_fr.json".into(), br#"{"b":"Banane"}"#.to_vec())]));
|
||||
let sources: [&dyn ResourceSource; 2] = [&base, &pack];
|
||||
let fr = Language::load(&sources, "fr_fr");
|
||||
assert_eq!(fr.get("a"), Some("Pomme"));
|
||||
assert_eq!(fr.get("b"), Some("Banane"));
|
||||
let langs = available(&sources);
|
||||
// de_de has no file, so only English and French are offered.
|
||||
assert_eq!(langs.iter().map(|l| l.code.as_str()).collect::<Vec<_>>(), ["en_us", "fr_fr"]);
|
||||
assert_eq!(langs[1].label(), "Français (France)");
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ pub mod biome;
|
||||
pub mod blocks;
|
||||
pub mod chunk;
|
||||
pub mod clock;
|
||||
pub mod command;
|
||||
pub mod containers;
|
||||
pub mod control;
|
||||
pub mod crafting;
|
||||
@@ -15,12 +16,15 @@ pub mod creative;
|
||||
pub mod collisions;
|
||||
pub mod entities;
|
||||
pub mod environment;
|
||||
pub mod font;
|
||||
pub mod gamerules;
|
||||
pub mod gfx;
|
||||
pub mod health;
|
||||
pub mod hud;
|
||||
pub mod hunger;
|
||||
pub mod input;
|
||||
pub mod items;
|
||||
pub mod lang;
|
||||
pub mod landing;
|
||||
pub mod light;
|
||||
pub mod mesher;
|
||||
@@ -35,7 +39,9 @@ pub mod sprint;
|
||||
pub mod sprites;
|
||||
pub mod streaming;
|
||||
pub mod testgen;
|
||||
pub mod text;
|
||||
pub mod title;
|
||||
pub mod vanillagen;
|
||||
pub mod world;
|
||||
pub mod zip;
|
||||
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
//! Styled text (a flattened `Component`): spans with ChatFormatting colours
|
||||
//! and decorations, translatable messages formatted like
|
||||
//! `TranslatableContents` (`%s`, `%1$s`, `%%`), and legacy `§` codes.
|
||||
use crate::lang;
|
||||
|
||||
/// ChatFormatting colours by legacy code index 0..=15.
|
||||
pub const COLORS: [(char, &str, u32); 16] = [
|
||||
('0', "black", 0x000000),
|
||||
('1', "dark_blue", 0x0000AA),
|
||||
('2', "dark_green", 0x00AA00),
|
||||
('3', "dark_aqua", 0x00AAAA),
|
||||
('4', "dark_red", 0xAA0000),
|
||||
('5', "dark_purple", 0xAA00AA),
|
||||
('6', "gold", 0xFFAA00),
|
||||
('7', "gray", 0xAAAAAA),
|
||||
('8', "dark_gray", 0x555555),
|
||||
('9', "blue", 0x5555FF),
|
||||
('a', "green", 0x55FF55),
|
||||
('b', "aqua", 0x55FFFF),
|
||||
('c', "red", 0xFF5555),
|
||||
('d', "light_purple", 0xFF55FF),
|
||||
('e', "yellow", 0xFFFF55),
|
||||
('f', "white", 0xFFFFFF),
|
||||
];
|
||||
pub const BLACK: u32 = 0x000000;
|
||||
pub const GRAY: u32 = 0xAAAAAA;
|
||||
pub const DARK_GRAY: u32 = 0x555555;
|
||||
pub const GREEN: u32 = 0x55FF55;
|
||||
pub const AQUA: u32 = 0x55FFFF;
|
||||
pub const RED: u32 = 0xFF5555;
|
||||
pub const YELLOW: u32 = 0xFFFF55;
|
||||
pub const GOLD: u32 = 0xFFAA00;
|
||||
pub const WHITE: u32 = 0xFFFFFF;
|
||||
pub const LIGHT_PURPLE: u32 = 0xFF55FF;
|
||||
|
||||
pub fn named_color(name: &str) -> Option<u32> {
|
||||
COLORS.iter().find(|c| c.1 == name).map(|c| c.2)
|
||||
}
|
||||
|
||||
/// Text style; `None` fields inherit from the enclosing style.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Style {
|
||||
pub color: Option<u32>,
|
||||
pub bold: Option<bool>,
|
||||
pub italic: Option<bool>,
|
||||
pub underlined: Option<bool>,
|
||||
pub strikethrough: Option<bool>,
|
||||
pub obfuscated: Option<bool>,
|
||||
/// ClickEvent.SuggestCommand: clicking puts this into the chat box.
|
||||
pub suggest: Option<String>,
|
||||
/// Hover text.
|
||||
pub hover: Option<Box<Text>>,
|
||||
}
|
||||
impl Style {
|
||||
pub fn color(c: u32) -> Self {
|
||||
Self { color: Some(c), ..Self::default() }
|
||||
}
|
||||
/// Fill unset fields from `base` (Style.applyTo).
|
||||
pub fn inherit(&mut self, base: &Style) {
|
||||
self.color = self.color.or(base.color);
|
||||
self.bold = self.bold.or(base.bold);
|
||||
self.italic = self.italic.or(base.italic);
|
||||
self.underlined = self.underlined.or(base.underlined);
|
||||
self.strikethrough = self.strikethrough.or(base.strikethrough);
|
||||
self.obfuscated = self.obfuscated.or(base.obfuscated);
|
||||
if self.suggest.is_none() {
|
||||
self.suggest.clone_from(&base.suggest);
|
||||
}
|
||||
if self.hover.is_none() {
|
||||
self.hover.clone_from(&base.hover);
|
||||
}
|
||||
}
|
||||
pub fn is_bold(&self) -> bool {
|
||||
self.bold == Some(true)
|
||||
}
|
||||
pub fn is_italic(&self) -> bool {
|
||||
self.italic == Some(true)
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Span {
|
||||
pub text: String,
|
||||
pub style: Style,
|
||||
}
|
||||
/// A run of styled spans.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Text {
|
||||
pub spans: Vec<Span>,
|
||||
}
|
||||
impl From<&str> for Text {
|
||||
fn from(s: &str) -> Self {
|
||||
Text::literal(s)
|
||||
}
|
||||
}
|
||||
impl From<String> for Text {
|
||||
fn from(s: String) -> Self {
|
||||
Text::literal(s)
|
||||
}
|
||||
}
|
||||
impl Text {
|
||||
pub fn empty() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
pub fn literal(s: impl Into<String>) -> Self {
|
||||
let text = s.into();
|
||||
if text.is_empty() {
|
||||
return Self::default();
|
||||
}
|
||||
Self { spans: vec![Span { text, style: Style::default() }] }
|
||||
}
|
||||
pub fn styled(s: impl Into<String>, style: Style) -> Self {
|
||||
let mut t = Self::literal(s);
|
||||
for span in &mut t.spans {
|
||||
span.style = style.clone();
|
||||
}
|
||||
t
|
||||
}
|
||||
pub fn colored(s: impl Into<String>, color: u32) -> Self {
|
||||
Self::styled(s, Style::color(color))
|
||||
}
|
||||
/// Component.translatable(key, args) in the current language.
|
||||
pub fn translate(key: &str, args: &[Text]) -> Self {
|
||||
format_translation(&lang::get(key), args)
|
||||
}
|
||||
/// A translatable message whose arguments are plain strings.
|
||||
pub fn tr(key: &str, args: &[&dyn std::fmt::Display]) -> Self {
|
||||
let args: Vec<Text> = args.iter().map(|a| Text::literal(a.to_string())).collect();
|
||||
Self::translate(key, &args)
|
||||
}
|
||||
pub fn append(mut self, other: impl Into<Text>) -> Self {
|
||||
self.spans.extend(other.into().spans);
|
||||
self
|
||||
}
|
||||
pub fn push(&mut self, other: impl Into<Text>) {
|
||||
self.spans.extend(other.into().spans);
|
||||
}
|
||||
/// Apply `style` underneath every span (MutableComponent.withStyle on a parent).
|
||||
pub fn with_style(mut self, style: &Style) -> Self {
|
||||
for span in &mut self.spans {
|
||||
span.style.inherit(style);
|
||||
}
|
||||
self
|
||||
}
|
||||
pub fn with_color(self, color: u32) -> Self {
|
||||
self.with_style(&Style::color(color))
|
||||
}
|
||||
pub fn italic(self) -> Self {
|
||||
self.with_style(&Style { italic: Some(true), ..Style::default() })
|
||||
}
|
||||
pub fn underlined(self) -> Self {
|
||||
self.with_style(&Style { underlined: Some(true), ..Style::default() })
|
||||
}
|
||||
pub fn bold(self) -> Self {
|
||||
self.with_style(&Style { bold: Some(true), ..Style::default() })
|
||||
}
|
||||
/// Component.getString: the plain characters.
|
||||
pub fn plain(&self) -> String {
|
||||
self.spans.iter().map(|s| s.text.as_str()).collect()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.spans.iter().all(|s| s.text.is_empty())
|
||||
}
|
||||
/// Parse legacy formatting codes (`§a`, `§l`, `§r`...) as the font does.
|
||||
pub fn legacy(s: &str) -> Self {
|
||||
let mut out = Text::default();
|
||||
let mut style = Style::default();
|
||||
let mut current = String::new();
|
||||
let mut chars = s.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
if c != '§' {
|
||||
current.push(c);
|
||||
continue;
|
||||
}
|
||||
let Some(code) = chars.next() else { break };
|
||||
if !current.is_empty() {
|
||||
out.spans.push(Span { text: std::mem::take(&mut current), style: style.clone() });
|
||||
}
|
||||
let code = code.to_ascii_lowercase();
|
||||
if let Some(c) = COLORS.iter().find(|c| c.0 == code) {
|
||||
// Colour codes reset decorations (Style.applyLegacyFormat).
|
||||
style = Style::color(c.2);
|
||||
} else {
|
||||
match code {
|
||||
'k' => style.obfuscated = Some(true),
|
||||
'l' => style.bold = Some(true),
|
||||
'm' => style.strikethrough = Some(true),
|
||||
'n' => style.underlined = Some(true),
|
||||
'o' => style.italic = Some(true),
|
||||
'r' => style = Style::default(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !current.is_empty() {
|
||||
out.spans.push(Span { text: current, style });
|
||||
}
|
||||
out
|
||||
}
|
||||
/// Characters with their effective styles.
|
||||
pub fn chars(&self) -> impl Iterator<Item = (char, &Style)> {
|
||||
self.spans.iter().flat_map(|s| s.text.chars().map(move |c| (c, &s.style)))
|
||||
}
|
||||
/// Sub-range of characters [from, to) keeping styles.
|
||||
pub fn slice(&self, from: usize, to: usize) -> Text {
|
||||
let mut out = Text::default();
|
||||
let mut index = 0;
|
||||
for span in &self.spans {
|
||||
let mut part = String::new();
|
||||
for c in span.text.chars() {
|
||||
if index >= from && index < to {
|
||||
part.push(c);
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
if !part.is_empty() {
|
||||
out.spans.push(Span { text: part, style: span.style.clone() });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
pub fn char_count(&self) -> usize {
|
||||
self.spans.iter().map(|s| s.text.chars().count()).sum()
|
||||
}
|
||||
}
|
||||
|
||||
/// TranslatableContents.decomposeTemplate: `%s` takes the next argument,
|
||||
/// `%n$s` a numbered one and `%%` is a percent sign. Malformed templates are
|
||||
/// shown verbatim.
|
||||
pub fn format_translation(template: &str, args: &[Text]) -> Text {
|
||||
let mut out = Text::default();
|
||||
let mut literal = String::new();
|
||||
let mut next = 0usize;
|
||||
let chars: Vec<char> = template.chars().collect();
|
||||
let mut i = 0;
|
||||
while i < chars.len() {
|
||||
if chars[i] != '%' {
|
||||
literal.push(chars[i]);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// %(?:(\d+)\$)?([A-Za-z%]|$)
|
||||
let mut j = i + 1;
|
||||
let mut number = None;
|
||||
let digits_start = j;
|
||||
while j < chars.len() && chars[j].is_ascii_digit() {
|
||||
j += 1;
|
||||
}
|
||||
if j > digits_start && j < chars.len() && chars[j] == '$' {
|
||||
number = chars[digits_start..j].iter().collect::<String>().parse::<usize>().ok();
|
||||
j += 1;
|
||||
} else {
|
||||
j = digits_start;
|
||||
}
|
||||
let conversion = chars.get(j).copied();
|
||||
match conversion {
|
||||
Some('%') if number.is_none() => {
|
||||
literal.push('%');
|
||||
i = j + 1;
|
||||
}
|
||||
// Not a format specifier at all: the percent sign is literal.
|
||||
Some(c) if !c.is_ascii_alphabetic() && c != '%' => {
|
||||
literal.push('%');
|
||||
i += 1;
|
||||
}
|
||||
Some('s') => {
|
||||
let index = match number {
|
||||
Some(n) => n.wrapping_sub(1),
|
||||
None => {
|
||||
next += 1;
|
||||
next - 1
|
||||
}
|
||||
};
|
||||
let Some(arg) = args.get(index) else {
|
||||
return Text::literal(template);
|
||||
};
|
||||
if !literal.is_empty() {
|
||||
out.spans.push(Span { text: std::mem::take(&mut literal), style: Style::default() });
|
||||
}
|
||||
out.spans.extend(arg.spans.iter().cloned());
|
||||
i = j + 1;
|
||||
}
|
||||
_ => return Text::literal(template),
|
||||
}
|
||||
}
|
||||
if !literal.is_empty() {
|
||||
out.spans.push(Span { text: literal, style: Style::default() });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn formats_like_translatable_contents() {
|
||||
let a = [Text::literal("Steve"), Text::colored("Zombie", RED)];
|
||||
assert_eq!(format_translation("%s was slain by %s", &a).plain(), "Steve was slain by Zombie");
|
||||
assert_eq!(format_translation("%2$s then %1$s", &a).plain(), "Zombie then Steve");
|
||||
assert_eq!(format_translation("100%% sure %s", &a).plain(), "100% sure Steve");
|
||||
// Missing arguments or unknown conversions show the template.
|
||||
assert_eq!(format_translation("%s %s %s", &a).plain(), "%s %s %s");
|
||||
assert_eq!(format_translation("%d", &a).plain(), "%d");
|
||||
assert_eq!(format_translation("50% off %s", &a).plain(), "50% off Steve");
|
||||
assert_eq!(format_translation("end %", &a).plain(), "end %");
|
||||
let t = format_translation("%s was slain by %s", &a);
|
||||
assert_eq!(t.spans.last().unwrap().style.color, Some(RED));
|
||||
}
|
||||
#[test]
|
||||
fn legacy_codes_and_inheritance() {
|
||||
let t = Text::legacy("§aGreen §lbold§r plain");
|
||||
assert_eq!(t.plain(), "Green bold plain");
|
||||
assert_eq!(t.spans[0].style.color, Some(GREEN));
|
||||
assert!(t.spans[1].style.is_bold());
|
||||
assert_eq!(t.spans[2].style, Style::default());
|
||||
let t = Text::literal("x").append(Text::colored("y", GOLD)).with_color(RED);
|
||||
assert_eq!(t.spans[0].style.color, Some(RED));
|
||||
assert_eq!(t.spans[1].style.color, Some(GOLD));
|
||||
assert_eq!(t.slice(1, 2).plain(), "y");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//! Minimal read-only ZIP archive support (stored and deflated entries), used
|
||||
//! for resource packs and the unifont glyph archive.
|
||||
use std::{collections::BTreeMap, fs, io, path::Path};
|
||||
|
||||
/// One archive held in memory with its central directory indexed by name.
|
||||
pub struct Zip {
|
||||
data: Vec<u8>,
|
||||
entries: BTreeMap<String, Entry>,
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
struct Entry {
|
||||
method: u16,
|
||||
compressed: usize,
|
||||
size: usize,
|
||||
header: usize,
|
||||
}
|
||||
fn invalid(message: &str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, message)
|
||||
}
|
||||
fn u16_at(d: &[u8], at: usize) -> io::Result<u16> {
|
||||
d.get(at..at + 2).map(|b| u16::from_le_bytes([b[0], b[1]])).ok_or_else(|| invalid("truncated zip"))
|
||||
}
|
||||
fn u32_at(d: &[u8], at: usize) -> io::Result<u32> {
|
||||
d.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).ok_or_else(|| invalid("truncated zip"))
|
||||
}
|
||||
impl Zip {
|
||||
pub fn open(path: &Path) -> io::Result<Self> {
|
||||
Self::from_bytes(fs::read(path)?)
|
||||
}
|
||||
pub fn from_bytes(data: Vec<u8>) -> io::Result<Self> {
|
||||
// End of central directory: the last "PK\x05\x06" within 64 KiB of the end.
|
||||
let min = data.len().saturating_sub(22 + 65_535);
|
||||
let eocd = (min..=data.len().saturating_sub(22))
|
||||
.rev()
|
||||
.find(|&i| data[i..i + 4] == [0x50, 0x4b, 0x05, 0x06])
|
||||
.ok_or_else(|| invalid("not a zip archive"))?;
|
||||
let count = usize::from(u16_at(&data, eocd + 10)?);
|
||||
let mut at = u32_at(&data, eocd + 16)? as usize;
|
||||
let mut entries = BTreeMap::new();
|
||||
for _ in 0..count {
|
||||
if u32_at(&data, at)? != 0x0201_4b50 {
|
||||
return Err(invalid("bad central directory entry"));
|
||||
}
|
||||
let method = u16_at(&data, at + 10)?;
|
||||
let compressed = u32_at(&data, at + 20)? as usize;
|
||||
let size = u32_at(&data, at + 24)? as usize;
|
||||
let name_len = usize::from(u16_at(&data, at + 28)?);
|
||||
let extra_len = usize::from(u16_at(&data, at + 30)?);
|
||||
let comment_len = usize::from(u16_at(&data, at + 32)?);
|
||||
let header = u32_at(&data, at + 42)? as usize;
|
||||
let name = data.get(at + 46..at + 46 + name_len).ok_or_else(|| invalid("truncated zip name"))?;
|
||||
let name = String::from_utf8_lossy(name).replace('\\', "/");
|
||||
if !name.ends_with('/') {
|
||||
entries.insert(name, Entry { method, compressed, size, header });
|
||||
}
|
||||
at += 46 + name_len + extra_len + comment_len;
|
||||
}
|
||||
Ok(Self { data, entries })
|
||||
}
|
||||
pub fn names(&self) -> impl Iterator<Item = &str> {
|
||||
self.entries.keys().map(String::as_str)
|
||||
}
|
||||
pub fn contains(&self, name: &str) -> bool {
|
||||
self.entries.contains_key(name)
|
||||
}
|
||||
pub fn read(&self, name: &str) -> io::Result<Vec<u8>> {
|
||||
let e = *self.entries.get(name).ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, name.to_owned()))?;
|
||||
if u32_at(&self.data, e.header)? != 0x0403_4b50 {
|
||||
return Err(invalid("bad local file header"));
|
||||
}
|
||||
let start = e.header + 30 + usize::from(u16_at(&self.data, e.header + 26)?) + usize::from(u16_at(&self.data, e.header + 28)?);
|
||||
let raw = self.data.get(start..start + e.compressed).ok_or_else(|| invalid("truncated zip entry"))?;
|
||||
match e.method {
|
||||
0 => Ok(raw.to_vec()),
|
||||
8 => {
|
||||
let out = miniz_oxide::inflate::decompress_to_vec_with_limit(raw, e.size.max(1) * 2 + 1024)
|
||||
.map_err(|_| invalid("corrupt deflate stream"))?;
|
||||
Ok(out)
|
||||
}
|
||||
_ => Err(invalid("unsupported zip compression")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
/// A hand-built archive with one stored and one deflated entry.
|
||||
fn archive() -> Vec<u8> {
|
||||
let files: [(&str, &[u8], bool); 2] = [("pack.mcmeta", b"{\"pack\":{}}", false), ("a/b.txt", b"hello hello hello hello", true)];
|
||||
let mut out = Vec::new();
|
||||
let mut central = Vec::new();
|
||||
for (name, body, deflate) in files {
|
||||
let data = if deflate { miniz_oxide::deflate::compress_to_vec(body, 6) } else { body.to_vec() };
|
||||
let offset = out.len() as u32;
|
||||
let local = |v: &mut Vec<u8>, sig: u32| {
|
||||
v.extend(sig.to_le_bytes());
|
||||
};
|
||||
local(&mut out, 0x0403_4b50);
|
||||
out.extend([20, 0, 0, 0]);
|
||||
out.extend((if deflate { 8u16 } else { 0 }).to_le_bytes());
|
||||
out.extend([0; 8]);
|
||||
out.extend((data.len() as u32).to_le_bytes());
|
||||
out.extend((body.len() as u32).to_le_bytes());
|
||||
out.extend((name.len() as u16).to_le_bytes());
|
||||
out.extend(0u16.to_le_bytes());
|
||||
out.extend(name.as_bytes());
|
||||
out.extend(&data);
|
||||
local(&mut central, 0x0201_4b50);
|
||||
central.extend([20, 0, 20, 0, 0, 0]);
|
||||
central.extend((if deflate { 8u16 } else { 0 }).to_le_bytes());
|
||||
central.extend([0; 8]);
|
||||
central.extend((data.len() as u32).to_le_bytes());
|
||||
central.extend((body.len() as u32).to_le_bytes());
|
||||
central.extend((name.len() as u16).to_le_bytes());
|
||||
central.extend([0; 12]);
|
||||
central.extend(offset.to_le_bytes());
|
||||
central.extend(name.as_bytes());
|
||||
}
|
||||
let start = out.len() as u32;
|
||||
out.extend(¢ral);
|
||||
out.extend(0x0605_4b50u32.to_le_bytes());
|
||||
out.extend([0; 4]);
|
||||
out.extend(2u16.to_le_bytes());
|
||||
out.extend(2u16.to_le_bytes());
|
||||
out.extend((central.len() as u32).to_le_bytes());
|
||||
out.extend(start.to_le_bytes());
|
||||
out.extend([0; 2]);
|
||||
out
|
||||
}
|
||||
#[test]
|
||||
fn reads_stored_and_deflated_entries() {
|
||||
let zip = Zip::from_bytes(archive()).unwrap();
|
||||
assert_eq!(zip.names().collect::<Vec<_>>(), ["a/b.txt", "pack.mcmeta"]);
|
||||
assert_eq!(zip.read("pack.mcmeta").unwrap(), b"{\"pack\":{}}");
|
||||
assert_eq!(zip.read("a/b.txt").unwrap(), b"hello hello hello hello");
|
||||
assert!(zip.read("missing").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fetch the pinned version's indexed client assets that are not in the game
|
||||
jar: language files and the language list (pack.mcmeta), the unifont glyph
|
||||
archives and their font definitions, and the built-in Programmer Art and High
|
||||
Contrast resource packs. Every object's SHA-1 is verified. Files go to the
|
||||
private client resource directory (or --target) and are never committed."""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
LOCAL = ROOT / '.local'
|
||||
|
||||
|
||||
def fetch(url):
|
||||
with urllib.request.urlopen(url, timeout=120) as response:
|
||||
return response.read()
|
||||
|
||||
|
||||
def wanted(name):
|
||||
return (name == 'pack.mcmeta'
|
||||
or name.startswith('minecraft/lang/')
|
||||
or name.startswith('minecraft/font/')
|
||||
or name.startswith('minecraft/resourcepacks/'))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--target', type=Path, default=LOCAL / 'horizon-client/26.3',
|
||||
help='prepared resource directory (default: .local/horizon-client/26.3)')
|
||||
args = parser.parse_args()
|
||||
manifest = json.loads((LOCAL / 'minecraft/26.3/manifest.json').read_text())
|
||||
index_info = manifest['assetIndex']
|
||||
target = args.target
|
||||
index_path = target / 'asset-index.json'
|
||||
if not index_path.exists() or hashlib.sha1(index_path.read_bytes()).hexdigest() != index_info['sha1']:
|
||||
data = fetch(index_info['url'])
|
||||
if hashlib.sha1(data).hexdigest() != index_info['sha1']:
|
||||
raise ValueError('asset index checksum mismatch')
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
index_path.write_bytes(data)
|
||||
objects = json.loads(index_path.read_text())['objects']
|
||||
selected = {name: info for name, info in objects.items() if wanted(name)}
|
||||
|
||||
def download(item):
|
||||
name, info = item
|
||||
path = target / 'assets' / name
|
||||
if path.exists() and hashlib.sha1(path.read_bytes()).hexdigest() == info['hash']:
|
||||
return 0
|
||||
h = info['hash']
|
||||
data = fetch(f'https://resources.download.minecraft.net/{h[:2]}/{h}')
|
||||
if hashlib.sha1(data).hexdigest() != h:
|
||||
raise ValueError(f'checksum mismatch for {name}')
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(data)
|
||||
return len(data)
|
||||
|
||||
total = 0
|
||||
with concurrent.futures.ThreadPoolExecutor(16) as pool:
|
||||
for size in pool.map(download, selected.items()):
|
||||
total += size
|
||||
print(f'Client assets ready: {len(selected)} files, {total / 1e6:.1f} MB downloaded')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user