Skip to content
Snippets Groups Projects
main.c 26.8 KiB
Newer Older
dg's avatar
dg committed
/*
    TE4 - T-Engine 4
dg's avatar
dg committed
    Copyright (C) 2009, 2010, 2011 Nicolas Casalini
dg's avatar
dg committed

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Nicolas Casalini "DarkGod"
    darkgod@te4.org
*/
dg's avatar
dg committed
#include "display.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
dg's avatar
dg committed
#include <sys/time.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include "luasocket.h"
#include "luasocket/mime.h"
dg's avatar
dg committed
#include "SFMT.h"
dg's avatar
dg committed

#include "types.h"
#include "script.h"
#include "physfs.h"
dg's avatar
dg committed
#include "core_lua.h"
dg's avatar
dg committed
#include "getself.h"
dg's avatar
dg committed
#include "music.h"
#include "serial.h"
dg's avatar
dg committed
#include "profile.h"
dg's avatar
dg committed
#include "main.h"
dg's avatar
dg committed
#include "runner/core.h"
dg's avatar
dg committed
#ifdef SELFEXE_WINDOWS
#include <windows.h>
#endif
dg's avatar
dg committed

dg's avatar
dg committed
#define WIDTH 800
#define HEIGHT 600
dg's avatar
dg committed

SDL_Window *window = NULL;
SDL_GLContext maincontext; /* Our opengl context handle */
dg's avatar
dg committed
lua_State *L = NULL;
dg's avatar
dg committed
bool no_debug = FALSE;
dg's avatar
dg committed
int current_mousehandler = LUA_NOREF;
dg's avatar
dg committed
int current_keyhandler = LUA_NOREF;
dg's avatar
dg committed
int current_game = LUA_NOREF;
dg's avatar
dg committed
core_boot_type *core_def = NULL;
dg's avatar
dg committed
bool exit_engine = FALSE;
dg's avatar
dg committed
bool no_sound = FALSE;
bool isActive = TRUE;
int mouse_cursor_tex = 0, mouse_cursor_tex_ref = LUA_NOREF;
int mouse_cursor_down_tex = 0, mouse_cursor_down_tex_ref = LUA_NOREF;
int mouse_cursor_ox = 0, mouse_cursor_oy = 0;
int mousex = 0, mousey = 0;
dg's avatar
dg committed
float gamma_correction = 1;
SDL_TimerID display_timer_id = NULL;
SDL_TimerID realtime_timer_id = NULL;

/* OpenGL capabilities */
dg's avatar
dg committed
extern bool shaders_active;
bool fbo_active;
bool multitexture_active;
dg's avatar
dg committed

/* Error handling */
lua_err_type *last_lua_error_head = NULL, *last_lua_error_tail = NULL;

void del_lua_error()
{
	lua_err_type *cur = last_lua_error_head;
	while (cur)
	{
		if (cur->err_msg) free(cur->err_msg);
		if (cur->file) free(cur->file);
		if (cur->func) free(cur->func);

		lua_err_type *ocur = cur;
		cur = cur->next;
		free(ocur);
	}

	last_lua_error_head = NULL;
	last_lua_error_tail = NULL;
}

static void new_lua_error(const char *err)
{
	del_lua_error();

	lua_err_type *cur = calloc(1, sizeof(lua_err_type));
	cur->err_msg = strdup(err);
	cur->next = NULL;

	last_lua_error_head = cur;
	last_lua_error_tail = cur;
}

static void add_lua_error(const char *file, int line, const char *func)
{
	lua_err_type *cur = calloc(1, sizeof(lua_err_type));
	cur->err_msg = NULL;
	cur->file = strdup(file);
	cur->line = line;
	cur->func = strdup(func);
	cur->next = NULL;

	last_lua_error_tail->next = cur;
	last_lua_error_tail = cur;
}

