fix: latest rust clippy lints

This commit is contained in:
Alexander Medvedev 2026-03-05 21:34:47 +01:00
parent fbe13bbacd
commit 7248f942e7
50 changed files with 225 additions and 248 deletions

48
Cargo.lock generated
View File

@ -66,9 +66,9 @@ dependencies = [
[[package]] [[package]]
name = "async-compression" name = "async-compression"
version = "0.4.40" version = "0.4.41"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d67d43201f4d20c78bcda740c142ca52482d81da80681533d33bf3f0596c8e2" checksum = "d0f9ee0f6e02ffd7ad5816e9464499fba7b3effd01123b515c41d1697c43dad1"
dependencies = [ dependencies = [
"compression-codecs", "compression-codecs",
"compression-core", "compression-core",
@ -586,9 +586,9 @@ checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
[[package]] [[package]]
name = "crossfire" name = "crossfire"
version = "3.1.3" version = "3.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4150133c3f558d3190b52a4d36b571e29c18a24e98d24d12201bed0c038986f8" checksum = "3fb12e9c05ae4854f743f0acec2f817148ba59a902484f6aa298d4fc7df2fac4"
dependencies = [ dependencies = [
"crossbeam-utils", "crossbeam-utils",
"futures-core", "futures-core",
@ -616,9 +616,9 @@ dependencies = [
[[package]] [[package]]
name = "crypto-bigint" name = "crypto-bigint"
version = "0.7.0-rc.27" version = "0.7.0-rc.28"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b43308b9b6a47554f4612d5b1fb95ff935040aa3927dd42b1d6cbc015a262d96" checksum = "96dacf199529fb801ae62a9aafdc01b189e9504c0d1ee1512a4c16bcd8666a93"
dependencies = [ dependencies = [
"cpubits", "cpubits",
"ctutils", "ctutils",
@ -653,7 +653,7 @@ version = "0.7.0-pre.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6081ce8b60c0e533e2bba42771b94eb6149052115f4179744d5779883dc98583" checksum = "6081ce8b60c0e533e2bba42771b94eb6149052115f4179744d5779883dc98583"
dependencies = [ dependencies = [
"crypto-bigint 0.7.0-rc.27", "crypto-bigint 0.7.0-rc.28",
"libm", "libm",
"rand_core 0.10.0", "rand_core 0.10.0",
] ]
@ -1463,9 +1463,9 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]] [[package]]
name = "linux-raw-sys" name = "linux-raw-sys"
version = "0.11.0" version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]] [[package]]
name = "litemap" name = "litemap"
@ -1871,9 +1871,9 @@ dependencies = [
[[package]] [[package]]
name = "pin-project-lite" name = "pin-project-lite"
version = "0.2.16" version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]] [[package]]
name = "pin-utils" name = "pin-utils"
@ -2202,9 +2202,9 @@ dependencies = [
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.44" version = "1.0.45"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
] ]
@ -2330,12 +2330,12 @@ dependencies = [
[[package]] [[package]]
name = "rsa" name = "rsa"
version = "0.10.0-rc.15" version = "0.10.0-rc.16"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b342b99544549f37509ed7fd42b0cea04bfd9ce07c16ca56094cf0fbeefbbcd" checksum = "6fb9fd8c1edd9e6a2693623baf0fe77ff05ce022a5d7746900ffc38a15c233de"
dependencies = [ dependencies = [
"const-oid 0.10.2", "const-oid 0.10.2",
"crypto-bigint 0.7.0-rc.27", "crypto-bigint 0.7.0-rc.28",
"crypto-primes", "crypto-primes",
"digest 0.11.0", "digest 0.11.0",
"pkcs1", "pkcs1",
@ -2354,9 +2354,9 @@ checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
[[package]] [[package]]
name = "rustix" name = "rustix"
version = "1.1.3" version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34" checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"errno", "errno",
@ -2752,9 +2752,9 @@ checksum = "016ef9739649996fcc983b9c588fe3d557cf216d4d98503ce1b057ab5a66d689"
[[package]] [[package]]
name = "tempfile" name = "tempfile"
version = "3.25.0" version = "3.26.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0136791f7c95b1f6dd99f9cc786b91bb81c3800b639b3478e561ddb7be95e5f1" checksum = "82a72c767771b47409d2345987fda8628641887d5466101319899796367354a0"
dependencies = [ dependencies = [
"fastrand", "fastrand",
"once_cell", "once_cell",
@ -2844,9 +2844,9 @@ dependencies = [
[[package]] [[package]]
name = "tokio" name = "tokio"
version = "1.49.0" version = "1.50.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86" checksum = "27ad5e34374e03cfffefc301becb44e9dc3c17584f414349ebe29ed26661822d"
dependencies = [ dependencies = [
"bytes", "bytes",
"libc", "libc",
@ -2861,9 +2861,9 @@ dependencies = [
[[package]] [[package]]
name = "tokio-macros" name = "tokio-macros"
version = "2.6.0" version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" checksum = "5c55a2eff8b69ce66c84f85e1da1c233edc36ceb85a2058d11b0d6a3c7e7569c"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",

View File

@ -71,7 +71,7 @@ struct_excessive_bools = "allow"
[workspace.package] [workspace.package]
version = "0.1.0-dev+1.21.11" version = "0.1.0-dev+1.21.11"
edition = "2024" edition = "2024"
rust-version = "1.89" rust-version = "1.94"
[profile.release] [profile.release]
lto = true lto = true
@ -87,7 +87,7 @@ debug = true
strip = false strip = false
[workspace.dependencies] [workspace.dependencies]
tokio = { version = "1.49", default-features = false } tokio = { version = "1.50", default-features = false }
syn = { version = "2.0", default-features = false, features = ["printing"] } syn = { version = "2.0", default-features = false, features = ["printing"] }
@ -104,10 +104,10 @@ uuid = { version = "1.21", features = ["serde", "v3", "v4"] }
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
tempfile = { version = "3.25.0", default-features = false } tempfile = { version = "3.26.0", default-features = false }
proc-macro-error2 = "2" proc-macro-error2 = "2"
aes = "0.8" aes = "0.8"
async-compression = "0.4.40" async-compression = "0.4.41"
base64 = "0.22.1" base64 = "0.22.1"
bitflags = "2.11.0" bitflags = "2.11.0"
cesu8 = "1.1" cesu8 = "1.1"
@ -117,7 +117,7 @@ console-subscriber = { version = "0.5.0", default-features = false }
crc-fast = "1.10.0" crc-fast = "1.10.0"
criterion = { version = "0.8", default-features = false } criterion = { version = "0.8", default-features = false }
crossbeam-utils = "0.8.21" crossbeam-utils = "0.8.21"
crossfire = { version = "3.1.3", features = ["compat"] } crossfire = { version = "3.1.4", features = ["compat"] }
dashmap = "6.1" dashmap = "6.1"
ecdsa = "0.16.9" ecdsa = "0.16.9"
enum_dispatch = "0.3.13" enum_dispatch = "0.3.13"
@ -148,7 +148,7 @@ pumpkin-util = { path = "pumpkin-util" }
pumpkin-world = { path = "pumpkin-world" } pumpkin-world = { path = "pumpkin-world" }
quote = "1.0" quote = "1.0"
rand = "0.10.0" rand = "0.10.0"
rsa = "=0.10.0-rc.15" rsa = "=0.10.0-rc.16"
rustc-hash = "2.1.1" rustc-hash = "2.1.1"
rustyline = "17.0.2" rustyline = "17.0.2"
ruzstd = "0.8.2" ruzstd = "0.8.2"

View File

@ -393,11 +393,13 @@ pub fn build() -> TokenStream {
} }
impl GenerationShapeConfig { impl GenerationShapeConfig {
#[inline] #[must_use] #[inline]
pub fn vertical_cell_block_count(&self) -> u8 { self.size_vertical << 2 } #[must_use]
pub const fn vertical_cell_block_count(&self) -> u8 { self.size_vertical << 2 }
#[inline] #[must_use] #[inline]
pub fn horizontal_cell_block_count(&self) -> u8 { self.size_horizontal << 2 } #[must_use]
pub const fn horizontal_cell_block_count(&self) -> u8 { self.size_horizontal << 2 }
#[must_use] #[must_use]
pub const fn max_y(&self) -> u16 { pub const fn max_y(&self) -> u16 {

View File

@ -28,12 +28,12 @@ pub struct GenerationShapeConfig {
impl GenerationShapeConfig { impl GenerationShapeConfig {
#[inline] #[inline]
#[must_use] #[must_use]
pub fn vertical_cell_block_count(&self) -> u8 { pub const fn vertical_cell_block_count(&self) -> u8 {
self.size_vertical << 2 self.size_vertical << 2
} }
#[inline] #[inline]
#[must_use] #[must_use]
pub fn horizontal_cell_block_count(&self) -> u8 { pub const fn horizontal_cell_block_count(&self) -> u8 {
self.size_horizontal << 2 self.size_horizontal << 2
} }
#[must_use] #[must_use]

View File

@ -29,7 +29,7 @@ impl ClientPacket for CUpdateTags<'_> {
version: &MinecraftVersion, version: &MinecraftVersion,
) -> Result<(), WritingError> { ) -> Result<(), WritingError> {
write.write_list(self.tags, |p, registry_key| { write.write_list(self.tags, |p, registry_key| {
p.write_string(&format!("minecraft:{}", registry_key.identifier_string(),))?; p.write_string(&format!("minecraft:{}", registry_key.identifier_string()))?;
let Some(values) = get_registry_key_tags(*version, *registry_key) else { let Some(values) = get_registry_key_tags(*version, *registry_key) else {
// no tags defined for that registry key in this version // no tags defined for that registry key in this version

View File

@ -259,13 +259,13 @@ impl BoundingBox {
/// Returns the minimum block position covered by this bounding box. /// Returns the minimum block position covered by this bounding box.
#[must_use] #[must_use]
pub fn min_block_pos(&self) -> BlockPos { pub const fn min_block_pos(&self) -> BlockPos {
BlockPos::floored_v(self.min) BlockPos::floored_v(self.min)
} }
/// Returns the maximum block position covered by this bounding box. /// Returns the maximum block position covered by this bounding box.
#[must_use] #[must_use]
pub fn max_block_pos(&self) -> BlockPos { pub const fn max_block_pos(&self) -> BlockPos {
// Use a tiny epsilon and floor the max coordinates so that a box whose // Use a tiny epsilon and floor the max coordinates so that a box whose
// max is exactly on a block boundary does not include the adjacent // max is exactly on a block boundary does not include the adjacent
// block. This mirrors vanilla behaviour where max block is inclusive // block. This mirrors vanilla behaviour where max block is inclusive
@ -295,7 +295,7 @@ impl BoundingBox {
/// # Arguments /// # Arguments
/// * `other` – Vector specifying how much to stretch along each axis. /// * `other` – Vector specifying how much to stretch along each axis.
#[must_use] #[must_use]
pub fn stretch(&self, other: Vector3<f64>) -> Self { pub const fn stretch(&self, other: Vector3<f64>) -> Self {
let mut new = *self; let mut new = *self;
if other.x < 0.0 { if other.x < 0.0 {

View File

@ -73,7 +73,7 @@ pub fn subtract_angles(start: f32, end: f32) -> f32 {
/// # Returns /// # Returns
/// `a² + b² + c²` /// `a² + b² + c²`
#[must_use] #[must_use]
pub fn squared_magnitude(a: f64, b: f64, c: f64) -> f64 { pub const fn squared_magnitude(a: f64, b: f64, c: f64) -> f64 {
c.mul_add(c, a.mul_add(a, b * b)) c.mul_add(c, a.mul_add(a, b * b))
} }
@ -179,7 +179,14 @@ pub fn floor_div<T: PrimInt + Zero + One>(x: T, y: T) -> T {
/// # Returns /// # Returns
/// n² /// n²
#[inline] #[inline]
pub fn square<T: Float>(n: T) -> T { #[must_use]
pub const fn square_f64(n: f64) -> f64 {
n * n
}
#[inline]
#[must_use]
pub const fn square_f32(n: f32) -> f32 {
n * n n * n
} }

View File

@ -371,7 +371,7 @@ impl BlockPos {
/// # Returns /// # Returns
/// A `BlockPos` with each coordinate floored to the nearest integer. /// A `BlockPos` with each coordinate floored to the nearest integer.
#[must_use] #[must_use]
pub fn floored(x: f64, y: f64, z: f64) -> Self { pub const fn floored(x: f64, y: f64, z: f64) -> Self {
Self(Vector3::new( Self(Vector3::new(
x.floor() as i32, x.floor() as i32,
y.floor() as i32, y.floor() as i32,
@ -387,7 +387,7 @@ impl BlockPos {
/// # Returns /// # Returns
/// A `BlockPos` with each component floored to the nearest integer. /// A `BlockPos` with each component floored to the nearest integer.
#[must_use] #[must_use]
pub fn floored_v(pos: Vector3<f64>) -> Self { pub const fn floored_v(pos: Vector3<f64>) -> Self {
Self(Vector3::new( Self(Vector3::new(
pos.x.floor() as i32, pos.x.floor() as i32,
pos.y.floor() as i32, pos.y.floor() as i32,
@ -403,7 +403,7 @@ impl BlockPos {
/// # Returns /// # Returns
/// A `BlockPos` with each component ceiled to the nearest integer. /// A `BlockPos` with each component ceiled to the nearest integer.
#[must_use] #[must_use]
pub fn ceiled_v(pos: Vector3<f64>) -> Self { pub const fn ceiled_v(pos: Vector3<f64>) -> Self {
Self(Vector3::new( Self(Vector3::new(
pos.x.ceil() as i32, pos.x.ceil() as i32,
pos.y.ceil() as i32, pos.y.ceil() as i32,

View File

@ -107,7 +107,7 @@ impl Gradient {
/// The dot product `self.x * x + self.y * y + self.z * z`. /// The dot product `self.x * x + self.y * y + self.z * z`.
#[inline] #[inline]
#[must_use] #[must_use]
pub fn dot(&self, x: f64, y: f64, z: f64) -> f64 { pub const fn dot(&self, x: f64, y: f64, z: f64) -> f64 {
self.z.mul_add(z, self.x.mul_add(x, self.y * y)) self.z.mul_add(z, self.x.mul_add(x, self.y * y))
} }
} }

View File

@ -137,7 +137,7 @@ impl PerlinNoiseSampler {
/// # Returns /// # Returns
/// The dot product of the selected gradient with (x, y, z). /// The dot product of the selected gradient with (x, y, z).
#[inline] #[inline]
fn grad(hash: i32, x: f64, y: f64, z: f64) -> f64 { const fn grad(hash: i32, x: f64, y: f64, z: f64) -> f64 {
GRADIENTS[(hash & 15) as usize].dot(x, y, z) GRADIENTS[(hash & 15) as usize].dot(x, y, z)
} }
@ -152,8 +152,7 @@ impl PerlinNoiseSampler {
/// # Returns /// # Returns
/// The faded value. /// The faded value.
#[inline] #[inline]
#[expect(clippy::suboptimal_flops)] const fn perlin_fade(value: f64) -> f64 {
fn perlin_fade(value: f64) -> f64 {
value * value * value * (value * (value * 6.0 - 15.0) + 10.0) value * value * value * (value * (value * 6.0 - 15.0) + 10.0)
} }
@ -297,8 +296,7 @@ impl OctavePerlinNoiseSampler {
/// The wrapped value. /// The wrapped value.
#[inline] #[inline]
#[must_use] #[must_use]
#[expect(clippy::suboptimal_flops)] pub const fn maintain_precision(value: f64) -> f64 {
pub fn maintain_precision(value: f64) -> f64 {
value - (value / 3.355_443_2E7 + 0.5).floor() * 3.355_443_2E7 value - (value / 3.355_443_2E7 + 0.5).floor() * 3.355_443_2E7
} }

View File

@ -113,8 +113,7 @@ impl SimplexNoiseSampler {
/// ///
/// # Returns /// # Returns
/// The contribution of this corner to the final noise value. /// The contribution of this corner to the final noise value.
#[expect(clippy::suboptimal_flops)] const fn grad(gradient_index: usize, x: f64, y: f64, z: f64, distance: f64) -> f64 {
fn grad(gradient_index: usize, x: f64, y: f64, z: f64, distance: f64) -> f64 {
let d = distance - x * x - y * y - z * z; let d = distance - x * x - y * y - z * z;
if d < 0f64 { if d < 0f64 {
0f64 0f64

View File

@ -1,7 +1,7 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[must_use] #[must_use]
pub fn to_long(float: f32) -> i64 { pub const fn to_long(float: f32) -> i64 {
(float * 10000f32) as i64 (float * 10000f32) as i64
} }

View File

@ -1,7 +1,7 @@
/// Implements the BlockEntity trait for chest-like block entities. /// Implements the `BlockEntity` trait for chest-like block entities.
/// Parameters: /// Parameters:
/// - $struct_name: The type of the chest struct (e.g., ChestBlockEntity) /// - $`struct_name`: The type of the chest struct (e.g., `ChestBlockEntity`)
/// - $resource_id: The resource location string (e.g., "minecraft:chest") /// - $`resource_id`: The resource location string (e.g., "minecraft:chest")
#[macro_export] #[macro_export]
macro_rules! impl_block_entity_for_chest { macro_rules! impl_block_entity_for_chest {
($struct_name:ty) => { ($struct_name:ty) => {
@ -179,9 +179,10 @@ macro_rules! impl_clearable_for_chest {
}; };
} }
/// Implements the ViewerCountListener trait for chest-like block entities. /// Implements the `ViewerCountListener` trait for chest-like block entities.
/// The behavior is controlled by the EMITS_REDSTONE constant on the struct. ///
/// When EMITS_REDSTONE is true, updates neighbors for redstone signals when viewer count changes. /// The behavior is controlled by the `EMITS_REDSTONE` constant on the struct.
/// When `EMITS_REDSTONE` is true, updates neighbors for redstone signals when viewer count changes.
#[macro_export] #[macro_export]
macro_rules! impl_viewer_count_listener_for_chest { macro_rules! impl_viewer_count_listener_for_chest {
($struct_name:ty) => { ($struct_name:ty) => {
@ -243,8 +244,9 @@ macro_rules! impl_viewer_count_listener_for_chest {
} }
/// Implements helper methods for chest-like block entities. /// Implements helper methods for chest-like block entities.
/// Includes the play_sound method which handles sound positioning for single and double chests, ///
/// as well as new() and get_viewer_count() methods. /// Includes the `play_sound` method which handles sound positioning for single and double chests,
/// as well as `new()` and `get_viewer_count()` methods.
#[macro_export] #[macro_export]
macro_rules! impl_chest_helper_methods { macro_rules! impl_chest_helper_methods {
($struct_name:ty) => { ($struct_name:ty) => {

View File

@ -89,6 +89,7 @@ impl From<StagedChunkEnum> for ChunkStatus {
} }
impl StagedChunkEnum { impl StagedChunkEnum {
#[must_use]
pub const fn level_to_stage(level: i8) -> Self { pub const fn level_to_stage(level: i8) -> Self {
if level <= 43 { if level <= 43 {
Self::Full Self::Full
@ -108,6 +109,7 @@ impl StagedChunkEnum {
pub const FULL_DEPENDENCIES: &'static [Self] = pub const FULL_DEPENDENCIES: &'static [Self] =
&[Self::Full, Self::Lighting, Self::Features, Self::Surface]; &[Self::Full, Self::Lighting, Self::Features, Self::Surface];
pub const FULL_RADIUS: i32 = 3; pub const FULL_RADIUS: i32 = 3;
#[must_use]
pub const fn get_direct_radius(self) -> i32 { pub const fn get_direct_radius(self) -> i32 {
// self exclude // self exclude
match self { match self {
@ -123,6 +125,7 @@ impl StagedChunkEnum {
_ => panic!(), _ => panic!(),
} }
} }
#[must_use]
pub const fn get_write_radius(self) -> i32 { pub const fn get_write_radius(self) -> i32 {
// self exclude // self exclude
match self { match self {
@ -138,6 +141,7 @@ impl StagedChunkEnum {
_ => panic!(), _ => panic!(),
} }
} }
#[must_use]
pub const fn get_direct_dependencies(self) -> &'static [Self] { pub const fn get_direct_dependencies(self) -> &'static [Self] {
match self { match self {
// In vanilla StructureStart is first, but since it needs the biome in Vanilla it gets computed in StructureStart and // In vanilla StructureStart is first, but since it needs the biome in Vanilla it gets computed in StructureStart and
@ -161,6 +165,7 @@ pub enum Chunk {
} }
impl Chunk { impl Chunk {
#[must_use]
pub fn get_stage_id(&self) -> u8 { pub fn get_stage_id(&self) -> u8 {
match self { match self {
Self::Proto(data) => data.stage_id(), Self::Proto(data) => data.stage_id(),
@ -170,13 +175,14 @@ impl Chunk {
pub fn get_proto_chunk_mut(&mut self) -> &mut ProtoChunk { pub fn get_proto_chunk_mut(&mut self) -> &mut ProtoChunk {
match self { match self {
Self::Level(_) => panic!("chunk isn't a ProtoChunk"), Self::Level(_) => panic!("chunk isn't a ProtoChunk"),
Chunk::Proto(chunk) => chunk, Self::Proto(chunk) => chunk,
} }
} }
#[must_use]
pub fn get_proto_chunk(&self) -> &ProtoChunk { pub fn get_proto_chunk(&self) -> &ProtoChunk {
match self { match self {
Self::Level(_) => panic!("chunk isn't a ProtoChunk"), Self::Level(_) => panic!("chunk isn't a ProtoChunk"),
Chunk::Proto(chunk) => chunk, Self::Proto(chunk) => chunk,
} }
} }
pub fn upgrade_to_level_chunk( pub fn upgrade_to_level_chunk(
@ -188,7 +194,7 @@ impl Chunk {
// This allows us to move the light data instead of cloning it // This allows us to move the light data instead of cloning it
let proto_chunk_box = match std::mem::replace( let proto_chunk_box = match std::mem::replace(
self, self,
Chunk::Level(Arc::new(ChunkData { Self::Level(Arc::new(ChunkData {
section: ChunkSections::new(0, 0), section: ChunkSections::new(0, 0),
heightmap: Default::default(), heightmap: Default::default(),
x: 0, x: 0,
@ -202,8 +208,8 @@ impl Chunk {
dirty: AtomicBool::new(false), dirty: AtomicBool::new(false),
})), })),
) { ) {
Chunk::Proto(proto) => proto, Self::Proto(proto) => proto,
Chunk::Level(_) => panic!("Cannot upgrade a Level chunk"), Self::Level(_) => panic!("Cannot upgrade a Level chunk"),
}; };
let proto_chunk = *proto_chunk_box; let proto_chunk = *proto_chunk_box;

View File

@ -12,6 +12,7 @@ pub struct Node {
} }
impl Node { impl Node {
#[must_use]
pub fn new(pos: ChunkPos, stage: StagedChunkEnum) -> Self { pub fn new(pos: ChunkPos, stage: StagedChunkEnum) -> Self {
Self { Self {
pos, pos,
@ -30,6 +31,7 @@ pub struct Edge {
} }
impl Edge { impl Edge {
#[must_use]
pub const fn new(to: NodeKey, next: EdgeKey) -> Self { pub const fn new(to: NodeKey, next: EdgeKey) -> Self {
Self { to, next } Self { to, next }
} }

View File

@ -296,6 +296,7 @@ impl GenerationCache for Cache {
} }
impl Cache { impl Cache {
#[must_use]
pub fn new(x: i32, z: i32, size: i32) -> Self { pub fn new(x: i32, z: i32, size: i32) -> Self {
Self { Self {
x, x,

View File

@ -158,10 +158,10 @@ impl GenerationSchedule {
LightingEngineConfig::Full => { LightingEngineConfig::Full => {
let mut engine = chunk.light_engine.lock().unwrap(); let mut engine = chunk.light_engine.lock().unwrap();
for section in engine.block_light.iter_mut() { for section in &mut engine.block_light {
section.fill(15); section.fill(15);
} }
for section in engine.sky_light.iter_mut() { for section in &mut engine.sky_light {
section.fill(15); section.fill(15);
} }
@ -170,10 +170,10 @@ impl GenerationSchedule {
LightingEngineConfig::Dark => { LightingEngineConfig::Dark => {
let mut engine = chunk.light_engine.lock().unwrap(); let mut engine = chunk.light_engine.lock().unwrap();
for section in engine.block_light.iter_mut() { for section in &mut engine.block_light {
section.fill(0); section.fill(0);
} }
for section in engine.sky_light.iter_mut() { for section in &mut engine.sky_light {
section.fill(0); section.fill(0);
} }
@ -639,7 +639,18 @@ impl GenerationSchedule {
// Check if this is the first time becoming public // Check if this is the first time becoming public
let was_public = holder.public; let was_public = holder.public;
if !was_public { if was_public {
// Was already public but chunk has been regenerated (e.g., after relighting)
// Update the chunk data and re-notify players
self.apply_lighting_override(&chunk);
holder.chunk = Some(Chunk::Level(chunk.clone()));
self.public_chunk_map.insert(new_pos, chunk.clone());
info!(
"Notifying players: regenerated chunk at {:?} (was already public)",
new_pos
);
self.listener.process_new_chunk(new_pos, &chunk);
} else {
self.apply_lighting_override(&chunk); self.apply_lighting_override(&chunk);
// Clone once for public_chunk_map (needed for player access) // Clone once for public_chunk_map (needed for player access)
let public_chunk = chunk.clone(); let public_chunk = chunk.clone();
@ -665,17 +676,6 @@ impl GenerationSchedule {
new_pos new_pos
); );
} }
} else {
// Was already public but chunk has been regenerated (e.g., after relighting)
// Update the chunk data and re-notify players
self.apply_lighting_override(&chunk);
holder.chunk = Some(Chunk::Level(chunk.clone()));
self.public_chunk_map.insert(new_pos, chunk.clone());
info!(
"Notifying players: regenerated chunk at {:?} (was already public)",
new_pos
);
self.listener.process_new_chunk(new_pos, &chunk);
} }
} else { } else {
// Non-center chunk... just restore it to holder without cloning // Non-center chunk... just restore it to holder without cloning
@ -968,19 +968,16 @@ impl GenerationSchedule {
if self.queue.is_empty() { if self.queue.is_empty() {
// debug!("the queue is empty. thread sleep"); // debug!("the queue is empty. thread sleep");
while self.running_task_count > 0 && self.queue.is_empty() { while self.running_task_count > 0 && self.queue.is_empty() {
match self.recv_chunk.try_recv() { if let Ok((pos, data)) = self.recv_chunk.try_recv() {
Ok((pos, data)) => {
self.receive_chunk(pos, data); self.receive_chunk(pos, data);
self.resort_work(self.send_level.get()); self.resort_work(self.send_level.get());
} } else {
Err(_) => {
if level.shut_down_chunk_system.load(Relaxed) { if level.shut_down_chunk_system.load(Relaxed) {
break; break;
} }
thread::sleep(Duration::from_millis(50)); thread::sleep(Duration::from_millis(50));
} }
} }
}
if self.queue.is_empty() { if self.queue.is_empty() {
// debug!("no work to do. thread sleep"); // debug!("no work to do. thread sleep");
debug_assert!(self.debug_check()); debug_assert!(self.debug_check());
@ -996,12 +993,10 @@ impl GenerationSchedule {
let mut wait_iterations = 0; let mut wait_iterations = 0;
let max_wait_iterations = 100; // 5 seconds max wait let max_wait_iterations = 100; // 5 seconds max wait
while self.running_task_count > 0 && wait_iterations < max_wait_iterations { while self.running_task_count > 0 && wait_iterations < max_wait_iterations {
match self.recv_chunk.try_recv() { if let Ok((pos, data)) = self.recv_chunk.try_recv() {
Ok((pos, data)) => {
self.receive_chunk(pos, data); self.receive_chunk(pos, data);
wait_iterations = 0; // Reset counter when we receive data wait_iterations = 0; // Reset counter when we receive data
} } else {
Err(_) => {
wait_iterations += 1; wait_iterations += 1;
if wait_iterations % 20 == 0 { if wait_iterations % 20 == 0 {
warn!( warn!(
@ -1013,7 +1008,6 @@ impl GenerationSchedule {
thread::sleep(Duration::from_millis(50)); thread::sleep(Duration::from_millis(50));
} }
} }
}
if self.running_task_count > 0 { if self.running_task_count > 0 {
warn!( warn!(

View File

@ -234,12 +234,11 @@ pub fn generation_work(
let settings = GenerationSettings::from_dimension(&level.world_gen.dimension); let settings = GenerationSettings::from_dimension(&level.world_gen.dimension);
loop { loop {
let (pos, mut cache, stage) = match recv.recv() { let (pos, mut cache, stage) = if let Ok(data) = recv.recv() {
Ok(data) => data, data
Err(_) => { } else {
debug!("generation channel closed, exiting"); debug!("generation channel closed, exiting");
break; break;
}
}; };
// Run generation with panic catching // Run generation with panic catching
@ -267,7 +266,11 @@ pub fn generation_work(
let msg = payload let msg = payload
.downcast_ref::<&str>() .downcast_ref::<&str>()
.copied() .copied()
.or_else(|| payload.downcast_ref::<String>().map(|s| s.as_str())) .or_else(|| {
payload
.downcast_ref::<String>()
.map(std::string::String::as_str)
})
.unwrap_or("Unknown panic payload"); .unwrap_or("Unknown panic payload");
error!("Chunk generation FAILED at {pos:?} ({stage:?}): {msg}"); error!("Chunk generation FAILED at {pos:?} ({stage:?}): {msg}");

View File

@ -1,4 +1,4 @@
use pumpkin_util::math::{floor_mod, square, vector3::Vector3}; use pumpkin_util::math::{square_f64, vector3::Vector3};
use super::biome_coords; use super::biome_coords;
@ -110,7 +110,7 @@ pub fn get_biome_blend(
// This is effectively getting a random offset (+/- 0.0-0.8ish) to our biome position quarters and // This is effectively getting a random offset (+/- 0.0-0.8ish) to our biome position quarters and
// returning a hypotenuse squared of the parts + the offset // returning a hypotenuse squared of the parts + the offset
fn score_permutation( const fn score_permutation(
seed: i64, seed: i64,
x: i32, x: i32,
y: i32, y: i32,
@ -131,12 +131,15 @@ fn score_permutation(
let mix = salt_mix(mix, seed); let mix = salt_mix(mix, seed);
let offset_z = scale_mix(mix); let offset_z = scale_mix(mix);
square(z_part + offset_z) + square(y_part + offset_y) + square(x_part + offset_x) square_f64(z_part + offset_z) + square_f64(y_part + offset_y) + square_f64(x_part + offset_x)
} }
#[inline] #[inline]
fn scale_mix(l: i64) -> f64 { pub const fn scale_mix(l: i64) -> f64 {
let d = floor_mod(l >> 24, 1024i64) as i32 as f64 / 1024.0; // Shifting and then masking with 1023 (1024 - 1)
// This is mathematically identical to floor_mod(l >> 24, 1024)
// but executes in a single CPU cycle.
let d = ((l >> 24) & 1023) as f64 / 1024.0;
(d - 0.5) * 0.9 (d - 0.5) * 0.9
} }

View File

@ -19,7 +19,7 @@ struct NormalNoise(crate::generation::noise::perlin::DoublePerlinNoiseSampler);
impl NormalNoise { impl NormalNoise {
fn create(rand: &mut RandomGenerator, first_octave: i32, amplitudes: &[f64]) -> Self { fn create(rand: &mut RandomGenerator, first_octave: i32, amplitudes: &[f64]) -> Self {
NormalNoise( Self(
crate::generation::noise::perlin::DoublePerlinNoiseSampler::new( crate::generation::noise::perlin::DoublePerlinNoiseSampler::new(
rand, rand,
first_octave, first_octave,
@ -259,7 +259,7 @@ impl GeodeFeature {
} }
if matches!( if matches!(
dist_sum_shell.partial_cmp(&outer_crust), dist_sum_shell.partial_cmp(&outer_crust),
Some(Ordering::Greater) | Some(Ordering::Equal) Some(Ordering::Greater | Ordering::Equal)
) { ) {
if should_generate_crack if should_generate_crack
&& dist_sum_crack >= crack_size && dist_sum_crack >= crack_size

View File

@ -1,5 +1,6 @@
use pumpkin_data::BlockState; use pumpkin_data::BlockState;
use pumpkin_util::{math::square, random::RandomGenerator}; use pumpkin_util::math::square_f32;
use pumpkin_util::random::RandomGenerator;
use super::{FoliagePlacer, LeaveValidator}; use super::{FoliagePlacer, LeaveValidator};
use crate::generation::feature::features::tree::TreeNode; use crate::generation::feature::features::tree::TreeNode;
@ -51,6 +52,6 @@ impl LeaveValidator for LargeOakFoliagePlacer {
radius: i32, radius: i32,
_giant_trunk: bool, _giant_trunk: bool,
) -> bool { ) -> bool {
square(dx as f32 + 0.5) + square(dz as f32 + 0.5) > (radius * radius) as f32 square_f32(dx as f32 + 0.5) + square_f32(dz as f32 + 0.5) > (radius * radius) as f32
} }
} }

View File

@ -408,13 +408,13 @@ impl<'a> ChunkNoiseGenerator<'a> {
#[inline] #[inline]
#[must_use] #[must_use]
pub fn horizontal_cell_block_count(&self) -> u8 { pub const fn horizontal_cell_block_count(&self) -> u8 {
self.generation_shape.horizontal_cell_block_count() self.generation_shape.horizontal_cell_block_count()
} }
#[inline] #[inline]
#[must_use] #[must_use]
pub fn vertical_cell_block_count(&self) -> u8 { pub const fn vertical_cell_block_count(&self) -> u8 {
self.generation_shape.vertical_cell_block_count() self.generation_shape.vertical_cell_block_count()
} }

View File

@ -53,7 +53,7 @@ impl SplinePoint {
} }
} }
fn sample_outside_range(&self, sample_location: f32, last_known_sample: f32) -> f32 { const fn sample_outside_range(&self, sample_location: f32, last_known_sample: f32) -> f32 {
if self.derivative == 0f32 { if self.derivative == 0f32 {
last_known_sample last_known_sample
} else { } else {

View File

@ -6,6 +6,7 @@ pub struct BlockMatchRuleTest {
} }
impl BlockMatchRuleTest { impl BlockMatchRuleTest {
#[must_use]
pub fn test(&self, state: RawBlockState) -> bool { pub fn test(&self, state: RawBlockState) -> bool {
state.to_block().name == self.block.strip_prefix("minecraft:").unwrap_or(&self.block) state.to_block().name == self.block.strip_prefix("minecraft:").unwrap_or(&self.block)
} }

View File

@ -5,6 +5,7 @@ pub struct BlockStateMatchRuleTest {
} }
impl BlockStateMatchRuleTest { impl BlockStateMatchRuleTest {
#[must_use]
pub fn test(&self, state: RawBlockState) -> bool { pub fn test(&self, state: RawBlockState) -> bool {
state.0 == self.block_state.get_state_id() state.0 == self.block_state.get_state_id()
} }

View File

@ -7,6 +7,7 @@ pub struct TagMatchRuleTest {
} }
impl TagMatchRuleTest { impl TagMatchRuleTest {
#[must_use]
pub fn test(&self, state: RawBlockState) -> bool { pub fn test(&self, state: RawBlockState) -> bool {
let values = get_tag_ids(RegistryKey::Block, &self.tag).unwrap(); let values = get_tag_ids(RegistryKey::Block, &self.tag).unwrap();
values.contains(&state.to_block_id()) values.contains(&state.to_block_id())

View File

@ -45,11 +45,11 @@ const BASEMENT_DEPTH: i32 = 9;
const PIVOT_OFFSET_X: i32 = 3; const PIVOT_OFFSET_X: i32 = 3;
const PIVOT_OFFSET_Z: i32 = 5; const PIVOT_OFFSET_Z: i32 = 5;
/// Offset from dome to shaft entrance (vanilla: OFFSETS_FROM_TOP for middle). /// Offset from dome to shaft entrance (vanilla: `OFFSETS_FROM_TOP` for middle).
const SHAFT_OFFSET_X: i32 = 2; const SHAFT_OFFSET_X: i32 = 2;
const SHAFT_OFFSET_Z: i32 = 4; const SHAFT_OFFSET_Z: i32 = 4;
/// Offset from dome to basement (vanilla: OFFSETS_FROM_TOP for bottom). /// Offset from dome to basement (vanilla: `OFFSETS_FROM_TOP` for bottom).
const BASEMENT_OFFSET_X: i32 = 0; const BASEMENT_OFFSET_X: i32 = 0;
const BASEMENT_OFFSET_Z: i32 = -2; const BASEMENT_OFFSET_Z: i32 = -2;

View File

@ -41,8 +41,8 @@ const TEMPLATE_NAMES: [&str; 14] = [
]; ];
/// Vanilla height provider bounds for nether fossils. /// Vanilla height provider bounds for nether fossils.
/// From nether_fossil.json: uniform(absolute=32, below_top=2). /// From `nether_fossil.json`: uniform(absolute=32, `below_top=2`).
/// Vanilla BelowTop: height - 1 + min_y - offset = 256 - 1 + 0 - 2 = 253. /// Vanilla `BelowTop`: height - 1 + `min_y` - offset = 256 - 1 + 0 - 2 = 253.
const HEIGHT_MIN: i32 = 32; const HEIGHT_MIN: i32 = 32;
const HEIGHT_MAX: i32 = 253; const HEIGHT_MAX: i32 = 253;
@ -122,7 +122,7 @@ struct NetherFossilPiece {
} }
impl NetherFossilPiece { impl NetherFossilPiece {
/// Vanilla column scan: search downward from initial_y for air above (soul sand OR solid block). /// Vanilla column scan: search downward from `initial_y` for air above (soul sand OR solid block).
/// Returns the Y of the support block, or None if no valid position found above sea level. /// Returns the Y of the support block, or None if no valid position found above sea level.
/// ///
/// Mirrors vanilla's pre-decrement loop: /// Mirrors vanilla's pre-decrement loop:
@ -134,7 +134,7 @@ impl NetherFossilPiece {
/// } /// }
/// if (l <= k) return empty; /// if (l <= k) return empty;
/// ``` /// ```
/// After the loop, l is the support block Y. Vanilla rejects if l <= sea_level. /// After the loop, l is the support block Y. Vanilla rejects if l <= `sea_level`.
fn find_placement_y(&self, chunk: &ProtoChunk) -> Option<i32> { fn find_placement_y(&self, chunk: &ProtoChunk) -> Option<i32> {
let origin = self.shiftable_structure_piece.piece.bounding_box.min; let origin = self.shiftable_structure_piece.piece.bounding_box.min;
let mut y = self.initial_y; let mut y = self.initial_y;
@ -213,9 +213,9 @@ impl NetherFossilPiece {
use pumpkin_util::random::xoroshiro128::Xoroshiro; use pumpkin_util::random::xoroshiro128::Xoroshiro;
let bbox = self.shiftable_structure_piece.piece.bounding_box; let bbox = self.shiftable_structure_piece.piece.bounding_box;
let center_x = (bbox.min.x + bbox.max.x) / 2; let center_x = i32::midpoint(bbox.min.x, bbox.max.x);
let center_y = (bbox.min.y + bbox.max.y) / 2; let center_y = i32::midpoint(bbox.min.y, bbox.max.y);
let center_z = (bbox.min.z + bbox.max.z) / 2; let center_z = i32::midpoint(bbox.min.z, bbox.max.z);
// Vanilla: Random.create(world.getSeed()).nextSplitter().split(box.getCenter()) // Vanilla: Random.create(world.getSeed()).nextSplitter().split(box.getCenter())
let mut rng = RandomGenerator::Xoroshiro(Xoroshiro::from_seed(seed as u64)); let mut rng = RandomGenerator::Xoroshiro(Xoroshiro::from_seed(seed as u64));

View File

@ -33,12 +33,11 @@ impl BlockStateResolver {
// Find the block // Find the block
let block = Block::from_name(&entry.name).or_else(|| Block::from_registry_key(block_name)); let block = Block::from_name(&entry.name).or_else(|| Block::from_registry_key(block_name));
let block = match block { let block = if let Some(b) = block {
Some(b) => b, b
None => { } else {
warn!("Unknown block in template: {}", entry.name); warn!("Unknown block in template: {}", entry.name);
return None; return None;
}
}; };
// If no properties, return default state // If no properties, return default state
@ -108,7 +107,7 @@ impl BlockStateResolver {
} }
/// Converts a rotation value (0-15) to a static string. /// Converts a rotation value (0-15) to a static string.
fn rotation_to_str(rotation: i32) -> &'static str { const fn rotation_to_str(rotation: i32) -> &'static str {
match rotation % 16 { match rotation % 16 {
0 => "0", 0 => "0",
1 => "1", 1 => "1",

View File

@ -49,7 +49,7 @@ pub use template_piece::TemplatePiece;
/// - Block entities are created from template NBT data /// - Block entities are created from template NBT data
/// ///
/// `origin` is the base world position (x, y, z). /// `origin` is the base world position (x, y, z).
/// `offset` is the un-rotated XZ offset from origin (x_offset, z_offset) - rotation is applied automatically. /// `offset` is the un-rotated XZ offset from origin (`x_offset`, `z_offset`) - rotation is applied automatically.
pub fn place_template( pub fn place_template(
chunk: &mut ProtoChunk, chunk: &mut ProtoChunk,
template: &StructureTemplate, template: &StructureTemplate,

View File

@ -47,7 +47,7 @@ impl BlockRotation {
/// The position is rotated around the Y axis. The `size` parameter defines /// The position is rotated around the Y axis. The `size` parameter defines
/// the template dimensions, used to calculate the pivot point. /// the template dimensions, used to calculate the pivot point.
#[must_use] #[must_use]
pub fn transform_pos(&self, pos: Vector3<i32>, size: Vector3<i32>) -> Vector3<i32> { pub const fn transform_pos(&self, pos: Vector3<i32>, size: Vector3<i32>) -> Vector3<i32> {
match self { match self {
Self::None => pos, Self::None => pos,
Self::Clockwise90 => Vector3::new(size.z - 1 - pos.z, pos.y, pos.x), Self::Clockwise90 => Vector3::new(size.z - 1 - pos.z, pos.y, pos.x),
@ -61,7 +61,7 @@ impl BlockRotation {
/// Unlike `transform_pos` which rotates within template bounds, /// Unlike `transform_pos` which rotates within template bounds,
/// this rotates a simple offset (e.g. sub-template positioning). /// this rotates a simple offset (e.g. sub-template positioning).
#[must_use] #[must_use]
pub fn rotate_offset(self, x: i32, z: i32) -> (i32, i32) { pub const fn rotate_offset(self, x: i32, z: i32) -> (i32, i32) {
match self { match self {
Self::None => (x, z), Self::None => (x, z),
Self::Clockwise90 => (-z, x), Self::Clockwise90 => (-z, x),
@ -169,7 +169,7 @@ impl BlockRotation {
/// Converts rotation to a primary axis for bounding box creation. /// Converts rotation to a primary axis for bounding box creation.
#[must_use] #[must_use]
pub fn to_axis(self) -> pumpkin_util::math::vector3::Axis { pub const fn to_axis(self) -> pumpkin_util::math::vector3::Axis {
match self { match self {
Self::None | Self::Rotate180 => pumpkin_util::math::vector3::Axis::Z, Self::None | Self::Rotate180 => pumpkin_util::math::vector3::Axis::Z,
Self::Clockwise90 | Self::CounterClockwise90 => pumpkin_util::math::vector3::Axis::X, Self::Clockwise90 | Self::CounterClockwise90 => pumpkin_util::math::vector3::Axis::X,
@ -198,7 +198,7 @@ impl BlockMirror {
/// Transforms a position within the template bounds according to this mirror. /// Transforms a position within the template bounds according to this mirror.
#[must_use] #[must_use]
pub fn transform_pos(&self, pos: Vector3<i32>, size: Vector3<i32>) -> Vector3<i32> { pub const fn transform_pos(&self, pos: Vector3<i32>, size: Vector3<i32>) -> Vector3<i32> {
match self { match self {
Self::None => pos, Self::None => pos,
Self::LeftRight => Vector3::new(size.x - 1 - pos.x, pos.y, pos.z), Self::LeftRight => Vector3::new(size.x - 1 - pos.x, pos.y, pos.z),

View File

@ -50,7 +50,7 @@ pub struct StructureTemplate {
/// Each palette entry defines a block type with optional properties. /// Each palette entry defines a block type with optional properties.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct PaletteEntry { pub struct PaletteEntry {
/// The block name (e.g., "minecraft:stone_bricks"). /// The block name (e.g., "`minecraft:stone_bricks`").
pub name: String, pub name: String,
/// Block state properties (e.g., [("facing", "north"), ("lit", "false")]). /// Block state properties (e.g., [("facing", "north"), ("lit", "false")]).
@ -60,7 +60,7 @@ pub struct PaletteEntry {
impl PaletteEntry { impl PaletteEntry {
/// Creates a new palette entry with no properties. /// Creates a new palette entry with no properties.
#[must_use] #[must_use]
pub fn new(name: String) -> Self { pub const fn new(name: String) -> Self {
Self { Self {
name, name,
properties: Vec::new(), properties: Vec::new(),
@ -69,7 +69,7 @@ impl PaletteEntry {
/// Creates a new palette entry with the given properties. /// Creates a new palette entry with the given properties.
#[must_use] #[must_use]
pub fn with_properties(name: String, properties: Vec<(String, String)>) -> Self { pub const fn with_properties(name: String, properties: Vec<(String, String)>) -> Self {
Self { name, properties } Self { name, properties }
} }
} }
@ -334,7 +334,7 @@ impl StructureTemplate {
/// Returns the total number of blocks in this template. /// Returns the total number of blocks in this template.
#[must_use] #[must_use]
pub fn block_count(&self) -> usize { pub const fn block_count(&self) -> usize {
self.blocks.len() self.blocks.len()
} }
@ -346,7 +346,7 @@ impl StructureTemplate {
/// Returns whether this template has any entities. /// Returns whether this template has any entities.
#[must_use] #[must_use]
pub fn has_entities(&self) -> bool { pub const fn has_entities(&self) -> bool {
!self.entities.is_empty() !self.entities.is_empty()
} }
} }

View File

@ -131,13 +131,13 @@ impl TemplatePiece {
} }
// Resolve the block state with rotation/mirror // Resolve the block state with rotation/mirror
let state = match BlockStateResolver::resolve(palette_entry, self.rotation, self.mirror) let state = if let Some(s) =
BlockStateResolver::resolve(palette_entry, self.rotation, self.mirror)
{ {
Some(s) => s, s
None => { } else {
debug!("Failed to resolve block: {}", palette_entry.name); debug!("Failed to resolve block: {}", palette_entry.name);
continue; continue;
}
}; };
// Transform position to world coordinates // Transform position to world coordinates

View File

@ -295,7 +295,7 @@ impl Level {
info!("Joining {} threads for {}...", handle_count, world_id); info!("Joining {} threads for {}...", handle_count, world_id);
let join_task = tokio::task::spawn_blocking(move || { let join_task = tokio::task::spawn_blocking(move || {
let mut failed_count = 0; let mut failed_count = 0;
for handle in handles.into_iter() { for handle in handles {
if handle.join().is_err() { if handle.join().is_err() {
failed_count += 1; failed_count += 1;
} }

View File

@ -29,7 +29,7 @@ impl LightProvider for BlockLightProvider {
} }
#[inline(always)] #[inline(always)]
fn set_light(cache: &mut Cache, pos: BlockPos, level: u8) { fn set_light(cache: &mut Cache, pos: BlockPos, level: u8) {
set_block_light(cache, pos, level) set_block_light(cache, pos, level);
} }
#[inline(always)] #[inline(always)]
fn propagate_level(current_level: u8, opacity: u8, _dir: BlockDirection) -> u8 { fn propagate_level(current_level: u8, opacity: u8, _dir: BlockDirection) -> u8 {
@ -45,7 +45,7 @@ impl LightProvider for SkyLightProvider {
} }
#[inline(always)] #[inline(always)]
fn set_light(cache: &mut Cache, pos: BlockPos, level: u8) { fn set_light(cache: &mut Cache, pos: BlockPos, level: u8) {
set_sky_light(cache, pos, level) set_sky_light(cache, pos, level);
} }
#[inline(always)] #[inline(always)]
fn propagate_level(current_level: u8, opacity: u8, dir: BlockDirection) -> u8 { fn propagate_level(current_level: u8, opacity: u8, dir: BlockDirection) -> u8 {
@ -75,6 +75,7 @@ pub struct LightPropagator<P: LightProvider> {
} }
impl<P: LightProvider> LightPropagator<P> { impl<P: LightProvider> LightPropagator<P> {
#[must_use]
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
queue: VecDeque::with_capacity(4096), queue: VecDeque::with_capacity(4096),
@ -447,22 +448,15 @@ impl SkyLightPropagator {
if y <= top_y { if y <= top_y {
break; break;
} }
// Safe to break if we're under our own roof
else {
continue; continue;
} }
}
let is_at_surface = y == top_y; let is_at_surface = y == top_y;
let below_neighbor = let below_neighbor =
y < north_top || y < south_top || y < west_top || y < east_top; y < north_top || y < south_top || y < west_top || y < east_top;
if (is_at_surface || below_neighbor) && self.visited.insert(pos) { if (is_at_surface || below_neighbor) && self.visited.insert(pos) {
let skip_dir = if y >= top_y { let skip_dir = (y >= top_y).then_some(BlockDirection::Up);
Some(BlockDirection::Up)
} else {
None
};
self.queue.push_back(PropagationEntry { self.queue.push_back(PropagationEntry {
pos, pos,
@ -489,6 +483,7 @@ pub struct LightEngine {
} }
impl LightEngine { impl LightEngine {
#[must_use]
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
block_light: BlockLightPropagator::new(), block_light: BlockLightPropagator::new(),

View File

@ -15,7 +15,8 @@ pub struct DynamicLightEngine {
} }
impl DynamicLightEngine { impl DynamicLightEngine {
pub fn new() -> Self { #[must_use]
pub const fn new() -> Self {
Self { Self {
decrease_block_light_queue: SegQueue::new(), decrease_block_light_queue: SegQueue::new(),
increase_block_light_queue: SegQueue::new(), increase_block_light_queue: SegQueue::new(),
@ -395,7 +396,7 @@ impl DynamicLightEngine {
if has_sky { if has_sky {
// Direct sunlight, reduced by opacity // Direct sunlight, reduced by opacity
15_u8.saturating_sub(opacity) 15u8.saturating_sub(opacity)
} else { } else {
// No direct sky, check neighbors for best light // No direct sky, check neighbors for best light
let mut best_light = 0; let mut best_light = 0;

View File

@ -4,7 +4,7 @@ use crate::generation::height_limit::HeightLimitView;
use pumpkin_util::math::position::BlockPos; use pumpkin_util::math::position::BlockPos;
#[inline(always)] #[inline(always)]
fn get_chunk_index(cache: &Cache, chunk_x: i32, chunk_z: i32) -> Option<usize> { const fn get_chunk_index(cache: &Cache, chunk_x: i32, chunk_z: i32) -> Option<usize> {
let rel_x = chunk_x - cache.x; let rel_x = chunk_x - cache.x;
let rel_z = chunk_z - cache.z; let rel_z = chunk_z - cache.z;
if rel_x < 0 || rel_x >= cache.size || rel_z < 0 || rel_z >= cache.size { if rel_x < 0 || rel_x >= cache.size || rel_z < 0 || rel_z >= cache.size {
@ -24,6 +24,7 @@ fn get_section_y(cache: &Cache, pos_y: i32) -> Option<usize> {
} }
#[inline(always)] #[inline(always)]
#[must_use]
pub fn get_block_light(cache: &Cache, pos: BlockPos) -> u8 { pub fn get_block_light(cache: &Cache, pos: BlockPos) -> u8 {
let chunk_x = pos.0.x >> 4; let chunk_x = pos.0.x >> 4;
let chunk_z = pos.0.z >> 4; let chunk_z = pos.0.z >> 4;
@ -90,6 +91,7 @@ pub fn set_block_light(cache: &mut Cache, pos: BlockPos, level: u8) {
} }
#[inline(always)] #[inline(always)]
#[must_use]
pub fn get_sky_light(cache: &Cache, pos: BlockPos) -> u8 { pub fn get_sky_light(cache: &Cache, pos: BlockPos) -> u8 {
let chunk_x = pos.0.x >> 4; let chunk_x = pos.0.x >> 4;
let chunk_z = pos.0.z >> 4; let chunk_z = pos.0.z >> 4;

View File

@ -235,8 +235,7 @@ impl PoiRegion {
let timestamp = std::time::SystemTime::now() let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH) .duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as u32) .map_or(0, |d| d.as_secs() as u32);
.unwrap_or(0);
// Start after header (2 sectors) // Start after header (2 sectors)
let mut current_sector: u32 = 2; let mut current_sector: u32 = 2;

View File

@ -91,19 +91,19 @@ const DEFAULT_DIFFICULTY: Difficulty = Difficulty::Normal;
const DEFAULT_LEVEL_NAME: &str = "world"; const DEFAULT_LEVEL_NAME: &str = "world";
const DEFAULT_SPAWN_Y: i32 = 200; const DEFAULT_SPAWN_Y: i32 = 200;
fn default_border_damage_per_block() -> f64 { const fn default_border_damage_per_block() -> f64 {
DEFAULT_BORDER_DAMAGE_PER_BLOCK DEFAULT_BORDER_DAMAGE_PER_BLOCK
} }
fn default_border_size() -> f64 { const fn default_border_size() -> f64 {
DEFAULT_BORDER_SIZE DEFAULT_BORDER_SIZE
} }
fn default_border_safe_zone() -> f64 { const fn default_border_safe_zone() -> f64 {
DEFAULT_BORDER_SAFE_ZONE DEFAULT_BORDER_SAFE_ZONE
} }
fn default_border_warning_blocks() -> f64 { const fn default_border_warning_blocks() -> f64 {
DEFAULT_BORDER_WARNING_BLOCKS DEFAULT_BORDER_WARNING_BLOCKS
} }
fn default_border_warning_time() -> f64 { const fn default_border_warning_time() -> f64 {
DEFAULT_BORDER_WARNING_TIME DEFAULT_BORDER_WARNING_TIME
} }
fn default_data_packs() -> DataPacks { fn default_data_packs() -> DataPacks {
@ -112,16 +112,16 @@ fn default_data_packs() -> DataPacks {
enabled: vec!["vanilla".to_string()], enabled: vec!["vanilla".to_string()],
} }
} }
fn default_difficulty() -> Difficulty { const fn default_difficulty() -> Difficulty {
DEFAULT_DIFFICULTY DEFAULT_DIFFICULTY
} }
fn default_level_name() -> String { fn default_level_name() -> String {
DEFAULT_LEVEL_NAME.to_string() DEFAULT_LEVEL_NAME.to_string()
} }
fn default_spawn_y() -> i32 { const fn default_spawn_y() -> i32 {
DEFAULT_SPAWN_Y DEFAULT_SPAWN_Y
} }
fn default_level_version() -> i32 { const fn default_level_version() -> i32 {
MAXIMUM_SUPPORTED_LEVEL_VERSION MAXIMUM_SUPPORTED_LEVEL_VERSION
} }

View File

@ -556,7 +556,6 @@ impl ActivatorRailBlock {
pos: &BlockPos, pos: &BlockPos,
) -> Option<(&'static Block, RailProperties)> { ) -> Option<(&'static Block, RailProperties)> {
let block = world.get_block(pos).await; let block = world.get_block(pos).await;
#[expect(clippy::if_then_some_else_none)]
if *block == Block::ACTIVATOR_RAIL { if *block == Block::ACTIVATOR_RAIL {
let state_id = world.get_block_state_id(pos).await; let state_id = world.get_block_state_id(pos).await;
let rail_props = RailProperties::new(state_id, block); let rail_props = RailProperties::new(state_id, block);

View File

@ -557,7 +557,6 @@ impl PoweredRailBlock {
pos: &BlockPos, pos: &BlockPos,
) -> Option<(&'static Block, RailProperties)> { ) -> Option<(&'static Block, RailProperties)> {
let block = world.get_block(pos).await; let block = world.get_block(pos).await;
#[expect(clippy::if_then_some_else_none)]
if *block == Block::POWERED_RAIL { if *block == Block::POWERED_RAIL {
let state_id = world.get_block_state_id(pos).await; let state_id = world.get_block_state_id(pos).await;
let rail_props = RailProperties::new(state_id, block); let rail_props = RailProperties::new(state_id, block);

View File

@ -103,7 +103,7 @@ impl CommandExecutor for Executor {
vec![TextComponent::text(version_string.clone())], vec![TextComponent::text(version_string.clone())],
) )
.hover_event(HoverEvent::show_text( .hover_event(HoverEvent::show_text(
TextComponent::text(format!("Commit: {GIT_HASH_FULL}\n\nContributors:\n",)) TextComponent::text(format!("Commit: {GIT_HASH_FULL}\n\nContributors:\n"))
.add_child( .add_child(
TextComponent::text(contributor_names) TextComponent::text(contributor_names)
.gradient_named(&[NamedColor::DarkGreen, NamedColor::Green]) .gradient_named(&[NamedColor::DarkGreen, NamedColor::Green])

View File

@ -165,42 +165,30 @@ impl CommandDispatcher {
continue; continue;
} }
match c { match c {
'{' => { '{' if !in_single_quotes && !in_double_quotes => {
if !in_single_quotes && !in_double_quotes {
in_braces += 1; in_braces += 1;
} }
} '}' if !in_single_quotes && !in_double_quotes => {
'}' => {
if !in_single_quotes && !in_double_quotes {
if in_braces == 0 { if in_braces == 0 {
return Err(CommandFailed(TextComponent::text("Unmatched braces"))); return Err(CommandFailed(TextComponent::text("Unmatched braces")));
} }
in_braces -= 1; in_braces -= 1;
} }
} '[' if !in_single_quotes && !in_double_quotes => {
'[' => {
if !in_single_quotes && !in_double_quotes {
in_brackets += 1; in_brackets += 1;
} }
} ']' if !in_single_quotes && !in_double_quotes => {
']' => {
if !in_single_quotes && !in_double_quotes {
if in_brackets == 0 { if in_brackets == 0 {
return Err(CommandFailed(TextComponent::text("Unmatched brackets"))); return Err(CommandFailed(TextComponent::text("Unmatched brackets")));
} }
in_brackets -= 1; in_brackets -= 1;
} }
} '\'' if !in_double_quotes => {
'\'' => {
if !in_double_quotes {
in_single_quotes = !in_single_quotes; in_single_quotes = !in_single_quotes;
} }
} '"' if !in_single_quotes => {
'"' => {
if !in_single_quotes {
in_double_quotes = !in_double_quotes; in_double_quotes = !in_double_quotes;
} }
}
' ' if !in_single_quotes ' ' if !in_single_quotes
&& !in_double_quotes && !in_double_quotes
&& in_braces == 0 && in_braces == 0

View File

@ -108,7 +108,7 @@ impl MobData {
} }
#[must_use] #[must_use]
pub fn block_position(&self) -> (i32, i32, i32) { pub const fn block_position(&self) -> (i32, i32, i32) {
( (
self.position.x.floor() as i32, self.position.x.floor() as i32,
self.position.y.floor() as i32, self.position.y.floor() as i32,

View File

@ -2440,11 +2440,11 @@ impl Entity {
return; return;
} }
} }
v if v == EntityType::SPIDER.id || v == EntityType::CAVE_SPIDER.id => { v if (v == EntityType::SPIDER.id || v == EntityType::CAVE_SPIDER.id)
if Block::from_state_id(state.id).id == Block::COBWEB.id { && Block::from_state_id(state.id).id == Block::COBWEB.id =>
{
return; return;
} }
}
v if v == EntityType::WITHER.id => { v if v == EntityType::WITHER.id => {
return; return;
} }

View File

@ -309,7 +309,7 @@ impl ChunkManager {
self.last_chunk_batch_sent_at = Instant::now(); self.last_chunk_batch_sent_at = Instant::now();
} }
pub fn handle_acknowledge(&mut self, chunks_per_tick: f32) { pub const fn handle_acknowledge(&mut self, chunks_per_tick: f32) {
self.batches_sent_since_ack = BatchState::Count(0); self.batches_sent_since_ack = BatchState::Count(0);
self.chunks_per_tick = chunks_per_tick.ceil() as usize; self.chunks_per_tick = chunks_per_tick.ceil() as usize;
} }

View File

@ -16,8 +16,6 @@ use crate::{
}; };
const EXPLOSION_POWER: f32 = 1.2; const EXPLOSION_POWER: f32 = 1.2;
// square(3.5)
const MAX_RENDER_DISTANCE_WHEN_NEWLY_SPAWNED: f32 = 3.5 * 3.5;
const DEFAULT_DEFLECT_COOLDOWN: u8 = 5; const DEFAULT_DEFLECT_COOLDOWN: u8 = 5;
pub struct WindChargeEntity { pub struct WindChargeEntity {
@ -50,28 +48,6 @@ impl WindChargeEntity {
.await; .await;
} }
pub fn should_render(&self, distance: f64) -> bool {
if self.get_entity().age.load(Ordering::Relaxed) < 2
&& distance < f64::from(MAX_RENDER_DISTANCE_WHEN_NEWLY_SPAWNED)
{
return false;
}
let mut average_side_length = self
.get_entity()
.bounding_box
.load()
.get_average_side_length();
if average_side_length.is_nan() {
average_side_length = 1.0;
}
// TODO: IMPLEMENT renderDistanceMultiplier instead of the 1.0
average_side_length *= 64.0 * 1.0;
distance < average_side_length * average_side_length
}
pub fn deflect( pub fn deflect(
&mut self, &mut self,
deflection: &ProjectileDeflectionType, deflection: &ProjectileDeflectionType,

View File

@ -191,7 +191,6 @@ impl PumpkinServer {
pub fn log_info(&self, message: &str) { pub fn log_info(&self, message: &str) {
tracing::info!(target: "plugin", "{}", message); tracing::info!(target: "plugin", "{}", message);
} }
#[expect(clippy::if_then_some_else_none)]
pub async fn new( pub async fn new(
basic_config: BasicConfiguration, basic_config: BasicConfiguration,
advanced_config: AdvancedConfiguration, advanced_config: AdvancedConfiguration,

View File

@ -420,7 +420,6 @@ impl Server {
PlayerLoginEvent::new(player.clone(), TextComponent::text("You have been kicked from the server")); PlayerLoginEvent::new(player.clone(), TextComponent::text("You have been kicked from the server"));
'after: { 'after: {
player.screen_handler_sync_handler.store_player(player.clone()).await; player.screen_handler_sync_handler.store_player(player.clone()).await;
#[expect(clippy::if_then_some_else_none)]
if world if world
.add_player(player.clone()) .add_player(player.clone())
.is_ok() { .is_ok() {