/*
 * Method: GetCommodityBasePriceAlterations
 *
 * Get the price alterations for cargo items bought and sold in this system
 *
 * > alteration = system:GetCommodityBasePriceAlterations(cargo_item)
 *
 * Parameters:
 *
 *   cargo_item - The cargo item for which one wants to know the alteration
 * Return:
 *
 *   percentage -  percentage change to the cargo base price. Loosely,
 *                 positive values make the commodity more expensive,
 *                 indicating it is in demand, while negative values make the
 *                 commodity cheaper, indicating a surplus.
 *
 * Availability:
 *
 *   June 2014
 *
 * Status:
 *
 *   experimental
 */
static int l_starsystem_get_commodity_base_price_alterations(lua_State *l)
{
	PROFILE_SCOPED()
	LUA_DEBUG_START(l);

	StarSystem *s = LuaObject<StarSystem>::CheckFromLua(1);
	if (!lua_istable(l, 2)) {
		return luaL_error(l, "GetCommodityBasePriceAlterations takes a cargo object as and argument.");
	}
	LuaTable equip(l, 2);

	if (!equip.CallMethod<bool>("IsValidSlot", "cargo")) {
		luaL_error(l, "GetCommodityBasePriceAlterations takes a valid cargo item as argument.");
		return 0;
	}
	equip.PushValueToStack("l10n_key"); // For now let's just use this poor man's hack.
	GalacticEconomy::Commodity e = static_cast<GalacticEconomy::Commodity>(
			LuaConstants::GetConstantFromArg(l, "CommodityType", -1));
	lua_pop(l, 1);
	lua_pushnumber(l, s->GetCommodityBasePriceModPercent(e));

	LUA_DEBUG_END(l, 1);
	return 1;
}
Beispiel #2
0
void Space::ToJson(Json::Value &jsonObj)
{
	PROFILE_SCOPED()
	RebuildFrameIndex();
	RebuildBodyIndex();
	RebuildSystemBodyIndex();

	Json::Value spaceObj(Json::objectValue); // Create JSON object to contain space data (all the bodies and things).

	StarSystem::ToJson(spaceObj, m_starSystem.Get());

	Frame::ToJson(spaceObj, m_rootFrame.get(), this);

	Json::Value bodyArray(Json::arrayValue); // Create JSON array to contain body data.
	for (Body* b : m_bodies)
	{
		Json::Value bodyArrayEl(Json::objectValue); // Create JSON object to contain body.
		b->ToJson(bodyArrayEl, this);
		bodyArray.append(bodyArrayEl); // Append body object to array.
	}
	spaceObj["bodies"] = bodyArray; // Add body array to space object.

	jsonObj["space"] = spaceObj; // Add space object to supplied object.
}
Beispiel #3
0
void SpeedLines::Render(Graphics::Renderer *r)
{
	PROFILE_SCOPED();
	if (!m_visible || m_points.empty()) return;

	const vector3f dir = m_dir * m_lineLength;

	Uint16 vtx = 0;
	//distance fade
	Color col(Color::GRAY);
	for (auto it = m_points.begin(); it != m_points.end(); ++it) {
		col.a = Clamp((1.f - it->Length() / BOUNDS),0.f,1.f) * 255;

		m_varray->Set(vtx, *it - dir, col);
		m_varray->Set(vtx+1,*it + dir, col);

		vtx += 2;
	}

	m_vbuffer->Populate( *m_varray );

	r->SetTransform(m_transform);
	r->DrawBuffer(m_vbuffer.get(), m_renderState, m_material.Get(), Graphics::LINE_SINGLE);
}
Beispiel #4
0
	float Animation::Update(float time)
	{
		PROFILE_SCOPED();
		if (m_completed)
			return 0.0f;

		const float remaining = m_continuous ? m_duration : (m_duration - time);
		m_completed = remaining < 0.0f;

		float pos;
		if (m_continuous)
			pos = m_completed ? m_duration : fmodf(time, m_duration);
		else
			pos = m_completed ? m_duration : Clamp(time, 0.0f, m_duration);

		m_targetFunc(m_wrapFunc(m_easingFunc, pos, m_duration));

		m_running = !m_completed;

		if (m_completed && m_callback)
			m_callback();

		return remaining;
	}
/*
 * Method: DistanceTo
 *
 * Calculate the distance between this and another system
 *
 * > dist = system:DistanceTo(system)
 *
 * Parameters:
 *
 *   system - a <SystemPath> or <StarSystem> to calculate the distance to
 *
 * Return:
 *
 *   dist - the distance, in light years
 *
 * Availability:
 *
 *   alpha 10
 *
 * Status:
 *
 *   stable
 */
