Example #1
1
static void initialize_pref_path(void)
{
    char *base_path = SDL_GetPrefPath("Lonely Cactus", "Project Burro");
    if (base_path)
    {
        pref_path = SDL_strdup(base_path);
        SDL_free(base_path);
        write_enabled =  true;
    }
    else
    {
        /* Do something to disable writing in-game */
    }
}
Example #2
0
// Called before render is available
bool j1FileSystem::Awake(pugi::xml_node& config)
{
	LOG("Loading File System");
	bool ret = true;

	// Add all paths in configuration in order
	for(pugi::xml_node path = config.child("path"); path; path = path.next_sibling("path"))
	{
		AddPath(path.child_value());
	}

	// Ask SDL for a write dir
	char* write_path = SDL_GetPrefPath(App->GetOrganization(), App->GetTitle());

	if(PHYSFS_setWriteDir(write_path) == 0)
		LOG("File System error while creating write dir: %s\n", PHYSFS_getLastError());
	else
	{
		// We add the writing directory as a reading directory too with speacial mount point
		LOG("Writing directory is %s\n", write_path);
		AddPath(write_path, GetSaveDirectory());
	}

	SDL_free(write_path);

	return ret;
}
Example #3
0
void dmx_device_load_from_disc(void)
{
	char *file_name = "device";
	char *base_path = SDL_GetPrefPath("net.exse", "untel");
	char *file_path = calloc((strlen(base_path)+strlen(file_name)+1),sizeof(char));
	strcat(file_path,base_path);
	strcat(file_path,file_name);
	free(base_path);	
	SDL_RWops *file = SDL_RWFromFile(file_path, "r");
	free(file_path);

	if(file == NULL)
		return;


	unsigned int devices = SDL_ReadBE32(file);

	for(unsigned int x = 0; x < devices;x++)
	{
		unsigned int type =SDL_ReadBE32(file);
		unsigned int addr =SDL_ReadBE32(file);
		unsigned int namelen=SDL_ReadU8(file);

		char name[DMX_NAME_LENGTH];
		if(namelen > DMX_NAME_LENGTH) namelen=DMX_NAME_LENGTH;
		SDL_RWread(file, name, 1, namelen+1);

		if(type == DMX_DEVICE_LEDPAR6)
		{
			dmx_device_create_ledpar6(addr,name);
		}
	}

	SDL_RWclose(file);
}
Example #4
0
static int get_path_info ( void )
{
	FILE *f;
	char buffer[PATH_MAX + 1];
	app_pref_path = NULL;	// to signal that it's not got yet
	/* Get base path (where executable is */
#ifdef __EMSCRIPTEN__
	app_base_path = strdup("/files/");
#else
	app_base_path = SDL_GetBasePath();
	if (!app_base_path) {
		ERROR_WINDOW("Cannot query base directory: %s", ERRSTR());
		return 1;
	}
#endif
	/* Check for pref dir override file in the same directory where executable is (base path) */
	snprintf(buffer, sizeof buffer, "%s%cxep128.dir", app_base_path, DIRSEP[0]);
	f = fopen(buffer, "r");
	if (f) {
		char *p = fgets(buffer, sizeof buffer, f);
		fclose(f);
		if (p) {
			p = strchr(buffer, 13);
			if (p)
				*p = 0;
			p = strchr(buffer, 10);
			if (p)
				*p = 0;
			if (*buffer == '.')
				app_pref_path = strdup(app_base_path);
			else if (*buffer)
				app_pref_path = strdup(buffer);
		}
	}
	/* Pref dir stuff */
	if (app_pref_path) {
		printf("CONFIG: Overriding pref path to: %s" NL, app_pref_path);
	} else {
#ifdef __EMSCRIPTEN__
		app_pref_path = strdup("/files/");
#else
		app_pref_path = SDL_GetPrefPath("nemesys.lgb", "xep128");
		if (!app_pref_path) {
			ERROR_WINDOW("Cannot query preferences directory: %s", ERRSTR());
			return 1;
		}
#endif
	}
	/* Get current directory */
#ifdef __EMSCRIPTEN__
	mkdir("/files", 0777);
	chdir("/files");
#endif
	if (getcwd(current_directory, sizeof current_directory) == NULL) {
		ERROR_WINDOW("Cannot query current directory: %s", ERRSTR());
		return 1;
	}
	strcat(current_directory, DIRSEP);
	return 0;
}
Example #5
0
void CBaseState::Initialize(CRenderManager* pRenderManager, CTextureManager* pTextureManager,
	CInputManager* pInputManager, CFontManager* pFontManager)
{
	m_pRenderManager = pRenderManager;
	m_pTextureManager = pTextureManager;
	m_pInputManager = pInputManager;
	m_pFontManager = pFontManager;

	m_cOverKey = INVALID_BUTTON;

	m_szPrefPath = SDL_GetPrefPath(COMP_NAME, APP_NAME);

	m_fInputDelayTimer = 0.25f;

	m_ucNumButtons = 0;
	m_ppButtons = NULL;

	// FPS Stuff
	m_unFrameCount = 0;
	m_fFPS = 0.0f;

	SDL_Color tColor = { 255, 0, 0, 255 };
	TextData tData = { 0.0f, 1.0f, 0.025f, BOTTOM_LEFT_POS };
	m_pFPSTextQuad = m_pFontManager->TTFCreateText("FPS: ", tColor, tData);

	tData.x += m_pFPSTextQuad->GetDstRect().w;
	m_pFPSQuad = m_pFontManager->TTFCreateText("0.0f", tColor, tData);

	// Last Thing!
	m_unStartTime = SDL_GetTicks();
}
Example #6
0
static void get_core_paths(char **res, char **storage, char **cache) {
	if(*(*res = (char*)env_get("TAISEI_RES_PATH", ""))) {
		*res = strdup(*res);
	} else {
		*res = get_default_res_path();
	}

	if(*(*storage = (char*)env_get("TAISEI_STORAGE_PATH", ""))) {
		*storage = strdup(*storage);
	} else {
		*storage = SDL_GetPrefPath("", "taisei");
	}

	if(*(*cache = (char*)env_get("TAISEI_CACHE_PATH", ""))) {
		*cache = strdup(*cache);
	} else {
		// TODO: follow XDG on linux
		if(*storage != NULL) {
			*cache = strfmt("%s%ccache", *storage, vfs_get_syspath_separator());
		} else {
			*cache = NULL;
		}
	}

	if(*res)     vfs_syspath_normalize_inplace(*res);
	if(*storage) vfs_syspath_normalize_inplace(*storage);
	if(*cache)   vfs_syspath_normalize_inplace(*cache);
}
Example #7
0
static std::string prefPath(const char *org, const char *app)
{
	char *path = SDL_GetPrefPath(org, app);
	std::string str(path);
	SDL_free(path);

	return str;
}
int main(int argc, char *argv[]) {
	app = new App();
	app->video.width = 1024;
	app->video.height = 640;
	app->video.pixel_scale = 1.0f;

	// set preferences_filepath and read preferences
	char *pref_path = SDL_GetPrefPath(COMPANY_NAME, APPLICATION_NAME);

	size_t preferences_ini_str_len = strlen(pref_path)+strlen("preferences.ini")+1;
	app->preferences_filepath = new char[preferences_ini_str_len];
	strcpy(app->preferences_filepath, pref_path);
	strcat(app->preferences_filepath, "preferences.ini");
	size_t session_ini_str_len = strlen(pref_path)+strlen("session.ini")+1;
	app->session_filepath = new char[session_ini_str_len];
	strcpy(app->session_filepath, pref_path);
	strcat(app->session_filepath, "session.ini");
	size_t imgui_ini_str_len = strlen(pref_path)+strlen("imgui.ini")+1;
	ImGuiIO& io = ImGui::GetIO();
	char *imgui_ini_filepath = new char[imgui_ini_str_len];
	strcpy(imgui_ini_filepath, pref_path);
	strcat(imgui_ini_filepath, "imgui.ini");
	io.IniFilename = imgui_ini_filepath;

	SDL_free(pref_path);
	app->readPreferences();
	app->readSession();

	initSDL(&app->video);

	ImGui_ImplSdlGL2_Init(sdl_window);

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

	app->init();

	// init this last for sake of last_ticks
	frametime.init();

	do {
		Uint32 beginTicks = SDL_GetTicks();
		mainLoop();
		// hack for when vsync isn't working
		Uint32 elapsedTicks = SDL_GetTicks() - beginTicks;
		if (elapsedTicks < 16) {
			SDL_Delay(16 - elapsedTicks);
		}
	} while(!app->quit);

	app->beforeQuit();

	ImGui_ImplSdlGL2_Shutdown();
	quitSDL();

	return 0;
}
Example #9
0
int
main(int argc, char *argv[])
{
    char *base_path;
    char *pref_path;

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    if (SDL_Init(0) == -1) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Init() failed: %s\n", SDL_GetError());
        return 1;
    }

    base_path = SDL_GetBasePath();
    if(base_path == NULL){
      SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't find base path: %s\n",
                   SDL_GetError());
      return 1;
    }
    SDL_Log("base path: '%s'\n", base_path);
    SDL_free(base_path);

    pref_path = SDL_GetPrefPath("libsdl", "testfilesystem");
    if(pref_path == NULL){
      SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't find pref path: %s\n",
                   SDL_GetError());
      return 1;
    }
    SDL_Log("pref path: '%s'\n", pref_path); 
    SDL_free(pref_path);

    pref_path = SDL_GetPrefPath(NULL, "testfilesystem");
    if(pref_path == NULL){
      SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't find pref path without organization: %s\n",
                   SDL_GetError());
      return 1;
    }
    SDL_Log("pref path: '%s'\n", pref_path); 
    SDL_free(pref_path);

    SDL_Quit();
    return 0;
}
Example #10
0
/* fills *savedir with the directory path where simplesok is supposed to keep its save files */
static void getsavedir(char *savedir, int maxlen) {
  char *prefpath;
  if (maxlen > 0) savedir[0] = 0;
  maxlen -= 16; /* to be sure we will always have enough room for the app's suffix and extra NULL terminator */
  if (maxlen < 1) return;
  prefpath = SDL_GetPrefPath("Mateusz Viste", "Simple Sokoban");
  if (prefpath == NULL) return;
  if (strlen(prefpath) > (unsigned) maxlen) return;
  strcpy(savedir, prefpath);
  SDL_free(prefpath);
}
Example #11
0
wxFileName GetPlatformDefaultConfigFilePathNew() {
	// SDL builds now use the user directory on all platforms
	// The sdl parameters are defined in the FSO code in the file code/osapi.cpp
	char* prefPath = SDL_GetPrefPath("HardLightProductions", "FreeSpaceOpen");

	wxString wxPrefPath = wxString::FromUTF8(prefPath);

	SDL_free(prefPath);

	wxFileName path;
	path.AssignDir(wxPrefPath);

	return path;
}
Example #12
0
/*
 ==============
 Sys_DefaultSavePath
 ==============
 */
