Exemple #1
0
/**
 * Load an old fashioned GRF file.
 * @param filename   The name of the file to open.
 * @param load_index The offset of the first sprite.
 * @param file_index The Fio offset to load the file in.
 * @return The number of loaded sprites.
 */
static uint LoadGrfFile(const char *filename, uint load_index, int file_index)
{
	uint load_index_org = load_index;
	uint sprite_id = 0;

	FioOpenFile(file_index, filename, BASESET_DIR);

	DEBUG(sprite, 2, "Reading grf-file '%s'", filename);

	byte container_ver = GetGRFContainerVersion();
	if (container_ver == 0) usererror("Base grf '%s' is corrupt", filename);
	ReadGRFSpriteOffsets(container_ver);
	if (container_ver >= 2) {
		/* Read compression. */
		byte compression = FioReadByte();
		if (compression != 0) usererror("Unsupported compression format");
	}

	while (LoadNextSprite(load_index, file_index, sprite_id, container_ver)) {
		load_index++;
		sprite_id++;
		if (load_index >= MAX_SPRITES) {
			usererror("Too many sprites. Recompile with higher MAX_SPRITES value or remove some custom GRF files.");
		}
	}
	DEBUG(sprite, 2, "Currently %i sprites are loaded", load_index);

	return load_index - load_index_org;
}
Exemple #2
0
/**
 * Load an old fashioned GRF file to replace already loaded sprites.
 * @param filename   The name of the file to open.
 * @param index_tlb  The offsets of each of the sprites.
 * @param file_index The Fio offset to load the file in.
 * @return The number of loaded sprites.
 */
static void LoadGrfFileIndexed(const char *filename, const SpriteID *index_tbl, int file_index)
{
	uint start;
	uint sprite_id = 0;

	FioOpenFile(file_index, filename, BASESET_DIR);

	DEBUG(sprite, 2, "Reading indexed grf-file '%s'", filename);

	byte container_ver = GetGRFContainerVersion();
	if (container_ver == 0) usererror("Base grf '%s' is corrupt", filename);
	ReadGRFSpriteOffsets(container_ver);
	if (container_ver >= 2) {
		/* Read compression. */
		byte compression = FioReadByte();
		if (compression != 0) usererror("Unsupported compression format");
	}

	while ((start = *index_tbl++) != END) {
		uint end = *index_tbl++;

		do {
			bool b = LoadNextSprite(start, file_index, sprite_id, container_ver);
			assert(b);
			sprite_id++;
		} while (++start <= end);
	}
}
static void CreateWindowsConsoleThread()
{
	DWORD dwThreadId;
	/* Create event to signal when console input is ready */
	_hInputReady = CreateEvent(NULL, false, false, NULL);
	_hWaitForInputHandling = CreateEvent(NULL, false, false, NULL);
	if (_hInputReady == NULL || _hWaitForInputHandling == NULL) usererror("Cannot create console event!");

	_hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)CheckForConsoleInput, NULL, 0, &dwThreadId);
	if (_hThread == NULL) usererror("Cannot create console thread!");

	DEBUG(driver, 2, "Windows console thread started");
}
Exemple #4
0
/**
 * Allocates new item with given index
 * @param size size of item
 * @param index index of item
 * @return pointer to allocated item
 * @note usererror() on failure! (index out of range or already used)
 */
DEFINE_POOL_METHOD(void *)::GetNew(size_t size, size_t index)
{
	if (index >= Tmax_size) {
		usererror("failed loading savegame: %s index " PRINTF_SIZE " out of range (" PRINTF_SIZE ")", this->name, index, Tmax_size);
	}

	if (index >= this->size) this->ResizeFor(index);

	if (this->data[index] != NULL) {
		usererror("failed loading savegame: %s index " PRINTF_SIZE " already in use", this->name, index);
	}

	return this->AllocateItem(size, index);
}
Exemple #5
0
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	int argc;
	char *argv[64]; // max 64 command line arguments

	CrashLog::InitialiseCrashLog();

#if defined(UNICODE)
	/* Check if a win9x user started the win32 version */
	if (HasBit(GetVersion(), 31)) usererror("This version of OpenTTD doesn't run on windows 95/98/ME.\nPlease download the win9x binary and try again.");
#endif

	/* Convert the command line to UTF-8. We need a dedicated buffer
	 * for this because argv[] points into this buffer and this needs to
	 * be available between subsequent calls to FS2OTTD(). */
	char *cmdline = stredup(FS2OTTD(GetCommandLine()));

#if defined(_DEBUG)
	CreateConsole();
#endif

	_set_error_mode(_OUT_TO_MSGBOX); // force assertion output to messagebox

	/* setup random seed to something quite random */
	SetRandomSeed(GetTickCount());

	argc = ParseCommandLine(cmdline, argv, lengthof(argv));

	/* Make sure our arguments contain only valid UTF-8 characters. */
	for (int i = 0; i < argc; i++) ValidateString(argv[i]);

	openttd_main(argc, argv);
	free(cmdline);
	return 0;
}
void FioOpenFile(int slot, const char *filename)
{
	FILE *f;

#if defined(LIMITED_FDS)
	FioFreeHandle();
#endif /* LIMITED_FDS */
	f = FioFOpenFile(filename);
	if (f == NULL) usererror("Cannot open file '%s'", filename);
	uint32 pos = ftell(f);

	FioCloseFile(slot); // if file was opened before, close it
	_fio.handles[slot] = f;
	_fio.filenames[slot] = filename;

	/* Store the filename without path and extension */
	const char *t = strrchr(filename, PATHSEPCHAR);
	_fio.shortnames[slot] = strdup(t == NULL ? filename : t);
	char *t2 = strrchr(_fio.shortnames[slot], '.');
	if (t2 != NULL) *t2 = '\0';
	strtolower(_fio.shortnames[slot]);

#if defined(LIMITED_FDS)
	_fio.usage_count[slot] = 0;
	_fio.open_handles++;
#endif /* LIMITED_FDS */
	FioSeekToFile(slot, pos);
}
Exemple #7
0
static void GetVideoModes()
{
	SDL_Rect **modes = SDL_CALL SDL_ListModes(NULL, SDL_SWSURFACE | SDL_FULLSCREEN);
	if (modes == NULL) usererror("sdl: no modes available");

	_all_modes = (SDL_CALL SDL_ListModes(NULL, SDL_SWSURFACE | (_fullscreen ? SDL_FULLSCREEN : 0)) == (void*)-1);
	if (modes == (void*)-1) {
		int n = 0;
		for (uint i = 0; i < lengthof(_default_resolutions); i++) {
			if (SDL_CALL SDL_VideoModeOK(_default_resolutions[i].width, _default_resolutions[i].height, 8, SDL_FULLSCREEN) != 0) {
				_resolutions[n] = _default_resolutions[i];
				if (++n == lengthof(_resolutions)) break;
			}
		}
		_num_resolutions = n;
	} else {
		int n = 0;
		for (int i = 0; modes[i]; i++) {
			uint w = modes[i]->w;
			uint h = modes[i]->h;
			int j;
			for (j = 0; j < n; j++) {
				if (_resolutions[j].width == w && _resolutions[j].height == h) break;
			}

			if (j == n) {
				_resolutions[j].width  = w;
				_resolutions[j].height = h;
				if (++n == lengthof(_resolutions)) break;
			}
		}
		_num_resolutions = n;
		SortResolutions(_num_resolutions);
	}
}
Exemple #8
0
/**
 * Handle all procedures for bootstrapping OpenTTD without a base graphics set.
 * This requires all kinds of trickery that is needed to avoid the use of
 * sprites from the base graphics set which are pretty interwoven.
 * @return True if a base set exists, otherwise false.
 */