dg's avatar
dg committed
static int traceback (lua_State *L) {
	lua_Debug ar;
dg's avatar
dg committed
	printf("Lua Error: %s\n", lua_tostring(L, 1));
	while(lua_getstack(L, n++, &ar)) {
		lua_getinfo(L, "nSl", &ar);
		printf("\tAt %s:%d %s\n", ar.short_src, ar.currentline, ar.name?ar.name:"");
	}

	// Do it again for the lua error popup, if needed
	if (1)
	{
		n = 0;
		new_lua_error(lua_tostring(L, 1));
		while(lua_getstack(L, n++, &ar)) {
			lua_getinfo(L, "nSl", &ar);
			add_lua_error(ar.short_src, ar.currentline, ar.name?ar.name:"");
		}
	}
dg's avatar
dg committed
	return 1;
}

	int i=lua_gettop(L);
	printf(" ----------------  Stack Dump ----------------\n" );
	while(  i   ) {
		int t = lua_type(L, i);
		switch (t) {
		case LUA_TSTRING:
			printf("%d:`%s'\n", i, lua_tostring(L, i));
			break;
		case LUA_TBOOLEAN:
			printf("%d: %s\n",i,lua_toboolean(L, i) ? "true" : "false");
			break;
		case LUA_TNUMBER:
			printf("%d: %g\n",  i, lua_tonumber(L, i));
			break;
		default:
#if defined(__PTRDIFF_TYPE__)
			if((sizeof(__PTRDIFF_TYPE__) == sizeof(long int)))
			{ printf("%d: %s // %lx\n", i, lua_typename(L, t), (unsigned long int)lua_topointer(L, i)); }
			{ printf("%d: %s // %x\n", i, lua_typename(L, t), (unsigned int)lua_topointer(L, i)); }
#else
			printf("%d: %s // %x\n", i, lua_typename(L, t), lua_topointer(L, i));
#endif
			break;
		}
		i--;
	}
	printf("--------------- Stack Dump Finished ---------------\n" );
}

dg's avatar
dg committed
int docall (lua_State *L, int narg, int nret)
dg's avatar
dg committed
{
dg's avatar
dg committed
#if 1
dg's avatar
dg committed
	int status;
	int base = lua_gettop(L) - narg;  /* function index */
dg's avatar
dg committed
//	printf("<===%d (%d)\n", base, narg);
dg's avatar
dg committed
	lua_pushcfunction(L, traceback);  /* push traceback function */
	lua_insert(L, base);  /* put it under chunk and args */
	status = lua_pcall(L, narg, nret, base);
	lua_remove(L, base);  /* remove traceback function */
	/* force a complete garbage collection in case of errors */
	if (status != 0) { lua_pop(L, 1); lua_gc(L, LUA_GCCOLLECT, 0); }
dg's avatar
dg committed
//	printf(">===%d (%d) [%d]\n", lua_gettop(L), nret, status);
	if (lua_gettop(L) != nret + (base - 1))
dg's avatar
dg committed
		lua_settop(L, base);
dg's avatar
dg committed
	return status;
dg's avatar
dg committed
#else
	int status=0;
	int base = lua_gettop(L) - narg;  /* function index */
	lua_call(L, narg, nret);
	return status;
#endif
dg's avatar
dg committed
}

dg's avatar
dg committed
/* No print function, does .. nothing */
int noprint(lua_State *L)
{
	return 0;
}

dg's avatar
dg committed
// define our data that is passed to our redraw function
typedef struct {
	Uint32 color;
} MainStateData;

int event_filter(void *userdata, SDL_Event* event)
dg's avatar
dg committed
{
	// Do not allow the user to close without asking the game to know about it
	if (event->type == SDL_QUIT && (current_game != LUA_NOREF))
	{
		lua_rawgeti(L, LUA_REGISTRYINDEX, current_game);
		lua_pushstring(L, "onQuit");
		lua_gettable(L, -2);
		lua_remove(L, -2);
		lua_rawgeti(L, LUA_REGISTRYINDEX, current_game);
		docall(L, 1, 0);

		return 0;
	}
	return 1;
}