const char* Sys_DefaultSavePath()
{
#if defined(__APPLE__)
	char* base_path = SDL_GetPrefPath( "", "RBDOOM-3-BFG" );
	if( base_path )
	{
		savepath = SDL_strdup( base_path );
		SDL_free( base_path );
	}
#else
	sprintf( savepath, "%s/.rbdoom3bfg", getenv( "HOME" ) );
#endif
	
	return savepath.c_str();
}
Example #13
0
// Called before render is available
bool j1FileSystem::Awake(pugi::xml_node node)
{
	LOG("Loading File System");
	bool ret = true;

	// Ask SDL for a write dir
	char* write_path = SDL_GetPrefPath(ORGANIZATION, APPNAME);

	if(PHYSFS_setWriteDir(write_path) == 0)
		LOG("File System error while creating write dir: %s\n", PHYSFS_getLastError());

	SDL_free(write_path);

	return ret;
}
int
main(int argc, char *argv[])
{
    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    if (SDL_Init(0) == -1) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Init() failed: %s\n", SDL_GetError());
        return 1;
    }

    SDL_Log("base path: '%s'\n", SDL_GetBasePath());
    SDL_Log("pref path: '%s'\n", SDL_GetPrefPath("libsdl", "testfilesystem"));

    SDL_Quit();
    return 0;
}
	static std::string GetFltkPreferencePath() {
#if defined(WIN32)
		std::string path = SdlReceiveString(SDL_GetPrefPath("yvt.jp", "OpenSpades.prefs"));
		if(path.back() == '\\') path.resize(path.size() - 1);
		return path;
#elif defined(__APPLE__)
		const char *homeptr = getenv("HOME");
		std::string home = homeptr ? homeptr : "";
		home += "/Library/Preferences/yvt.jp/OpenSpades.prefs";
		return home;
#else
		const char *homeptr = getenv("HOME");
		std::string home = homeptr ? homeptr : "";
		home += "/.fltk/yvt.jp/OpenSpades.prefs";
		return home;
#endif
	}