bool HandleBootstrap()
{
	if (BaseGraphics::GetUsedSet() != NULL) return true;

	/* No user interface, bail out with an error. */
	if (BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() == 0) goto failure;

	/* If there is no network or no freetype, then there is nothing we can do. Go straight to failure. */
#if defined(ENABLE_NETWORK) && defined(WITH_FREETYPE) && !defined(__APPLE__) && (defined(WITH_FONTCONFIG) || defined(WIN32))
	if (!_network_available) goto failure;

	/* First tell the game we're bootstrapping. */
	_game_mode = GM_BOOTSTRAP;

	/* Initialise the freetype font code. */
	InitializeUnicodeGlyphMap();
	/* Next "force" finding a suitable freetype font as the local font is missing. */
	CheckForMissingGlyphs(false);

	/* Initialise the palette. The biggest step is 'faking' some recolour sprites.
	 * This way the mauve and gray colours work and we can show the user interface. */
	GfxInitPalettes();
	static const int offsets[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x80, 0, 0, 0, 0x04, 0x08 };
	for (uint i = 0; i != 16; i++) {
		for (int j = 0; j < 8; j++) {
			_colour_gradient[i][j] = offsets[i] + j;
		}
	}

	/* Finally ask the question. */
	new BootstrapBackground();
	new BootstrapAskForDownloadWindow();

	/* Process the user events. */
	_video_driver->MainLoop();

	/* _exit_game is used to get out of the video driver's main loop.
	 * In case GM_BOOTSTRAP is still set we did not exit it via the
	 * "download complete" event, so it was a manual exit. Obey it. */
	_exit_game = _game_mode == GM_BOOTSTRAP;
	if (_exit_game) return false;

	/* Try to probe the graphics. Should work this time. */
	if (!BaseGraphics::SetSet(NULL)) goto failure;

	/* Finally we can continue heading for the menu. */
	_game_mode = GM_MENU;
	return true;
#endif

	/* Failure to get enough working to get a graphics set. */
failure:
	usererror("Failed to find a graphics set. Please acquire a graphics set for OpenTTD. See section 4.1 of readme.txt.");
	return false;
}
Exemple #9
0
static bool CreateMainSurface(uint w, uint h)
{
	SDL_Surface *newscreen, *icon;
	char caption[50];
	int bpp = BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth();

	GetAvailableVideoMode(&w, &h);

	DEBUG(driver, 1, "SDL: using mode %ux%ux%d", w, h, bpp);

	if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals");

	/* Give the application an icon */
	icon = SDL_CALL SDL_LoadBMP(ICON_DIR PATHSEP "openttd.32.bmp");
	if (icon != NULL) {
		/* Get the colourkey, which will be magenta */
		uint32 rgbmap = SDL_CALL SDL_MapRGB(icon->format, 255, 0, 255);

		SDL_CALL SDL_SetColorKey(icon, SDL_SRCCOLORKEY, rgbmap);
		SDL_CALL SDL_WM_SetIcon(icon, NULL);
		SDL_CALL SDL_FreeSurface(icon);
	}

	/* DO NOT CHANGE TO HWSURFACE, IT DOES NOT WORK */
	newscreen = SDL_CALL SDL_SetVideoMode(w, h, bpp, SDL_SWSURFACE | SDL_HWPALETTE | (_fullscreen ? SDL_FULLSCREEN : SDL_RESIZABLE));
	if (newscreen == NULL) {
		DEBUG(driver, 0, "SDL: Couldn't allocate a window to draw on");
		return false;
	}

	/* Delay drawing for this cycle; the next cycle will redraw the whole screen */
	_num_dirty_rects = 0;

	_screen.width = newscreen->w;
	_screen.height = newscreen->h;
	_screen.pitch = newscreen->pitch / (bpp / 8);
	_screen.dst_ptr = newscreen->pixels;
	_sdl_screen = newscreen;

	BlitterFactoryBase::GetCurrentBlitter()->PostResize();

	InitPalette();

	snprintf(caption, sizeof(caption), "OpenTTD %s", _openttd_revision);
	SDL_CALL SDL_WM_SetCaption(caption, caption);
	SDL_CALL SDL_ShowCursor(0);

	GameSizeChanged();

	return true;
}
Exemple #10
0
void  set_beagle_instances(world_fmt *world, boolean instance)
{
  int resource=1;//cpu=0, gpu=1
  long i;
  long ii;
  long locus = world->locus;
  beagle_fmt *beagle = world->beagle;
  for(i=0;i<world->nummutationmodels[locus];i++)
    {
      ii = world->sublocistarts[locus] + i;
      beagle->instance_handle[i] = beagleCreateInstance(world->sumtips,       // number of tips
							2 * (2 * world->sumtips-1), // total buffers (= total nodes in tree)
							// twice to accomodate rejections.
						  0,			// number of compact state representation [funny tips]
						  world->mutationmodels[ii].numstates, // number of states (nucleotides etc)
						  world->mutationmodels[ii].numsites,  // number of site patterns
						  1,			// number of rate matrices eigen-decomp buffers
							2*(2 * world->sumtips - 2),// number of rate matrix buffers (=number of branches)
						  world->mutationmodels[ii].numsiterates,// categoryCount
							0, //2*(2 * world->sumtips - 1),   number of scaling buffers
                                                  &resource,		        // List of resources (?)
						  1,			// Number of resources
						  0L,			// preferenceFlags (see BeagleFlags)
						  0L			// requirementFlags (see BeagleFlags) 
						  );

      if (beagle->instance_handle[i] < 0)
	usererror("createInstance returned a negative instance handle (and that's not good)");
      // initialize the instance
      int code = beagleInitializeInstance(beagle->instance_handle[i], NULL);
      
      if (code < 0) 
	{
	  usererror("initializeInstance returned a negative error code (and that is bad)\n\n");
	}
    }
}
Exemple #11
0
static bool CreateMainSurface(uint w, uint h)
{
	int bpp = BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth();
	if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals");
	set_color_depth(bpp);

	GetAvailableVideoMode(&w, &h);
	if (set_gfx_mode(_fullscreen ? GFX_AUTODETECT_FULLSCREEN : GFX_AUTODETECT_WINDOWED, w, h, 0, 0) != 0) {
		DEBUG(driver, 0, "Allegro: Couldn't allocate a window to draw on '%s'", allegro_error);
		return false;
	}

	/* The size of the screen might be bigger than the part we can actually draw on!
	 * So calculate the size based on the top, bottom, left and right */
	_allegro_screen = create_bitmap_ex(bpp, screen->cr - screen->cl, screen->cb - screen->ct);
	_screen.width = _allegro_screen->w;
	_screen.height = _allegro_screen->h;
	_screen.pitch = ((byte*)screen->line[1] - (byte*)screen->line[0]) / (bpp / 8);
	_screen.dst_ptr = _allegro_screen->line[0];

	/* Initialise the screen so we don't blit garbage to the screen */
	memset(_screen.dst_ptr, 0, _screen.height * _screen.pitch);

	/* Set the mouse at the place where we expect it */
	poll_mouse();
	_cursor.pos.x = mouse_x;
	_cursor.pos.y = mouse_y;

	BlitterFactoryBase::GetCurrentBlitter()->PostResize();

	InitPalette();

	char caption[32];
	snprintf(caption, sizeof(caption), "OpenTTD %s", _openttd_revision);
	set_window_title(caption);

	enable_hardware_cursor();
	select_mouse_cursor(MOUSE_CURSOR_ARROW);
	show_mouse(_allegro_screen);

	GameSizeChanged();

	return true;
}
Exemple #12
0
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
#endif
{
	int argc;
	char *argv[64]; // max 64 command line arguments
	char *cmdline;

#if !defined(UNICODE)
	_codepage = GetACP(); // get system codepage as some kind of a default
#endif /* UNICODE */

	CrashLog::InitialiseCrashLog();

#if defined(UNICODE)

#if !defined(WINCE)
	/* Check if a win9x user started the win32 version */
	if (HasBit(GetVersion(), 31)) usererror("This version of OpenTTD doesn't run on windows 95/98/ME.\nPlease download the win9x binary and try again.");
#endif

	/* For UNICODE we need to convert the commandline to char* _AND_
	 * save it because argv[] points into this buffer and thus needs to
	 * be available between subsequent calls to FS2OTTD() */
	char cmdlinebuf[MAX_PATH];
#endif /* UNICODE */

	cmdline = WIDE_TO_MB_BUFFER(GetCommandLine(), cmdlinebuf, lengthof(cmdlinebuf));

#if defined(_DEBUG)
	CreateConsole();
#endif

#if !defined(WINCE)
	_set_error_mode(_OUT_TO_MSGBOX); // force assertion output to messagebox
#endif

	/* setup random seed to something quite random */
	SetRandomSeed(GetTickCount());

	argc = ParseCommandLine(cmdline, argv, lengthof(argv));

	ttd_main(argc, argv);
	return 0;
}
/**
 * Load an old fashioned GRF file.
 * @param filename   The name of the file to open.
 * @param load_index The offset of the first sprite.
 * @param file_index The Fio offset to load the file in.
 * @return The number of loaded sprites.
 */
static uint LoadGrfFile(const char *filename, uint load_index, int file_index)
{
	uint load_index_org = load_index;
	uint sprite_id = 0;

	FioOpenFile(file_index, filename, BASESET_DIR);

	DEBUG(sprite, 2, "Reading grf-file '%s'", filename);

	while (LoadNextSprite(load_index, file_index, sprite_id)) {
		load_index++;
		sprite_id++;
		if (load_index >= MAX_SPRITES) {
			usererror("Too many sprites. Recompile with higher MAX_SPRITES value or remove some custom GRF files.");
		}
	}
	DEBUG(sprite, 2, "Currently %i sprites are loaded", load_index);

	return load_index - load_index_org;
}
Exemple #14
0
static void MakePalette()
{
	LOGPALETTE *pal = (LOGPALETTE*)alloca(sizeof(LOGPALETTE) + (256 - 1) * sizeof(PALETTEENTRY));

	pal->palVersion = 0x300;
	pal->palNumEntries = 256;

	for (uint i = 0; i != 256; i++) {
		pal->palPalEntry[i].peRed   = _cur_palette.palette[i].r;
		pal->palPalEntry[i].peGreen = _cur_palette.palette[i].g;
		pal->palPalEntry[i].peBlue  = _cur_palette.palette[i].b;
		pal->palPalEntry[i].peFlags = 0;

	}
	_wnd.gdi_palette = CreatePalette(pal);
	if (_wnd.gdi_palette == NULL) usererror("CreatePalette failed!\n");

	_cur_palette.first_dirty = 0;
	_cur_palette.count_dirty = 256;
	_local_palette = _cur_palette;
}
/**
 * Check blitter needed by NewGRF config and switch if needed.
 */
static void SwitchNewGRFBlitter()
{
	/* Get blitter of base set. */
	bool is_32bpp = BaseGraphics::GetUsedSet()->blitter == BLT_32BPP;

	/* Get combined blitter mode of all NewGRFs. */
	for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
		if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND || HasBit(c->flags, GCF_INIT_ONLY)) continue;

		if (c->palette & GRFP_BLT_32BPP) is_32bpp = true;
	}

	/* A GRF would like a 32 bpp blitter, switch blitter if needed. Never switch if the blitter was specified by the user. */
	if (_blitter_autodetected && is_32bpp && BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() != 0 && BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() < 16) {
		const char *cur_blitter = BlitterFactoryBase::GetCurrentBlitter()->GetName();
		if (BlitterFactoryBase::SelectBlitter("32bpp-anim") != NULL) {
			if (!_video_driver->AfterBlitterChange()) {
				/* Failed to switch blitter, let's hope we can return to the old one. */
				if (BlitterFactoryBase::SelectBlitter(cur_blitter) == NULL || !_video_driver->AfterBlitterChange()) usererror("Failed to reinitialize video driver for 32 bpp blitter. Specify a fixed blitter in the config");
			}
		}
	}
}
/**
 * Find the requested driver and return its class.
 * @param name the driver to select.
 * @param type the type of driver to select
 * @post Sets the driver so GetCurrentDriver() returns it too.
 */
