1
2
Fork 0
mirror of https://github.com/mat-1/azalea.git synced 2025-08-02 06:16:04 +00:00
azalea/azalea-chat/src/translatable_component.rs
mat 631ed63dbd
Swarm (#36)
* make azalea-pathfinder dir

* start writing d* lite impl

* more work on d* lite

* work more on implementing d* lite

* full d* lite impl

* updated edges

* add next() function

* add NoPathError

* why does dstar lite not work

* fix d* lite implementation

* make the test actually check the coords

* replace while loop with if statement

* fix clippy complaints

* make W only have to be PartialOrd

* fix PartialOrd issues

* implement mtd* lite

* add a test to mtd* lite

* remove normal d* lite

* make heuristic only take in one arg

* add `success` function

* Update README.md

* evil black magic to make .entity not need dimension

* start adding moves

* slightly improve the vec3/position situation

new macro that implements all the useful functions

* moves stuff

* make it compile

* update deps in az-pathfinder

* make it compile again

* more pathfinding stuff

* add Bot::look_at

* replace EntityMut and EntityRef with just Entity

* block pos pathfinding stuff

* rename movedirection to walkdirection

* execute path every tick

* advance path

* change az-pf version

* make azalea_client keep plugin state

* fix Plugins::get

* why does it think there is air

* start debugging incorrect air

* update some From methods to use rem_euclid

* start adding swarm

* fix deadlock

i still don't understand why it was happening but the solution was to keep the Client::player lock for shorter so it didn't overlap with the Client::dimension lock

* make lookat actually work probably

* fix going too fast

* Update main.rs

* make a thing immutable

* direction_looking_at

* fix rotations

* import swarm in an example

* fix stuff from merge

* remove azalea_pathfinder import

* delete azalea-pathfinder crate

already in azalea::pathfinder module

* swarms

* start working on shared dimensions

* Shared worlds work

* start adding Swarm::add_account

* add_account works

* change "client" to "bot" in some places

* Fix issues from merge

* Update world.rs

* add SwarmEvent::Disconnect(Account)

* almost add SwarmEvent::Chat and new plugin system

it panics rn

* make plugins have to provide the State associated type

* improve comments

* make fn build slightly cleaner

* fix SwarmEvent::Chat

* change a println in bot/main.rs

* Client::shutdown -> disconnect

* polish

fix clippy warnings + improve some docs a bit

* fix shared worlds*

*there's a bug that entities and bots will have their positions exaggerated because the relative movement packet is applied for every entity once per bot

* i am being trolled by rust

for some reason some stuff is really slow for literally no reason and it makes no sense i am going insane

* make world an RwLock again

* remove debug messages

* fix skipping event ticks

unfortunately now sending events is `.send().await?` instead of just `.send()`

* fix deadlock + warnings

* turns out my floor_mod impl was wrong

and i32::rem_euclid has the correct behavior LOL

* still errors with lots of bots

* make swarm iter & fix new chunks not loading

* improve docs

* start fixing tests

* fix all the tests

except the examples i don't know how to exclude them from the tests

* improve docs some more
2022-11-27 16:25:07 -06:00

218 lines
7.4 KiB
Rust
Executable file

use std::fmt::{self, Display, Formatter};
use crate::{
base_component::BaseComponent, style::Style, text_component::TextComponent, Component,
};
#[derive(Clone, Debug, PartialEq)]
pub enum StringOrComponent {
String(String),
Component(Component),
}
/// A message whose content depends on the client's language.
#[derive(Clone, Debug, PartialEq)]
pub struct TranslatableComponent {
pub base: BaseComponent,
pub key: String,
pub args: Vec<StringOrComponent>,
}
impl TranslatableComponent {
pub fn new(key: String, args: Vec<StringOrComponent>) -> Self {
Self {
base: BaseComponent::new(),
key,
args,
}
}
/// Convert the key and args to a Component.
pub fn read(&self) -> Result<TextComponent, fmt::Error> {
let template = azalea_language::get(&self.key).unwrap_or(&self.key);
// decode the % things
let mut i = 0;
let mut matched = 0;
// every time we get a char we add it to built_text, and we push it to
// `arguments` and clear it when we add a new argument component
let mut built_text = String::new();
let mut components = Vec::new();
while i < template.len() {
if template.chars().nth(i).unwrap() == '%' {
let char_after = match template.chars().nth(i + 1) {
Some(c) => c,
None => {
built_text.push(template.chars().nth(i).unwrap());
break;
}
};
i += 1;
match char_after {
'%' => {
built_text.push('%');
}
's' => {
let arg_component = self
.args
.get(matched)
.cloned()
.unwrap_or_else(|| StringOrComponent::String("".to_string()));
components.push(TextComponent::new(built_text.clone()));
built_text.clear();
components.push(TextComponent::from(arg_component));
matched += 1;
}
_ => {
// check if the char is a number
if let Some(d) = char_after.to_digit(10) {
// make sure the next two chars are $s
if let Some('$') = template.chars().nth(i + 1) {
if let Some('s') = template.chars().nth(i + 2) {
i += 2;
built_text.push_str(
&self
.args
.get((d - 1) as usize)
.unwrap_or(&StringOrComponent::String("".to_string()))
.to_string(),
);
} else {
return Err(fmt::Error);
}
} else {
return Err(fmt::Error);
}
} else {
i -= 1;
built_text.push('%');
}
}
}
} else {
built_text.push(template.chars().nth(i).unwrap());
}
i += 1
}
if components.is_empty() {
return Ok(TextComponent::new(built_text));
}
components.push(TextComponent::new(built_text));
Ok(TextComponent {
base: BaseComponent {
siblings: components.into_iter().map(Component::Text).collect(),
style: Style::default(),
},
text: "".to_string(),
})
}
}
impl Display for TranslatableComponent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// this contains the final string will all the ansi escape codes
for component in Component::Translatable(self.clone()).into_iter() {
let component_text = match &component {
Component::Text(c) => c.text.to_string(),
Component::Translatable(c) => c.read()?.to_string(),
};
f.write_str(&component_text)?;
}
Ok(())
}
}
impl Display for StringOrComponent {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
match self {
StringOrComponent::String(s) => write!(f, "{s}"),
StringOrComponent::Component(c) => write!(f, "{c}"),
}
}
}
impl From<StringOrComponent> for TextComponent {
fn from(soc: StringOrComponent) -> Self {
match soc {
StringOrComponent::String(s) => TextComponent::new(s),
StringOrComponent::Component(c) => TextComponent::new(c.to_string()),
}
}
}
// tests
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_none() {
let c = TranslatableComponent::new("translation.test.none".to_string(), vec![]);
assert_eq!(c.read().unwrap().to_string(), "Hello, world!".to_string());
}
#[test]
fn test_complex() {
let c = TranslatableComponent::new(
"translation.test.complex".to_string(),
vec![
StringOrComponent::String("a".to_string()),
StringOrComponent::String("b".to_string()),
StringOrComponent::String("c".to_string()),
StringOrComponent::String("d".to_string()),
],
);
// so true mojang
assert_eq!(
c.read().unwrap().to_string(),
"Prefix, ab again b and a lastly c and also a again!".to_string()
);
}
#[test]
fn test_escape() {
let c = TranslatableComponent::new(
"translation.test.escape".to_string(),
vec![
StringOrComponent::String("a".to_string()),
StringOrComponent::String("b".to_string()),
StringOrComponent::String("c".to_string()),
StringOrComponent::String("d".to_string()),
],
);
assert_eq!(c.read().unwrap().to_string(), "%s %a %%s %%b".to_string());
}
#[test]
fn test_invalid() {
let c = TranslatableComponent::new(
"translation.test.invalid".to_string(),
vec![
StringOrComponent::String("a".to_string()),
StringOrComponent::String("b".to_string()),
StringOrComponent::String("c".to_string()),
StringOrComponent::String("d".to_string()),
],
);
assert_eq!(c.read().unwrap().to_string(), "hi %".to_string());
}
#[test]
fn test_invalid2() {
let c = TranslatableComponent::new(
"translation.test.invalid2".to_string(),
vec![
StringOrComponent::String("a".to_string()),
StringOrComponent::String("b".to_string()),
StringOrComponent::String("c".to_string()),
StringOrComponent::String("d".to_string()),
],
);
assert_eq!(c.read().unwrap().to_string(), "hi % s".to_string());
}
}