extern SDL_Cursor *mouse_cursor;
extern SDL_Cursor *mouse_cursor_down;
dg's avatar
dg committed
void on_event(SDL_Event *event)
dg's avatar
dg committed
{
	switch (event->type) {
dg's avatar
dg committed
	case SDL_KEYDOWN:
dg's avatar
dg committed
	case SDL_KEYUP:
dg's avatar
dg committed
		if (current_keyhandler != LUA_NOREF)
dg's avatar
dg committed
		{
			lua_rawgeti(L, LUA_REGISTRYINDEX, current_keyhandler);
			lua_pushstring(L, "receiveKey");
			lua_gettable(L, -2);
			lua_remove(L, -2);
			lua_rawgeti(L, LUA_REGISTRYINDEX, current_keyhandler);
			if (event->type != SDL_TEXTINPUT) lua_pushnumber(L, event->key.keysym.scancode);
			else lua_pushnumber(L, 0);
dg's avatar
dg committed

			SDL_Keymod _pKeyState = SDL_GetModState();
			lua_pushboolean(L, (_pKeyState & KMOD_CTRL) ? TRUE : FALSE);
			lua_pushboolean(L, (_pKeyState & KMOD_SHIFT) ? TRUE : FALSE);
			lua_pushboolean(L, (_pKeyState & KMOD_ALT) ? TRUE : FALSE);
			lua_pushboolean(L, (_pKeyState & KMOD_GUI) ? TRUE : FALSE);
dg's avatar
dg committed

			if (event->type == SDL_TEXTINPUT)
			{
				lua_pushstring(L, event->text.text);
dg's avatar
dg committed
			}
			else
				lua_pushnil(L);
dg's avatar
dg committed
			lua_pushboolean(L, (event->type == SDL_KEYUP) ? TRUE : FALSE);
			docall(L, 8, 0);
dg's avatar
dg committed
		}
		break;
dg's avatar
dg committed
	case SDL_MOUSEBUTTONDOWN:
dg's avatar
dg committed
	case SDL_MOUSEBUTTONUP:
		if (event->type == SDL_MOUSEBUTTONDOWN) SDL_SetCursor(mouse_cursor_down);
		else SDL_SetCursor(mouse_cursor);

dg's avatar
dg committed
		if (current_mousehandler != LUA_NOREF)
		{
			lua_rawgeti(L, LUA_REGISTRYINDEX, current_mousehandler);
			lua_pushstring(L, "receiveMouse");
			lua_gettable(L, -2);
			lua_remove(L, -2);
			lua_rawgeti(L, LUA_REGISTRYINDEX, current_mousehandler);
			switch (event->button.button)
			{
			case SDL_BUTTON_LEFT:
				lua_pushstring(L, "left");
				break;
			case SDL_BUTTON_MIDDLE:
				lua_pushstring(L, "middle");
				break;
			case SDL_BUTTON_RIGHT:
				lua_pushstring(L, "right");
				break;
			case SDL_BUTTON_WHEELUP:
				lua_pushstring(L, "wheelup");
				break;
			case SDL_BUTTON_WHEELDOWN:
				lua_pushstring(L, "wheeldown");
				break;
dg's avatar
dg committed
			default:
				lua_pushstring(L, "button");
				lua_pushnumber(L, event->button.button);
				lua_concat(L, 2);
				break;
dg's avatar
dg committed
			}
			lua_pushnumber(L, event->button.x);
			lua_pushnumber(L, event->button.y);
dg's avatar
dg committed
			lua_pushboolean(L, (event->type == SDL_MOUSEBUTTONUP) ? TRUE : FALSE);
			docall(L, 5, 0);
dg's avatar
dg committed
		}
		break;
	case SDL_MOUSEWHEEL:
		if (current_mousehandler != LUA_NOREF)
		{
			int x = 0, y = 0;
			SDL_GetMouseState(&x, &y);

			int i;
			for (i = 0; i <= 1; i++)
			{
				lua_rawgeti(L, LUA_REGISTRYINDEX, current_mousehandler);
				lua_pushstring(L, "receiveMouse");
				lua_gettable(L, -2);
				lua_remove(L, -2);
				lua_rawgeti(L, LUA_REGISTRYINDEX, current_mousehandler);
				if (event->wheel.y > 0) lua_pushstring(L, "wheelup");
				else if (event->wheel.y < 0) lua_pushstring(L, "wheeldown");
				else if (event->wheel.x > 0) lua_pushstring(L, "wheelleft");
				else if (event->wheel.x < 0) lua_pushstring(L, "wheelright");
				else lua_pushstring(L, "wheelnone");
				lua_pushnumber(L, x);
				lua_pushnumber(L, y);
				lua_pushboolean(L, i);
				docall(L, 5, 0);
			}
		}
		break;
dg's avatar
dg committed
	case SDL_MOUSEMOTION:
		mousex = event->motion.x;
		mousey = event->motion.y;

dg's avatar
dg committed
		if (current_mousehandler != LUA_NOREF)
		{
			lua_rawgeti(L, LUA_REGISTRYINDEX, current_mousehandler);
			lua_pushstring(L, "receiveMouseMotion");
			lua_gettable(L, -2);
			lua_remove(L, -2);
			lua_rawgeti(L, LUA_REGISTRYINDEX, current_mousehandler);
			if (event->motion.state & SDL_BUTTON(1)) lua_pushstring(L, "left");
			else if (event->motion.state & SDL_BUTTON(2)) lua_pushstring(L, "middle");
			else if (event->motion.state & SDL_BUTTON(3)) lua_pushstring(L, "right");
			else if (event->motion.state & SDL_BUTTON(4)) lua_pushstring(L, "wheelup");
			else if (event->motion.state & SDL_BUTTON(5)) lua_pushstring(L, "wheeldown");
			else lua_pushstring(L, "none");
			lua_pushnumber(L, event->motion.x);
			lua_pushnumber(L, event->motion.y);
			lua_pushnumber(L, event->motion.xrel);
			lua_pushnumber(L, event->motion.yrel);
			docall(L, 6, 0);
		}
		break;
dg's avatar
dg committed
	}
}