ATOMIC_API int WriteMiniDump(const char* applicationName, void* exceptionPointers)
{
    // In case of recursive or repeating exceptions, only write the dump once
    /// \todo This function should not allocate any dynamic memory
    if (miniDumpWritten)
        return EXCEPTION_EXECUTE_HANDLER;
    
    miniDumpWritten = true;
    
    MINIDUMP_EXCEPTION_INFORMATION info;
    info.ThreadId = GetCurrentThreadId();
    info.ExceptionPointers = (EXCEPTION_POINTERS*)exceptionPointers;
    info.ClientPointers = TRUE;
    
    static time_t sysTime;
    time(&sysTime);
    const char* dateTime = ctime(&sysTime);
    String dateTimeStr = String(dateTime);
    dateTimeStr.Replace("\n", "");
    dateTimeStr.Replace(":", "");
    dateTimeStr.Replace("/", "");
    dateTimeStr.Replace(' ', '_');
    
    char* pathName = SDL_GetPrefPath("urho3d", "crashdumps");
    String miniDumpDir(pathName);
    String miniDumpName = miniDumpDir + String(applicationName) + "_" + dateTimeStr + ".dmp";
    if (pathName)
        SDL_free(pathName);
    
    CreateDirectoryW(WString(miniDumpDir).CString(), 0);
    HANDLE file = CreateFileW(WString(miniDumpName).CString(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ,
        0, CREATE_ALWAYS, 0, 0);
    
    BOOL success = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), file, MiniDumpWithDataSegs, &info, 0, 0);
    CloseHandle(file);
    
    if (success)
        ErrorDialog(applicationName, "An unexpected error occurred. A minidump was generated to " + miniDumpName);
    else
        ErrorDialog(applicationName, "An unexpected error occurred. Could not write minidump.");
    
    return EXCEPTION_EXECUTE_HANDLER;
}
Example #17
0
        void init(const char* company, const char* app)
        {
            if (_fsInitialized)
                return;
            _fsInitialized = true;

#ifdef __S3E__
            _nfs.setPath("rom://");
            _nfsWrite.setPath("ram://");
#elif EMSCRIPTEN
            //mkdir("data-ram/", S_IRWXU|S_IRWXG|S_IRWXO);
            //_nfsWrite.setPath("data-ram/");

#elif __ANDROID__
            log::messageln("internal %s", SDL_AndroidGetInternalStoragePath());
            log::messageln("external %s", SDL_AndroidGetExternalStoragePath());
            _nfsWrite.setPath(SDL_AndroidGetInternalStoragePath());
#elif OXYGINE_EDITOR
#elif __APPLE__
            _nfsWrite.setPath(getSupportFolder().c_str());
#else
            if (company && app && *company && *app)
            {
                char* base_path = SDL_GetPrefPath(company, app);
                if (base_path)
                {
                    _nfsWrite.setPath(base_path);
                    SDL_free(base_path);
                }
            }
            else
            {
#   ifdef _WIN32
                _mkdir("../data-ram/");
#   else
                mkdir("../data-ram/", ACCESSPERMS);
#   endif
                _nfsWrite.setPath("../data-ram/");
            }
#endif
            _nfs.mount(&_nfsWrite);
        }