Driver *DriverFactoryBase::SelectDriver(const char *name, Driver::Type type)
{
	if (GetDrivers().size() == 0) return NULL;

	if (StrEmpty(name)) {
		/* Probe for this driver, but do not fall back to dedicated/null! */
		for (int priority = 10; priority > 0; priority--) {
			Drivers::iterator it = GetDrivers().begin();
			for (; it != GetDrivers().end(); ++it) {
				DriverFactoryBase *d = (*it).second;

				/* Check driver type */
				if (d->type != type) continue;
				if (d->priority != priority) continue;

				Driver *newd = d->CreateInstance();
				const char *err = newd->Start(NULL);
				if (err == NULL) {
					DEBUG(driver, 1, "Successfully probed %s driver '%s'", GetDriverTypeName(type), d->name);
					delete *GetActiveDriver(type);
					*GetActiveDriver(type) = newd;
					return newd;
				}

				DEBUG(driver, 1, "Probing %s driver '%s' failed with error: %s", GetDriverTypeName(type), d->name, err);
				delete newd;
			}
		}
		usererror("Couldn't find any suitable %s driver", GetDriverTypeName(type));
	} else {
		char *parm;
		char buffer[256];
		const char *parms[32];

		/* Extract the driver name and put parameter list in parm */
		strecpy(buffer, name, lastof(buffer));
		parm = strchr(buffer, ':');
		parms[0] = NULL;
		if (parm != NULL) {
			uint np = 0;
			/* Tokenize the parm. */
			do {
				*parm++ = '\0';
				if (np < lengthof(parms) - 1) parms[np++] = parm;
				while (*parm != '\0' && *parm != ',') parm++;
			} while (*parm == ',');
			parms[np] = NULL;
		}

		/* Find this driver */
		Drivers::iterator it = GetDrivers().begin();
		for (; it != GetDrivers().end(); ++it) {
			DriverFactoryBase *d = (*it).second;

			/* Check driver type */
			if (d->type != type) continue;

			/* Check driver name */
			if (strcasecmp(buffer, d->name) != 0) continue;

			/* Found our driver, let's try it */
			Driver *newd = d->CreateInstance();

			const char *err = newd->Start(parms);
			if (err != NULL) {
				delete newd;
				usererror("Unable to load driver '%s'. The error was: %s", d->name, err);
			}

			DEBUG(driver, 1, "Successfully loaded %s driver '%s'", GetDriverTypeName(type), d->name);
			delete *GetActiveDriver(type);
			*GetActiveDriver(type) = newd;
			return newd;
		}
		usererror("No such %s driver: %s\n", GetDriverTypeName(type), buffer);
	}
}
/**
 * Check blitter needed by NewGRF config and switch if needed.
 * @return False when nothing changed, true otherwise.
 */
