Fix #10490: Allow ships to exit depots if another is not moving at the exit point...
[openttd-github.git] / src / stdafx.h
blob5fc27f4dcc6f26a1b9d08e274c5715bde5a43830
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file stdafx.h Definition of base types and functions in a cross-platform compatible way. */
10 #ifndef STDAFX_H
11 #define STDAFX_H
13 #if defined(_WIN32)
14 /* MinGW defaults to Windows 7 if none of these are set, and they must be set before any MinGW header is included */
15 # define NTDDI_VERSION NTDDI_WINXP // Windows XP
16 # define _WIN32_WINNT 0x501 // Windows XP
17 # define _WIN32_WINDOWS 0x501 // Windows XP
18 # define WINVER 0x0501 // Windows XP
19 # define _WIN32_IE_ 0x0600 // 6.0 (XP+)
20 #endif
22 #ifdef _MSC_VER
23 /* Stop Microsoft (and clang-cl) compilers from complaining about potentially-unsafe/potentially-non-standard functions */
24 # define _CRT_SECURE_NO_DEPRECATE
25 # define _CRT_SECURE_NO_WARNINGS
26 # define _CRT_NONSTDC_NO_WARNINGS
27 #endif
29 #if defined(__APPLE__)
30 # include "os/macosx/osx_stdafx.h"
31 #endif /* __APPLE__ */
33 #if defined(__HAIKU__)
34 # include <SupportDefs.h>
35 # include <unistd.h>
36 # define _DEFAULT_SOURCE
37 # define _GNU_SOURCE
38 #endif
40 /* It seems that we need to include stdint.h before anything else
41 * We need INT64_MAX, which for most systems comes from stdint.h. However, MSVC
42 * does not have stdint.h.
43 * For OSX the inclusion is already done in osx_stdafx.h. */
44 #if !defined(__APPLE__) && (!defined(_MSC_VER) || _MSC_VER >= 1600)
45 # define __STDC_LIMIT_MACROS
46 # include <stdint.h>
47 #endif
49 #include <algorithm>
50 #include <array>
51 #include <bit>
52 #include <cassert>
53 #include <cctype>
54 #include <cerrno>
55 #include <climits>
56 #include <cmath>
57 #include <cstddef>
58 #include <cstdint>
59 #include <cstdio>
60 #include <cstring>
61 #include <cstdlib>
62 #include <cwchar>
63 #include <deque>
64 #include <exception>
65 #include <functional>
66 #include <iterator>
67 #include <list>
68 #include <limits>
69 #include <map>
70 #include <memory>
71 #include <numeric>
72 #include <optional>
73 #include <set>
74 #include <span>
75 #include <stdexcept>
76 #include <string>
77 #include <type_traits>
78 #include <variant>
79 #include <vector>
81 #if defined(UNIX) || defined(__MINGW32__)
82 # include <sys/types.h>
83 #endif
85 /* Stuff for GCC */
86 #if defined(__GNUC__) || (defined(__clang__) && !defined(_MSC_VER))
87 # define CDECL
88 #endif /* __GNUC__ || __clang__ */
90 #if __GNUC__ > 11 || (__GNUC__ == 11 && __GNUC_MINOR__ >= 1)
91 # define NOACCESS(args) __attribute__ ((access (none, args)))
92 #else
93 # define NOACCESS(args)
94 #endif
96 #if defined(_WIN32)
97 # define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
98 #endif
100 #if defined(_MSC_VER)
101 // See https://learn.microsoft.com/en-us/cpp/cpp/empty-bases?view=msvc-170
102 # define EMPTY_BASES __declspec(empty_bases)
103 #else
104 # define EMPTY_BASES
105 #endif
107 /* Stuff for MSVC */
108 #if defined(_MSC_VER)
109 # pragma once
110 # define NOMINMAX // Disable min/max macros in windows.h.
112 # pragma warning(disable: 4244) // 'conversion' conversion from 'type1' to 'type2', possible loss of data
113 # pragma warning(disable: 4761) // integral size mismatch in argument : conversion supplied
114 # pragma warning(disable: 4200) // nonstandard extension used : zero-sized array in struct/union
115 # pragma warning(disable: 4355) // 'this' : used in base member initializer list
117 # if (_MSC_VER < 1400) // MSVC 2005 safety checks
118 # error "Only MSVC 2005 or higher are supported. MSVC 2003 and earlier are not! Upgrade your compiler."
119 # endif /* (_MSC_VER < 1400) */
120 # pragma warning(disable: 4291) // no matching operator delete found; memory will not be freed if initialization throws an exception (reason: our overloaded functions never throw an exception)
121 # pragma warning(disable: 4996) // 'function': was declared deprecated
122 # pragma warning(disable: 6308) // code analyzer: 'realloc' might return null pointer: assigning null pointer to 't_ptr', which is passed as an argument to 'realloc', will cause the original memory block to be leaked
123 # pragma warning(disable: 6011) // code analyzer: Dereferencing NULL pointer 'pfGetAddrInfo': Lines: 995, 996, 998, 999, 1001
124 # pragma warning(disable: 6326) // code analyzer: potential comparison of a constant with another constant
125 # pragma warning(disable: 6031) // code analyzer: Return value ignored: 'ReadFile'
126 # pragma warning(disable: 6246) // code analyzer: Local declaration of 'statspec' hides declaration of the same name in outer scope. For additional information, see previous declaration at ...
128 # if (_MSC_VER == 1500) // Addresses item #13 on http://blogs.msdn.com/b/vcblog/archive/2008/08/11/tr1-fixes-in-vc9-sp1.aspx, for Visual Studio 2008
129 # define _DO_NOT_DECLARE_INTERLOCKED_INTRINSICS_IN_MEMORY
130 # include <intrin.h>
131 # endif
133 # if (_MSC_VER < 1900)
134 # define inline __forceinline
135 # endif
137 # define CDECL _cdecl
139 # if defined(_WIN32) && !defined(_WIN64)
140 # if !defined(_W64)
141 # define _W64
142 # endif
144 typedef _W64 int INT_PTR, *PINT_PTR;
145 typedef _W64 unsigned int UINT_PTR, *PUINT_PTR;
146 # endif /* _WIN32 && !_WIN64 */
148 # if defined(_WIN64)
149 # define fseek _fseeki64
150 # endif /* _WIN64 */
152 /* zlib from vcpkg use cdecl calling convention without enforcing it in the headers */
153 # if defined(WITH_ZLIB)
154 # if !defined(ZEXPORT)
155 # define ZEXPORT CDECL
156 # endif
157 # endif
159 /* freetype from vcpkg use cdecl calling convention without enforcing it in the headers */
160 # if defined(WITH_FREETYPE)
161 # if !defined(FT_EXPORT)
162 # define FT_EXPORT( x ) extern "C" x CDECL
163 # endif
164 # endif
166 /* liblzma from vcpkg (before 5.2.4-2) used to patch lzma.h to define LZMA_API_STATIC for static builds */
167 # if defined(WITH_LIBLZMA)
168 # if !defined(LZMA_API_STATIC)
169 # define LZMA_API_STATIC
170 # endif
171 # endif
173 /* MSVC doesn't have these :( */
174 # define S_ISDIR(mode) (mode & S_IFDIR)
175 # define S_ISREG(mode) (mode & S_IFREG)
177 #endif /* defined(_MSC_VER) */
179 #if !defined(STRGEN) && !defined(SETTINGSGEN)
180 # if defined(_WIN32)
181 char *getcwd(char *buf, size_t size);
182 # include <io.h>
183 # include <tchar.h>
185 # define fopen(file, mode) _wfopen(OTTD2FS(file).c_str(), _T(mode))
186 # define unlink(file) _wunlink(OTTD2FS(file).c_str())
188 std::string FS2OTTD(const std::wstring &name);
189 std::wstring OTTD2FS(const std::string &name);
190 # elif defined(WITH_ICONV)
191 # define fopen(file, mode) fopen(OTTD2FS(file).c_str(), mode)
192 std::string FS2OTTD(const std::string &name);
193 std::string OTTD2FS(const std::string &name);
194 # else
195 // no override of fopen() since no transformation is required of the filename
196 template <typename T> std::string FS2OTTD(T name) { return name; }
197 template <typename T> std::string OTTD2FS(T name) { return name; }
198 # endif /* _WIN32 or WITH_ICONV */
199 #endif /* STRGEN || SETTINGSGEN */
201 #if defined(_WIN32)
202 # define PATHSEP "\\"
203 # define PATHSEPCHAR '\\'
204 #else
205 # define PATHSEP "/"
206 # define PATHSEPCHAR '/'
207 #endif
209 #if defined(_MSC_VER)
210 # define PACK_N(type_dec, n) __pragma(pack(push, n)) type_dec; __pragma(pack(pop))
211 #elif defined(__MINGW32__)
212 # define PRAGMA(x) _Pragma(#x)
213 # define PACK_N(type_dec, n) PRAGMA(pack(push, n)) type_dec; PRAGMA(pack(pop))
214 #else
215 # define PACK_N(type_dec, n) type_dec __attribute__((__packed__, aligned(n)))
216 #endif
217 #define PACK(type_dec) PACK_N(type_dec, 1)
220 * When making a (pure) debug build, the compiler will by default disable
221 * inlining of functions. This has a detremental effect on the performance of
222 * debug builds, especially when more and more trivial (wrapper) functions get
223 * added to the code base.
224 * Take for example the savegame called "Wentbourne", when running this game
225 * for 100 ticks with the null video driver a number of fairly trivial
226 * functions show up on top. The most common one is the implicit conversion
227 * operator of TileIndex to unsigned int, which takes up over 5% of the total
228 * run time and functionally does absolutely nothing. The remaining functions
229 * for the top 5 are GB, GetTileType, Map::Size and IsTileType to a total of
230 * about 12.5% of the game's total run time.
231 * It is possible to still force inlining in the most commonly used compilers,
232 * but that is at the cost of some problems with debugging due to the forced
233 * inlining. However, the performance benefit can be enormous; when forcing
234 * inlining for the previously mentioned top 5, the debug build ran about 15%
235 * quicker.
236 * The following debug_inline annotation may be added to functions comply
237 * with the following preconditions:
238 * 1: the function takes more than 0.5% of a profiled debug runtime
239 * 2: the function does not modify the game state
240 * 3: the function does not contain selection or iteration statements,
241 * i.e. no if, switch, for, do, while, etcetera.
242 * 4: the function is one line of code, excluding assertions.
243 * 5: the function is defined in a header file.
244 * The debug_inline annotation must be placed in front of the function, i.e.
245 * before the optional static or constexpr modifier.
247 #if !defined(_DEBUG) || defined(NO_DEBUG_INLINE)
249 * Do not force inlining when not in debug. This way we do not work against
250 * any carefully designed compiler optimizations.
252 #define debug_inline inline
253 #elif defined(__clang__) || defined(__GNUC__)
254 #define debug_inline [[gnu::always_inline]] inline
255 #else
257 * MSVC explicitly disables inlining, even forced inlining, in debug builds
258 * so __forceinline makes no difference compared to inline. Other unknown
259 * compilers can also just fallback to a normal inline.
261 #define debug_inline inline
262 #endif
264 typedef uint8_t byte;
266 /* This is already defined in unix, but not in QNX Neutrino (6.x) or Cygwin. */
267 #if (!defined(UNIX) && !defined(__HAIKU__)) || defined(__QNXNTO__) || defined(__CYGWIN__)
268 typedef unsigned int uint;
269 #endif
271 #if !defined(WITH_PERSONAL_DIR)
272 # define PERSONAL_DIR ""
273 #endif
275 /* Define the the platforms that use XDG */
276 #if defined(WITH_PERSONAL_DIR) && defined(UNIX) && !defined(__APPLE__) && !defined(__EMSCRIPTEN__)
277 # define USE_XDG
278 #endif
280 /* Check if the types have the bitsizes like we are using them */
281 static_assert(sizeof(uint64_t) == 8);
282 static_assert(sizeof(uint32_t) == 4);
283 static_assert(sizeof(uint16_t) == 2);
284 static_assert(sizeof(uint8_t) == 1);
285 static_assert(SIZE_MAX >= UINT32_MAX);
287 #ifndef M_PI_2
288 #define M_PI_2 1.57079632679489661923
289 #define M_PI 3.14159265358979323846
290 #endif /* M_PI_2 */
293 * Return the length of an fixed size array.
294 * Unlike sizeof this function returns the number of elements
295 * of the given type.
297 * @param x The pointer to the first element of the array
298 * @return The number of elements
300 #define lengthof(x) (sizeof(x) / sizeof(x[0]))
303 * Get the end element of an fixed size array.
305 * @param x The pointer to the first element of the array
306 * @return The pointer past to the last element of the array
308 #define endof(x) (&x[lengthof(x)])
311 * Get the last element of an fixed size array.
313 * @param x The pointer to the first element of the array
314 * @return The pointer to the last element of the array
316 #define lastof(x) (&x[lengthof(x) - 1])
319 * Gets the size of a variable within a class.
320 * @param base The class the variable is in.
321 * @param variable The variable to get the size of.
322 * @return the size of the variable
324 #define cpp_sizeof(base, variable) (sizeof(std::declval<base>().variable))
327 * Gets the length of an array variable within a class.
328 * @param base The class the variable is in.
329 * @param variable The array variable to get the size of.
330 * @return the length of the array
332 #define cpp_lengthof(base, variable) (cpp_sizeof(base, variable) / cpp_sizeof(base, variable[0]))
335 /* take care of some name clashes on MacOS */
336 #if defined(__APPLE__)
337 # define GetString OTTD_GetString
338 # define DrawString OTTD_DrawString
339 # define CloseConnection OTTD_CloseConnection
340 #endif /* __APPLE__ */
342 #if defined(__GNUC__) || defined(__clang__)
343 # define GNU_TARGET(x) [[gnu::target(x)]]
344 #else
345 # define GNU_TARGET(x)
346 #endif /* __GNUC__ || __clang__ */
348 /* For the FMT library we only want to use the headers, not link to some library. */
349 #define FMT_HEADER_ONLY
351 [[noreturn]] void NotReachedError(int line, const char *file);
352 [[noreturn]] void AssertFailedError(int line, const char *file, const char *expression);
353 #define NOT_REACHED() NotReachedError(__LINE__, __FILE__)
355 /* For non-debug builds with assertions enabled use the special assertion handler. */
356 #if defined(NDEBUG) && defined(WITH_ASSERT)
357 # undef assert
358 # define assert(expression) do { if (!(expression)) [[unlikely]] AssertFailedError(__LINE__, __FILE__, #expression); } while (false)
359 #endif
361 /* Define JSON_ASSERT, which is used by nlohmann-json. Otherwise the header-file
362 * will re-include assert.h, and reset the assert macro. */
363 #define JSON_ASSERT(x) assert(x)
365 #if defined(MAX_PATH)
366 /* It's already defined, no need to override */
367 #elif defined(PATH_MAX) && PATH_MAX > 0
368 /* Use the value from PATH_MAX, if it exists */
369 # define MAX_PATH PATH_MAX
370 #else
371 /* If all else fails, hardcode something :( */
372 # define MAX_PATH 260
373 #endif
376 * Version of the standard free that accepts const pointers.
377 * @param ptr The data to free.
379 inline void free(const void *ptr)
381 free(const_cast<void *>(ptr));
385 * The largest value that can be entered in a variable
386 * @param type the type of the variable
388 #define MAX_UVALUE(type) ((type)~(type)0)
390 #if defined(_MSC_VER) && !defined(_DEBUG)
391 # define IGNORE_UNINITIALIZED_WARNING_START __pragma(warning(push)) __pragma(warning(disable:4700))
392 # define IGNORE_UNINITIALIZED_WARNING_STOP __pragma(warning(pop))
393 #elif defined(__GNUC__) && !defined(_DEBUG)
394 # define HELPER0(x) #x
395 # define HELPER1(x) HELPER0(GCC diagnostic ignored x)
396 # define HELPER2(y) HELPER1(#y)
397 #if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
398 # define IGNORE_UNINITIALIZED_WARNING_START \
399 _Pragma("GCC diagnostic push") \
400 _Pragma(HELPER2(-Wuninitialized)) \
401 _Pragma(HELPER2(-Wmaybe-uninitialized))
402 # define IGNORE_UNINITIALIZED_WARNING_STOP _Pragma("GCC diagnostic pop")
403 #endif
404 #endif
406 #ifndef IGNORE_UNINITIALIZED_WARNING_START
407 # define IGNORE_UNINITIALIZED_WARNING_START
408 # define IGNORE_UNINITIALIZED_WARNING_STOP
409 #endif
411 #endif /* STDAFX_H */