Skip to content

Instantly share code, notes, and snippets.

@Rover656
Created January 18, 2022 00:17
Show Gist options
  • Save Rover656/7805e6447b4b1654cb57d5d865d71d9c to your computer and use it in GitHub Desktop.
Save Rover656/7805e6447b4b1654cb57d5d865d71d9c to your computer and use it in GitHub Desktop.
A quick and dirty way of locating the assets directory in a raylib project.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "raylib.h"
// Locate the assets directory.
char* GetAssetsDirectory() {
static char assetDir[1024] = {0};
// 1. Check environment variable
const char* assetsEnv = getenv("ASSETS");
if (assetsEnv != NULL) {
strcpy(assetDir, assetsEnv);
// Ensure trailing slash.
if (assetDir[strlen(assetDir) - 1] != '/') {
strcat(assetDir, "/");
}
return assetDir;
}
// 2. Check working directory
char wd[1024] = { 0 };
strcpy(wd, GetWorkingDirectory());
char* d = strcat(wd, "/assets/");
if (DirectoryExists(d)) {
strcpy(assetDir, d);
return assetDir;
}
// 3. Seek out git root
char searchDir[1024] = { 0 };
strcpy(searchDir, GetWorkingDirectory());
for (int i = 0; i < 10; i++) {
char gitDir[1024] = { 0 };
strcpy(gitDir, searchDir);
strcat(gitDir, "/.git");
if (DirectoryExists(gitDir)) {
strcpy(assetDir, searchDir);
return strcat(assetDir, "/assets/");
}
strcpy(searchDir, GetPrevDirectoryPath(searchDir));
}
// Failed to locate, write the error and kill the program.
TraceLog(LOG_ERROR, "Failed to locate asset directory!");
exit(1);
}
// Use this path to load the asset immediately, once called again original value is replaced!
char *GetAssetPath(const char* filename) {
static char path[1024] = { 0 };
strcpy(path, GetAssetsDirectory());
strcat(path, filename);
return path;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment