Debian Codegraph @

src/cdogs/utils.c

raw symbols SCIP
1 /*
2 C-Dogs SDL
3 A port of the legendary (and fun) action/arcade cdogs.
4 Copyright (C) 1995 Ronny Wester
5 Copyright (C) 2003 Jeremy Chin
6 Copyright (C) 2003-2007 Lucas Martin-King
7
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21
22 This file incorporates work covered by the following copyright and
23 permission notice:
24
25 Copyright (c) 2013-2017, 2019-2022, 2024-2025 Cong Xu
26 All rights reserved.
27
28 Redistribution and use in source and binary forms, with or without
29 modification, are permitted provided that the following conditions are met:
30
31 Redistributions of source code must retain the above copyright notice, this
32 list of conditions and the following disclaimer.
33 Redistributions in binary form must reproduce the above copyright notice,
34 this list of conditions and the following disclaimer in the documentation
35 and/or other materials provided with the distribution.
36
37 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
38 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
40 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
41 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
42 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
43 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
44 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
45 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
47 POSSIBILITY OF SUCH DAMAGE.
48 */
49 #define _BSD_SOURCE
50 #define _DEFAULT_SOURCE
51
52 #include "utils.h"
53
54 #include <assert.h>
55 #include <errno.h>
56 #include <limits.h>
57 #include <math.h>
58 #include <stdlib.h>
59 #include <string.h>
60
61 #define SDL_STBIMAGE_IMPLEMENTATION
62 #ifdef __GNUC__
63 #pragma GCC diagnostic push
64 #pragma GCC diagnostic ignored "-Wcast-qual"
65 #endif
66 #include <stb/SDL_stbimage.h>
67 #ifdef __GNUC__
68 #pragma GCC diagnostic pop
69 #endif
70 #include <tinydir/tinydir.h>
71
72 #include "events.h"
73 #include "joystick.h"
74 #include "log.h"
75 #include "sys_config.h"
76
77 bool gTrue = true;
78 bool gFalse = false;
79
80 // From answer by ThiefMaster
81 // http://stackoverflow.com/a/5309508/2038264
82 // License: http://creativecommons.org/licenses/by-sa/3.0/
83 // Author profile: http://stackoverflow.com/users/298479/thiefmaster
84 const char *StrGetFileExt(const char *filename)
85 {
86 const char *dot = strrchr(filename, '.');
87 if (!dot || dot == filename)
88 {
89 return "";
90 }
91 return dot + 1;
92 }
93
94 // Note: includes trailing slash
95 void PathGetDirname(char *buf, const char *path)
96 {
97 const char *basename = PathGetBasename(path);
98 if (basename == path)
99 {
100 strcpy(buf, "");
101 }
102 else
103 {
104 strncpy(buf, path, basename - path);
105 buf[basename - path] = '\0';
106 }
107 }
108 const char *PathGetBasename(const char *path)
109 {
110 const char *fslash = strrchr(path, '/');
111 const char *bslash = strrchr(path, '\\');
112 const char *slash =
113 fslash ? (bslash ? MAX(fslash, bslash) : fslash) : bslash;
114 if (slash == NULL)
115 {
116 // no slashes found, simply return path
117 return path;
118 }
119 else
120 {
121 return slash + 1;
122 }
123 }
124 void PathGetWithoutExtension(char *buf, const char *path)
125 {
126 const char *dot = strrchr(path, '.');
127 if (dot)
128 {
129 strncpy(buf, path, dot - path);
130 buf[dot - path] = '\0';
131 }
132 else
133 {
134 strcpy(buf, path);
135 }
136 }
137 void PathGetBasenameWithoutExtension(char *buf, const char *path)
138 {
139 const char *basename = PathGetBasename(path);
140 PathGetWithoutExtension(buf, basename);
141 }
142
143 static void TrimSlashes(char *s);
144 #ifdef _WIN32
145 #include "sys_config.h"
146 #define realpath(src, dst) _fullpath(dst, src, CDOGS_PATH_MAX)
147 #endif
148 static bool IsAbsolutePath(const char *path);
149 void RealPath(const char *src, char *dest)
150 {
151 char *res;
152 #ifndef _WIN32
153 // realpath will fail if the file does not exist; if this is the
154 // case then resolve the path ourselves
155 tinydir_file file;
156 const bool exists = tinydir_file_open(&file, src) == 0;
157 if (!exists)
158 {
159 char srcBuf[CDOGS_PATH_MAX];
160 // First, convert slashes
161 srcBuf[0] = '\0';
162 strncat(srcBuf, src, CDOGS_PATH_MAX - 1);
163 for (char *c = srcBuf; *c != '\0'; c++)
164 {
165 if (*c == '\\')
166 {
167 *c = '/';
168 }
169 }
170
171 // Then, add on the CWD if the path is not absolute
172 char resolveBuf[CDOGS_PATH_MAX];
173 resolveBuf[0] = '\0';
174 if (!IsAbsolutePath(srcBuf))
175 {
176 CDogsGetCWD(resolveBuf);
177 strcat(resolveBuf, "/");
178 }
179 // Add the path
180 strcat(resolveBuf, srcBuf);
181
182 // Finally, resolve the path one level at a time, ignoring '//'s, '.'s
183 // and resolving '..'s to the parent level
184 char *cOut = dest;
185 char cLast = '\0';
186 for (const char *c = resolveBuf; *c != '\0'; c++)
187 {
188 if (*c == '.' && (cLast == '.' || cLast == '/'))
189 {
190 if (cLast == '.')
191 {
192 // '..' parent dir
193 // Rewind the out ptr to the last path separator
194 if (cOut > dest + 1)
195 {
196 // Skip past the last slash
197 cOut -= 2;
198 while (*cOut != '/' && cOut > dest)
199 {
200 cOut--;
201 }
202 // Go back in front of the slash
203 if (*cOut == '/')
204 {
205 cOut++;
206 }
207 }
208 }
209 else if (cLast == '/')
210 {
211 // ignore for now
212 }
213 }
214 else if (*c == '/' && (cLast == '/' || cLast == '.'))
215 {
216 // Double slash; ignore
217 }
218 else
219 {
220 *cOut = *c;
221 cOut++;
222 }
223 cLast = *c;
224 }
225 // Write terminating char
226 *cOut = '\0';
227 res = dest;
228 }
229 else
230 #endif
231 res = realpath(src, dest);
232 if (!res)
233 {
234 fprintf(
235 stderr, "Cannot resolve relative path %s: %s\n", src,
236 strerror(errno));
237 // Default to relative path
238 strcpy(dest, src);
239 }
240 // Convert \'s to /'s (for consistency)
241 for (char *c = dest; *c != '\0'; c++)
242 {
243 if (*c == '\\')
244 {
245 *c = '/';
246 }
247 }
248 TrimSlashes(dest);
249 }
250
251 // Convert an absolute path to a relative path
252 // e.g. /a/path/from/here, /a/path/to -> ../to
253 void RelPath(char *buf, const char *to, const char *from)
254 {
255 #ifdef _WIN32
256 // If path is on a different Windows drive, just return the path
257 if (strlen(from) >= 2 && strlen(to) >= 2 && IsAbsolutePath(from) &&
258 IsAbsolutePath(to) && toupper(from[0]) != toupper(to[0]))
259 {
260 strcpy(buf, to);
261 return;
262 }
263 #endif
264 // Make sure both to/from paths were generated using RealPath,
265 // so that common substring means they share part of their paths,
266 // and not due to alternate renderings of the same path like
267 // different path separator chars, or relative paths.
268 char toBuf[CDOGS_PATH_MAX];
269 char fromBuf[CDOGS_PATH_MAX];
270 RealPath(to, toBuf);
271 RealPath(from, fromBuf);
272
273 // Remove trailing slashes
274 TrimSlashes(toBuf);
275 TrimSlashes(fromBuf);
276
277 // First, find common string prefix
278 const char *t = toBuf;
279 const char *f = fromBuf;
280 const char *tSlash = t;
281 const char *fSlash = f;
282 while (*t && *f)
283 {
284 if (*t != *f)
285 {
286 break;
287 }
288 if (*t == '/')
289 {
290 tSlash = t;
291 fSlash = f;
292 }
293 t++;
294 f++;
295 }
296 // e.g.: tSlash = "/to", fSlash = "/from/here"
297
298 // Check if one is a complete substring of the other
299 if (!*f)
300 {
301 tSlash = t;
302 fSlash = f;
303 }
304
305 // For every folder in "from", add "..", and finally add "to"
306 strcpy(buf, "");
307 while (*fSlash)
308 {
309 if (*fSlash == '/')
310 {
311 strcat(buf, "../");
312 }
313 fSlash++;
314 }
315 if (*tSlash == '/')
316 {
317 tSlash++;
318 }
319 strcat(buf, tSlash);
320 }
321 static void TrimSlashes(char *s)
322 {
323 char *end = s + strlen(s) - 1;
324 while (end > s && *end == '/')
325 {
326 end--;
327 }
328 *(end + 1) = '\0';
329 }
330
331 void FixPathSeparator(char *dst, const char *src)
332 {
333 const char *s = src;
334 char *d = dst;
335 #ifdef _WIN32
336 #define SEP '\\'
337 #define SEP_OTHER '/'
338 #else
339 #define SEP '/'
340 #define SEP_OTHER '\\'
341 #endif
342 while (*s != '\0')
343 {
344 if (*s == SEP_OTHER)
345 *d = SEP;
346 else
347 *d = *s;
348 d++;
349 s++;
350 }
351 #undef SEP
352 *d = '\0';
353 }
354
355 #ifdef __APPLE__
356 #include <mach-o/dyld.h>
357 #endif
358 char *CDogsGetCWD(char *buf)
359 {
360 #ifdef __APPLE__
361 uint32_t size = CDOGS_PATH_MAX;
362 if (_NSGetExecutablePath(buf, &size))
363 {
364 return NULL;
365 }
366 // This gives us the executable path; find the dirname
367 *strrchr(buf, '/') = '\0';
368 return buf;
369 #else
370 return getcwd(buf, CDOGS_PATH_MAX);
371 #endif
372 }
373 void RelPathFromCWD(char *buf, const char *to)
374 {
375 if (to == NULL || strlen(to) == 0)
376 {
377 return;
378 }
379 char cwd[CDOGS_PATH_MAX];
380 CASSERT(CDogsGetCWD(cwd) != NULL, "error");
381 if (CDogsGetCWD(cwd) == NULL)
382 {
383 fprintf(stderr, "Error getting CWD; %s\n", strerror(errno));
384 strcpy(buf, to);
385 }
386 else
387 {
388 RelPath(buf, to, cwd);
389 }
390 }
391
392 void GetDataFilePath(char *buf, const char *path)
393 {
394 if (IsAbsolutePath(path))
395 {
396 strcpy(buf, path);
397 return;
398 }
399 char relbuf[CDOGS_PATH_MAX];
400 // Don't bother prepending CWD if data dir already an absolute path
401 if (IsAbsolutePath(CDOGS_DATA_DIR))
402 {
403 sprintf(relbuf, "%s%s", CDOGS_DATA_DIR, path);
404 }
405 else
406 {
407 char cwd[CDOGS_PATH_MAX];
408 if (CDogsGetCWD(cwd) == NULL)
409 {
410 fprintf(stderr, "Error getting CWD; %s\n", strerror(errno));
411 strcpy(cwd, "");
412 }
413 sprintf(relbuf, "%s/%s%s", cwd, CDOGS_DATA_DIR, path);
414 }
415 RealPath(relbuf, buf);
416 }
417
418 static bool IsAbsolutePath(const char *path)
419 {
420 #ifdef _WIN32
421 return strlen(path) > 1 && path[1] == ':';
422 #else
423 return path[0] == '/';
424 #endif
425 }
426
427 double Round(double x)
428 {
429 return floor(x + 0.5);
430 }
431
432 double ToDegrees(double radians)
433 {
434 return radians * 180.0 / MPI;
435 }
436
437 struct vec2 CalcClosestPointOnLineSegmentToPoint(
438 const struct vec2 l1, const struct vec2 l2, const struct vec2 p)
439 {
440 // Using parametric representation, line l1->l2 is
441 // P(t) = l1 + t(l2 - l1)
442 // Projection of point p on line is
443 // t = ((p.x - l1.x)(l2.x - l1.x) + (p.y - l1.y)(l2.y - l1.y)) / ||l2 -
444 // l1||^2
445 const float lineDistanceSquared = svec2_distance_squared(l1, l2);
446 // Early exit since same point means 0 distance, and div by 0
447 if (lineDistanceSquared == 0)
448 {
449 return l1;
450 }
451 const float numerator =
452 (p.x - l1.x) * (l2.x - l1.x) + (p.y - l1.y) * (l2.y - l1.y);
453 const float t = CLAMP(numerator / lineDistanceSquared, 0, 1);
454 const struct vec2 closestPoint =
455 svec2(l1.x + t * (l2.x - l1.x), l1.y + t * (l2.y - l1.y));
456 return closestPoint;
457 }
458
459 const char *InputDeviceName(const int d, const int deviceIndex)
460 {
461 switch (d)
462 {
463 case INPUT_DEVICE_KEYBOARD:
464 return "Keyboard";
465 case INPUT_DEVICE_JOYSTICK:
466 return JoyName(deviceIndex);
467 case INPUT_DEVICE_AI:
468 return "AI";
469 default:
470 return "";
471 }
472 }
473
474 const char *AllyCollisionStr(int a)
475 {
476 switch (a)
477 {
478 T2S(ALLYCOLLISION_NORMAL, "Normal");
479 T2S(ALLYCOLLISION_REPEL, "Repel");
480 T2S(ALLYCOLLISION_NONE, "None");
481 default:
482 return "";
483 }
484 }
485 int StrAllyCollision(const char *s)
486 {
487 S2T(ALLYCOLLISION_NORMAL, "Normal");
488 S2T(ALLYCOLLISION_REPEL, "Repel");
489 S2T(ALLYCOLLISION_NONE, "None");
490 return ALLYCOLLISION_NORMAL;
491 }
492
493 char *IntStr(int i)
494 {
495 static char buf[32];
496 sprintf(buf, "%d", i);
497 return buf;
498 }
499 char *PercentStr(int p)
500 {
501 static char buf[32];
502 sprintf(buf, "%d%%", p);
503 return buf;
504 }
505 char *Div8Str(int i)
506 {
507 static char buf[16];
508 sprintf(buf, "%d", i / 8);
509 return buf;
510 }
511 void CamelToTitle(char *buf, const char *src)
512 {
513 const char *first = src;
514 #define IS_UPPER(_x) ((_x) >= 'A' && (_x) <= 'Z')
515 while (*src)
516 {
517 // Word boundaries marked by capital letters, as long as:
518 // - It's not the first letter, and
519 // - The previous letter is lower case, or
520 // - The next letter is lower case
521 if (IS_UPPER(*src) && src != first &&
522 (!IS_UPPER(*(src - 1)) || (*(src + 1) && !IS_UPPER(*(src + 1)))))
523 {
524 *buf++ = ' ';
525 }
526 *buf++ = *src++;
527 }
528 *buf = '\0';
529 }
530 bool StrStartsWith(const char *str, const char *prefix)
531 {
532 if (str == NULL || prefix == NULL)
533 {
534 return false;
535 }
536 const size_t lenStr = strlen(str);
537 const size_t lenPrefix = strlen(prefix);
538 if (lenPrefix > lenStr)
539 {
540 return false;
541 }
542 return strncmp(str, prefix, MIN(lenStr, lenPrefix)) == 0;
543 }
544 // From answer by plinth
545 // http://stackoverflow.com/a/744822/2038264
546 // License: http://creativecommons.org/licenses/by-sa/3.0/
547 // Author profile: http://stackoverflow.com/users/20481/plinth
548 bool StrEndsWith(const char *str, const char *suffix)
549 {
550 if (str == NULL || suffix == NULL)
551 {
552 return false;
553 }
554 const size_t lenStr = strlen(str);
555 const size_t lenSuffix = strlen(suffix);
556 if (lenSuffix > lenStr)
557 {
558 return false;
559 }
560 return strncmp(str + lenStr - lenSuffix, suffix, lenSuffix) == 0;
561 }
562
563 // From answer by chux
564 // https://stackoverflow.com/a/30734030/2038264
565 // License: http://creativecommons.org/licenses/by-sa/3.0/
566 int Stricmp(const char *a, const char *b)
567 {
568 int ca, cb;
569 do
570 {
571 ca = (unsigned char)*a++;
572 cb = (unsigned char)*b++;
573 ca = tolower(toupper(ca));
574 cb = tolower(toupper(cb));
575 } while (ca == cb && ca != '\0');
576 return ca - cb;
577 }
578
579 int CompareIntsAsc(const void *v1, const void *v2)
580 {
581 const int i1 = *(const int *)v1;
582 const int i2 = *(const int *)v2;
583 if (i1 < i2)
584 {
585 return -1;
586 }
587 else if (i1 > i2)
588 {
589 return 1;
590 }
591 return 0;
592 }
593 int CompareIntsDesc(const void *v1, const void *v2)
594 {
595 const int i1 = *(const int *)v1;
596 const int i2 = *(const int *)v2;
597 if (i1 > i2)
598 {
599 return -1;
600 }
601 else if (i1 < i2)
602 {
603 return 1;
604 }
605 return 0;
606 }
607
608 bool IntsEqual(const void *v1, const void *v2)
609 {
610 return *(const int *)v1 == *(const int *)v2;
611 }
612
613 const char *HeadPartStr(const HeadPart hp)
614 {
615 switch (hp)
616 {
617 T2S(HEAD_PART_HAIR, "Hair");
618 T2S(HEAD_PART_FACEHAIR, "Facial Hair");
619 T2S(HEAD_PART_HAT, "Hat");
620 T2S(HEAD_PART_GLASSES, "Glasses");
621 default:
622 return "";
623 }
624 }
625
626 BodyPart StrBodyPart(const char *s)
627 {
628 S2T(BODY_PART_HEAD, "head");
629 S2T(BODY_PART_HAIR, "hair");
630 S2T(BODY_PART_FACEHAIR, "facehair");
631 S2T(BODY_PART_HAT, "hat");
632 S2T(BODY_PART_GLASSES, "glasses");
633 S2T(BODY_PART_BODY, "body");
634 S2T(BODY_PART_LEGS, "legs");
635 S2T(BODY_PART_GUN_R, "gun_r");
636 S2T(BODY_PART_GUN_L, "gun_l");
637 return BODY_PART_HEAD;
638 }
639
640 int Pulse256(const int t)
641 {
642 const int pulsePeriod = ConfigGetInt(&gConfig, "Game.FPS") / 2;
643 int alphaUnscaled = (t % pulsePeriod) * 255 / (pulsePeriod / 2);
644 if (alphaUnscaled > 255)
645 {
646 alphaUnscaled = 255 * 2 - alphaUnscaled;
647 }
648 return alphaUnscaled;
649 }
650
651 char *ReadFileIntoBuf(const char *path, const char *mode)
652 {
653 char *buf = NULL;
654 FILE *f = fopen(path, mode);
655 if (f == NULL)
656 {
657 goto bail;
658 }
659
660 // Read into buffer
661 if (fseek(f, 0L, SEEK_END) != 0)
662 {
663 goto bail;
664 }
665 long len = ftell(f);
666 if (len == -1)
667 {
668 goto bail;
669 }
670 CCALLOC(buf, len + 1);
671 if (fseek(f, 0L, SEEK_SET) != 0)
672 {
673 goto bail;
674 }
675 if (fread(buf, 1, len, f) == 0)
676 {
677 goto bail;
678 }
679
680 goto end;
681
682 bail:
683 CFREE(buf);
684 buf = NULL;
685
686 end:
687 if (f != NULL && fclose(f) != 0)
688 {
689 LOG(LM_MAIN, LL_ERROR, "Cannot close file %s: %s", path,
690 strerror(errno));
691 }
692 return buf;
693 }
694
695 SDL_Surface *LoadImgToSurface(const char *path)
696 {
697 return STBIMG_Load(path);
698 }