Example #18
0
// Initializes the config system
void _Config::Init(const std::string &ConfigFile) {

	// Create config path
	char *PrefPath = SDL_GetPrefPath("", "choria");
	if(PrefPath) {
		ConfigPath = PrefPath;
		SDL_free(PrefPath);
	}
	else {
		throw std::runtime_error("Cannot create config path!");
	}

	this->ConfigFile = ConfigPath + ConfigFile;

	// Load defaults
	SetDefaults();

	// Load config
	Load();
}
Example #19
0
// Called before render is available
bool j1FileSystem::Awake(pugi::xml_node& config)
{
	LOG("Loading File System");
	bool ret = true;

	// Add all paths in configuration in order
	for(pugi::xml_node path = config.child("path"); path; path = path.next_sibling("path"))
	{
		AddPath(path.child_value());
	}

	// Ask SDL for a write dir
	char* write_path = SDL_GetPrefPath(App->GetOrganization(), App->GetTitle());

	if(PHYSFS_setWriteDir(write_path) == 0)
		LOG("File System error while creating write dir: %s\n", PHYSFS_getLastError());

	SDL_free(write_path);

	return ret;
}
Example #20
0
void dmx_device_store_to_disc(void)
{
	char *file_name = "device";
	char *base_path = SDL_GetPrefPath("net.exse", "untel");
	char *file_path = calloc((strlen(base_path)+strlen(file_name)+1),sizeof(char));
	strcat(file_path,base_path);
	strcat(file_path,file_name);
	free(base_path);	
	SDL_RWops *file = SDL_RWFromFile(file_path, "w");
	free(file_path);

	SDL_WriteBE32(file,devices_inuse);
	for(unsigned int i=0;i<devices_inuse;i++)
	{
		SDL_WriteBE32(file,dmx_device_list[i].type);
		SDL_WriteBE32(file,dmx_device_list[i].addr);
		SDL_WriteU8(file,strnlen(dmx_device_list[i].name,DMX_NAME_LENGTH));
		SDL_RWwrite(file,dmx_device_list[i].name,1,1+strnlen(dmx_device_list[i].name,DMX_NAME_LENGTH));
	}

	SDL_RWclose(file);
}
    FILE* platform_support::open_rw_file(const char* org,
          const char* app, const char* fname)
    {
       DEBUG_PRINT("open_rw %s, %s, %s", org, app, fname);
#ifdef __ANDROID__
       SDL_RWops* ops = SDL_RWFromFile(fname, "r+");
       if (ops)
       {
          return ops->hidden.stdio.fp;
       }
       ops = SDL_RWFromFile(fname, "w+");
       {
          return ops->hidden.stdio.fp;
       }
       return NULL;
#else
       char* path = SDL_GetPrefPath(org, app);
       if (!path)
       {
          ERROR_PRINT("Couldn't get path: %s\n", SDL_GetError());
          return NULL;
       }
       char filename[1024];
       strcpy(filename, path);
       strcat(filename, fname);
       FILE* f = fopen(filename, "r+");
       if (!f)
       {
          ERROR_PRINT("could not open file: %s\n", strerror(errno));
          f = fopen(filename, "w+");
          if (!f)
             ERROR_PRINT("could not open file: %s\n", strerror(errno));
       }
       SDL_free(path);
       return f;
#endif
    }
bool FileSystem::awake(pugi::xml_node &node)
{
	bool ret = true;

	for (pugi::xml_node path = node.child("path"); path ; path = path.next_sibling("path"))
		addSearchPath(path.child_value());

	char *write_dir = SDL_GetPrefPath("Carlos", "Game_development");

	if (PHYSFS_setWriteDir(write_dir) == 0)
	{
		LOG("%s,%s","Error on setting Write Dir. Error:", PHYSFS_getLastError());
		ret = false;
	}
	else
	{
		LOG("%s %s", "Write directory is ", write_dir);
		addSearchPath(write_dir, getSaveDirectory());
	}

	SDL_free(write_dir);
	
	return ret;
}
Example #23
0
int
main(int argc, char *argv[])
{
    /* initialize SDL */
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        GUI_Log("Could not initialize SDL");
    }
    if (TTF_Init() != 0){
        GUI_Log( "TTF_Init failed.");
        SDL_Quit();
        return 1;
    }
    if( GUI_Init() != 0 ) {
        GUI_Log( "GUI_Init failed." );
        TTF_Quit();
        SDL_Quit();
        return 1;
    }
    
    char *pref = SDL_GetPrefPath( "JimmySoftware.com", "ToolBarDialog" );
    strcpy( preferenctPath, pref );
    strcat( preferenctPath, "preference.conf" );
    
    SDL_Log( "Pref: %s\n", preferenctPath );
    if( access( preferenctPath, 0 ) != -1 ) {
        GUI_Log( "File Existed\n" );
        loadPalette( preferenctPath );
    } else {
        GUI_Log( "File not existed\n" );
        for( int i=0; i<numPalette; i++ ) {
            for( int j=0; j<numColor; j++ ) {
                mainPalette[i][j] = mColor[j];
            }
        }
    }
    activePalette = 0;
    
    //int sx = 720, sy = 405;
#if __IPHONEOS__ or __ANDROID__
    int sx = 640, sy = 360;
#else
    int sx = 640, sy = 360;