static int l_starsystem_distance_to(lua_State *l)
{
	PROFILE_SCOPED()
	LUA_DEBUG_START(l);

	StarSystem *s = LuaObject<StarSystem>::CheckFromLua(1);
	const SystemPath *loc1 = &(s->GetPath());

	const SystemPath *loc2 = LuaObject<SystemPath>::GetFromLua(2);
	if (!loc2) {
		StarSystem *s2 = LuaObject<StarSystem>::CheckFromLua(2);
		loc2 = &(s2->GetPath());
	}

	RefCountedPtr<const Sector> sec1 = s->m_galaxy->GetSector(*loc1);
	RefCountedPtr<const Sector> sec2 = s->m_galaxy->GetSector(*loc2);

	double dist = Sector::DistanceBetween(sec1, loc1->systemIndex, sec2, loc2->systemIndex);

	lua_pushnumber(l, dist);

	LUA_DEBUG_END(l, 1);
	return 1;
}
void ShipCockpit::Render(Graphics::Renderer *renderer, const Camera *camera, const vector3d &viewCoords, const matrix4x4d &viewTransform)
{
	PROFILE_SCOPED()
	RenderModel(renderer, camera, viewCoords, viewTransform);
}
Beispiel #7
0
void ShipCpanel::TimeStepUpdate(float step)
{
	PROFILE_SCOPED()
	m_scanner->TimeStepUpdate(step);
}
Beispiel #8
0
void Pi::MainLoop()
{
	double time_player_died = 0;
#ifdef MAKING_VIDEO
	Uint32 last_screendump = SDL_GetTicks();
	int dumpnum = 0;
#endif /* MAKING_VIDEO */

#if WITH_DEVKEYS
	Uint32 last_stats = SDL_GetTicks();
	int frame_stat = 0;
	int phys_stat = 0;
	char fps_readout[256];
	memset(fps_readout, 0, sizeof(fps_readout));
#endif

	int MAX_PHYSICS_TICKS = Pi::config->Int("MaxPhysicsCyclesPerRender");
	if (MAX_PHYSICS_TICKS <= 0)
		MAX_PHYSICS_TICKS = 4;

	double currentTime = 0.001 * double(SDL_GetTicks());
	double accumulator = Pi::game->GetTimeStep();
	Pi::gameTickAlpha = 0;

	while (Pi::game) {
		PROFILE_SCOPED()

#ifdef PIONEER_PROFILER
		Profiler::reset();
#endif

		const Uint32 newTicks = SDL_GetTicks();
		double newTime = 0.001 * double(newTicks);
		Pi::frameTime = newTime - currentTime;
		if (Pi::frameTime > 0.25) Pi::frameTime = 0.25;
		currentTime = newTime;
		accumulator += Pi::frameTime * Pi::game->GetTimeAccelRate();

		const float step = Pi::game->GetTimeStep();
		if (step > 0.0f) {
			PROFILE_SCOPED_RAW("unpaused")
			int phys_ticks = 0;
			while (accumulator >= step) {
				if (++phys_ticks >= MAX_PHYSICS_TICKS) {
					accumulator = 0.0;
					break;
				}
				game->TimeStep(step);
				BaseSphere::UpdateAllBaseSphereDerivatives();

				accumulator -= step;
			}
			// rendering interpolation between frames: don't use when docked
			int pstate = Pi::game->GetPlayer()->GetFlightState();
			if (pstate == Ship::DOCKED || pstate == Ship::DOCKING) Pi::gameTickAlpha = 1.0;
			else Pi::gameTickAlpha = accumulator / step;

#if WITH_DEVKEYS
			phys_stat += phys_ticks;
#endif
		} else {
Beispiel #9
0
GeomTree::GeomTree(Serializer::Reader &rd)
{
	PROFILE_SCOPED()
	m_numVertices = rd.Int32();
	m_numEdges = rd.Int32();
	m_numTris = rd.Int32();
	m_radius = rd.Double();

	m_aabb.max = rd.Vector3d();
	m_aabb.min = rd.Vector3d();
	m_aabb.radius = rd.Double();

	const Uint32 numAabbs = rd.Int32();
	m_aabbs.resize(numAabbs);
	for (Uint32 iAabb = 0; iAabb < numAabbs; ++iAabb) {
		m_aabbs[iAabb].max = rd.Vector3d();
		m_aabbs[iAabb].min = rd.Vector3d();
		m_aabbs[iAabb].radius = rd.Double();
	}

	m_edges.resize(m_numEdges);
	for (Sint32 iEdge = 0; iEdge < m_numEdges; ++iEdge) {
		m_edges[iEdge].Load(rd);
	}

	m_vertices.resize(m_numVertices);
	for (Sint32 iVert = 0; iVert < m_numVertices; ++iVert) {
		m_vertices[iVert] = rd.Vector3f();
	}

	const int numIndicies(m_numTris * 3);
	m_indices.resize(numIndicies);
	for (Sint32 iIndi = 0; iIndi < numIndicies; ++iIndi) {
		m_indices[iIndi] = rd.Int32();
	}

	m_triFlags.resize(m_numTris);
	for (Sint32 iTri = 0; iTri < m_numTris; ++iTri) {
		m_triFlags[iTri] = rd.Int32();
	}

	// activeTris = tris we are still trying to put into leaves
	std::vector<int> activeTris;
	activeTris.reserve(m_numTris);
	for (int i = 0; i < m_numTris; i++) {
		activeTris.push_back(i * 3);
	}

	// regenerate the aabb data
	Aabb *aabbs = new Aabb[activeTris.size()];
	for (Uint32 i = 0; i < activeTris.size(); i++) {
		const vector3d v1 = vector3d(m_vertices[m_indices[activeTris[i] + 0]]);
		const vector3d v2 = vector3d(m_vertices[m_indices[activeTris[i] + 1]]);
		const vector3d v3 = vector3d(m_vertices[m_indices[activeTris[i] + 2]]);
		aabbs[i].min = aabbs[i].max = v1;
		aabbs[i].Update(v2);
		aabbs[i].Update(v3);
	}
	m_triTree.reset(new BVHTree(activeTris.size(), &activeTris[0], aabbs));
	delete[] aabbs;

	//
	int *edgeIdxs = new int[m_numEdges];
	memset(edgeIdxs, 0, sizeof(int) * m_numEdges);
	for (int i = 0; i < m_numEdges; i++) {
		edgeIdxs[i] = i;
	}
	m_edgeTree.reset(new BVHTree(m_numEdges, edgeIdxs, &m_aabbs[0]));
}
Beispiel #10
0
GeomTree::GeomTree(const int numVerts, const int numTris, const std::vector<vector3f> &vertices, const Uint32 *indices, const Uint32 *triflags) :
	m_numVertices(numVerts),
	m_numTris(numTris),
	m_vertices(vertices)
{
	PROFILE_SCOPED()
	assert(static_cast<int>(vertices.size()) == m_numVertices);
	Profiler::Timer timer;
	timer.Start();

	const int numIndices = numTris * 3;
	m_indices.reserve(numIndices);
	for (int i = 0; i < numIndices; ++i) {
		m_indices.push_back(indices[i]);
	}

	m_triFlags.reserve(numTris);
	for (int i = 0; i < numTris; ++i) {
		m_triFlags.push_back(triflags[i]);
	}

	m_aabb.min = vector3d(FLT_MAX, FLT_MAX, FLT_MAX);
	m_aabb.max = vector3d(-FLT_MAX, -FLT_MAX, -FLT_MAX);

	// activeTris = tris we are still trying to put into leaves
	std::vector<int> activeTris;
	activeTris.reserve(numTris);
	for (int i = 0; i < numTris; i++) {
		activeTris.push_back(i * 3);
	}

	typedef std::map<std::pair<int, int>, int> EdgeType;
	EdgeType edges;
#define ADD_EDGE(_i1, _i2, _triflag)                     \
	if ((_i1) < (_i2))                                   \
		edges[std::pair<int, int>(_i1, _i2)] = _triflag; \
	else if ((_i1) > (_i2))                              \
		edges[std::pair<int, int>(_i2, _i1)] = _triflag;

	// eliminate duplicate vertices
	{
		std::vector<Uint32> xrefs;
		nv::Weld<vector3f> weld;
		weld(m_vertices, xrefs);
		m_numVertices = m_vertices.size();

		//Output("---   %d vertices welded\n", count - newCount);

		// Remap faces.
		const Uint32 faceCount = numTris;
		for (Uint32 f = 0; f < faceCount; f++) {
			const Uint32 idx = (f * 3);
			m_indices[idx + 0] = xrefs.at(m_indices[idx + 0]);
			m_indices[idx + 1] = xrefs.at(m_indices[idx + 1]);
			m_indices[idx + 2] = xrefs.at(m_indices[idx + 2]);
		}
	}

	// Get radius, m_aabb, and merge duplicate edges
	m_radius = 0;
	for (int i = 0; i < numTris; i++) {
		const Uint32 triflag = m_triFlags[i];
		const int vi1 = m_indices[3 * i + 0];
		const int vi2 = m_indices[3 * i + 1];
		const int vi3 = m_indices[3 * i + 2];

		ADD_EDGE(vi1, vi2, triflag);
		ADD_EDGE(vi1, vi3, triflag);
		ADD_EDGE(vi2, vi3, triflag);

		vector3d v[3];
		v[0] = vector3d(m_vertices[vi1]);
		v[1] = vector3d(m_vertices[vi2]);
		v[2] = vector3d(m_vertices[vi3]);
		m_aabb.Update(v[0]);
		m_aabb.Update(v[1]);
		m_aabb.Update(v[2]);
		for (int j = 0; j < 3; j++) {
			const double rad = v[j].x * v[j].x + v[j].y * v[j].y + v[j].z * v[j].z;
			if (rad > m_radius) m_radius = rad;
		}
	}
	m_radius = sqrt(m_radius);

	{
		Aabb *aabbs = new Aabb[activeTris.size()];
		for (Uint32 i = 0; i < activeTris.size(); i++) {
			const vector3d v1 = vector3d(m_vertices[m_indices[activeTris[i] + 0]]);
			const vector3d v2 = vector3d(m_vertices[m_indices[activeTris[i] + 1]]);
			const vector3d v3 = vector3d(m_vertices[m_indices[activeTris[i] + 2]]);
			aabbs[i].min = aabbs[i].max = v1;
			aabbs[i].Update(v2);
			aabbs[i].Update(v3);
		}

		//int t = SDL_GetTicks();
		m_triTree.reset(new BVHTree(activeTris.size(), &activeTris[0], aabbs));
		delete[] aabbs;
	}
	//Output("Tri tree of %d tris build in %dms\n", activeTris.size(), SDL_GetTicks() - t);

	m_numEdges = edges.size();
	m_edges.resize(m_numEdges);
	// to build Edge bvh tree with.
	m_aabbs.resize(m_numEdges);
	int *edgeIdxs = new int[m_numEdges];

	int pos = 0;
	typedef EdgeType::iterator MapPairIter;
	for (MapPairIter i = edges.begin(), iEnd = edges.end(); i != iEnd; ++i, pos++) {
		// precalc some j**z
		const std::pair<int, int> &vtx = (*i).first;
		const int triflag = (*i).second;
		const vector3f &v1 = m_vertices[vtx.first];
		const vector3f &v2 = m_vertices[vtx.second];
		vector3f dir = (v2 - v1);
		const float len = dir.Length();
		dir *= 1.0f / len;

		m_edges[pos].v1i = vtx.first;
		m_edges[pos].v2i = vtx.second;
		m_edges[pos].triFlag = triflag;
		m_edges[pos].len = len;
		m_edges[pos].dir = dir;

		edgeIdxs[pos] = pos;
		m_aabbs[pos].min = m_aabbs[pos].max = vector3d(v1);
		m_aabbs[pos].Update(vector3d(v2));
	}

	//t = SDL_GetTicks();
	m_edgeTree.reset(new BVHTree(m_numEdges, edgeIdxs, &m_aabbs[0]));
	delete[] edgeIdxs;
	//Output("Edge tree of %d edges build in %dms\n", m_numEdges, SDL_GetTicks() - t);

	timer.Stop();
	//Output(" - - GeomTree::GeomTree took: %lf milliseconds\n", timer.millicycles());
}
Beispiel #11
0
void Pi::Init(const std::map<std::string, std::string> &options, bool no_gui)
{
#ifdef PIONEER_PROFILER
	Profiler::reset();
#endif

	Profiler::Timer timer;
	timer.Start();

	OS::EnableBreakpad();
	OS::NotifyLoadBegin();

	FileSystem::Init();
	FileSystem::userFiles.MakeDirectory(""); // ensure the config directory exists
#ifdef PIONEER_PROFILER
	FileSystem::userFiles.MakeDirectory("profiler");
	profilerPath = FileSystem::JoinPathBelow(FileSystem::userFiles.GetRoot(), "profiler");
#endif
	PROFILE_SCOPED()

	Pi::config = new GameConfig(options);

	if (config->Int("RedirectStdio"))
		OS::RedirectStdio();

	std::string version(PIONEER_VERSION);
	if (strlen(PIONEER_EXTRAVERSION)) version += " (" PIONEER_EXTRAVERSION ")";
	const char *platformName = SDL_GetPlatform();
	if (platformName)
		Output("ver %s on: %s\n\n", version.c_str(), platformName);
	else
		Output("ver %s but could not detect platform name.\n\n", version.c_str());

	Output("%s\n", OS::GetOSInfoString().c_str());

	ModManager::Init();

	Lang::Resource res(Lang::GetResource("core", config->String("Lang")));
	Lang::MakeCore(res);

	Pi::SetAmountBackgroundStars(config->Float("AmountOfBackgroundStars"));
	Pi::detail.planets = config->Int("DetailPlanets");
	Pi::detail.cities = config->Int("DetailCities");

	// Initialize SDL
	Uint32 sdlInitFlags = SDL_INIT_VIDEO | SDL_INIT_JOYSTICK;
#if defined(DEBUG) || defined(_DEBUG)
	sdlInitFlags |= SDL_INIT_NOPARACHUTE;
#endif
	if (SDL_Init(sdlInitFlags) < 0) {
		Error("SDL initialization failed: %s\n", SDL_GetError());
	}

	OutputVersioningInfo();

	Graphics::RendererOGL::RegisterRenderer();

	// determine what renderer we should use, default to Opengl 3.x
	const std::string rendererName = config->String("RendererName", Graphics::RendererNameFromType(Graphics::RENDERER_OPENGL_3x));
	Graphics::RendererType rType = Graphics::RENDERER_OPENGL_3x;
	//if(rendererName == Graphics::RendererNameFromType(Graphics::RENDERER_OPENGL_3x))
	//{
	//	rType = Graphics::RENDERER_OPENGL_3x;
	//}

	// Do rest of SDL video initialization and create Renderer
	Graphics::Settings videoSettings = {};
	videoSettings.rendererType = rType;
	videoSettings.width = config->Int("ScrWidth");
	videoSettings.height = config->Int("ScrHeight");
	videoSettings.fullscreen = (config->Int("StartFullscreen") != 0);
	videoSettings.hidden = no_gui;
	videoSettings.requestedSamples = config->Int("AntiAliasingMode");
	videoSettings.vsync = (config->Int("VSync") != 0);
	videoSettings.useTextureCompression = (config->Int("UseTextureCompression") != 0);
	videoSettings.useAnisotropicFiltering = (config->Int("UseAnisotropicFiltering") != 0);
	videoSettings.enableDebugMessages = (config->Int("EnableGLDebug") != 0);
	videoSettings.gl3ForwardCompatible = (config->Int("GL3ForwardCompatible") != 0);
	videoSettings.iconFile = OS::GetIconFilename();
	videoSettings.title = "Pioneer";

	Pi::renderer = Graphics::Init(videoSettings);

	Pi::CreateRenderTarget(videoSettings.width, videoSettings.height);
	Pi::rng.IncRefCount(); // so nothing tries to free it
	Pi::rng.seed(time(0));

	input.Init();
	input.onKeyPress.connect(sigc::ptr_fun(&Pi::HandleKeyDown));

	// we can only do bindings once joysticks are initialised.
	if (!no_gui) // This re-saves the config file. With no GUI we want to allow multiple instances in parallel.
		KeyBindings::InitBindings();

	RegisterInputBindings();

	navTunnelDisplayed = (config->Int("DisplayNavTunnel")) ? true : false;
	speedLinesDisplayed = (config->Int("SpeedLines")) ? true : false;
	hudTrailsDisplayed = (config->Int("HudTrails")) ? true : false;

	TestGPUJobsSupport();

	EnumStrings::Init();

	// get threads up
	Uint32 numThreads = config->Int("WorkerThreads");
	const int numCores = OS::GetNumCores();
	assert(numCores > 0);
	if (numThreads == 0) numThreads = std::max(Uint32(numCores) - 1, 1U);
	asyncJobQueue.reset(new AsyncJobQueue(numThreads));
	Output("started %d worker threads\n", numThreads);
	syncJobQueue.reset(new SyncJobQueue);

	Output("ShipType::Init()\n");
	// XXX early, Lua init needs it
	ShipType::Init();

	// XXX UI requires Lua  but Pi::ui must exist before we start loading
	// templates. so now we have crap everywhere :/
	Output("Lua::Init()\n");
	Lua::Init();

	Pi::pigui.Reset(new PiGui);
	Pi::pigui->Init(Pi::renderer->GetSDLWindow());

	float ui_scale = config->Float("UIScaleFactor", 1.0f);
	if (Graphics::GetScreenHeight() < 768) {
		ui_scale = float(Graphics::GetScreenHeight()) / 768.0f;
	}

	Pi::ui.Reset(new UI::Context(
		Lua::manager,
		Pi::renderer,
		Graphics::GetScreenWidth(),
		Graphics::GetScreenHeight(),
		ui_scale));

#ifdef ENABLE_SERVER_AGENT
	Pi::serverAgent = 0;
	if (config->Int("EnableServerAgent")) {
		const std::string endpoint(config->String("ServerEndpoint"));
		if (endpoint.size() > 0) {
			Output("Server agent enabled, endpoint: %s\n", endpoint.c_str());
			Pi::serverAgent = new HTTPServerAgent(endpoint);
		}
	}
	if (!Pi::serverAgent) {
		Output("Server agent disabled\n");
		Pi::serverAgent = new NullServerAgent();
	}
#endif

	LuaInit();

	Gui::Init(renderer, Graphics::GetScreenWidth(), Graphics::GetScreenHeight(), 800, 600);

	// twice, to initialize the font correctly
	draw_progress(0.01f);
	draw_progress(0.01f);

	Output("GalaxyGenerator::Init()\n");
	if (config->HasEntry("GalaxyGenerator"))
		GalaxyGenerator::Init(config->String("GalaxyGenerator"),
			config->Int("GalaxyGeneratorVersion", GalaxyGenerator::LAST_VERSION));
	else
		GalaxyGenerator::Init();

	draw_progress(0.1f);

	Output("FaceParts::Init()\n");
	FaceParts::Init();
	draw_progress(0.2f);

	Output("new ModelCache\n");
	modelCache = new ModelCache(Pi::renderer);
	draw_progress(0.3f);

	Output("Shields::Init\n");
	Shields::Init(Pi::renderer);
	draw_progress(0.4f);

	//unsigned int control_word;
	//_clearfp();
	//_controlfp_s(&control_word, _EM_INEXACT | _EM_UNDERFLOW | _EM_ZERODIVIDE, _MCW_EM);
	//double fpexcept = Pi::timeAccelRates[1] / Pi::timeAccelRates[0];

	Output("BaseSphere::Init\n");
	BaseSphere::Init();
	draw_progress(0.5f);

	Output("CityOnPlanet::Init\n");
	CityOnPlanet::Init();
	draw_progress(0.6f);

	Output("SpaceStation::Init\n");
	SpaceStation::Init();
	draw_progress(0.7f);

	Output("NavLights::Init\n");
	NavLights::Init(Pi::renderer);
	draw_progress(0.75f);

	Output("Sfx::Init\n");
	SfxManager::Init(Pi::renderer);
	draw_progress(0.8f);

	if (!no_gui && !config->Int("DisableSound")) {
		Output("Sound::Init\n");
		Sound::Init();
		Sound::SetMasterVolume(config->Float("MasterVolume"));
		Sound::SetSfxVolume(config->Float("SfxVolume"));
		GetMusicPlayer().SetVolume(config->Float("MusicVolume"));

		Sound::Pause(0);
		if (config->Int("MasterMuted")) Sound::Pause(1);
		if (config->Int("SfxMuted")) Sound::SetSfxVolume(0.f);
		if (config->Int("MusicMuted")) GetMusicPlayer().SetEnabled(false);
	}
	draw_progress(0.9f);

	OS::NotifyLoadEnd();
	draw_progress(0.95f);

#if 0
	// frame test code

	Frame *root = new Frame(0, "root", 0);
	Frame *p1 = new Frame(root, "p1", Frame::FLAG_HAS_ROT);
	Frame *p1r = new Frame(p1, "p1r", Frame::FLAG_ROTATING);
	Frame *m1 = new Frame(p1, "m1", Frame::FLAG_HAS_ROT);
	Frame *m1r = new Frame(m1, "m1r", Frame::FLAG_ROTATING);
	Frame *p2 = new Frame(root, "p2", Frame::FLAG_HAS_ROT);
	Frame *p2r = new Frame(p2, "pr2", Frame::FLAG_ROTATING);

	p1->SetPosition(vector3d(1000,0,0));
	p1->SetVelocity(vector3d(0,1,0));
	p2->SetPosition(vector3d(0,2000,0));
	p2->SetVelocity(vector3d(-2,0,0));
	p1r->SetAngVelocity(vector3d(0,0,0.0001));
	p1r->SetOrient(matrix3x3d::BuildRotate(M_PI/4, vector3d(0,0,1)));
	p2r->SetAngVelocity(vector3d(0,0,-0.0004));
	p2r->SetOrient(matrix3x3d::BuildRotate(-M_PI/2, vector3d(0,0,1)));
	root->UpdateOrbitRails(0, 0);

	CargoBody *c1 = new CargoBody(Equip::Type::SLAVES);
	c1->SetFrame(p1r);
	c1->SetPosition(vector3d(0,180,0));
//	c1->SetVelocity(vector3d(1,0,0));
	CargoBody *c2 = new CargoBody(Equip::Type::SLAVES);
	c2->SetFrame(p1r);
	c2->SetPosition(vector3d(0,200,0));
//	c2->SetVelocity(vector3d(1,0,0));

	vector3d pos = c1->GetPositionRelTo(p1);
	vector3d vel = c1->GetVelocityRelTo(p1);
	double speed = vel.Length();
	vector3d pos2 = c2->GetPositionRelTo(p1);
	vector3d vel2 = c2->GetVelocityRelTo(p1);
	double speed2 = vel2.Length();

	double speed3 = c2->GetVelocityRelTo(c1).Length();
	c2->SwitchToFrame(p1);
	vector3d vel4 = c2->GetVelocityRelTo(c1);
	double speed4 = c2->GetVelocityRelTo(c1).Length();

	root->UpdateOrbitRails(0, 1.0);

	//buildrotate test

	matrix3x3d m = matrix3x3d::BuildRotate(M_PI/2, vector3d(0,0,1));
	vector3d v = m * vector3d(1,0,0);

/*	vector3d pos = p1r->GetPositionRelTo(p2r);
	vector3d vel = p1r->GetVelocityRelTo(p2r);
	matrix3x3d o1 = p1r->GetOrientRelTo(p2r);
	double speed = vel.Length();
	vector3d pos2 = p2r->GetPositionRelTo(p1r);
	vector3d vel2 = p2r->GetVelocityRelTo(p1r);
	matrix3x3d o2 = p2r->GetOrientRelTo(p1r);
	double speed2 = vel2.Length();
*/	root->UpdateOrbitRails(0, 1.0/60);

	delete p2r; delete p2; delete m1r; delete m1; delete p1r; delete p1; delete root;
	delete c1; delete c2;

#endif

#if 0
	// test code to produce list of ship stats

	FILE *pStatFile = fopen("shipstat.csv","wt");
	if (pStatFile)
	{
		fprintf(pStatFile, "name,modelname,hullmass,capacity,fakevol,rescale,xsize,ysize,zsize,facc,racc,uacc,sacc,aacc,exvel\n");
		for (auto iter : ShipType::types)
		{
			const ShipType *shipdef = &(iter.second);
			SceneGraph::Model *model = Pi::FindModel(shipdef->modelName, false);

			double hullmass = shipdef->hullMass;
			double capacity = shipdef->capacity;

			double xsize = 0.0, ysize = 0.0, zsize = 0.0, fakevol = 0.0, rescale = 0.0, brad = 0.0;
			if (model) {
				std::unique_ptr<SceneGraph::Model> inst(model->MakeInstance());
				model->CreateCollisionMesh();
				Aabb aabb = model->GetCollisionMesh()->GetAabb();
				xsize = aabb.max.x-aabb.min.x;
				ysize = aabb.max.y-aabb.min.y;
				zsize = aabb.max.z-aabb.min.z;
				fakevol = xsize*ysize*zsize;
				brad = aabb.GetRadius();
				rescale = pow(fakevol/(100 * (hullmass+capacity)), 0.3333333333);
			}

			double simass = (hullmass + capacity) * 1000.0;
			double angInertia = (2/5.0)*simass*brad*brad;
			double acc1 = shipdef->linThrust[Thruster::THRUSTER_FORWARD] / (9.81*simass);
			double acc2 = shipdef->linThrust[Thruster::THRUSTER_REVERSE] / (9.81*simass);
			double acc3 = shipdef->linThrust[Thruster::THRUSTER_UP] / (9.81*simass);
			double acc4 = shipdef->linThrust[Thruster::THRUSTER_RIGHT] / (9.81*simass);
			double acca = shipdef->angThrust/angInertia;
			double exvel = shipdef->effectiveExhaustVelocity;

			fprintf(pStatFile, "%s,%s,%.1f,%.1f,%.1f,%.3f,%.1f,%.1f,%.1f,%.1f,%.1f,%.1f,%.1f,%f,%.1f\n",
				shipdef->name.c_str(), shipdef->modelName.c_str(), hullmass, capacity,
				fakevol, rescale, xsize, ysize, zsize, acc1, acc2, acc3, acc4, acca, exvel);
		}
		fclose(pStatFile);
	}
#endif

	luaConsole = new LuaConsole();
	KeyBindings::toggleLuaConsole.onPress.connect(sigc::mem_fun(Pi::luaConsole, &LuaConsole::Toggle));

	planner = new TransferPlanner();

	draw_progress(1.0f);

	timer.Stop();
#ifdef PIONEER_PROFILER
	Profiler::dumphtml(profilerPath.c_str());
#endif
	Output("\n\nLoading took: %lf milliseconds\n", timer.millicycles());
}
Beispiel #12
0
void Pi::HandleEvents()
{
	PROFILE_SCOPED()
	SDL_Event event;

	// XXX for most keypresses SDL will generate KEYUP/KEYDOWN and TEXTINPUT
	// events. keybindings run off KEYUP/KEYDOWN. the console is opened/closed
	// via keybinding. the console TextInput widget uses TEXTINPUT events. thus
	// after switching the console, the stray TEXTINPUT event causes the
	// console key (backtick) to appear in the text entry field. we hack around
	// this by setting this flag if the console was switched. if its set, we
	// swallow the TEXTINPUT event this hack must remain until we have a
	// unified input system
	bool skipTextInput = false;

	Pi::input.mouseMotion[0] = Pi::input.mouseMotion[1] = 0;
	while (SDL_PollEvent(&event)) {
		if (event.type == SDL_QUIT) {
			Pi::RequestQuit();
		}

		Pi::pigui->ProcessEvent(&event);

		if (Pi::pigui->WantCaptureMouse()) {
			// don't process mouse event any further, imgui already handled it
			switch (event.type) {
			case SDL_MOUSEBUTTONDOWN:
			case SDL_MOUSEBUTTONUP:
			case SDL_MOUSEWHEEL:
			case SDL_MOUSEMOTION:
				continue;
			default: break;
			}
		}
		if (Pi::pigui->WantCaptureKeyboard()) {
			// don't process keyboard event any further, imgui already handled it
			switch (event.type) {
			case SDL_KEYDOWN:
			case SDL_KEYUP:
			case SDL_TEXTINPUT:
				continue;
			default: break;
			}
		}

		if (skipTextInput && event.type == SDL_TEXTINPUT) {
			skipTextInput = false;
			continue;
		}
		if (ui->DispatchSDLEvent(event))
			continue;

		bool consoleActive = Pi::IsConsoleActive();
		if (!consoleActive) {
			KeyBindings::DispatchSDLEvent(&event);
			if (currentView)
				currentView->HandleSDLEvent(event);
		} else
			KeyBindings::toggleLuaConsole.CheckSDLEventAndDispatch(&event);
		if (consoleActive != Pi::IsConsoleActive()) {
			skipTextInput = true;
			continue;
		}

		if (Pi::IsConsoleActive())
			continue;

		Gui::HandleSDLEvent(&event);
		input.HandleSDLEvent(event);
	}
}
Beispiel #13
0
void Disk::Draw(Renderer *r)
{
	PROFILE_SCOPED()
	r->DrawBuffer(m_vertexBuffer.get(), m_renderState, m_material.Get(), TRIANGLE_FAN);
}
Beispiel #14
0
void Geom::MoveTo(const matrix4x4d &m)
{
	PROFILE_SCOPED()
	m_orient = m;
	m_invOrient = m.Inverse();
}
Beispiel #15
0
void Container::SetIntensity(float intensity)
{
	PROFILE_SCOPED()
	m_starField.SetIntensity(intensity);
	m_milkyWay.SetIntensity(intensity);
}
Beispiel #16
0
const std::string SectorRandomSystemsGenerator::GenName(RefCountedPtr<Galaxy> galaxy, const Sector& sec, Sector::System &sys, int si, Random &rng)
{
	PROFILE_SCOPED()
	std::string name;
	const int sx = sec.sx;
	const int sy = sec.sy;
	const int sz = sec.sz;
	const int dist = std::max(std::max(abs(sx),abs(sy)),abs(sz));

	int chance = 100;
	switch (sys.m_starType[0]) {
		case SystemBody::TYPE_STAR_O:
		case SystemBody::TYPE_STAR_B: break;
		case SystemBody::TYPE_STAR_A: chance += dist; break;
		case SystemBody::TYPE_STAR_F: chance += 2*dist; break;
		case SystemBody::TYPE_STAR_G: chance += 4*dist; break;
		case SystemBody::TYPE_STAR_K: chance += 8*dist; break;
		case SystemBody::TYPE_STAR_O_GIANT:
		case SystemBody::TYPE_STAR_B_GIANT: chance = 50; break;
		case SystemBody::TYPE_STAR_A_GIANT: chance = int(0.2*dist); break;
		case SystemBody::TYPE_STAR_F_GIANT: chance = int(0.4*dist); break;
		case SystemBody::TYPE_STAR_G_GIANT: chance = int(0.5*dist); break;
		case SystemBody::TYPE_STAR_K_GIANT:
		case SystemBody::TYPE_STAR_M_GIANT: chance = dist; break;
		case SystemBody::TYPE_STAR_O_SUPER_GIANT:
		case SystemBody::TYPE_STAR_B_SUPER_GIANT: chance = 10; break;
		case SystemBody::TYPE_STAR_A_SUPER_GIANT:
		case SystemBody::TYPE_STAR_F_SUPER_GIANT:
		case SystemBody::TYPE_STAR_G_SUPER_GIANT:
		case SystemBody::TYPE_STAR_K_SUPER_GIANT: chance = 15; break;
		case SystemBody::TYPE_STAR_M_SUPER_GIANT: chance = 20; break;
		case SystemBody::TYPE_STAR_O_HYPER_GIANT:
		case SystemBody::TYPE_STAR_B_HYPER_GIANT:
		case SystemBody::TYPE_STAR_A_HYPER_GIANT:
		case SystemBody::TYPE_STAR_F_HYPER_GIANT:
		case SystemBody::TYPE_STAR_G_HYPER_GIANT:
		case SystemBody::TYPE_STAR_K_HYPER_GIANT:
		case SystemBody::TYPE_STAR_M_HYPER_GIANT: chance = 1; break;  //Should give a nice name almost all the time
		default: chance += 16*dist; break;
	}

	Uint32 weight = rng.Int32(chance);
	if (weight < 500 || galaxy->GetFactions()->IsHomeSystem(SystemPath(sx, sy, sz, si))) {
		/* well done. you get a real name  */
		int len = rng.Int32(2,3);
		for (int i=0; i<len; i++) {
			name += sys_names[rng.Int32(0,SYS_NAME_FRAGS-1)];
		}
		name[0] = toupper(name[0]);
		return name;
	} else if (weight < 800) {
		char buf[128];
		snprintf(buf, sizeof(buf), "MJBN %d%+d%+d", rng.Int32(10,999),sx,sy); // MJBN -> Morton Jordan Bennett Norris
		return buf;
	} else if (weight < 1200) {
		char buf[128];
		snprintf(buf, sizeof(buf), "SC %d%+d%+d", rng.Int32(1000,9999),sx,sy);
		return buf;
	} else {
		char buf[128];
		snprintf(buf, sizeof(buf), "DSC %d%+d%+d", rng.Int32(1000,9999),sx,sy);
		return buf;
	}
}
Beispiel #17
0
void Sensors::ResetTrails()
{
	PROFILE_SCOPED();
	for (auto it = m_radarContacts.begin(); it != m_radarContacts.end(); ++it)
		it->trail->Reset(Pi::player->GetFrame());
}
Beispiel #18
0
Faction *FactionsDatabase::GetFaction(const Uint32 index)
{
	PROFILE_SCOPED()
	assert( index < m_factions.size() );
	return m_factions[index];
}
Beispiel #19
0
	void MatrixTransform::Render(const matrix4x4f &trans, const RenderData *rd)
	{
		PROFILE_SCOPED();
		const matrix4x4f t = trans * m_transform;
		RenderChildren(t, rd);
	}
Beispiel #20
0
	void DrawOutdent(const float size[2], Graphics::RenderState *state)
	{
		PROFILE_SCOPED()

		// locals
		RefCountedPtr<Graphics::VertexBuffer> vb;
		RefCountedPtr<Graphics::IndexBuffer> ib[3];

		// see if we have this size of indent in the cache already
		const vector2f vsize(size[0], size[1]);
		MapOutdentBuffers::iterator bufIt = s_outdentBuffers.find(vsize);
		if (bufIt != s_outdentBuffers.end())
		{
			// found it
			vb = bufIt->second.vb;
			ib[0] = bufIt->second.ib[0];
			ib[1] = bufIt->second.ib[1];
			ib[2] = bufIt->second.ib[2];
		}
		else
		{
			// generate it
			const vector3f vertices[] = {
				/* 0 */	vector3f(0, 0, 0),
				/* 1 */	vector3f(0, size[1], 0),
				/* 2 */	vector3f(size[0], size[1], 0),
				/* 3 */	vector3f(size[0], 0, 0),
				/* 4 */	vector3f(BORDER_WIDTH, BORDER_WIDTH, 0),
				/* 5 */	vector3f(BORDER_WIDTH, size[1] - BORDER_WIDTH, 0),
				/* 6 */	vector3f(size[0] - BORDER_WIDTH, size[1] - BORDER_WIDTH, 0),
				/* 7 */	vector3f(size[0] - BORDER_WIDTH, BORDER_WIDTH, 0)
			};
			const Uint32 indices[] = {
				0, 1, 5, 0, 5, 4, 0, 4, 7, 0, 7, 3,
				3, 7, 6, 3, 6, 2, 1, 2, 6, 1, 6, 5,
				4, 5, 6, 4, 6, 7 };

			// create buffer
			Graphics::VertexBufferDesc vbd;
			vbd.attrib[0].semantic = Graphics::ATTRIB_POSITION;
			vbd.attrib[0].format = Graphics::ATTRIB_FORMAT_FLOAT3;
			vbd.numVertices = 8;
			vbd.usage = Graphics::BUFFER_USAGE_STATIC;

			// Upload data
			vb.Reset(Screen::GetRenderer()->CreateVertexBuffer(vbd));
			TPos* vtxPtr = vb->Map<TPos>(Graphics::BUFFER_MAP_WRITE);
			assert(vb->GetDesc().stride == sizeof(TPos));
			for (Uint32 i = 0; i < 8; i++) {
				vtxPtr[i].pos = vertices[i];
			}
			vb->Unmap();

			// indices
			Uint32 IndexStart = 0;
			Uint32 IndexEnd = 12;
			Uint32 NumIndices = 12;

			ib[0].Reset(CreateIndexBuffer(indices, IndexStart, IndexEnd, NumIndices));

			IndexStart += NumIndices;
			NumIndices = 12;
			IndexEnd += NumIndices;

			ib[1].Reset(CreateIndexBuffer(indices, IndexStart, IndexEnd, NumIndices));

			IndexStart += NumIndices;
			NumIndices = 6;
			IndexEnd += NumIndices;

			ib[2].Reset(CreateIndexBuffer(indices, IndexStart, IndexEnd, NumIndices));

			TOutdentBuffers tib;
			tib.vb = vb;
			tib.ib[0] = ib[0];
			tib.ib[1] = ib[1];
			tib.ib[2] = ib[2];
			s_outdentBuffers[vsize] = tib;
		}

		// Draw it!
		Screen::flatColorMaterial->diffuse = Color(153,153,153,255);
		Screen::GetRenderer()->DrawBufferIndexed(vb.Get(), ib[0].Get(), state, Screen::flatColorMaterial);
		Screen::flatColorMaterial->diffuse = Colors::bgShadow;
		Screen::GetRenderer()->DrawBufferIndexed(vb.Get(), ib[1].Get(), state, Screen::flatColorMaterial);
		Screen::flatColorMaterial->diffuse = Colors::bg;
		Screen::GetRenderer()->DrawBufferIndexed(vb.Get(), ib[2].Get(), state, Screen::flatColorMaterial);
	}
Beispiel #21
0
/*
 * Method: GetNearbySystems
 *
 * Get a list of nearby <StarSystems> that match some criteria
 *
 * > systems = system:GetNearbySystems(range, filter)
 *
 * Parameters:
 *
 *   range - distance from this system to search, in light years
 *
 *   filter - an optional function. If specified the function will be called
 *            once for each candidate system with the <StarSystem> object
 *            passed as the only parameter. If the filter function returns
 *            true then the system will be included in the array returned by
 *            <GetNearbySystems>, otherwise it will be omitted. If no filter
 *            function is specified then all systems in range are returned.
 *
 * Return:
 *
 *  systems - an array of systems in range that matched the filter
 *
 * Availability:
 *
 *   alpha 10
 *
 * Status:
 *
 *   experimental
 */
static int l_starsystem_get_nearby_systems(lua_State *l)
{
	PROFILE_SCOPED()
	LUA_DEBUG_START(l);

	const StarSystem *s = LuaObject<StarSystem>::CheckFromLua(1);
	const double dist_ly = luaL_checknumber(l, 2);

	bool filter = false;
	if (lua_gettop(l) >= 3) {
		luaL_checktype(l, 3, LUA_TFUNCTION); // any type of function
		filter = true;
	}

	lua_newtable(l);

	const SystemPath &here = s->GetPath();

	const int here_x = here.sectorX;
	const int here_y = here.sectorY;
	const int here_z = here.sectorZ;
	const Uint32 here_idx = here.systemIndex;
	RefCountedPtr<const Sector> here_sec = Pi::GetGalaxy()->GetSector(here);

	const int diff_sec = int(ceil(dist_ly/Sector::SIZE));

	for (int x = here_x-diff_sec; x <= here_x+diff_sec; x++) {
		for (int y = here_y-diff_sec; y <= here_y+diff_sec; y++) {
			for (int z = here_z-diff_sec; z <= here_z+diff_sec; z++) {
				RefCountedPtr<const Sector> sec = Pi::GetGalaxy()->GetSector(SystemPath(x, y, z));

				for (unsigned int idx = 0; idx < sec->m_systems.size(); idx++) {
					if (x == here_x && y == here_y && z == here_z && idx == here_idx)
						continue;

					if (Sector::DistanceBetween(here_sec, here_idx, sec, idx) > dist_ly)
						continue;

					RefCountedPtr<StarSystem> sys = Pi::GetGalaxy()->GetStarSystem(SystemPath(x, y, z, idx));
					if (filter) {
						lua_pushvalue(l, 3);
						LuaObject<StarSystem>::PushToLua(sys.Get());
						lua_call(l, 1, 1);
						if (!lua_toboolean(l, -1)) {
							lua_pop(l, 1);
							continue;
						}
						lua_pop(l, 1);
					}

					lua_pushinteger(l, lua_rawlen(l, -1)+1);
					LuaObject<StarSystem>::PushToLua(sys.Get());
					lua_rawset(l, -3);
				}
			}
		}
	}

	LUA_DEBUG_END(l, 1);

	return 1;
}
Beispiel #22
0
//////////////////////// Sector
Sector::Sector(const SystemPath& path) : m_factionsAssigned(false)
{
	PROFILE_SCOPED()
	Uint32 _init[4] = { Uint32(path.sectorX), Uint32(path.sectorY), Uint32(path.sectorZ), UNIVERSE_SEED };
	Random rng(_init, 4);

	sx = path.sectorX; sy = path.sectorY; sz = path.sectorZ;

	GetCustomSystems(rng);
	int customCount = m_systems.size();

	/* Always place random systems outside the core custom-only region */
	if ((path.sectorX < -CUSTOM_ONLY_RADIUS) || (path.sectorX > CUSTOM_ONLY_RADIUS-1) ||
	    (path.sectorY < -CUSTOM_ONLY_RADIUS) || (path.sectorY > CUSTOM_ONLY_RADIUS-1) ||
	    (path.sectorZ < -CUSTOM_ONLY_RADIUS) || (path.sectorZ > CUSTOM_ONLY_RADIUS-1)) {
		int numSystems = (rng.Int32(4,20) * Galaxy::GetSectorDensity(path.sectorX, path.sectorY, path.sectorZ)) >> 8;

		for (int i=0; i<numSystems; i++) {
			System s(sx, sy, sz, customCount + i);

			switch (rng.Int32(15)) {
				case 0:
					s.numStars = 4; break;
				case 1: case 2:
					s.numStars = 3; break;
				case 3: case 4: case 5: case 6:
					s.numStars = 2; break;
				default:
					s.numStars = 1; break;
			}

			s.p.x = rng.Double(SIZE);
			s.p.y = rng.Double(SIZE);
			s.p.z = rng.Double(SIZE);

			s.seed = 0;
			s.customSys = 0;

			/*
			 * 0 - ~500ly from sol: explored
			 * ~500ly - ~700ly (65-90 sectors): gradual
			 * ~700ly+: unexplored
			 */
			int dist = isqrt(1 + sx*sx + sy*sy + sz*sz);
			s.explored = ((dist <= 90) && ( dist <= 65 || rng.Int32(dist) <= 40)) || Faction::IsHomeSystem(SystemPath(sx, sy, sz, customCount + i));

			Uint32 weight = rng.Int32(1000000);

			// Frequencies are low enough that we probably don't need this anymore.
			if (isqrt(1+sx*sx+sy*sy) > 10)
			{
				if (weight < 1) {
					s.starType[0] = SystemBody::TYPE_STAR_IM_BH;  // These frequencies are made up
				} else if (weight < 3) {
					s.starType[0] = SystemBody::TYPE_STAR_S_BH;
				} else if (weight < 5) {
					s.starType[0] = SystemBody::TYPE_STAR_O_WF;
				} else if (weight < 8) {
					s.starType[0] = SystemBody::TYPE_STAR_B_WF;
				} else if (weight < 12) {
					s.starType[0] = SystemBody::TYPE_STAR_M_WF;
				} else if (weight < 15) {
					s.starType[0] = SystemBody::TYPE_STAR_K_HYPER_GIANT;
				} else if (weight < 18) {
					s.starType[0] = SystemBody::TYPE_STAR_G_HYPER_GIANT;
				} else if (weight < 23) {
					s.starType[0] = SystemBody::TYPE_STAR_O_HYPER_GIANT;
				} else if (weight < 28) {
					s.starType[0] = SystemBody::TYPE_STAR_A_HYPER_GIANT;
				} else if (weight < 33) {
					s.starType[0] = SystemBody::TYPE_STAR_F_HYPER_GIANT;
				} else if (weight < 41) {
					s.starType[0] = SystemBody::TYPE_STAR_B_HYPER_GIANT;
				} else if (weight < 48) {
					s.starType[0] = SystemBody::TYPE_STAR_M_HYPER_GIANT;
				} else if (weight < 58) {
					s.starType[0] = SystemBody::TYPE_STAR_K_SUPER_GIANT;
				} else if (weight < 68) {
					s.starType[0] = SystemBody::TYPE_STAR_G_SUPER_GIANT;
				} else if (weight < 78) {
					s.starType[0] = SystemBody::TYPE_STAR_O_SUPER_GIANT;
				} else if (weight < 88) {
					s.starType[0] = SystemBody::TYPE_STAR_A_SUPER_GIANT;
				} else if (weight < 98) {
					s.starType[0] = SystemBody::TYPE_STAR_F_SUPER_GIANT;
				} else if (weight < 108) {
					s.starType[0] = SystemBody::TYPE_STAR_B_SUPER_GIANT;
				} else if (weight < 158) {
					s.starType[0] = SystemBody::TYPE_STAR_M_SUPER_GIANT;
				} else if (weight < 208) {
					s.starType[0] = SystemBody::TYPE_STAR_K_GIANT;
				} else if (weight < 250) {
					s.starType[0] = SystemBody::TYPE_STAR_G_GIANT;
				} else if (weight < 300) {
					s.starType[0] = SystemBody::TYPE_STAR_O_GIANT;
				} else if (weight < 350) {
					s.starType[0] = SystemBody::TYPE_STAR_A_GIANT;
				} else if (weight < 400) {
					s.starType[0] = SystemBody::TYPE_STAR_F_GIANT;
				} else if (weight < 500) {
					s.starType[0] = SystemBody::TYPE_STAR_B_GIANT;
				} else if (weight < 700) {
					s.starType[0] = SystemBody::TYPE_STAR_M_GIANT;
				} else if (weight < 800) {
					s.starType[0] = SystemBody::TYPE_STAR_O;  // should be 1 but that is boring
				} else if (weight < 2000) { // weight < 1300 / 20500
					s.starType[0] = SystemBody::TYPE_STAR_B;
				} else if (weight < 8000) { // weight < 7300
					s.starType[0] = SystemBody::TYPE_STAR_A;
				} else if (weight < 37300) { // weight < 37300
					s.starType[0] = SystemBody::TYPE_STAR_F;
				} else if (weight < 113300) { // weight < 113300
					s.starType[0] = SystemBody::TYPE_STAR_G;
				} else if (weight < 234300) { // weight < 234300
					s.starType[0] = SystemBody::TYPE_STAR_K;
				} else if (weight < 250000) { // weight < 250000
					s.starType[0] = SystemBody::TYPE_WHITE_DWARF;
				} else if (weight < 900000) {  //weight < 900000
					s.starType[0] = SystemBody::TYPE_STAR_M;
				} else {
					s.starType[0] = SystemBody::TYPE_BROWN_DWARF;
				}
			} else {
				if (weight < 100) { // should be 1 but that is boring
					s.starType[0] = SystemBody::TYPE_STAR_O;
				} else if (weight < 1300) {
					s.starType[0] = SystemBody::TYPE_STAR_B;
				} else if (weight < 7300) {
					s.starType[0] = SystemBody::TYPE_STAR_A;
				} else if (weight < 37300) {
					s.starType[0] = SystemBody::TYPE_STAR_F;
				} else if (weight < 113300) {
					s.starType[0] = SystemBody::TYPE_STAR_G;
				} else if (weight < 234300) {
					s.starType[0] = SystemBody::TYPE_STAR_K;
				} else if (weight < 250000) {
					s.starType[0] = SystemBody::TYPE_WHITE_DWARF;
				} else if (weight < 900000) {
					s.starType[0] = SystemBody::TYPE_STAR_M;
				} else {
					s.starType[0] = SystemBody::TYPE_BROWN_DWARF;
				}
			}
			//Output("%d: %d%\n", sx, sy);

			if (s.numStars > 1) {
				s.starType[1] = SystemBody::BodyType(rng.Int32(SystemBody::TYPE_STAR_MIN, s.starType[0]));
				if (s.numStars > 2) {
					s.starType[2] = SystemBody::BodyType(rng.Int32(SystemBody::TYPE_STAR_MIN, s.starType[0]));
					s.starType[3] = SystemBody::BodyType(rng.Int32(SystemBody::TYPE_STAR_MIN, s.starType[2]));
				}
			}

			if ((s.starType[0] <= SystemBody::TYPE_STAR_A) && (rng.Int32(10)==0)) {
				// make primary a giant. never more than one giant in a system
				// while
				if (isqrt(1+sx*sx+sy*sy) > 10)
				{
					weight = rng.Int32(1000);
					if (weight >= 999) {
						s.starType[0] = SystemBody::TYPE_STAR_B_HYPER_GIANT;
					} else if (weight >= 998) {
						s.starType[0] = SystemBody::TYPE_STAR_O_HYPER_GIANT;
					} else if (weight >= 997) {
						s.starType[0] = SystemBody::TYPE_STAR_K_HYPER_GIANT;
					} else if (weight >= 995) {
						s.starType[0] = SystemBody::TYPE_STAR_B_SUPER_GIANT;
					} else if (weight >= 993) {
						s.starType[0] = SystemBody::TYPE_STAR_O_SUPER_GIANT;
					} else if (weight >= 990) {
						s.starType[0] = SystemBody::TYPE_STAR_K_SUPER_GIANT;
					} else if (weight >= 985) {
						s.starType[0] = SystemBody::TYPE_STAR_B_GIANT;
					} else if (weight >= 980) {
						s.starType[0] = SystemBody::TYPE_STAR_O_GIANT;
					} else if (weight >= 975) {
						s.starType[0] = SystemBody::TYPE_STAR_K_GIANT;
					} else if (weight >= 950) {
						s.starType[0] = SystemBody::TYPE_STAR_M_HYPER_GIANT;
					} else if (weight >= 875) {
						s.starType[0] = SystemBody::TYPE_STAR_M_SUPER_GIANT;
					} else {
						s.starType[0] = SystemBody::TYPE_STAR_M_GIANT;
					}
				} else if (isqrt(1+sx*sx+sy*sy) > 5) s.starType[0] = SystemBody::TYPE_STAR_M_GIANT;
				else s.starType[0] = SystemBody::TYPE_STAR_M;

				//Output("%d: %d%\n", sx, sy);
			}

			s.name = GenName(s, customCount + i,  rng);
			//Output("%s: \n", s.name.c_str());

			m_systems.push_back(s);
		}
	}
Beispiel #23
0
void Pi::HandleEvents()
{
	PROFILE_SCOPED()
	SDL_Event event;

	// XXX for most keypresses SDL will generate KEYUP/KEYDOWN and TEXTINPUT
	// events. keybindings run off KEYUP/KEYDOWN. the console is opened/closed
	// via keybinding. the console TextInput widget uses TEXTINPUT events. thus
	// after switching the console, the stray TEXTINPUT event causes the
	// console key (backtick) to appear in the text entry field. we hack around
	// this by setting this flag if the console was switched. if its set, we
	// swallow the TEXTINPUT event this hack must remain until we have a
	// unified input system
	bool skipTextInput = false;

	Pi::mouseMotion[0] = Pi::mouseMotion[1] = 0;
	while (SDL_PollEvent(&event)) {
		if (event.type == SDL_QUIT) {
			if (Pi::game)
				Pi::EndGame();
			Pi::Quit();
		}

		if (skipTextInput && event.type == SDL_TEXTINPUT) {
			skipTextInput = false;
			continue;
		}
		if (ui->DispatchSDLEvent(event))
			continue;

		bool consoleActive = Pi::IsConsoleActive();
		if (!consoleActive)
			KeyBindings::DispatchSDLEvent(&event);
		else
			KeyBindings::toggleLuaConsole.CheckSDLEventAndDispatch(&event);
		if (consoleActive != Pi::IsConsoleActive()) {
			skipTextInput = true;
			continue;
		}

		if (Pi::IsConsoleActive())
			continue;

		Gui::HandleSDLEvent(&event);

		switch (event.type) {
			case SDL_KEYDOWN:
				if (event.key.keysym.sym == SDLK_ESCAPE) {
					if (Pi::game) {
						// only accessible once game started
						if (currentView != 0) {
							if (currentView != Pi::game->GetSettingsView()) {
								Pi::game->SetTimeAccel(Game::TIMEACCEL_PAUSED);
								SetView(Pi::game->GetSettingsView());
							}
							else {
								Pi::game->RequestTimeAccel(Game::TIMEACCEL_1X);
								SetView(Pi::player->IsDead()
										? static_cast<View*>(Pi::game->GetDeathView())
										: static_cast<View*>(Pi::game->GetWorldView()));
							}
						}
					}
					break;
				}
				// special keys. LCTRL+turd
				if ((KeyState(SDLK_LCTRL) || (KeyState(SDLK_RCTRL)))) {
					switch (event.key.keysym.sym) {
						case SDLK_q: // Quit
							if (Pi::game)
								Pi::EndGame();
							Pi::Quit();
							break;
						case SDLK_PRINTSCREEN: // print
						case SDLK_KP_MULTIPLY: // screen
						{
							char buf[256];
							const time_t t = time(0);
							struct tm *_tm = localtime(&t);
							strftime(buf, sizeof(buf), "screenshot-%Y%m%d-%H%M%S.png", _tm);
							Graphics::ScreendumpState sd;
							Pi::renderer->Screendump(sd);
							write_screenshot(sd, buf);
							break;
						}
#if WITH_DEVKEYS
						case SDLK_i: // Toggle Debug info
							Pi::showDebugInfo = !Pi::showDebugInfo;
							break;

#ifdef PIONEER_PROFILER
						case SDLK_p: // alert it that we want to profile
							if (KeyState(SDLK_LSHIFT) || KeyState(SDLK_RSHIFT))
								Pi::doProfileOne = true;
							else {
								Pi::doProfileSlow = !Pi::doProfileSlow;
								Output("slow frame profiling %s\n", Pi::doProfileSlow ? "enabled" : "disabled");
							}
							break;
#endif

						case SDLK_F12:
						{
							if(Pi::game) {
								vector3d dir = -Pi::player->GetOrient().VectorZ();
								/* add test object */
								if (KeyState(SDLK_RSHIFT)) {
									Missile *missile =
										new Missile(ShipType::MISSILE_GUIDED, Pi::player);
									missile->SetOrient(Pi::player->GetOrient());
									missile->SetFrame(Pi::player->GetFrame());
									missile->SetPosition(Pi::player->GetPosition()+50.0*dir);
									missile->SetVelocity(Pi::player->GetVelocity());
									game->GetSpace()->AddBody(missile);
									missile->AIKamikaze(Pi::player->GetCombatTarget());
								} else if (KeyState(SDLK_LSHIFT)) {
									SpaceStation *s = static_cast<SpaceStation*>(Pi::player->GetNavTarget());
									if (s) {
										Ship *ship = new Ship(ShipType::POLICE);
										int port = s->GetFreeDockingPort(ship);
										if (port != -1) {
											Output("Putting ship into station\n");
											// Make police ship intent on killing the player
											ship->AIKill(Pi::player);
											ship->SetFrame(Pi::player->GetFrame());
											ship->SetDockedWith(s, port);
											game->GetSpace()->AddBody(ship);
										} else {
											delete ship;
											Output("No docking ports free dude\n");
										}
									} else {
											Output("Select a space station...\n");
									}
								} else {
									Ship *ship = new Ship(ShipType::POLICE);
									if( KeyState(SDLK_LCTRL) )
										ship->AIFlyTo(Pi::player);	// a less lethal option
									else
										ship->AIKill(Pi::player);	// a really lethal option!
									lua_State *l = Lua::manager->GetLuaState();
									pi_lua_import(l, "Equipment");
									LuaTable equip(l, -1);
									LuaObject<Ship>::CallMethod<>(ship, "AddEquip", equip.Sub("laser").Sub("pulsecannon_dual_1mw"));
									LuaObject<Ship>::CallMethod<>(ship, "AddEquip", equip.Sub("misc").Sub("laser_cooling_booster"));
									LuaObject<Ship>::CallMethod<>(ship, "AddEquip", equip.Sub("misc").Sub("atmospheric_shielding"));
									lua_pop(l, 5);
									ship->SetFrame(Pi::player->GetFrame());
									ship->SetPosition(Pi::player->GetPosition()+100.0*dir);
									ship->SetVelocity(Pi::player->GetVelocity());
									ship->UpdateEquipStats();
									game->GetSpace()->AddBody(ship);
								}
							}
							break;
						}
#endif /* DEVKEYS */
#if WITH_OBJECTVIEWER
						case SDLK_F10:
							Pi::SetView(Pi::game->GetObjectViewerView());
							break;
#endif
						case SDLK_F11:
							// XXX only works on X11
							//SDL_WM_ToggleFullScreen(Pi::scrSurface);
#if WITH_DEVKEYS
							renderer->ReloadShaders();
#endif
							break;
						case SDLK_F9: // Quicksave
						{
							if(Pi::game) {
								if (Pi::game->IsHyperspace())
									Pi::game->log->Add(Lang::CANT_SAVE_IN_HYPERSPACE);

								else {
									const std::string name = "_quicksave";
									const std::string path = FileSystem::JoinPath(GetSaveDir(), name);
									try {
										Game::SaveGame(name, Pi::game);
										Pi::game->log->Add(Lang::GAME_SAVED_TO + path);
									} catch (CouldNotOpenFileException) {
										Pi::game->log->Add(stringf(Lang::COULD_NOT_OPEN_FILENAME, formatarg("path", path)));
									}
									catch (CouldNotWriteToFileException) {
										Pi::game->log->Add(Lang::GAME_SAVE_CANNOT_WRITE);
									}
								}
							}
							break;
						}
						default:
							break; // This does nothing but it stops the compiler warnings
					}
				}
				Pi::keyState[event.key.keysym.sym] = true;
				Pi::keyModState = event.key.keysym.mod;
				Pi::onKeyPress.emit(&event.key.keysym);
				break;
			case SDL_KEYUP:
				Pi::keyState[event.key.keysym.sym] = false;
				Pi::keyModState = event.key.keysym.mod;
				Pi::onKeyRelease.emit(&event.key.keysym);
				break;
			case SDL_MOUSEBUTTONDOWN:
				if (event.button.button < COUNTOF(Pi::mouseButton)) {
					Pi::mouseButton[event.button.button] = 1;
					Pi::onMouseButtonDown.emit(event.button.button,
							event.button.x, event.button.y);
				}
				break;
			case SDL_MOUSEBUTTONUP:
				if (event.button.button < COUNTOF(Pi::mouseButton)) {
					Pi::mouseButton[event.button.button] = 0;
					Pi::onMouseButtonUp.emit(event.button.button,
							event.button.x, event.button.y);
				}
				break;
			case SDL_MOUSEWHEEL:
				Pi::onMouseWheel.emit(event.wheel.y > 0); // true = up
				break;
			case SDL_MOUSEMOTION:
				Pi::mouseMotion[0] += event.motion.xrel;
				Pi::mouseMotion[1] += event.motion.yrel;
		//		SDL_GetRelativeMouseState(&Pi::mouseMotion[0], &Pi::mouseMotion[1]);
				break;
			case SDL_JOYAXISMOTION:
				if (!joysticks[event.jaxis.which].joystick)
					break;
				if (event.jaxis.value == -32768)
					joysticks[event.jaxis.which].axes[event.jaxis.axis] = 1.f;
				else
					joysticks[event.jaxis.which].axes[event.jaxis.axis] = -event.jaxis.value / 32767.f;
				break;
			case SDL_JOYBUTTONUP:
			case SDL_JOYBUTTONDOWN:
				if (!joysticks[event.jaxis.which].joystick)
					break;
				joysticks[event.jbutton.which].buttons[event.jbutton.button] = event.jbutton.state != 0;
				break;
			case SDL_JOYHATMOTION:
				if (!joysticks[event.jaxis.which].joystick)
					break;
				joysticks[event.jhat.which].hats[event.jhat.hat] = event.jhat.value;
				break;
		}
	}
}
Beispiel #24
0
void Group::Render(const matrix4x4f &trans, const RenderData *rd)
{
	PROFILE_SCOPED()
	RenderChildren(trans, rd);
}