static bool SwitchNewGRFBlitter()
{
	/* Never switch if the blitter was specified by the user. */
	if (!_blitter_autodetected) return false;

	/* Null driver => dedicated server => do nothing. */
	if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return false;

	/* Get preferred depth.
	 *  - depth_wanted_by_base: Depth required by the baseset, i.e. the majority of the sprites.
	 *  - depth_wanted_by_grf:  Depth required by some NewGRF.
	 * Both can force using a 32bpp blitter. depth_wanted_by_base is used to select
	 * between multiple 32bpp blitters, which perform differently with 8bpp sprites.
	 */
	uint depth_wanted_by_base = BaseGraphics::GetUsedSet()->blitter == BLT_32BPP ? 32 : 8;
	uint depth_wanted_by_grf = _support8bpp == S8BPP_NONE ? 32 : 8;
	for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
		if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND || HasBit(c->flags, GCF_INIT_ONLY)) continue;
		if (c->palette & GRFP_BLT_32BPP) depth_wanted_by_grf = 32;
	}

	/* Search the best blitter. */
	static const struct {
		const char *name;
		uint animation; ///< 0: no support, 1: do support, 2: both
		uint min_base_depth, max_base_depth, min_grf_depth, max_grf_depth;
	} replacement_blitters[] = {
#ifdef WITH_SSE
		{ "32bpp-sse4",      0, 32, 32,  8, 32 },
		{ "32bpp-ssse3",     0, 32, 32,  8, 32 },
		{ "32bpp-sse2",      0, 32, 32,  8, 32 },
		{ "32bpp-sse4-anim", 1, 32, 32,  8, 32 },
#endif
		{ "8bpp-optimized",  2,  8,  8,  8,  8 },
		{ "32bpp-optimized", 0,  8, 32,  8, 32 },
		{ "32bpp-anim",      1,  8, 32,  8, 32 },
	};

	const bool animation_wanted = HasBit(_display_opt, DO_FULL_ANIMATION);
	const char *cur_blitter = BlitterFactory::GetCurrentBlitter()->GetName();

	for (uint i = 0; i < lengthof(replacement_blitters); i++) {
		if (animation_wanted && (replacement_blitters[i].animation == 0)) continue;
		if (!animation_wanted && (replacement_blitters[i].animation == 1)) continue;

		if (!IsInsideMM(depth_wanted_by_base, replacement_blitters[i].min_base_depth, replacement_blitters[i].max_base_depth + 1)) continue;
		if (!IsInsideMM(depth_wanted_by_grf, replacement_blitters[i].min_grf_depth, replacement_blitters[i].max_grf_depth + 1)) continue;
		const char *repl_blitter = replacement_blitters[i].name;

		if (strcmp(repl_blitter, cur_blitter) == 0) return false;
		if (BlitterFactory::GetBlitterFactory(repl_blitter) == NULL) continue;

		DEBUG(misc, 1, "Switching blitter from '%s' to '%s'... ", cur_blitter, repl_blitter);
		Blitter *new_blitter = BlitterFactory::SelectBlitter(repl_blitter);
		if (new_blitter == NULL) NOT_REACHED();
		DEBUG(misc, 1, "Successfully switched to %s.", repl_blitter);
		break;
	}

	if (!VideoDriver::GetInstance()->AfterBlitterChange()) {
		/* Failed to switch blitter, let's hope we can return to the old one. */
		if (BlitterFactory::SelectBlitter(cur_blitter) == NULL || !VideoDriver::GetInstance()->AfterBlitterChange()) usererror("Failed to reinitialize video driver. Specify a fixed blitter in the config");
	}

	return true;
}
const Sprite *GetGlyph(FontSize size, WChar key)
{
	FT_Face face = GetFontFace(size);
	FT_GlyphSlot slot;
	GlyphEntry new_glyph;
	GlyphEntry *glyph;
	SpriteLoader::Sprite sprite;
	int width;
	int height;
	int x;
	int y;

	assert(IsPrintable(key));

	/* Bail out if no face loaded, or for our special characters */
	if (face == NULL || (key >= SCC_SPRITE_START && key <= SCC_SPRITE_END)) {
		SpriteID sprite = GetUnicodeGlyph(size, key);
		if (sprite == 0) sprite = GetUnicodeGlyph(size, '?');

		/* Load the sprite if it's known. */
		if (sprite != 0) return GetSprite(sprite, ST_FONT);

		/* For the 'rare' case there is no font available at all. */
		if (face == NULL) error("No sprite font and no real font either... bailing!");

		/* Use the '?' from the freetype font. */
		key = '?';
	}

	/* Check for the glyph in our cache */
	glyph = GetGlyphPtr(size, key);
	if (glyph != NULL && glyph->sprite != NULL) return glyph->sprite;

	slot = face->glyph;

	bool aa = GetFontAAState(size);

	FT_UInt glyph_index = FT_Get_Char_Index(face, key);
	if (glyph_index == 0) {
		if (key == '?') {
			/* The font misses the '?' character. Use sprite font. */
			SpriteID sprite = GetUnicodeGlyph(size, key);
			Sprite *spr = (Sprite*)GetRawSprite(sprite, ST_FONT, AllocateFont);
			assert(spr != NULL);
			new_glyph.sprite = spr;
			new_glyph.width  = spr->width + (size != FS_NORMAL);
			SetGlyphPtr(size, key, &new_glyph, false);
			return new_glyph.sprite;
		} else {
			/* Use '?' for missing characters. */
			GetGlyph(size, '?');
			glyph = GetGlyphPtr(size, '?');
			SetGlyphPtr(size, key, glyph, true);
			return glyph->sprite;
		}
	}
	FT_Load_Glyph(face, glyph_index, FT_LOAD_DEFAULT);
	FT_Render_Glyph(face->glyph, aa ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO);

	/* Despite requesting a normal glyph, FreeType may have returned a bitmap */
	aa = (slot->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY);

	/* Add 1 pixel for the shadow on the medium font. Our sprite must be at least 1x1 pixel */
	width  = max(1, slot->bitmap.width + (size == FS_NORMAL));
	height = max(1, slot->bitmap.rows  + (size == FS_NORMAL));

	/* Limit glyph size to prevent overflows later on. */
	if (width > 256 || height > 256) usererror("Font glyph is too large");

	/* FreeType has rendered the glyph, now we allocate a sprite and copy the image into it */
	sprite.AllocateData(width * height);
	sprite.type = ST_FONT;
	sprite.width = width;
	sprite.height = height;
	sprite.x_offs = slot->bitmap_left;
	sprite.y_offs = _ascender[size] - slot->bitmap_top;

	/* Draw shadow for medium size */
	if (size == FS_NORMAL && !aa) {
		for (y = 0; y < slot->bitmap.rows; y++) {
			for (x = 0; x < slot->bitmap.width; x++) {
				if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
					sprite.data[1 + x + (1 + y) * sprite.width].m = SHADOW_COLOUR;
					sprite.data[1 + x + (1 + y) * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
				}
			}
		}
	}

	for (y = 0; y < slot->bitmap.rows; y++) {
		for (x = 0; x < slot->bitmap.width; x++) {
			if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
				sprite.data[x + y * sprite.width].m = FACE_COLOUR;
				sprite.data[x + y * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
			}
		}
	}

	new_glyph.sprite = BlitterFactoryBase::GetCurrentBlitter()->Encode(&sprite, AllocateFont);
	new_glyph.width  = slot->advance.x >> 6;

	SetGlyphPtr(size, key, &new_glyph);

	return new_glyph.sprite;
}
Exemple #19
0
void fill_beagle_instances(world_fmt *world)
{
  beagle_fmt *beagle = world->beagle;
  unsigned long i;
  unsigned long ii;
  unsigned long j;
  //unsigned long zz;
  unsigned long site;
  unsigned int numsites;
  unsigned int numstates;
  unsigned int numweights=0;
  int code;
  long locus = world->locus;
  // set partials for all tipnodes
  // use z to advance through the partial array
  unsigned long z = 0L;

  for(i=0; i<world->nummutationmodels[locus]; i++)
    {
      ii = world->sublocistarts[locus] + i;
      numstates = world->mutationmodels[ii].numstates;
      numsites = world->mutationmodels[ii].numsites;
      // will currently fail with more complex data
      if(numsites + numweights < beagle->numallocallyweights)
	{
	  beagle->numallocallyweights += numsites * 2;
	  beagle->allyweights = (int *) myrealloc(beagle->allyweights,sizeof(int) * beagle->numallocallyweights);
	}
      memcpy(beagle->allyweights+numweights, world->data->seq[0]->aliasweight, sizeof(int) * numsites);
      numweights += numsites;
      for (j = 0; j < world->sumtips; ++j)
	{
	  for(site=0;site<numsites;site++)
	    {
	      if(z > beagle->numallocpartials)
		{
		  beagle->numallocpartials += numsites * numstates;
		  beagle->partials = (double *) myrealloc(beagle->partials,sizeof(double) * beagle->numallocpartials);
		}
	      memcpy(&beagle->partials[z], 
		     &(world->nodep[j]->x.s[site][0][0]),
		     sizeof(double) * numstates);
	      beagle->numpartials++;
#if 0
	      fprintf(stdout,"Site %li Partial: %li (%f ", site, j, 
		      beagle->partials[z]);
	      for(zz=1;zz<world->mutationmodels[ii].numstates;zz++)
		{
		  fprintf(stdout,"%f ",beagle->partials[z+zz]);
		}
	      fprintf(stdout,")\n")
#endif;
	      // advance z
	      z += numstates;
	    }
	  code = beagleSetTipPartials(
			     beagle->instance_handle[i],			// instance
			     j,							// indicator for tips
			     &beagle->partials[z - numsites*numstates]);// inPartials
	  if (code != 0)
	    usererror("setTipPartials encountered a problem");
	}
    }

  
  for(i=0; i<world->nummutationmodels[locus]; i++)
    {
      ii = world->sublocistarts[locus] + i;

      code = beagleSetCategoryRates(beagle->instance_handle[i], world->mutationmodels[ii].siterates);
      if (code != 0)
	usererror("setCategoryRates encountered a problem");

      code = beagleSetEigenDecomposition(beagle->instance_handle[i],		  // instance
				   0,					  // eigenIndex,
				   (const double *)world->mutationmodels[ii].eigenvectormatrix,	// inEigenVectors,
				   (const double *)world->mutationmodels[ii].inverseeigenvectormatrix,// inInverseEigenVectors,
				   world->mutationmodels[i].eigenvalues); // inEigenValues
      
      if (code != 0)
	usererror("setEigenDecomposition encountered a problem");
    }
}
Exemple #20
0
int ttd_main(int argc, char *argv[])
{
	int i;
	const char *optformat;
	char *musicdriver = NULL;
	char *sounddriver = NULL;
	char *videodriver = NULL;
	char *blitter = NULL;
	char *graphics_set = NULL;
	char *sounds_set = NULL;
	char *music_set = NULL;
	Dimension resolution = {0, 0};
	Year startyear = INVALID_YEAR;
	uint generation_seed = GENERATE_NEW_SEED;
	bool save_config = true;
#if defined(ENABLE_NETWORK)
	bool dedicated = false;
	bool network   = false;
	char *network_conn = NULL;
	char *debuglog_conn = NULL;
	char *dedicated_host = NULL;
	uint16 dedicated_port = 0;
	char *join_server_password = NULL;
	char *join_company_password = NULL;

	extern bool _dedicated_forks;
	_dedicated_forks = false;
#endif /* ENABLE_NETWORK */

	_game_mode = GM_MENU;
	_switch_mode = SM_MENU;
	_switch_mode_errorstr = INVALID_STRING_ID;
	_config_file = NULL;

	/* The last param of the following function means this:
	 *   a letter means: it accepts that param (e.g.: -h)
	 *   a ':' behind it means: it need a param (e.g.: -m<driver>)
	 *   a '::' behind it means: it can optional have a param (e.g.: -d<debug>) */
	optformat = "m:s:v:b:hD::n::ei::I:S:M:t:d::r:g::G:c:xl:p:P:"
#if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
		"f"
#endif
	;

	MyGetOptData mgo(argc - 1, argv + 1, optformat);

	while ((i = MyGetOpt(&mgo)) != -1) {
		switch (i) {
		case 'I': free(graphics_set); graphics_set = strdup(mgo.opt); break;
		case 'S': free(sounds_set); sounds_set = strdup(mgo.opt); break;
		case 'M': free(music_set); music_set = strdup(mgo.opt); break;
		case 'm': free(musicdriver); musicdriver = strdup(mgo.opt); break;
		case 's': free(sounddriver); sounddriver = strdup(mgo.opt); break;
		case 'v': free(videodriver); videodriver = strdup(mgo.opt); break;
		case 'b': free(blitter); blitter = strdup(mgo.opt); break;
#if defined(ENABLE_NETWORK)
		case 'D':
			free(musicdriver);
			free(sounddriver);
			free(videodriver);
			free(blitter);
			musicdriver = strdup("null");
			sounddriver = strdup("null");
			videodriver = strdup("dedicated");
			blitter = strdup("null");
			dedicated = true;
			SetDebugString("net=6");
			if (mgo.opt != NULL) {
				/* Use the existing method for parsing (openttd -n).
				 * However, we do ignore the #company part. */
				const char *temp = NULL;
				const char *port = NULL;
				ParseConnectionString(&temp, &port, mgo.opt);
				if (!StrEmpty(mgo.opt)) dedicated_host = mgo.opt;
				if (port != NULL) dedicated_port = atoi(port);
			}
			break;
		case 'f': _dedicated_forks = true; break;
		case 'n':
			network = true;
			network_conn = mgo.opt; // optional IP parameter, NULL if unset
			break;
		case 'l':
			debuglog_conn = mgo.opt;
			break;
		case 'p':
			join_server_password = mgo.opt;
			break;
		case 'P':
			join_company_password = mgo.opt;
			break;
#endif /* ENABLE_NETWORK */
		case 'r': ParseResolution(&resolution, mgo.opt); break;
		case 't': startyear = atoi(mgo.opt); break;
		case 'd': {
#if defined(WIN32)
				CreateConsole();
#endif
				if (mgo.opt != NULL) SetDebugString(mgo.opt);
				break;
			}
		case 'e': _switch_mode = SM_EDITOR; break;
		case 'i':
			/* there is an argument, it is not empty, and it is exactly 1 char long */
			if (!StrEmpty(mgo.opt) && mgo.opt[1] == '\0') {
				_use_palette = (PaletteType)(mgo.opt[0] - '0');
				if (_use_palette <= MAX_PAL) break;
			}
			usererror("Valid value for '-i' is 0, 1 or 2");
		case 'g':
			if (mgo.opt != NULL) {
				strecpy(_file_to_saveload.name, mgo.opt, lastof(_file_to_saveload.name));
				_switch_mode = SM_LOAD;
				_file_to_saveload.mode = SL_LOAD;

				/* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
				const char *t = strrchr(_file_to_saveload.name, '.');
				if (t != NULL) {
					FiosType ft = FiosGetSavegameListCallback(SLD_LOAD_GAME, _file_to_saveload.name, t, NULL, NULL);
					if (ft != FIOS_TYPE_INVALID) SetFiosType(ft);
				}

				break;
			}

			_switch_mode = SM_NEWGAME;
			/* Give a random map if no seed has been given */
			if (generation_seed == GENERATE_NEW_SEED) {
				generation_seed = InteractiveRandom();
			}
			break;
		case 'G': generation_seed = atoi(mgo.opt); break;
		case 'c': _config_file = strdup(mgo.opt); break;
		case 'x': save_config = false; break;
		case -2:
		case 'h':
			/* The next two functions are needed to list the graphics sets.
			 * We can't do them earlier because then we can't show it on
			 * the debug console as that hasn't been configured yet. */
			DeterminePaths(argv[0]);
			BaseGraphics::FindSets();
			BaseSounds::FindSets();
			BaseMusic::FindSets();
			ShowHelp();
			return 0;
		}
	}

#if defined(WINCE) && defined(_DEBUG)
	/* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
	SetDebugString("4");
#endif

	DeterminePaths(argv[0]);
	BaseGraphics::FindSets();
	BaseSounds::FindSets();
	BaseMusic::FindSets();

#if defined(ENABLE_NETWORK) && defined(UNIX) && !defined(__MORPHOS__)
	/* We must fork here, or we'll end up without some resources we need (like sockets) */
	if (_dedicated_forks) DedicatedFork();
#endif

	TarScanner::DoScan();
	AI::Initialize();
	LoadFromConfig();
	AI::Uninitialize(true);
	CheckConfig();
	LoadFromHighScore();
	LoadHotkeysFromConfig();

	if (resolution.width != 0) { _cur_resolution = resolution; }
	if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
	if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;

	/*
	 * The width and height must be at least 1 pixel and width times
	 * height times bytes per pixel must still fit within a 32 bits
	 * integer, even for 32 bpp video modes. This way all internal
	 * drawing routines work correctly.
	 */
	_cur_resolution.width  = ClampU(_cur_resolution.width,  1, UINT16_MAX / 2);
	_cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX / 2);

#if defined(ENABLE_NETWORK)
	if (dedicated) DEBUG(net, 0, "Starting dedicated version %s", _openttd_revision);
	if (dedicated_host) {
		_network_bind_list.Clear();
		*_network_bind_list.Append() = strdup(dedicated_host);
	}
	if (dedicated_port) _settings_client.network.server_port = dedicated_port;
	if (_dedicated_forks && !dedicated) _dedicated_forks = false;
#endif /* ENABLE_NETWORK */

	/* enumerate language files */
	InitializeLanguagePacks();

	/* initialize screenshot formats */
	InitializeScreenshotFormats();

	/* Initialize FreeType */
	InitFreeType();

	/* This must be done early, since functions use the SetWindowDirty* calls */
	InitWindowSystem();

	/* Look for the sounds before the graphics. Otherwise none would be set and
	 * the first initialisation of the video happens on the wrong data. Now it
	 * can do the first initialisation right. */
	if (sounds_set == NULL && BaseSounds::ini_set != NULL) sounds_set = strdup(BaseSounds::ini_set);
	if (!BaseSounds::SetSet(sounds_set)) {
		StrEmpty(sounds_set) ?
			usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.") :
			usererror("Failed to select requested sounds set '%s'", sounds_set);
	}
	free(sounds_set);

	if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = strdup(BaseGraphics::ini_set);
	if (!BaseGraphics::SetSet(graphics_set)) {
		StrEmpty(graphics_set) ?
			usererror("Failed to find a graphics set. Please acquire a graphics set for OpenTTD. See section 4.1 of readme.txt.") :
			usererror("Failed to select requested graphics set '%s'", graphics_set);
	}
	free(graphics_set);

	if (music_set == NULL && BaseMusic::ini_set != NULL) music_set = strdup(BaseMusic::ini_set);
	if (!BaseMusic::SetSet(music_set)) {
		StrEmpty(music_set) ?
			usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.") :
			usererror("Failed to select requested music set '%s'", music_set);
	}
	free(music_set);

	/* Initialize game palette */
	GfxInitPalettes();

	DEBUG(misc, 1, "Loading blitter...");
	if (blitter == NULL && _ini_blitter != NULL) blitter = strdup(_ini_blitter);
	if (BlitterFactoryBase::SelectBlitter(blitter) == NULL) {
		StrEmpty(blitter) ?
			usererror("Failed to autoprobe blitter") :
			usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
	}
	free(blitter);

	DEBUG(driver, 1, "Loading drivers...");

	if (sounddriver == NULL && _ini_sounddriver != NULL) sounddriver = strdup(_ini_sounddriver);
	_sound_driver = (SoundDriver*)SoundDriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
	if (_sound_driver == NULL) {
		StrEmpty(sounddriver) ?
			usererror("Failed to autoprobe sound driver") :
			usererror("Failed to select requested sound driver '%s'", sounddriver);
	}
	free(sounddriver);

	if (videodriver == NULL && _ini_videodriver != NULL) videodriver = strdup(_ini_videodriver);
	_video_driver = (VideoDriver*)VideoDriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
	if (_video_driver == NULL) {
		StrEmpty(videodriver) ?
			usererror("Failed to autoprobe video driver") :
			usererror("Failed to select requested video driver '%s'", videodriver);
	}
	free(videodriver);

	if (musicdriver == NULL && _ini_musicdriver != NULL) musicdriver = strdup(_ini_musicdriver);
	_music_driver = (MusicDriver*)MusicDriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
	if (_music_driver == NULL) {
		StrEmpty(musicdriver) ?
			usererror("Failed to autoprobe music driver") :
			usererror("Failed to select requested music driver '%s'", musicdriver);
	}
	free(musicdriver);

	/* Initialize the zoom level of the screen to normal */
	_screen.zoom = ZOOM_LVL_NORMAL;

	/* restore saved music volume */
	_music_driver->SetVolume(_msf.music_vol);

	NetworkStartUp(); // initialize network-core

#if defined(ENABLE_NETWORK)
	if (debuglog_conn != NULL && _network_available) {
		const char *not_used = NULL;
		const char *port = NULL;
		uint16 rport;

		rport = NETWORK_DEFAULT_DEBUGLOG_PORT;

		ParseConnectionString(&not_used, &port, debuglog_conn);
		if (port != NULL) rport = atoi(port);

		NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
	}
#endif /* ENABLE_NETWORK */

	ScanNewGRFFiles();

	ResetGRFConfig(false);

	/* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
	if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();

	/* initialize the ingame console */
	IConsoleInit();
	_cursor.in_window = true;
	InitializeGUI();
	IConsoleCmdExec("exec scripts/autoexec.scr 0");

	/* Take our initial lock on whatever we might want to do! */
	_genworld_paint_mutex->BeginCritical();
	_genworld_mapgen_mutex->BeginCritical();

	GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
	WaitTillGeneratedWorld();

	CheckForMissingGlyphsInLoadedLanguagePack();

#ifdef ENABLE_NETWORK
	if (network && _network_available) {
		if (network_conn != NULL) {
			const char *port = NULL;
			const char *company = NULL;
			uint16 rport = NETWORK_DEFAULT_PORT;
			CompanyID join_as = COMPANY_NEW_COMPANY;

			ParseConnectionString(&company, &port, network_conn);

			if (company != NULL) {
				join_as = (CompanyID)atoi(company);

				if (join_as != COMPANY_SPECTATOR) {
					join_as--;
					if (join_as >= MAX_COMPANIES) return false;
				}
			}
			if (port != NULL) rport = atoi(port);

			LoadIntroGame();
			_switch_mode = SM_NONE;
			NetworkClientConnectGame(NetworkAddress(network_conn, rport), join_as, join_server_password, join_company_password);
		}
	}
#endif /* ENABLE_NETWORK */

	_video_driver->MainLoop();

	WaitTillSaved();

	/* only save config if we have to */
	if (save_config) {
		SaveToConfig();
		SaveHotkeysToConfig();
		SaveToHighScore();
	}

	/* Reset windowing system, stop drivers, free used memory, ... */
	ShutdownGame();

	free(const_cast<char *>(BaseGraphics::ini_set));
	free(const_cast<char *>(BaseSounds::ini_set));
	free(const_cast<char *>(BaseMusic::ini_set));
	free(_ini_musicdriver);
	free(_ini_sounddriver);
	free(_ini_videodriver);
	free(_ini_blitter);

	return 0;
}
Exemple #21
0
/**
 * Main entry point for this lovely game.
 * @param argc The number of arguments passed to this game.
 * @param argv The values of the arguments.
 * @return 0 when there is no error.
 */