#endif
    SDL_Window *window = GUI_CreateWindow( "GUI", sx, sy );
    if (window == NULL) {
        fatalError("GUI_CreateWindow Error");
        return 1;
    }
    
    SCREEN_WIDTH = GUI_windowWidth;
    SCREEN_HEIGHT = GUI_windowHeight;
    
    topWin=new GUI_TopWin( "TopWin", GUI_Rect(0,0,GUI_windowWidth,GUI_windowHeight),0,
       []( GUI_WinBase *tw ) {
           //tw->clear();
       }
    );
    
    textureFileIcon = loadTexture( "icon_file.png", GUI_renderer );

    
    GUI_WinBase *topBar = new GUI_WinBase( topWin, "TopBar", 0, 0, GUI_windowWidth, 48, cDarkGrey );
    if( topBar ) {
        GUI_Button *bttnFile = new GUI_Button( topBar, "F", 8, 8, 32, 32, cGrey,
            [](GUI_Button *bt) {
                if( menuFile == NULL ) {
                    GUI_Log( "create new MenuFile\n" );
                    static const char *menuText[] = {
                        "File", "Open", "Save", "Exit", NULL
                    };
                    menuFile = new GUI_List( topWin, menuText, 4, bt->tw_area.x, bt->tw_area.y+bt->tw_area.w+10, 240, 0, 0, true,
                        [](GUI_List *l,const char *sel, int index) {
                            switch (index) {
                                case 1:
                                    OpenFile();
                                    break;
                                case 3:
                                    SDL_AddTimer( 100, ExitCallback, NULL );
                                    break;
                                default:
                                    break;
                            }
                            menuFile = NULL;
                        }
                    );
                    menuFile->title_str = "Menu File";
                    menuFile->onClose = [] (GUI_WinBase *) -> bool {
                        menuFile = NULL;
                        return true;
                    };
                }
            }
        );
        bttnFile->texImage = textureFileIcon;
        bttnFile->color = cClear;
        
        new GUI_Button( topBar, "C", 48, 8, 32, 32, cGrey,
            [](GUI_Button *bt) {
                OpenColor();
            }
        );
        
        GUI_WinBase *colorBox = new GUI_WinBase( topBar, "สี", 88, 6, 32*9+18, 36, cClear,
                                                [](GUI_WinBase *wb) {
                                                    GUI_FillRoundRect( 0, 0, wb->tw_area.w, wb->tw_area.h, wb->tw_area.h/2, sdl_color( 0x484848ff ) );
                                                }
                                                );
        if( colorBox ) {
            for( int i=0; i<numColor; i++ ) {
                c[i] = new GUI_Button( colorBox, "", 6+32*i, 3, 31, 31, mainPalette[activePalette][i], setActiveColor );
                c[i]->tag = i;
                c[i]->radius = 15;
                c[i]->border = 1;
            }
            
            setActiveColor( c[0] );
            
            GUI_WinBase *paletteButton = new GUI_WinBase( colorBox, "Palette", 6+32*numColor+5, 3+8, 25, 15, cClear,
                [](GUI_WinBase *w)
                {
                    //GUI_DrawRect( GUI_MakeRect(0, 0, w->tw_area.w, w->tw_area.h), cBlack );
                    SDL_RenderCopy(GUI_renderer, GUI_dropdownTexture, NULL, GUI_MakeRect(1, 1, w->tw_area.w-2, w->tw_area.h-2));
                }
            );
            paletteButton->handle_event_cmd = [](GUI_WinBase *w, SDL_Event* ev ) -> bool {
                switch (ev->type) {
                    case SDL_MOUSEBUTTONUP: {
                        static const char *menuPalette[] = {
                            "Palette1", "Palette2", "Palette3", "Palette4", "Palette5", "---", "Load", "Save", NULL
                        };

                        //GUI_Log( "Palette\n" );
                        GUI_List *listPal = new GUI_List( topWin, menuPalette, 8, w->tw_area.x, w->tw_area.y+w->tw_area.h+18, 240, 0, 0, true,
                                     [](GUI_List* l,const char*sz,int n) {
                                         if( n < numPalette ) {
                                             activePalette = n;
                                             l->setCheck( n );
                                             for( int i=0; i<numColor; i++ ) {
                                                 c[i]->color = mainPalette[n][i];
                                             }
                                         }
                                         else if( n == numPalette + 1 ) {
                                             SDL_AddTimer( 100, LoadPaletteCallback, NULL );
                                         }
                                         else if( n == numPalette + 2 ) {
                                             SDL_AddTimer( 100, SavePaletteCallback, NULL );
                                         }
                                     });
                        for( int i=0; i<numPalette; i++ ) {
                            GUI_ListCell *cell = listPal->getCell( i );
                            cell->checkable = true;
                            cell->display_cmd = cellDraw;
                        }
                        listPal->setCheck( activePalette );
                    }
                }
                return false;
            };

        }
    }
    
    GUI_WinBase *sizeBox = new GUI_WinBase( topBar, "สี", 402, 6, 32*3+6, 36, cClear,
                                            [](GUI_WinBase *wb) {
                                                GUI_FillRoundRect( 0, 0, wb->tw_area.w, wb->tw_area.h, 10, sdl_color( 0x484848ff ) );
                                            }
                                            );
    if( sizeBox ) {
        for( int i=0; i<numSize; i++ ) {
            s[i] = new GUI_Button( sizeBox, "", 3+32*i, 3, 30, 30, cClear, setActiveSize );
            s[i]->tag = i;
            s[i]->radius = 5;
            s[i]->border = 1;
            s[i]->display_cmd = [](GUI_WinBase *w) {
                int bw = 12 + w->tag * 6;
                int cw = 0;
                if( w->tag == 1 )
                    cw -= 3;
                GUI_FillRect( cw+(w->tw_area.w-bw)/2, (w->tw_area.h-bw)/2, bw, bw, cGrey );
                GUI_DrawRect( cw+(w->tw_area.w-bw)/2, (w->tw_area.h-bw)/2, bw, bw, ((GUI_Button*)w)->borderColor );
            };
        }
        setActiveSize( s[0] );
    }
    
    GUI_WinBase *bottomBar = new GUI_WinBase( topWin, "BottomBar", 0, GUI_windowHeight-48, GUI_windowWidth, 48, cDarkGrey );


    //createTestWindows( 20, 20, "Red", cRed );

    
    GUI_Run();
    
    savePalette( preferenctPath );
    
    
    
    /* shutdown SDL */
    GUI_Quit();
    TTF_Quit();
    SDL_Quit();
    
    return 0;
}
Example #24
0
	const char* System::GetDirectory (SystemDirectory type, const char* company, const char* title) {
		
		switch (type) {
			
			case APPLICATION:
				
				return SDL_GetBasePath ();
				break;
			
			case APPLICATION_STORAGE:
				
				return SDL_GetPrefPath (company, title);
				break;
			
			case DESKTOP: {
				
				#if defined (HX_WINRT)
				
				Windows::Storage::StorageFolder folder = Windows::Storage::KnownFolders::HomeGroup;
				std::wstring resultW (folder->Begin ());
				std::string result (resultW.begin (), resultW.end ());
				return result.c_str ();
				
				#elif defined (HX_WINDOWS)
				
				char result[MAX_PATH] = "";
				SHGetFolderPath (NULL, CSIDL_DESKTOPDIRECTORY, NULL, SHGFP_TYPE_CURRENT, result);
				return WIN_StringToUTF8 (result);
				
				#else
				
				std::string result = std::string (getenv ("HOME")) + std::string ("/Desktop");
				return result.c_str ();
				
				#endif
				break;
				
			}
			
			case DOCUMENTS: {
				
				#if defined (HX_WINRT)
				
				Windows::Storage::StorageFolder folder = Windows::Storage::KnownFolders::DocumentsLibrary;
				std::wstring resultW (folder->Begin ());
				std::string result (resultW.begin (), resultW.end ());
				return result.c_str ();
				
				#elif defined (HX_WINDOWS)
				
				char result[MAX_PATH] = "";
				SHGetFolderPath (NULL, CSIDL_MYDOCUMENTS, NULL, SHGFP_TYPE_CURRENT, result);
				return WIN_StringToUTF8 (result);
				
				#else
				
				std::string result = std::string (getenv ("HOME")) + std::string ("/Documents");
				return result.c_str ();
				
				#endif
				break;
				
			}
			
			case FONTS: {
				
				#if defined (HX_WINRT)
				
				return 0;
				
				#elif defined (HX_WINDOWS)
				
				char result[MAX_PATH] = "";
				SHGetFolderPath (NULL, CSIDL_FONTS, NULL, SHGFP_TYPE_CURRENT, result);
				return WIN_StringToUTF8 (result);
				
				#elif defined (HX_MACOS)
				
				return "/Library/Fonts";
				
				#elif defined (IPHONEOS)
				
				return "/System/Library/Fonts";
				
				#elif defined (ANDROID)
				
				return "/system/fonts";
				
				#elif defined (BLACKBERRY)
				
				return "/usr/fonts/font_repository/monotype";
				
				#else
				
				return "/usr/share/fonts/truetype";
				
				#endif
				break;
				
			}
			
			case USER: {
				
				#if defined (HX_WINRT)
				
				Windows::Storage::StorageFolder folder = Windows::Storage::ApplicationData::Current->RoamingFolder;
				std::wstring resultW (folder->Begin ());
				std::string result (resultW.begin (), resultW.end ());
				return result.c_str ();
				
				#elif defined (HX_WINDOWS)
				
				char result[MAX_PATH] = "";
				SHGetFolderPath (NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT, result);
				return WIN_StringToUTF8 (result);
				
				#else
				
				std::string result = getenv ("HOME");
				return result.c_str ();
				
				#endif
				break;
				
			}
			
		}
		
		return 0;
		
	}
