src/ai/squirrel/squirrel.cpp
branchnoai
changeset 9411 29c9dfcdb8e9
parent 9410 286fcd8edc64
child 9412 af09fe15860d
--- a/src/ai/squirrel/squirrel.cpp	Thu Mar 15 14:50:03 2007 +0000
+++ b/src/ai/squirrel/squirrel.cpp	Thu Mar 15 15:20:26 2007 +0000
@@ -4,6 +4,10 @@
 
 #include "squirrel.hpp"
 #include "../../debug.h"
+#include "../../string.h"
+#include "../../fios.h"
+#include <sys/types.h>
+#include <sys/stat.h>
 
 #define SQUIRREL_CLASS
 #include "convert.hpp"
@@ -87,6 +91,46 @@
 	return 0;
 }
 
+extern bool FiosIsValidFile(const char *path, const struct dirent *ent, struct stat *sb);
+extern bool FiosIsHiddenFile(const struct dirent *ent);
+
+
+void FSquirrel::ScanDir(const char *dirname)
+{
+	struct stat sb;
+	struct dirent *dirent;
+	DIR *dir;
+	char d_name[256];
+	char script_name[256];
+	dir = ttd_opendir(dirname);
+	/* Dir not found, so do nothing */
+	if (dir == NULL) return;
+
+	/* Walk all dirs trying to find a dir in which 'main.nut' exists */
+	while ((dirent = readdir(dir)) != NULL) {
+		ttd_strlcpy(d_name, FS2OTTD(dirent->d_name), sizeof(d_name));
+
+		/* Found file must be directory, but not '.' or '..' */
+		if (FiosIsValidFile("ai", dirent, &sb) && (sb.st_mode & S_IFDIR) &&
+				(!FiosIsHiddenFile(dirent) || strncasecmp(d_name, PERSONAL_DIR, strlen(d_name)) == 0) &&
+				strcmp(d_name, ".") != 0 && strcmp(d_name, "..") != 0) {
+			/* Create the full-length script-name */
+			strcpy(script_name, dirname);
+			strcat(script_name, PATHSEP);
+			strcat(script_name, d_name);
+			strcat(script_name, PATHSEP);
+			strcat(script_name, "main.nut");
+			/* If it exists, load it up */
+			if (FileExists(script_name)) {
+				DEBUG(ai, 6, "[squirrel] Loading script '%s' for AI handling", script_name);
+				this->current_script = script_name;
+				this->engine->LoadScript(this->current_script);
+			}
+		}
+	}
+	closedir(dir);
+}
+
 void FSquirrel::Initializer()
 {
 	this->engine = new SquirrelEngine();
@@ -102,9 +146,8 @@
 	/* Mark this class as global pointer */
 	this->engine->SetGlobalPointer(this);
 
-	/* Now load all scripts we can find */
-	this->current_script = "ai/SQNoAI/main.nut";
-	this->engine->LoadScript(this->current_script);
+	/* Scan the AI dir for scripts */
+	this->ScanDir("ai");
 }
 
 FSquirrel::~FSquirrel()