int openttd_main(int argc, char *argv[])
{
	char *musicdriver = NULL;
	char *sounddriver = NULL;
	char *videodriver = NULL;
	char *blitter = NULL;
	char *graphics_set = NULL;
	char *sounds_set = NULL;
	char *music_set = NULL;
	Dimension resolution = {0, 0};
	/* AfterNewGRFScan sets save_config to true after scanning completed. */
	bool save_config = false;
	AfterNewGRFScan *scanner = new AfterNewGRFScan(&save_config);
#if defined(ENABLE_NETWORK)
	bool dedicated = false;
	char *debuglog_conn = NULL;

	extern bool _dedicated_forks;
	_dedicated_forks = false;
#endif /* ENABLE_NETWORK */

	_game_mode = GM_MENU;
	_switch_mode = SM_MENU;
	_config_file = NULL;

	GetOptData mgo(argc - 1, argv + 1, _options);
	int ret = 0;

	int i;
	while ((i = mgo.GetOpt()) != -1) {
		switch (i) {
		case 'I': free(graphics_set); graphics_set = stredup(mgo.opt); break;
		case 'S': free(sounds_set); sounds_set = stredup(mgo.opt); break;
		case 'M': free(music_set); music_set = stredup(mgo.opt); break;
		case 'm': free(musicdriver); musicdriver = stredup(mgo.opt); break;
		case 's': free(sounddriver); sounddriver = stredup(mgo.opt); break;
		case 'v': free(videodriver); videodriver = stredup(mgo.opt); break;
		case 'b': free(blitter); blitter = stredup(mgo.opt); break;
#if defined(ENABLE_NETWORK)
		case 'D':
			free(musicdriver);
			free(sounddriver);
			free(videodriver);
			free(blitter);
			musicdriver = stredup("null");
			sounddriver = stredup("null");
			videodriver = stredup("dedicated");
			blitter = stredup("null");
			dedicated = true;
			SetDebugString("net=6");
			if (mgo.opt != NULL) {
				/* Use the existing method for parsing (openttd -n).
				 * However, we do ignore the #company part. */
				const char *temp = NULL;
				const char *port = NULL;
				ParseConnectionString(&temp, &port, mgo.opt);
				if (!StrEmpty(mgo.opt)) scanner->dedicated_host = mgo.opt;
				if (port != NULL) scanner->dedicated_port = atoi(port);
			}
			break;
		case 'f': _dedicated_forks = true; break;
		case 'n':
			scanner->network_conn = mgo.opt; // optional IP parameter, NULL if unset
			break;
		case 'l':
			debuglog_conn = mgo.opt;
			break;
		case 'p':
			scanner->join_server_password = mgo.opt;
			break;
		case 'P':
			scanner->join_company_password = mgo.opt;
			break;
#endif /* ENABLE_NETWORK */
		case 'r': ParseResolution(&resolution, mgo.opt); break;
		case 't': scanner->startyear = atoi(mgo.opt); break;
		case 'd': {
#if defined(WIN32)
				CreateConsole();
#endif
				if (mgo.opt != NULL) SetDebugString(mgo.opt);
				break;
			}
		case 'e': _switch_mode = (_switch_mode == SM_LOAD_GAME || _switch_mode == SM_LOAD_SCENARIO ? SM_LOAD_SCENARIO : SM_EDITOR); break;
		case 'g':
			if (mgo.opt != NULL) {
				_file_to_saveload.SetName(mgo.opt);
				bool is_scenario = _switch_mode == SM_EDITOR || _switch_mode == SM_LOAD_SCENARIO;
				_switch_mode = is_scenario ? SM_LOAD_SCENARIO : SM_LOAD_GAME;
				_file_to_saveload.SetMode(SLO_LOAD, is_scenario ? FT_SCENARIO : FT_SAVEGAME, DFT_GAME_FILE);

				/* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
				const char *t = strrchr(_file_to_saveload.name, '.');
				if (t != NULL) {
					FiosType ft = FiosGetSavegameListCallback(SLO_LOAD, _file_to_saveload.name, t, NULL, NULL);
					if (ft != FIOS_TYPE_INVALID) _file_to_saveload.SetMode(ft);
				}

				break;
			}

			_switch_mode = SM_NEWGAME;
			/* Give a random map if no seed has been given */
			if (scanner->generation_seed == GENERATE_NEW_SEED) {
				scanner->generation_seed = InteractiveRandom();
			}
			break;
		case 'q': {
			DeterminePaths(argv[0]);
			if (StrEmpty(mgo.opt)) {
				ret = 1;
				goto exit_noshutdown;
			}

			char title[80];
			title[0] = '\0';
			FiosGetSavegameListCallback(SLO_LOAD, mgo.opt, strrchr(mgo.opt, '.'), title, lastof(title));

			_load_check_data.Clear();
			SaveOrLoadResult res = SaveOrLoad(mgo.opt, SLO_CHECK, DFT_GAME_FILE, SAVE_DIR, false);
			if (res != SL_OK || _load_check_data.HasErrors()) {
				fprintf(stderr, "Failed to open savegame\n");
				if (_load_check_data.HasErrors()) {
					char buf[256];
					SetDParamStr(0, _load_check_data.error_data);
					GetString(buf, _load_check_data.error, lastof(buf));
					fprintf(stderr, "%s\n", buf);
				}
				goto exit_noshutdown;
			}

			WriteSavegameInfo(title);

			goto exit_noshutdown;
		}
		case 'G': scanner->generation_seed = atoi(mgo.opt); break;
		case 'c': free(_config_file); _config_file = stredup(mgo.opt); break;
		case 'x': scanner->save_config = false; break;
		case 'h':
			i = -2; // Force printing of help.
			break;
		}
		if (i == -2) break;
	}

	if (i == -2 || mgo.numleft > 0) {
		/* Either the user typed '-h', he made an error, or he added unrecognized command line arguments.
		 * In all cases, print the help, and exit.
		 *
		 * The next two functions are needed to list the graphics sets. We can't do them earlier
		 * because then we cannot show it on the debug console as that hasn't been configured yet. */
		DeterminePaths(argv[0]);
		TarScanner::DoScan(TarScanner::BASESET);
		BaseGraphics::FindSets();
		BaseSounds::FindSets();
		BaseMusic::FindSets();
		ShowHelp();

		goto exit_noshutdown;
	}

	DeterminePaths(argv[0]);
	TarScanner::DoScan(TarScanner::BASESET);

#if defined(ENABLE_NETWORK)
	if (dedicated) DEBUG(net, 0, "Starting dedicated version %s", _openttd_revision);
	if (_dedicated_forks && !dedicated) _dedicated_forks = false;

#if defined(UNIX) && !defined(__MORPHOS__)
	/* We must fork here, or we'll end up without some resources we need (like sockets) */
	if (_dedicated_forks) DedicatedFork();
#endif
#endif

	LoadFromConfig(true);

	if (resolution.width != 0) _cur_resolution = resolution;

	/*
	 * The width and height must be at least 1 pixel and width times
	 * height times bytes per pixel must still fit within a 32 bits
	 * integer, even for 32 bpp video modes. This way all internal
	 * drawing routines work correctly.
	 */
	_cur_resolution.width  = ClampU(_cur_resolution.width,  1, UINT16_MAX / 2);
	_cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX / 2);

	/* Assume the cursor starts within the game as not all video drivers
	 * get an event that the cursor is within the window when it is opened.
	 * Saying the cursor is there makes no visible difference as it would
	 * just be out of the bounds of the window. */
	_cursor.in_window = true;

	/* enumerate language files */
	InitializeLanguagePacks();

	/* Initialize the regular font for FreeType */
	InitFreeType(false);

	/* This must be done early, since functions use the SetWindowDirty* calls */
	InitWindowSystem();

	BaseGraphics::FindSets();
	if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = stredup(BaseGraphics::ini_set);
	if (!BaseGraphics::SetSet(graphics_set)) {
		if (!StrEmpty(graphics_set)) {
			BaseGraphics::SetSet(NULL);

			ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
			msg.SetDParamStr(0, graphics_set);
			ScheduleErrorMessage(msg);
		}
	}
	free(graphics_set);

	/* Initialize game palette */
	GfxInitPalettes();

	DEBUG(misc, 1, "Loading blitter...");
	if (blitter == NULL && _ini_blitter != NULL) blitter = stredup(_ini_blitter);
	_blitter_autodetected = StrEmpty(blitter);
	/* Activate the initial blitter.
	 * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
	 *  - Never guess anything, if the user specified a blitter. (_blitter_autodetected)
	 *  - Use 32bpp blitter if baseset or 8bpp-support settings says so.
	 *  - Use 8bpp blitter otherwise.
	 */
	if (!_blitter_autodetected ||
			(_support8bpp != S8BPP_NONE && (BaseGraphics::GetUsedSet() == NULL || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP)) ||
			BlitterFactory::SelectBlitter("32bpp-anim") == NULL) {
		if (BlitterFactory::SelectBlitter(blitter) == NULL) {
			StrEmpty(blitter) ?
				usererror("Failed to autoprobe blitter") :
				usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
		}
	}
	free(blitter);

	if (videodriver == NULL && _ini_videodriver != NULL) videodriver = stredup(_ini_videodriver);
	DriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
	free(videodriver);

	InitializeSpriteSorter();

	/* Initialize the zoom level of the screen to normal */
	_screen.zoom = ZOOM_LVL_NORMAL;

	NetworkStartUp(); // initialize network-core

#if defined(ENABLE_NETWORK)
	if (debuglog_conn != NULL && _network_available) {
		const char *not_used = NULL;
		const char *port = NULL;
		uint16 rport;

		rport = NETWORK_DEFAULT_DEBUGLOG_PORT;

		ParseConnectionString(&not_used, &port, debuglog_conn);
		if (port != NULL) rport = atoi(port);

		NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
	}
#endif /* ENABLE_NETWORK */

	if (!HandleBootstrap()) {
		ShutdownGame();

		goto exit_bootstrap;
	}

	VideoDriver::GetInstance()->ClaimMousePointer();

	/* initialize screenshot formats */
	InitializeScreenshotFormats();

	BaseSounds::FindSets();
	if (sounds_set == NULL && BaseSounds::ini_set != NULL) sounds_set = stredup(BaseSounds::ini_set);
	if (!BaseSounds::SetSet(sounds_set)) {
		if (StrEmpty(sounds_set) || !BaseSounds::SetSet(NULL)) {
			usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of README.md.");
		} else {
			ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
			msg.SetDParamStr(0, sounds_set);
			ScheduleErrorMessage(msg);
		}
	}
	free(sounds_set);

	BaseMusic::FindSets();
	if (music_set == NULL && BaseMusic::ini_set != NULL) music_set = stredup(BaseMusic::ini_set);
	if (!BaseMusic::SetSet(music_set)) {
		if (StrEmpty(music_set) || !BaseMusic::SetSet(NULL)) {
			usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of README.md.");
		} else {
			ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
			msg.SetDParamStr(0, music_set);
			ScheduleErrorMessage(msg);
		}
	}
	free(music_set);

	if (sounddriver == NULL && _ini_sounddriver != NULL) sounddriver = stredup(_ini_sounddriver);
	DriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
	free(sounddriver);

	if (musicdriver == NULL && _ini_musicdriver != NULL) musicdriver = stredup(_ini_musicdriver);
	DriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
	free(musicdriver);

	/* Take our initial lock on whatever we might want to do! */
	_modal_progress_paint_mutex->BeginCritical();
	_modal_progress_work_mutex->BeginCritical();

	GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
	WaitTillGeneratedWorld();

	LoadIntroGame(false);

	CheckForMissingGlyphs();

	/* ScanNewGRFFiles now has control over the scanner. */
	ScanNewGRFFiles(scanner);
	scanner = NULL;

	VideoDriver::GetInstance()->MainLoop();

	WaitTillSaved();

	/* only save config if we have to */
	if (save_config) {
		SaveToConfig();
		SaveHotkeysToConfig();
		WindowDesc::SaveToConfig();
		SaveToHighScore();
	}

	/* Reset windowing system, stop drivers, free used memory, ... */
	ShutdownGame();
	goto exit_normal;

exit_noshutdown:
	/* These three are normally freed before bootstrap. */
	free(graphics_set);
	free(videodriver);
	free(blitter);

exit_bootstrap:
	/* These are normally freed before exit, but after bootstrap. */
	free(sounds_set);
	free(music_set);
	free(musicdriver);
	free(sounddriver);

exit_normal:
	free(BaseGraphics::ini_set);
	free(BaseSounds::ini_set);
	free(BaseMusic::ini_set);

	free(_ini_musicdriver);
	free(_ini_sounddriver);
	free(_ini_videodriver);
	free(_ini_blitter);

	delete scanner;

#ifdef ENABLE_NETWORK
	extern FILE *_log_fd;
	if (_log_fd != NULL) {
		fclose(_log_fd);
	}
#endif /* ENABLE_NETWORK */

	return ret;
}
Exemple #22
0
const Sprite *FreeTypeFontCache::GetGlyph(GlyphID key)
{
	if ((key & SPRITE_GLYPH) != 0) return parent->GetGlyph(key);

	/* Check for the glyph in our cache */
	GlyphEntry *glyph = this->GetGlyphPtr(key);
	if (glyph != NULL && glyph->sprite != NULL) return glyph->sprite;

	FT_GlyphSlot slot = this->face->glyph;

	bool aa = GetFontAAState(this->fs);

	GlyphEntry new_glyph;
	if (key == 0) {
		GlyphID question_glyph = this->MapCharToGlyph('?');
		if (question_glyph == 0) {
			/* The font misses the '?' character. Use built-in sprite.
			 * Note: We cannot use the baseset as this also has to work in the bootstrap GUI. */
#define CPSET { 0, 0, 0, 0, 1 }
#define CP___ { 0, 0, 0, 0, 0 }
			static SpriteLoader::CommonPixel builtin_questionmark_data[10 * 8] = {
				CP___, CP___, CPSET, CPSET, CPSET, CPSET, CP___, CP___,
				CP___, CPSET, CPSET, CP___, CP___, CPSET, CPSET, CP___,
				CP___, CP___, CP___, CP___, CP___, CPSET, CPSET, CP___,
				CP___, CP___, CP___, CP___, CPSET, CPSET, CP___, CP___,
				CP___, CP___, CP___, CPSET, CPSET, CP___, CP___, CP___,
				CP___, CP___, CP___, CPSET, CPSET, CP___, CP___, CP___,
				CP___, CP___, CP___, CPSET, CPSET, CP___, CP___, CP___,
				CP___, CP___, CP___, CP___, CP___, CP___, CP___, CP___,
				CP___, CP___, CP___, CPSET, CPSET, CP___, CP___, CP___,
				CP___, CP___, CP___, CPSET, CPSET, CP___, CP___, CP___,
			};
#undef CPSET
#undef CP___
			static const SpriteLoader::Sprite builtin_questionmark = {
				10, // height
				8,  // width
				0,  // x_offs
				0,  // y_offs
				ST_FONT,
				builtin_questionmark_data
			};

			Sprite *spr = BlitterFactory::GetCurrentBlitter()->Encode(&builtin_questionmark, AllocateFont);
			assert(spr != NULL);
			new_glyph.sprite = spr;
			new_glyph.width  = spr->width + (this->fs != FS_NORMAL);
			this->SetGlyphPtr(key, &new_glyph, false);
			return new_glyph.sprite;
		} else {
			/* Use '?' for missing characters. */
			this->GetGlyph(question_glyph);
			glyph = this->GetGlyphPtr(question_glyph);
			this->SetGlyphPtr(key, glyph, true);
			return glyph->sprite;
		}
	}
	FT_Load_Glyph(this->face, key, FT_LOAD_DEFAULT);
	FT_Render_Glyph(this->face->glyph, aa ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO);

	/* Despite requesting a normal glyph, FreeType may have returned a bitmap */
	aa = (slot->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY);

	/* Add 1 pixel for the shadow on the medium font. Our sprite must be at least 1x1 pixel */
	int width  = max(1, slot->bitmap.width + (this->fs == FS_NORMAL));
	int height = max(1, slot->bitmap.rows  + (this->fs == FS_NORMAL));

	/* Limit glyph size to prevent overflows later on. */
	if (width > 256 || height > 256) usererror("Font glyph is too large");

	/* FreeType has rendered the glyph, now we allocate a sprite and copy the image into it */
	SpriteLoader::Sprite sprite;
	sprite.AllocateData(ZOOM_LVL_NORMAL, width * height);
	sprite.type = ST_FONT;
	sprite.width = width;
	sprite.height = height;
	sprite.x_offs = slot->bitmap_left;
	sprite.y_offs = this->ascender - slot->bitmap_top;

	/* Draw shadow for medium size */
	if (this->fs == FS_NORMAL && !aa) {
		for (int y = 0; y < slot->bitmap.rows; y++) {
			for (int x = 0; x < slot->bitmap.width; x++) {
				if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
					sprite.data[1 + x + (1 + y) * sprite.width].m = SHADOW_COLOUR;
					sprite.data[1 + x + (1 + y) * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
				}
			}
		}
	}

	for (int y = 0; y < slot->bitmap.rows; y++) {
		for (int x = 0; x < slot->bitmap.width; x++) {
			if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
				sprite.data[x + y * sprite.width].m = FACE_COLOUR;
				sprite.data[x + y * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
			}
		}
	}

	new_glyph.sprite = BlitterFactory::GetCurrentBlitter()->Encode(&sprite, AllocateFont);
	new_glyph.width  = slot->advance.x >> 6;

	this->SetGlyphPtr(key, &new_glyph);

	return new_glyph.sprite;
}
Exemple #23
0
/*-----------------------------------------------------------------------------
|	Calculates the log likelihood by calling the beagle functions
|	updateTransitionMatrices, updatePartials and calculateEdgeLogLikelihoods.
*/
double calcLnL(world_fmt *world, boolean instance)
{
  beagle_fmt *beagle = world->beagle;
  double logL = 0.0;
  unsigned long i;
  unsigned long j;
  //unsigned long z;
  long locus = world->locus;
  long ii;
  double *patternloglike = (double *) calloc(world->maxnumpattern[locus],sizeof(double));
   double *outlike = (double *) calloc(10*world->maxnumpattern[locus],sizeof(double));
  int rootIndex = beagle->operations[BEAGLE_PARTIALS * (beagle->numoperations-1)];//world->root->next->back->id;
  for(i=0; i<world->nummutationmodels[locus]; i++)
    {
      ii = world->sublocistarts[locus] + i;
      int code = beagleUpdateTransitionMatrices(beagle->instance_handle[i],		// instance,
					  0,					// eigenIndex,
					  (const int *) beagle->branch_indices,	// indicators transitionrates for each branch,
					  NULL, 			        // firstDerivativeIndices,
					  NULL,					// secondDervativeIndices,
					  beagle->branch_lengths,		// edgeLengths,
					  beagle->numbranches);			// number branches to update, count

	if (code != 0)
		usererror("updateTransitionMatrices encountered a problem");

	int cumulativeScalingFactorIndex = 0; //BEAGLE_OP_NONE; //this would be the index of the root scaling location 
	
	beagleResetScaleFactors(beagle->instance_handle[i],
			  cumulativeScalingFactorIndex);

	beagleAccumulateScaleFactors(beagle->instance_handle[i],
			       beagle->scalingfactorsindices,
			       beagle->scalingfactorscount,
			       cumulativeScalingFactorIndex);
	

	code = beagleUpdatePartials((const int *) &beagle->instance_handle[i],	// instance
			      1,					        // instanceCount
			      beagle->operations,		                // operations
			      beagle->numoperations,				// operationCount
				    cumulativeScalingFactorIndex);//BEAGLE_OP_NONE);					        // connected to accumulate....
#ifdef BEAGLEDEBUG
	for(j=0;j<2*(world->sumtips * 2 - 1); j++)
	  {
	    beagleGetPartials(beagle->instance_handle[i],j,BEAGLE_OP_NONE, outlike);
	    if(j==world->sumtips * 2 - 1)
	      printf("-----------------------\n");
	    printf("%li: {%f, %f, %f, %f}\n",j, outlike[0],outlike[1],outlike[2],outlike[3]);
	  }
#endif
	if (code != 0)
	  usererror("updatePartials encountered a problem");



	if(beagle->weights==NULL)
	  beagle->weights = (double *) mycalloc(1,sizeof(double));
	//	else
	//  beagle->weights = (double *) myrealloc(beagle->weights,beagle->numoperations * sizeof(double));

	beagle->weights[0]= 1.0;

	// calculate the site likelihoods at the root node
	code = beagleCalculateRootLogLikelihoods(beagle->instance_handle[i],         // instance
					   (const int *) &rootIndex, // bufferIndices
					   (const double *) world->mutationmodels[ii].siteprobs,   // weights
					   (const double *) world->mutationmodels[ii].basefreqs,// stateFrequencies
					   &cumulativeScalingFactorIndex, //scalingfactors index,
					   1,              // count is this correct
	                            patternloglike);         // outLogLikelihoods
	//trash from function above					   &beagle->scalingfactorscount,//size of the scaling factor index
	if (code != 0)
		usererror("calculateRootLogLikelihoods encountered a problem");

	for (j = 0; j < world->mutationmodels[ii].numsites; j++) 
	  {
		logL += beagle->allyweights[j] * patternloglike[j];
		//		printf("%.1f ",patternloglike[j]);
	}
    }
  printf("Log LnL=%f (instance=%li)\n",logL,(long) instance);
#ifdef BEAGLEDEBUG
  debug_beagle(beagle);
#endif
  myfree(patternloglike);
  myfree(outlike);
  return logL; 
}
Exemple #24
0
bool VideoDriver_SDL::CreateMainSurface(uint w, uint h)
{
	SDL_Surface *newscreen, *icon;
	char caption[50];
	int bpp = BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth();
	bool want_hwpalette;

	GetAvailableVideoMode(&w, &h);

	DEBUG(driver, 1, "SDL: using mode %ux%ux%d", w, h, bpp);

	if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals");

	char icon_path[MAX_PATH];
	if (FioFindFullPath(icon_path, lengthof(icon_path), BASESET_DIR, "openttd.32.bmp") != NULL) {
		/* Give the application an icon */
		icon = SDL_CALL SDL_LoadBMP(icon_path);
		if (icon != NULL) {
			/* Get the colourkey, which will be magenta */
			uint32 rgbmap = SDL_CALL SDL_MapRGB(icon->format, 255, 0, 255);

			SDL_CALL SDL_SetColorKey(icon, SDL_SRCCOLORKEY, rgbmap);
			SDL_CALL SDL_WM_SetIcon(icon, NULL);
			SDL_CALL SDL_FreeSurface(icon);
		}
	}

	if (_use_hwpalette == 2) {
		/* Default is to autodetect when to use SDL_HWPALETTE.
		 * In this case, SDL_HWPALETTE is only used for 8bpp
		 * blitters in fullscreen.
		 *
		 * When using an 8bpp blitter on a 8bpp system in
		 * windowed mode with SDL_HWPALETTE, OpenTTD will claim
		 * the system palette, making all other applications
		 * get the wrong colours. In this case, we're better of
		 * trying to approximate the colors we need using system
		 * colors, using a shadow surface (see below).
		 *
		 * On a 32bpp system, SDL_HWPALETTE is ignored, so it
		 * doesn't matter what we do.
		 *
		 * When using a 32bpp blitter on a 8bpp system, setting
		 * SDL_HWPALETTE messes up rendering (at least on X11),
		 * so we don't do that. In this case, SDL takes care of
		 * color approximation using its own shadow surface
		 * (which we can't force in 8bpp on 8bpp mode,
		 * unfortunately).
		 */
		want_hwpalette = (bpp == 8 && _fullscreen);
	} else {
		/* User specified a value manually */
		want_hwpalette = _use_hwpalette;
	}

	if (want_hwpalette) DEBUG(driver, 1, "SDL: requesting hardware palete");

	/* Free any previously allocated shadow surface */
	if (_sdl_screen != NULL && _sdl_screen != _sdl_realscreen) SDL_CALL SDL_FreeSurface(_sdl_screen);

	if (_sdl_realscreen != NULL) {
		if (_requested_hwpalette != want_hwpalette) {
			/* SDL (at least the X11 driver), reuses the
			 * same window and palette settings when the bpp
			 * (and a few flags) are the same. Since we need
			 * to hwpalette value to change (in particular
			 * when switching between fullscreen and
			 * windowed), we restart the entire video
			 * subsystem to force creating a new window.
			 */
			DEBUG(driver, 0, "SDL: Restarting SDL video subsystem, to force hwpalette change");
			SDL_CALL SDL_QuitSubSystem(SDL_INIT_VIDEO);
			SDL_CALL SDL_InitSubSystem(SDL_INIT_VIDEO);
			ClaimMousePointer();
			SetupKeyboard();
		}
	}
	/* Remember if we wanted a hwpalette. We can't reliably query
	 * SDL for the SDL_HWPALETTE flag, since it might get set even
	 * though we didn't ask for it (when SDL creates a shadow
	 * surface, for example). */
	_requested_hwpalette = want_hwpalette;

	/* DO NOT CHANGE TO HWSURFACE, IT DOES NOT WORK */
	newscreen = SDL_CALL SDL_SetVideoMode(w, h, bpp, SDL_SWSURFACE | (want_hwpalette ? SDL_HWPALETTE : 0) | (_fullscreen ? SDL_FULLSCREEN : SDL_RESIZABLE));
	if (newscreen == NULL) {
		DEBUG(driver, 0, "SDL: Couldn't allocate a window to draw on");
		return false;
	}
	_sdl_realscreen = newscreen;

	if (bpp == 8 && (_sdl_realscreen->flags & SDL_HWPALETTE) != SDL_HWPALETTE) {
		/* Using an 8bpp blitter, if we didn't get a hardware
		 * palette (most likely because we didn't request one,
		 * see above), we'll have to set up a shadow surface to
		 * render on.
		 *
		 * Our palette will be applied to this shadow surface,
		 * while the real screen surface will use the shared
		 * system palette (which will partly contain our colors,
		 * but most likely will not have enough free color cells
		 * for all of our colors). SDL can use these two
		 * palettes at blit time to approximate colors used in
		 * the shadow surface using system colors automatically.
		 *
		 * Note that when using an 8bpp blitter on a 32bpp
		 * system, SDL will create an internal shadow surface.
		 * This shadow surface will have SDL_HWPALLETE set, so
		 * we won't create a second shadow surface in this case.
		 */
		DEBUG(driver, 1, "SDL: using shadow surface");
		newscreen = SDL_CALL SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, bpp, 0, 0, 0, 0);
		if (newscreen == NULL) {
			DEBUG(driver, 0, "SDL: Couldn't allocate a shadow surface to draw on");
			return false;
		}
	}

	/* Delay drawing for this cycle; the next cycle will redraw the whole screen */
	_num_dirty_rects = 0;

	_screen.width = newscreen->w;
	_screen.height = newscreen->h;
	_screen.pitch = newscreen->pitch / (bpp / 8);
	_screen.dst_ptr = newscreen->pixels;
	_sdl_screen = newscreen;

	/* When in full screen, we will always have the mouse cursor
	 * within the window, even though SDL does not give us the
	 * appropriate event to know this. */
	if (_fullscreen) _cursor.in_window = true;

	Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
	blitter->PostResize();

	InitPalette();
	switch (blitter->UsePaletteAnimation()) {
		case Blitter::PALETTE_ANIMATION_NONE:
		case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
			UpdatePalette();
			break;

		case Blitter::PALETTE_ANIMATION_BLITTER:
			if (_video_driver != NULL) blitter->PaletteAnimate(_local_palette);
			break;

		default:
			NOT_REACHED();
	}

	snprintf(caption, sizeof(caption), "OpenTTD %s", _openttd_revision);
	SDL_CALL SDL_WM_SetCaption(caption, caption);

	GameSizeChanged();

	return true;
}
Exemple #25
0
/**
 * Instantiate a new window.
 * @param full_screen Whether to make a full screen window or not.
 * @return True if the window could be created.
 */
