Add VSCode section headers to make navigating large files easier.

This commit is contained in:
IntegratedQuantum 2024-07-14 11:31:57 +02:00
parent 45cc9a9419
commit 289e3c61f1
26 changed files with 156 additions and 141 deletions

View File

@ -167,7 +167,7 @@ fn registerRecipesFromFile(file: []const u8) void {
items_zig.registerRecipes(file); items_zig.registerRecipes(file);
} }
pub const Palette = struct { pub const Palette = struct { // MARK: Palette
palette: main.List([]const u8), palette: main.List([]const u8),
pub fn init(allocator: NeverFailingAllocator, json: JsonElement, firstElement: ?[]const u8) !*Palette { pub fn init(allocator: NeverFailingAllocator, json: JsonElement, firstElement: ?[]const u8) !*Palette {
const self = allocator.create(Palette); const self = allocator.create(Palette);
@ -221,7 +221,7 @@ pub const Palette = struct {
var loadedAssets: bool = false; var loadedAssets: bool = false;
pub fn loadWorldAssets(assetFolder: []const u8, blockPalette: *Palette, biomePalette: *Palette) !void { pub fn loadWorldAssets(assetFolder: []const u8, blockPalette: *Palette, biomePalette: *Palette) !void { // MARK: loadWorldAssets()
if(loadedAssets) return; // The assets already got loaded by the server. if(loadedAssets) return; // The assets already got loaded by the server.
loadedAssets = true; loadedAssets = true;
var blocks = commonBlocks.cloneWithAllocator(main.stackAllocator.allocator) catch unreachable; var blocks = commonBlocks.cloneWithAllocator(main.stackAllocator.allocator) catch unreachable;
@ -312,7 +312,7 @@ pub fn loadWorldAssets(assetFolder: []const u8, blockPalette: *Palette, biomePal
} }
} }
pub fn unloadAssets() void { pub fn unloadAssets() void { // MARK: unloadAssets()
if(!loadedAssets) return; if(!loadedAssets) return;
loadedAssets = false; loadedAssets = false;
blocks_zig.reset(); blocks_zig.reset();

View File

@ -225,7 +225,7 @@ pub fn hasRegistered(id: []const u8) bool {
return reverseIndices.contains(id); return reverseIndices.contains(id);
} }
pub const Block = packed struct { pub const Block = packed struct { // MARK: Block
typ: u16, typ: u16,
data: u16, data: u16,
pub fn toInt(self: Block) u32 { pub fn toInt(self: Block) u32 {
@ -315,7 +315,7 @@ pub const Block = packed struct {
}; };
pub const meshes = struct { pub const meshes = struct { // MARK: meshes
const AnimationData = extern struct { const AnimationData = extern struct {
frames: i32, frames: i32,
time: i32, time: i32,

View File

@ -16,7 +16,7 @@ pub const chunkVolume: u31 = 1 << 3*chunkShift;
pub const chunkMask: i32 = chunkSize - 1; pub const chunkMask: i32 = chunkSize - 1;
/// Contains a bunch of constants used to describe neighboring blocks. /// Contains a bunch of constants used to describe neighboring blocks.
pub const Neighbors = struct { // TODO: Should this be an enum? pub const Neighbors = struct { // TODO: Should this be an enum? // MARK: Neighbors
/// How many neighbors there are. /// How many neighbors there are.
pub const neighbors: u3 = 6; pub const neighbors: u3 = 6;
/// Directions Index /// Directions Index
@ -113,7 +113,7 @@ pub fn deinit() void {
serverPool.deinit(); serverPool.deinit();
} }
pub const ChunkPosition = struct { pub const ChunkPosition = struct { // MARK: ChunkPosition
wx: i32, wx: i32,
wy: i32, wy: i32,
wz: i32, wz: i32,
@ -175,7 +175,7 @@ pub const ChunkPosition = struct {
} }
}; };
pub const Chunk = struct { pub const Chunk = struct { // MARK: Chunk
pos: ChunkPosition, pos: ChunkPosition,
data: main.utils.PaletteCompressedRegion(Block, chunkVolume) = undefined, data: main.utils.PaletteCompressedRegion(Block, chunkVolume) = undefined,
@ -230,7 +230,7 @@ pub const Chunk = struct {
} }
}; };
pub const ServerChunk = struct { pub const ServerChunk = struct { // MARK: ServerChunk
super: Chunk, super: Chunk,
wasChanged: bool = false, wasChanged: bool = false,

View File

@ -24,7 +24,7 @@ const Fog = graphics.Fog;
const renderer = @import("renderer.zig"); const renderer = @import("renderer.zig");
const settings = @import("settings.zig"); const settings = @import("settings.zig");
pub const camera = struct { pub const camera = struct { // MARK: camera
pub var rotation: Vec3f = Vec3f{0, 0, 0}; pub var rotation: Vec3f = Vec3f{0, 0, 0};
pub var direction: Vec3f = Vec3f{0, 0, 0}; pub var direction: Vec3f = Vec3f{0, 0, 0};
pub var viewMatrix: Mat4f = Mat4f.identity(); pub var viewMatrix: Mat4f = Mat4f.identity();
@ -59,7 +59,7 @@ const Box = struct {
} }
}; };
pub const Player = struct { pub const Player = struct { // MARK: Player
pub var super: main.server.Entity = .{}; pub var super: main.server.Entity = .{};
pub var id: u32 = 0; pub var id: u32 = 0;
pub var isFlying: Atomic(bool) = Atomic(bool).init(false); pub var isFlying: Atomic(bool) = Atomic(bool).init(false);
@ -433,7 +433,7 @@ pub const Player = struct {
} }
}; };
pub const World = struct { pub const World = struct { // MARK: World
const dayCycle: u63 = 12000; // Length of one in-game day in 100ms. Midnight is at DAY_CYCLE/2. Sunrise and sunset each take about 1/16 of the day. Currently set to 20 minutes const dayCycle: u63 = 12000; // Length of one in-game day in 100ms. Midnight is at DAY_CYCLE/2. Sunrise and sunset each take about 1/16 of the day. Currently set to 20 minutes
conn: *Connection, conn: *Connection,
@ -602,7 +602,7 @@ pub fn hyperSpeedToggle() void {
Player.hyperSpeed.store(!Player.hyperSpeed.load(.monotonic), .monotonic); Player.hyperSpeed.store(!Player.hyperSpeed.load(.monotonic), .monotonic);
} }
pub fn update(deltaTime: f64) void { pub fn update(deltaTime: f64) void { // MARK: update()
const gravity = 30.0; const gravity = 30.0;
const terminalVelocity = 90.0; const terminalVelocity = 90.0;
const airFrictionCoefficient = gravity/terminalVelocity; // λ = a/v in equillibrium const airFrictionCoefficient = gravity/terminalVelocity; // λ = a/v in equillibrium

View File

@ -39,7 +39,7 @@ pub const stb_image = @cImport ({
@cInclude("stb/stb_image_write.h"); @cInclude("stb/stb_image_write.h");
}); });
pub const draw = struct { pub const draw = struct { // MARK: draw
var color: u32 = 0; var color: u32 = 0;
var clip: ?Vec4i = null; var clip: ?Vec4i = null;
var translation: Vec2f = Vec2f{0, 0}; var translation: Vec2f = Vec2f{0, 0};
@ -118,7 +118,7 @@ pub const draw = struct {
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Stuff for fillRect: // MARK: fillRect()
var rectUniforms: struct { var rectUniforms: struct {
screen: c_int, screen: c_int,
start: c_int, start: c_int,
@ -172,7 +172,7 @@ pub const draw = struct {
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Stuff for fillRectBorder: // MARK: fillRectBorder()
var rectBorderUniforms: struct { var rectBorderUniforms: struct {
screen: c_int, screen: c_int,
start: c_int, start: c_int,
@ -236,7 +236,7 @@ pub const draw = struct {
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Stuff for drawLine: // MARK: drawLine()
var lineUniforms: struct { var lineUniforms: struct {
screen: c_int, screen: c_int,
start: c_int, start: c_int,
@ -289,7 +289,7 @@ pub const draw = struct {
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Stuff for drawRect: // MARK: drawRect()
// Draw rect can use the same shader as drawline, because it essentially draws lines. // Draw rect can use the same shader as drawline, because it essentially draws lines.
var drawRectVAO: c_uint = undefined; var drawRectVAO: c_uint = undefined;
var drawRectVBO: c_uint = undefined; var drawRectVBO: c_uint = undefined;
@ -335,7 +335,7 @@ pub const draw = struct {
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Stuff for fillCircle: // MARK: fillCircle()
var circleUniforms: struct { var circleUniforms: struct {
screen: c_int, screen: c_int,
center: c_int, center: c_int,
@ -388,7 +388,7 @@ pub const draw = struct {
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Stuff for drawImage: // MARK: drawImage()
// Luckily the vao of the regular rect can used. // Luckily the vao of the regular rect can used.
var imageUniforms: struct { var imageUniforms: struct {
screen: c_int, screen: c_int,
@ -454,6 +454,7 @@ pub const draw = struct {
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// MARK: customShadedRect()
pub fn customShadedRect(uniforms: anytype, _pos: Vec2f, _dim: Vec2f) void { pub fn customShadedRect(uniforms: anytype, _pos: Vec2f, _dim: Vec2f) void {
var pos = _pos; var pos = _pos;
@ -475,7 +476,8 @@ pub const draw = struct {
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// MARK: text()
pub fn text(_text: []const u8, x: f32, y: f32, fontSize: f32, alignment: TextBuffer.Alignment) void { pub fn text(_text: []const u8, x: f32, y: f32, fontSize: f32, alignment: TextBuffer.Alignment) void {
TextRendering.renderText(_text, x, y, fontSize, .{.color = @truncate(@as(u32, @bitCast(color)))}, alignment); TextRendering.renderText(_text, x, y, fontSize, .{.color = @truncate(@as(u32, @bitCast(color)))}, alignment);
} }
@ -487,7 +489,7 @@ pub const draw = struct {
} }
}; };
pub const TextBuffer = struct { pub const TextBuffer = struct { // MARK: TextBuffer
pub const Alignment = enum { pub const Alignment = enum {
left, left,
@ -974,7 +976,7 @@ pub const TextBuffer = struct {
} }
}; };
const TextRendering = struct { const TextRendering = struct { // MARK: TextRendering
const Glyph = struct { const Glyph = struct {
textureX: i32, textureX: i32,
size: Vec2i, size: Vec2i,
@ -1133,7 +1135,7 @@ const TextRendering = struct {
} }
}; };
pub fn init() void { pub fn init() void { // MARK: init()
draw.initCircle(); draw.initCircle();
draw.initDrawRect(); draw.initDrawRect();
draw.initImage(); draw.initImage();
@ -1157,7 +1159,7 @@ pub fn deinit() void {
block_texture.deinit(); block_texture.deinit();
} }
pub const Shader = struct { pub const Shader = struct { // MARK: Shader
id: c_uint, id: c_uint,
fn addShader(self: *const Shader, filename: []const u8, shader_stage: c_uint) !void { fn addShader(self: *const Shader, filename: []const u8, shader_stage: c_uint) !void {
@ -1247,7 +1249,7 @@ pub const Shader = struct {
} }
}; };
pub const SSBO = struct { pub const SSBO = struct { // MARK: SSBO
bufferID: c_uint, bufferID: c_uint,
pub fn init() SSBO { pub fn init() SSBO {
var self = SSBO{.bufferID = undefined}; var self = SSBO{.bufferID = undefined};
@ -1298,7 +1300,7 @@ pub const SubAllocation = struct {
}; };
/// A big SSBO that is able to allocate/free smaller regions. /// A big SSBO that is able to allocate/free smaller regions.
pub fn LargeBuffer(comptime Entry: type) type { pub fn LargeBuffer(comptime Entry: type) type { // MARK: LargerBuffer
return struct { return struct {
ssbo: SSBO, ssbo: SSBO,
freeBlocks: main.List(SubAllocation), freeBlocks: main.List(SubAllocation),
@ -1459,7 +1461,7 @@ pub fn LargeBuffer(comptime Entry: type) type {
}; };
} }
pub const FrameBuffer = struct { pub const FrameBuffer = struct { // MARK: FrameBuffer
frameBuffer: c_uint, frameBuffer: c_uint,
texture: c_uint, texture: c_uint,
hasDepthTexture: bool, hasDepthTexture: bool,
@ -1550,7 +1552,7 @@ pub const FrameBuffer = struct {
} }
}; };
pub const TextureArray = struct { pub const TextureArray = struct { // MARK: TextureArray
textureID: c_uint, textureID: c_uint,
pub fn init() TextureArray { pub fn init() TextureArray {
@ -1675,7 +1677,7 @@ pub const TextureArray = struct {
} }
}; };
pub const Texture = struct { pub const Texture = struct { // MARK: Texture
textureID: c_uint, textureID: c_uint,
pub fn init() Texture { pub fn init() Texture {
@ -1733,7 +1735,7 @@ pub const Texture = struct {
} }
}; };
pub const CubeMapTexture = struct { pub const CubeMapTexture = struct { // MARK: CubeMapTexture
textureID: c_uint, textureID: c_uint,
pub fn init() CubeMapTexture { pub fn init() CubeMapTexture {
@ -1812,7 +1814,7 @@ pub const CubeMapTexture = struct {
} }
}; };
pub const Color = extern struct { pub const Color = extern struct { // MARK: Color
r: u8, r: u8,
g: u8, g: u8,
b: u8, b: u8,
@ -1823,7 +1825,7 @@ pub const Color = extern struct {
} }
}; };
pub const Image = struct { pub const Image = struct { // MARK: Image
var defaultImageData = [4]Color { var defaultImageData = [4]Color {
Color{.r=0, .g=0, .b=0, .a=255}, Color{.r=0, .g=0, .b=0, .a=255},
Color{.r=255, .g=0, .b=255, .a=255}, Color{.r=255, .g=0, .b=255, .a=255},
@ -1911,13 +1913,13 @@ pub const Image = struct {
} }
}; };
pub const Fog = struct { pub const Fog = struct { // MARK: Fog
fogColor: Vec3f, fogColor: Vec3f,
skyColor: Vec3f, skyColor: Vec3f,
density: f32, density: f32,
}; };
const block_texture = struct { const block_texture = struct { // MARK: block_texture
var uniforms: struct { var uniforms: struct {
color: c_int, color: c_int,
transparent: c_int, transparent: c_int,

View File

@ -16,7 +16,7 @@ pub var window: *c.GLFWwindow = undefined;
pub var grabbed: bool = false; pub var grabbed: bool = false;
pub var scrollOffset: f32 = 0; pub var scrollOffset: f32 = 0;
pub const Key = struct { pub const Key = struct { // MARK: Key
name: []const u8, name: []const u8,
pressed: bool = false, pressed: bool = false,
key: c_int = c.GLFW_KEY_UNKNOWN, key: c_int = c.GLFW_KEY_UNKNOWN,
@ -109,7 +109,7 @@ pub const Key = struct {
} }
}; };
pub const GLFWCallbacks = struct { pub const GLFWCallbacks = struct { // MARK: GLFWCallbacks
fn errorCallback(errorCode: c_int, description: [*c]const u8) callconv(.C) void { fn errorCallback(errorCode: c_int, description: [*c]const u8) callconv(.C) void {
std.log.err("GLFW Error({}): {s}", .{errorCode, description}); std.log.err("GLFW Error({}): {s}", .{errorCode, description});
} }
@ -305,7 +305,7 @@ pub fn setClipboardString(string: []const u8) void {
c.glfwSetClipboardString(window, nullTerminatedString.ptr); c.glfwSetClipboardString(window, nullTerminatedString.ptr);
} }
pub fn init() void { pub fn init() void { // MARK: init()
_ = c.glfwSetErrorCallback(GLFWCallbacks.errorCallback); _ = c.glfwSetErrorCallback(GLFWCallbacks.errorCallback);
if(c.glfwInit() == 0) { if(c.glfwInit() == 0) {

View File

@ -36,7 +36,7 @@ pub var scale: f32 = undefined;
pub var hoveredItemSlot: ?*ItemSlot = null; pub var hoveredItemSlot: ?*ItemSlot = null;
const GuiCommandQueue = struct { const GuiCommandQueue = struct { // MARK: GuiCommandQueue
const Action = enum { const Action = enum {
open, open,
close, close,
@ -126,7 +126,7 @@ pub const Callback = struct {
} }
}; };
pub fn init() void { pub fn init() void { // MARK: init()
GuiCommandQueue.init(); GuiCommandQueue.init();
windowList = List(*GuiWindow).init(main.globalAllocator); windowList = List(*GuiWindow).init(main.globalAllocator);
hudWindows = List(*GuiWindow).init(main.globalAllocator); hudWindows = List(*GuiWindow).init(main.globalAllocator);
@ -183,7 +183,7 @@ pub fn deinit() void {
GuiCommandQueue.deinit(); GuiCommandQueue.deinit();
} }
pub fn save() void { pub fn save() void { // MARK: save()
const guiJson = JsonElement.initObject(main.stackAllocator); const guiJson = JsonElement.initObject(main.stackAllocator);
defer guiJson.free(main.stackAllocator); defer guiJson.free(main.stackAllocator);
for(windowList.items) |window| { for(windowList.items) |window| {
@ -572,7 +572,7 @@ pub fn toggleGameMenu() void {
} }
} }
pub const inventory = struct { pub const inventory = struct { // MARK: inventory
const ItemStack = main.items.ItemStack; const ItemStack = main.items.ItemStack;
pub var carriedItemStack: ItemStack = .{.item = null, .amount = 0}; pub var carriedItemStack: ItemStack = .{.item = null, .amount = 0};
var carriedItemSlot: *ItemSlot = undefined; var carriedItemSlot: *ItemSlot = undefined;

View File

@ -22,7 +22,7 @@ const Vec3f = vec.Vec3f;
const Vec3i = vec.Vec3i; const Vec3i = vec.Vec3i;
const NeverFailingAllocator = main.utils.NeverFailingAllocator; const NeverFailingAllocator = main.utils.NeverFailingAllocator;
const ItemDrop = struct { const ItemDrop = struct { // MARK: ItemDrop
pos: Vec3d, pos: Vec3d,
vel: Vec3d, vel: Vec3d,
rot: Vec3f, rot: Vec3f,
@ -33,7 +33,7 @@ const ItemDrop = struct {
reverseIndex: u16, reverseIndex: u16,
}; };
pub const ItemDropManager = struct { pub const ItemDropManager = struct { // MARK: ItemDropManager
/// Half the side length of all item entities hitboxes as a cube. /// Half the side length of all item entities hitboxes as a cube.
const radius: f64 = 0.1; const radius: f64 = 0.1;
/// Side length of all item entities hitboxes as a cube. /// Side length of all item entities hitboxes as a cube.
@ -387,7 +387,7 @@ pub const ItemDropManager = struct {
} }
}; };
pub const ClientItemDropManager = struct { pub const ClientItemDropManager = struct { // MARK: ClientItemDropManager
const maxf64Capacity = ItemDropManager.maxCapacity*@sizeOf(Vec3d)/@sizeOf(f64); const maxf64Capacity = ItemDropManager.maxCapacity*@sizeOf(Vec3d)/@sizeOf(f64);
super: ItemDropManager, super: ItemDropManager,
@ -479,7 +479,7 @@ pub const ClientItemDropManager = struct {
} }
}; };
pub const ItemDropRenderer = struct { pub const ItemDropRenderer = struct { // MARK: ItemDropRenderer
var itemShader: graphics.Shader = undefined; var itemShader: graphics.Shader = undefined;
var itemUniforms: struct { var itemUniforms: struct {
projectionMatrix: c_int, projectionMatrix: c_int,

View File

@ -17,7 +17,7 @@ const Vec3f = vec.Vec3f;
const NeverFailingAllocator = main.utils.NeverFailingAllocator; const NeverFailingAllocator = main.utils.NeverFailingAllocator;
/// Holds the basic properties of a tool crafting material. /// Holds the basic properties of a tool crafting material.
const Material = struct { const Material = struct { // MARK: Material
/// how much it weighs /// how much it weighs
density: f32 = undefined, density: f32 = undefined,
/// how long it takes until the tool breaks /// how long it takes until the tool breaks
@ -59,7 +59,7 @@ const Material = struct {
}; };
pub const BaseItem = struct { pub const BaseItem = struct { // MARK: BaseItem
image: graphics.Image, image: graphics.Image,
texture: ?graphics.Texture, // TODO: Properly deinit texture: ?graphics.Texture, // TODO: Properly deinit
id: []const u8, id: []const u8,
@ -149,7 +149,7 @@ pub const BaseItem = struct {
}; };
///Generates the texture of a Tool using the material information. ///Generates the texture of a Tool using the material information.
const TextureGenerator = struct { const TextureGenerator = struct { // MARK: TextureGenerator
/// Used to translate between grid and pixel coordinates. /// Used to translate between grid and pixel coordinates.
pub const GRID_CENTERS_X = [_]u8 { pub const GRID_CENTERS_X = [_]u8 {
2, 5, 8, 11, 14, 2, 5, 8, 11, 14,
@ -523,7 +523,7 @@ const TextureGenerator = struct {
}; };
/// Determines the physical properties of a tool to caclulate in-game parameters such as durability and speed. /// Determines the physical properties of a tool to caclulate in-game parameters such as durability and speed.
const ToolPhysics = struct { const ToolPhysics = struct { // MARK: ToolPhysics
/// Finds the handle of the tool. /// Finds the handle of the tool.
/// Uses a quite simple algorithm: /// Uses a quite simple algorithm:
/// It just simply takes the lowest, right-most 2×2 grid of filled pixels. /// It just simply takes the lowest, right-most 2×2 grid of filled pixels.
@ -871,7 +871,7 @@ const ToolPhysics = struct {
} }
}; };
pub const Tool = struct { pub const Tool = struct { // MARK: Tool
craftingGrid: [25]?*const BaseItem, craftingGrid: [25]?*const BaseItem,
materialGrid: [16][16]?*const BaseItem, materialGrid: [16][16]?*const BaseItem,
tooltip: ?[]const u8, tooltip: ?[]const u8,
@ -1020,7 +1020,7 @@ pub const Tool = struct {
} }
}; };
pub const Item = union(enum) { pub const Item = union(enum) { // MARK: Item
baseItem: *BaseItem, baseItem: *BaseItem,
tool: *Tool, tool: *Tool,
@ -1109,7 +1109,7 @@ pub const Item = union(enum) {
} }
}; };
pub const ItemStack = struct { pub const ItemStack = struct { // MARK: ItemStack
item: ?Item = null, item: ?Item = null,
amount: u16 = 0, amount: u16 = 0,
@ -1179,7 +1179,7 @@ pub const ItemStack = struct {
} }
}; };
pub const Inventory = struct { pub const Inventory = struct { // MARK: Inventory
items: []ItemStack, items: []ItemStack,
pub fn init(allocator: NeverFailingAllocator, size: usize) Inventory { pub fn init(allocator: NeverFailingAllocator, size: usize) Inventory {
@ -1270,7 +1270,7 @@ pub const Inventory = struct {
} }
}; };
const Recipe = struct { const Recipe = struct { // MARK: Recipe
sourceItems: []*BaseItem, sourceItems: []*BaseItem,
sourceAmounts: []u16, sourceAmounts: []u16,
resultItem: ItemStack, resultItem: ItemStack,

View File

@ -14,7 +14,7 @@ const JsonType = enum(u8) {
JsonArray, JsonArray,
JsonObject JsonObject
}; };
pub const JsonElement = union(JsonType) { pub const JsonElement = union(JsonType) { // MARK: JsonElement
JsonInt: i64, JsonInt: i64,
JsonFloat: f64, JsonFloat: f64,
JsonString: []const u8, JsonString: []const u8,
@ -347,7 +347,7 @@ pub const JsonElement = union(JsonType) {
} }
}; };
const Parser = struct { const Parser = struct { // MARK: Parser
/// All whitespaces from unicode 14. /// All whitespaces from unicode 14.
const whitespaces = [_][]const u8 {"\u{0009}", "\u{000A}", "\u{000B}", "\u{000C}", "\u{000D}", "\u{0020}", "\u{0085}", "\u{00A0}", "\u{1680}", "\u{2000}", "\u{2001}", "\u{2002}", "\u{2003}", "\u{2004}", "\u{2005}", "\u{2006}", "\u{2007}", "\u{2008}", "\u{2009}", "\u{200A}", "\u{2028}", "\u{2029}", "\u{202F}", "\u{205F}", "\u{3000}"}; const whitespaces = [_][]const u8 {"\u{0009}", "\u{000A}", "\u{000B}", "\u{000C}", "\u{000D}", "\u{0020}", "\u{0085}", "\u{00A0}", "\u{1680}", "\u{2000}", "\u{2001}", "\u{2002}", "\u{2003}", "\u{2004}", "\u{2005}", "\u{2006}", "\u{2007}", "\u{2008}", "\u{2009}", "\u{200A}", "\u{2028}", "\u{2029}", "\u{202F}", "\u{205F}", "\u{3000}"};
@ -646,7 +646,7 @@ const Parser = struct {
// //
// TESTING // MARK: Testing
// //
test "skipWhitespaces" { test "skipWhitespaces" {

View File

@ -51,7 +51,7 @@ var logFile: ?std.fs.File = undefined;
var logFileTs: ?std.fs.File = undefined; var logFileTs: ?std.fs.File = undefined;
var supportsANSIColors: bool = undefined; var supportsANSIColors: bool = undefined;
// overwrite the log function: // overwrite the log function:
pub const std_options: std.Options = .{ pub const std_options: std.Options = .{ // MARK: std_options
.log_level = .debug, .log_level = .debug,
.logFn = struct {pub fn logFn( .logFn = struct {pub fn logFn(
comptime level: std.log.Level, comptime level: std.log.Level,
@ -238,6 +238,7 @@ fn logToStdErr(comptime format: []const u8, args: anytype) void {
nosuspend std.io.getStdErr().writeAll(string) catch {}; nosuspend std.io.getStdErr().writeAll(string) catch {};
} }
// MARK: Callbacks
fn escape() void { fn escape() void {
if(gui.selectedTextInput != null) { if(gui.selectedTextInput != null) {
gui.selectedTextInput = null; gui.selectedTextInput = null;
@ -296,7 +297,7 @@ fn setHotbarSlot(i: comptime_int) *const fn() void {
}.set; }.set;
} }
pub const KeyBoard = struct { pub const KeyBoard = struct { // MARK: KeyBoard
const c = Window.c; const c = Window.c;
pub var keys = [_]Window.Key { pub var keys = [_]Window.Key {
// Gameplay: // Gameplay:
@ -377,7 +378,7 @@ pub var lastFrameTime = std.atomic.Value(f64).init(0);
/// Measures time between different frames' beginnings. /// Measures time between different frames' beginnings.
pub var lastDeltaTime = std.atomic.Value(f64).init(0); pub var lastDeltaTime = std.atomic.Value(f64).init(0);
pub fn main() void { pub fn main() void { // MARK: main()
seed = @bitCast(std.time.milliTimestamp()); seed = @bitCast(std.time.milliTimestamp());
defer if(global_gpa.deinit() == .leak) { defer if(global_gpa.deinit() == .leak) {
std.log.err("Memory leak", .{}); std.log.err("Memory leak", .{});

View File

@ -137,7 +137,7 @@ const Request = struct {
/// Implements parts of the STUN(Session Traversal Utilities for NAT) protocol to discover public IP+Port /// Implements parts of the STUN(Session Traversal Utilities for NAT) protocol to discover public IP+Port
/// Reference: https://datatracker.ietf.org/doc/html/rfc5389 /// Reference: https://datatracker.ietf.org/doc/html/rfc5389
const STUN = struct { const STUN = struct { // MARK: STUN
const ipServerList = [_][]const u8 { const ipServerList = [_][]const u8 {
"iphone-stun.strato-iphone.de:3478", "iphone-stun.strato-iphone.de:3478",
"stun.12connect.com:3478", "stun.12connect.com:3478",
@ -374,7 +374,7 @@ const STUN = struct {
} }
}; };
pub const ConnectionManager = struct { pub const ConnectionManager = struct { // MARK: ConnectionManager
socket: Socket = undefined, socket: Socket = undefined,
thread: std.Thread = undefined, thread: std.Thread = undefined,
threadId: std.Thread.Id = undefined, threadId: std.Thread.Id = undefined,
@ -632,6 +632,7 @@ const UnconfirmedPacket = struct {
id: u32, id: u32,
}; };
// MARK: Protocols
pub var bytesReceived: [256]Atomic(usize) = [_]Atomic(usize) {Atomic(usize).init(0)} ** 256; pub var bytesReceived: [256]Atomic(usize) = [_]Atomic(usize) {Atomic(usize).init(0)} ** 256;
pub var packetsReceived: [256]Atomic(usize) = [_]Atomic(usize) {Atomic(usize).init(0)} ** 256; pub var packetsReceived: [256]Atomic(usize) = [_]Atomic(usize) {Atomic(usize).init(0)} ** 256;
pub const Protocols = struct { pub const Protocols = struct {
@ -1239,7 +1240,7 @@ pub const Protocols = struct {
}; };
pub const Connection = struct { pub const Connection = struct { // MARK: Connection
const maxPacketSize: u32 = 65507; // max udp packet size const maxPacketSize: u32 = 65507; // max udp packet size
const importantHeaderSize: u32 = 5; const importantHeaderSize: u32 = 5;
const maxImportantPacketSize: u32 = 1500 - 14 - 20 - 8; // Ethernet MTU minus Ethernet header minus IP header minus udp header const maxImportantPacketSize: u32 = 1500 - 14 - 20 - 8; // Ethernet MTU minus Ethernet header minus IP header minus udp header

View File

@ -164,7 +164,7 @@ pub fn crosshairDirection(rotationMatrix: Mat4f, fovY: f32, width: u31, height:
return adjusted; return adjusted;
} }
pub fn renderWorld(world: *World, ambientLight: Vec3f, skyColor: Vec3f, playerPos: Vec3d) void { pub fn renderWorld(world: *World, ambientLight: Vec3f, skyColor: Vec3f, playerPos: Vec3d) void { // MARK: renderWorld()
worldFrameBuffer.bind(); worldFrameBuffer.bind();
c.glViewport(0, 0, lastWidth, lastHeight); c.glViewport(0, 0, lastWidth, lastHeight);
gpu_performance_measuring.startQuery(.clear); gpu_performance_measuring.startQuery(.clear);
@ -291,7 +291,7 @@ pub fn renderWorld(world: *World, ambientLight: Vec3f, skyColor: Vec3f, playerPo
gpu_performance_measuring.stopQuery(); gpu_performance_measuring.stopQuery();
} }
const Bloom = struct { const Bloom = struct { // MARK: Bloom
var buffer1: graphics.FrameBuffer = undefined; var buffer1: graphics.FrameBuffer = undefined;
var buffer2: graphics.FrameBuffer = undefined; var buffer2: graphics.FrameBuffer = undefined;
var emptyBuffer: graphics.Texture = undefined; var emptyBuffer: graphics.Texture = undefined;
@ -583,7 +583,7 @@ pub const MenuBackGround = struct {
} }
}; };
pub const Frustum = struct { pub const Frustum = struct { // MARK: Frustum
const Plane = struct { const Plane = struct {
pos: Vec3f, pos: Vec3f,
norm: Vec3f, norm: Vec3f,
@ -618,7 +618,7 @@ pub const Frustum = struct {
} }
}; };
pub const MeshSelection = struct { pub const MeshSelection = struct { // MARK: MeshSelection
var shader: Shader = undefined; var shader: Shader = undefined;
var uniforms: struct { var uniforms: struct {
projectionMatrix: c_int, projectionMatrix: c_int,

View File

@ -276,7 +276,7 @@ pub const IndirectData = extern struct {
baseInstance: u32, baseInstance: u32,
}; };
const PrimitiveMesh = struct { const PrimitiveMesh = struct { // MARK: PrimitiveMesh
coreFaces: main.ListUnmanaged(FaceData) = .{}, coreFaces: main.ListUnmanaged(FaceData) = .{},
neighborFacesSameLod: [6]main.ListUnmanaged(FaceData) = [_]main.ListUnmanaged(FaceData){.{}} ** 6, neighborFacesSameLod: [6]main.ListUnmanaged(FaceData) = [_]main.ListUnmanaged(FaceData){.{}} ** 6,
neighborFacesHigherLod: [6]main.ListUnmanaged(FaceData) = [_]main.ListUnmanaged(FaceData){.{}} ** 6, neighborFacesHigherLod: [6]main.ListUnmanaged(FaceData) = [_]main.ListUnmanaged(FaceData){.{}} ** 6,
@ -605,7 +605,7 @@ const PrimitiveMesh = struct {
} }
}; };
pub const ChunkMesh = struct { pub const ChunkMesh = struct { // MARK: ChunkMesh
const SortingData = struct { const SortingData = struct {
face: FaceData, face: FaceData,
distance: u32, distance: u32,

View File

@ -53,7 +53,7 @@ const BlockUpdate = struct {
}; };
var blockUpdateList: main.List(BlockUpdate) = undefined; var blockUpdateList: main.List(BlockUpdate) = undefined;
pub fn init() void { pub fn init() void { // MARK: init()
lastRD = 0; lastRD = 0;
blockUpdateList = main.List(BlockUpdate).init(main.globalAllocator); blockUpdateList = main.List(BlockUpdate).init(main.globalAllocator);
for(&storageLists) |*storageList| { for(&storageLists) |*storageList| {
@ -106,6 +106,8 @@ pub fn deinit() void {
clearList.clearAndFree(); clearList.clearAndFree();
} }
// MARK: getters
fn getNodePointer(pos: chunk.ChunkPosition) *ChunkMeshNode { fn getNodePointer(pos: chunk.ChunkPosition) *ChunkMeshNode {
const lod = std.math.log2_int(u31, pos.voxelSize); const lod = std.math.log2_int(u31, pos.voxelSize);
var xIndex = pos.wx >> lod+chunk.chunkShift; var xIndex = pos.wx >> lod+chunk.chunkShift;
@ -202,7 +204,7 @@ fn reduceRenderDistance(fullRenderDistance: i64, reduction: i64) i32 {
return reducedRenderDistance; return reducedRenderDistance;
} }
fn isInRenderDistance(pos: chunk.ChunkPosition) bool { fn isInRenderDistance(pos: chunk.ChunkPosition) bool { // MARK: isInRenderDistance()
const maxRenderDistance = lastRD*chunk.chunkSize*pos.voxelSize; const maxRenderDistance = lastRD*chunk.chunkSize*pos.voxelSize;
const size: u31 = chunk.chunkSize*pos.voxelSize; const size: u31 = chunk.chunkSize*pos.voxelSize;
const mask: i32 = size - 1; const mask: i32 = size - 1;
@ -254,7 +256,7 @@ fn isMapInRenderDistance(pos: LightMap.MapFragmentPosition) bool {
return true; return true;
} }
fn freeOldMeshes(olderPx: i32, olderPy: i32, olderPz: i32, olderRD: i32) void { fn freeOldMeshes(olderPx: i32, olderPy: i32, olderPz: i32, olderRD: i32) void { // MARK: freeOldMeshes()
for(0..storageLists.len) |_lod| { for(0..storageLists.len) |_lod| {
const lod: u5 = @intCast(_lod); const lod: u5 = @intCast(_lod);
const maxRenderDistanceNew = lastRD*chunk.chunkSize << lod; const maxRenderDistanceNew = lastRD*chunk.chunkSize << lod;
@ -392,7 +394,7 @@ fn freeOldMeshes(olderPx: i32, olderPy: i32, olderPz: i32, olderRD: i32) void {
} }
} }
fn createNewMeshes(olderPx: i32, olderPy: i32, olderPz: i32, olderRD: i32, meshRequests: *main.List(chunk.ChunkPosition), mapRequests: *main.List(LightMap.MapFragmentPosition)) void { fn createNewMeshes(olderPx: i32, olderPy: i32, olderPz: i32, olderRD: i32, meshRequests: *main.List(chunk.ChunkPosition), mapRequests: *main.List(LightMap.MapFragmentPosition)) void { // MARK: createNewMeshes()
for(0..storageLists.len) |_lod| { for(0..storageLists.len) |_lod| {
const lod: u5 = @intCast(_lod); const lod: u5 = @intCast(_lod);
const maxRenderDistanceNew = lastRD*chunk.chunkSize << lod; const maxRenderDistanceNew = lastRD*chunk.chunkSize << lod;
@ -532,7 +534,7 @@ fn createNewMeshes(olderPx: i32, olderPy: i32, olderPz: i32, olderRD: i32, meshR
} }
} }
pub noinline fn updateAndGetRenderChunks(conn: *network.Connection, playerPos: Vec3d, renderDistance: i32) []*chunk_meshing.ChunkMesh { pub noinline fn updateAndGetRenderChunks(conn: *network.Connection, playerPos: Vec3d, renderDistance: i32) []*chunk_meshing.ChunkMesh { // MARK: updateAndGetRenderChunks()
meshList.clearRetainingCapacity(); meshList.clearRetainingCapacity();
if(lastRD != renderDistance) { if(lastRD != renderDistance) {
network.Protocols.genericUpdate.sendRenderDistance(conn, renderDistance); network.Protocols.genericUpdate.sendRenderDistance(conn, renderDistance);
@ -894,7 +896,7 @@ pub noinline fn updateAndGetRenderChunks(conn: *network.Connection, playerPos: V
return meshList.items; return meshList.items;
} }
pub fn updateMeshes(targetTime: i64) void { pub fn updateMeshes(targetTime: i64) void { // MARK: updateMeshes()
{ // First of all process all the block updates: { // First of all process all the block updates:
blockUpdateMutex.lock(); blockUpdateMutex.lock();
defer blockUpdateMutex.unlock(); defer blockUpdateMutex.unlock();
@ -997,6 +999,8 @@ pub fn updateMeshes(targetTime: i64) void {
} }
} }
// MARK: adders
pub fn addMeshToClearListAndDecreaseRefCount(mesh: *chunk_meshing.ChunkMesh) void { pub fn addMeshToClearListAndDecreaseRefCount(mesh: *chunk_meshing.ChunkMesh) void {
std.debug.assert(mesh.refCount.load(.monotonic) == 0); std.debug.assert(mesh.refCount.load(.monotonic) == 0);
mutex.lock(); mutex.lock();
@ -1040,7 +1044,7 @@ pub fn finishMesh(mesh: *chunk_meshing.ChunkMesh) void {
updatableList.append(mesh); updatableList.append(mesh);
} }
pub const MeshGenerationTask = struct { pub const MeshGenerationTask = struct { // MARK: MeshGenerationTask
mesh: *chunk.Chunk, mesh: *chunk.Chunk,
pub const vtable = utils.ThreadPool.VTable{ pub const vtable = utils.ThreadPool.VTable{
@ -1084,6 +1088,8 @@ pub const MeshGenerationTask = struct {
} }
}; };
// MARK: updaters
pub fn updateBlock(x: i32, y: i32, z: i32, newBlock: blocks.Block) void { pub fn updateBlock(x: i32, y: i32, z: i32, newBlock: blocks.Block) void {
blockUpdateMutex.lock(); blockUpdateMutex.lock();
defer blockUpdateMutex.unlock(); defer blockUpdateMutex.unlock();

View File

@ -21,7 +21,7 @@ const RayIntersectionResult = struct {
/// Each block gets 16 bit of additional storage(apart from the reference to the block type). /// Each block gets 16 bit of additional storage(apart from the reference to the block type).
/// These 16 bits are accessed and interpreted by the `RotationMode`. /// These 16 bits are accessed and interpreted by the `RotationMode`.
/// With the `RotationMode` interface there is almost no limit to what can be done with those 16 bit. /// With the `RotationMode` interface there is almost no limit to what can be done with those 16 bit.
pub const RotationMode = struct { pub const RotationMode = struct { // MARK: RotationMode
const DefaultFunctions = struct { const DefaultFunctions = struct {
fn model(block: Block) u16 { fn model(block: Block) u16 {
return blocks.meshes.modelIndexStart(block); return blocks.meshes.modelIndexStart(block);
@ -83,12 +83,12 @@ fn rotationMatrixTransform(quad: *main.models.QuadInfo, transformMatrix: Mat4f)
} }
pub const RotationModes = struct { pub const RotationModes = struct {
pub const NoRotation = struct { pub const NoRotation = struct { // MARK: NoRotation
pub const id: []const u8 = "no_rotation"; pub const id: []const u8 = "no_rotation";
fn init() void {} fn init() void {}
fn deinit() void {} fn deinit() void {}
}; };
pub const Log = struct { pub const Log = struct { // MARK: Log
pub const id: []const u8 = "log"; pub const id: []const u8 = "log";
var rotatedModels: std.StringHashMap(u16) = undefined; var rotatedModels: std.StringHashMap(u16) = undefined;
@ -133,7 +133,7 @@ pub const RotationModes = struct {
return false; return false;
} }
}; };
pub const Planar = struct { pub const Planar = struct { // MARK: Planar
pub const id: []const u8 = "planar"; pub const id: []const u8 = "planar";
var rotatedModels: std.StringHashMap(u16) = undefined; var rotatedModels: std.StringHashMap(u16) = undefined;
@ -177,7 +177,7 @@ pub const RotationModes = struct {
return false; return false;
} }
}; };
pub const Fence = struct { pub const Fence = struct { // MARK: Fence
pub const id: []const u8 = "fence"; pub const id: []const u8 = "fence";
pub const dependsOnNeighbors = true; pub const dependsOnNeighbors = true;
var fenceModels: std.StringHashMap(u16) = undefined; var fenceModels: std.StringHashMap(u16) = undefined;
@ -262,7 +262,7 @@ pub const RotationModes = struct {
return true; return true;
} }
}; };
pub const Stairs = struct { pub const Stairs = struct { // MARK: Stairs
pub const id: []const u8 = "stairs"; pub const id: []const u8 = "stairs";
var modelIndex: u16 = 0; var modelIndex: u16 = 0;
@ -544,7 +544,7 @@ pub const RotationModes = struct {
return false; return false;
} }
}; };
pub const Torch = struct { pub const Torch = struct { // MARK: Torch
pub const id: []const u8 = "torch"; pub const id: []const u8 = "torch";
pub const dependsOnNeighbors = true; pub const dependsOnNeighbors = true;
var rotatedModels: std.StringHashMap(u16) = undefined; var rotatedModels: std.StringHashMap(u16) = undefined;
@ -665,6 +665,8 @@ pub const RotationModes = struct {
}; };
}; };
// MARK: init/register
pub fn init() void { pub fn init() void {
rotationModes = std.StringHashMap(RotationMode).init(main.globalAllocator.allocator); rotationModes = std.StringHashMap(RotationMode).init(main.globalAllocator.allocator);
inline for(@typeInfo(RotationModes).Struct.decls) |declaration| { inline for(@typeInfo(RotationModes).Struct.decls) |declaration| {

View File

@ -17,7 +17,7 @@ pub const storage = @import("storage.zig");
const command = @import("command/_command.zig"); const command = @import("command/_command.zig");
pub const User = struct { pub const User = struct { // MARK: User
conn: *Connection = undefined, conn: *Connection = undefined,
player: Entity = .{}, player: Entity = .{},
timeDifference: utils.TimeDifference = .{}, timeDifference: utils.TimeDifference = .{},
@ -123,7 +123,7 @@ pub var mutex: std.Thread.Mutex = .{};
pub var thread: ?std.Thread = null; pub var thread: ?std.Thread = null;
fn init(name: []const u8) void { fn init(name: []const u8) void { // MARK: init()
std.debug.assert(world == null); // There can only be one world. std.debug.assert(world == null); // There can only be one world.
command.init(); command.init();
users = main.List(*User).init(main.globalAllocator); users = main.List(*User).init(main.globalAllocator);
@ -172,7 +172,7 @@ fn deinit() void {
command.deinit(); command.deinit();
} }
fn update() void { fn update() void { // MARK: update()
world.?.update(); world.?.update();
mutex.lock(); mutex.lock();
for(users.items) |user| { for(users.items) |user| {
@ -238,7 +238,7 @@ pub fn stop() void {
running.store(false, .monotonic); running.store(false, .monotonic);
} }
pub fn disconnect(user: *User) void { pub fn disconnect(user: *User) void { // MARK: disconnect()
if(!user.connected.load(.unordered)) return; if(!user.connected.load(.unordered)) return;
// TODO: world.forceSave(); // TODO: world.forceSave();
const message = std.fmt.allocPrint(main.stackAllocator.allocator, "{s} #ffff00left", .{user.name}) catch unreachable; const message = std.fmt.allocPrint(main.stackAllocator.allocator, "{s} #ffff00left", .{user.name}) catch unreachable;
@ -312,7 +312,7 @@ pub fn connect(user: *User) void {
users.append(user); users.append(user);
} }
pub fn messageFrom(msg: []const u8, source: *User) void { pub fn messageFrom(msg: []const u8, source: *User) void { // MARK: message
if(msg[0] == '/') { // Command. if(msg[0] == '/') { // Command.
std.log.info("User \"{s}\" executed command \"{s}\"", .{source.name, msg}); // TODO use color \033[0;32m std.log.info("User \"{s}\" executed command \"{s}\"", .{source.name, msg}); // TODO use color \033[0;32m
command.execute(msg[1..], source); command.execute(msg[1..], source);

View File

@ -5,7 +5,7 @@ const main = @import("root");
const chunk = main.chunk; const chunk = main.chunk;
const server = @import("server.zig"); const server = @import("server.zig");
pub const RegionFile = struct { pub const RegionFile = struct { // MARK: RegionFile
const version = 0; const version = 0;
pub const regionShift = 2; pub const regionShift = 2;
pub const regionSize = 1 << regionShift; pub const regionSize = 1 << regionShift;
@ -175,7 +175,7 @@ pub const RegionFile = struct {
} }
}; };
// MARK: cache
const cacheSize = 1 << 8; // Must be a power of 2! const cacheSize = 1 << 8; // Must be a power of 2!
const cacheMask = cacheSize - 1; const cacheMask = cacheSize - 1;
const associativity = 8; const associativity = 8;
@ -205,7 +205,7 @@ pub fn loadRegionFileAndIncreaseRefCount(wx: i32, wy: i32, wz: i32, voxelSize: u
return result; return result;
} }
pub const ChunkCompression = struct { pub const ChunkCompression = struct { // MARK: ChunkCompression
const CompressionAlgo = enum(u32) { const CompressionAlgo = enum(u32) {
deflate_with_position = 0, deflate_with_position = 0,
deflate = 1, // TODO: Investigate if palette compression (or palette compression with huffman coding) is more efficient. deflate = 1, // TODO: Investigate if palette compression (or palette compression with huffman coding) is more efficient.

View File

@ -17,7 +17,7 @@ const Biome = terrain.biomes.Biome;
const SurfaceMap = terrain.SurfaceMap; const SurfaceMap = terrain.SurfaceMap;
/// Cave biome data from a big chunk of the world. /// Cave biome data from a big chunk of the world.
pub const CaveBiomeMapFragment = struct { pub const CaveBiomeMapFragment = struct { // MARK: caveBiomeMapFragment
pub const caveBiomeShift = 7; pub const caveBiomeShift = 7;
pub const caveBiomeSize = 1 << caveBiomeShift; pub const caveBiomeSize = 1 << caveBiomeShift;
pub const caveBiomeMask = caveBiomeSize - 1; pub const caveBiomeMask = caveBiomeSize - 1;
@ -66,7 +66,7 @@ pub const CaveBiomeMapFragment = struct {
}; };
/// A generator for the cave biome map. /// A generator for the cave biome map.
pub const CaveBiomeGenerator = struct { pub const CaveBiomeGenerator = struct { // MARK: CaveBiomeGenerator
init: *const fn(parameters: JsonElement) void, init: *const fn(parameters: JsonElement) void,
deinit: *const fn() void, deinit: *const fn() void,
generate: *const fn(map: *CaveBiomeMapFragment, seed: u64) void, generate: *const fn(map: *CaveBiomeMapFragment, seed: u64) void,
@ -109,7 +109,7 @@ pub const CaveBiomeGenerator = struct {
}; };
/// Doesn't allow getting the biome at one point and instead is only useful for interpolating values between biomes. /// Doesn't allow getting the biome at one point and instead is only useful for interpolating values between biomes.
pub const InterpolatableCaveBiomeMapView = struct { pub const InterpolatableCaveBiomeMapView = struct { // MARK: InterpolatableCaveBiomeMapView
fragments: Array3D(*CaveBiomeMapFragment), fragments: Array3D(*CaveBiomeMapFragment),
surfaceFragments: [4]*MapFragment, surfaceFragments: [4]*MapFragment,
pos: ChunkPosition, pos: ChunkPosition,
@ -382,7 +382,7 @@ pub const InterpolatableCaveBiomeMapView = struct {
} }
}; };
pub const CaveBiomeMapView = struct { pub const CaveBiomeMapView = struct { // MARK: CaveBiomeMapView
const CachedFractalNoise3D = terrain.noise.CachedFractalNoise3D; const CachedFractalNoise3D = terrain.noise.CachedFractalNoise3D;
super: InterpolatableCaveBiomeMapView, super: InterpolatableCaveBiomeMapView,
@ -451,6 +451,7 @@ pub const CaveBiomeMapView = struct {
} }
}; };
// MARK: cache
const cacheSize = 1 << 8; // Must be a power of 2! const cacheSize = 1 << 8; // Must be a power of 2!
const cacheMask = cacheSize - 1; const cacheMask = cacheSize - 1;
const associativity = 8; const associativity = 8;

View File

@ -12,7 +12,7 @@ const terrain = @import("terrain.zig");
const TerrainGenerationProfile = terrain.TerrainGenerationProfile; const TerrainGenerationProfile = terrain.TerrainGenerationProfile;
/// Cave data represented in a 1-Bit per block format, where 0 means empty and 1 means not empty. /// Cave data represented in a 1-Bit per block format, where 0 means empty and 1 means not empty.
pub const CaveMapFragment = struct { pub const CaveMapFragment = struct { // MARK: CaveMapFragment
pub const width = 1 << 6; pub const width = 1 << 6;
pub const widthMask = width - 1; pub const widthMask = width - 1;
pub const height = 64; // Size of u64 pub const height = 64; // Size of u64
@ -98,7 +98,7 @@ pub const CaveMapFragment = struct {
}; };
/// A generator for the cave map. /// A generator for the cave map.
pub const CaveGenerator = struct { pub const CaveGenerator = struct { // MARK: CaveGenerator
init: *const fn(parameters: JsonElement) void, init: *const fn(parameters: JsonElement) void,
deinit: *const fn() void, deinit: *const fn() void,
generate: *const fn(map: *CaveMapFragment, seed: u64) void, generate: *const fn(map: *CaveMapFragment, seed: u64) void,
@ -140,7 +140,7 @@ pub const CaveGenerator = struct {
} }
}; };
pub const CaveMapView = struct { pub const CaveMapView = struct { // MARK: CaveMapView
reference: *ServerChunk, reference: *ServerChunk,
fragments: [8]*CaveMapFragment, fragments: [8]*CaveMapFragment,
@ -297,6 +297,7 @@ pub const CaveMapView = struct {
} }
}; };
// MARK: cache
const cacheSize = 1 << 11; // Must be a power of 2! const cacheSize = 1 << 11; // Must be a power of 2!
const cacheMask = cacheSize - 1; const cacheMask = cacheSize - 1;
const associativity = 8; // 512 MiB Cache size const associativity = 8; // 512 MiB Cache size

View File

@ -56,7 +56,7 @@ pub const MapFragmentPosition = struct {
}; };
/// Generates and stores the height and Biome maps of the planet. /// Generates and stores the height and Biome maps of the planet.
pub const MapFragment = struct { pub const MapFragment = struct { // MARK: MapFragment
pub const biomeShift = 5; pub const biomeShift = 5;
/// The average diameter of a biome. /// The average diameter of a biome.
pub const biomeSize = 1 << biomeShift; pub const biomeSize = 1 << biomeShift;
@ -270,7 +270,7 @@ fn cacheInit(pos: MapFragmentPosition) *MapFragment {
return mapFragment; return mapFragment;
} }
pub fn regenerateLOD(worldName: []const u8) !void { pub fn regenerateLOD(worldName: []const u8) !void { // MARK: regenerateLOD()
std.log.info("Regenerating map LODs...", .{}); std.log.info("Regenerating map LODs...", .{});
// Delete old LODs: // Delete old LODs:
for(1..main.settings.highestLOD+1) |i| { for(1..main.settings.highestLOD+1) |i| {

View File

@ -10,7 +10,7 @@ const vec = @import("main.vec");
const Vec3f = main.vec.Vec3f; const Vec3f = main.vec.Vec3f;
const Vec3d = main.vec.Vec3d; const Vec3d = main.vec.Vec3d;
pub const SimpleStructureModel = struct { pub const SimpleStructureModel = struct { // MARK: SimpleStructureModel
const GenerationMode = enum { const GenerationMode = enum {
floor, floor,
ceiling, ceiling,
@ -74,7 +74,7 @@ pub const SimpleStructureModel = struct {
} }
}; };
const Stripe = struct { const Stripe = struct { // MARK: Stripe
direction: ?Vec3d, direction: ?Vec3d,
block: u16, block: u16,
minDistance: f64, minDistance: f64,
@ -203,7 +203,7 @@ fn u32ToVec3(color: u32) Vec3f {
} }
/// A climate region with special ground, plants and structures. /// A climate region with special ground, plants and structures.
pub const Biome = struct { pub const Biome = struct { // MARK: Biome
const GenerationProperties = packed struct(u8) { const GenerationProperties = packed struct(u8) {
// pairs of opposite properties. In-between values are allowed. // pairs of opposite properties. In-between values are allowed.
hot: bool = false, hot: bool = false,
@ -337,7 +337,7 @@ pub const Biome = struct {
}; };
/// Stores the vertical ground structure of a biome from top to bottom. /// Stores the vertical ground structure of a biome from top to bottom.
pub const BlockStructure = struct { pub const BlockStructure = struct { // MARK: BlockStructure
pub const BlockStack = struct { pub const BlockStack = struct {
blockType: u16 = 0, blockType: u16 = 0,
min: u31 = 0, min: u31 = 0,
@ -406,7 +406,7 @@ pub const BlockStructure = struct {
} }
}; };
pub const TreeNode = union(enum) { pub const TreeNode = union(enum) { // MARK: TreeNode
leaf: struct { leaf: struct {
totalChance: f64 = 0, totalChance: f64 = 0,
aliasTable: main.utils.AliasTable(Biome) = undefined, aliasTable: main.utils.AliasTable(Biome) = undefined,
@ -526,6 +526,7 @@ pub const TreeNode = union(enum) {
} }
}; };
// MARK: init/register
var finishedLoading: bool = false; var finishedLoading: bool = false;
var biomes: main.List(Biome) = undefined; var biomes: main.List(Biome) = undefined;
var caveBiomes: main.List(Biome) = undefined; var caveBiomes: main.List(Biome) = undefined;

View File

@ -23,7 +23,7 @@ const Entity = server.Entity;
const storage = @import("storage.zig"); const storage = @import("storage.zig");
const ChunkManager = struct { const ChunkManager = struct { // MARK: ChunkManager
world: *ServerWorld, world: *ServerWorld,
terrainGenerationProfile: server.terrain.TerrainGenerationProfile, terrainGenerationProfile: server.terrain.TerrainGenerationProfile,
@ -31,7 +31,7 @@ const ChunkManager = struct {
const reducedChunkCacheMask = 2047; const reducedChunkCacheMask = 2047;
var chunkCache: Cache(ServerChunk, reducedChunkCacheMask+1, 4, chunkDeinitFunctionForCache) = .{}; var chunkCache: Cache(ServerChunk, reducedChunkCacheMask+1, 4, chunkDeinitFunctionForCache) = .{};
const ChunkLoadTask = struct { const ChunkLoadTask = struct { // MARK: ChunkLoadTask
pos: ChunkPosition, pos: ChunkPosition,
creationTime: i64, creationTime: i64,
source: ?*User, source: ?*User,
@ -95,7 +95,7 @@ const ChunkManager = struct {
} }
}; };
const LightMapLoadTask = struct { const LightMapLoadTask = struct { // MARK: LightMapLoadTask
pos: terrain.SurfaceMap.MapFragmentPosition, pos: terrain.SurfaceMap.MapFragmentPosition,
creationTime: i64, creationTime: i64,
source: ?*User, source: ?*User,
@ -153,7 +153,7 @@ const ChunkManager = struct {
} }
}; };
pub fn init(world: *ServerWorld, settings: JsonElement) !ChunkManager { pub fn init(world: *ServerWorld, settings: JsonElement) !ChunkManager { // MARK: init()
const self = ChunkManager { const self = ChunkManager {
.world = world, .world = world,
.terrainGenerationProfile = try server.terrain.TerrainGenerationProfile.init(settings, world.seed), .terrainGenerationProfile = try server.terrain.TerrainGenerationProfile.init(settings, world.seed),
@ -183,7 +183,7 @@ const ChunkManager = struct {
ChunkLoadTask.scheduleAndDecreaseRefCount(pos, source); ChunkLoadTask.scheduleAndDecreaseRefCount(pos, source);
} }
pub fn generateChunk(pos: ChunkPosition, source: ?*User) void { pub fn generateChunk(pos: ChunkPosition, source: ?*User) void { // MARK: generateChunk()
if(source != null and !source.?.connected.load(.unordered)) return; // User disconnected. if(source != null and !source.?.connected.load(.unordered)) return; // User disconnected.
const ch = getOrGenerateChunkAndIncreaseRefCount(pos); const ch = getOrGenerateChunkAndIncreaseRefCount(pos);
defer ch.decreaseRefCount(); defer ch.decreaseRefCount();
@ -255,7 +255,7 @@ const ChunkManager = struct {
} }
}; };
const WorldIO = struct { const WorldIO = struct { // MARK: WorldIO
const worldDataVersion: u32 = 2; const worldDataVersion: u32 = 2;
dir: files.Dir, dir: files.Dir,
@ -311,7 +311,7 @@ const WorldIO = struct {
} }
}; };
pub const ServerWorld = struct { pub const ServerWorld = struct { // MARK: ServerWorld
pub const dayCycle: u31 = 12000; // Length of one in-game day in units of 100ms. Midnight is at DAY_CYCLE/2. Sunrise and sunset each take about 1/16 of the day. Currently set to 20 minutes pub const dayCycle: u31 = 12000; // Length of one in-game day in units of 100ms. Midnight is at DAY_CYCLE/2. Sunrise and sunset each take about 1/16 of the day. Currently set to 20 minutes
pub const earthGravity: f32 = 9.81; pub const earthGravity: f32 = 9.81;
@ -352,7 +352,7 @@ pub const ServerWorld = struct {
milliTimeStamp: i64, milliTimeStamp: i64,
}; };
pub fn init(name: []const u8, nullGeneratorSettings: ?JsonElement) !*ServerWorld { pub fn init(name: []const u8, nullGeneratorSettings: ?JsonElement) !*ServerWorld { // MARK: init()
const self = main.globalAllocator.create(ServerWorld); const self = main.globalAllocator.create(ServerWorld);
errdefer main.globalAllocator.destroy(self); errdefer main.globalAllocator.destroy(self);
self.* = ServerWorld { self.* = ServerWorld {
@ -427,7 +427,7 @@ pub const ServerWorld = struct {
} }
const RegenerateLODTask = struct { const RegenerateLODTask = struct { // MARK: RegenerateLODTask
pos: ChunkPosition, pos: ChunkPosition,
storeMaps: bool, storeMaps: bool,
@ -663,7 +663,7 @@ pub const ServerWorld = struct {
self.dropWithCooldown(stack, pos, dir, velocity, 0); self.dropWithCooldown(stack, pos, dir, velocity, 0);
} }
pub fn update(self: *ServerWorld) void { pub fn update(self: *ServerWorld) void { // MARK: update()
const newTime = std.time.milliTimestamp(); const newTime = std.time.milliTimestamp();
var deltaTime = @as(f32, @floatFromInt(newTime - self.lastUpdateTime))/1000.0; var deltaTime = @as(f32, @floatFromInt(newTime - self.lastUpdateTime))/1000.0;
self.lastUpdateTime = newTime; self.lastUpdateTime = newTime;

View File

@ -7,7 +7,7 @@ const main = @import("main.zig");
pub const file_monitor = @import("utils/file_monitor.zig"); pub const file_monitor = @import("utils/file_monitor.zig");
pub const Compression = struct { pub const Compression = struct { // MARK: Compression
pub fn deflate(allocator: NeverFailingAllocator, data: []const u8, level: std.compress.flate.deflate.Level) []u8 { pub fn deflate(allocator: NeverFailingAllocator, data: []const u8, level: std.compress.flate.deflate.Level) []u8 {
var result = main.List(u8).init(allocator); var result = main.List(u8).init(allocator);
var comp = std.compress.flate.compressor(result.writer(), .{.level = level}) catch unreachable; var comp = std.compress.flate.compressor(result.writer(), .{.level = level}) catch unreachable;
@ -86,7 +86,7 @@ pub const Compression = struct {
}; };
/// Implementation of https://en.wikipedia.org/wiki/Alias_method /// Implementation of https://en.wikipedia.org/wiki/Alias_method
pub fn AliasTable(comptime T: type) type { pub fn AliasTable(comptime T: type) type { // MARK: AliasTable
return struct { return struct {
const AliasData = struct { const AliasData = struct {
chance: u16, chance: u16,
@ -188,7 +188,7 @@ pub fn AliasTable(comptime T: type) type {
} }
/// A list that is always sorted in ascending order based on T.lessThan(lhs, rhs). /// A list that is always sorted in ascending order based on T.lessThan(lhs, rhs).
pub fn SortedList(comptime T: type) type { pub fn SortedList(comptime T: type) type { // MARK: SortedList
return struct { return struct {
const Self = @This(); const Self = @This();
@ -236,7 +236,7 @@ pub fn SortedList(comptime T: type) type {
}; };
} }
pub fn Array2D(comptime T: type) type { pub fn Array2D(comptime T: type) type { // MARK: Array2D
return struct { return struct {
const Self = @This(); const Self = @This();
mem: []T, mem: []T,
@ -277,7 +277,7 @@ pub fn Array2D(comptime T: type) type {
}; };
} }
pub fn Array3D(comptime T: type) type { pub fn Array3D(comptime T: type) type { // MARK: Array3D
return struct { return struct {
const Self = @This(); const Self = @This();
mem: []T, mem: []T,
@ -315,7 +315,7 @@ pub fn Array3D(comptime T: type) type {
}; };
} }
pub fn CircularBufferQueue(comptime T: type) type { pub fn CircularBufferQueue(comptime T: type) type { // MARK: CircularBufferQueue
return struct { return struct {
const Self = @This(); const Self = @This();
mem: []T, mem: []T,
@ -375,7 +375,7 @@ pub fn CircularBufferQueue(comptime T: type) type {
/// Allows for stack-like allocations in a fast and safe way. /// Allows for stack-like allocations in a fast and safe way.
/// It is safe in the sense that a regular allocator will be used when the buffer is full. /// It is safe in the sense that a regular allocator will be used when the buffer is full.
pub const StackAllocator = struct { pub const StackAllocator = struct { // MARK: StackAllocator
const AllocationTrailer = packed struct{wasFreed: bool, previousAllocationTrailer: u31}; const AllocationTrailer = packed struct{wasFreed: bool, previousAllocationTrailer: u31};
backingAllocator: NeverFailingAllocator, backingAllocator: NeverFailingAllocator,
buffer: []align(4096) u8, buffer: []align(4096) u8,
@ -524,7 +524,7 @@ pub const StackAllocator = struct {
}; };
/// An allocator that handles OutOfMemory situations by panicing or freeing memory(TODO), making it safe to ignore errors. /// An allocator that handles OutOfMemory situations by panicing or freeing memory(TODO), making it safe to ignore errors.
pub const ErrorHandlingAllocator = struct { pub const ErrorHandlingAllocator = struct { // MARK: ErrorHandlingAllocator
backingAllocator: Allocator, backingAllocator: Allocator,
pub fn init(backingAllocator: Allocator) ErrorHandlingAllocator { pub fn init(backingAllocator: Allocator) ErrorHandlingAllocator {
@ -599,7 +599,7 @@ pub const ErrorHandlingAllocator = struct {
}; };
/// An allocator interface signaling that you can use /// An allocator interface signaling that you can use
pub const NeverFailingAllocator = struct { pub const NeverFailingAllocator = struct { // MARK: NeverFailingAllocator
allocator: Allocator, allocator: Allocator,
IAssertThatTheProvidedAllocatorCantFail: void, IAssertThatTheProvidedAllocatorCantFail: void,
@ -760,7 +760,7 @@ pub const NeverFailingAllocator = struct {
} }
}; };
pub const NeverFailingArenaAllocator = struct { pub const NeverFailingArenaAllocator = struct { // MARK: NeverFailingArena
arena: std.heap.ArenaAllocator, arena: std.heap.ArenaAllocator,
pub fn init(child_allocator: NeverFailingAllocator) NeverFailingArenaAllocator { pub fn init(child_allocator: NeverFailingAllocator) NeverFailingArenaAllocator {
@ -796,7 +796,7 @@ pub const NeverFailingArenaAllocator = struct {
} }
}; };
pub const BufferFallbackAllocator = struct { pub const BufferFallbackAllocator = struct { // MARK: BufferFallbackAllocator
fixedBuffer: std.heap.FixedBufferAllocator, fixedBuffer: std.heap.FixedBufferAllocator,
fallbackAllocator: NeverFailingAllocator, fallbackAllocator: NeverFailingAllocator,
@ -849,7 +849,7 @@ pub const BufferFallbackAllocator = struct {
/// A simple binary heap. /// A simple binary heap.
/// Thread safe and blocking. /// Thread safe and blocking.
/// Expects T to have a `biggerThan(T) bool` function /// Expects T to have a `biggerThan(T) bool` function
pub fn BlockingMaxHeap(comptime T: type) type { pub fn BlockingMaxHeap(comptime T: type) type { // MARK: BlockingMaxHeap
return struct { return struct {
const initialSize = 16; const initialSize = 16;
size: usize, size: usize,
@ -984,7 +984,7 @@ pub fn BlockingMaxHeap(comptime T: type) type {
}; };
} }
pub const ThreadPool = struct { pub const ThreadPool = struct { // MARK: ThreadPool
const Task = struct { const Task = struct {
cachedPriority: f32, cachedPriority: f32,
self: *anyopaque, self: *anyopaque,
@ -1137,7 +1137,7 @@ pub const ThreadPool = struct {
/// An packed array of integers with dynamic bit size. /// An packed array of integers with dynamic bit size.
/// The bit size can be changed using the `resize` function. /// The bit size can be changed using the `resize` function.
pub fn DynamicPackedIntArray(size: comptime_int) type { pub fn DynamicPackedIntArray(size: comptime_int) type { // MARK: DynamicPackedIntArray
return struct { return struct {
data: []u8 = &.{}, data: []u8 = &.{},
bitSize: u5 = 0, bitSize: u5 = 0,
@ -1208,7 +1208,7 @@ pub fn DynamicPackedIntArray(size: comptime_int) type {
}; };
} }
pub fn PaletteCompressedRegion(T: type, size: comptime_int) type { pub fn PaletteCompressedRegion(T: type, size: comptime_int) type { // MARK: PaletteCompressedRegion
return struct { return struct {
data: DynamicPackedIntArray(size) = .{}, data: DynamicPackedIntArray(size) = .{},
palette: []T, palette: []T,
@ -1321,7 +1321,7 @@ pub fn PaletteCompressedRegion(T: type, size: comptime_int) type {
} }
/// Implements a simple set associative cache with LRU replacement strategy. /// Implements a simple set associative cache with LRU replacement strategy.
pub fn Cache(comptime T: type, comptime numberOfBuckets: u32, comptime bucketSize: u32, comptime deinitFunction: fn(*T) void) type { pub fn Cache(comptime T: type, comptime numberOfBuckets: u32, comptime bucketSize: u32, comptime deinitFunction: fn(*T) void) type { // MARK: Cache
const hashMask = numberOfBuckets-1; const hashMask = numberOfBuckets-1;
if(numberOfBuckets & hashMask != 0) @compileError("The number of buckets should be a power of 2!"); if(numberOfBuckets & hashMask != 0) @compileError("The number of buckets should be a power of 2!");
@ -1438,7 +1438,7 @@ pub fn Cache(comptime T: type, comptime numberOfBuckets: u32, comptime bucketSiz
} }
/// https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Unit_interval_(0,_1) /// https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Unit_interval_(0,_1)
pub fn unitIntervalSpline(comptime Float: type, p0: Float, m0: Float, p1: Float, m1: Float) [4]Float { pub fn unitIntervalSpline(comptime Float: type, p0: Float, m0: Float, p1: Float, m1: Float) [4]Float { // MARK: unitIntervalSpline()
return .{ return .{
p0, p0,
m0, m0,
@ -1447,7 +1447,7 @@ pub fn unitIntervalSpline(comptime Float: type, p0: Float, m0: Float, p1: Float,
}; };
} }
pub fn GenericInterpolation(comptime elements: comptime_int) type { pub fn GenericInterpolation(comptime elements: comptime_int) type { // MARK: GenericInterpolation
const frames: u32 = 8; const frames: u32 = 8;
return struct { return struct {
lastPos: [frames][elements]f64, lastPos: [frames][elements]f64,
@ -1587,7 +1587,7 @@ pub fn GenericInterpolation(comptime elements: comptime_int) type {
}; };
} }
pub const TimeDifference = struct { pub const TimeDifference = struct { // MARK: TimeDifference
difference: Atomic(i16) = Atomic(i16).init(0), difference: Atomic(i16) = Atomic(i16).init(0),
firstValue: bool = true, firstValue: bool = true,
@ -1606,7 +1606,7 @@ pub const TimeDifference = struct {
} }
}; };
pub fn assertLocked(mutex: *const std.Thread.Mutex) void { pub fn assertLocked(mutex: *const std.Thread.Mutex) void { // MARK: assertLocked()
if(builtin.mode == .Debug) { if(builtin.mode == .Debug) {
std.debug.assert(!@constCast(mutex).tryLock()); std.debug.assert(!@constCast(mutex).tryLock());
} }
@ -1619,7 +1619,7 @@ pub fn assertLockedShared(lock: *const std.Thread.RwLock) void {
} }
/// A read-write lock with read priority. /// A read-write lock with read priority.
pub const ReadWriteLock = struct { pub const ReadWriteLock = struct { // MARK: ReadWriteLock
condition: std.Thread.Condition = .{}, condition: std.Thread.Condition = .{},
mutex: std.Thread.Mutex = .{}, mutex: std.Thread.Mutex = .{},
readers: u32 = 0, readers: u32 = 0,

View File

@ -39,7 +39,7 @@ const NoImpl = struct {
fn removePath(_: [:0]const u8) void {} fn removePath(_: [:0]const u8) void {}
}; };
const LinuxImpl = struct { const LinuxImpl = struct { // MARK: LinuxImpl
const c = @cImport({ const c = @cImport({
@cInclude("sys/inotify.h"); @cInclude("sys/inotify.h");
@cInclude("sys/ioctl.h"); @cInclude("sys/ioctl.h");
@ -209,7 +209,7 @@ const LinuxImpl = struct {
} }
}; };
const WindowsImpl = struct { const WindowsImpl = struct { // MARK: WindowsImpl
const c = @cImport({ const c = @cImport({
@cInclude("fileapi.h"); @cInclude("fileapi.h");
}); });

View File

@ -80,7 +80,7 @@ pub fn rotateZ(self: anytype, angle: @typeInfo(@TypeOf(self)).Vector.child) @Typ
}; };
} }
pub const Mat4f = struct { pub const Mat4f = struct { // MARK: Mat4f
rows: [4]Vec4f, rows: [4]Vec4f,
pub fn identity() Mat4f { pub fn identity() Mat4f {
return Mat4f { return Mat4f {
@ -191,7 +191,7 @@ pub const Mat4f = struct {
} }
}; };
pub const Complex = struct { pub const Complex = struct { // MARK: Complex
val: Vec2d, val: Vec2d,
fn valSquare(a: Complex) f64 { fn valSquare(a: Complex) f64 {