Example #25
0
	s32 proc()
	{
#if _WIN32
		SetProcessDPIAware();
#endif

#if defined(__APPLE__)
		SDL_SetHint(SDL_HINT_MOUSE_RELATIVE_MODE_WARP, "1");
#endif

		// Initialize SDL
		if (SDL_Init(
			SDL_INIT_VIDEO
			| SDL_INIT_EVENTS
			| SDL_INIT_GAMECONTROLLER
			| SDL_INIT_HAPTIC
			| SDL_INIT_TIMER
			| SDL_INIT_JOYSTICK
		) < 0)
		{
			fprintf(stderr, "Failed to initialize SDL: %s\n", SDL_GetError());
			return -1;
		}

		Loader::data_directory = SDL_GetPrefPath("HelveticaScenario", "Yearning");

		SDL_GameControllerAddMappingsFromFile("gamecontrollerdb.txt");

		SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
		SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);

		{
			SDL_DisplayMode display;
			SDL_GetDesktopDisplayMode(0, &display);
			Loader::settings_load(display.w, display.h);
		}

		if (SDL_SetRelativeMouseMode(SDL_TRUE) != 0)
		{
			fprintf(stderr, "Failed to set relative mouse mode: %s\n", SDL_GetError());
			return -1;
		}

		window = SDL_CreateWindow
		(
			"The Yearning",
			0,
			0,
			Settings::width, Settings::height,
			SDL_WINDOW_OPENGL
			| SDL_WINDOW_SHOWN
			| SDL_WINDOW_INPUT_GRABBED
			| SDL_WINDOW_INPUT_FOCUS
			| SDL_WINDOW_MOUSE_FOCUS
			| SDL_WINDOW_MOUSE_CAPTURE
			| SDL_WINDOW_ALLOW_HIGHDPI
			| (Settings::fullscreen ? SDL_WINDOW_FULLSCREEN : SDL_WINDOW_BORDERLESS)
		);

#if defined(__APPLE__)
		SDL_SetWindowGrab(window, SDL_TRUE);
