Add: Setting to uniformly slow the acceleration and braking of realistic trains
[openttd-jgr.git] / CODINGSTYLE.md
blob555bd5f681466fd4a8dcba9391e56029fc905131
1 **Why a set coding style is important** <br>
2 This project is an open source project. To get open source working as intended, many people should be able to comprehend the code. This implies that there is a well documented and uniform flow of code.
3 That does not necessarily mean that a contributor should not write optimised yet cryptic code - one should always care about performance.  However, other developers need to understand the code which means complicated parts of code **must** have good documentation.
5 **Why we require that EVERYTHING is documented**<br>
6 What is simple to some might appear very complicated to others. Documentation helps these others. Anyone should be able to improve the code. But the main reason is, that when patch contributors want their patches added to the common codebase, the code needs to be reviewed by one or more developers. Documentation makes reviewing much easier.
8 ## Coding style for OpenTTD
9 ### Functions
10 * Function names use [CamelCase](http://www.wikipedia.org/wiki/Camelcase) without underscores.
11 * Opening curly bracket **{** for a function starts on the next line.
12 * Use Foo() instead of Foo(void).
13 ```c++
14 void ThisIsAFunction()
17 ```
19 ### Variables
20 * Variable names are all lowercase, and use "_" as separator.
21 * Global variables are preceded by an underscore. ("_") Use descriptive names because leading underscores are often used for system / compiler variables.
22 * Own members of classes should always be referenced using "this->"
23 * Pointers and references should have their reference symbol next to the name (compatibility with current code).
24 * Variables that are declared below one another should have their type, name or reference operator, and assignment operator aligned by spaces.
25 * There are set names for many variables. Those are (but not limited to): Vehicle *u, *v, *w; Station *st; Town *t; Window *w; Engine *e.
26 * For multiple instances, use numbers "*t1, *t2" or postfixes "*st_from, *st_to".
27 * Declare variables upon first usage.
28 * Declare iterators in their loop.
29 * There is a space between '*' and 'const' in "const pointers"
30 ```c++
31 int     number         = 10;
32 Vehicle *u_first_wagon = v->next;
33 int     value          = v->value;
35 uint32 _global_variable = 3750;
37 static const char * const _global_array[] = {
38         "first string",
39         "second string",
40         "another string",
41         "last string followed by comma",
44 protected:
45         char protected_array[10];
47 for (int i = 0;;);
48 ```
50 * Give the variables expedient names, this increases the readability of the code
51 ```c++
52 bool is_maglev_train = true;
53 if (!is_maglev_train) DoSomething();
54 ```
56 * Some people like to introduce copies of variables to increase readability, which can waste memory. However, in some cases, especially in code pieces which are often called, it makes sense to cache some calculated variables.
57 ```c++
58 /* Unoptimized code:
59  * foo is not touched inside the loop!
60  */
61 for (uint8 i = 0; i < 100000; i++) {
62         /* Do something */
63         if (value_to_check == (foo * 4) % 5 + 6) DoSomething();
64         /* Do something else */
67 /* Better:
68  * The used value of foo is calculated outside the loop.
69  */
70 const uint32 bar = (foo * 4) % 5 + 6;
71 for (uint8 i = 0; i < 100000; i++) {
72         /* Do something */
73         if (value_to_check == bar) DoSomething();
74         /* Do something else */
76 ```
78 ### Enumerations / static consts
79 * Enumerations store integers that belong logically together (railtypes, string IDs, etc.).
80 * Enumeration names also use CamelCase.
81 * Unscoped enumerators are all caps with "_" between the words.
82 * Scoped enumerators are use CamelCase.
83 * Enums are not used to store single numbers.
84 * Enums have consecutive numbers OR
85 * Enums have consecutive powers of two. Powers of two (bits) are written in hex or with the shift operator.
86 * Enums may have special enumerators: "_BEGIN", "\_END", and "INVALID\_").  See example.
87 * The invalid always has 0xFF, 0xFFFF, 0xFFFFFFFF as a value.
88 * Other special values are consecutively less than the invalid.
89 * Variables that hold enumerators should have the type of the enumeration.
90 ```c++
91 enum DiagDirection {
92         DIAGDIR_BEGIN = 0,
93         DIAGDIR_NE  = 0,
94         DIAGDIR_SE  = 1,
95         DIAGDIR_SW  = 2,
96         DIAGDIR_NW  = 3,
97         DIAGDIR_END,
98         INVALID_DIAGDIR = 0xFF,
99         BROKEN_DIAGDIR = 0xFE,
102 enum {
103         DEPOT_SERVICE       = (1 << 0),
104         DEPOT_MASS_SEND     = (1 << 1),
105         DEPOT_DONT_CANCEL   = (1 << 2),
106         DEPOT_LOCATE_HANGAR = (1 << 3),
109 DiagDirection enterdir = DIAGDIR_NE;
112 * Numbers that store single or uncorrelated data are static consts. Those may use the naming conventions of enums.
113 Example:
114 ```c++
115 static const int MAXIMUM_STATIONS = 42;
118 * Enums are useful in GUI code: When widgets are enumerated, they are easier to access during many operations. Additionally changes caused by modified widget sequences require less code adapting. If a widget is used like this, its enum name should be present in a comment behind the corresponding widget definition.
119 ```c++
120 /** Enum referring to the widgets of the build rail depot window */
121 enum BuildRailDepotWidgets {
122         BRDW_CLOSEBOX = 0,
123         BRDW_CAPTION,
124         BRDW_BACKGROUND,
125         BRDW_DEPOT_NE,
126         BRDW_DEPOT_SE,
127         BRDW_DEPOT_SW,
128         BRDW_DEPOT_NW,
130 /* ... */
131 /** Widget definition of the build rail depot window */
132 static const Widget _build_depot_widgets[] = {
133 {   WWT_CLOSEBOX,   RESIZE_NONE,     7,     0,    10,     0,    13, STR_00C5, STR_..},   // BRDW_CLOSEBOX
134 {    WWT_CAPTION,   RESIZE_NONE,     7,    11,   139,     0,    13, STR_...,  STR_...},  // BRDW_CAPTION
135 {      WWT_PANEL,   RESIZE_NONE,     7,     0,   139,    14,   121, 0x0,      STR_NULL}, // BRDW_BACKGROUND
136 {      WWT_PANEL,   RESIZE_NONE,    14,    71,   136,    17,    66, 0x0,      STR_..},   // BRDW_DEPOT_NE
137 {      WWT_PANEL,   RESIZE_NONE,    14,    71,   136,    69,   118, 0x0,      STR_..},   // BRDW_DEPOT_SE
138 {      WWT_PANEL,   RESIZE_NONE,    14,     3,    68,    69,   118, 0x0,      STR_..},   // BRDW_DEPOT_SW
139 {      WWT_PANEL,   RESIZE_NONE,    14,     3,    68,    17,    66, 0x0,      STR_..},   // BRDW_DEPOT_NW
140 {   WIDGETS_END},
144 * Comments on the enum values should start with "///<" to enable doxygen documentation
145 ```c++
146 enum SomeEnumeration {
147         SE_BEGIN = 0,        ///< Begin of the enumeration, used for iterations
148         SE_FOO = 0,          ///< Used for xy
149         SE_BAR,              ///< Another value of the enumeration
150         SE_SUB,              ///< Special case for z
151         SE_END,              ///< End of the enumeration, used for iterations
155 ### Control flow
156 * Put a space before the parentheses in **if**, **switch**, **for** and **while** statements.
157 * Use curly braces and put the contained statements on their own lines (e.g., don't put them directly after the **if**).
158 * Opening curly bracket **{** stays on the first line, closing curly bracket **}** gets a line to itself (except for the **}** preceding an **else**, which should be on the same line as the **else**).
159 * When only a single statement is contained, the brackets can be omitted. In this case, put the single statement on the same line as the preceding keyword (**if**, **while**, etc.). Note that this is only allowed for if statements without an **else** clause.
160 * Non-trivial fall throughs must be documented, using a `[[fallthrough]]` attribute.
161 * The NOT_REACHED() macro can be used in default constructs that should never be reached.
162 * Unconditional loops are written with **`for (;;) {`**
164 ```c++
165 if (a == b) {
166         Foo();
167 } else {
168         Bar();
171 if (very_large_checks &&
172                 spread_over_two_lines) {
173         Foo();
176 if (a == b) Foo();
178 switch (a) {
179         case 0: DoSomethingShort(); break;
181         case 1:
182                 DoSomething();
183                 [[fallthrough]];
185         case 2:
186                 DoMore();
187                 b = a;
188                 break;
190         case 3: {
191                 int r = 2;
193                 DoEvenMore(a);
194                 [[fallthrough]];
195         }
197         case 4: {
198                 int q = 345;
200                 DoIt();
201                 break;
202         }
204         default:
205                 NOT_REACHED();
208 for (int i = 0; i < 10; i++) {
209         Foo();
210         Bar();
214 ### Classes
215 * Classes names also use CamelCase.
216 * Classes should have "public", "protected", and "private" sections.
217 * Within these section the order is: types, static const members, static members, members, constructors / destructors, static methods, methods.
218 * Deviations from above order are allowed when the code dictates it (e.g. a static const is needed for a typedef)
219 * Methods and members ought to be grouped logically.
220 * All those sorting rules sometimes conflict which one another. Please use common sense what increases legibility of the code in such a case.
221 * The method implementation should indicate if it is virtual or similar by using a comment.
222 * Very short methods can have one-line definition (if defined in the class scope).
223 ```c++
224 class ThisIsAClass {
225 public:
226         typedef Titem_   *ItemPtr;
227 private:
228         static const int MAX_SIZE = 500;
229         int              size;
230         ItemPtr          *items;
232 public:
233         explicit ThisIsAClass();
234         ~ThisIsAClass();
236         int GetSize() { return this->size; }
237         virtual void Method();
240 /*virtual*/ void Class::Method()
242         this->size *= 2;
246 ### Templates
247 Templates are a very powerful C++ tool, but they can easily confuse beginners. Thus:
248 * Templates are to be documented in a very clear and verbose manner. Never assume anything in the documentation.
249 * the template keyword and the template layout get a separate line. typenames are either "T" or preceded by a "T", integers get a single capital letter or a descriptive name preceded by "T".
250 ```c++
251 template <typename T, typename Tsomething, int N, uint8_t Tnumber_of_something>
252 int Func();
255 * If you are writing one or more template class in the dedicated header file, use file.hpp for its name instead of file.h. This will let others know that it is template library (includes also implementation), not just header with declarations.
257 ### Other important rules
258 * Put a space before and after binary operators: "a + b", "a == b", "a & b", "a <<= b", etc.. Exceptions are ".", "->" and "[]" (no spaces) and "," (just space after it).
259 * Put parenthesis where it improves readability: "*(b++)" instead of "*b++", and "if ((a & b) && c == 2)" instead of "if (a & b && c == 2)".
260 * Do not put external declarations in implementation (i.e. cpp) files.
261 * Use const where possible.
262 * Do not typedef enums and structs.
263 * Don't treat non-flags as flags: use "if (char_pointer != nullptr && *char_pointer != '\0')", not "if (char_pointer && *char_pointer)".
264 * Use "free(p)" instead of "if (p != nullptr) free(p)". "free(nullptr)" doesn't hurt anyone.
265 * No trailing whitespace. The Github workflows will not allow tabs or space on the end of lines.
266 * Only use tabs to indent from the start of the line.
267 * Line length is unlimited. In practice it may be useful to split a long line. When splitting, add two tabs in front of the second part.
268 * The '#' of preprocessor instructions goes into the first column of a line. Indenting is done after the '#' (using tabs again).
269 * Use /* */ for single line comments.
270 * Use // at the end of a command line to indicate comments.
271 ** However, use /* */ after # preprocessor statements as // causes warnings in some compilers and/or might have unwanted side effects.
272 * C++ is defined using the ASCII character set. Do not use other character sets, not even in comments.
273 * OpenTTD includes some Objective-C sources (*.mm, used by OSX), which has a special object method invocation syntax: "[ obj doStuff:foo ]". Please use spaces on the inside of the brackets to differentiate from the C array syntax.
275 ## Documentation
276 We use [Doxygen](http://doxygen.org/) to automatically generate documentation from the source code. It scans the source files for *recognizable* comments.
277 * **Make your comments recognizable.**
278 Doxygen only comments starting with the following style:
279 ```c++
281 ///<
284 Use /** for multi-line comment blocks. Use ///< for single line comments for variables. Use //!< for single-line comments in the NoAI .hpp files.
285 For comments blocks inside a function always use /* */ or //. Use // only if the comment is on the same line as an instruction, otherwise use /* */.
287 ### Files
288 * Put a @file command in a JavaDoc style comment at the start of the file, followed by a description.
289 ```c++
291  * @file
292  * This is the brief description.
293  * This is the detailed description here and on the following lines.
294  */
296 > ### Warning
297 > If a file lacks a **file comment block** then NO entities in that file will be documented by Doxygen!
299 ### Functions
300 * The documentation should be as close to the actual code as possible to maximise the chance of staying in sync.
301         * Comments for functions go in the .cpp file.
302         * Comments for inlines go in the .h/.hpp file.
303 * Small inlines can have a short 3 or 4 line JavaDoc style comment.
304 * Completely document larger functions.
305 * Document obvious parameters and return values too!
307 ```c++
309  * A brief explanation of what the function does and/or what purpose it serves.
310  * Then follows a more detailed explanation of the function that can span multiple lines.
312  * @param foo Explanation of the foo parameter
313  * @param bar Explanation of the bar parameter
314  * @return The sum of foo and bar (@return can be omitted if the return type is void)
316  * @see SomeOtherFunc()
317  * @see SOME_ENUM
319  * @bug Some bug description
320  * @bug Another bug description which continues in the next line
321  *           and ends with the following blank line
323  * @todo Some to-do entry
324  */
325 static int FooBar(int foo, int bar)
327         return foo + bar;
331 ### Classes
332 * Document structs similarly to functions:
333 ```c++
335  * A short description of the struct.
336  * More detailed description of the its usage.
338  * @see [link to anything of interest]
339  */
340 struct foo {
344 ### JavaDoc structural commands
346 This table shows the commands you should use with OpenTTD.  The full list is [here](http://www.stack.nl/~dimitri/doxygen/commands.html).
348 | Command | Action | Example |
349 | ------- | -------- | ------- |
350 | **@attention** | Starts a paragraph where a message that needs attention may be entered. The paragraph will be indented. | @attention Whales crossing! |
351 | **@brief** | Starts a paragraph that serves as a brief description. For classes and files the brief description will be used in lists and at the start of the documentation page. For class and file members, the brief description will be placed at the declaration of the member and prepended to the detailed description. A brief description may span several lines (although it is advised to keep it brief!). | @brief This is the brief description. |
352 | **@bug** | Starts a paragraph where one or more bugs may be reported. The paragraph will be indented. Multiple adjacent @bug commands will be joined into a single paragraph. Each bug description will start on a new line. Alternatively, one @bug command may mention several bugs. | @bug Memory leak in here? |
353 | **@note** | Starts a paragraph where a note can be entered. The paragraph will be indented. | @note Might be slow |
354 | **@todo** | Starts a paragraph where a TODO item is described. The description will also add an item to a separate TODO list. The two instances of the description will be cross-referenced. Each item in the TODO list will be preceded by a header that indicates the origin of the item. | @todo Better error checking |
355 | **@warning** | Starts a paragraph where one or more warning messages may be entered. The paragraph will be indented. | @warning Not thread safe! |
356 | | <small>**Function related commands**</small> | |
357 | **@return** | Starts a return value description for a function. | @return a character pointer |
358 | **@param** | Starts a parameter description for a function parameter with name <parameter-name>. Followed by a description of the parameter. The existence of the parameter is checked and a warning is given if the documentation of this (or any other) parameter is missing or not present in the function declaration or definition.<br><br>The @param command has an optional attribute specifying the direction of the attribute. Possible values are "in" and "out". | @param  n    The number of bytes to copy<br>@param[out] dest The memory area to copy to.<br>@param[in]  src  The memory area to copy from. |
359 | **@see** | Starts a paragraph where one or more cross-references to classes, functions, methods, variables, files or URL may be specified. Two names joined by either :: or # are understood as referring to a class and one of its members. One of several overloaded methods or constructors may be selected by including a parenthesized list of argument types after the method name. [Here](http://www.stack.nl/~dimitri/doxygen/autolink.html) you can find detailed information about this feature. | @see OtherFunc() |
360 | **@b** | Displays the following word using a bold font. Equivalent to &lt;b&gt;word&lt;/b&gt;. To put multiple words in bold use &lt;b&gt;multiple words&lt;/b&gt;.| ...@b this and @b that... |
361 | **@c / @p** | Displays the parameter <word> using a typewriter font. You can use this command to refer to member function parameters in the running text. To have multiple words in typewriter font use &lt;tt&gt;multiple words&lt;/tt&gt;. | ... the @p x and @p y coordinates are used to... |
362 | **@arg / @li** | This command has one argument that continues until the first blank line or until another @arg / @li is encountered. The command can be used to generate a simple, not nested list of arguments. Each argument should start with an @arg / @li command. | @arg @c AlignLeft left alignment.<br>@arg @c AlignCenter center alignment.<br>@arg @c AlignRight right alignment |
363 | **@n** | Forces a new line. Equivalent to and inspired by the printf function. |@n |
365 ### More on Doxygen and JavaDoc
367 Doxygen knows two different kinds of comments:
368 * *Brief descriptions*: one-liners that describe the function roughly ([example](http://docs.openttd.org/annotated.html))
369 * *Detailed descriptions*: as the name suggests, these contain the detailed function/purpose of the entity they describe ([example](http://docs.openttd.org/structBridge.html))
371 You can omit either one or put them into different places but there's only one brief and one detailed description allowed for the same entity.
373 Doxygen knows three modes for documenting an entity:
374 * Before the entity
375 * After the entity
376 * In a different file
378 The latter is a little harder to maintain since the prototype of the entity it describes then is stored in several places (e.g. the .h file and the file with the descriptions). Also while it makes the code easier to read it also makes it easier to omit the important step of updating the description of an entity if it was changed - and we all know why that shouldn't happen ;)<br>
379 Because of those reasons, we will only use the first two documentation schemes.
382 Doxygen supports both Qt and JavaDoc comment styles:
383 * Qt style example: **int i; //!< The counter for the main loop**
384 * JavaDoc style example: **int i; /*\*< The counter for the main loop \*/**
386 It also supports more comment styles but those two are the ones which are standardized. For OTTD we'll be using the JavaDoc style. One of the reasons is that it has a feature that the Qt style doesn't offer: JavaDoc style comment blocks will automatically start a brief description which ends at the first dot followed by a space or new line. Everything after that will also be part of the detailed description.
388 The general structure of a JavaDoc style comment is
389 ```c++
391  * This is the brief description. And this sentence contains some further explanations that will appear in the detailed description only.
392  */
395 and the resulting descriptions of that block would be:
396 * *Brief description*: This is the brief description.
397 * *Detailed description*: This is the brief description. And this sentence contains some further explanations that will appear in the detailed description only.
399 The distinction between the brief and detailed descriptions is made by the dot followed by a space/newline, so if you want to use that inside the brief description you need to escape the space/newline:
400 ```c++
402  * This is a brief description (e.g.\ using only a few words). Details go here.
403  */
406 If you're doing a one-line comment, use:
407 ```c++
408 int i; ///< This is the description.
411 Also in the comment block you can include so-called structural commands which tell Doxygen what follows. In general, their area of effect begins after the command word and ends when a blank line or some other command is encountered. Also, multiple occurrences of the same structural command within a comment block or the referring entity will be joined in the documentation output usually.
413 ## Commit message
414 To achieve a coherent whole and to make changelog writing easier, here are some guidelines for commit messages.
415 There is a check-script on the git server (also available for clients, see below) to make sure we all follow those rules.
417 The first line of a message must match:
419 <keyword>( #<issue>|<commit>(, (#<issue>|<commit>))*)?: ([<component>])? <details>
422 Keywords can either be player-facing, NewGRF / Script author-facing, or developer-facing.
424 For player-facing changes, we have these keywords:
425 * Feature: Adding a significant new functionality to the game. This can be small in code-size, but is meant for the bigger things from a player perspective.
426 * Add: Similar to Feature, but for small functionalities.
427 * Change: Changing existing behaviour to an extent the player needs to know about it.
428 * Fix: Fixing an issue with the game (as seen by the player).
429 * Remove: Completely removing a functionality.
430 * Revert: Reverting an earlier Feature / Add / Change / Fix / Remove.
431 * Doc: Update to (player-facing) documentation, like in the `docs/` folder etc.
432 * Update: Translator commits.
434 For NewGRF / Script author-facing changes, we use the same keywords as player-facing changes, followed by `[NewGRF]` / `[Script]` component.
435 This also means the commit is aimed (and worded) towards the NewGRF / Script authors, rather than players.
437 For developer-facing changes, we have these keywords:
438 * Codechange: Changes to the code the player is not going to notice. Refactors, modernization, etc.
439 * Cleanup: Similar to Codechange, but when it is more about removing old code, rather than an actual change.
440 * Codefix: Fixing problems in earlier commits that the player is not actually going to notice. Wrong comments, missing files, CI changes.
442 If you commit a `Fix` for an [issue](https://github.com/OpenTTD/OpenTTD/issues), add the corresponding issue number in the form of #NNNNN.
444 In the case of `Fix`es, if you know the hash of the commit in which the bug was introduced (eg regression), please mention that hash (the first 7 characters) as well just after the keyword (or, if present, after the issue number).
445 Finding the trouble-causing commit is highly encouraged as it makes backporting / branching / releases that much easier.
447 Do not mention two keywords; if two apply, pick one that best represents the commit (for example, "Fix #123" is mostly always better than "Revert", even if both are true).
449 The `<details>` part starts with a capital and does not end with a dot.
450 Try to be descriptive to what the player will notice, not to what is actually being changed in the code.
451 See `changelog.txt` for inspiration.
453 To further structure the changelog, you can add components. Example are:
454 * "Network" for network specific changes.
455 * "NewGRF" for NewGRF additions.
456 * "Script" for AI / GS additions.
457 * "YAPF", "NPF", for changes in these features.
458 * "MacOS", "Linux", "Windows", for OS-specific changes.
459 * "CI", "CMake", for changes to the (build) infrastructure.
461 Further explanations, more details, etc. don't go into the first line. Use a new line for those.
463 Complete examples:
464 * `Fix: [YAPF] Infinite loop in pathfinder`
465 * `Fix #5926: [YAPF] Infinite loop in pathfinder`
466 * `Codefix 80dffae: Warning about unsigned unary minus`
467 * `Fix #6673, 99bb3a9: Store the map variety setting in the savegame`
468 * `Codefix #5922: ClientSizeChanged is only called via WndProcGdi which already has the mutex`
469 * `Codechange #1264, #2037, #2038, #2110: Rewrite the autoreplace kernel`
472 ## Other tips
473 ### Remove trailing whitespace
474 To find out if/where you have trailing whitespace, you can use the following (unix/bash) command:
476 grep -n -R --include "*.[ch]" '[        ]$' * | grep --invert-match ".diff" | grep --invert-match ".patch"
478 Automatically removing whitespace is also possible with the following shell script (Note that it only checks .c, .cpp, .h, .hpp and .mm files):
480 #!/bin/sh
481 IFS='
483 for i in Makefile `find . -name \*.c -o -name \*.cpp -o -name \*.h -o -name \*.hpp -o -name \*.mm`
485   (
486         echo '%s/[      ]\{1,\}$/'
487         echo w
488         echo q
489   ) | ed $i 2> /dev/null > /dev/null
490 done
493 ### Install the client-side git commit hooks
495 The client-side hooks perform various checks when you commit changes locally.
496 * Whitespace and indentation checks.
497 * **Coding style** checks.
499 Get the hooks:
501 git clone https://github.com/OpenTTD/OpenTTD-git-hooks.git openttd_hooks
504 Install the hooks, assuming "openttd" is your work tree folder:
506 cd openttd/.git/hooks
507 ln -s -t . ../../../openttd_hooks/hooks/*