Code Style
Language
The engine is C++23. Prefer the standard facilities it adds over the older workarounds, and do not lower the level to suit a compiler that the requirements page does not list.
Clang-format
Format all C++ code with clang-format 21. The config file is in the repository root. If your editor supports format-on-save,
enable it. Otherwise format before you commit, and check the result with
clang-format --dry-run --Werror <files>.
Dependencies stay out of automatic formatting. They rarely match Voxelius style.
Notable settings:
| Settings | Value |
|---|---|
| Column limit | 140 |
| Indentation | 4 spaces |
| Line endings | CRLF |
| Braces | Custom, see below |
| Pointer alignment | Left |
| Reference alignment | Left |
NOTE: If formatting looks wrong, do not edit
.clang-formatfirst. Split the code into smaller chunks so clang-format can handle it better.
Naming
| Kind | Style | Example |
|---|---|---|
| Files | snake_case | shared/block_storage.cc |
| Namespaces | snake_case | namespace block_storage |
| Classes and structures | PascalCase | class ReadBuffer |
| Functions and methods | snake_case | block_registry::name_of(...) |
| Public fields and members | snake_case | BlockDefinition::model_offset |
| Private fields and members | m_snake_case | Chunk::m_blocks |
| Constants | UPPER_SNAKE_CASE | BASE_WIDTH |
| Enumeration types | snake_case | enum class task_status |
| Enumeration values | UPPER_SNAKE_CASE | task_status::ENQUEUED |
| Type aliases | snake_case | using block_tag_bit = std::uint32_t; |
- Two names must differ by more than capitalization:
world_scopeandWorldScoperead as the same name, so keep one of them. - A cvar binding takes the cvar name and the
_bindingsuffix:auto& gr_weather_cycle_binding = cvar::bind_var(weather, "gr_weather_cycle");, notweather_binding.
Brace newlines
- Functions, methods, and namespaces put the opening brace on a new line.
- Classes, structs, enums, unions, control statements, and lambdas keep the brace on the same line.
- Put
elseandcatchon a new line after the closing brace. Two braces and a keyword on one line are hard to read.
Example:
namespace vx
{
void setup(void);
void teardown(void);
} // namespace vx
void vx::setup(void)
{
// empty
}
void vx::teardown(void)
{
Type name {};
name.do_something();
if(name.valid()) {
// ...
}
else {
// ...
}
}
Styling considerations
- Mark classes and structures
finalunless they are meant as a base. - A structure that gains a method becomes a class. A structure holds fields and no behavior.
- A tag structure stays a structure. It holds no fields, declares only static members, and marks a template argument.
- Functions and methods with zero arguments use C-style
voidinside the parentheses. - Do not silence an unused value with a
voidcast ((void)x;,static_cast<void>(x);). - Name every parameter, including an unused one (
void f(int x, int y)). An unnamed parameter of a fundamental type makesfunction(char)read likefunction(void). Disable the unused-parameter warning for that function or translation unit instead. - Place
constexprfunction bodies in the header, just after the declarations. - Do not repeat a
constthe initializer already carries. When a function returns a const reference,auto&is enough andconst auto&is noise. - Write
autoeven when the deduction yields a pointer (auto world = WorldScope::active();), notauto*. - When a block of locals comes from deduction, keep them all on
auto. Do not spell the type between them. Put it in the initializer instead:auto elapsed = std::chrono::system_clock::duration(now.time_since_epoch());. - C++ headers use
.hh. C++ sources use.cc. - You may use profanity in source code. I own the code and can comment as I choose.
- Use standard
assertfor debug-time checks. Report a failure withvx::throw_iforvx::throw_if_notfromcore/exception.hh.maincatches the exception, logs it and returns a failure code. - Test a pointer or a handle by itself when it must be present. Compare it with the null value when it must be absent:
if(ptr)andif(ptr == nullptr),if(handle)andif(handle == BIOME_ID_NULL). A count follows the same split. Never write the absent case as a negation or an inequality (if(!ptr),if(!handle),!= 0,!= nullptr), and keep negating a call that only reports a condition:if(!load(path)),if(!value.has_value()). - Test a bitmask against zero explicitly:
if(0 == (flags & FLAG)), notif(!(flags & FLAG)). - Use a ternary only for a short pick between constants, written
cond ? a : bwith spaces around both operators. A call, a dereference or another non-trivial operand on either side meansif/else. - No standalone
++xorx--statement: writex += 1orx -= 1. An iterator advances withstd::next(it). - A
forheader has all three parts or none. A loop that fills two of them is awhilewith the step at the end of its body. - A
switchcase does not open a scope. Move a body that needs locals into a function. - Do not chain on a call result through a pointer (
registry().find(id)->name,map.find(key)->second). Put it in a named local first. A short dot chain reads as one operation and may stay in place:dispatcher.sink<Event>().connect<&handler>(). A chain of three or more calls goes into named locals. Do not nest calls deeper than one level. Do not put a call in the middle of another call’s arguments. A call as the only or the last argument is fine. - Keep the registration calls together: a run of
dispatcher.sink<Event>().connect<&handler>()lines has no blank lines inside it, and one blank line separates a different group of events. - Keep a condition to three operands joined by
&&or||, on one line. Name the parts inboollocals or split the test. - Do not initialize a structure with its fields on one line: designated fields one per line with a trailing comma, or
{}and assign after. File-scope tables keep their initializers. - Give a non-trivial size or index expression a name instead of writing it inline.
Include guards
- Every header uses an ifndef block with a random GUID-style token. Dashes become underscores.
- Do not use
#pragma once. - End the ifndef block with a block comment that repeats the same GUID.
Example:
#ifndef B843EAA9_60C3_4C2B_8036_DF1026035AA8
#define B843EAA9_60C3_4C2B_8036_DF1026035AA8
// ...
#endif /* B843EAA9_60C3_4C2B_8036_DF1026035AA8 */
NOTE: This matches the default behaviour of the C/C++ Include Guard VSCode extension.
Namespaces
- Do not qualify a name with its own namespace when the code already sits inside it.
- Namespaces follow modules. The same header often reopens a namespace per logical group. Put internal or private types in a
detailsub-namespace. - Every closing brace gets a
// namespace namecomment. Clang-format enforces this.
Example:
namespace vx::detail
{
class Exception {
// ...
};
} // namespace vx::detail
namespace vx
{
using runtime_error = detail::TaggedException<struct runtime_error_tag>;
} // namespace vx
Include grouping
- Each engine module has its own precompiled header. Include it first in every compiled source.
- Sort includes by dependency order (for example
core, thenshared, thenclient). - Within a group, clang-format sorts includes alphabetically.
Example:
#include "client/pch.hh"
#include "client/game.hh"
#include "core/buffer.hh"
#include "core/exception.hh"
#include "core/identifier.hh"
#include "core/res/resource.hh"
#include "shared/block_registry.hh"
#include "shared/block_storage.hh"
#include "shared/coord.hh"
#include "shared/mod_loader.hh"
#include "shared/utils/coord.hh"
#include "shared/utils/lua.hh"
#include "shared/world.hh"
#include "client/globals.hh"
#include "client/res/texture_2d.hh"
Order in a file
Every translation unit keeps the same top-level order:
- includes.
- forward declarations.
- compile-time constants:
constexpr,static constexprand object-like#defines. - type definitions:
using,enum,structandclass. - read-only data such as
static const char* const names[] = { ... }. - static and global variables, in any order among themselves.
- static functions and other functions with internal linkage.
- public functions, including out-of-line member definitions.
- A constant belongs in the constant block and a helper belongs in the static function block. Do not put either next to its first use between functions of another kind.
- Static functions go in dependency order, callees first. A static prototype is only necessary for mutual recursion.
- A table of callbacks or a registration list goes right after the last function it points to.
- Function-like macros and
static_asserts stay next to what they belong to. - Headers follow the same order. A
constexprbody stays right after its declaration.
Class bodies
- Use one access block per class:
public, thenprotected, thenprivate. Do not repeat a specifier. - Statics come first: the constants and the static methods.
- After them the constructor and destructor (plus
operator=), the non-static methods, then the fields. - A static member comes before a non-static one. A field comes after every method.
Comments
- Use plain C++ comments (except for include guards).
- A comment is the exception. Leave one only for what the code cannot carry: a measurement, a tuning value, a batch size, a protocol quirk, an outside requirement, or the reason behind a construct that looks wrong.
- Never restate what the code next to it does.
- Before you write a comment, try to remove the need for it. Rename the value (
free_slots, notslots // A set bit means free), move the code into a function whose name says what it does, or turn the claim into astatic_assert. - Do not describe the algorithm of a function above it. A precondition or an ownership rule that every caller must respect stays at the declaration: in the header for a public function, at the definition for a static one. A guarantee that only some callers rely on goes at those call sites, as the reason the caller is correct.
- A field, a constant or a local gets no comment that repeats its name, frame, units, axis or range. If the value needs that
text, write it once in the type or the schema. A comment that explains a field is a missing rename:
local_box,axis_contacts,volume_fraction. - Keep the measurement or the outside rule with the value it chose:
// 64 keeps the upload under the 1 MiB limit, not// batch size. Keep the reason with the strange construct:// The server applies the client state on purpose; the client cannot rebuild it. - A comment that fails this test is removed in review. Do not add one to look helpful.
- Read the existing comments for the tone.
- Write a comment in Simplified Technical English: short sentences, one statement per sentence, active voice, present tense, and one meaning per word.
- Write a comment that needs following up as a tagged one:
TODO:,UNDONE:,FIXME:orNOTE:. Keep it to the line limit and write it in the same plain wording as the prose. - Do not leave commented-out code behind. Delete it.
- Mark empty function or method bodies with
// empty.
Example 1:
explicit Exception(std::string_view what, std::source_location location = std::source_location::current())
{
// empty
}
Example 2:
// NOTE: SDL seems to defer handle release until the GPU
// is truly done with the object, so it's probably safe
// to even release the old handle mid-frame
reset();