bool VideoDriver_Win32::MakeWindow(bool full_screen)
{
	_fullscreen = full_screen;

	/* recreate window? */
	if ((full_screen || _wnd.fullscreen) && _wnd.main_wnd) {
		DestroyWindow(_wnd.main_wnd);
		_wnd.main_wnd = 0;
	}

#if defined(WINCE)
	/* WinCE is always fullscreen */
#else
	if (full_screen) {
		DEVMODE settings;

		/* Make sure we are always at least the screen-depth of the blitter */
		if (_fullscreen_bpp < BlitterFactory::GetCurrentBlitter()->GetScreenDepth()) _fullscreen_bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth();

		memset(&settings, 0, sizeof(settings));
		settings.dmSize = sizeof(settings);
		settings.dmFields =
			(_fullscreen_bpp != 0 ? DM_BITSPERPEL : 0) |
			DM_PELSWIDTH |
			DM_PELSHEIGHT |
			(_display_hz != 0 ? DM_DISPLAYFREQUENCY : 0);
		settings.dmBitsPerPel = _fullscreen_bpp;
		settings.dmPelsWidth  = _wnd.width_org;
		settings.dmPelsHeight = _wnd.height_org;
		settings.dmDisplayFrequency = _display_hz;

		/* Check for 8 bpp support. */
		if (settings.dmBitsPerPel != 32 && ChangeDisplaySettings(&settings, CDS_FULLSCREEN | CDS_TEST) != DISP_CHANGE_SUCCESSFUL) {
			settings.dmBitsPerPel = 32;
		}

		/* Test fullscreen with current resolution, if it fails use desktop resolution. */
		if (ChangeDisplaySettings(&settings, CDS_FULLSCREEN | CDS_TEST) != DISP_CHANGE_SUCCESSFUL) {
			RECT r;
			GetWindowRect(GetDesktopWindow(), &r);
			/* Guard against recursion. If we already failed here once, just fall through to
			 * the next ChangeDisplaySettings call which will fail and error out appropriately. */
			if ((int)settings.dmPelsWidth != r.right - r.left || (int)settings.dmPelsHeight != r.bottom - r.top) {
				return this->ChangeResolution(r.right - r.left, r.bottom - r.top);
			}
		}

		if (ChangeDisplaySettings(&settings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) {
			this->MakeWindow(false);  // don't care about the result
			return false;  // the request failed
		}
	} else if (_wnd.fullscreen) {
		/* restore display? */
		ChangeDisplaySettings(NULL, 0);
		/* restore the resolution */
		_wnd.width = _bck_resolution.width;
		_wnd.height = _bck_resolution.height;
	}
#endif

	{
		RECT r;
		DWORD style, showstyle;
		int w, h;

		showstyle = SW_SHOWNORMAL;
		_wnd.fullscreen = full_screen;
		if (_wnd.fullscreen) {
			style = WS_POPUP;
			SetRect(&r, 0, 0, _wnd.width_org, _wnd.height_org);
		} else {
			style = WS_OVERLAPPEDWINDOW;
			/* On window creation, check if we were in maximize mode before */
			if (_window_maximize) showstyle = SW_SHOWMAXIMIZED;
			SetRect(&r, 0, 0, _wnd.width, _wnd.height);
		}

#if !defined(WINCE)
		AdjustWindowRect(&r, style, FALSE);
#endif
		w = r.right - r.left;
		h = r.bottom - r.top;

		if (_wnd.main_wnd != NULL) {
			if (!_window_maximize) SetWindowPos(_wnd.main_wnd, 0, 0, 0, w, h, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOMOVE);
		} else {
			TCHAR Windowtitle[50];
			int x = (GetSystemMetrics(SM_CXSCREEN) - w) / 2;
			int y = (GetSystemMetrics(SM_CYSCREEN) - h) / 2;

			_sntprintf(Windowtitle, lengthof(Windowtitle), _T("OpenTTD %s"), MB_TO_WIDE(_openttd_revision));

			_wnd.main_wnd = CreateWindow(_T("OTTD"), Windowtitle, style, x, y, w, h, 0, 0, GetModuleHandle(NULL), 0);
			if (_wnd.main_wnd == NULL) usererror("CreateWindow failed");
			ShowWindow(_wnd.main_wnd, showstyle);
		}
	}

	BlitterFactory::GetCurrentBlitter()->PostResize();

	GameSizeChanged(); // invalidate all windows, force redraw
	return true; // the request succeeded
}