]> git.xonotic.org Git - xonotic/darkplaces.git/blob - common.h
keysym2ucs: Delete. Was only used for the GLX client which no longer exists
[xonotic/darkplaces.git] / common.h
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3 Copyright (C) 2000-2020 DarkPlaces contributors
4
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License
7 as published by the Free Software Foundation; either version 2
8 of the License, or (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 See the GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 */
21
22 #ifndef COMMON_H
23 #define COMMON_H
24
25 #include <stdarg.h>
26 #include <assert.h>
27 #include "qtypes.h"
28 #include "qdefs.h"
29
30 /// MSVC has a different name for several standard functions
31 #ifdef WIN32
32 # define strcasecmp _stricmp
33 # define strncasecmp _strnicmp
34 #else
35 #include "strings.h"
36 #endif
37
38 // Create our own define for Mac OS X
39 #if defined(__APPLE__) && defined(__MACH__)
40 # define MACOSX
41 #endif
42
43
44 //============================================================================
45
46 #define ContainerOf(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member)))
47
48 typedef struct sizebuf_s
49 {
50         qbool   allowoverflow;  ///< if false, do a Sys_Error
51         qbool   overflowed;             ///< set to true if the buffer size failed
52         unsigned char           *data;
53         int                     maxsize;
54         int                     cursize;
55         int                     readcount;
56         qbool   badread;                // set if a read goes beyond end of message
57 } sizebuf_t;
58
59 void SZ_Clear (sizebuf_t *buf);
60 unsigned char *SZ_GetSpace (sizebuf_t *buf, int length);
61 void SZ_Write (sizebuf_t *buf, const unsigned char *data, int length);
62 void SZ_HexDumpToConsole(const sizebuf_t *buf);
63
64 void Com_HexDumpToConsole(const unsigned char *data, int size);
65
66 unsigned short CRC_Block(const unsigned char *data, size_t size);
67 unsigned short CRC_Block_CaseInsensitive(const unsigned char *data, size_t size); // for hash lookup functions that use strcasecmp for comparison
68
69 unsigned char COM_BlockSequenceCRCByteQW(unsigned char *base, int length, int sequence);
70
71 // these are actually md4sum (mdfour.c)
72 unsigned Com_BlockChecksum (void *buffer, int length);
73 void Com_BlockFullChecksum (void *buffer, int len, unsigned char *outbuf);
74
75 void COM_Init_Commands(void);
76
77
78 //============================================================================
79 //                                                      Endianess handling
80 //============================================================================
81
82 // check mem_bigendian if you need to know the system byte order
83
84 /*! \name Byte order functions.
85  * @{
86  */
87
88 // unaligned memory access crashes on some platform, so always read bytes...
89 #define BigShort(l) BuffBigShort((unsigned char *)&(l))
90 #define LittleShort(l) BuffLittleShort((unsigned char *)&(l))
91 #define BigLong(l) BuffBigLong((unsigned char *)&(l))
92 #define LittleLong(l) BuffLittleLong((unsigned char *)&(l))
93 #define BigFloat(l) BuffBigFloat((unsigned char *)&(l))
94 #define LittleFloat(l) BuffLittleFloat((unsigned char *)&(l))
95
96 /// Extract a big endian 32bit float from the given \p buffer.
97 float BuffBigFloat (const unsigned char *buffer);
98
99 /// Extract a big endian 32bit int from the given \p buffer.
100 int BuffBigLong (const unsigned char *buffer);
101
102 /// Extract a big endian 16bit short from the given \p buffer.
103 short BuffBigShort (const unsigned char *buffer);
104
105 /// Extract a little endian 32bit float from the given \p buffer.
106 float BuffLittleFloat (const unsigned char *buffer);
107
108 /// Extract a little endian 32bit int from the given \p buffer.
109 int BuffLittleLong (const unsigned char *buffer);
110
111 /// Extract a little endian 16bit short from the given \p buffer.
112 short BuffLittleShort (const unsigned char *buffer);
113
114 /// Encode a big endian 32bit int to the given \p buffer
115 void StoreBigLong (unsigned char *buffer, unsigned int i);
116
117 /// Encode a big endian 16bit int to the given \p buffer
118 void StoreBigShort (unsigned char *buffer, unsigned short i);
119
120 /// Encode a little endian 32bit int to the given \p buffer
121 void StoreLittleLong (unsigned char *buffer, unsigned int i);
122
123 /// Encode a little endian 16bit int to the given \p buffer
124 void StoreLittleShort (unsigned char *buffer, unsigned short i);
125 //@}
126
127 //============================================================================
128
129 // these versions are purely for internal use, never sent in network protocol
130 // (use Protocol_EnumForNumber and Protocol_NumberToEnum to convert)
131 typedef enum protocolversion_e
132 {
133         PROTOCOL_UNKNOWN,
134         PROTOCOL_DARKPLACES8, ///< added parting messages. WIP
135         PROTOCOL_DARKPLACES7, ///< added QuakeWorld-style movement protocol to allow more consistent prediction
136         PROTOCOL_DARKPLACES6, ///< various changes
137         PROTOCOL_DARKPLACES5, ///< uses EntityFrame5 entity snapshot encoder/decoder which is based on a Tribes networking article at http://www.garagegames.com/articles/networking1/
138         PROTOCOL_DARKPLACES4, ///< various changes
139         PROTOCOL_DARKPLACES3, ///< uses EntityFrame4 entity snapshot encoder/decoder which is broken, this attempted to do partial snapshot updates on a QuakeWorld-like protocol, but it is broken and impossible to fix
140         PROTOCOL_DARKPLACES2, ///< various changes
141         PROTOCOL_DARKPLACES1, ///< uses EntityFrame entity snapshot encoder/decoder which is a QuakeWorld-like entity snapshot delta compression method
142         PROTOCOL_QUAKEDP, ///< darkplaces extended quake protocol (used by TomazQuake and others), backwards compatible as long as no extended features are used
143         PROTOCOL_NEHAHRAMOVIE, ///< Nehahra movie protocol, a big nasty hack dating back to early days of the Quake Standards Group (but only ever used by neh_gl.exe), this is potentially backwards compatible with quake protocol as long as no extended features are used (but in actuality the neh_gl.exe which wrote this protocol ALWAYS wrote the extended information)
144         PROTOCOL_QUAKE, ///< quake (aka netquake/normalquake/nq) protocol
145         PROTOCOL_QUAKEWORLD, ///< quakeworld protocol
146         PROTOCOL_NEHAHRABJP, ///< same as QUAKEDP but with 16bit modelindex
147         PROTOCOL_NEHAHRABJP2, ///< same as NEHAHRABJP but with 16bit soundindex
148         PROTOCOL_NEHAHRABJP3 ///< same as NEHAHRABJP2 but with some changes
149 }
150 protocolversion_t;
151
152 /*! \name Message IO functions.
153  * Handles byte ordering and avoids alignment errors
154  * @{
155  */
156
157 void MSG_InitReadBuffer (sizebuf_t *buf, unsigned char *data, int size);
158 void MSG_WriteChar (sizebuf_t *sb, int c);
159 void MSG_WriteByte (sizebuf_t *sb, int c);
160 void MSG_WriteShort (sizebuf_t *sb, int c);
161 void MSG_WriteLong (sizebuf_t *sb, int c);
162 void MSG_WriteFloat (sizebuf_t *sb, vec_t f);
163 void MSG_WriteString (sizebuf_t *sb, const char *s);
164 void MSG_WriteUnterminatedString (sizebuf_t *sb, const char *s);
165 void MSG_WriteAngle8i (sizebuf_t *sb, vec_t f);
166 void MSG_WriteAngle16i (sizebuf_t *sb, vec_t f);
167 void MSG_WriteAngle32f (sizebuf_t *sb, vec_t f);
168 void MSG_WriteCoord13i (sizebuf_t *sb, vec_t f);
169 void MSG_WriteCoord16i (sizebuf_t *sb, vec_t f);
170 void MSG_WriteCoord32f (sizebuf_t *sb, vec_t f);
171 void MSG_WriteCoord (sizebuf_t *sb, vec_t f, protocolversion_t protocol);
172 void MSG_WriteVector (sizebuf_t *sb, const vec3_t v, protocolversion_t protocol);
173 void MSG_WriteAngle (sizebuf_t *sb, vec_t f, protocolversion_t protocol);
174
175 void MSG_BeginReading (sizebuf_t *sb);
176 int MSG_ReadLittleShort (sizebuf_t *sb);
177 int MSG_ReadBigShort (sizebuf_t *sb);
178 int MSG_ReadLittleLong (sizebuf_t *sb);
179 int MSG_ReadBigLong (sizebuf_t *sb);
180 float MSG_ReadLittleFloat (sizebuf_t *sb);
181 float MSG_ReadBigFloat (sizebuf_t *sb);
182 char *MSG_ReadString (sizebuf_t *sb, char *string, size_t maxstring);
183 int MSG_ReadBytes (sizebuf_t *sb, int numbytes, unsigned char *out);
184
185 #define MSG_ReadChar(sb) ((sb)->readcount >= (sb)->cursize ? ((sb)->badread = true, -1) : (signed char)(sb)->data[(sb)->readcount++])
186 #define MSG_ReadByte(sb) ((sb)->readcount >= (sb)->cursize ? ((sb)->badread = true, -1) : (unsigned char)(sb)->data[(sb)->readcount++])
187 #define MSG_ReadShort MSG_ReadLittleShort
188 #define MSG_ReadLong MSG_ReadLittleLong
189 #define MSG_ReadFloat MSG_ReadLittleFloat
190
191 float MSG_ReadAngle8i (sizebuf_t *sb);
192 float MSG_ReadAngle16i (sizebuf_t *sb);
193 float MSG_ReadAngle32f (sizebuf_t *sb);
194 float MSG_ReadCoord13i (sizebuf_t *sb);
195 float MSG_ReadCoord16i (sizebuf_t *sb);
196 float MSG_ReadCoord32f (sizebuf_t *sb);
197 float MSG_ReadCoord (sizebuf_t *sb, protocolversion_t protocol);
198 void MSG_ReadVector (sizebuf_t *sb, vec3_t v, protocolversion_t protocol);
199 float MSG_ReadAngle (sizebuf_t *sb, protocolversion_t protocol);
200 //@}
201 //============================================================================
202
203 typedef float (*COM_WordWidthFunc_t) (void *passthrough, const char *w, size_t *length, float maxWidth); // length is updated to the longest fitting string into maxWidth; if maxWidth < 0, all characters are used and length is used as is
204 typedef int (*COM_LineProcessorFunc) (void *passthrough, const char *line, size_t length, float width, qbool isContination);
205 int COM_Wordwrap(const char *string, size_t length, float continuationSize, float maxWidth, COM_WordWidthFunc_t wordWidth, void *passthroughCW, COM_LineProcessorFunc processLine, void *passthroughPL);
206
207 extern char com_token[MAX_INPUTLINE];
208
209 int COM_ParseToken_Simple(const char **datapointer, qbool returnnewline, qbool parsebackslash, qbool parsecomments);
210 int COM_ParseToken_QuakeC(const char **datapointer, qbool returnnewline);
211 int COM_ParseToken_VM_Tokenize(const char **datapointer, qbool returnnewline);
212 int COM_ParseToken_Console(const char **datapointer);
213
214 void COM_Init (void);
215 void COM_Shutdown (void);
216 void COM_InitGameType (void);
217
218 char *va(char *buf, size_t buflen, const char *format, ...) DP_FUNC_PRINTF(3);
219 // does a varargs printf into provided buffer, returns buffer (so it can be called in-line unlike dpsnprintf)
220
221 // GCC with -Werror=c++-compat will error out if static_assert is used even though the macro is valid C11...
222 #ifndef __cplusplus
223 #define DP_STATIC_ASSERT(expr, str) _Static_assert(expr, str)
224 #else
225 #define DP_STATIC_ASSERT(expr, str) static_assert(expr, str)
226 #endif
227
228 // snprintf and vsnprintf are NOT portable. Use their DP counterparts instead
229 #ifdef snprintf
230 # undef snprintf
231 #endif
232 #define snprintf DP_STATIC_ASSERT(0, "snprintf is forbidden for portability reasons. Use dpsnprintf instead.")
233 #ifdef vsnprintf
234 # undef vsnprintf
235 #endif
236 #define vsnprintf DP_STATIC_ASSERT(0, "vsnprintf is forbidden for portability reasons. Use dpvsnprintf instead.")
237
238 // dpsnprintf and dpvsnprintf
239 // return the number of printed characters, excluding the final '\0'
240 // or return -1 if the buffer isn't big enough to contain the entire string.
241 // buffer is ALWAYS null-terminated
242 extern int dpsnprintf (char *buffer, size_t buffersize, const char *format, ...) DP_FUNC_PRINTF(3);
243 extern int dpvsnprintf (char *buffer, size_t buffersize, const char *format, va_list args);
244
245 // A bunch of functions are forbidden for security reasons (and also to please MSVS 2005, for some of them)
246 // LadyHavoc: added #undef lines here to avoid warnings in Linux
247 #undef strcat
248 #define strcat DP_STATIC_ASSERT(0, "strcat is forbidden for security reasons. Use strlcat or memcpy instead.")
249 #undef strncat
250 #define strncat DP_STATIC_ASSERT(0, "strncat is forbidden for security reasons. Use strlcat or memcpy instead.")
251 #undef strcpy
252 #define strcpy DP_STATIC_ASSERT(0, "strcpy is forbidden for security reasons. Use strlcpy or memcpy instead.")
253 #undef strncpy
254 #define strncpy DP_STATIC_ASSERT(0, "strncpy is forbidden for security reasons. Use strlcpy or memcpy instead.")
255 #undef sprintf
256 #define sprintf DP_STATIC_ASSERT(0, "sprintf is forbidden for security reasons. Use dpsnprintf instead.")
257
258
259 //============================================================================
260
261 extern  struct cvar_s   registered;
262 extern  struct cvar_s   cmdline;
263
264 typedef enum userdirmode_e
265 {
266         USERDIRMODE_NOHOME, // basedir only
267         USERDIRMODE_HOME, // Windows basedir, general POSIX (~/.)
268         USERDIRMODE_MYGAMES, // pre-Vista (My Documents/My Games/), general POSIX (~/.)
269         USERDIRMODE_SAVEDGAMES, // Vista (%USERPROFILE%/Saved Games/), OSX (~/Library/Application Support/), Linux (~/.config)
270         USERDIRMODE_COUNT
271 }
272 userdirmode_t;
273
274 typedef enum gamemode_e
275 {
276         GAME_NORMAL,
277         GAME_HIPNOTIC,
278         GAME_ROGUE,
279         GAME_QUOTH,
280         GAME_NEHAHRA,
281         GAME_NEXUIZ,
282         GAME_XONOTIC,
283         GAME_TRANSFUSION,
284         GAME_GOODVSBAD2,
285         GAME_TEU,
286         GAME_BATTLEMECH,
287         GAME_ZYMOTIC,
288         GAME_SETHERAL,
289         GAME_TENEBRAE, // full of evil hackery
290         GAME_NEOTERIC,
291         GAME_OPENQUARTZ, //this game sucks
292         GAME_PRYDON,
293         GAME_DELUXEQUAKE,
294         GAME_THEHUNTED,
295         GAME_DEFEATINDETAIL2,
296         GAME_DARSANA,
297         GAME_CONTAGIONTHEORY,
298         GAME_EDU2P,
299         GAME_PROPHECY,
300         GAME_BLOODOMNICIDE,
301         GAME_STEELSTORM, // added by motorsep
302         GAME_STEELSTORM2, // added by motorsep
303         GAME_SSAMMO, // added by motorsep
304         GAME_STEELSTORMREVENANTS, // added by motorsep 07/19/2015
305         GAME_TOMESOFMEPHISTOPHELES, // added by motorsep
306         GAME_STRAPBOMB, // added by motorsep for Urre
307         GAME_MOONHELM,
308         GAME_VORETOURNAMENT,
309         GAME_DOOMBRINGER, // added by Cloudwalk for kristus
310         GAME_BATTLEMETAL, // added by Cloudwalk for Subject9x
311         GAME_COUNT
312 }
313 gamemode_t;
314
315 // Master switch for some hacks/changes that eventually should become cvars.
316 #define IS_NEXUIZ_DERIVED(g) ((g) == GAME_NEXUIZ || (g) == GAME_XONOTIC || (g) == GAME_VORETOURNAMENT)
317 // Pre-csqcmodels era.
318 #define IS_OLDNEXUIZ_DERIVED(g) ((g) == GAME_NEXUIZ || (g) == GAME_VORETOURNAMENT)
319
320 extern gamemode_t gamemode;
321 extern const char *gamename;
322 extern const char *gamenetworkfiltername;
323 extern const char *gamedirname1;
324 extern const char *gamedirname2;
325 extern const char *gamescreenshotname;
326 extern const char *gameuserdirname;
327 extern char com_modname[MAX_OSPATH];
328
329 void COM_ChangeGameTypeForGameDirs(void);
330
331 void COM_ToLowerString (const char *in, char *out, size_t size_out);
332 void COM_ToUpperString (const char *in, char *out, size_t size_out);
333 int COM_StringBeginsWith(const char *s, const char *match);
334
335 int COM_ReadAndTokenizeLine(const char **text, char **argv, int maxargc, char *tokenbuf, int tokenbufsize, const char *commentprefix);
336
337 size_t COM_StringLengthNoColors(const char *s, size_t size_s, qbool *valid);
338 qbool COM_StringDecolorize(const char *in, size_t size_in, char *out, size_t size_out, qbool escape_carets);
339 void COM_ToLowerString (const char *in, char *out, size_t size_out);
340 void COM_ToUpperString (const char *in, char *out, size_t size_out);
341
342 typedef struct stringlist_s
343 {
344         /// maxstrings changes as needed, causing reallocation of strings[] array
345         int maxstrings;
346         int numstrings;
347         char **strings;
348 } stringlist_t;
349
350 int matchpattern(const char *in, const char *pattern, int caseinsensitive);
351 int matchpattern_with_separator(const char *in, const char *pattern, int caseinsensitive, const char *separators, qbool wildcard_least_one);
352 void stringlistinit(stringlist_t *list);
353 void stringlistfreecontents(stringlist_t *list);
354 void stringlistappend(stringlist_t *list, const char *text);
355 void stringlistsort(stringlist_t *list, qbool uniq);
356 void listdirectory(stringlist_t *list, const char *basepath, const char *path);
357
358 char *InfoString_GetValue(const char *buffer, const char *key, char *value, size_t valuelength);
359 void InfoString_SetValue(char *buffer, size_t bufferlength, const char *key, const char *value);
360 void InfoString_Print(char *buffer);
361
362 // strlcat and strlcpy, from OpenBSD
363 // Most (all?) BSDs already have them
364 #if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(MACOSX)
365 # define HAVE_STRLCAT 1
366 # define HAVE_STRLCPY 1
367 #endif
368
369 #ifndef HAVE_STRLCAT
370 /*!
371  * Appends src to string dst of size siz (unlike strncat, siz is the
372  * full size of dst, not space left).  At most siz-1 characters
373  * will be copied.  Always NUL terminates (unless siz <= strlen(dst)).
374  * Returns strlen(src) + MIN(siz, strlen(initial dst)).
375  * If retval >= siz, truncation occurred.
376  */
377 size_t strlcat(char *dst, const char *src, size_t siz);
378 #endif  // #ifndef HAVE_STRLCAT
379
380 #ifndef HAVE_STRLCPY
381 /*!
382  * Copy src to string dst of size siz.  At most siz-1 characters
383  * will be copied.  Always NUL terminates (unless siz == 0).
384  * Returns strlen(src); if retval >= siz, truncation occurred.
385  */
386 size_t strlcpy(char *dst, const char *src, size_t siz);
387
388 #endif  // #ifndef HAVE_STRLCPY
389
390 void FindFraction(double val, int *num, int *denom, int denomMax);
391
392 // decodes XPM file to XPM array (as if #include'd)
393 char **XPM_DecodeString(const char *in);
394
395 size_t base64_encode(unsigned char *buf, size_t buflen, size_t outbuflen);
396
397 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
398
399 float Com_CalcRoll (const vec3_t angles, const vec3_t velocity, const vec_t angleval, const vec_t velocityval);
400
401 #endif
402