mirror of
https://github.com/horizon-rust/horizon.git
synced 2026-11-07 17:21:49 -10:00
Compare commits
257
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cef8fa7e6d | ||
|
|
de8ffbb294 | ||
|
|
c177fef871 | ||
|
|
45ecf7bef0 | ||
|
|
181040539d | ||
|
|
57d4801bff | ||
|
|
0050a65600 | ||
|
|
0914c90455 | ||
|
|
2dd4903b5e | ||
|
|
a3b4d135aa | ||
|
|
8474ac55c9 | ||
|
|
bcb3d50624 | ||
|
|
9c62d4f850 | ||
|
|
ed45e27d15 | ||
|
|
edd340a621 | ||
|
|
9c15e18c6f | ||
|
|
e5338ff202 | ||
|
|
b13b4f2c7f | ||
|
|
2730949b41 | ||
|
|
73cbd863af | ||
|
|
9c67dd3b76 | ||
|
|
702f7e2b93 | ||
|
|
765cdb6bb0 | ||
|
|
4103382062 | ||
|
|
7f9cc4084d | ||
|
|
89f949155c | ||
|
|
129ad4fdf8 | ||
|
|
ea3c3532b6 | ||
|
|
46a5e18630 | ||
|
|
703ba156da | ||
|
|
dd40744480 | ||
|
|
cca5298864 | ||
|
|
44c88b6c7b | ||
|
|
6a9ff4a38f | ||
|
|
4c33a0fdfe | ||
|
|
2e01c336a3 | ||
|
|
d26740a103 | ||
|
|
fdcefc0d90 | ||
|
|
1c87226ac9 | ||
|
|
9c86860e40 | ||
|
|
ca3d2d32af | ||
|
|
1b0923d8cf | ||
|
|
68f50bbd41 | ||
|
|
47bce76078 | ||
|
|
125e540126 | ||
|
|
1578a97c79 | ||
|
|
dbd5fb7f62 | ||
|
|
2a8dc29c69 | ||
|
|
81a0e7e9a5 | ||
|
|
ce980a90de | ||
|
|
dd32d3dc38 | ||
|
|
29f427dabe | ||
|
|
b156515edd | ||
|
|
0fdf1aeee1 | ||
|
|
ee2fb39605 | ||
|
|
559e36ee04 | ||
|
|
7037510e65 | ||
|
|
417a1cebc1 | ||
|
|
9edc7eb80a | ||
|
|
5667e9ebd1 | ||
|
|
d9628314ab | ||
|
|
4984a1329a | ||
|
|
d22b63b9ca | ||
|
|
dc5e8c45f7 | ||
|
|
2782a9057a | ||
|
|
66620f22a3 | ||
|
|
18070bb4ce | ||
|
|
b575402076 | ||
|
|
5b3c3684b1 | ||
|
|
29b4b72dd5 | ||
|
|
9bc8447871 | ||
|
|
39592697c7 | ||
|
|
d785041833 | ||
|
|
56c1100644 | ||
|
|
a881d284a7 | ||
|
|
08c0fc1286 | ||
|
|
e81e23e64e | ||
|
|
5005a7ad9f | ||
|
|
87a6a7a161 | ||
|
|
5ceba01475 | ||
|
|
da9d0dcbe1 | ||
|
|
dc66e37847 | ||
|
|
e2a9909521 | ||
|
|
19faf89699 | ||
|
|
f230017ec1 | ||
|
|
ba86a4d76d | ||
|
|
a734609ab4 | ||
|
|
eab3195848 | ||
|
|
0d2f7b86d5 | ||
|
|
e79992e80b | ||
|
|
248aa8b302 | ||
|
|
cf586e4159 | ||
|
|
7443236850 | ||
|
|
5e391eb673 | ||
|
|
c10553eebf | ||
|
|
215d8e779a | ||
|
|
58a4fd8263 | ||
|
|
3c63c5913e | ||
|
|
7f870d7447 | ||
|
|
f49659c78b | ||
|
|
62ff5241a4 | ||
|
|
4d460c7374 | ||
|
|
d99f7d6d7b | ||
|
|
49c6c47f98 | ||
|
|
b029efa3d3 | ||
|
|
37b4ee3abd | ||
|
|
b07f2775a2 | ||
|
|
e831cb0333 | ||
|
|
16090d3d4a | ||
|
|
31cfdb4b95 | ||
|
|
3b5643628a | ||
|
|
a7e279cfed | ||
|
|
2fe5fa0939 | ||
|
|
5c18ae844b | ||
|
|
584a59ad8c | ||
|
|
7c31259376 | ||
|
|
40c1ab898f | ||
|
|
7fa0fe50f7 | ||
|
|
611d1ef51e | ||
|
|
49866a4482 | ||
|
|
6a06853032 | ||
|
|
54e56ca215 | ||
|
|
cdefed7a19 | ||
|
|
b8f48f3ad0 | ||
|
|
cc15e8ebb3 | ||
|
|
db8fa8377d | ||
|
|
dbeb13ff6b | ||
|
|
39d23ac256 | ||
|
|
d900488d12 | ||
|
|
e7827deabb | ||
|
|
916150f02c | ||
|
|
5302f6a22a | ||
|
|
3497737ecc | ||
|
|
9db690b1e0 | ||
|
|
70a6aa45aa | ||
|
|
8c0b674fe8 | ||
|
|
ddd1dbdf91 | ||
|
|
5bc76cbba9 | ||
|
|
c3dceac2aa | ||
|
|
4bd3210f78 | ||
|
|
6255c02096 | ||
|
|
ced6323bb2 | ||
|
|
698e7fd662 | ||
|
|
cf0b5a8e63 | ||
|
|
7808916266 | ||
|
|
53beacfd13 | ||
|
|
6a59002283 | ||
|
|
ab9ceb6a6d | ||
|
|
46d466f7c3 | ||
|
|
113cafd2d1 | ||
|
|
ab640c7646 | ||
|
|
b2a5abb885 | ||
|
|
1da38a5c46 | ||
|
|
2bb3903b49 | ||
|
|
c8915be58c | ||
|
|
b1d3c9b92b | ||
|
|
8dffd2b847 | ||
|
|
2a7ee57bab | ||
|
|
4245540711 | ||
|
|
6bd34b64d6 | ||
|
|
a690ccef3c | ||
|
|
624be7df86 | ||
|
|
3c7e4ba574 | ||
|
|
b27d4b85e1 | ||
|
|
d5a7e8420b | ||
|
|
bd80ffd540 | ||
|
|
1df28d1793 | ||
|
|
168bc8ffd5 | ||
|
|
8bb8239603 | ||
|
|
0352ad0e19 | ||
|
|
702d7cf2cc | ||
|
|
526887be89 | ||
|
|
a5ae075a5d | ||
|
|
14a4d2726d | ||
|
|
38712c49ec | ||
|
|
a287f701e6 | ||
|
|
85032102a8 | ||
|
|
c3987df0b2 | ||
|
|
6c50b7d980 | ||
|
|
1fa4a780f0 | ||
|
|
d372e9ece9 | ||
|
|
3c514d5c17 | ||
|
|
833b9385ee | ||
|
|
21ba38e633 | ||
|
|
940b642233 | ||
|
|
d192946a6f | ||
|
|
af3aa00377 | ||
|
|
fd0aeb5331 | ||
|
|
e9c6751a1b | ||
|
|
cf0b111bdd | ||
|
|
bf7179c48b | ||
|
|
dbb03a42d3 | ||
|
|
99b6b8f3e8 | ||
|
|
fc409d28f4 | ||
|
|
fa727a627a | ||
|
|
dc44f98818 | ||
|
|
511eb49629 | ||
|
|
90014f63d2 | ||
|
|
a278572906 | ||
|
|
2882f0764d | ||
|
|
859b6be783 | ||
|
|
e8896336da | ||
|
|
e2b2b2ccd0 | ||
|
|
8f00332979 | ||
|
|
0e2b244120 | ||
|
|
835674f45d | ||
|
|
c6efb367b0 | ||
|
|
2acf1d7798 | ||
|
|
c9bd057d70 | ||
|
|
8339f6d12f | ||
|
|
0320e7d593 | ||
|
|
22a4620643 | ||
|
|
8422225047 | ||
|
|
9d7b4e8a2d | ||
|
|
f52af64e89 | ||
|
|
54360a74e3 | ||
|
|
cd97b34460 | ||
|
|
03f3fb057d | ||
|
|
3fe4834ceb | ||
|
|
be8b86d470 | ||
|
|
f755d7fba0 | ||
|
|
b08e04cd8a | ||
|
|
150a29974d | ||
|
|
eff8ae41c6 | ||
|
|
c5dead28a0 | ||
|
|
15099724ed | ||
|
|
52a820e708 | ||
|
|
85f2a9ad87 | ||
|
|
16d71b0a24 | ||
|
|
f83310a891 | ||
|
|
d480ce24dd | ||
|
|
f1a8cc6a0d | ||
|
|
d321b656f6 | ||
|
|
41f60562fd | ||
|
|
136b352e4f | ||
|
|
ff1b01616f | ||
|
|
be26c6db88 | ||
|
|
66b705cec3 | ||
|
|
780abb9832 | ||
|
|
826147d716 | ||
|
|
0b4fa473e7 | ||
|
|
b85ce82160 | ||
|
|
ea7df1d0dc | ||
|
|
fea8346f23 | ||
|
|
e36a480063 | ||
|
|
ee9d8a656f | ||
|
|
dae67a88cc | ||
|
|
758d66bf44 | ||
|
|
b201dafa75 | ||
|
|
7c58bf004f | ||
|
|
4119284a4f | ||
|
|
957a3c6622 | ||
|
|
1758b147b8 | ||
|
|
3788dff6a1 | ||
|
|
4e96037c78 | ||
|
|
5b066b1b78 | ||
|
|
4eb95c4d3e |
No files matched your search
@@ -16,12 +16,14 @@ jobs:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
REPO: ${{ github.repository }}
|
||||
BRANCH: ${{ github.event.pull_request.head.ref }}
|
||||
SHA: ${{ github.event.pull_request.head.sha }}
|
||||
HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
run: |
|
||||
# Every head the pull request had, not only its last: a run-parity label added on an older head left that
|
||||
# run queued after the merge (#3104, 2026-10-29). Its branch in its own repository names its runs (another
|
||||
# fork can have a branch of the same name).
|
||||
for status in queued in_progress waiting pending requested; do
|
||||
gh run list -R "$REPO" --branch "$BRANCH" --status "$status" --limit 100 \
|
||||
--json databaseId,event,headSha \
|
||||
-q ".[] | select(.event == \"pull_request\" and .headSha == \"$SHA\") | .databaseId"
|
||||
gh api -X GET "repos/$REPO/actions/runs" -f branch="$BRANCH" -f event=pull_request -f status="$status" \
|
||||
-f per_page=100 --jq ".workflow_runs[] | select(.head_repository.full_name == \"$HEAD_REPO\") | .id"
|
||||
done | sort -u | while read -r id; do
|
||||
gh run cancel -R "$REPO" "$id" || true
|
||||
done
|
||||
@@ -5,11 +5,15 @@ name: run-parity
|
||||
# skipped `verify`, and GitHub counts a skipped required check as passed.
|
||||
on:
|
||||
pull_request:
|
||||
types: [labeled]
|
||||
# A push starts a run only to cancel the old head's (see concurrency): the job runs on the label alone.
|
||||
types: [labeled, synchronize]
|
||||
permissions:
|
||||
contents: read
|
||||
concurrency:
|
||||
group: run-parity-${{ github.event.pull_request.number }}
|
||||
# The run-parity label and pushes share one group per pull request, so the newest run cancels the one before: a
|
||||
# pushed pull request's run tested a head the merge would no longer land. Any other label gets a group of its own:
|
||||
# in the shared one, adding needs-proof cancelled the parity run queued seconds before (run 40766180150).
|
||||
group: run-parity-${{ github.event.pull_request.number }}${{ github.event.action == 'labeled' && github.event.label.name != 'run-parity' && format('-{0}', github.run_id) || '' }}
|
||||
cancel-in-progress: true
|
||||
env:
|
||||
# Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md).
|
||||
|
||||
@@ -11,13 +11,18 @@ pub fn parse_snbt(input: &str) -> Result<(Value, usize), String> {
|
||||
let mut p = Parser {
|
||||
s: input.as_bytes(),
|
||||
i: 0,
|
||||
depth: 0,
|
||||
};
|
||||
let v = p.value()?;
|
||||
Ok((v, p.i))
|
||||
}
|
||||
/// Nesting deeper than NBT's own limit (`NbtAccounter`'s 512) is refused
|
||||
/// rather than overflowing the stack.
|
||||
const SNBT_MAX_DEPTH: usize = 512;
|
||||
struct Parser<'a> {
|
||||
s: &'a [u8],
|
||||
i: usize,
|
||||
depth: usize,
|
||||
}
|
||||
impl Parser<'_> {
|
||||
fn ws(&mut self) {
|
||||
@@ -41,57 +46,22 @@ impl Parser<'_> {
|
||||
self.ws();
|
||||
match self.peek() {
|
||||
Some(b'{') => {
|
||||
self.i += 1;
|
||||
let mut map = Map::new();
|
||||
self.ws();
|
||||
if self.peek() == Some(b'}') {
|
||||
self.i += 1;
|
||||
return Ok(Value::Object(map));
|
||||
}
|
||||
loop {
|
||||
self.ws();
|
||||
let key = self.string()?;
|
||||
self.expect(b':')?;
|
||||
map.insert(key, self.value()?);
|
||||
self.ws();
|
||||
match self.peek() {
|
||||
Some(b',') => self.i += 1,
|
||||
Some(b'}') => {
|
||||
self.i += 1;
|
||||
return Ok(Value::Object(map));
|
||||
}
|
||||
_ => return Err("expected ',' or '}'".into()),
|
||||
}
|
||||
if self.depth >= SNBT_MAX_DEPTH {
|
||||
return Err(format!("tag nesting too deep at {}", self.i));
|
||||
}
|
||||
self.depth += 1;
|
||||
let v = self.object();
|
||||
self.depth -= 1;
|
||||
v
|
||||
}
|
||||
Some(b'[') => {
|
||||
self.i += 1;
|
||||
let mut list = Vec::new();
|
||||
self.ws();
|
||||
// Typed arrays [B;...], [I;...], [L;...].
|
||||
if matches!(
|
||||
self.s.get(self.i..self.i + 2),
|
||||
Some([b'B' | b'I' | b'L', b';'])
|
||||
) {
|
||||
self.i += 2;
|
||||
}
|
||||
self.ws();
|
||||
if self.peek() == Some(b']') {
|
||||
self.i += 1;
|
||||
return Ok(Value::Array(list));
|
||||
}
|
||||
loop {
|
||||
list.push(self.value()?);
|
||||
self.ws();
|
||||
match self.peek() {
|
||||
Some(b',') => self.i += 1,
|
||||
Some(b']') => {
|
||||
self.i += 1;
|
||||
return Ok(Value::Array(list));
|
||||
}
|
||||
_ => return Err("expected ',' or ']'".into()),
|
||||
}
|
||||
if self.depth >= SNBT_MAX_DEPTH {
|
||||
return Err(format!("tag nesting too deep at {}", self.i));
|
||||
}
|
||||
self.depth += 1;
|
||||
let v = self.array();
|
||||
self.depth -= 1;
|
||||
v
|
||||
}
|
||||
Some(b'"' | b'\'') => Ok(Value::String(self.string()?)),
|
||||
Some(_) => {
|
||||
@@ -105,10 +75,20 @@ impl Parser<'_> {
|
||||
_ => {
|
||||
let digits = word
|
||||
.trim_end_matches(['b', 'B', 's', 'S', 'l', 'L', 'f', 'F', 'd', 'D']);
|
||||
match (digits.parse::<i64>(), digits.parse::<f64>()) {
|
||||
(Ok(n), _) if digits.len() + 1 >= word.len() => Value::from(n),
|
||||
(_, Ok(f)) if digits.len() + 1 >= word.len() => Value::from(f),
|
||||
_ => Value::String(word),
|
||||
// Only digits (and an exponent) make a number: `nan`
|
||||
// or `Infinity`, which Rust's parse would take, stays
|
||||
// a string.
|
||||
if digits
|
||||
.bytes()
|
||||
.any(|c| c.is_ascii_alphabetic() && c != b'e' && c != b'E')
|
||||
{
|
||||
Value::String(word)
|
||||
} else {
|
||||
match (digits.parse::<i64>(), digits.parse::<f64>()) {
|
||||
(Ok(n), _) if digits.len() + 1 >= word.len() => Value::from(n),
|
||||
(_, Ok(f)) if digits.len() + 1 >= word.len() => Value::from(f),
|
||||
_ => Value::String(word),
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -116,6 +96,59 @@ impl Parser<'_> {
|
||||
None => Err("expected a value".into()),
|
||||
}
|
||||
}
|
||||
fn object(&mut self) -> Result<Value, String> {
|
||||
self.i += 1;
|
||||
let mut map = Map::new();
|
||||
self.ws();
|
||||
if self.peek() == Some(b'}') {
|
||||
self.i += 1;
|
||||
return Ok(Value::Object(map));
|
||||
}
|
||||
loop {
|
||||
self.ws();
|
||||
let key = self.string()?;
|
||||
self.expect(b':')?;
|
||||
map.insert(key, self.value()?);
|
||||
self.ws();
|
||||
match self.peek() {
|
||||
Some(b',') => self.i += 1,
|
||||
Some(b'}') => {
|
||||
self.i += 1;
|
||||
return Ok(Value::Object(map));
|
||||
}
|
||||
_ => return Err("expected ',' or '}'".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn array(&mut self) -> Result<Value, String> {
|
||||
self.i += 1;
|
||||
let mut list = Vec::new();
|
||||
self.ws();
|
||||
// Typed arrays [B;...], [I;...], [L;...].
|
||||
if matches!(
|
||||
self.s.get(self.i..self.i + 2),
|
||||
Some([b'B' | b'I' | b'L', b';'])
|
||||
) {
|
||||
self.i += 2;
|
||||
}
|
||||
self.ws();
|
||||
if self.peek() == Some(b']') {
|
||||
self.i += 1;
|
||||
return Ok(Value::Array(list));
|
||||
}
|
||||
loop {
|
||||
list.push(self.value()?);
|
||||
self.ws();
|
||||
match self.peek() {
|
||||
Some(b',') => self.i += 1,
|
||||
Some(b']') => {
|
||||
self.i += 1;
|
||||
return Ok(Value::Array(list));
|
||||
}
|
||||
_ => return Err("expected ',' or ']'".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn unquoted(&mut self) -> String {
|
||||
let start = self.i;
|
||||
while let Some(c) = self.peek() {
|
||||
@@ -351,4 +384,22 @@ mod tests {
|
||||
let t = to_text(&v, &mut |_| Text::empty());
|
||||
assert_eq!(t.spans[0].style.font, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snbt_nesting_is_bounded() {
|
||||
let nest = |n: usize| format!("{}1{}", "[".repeat(n), "]".repeat(n));
|
||||
assert!(parse_snbt(&nest(512)).is_ok());
|
||||
assert!(parse_snbt(&nest(513)).is_err());
|
||||
assert!(parse_snbt(&nest(100_000)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_words_that_look_numeric_stay_strings() {
|
||||
let (v, _) = parse_snbt("{text:nan}").unwrap();
|
||||
assert_eq!(v["text"], Value::String("nan".into()));
|
||||
let (v, _) = parse_snbt("{text:Infinity}").unwrap();
|
||||
assert_eq!(v["text"], Value::String("Infinity".into()));
|
||||
let (v, _) = parse_snbt("{n:1.5}").unwrap();
|
||||
assert_eq!(v["n"], Value::from(1.5));
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,9 @@ pub struct Registries {
|
||||
pub function_tags: Vec<String>,
|
||||
/// The block the source is looking at (relevant coordinates).
|
||||
pub target_block: Option<[i32; 3]>,
|
||||
/// `ClientSuggestionProvider.getAbsoluteCoordinates`: the exact point of
|
||||
/// that block hit, each coordinate as `%.2f` (`Locale.ROOT`).
|
||||
pub target_point: Option<[String; 3]>,
|
||||
/// Every registry's element and tag ids (`minecraft:item` -> ...), as
|
||||
/// the server's registry access and reloadable registries hold them.
|
||||
pub by_registry: BTreeMap<String, RegistryIds>,
|
||||
|
||||
@@ -662,10 +662,22 @@ pub fn name_shown(own: Option<&Team>, viewer: Option<&Team>, v: NameView) -> boo
|
||||
}
|
||||
!v.hud_hidden && !v.is_camera && visible && !v.is_vehicle
|
||||
}
|
||||
/// `ServerPlayer.die`: whether a player's death message reaches the player
|
||||
/// themselves (the team broadcasts leave out the dying player).
|
||||
pub fn own_death_message_shown(team: Option<&Team>) -> bool {
|
||||
team.is_none_or(|t| t.death_message_visibility == Visibility::Always)
|
||||
/// `ServerPlayer.die`: whether `other` hears the death message of `dying`
|
||||
/// (`broadcastSystemMessage`, `broadcastSystemToTeam` or
|
||||
/// `broadcastSystemToAllExceptTeam`, by the team's death message visibility).
|
||||
pub fn death_message_reaches(board: &Scoreboard, dying: &str, other: &str) -> bool {
|
||||
let Some(team) = board.players_team(dying) else {
|
||||
return true;
|
||||
};
|
||||
let same_team = board
|
||||
.players_team(other)
|
||||
.is_some_and(|t| t.name == team.name);
|
||||
match team.death_message_visibility {
|
||||
Visibility::Always => true,
|
||||
Visibility::Never => false,
|
||||
Visibility::HideForOtherTeams => same_team && other != dying,
|
||||
Visibility::HideForOwnTeam => !same_team,
|
||||
}
|
||||
}
|
||||
|
||||
// ---- objectives and scores ---------------------------------------------
|
||||
|
||||
@@ -403,31 +403,7 @@ impl Text {
|
||||
continue;
|
||||
}
|
||||
let Some(code) = chars.next() else { break };
|
||||
let code = code.to_ascii_lowercase();
|
||||
let next = if let Some(c) = COLORS.iter().find(|c| c.0 == code) {
|
||||
// Style.applyLegacyFormat: a colour clears the decorations.
|
||||
Style {
|
||||
color: Some(c.2),
|
||||
bold: Some(false),
|
||||
italic: Some(false),
|
||||
underlined: Some(false),
|
||||
strikethrough: Some(false),
|
||||
obfuscated: Some(false),
|
||||
..style.clone()
|
||||
}
|
||||
} else {
|
||||
let mut s = style.clone();
|
||||
match code {
|
||||
'k' => s.obfuscated = Some(true),
|
||||
'l' => s.bold = Some(true),
|
||||
'm' => s.strikethrough = Some(true),
|
||||
'n' => s.underlined = Some(true),
|
||||
'o' => s.italic = Some(true),
|
||||
'r' => s = span.style.clone(),
|
||||
_ => {}
|
||||
}
|
||||
s
|
||||
};
|
||||
let next = legacy_format(&style, code, &span.style);
|
||||
if next != style {
|
||||
if !current.is_empty() {
|
||||
out.spans.push(Span {
|
||||
@@ -588,6 +564,35 @@ fn style_json(style: &Style) -> Vec<(String, Value)> {
|
||||
out
|
||||
}
|
||||
|
||||
/// `Style.applyLegacyFormat` for the code after a `§`, `§r` going back to
|
||||
/// `reset` (`StringDecomposer.iterateFormatted`); an unknown code changes nothing.
|
||||
pub fn legacy_format(style: &Style, code: char, reset: &Style) -> Style {
|
||||
let code = code.to_ascii_lowercase();
|
||||
if let Some(c) = COLORS.iter().find(|c| c.0 == code) {
|
||||
// A colour clears the decorations.
|
||||
return Style {
|
||||
color: Some(c.2),
|
||||
bold: Some(false),
|
||||
italic: Some(false),
|
||||
underlined: Some(false),
|
||||
strikethrough: Some(false),
|
||||
obfuscated: Some(false),
|
||||
..style.clone()
|
||||
};
|
||||
}
|
||||
let mut s = style.clone();
|
||||
match code {
|
||||
'k' => s.obfuscated = Some(true),
|
||||
'l' => s.bold = Some(true),
|
||||
'm' => s.strikethrough = Some(true),
|
||||
'n' => s.underlined = Some(true),
|
||||
'o' => s.italic = Some(true),
|
||||
'r' => s = reset.clone(),
|
||||
_ => {}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// TranslatableContents.decomposeTemplate: `%s` takes the next argument,
|
||||
/// `%n$s` a numbered one and `%%` is a percent sign. Malformed templates are
|
||||
/// shown verbatim.
|
||||
|
||||
@@ -300,9 +300,8 @@ impl Default for KeyBinds {
|
||||
}
|
||||
}
|
||||
/// Each default key once, in order: two mappings that share a default key
|
||||
/// (Advancements and the debug profiler both on L) are one press of it, not
|
||||
/// two (the second would close the screen the first opened). Vanilla clicks
|
||||
/// both mappings, but the profiler one only acts with F3 held.
|
||||
/// (Pick Block and the spectator hotbar both on the middle button) are one
|
||||
/// press of it, not two.
|
||||
fn distinct<T: PartialEq>(keys: Vec<T>) -> Vec<T> {
|
||||
let mut out = Vec::with_capacity(keys.len());
|
||||
for k in keys {
|
||||
@@ -368,6 +367,25 @@ impl KeyBinds {
|
||||
.map(|m| m.0)
|
||||
.filter(move |n| self.get(n) == key)
|
||||
}
|
||||
/// The mappings bound to `key` that [`KeyBinds::translate_all`] follows:
|
||||
/// all but the debug keys. Those act only with F3 held
|
||||
/// (`KeyboardHandler.handleDebugKeys`, `debug_keys.rs` reads the physical
|
||||
/// key and the binding itself); their defaults (A, S, D, T, L, 1 to 4...)
|
||||
/// would otherwise turn the key back into its old gameplay meaning.
|
||||
fn translated_mappings<'a>(&'a self, key: &'a str) -> impl Iterator<Item = &'static str> + 'a {
|
||||
MAPPINGS
|
||||
.iter()
|
||||
.filter(|m| m.2 != "debug")
|
||||
.map(|m| m.0)
|
||||
.filter(move |n| self.get(n) == key)
|
||||
}
|
||||
/// Whether a mapping (other than a debug key) whose default is `key` was
|
||||
/// bound elsewhere.
|
||||
fn default_moved(&self, key: &str) -> bool {
|
||||
MAPPINGS
|
||||
.iter()
|
||||
.any(|(n, d, c)| *d == key && *c != "debug" && !self.is_default(n))
|
||||
}
|
||||
/// Translate a physical key into the default key of the mapping it is
|
||||
/// bound to, so game code written against vanilla defaults follows the
|
||||
/// player's bindings. `None` means the key now does nothing; mouse
|
||||
@@ -384,7 +402,7 @@ impl KeyBinds {
|
||||
return vec![Ok(key)];
|
||||
};
|
||||
let bound: Vec<_> = self
|
||||
.mappings_for(name)
|
||||
.translated_mappings(name)
|
||||
.filter_map(|mapping| {
|
||||
let default = Self::default_of(mapping);
|
||||
match key_code(default) {
|
||||
@@ -397,10 +415,7 @@ impl KeyBinds {
|
||||
return distinct(bound);
|
||||
}
|
||||
// An unbound key whose default meaning was moved elsewhere is inert.
|
||||
if MAPPINGS
|
||||
.iter()
|
||||
.any(|(n, d, _)| *d == name && !self.is_default(n))
|
||||
{
|
||||
if self.default_moved(name) {
|
||||
return Vec::new();
|
||||
}
|
||||
vec![Ok(key)]
|
||||
@@ -413,7 +428,7 @@ impl KeyBinds {
|
||||
pub fn translate_mouse_all(&self, button: MouseButton) -> Vec<Result<KeyCode, MouseButton>> {
|
||||
let name = mouse_name(button);
|
||||
let bound: Vec<_> = self
|
||||
.mappings_for(&name)
|
||||
.translated_mappings(&name)
|
||||
.filter_map(|mapping| {
|
||||
let default = Self::default_of(mapping);
|
||||
match mouse_button(default) {
|
||||
@@ -425,10 +440,7 @@ impl KeyBinds {
|
||||
if !bound.is_empty() {
|
||||
return distinct(bound);
|
||||
}
|
||||
if MAPPINGS
|
||||
.iter()
|
||||
.any(|(n, d, _)| *d == name && !self.is_default(n))
|
||||
{
|
||||
if self.default_moved(&name) {
|
||||
return Vec::new();
|
||||
}
|
||||
vec![Err(button)]
|
||||
@@ -508,6 +520,29 @@ mod tests {
|
||||
assert_eq!(k.conflicts("key.forward"), ["key.jump"]);
|
||||
}
|
||||
#[test]
|
||||
fn a_moved_key_keeps_no_default_action() {
|
||||
// #3158: the debug keys (F3+A, F3+1...) share these keys' defaults,
|
||||
// and must not hand them back their gameplay meaning.
|
||||
let mut k = KeyBinds::default();
|
||||
k.set("key.hotbar.1", "key.keyboard.q");
|
||||
assert_eq!(k.translate_all(KeyCode::Digit1), []);
|
||||
assert_eq!(
|
||||
k.translate_all(KeyCode::KeyQ),
|
||||
[Ok(KeyCode::KeyQ), Ok(KeyCode::Digit1)]
|
||||
);
|
||||
k.set("key.inventory", "key.keyboard.a");
|
||||
k.set("key.left", "key.keyboard.e");
|
||||
assert_eq!(k.translate_all(KeyCode::KeyA), [Ok(KeyCode::KeyE)]);
|
||||
assert_eq!(k.translate_all(KeyCode::KeyE), [Ok(KeyCode::KeyA)]);
|
||||
k.set("key.back", "key.keyboard.down");
|
||||
assert_eq!(k.translate_all(KeyCode::KeyS), []);
|
||||
// Keys left alone still act, and a moved debug key changes nothing.
|
||||
k.set("key.debug.fpsCharts", "key.keyboard.9");
|
||||
assert_eq!(k.translate_all(KeyCode::Digit2), [Ok(KeyCode::Digit2)]);
|
||||
assert_eq!(k.translate_all(KeyCode::Digit9), [Ok(KeyCode::Digit9)]);
|
||||
assert_eq!(k.translate_all(KeyCode::F3), [Ok(KeyCode::F3)]);
|
||||
}
|
||||
#[test]
|
||||
fn display_names() {
|
||||
assert_eq!(display_name("key.keyboard.w").plain(), "W");
|
||||
assert_eq!(display_name("key.keyboard.slash").plain(), "/");
|
||||
|
||||
@@ -654,10 +654,20 @@ fn sign_text_calls(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// How far the text of an outlined call sits in front of its outline, in
|
||||
/// text units (`Font.DisplayMode.POLYGON_OFFSET`, see `draw_text`).
|
||||
const TEXT_OVER_OUTLINE: f32 = 0.05;
|
||||
|
||||
/// Draws a text call with the font atlas: 8x8 glyph cells, the outline as
|
||||
/// eight one-pixel offsets under the text.
|
||||
///
|
||||
/// `TextFeatureRenderer.renderText` draws the outline glyphs NORMAL and the
|
||||
/// text over them POLYGON_OFFSET, so the coplanar text always wins the depth
|
||||
/// test. Here both share one mesh, so the text is lifted a hair towards the
|
||||
/// reader instead (a twentieth of a font pixel, invisible) rather than
|
||||
/// z-fighting with the outline under it.
|
||||
fn draw_text(scene: &Scene, call: &TextCall, out: &mut Vec<Vertex>) {
|
||||
let mut emit = |dx: f32, dy: f32, argb: u32| {
|
||||
let mut emit = |dx: f32, dy: f32, z: f32, argb: u32| {
|
||||
let mut x = call.x + dx;
|
||||
let y0 = call.y + dy;
|
||||
for ch in call.text.chars() {
|
||||
@@ -672,7 +682,7 @@ fn draw_text(scene: &Scene, call: &TextCall, out: &mut Vec<Vertex>) {
|
||||
normal: [0; 4],
|
||||
pos: call
|
||||
.matrix
|
||||
.transform_point3(Vec3::new(cx, cy, 0.0))
|
||||
.transform_point3(Vec3::new(cx, cy, z))
|
||||
.to_array(),
|
||||
uv,
|
||||
layer: 0,
|
||||
@@ -697,10 +707,15 @@ fn draw_text(scene: &Scene, call: &TextCall, out: &mut Vec<Vertex>) {
|
||||
(0.0, 1.0),
|
||||
(1.0, 1.0),
|
||||
] {
|
||||
emit(dx, dy, call.outline);
|
||||
emit(dx, dy, 0.0, call.outline);
|
||||
}
|
||||
}
|
||||
emit(0.0, 0.0, call.color);
|
||||
let z = if call.outline != 0 {
|
||||
TEXT_OVER_OUTLINE
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
emit(0.0, 0.0, z, call.color);
|
||||
}
|
||||
|
||||
/// Block-entity fields the level ticks, at one position (vanilla's own field
|
||||
@@ -2258,6 +2273,69 @@ mod tests {
|
||||
assert_eq!(out[2].uv, [0.5, 0.5]);
|
||||
}
|
||||
|
||||
/// TextFeatureRenderer.renderText: an outlined call's text is drawn over
|
||||
/// its outline (Font.DisplayMode.POLYGON_OFFSET), never level with it,
|
||||
/// and plain text stays on the sign's plane.
|
||||
#[test]
|
||||
fn outlined_sign_text_sits_in_front_of_its_outline() {
|
||||
let world = World::new(BlockStateId(0), 1);
|
||||
let sprites = HashMap::new();
|
||||
let glyph = |_: char| {
|
||||
let rect = Rect {
|
||||
u0: 0.0,
|
||||
v0: 0.0,
|
||||
u1: 0.0625,
|
||||
v1: 0.0625,
|
||||
w: 8,
|
||||
h: 8,
|
||||
};
|
||||
(Some(rect), 6.0)
|
||||
};
|
||||
let scene = Scene {
|
||||
camera: DVec3::ZERO,
|
||||
orientation: Quat::IDENTITY,
|
||||
anim: &|_| BlockAnim::default(),
|
||||
texts: None,
|
||||
partial: 0.0,
|
||||
game_time: 0,
|
||||
max_y: 320,
|
||||
world: &world,
|
||||
sprites: &sprites,
|
||||
nether: false,
|
||||
lid: &|_| 0.0,
|
||||
sign: &|_| None,
|
||||
banner: &|_| Vec::new(),
|
||||
skull: &|_| None,
|
||||
glyph: &glyph,
|
||||
glyphs: 0,
|
||||
};
|
||||
let mut call = TextCall {
|
||||
matrix: Mat4::IDENTITY,
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
text: "Hi".into(),
|
||||
color: 0xFFFF_FF00,
|
||||
outline: 0xFF33_3300,
|
||||
light: 240 | 240 << 8,
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
draw_text(&scene, &call, &mut out);
|
||||
// Eight outline copies, then the text, four corners a glyph.
|
||||
assert_eq!(out.len(), 9 * 2 * 4);
|
||||
let (outline, text) = out.split_at(8 * 2 * 4);
|
||||
let front = outline.iter().map(|v| v.pos[2]).fold(f32::MIN, f32::max);
|
||||
assert!(
|
||||
text.iter().all(|v| v.pos[2] > front),
|
||||
"text z {:?} not in front of the outline at {front}",
|
||||
text.iter().map(|v| v.pos[2]).collect::<Vec<_>>()
|
||||
);
|
||||
call.outline = 0;
|
||||
out.clear();
|
||||
draw_text(&scene, &call, &mut out);
|
||||
assert_eq!(out.len(), 2 * 4);
|
||||
assert!(out.iter().all(|v| v.pos[2] == 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_sign_text_matches_and_follows_changes() {
|
||||
let renderer = BlockEntityRenderer {
|
||||
|
||||
@@ -14,14 +14,19 @@ pub use horizon_client_core::potions::{
|
||||
BASE_POTION_COLOR, Category, EFFECTS, EffectDef, POTIONS, PotionDef, effect, namespaced,
|
||||
potion, potion_color,
|
||||
};
|
||||
/// `MobEffectUtil.formatDuration` at 20 TPS: m:ss or h:mm:ss.
|
||||
/// `MobEffectUtil.formatDuration` at 20 TPS.
|
||||
pub fn format_duration(ticks: i32) -> String {
|
||||
let secs = ticks / 20;
|
||||
format_tick_duration(ticks, 20.0)
|
||||
}
|
||||
/// `StringUtil.formatTickDuration`: mm:ss, or hh:mm:ss from an hour up, every
|
||||
/// field two digits.
|
||||
pub fn format_tick_duration(ticks: i32, tick_rate: f32) -> String {
|
||||
let secs = (ticks as f32 / tick_rate).floor() as i32;
|
||||
let (h, m, s) = (secs / 3600, secs / 60 % 60, secs % 60);
|
||||
if h > 0 {
|
||||
format!("{h}:{m:02}:{s:02}")
|
||||
format!("{h:02}:{m:02}:{s:02}")
|
||||
} else {
|
||||
format!("{m}:{s:02}")
|
||||
format!("{m:02}:{s:02}")
|
||||
}
|
||||
}
|
||||
/// `item.minecraft.potion.effect.<name>` style translation key for a potion item.
|
||||
@@ -317,10 +322,14 @@ mod tests {
|
||||
potion_name_key("minecraft:splash_potion", Some("minecraft:long_swiftness")),
|
||||
"item.minecraft.splash_potion.effect.swiftness"
|
||||
);
|
||||
assert_eq!(format_duration(9600), "8:00");
|
||||
assert_eq!(format_duration(450), "0:22");
|
||||
assert_eq!(format_duration(9600), "08:00");
|
||||
assert_eq!(format_duration(450), "00:22");
|
||||
assert_eq!(format_duration(140), "00:07");
|
||||
assert_eq!(format_duration(1800), "01:30");
|
||||
assert_eq!(format_duration(72000), "01:00:00");
|
||||
assert_eq!(format_tick_duration(9600, 40.0), "04:00");
|
||||
let t = tooltip(Some("minecraft:strong_poison"), 1.0, &|_| None);
|
||||
assert_eq!(t[0].0, "poison II (0:21)");
|
||||
assert_eq!(t[0].0, "poison II (00:21)");
|
||||
assert_eq!(POTIONS.len(), 46);
|
||||
}
|
||||
|
||||
@@ -377,4 +386,23 @@ mod tests {
|
||||
stand.tick(&brewing, &items, &providers);
|
||||
assert_eq!(stand.brew_time, 0);
|
||||
}
|
||||
|
||||
/// #3312: `PotionContents.getPotionDescription` names the effects with
|
||||
/// translatable components, so a Russian game reads them from ru_ru.json
|
||||
/// (the prepared one; skipped without it), as the tooltip's other lines.
|
||||
#[test]
|
||||
fn effect_lines_read_the_selected_language() {
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../.local/horizon-client")
|
||||
.join(horizon_core::VANILLA_VERSION);
|
||||
if !root.join("assets/minecraft/lang/ru_ru.json").exists() {
|
||||
return;
|
||||
}
|
||||
let ru = crate::lang::Language::load(&[&root], "ru_ru");
|
||||
let translate = |key: &str| ru.get(key).map(str::to_owned);
|
||||
let lines = tooltip(Some("minecraft:turtle_master"), 0.125, &translate);
|
||||
assert_eq!(lines.len(), 2);
|
||||
assert!(lines[0].0.starts_with("Замедление IV ("), "{lines:?}");
|
||||
assert!(lines[1].0.starts_with("Сопротивление III ("), "{lines:?}");
|
||||
}
|
||||
}
|
||||
@@ -653,18 +653,57 @@ pub fn modify_fov_based_on_death_or_fluid(
|
||||
fov
|
||||
}
|
||||
|
||||
/// `ClientAvatarState`: the walked distance and view bob of a player.
|
||||
/// `ClientAvatarState`: the walked distance, view bob and cloak of a player.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct AvatarBob {
|
||||
pub walk_dist: f32,
|
||||
pub walk_dist_o: f32,
|
||||
pub bob: f32,
|
||||
pub bob_o: f32,
|
||||
/// `xCloak`, `yCloak`, `zCloak`: a point trailing the player, which the cape leans from.
|
||||
pub cloak: [f64; 3],
|
||||
pub cloak_o: [f64; 3],
|
||||
}
|
||||
impl AvatarBob {
|
||||
/// `ClientAvatarState.tick` (at the start of `AbstractClientPlayer.tick`).
|
||||
pub fn tick(&mut self) {
|
||||
/// `ClientAvatarState.tick` (at the start of `AbstractClientPlayer.tick`)
|
||||
/// with the player's position then: `moveCloak` eases the cloak a quarter
|
||||
/// of the way there, or puts it there from 10 blocks away.
|
||||
pub fn tick(&mut self, position: [f64; 3]) {
|
||||
self.walk_dist_o = self.walk_dist;
|
||||
self.cloak_o = self.cloak;
|
||||
for i in 0..3 {
|
||||
let d = position[i] - self.cloak[i];
|
||||
if d > 10.0 || d < -10.0 {
|
||||
self.cloak[i] = position[i];
|
||||
self.cloak_o[i] = position[i];
|
||||
} else {
|
||||
self.cloak[i] += d * 0.25;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `AvatarRenderer.extractCapeState`: the cape's `capeFlap`, `capeLean`
|
||||
/// and `capeLean2` (degrees) for the player at `position` (interpolated)
|
||||
/// with its body turned `body_yaw` and its `fallFlyingScale`.
|
||||
pub fn cape(
|
||||
&self,
|
||||
partial: f32,
|
||||
position: [f64; 3],
|
||||
body_yaw: f32,
|
||||
fall_flying_scale: f32,
|
||||
) -> [f32; 3] {
|
||||
let d: [f64; 3] = std::array::from_fn(|i| {
|
||||
lerp_d(f64::from(partial), self.cloak_o[i], self.cloak[i]) - position[i]
|
||||
});
|
||||
let rad = f64::from(body_yaw * DEG_TO_RAD);
|
||||
let (sin, cos) = (f64::from(trig::sin(rad)), f64::from(-trig::cos(rad)));
|
||||
let mut flap = (d[1] as f32 * 10.0).clamp(-6.0, 32.0);
|
||||
let lean = ((d[0] * sin + d[2] * cos) as f32 * 100.0 * (1.0 - fall_flying_scale))
|
||||
.clamp(0.0, 150.0);
|
||||
let lean2 = ((d[0] * cos - d[2] * sin) as f32 * 100.0).clamp(-20.0, 20.0);
|
||||
let bob = self.interpolated_bob(partial);
|
||||
let walk = lerp(partial, self.walk_dist_o, self.walk_dist);
|
||||
flap += trig::sin(f64::from(walk * 6.0)) * 32.0 * bob;
|
||||
[flap, lean, lean2]
|
||||
}
|
||||
/// `LocalPlayer.move`: `addWalkedDistance(Mth.length(dx, dz) * 0.6F)`
|
||||
/// with the float horizontal displacement.
|
||||
@@ -795,6 +834,23 @@ pub fn spinning_effect_matrix(intensity: f32, angle_degrees: f32) -> glam::Mat4
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// `moveCloak` trails a quarter of the way, jumps from 10 blocks away; the
|
||||
/// cape leans back as the player walks forward (south, body yaw 0).
|
||||
#[test]
|
||||
fn the_cloak_trails_the_player() {
|
||||
let mut a = super::AvatarBob::default();
|
||||
a.tick([0.0, 64.0, 0.0]);
|
||||
assert_eq!((a.cloak, a.cloak_o), ([0.0, 64.0, 0.0], [0.0, 64.0, 0.0]));
|
||||
a.tick([0.0, 64.0, 1.0]);
|
||||
assert_eq!(a.cloak, [0.0, 64.0, 0.25]);
|
||||
let [flap, lean, lean2] = a.cape(1.0, [0.0, 64.0, 1.0], 0.0, 0.0);
|
||||
assert_eq!((flap, lean, lean2), (0.0, 75.0, 0.0));
|
||||
// Falling lifts the flap, at most 32 degrees.
|
||||
assert_eq!(a.cape(1.0, [0.0, 60.0, 0.25], 0.0, 0.0)[0], 32.0);
|
||||
// Gliding takes the lean away.
|
||||
assert_eq!(a.cape(1.0, [0.0, 64.0, 1.0], 0.0, 1.0)[1], 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depth_far_covers_the_cloud_range() {
|
||||
// renderDistance 2 with the default Cloud Distance (128 chunks).
|
||||
|
||||
@@ -42,6 +42,45 @@ pub fn recipe_used_key(id: &str) -> String {
|
||||
/// A hopper's slots: the only plain container with five.
|
||||
pub const HOPPER_SLOTS: usize = 5;
|
||||
|
||||
/// `getDefaultName` of the `BaseContainerBlockEntity` that `block` holds: the
|
||||
/// translation key of its menu's title when it has no custom name. Copper
|
||||
/// chests hold a `ChestBlockEntity`, shulker boxes of every colour a
|
||||
/// `ShulkerBoxBlockEntity`.
|
||||
pub fn default_name_key(block: &str) -> Option<&'static str> {
|
||||
Some(match block {
|
||||
"minecraft:chest" | "minecraft:trapped_chest" => "container.chest",
|
||||
n if n.ends_with("copper_chest") => "container.chest",
|
||||
"minecraft:barrel" => "container.barrel",
|
||||
n if n.ends_with("shulker_box") => "container.shulkerBox",
|
||||
"minecraft:dispenser" => "container.dispenser",
|
||||
"minecraft:dropper" => "container.dropper",
|
||||
"minecraft:hopper" => "container.hopper",
|
||||
"minecraft:furnace" => "container.furnace",
|
||||
"minecraft:smoker" => "container.smoker",
|
||||
"minecraft:blast_furnace" => "container.blast_furnace",
|
||||
"minecraft:brewing_stand" => "container.brewing",
|
||||
"minecraft:crafter" => "container.crafter",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `BaseContainerBlockEntity.getDisplayName` (`getName`), the title of the
|
||||
/// `ClientboundOpenScreenPacket` that opens it: the block entity's custom
|
||||
/// name (`CustomName`, a literal), else its default name.
|
||||
pub fn display_name(custom: Option<&str>, default_key: &str) -> horizon_world::nbt::Tag {
|
||||
match custom {
|
||||
Some(name) => horizon_protocol::text::literal(name),
|
||||
None => horizon_protocol::text::translatable(default_key, &[]),
|
||||
}
|
||||
}
|
||||
|
||||
/// `ChestBlock.MENU_PROVIDER_COMBINER`'s `getDisplayName` for a double chest:
|
||||
/// the first half's custom name (the right half, `DoubleBlockCombiner`'s
|
||||
/// `FIRST`), else the second's, else `container.chestDouble`.
|
||||
pub fn double_chest_name(first: Option<&str>, second: Option<&str>) -> horizon_world::nbt::Tag {
|
||||
display_name(first.or(second), "container.chestDouble")
|
||||
}
|
||||
|
||||
impl Campfire {
|
||||
/// `placeFood`'s slot: the first empty one, given the item's
|
||||
/// `campfire_cooking` time; it takes one item of `held`.
|
||||
@@ -378,6 +417,58 @@ impl BlockEntity {
|
||||
}
|
||||
pub use crate::providers::Providers;
|
||||
|
||||
/// A `ChestBlock`, which `ChestBlock.combine` can join into a double chest:
|
||||
/// chests, trapped chests and copper chests in every weathering state, waxed
|
||||
/// or not (`CopperChestBlock` extends `ChestBlock`). Ender chests are
|
||||
/// `EnderChestBlock`s and always single.
|
||||
pub fn is_chest_block(name: &str) -> bool {
|
||||
matches!(name, "minecraft:chest" | "minecraft:trapped_chest") || name.ends_with("copper_chest")
|
||||
}
|
||||
|
||||
/// A chest block's name with its `type` and `facing` properties.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct ChestHalf<'a> {
|
||||
pub block: &'a str,
|
||||
pub kind: &'a str,
|
||||
pub facing: &'a str,
|
||||
}
|
||||
|
||||
impl ChestHalf<'_> {
|
||||
/// `ChestBlock.getConnectedDirection` as an (x, z) step to the other
|
||||
/// half: clockwise from the facing for a left half, counter-clockwise for
|
||||
/// a right one. None for a single chest.
|
||||
pub fn connected_step(&self) -> Option<(i32, i32)> {
|
||||
let step = |facing: &str| match facing {
|
||||
"north" => Some((0, -1)),
|
||||
"south" => Some((0, 1)),
|
||||
"west" => Some((-1, 0)),
|
||||
"east" => Some((1, 0)),
|
||||
_ => None,
|
||||
};
|
||||
let (x, z) = step(self.facing)?;
|
||||
// Turning clockwise seen from above takes (x, z) to (-z, x).
|
||||
match self.kind {
|
||||
"left" => Some((-z, x)),
|
||||
"right" => Some((z, -x)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `DoubleBlockCombiner.combineWithNeigbour` as `ChestBlock.combine` calls
|
||||
/// it: `other`, the block in this half's connected direction, is its other
|
||||
/// half when it is the same block, a half of the other side and faces the
|
||||
/// same way. Copper chests in different weathering states never join
|
||||
/// (`CopperChestBlock` keeps both halves in one state instead).
|
||||
pub fn pairs_with(&self, other: &ChestHalf) -> bool {
|
||||
is_chest_block(self.block)
|
||||
&& self.kind != "single"
|
||||
&& other.block == self.block
|
||||
&& other.kind != "single"
|
||||
&& other.kind != self.kind
|
||||
&& other.facing == self.facing
|
||||
}
|
||||
}
|
||||
|
||||
/// `AbstractFurnaceBlockEntity.createExperience`: `count * experience`, floored, and one
|
||||
/// more with the chance of what is left over (a level random draw only when there is some).
|
||||
pub fn create_experience(
|
||||
|
||||
@@ -22,6 +22,7 @@ struct Globals {
|
||||
outline_params: vec4<f32>,
|
||||
// Horizon Extras' dynamic lights: camera-relative position and level (dynamic_light.rs).
|
||||
dynamic_lights: array<vec4<f32>, 16>,
|
||||
sunrise_fan: array<vec4<f32>, 32>,
|
||||
}
|
||||
@group(0) @binding(0) var<uniform> globals: Globals;
|
||||
@group(0) @binding(1) var atlas: texture_2d<f32>;
|
||||
|
||||
@@ -379,6 +379,22 @@ pub fn setup_fog(tables: &FogTables, state: &FogState, input: &FogInputs) -> Fog
|
||||
}
|
||||
fog
|
||||
}
|
||||
/// Horizon's Fog option turned off (`horizon-graphics.txt` `fog:false`):
|
||||
/// no distance fog, in any dimension: the dimension's and biome's own fog
|
||||
/// (`visual/fog_start_distance`, `fog_end_distance`: the Nether's ends at 96
|
||||
/// blocks) and the render-distance fog. The fog of the fluid or powder snow
|
||||
/// the camera is in, blindness, darkness and a boss's world fog keep their
|
||||
/// limits. Vanilla has no such option.
|
||||
pub fn clear_distance_fog(fog: &mut FogData, input: &FogInputs) {
|
||||
if input.fog_type == FogType::Atmospheric
|
||||
&& input.darkness.is_none()
|
||||
&& !input.boss_world_fog
|
||||
&& input.blindness.is_none()
|
||||
{
|
||||
(fog.render_distance_start, fog.render_distance_end) = (1e9, 2e9);
|
||||
(fog.environmental_start, fog.environmental_end) = (1e9, 2e9);
|
||||
}
|
||||
}
|
||||
/// `AtmosphericFogEnvironment.updateRainFogState`.
|
||||
pub fn update_rain_fog(
|
||||
state: &mut FogState,
|
||||
@@ -452,6 +468,56 @@ mod tests {
|
||||
assert_eq!(water.environmental_start, -8.0);
|
||||
}
|
||||
#[test]
|
||||
fn fog_off_clears_the_nether_fog_too() {
|
||||
// The Nether's visual/fog_start_distance and fog_end_distance (10, 96)
|
||||
// end before the render distance; the Fog option still clears them.
|
||||
let nether = Sky {
|
||||
fog_start: 10.0,
|
||||
fog_end: 96.0,
|
||||
..Sky::default()
|
||||
};
|
||||
let tables = FogTables {
|
||||
water_fog_end: vec![1.0],
|
||||
};
|
||||
let mut input = inputs(&nether);
|
||||
input.skybox = false;
|
||||
let mut fog = setup_fog(&tables, &FogState::default(), &input);
|
||||
assert_eq!(fog.environmental_end, 96.0);
|
||||
clear_distance_fog(&mut fog, &input);
|
||||
assert!(fog.environmental_start >= 1e9 && fog.render_distance_start >= 1e9);
|
||||
}
|
||||
#[test]
|
||||
fn fog_off_keeps_fluid_and_effect_fog() {
|
||||
let sky = Sky {
|
||||
fog_start: 10.0,
|
||||
fog_end: 96.0,
|
||||
..Sky::default()
|
||||
};
|
||||
let tables = FogTables {
|
||||
water_fog_end: vec![1.0],
|
||||
};
|
||||
let kept = |input: &FogInputs| {
|
||||
let mut fog = setup_fog(&tables, &FogState::default(), input);
|
||||
let before = fog;
|
||||
clear_distance_fog(&mut fog, input);
|
||||
fog == before
|
||||
};
|
||||
for fog_type in [FogType::Lava, FogType::PowderSnow, FogType::Water] {
|
||||
let mut input = inputs(&sky);
|
||||
input.fog_type = fog_type;
|
||||
assert!(kept(&input), "{fog_type:?}");
|
||||
}
|
||||
let mut input = inputs(&sky);
|
||||
input.blindness = Some((100, false));
|
||||
assert!(kept(&input));
|
||||
let mut input = inputs(&sky);
|
||||
input.darkness = Some(0.5);
|
||||
assert!(kept(&input));
|
||||
let mut input = inputs(&sky);
|
||||
input.boss_world_fog = true;
|
||||
assert!(kept(&input));
|
||||
}
|
||||
#[test]
|
||||
fn boss_darkening_dims_fog_color() {
|
||||
// FogRenderer.computeFogColor: lerp toward 70/60/60% of each channel.
|
||||
let sky = Sky {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
//! offsets), styled drawing and StringSplitter-style line wrapping.
|
||||
use crate::{
|
||||
hud::Rect,
|
||||
text::{Style, Text},
|
||||
text::{Span, Style, Text, legacy_format},
|
||||
zip::Zip,
|
||||
};
|
||||
use ab_glyph::{Font as _, ScaleFont as _};
|
||||
@@ -966,6 +966,83 @@ impl Font {
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `Font.split`: `StringSplitter.splitLines(text, width, Style.EMPTY)` over
|
||||
/// the text's parts with their `§` codes in. A code styles what follows
|
||||
/// (`§r` back to no style while measuring), and the part a line breaks in
|
||||
/// goes on in the style at the break. Lines keep their codes for drawing.
|
||||
pub fn split_formatted(&self, t: &Text, max_width: f32) -> Vec<Text> {
|
||||
let max_width = max_width.max(1.0);
|
||||
let mut parts: Vec<(Vec<char>, Style)> = t
|
||||
.spans
|
||||
.iter()
|
||||
.filter(|s| !s.text.is_empty())
|
||||
.map(|s| (s.text.chars().collect(), s.style.clone()))
|
||||
.collect();
|
||||
let mut flat: Vec<char> = parts.iter().flat_map(|p| p.0.iter().copied()).collect();
|
||||
let mut out = Vec::new();
|
||||
let mut force_new_line = false;
|
||||
// One LineBreakFinder per line, over the parts left.
|
||||
while let Some((at, split_style)) = self.line_break(&parts, max_width) {
|
||||
let tail = flat[at];
|
||||
let new_line = tail == '\n';
|
||||
let skip = usize::from(new_line || tail == ' ');
|
||||
force_new_line = new_line;
|
||||
out.push(split_at(&mut parts, at, skip, &split_style));
|
||||
flat.drain(..at + skip);
|
||||
}
|
||||
if !parts.is_empty() {
|
||||
let mut rest = Text::default();
|
||||
rest.spans = parts
|
||||
.into_iter()
|
||||
.map(|(text, style)| Span {
|
||||
text: text.into_iter().collect(),
|
||||
style,
|
||||
})
|
||||
.collect();
|
||||
out.push(rest);
|
||||
} else if force_new_line {
|
||||
out.push(Text::empty());
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `StringSplitter.LineBreakFinder` fed by `StringDecomposer.iterateFormatted`:
|
||||
/// where the parts break (a character index) and the style there.
|
||||
fn line_break(&self, parts: &[(Vec<char>, Style)], max_width: f32) -> Option<(usize, Style)> {
|
||||
let (mut width, mut had_visible, mut last_space) = (0.0f32, false, None);
|
||||
let mut offset = 0;
|
||||
for (contents, part_style) in parts {
|
||||
let mut style = part_style.clone();
|
||||
let mut i = 0;
|
||||
while i < contents.len() {
|
||||
let c = contents[i];
|
||||
if c == '§' {
|
||||
// A `§` that ends its part ends only that part.
|
||||
let Some(&code) = contents.get(i + 1) else {
|
||||
break;
|
||||
};
|
||||
style = legacy_format(&style, code, &Style::default());
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
let at = offset + i;
|
||||
if c == '\n' {
|
||||
return Some((at, style));
|
||||
}
|
||||
if c == ' ' {
|
||||
last_space = Some((at, style.clone()));
|
||||
}
|
||||
let advance = self.advance(c, &style);
|
||||
width += advance;
|
||||
if had_visible && width > max_width {
|
||||
return Some(last_space.unwrap_or((at, style)));
|
||||
}
|
||||
had_visible |= advance != 0.0;
|
||||
i += 1;
|
||||
}
|
||||
offset += contents.len();
|
||||
}
|
||||
None
|
||||
}
|
||||
/// `ComponentRenderUtils.wrapComponents`: the split lines, wrapped ones
|
||||
/// indented by an unstyled space; one empty line for empty text.
|
||||
pub fn wrap_components(&self, t: &Text, max_width: i32) -> Vec<Text> {
|
||||
@@ -1059,6 +1136,47 @@ impl Font {
|
||||
}
|
||||
}
|
||||
|
||||
/// `StringSplitter.FlatComponents.splitAt`: the parts before `at` as a line,
|
||||
/// `skip` characters dropped, and the part it ends in restyled as `style`.
|
||||
fn split_at(parts: &mut Vec<(Vec<char>, Style)>, at: usize, skip: usize, style: &Style) -> Text {
|
||||
let mut line = Text::default();
|
||||
let mut push = |text: &[char], style: &Style| {
|
||||
line.spans.push(Span {
|
||||
text: text.iter().collect(),
|
||||
style: style.clone(),
|
||||
})
|
||||
};
|
||||
// Each part done is removed, so the one at hand is always the first.
|
||||
let (mut position, mut in_skip) = (at, false);
|
||||
while let Some((text, part_style)) = parts.first() {
|
||||
let size = text.len();
|
||||
if !in_skip {
|
||||
if position > size {
|
||||
push(text, part_style);
|
||||
parts.remove(0);
|
||||
position -= size;
|
||||
continue;
|
||||
}
|
||||
if position > 0 {
|
||||
push(&text[..position], part_style);
|
||||
}
|
||||
position += skip;
|
||||
in_skip = true;
|
||||
}
|
||||
if position <= size {
|
||||
if position == size {
|
||||
parts.remove(0);
|
||||
} else {
|
||||
parts[0] = (text[position..].to_vec(), style.clone());
|
||||
}
|
||||
break;
|
||||
}
|
||||
parts.remove(0);
|
||||
position -= size;
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -1221,6 +1339,37 @@ mod tests {
|
||||
assert!(!font.take_patches().is_empty());
|
||||
}
|
||||
|
||||
/// StringDecomposer.iterateFormatted: a `§` that ends a part stops that
|
||||
/// part only; the next part is still measured and can break.
|
||||
#[test]
|
||||
fn a_section_sign_ending_a_part_still_breaks_the_next() {
|
||||
let sheet = png(16, 8, |x, _| x < 2);
|
||||
let default = br#"{"providers":[{"type":"space","advances":{" ":4}},{"type":"bitmap","file":"minecraft:font/a.png","ascent":7,"chars":["ab"]}]}"#;
|
||||
let root = root(
|
||||
"section-sign",
|
||||
&[
|
||||
("assets/minecraft/font/default.json", default),
|
||||
("assets/minecraft/textures/font/a.png", &sheet),
|
||||
],
|
||||
);
|
||||
let font = load(&root);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let mut text = Text::default();
|
||||
text.spans = ["a§", "a a"]
|
||||
.map(|part| Span {
|
||||
text: part.into(),
|
||||
style: Style::default(),
|
||||
})
|
||||
.into();
|
||||
// 3 + 3 + 4 + 3 is past 12: the line breaks at the space.
|
||||
let lines: Vec<String> = font
|
||||
.split_formatted(&text, 12.0)
|
||||
.iter()
|
||||
.map(Text::plain)
|
||||
.collect();
|
||||
assert_eq!(lines, ["a§a", "a"]);
|
||||
}
|
||||
|
||||
/// A renderer rebuilt over the same font (the loading screen's handoff)
|
||||
/// makes its atlas texture from the textures alone, so the glyphs it had
|
||||
/// rasterized into the previous texture must be placed into the new one.
|
||||
|
||||
@@ -39,8 +39,9 @@ mod entity_outline;
|
||||
mod weather;
|
||||
use entity_batch::EntityBatch;
|
||||
pub use entity_batch::{
|
||||
ENERGY_SWIRL_OVERLAY, SHADOW_OVERLAY, TRANSLUCENT_GLINT_ITEM_OVERLAY, TRANSLUCENT_ITEM_OVERLAY,
|
||||
TRANSLUCENT_PARTICLE_OVERLAY, WATER_MASK_OVERLAY,
|
||||
ENERGY_SWIRL_OVERLAY, SHADOW_OVERLAY, TEXT_POLYGON_OFFSET_OVERLAY,
|
||||
TRANSLUCENT_GLINT_ITEM_OVERLAY, TRANSLUCENT_ITEM_OVERLAY, TRANSLUCENT_PARTICLE_OVERLAY,
|
||||
WATER_MASK_OVERLAY,
|
||||
};
|
||||
|
||||
/// Window.getAppropriateLineWidth, in framebuffer pixels.
|
||||
@@ -93,6 +94,7 @@ mod page_runs;
|
||||
pub mod panorama;
|
||||
mod resident;
|
||||
mod stars;
|
||||
mod sunrise_fan;
|
||||
mod timing;
|
||||
pub mod translucency;
|
||||
pub(crate) mod upload;
|
||||
@@ -188,6 +190,8 @@ struct Globals {
|
||||
outline_params: [f32; 4],
|
||||
/// Horizon Extras' dynamic lights: camera-relative position and level (`dynamic_light`).
|
||||
dynamic_lights: [[f32; 4]; crate::dynamic_light::MAX],
|
||||
/// The sunrise fan's triangles as the sky shader tests them (`sunrise_fan::normals`).
|
||||
sunrise_fan: [[f32; 4]; 2 * sunrise_fan::TRIANGLES],
|
||||
}
|
||||
pub type SectionKey = (i32, i32, i32);
|
||||
struct SectionGpu {
|
||||
@@ -425,6 +429,7 @@ pub struct Renderer {
|
||||
lightning_pipeline: wgpu::RenderPipeline,
|
||||
lightning: lightning::Renderer,
|
||||
see_through_pipeline: wgpu::RenderPipeline,
|
||||
text_polygon_offset_pipeline: wgpu::RenderPipeline,
|
||||
celestial_pipeline: wgpu::RenderPipeline,
|
||||
celestial_buffer: wgpu::Buffer,
|
||||
end_sky: end_sky::EndSky,
|
||||
@@ -533,7 +538,7 @@ pub struct Renderer {
|
||||
block_entity_revision: u64,
|
||||
/// VisGraph face connectivity per meshed section (cave culling).
|
||||
occlusion: occlusion::Occlusion,
|
||||
/// Resolution scale and FXAA (Horizon settings).
|
||||
/// Resolution scale, FXAA and TAA (Horizon settings).
|
||||
world_post: world_post::Post,
|
||||
/// HDR output (Horizon setting): `Some` while the swapchain is HDR.
|
||||
hdr: Option<hdr::Hdr>,
|
||||
@@ -874,6 +879,14 @@ fn check_layers(limits: &wgpu::Limits, layers: u32) -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Whether the swapchain can take a window of `width` x `height`: each side from 1 to the
|
||||
/// device's `max_texture_dimension_2d` (`max`), else `Surface::configure` panics. 0 is a
|
||||
/// minimized window. Past `max`: Windows lets a program size a window up to 65535 pixels
|
||||
/// (`SetWindowPos`), a 984x65496 client area, when an RTX 5080 takes 32768. Vanilla's
|
||||
/// `Window.onFramebufferResize` likewise keeps the last size for one that is not positive.
|
||||
fn drawable_size(width: u32, height: u32, max: u32) -> bool {
|
||||
(1..=max).contains(&width) && (1..=max).contains(&height)
|
||||
}
|
||||
/// The swapchain format: a non-sRGB target, because vanilla blends and tints in gamma
|
||||
/// space, and 8-bit, because wgpu gives `Rgba16Float` the linear `ExtendedSrgb` color
|
||||
/// space: the compositor would read these gamma-encoded values as linear light and wash
|
||||
@@ -1121,9 +1134,14 @@ impl Renderer {
|
||||
let info = adapter.get_info();
|
||||
crate::graphics::suggest_reduced_far_detail(crate::graphics::lod_capped(&info));
|
||||
let size = window.inner_size();
|
||||
let max_side = device.limits().max_texture_dimension_2d;
|
||||
let (config, present_modes, hdr_output) = if let Some(surface) = &surface {
|
||||
let mut config = surface
|
||||
.get_default_config(&adapter, size.width.max(1), size.height.max(1))
|
||||
.get_default_config(
|
||||
&adapter,
|
||||
size.width.clamp(1, max_side),
|
||||
size.height.clamp(1, max_side),
|
||||
)
|
||||
.ok_or("surface has no supported configuration")?;
|
||||
let caps = surface.get_capabilities(&adapter);
|
||||
config.format = surface_format(&caps.formats, config.format);
|
||||
@@ -1149,14 +1167,21 @@ impl Renderer {
|
||||
));
|
||||
}
|
||||
surface.configure(&device, &config);
|
||||
(config, caps.present_modes.clone(), hdr::output(&caps))
|
||||
let hdr_output = hdr::output(&caps);
|
||||
if previous.is_none() {
|
||||
log::info!(
|
||||
"Horizon renderer: HDR output {}",
|
||||
hdr_output.map_or("not offered by this display", hdr::Output::name)
|
||||
);
|
||||
}
|
||||
(config, caps.present_modes.clone(), hdr_output)
|
||||
} else {
|
||||
let format = wgpu::TextureFormat::Bgra8Unorm;
|
||||
let config = wgpu::SurfaceConfiguration {
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
|
||||
format,
|
||||
width: size.width.max(1),
|
||||
height: size.height.max(1),
|
||||
width: size.width.clamp(1, max_side),
|
||||
height: size.height.clamp(1, max_side),
|
||||
present_mode: wgpu::PresentMode::Immediate,
|
||||
desired_maximum_frame_latency: 2,
|
||||
alpha_mode: wgpu::CompositeAlphaMode::Opaque,
|
||||
@@ -2037,6 +2062,21 @@ impl Renderer {
|
||||
alpha_blend,
|
||||
false,
|
||||
);
|
||||
// RenderPipelines.TEXT_POLYGON_OFFSET: a text display's text and
|
||||
// background win against the surface they lie on (bias 1, 10).
|
||||
let text_polygon_offset_pipeline = entity_pipeline(
|
||||
"Polygon offset text",
|
||||
None,
|
||||
true,
|
||||
wgpu::CompareFunction::GreaterEqual,
|
||||
wgpu::DepthBiasState {
|
||||
constant: 10,
|
||||
slope_scale: 1.0,
|
||||
clamp: 0.0,
|
||||
},
|
||||
alpha_blend,
|
||||
false,
|
||||
);
|
||||
let entity_pipeline = entity_pipeline(
|
||||
"Entities",
|
||||
None,
|
||||
@@ -2594,6 +2634,7 @@ impl Renderer {
|
||||
lightning_pipeline,
|
||||
lightning: lightning::Renderer::new(),
|
||||
see_through_pipeline,
|
||||
text_polygon_offset_pipeline,
|
||||
celestial_pipeline,
|
||||
celestial_buffer,
|
||||
end_sky: end_sky::EndSky::default(),
|
||||
@@ -2682,7 +2723,7 @@ impl Renderer {
|
||||
hud,
|
||||
menu_blur: None,
|
||||
info,
|
||||
suspended: size.width == 0 || size.height == 0,
|
||||
suspended: !drawable_size(size.width, size.height, max_side),
|
||||
drawn_sections: 0,
|
||||
section_draws: 0,
|
||||
section_draw_calls: 0,
|
||||
@@ -2842,8 +2883,11 @@ impl Renderer {
|
||||
);
|
||||
}
|
||||
}
|
||||
/// Follows the window to `width` x `height`. A size the swapchain can't take
|
||||
/// ([`drawable_size`]) keeps the last one and draws nothing until the next.
|
||||
pub fn resize(&mut self, width: u32, height: u32) {
|
||||
self.suspended = width == 0 || height == 0;
|
||||
let max = self.device.limits().max_texture_dimension_2d;
|
||||
self.suspended = !drawable_size(width, height, max);
|
||||
if self.suspended {
|
||||
return;
|
||||
}
|
||||
@@ -3227,6 +3271,19 @@ impl Renderer {
|
||||
}
|
||||
config
|
||||
}
|
||||
/// The F3 screen's HDR line while the setting is on: the swapchain HDR presents to with
|
||||
/// its paper white and peak, or that the surface offers none.
|
||||
pub fn hdr_line(&self) -> String {
|
||||
match &self.hdr {
|
||||
Some(hdr) => format!(
|
||||
"HDR: {}, {}/{} nits",
|
||||
hdr.output.name(),
|
||||
hdr.paper_white.round(),
|
||||
hdr.peak.round()
|
||||
),
|
||||
None => "HDR: not offered by this display".into(),
|
||||
}
|
||||
}
|
||||
/// HDR output (Horizon setting): HDR10 or scRGB at `paper_white` nits, the world's
|
||||
/// highlights expanded up to `peak` nits. Off where the surface can't present it.
|
||||
pub fn set_hdr(&mut self, on: bool, paper_white: f32, peak: f32, marker: &std::path::Path) {
|
||||
@@ -3243,6 +3300,14 @@ impl Renderer {
|
||||
let format = self.config.format.remove_srgb_suffix();
|
||||
self.hdr = output.map(|output| hdr::Hdr::new(&self.device, format, output));
|
||||
self.configure_surface();
|
||||
match output {
|
||||
Some(output) => log::info!(
|
||||
"Horizon renderer: HDR on: {} ({:?}), {paper_white}/{peak} nits",
|
||||
output.name(),
|
||||
output.format()
|
||||
),
|
||||
None => log::info!("Horizon renderer: HDR off"),
|
||||
}
|
||||
}
|
||||
if let Some(hdr) = &mut self.hdr
|
||||
&& (hdr.paper_white, hdr.peak) != (paper_white, peak)
|
||||
@@ -3252,9 +3317,12 @@ impl Renderer {
|
||||
self.send_hdr_metadata();
|
||||
}
|
||||
}
|
||||
pub fn set_world_post(&mut self, scale: f32, antialias: bool) {
|
||||
/// `upscale`: output pixels per rendered pixel, for TAA to rebuild (1: native).
|
||||
pub fn set_world_post(&mut self, scale: f32, antialias: bool, taa: bool, upscale: f32) {
|
||||
self.world_post.scale = scale.clamp(0.25, 2.0);
|
||||
self.world_post.antialias = antialias;
|
||||
self.world_post.antialias = antialias && !taa;
|
||||
self.world_post.taa = taa;
|
||||
self.world_post.upscale = if taa { upscale.clamp(1.0, 4.0) } else { 1.0 };
|
||||
}
|
||||
/// Runs `post` over the world from now on (`None`: no pack), for the dimension `dimension`;
|
||||
/// `block_ids` gives each block sprite layer's `mc_Entity` (id, fluid) pair.
|
||||
@@ -3636,6 +3704,16 @@ impl Renderer {
|
||||
frame.boss_darken,
|
||||
);
|
||||
let view_proj = self.view_projection(frame);
|
||||
// TAA runs where the world post pass does, not under a shader pack's own.
|
||||
let taa = !frame.title
|
||||
&& self.pack_post.as_ref().is_none_or(|p| p.1.is_none())
|
||||
&& self.native.as_ref().is_none_or(|n| n.post.is_none());
|
||||
let jittered = self.world_post.jitter(
|
||||
[self.config.width, self.config.height],
|
||||
taa,
|
||||
view_proj,
|
||||
frame.camera,
|
||||
) * view_proj;
|
||||
if frame.title {
|
||||
self.panorama.prepare(
|
||||
&self.queue,
|
||||
@@ -3687,7 +3765,7 @@ impl Renderer {
|
||||
)
|
||||
};
|
||||
let globals = Globals {
|
||||
view_proj: view_proj.to_cols_array_2d(),
|
||||
view_proj: jittered.to_cols_array_2d(),
|
||||
fog_color,
|
||||
fog,
|
||||
sky_color: [
|
||||
@@ -3727,6 +3805,7 @@ impl Renderer {
|
||||
}
|
||||
lights
|
||||
},
|
||||
sunrise_fan: sunrise_fan::normals(frame.sky.sunrise_color[3], sun),
|
||||
};
|
||||
self.uploads
|
||||
.buffer(&mut encoder, &self.globals, 0, bytemuck::bytes_of(&globals));
|
||||
@@ -4229,6 +4308,7 @@ impl Renderer {
|
||||
}
|
||||
let [
|
||||
entity_quads,
|
||||
text_quads,
|
||||
crumbling_quads,
|
||||
translucent_crumbling_quads,
|
||||
water_mask_quads,
|
||||
@@ -4241,6 +4321,7 @@ impl Renderer {
|
||||
.update(entities, frame.additive, frame.hand, frame.see_through);
|
||||
let weather_quads = frame.weather.len() as u32 / 4;
|
||||
let world_quads = entity_quads
|
||||
+ text_quads
|
||||
+ crumbling_quads
|
||||
+ translucent_crumbling_quads
|
||||
+ water_mask_quads
|
||||
@@ -4319,7 +4400,7 @@ impl Renderer {
|
||||
self.stars.prepare(
|
||||
&mut self.uploads,
|
||||
&mut encoder,
|
||||
view_proj * rotation,
|
||||
jittered * rotation,
|
||||
brightness,
|
||||
);
|
||||
}
|
||||
@@ -4492,6 +4573,8 @@ impl Renderer {
|
||||
.flatten();
|
||||
}
|
||||
let pack_reads_world = pack_post || native_post;
|
||||
// Phase 2 of occlusion culling draws over the depth, and a shader pack or TAA reads it.
|
||||
let keep_depth = pack_reads_world || (taa && self.world_post.taa);
|
||||
// The pack's program reads the vertices this frame's draws bind.
|
||||
let pack_draws_terrain = pack_terrain && flat_frame == self.pack_terrain_flat;
|
||||
// The shadow camera's lists, drawn by the pack's shadow programs.
|
||||
@@ -4643,8 +4726,7 @@ impl Renderer {
|
||||
view: world_depth,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(0.0),
|
||||
// Phase 2 of occlusion culling draws over it; a shader pack reads it.
|
||||
store: if cull.is_some() || pack_reads_world {
|
||||
store: if cull.is_some() || keep_depth {
|
||||
wgpu::StoreOp::Store
|
||||
} else {
|
||||
wgpu::StoreOp::Discard
|
||||
@@ -4719,7 +4801,7 @@ impl Renderer {
|
||||
&mut encoder,
|
||||
world_view,
|
||||
world_depth,
|
||||
pack_reads_world,
|
||||
keep_depth,
|
||||
);
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
pack_frame(&mut pass);
|
||||
@@ -4749,7 +4831,7 @@ impl Renderer {
|
||||
&mut encoder,
|
||||
world_view,
|
||||
world_depth,
|
||||
pack_reads_world,
|
||||
keep_depth,
|
||||
);
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
pack_frame(&mut pass);
|
||||
@@ -4778,6 +4860,13 @@ impl Renderer {
|
||||
pass.draw_indexed(0..entity_quads * 6, 0, 0..1);
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
}
|
||||
if text_quads > 0 {
|
||||
pass.set_pipeline(&self.text_polygon_offset_pipeline);
|
||||
pass.set_bind_group(0, &self.entity_group, &[]);
|
||||
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
|
||||
pass.draw_indexed(0..text_quads * 6, (entity_quads * 4) as i32, 0..1);
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
}
|
||||
if translucent_item_quads > 0 {
|
||||
pass.set_pipeline(&self.translucent_item_pipeline);
|
||||
pass.set_bind_group(0, &self.entity_group, &[]);
|
||||
@@ -4797,7 +4886,11 @@ impl Renderer {
|
||||
pass.set_pipeline(&self.crumbling_pipeline);
|
||||
pass.set_bind_group(0, &self.entity_group, &[]);
|
||||
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
|
||||
pass.draw_indexed(0..crumbling_quads * 6, (entity_quads * 4) as i32, 0..1);
|
||||
pass.draw_indexed(
|
||||
0..crumbling_quads * 6,
|
||||
((entity_quads + text_quads) * 4) as i32,
|
||||
0..1,
|
||||
);
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
}
|
||||
if shadow_quads > 0 {
|
||||
@@ -4823,7 +4916,8 @@ impl Renderer {
|
||||
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
|
||||
pass.draw_indexed(
|
||||
0..water_mask_quads * 6,
|
||||
((entity_quads + crumbling_quads + translucent_crumbling_quads) * 4) as i32,
|
||||
((entity_quads + text_quads + crumbling_quads + translucent_crumbling_quads)
|
||||
* 4) as i32,
|
||||
0..1,
|
||||
);
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
@@ -4841,6 +4935,7 @@ impl Renderer {
|
||||
pass.draw_indexed(
|
||||
0..swirl_quads * 6,
|
||||
((entity_quads
|
||||
+ text_quads
|
||||
+ crumbling_quads
|
||||
+ translucent_crumbling_quads
|
||||
+ water_mask_quads)
|
||||
@@ -4934,7 +5029,7 @@ impl Renderer {
|
||||
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
|
||||
pass.draw_indexed(
|
||||
0..translucent_crumbling_quads * 6,
|
||||
((entity_quads + crumbling_quads) * 4) as i32,
|
||||
((entity_quads + text_quads + crumbling_quads) * 4) as i32,
|
||||
0..1,
|
||||
);
|
||||
}
|
||||
@@ -5062,7 +5157,8 @@ impl Renderer {
|
||||
native.timing.as_mut(),
|
||||
);
|
||||
} else if scaled.is_some() {
|
||||
self.world_post.finish(&mut encoder, &view_target);
|
||||
self.world_post
|
||||
.finish(&self.queue, &mut encoder, &view_target);
|
||||
}
|
||||
if let Some(hdr) = &self.hdr {
|
||||
hdr.keep_world(&mut encoder);
|
||||
@@ -5473,6 +5569,23 @@ fn frustum(m: Mat4) -> [Vec4; 6] {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn drawable_size_skips_minimized_and_oversized_windows() {
|
||||
use super::drawable_size;
|
||||
assert!(drawable_size(1280, 720, 8192));
|
||||
assert!(drawable_size(1, 1, 8192));
|
||||
assert!(drawable_size(8192, 8192, 8192));
|
||||
// Minimized.
|
||||
assert!(!drawable_size(0, 720, 8192));
|
||||
assert!(!drawable_size(1280, 0, 8192));
|
||||
assert!(!drawable_size(0, 0, 8192));
|
||||
// One past the device's largest texture.
|
||||
assert!(!drawable_size(8193, 720, 8192));
|
||||
assert!(!drawable_size(1280, 8193, 8192));
|
||||
// The crash: a window `SetWindowPos` made 65535 pixels tall, on an RTX 5080 (32768).
|
||||
assert!(!drawable_size(984, 65496, 32768));
|
||||
assert!(!drawable_size(984, u32::MAX, 32768));
|
||||
}
|
||||
#[test]
|
||||
fn surface_is_8_bit_and_not_srgb() {
|
||||
use super::surface_format;
|
||||
@@ -5537,6 +5650,7 @@ mod tests {
|
||||
(11, 2),
|
||||
(15, 10),
|
||||
(7, 3),
|
||||
(35, 11),
|
||||
(4, 4),
|
||||
(12, 7),
|
||||
]
|
||||
@@ -5546,7 +5660,7 @@ mod tests {
|
||||
let mut batch = super::EntityBatch::default();
|
||||
let counts = batch.update(&entities, &quad(3, 5), &quad(0, 6), &quad(0, 8));
|
||||
let vertices = &batch.combined;
|
||||
assert_eq!(counts, [4, 1, 1, 0, 0, 1, 1, 0]);
|
||||
assert_eq!(counts, [4, 1, 1, 1, 0, 0, 1, 1, 0]);
|
||||
assert_eq!(
|
||||
vertices
|
||||
.as_chunks::<4>()
|
||||
@@ -5554,7 +5668,7 @@ mod tests {
|
||||
.iter()
|
||||
.map(|q| q[0].light)
|
||||
.collect::<Vec<_>>(),
|
||||
[0, 1, 3, 4, 2, 7, 9, 10, 5, 6, 8]
|
||||
[0, 1, 3, 4, 11, 2, 7, 9, 10, 5, 6, 8]
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
|
||||
@@ -103,10 +103,11 @@ impl SpriteAnimator {
|
||||
let mut counts: Vec<usize> = Vec::new();
|
||||
let mut sprites = Vec::with_capacity(animations.len());
|
||||
for animation in animations {
|
||||
let chains: Vec<_> = (0..animation.frame_count())
|
||||
.map(|frame| source_chain(animation.pixels(frame), size, settings, animation.layer))
|
||||
let pixels: Vec<_> = (0..animation.frame_count())
|
||||
.map(|frame| animation.pixels(frame))
|
||||
.collect();
|
||||
let bytes: u64 = chains.iter().map(|(chain, _)| chain.len() as u64).sum();
|
||||
let (chains, edge) = source_chains(&pixels, size, settings, animation.layer);
|
||||
let bytes: u64 = chains.iter().map(|chain| chain.len() as u64).sum();
|
||||
if bytes > limit {
|
||||
log::warn!(
|
||||
"Horizon: layer {}'s animation ({bytes} bytes) does not fit in a storage buffer; it stays still",
|
||||
@@ -124,7 +125,7 @@ impl SpriteAnimator {
|
||||
let data = &mut frames[buffer];
|
||||
let offsets = chains
|
||||
.iter()
|
||||
.map(|(chain, _)| {
|
||||
.map(|chain| {
|
||||
let offset = (data.len() / 4) as u32;
|
||||
data.extend_from_slice(chain);
|
||||
offset
|
||||
@@ -142,7 +143,7 @@ impl SpriteAnimator {
|
||||
shown: None,
|
||||
layer: animation.layer % split,
|
||||
frames: offsets,
|
||||
edge: chains[0].1,
|
||||
edge,
|
||||
group,
|
||||
});
|
||||
}
|
||||
@@ -424,15 +425,63 @@ fn mix_level(frames: &[u8], [_, current, next, millis, edge]: [u32; 5], width: u
|
||||
/// array's size from its own size's chain, its first level repeated into the
|
||||
/// larger levels: that chain, which the shader repeats. Any other sprite: its
|
||||
/// chain at the array's size.
|
||||
#[cfg(test)]
|
||||
fn source_chain(pixels: &[u8], size: u32, settings: &[Settings], layer: u32) -> (Vec<u8>, u32) {
|
||||
let native = settings.get(layer as usize).map_or(0, |s| s.native_size);
|
||||
let edge = if native.is_power_of_two() && native < size {
|
||||
native
|
||||
let (mut chains, edge) = source_chains(&[pixels], size, settings, layer);
|
||||
(chains.swap_remove(0), edge)
|
||||
}
|
||||
|
||||
/// Every frame's chain, laid out as one frame's `source_chain`, but mipmapped as
|
||||
/// vanilla's `SpriteContents.increaseMipLevel` does: over the whole animation
|
||||
/// sheet (the frames stacked), so `solidify` and the alpha-to-coverage scale
|
||||
/// of each level are the sheet's, not each frame's. A frame alone has a
|
||||
/// single texel square at its 2x2 level, and its coverage scale could round
|
||||
/// a whole far frame transparent (kelp blinking out at distance).
|
||||
fn source_chains(
|
||||
frames: &[&[u8]],
|
||||
size: u32,
|
||||
settings: &[Settings],
|
||||
layer: u32,
|
||||
) -> (Vec<Vec<u8>>, u32) {
|
||||
let s = settings.get(layer as usize).copied().unwrap_or_default();
|
||||
let edge = if s.native_size.is_power_of_two() && s.native_size < size {
|
||||
s.native_size
|
||||
} else {
|
||||
size
|
||||
};
|
||||
let frame = crate::sprites::resample(pixels, size, edge);
|
||||
(super::mip_chain(&frame, edge, settings, layer, 1).0, edge)
|
||||
let mut sheet = crate::mipmap::Image {
|
||||
width: edge,
|
||||
height: edge * frames.len() as u32,
|
||||
pixels: Vec::with_capacity((edge * edge) as usize * frames.len()),
|
||||
};
|
||||
for frame in frames {
|
||||
let frame = crate::sprites::resample(frame, size, edge);
|
||||
sheet.pixels.extend_from_slice(frame.as_chunks::<4>().0);
|
||||
}
|
||||
let has_transparent = s.has_transparent || sheet.pixels.iter().any(|p| p[3] == 0);
|
||||
let levels = crate::mipmap::generate(
|
||||
sheet,
|
||||
edge.trailing_zeros(),
|
||||
Settings {
|
||||
has_transparent,
|
||||
..s
|
||||
},
|
||||
);
|
||||
let chains = (0..frames.len())
|
||||
.map(|frame| {
|
||||
let mut chain = Vec::new();
|
||||
for level in &levels {
|
||||
let texels = (level.width * level.width) as usize;
|
||||
chain.extend(
|
||||
level.pixels[frame * texels..(frame + 1) * texels]
|
||||
.iter()
|
||||
.flatten(),
|
||||
);
|
||||
}
|
||||
chain
|
||||
})
|
||||
.collect();
|
||||
(chains, edge)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -572,6 +621,63 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kelp_frames_share_the_sheet_mips() {
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../.local/horizon-client")
|
||||
.join(horizon_core::VANILLA_VERSION);
|
||||
if !root
|
||||
.join("assets/minecraft/textures/block/kelp.png")
|
||||
.exists()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let mut sprites = crate::sprites::Sprites::default();
|
||||
for name in ["kelp", "kelp_plant", "seagrass", "tall_seagrass_top"] {
|
||||
sprites
|
||||
.insert(&root, &format!("minecraft:block/{name}"))
|
||||
.unwrap();
|
||||
}
|
||||
sprites.finish();
|
||||
// A level drawn nowhere: no texel passes the cutout's alpha test.
|
||||
let blank = |chain: &[u8], edge: u32| {
|
||||
let mut start = 0;
|
||||
let mut level = edge;
|
||||
let mut blank = Vec::new();
|
||||
while level > 0 {
|
||||
let bytes = (level * level * 4) as usize;
|
||||
let texels = &chain[start..start + bytes];
|
||||
blank.push(texels.as_chunks::<4>().0.iter().all(|p| p[3] < 128));
|
||||
start += bytes;
|
||||
level >>= 1;
|
||||
}
|
||||
blank
|
||||
};
|
||||
let mut blinked = 0;
|
||||
for animation in &sprites.animations {
|
||||
let size = sprites.size;
|
||||
let pixels: Vec<_> = (0..animation.frame_count())
|
||||
.map(|f| animation.pixels(f))
|
||||
.collect();
|
||||
let (chains, edge) = source_chains(&pixels, size, &sprites.mips, animation.layer);
|
||||
for (frame, chain) in chains.iter().enumerate() {
|
||||
// The 1x1 level has no texel square to measure coverage on
|
||||
// (vanilla leaves it unscaled); every larger level shows.
|
||||
let levels = blank(chain, edge);
|
||||
assert!(
|
||||
!levels[..levels.len() - 1].contains(&true),
|
||||
"layer {} frame {frame}: {levels:?}",
|
||||
animation.layer
|
||||
);
|
||||
let (alone, _) = source_chain(pixels[frame], size, &sprites.mips, animation.layer);
|
||||
let alone = blank(&alone, edge);
|
||||
blinked += usize::from(alone[..alone.len() - 1].contains(&true));
|
||||
}
|
||||
}
|
||||
// Mipmapped frame by frame, some kelp frames vanished at the 2x2 level.
|
||||
assert!(blinked > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rounding_matches_f32_mix_but_for_exact_halves() {
|
||||
// The CPU blend this replaced: f32 mix, then rounded. They differ
|
||||
@@ -730,8 +836,11 @@ mod tests {
|
||||
queue.submit([encoder.finish()]);
|
||||
for animation in &animations {
|
||||
let blend = animation.blend(tick);
|
||||
let chain = |f| source_chain(animation.pixels(f), size, &mips, animation.layer);
|
||||
let ((current, edge), (next, _)) = (chain(blend.frame), chain(blend.next));
|
||||
let pixels: Vec<_> = (0..animation.frame_count())
|
||||
.map(|f| animation.pixels(f))
|
||||
.collect();
|
||||
let (chains, edge) = source_chains(&pixels, size, &mips, animation.layer);
|
||||
let (current, next) = (&chains[blend.frame], &chains[blend.next]);
|
||||
let layers = read_back(
|
||||
&device,
|
||||
&queue,
|
||||
@@ -739,7 +848,7 @@ mod tests {
|
||||
);
|
||||
assert_eq!(
|
||||
layers[(animation.layer % split) as usize],
|
||||
reference(¤t, &next, blend.millis, edge, size),
|
||||
reference(current, next, blend.millis, edge, size),
|
||||
"layer {} at tick {tick}",
|
||||
animation.layer
|
||||
);
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
use super::Vertex;
|
||||
|
||||
/// Entity materials by a quad's overlay (`Vertex::layer`), in draw order:
|
||||
/// ordinary entities, breaking cracks (11), translucent breaking cracks (12),
|
||||
/// the boat water mask (13, `RenderPipelines.WATER_MASK`), energy swirls
|
||||
/// (34, `RenderPipelines.ENERGY_SWIRL`), entity shadows (14,
|
||||
/// ordinary entities, world text drawn with a depth bias (35,
|
||||
/// `RenderPipelines.TEXT_POLYGON_OFFSET`), breaking cracks (11), translucent
|
||||
/// breaking cracks (12), the boat water mask (13, `RenderPipelines.WATER_MASK`),
|
||||
/// energy swirls (34, `RenderPipelines.ENERGY_SWIRL`), entity shadows (14,
|
||||
/// `RenderPipelines.ENTITY_SHADOW`), translucent-layer particles (15, drawn
|
||||
/// after translucent terrain: `SubmitNodeCollection.submitQuadParticleGroup`)
|
||||
/// and translucent item quads (32, drawn without depth writes).
|
||||
const MATERIALS: usize = 8;
|
||||
const MATERIALS: usize = 9;
|
||||
/// The overlay of depth-only quads that hide water (`RenderTypes.waterMask`).
|
||||
pub const WATER_MASK_OVERLAY: u32 = 13;
|
||||
/// The overlay of energy swirl quads (`RenderTypes.energySwirl`: the charged creeper's and the
|
||||
@@ -24,17 +25,21 @@ pub const TRANSLUCENT_PARTICLE_OVERLAY: u32 = 15;
|
||||
pub const TRANSLUCENT_ITEM_OVERLAY: u32 = 32;
|
||||
/// A translucent item with an enchantment glint.
|
||||
pub const TRANSLUCENT_GLINT_ITEM_OVERLAY: u32 = 33;
|
||||
/// The overlay of text in `Font.DisplayMode.POLYGON_OFFSET` (text displays):
|
||||
/// drawn like an ordinary entity, pulled toward the camera.
|
||||
pub const TEXT_POLYGON_OFFSET_OVERLAY: u32 = 35;
|
||||
|
||||
/// The material of a quad by its overlay (`MATERIALS` order).
|
||||
fn material(layer: u32) -> usize {
|
||||
match layer {
|
||||
11 => 1,
|
||||
12 => 2,
|
||||
WATER_MASK_OVERLAY => 3,
|
||||
ENERGY_SWIRL_OVERLAY => 4,
|
||||
SHADOW_OVERLAY => 5,
|
||||
TRANSLUCENT_PARTICLE_OVERLAY => 6,
|
||||
TRANSLUCENT_ITEM_OVERLAY | TRANSLUCENT_GLINT_ITEM_OVERLAY => 7,
|
||||
TEXT_POLYGON_OFFSET_OVERLAY => 1,
|
||||
11 => 2,
|
||||
12 => 3,
|
||||
WATER_MASK_OVERLAY => 4,
|
||||
ENERGY_SWIRL_OVERLAY => 5,
|
||||
SHADOW_OVERLAY => 6,
|
||||
TRANSLUCENT_PARTICLE_OVERLAY => 7,
|
||||
TRANSLUCENT_ITEM_OVERLAY | TRANSLUCENT_GLINT_ITEM_OVERLAY => 8,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
@@ -102,9 +107,10 @@ mod tests {
|
||||
) -> (Vec<Vertex>, [u32; MATERIALS]) {
|
||||
let mut combined = Vec::with_capacity(entities.len() + additive.len() + hand.len());
|
||||
let mut counts = [0; MATERIALS];
|
||||
for (i, layer) in [0, 11, 12, 13, 34, 14, 15].into_iter().enumerate() {
|
||||
for (i, layer) in [0, 35, 11, 12, 13, 34, 14, 15].into_iter().enumerate() {
|
||||
for quad in entities.as_chunks::<4>().0 {
|
||||
let material = match quad[0].layer {
|
||||
35 => 35,
|
||||
11 => 11,
|
||||
12 => 12,
|
||||
13 => 13,
|
||||
@@ -130,7 +136,7 @@ mod tests {
|
||||
pos: [index as f32, 2.0, 3.0],
|
||||
uv: [index as f32, 5.0],
|
||||
layer: if mixed {
|
||||
[7, 11, 14, 12, 4, 13, 15, 0][index / 4 % 8]
|
||||
[7, 11, 14, 35, 12, 4, 13, 15, 0][index / 4 % 9]
|
||||
} else {
|
||||
0
|
||||
},
|
||||
|
||||
@@ -14,6 +14,12 @@ pub enum Output {
|
||||
}
|
||||
|
||||
impl Output {
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Pq => "HDR10 (PQ)",
|
||||
Self::ScRgb => "scRGB",
|
||||
}
|
||||
}
|
||||
pub fn format(self) -> wgpu::TextureFormat {
|
||||
match self {
|
||||
Self::Pq => wgpu::TextureFormat::Rgb10a2Unorm,
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
//! The sunrise/sunset fan (`SkyRenderer.renderSunriseAndSunset`) as the sky
|
||||
//! shader tests it. The fan's 16 triangles depend only on the sunrise alpha
|
||||
//! and the horizon the sun is on, so their vertices are built here once a
|
||||
//! frame instead of in every sky pixel (#3143: with the per-pixel build, four
|
||||
//! `sin`/`cos` per triangle, the sky pass took 10.2 ms at dawn at 1080p on an
|
||||
//! Intel UHD 730 against 0.6 ms by day; now 1.8 ms).
|
||||
//!
|
||||
//! Möller-Trumbore from the camera reduces to triple products: with apex A
|
||||
//! and rim vertices r0, r1, a ray d hits at barycentrics proportional to
|
||||
//! (`[d, r0, r1]`, `[A, d, r1]`, `[A, r0, d]`), each a dot of d with a
|
||||
//! constant normal, and their sum S is the negated determinant. A hit needs
|
||||
//! S on the side of `[A, r0, r1]`, so only the triangles whose rim normals'
|
||||
//! dots change sign there are tested in full.
|
||||
use glam::Vec3;
|
||||
|
||||
pub const TRIANGLES: usize = 16;
|
||||
|
||||
/// Per triangle: xyz `r0 × r1` (its dot with a ray is the apex's weight
|
||||
/// times S), w `[A, r0, r1]` (its sign is S's where the hit lies ahead).
|
||||
/// Then per rim vertex: xyz `r × A`.
|
||||
pub fn normals(alpha: f32, sun: Vec3) -> [[f32; 4]; 2 * TRIANGLES] {
|
||||
let (apex, rim) = vertices(alpha, sun);
|
||||
let mut out = [[0.0; 4]; 2 * TRIANGLES];
|
||||
for i in 0..TRIANGLES {
|
||||
let (r0, r1) = (rim[i], rim[(i + 1) % TRIANGLES]);
|
||||
out[i] = r0.cross(r1).extend(apex.dot(r0.cross(r1))).to_array();
|
||||
out[TRIANGLES + i] = r0.cross(apex).extend(0.0).to_array();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The fan's apex and rim in camera space, as vanilla builds them: the
|
||||
/// fan turned to the horizon the sun sets on (or rises from), its rim
|
||||
/// tilted by the alpha.
|
||||
fn vertices(alpha: f32, sun: Vec3) -> (Vec3, [Vec3; TRIANGLES]) {
|
||||
// sin(sunAngle) < 0 flips the fan to the other horizon; sun.z = -sin(sunAngle).
|
||||
let flip = if -sun.z < 0.0 { 180f32 } else { 0.0 };
|
||||
let (s, c) = (flip + 90.0).to_radians().sin_cos();
|
||||
let rotate_x90 = |v: Vec3| Vec3::new(v.x, -v.z, v.y);
|
||||
let apex = rotate_x90(Vec3::new(-100.0 * s, 100.0 * c, 0.0));
|
||||
let rim = std::array::from_fn(|i| {
|
||||
let a = i as f32 * std::f32::consts::TAU / TRIANGLES as f32;
|
||||
let l = Vec3::new(a.sin() * 120.0, a.cos() * 120.0, -a.cos() * 40.0 * alpha);
|
||||
rotate_x90(Vec3::new(l.x * c - l.y * s, l.x * s + l.y * c, l.z))
|
||||
});
|
||||
(apex, rim)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// terrain.wgsl's `sunrise_weight` over the normals.
|
||||
fn weight(normals: &[[f32; 4]; 2 * TRIANGLES], d: Vec3) -> f32 {
|
||||
let n = |i: usize| Vec3::from_slice(&normals[i][..3]);
|
||||
let mut best = 0.0f32;
|
||||
let mut k0 = d.dot(n(TRIANGLES));
|
||||
for i in 0..TRIANGLES {
|
||||
let k1 = d.dot(n(TRIANGLES + (i + 1) % TRIANGLES));
|
||||
let w = normals[i][3];
|
||||
if k0 * w <= 0.0 && k1 * w >= 0.0 {
|
||||
let apex = d.dot(n(i));
|
||||
let s = apex + k1 - k0;
|
||||
if s.abs() >= 1e-6
|
||||
&& s * w > 0.0
|
||||
&& apex * s >= 0.0
|
||||
&& k1 * s >= 0.0
|
||||
&& k0 * s <= 0.0
|
||||
{
|
||||
best = best.max(apex / s);
|
||||
}
|
||||
}
|
||||
k0 = k1;
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// The shader's former per-pixel Möller-Trumbore over the same vertices.
|
||||
fn reference(alpha: f32, sun: Vec3, d: Vec3) -> f32 {
|
||||
let (apex, rim) = vertices(alpha, sun);
|
||||
let mut best = 0.0f32;
|
||||
for i in 0..TRIANGLES {
|
||||
let e1 = rim[i] - apex;
|
||||
let e2 = rim[(i + 1) % TRIANGLES] - apex;
|
||||
let pv = d.cross(e2);
|
||||
let det = e1.dot(pv);
|
||||
if det.abs() < 1e-6 {
|
||||
continue;
|
||||
}
|
||||
let tv = -apex;
|
||||
let u = tv.dot(pv) / det;
|
||||
let qv = tv.cross(e1);
|
||||
let v = d.dot(qv) / det;
|
||||
let t = e2.dot(qv) / det;
|
||||
if u >= 0.0 && v >= 0.0 && u + v <= 1.0 && t > 0.0 {
|
||||
best = best.max(1.0 - u - v);
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normals_weigh_every_ray_as_the_per_pixel_fan_did() {
|
||||
let mut hits = 0;
|
||||
for (alpha, sun_z) in [(1.0f32, -0.2f32), (0.6, 0.3), (0.05, -0.9), (0.9, 0.05)] {
|
||||
let sun = Vec3::new(0.0, (1.0 - sun_z * sun_z).sqrt(), sun_z);
|
||||
let normals = normals(alpha, sun);
|
||||
for yaw in 0..180 {
|
||||
for pitch in -45..=45 {
|
||||
let (yaw, pitch) = (
|
||||
(yaw as f32 * 2.0).to_radians(),
|
||||
(pitch as f32 * 2.0).to_radians(),
|
||||
);
|
||||
let d = Vec3::new(
|
||||
yaw.cos() * pitch.cos(),
|
||||
pitch.sin(),
|
||||
yaw.sin() * pitch.cos(),
|
||||
);
|
||||
let (got, want) = (weight(&normals, d), reference(alpha, sun, d));
|
||||
assert!(
|
||||
(got - want).abs() < 1e-4,
|
||||
"{alpha} {sun_z} {d}: {got} vs {want}"
|
||||
);
|
||||
hits += usize::from(want > 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The fan covers part of the sky, not none of it.
|
||||
assert!(hits > 1000, "{hits}");
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,44 @@
|
||||
//! Resolution scale and FXAA (Horizon settings): the world renders into its
|
||||
//! Resolution scale, FXAA and TAA (Horizon settings): the world renders into its
|
||||
//! own target at the scaled size, then one full-screen pass copies or
|
||||
//! anti-aliases it onto the screen, under the hand and HUD. With neither on,
|
||||
//! anti-aliases it onto the screen, under the hand and HUD. With none on,
|
||||
//! the world renders straight to the screen.
|
||||
//!
|
||||
//! TAA jitters the world's projection by a sub-pixel offset each frame and blends
|
||||
//! the frame into a history reprojected through the depth buffer: its motion
|
||||
//! vectors are the camera's, so what moves on its own leans on the neighbourhood
|
||||
//! clamp alone.
|
||||
|
||||
use glam::{DMat4, DVec3, Mat4, Vec2};
|
||||
|
||||
/// The TAA history format: 8 bits would band as frames accumulate.
|
||||
const HISTORY_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
|
||||
|
||||
struct WorldTarget {
|
||||
size: [u32; 2],
|
||||
color: wgpu::TextureView,
|
||||
depth: wgpu::TextureView,
|
||||
group: wgpu::BindGroup,
|
||||
taa: Option<History>,
|
||||
}
|
||||
|
||||
/// TAA's two history textures at the output size (the world's, times the upscale), written
|
||||
/// in turn: `resolve[i]` writes `history[i]` from the world and `history[1 - i]`; `show[i]`
|
||||
/// copies `history[i]` to the screen.
|
||||
struct History {
|
||||
size: [u32; 2],
|
||||
history: [wgpu::TextureView; 2],
|
||||
resolve: [wgpu::BindGroup; 2],
|
||||
show: [wgpu::BindGroup; 2],
|
||||
}
|
||||
|
||||
/// `world_post.wgsl`'s `Taa`.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct TaaUniform {
|
||||
/// This frame's unjittered clip space to the previous frame's.
|
||||
reproject: [[f32; 4]; 4],
|
||||
/// xy: this frame's jitter in clip space; z: 1 when the history is unusable.
|
||||
jitter: [f32; 4],
|
||||
}
|
||||
|
||||
pub struct Post {
|
||||
@@ -19,7 +50,21 @@ pub struct Post {
|
||||
/// World resolution relative to the window (0.5..=2.0).
|
||||
pub scale: f32,
|
||||
pub antialias: bool,
|
||||
pub taa: bool,
|
||||
/// Output pixels per rendered pixel while TAA is on (1: native): the world renders
|
||||
/// this much smaller and TAA rebuilds it at the resolution scale's size.
|
||||
pub upscale: f32,
|
||||
/// TAA runs this frame (`jitter`): not on the title screen or under a shader pack.
|
||||
taa_on: bool,
|
||||
target: Option<WorldTarget>,
|
||||
taa_layout: wgpu::BindGroupLayout,
|
||||
taa_pipeline: wgpu::RenderPipeline,
|
||||
taa_uniform: wgpu::Buffer,
|
||||
/// Frames jittered so far (the Halton index), and which history the next resolve writes.
|
||||
taa_frame: u32,
|
||||
/// The last TAA frame's unjittered `view_proj` and camera, `None` once a frame ran without it.
|
||||
taa_previous: Option<(DMat4, DVec3)>,
|
||||
taa_this_frame: TaaUniform,
|
||||
}
|
||||
|
||||
impl Post {
|
||||
@@ -49,15 +94,55 @@ impl Post {
|
||||
},
|
||||
],
|
||||
});
|
||||
let texture = |binding, sample_type| wgpu::BindGroupLayoutEntry {
|
||||
binding,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type,
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
};
|
||||
let float = wgpu::TextureSampleType::Float { filterable: true };
|
||||
let taa_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("Horizon TAA bindings"),
|
||||
entries: &[
|
||||
texture(0, float),
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
texture(2, float),
|
||||
texture(3, wgpu::TextureSampleType::Depth),
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 4,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Horizon post"),
|
||||
bind_group_layouts: &[Some(&layout)],
|
||||
..Default::default()
|
||||
});
|
||||
let pipeline = |entry: &str| {
|
||||
let taa_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Horizon TAA"),
|
||||
bind_group_layouts: &[Some(&taa_layout)],
|
||||
..Default::default()
|
||||
});
|
||||
let pipeline = |entry: &str, layout: &wgpu::PipelineLayout, format| {
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Horizon post"),
|
||||
layout: Some(&pipeline_layout),
|
||||
layout: Some(layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some("vs_post"),
|
||||
@@ -88,41 +173,102 @@ impl Post {
|
||||
..Default::default()
|
||||
});
|
||||
Self {
|
||||
copy: pipeline("fs_copy"),
|
||||
fxaa: pipeline("fs_fxaa"),
|
||||
copy: pipeline("fs_copy", &pipeline_layout, format),
|
||||
fxaa: pipeline("fs_fxaa", &pipeline_layout, format),
|
||||
taa_pipeline: pipeline("fs_taa", &taa_pipeline_layout, HISTORY_FORMAT),
|
||||
taa_uniform: device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Horizon TAA"),
|
||||
size: std::mem::size_of::<TaaUniform>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
}),
|
||||
layout,
|
||||
taa_layout,
|
||||
sampler,
|
||||
format,
|
||||
scale: 1.0,
|
||||
antialias: false,
|
||||
taa: false,
|
||||
upscale: 1.0,
|
||||
taa_on: false,
|
||||
target: None,
|
||||
taa_frame: 0,
|
||||
taa_previous: None,
|
||||
taa_this_frame: bytemuck::Zeroable::zeroed(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The world's rendered size and the size it is shown at (TAA's history).
|
||||
fn sizes(&self, window: [u32; 2]) -> ([u32; 2], [u32; 2]) {
|
||||
let output = window.map(|v| ((v as f32 * self.scale).round() as u32).clamp(1, 8192));
|
||||
let upscale = if self.taa_on { self.upscale } else { 1.0 };
|
||||
(
|
||||
output.map(|v| ((v as f32 / upscale).round() as u32).max(1)),
|
||||
output,
|
||||
)
|
||||
}
|
||||
|
||||
/// TAA's sub-pixel jitter this frame, as a clip-space matrix to multiply into the
|
||||
/// world's projection (identity while `on` is false); `view_proj` is the unjittered
|
||||
/// projection, relative to `camera`. Call it before `prepare`, once per frame.
|
||||
pub fn jitter(&mut self, window: [u32; 2], on: bool, view_proj: Mat4, camera: DVec3) -> Mat4 {
|
||||
self.taa_on = on && self.taa;
|
||||
if !self.taa_on {
|
||||
self.taa_previous = None;
|
||||
return Mat4::IDENTITY;
|
||||
}
|
||||
self.taa_frame = self.taa_frame.wrapping_add(1);
|
||||
let (size, _) = self.sizes(window);
|
||||
// Halton (2, 3) over 8 frames per output pixel (FSR's count), in rendered
|
||||
// pixels around the centre.
|
||||
let phases = (8.0 * self.upscale * self.upscale).ceil() as u32;
|
||||
let i = self.taa_frame % phases + 1;
|
||||
let offset = Vec2::new(halton(i, 2), halton(i, 3)) - 0.5;
|
||||
let jitter = offset * 2.0 / Vec2::new(size[0] as f32, size[1] as f32);
|
||||
let current = view_proj.as_dmat4();
|
||||
let (reproject, reset) = match self.taa_previous {
|
||||
Some((previous, previous_camera)) => (
|
||||
reprojection(previous, previous_camera, current, camera),
|
||||
0.0,
|
||||
),
|
||||
None => (DMat4::IDENTITY, 1.0),
|
||||
};
|
||||
self.taa_previous = Some((current, camera));
|
||||
self.taa_this_frame = TaaUniform {
|
||||
reproject: reproject.as_mat4().to_cols_array_2d(),
|
||||
jitter: [jitter.x, jitter.y, reset, 0.0],
|
||||
};
|
||||
Mat4::from_translation(jitter.extend(0.0))
|
||||
}
|
||||
|
||||
/// The world's colour and depth targets this frame, or `None` to draw
|
||||
/// it straight to the screen.
|
||||
/// `always`: a target even at scale 1 without FXAA (a shader pack reads it).
|
||||
/// `always`: a target even at scale 1 without anti-aliasing (a shader pack reads it).
|
||||
pub fn prepare(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
window: [u32; 2],
|
||||
always: bool,
|
||||
) -> Option<(wgpu::TextureView, wgpu::TextureView)> {
|
||||
if self.scale == 1.0 && !self.antialias && !always {
|
||||
if self.scale == 1.0 && !self.antialias && !self.taa_on && !always {
|
||||
self.target = None;
|
||||
return None;
|
||||
}
|
||||
let size = window.map(|v| ((v as f32 * self.scale).round() as u32).clamp(1, 8192));
|
||||
if self.target.as_ref().is_none_or(|t| t.size != size) {
|
||||
let extent = wgpu::Extent3d {
|
||||
width: size[0],
|
||||
height: size[1],
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
let make_tex = |label, format, usage| {
|
||||
let (size, output) = self.sizes(window);
|
||||
let history_size = self.taa_on.then_some(output);
|
||||
if self
|
||||
.target
|
||||
.as_ref()
|
||||
.is_none_or(|t| t.size != size || t.taa.as_ref().map(|h| h.size) != history_size)
|
||||
{
|
||||
let make_tex = |label, size: [u32; 2], format, usage| {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(label),
|
||||
size: extent,
|
||||
size: wgpu::Extent3d {
|
||||
width: size[0],
|
||||
height: size[1],
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
@@ -131,25 +277,68 @@ impl Post {
|
||||
view_formats: &[],
|
||||
})
|
||||
};
|
||||
let color = make_tex(
|
||||
"Scaled world",
|
||||
self.format,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
)
|
||||
.create_view(&Default::default());
|
||||
// TEXTURE_BINDING: occlusion culling reads it.
|
||||
let sampled =
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING;
|
||||
let color = make_tex("Scaled world", size, self.format, sampled)
|
||||
.create_view(&Default::default());
|
||||
// TEXTURE_BINDING: occlusion culling and TAA read it.
|
||||
let depth = make_tex(
|
||||
"Scaled world depth",
|
||||
size,
|
||||
wgpu::TextureFormat::Depth32Float,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
sampled,
|
||||
)
|
||||
.create_view(&Default::default());
|
||||
let group = self.bind(device, &color);
|
||||
let taa = history_size.map(|output| {
|
||||
let history = [0, 1].map(|_| {
|
||||
make_tex("TAA history", output, HISTORY_FORMAT, sampled)
|
||||
.create_view(&Default::default())
|
||||
});
|
||||
let resolve = [0, 1].map(|i| {
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Horizon TAA"),
|
||||
layout: &self.taa_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(&color),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::Sampler(&self.sampler),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: wgpu::BindingResource::TextureView(&history[1 - i]),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: wgpu::BindingResource::TextureView(&depth),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: self.taa_uniform.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
})
|
||||
});
|
||||
let show = [0, 1].map(|i| self.bind(device, &history[i]));
|
||||
History {
|
||||
size: output,
|
||||
history,
|
||||
resolve,
|
||||
show,
|
||||
}
|
||||
});
|
||||
// New textures: no history yet.
|
||||
self.taa_this_frame.jitter[2] = 1.0;
|
||||
self.target = Some(WorldTarget {
|
||||
size,
|
||||
color,
|
||||
depth,
|
||||
group,
|
||||
taa,
|
||||
});
|
||||
}
|
||||
self.target
|
||||
@@ -180,10 +369,43 @@ impl Post {
|
||||
})
|
||||
}
|
||||
|
||||
/// Draw the scaled world onto `screen`.
|
||||
pub fn finish(&self, encoder: &mut wgpu::CommandEncoder, screen: &wgpu::TextureView) {
|
||||
/// Draw the scaled world onto `screen`, through TAA when this frame's `jitter` had it on.
|
||||
pub fn finish(
|
||||
&self,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
screen: &wgpu::TextureView,
|
||||
) {
|
||||
let Some(target) = &self.target else { return };
|
||||
self.finish_with(encoder, screen, &target.group);
|
||||
let Some(taa) = target.taa.as_ref().filter(|_| self.taa_previous.is_some()) else {
|
||||
self.finish_with(encoder, screen, &target.group);
|
||||
return;
|
||||
};
|
||||
let i = (self.taa_frame % 2) as usize;
|
||||
queue.write_buffer(
|
||||
&self.taa_uniform,
|
||||
0,
|
||||
bytemuck::bytes_of(&self.taa_this_frame),
|
||||
);
|
||||
let attachments = [Some(wgpu::RenderPassColorAttachment {
|
||||
view: &taa.history[i],
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})];
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Horizon TAA"),
|
||||
color_attachments: &attachments,
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_pipeline(&self.taa_pipeline);
|
||||
pass.set_bind_group(0, &taa.resolve[i], &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
drop(pass);
|
||||
self.finish_with(encoder, screen, &taa.show[i]);
|
||||
}
|
||||
|
||||
/// Draw what `group` binds (`bind`) onto `screen`.
|
||||
@@ -216,3 +438,51 @@ impl Post {
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
/// This frame's clip space to the previous frame's, for camera-relative projections:
|
||||
/// a point `camera - previous_camera` further from the previous camera than from this one.
|
||||
fn reprojection(previous: DMat4, previous_camera: DVec3, current: DMat4, camera: DVec3) -> DMat4 {
|
||||
previous * DMat4::from_translation(camera - previous_camera) * current.inverse()
|
||||
}
|
||||
|
||||
/// The radical inverse of `i` in `base`: a low-discrepancy sequence in 0..1.
|
||||
fn halton(mut i: u32, base: u32) -> f32 {
|
||||
let (mut f, mut r) = (1.0, 0.0);
|
||||
while i > 0 {
|
||||
f /= base as f32;
|
||||
r += f * (i % base) as f32;
|
||||
i /= base;
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reprojection_finds_where_a_block_was_last_frame() {
|
||||
let projection = DMat4::perspective_rh(1.2, 16.0 / 9.0, 1024.0, 0.05);
|
||||
let previous = projection * DMat4::from_rotation_y(0.3);
|
||||
let current = projection * DMat4::from_rotation_y(0.35);
|
||||
let (previous_camera, camera) = (DVec3::new(10.0, 64.0, 5.0), DVec3::new(10.5, 64.2, 4.0));
|
||||
let block = DVec3::new(14.0, 66.0, -8.0);
|
||||
let clip = |m: DMat4, eye: DVec3| m * (block - eye).extend(1.0);
|
||||
let now = clip(current, camera);
|
||||
let then = reprojection(previous, previous_camera, current, camera) * (now / now.w);
|
||||
let expected = clip(previous, previous_camera);
|
||||
assert!((then.truncate() / then.w - expected.truncate() / expected.w).length() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jitter_stays_inside_the_pixel() {
|
||||
for i in 1..=8 {
|
||||
let (x, y) = (halton(i, 2), halton(i, 3));
|
||||
assert!((0.0..1.0).contains(&x) && (0.0..1.0).contains(&y));
|
||||
}
|
||||
assert_eq!(
|
||||
[halton(1, 2), halton(2, 2), halton(3, 2)],
|
||||
[0.5, 0.25, 0.75]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -220,6 +220,61 @@ impl FarDetail {
|
||||
}
|
||||
}
|
||||
|
||||
/// TAA upscaling: the world renders this much smaller than the resolution scale's size,
|
||||
/// and TAA builds the full-size picture from the jittered frames (FSR's and DLSS's ratios).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum Upscaling {
|
||||
#[default]
|
||||
Native,
|
||||
Quality,
|
||||
Balanced,
|
||||
Performance,
|
||||
UltraPerformance,
|
||||
}
|
||||
impl Upscaling {
|
||||
pub const ALL: [Upscaling; 5] = [
|
||||
Upscaling::Native,
|
||||
Upscaling::Quality,
|
||||
Upscaling::Balanced,
|
||||
Upscaling::Performance,
|
||||
Upscaling::UltraPerformance,
|
||||
];
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Upscaling::Native => "native",
|
||||
Upscaling::Quality => "quality",
|
||||
Upscaling::Balanced => "balanced",
|
||||
Upscaling::Performance => "performance",
|
||||
Upscaling::UltraPerformance => "ultraPerformance",
|
||||
}
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Upscaling::Native => "Native",
|
||||
Upscaling::Quality => "Quality",
|
||||
Upscaling::Balanced => "Balanced",
|
||||
Upscaling::Performance => "Performance",
|
||||
Upscaling::UltraPerformance => "Ultra Performance",
|
||||
}
|
||||
}
|
||||
/// Output pixels per rendered pixel, along each axis.
|
||||
pub fn ratio(self) -> f32 {
|
||||
match self {
|
||||
Upscaling::Native => 1.0,
|
||||
Upscaling::Quality => 1.5,
|
||||
Upscaling::Balanced => 1.7,
|
||||
Upscaling::Performance => 2.0,
|
||||
Upscaling::UltraPerformance => 3.0,
|
||||
}
|
||||
}
|
||||
fn parse(s: &str) -> Self {
|
||||
Self::ALL
|
||||
.into_iter()
|
||||
.find(|u| u.name() == s)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
static REDUCED_SUGGESTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
/// Whether the settings suggest Reduced far detail: set when the renderer
|
||||
/// starts, on the GPUs `lod_capped` names (far terrain slows them most).
|
||||
@@ -282,6 +337,10 @@ pub struct Graphics {
|
||||
pub resolution_scale: u32,
|
||||
/// FXAA over the world.
|
||||
pub fxaa: bool,
|
||||
/// TAA over the world (FXAA is off while it is on).
|
||||
pub taa: bool,
|
||||
/// TAA upscaling; anything but `Native` comes with `taa` on.
|
||||
pub upscaling: Upscaling,
|
||||
/// HDR output (HDR10, or scRGB), where the display path offers it.
|
||||
pub hdr: bool,
|
||||
/// HDR paper white (where SDR white sits), in nits.
|
||||
@@ -319,6 +378,8 @@ impl Default for Graphics {
|
||||
overlay: Overlay::Off,
|
||||
resolution_scale: 100,
|
||||
fxaa: false,
|
||||
taa: false,
|
||||
upscaling: Upscaling::Native,
|
||||
hdr: false,
|
||||
hdr_paper_white: 200,
|
||||
hdr_peak: 1000,
|
||||
@@ -381,6 +442,8 @@ impl Graphics {
|
||||
"workers" => g.workers = number(g.workers).min(64),
|
||||
"resolutionScale" => g.resolution_scale = number(g.resolution_scale).clamp(50, 200),
|
||||
"fxaa" => g.fxaa = flag(g.fxaa),
|
||||
"taa" => g.taa = flag(g.taa),
|
||||
"upscaling" => g.upscaling = Upscaling::parse(value),
|
||||
"hdr" => g.hdr = flag(g.hdr),
|
||||
"hdrPaperWhite" => g.hdr_paper_white = number(g.hdr_paper_white).clamp(80, 480),
|
||||
"hdrPeak" => g.hdr_peak = number(g.hdr_peak).clamp(200, 2000),
|
||||
@@ -401,7 +464,7 @@ impl Graphics {
|
||||
}
|
||||
pub fn serialize(&self) -> String {
|
||||
format!(
|
||||
"preset:{}\nlodDistance:{}\nfarDetail:{}\ncaveCulling:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nhdr:{}\nhdrPaperWhite:{}\nhdrPeak:{}\nbatteryMode:{}\ngraphicsApi:{}\npickedShaderPack:{}\n",
|
||||
"preset:{}\nlodDistance:{}\nfarDetail:{}\ncaveCulling:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\ntaa:{}\nupscaling:{}\nhdr:{}\nhdrPaperWhite:{}\nhdrPeak:{}\nbatteryMode:{}\ngraphicsApi:{}\npickedShaderPack:{}\n",
|
||||
self.preset.name(),
|
||||
self.lod_distance,
|
||||
self.far_detail.name(),
|
||||
@@ -426,6 +489,8 @@ impl Graphics {
|
||||
},
|
||||
self.resolution_scale,
|
||||
bool_text(self.fxaa),
|
||||
bool_text(self.taa),
|
||||
self.upscaling.name(),
|
||||
bool_text(self.hdr),
|
||||
self.hdr_paper_white,
|
||||
self.hdr_peak,
|
||||
@@ -541,6 +606,8 @@ mod tests {
|
||||
overlay: Overlay::Graph,
|
||||
resolution_scale: 75,
|
||||
fxaa: true,
|
||||
taa: true,
|
||||
upscaling: Upscaling::Balanced,
|
||||
hdr: true,
|
||||
hdr_paper_white: 240,
|
||||
hdr_peak: 1400,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! they show, in what groups, with what description and cost, and their
|
||||
//! input. How they look comes from `graphics_style`.
|
||||
use crate::{
|
||||
graphics::{FarDetail, GraphicsApi, Overlay, Pacing, PresentMode, Preset},
|
||||
graphics::{FarDetail, GraphicsApi, Overlay, Pacing, PresentMode, Preset, Upscaling},
|
||||
graphics_style::{Cost, STYLE},
|
||||
hud::{HudAtlas, HudBatch},
|
||||
settings::{Opt, Settings},
|
||||
@@ -36,6 +36,7 @@ pub enum H {
|
||||
Overlay,
|
||||
ResolutionScale,
|
||||
Antialiasing,
|
||||
Upscaling,
|
||||
Hdr,
|
||||
HdrPaperWhite,
|
||||
HdrPeak,
|
||||
@@ -221,7 +222,12 @@ pub fn rows(level: Level) -> Vec<Row> {
|
||||
h(
|
||||
H::Antialiasing,
|
||||
Medium,
|
||||
"FXAA smooths jagged edges of the world; slightly softer image.",
|
||||
"Smooths jagged edges. FXAA: softer. TAA: smoothest, moving things may trail.",
|
||||
),
|
||||
h(
|
||||
H::Upscaling,
|
||||
High,
|
||||
"Renders the world smaller and rebuilds it with TAA. Faster, softer.",
|
||||
),
|
||||
h(
|
||||
H::Hdr,
|
||||
@@ -303,9 +309,13 @@ pub fn rows(level: Level) -> Vec<Row> {
|
||||
const UPLOAD_STEPS: [u32; 8] = [0, 256, 512, 1024, 2048, 4096, 8192, 16384];
|
||||
|
||||
/// Horizon's graphics screens supplement the vanilla options on Video Settings.
|
||||
fn extra_rows(level: Level) -> Vec<Row> {
|
||||
/// Upscaling is only there while TAA is, which does it.
|
||||
fn extra_rows(level: Level, settings: &Settings) -> Vec<Row> {
|
||||
let mut rows = rows(level);
|
||||
rows.retain(|row| !matches!(row, Row::Setting(s) if matches!(s.item, Item::Vanilla(_))));
|
||||
if !settings.horizon.taa {
|
||||
rows.retain(|row| !matches!(row, Row::Setting(s) if s.item == Item::Horizon(H::Upscaling)));
|
||||
}
|
||||
// Drop headings whose settings were all on the parent screens.
|
||||
let mut has_setting = false;
|
||||
rows.reverse();
|
||||
@@ -383,7 +393,15 @@ impl H {
|
||||
n => labelled("Worker Threads", n),
|
||||
},
|
||||
H::ResolutionScale => labelled("Resolution Scale", format!("{}%", g.resolution_scale)),
|
||||
H::Antialiasing => labelled("Anti-aliasing", if g.fxaa { "FXAA" } else { "Off" }),
|
||||
H::Antialiasing => labelled(
|
||||
"Anti-aliasing",
|
||||
match (g.fxaa, g.taa) {
|
||||
(_, true) => "TAA",
|
||||
(true, false) => "FXAA",
|
||||
(false, false) => "Off",
|
||||
},
|
||||
),
|
||||
H::Upscaling => labelled("Upscaling", g.upscaling.label()),
|
||||
H::Hdr => labelled("HDR", on_off(g.hdr)),
|
||||
H::HdrPaperWhite => labelled("Paper White", format!("{} nits", g.hdr_paper_white)),
|
||||
H::HdrPeak => labelled("Peak Brightness", format!("{} nits", g.hdr_peak)),
|
||||
@@ -441,7 +459,22 @@ impl H {
|
||||
H::Weather => g.weather = !g.weather,
|
||||
H::AnimatedTextures => g.animated_textures = !g.animated_textures,
|
||||
H::PresentMode => g.present_mode = step(&PresentMode::ALL, g.present_mode, back),
|
||||
H::Antialiasing => g.fxaa = !g.fxaa,
|
||||
// Off, FXAA, TAA.
|
||||
H::Antialiasing => {
|
||||
let i = if g.taa { 2 } else { usize::from(g.fxaa) };
|
||||
let i = (i + if back { 2 } else { 1 }) % 3;
|
||||
(g.fxaa, g.taa) = (i == 1, i == 2);
|
||||
if !g.taa {
|
||||
g.upscaling = Upscaling::Native;
|
||||
}
|
||||
}
|
||||
// Upscaling is TAA's: picking a ratio turns it on.
|
||||
H::Upscaling => {
|
||||
g.upscaling = step(&Upscaling::ALL, g.upscaling, back);
|
||||
if g.upscaling != Upscaling::Native {
|
||||
(g.fxaa, g.taa) = (false, true);
|
||||
}
|
||||
}
|
||||
H::Hdr => g.hdr = !g.hdr,
|
||||
H::BatteryMode => g.battery = !g.battery,
|
||||
H::GraphicsApi => g.api = step(GraphicsApi::choices(), g.api, back),
|
||||
@@ -481,7 +514,6 @@ impl Item {
|
||||
Item::Horizon(H::Fog) => g.fog,
|
||||
Item::Horizon(H::Weather) => g.weather,
|
||||
Item::Horizon(H::AnimatedTextures) => g.animated_textures,
|
||||
Item::Horizon(H::Antialiasing) => g.fxaa,
|
||||
Item::Horizon(H::Hdr) => g.hdr,
|
||||
Item::Horizon(H::BatteryMode) => g.battery,
|
||||
Item::Vanilla(Opt::ViewBobbing) => s.view_bobbing,
|
||||
@@ -570,6 +602,7 @@ impl Item {
|
||||
pub enum Action {
|
||||
ButtonClick,
|
||||
Changed,
|
||||
SliderDrag,
|
||||
OpenAdvanced,
|
||||
OpenSimple,
|
||||
Done,
|
||||
@@ -603,8 +636,8 @@ impl GraphicsUi {
|
||||
fn bounds(h: f32) -> (f32, f32) {
|
||||
(STYLE.band, h - STYLE.band)
|
||||
}
|
||||
fn content_height(level: Level) -> f32 {
|
||||
extra_rows(level).iter().fold(4.0, |height, row| {
|
||||
fn content_height(level: Level, s: &Settings) -> f32 {
|
||||
extra_rows(level, s).iter().fold(4.0, |height, row| {
|
||||
height
|
||||
+ match row {
|
||||
Row::Header(_) => STYLE.header_height,
|
||||
@@ -616,17 +649,18 @@ impl GraphicsUi {
|
||||
fn layout(
|
||||
&mut self,
|
||||
level: Level,
|
||||
s: &Settings,
|
||||
w: f32,
|
||||
h: f32,
|
||||
) -> (Vec<Widget>, Vec<(f32, &'static str)>, f32) {
|
||||
let content = Self::content_height(level);
|
||||
let content = Self::content_height(level, s);
|
||||
self.clamp_scroll(h, content);
|
||||
let (top, _) = Self::bounds(h);
|
||||
let x = STYLE.row_x(w);
|
||||
let mut y = top + 4.0 - self.scroll;
|
||||
let mut widgets = Vec::new();
|
||||
let mut headers = Vec::new();
|
||||
for row in extra_rows(level) {
|
||||
for row in extra_rows(level, s) {
|
||||
match row {
|
||||
Row::Header(name) => {
|
||||
headers.push((y, name));
|
||||
@@ -680,7 +714,7 @@ impl GraphicsUi {
|
||||
in_world: bool,
|
||||
) {
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
let (widgets, headers, content) = self.layout(level, w, h);
|
||||
let (widgets, headers, content) = self.layout(level, s, w, h);
|
||||
let (top, bottom) = Self::bounds(h);
|
||||
STYLE.background(batch, atlas, top, bottom, in_world);
|
||||
let shown = |y: f32, height: f32| y >= top && y + height <= bottom;
|
||||
@@ -690,7 +724,7 @@ impl GraphicsUi {
|
||||
STYLE.header(batch, atlas, &Text::literal(name), x, y);
|
||||
}
|
||||
}
|
||||
let descriptions: Vec<(Cost, &'static str)> = extra_rows(level)
|
||||
let descriptions: Vec<(Cost, &'static str)> = extra_rows(level, s)
|
||||
.into_iter()
|
||||
.filter_map(|r| match r {
|
||||
Row::Setting(s) => Some((s.cost, s.text)),
|
||||
@@ -791,7 +825,7 @@ impl GraphicsUi {
|
||||
drag: bool,
|
||||
right: bool,
|
||||
) -> Vec<Action> {
|
||||
let (widgets, _, _) = self.layout(level, w, h);
|
||||
let (widgets, _, _) = self.layout(level, s, w, h);
|
||||
let (top, bottom) = Self::bounds(h);
|
||||
if drag {
|
||||
if let Some(item) = self.dragging
|
||||
@@ -800,7 +834,7 @@ impl GraphicsUi {
|
||||
.find(|wd| matches!(wd.target, Target::Item(i) if i == item))
|
||||
{
|
||||
item.set_slider(s, ui::slider_value(wd.x, wd.w, x));
|
||||
return vec![Action::Changed];
|
||||
return vec![Action::SliderDrag];
|
||||
}
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -822,11 +856,11 @@ impl GraphicsUi {
|
||||
if item.slider(s).is_some() {
|
||||
self.dragging = Some(item);
|
||||
item.set_slider(s, ui::slider_value(wd.x, wd.w, x));
|
||||
vec![Action::SliderDrag]
|
||||
} else {
|
||||
item.cycle(s, right, framebuffer);
|
||||
return vec![Action::ButtonClick, Action::Changed];
|
||||
vec![Action::ButtonClick, Action::Changed]
|
||||
}
|
||||
vec![Action::Changed]
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -835,8 +869,8 @@ impl GraphicsUi {
|
||||
pub fn release(&mut self) -> bool {
|
||||
self.dragging.take().is_some()
|
||||
}
|
||||
pub fn scroll(&mut self, level: Level, h: f32, amount: f32) {
|
||||
let content = Self::content_height(level);
|
||||
pub fn scroll(&mut self, level: Level, s: &Settings, h: f32, amount: f32) {
|
||||
let content = Self::content_height(level, s);
|
||||
self.clamp_scroll(h, content);
|
||||
self.scroll -= amount * 18.0;
|
||||
self.clamp_scroll(h, content);
|
||||
@@ -852,7 +886,7 @@ mod tests {
|
||||
let mut s = Settings::default();
|
||||
let mut ui = GraphicsUi::default();
|
||||
let size = (480.0, 320.0);
|
||||
let (widgets, _, _) = ui.layout(Level::Advanced, size.0, size.1);
|
||||
let (widgets, _, _) = ui.layout(Level::Advanced, &s, size.0, size.1);
|
||||
let button = widgets
|
||||
.iter()
|
||||
.find(|w| matches!(w.target, Target::Button(_)))
|
||||
@@ -897,7 +931,7 @@ mod tests {
|
||||
false,
|
||||
false
|
||||
),
|
||||
vec![Action::Changed]
|
||||
vec![Action::SliderDrag]
|
||||
);
|
||||
assert_eq!(
|
||||
ui.click(
|
||||
@@ -909,7 +943,7 @@ mod tests {
|
||||
true,
|
||||
false
|
||||
),
|
||||
vec![Action::Changed]
|
||||
vec![Action::SliderDrag]
|
||||
);
|
||||
assert!(ui.release());
|
||||
assert!(!ui.release());
|
||||
@@ -917,45 +951,47 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn scrolling_stops_at_both_limits_before_layout() {
|
||||
let s = Settings::default();
|
||||
for level in [Level::Simple, Level::Advanced] {
|
||||
let mut ui = GraphicsUi::default();
|
||||
let h = 2.0 * STYLE.band + 10.0;
|
||||
let (top, bottom) = GraphicsUi::bounds(h);
|
||||
let max = GraphicsUi::content_height(level) - (bottom - top);
|
||||
let max = GraphicsUi::content_height(level, &s) - (bottom - top);
|
||||
assert!(max > 4.5);
|
||||
for _ in 0..3 {
|
||||
ui.scroll(level, h, 1000.0);
|
||||
ui.scroll(level, &s, h, 1000.0);
|
||||
assert_eq!(ui.scroll, 0.0);
|
||||
}
|
||||
for _ in 0..3 {
|
||||
ui.scroll(level, h, -1000.0);
|
||||
ui.scroll(level, &s, h, -1000.0);
|
||||
assert_eq!(ui.scroll, max);
|
||||
}
|
||||
ui.scroll(level, h, 0.25);
|
||||
ui.scroll(level, &s, h, 0.25);
|
||||
assert_eq!(ui.scroll, max - 4.5);
|
||||
ui.scroll(level, h, 1000.0);
|
||||
ui.scroll(level, h, -0.25);
|
||||
ui.scroll(level, &s, h, 1000.0);
|
||||
ui.scroll(level, &s, h, -0.25);
|
||||
assert_eq!(ui.scroll, 4.5);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resizing_clamps_before_positioning_graphics_rows() {
|
||||
let s = Settings::default();
|
||||
for level in [Level::Simple, Level::Advanced] {
|
||||
let mut ui = GraphicsUi::default();
|
||||
ui.scroll(level, 2.0 * STYLE.band + 10.0, -1000.0);
|
||||
ui.scroll(level, &s, 2.0 * STYLE.band + 10.0, -1000.0);
|
||||
assert!(ui.scroll > 0.0);
|
||||
let (widgets, headers, _) = ui.layout(level, 480.0, 4000.0);
|
||||
let (widgets, headers, _) = ui.layout(level, &s, 480.0, 4000.0);
|
||||
assert_eq!(ui.scroll, 0.0);
|
||||
if let Some((y, _)) = headers.first() {
|
||||
assert_eq!(*y, STYLE.band + 4.0);
|
||||
}
|
||||
let (expected, _, _) = GraphicsUi::default().layout(level, 480.0, 4000.0);
|
||||
let (expected, _, _) = GraphicsUi::default().layout(level, &s, 480.0, 4000.0);
|
||||
assert_eq!(
|
||||
widgets.iter().map(|w| w.y).collect::<Vec<_>>(),
|
||||
expected.iter().map(|w| w.y).collect::<Vec<_>>()
|
||||
);
|
||||
ui.scroll(level, 4000.0, -1000.0);
|
||||
ui.scroll(level, &s, 4000.0, -1000.0);
|
||||
assert_eq!(ui.scroll, 0.0);
|
||||
}
|
||||
}
|
||||
@@ -963,7 +999,7 @@ mod tests {
|
||||
#[test]
|
||||
fn classic_submenus_only_add_horizon_settings_without_empty_groups() {
|
||||
for level in [Level::Simple, Level::Advanced] {
|
||||
let rows = extra_rows(level);
|
||||
let rows = extra_rows(level, &Settings::default());
|
||||
assert!(rows.iter().any(|row| matches!(row, Row::Setting(_))));
|
||||
for (i, row) in rows.iter().enumerate() {
|
||||
match row {
|
||||
@@ -1051,6 +1087,37 @@ mod tests {
|
||||
assert_eq!(s.horizon.upload_budget_kib, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn antialiasing_cycles_off_fxaa_taa() {
|
||||
let mut s = Settings::default();
|
||||
let item = Item::Horizon(H::Antialiasing);
|
||||
for label in ["FXAA", "TAA", "Off"] {
|
||||
item.cycle(&mut s, false, [854, 480]);
|
||||
assert_eq!(item.label(&s).plain(), format!("Anti-aliasing: {label}"));
|
||||
}
|
||||
item.cycle(&mut s, true, [854, 480]);
|
||||
assert_eq!((s.horizon.fxaa, s.horizon.taa), (false, true));
|
||||
|
||||
// Upscaling needs TAA: a ratio turns it on, leaving TAA goes back to Native.
|
||||
s.horizon.taa = false;
|
||||
let upscaling = Item::Horizon(H::Upscaling);
|
||||
upscaling.cycle(&mut s, false, [854, 480]);
|
||||
assert_eq!(upscaling.label(&s).plain(), "Upscaling: Quality");
|
||||
assert!(s.horizon.taa);
|
||||
item.cycle(&mut s, false, [854, 480]);
|
||||
assert_eq!(s.horizon.upscaling, Upscaling::Native);
|
||||
|
||||
// The Upscaling row is only on the screen while TAA is on.
|
||||
let shown = |s: &Settings| {
|
||||
extra_rows(Level::Advanced, s)
|
||||
.iter()
|
||||
.any(|row| matches!(row, Row::Setting(r) if r.item == upscaling))
|
||||
};
|
||||
assert!(!shown(&s));
|
||||
s.horizon.taa = true;
|
||||
assert!(shown(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entity_culling_is_opt_in_and_toggles_from_advanced_graphics() {
|
||||
let mut s = Settings::default();
|
||||
@@ -1067,7 +1134,7 @@ mod tests {
|
||||
|
||||
let mut ui = GraphicsUi::default();
|
||||
let size = (480.0, 4000.0);
|
||||
let (widgets, _, _) = ui.layout(Level::Advanced, size.0, size.1);
|
||||
let (widgets, _, _) = ui.layout(Level::Advanced, &s, size.0, size.1);
|
||||
let switch = widgets
|
||||
.iter()
|
||||
.find(|w| matches!(w.target, Target::Item(i) if i == item))
|
||||
|
||||
@@ -1001,6 +1001,35 @@ impl HudBatch {
|
||||
y: f32,
|
||||
color: u32,
|
||||
shadow: bool,
|
||||
) -> f32 {
|
||||
self.styled_text(atlas, text, x, y, color, shadow, false)
|
||||
}
|
||||
/// `text_styled` for text drawn in the world (`TextRenderable.render`
|
||||
/// with `flat` false): each quad's `depth` is its z in text units, the
|
||||
/// glyphs `Font.SHADOW_DEPTH` in front of their shadow, a bold copy 0.001
|
||||
/// in front of its glyph and the lines 0.01 (`BakedSheetGlyph`), so they
|
||||
/// do not fight over the same pixels.
|
||||
pub fn text_styled_world(
|
||||
&mut self,
|
||||
atlas: &HudAtlas,
|
||||
text: &crate::text::Text,
|
||||
x: f32,
|
||||
y: f32,
|
||||
color: u32,
|
||||
shadow: bool,
|
||||
) -> f32 {
|
||||
self.styled_text(atlas, text, x, y, color, shadow, true)
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn styled_text(
|
||||
&mut self,
|
||||
atlas: &HudAtlas,
|
||||
text: &crate::text::Text,
|
||||
x: f32,
|
||||
y: f32,
|
||||
color: u32,
|
||||
shadow: bool,
|
||||
world: bool,
|
||||
) -> f32 {
|
||||
// StringDecomposer.iterateFormatted inside Font.drawInternal:
|
||||
// `§` codes inside a span restyle what follows and are not drawn.
|
||||
@@ -1011,7 +1040,13 @@ impl HudBatch {
|
||||
let alpha = (color >> 24) as u8;
|
||||
let mut glyphs = Vec::new();
|
||||
let mut cursor = x;
|
||||
let mut previous = None;
|
||||
for (i, (ch, style)) in text.chars().enumerate() {
|
||||
// Font.PreparedTextBuilder.accept: lines start 1 left of a
|
||||
// sequence's first character. Language.getVisualOrder makes a
|
||||
// sequence of each run of one style, which world text has.
|
||||
let first = i == 0 || world && previous != Some(style);
|
||||
previous = Some(style);
|
||||
// The style's font (`Style.getFont`), the default one unless set.
|
||||
let mut g = font.glyph_styled(ch, style);
|
||||
// Font.StringRenderOutput.accept: obfuscated characters draw a
|
||||
@@ -1032,7 +1067,7 @@ impl HudBatch {
|
||||
style.is_italic(),
|
||||
style.underlined == Some(true),
|
||||
style.strikethrough == Some(true),
|
||||
i == 0,
|
||||
first,
|
||||
advance,
|
||||
));
|
||||
cursor += advance;
|
||||
@@ -1040,19 +1075,25 @@ impl HudBatch {
|
||||
self.patches.extend(font.take_patches());
|
||||
let white = font.white();
|
||||
let passes: &[bool] = if shadow { &[true, false] } else { &[false] };
|
||||
// ARGB.scaleRGB(color, 0.25): the shadow's colour.
|
||||
let shade = |c: u32| {
|
||||
let b = c.to_le_bytes();
|
||||
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],
|
||||
)
|
||||
};
|
||||
for &is_shadow in passes {
|
||||
for &(gx, g, c, bold, italic, underline, strike, first, advance) in &glyphs {
|
||||
// In the world a glyph whose shadow is 0 has none (hasShadow).
|
||||
let has_shadow = shadow && !(world && shade(c) == 0);
|
||||
if is_shadow && !has_shadow {
|
||||
continue;
|
||||
}
|
||||
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],
|
||||
),
|
||||
)
|
||||
(g.offset, shade(c))
|
||||
} else {
|
||||
(0.0, c)
|
||||
};
|
||||
@@ -1092,21 +1133,62 @@ impl HudBatch {
|
||||
}
|
||||
None => {}
|
||||
};
|
||||
let base = if has_shadow && !is_shadow { 0.03 } else { 0.0 };
|
||||
let lift = |batch: &mut Self, start: usize, z: f32| {
|
||||
if world {
|
||||
for v in &mut batch.vertices[start..] {
|
||||
v.depth = z;
|
||||
}
|
||||
}
|
||||
};
|
||||
let start = self.vertices.len();
|
||||
draw(self, 0.0);
|
||||
lift(self, start, base);
|
||||
if bold {
|
||||
let start = self.vertices.len();
|
||||
draw(self, g.offset);
|
||||
lift(self, start, base + 0.001);
|
||||
}
|
||||
let x0 = if first { px - 1.0 } else { px };
|
||||
let start = self.vertices.len();
|
||||
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);
|
||||
}
|
||||
lift(self, start, base + 0.01);
|
||||
}
|
||||
}
|
||||
cursor - x
|
||||
}
|
||||
/// SubmitNodeCollection.submitNameTag's text in its own space (x right,
|
||||
/// y down, in GUI pixels): centred at `-Font.width / 2`, drawn as
|
||||
/// Font.prepareText draws any text (styles, fonts and glyph boxes; no
|
||||
/// shadow), over `background` (RGBA) unless its alpha is 0. Returns how
|
||||
/// many vertices at the start of the batch are the background.
|
||||
pub fn name_tag(
|
||||
&mut self,
|
||||
atlas: &HudAtlas,
|
||||
text: &crate::text::Text,
|
||||
y: f32,
|
||||
color: u32,
|
||||
background: u32,
|
||||
) -> usize {
|
||||
let x = -atlas.font.width_text(text) / 2.0;
|
||||
let start = self.vertices.len();
|
||||
let advance = self.text_styled(atlas, text, x, y, color, false);
|
||||
if background >> 24 == 0 {
|
||||
return 0;
|
||||
}
|
||||
// PreparedTextBuilder.markBackground: one pixel round the advances,
|
||||
// from a pixel above the line to 9 below its top.
|
||||
let glyphs = self.vertices.split_off(start);
|
||||
self.fill(atlas, x - 1.0, y - 1.0, advance + 1.0, 10.0, background);
|
||||
let behind = self.vertices.len() - start;
|
||||
self.vertices.extend(glyphs);
|
||||
behind
|
||||
}
|
||||
}
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
@@ -1822,6 +1904,65 @@ mod tests {
|
||||
assert!(missing.rect.is_none() && missing.right == 5.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn name_tags_draw_bold_text_and_tall_glyphs_like_any_text() {
|
||||
// `ascii.png`'s 8x8 'a' (4 pixels wide) and `accented.png`'s 9x12
|
||||
// 'й' (height 12, ascent 10: the breve above the line), 7 wide.
|
||||
let root = std::env::temp_dir().join(format!("horizon-name-tag-{}", std::process::id()));
|
||||
let textures = root.join("assets/minecraft/textures/font");
|
||||
fs::create_dir_all(root.join("assets/minecraft/font")).unwrap();
|
||||
fs::create_dir_all(&textures).unwrap();
|
||||
fs::write(
|
||||
root.join("assets/minecraft/font/default.json"),
|
||||
r#"{"providers":[
|
||||
{"type":"bitmap","file":"minecraft:font/a.png","ascent":7,"chars":["a"]},
|
||||
{"type":"bitmap","file":"minecraft:font/tall.png","height":12,"ascent":10,"chars":["й"]}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
for (name, (w, h), used) in [("a", (8, 8), 4), ("tall", (9, 12), 7)] {
|
||||
let pixels: Vec<u8> = (0..w * h)
|
||||
.flat_map(|i| [255, 255, 255, if i % w < used { 255 } else { 0 }])
|
||||
.collect();
|
||||
let file = fs::File::create(textures.join(format!("{name}.png"))).unwrap();
|
||||
let mut encoder = png::Encoder::new(file, w, h);
|
||||
encoder.set_color(png::ColorType::Rgba);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
let mut writer = encoder.write_header().unwrap();
|
||||
writer.write_image_data(&pixels).unwrap();
|
||||
}
|
||||
let atlas = HudAtlas::build(&root).unwrap();
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
let text = crate::text::Text::literal("aй").bold();
|
||||
let mut batch = HudBatch::new([1, 1]);
|
||||
let behind = batch.name_tag(&atlas, &text, 0.0, u32::MAX, 0x3F00_0000);
|
||||
// Each quad's box: x0, y0, x1, y1.
|
||||
let boxes: Vec<[f32; 4]> = batch
|
||||
.vertices
|
||||
.as_chunks::<6>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|q| [q[0].pos[0], q[0].pos[1], q[2].pos[0], q[2].pos[1]])
|
||||
.collect();
|
||||
// Advances 5 and 8, plus 1 each for bold: Font.width 15, centred.
|
||||
let x = -7.5;
|
||||
// Each glyph twice (bold), the copy a pixel right; 'й' in its 9x12
|
||||
// box from 3 pixels above the line, each bold quad 0.1 larger.
|
||||
let near = |a: [f32; 4], b: [f32; 4]| a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-4);
|
||||
let expected = [
|
||||
[x - 0.1, -0.1, x + 8.1, 8.1],
|
||||
[x + 0.9, -0.1, x + 9.1, 8.1],
|
||||
[x + 5.9, -3.1, x + 15.1, 9.1],
|
||||
[x + 6.9, -3.1, x + 16.1, 9.1],
|
||||
];
|
||||
for (got, want) in boxes[1..].iter().zip(expected) {
|
||||
assert!(near(*got, want), "{got:?} != {want:?}");
|
||||
}
|
||||
assert_eq!(boxes.len(), 1 + expected.len());
|
||||
// The background first: a pixel round the advances, 10 pixels tall.
|
||||
assert_eq!(behind, 6);
|
||||
assert_eq!(boxes[0], [x - 1.0, -1.0, x + 15.0, 9.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effect_icons_are_painted_from_the_mob_effect_directory() {
|
||||
use crate::{effects::EffectInstance, hud_layout, hud_overlays, inventory_effects};
|
||||
|
||||
@@ -59,13 +59,7 @@ pub fn panels(
|
||||
translate("effect.duration.infinite").unwrap_or_else(|| "∞".to_owned())
|
||||
} else {
|
||||
// StringUtil.formatTickDuration uses the level's current rate.
|
||||
let seconds = (effect.duration as f32 / tick_rate) as i32;
|
||||
let (hours, minutes, seconds) = (seconds / 3600, seconds / 60 % 60, seconds % 60);
|
||||
if hours > 0 {
|
||||
format!("{hours:02}:{minutes:02}:{seconds:02}")
|
||||
} else {
|
||||
format!("{minutes:02}:{seconds:02}")
|
||||
}
|
||||
crate::brewing::format_tick_duration(effect.duration, tick_rate)
|
||||
};
|
||||
let width = max_width.min(39 + text_width(&name).max(text_width(&duration)));
|
||||
EffectPanel {
|
||||
|
||||
@@ -25,6 +25,16 @@ const MAX_SAVED: usize = 1024;
|
||||
/// (`Lod::observing`).
|
||||
pub const OBSERVE_AHEAD: usize = 8;
|
||||
const SAMPLE_JOBS: usize = 4;
|
||||
/// Threads that sample far tiles beside the mesher. Machines with 12 or more
|
||||
/// threads use up to 6 (measured: a cold 1024-chunk LoD loads about a quarter
|
||||
/// sooner than with 3); the rest keep a quarter of their threads, at most 3.
|
||||
fn sampling_threads(cores: usize) -> usize {
|
||||
if cores >= 12 {
|
||||
(cores / 2).min(6)
|
||||
} else {
|
||||
(cores / 4).clamp(1, 3)
|
||||
}
|
||||
}
|
||||
/// While the near terrain loads on a machine with four threads or fewer, far
|
||||
/// terrain starts one sample job at most this often and no detail: it would
|
||||
/// otherwise take the cores the near chunks and the frame need.
|
||||
@@ -550,6 +560,8 @@ pub struct Lod {
|
||||
detail_request_at: std::time::Instant,
|
||||
/// Four threads or fewer: far work waits for the near terrain (`hold`).
|
||||
small: bool,
|
||||
/// Sample jobs that may be queued or running at once.
|
||||
sample_jobs: usize,
|
||||
/// The near terrain is loading (`set_near_loading`).
|
||||
near_loading: bool,
|
||||
/// When `request_samples` last started a job while held.
|
||||
@@ -570,6 +582,7 @@ pub struct Lod {
|
||||
}
|
||||
impl Lod {
|
||||
pub fn new(source: Arc<dyn LodSource>, context: Arc<WorkerContext>) -> Self {
|
||||
let cores = thread::available_parallelism().map_or(1, |n| n.get());
|
||||
let shared = Arc::new(Shared {
|
||||
jobs: Mutex::new(VecDeque::new()),
|
||||
observed: Mutex::new(FxHashMap::default()),
|
||||
@@ -583,10 +596,10 @@ impl Lod {
|
||||
let handle = thread::Builder::new()
|
||||
.name("Far terrain".into())
|
||||
.spawn(move || {
|
||||
// Ticks and frames come first (horizon_threads).
|
||||
horizon_threads::behind_server();
|
||||
let mut sampler = source.sampler();
|
||||
let count = thread::available_parallelism()
|
||||
.map_or(1, |n| n.get() / 4)
|
||||
.clamp(1, 3);
|
||||
let count = sampling_threads(cores);
|
||||
let mut sampling = Vec::new();
|
||||
for _ in 0..count {
|
||||
let Some(mut sample) = sampler.fork() else {
|
||||
@@ -598,6 +611,7 @@ impl Lod {
|
||||
thread::Builder::new()
|
||||
.name("Far sampling".into())
|
||||
.spawn(move || {
|
||||
horizon_threads::behind_server();
|
||||
loop {
|
||||
let key = {
|
||||
let mut jobs = shared.jobs.lock().unwrap();
|
||||
@@ -746,7 +760,8 @@ impl Lod {
|
||||
detail_masks: FxHashMap::default(),
|
||||
detail_request_pending: false,
|
||||
detail_request_at: std::time::Instant::now(),
|
||||
small: thread::available_parallelism().map_or(1, |n| n.get()) <= 4,
|
||||
small: cores <= 4,
|
||||
sample_jobs: SAMPLE_JOBS.max(sampling_threads(cores) + 1),
|
||||
near_loading: false,
|
||||
held_sample_at: std::time::Instant::now(),
|
||||
ready: FxHashMap::default(),
|
||||
@@ -1243,7 +1258,13 @@ impl Lod {
|
||||
self.pending.is_empty() && self.held_sample_at.elapsed() >= HELD_SAMPLE_STEP,
|
||||
)
|
||||
} else {
|
||||
SAMPLE_JOBS.saturating_sub(self.pending.len())
|
||||
// The extra sampling threads wait until the near terrain is in.
|
||||
let slots = if self.near_loading {
|
||||
SAMPLE_JOBS
|
||||
} else {
|
||||
self.sample_jobs
|
||||
};
|
||||
slots.saturating_sub(self.pending.len())
|
||||
};
|
||||
if free == 0 {
|
||||
return;
|
||||
@@ -1291,8 +1312,8 @@ impl Lod {
|
||||
}
|
||||
// Only the first `free` keys not already pending are taken. A key is
|
||||
// listed at most twice (as a root and as a node), so the best
|
||||
// `2 * (SAMPLE_JOBS + pending)` entries hold them, in order.
|
||||
let best = 2 * (SAMPLE_JOBS + self.pending.len());
|
||||
// `2 * (sample_jobs + pending)` entries hold them, in order.
|
||||
let best = 2 * (self.sample_jobs + self.pending.len());
|
||||
if wanted.len() > best {
|
||||
wanted.select_nth_unstable(best);
|
||||
wanted.truncate(best);
|
||||
@@ -2000,6 +2021,7 @@ mod tests {
|
||||
lod.ready
|
||||
.insert(parent, Arc::new(vec![Column::default(); 256]));
|
||||
lod.active = [parent].into_iter().collect();
|
||||
lod.sample_jobs = SAMPLE_JOBS;
|
||||
lod.pending = (0..SAMPLE_JOBS - 1)
|
||||
.map(|i| TileKey {
|
||||
x: 999 + i as i32,
|
||||
@@ -2058,6 +2080,7 @@ mod tests {
|
||||
}
|
||||
lod.active = [near, far].into_iter().collect();
|
||||
lod.shared.jobs.lock().unwrap().clear();
|
||||
lod.sample_jobs = SAMPLE_JOBS;
|
||||
lod.pending = (0..SAMPLE_JOBS - 1)
|
||||
.map(|i| TileKey {
|
||||
x: 999 + i as i32,
|
||||
@@ -2091,6 +2114,34 @@ mod tests {
|
||||
(1..=32).map(|x| (x, 0)).collect::<Vec<_>>(),
|
||||
"one unfinished fine tile must not starve neighbouring requests"
|
||||
);
|
||||
|
||||
// The extra sampling threads' slots open once the near terrain is in.
|
||||
lod.small = false;
|
||||
lod.sample_jobs = SAMPLE_JOBS + 3;
|
||||
lod.plan = Plan::new([-256, -256], 2, 64);
|
||||
lod.ready.clear();
|
||||
lod.active.clear();
|
||||
lod.pending.clear();
|
||||
lod.meshing = true;
|
||||
lod.shared.jobs.lock().unwrap().clear();
|
||||
let queued = |lod: &mut Lod, near_loading: bool| {
|
||||
lod.set_near_loading(near_loading);
|
||||
lod.shared.jobs.lock().unwrap().clear();
|
||||
lod.pending.clear();
|
||||
lod.update([-256., 64., -256.], 0., 2, 64, Some(FxHashSet::default()));
|
||||
let jobs = lod.shared.jobs.lock().unwrap();
|
||||
jobs.iter()
|
||||
.filter(|job| matches!(job, Job::Sample(_)))
|
||||
.count()
|
||||
};
|
||||
assert_eq!(queued(&mut lod, true), SAMPLE_JOBS);
|
||||
assert_eq!(queued(&mut lod, false), SAMPLE_JOBS + 3);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_sampling_threads_only_on_large_machines() {
|
||||
assert_eq!([1, 2, 4, 8, 11].map(sampling_threads), [1, 1, 1, 2, 2]);
|
||||
assert_eq!([12, 16, 64].map(sampling_threads), [6, 6, 6]);
|
||||
}
|
||||
}
|
||||
@@ -1004,8 +1004,10 @@ pub enum Event {
|
||||
ButtonClick,
|
||||
/// Close the options screens (back to the pause menu or title).
|
||||
Close,
|
||||
/// Settings changed: apply them.
|
||||
/// Settings changed: apply and save them.
|
||||
Changed,
|
||||
/// A slider is being dragged: apply settings live but defer saving.
|
||||
SliderDrag,
|
||||
/// The language changed (reload translations).
|
||||
Language(String),
|
||||
/// The pack selection changed (reload resources).
|
||||
@@ -1020,6 +1022,9 @@ pub enum Event {
|
||||
/// Open the mod's own settings page (capability `ui`): the installed
|
||||
/// mod's index in `mods.installed`.
|
||||
ModSettings(usize),
|
||||
/// Native mod `.0`'s page opened: the game asks the mod for its labels
|
||||
/// again (they were made with the list, maybe in another language).
|
||||
NativeSettings(usize),
|
||||
/// Button `.1` of native mod `.0`'s page was pressed: the game tells the
|
||||
/// mod and refreshes the page.
|
||||
NativeButton(usize, usize),
|
||||
@@ -2526,6 +2531,7 @@ impl OptionsUi {
|
||||
match action {
|
||||
Action::ButtonClick => events.push(Event::ButtonClick),
|
||||
Action::Changed => events.push(Event::Changed),
|
||||
Action::SliderDrag => events.push(Event::SliderDrag),
|
||||
Action::OpenAdvanced => self.push(Page::GraphicsAdvanced),
|
||||
Action::OpenSimple => {
|
||||
if self.stack.len() >= 2
|
||||
@@ -2606,7 +2612,7 @@ impl OptionsUi {
|
||||
let v = ui::slider_value(wd.x, wd.w, x);
|
||||
self.slider_value = Some((opt, v, Instant::now()));
|
||||
set_slider(opt, s, v);
|
||||
events.push(Event::Changed);
|
||||
events.push(Event::SliderDrag);
|
||||
}
|
||||
return events;
|
||||
}
|
||||
@@ -2711,6 +2717,7 @@ impl OptionsUi {
|
||||
events.push(Event::ButtonClick);
|
||||
if s.mods.installed.get(i).is_some_and(|m| m.native.is_some()) {
|
||||
self.push(Page::NativeMod(i));
|
||||
events.push(Event::NativeSettings(i));
|
||||
} else {
|
||||
events.push(Event::ModSettings(i));
|
||||
}
|
||||
@@ -2742,7 +2749,7 @@ impl OptionsUi {
|
||||
let v = ui::slider_value(wd.x, wd.w, x);
|
||||
self.slider_value = Some((opt, v, Instant::now()));
|
||||
set_slider(opt, s, v);
|
||||
events.push(Event::Changed);
|
||||
events.push(Event::SliderDrag);
|
||||
}
|
||||
WKind::LanguageRow { code, .. } => {
|
||||
if self.language_choice.as_deref() == Some(code.as_str()) {
|
||||
@@ -2775,7 +2782,7 @@ impl OptionsUi {
|
||||
let slider = self.dragging.take().is_some();
|
||||
let graphics_slider = self.graphics.release();
|
||||
if slider || graphics_slider {
|
||||
vec![Event::ButtonClick]
|
||||
vec![Event::ButtonClick, Event::Changed]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
@@ -2791,7 +2798,7 @@ impl OptionsUi {
|
||||
return;
|
||||
}
|
||||
if let Some(level) = Self::graphics_level(self.page()) {
|
||||
self.graphics.scroll(level, size.1, amount);
|
||||
self.graphics.scroll(level, s, size.1, amount);
|
||||
return;
|
||||
}
|
||||
match &mut self.pack_screen {
|
||||
@@ -3329,6 +3336,50 @@ mod tests {
|
||||
assert_eq!(ui.page(), Page::Main);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_a_native_mods_page_asks_the_game_for_its_labels_again() {
|
||||
let atlas = atlas();
|
||||
let mut s = Settings::default();
|
||||
let mut ui = OptionsUi::default();
|
||||
let size = (480.0, 240.0);
|
||||
s.mods.installed.push(crate::mod_list::Installed {
|
||||
id: "native".into(),
|
||||
title: "Native 1.0".into(),
|
||||
description: String::new(),
|
||||
problem: None,
|
||||
dev: false,
|
||||
has_settings: false,
|
||||
native: Some(crate::mod_list::NativePage::default()),
|
||||
});
|
||||
ui.show(Page::Mods);
|
||||
let (widgets, ..) = ui.layout(&s, size.0, size.1);
|
||||
let settings = widgets
|
||||
.iter()
|
||||
.find(|w| {
|
||||
matches!(
|
||||
w.kind,
|
||||
WKind::Button {
|
||||
act: Act::ModSettings(0),
|
||||
..
|
||||
}
|
||||
)
|
||||
})
|
||||
.expect("a native mod's row has a Settings button");
|
||||
let events = ui.click(
|
||||
&mut s,
|
||||
&atlas,
|
||||
settings.x + 1.0,
|
||||
settings.y + 1.0,
|
||||
size,
|
||||
[480, 240],
|
||||
false,
|
||||
false,
|
||||
);
|
||||
// Its labels were made with the list, maybe in another language.
|
||||
assert_eq!(events.last(), Some(&Event::NativeSettings(0)));
|
||||
assert_eq!(ui.page(), Page::NativeMod(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn option_tooltip_keys_follow_value_dependent_descriptions() {
|
||||
let mut s = Settings::default();
|
||||
@@ -3765,22 +3816,22 @@ mod tests {
|
||||
let (x, y) = (slider.x + slider.w - 1.0, slider.y + 1.0);
|
||||
assert_eq!(
|
||||
ui.click(&mut s, &atlas, x, y, size, [854, 480], false, false),
|
||||
vec![Event::Changed]
|
||||
vec![Event::SliderDrag]
|
||||
);
|
||||
assert_eq!(s.master_volume, 1.0);
|
||||
assert_eq!(ui.release(), vec![Event::ButtonClick]);
|
||||
assert_eq!(ui.release(), vec![Event::ButtonClick, Event::Changed]);
|
||||
assert!(ui.release().is_empty());
|
||||
assert_eq!(
|
||||
ui.click(&mut s, &atlas, x, y, size, [854, 480], false, false),
|
||||
vec![Event::Changed]
|
||||
vec![Event::SliderDrag]
|
||||
);
|
||||
for cx in [-100.0, 250.0, 1000.0] {
|
||||
assert_eq!(
|
||||
ui.click(&mut s, &atlas, cx, -100.0, size, [854, 480], true, false),
|
||||
vec![Event::Changed]
|
||||
vec![Event::SliderDrag]
|
||||
);
|
||||
}
|
||||
assert_eq!(ui.release(), vec![Event::ButtonClick]);
|
||||
assert_eq!(ui.release(), vec![Event::ButtonClick, Event::Changed]);
|
||||
assert!(
|
||||
ui.click(&mut s, &atlas, x, y, size, [854, 480], true, false)
|
||||
.is_empty()
|
||||
|
||||
@@ -380,11 +380,45 @@ fn link(target: &Path, at: &Path) -> io::Result<()> {
|
||||
if target.is_dir() {
|
||||
Ok(())
|
||||
} else {
|
||||
fs::copy(target, at).map(|_| ())
|
||||
// The mirror only reads these files, and unix links them: a hardlink gives
|
||||
// the same view without writing the 639 MB prepared root again, which was
|
||||
// 33 s of a cold Windows launch with a pack on. Another volume (or a
|
||||
// filesystem without hardlinks) still copies.
|
||||
fs::hard_link(target, at).or_else(|_| fs::copy(target, at).map(|_| ()))
|
||||
}
|
||||
}
|
||||
/// A directory junction, which Windows creates without privileges (a directory symlink needs
|
||||
/// developer mode). The mirror falls back to copying the tree when it fails.
|
||||
#[cfg(windows)]
|
||||
fn junction(target: &Path, at: &Path) -> io::Result<()> {
|
||||
use std::os::windows::process::CommandExt;
|
||||
// cmd parses its own line: Rust quotes only paths with spaces, so `&` or `^` in an
|
||||
// unquoted path would split or change the command. A Windows path cannot hold `"`.
|
||||
let quoted = |path: &Path| -> io::Result<std::ffi::OsString> {
|
||||
let mut quoted = std::ffi::OsString::from("\"");
|
||||
quoted.push(std::path::absolute(path)?);
|
||||
quoted.push("\"");
|
||||
Ok(quoted)
|
||||
};
|
||||
let status = std::process::Command::new("cmd")
|
||||
.args(["/C", "mklink", "/J"])
|
||||
.raw_arg(quoted(at)?)
|
||||
.raw_arg(quoted(target)?)
|
||||
.creation_flags(0x0800_0000) // CREATE_NO_WINDOW
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.status()?;
|
||||
status
|
||||
.success()
|
||||
.then_some(())
|
||||
.ok_or_else(|| io::Error::other("mklink /J failed"))
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
fn junction(_: &Path, _: &Path) -> io::Result<()> {
|
||||
Err(io::ErrorKind::Unsupported.into())
|
||||
}
|
||||
/// Build `out` as `vanilla` with the packs' files layered on top (packs in
|
||||
/// load order, last wins). Untouched directories are symlinks into vanilla.
|
||||
/// load order, last wins). Untouched directories are links into vanilla.
|
||||
pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<()> {
|
||||
cache::build(vanilla, packs, out)
|
||||
}
|
||||
@@ -516,11 +550,17 @@ fn build_overlay_uncached(
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if filters.is_empty()
|
||||
&& !touched.contains(&child)
|
||||
&& vanilla.join(&child).is_dir()
|
||||
&& junction(&vanilla.join(&child), &out.join(&child)).is_ok()
|
||||
{
|
||||
// Linked whole, like the unix symlink: no file in it is visited or copied.
|
||||
} else if touched.contains(&child)
|
||||
// Windows cannot link a directory the way unix does (`link` above), so an
|
||||
// untouched one has to be mirrored: skipping it hid textures/font and the
|
||||
// title panorama from the overlay, and a font json that names those sheets
|
||||
// then failed to load (#1688).
|
||||
// Without a junction Windows cannot link a directory the way unix does (`link`
|
||||
// above), so an untouched one has to be mirrored: skipping it hid textures/font
|
||||
// and the title panorama from the overlay, and a font json that names those
|
||||
// sheets then failed to load (#1688).
|
||||
|| (vanilla.join(&child).is_dir() && (cfg!(not(unix)) || !filters.is_empty()))
|
||||
{
|
||||
mirror(
|
||||
@@ -939,7 +979,8 @@ mod tests {
|
||||
}
|
||||
#[test]
|
||||
fn overlay_layers_packs_over_vanilla() {
|
||||
let base = std::env::temp_dir().join(format!("horizon-packs-{}", std::process::id()));
|
||||
// `&` would split an unquoted `cmd /C mklink` line.
|
||||
let base = std::env::temp_dir().join(format!("horizon-packs-&{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&base);
|
||||
let vanilla = base.join("vanilla");
|
||||
fs::create_dir_all(vanilla.join("assets/minecraft/textures/block")).unwrap();
|
||||
@@ -960,6 +1001,13 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(vanilla.join("facts.json"), b"[]").unwrap();
|
||||
// A directory no pack touches (#1688: a font json names sheets in it).
|
||||
fs::create_dir_all(vanilla.join("assets/minecraft/textures/font")).unwrap();
|
||||
fs::write(
|
||||
vanilla.join("assets/minecraft/textures/font/ascii.png"),
|
||||
b"font",
|
||||
)
|
||||
.unwrap();
|
||||
let pack_dir = base.join("packs/Mine");
|
||||
fs::create_dir_all(pack_dir.join("assets/minecraft/textures/block")).unwrap();
|
||||
fs::write(
|
||||
@@ -997,6 +1045,17 @@ mod tests {
|
||||
br#"{"a":"vanilla","b":"pack"}"#
|
||||
);
|
||||
assert_eq!(fs::read(out.join("facts.json")).unwrap(), b"[]");
|
||||
assert_eq!(
|
||||
fs::read(out.join("assets/minecraft/textures/font/ascii.png")).unwrap(),
|
||||
b"font"
|
||||
);
|
||||
// Linked, not mirrored: a junction on Windows, a symlink on unix.
|
||||
assert!(
|
||||
fs::symlink_metadata(out.join("assets/minecraft/textures/font"))
|
||||
.unwrap()
|
||||
.file_type()
|
||||
.is_symlink()
|
||||
);
|
||||
let _ = fs::remove_dir_all(base);
|
||||
}
|
||||
#[test]
|
||||
|
||||
@@ -8,8 +8,9 @@ use std::io::Read;
|
||||
use std::{collections::BTreeSet, fs, io, path::Path, path::PathBuf};
|
||||
|
||||
// Bump when overlay/merge semantics change. Markers are disposable cache data.
|
||||
// Version 4 mirrored every untouched directory file by file on Windows.
|
||||
// Version 3 could omit untouched vanilla directories on Windows (#1649, #1688).
|
||||
const VERSION: u32 = 4;
|
||||
const VERSION: u32 = 5;
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
pub(super) struct Dependencies {
|
||||
|
||||
@@ -491,15 +491,69 @@ pub fn texture_hash(url: &str) -> Option<String> {
|
||||
/// `SkinManager.TextureCache.registerTexture`: the texture id of a skin,
|
||||
/// `skins/` and the SHA-1 of its hash's UTF-16 code units.
|
||||
pub fn skin_location(hash: &str) -> String {
|
||||
location("skins/", hash)
|
||||
}
|
||||
/// `registerTexture` in the cape cache: `capes/` and the same SHA-1.
|
||||
pub fn cape_location(hash: &str) -> String {
|
||||
location("capes/", hash)
|
||||
}
|
||||
fn location(prefix: &str, hash: &str) -> String {
|
||||
let units: Vec<u8> = hash.encode_utf16().flat_map(u16::to_le_bytes).collect();
|
||||
let digest = sha1(&units);
|
||||
let mut out = String::from("skins/");
|
||||
let mut out = String::from(prefix);
|
||||
for b in digest {
|
||||
out.push_str(&format!("{b:02x}"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `PlayerSkin.cape`: the cape texture of textures whose lookup gave a skin
|
||||
/// (every download ready), if they name one.
|
||||
pub fn cape(textures: &Textures) -> Option<String> {
|
||||
textures
|
||||
.cape
|
||||
.as_deref()
|
||||
.and_then(texture_hash)
|
||||
.map(|hash| cape_location(&hash))
|
||||
}
|
||||
|
||||
/// A cape in a 64x64 skin slot: the 64x32 picture (or the older 22x17,
|
||||
/// which has the same layout) in its top half. Vanilla draws a cape of any
|
||||
/// size; a larger one is scaled down to 64x32 here.
|
||||
pub fn process_cape(width: u32, height: u32, rgba: &[u8]) -> Option<Vec<u8>> {
|
||||
let (w, h) = (width as usize, height as usize);
|
||||
if w == 0 || h == 0 || rgba.len() < w * h * 4 {
|
||||
return None;
|
||||
}
|
||||
let mut img = vec![0u8; 64 * 64 * 4];
|
||||
let (fit_w, fit_h) = if w <= 64 && h <= 32 { (w, h) } else { (64, 32) };
|
||||
for y in 0..fit_h {
|
||||
for x in 0..fit_w {
|
||||
let (sx, sy) = (x * w / fit_w, y * h / fit_h);
|
||||
let (s, d) = ((sy * w + sx) * 4, (y * 64 + x) * 4);
|
||||
img[d..d + 4].copy_from_slice(&rgba[s..s + 4]);
|
||||
}
|
||||
}
|
||||
Some(img)
|
||||
}
|
||||
|
||||
/// The cape the launcher gives an offline name (`HORIZON_OFFLINE_CAPE`, a
|
||||
/// PNG's path; launcher/src/skins.rs), read once as `process_cape` lays it out.
|
||||
pub fn offline_cape() -> Option<&'static [u8]> {
|
||||
static CAPE: std::sync::OnceLock<Option<Vec<u8>>> = std::sync::OnceLock::new();
|
||||
CAPE.get_or_init(|| {
|
||||
let path = std::env::var_os("HORIZON_OFFLINE_CAPE").filter(|p| !p.is_empty())?;
|
||||
let image = std::fs::read(&path)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|bytes| crate::hud::decode_bytes(&bytes).map_err(|e| e.to_string()))
|
||||
.and_then(|(w, h, rgba)| process_cape(w, h, &rgba).ok_or("not an image".into()));
|
||||
image
|
||||
.inspect_err(|e| eprintln!("Horizon: no offline cape ({}): {e}", path.display()))
|
||||
.ok()
|
||||
})
|
||||
.as_deref()
|
||||
}
|
||||
|
||||
/// Where a texture download stands.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Download {
|
||||
@@ -650,9 +704,10 @@ impl Downloader {
|
||||
while let Ok((key, image)) = self.done.try_recv() {
|
||||
let state = match image {
|
||||
Some(rgba) => {
|
||||
if key.0 == Kind::Skin {
|
||||
let location = skin_location(&key.1);
|
||||
self.queue(location, rgba);
|
||||
match key.0 {
|
||||
Kind::Skin => self.queue(skin_location(&key.1), rgba),
|
||||
Kind::Cape => self.queue(cape_location(&key.1), rgba),
|
||||
Kind::Elytra => {}
|
||||
}
|
||||
Download::Ready
|
||||
}
|
||||
@@ -685,7 +740,8 @@ impl Downloader {
|
||||
.and_then(|b| crate::hud::decode_bytes(&b).ok())
|
||||
.and_then(|(w, h, rgba)| match kind {
|
||||
Kind::Skin => process_legacy_skin(w, h, &rgba),
|
||||
_ => Some(rgba),
|
||||
Kind::Cape => process_cape(w, h, &rgba),
|
||||
Kind::Elytra => Some(rgba),
|
||||
});
|
||||
let _ = send.send((key, image));
|
||||
});
|
||||
@@ -716,16 +772,21 @@ impl Downloader {
|
||||
if self.queued.contains(location) {
|
||||
return true;
|
||||
}
|
||||
let Some(digest) = location.strip_prefix("skins/") else {
|
||||
return false;
|
||||
};
|
||||
let (digest, process): (_, fn(u32, u32, &[u8]) -> Option<Vec<u8>>) =
|
||||
if let Some(digest) = location.strip_prefix("skins/") {
|
||||
(digest, process_legacy_skin)
|
||||
} else if let Some(digest) = location.strip_prefix("capes/") {
|
||||
(digest, process_cape)
|
||||
} else {
|
||||
return false;
|
||||
};
|
||||
let image = self.images.get(location).cloned().or_else(|| {
|
||||
let file = self
|
||||
.root
|
||||
.join(if digest.len() > 2 { &digest[..2] } else { "xx" })
|
||||
.join(digest);
|
||||
let (w, h, rgba) = crate::hud::decode_bytes(&std::fs::read(&file).ok()?).ok()?;
|
||||
process_legacy_skin(w, h, &rgba)
|
||||
process(w, h, &rgba)
|
||||
});
|
||||
let Some(image) = image else {
|
||||
return false;
|
||||
@@ -961,6 +1022,31 @@ mod tests {
|
||||
assert_eq!(d.take_ready(), vec![("skins/def".to_owned(), vec![4])]);
|
||||
}
|
||||
|
||||
/// A cape fills the top half of a 64x64 slot; a larger one is scaled to 64x32.
|
||||
#[test]
|
||||
fn capes_fill_the_top_half_of_a_slot() {
|
||||
let at = |x: usize, y: usize| (y * 64 + x) * 4;
|
||||
let legacy = super::process_cape(22, 17, &[7; 22 * 17 * 4]).unwrap();
|
||||
assert_eq!(legacy.len(), 64 * 64 * 4);
|
||||
assert_eq!(legacy[at(21, 16)], 7);
|
||||
assert_eq!(legacy[at(22, 16)], 0);
|
||||
let mut hd = vec![0u8; 128 * 64 * 4];
|
||||
hd[(62 * 128 + 126) * 4] = 9;
|
||||
let hd = super::process_cape(128, 64, &hd).unwrap();
|
||||
assert_eq!(hd[at(63, 31)], 9);
|
||||
assert_eq!(hd[at(0, 32)], 0);
|
||||
assert!(super::process_cape(64, 32, &[0; 4]).is_none());
|
||||
let textures = super::Textures {
|
||||
cape: Some("http://textures.minecraft.net/texture/abc".into()),
|
||||
..Default::default()
|
||||
};
|
||||
let cape = super::cape(&textures).unwrap();
|
||||
assert_eq!(
|
||||
cape["capes/".len()..],
|
||||
super::skin_location("abc")["skins/".len()..]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_components_supply_unsigned_head_skins() {
|
||||
let value = "eyJ0ZXh0dXJlcyI6IHsiU0tJTiI6IHsidXJsIjogImh0dHBzOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlL2FiYzEyMyJ9fX0=";
|
||||
|
||||
@@ -6,7 +6,11 @@
|
||||
//! instance's random.
|
||||
use horizon_core::random::RandomSource;
|
||||
use serde_json::Value;
|
||||
use std::{collections::HashMap, fs, path::Path};
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
fs,
|
||||
path::Path,
|
||||
};
|
||||
|
||||
/// `SoundManager.EMPTY_SOUND_LOCATION`.
|
||||
pub const EMPTY: &str = "minecraft:empty";
|
||||
@@ -224,6 +228,34 @@ fn parse_sound(v: &Value) -> Option<Sound> {
|
||||
sentinel: Sentinel::None,
|
||||
})
|
||||
}
|
||||
/// The files under a namespace's `sounds/`, as `sounds/<path>` with `/`.
|
||||
fn sound_files(namespace: &Path) -> HashSet<String> {
|
||||
let mut files = HashSet::new();
|
||||
let mut stack = vec![namespace.join("sounds")];
|
||||
while let Some(dir) = stack.pop() {
|
||||
let Ok(entries) = fs::read_dir(&dir) else {
|
||||
continue;
|
||||
};
|
||||
for e in entries.flatten() {
|
||||
let path = e.path();
|
||||
// The listing's own type; a link is followed, as `is_file` does.
|
||||
let Ok(kind) = e.file_type() else {
|
||||
continue;
|
||||
};
|
||||
let (dir, file) = if kind.is_symlink() {
|
||||
(path.is_dir(), path.is_file())
|
||||
} else {
|
||||
(kind.is_dir(), kind.is_file())
|
||||
};
|
||||
if dir {
|
||||
stack.push(path);
|
||||
} else if file && let Ok(rel) = path.strip_prefix(namespace) {
|
||||
files.insert(rel.to_string_lossy().replace('\\', "/"));
|
||||
}
|
||||
}
|
||||
}
|
||||
files
|
||||
}
|
||||
impl SoundRegistry {
|
||||
/// Every `assets/<namespace>/sounds.json` under a resource root, files
|
||||
/// validated against `assets/<namespace>/sounds/`.
|
||||
@@ -236,13 +268,19 @@ impl SoundRegistry {
|
||||
.filter_map(|e| e.file_name().to_str().map(str::to_owned))
|
||||
.collect();
|
||||
namespaces.sort();
|
||||
// Each namespace's sound files are listed once, as the resource manager
|
||||
// lists a pack, instead of one file lookup per sound (thousands).
|
||||
let files: HashMap<&str, HashSet<String>> = namespaces
|
||||
.iter()
|
||||
.map(|ns| (ns.as_str(), sound_files(&assets.join(ns))))
|
||||
.collect();
|
||||
let exists = |ns: &str, path: &str| files.get(ns).is_some_and(|f| f.contains(path));
|
||||
let mut registry = Self::default();
|
||||
for namespace in namespaces {
|
||||
let Ok(text) = fs::read(assets.join(&namespace).join("sounds.json")) else {
|
||||
for namespace in &namespaces {
|
||||
let Ok(text) = fs::read(assets.join(namespace).join("sounds.json")) else {
|
||||
continue;
|
||||
};
|
||||
let exists = |ns: &str, path: &str| assets.join(ns).join(path).is_file();
|
||||
registry.add_file(&namespace, &text, &exists);
|
||||
registry.add_file(namespace, &text, &exists);
|
||||
}
|
||||
registry
|
||||
}
|
||||
@@ -369,6 +407,24 @@ mod tests {
|
||||
use super::*;
|
||||
use horizon_core::random::LegacyRandom;
|
||||
|
||||
#[test]
|
||||
fn load_keeps_the_sound_files_a_root_holds() {
|
||||
let root = std::env::temp_dir().join(format!("horizon-sounds-{}", std::process::id()));
|
||||
let ns = root.join("assets/minecraft");
|
||||
fs::create_dir_all(ns.join("sounds/block/note")).unwrap();
|
||||
fs::write(ns.join("sounds/block/note/harp.ogg"), b"").unwrap();
|
||||
fs::write(
|
||||
ns.join("sounds.json"),
|
||||
br#"{"note": {"sounds": ["block/note/harp", "block/note/gone"]}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let r = SoundRegistry::load(&root);
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
let sounds = &r.get("minecraft:note").unwrap().sounds;
|
||||
let kept: Vec<&str> = sounds.iter().map(|s| s.location.as_str()).collect();
|
||||
assert_eq!(kept, ["minecraft:block/note/harp"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_weigh_as_much_as_their_event() {
|
||||
let mut r = SoundRegistry::default();
|
||||
|
||||
@@ -24,6 +24,9 @@ struct Globals {
|
||||
outline_params: vec4<f32>,
|
||||
// Horizon Extras' dynamic lights: camera-relative position and level (dynamic_light.rs).
|
||||
dynamic_lights: array<vec4<f32>, 16>,
|
||||
// The sunrise fan's 16 triangles (gfx/sunrise_fan.rs): xyz the apex weight's normal, w the
|
||||
// triangle's volume with the camera; then each rim vertex's normal against the apex.
|
||||
sunrise_fan: array<vec4<f32>, 32>,
|
||||
}
|
||||
@group(0) @binding(0) var<uniform> globals: Globals;
|
||||
@group(0) @binding(1) var sprites: texture_2d_array<f32>;
|
||||
@@ -197,39 +200,26 @@ fn sky_fog(color: vec3<f32>, dist: vec2<f32>) -> vec3<f32> {
|
||||
let f = max(linear_fog(dist.x, 0.0, end), linear_fog(dist.y, end, end));
|
||||
return mix(color, globals.fog_color.rgb, f * globals.fog_color.a);
|
||||
}
|
||||
fn rotate_x90(v: vec3<f32>) -> vec3<f32> { return vec3(v.x, -v.z, v.y); }
|
||||
// Weight of the fan centre where the ray crosses the sunrise fan (0 when missed).
|
||||
// Weight of the fan centre where the ray crosses the sunrise fan (0 when missed):
|
||||
// Moller-Trumbore from the origin along d, over normals built once a frame
|
||||
// (gfx/sunrise_fan.rs). The barycentrics are apex/s, k1/s and -k0/s; s is -det.
|
||||
fn sunrise_weight(d: vec3<f32>) -> f32 {
|
||||
let alpha = globals.sunrise.a;
|
||||
if alpha <= 0.001 { return 0.0; }
|
||||
// sin(sunAngle) < 0 flips the fan to the other horizon; sun.z = -sin(sunAngle).
|
||||
let flip = select(0.0, 180.0, -globals.sun.z < 0.0);
|
||||
let theta = radians(flip + 90.0);
|
||||
let c = cos(theta);
|
||||
let s = sin(theta);
|
||||
if globals.sunrise.a <= 0.001 { return 0.0; }
|
||||
var best = 0.0;
|
||||
let apex = rotate_x90(vec3(-100.0 * s, 100.0 * c, 0.0));
|
||||
var k0 = dot(d, globals.sunrise_fan[16].xyz);
|
||||
for (var i = 0; i < 16; i++) {
|
||||
let a0 = f32(i) * 2.0 * PI / 16.0;
|
||||
let a1 = f32(i + 1) * 2.0 * PI / 16.0;
|
||||
let l0 = vec3(sin(a0) * 120.0, cos(a0) * 120.0, -cos(a0) * 40.0 * alpha);
|
||||
let l1 = vec3(sin(a1) * 120.0, cos(a1) * 120.0, -cos(a1) * 40.0 * alpha);
|
||||
let r0 = rotate_x90(vec3(l0.x * c - l0.y * s, l0.x * s + l0.y * c, l0.z));
|
||||
let r1 = rotate_x90(vec3(l1.x * c - l1.y * s, l1.x * s + l1.y * c, l1.z));
|
||||
// Moller-Trumbore from the origin along d.
|
||||
let e1 = r0 - apex;
|
||||
let e2 = r1 - apex;
|
||||
let pv = cross(d, e2);
|
||||
let det = dot(e1, pv);
|
||||
if abs(det) < 1e-6 { continue; }
|
||||
let tv = -apex;
|
||||
let u = dot(tv, pv) / det;
|
||||
let qv = cross(tv, e1);
|
||||
let v = dot(d, qv) / det;
|
||||
let t = dot(e2, qv) / det;
|
||||
if u >= 0.0 && v >= 0.0 && u + v <= 1.0 && t > 0.0 {
|
||||
best = max(best, 1.0 - u - v);
|
||||
let triangle = globals.sunrise_fan[i];
|
||||
let k1 = dot(d, globals.sunrise_fan[16 + (i + 1) % 16].xyz);
|
||||
// A hit needs s on the side of w, so k0 and k1 on either side of 0.
|
||||
if k0 * triangle.w <= 0.0 && k1 * triangle.w >= 0.0 {
|
||||
let apex = dot(d, triangle.xyz);
|
||||
let s = apex + k1 - k0;
|
||||
if abs(s) >= 1e-6 && s * triangle.w > 0.0 && apex * s >= 0.0 && k1 * s >= 0.0
|
||||
&& k0 * s <= 0.0 {
|
||||
best = max(best, apex / s);
|
||||
}
|
||||
}
|
||||
k0 = k1;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
@@ -79,27 +79,31 @@ pub fn load_metadata(root: &Path) {
|
||||
}
|
||||
*NINE_SLICE.write().unwrap_or_else(|e| e.into_inner()) = Some(map);
|
||||
}
|
||||
/// The sprite's nine-slice metadata; without any (no resources loaded), its
|
||||
/// GUI size and the widgets' usual borders.
|
||||
fn scaling(sprite: &str, r: &Rect) -> NineSlice {
|
||||
/// The sprite's nine-slice metadata, when its `.png.mcmeta` has any.
|
||||
fn nine_slice_metadata(sprite: &str) -> Option<NineSlice> {
|
||||
NINE_SLICE
|
||||
.read()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.as_ref()
|
||||
.and_then(|m| m.get(sprite).copied())
|
||||
.unwrap_or(NineSlice {
|
||||
width: r.w,
|
||||
height: r.h,
|
||||
border: match sprite {
|
||||
"gui/sprites/widget/button"
|
||||
| "gui/sprites/widget/button_highlighted"
|
||||
| "gui/sprites/widget/button_disabled" => [3; 4],
|
||||
"gui/sprites/widget/slider_handle"
|
||||
| "gui/sprites/widget/slider_handle_highlighted" => [2, 2, 2, 3],
|
||||
_ => [1; 4],
|
||||
},
|
||||
stretch_inner: false,
|
||||
})
|
||||
}
|
||||
/// The sprite's nine-slice metadata; without any (no resources loaded), its
|
||||
/// GUI size and the widgets' usual borders.
|
||||
fn scaling(sprite: &str, r: &Rect) -> NineSlice {
|
||||
nine_slice_metadata(sprite).unwrap_or(NineSlice {
|
||||
width: r.w,
|
||||
height: r.h,
|
||||
border: match sprite {
|
||||
"gui/sprites/widget/button"
|
||||
| "gui/sprites/widget/button_highlighted"
|
||||
| "gui/sprites/widget/button_disabled" => [3; 4],
|
||||
"gui/sprites/widget/slider_handle" | "gui/sprites/widget/slider_handle_highlighted" => {
|
||||
[2, 2, 2, 3]
|
||||
}
|
||||
_ => [1; 4],
|
||||
},
|
||||
stretch_inner: false,
|
||||
})
|
||||
}
|
||||
/// The region `[x, y, w, h]` of a sprite `size` GUI pixels large, in its
|
||||
/// own units (`TextureAtlasSprite.getU(x / width)`).
|
||||
@@ -152,6 +156,35 @@ pub fn nine_slice(
|
||||
draw_nine_slice(batch, *r, scaling(sprite, r), [x, y, w, h], color);
|
||||
}
|
||||
}
|
||||
/// `GuiGraphicsExtractor.blitSprite`: a sprite over `w` × `h` as its
|
||||
/// `gui.scaling` says, nine-sliced, or stretched when it has no metadata.
|
||||
/// (`tile`, which no vanilla sprite uses, isn't read yet: it stretches.)
|
||||
pub fn blit_sprite(
|
||||
batch: &mut HudBatch,
|
||||
atlas: &HudAtlas,
|
||||
sprite: &str,
|
||||
x: f32,
|
||||
y: f32,
|
||||
w: f32,
|
||||
h: f32,
|
||||
color: u32,
|
||||
) {
|
||||
if let Some(r) = atlas.sprites.get(sprite) {
|
||||
draw_sprite(batch, *r, nine_slice_metadata(sprite), [x, y, w, h], color);
|
||||
}
|
||||
}
|
||||
fn draw_sprite(
|
||||
batch: &mut HudBatch,
|
||||
r: Rect,
|
||||
nine_slice: Option<NineSlice>,
|
||||
[x, y, w, h]: [f32; 4],
|
||||
color: u32,
|
||||
) {
|
||||
match nine_slice {
|
||||
Some(n) => draw_nine_slice(batch, r, n, [x, y, w, h], color),
|
||||
None => batch.rect_uv(x, y, w, h, r, color),
|
||||
}
|
||||
}
|
||||
fn draw_nine_slice(
|
||||
batch: &mut HudBatch,
|
||||
r: Rect,
|
||||
@@ -1378,6 +1411,40 @@ mod tests {
|
||||
assert_quad(q[0], ([4.0, 4.0, 54.0, 54.0], [0.0, 0.0, 1.0, 1.0]));
|
||||
}
|
||||
#[test]
|
||||
fn blit_sprite_nine_slices_a_sprite_whose_metadata_says_so() {
|
||||
// Vanilla's tooltip/frame: 100x100, border 10, stretched centre.
|
||||
let n = faithful(
|
||||
r#"{"gui":{"scaling":{"type":"nine_slice","width":100,"height":100,"border":10,"stretch_inner":true}}}"#,
|
||||
);
|
||||
let mut batch = HudBatch::new([640, 480]);
|
||||
draw_sprite(
|
||||
&mut batch,
|
||||
sprite(100, 100),
|
||||
Some(n),
|
||||
[10.0, 10.0, 160.0, 26.0],
|
||||
u32::MAX,
|
||||
);
|
||||
let q = quads(&batch);
|
||||
assert_eq!(q.len(), 9);
|
||||
// The corners keep their 10 pixels instead of stretching with the box.
|
||||
assert_quad(q[0], ([10.0, 10.0, 20.0, 20.0], [0.0, 0.0, 0.1, 0.1]));
|
||||
assert_quad(q[5], ([160.0, 26.0, 170.0, 36.0], [0.9, 0.9, 1.0, 1.0]));
|
||||
}
|
||||
#[test]
|
||||
fn blit_sprite_stretches_a_sprite_without_metadata() {
|
||||
let mut batch = HudBatch::new([640, 480]);
|
||||
draw_sprite(
|
||||
&mut batch,
|
||||
sprite(9, 9),
|
||||
None,
|
||||
[0.0, 0.0, 27.0, 18.0],
|
||||
u32::MAX,
|
||||
);
|
||||
let q = quads(&batch);
|
||||
assert_eq!(q.len(), 1);
|
||||
assert_quad(q[0], ([0.0, 0.0, 27.0, 18.0], [0.0, 0.0, 1.0, 1.0]));
|
||||
}
|
||||
#[test]
|
||||
fn borders_shrink_to_half_the_drawn_size() {
|
||||
let n = NineSlice {
|
||||
width: 20,
|
||||
|
||||
@@ -55,3 +55,79 @@ fn luma(c: vec3<f32>) -> f32 {
|
||||
}
|
||||
return vec4(b, centre.a);
|
||||
}
|
||||
|
||||
// TAA (`world_post.rs`): blend this frame into the history, reprojected from the
|
||||
// depth buffer through the camera's motion and clamped to this frame's 3x3
|
||||
// neighbourhood so that what moved or appeared does not ghost.
|
||||
struct Taa {
|
||||
reproject: mat4x4<f32>,
|
||||
// xy: this frame's jitter in clip space; z: 1 when the history is unusable.
|
||||
jitter: vec4<f32>,
|
||||
};
|
||||
@group(0) @binding(2) var history: texture_2d<f32>;
|
||||
@group(0) @binding(3) var depth: texture_depth_2d;
|
||||
@group(0) @binding(4) var<uniform> taa: Taa;
|
||||
|
||||
// Catmull-Rom over the history in 5 bilinear taps: sharper than one under motion.
|
||||
fn sample_history(uv: vec2<f32>) -> vec3<f32> {
|
||||
let size = vec2<f32>(textureDimensions(history));
|
||||
let pos = uv * size;
|
||||
let centre = floor(pos - 0.5) + 0.5;
|
||||
let f = pos - centre;
|
||||
let w0 = f * (-0.5 + f * (1.0 - 0.5 * f));
|
||||
let w1 = 1.0 + f * f * (-2.5 + 1.5 * f);
|
||||
let w2 = f * (0.5 + f * (2.0 - 1.5 * f));
|
||||
let w3 = f * f * (-0.5 + 0.5 * f);
|
||||
let w12 = w1 + w2;
|
||||
let t0 = (centre - 1.0) / size;
|
||||
let t3 = (centre + 2.0) / size;
|
||||
let t12 = (centre + w2 / w12) / size;
|
||||
let c = textureSampleLevel(history, world_sampler, vec2(t12.x, t0.y), 0.0).rgb * (w12.x * w0.y)
|
||||
+ textureSampleLevel(history, world_sampler, vec2(t0.x, t12.y), 0.0).rgb * (w0.x * w12.y)
|
||||
+ textureSampleLevel(history, world_sampler, t12, 0.0).rgb * (w12.x * w12.y)
|
||||
+ textureSampleLevel(history, world_sampler, vec2(t3.x, t12.y), 0.0).rgb * (w3.x * w12.y)
|
||||
+ textureSampleLevel(history, world_sampler, vec2(t12.x, t3.y), 0.0).rgb * (w12.x * w3.y);
|
||||
let weight = w12.x * w0.y + w0.x * w12.y + w12.x * w12.y + w3.x * w12.y + w12.x * w3.y;
|
||||
return max(c / weight, vec3(0.0));
|
||||
}
|
||||
|
||||
// It runs at the history's size, which upscaling makes larger than the world's.
|
||||
// The history is unjittered: each output pixel takes the world pixel whose
|
||||
// jittered sample lands nearest its centre, weighted by how near it lands.
|
||||
@fragment fn fs_taa(in: PostOut) -> @location(0) vec4<f32> {
|
||||
let size = vec2<f32>(textureDimensions(world));
|
||||
// The jitter moved the scene by `jitter` in clip space: where this pixel's
|
||||
// point was drawn, in world pixels.
|
||||
let drawn = (in.uv + taa.jitter.xy * vec2(0.5, -0.5)) * size;
|
||||
let last = vec2<i32>(size) - 1;
|
||||
let p = clamp(vec2<i32>(floor(drawn)), vec2(0), last);
|
||||
let centre = textureLoad(world, p, 0);
|
||||
var lo = centre.rgb;
|
||||
var hi = centre.rgb;
|
||||
// Reversed depth: the nearest of the 3x3 is the largest, and its motion keeps
|
||||
// the edges of what is in front from trailing.
|
||||
var near = 0.0;
|
||||
for (var y = -1; y <= 1; y++) {
|
||||
for (var x = -1; x <= 1; x++) {
|
||||
let q = clamp(p + vec2(x, y), vec2(0), last);
|
||||
let c = textureLoad(world, q, 0).rgb;
|
||||
lo = min(lo, c);
|
||||
hi = max(hi, c);
|
||||
near = max(near, textureLoad(depth, q, 0));
|
||||
}
|
||||
}
|
||||
let ndc = vec2(in.uv.x * 2.0 - 1.0, 1.0 - in.uv.y * 2.0);
|
||||
let previous = taa.reproject * vec4(ndc, near, 1.0);
|
||||
let uv = vec2(0.5, -0.5) * previous.xy / previous.w + 0.5;
|
||||
if taa.jitter.z > 0.0 || any(uv != clamp(uv, vec2(0.0), vec2(1.0))) {
|
||||
return vec4(centre.rgb, centre.a);
|
||||
}
|
||||
let past = clamp(sample_history(uv), lo, hi);
|
||||
// How far the sample landed from this pixel's centre, in output pixels: a
|
||||
// Gaussian of it scales the new frame's share, so that frames whose sample
|
||||
// fell far away (most of them when upscaling) barely move the pixel.
|
||||
let off = (drawn - (vec2<f32>(p) + 0.5)) * vec2<f32>(textureDimensions(history)) / size;
|
||||
let share = 0.1 * exp(-2.0 * dot(off, off));
|
||||
// The alpha carries the emissive mark through to HDR output (hdr.wgsl).
|
||||
return vec4(mix(past, centre.rgb, share), centre.a);
|
||||
}
|
||||
@@ -302,7 +302,7 @@ fn avatar(c: &Value, out: &mut impl Write) -> Result<()> {
|
||||
for op in c["ops"].as_array().unwrap() {
|
||||
let name = op[0].as_str().unwrap();
|
||||
match name {
|
||||
"tick" => state.tick(),
|
||||
"tick" => state.tick([0.0; 3]),
|
||||
"move" => state.add_walked(fl(&op[1]), fl(&op[2])),
|
||||
"bob" => state.update_bob(b(&op[1]) && !b(&op[2]) && !b(&op[3]), vec3(&op[4])),
|
||||
"reset" => state.reset_bob(),
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Double chests for tools/test_chest_pair_parity.py: reads one JSON case per
|
||||
//! line (see VanillaChestPairOracle), a chest's block state at the origin and
|
||||
//! another block state at the offset "at", and prints what
|
||||
//! `horizon_client::containers::ChestHalf` pairs them into, as the game's
|
||||
//! menus and hoppers do: "double" with the right half's x,z then the left
|
||||
//! half's, or "single".
|
||||
//!
|
||||
//! usage: chest_pair_fixture INPUT OUTPUT
|
||||
use horizon_client::containers::{ChestHalf, is_chest_block};
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
|
||||
/// `minecraft:chest[facing=north,type=left]` as its name and properties.
|
||||
fn parse(state: &str) -> Option<(&str, BTreeMap<&str, &str>)> {
|
||||
let (name, props) = match state.split_once('[') {
|
||||
Some((name, rest)) => (name, rest.strip_suffix(']')?),
|
||||
None => (state, ""),
|
||||
};
|
||||
let props = props
|
||||
.split(',')
|
||||
.filter(|p| !p.is_empty())
|
||||
.map(|p| p.split_once('='))
|
||||
.collect::<Option<_>>()?;
|
||||
Some((name, props))
|
||||
}
|
||||
|
||||
fn half<'a>(name: &'a str, props: &BTreeMap<&str, &'a str>) -> Option<ChestHalf<'a>> {
|
||||
Some(ChestHalf {
|
||||
block: name,
|
||||
kind: props.get("type")?,
|
||||
facing: props.get("facing")?,
|
||||
})
|
||||
}
|
||||
|
||||
fn case(line: &str) -> Option<String> {
|
||||
let case: Value = serde_json::from_str(line).ok()?;
|
||||
let (name, props) = parse(case["state"].as_str()?)?;
|
||||
let (other_name, other_props) = parse(case["other"].as_str()?)?;
|
||||
let at = (
|
||||
i32::try_from(case["at"][0].as_i64()?).ok()?,
|
||||
i32::try_from(case["at"][1].as_i64()?).ok()?,
|
||||
);
|
||||
if !is_chest_block(name) {
|
||||
return None;
|
||||
}
|
||||
let own = half(name, &props)?;
|
||||
let paired = own.connected_step() == Some(at)
|
||||
&& half(other_name, &other_props).is_some_and(|other| own.pairs_with(&other));
|
||||
Some(if !paired {
|
||||
"single".to_owned()
|
||||
} else if own.kind == "right" {
|
||||
format!("double 0,0 {},{}", at.0, at.1)
|
||||
} else {
|
||||
format!("double {},{} 0,0", at.0, at.1)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn main() -> horizon_client::Result<()> {
|
||||
let args: Vec<String> = crate::args().collect();
|
||||
let input = fs::read_to_string(
|
||||
args.get(1)
|
||||
.ok_or("usage: chest_pair_fixture INPUT OUTPUT")?,
|
||||
)?;
|
||||
let lines: Vec<String> = input
|
||||
.lines()
|
||||
.map(|line| case(line).unwrap_or_else(|| "error".to_owned()))
|
||||
.collect();
|
||||
fs::write(
|
||||
args.get(2).ok_or("missing OUTPUT")?,
|
||||
lines.join("\n") + "\n",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! Container menu titles for tools/test_container_title_parity.py: reads one
|
||||
//! JSON case per line (see VanillaContainerTitleOracle) and prints the title
|
||||
//! the server opens the container's menu with, as canonical NBT. A single
|
||||
//! block entity is placed as the game places it (`block_entity_item::place`,
|
||||
//! whose `CustomName` the game keeps in `World::block_names`), then named by
|
||||
//! `containers::display_name`; a double chest's halves by
|
||||
//! `containers::double_chest_name`.
|
||||
//!
|
||||
//! usage: container_title_fixture INPUT OUTPUT
|
||||
use horizon_client::block_entity_item::place;
|
||||
use horizon_client::block_entity_nbt::canonical;
|
||||
use horizon_client::containers::{default_name_key, display_name, double_chest_name};
|
||||
use horizon_client::save::text;
|
||||
use horizon_world::nbt::{Tag, parse_snbt};
|
||||
use serde_json::Value;
|
||||
use std::fs;
|
||||
|
||||
/// ParityData.canon of a text component: sorted keys.
|
||||
fn canon(tag: &Tag, out: &mut String) {
|
||||
match tag {
|
||||
Tag::Compound(map) => {
|
||||
let mut keys: Vec<_> = map.iter().map(|(k, v)| (k.to_string_lossy(), v)).collect();
|
||||
keys.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
out.push('{');
|
||||
for (i, (k, v)) in keys.into_iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push(',');
|
||||
}
|
||||
out.push_str(&k);
|
||||
out.push(':');
|
||||
canon(v, out);
|
||||
}
|
||||
out.push('}');
|
||||
}
|
||||
Tag::List(items) => {
|
||||
out.push('[');
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push(',');
|
||||
}
|
||||
canon(item, out);
|
||||
}
|
||||
out.push(']');
|
||||
}
|
||||
other => out.push_str(&horizon_client::item_data::canon_tag(other)),
|
||||
}
|
||||
}
|
||||
|
||||
fn snbt(value: &Value) -> Option<Tag> {
|
||||
parse_snbt(value.as_str()?).ok().map(|(tag, _)| tag)
|
||||
}
|
||||
|
||||
/// The custom name the game keeps for a block entity saved as `value`.
|
||||
fn custom_name(value: &Value) -> Option<Option<String>> {
|
||||
let saved = canonical(&snbt(value)?)?;
|
||||
Some(text(saved.get("CustomName")))
|
||||
}
|
||||
|
||||
fn case(line: &str) -> Option<String> {
|
||||
let case: Value = serde_json::from_str(line).ok()?;
|
||||
let title = if let Some(first) = case.get("first") {
|
||||
let first = custom_name(first)?;
|
||||
let second = custom_name(&case["second"])?;
|
||||
double_chest_name(first.as_deref(), second.as_deref())
|
||||
} else {
|
||||
let saved = canonical(&snbt(&case["nbt"])?)?;
|
||||
// BlockItem.updateBlockEntityComponents, as Game::apply_placed_item runs it.
|
||||
let placed = match case.get("patch") {
|
||||
Some(p) => match snbt(p)? {
|
||||
Tag::Compound(patch) => place(&saved, &patch, true),
|
||||
_ => return None,
|
||||
},
|
||||
None => saved,
|
||||
};
|
||||
let key = default_name_key(case["block"].as_str()?)?;
|
||||
display_name(text(placed.get("CustomName")).as_deref(), key)
|
||||
};
|
||||
let mut out = String::new();
|
||||
canon(&title, &mut out);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
pub fn main() -> horizon_client::Result<()> {
|
||||
let args: Vec<String> = crate::args().collect();
|
||||
let input = fs::read_to_string(
|
||||
args.get(1)
|
||||
.ok_or("usage: container_title_fixture INPUT OUTPUT")?,
|
||||
)?;
|
||||
let lines: Vec<String> = input
|
||||
.lines()
|
||||
.map(|line| case(line).unwrap_or_else(|| "error".to_owned()))
|
||||
.collect();
|
||||
fs::write(
|
||||
args.get(2).ok_or("missing OUTPUT")?,
|
||||
lines.join("\n") + "\n",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -24,9 +24,11 @@ mod breaking_fixture;
|
||||
mod camera_probe;
|
||||
mod cauldron_fixture;
|
||||
mod chat_screen_fixture;
|
||||
mod chest_pair_fixture;
|
||||
mod cloud_fixture;
|
||||
mod command_parse_fixture;
|
||||
mod container_screen_probe;
|
||||
mod container_title_fixture;
|
||||
mod creative_mining_probe;
|
||||
mod creative_search_fixture;
|
||||
mod cushion_placement_probe;
|
||||
@@ -90,6 +92,7 @@ mod subtitle_fixture;
|
||||
mod tab_list_fixture;
|
||||
mod team_rules_fixture;
|
||||
mod text_display_fixture;
|
||||
mod text_display_render_fixture;
|
||||
mod toggle_keys_probe;
|
||||
mod tooltip_display_fixture;
|
||||
mod trading_fixture;
|
||||
@@ -115,9 +118,11 @@ probes! {
|
||||
cushion_placement_probe,
|
||||
cauldron_fixture,
|
||||
chat_screen_fixture,
|
||||
chest_pair_fixture,
|
||||
cloud_fixture,
|
||||
command_parse_fixture,
|
||||
container_screen_probe,
|
||||
container_title_fixture,
|
||||
creative_search_fixture,
|
||||
emitter_particles_probe,
|
||||
enchanting_fixture,
|
||||
@@ -180,6 +185,7 @@ probes! {
|
||||
toggle_keys_probe,
|
||||
tooltip_display_fixture,
|
||||
text_display_fixture,
|
||||
text_display_render_fixture,
|
||||
trading_fixture,
|
||||
translucency_fixture,
|
||||
weather_fixture,
|
||||
|
||||
@@ -67,8 +67,9 @@ struct Scenario {
|
||||
/// The player hits a mob for 1 at the start of a tick: (tick, mob index).
|
||||
hurts: Vec<(i32, usize)>,
|
||||
/// The player feeds an animal at the start of a tick (Animal.mobInteract):
|
||||
/// (tick, mob index); the scenario only feeds each animal its food.
|
||||
feeds: Vec<(i32, usize)>,
|
||||
/// (tick, mob index, None); the scenario only feeds each animal its food.
|
||||
/// `interact` uses another item on a horse: (tick, mob index, Some(item)).
|
||||
feeds: Vec<(i32, usize, Option<String>)>,
|
||||
hand: Option<String>,
|
||||
mobs: Vec<MobSpec>,
|
||||
}
|
||||
@@ -108,7 +109,14 @@ fn parse(text: &str) -> Vec<Scenario> {
|
||||
}
|
||||
"heart" => s.hearts.push(f.iter().map(|x| (*x).to_owned()).collect()),
|
||||
"hurt" => s.hurts.push((f[1].parse().unwrap(), f[2].parse().unwrap())),
|
||||
"feed" => s.feeds.push((f[1].parse().unwrap(), f[2].parse().unwrap())),
|
||||
"feed" => s
|
||||
.feeds
|
||||
.push((f[1].parse().unwrap(), f[2].parse().unwrap(), None)),
|
||||
"interact" => s.feeds.push((
|
||||
f[1].parse().unwrap(),
|
||||
f[2].parse().unwrap(),
|
||||
Some(f[3].to_owned()),
|
||||
)),
|
||||
"player" => {
|
||||
s.player = Some([
|
||||
f[1].parse().unwrap(),
|
||||
@@ -1209,10 +1217,22 @@ pub fn main() -> horizon_client::Result<()> {
|
||||
}
|
||||
events.append(&mut mobs[i].outbox);
|
||||
}
|
||||
for &(tick, i) in &s.feeds {
|
||||
for (tick, i, item) in &s.feeds {
|
||||
let (tick, i) = (*tick, *i);
|
||||
if tick != t || i >= mobs.len() || mobs[i].removed {
|
||||
continue;
|
||||
}
|
||||
// Horse.mobInteract's held-item branch (makeMad).
|
||||
if let Some(item) = item {
|
||||
horizon_client::mobs::equine::held_item(
|
||||
&mut mobs[i],
|
||||
item,
|
||||
false,
|
||||
item == "minecraft:golden_dandelion",
|
||||
&mut events,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if let Some(Some((name, volume, pitch))) =
|
||||
horizon_client::mobs::ai::feed_animal(&mut mobs[i], &mut level_random)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//! A text display's text for differential tests against vanilla's
|
||||
//! `TextDisplayRenderer.submitInner` (tools/test_text_display_render_parity.py):
|
||||
//! decodes each case's entity data from vanilla's wire bytes, lays the text out
|
||||
//! with `horizon_client::text_display` and prints the pose and every quad in
|
||||
//! text units [x, y, z, ARGB], as VanillaTextDisplayRenderOracle does.
|
||||
//!
|
||||
//! usage: text_display_render_fixture RESOURCES INPUTS OUTPUT
|
||||
use horizon_client::{
|
||||
hud::{HudAtlas, HudBatch},
|
||||
hud_layout::background_color,
|
||||
text_display::{self, Lines, TextDisplayData},
|
||||
};
|
||||
use horizon_protocol::{ids, packets::play::Clientbound};
|
||||
use serde_json::{Value, json};
|
||||
use std::{error::Error, io::Write};
|
||||
|
||||
pub fn main() -> Result<(), Box<dyn Error>> {
|
||||
let args: Vec<String> = crate::args().collect();
|
||||
let [_, resources, inputs, output] = args.as_slice() else {
|
||||
return Err("usage: text_display_render_fixture RESOURCES INPUTS OUTPUT".into());
|
||||
};
|
||||
let atlas = HudAtlas::build(std::path::Path::new(resources))?;
|
||||
let mut out = std::io::BufWriter::new(std::fs::File::create(output)?);
|
||||
for line in std::fs::read_to_string(inputs)?.lines() {
|
||||
let input: Value = serde_json::from_str(line)?;
|
||||
let hex = input["wire"].as_str().unwrap_or_default();
|
||||
let bytes: Vec<u8> = (0..hex.len())
|
||||
.step_by(2)
|
||||
.map(|i| u8::from_str_radix(&hex[i..i + 2], 16))
|
||||
.collect::<Result<_, _>>()?;
|
||||
let Clientbound::SetEntityData(packet) =
|
||||
Clientbound::decode(ids::play::clientbound::SET_ENTITY_DATA, &bytes)?
|
||||
else {
|
||||
return Err("not entity data".into());
|
||||
};
|
||||
let mut d = TextDisplayData::default();
|
||||
d.apply(&packet.values);
|
||||
let lines = Lines::split(&atlas.font, &d.text, d.line_width);
|
||||
let mut batch = HudBatch::new([1, 1]);
|
||||
let default_background = background_color(
|
||||
input["chat_only"].as_bool().unwrap_or(false),
|
||||
input["background_opacity"].as_f64().unwrap_or(0.0),
|
||||
0.25,
|
||||
);
|
||||
text_display::draw(&mut batch, &atlas, &d, &lines, default_background);
|
||||
let quads: Vec<Value> = batch
|
||||
.vertices
|
||||
.as_chunks::<6>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|q| {
|
||||
let corners: Vec<Value> = [0, 1, 2, 5]
|
||||
.map(|i| {
|
||||
let v = q[i];
|
||||
let [r, g, b, a] = v.color.to_le_bytes().map(u32::from);
|
||||
let argb = (a << 24 | r << 16 | g << 8 | b) as i32;
|
||||
json!([v.pos[0], v.pos[1], v.depth, argb])
|
||||
})
|
||||
.into();
|
||||
corners.into()
|
||||
})
|
||||
.collect();
|
||||
writeln!(
|
||||
out,
|
||||
"{}",
|
||||
json!({"pose": lines.pose().to_cols_array(), "quads": quads})
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -527,6 +527,53 @@ impl Creative {
|
||||
pub fn scroller_offset(&self) -> f32 {
|
||||
((Self::SCROLL_HEIGHT - 17.0) * self.scroll) as i32 as f32
|
||||
}
|
||||
/// The tabs whose `CreativeModeTab.contains(stack)` holds, in
|
||||
/// `CreativeModeTabs.tabs()` order, the search tab left out: the stack is
|
||||
/// among the tab's search-tab items, by item and components. The export
|
||||
/// lists each tab's own items; the search tab's stacks that no tab shows
|
||||
/// (the enchanted books below their top level, `SEARCH_TAB_ONLY`) belong
|
||||
/// to the tabs that show their item.
|
||||
pub fn tabs_containing(&self, stack: &ItemStack) -> Vec<usize> {
|
||||
let category = |t: &Tab| !t.search && !t.inventory;
|
||||
let tabs_where = |shows: &dyn Fn(&ItemStack) -> bool| -> Vec<usize> {
|
||||
(0..self.tabs.len())
|
||||
.filter(|&i| category(&self.tabs[i]) && self.tabs[i].items.iter().any(shows))
|
||||
.collect()
|
||||
};
|
||||
let found = tabs_where(&|s| same_components(s, stack));
|
||||
if found.is_empty() && self.search_items.iter().any(|s| same_components(s, stack)) {
|
||||
return tabs_where(&|s| s.item == stack.item);
|
||||
}
|
||||
found
|
||||
}
|
||||
/// The `#namespace:path` lines `getTooltipFromContainerItem` adds for a
|
||||
/// search tab stack while the search is a `#` query: the item tags
|
||||
/// `updateVisibleTags` keeps for the text after `#` (the path contains it;
|
||||
/// with a colon, the namespace and the path each contain their part) that
|
||||
/// the stack has.
|
||||
pub fn search_tag_lines(&self, stack: &ItemStack) -> Vec<String> {
|
||||
let Some(text) = self.search.value.strip_prefix('#') else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(entry) = self
|
||||
.search_items
|
||||
.iter()
|
||||
.position(|s| same_components(s, stack))
|
||||
.and_then(|i| self.search_index.get(i))
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let visible = |(ns, path): &(String, String)| match text.split_once(':') {
|
||||
None => path.contains(text),
|
||||
Some((n, p)) => ns.contains(java_trim(n)) && path.contains(java_trim(p)),
|
||||
};
|
||||
entry
|
||||
.tags
|
||||
.iter()
|
||||
.filter(|t| visible(t))
|
||||
.map(|(ns, path)| format!("#{ns}:{path}"))
|
||||
.collect()
|
||||
}
|
||||
/// Tab button position relative to the screen origin (CreativeModeInventoryScreen.getTabX/Y).
|
||||
pub fn tab_position(tab: &Tab) -> (f32, f32) {
|
||||
let mut x = tab.column as f32 * 27.0;
|
||||
@@ -543,6 +590,21 @@ impl Creative {
|
||||
fn any<'a>(strings: impl IntoIterator<Item = &'a str>, text: &str) -> bool {
|
||||
strings.into_iter().any(|s| s.contains(text))
|
||||
}
|
||||
/// `ItemStack.isSameItemSameComponents`, the count left out, as the
|
||||
/// tabs' `ItemStackLinkedSet` compares: no components and empty ones match.
|
||||
fn same_components(a: &ItemStack, b: &ItemStack) -> bool {
|
||||
let none = crate::item_data::StackData::default();
|
||||
a.item == b.item
|
||||
&& a.damage == b.damage
|
||||
&& a.data().unwrap_or(&none) == b.data().unwrap_or(&none)
|
||||
}
|
||||
/// `CreativeModeInventoryScreen.getTooltipFromContainerItem`: the plain
|
||||
/// tooltip only for a category tab's own grid slots (`CustomCreativeSlot`);
|
||||
/// everywhere else in the screen the tab names (and, on the search tab's
|
||||
/// grid, the tag lines) follow the item's name.
|
||||
pub fn tooltip_lists_tabs(category_tab: bool, grid_slot: bool) -> bool {
|
||||
!(category_tab && grid_slot)
|
||||
}
|
||||
/// String.toLowerCase(Locale.ROOT).
|
||||
fn java_lower(s: &str) -> String {
|
||||
s.to_lowercase()
|
||||
@@ -690,6 +752,109 @@ mod tests {
|
||||
(carried, effect)
|
||||
}
|
||||
|
||||
/// Tabs as the export lists them: two block tabs sharing the oak log,
|
||||
/// ingredients with the top-level book only, the search tab with every
|
||||
/// stack (a level 1 book only there) and its tags, the inventory.
|
||||
fn tooltip_tabs() -> Creative {
|
||||
let book = |level: u8| {
|
||||
format!(
|
||||
r#"{{components:{{"minecraft:stored_enchantments":{{"minecraft:sharpness":{level}}}}},count:1,id:"minecraft:enchanted_book"}}"#
|
||||
)
|
||||
};
|
||||
let log = r#"{count:1,id:"minecraft:oak_log"}"#;
|
||||
let dirt = r#"{count:1,id:"minecraft:dirt"}"#;
|
||||
let tab = |id: &str, kind: &str, items: Vec<String>| serde_json::json!({"id": id, "type": kind, "title": id, "icon": log, "items": items});
|
||||
let mut search = tab(
|
||||
"minecraft:search",
|
||||
"SEARCH",
|
||||
vec![log.into(), dirt.into(), book(1), book(5)],
|
||||
);
|
||||
search["lines"] = serde_json::json!([[], [], [], []]);
|
||||
search["tags"] = serde_json::json!([
|
||||
[
|
||||
"minecraft:logs",
|
||||
"minecraft:oak_logs",
|
||||
"minecraft:logs_that_burn"
|
||||
],
|
||||
["minecraft:dirt"],
|
||||
[],
|
||||
[]
|
||||
]);
|
||||
Creative::from_json(&serde_json::json!({"tabs": [
|
||||
tab("minecraft:building_blocks", "CATEGORY", vec![log.into()]),
|
||||
tab("minecraft:natural_blocks", "CATEGORY", vec![log.into(), dirt.into()]),
|
||||
tab("minecraft:hotbar", "HOTBAR", vec![]),
|
||||
search,
|
||||
tab("minecraft:ingredients", "CATEGORY", vec![book(5)]),
|
||||
tab("minecraft:inventory", "INVENTORY", vec![]),
|
||||
]}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tooltip_lists_the_tabs_that_contain_the_stack() {
|
||||
let c = tooltip_tabs();
|
||||
let ids = |s: &ItemStack| -> Vec<&str> {
|
||||
c.tabs_containing(s)
|
||||
.into_iter()
|
||||
.map(|i| c.tabs[i].id.as_str())
|
||||
.collect()
|
||||
};
|
||||
// In tab order, the search and inventory tabs left out; the count
|
||||
// doesn't matter.
|
||||
assert_eq!(
|
||||
ids(&stack("oak_log", 37)),
|
||||
["minecraft:building_blocks", "minecraft:natural_blocks"]
|
||||
);
|
||||
assert_eq!(ids(&stack("dirt", 1)), ["minecraft:natural_blocks"]);
|
||||
// A stack no tab holds: other components, or no creative item.
|
||||
let mut damaged = stack("oak_log", 1);
|
||||
damaged.damage = 3;
|
||||
assert!(ids(&damaged).is_empty());
|
||||
assert!(ids(&stack("barrier", 1)).is_empty());
|
||||
// A level 1 book is a search-tab-only stack of the ingredients tab.
|
||||
let books: Vec<&ItemStack> = c
|
||||
.search_items()
|
||||
.iter()
|
||||
.filter(|s| &*s.item == "minecraft:enchanted_book")
|
||||
.collect();
|
||||
assert_eq!(ids(books[0]), ["minecraft:ingredients"]);
|
||||
assert_eq!(ids(books[1]), ["minecraft:ingredients"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tooltip_tab_names_skip_only_a_category_tab_grid() {
|
||||
assert!(!tooltip_lists_tabs(true, true));
|
||||
// The hotbar row of a category tab, the search tab's grid and hotbar,
|
||||
// the inventory tab.
|
||||
assert!(tooltip_lists_tabs(true, false));
|
||||
assert!(tooltip_lists_tabs(false, true));
|
||||
assert!(tooltip_lists_tabs(false, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tag_search_lists_the_matching_tags_of_the_stack() {
|
||||
let mut c = tooltip_tabs();
|
||||
let log = stack("oak_log", 1);
|
||||
assert!(c.search_tag_lines(&log).is_empty());
|
||||
c.search.set_value("logs");
|
||||
assert!(c.search_tag_lines(&log).is_empty());
|
||||
c.search.set_value("#logs");
|
||||
assert_eq!(
|
||||
c.search_tag_lines(&log),
|
||||
[
|
||||
"#minecraft:logs",
|
||||
"#minecraft:oak_logs",
|
||||
"#minecraft:logs_that_burn"
|
||||
]
|
||||
);
|
||||
c.search.set_value("#oak");
|
||||
assert_eq!(c.search_tag_lines(&log), ["#minecraft:oak_logs"]);
|
||||
c.search.set_value("#mine : burn");
|
||||
assert_eq!(c.search_tag_lines(&log), ["#minecraft:logs_that_burn"]);
|
||||
assert!(c.search_tag_lines(&stack("dirt", 1)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_tab_number_keys_swap_over_a_slot_before_typing() {
|
||||
let filled = Hover::Display { filled: true };
|
||||
|
||||
@@ -152,6 +152,14 @@ impl DebugCharts {
|
||||
}
|
||||
self.packet_tick = (self.packet_tick + 1) % 20;
|
||||
}
|
||||
/// Whether `draw` (or the lightmap view) puts something in the bottom
|
||||
/// left and the bottom right corner, for a `remote` server or not.
|
||||
pub fn corners(&self, remote: bool) -> [bool; 2] {
|
||||
[
|
||||
self.fps || (self.network && remote),
|
||||
(self.fps && !self.tick_times.is_empty()) || self.network || self.lightmap,
|
||||
]
|
||||
}
|
||||
/// The charts along the bottom of the screen (`extractRenderState`):
|
||||
/// frame times left and tick times right, or bandwidth left (remote
|
||||
/// servers only) and ping right. `mspt` is the level's milliseconds
|
||||
@@ -525,6 +533,26 @@ mod tests {
|
||||
assert!(overlay && c.fps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corners_are_where_the_charts_are_drawn() {
|
||||
let mut c = DebugCharts::default();
|
||||
assert_eq!(c.corners(true), [false, false]);
|
||||
// Frame times left; tick times right once the server logged a tick.
|
||||
c.fps = true;
|
||||
assert_eq!(c.corners(false), [true, false]);
|
||||
c.tick_times.log(1);
|
||||
assert_eq!(c.corners(false), [true, true]);
|
||||
// Ping right; bandwidth left on a remote server only.
|
||||
c.fps = false;
|
||||
c.network = true;
|
||||
assert_eq!(c.corners(false), [false, true]);
|
||||
assert_eq!(c.corners(true), [true, true]);
|
||||
// The lightmap view, bottom right.
|
||||
c.network = false;
|
||||
c.lightmap = true;
|
||||
assert_eq!(c.corners(true), [false, true]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lightmap_puts_full_sky_light_at_the_top_left() {
|
||||
let mut pixels = [0u8; 16 * 16 * 4];
|
||||
|
||||
@@ -953,7 +953,20 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
|
||||
continue;
|
||||
};
|
||||
let v = f64::from_bits(*bits);
|
||||
// A mount's rolled health and speed stay attribute bases, which
|
||||
// the server syncs (its hearts over the rider's hotbar).
|
||||
let equine = crate::mobs::equine::is_equine(m.species());
|
||||
match id.as_str() {
|
||||
"minecraft:max_health" if equine => crate::mobs::finalize::set_base(
|
||||
&mut m,
|
||||
crate::mobs::finalize::Attr::MaxHealth,
|
||||
v,
|
||||
),
|
||||
"minecraft:movement_speed" if equine => crate::mobs::finalize::set_base(
|
||||
&mut m,
|
||||
crate::mobs::finalize::Attr::MovementSpeed,
|
||||
v,
|
||||
),
|
||||
"minecraft:max_health" => m.attrs.max_health = v as f32,
|
||||
"minecraft:movement_speed" => m.attrs.speed = v,
|
||||
"minecraft:attack_damage" => m.attrs.attack_damage = v as f32,
|
||||
@@ -1692,6 +1705,33 @@ pub fn fireball_from_nbt(tag: &Tag, player: Option<[i32; 4]>) -> Option<Projecti
|
||||
Some(p)
|
||||
}
|
||||
|
||||
/// `FireworkRocketEntity.readAdditionalSaveData`: Life, LifeTime (0 when
|
||||
/// absent: a bare `/summon` explodes at once), FireworksItem and
|
||||
/// ShotAtAngle, with `Projectile`'s Owner and LeftOwner.
|
||||
pub struct RocketNbt {
|
||||
pub position: Vec3,
|
||||
pub motion: Vec3,
|
||||
pub life: i32,
|
||||
pub lifetime: i32,
|
||||
pub item: Option<crate::items::ItemStack>,
|
||||
pub angled: bool,
|
||||
pub owner: Option<Who>,
|
||||
pub left_owner: bool,
|
||||
}
|
||||
pub fn firework_rocket_from_nbt(tag: &Tag, player: Option<[i32; 4]>) -> Option<RocketNbt> {
|
||||
let owner = uuid_from_tag(tag.get("Owner"));
|
||||
Some(RocketNbt {
|
||||
position: position(tag)?,
|
||||
motion: motion(tag),
|
||||
life: number(tag.get("Life")).unwrap_or(0) as i32,
|
||||
lifetime: number(tag.get("LifeTime")).unwrap_or(0) as i32,
|
||||
item: tag.get("FireworksItem").and_then(item_from_nbt),
|
||||
angled: flag(tag, "ShotAtAngle"),
|
||||
owner: (player.is_some() && owner == player).then_some(Who::Player),
|
||||
left_owner: flag(tag, "LeftOwner"),
|
||||
})
|
||||
}
|
||||
|
||||
/// `FallingBlockEntity`: BlockState, Time, DropItem, HurtEntities.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn falling_block_to_nbt(
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum ItemPose {
|
||||
Swing,
|
||||
/// A STAB swing (`SwingAnimationType` 2): a spear's jab.
|
||||
Stab,
|
||||
Using,
|
||||
Eat {
|
||||
remaining: f32,
|
||||
@@ -86,6 +88,9 @@ pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) -
|
||||
return Mat4::from_translation(Vec3::new(invert * 0.56, -0.52, -0.72))
|
||||
* crate::spear::first_person_use(&kinetic, ticks_since_hit, time_held, !left);
|
||||
}
|
||||
if matches!(pose, ItemPose::Stab) {
|
||||
return m * crate::spear::first_person_attack(attack, !left);
|
||||
}
|
||||
if matches!(pose, ItemPose::SpinAttack) {
|
||||
return m
|
||||
* Mat4::from_translation(Vec3::new(invert * -0.4, 0.8, 0.3))
|
||||
@@ -172,8 +177,94 @@ impl MapHold {
|
||||
}
|
||||
}
|
||||
|
||||
/// `renderPlayerArm` up to `renderPlayerHand`: the pose of the bare `left`
|
||||
/// or right arm.
|
||||
pub fn player_arm_pose(left: bool, inverse_height: f32, attack: f32) -> glam::Mat4 {
|
||||
use glam::{Mat4, Vec3};
|
||||
use horizon_core::geometry::trig::Mth;
|
||||
let f = if left { -1.0 } else { 1.0 };
|
||||
let pi = std::f32::consts::PI;
|
||||
let root = attack.sqrt();
|
||||
let x = -0.3 * (root * pi).msin();
|
||||
let y = 0.4 * (root * std::f32::consts::TAU).msin();
|
||||
let z = -0.4 * (attack * pi).msin();
|
||||
let z_rot = (attack * attack * pi).msin();
|
||||
let y_rot = (root * pi).msin();
|
||||
let deg = |d: f32| d.to_radians();
|
||||
Mat4::from_translation(Vec3::new(
|
||||
f * (x + 0.640_000_05),
|
||||
y - 0.6 + inverse_height * -0.6,
|
||||
z + -0.719_999_97,
|
||||
)) * Mat4::from_rotation_y(deg(f * 45.0))
|
||||
* Mat4::from_rotation_y(deg(f * y_rot * 70.0))
|
||||
* Mat4::from_rotation_z(deg(f * z_rot * -20.0))
|
||||
* Mat4::from_translation(Vec3::new(-f, 3.6, 3.5))
|
||||
* Mat4::from_rotation_z(deg(f * 120.0))
|
||||
* Mat4::from_rotation_x(deg(200.0))
|
||||
* Mat4::from_rotation_y(deg(f * -135.0))
|
||||
* Mat4::from_translation(Vec3::new(f * 5.6, 0.0, 0.0))
|
||||
}
|
||||
|
||||
/// `renderTwoHandedMap` up to its arms: the swing, the tilt from the view
|
||||
/// pitch (`calculateMapTilt`) and the turn towards the player.
|
||||
pub fn two_handed_map_base(pitch: f32, inverse_height: f32, attack: f32) -> glam::Mat4 {
|
||||
use glam::{Mat4, Vec3};
|
||||
use horizon_core::geometry::trig::Mth;
|
||||
let pi = std::f32::consts::PI;
|
||||
let y_swing = -0.2 * (attack * pi).msin();
|
||||
let z_swing = -0.4 * (attack.sqrt() * pi).msin();
|
||||
let tilt = (1.0 - pitch / 45.0 + 0.1).clamp(0.0, 1.0);
|
||||
let tilt = -(tilt * pi).mcos() * 0.5 + 0.5;
|
||||
Mat4::from_translation(Vec3::new(0.0, -y_swing / 2.0, z_swing))
|
||||
* Mat4::from_translation(Vec3::new(
|
||||
0.0,
|
||||
0.04 + inverse_height * -1.2 + tilt * -0.5,
|
||||
-0.72,
|
||||
))
|
||||
* Mat4::from_rotation_x((tilt * -85.0).to_radians())
|
||||
}
|
||||
|
||||
/// The arms under a held map, as (left arm, pose before `renderPlayerHand`):
|
||||
/// `renderOneHandedMap`'s arm turned 10 degrees outwards, or
|
||||
/// `renderTwoHandedMap`'s two `renderMapHand` arms under the map's
|
||||
/// `two_handed_map_base`. Vanilla skips them for an invisible player.
|
||||
pub fn map_arm_poses(
|
||||
hold: MapHold,
|
||||
left: bool,
|
||||
pitch: f32,
|
||||
inverse_height: f32,
|
||||
attack: f32,
|
||||
) -> Vec<(bool, glam::Mat4)> {
|
||||
use glam::{Mat4, Vec3};
|
||||
let deg = |d: f32| d.to_radians();
|
||||
match hold {
|
||||
MapHold::OneHanded => {
|
||||
let f = if left { -1.0 } else { 1.0 };
|
||||
let m = Mat4::from_translation(Vec3::new(f * 0.125, -0.125, 0.0))
|
||||
* Mat4::from_rotation_z(deg(f * 10.0))
|
||||
* player_arm_pose(left, inverse_height, attack);
|
||||
vec![(left, m)]
|
||||
}
|
||||
MapHold::TwoHanded => {
|
||||
let base = two_handed_map_base(pitch, inverse_height, attack)
|
||||
* Mat4::from_rotation_y(deg(90.0));
|
||||
[false, true]
|
||||
.into_iter()
|
||||
.map(|left| {
|
||||
let f = if left { -1.0 } else { 1.0 };
|
||||
let hand = Mat4::from_rotation_y(deg(92.0))
|
||||
* Mat4::from_rotation_x(deg(45.0))
|
||||
* Mat4::from_rotation_z(deg(f * -41.0))
|
||||
* Mat4::from_translation(Vec3::new(f * 0.3, -1.1, 0.45));
|
||||
(left, base * hand)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `renderOneHandedMap` up to `renderMap`: the pose of a map in the hand on
|
||||
/// the `left` or right arm (the arm under it is not drawn).
|
||||
/// the `left` or right arm (its arm: [`map_arm_poses`]).
|
||||
pub fn one_handed_map_pose(left: bool, inverse_height: f32, attack: f32) -> glam::Mat4 {
|
||||
use glam::{Mat4, Vec3};
|
||||
use horizon_core::geometry::trig::Mth;
|
||||
@@ -945,6 +1036,83 @@ mod item_pose_tests {
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn maps_draw_the_arms_under_them_as_vanilla() {
|
||||
// PoseStack.last().pose() (column-major) where renderOneHandedMap's
|
||||
// renderPlayerArm and renderTwoHandedMap's renderMapHand call
|
||||
// renderPlayerHand, replayed with vanilla's PoseStack, Axis and Mth.
|
||||
let near = |got: glam::Mat4, want: [f32; 16], what: &str| {
|
||||
let got = got.to_cols_array();
|
||||
for (g, w) in got.iter().zip(want) {
|
||||
assert!((g - w).abs() < 1e-5, "{what}: {got:?}");
|
||||
}
|
||||
};
|
||||
// (left, inverse height, attack, arm)
|
||||
#[rustfmt::skip]
|
||||
let one: [(bool, f32, f32, [f32; 16]); 3] = [
|
||||
(false, 0.0, 0.0, [
|
||||
-0.2350201, -0.7860474, -0.5717472, 0.0,
|
||||
0.24694103, 0.52063686, -0.8172866, 0.0,
|
||||
0.9400987, -0.33326668, 0.07174723, 0.0,
|
||||
0.65913033, -1.1543381, -0.73980355, 1.0,
|
||||
]),
|
||||
(true, 0.25, 0.3, [
|
||||
-0.4967606, 0.84289914, -0.20676011, 0.0,
|
||||
0.7202682, 0.2674863, -0.6400506, 0.0,
|
||||
-0.4841926, -0.46687466, -0.7399901, 0.0,
|
||||
-0.59715486, -1.4160433, -0.7328731, 1.0,
|
||||
]),
|
||||
(false, 0.6, 0.85, [
|
||||
-0.47358897, -0.8403256, -0.2637542, 0.0,
|
||||
0.081554025, 0.25634, -0.96313995, 0.0,
|
||||
0.87696207, -0.47764266, -0.052867785, 0.0,
|
||||
0.61887383, -1.6482887, -0.7229744, 1.0,
|
||||
]),
|
||||
];
|
||||
for (left, inverse_height, attack, want) in one {
|
||||
let arms = map_arm_poses(MapHold::OneHanded, left, 0.0, inverse_height, attack);
|
||||
assert_eq!(arms.len(), 1, "one arm under a one-handed map");
|
||||
assert_eq!(arms[0].0, left, "the arm of the hand holding it");
|
||||
near(
|
||||
arms[0].1,
|
||||
want,
|
||||
&format!("one {left} {inverse_height} {attack}"),
|
||||
);
|
||||
}
|
||||
// (pitch, inverse height, attack, right arm, left arm)
|
||||
#[rustfmt::skip]
|
||||
let two: [(f32, f32, f32, [f32; 16], [f32; 16]); 2] = [
|
||||
(0.0, 0.0, 0.0, [
|
||||
-0.7380599, 0.44766384, 0.50484115, 0.0,
|
||||
-0.67428374, -0.46198538, -0.57611704, 0.0,
|
||||
-0.024677532, -0.76561517, 0.64282537, 0.0,
|
||||
0.5091893, -0.16204369, 0.3544525, 1.0,
|
||||
], [
|
||||
-0.77043974, -0.3951866, -0.50025004, 0.0,
|
||||
0.637035, -0.5076031, -0.58010805, 0.0,
|
||||
-0.024677532, -0.76561517, 0.64282537, 0.0,
|
||||
-0.48071152, -0.12760738, 0.35746527, 1.0,
|
||||
]),
|
||||
(30.0, 0.2, 0.5, [
|
||||
-0.7380599, -0.11453738, 0.6649426, 0.0,
|
||||
-0.67428374, 0.16124588, -0.72065324, 0.0,
|
||||
-0.024677532, -0.98024535, -0.1962398, 0.0,
|
||||
0.5091893, -0.9508533, -0.13439482, 1.0,
|
||||
], [
|
||||
-0.77043974, 0.14373614, -0.6210978, 0.0,
|
||||
0.637035, 0.13586378, -0.75876695, 0.0,
|
||||
-0.024677532, -0.98024535, -0.1962398, 0.0,
|
||||
-0.48071152, -0.9316926, -0.1056232, 1.0,
|
||||
]),
|
||||
];
|
||||
for (pitch, inverse_height, attack, right, left) in two {
|
||||
let arms = map_arm_poses(MapHold::TwoHanded, false, pitch, inverse_height, attack);
|
||||
assert_eq!(arms.len(), 2, "both arms under a two-handed map");
|
||||
assert_eq!((arms[0].0, arms[1].0), (false, true), "right, then left");
|
||||
near(arms[0].1, right, &format!("two right {pitch}"));
|
||||
near(arms[1].1, left, &format!("two left {pitch}"));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn ranged_draw_uses_native_charge_curves_and_caps() {
|
||||
for (ticks, stretch) in [
|
||||
(0.0, 1.0),
|
||||
|
||||
+179
-102
@@ -1200,9 +1200,10 @@ struct WorldRest {
|
||||
nether_environment: Environment,
|
||||
end_environment: Environment,
|
||||
behaviours: Behaviours,
|
||||
player_arm: Option<horizon_client::mobs::Part>,
|
||||
/// The slim model's right arm (3 pixels wide).
|
||||
player_arm_slim: Option<horizon_client::mobs::Part>,
|
||||
/// The player model's right and left arms.
|
||||
player_arm: [Option<horizon_client::mobs::Part>; 2],
|
||||
/// The slim model's right and left arms (3 pixels wide).
|
||||
player_arm_slim: [Option<horizon_client::mobs::Part>; 2],
|
||||
player_type: Option<Arc<horizon_client::mobs::MobType>>,
|
||||
/// `SpinAttackEffectModel` (Riptide's spinning boxes).
|
||||
spin_attack: Option<horizon_client::mobs::Part>,
|
||||
@@ -1275,12 +1276,13 @@ impl Resources {
|
||||
fn threads(&self) -> usize {
|
||||
self.core.threads
|
||||
}
|
||||
fn player_arm(&self, slim: bool) -> &Option<horizon_client::mobs::Part> {
|
||||
if slim {
|
||||
fn player_arm(&self, slim: bool, left: bool) -> &Option<horizon_client::mobs::Part> {
|
||||
let arms = if slim {
|
||||
&self.rest().player_arm_slim
|
||||
} else {
|
||||
&self.rest().player_arm
|
||||
}
|
||||
};
|
||||
&arms[usize::from(left)]
|
||||
}
|
||||
fn player_type(&self) -> &Option<Arc<horizon_client::mobs::MobType>> {
|
||||
&self.rest().player_type
|
||||
@@ -1384,6 +1386,23 @@ fn ticking_chunk(world: &World, x: i32, z: i32) -> bool {
|
||||
world.chunks.get(&(x, z)).is_some_and(|c| c.lit)
|
||||
&& (-1..=1).all(|dz| (-1..=1).all(|dx| world.chunks.contains_key(&(x + dx, z + dz))))
|
||||
}
|
||||
/// Key events carry the scancode's US-layout code, which ignores XKB options like
|
||||
/// `caps:swapescape`. For the keys whose meaning the keymap may remap, take the code
|
||||
/// from the keysym the keymap resolved instead.
|
||||
fn follow_keymap(event: &mut WindowEvent) {
|
||||
use winit::keyboard::{Key, NamedKey};
|
||||
if let WindowEvent::KeyboardInput { event, .. } = event
|
||||
&& let Key::Named(named) = &event.logical_key
|
||||
{
|
||||
let code = match named {
|
||||
NamedKey::Escape => KeyCode::Escape,
|
||||
NamedKey::CapsLock => KeyCode::CapsLock,
|
||||
_ => return,
|
||||
};
|
||||
event.physical_key = PhysicalKey::Code(code);
|
||||
}
|
||||
}
|
||||
|
||||
fn drop_whole_stack(physical_keys: &HashSet<KeyCode>) -> bool {
|
||||
physical_keys.contains(&KeyCode::ControlLeft) || physical_keys.contains(&KeyCode::ControlRight)
|
||||
}
|
||||
@@ -1432,6 +1451,9 @@ struct Game<'a> {
|
||||
lod: Option<horizon_client::lod::Lod>,
|
||||
lod_source_attempted: bool,
|
||||
lod_observe: horizon_client::fast_hash::FxHashSet<(i32, i32)>,
|
||||
/// Beacon beam sections kept after their chunk unloads, so far terrain
|
||||
/// LOD still draws their beams (`beacon_geometry` refreshes them).
|
||||
far_beacons: HashMap<(i32, i32, i32), Vec<(u32, i32)>>,
|
||||
/// The detail revision, centre and radius `Lod::update` last had covered for.
|
||||
lod_covered_at: Option<(u64, (i32, i32), i32)>,
|
||||
options: Options,
|
||||
@@ -4215,8 +4237,15 @@ impl Game<'_> {
|
||||
}
|
||||
/// `Minecraft.startUseItem`: the main hand, then the off hand.
|
||||
fn use_item_as_player(&mut self) -> Result<Option<Hand>> {
|
||||
// Spectators only look (MultiPlayerGameMode.useItemOn/useItem pass).
|
||||
// Spectators only look (MultiPlayerGameMode.useItemOn/useItem pass),
|
||||
// but on a server a spectator's use on a block opens the block's
|
||||
// menu (ServerPlayerGameMode.useItemOn).
|
||||
if self.spectator() {
|
||||
if matches!(self.guest_use, Some(GuestUse::OnBlock(_)))
|
||||
&& let Some(hit) = self.pick()
|
||||
{
|
||||
self.spectator_open_menu(hit.pos);
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
// A carrot or warped fungus on a stick boosts the ridden pig or strider.
|
||||
@@ -4767,7 +4796,9 @@ impl Game<'_> {
|
||||
self.tick_crossbow(slot, ticks, &stack);
|
||||
return;
|
||||
}
|
||||
if &*stack.item == "minecraft:trident" {
|
||||
// TridentItem and EnderEyeItem: used until released (an eye's
|
||||
// getUseDuration 0 never counts down to finishUsingItem).
|
||||
if matches!(&*stack.item, "minecraft:trident" | "minecraft:ender_eye") {
|
||||
self.using = Some((slot, ticks + 1));
|
||||
return;
|
||||
}
|
||||
@@ -6633,9 +6664,15 @@ impl Game<'_> {
|
||||
}
|
||||
};
|
||||
part(batch, tex, 0.0, 0.0, 176.0, 166.0, ox, oy);
|
||||
let title = self.container_title(self.translate(key, fallback));
|
||||
let tw = HudBatch::text_width(atlas, &title);
|
||||
batch.text(
|
||||
// A server's furnace menu has the title it was given.
|
||||
let title = self.remote_menu_title().unwrap_or_else(|| {
|
||||
horizon_client::text::Text::literal(
|
||||
self.container_title(self.translate(key, fallback)),
|
||||
)
|
||||
.resolve_legacy()
|
||||
});
|
||||
let tw = atlas.font.width_text(&title);
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&title,
|
||||
ox + (176.0 - tw) / 2.0,
|
||||
@@ -7329,6 +7366,13 @@ impl Game<'_> {
|
||||
let at = [p.position.x, p.position.y, p.position.z];
|
||||
self.award_furnace_recipes(pos, at);
|
||||
}
|
||||
} else if self.creative_inventory_open() {
|
||||
// CreativeModeInventoryScreen.slotClicked's THROW on the Survival Inventory tab: the
|
||||
// stack goes to the server (handleCreativeModeItemDrop), the slot follows with the
|
||||
// others (SetCreativeModeSlot).
|
||||
for stack in dropped {
|
||||
self.remote_creative_throw(stack);
|
||||
}
|
||||
}
|
||||
if kind == Kind::Loom {
|
||||
if let Some(s) = self.station.as_mut() {
|
||||
@@ -7528,7 +7572,8 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
if let Some(moved) = self.last_quick_moved.clone() {
|
||||
if self.remote.is_some() {
|
||||
// The creative screen clicks its own menu, on a server too.
|
||||
if self.remote.is_some() && self.screen != Screen::Creative {
|
||||
self.remote_quick_move_all(slot, &moved);
|
||||
} else {
|
||||
self.menu_session(|menu, env, to_menu| {
|
||||
@@ -8068,7 +8113,7 @@ impl Game<'_> {
|
||||
for m in &self.mobs {
|
||||
// Blaze.isOnFire: a charged blaze burns.
|
||||
let blazing = m.species() == horizon_client::mobs::Species::Blaze && m.extra.flag;
|
||||
if (m.fire_ticks > 0 || blazing) && !m.removed {
|
||||
if (m.is_on_fire() || blazing) && !m.removed {
|
||||
let at = m.previous.lerp(m.position, alpha);
|
||||
horizon_client::fire_render::flames(
|
||||
[at.x, at.y, at.z],
|
||||
@@ -8200,11 +8245,8 @@ impl Game<'_> {
|
||||
p.z + (q.z - p.z) * a,
|
||||
)
|
||||
};
|
||||
let mut casters: Vec<(glam::DVec3, &str)> = self
|
||||
.mobs
|
||||
.iter()
|
||||
.map(|m| (lerp(m.previous, m.position), m.kind.id.as_str()))
|
||||
.collect();
|
||||
let mut casters: Vec<(glam::DVec3, &str)> =
|
||||
horizon_client::shadows::mob_casters(&self.mobs, a).collect();
|
||||
casters.extend(
|
||||
self.dropped
|
||||
.iter()
|
||||
@@ -10621,6 +10663,36 @@ impl Game<'_> {
|
||||
}
|
||||
self.damage_held(1);
|
||||
}
|
||||
/// `renderPlayerHand` (`AvatarRenderer.renderHand`): the player's own
|
||||
/// `left` or right arm with its skin at pose `m`, in its rest pose
|
||||
/// turned 0.1 radians outwards.
|
||||
fn first_person_arm(&self, left: bool, m: glam::Mat4, light: u32, out: &mut Vec<Vertex>) {
|
||||
let slim = self.player_model.as_ref().is_some_and(|m| m.slim);
|
||||
let Some(arm) = self.res.player_arm(slim, left).as_ref() else {
|
||||
return;
|
||||
};
|
||||
// The player's own skin, as the inventory's model shows it.
|
||||
let sprites = &self.gui.atlas.sprites;
|
||||
let Some(r) = self
|
||||
.player_model
|
||||
.as_ref()
|
||||
.and_then(|m| m.skin.as_deref())
|
||||
.and_then(|skin| sprites.get(skin))
|
||||
.or_else(|| sprites.get("entity/player/wide/steve"))
|
||||
.copied()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let z_rot = if left { -0.1 } else { 0.1 };
|
||||
let pose = |p: &horizon_client::mobs::Part| {
|
||||
let mut pose = p.pose;
|
||||
pose[3] = 0.0;
|
||||
pose[4] = 0.0;
|
||||
pose[5] = if p.name == arm.name { z_rot } else { 0.0 };
|
||||
pose
|
||||
};
|
||||
horizon_client::mobs::render_model(arm, m, &pose, [r.u0, r.v0, r.u1, r.v1], light, 0, out);
|
||||
}
|
||||
/// FirstPersonHandsAndItemsRenderer: the right arm or the held items of
|
||||
/// both hands in view space, converted to camera-relative world space.
|
||||
fn hand_geometry(&mut self, alpha: f64) -> Vec<Vertex> {
|
||||
@@ -10664,7 +10736,6 @@ impl Game<'_> {
|
||||
eye[2].floor() as i32,
|
||||
);
|
||||
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
|
||||
let deg = |d: f32| d.to_radians();
|
||||
let shown = self.hands_to_render();
|
||||
let used_hand = self.used_hand();
|
||||
let spinning = self
|
||||
@@ -10678,7 +10749,6 @@ impl Game<'_> {
|
||||
continue;
|
||||
}
|
||||
let (attack, inverse_height) = (attacks[i], inverse_heights[i]);
|
||||
let sqrt_attack = attack.sqrt();
|
||||
// The main hand on its arm, the off hand on the other one.
|
||||
let left = self.settings.main_hand_left != (hand == Hand::Off);
|
||||
let Some(stack) = item else {
|
||||
@@ -10686,63 +10756,24 @@ impl Game<'_> {
|
||||
if hand == Hand::Off {
|
||||
continue;
|
||||
}
|
||||
let slim = self.player_model.as_ref().is_some_and(|m| m.slim);
|
||||
let Some(arm) = self.res.player_arm(slim).clone() else {
|
||||
continue;
|
||||
};
|
||||
// The player's own skin, as the inventory's model shows it.
|
||||
let sprites = &self.gui.atlas.sprites;
|
||||
let Some(r) = self
|
||||
.player_model
|
||||
.as_ref()
|
||||
.and_then(|m| m.skin.as_deref())
|
||||
.and_then(|skin| sprites.get(skin))
|
||||
.or_else(|| sprites.get("entity/player/wide/steve"))
|
||||
.copied()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
// renderPlayerArm (right arm)
|
||||
let x_swing = -0.3 * (sqrt_attack * std::f32::consts::PI).sin();
|
||||
let y_swing = 0.4 * (sqrt_attack * std::f32::consts::TAU).sin();
|
||||
let z_swing = -0.4 * (attack * std::f32::consts::PI).sin();
|
||||
let z_rot = (attack * attack * std::f32::consts::PI).sin();
|
||||
let y_rot = (sqrt_attack * std::f32::consts::PI).sin();
|
||||
let m = to_world
|
||||
* glam::Mat4::from_translation(glam::Vec3::new(
|
||||
x_swing + 0.64,
|
||||
y_swing - 0.6 + inverse_height * -0.6,
|
||||
z_swing - 0.72,
|
||||
))
|
||||
* glam::Mat4::from_rotation_y(deg(45.0))
|
||||
* glam::Mat4::from_rotation_y(deg(y_rot * 70.0))
|
||||
* glam::Mat4::from_rotation_z(deg(z_rot * -20.0))
|
||||
* glam::Mat4::from_translation(glam::Vec3::new(-1.0, 3.6, 3.5))
|
||||
* glam::Mat4::from_rotation_z(deg(120.0))
|
||||
* glam::Mat4::from_rotation_x(deg(200.0))
|
||||
* glam::Mat4::from_rotation_y(deg(-135.0))
|
||||
* glam::Mat4::from_translation(glam::Vec3::new(5.6, 0.0, 0.0));
|
||||
let pose = |p: &horizon_client::mobs::Part| {
|
||||
let mut pose = p.pose;
|
||||
pose[3] = 0.0;
|
||||
pose[4] = 0.0;
|
||||
pose[5] = 0.0;
|
||||
pose
|
||||
};
|
||||
horizon_client::mobs::render_model(
|
||||
&arm,
|
||||
m,
|
||||
&pose,
|
||||
[r.u0, r.v0, r.u1, r.v1],
|
||||
packed,
|
||||
0,
|
||||
&mut out,
|
||||
);
|
||||
* horizon_client::first_person::player_arm_pose(false, inverse_height, attack);
|
||||
self.first_person_arm(false, m, packed, &mut out);
|
||||
continue;
|
||||
};
|
||||
if let Some(id) = maps::map_id(&stack) {
|
||||
use horizon_client::first_person::{MapHold, one_handed_map_pose};
|
||||
match MapHold::of(hand, off_hand_empty) {
|
||||
use horizon_client::first_person::{MapHold, map_arm_poses, one_handed_map_pose};
|
||||
let hold = MapHold::of(hand, off_hand_empty);
|
||||
// renderOneHandedMap and renderTwoHandedMap: the arms under
|
||||
// the map, unless the player is invisible.
|
||||
if self.potions.effects.get("invisibility").is_none() {
|
||||
for (arm, pose) in map_arm_poses(hold, left, self.pitch, inverse_height, attack)
|
||||
{
|
||||
self.first_person_arm(arm, to_world * pose, packed, &mut out);
|
||||
}
|
||||
}
|
||||
match hold {
|
||||
MapHold::TwoHanded => self.two_handed_map_geometry(
|
||||
to_world,
|
||||
attack,
|
||||
@@ -10823,6 +10854,14 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
_ if spinning => ItemPose::SpinAttack,
|
||||
// ItemInHandRenderer: a STAB swing of this hand jabs.
|
||||
_ if self
|
||||
.swing
|
||||
.current
|
||||
.is_some_and(|c| c.hand == hand && c.animation.kind == 2) =>
|
||||
{
|
||||
ItemPose::Stab
|
||||
}
|
||||
_ => ItemPose::Swing,
|
||||
};
|
||||
let m = to_world
|
||||
@@ -11263,6 +11302,38 @@ impl Game<'_> {
|
||||
batch.fill(atlas, x - 3.0, y + 10.0, w + 6.0, 1.0, rgba(40, 0, 127, 80));
|
||||
batch.text(atlas, text, x, y, u32::MAX, true);
|
||||
}
|
||||
/// `CreativeModeInventoryScreen.getTooltipFromContainerItem`: the lines
|
||||
/// that follow the item's name, none for a category tab's own grid slots
|
||||
/// (`grid`): the names of the tabs containing the stack, in blue, then on
|
||||
/// the search tab's grid the tags a `#` search shows, in dark purple.
|
||||
fn creative_tooltip_tabs(
|
||||
&self,
|
||||
stack: &ItemStack,
|
||||
grid: bool,
|
||||
) -> Vec<(horizon_client::text::Text, u32)> {
|
||||
let screen = &self.creative_screen;
|
||||
let tab = screen.tab();
|
||||
let category = !tab.search && !tab.inventory;
|
||||
if !horizon_client::creative::tooltip_lists_tabs(category, grid) {
|
||||
return Vec::new();
|
||||
}
|
||||
let blue = rgba(85, 85, 255, 255);
|
||||
let dark_purple = rgba(170, 0, 170, 255);
|
||||
let mut lines: Vec<(horizon_client::text::Text, u32)> = screen
|
||||
.tabs_containing(stack)
|
||||
.into_iter()
|
||||
.map(|i| {
|
||||
let title = self.creative_tab_title(&screen.tabs[i]);
|
||||
(horizon_client::text::Text::literal(title), blue)
|
||||
})
|
||||
.collect();
|
||||
if tab.search && grid {
|
||||
for tag in screen.search_tag_lines(stack) {
|
||||
lines.push((horizon_client::text::Text::literal(tag), dark_purple));
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
fn draw_creative(&mut self, batch: &mut HudBatch) {
|
||||
let (ox, oy) = Self::creative_origin(batch);
|
||||
let selected = self.creative_screen.selected;
|
||||
@@ -11345,7 +11416,8 @@ impl Game<'_> {
|
||||
search.max_length = clipboard::CREATIVE_SEARCH_CHARS;
|
||||
search.draw(batch, atlas, None);
|
||||
}
|
||||
let mut hovered: Option<ItemStack> = None;
|
||||
// The hovered stack, and whether it is a grid slot (`CustomCreativeSlot`).
|
||||
let mut hovered: Option<(ItemStack, bool)> = None;
|
||||
if tab.inventory {
|
||||
self.draw_player_preview(
|
||||
batch,
|
||||
@@ -11395,7 +11467,7 @@ impl Game<'_> {
|
||||
&& self.cursor.1 < y + 16.0
|
||||
{
|
||||
batch.fill(&self.gui.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128));
|
||||
hovered = Some(stack.clone());
|
||||
hovered = Some((stack.clone(), true));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11409,7 +11481,7 @@ impl Game<'_> {
|
||||
&& self.cursor.1 < y + 16.0
|
||||
{
|
||||
batch.fill(&self.gui.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128));
|
||||
hovered = self.inventory[c].clone();
|
||||
hovered = self.inventory[c].clone().map(|s| (s, false));
|
||||
}
|
||||
}
|
||||
let scrollable = self.creative_screen.rows(&self.pack.names) > 5;
|
||||
@@ -11444,13 +11516,18 @@ impl Game<'_> {
|
||||
if tab.inventory {
|
||||
if Self::creative_trash_hovered(batch, self.cursor) {
|
||||
self.tooltip(batch, "Destroy Item", self.cursor.0, self.cursor.1);
|
||||
} else {
|
||||
self.draw_slot_tooltip(batch);
|
||||
} else if self.carried.is_none()
|
||||
&& let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1)
|
||||
&& let Some(stack) = self.slot_view(slot)
|
||||
{
|
||||
let tabs = self.creative_tooltip_tabs(&stack, false);
|
||||
self.draw_stack_tooltip_with(batch, &stack, self.cursor.0, self.cursor.1, tabs);
|
||||
}
|
||||
} else if self.carried.is_none()
|
||||
&& let Some(item) = hovered
|
||||
&& let Some((item, grid)) = hovered
|
||||
{
|
||||
self.draw_stack_tooltip(batch, &item, self.cursor.0, self.cursor.1);
|
||||
let tabs = self.creative_tooltip_tabs(&item, grid);
|
||||
self.draw_stack_tooltip_with(batch, &item, self.cursor.0, self.cursor.1, tabs);
|
||||
}
|
||||
self.draw_inventory_effects(batch, (ox, oy), Creative::WIDTH as i32);
|
||||
}
|
||||
@@ -11866,8 +11943,9 @@ impl Game<'_> {
|
||||
// GameRenderer.shouldRenderBlockOutline: not with the HUD hidden (F1), and only for a
|
||||
// player who may build. Adventure players only get one with a CAN_BREAK or
|
||||
// CAN_PLACE_ON item and spectators with a menu block; Horizon reads neither the
|
||||
// components nor opens menus for spectators, so those never show it.
|
||||
let outline = if self.screen == Screen::Playing && !self.ui.hide_gui && self.may_build() {
|
||||
// components nor opens menus for spectators, so those never show it. An open
|
||||
// screen does not hide it: vanilla checks the HUD and the game mode, not the screen.
|
||||
let outline = if !self.ui.hide_gui && self.may_build() {
|
||||
self.pick()
|
||||
.map(|h| {
|
||||
let state = self.world.block(h.pos[0], h.pos[1], h.pos[2]);
|
||||
@@ -12065,21 +12143,7 @@ impl Game<'_> {
|
||||
environment_fog: (self.dim == Dim::Nether).then_some((sky.fog_start, sky.fog_end)),
|
||||
cave_culling,
|
||||
water_fog,
|
||||
fog: Some({
|
||||
let mut fog = self.frame_fog(camera, &sky, biome, water_fog);
|
||||
// Horizon's fog setting: no distance fog (fluids keep theirs).
|
||||
if !self.settings.horizon.fog
|
||||
&& !underwater
|
||||
&& self.darkness_fog().is_none()
|
||||
&& !self.boss_overlay.should_create_world_fog()
|
||||
&& self.potions.effects.get("blindness").is_none()
|
||||
&& fog.environmental_end >= (self.streaming.radius * 16) as f32
|
||||
{
|
||||
(fog.render_distance_start, fog.render_distance_end) = (1e9, 2e9);
|
||||
(fog.environmental_start, fog.environmental_end) = (1e9, 2e9);
|
||||
}
|
||||
fog
|
||||
}),
|
||||
fog: Some(self.frame_fog(camera, &sky, biome, water_fog)),
|
||||
dark_disc: self.dark_disc(camera),
|
||||
outline,
|
||||
outline_after_terrain,
|
||||
@@ -12563,6 +12627,7 @@ impl Game<'_> {
|
||||
self.lod = None;
|
||||
self.lod_source_attempted = false;
|
||||
self.lod_observe.clear();
|
||||
self.far_beacons.clear();
|
||||
self.lod_covered_at = None;
|
||||
if let Some(renderer) = &mut self.renderer {
|
||||
renderer.clear_lods();
|
||||
@@ -12812,10 +12877,11 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.apply_settings();
|
||||
self.previous = Instant::now();
|
||||
}
|
||||
fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
|
||||
fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, mut event: WindowEvent) {
|
||||
if self.window.as_ref().is_none_or(|w| w.id() != id) {
|
||||
return;
|
||||
}
|
||||
follow_keymap(&mut event);
|
||||
if let WindowEvent::KeyboardInput { event, .. } = &event
|
||||
&& let PhysicalKey::Code(key) = event.physical_key
|
||||
{
|
||||
@@ -13931,6 +13997,7 @@ impl<'a> Game<'a> {
|
||||
streaming,
|
||||
lod: None,
|
||||
lod_source_attempted: false,
|
||||
far_beacons: HashMap::new(),
|
||||
lod_observe: Default::default(),
|
||||
lod_covered_at: None,
|
||||
options,
|
||||
@@ -14859,10 +14926,8 @@ fn load_world_rest(
|
||||
.collect(),
|
||||
mob_data,
|
||||
player_type: perspective::player_type(root),
|
||||
player_arm: horizon_client::mobs::load_model(root, "minecraft:player#main")
|
||||
.and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")),
|
||||
player_arm_slim: horizon_client::mobs::load_model(root, "minecraft:player_slim#main")
|
||||
.and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")),
|
||||
player_arm: player_arms(root, "minecraft:player#main"),
|
||||
player_arm_slim: player_arms(root, "minecraft:player_slim#main"),
|
||||
spin_attack: horizon_client::mobs::load_model(root, "minecraft:spin_attack#main"),
|
||||
})
|
||||
}
|
||||
@@ -15310,10 +15375,11 @@ impl Loading {
|
||||
horizon_client::hud::GUI_SCALE.store(self.settings.gui_scale, Ordering::Relaxed);
|
||||
self.window = Some(window);
|
||||
}
|
||||
fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
|
||||
fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, mut event: WindowEvent) {
|
||||
if self.window.as_ref().is_none_or(|w| w.id() != id) {
|
||||
return;
|
||||
}
|
||||
follow_keymap(&mut event);
|
||||
if let Err(error) = self.menu_event(event_loop, event) {
|
||||
self.error = Some(error);
|
||||
event_loop.exit();
|
||||
@@ -15708,6 +15774,17 @@ pub fn run() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The right and left arms of a player model layer (`PlayerModel.rightArm`
|
||||
/// and `leftArm`, with their sleeves).
|
||||
fn player_arms(root: &std::path::Path, key: &str) -> [Option<horizon_client::mobs::Part>; 2] {
|
||||
let model = horizon_client::mobs::load_model(root, key);
|
||||
["right_arm", "left_arm"].map(|name| {
|
||||
model
|
||||
.as_ref()
|
||||
.and_then(|m| m.children.iter().find(|c| c.name == name).cloned())
|
||||
})
|
||||
}
|
||||
|
||||
// Player.tick: cap the sleeping fade at 100, then fade out over 10 waking ticks.
|
||||
fn tick_sleep_timer(timer: u32, sleeping: bool) -> u32 {
|
||||
if sleeping {
|
||||
|
||||
@@ -588,10 +588,17 @@ impl Game<'_> {
|
||||
.announced
|
||||
.push(Text::translate(key, &[player, name]));
|
||||
}
|
||||
None => self.system_message(Text::translate(
|
||||
key,
|
||||
&[Text::literal(super::chat::PLAYER_NAME), name],
|
||||
)),
|
||||
None => {
|
||||
let text = Text::translate(key, &[self.player_display_text(), name]);
|
||||
// The guests hear of the host's advancement too.
|
||||
if let Some(host) = &self.lan {
|
||||
host.hub
|
||||
.system_message(horizon_client::lan::data::component_nbt(
|
||||
&text.component(),
|
||||
));
|
||||
}
|
||||
self.system_message(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -536,7 +536,9 @@ impl Game<'_> {
|
||||
title
|
||||
.recent_worlds()
|
||||
.iter()
|
||||
.map(|w| json!({ "folder": w.folder, "name": w.name, "creative": w.creative }))
|
||||
.map(
|
||||
|w| json!({ "folder": w.folder, "name": w.name, "creative": w.game_mode == 1 }),
|
||||
)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
match &title.mode {
|
||||
@@ -546,7 +548,7 @@ impl Game<'_> {
|
||||
selected,
|
||||
} => json!({
|
||||
"mode": "select-world",
|
||||
"worlds": list.iter().map(|w| json!({ "folder": w.folder, "name": w.name, "creative": w.creative })).collect::<Vec<_>>(),
|
||||
"worlds": list.iter().map(|w| json!({ "folder": w.folder, "name": w.name, "creative": w.game_mode == 1 })).collect::<Vec<_>>(),
|
||||
"selected": selected,
|
||||
}),
|
||||
Mode::Create {
|
||||
|
||||
@@ -616,9 +616,6 @@ impl Game<'_> {
|
||||
};
|
||||
for a in &self.armor_stands {
|
||||
let entity_start = out.len();
|
||||
if a.invisible {
|
||||
continue;
|
||||
}
|
||||
// ArmorStand.shouldRenderAtSqrDistance: 256 times the box's mean
|
||||
// edge (4 for a marker's empty box), whatever the entity distance.
|
||||
// LivingEntityRenderer grows the culling box by 0.5 for a dragon head.
|
||||
@@ -690,16 +687,20 @@ impl Game<'_> {
|
||||
a.position.z.floor() as i32,
|
||||
);
|
||||
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
|
||||
horizon_client::mobs::render::draw(
|
||||
model,
|
||||
base,
|
||||
&poses,
|
||||
wood,
|
||||
0xFFFF_FFFF,
|
||||
packed,
|
||||
0,
|
||||
out,
|
||||
);
|
||||
// LivingEntityRenderer.submit: an invisible stand has no body render type, but its
|
||||
// layers (held items, custom head, armour) are submitted all the same.
|
||||
if !a.invisible {
|
||||
horizon_client::mobs::render::draw(
|
||||
model,
|
||||
base,
|
||||
&poses,
|
||||
wood,
|
||||
0xFFFF_FFFF,
|
||||
packed,
|
||||
0,
|
||||
out,
|
||||
);
|
||||
}
|
||||
self.armor_stand_items(a, model, base, &posed, packed, out);
|
||||
// HumanoidArmorLayer: head, chest, legs, feet.
|
||||
for (slot, layer) in [
|
||||
|
||||
@@ -105,10 +105,28 @@ impl Game<'_> {
|
||||
let Some(BlockEntity::Beacon(mut b)) = self.world.block_entities.take(&key) else {
|
||||
return;
|
||||
};
|
||||
self.tick_beacon(key, &mut b);
|
||||
self.tick_beacon(key, &mut b, false);
|
||||
self.world.block_entities.put(key, BlockEntity::Beacon(b));
|
||||
}
|
||||
fn tick_beacon(&mut self, (x, y, z): (i32, i32, i32), b: &mut Beacon) {
|
||||
/// `ClientLevel.tickBlockEntities` for beacons: a server's chunk data
|
||||
/// carries no beam sections, so the client builds them too; effects,
|
||||
/// sounds and the advancement stay with the server.
|
||||
pub(super) fn client_tick_beacons(&mut self) {
|
||||
let keys: Vec<_> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter_map(|(k, e)| matches!(e, BlockEntity::Beacon(_)).then_some(*k))
|
||||
.collect();
|
||||
for key in keys {
|
||||
let Some(BlockEntity::Beacon(mut b)) = self.world.block_entities.take(&key) else {
|
||||
continue;
|
||||
};
|
||||
self.tick_beacon(key, &mut b, true);
|
||||
self.world.block_entities.put(key, BlockEntity::Beacon(b));
|
||||
}
|
||||
}
|
||||
fn tick_beacon(&mut self, (x, y, z): (i32, i32, i32), b: &mut Beacon, client: bool) {
|
||||
let mut check = if b.last_check_y < y {
|
||||
b.checking.clear();
|
||||
b.last_check_y = y - 1;
|
||||
@@ -153,7 +171,7 @@ impl Game<'_> {
|
||||
if !b.sections.is_empty() {
|
||||
b.levels = self.beacon_base(x, y, z);
|
||||
}
|
||||
if b.levels > 0 && !b.sections.is_empty() {
|
||||
if !client && b.levels > 0 && !b.sections.is_empty() {
|
||||
self.beacon_effects([x, y, z], b);
|
||||
self.beacon_sound([x, y, z], "minecraft:block.beacon.ambient");
|
||||
}
|
||||
@@ -163,10 +181,12 @@ impl Game<'_> {
|
||||
b.sections = std::mem::take(&mut b.checking);
|
||||
let (was, is) = (previous > 0, b.levels > 0);
|
||||
if !was && is {
|
||||
self.beacon_sound([x, y, z], "minecraft:block.beacon.activate");
|
||||
let levels = b.levels;
|
||||
self.for_each_player(|g| g.beacon_constructed([x, y, z], levels));
|
||||
} else if was && !is {
|
||||
if !client {
|
||||
self.beacon_sound([x, y, z], "minecraft:block.beacon.activate");
|
||||
let levels = b.levels;
|
||||
self.for_each_player(|g| g.beacon_constructed([x, y, z], levels));
|
||||
}
|
||||
} else if was && !is && !client {
|
||||
self.beacon_sound([x, y, z], "minecraft:block.beacon.deactivate");
|
||||
}
|
||||
}
|
||||
@@ -551,7 +571,12 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// `BeaconRenderer`: each section's rotating solid beam and its glow.
|
||||
pub(super) fn beacon_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
|
||||
pub(super) fn beacon_geometry(
|
||||
&mut self,
|
||||
camera: glam::DVec3,
|
||||
alpha: f64,
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
let Some(s) = self
|
||||
.gui
|
||||
.atlas
|
||||
@@ -563,15 +588,28 @@ impl Game<'_> {
|
||||
};
|
||||
let time = (self.world.game_time.rem_euclid(40)) as f32 + alpha as f32;
|
||||
let scoping = self.scoping();
|
||||
let view = f64::from(self.settings.render_distance * 16);
|
||||
for (k, e) in &self.world.block_entities {
|
||||
let BlockEntity::Beacon(b) = e else { continue };
|
||||
// `getBeamSections` is empty while Levels is 0.
|
||||
if b.levels == 0 || b.sections.is_empty() {
|
||||
continue;
|
||||
// `BeaconRenderer.shouldRender` culls at the render distance; far
|
||||
// terrain extends that to its own distance.
|
||||
let view = f64::from(self.terrain_distance() * 16);
|
||||
let world = &self.world;
|
||||
if self.lod.is_some() {
|
||||
// The beam stays after its chunk unloads; once the chunk is back,
|
||||
// its block entity decides whether the beam is still there.
|
||||
self.far_beacons.retain(|&pos, _| {
|
||||
let (x, _, z) = pos;
|
||||
!world.chunks.contains_key(&(x >> 4, z >> 4))
|
||||
|| world.block_entities.get(&pos).and_then(beam).is_some()
|
||||
});
|
||||
} else {
|
||||
self.far_beacons.clear();
|
||||
}
|
||||
for (k, e) in &world.block_entities {
|
||||
if let Some(sections) = beam(e) {
|
||||
self.far_beacons.insert(*k, sections.to_vec());
|
||||
}
|
||||
}
|
||||
for (k, sections) in &self.far_beacons {
|
||||
let base = glam::DVec3::new(f64::from(k.0) + 0.5, f64::from(k.1), f64::from(k.2) + 0.5);
|
||||
// `BeaconRenderer.shouldRender`: horizontal distance under render distance × 16.
|
||||
let offset = base - camera;
|
||||
let horizontal = glam::DVec2::new(offset.x, offset.z).length();
|
||||
if horizontal >= view {
|
||||
@@ -586,14 +624,30 @@ impl Game<'_> {
|
||||
let origin = (glam::DVec3::new(f64::from(k.0), f64::from(k.1), f64::from(k.2))
|
||||
- camera)
|
||||
.as_vec3();
|
||||
horizon_client::block_entity_render::beacon_beam(
|
||||
origin,
|
||||
&b.sections,
|
||||
time,
|
||||
scale,
|
||||
s,
|
||||
out,
|
||||
);
|
||||
horizon_client::block_entity_render::beacon_beam(origin, sections, time, scale, s, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The beam sections of an active beacon (`BeaconRenderer` draws no beam for
|
||||
/// a beacon without a pyramid or with all sections cleared).
|
||||
fn beam(e: &BlockEntity) -> Option<&[(u32, i32)]> {
|
||||
match e {
|
||||
BlockEntity::Beacon(b) if b.levels > 0 && !b.sections.is_empty() => Some(&b.sections),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn only_active_beacons_have_beams() {
|
||||
let mut b = Beacon::default();
|
||||
assert!(beam(&BlockEntity::Beacon(Box::new(b.clone()))).is_none());
|
||||
b.levels = 1;
|
||||
b.sections.push((0xFFFFFF, 10));
|
||||
assert_eq!(
|
||||
beam(&BlockEntity::Beacon(Box::new(b))),
|
||||
Some(&[(0xFFFFFF, 10)][..])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -658,15 +658,30 @@ impl Game<'_> {
|
||||
}
|
||||
/// `BoatItem.use`: aim at a block or the water surface.
|
||||
pub(super) fn place_boat(&mut self, stack: &ItemStack) -> bool {
|
||||
let Some((wood, chest)) = any_boat_wood(&stack.item) else {
|
||||
let Some(boat) = self.boat_to_place(stack) else {
|
||||
return false;
|
||||
};
|
||||
if !self.boat_models.has(wood, chest) {
|
||||
return false;
|
||||
self.next_entity += 1;
|
||||
let key = (
|
||||
boat.position.x.floor() as i32 >> 4,
|
||||
boat.position.z.floor() as i32 >> 4,
|
||||
);
|
||||
self.world.modified.insert(key);
|
||||
self.boats.push(boat);
|
||||
if !self.creative {
|
||||
self.consume_held();
|
||||
}
|
||||
let Some((eye, dir)) = self.aim() else {
|
||||
return false;
|
||||
};
|
||||
self.swing_arm();
|
||||
true
|
||||
}
|
||||
/// The boat `BoatItem.use` would place for `stack` (its SUCCESS), or
|
||||
/// None when it aims at nothing (PASS) or the spot is taken (FAIL).
|
||||
pub(super) fn boat_to_place(&self, stack: &ItemStack) -> Option<Boat> {
|
||||
let (wood, chest) = any_boat_wood(&stack.item)?;
|
||||
if !self.boat_models.has(wood, chest) {
|
||||
return None;
|
||||
}
|
||||
let (eye, dir) = self.aim()?;
|
||||
let reach = self.reach();
|
||||
// ClipContext.Fluid.ANY: the first fluid surface (water or lava) or
|
||||
// block along the ray.
|
||||
@@ -706,7 +721,7 @@ impl Game<'_> {
|
||||
}
|
||||
(Some(b), None) => b.0,
|
||||
(None, Some(w)) => w.0,
|
||||
(None, None) => return false,
|
||||
(None, None) => return None,
|
||||
};
|
||||
let mut boat = Boat::new(
|
||||
self.next_entity + 1,
|
||||
@@ -730,17 +745,9 @@ impl Game<'_> {
|
||||
subject: None,
|
||||
};
|
||||
if !scene.unobstructed(inner).unwrap_or(false) || self.boat_entity_collision(bb) {
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
self.next_entity += 1;
|
||||
let key = (hit[0].floor() as i32 >> 4, hit[2].floor() as i32 >> 4);
|
||||
self.world.modified.insert(key);
|
||||
self.boats.push(boat);
|
||||
if !self.creative {
|
||||
self.consume_held();
|
||||
}
|
||||
self.swing_arm();
|
||||
true
|
||||
Some(boat)
|
||||
}
|
||||
pub(super) fn boat_hit(&self) -> Option<(usize, f64)> {
|
||||
let (eye, dir) = self.aim()?;
|
||||
|
||||
@@ -95,6 +95,11 @@ impl Game<'_> {
|
||||
/// `BookViewScreen.mouseClicked`: the click event of the text under the
|
||||
/// cursor on the page.
|
||||
fn book_link_at(&self, page: &Text, left: f32) -> Option<horizon_client::text::ClickEvent> {
|
||||
self.book_style_at(page, left)?.click
|
||||
}
|
||||
/// `ActiveTextCollector` over the page: the style of the character
|
||||
/// under the cursor, for its click and hover events.
|
||||
fn book_style_at(&self, page: &Text, left: f32) -> Option<horizon_client::text::Style> {
|
||||
let (mx, my) = self.cursor;
|
||||
let row = ((my - 32.0) / 9.0).floor();
|
||||
if row < 0.0 || row >= LINES as f32 {
|
||||
@@ -109,7 +114,7 @@ impl Game<'_> {
|
||||
for (c, style) in line.chars() {
|
||||
x -= self.gui.atlas.font.advance(c, style);
|
||||
if x < 0.0 {
|
||||
return style.click.clone();
|
||||
return Some(style.clone());
|
||||
}
|
||||
}
|
||||
None
|
||||
@@ -139,22 +144,22 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
ClickEvent::OpenUrl(url) => self.click_url(url),
|
||||
ClickEvent::RunCommand(command) => self.click_command(&command),
|
||||
ClickEvent::SuggestCommand(command) => {
|
||||
// defaultHandleClickEvent: the chat screen takes it over.
|
||||
if self.player.is_some() {
|
||||
self.close_book();
|
||||
self.open_chat(&command);
|
||||
}
|
||||
// closeContainerOnServer, then clickCommandAction with no screen
|
||||
// after the command: the book closes and the command runs.
|
||||
ClickEvent::RunCommand(command) => {
|
||||
self.close_book();
|
||||
self.click_command(&command);
|
||||
}
|
||||
// Screen.defaultHandleClickEvent: copied, the book stays open.
|
||||
ClickEvent::CopyToClipboard(value) => {
|
||||
use horizon_client::clipboard::Clipboard;
|
||||
self.clipboard.set(&value);
|
||||
}
|
||||
// BookViewScreen.handleClickEvent: the rest is
|
||||
// Screen.defaultHandleGameClickEvent's.
|
||||
// defaultHandleGameClickEvent: the dialog opens over the book.
|
||||
ClickEvent::ShowDialog(dialog) => self.show_dialog_ref(&dialog),
|
||||
_ => {}
|
||||
// SuggestCommand's insertText does nothing on a book; a server's
|
||||
// text never opens a file.
|
||||
ClickEvent::SuggestCommand(_) | ClickEvent::OpenFile(_) => {}
|
||||
}
|
||||
}
|
||||
/// `WritableBookItem.use` / `WrittenBookItem.use` (`Player.openItemGui`).
|
||||
@@ -1314,6 +1319,16 @@ impl Game<'_> {
|
||||
true,
|
||||
);
|
||||
}
|
||||
// HoveredTextEffects.TOOLTIP_AND_CURSOR: the hovered words'
|
||||
// show_text hover event, as the chat shows it.
|
||||
if let Some(hover) = pages
|
||||
.get(*page)
|
||||
.and_then(|t| self.book_style_at(t, left))
|
||||
.and_then(|s| s.hover)
|
||||
{
|
||||
let lines = self.wrapped_rows(&hover, (w as i32 / 2).max(200));
|
||||
self.draw_tooltip_lines(batch, &lines, mx, my);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,11 @@ use horizon_client::{
|
||||
screen_draw::Measure,
|
||||
text::{ClickEvent, Style, Text},
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
path::{Path, PathBuf},
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
/// The tree the chat parses and completes with: a server's, once it has
|
||||
/// sent one (ClientPacketListener.commands), else the game's own.
|
||||
@@ -123,6 +127,64 @@ impl UiState {
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids `build_registries` lists from the prepared resources' folders.
|
||||
/// The folders don't change while the game runs, so each root is read once
|
||||
/// instead of at every world opening (thousands of files).
|
||||
struct ResourceIds {
|
||||
recipes: Vec<String>,
|
||||
damage_types: Vec<String>,
|
||||
loot_tables: Vec<String>,
|
||||
templates: Vec<String>,
|
||||
}
|
||||
static RESOURCE_IDS: Mutex<Vec<(PathBuf, Arc<ResourceIds>)>> = Mutex::new(Vec::new());
|
||||
|
||||
fn resource_ids(root: &Path) -> Arc<ResourceIds> {
|
||||
let mut cache = RESOURCE_IDS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some((_, ids)) = cache.iter().find(|(cached, _)| cached == root) {
|
||||
return ids.clone();
|
||||
}
|
||||
let data = root.join("data/minecraft");
|
||||
let ids = Arc::new(ResourceIds {
|
||||
recipes: ids_under(&data.join("recipe"), "json"),
|
||||
damage_types: ids_under(&data.join("damage_type"), "json"),
|
||||
loot_tables: ids_under(&data.join("loot_table"), "json"),
|
||||
templates: ids_under(&root.join("worldgen/structure/minecraft"), "nbt"),
|
||||
});
|
||||
cache.push((root.to_owned(), ids.clone()));
|
||||
ids
|
||||
}
|
||||
|
||||
/// The `minecraft:` ids of the `extension` files under `root`, sorted.
|
||||
fn ids_under(root: &Path, extension: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![root.to_owned()];
|
||||
while let Some(dir) = stack.pop() {
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else {
|
||||
continue;
|
||||
};
|
||||
for e in entries.flatten() {
|
||||
let path = e.path();
|
||||
// The listing's own type, without another look at each file; a
|
||||
// link is followed, as `Path::is_dir` does.
|
||||
let is_dir = e
|
||||
.file_type()
|
||||
.is_ok_and(|t| t.is_dir() || (t.is_symlink() && path.is_dir()));
|
||||
if is_dir {
|
||||
stack.push(path);
|
||||
} else if path.extension().and_then(|x| x.to_str()) == Some(extension)
|
||||
&& let Ok(rel) = path.strip_prefix(root)
|
||||
{
|
||||
out.push(format!(
|
||||
"minecraft:{}",
|
||||
rel.with_extension("").to_string_lossy().replace('\\', "/")
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `PlayerList.isOp` for the single-player owner: the world's Allow Commands.
|
||||
pub(super) fn allow_commands(&self) -> bool {
|
||||
@@ -146,61 +208,11 @@ impl Game<'_> {
|
||||
let permission = owner_permission(self.allow_commands());
|
||||
let reg = &mut self.ui.registries;
|
||||
reg.permission = permission;
|
||||
{
|
||||
let dir = |sub: &str| -> Vec<String> {
|
||||
let root = self.options.resources.join("data/minecraft").join(sub);
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![root.clone()];
|
||||
while let Some(d) = stack.pop() {
|
||||
let Ok(entries) = std::fs::read_dir(&d) else {
|
||||
continue;
|
||||
};
|
||||
for e in entries.flatten() {
|
||||
let p = e.path();
|
||||
if p.is_dir() {
|
||||
stack.push(p);
|
||||
} else if p.extension().and_then(|x| x.to_str()) == Some("json")
|
||||
&& let Ok(rel) = p.strip_prefix(&root)
|
||||
{
|
||||
out.push(format!(
|
||||
"minecraft:{}",
|
||||
rel.with_extension("").to_string_lossy().replace('\\', "/")
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
};
|
||||
self.ui.registries.recipes = dir("recipe");
|
||||
self.ui.registries.damage_types = dir("damage_type");
|
||||
self.ui.registries.loot_tables = dir("loot_table");
|
||||
self.ui.registries.templates = {
|
||||
let root = self.options.resources.join("worldgen/structure/minecraft");
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![root.clone()];
|
||||
while let Some(d) = stack.pop() {
|
||||
let Ok(entries) = std::fs::read_dir(&d) else {
|
||||
continue;
|
||||
};
|
||||
for e in entries.flatten() {
|
||||
let p = e.path();
|
||||
if p.is_dir() {
|
||||
stack.push(p);
|
||||
} else if p.extension().and_then(|x| x.to_str()) == Some("nbt")
|
||||
&& let Ok(rel) = p.strip_prefix(&root)
|
||||
{
|
||||
out.push(format!(
|
||||
"minecraft:{}",
|
||||
rel.with_extension("").to_string_lossy().replace('\\', "/")
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
};
|
||||
}
|
||||
let ids = resource_ids(&self.options.resources);
|
||||
self.ui.registries.recipes = ids.recipes.clone();
|
||||
self.ui.registries.damage_types = ids.damage_types.clone();
|
||||
self.ui.registries.loot_tables = ids.loot_tables.clone();
|
||||
self.ui.registries.templates = ids.templates.clone();
|
||||
self.ui.registries.sounds = self.audio.event_names();
|
||||
self.ui.registries.attributes = [
|
||||
"armor",
|
||||
@@ -416,8 +428,18 @@ impl Game<'_> {
|
||||
.collect();
|
||||
}
|
||||
/// The block the player is looking at, for coordinate suggestions.
|
||||
/// `ClientSuggestionProvider.getRelevantCoordinates` and
|
||||
/// `getAbsoluteCoordinates` read `Minecraft.hitResult` only when it is a
|
||||
/// block: an entity in front of the block leaves the `~` defaults.
|
||||
fn refresh_dynamic_registries(&mut self) {
|
||||
self.ui.registries.target_block = self.pick().map(|h| h.pos);
|
||||
let hit = if self.pick_entity_hit().is_some() {
|
||||
None
|
||||
} else {
|
||||
self.pick()
|
||||
};
|
||||
self.ui.registries.target_block = hit.as_ref().map(|h| h.pos);
|
||||
self.ui.registries.target_point =
|
||||
hit.map(|h| h.point.map(horizon_client::java_text::format_fixed2));
|
||||
// ClientPacketListener.getOnlinePlayerNames on a server.
|
||||
if let Some(names) = self.remote_online_names() {
|
||||
self.ui.registries.players = names;
|
||||
@@ -961,7 +983,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// `Font.split`: a tooltip text wrapped at `width`, one white row per line.
|
||||
fn wrapped_rows(&self, text: &Text, width: i32) -> Vec<(Text, u32)> {
|
||||
pub(super) fn wrapped_rows(&self, text: &Text, width: i32) -> Vec<(Text, u32)> {
|
||||
let split = self
|
||||
.gui
|
||||
.atlas
|
||||
@@ -1126,9 +1148,19 @@ impl Game<'_> {
|
||||
None => self.combat_death_message(),
|
||||
};
|
||||
self.ui.death_text = Some(message.clone());
|
||||
// ServerPlayer.die: a team that hides death messages keeps it out of
|
||||
// the dying player's own chat (the death screen still shows it).
|
||||
if horizon_client::scoreboard::own_death_message_shown(self.player_team()) {
|
||||
// ServerPlayer.die: the team's death message visibility decides who
|
||||
// hears it, the dying player's own chat included (the death screen
|
||||
// still shows it).
|
||||
let board = &self.score.board;
|
||||
if let Some(host) = &self.lan {
|
||||
host.hub.system_message_to(
|
||||
horizon_client::lan::data::component_nbt(&message.component()),
|
||||
|other| {
|
||||
horizon_client::scoreboard::death_message_reaches(board, PLAYER_NAME, other)
|
||||
},
|
||||
);
|
||||
}
|
||||
if horizon_client::scoreboard::death_message_reaches(board, PLAYER_NAME, PLAYER_NAME) {
|
||||
self.system_message(message);
|
||||
}
|
||||
}
|
||||
@@ -1224,3 +1256,24 @@ fn owner_permission(allow_commands: bool) -> u8 {
|
||||
/// `ConfirmLinkScreen`'s buttons, left to right: yes, copy, no.
|
||||
const LINK_YES: usize = 0;
|
||||
const LINK_COPY: usize = 1;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn resource_ids_are_listed_once_per_root() {
|
||||
let root = std::env::temp_dir().join(format!("horizon-ids-{}", std::process::id()));
|
||||
let recipe = root.join("data/minecraft/recipe");
|
||||
std::fs::create_dir_all(recipe.join("sub")).unwrap();
|
||||
std::fs::write(recipe.join("b.json"), "{}").unwrap();
|
||||
std::fs::write(recipe.join("sub/a.json"), "{}").unwrap();
|
||||
std::fs::write(recipe.join("notes.txt"), "").unwrap();
|
||||
let first = resource_ids(&root);
|
||||
assert_eq!(first.recipes, ["minecraft:b", "minecraft:sub/a"]);
|
||||
assert!(first.loot_tables.is_empty());
|
||||
std::fs::write(recipe.join("c.json"), "{}").unwrap();
|
||||
assert!(Arc::ptr_eq(&first, &resource_ids(&root)));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,10 @@ pub(super) struct CombatTracker {
|
||||
/// The mob exploding now (`ServerExplosion.source`): its team's friendly
|
||||
/// fire decides whom the blast may hurt.
|
||||
pub(super) explosion_source: Option<u32>,
|
||||
/// The exploding mob named itself (`MobEvent::ExplosionSource`), so the
|
||||
/// blast leaves it out (`getEntities(source, box)`). A source guessed
|
||||
/// from the mobs near the centre is still hurt: it may be a bystander.
|
||||
pub(super) explosion_source_named: bool,
|
||||
/// The blast now going off comes from a primed TNT, creeper, wither
|
||||
/// skull, wither or TNT minecart, the sources that empty a hive they
|
||||
/// destroy (`BeehiveBlock.getDrops`).
|
||||
|
||||
@@ -925,24 +925,7 @@ impl Game<'_> {
|
||||
Ok(1)
|
||||
}
|
||||
"say" | "me" | "msg" => self.cmd_say(id, ctx),
|
||||
"list" => {
|
||||
let names = if ctx.has("uuids") {
|
||||
Text::translate(
|
||||
"commands.list.nameAndId",
|
||||
&[
|
||||
Text::literal(PLAYER_NAME),
|
||||
Text::literal(self.player_uuid_string()),
|
||||
],
|
||||
)
|
||||
} else {
|
||||
Text::literal(PLAYER_NAME)
|
||||
};
|
||||
self.system_message(Text::translate(
|
||||
"commands.list.players",
|
||||
&[Text::literal("1"), Text::literal("8"), names],
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
"list" => self.cmd_list(ctx),
|
||||
_ => Err(err("command.failed", &[])),
|
||||
}
|
||||
}
|
||||
@@ -1929,7 +1912,10 @@ impl Game<'_> {
|
||||
fn spawned_mark(&self) -> (u32, usize) {
|
||||
(
|
||||
self.next_entity,
|
||||
self.tnts.len() + self.falling.len() + self.creatures.projectiles.len(),
|
||||
self.tnts.len()
|
||||
+ self.falling.len()
|
||||
+ self.creatures.projectiles.len()
|
||||
+ self.rockets.len(),
|
||||
)
|
||||
}
|
||||
/// BlockStateArgument -> registry state.
|
||||
@@ -3096,6 +3082,63 @@ impl Game<'_> {
|
||||
}
|
||||
out
|
||||
}
|
||||
/// ListPlayersCommand: every online player, the host of a hosted world
|
||||
/// first and then the guests in join order, with the count and the max.
|
||||
fn cmd_list(&mut self, ctx: &Context) -> R<i32> {
|
||||
// A single-player owner is a placed guest of the in-process server, so
|
||||
// it is the host and needs no entry of its own.
|
||||
let owner_listed = self
|
||||
.lan
|
||||
.as_ref()
|
||||
.is_some_and(|h| h.hub.singleplayer_owner.is_some());
|
||||
// The host is online unless this is a dedicated server, which has none.
|
||||
let host = (self.options.dedicated.is_none() && !owner_listed).then(|| match &self.lan {
|
||||
Some(h) => (h.host_uuid, h.host_name.clone()),
|
||||
None => (self.player_uuid(), PLAYER_NAME.to_owned()),
|
||||
});
|
||||
let guests = self
|
||||
.lan
|
||||
.iter()
|
||||
.flat_map(|h| h.hub.guests.iter())
|
||||
.filter(|g| g.placed)
|
||||
.map(|g| (g.uuid, g.name.clone()));
|
||||
let players: Vec<(u128, String)> = host.into_iter().chain(guests).collect();
|
||||
let max = self
|
||||
.lan
|
||||
.as_ref()
|
||||
.map_or(horizon_client::lan::MAX_PLAYERS, |h| {
|
||||
h.hub.lan.shared.max_players()
|
||||
});
|
||||
let uuids = ctx.has("uuids");
|
||||
let mut names = Text::empty();
|
||||
for (k, (uuid, name)) in players.iter().enumerate() {
|
||||
if k > 0 {
|
||||
// ComponentUtils.formatList: gray commas.
|
||||
names.push(Text::colored(", ", text::GRAY));
|
||||
}
|
||||
if uuids {
|
||||
names.push(Text::translate(
|
||||
"commands.list.nameAndId",
|
||||
&[
|
||||
Text::literal(name.as_str()),
|
||||
Text::literal(horizon_protocol::crypto::uuid_string(*uuid)),
|
||||
],
|
||||
));
|
||||
} else {
|
||||
names.push(self.player_text(name, *uuid));
|
||||
}
|
||||
}
|
||||
let count = players.len();
|
||||
self.system_message(Text::translate(
|
||||
"commands.list.players",
|
||||
&[
|
||||
Text::literal(count.to_string()),
|
||||
Text::literal(max.to_string()),
|
||||
names,
|
||||
],
|
||||
));
|
||||
Ok(count as i32)
|
||||
}
|
||||
fn cmd_say(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let raw = match ctx.get(if id == "me" { "action" } else { "message" }) {
|
||||
Some(Arg::Str(s)) => s.clone(),
|
||||
|
||||
@@ -1115,10 +1115,10 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
impl Game<'_> {
|
||||
/// The player's profile id as `UUID.toString()`: the saved id, else the
|
||||
/// offline id of the player's name.
|
||||
pub(in crate::game) fn player_uuid_string(&self) -> String {
|
||||
let id = self.level.player_uuid.map_or_else(
|
||||
/// The player's profile id: the saved id, else the offline id of the
|
||||
/// player's name.
|
||||
pub(in crate::game) fn player_uuid(&self) -> u128 {
|
||||
self.level.player_uuid.map_or_else(
|
||||
|| horizon_protocol::crypto::offline_uuid(super::super::chat::PLAYER_NAME),
|
||||
|[a, b, c, d]| {
|
||||
(u128::from(a as u32) << 96)
|
||||
@@ -1126,15 +1126,6 @@ impl Game<'_> {
|
||||
| (u128::from(c as u32) << 32)
|
||||
| u128::from(d as u32)
|
||||
},
|
||||
);
|
||||
let h = format!("{id:032x}");
|
||||
format!(
|
||||
"{}-{}-{}-{}-{}",
|
||||
&h[..8],
|
||||
&h[8..12],
|
||||
&h[12..16],
|
||||
&h[16..20],
|
||||
&h[20..]
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ use horizon_protocol::packets::play::{self, Clientbound as C};
|
||||
impl Game<'_> {
|
||||
/// ComponentArgument with selectors resolved for the source
|
||||
/// (ComponentUtils.updateForEntity: names joined by ", ").
|
||||
fn component_arg(&mut self, ctx: &Context, name: &str) -> R<Text> {
|
||||
pub(in crate::game) fn component_arg(&mut self, ctx: &Context, name: &str) -> R<Text> {
|
||||
let Some(Arg::Str(json)) = ctx.get(name) else {
|
||||
return Ok(Text::empty());
|
||||
};
|
||||
|
||||
@@ -124,6 +124,21 @@ impl Game<'_> {
|
||||
"freeze" => DamageKind::Freeze,
|
||||
"in_wall" => DamageKind::InWall,
|
||||
"thorns" => DamageKind::Thorns,
|
||||
"cramming" => DamageKind::Cramming,
|
||||
"falling_anvil" => DamageKind::FallingAnvil,
|
||||
"falling_block" => DamageKind::FallingBlock,
|
||||
"fireworks" => DamageKind::Fireworks,
|
||||
"generic_kill" => DamageKind::GenericKill,
|
||||
"lightning_bolt" => DamageKind::LightningBolt,
|
||||
"out_of_world" => DamageKind::OutOfWorld,
|
||||
"outside_border" => DamageKind::OutsideBorder,
|
||||
"sonic_boom" => DamageKind::SonicBoom,
|
||||
"spit" => DamageKind::Spit,
|
||||
"stalagmite" => DamageKind::Stalagmite,
|
||||
"starve" => DamageKind::Starve,
|
||||
"sulfur_cube_hot" => DamageKind::SulfurCubeHot,
|
||||
"wind_charge" => DamageKind::WindCharge,
|
||||
"wither" => DamageKind::Wither,
|
||||
_ => DamageKind::Generic,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +25,11 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
rows[index] = self.inventory[..hotbar::SIZE].to_vec();
|
||||
let _ = hotbar::save(&path, &rows);
|
||||
if let Err(e) = hotbar::save(&path, &rows) {
|
||||
// saveHotbar sets the message inside its try, so a failed save says nothing.
|
||||
log::warn!("the creative hotbar was not saved: {e}");
|
||||
return;
|
||||
}
|
||||
let key = |mapping: &str| keybinds::display_name(self.settings.keys.get(mapping));
|
||||
let message = Text::translate(
|
||||
"inventory.hotbarSaved",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! chunk-generation spawning (`NaturalSpawner`), mob events (attacks,
|
||||
//! breeding, conversions, drops), projectiles, player interactions
|
||||
//! (feeding, shearing, milking, spawn eggs, throwing) and rendering.
|
||||
use super::{Dim, Game, view_vector};
|
||||
use super::{Dim, Game, dispenser, view_vector};
|
||||
use horizon_assets::item_model::DisplayContext;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
@@ -857,7 +857,7 @@ impl Game<'_> {
|
||||
}
|
||||
self.score_entity_removed(m.id);
|
||||
self.raider_died(m, by_player);
|
||||
self.villager_murdered(m, by_player);
|
||||
self.villager_murdered(m, by_player, killer.flatten());
|
||||
let pos = [m.position.x, m.position.y + 0.5, m.position.z];
|
||||
self.drop_death_loot(&mut dying, by_player, consumed, pos);
|
||||
self.create_wither_rose(m);
|
||||
@@ -1019,7 +1019,13 @@ impl Game<'_> {
|
||||
} else {
|
||||
from_loot(&stack)
|
||||
};
|
||||
self.spawn_item(item, pos, [0.0, 0.2, 0.0], 10);
|
||||
// Every death drop is its own ItemEntity, and the drop
|
||||
// entity's own random (not the level's) gives it the
|
||||
// constructor's horizontal push (its motion otherwise
|
||||
// stays [0, 0.2, 0] and the drops land stacked at the
|
||||
// mob's centre, without disturbing the level random that
|
||||
// the orbs' merge ids and block ticks read next).
|
||||
self.spawn_item(item, pos, dispenser::new_item_motion(), 10);
|
||||
}
|
||||
drops::Drop::Orb(value) if !consumed => self.spawn_orbs(pos, value as u32),
|
||||
drops::Drop::Orb(_) => {}
|
||||
@@ -1125,7 +1131,9 @@ impl Game<'_> {
|
||||
.loot_table(table, false, None, &mut self.world.random),
|
||||
};
|
||||
for d in stacks {
|
||||
self.spawn_item(d, at, [0.0, 0.2, 0.0], 10);
|
||||
// The ItemEntity constructor's motion, from the entity's own
|
||||
// random (not the level's).
|
||||
self.spawn_item(d, at, dispenser::new_item_motion(), 10);
|
||||
}
|
||||
}
|
||||
/// Adds a projectile, giving it an id from the entity counter
|
||||
@@ -1301,6 +1309,7 @@ impl Game<'_> {
|
||||
self.note_attacker("minecraft:explosion", id);
|
||||
}
|
||||
self.combat.explosion_source = source_mob;
|
||||
self.combat.explosion_source_named = noted;
|
||||
// Only a creeper or a wither empties the hives it blows up.
|
||||
// The creeper is already gone from the list, so the event
|
||||
// carries its kind.
|
||||
@@ -1310,6 +1319,7 @@ impl Game<'_> {
|
||||
self.explode(at, radius)
|
||||
};
|
||||
self.combat.explosion_source = None;
|
||||
self.combat.explosion_source_named = false;
|
||||
result?
|
||||
}
|
||||
MobEvent::AttackMob {
|
||||
@@ -1467,7 +1477,11 @@ impl Game<'_> {
|
||||
extra: None,
|
||||
},
|
||||
at,
|
||||
[0.0, 0.2, 0.0],
|
||||
// The ItemEntity constructor's motion, from the entity's
|
||||
// own random (not the level's), so spawnAtLocation drops
|
||||
// (a fox's berries, a panda's held food, a goat's horn)
|
||||
// land apart.
|
||||
dispenser::new_item_motion(),
|
||||
10,
|
||||
),
|
||||
MobEvent::DropGift { table, at } => {
|
||||
@@ -1476,14 +1490,9 @@ impl Game<'_> {
|
||||
.items()
|
||||
.loot_table(table, false, None, &mut self.world.random);
|
||||
for stack in stacks {
|
||||
// The ItemEntity constructor's random motion.
|
||||
let r = &mut self.world.random;
|
||||
let v = [
|
||||
r.next_double() * 0.2 - 0.1,
|
||||
0.2,
|
||||
r.next_double() * 0.2 - 0.1,
|
||||
];
|
||||
self.spawn_item(stack, at, v, 10);
|
||||
// The ItemEntity constructor's motion, from the
|
||||
// entity's own random (not the level's).
|
||||
self.spawn_item(stack, at, dispenser::new_item_motion(), 10);
|
||||
}
|
||||
}
|
||||
// `Level.setBlockAndUpdate`: neighbour and shape updates, so a crop
|
||||
@@ -4552,15 +4561,10 @@ impl Game<'_> {
|
||||
out,
|
||||
);
|
||||
if &*mob.kind.id == "minecraft:player" {
|
||||
// PlayerRenderer's WingsLayer and SpinAttackEffectLayer.
|
||||
self.player_elytra_geometry(
|
||||
mob,
|
||||
mob.extra.chest.as_deref(),
|
||||
camera,
|
||||
alpha as f32,
|
||||
packed,
|
||||
out,
|
||||
);
|
||||
// PlayerRenderer's CapeLayer, WingsLayer and SpinAttackEffectLayer.
|
||||
let chest = mob.extra.chest.as_deref();
|
||||
self.player_cape_geometry(mob, chest, camera, alpha as f32, packed, out);
|
||||
self.player_elytra_geometry(mob, chest, camera, alpha as f32, packed, out);
|
||||
self.spin_attack_geometry(mob, camera, alpha as f32, packed, out);
|
||||
}
|
||||
self.mob_block_geometry(mob, camera, alpha, packed, out);
|
||||
@@ -4880,6 +4884,17 @@ pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool)
|
||||
K::Freeze => "minecraft:freeze",
|
||||
K::OutOfWorld => "minecraft:out_of_world",
|
||||
K::Cramming => "minecraft:cramming",
|
||||
K::FallingAnvil => "minecraft:falling_anvil",
|
||||
K::Fireworks => "minecraft:fireworks",
|
||||
K::GenericKill => "minecraft:generic_kill",
|
||||
K::LightningBolt => "minecraft:lightning_bolt",
|
||||
K::OutsideBorder => "minecraft:outside_border",
|
||||
K::Spit => "minecraft:spit",
|
||||
K::Stalagmite => "minecraft:stalagmite",
|
||||
K::Starve => "minecraft:starve",
|
||||
K::SulfurCubeHot => "minecraft:sulfur_cube_hot",
|
||||
K::WindCharge => "minecraft:wind_charge",
|
||||
K::Wither => "minecraft:wither",
|
||||
}
|
||||
}
|
||||
/// A Horizon item stack as a loot stack (id, count, damage, enchantments).
|
||||
|
||||
@@ -203,7 +203,7 @@ impl Game<'_> {
|
||||
power,
|
||||
1.0,
|
||||
);
|
||||
self.launch_angled_rocket(at, shot.velocity, ammo);
|
||||
self.launch_angled_rocket(at, shot.velocity, ammo, Some(Who::Player));
|
||||
}
|
||||
if !rocket {
|
||||
let kind = ProjectileKind::Arrow {
|
||||
|
||||
@@ -416,6 +416,13 @@ impl Game<'_> {
|
||||
],
|
||||
);
|
||||
}
|
||||
// Horizon's own: HDR's output while the setting is on, under the GPU (a group of its
|
||||
// own would move others to the other column).
|
||||
if self.settings.horizon.hdr
|
||||
&& let Some(r) = self.renderer.as_ref()
|
||||
{
|
||||
d.group("system", [r.hdr_line()]);
|
||||
}
|
||||
// Horizon's own: the shader pack's GPU time per pass (an empty group would move others).
|
||||
let pass_lines = self.renderer.as_ref().map_or_else(Vec::new, |r| {
|
||||
debug_overlay::shader_pass_lines(&r.shader_pass_times())
|
||||
@@ -917,6 +924,17 @@ impl Game<'_> {
|
||||
(t.pitch, t.yaw),
|
||||
);
|
||||
}
|
||||
// EntityType.EYE_OF_ENDER: 0.25 by 0.25, never turned.
|
||||
for (previous, now) in self.end.eye_motions() {
|
||||
let v = |p: glam::DVec3| Vec3::new(p.x, p.y, p.z);
|
||||
g.hitbox(
|
||||
at(v(previous), v(now)),
|
||||
(0.25, 0.25),
|
||||
0.2125,
|
||||
false,
|
||||
(0.0, 0.0),
|
||||
);
|
||||
}
|
||||
for r in &self.rockets {
|
||||
// Projectile.updateRotation: the look follows the motion.
|
||||
let v = r.velocity;
|
||||
|
||||
@@ -987,7 +987,7 @@ impl Game<'_> {
|
||||
"minecraft:firework_rocket" => {
|
||||
let mut shot = Projectile::new(ProjectileKind::Snowball, at, None);
|
||||
shot.shoot(&mut own, dir, power, uncertainty);
|
||||
self.launch_angled_rocket(at, shot.velocity, &one);
|
||||
self.launch_angled_rocket(at, shot.velocity, &one, None);
|
||||
}
|
||||
_ => {
|
||||
let kind = match item.as_str() {
|
||||
|
||||
@@ -181,6 +181,10 @@ impl EndState {
|
||||
survive: false,
|
||||
});
|
||||
}
|
||||
/// Where each eye in flight was last tick and is now (the hitbox view).
|
||||
pub(super) fn eye_motions(&self) -> impl Iterator<Item = (glam::DVec3, glam::DVec3)> + '_ {
|
||||
self.eyes.iter().map(|e| (e.previous, e.position))
|
||||
}
|
||||
/// `EyeOfEnder.tick` on a server's client: it moves by its last known
|
||||
/// motion; only the server steers it.
|
||||
pub(super) fn step_remote_eyes(&mut self) {
|
||||
@@ -329,6 +333,13 @@ impl Game<'_> {
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// EnderEyeItem.use's `getPlayerPOVHitResult`: whether the block aimed
|
||||
/// at is an End portal frame (the use passes there).
|
||||
pub(super) fn aims_at_end_portal_frame(&self) -> bool {
|
||||
self.pick()
|
||||
.is_some_and(|hit| &*self.block_name(hit.pos) == "minecraft:end_portal_frame")
|
||||
}
|
||||
|
||||
/// EnderEyeItem.useOn: fill an empty End portal frame, then light the
|
||||
/// portal when the ring of twelve filled frames is complete.
|
||||
pub(super) fn use_ender_eye(&mut self, stack: &ItemStack, use_on_block: bool) -> Result<bool> {
|
||||
@@ -345,7 +356,12 @@ impl Game<'_> {
|
||||
if matches!(self.guest_use, Some(super::GuestUse::OnBlock(_))) {
|
||||
return Ok(false);
|
||||
}
|
||||
// EnderEyeItem.use: throw the eye towards the nearest stronghold.
|
||||
// EnderEyeItem.use: startUsingItem (getUseDuration 0, so the use
|
||||
// lasts until the button lets go), then the eye is thrown towards
|
||||
// the nearest stronghold if there is one (CONSUME without).
|
||||
if self.using.is_none() {
|
||||
self.using = Some((self.held_slot(), 0));
|
||||
}
|
||||
self.throw_ender_eye();
|
||||
return Ok(true);
|
||||
};
|
||||
|
||||
@@ -382,9 +382,14 @@ impl Game<'_> {
|
||||
}
|
||||
self.lan = Some(host);
|
||||
}
|
||||
// Mobs.
|
||||
// Mobs, but not the one exploding (`getEntities(source, box)`): a
|
||||
// wither's spawn blast neither hurts nor pushes it.
|
||||
let spared = exploding.filter(|_| self.combat.explosion_source_named);
|
||||
let mut mobs = std::mem::take(&mut self.mobs);
|
||||
for m in mobs.iter_mut().filter(|m| m.alive()) {
|
||||
for m in mobs
|
||||
.iter_mut()
|
||||
.filter(|m| m.alive() && spared != Some(m.id))
|
||||
{
|
||||
let hurtable = teams_allow(self, self.mob_team(m.id));
|
||||
let feet = [m.position.x, m.position.y, m.position.z];
|
||||
let dist = distance(feet) / diameter;
|
||||
|
||||
@@ -7,10 +7,12 @@ use horizon_assets::item_model::DisplayContext;
|
||||
use horizon_client::{
|
||||
block_entity_render::vertex_light,
|
||||
collisions::SceneCollisions,
|
||||
entity_nbt::RocketNbt,
|
||||
items::ItemStack,
|
||||
mesher::Vertex,
|
||||
mobs::{Damage, DamageKind},
|
||||
mobs::{Damage, DamageKind, Species, Who},
|
||||
particles::{FireworkExplosion, ParticleOptions, ParticleType},
|
||||
projectiles::ProjectileWorld,
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3},
|
||||
@@ -30,9 +32,14 @@ pub(super) struct Rocket {
|
||||
pub(super) explosions: Vec<FireworkExplosion>,
|
||||
/// Boosting the player (attachedToEntity).
|
||||
pub(super) attached: bool,
|
||||
/// On a server, the player it boosts when not this game's own: a guest's
|
||||
/// connection.
|
||||
/// On a server, the guest (by connection) who launched it, or whom it
|
||||
/// boosts: `owner`'s `Who::Player` then means them, not the host.
|
||||
pub(super) guest: Option<u32>,
|
||||
/// `Projectile.getOwner`: the player who launched it, credited with
|
||||
/// what its blast hurts.
|
||||
pub(super) owner: Option<Who>,
|
||||
/// `Projectile.leftOwner`: until then it can't hit its owner.
|
||||
left_owner: bool,
|
||||
/// `DATA_ATTACHED_TO_TARGET`: the server entity the rocket follows;
|
||||
/// boosting happens when it is the local player.
|
||||
pub(super) attached_to: Option<u32>,
|
||||
@@ -57,11 +64,36 @@ impl Rocket {
|
||||
explosions,
|
||||
attached: false,
|
||||
guest: None,
|
||||
owner: None,
|
||||
left_owner: false,
|
||||
attached_to: None,
|
||||
angled: false,
|
||||
item,
|
||||
}
|
||||
}
|
||||
/// A rocket loaded from its NBT (`/summon`, a saved chunk).
|
||||
pub(super) fn from_nbt(r: RocketNbt) -> Self {
|
||||
let item = r
|
||||
.item
|
||||
.unwrap_or_else(|| ItemStack::new("minecraft:firework_rocket", 1));
|
||||
let (_, explosions) = fireworks_of(&item);
|
||||
Self {
|
||||
id: 0,
|
||||
position: r.position,
|
||||
previous: r.position,
|
||||
velocity: r.motion,
|
||||
life: r.life,
|
||||
lifetime: r.lifetime,
|
||||
explosions,
|
||||
attached: false,
|
||||
guest: None,
|
||||
owner: r.owner,
|
||||
left_owner: r.left_owner,
|
||||
attached_to: None,
|
||||
angled: r.angled,
|
||||
item,
|
||||
}
|
||||
}
|
||||
/// One tick of a server's client: the rocket flies on by itself between
|
||||
/// the server's updates (a rocket that follows an entity is placed by the
|
||||
/// caller).
|
||||
@@ -72,6 +104,19 @@ impl Rocket {
|
||||
}
|
||||
self.life += 1;
|
||||
}
|
||||
/// The move of a rocket attached to no entity: sped up and rising, or an
|
||||
/// angled one's own motion.
|
||||
fn next_motion(&self) -> Vec3 {
|
||||
if self.angled {
|
||||
self.velocity
|
||||
} else {
|
||||
Vec3::new(
|
||||
self.velocity.x * 1.15,
|
||||
self.velocity.y + 0.04,
|
||||
self.velocity.z * 1.15,
|
||||
)
|
||||
}
|
||||
}
|
||||
/// `FireworkRocketEntity.tick` for a rocket attached to no entity: speed
|
||||
/// up (an angled one keeps its motion) and rise, then move. True when a
|
||||
/// block stopped it.
|
||||
@@ -85,15 +130,7 @@ impl Rocket {
|
||||
self.position.z + h,
|
||||
),
|
||||
);
|
||||
let wanted = if self.angled {
|
||||
self.velocity
|
||||
} else {
|
||||
Vec3::new(
|
||||
self.velocity.x * 1.15,
|
||||
self.velocity.y + 0.04,
|
||||
self.velocity.z * 1.15,
|
||||
)
|
||||
};
|
||||
let wanted = self.next_motion();
|
||||
let Ok(moved) = scene.resolve(bounds, wanted, 0.0, false) else {
|
||||
return false;
|
||||
};
|
||||
@@ -157,6 +194,8 @@ impl Game<'_> {
|
||||
explosions,
|
||||
attached,
|
||||
guest: None,
|
||||
owner: None,
|
||||
left_owner: false,
|
||||
attached_to: None,
|
||||
angled: false,
|
||||
item: stack.clone(),
|
||||
@@ -172,7 +211,9 @@ impl Game<'_> {
|
||||
hit.point[1] + f64::from(hit.face[1]) * 0.15,
|
||||
hit.point[2] + f64::from(hit.face[2]) * 0.15,
|
||||
);
|
||||
let rocket = self.new_rocket(at, stack, false);
|
||||
let mut rocket = self.new_rocket(at, stack, false);
|
||||
rocket.owner = Some(Who::Player);
|
||||
rocket.guest = self.lan_acting;
|
||||
self.rockets.push(rocket);
|
||||
if !self.creative {
|
||||
self.consume_held();
|
||||
@@ -182,10 +223,18 @@ impl Game<'_> {
|
||||
}
|
||||
/// A rocket shot at an angle (`DATA_SHOT_AT_ANGLE`): out of a dispenser
|
||||
/// (`FireworkRocketItem.asProjectile`) or a crossbow.
|
||||
pub(super) fn launch_angled_rocket(&mut self, at: Vec3, velocity: Vec3, stack: &ItemStack) {
|
||||
pub(super) fn launch_angled_rocket(
|
||||
&mut self,
|
||||
at: Vec3,
|
||||
velocity: Vec3,
|
||||
stack: &ItemStack,
|
||||
owner: Option<Who>,
|
||||
) {
|
||||
let mut rocket = self.new_rocket(at, stack, false);
|
||||
rocket.velocity = velocity;
|
||||
rocket.angled = true;
|
||||
rocket.owner = owner;
|
||||
rocket.guest = self.lan_acting.filter(|_| owner == Some(Who::Player));
|
||||
self.rockets.push(rocket);
|
||||
}
|
||||
/// `FireworkRocketItem.use` while gliding: a rocket attached to the player.
|
||||
@@ -197,6 +246,7 @@ impl Game<'_> {
|
||||
}
|
||||
let at = self.player.as_ref().map_or(Vec3::ZERO, |p| p.position);
|
||||
let mut rocket = self.new_rocket(at, stack, true);
|
||||
rocket.owner = Some(Who::Player);
|
||||
rocket.guest = self.lan_acting;
|
||||
self.rockets.push(rocket);
|
||||
if !self.creative {
|
||||
@@ -206,10 +256,33 @@ impl Game<'_> {
|
||||
true
|
||||
}
|
||||
pub(super) fn tick_rockets(&mut self) {
|
||||
let targets = if self.rockets.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.rocket_targets()
|
||||
};
|
||||
let mut i = 0;
|
||||
while i < self.rockets.len() {
|
||||
let mut r = self.rockets.remove(i);
|
||||
r.previous = r.position;
|
||||
// Projectile.tick: whether it has left its owner, before it moves.
|
||||
let owner = self.rocket_owner(&r);
|
||||
if !r.left_owner {
|
||||
let h = 0.125;
|
||||
let reach = Aabb::new(
|
||||
Vec3::new(r.position.x - h, r.position.y, r.position.z - h),
|
||||
Vec3::new(r.position.x + h, r.position.y + 2.0 * h, r.position.z + h),
|
||||
)
|
||||
.expand_towards(r.velocity)
|
||||
.inflate(Vec3::new(1.0, 1.0, 1.0));
|
||||
r.left_owner = owner.is_none_or(|o| {
|
||||
!targets
|
||||
.iter()
|
||||
.any(|(who, b)| *who == o && b.intersects(reach))
|
||||
});
|
||||
}
|
||||
let skip = owner.filter(|_| !r.left_owner);
|
||||
let mut hit = None;
|
||||
if r.attached
|
||||
&& let Some(conn) = r.guest
|
||||
{
|
||||
@@ -235,7 +308,10 @@ impl Game<'_> {
|
||||
r.position = p.position;
|
||||
r.velocity = p.velocity;
|
||||
}
|
||||
hit = self.rocket_struck(&targets, &r, r.velocity, skip);
|
||||
} else {
|
||||
// getHitResultOnMoveVector before the move.
|
||||
hit = self.rocket_struck(&targets, &r, r.next_motion(), skip);
|
||||
let mut scene = SceneCollisions {
|
||||
world: &self.world,
|
||||
binding: self.collision,
|
||||
@@ -246,6 +322,20 @@ impl Game<'_> {
|
||||
r.life = r.lifetime;
|
||||
}
|
||||
}
|
||||
// hitTargetOrDeflectSelf on an entity: a breeze turns it back
|
||||
// (ProjectileDeflection.REVERSE), anything else sets it off.
|
||||
match hit {
|
||||
Some(Who::Mob(id))
|
||||
if self
|
||||
.mobs
|
||||
.iter()
|
||||
.any(|m| m.id == id && m.species() == Species::Breeze) =>
|
||||
{
|
||||
r.velocity = r.velocity.scale(-0.5);
|
||||
}
|
||||
Some(_) => r.life = r.lifetime,
|
||||
None => {}
|
||||
}
|
||||
let at = [r.position.x, r.position.y, r.position.z];
|
||||
if r.life == 0 {
|
||||
self.audio.play(
|
||||
@@ -327,17 +417,28 @@ impl Game<'_> {
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
for (id, amount) in hits {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
m.damage(
|
||||
amount,
|
||||
Damage {
|
||||
kind: DamageKind::Explosion,
|
||||
attacker: None,
|
||||
from: Some(at),
|
||||
},
|
||||
);
|
||||
// damageSources().fireworks(this, getOwner()): a guest's rocket
|
||||
// hurts as theirs, and the mobs it hit answer to them.
|
||||
let owner = r.owner;
|
||||
if let Some(conn) = r.guest.filter(|_| owner.is_some())
|
||||
&& let Some(mut host) = self.lan.take()
|
||||
{
|
||||
let ran = self
|
||||
.as_guest(&mut host, conn, |g| g.rocket_hurt_mobs(&hits, owner, at))
|
||||
.is_some();
|
||||
if ran {
|
||||
for (id, _) in &hits {
|
||||
if self.mobs.iter().any(|m| m.id == *id) {
|
||||
host.mob_players.insert(*id, conn);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.lan = Some(host);
|
||||
if !ran {
|
||||
self.rocket_hurt_mobs(&hits, owner, at);
|
||||
}
|
||||
} else {
|
||||
self.rocket_hurt_mobs(&hits, owner, at);
|
||||
}
|
||||
}
|
||||
let camera = self.eye_position().unwrap_or(at);
|
||||
@@ -345,6 +446,87 @@ impl Game<'_> {
|
||||
self.particles
|
||||
.fireworks(at, v, r.explosions.clone(), camera);
|
||||
}
|
||||
fn rocket_hurt_mobs(&mut self, hits: &[(u32, f32)], attacker: Option<Who>, at: [f64; 3]) {
|
||||
for &(id, amount) in hits {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
m.damage(
|
||||
amount,
|
||||
Damage {
|
||||
kind: DamageKind::Explosion,
|
||||
attacker,
|
||||
from: Some(at),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The owner as `rocket_targets` names it: a guest by their entity id.
|
||||
fn rocket_owner(&self, r: &Rocket) -> Option<Who> {
|
||||
let owner = r.owner?;
|
||||
let Some(conn) = r.guest.filter(|_| owner == Who::Player) else {
|
||||
return Some(owner);
|
||||
};
|
||||
let host = self.lan.as_ref()?;
|
||||
let g = host.hub.guests.iter().find(|g| g.conn == conn)?;
|
||||
Some(Who::Mob(g.entity_id as u32))
|
||||
}
|
||||
/// What a rocket can hit (`Projectile.canHitEntity`): living mobs, the
|
||||
/// dragon's parts and crystals, the player and the guests.
|
||||
fn rocket_targets(&self) -> Vec<(Who, Aabb)> {
|
||||
let mut targets: Vec<(Who, Aabb)> = self
|
||||
.mobs
|
||||
.iter()
|
||||
.filter(|m| m.alive())
|
||||
.map(|m| (Who::Mob(m.id), m.bounds()))
|
||||
.collect();
|
||||
if let Some(p) = self.player_view()
|
||||
&& p.alive
|
||||
&& !self.spectator()
|
||||
{
|
||||
targets.push((Who::Player, p.bounds));
|
||||
}
|
||||
targets.extend(
|
||||
self.special_targets()
|
||||
.into_iter()
|
||||
.map(|(id, b)| (Who::Mob(id), b)),
|
||||
);
|
||||
targets.extend(self.lan_projectile_targets());
|
||||
targets
|
||||
}
|
||||
/// `ProjectileUtil.getHitResultOnMoveVector`'s entity half: the nearest
|
||||
/// target on the move, short of the block it clips, each box grown by
|
||||
/// `computeMargin` (`tickCount` is the rocket's life plus one).
|
||||
fn rocket_struck(
|
||||
&self,
|
||||
targets: &[(Who, Aabb)],
|
||||
r: &Rocket,
|
||||
motion: Vec3,
|
||||
skip: Option<Who>,
|
||||
) -> Option<Who> {
|
||||
let from = r.position;
|
||||
let mut to = from.add_vector(motion);
|
||||
let w = self.mob_world_base(&[]);
|
||||
if let Some((at, ..)) = (super::creatures::ProjWorld {
|
||||
w: &w,
|
||||
targets: Vec::new(),
|
||||
})
|
||||
.clip(from, to)
|
||||
{
|
||||
to = at;
|
||||
}
|
||||
let margin = (f64::from(r.life - 1) / 20.0).clamp(0.0, 0.3);
|
||||
targets
|
||||
.iter()
|
||||
.filter(|(who, _)| Some(*who) != skip)
|
||||
.filter_map(|(who, b)| {
|
||||
let at = b
|
||||
.inflate(Vec3::new(margin, margin, margin))
|
||||
.clip(from, to)?;
|
||||
Some((*who, from.distance_squared(at)))
|
||||
})
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
.map(|(who, _)| who)
|
||||
}
|
||||
/// FireworkRocketEntity.handleEntityEvent: use the synchronized item data.
|
||||
pub(super) fn remote_firework_explosion(&mut self, id: i32) {
|
||||
let camera = self.eye_position();
|
||||
|
||||
@@ -164,7 +164,7 @@ impl Game<'_> {
|
||||
(p.position.x - start[0]) as f32,
|
||||
(p.position.z - start[2]) as f32,
|
||||
);
|
||||
self.avatar.tick();
|
||||
self.avatar.tick(start);
|
||||
self.avatar
|
||||
.update_bob(ground && alive && !swimming, velocity);
|
||||
if riding {
|
||||
|
||||
@@ -572,6 +572,75 @@ impl Game<'_> {
|
||||
.chain(self.fns.enabled.iter().cloned())
|
||||
.collect()
|
||||
}
|
||||
/// `FileUtil.isPathPartPortable`: no trailing dot and no Windows device
|
||||
/// name (CON, PRN, AUX, NUL, COM and LPT with a digit from 1 to 9).
|
||||
fn is_portable_name(name: &str) -> bool {
|
||||
let stem = name.split('.').next().unwrap_or_default();
|
||||
let device = match stem.len() {
|
||||
3 => matches!(stem, "com" | "con" | "prn" | "aux" | "nul"),
|
||||
4 => matches!(&stem[..3], "com" | "lpt") && matches!(stem.as_bytes()[3], b'1'..=b'9'),
|
||||
_ => false,
|
||||
};
|
||||
!device && !name.ends_with('.')
|
||||
}
|
||||
/// `DataPackCommand.createPack`: a pack folder with its `data` folder and a
|
||||
/// `pack.mcmeta` in the world's datapacks folder.
|
||||
fn create_pack(&mut self, ctx: &Context) -> R<i32> {
|
||||
let id = match ctx.get("id") {
|
||||
Some(Arg::Str(s)) => s.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let description = self.component_arg(ctx, "description")?;
|
||||
// FileUtil.isValidPathSegment: lowercase letters, digits, '-', '.' and '_'.
|
||||
let valid = !id.is_empty()
|
||||
&& id != "."
|
||||
&& id != ".."
|
||||
&& id
|
||||
.chars()
|
||||
.all(|c| matches!(c, 'a'..='z' | '0'..='9' | '-' | '.' | '_'));
|
||||
if !valid {
|
||||
return Err(err("commands.datapack.create.invalid_name", &[&id]));
|
||||
}
|
||||
if !Self::is_portable_name(&id) {
|
||||
return Err(err("commands.datapack.create.invalid_full_name", &[&id]));
|
||||
}
|
||||
// Without a world there is no datapacks folder to write to.
|
||||
if self.world_root.as_os_str().is_empty() {
|
||||
return Err(err("commands.datapack.create.io_failure", &[&id]));
|
||||
}
|
||||
let datapacks = self.world_root.join("datapacks");
|
||||
let pack = datapacks.join(&id);
|
||||
if pack.exists() {
|
||||
return Err(err("commands.datapack.create.already_exists", &[&id]));
|
||||
}
|
||||
// The data pack version (SharedConstants), written as a bare major
|
||||
// number for both bounds, as vanilla does.
|
||||
let pack_format = horizon_core::version::DATA_PACK_FORMAT.0;
|
||||
let mcmeta = serde_json::json!({
|
||||
"pack": {
|
||||
"description": description.component(),
|
||||
"min_format": pack_format,
|
||||
"max_format": pack_format,
|
||||
}
|
||||
});
|
||||
let written = std::fs::create_dir_all(&datapacks)
|
||||
.and_then(|()| std::fs::create_dir(&pack))
|
||||
.and_then(|()| std::fs::create_dir(pack.join("data")))
|
||||
.and_then(|()| {
|
||||
std::fs::write(
|
||||
pack.join("pack.mcmeta"),
|
||||
serde_json::to_string_pretty(&mcmeta).unwrap_or_default(),
|
||||
)
|
||||
});
|
||||
if written.is_err() {
|
||||
return Err(err("commands.datapack.create.io_failure", &[&id]));
|
||||
}
|
||||
self.feedback(Text::translate(
|
||||
"commands.datapack.create.success",
|
||||
&[Text::literal(id)],
|
||||
));
|
||||
Ok(1)
|
||||
}
|
||||
pub(super) fn cmd_datapack(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
self.ensure_datapacks();
|
||||
let name = match ctx.get("name") {
|
||||
@@ -590,6 +659,7 @@ impl Game<'_> {
|
||||
|| g.fns.packs.iter().any(|p| p.id == n)
|
||||
};
|
||||
match id {
|
||||
"datapack.create" => self.create_pack(ctx),
|
||||
"datapack.list" => {
|
||||
let want_enabled = ctx.has("enabled") || (!ctx.has("available"));
|
||||
let want_available = ctx.has("available") || (!ctx.has("enabled"));
|
||||
|
||||
@@ -10,12 +10,14 @@ use horizon_client::{
|
||||
first_person::{Hand, HandWorld, Hit, SwingAnimation, UseResult, swing_duration},
|
||||
items::ItemStack,
|
||||
};
|
||||
use horizon_core::geometry::{Aabb, Vec3};
|
||||
|
||||
/// The off hand's place in `visible_hands` (the main hand uses its hotbar slot).
|
||||
const OFFHAND: usize = usize::MAX;
|
||||
|
||||
/// `AttackRange.isInRange`: float bounds, then inclusive double comparison.
|
||||
fn attack_range_contains(range: &serde_json::Value, distance: f64, creative: bool) -> bool {
|
||||
/// `AttackRange.effectiveMinRange`, `effectiveMaxRange` (for a player) and
|
||||
/// `hitboxMargin` of an `attack_range` component.
|
||||
fn attack_reach(range: &serde_json::Value, creative: bool) -> (f32, f32, f32) {
|
||||
let value = |key: &str, default: f32| range[key].as_f64().map_or(default, |v| v as f32);
|
||||
let (min, max) = if creative {
|
||||
(
|
||||
@@ -25,7 +27,34 @@ fn attack_range_contains(range: &serde_json::Value, distance: f64, creative: boo
|
||||
} else {
|
||||
(value("min_reach", 0.0), value("max_reach", 3.0))
|
||||
};
|
||||
let margin = value("hitbox_margin", 0.3);
|
||||
(min, max, value("hitbox_margin", 0.3))
|
||||
}
|
||||
|
||||
fn v3(v: [f64; 3]) -> Vec3 {
|
||||
Vec3::new(v[0], v[1], v[2])
|
||||
}
|
||||
|
||||
/// `LocalPlayer.raycastHitResult` with an item that has an attack range
|
||||
/// (`AttackRange.getClosesetHit`): the distance from the eye to the nearest
|
||||
/// box hit along the item's own `reach`, which goes past the plain pick's
|
||||
/// 3 blocks (a spear's 4.5). A miss falls back to the plain pick (`None`).
|
||||
fn reach_pick(
|
||||
boxes: &[(usize, Aabb)],
|
||||
eye: Vec3,
|
||||
look: Vec3,
|
||||
movement: Vec3,
|
||||
reach: (f32, f32, f32),
|
||||
clip: impl Fn(Vec3, Vec3) -> Option<Vec3>,
|
||||
) -> Option<f64> {
|
||||
super::spear::hits_in_reach(boxes, eye, look, movement, reach, clip)
|
||||
.into_iter()
|
||||
.map(|(_, at)| eye.distance_squared(at).sqrt())
|
||||
.reduce(f64::min)
|
||||
}
|
||||
|
||||
/// `AttackRange.isInRange`: float bounds, then inclusive double comparison.
|
||||
fn attack_range_contains(range: &serde_json::Value, distance: f64, creative: bool) -> bool {
|
||||
let (min, max, margin) = attack_reach(range, creative);
|
||||
distance >= f64::from(min - margin) && distance <= f64::from(max + margin)
|
||||
}
|
||||
|
||||
@@ -261,10 +290,6 @@ impl Game<'_> {
|
||||
/// it is alive (the nearest entity under the crosshair, before any block).
|
||||
pub(super) fn crosshair_living(&self) -> Option<bool> {
|
||||
let nearest = |hits: &[Option<f64>]| hits.iter().flatten().copied().reduce(f64::min);
|
||||
let living = nearest(&[
|
||||
self.mob_hit().map(|h| h.1),
|
||||
self.armor_stand_hit().map(|h| h.1),
|
||||
])?;
|
||||
let other = nearest(&[
|
||||
self.painting_hit().map(|h| h.1),
|
||||
self.frame_hit().map(|h| h.1),
|
||||
@@ -272,24 +297,49 @@ impl Game<'_> {
|
||||
self.cart_hit().map(|h| h.1),
|
||||
self.dragon_hit().map(|h| h.1),
|
||||
]);
|
||||
if !self.before_block(living) || other.is_some_and(|o| o <= living) {
|
||||
return None;
|
||||
}
|
||||
let active = self
|
||||
.using
|
||||
.and_then(|(slot, _)| self.inventory.get(slot).and_then(Option::as_ref))
|
||||
.or_else(|| self.held());
|
||||
if let Some(stack) = active {
|
||||
let components = self
|
||||
.pack
|
||||
let range = active.and_then(|stack| {
|
||||
self.pack
|
||||
.item_renderer
|
||||
.models
|
||||
.components(&horizon_client::item_render::stack_view(stack));
|
||||
if let Some(range) = components.get("minecraft:attack_range")
|
||||
&& !attack_range_contains(range, living, self.creative)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
.components(&horizon_client::item_render::stack_view(stack))
|
||||
.get("minecraft:attack_range")
|
||||
.cloned()
|
||||
});
|
||||
let spear = range.as_ref().and_then(|r| {
|
||||
let eye = self.eye_position()?;
|
||||
let look = super::view_vector(self.yaw, self.pitch);
|
||||
let reach = attack_reach(r, self.creative);
|
||||
let boxes = self.hittable_mob_boxes();
|
||||
let clip = |from: Vec3, to: Vec3| {
|
||||
let length = from.distance_squared(to).sqrt();
|
||||
let d = to.subtract(from).scale(1.0 / length);
|
||||
(length > 0.0)
|
||||
.then(|| self.clip_ray([from.x, from.y, from.z], [d.x, d.y, d.z], length))
|
||||
.flatten()
|
||||
.map(|hit| Vec3::new(hit.point[0], hit.point[1], hit.point[2]))
|
||||
};
|
||||
let movement = self.known_player_movement();
|
||||
reach_pick(&boxes, v3(eye), v3(look), movement, reach, clip)
|
||||
});
|
||||
let living = match spear {
|
||||
Some(distance) => distance,
|
||||
None => nearest(&[
|
||||
self.mob_hit().map(|h| h.1),
|
||||
self.armor_stand_hit().map(|h| h.1),
|
||||
])?,
|
||||
};
|
||||
if (spear.is_none() && !self.before_block(living)) || other.is_some_and(|o| o <= living) {
|
||||
return None;
|
||||
}
|
||||
// Hud.extractCrosshair: with an attack range, the hit must be in it.
|
||||
if let Some(range) = &range
|
||||
&& !attack_range_contains(range, living, self.creative)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// Only alive mobs are hit, so a picked living entity is alive.
|
||||
Some(true)
|
||||
@@ -324,12 +374,12 @@ impl Game<'_> {
|
||||
let Some(hit) = self.pick() else {
|
||||
return false;
|
||||
};
|
||||
let name = &*self
|
||||
let id = &*self
|
||||
.res
|
||||
.facts()
|
||||
.get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]))
|
||||
.name;
|
||||
let name = name.trim_start_matches("minecraft:");
|
||||
let name = id.trim_start_matches("minecraft:");
|
||||
match name {
|
||||
// BlockBehaviour.getMenuProvider and `instanceof Portal`.
|
||||
"crafting_table" | "enchanting_table" | "anvil" | "chipped_anvil" | "damaged_anvil"
|
||||
@@ -338,8 +388,9 @@ impl Game<'_> {
|
||||
| "dispenser" | "dropper" | "crafter" | "lectern" | "beacon" | "nether_portal"
|
||||
| "end_portal" | "end_gateway" => true,
|
||||
// ChestBlock.getMenuProvider: none while a redstone conductor
|
||||
// sits on top of either half (a sitting cat aside).
|
||||
"chest" | "trapped_chest" => {
|
||||
// sits on top of either half (a sitting cat aside). Copper
|
||||
// chests are `ChestBlock`s too.
|
||||
_ if horizon_client::containers::is_chest_block(id) => {
|
||||
let key = (hit.pos[0], hit.pos[1], hit.pos[2]);
|
||||
let blocked = |p: (i32, i32, i32)| {
|
||||
let above = self.world.block(p.0, p.1 + 1, p.2);
|
||||
@@ -563,6 +614,40 @@ impl HandWorld for GameHands<'_, '_> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A zombie-sized box whose near face is `distance` blocks ahead of an
|
||||
/// eye at the origin looking along +z.
|
||||
fn mob_ahead(distance: f64) -> Vec<(usize, Aabb)> {
|
||||
let min = Vec3::new(-0.3, -1.0, distance);
|
||||
vec![(0, Aabb::new(min, min.add_vector(Vec3::new(0.6, 1.95, 0.6))))]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spear_picks_a_mob_past_the_plain_reach() {
|
||||
// #3209: a mob 4 blocks ahead is out of the plain pick's 3 blocks but
|
||||
// within a spear's attack range (min 2, max 4.5, margin 0.125), so the
|
||||
// crosshair picks it and the attack indicator shows.
|
||||
let spear = serde_json::json!({
|
||||
"min_reach": 2.0, "max_reach": 4.5,
|
||||
"min_creative_reach": 2.0, "max_creative_reach": 6.5,
|
||||
"hitbox_margin": 0.125,
|
||||
});
|
||||
let (eye, look) = (Vec3::ZERO, Vec3::new(0.0, 0.0, 1.0));
|
||||
let boxes = mob_ahead(4.0);
|
||||
let reach = attack_reach(&spear, false);
|
||||
let pick = reach_pick(&boxes, eye, look, Vec3::ZERO, reach, |_, _| None);
|
||||
assert_eq!(pick, Some(4.0));
|
||||
assert!(attack_range_contains(&spear, 4.0, false));
|
||||
// Past the maximum plus the margin: no pick.
|
||||
let far = mob_ahead(4.7);
|
||||
assert_eq!(
|
||||
reach_pick(&far, eye, look, Vec3::ZERO, reach, |_, _| None),
|
||||
None
|
||||
);
|
||||
// A block nearer than the minimum reach takes the pick.
|
||||
let wall = |from: Vec3, _: Vec3| Some(from.add_vector(Vec3::new(0.0, 0.0, 1.0)));
|
||||
assert_eq!(reach_pick(&boxes, eye, look, Vec3::ZERO, reach, wall), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attack_range_uses_inclusive_float_bounds() {
|
||||
let range = serde_json::json!({
|
||||
|
||||
@@ -425,6 +425,7 @@ impl Game<'_> {
|
||||
return result.and(stopped);
|
||||
}
|
||||
let mut next = Instant::now();
|
||||
let mut was_paused = false;
|
||||
while !flags.stop.load(Ordering::Relaxed) {
|
||||
self.run_tasks();
|
||||
if self.agent.hold_server {
|
||||
@@ -434,6 +435,14 @@ impl Game<'_> {
|
||||
continue;
|
||||
}
|
||||
let paused = flags.paused.load(Ordering::Relaxed);
|
||||
if paused && !was_paused {
|
||||
// IntegratedServer.tickServer: the tick the game pauses saves
|
||||
// everything (saveEverything, without flushing), as an
|
||||
// autosave does.
|
||||
log::info!("Saving and pausing game...");
|
||||
self.save_game_with(false)?;
|
||||
}
|
||||
was_paused = paused;
|
||||
if paused {
|
||||
// Only the connections run.
|
||||
self.tick_server_timed(true)?;
|
||||
|
||||
@@ -458,6 +458,7 @@ impl Game<'_> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn civil_dates_follow_the_gregorian_calendar() {
|
||||
@@ -465,4 +466,27 @@ mod tests {
|
||||
assert_eq!(civil(19_716), (2023, 12, 25));
|
||||
assert_eq!(civil(11_016), (2000, 2, 29));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shield_is_used_for_the_vanilla_s_time() {
|
||||
// Item.getUseDuration: an item with `blocks_attacks` (a shield) is
|
||||
// used for 72000 ticks, so its use animation (the arm held up)
|
||||
// runs instead of ending at once (#2289).
|
||||
let mut shield = Components::new();
|
||||
shield.insert("minecraft:blocks_attacks".into(), json!({}));
|
||||
assert_eq!(use_duration(&shield), 72_000);
|
||||
// Food is used for as long as it takes to eat it.
|
||||
let mut food = Components::new();
|
||||
food.insert(
|
||||
"minecraft:consumable".into(),
|
||||
json!({"consume_seconds": 1.6}),
|
||||
);
|
||||
assert_eq!(use_duration(&food), 32);
|
||||
// The bow keeps its own use time.
|
||||
let mut bow = Components::new();
|
||||
bow.insert("minecraft:item_model".into(), json!("minecraft:bow"));
|
||||
assert_eq!(use_duration(&bow), 72_000);
|
||||
// Anything else is not used at all.
|
||||
assert_eq!(use_duration(&Components::new()), 0);
|
||||
}
|
||||
}
|
||||
@@ -328,7 +328,7 @@ fn mob_meta(
|
||||
// Entity.DATA_SHARED_FLAGS_ID: on fire 0x01, swimming 0x10 (a drowned
|
||||
// under water, `Drowned.setSwimming`), invisible 0x20 (the effect's flag)
|
||||
// and glowing 0x40 (LivingEntity.updateGlowingStatus).
|
||||
let shared = i8::from(m.fire_ticks > 0)
|
||||
let shared = i8::from(m.is_on_fire())
|
||||
| i8::from(m.species() == Species::Drowned && m.extra.flag) << 4
|
||||
| i8::from(m.invisible || horizon_client::mobs::trader::is_invisible(m)) << 5
|
||||
| i8::from(m.is_currently_glowing()) << 6;
|
||||
@@ -801,6 +801,14 @@ fn mob_meta(
|
||||
}
|
||||
defaults.push((18, serializer::BOOLEAN, Value::Bool(false)));
|
||||
}
|
||||
// Skeleton.DATA_STRAY_CONVERSION_ID (the first entry after Mob's):
|
||||
// the shaking of the freezing conversion.
|
||||
"minecraft:skeleton" => {
|
||||
if e.counter2 > 0 {
|
||||
meta.push((16, serializer::BOOLEAN, Value::Bool(true)));
|
||||
}
|
||||
defaults.push((16, serializer::BOOLEAN, Value::Bool(false)));
|
||||
}
|
||||
// AbstractVillager.DATA_UNHAPPY_COUNTER (after AgeableMob's two).
|
||||
"minecraft:wandering_trader" => unhappy_counter(m, meta, defaults),
|
||||
// Hoglin.DATA_IMMUNE_TO_ZOMBIFICATION (after AgeableMob's two) and
|
||||
|
||||
@@ -833,35 +833,23 @@ impl Game<'_> {
|
||||
.facts()
|
||||
.get(self.world.block(pos.0, pos.1, pos.2))
|
||||
.name;
|
||||
let (menu, title, slots) = if &**name == "minecraft:ender_chest" {
|
||||
let (menu, slots) = if &**name == "minecraft:ender_chest" {
|
||||
// EnderChestBlock.useWithoutItem: the player's own inventory.
|
||||
(
|
||||
"minecraft:generic_9x3",
|
||||
"container.enderchest",
|
||||
Slots::Ender,
|
||||
)
|
||||
("minecraft:generic_9x3", Slots::Ender)
|
||||
} else if let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get(&pos) {
|
||||
// AbstractFurnaceBlock.openContainer: FurnaceMenu, BlastFurnaceMenu, SmokerMenu.
|
||||
let (menu, title) = match f.kind.recipe_type() {
|
||||
"minecraft:blasting" => ("minecraft:blast_furnace", "container.blast_furnace"),
|
||||
"minecraft:smoking" => ("minecraft:smoker", "container.smoker"),
|
||||
_ => ("minecraft:furnace", "container.furnace"),
|
||||
let menu = match f.kind.recipe_type() {
|
||||
"minecraft:blasting" => "minecraft:blast_furnace",
|
||||
"minecraft:smoking" => "minecraft:smoker",
|
||||
_ => "minecraft:furnace",
|
||||
};
|
||||
(menu, title, Slots::Block(pos))
|
||||
(menu, Slots::Block(pos))
|
||||
} else if let Some(BlockEntity::Crafter(_)) = self.world.block_entities.get(&pos) {
|
||||
// CrafterBlock.useWithoutItem: CrafterMenu over the block entity.
|
||||
(
|
||||
"minecraft:crafter_3x3",
|
||||
"container.crafter",
|
||||
Slots::Block(pos),
|
||||
)
|
||||
("minecraft:crafter_3x3", Slots::Block(pos))
|
||||
} else if let Some(BlockEntity::Brewing(_)) = self.world.block_entities.get(&pos) {
|
||||
// BrewingStandBlock.useWithoutItem: BrewingStandMenu.
|
||||
(
|
||||
"minecraft:brewing_stand",
|
||||
"container.brewing",
|
||||
Slots::Block(pos),
|
||||
)
|
||||
("minecraft:brewing_stand", Slots::Block(pos))
|
||||
} else if let Some((other, right)) = self.chest_partner(pos) {
|
||||
// ChestBlock.combine: the right half's slots come first.
|
||||
let halves = if right {
|
||||
@@ -869,24 +857,33 @@ impl Game<'_> {
|
||||
} else {
|
||||
Slots::Double(other, pos)
|
||||
};
|
||||
("minecraft:generic_9x6", "container.chestDouble", halves)
|
||||
("minecraft:generic_9x6", halves)
|
||||
} else {
|
||||
let Some(BlockEntity::Chest(items)) = self.world.block_entities.get(&pos) else {
|
||||
return false;
|
||||
};
|
||||
let (menu, title) = match items.len() {
|
||||
27 => ("minecraft:generic_9x3", "container.chest"),
|
||||
9 => ("minecraft:generic_3x3", "container.dispenser"),
|
||||
5 => ("minecraft:hopper", "container.hopper"),
|
||||
let menu = match items.len() {
|
||||
27 => "minecraft:generic_9x3",
|
||||
9 => "minecraft:generic_3x3",
|
||||
5 => "minecraft:hopper",
|
||||
_ => return false,
|
||||
};
|
||||
let title = match &**name {
|
||||
"minecraft:barrel" => "container.barrel",
|
||||
"minecraft:dropper" => "container.dropper",
|
||||
n if n.ends_with("shulker_box") => "container.shulkerBox",
|
||||
_ => title,
|
||||
};
|
||||
(menu, title, Slots::Block(pos))
|
||||
(menu, Slots::Block(pos))
|
||||
};
|
||||
// The menu provider's getDisplayName: a container's custom name
|
||||
// (BaseContainerBlockEntity.getName) or its default name.
|
||||
let custom = |k: (i32, i32, i32)| self.world.block_names.get(&k).map(String::as_str);
|
||||
let title = match slots {
|
||||
Slots::Ender => horizon_protocol::text::translatable("container.enderchest", &[]),
|
||||
Slots::Double(first, second) => {
|
||||
horizon_client::containers::double_chest_name(custom(first), custom(second))
|
||||
}
|
||||
Slots::Block(k) => {
|
||||
let Some(key) = horizon_client::containers::default_name_key(name) else {
|
||||
return false;
|
||||
};
|
||||
horizon_client::containers::display_name(custom(k), key)
|
||||
}
|
||||
};
|
||||
let Some(items) = host
|
||||
.hub
|
||||
@@ -898,14 +895,8 @@ impl Game<'_> {
|
||||
// ServerPlayer.openMenu closes the menu that was open.
|
||||
self.guest_container_closed(host, conn);
|
||||
self.lan_station_closed(host, conn, None);
|
||||
host.hub.open_container(
|
||||
conn,
|
||||
menu,
|
||||
horizon_protocol::text::translatable(title, &[]),
|
||||
pos,
|
||||
slots,
|
||||
items,
|
||||
);
|
||||
host.hub
|
||||
.open_container(conn, menu, title, pos, slots, items);
|
||||
true
|
||||
}
|
||||
|
||||
@@ -1186,9 +1177,6 @@ impl Game<'_> {
|
||||
}
|
||||
S::UseItemOn(p) => {
|
||||
host.hub.ack(conn, p.sequence);
|
||||
if spectator {
|
||||
return;
|
||||
}
|
||||
// handleUseItemOn: within reach, and the hit point within the block.
|
||||
let inside = p
|
||||
.cursor
|
||||
@@ -1331,6 +1319,9 @@ impl Game<'_> {
|
||||
let g = &mut host.hub.guests[gi];
|
||||
let old = g.menu_slot(slot);
|
||||
g.set_menu_slot(slot, item.clone());
|
||||
// InventoryMenu.setRemoteSlot: the client already has it, so broadcastChanges
|
||||
// sends nothing back that could undo a click made since.
|
||||
g.menu_sent[slot] = item.clone();
|
||||
// InventoryMenu's ArmorSlot and off-hand slot: setByPlayer.
|
||||
let equipment = match slot {
|
||||
5..=8 => Some(["head", "chest", "legs", "feet"][slot - 5]),
|
||||
@@ -1667,9 +1658,7 @@ impl Game<'_> {
|
||||
host.hub.teleport(gi, Some(at));
|
||||
}
|
||||
fn guest_tick_death(&mut self, host: &mut LanHost, gi: usize) {
|
||||
let g = &mut host.hub.guests[gi];
|
||||
g.death_time += 1;
|
||||
if g.death_time >= 20 {
|
||||
if host.hub.guests[gi].tick_death() {
|
||||
self.guest_drop_carried(host, gi);
|
||||
}
|
||||
}
|
||||
@@ -1888,8 +1877,11 @@ impl Game<'_> {
|
||||
// ListPlayersCommand needs no permission and lists every player.
|
||||
let words: Vec<&str> = command.trim_start_matches('/').split(' ').collect();
|
||||
if words[0] == "list" && (words.len() == 1 || words[1..] == ["uuids"]) {
|
||||
let me = (self.options.dedicated.is_none() && self.player.is_some())
|
||||
.then_some((host.host_uuid, host.host_name.as_str()));
|
||||
// A single-player owner is a placed guest already: no host entry.
|
||||
let me = (self.options.dedicated.is_none()
|
||||
&& self.player.is_some()
|
||||
&& host.hub.singleplayer_owner.is_none())
|
||||
.then_some((host.host_uuid, host.host_name.as_str()));
|
||||
let content = host.hub.list_reply(me, words.len() == 2);
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
@@ -2372,14 +2364,25 @@ impl Game<'_> {
|
||||
None => self.guest_death_message(conn, me),
|
||||
};
|
||||
let message = horizon_client::lan::data::component_nbt(&text.component());
|
||||
let team = self.score.board.players_team(&name);
|
||||
if horizon_client::scoreboard::own_death_message_shown(team) {
|
||||
host.hub.system_message(message.clone());
|
||||
if self.options.dedicated.is_some() {
|
||||
let board = &self.score.board;
|
||||
host.hub.system_message_to(message.clone(), |other| {
|
||||
horizon_client::scoreboard::death_message_reaches(board, &name, other)
|
||||
});
|
||||
if self.options.dedicated.is_some() {
|
||||
// Only a message for everyone is logged (`broadcastSystemMessage`).
|
||||
if board.players_team(&name).is_none_or(|t| {
|
||||
t.death_message_visibility == horizon_client::scoreboard::Visibility::Always
|
||||
}) {
|
||||
super::dedicated::log("INFO", &format!("System chat: {}", text.plain()));
|
||||
} else if self.player.is_some() {
|
||||
self.system_message(text);
|
||||
}
|
||||
} else if self.player.is_some()
|
||||
&& horizon_client::scoreboard::death_message_reaches(
|
||||
board,
|
||||
&name,
|
||||
super::chat::PLAYER_NAME,
|
||||
)
|
||||
{
|
||||
self.system_message(text);
|
||||
}
|
||||
message
|
||||
} else {
|
||||
|
||||
@@ -242,6 +242,9 @@ impl Game<'_> {
|
||||
_ => None,
|
||||
};
|
||||
if host.hub.guests[gi].spectator() {
|
||||
// handleContainerClick: nothing changes, and sendAllDataToRemote
|
||||
// takes back what the client predicted.
|
||||
host.hub.resend_menu(conn, p.container, &self.world);
|
||||
return true;
|
||||
}
|
||||
let mut menu = host
|
||||
|
||||
@@ -167,6 +167,24 @@ impl Game<'_> {
|
||||
e.meta.push((15, serializer::BYTE, Value::Byte(flags)));
|
||||
}
|
||||
e.meta.extend(stand_poses(a));
|
||||
// Entity.DATA_CUSTOM_NAME and DATA_CUSTOM_NAME_VISIBLE: a hologram's text.
|
||||
if let Some(name) = &a.custom_name {
|
||||
e.meta.push((
|
||||
2,
|
||||
serializer::OPTIONAL_COMPONENT,
|
||||
Value::OptText(Some(horizon_client::scoreboard::json_to_tag(
|
||||
&name.component(),
|
||||
))),
|
||||
));
|
||||
if a.name_visible {
|
||||
e.meta.push((3, serializer::BOOLEAN, Value::Bool(true)));
|
||||
}
|
||||
}
|
||||
// A name taken away or hidden again (`/data`) is sent as none / false.
|
||||
e.defaults
|
||||
.push((2, serializer::OPTIONAL_COMPONENT, Value::OptText(None)));
|
||||
e.defaults
|
||||
.push((3, serializer::BOOLEAN, Value::Bool(false)));
|
||||
// A pose put back to its default (`/data`) is sent as that default.
|
||||
e.defaults.push((15, serializer::BYTE, Value::Byte(0)));
|
||||
for (i, default) in horizon_client::entities::ArmorStand::DEFAULT_POSE
|
||||
|
||||
@@ -109,16 +109,6 @@ fn offset(p: Pos, d: Direction) -> Pos {
|
||||
let s = step(d);
|
||||
(p.0 + s[0], p.1 + s[1], p.2 + s[2])
|
||||
}
|
||||
fn clockwise(d: Direction) -> Direction {
|
||||
match d {
|
||||
Direction::North => Direction::East,
|
||||
Direction::East => Direction::South,
|
||||
Direction::South => Direction::West,
|
||||
Direction::West => Direction::North,
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// State-level container queries shared by the game and comparator signals.
|
||||
struct Containers<'a> {
|
||||
world: &'a World,
|
||||
@@ -176,7 +166,7 @@ impl Containers<'_> {
|
||||
_ => Kind::Generic,
|
||||
};
|
||||
let size = entity.slots().len();
|
||||
if matches!(name, "minecraft:chest" | "minecraft:trapped_chest") {
|
||||
if horizon_client::containers::is_chest_block(name) {
|
||||
let is_blocked = |p: Pos| {
|
||||
let above = self.world.block(p.0, p.1 + 1, p.2);
|
||||
self.behaviours.facts(above).flags
|
||||
@@ -186,22 +176,19 @@ impl Containers<'_> {
|
||||
if blocked_chests && is_blocked(pos) {
|
||||
return None;
|
||||
}
|
||||
let kind_prop = self.prop(state, "type").unwrap_or("single");
|
||||
if kind_prop != "single"
|
||||
&& let Some(facing) = self.prop(state, "facing").and_then(dir_from_name)
|
||||
let half = |s: BlockStateId| {
|
||||
Some(horizon_client::containers::ChestHalf {
|
||||
block: self.name(s),
|
||||
kind: self.prop(s, "type")?,
|
||||
facing: self.prop(s, "facing")?,
|
||||
})
|
||||
};
|
||||
if let Some(own) = half(state)
|
||||
&& let Some((dx, dz)) = own.connected_step()
|
||||
{
|
||||
// ChestBlock.getConnectedDirection
|
||||
let connected = if kind_prop == "left" {
|
||||
clockwise(facing)
|
||||
} else {
|
||||
clockwise(clockwise(clockwise(facing)))
|
||||
};
|
||||
let other = offset(pos, connected);
|
||||
let other = (pos.0 + dx, pos.1, pos.2 + dz);
|
||||
let other_state = self.world.block(other.0, other.1, other.2);
|
||||
let paired = self.name(other_state) == name
|
||||
&& self
|
||||
.prop(other_state, "type")
|
||||
.is_some_and(|t| t != "single" && t != kind_prop)
|
||||
let paired = half(other_state).is_some_and(|o| own.pairs_with(&o))
|
||||
&& self
|
||||
.world
|
||||
.block_entities
|
||||
@@ -211,7 +198,7 @@ impl Containers<'_> {
|
||||
if blocked_chests && is_blocked(other) {
|
||||
return None;
|
||||
}
|
||||
let parts = if kind_prop == "right" {
|
||||
let parts = if own.kind == "right" {
|
||||
vec![(pos, size), (other, 27)]
|
||||
} else {
|
||||
vec![(other, 27), (pos, size)]
|
||||
|
||||
@@ -246,9 +246,15 @@ impl Game<'_> {
|
||||
self.paint_screen(batch, ox, oy, background, true);
|
||||
let atlas = &self.gui.atlas;
|
||||
let grey = rgba(64, 64, 64, 255);
|
||||
let title = self.container_title(self.translate("container.crafter", "Crafter"));
|
||||
let tw = HudBatch::text_width(atlas, &title);
|
||||
batch.text(
|
||||
// A server's crafter menu has the title it was given.
|
||||
let title = self.remote_menu_title().unwrap_or_else(|| {
|
||||
horizon_client::text::Text::literal(
|
||||
self.container_title(self.translate("container.crafter", "Crafter")),
|
||||
)
|
||||
.resolve_legacy()
|
||||
});
|
||||
let tw = atlas.font.width_text(&title);
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&title,
|
||||
ox + ((176.0 - tw) / 2.0).trunc(),
|
||||
|
||||
@@ -1308,7 +1308,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// `renderTwoHandedMap`: map `id` held in both hands, in view space (the
|
||||
/// arms under it are not drawn).
|
||||
/// arms under it: `first_person::map_arm_poses`).
|
||||
pub(super) fn two_handed_map_geometry(
|
||||
&mut self,
|
||||
to_world: glam::Mat4,
|
||||
@@ -1318,22 +1318,11 @@ impl Game<'_> {
|
||||
light: u32,
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
use horizon_core::geometry::trig::Mth;
|
||||
let deg = |d: f32| d.to_radians();
|
||||
let sqrt_attack = attack.sqrt();
|
||||
let y_swing = -0.2 * (attack * std::f32::consts::PI).sin();
|
||||
let z_swing = -0.4 * (sqrt_attack * std::f32::consts::PI).sin();
|
||||
// calculateMapTilt
|
||||
let tilt = (1.0 - self.pitch / 45.0 + 0.1).clamp(0.0, 1.0);
|
||||
let tilt = -(tilt * std::f32::consts::PI).cos() * 0.5 + 0.5;
|
||||
let base = to_world
|
||||
* glam::Mat4::from_translation(glam::Vec3::new(0.0, -y_swing / 2.0, z_swing))
|
||||
* glam::Mat4::from_translation(glam::Vec3::new(
|
||||
0.0,
|
||||
0.04 + inverse_height * -1.2 + tilt * -0.5,
|
||||
-0.72,
|
||||
))
|
||||
* glam::Mat4::from_rotation_x(deg(tilt * -85.0));
|
||||
let swing = (sqrt_attack * std::f32::consts::PI).sin();
|
||||
* horizon_client::first_person::two_handed_map_base(self.pitch, inverse_height, attack);
|
||||
let swing = (attack.sqrt() * std::f32::consts::PI).msin();
|
||||
let m = base
|
||||
* glam::Mat4::from_rotation_x(deg(swing * 20.0))
|
||||
* glam::Mat4::from_scale(glam::Vec3::splat(2.0));
|
||||
|
||||
@@ -1227,6 +1227,20 @@ impl Game<'_> {
|
||||
light: u32,
|
||||
diffuse: bool,
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
self.block_model_vertices_tinted(state, seed, m, light, diffuse, 0xFF_FFFF, out);
|
||||
}
|
||||
/// `block_model_vertices` with `tint` (RGB) on the faces that have a tint index.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn block_model_vertices_tinted(
|
||||
&self,
|
||||
state: BlockStateId,
|
||||
seed: i64,
|
||||
m: glam::Mat4,
|
||||
light: u32,
|
||||
diffuse: bool,
|
||||
tint: u32,
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
let Ok(models) = self.pack.render.model_catalog.collect_seeded(state, seed) else {
|
||||
return;
|
||||
@@ -1253,6 +1267,12 @@ impl Game<'_> {
|
||||
} else {
|
||||
0xFF00_0000 | shade << 16 | shade << 8 | shade
|
||||
};
|
||||
let color = if face.quad.tint_index >= 0 {
|
||||
let tint = horizon_client::mobs::render::abgr(tint);
|
||||
horizon_client::hud_layout::multiply(color, tint)
|
||||
} else {
|
||||
color
|
||||
};
|
||||
let normal = if diffuse {
|
||||
use horizon_client::item_render::{direction_vector, transform_normal};
|
||||
let n = transform_normal(m, direction_vector(face.quad.facing));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Blocks mobs carry: block items in a hand (`ItemInHandLayer`) and the
|
||||
//! block an enderman holds (`CarriedBlockLayer`), drawn as shaded cubes like
|
||||
//! dropped block items. Also the block models mobs wear (`SnowGolemHeadLayer`,
|
||||
//! block an enderman holds (`CarriedBlockLayer`), drawn as baked block models.
|
||||
//! Also the block models mobs wear (`SnowGolemHeadLayer`,
|
||||
//! `MushroomCowMushroomLayer`).
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
@@ -9,46 +9,6 @@ use horizon_client::{
|
||||
mobs::{Mob, Species, render},
|
||||
};
|
||||
|
||||
/// The six faces of the unit cube with their shade: top, bottom, the two
|
||||
/// z faces, the two x faces.
|
||||
const FACES: [([[f32; 3]; 4], f32, u8); 6] = [
|
||||
(
|
||||
[[0., 1., 1.], [1., 1., 1.], [1., 1., 0.], [0., 1., 0.]],
|
||||
1.0,
|
||||
0,
|
||||
),
|
||||
(
|
||||
[[0., 0., 0.], [1., 0., 0.], [1., 0., 1.], [0., 0., 1.]],
|
||||
0.5,
|
||||
0,
|
||||
),
|
||||
(
|
||||
[[1., 0., 0.], [0., 0., 0.], [0., 1., 0.], [1., 1., 0.]],
|
||||
0.8,
|
||||
1,
|
||||
),
|
||||
(
|
||||
[[0., 0., 1.], [1., 0., 1.], [1., 1., 1.], [0., 1., 1.]],
|
||||
0.8,
|
||||
1,
|
||||
),
|
||||
(
|
||||
[[0., 0., 0.], [0., 0., 1.], [0., 1., 1.], [0., 1., 0.]],
|
||||
0.6,
|
||||
2,
|
||||
),
|
||||
(
|
||||
[[1., 0., 1.], [1., 0., 0.], [1., 1., 0.], [1., 1., 1.]],
|
||||
0.6,
|
||||
2,
|
||||
),
|
||||
];
|
||||
/// The sprites of a cube's top, z sides and x sides, and the top's tint.
|
||||
struct Cube<'a> {
|
||||
sprites: [&'a str; 3],
|
||||
tint: u32,
|
||||
}
|
||||
|
||||
/// `CustomHeadLayer.translateToHead` and the banner's `head` display.
|
||||
fn banner_matrix(head: glam::Mat4) -> glam::Mat4 {
|
||||
head * glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.25, 0.0))
|
||||
@@ -178,38 +138,6 @@ impl Game<'_> {
|
||||
render::draw(flag, m, &flag_poses, r, color, light, 0, out);
|
||||
}
|
||||
}
|
||||
fn push_cube(
|
||||
&self,
|
||||
t: glam::Mat4,
|
||||
cube: &Cube,
|
||||
light: u32,
|
||||
overlay: u32,
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
for (corners, shade, side) in FACES {
|
||||
let name = cube.sprites[usize::from(side)];
|
||||
let Some(r) = self.gui.atlas.sprites.get(name).copied() else {
|
||||
continue;
|
||||
};
|
||||
let tint = if side == 0 { cube.tint } else { 0xFF_FFFF };
|
||||
let c = |sft: u32| (((tint >> sft) & 255) as f32 * shade) as u32;
|
||||
let color = 0xFF00_0000 | c(0) << 16 | c(8) << 8 | c(16);
|
||||
let uvs = [[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]];
|
||||
for (corner, uv) in corners.iter().zip(uvs) {
|
||||
let p = t.transform_point3(glam::Vec3::from(*corner));
|
||||
out.push(Vertex {
|
||||
normal: [0; 4],
|
||||
pos: p.to_array(),
|
||||
uv,
|
||||
layer: overlay,
|
||||
color,
|
||||
light,
|
||||
|
||||
glint_uv: [0.0, 0.0],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The blocks one mob holds or carries.
|
||||
pub(super) fn mob_block_geometry(
|
||||
&self,
|
||||
@@ -222,11 +150,13 @@ impl Game<'_> {
|
||||
self.captain_banner_geometry(mob, camera, alpha, light, out);
|
||||
self.held_item_geometry(mob, camera, alpha, light, true, out);
|
||||
self.worn_block_geometry(mob, camera, alpha, light, out);
|
||||
self.golem_flower_geometry(mob, camera, alpha, light, out);
|
||||
if mob.species() == Species::Enderman
|
||||
&& let Some(state) = mob.extra.carried
|
||||
&& let Some((sprite, tint)) = self.block_face_sprite(state)
|
||||
&& let Some((_, tint)) = self.block_face_sprite(state)
|
||||
{
|
||||
// CarriedBlockLayer: OverlayTexture.NO_OVERLAY, never the hurt tint.
|
||||
// CarriedBlockLayer: OverlayTexture.NO_OVERLAY, never the hurt tint;
|
||||
// the block's baked model (seed 42) on the unit cube, not centred.
|
||||
let base = render::base_transform(mob, alpha as f32, camera);
|
||||
let t = base
|
||||
* glam::Mat4::from_translation(glam::Vec3::new(0.0, 0.6875, -0.75))
|
||||
@@ -234,20 +164,43 @@ impl Game<'_> {
|
||||
* glam::Mat4::from_rotation_y(45.0f32.to_radians())
|
||||
* glam::Mat4::from_translation(glam::Vec3::new(0.25, 0.1875, 0.25))
|
||||
* glam::Mat4::from_scale(glam::Vec3::new(-0.5, -0.5, 0.5))
|
||||
* glam::Mat4::from_rotation_y(90.0f32.to_radians())
|
||||
* glam::Mat4::from_translation(glam::Vec3::splat(-0.5));
|
||||
self.push_cube(
|
||||
t,
|
||||
&Cube {
|
||||
sprites: [&sprite, &sprite, &sprite],
|
||||
tint,
|
||||
},
|
||||
light,
|
||||
0,
|
||||
out,
|
||||
);
|
||||
* glam::Mat4::from_rotation_y(90.0f32.to_radians());
|
||||
self.block_model_vertices_tinted(state, 42, t, light, true, tint, out);
|
||||
}
|
||||
}
|
||||
/// `IronGolemFlowerLayer`: the poppy in the right arm while the golem
|
||||
/// offers it (`getOfferFlowerTick() > 0`), drawn with `NO_OVERLAY`.
|
||||
fn golem_flower_geometry(
|
||||
&self,
|
||||
mob: &Mob,
|
||||
camera: glam::DVec3,
|
||||
alpha: f64,
|
||||
light: u32,
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
use glam::{Mat4, Vec3};
|
||||
if mob.species() != Species::IronGolem
|
||||
|| mob.extra.counter <= 0
|
||||
|| horizon_client::mobs::trader::is_invisible(mob)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(state) = self.pack.assets.registry.default_state("minecraft:poppy") else {
|
||||
return;
|
||||
};
|
||||
let Some(arm) =
|
||||
render::part_transform(mob, alpha as f32, camera, self.res.mob_data(), "right_arm")
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let t = arm
|
||||
* Mat4::from_translation(Vec3::new(-1.1875, 1.0625, -0.9375))
|
||||
* Mat4::from_translation(Vec3::splat(0.5))
|
||||
* Mat4::from_scale(Vec3::splat(0.5))
|
||||
* Mat4::from_rotation_x((-90.0f32).to_radians())
|
||||
* Mat4::from_translation(Vec3::splat(-0.5));
|
||||
self.block_model_vertices(state, 42, t, light, true, out);
|
||||
}
|
||||
/// `SnowGolemHeadLayer` and `MushroomCowMushroomLayer`: the carved pumpkin
|
||||
/// on a snow golem's head, and the mushrooms on an adult mooshroom's back
|
||||
/// and head, as baked block models.
|
||||
@@ -387,9 +340,10 @@ impl Game<'_> {
|
||||
owner.crossbow_charge_duration = 25;
|
||||
}
|
||||
use horizon_assets::item_model::DisplayContext as Context;
|
||||
// PandaHoldsItemLayer shows the item as it lies on the ground.
|
||||
// PandaHoldsItemLayer and FoxHeldItemLayer show the item as it lies
|
||||
// on the ground.
|
||||
let (context, ordinal) = match (mob.species(), left) {
|
||||
(Species::Panda, _) => (Context::Ground, 7),
|
||||
(Species::Panda | Species::Fox, _) => (Context::Ground, 7),
|
||||
(_, true) => (Context::ThirdPersonLeftHand, 1),
|
||||
(_, false) => (Context::ThirdPersonRightHand, 2),
|
||||
};
|
||||
|
||||
@@ -6,7 +6,7 @@ use super::Game;
|
||||
use horizon_client::hud::HudBatch;
|
||||
#[cfg(feature = "mods")]
|
||||
use {
|
||||
horizon_client::{hud::rgba, items::ItemStack, text::Text},
|
||||
horizon_client::{hud::rgba, items::ItemStack, text::Text, ui},
|
||||
horizon_mods::Shape,
|
||||
std::time::Instant,
|
||||
};
|
||||
@@ -108,7 +108,17 @@ impl Game<'_> {
|
||||
let r = s.rect;
|
||||
let name = s.sprite.strip_prefix("minecraft:").unwrap_or(&s.sprite);
|
||||
let name = format!("gui/sprites/{name}");
|
||||
batch.sprite_scaled(atlas, &name, ox + r.x, oy + r.y, r.w, r.h, argb(s.color));
|
||||
// As vanilla's blitSprite: a frame or a button keeps its border.
|
||||
ui::blit_sprite(
|
||||
batch,
|
||||
atlas,
|
||||
&name,
|
||||
ox + r.x,
|
||||
oy + r.y,
|
||||
r.w,
|
||||
r.h,
|
||||
argb(s.color),
|
||||
);
|
||||
}
|
||||
Shape::Item(i) => {
|
||||
if self.res.items().get(&i.item).is_none() {
|
||||
|
||||
@@ -1074,26 +1074,15 @@ impl Game<'_> {
|
||||
batch.fill(atlas, xx, yy, 1.0, wh, 0xFF50_5050);
|
||||
}
|
||||
let content = l.rows.len() as f32 * 12.0;
|
||||
let first = (scroll.amount / 12.0) as usize;
|
||||
let last = (first + ((rows_bottom - rows_top) / 12.0).ceil() as usize + 1)
|
||||
.min(l.rows.len());
|
||||
for (vi, ri) in (first..last).enumerate() {
|
||||
let ry = rows_top + vi as f32 * 12.0 - (scroll.amount % 12.0);
|
||||
if ui::hovered(self.cursor, x, ry, MOD_UI_COLUMN - 6.0, 12.0) {
|
||||
batch.fill(atlas, x + 1.0, ry, MOD_UI_COLUMN - 8.0, 12.0, 0x20FF_FFFF);
|
||||
}
|
||||
if l.selected == Some(ri as u32) {
|
||||
batch.fill(atlas, x + 1.0, ry, 3.0, 12.0, 0xFFFF_FFFF);
|
||||
}
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&Text::literal(l.rows[ri].clone()),
|
||||
x + 6.0,
|
||||
ry + 2.0,
|
||||
u32::MAX,
|
||||
true,
|
||||
);
|
||||
}
|
||||
draw_list_rows(
|
||||
batch,
|
||||
atlas,
|
||||
self.cursor,
|
||||
&l.rows,
|
||||
l.selected,
|
||||
scroll.amount,
|
||||
(x, wy, wh),
|
||||
);
|
||||
ui::scrollbar(
|
||||
batch,
|
||||
atlas,
|
||||
@@ -1231,6 +1220,51 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A mod screen's `list` rows in its frame at (`x`, `wy`), `wh` high, scrolled by `scroll`: the
|
||||
/// rows in view, the hovered one lit and the selected one marked. As AbstractSelectionList draws
|
||||
/// its entries inside `enableScissor`, they are cut at the frame's inside: the row a scroll shows
|
||||
/// in part, and the one below a full view, never draw over the frame or below it.
|
||||
#[cfg(feature = "mods")]
|
||||
fn draw_list_rows(
|
||||
batch: &mut HudBatch,
|
||||
atlas: &horizon_client::hud::HudAtlas,
|
||||
cursor: (f32, f32),
|
||||
rows: &[String],
|
||||
selected: Option<u32>,
|
||||
scroll: f32,
|
||||
(x, wy, wh): (f32, f32, f32),
|
||||
) {
|
||||
let rows_top = wy + 4.0;
|
||||
let rows_bottom = wy + wh - 4.0;
|
||||
let first = (scroll / 12.0) as usize;
|
||||
let last = (first + ((rows_bottom - rows_top) / 12.0).ceil() as usize + 1).min(rows.len());
|
||||
let start = batch.vertices.len();
|
||||
for (vi, ri) in (first..last).enumerate() {
|
||||
let ry = rows_top + vi as f32 * 12.0 - (scroll % 12.0);
|
||||
if ui::hovered(cursor, x, ry, MOD_UI_COLUMN - 6.0, 12.0) {
|
||||
batch.fill(atlas, x + 1.0, ry, MOD_UI_COLUMN - 8.0, 12.0, 0x20FF_FFFF);
|
||||
}
|
||||
if selected == Some(ri as u32) {
|
||||
batch.fill(atlas, x + 1.0, ry, 3.0, 12.0, 0xFFFF_FFFF);
|
||||
}
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&Text::literal(rows[ri].clone()),
|
||||
x + 6.0,
|
||||
ry + 2.0,
|
||||
u32::MAX,
|
||||
true,
|
||||
);
|
||||
}
|
||||
batch.clip_since(
|
||||
start,
|
||||
x + 1.0,
|
||||
wy + 1.0,
|
||||
x + MOD_UI_COLUMN - 1.0,
|
||||
wy + wh - 1.0,
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "mods")]
|
||||
const MOD_UI_TOP: f32 = 40.0;
|
||||
#[cfg(feature = "mods")]
|
||||
@@ -1238,3 +1272,45 @@ const MOD_UI_COLUMN: f32 = 200.0;
|
||||
/// A key row's height with its gap, as the widgets below it space out.
|
||||
#[cfg(feature = "mods")]
|
||||
const MOD_UI_KEY_ROW: f32 = 26.0;
|
||||
|
||||
#[cfg(all(test, feature = "mods"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_client::hud::HudAtlas;
|
||||
|
||||
#[test]
|
||||
fn list_rows_stay_inside_the_frame_scrolled_or_not() {
|
||||
let atlas =
|
||||
HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap();
|
||||
// #3237: 22 rows in a frame of 6 (mod_ui_layout's height for a long list). The 7th row
|
||||
// (index 6), drawn for a scroll that shows it in part, is selected and under the
|
||||
// cursor, so its fills reach past the frame unless they are cut.
|
||||
let rows: Vec<String> = (0..22).map(|i| format!("Row {i}")).collect();
|
||||
let (x, wy, wh) = (100.0, 40.0, 6.0 * 12.0 + 8.0);
|
||||
for scroll in [0.0, 6.0, 30.0] {
|
||||
let mut batch = HudBatch::new([640, 480]);
|
||||
let seventh_row = wy + 4.0 + 6.0 * 12.0 - scroll % 12.0;
|
||||
draw_list_rows(
|
||||
&mut batch,
|
||||
&atlas,
|
||||
(x + 10.0, seventh_row + 2.0),
|
||||
&rows,
|
||||
Some(6 + (scroll / 12.0) as u32),
|
||||
scroll,
|
||||
(x, wy, wh),
|
||||
);
|
||||
assert!(!batch.vertices.is_empty(), "scroll {scroll}: rows drawn");
|
||||
let (top, bottom) = batch
|
||||
.vertices
|
||||
.iter()
|
||||
.map(|v| v.pos[1])
|
||||
.fold((f32::MAX, f32::MIN), |(lo, hi), y| (lo.min(y), hi.max(y)));
|
||||
assert!(
|
||||
top >= wy + 1.0 && bottom <= wy + wh - 1.0,
|
||||
"scroll {scroll}: rows span {top}..{bottom}, the frame's inside is {}..{}",
|
||||
wy + 1.0,
|
||||
wy + wh - 1.0
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -142,13 +142,36 @@ impl Game<'_> {
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// SkeletonHorse.mobInteract: nothing for an untamed one.
|
||||
if species == Species::SkeletonHorse && !m.extra.tame {
|
||||
return false;
|
||||
}
|
||||
let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft)
|
||||
|| self.keys.contains(&winit::keyboard::KeyCode::ShiftRight);
|
||||
// Horse / ZombieHorse.mobInteract: food is fed, and anything else in
|
||||
// hand makes an untamed one mad instead of seating the player.
|
||||
let dandelion = [self.held(), self.offhand.as_ref()]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|s| &*s.item == "minecraft:golden_dandelion");
|
||||
let mut events = Vec::new();
|
||||
match equine::held_item(
|
||||
&mut self.mobs[index],
|
||||
item,
|
||||
sneaking,
|
||||
dandelion,
|
||||
&mut events,
|
||||
) {
|
||||
Some(equine::HeldItem::Feed) => return self.feed_mount(index, item),
|
||||
Some(equine::HeldItem::Refused) => {
|
||||
let _ = self.handle_mob_events(events);
|
||||
return true;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
let m = &self.mobs[index];
|
||||
// AbstractHorse.mobInteract: shift + use opens a tamed adult's inventory.
|
||||
if !m.is_baby()
|
||||
&& m.extra.tame
|
||||
&& (self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft)
|
||||
|| self.keys.contains(&winit::keyboard::KeyCode::ShiftRight))
|
||||
{
|
||||
if !m.is_baby() && m.extra.tame && sneaking {
|
||||
self.open_mount_menu(index);
|
||||
return true;
|
||||
}
|
||||
@@ -489,6 +512,22 @@ impl Game<'_> {
|
||||
MobEvent::Buck { mob } => {
|
||||
if self.riding == Some(mob) {
|
||||
self.dismount_mount();
|
||||
} else {
|
||||
// ejectPassengers: a server's player gets off too
|
||||
// (leave_guest tells their client).
|
||||
let rider = self.lan.as_ref().and_then(|h| {
|
||||
h.hub
|
||||
.guests
|
||||
.iter()
|
||||
.find(|g| g.vehicle == Some(mob))
|
||||
.map(|g| g.conn)
|
||||
});
|
||||
if let Some(conn) = rider
|
||||
&& let Some(mut host) = self.lan.take()
|
||||
{
|
||||
self.as_guest(&mut host, conn, |g| g.dismount_mount());
|
||||
self.lan = Some(host);
|
||||
}
|
||||
}
|
||||
// RunAroundLikeCrazyGoal.tick: entity event 6, smoke.
|
||||
self.mob_event_particles(mob, 6);
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
//! or a server) show whenever `LivingEntityRenderer.shouldShowName` allows.
|
||||
use super::{Game, view_vector};
|
||||
use horizon_client::{
|
||||
block_entity_render::vertex_light, mesher::Vertex, mobs::Mob, save::uuid_text,
|
||||
block_entity_render::vertex_light, hud::HudBatch, mesher::Vertex, mobs::Mob, save::uuid_text,
|
||||
scoreboard as sb, text::Text,
|
||||
};
|
||||
|
||||
@@ -289,7 +289,7 @@ impl Game<'_> {
|
||||
/// faded, on its background; any other in full over the world, its faded
|
||||
/// copy and background in `see_through`, over everything.
|
||||
pub(super) fn name_tag_geometry(
|
||||
&self,
|
||||
&mut self,
|
||||
camera: glam::DVec3,
|
||||
alpha: f64,
|
||||
out: &mut Vec<Vertex>,
|
||||
@@ -298,26 +298,31 @@ impl Game<'_> {
|
||||
// The text alpha that goes with getBackgroundOpacity(0.25):
|
||||
// max((0.25 + 0.75) / 2, 0.5), as ARGB.color (the floor of 255 times it).
|
||||
const FADED: u32 = 0x7F;
|
||||
let mut patches = Vec::new();
|
||||
for tag in self.name_tags(camera, alpha) {
|
||||
let o = tag.at - camera;
|
||||
// `gbuffers_entities` draws name tag text (2.3); a sneaking player's faded tag, on its
|
||||
// background, blends.
|
||||
if tag.discrete {
|
||||
self.mark_translucent_entity(out.len(), "minecraft:name_tag");
|
||||
self.name_tag_quads(o, &tag.lines, FADED, true, 0, vertex_light(tag.light), out);
|
||||
let light = vertex_light(tag.light);
|
||||
patches.extend(self.name_tag_quads(o, &tag.lines, FADED, true, 0, light, out));
|
||||
continue;
|
||||
}
|
||||
// LightCoordsUtil.lightCoordsWithEmission(lightCoords, 2).
|
||||
let lit = (tag.light >> 4).max(2) << 4 | (tag.light & 15).max(2);
|
||||
self.mark_entity(out.len(), "minecraft:name_tag");
|
||||
self.name_tag_quads(o, &tag.lines, 0xFF, false, 0, vertex_light(lit), out);
|
||||
let light = vertex_light(lit);
|
||||
patches.extend(self.name_tag_quads(o, &tag.lines, 0xFF, false, 0, light, out));
|
||||
// RenderPipelines.TEXT_SEE_THROUGH: no depth test, no lightmap.
|
||||
self.name_tag_quads(o, &tag.lines, FADED, true, 2, 0, see_through);
|
||||
patches.extend(self.name_tag_quads(o, &tag.lines, FADED, true, 2, 0, see_through));
|
||||
}
|
||||
self.map_patches.extend(patches);
|
||||
}
|
||||
/// The lines of one name tag, `o` from the camera: the text at
|
||||
/// `text_alpha` in its layer, on the translucent black background
|
||||
/// (in `text_layer` like the glyphs, a hair behind) when `background`.
|
||||
/// Returns the glyph pixels the atlas still needs.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn name_tag_quads(
|
||||
&self,
|
||||
@@ -328,7 +333,7 @@ impl Game<'_> {
|
||||
text_layer: u32,
|
||||
light: u32,
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
) -> Vec<horizon_client::font::Patch> {
|
||||
// Options.getBackgroundOpacity(0.25) black, as ARGB.color.
|
||||
const BACKGROUND: u32 = 0x3F00_0000;
|
||||
// The camera's facing (Camera.rotation()), turned round in third-person
|
||||
@@ -342,85 +347,50 @@ impl Game<'_> {
|
||||
let forward = glam::DVec3::from_array(view_vector(view_yaw, view_pitch));
|
||||
let right = forward.cross(glam::DVec3::Y).normalize_or_zero();
|
||||
let up = right.cross(forward).normalize_or_zero();
|
||||
let white = self.gui.atlas.font.white();
|
||||
let away = forward.as_vec3() * 0.002;
|
||||
let mut batch = HudBatch::new([1, 1]);
|
||||
for (text, lift) in lines {
|
||||
let o = (o + glam::DVec3::new(0.0, *lift, 0.0)).as_vec3();
|
||||
let (r, u) = (right.as_vec3() * 0.025, up.as_vec3() * 0.025);
|
||||
// Text space: x right, y down (scale 0.025, -0.025).
|
||||
let at = |x: f32, y: f32| o + r * x - u * y;
|
||||
// Component.getVisualOrderText.
|
||||
let shown = horizon_client::bidi::visual(text);
|
||||
let chars: Vec<(char, u32)> = shown
|
||||
.spans
|
||||
.iter()
|
||||
.flat_map(|s| {
|
||||
let rgb = s.style.color.unwrap_or(0xFF_FF_FF);
|
||||
// RGBA8, alpha in the top byte.
|
||||
let color = text_alpha << 24
|
||||
| ((rgb & 0xFF) << 16)
|
||||
| (rgb & 0xFF00)
|
||||
| ((rgb >> 16) & 0xFF);
|
||||
s.text.chars().map(move |c| (c, color))
|
||||
})
|
||||
.collect();
|
||||
let width: f32 = chars
|
||||
.iter()
|
||||
.map(|(c, _)| self.gui.atlas.glyph(*c).map_or(6.0, |g| g.1))
|
||||
.sum();
|
||||
let x0 = -(width / 2.0).trunc();
|
||||
let y0 = if text.plain() == "deadmau5" {
|
||||
-10.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let mut quad = |a: [f32; 4], uv: [f32; 4], color: u32, behind: bool, layer: u32| {
|
||||
let corners = [(a[0], a[3]), (a[2], a[3]), (a[2], a[1]), (a[0], a[1])];
|
||||
let uvs = [
|
||||
[uv[0], uv[3]],
|
||||
[uv[2], uv[3]],
|
||||
[uv[2], uv[1]],
|
||||
[uv[0], uv[1]],
|
||||
];
|
||||
for ((x, y), uv) in corners.into_iter().zip(uvs) {
|
||||
batch.vertices.clear();
|
||||
// Font.prepareText, as any text: bold, italic, fonts and each
|
||||
// glyph's own box (accented.png's are 12 pixels tall).
|
||||
let behind = batch.name_tag(
|
||||
&self.gui.atlas,
|
||||
text,
|
||||
y0,
|
||||
text_alpha << 24 | 0xFF_FFFF,
|
||||
if background { BACKGROUND } else { 0 },
|
||||
);
|
||||
for (i, quad) in batch.vertices.as_chunks::<6>().0.iter().enumerate() {
|
||||
let shift = if i * 6 < behind {
|
||||
away
|
||||
} else {
|
||||
glam::Vec3::ZERO
|
||||
};
|
||||
// The corners from the bottom left, as the world draws quads.
|
||||
for v in [quad[5], quad[2], quad[1], quad[0]] {
|
||||
out.push(Vertex {
|
||||
normal: [0; 4],
|
||||
pos: (at(x, y) + if behind { away } else { glam::Vec3::ZERO }).to_array(),
|
||||
uv,
|
||||
layer,
|
||||
color,
|
||||
pos: (at(v.pos[0], v.pos[1]) + shift).to_array(),
|
||||
uv: v.uv,
|
||||
layer: text_layer,
|
||||
color: v.color,
|
||||
light,
|
||||
glint_uv: [0.0, 0.0],
|
||||
});
|
||||
}
|
||||
};
|
||||
if background {
|
||||
quad(
|
||||
[x0 - 1.0, y0 - 1.0, x0 + width, y0 + 8.0],
|
||||
[white.u0, white.v0, white.u1, white.v1],
|
||||
BACKGROUND,
|
||||
true,
|
||||
text_layer,
|
||||
);
|
||||
}
|
||||
let mut x = x0;
|
||||
for (ch, color) in chars {
|
||||
let Some((g, advance)) = self.gui.atlas.glyph(ch) else {
|
||||
x += 6.0;
|
||||
continue;
|
||||
};
|
||||
if ch != ' ' {
|
||||
quad(
|
||||
[x, y0, x + 8.0, y0 + 8.0],
|
||||
[g.u0, g.v0, g.u1, g.v1],
|
||||
color,
|
||||
false,
|
||||
text_layer,
|
||||
);
|
||||
}
|
||||
x += advance;
|
||||
}
|
||||
}
|
||||
// Glyphs rasterized on first use (Unifont's) upload with the frame.
|
||||
batch.patches
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -305,7 +305,8 @@ impl Game<'_> {
|
||||
let _ = mods;
|
||||
}
|
||||
/// The buttons of mod `mod_id`'s settings page, under its keys: push
|
||||
/// their labels when it is yours. Asked again after each click.
|
||||
/// their labels when it is yours. Asked again each time the page opens
|
||||
/// and after each click.
|
||||
pub(super) fn native_settings(&mut self, mod_id: &str, buttons: &mut Vec<String>) {
|
||||
let _ = (mod_id, buttons);
|
||||
}
|
||||
@@ -341,9 +342,12 @@ impl Game<'_> {
|
||||
pub(super) fn native_window(&self) -> bool {
|
||||
self.options.execution_role == ExecutionRole::Client
|
||||
}
|
||||
/// Whether a box in `corner` shows: F3's debug screen takes the top left.
|
||||
/// Whether a box in `corner` shows: F3's debug screen takes both top
|
||||
/// corners (its left and right columns), and a bottom corner while one
|
||||
/// of its charts is drawn there.
|
||||
pub(super) fn native_corner_shown(&self, corner: Corner) -> bool {
|
||||
!self.debug || corner != Corner::TopLeft
|
||||
let charts = self.debug_charts.corners(!self.has_singleplayer_server());
|
||||
!debug_takes(corner, self.debug, charts)
|
||||
}
|
||||
/// The width of `text` in GUI pixels.
|
||||
pub(super) fn native_text_width(&self, text: &str) -> f32 {
|
||||
@@ -533,6 +537,14 @@ impl Game<'_> {
|
||||
return;
|
||||
};
|
||||
self.native_settings_click(&id, button);
|
||||
self.native_settings_refresh(i);
|
||||
}
|
||||
/// Native mod `i`'s page opened: its labels asked again, so that they
|
||||
/// follow the language (and the mod's state) since the list was made.
|
||||
pub(super) fn native_settings_refresh(&mut self, i: usize) {
|
||||
let Some(id) = self.settings.mods.installed.get(i).map(|m| m.id.clone()) else {
|
||||
return;
|
||||
};
|
||||
let mut buttons = Vec::new();
|
||||
self.native_settings(&id, &mut buttons);
|
||||
let row = self.settings.mods.installed.get_mut(i);
|
||||
@@ -602,6 +614,19 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether F3's debug screen, open when `debug`, covers `corner`
|
||||
/// (`DebugScreenOverlay.extractRenderState`): its left and right columns
|
||||
/// the top corners, and its charts the bottom corners `charts` (bottom left,
|
||||
/// bottom right) says they are drawn in.
|
||||
fn debug_takes(corner: Corner, debug: bool, charts: [bool; 2]) -> bool {
|
||||
debug
|
||||
&& match corner {
|
||||
Corner::TopLeft | Corner::TopRight => true,
|
||||
Corner::BottomLeft => charts[0],
|
||||
Corner::BottomRight => charts[1],
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` within `lo..=hi`; `lo` when it is not a number.
|
||||
fn finite(v: f32, lo: f32, hi: f32) -> f32 {
|
||||
if v.is_finite() { v.clamp(lo, hi) } else { lo }
|
||||
@@ -625,4 +650,21 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Vanilla's F3 draws a column in each top corner (`extractLines`, left
|
||||
/// and right aligned), and its charts along the bottom.
|
||||
#[test]
|
||||
fn the_debug_screen_takes_both_top_corners_and_its_charts_corners() {
|
||||
use super::{Corner, debug_takes};
|
||||
for corner in Corner::ALL {
|
||||
assert!(!debug_takes(corner, false, [true, true]), "{corner:?}");
|
||||
}
|
||||
assert!(debug_takes(Corner::TopLeft, true, [false, false]));
|
||||
assert!(debug_takes(Corner::TopRight, true, [false, false]));
|
||||
assert!(!debug_takes(Corner::BottomLeft, true, [false, false]));
|
||||
assert!(!debug_takes(Corner::BottomRight, true, [false, false]));
|
||||
assert!(debug_takes(Corner::BottomLeft, true, [true, false]));
|
||||
assert!(!debug_takes(Corner::BottomRight, true, [true, false]));
|
||||
assert!(debug_takes(Corner::BottomRight, true, [false, true]));
|
||||
}
|
||||
}
|
||||
@@ -200,6 +200,9 @@ impl Game<'_> {
|
||||
self.sync_agent_control();
|
||||
self.ui.options.agent_status = self.agent_status_lines();
|
||||
}
|
||||
Event::SliderDrag => {
|
||||
self.apply_settings();
|
||||
}
|
||||
Event::CopyAgentDetails => {
|
||||
use horizon_client::clipboard::Clipboard;
|
||||
let text = self.agent_details();
|
||||
@@ -246,6 +249,7 @@ impl Game<'_> {
|
||||
super::packs::open_folder(&dir);
|
||||
}
|
||||
Event::ModSettings(i) => self.open_mod_screen(i, true),
|
||||
Event::NativeSettings(i) => self.native_settings_refresh(i),
|
||||
Event::NativeButton(i, b) => self.native_settings_event(i, b),
|
||||
Event::Credits => self.open_win_screen(false, super::win::Finish::Options),
|
||||
}
|
||||
@@ -269,7 +273,12 @@ impl Game<'_> {
|
||||
r.set_present_mode(s.vsync, s.horizon.present_mode);
|
||||
r.animated_textures = s.horizon.animated_textures;
|
||||
r.set_mipmap_levels(s.mipmap_levels.max(0) as u32);
|
||||
r.set_world_post(s.horizon.resolution_scale as f32 / 100.0, s.horizon.fxaa);
|
||||
r.set_world_post(
|
||||
s.horizon.resolution_scale as f32 / 100.0,
|
||||
s.horizon.fxaa,
|
||||
s.horizon.taa,
|
||||
s.horizon.upscaling.ratio(),
|
||||
);
|
||||
r.set_hdr(
|
||||
s.horizon.hdr,
|
||||
s.horizon.hdr_paper_white as f32,
|
||||
|
||||
@@ -228,6 +228,11 @@ impl Game<'_> {
|
||||
});
|
||||
}
|
||||
}
|
||||
"minecraft:firework_rocket" => {
|
||||
if let Some(r) = entity_nbt::firework_rocket_from_nbt(&tag, player_uuid) {
|
||||
self.rockets.push(super::fireworks::Rocket::from_nbt(r));
|
||||
}
|
||||
}
|
||||
// PrimedTnt.readAdditionalSaveData: its fuse (80 when absent) and motion.
|
||||
"minecraft:tnt" => {
|
||||
if let Some(position) = entity_nbt::position(&tag) {
|
||||
|
||||
@@ -124,7 +124,8 @@ impl CameraType {
|
||||
}
|
||||
/// The player's model type (`PlayerModel` with the default skin).
|
||||
pub(super) fn player_type(root: &Path) -> Option<Arc<MobType>> {
|
||||
horizon_client::mobs::load_model(root, "minecraft:player#main").map(|model| {
|
||||
let models = horizon_client::mobs::EntityModelDocument::load(root).ok()?;
|
||||
models.model("minecraft:player#main").map(|model| {
|
||||
Arc::new(MobType {
|
||||
id: "minecraft:player".into(),
|
||||
// Players render as a humanoid; the species only drives local AI.
|
||||
@@ -158,10 +159,14 @@ pub(super) fn player_type(root: &Path) -> Option<Arc<MobType>> {
|
||||
ambient_interval: 80,
|
||||
flags: Default::default(),
|
||||
model: Arc::new(model),
|
||||
// PlayerModel's slim arms, for slim skins.
|
||||
layers: horizon_client::mobs::load_model(root, "minecraft:player_slim#main")
|
||||
.map(|slim| [("player_slim#main".to_owned(), Arc::new(slim))].into())
|
||||
.unwrap_or_default(),
|
||||
// PlayerModel's slim arms, for slim skins, and PlayerCapeModel.
|
||||
layers: ["player_slim#main", "player#cape"]
|
||||
.into_iter()
|
||||
.filter_map(|key| {
|
||||
let model = models.model(&format!("minecraft:{key}"))?;
|
||||
Some((key.to_owned(), Arc::new(model)))
|
||||
})
|
||||
.collect(),
|
||||
texture: "entity/player/wide/steve".into(),
|
||||
brain: Brain::Passive,
|
||||
anim: Anim::Humanoid { zombie_arms: false },
|
||||
@@ -322,7 +327,7 @@ impl Game<'_> {
|
||||
self.player_model = Some(Mob::new(0, kind, p.position, self.yaw));
|
||||
}
|
||||
let crouching = p.pose == Pose::Crouching;
|
||||
let (position, flying) = (p.position, p.flying || p.fall_flying);
|
||||
let position = p.position;
|
||||
let (fall_flying, fly_ticks, velocity) = (p.fall_flying, p.fall_fly_ticks, p.velocity);
|
||||
let spinning = p.auto_spin_attack_ticks > 0;
|
||||
let using = self.using.map(|(_, ticks)| ticks as i32 + 1).unwrap_or(0);
|
||||
@@ -357,6 +362,7 @@ impl Game<'_> {
|
||||
let off = self.offhand.as_ref().map(|s| s.item.clone());
|
||||
let riding = self.riding.is_some();
|
||||
let hurt = p.health.hurt_animation_time;
|
||||
let avatar = self.avatar;
|
||||
// LivingEntity.getBedOrientation: the model lies in the bed as
|
||||
// another player's does (`villager::sleep_pose`).
|
||||
let bed = self.sleeping.map_or(0, |head| self.bed_facing(head));
|
||||
@@ -374,6 +380,7 @@ impl Game<'_> {
|
||||
at.y - m.position.y,
|
||||
at.z - m.position.z,
|
||||
);
|
||||
let walked = player_walk_distance(m.position, at);
|
||||
m.previous = m.position;
|
||||
m.position = at;
|
||||
if dx * dx + dy * dy + dz * dz > 100.0 {
|
||||
@@ -408,9 +415,8 @@ impl Game<'_> {
|
||||
m.body_yaw += diff - diff.signum() * 50.0;
|
||||
}
|
||||
// WalkAnimationState.update(min(distance * 4, 1), 0.4).
|
||||
let dist = (dx * dx + dz * dz + if flying { dy * dy } else { 0.0 }).sqrt() as f32;
|
||||
m.previous_limb_speed = m.limb_speed;
|
||||
m.limb_speed += ((dist * 4.0).min(1.0) - m.limb_speed) * 0.4;
|
||||
m.limb_speed += ((walked * 4.0).min(1.0) - m.limb_speed) * 0.4;
|
||||
m.limb_position += m.limb_speed;
|
||||
m.age = m.age.wrapping_add(1);
|
||||
m.anim.attack_anim_o = attack.0;
|
||||
@@ -432,7 +438,15 @@ impl Game<'_> {
|
||||
m.extra.ints[5] = charge_duration;
|
||||
m.extra.elytra.tick(fall_flying, crouching, velocity);
|
||||
m.extra.swim.tick(visually_swimming, in_water);
|
||||
// The local player's ClientAvatarState, its cloak in the model's frame
|
||||
// (the model stands 0.125 lower while crouching).
|
||||
m.extra.avatar = avatar;
|
||||
if crouching {
|
||||
m.extra.avatar.cloak[1] -= 0.125;
|
||||
m.extra.avatar.cloak_o[1] -= 0.125;
|
||||
}
|
||||
m.extra.swing_right_arm = swing_right_arm;
|
||||
m.extra.swing_stab = self.swing.current.is_some_and(|c| c.animation.kind == 2);
|
||||
m.hurt_time = hurt;
|
||||
}
|
||||
/// `LevelExtractor`'s skip of the camera entity: the player's own body
|
||||
@@ -483,14 +497,9 @@ impl Game<'_> {
|
||||
&self.player_armor_layers(),
|
||||
out,
|
||||
);
|
||||
self.player_elytra_geometry(
|
||||
m,
|
||||
self.armor[1].as_ref().map(|s| &*s.item),
|
||||
camera,
|
||||
alpha as f32,
|
||||
packed,
|
||||
out,
|
||||
);
|
||||
let chest = self.armor[1].as_ref().map(|s| &*s.item);
|
||||
self.player_cape_geometry(m, chest, camera, alpha as f32, packed, out);
|
||||
self.player_elytra_geometry(m, chest, camera, alpha as f32, packed, out);
|
||||
self.spin_attack_geometry(m, camera, alpha as f32, packed, out);
|
||||
self.held_item_geometry(m, camera, alpha, packed, true, out);
|
||||
// LivingEntity.isCurrentlyGlowing: the Glowing effect. A server's client is
|
||||
@@ -555,14 +564,9 @@ impl Game<'_> {
|
||||
&self.player_armor_layers(),
|
||||
&mut verts,
|
||||
);
|
||||
self.player_elytra_geometry(
|
||||
&m,
|
||||
self.armor[1].as_ref().map(|s| &*s.item),
|
||||
camera,
|
||||
1.0,
|
||||
240 | 240 << 8,
|
||||
&mut verts,
|
||||
);
|
||||
let chest = self.armor[1].as_ref().map(|s| &*s.item);
|
||||
self.player_cape_geometry(&m, chest, camera, 1.0, 240 | 240 << 8, &mut verts);
|
||||
self.player_elytra_geometry(&m, chest, camera, 1.0, 240 | 240 << 8, &mut verts);
|
||||
self.held_item_geometry(&m, camera, 1.0, 240 | 240 << 8, false, &mut verts);
|
||||
let height = if m.extra.crouching { 1.5 } else { 1.8 };
|
||||
// PictureInPictureRenderer: the box centre, (size, size, -size);
|
||||
@@ -621,9 +625,12 @@ impl Game<'_> {
|
||||
let Some((texture, _)) = assets.equipment.get(asset).and_then(|k| k.get("wings")) else {
|
||||
return;
|
||||
};
|
||||
// WingsLayer.getPlayerElytraTexture: a player's cape texture has its elytra.
|
||||
let sprites = &self.gui.atlas.sprites;
|
||||
let rect = m.cape.as_deref().and_then(|c| sprites.get(c));
|
||||
let (Some(model), Some(rect)) = (
|
||||
assets.player.get("elytra"),
|
||||
self.gui.atlas.sprites.get(texture),
|
||||
rect.or_else(|| sprites.get(texture)),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
@@ -650,6 +657,48 @@ impl Game<'_> {
|
||||
out,
|
||||
);
|
||||
}
|
||||
/// `CapeLayer` for a player wearing `chest`: no cape under an elytra's
|
||||
/// wings, and moved out over a chestplate.
|
||||
pub(super) fn player_cape_geometry(
|
||||
&self,
|
||||
m: &Mob,
|
||||
chest: Option<&str>,
|
||||
camera: glam::DVec3,
|
||||
partial: f32,
|
||||
light: u32,
|
||||
out: &mut Vec<horizon_client::mesher::Vertex>,
|
||||
) {
|
||||
let Some(rect) = m
|
||||
.cape
|
||||
.as_deref()
|
||||
.and_then(|c| self.gui.atlas.sprites.get(c))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if horizon_client::mobs::trader::is_invisible(m) {
|
||||
return;
|
||||
}
|
||||
let layers = chest
|
||||
.and_then(|item| self.res.items().get(item))
|
||||
.and_then(|i| i.equip_asset.as_ref())
|
||||
.and_then(|asset| self.armor_stand_assets.equipment.get(asset));
|
||||
if layers.is_some_and(|k| k.contains_key("wings")) {
|
||||
return;
|
||||
}
|
||||
let mut base = horizon_client::mobs::render::base_transform(m, partial, camera);
|
||||
if layers.is_some_and(|k| k.contains_key("humanoid")) {
|
||||
base *= glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.053125, 0.06875));
|
||||
}
|
||||
horizon_client::mobs::render::cape(
|
||||
m,
|
||||
partial,
|
||||
base,
|
||||
[rect.u0, rect.v0, rect.u1, rect.v1],
|
||||
light,
|
||||
self.res.mob_data(),
|
||||
out,
|
||||
);
|
||||
}
|
||||
/// `SpinAttackEffectLayer`: Riptide's two boxes turning around a spinning
|
||||
/// player (`SpinAttackEffectModel.setupAnim`).
|
||||
pub(super) fn spin_attack_geometry(
|
||||
@@ -744,10 +793,30 @@ fn player_preview_quads(
|
||||
quads
|
||||
}
|
||||
|
||||
/// The distance `LivingEntity.calculateEntityAnimation` walks the player's
|
||||
/// model for a move from `from` to `to`. `omnidirectionalAirMover()` is false
|
||||
/// for every player (`Entity`'s, not overridden), so only the horizontal
|
||||
/// distance counts, flying and gliding included: rising or sinking straight
|
||||
/// up or down leaves the legs and arms still.
|
||||
fn player_walk_distance(from: Vec3, to: Vec3) -> f32 {
|
||||
let (dx, dz) = (to.x - from.x, to.z - from.z);
|
||||
(dx * dx + dz * dz).sqrt() as f32
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod preview_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn flying_straight_up_does_not_walk_the_player_model() {
|
||||
let from = Vec3::new(0.5, 80.0, 0.5);
|
||||
// Creative flight straight up (#3302) and straight down.
|
||||
assert_eq!(player_walk_distance(from, Vec3::new(0.5, 80.375, 0.5)), 0.0);
|
||||
assert_eq!(player_walk_distance(from, Vec3::new(0.5, 78.5, 0.5)), 0.0);
|
||||
// Moving sideways while rising walks only the horizontal part.
|
||||
let d = player_walk_distance(from, Vec3::new(0.8, 81.0, 0.9));
|
||||
assert!((d - 0.5).abs() < 1e-6, "{d}");
|
||||
}
|
||||
#[test]
|
||||
fn preview_keeps_crossing_faces_depth_and_clips_without_dropping_faces() {
|
||||
use horizon_client::{
|
||||
hud::{Blend, HudBatch},
|
||||
|
||||
@@ -11,6 +11,7 @@ use super::{Dim, Game, Mining, Screen};
|
||||
use horizon_client::first_person::{Hand, SwingAnimation};
|
||||
use horizon_client::{
|
||||
Result,
|
||||
blocks::Fluid,
|
||||
chunk::Chunk,
|
||||
containers::{BlockEntity, Furnace, FurnaceKind},
|
||||
entities::{Experience, ExperienceOrb, ItemEntity},
|
||||
@@ -217,8 +218,8 @@ pub(super) struct Remote {
|
||||
/// `LocalPlayer.showDeathScreen`: off with `immediate_respawn`.
|
||||
show_death_screen: bool,
|
||||
player_type: Option<Arc<MobType>>,
|
||||
/// Inventory (then the off hand) as last synchronised, for creative-mode
|
||||
/// slot updates.
|
||||
/// Inventory, off hand and armour as last synchronised, for creative-mode
|
||||
/// slot updates (`creative_sync_stacks`).
|
||||
synced: Vec<Option<ItemStack>>,
|
||||
decode_errors: u32,
|
||||
clock: Option<i32>,
|
||||
@@ -517,7 +518,7 @@ impl Game<'_> {
|
||||
death_message: None,
|
||||
show_death_screen: true,
|
||||
player_type,
|
||||
synced: vec![None; 37],
|
||||
synced: vec![None; CREATIVE_SYNCED],
|
||||
decode_errors: 0,
|
||||
clock: None,
|
||||
clock_rate: 1.0,
|
||||
@@ -548,13 +549,22 @@ impl Game<'_> {
|
||||
self.extras_left();
|
||||
}
|
||||
self.clear_waypoints();
|
||||
self.boss_overlay.reset();
|
||||
self.hud_disconnected();
|
||||
// Vanilla's Hud also ticks on the title and connect screens, so the
|
||||
// action bar has run out by the next world; Horizon's ticks in one.
|
||||
self.titles.overlay_time = 0;
|
||||
if let Some(mut r) = self.remote.take() {
|
||||
r.session.disconnect();
|
||||
}
|
||||
self.server_packs_disconnect();
|
||||
self.code_of_conduct = None;
|
||||
self.close_dialogs();
|
||||
// Gui.setScreen -> KeyMapping.releaseAll: the title or disconnect
|
||||
// screen releases every held key. Its release goes to that screen,
|
||||
// so a key kept here would still be down in the next world (#3246).
|
||||
self.keys.clear();
|
||||
self.left = false;
|
||||
self.right = false;
|
||||
// Single player's server thread saves the world before the title shows.
|
||||
let single_player = match self.integrated.take() {
|
||||
Some(server) => {
|
||||
@@ -567,8 +577,6 @@ impl Game<'_> {
|
||||
self.clock = Default::default();
|
||||
self.adv = Default::default();
|
||||
self.stats = Default::default();
|
||||
self.debug_charts.reset();
|
||||
self.tab_list.reset();
|
||||
self.score.board = Default::default();
|
||||
self.streaming = Streaming::new(Arc::new(NoTerrain), self.pack.context.clone(), 1);
|
||||
self.streaming.paused = true;
|
||||
@@ -612,6 +620,17 @@ impl Game<'_> {
|
||||
self.capture(false);
|
||||
Ok(())
|
||||
}
|
||||
/// `Hud.onDisconnected`, from `Minecraft.disconnect` and `clearClientLevel`
|
||||
/// (a proxy's reconfiguration too), but the chat: joining clears it and a
|
||||
/// reconfiguration keeps it (`ChatComponent.storeState`).
|
||||
fn hud_disconnected(&mut self) {
|
||||
self.tab_list.reset();
|
||||
self.boss_overlay.reset();
|
||||
self.adv.toasts.clear();
|
||||
self.debug_charts.reset();
|
||||
self.titles.clear();
|
||||
self.titles.reset_times();
|
||||
}
|
||||
|
||||
pub(super) fn send(&self, packet: S) {
|
||||
if let Some(r) = &self.remote {
|
||||
@@ -903,7 +922,15 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
Event::Reconfigured(registries) => {
|
||||
self.boss_overlay.reset();
|
||||
// handleConfigurationStart → clearClientLevel, and the next
|
||||
// ClientPacketListener starts with no players or scoreboard.
|
||||
self.hud_disconnected();
|
||||
self.score.board = Default::default();
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.players.clear();
|
||||
r.tab_players.clear();
|
||||
r.listed.clear();
|
||||
}
|
||||
self.set_registries(registries);
|
||||
}
|
||||
// handleTransfer: "Cannot transfer to server from
|
||||
@@ -1427,7 +1454,16 @@ impl Game<'_> {
|
||||
on_ground: bool,
|
||||
far_snaps: bool,
|
||||
) {
|
||||
let mob = self.mobs.iter_mut().find(|m| m.id == id as u32);
|
||||
// The dragon is drawn from its own state (game/dragon.rs), which
|
||||
// tick_remote_dragon eases to the server's moves through `lerps`. Its
|
||||
// copy in the mob list draws nothing: given the move, it kept the
|
||||
// dragon where it spawned (#2083).
|
||||
let dragon = self.dragon.as_ref().is_some_and(|d| d.id as i32 == id);
|
||||
let mob = self
|
||||
.mobs
|
||||
.iter_mut()
|
||||
.find(|m| m.id == id as u32)
|
||||
.filter(|_| !dragon);
|
||||
let tracked = self
|
||||
.remote
|
||||
.as_ref()
|
||||
@@ -1780,8 +1816,9 @@ impl Game<'_> {
|
||||
C::Login(p) => {
|
||||
self.level.hardcore = p.hardcore;
|
||||
// handleLogin makes a new MultiPlayerGameMode (carried index 0) and a
|
||||
// new LocalPlayer (slot 0).
|
||||
// new LocalPlayer (slot 0, no effects).
|
||||
self.selected = 0;
|
||||
self.potions.effects.clear();
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.carried = Some(0);
|
||||
r.online_mode = p.online_mode;
|
||||
@@ -1806,6 +1843,12 @@ impl Game<'_> {
|
||||
// again) and with no item in use.
|
||||
self.potions.effects.clear();
|
||||
self.using = None;
|
||||
// After a death (no KEEP_ENTITY_DATA) the new LocalPlayer
|
||||
// rides nothing: the server pairs a vehicle again with its
|
||||
// passengers. A dimension change keeps the vehicle it travels in.
|
||||
if p.keep & 2 == 0 {
|
||||
self.riding = None;
|
||||
}
|
||||
let dimension_changed = self.dim != Dim::from_id(&p.spawn.dimension);
|
||||
self.enter_remote_dimension(&p.spawn, true);
|
||||
if dimension_changed {
|
||||
@@ -2537,7 +2580,7 @@ impl Game<'_> {
|
||||
if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) {
|
||||
self.swing_hand(hand, animation);
|
||||
} else if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) {
|
||||
m.swing_hand_modified(hand == Hand::Off, animation.duration);
|
||||
m.swing_hand_modified(hand == Hand::Off, animation);
|
||||
}
|
||||
}
|
||||
// The player's own instances: its maximum health (the hearts the
|
||||
@@ -2741,12 +2784,14 @@ impl Game<'_> {
|
||||
self.hotbar_pop[pop] = 5;
|
||||
}
|
||||
}
|
||||
let before = self.creative_stacks();
|
||||
self.set_menu_slot(p.container, i32::from(p.slot), stack);
|
||||
self.remote_synced();
|
||||
self.remote_synced_since(&before);
|
||||
}
|
||||
C::SetCursorItem(p) => self.carried = self.to_stack(&p.item),
|
||||
C::SetPlayerInventory(p) => {
|
||||
let stack = self.to_stack(&p.item);
|
||||
let before = self.creative_stacks();
|
||||
match p.slot {
|
||||
0..=35 => self.inventory[p.slot as usize] = stack,
|
||||
36..=39 => self.armor[3 - (p.slot - 36) as usize] = stack,
|
||||
@@ -2754,7 +2799,7 @@ impl Game<'_> {
|
||||
40 => self.offhand = stack,
|
||||
_ => {}
|
||||
}
|
||||
self.remote_synced();
|
||||
self.remote_synced_since(&before);
|
||||
}
|
||||
C::ContainerSetData(p) if self.open_menu_name(p.container) == "minecraft:lectern" => {
|
||||
self.remote_lectern_page(i32::from(p.value));
|
||||
@@ -3230,6 +3275,8 @@ impl Game<'_> {
|
||||
let mut resolved: Vec<(u128, String)> = Vec::new();
|
||||
// PlayerSkin.model of each resolved skin: the textures' `slim`.
|
||||
let mut slim = std::collections::HashSet::new();
|
||||
// PlayerSkin.cape of each resolved skin.
|
||||
let mut capes: HashMap<u128, String> = HashMap::new();
|
||||
for (uuid, textures) in entries {
|
||||
// PlayerInfo.createSkinLookup: only the local player's own skin
|
||||
// may be unsigned.
|
||||
@@ -3243,10 +3290,24 @@ impl Game<'_> {
|
||||
if textures.slim {
|
||||
slim.insert(uuid);
|
||||
}
|
||||
if let Some(cape) = horizon_client::skins::cape(&textures) {
|
||||
capes.insert(uuid, cape);
|
||||
}
|
||||
resolved.push((uuid, skin));
|
||||
}
|
||||
}
|
||||
resolved.retain(|(_, skin)| !skin.starts_with("skins/") || self.again_skin(skin));
|
||||
// An offline name's cape from the launcher, where the profile has none.
|
||||
if !capes.contains_key(&local)
|
||||
&& let Some(rgba) = horizon_client::skins::offline_cape()
|
||||
{
|
||||
const OFFLINE: &str = "capes/offline";
|
||||
if !self.show_skin(OFFLINE) {
|
||||
self.store_skin(OFFLINE.into(), rgba.to_vec());
|
||||
}
|
||||
capes.insert(local, OFFLINE.into());
|
||||
}
|
||||
capes.retain(|_, cape| self.again_skin(cape));
|
||||
// PlayerInfo.getSkin: the downloaded skin and its model, else the
|
||||
// profile's default skin (DefaultPlayerSkin.get), slim or wide.
|
||||
let skin_of = |skins: &HashMap<u128, String>, uuid: u128| match skins.get(&uuid) {
|
||||
@@ -3278,12 +3339,18 @@ impl Game<'_> {
|
||||
{
|
||||
mob.skin = Some(skin);
|
||||
mob.slim = is_slim;
|
||||
mob.cape = capes.get(&uuid).cloned();
|
||||
}
|
||||
}
|
||||
if let Some(mob) = self.player_model.as_mut() {
|
||||
let (skin, is_slim) = skin_of(&skins, own);
|
||||
mob.skin = Some(skin);
|
||||
mob.slim = is_slim;
|
||||
// Avatar.isModelPartShown(CAPE): the Skin Customization option.
|
||||
mob.cape = capes
|
||||
.get(&own)
|
||||
.filter(|_| self.settings.file.bool("modelPart_cape"))
|
||||
.cloned();
|
||||
}
|
||||
// ClientMannequin.updateSkin (PlayerSkinRenderCache.lookup): a
|
||||
// mannequin's DATA_PROFILE `textures` property resolves like a
|
||||
@@ -3367,7 +3434,7 @@ impl Game<'_> {
|
||||
self.gui.atlas.sprites.remove(&old);
|
||||
slot
|
||||
};
|
||||
let Some(rect) = self
|
||||
let Some(mut rect) = self
|
||||
.gui
|
||||
.atlas
|
||||
.sprites
|
||||
@@ -3384,6 +3451,10 @@ impl Game<'_> {
|
||||
height: 64,
|
||||
rgba,
|
||||
});
|
||||
// A cape is a 64x32 texture in the top half of the slot (skins::process_cape).
|
||||
if location.starts_with("capes/") {
|
||||
rect.v1 = (rect.v0 + rect.v1) / 2.0;
|
||||
}
|
||||
self.gui.atlas.sprites.insert(location.clone(), rect);
|
||||
self.skin_slots.push((location, slot));
|
||||
}
|
||||
@@ -3720,6 +3791,7 @@ impl Game<'_> {
|
||||
// and the moving pistons a block event's client-side moveBlocks made
|
||||
// (their progress advances between the server's block updates).
|
||||
self.tick_block_entity_anims();
|
||||
self.client_tick_beacons();
|
||||
self.with_level(|b, level, ticks| {
|
||||
b.client_tick_block_entities(level, ticks);
|
||||
});
|
||||
@@ -3841,6 +3913,17 @@ impl Game<'_> {
|
||||
// player too (controlled_simulation_tick does it otherwise): left
|
||||
// at 10, the hurt tilt restarted every frame and shook the camera.
|
||||
player.health.advance_clock();
|
||||
if riding && !dead {
|
||||
MotionWorld {
|
||||
entities: &entity_collisions,
|
||||
player: &mut *player,
|
||||
scene: &mut self.world,
|
||||
assets: &self.pack.assets,
|
||||
collision_binding: self.collision,
|
||||
resources: self.motion,
|
||||
}
|
||||
.passenger_pose_tick()?;
|
||||
}
|
||||
}
|
||||
// LocalPlayer.onUpdateAbilities: flight turned on or off (a double
|
||||
// jump, a spectator, landing) is sent to the server.
|
||||
@@ -4455,41 +4538,44 @@ impl Game<'_> {
|
||||
{
|
||||
out.push(packet);
|
||||
}
|
||||
// Creative inventory edits are sent slot by slot (SetCreativeModeSlot);
|
||||
// `synced[36]` is the off hand.
|
||||
// Creative inventory edits are sent slot by slot (SetCreativeModeSlot).
|
||||
let mut creative_slots = Vec::new();
|
||||
if self.creative {
|
||||
for i in 0..37 {
|
||||
let stack = self.inventory.get(i).unwrap_or(&self.offhand);
|
||||
if *stack != r.synced[i] {
|
||||
let stacks = creative_sync_stacks(&self.inventory, &self.offhand, &self.armor);
|
||||
for (i, stack) in stacks.into_iter().enumerate() {
|
||||
if stack != r.synced[i] {
|
||||
r.synced[i] = stack.clone();
|
||||
creative_slots.push(i);
|
||||
creative_slots.push((creative_sync_slot(i), stack));
|
||||
}
|
||||
}
|
||||
}
|
||||
for packet in out {
|
||||
self.send(packet);
|
||||
}
|
||||
for i in creative_slots {
|
||||
// InventoryMenu's slots: the hotbar is 36..=44, the off hand 45.
|
||||
let slot = match i {
|
||||
0..9 => 36 + i,
|
||||
36 => 45,
|
||||
_ => i,
|
||||
} as i16;
|
||||
let item = self.to_network(self.inventory.get(i).unwrap_or(&self.offhand));
|
||||
for (slot, stack) in creative_slots {
|
||||
let item = self.to_network(&stack);
|
||||
self.send(S::SetCreativeModeSlot(play::SetCreativeModeSlot {
|
||||
slot,
|
||||
item,
|
||||
}));
|
||||
}
|
||||
}
|
||||
fn creative_stacks(&self) -> Vec<Option<ItemStack>> {
|
||||
creative_sync_stacks(&self.inventory, &self.offhand, &self.armor)
|
||||
}
|
||||
/// Inventory as the server last described it.
|
||||
fn remote_synced(&mut self) {
|
||||
let mut inventory = self.inventory.clone();
|
||||
inventory.push(self.offhand.clone());
|
||||
let stacks = self.creative_stacks();
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.synced = inventory;
|
||||
r.synced = stacks;
|
||||
}
|
||||
}
|
||||
/// The slots a server packet changed since `before` are as the server has them; the
|
||||
/// others keep what was last sent, so a creative click made since still goes out.
|
||||
fn remote_synced_since(&mut self, before: &[Option<ItemStack>]) {
|
||||
let now = self.creative_stacks();
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
mark_synced(&mut r.synced, before, now);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4762,10 +4848,17 @@ impl Game<'_> {
|
||||
.and_then(|h| self.res.items().get(&h.item))
|
||||
.is_some_and(|i| i.block.is_some());
|
||||
if let Some(hit) = self.pick() {
|
||||
let (reacts, changes) = if hand == Hand::Main {
|
||||
let spectator = self.spectator();
|
||||
let (reacts, changes) = if hand == Hand::Main && !spectator {
|
||||
self.remote_block_reacts(&hit, held.as_ref())
|
||||
} else {
|
||||
(false, DryUse::default())
|
||||
// useItemOn runs for the off hand too (useWithoutItem doesn't):
|
||||
// RespawnAnchorBlock.useItemOn charges an anchor with its glowstone.
|
||||
let sneaking = self.keys.contains(&KeyCode::ShiftLeft);
|
||||
let hands_full = self.stack_in(self.selected).is_some() || self.offhand.is_some();
|
||||
let charges =
|
||||
!(sneaking && hands_full) && self.anchor_takes(hit.pos, held.as_ref());
|
||||
(charges, DryUse::default())
|
||||
};
|
||||
let seq = self.next_sequence();
|
||||
let cursor = [
|
||||
@@ -4782,6 +4875,12 @@ impl Game<'_> {
|
||||
world_border: false,
|
||||
sequence: seq,
|
||||
}));
|
||||
// MultiPlayerGameMode.performUseItemOn: a spectator's use predicts
|
||||
// nothing and ends the click (CONSUME, no swing); the server opens
|
||||
// the block's menu.
|
||||
if spectator {
|
||||
return true;
|
||||
}
|
||||
// Only a predicted placement (predict_place) marks a cell whose
|
||||
// resend plays a place sound: an empty hand or a non-block item
|
||||
// places nothing (BlockItem.place is where the sound comes from).
|
||||
@@ -4930,6 +5029,12 @@ impl Game<'_> {
|
||||
if self.jukebox_takes(hit.pos, held) {
|
||||
return (true, DryUse::default());
|
||||
}
|
||||
// RespawnAnchorBlock.useItemOn: PASS when the off hand's glowstone is to
|
||||
// charge the anchor, so useWithoutItem doesn't run and the off hand's turn
|
||||
// comes (glowstone in this hand charges it in `use_item_on`).
|
||||
if !self.anchor_takes(hit.pos, held) && self.anchor_takes(hit.pos, self.offhand.as_ref()) {
|
||||
return (false, DryUse::default());
|
||||
}
|
||||
// BeehiveBlock.useItemOn: shears or a glass bottle on a full hive
|
||||
// (honey level 5) is SUCCESS, so the click ends after UseItemOn and
|
||||
// no UseItem follows (the server does the harvest, see `use_beehive`).
|
||||
@@ -5034,7 +5139,7 @@ impl Game<'_> {
|
||||
}
|
||||
|
||||
/// MultiPlayerGameMode.useItem for `hand`, if it holds something: whether
|
||||
/// the click ends there, as far as this client can tell (`item_has_use`).
|
||||
/// the click ends there, as far as this client can tell (`use_ends_click`).
|
||||
fn remote_use_item(&mut self, hand: Hand) -> bool {
|
||||
let Some(held) = self.with_hand(hand, |g| g.held().cloned()) else {
|
||||
return false;
|
||||
@@ -5063,6 +5168,12 @@ impl Game<'_> {
|
||||
if info.food.is_some() && !eating {
|
||||
return false;
|
||||
}
|
||||
// A bucket, a glass bottle or a boat with nothing to fill, empty or
|
||||
// place PASSes or FAILs: startUseItem goes on to the off hand (a
|
||||
// Riptide trident there charges).
|
||||
if self.with_hand(hand, |g| g.use_finds_no_target(&held)) {
|
||||
return false;
|
||||
}
|
||||
// It runs the use here too: ItemStack.use starts the `use_cooldown`
|
||||
// of an item with no use time, and the server's
|
||||
// ClientboundCooldownPacket confirms it; one held in use starts it at
|
||||
@@ -5074,9 +5185,65 @@ impl Game<'_> {
|
||||
return true;
|
||||
}
|
||||
self.with_hand(hand, |g| g.remote_start_held_use(&held));
|
||||
item_has_use(&info)
|
||||
let gliding = self.player.as_ref().is_some_and(|p| p.fall_flying);
|
||||
use_ends_click(&info, gliding)
|
||||
}
|
||||
|
||||
/// Whether `held`'s `Item.use` needs a target this client sees none of
|
||||
/// (not SUCCESS): BucketItem.use (a fluid source or powder snow to pick
|
||||
/// up through `ClipContext.Fluid.SOURCE_ONLY`, a block to empty a full
|
||||
/// one against, `mayUseItemAt`), BottleItem.use (water to fill from) and
|
||||
/// BoatItem.use (a block or fluid surface with room for the boat).
|
||||
fn use_finds_no_target(&self, held: &ItemStack) -> bool {
|
||||
let id = &*held.item;
|
||||
let facts = |pos: [i32; 3]| {
|
||||
self.res
|
||||
.facts()
|
||||
.get(self.world.block(pos[0], pos[1], pos[2]))
|
||||
};
|
||||
let source = |want: Option<Fluid>| {
|
||||
let fluid_hit = self.pick_fluid();
|
||||
// pick_fluid steps through waterlogged blocks, but their water is
|
||||
// a source the SOURCE_ONLY ray stops at (and a BucketPickup).
|
||||
if let Some(hit) = self.pick()
|
||||
&& facts(hit.pos).waterlogged
|
||||
{
|
||||
let eye = self.aim().map_or(hit.point, |(eye, _)| eye);
|
||||
let d = |p: [f64; 3]| (0..3).map(|a| (p[a] - eye[a]).powi(2)).sum::<f64>();
|
||||
if fluid_hit
|
||||
.as_ref()
|
||||
.is_none_or(|fluid| d(fluid.point) >= d(hit.point))
|
||||
{
|
||||
return want.is_none_or(|want| want == Fluid::Water);
|
||||
}
|
||||
}
|
||||
fluid_hit.is_some_and(|hit| {
|
||||
let f = facts(hit.pos);
|
||||
let fluid = f.fluid != Fluid::None && f.fluid_level == 8 && !f.fluid_falling;
|
||||
match want {
|
||||
Some(want) => fluid && f.fluid == want,
|
||||
None => fluid || self.is_powder_snow(hit.pos),
|
||||
}
|
||||
})
|
||||
};
|
||||
// SolidBucketItem only has useOn: its use is Item.use's PASS.
|
||||
if id == "minecraft:powder_snow_bucket" {
|
||||
return true;
|
||||
}
|
||||
if id == "minecraft:bucket" {
|
||||
return !self.may_build() || !source(None);
|
||||
}
|
||||
if horizon_client::items::bucket_contents(id).is_some() {
|
||||
return !self.may_build() || self.pick().is_none();
|
||||
}
|
||||
if id == "minecraft:glass_bottle" {
|
||||
return !source(Some(Fluid::Water));
|
||||
}
|
||||
if super::boats::any_boat_wood(id).is_some() {
|
||||
return self.boat_to_place(held).is_none();
|
||||
}
|
||||
false
|
||||
}
|
||||
/// `Item.use` runs on the client too (MultiPlayerGameMode.useItem): an
|
||||
/// item held in use until the button lets go starts being used here, so
|
||||
/// that letting go sends RELEASE_USE_ITEM (Minecraft.handleKeybinds) and
|
||||
@@ -5106,6 +5273,9 @@ impl Game<'_> {
|
||||
}
|
||||
// SpyglassItem.use (its sound is the server's).
|
||||
"minecraft:spyglass" => true,
|
||||
// EnderEyeItem.use: startUsingItem unless an End portal frame is
|
||||
// aimed at, with or without a stronghold to throw the eye at.
|
||||
"minecraft:ender_eye" => !self.aims_at_end_portal_frame(),
|
||||
// Item.use: a kinetic weapon starts being used.
|
||||
id if horizon_client::spear::Kinetic::of(id).is_some() => true,
|
||||
// ShieldItem.use: anything that blocks attacks, off cooldown.
|
||||
@@ -5119,11 +5289,17 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// Whether `stack` stays in use until the button lets go (bows,
|
||||
/// crossbows, tridents, spyglasses, shields): its use only counts ticks here.
|
||||
/// crossbows, tridents, spyglasses, shields, eyes of ender, whose
|
||||
/// `getUseDuration` 0 never counts down to the end): its use only counts
|
||||
/// ticks here.
|
||||
fn held_until_released(&self, stack: &ItemStack) -> bool {
|
||||
matches!(
|
||||
&*stack.item,
|
||||
"minecraft:bow" | "minecraft:crossbow" | "minecraft:trident" | "minecraft:spyglass"
|
||||
"minecraft:bow"
|
||||
| "minecraft:crossbow"
|
||||
| "minecraft:trident"
|
||||
| "minecraft:spyglass"
|
||||
| "minecraft:ender_eye"
|
||||
) || horizon_client::spear::Kinetic::of(&stack.item).is_some()
|
||||
|| self.blocks_attacks(stack).is_some()
|
||||
}
|
||||
@@ -5607,6 +5783,14 @@ impl Game<'_> {
|
||||
} else {
|
||||
Input::Pickup
|
||||
};
|
||||
if self.screen == Screen::Creative {
|
||||
// CreativeModeInventoryScreen.slotClicked: the Survival Inventory tab clicks the
|
||||
// player's own InventoryMenu, and its CreativeInventoryListener sends each slot that
|
||||
// changed (SetCreativeModeSlot). No ContainerClick: a server holding the carried
|
||||
// stack would give it back after the Destroy Item slot cleared it (#3307).
|
||||
self.menu_click(Some(internal), i32::from(right), input);
|
||||
return;
|
||||
}
|
||||
self.remote_menu_ops(&[(Some(internal), i32::from(right), input)]);
|
||||
}
|
||||
/// The server's open menu: its window id and menu type (0, "inventory"
|
||||
@@ -5763,6 +5947,12 @@ impl Game<'_> {
|
||||
} else {
|
||||
self.carried.take().expect("carried")
|
||||
};
|
||||
self.remote_creative_throw(thrown);
|
||||
}
|
||||
/// `MultiPlayerGameMode.handleCreativeModeItemDrop`: a stack thrown out of the creative
|
||||
/// screen goes to the server as a SetCreativeModeSlot to slot -1, which drops it from the
|
||||
/// player's hand; the client only swings (`Player.drop` on a client).
|
||||
pub(super) fn remote_creative_throw(&mut self, thrown: ItemStack) {
|
||||
if !self.creative {
|
||||
return;
|
||||
}
|
||||
@@ -6263,6 +6453,50 @@ type Predicted = (
|
||||
Option<ItemStack>,
|
||||
);
|
||||
|
||||
/// How many stacks the creative screen keeps in step with the server (`Remote::synced`).
|
||||
const CREATIVE_SYNCED: usize = 41;
|
||||
|
||||
/// The player's stacks in `Remote::synced` order: the 36 inventory slots, the off hand, then
|
||||
/// the armour from the head down. `CreativeInventoryListener.slotChanged` sends every
|
||||
/// InventoryMenu slot the creative screen changes, the armour slots too.
|
||||
fn creative_sync_stacks(
|
||||
inventory: &[Option<ItemStack>],
|
||||
offhand: &Option<ItemStack>,
|
||||
armor: &[Option<ItemStack>; 4],
|
||||
) -> Vec<Option<ItemStack>> {
|
||||
let mut stacks: Vec<Option<ItemStack>> = inventory.iter().take(36).cloned().collect();
|
||||
stacks.resize(36, None);
|
||||
stacks.push(offhand.clone());
|
||||
stacks.extend(armor.iter().cloned());
|
||||
stacks
|
||||
}
|
||||
|
||||
/// Entries of `creative_sync_stacks` that went from `before` to `now` are synced as `now`.
|
||||
fn mark_synced(
|
||||
synced: &mut [Option<ItemStack>],
|
||||
before: &[Option<ItemStack>],
|
||||
now: Vec<Option<ItemStack>>,
|
||||
) {
|
||||
for (i, stack) in now.into_iter().enumerate() {
|
||||
if before.get(i) != Some(&stack)
|
||||
&& let Some(s) = synced.get_mut(i)
|
||||
{
|
||||
*s = stack;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// InventoryMenu's slot for entry `i` of `creative_sync_stacks`: the hotbar is 36..=44, the
|
||||
/// main inventory 9..=35, the off hand 45 and the armour 5..=8 (head first).
|
||||
fn creative_sync_slot(i: usize) -> i16 {
|
||||
(match i {
|
||||
0..9 => 36 + i,
|
||||
36 => 45,
|
||||
37.. => 5 + (i - 37),
|
||||
_ => i,
|
||||
}) as i16
|
||||
}
|
||||
|
||||
fn menu_items(m: &horizon_client::menu::Menu) -> Vec<Option<ItemStack>> {
|
||||
(0..m.slot_count()).map(|i| m.slot(i).cloned()).collect()
|
||||
}
|
||||
@@ -6400,6 +6634,13 @@ fn hand_id(hand: Hand) -> i32 {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `Item.use` of `info` ends `Minecraft.startUseItem`'s click, so the
|
||||
/// off hand gets no turn. `FireworkRocketItem.use` answers SUCCESS while the
|
||||
/// player glides (the rocket boosts them) and PASS otherwise.
|
||||
fn use_ends_click(info: &horizon_client::items::ItemInfo, fall_flying: bool) -> bool {
|
||||
item_has_use(info) || (fall_flying && &*info.id == "minecraft:firework_rocket")
|
||||
}
|
||||
|
||||
/// Whether `Item.use` usually acts on this item (eats, drinks, equips, raises,
|
||||
/// throws, shoots, fills or places), which ends `Minecraft.startUseItem` at
|
||||
/// its hand. Tools and materials pass, and the off hand gets its turn. The
|
||||
@@ -6655,6 +6896,58 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_creative_sync_covers_inventory_menu_slots_5_to_45_once_each() {
|
||||
// CreativeInventoryListener sends every InventoryMenu slot but the crafting ones: the
|
||||
// armour (5..=8), the inventory (9..=44) and the off hand (45).
|
||||
let stack = |item: &str| Some(horizon_client::items::ItemStack::new(item, 1));
|
||||
let inventory: Vec<_> = (0..36)
|
||||
.map(|i| stack(&format!("minecraft:item_{i}")))
|
||||
.collect();
|
||||
let offhand = stack("minecraft:shield");
|
||||
let armor = [
|
||||
stack("minecraft:diamond_helmet"),
|
||||
stack("minecraft:diamond_chestplate"),
|
||||
stack("minecraft:diamond_leggings"),
|
||||
stack("minecraft:diamond_boots"),
|
||||
];
|
||||
let stacks = super::creative_sync_stacks(&inventory, &offhand, &armor);
|
||||
assert_eq!(stacks.len(), super::CREATIVE_SYNCED);
|
||||
let mut slots: Vec<i16> = (0..stacks.len()).map(super::creative_sync_slot).collect();
|
||||
// Each entry goes to the menu slot that holds that stack.
|
||||
for (i, &slot) in slots.iter().enumerate() {
|
||||
let game_slot = Game::menu_slot("inventory", i32::from(slot)).unwrap();
|
||||
let expected = match game_slot {
|
||||
0..36 => &inventory[game_slot],
|
||||
504 => &offhand,
|
||||
500..504 => &armor[game_slot - 500],
|
||||
_ => panic!("entry {i} went to game slot {game_slot}"),
|
||||
};
|
||||
assert_eq!(&stacks[i], expected, "entry {i}, menu slot {slot}");
|
||||
}
|
||||
slots.sort();
|
||||
assert_eq!(slots, (5..=45).collect::<Vec<i16>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_server_slot_update_leaves_an_unsent_creative_click_to_be_sent() {
|
||||
let stack = |item: &str| Some(horizon_client::items::ItemStack::new(item, 1));
|
||||
let none = || vec![None; super::CREATIVE_SYNCED];
|
||||
// Synced: nothing. A click puts a helmet on (entry 37, not sent yet), then the server
|
||||
// sets hotbar slot 0 (a pickup): only that entry counts as synced.
|
||||
let mut synced = none();
|
||||
let mut before = none();
|
||||
before[37] = stack("minecraft:diamond_helmet");
|
||||
let mut now = before.clone();
|
||||
now[0] = stack("minecraft:stick");
|
||||
super::mark_synced(&mut synced, &before, now.clone());
|
||||
assert_eq!(synced[0], now[0]);
|
||||
assert_eq!(
|
||||
synced[37], None,
|
||||
"the helmet still differs, so the next tick sends it"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_inventory_menu_slot_is_a_game_slot_and_45_is_the_off_hand() {
|
||||
// InventoryMenu: result, 2x2 grid, armour, 27 + 9 inventory slots, then the off hand.
|
||||
@@ -6690,4 +6983,31 @@ mod tests {
|
||||
assert_eq!(Game::menu_slot_index("minecraft:generic_9x6", 504), None);
|
||||
assert_eq!(Game::menu_slot_index("unknown", 0), None);
|
||||
}
|
||||
|
||||
/// `FireworkRocketItem.use` is SUCCESS while gliding: the main hand's
|
||||
/// rocket ends the click and the off hand's shield is not raised (#3424).
|
||||
/// On foot it passes, so the off hand still gets its turn.
|
||||
#[test]
|
||||
fn a_rocket_used_while_gliding_ends_the_click() {
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../.local/horizon-client")
|
||||
.join(horizon_core::VANILLA_VERSION);
|
||||
if !root.join("items.json").exists() {
|
||||
eprintln!("skipping: no prepared resources in {}", root.display());
|
||||
return;
|
||||
}
|
||||
let registry = horizon_world::level::data::load_registry(&root).unwrap();
|
||||
let facts = horizon_client::blocks::BlockFacts::load(&root, ®istry).unwrap();
|
||||
let items = horizon_client::items::Items::load(&root, ®istry, &facts).unwrap();
|
||||
let rocket = items.get("minecraft:firework_rocket").unwrap();
|
||||
assert!(super::use_ends_click(rocket, true), "gliding");
|
||||
assert!(!super::use_ends_click(rocket, false), "on foot");
|
||||
// Other items answer the same whether or not the player glides.
|
||||
let shield = items.get("minecraft:shield").unwrap();
|
||||
let stick = items.get("minecraft:stick").unwrap();
|
||||
for gliding in [false, true] {
|
||||
assert!(super::use_ends_click(shield, gliding));
|
||||
assert!(!super::use_ends_click(stick, gliding));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -246,6 +246,11 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti
|
||||
(Species::Zombie | Species::Husk, 18, Value::Bool(converting)) => {
|
||||
m.extra.counter2 = i32::from(*converting);
|
||||
}
|
||||
// Skeleton.DATA_STRAY_CONVERSION_ID (the first entry after Mob's):
|
||||
// the freezing conversion's shaking.
|
||||
(Species::Skeleton, 16, Value::Bool(converting)) => {
|
||||
m.extra.counter2 = i32::from(*converting);
|
||||
}
|
||||
// ZombieVillager.DATA_CONVERTING_ID (before its villager data).
|
||||
(Species::ZombieVillager, 19, Value::Bool(converting)) => {
|
||||
zombie_villager::set_converting(m, *converting);
|
||||
|
||||
@@ -68,7 +68,7 @@ impl Game<'_> {
|
||||
yaw.cos() * pitch.cos(),
|
||||
]
|
||||
}
|
||||
/// `FogRenderer.setupFog` for the frame's camera.
|
||||
/// `FogRenderer.setupFog` for the frame's camera, and Horizon's Fog option.
|
||||
pub(super) fn frame_fog(
|
||||
&self,
|
||||
camera: glam::DVec3,
|
||||
@@ -90,39 +90,40 @@ impl Game<'_> {
|
||||
} else {
|
||||
self.res.fog()
|
||||
};
|
||||
horizon_client::fog::setup_fog(
|
||||
tables,
|
||||
&self.fog,
|
||||
&FogInputs {
|
||||
fog_type,
|
||||
sky,
|
||||
water_fog_color,
|
||||
biome,
|
||||
render_distance_chunks: self.terrain_distance(),
|
||||
distant_terrain: self.lod.is_some(),
|
||||
cloud_range_chunks: self.settings.cloud_range,
|
||||
camera_y: camera.y,
|
||||
min_y: self.level_min_y(),
|
||||
flat: self.level_flat(),
|
||||
forward: forward.map(|c| c as f32),
|
||||
rain,
|
||||
thunder,
|
||||
skybox: self.dim == Dim::Overworld,
|
||||
blindness: self
|
||||
.potions
|
||||
.effects
|
||||
.get("blindness")
|
||||
.map(|effect| (effect.duration, effect.duration == -1)),
|
||||
darkness: self.darkness_fog(),
|
||||
darken_world: self
|
||||
.boss_overlay
|
||||
.darken_amount(self.clock.fraction() as f32),
|
||||
boss_world_fog: self.boss_overlay.should_create_world_fog(),
|
||||
spectator: self.spectator(),
|
||||
fire_resistance: self.potions.effects.get("fire_resistance").is_some(),
|
||||
night_vision: self.fog_night_vision(),
|
||||
},
|
||||
)
|
||||
let input = FogInputs {
|
||||
fog_type,
|
||||
sky,
|
||||
water_fog_color,
|
||||
biome,
|
||||
render_distance_chunks: self.terrain_distance(),
|
||||
distant_terrain: self.lod.is_some(),
|
||||
cloud_range_chunks: self.settings.cloud_range,
|
||||
camera_y: camera.y,
|
||||
min_y: self.level_min_y(),
|
||||
flat: self.level_flat(),
|
||||
forward: forward.map(|c| c as f32),
|
||||
rain,
|
||||
thunder,
|
||||
skybox: self.dim == Dim::Overworld,
|
||||
blindness: self
|
||||
.potions
|
||||
.effects
|
||||
.get("blindness")
|
||||
.map(|effect| (effect.duration, effect.duration == -1)),
|
||||
darkness: self.darkness_fog(),
|
||||
darken_world: self
|
||||
.boss_overlay
|
||||
.darken_amount(self.clock.fraction() as f32),
|
||||
boss_world_fog: self.boss_overlay.should_create_world_fog(),
|
||||
spectator: self.spectator(),
|
||||
fire_resistance: self.potions.effects.get("fire_resistance").is_some(),
|
||||
night_vision: self.fog_night_vision(),
|
||||
};
|
||||
let mut fog = horizon_client::fog::setup_fog(tables, &self.fog, &input);
|
||||
if !self.settings.horizon.fog {
|
||||
horizon_client::fog::clear_distance_fog(&mut fog, &input);
|
||||
}
|
||||
fog
|
||||
}
|
||||
/// `FogRenderer.computeFogColor`'s night vision brightenFactor:
|
||||
/// `GameRenderer.nightVisionScale`, but not while Darkness is on.
|
||||
|
||||
@@ -132,6 +132,15 @@ impl Game<'_> {
|
||||
.play("minecraft:block.respawn_anchor.charge", Some(at), 1.0, 1.0);
|
||||
Ok(())
|
||||
}
|
||||
/// `RespawnAnchorBlock.useItemOn`'s test: `held` is glowstone
|
||||
/// (`isRespawnFuel`) and the block at `pos` is an anchor that takes another
|
||||
/// charge (`canBeCharged`).
|
||||
pub(super) fn anchor_takes(&self, pos: [i32; 3], held: Option<&ItemStack>) -> bool {
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
held.is_some_and(|s| &*s.item == "minecraft:glowstone")
|
||||
&& self.is_anchor(state)
|
||||
&& self.anchor_charges(state) < 4
|
||||
}
|
||||
/// `RespawnAnchorBlock.useItemOn` with `held` in the hand that acts.
|
||||
pub(super) fn use_respawn_anchor(
|
||||
&mut self,
|
||||
|
||||
@@ -50,7 +50,7 @@ impl Game<'_> {
|
||||
json!({
|
||||
"folder": w.folder,
|
||||
"name": w.name,
|
||||
"mode": if w.creative { "creative" } else { "survival" },
|
||||
"mode": if w.game_mode == 1 { "creative" } else { "survival" },
|
||||
"last_played": w.modified.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64),
|
||||
"commands": w.commands,
|
||||
"version": w.version,
|
||||
|
||||
@@ -85,27 +85,31 @@ impl Game<'_> {
|
||||
}
|
||||
self.score.storage.save(&self.world_root);
|
||||
self.score.stopwatches.save(&self.world_root);
|
||||
if self.border != horizon_client::worldborder::WorldBorder::default() {
|
||||
let _ = save::write_dat(
|
||||
if self.border != horizon_client::worldborder::WorldBorder::default()
|
||||
&& let Err(e) = save::write_dat(
|
||||
&self.border_path(),
|
||||
Tag::compound([
|
||||
("data", self.border.pack()),
|
||||
("DataVersion", Tag::Int(horizon_world::DATA_VERSION)),
|
||||
]),
|
||||
);
|
||||
)
|
||||
{
|
||||
log::warn!("the world border was not written: {e}");
|
||||
}
|
||||
let path = self.scoreboard_path();
|
||||
let board = &self.score.board;
|
||||
if board == &Scoreboard::default() && !path.exists() {
|
||||
return;
|
||||
}
|
||||
let _ = save::write_dat(
|
||||
if let Err(e) = save::write_dat(
|
||||
&path,
|
||||
Tag::compound([
|
||||
("data", board.pack()),
|
||||
("DataVersion", Tag::Int(horizon_world::DATA_VERSION)),
|
||||
]),
|
||||
);
|
||||
) {
|
||||
log::warn!("the scoreboard was not written: {e}");
|
||||
}
|
||||
}
|
||||
/// The names commands complete: objectives, teams and tracked holders.
|
||||
pub(super) fn sync_score_registries(&mut self) {
|
||||
|
||||
@@ -118,14 +118,12 @@ fn death_buttons(w: f32, h: f32, hardcore: bool) -> [(f32, f32, &'static str, u8
|
||||
} else {
|
||||
"deathScreen.respawn"
|
||||
};
|
||||
// DeathScreen.init: `width / 2 - 100`, `height / 4 + 72` and `+ 96`, in
|
||||
// int GUI pixels.
|
||||
let (x, y) = ((w.ceil() / 2.0).floor() - 100.0, (h.ceil() / 4.0).floor());
|
||||
[
|
||||
(w / 2.0 - 100.0, h / 4.0 + 72.0, respawn, 0),
|
||||
(
|
||||
w / 2.0 - 100.0,
|
||||
h / 4.0 + 96.0,
|
||||
"deathScreen.titleScreen",
|
||||
1,
|
||||
),
|
||||
(x, y + 72.0, respawn, 0),
|
||||
(x, y + 96.0, "deathScreen.titleScreen", 1),
|
||||
]
|
||||
}
|
||||
impl Game<'_> {
|
||||
@@ -366,6 +364,9 @@ impl Game<'_> {
|
||||
}
|
||||
// Autosaves keep a login position; death must resolve the respawn point instead.
|
||||
self.level.position = None;
|
||||
// The dead player's Entity.setRemoved stopped its riding: the
|
||||
// new one is not put back into the vehicle.
|
||||
self.riding = None;
|
||||
}
|
||||
if self.remote.is_some() {
|
||||
self.ui.death_text = None;
|
||||
@@ -466,7 +467,16 @@ impl Game<'_> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Screen, pause_buttons, pause_icons};
|
||||
use super::{Screen, death_buttons, pause_buttons, pause_icons};
|
||||
|
||||
#[test]
|
||||
fn death_buttons_sit_on_whole_gui_pixels() {
|
||||
// DeathScreen.init in ints: a 427x253 GUI (1709x1009 at scale 4) puts
|
||||
// Respawn at (113, 63 + 72), not (113.5, 63.25 + 72).
|
||||
let at = |w, h| death_buttons(w, h, false).map(|b| (b.0, b.1));
|
||||
assert_eq!(at(427.0, 253.0), [(113.0, 135.0), (113.0, 159.0)]);
|
||||
assert_eq!(at(320.0, 334.0), [(60.0, 155.0), (60.0, 179.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_blur_matches_vanilla_screen_backgrounds() {
|
||||
|
||||
@@ -204,7 +204,7 @@ mod run {
|
||||
&& let Some(p) = &self.player
|
||||
{
|
||||
out.push(ServerPlayer {
|
||||
id: self.player_uuid_string(),
|
||||
id: uuid_string(self.player_uuid()),
|
||||
name: crate::game::chat::PLAYER_NAME.to_owned(),
|
||||
x: p.position.x,
|
||||
y: p.position.y,
|
||||
@@ -272,7 +272,7 @@ mod run {
|
||||
for event in std::mem::take(&mut self.mods.events) {
|
||||
let who = |w: &Who| {
|
||||
let id = match w {
|
||||
Who::Local => self.player_uuid_string(),
|
||||
Who::Local => uuid_string(self.player_uuid()),
|
||||
Who::Uuid(u) => uuid_string(*u),
|
||||
Who::Conn(c) => {
|
||||
let guests = self.lan.iter().flat_map(|h| &h.hub.guests);
|
||||
@@ -490,7 +490,7 @@ mod run {
|
||||
let local = self.options.execution_role.is_client()
|
||||
&& self.remote.is_none()
|
||||
&& self.player.is_some();
|
||||
if local && self.player_uuid_string() == id {
|
||||
if local && uuid_string(self.player_uuid()) == id {
|
||||
self.add_mod_chat_line(line);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -34,6 +34,15 @@ fn sign_box() -> EditBox {
|
||||
edit
|
||||
}
|
||||
|
||||
/// AbstractSignEditScreen.init's Done button: `width / 2 - 100`,
|
||||
/// `height / 4 + 144`, int GUI pixels.
|
||||
fn done_button(w: f32, h: f32) -> (f32, f32) {
|
||||
(
|
||||
(w.ceil() / 2.0).floor() - 100.0,
|
||||
(h.ceil() / 4.0).floor() + 144.0,
|
||||
)
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `SignBlockEntity.getSlotPlayerIsFacing`: whether the player stands in
|
||||
/// front of the sign's text (within 90 degrees of its facing).
|
||||
@@ -464,7 +473,7 @@ impl Game<'_> {
|
||||
/// or a click on a line (`EditBox.onClick`).
|
||||
pub(super) fn sign_edit_click(&mut self, size: [u32; 2]) {
|
||||
let b = HudBatch::new(size);
|
||||
let (x, y) = (b.width / 2.0 - 100.0, b.height / 4.0 + 144.0);
|
||||
let (x, y) = done_button(b.width, b.height);
|
||||
let (mx, my) = self.cursor;
|
||||
if mx >= x && mx < x + 200.0 && my >= y && my < y + 20.0 {
|
||||
self.audio.play_button_click();
|
||||
@@ -628,7 +637,7 @@ impl Game<'_> {
|
||||
);
|
||||
}
|
||||
}
|
||||
let (bx, by) = (w / 2.0 - 100.0, h / 4.0 + 144.0);
|
||||
let (bx, by) = done_button(w, h);
|
||||
batch.sprite_scaled(
|
||||
atlas,
|
||||
"gui/sprites/widget/button",
|
||||
@@ -642,10 +651,20 @@ impl Game<'_> {
|
||||
batch.text(
|
||||
atlas,
|
||||
"Done",
|
||||
bx + (200.0 - tw) / 2.0,
|
||||
bx + 100.0 - (tw / 2.0).floor(),
|
||||
by + 6.0,
|
||||
u32::MAX,
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn done_button_sits_on_whole_gui_pixels() {
|
||||
// `width / 2 - 100, height / 4 + 144` in ints: 334 high is 83 + 144.
|
||||
assert_eq!(super::done_button(427.0, 334.0), (113.0, 227.0));
|
||||
assert_eq!(super::done_button(320.0, 240.0), (60.0, 204.0));
|
||||
}
|
||||
}
|
||||
@@ -99,36 +99,16 @@ impl Game<'_> {
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// `ProjectileUtil.getHitEntitiesAlong` for the mobs: those whose box the
|
||||
/// segment `from`..`to` meets, or comes within the margin of with no
|
||||
/// block between.
|
||||
fn mobs_along(&self, from: Vec3, to: Vec3, margin: f64) -> Vec<usize> {
|
||||
let grow = Vec3::new(margin, margin, margin);
|
||||
let mut hits = Vec::new();
|
||||
for (i, m) in self.mobs.iter().enumerate() {
|
||||
// PiercingWeapon.canHitEntity: alive, and not the vehicle ridden.
|
||||
if !m.alive() || m.removed || self.riding == Some(m.id) {
|
||||
continue;
|
||||
}
|
||||
let bounds: Aabb = m.bounds();
|
||||
let hit = bounds.contains(from)
|
||||
|| bounds.clip(from, to).is_some()
|
||||
|| (margin > 0.0
|
||||
&& bounds.inflate(grow).clip(from, to).is_some_and(|outside| {
|
||||
let centre = bounds.center();
|
||||
let toward = self.clip_collider(outside, centre).unwrap_or(centre);
|
||||
bounds.clip(outside, toward).is_some()
|
||||
}));
|
||||
if hit {
|
||||
hits.push(i);
|
||||
}
|
||||
}
|
||||
hits
|
||||
/// The boxes of the mobs a spear can hit: alive, and not the vehicle
|
||||
/// ridden (`PiercingWeapon.canHitEntity`), with their index.
|
||||
pub(super) fn hittable_mob_boxes(&self) -> Vec<(usize, Aabb)> {
|
||||
(self.mobs.iter().enumerate())
|
||||
.filter(|(_, m)| m.alive() && !m.removed && self.riding != Some(m.id))
|
||||
.map(|(i, m)| (i, m.bounds()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `ProjectileUtil.getHitEntitiesAlong` with the spear's `AttackRange`: the
|
||||
/// mobs along the view from the minimum reach to the maximum plus the
|
||||
/// attacker's own movement, none when a block is closer than the minimum.
|
||||
/// `ProjectileUtil.getHitEntitiesAlong` with the spear's `AttackRange`.
|
||||
fn stab_targets(&self, eye: Vec3, look: Vec3, movement: Vec3) -> Vec<usize> {
|
||||
// AttackRange.effectiveMinRange and effectiveMaxRange for a player.
|
||||
let (min, max) = if self.creative {
|
||||
@@ -136,16 +116,13 @@ impl Game<'_> {
|
||||
} else {
|
||||
(REACH.min, REACH.max)
|
||||
};
|
||||
let from = eye.add_vector(look.scale(f64::from(min)));
|
||||
let mut to = eye.add_vector(look.scale(f64::from(max) + movement.dot(look).max(0.0)));
|
||||
// A block closer than the minimum reach takes the whole stab.
|
||||
if let Some(block) = self.clip_collider(eye, to) {
|
||||
to = block;
|
||||
if eye.distance_squared(to) < eye.distance_squared(from) {
|
||||
return Vec::new();
|
||||
}
|
||||
}
|
||||
self.mobs_along(from, to, f64::from(REACH.hitbox_margin))
|
||||
let reach = (min, max, REACH.hitbox_margin);
|
||||
let clip = |from, to| self.clip_collider(from, to);
|
||||
let boxes = self.hittable_mob_boxes();
|
||||
hits_in_reach(&boxes, eye, look, movement, reach, clip)
|
||||
.into_iter()
|
||||
.map(|(i, _)| i)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `KineticWeapon.damageEntities`: one tick of the spear in use, `ticks`
|
||||
@@ -411,3 +388,60 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `ProjectileUtil.getManyEntityHitResult` over `boxes`: those the segment
|
||||
/// `from`..`to` meets, or comes within the margin of with no block between
|
||||
/// (`clip`: where a segment first meets a block), each with where it is hit.
|
||||
fn hits_along(
|
||||
boxes: &[(usize, Aabb)],
|
||||
from: Vec3,
|
||||
to: Vec3,
|
||||
margin: f64,
|
||||
clip: &impl Fn(Vec3, Vec3) -> Option<Vec3>,
|
||||
) -> Vec<(usize, Vec3)> {
|
||||
let grow = Vec3::new(margin, margin, margin);
|
||||
let mut hits = Vec::new();
|
||||
for &(i, bounds) in boxes {
|
||||
let hit = if bounds.contains(from) {
|
||||
Some(from)
|
||||
} else if let Some(at) = bounds.clip(from, to) {
|
||||
Some(at)
|
||||
} else if margin > 0.0 {
|
||||
bounds.inflate(grow).clip(from, to).and_then(|outside| {
|
||||
let centre = bounds.center();
|
||||
let toward = clip(outside, centre).unwrap_or(centre);
|
||||
bounds.clip(outside, toward)
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(at) = hit {
|
||||
hits.push((i, at));
|
||||
}
|
||||
}
|
||||
hits
|
||||
}
|
||||
|
||||
/// `ProjectileUtil.getHitEntitiesAlong` with an `AttackRange` of `reach` (its
|
||||
/// effective min and max range and hitbox margin): the boxes along `look`
|
||||
/// from the minimum reach to the maximum plus the attacker's own movement,
|
||||
/// none when a block (`clip`) is closer than the minimum.
|
||||
pub(super) fn hits_in_reach(
|
||||
boxes: &[(usize, Aabb)],
|
||||
eye: Vec3,
|
||||
look: Vec3,
|
||||
movement: Vec3,
|
||||
(min, max, margin): (f32, f32, f32),
|
||||
clip: impl Fn(Vec3, Vec3) -> Option<Vec3>,
|
||||
) -> Vec<(usize, Vec3)> {
|
||||
let from = eye.add_vector(look.scale(f64::from(min)));
|
||||
let mut to = eye.add_vector(look.scale(f64::from(max) + movement.dot(look).max(0.0)));
|
||||
// A block closer than the minimum reach takes the whole stab.
|
||||
if let Some(block) = clip(eye, to) {
|
||||
to = block;
|
||||
if eye.distance_squared(to) < eye.distance_squared(from) {
|
||||
return Vec::new();
|
||||
}
|
||||
}
|
||||
hits_along(boxes, from, to, f64::from(margin), &clip)
|
||||
}
|
||||
@@ -340,6 +340,9 @@ impl Loading {
|
||||
self.save_menu_settings();
|
||||
self.apply_menu_settings();
|
||||
}
|
||||
Event::SliderDrag => {
|
||||
self.apply_menu_settings();
|
||||
}
|
||||
Event::Close if self.menu.options.resource_error.is_some() => {}
|
||||
Event::Close => {
|
||||
self.menu.options_open = false;
|
||||
@@ -393,7 +396,7 @@ impl Loading {
|
||||
}
|
||||
}
|
||||
// Mods' settings pages open only in a running game.
|
||||
Event::ModSettings(_) | Event::NativeButton(..) => {}
|
||||
Event::ModSettings(_) | Event::NativeSettings(_) | Event::NativeButton(..) => {}
|
||||
// The startup menu runs before the game opens a control socket.
|
||||
Event::ButtonClick | Event::CopyAgentDetails => {}
|
||||
}
|
||||
|
||||
@@ -1875,9 +1875,9 @@ impl Game<'_> {
|
||||
"minecraft:tipped_arrow" => 0.125,
|
||||
_ => 1.0,
|
||||
};
|
||||
for (text, cat) in brewing::tooltip(stack.potion(), scale, &|k| {
|
||||
e.translate(k).map(str::to_owned)
|
||||
}) {
|
||||
// PotionContents.getPotionDescription: the effect names are
|
||||
// translatable, read in the selected language like every other line.
|
||||
for (text, cat) in brewing::tooltip(stack.potion(), scale, &translate) {
|
||||
let c = match cat {
|
||||
brewing::Category::Beneficial => rgba(85, 85, 255, 255),
|
||||
brewing::Category::Harmful => rgba(255, 85, 85, 255),
|
||||
@@ -1902,18 +1902,15 @@ impl Game<'_> {
|
||||
{
|
||||
push(
|
||||
&mut lines,
|
||||
e.translate("item.minecraft.smithing_template.upgrade")
|
||||
.unwrap_or("Upgrade:")
|
||||
.to_owned(),
|
||||
translate("item.minecraft.smithing_template.upgrade")
|
||||
.unwrap_or_else(|| "Upgrade:".to_owned()),
|
||||
rgba(170, 170, 170, 255),
|
||||
);
|
||||
let short = |s: &str| s.trim_start_matches("minecraft:").to_owned();
|
||||
let p = e
|
||||
.translate(&format!("trim_pattern.minecraft.{}", short(&pattern)))
|
||||
.map_or_else(|| short(&pattern), str::to_owned);
|
||||
let m = e
|
||||
.translate(&format!("trim_material.minecraft.{}", short(&material)))
|
||||
.map_or_else(|| short(&material), str::to_owned);
|
||||
let p = translate(&format!("trim_pattern.minecraft.{}", short(&pattern)))
|
||||
.unwrap_or_else(|| short(&pattern));
|
||||
let m = translate(&format!("trim_material.minecraft.{}", short(&material)))
|
||||
.unwrap_or_else(|| short(&material));
|
||||
push(&mut lines, format!(" {p}"), rgba(170, 170, 170, 255));
|
||||
push(&mut lines, format!(" {m}"), rgba(170, 170, 170, 255));
|
||||
}
|
||||
@@ -1997,6 +1994,12 @@ impl Game<'_> {
|
||||
{
|
||||
push(&mut lines, text, rgba(85, 85, 255, 255));
|
||||
}
|
||||
// OminousBottleAmplifier.addToTooltip.
|
||||
if let Some((text, c)) =
|
||||
horizon_client::item_tooltip::ominous_bottle_line(stack, &display, &translate)
|
||||
{
|
||||
push(&mut lines, text, c);
|
||||
}
|
||||
// BlockItemStateProperties.addToTooltip.
|
||||
if let Some(text) = horizon_client::item_tooltip::honey_line(stack, &display, &translate) {
|
||||
push(&mut lines, text, gray);
|
||||
@@ -2245,10 +2248,24 @@ impl Game<'_> {
|
||||
x: f32,
|
||||
y: f32,
|
||||
) {
|
||||
let lines = Self::resolved(&self.stack_tooltip(stack));
|
||||
self.draw_stack_tooltip_with(batch, stack, x, y, Vec::new());
|
||||
}
|
||||
/// [`Self::draw_stack_tooltip`] with `after_name` inserted from line 1,
|
||||
/// as the creative screen adds its tab names.
|
||||
pub(super) fn draw_stack_tooltip_with(
|
||||
&mut self,
|
||||
batch: &mut HudBatch,
|
||||
stack: &ItemStack,
|
||||
x: f32,
|
||||
y: f32,
|
||||
after_name: Vec<(horizon_client::text::Text, u32)>,
|
||||
) {
|
||||
let mut lines = self.stack_tooltip(stack);
|
||||
if lines.is_empty() {
|
||||
return;
|
||||
}
|
||||
lines.splice(1..1, after_name);
|
||||
let lines = Self::resolved(&lines);
|
||||
// The component's height does not depend on where it is drawn, so a
|
||||
// probe at the origin gives the box its extra height.
|
||||
let probe = horizon_client::bundle::tooltip_layout(self.res.items(), stack, 0.0, 0.0, 96.0);
|
||||
|
||||
@@ -2,13 +2,62 @@
|
||||
//! kept in the dropped item's `container` component) and ender chests (the
|
||||
//! player's `PlayerEnderChestContainer`, saved as `EnderItems`).
|
||||
use super::Game;
|
||||
use horizon_client::{containers::BlockEntity, items::ItemStack, text::Text};
|
||||
use horizon_client::{
|
||||
containers::{BlockEntity, ChestHalf, is_chest_block},
|
||||
items::ItemStack,
|
||||
text::Text,
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
|
||||
pub(super) fn is_shulker_box(name: &str) -> bool {
|
||||
name.ends_with("shulker_box")
|
||||
}
|
||||
impl Game<'_> {
|
||||
/// `ServerPlayerGameMode.useItemOn` for a spectator: the block's menu
|
||||
/// (`BlockState.getMenuProvider`) opens, and nothing else happens. The
|
||||
/// lid, its sound and the `container_open` game event come from
|
||||
/// `ContainerOpenersCounter`, which spectators never join
|
||||
/// (`ChestBlockEntity.startOpen`); the stat, the piglins' anger and the
|
||||
/// shulker box's room check are `useWithoutItem`'s, which is not called.
|
||||
/// Only the block containers whose clicks the server takes back from a
|
||||
/// spectator (`handleContainerClick`) open here: storage, the furnaces,
|
||||
/// the brewing stand and the crafter.
|
||||
pub(super) fn spectator_open_menu(&mut self, pos: [i32; 3]) {
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
let name = self
|
||||
.res
|
||||
.facts()
|
||||
.get(self.world.block(pos[0], pos[1], pos[2]))
|
||||
.name
|
||||
.clone();
|
||||
let container = is_shulker_box(&name)
|
||||
|| matches!(
|
||||
name.trim_start_matches("minecraft:"),
|
||||
"chest"
|
||||
| "trapped_chest"
|
||||
| "barrel"
|
||||
| "hopper"
|
||||
| "dispenser"
|
||||
| "dropper"
|
||||
| "furnace"
|
||||
| "blast_furnace"
|
||||
| "smoker"
|
||||
| "brewing_stand"
|
||||
| "crafter"
|
||||
);
|
||||
// ChestBlock.getMenuProvider: none while either half is blocked.
|
||||
if !container || self.chest_menu_blocked(key, &name) {
|
||||
return;
|
||||
}
|
||||
let Some(entity) = BlockEntity::for_block(&name) else {
|
||||
return;
|
||||
};
|
||||
self.world.block_entities.get_or_insert_with(key, || entity);
|
||||
self.container = Some(key);
|
||||
self.screen = super::Screen::Inventory;
|
||||
self.capture(false);
|
||||
self.right = false;
|
||||
}
|
||||
/// The custom name of the open container, or its default title
|
||||
/// (a double chest is named by whichever half has a name).
|
||||
pub(super) fn container_title(&self, default: String) -> String {
|
||||
@@ -72,7 +121,7 @@ impl Game<'_> {
|
||||
/// with either half blocked, opens no menu.
|
||||
pub(super) fn chest_menu_blocked(&self, key: (i32, i32, i32), name: &str) -> bool {
|
||||
match name {
|
||||
"minecraft:chest" | "minecraft:trapped_chest" => {
|
||||
n if is_chest_block(n) => {
|
||||
self.chest_blocked_at(key)
|
||||
|| self
|
||||
.chest_partner(key)
|
||||
@@ -96,22 +145,13 @@ impl Game<'_> {
|
||||
|
||||
// ---- chest menus: double chests, titles and shift-click ----
|
||||
|
||||
/// `Direction.getClockWise` for horizontal facings.
|
||||
fn clockwise(facing: &str) -> &'static str {
|
||||
match facing {
|
||||
"north" => "east",
|
||||
"east" => "south",
|
||||
"south" => "west",
|
||||
_ => "north",
|
||||
}
|
||||
}
|
||||
fn counter_clockwise(facing: &str) -> &'static str {
|
||||
match clockwise(facing) {
|
||||
"east" => "west",
|
||||
"south" => "north",
|
||||
"west" => "east",
|
||||
_ => "south",
|
||||
}
|
||||
/// A chest block state's half: its block, `type` and `facing`.
|
||||
fn chest_half(state: &horizon_world::chunk::BlockState) -> Option<ChestHalf<'_>> {
|
||||
Some(ChestHalf {
|
||||
block: &state.name,
|
||||
kind: state.properties.get("type")?,
|
||||
facing: state.properties.get("facing")?,
|
||||
})
|
||||
}
|
||||
fn facing_step(facing: &str) -> (i32, i32) {
|
||||
match facing {
|
||||
@@ -128,34 +168,19 @@ impl Game<'_> {
|
||||
pub(super) fn chest_partner(&self, key: (i32, i32, i32)) -> Option<((i32, i32, i32), bool)> {
|
||||
let registry = self.pack.assets.registry;
|
||||
let state = registry.state(self.world.block(key.0, key.1, key.2))?;
|
||||
if !matches!(
|
||||
state.name.as_str(),
|
||||
"minecraft:chest" | "minecraft:trapped_chest"
|
||||
) {
|
||||
if !is_chest_block(&state.name) {
|
||||
return None;
|
||||
}
|
||||
let kind = state.properties.get("type")?.as_str();
|
||||
if kind == "single" {
|
||||
return None;
|
||||
}
|
||||
let facing = state.properties.get("facing")?.as_str();
|
||||
let dir = if kind == "left" {
|
||||
clockwise(facing)
|
||||
} else {
|
||||
counter_clockwise(facing)
|
||||
};
|
||||
let (dx, dz) = facing_step(dir);
|
||||
let own = chest_half(state)?;
|
||||
let (dx, dz) = own.connected_step()?;
|
||||
let other = (key.0 + dx, key.1, key.2 + dz);
|
||||
let other_state = registry.state(self.world.block(other.0, other.1, other.2))?;
|
||||
let other_kind = other_state.properties.get("type")?.as_str();
|
||||
let paired = other_state.name == state.name
|
||||
&& other_kind != "single"
|
||||
&& other_kind != kind
|
||||
let paired = own.pairs_with(&chest_half(other_state)?)
|
||||
&& matches!(
|
||||
self.world.block_entities.get(&other),
|
||||
Some(BlockEntity::Chest(items)) if items.len() == 27
|
||||
);
|
||||
paired.then_some((other, kind == "right"))
|
||||
paired.then_some((other, own.kind == "right"))
|
||||
}
|
||||
/// The open or close sound of a container block (`ChestBlockEntity.playSound`,
|
||||
/// `BarrelBlockEntity.playSound`, `ShulkerBoxBlockEntity.startOpen`): volume
|
||||
@@ -345,12 +370,8 @@ impl Game<'_> {
|
||||
return None;
|
||||
}
|
||||
let generic = match self.container_block().as_deref() {
|
||||
Some(
|
||||
"minecraft:chest"
|
||||
| "minecraft:trapped_chest"
|
||||
| "minecraft:barrel"
|
||||
| "minecraft:ender_chest",
|
||||
) => true,
|
||||
Some("minecraft:barrel" | "minecraft:ender_chest") => true,
|
||||
Some(n) if is_chest_block(n) => true,
|
||||
_ => self.open_cart_kind() == Some(super::minecarts::CartKind::Chest),
|
||||
};
|
||||
generic.then(|| self.container_size() / 9)
|
||||
@@ -394,8 +415,15 @@ impl Game<'_> {
|
||||
256.0,
|
||||
256.0,
|
||||
);
|
||||
let title = self.translate("container.shulkerBox", "Shulker Box");
|
||||
batch.text(atlas, &title, ox + 8.0, oy + 6.0, grey, false);
|
||||
// ShulkerBoxScreen draws the menu's title: the box's custom name
|
||||
// (BaseContainerBlockEntity.getDisplayName) or its default name.
|
||||
let title = self.remote_menu_title().unwrap_or_else(|| {
|
||||
Text::literal(
|
||||
self.container_title(self.translate("container.shulkerBox", "Shulker Box")),
|
||||
)
|
||||
.resolve_legacy()
|
||||
});
|
||||
batch.text_styled(atlas, &title, ox + 8.0, oy + 6.0, grey, false);
|
||||
let inventory = self.translate("container.inventory", "Inventory");
|
||||
batch.text(atlas, &inventory, ox + 8.0, oy + 73.0, grey, false);
|
||||
return;
|
||||
@@ -452,11 +480,38 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn double_chest_halves_connect_around_the_facing() {
|
||||
let half = |kind, facing| ChestHalf {
|
||||
block: "minecraft:chest",
|
||||
kind,
|
||||
facing,
|
||||
};
|
||||
// A left half facing north connects east, a right half west.
|
||||
assert_eq!(facing_step(clockwise("north")), (1, 0));
|
||||
assert_eq!(facing_step(counter_clockwise("north")), (-1, 0));
|
||||
assert_eq!(facing_step(clockwise("south")), (-1, 0));
|
||||
assert_eq!(facing_step(counter_clockwise("east")), (0, -1));
|
||||
assert_eq!(half("left", "north").connected_step(), Some((1, 0)));
|
||||
assert_eq!(half("right", "north").connected_step(), Some((-1, 0)));
|
||||
assert_eq!(half("left", "south").connected_step(), Some((-1, 0)));
|
||||
assert_eq!(half("right", "east").connected_step(), Some((0, -1)));
|
||||
assert_eq!(half("single", "east").connected_step(), None);
|
||||
}
|
||||
#[test]
|
||||
fn copper_chests_join_like_chests() {
|
||||
let half = |block, kind| ChestHalf {
|
||||
block,
|
||||
kind,
|
||||
facing: "north",
|
||||
};
|
||||
for block in [
|
||||
"minecraft:chest",
|
||||
"minecraft:trapped_chest",
|
||||
"minecraft:copper_chest",
|
||||
"minecraft:waxed_weathered_copper_chest",
|
||||
] {
|
||||
assert!(is_chest_block(block));
|
||||
assert!(half(block, "left").pairs_with(&half(block, "right")));
|
||||
}
|
||||
// ChestBlock.combine needs the same block on both halves.
|
||||
let copper = half("minecraft:copper_chest", "left");
|
||||
assert!(!copper.pairs_with(&half("minecraft:exposed_copper_chest", "right")));
|
||||
assert!(!is_chest_block("minecraft:ender_chest"));
|
||||
}
|
||||
#[test]
|
||||
fn shulker_boxes_are_recognised_by_name() {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
//! Server text displays: metadata, interpolation, billboard transforms and world text.
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
hud::{HudBatch, rgba},
|
||||
gfx::TEXT_POLYGON_OFFSET_OVERLAY,
|
||||
hud::HudBatch,
|
||||
mesher::Vertex,
|
||||
text::Text,
|
||||
text_display::{Align, TextDisplayData},
|
||||
text_display::{self, Lines, TextDisplayData},
|
||||
};
|
||||
use horizon_protocol::entity_data::Value;
|
||||
|
||||
@@ -34,12 +34,6 @@ pub(super) struct RemoteTextDisplay {
|
||||
lines: Option<Lines>,
|
||||
}
|
||||
|
||||
/// `TextDisplay.CachedInfo`: each line and its width, and the widest.
|
||||
struct Lines {
|
||||
lines: Vec<(Text, f32)>,
|
||||
width: f32,
|
||||
}
|
||||
|
||||
/// `Display.RENDER_STATE_IDS` and `TextDisplay.TEXT_RENDER_STATE_IDS`: the
|
||||
/// data a render state is built from (not the view range, size or glow).
|
||||
fn renders(id: u8) -> bool {
|
||||
@@ -157,6 +151,7 @@ impl Game<'_> {
|
||||
see_through: &mut Vec<Vertex>,
|
||||
) {
|
||||
self.text_display_vertices = 0;
|
||||
self.mark_translucent_entity(normal.len(), "minecraft:text_display");
|
||||
let atlas = &self.gui.atlas;
|
||||
let front = self.camera_type == super::perspective::CameraType::ThirdPersonFront;
|
||||
let angles = if front {
|
||||
@@ -177,69 +172,23 @@ impl Game<'_> {
|
||||
display.old_rotation[i]
|
||||
+ angle(display.rotation[i] - display.old_rotation[i]) * partial as f32
|
||||
});
|
||||
let mut matrix = glam::Mat4::from_translation((position - camera).as_vec3())
|
||||
let lines = display
|
||||
.lines
|
||||
.get_or_insert_with(|| Lines::split(&atlas.font, &d.text, d.line_width));
|
||||
let matrix = glam::Mat4::from_translation((position - camera).as_vec3())
|
||||
* d.matrix(rotation, angles)
|
||||
* glam::Mat4::from_rotation_y(std::f32::consts::PI)
|
||||
* glam::Mat4::from_scale(glam::Vec3::splat(-0.025));
|
||||
* lines.pose();
|
||||
if !matrix.is_finite() {
|
||||
continue;
|
||||
}
|
||||
// TextDisplayRenderer.splitLines: Font.split, no indent on wrapped lines.
|
||||
let Lines { lines, width } = display.lines.get_or_insert_with(|| {
|
||||
let lines: Vec<_> = atlas
|
||||
.font
|
||||
.split(&d.text, d.line_width as f32)
|
||||
.into_iter()
|
||||
.map(|line| {
|
||||
let width = atlas.font.width_text(&line).ceil();
|
||||
(line, width)
|
||||
})
|
||||
.collect();
|
||||
let width = lines.iter().map(|l| l.1).fold(0.0, f32::max);
|
||||
Lines { lines, width }
|
||||
});
|
||||
let width = *width;
|
||||
let height = lines.len() as f32 * 10.0 - 1.0;
|
||||
matrix *=
|
||||
glam::Mat4::from_translation(glam::Vec3::new(1.0 - width / 2.0, -height, 0.0));
|
||||
let mut batch = HudBatch::new([1, 1]);
|
||||
let bg = if d.flags & 4 != 0 {
|
||||
self.settings.text_background(0.25)
|
||||
} else {
|
||||
d.background as u32
|
||||
};
|
||||
if bg != 0 {
|
||||
batch.fill(
|
||||
atlas,
|
||||
// submitTextBackground(-1, -1, width, height): corners, not a size.
|
||||
-1.0,
|
||||
-1.0,
|
||||
width + 1.0,
|
||||
height + 1.0,
|
||||
rgba(
|
||||
(bg >> 16) as u8,
|
||||
(bg >> 8) as u8,
|
||||
bg as u8,
|
||||
(bg >> 24) as u8,
|
||||
),
|
||||
);
|
||||
}
|
||||
let align = d.align();
|
||||
for (i, (line, line_width)) in lines.iter().enumerate() {
|
||||
let x = match align {
|
||||
Align::Left => 0.0,
|
||||
Align::Right => width - line_width,
|
||||
Align::Center => (width - line_width) / 2.0,
|
||||
};
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
line,
|
||||
x,
|
||||
i as f32 * 10.0,
|
||||
rgba(255, 255, 255, d.opacity as u8),
|
||||
d.flags & 1 != 0,
|
||||
);
|
||||
}
|
||||
text_display::draw(
|
||||
&mut batch,
|
||||
atlas,
|
||||
&d,
|
||||
lines,
|
||||
self.settings.text_background(0.25),
|
||||
);
|
||||
let world_light = self.world.light(
|
||||
position.x.floor() as i32,
|
||||
position.y.floor() as i32,
|
||||
@@ -251,11 +200,12 @@ impl Game<'_> {
|
||||
((d.brightness as u32 >> 20 & 15) * 16)
|
||||
| (((d.brightness as u32 >> 4 & 15) * 16) << 8)
|
||||
};
|
||||
// Font.DisplayMode: SEE_THROUGH over everything, else POLYGON_OFFSET.
|
||||
let through = d.flags & 2 != 0;
|
||||
let out = if through {
|
||||
&mut *see_through
|
||||
let (out, layer) = if through {
|
||||
(&mut *see_through, 2)
|
||||
} else {
|
||||
&mut *normal
|
||||
(&mut *normal, TEXT_POLYGON_OFFSET_OVERLAY)
|
||||
};
|
||||
for quad in batch.vertices.as_chunks::<6>().0 {
|
||||
for i in [0, 1, 2, 5] {
|
||||
@@ -267,7 +217,7 @@ impl Game<'_> {
|
||||
uv: v.uv,
|
||||
color: v.color,
|
||||
light,
|
||||
layer: if through { 2 } else { 0 },
|
||||
layer,
|
||||
normal: [0; 4],
|
||||
|
||||
glint_uv: [0.0, 0.0],
|
||||
|
||||
Loaded 100 of 182 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user