src/ai/api/ai_controller.cpp
branchnoai
changeset 10958 65088d587094
parent 10902 57b380ee1607
child 10971 aaf89f8c59b9
--- a/src/ai/api/ai_controller.cpp	Fri Jun 13 19:57:25 2008 +0000
+++ b/src/ai/api/ai_controller.cpp	Fri Jun 13 20:19:00 2008 +0000
@@ -6,6 +6,7 @@
 #include "../../openttd.h"
 #include "../../player_func.h"
 #include "../../core/alloc_func.hpp"
+#include "../../string_func.h"
 #include "table/strings.h"
 
 #include <squirrel.h>
@@ -152,32 +153,36 @@
 	AIController::Print(error_msg, FS2OTTD(message));
 }
 
-AIController::AIController(const char *script, const char *class_name)
+AIController::AIController(const char *script, const char *class_name) :
+	tick(0),
+	engine(NULL),
+	SQ_instance(NULL),
+	loaded_library_count(0)
 {
-	this->tick = 0;
-	this->SQ_instance = NULL;
+	this->script = strdup(script);
+	this->class_name = strdup(class_name);
+}
+
+void AIController::Start()
+{
+	assert(this->engine == NULL);
 
 	/* Create the Squirrel Engine and assign all required classes and settings */
 	this->engine = new Squirrel();
 	this->engine->SetPrintFunction(&PrintFunc);
 	this->RegisterClasses();
-	if (!this->engine->LoadScript(script)) {
+	if (!this->engine->LoadScript(this->script)) {
 		delete this->engine;
 		this->engine = NULL;
 		return;
 	}
 	/* Create the main-class */
 	this->SQ_instance = MallocT<SQObject>(sizeof(SQObject));
-	if (!this->engine->CreateClassInstance(class_name, this, this->SQ_instance)) {
+	if (!this->engine->CreateClassInstance(this->class_name, this, this->SQ_instance)) {
 		delete this->engine;
 		this->engine = NULL;
 		return;
 	}
-}
-
-void AIController::Start()
-{
-	if (this->engine == NULL) return;
 
 	/* Run the constructor first */
 	if (this->engine->MethodExists(*this->SQ_instance, "constructor")) {
@@ -191,6 +196,15 @@
 {
 	if (this->engine != NULL) delete this->engine;
 	free(this->SQ_instance);
+	free((void *)this->script);
+	free((void *)this->class_name);
+
+	for (LoadedLibraryList::iterator iter = this->loaded_library.begin(); iter != this->loaded_library.end(); iter++) {
+		free((void *)(*iter).second);
+		free((void *)(*iter).first);
+	}
+
+	this->loaded_library.clear();
 }
 
 void AIController::IncreaseTick()
@@ -202,3 +216,20 @@
 {
 	return this->tick;
 }
+
+bool AIController::LoadedLibrary(const char *library_name, int *next_number, char *fake_class_name, int fake_class_name_len)
+{
+	LoadedLibraryList::iterator iter = this->loaded_library.find(library_name);
+	if (iter == this->loaded_library.end()) {
+		*next_number = ++this->loaded_library_count;
+		return false;
+	}
+
+	ttd_strlcpy(fake_class_name, (*iter).second, fake_class_name_len);
+	return true;
+}
+
+void AIController::AddLoadedLibrary(const char *library_name, const char *fake_class_name)
+{
+	this->loaded_library[strdup(library_name)] = strdup(fake_class_name);
+}