#endif

		// Open a window and create its OpenGL context
		if (!window)
		{
			fprintf(stderr, "Failed to open SDL window. Most likely your GPU is out of date! %s\n", SDL_GetError());
			SDL_Quit();
			return -1;
		}

		SDL_GLContext context = SDL_GL_CreateContext(window);
		if (!context)
		{
			fprintf(stderr, "Failed to create GL context: %s\n", SDL_GetError());
			return -1;
		}

		if (SDL_GL_SetSwapInterval(Settings::vsync ? 1 : 0) != 0)
		{
			fprintf(stderr, "Failed to set OpenGL swap interval: %s\n", SDL_GetError());
			return -1;
		}

		{
			glewExperimental = true; // Needed for core profile

			GLenum glew_result = glewInit();
			if (glew_result != GLEW_OK)
			{
				fprintf(stderr, "Failed to initialize GLEW: %s\n", glewGetErrorString(glew_result));
				return -1;
			}
		}

		glGetError(); // Clear initial error caused by GLEW

		render_init();

		// Launch threads

		Sync<LoopSync> render_sync;

		LoopSwapper swapper_render_update = render_sync.swapper(0);
		LoopSwapper swapper_render = render_sync.swapper(1);

		Sync<PhysicsSync, 1> physics_sync;

		PhysicsSwapper swapper_physics = physics_sync.swapper();
		PhysicsSwapper swapper_physics_update = physics_sync.swapper();

		std::thread thread_physics(Physics::loop, &swapper_physics);

		std::thread thread_update(Loop::loop, &swapper_render_update, &swapper_physics_update);

		std::thread thread_ai(AI::loop);

		LoopSync* sync = swapper_render.get();

		r64 last_time = SDL_GetTicks() / 1000.0;

		b8 has_focus = true;

		SDL_PumpEvents();

		const u8* sdl_keys = SDL_GetKeyboardState(0);

		refresh_controllers();

		while (true)
		{
			render(sync);

			// Swap buffers
			SDL_GL_SwapWindow(window);

			SDL_PumpEvents();

			memcpy(sync->input.keys, sdl_keys, sizeof(sync->input.keys));

			sync->input.keys[(s32)KeyCode::MouseWheelDown] = false;
			sync->input.keys[(s32)KeyCode::MouseWheelUp] = false;

			SDL_Event sdl_event;
			while (SDL_PollEvent(&sdl_event))
			{
				if (sdl_event.type == SDL_QUIT)
					sync->quit = true;
				else if (sdl_event.type == SDL_MOUSEWHEEL)
				{ 
					b8 up = sdl_event.wheel.y > 0;
					if (sdl_event.wheel.direction == SDL_MOUSEWHEEL_FLIPPED)
						up = !up;
					if (up)
						sync->input.keys[(s32)KeyCode::MouseWheelUp] = true;
					else
						sync->input.keys[(s32)KeyCode::MouseWheelDown] = true;
				} 
				else if (sdl_event.type == SDL_JOYDEVICEADDED
					|| sdl_event.type == SDL_JOYDEVICEREMOVED)
					refresh_controllers();
				else if (sdl_event.type == SDL_WINDOWEVENT)
				{
					if (sdl_event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED)
						has_focus = true;
					else if (sdl_event.window.event == SDL_WINDOWEVENT_FOCUS_LOST)
						has_focus = false;
				}
			}

			sync->input.focus = has_focus;

			s32 mouse_buttons = SDL_GetRelativeMouseState(&sync->input.cursor_x, &sync->input.cursor_y);

			sync->input.keys[(s32)KeyCode::MouseLeft] = mouse_buttons & (1 << 0);
			sync->input.keys[(s32)KeyCode::MouseMiddle] = mouse_buttons & (1 << 1);
			sync->input.keys[(s32)KeyCode::MouseRight] = mouse_buttons & (1 << 2);

			s32 active_gamepads = 0;
			for (s32 i = 0; i < MAX_GAMEPADS; i++)
			{
				SDL_GameController* controller = controllers[i];
				Gamepad* gamepad = &sync->input.gamepads[i];
				gamepad->active = controller != 0;
				gamepad->btns = 0;
				if (gamepad->active)
				{
					gamepad->left_x = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_LEFTX) / 32767.0f;
					gamepad->left_y = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_LEFTY) / 32767.0f;
					gamepad->right_x = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_RIGHTX) / 32767.0f;
					gamepad->right_y = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_RIGHTY) / 32767.0f;
					gamepad->left_trigger = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_TRIGGERLEFT) / 32767.0f;
					gamepad->right_trigger = (r32)SDL_GameControllerGetAxis(controller, SDL_CONTROLLER_AXIS_TRIGGERRIGHT) / 32767.0f;
					if (gamepad->left_trigger > 0.5f)
						gamepad->btns |= Gamepad::Btn::LeftTrigger;
					if (gamepad->right_trigger > 0.5f)
						gamepad->btns |= Gamepad::Btn::RightTrigger;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_LEFTSHOULDER))
						gamepad->btns |= Gamepad::Btn::LeftShoulder;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER))
						gamepad->btns |= Gamepad::Btn::RightShoulder;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_LEFTSTICK))
						gamepad->btns |= Gamepad::Btn::LeftClick;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_RIGHTSTICK))
						gamepad->btns |= Gamepad::Btn::RightClick;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_A))
						gamepad->btns |= Gamepad::Btn::A;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_B))
						gamepad->btns |= Gamepad::Btn::B;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_X))
						gamepad->btns |= Gamepad::Btn::X;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_Y))
						gamepad->btns |= Gamepad::Btn::Y;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_BACK))
						gamepad->btns |= Gamepad::Btn::Back;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_START))
						gamepad->btns |= Gamepad::Btn::Start;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_DPAD_UP))
						gamepad->btns |= Gamepad::Btn::DUp;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_DPAD_DOWN))
						gamepad->btns |= Gamepad::Btn::DDown;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_DPAD_LEFT))
						gamepad->btns |= Gamepad::Btn::DLeft;
					if (SDL_GameControllerGetButton(controller, SDL_CONTROLLER_BUTTON_DPAD_RIGHT))
						gamepad->btns |= Gamepad::Btn::DRight;
					if (gamepad->rumble > 0.0f)
						SDL_HapticRumblePlay(haptics[i], gamepad->rumble, 33);
					gamepad->rumble = 0.0f;
					active_gamepads++;
				}
				else
				{
					gamepad->left_x = 0.0f;
					gamepad->left_y = 0.0f;
					gamepad->right_x = 0.0f;
					gamepad->right_y = 0.0f;
					gamepad->left_trigger = 0.0f;
					gamepad->right_trigger = 0.0f;
					gamepad->rumble = 0.0f;
				}
			}

			SDL_GetWindowSize(window, &sync->input.width, &sync->input.height);

			r64 time = (SDL_GetTicks() / 1000.0);
			sync->time.total = (r32)time;
			sync->time.delta = vi_min((r32)(time - last_time), 0.25f);
			last_time = time;

			b8 quit = sync->quit;

			sync = swapper_render.swap<SwapType_Read>();

			if (quit || sync->quit)
				break;
		}

		AI::quit();

		thread_update.join();
		thread_physics.join();
		thread_ai.join();

		SDL_GL_DeleteContext(context);
		SDL_DestroyWindow(window);

		// SDL sucks
		for (s32 i = 0; i < MAX_GAMEPADS; i++)
		{
			if (haptics[i])
				SDL_HapticClose(haptics[i]);
		}

		SDL_Quit();

		return 0;
	}