// redraw the screen and update game logics, if any
dg's avatar
dg committed
void on_tick()
dg's avatar
dg committed
{
	static int Frames = 0;
	static int T0     = 0;

dg's avatar
dg committed
	if (current_game != LUA_NOREF)
dg's avatar
dg committed
	{
dg's avatar
dg committed
		lua_rawgeti(L, LUA_REGISTRYINDEX, current_game);
dg's avatar
dg committed
		lua_pushstring(L, "tick");
		lua_gettable(L, -2);
		lua_remove(L, -2);
dg's avatar
dg committed
		lua_rawgeti(L, LUA_REGISTRYINDEX, current_game);
		docall(L, 1, 1);
		tickPaused = lua_toboolean(L, -1);
dg's avatar
dg committed
	}

	/* Gather our frames per second */
	Frames++;
	{
		int t = SDL_GetTicks();
dg's avatar
dg committed
		if (t - T0 >= 10000) {
			float seconds = (t - T0) / 1000.0;
			float fps = Frames / seconds;
dg's avatar
dg committed
//			printf("%d ticks  in %g seconds = %g TPS\n", Frames, seconds, fps);
			T0 = t;
			Frames = 0;
		}
	}
void call_draw(int nb_keyframes)
dg's avatar
dg committed
{
dg's avatar
dg committed
	if (nb_keyframes > 30) nb_keyframes = 30;

	// Notify the particles threads that there are new keyframes
	thread_particle_new_keyframes(nb_keyframes);

dg's avatar
dg committed
	if (current_game != LUA_NOREF)
dg's avatar
dg committed
	{
dg's avatar
dg committed
		lua_rawgeti(L, LUA_REGISTRYINDEX, current_game);
dg's avatar
dg committed
		lua_pushstring(L, "display");
		lua_gettable(L, -2);
		lua_remove(L, -2);
dg's avatar
dg committed
		lua_rawgeti(L, LUA_REGISTRYINDEX, current_game);
		lua_pushnumber(L, (nb_keyframes < 0) ? 0 : nb_keyframes);
		docall(L, 2, 0);
dg's avatar
dg committed
	}

	/* Mouse pointer */
	if (mouse_cursor_tex && mouse_cursor_down_tex)
	{
		GLfloat texcoords[2*4] = {
			0, 0,
			1, 0,
			1, 1,
			0, 1,
		};
		GLfloat colors[4*4] = {
			1, 1, 1, 1,
			1, 1, 1, 1,
			1, 1, 1, 1,
			1, 1, 1, 1,
		};

		glTexCoordPointer(2, GL_FLOAT, 0, texcoords);
		glColorPointer(4, GL_FLOAT, 0, colors);
		int x = mousex + mouse_cursor_ox;
		int y = mousey + mouse_cursor_oy;
		int down = SDL_GetMouseState(NULL, NULL);
		tglBindTexture(GL_TEXTURE_2D, down ? mouse_cursor_down_tex : mouse_cursor_tex);

		GLfloat vertices[2*4] = {
			x, y,
			x, y + 32,
			x + 32, y + 32,
			x + 32, y,
		};
		glVertexPointer(2, GL_FLOAT, 0, vertices);
		glDrawArrays(GL_QUADS, 0, 4);
void on_redraw()
{
	static int Frames = 0;
	static int T0     = 0;
	static float nb_keyframes = 0;
	static int last_keyframe = 0;
	static float reference_fps = 30;
	static int count_keyframes = 0;
dg's avatar
dg committed

	/* Gather our frames per second */
	Frames++;
	{
		int t = SDL_GetTicks();
dg's avatar
dg committed
			float seconds = (t - T0) / 1000.0;
			float fps = Frames / seconds;
dg's avatar
dg committed
//			printf("%d frames in %g seconds = %g FPS (%d keyframes)\n", Frames, seconds, fps, count_keyframes);
dg's avatar
dg committed
			T0 = t;
			Frames = 0;
			last_keyframe = 0;
			nb_keyframes = 0;
			count_keyframes = 0;
dg's avatar
dg committed
		}
	}
dg's avatar
dg committed

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();
	float step = 30 / reference_fps;
	nb_keyframes += step;
	int nb = ceilf(nb_keyframes);
	count_keyframes += nb - last_keyframe;
	total_keyframes += nb - last_keyframe;
//	printf("keyframes: %f / %f by %f => %d\n", nb_keyframes, reference_fps, step, nb - (last_keyframe));
	call_draw(nb - last_keyframe);
	//SDL_GL_SwapBuffers();
	SDL_GL_SwapWindow(window);
dg's avatar
dg committed
void pass_command_args(int argc, char *argv[])
{
	int i;

	if (current_game != LUA_NOREF)
	{
		lua_rawgeti(L, LUA_REGISTRYINDEX, current_game);
		lua_pushstring(L, "commandLineArgs");
		lua_gettable(L, -2);
		lua_remove(L, -2);
		lua_rawgeti(L, LUA_REGISTRYINDEX, current_game);
		lua_newtable(L);

		for (i = 1; i <= argc; i++)
		{
			lua_pushnumber(L, i);
			lua_pushstring(L, argv[i]);
			lua_settable(L, -3);
		}
		docall(L, 2, 0);
	}
}

dg's avatar
dg committed
Uint32 redraw_timer(Uint32 interval, void *param)
{
	SDL_Event event;
	SDL_UserEvent userevent;

	/* In this example, our callback pushes an SDL_USEREVENT event
	 into the queue, and causes ourself to be called again at the
	 same interval: */

	userevent.type = SDL_USEREVENT;
	userevent.code = 0;
	userevent.data1 = NULL;
	userevent.data2 = NULL;

	event.type = SDL_USEREVENT;
	event.user = userevent;

	if (!redraw_pending && isActive) {
dg's avatar
dg committed
	return(interval);
}

int realtime_pending = 0;

Uint32 realtime_timer(Uint32 interval, void *param)
{
	SDL_Event event;
	SDL_UserEvent userevent;

	/* In this example, our callback pushes an SDL_USEREVENT event
	 into the queue, and causes ourself to be called again at the
	 same interval: */

	userevent.type = SDL_USEREVENT;
	userevent.code = 2;
	userevent.data1 = NULL;
	userevent.data2 = NULL;

	event.type = SDL_USEREVENT;
	event.user = userevent;

	if (!realtime_pending && isActive) {
		SDL_PushEvent(&event);
//		realtime_pending = 1;
	}
	return(interval);
}

dg's avatar
dg committed
// Calls the lua music callback
void on_music_stop()
{
	if (current_game != LUA_NOREF)
	{
		lua_rawgeti(L, LUA_REGISTRYINDEX, current_game);
		lua_pushstring(L, "onMusicStop");
		lua_gettable(L, -2);
		lua_remove(L, -2);
		if (lua_isfunction(L, -1))
		{
			lua_rawgeti(L, LUA_REGISTRYINDEX, current_game);
			docall(L, 1, 0);
		}
		else
			lua_pop(L, 1);
	}
}

// Setup realtime
void setupRealtime(float freq)
{
	if (!freq)
	{
		if (realtime_timer_id) SDL_RemoveTimer(realtime_timer_id);
		printf("[ENGINE] Switching to turn based\n");
	}
	else
	{
		float interval = 1000 / freq;
		realtime_timer_id = SDL_AddTimer((int)interval, realtime_timer, NULL);
		printf("[ENGINE] Switching to realtime, interval %d ms\n", (int)interval);
	}
}
dg's avatar
dg committed

void setupDisplayTimer(int fps)
{
	if (display_timer_id) SDL_RemoveTimer(display_timer_id);
	display_timer_id = SDL_AddTimer(1000 / fps, redraw_timer, NULL);
	printf("[ENGINE] Setting requested FPS to %d (%d ms)\n", fps, 1000 / fps);
}


dg's avatar
dg committed
/* general OpenGL initialization function */
int initGL()
{
	/* Set the background black */
dg's avatar
dg committed
	tglClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
dg's avatar
dg committed

	/* Depth buffer setup */
dg's avatar
dg committed

	/* The Type Of Depth Test To Do */
dg's avatar
dg committed

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);

	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	glEnableClientState(GL_COLOR_ARRAY);
dg's avatar
dg committed
	return( TRUE );
}

int resizeWindow(int width, int height)
{
	/* Height / width ration */
	GLfloat ratio;

dg's avatar
dg committed
	SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
	initGL();

dg's avatar
dg committed
	/* Protect against a divide by zero */
	if ( height == 0 )
		height = 1;

	ratio = ( GLfloat )width / ( GLfloat )height;

dg's avatar
dg committed
//	tglActiveTexture(GL_TEXTURE0);
dg's avatar
dg committed
	glEnable(GL_TEXTURE_2D);
dg's avatar
dg committed

	/* Setup our viewport. */
	glViewport( 0, 0, ( GLsizei )width, ( GLsizei )height );

	/* change to the projection matrix and set our viewing volume. */
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	/* Set our perspective */
	//gluPerspective( 45.0f, ratio, 0.1f, 100.0f );
dg's avatar
dg committed
	glOrtho(0, width, height, 0, -1001, 1001);
dg's avatar
dg committed

	/* Make sure we're chaning the model view and not the projection */
	glMatrixMode( GL_MODELVIEW );

	/* Reset The View */
	glLoadIdentity( );

dg's avatar
dg committed
	SDL_SetGamma(gamma_correction, gamma_correction, gamma_correction);

dg's avatar
dg committed
	GLint texSize;
	glGetIntegerv(GL_MAX_TEXTURE_SIZE, &texSize);
	printf("OpenGL max texture size: %d\n", texSize);


dg's avatar
dg committed
	return( TRUE );
}

dg's avatar
dg committed
void do_resize(int w, int h, bool fullscreen)
{
	if (!window)
	{
		window = SDL_CreateWindow("TE4", 0, 0, w, h, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | (fullscreen ? SDL_WINDOW_FULLSCREEN : 0));
		if (window==NULL) {
			printf("error opening screen: %s\n", SDL_GetError());
			exit(1);
		}
		screen = SDL_GetWindowSurface(window);
		maincontext = SDL_GL_CreateContext(window);
dg's avatar
dg committed
		SDL_GL_MakeCurrent(window, maincontext);
dg's avatar
dg committed
		glewInit();
	}
	else
	{
		SDL_SetWindowSize(window, w, h);
		screen = SDL_GetWindowSurface(window);
	SDL_SetWindowFullscreen(window, fullscreen);
	SDL_GetWindowSize(window, &w, &h);
	resizeWindow(w, h);
dg's avatar
dg committed
	SDL_GL_MakeCurrent(window, maincontext);
	resizeWindow(w, h);
void boot_lua(int state, bool rebooting, int argc, char *argv[])
{
dg's avatar
dg committed
	core_def->corenum = 0;

	if (state == 1)
	{
		const char *selfexe;

		/* When rebooting we destroy the lua state to free memory and we reset physfs */
		if (rebooting)
		{
			current_mousehandler = LUA_NOREF;
			current_keyhandler = LUA_NOREF;
			current_game = LUA_NOREF;
			lua_close(L);
			PHYSFS_deinit();
		}

		/***************** Physfs Init *****************/
		PHYSFS_init(argv[0]);

		selfexe = get_self_executable(argc, argv);
dg's avatar
dg committed
		if (selfexe && PHYSFS_mount(selfexe, "/", 1))
		{
		}
		else
		{
			printf("NO SELFEXE: bootstrapping from CWD\n");
			PHYSFS_mount("bootstrap", "/bootstrap", 1);
		}

		/***************** Lua Init *****************/
		L = lua_open();  /* create state */
		luaL_openlibs(L);  /* open libraries */
dg's avatar
dg committed
		luaopen_physfs(L);
		luaopen_core(L);
		luaopen_socket_core(L);
		luaopen_mime_core(L);
		luaopen_struct(L);
		luaopen_profiler(L);
dg's avatar
dg committed
		luaopen_bit(L);
		luaopen_lpeg(L);
dg's avatar
dg committed
		luaopen_lxp(L);
		luaopen_map(L);
		luaopen_particles(L);
dg's avatar
dg committed
		luaopen_gas(L);
		luaopen_sound(L);
dg's avatar
dg committed
		luaopen_noise(L);
dg's avatar
dg committed
		luaopen_diamond_square(L);
dg's avatar
dg committed
		luaopen_shaders(L);
		luaopen_serial(L);
dg's avatar
dg committed
		luaopen_zlib(L);
dg's avatar
dg committed
		luaopen_bit(L);
dg's avatar
dg committed
		// Override "print" if requested
		if (no_debug)
		{
			lua_pushcfunction(L, noprint);
			lua_setglobal(L, "print");
		}

		// Make the uids repository
		lua_newtable(L);
		lua_setglobal(L, "__uids");

		// Tell the boostrapping code the selfexe path
		if (selfexe)
			lua_pushstring(L, selfexe);
		else
			lua_pushnil(L);
		lua_setglobal(L, "__SELFEXE");

		// Will be useful
#ifdef __APPLE__
		lua_pushboolean(L, TRUE);
		lua_setglobal(L, "__APPLE__");
#endif

		// Run bootstrapping
		if (!luaL_loadfile(L, "/bootstrap/boot.lua"))
		{
			docall(L, 0, 0);
		}
		// Could not load bootstrap! Try to mount the engine from working directory as last resort
		else
		{
			printf("WARNING: No bootstrap code found, defaulting to working directory for engine code!\n");
			PHYSFS_mount("game/thirdparty", "/", 1);
			PHYSFS_mount("game/", "/", 1);
		}

		// And run the lua engine pre init scripts
		if (!luaL_loadfile(L, "/loader/pre-init.lua"))
			docall(L, 0, 0);
		else
			lua_pop(L, 1);

		create_particles_thread();
	}
	else if (state == 2)
	{
		SDL_WM_SetCaption("T-Engine4", NULL);

		// Now we can open lua lanes, the physfs paths are set and it can load it's lanes-keeper.lua file
dg's avatar
dg committed
		//		luaopen_lanes(L);

		printf("Running lua loader code...\n");

		// And run the lua engine scripts
		if (!luaL_loadfile(L, "/loader/init.lua"))
		{
dg's avatar
dg committed
			if (core_def->reboot_engine) lua_pushstring(L, core_def->reboot_engine); else lua_pushnil(L);
			if (core_def->reboot_engine_version) lua_pushstring(L, core_def->reboot_engine_version); else lua_pushnil(L);
			if (core_def->reboot_module) lua_pushstring(L, core_def->reboot_module); else lua_pushnil(L);
			if (core_def->reboot_name) lua_pushstring(L, core_def->reboot_name); else lua_pushnil(L);
			lua_pushboolean(L, core_def->reboot_new);
			if (core_def->reboot_einfo) lua_pushstring(L, core_def->reboot_einfo); else lua_pushnil(L);
			docall(L, 6, 0);
dg's avatar
dg committed
// Update core to run
static void define_core(core_boot_type *core_def, const char *coretype, int id, const char *reboot_engine, const char *reboot_engine_version, const char *reboot_module, const char *reboot_name, int reboot_new, const char *reboot_einfo)
{
	if (core_def->coretype) free(core_def->coretype);
	if (core_def->reboot_engine) free(core_def->reboot_engine);
	if (core_def->reboot_engine_version) free(core_def->reboot_engine_version);
	if (core_def->reboot_module) free(core_def->reboot_module);
	if (core_def->reboot_name) free(core_def->reboot_name);
	if (core_def->reboot_einfo) free(core_def->reboot_einfo);

	core_def->corenum = id;
	core_def->coretype = coretype ? strdup(coretype) : NULL;
	core_def->reboot_engine = reboot_engine ? strdup(reboot_engine) : NULL;
	core_def->reboot_engine_version = reboot_engine_version ? strdup(reboot_engine_version) : NULL;
	core_def->reboot_module = reboot_module ? strdup(reboot_module) : NULL;
	core_def->reboot_name = reboot_name ? strdup(reboot_name) : NULL;
	core_def->reboot_einfo = reboot_einfo ? strdup(reboot_einfo) : NULL;
	core_def->reboot_new = reboot_new;
}

dg's avatar
dg committed
// Let some platforms use a different entry point
#ifdef USE_TENGINE_MAIN
#ifdef main
#undef main
#endif
#define main tengine_main
#endif


dg's avatar
dg committed
/**
dg's avatar
dg committed
 */
dg's avatar
dg committed
int main(int argc, char *argv[])
dg's avatar
dg committed
{
dg's avatar
dg committed
	core_def = calloc(1, sizeof(core_boot_type));
dg's avatar
dg committed
	core_def->define = &define_core;
	core_def->define(core_def, "te4core", -1, NULL, NULL, NULL, NULL, 0, NULL);

	// Parse arguments
	int i;
	for (i = 1; i < argc; i++)
	{
		char *arg = argv[i];
dg's avatar
dg committed
		if (!strncmp(arg, "-M", 2)) core_def->reboot_module = strdup(arg+2);
		if (!strncmp(arg, "-u", 2)) core_def->reboot_name = strdup(arg+2);
		if (!strncmp(arg, "-E", 2)) core_def->reboot_einfo = strdup(arg+2);
		if (!strncmp(arg, "-n", 2)) core_def->reboot_new = 1;
		if (!strncmp(arg, "--flush-stdout", 14)) setvbuf(stdout, (char *) NULL, _IOLBF, 0);;
		if (!strncmp(arg, "--no-debug", 10)) no_debug = TRUE;
#ifdef SELFEXE_WINDOWS
	freopen ("te4_log.txt", "w", stdout);
#endif

	// Get cpu cores
	nb_cpus = get_number_cpus();
	printf("[CPU] Detected %d CPUs\n", nb_cpus);

	// RNG init
	init_gen_rand(time(NULL));

dg's avatar
dg committed
	int vid_drv;
	for (vid_drv = 0; vid_drv < SDL_GetNumVideoDrivers(); vid_drv++)
	{
		printf("Available video driver: %s\n", SDL_GetVideoDriver(vid_drv));
	}

dg's avatar
dg committed
	// initialize engine and set up resolution and depth
dg's avatar
dg committed
	Uint32 flags=SDL_INIT_TIMER;
dg's avatar
dg committed
	if (SDL_Init (flags) < 0) {
		printf("cannot initialize SDL: %s\n", SDL_GetError ());
dg's avatar
dg committed
		return 1;
dg's avatar
dg committed
	}
dg's avatar
dg committed

dg's avatar
dg committed
	if (SDL_VideoInit(NULL) != 0) {
		printf("Error initializing SDL video:  %s\n", SDL_GetError());
		return 2;
	}


dg's avatar
dg committed
	// Filter events, to catch the quit event
dg's avatar
dg committed

	boot_lua(1, FALSE, argc, argv);

dg's avatar
dg committed
	do_resize(WIDTH, HEIGHT, FALSE);
dg's avatar
dg committed
	if (screen==NULL) {
		printf("error opening screen: %s\n", SDL_GetError());
dg's avatar
dg committed
		return;
dg's avatar
dg committed
	}
	SDL_SetWindowIcon(window, IMG_Load_RW(PHYSFSRWOPS_openRead("/engines/default/data/gfx/te4-icon.png"), TRUE));
	SDL_SetWindowTitle(window, "T4Engine");
dg's avatar
dg committed
	SDL_EnableKeyRepeat(300, 10);
dg's avatar
dg committed
	TTF_Init();
dg's avatar
dg committed

dg's avatar
dg committed
	/* Sets up OpenGL double buffering */
	resizeWindow(WIDTH, HEIGHT);

	// Allow getting unicode events
	SDL_StartTextInput();
	// Allow screensaver to work
	SDL_EnableScreenSaver();

	// Get OpenGL capabilities
dg's avatar
dg committed
	multitexture_active = GLEW_ARB_multitexture;
	shaders_active = GLEW_ARB_shader_objects;
	fbo_active = GLEW_EXT_framebuffer_object || GLEW_ARB_framebuffer_object;
	if (!multitexture_active) shaders_active = FALSE;
dg's avatar
dg committed
	if (!GLEW_VERSION_2_1)
	{
		multitexture_active = FALSE;
		shaders_active = FALSE;
		fbo_active = FALSE;
	}
dg's avatar
dg committed
	printf("===fbo %d\n", fbo_active);
dg's avatar
dg committed

	boot_lua(2, FALSE, argc, argv);
dg's avatar
dg committed

dg's avatar
dg committed
	pass_command_args(argc, argv);

dg's avatar
dg committed
	SDL_Event event;
dg's avatar
dg committed
	while (!exit_engine)
dg's avatar
dg committed
	{
		if (!isActive || tickPaused) SDL_WaitEvent(NULL);
dg's avatar
dg committed
		/* handle the events in the queue */
		while (SDL_PollEvent(&event))
		{
			switch(event.type)
			{
			case SDL_WINDOWEVENT:
				switch (event.window.event)
				case SDL_WINDOWEVENT_RESIZED:
					printf("resize %d x %d\n", event.window.data1, event.window.data2);
					do_resize(event.window.data1, event.window.data2, FALSE);

					if (current_game != LUA_NOREF)
					{
						lua_rawgeti(L, LUA_REGISTRYINDEX, current_game);
						lua_pushstring(L, "onResolutionChange");
						lua_gettable(L, -2);
						lua_remove(L, -2);
						lua_rawgeti(L, LUA_REGISTRYINDEX, current_game);
						docall(L, 1, 0);
					}
					break;
				case SDL_WINDOWEVENT_MOVED: {
					int x, y;
					SDL_GetWindowPosition(window, &x, &y);
					printf("move %d x %d\n", x, y);
					if (current_game != LUA_NOREF)
					{
						lua_rawgeti(L, LUA_REGISTRYINDEX, current_game);
						lua_pushstring(L, "onWindowMoved");
						lua_gettable(L, -2);
						lua_remove(L, -2);
						lua_rawgeti(L, LUA_REGISTRYINDEX, current_game);
						lua_pushnumber(L, x);
						lua_pushnumber(L, y);