Skip to content

Commit c1dbf6d

Browse files
authored
docs: pumpkin-util (#1719)
* init Signed-off-by: illyrius666 <28700752+illyrius666@users.noreply.github.com> * part 1 Signed-off-by: illyrius666 <28700752+illyrius666@users.noreply.github.com> * finished math section Signed-off-by: illyrius666 <28700752+illyrius666@users.noreply.github.com> * fmt Signed-off-by: illyrius666 <28700752+illyrius666@users.noreply.github.com> * finished text and some initial work on other unfinished folders Signed-off-by: illyrius666 <28700752+illyrius666@users.noreply.github.com> * fmt Signed-off-by: illyrius666 <28700752+illyrius666@users.noreply.github.com> * fmt Signed-off-by: illyrius666 <28700752+illyrius666@users.noreply.github.com> * finish noise Signed-off-by: illyrius666 <28700752+illyrius666@users.noreply.github.com> * finish random Signed-off-by: illyrius666 <28700752+illyrius666@users.noreply.github.com> --------- Signed-off-by: illyrius666 <28700752+illyrius666@users.noreply.github.com> Signed-off-by: Illyrius <28700752+illyrius666@users.noreply.github.com>
1 parent fadccf9 commit c1dbf6d

39 files changed

+2846
-220
lines changed

pumpkin-util/Cargo.toml

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,7 @@ proc-macro2.workspace = true
2121
enum_dispatch.workspace = true
2222

2323
uuid.workspace = true
24-
tokio = { workspace = true, features = [
25-
"sync",
26-
] }
24+
tokio = { workspace = true, features = ["sync"] }
2725
base64.workspace = true
2826
p384 = { workspace = true, features = ["ecdsa"] }
2927
thiserror.workspace = true

pumpkin-util/src/biome.rs

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,29 +4,44 @@ use serde::Deserialize;
44

55
use crate::{noise::simplex::OctaveSimplexNoiseSampler, random::legacy_rand::LegacyRand};
66

7+
/// Global noise sampler for biome temperature variation.
78
pub static TEMPERATURE_NOISE: LazyLock<OctaveSimplexNoiseSampler> = LazyLock::new(|| {
89
let mut rand = LegacyRand::from_seed(1234);
910
OctaveSimplexNoiseSampler::new(&mut rand, &[0])
1011
});
1112

13+
/// Global noise sampler for frozen ocean biome adjustments.
1214
pub static FROZEN_OCEAN_NOISE: LazyLock<OctaveSimplexNoiseSampler> = LazyLock::new(|| {
1315
let mut rand = LegacyRand::from_seed(3456);
1416
OctaveSimplexNoiseSampler::new(&mut rand, &[-2, -1, 0])
1517
});
1618

19+
/// Global noise sampler for foliage-based temperature adjustments.
1720
pub static FOLIAGE_NOISE: LazyLock<OctaveSimplexNoiseSampler> = LazyLock::new(|| {
1821
let mut rand = LegacyRand::from_seed(2345);
1922
OctaveSimplexNoiseSampler::new(&mut rand, &[0])
2023
});
2124

25+
/// Modifiers that adjust the base biome temperature.
2226
#[derive(Clone, Deserialize, Copy, Hash, PartialEq, Eq, Debug)]
2327
#[serde(rename_all = "UPPERCASE")]
2428
pub enum TemperatureModifier {
29+
/// No temperature modification.
2530
None,
31+
/// Frozen biome adjustment, typically used for frozen oceans and snowy areas.
2632
Frozen,
2733
}
2834

2935
impl TemperatureModifier {
36+
/// Applies the temperature modifier to a given position and base temperature.
37+
///
38+
/// # Parameters
39+
/// - `x`: X coordinate in the world.
40+
/// - `z`: Z coordinate in the world.
41+
/// - `temperature`: The base biome temperature.
42+
///
43+
/// # Returns
44+
/// - The modified temperature as an `f32`.
3045
pub fn convert_temperature(&self, x: f64, z: f64, temperature: f32) -> f32 {
3146
match self {
3247
Self::None => temperature,
@@ -49,17 +64,28 @@ impl TemperatureModifier {
4964
}
5065
}
5166

67+
/// Represents weather information for a biome, including temperature and precipitation.
5268
#[derive(Clone, Debug)]
5369
pub struct Weather {
5470
#[expect(dead_code)]
5571
has_precipitation: bool,
72+
/// Base temperature of the biome.
5673
temperature: f32,
74+
/// Modifier affecting the base temperature.
5775
temperature_modifier: TemperatureModifier,
76+
/// Rate of rainfall or snowfall in the biome.
5877
#[expect(dead_code)]
5978
downfall: f32,
6079
}
6180

6281
impl Weather {
82+
/// Creates a new `Weather` instance.
83+
///
84+
/// # Parameters
85+
/// - `has_precipitation`: Whether the biome has precipitation.
86+
/// - `temperature`: Base temperature of the biome.
87+
/// - `temperature_modifier`: Modifier affecting the temperature.
88+
/// - `downfall`: Amount of rainfall or snowfall.
6389
#[must_use]
6490
pub const fn new(
6591
has_precipitation: bool,
@@ -75,7 +101,19 @@ impl Weather {
75101
}
76102
}
77103

78-
/// This is an expensive function and should be cached
104+
/// Computes the effective temperature at a given position.
105+
///
106+
/// # Parameters
107+
/// - `x`, `z`: World coordinates.
108+
/// - `y`: Y-level of the position.
109+
/// - `sea_level`: Sea level in the world.
110+
///
111+
/// # Returns
112+
/// - The temperature at the position as `f32`.
113+
///
114+
/// # Notes
115+
/// - This function is computationally expensive and should be cached.
116+
/// - Temperature is influenced by `TemperatureModifier` and noise samplers.
79117
pub fn compute_temperature(&self, x: f64, y: i32, z: f64, sea_level: i32) -> f32 {
80118
let modified_temperature =
81119
self.temperature_modifier

pumpkin-util/src/difficulty.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,25 @@ use std::str::FromStr;
33
use num_derive::{FromPrimitive, ToPrimitive};
44
use serde::{Deserialize, Serialize};
55

6+
/// Error returned when parsing a [`Difficulty`] from a string fails.
67
pub struct ParseDifficultyError;
78

9+
/// Represents the difficulty level of the game.
10+
///
11+
/// Each numeric value corresponds to a specific difficulty:
12+
/// - `Peaceful` (0): No hostile mobs spawn, health regenerates naturally.
13+
/// - `Easy` (1): Standard gameplay, hostile mobs spawn with reduced damage.
14+
/// - `Normal` (2): Standard difficulty with full damage from mobs.
15+
/// - `Hard` (3): Hostile mobs deal extra damage and health regeneration is limited.
816
#[derive(Serialize, Deserialize, FromPrimitive, ToPrimitive, PartialEq, Eq, Clone, Copy, Debug)]
917
pub enum Difficulty {
18+
/// No hostile mobs; natural health regeneration.
1019
Peaceful = 0,
20+
/// Easy difficulty; hostile mobs deal reduced damage.
1121
Easy = 1,
22+
/// Normal difficulty; standard mob damage and health.
1223
Normal = 2,
24+
/// Hard difficulty; increased mob damage and limited health regen.
1325
Hard = 3,
1426
}
1527

pumpkin-util/src/gamemode.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,25 @@
11
use serde::{Deserialize, Serialize};
22
use std::str::FromStr;
33

4+
/// Error returned when parsing a string into a [`GameMode`] fails.
45
#[derive(Debug, PartialEq, Eq)]
56
pub struct ParseGameModeError;
67

8+
/// Represents the various game modes a player can be in.
79
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
810
pub enum GameMode {
11+
/// Standard survival mode: players take damage, gather resources, and interact normally.
912
Survival = 0,
13+
/// Creative mode: players have unlimited resources, can fly, and cannot take damage.
1014
Creative = 1,
15+
/// Adventure mode: players cannot break blocks without the proper tools.
1116
Adventure = 2,
17+
/// Spectator mode: players can fly through blocks and observe without interacting.
1218
Spectator = 3,
1319
}
1420

1521
impl GameMode {
22+
/// Returns the display string for this game mode.
1623
#[must_use]
1724
pub const fn to_str(&self) -> &'static str {
1825
match self {
@@ -27,6 +34,18 @@ impl GameMode {
2734
impl TryFrom<i8> for GameMode {
2835
type Error = ();
2936

37+
/// Attempts to convert an `i8` value into a [`GameMode`].
38+
///
39+
/// # Parameters
40+
/// - `value`: The numeric representation of a game mode.
41+
///
42+
/// # Returns
43+
/// - `Ok(GameMode)` if the value corresponds to a valid game mode:
44+
/// - `0` → `Survival`
45+
/// - `1` → `Creative`
46+
/// - `2` → `Adventure`
47+
/// - `3` → `Spectator`
48+
/// - `Err(())` if the value does not correspond to any valid game mode.
3049
fn try_from(value: i8) -> Result<Self, Self::Error> {
3150
match value {
3251
0 => Ok(Self::Survival),

pumpkin-util/src/lib.rs

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,17 +28,25 @@ pub mod y_offset;
2828

2929
pub mod jwt;
3030

31+
/// Represents the different types of height maps used for terrain generation and collision checks.
3132
#[derive(Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
3233
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
3334
pub enum HeightMap {
35+
/// Topmost block including plants, snow layers, and surface features (used during world generation).
3436
WorldSurfaceWg,
37+
/// Topmost solid or liquid block counting as surface.
3538
WorldSurface,
39+
/// Lowest solid block in oceans including underwater terrain features (used during world generation).
3640
OceanFloorWg,
41+
/// Lowest solid block in oceans, ignoring non-solid features like kelp.
3742
OceanFloor,
43+
/// Topmost block that blocks entity motion (ignores leaves).
3844
MotionBlocking,
45+
/// Topmost block that blocks entity motion, ignoring leaf blocks.
3946
MotionBlockingNoLeaves,
4047
}
4148

49+
/// Constructs a global file system path relative to the project root.
4250
#[macro_export]
4351
macro_rules! global_path {
4452
($path:expr) => {{
@@ -53,7 +61,7 @@ macro_rules! global_path {
5361
}};
5462
}
5563

56-
/// Reads JSON files from disk. Don't use this for static files!
64+
/// Reads JSON files from the disk. Don't use this for static files!
5765
#[macro_export]
5866
macro_rules! read_data_from_file {
5967
($path:expr) => {{
@@ -86,24 +94,35 @@ pub fn encompassing_bits(count: usize) -> u8 {
8694
}
8795
}
8896

97+
/// Represents actions applied to a player profile that may require moderation or restrictions.
8998
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
9099
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
91100
pub enum ProfileAction {
101+
/// The player's name was forcibly changed by the server or an administrator.
92102
ForcedNameChange,
103+
/// The player attempted to use a skin that is banned or not allowed on the server.
93104
UsingBannedSkin,
94105
}
95106

107+
/// Represents the six possible block-facing directions in a 3D world.
96108
#[derive(Clone, Copy, PartialEq, Eq)]
97109
pub enum BlockDirection {
110+
/// Points downward along the Y axis; often used for blocks attached to the ceiling.
98111
Down = 0,
112+
/// Points upward along the Y axis; commonly used for blocks resting on the ground.
99113
Up,
114+
/// Points toward the negative Z axis; typically toward the front of a structure.
100115
North,
116+
/// Points toward the positive Z axis; typically toward the back of a structure.
101117
South,
118+
/// Points toward the negative X axis; commonly used for left-facing orientation.
102119
West,
120+
/// Points toward the positive X axis; commonly used for right-facing orientation.
103121
East,
104122
}
105123

106124
impl BlockDirection {
125+
/// Returns the principal axis (`X`, `Y`, or `Z`) associated with this direction.
107126
#[must_use]
108127
pub const fn get_axis(&self) -> Axis {
109128
match self {
@@ -114,14 +133,21 @@ impl BlockDirection {
114133
}
115134
}
116135

117-
/// Takes a mutable reference of an index and returns a mutable "slice" where we can mutate both at
118-
/// the same time
136+
/// A mutable slice split into three parts: the element at the split index, the start, and the end.
137+
///
138+
/// This allows modifying the selected element while still having access to the surrounding slices.
119139
pub struct MutableSplitSlice<'a, T> {
140+
/// Elements before the split index.
120141
start: &'a mut [T],
142+
/// Elements after the split index.
121143
end: &'a mut [T],
122144
}
123145

124146
impl<'a, T> MutableSplitSlice<'a, T> {
147+
/// Extracts the `index`-th element as a mutable reference along with a `MutableSplitSlice` representing the remaining elements.
148+
///
149+
/// # Panics
150+
/// * if `index` is out of bounds of the base slice.
125151
pub const fn extract_ith(base: &'a mut [T], index: usize) -> (&'a mut T, Self) {
126152
let (start, end_inclusive) = base.split_at_mut(index);
127153
let (value, end) = end_inclusive
@@ -131,11 +157,13 @@ impl<'a, T> MutableSplitSlice<'a, T> {
131157
(value, Self { start, end })
132158
}
133159

160+
/// Returns the total number of elements in the split slice (start + removed element + end).
134161
#[must_use]
135162
pub const fn len(&self) -> usize {
136163
self.start.len() + self.end.len() + 1
137164
}
138165

166+
/// Returns `false` since the split slice always contains at least the removed element.
139167
#[must_use]
140168
pub const fn is_empty(&self) -> bool {
141169
false
@@ -157,10 +185,13 @@ impl<T> Index<usize> for MutableSplitSlice<'_, T> {
157185
}
158186
}
159187

188+
/// Codec for deserializing parameters of a double Perlin noise sampler.
160189
#[derive(Deserialize, Clone)]
161190
pub struct DoublePerlinNoiseParametersCodec {
191+
/// The first octave index (can be negative for lower frequencies).
162192
#[serde(rename = "firstOctave")]
163193
pub first_octave: i32,
194+
/// Amplitude values for each octave, determining the weight of each frequency layer.
164195
pub amplitudes: Vec<f64>,
165196
}
166197

@@ -193,11 +224,20 @@ impl Hand {
193224
}
194225
}
195226

227+
/// Error type for invalid hand conversion.
196228
pub struct InvalidHand;
197229

198230
impl TryFrom<i32> for Hand {
199231
type Error = InvalidHand;
200232

233+
/// Converts an integer into a `Hand`.
234+
///
235+
/// # Parameters
236+
/// - `0`: `Left`
237+
/// - `1`: `Right`
238+
///
239+
/// # Errors
240+
/// Returns `InvalidHand` if the value is not 0 or 1.
201241
fn try_from(value: i32) -> Result<Self, Self::Error> {
202242
match value {
203243
0 => Ok(Self::Left),

0 commit comments

Comments
 (0)