Example #26
0
int
Main::run(int argc, char** argv)
{
#ifdef WIN32
	//SDL is used instead of PHYSFS because both create the same path in app data
	//However, PHYSFS is not yet initizlized, and this should be run before anything is initialized
	std::string prefpath = SDL_GetPrefPath("SuperTux", "supertux2");

	std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;

	//All this conversion stuff is necessary to make this work for internationalized usernames
	std::string outpath = prefpath + u8"/console.out";
	std::wstring w_outpath = converter.from_bytes(outpath);
	_wfreopen(w_outpath.c_str(), L"a", stdout);

	std::string errpath = prefpath + u8"/console.err";
	std::wstring w_errpath = converter.from_bytes(errpath);
	_wfreopen(w_errpath.c_str(), L"a", stderr);
#endif

  // Create and install global locale
  std::locale::global(boost::locale::generator().generate(""));
  // Make boost.filesystem use it
  boost::filesystem::path::imbue(std::locale());

  int result = 0;

  try
  {
    CommandLineArguments args;

    try
    {
      args.parse_args(argc, argv);
      g_log_level = args.get_log_level();
    }
    catch(const std::exception& err)
    {
      std::cout << "Error: " << err.what() << std::endl;
      return EXIT_FAILURE;
    }

    PhysfsSubsystem physfs_subsystem(argv[0], args.datadir, args.userdir);
    physfs_subsystem.print_search_path();

    timelog("config");
    ConfigSubsystem config_subsystem;
    args.merge_into(*g_config);

    timelog("tinygettext");
    init_tinygettext();

    switch (args.get_action())
    {
      case CommandLineArguments::PRINT_VERSION:
        args.print_version();
        return 0;

      case CommandLineArguments::PRINT_HELP:
        args.print_help(argv[0]);
        return 0;

      case CommandLineArguments::PRINT_DATADIR:
        args.print_datadir();
        return 0;

      default:
        launch_game();
        break;
    }
  }
  catch(const std::exception& e)
  {
    log_fatal << "Unexpected exception: " << e.what() << std::endl;
    result = 1;
  }
  catch(...)
  {
    log_fatal << "Unexpected exception" << std::endl;
    result = 1;
  }

  g_dictionary_manager.reset();

  return result;
}
Example #27
0
int
Main::run(int argc, char** argv)
{
#ifdef WIN32
	//SDL is used instead of PHYSFS because both create the same path in app data
	//However, PHYSFS is not yet initizlized, and this should be run before anything is initialized
	std::string prefpath = SDL_GetPrefPath("SuperTux", "supertux2");
	freopen((prefpath + "/console.out").c_str(), "a", stdout);
	freopen((prefpath + "/console.err").c_str(), "a", stderr);
#endif
 
  int result = 0;

  try
  {
    CommandLineArguments args;

    try
    {
      args.parse_args(argc, argv);
      g_log_level = args.get_log_level();
    }
    catch(const std::exception& err)
    {
      std::cout << "Error: " << err.what() << std::endl;
      return EXIT_FAILURE;
    }

    PhysfsSubsystem physfs_subsystem(argv[0], args.datadir, args.userdir);
    physfs_subsystem.print_search_path();

    timelog("config");
    ConfigSubsystem config_subsystem;
    args.merge_into(*g_config);

    timelog("tinygettext");
    init_tinygettext();

    switch (args.get_action())
    {
      case CommandLineArguments::PRINT_VERSION:
        args.print_version();
        return 0;

      case CommandLineArguments::PRINT_HELP:
        args.print_help(argv[0]);
        return 0;

      case CommandLineArguments::PRINT_DATADIR:
        args.print_datadir();
        return 0;

      default:
        launch_game();
        break;
    }
  }
  catch(const std::exception& e)
  {
    log_fatal << "Unexpected exception: " << e.what() << std::endl;
    result = 1;
  }
  catch(...)
  {
    log_fatal << "Unexpected exception" << std::endl;
    result = 1;
  }

  g_dictionary_manager.reset();

  return result;
}